@inkeep/open-knowledge 0.13.1-beta.3 → 0.14.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/THIRD_PARTY_NOTICES.md +2 -2
  2. package/dist/assets/skills/discovery/SKILL.md +1 -1
  3. package/dist/assets/skills/project/SKILL.md +1 -1
  4. package/dist/cli.mjs +5 -5
  5. package/dist/constants-acQ6Ybfl.mjs +2 -0
  6. package/dist/{dist-D4w1Xe5t.mjs → dist-DDXOiPkg.mjs} +2 -2
  7. package/dist/{dist-BXU3sfTZ.mjs → dist-De0GFsdh.mjs} +1 -1
  8. package/dist/index.mjs +1 -1
  9. package/dist/{init-BJWXZw7g.mjs → init-Bp64Lvl-.mjs} +4 -4
  10. package/dist/init-Dky4vpd9.mjs +1 -0
  11. package/dist/{loader-CyDqzvXj.mjs → loader-HZLNd747.mjs} +2 -2
  12. package/dist/loader-s5lhNT8V.mjs +1 -0
  13. package/dist/preview-BSIRt3Gp.mjs +1 -0
  14. package/dist/{preview-DAMaD8d5.mjs → preview-TG2mvVXo.mjs} +2 -2
  15. package/dist/public/assets/index-uIc17Io3.js +2019 -0
  16. package/dist/public/index.html +1 -1
  17. package/dist/{repair-launch-json-CP4zuYb5.mjs → repair-launch-json-BTVsNA32.mjs} +2 -2
  18. package/dist/{repair-mcp-configs-CLCzpwjN.mjs → repair-mcp-configs-DqUKj17t.mjs} +2 -2
  19. package/dist/{repair-skills-dQe6TLTl.mjs → repair-skills-4UqJa14n.mjs} +2 -2
  20. package/dist/repair-skills-D35qgsTr.mjs +1 -0
  21. package/dist/{src-CI8DR-q-.mjs → src-DHDfWHi4.mjs} +2 -2
  22. package/dist/{start-CdaVt-dN.mjs → start-CHqWJ1Uf.mjs} +2 -2
  23. package/dist/start-DujEO1M-.mjs +1 -0
  24. package/dist/{write-project-skill-_VwpecbD.mjs → write-project-skill-BOMiBSxq.mjs} +2 -2
  25. package/package.json +1 -1
  26. package/dist/constants-Do6Db5Jx.mjs +0 -2
  27. package/dist/init-CyytdzLx.mjs +0 -1
  28. package/dist/loader-7E2btZCD.mjs +0 -1
  29. package/dist/preview-CpSuy3Ei.mjs +0 -1
  30. package/dist/public/assets/index-DPXZhUxX.js +0 -1970
  31. package/dist/repair-skills-COMRWbeK.mjs +0 -1
  32. package/dist/start-BnH1uaVq.mjs +0 -1
@@ -744,7 +744,7 @@ Homepage: https://github.com/oramasearch/orama
744
744
 
745
745
  Copyright 2023 OramaSearch Inc
746
746
 
747
- ### `@pierre/trees@1.0.0-beta.3`
747
+ ### `@pierre/trees@1.0.0-beta.4`
748
748
 
749
749
  Copyright 2025 Pierre Computer Company
750
750
 
@@ -6404,7 +6404,7 @@ The following MIT-licensed packages are patched in this repository via Bun's `pa
6404
6404
  | Package | Patch file |
6405
6405
  | --- | --- |
6406
6406
  | `@handlewithcare/remark-prosemirror@0.1.5` | `patches/@handlewithcare%2Fremark-prosemirror@0.1.5.patch` |
6407
- | `@pierre/trees@1.0.0-beta.3` | `patches/@pierre%2Ftrees@1.0.0-beta.3.patch` |
6407
+ | `@pierre/trees@1.0.0-beta.4` | `patches/@pierre%2Ftrees@1.0.0-beta.4.patch` |
6408
6408
  | `@tiptap/extension-drag-handle@3.22.3` | `patches/@tiptap%2Fextension-drag-handle@3.22.3.patch` |
6409
6409
  | `@tiptap/y-tiptap@3.0.3` | `patches/@tiptap%2Fy-tiptap@3.0.3.patch` |
6410
6410
  | `react-medium-image-zoom@5.4.3` | `patches/react-medium-image-zoom@5.4.3.patch` |
@@ -3,7 +3,7 @@ name: open-knowledge-discovery
3
3
  description: "Read when the user asks what Open Knowledge is, wants to install it on a repository, wants to share an Open Knowledge project with collaborators, or asks how `ok init` / `ok install-skill` / OK Desktop set up a project. Do NOT load to perform Open Knowledge reads/writes — the runtime guidance for editing markdown inside an initialized OK project ships as a separate project-local skill at `.claude/skills/open-knowledge/` whenever `ok init` runs. If the user appears to be editing markdown inside a `.ok/` project and this is the only OK skill loaded, advise them to re-run `ok init` to install the project-local skill."
4
4
  compatibility: "Any agent host — no MCP server required. Pure discovery + install guidance."
5
5
  metadata:
6
- version: "0.13.1-beta.3"
6
+ version: "0.14.0-beta.0"
7
7
  author: "Inkeep"
8
8
  repository: "https://github.com/inkeep/open-knowledge"
9
9
  ---
@@ -3,7 +3,7 @@ name: open-knowledge
3
3
  description: "MUST invoke before reading or editing any `.md` / `.mdx` file, and before any `mcp__open-knowledge__*` tool call (`exec`, `search`, `write`, `edit`, and the rest). This skill is installed into the repository by `ok init`, so its presence alone means this is an Open Knowledge project — its runtime contract governs every markdown file here, with no need to probe for a `.ok/` directory. Authoritative agent-runtime contract; supersedes the overlapping MCP server `instructions` echo."
4
4
  compatibility: "Claude Code, Claude Desktop, Claude Cowork, Claude.ai web. Requires Open Knowledge MCP server + code execution."
5
5
  metadata:
6
- version: "0.13.1-beta.3"
6
+ version: "0.14.0-beta.0"
7
7
  author: "Inkeep"
8
8
  repository: "https://github.com/inkeep/open-knowledge"
9
9
  ---
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{s as e}from"./chunk-C94x7I9S.mjs";import{t}from"./esm-BLMtE3s6.mjs";import{$i as n,Ai as r,Gi as i,Ki as a,Pi as o,Qi as s,Ta as c,Vi as l,Wr as u,Zi as d,bn as f,ea as p,f as m,ia as h,ki as g,n as _,qi as v,s as y,sa as b,ua as x,wa as S,xr as C}from"./server-lock-BpjJj3OD-Co1tfNQM.mjs";import{a as ee,n as w,r as te,t as ne}from"./gh-detect-CiwGHfLq.mjs";import{r as re}from"./git-handle--dq7Gq14-BpH0pmv5.mjs";import{$n as ie,Br as ae,En as oe,F as se,Fn as ce,Gi as le,Hn as ue,Ht as de,Ji as fe,Jt as pe,Ki as me,Kr as he,Mt as ge,P as _e,Pr as ve,Q as ye,Qi as be,Rn as xe,T as Se,Ur as Ce,Ut as we,Vt as Te,Wi as Ee,Yi as De,Z as Oe,Zt as ke,_ as Ae,_t as je,aa as Me,ai as Ne,at as Pe,bn as Fe,br as Ie,c as Le,dn as Re,ea as ze,fn as Be,it as Ve,mt as He,na as Ue,on as We,qi as Ge,ra as Ke,rt as qe,ta as Je,tt as Ye,v as Xe,w as Ze,wr as Qe,wt as $e,xt as et,yr as tt}from"./dist-D4w1Xe5t.mjs";import{t as nt}from"./yazl-Docqgl6q.mjs";import{n as rt,r as it,t as T}from"./dist-bundle-D75dREX-.mjs";import{B as at,C as ot,E as st,F as ct,H as lt,I as ut,L as dt,M as ft,N as pt,P as mt,R as ht,S as gt,T as _t,V as vt,b as yt,u as bt,v as xt,w as St,z as Ct}from"./init-BJWXZw7g.mjs";import{a as wt,c as Tt,h as Et,i as Dt,l as Ot,m as kt,o as At,s as jt,u as Mt}from"./src-CI8DR-q-.mjs";import{n as Nt,t as Pt}from"./constants-Do6Db5Jx.mjs";import{n as Ft,t as It}from"./loader-CyDqzvXj.mjs";import{S as Lt,_ as Rt,b as zt,m as Bt,x as Vt,y as Ht}from"./start-CdaVt-dN.mjs";import{c as Ut,i as E,n as D,o as O,r as k,s as A,t as j}from"./colors-8SzMRIVy.mjs";import{n as Wt}from"./repair-skills-dQe6TLTl.mjs";import{execFile as Gt,execSync as Kt,spawn as M,spawnSync as N}from"node:child_process";import{accessSync as qt,closeSync as Jt,constants as Yt,cpSync as Xt,createWriteStream as Zt,existsSync as P,mkdirSync as F,mkdtempSync as Qt,openSync as $t,readFileSync as I,readdirSync as en,realpathSync as tn,rmSync as nn,statSync as rn,unlinkSync as an,writeFileSync as L}from"node:fs";import on,{basename as R,dirname as sn,join as z,relative as cn,resolve as B,sep as ln}from"node:path";import un from"node:process";import{arch as dn,freemem as fn,homedir as pn,platform as mn,release as hn,tmpdir as gn,totalmem as _n,type as vn,uptime as yn}from"node:os";import{fileURLToPath as bn}from"node:url";import{rm as xn}from"node:fs/promises";import{createHash as Sn,randomUUID as Cn}from"node:crypto";import{setTimeout as wn}from"node:timers/promises";import{promisify as Tn,stripVTControlCharacters as En,styleText as V}from"node:util";import{AsyncLocalStorage as Dn,AsyncResource as On}from"node:async_hooks";import*as kn from"node:readline";import{createInterface as An}from"node:readline/promises";const jn={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var Mn;(function(e){})(Mn||={});function Nn(e){return x(l,e)}async function Pn(e,t,n,r){let i=Fn(await In(e)).host??``,a=e=>e.replace(/[\r\n]/g,``);if(!i)return r?.log?.warn({outcome:`no-host`,backend:n.backend},`[auth] git-credential get`),1;let o=process.env.OK_GH_TOKEN,s=process.env.OK_GH_TOKEN_HOST;if(o&&s===i)return r?.log?.debug({host:i,outcome:`gh-env-token`,backend:n.backend},`[auth] git-credential get`),t.write(`username=x-access-token\npassword=${a(o)}\n`),0;let c=await n.get(i),l=r?.getDiag?.(),u=c==null?l?.kind??`absent`:`found`;if(r?.log){let e={host:i,outcome:u,backend:n.backend,...l?.error?{keychainError:l.error}:{}};u===`found`?r.log.debug(e,`[auth] git-credential get`):r.log.warn(e,`[auth] git-credential get`)}return c==null?1:(t.write(`username=${a(c.login)}\npassword=${a(c.token)}\n`),0)}function Fn(e){let t={};for(let n of e.split(`
2
+ import{s as e}from"./chunk-C94x7I9S.mjs";import{t}from"./esm-BLMtE3s6.mjs";import{$i as n,Ai as r,Gi as i,Ki as a,Pi as o,Qi as s,Ta as c,Vi as l,Wr as u,Zi as d,bn as f,ea as p,f as m,ia as h,ki as g,n as _,qi as v,s as y,sa as b,ua as x,wa as S,xr as C}from"./server-lock-BpjJj3OD-Co1tfNQM.mjs";import{a as ee,n as w,r as te,t as ne}from"./gh-detect-CiwGHfLq.mjs";import{r as re}from"./git-handle--dq7Gq14-BpH0pmv5.mjs";import{$n as ie,Br as ae,En as oe,F as se,Fn as ce,Gi as le,Hn as ue,Ht as de,Ji as fe,Jt as pe,Ki as me,Kr as he,Mt as ge,P as _e,Pr as ve,Q as ye,Qi as be,Rn as xe,T as Se,Ur as Ce,Ut as we,Vt as Te,Wi as Ee,Yi as De,Z as Oe,Zt as ke,_ as Ae,_t as je,aa as Me,ai as Ne,at as Pe,bn as Fe,br as Ie,c as Le,dn as Re,ea as ze,fn as Be,it as Ve,mt as He,na as Ue,on as We,qi as Ge,ra as Ke,rt as qe,ta as Je,tt as Ye,v as Xe,w as Ze,wr as Qe,wt as $e,xt as et,yr as tt}from"./dist-DDXOiPkg.mjs";import{t as nt}from"./yazl-Docqgl6q.mjs";import{n as rt,r as it,t as T}from"./dist-bundle-D75dREX-.mjs";import{B as at,C as ot,E as st,F as ct,H as lt,I as ut,L as dt,M as ft,N as pt,P as mt,R as ht,S as gt,T as _t,V as vt,b as yt,u as bt,v as xt,w as St,z as Ct}from"./init-Bp64Lvl-.mjs";import{a as wt,c as Tt,h as Et,i as Dt,l as Ot,m as kt,o as At,s as jt,u as Mt}from"./src-DHDfWHi4.mjs";import{n as Nt,t as Pt}from"./constants-acQ6Ybfl.mjs";import{n as Ft,t as It}from"./loader-HZLNd747.mjs";import{S as Lt,_ as Rt,b as zt,m as Bt,x as Vt,y as Ht}from"./start-CHqWJ1Uf.mjs";import{c as Ut,i as E,n as D,o as O,r as k,s as A,t as j}from"./colors-8SzMRIVy.mjs";import{n as Wt}from"./repair-skills-4UqJa14n.mjs";import{execFile as Gt,execSync as Kt,spawn as M,spawnSync as N}from"node:child_process";import{accessSync as qt,closeSync as Jt,constants as Yt,cpSync as Xt,createWriteStream as Zt,existsSync as P,mkdirSync as F,mkdtempSync as Qt,openSync as $t,readFileSync as I,readdirSync as en,realpathSync as tn,rmSync as nn,statSync as rn,unlinkSync as an,writeFileSync as L}from"node:fs";import on,{basename as R,dirname as sn,join as z,relative as cn,resolve as B,sep as ln}from"node:path";import un from"node:process";import{arch as dn,freemem as fn,homedir as pn,platform as mn,release as hn,tmpdir as gn,totalmem as _n,type as vn,uptime as yn}from"node:os";import{fileURLToPath as bn}from"node:url";import{rm as xn}from"node:fs/promises";import{createHash as Sn,randomUUID as Cn}from"node:crypto";import{setTimeout as wn}from"node:timers/promises";import{promisify as Tn,stripVTControlCharacters as En,styleText as V}from"node:util";import{AsyncLocalStorage as Dn,AsyncResource as On}from"node:async_hooks";import*as kn from"node:readline";import{createInterface as An}from"node:readline/promises";const jn={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var Mn;(function(e){})(Mn||={});function Nn(e){return x(l,e)}async function Pn(e,t,n,r){let i=Fn(await In(e)).host??``,a=e=>e.replace(/[\r\n]/g,``);if(!i)return r?.log?.warn({outcome:`no-host`,backend:n.backend},`[auth] git-credential get`),1;let o=process.env.OK_GH_TOKEN,s=process.env.OK_GH_TOKEN_HOST;if(o&&s===i)return r?.log?.debug({host:i,outcome:`gh-env-token`,backend:n.backend},`[auth] git-credential get`),t.write(`username=x-access-token\npassword=${a(o)}\n`),0;let c=await n.get(i),l=r?.getDiag?.(),u=c==null?l?.kind??`absent`:`found`;if(r?.log){let e={host:i,outcome:u,backend:n.backend,...l?.error?{keychainError:l.error}:{}};u===`found`?r.log.debug(e,`[auth] git-credential get`):r.log.warn(e,`[auth] git-credential get`)}return c==null?1:(t.write(`username=${a(c.login)}\npassword=${a(c.token)}\n`),0)}function Fn(e){let t={};for(let n of e.split(`
3
3
  `)){let e=n.trim();if(e===``)continue;let r=e.indexOf(`=`);r!==-1&&(t[e.slice(0,r)]=e.slice(r+1))}return t}function In(e){return new Promise((t,n)=>{let r=[];e.on(`data`,e=>r.push(e)),e.on(`end`,()=>t(Buffer.concat(r).toString(`utf-8`))),e.on(`error`,n)})}function Ln(e,n){let r=new t(`git-credential`);return r.description(`Git credential helper (git credential-helper protocol)`),r.command(`get`).description(`Lookup credentials from TokenStore (called by git)`).action(async()=>{let t=n?.();try{let n,r=await e({onKeychainRead:e=>{n=e},onBackendSelected:e=>{e.backend===`file`&&e.reason&&t?.warn({backend:`file`,reason:e.reason},`[auth] token storage fallback`)}}),i=await Pn(process.stdin,process.stdout,r,{log:t,getDiag:()=>n});await Fe(t),process.exit(i)}catch(e){t?.error({error:e instanceof Error?e.message:String(e)},`[auth] git-credential get: unexpected error`),await Fe(t),process.exit(1)}}),r}function Rn(e){let t=e.endpoint.DEFAULTS;return/^https:\/\/(api\.)?github\.com$/.test(t.baseUrl)?`https://github.com`:t.baseUrl.replace(`/api/v3`,``)}async function zn(e,t,n){let r={baseUrl:Rn(e),headers:{accept:`application/json`},...n},i=await e(t,r);if(`error`in i.data){let n=new rt(`${i.data.error_description} (${i.data.error}, ${i.data.error_uri})`,400,{request:e.endpoint.merge(t,r)});throw n.response=i,n}return i}async function Bn(e){let t=e.request||T,n={client_id:e.clientId};return`scopes`in e&&Array.isArray(e.scopes)&&(n.scope=e.scopes.join(` `)),zn(t,`POST /login/device/code`,n)}async function Vn(e){let t=await zn(e.request||T,`POST /login/oauth/access_token`,{client_id:e.clientId,device_code:e.code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`}),n={clientType:e.clientType,clientId:e.clientId,token:t.data.access_token,scopes:t.data.scope.split(/\s+/).filter(Boolean)};if(`clientSecret`in e&&(n.clientSecret=e.clientSecret),e.clientType===`github-app`){if(`refresh_token`in t.data){let e=new Date(t.headers.date).getTime();n.refreshToken=t.data.refresh_token,n.expiresAt=Hn(e,t.data.expires_in),n.refreshTokenExpiresAt=Hn(e,t.data.refresh_token_expires_in)}delete n.scopes}return{...t,authentication:n}}function Hn(e,t){return new Date(e+t*1e3).toISOString()}async function Un(e,t){let n=Wn(e,t.auth);if(n)return n;let{data:r}=await Bn({clientType:e.clientType,clientId:e.clientId,request:t.request||e.request,scopes:t.auth.scopes||e.scopes});await e.onVerification(r);let i=await Kn(t.request||e.request,e.clientId,e.clientType,r);return e.authentication=i,i}function Wn(e,t){if(t.refresh===!0||!e.authentication)return!1;if(e.clientType===`github-app`)return e.authentication;let n=e.authentication;return(`scopes`in t&&t.scopes||e.scopes).join(` `)===n.scopes.join(` `)?n:!1}async function Gn(e){await new Promise(t=>setTimeout(t,e*1e3))}async function Kn(e,t,n,r){try{let i={clientId:t,request:e,code:r.device_code},{authentication:a}=n===`oauth-app`?await Vn({...i,clientType:`oauth-app`}):await Vn({...i,clientType:`github-app`});return{type:`token`,tokenType:`oauth`,...a}}catch(i){if(!i.response)throw i;let a=i.response.data.error;if(a===`authorization_pending`)return await Gn(r.interval),Kn(e,t,n,r);if(a===`slow_down`)return await Gn(r.interval+7),Kn(e,t,n,r);throw i}}async function qn(e,t){return Un(e,{auth:t})}async function Jn(e,t,n,r){let i=t.endpoint.merge(n,r);if(/\/login\/(oauth\/access_token|device\/code)$/.test(i.url))return t(i);let{token:a}=await Un(e,{request:t,auth:{type:`oauth`}});return i.headers.authorization=`token ${a}`,t(i)}var Yn=`0.0.0-development`;function Xn(e){let t=e.request||T.defaults({headers:{"user-agent":`octokit-auth-oauth-device.js/${Yn} ${it()}`}}),{request:n=t,...r}=e,i=e.clientType===`github-app`?{...r,clientType:`github-app`,request:n}:{...r,clientType:`oauth-app`,request:n,scopes:e.scopes||[]};if(!e.clientId)throw Error(`[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)`);if(!e.onVerification)throw Error(`[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)`);return Object.assign(qn.bind(null,i),{hook:Jn.bind(null,i)})}async function Zn(e){let{clientId:t,scopes:n=[`repo`,`read:user`,`user:email`],onVerification:r,host:i}=e,a=i&&i!==`github.com`?`https://${i}/api/v3`:`https://api.github.com`,o=Xn({clientType:`oauth-app`,clientId:t,scopes:n,onVerification:async e=>{await r({verificationUri:e.verification_uri,userCode:e.user_code,expiresIn:e.expires_in,interval:e.interval})},request:a===`https://api.github.com`?void 0:(await import(`./dist-bundle-BnlRWriT.mjs`)).request.defaults({baseUrl:a})}),s;try{s=await o({type:`oauth`})}catch(e){if(e instanceof Error){let t=e.message.toLowerCase();throw t.includes(`access_denied`)?Error(`Device-flow authorization was denied.`):t.includes(`expired_token`)||t.includes(`timeout`)||t.includes(`timed out`)?Error(`Device-flow code expired before authorization — please try again.`):Error(`GitHub sign-in failed: ${e.message}`)}throw e}return{token:s.token,tokenType:s.tokenType,scopes:s.scopes??[]}}function Qn(){return process.env.OPEN_KNOWLEDGE_GITHUB_CLIENT_ID??`Ov23liqlSd0V1MwR6rhI`}const $n=new Set([`gitlab.com`,`bitbucket.org`,`codeberg.org`,`gitea.com`,`sr.ht`,`sourcehut.org`]);function H(e){let t=e.toLowerCase().replace(/:\d+$/,``);$n.has(t)&&(process.stderr.write(`Error: ${e} is not a GitHub host. Only GitHub and GitHub Enterprise Server are supported.\n`),process.exit(1))}function er(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function tr(e,t,n=Zn){let r=Qn(),{host:i,json:a}=e;H(i),a||process.stderr.write(`Logging in to ${i}\n`);let o=await n({clientId:r,host:i===`github.com`?void 0:i,onVerification:e=>{e.userCode,e.verificationUri,a?er(!0,{type:`verification`,user_code:e.userCode,verification_uri:e.verificationUri,expires_in:e.expiresIn}):process.stderr.write(`Open: ${e.verificationUri}\nEnter code: ${e.userCode}\n`)}}),s=`unknown`,c,l;try{let e=i===`github.com`?`https://api.github.com`:`https://${i}/api/v3`,t=await fetch(`${e}/user`,{headers:{Authorization:`Bearer ${o.token}`,"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();s=e.login??s,c=e.name??void 0,l=e.email??void 0}}catch{}await t.set(i,s,o.token,{gitProtocol:`https`,name:c,email:l}),a?er(!0,{type:`complete`,host:i,login:s}):process.stderr.write(`✓ Logged in as ${s} on ${i}\n`)}function nr(e){return new t(`login`).description(`Authenticate with GitHub via Device Flow`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{await tr(t,await e())})}const rr=e=>e.name===`enter`||e.name===`return`;var ir=class extends Error{name=`AbortPromptError`;message=`Prompt was aborted`;constructor(e){super(),this.cause=e?.cause}},ar=class extends Error{name=`CancelPromptError`;message=`Prompt was canceled`},or=class extends Error{name=`ExitPromptError`},sr=class extends Error{name=`HookError`},cr=class extends Error{name=`ValidationError`};const lr=new Dn;function ur(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function dr(e,t){let n=ur(e);return lr.run(n,()=>{function e(e){n.handleChange=()=>{n.index=0,e()},n.handleChange()}return t(e)})}function U(){let e=lr.getStore();if(!e)throw new sr(`[Inquirer] Hook functions can only be called from within a prompt`);return e}function fr(){return U().rl}function pr(e){return On.bind((...t)=>{let n=U(),r=!1,i=n.handleChange;n.handleChange=()=>{r=!0};let a=e(...t);return r&&i(),n.handleChange=i,a})}function mr(e){let t=U(),{index:n}=t,r=e({get(){return t.hooks[n]},set(e){t.hooks[n]=e},initialized:n in t.hooks});return t.index++,r}function hr(){U().handleChange()}const gr={queue(e){let t=U(),{index:n}=t;t.hooksEffect.push(()=>{t.hooksCleanup[n]?.();let r=e(fr());if(r!=null&&typeof r!=`function`)throw new cr(`useEffect return value must be a cleanup function or nothing.`);t.hooksCleanup[n]=r})},run(){let e=U();pr(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=U();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function _r(e){return typeof e==`function`}function W(e){return mr(t=>{let n=On.bind(function(e){t.get()!==e&&(t.set(e),hr())});if(t.initialized)return[t.get(),n];let r=_r(e)?e():e;return t.set(r),[r,n]})}function vr(e,t){mr(n=>{let r=n.get();(!Array.isArray(r)||t.some((e,t)=>!Object.is(e,r[t])))&&gr.queue(e),n.set(t)})}const yr={prefix:{idle:V(`blue`,`?`),done:V(`green`,lt.tick)},spinner:{interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`].map(e=>V(`yellow`,e))},style:{answer:e=>V(`cyan`,e),message:e=>V(`bold`,e),error:e=>V(`red`,`> ${e}`),defaultAnswer:e=>V(`dim`,`(${e})`),help:e=>V(`dim`,e),highlight:e=>V(`cyan`,e),key:e=>V(`cyan`,V(`bold`,`<${e}>`))}};function br(e){if(typeof e!=`object`||!e)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function xr(...e){let t={};for(let n of e)for(let[e,r]of Object.entries(n)){let n=t[e];t[e]=br(n)&&br(r)?xr(n,r):r}return t}function Sr(...e){return xr(yr,...e.filter(e=>e!=null))}function Cr({status:e=`idle`,theme:t}){let[n,r]=W(!1),[i,a]=W(0),{prefix:o,spinner:s}=Sr(t);return vr(()=>{if(e===`loading`){let e,t=-1,n=setTimeout(()=>{r(!0),e=setInterval(()=>{t+=1,a(t%s.frames.length)},s.interval)},300);return()=>{clearTimeout(n),clearInterval(e)}}else r(!1)},[e]),n?s.frames[i]:typeof o==`string`?o:o[e===`loading`?`idle`:e]??o.idle}function wr(e){return W({current:e})[0]}function Tr(e){let t=wr(e);t.current=e,vr(e=>{let n=!1,r=pr((r,i)=>{n||t.current(i,e)});return e.input.on(`keypress`,r),()=>{n=!0,e.input.removeListener(`keypress`,r)}},[])}var Er=e(vt(),1);function Dr(e,t){return e.split(`
4
4
  `).flatMap(e=>at(e,t,{trim:!1,hard:!0}).split(`
5
5
  `).map(e=>e.trimEnd())).join(`
@@ -19,7 +19,7 @@ import{s as e}from"./chunk-C94x7I9S.mjs";import{t}from"./esm-BLMtE3s6.mjs";impor
19
19
  `),patterns:[...t],lineCount:n}}const qi=z(pn(),`.ok`,`logs`),Ji=z(pn(),`.ok`,`bug-reports`);function Yi(e){let t=z(e,`.ok`,`config.yml`);if(P(t))try{let e=I(t,`utf8`).match(/^\s*name:\s*['"]?(.+?)['"]?\s*$/m);if(e?.[1])return e[1]}catch{}return P(z(e,`.ok`))?Sn(`sha256`).update(B(e)).digest(`hex`).slice(0,12):null}function Xi(){let e={timestamp:new Date().toISOString(),platform:mn(),osType:vn(),osRelease:hn(),hostname:`[redacted]`,uptime:yn(),freeMem:fn(),totalMem:_n(),nodeVersion:process.version,bunVersion:process.versions.bun??null,v8Version:process.versions.v8??null,pid:process.pid};try{e.macosVersion=Kt(`sw_vers -productVersion 2>/dev/null`,{encoding:`utf8`}).trim()}catch{}try{let t=z(__dirname,`..`,`..`,`package.json`);P(t)&&(e.okVersion=JSON.parse(I(t,`utf8`)).version)}catch{}return e}function Zi(e){if(!P(qi))return{files:[],dir:qi};let t=en(qi).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(e=>z(qi,e));if(e&&t.length>0){let n=t.filter(t=>{try{return I(t,`utf8`).includes(`"project":"${e}"`)}catch{return!0}});n.length>0&&(t=n)}return{files:t,dir:qi}}function Qi(e){let t=z(e,`.ok`,`local`);return P(t)?{files:[`server.lock`,`last-spawn-error.log`].map(e=>z(t,e)).filter(e=>P(e)),dir:t}:{files:[],dir:null}}function $i(e){let t=z(e,`.ok`,`local`,`logs`);return P(t)?{files:[`server-current.jsonl`,`server-prev.jsonl`].map(e=>z(t,e)).filter(e=>P(e)),dir:t}:{files:[],dir:null}}async function ea(t){let n=ju();F(Ji,{recursive:!0});let r=z(Ji,`${new Date().toISOString().replace(/[:.]/g,`-`)}-bugreport.zip`);n?.info({projectSlug:t.projectSlug},`gathering diagnostic data`);let i=Xi(),{files:a}=Zi(t.projectSlug),{files:o}=Qi(t.cwd),{files:s}=$i(t.cwd);n?.info({logFileCount:a.length,lockFileCount:o.length,localSinkFileCount:s.length},`files collected`);let c=[],l=[],{ZipFile:u}=await import(`./yazl-CQSNnbvt.mjs`).then(t=>e(t.default,1)),d=new u;for(let e of a)try{let{redacted:t,patterns:n,lineCount:r}=Ki(I(e,`utf8`)),i=`logs/${R(e)}`;d.addBuffer(Buffer.from(t,`utf8`),i),l.push(i),n.length>0&&c.push({file:i,lineCount:r,patterns:n})}catch{}for(let e of o)try{let{redacted:t,patterns:n,lineCount:r}=Ki(I(e,`utf8`)),i=`lockdir/${R(e)}`;d.addBuffer(Buffer.from(t,`utf8`),i),l.push(i),n.length>0&&c.push({file:i,lineCount:r,patterns:n})}catch{}for(let e of s)try{let{redacted:t,patterns:n,lineCount:r}=Ki(I(e,`utf8`)),i=`local-logs/${R(e)}`;d.addBuffer(Buffer.from(t,`utf8`),i),l.push(i),n.length>0&&c.push({file:i,lineCount:r,patterns:n})}catch{}let f=JSON.stringify(i,null,2);d.addBuffer(Buffer.from(f,`utf8`),`sysinfo.json`),l.push(`sysinfo.json`);let p={generatedAt:new Date().toISOString(),disciplineVersion:`1.0.0`,projectSlug:t.projectSlug,files:l,redactions:c,sysinfo:i};d.addBuffer(Buffer.from(JSON.stringify(p,null,2),`utf8`),`MANIFEST.json`);let m=c.reduce((e,t)=>e+t.lineCount,0),h=[`# Bug Report Bundle`,``,`Generated: ${p.generatedAt}`,`Project: ${t.projectSlug??`(unscoped)`}`,`Discipline version: ${p.disciplineVersion}`,``,`## Contents`,``,...l.map(e=>`- ${e}`),``,`## Privacy`,``,`This bundle was auto-redacted before packaging.`,`Patterns checked: ${Gi.join(`, `)}`,m>0?`${m} line(s) were scrubbed across ${c.length} file(s).`:`No redactions were needed.`,`See MANIFEST.json for the full redaction audit report.`,``,`This bundle is safe to attach to a GitHub issue.`].join(`
20
20
  `);d.addBuffer(Buffer.from(h,`utf8`),`README.md`),d.end();let g=Zt(r);if(d.outputStream.pipe(g),await new Promise((e,t)=>{g.on(`close`,e),g.on(`error`,t)}),n?.info({bundlePath:r,fileCount:l.length,redactionCount:m},`bundle written`),process.stdout.write(`${r}\n`),m>0&&process.stderr.write(`ok bug-report: ${m} line(s) auto-redacted across ${c.length} file(s)\n`),!t.noReveal&&mn()===`darwin`)try{M(`/usr/bin/open`,[`-R`,r],{detached:!0,stdio:`ignore`}).unref()}catch{}return r}function ta(){return new t(`bug-report`).description(`Generate a diagnostic bundle for bug reporting`).option(`--reveal`,`Reveal the bundle in Finder (default: true)`,!0).option(`--no-reveal`,`Do not reveal the bundle in Finder`).action(async e=>{let t=process.cwd(),n=Yi(t);try{await ea({projectSlug:n,cwd:t,noReveal:!e.reveal})}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`ok bug-report: failed — ${t}\n`),process.exitCode=1}})}function na(e,t){let n=[];for(let[r,i]of[[`server`,e],[`ui`,t]])(i.status===`dead-pid`||i.status===`corrupt`)&&n.push({name:r,lockPath:i.lockPath,reason:i.status});return{prune:n}}function ra(e){let t=e.inspect??(t=>Et(e.lockDir,t)),n=e.unlink??(e=>an(e)),r=e.log??(e=>console.log(e)),i=e.error??(e=>console.error(e)),a=na(t(`server`),t(`ui`));if(a.prune.length===0)return r(`No stale locks.`),{pruned:[],failed:[]};let o=[],s=[];for(let e of a.prune)try{n(e.lockPath),o.push(e)}catch(t){s.push({target:e,error:t instanceof Error?t.message:String(t)})}if(o.length>0){let e=o.map(e=>`${e.name} (${e.reason})`).join(`, `);r(`Pruned ${o.length} stale lock${o.length===1?``:`s`}: ${e}`)}return s.length>0&&i(`Failed to prune: ${s.map(({target:e,error:t})=>`${e.name} (${e.lockPath}): ${t}`).join(`; `)}`),{pruned:o,failed:s}}function ia(e){return new t(`clean`).description(`Prune stale / corrupt open-knowledge lock files (never touches live locks)`).action(()=>{e(),ra({lockDir:Ce(process.cwd())}).failed.length>0&&(process.exitCode=1)})}async function aa(e,t,n={},r=ne){if(!n.skipGhDetect&&r().available)return{tier:`A`,credentialArgs:[`-c`,`credential.helper=!gh auth git-credential`]};let i=await t.get(e);return i==null?{tier:`none`,credentialArgs:[]}:{tier:i.gitProtocol===`ssh`?`C`:`B`,credentialArgs:[`-c`,`credential.helper=!open-knowledge auth git-credential`]}}async function oa(e,t,n=fetch){let r=new AbortController,i=setTimeout(()=>r.abort(),5e3);try{return(await n(`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{signal:r.signal,headers:{"User-Agent":`open-knowledge-cli`,Accept:`application/vnd.github+json`}})).status===200}catch{return!1}finally{clearTimeout(i)}}const sa=[[`count`,0,10],[`compress`,10,20],[`receiv`,20,60],[`resolv`,60,100]];function ca(e){let t=/^([\w ]+):\s+(\d+)%/.exec(e.trim());if(!t)return null;let n=t[1].toLowerCase(),r=Number(t[2]);for(let[e,i,a]of sa)if(n.includes(e))return{stage:t[1],pct:Math.round(i+r/100*(a-i))};return null}function q(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}function la(e=process.env){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t.GIT_TERMINAL_PROMPT=`0`,t.LANG=`C`,t.LC_ALL=`C`,t}function ua(e){return typeof e!=`string`||e.length===0?[`--progress`]:[`--progress`,`-b`,e]}const da=u;async function fa(e){try{return await e.clone(ua(e.branch)),{fellBack:!1}}catch(t){if(e.branch!==null&&da(t))return e.onFallback(e.branch),await e.clone(ua(null)),{fellBack:!0};throw t}}function pa(e,t,n){return e===`https`&&t===`github.com`&&n}async function ma(e,t,n,r=process.cwd()){let i=kt(e);if(!i)throw Error(`Invalid git URL: ${e}`);let a=t.dir?B(r,t.dir):B(r,i.name);if(P(a)&&en(a).length>0)throw Error(`Target directory is not empty: ${a}`);let o=ee(),s=i.protocol===`https`&&i.hostname===`github.com`?await oa(i.owner,i.name):!1,c=pa(i.protocol,i.hostname,s)?{tier:`none`,credentialArgs:[]}:await aa(i.hostname,o,{}),l=la(),u=re({baseDir:r,config:c.credentialArgs.length>=2?[c.credentialArgs[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env(l),d=-1;u.outputHandler((e,n,r)=>{r.on(`data`,e=>{let n=e.toString(`utf-8`);for(let e of n.split(`
21
21
  `)){let n=ca(e);n&&n.pct!==d&&(d=n.pct,q(t.json,{type:`progress`,pct:n.pct,stage:n.stage}),t.json||process.stderr.write(`\r Cloning ${n.pct}%`))}})}),await fa({branch:typeof t.branch==`string`&&t.branch.length>0?t.branch:null,clone:t=>u.clone(e,a,t),onFallback:e=>{q(t.json,{type:`branch-fallback`,branch:e}),t.json||process.stderr.write(`\n Branch '${e}' not found upstream — cloning default branch instead.\n`)}}),t.json||process.stderr.write(`
22
- `);try{let{runInit:e}=await import(`./init-CyytdzLx.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?q(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?q(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{ha(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?q(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function ha(e){let t=yt(e,[`.ok/`]);return t.kind===`no-exclude`?`no-exclude`:t.kind===`refused-tracked`?`already-present`:t.appended.length>0?`appended`:`already-present`}function ga(e){return new t(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).option(`-b, --branch <branch>`,`Branch to check out (falls back to default if missing)`).action(async(t,n,r)=>{let i=e();try{let a=await ma(t,{json:r.json,dir:n,branch:r.branch??null},i);if(r.json)q(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-BnH1uaVq.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?q(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}var _a=c();const va=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],...r.map(e=>e.path)];function ya(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??Ft;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function ba(e){let t=(0,_a.parseDocument)(I(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of va)t.hasIn(e)&&n.push(e.join(`.`));return n}function xa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Sa(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=xa(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function Ca(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,i=e.dryRun??!1,a=e.cwd??process.cwd(),s=e.writeConfigPatchFn??ze,c=[];(r===`project`||r===`both`)&&c.push({scope:`project`,absPath:be(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&c.push({scope:`user`,absPath:be(`user`,a,e.homedirOverride)});let l=[],u=!0;for(let{scope:t,absPath:n}of c){if(!P(n)){l.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=ba(n)}catch(e){let r=e instanceof Error?e.message:String(e);l.push({path:n,scope:t,found:[],removed:[],error:r}),u=!1;continue}if(r.length===0||i){l.push({path:n,scope:t,found:r,removed:[]});continue}let c=await s({cwd:a,scope:t,patch:Sa(va.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!c.ok){l.push({path:n,scope:t,found:r,removed:[],error:o(c.error)}),u=!1;continue}l.push({path:n,scope:t,found:r,removed:r})}for(let e of l)e.error&&n(`✗ ${e.path}: ${e.error}`);let d=l.some(e=>e.error!==void 0),f=l.reduce((e,t)=>e+t.found.length,0);if(f===0&&!d)t(`No deprecated fields found.`);else if(f>0)for(let e of l)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:l,ok:u}}function wa(){let e=new t(`config`).description(`Inspect and maintain Open Knowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{ya({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields from config.yml idempotently (every removed key in the registry — content.*, folders, appearance.editorModeDefault, server.host, etc. — plus the silently-dropped sync.*, persistence.*, server.port)`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await Ca({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var Ta=e(nt(),1),J=e(Ut(),1);const Ea=new Set([`doc.name`]);function Da(e){return`doc:${Sn(`blake2b512`,{outputLength:32}).update(e).digest(`hex`).slice(0,8)}`}function Oa(e,t,n){let r=e.docNameMap[n];if(r===void 0){e.docNameMap[n]=t;return}if(r===t)return;let i=e.docNameCollisions[n];i?i.includes(t)||i.push(t):e.docNameCollisions[n]=[t]}function ka(e,t){let n=t.originalToHashed.get(e);if(n!==void 0)return n;let r=Da(e);return t.originalToHashed.set(e,r),Oa(t,e,r),r}function Aa(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function ja(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ma(e,t){if(typeof e==`string`)return Aa(e,t.contentDir);if(Array.isArray(e))return e.map(e=>Ma(e,t));if(!ja(e))return e;let n=typeof e.key==`string`&&Ea.has(e.key)&&ja(e.value)&&typeof e.value.stringValue==`string`?e.value.stringValue:null,r={};for(let[i,a]of Object.entries(e))if(n!==null&&i===`value`&&ja(a)){let e=ka(n,t);r[i]={...a,stringValue:e}}else Ea.has(i)&&typeof a==`string`?r[i]=ka(a,t):r[i]=Ma(a,t);return r}function Na(e,t){if(t.originalToHashed.size===0)return e;let n=Array.from(t.originalToHashed.entries()).sort(([e],[t])=>t.length-e.length),r=e;for(let[e,t]of n)e.length!==0&&r.includes(e)&&(r=r.split(e).join(t));return r}function Pa(e,t){let n=I(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
22
+ `);try{let{runInit:e}=await import(`./init-Dky4vpd9.mjs`),n=await e({cwd:a,mcp:!1});if(n.contentUpdated.length>0){let e=`auto-init: updated ${n.contentUpdated.join(`, `)}`;t.json?q(!0,{type:`warning`,message:e}):process.stderr.write(` ${e}\n`)}}catch(e){let n=e instanceof Error?e.message:String(e);t.json?q(!0,{type:`warning`,message:`auto-init: ${n}`}):process.stderr.write(` auto-init: ${n}\n`)}try{ha(a)}catch(e){let n=e instanceof Error?e.message:String(e);t.json?q(!0,{type:`warning`,message:`git-exclude: ${n}`}):process.stderr.write(` git-exclude: ${n}\n`)}return a}function ha(e){let t=yt(e,[`.ok/`]);return t.kind===`no-exclude`?`no-exclude`:t.kind===`refused-tracked`?`already-present`:t.appended.length>0?`appended`:`already-present`}function ga(e){return new t(`clone`).description(`Clone a git repository and open it`).argument(`<url>`,`Repository URL or owner/repo shorthand`).argument(`[dir]`,`Target directory (default: ./<repo-name>)`).option(`--json`,`Output JSONL progress events`,!1).option(`-b, --branch <branch>`,`Branch to check out (falls back to default if missing)`).action(async(t,n,r)=>{let i=e();try{let a=await ma(t,{json:r.json,dir:n,branch:r.branch??null},i);if(r.json)q(!0,{type:`complete`,dir:a});else{process.stderr.write(`✓ Cloned to ${a}\n`),process.chdir(a);let{startCommand:t}=await import(`./start-DujEO1M-.mjs`);await t(e).parseAsync([],{from:`user`})}}catch(e){let t=e instanceof Error?e.message:String(e);r.json?q(!0,{type:`error`,message:t}):process.stderr.write(`✗ ${t}\n`),process.exitCode=1}})}var _a=c();const va=[[`sync`],[`persistence`,`debounceMs`],[`persistence`,`maxDebounceMs`],[`server`,`port`],...r.map(e=>e.path)];function ya(e={}){let t=e.log??(e=>console.error(e)),n=e.error??(e=>console.error(e)),r=e.loadConfigFn??Ft;try{let{sources:n}=r(e.cwd);return t(`✓ Configuration valid (sources: ${n.length===0?`defaults only`:n.join(`, `)})`),{ok:!0}}catch(e){return n(e instanceof Error?e.message:String(e)),{ok:!1}}}function ba(e){let t=(0,_a.parseDocument)(I(e,`utf-8`));if(t.errors.length>0)throw Error(`Could not parse ${e}: ${t.errors.map(e=>e.message).join(`; `)}`);let n=[];for(let e of va)t.hasIn(e)&&n.push(e.join(`.`));return n}function xa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Sa(e){let t={};for(let n of e){let e=t;for(let t=0;t<n.length-1;t++){let r=n[t],i=e[r],a=xa(i)?i:{};e[r]=a,e=a}e[n[n.length-1]]=null}return t}async function Ca(e={}){let t=e.log??(e=>console.log(e)),n=e.error??(e=>console.error(e)),r=e.scope??`both`,i=e.dryRun??!1,a=e.cwd??process.cwd(),s=e.writeConfigPatchFn??ze,c=[];(r===`project`||r===`both`)&&c.push({scope:`project`,absPath:be(`project`,a,e.homedirOverride)}),(r===`user`||r===`both`)&&c.push({scope:`user`,absPath:be(`user`,a,e.homedirOverride)});let l=[],u=!0;for(let{scope:t,absPath:n}of c){if(!P(n)){l.push({path:n,scope:t,found:[],removed:[]});continue}let r;try{r=ba(n)}catch(e){let r=e instanceof Error?e.message:String(e);l.push({path:n,scope:t,found:[],removed:[],error:r}),u=!1;continue}if(r.length===0||i){l.push({path:n,scope:t,found:r,removed:[]});continue}let c=await s({cwd:a,scope:t,patch:Sa(va.filter(e=>r.includes(e.join(`.`)))),homedirOverride:e.homedirOverride});if(!c.ok){l.push({path:n,scope:t,found:r,removed:[],error:o(c.error)}),u=!1;continue}l.push({path:n,scope:t,found:r,removed:r})}for(let e of l)e.error&&n(`✗ ${e.path}: ${e.error}`);let d=l.some(e=>e.error!==void 0),f=l.reduce((e,t)=>e+t.found.length,0);if(f===0&&!d)t(`No deprecated fields found.`);else if(f>0)for(let e of l)e.error||(e.found.length===0?t(` ${e.path}: no deprecated fields`):t(i?`[dry-run] ${e.path}: would remove ${e.found.length} field(s): ${e.found.join(`, `)}`:`✓ ${e.path}: removed ${e.removed.length} field(s): ${e.removed.join(`, `)}`));return{outcomes:l,ok:u}}function wa(){let e=new t(`config`).description(`Inspect and maintain Open Knowledge configuration files`);return e.command(`validate`).description(`Validate the merged config (defaults → user → project)`).action(()=>{ya({}).ok||(process.exitCode=1)}),e.command(`migrate`).description(`Remove deprecated config fields from config.yml idempotently (every removed key in the registry — content.*, folders, appearance.editorModeDefault, server.host, etc. — plus the silently-dropped sync.*, persistence.*, server.port)`).option(`--scope <scope>`,`Which scope to migrate: project | user | both`,`both`).option(`--dry-run`,`Preview without writing`,!1).action(async e=>{let t=e.scope;if(t!==`project`&&t!==`user`&&t!==`both`){console.error(`Invalid --scope: ${t}. Expected: project | user | both`),process.exitCode=2;return}(await Ca({scope:t,dryRun:e.dryRun})).ok||(process.exitCode=1)}),e}var Ta=e(nt(),1),J=e(Ut(),1);const Ea=new Set([`doc.name`]);function Da(e){return`doc:${Sn(`blake2b512`,{outputLength:32}).update(e).digest(`hex`).slice(0,8)}`}function Oa(e,t,n){let r=e.docNameMap[n];if(r===void 0){e.docNameMap[n]=t;return}if(r===t)return;let i=e.docNameCollisions[n];i?i.includes(t)||i.push(t):e.docNameCollisions[n]=[t]}function ka(e,t){let n=t.originalToHashed.get(e);if(n!==void 0)return n;let r=Da(e);return t.originalToHashed.set(e,r),Oa(t,e,r),r}function Aa(e,t){return t.length===0||!e.includes(t)?e:e.split(t).join(`<CONTENT_DIR>`)}function ja(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ma(e,t){if(typeof e==`string`)return Aa(e,t.contentDir);if(Array.isArray(e))return e.map(e=>Ma(e,t));if(!ja(e))return e;let n=typeof e.key==`string`&&Ea.has(e.key)&&ja(e.value)&&typeof e.value.stringValue==`string`?e.value.stringValue:null,r={};for(let[i,a]of Object.entries(e))if(n!==null&&i===`value`&&ja(a)){let e=ka(n,t);r[i]={...a,stringValue:e}}else Ea.has(i)&&typeof a==`string`?r[i]=ka(a,t):r[i]=Ma(a,t);return r}function Na(e,t){if(t.originalToHashed.size===0)return e;let n=Array.from(t.originalToHashed.entries()).sort(([e],[t])=>t.length-e.length),r=e;for(let[e,t]of n)e.length!==0&&r.includes(e)&&(r=r.split(e).join(t));return r}function Pa(e,t){let n=I(e,`utf-8`);if(n.length===0)return;let r=n.endsWith(`
23
23
  `),i=n.split(`
24
24
  `),a=[];for(let e=0;e<i.length;e++){let n=i[e]??``;if(!(e===i.length-1&&n===``)){if(n.length===0){a.push(``);continue}try{let e=Ma(JSON.parse(n),t);a.push(JSON.stringify(e))}catch{a.push(n)}}}L(e,r?`${a.join(`
25
25
  `)}\n`:a.join(`
@@ -50,7 +50,7 @@ ws.addEventListener('error', () => process.exit(1));
50
50
  setTimeout(() => process.exit(2), ${t+1e4});
51
51
  `),r}async function Ko(e,t,n,r,i){let a=Go(e,t,z(r,`cpu.cpuprofile`)),o=!1,s=M(process.execPath,[a],{stdio:`ignore`}),c=setInterval(()=>{let e=Vo(n);e&&i(e)},1e3);await new Promise(e=>{s.once(`close`,t=>{o=t===0,e()}),setTimeout(()=>{s.kill(),e()},t+12e3)}),clearInterval(c);try{nn(z(a,`..`),{recursive:!0,force:!0})}catch{}return o}function qo(e){let t;try{t=JSON.parse(e)}catch{return`(could not parse profile)`}let n=new Map(t.nodes.map(e=>[e.id,e])),r=new Map;for(let e of t.nodes)for(let t of e.children??[])r.set(t,e.id);let i=new Map;for(let e of t.samples??[])i.set(e,(i.get(e)??0)+1);let a=t.samples?.length??0,o=t.endTime!=null&&t.startTime!=null?((t.endTime-t.startTime)/1e3).toFixed(2):`?`,s=[...i.entries()].sort((e,t)=>t[1]-e[1]).slice(0,10),c=[`samples ${a} duration_ms ${o}`,``,`Top leaf nodes`];for(let[e,t]of s){let r=n.get(e);if(!r)continue;let i=a>0?(t/a*100).toFixed(1):`0.0`,{functionName:o,url:s,lineNumber:l,columnNumber:u}=r.callFrame;c.push(` ${t} ${i}% id=${e} ${o||`(anonymous)`} ${s}:${l}:${u} hit=${r.hitCount??0}`)}c.push(``,`Top stacks`);let l=e=>{let t=[],i=e;for(;i!=null;){let e=n.get(i);if(!e)break;let{functionName:a,url:o,lineNumber:s,columnNumber:c}=e.callFrame;t.unshift(` ${a||`(anonymous)`} ${o} ${s} ${c}`),i=r.get(i)}return t};for(let[e,t]of s.slice(0,5)){let n=a>0?(t/a*100).toFixed(1):`0.0`;c.push(``,`--- ${t} ${n}%`,...l(e))}return c.join(`
52
52
  `)}async function Jo(e,t={}){let{pid:n,cpuProfileSecs:r=15,noInspector:i=!1}=e,a=t.log??(e=>console.log(e)),o=t.discover??Tt,s=t.inspect??Et,c=t.resolveCommand??Ot,l=t.resolveUsage??Mt,u=t.collectLsofFn??Ho,d=t.getEndpoints??Wo,f=t.profiler??Ko,p=t.isAlive??(e=>{try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}),m=t.sendSignal??((e,t)=>{process.kill(e,t)}),h=t.sleep??(e=>new Promise(t=>setTimeout(t,e))),g=r*1e3;if(!p(n)){a(J.default.red(`No process with pid ${n} found.`));return}let _=await o(),v=null,y=null;for(let e of _){let t=s(e,`server`);if(t.status!==`missing`&&t.status!==`corrupt`&&t.lock.pid===n){v=t.lock.worktreeRoot,y={lockDir:e,state:t.status,lockPath:t.lockPath,lock:t.lock};break}}let b=new Date().toISOString().replace(/[:.]/g,`-`),x=e.output?e.output:v?z(v,`.ok`,`local`,`diagnostics`,`process-${n}-${b}`):z(process.cwd(),`ok-diagnose-${n}-${b}`);try{F(x,{recursive:!0})}catch(e){a(J.default.red(`Cannot create output directory ${x}: ${e.message}`));return}a(J.default.bold(`Diagnosing pid ${n}`)),a(`Output: ${x}`),a(``);let S=(e,t)=>{L(z(x,e),t),a(` wrote ${e}`)},C=c(n),ee=l(n);S(`metadata.json`,JSON.stringify({capturedAt:new Date().toISOString(),pid:n,command:C,usage:ee,lockInfo:y},null,2)),a(` sampling lsof`);let w=u(n);if(w&&S(`lsof.txt`,w),!i){let e=w?Uo(w).find(e=>e>=9229&&e<=9299)??9229:9229,t=d(e);if(!t||t.length===0){a(` no inspector on :${e}, sending SIGUSR1 to pid ${n}`);try{m(n,`SIGUSR1`),await h(2e3),t=d(e)}catch(e){a(J.default.yellow(` SIGUSR1 delivery failed: ${e.message}`))}}if(t&&t.length>0){S(`inspector-endpoints.json`,JSON.stringify(t,null,2));let e=t[0].webSocketDebuggerUrl;if(e){a(` capturing ${r}s CPU profile`);let t=[];await f(e,g,n,x,e=>t.push(e))?a(` wrote cpu.cpuprofile`):a(J.default.yellow(` CPU profile capture failed`)),t.length>0&&S(`process-stats.jsonl`,`${t.map(e=>JSON.stringify(e)).join(`
53
- `)}\n`);try{S(`stacks.txt`,qo(I(z(x,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(J.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(J.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(J.default.yellow(`⚠ Before sharing, review what each file contains:`)),a(` metadata.json — content directory paths, lock file locations, CPU/MEM at capture time`),a(` lsof.txt — all open files, network connections, and private paths for this process`),a(` inspector-endpoints.json — Node debugger metadata (titles, URLs)`),a(` cpu.cpuprofile — function names and source file paths from your Node process`),a(` stacks.txt — call stacks derived from cpu.cpuprofile; includes source paths`),a(` process-stats.jsonl — CPU/MEM/RSS numbers only; safe to share`),a(``),a(`Bundle: ${J.default.bold(x)}`)}async function Yo(e){let t=An({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function Xo(e){let t=Qt(z(gn(),`ok-bundle-process-`));return await Jo({pid:e,output:t}),t}function Zo(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(1)} GB`}function Qo(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function $o(e,t,n){let{summary:r,manifest:i}=t;e(``),e(J.default.bold(`ok diagnose bundle — content summary`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${Zo(r.totalBytes)} uncompressed`),e(` doc.name attributes: ${r.docNameCount} occurrence(s) in telemetry${r.redacted?` (values hashed)`:``}`),e(` Content-dir path: ${r.contentDirVisible?`visible (${i.contentDir.absolutePath})`:`not visible`}`),e(` Redacted: ${r.redacted?`yes`:`no`}`),e(` Server status: ${i.serverStatus}`),e(` Output: ${n}`),e(``)}async function es(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??Yo,i=t.runProcessDiagnose??Xo,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=sn(o);if(!P(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=z(e.contentDir,`.ok`,`local`,`diagnostics`);F(n,{recursive:!0}),o=z(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(J.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=await go({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:e.redact===!0,deps:t.collectDeps});try{return c.manifest.serverStatus===`not-running`&&n(J.default.yellow(` server not running — live state unavailable`)),$o(n,c,o),e.yes!==!0&&!Qo(await r(`Write bundle? [y/N]: `))?(n(J.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await _o({collected:c,outputPath:o}),n(J.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(c.cleanup(),s!==void 0)try{nn(s,{recursive:!0,force:!0})}catch{}}}function ts(){let e=new t(`diagnose`).description(`Diagnostic utilities for open-knowledge processes`);return e.command(`process`).description(`Capture a diagnostic bundle (metadata, lsof, CPU profile) for a running process`).argument(`<pid>`,`Process ID to diagnose`).option(`--cpu-profile <seconds>`,`CPU profile duration (default: 15)`,`15`).option(`--output <dir>`,`Output directory`).option(`--no-inspector`,`Collect metadata only; skip Node inspector and CPU profile`).action(async(e,t)=>{let n=Number.parseInt(e,10);(Number.isNaN(n)||n<=0)&&(console.error(J.default.red(`Invalid pid '${e}': must be a positive integer`)),process.exit(1));let r=Number.parseInt(t.cpuProfile,10);(Number.isNaN(r)||r<=0)&&(console.error(J.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await Jo({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(Bo()),e.command(`bundle`).description(`Capture a support bundle (telemetry + logs + server state) into a zip suitable for bug reports`).option(`--pid <pid>`,"Include `ok diagnose process <pid>` output under process/ in the bundle").option(`--out <path>`,`Write the zip to this path instead of the default location`).option(`--yes`,`Skip the y/N prompt`).option(`--redact`,`Hash doc names and strip the content-dir prefix from the staged bundle`).action(async e=>{let t;e.pid!==void 0&&(t=Number.parseInt(e.pid,10),(Number.isNaN(t)||t<=0)&&(console.error(J.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-7E2btZCD.mjs`),{resolveContentDir:r}=await import(`./dist-BXU3sfTZ.mjs`),i=process.cwd(),{config:a}=n(i);await es({contentDir:r(a,i),projectDir:i,pid:t,out:e.out,yes:e.yes===!0,redact:e.redact===!0})}catch(e){let t=e instanceof Error?e.message:String(e);console.error(J.default.red(t)),process.exit(1)}}),e}async function ns(){if(!process.stdin.isTTY){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf-8`).trim()}return(await Rr({message:`Enter OpenAI embeddings API key:`})).trim()}function rs(e){return Qe(e)}async function is(){return(await We()).file?{present:!0,source:`file`}:process.env.OK_EMBEDDINGS_API_KEY?{present:!0,source:`env`}:{present:!1,source:null}}async function as(e){try{let t=m(Ce(e));if(!t||t.port<=0||!y(t.pid))return null;let n=await fetch(`http://127.0.0.1:${t.port}/api/semantic-status`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return null;let r=await n.json();return typeof r.embedded!=`number`||typeof r.total!=`number`?null:{embedded:r.embedded,total:r.total}}catch{return null}}function os(){return new t(`set-key`).description(`Store your OpenAI embeddings API key in ~/.ok/secrets.yml`).action(async()=>{let e=await ns();if(!e){process.stderr.write(`No key provided.
53
+ `)}\n`);try{S(`stacks.txt`,qo(I(z(x,`cpu.cpuprofile`),`utf-8`)))}catch(e){a(J.default.yellow(` stacks.txt skipped: ${e.message}`))}}}else a(J.default.yellow(` Node inspector unavailable — skipping CPU profile`))}a(``),a(J.default.yellow(`⚠ Before sharing, review what each file contains:`)),a(` metadata.json — content directory paths, lock file locations, CPU/MEM at capture time`),a(` lsof.txt — all open files, network connections, and private paths for this process`),a(` inspector-endpoints.json — Node debugger metadata (titles, URLs)`),a(` cpu.cpuprofile — function names and source file paths from your Node process`),a(` stacks.txt — call stacks derived from cpu.cpuprofile; includes source paths`),a(` process-stats.jsonl — CPU/MEM/RSS numbers only; safe to share`),a(``),a(`Bundle: ${J.default.bold(x)}`)}async function Yo(e){let t=An({input:process.stdin,output:process.stdout});try{return(await t.question(e)).trim()}finally{t.close()}}async function Xo(e){let t=Qt(z(gn(),`ok-bundle-process-`));return await Jo({pid:e,output:t}),t}function Zo(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(1)} GB`}function Qo(e){let t=e.trim().toLowerCase();return t===`y`||t===`yes`}function $o(e,t,n){let{summary:r,manifest:i}=t;e(``),e(J.default.bold(`ok diagnose bundle — content summary`)),e(``),e(` Files: ${r.fileCount}`),e(` Total size: ${Zo(r.totalBytes)} uncompressed`),e(` doc.name attributes: ${r.docNameCount} occurrence(s) in telemetry${r.redacted?` (values hashed)`:``}`),e(` Content-dir path: ${r.contentDirVisible?`visible (${i.contentDir.absolutePath})`:`not visible`}`),e(` Redacted: ${r.redacted?`yes`:`no`}`),e(` Server status: ${i.serverStatus}`),e(` Output: ${n}`),e(``)}async function es(e,t={}){let n=t.log??(e=>console.log(e)),r=t.prompt??Yo,i=t.runProcessDiagnose??Xo,a=t.now??(()=>new Date),o;if(e.out!==void 0){o=e.out;let t=sn(o);if(!P(t))throw Error(`ok diagnose bundle: --out parent directory does not exist: ${t}. Create it first.`)}else{let t=a().toISOString().replace(/[:.]/g,`-`),n=z(e.contentDir,`.ok`,`local`,`diagnostics`);F(n,{recursive:!0}),o=z(n,`bundle-${t}.zip`)}let s;e.pid!==void 0&&(n(J.default.dim(`Running ok diagnose process ${e.pid} into a temp dir`)),s=await i(e.pid));let c=await go({contentDir:e.contentDir,projectDir:e.projectDir,processDir:s,redact:e.redact===!0,deps:t.collectDeps});try{return c.manifest.serverStatus===`not-running`&&n(J.default.yellow(` server not running — live state unavailable`)),$o(n,c,o),e.yes!==!0&&!Qo(await r(`Write bundle? [y/N]: `))?(n(J.default.dim(`Aborted; no bundle written.`)),{outputPath:null,declined:!0}):(await _o({collected:c,outputPath:o}),n(J.default.bold(`Bundle: ${o}`)),{outputPath:o,declined:!1})}finally{if(c.cleanup(),s!==void 0)try{nn(s,{recursive:!0,force:!0})}catch{}}}function ts(){let e=new t(`diagnose`).description(`Diagnostic utilities for open-knowledge processes`);return e.command(`process`).description(`Capture a diagnostic bundle (metadata, lsof, CPU profile) for a running process`).argument(`<pid>`,`Process ID to diagnose`).option(`--cpu-profile <seconds>`,`CPU profile duration (default: 15)`,`15`).option(`--output <dir>`,`Output directory`).option(`--no-inspector`,`Collect metadata only; skip Node inspector and CPU profile`).action(async(e,t)=>{let n=Number.parseInt(e,10);(Number.isNaN(n)||n<=0)&&(console.error(J.default.red(`Invalid pid '${e}': must be a positive integer`)),process.exit(1));let r=Number.parseInt(t.cpuProfile,10);(Number.isNaN(r)||r<=0)&&(console.error(J.default.red(`--cpu-profile must be a positive integer`)),process.exit(1)),await Jo({pid:n,cpuProfileSecs:r,output:t.output,noInspector:!t.inspector})}),e.addCommand(Bo()),e.command(`bundle`).description(`Capture a support bundle (telemetry + logs + server state) into a zip suitable for bug reports`).option(`--pid <pid>`,"Include `ok diagnose process <pid>` output under process/ in the bundle").option(`--out <path>`,`Write the zip to this path instead of the default location`).option(`--yes`,`Skip the y/N prompt`).option(`--redact`,`Hash doc names and strip the content-dir prefix from the staged bundle`).action(async e=>{let t;e.pid!==void 0&&(t=Number.parseInt(e.pid,10),(Number.isNaN(t)||t<=0)&&(console.error(J.default.red(`Invalid --pid '${e.pid}': must be a positive integer`)),process.exit(1)));try{let{loadConfig:n}=await import(`./loader-s5lhNT8V.mjs`),{resolveContentDir:r}=await import(`./dist-De0GFsdh.mjs`),i=process.cwd(),{config:a}=n(i);await es({contentDir:r(a,i),projectDir:i,pid:t,out:e.out,yes:e.yes===!0,redact:e.redact===!0})}catch(e){let t=e instanceof Error?e.message:String(e);console.error(J.default.red(t)),process.exit(1)}}),e}async function ns(){if(!process.stdin.isTTY){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf-8`).trim()}return(await Rr({message:`Enter OpenAI embeddings API key:`})).trim()}function rs(e){return Qe(e)}async function is(){return(await We()).file?{present:!0,source:`file`}:process.env.OK_EMBEDDINGS_API_KEY?{present:!0,source:`env`}:{present:!1,source:null}}async function as(e){try{let t=m(Ce(e));if(!t||t.port<=0||!y(t.pid))return null;let n=await fetch(`http://127.0.0.1:${t.port}/api/semantic-status`,{signal:AbortSignal.timeout(1500)});if(!n.ok)return null;let r=await n.json();return typeof r.embedded!=`number`||typeof r.total!=`number`?null:{embedded:r.embedded,total:r.total}}catch{return null}}function os(){return new t(`set-key`).description(`Store your OpenAI embeddings API key in ~/.ok/secrets.yml`).action(async()=>{let e=await ns();if(!e){process.stderr.write(`No key provided.
54
54
  `),process.exitCode=1;return}await pe().set(e),process.stderr.write(`✓ OpenAI embeddings API key stored in ~/.ok/secrets.yml (0600, this machine only).
55
55
  Now enable it per project — the easiest path is OK Desktop → Settings → This
56
56
  project → Search (a toggle with an egress-confirmation prompt), or run
@@ -70,7 +70,7 @@ project → Search (a toggle with an egress-confirmation prompt), or run
70
70
  `).filter(e=>e.startsWith(`worktree `)).length}catch{return 0}}function Sl(e){let t=B(e);for(;;){if(ie(t))return t;let n=sn(t);if(n===t)throw Error(`No Open Knowledge project found at or above ${e}. Pass an explicit \`cwd\` argument that points inside an OK project (a directory with a \`${g}\`).`);t=n}}function Cl(e){try{let t=new URL(e);return t.protocol===`file:`?bn(t):void 0}catch{return}}async function wl(e){if(!e.getClientCapabilities()?.roots)return;let t;try{t=await e.listRoots()}catch(t){e.log?.(`listRoots fallback failed: ${t instanceof Error?t.message:String(t)}`);return}let n=t.roots??[];if(n.length!==1)return;let r=Cl(n[0].uri);return r===void 0&&e.log?.(`single root URI not usable as fs path: ${n[0].uri}`),r}async function Tl(e,t,n,r=Sl){if(e!==void 0){let t=r(e);return{projectDir:t,viaRootGuess:!1,nextSticky:t}}if(t!==void 0){let e=r(t);return{projectDir:e,viaRootGuess:!1,nextSticky:e}}let i=await n();return i===void 0?{projectDir:void 0,viaRootGuess:!1,nextSticky:void 0}:{projectDir:r(i),viaRootGuess:!0,nextSticky:void 0}}async function El(e){let t=process.stderr,n=e.spawnTimeoutMs??il(process.env.OK_MCP_SPAWN_TIMEOUT_MS),r=e.envAutoStart??process.env.OK_MCP_AUTOSTART,i=It({startupCwd:e.startupCwd,startupConfig:e.startupConfig}),a=new Ee({name:se,version:_},{instructions:$e({dir:`.`})});ue(a);let o=Cn(),s={current:{connectionId:o,displayName:o,colorSeed:o}},c=new Map,l=e=>{if(c.has(e))return;let n=oe(e),r=s.current,i=Ts({connectionId:o,displayName:r.displayName,clientName:r.clientInfo?.name??r.displayName,colorSeed:r.colorSeed,resolveWsUrl:async()=>gl({lockDir:n,contentDir:e},``),log:n=>t.write(`[mcp] keepalive[${e}]: ${n}\n`)});c.set(e,i)},u=()=>wl({getClientCapabilities:()=>a.server.getClientCapabilities(),listRoots:()=>a.server.listRoots(),log:e=>t.write(`[mcp] ${e}\n`)}),d,f=!1,p=async e=>{if(f)return;f=!0;let n=await xl(e);if(n<=1){f=!1;return}let r=`Routed to ${e} from the MCP client's single advertised root, but this repo has ${n} git worktrees. If you are working in a worktree, pass its path as \`cwd\` on OK tool calls once — it sticks for the session, so reads, writes, and the preview all target that worktree instead of this checkout.`;try{t.write(`[mcp] ${r}\n`),await a.server.sendLoggingMessage({level:`warning`,data:r})}catch{}},m=async e=>{let t=await Tl(e,d,u);if(d=t.nextSticky??d,t.projectDir===void 0)throw Error("`cwd` is required for tool calls against the global MCP server. Pass an absolute path inside an Open Knowledge project, or have the MCP client advertise a single root.");return t.viaRootGuess&&p(t.projectDir),t.projectDir},h=async e=>{let t=await Tl(e,d,u);if(d=t.nextSticky??d,t.projectDir===void 0)return;t.viaRootGuess&&p(t.projectDir);let a=t.projectDir,o=await i(a),s=await hl({lockDir:oe(a),contentDir:ae(o,a),envAutoStart:r,...n===void 0?{}:{timeoutMs:n}});return l(a),s.replace(/\/mcp$/,``)};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=Ne(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:t,colorSeed:t}},ve(a,{serverUrl:h,resolveCwd:m,config:i,identityRef:s});let g=new ks,v=!1,y,b,x=async()=>{if(v)return;v=!0,y?.stop(),b?.stop();for(let e of c.values())try{e.close()}catch(e){t.write(`[mcp] keepalive close error: ${e instanceof Error?e.message:String(e)}\n`)}c.clear();let e=await Promise.allSettled([a.close(),g.close()]);for(let n of e)if(n.status===`rejected`){let e=n.reason;t.write(`[mcp] shutdown close error: ${e instanceof Error?e.message:String(e)}\n`)}};await a.connect(g),t.write(`[mcp] global stdio server ready (per-call project routing)
71
71
  `);let S=!1,C=()=>{S||(S=!0,setTimeout(()=>{t.write(`[mcp] shutdown deadline (5s) reached — forcing exit(1)
72
72
  `),process.exit(1)},5e3).unref(),x().finally(()=>{process.exit(0)}))};if(process.once(`SIGINT`,C),process.once(`SIGTERM`,C),process.stdin.on(`end`,()=>{t.write(`[mcp] stdin end — host disconnected, shutting down
73
- `),C()}),process.stdin.on(`error`,e=>{t.write(`[mcp] stdin error (${e instanceof Error?e.message:String(e)}) — host disconnected, shutting down\n`),C()}),b=Ns({getPpid:()=>process.ppid,onHostGone:e=>{t.write(`[mcp] ${e} — shutting down\n`),C()}}),Ps({log:e=>t.write(`${e}\n`),transport:g,process,stdin:process.stdin}),process.platform===`darwin`){let e=Ms(yl,{realpathSync:tn,statInoSync:e=>rn(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${_}\n`);let{resolvedPath:n,inode:r}=e;y=js({detect:()=>As({bundleAnchorPath:yl,currentInode:r,platform:process.platform,realpath:tn,statInode:e=>rn(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${_} — exiting for host respawn\n`),C()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:x}}function Dl(e){return new t(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override per-call routing and proxy stdio to this HTTP MCP port (skips bundle proxy)`,void 0).option(`--no-bundle-proxy`,`Run the npm-fetched MCP server in-process instead of proxying to the macOS Desktop bundle (equivalent: OK_BUNDLE_PROXY=0)`).action(async t=>{try{let n=e(),r=process.cwd();if(t.port!==void 0){let e=il(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await vl({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}let i=t.bundleProxy===!1?[...process.argv,`--no-bundle-proxy`]:process.argv,a=Ss(process.env,i,process.platform);if(a.proxy){let e=xs(process.platform,pn(),{existsSync:P});if(e===null)Cs({stderr:process.stderr,mode:`fallback-absent`,bundlePath:null,reason:`no installed Open Knowledge.app bundle found`});else try{await ws({bundlePath:e,argv:process.argv.slice(2),env:process.env,stderr:process.stderr});return}catch(t){Cs({stderr:process.stderr,mode:`fallback-exec-failed`,bundlePath:e,reason:t instanceof Error?t.message:String(t)})}}else{let e=a.suppressedBy===`env`?`suppressed-env`:a.suppressedBy===`flag`?`suppressed-flag`:a.suppressedBy===`self`?`suppressed-self`:`suppressed-platform`;Cs({stderr:process.stderr,mode:e,bundlePath:null,reason:null})}await El({startupCwd:r,startupConfig:n})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function Ol(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function kl(e=()=>Vt(zt())){return{detectBundlePath:()=>e().bundlePath??null,resolveBaseUrl:e=>he({lockDir:Ce(e)}).baseUrl,openTarget:e=>{M(`open`,[e],{detached:!0,stdio:`ignore`,env:Ol(process.env)}).unref()},log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function Al(e,t,n){let r=B(t.project??process.cwd()),i=t.folder===!0||/\/+$/.test(e),a=e.replace(/\/+$/,``);if(!a)return n.error("Nothing to open: pass a doc path (e.g. `ok open specs/foo/SPEC`)."),1;if(a.startsWith(`/`)||a.includes(`\\`)||a.split(`/`).includes(`..`))return n.error(`Invalid name "${a}": must be a relative path with no '..' segments, leading '/', or backslashes.`),1;if(i){let e=n.resolveBaseUrl(r);if(!e)return n.error(`No Open Knowledge UI is running for ${r}. Folder preview requires a running UI — start one with \`ok ui\`, then retry.`),1;let t=`${e}/#/${Be(a)}`;return n.openTarget(t),n.log(`Opening folder ${a} in your browser: ${t}`),0}if(n.detectBundlePath()){let e=`openknowledge://open?project=${encodeURIComponent(r)}&doc=${encodeURIComponent(a)}`;return n.openTarget(e),n.log(`Opening ${a} in the Open Knowledge desktop app.`),0}let o=n.resolveBaseUrl(r);if(o){let e=`${o}/#/${Re(a)}`;return n.openTarget(e),n.log(`Opening ${a} in your browser: ${e}`),0}return n.error("No Open Knowledge desktop app found and no UI is running. Install OK Desktop, or start a UI with `ok ui`, then retry."),1}function jl(){return new t(`open`).description(`Open a doc in the OK Desktop app (folders open in the browser)`).argument(`<doc>`,`Extension-less doc path (e.g. specs/foo/SPEC), or a folder path with --folder`).option(`--folder`,`Treat <doc> as a folder and open the folder route in the browser`).option(`--project <dir>`,`Project root (defaults to the current directory)`).action((e,t)=>{process.exitCode=Al(e,t,kl())})}function Ml(e){return new t(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-CpSuy3Ei.mjs`),r=e(),i=process.cwd(),a=ae(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function Z(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Nl(e,t,n=process.cwd()){let r=e.op??`sync`,i=m(Ce(n));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,...C({kind:`cli`,runtimeVersion:_})},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.title??e.error??e.message??`Server responded with ${n.status}`)}Z(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)\n`);let a=re({baseDir:n});if(r===`sync`||r===`pull`){Z(e.json,{type:`step`,step:`pull`});let t=await a.pull();Z(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Z(e.json,{type:`step`,step:`push`}),await a.push(),Z(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
73
+ `),C()}),process.stdin.on(`error`,e=>{t.write(`[mcp] stdin error (${e instanceof Error?e.message:String(e)}) — host disconnected, shutting down\n`),C()}),b=Ns({getPpid:()=>process.ppid,onHostGone:e=>{t.write(`[mcp] ${e} — shutting down\n`),C()}}),Ps({log:e=>t.write(`${e}\n`),transport:g,process,stdin:process.stdin}),process.platform===`darwin`){let e=Ms(yl,{realpathSync:tn,statInoSync:e=>rn(e).ino,log:e=>t.write(`${e}\n`)});if(e!==void 0){t.write(`[mcp] bundle identity anchor=${e.resolvedPath} inode=${e.inode} version=${_}\n`);let{resolvedPath:n,inode:r}=e;y=js({detect:()=>As({bundleAnchorPath:yl,currentInode:r,platform:process.platform,realpath:tn,statInode:e=>rn(e).ino}),onReplaced:e=>{t.write(`[mcp] bundle replaced anchor=${n} bootInode=${e.currentInode} onDiskInode=${e.onDiskInode} version=${_} — exiting for host respawn\n`),C()},log:e=>t.write(`[mcp] ${e}\n`)})}}return{close:x}}function Dl(e){return new t(`mcp`).description(`Start MCP stdio server for project knowledge base`).option(`-p, --port <port>`,`Override per-call routing and proxy stdio to this HTTP MCP port (skips bundle proxy)`,void 0).option(`--no-bundle-proxy`,`Run the npm-fetched MCP server in-process instead of proxying to the macOS Desktop bundle (equivalent: OK_BUNDLE_PROXY=0)`).action(async t=>{try{let n=e(),r=process.cwd();if(t.port!==void 0){let e=il(process.env.OK_MCP_SPAWN_TIMEOUT_MS);await vl({lockDir:``,contentDir:``,portOverride:t.port,envAutoStart:process.env.OK_MCP_AUTOSTART,timeoutMs:e});return}let i=t.bundleProxy===!1?[...process.argv,`--no-bundle-proxy`]:process.argv,a=Ss(process.env,i,process.platform);if(a.proxy){let e=xs(process.platform,pn(),{existsSync:P});if(e===null)Cs({stderr:process.stderr,mode:`fallback-absent`,bundlePath:null,reason:`no installed Open Knowledge.app bundle found`});else try{await ws({bundlePath:e,argv:process.argv.slice(2),env:process.env,stderr:process.stderr});return}catch(t){Cs({stderr:process.stderr,mode:`fallback-exec-failed`,bundlePath:e,reason:t instanceof Error?t.message:String(t)})}}else{let e=a.suppressedBy===`env`?`suppressed-env`:a.suppressedBy===`flag`?`suppressed-flag`:a.suppressedBy===`self`?`suppressed-self`:`suppressed-platform`;Cs({stderr:process.stderr,mode:e,bundlePath:null,reason:null})}await El({startupCwd:r,startupConfig:n})}catch(e){process.stderr.write(`MCP server failed to start: ${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1}})}function Ol(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function kl(e=()=>Vt(zt())){return{detectBundlePath:()=>e().bundlePath??null,resolveBaseUrl:e=>he({lockDir:Ce(e)}).baseUrl,openTarget:e=>{M(`open`,[e],{detached:!0,stdio:`ignore`,env:Ol(process.env)}).unref()},log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}function Al(e,t,n){let r=B(t.project??process.cwd()),i=t.folder===!0||/\/+$/.test(e),a=e.replace(/\/+$/,``);if(!a)return n.error("Nothing to open: pass a doc path (e.g. `ok open specs/foo/SPEC`)."),1;if(a.startsWith(`/`)||a.includes(`\\`)||a.split(`/`).includes(`..`))return n.error(`Invalid name "${a}": must be a relative path with no '..' segments, leading '/', or backslashes.`),1;if(i){let e=n.resolveBaseUrl(r);if(!e)return n.error(`No Open Knowledge UI is running for ${r}. Folder preview requires a running UI — start one with \`ok ui\`, then retry.`),1;let t=`${e}/#/${Be(a)}`;return n.openTarget(t),n.log(`Opening folder ${a} in your browser: ${t}`),0}if(n.detectBundlePath()){let e=`openknowledge://open?project=${encodeURIComponent(r)}&doc=${encodeURIComponent(a)}`;return n.openTarget(e),n.log(`Opening ${a} in the Open Knowledge desktop app.`),0}let o=n.resolveBaseUrl(r);if(o){let e=`${o}/#/${Re(a)}`;return n.openTarget(e),n.log(`Opening ${a} in your browser: ${e}`),0}return n.error("No Open Knowledge desktop app found and no UI is running. Install OK Desktop, or start a UI with `ok ui`, then retry."),1}function jl(){return new t(`open`).description(`Open a doc in the OK Desktop app (folders open in the browser)`).argument(`<doc>`,`Extension-less doc path (e.g. specs/foo/SPEC), or a folder path with --folder`).option(`--folder`,`Treat <doc> as a folder and open the folder route in the browser`).option(`--project <dir>`,`Project root (defaults to the current directory)`).action((e,t)=>{process.exitCode=Al(e,t,kl())})}function Ml(e){return new t(`preview`).description(`Show what content the watcher will track (read-only)`).action(async()=>{let{previewContent:t,formatPreviewBlock:n}=await import(`./preview-BSIRt3Gp.mjs`),r=e(),i=process.cwd(),a=ae(r,i),o;try{o=t({projectDir:i,contentDir:a})}catch(e){console.error(`Content preview failed: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1;return}process.stdout.write(`${n(o,i)}\n`),o.totalCount===0&&o.warnings.length>0&&(process.exitCode=1)})}function Z(e,t){e&&process.stdout.write(`${JSON.stringify(t)}\n`)}async function Nl(e,t,n=process.cwd()){let r=e.op??`sync`,i=m(Ce(n));if(i&&i.port>0){let t=`http://127.0.0.1:${i.port}/api/sync/trigger`;e.json||process.stderr.write(`Triggering ${r} via running server (port ${i.port})\n`);try{let n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,...C({kind:`cli`,runtimeVersion:_})},body:JSON.stringify({op:r})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.title??e.error??e.message??`Server responded with ${n.status}`)}Z(e.json,{type:`triggered`,op:r,port:i.port}),e.json||process.stderr.write(`✓ ${r} triggered\n`);return}catch(t){let n=t instanceof Error?t.message:String(t);e.json||process.stderr.write(`Server trigger failed (${n}), running directly\n`)}}e.json||process.stderr.write(`Running ${r} directly (no live server)\n`);let a=re({baseDir:n});if(r===`sync`||r===`pull`){Z(e.json,{type:`step`,step:`pull`});let t=await a.pull();Z(e.json,{type:`pull`,summary:t.summary}),e.json||process.stderr.write(` pull: ${t.summary.changes} changes\n`)}(r===`sync`||r===`push`)&&(Z(e.json,{type:`step`,step:`push`}),await a.push(),Z(e.json,{type:`push`,ok:!0}),e.json||process.stderr.write(` push: ok
74
74
  `)),Z(e.json,{type:`complete`,op:r}),e.json||process.stderr.write(`✓ ${r} complete\n`)}function Pl(e){return new t(`sync`).description(`Commit, pull, and push to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Nl({json:t.json,op:`sync`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ sync failed: ${n}\n`),process.exit(1)}})}function Fl(e){return new t(`pull`).description(`Pull changes from the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Nl({json:t.json,op:`pull`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ pull failed: ${n}\n`),process.exit(1)}})}function Il(e){return new t(`push`).description(`Push commits to the remote`).option(`--json`,`Output JSONL progress events`,!1).action(async t=>{try{await Nl({json:t.json,op:`push`},e())}catch(e){let n=e instanceof Error?e.message:String(e);t.json?process.stdout.write(`${JSON.stringify({type:`error`,message:n})}\n`):process.stderr.write(`✗ push failed: ${n}\n`),process.exit(1)}})}function Ll(e){return typeof e==`string`&&ye.includes(e)}async function Rl(e={}){let t=B(e.cwd??process.cwd()),n=e.pack??`knowledge-base`;if(!Oe[n])return{status:`failed`,message:`${k(`Error:`)} Unknown pack "${n}". Available: ${ye.join(`, `)}`,exitCode:1};let r;try{r=await tt({projectDir:t,rootDir:e.root,packId:n})}catch(e){return e instanceof Ye?{status:`prerequisite-missing`,message:`${k(`Error:`)} ${e.message}`,exitCode:1}:{status:`failed`,message:`${k(`Error:`)} ${e instanceof Error?e.message:String(e)}`,exitCode:1}}if(r.created.length===0){let e=Oe[n].name;return{status:`no-op`,message:`${O(`Your ${e} pack is already seeded.`)}\n${D(`Nothing to do.`)}`,plan:r,exitCode:0}}if(e.dryRun)return{status:`dry-run`,message:`${j(`Plan (dry-run — no changes made):`)}\n\n${Bl(r,t)}`,plan:r,exitCode:0};if(!e.yes&&!await Vl(`${j(`Plan:`)}\n\n${Bl(r,t)}\n\n${j(`Apply?`)} ${D(`[Y/n] `)}`,e.confirmStream))return{status:`cancelled`,message:D(`Cancelled.`),plan:r,exitCode:0};let i=await He(r,{projectDir:t,packId:n});if(i.errors.length>0){let e=i.errors.map(e=>` ${k(`✗`)} ${e.path}: ${e.error}`);return{status:`failed`,message:[`${A(`Applied`)} ${i.applied} entries, ${A(String(i.errors.length))} error(s):`,...e].join(`
75
75
  `),plan:r,exitCode:1}}let a=Oe[n].name,o=i.packSkillsInstalled.length>0?`\n${D(`Installed the ${a} skill for: ${i.packSkillsInstalled.join(`, `)}`)}`:``;return{status:`applied`,message:`${O(`✓ Seeded ${a}`)} ${D(`(${i.applied} entries, ${i.durationMs}ms)`)}${o}`,plan:r,exitCode:0}}function zl(){let e=[j(`Available packs:`)];for(let t of ye){let n=Oe[t];e.push(` ${O(t)} ${D(`—`)} ${n.name}: ${n.description}`)}return e.join(`
76
76
  `)}function Bl(e,t){let n=[],r=e.created.filter(e=>e.kind===`folder`),i=e.created.filter(e=>e.kind===`file`);if(r.length>0){n.push(j(`Folders to create:`));for(let e of r)n.push(` ${O(`+`)} ${E(cn(t,B(t,e.path))||e.path)}${D(`/`)}`)}if(i.length>0){n.length>0&&n.push(``),n.push(j(`Files to create:`));for(let e of i)n.push(` ${O(`+`)} ${E(cn(t,B(t,e.path))||e.path)}`)}if(e.skipped.length>0){n.length>0&&n.push(``),n.push(D(`Already present (skipped):`));for(let t of e.skipped)n.push(` ${D(`· ${t.path} (${t.reason})`)}`)}if(e.warnings.length>0){n.length>0&&n.push(``),n.push(A(`Warnings:`));for(let t of e.warnings)n.push(` ${A(`!`)} ${t}`)}return n.join(`
@@ -79,7 +79,7 @@ project → Search (a toggle with an egress-confirmation prompt), or run
79
79
  `);return}if(a){process.stdout.write(`${JSON.stringify({type:`error`,code:c.kind})}\n`);return}process.stderr.write(`✗ share name-check failed: ${c.kind}\n`),process.exit(1)}function Gl(e){return new t(`name-check`).description(`Check if owner/name is available on GitHub`).requiredOption(`--owner <owner>`,`GitHub owner (user or org)`).requiredOption(`--name <name>`,`Repository name`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await Wl(t,await e())})}async function Kl(e){try{let t=[],n=await e.users.getAuthenticated();t.push({login:n.data.login,kind:`user`,avatarUrl:n.data.avatar_url});for await(let n of e.paginate.iterator(e.orgs.listMembershipsForAuthenticatedUser,{state:`active`,per_page:100}))for(let e of n.data)(e.permissions?.can_create_repository===!0||e.role===`admin`)&&t.push({login:e.organization.login,kind:`org`,avatarUrl:e.organization.avatar_url??void 0});return{kind:`ok`,owners:t}}catch(e){return e.status===401?{kind:`auth-required`}:{kind:`network`}}}async function ql(e,t){let{host:n,json:r}=e;H(n);let i=await Pi(n,t);if(i==null){if(r){process.stdout.write(`${JSON.stringify({type:`error`,code:`auth-required`})}\n`);return}process.stderr.write(`Not logged in to ${n}\n`),process.exit(1)}let a=n===`github.com`?void 0:`https://${n}/api/v3`,o=await Kl(new K({auth:i,...a?{baseUrl:a}:{}}));if(o.kind===`ok`){if(r)process.stdout.write(`${JSON.stringify({type:`owners`,owners:o.owners})}\n`);else for(let e of o.owners)process.stdout.write(`${e.kind}\t${e.login}\n`);return}if(r){process.stdout.write(`${JSON.stringify({type:`error`,code:o.kind})}\n`);return}process.stderr.write(`✗ share owners failed: ${o.kind}\n`),process.exit(1)}function Jl(e){return new t(`owners`).description(`List GitHub owners eligible to host a new repository`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{await ql(t,await e())})}function Yl(e){let t=e,n=t.status,r=t.response?.data,i=t.response?.headers,a=`${r?.message??r?.errors?.map(e=>e.message??``).join(`
80
80
  `)??``}\n${t.message??``}`.toLowerCase();return n===401?`auth-required`:n===403?i?.[`x-github-sso`]||a.includes(`saml`)||a.includes(`sso`)?`saml-sso`:`network`:n===422&&(r?.errors?.some(e=>e.field===`name`)||a.includes(`already exists`)||a.includes(`name already exists`))?`name-conflict`:`network`}async function Xl(e){let{octokit:t,ownerLogin:n,ownerKind:r,name:i,visibility:a,description:o}=e,s=a===`private`;if(r===`user`){let{data:e}=await t.repos.createForAuthenticatedUser({name:i,private:s,...o?{description:o}:{}});return{cloneUrl:e.clone_url,defaultBranch:e.default_branch??`main`}}let{data:c}=await t.repos.createInOrg({org:n,name:i,visibility:a,...o?{description:o}:{}});return{cloneUrl:c.clone_url,defaultBranch:c.default_branch??`main`}}async function Zl(e,t,n){try{let{data:r}=await e.repos.get({owner:t,repo:n});return{cloneUrl:r.clone_url,defaultBranch:r.default_branch??`main`}}catch{return null}}async function Ql(e,t){return(await e.users.getAuthenticated()).data.login.toLowerCase()===t.toLowerCase()?`user`:`org`}function $l(e){return re({baseDir:e,unsafe:{allowUnsafeCredentialHelper:!0}}).env({GIT_TERMINAL_PROMPT:`0`})}function eu(e,t){if(!e.startsWith(`https://`))return e;try{if(new URL(e).hostname!==`github.com`)return e}catch{return e}return e.replace(`https://`,`https://x-access-token:${t}@`)}const tu={ensureOkScaffold:e=>{xe(e)},gitFactory:$l};async function nu(e){let t={...tu,...e.deps},n=B(e.projectDir),r;if(e.ownerKind)r=e.ownerKind;else try{r=await Ql(e.octokit,e.body.owner)}catch(e){return{kind:`error`,code:Yl(e)}}try{t.ensureOkScaffold(n)}catch{return{kind:`error`,code:`init-failed`}}let i=t.gitFactory(n);if(!P(z(n,`.git`)))try{await i.init()}catch{return{kind:`error`,code:`init-failed`}}let a;try{a=await Xl({octokit:e.octokit,ownerLogin:e.body.owner,ownerKind:r,name:e.body.name,visibility:e.body.visibility,description:e.body.description})}catch(t){if(Yl(t)===`name-conflict`){let t=await Zl(e.octokit,e.body.owner,e.body.name);if(t===null)return{kind:`error`,code:`name-conflict`};a=t}else return{kind:`error`,code:Yl(t)}}try{await i.addRemote(`origin`,a.cloneUrl)}catch(e){if(!String(e.message??``).toLowerCase().includes(`remote origin already exists`))return{kind:`error`,code:`push-failed`}}let o=!1;try{await i.raw([`rev-parse`,`--verify`,`HEAD`])}catch{o=!0}if(o)try{await i.add(`.`),await i.raw([`commit`,`--allow-empty`,`-m`,`Initial commit`])}catch{return{kind:`error`,code:`init-failed`}}let s=eu(a.cloneUrl,e.token);try{await i.raw([`push`,s,`HEAD:refs/heads/${a.defaultBranch}`])}catch(e){let t=String(e.message??``).toLowerCase();return t.includes(`saml`)||t.includes(`sso`)?{kind:`error`,code:`saml-sso`}:{kind:`error`,code:`push-failed`}}try{await i.raw([`update-ref`,`refs/remotes/origin/${a.defaultBranch}`,`HEAD`])}catch{}return{kind:`ok`,value:{ownerLogin:e.body.owner,repoName:e.body.name,cloneUrl:a.cloneUrl,defaultBranch:a.defaultBranch}}}function ru(e,t){if(!e){t.kind===`ok`?process.stdout.write(`✓ Published ${t.value.cloneUrl}\n`):(process.stderr.write(`✗ share publish failed: ${t.code}\n`),process.exit(1));return}if(t.kind===`ok`){process.stdout.write(`${JSON.stringify({type:`publish`,...t.value})}\n`);return}process.stdout.write(`${JSON.stringify({type:`error`,code:t.code})}\n`)}async function iu(e,t){let{host:n,owner:r,name:i,visibility:a,description:o,projectDir:s,json:c}=e;H(n);let l=await Pi(n,t);if(l==null){ru(c,{kind:`error`,code:`auth-required`});return}let u=n===`github.com`?void 0:`https://${n}/api/v3`,d=new K({auth:l,...u?{baseUrl:u}:{}});try{Kt(`git config user.email`,{cwd:s,stdio:`ignore`})}catch{process.env.GIT_AUTHOR_NAME??=`Open Knowledge`,process.env.GIT_AUTHOR_EMAIL??=`noreply@inkeep.com`,process.env.GIT_COMMITTER_NAME??=`Open Knowledge`,process.env.GIT_COMMITTER_EMAIL??=`noreply@inkeep.com`}ru(c,await nu({octokit:d,token:l,projectDir:s,body:{owner:r,name:i,visibility:a,description:o}}))}function au(e){return new t(`publish`).description(`Publish a no-remote project to GitHub`).requiredOption(`--owner <owner>`,`GitHub owner (user or org)`).requiredOption(`--name <name>`,`Repository name`).requiredOption(`--visibility <visibility>`,`public or private`).option(`--description <description>`,`Repository description`).requiredOption(`--project-dir <projectDir>`,`Path to the project on disk`).option(`--host <host>`,`GitHub or GitHub Enterprise hostname`,`github.com`).option(`--json`,`Output JSON`,!1).action(async t=>{t.visibility!==`public`&&t.visibility!==`private`&&(process.stderr.write(`✗ visibility must be 'public' or 'private'
81
81
  `),process.exit(1)),await iu(t,await e())})}function ou(){let e=new t(`share`);e.description(`Sharing flow operations (owners, name-check, publish)`);let n=()=>te();return e.addCommand(Jl(n)),e.addCommand(Gl(n)),e.addCommand(au(n)),e}function su(){return new t(`share`).description(`Switch this project to shared mode (commit OK config alongside content)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.project??process.cwd()),n=_t(t),r=st(t,ot(t));if(r.kind===`no-exclude`){cu(e.json,t,r.reason);return}let i=_t(t);if(e.json){let e={type:`sharing-share`,projectRoot:t,mode:i,removed:r.removed};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n===`shared`){process.stderr.write(`${E(`Sharing mode is already`)} ${j(`shared`)} ${E(`— nothing to do.`)}\n`);return}process.stderr.write(`${O(`✓`)} ${j(`Sharing mode set to`)} ${O(`shared`)}\n`),process.stderr.write(` Removed OK paths from ${j(`.git/info/exclude`)}; commit the files to share with teammates.\n`)})}function cu(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-share`,projectRoot:t,mode:`no-git`,removed:[],reason:n})}\n`);return}process.stderr.write(`${A({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function lu(){return new t(`status`).description(`Print the current sharing mode and the OK paths in .git/info/exclude`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.project??process.cwd()),n=_t(t),r=[...gt(t)],i=St(t,ot(t)).tracked;if(e.json){let e={type:`sharing-status`,projectRoot:t,mode:n,excluded:r,trackedUpstream:i};process.stdout.write(`${JSON.stringify(e)}\n`);return}let a=[];if(a.push(`Open Knowledge sharing mode: ${uu(n)}`),a.push(``),a.push(`Excluded from git via ${j(`.git/info/exclude`)}:`),r.length===0)a.push(` (none)`);else for(let e of r)a.push(` ${e}`);if(a.push(``),a.push(`Other OK paths exist but are tracked upstream:`),i.length===0)a.push(` (none)`);else for(let e of i)a.push(` ${e}`);a.push(``),a.push(`Toggle with: ${E(n===`local-only`?`ok config-sharing share`:`ok config-sharing unshare`)}`),process.stdout.write(`${a.join(`
82
- `)}\n`)})}function uu(e){switch(e){case`shared`:return O(`shared`);case`local-only`:return O(`local-only`);case`no-git`:return A(`no-git (not a git repository)`)}}function du(){return new t(`unshare`).description(`Switch this project to local-only mode (add OK artifacts to .git/info/exclude so they stay out of git)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.project??process.cwd()),n=yt(t,ot(t));if(n.kind===`refused-tracked`){if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:`refused-tracked`,tracked:n.tracked,remediation:n.remediation};process.stdout.write(`${JSON.stringify(e)}\n`)}else process.stderr.write(`${n.remediation}\n`);process.exitCode=1;return}if(n.kind===`no-exclude`){fu(e.json,t,n.reason);return}let r=_t(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:r,appended:n.appended,alreadyPresent:n.alreadyPresent};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n.appended.length===0){process.stderr.write(`${j(`Sharing mode is already`)} ${O(`local-only`)} ${j(`— nothing to do.`)}\n`);return}process.stderr.write(`${O(`✓`)} ${j(`Sharing mode set to`)} ${O(`local-only`)}\n`),process.stderr.write(` Added ${n.appended.length} path(s) to ${j(`.git/info/exclude`)} (per-clone, not committed).\n`)})}function fu(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-unshare`,projectRoot:t,mode:`no-git`,appended:[],alreadyPresent:[],reason:n})}\n`);return}process.stderr.write(`${A({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function pu(){let e=new t(`config-sharing`);return e.description(`Manage Open Knowledge's git-sharing mode (share OK config with the team, or keep local-only on this machine)`),e.addCommand(su()),e.addCommand(du()),e.addCommand(lu()),e}const mu=new Set([`--cwd`,`--log-level`]);function hu(e){let t=[],n=null,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`--help`||a===`-h`||a===`--version`||a===`-V`){r=!0;break}if(a===`--cwd`||a===`--log-level`){a===`--cwd`&&(n=e[i+1]??null),i++;continue}if(a.startsWith(`--cwd=`)){n=a.slice(6);continue}if(!a.startsWith(`--log-level=`)&&!(a===`--no-color`||a===`--color`)){if(a.startsWith(`-`)){mu.has(a)&&i++;continue}t.push(a)}}return{operands:t,cwd:n,sawTerminalFlag:r}}function gu(e,t){if(e.length===0)return null;let n=e[0];return n===`open`&&e[1]!==void 0&&t.isFileish(e[1])?e[1]:t.knownSubcommands.has(n)?null:t.isFileish(n)?n:null}function _u(e){return/\.(md|mdx)$/i.test(e)}function vu(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function yu(e=()=>Vt(zt())){return{prepare:Ie,detectBundlePath:()=>e().bundlePath??null,openTarget:e=>{M(`open`,[e],{detached:!0,stdio:`ignore`,env:vu(process.env)}).unref()},runProjectOpen:(e,t)=>Al(e,{project:t},kl()),runBrowserOpen:e=>Su(e),log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}async function bu(e,t){let n;try{n=t.prepare(e)}catch(e){if(e instanceof Ve||e instanceof qe||e instanceof Pe)return t.error(e.message),1;throw e}if(n.mode===`project`)return t.runProjectOpen(n.docName,n.projectRoot);if(t.detectBundlePath()){let e=`openknowledge://open?file=${encodeURIComponent(n.canonicalFilePath)}`;return t.openTarget(e),t.log(`Opening ${n.singleDocRelPath} in the Open Knowledge desktop app.`),0}return await t.runBrowserOpen(n),0}function xu(){let e=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[B(e,`public`),B(e,`../../app/dist`),B(e,`../../../app/dist`)].find(e=>P(e))}async function Su(e){let{createEphemeralProjectDir:t}=await import(`./dist-BXU3sfTZ.mjs`),{loadConfig:n}=await import(`./index.mjs`),{bootStartServer:r,resolveHost:i}=await import(`./start-BnH1uaVq.mjs`),{openBrowser:a}=await import(`./open-browser-DHTbHSqx.mjs`),o=xu();o||(process.stderr.write("Open Knowledge UI assets were not found. Reinstall @inkeep/open-knowledge, or build the app (`bun run build`) in a monorepo checkout.\n"),process.exit(1));let s=t(e.contentDir),c=!1,l,u=async()=>{if(!c){c=!0;try{await l?.destroy()}catch{}try{await xn(s,{recursive:!0,force:!0})}catch{}}},d=()=>{u().then(()=>process.exit(0))};process.once(`SIGINT`,d),process.once(`SIGTERM`,d);let{config:f}=n(s),p=i({},process.env);try{l=await r({config:f,cwd:s,host:p,port:0,projectDir:s,singleFile:e.canonicalFilePath,serveContentAssets:!0,reactShellDistDir:o})}catch(t){await u(),process.stderr.write(`Failed to open ${e.singleDocRelPath}: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}let m=`http://${p}:${l.port}/#/${Re(e.docName)}`;process.stdout.write(`Opening ${e.singleDocRelPath} in your browser: ${m}\n`),process.stdout.write(`Press Ctrl-C to close the session.
82
+ `)}\n`)})}function uu(e){switch(e){case`shared`:return O(`shared`);case`local-only`:return O(`local-only`);case`no-git`:return A(`no-git (not a git repository)`)}}function du(){return new t(`unshare`).description(`Switch this project to local-only mode (add OK artifacts to .git/info/exclude so they stay out of git)`).option(`--project <dir>`,`Project root (defaults to cwd)`).option(`--json`,`Output JSON`,!1).action(async e=>{let t=B(e.project??process.cwd()),n=yt(t,ot(t));if(n.kind===`refused-tracked`){if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:`refused-tracked`,tracked:n.tracked,remediation:n.remediation};process.stdout.write(`${JSON.stringify(e)}\n`)}else process.stderr.write(`${n.remediation}\n`);process.exitCode=1;return}if(n.kind===`no-exclude`){fu(e.json,t,n.reason);return}let r=_t(t);if(e.json){let e={type:`sharing-unshare`,projectRoot:t,mode:r,appended:n.appended,alreadyPresent:n.alreadyPresent};process.stdout.write(`${JSON.stringify(e)}\n`);return}if(n.appended.length===0){process.stderr.write(`${j(`Sharing mode is already`)} ${O(`local-only`)} ${j(`— nothing to do.`)}\n`);return}process.stderr.write(`${O(`✓`)} ${j(`Sharing mode set to`)} ${O(`local-only`)}\n`),process.stderr.write(` Added ${n.appended.length} path(s) to ${j(`.git/info/exclude`)} (per-clone, not committed).\n`)})}function fu(e,t,n){if(e){process.stdout.write(`${JSON.stringify({type:`sharing-unshare`,projectRoot:t,mode:`no-git`,appended:[],alreadyPresent:[],reason:n})}\n`);return}process.stderr.write(`${A({"no-git":`No git repository here — sharing mode does not apply.`,"no-info-dir":`The gitdir's info/ folder is absent; cannot toggle sharing mode.`,"malformed-pointer":"The .git pointer file is malformed (stale worktree). Run `git worktree prune` and try again.",inaccessible:`The .git path is inaccessible (permissions or mount issue).`}[n])}\n`)}function pu(){let e=new t(`config-sharing`);return e.description(`Manage Open Knowledge's git-sharing mode (share OK config with the team, or keep local-only on this machine)`),e.addCommand(su()),e.addCommand(du()),e.addCommand(lu()),e}const mu=new Set([`--cwd`,`--log-level`]);function hu(e){let t=[],n=null,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`--help`||a===`-h`||a===`--version`||a===`-V`){r=!0;break}if(a===`--cwd`||a===`--log-level`){a===`--cwd`&&(n=e[i+1]??null),i++;continue}if(a.startsWith(`--cwd=`)){n=a.slice(6);continue}if(!a.startsWith(`--log-level=`)&&!(a===`--no-color`||a===`--color`)){if(a.startsWith(`-`)){mu.has(a)&&i++;continue}t.push(a)}}return{operands:t,cwd:n,sawTerminalFlag:r}}function gu(e,t){if(e.length===0)return null;let n=e[0];return n===`open`&&e[1]!==void 0&&t.isFileish(e[1])?e[1]:t.knownSubcommands.has(n)?null:t.isFileish(n)?n:null}function _u(e){return/\.(md|mdx)$/i.test(e)}function vu(e){let t={...e};return delete t.ELECTRON_RUN_AS_NODE,t}function yu(e=()=>Vt(zt())){return{prepare:Ie,detectBundlePath:()=>e().bundlePath??null,openTarget:e=>{M(`open`,[e],{detached:!0,stdio:`ignore`,env:vu(process.env)}).unref()},runProjectOpen:(e,t)=>Al(e,{project:t},kl()),runBrowserOpen:e=>Su(e),log:e=>process.stdout.write(`${e}\n`),error:e=>process.stderr.write(`${e}\n`)}}async function bu(e,t){let n;try{n=t.prepare(e)}catch(e){if(e instanceof Ve||e instanceof qe||e instanceof Pe)return t.error(e.message),1;throw e}if(n.mode===`project`)return t.runProjectOpen(n.docName,n.projectRoot);if(t.detectBundlePath()){let e=`openknowledge://open?file=${encodeURIComponent(n.canonicalFilePath)}`;return t.openTarget(e),t.log(`Opening ${n.singleDocRelPath} in the Open Knowledge desktop app.`),0}return await t.runBrowserOpen(n),0}function xu(){let e=import.meta.dirname??new URL(`.`,import.meta.url).pathname;return[B(e,`public`),B(e,`../../app/dist`),B(e,`../../../app/dist`)].find(e=>P(e))}async function Su(e){let{createEphemeralProjectDir:t}=await import(`./dist-De0GFsdh.mjs`),{loadConfig:n}=await import(`./index.mjs`),{bootStartServer:r,resolveHost:i}=await import(`./start-DujEO1M-.mjs`),{openBrowser:a}=await import(`./open-browser-DHTbHSqx.mjs`),o=xu();o||(process.stderr.write("Open Knowledge UI assets were not found. Reinstall @inkeep/open-knowledge, or build the app (`bun run build`) in a monorepo checkout.\n"),process.exit(1));let s=t(e.contentDir),c=!1,l,u=async()=>{if(!c){c=!0;try{await l?.destroy()}catch{}try{await xn(s,{recursive:!0,force:!0})}catch{}}},d=()=>{u().then(()=>process.exit(0))};process.once(`SIGINT`,d),process.once(`SIGTERM`,d);let{config:f}=n(s),p=i({},process.env);try{l=await r({config:f,cwd:s,host:p,port:0,projectDir:s,singleFile:e.canonicalFilePath,serveContentAssets:!0,reactShellDistDir:o})}catch(t){await u(),process.stderr.write(`Failed to open ${e.singleDocRelPath}: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}let m=`http://${p}:${l.port}/#/${Re(e.docName)}`;process.stdout.write(`Opening ${e.singleDocRelPath} in your browser: ${m}\n`),process.stdout.write(`Press Ctrl-C to close the session.
83
83
  `),a(m),await new Promise(()=>{})}function Cu(e,t){return{server:wu(`server`,e),ui:wu(`ui`,t)}}function wu(e,t){switch(t.status){case`missing`:return{name:e,state:`missing`,alive:!1};case`corrupt`:return{name:e,state:`corrupt`,alive:!1};case`foreign-host`:return{name:e,state:`foreign-host`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:`unknown`};case`dead-pid`:return{name:e,state:`dead-pid`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!1};case`alive`:return{name:e,state:`alive`,pid:t.lock.pid,port:t.lock.port,startedAt:t.lock.startedAt,host:t.lock.hostname,alive:!0}}}function Tu(e){return`${Eu(e.server)}\n${Eu(e.ui)}`}function Eu(e){let t=e.name===`server`?`server`:`ui `;return e.state===`missing`?`${t} not running`:e.state===`corrupt`?`${t} lock file corrupt — run \`ok clean\``:e.state===`foreign-host`?`${t} foreign host (${e.host}) pid=${e.pid} port=${e.port}`:e.state===`dead-pid`?`${t} stale (dead pid=${e.pid}) — run \`ok clean\``:`${t} alive pid=${e.pid} port=${e.port} started=${e.startedAt}`}function Du(e){let t=e.inspect??(t=>Et(e.lockDir,t)),n=e.log??(e=>console.log(e)),r=Cu(t(`server`),t(`ui`));return e.json?n(JSON.stringify(r,null,2)):n(Tu(r)),r}function Ou(e){return new t(`status`).description(`Show live state of the server + ui lockfiles for this project`).option(`--json`,`Emit structured JSON instead of formatted text`).action(t=>{e(),Du({lockDir:Ce(process.cwd()),json:t.json===!0})})}function ku(e){return[e,`Copyright (C) 2026 Inkeep, Inc.`,`License GPL-3.0-or-later: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.`,`This is free software: you are free to change and redistribute it.`,`There is NO WARRANTY, to the extent permitted by law.`].join(`
84
84
  `)}process.argv.includes(`--no-color`)?(process.env.NO_COLOR=`1`,delete process.env.FORCE_COLOR):process.argv.includes(`--color`)&&(process.env.FORCE_COLOR=`1`,delete process.env.NO_COLOR);const Q=new t;let $,Au;function ju(){return Au}Q.name(`open-knowledge`).description(`Local-first knowledge base with CRDT collaboration`).usage(`[options] [file | command]`).version(ku(Nt)).option(`--cwd <path>`,`Working directory`).option(`--log-level <level>`,`Log level: silent, error, warn, info (default), debug, trace`,`info`).option(`--no-color`,`Disable color output`).option(`--color`,`Force color output`).hook(`preAction`,e=>{let t=e.opts().cwd;if(t!==void 0&&process.chdir(t),Q.getOptionValueSource(`logLevel`)===`cli`){let e=String(Q.opts().logLevel);process.env.LOG_LEVEL=e,process.env.OK_CONSOLE_LEVEL=e}let n=e.args?.[0],r=At(n,process.cwd());r!==null&&(wt(process.cwd()),process.chdir(r),console.error(`[ok] Using Open Knowledge project at ${r}`));let{config:i}=Ft(r??t);$=i;let a=e.args?.[0]??e.name()??`cli`;Au=ke({name:`cli`,project:i.project?.name??void 0}),Au.info({command:a,cwd:process.cwd()},`cli command started`)}),Q.action(async()=>{if(Vt(zt()).available){Lt({spawn:M});return}await Bt($,{})});const Mu=Rt(()=>$);Q.addCommand(Mu);const Nu=Dl(()=>$);Q.addCommand(Nu),Q.addCommand(bt()),Q.addCommand(Hl()),Q.addCommand(vs()),Q.addCommand(Wt());const Pu=Ml(()=>$);Q.addCommand(Pu);const Fu=xt(()=>$);Q.addCommand(Fu),Q.addCommand(jl()),Q.addCommand(Dt(()=>$)),Q.addCommand(ia(()=>$)),Q.addCommand(Ou(()=>$)),Q.addCommand(jt()),Q.addCommand(ts()),Q.addCommand(ta()),Q.addCommand(wa()),Q.addCommand(Ui(ju)),Q.addCommand(us()),Q.addCommand(ga(()=>$)),Q.addCommand(Pl(()=>$)),Q.addCommand(Il(()=>$)),Q.addCommand(Fl(()=>$)),Q.addCommand(ou()),Q.addCommand(pu()),Q.addHelpText(`after`,`
85
85
  Examples:
@@ -0,0 +1,2 @@
1
+ import"./server-lock-BpjJj3OD-Co1tfNQM.mjs";var e=`0.14.0-beta.0`;const t=`config.yml`,n=e;export{n,t};
2
+ //# sourceMappingURL=constants-acQ6Ybfl.mjs.map
@@ -2808,7 +2808,7 @@ In headless mode, write the recap into the research article's "Further reading"
2808
2808
  `),{asset:{ok:!0,...B?{src:B}:{},...H?{path:H}:{},...q?{deduped:q}:{}}})}async function handleBatch(e,t,s,g,S,w,E){let D=[];for(let w of e)D.push(await writeOneDoc(w,t,s,g,S));let O=D.map(e=>{if(!e.ok)return{docName:e.docName,ok:!1,error:e.error};let t=resolvePreviewUrl(e.docName,{lockDir:w}),s=parseAdvisoryWarnings(e.raw.warnings);return{docName:e.docName,ok:!0,position:e.position,...t?{previewUrl:t.url}:{},...s?{warnings:s}:{}}}),k=O.filter(e=>e.ok).length,j=k===O.length,F=e.map((e,t)=>{let s=D[t];if(!s?.ok)return`Failed ${e.path}: ${s?.error??`unknown error`}`;if(emptyAppendNoOpNote(s.position,e.content))return`No change to ${e.path} — empty ${s.position}, document unchanged.`;let g=O[t],S=[`Wrote ${e.path} (${s.position}).`];return g?.ok&&g.warnings&&S.push(...formatAdvisoryBriefs(g.warnings)),S.join(` `)}),L=e.flatMap((e,t)=>{let s=D[t];if(!s?.ok)return[];let g=frontmatterIgnoredNote(s.position,e.content);return[...g?[g]:[],...s.extensionNote?[s.extensionNote]:[]].map(t=>`${e.path} — ${t}`)}),B=[`${k}/${O.length} written.`,...F,...L].join(`
2809
2809
  `),H={documents:O},q=D.find(e=>e.ok);return q&&q.raw.systemSubscriberCount===0&&(H.warning=buildPreviewAttachWarning(resolvePreviewUrl(q.docName,{lockDir:w}),E)),textPlusStructured(B,H,!j)}async function handleSingleDoc(e,t,s,g,S,w,E){let D=await writeOneDoc(e,t,s,g,S);if(!D.ok)return textResult(`Error: ${D.error}`,!0);let O=D.raw,k=resolvePreviewUrl(D.docName,{lockDir:w}),j=typeof O.subscriberCount==`number`?O.subscriberCount:void 0,F=(typeof O.systemSubscriberCount==`number`?O.systemSubscriberCount:void 0)===0,L=j===0,B=Array.isArray(O.hints)?O.hints:void 0,H=O.summary&&typeof O.summary==`object`?O.summary:void 0,q=typeof H?.hint==`string`?H.hint:void 0,ee=parseAdvisoryWarnings(O.warnings),J=[emptyAppendNoOpNote(D.position,e.content)??(D.fromTemplate===void 0?`Written successfully (${D.position}).`:`Written successfully (instantiated from template "${D.fromTemplate}").`)],Y=frontmatterIgnoredNote(D.position,e.content);if(Y&&J.push(Y),D.extensionNote&&J.push(D.extensionNote),F&&!k&&J.push(START_UI_TEXT_HINT),q&&J.push(q),B)for(let e of B)e.message&&J.push(e.message);ee&&J.push(...formatAdvisoryLines(ee));let te=J.join(`
2810
2810
  `);if(!k&&!F&&!L&&!B&&!H&&!ee)return textResult(te);let ne={};return B&&(ne.hints=B),H&&(ne.summary=H),ee&&(ne.warnings=ee),textPlusStructured(te,nestDocResult(k,F?buildPreviewAttachWarning(k,E):void 0,ne))}function register(e,t){let s={path:string().describe(`Document path, no extension. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup".`),content:string().optional().describe("The full Markdown body. Mutually exclusive with `template`."),template:string().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:FrontmatterArg.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:PositionArg.optional()};e.registerTool(`write`,{description:DESCRIPTION,inputSchema:{document:object$1(s).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:object$1({path:string().describe(`Folder path. Example: "meetings".`),frontmatter:FrontmatterArg.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:object$1({path:string().describe(TEMPLATE_PATH_DESCRIBE),content:string().describe(TEMPLATE_CONTENT_DESCRIBE),frontmatter:object$1({title:string().min(1).describe(`Required — the label shown when an agent picks this template.`),description:string().optional().describe(`Optional — shown beside the title in the template menu.`),tags:array(string()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),asset:object$1({path:string().describe(`Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".`),content:string().optional().describe(`Base64 of the binary. Use for small files.`),source:string().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:array(object$1({...s,summary:summaryArgSchema})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:summaryArgSchema,cwd:string().optional().describe(ROUTED_CWD_DESCRIPTION)},outputSchema:outputSchemaWithText({document:object$1({hints:looseObjectArray.optional().describe(`Server-provided write hints, when any.`),...documentResultBaseShape}).optional().describe(`Single-document write result (present when there is a doc-specific signal).`),folder:object$1({ok:boolean(),path:string(),frontmatterError:string().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:object$1({ok:boolean(),path:string(),created:boolean().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),asset:object$1({ok:boolean(),src:string().optional().describe(`The reference src to embed in a doc.`),path:string().optional(),deduped:boolean().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:looseObjectArray.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, error? }`."),previewUrl:previewUrlOutputField.optional(),previewUrlSource:previewUrlSourceField,warning:previewAttachWarningField})},async e=>{let s=await resolveProjectServerContext(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!s.ok)return textResult(`Error: ${s.error}`,!0);let{cwd:g,config:S,url:w}=s,E=resolveLockDir(g),D=resolveContentDir(S,g),O=S.appearance.preview.autoOpen;if(e.documents!==void 0){let s=exactlyOneTargetError(e,[`document`,`folder`,`template`,`asset`,`documents`]);return s?textResult(`Error: ${s}`,!0):w?handleBatch(e.documents,g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)}let k=exactlyOneTargetError(e,[`document`,`folder`,`template`,`asset`]);return k?textResult(`Error: ${k}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?handleAsset(e.asset,g,w,t):handleTemplate(e.template,e.summary,w,t):handleFolder(e.folder,e.summary,w,t):w?handleSingleDoc({...e.document,summary:e.summary},g,D,w,t,E,O):textResult(HOCUSPOCUS_NOT_RUNNING_ERROR,!0)})}function registerAllTools(e,t){let s=t.logger,g=createLoggedServer(e,{logger:t.logger,identityRef:t.identityRef}),S=e=>async g=>{try{let S=await t.resolveCwd(g);return(getCurrentMcpLogger()??s)?.debug(`tool cwd resolved`,{tool:e,cwd:S,...g?{explicit:g}:{}}),S}catch(t){throw(getCurrentMcpLogger()??s)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...g?{explicit:g}:{}}),t}};register$11(g,{resolveCwd:S(`exec`),serverUrl:t.serverUrl,config:t.config}),register$1(g,{config:t.config,resolveCwd:S(`workflow`)}),register$3(g,{resolveCwd:S(`search`),config:t.config,serverUrl:t.serverUrl}),register$8(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`links`)}),register(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`write`),identityRef:t.identityRef}),register$12(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`edit`),identityRef:t.identityRef}),register$13(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`delete`),identityRef:t.identityRef}),register$7(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`move`),identityRef:t.identityRef}),register$9(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`history`)}),register$16(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`checkpoint`),identityRef:t.identityRef}),register$4(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`restore_version`),identityRef:t.identityRef}),register$6(g,{resolveCwd:S(`palette`),config:t.config}),register$15(g,{config:t.config,resolveCwd:S(`config`)}),register$10(g,{config:t.config,resolveCwd:S(`preview_url`),serverUrl:t.serverUrl}),register$14(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`conflicts`)}),register$5(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`resolve_conflict`)}),register$2(g,{serverUrl:t.serverUrl,config:t.config,resolveCwd:S(`share_link`)})}function firstHeader(e){return Array.isArray(e)?e[0]:e}function writePlain(e,t,s){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(s))}function createSessionServer(e,t,s){let g=e.config,S=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION},{instructions:buildInstructions(g.content)});installPrettyZodErrors(S);let w=s??randomUUID$1(),E={current:{connectionId:w,displayName:w,colorSeed:w}};S.server.oninitialized=()=>{let e=S.server.getClientVersion(),t=sanitizeClientName(e?.name,w);E.current={connectionId:w,clientInfo:e?{name:t,version:e.version}:void 0,displayName:displayNameFromClientName(t),colorSeed:t}};let D=e.projectDir??e.contentDir;return registerAllTools(S,{serverUrl:async()=>e.getServerUrl(),resolveCwd:async e=>{if(e===void 0)return D;let t=resolveWithinRoot(D,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:g,identityRef:E}),{server:S,transport:t}}function createMcpHttpHandler(e){let t=new Map,s=e.sessionTtlMs??1800*1e3,g=e.maxSessions??100;async function S(s,g){let S=t.get(s);if(!S)return;t.delete(s),S.ttlTimer!==void 0&&clearTimeout(S.ttlTimer);let w=await Promise.allSettled([S.server.close(),S.transport.close()]);for(let t of w)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:s,reason:g},`MCP HTTP session close failed`);e.log?.info?.({sessionId:s,reason:g},`MCP HTTP session closed`)}function w(t,g){g.ttlTimer!==void 0&&clearTimeout(g.ttlTimer),g.ttlTimer=setTimeout(()=>{S(t,`ttl-expired`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},s),g.ttlTimer.unref?.()}return{async handle(s,E){let D=firstHeader(s.headers[`mcp-session-id`]);if(D){let e=t.get(D);if(!e){writePlain(E,404,`MCP session not found`);return}w(D,e),await e.transport.handleRequest(s,E);return}if(s.method!==`POST`){writePlain(E,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=g){e.log?.warn?.({activeSessions:t.size,maxSessions:g},`MCP HTTP session cap reached`),writePlain(E,503,`Too many active MCP sessions`);return}let O=firstHeader(s.headers[MCP_CONNECTION_ID_HEADER]),k=validateAgentId(O)??void 0;O!==void 0&&k===void 0&&e.log?.warn?.({headerLength:O.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let j=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID$1(),enableJsonResponse:!0,onsessioninitialized:async s=>{try{let g=createSessionServer(e,j,k);await g.server.connect(j),t.set(s,g),w(s,g),e.log?.info?.({sessionId:s},`MCP HTTP session initialized`)}catch(g){throw t.delete(s),e.log?.error?.({err:g,sessionId:s},`MCP HTTP session initialization failed`),g}}});j.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},j.onclose=()=>{let t=j.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}S(t,`transport-closed`).catch(s=>{e.log?.warn?.({err:s,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await j.handleRequest(s,E)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>S(e,`handler-close`)))}}}const DEFAULT_KEEPALIVE_GRACE_MS=1e4,MAX_COLLAB_MESSAGE_BYTES=1024*1024,MCP_CORS_HEADERS={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function mountMcpAndApi(e){let{httpServer:t,hocuspocus:s,mcpHttpHandler:g,log:S,sessionManager:w,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:O,contentAssetMiddleware:k,reactShellMiddleware:j,ephemeral:F}=e,L=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,B=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});B.on(`error`,e=>{S.error({err:e},`WebSocketServer error`)});let H=new Map,q=new Set,ee=!1;return t.on(`request`,(e,t)=>{let w=e.url?.split(`?`)[0];if(g!==void 0&&w===`/mcp`){let s=e.headers.origin,w=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`mcp`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`});return}if(s!==void 0&&!isAllowedApiOrigin(s)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}s!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,s),t.setHeader(`Vary`,`Origin`));for(let[e,s]of Object.entries(MCP_CORS_HEADERS))t.setHeader(e,s);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}g.handle(e,t).catch(e=>{S.error({err:e,sessionId:w},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(w?.startsWith(`/api/`)){s.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${w}`})}).catch(e=>{S.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let E=(s,g,w)=>{if(s===void 0){w();return}try{s(e,t,()=>{t.writableEnded||t.headersSent||w()})}catch(e){S.error({err:e},`Unhandled ${g} middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}},D=s=>{if(F===!0&&k!==void 0&&(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host))){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`content-asset`});return}E(k,`content-asset`,s)},O=e=>E(j,`react-shell`,e),L=()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${w??`/`}`})};if(j!==void 0&&w?.startsWith(`/assets/`)){O(()=>D(L));return}if(k!==void 0||j!==void 0){D(()=>O(L));return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`The React UI is served by \`ok ui\` (run \`ok ui\` and check \`ui.lock.port\`). No handler for ${w??`/`}`})}),t.on(`upgrade`,(e,t,g)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive socket error`)}),B.handleUpgrade(e,t,g,t=>{let s=parseKeepaliveConnectionId(e.url);if(s){let e=H.get(s);e!==void 0&&(clearTimeout(e),H.delete(s),S.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&D){let t=parseKeepaliveIdentity(e.url);if(t)try{let e=iconFromClientName(t.clientName),g=AGENT_ICON_COLORS[e]??colorFromSeed(t.colorSeed);D.setPresence(toBroadcasterKey(s),{displayName:t.displayName,icon:e,color:g,currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){S.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let g=setInterval(()=>{try{t.ping()}catch{}},3e4);g.unref?.();let k=s?setInterval(()=>{D?.bumpPresenceTs(toBroadcasterKey(s))},3e3):null;k?.unref?.(),t.on(`close`,()=>{if(clearInterval(g),k!==null&&clearInterval(k),!s)return;let e=setTimeout(()=>{if(H.delete(s),ee)return;let e=(async()=>{S.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await w?.closeAllForAgent(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{E?.clearFocus(s)}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{D?.clearPresence(toBroadcasterKey(s))}catch(e){S.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}try{await O?.onSessionClose()}catch(e){S.error({err:e,connectionId:s},`[keepalive] maintenance onSessionClose failed`)}})();q.add(e),e.finally(()=>q.delete(e))},L);e.unref?.(),H.set(s,e),S.info({connectionId:s,graceMs:L},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}if(e.url?.startsWith(`/collab`)){t.on(`error`,e=>{handleCollabSocketError(e)||S.error({err:e},`Upgrade socket error`)}),B.handleUpgrade(e,t,g,t=>{let g=s.handleConnection(t,e),w=!1;t.on(`message`,e=>{if(w)return;let s=e.byteLength;if(s>MAX_COLLAB_MESSAGE_BYTES){w=!0,incrementCollabMessageTooLarge(),S.warn({event:`collab-message-too-large`,bytes:s,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket message rejected before Yjs processing`),t.close(1009,`Message Too Big`);return}g.handleMessage(new Uint8Array(e))}),t.on(`close`,(e,t)=>{g.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{if(e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`){incrementCollabMessageTooLarge(),S.warn({event:`collab-message-too-large`,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`),t.terminate();return}handleCollabSocketError(e)||S.error({err:e},`WebSocket error`),t.terminate()})});return}t.destroy()}),{wss:B,shutdown:async()=>{if(!ee){ee=!0;for(let e of H.values())clearTimeout(e);H.clear(),q.size>0&&await Promise.allSettled(q)}}}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_KEEPALIVE_IDENTITY_LEN=256;function sanitizeIdentityField(e){return e===null||e.length===0||e.length>MAX_KEEPALIVE_IDENTITY_LEN||/[-]/.test(e)?null:e}function parseKeepaliveIdentity(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),s=sanitizeIdentityField(t.searchParams.get(`displayName`)),g=sanitizeIdentityField(t.searchParams.get(`clientName`)),S=sanitizeIdentityField(t.searchParams.get(`colorSeed`));return s===null||g===null||S===null?null:{displayName:s,clientName:g,colorSeed:S}}catch{return null}}const MISSING_OK_CONFIG_MESSAGE=`Open Knowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var MissingOkConfigError=class extends Error{kind;projectDir;constructor(e,t,s){super(MISSING_OK_CONFIG_MESSAGE,s),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};async function startConfigFileWatcher(e,t){let s=getLogger(`config-file-watcher`),{watch:g}=await import(`./chokidar-Bu9Rdqzq.mjs`),S=dirname(e);try{tracedMkdirSync(S,{recursive:!0})}catch(e){e.code!==`EEXIST`&&s.warn({err:e,watchDir:S},`failed to create watch directory; watcher may be inert`)}let w=g(S,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==S&&t!==e});await new Promise(e=>{w.once(`ready`,e)});let E=null;try{E=readFileSync(e,`utf-8`)}catch{}let D=(g,S=!0)=>{if(g!==e)return;let w;try{w=readFileSync(g,`utf-8`)}catch(e){if(e.code===`ENOENT`){S&&s.debug({path:g},`config file disappeared between event and read; dropping`);return}s.warn({err:e,path:g},`config file read failed; dropping event`);return}if(w!==E){E=w;try{t(w)}catch(e){s.warn({err:e,path:g},`config file change handler threw`)}}},O=e=>D(e);w.on(`add`,O),w.on(`change`,O),w.on(`unlink`,t=>{t===e&&s.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),w.on(`error`,t=>{s.warn({err:t,watchDir:S,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let k=0,j=setInterval(()=>{k++,D(e,!1),k>=20&&clearInterval(j)},500);j.unref?.();let F=!1;return async()=>{F||(F=!0,clearInterval(j),await w.close())}}async function startMultiPathConfigFileWatcher(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let s=getLogger(`config-file-watcher`),{watch:g}=await import(`./chokidar-Bu9Rdqzq.mjs`),S=new Set(e),w=Array.from(new Set(Array.from(S,e=>dirname(e))));for(let e of w)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&s.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let E=g(w,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!S.has(e)&&!w.includes(e)});await new Promise(e=>{E.once(`ready`,e)});let D=new Map;for(let e of S)try{D.set(e,readFileSync(e,`utf-8`))}catch{D.set(e,null)}let O=(e,g=!0)=>{if(!S.has(e))return;let w;try{w=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){g&&s.debug({path:e},`config file disappeared between event and read; dropping`);return}s.warn({err:t,path:e},`config file read failed; dropping event`);return}if(w!==D.get(e)){D.set(e,w);try{t(e,w)}catch(t){s.warn({err:t,path:e},`config file change handler threw`)}}},k=e=>O(e);E.on(`add`,k),E.on(`change`,k),E.on(`unlink`,e=>{S.has(e)&&s.debug({path:e},`config file unlinked; downstream state retained`)}),E.on(`error`,e=>{s.warn({err:e,watchDirs:w,paths:Array.from(S)},`[config-file-watcher] chokidar error in multi-path watcher`)});let j=0,F=setInterval(()=>{j++;for(let e of S)O(e,!1);j>=20&&clearInterval(F)},500);F.unref?.();let L=!1;return async()=>{L||(L=!0,clearInterval(F),await E.close())}}function entryMatchesDocName(e,t,s,g){let S=relative(g,join(s,e.file));return S.startsWith(`..`)?!1:stripDocExtension(S)===t}function createConflictLifecycleSeedExtension(e){let{getSyncEngine:t,projectDir:s,contentDir:g}=e;return{async afterLoadDocument({documentName:e,document:S}){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let w=t();if(!w)return;let E=w.getConflicts();if(E.length===0||!E.some(t=>entryMatchesDocName(t,e,s,g)))return;let D=S.getMap(`lifecycle`);if(D.get(`status`)===`conflict`)return;D.set(`status`,`conflict`),D.set(`reason`,`conflict-markers`),console.warn(JSON.stringify({event:`lifecycle-seeded-on-load-from-conflict-store`,"doc.name":e}))}catch(t){console.warn(`[conflict-lifecycle-seed] failed to seed lifecycle on load (doc=${e}):`,t instanceof Error?t:String(t))}}}}const execFileAsync$1=promisify(execFile),BUILTIN_SKIP_DIRS=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`.open-knowledge`,`.openknowledge`,`Library`,`Applications`,`.Trash`]),ALWAYS_SKIP_DIRS=new Set([`.git`,`node_modules`,`.ok`,`.open-knowledge`,`.openknowledge`]);function pathHasAlwaysSkipSegment(e){for(let t of e.split(`/`))if(ALWAYS_SKIP_DIRS.has(t))return!0;return!1}const BUILTIN_SKIP_FILES=new Set([`.DS_Store`,`.localized`]);function isAlwaysSkipFile(e){return BUILTIN_SKIP_FILES.has(e.slice(e.lastIndexOf(`/`)+1))}function isSingleDocAncestorDir(e,t){return t===e||t.startsWith(`${e}/`)}const IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function loadGitExcludeSources(e,t){let s=readGitCommonDirSync(e);if(s===null)return[];let g=[];appendExcludeFileIfExists(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=resolveGlobalExcludesfileSync(e);return S&&appendExcludeFileIfExists(S,t,g,`global excludesfile`),g}async function loadGitExcludeSourcesAsync(e,t){let s=await readGitCommonDirAsync(e);if(s===null)return[];let g=[];await appendExcludeFileIfExistsAsync(join(s,`info`,`exclude`),t,g,`info/exclude`);let S=await resolveGlobalExcludesfileAsync(e);return S&&await appendExcludeFileIfExistsAsync(S,t,g,`global excludesfile`),g}function readGitCommonDirSync(e){let t=spawnSync(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t.status!==0||!t.stdout?null:resolve(e,t.stdout.trim())}async function readGitCommonDirAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf-8`,timeout:5e3});return t?resolve(e,t.trim()):null}catch{return null}}function resolveGlobalExcludesfileSync(e){let t=spawnSync(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3});if(t.status===0&&t.stdout){let e=t.stdout.trim();if(e)return e}return xdgGlobalIgnoreDefault()}async function resolveGlobalExcludesfileAsync(e){try{let{stdout:t}=await execFileAsync$1(`git`,[`config`,`--get`,`--type=path`,`core.excludesfile`],{cwd:e,encoding:`utf-8`,timeout:5e3}),s=t.trim();if(s)return s}catch{}return xdgGlobalIgnoreDefault()}function xdgGlobalIgnoreDefault(){let e=process.env.XDG_CONFIG_HOME?.trim();return join(e&&e.length>0?e:join(homedir(),`.config`),`git`,`ignore`)}function appendExcludeFileIfExists(e,t,s,g){if(existsSync(e))try{let g=readFileSync(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}async function appendExcludeFileIfExistsAsync(e,t,s,g){if(existsSync(e))try{let g=await readFile$1(e,`utf-8`);t.value+=g.length,s.push(...parseIgnorePatterns(g))}catch(t){console.warn(`[content-filter] Failed to read ${g} at ${e}:`,t)}}function createContentFilter(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,singleDocRelPath:S}=e,w=relative(t,s),E=w.startsWith(`..`),D,O,k,j=0,F=0,L=0;function B(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[],S=0,B=0;for(let s of IGNORE_FILE_NAMES){let w=join(t,s);if(existsSync(w))try{let t=readFileSync(w,`utf-8`);S+=t.length;let s=parseIgnorePatterns(t);g.push(...s),e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${w}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=readFileSync(g,`utf-8`);S+=t.length,B++;let s=parseIgnorePatterns(t).map(e=>prefixPattern(e,w));e.add(s)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let H={value:S};B+=loadNestedIgnoreFiles(s,t,e,H),S=H.value;let q=loadGitExcludeSources(t,H);S=H.value,q.length>0&&(g.push(...q),e.add(q));let ee=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`));return D=e,O=g,k=ee,j=g.length,F=B,L=S,{patternCount:j,nestedFileCount:F,bytes:L}}B();let H=new Map;function q(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}let ee=()=>{S===void 0&&populateDirCount(s,``,q,H)};ee();function J(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function Y(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:q(e)}return{isExcluded(e,t){if(J(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(Y(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((H.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasAlwaysSkipSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return J(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)?!0:t?.bypassFilters?!1:Y(e)},getWatcherIgnoreGlobs(){return k},incrementMdDir(e){let t=e===`.`?``:e;H.set(t,(H.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=H.get(t)??0;s<=1?H.delete(t):H.set(t,s-1)},rebuildDirCount(){let e=new Map(H);H.clear();try{ee()}catch(t){for(let[t,s]of e)H.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=k,w=j,E=F,q=L,J=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async Y=>{try{let t=B();H.clear(),ee();let s=Date.now()-J;if(Y.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s},`content-filter rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:s}}catch(g){D=t,O=s,k=S,j=w,F=E,L=q,H.clear();try{ee()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let B=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(B)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:B}}}})}}}function populateDirCount(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let w of S){let S=t?`${t}/${w.name}`:w.name;if(w.isDirectory()){if(BUILTIN_SKIP_DIRS.has(w.name)||s(S)||s(`${S}/`))continue;populateDirCount(join(e,w.name),S,s,g)}else w.isFile()&&isSupportedDocFile(w.name)&&!s(S)&&g.set(t,(g.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
2811
- `).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function prefixPattern(e,t){return e.startsWith(`!`)?`!${t}/${e.slice(1)}`:`${t}/${e}`}function loadNestedIgnoreFiles(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){return console.warn(`[content-filter] Failed to read directory ${e}:`,t),0}let w=0;for(let E of S){if(!E.isDirectory()||BUILTIN_SKIP_DIRS.has(E.name))continue;let S=join(e,E.name),D=relative(t,S);if(!D.startsWith(`..`)&&!(s.ignores(D)||s.ignores(`${D}/`))){for(let e of IGNORE_FILE_NAMES){let t=join(S,e);if(existsSync(t))try{let e=readFileSync(t,`utf-8`);g.value+=e.length;let S=parseIgnorePatterns(e).map(e=>prefixPattern(e,D));s.add(S),w++}catch(s){console.warn(`[content-filter] Failed to read nested ${e} at ${t}:`,s)}}w+=loadNestedIgnoreFiles(S,t,s,g)}}return w}async function initContentDirStateAsync(e,t,s,g,S,w,E){let D;try{D=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let O of D){let D=t?`${t}/${O.name}`:O.name;if(O.isDirectory()){if(BUILTIN_SKIP_DIRS.has(O.name))continue;let t=join(e,O.name);if(!w){let e=relative(s,t);if(e.startsWith(`..`)||g.ignores(e)||g.ignores(`${e}/`))continue;for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.add(t.map(t=>prefixPattern(t,e)))}catch(e){console.warn(`[content-filter] Failed to read nested ${s} at ${S}:`,e)}}}await initContentDirStateAsync(t,D,s,g,S,w,E)}else if(O.isFile()&&isSupportedDocFile(O.name)){if(!w){let e=S?`${S}/${D}`:D;if(g.ignores(e))continue}E.set(t,(E.get(t)??0)+1)}}}async function createContentFilterAsync(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,singleDocRelPath:S}=e,w=relative(t,s),E=w.startsWith(`..`),D=(0,import_ignore.default)(),O=[],k=new Map,j=()=>{S===void 0&&populateDirCount(s,``,F,k)};function F(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}function L(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function B(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:F(e)}async function H(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[];for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.push(...t),e.add(t)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${S}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=parseIgnorePatterns(await readFile$1(g,`utf-8`));e.add(t.map(e=>prefixPattern(e,w)))}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let j=await loadGitExcludeSourcesAsync(t,{value:0});j.length>0&&(g.push(...j),e.add(j));let F=new Map;S===void 0&&await initContentDirStateAsync(s,``,t,e,w,E,F),D=e,O=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)),k.clear();for(let[e,t]of F)k.set(e,t)}return await H(),{isExcluded(e,t){if(L(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(B(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((k.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasAlwaysSkipSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return L(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)?!0:t?.bypassFilters?!1:B(e)},getWatcherIgnoreGlobs(){return O},incrementMdDir(e){let t=e===`.`?``:e;k.set(t,(k.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=k.get(t)??0;s<=1?k.delete(t):k.set(t,s-1)},rebuildDirCount(){let e=new Map(k);k.clear();try{j()}catch(t){for(let[t,s]of e)k.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=new Map(k),w=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async E=>{try{await H();let t=Date.now()-w;if(E.setAttributes({"ok.ignore.pattern_count":O.length,"ok.ignore.nested_file_count":0,"ok.ignore.bytes":0}),e.info({durationMs:t},`content-filter async rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:O.length,nestedFileCount:0,bytes:0,durationMs:t}}catch(g){D=t,O=s,k.clear();for(let[e,t]of S)k.set(e,t);let w=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(w)},`content-filter async rebuild failed — rolled back`),{ok:!1,error:{message:w}}}})}}}function runDocLineageGuard(e,t,s){try{if(typeof t!=`string`||t.length===0||isSystemDoc(e)||isConfigDoc(e))return;let g=s.getLoadedDoc(e);if(g===void 0)throw incrementAuthDocLineageMismatch(),setActiveSpanAttributes({"auth.reason":`doc-lineage-mismatch`}),new HocuspocusAuthRejection(`doc-lineage-mismatch`,`doc lineage mismatch: claim against unloaded ${e} is stale by construction`);let S=g.getMap(`lifecycle`).get(LINEAGE_EPOCH_KEY);if(typeof S!=`string`||S.length===0||S!==t)throw incrementAuthDocLineageMismatch(),setActiveSpanAttributes({"auth.reason":`doc-lineage-mismatch`}),new HocuspocusAuthRejection(`doc-lineage-mismatch`,`doc lineage mismatch for ${e}: claimed epoch does not match the live lineage`)}catch(t){if(t instanceof HocuspocusAuthRejection)throw t;incrementAuthDocLineageGuardError(),console.warn(JSON.stringify({event:`doc-lineage-guard-error`,documentName:e,errorName:t instanceof Error?t.name:typeof t,message:t instanceof Error?t.message:String(t)}))}}const QUIET_WINDOW_MS=100,BATCH_TIMEOUT_MS=3e4,WATCHED_FILES=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function readHeadSha(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let s=resolve(e,t.slice(5));try{return readFileSync(s,`utf-8`).trim()}catch{try{let s=readFileSync(resolve(e,`packed-refs`),`utf-8`),g=t.slice(5),S=s.split(`
2811
+ `).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function prefixPattern(e,t){let s=e.startsWith(`!`),g=s?e.slice(1):e,S=g.startsWith(`/`)?g.slice(1):g,w=S.endsWith(`/`)?S.slice(0,-1):S,E=g.startsWith(`/`)||w.includes(`/`)?`${t}/${S}`:`${t}/**/${S}`;return s?`!${E}`:E}function loadNestedIgnoreFiles(e,t,s,g){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){return console.warn(`[content-filter] Failed to read directory ${e}:`,t),0}let w=0;for(let E of S){if(!E.isDirectory()||BUILTIN_SKIP_DIRS.has(E.name))continue;let S=join(e,E.name),D=relative(t,S);if(!D.startsWith(`..`)&&!(s.ignores(D)||s.ignores(`${D}/`))){for(let e of IGNORE_FILE_NAMES){let t=join(S,e);if(existsSync(t))try{let e=readFileSync(t,`utf-8`);g.value+=e.length;let S=parseIgnorePatterns(e).map(e=>prefixPattern(e,D));s.add(S),w++}catch(s){console.warn(`[content-filter] Failed to read nested ${e} at ${t}:`,s)}}w+=loadNestedIgnoreFiles(S,t,s,g)}}return w}async function initContentDirStateAsync(e,t,s,g,S,w,E){let D;try{D=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let O of D){let D=t?`${t}/${O.name}`:O.name;if(O.isDirectory()){if(BUILTIN_SKIP_DIRS.has(O.name))continue;let t=join(e,O.name);if(!w){let e=relative(s,t);if(e.startsWith(`..`)||g.ignores(e)||g.ignores(`${e}/`))continue;for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.add(t.map(t=>prefixPattern(t,e)))}catch(e){console.warn(`[content-filter] Failed to read nested ${s} at ${S}:`,e)}}}await initContentDirStateAsync(t,D,s,g,S,w,E)}else if(O.isFile()&&isSupportedDocFile(O.name)){if(!w){let e=S?`${S}/${D}`:D;if(g.ignores(e))continue}E.set(t,(E.get(t)??0)+1)}}}async function createContentFilterAsync(e){let{projectDir:t,contentDir:s,onAfterRebuild:g,singleDocRelPath:S}=e,w=relative(t,s),E=w.startsWith(`..`),D=(0,import_ignore.default)(),O=[],k=new Map,j=()=>{S===void 0&&populateDirCount(s,``,F,k)};function F(e){if(E)return!1;let t=w?`${w}/${e}`:e;return D.ignores(t)}function L(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function B(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return E?!1:F(e)}async function H(){let e=(0,import_ignore.default)();e.add(`.git`);let g=[];for(let s of IGNORE_FILE_NAMES){let S=join(t,s);if(existsSync(S))try{let t=parseIgnorePatterns(await readFile$1(S,`utf-8`));g.push(...t),e.add(t)}catch(e){console.warn(`[content-filter] Failed to read ${s} at ${S}:`,e)}}if(w&&!E)for(let t of IGNORE_FILE_NAMES){let g=join(s,t);if(existsSync(g))try{let t=parseIgnorePatterns(await readFile$1(g,`utf-8`));e.add(t.map(e=>prefixPattern(e,w)))}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${g}:`,e)}}let j=await loadGitExcludeSourcesAsync(t,{value:0});j.length>0&&(g.push(...j),e.add(j));let F=new Map;S===void 0&&await initContentDirStateAsync(s,``,t,e,w,E,F),D=e,O=g.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)),k.clear();for(let[e,t]of F)k.set(e,t)}return await H(),{isExcluded(e,t){if(L(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e))return!0;if(S!==void 0)return e!==S;if(t?.bypassFilters)return!1;if(B(e))return!0;if(isSupportedDocFile(e))return!1;let s=extname(e).slice(1).toLowerCase();if(LINKABLE_ASSET_EXTENSIONS.has(s)){let t=dirname(e),s=t===`.`?``:t;if((k.get(s)??0)>0)return!1}return!0},isDirExcluded(e,t){if(pathHasAlwaysSkipSegment(e))return!0;if(S!==void 0)return!isSingleDocAncestorDir(e,S);if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(E)return!1;let s=w?`${w}/${e}`:e;return D.ignores(s)||D.ignores(`${s}/`)},isPathIgnored(e,t){return L(e)||pathHasAlwaysSkipSegment(e)||isAlwaysSkipFile(e)?!0:t?.bypassFilters?!1:B(e)},getWatcherIgnoreGlobs(){return O},incrementMdDir(e){let t=e===`.`?``:e;k.set(t,(k.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,s=k.get(t)??0;s<=1?k.delete(t):k.set(t,s-1)},rebuildDirCount(){let e=new Map(k);k.clear();try{j()}catch(t){for(let[t,s]of e)k.set(t,s);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=D,s=O,S=new Map(k),w=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async E=>{try{await H();let t=Date.now()-w;if(E.setAttributes({"ok.ignore.pattern_count":O.length,"ok.ignore.nested_file_count":0,"ok.ignore.bytes":0}),e.info({durationMs:t},`content-filter async rebuild succeeded`),g)try{g()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:O.length,nestedFileCount:0,bytes:0,durationMs:t}}catch(g){D=t,O=s,k.clear();for(let[e,t]of S)k.set(e,t);let w=g instanceof Error?g.message:String(g);return e.warn({err:g instanceof Error?g:Error(w)},`content-filter async rebuild failed — rolled back`),{ok:!1,error:{message:w}}}})}}}function runDocLineageGuard(e,t,s){try{if(typeof t!=`string`||t.length===0||isSystemDoc(e)||isConfigDoc(e))return;let g=s.getLoadedDoc(e);if(g===void 0)throw incrementAuthDocLineageMismatch(),setActiveSpanAttributes({"auth.reason":`doc-lineage-mismatch`}),new HocuspocusAuthRejection(`doc-lineage-mismatch`,`doc lineage mismatch: claim against unloaded ${e} is stale by construction`);let S=g.getMap(`lifecycle`).get(LINEAGE_EPOCH_KEY);if(typeof S!=`string`||S.length===0||S!==t)throw incrementAuthDocLineageMismatch(),setActiveSpanAttributes({"auth.reason":`doc-lineage-mismatch`}),new HocuspocusAuthRejection(`doc-lineage-mismatch`,`doc lineage mismatch for ${e}: claimed epoch does not match the live lineage`)}catch(t){if(t instanceof HocuspocusAuthRejection)throw t;incrementAuthDocLineageGuardError(),console.warn(JSON.stringify({event:`doc-lineage-guard-error`,documentName:e,errorName:t instanceof Error?t.name:typeof t,message:t instanceof Error?t.message:String(t)}))}}const QUIET_WINDOW_MS=100,BATCH_TIMEOUT_MS=3e4,WATCHED_FILES=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function readHeadSha(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let s=resolve(e,t.slice(5));try{return readFileSync(s,`utf-8`).trim()}catch{try{let s=readFileSync(resolve(e,`packed-refs`),`utf-8`),g=t.slice(5),S=s.split(`
2812
2812
  `).find(e=>e.endsWith(` ${g}`));if(S)return S.split(` `)[0]}catch{}return null}}return t.length>=40?t.slice(0,40):null}catch{return null}}function readBranchFromHead(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();return t.startsWith(`ref: refs/heads/`)?t.slice(16):t.length>=40?`detached-${t.slice(0,12)}`:null}catch{return null}}function watchedGitFile(e){let t=e.split(`/`).pop()??``;return WATCHED_FILES.has(t)?t:null}async function tryStartParcelHeadWatcher(e,t){let s;try{s=await import(`@parcel/watcher`)}catch(e){return getLogger(`head-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher unavailable; falling back to chokidar`),null}try{let g=await s.subscribe(e,(e,s)=>{if(e){getLogger(`head-watcher`).warn({err:e},`[head-watcher] parcel subscription error`);return}for(let e of s)t(e.path)});return()=>g.unsubscribe()}catch(e){return getLogger(`head-watcher`).debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher subscribe failed; falling back to chokidar`),null}}async function startChokidarHeadWatcher(e,t){let{watch:s}=await import(`./chokidar-Bu9Rdqzq.mjs`),g=s(e,{ignoreInitial:!0,depth:0,followSymlinks:!1});return g.on(`all`,(e,s)=>t(s)),g.on(`error`,e=>{getLogger(`head-watcher`).warn({err:e},`[head-watcher] chokidar watcher error`)}),()=>g.close()}async function startHeadWatcher(e,t,s,g={}){let S=resolveGitDir(e);if(!S)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let w=S,E=!1,D=null,O=null,k=null,j=null;async function F(e){if(B&&await B,!E)return;D&&=(clearTimeout(D),null),O&&=(clearTimeout(O),null);let t=readHeadSha(w),g=k!==t,S=readBranchFromHead(w),F;F=S?.startsWith(`detached-`)?`detached-head`:j===S?`within-branch`:`cross-branch`;let L=j;try{await s({headMoved:g,oldHead:k,newHead:t,timeout:e,batchKind:F,oldBranch:L,newBranch:S})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{E=!1,k=t,j=S}}function L(){D&&clearTimeout(D),D=setTimeout(()=>{D=null,F(!1)},QUIET_WINDOW_MS)}let B=null;async function H(e){if(!E){E=!0,k=readHeadSha(w);let s=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();B=s,await s,B=null,O=setTimeout(()=>{O=null,F(!0)},BATCH_TIMEOUT_MS)}L()}let q=e=>{let t=watchedGitFile(e);t!==null&&H(t)},ee=null,J=`chokidar`;if(g.forceBackend!==`chokidar`&&(ee=await tryStartParcelHeadWatcher(w,q),ee&&(J=`parcel`)),!ee){if(g.forceBackend===`parcel`)throw Error(`@parcel/watcher unavailable for HEAD watching (forced backend)`);ee=await startChokidarHeadWatcher(w,q),J=`chokidar`}let Y=ee;return k=readHeadSha(w),j=readBranchFromHead(w),getLogger(`head-watcher`).info({gitDir:w,backend:J},`watching for HEAD changes`),{unsubscribe:async()=>{E&&await F(!1),D&&clearTimeout(D),O&&clearTimeout(O),await Y()},getLastKnownBranch:()=>j}}const LIVE_DERIVED_INDEX_DEBOUNCE_MS=100;function isLocalOriginLike(e){return typeof e!=`object`||!e?!1:e.source===`local`}function serializeLiveDocument(e){return e.getText(`source`).toString()}function createLiveDerivedIndexExtension(e){let{backlinkIndex:t,tagIndex:s,signalChannel:g,debounceMs:S=100}=e,w=new Map;function E(e){let t=w.get(e);t&&(clearTimeout(t),w.delete(e))}function D(e,D){E(e),w.set(e,setTimeout(()=>{w.delete(e);try{let S=serializeLiveDocument(D);t.updateDocumentFromMarkdown(e,S),g?.(`backlinks`),g?.(`graph`),s&&(s.updateDocumentFromMarkdown(e,S),g?.(`tags`))}catch(t){console.error(`[live-derived-index] Failed to update derived views for ${e}:`,t)}},S))}return{async onChange({documentName:e,document:t,transactionOrigin:s}){isSystemDoc(e)||isConfigDoc(e)||isLocalOriginLike(s)&&s.context?.origin===`file-watcher`||D(e,t)},async beforeUnloadDocument({documentName:e}){E(e)},async onDestroy(){for(let e of w.values())clearTimeout(e);w.clear()}}}const log$4=getLogger(`shadow-gc`),GC_GRACE_PERIOD_MS=1440*60*1e3,SESSION_WRITER_TTL_MS=720*60*60*1e3;function extractBranchNames(e){let t=new Set;for(let s of e){let e=s.replace(/^refs\/wip\//,``),g=e.lastIndexOf(`/`);if(g<=0)continue;let S=e.slice(0,g);parseWriterId(e.slice(g+1)).classification!==`unknown`&&t.add(S)}return t}async function getProjectBranchSha(e,t){try{return(await esm_default().env({GIT_DIR:e}).raw(`rev-parse`,`refs/heads/${t}`)).trim()}catch{return null}}async function listProjectBranches(e){let t=new Set;try{let s=(await esm_default().env({GIT_DIR:e}).raw(`for-each-ref`,`refs/heads/`,`--format=%(refname:short)`)).trim();if(s)for(let e of s.split(`
2813
2813
  `))e&&t.add(e)}catch(e){log$4.warn({err:e},`[shadow-gc] listProjectBranches failed; treating as no project branches`)}return t}async function gcShadowBranches(e,t,s=DEFAULT_CHECKPOINT_RETENTION,g=`.`){let S={deletedBranches:[],renamedBranches:[],retainedBranches:[],checkpointGc:{},deletedStaleSessionRefs:0},w=shadowGit(e,{timeoutMs:MAINTENANCE_GIT_TIMEOUT_MS}),E;try{E=(await w.raw(`for-each-ref`,`refs/wip/`,`--format=%(refname)`)).trim()}catch{return S}if(!E)return S;let D=E.split(`
2814
2814
  `).filter(Boolean),O=extractBranchNames(D),k=await listProjectBranches(t),j=[];for(let e of O)e.startsWith(`detached-`)||(k.has(e)?S.retainedBranches.push(e):j.push(e));if(j.length!==0){let e=new Set;for(let t of k)O.has(t)||e.add(t);for(let s of j){let g=!1;if(e.size>0){let E=null;for(let e of D)if(e.startsWith(`refs/wip/${s}/`))try{E=(await w.raw(`rev-parse`,e)).trim();break}catch{}if(E){for(let O of e)if(await getProjectBranchSha(t,O)===E){let t=D.filter(e=>e.startsWith(`refs/wip/${s}/`));for(let e of t){let t=`refs/wip/${O}/${e.slice(`refs/wip/${s}/`.length)}`;try{let s=(await w.raw(`rev-parse`,e)).trim();await w.raw(`update-ref`,t,s),await w.raw(`update-ref`,`-d`,e)}catch(s){log$4.error({err:s,oldRef:e,newRef:t},`[shadow-gc] failed to migrate WIP ref`)}}S.renamedBranches.push({from:s,to:O}),e.delete(O),g=!0;break}}}if(!g){let e=D.filter(e=>e.startsWith(`refs/wip/${s}/`));for(let t of e)try{let e=(await w.raw(`log`,`-1`,`--format=%ci`,t)).trim(),g=new Date(e).getTime();if(Date.now()-g<GC_GRACE_PERIOD_MS){S.retainedBranches.push(s);break}await w.raw(`update-ref`,`-d`,t)}catch{}S.retainedBranches.includes(s)||S.deletedBranches.push(s)}}}let F=new Set([...k,...S.retainedBranches]);for(let t of F)try{let g=await gcCheckpointRefs(e,t,s);(g.scanned>0||g.deletedBridgeMergeLoss>0||g.deletedExternalChangeRescue>0||g.deletedAutoConsolidation>0)&&(S.checkpointGc[t]={scanned:g.scanned,deletedBridgeMergeLoss:g.deletedBridgeMergeLoss,deletedExternalChangeRescue:g.deletedExternalChangeRescue,deletedAutoConsolidation:g.deletedAutoConsolidation,retained:g.retained})}catch(e){log$4.warn({err:e,branch:t},`[shadow-gc] checkpoint GC failed`)}try{await gcRenameLog(e,getOrLoadRenameLogIndex(e.gitDir))}catch(e){log$4.warn({err:e},`[shadow-gc] rename-log GC failed`)}let L=Date.now();for(let t of k){let s=await enumerateWipChains(e,t),w=[];for(let e of s)if(!(e.classification===`classified-file-system`||e.classification===`classified-git-upstream`||e.classification===`classified-openknowledge-service`)){if(e.classification===`unknown`){log$4.warn({branch:t,writerId:e.writerId},`[shadow-gc] unknown writer id in active branch ref — preserved`);continue}if(e.classification===`agent`||e.classification===`principal`){if(e.isPark)continue;e.committedAtMs>0&&L-e.committedAtMs>=SESSION_WRITER_TTL_MS&&w.push({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})}}if(w.length>0)try{await saveVersion(e,g,w,t,void 0,{checkpointKind:{foldedRefs:w.length,trigger:`ttl`},includeUpstream:!1,timeoutMs:MAINTENANCE_GIT_TIMEOUT_MS}),S.deletedStaleSessionRefs+=w.length}catch(e){log$4.warn({err:e,branch:t},`[shadow-gc] TTL consolidation failed`)}}return S}let _runDuration=null,_gcLatch=null,_consolidation=null;function runDurationHist(){return _runDuration||=getMeter().createHistogram(`ok.shadow.maintenance.run_duration_ms`,{description:`Wall-clock duration of one maintenance op. Bounded labels: op ∈ {gc, consolidation, reap}, outcome ∈ {ok, skipped, error}.`,unit:`ms`}),_runDuration}function gcLatchCounter(){return _gcLatch||=getMeter().createCounter(`ok.shadow.maintenance.gc_latch_total`,{description:`Distinct gc.log latch EPISODES (counted on the absent→present transition, not per observation, so one persistent ~1-day latch counts once). A latch means auto-gc is silently disabled until it self-expires; a nonzero rate means a repo is re-degrading invisibly.`}),_gcLatch}function consolidationCounter(){return _consolidation||=getMeter().createCounter(`ok.shadow.maintenance.consolidation_total`,{description:`Auto-consolidation runs that folded ≥1 dead chain. Bounded label: trigger ∈ {dead-chain, session-close, boot, ttl}. Width before/after ride the structured log, not metric labels.`}),_consolidation}function recordMaintenanceRun(e,t,s){runDurationHist().record(Math.max(0,s),{op:e,outcome:t})}function recordGcLatch(){gcLatchCounter().add(1)}function recordConsolidation(e){consolidationCounter().add(1,{trigger:e})}async function countShadowObjects(e){let t=await shadowGit(e).raw(`count-objects`,`-v`),s=new Map;for(let e of t.split(`
@@ -2829,4 +2829,4 @@ In headless mode, write the recap into the research article's "Further reading"
2829
2829
  `))e&&await t.raw(`update-ref`,`-d`,e);Y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){Y.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await ye.flushDeferredStores(`discard-stale`),Te?.emitBranchSwitched(g)}if(e.headMoved&&e.newHead&&_e.current&&s>0){let t=L??`.`;try{let s=await commitUpstreamImport(_e.current,t,e.oldHead,e.newHead,g);incrementUpstreamImport(),Y.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){Y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){Y.error({err:e},`[server] HEAD watcher failed to start`),Fr.push(`head-watcher`)}function D(e){for(let g of e)try{let e=relative(t,join(s,g));if(e.startsWith(`..`))continue;let S=stripDocExtension(e),w=Ce.documents.get(S);if(!w)continue;let E=jt(S);E===null?Y.warn({docName:S,file:g},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):setReconciledBase(S,E);let D=w.getMap(`lifecycle`);D.set(`status`,`conflict`),D.set(`reason`,`sync-merge-conflict`),Y.info({docName:S,file:g},`[sync] marked loaded content conflict`)}catch(e){Y.warn({err:e,file:g},`[sync] failed to mark loaded content conflict`)}}let O=buildSyncCredentialArgs(H);try{$t=new SyncEngine({projectDir:s,contentDir:t,contentFilter:fe,contentRoot:L,syncEnabled:te(),credentialArgs:O,cc1Broadcaster:Te,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{setBatchInProgress(e),e||ye.flushDeferredStores(`within-branch`).catch(e=>{Y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{Y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:D,onAutoDisable:async e=>{Y.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||Y.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 $t.start()}catch(e){Y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),$t=null}Ke(`files`),Ke(`backlinks`),Ke(`graph`),Ke(`tags`)}return Ir().then(Ue,We),{hocuspocus:Ce,sessionManager:we,cc1Broadcaster:Te,agentFocusBroadcaster:De,agentPresenceBroadcaster:je,maintenanceCoordinator:ve,contentFilter:fe,basenameIndex:ce,serverInstanceId:oe,destroy:Mr,ready:Ge,degraded:Fr,lockDir:se,get syncEngine(){return $t}}}const SERVER_MEMORY_SCHEMA_VERSION=1,BYTES_PER_MB=1024*1024;function toMb(e){return e/BYTES_PER_MB}function captureServerMemorySnapshot(){let e=process.memoryUsage();return{schemaVersion:SERVER_MEMORY_SCHEMA_VERSION,capturedAt:new Date().toISOString(),snapshot:{rssMb:toMb(e.rss),heapTotalMb:toMb(e.heapTotal),heapUsedMb:toMb(e.heapUsed),externalMb:toMb(e.external),arrayBuffersMb:toMb(e.arrayBuffers)}}}let cachedGauge=null;onTelemetryShutdown(()=>{cachedGauge=null});function installServerMemoryGauge(){if(cachedGauge)return;let e=getMeter().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=captureServerMemorySnapshot();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`})}),cachedGauge=e}const TELEMETRY_FILENAME=`tolerance-telemetry.jsonl`,TELEMETRY_PREV_FILENAME=`tolerance-telemetry.prev.jsonl`,TELEMETRY_MAX_BYTES=8*1024*1024;let appender=null,appendFailureWarned=!1;function isToleranceTelemetryEnabled(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function initToleranceTelemetryWriter(e){if(!isToleranceTelemetryEnabled())return;let t=getLocalDir(e);appender=new RotatingAppender({currentPath:resolve(t,TELEMETRY_FILENAME),previousPath:resolve(t,TELEMETRY_PREV_FILENAME),maxBytes:TELEMETRY_MAX_BYTES}),setToleranceTelemetryHook(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};appender?.append(`${JSON.stringify(t)}\n`).catch(e=>{appendFailureWarned||(appendFailureWarned=!0,console.warn(`[tolerance-telemetry] append failed; further failures are silent:`,e instanceof Error?e.message:String(e)))})})}async function teardownToleranceTelemetryWriter(){setToleranceTelemetryHook(null),await appender?.drain(),appender=null,appendFailureWarned=!1}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let s=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&s.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let g=resolve(e,t);try{existsSync(g)&&statSync(g).isDirectory()&&s.push(`${t}/`)}catch{}}return s}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3,PINO_REDACT_MAX_DEPTH=5;async function bootServer(e){let t=e.projectDir??e.contentDir,s=resolveLocalSinkConfig({projectDir:t});if(s){let e=s.telemetry.attributeDenylist,t=[];for(let s of e){t.push(s);for(let e=1;e<=PINO_REDACT_MAX_DEPTH;e++)t.push(`${`*.`.repeat(e)}${s}`)}loggerFactory.configure({pinoConfig:{fileSink:s.logs,redactPaths:t}})}initTelemetry({localSink:s?.telemetry}),initToleranceTelemetryWriter(t),installServerMemoryGauge();let{kind:g,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":g};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,g=e.idleShutdownMs,S=e.log??getLogger(`boot`),w=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,E=e.lockKind??w??`interactive`,{createServer:D}=await import(`node:http`),{updateServerLockPort:O}=await import(`./server-lock-CyhBidkz-Bo2K-DzL.mjs`),k=!1;if(!t&&e.autoInitFn)try{k=!!await e.autoInitFn()}catch(e){S.warn({err:e},`autoInitFn failed`)}let j=e.projectDir??e.contentDir,F=resolve(j,`.ok`);if(!existsSync(resolve(F,`config.yml`)))throw new MissingOkConfigError(existsSync(F)?`config`:`okdir`,j);existsSync(resolve(F,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let L=e.gitPreflight??assertGitAvailable;try{e.gitEnabled!==!1&&L()}catch(e){if(e instanceof GitNotAvailableError||e instanceof GitTooOldError){let t=e instanceof GitTooOldError?e.detected:``,s=e instanceof GitTooOldError?`too_old`:`not_available`;emitPreflightFailureSpan(e),S.warn({event:`git_preflight_fail`,platform:e.platform,reason:s,detectedVersion:t},s===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await shutdownTelemetry(),await Promise.race([teardownToleranceTelemetryWriter(),new Promise(e=>setTimeout(e,DESTROY_STEP_TIMEOUT_MS))]),e}let B=findLegacyRuntimeFiles(F);B.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${B.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let H=createServer$1({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:E,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:q,destroy:ee,ready:J,degraded:Y,lockDir:te,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se}=H,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=e.ephemeral?void 0:createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ce}:${ue}`,log:S}),fe=D();fe.headersTimeout=3e4,fe.requestTimeout=6e4;let me=e.serveContentAssets?createAssetServeMiddleware({contentFilter:H.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ge=!1;if(e.reactShellDistDir)try{acquireUiLock(te,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ge=!0}catch(e){if(e instanceof UiLockCollisionError)S.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:te},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await ee().catch(()=>{}),e}let _e=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ve=mountMcpAndApi({httpServer:fe,hocuspocus:q,mcpHttpHandler:de,log:S,sessionManager:ne,agentFocusBroadcaster:ae,agentPresenceBroadcaster:oe,maintenanceCoordinator:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me,reactShellMiddleware:_e,ephemeral:e.ephemeral}),ye=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Ce=null;g!==null&&(Ce=attachIdleShutdown({httpServer:fe,thresholdMs:g??DEFAULT_IDLE_THRESHOLD_MS,log:S,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ye()})})),await restoreLifecycleFromConflictsJson({hocuspocus:q,projectDir:e.projectDir??e.contentDir,log:S});try{await new Promise((t,s)=>{let g=e=>s(e);fe.once(`error`,g),fe.listen(e.port,e.host,()=>{fe.removeListener(`error`,g),t()})})}catch(e){if(ge)try{releaseUiLock(te)}catch(e){S.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await ee().catch(()=>{}),e}let we=fe.address(),Te=typeof we==`object`&&we?we.port:e.port??0;if(ue=Te,O(te,Te),ge&&updateUiLockPort(te,Te),s&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:te,log:S})}catch(e){S.warn({err:e},`spawnUiSiblingFn failed`)}let De=!1,je=async(e,t)=>{let s;try{await Promise.race([t(),new Promise((t,g)=>{s=setTimeout(()=>{g(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),s.unref?.()})])}finally{s!==void 0&&clearTimeout(s)}};return ye=async()=>{if(De)return;De=!0;let e=[],t=async(t,s)=>{try{await je(t,s)}catch(s){e.push(s),S.warn({err:s,step:t},`bootServer destroy step failed`)}};try{Ce?.detach()}catch(t){e.push(t),S.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ve.shutdown()),de!==void 0&&await t(`mcpHttpHandler.close`,()=>de.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ve.wss.close(s=>s?t(s):e())})),await t(`httpServer.closeAllConnections`,async()=>{fe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{fe.close(s=>s&&s.code!==`ERR_SERVER_NOT_RUNNING`?t(s):e())})),await t(`destroyHocuspocus`,()=>ee()),ge&&await t(`releaseUiLock`,async()=>releaseUiLock(te)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),await t(`teardownToleranceTelemetry`,()=>teardownToleranceTelemetryWriter()),await t(`flushLogFileSinks`,()=>loggerFactory.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},{httpServer:fe,destroy:ye,lockDir:te,contentDir:e.contentDir,port:Te,ready:J,degraded:Y,didAutoInit:k,serverInstance:H}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:s,log:g}=e,S,w;try{S=new ConflictStore(s),w=S.list()}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(w.length===0)return;let E=null;try{let e=resolveGitDir(s),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){S.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:w.length}));return}let g=(await simpleGit({baseDir:s,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();E=new Set(g?g.split(`
2830
2830
  `).map(e=>e.trim()).filter(Boolean):[])}catch(e){g.warn({err:e,projectDir:s},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(E!==null){let e=0;for(let t of w)E.has(t.file)||(S.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:w.length-e})),w=w.filter(e=>E?.has(e.file)),w.length===0)return}for(let e of w){let s=stripDocExtension(e.file),S=null,w=!1;try{S=await t.openDirectConnection(s);let e=S.document;if(!e)continue;let g=e.getMap(`lifecycle`);g.set(`status`,`conflict`),g.set(`reason`,`conflict-markers`),w=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":s}))}catch(e){g.warn({err:e,docName:s},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(S)try{await S.disconnect()}catch(e){g.warn({err:e,docName:s,restored:w},`[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,g=e.env??process.env;return s===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):s===`win32`?existsSync(join(g.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const OK_LOGS_DIR=join(homedir(),`.ok`,`logs`),MAX_ROTATED_FILES=2,MAX_AGE_DAYS=7,MAX_DIR_SIZE_BYTES=45*1024*1024,REDACT_PATHS=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function resolveLogLevel(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],s=e.toLowerCase();if(t.includes(s))return s}return process.env.NODE_ENV===`test`?`silent`:`info`}function ensureDir(e){mkdirSync(e,{recursive:!0})}function todayDateString(){return new Date().toISOString().slice(0,10)}function rotateIfNeeded(e){try{if(statSync(e).size<5242880)return}catch{return}for(let t=MAX_ROTATED_FILES;t>=1;t--){let s=t===1?e:`${e}.${t-1}`,g=`${e}.${t}`;try{renameSync(s,g)}catch{}}try{unlinkSync(`${e}.${MAX_ROTATED_FILES+1}`)}catch{}}function pruneLogsDir(e){try{let t=Date.now(),s=MAX_AGE_DAYS*24*60*60*1e3,g=readdirSync(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let s=statSync(join(e,t));return{name:t,mtime:s.mtimeMs,size:s.size}}catch{return null}}).filter(Boolean);for(let S of g)if(t-S.mtime>s)try{unlinkSync(join(e,S.name))}catch{}let S=g.filter(e=>t-e.mtime<=s).sort((e,t)=>e.mtime-t.mtime),w=S.reduce((e,t)=>e+t.size,0);for(let t of S){if(w<=MAX_DIR_SIZE_BYTES)break;try{unlinkSync(join(e,t.name)),w-=t.size}catch{}}}catch{}}function createFileLogger(e){ensureDir(OK_LOGS_DIR);let t=todayDateString(),s=e.filePath??join(OK_LOGS_DIR,`${e.name}.${t}.log`);rotateIfNeeded(s),(e._setTimeout??setTimeout)(()=>pruneLogsDir(OK_LOGS_DIR),5e3).unref();let g=import_pino.default.destination({dest:s,append:!0,sync:!0});return(0,import_pino.default)({level:resolveLogLevel(),name:e.name,redact:{paths:REDACT_PATHS,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:import_pino.default.stdTimeFunctions.isoTime,...e.additionalOptions},g)}function flushFileLogger(e,t=250){return new Promise(s=>{if(!e){s();return}let g=e[import_pino.default.symbols.streamSym],S=!1,w=()=>{S||(S=!0,s())};if(!g||typeof g.flushSync!=`function`){w();return}let E=()=>{try{g.flushSync?.()}catch{}w()},D=setTimeout(w,t);typeof D.unref==`function`&&D.unref(),typeof g.fd==`number`&&g.fd>=0?(clearTimeout(D),E()):typeof g.once==`function`?g.once(`ready`,()=>{clearTimeout(D),E()}):(clearTimeout(D),E())})}function getLogFilePath(e){return join(OK_LOGS_DIR,`${e}.${todayDateString()}.log`)}function getLogsDir(){return OK_LOGS_DIR}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),s=0;for(;s<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:s};let g=dirname(t);if(g===t)return null;t=g,s+=1}return null}const execFileAsync=promisify(execFile),log=getLogger(`project-git`);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,s){super(e,s),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),s=resolve(t,`.git`),g=resolve(s,`HEAD`),S=!1;if(existsSync(s)){if(!statSync(s).isDirectory()||existsSync(g))return{didInit:!1};log.info({},`detected partial .git/ — running git init to repair`),S=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let w=``;try{w=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let s=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,s,{cause:e})}if(!existsSync(g))throw new ProjectGitInitError(`git init reported success but ${s}/HEAD is missing (partial init detected)`,w);return S?(log.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(log.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}async function resolvePackageVersion(e,t){let s;try{s=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(s),g=0;g<32;g+=1){let s=join(t,`package.json`);if(existsSync(s))try{let t=JSON.parse(await readFile$1(s,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let g=dirname(t);if(g===t)return;t=g}}const MAX_CAUSE_DEPTH=5,HOME_PATH_PATTERNS=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function scrubPaths(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:s}of HOME_PATH_PATTERNS)t=t.replace(e,s);return t}function serializeError(e,t=0,s=new WeakSet){if(t>=MAX_CAUSE_DEPTH)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > ${MAX_CAUSE_DEPTH}; truncated`};if(typeof e==`object`&&e){if(s.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};s.add(e)}if(e instanceof Error)return{name:e.name,message:scrubPaths(e.message)??``,stack:scrubPaths(e.stack),code:e.code,cause:e.cause===void 0?void 0:serializeError(e.cause,t+1,s)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:scrubPaths(e)??e};if(typeof e==`object`){let g=e;return{name:String(g.name??`ObjectError`),message:scrubPaths(String(g.message??``))??``,stack:scrubPaths(g.stack),code:g.code,cause:g.cause===void 0?void 0:serializeError(g.cause,t+1,s)}}return{name:`UnknownError`,message:String(e)}}var SingleFileNotFoundError=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},SingleFileNotAFileError=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},SingleFileNotMarkdownError=class extends Error{constructor(e){super(`Open Knowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function prepareSingleFileOpen(e){if(!isSupportedDocFile(e))throw new SingleFileNotMarkdownError(e);let t;try{t=realpathSync(resolve(e))}catch(t){throw t.code===`ENOENT`?new SingleFileNotFoundError(e):t}if(!statSync(t).isFile())throw new SingleFileNotAFileError(e);let s=dirname(t),g=findEnclosingProjectRoot(s);if(g){let e=g.rootPath;return{mode:`project`,projectRoot:e,docName:stripDocExtension(relative(resolveProjectContentDir(e),t).split(sep).join(`/`)),canonicalFilePath:t}}let S=basename(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:s,singleDocRelPath:S,docName:stripDocExtension(S)}}function resolveProjectContentDir(e){return resolve(e,readConfigSafely({absPath:resolveConfigPath(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function createEphemeralProjectDir(e){let t=mkdtempSync(resolve(tmpdir(),`ok-ephemeral-`)),s=resolve(t,`.ok`);return mkdirSync(s,{recursive:!0}),writeFileSync(resolve(s,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),writeFileSync(resolve(s,`.gitignore`),`local/
2831
2831
  `,`utf-8`),t}export{STARTER_TEMPLATES as $,withFileLockSync as $i,isProjectRoot as $n,runCloneSubprocess as $r,createMcpHttpHandler as $t,LIVE_DERIVED_INDEX_DEBOUNCE_MS as A,tracedUnlinkSync as Ai,getMeter as An,readUiLock as Ar,clearArmedPaneTarget as At,OBSERVER_SYNC_ORIGIN as B,writeRootGitignoreForNewRepo as Bi,initTelemetry as Bn,resolveContentDir as Br,contributorCount as Bt,GIT_UPSTREAM_WRITER as C,tracedLinkSync as Ci,formatContributorsFrom as Cn,readBranchFromHead as Cr,buildExecResult as Ct,HocuspocusAuthRejection as D,tracedRenameSync as Di,getLogFilePath as Dn,readStateManifest as Dr,buildWipTree as Dt,HOCUSPOCUS_AUTH_REJECTION_REASONS as E,tracedRename as Ei,getLocalDir as En,readSkillInstallStateSnapshot as Er,buildStarterFolderFrontmatterYaml as Et,MCP_SERVER_NAME as F,validateAgentId as Fi,hasGcLogLatch as Fn,registerWrite as Fr,commitWip as Ft,ROLLBACK_ORIGIN as G,JSONRPCMessageSchema as Gi,isAllowedApiOrigin as Gn,resolvePackageVersion as Gr,createAssetServeMiddleware as Gt,PANE_TARGET_TTL_MS as H,writeTargetVersion as Hi,installPrettyZodErrors as Hn,resolveCursorSpawnInvocation as Hr,countStaleAgentWipRefs as Ht,MIN_GIT_VERSION as I,validateCloneInputs as Ii,incrementCollabSocketFilteredError as In,releaseUiLock as Ir,commitWipFromTree as It,SKILL_INSTALL_EVENTS_FILE_REL as J,isJSONRPCRequest as Ji,isHocuspocusAuthRejectionReason as Jn,restoreLifecycleFromConflictsJson as Jr,createEmbeddingsSecretStore as Jt,ROOT_GITIGNORE_TEMPLATE as K,LATEST_PROTOCOL_VERSION as Ki,isAllowedWorkspaceHostHeader as Kn,resolveUiInfo as Kr,createContentFilter as Kt,MISSING_OK_CONFIG_MESSAGE as L,validateSkillZip as Li,incrementServerObserverFire as Ln,removeLastKnownHash as Lr,compareSemver as Lt,MANAGED_RENAME_ORIGIN as M,tracedWriteFileSync as Mi,getTracer as Mn,recordContributor as Mr,clearEmbeddingsKeyFromAllBackends as Mt,MAX_AGENT_SESSIONS as N,updateLastKnownHash as Ni,handleCollabSocketError as Nn,recordSkillInstallEvent as Nr,coercePackId as Nt,HocuspocusAuthTokenSchema as O,tracedRmSync as Oi,getLogger as On,readTargetRecordedAt as Or,classifyEvents as Ot,MCP_CONNECTION_ID_HEADER as P,updateUiLockPort as Pi,handleSpawnCursor as Pn,registerAllTools as Pr,commitUpstreamImport as Pt,STARTER_PACK_IDS as Q,resolveConfigPath as Qi,isPathWithinDir as Qn,runAuthStatusSubprocess as Qr,createLiveDerivedIndexExtension as Qt,McpLogger as R,withSpan as Ri,initContent as Rn,resetMetrics as Rr,containsConflictMarkers as Rt,GIT_PREFLIGHT_FAIL_SPAN_NAME as S,tracedAppendFileSync as Si,formatContributors as Sn,readArmedPaneTarget as Sr,buildConfigYmlContent as St,GitTooOldError as T,tracedMkdirSync as Ti,getCurrentMcpLogger as Tn,readServerPackageVersion as Tr,buildSkillZip as Tt,PinoLogger as U,writeTracker as Ui,installTestLoggers as Un,resolveLockDir as Ur,countWipRefs as Ut,OK_OKIGNORE_TEMPLATE as V,writeStateManifest as Vi,initToleranceTelemetryWriter as Vn,resolveCursorBinaryDefault as Vr,countShadowObjects as Vt,ProjectGitInitError as W,McpServer as Wi,installUserSkill as Wn,resolvePack as Wr,createApiExtension as Wt,STARTER_FOLDER_FRONTMATTER_FILENAME as X,atomicWriteFileSync as Xi,isLoopbackAddress as Xn,rewriteWikiLinksForDocumentRename as Xr,createExternalChangeHandler as Xt,STARTER_FOLDERS as Y,isJSONRPCResultResponse as Yi,isKnownPackId as Yn,rewriteMarkdownLinksForDocumentRename as Yr,createEphemeralProjectDir as Yt,STARTER_PACKS as Z,readConfigSafely as Zi,isPairedWriteOrigin as Zn,runAuthReposSubprocess as Zr,createFileLogger as Zt,DEFAULT_PACK_ID as _,startWatcher as _i,fallbackPaths as _n,parseKeepaliveConnectionId as _r,assertGitAvailable as _t,AgentPresenceBroadcaster as a,resolveShadowDir as aa,sanitizeClientName as ai,createTestLogger as an,listStarterPacks as ar,SingleFileNotMarkdownError as at,FILE_WATCHER_ORIGIN as b,teardownToleranceTelemetryWriter as bi,flushFileLogger as bn,prepareSingleFileOpen as br,bootServer as bt,AutoStartDisabledError as c,seedBasenameIndex as ci,detectGit as cn,logsCurrentPath as cr,UiLockCollisionError as ct,CONFIG_FILENAME as d,shadowGit as di,encodeDocName as dn,mountMcpAndApi as dr,acquireUiLock as dt,writeConfigPatch as ea,runDeviceFlowSubprocess as ei,createOsProbe as en,isSelfWrite as er,STATE_MANIFEST_FILENAME as et,CONFLICT_MARKER_RE as f,shutdownTelemetry as fi,encodeFolderRoute as fn,normalizeFsPath as fr,applyAgentMarkdownWrite as ft,DEFAULT_EMBEDDINGS_DIMENSIONS as g,splitMarkdownBlocks as gi,extractWikiLinksFromMarkdown as gn,parseHocuspocusAuthToken as gr,assertCompatibleStateManifest as gt,DEFAULT_CHECKPOINT_RETENTION as h,spawnDetached as hi,evictStaleTrackerEntries as hn,parseGitVersion as hr,armPaneTarget as ht,AgentFocusBroadcaster as i,resolveGitDirDetailed as ia,safetyCheckpoint as ii,createStreamingErrorWriter as in,listRescueCheckpoints as ir,SingleFileNotFoundError as it,LOG_MD_TEMPLATE as j,tracedWriteFile as ji,getMetrics as jn,reconcile as jr,clearContributors as jt,INSTALLED_AGENTS_SCHEMES as k,tracedRmdirSync as ki,getLogsDir as kn,readTargetVersion as kr,classifyFsPath as kt,BacklinkIndex as l,serializeError as li,detectProjectShape as ln,logsPreviousPath as lr,__getShowAllWalkStatsForTesting as lt,ConfigSchema as m,spansPreviousPath as mi,errorResponse as mn,parseAuthRejectionWire as mr,applySeed as mt,AGENT_ID_RE as n,MalformedGitPointerError as na,safeContentPath as ni,createServer$1 as nn,isToleranceTelemetryEnabled as nr,SeedRootDirError as nt,AgentSessionCapacityError as o,saveInMemoryCheckpoint as oi,describeStoredEmbeddingsKey as on,loadPrincipal as or,StateManifestError as ot,CURSOR_BUNDLE_PATHS_BY_PLATFORM as p,spansCurrentPath as pi,ensureProjectGit as pn,packageVersionMajorMinor as pr,applyExternalChange as pt,SERVICE_WRITER as q,isInitializedNotification as qi,isConfigDoc as qn,restoreContributors as qr,createContentFilterAsync as qt,AGENT_WRITE_ORIGIN as r,parseCheckpoint as ra,safeSubdir as ri,createServerObserverExtension as rn,lastKnownHash as rr,SingleFileNotAFileError as rt,AgentSessionManager as s,saveVersion as si,detectClaudeDesktopPresence as sn,loggerFactory as sr,TagIndex as st,AGENT_ID_MAX_LEN as t,GitDirAccessError as ta,runWithMcpLogger as ti,createPersistenceExtension as tn,isSystemDoc as tr,SeedPrerequisiteError as tt,CC1Broadcaster as u,setActiveSpanAttributes as ui,emitPreflightFailureSpan as un,makeLazyEmbeddingsKeyStore as ur,__resetShowAllWalkStatsForTesting as ut,EMBEDDINGS_API_KEY_ENV as v,streamingProblemEvent as vi,findEnclosingGitRoot as vn,pathToDocName as vr,assertNeverDiskEvent as vt,GitNotAvailableError as w,tracedMkdir as wi,gcCheckpointRefs as wn,readProjectLocalSemanticConfig as wr,buildInstructions as wt,FileEmbeddingsBackend as x,toBroadcasterKey as xi,formatAuthRejectionWire as xn,readAllTargets as xr,buildAndOpenSkill as xt,FILE_SYSTEM_WRITER as y,swapContributors as yi,findEnclosingProjectRoot as yn,planSeed as yr,attachIdleShutdown as yt,MissingOkConfigError as z,withSpanSync as zi,initShadowRepo as zn,resolveBundledSkillDir as zr,contentHash as zt};
2832
- //# sourceMappingURL=dist-D4w1Xe5t.mjs.map
2832
+ //# sourceMappingURL=dist-DDXOiPkg.mjs.map
@@ -1 +1 @@
1
- import{J as e,Sr as t,Ur as n,a as r,an as i,c as a,d as o,f as s,g as c,h as l,i as u,l as d,m as f,n as p,o as m,p as h,qr as g,r as _,s as v,t as y,tn as b,u as x,vn as S,xn as C,zt as w}from"./server-lock-BpjJj3OD-Co1tfNQM.mjs";import{$ as T,$n as E,$r as D,$t as O,A as k,Ai as A,An as j,Ar as M,At as N,B as P,Bi as F,Bn as I,Br as L,Bt as R,C as z,Ci as B,Cn as V,Cr as H,Ct as U,D as W,Di as G,Dn as K,Dr as q,Dt as J,E as Y,Ei as X,En as Z,Er as Q,Et as $,F as ee,Fi as te,Fn as ne,Fr as re,Ft as ie,G as ae,Gn as oe,Gr as se,Gt as ce,H as le,Hi as ue,Hn as de,Hr as fe,Ht as pe,I as me,Ii as he,In as ge,Ir as _e,It as ve,J as ye,Jn as be,Jr as xe,Jt as Se,K as Ce,Kn as we,Kr as Te,Kt as Ee,L as De,Li as Oe,Ln as ke,Lr as Ae,Lt as je,M as Me,Mi as Ne,Mn as Pe,Mr as Fe,Mt as Ie,N as Le,Ni as Re,Nn as ze,Nr as Be,Nt as Ve,O as He,Oi as Ue,On as We,Or as Ge,Ot as Ke,P as qe,Pi as Je,Pn as Ye,Pr as Xe,Pt as Ze,Q as Qe,Qn as $e,Qr as et,Qt as tt,R as nt,Ri as rt,Rn as it,Rr as at,Rt as ot,S as st,Si as ct,Sn as lt,Sr as ut,St as dt,T as ft,Ti as pt,Tn as mt,Tr as ht,Tt as gt,U as _t,Ui as vt,Un as yt,Ur as bt,Ut as xt,V as St,Vi as Ct,Vn as wt,Vr as Tt,Vt as Et,W as Dt,Wn as Ot,Wr as kt,Wt as At,X as jt,Xn as Mt,Xr as Nt,Xt as Pt,Y as Ft,Yn as It,Yr as Lt,Yt as Rt,Z as zt,Zn as Bt,Zr as Vt,Zt as Ht,_ as Ut,_i as Wt,_n as Gt,_r as Kt,_t as qt,a as Jt,ai as Yt,an as Xt,ar as Zt,at as Qt,b as $t,bi as en,bn as tn,br as nn,bt as rn,c as an,ci as on,cn as sn,cr as cn,ct as ln,d as un,di as dn,dn as fn,dr as pn,dt as mn,ei as hn,en as gn,er as _n,et as vn,f as yn,fi as bn,fn as xn,fr as Sn,ft as Cn,g as wn,gi as Tn,gn as En,gr as Dn,gt as On,h as kn,hi as An,hn as jn,hr as Mn,ht as Nn,i as Pn,ii as Fn,in as In,ir as Ln,it as Rn,j as zn,ji as Bn,jn as Vn,jr as Hn,jt as Un,k as Wn,ki as Gn,kn as Kn,kr as qn,kt as Jn,l as Yn,li as Xn,ln as Zn,lr as Qn,lt as $n,m as er,mi as tr,mn as nr,mr as rr,mt as ir,n as ar,na as or,ni as sr,nn as cr,nr as lr,nt as ur,o as dr,oi as fr,on as pr,or as mr,ot as hr,p as gr,pi as _r,pn as vr,pr as yr,pt as br,q as xr,qn as Sr,qr as Cr,qt as wr,r as Tr,ri as Er,rn as Dr,rr as Or,rt as kr,s as Ar,si as jr,sn as Mr,sr as Nr,st as Pr,t as Fr,ta as Ir,ti as Lr,tn as Rr,tr as zr,tt as Br,u as Vr,ui as Hr,un as Ur,ur as Wr,ut as Gr,v as Kr,vi as qr,vn as Jr,vr as Yr,vt as Xr,w as Zr,wi as Qr,wn as $r,wr as ei,wt as ti,x as ni,xi as ri,xn as ii,xr as ai,xt as oi,y as si,yi as ci,yn as li,yr as ui,yt as di,z as fi,zi as pi,zn as mi,zr as hi,zt as gi}from"./dist-D4w1Xe5t.mjs";export{Fr as AGENT_ID_MAX_LEN,ar as AGENT_ID_RE,Tr as AGENT_WRITE_ORIGIN,Pn as AgentFocusBroadcaster,Jt as AgentPresenceBroadcaster,dr as AgentSessionCapacityError,Ar as AgentSessionManager,an as AutoStartDisabledError,Yn as BacklinkIndex,Vr as CC1Broadcaster,e as CC1_CONTRACT_VERSION,un as CONFIG_FILENAME,yn as CONFLICT_MARKER_RE,gr as CURSOR_BUNDLE_PATHS_BY_PLATFORM,er as ConfigSchema,kn as DEFAULT_CHECKPOINT_RETENTION,wn as DEFAULT_EMBEDDINGS_DIMENSIONS,Ut as DEFAULT_PACK_ID,Kr as EMBEDDINGS_API_KEY_ENV,si as FILE_SYSTEM_WRITER,$t as FILE_WATCHER_ORIGIN,ni as FileEmbeddingsBackend,st as GIT_PREFLIGHT_FAIL_SPAN_NAME,z as GIT_UPSTREAM_WRITER,Ir as GitDirAccessError,Zr as GitNotAvailableError,ft as GitTooOldError,Y as HOCUSPOCUS_AUTH_REJECTION_REASONS,W as HocuspocusAuthRejection,He as HocuspocusAuthTokenSchema,Wn as INSTALLED_AGENTS_SCHEMES,w as LINEAGE_EPOCH_KEY,k as LIVE_DERIVED_INDEX_DEBOUNCE_MS,zn as LOG_MD_TEMPLATE,Me as MANAGED_RENAME_ORIGIN,Le as MAX_AGENT_SESSIONS,qe as MCP_CONNECTION_ID_HEADER,ee as MCP_SERVER_NAME,me as MIN_GIT_VERSION,De as MISSING_OK_CONFIG_MESSAGE,or as MalformedGitPointerError,nt as McpLogger,fi as MissingOkConfigError,P as OBSERVER_SYNC_ORIGIN,St as OK_OKIGNORE_TEMPLATE,b as ORPHAN_MODES,le as PANE_TARGET_TTL_MS,i as PROTOCOL_VERSION,_t as PinoLogger,y as ProcessLockCollisionError,Dt as ProjectGitInitError,ae as ROLLBACK_ORIGIN,Ce as ROOT_GITIGNORE_TEMPLATE,p as RUNTIME_VERSION,xr as SERVICE_WRITER,ye as SKILL_INSTALL_EVENTS_FILE_REL,S as SKILL_STATE_TARGETS,Ft as STARTER_FOLDERS,jt as STARTER_FOLDER_FRONTMATTER_FILENAME,zt as STARTER_PACKS,Qe as STARTER_PACK_IDS,T as STARTER_TEMPLATES,vn as STATE_MANIFEST_FILENAME,_ as STATE_SCHEMA_VERSION,C as SYSTEM_DOC_NAME,Br as SeedPrerequisiteError,ur as SeedRootDirError,u as ServerLockCollisionError,kr as SingleFileNotAFileError,Rn as SingleFileNotFoundError,Qt as SingleFileNotMarkdownError,hr as StateManifestError,Pr as TagIndex,ln as UiLockCollisionError,$n as __getShowAllWalkStatsForTesting,Gr as __resetShowAllWalkStatsForTesting,r as acquireProcessLock,m as acquireServerLock,mn as acquireUiLock,Cn as applyAgentMarkdownWrite,br as applyExternalChange,ir as applySeed,Nn as armPaneTarget,On as assertCompatibleStateManifest,qt as assertGitAvailable,Xr as assertNeverDiskEvent,di as attachIdleShutdown,rn as bootServer,oi as buildAndOpenSkill,dt as buildConfigYmlContent,U as buildExecResult,ti as buildInstructions,gt as buildSkillZip,$ as buildStarterFolderFrontmatterYaml,J as buildWipTree,Ke as classifyEvents,Jn as classifyFsPath,N as clearArmedPaneTarget,Un as clearContributors,Ie as clearEmbeddingsKeyFromAllBackends,Ve as coercePackId,t as colorFromSeed,Ze as commitUpstreamImport,ie as commitWip,ve as commitWipFromTree,je as compareSemver,ot as containsConflictMarkers,gi as contentHash,R as contributorCount,Et as countShadowObjects,pe as countStaleAgentWipRefs,xt as countWipRefs,At as createApiExtension,ce as createAssetServeMiddleware,Ee as createContentFilter,wr as createContentFilterAsync,Se as createEmbeddingsSecretStore,Rt as createEphemeralProjectDir,Pt as createExternalChangeHandler,Ht as createFileLogger,tt as createLiveDerivedIndexExtension,O as createMcpHttpHandler,gn as createOsProbe,Rr as createPersistenceExtension,cr as createServer,Dr as createServerObserverExtension,In as createStreamingErrorWriter,Xt as createTestLogger,pr as describeStoredEmbeddingsKey,Mr as detectClaudeDesktopPresence,sn as detectGit,Zn as detectProjectShape,Ur as emitPreflightFailureSpan,fn as encodeDocName,xn as encodeFolderRoute,vr as ensureProjectGit,nr as errorResponse,jn as evictStaleTrackerEntries,En as extractWikiLinksFromMarkdown,Gt as fallbackPaths,Jr as findEnclosingGitRoot,li as findEnclosingProjectRoot,tn as flushFileLogger,ii as formatAuthRejectionWire,lt as formatContributors,V as formatContributorsFrom,$r as gcCheckpointRefs,mt as getCurrentMcpLogger,Z as getLocalDir,K as getLogFilePath,We as getLogger,Kn as getLogsDir,j as getMeter,Vn as getMetrics,Pe as getTracer,ze as handleCollabSocketError,Ye as handleSpawnCursor,ne as hasGcLogLatch,n as iconFromClientName,ge as incrementCollabSocketFilteredError,ke as incrementServerObserverFire,it as initContent,mi as initShadowRepo,I as initTelemetry,wt as initToleranceTelemetryWriter,de as installPrettyZodErrors,yt as installTestLoggers,Ot as installUserSkill,oe as isAllowedApiOrigin,we as isAllowedWorkspaceHostHeader,Sr as isConfigDoc,be as isHocuspocusAuthRejectionReason,It as isKnownPackId,Mt as isLoopbackAddress,g as isOrphanMode,Bt as isPairedWriteOrigin,$e as isPathWithinDir,v as isProcessAlive,E as isProjectRoot,_n as isSelfWrite,zr as isSystemDoc,lr as isToleranceTelemetryEnabled,a as isValidLockPid,Or as lastKnownHash,Ln as listRescueCheckpoints,Zt as listStarterPacks,mr as loadPrincipal,d as lockFilePath,Nr as loggerFactory,cn as logsCurrentPath,Qn as logsPreviousPath,Wr as makeLazyEmbeddingsKeyStore,pn as mountMcpAndApi,Sn as normalizeFsPath,yr as packageVersionMajorMinor,rr as parseAuthRejectionWire,Mn as parseGitVersion,Dn as parseHocuspocusAuthToken,Kt as parseKeepaliveConnectionId,Yr as pathToDocName,ui as planSeed,nn as prepareSingleFileOpen,ai as readAllTargets,ut as readArmedPaneTarget,H as readBranchFromHead,x as readProcessLock,o as readProcessLockDetailed,ei as readProjectLocalSemanticConfig,s as readServerLock,ht as readServerPackageVersion,Q as readSkillInstallStateSnapshot,q as readStateManifest,Ge as readTargetRecordedAt,qn as readTargetVersion,M as readUiLock,Hn as reconcile,Fe as recordContributor,Be as recordSkillInstallEvent,Xe as registerAllTools,re as registerWrite,h as releaseProcessLock,f as releaseServerLock,_e as releaseUiLock,Ae as removeLastKnownHash,at as resetMetrics,hi as resolveBundledSkillDir,L as resolveContentDir,Tt as resolveCursorBinaryDefault,fe as resolveCursorSpawnInvocation,bt as resolveLockDir,kt as resolvePack,se as resolvePackageVersion,Te as resolveUiInfo,Cr as restoreContributors,xe as restoreLifecycleFromConflictsJson,Lt as rewriteMarkdownLinksForDocumentRename,Nt as rewriteWikiLinksForDocumentRename,Vt as runAuthReposSubprocess,et as runAuthStatusSubprocess,D as runCloneSubprocess,hn as runDeviceFlowSubprocess,Lr as runWithMcpLogger,sr as safeContentPath,Er as safeSubdir,Fn as safetyCheckpoint,Yt as sanitizeClientName,fr as saveInMemoryCheckpoint,jr as saveVersion,on as seedBasenameIndex,Xn as serializeError,Hr as setActiveSpanAttributes,dn as shadowGit,bn as shutdownTelemetry,_r as spansCurrentPath,tr as spansPreviousPath,An as spawnDetached,Tn as splitMarkdownBlocks,Wt as startWatcher,qr as streamingProblemEvent,ci as swapContributors,en as teardownToleranceTelemetryWriter,ri as toBroadcasterKey,ct as tracedAppendFileSync,B as tracedLinkSync,Qr as tracedMkdir,pt as tracedMkdirSync,X as tracedRename,G as tracedRenameSync,Ue as tracedRmSync,Gn as tracedRmdirSync,A as tracedUnlinkSync,Bn as tracedWriteFile,Ne as tracedWriteFileSync,Re as updateLastKnownHash,l as updateProcessLockPort,c as updateServerLockPort,Je as updateUiLockPort,te as validateAgentId,he as validateCloneInputs,Oe as validateSkillZip,rt as withSpan,pi as withSpanSync,F as writeRootGitignoreForNewRepo,Ct as writeStateManifest,ue as writeTargetVersion,vt as writeTracker};
1
+ import{J as e,Sr as t,Ur as n,a as r,an as i,c as a,d as o,f as s,g as c,h as l,i as u,l as d,m as f,n as p,o as m,p as h,qr as g,r as _,s as v,t as y,tn as b,u as x,vn as S,xn as C,zt as w}from"./server-lock-BpjJj3OD-Co1tfNQM.mjs";import{$ as T,$n as E,$r as D,$t as O,A as k,Ai as A,An as j,Ar as M,At as N,B as P,Bi as F,Bn as I,Br as L,Bt as R,C as z,Ci as B,Cn as V,Cr as H,Ct as U,D as W,Di as G,Dn as K,Dr as q,Dt as J,E as Y,Ei as X,En as Z,Er as Q,Et as $,F as ee,Fi as te,Fn as ne,Fr as re,Ft as ie,G as ae,Gn as oe,Gr as se,Gt as ce,H as le,Hi as ue,Hn as de,Hr as fe,Ht as pe,I as me,Ii as he,In as ge,Ir as _e,It as ve,J as ye,Jn as be,Jr as xe,Jt as Se,K as Ce,Kn as we,Kr as Te,Kt as Ee,L as De,Li as Oe,Ln as ke,Lr as Ae,Lt as je,M as Me,Mi as Ne,Mn as Pe,Mr as Fe,Mt as Ie,N as Le,Ni as Re,Nn as ze,Nr as Be,Nt as Ve,O as He,Oi as Ue,On as We,Or as Ge,Ot as Ke,P as qe,Pi as Je,Pn as Ye,Pr as Xe,Pt as Ze,Q as Qe,Qn as $e,Qr as et,Qt as tt,R as nt,Ri as rt,Rn as it,Rr as at,Rt as ot,S as st,Si as ct,Sn as lt,Sr as ut,St as dt,T as ft,Ti as pt,Tn as mt,Tr as ht,Tt as gt,U as _t,Ui as vt,Un as yt,Ur as bt,Ut as xt,V as St,Vi as Ct,Vn as wt,Vr as Tt,Vt as Et,W as Dt,Wn as Ot,Wr as kt,Wt as At,X as jt,Xn as Mt,Xr as Nt,Xt as Pt,Y as Ft,Yn as It,Yr as Lt,Yt as Rt,Z as zt,Zn as Bt,Zr as Vt,Zt as Ht,_ as Ut,_i as Wt,_n as Gt,_r as Kt,_t as qt,a as Jt,ai as Yt,an as Xt,ar as Zt,at as Qt,b as $t,bi as en,bn as tn,br as nn,bt as rn,c as an,ci as on,cn as sn,cr as cn,ct as ln,d as un,di as dn,dn as fn,dr as pn,dt as mn,ei as hn,en as gn,er as _n,et as vn,f as yn,fi as bn,fn as xn,fr as Sn,ft as Cn,g as wn,gi as Tn,gn as En,gr as Dn,gt as On,h as kn,hi as An,hn as jn,hr as Mn,ht as Nn,i as Pn,ii as Fn,in as In,ir as Ln,it as Rn,j as zn,ji as Bn,jn as Vn,jr as Hn,jt as Un,k as Wn,ki as Gn,kn as Kn,kr as qn,kt as Jn,l as Yn,li as Xn,ln as Zn,lr as Qn,lt as $n,m as er,mi as tr,mn as nr,mr as rr,mt as ir,n as ar,na as or,ni as sr,nn as cr,nr as lr,nt as ur,o as dr,oi as fr,on as pr,or as mr,ot as hr,p as gr,pi as _r,pn as vr,pr as yr,pt as br,q as xr,qn as Sr,qr as Cr,qt as wr,r as Tr,ri as Er,rn as Dr,rr as Or,rt as kr,s as Ar,si as jr,sn as Mr,sr as Nr,st as Pr,t as Fr,ta as Ir,ti as Lr,tn as Rr,tr as zr,tt as Br,u as Vr,ui as Hr,un as Ur,ur as Wr,ut as Gr,v as Kr,vi as qr,vn as Jr,vr as Yr,vt as Xr,w as Zr,wi as Qr,wn as $r,wr as ei,wt as ti,x as ni,xi as ri,xn as ii,xr as ai,xt as oi,y as si,yi as ci,yn as li,yr as ui,yt as di,z as fi,zi as pi,zn as mi,zr as hi,zt as gi}from"./dist-DDXOiPkg.mjs";export{Fr as AGENT_ID_MAX_LEN,ar as AGENT_ID_RE,Tr as AGENT_WRITE_ORIGIN,Pn as AgentFocusBroadcaster,Jt as AgentPresenceBroadcaster,dr as AgentSessionCapacityError,Ar as AgentSessionManager,an as AutoStartDisabledError,Yn as BacklinkIndex,Vr as CC1Broadcaster,e as CC1_CONTRACT_VERSION,un as CONFIG_FILENAME,yn as CONFLICT_MARKER_RE,gr as CURSOR_BUNDLE_PATHS_BY_PLATFORM,er as ConfigSchema,kn as DEFAULT_CHECKPOINT_RETENTION,wn as DEFAULT_EMBEDDINGS_DIMENSIONS,Ut as DEFAULT_PACK_ID,Kr as EMBEDDINGS_API_KEY_ENV,si as FILE_SYSTEM_WRITER,$t as FILE_WATCHER_ORIGIN,ni as FileEmbeddingsBackend,st as GIT_PREFLIGHT_FAIL_SPAN_NAME,z as GIT_UPSTREAM_WRITER,Ir as GitDirAccessError,Zr as GitNotAvailableError,ft as GitTooOldError,Y as HOCUSPOCUS_AUTH_REJECTION_REASONS,W as HocuspocusAuthRejection,He as HocuspocusAuthTokenSchema,Wn as INSTALLED_AGENTS_SCHEMES,w as LINEAGE_EPOCH_KEY,k as LIVE_DERIVED_INDEX_DEBOUNCE_MS,zn as LOG_MD_TEMPLATE,Me as MANAGED_RENAME_ORIGIN,Le as MAX_AGENT_SESSIONS,qe as MCP_CONNECTION_ID_HEADER,ee as MCP_SERVER_NAME,me as MIN_GIT_VERSION,De as MISSING_OK_CONFIG_MESSAGE,or as MalformedGitPointerError,nt as McpLogger,fi as MissingOkConfigError,P as OBSERVER_SYNC_ORIGIN,St as OK_OKIGNORE_TEMPLATE,b as ORPHAN_MODES,le as PANE_TARGET_TTL_MS,i as PROTOCOL_VERSION,_t as PinoLogger,y as ProcessLockCollisionError,Dt as ProjectGitInitError,ae as ROLLBACK_ORIGIN,Ce as ROOT_GITIGNORE_TEMPLATE,p as RUNTIME_VERSION,xr as SERVICE_WRITER,ye as SKILL_INSTALL_EVENTS_FILE_REL,S as SKILL_STATE_TARGETS,Ft as STARTER_FOLDERS,jt as STARTER_FOLDER_FRONTMATTER_FILENAME,zt as STARTER_PACKS,Qe as STARTER_PACK_IDS,T as STARTER_TEMPLATES,vn as STATE_MANIFEST_FILENAME,_ as STATE_SCHEMA_VERSION,C as SYSTEM_DOC_NAME,Br as SeedPrerequisiteError,ur as SeedRootDirError,u as ServerLockCollisionError,kr as SingleFileNotAFileError,Rn as SingleFileNotFoundError,Qt as SingleFileNotMarkdownError,hr as StateManifestError,Pr as TagIndex,ln as UiLockCollisionError,$n as __getShowAllWalkStatsForTesting,Gr as __resetShowAllWalkStatsForTesting,r as acquireProcessLock,m as acquireServerLock,mn as acquireUiLock,Cn as applyAgentMarkdownWrite,br as applyExternalChange,ir as applySeed,Nn as armPaneTarget,On as assertCompatibleStateManifest,qt as assertGitAvailable,Xr as assertNeverDiskEvent,di as attachIdleShutdown,rn as bootServer,oi as buildAndOpenSkill,dt as buildConfigYmlContent,U as buildExecResult,ti as buildInstructions,gt as buildSkillZip,$ as buildStarterFolderFrontmatterYaml,J as buildWipTree,Ke as classifyEvents,Jn as classifyFsPath,N as clearArmedPaneTarget,Un as clearContributors,Ie as clearEmbeddingsKeyFromAllBackends,Ve as coercePackId,t as colorFromSeed,Ze as commitUpstreamImport,ie as commitWip,ve as commitWipFromTree,je as compareSemver,ot as containsConflictMarkers,gi as contentHash,R as contributorCount,Et as countShadowObjects,pe as countStaleAgentWipRefs,xt as countWipRefs,At as createApiExtension,ce as createAssetServeMiddleware,Ee as createContentFilter,wr as createContentFilterAsync,Se as createEmbeddingsSecretStore,Rt as createEphemeralProjectDir,Pt as createExternalChangeHandler,Ht as createFileLogger,tt as createLiveDerivedIndexExtension,O as createMcpHttpHandler,gn as createOsProbe,Rr as createPersistenceExtension,cr as createServer,Dr as createServerObserverExtension,In as createStreamingErrorWriter,Xt as createTestLogger,pr as describeStoredEmbeddingsKey,Mr as detectClaudeDesktopPresence,sn as detectGit,Zn as detectProjectShape,Ur as emitPreflightFailureSpan,fn as encodeDocName,xn as encodeFolderRoute,vr as ensureProjectGit,nr as errorResponse,jn as evictStaleTrackerEntries,En as extractWikiLinksFromMarkdown,Gt as fallbackPaths,Jr as findEnclosingGitRoot,li as findEnclosingProjectRoot,tn as flushFileLogger,ii as formatAuthRejectionWire,lt as formatContributors,V as formatContributorsFrom,$r as gcCheckpointRefs,mt as getCurrentMcpLogger,Z as getLocalDir,K as getLogFilePath,We as getLogger,Kn as getLogsDir,j as getMeter,Vn as getMetrics,Pe as getTracer,ze as handleCollabSocketError,Ye as handleSpawnCursor,ne as hasGcLogLatch,n as iconFromClientName,ge as incrementCollabSocketFilteredError,ke as incrementServerObserverFire,it as initContent,mi as initShadowRepo,I as initTelemetry,wt as initToleranceTelemetryWriter,de as installPrettyZodErrors,yt as installTestLoggers,Ot as installUserSkill,oe as isAllowedApiOrigin,we as isAllowedWorkspaceHostHeader,Sr as isConfigDoc,be as isHocuspocusAuthRejectionReason,It as isKnownPackId,Mt as isLoopbackAddress,g as isOrphanMode,Bt as isPairedWriteOrigin,$e as isPathWithinDir,v as isProcessAlive,E as isProjectRoot,_n as isSelfWrite,zr as isSystemDoc,lr as isToleranceTelemetryEnabled,a as isValidLockPid,Or as lastKnownHash,Ln as listRescueCheckpoints,Zt as listStarterPacks,mr as loadPrincipal,d as lockFilePath,Nr as loggerFactory,cn as logsCurrentPath,Qn as logsPreviousPath,Wr as makeLazyEmbeddingsKeyStore,pn as mountMcpAndApi,Sn as normalizeFsPath,yr as packageVersionMajorMinor,rr as parseAuthRejectionWire,Mn as parseGitVersion,Dn as parseHocuspocusAuthToken,Kt as parseKeepaliveConnectionId,Yr as pathToDocName,ui as planSeed,nn as prepareSingleFileOpen,ai as readAllTargets,ut as readArmedPaneTarget,H as readBranchFromHead,x as readProcessLock,o as readProcessLockDetailed,ei as readProjectLocalSemanticConfig,s as readServerLock,ht as readServerPackageVersion,Q as readSkillInstallStateSnapshot,q as readStateManifest,Ge as readTargetRecordedAt,qn as readTargetVersion,M as readUiLock,Hn as reconcile,Fe as recordContributor,Be as recordSkillInstallEvent,Xe as registerAllTools,re as registerWrite,h as releaseProcessLock,f as releaseServerLock,_e as releaseUiLock,Ae as removeLastKnownHash,at as resetMetrics,hi as resolveBundledSkillDir,L as resolveContentDir,Tt as resolveCursorBinaryDefault,fe as resolveCursorSpawnInvocation,bt as resolveLockDir,kt as resolvePack,se as resolvePackageVersion,Te as resolveUiInfo,Cr as restoreContributors,xe as restoreLifecycleFromConflictsJson,Lt as rewriteMarkdownLinksForDocumentRename,Nt as rewriteWikiLinksForDocumentRename,Vt as runAuthReposSubprocess,et as runAuthStatusSubprocess,D as runCloneSubprocess,hn as runDeviceFlowSubprocess,Lr as runWithMcpLogger,sr as safeContentPath,Er as safeSubdir,Fn as safetyCheckpoint,Yt as sanitizeClientName,fr as saveInMemoryCheckpoint,jr as saveVersion,on as seedBasenameIndex,Xn as serializeError,Hr as setActiveSpanAttributes,dn as shadowGit,bn as shutdownTelemetry,_r as spansCurrentPath,tr as spansPreviousPath,An as spawnDetached,Tn as splitMarkdownBlocks,Wt as startWatcher,qr as streamingProblemEvent,ci as swapContributors,en as teardownToleranceTelemetryWriter,ri as toBroadcasterKey,ct as tracedAppendFileSync,B as tracedLinkSync,Qr as tracedMkdir,pt as tracedMkdirSync,X as tracedRename,G as tracedRenameSync,Ue as tracedRmSync,Gn as tracedRmdirSync,A as tracedUnlinkSync,Bn as tracedWriteFile,Ne as tracedWriteFileSync,Re as updateLastKnownHash,l as updateProcessLockPort,c as updateServerLockPort,Je as updateUiLockPort,te as validateAgentId,he as validateCloneInputs,Oe as validateSkillZip,rt as withSpan,pi as withSpanSync,F as writeRootGitignoreForNewRepo,Ct as writeStateManifest,ue as writeTargetVersion,vt as writeTracker};
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{i as e,r as t,t as n}from"./gh-detect-CiwGHfLq.mjs";import{A as r,C as i,D as a,E as o,O as s,S as c,T as l,_ as u,b as d,d as f,g as p,h as m,i as h,j as g,k as _,o as v,r as y,s as b,t as x,w as S,x as C,y as w}from"./init-BJWXZw7g.mjs";import{d as T,f as E,m as D,n as O,p as k,r as A,t as j}from"./src-CI8DR-q-.mjs";import{n as M}from"./loader-CyDqzvXj.mjs";import{n as N}from"./preview-DAMaD8d5.mjs";import{n as P,t as F}from"./mcp-migrate-event-D0NrGjvc.mjs";export{a as ALL_EDITOR_IDS,s as EDITOR_LABELS,_ as EDITOR_TARGETS,x as LAUNCH_CONFIG_NAME,y as LAUNCH_UI_CHAIN_SENTINEL,h as LAUNCH_UI_CHAIN_V1,d as addOkPathsToGitExclude,r as buildManagedServerEntry,F as buildMcpConfigMigrateEvent,v as classifyExistingMcpEntry,t as createTokenStore,n as detectGh,b as detectInstalledEditors,C as formatTrackedRemediation,c as getExcludedOkPaths,i as getOkArtifactPaths,g as isEntryUpToDate,M as loadConfig,e as makeLazyProbeTokenStore,T as parseGitHubBlobUrl,E as parseGitHubShareUrl,k as parseGitHubTreeUrl,D as parseGitUrl,N as previewContent,S as probeTrackedOkPaths,f as readExistingMcpEntry,l as readSharingMode,o as removeOkPathsFromGitExclude,w as resolveProjectRoot,A as runStop,m as scaffoldLaunchJson,P as truncatePriorEntry,O as validateLocalFolderForShare,p as writeEditorMcpConfig,j as writeProjectAiIntegrations,u as writeUserMcpConfigs};
1
+ import{i as e,r as t,t as n}from"./gh-detect-CiwGHfLq.mjs";import{A as r,C as i,D as a,E as o,O as s,S as c,T as l,_ as u,b as d,d as f,g as p,h as m,i as h,j as g,k as _,o as v,r as y,s as b,t as x,w as S,x as C,y as w}from"./init-Bp64Lvl-.mjs";import{d as T,f as E,m as D,n as O,p as k,r as A,t as j}from"./src-DHDfWHi4.mjs";import{n as M}from"./loader-HZLNd747.mjs";import{n as N}from"./preview-TG2mvVXo.mjs";import{n as P,t as F}from"./mcp-migrate-event-D0NrGjvc.mjs";export{a as ALL_EDITOR_IDS,s as EDITOR_LABELS,_ as EDITOR_TARGETS,x as LAUNCH_CONFIG_NAME,y as LAUNCH_UI_CHAIN_SENTINEL,h as LAUNCH_UI_CHAIN_V1,d as addOkPathsToGitExclude,r as buildManagedServerEntry,F as buildMcpConfigMigrateEvent,v as classifyExistingMcpEntry,t as createTokenStore,n as detectGh,b as detectInstalledEditors,C as formatTrackedRemediation,c as getExcludedOkPaths,i as getOkArtifactPaths,g as isEntryUpToDate,M as loadConfig,e as makeLazyProbeTokenStore,T as parseGitHubBlobUrl,E as parseGitHubShareUrl,k as parseGitHubTreeUrl,D as parseGitUrl,N as previewContent,S as probeTrackedOkPaths,f as readExistingMcpEntry,l as readSharingMode,o as removeOkPathsFromGitExclude,w as resolveProjectRoot,A as runStop,m as scaffoldLaunchJson,P as truncatePriorEntry,O as validateLocalFolderForShare,p as writeEditorMcpConfig,j as writeProjectAiIntegrations,u as writeUserMcpConfigs};