epiq 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -1,57 +1,57 @@
1
1
  #!/usr/bin/env node
2
- var El=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var Nl=(e,t)=>{for(var n in t)El(e,n,{get:t[n],enumerable:!0})};var ut,i,c,a,Rt,C=y(()=>{"use strict";ut={Success:"success",Fail:"fail"},i=e=>({status:ut.Fail,message:e,value:null}),c=(e,t)=>({status:ut.Success,message:e,value:t}),a=e=>e.status==="fail",Rt=e=>e.status==="success"});import Nn from"node:fs";import nt from"node:path";var Og,rt,Fe,er,Cl,tr,nr,Cn,Vs,Rl,bo,rr,mt,qs,ze,ue=y(()=>{"use strict";C();pt();Og=process.env.IS_LOCAL==="true",rt=".epiq",Fe=".epiq-global",er="events",Cl="project.json",tr=e=>nt.join(e,rt),nr=e=>nt.join(tr(e),Cl),Cn=e=>nt.join(tr(e),er),Vs=e=>nt.join(e,rt),Rl=e=>{let t=nt.join(e,rt);return Nn.existsSync(t)&&Nn.statSync(t).isDirectory()},bo=e=>{let t=nr(e);return Nn.existsSync(t)&&Nn.statSync(t).isFile()},rr=e=>{let t=nt.resolve(e);for(;;){if(Rl(t))return c("Resolved closest .epiq root",t);let n=nt.dirname(t);if(n===t)return i("No .epiq directory found in any parent");t=n}},mt=e=>{let t=nt.resolve(e);for(;;){if(bo(t))return c("Resolved closest epiq project root",t);let n=nt.dirname(t);if(n===t)return i("No .epiq/project.json found in any parent");t=n}},qs=e=>{let t=Cn(e);try{return Nn.mkdirSync(t,{recursive:!0}),c("Resolved events dir",t)}catch(n){return i(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},ze=async()=>{let e=await Ve(process.cwd());if(a(e))return e;let t=We({repoRoot:e.value});return a(t)?t:c("Resolved persist root",t.value)}});import Rn from"node:fs";import{ulid as Sl}from"ulid";import{z as or}from"zod";var Al,Tl,sr,gt,Gs,Ks,St=y(()=>{"use strict";C();ue();Al="__epiq_state__",Tl=or.object({projectId:or.string().min(1),stateBranch:or.string().min(1),createdAt:or.iso.datetime()}),sr=()=>({projectId:Sl(),stateBranch:Al,createdAt:new Date().toISOString()}),gt=e=>{let t=nr(e);if(!Rn.existsSync(t))return i("Missing .epiq/project.json");try{let n=Rn.readFileSync(t,"utf8"),r=JSON.parse(n),o=Tl.safeParse(r);return o.success?c("Read project.json",o.data):i(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return i(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},Gs=e=>{let t=gt(e);return a(t)?i(t.message):c("Read projectId",t.value.projectId)},Ks=({repoRoot:e,fileContents:t})=>{let n=tr(e),r=nr(e);try{if(Rn.mkdirSync(n,{recursive:!0}),Rn.existsSync(r)){let o=gt(e);return a(o)?i(o.message):c("Project already initialized",null)}return Rn.writeFileSync(r,JSON.stringify(t,null,2)+`
3
- `,"utf8"),c("Created project.json",null)}catch(o){return i(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}}});var Eo,Ys=y(()=>{"use strict";C();Eo=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let d=r(...s);if(!n.has(d)){let l=e(...s).then(u=>(a(u)&&n.delete(d),u));n.set(d,l)}return n.get(d)});return o.clear=()=>n.clear(),o}});import Sn from"fs";import So from"path";import wl from"util";function Ll(){let e=Qs();if(!e||!Sn.existsSync(e))return;let n=Sn.readFileSync(e,"utf8").split(`
4
- `);if(n[n.length-1]===""&&n.pop(),n.length<=Xs)return;let r=n.slice(-Xs).join(`
2
+ var wl=Object.defineProperty;var h=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ml=(e,t)=>{for(var n in t)wl(e,n,{get:t[n],enumerable:!0})};var ft,i,c,a,Lt,C=h(()=>{"use strict";ft={Success:"success",Fail:"fail"},i=e=>({status:ft.Fail,message:e,value:null}),c=(e,t)=>({status:ft.Success,message:e,value:t}),a=e=>e.status==="fail",Lt=e=>e.status==="success"});import Mn from"node:fs";import at from"node:path";var Gg,dt,Oe,cr,kl,lr,ur,kn,Ys,Ll,Ao,mr,vt,Xs,Ke,pe=h(()=>{"use strict";C();yt();Gg=process.env.IS_LOCAL==="true",dt=".epiq",Oe=".epiq-global",cr="events",kl="project.json",lr=e=>at.join(e,dt),ur=e=>at.join(lr(e),kl),kn=e=>at.join(lr(e),cr),Ys=e=>at.join(e,dt),Ll=e=>{let t=at.join(e,dt);return Mn.existsSync(t)&&Mn.statSync(t).isDirectory()},Ao=e=>{let t=ur(e);return Mn.existsSync(t)&&Mn.statSync(t).isFile()},mr=e=>{let t=at.resolve(e);for(;;){if(Ll(t))return c("Resolved closest .epiq root",t);let n=at.dirname(t);if(n===t)return i("No .epiq directory found in any parent");t=n}},vt=e=>{let t=at.resolve(e);for(;;){if(Ao(t))return c("Resolved closest epiq project root",t);let n=at.dirname(t);if(n===t)return i("No .epiq/project.json found in any parent");t=n}},Xs=e=>{let t=kn(e);try{return Mn.mkdirSync(t,{recursive:!0}),c("Resolved events dir",t)}catch(n){return i(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},Ke=async()=>{let e=await Ye(process.cwd());if(a(e))return e;let t=ze({repoRoot:e.value});return a(t)?t:c("Resolved persist root",t.value)}});import Ln from"node:fs";import{ulid as Pl}from"ulid";import{z as pr}from"zod";var Dl,Fl,gr,ht,Js,Qs,Pt=h(()=>{"use strict";C();pe();Dl="__epiq_state__",Fl=pr.object({projectId:pr.string().min(1),stateBranch:pr.string().min(1),createdAt:pr.iso.datetime()}),gr=()=>({projectId:Pl(),stateBranch:Dl,createdAt:new Date().toISOString()}),ht=e=>{let t=ur(e);if(!Ln.existsSync(t))return i("Missing .epiq/project.json");try{let n=Ln.readFileSync(t,"utf8"),r=JSON.parse(n),o=Fl.safeParse(r);return o.success?c("Read project.json",o.data):i(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return i(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},Js=e=>{let t=ht(e);return a(t)?i(t.message):c("Read projectId",t.value.projectId)},Qs=({repoRoot:e,fileContents:t})=>{let n=lr(e),r=ur(e);try{if(Ln.mkdirSync(n,{recursive:!0}),Ln.existsSync(r)){let o=ht(e);return a(o)?i(o.message):c("Project already initialized",null)}return Ln.writeFileSync(r,JSON.stringify(t,null,2)+`
3
+ `,"utf8"),c("Created project.json",null)}catch(o){return i(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}}});var To,Zs=h(()=>{"use strict";C();To=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let d=r(...s);if(!n.has(d)){let l=e(...s).then(u=>(a(u)&&n.delete(d),u));n.set(d,l)}return n.get(d)});return o.clear=()=>n.clear(),o}});import Pn from"fs";import Lo from"path";import Ol from"util";function Bl(){let e=ni();if(!e||!Pn.existsSync(e))return;let n=Pn.readFileSync(e,"utf8").split(`
4
+ `);if(n[n.length-1]===""&&n.pop(),n.length<=ei)return;let r=n.slice(-ei).join(`
5
5
  `)+`
6
- `;Sn.writeFileSync(e,r,"utf8")}function Co(e,t,n=!1){let r=Qs();if(!r)return;let o=wl.format(...t),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
7
- `;Sn.mkdirSync(So.dirname(r),{recursive:!0}),Sn.appendFileSync(r,l,"utf8"),No++,No>=Ml&&(No=0,Ll())}var Xs,Ml,No,Js,Qs,Ro,me,An=y(()=>{"use strict";C();ue();Xs=1e3,Ml=50,No=0,Js=()=>process.env.EPIQ_MCP==="true",Qs=()=>{let e=process.cwd(),t=rr(e);return a(t)?Js()?So.join(process.cwd(),".epiq-mcp.log"):void 0:So.join(t.value,rt,"log","epiq.log")};Ro=()=>Js()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",me={info(...e){let t=Ro();(t==="info"||t==="debug")&&Co("[Info]",e,!1)},debug(...e){Ro()==="debug"&&Co("[Debug]",e,!0)},error(...e){let t=Ro();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;Co("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=me});var re,ir=y(()=>{"use strict";At();re={stage:({cwd:e,pathspec:t})=>_({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>_({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>_({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>_({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>_({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push",...r?["-u"]:[],t,n]:["push"];return _({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>_({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>_({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>_({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>_({args:["worktree","prune"],cwd:e})}});var Yt,Oe,ar=y(()=>{"use strict";St();C();ue();Yt=e=>{let t=mt(e);if(a(t))return i("Unable to resolve epiq project root");let n=gt(t.value);return a(n)?i("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},Oe="origin"});import{spawn as kl}from"node:child_process";import dr from"node:fs";import Tn from"node:path";var Zs,Pl,ei,_,qe,Xt,Dl,Fl,cr,Ao,lr,ur,wn,ti,To,mr,ni,ri,Ol,wo,oi,si,At=y(()=>{"use strict";C();ir();ar();Zs=1e4,Pl={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},ei=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!dr.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:p,exitCode:1});return}r(i(p));return}let o=kl("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Pl}),s=!1,d="",l="",u=p=>{s||(s=!0,clearTimeout(m),r(p))},m=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${Zs}ms`].join(`
8
- `);u(n?{stdout:d,stderr:p,exitCode:124}:i(p))},Zs);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{d+=p}),o.stderr.on("data",p=>{l+=p}),o.on("error",p=>{if(n){u({stdout:d,stderr:p.message,exitCode:1});return}u(i([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
9
- `)))}),o.on("close",p=>{let h=p??1;if(n){u({stdout:d,stderr:l,exitCode:h});return}if(h!==0){u(i([`git ${e.join(" ")}`,l.trim()||d.trim()||"Git command failed"].filter(Boolean).join(`
10
- `)));return}u(c("Git command succeeded",{stdout:d,stderr:l,exitCode:h}))})}),_=({args:e,cwd:t})=>ei({args:e,cwd:t,allowFail:!1}),qe=({args:e,cwd:t})=>ei({args:e,cwd:t,allowFail:!0}),Xt=async({cwd:e,message:t})=>{let n=await re.commit({cwd:e,message:t});if(a(n))return i(`Failed to create commit
6
+ `;Pn.writeFileSync(e,r,"utf8")}function Mo(e,t,n=!1){let r=ni();if(!r)return;let o=Ol.format(...t),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
7
+ `;Pn.mkdirSync(Lo.dirname(r),{recursive:!0}),Pn.appendFileSync(r,l,"utf8"),wo++,wo>=Ul&&(wo=0,Bl())}var ei,Ul,wo,ti,ni,ko,ge,Dn=h(()=>{"use strict";C();pe();ei=1e3,Ul=50,wo=0,ti=()=>process.env.EPIQ_MCP==="true",ni=()=>{let e=process.cwd(),t=mr(e);return a(t)?ti()?Lo.join(process.cwd(),".epiq-mcp.log"):void 0:Lo.join(t.value,dt,"log","epiq.log")};ko=()=>ti()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",ge={info(...e){let t=ko();(t==="info"||t==="debug")&&Mo("[Info]",e,!1)},debug(...e){ko()==="debug"&&Mo("[Debug]",e,!0)},error(...e){let t=ko();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;Mo("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=ge});var oe,fr=h(()=>{"use strict";Dt();oe={stage:({cwd:e,pathspec:t})=>_({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>_({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>_({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>_({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>_({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push",...r?["-u"]:[],t,n]:["push"];return _({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>_({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>_({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>_({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>_({args:["worktree","prune"],cwd:e})}});var Qt,Ue,vr=h(()=>{"use strict";Pt();C();pe();Qt=e=>{let t=vt(e);if(a(t))return i("Unable to resolve epiq project root");let n=ht(t.value);return a(n)?i("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},Ue="origin"});import{spawn as _l}from"node:child_process";import yr from"node:fs";import Fn from"node:path";var ri,jl,oi,_,Xe,Zt,$l,Wl,hr,Po,xr,Ir,On,si,Do,Er,ii,ai,Hl,Fo,di,ci,Dt=h(()=>{"use strict";C();fr();vr();ri=1e4,jl={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},oi=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!yr.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:p,exitCode:1});return}r(i(p));return}let o=_l("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:jl}),s=!1,d="",l="",u=p=>{s||(s=!0,clearTimeout(m),r(p))},m=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${ri}ms`].join(`
8
+ `);u(n?{stdout:d,stderr:p,exitCode:124}:i(p))},ri);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{d+=p}),o.stderr.on("data",p=>{l+=p}),o.on("error",p=>{if(n){u({stdout:d,stderr:p.message,exitCode:1});return}u(i([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
9
+ `)))}),o.on("close",p=>{let y=p??1;if(n){u({stdout:d,stderr:l,exitCode:y});return}if(y!==0){u(i([`git ${e.join(" ")}`,l.trim()||d.trim()||"Git command failed"].filter(Boolean).join(`
10
+ `)));return}u(c("Git command succeeded",{stdout:d,stderr:l,exitCode:y}))})}),_=({args:e,cwd:t})=>oi({args:e,cwd:t,allowFail:!1}),Xe=({args:e,cwd:t})=>oi({args:e,cwd:t,allowFail:!0}),Zt=async({cwd:e,message:t})=>{let n=await oe.commit({cwd:e,message:t});if(a(n))return i(`Failed to create commit
11
11
  ${n.message}`);let r=await _({args:["rev-parse","HEAD"],cwd:e});return a(r)?i(`Commit created, but failed to read HEAD SHA
12
- ${r.message}`):c("Created commit and resolved SHA",r.value.stdout.trim())},Dl=async e=>{let t=await _({cwd:e,args:["rev-parse","--git-dir"]});if(a(t))return i(t.message);let n=t.value.stdout.trim();return c("Resolved git dir",Tn.isAbsolute(n)?n:Tn.resolve(e,n))},Fl=async e=>{let t=await Dl(e);if(a(t))return i(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,d]of Object.entries(r))if(dr.existsSync(Tn.join(n,s)))return c("Checked for in-progress Git operation",d);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,d]of Object.entries(o))if(dr.existsSync(Tn.join(n,s)))return c("Checked for in-progress Git operation",d);return c("Checked for in-progress Git operation",null)},cr=async e=>{let t=await Fl(e);return a(t)?i(t.message):c("Checked for in-progress Git operation",t.value!==null)},Ao=async({repoRoot:e})=>{let n=(await qe({args:["remote","get-url",Oe],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},lr=async({repoRoot:e,branch:t})=>{let n=await qe({args:["ls-remote","--heads",Oe,t],cwd:e});return n.exitCode!==0?i(n.stderr.trim()||`Unable to inspect remote branch ${Oe}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},ur=async({repoRoot:e,branch:t})=>{let n=await qe({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?c("Local branch exists",!0):n.exitCode===1?c("Local branch missing",!1):i(n.stderr.trim()||`Unable to inspect branch ${t}`)},wn=e=>{try{return dr.realpathSync.native(e)}catch{return Tn.resolve(e)}},ti=async({repoRoot:e,worktreeRoot:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let r=wn(t),o=n.value.stdout.split(`
13
- `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(wn).includes(r);return c("Checked worktree registration",o)},To=async e=>{let t=await qe({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},mr=async e=>{let t=await _({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved current branch",t.value.stdout.trim())},ni=async e=>{let t=await _({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},ri=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Ol=async e=>(await qe({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1),wo=async({cwd:e,branch:t})=>{let n=await lr({repoRoot:e,branch:t});if(a(n))return i(n.message);if(!n.value)return c("Remote branch missing, skipped pull",!1);let r=await Ol(e);if(a(r))return i(r.message);let o=await re.fetch({cwd:e,remote:Oe,branch:t});if(a(o))return i(`Failed to fetch ${t}
14
- ${o.message}`);let s=await re.pullRebase({cwd:e,remote:Oe,branch:t});return a(s)?i(`Failed during pull --rebase
15
- ${s.message}`):c("Pulled with rebase",!0)},oi=async e=>{let t=await qe({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?c("No staged changes",!1):t.exitCode===1?c("Has staged changes",!0):i(t.stderr.trim()||"Unable to inspect staged changes")},si=async e=>{let t=await mr(e);return a(t)?i(t.message):c("Checked detached HEAD state",t.value==="HEAD")}});import Mo from"node:fs";import Ul from"node:os";import Ge from"node:path";var ai,Lo,di,pr,We,Bl,ii,Mn,gr,ci,li,ui,Ve,Sf,pt=y(()=>{"use strict";St();C();ue();Ys();An();At();ai="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Lo=e=>Ge.join(rt,er,e),di=()=>Ge.join(Ul.homedir(),Fe),pr=()=>Ge.join(di(),"worktrees"),We=({repoRoot:e})=>{let t=Gs(e);return a(t)?i(t.message):c("Resolved state branch root",Ge.join(pr(),t.value))},Bl=e=>Ge.join(e,rt),ii=e=>Ge.join(Bl(e),er),Mn=e=>{try{return Mo.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return i(t instanceof Error?t.message:String(t))}},gr=()=>{let e=Mn(di());if(a(e))return i(`Ensure epiq home failed.
16
- `+e.message);let t=Mn(pr());return a(t)?i(`Ensure worktrees dir failed.
17
- `+t.message):c("Ensured epiq storage",!0)},ci=e=>{Mo.existsSync(e)&&(me.debug("[sync] remove path",e),Mo.rmSync(e,{recursive:!0,force:!0}))},li=(e,t)=>{for(let n of[ii(e),ii(t)]){let r=Mn(n);if(a(r))return i(r.message)}return c("Ensured state branch",void 0)},ui=async e=>{let t=await _({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return i(`ensure state branch is storage only failed
12
+ ${r.message}`):c("Created commit and resolved SHA",r.value.stdout.trim())},$l=async e=>{let t=await _({cwd:e,args:["rev-parse","--git-dir"]});if(a(t))return i(t.message);let n=t.value.stdout.trim();return c("Resolved git dir",Fn.isAbsolute(n)?n:Fn.resolve(e,n))},Wl=async e=>{let t=await $l(e);if(a(t))return i(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,d]of Object.entries(r))if(yr.existsSync(Fn.join(n,s)))return c("Checked for in-progress Git operation",d);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,d]of Object.entries(o))if(yr.existsSync(Fn.join(n,s)))return c("Checked for in-progress Git operation",d);return c("Checked for in-progress Git operation",null)},hr=async e=>{let t=await Wl(e);return a(t)?i(t.message):c("Checked for in-progress Git operation",t.value!==null)},Po=async({repoRoot:e})=>{let n=(await Xe({args:["remote","get-url",Ue],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},xr=async({repoRoot:e,branch:t})=>{let n=await Xe({args:["ls-remote","--heads",Ue,t],cwd:e});return n.exitCode!==0?i(n.stderr.trim()||`Unable to inspect remote branch ${Ue}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},Ir=async({repoRoot:e,branch:t})=>{let n=await Xe({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?c("Local branch exists",!0):n.exitCode===1?c("Local branch missing",!1):i(n.stderr.trim()||`Unable to inspect branch ${t}`)},On=e=>{try{return yr.realpathSync.native(e)}catch{return Fn.resolve(e)}},si=async({repoRoot:e,worktreeRoot:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let r=On(t),o=n.value.stdout.split(`
13
+ `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(On).includes(r);return c("Checked worktree registration",o)},Do=async e=>{let t=await Xe({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Er=async e=>{let t=await _({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved current branch",t.value.stdout.trim())},ii=async e=>{let t=await _({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},ai=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Hl=async e=>(await Xe({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1),Fo=async({cwd:e,branch:t})=>{let n=await xr({repoRoot:e,branch:t});if(a(n))return i(n.message);if(!n.value)return c("Remote branch missing, skipped pull",!1);let r=await Hl(e);if(a(r))return i(r.message);let o=await oe.fetch({cwd:e,remote:Ue,branch:t});if(a(o))return i(`Failed to fetch ${t}
14
+ ${o.message}`);let s=await oe.pullRebase({cwd:e,remote:Ue,branch:t});return a(s)?i(`Failed during pull --rebase
15
+ ${s.message}`):c("Pulled with rebase",!0)},di=async e=>{let t=await Xe({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?c("No staged changes",!1):t.exitCode===1?c("Has staged changes",!0):i(t.stderr.trim()||"Unable to inspect staged changes")},ci=async e=>{let t=await Er(e);return a(t)?i(t.message):c("Checked detached HEAD state",t.value==="HEAD")}});import Oo from"node:fs";import Vl from"node:os";import Je from"node:path";var ui,Uo,mi,br,ze,zl,li,Un,Nr,pi,gi,fi,Ye,Uf,yt=h(()=>{"use strict";Pt();C();pe();Zs();Dn();Dt();ui="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Uo=e=>Je.join(dt,cr,e),mi=()=>Je.join(Vl.homedir(),Oe),br=()=>Je.join(mi(),"worktrees"),ze=({repoRoot:e})=>{let t=Js(e);return a(t)?i(t.message):c("Resolved state branch root",Je.join(br(),t.value))},zl=e=>Je.join(e,dt),li=e=>Je.join(zl(e),cr),Un=e=>{try{return Oo.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return i(t instanceof Error?t.message:String(t))}},Nr=()=>{let e=Un(mi());if(a(e))return i(`Ensure epiq home failed.
16
+ `+e.message);let t=Un(br());return a(t)?i(`Ensure worktrees dir failed.
17
+ `+t.message):c("Ensured epiq storage",!0)},pi=e=>{Oo.existsSync(e)&&(ge.debug("[sync] remove path",e),Oo.rmSync(e,{recursive:!0,force:!0}))},gi=(e,t)=>{for(let n of[li(e),li(t)]){let r=Un(n);if(a(r))return i(r.message)}return c("Ensured state branch",void 0)},fi=async e=>{let t=await _({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return i(`ensure state branch is storage only failed
18
18
  `+t.message);let r=t.value.stdout.trim().split(`
19
- `).filter(Boolean).filter(d=>d!==rt);if(r.length===0)return c("State branch is storage-only",!1);let o=await _({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(a(o))return i(`Failed to clean storage branch
20
- ${o.message}`);let s=await Xt({cwd:e,message:"[epiq:repair-storage-branch]"});return a(s)?i(s.message):c("Cleaned storage branch",!0)},Ve=Eo(async(e=process.cwd())=>{let t=await _({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?i("Not inside a Git repository"):c("Resolved repo root",t.value.stdout.trim())},e=>Ge.resolve(e)),Sf=Eo(async e=>{let t=await _({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return i(t.message);let n=t.value.stdout.trim(),r=Ge.isAbsolute(n)?n:Ge.join(e,n);return c("Resolved git dir",r)},e=>Ge.resolve(e))});import Jt from"node:fs";import ko from"node:path";var pi,mi,_l,Po,jl,$l,Wl,Ln,Hl,zl,fr,gi,kn,fi,vr=y(()=>{"use strict";C();An();ir();ar();pt();At();pi=async e=>{if((await qe({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);me.info("Creating initial commit");let n=await re.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return a(n)?i(n.message):c("Created initial commit",!0)},mi=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",_l=async e=>{let t=await mr(e);if(a(t))return i(t.message);let n=await ni(e);return a(n)?i(n.message):c("Built sync commit message",`[sync|branch:${mi(t.value)}:sha:${mi(n.value)}]`)},Po=async({repoRoot:e,stateBranchName:t})=>{me.info(`Creating ${t}`);let n=await _({args:["commit-tree",ai,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return i(`Failed to create state branch commit
19
+ `).filter(Boolean).filter(d=>d!==dt);if(r.length===0)return c("State branch is storage-only",!1);let o=await _({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(a(o))return i(`Failed to clean storage branch
20
+ ${o.message}`);let s=await Zt({cwd:e,message:"[epiq:repair-storage-branch]"});return a(s)?i(s.message):c("Cleaned storage branch",!0)},Ye=To(async(e=process.cwd())=>{let t=await _({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?i("Not inside a Git repository"):c("Resolved repo root",t.value.stdout.trim())},e=>Je.resolve(e)),Uf=To(async e=>{let t=await _({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return i(t.message);let n=t.value.stdout.trim(),r=Je.isAbsolute(n)?n:Je.join(e,n);return c("Resolved git dir",r)},e=>Je.resolve(e))});import en from"node:fs";import Bo from"node:path";var yi,vi,ql,_o,Gl,Kl,Yl,Bn,Xl,Jl,Cr,hi,_n,xi,Sr=h(()=>{"use strict";C();Dn();fr();vr();yt();Dt();yi=async e=>{if((await Xe({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);ge.info("Creating initial commit");let n=await oe.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return a(n)?i(n.message):c("Created initial commit",!0)},vi=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",ql=async e=>{let t=await Er(e);if(a(t))return i(t.message);let n=await ii(e);return a(n)?i(n.message):c("Built sync commit message",`[sync|branch:${vi(t.value)}:sha:${vi(n.value)}]`)},_o=async({repoRoot:e,stateBranchName:t})=>{ge.info(`Creating ${t}`);let n=await _({args:["commit-tree",ui,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return i(`Failed to create state branch commit
21
21
  ${n.message}`);let r=n.value.stdout.trim(),o=await _({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return a(o)?i(`Failed to create ${t}
22
- ${o.message}`):c("Created state branch",!0)},jl=async({repoRoot:e,stateBranchName:t})=>{let n=await Ao({repoRoot:e});if(a(n))return i(`Ensure local state branch failed
23
- `+n.message);let r=n.value,o=r?await lr({repoRoot:e,branch:t}):c("No remote, no remote state branch",!1);if(a(o))return i(`Ensure local state branch failed
24
- `+o.message);let s=o.value;if(r&&s){let l=await re.fetch({cwd:e,remote:Oe,branch:t});if(a(l))return i(`Failed to fetch ${t} from remote
25
- ${l.message}`)}let d=await ur({repoRoot:e,branch:t});if(a(d))return i(`Ensure local state branch failed
26
- `+d.message);if(d.value)return c("Local state branch already exists",!1);if(s){let l=await _({args:["branch","--track",t,`${Oe}/${t}`],cwd:e});return a(l)?i(`Failed to create local ${t} from remote
27
- ${l.message}`):c("Created local state branch from remote",!0)}return Po({repoRoot:e,stateBranchName:t})},$l=async({repoRoot:e,branch:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let r=n.value.stdout.split(`
28
- `),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return c("Found worktree for branch",o)}return c("No worktree found for branch",null)},Wl=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Mn(ko.dirname(t));if(a(r))return i(`Failed to create state branch worktree
29
- `+r.message);Jt.existsSync(t)&&!Jt.existsSync(ko.join(t,".git"))&&(me.info("Removing broken state branch worktree path"),ci(t)),me.info("Creating state branch worktree");let o=await re.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(o)?i(`Failed to create state branch worktree
30
- ${o.message}`):c("Created state branch worktree",!0)},Ln=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await $l({repoRoot:e,branch:n});if(a(r))return i(r.message);let o=wn(t),s=r.value?wn(r.value):null;if(s&&s===o&&Jt.existsSync(s))return c("State branch already checked out in expected worktree",!1);if(s&&s!==o){me.info("Moving state branch worktree to expected location");let u=await re.worktreeRemove({cwd:e,worktreeRoot:s});if(a(u))return i(`Failed to remove existing state branch worktree
31
- ${u.message}`)}if(s&&!Jt.existsSync(s)){me.info("Pruning stale state branch worktree");let u=await re.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
32
- ${u.message}`)}let d=await ti({repoRoot:e,worktreeRoot:t});if(a(d))return i(d.message);let l=Jt.existsSync(t);if(d.value&&l)return c("State branch worktree already exists",!1);if(d.value&&!l){me.info("Pruning missing registered state branch worktree");let u=await re.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
33
- ${u.message}`)}return Wl({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Hl=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await mr(e);if(a(n))return i(n.message);if(n.value===t)return c("State branch already checked out",!1);(await qe({cwd:e,args:["rebase","--abort"]})).exitCode===0&&me.info("Aborted stale state branch rebase");let o=await re.checkout({cwd:e,branch:t});return a(o)?i(`Failed to checkout ${t}
34
- ${o.message}`):c("Checked out state branch",!0)},zl=async({repoRoot:e,stateBranchRoot:t})=>{let n=await To(t);if(a(n))return i(n.message);if(n.value)return c("State branch upstream already configured",!1);let r=await Ao({repoRoot:t});if(a(r))return i(r.message);if(!r.value)return c("No remote available for state branch upstream",!1);let o=Yt(e);if(a(o))return o;let s=o.value,d=await lr({repoRoot:t,branch:s});if(a(d))return i(d.message);if(!d.value)return c("Remote state branch missing; upstream will be configured on first push",!1);me.info(`Configuring ${s} upstream`);let l=await re.fetch({cwd:t,remote:Oe,branch:s});if(a(l))return i(`Failed to fetch ${s}
35
- ${l.message}`);let u=await re.setUpstream({cwd:t,branch:s,upstream:`${Oe}/${s}`});return a(u)?i(`Failed to set state branch upstream
36
- ${u.message}`):c("Configured state branch upstream",!0)},fr=async({stateBranchRoot:e,eventFileName:t})=>{let n=Lo(t),r=ko.join(e,n);if(!Jt.existsSync(r))return c("No event file to stage",void 0);let o=await re.stage({cwd:e,pathspec:[n]});return a(o)?i(`Failed to stage state branch event file
37
- ${o.message}`):c("Staged state branch event file",void 0)},gi=async({repoRoot:e,stateBranchRoot:t})=>{let n=await _l(e);return a(n)?i(`Create state branch sync commit failed
38
- `+n.message):Xt({cwd:t,message:n.value})},kn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await To(t);if(a(n))return i(n.message);let r=Yt(e);if(a(r))return r;let o=r.value,s=n.value?await re.push({cwd:t}):await re.push({cwd:t,remote:Oe,branch:o,setUpstream:!0});return a(s)?i(`Failed during state branch push
39
- ${s.message}`):c("Pushed state branch",!0)},fi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Yt(e);if(a(o))return o;let s=o.value,d=[gr(),await jl({repoRoot:e,stateBranchName:s}),await Ln({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Hl({stateBranchRoot:t,stateBranchName:s}),await ui(t),n?await zl({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of d){if(a(l))return i(l.message);r=r||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)}});import{WebSocket as Vl}from"ws";var ql,vi,yi=y(()=>{"use strict";ql=new Set,vi=e=>{let t=JSON.stringify(e);for(let n of ql)n.readyState===Vl.OPEN&&n.send(t)}});function Do(e){return e.context===M.WORKSPACE}function T(e){return e.context===M.TICKET}function hi(e){return e.context===M.TEXT}function Ke(e){return e.context===M.FIELD}function Pn(e){return e.context===M.FIELD_LIST}var M,Dn,Fo,Fn,Z=y(()=>{"use strict";M={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};Dn=e=>e.context===M.SWIMLANE,Fo=e=>e.context===M.BOARD,Fn=e=>e.context===M.COMMENT});var f,Y=y(()=>{"use strict";f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var xi=y(()=>{"use strict";Tt()});function yr(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var hr,wt,Qt=y(()=>{"use strict";hr=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",wt=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var Ii,bi,Ei=y(()=>{"use strict";Ii=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},bi=(e,t)=>t?e.get(t)??[]:[]});var Ni,Gl,Ci,Ri=y(()=>{"use strict";Qt();Ei();Ni=new WeakMap,Gl=e=>{let t=Ni.get(e);return t||(t=Ii(e),Ni.set(e,t)),t},Ci=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return bi(Gl(e),r).filter(s=>yr(r,s)>=n)}});var Kl,Si,Yl,Ai=y(()=>{"use strict";Qt();Ri();Kl={hint:"",hints:[],overlap:0,remainder:""},Si=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Kl;let o=Ci({wordList:r,inputToMatch:e,overlapThreshold:1});return Yl(t,o)},Yl=(e,t)=>{let n=t[0]??"",r=yr(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),d=r<(o??"").length,l=!!s,p=(l&&d?o:n)+(l&&d?":":" "),h=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:h}}});import{useSyncExternalStore as ev}from"react";var xr,Xl,Jl,ee,Ye,Ee=y(()=>{"use strict";xr={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Xl=new Set,Jl=()=>{for(let e of Xl)e()},ee=()=>xr,Ye=e=>(xr={...xr,...e},Jl(),xr)});function Ti(e){return!e||!Zl.test(e)?i(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Ue(e,t=Zt){if(e<0n)return i("Negative rank not allowed");let n=e.toString(16);return c("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Ne(e,t){if(!e&&!t)return Ue(Xe/2n,Zt);let n=e?Ti(e):c("Resolved lower bound",0n);if(a(n))return n;let r=t?Ti(t):c("Resolved upper bound",Xe);if(a(r))return r;let o=n.value,s=r.value;if(s<=o)return Ue(Xe/2n,Zt);let d=(o+s)/2n;return d===o||d===s?i("No rank space available between neighbors"):Ue(d,Zt)}function wi(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Xe*BigInt(r+1)/(t+1n),s=Ue(o,Zt);if(a(s))return s;n.push(s.value)}return c("Resolved evenly spaced ranks",n)}var Zt,Ql,Xe,Zl,en=y(()=>{"use strict";C();Zt=24n,Ql=Zt*4n,Xe=(1n<<Ql)-1n,Zl=/^[0-9a-f]+$/});import{ulid as eu}from"ulid";var Oo,Mi=y(()=>{"use strict";C();Je();en();Oo=(e,t)=>{let n=G(e),r=wi(n.length);if(a(r))return r;let o={};for(let s=0;s<n.length;s++){let d=n[s],l=r.value[s];if(!d||!l)return i("Unable to assign rebalance rank");o[d.id]=l}return c("Created rebalance event",{id:eu(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})}});var Lt,tu,Mt,b,ie=y(()=>{"use strict";Z();C();w();Je();Lt=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r)return i("Node not found");if(r.context===t)return c("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return c("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return i(`No ancestor found for context: ${t}`)},tu=(e,t)=>{let{nodes:n}=g(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Mt=(e,t)=>e?e.readonly?i({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:i("Node not found"),b={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return i("Contributor not found");if(n.userId&&n.userId!==t)return i("Contributor is already linked to another user");let r={...n,userId:t},o=ge(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?i("Unable to link contributor to user"):c("Linked contributor to user",r)},deleteNode(e){ge(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create comment, missing issue");if(!T(t))return i("Can only comment on issues");let n=ge(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?i("Unable to create comment"):c("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return i("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return i("Unable to edit comment, missing issue");if(!T(r))return i("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=ge(d=>({...d,comments:{...d.comments??{},[e]:o}}));return a(s)?i("Unable to edit comment"):c("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return i("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=ge(o=>({...o,comments:{...o.comments??{},[e]:n}}));return a(r)?i("Unable to delete comment"):c("Deleted comment",n)},getComment(e){return g().comments?.[e]},getCommentsByIssue(e){return Object.values(g().comments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=g(),r=n[e];if(!r)return i("Edit target node not found");let o=Mt(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return i("Rename target node not found");let r=Mt(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return G(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=g(),o=this.getNode(e),s=this.getNode(t);if(!o)return i("Node not found");if(!s)return i("Target parent not found");if(r===e)return i("Cannot move root node");if(e===t)return i("Cannot move node into itself");let d=Mt(o,"move");if(d)return d;if(tu(t,e))return i("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=g(),o=this.getNode(e);if(!o)return i("Node not found");if(r===e)return i("Cannot delete root node");let s=new Set,d=u=>{let m=t[u];if(!(!m||s.has(u))){s.add(u);for(let p of G(m.id))d(p.id)}};d(e);let l={...structuredClone(t)};for(let u of s){if(!l[u])return i("Unable to locate node to delete");l[u]={...l[u],isDeleted:!0}}return n?(x({nodes:l}),c("Successfully tomb stoned",o)):i("Unable to delete undefined")},createContributor(e){let t=ge(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?i("Unable to create contributor"):c("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return i("Unable to assign contributor, missing contributor");if(!r)return i("Unable to assign contributor, missing target");let o=Mt(r,"edit");if(o)return o;if(!T(r))return i("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return i("Contributor already assigned");let d={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(d),c("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return i("Unable to unassign, missing contributor");if(!r)return i("Unable to unassign, missing target");let o=Mt(r,"edit");if(o)return o;if(!T(r))return i("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return c("Issue is not assigned to that contributor",{assignee:t});let d={...r,props:{...r.props,assignees:s.filter(l=>l!==t)}};return this.updateNode(d),c("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return i("Unable to add tag, missing tag");if(!r)return i("Unable to add tag, missing target");let o=Mt(r,"edit");if(o)return o;if(!T(r))return i("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return i("Tag already assigned");let d={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(d),c("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return i("Unable to remove tag, missing tag");if(!r)return i("Unable to remove tag, missing target");let o=Mt(r,"edit");if(o)return o;if(!T(r))return i("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return c("Issue is not tagged with that tag",{tag:t});let d={...r,props:{...r.props,tags:s.filter(l=>l!==t)}};return this.updateNode(d),c("Tag removed",{tag:t})},createTag(e){let t=ge(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?i("Could not create tag"):c("Tag created",e)},createNode(e){let t=ge(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?i("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return i("Failed to locate node");let n={...t,readonly:!0},r=ge(o=>({...o,nodes:{...o.nodes,[e]:n}}));return a(r)?i(r.message):c("Locked node",n)},updateNode(e){let t=ge(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?t:c("Updated node",e)},getContributor(e){return g().contributors[e]},getTag(e){return g().tags[e]},getNode(e){return g().nodes[e]},getSiblings(e){return G(e)}}});var oe,tn=y(()=>{"use strict";oe={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments"}});var kt,Li,Ir=y(()=>{"use strict";kt=e=>e.slice(-7).toUpperCase(),Li=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?kt(e).includes(n):!0}});var fe,nn=y(()=>{"use strict";Z();Ir();fe={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:M.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:kt(e)},context:M.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:M.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:d=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:M.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:d}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:M.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:kt(e)},context:M.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:M.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:d=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:M.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:d})}});var ve,R,Ce=y(()=>{"use strict";ve={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},R={accent:ve.cyan,accent2:ve.magenta,primary:ve.white,secondary:ve.grayDark,secondary2:ve.grayLight,gray:ve.gray,green:ve.green,yellow:ve.yellow,red:ve.red}});var I,rn,br=y(()=>{"use strict";Ce();I={red:ve.red,yellow:ve.yellow,green:ve.green,blue:ve.blue,magenta:ve.magenta,cyan:ve.cyan},rn={urgent:I.red,critical:I.red,important:I.red,blocker:I.red,asap:I.red,immediate:I.red,fail:I.red,failure:I.red,broken:I.red,bug:I.red,error:I.red,incident:I.red,outage:I.red,production:I.red,crash:I.red,security:I.red,warning:I.yellow,warn:I.yellow,risky:I.yellow,risk:I.yellow,attention:I.yellow,pending:I.yellow,review:I.yellow,"needs-review":I.yellow,qa:I.yellow,testing:I.yellow,test:I.yellow,validate:I.yellow,verification:I.yellow,staging:I.yellow,check:I.yellow,"follow-up":I.yellow,followup:I.yellow,waiting:I.yellow,blocked:I.yellow,hold:I.yellow,done:I.green,complete:I.green,completed:I.green,success:I.green,ok:I.green,stable:I.green,resolved:I.green,fixed:I.green,closed:I.green,merged:I.green,released:I.green,deployed:I.green,approved:I.green,verified:I.green,working:I.green,healthy:I.green,pass:I.green,passing:I.green,info:I.blue,information:I.blue,note:I.blue,docs:I.blue,documentation:I.blue,doc:I.blue,guide:I.blue,help:I.blue,explanation:I.blue,detail:I.blue,details:I.blue,context:I.blue,design:I.blue,discussion:I.blue,proposal:I.blue,idea:I.blue,feature:I.magenta,enhancement:I.magenta,improvement:I.magenta,refactor:I.magenta,refactoring:I.magenta,cleanup:I.magenta,optimize:I.magenta,optimization:I.magenta,perf:I.magenta,performance:I.magenta,upgrade:I.magenta,migration:I.magenta,modernize:I.magenta,debt:I.magenta,todo:I.cyan,next:I.cyan,planned:I.cyan,plan:I.cyan,future:I.cyan,backlog:I.cyan,investigate:I.cyan,explore:I.cyan,prototype:I.cyan}});import ki from"chalk";var Bo,Pi,Uo,Di,nu,ru,Fi,ou,su,On,Re,Oi,Ui,Er,iu,au,Nr,ot=y(()=>{"use strict";br();Bo={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Pi=(e,t,n)=>Math.max(t,Math.min(n,e)),Uo=(e,t,n)=>e+(t-e)*n,Di=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},nu=e=>e.toLowerCase().trim(),ru=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,d=e/60,l=s*(1-Math.abs(d%2-1)),u=0,m=0,p=0;d>=0&&d<1?(u=s,m=l):d>=1&&d<2?(u=l,m=s):d>=2&&d<3?(m=s,p=l):d>=3&&d<4?(m=l,p=s):d>=4&&d<5?(u=l,p=s):(u=s,p=l);let h=o-s/2;return[Math.round((u+h)*255),Math.round((m+h)*255),Math.round((p+h)*255)]},Fi=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,ou=(e,t,n)=>{let r=Pi(n,0,1);return[Math.round(Uo(e[0],t[0],r)),Math.round(Uo(e[1],t[1],r)),Math.round(Uo(e[2],t[2],r))]},su=(e,t,n)=>ou(e,t,n),On=e=>{let n=Di(e)%360,r=ru(n,Bo.stringColor.saturation,Bo.stringColor.lightness);return Fi(r)},Re=(e,t=rn)=>{let n=nu(e);return n&&t[n]?t[n]:On(n)},Oi=e=>{let t=Bo.gradient.stops,n=Pi(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,s=Math.min(Math.floor(o),r-1),d=o-s;return su(t[s],t[s+1],d)},Ui=e=>Fi(Oi(e)),Er=e=>Di(e.toLowerCase().trim())/4294967295,iu=e=>{let t=Er(e);return Oi(t)},au=e=>{let[t,n,r]=iu(e);return{normal:o=>ki.bgRgb(t,n,r).black(o),cursor:o=>ki.bgRgb(t,n,r).white.bold(o)}},Nr=e=>au(e).normal(` ${e} `)});import{decodeTime as Bi}from"ulid";var Cr,_i,on,sn=y(()=>{"use strict";C();Cr=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"},_i=e=>{try{return c("Decoded date",new Date(Bi(e)))}catch(t){return i("Decoding failed + "+t.message)}},on=e=>{if(!e?.id)return null;try{return Bi(e.id)}catch{return null}}});import Pt from"chalk";import ji from"string-width";import{decodeTime as du}from"ulid";var cu,lu,$i,uu,mu,pu,gu,fu,vu,yu,Wi,Hi,_o=y(()=>{"use strict";ie();w();ot();sn();cu=(e,t)=>e+" ".repeat(Math.max(0,t-ji(e))),lu=(e,t)=>" ".repeat(Math.max(0,t-ji(e)))+e,$i=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),uu=(e,t)=>t?e<t?"up":e>t?"down":null:null,mu=(e,t)=>{let n=b.getNode(e.payload.parent),r=n?Pt.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=uu(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},pu=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Pt.bgHex(Re(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Pt.bgHex(Re(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Pt.hex(Re(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Pt.hex(Re(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;default:return""}},gu=e=>{let t=Cr(du(e));return Pt.gray(lu(t,8))},fu=12,vu=e=>cu(`${e}`,fu),yu=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?t.name:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=b.getNode(e.payload.parent);return t?`to ${t.title}`:""}default:return""}},Wi=e=>[$i(e.action),yu(e)].filter(Boolean).join(" "),Hi=(e,t)=>{let n=gu(e.id),r=vu(e.userName),o=Pt.dim("\u203A"),s=e.action==="move.node"?mu(e,t):[$i(e.action),pu(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`}});import{createHash as hu}from"node:crypto";var xu,Iu,Se,Un=y(()=>{"use strict";xu="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Iu=e=>{let t=hu("sha256").update(e).digest(),n=0n;for(let o=0;o<16;o++)n=n<<8n|BigInt(t[o]);let r="";for(let o=0;o<26;o++){let s=BigInt((25-o)*5);r+=xu[Number(n>>s&31n)]}return r},Se=(e,t)=>Iu(`${e}:virtual:${t}`)});var bu,Eu,Nu,Cu,Ru,jo,zi,Vi,Su,qi=y(()=>{"use strict";_o();Z();C();tn();ie();nn();w();en();Un();bu=e=>Se(e,"comments"),Eu=e=>Se(e,"description"),Nu=e=>Se(e,"assignees"),Cu=e=>Se(e,"tags"),Ru=e=>Se(e,"history"),jo=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:d="horizontal"})=>{let l=b.getNode(e);if(!l){let p=b.createNode({...fe.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:d});return a(p)?p:c("Virtual field created",void 0)}if(!Ke(l))return i(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==r||l.props.value!==o||l.readonly!==s||l.childRenderAxis!==d))return c("Virtual field unchanged",void 0);let m=b.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:s,childRenderAxis:d});return a(m)?m:c("Virtual field updated",void 0)},zi=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let d=b.getNode(e);if(!d){let m=b.createNode({...fe.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return a(m)?m:c("Virtual field list created",void 0)}if(!Pn(d))return i(`Existing virtual node ${e} is not a field list`);if(!(d.title!==t||d.parentNodeId!==n||d.rank!==r||d.readonly!==o||d.childRenderAxis!==s))return c("Virtual field list unchanged",void 0);let u=b.updateNode({...d,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(u)?u:c("Virtual field list updated",void 0)},Vi=e=>{let t=Ue(Xe/4n),n=Ue(Xe/2n),r=Ue(Xe*3n/4n),o=Ue(Xe*7n/8n),s=Ue(Xe*13n/16n);if(a(t))return t;if(a(n))return n;if(a(r))return r;if(a(o))return o;if(a(s))return s;let d=jo({id:Eu(e.id),name:oe.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(d))return d;let l=zi({id:Nu(e.id),name:oe.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(l))return l;let u=zi({id:Cu(e.id),name:oe.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(a(u))return u;let m=jo({id:bu(e.id),name:oe.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(m))return m;let p=jo({id:Ru(e.id),name:oe.HISTORY,parentNodeId:e.id,rank:s.value,value:Su(e),readonly:!0,childRenderAxis:"vertical"});return a(p)?p:c("Ticket virtual nodes materialized",void 0)},Su=e=>{let t=[...e.log].reverse(),n=new Map;for(let r of t){let o=n.get(r.action)??[];o.push(r.payload),n.set(r.action,o)}return t.map(r=>Hi(r,n.get(r.action)??[])).join(`
40
- `)}});var Au,ae,Rr,an=y(()=>{"use strict";Au=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ae,Rr]=Au});function ft(e,t=!1){let n=Du[e.action](e);if(a(n))return n;let r=Pu(e,t);return r||n}var D,Gi,Tu,wu,Mu,$o,Lu,ku,Pu,Du,vt,yt=y(()=>{"use strict";Z();C();tn();ie();nn();w();qi();an();D=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Gi=e=>{let t=b.getNode(e);if(!t||!T(t)||t.isDeleted)return null;let n=Vi(t);return a(n)?n:null},Tu=e=>{for(let t of e){let n=Gi(t);if(n)return n;let r=g().nodes[t]?.parentNodeId;if(!r)continue;let o=Gi(r);if(o)return o}return null},wu=(e,t)=>{let n=b.getNode(e);n&&b.updateNode({...n,log:[...n.log??[],t]})},Mu=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},$o=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":return[e.payload.issue];case"delete.node":case"edit.description":return Mu(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"create.contributor":case"link.contributor.user":default:return[]}},Lu=e=>{ge(t=>({...t,eventLog:[...t.eventLog,e]}))},ku=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?D("Invalid user ID format",e):c("Valid user",null)},Pu=(e,t)=>{let n=ku(e);if(a(n))return n;let r=[...new Set($o(e))];t||(r.forEach(s=>wu(s,e)),Lu(e));let o=Tu(r);return o||null},Du={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=fe.workspace(t,n,r),s=Bn(o);if(a(s))return D(s.message,e);let d=b.createNode(o);return a(d)?D(d.message??"Failed to initialize workspace",e):Do(d.value)?c("Workspace initialized",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=b.createNode(fe.workspace(t,n,r));return a(o)?D(o.message??"Failed to add workspace",e):Do(o.value)?c("Added workspace",{action:e.action,result:o.value}):i("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=b.createNode(fe.board(t,n,r,o));return a(s)?D(s.message??"Unable to create board",e):Fo(s.value)?c("Added board",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=b.createNode(fe.swimlane(t,n,r,o));return a(s)?D(s.message??"Unable to create swimlane",e):Dn(s.value)?c("Added swimlane",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=b.createNode(fe.ticket(t,n,r,o));return a(s)?D(s.message??"Unable to create issue",e):T(s.value)?c("Added issue",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,d=b.createNode(fe.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(oe.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?D(d.message??`Unable to create field: ${n}`,e):Ke(d.value)?c("Added field",{action:e.action,result:d.value}):i("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!b.getNode(t))return D(`Unable to locate node with id ${t}`,e);let o=b.renameNode(t,n);return a(o)?D(o.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=b.tombstoneNode(t);return a(n)?D(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=b.createTag({id:t,name:n});return a(r)?D(r.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=b.createContributor({id:t,name:n});return a(r)?D(r.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=b.tag(t,n);return a(r)?D(r.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=b.untag(t,n);return a(r)?D(r.message??"Unable to untag issue",e):c("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=b.assign(t,n);return a(r)?D(r.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=b.unassign(t,n);return a(r)?D(r.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?D(o.message??"Failed to move node",e):c("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=b.editValue(t,n);return a(r)?D(r.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return D("Unable to locate issue",e);if(!T(o))return D("Can only close issues",e);let s=b.getNode(ae);if(!s)return D("Unable to locate target swimlane",e);if(n!==s.id)return D("Close target must be closed swimlane",e);let d=b.moveNodeToRank({id:t,parentId:n,rank:r});return a(d)?D(d.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return D("Unable to locate issue",e);if(!T(o))return D("Can only reopen issues",e);let s=b.getNode(ae);if(!s)return D("Unable to locate closed swimlane",e);if(n===s.id)return D("Cannot reopen issue into closed swimlane",e);if(!b.getNode(n))return D("Reopen parent no longer exists",e);let l=b.moveNodeToRank({id:t,parentId:n,rank:r});return a(l)?D(l.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=b.lockNode(t);return a(n)?D(n.message??"Unable to lock node",e):c("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let s=b.getNode(r);if(!s)return D(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return D(`Node ${r} is not child of ${t}`,e);let d=b.updateNode({...s,rank:o});if(a(d))return D(d.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=b.createComment({id:t,issue:n,authorId:r,authorName:b.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return a(s)?D(s.message??"Unable to add comment",e):c("Comment added",{action:e.action,result:{id:t,issue:n,author:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=e.payload,o=b.getComment(t);if(!o)return D("Unable to locate comment",e);if(o.issue!==n)return D("Comment does not belong to issue",e);let s=b.editComment(t,r);return a(s)?D(s.message??"Unable to edit comment",e):c("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=b.getComment(t);if(!r)return D("Unable to locate comment",e);if(r.issue!==n)return D("Comment does not belong to issue",e);let o=b.deleteComment(t);return a(o)?D(o.message??"Unable to delete comment",e):c("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=b.linkUserId({contributorId:t,userId:e.userId});return a(n)?D(n.message??"Unable to link contributor",e):c("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};vt=e=>e.map(t=>ft(t))});import Sr from"node:fs";import Ho from"node:path";import{decodeTime as Fu}from"ulid";import{z as Wo}from"zod";function Vo(e){let t=Cn(e);if(!Sr.existsSync(t))return c("No events found",[]);let n=Sr.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Ho.join(t,o)),r=[];for(let o of n){let s=Wu(o);if(a(s))return i(s.message);r.push(...s.value)}return c("All events loaded",Hu(r))}function Dt(e){let t=Vo(e);return a(t)?i(t.message):zo(t.value)}function Ki(e,t){let n=Vo(e);if(a(n))return i(n.message);let{appliedEvents:r,unappliedEvents:o}=zu(n.value,t),s=zo(r);if(a(s))return i(s.message);let d=zo(o);return a(d)?i(d.message):c("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function Yi(e=process.cwd()){let t=Vo(e);return a(t)?i(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Ou,Uu,Bu,_u,ju,$u,zo,Wu,Hu,zu,dn=y(()=>{"use strict";C();ue();He();Ou=Wo.object({userId:Wo.string().min(1).default("unknown"),userName:Wo.string().min(1).default("unknown")}),Uu=e=>{let[t,n]=Ho.basename(e,".jsonl").split("."),r=Ou.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):i(`Invalid event file name ${Ho.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Bu=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?i(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?i("Invalid persisted event: action key is missing or invalid"):c("Resolved persisted action",t[0])},_u=(e,t)=>t in e,ju=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),$u=e=>{let{userId:t,userName:n,...r}=e,o=Bu(r);if(a(o))return i(o.message);let s=o.value,d=e.id?.[0];return d?_u(r,s)?c("Decoded persisted event",ju({id:d,action:s,payload:r[s],userId:t,userName:n})):i(`Persisted event is missing payload for action: ${s}`):i("Persisted event is missing id")},zo=e=>{let t=[];for(let n of e){let r=$u(n);if(a(r))return i(`Failed to decode event ${n.id?.[0]??"<unknown>"}: ${r.message}`);t.push(r.value)}return c("Decoded reconstructed events",t)},Wu=e=>{if(!Sr.existsSync(e))return c("Event file missing",[]);let t=Uu(e);if(a(t))return i(t.message);let n=Sr.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
41
- `)){let s=o.trim();if(!s)continue;let d;try{d=JSON.parse(s)}catch{return i(`Failed to parse event JSON from ${e}: ${s}`)}let l=qo(d);if(a(l))return i(`${l.message} in ${e}: ${s}`);r.push({...l.value,userId:t.value.userId,userName:t.value.userName})}return c("Parsed persisted events file",r)};Hu=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],h=m.id[1]??null;t.set(p,m);let N=n.get(h)??[];N.push(m),n.set(h,N)}for(let m of n.values())m.sort((p,h)=>p.id[0].localeCompare(h.id[0]));let r=[],o=new Set,s=m=>{let p=m.id[0];if(o.has(p))return;r.push(m),o.add(p);let h=n.get(p)??[];for(let N of h)s(N)},d=n.get(null)??[];for(let m of d)s(m);let l=e.filter(m=>{let p=m.id[0],h=m.id[1]??null;return!o.has(p)&&h!==null&&!t.has(h)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of l)s(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)s(m);return r},zu=(e,t)=>{let n=new Set,r=[],o=[];for(let s of e){let d=s.id[0],l=s.id[1],u=!1;try{u=Fu(d)<t}catch{u=!1}!u||l&&n.has(l)?(n.add(d),o.push(s)):r.push(s)}return{appliedEvents:r,unappliedEvents:o}}});var Xi,Ji=y(()=>{"use strict";Xi=e=>({action:e.action,payload:e.payload})});import Vu from"node:fs";import qu from"node:path";import{decodeTime as Gu,monotonicFactory as Ku}from"ulid";import{z as _n}from"zod";function Ar({event:e,rootDir:t}){try{let n=qs(t);if(a(n))return n;let r=Zu(t,{userId:e.userId,userName:e.userName});if(a(r))return r;let o=Yi(t);if(a(o))return i(o.message);let s=o.value?Qi(Math.max(Date.now(),Gu(o.value)+1)):Qi(),d=em(Xi(e),[s,o.value]);return a(d)?i(d.message):(Vu.appendFileSync(r.value,`${JSON.stringify(d.value)}
42
- `,"utf8"),c("Event persisted",{path:r.value,entry:d.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return i(`Failed to persist event: ${r}`)}}var ea,Qi,Yu,Xu,qo,Zi,Ju,Qu,X,Ft,Zu,em,He=y(()=>{"use strict";C();Ee();ue();dn();Ji();ea=1,Qi=Ku(),Yu=_n.tuple([_n.string().min(1),_n.string().min(1).nullable()]),Xu=_n.looseObject({v:_n.literal(ea),id:Yu}),qo=e=>{let t=Xu.safeParse(e);return t.success?c("Parsed persisted event",t.data):i(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Zi=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",Ju=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),Qu=e=>e.trim().length>0&&e.length<=80,X=()=>{let{userName:e,userId:t}=ee();return e?t?Ju(t)?Qu(e)?c("Successfully resolved actor ID",{userId:t,userName:e}):i("Invalid user name in config"):i("Invalid user ID in config"):i("User ID not configured"):i("User name not configured")},Ft=({userId:e,userName:t})=>`${Zi(e)}.${Zi(t)}.jsonl`,Zu=(e,{userId:t,userName:n})=>{let r=Ft({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return i(`Invalid event log file name: ${r}`);let s=qu.join(Cn(e),r);return c("Successfully resolved event log path",s)},em=(e,t)=>{let n={[e.action]:e.payload,v:ea,id:t};return qo(n)}});import{ulid as tm}from"ulid";function ta(e,t){let n=ft(e);if(n.status!==ut.Success)return n;let r=Ar({event:e,rootDir:t});return a(r)?r:n}function B(e,t){if(e.length===0||!e[0])return i("No events provided");let n=nm(e[0],t);if(a(n))return n;let r=e.map(s=>ta(s,t)),o=r.filter(a);return o.length>0?i("Materialize and persist failed: "+o.map(s=>s.message).join(", ")):c("Materialization succeeded",r.map(s=>s.value))}var nm,Ot=y(()=>{"use strict";C();ie();yt();He();nm=(e,t)=>{if(e.action==="create.contributor")return c("Contributor already being created",void 0);if(b.getContributor(e.userId))return c("Contributor exists",void 0);let n={id:tm(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},r=ta(n,t);return a(r)?i(r.message):c("Contributor created",void 0)}});var na,Tr,G,ra,oa,Ut,cn,Je=y(()=>{"use strict";Mi();Ot();C();w();en();na=e=>Tr(G(e),{at:"end"}),Tr=(e,t={at:"end"})=>{let n=r=>a(r)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(Ne(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(Ne(void 0,r.rank)):i("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(Ne(r.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let r=ra(e,t.sibling);if(r<0)return i("Sibling not found");let o=r>0?e[r-1]:void 0,s=e[r];return s?n(Ne(o?.rank,s.rank)):i("Sibling not found")}case"after":{let r=ra(e,t.sibling);if(r<0)return i("Sibling not found");let o=e[r],s=r<e.length-1?e[r+1]:void 0;return o?n(Ne(o.rank,s?.rank)):i("Sibling not found")}}},G=e=>Object.values(g().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),ra=(e,t)=>e.findIndex(n=>n.id===t),oa=(e,t,n={at:"end"})=>Tr(G(t).filter(r=>r.id!==e),n),Ut=(e,t,n,r,o)=>{let s=oa(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return c("Resolved rank",s.value.rank);let d=Oo(e,r);if(a(d))return d;let l=B([d.value],o);if(a(l))return l;let u=oa(t,e,n);return a(u)?u:u.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",u.value.rank)},cn=(e,t,n)=>{let r=na(e);if(a(r))return r;if(!r.value.needsRebalance)return c("Resolved rank",r.value.rank);let o=Oo(e,t);if(a(o))return o;let s=B([o.value],n);if(a(s))return s;let d=na(e);return a(d)?d:d.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",d.value.rank)}});var P,sa,ia,Be=y(()=>{"use strict";w();P={exit(){process.exit(0)},enterChildNode(){let e=g(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=V(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||P.navigate({contextNode:o,selectedIndex:V(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=g();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=V(n.id),o=r.findIndex(({id:d})=>d===e.id),s=r.length===0?-1:o>=0?o:0;P.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>sa(1),navigateToPreviousItem:()=>sa(-1),navigateToNextContainer:()=>ia(1),navigateToPreviousContainer:()=>ia(-1),navigate:({contextNode:e,selectedIndex:t})=>{x({contextNodeId:e.id,selectedIndex:t})}},sa=e=>{let{selectedIndex:t,contextNode:n}=g(),r=V(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;P.navigate({selectedIndex:s,contextNode:n})},ia=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=g();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=V(o.id),d=s.findIndex(N=>N.id===t.id);if(d<0)return;let l=s.at(d+e)??s.at(0);if(!l)return;let u=V(l.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),h=u.length?p:-1;P.navigate({contextNode:l,selectedIndex:h})}});var da,ca,rm,wr,la,aa,om,ua,ma=y(()=>{"use strict";Z();C();Je();w();Be();da=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),ca=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},rm=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&Ke(t)&&t.childRenderAxis==="vertical"},wr=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r||r.isDeleted)return!1;let o=G(r.id);return P.navigate({contextNode:r,selectedIndex:da(t,o.length)}),!0},la=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return wr(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let d=G(o.id).findIndex(l=>l.id===n.id);return d>=0?(P.navigate({contextNode:o,selectedIndex:d}),!0):la(o.id)},aa=e=>{let{nodes:t}=g(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),la(n))return!0;n=t[n]?.parentNodeId}return!1},om=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},ua=e=>{let{nodes:t,rootNodeId:n}=g();if(rm(e.contextNodeId)&&wr(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(om(e.selectedNodeId)&&e.selectedNodeId&&aa(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(wr(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&wr(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(aa(e.contextNodeId))return c("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return i("Unable to restore navigation");let o=G(r.id);return P.navigate({contextNode:r,selectedIndex:da(e.selectedIndex,o.length)}),c("Restored navigation to root",null)}});import{monotonicFactory as sm,ulid as st}from"ulid";function im(){let e=_e();if(a(e))return i("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)throw new Error("No workspace found in event log");let[r]=V(n.id),[o]=r?V(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return c("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?c("Resolved boot nav target",{contextNode:r,selectedIndex:0}):n?c("Resolved boot nav target",{contextNode:n,selectedIndex:0}):c("Resolved boot nav target",{contextNode:t.nodes[t.rootNodeId],selectedIndex:0})}function am(){let e=im();return a(e)?e:P.navigate(e.value)}function pa({userId:e,userName:t}){let n=jn(),r=jn(),o=jn(),s=jn(),d=jn(),l=Ne(void 0,void 0);if(a(l))return l;let u=Ne(void 0,void 0);if(a(u))return u;let m=Ne(u.value,void 0);if(a(m))return m;let p=Ne(void 0,void 0);if(a(p))return p;let h=Ne(p.value,void 0);if(a(h))return h;let N=Ne(h.value,void 0);if(a(N))return N;let S=Ne(void 0,void 0);return a(S)?S:c("Created default events",[{id:st(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:st(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:st(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:st(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:h.value}},{id:st(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:r,rank:N.value}},{id:st(),userId:e,userName:t,action:"add.board",payload:{id:Rr,name:"Closed",parent:n,rank:m.value}},{id:st(),userId:e,userName:t,action:"add.swimlane",payload:{id:ae,name:"Closed",parent:Rr,rank:S.value}},{id:st(),userId:e,userName:t,action:"lock.node",payload:{id:Rr}},{id:st(),userId:e,userName:t,action:"lock.node",payload:{id:ae}}])}function $n(e){if(!e.length){let r=fe.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=Bn(r);return a(o)?o:(x({hasProjectDefinition:!1,mode:f.DEFAULT}),c("Booted uninitialized workspace placeholder",null))}if(!e.some(r=>r.action==="init.workspace"))return i("Initialized Epiq project has no workspace init event");let n=vt(e).filter(a);return n.length>0?i(`Materializing failed:
22
+ ${o.message}`):c("Created state branch",!0)},Gl=async({repoRoot:e,stateBranchName:t})=>{let n=await Po({repoRoot:e});if(a(n))return i(`Ensure local state branch failed
23
+ `+n.message);let r=n.value,o=r?await xr({repoRoot:e,branch:t}):c("No remote, no remote state branch",!1);if(a(o))return i(`Ensure local state branch failed
24
+ `+o.message);let s=o.value;if(r&&s){let l=await oe.fetch({cwd:e,remote:Ue,branch:t});if(a(l))return i(`Failed to fetch ${t} from remote
25
+ ${l.message}`)}let d=await Ir({repoRoot:e,branch:t});if(a(d))return i(`Ensure local state branch failed
26
+ `+d.message);if(d.value)return c("Local state branch already exists",!1);if(s){let l=await _({args:["branch","--track",t,`${Ue}/${t}`],cwd:e});return a(l)?i(`Failed to create local ${t} from remote
27
+ ${l.message}`):c("Created local state branch from remote",!0)}return _o({repoRoot:e,stateBranchName:t})},Kl=async({repoRoot:e,branch:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let r=n.value.stdout.split(`
28
+ `),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return c("Found worktree for branch",o)}return c("No worktree found for branch",null)},Yl=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Un(Bo.dirname(t));if(a(r))return i(`Failed to create state branch worktree
29
+ `+r.message);en.existsSync(t)&&!en.existsSync(Bo.join(t,".git"))&&(ge.info("Removing broken state branch worktree path"),pi(t)),ge.info("Creating state branch worktree");let o=await oe.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(o)?i(`Failed to create state branch worktree
30
+ ${o.message}`):c("Created state branch worktree",!0)},Bn=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await Kl({repoRoot:e,branch:n});if(a(r))return i(r.message);let o=On(t),s=r.value?On(r.value):null;if(s&&s===o&&en.existsSync(s))return c("State branch already checked out in expected worktree",!1);if(s&&s!==o){ge.info("Moving state branch worktree to expected location");let u=await oe.worktreeRemove({cwd:e,worktreeRoot:s});if(a(u))return i(`Failed to remove existing state branch worktree
31
+ ${u.message}`)}if(s&&!en.existsSync(s)){ge.info("Pruning stale state branch worktree");let u=await oe.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
32
+ ${u.message}`)}let d=await si({repoRoot:e,worktreeRoot:t});if(a(d))return i(d.message);let l=en.existsSync(t);if(d.value&&l)return c("State branch worktree already exists",!1);if(d.value&&!l){ge.info("Pruning missing registered state branch worktree");let u=await oe.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
33
+ ${u.message}`)}return Yl({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Xl=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Er(e);if(a(n))return i(n.message);if(n.value===t)return c("State branch already checked out",!1);(await Xe({cwd:e,args:["rebase","--abort"]})).exitCode===0&&ge.info("Aborted stale state branch rebase");let o=await oe.checkout({cwd:e,branch:t});return a(o)?i(`Failed to checkout ${t}
34
+ ${o.message}`):c("Checked out state branch",!0)},Jl=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Do(t);if(a(n))return i(n.message);if(n.value)return c("State branch upstream already configured",!1);let r=await Po({repoRoot:t});if(a(r))return i(r.message);if(!r.value)return c("No remote available for state branch upstream",!1);let o=Qt(e);if(a(o))return o;let s=o.value,d=await xr({repoRoot:t,branch:s});if(a(d))return i(d.message);if(!d.value)return c("Remote state branch missing; upstream will be configured on first push",!1);ge.info(`Configuring ${s} upstream`);let l=await oe.fetch({cwd:t,remote:Ue,branch:s});if(a(l))return i(`Failed to fetch ${s}
35
+ ${l.message}`);let u=await oe.setUpstream({cwd:t,branch:s,upstream:`${Ue}/${s}`});return a(u)?i(`Failed to set state branch upstream
36
+ ${u.message}`):c("Configured state branch upstream",!0)},Cr=async({stateBranchRoot:e,eventFileName:t})=>{let n=Uo(t),r=Bo.join(e,n);if(!en.existsSync(r))return c("No event file to stage",void 0);let o=await oe.stage({cwd:e,pathspec:[n]});return a(o)?i(`Failed to stage state branch event file
37
+ ${o.message}`):c("Staged state branch event file",void 0)},hi=async({repoRoot:e,stateBranchRoot:t})=>{let n=await ql(e);return a(n)?i(`Create state branch sync commit failed
38
+ `+n.message):Zt({cwd:t,message:n.value})},_n=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Do(t);if(a(n))return i(n.message);let r=Qt(e);if(a(r))return r;let o=r.value,s=n.value?await oe.push({cwd:t}):await oe.push({cwd:t,remote:Ue,branch:o,setUpstream:!0});return a(s)?i(`Failed during state branch push
39
+ ${s.message}`):c("Pushed state branch",!0)},xi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Qt(e);if(a(o))return o;let s=o.value,d=[Nr(),await Gl({repoRoot:e,stateBranchName:s}),await Bn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Xl({stateBranchRoot:t,stateBranchName:s}),await fi(t),n?await Jl({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of d){if(a(l))return i(l.message);r=r||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)}});import{WebSocket as Ql}from"ws";var Zl,Ii,Ei=h(()=>{"use strict";Zl=new Set,Ii=e=>{let t=JSON.stringify(e);for(let n of Zl)n.readyState===Ql.OPEN&&n.send(t)}});function jo(e){return e.context===k.WORKSPACE}function w(e){return e.context===k.TICKET}function bi(e){return e.context===k.TEXT}function Qe(e){return e.context===k.FIELD}function jn(e){return e.context===k.FIELD_LIST}var k,$n,$o,Wn,ne=h(()=>{"use strict";k={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};$n=e=>e.context===k.SWIMLANE,$o=e=>e.context===k.BOARD,Wn=e=>e.context===k.COMMENT});var f,X=h(()=>{"use strict";f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var Ni=h(()=>{"use strict";Ft()});function Rr(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Hn,xt,tn=h(()=>{"use strict";Hn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",xt=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var Ci,Si,Ri=h(()=>{"use strict";Ci=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},Si=(e,t)=>t?e.get(t)??[]:[]});var Ai,eu,Ti,wi=h(()=>{"use strict";tn();Ri();Ai=new WeakMap,eu=e=>{let t=Ai.get(e);return t||(t=Ci(e),Ai.set(e,t)),t},Ti=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Si(eu(e),r).filter(s=>Rr(r,s)>=n)}});var tu,Mi,nu,ki=h(()=>{"use strict";tn();wi();tu={hint:"",hints:[],overlap:0,remainder:""},Mi=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return tu;let o=Ti({wordList:r,inputToMatch:e,overlapThreshold:1});return nu(t,o)},nu=(e,t)=>{let n=t[0]??"",r=Rr(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),d=r<(o??"").length,l=!!s,p=(l&&d?o:n)+(l&&d?":":" "),y=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:y}}});import{useSyncExternalStore as uv}from"react";var Ar,ru,ou,re,Ze,Ne=h(()=>{"use strict";Ar={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},ru=new Set,ou=()=>{for(let e of ru)e()},re=()=>Ar,Ze=e=>(Ar={...Ar,...e},ou(),Ar)});function Li(e){return!e||!iu.test(e)?i(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Be(e,t=nn){if(e<0n)return i("Negative rank not allowed");let n=e.toString(16);return c("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Ce(e,t){if(!e&&!t)return Be(et/2n,nn);let n=e?Li(e):c("Resolved lower bound",0n);if(a(n))return n;let r=t?Li(t):c("Resolved upper bound",et);if(a(r))return r;let o=n.value,s=r.value;if(s<=o)return Be(et/2n,nn);let d=(o+s)/2n;return d===o||d===s?i("No rank space available between neighbors"):Be(d,nn)}function Pi(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=et*BigInt(r+1)/(t+1n),s=Be(o,nn);if(a(s))return s;n.push(s.value)}return c("Resolved evenly spaced ranks",n)}var nn,su,et,iu,rn=h(()=>{"use strict";C();nn=24n,su=nn*4n,et=(1n<<su)-1n,iu=/^[0-9a-f]+$/});import{ulid as au}from"ulid";var Wo,Di=h(()=>{"use strict";C();tt();rn();Wo=(e,t)=>{let n=K(e),r=Pi(n.length);if(a(r))return r;let o={};for(let s=0;s<n.length;s++){let d=n[s],l=r.value[s];if(!d||!l)return i("Unable to assign rebalance rank");o[d.id]=l}return c("Created rebalance event",{id:au(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})}});var Ut,du,Ot,E,ae=h(()=>{"use strict";ne();C();T();tt();Ut=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r)return i("Node not found");if(r.context===t)return c("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return c("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return i(`No ancestor found for context: ${t}`)},du=(e,t)=>{let{nodes:n}=g(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Ot=(e,t)=>e?e.readonly?i({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:i("Node not found"),E={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return i("Contributor not found");if(n.userId&&n.userId!==t)return i("Contributor is already linked to another user");let r={...n,userId:t},o=ye(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?i("Unable to link contributor to user"):c("Linked contributor to user",r)},deleteNode(e){ye(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create comment, missing issue");if(!w(t))return i("Can only comment on issues");let n=ye(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?i("Unable to create comment"):c("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return i("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return i("Unable to edit comment, missing issue");if(!w(r))return i("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=ye(d=>({...d,comments:{...d.comments??{},[e]:o}}));return a(s)?i("Unable to edit comment"):c("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return i("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=ye(o=>({...o,comments:{...o.comments??{},[e]:n}}));return a(r)?i("Unable to delete comment"):c("Deleted comment",n)},getComment(e){return g().comments?.[e]},getCommentsByIssue(e){return Object.values(g().comments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=g(),r=n[e];if(!r)return i("Edit target node not found");let o=Ot(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return i("Rename target node not found");let r=Ot(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return K(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=g(),o=this.getNode(e),s=this.getNode(t);if(!o)return i("Node not found");if(!s)return i("Target parent not found");if(r===e)return i("Cannot move root node");if(e===t)return i("Cannot move node into itself");let d=Ot(o,"move");if(d)return d;if(du(t,e))return i("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=g(),o=this.getNode(e);if(!o)return i("Node not found");if(r===e)return i("Cannot delete root node");let s=new Set,d=u=>{let m=t[u];if(!(!m||s.has(u))){s.add(u);for(let p of K(m.id))d(p.id)}};d(e);let l={...structuredClone(t)};for(let u of s){if(!l[u])return i("Unable to locate node to delete");l[u]={...l[u],isDeleted:!0}}return n?(x({nodes:l}),c("Successfully tomb stoned",o)):i("Unable to delete undefined")},createContributor(e){let t=ye(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?i("Unable to create contributor"):c("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return i("Unable to assign contributor, missing contributor");if(!r)return i("Unable to assign contributor, missing target");let o=Ot(r,"edit");if(o)return o;if(!w(r))return i("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return i("Contributor already assigned");let d={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(d),c("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return i("Unable to unassign, missing contributor");if(!r)return i("Unable to unassign, missing target");let o=Ot(r,"edit");if(o)return o;if(!w(r))return i("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return c("Issue is not assigned to that contributor",{assignee:t});let d={...r,props:{...r.props,assignees:s.filter(l=>l!==t)}};return this.updateNode(d),c("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return i("Unable to add tag, missing tag");if(!r)return i("Unable to add tag, missing target");let o=Ot(r,"edit");if(o)return o;if(!w(r))return i("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return i("Tag already assigned");let d={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(d),c("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return i("Unable to remove tag, missing tag");if(!r)return i("Unable to remove tag, missing target");let o=Ot(r,"edit");if(o)return o;if(!w(r))return i("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return c("Issue is not tagged with that tag",{tag:t});let d={...r,props:{...r.props,tags:s.filter(l=>l!==t)}};return this.updateNode(d),c("Tag removed",{tag:t})},createTag(e){let t=ye(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?i("Could not create tag"):c("Tag created",e)},createNode(e){let t=ye(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?i("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return i("Failed to locate node");let n={...t,readonly:!0},r=ye(o=>({...o,nodes:{...o.nodes,[e]:n}}));return a(r)?i(r.message):c("Locked node",n)},updateNode(e){let t=ye(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?t:c("Updated node",e)},getContributor(e){return g().contributors[e]},getTag(e){return g().tags[e]},getNode(e){return g().nodes[e]},getSiblings(e){return K(e)}}});var Y,on=h(()=>{"use strict";Y={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments"}});var qe,Fi,sn=h(()=>{"use strict";qe=e=>e.slice(-7).toUpperCase(),Fi=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?qe(e).includes(n):!0}});var he,an=h(()=>{"use strict";ne();sn();he={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:k.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:qe(e)},context:k.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:k.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:d=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:k.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:d}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:k.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:qe(e)},context:k.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:k.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:d=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:k.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:d})}});var xe,S,Se=h(()=>{"use strict";xe={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},S={accent:xe.cyan,accent2:xe.magenta,primary:xe.white,secondary:xe.grayDark,secondary2:xe.grayLight,gray:xe.gray,green:xe.green,yellow:xe.yellow,red:xe.red}});var I,dn,Tr=h(()=>{"use strict";Se();I={red:xe.red,yellow:xe.yellow,green:xe.green,blue:xe.blue,magenta:xe.magenta,cyan:xe.cyan},dn={urgent:I.red,critical:I.red,important:I.red,blocker:I.red,asap:I.red,immediate:I.red,fail:I.red,failure:I.red,broken:I.red,bug:I.red,error:I.red,incident:I.red,outage:I.red,production:I.red,crash:I.red,security:I.red,warning:I.yellow,warn:I.yellow,risky:I.yellow,risk:I.yellow,attention:I.yellow,pending:I.yellow,review:I.yellow,"needs-review":I.yellow,qa:I.yellow,testing:I.yellow,test:I.yellow,validate:I.yellow,verification:I.yellow,staging:I.yellow,check:I.yellow,"follow-up":I.yellow,followup:I.yellow,waiting:I.yellow,blocked:I.yellow,hold:I.yellow,done:I.green,complete:I.green,completed:I.green,success:I.green,ok:I.green,stable:I.green,resolved:I.green,fixed:I.green,closed:I.green,merged:I.green,released:I.green,deployed:I.green,approved:I.green,verified:I.green,working:I.green,healthy:I.green,pass:I.green,passing:I.green,info:I.blue,information:I.blue,note:I.blue,docs:I.blue,documentation:I.blue,doc:I.blue,guide:I.blue,help:I.blue,explanation:I.blue,detail:I.blue,details:I.blue,context:I.blue,design:I.blue,discussion:I.blue,proposal:I.blue,idea:I.blue,feature:I.magenta,enhancement:I.magenta,improvement:I.magenta,refactor:I.magenta,refactoring:I.magenta,cleanup:I.magenta,optimize:I.magenta,optimization:I.magenta,perf:I.magenta,performance:I.magenta,upgrade:I.magenta,migration:I.magenta,modernize:I.magenta,debt:I.magenta,todo:I.cyan,next:I.cyan,planned:I.cyan,plan:I.cyan,future:I.cyan,backlog:I.cyan,investigate:I.cyan,explore:I.cyan,prototype:I.cyan}});import Oi from"chalk";var Vo,Ui,Ho,Bi,cu,lu,_i,uu,mu,Vn,Re,ji,$i,wr,pu,gu,Mr,ct=h(()=>{"use strict";Tr();Vo={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Ui=(e,t,n)=>Math.max(t,Math.min(n,e)),Ho=(e,t,n)=>e+(t-e)*n,Bi=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},cu=e=>e.toLowerCase().trim(),lu=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,d=e/60,l=s*(1-Math.abs(d%2-1)),u=0,m=0,p=0;d>=0&&d<1?(u=s,m=l):d>=1&&d<2?(u=l,m=s):d>=2&&d<3?(m=s,p=l):d>=3&&d<4?(m=l,p=s):d>=4&&d<5?(u=l,p=s):(u=s,p=l);let y=o-s/2;return[Math.round((u+y)*255),Math.round((m+y)*255),Math.round((p+y)*255)]},_i=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,uu=(e,t,n)=>{let r=Ui(n,0,1);return[Math.round(Ho(e[0],t[0],r)),Math.round(Ho(e[1],t[1],r)),Math.round(Ho(e[2],t[2],r))]},mu=(e,t,n)=>uu(e,t,n),Vn=e=>{let n=Bi(e)%360,r=lu(n,Vo.stringColor.saturation,Vo.stringColor.lightness);return _i(r)},Re=(e,t=dn)=>{let n=cu(e);return n&&t[n]?t[n]:Vn(n)},ji=e=>{let t=Vo.gradient.stops,n=Ui(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,s=Math.min(Math.floor(o),r-1),d=o-s;return mu(t[s],t[s+1],d)},$i=e=>_i(ji(e)),wr=e=>Bi(e.toLowerCase().trim())/4294967295,pu=e=>{let t=wr(e);return ji(t)},gu=e=>{let[t,n,r]=pu(e);return{normal:o=>Oi.bgRgb(t,n,r).black(o),cursor:o=>Oi.bgRgb(t,n,r).white.bold(o)}},Mr=e=>gu(e).normal(` ${e} `)});import{decodeTime as Wi}from"ulid";var kr,Hi,cn,ln=h(()=>{"use strict";C();kr=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"},Hi=e=>{try{return c("Decoded date",new Date(Wi(e)))}catch(t){return i("Decoding failed + "+t.message)}},cn=e=>{if(!e?.id)return null;try{return Wi(e.id)}catch{return null}}});import Bt from"chalk";import Vi from"string-width";import{decodeTime as fu}from"ulid";var vu,yu,zi,hu,xu,Iu,Eu,bu,Nu,Cu,qi,Gi,zo=h(()=>{"use strict";ae();T();ct();ln();vu=(e,t)=>e+" ".repeat(Math.max(0,t-Vi(e))),yu=(e,t)=>" ".repeat(Math.max(0,t-Vi(e)))+e,zi=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),hu=(e,t)=>t?e<t?"up":e>t?"down":null:null,xu=(e,t)=>{let n=E.getNode(e.payload.parent),r=n?Bt.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=hu(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Iu=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Bt.bgHex(Re(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Bt.bgHex(Re(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Bt.hex(Re(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Bt.hex(Re(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;default:return""}},Eu=e=>{let t=kr(fu(e));return Bt.gray(yu(t,8))},bu=12,Nu=e=>vu(`${e}`,bu),Cu=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?t.name:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=E.getNode(e.payload.parent);return t?`to ${t.title}`:""}default:return""}},qi=e=>[zi(e.action),Cu(e)].filter(Boolean).join(" "),Gi=(e,t)=>{let n=Eu(e.id),r=Nu(e.userName),o=Bt.dim("\u203A"),s=e.action==="move.node"?xu(e,t):[zi(e.action),Iu(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`}});import{createHash as Su}from"node:crypto";var Ru,Au,Ae,zn=h(()=>{"use strict";Ru="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Au=e=>{let t=Su("sha256").update(e).digest(),n=0n;for(let o=0;o<16;o++)n=n<<8n|BigInt(t[o]);let r="";for(let o=0;o<26;o++){let s=BigInt((25-o)*5);r+=Ru[Number(n>>s&31n)]}return r},Ae=(e,t)=>Au(`${e}:virtual:${t}`)});var Tu,wu,Mu,ku,Lu,qo,Ki,Yi,Pu,Xi=h(()=>{"use strict";zo();ne();C();on();ae();an();T();rn();zn();Tu=e=>Ae(e,"comments"),wu=e=>Ae(e,"description"),Mu=e=>Ae(e,"assignees"),ku=e=>Ae(e,"tags"),Lu=e=>Ae(e,"history"),qo=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:d="horizontal"})=>{let l=E.getNode(e);if(!l){let p=E.createNode({...he.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:d});return a(p)?p:c("Virtual field created",void 0)}if(!Qe(l))return i(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==r||l.props.value!==o||l.readonly!==s||l.childRenderAxis!==d))return c("Virtual field unchanged",void 0);let m=E.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:s,childRenderAxis:d});return a(m)?m:c("Virtual field updated",void 0)},Ki=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let d=E.getNode(e);if(!d){let m=E.createNode({...he.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return a(m)?m:c("Virtual field list created",void 0)}if(!jn(d))return i(`Existing virtual node ${e} is not a field list`);if(!(d.title!==t||d.parentNodeId!==n||d.rank!==r||d.readonly!==o||d.childRenderAxis!==s))return c("Virtual field list unchanged",void 0);let u=E.updateNode({...d,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(u)?u:c("Virtual field list updated",void 0)},Yi=e=>{let t=Be(et/4n),n=Be(et/2n),r=Be(et*3n/4n),o=Be(et*7n/8n),s=Be(et*13n/16n);if(a(t))return t;if(a(n))return n;if(a(r))return r;if(a(o))return o;if(a(s))return s;let d=qo({id:wu(e.id),name:Y.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(d))return d;let l=Ki({id:Mu(e.id),name:Y.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(l))return l;let u=Ki({id:ku(e.id),name:Y.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(a(u))return u;let m=qo({id:Tu(e.id),name:Y.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(m))return m;let p=qo({id:Lu(e.id),name:Y.HISTORY,parentNodeId:e.id,rank:s.value,value:Pu(e),readonly:!0,childRenderAxis:"vertical"});return a(p)?p:c("Ticket virtual nodes materialized",void 0)},Pu=e=>{let t=[...e.log].reverse(),n=new Map;for(let r of t){let o=n.get(r.action)??[];o.push(r.payload),n.set(r.action,o)}return t.map(r=>Gi(r,n.get(r.action)??[])).join(`
40
+ `)}});var Du,de,Lr,un=h(()=>{"use strict";Du=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[de,Lr]=Du});function It(e,t=!1){let n=$u[e.action](e);if(a(n))return n;let r=ju(e,t);return r||n}var D,Ji,Fu,Ou,Uu,Go,Bu,_u,ju,$u,Et,bt=h(()=>{"use strict";ne();C();on();ae();an();T();Xi();un();D=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Ji=e=>{let t=E.getNode(e);if(!t||!w(t)||t.isDeleted)return null;let n=Yi(t);return a(n)?n:null},Fu=e=>{for(let t of e){let n=Ji(t);if(n)return n;let r=g().nodes[t]?.parentNodeId;if(!r)continue;let o=Ji(r);if(o)return o}return null},Ou=(e,t)=>{let n=E.getNode(e);n&&E.updateNode({...n,log:[...n.log??[],t]})},Uu=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},Go=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":return[e.payload.issue];case"delete.node":case"edit.description":return Uu(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"create.contributor":case"link.contributor.user":default:return[]}},Bu=e=>{ye(t=>({...t,eventLog:[...t.eventLog,e]}))},_u=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?D("Invalid user ID format",e):c("Valid user",null)},ju=(e,t)=>{let n=_u(e);if(a(n))return n;let r=[...new Set(Go(e))];t||(r.forEach(s=>Ou(s,e)),Bu(e));let o=Fu(r);return o||null},$u={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=he.workspace(t,n,r),s=qn(o);if(a(s))return D(s.message,e);let d=E.createNode(o);return a(d)?D(d.message??"Failed to initialize workspace",e):jo(d.value)?c("Workspace initialized",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=E.createNode(he.workspace(t,n,r));return a(o)?D(o.message??"Failed to add workspace",e):jo(o.value)?c("Added workspace",{action:e.action,result:o.value}):i("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=E.createNode(he.board(t,n,r,o));return a(s)?D(s.message??"Unable to create board",e):$o(s.value)?c("Added board",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=E.createNode(he.swimlane(t,n,r,o));return a(s)?D(s.message??"Unable to create swimlane",e):$n(s.value)?c("Added swimlane",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=E.createNode(he.ticket(t,n,r,o));return a(s)?D(s.message??"Unable to create issue",e):w(s.value)?c("Added issue",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,d=E.createNode(he.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(Y.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?D(d.message??`Unable to create field: ${n}`,e):Qe(d.value)?c("Added field",{action:e.action,result:d.value}):i("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!E.getNode(t))return D(`Unable to locate node with id ${t}`,e);let o=E.renameNode(t,n);return a(o)?D(o.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=E.tombstoneNode(t);return a(n)?D(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=E.createTag({id:t,name:n});return a(r)?D(r.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=E.createContributor({id:t,name:n});return a(r)?D(r.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=E.tag(t,n);return a(r)?D(r.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=E.untag(t,n);return a(r)?D(r.message??"Unable to untag issue",e):c("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=E.assign(t,n);return a(r)?D(r.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=E.unassign(t,n);return a(r)?D(r.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=E.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?D(o.message??"Failed to move node",e):c("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=E.editValue(t,n);return a(r)?D(r.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=E.getNode(t);if(!o)return D("Unable to locate issue",e);if(!w(o))return D("Can only close issues",e);let s=E.getNode(de);if(!s)return D("Unable to locate target swimlane",e);if(n!==s.id)return D("Close target must be closed swimlane",e);let d=E.moveNodeToRank({id:t,parentId:n,rank:r});return a(d)?D(d.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=E.getNode(t);if(!o)return D("Unable to locate issue",e);if(!w(o))return D("Can only reopen issues",e);let s=E.getNode(de);if(!s)return D("Unable to locate closed swimlane",e);if(n===s.id)return D("Cannot reopen issue into closed swimlane",e);if(!E.getNode(n))return D("Reopen parent no longer exists",e);let l=E.moveNodeToRank({id:t,parentId:n,rank:r});return a(l)?D(l.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=E.lockNode(t);return a(n)?D(n.message??"Unable to lock node",e):c("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let s=E.getNode(r);if(!s)return D(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return D(`Node ${r} is not child of ${t}`,e);let d=E.updateNode({...s,rank:o});if(a(d))return D(d.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=E.createComment({id:t,issue:n,authorId:r,authorName:E.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return a(s)?D(s.message??"Unable to add comment",e):c("Comment added",{action:e.action,result:{id:t,issue:n,author:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=e.payload,o=E.getComment(t);if(!o)return D("Unable to locate comment",e);if(o.issue!==n)return D("Comment does not belong to issue",e);let s=E.editComment(t,r);return a(s)?D(s.message??"Unable to edit comment",e):c("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=E.getComment(t);if(!r)return D("Unable to locate comment",e);if(r.issue!==n)return D("Comment does not belong to issue",e);let o=E.deleteComment(t);return a(o)?D(o.message??"Unable to delete comment",e):c("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=E.linkUserId({contributorId:t,userId:e.userId});return a(n)?D(n.message??"Unable to link contributor",e):c("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};Et=e=>e.map(t=>It(t))});import Pr from"node:fs";import Yo from"node:path";import{decodeTime as Wu}from"ulid";import{z as Ko}from"zod";function Jo(e){let t=kn(e);if(!Pr.existsSync(t))return c("No events found",[]);let n=Pr.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Yo.join(t,o)),r=[];for(let o of n){let s=Yu(o);if(a(s))return i(s.message);r.push(...s.value)}return c("All events loaded",Xu(r))}function _t(e){let t=Jo(e);return a(t)?i(t.message):Xo(t.value)}function Qi(e,t){let n=Jo(e);if(a(n))return i(n.message);let{appliedEvents:r,unappliedEvents:o}=Ju(n.value,t),s=Xo(r);if(a(s))return i(s.message);let d=Xo(o);return a(d)?i(d.message):c("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function Zi(e=process.cwd()){let t=Jo(e);return a(t)?i(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Hu,Vu,zu,qu,Gu,Ku,Xo,Yu,Xu,Ju,mn=h(()=>{"use strict";C();pe();Ge();Hu=Ko.object({userId:Ko.string().min(1).default("unknown"),userName:Ko.string().min(1).default("unknown")}),Vu=e=>{let[t,n]=Yo.basename(e,".jsonl").split("."),r=Hu.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):i(`Invalid event file name ${Yo.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},zu=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?i(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?i("Invalid persisted event: action key is missing or invalid"):c("Resolved persisted action",t[0])},qu=(e,t)=>t in e,Gu=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Ku=e=>{let{userId:t,userName:n,...r}=e,o=zu(r);if(a(o))return i(o.message);let s=o.value,d=e.id?.[0];return d?qu(r,s)?c("Decoded persisted event",Gu({id:d,action:s,payload:r[s],userId:t,userName:n})):i(`Persisted event is missing payload for action: ${s}`):i("Persisted event is missing id")},Xo=e=>{let t=[];for(let n of e){let r=Ku(n);if(a(r))return i(`Failed to decode event ${n.id?.[0]??"<unknown>"}: ${r.message}`);t.push(r.value)}return c("Decoded reconstructed events",t)},Yu=e=>{if(!Pr.existsSync(e))return c("Event file missing",[]);let t=Vu(e);if(a(t))return i(t.message);let n=Pr.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
41
+ `)){let s=o.trim();if(!s)continue;let d;try{d=JSON.parse(s)}catch{return i(`Failed to parse event JSON from ${e}: ${s}`)}let l=Qo(d);if(a(l))return i(`${l.message} in ${e}: ${s}`);r.push({...l.value,userId:t.value.userId,userName:t.value.userName})}return c("Parsed persisted events file",r)};Xu=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],y=m.id[1]??null;t.set(p,m);let N=n.get(y)??[];N.push(m),n.set(y,N)}for(let m of n.values())m.sort((p,y)=>p.id[0].localeCompare(y.id[0]));let r=[],o=new Set,s=m=>{let p=m.id[0];if(o.has(p))return;r.push(m),o.add(p);let y=n.get(p)??[];for(let N of y)s(N)},d=n.get(null)??[];for(let m of d)s(m);let l=e.filter(m=>{let p=m.id[0],y=m.id[1]??null;return!o.has(p)&&y!==null&&!t.has(y)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of l)s(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)s(m);return r},Ju=(e,t)=>{let n=new Set,r=[],o=[];for(let s of e){let d=s.id[0],l=s.id[1],u=!1;try{u=Wu(d)<t}catch{u=!1}!u||l&&n.has(l)?(n.add(d),o.push(s)):r.push(s)}return{appliedEvents:r,unappliedEvents:o}}});var ea,ta=h(()=>{"use strict";ea=e=>({action:e.action,payload:e.payload})});import Qu from"node:fs";import Zu from"node:path";import{decodeTime as em,monotonicFactory as tm}from"ulid";import{z as Gn}from"zod";function Dr({event:e,rootDir:t}){try{let n=Xs(t);if(a(n))return n;let r=im(t,{userId:e.userId,userName:e.userName});if(a(r))return r;let o=Zi(t);if(a(o))return i(o.message);let s=o.value?na(Math.max(Date.now(),em(o.value)+1)):na(),d=am(ea(e),[s,o.value]);return a(d)?i(d.message):(Qu.appendFileSync(r.value,`${JSON.stringify(d.value)}
42
+ `,"utf8"),c("Event persisted",{path:r.value,entry:d.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return i(`Failed to persist event: ${r}`)}}var oa,na,nm,rm,Qo,ra,om,sm,J,jt,im,am,Ge=h(()=>{"use strict";C();Ne();pe();mn();ta();oa=1,na=tm(),nm=Gn.tuple([Gn.string().min(1),Gn.string().min(1).nullable()]),rm=Gn.looseObject({v:Gn.literal(oa),id:nm}),Qo=e=>{let t=rm.safeParse(e);return t.success?c("Parsed persisted event",t.data):i(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},ra=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",om=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),sm=e=>e.trim().length>0&&e.length<=80,J=()=>{let{userName:e,userId:t}=re();return e?t?om(t)?sm(e)?c("Successfully resolved actor ID",{userId:t,userName:e}):i("Invalid user name in config"):i("Invalid user ID in config"):i("User ID not configured"):i("User name not configured")},jt=({userId:e,userName:t})=>`${ra(e)}.${ra(t)}.jsonl`,im=(e,{userId:t,userName:n})=>{let r=jt({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return i(`Invalid event log file name: ${r}`);let s=Zu.join(kn(e),r);return c("Successfully resolved event log path",s)},am=(e,t)=>{let n={[e.action]:e.payload,v:oa,id:t};return Qo(n)}});import{ulid as dm}from"ulid";function sa(e,t){let n=It(e);if(n.status!==ft.Success)return n;let r=Dr({event:e,rootDir:t});return a(r)?r:n}function B(e,t){if(e.length===0||!e[0])return i("No events provided");let n=cm(e[0],t);if(a(n))return n;let r=e.map(s=>sa(s,t)),o=r.filter(a);return o.length>0?i("Materialize and persist failed: "+o.map(s=>s.message).join(", ")):c("Materialization succeeded",r.map(s=>s.value))}var cm,$t=h(()=>{"use strict";C();ae();bt();Ge();cm=(e,t)=>{if(e.action==="create.contributor")return c("Contributor already being created",void 0);if(E.getContributor(e.userId))return c("Contributor exists",void 0);let n={id:dm(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},r=sa(n,t);return a(r)?i(r.message):c("Contributor created",void 0)}});var ia,Fr,K,aa,da,Wt,pn,tt=h(()=>{"use strict";Di();$t();C();T();rn();ia=e=>Fr(K(e),{at:"end"}),Fr=(e,t={at:"end"})=>{let n=r=>a(r)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(Ce(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(Ce(void 0,r.rank)):i("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(Ce(r.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let r=aa(e,t.sibling);if(r<0)return i("Sibling not found");let o=r>0?e[r-1]:void 0,s=e[r];return s?n(Ce(o?.rank,s.rank)):i("Sibling not found")}case"after":{let r=aa(e,t.sibling);if(r<0)return i("Sibling not found");let o=e[r],s=r<e.length-1?e[r+1]:void 0;return o?n(Ce(o.rank,s?.rank)):i("Sibling not found")}}},K=e=>Object.values(g().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),aa=(e,t)=>e.findIndex(n=>n.id===t),da=(e,t,n={at:"end"})=>Fr(K(t).filter(r=>r.id!==e),n),Wt=(e,t,n,r,o)=>{let s=da(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return c("Resolved rank",s.value.rank);let d=Wo(e,r);if(a(d))return d;let l=B([d.value],o);if(a(l))return l;let u=da(t,e,n);return a(u)?u:u.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",u.value.rank)},pn=(e,t,n)=>{let r=ia(e);if(a(r))return r;if(!r.value.needsRebalance)return c("Resolved rank",r.value.rank);let o=Wo(e,t);if(a(o))return o;let s=B([o.value],n);if(a(s))return s;let d=ia(e);return a(d)?d:d.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",d.value.rank)}});var P,ca,la,_e=h(()=>{"use strict";T();P={exit(){process.exit(0)},enterChildNode(){let e=g(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=z(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||P.navigate({contextNode:o,selectedIndex:z(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=g();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=z(n.id),o=r.findIndex(({id:d})=>d===e.id),s=r.length===0?-1:o>=0?o:0;P.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>ca(1),navigateToPreviousItem:()=>ca(-1),navigateToNextContainer:()=>la(1),navigateToPreviousContainer:()=>la(-1),navigate:({contextNode:e,selectedIndex:t})=>{x({contextNodeId:e.id,selectedIndex:t})}},ca=e=>{let{selectedIndex:t,contextNode:n}=g(),r=z(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;P.navigate({selectedIndex:s,contextNode:n})},la=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=g();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=z(o.id),d=s.findIndex(N=>N.id===t.id);if(d<0)return;let l=s.at(d+e)??s.at(0);if(!l)return;let u=z(l.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),y=u.length?p:-1;P.navigate({contextNode:l,selectedIndex:y})}});var ma,pa,lm,Or,ga,ua,um,fa,va=h(()=>{"use strict";ne();C();tt();T();_e();ma=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),pa=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},lm=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&Qe(t)&&t.childRenderAxis==="vertical"},Or=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r||r.isDeleted)return!1;let o=K(r.id);return P.navigate({contextNode:r,selectedIndex:ma(t,o.length)}),!0},ga=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Or(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let d=K(o.id).findIndex(l=>l.id===n.id);return d>=0?(P.navigate({contextNode:o,selectedIndex:d}),!0):ga(o.id)},ua=e=>{let{nodes:t}=g(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),ga(n))return!0;n=t[n]?.parentNodeId}return!1},um=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},fa=e=>{let{nodes:t,rootNodeId:n}=g();if(lm(e.contextNodeId)&&Or(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(um(e.selectedNodeId)&&e.selectedNodeId&&ua(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(Or(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&Or(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(ua(e.contextNodeId))return c("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return i("Unable to restore navigation");let o=K(r.id);return P.navigate({contextNode:r,selectedIndex:ma(e.selectedIndex,o.length)}),c("Restored navigation to root",null)}});import{monotonicFactory as mm,ulid as lt}from"ulid";function pm(){let e=je();if(a(e))return i("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)throw new Error("No workspace found in event log");let[r]=z(n.id),[o]=r?z(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return c("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?c("Resolved boot nav target",{contextNode:r,selectedIndex:0}):n?c("Resolved boot nav target",{contextNode:n,selectedIndex:0}):c("Resolved boot nav target",{contextNode:t.nodes[t.rootNodeId],selectedIndex:0})}function gm(){let e=pm();return a(e)?e:P.navigate(e.value)}function ya({userId:e,userName:t}){let n=Kn(),r=Kn(),o=Kn(),s=Kn(),d=Kn(),l=Ce(void 0,void 0);if(a(l))return l;let u=Ce(void 0,void 0);if(a(u))return u;let m=Ce(u.value,void 0);if(a(m))return m;let p=Ce(void 0,void 0);if(a(p))return p;let y=Ce(p.value,void 0);if(a(y))return y;let N=Ce(y.value,void 0);if(a(N))return N;let R=Ce(void 0,void 0);return a(R)?R:c("Created default events",[{id:lt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:lt(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:lt(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:lt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:y.value}},{id:lt(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:r,rank:N.value}},{id:lt(),userId:e,userName:t,action:"add.board",payload:{id:Lr,name:"Closed",parent:n,rank:m.value}},{id:lt(),userId:e,userName:t,action:"add.swimlane",payload:{id:de,name:"Closed",parent:Lr,rank:R.value}},{id:lt(),userId:e,userName:t,action:"lock.node",payload:{id:Lr}},{id:lt(),userId:e,userName:t,action:"lock.node",payload:{id:de}}])}function Yn(e){if(!e.length){let r=he.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=qn(r);return a(o)?o:(x({hasProjectDefinition:!1,mode:f.DEFAULT}),c("Booted uninitialized workspace placeholder",null))}if(!e.some(r=>r.action==="init.workspace"))return i("Initialized Epiq project has no workspace init event");let n=Et(e).filter(a);return n.length>0?i(`Materializing failed:
43
43
  ${n.map(r=>r.message).join(`
44
- `)}`):(am(),x({hasProjectDefinition:!0}),c("State booted successfully",null))}var jn,Mr=y(()=>{"use strict";Be();Y();C();nn();w();en();yt();an();jn=sm()});var z,Go=y(()=>{"use strict";C();z=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});var Qe,Lr,dm,ga,Ko=y(()=>{"use strict";ma();Mr();dn();He();Y();C();w();kr();Go();Yo();Qe=null,Lr=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Qe,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),Qe)return logger.debug("[sync] syncAndReloadState joining existing promise"),Qe;logger.debug("[sync] syncAndReloadState creating promise"),Qe=dm();try{let e=await Qe;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:g().syncStatus?.status,statusMessageAfterResolve:g().syncStatus?.msg}),a(e)&&g().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),x({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),Qe||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),Qe=null}},dm=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=ga();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(Qe)return Qe;logger.debug("[sync] syncAndReloadState:start");let t=z("resolveActorId",X());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),i("Unable to resolve event log path");x({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:g().syncStatus});let n=Ft(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=z("syncEpiqWithRemote",await Pr({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(r),message:(a(r),r.message)}),a(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),x({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),je(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let s=z("loadMergedEvents",Dt(o));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(s),message:(a(s),s.message),count:a(s)?void 0:s.value.length}),a(s))return x({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:g().syncStatus}),i(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let d=ga();if(d)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:d.message,syncStatus:g().syncStatus}),d;let l=ca(),u=g().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:l,selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id,selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual}),!g().selectedNode?.isVirtual&&!g().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let p=z("bootStateFromEventLog",$n(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(p),message:(a(p),p.message)}),a(p))return x({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:g().syncStatus}),i(`Unable to boot synced state. ${p.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),x({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=z("restoreNavigationAnchor",ua(l));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(m),message:a(m)?m.message:"Navigation restored",selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id}),a(m)?(x({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),m):(x({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),c("Synced",!0))},ga=()=>g().mode===f.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),x({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),i("Will not re-materialize if not in default mode, to not lose edit data"))});var ln,fa,va,Xo,Jo,Wn,Qo,cm,ya,lm,ha,Dr=y(()=>{"use strict";C();Ee();w();Ko();ln=3e3,fa=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<ln?null:t},va=0,Jo=!1,Wn=!1,Qo=()=>{if(Jo)return!0;let e=_e();return a(e)?!1:e.value.syncStatus.status==="syncing"},cm=()=>{let e=ee().autoSyncIntervalMs??1e4,t=Date.now()-va;return Math.max(0,e-t)},ya=()=>{Xo||(Xo=setTimeout(async()=>{if(Xo=void 0,!!un()){if(Qo()){Wn=!0;return}Wn=!1,await lm()}},cm()))},lm=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return i("Cannot auto-sync while peeking");if(!un())return i("Cannot auto-sync before state is initialized");if(Qo())return Wn=!0,i("Sync already in progress");Jo=!0,va=Date.now(),x({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Lr()}finally{Jo=!1,Wn&&ya()}},ha=()=>{un()&&(Wn=!0,!Qo()&&ya())}});var Fr,xa,Ia,ba,Hn=y(()=>{"use strict";C();St();Ee();ue();Fr=()=>{let e=ee(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},xa=()=>{let e=mt(process.cwd());if(a(e))return!1;let t=gt(e.value);return Rt(t)},Ia=e=>e===!0?"on":e===!1?"off":null,ba=e=>e==="on"?!0:e==="off"?!1:null});var um,mm,zn,Vn,Or,Ur,Br=y(()=>{"use strict";Z();C();ie();w();um=e=>e.props.tags??[],mm=e=>e.props.assignees??[],zn=e=>um(e).map(t=>b.getTag(t)).filter(t=>!!t),Vn=e=>mm(e).map(t=>b.getContributor(t)).filter(t=>!!t),Or=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!T(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",zn(n))},Ur=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!T(n)?i("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",Vn(n))}});var v,Bt=y(()=>{"use strict";v={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""}});var pm,gm,fm,vm,ym,_t,Ea,_r,jr,Na,hm,Zo,qn=y(()=>{"use strict";pm=/^(\d+)(h|d|w|mo|y)$/,gm=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,fm=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let s=new Date(e,t-1,n,r,o);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===r&&s.getMinutes()===o},vm=(e,t=new Date)=>{let n=e.match(pm);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let d=new Date(t);switch(o){case"h":return d.setHours(d.getHours()-s),d;case"d":return d.setDate(d.getDate()-s),d;case"w":return d.setDate(d.getDate()-s*7),d;case"mo":return d.setMonth(d.getMonth()-s),d;case"y":return d.setFullYear(d.getFullYear()-s),d;default:return null}},ym=e=>{let t=e.match(gm);if(!t)return null;let[,n,r,o,s,d]=t,l=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,h=d?Number(d):0;return fm({year:l,month:u,day:m,hour:p,minute:h})?new Date(l,u-1,m,p,h):null},_t=e=>{let t=e.trim().toLowerCase();return vm(t)??ym(t)},Ea=/^(\d+)(s|m)?$/,_r=e=>{let t=e.trim().toLowerCase().match(Ea);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},jr=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Ea.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Na=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,hm=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],Zo=(e=hm)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let s=r;s<=o;s++)t.push(`${s}${n}`);return t}});var xm,se,Ae,Im,bm,ts,Sa,jt,$r,es,Ca,Em,Nm,Aa,Ra,Cm,Rm,pe,mn=y(()=>{"use strict";Dr();Hn();an();Z();ie();w();br();Br();Bt();qn();xm=["BOARD","TICKET","SWIMLANE","COMMENT"],se={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},Ae={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Im=[se.EDITOR,se.VIEW,se.USERNAME,se.AUTOSYNC,se.SYNC_DEBOUNCE_MS,se.LOG_LEVEL],bm=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[Ae.TITLE,Ae.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Ae.TITLE];case"COMMENT":return[Ae.COMMENT];default:return[]}},ts=[String(ln),"5000","15000","30000","60000"],Sa=["10s","20s","30s","45s"],jt=[v.COFFEE,v.EXIT,v.SYNC,v.HELP,v.EXPORT,v.CONFIG],$r=[v.NEW,v.EDIT,v.DELETE,v.MOVE],es=[v.TAG,v.UNTAG,v.ASSIGN,v.UNASSIGN,v.CLOSE_ISSUE,v.RE_OPEN_ISSUE,v.EDIT,v.COMMENT],Ca=[v.FILTER,v.PEEK,v.REPLAY],Em={WORKSPACE:[...jt,...$r],BOARD:[...Ca,...jt,...$r],SWIMLANE:[...Ca,...jt,...$r],TICKET:[...jt,...$r,...es],FIELD:[...jt,...es],FIELD_LIST:[...jt,...es],TEXT:[...jt],COMMENT:[v.EDIT,v.DELETE]},Nm=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Aa=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&T(n)),Ra=e=>e.parentNodeId===ae,Cm=({selectedNode:e,breadCrumb:t})=>{let n=bm(e?.context);return Aa({breadCrumb:t,selectedNode:e})?n.includes(Ae.DESCRIPTION)?n:[...n,Ae.DESCRIPTION]:n},Rm=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Fr();if(!r)return[v.HELP,v.CONFIG];if(!xa())return[v.HELP,v.INIT];if(t)return[v.HELP,v.PEEK,v.REPLAY,v.EXPORT,v.CONFIG];let o=e?.context,s=o&&xm.includes(o),d=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?Em[u]:[]))],l=Aa({breadCrumb:n,selectedNode:e});return d.filter(u=>u===v.MOVE?!1:u===v.EDIT?s||!!l:u===v.DELETE?s:u===v.UNTAG?!!(l&&zn(l).length>0):u===v.UNASSIGN?!!(l&&Vn(l).length>0):u===v.RE_OPEN_ISSUE?!!(l&&Ra(l)):u===v.CLOSE_ISSUE?!!(l&&!Ra(l)):!0)},pe=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=g())=>{let s=t.context??"WORKSPACE";return{[v.NONE]:Rm({breadCrumb:o,readOnly:r,selectedNode:n}),[v.EXIT]:["confirm"],[v.EXPORT]:[],[v.SYNC]:[],[v.INIT]:[],[v.HELP]:[],[v.PEEK]:[...Zo(),"now","prev","next"],[v.REPLAY]:[...Zo()],[v.EDIT]:Cm({selectedNode:n,breadCrumb:o}),[v.COMMENT]:[],[v.DELETE]:["confirm"],[v.RE_OPEN_ISSUE]:["confirm"],[v.CLOSE_ISSUE]:["confirm"],[v.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[v.FILTER]:["tag","assignee","description","title","ref","clear"],[v.TAG]:[...new Set([...Object.keys(rn),...b.getExistingTags()])],[v.UNTAG]:[...Or()?.value?.map(({name:l})=>l)??[]],[v.UNASSIGN]:[...Ur()?.value?.map(({name:l})=>l)??[]],[v.ASSIGN]:b.getExistingAssignees(),[v.NEW]:Nm(s),[v.CONFIG]:[...Im],[v.COFFEE]:["1","3","5","20","custom"]}[e]??[]}});var Ta,wa=y(()=>{"use strict";Ta=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});var Te,$t=y(()=>{"use strict";C();Te=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?c("Found node",n):i("Unable to find node in breadcrumb")}});import Ma from"chalk";var K,ye,he,La=y(()=>{"use strict";ot();Ce();K=e=>Ma.dim(e),ye=e=>Ma.hex(R.primary)(e),he=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let d=o.trim();if(d.length<s)return"";let p=[...t.filter(Boolean).filter(h=>h.startsWith(d))].sort((h,N)=>Er(h)-Er(N)).slice(0,r).map(h=>Nr(h)).join(" ");return p?`${K(e)}${p}${K(n)}`:""}});var ht,Wr=y(()=>{"use strict";ht={None:"none",Invalid:"invalid",Valid:"valid"}});import Da from"chalk";var pn,Sm,ka,te,H,U,zr,Pa,Hr,ns,Am,Wt,Tm,wm,Mm,Fa,rs=y(()=>{"use strict";Dr();Hn();wa();sn();$t();C();ie();Ee();w();ot();Br();Un();La();Bt();Wr();mn();qn();pn=140,Sm=["BOARD","TICKET","SWIMLANE"],ka=()=>{let e=g().selectedNode;if(!e?.context)return U({message:K("Missing target context")});if(Sm.includes(e.context))return H();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===Se(t?.parentNodeId??"","comments"))return H()}return U({message:K("Command not available in this context")})},te="<ENTER> to confirm",H=(e="",t=[])=>({message:K(e),validity:ht.Valid,completionWordList:t}),U=({message:e,completionWordList:t=[]})=>({validity:ht.Invalid,message:e,completionWordList:t}),zr=e=>e.length===0,Pa=(e,t)=>{let n=Te(g().breadCrumb,"BOARD");if(a(n))return U({message:ye("Command is not applicable in this context")});let r=_i(n.value.id);return a(r)?U({message:ye(`Unable to ${t}: board id is not a valid ULID`)}):Na({date:e,horizonDate:r.value})?null:U({message:ye(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},Hr=e=>` ${Da.hex("#000").bgHex(Re(e))(` ${e} `)} `,ns=({modifier:e})=>{let t="confirm";return e===t?H(te):U({message:zr(e)?K("if you are certain, enter ")+Nr(t):"",completionWordList:[t]})},Am=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?U({message:K(n)}):H():U({message:zr(r)?t:"",completionWordList:[...e]}),Wt=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>zr(n)&&zr(r)?U({message:e,completionWordList:[]}):H(t??te),Tm=({modifier:e,inputString:t})=>{let n=pe(v.CONFIG);if(!n.includes(e))return U({message:he({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case se.EDITOR:{let r=[...Ta];return t.trim()?r.includes(t.trim())?H(te):U({message:he({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):U({message:he({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case se.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?H(te):U({message:he({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case se.USERNAME:return t.trim()?H(te):U({message:ye("Enter a user name. Saved in ")+Da.bgBlack("~/.epiq-global/config.json")});case se.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?H(te):U({message:he({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case se.AUTOSYNC:{let r=["on","off"],o=ee().autoSync;if(!r.includes(t.trim())){let s=Ia(o);return U({message:he({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return H(te)}case se.SYNC_DEBOUNCE_MS:{let r=ee().autoSyncIntervalMs,o=fa(t);if(!t.trim()||o===null||o<ln){let s=he({prefix:" examples: ",wordList:ts,minLengthForHints:0,inputString:t});return U({message:ye(`provide duration above ${ln}ms. current duration: ${r}ms.`)+s,completionWordList:ts})}return H(te)}default:return U({message:ye("Unknown config option"),completionWordList:n})}},wm=({modifier:e,inputString:t})=>{let n=pe(v.EDIT);if(!n.length)return U({message:ye("Command not available in this context")});if(!n.includes(e)){let r=he({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return U({message:r||ye("Unknown edit option"),completionWordList:n})}switch(e){case Ae.COMMENT:return t.trim()?H(te):U({message:K("write a comment...")});case Ae.TITLE:return H(te);case Ae.DESCRIPTION:{let{preferredEditor:r}=ee();return r?H(K("<ENTER> to edit in ")+r):U({message:"No editor selected"})}default:return U({message:ye("Unknown edit option"),completionWordList:n})}},Mm={[v.EXPORT]:()=>H(te+K(", and create export markdown file")),[v.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return H(te);let n={message:K("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=_t(r);if(!r||!o)return U(n);let s=Pa(o,"peek");return s||H(te)},[v.REPLAY]:e=>{let{dateInput:t,durationInput:n}=jr(e.modifier,e.inputString),r={message:K("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=_t(t);if(!t||!o)return U(r);let s=Pa(o,"replay");return s||(n&&_r(n)===null?U({message:ye("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):H("<ENTER> to replay board history",n?Sa:[]))},[v.EXIT]:()=>H(te+K(" and exit the application")),[v.INIT]:()=>H(te),[v.PALETTE]:()=>H(te),[v.FILTER]:e=>{if(e.modifier==="clear")return H(te);let t=s=>pe(v.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return U({message:he({wordList:pe(v.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:pe(v.FILTER)});let n=Object.values(g().tags).map(s=>s.name),r=Object.values(g().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?U({message:he({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):H():U({message:he({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[v.NONE]:e=>{let t=pe(v.NONE);return U({message:he({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[v.NEW]:e=>Am({list:pe(v.NEW),hint:he({wordList:pe(v.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[v.HELP]:()=>H(te),[v.EDIT]:wm,[v.COMMENT]:e=>{let t=Wt({hint:K(`write a comment (max ${pn} char)...`),onOk:K(`(${e.inputString.length}/${pn})`)})(e);return t.validity===ht.Invalid?t:e.inputString.length>pn?H(ye("max input exceeded")):t},[v.CONFIG]:Tm,[v.DELETE]:e=>{let t=ka();return t.validity==="invalid"?t:ns(e)},[v.CLOSE_ISSUE]:e=>ns(e),[v.RE_OPEN_ISSUE]:e=>ns(e),[v.MOVE]:e=>{let t=ka();return t.validity==="invalid"?t:Wt({hint:he({prefix:"hey hacker! These commands are blocked for you... ",wordList:pe(v.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[v.TAG]:e=>{let n=b.getExistingTags().slice(0,10).map(Hr).join("");return Wt({hint:n.length?K("create tag or reuse:")+n+K(""):K("create tag ...")})(e)},[v.UNTAG]:e=>{let t=Or();if(a(t))return U({message:ye("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Hr).slice(0,10);return n.length?Wt({hint:K(" ... ")+n.join("")})(e):U({message:ye("Issue has no tags"),completionWordList:[]})},[v.ASSIGN]:e=>{let t=b.getExistingAssignees().map(Hr).slice(0,10);return Wt({hint:K("assignees... ")+t.join("")})(e)},[v.UNASSIGN]:e=>{let t=Ur();if(a(t))return U({message:ye("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Hr).slice(0,10);return n.length?Wt({hint:K("remove assignee... ")+n.join("")})(e):U({message:ye("Issue has no assignees"),completionWordList:[]})},[v.SYNC]:()=>H(te),[v.COFFEE]:e=>{let{modifier:t}=e,n=pe(v.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?U({message:K("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):Wt({hint:he({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},Fa=Object.fromEntries(Object.entries(Mm).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]))});var Vr,Oa=y(()=>{"use strict";Vr=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"]});var Lm,km,Pm,Dm,Fm,Ua,Ba,_a,ja=y(()=>{"use strict";C();w();Oa();Lm=3,km=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),Pm=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let r=n.props;typeof r.description=="string"&&t.push(r.description),typeof r.value=="string"&&t.push(r.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},Dm=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=Lm&&!km.has(t)&&!/^\d+$/.test(t)),Fm=e=>{let t=new Map;for(let s of Pm(e))for(let d of Dm(s))t.set(d,(t.get(d)??0)+1);let n=[...t.entries()].sort((s,d)=>d[1]-s[1]||s[0].localeCompare(d[0])).map(([s])=>s),r=new Set(n),o=Vr.filter(s=>!r.has(s));return[...n,...o]},Ua=Vr,Ba=-1,_a=()=>{let e=_e();if(a(e))return Vr;let t=e.value,n=t.eventLog.length;return n!==Ba&&(Ua=Fm(t),Ba=n),Ua}});var $a,Wa,os=y(()=>{"use strict";Ai();mn();Bt();rs();ja();w();Y();$a=e=>Object.values(v).includes(e),Wa=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:d,validity:l,completionWordList:u}=Fa[n].validate(n,r,s),m=n!==v.PEEK&&n!==v.REPLAY,p=o==="command"||o==="modifier"?pe(n):m?_a():[],{mode:h}=g(),N=h===f.COMMAND_LINE?d??"":"",S=[...u,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:N,autoCompletion:t?Si(e,S):{hint:"",hints:[],remainder:"",overlap:0}}}});var Ha,Om,Um,Bm,za=y(()=>{"use strict";os();mn();Ha=e=>{let t=e.trimStart(),n=Um(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),d=Bm(e),l=$a(r)?r:null,u=l!==null,m=r!=="",p=l?pe(l)??[]:[],h=l&&p.includes(o)?o:"",N="word";n.length===0||n.length===1&&!s?N="command":(n.length===1&&s||n.length===2&&!s)&&(N="modifier");let S=s?"":d,F=Om(t,l,h);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:s,modifier:h,target:N,inputToMatch:S,inputString:F}},Om=(e,t,n)=>{let r=e;return t&&r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/^\s+/,""),n&&r.startsWith(n)&&(r=r.slice(n.length),r=r.replace(/^\s+/,"")),r},Um=e=>e.trim()?e.trim().split(/\s+/):[],Bm=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as bI}from"react";var gn,ss,fn,_m,Va,Ze,Gn,is,as,qa,Ga,qr,Ka,W,Ya,Xa,Ja,J,Qa,ce=y(()=>{"use strict";os();za();C();Wr();gn=e=>e===ss||e===":",ss=" ",fn={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:ht.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},_m=new Set,Va=()=>{for(let e of _m)e()},Ze=e=>{let n=e(fn),r=Ha(n.value),o=n.cursorPosition===n.value.length;fn={...n,commandMeta:Wa(r,o)},Va()},Gn=({message:e,status:t})=>{let n=structuredClone(fn);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,fn=n,Va(),c(e,null)},is=e=>{Ze(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},as=e=>{Ze(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&gn(n[o-1]);)o--;for(;o>0&&!gn(n[o-1]);)o--}else{for(;o<n.length&&!gn(n[o]);)o++;for(;o<n.length&&gn(n[o]);)o++}return{...t,cursorPosition:o}})},qa=()=>{Ze(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},Ga=()=>{Ze(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&gn(t[r-1]);)r--;for(;r>0&&!gn(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},qr=e=>{Ze(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),d=s+o,l=Math.max(0,Math.min(s.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},Ka=()=>{Ze(e=>({...e,commandIsPending:!0}))},W=e=>{Ze(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Ya=({addToHistory:e=!0})=>{Ze(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Xa=()=>{Ze(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Ja=()=>{Ze(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},J=()=>fn,Qa=()=>{let[e,...t]=fn.value.split(ss);return t.join(ss).trim()}});var A,Tt=y(()=>{"use strict";Y();xi();w();ce();Ee();A={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"}});var Za,L,ds=y(()=>{"use strict";w();Bt();Za=e=>{let{context:t}=g().contextNode;if(!t)return L.None;switch(e){case v.EXIT:return L.Exit;case v.EXPORT:return L.Export;case v.COFFEE:return L.Coffee;case v.INIT:return L.Init;case v.DELETE:return L.Delete;case v.EDIT:return L.Edit;case v.COMMENT:return L.Comment;case v.HELP:return L.ViewHelp;case v.RE_OPEN_ISSUE:return L.ReopenIssue;case v.CLOSE_ISSUE:return L.CloseIssue;case v.TAG:return L.TagTicket;case v.UNTAG:return L.UntagTicket;case v.ASSIGN:return L.AssignUserToTicket;case v.UNASSIGN:return L.UnassignUserFromTicket;case v.NEW:return L.NewItem;case v.FILTER:return L.Filter;case v.MOVE:return L.Move;case v.PEEK:return L.Peek;case v.REPLAY:return L.Replay;case v.CONFIG:return L.Config;case v.SYNC:return L.Sync;default:return L.None}},L={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export",Coffee:"coffee"}});import{Text as ed}from"ink";import td,{useEffect as nd,useState as jm}from"react";var rd,we,vn=y(()=>{"use strict";w();Ce();rd={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},we=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=$e(),r=rd[n]??rd.default,[o,s]=jm(0);if(nd(()=>{s(0)},[r]),nd(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return td.createElement(ed,null,t);let d=r[o]??r[0]??t;return td.createElement(ed,{color:R.accent,dimColor:o===1},d)}});import{Box as cs,Text as $m}from"ink";import Gr from"react";var yn,Kr=y(()=>{"use strict";Ce();yn=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),d=Math.max(1,Math.ceil(r)),l=Math.max(1,Math.floor(s/d)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-l),p=o?Math.min(m,Math.max(0,u-l+1)):Math.min(m,Math.floor(u/l)*l),h=p+l,N=e.slice(p,h),S=e.length>l,F=s,O=S?Math.max(1,Math.floor(l/e.length*F)):F,j=Math.max(0,F-O),ne=Math.max(1,e.length-l),Q=S?Math.floor(p/ne*j):0;return Gr.createElement(cs,{flexDirection:"row",height:s,width:"100%"},Gr.createElement(cs,{flexDirection:"column",flexGrow:1,height:s},N),Gr.createElement(cs,{flexDirection:"column",width:1,height:F},Array.from({length:F}).map((k,$)=>Gr.createElement($m,{key:$,color:S&&$>=Q&&$<Q+O?R.accent:R.secondary},S?"\u2502":" "))))}});import{Text as Wm}from"ink";import Hm from"react";var zm,Vm,hn,Yr=y(()=>{"use strict";br();ot();ie();zm=e=>e.toLowerCase().trim(),Vm=(e,t=rn)=>{let n=zm(e);return t[n]?t[n]:On(n)},hn=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return Hm.createElement(Wm,{underline:t,color:Vm(n.name)},"@"+n.name)}});import{Text as qm}from"ink";import Gm from"react";var Xr,ls=y(()=>{"use strict";ie();Ce();ot();Xr=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return Gm.createElement(qm,{underline:t,backgroundColor:Re(n.name),color:R.secondary}," "+n.name+" ")}});import{useEffect as Km,useState as Ym}from"react";var Xm,od,Jr,Kn,Jm,Qm,xn,Qr=y(()=>{"use strict";ot();Xm=80,od=1400,Jr=new Set,Kn=null,Jm=e=>(Jr.add(e),Kn||(Kn=setInterval(()=>{for(let t of Jr)t()},Xm)),()=>{Jr.delete(e),Jr.size===0&&Kn&&(clearInterval(Kn),Kn=null)}),Qm=()=>{let e=Date.now()%od/od;return e<.5?e*2:(1-e)*2},xn=e=>{let[,t]=Ym(0);return Km(()=>{if(e)return Jm(()=>t(n=>n+1))},[e]),Ui(Qm())}});import{Box as Zr,Text as Zm}from"ink";import Ht from"react";var sd,id=y(()=>{"use strict";Ce();Qt();Br();Yr();ls();Qr();sd=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=xn(r),s=e-14,d=hr(wt(t.title),s),l=zn(t),u=Vn(t);return Ht.createElement(Zr,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:r?o:n?R.accent:R.secondary,justifyContent:"space-between"},Ht.createElement(Zr,{borderBottom:!0},Ht.createElement(Zr,{paddingLeft:1,flexDirection:"column"},Ht.createElement(Zm,{color:R.primary},d))),Ht.createElement(Zr,{flexDirection:"row",paddingLeft:1},l.map(m=>Ht.createElement(Xr,{key:m.id,id:m.id})),u.map(m=>Ht.createElement(hn,{key:m.id,id:m.id}))))}});import{Box as zt,Text as Yn}from"ink";import Me from"react";var ep,ad,dd=y(()=>{"use strict";Y();ie();Ce();ot();vn();Qr();ep=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,ad=({width:e,ticket:t,isSelected:n,isFlashing:r=!1,index:o,mode:s})=>{let d=xn(r),l=(t.props.tags??[]).map(k=>b.getTag(k)).filter(k=>!!k),u=(t.props.assignees??[]).map(k=>b.getContributor(k)).filter(k=>!!k),m=1,p=l.length*(1+m),h=u.length*(2+m),N=l.map(k=>Me.createElement(zt,{key:k.id,paddingRight:m},Me.createElement(Yn,{color:Re(k.name)},"\u25A0"))),S=u.map(k=>Me.createElement(zt,{key:k.id,paddingRight:m},Me.createElement(Yn,{color:On(k.name)},"@"+k.name.at(0)))),F=r?d:n?R.accent:s===f.MOVE?R.secondary:R.primary,O=4,j=b.getCommentsByIssue(t.id),ne=j.length?String(j.length).length+2+m:0,Q=j.length?Me.createElement(zt,{paddingRight:m},Me.createElement(Yn,{color:R.accent},"[",j.length,"]")):null;return Me.createElement(zt,{borderBottom:!0,justifyContent:"space-between"},Me.createElement(zt,null,Me.createElement(zt,{width:O},n?Me.createElement(we,{isSelected:n}):Me.createElement(Yn,{color:"gray",dimColor:!0},o+1)),Me.createElement(Yn,{wrap:"truncate",color:F},ep(t.title,e-p-h-ne-18))),Me.createElement(zt,null,N,S,Q))}});import tp from"chalk";import{Box as us,Text as np}from"ink";import et from"react";var rp,cd,ld=y(()=>{"use strict";Z();w();Ce();vn();Kr();id();dd();Qr();rp=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u,replay:m}=$e(),p=u[e.id]??[],h=m?new Set(m.flashNodeIds):null,N=h?.has(e.id)??!1,S=xn(N),F=`${e.title} ${tp.hex(R.secondary2).dim("("+p.length+")")}`,O=3,j=o?1:4,ne=r-O-(o?2:1),Q=et.createElement(us,{borderStyle:"round",borderColor:R.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},et.createElement(we,{isSelected:t}),et.createElement(np,{bold:!0,color:N?S:t?R.accent:R.primary},F," ",e.readonly?"\u{1F512}":"")),k=($,Gt)=>{let Ct=s&&d===Gt;if(!T($))return null;let Kt=h?.has($.id)??!1;return o?et.createElement(ad,{key:$.id,index:Gt,width:n,ticket:$,isSelected:Ct,isFlashing:Kt,mode:l}):et.createElement(sd,{key:$.id,width:n,ticket:$,isSelected:Ct,isFlashing:Kt})};return et.createElement(us,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?R.accent:R.secondary,paddingRight:1,paddingLeft:1,height:r},Q,et.createElement(us,{padding:o?1:0},p.length>0&&et.createElement(yn,{selectedIndex:d,height:ne,itemHeight:j},p.map(k)),et.createElement(we,{isSelected:s&&d===-1})))},cd=et.memo(rp)});var ud,md,ms=y(()=>{"use strict";nn();ud=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},md=(e,t,n)=>fe.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0})});import{Box as xt,Text as it}from"ink";import de,{useEffect as op,useMemo as sp,useRef as ip}from"react";import{decodeTime as ps}from"ulid";function gd({ticket:e,width:t,height:n}){let r=sp(()=>dp(e),[e]),o=ip([]);op(()=>(pd(o.current),o.current=cp(e,r),()=>{pd(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=$e(),l=Math.max(1,n-4),u=Math.max(20,t-8);return r.length===0?de.createElement(xt,{flexDirection:"column",width:t,height:n,padding:1},de.createElement(it,{color:R.primary},"No comments yet."),de.createElement(xt,{paddingTop:1},de.createElement(it,{color:R.primary},"Use"),de.createElement(it,{color:R.accent}," :comment "),de.createElement(it,{color:R.primary},"to add the first one."))):de.createElement(xt,{flexDirection:"column",width:t,height:n},de.createElement(xt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:R.secondary,borderStyle:"single",paddingBottom:1},de.createElement(it,{color:R.secondary2},"Comments (",r.length,") ")),de.createElement(yn,{height:l,itemHeight:4,selectedIndex:s},r.map((m,p)=>{let h=p===s;return de.createElement(xt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:R.secondary,borderStyle:"single"},de.createElement(xt,{flexDirection:"row",paddingBottom:1},de.createElement(it,{color:R.accent},h?"\u276F ":" "),de.createElement(xt,{paddingLeft:1},de.createElement(it,{color:R.secondary2},`#${p+1} `),de.createElement(hn,{id:m.authorId}),de.createElement(it,{color:R.secondary2}," "+Cr(ps(m.id))))),de.createElement(xt,{paddingLeft:3,paddingBottom:1},de.createElement(it,{color:R.primary},lp(m.md,u))))})))}var ap,dp,pd,cp,lp,fd=y(()=>{"use strict";Be();sn();Z();C();ie();w();Ce();Un();Yr();Kr();ms();ap=e=>Se(e,"comments"),dp=e=>b.getCommentsByIssue(e.id).sort((t,n)=>ps(t.id)-ps(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),pd=e=>{for(let t of e)b.deleteNode(t.id)},cp=(e,t)=>{let n=b.getNode(ap(e.id));if(!n||!Ke(n))return[];let r=t.map((o,s)=>md(o,s,n.id)).map(b.createNode).filter(Rt).map(({value:o})=>o).filter(Fn);return t.length>0&&g().selectedIndex<0&&P.navigate({contextNode:n,selectedIndex:0}),r},lp=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`}});import{Box as eo,Text as up}from"ink";import at from"react";var vd,yd=y(()=>{"use strict";Z();ie();tn();w();Ce();Yr();vn();ls();vd=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=$e(),{title:o}=t,s=t.parentNodeId?b.getNode(t.parentNodeId):void 0,d=s&&T(s)?o===oe.ASSIGNEES?s.props.assignees??[]:o===oe.TAGS?s.props.tags??[]:[]:[];return at.createElement(eo,{alignItems:"center",paddingTop:1},at.createElement(eo,{minWidth:12},at.createElement(we,{isSelected:n}),at.createElement(up,{color:n?R.accent:R.secondary2},o,":")),at.createElement(eo,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=r.id===t.id&&u===e;return at.createElement(eo,{key:`${o}-${l}`,paddingRight:2,minHeight:1},at.createElement(we,{isSelected:m}),o===oe.ASSIGNEES?at.createElement(hn,{isSelected:m,id:l}):o===oe.TAGS?at.createElement(Xr,{isSelected:m,id:l}):null)})))}});import{Box as to,Text as gs}from"ink";import dt,{useEffect as mp,useMemo as hd}from"react";var pp,xd,fs,Id,gp,vs,bd=y(()=>{"use strict";ie();C();nn();w();Ce();Qt();vn();Kr();en();pp="\u2029",xd=(e,t)=>`${e}::inline-line::${t}`,fs=new Map,Id=e=>{let t=fs.get(e)??[];fs.delete(e);for(let n of t)b.deleteNode(n)},gp=(e,t)=>{Id(e);let n=[];t.forEach((r,o)=>{let s=Ue(BigInt(o+1));if(!Rt(s))return;let d=b.createNode(fe.text({id:xd(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));Rt(d)&&n.push(d.value.id)}),fs.set(e,n)},vs=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:d,contextNode:l}=$e(),u=hd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=hd(()=>u.join("\0"),[u]);mp(()=>(gp(e,u),()=>{Id(e)}),[e,m]);let p=N=>String(N).replace(/\r?\n/g,""),h=u.map((N,S)=>{let F=l.id===e&&d===S;return dt.createElement(to,{key:xd(e,S)},dt.createElement(gs,{color:F?R.primary:R.secondary2,dimColor:!F},`${S+1} `.padStart(5,"\xA0")),dt.createElement(gs,{backgroundColor:F?"gray":void 0},p(N.length?hr(N,s-10):pp)))});return dt.createElement(to,{flexDirection:"column",paddingTop:1},dt.createElement(to,null,dt.createElement(we,{isSelected:o}),dt.createElement(gs,{color:o?R.accent:R.secondary2},t)),dt.createElement(to,{flexDirection:"row",borderStyle:"round",borderColor:R.secondary,paddingLeft:1,marginLeft:1},dt.createElement(yn,{scrollByOne:!0,height:r-3,selectedIndex:d,itemHeight:1},h)))}});import{Box as Xn,Text as Ed}from"ink";import Le,{useMemo as no}from"react";var fp,vp,yp,Nd,Cd=y(()=>{"use strict";Z();ie();w();Ce();ms();Un();fd();vn();yd();bd();fp=e=>Se(e,"description"),vp=e=>Se(e,"comments"),yp=e=>Se(e,"history"),Nd=({ticket:e,height:t})=>{let n=no(()=>ud(e),[e]),{selectedIndex:r,contextNode:o}=$e(),s=process.stdout.columns||120,d=no(()=>fp(e.id),[e.id]),l=no(()=>vp(e.id),[e.id]),u=no(()=>yp(e.id),[e.id]),m=o.id===e.id,p=o.id===l||o.parentNodeId===l,h=o.id===u||o.parentNodeId===u,N=V(e.id);if(p){let $=t-3;return Le.createElement(Xn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Le.createElement(gd,{ticket:e,width:s,height:$}))}if(h){let k=b.getNode(u),$=k&&Ke(k)?k.props.value??"":"",Ct=t-3;return Le.createElement(Xn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},k?Le.createElement(vs,{id:k.id,label:"Event log",text:$,selected:!1,maxWidth:s,height:Ct}):null)}let S=N.reduce((k,$)=>Pn($)||$.id===l||$.id===u?k+1:k,0),F=2,O=3,j=S,ne=t-O-j-F,Q=(k,$)=>k.id===d?Le.createElement(vs,{key:k.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:$,maxWidth:s,height:ne}):Pn(k)?Le.createElement(vd,{key:k.id,parent:k,selected:$,selectedIndex:r}):k.id===l?Le.createElement(Xn,{key:k.id,paddingTop:1},Le.createElement(we,{isSelected:$}),Le.createElement(Ed,{backgroundColor:R.secondary,color:$?R.accent:R.primary},` Comments (${n}) \u203A\u203A `)):k.id===u?Le.createElement(Xn,{key:k.id,paddingTop:1},Le.createElement(we,{isSelected:$}),Le.createElement(Ed,{backgroundColor:R.secondary,color:$?R.accent:R.primary}," History \u203A\u203A ")):null;return Le.createElement(Xn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},N.map((k,$)=>Q(k,m&&r===$)))}});import{Box as hp}from"ink";import ro from"react";var xp,Rd,Sd=y(()=>{"use strict";Z();ld();Cd();xp=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:d,width:l})=>{let u=t.context,m=u===M.TICKET||u===M.FIELD_LIST||u===M.FIELD,p=u===M.BOARD||u===M.SWIMLANE,h=u===M.TICKET?t:r.find(j=>j.context===M.TICKET),N=Math.floor(l/3),S=Math.floor(l/Math.max(e.length,1)),F=Math.min(S,N),O=s==="dense";return ro.createElement(hp,{flexDirection:"row",height:d},p&&e.map((j,ne)=>{let Q=t.id===j.id,k=Q?n:-1,$=t.context===M.BOARD&&n===ne;return ro.createElement(cd,{key:j.id,height:d,width:F,swimlane:j,isSelected:$,isDense:O,isFocused:Q,listSelectedIndex:k,mode:o})}),m&&h&&ro.createElement(Nd,{height:d,ticket:h}))},Rd=ro.memo(xp)});import Ad from"node:fs";import Ip from"node:path";import bp from"react";import{render as Ep}from"ink";import{Writable as Np}from"node:stream";var Jn,Cp,Rp,Sp,Ap,Td,wd=y(()=>{"use strict";Sd();Z();C();w();ue();Ee();Jn=e=>String(e).padStart(2,"0"),Cp=e=>{let t=e.getUTCFullYear(),n=Jn(e.getUTCMonth()+1),r=Jn(e.getUTCDate()),o=Jn(e.getUTCHours()),s=Jn(e.getUTCMinutes()),d=Jn(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${d}`},Rp=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Sp=async(e,{width:t,height:n})=>{let r="",o=new Np({write(d,l,u){let m=Ap(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=Ep(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),r},Ap=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Td=async()=>{let{viewMode:e}=ee(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=g(),d=r.find(ne=>ne.context==="BOARD");if(!d)return i("No board found to export");let l=120,u=40,m=await Sp(bp.createElement(Rd,{height:u,width:l,swimlanes:(s[d.id]??[]).filter(ne=>ne!==void 0&&Dn(ne)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:u});if(!m)return i("Failed to render board export");let p=rr(process.cwd());if(a(p))return i("Unable to export, epiq root not found");let h=new Date,N=Cp(h),S=`board_${Rp(d.title)}_${N}.md`,F=Vs(p.value);Ad.mkdirSync(F,{recursive:!0});let O=Ip.join(F,S),j=`# Board - ${d.title}
45
- Date: ${h.toISOString()}
44
+ `)}`):(gm(),x({hasProjectDefinition:!0}),c("State booted successfully",null))}var Kn,Ur=h(()=>{"use strict";_e();X();C();an();T();rn();bt();un();Kn=mm()});var V,Zo=h(()=>{"use strict";C();V=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});var nt,Br,fm,ha,es=h(()=>{"use strict";va();Ur();mn();Ge();X();C();T();_r();Zo();ts();nt=null,Br=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!nt,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),nt)return logger.debug("[sync] syncAndReloadState joining existing promise"),nt;logger.debug("[sync] syncAndReloadState creating promise"),nt=fm();try{let e=await nt;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:g().syncStatus?.status,statusMessageAfterResolve:g().syncStatus?.msg}),a(e)&&g().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),x({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),nt||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),nt=null}},fm=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=ha();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(nt)return nt;logger.debug("[sync] syncAndReloadState:start");let t=V("resolveActorId",J());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),i("Unable to resolve event log path");x({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:g().syncStatus});let n=jt(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=V("syncEpiqWithRemote",await jr({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(r),message:(a(r),r.message)}),a(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),x({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),$e(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let s=V("loadMergedEvents",_t(o));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(s),message:(a(s),s.message),count:a(s)?void 0:s.value.length}),a(s))return x({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:g().syncStatus}),i(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let d=ha();if(d)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:d.message,syncStatus:g().syncStatus}),d;let l=pa(),u=g().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:l,selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id,selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual}),!g().selectedNode?.isVirtual&&!g().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let p=V("bootStateFromEventLog",Yn(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(p),message:(a(p),p.message)}),a(p))return x({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:g().syncStatus}),i(`Unable to boot synced state. ${p.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),x({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=V("restoreNavigationAnchor",fa(l));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(m),message:a(m)?m.message:"Navigation restored",selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id}),a(m)?(x({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),m):(x({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),c("Synced",!0))},ha=()=>g().mode===f.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),x({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),i("Will not re-materialize if not in default mode, to not lose edit data"))});var gn,xa,Ia,ns,rs,Xn,os,vm,Ea,ym,ba,$r=h(()=>{"use strict";C();Ne();T();es();gn=3e3,xa=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<gn?null:t},Ia=0,rs=!1,Xn=!1,os=()=>{if(rs)return!0;let e=je();return a(e)?!1:e.value.syncStatus.status==="syncing"},vm=()=>{let e=re().autoSyncIntervalMs??1e4,t=Date.now()-Ia;return Math.max(0,e-t)},Ea=()=>{ns||(ns=setTimeout(async()=>{if(ns=void 0,!!fn()){if(os()){Xn=!0;return}Xn=!1,await ym()}},vm()))},ym=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return i("Cannot auto-sync while peeking");if(!fn())return i("Cannot auto-sync before state is initialized");if(os())return Xn=!0,i("Sync already in progress");rs=!0,Ia=Date.now(),x({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Br()}finally{rs=!1,Xn&&Ea()}},ba=()=>{fn()&&(Xn=!0,!os()&&Ea())}});var Wr,Na,Ca,Sa,Jn=h(()=>{"use strict";C();Pt();Ne();pe();Wr=()=>{let e=re(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},Na=()=>{let e=vt(process.cwd());if(a(e))return!1;let t=ht(e.value);return Lt(t)},Ca=e=>e===!0?"on":e===!1?"off":null,Sa=e=>e==="on"?!0:e==="off"?!1:null});var hm,xm,Nt,Ct,Hr,Vr,Qn=h(()=>{"use strict";ne();C();ae();T();hm=e=>e.props.tags??[],xm=e=>e.props.assignees??[],Nt=e=>hm(e).map(t=>E.getTag(t)).filter(t=>!!t),Ct=e=>xm(e).map(t=>E.getContributor(t)).filter(t=>!!t),Hr=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!w(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Nt(n))},Vr=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!w(n)?i("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",Ct(n))}});var v,Ht=h(()=>{"use strict";v={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""}});var Im,Em,bm,Nm,Cm,Vt,Ra,zr,qr,Aa,Sm,ss,Zn=h(()=>{"use strict";Im=/^(\d+)(h|d|w|mo|y)$/,Em=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,bm=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let s=new Date(e,t-1,n,r,o);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===r&&s.getMinutes()===o},Nm=(e,t=new Date)=>{let n=e.match(Im);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let d=new Date(t);switch(o){case"h":return d.setHours(d.getHours()-s),d;case"d":return d.setDate(d.getDate()-s),d;case"w":return d.setDate(d.getDate()-s*7),d;case"mo":return d.setMonth(d.getMonth()-s),d;case"y":return d.setFullYear(d.getFullYear()-s),d;default:return null}},Cm=e=>{let t=e.match(Em);if(!t)return null;let[,n,r,o,s,d]=t,l=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,y=d?Number(d):0;return bm({year:l,month:u,day:m,hour:p,minute:y})?new Date(l,u-1,m,p,y):null},Vt=e=>{let t=e.trim().toLowerCase();return Nm(t)??Cm(t)},Ra=/^(\d+)(s|m)?$/,zr=e=>{let t=e.trim().toLowerCase().match(Ra);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},qr=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Ra.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Aa=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Sm=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],ss=(e=Sm)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let s=r;s<=o;s++)t.push(`${s}${n}`);return t}});var Rm,se,Te,ce,Am,Tm,as,Ma,zt,Gr,is,Ta,wm,Mm,er,wa,km,Lm,Pm,ie,St=h(()=>{"use strict";$r();Jn();un();ne();ae();T();Tr();Qn();Ht();Zn();Rm=["BOARD","TICKET","SWIMLANE","COMMENT"],se={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},Te={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},ce={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},Am=[se.EDITOR,se.VIEW,se.USERNAME,se.AUTOSYNC,se.SYNC_DEBOUNCE_MS,se.LOG_LEVEL],Tm=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[Te.TITLE,Te.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Te.TITLE];case"COMMENT":return[Te.COMMENT];default:return[]}},as=[String(gn),"5000","15000","30000","60000"],Ma=["10s","20s","30s","45s"],zt=[v.COFFEE,v.EXIT,v.SYNC,v.HELP,v.EXPORT,v.CONFIG,v.YANK],Gr=[v.NEW,v.EDIT,v.DELETE,v.MOVE],is=[v.TAG,v.UNTAG,v.ASSIGN,v.UNASSIGN,v.CLOSE_ISSUE,v.RE_OPEN_ISSUE,v.EDIT,v.COMMENT],Ta=[v.FILTER,v.PEEK,v.REPLAY],wm={WORKSPACE:[...zt,...Gr],BOARD:[...Ta,...zt,...Gr],SWIMLANE:[...Ta,...zt,...Gr],TICKET:[...zt,...Gr,...is],FIELD:[...zt,...is],FIELD_LIST:[...zt,...is],TEXT:[...zt],COMMENT:[v.EDIT,v.DELETE,v.YANK]},Mm=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],er=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&w(n)),wa=e=>e.parentNodeId===de,km=({selectedNode:e,breadCrumb:t})=>{let n=Tm(e?.context);return er({breadCrumb:t,selectedNode:e})?n.includes(Te.DESCRIPTION)?n:[...n,Te.DESCRIPTION]:n},Lm=({selectedNode:e,breadCrumb:t})=>{let n=er({breadCrumb:t,selectedNode:e});return n?[ce.REF,ce.TITLE,...n.props?.description?.trim()?[ce.DESCRIPTION]:[],...Nt(n).length>0?[ce.TAGS]:[],...Ct(n).length>0?[ce.ASSIGNEES]:[]]:e?[ce.REF,ce.TITLE]:[]},Pm=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Wr();if(!r)return[v.HELP,v.CONFIG];if(!Na())return[v.HELP,v.INIT];if(t)return[v.HELP,v.PEEK,v.REPLAY,v.EXPORT,v.CONFIG,v.YANK];let o=e?.context,s=o&&Rm.includes(o),d=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?wm[u]:[]))],l=er({breadCrumb:n,selectedNode:e});return d.filter(u=>u===v.MOVE?!1:u===v.YANK?!!(l??e):u===v.EDIT?s||!!l:u===v.DELETE?s:u===v.UNTAG?!!(l&&Nt(l).length>0):u===v.UNASSIGN?!!(l&&Ct(l).length>0):u===v.RE_OPEN_ISSUE?!!(l&&wa(l)):u===v.CLOSE_ISSUE?!!(l&&!wa(l)):!0)},ie=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=g())=>{let s=t.context??"WORKSPACE";return{[v.NONE]:Pm({breadCrumb:o,readOnly:r,selectedNode:n}),[v.EXIT]:["confirm"],[v.EXPORT]:[],[v.SYNC]:[],[v.INIT]:[],[v.HELP]:[],[v.PEEK]:[...ss(),"now","prev","next"],[v.REPLAY]:[...ss()],[v.EDIT]:km({selectedNode:n,breadCrumb:o}),[v.YANK]:Lm({selectedNode:n,breadCrumb:o}),[v.COMMENT]:[],[v.DELETE]:["confirm"],[v.RE_OPEN_ISSUE]:["confirm"],[v.CLOSE_ISSUE]:["confirm"],[v.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[v.FILTER]:["tag","assignee","description","title","ref","clear"],[v.TAG]:[...new Set([...Object.keys(dn),...E.getExistingTags()])],[v.UNTAG]:[...Hr()?.value?.map(({name:l})=>l)??[]],[v.UNASSIGN]:[...Vr()?.value?.map(({name:l})=>l)??[]],[v.ASSIGN]:E.getExistingAssignees(),[v.NEW]:Mm(s),[v.CONFIG]:[...Am],[v.COFFEE]:["1","3","5","20","custom"]}[e]??[]}});var ka,La=h(()=>{"use strict";ka=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});var we,qt=h(()=>{"use strict";C();we=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?c("Found node",n):i("Unable to find node in breadcrumb")}});import Pa from"chalk";var q,fe,ve,Da=h(()=>{"use strict";ct();Se();q=e=>Pa.dim(e),fe=e=>Pa.hex(S.primary)(e),ve=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let d=o.trim();if(d.length<s)return"";let p=[...t.filter(Boolean).filter(y=>y.startsWith(d))].sort((y,N)=>wr(y)-wr(N)).slice(0,r).map(y=>Mr(y)).join(" ");return p?`${q(e)}${p}${q(n)}`:""}});var Rt,Kr=h(()=>{"use strict";Rt={None:"none",Invalid:"invalid",Valid:"valid"}});import Ua from"chalk";var vn,Dm,Fa,Q,W,O,Xr,Oa,Yr,ds,Fm,Gt,Om,Um,Bm,_m,Ba,cs=h(()=>{"use strict";$r();Jn();La();ln();qt();C();ae();Ne();T();ct();Qn();zn();Da();Ht();Kr();St();Zn();vn=140,Dm=["BOARD","TICKET","SWIMLANE"],Fa=()=>{let e=g().selectedNode;if(!e?.context)return O({message:q("Missing target context")});if(Dm.includes(e.context))return W();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===Ae(t?.parentNodeId??"","comments"))return W()}return O({message:q("Command not available in this context")})},Q="<ENTER> to confirm",W=(e="",t=[])=>({message:q(e),validity:Rt.Valid,completionWordList:t}),O=({message:e,completionWordList:t=[]})=>({validity:Rt.Invalid,message:e,completionWordList:t}),Xr=e=>e.length===0,Oa=(e,t)=>{let n=we(g().breadCrumb,"BOARD");if(a(n))return O({message:fe("Command is not applicable in this context")});let r=Hi(n.value.id);return a(r)?O({message:fe(`Unable to ${t}: board id is not a valid ULID`)}):Aa({date:e,horizonDate:r.value})?null:O({message:fe(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},Yr=e=>` ${Ua.hex("#000").bgHex(Re(e))(` ${e} `)} `,ds=({modifier:e})=>{let t="confirm";return e===t?W(Q):O({message:Xr(e)?q("if you are certain, enter ")+Mr(t):"",completionWordList:[t]})},Fm=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?O({message:q(n)}):W():O({message:Xr(r)?t:"",completionWordList:[...e]}),Gt=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>Xr(n)&&Xr(r)?O({message:e,completionWordList:[]}):W(t??Q),Om=({modifier:e,inputString:t})=>{let n=ie(v.CONFIG);if(!n.includes(e))return O({message:ve({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case se.EDITOR:{let r=[...ka];return t.trim()?r.includes(t.trim())?W(Q):O({message:ve({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):O({message:ve({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case se.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?W(Q):O({message:ve({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case se.USERNAME:return t.trim()?W(Q):O({message:fe("Enter a user name. Saved in ")+Ua.bgBlack("~/.epiq-global/config.json")});case se.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?W(Q):O({message:ve({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case se.AUTOSYNC:{let r=["on","off"],o=re().autoSync;if(!r.includes(t.trim())){let s=Ca(o);return O({message:ve({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return W(Q)}case se.SYNC_DEBOUNCE_MS:{let r=re().autoSyncIntervalMs,o=xa(t);if(!t.trim()||o===null||o<gn){let s=ve({prefix:" examples: ",wordList:as,minLengthForHints:0,inputString:t});return O({message:fe(`provide duration above ${gn}ms. current duration: ${r}ms.`)+s,completionWordList:as})}return W(Q)}default:return O({message:fe("Unknown config option"),completionWordList:n})}},Um=({modifier:e,inputString:t})=>{let n=ie(v.EDIT);if(!n.length)return O({message:fe("Command not available in this context")});if(!n.includes(e)){let r=ve({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return O({message:r||fe("Unknown edit option"),completionWordList:n})}switch(e){case Te.COMMENT:return t.trim()?W(Q):O({message:q("write a comment...")});case Te.TITLE:return W(Q);case Te.DESCRIPTION:{let{preferredEditor:r}=re();return r?W(q("<ENTER> to edit in ")+r):O({message:"No editor selected"})}default:return O({message:fe("Unknown edit option"),completionWordList:n})}},Bm=({modifier:e})=>{let t=ie(v.YANK);return t.length?t.includes(e)?W(Q+q(" and copy to clipboard")):O({message:ve({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):O({message:fe("Nothing selected to copy from")})},_m={[v.EXPORT]:()=>W(Q+q(", and create export markdown file")),[v.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return W(Q);let n={message:q("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Vt(r);if(!r||!o)return O(n);let s=Oa(o,"peek");return s||W(Q)},[v.REPLAY]:e=>{let{dateInput:t,durationInput:n}=qr(e.modifier,e.inputString),r={message:q("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Vt(t);if(!t||!o)return O(r);let s=Oa(o,"replay");return s||(n&&zr(n)===null?O({message:fe("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):W("<ENTER> to replay board history",n?Ma:[]))},[v.EXIT]:()=>W(Q+q(" and exit the application")),[v.INIT]:()=>W(Q),[v.PALETTE]:()=>W(Q),[v.FILTER]:e=>{if(e.modifier==="clear")return W(Q);let t=s=>ie(v.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return O({message:ve({wordList:ie(v.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:ie(v.FILTER)});let n=Object.values(g().tags).map(s=>s.name),r=Object.values(g().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?O({message:ve({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):W():O({message:ve({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[v.NONE]:e=>{let t=ie(v.NONE);return O({message:ve({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[v.NEW]:e=>Fm({list:ie(v.NEW),hint:ve({wordList:ie(v.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[v.HELP]:()=>W(Q),[v.EDIT]:Um,[v.COMMENT]:e=>{let t=Gt({hint:q(`write a comment (max ${vn} char)...`),onOk:q(`(${e.inputString.length}/${vn})`)})(e);return t.validity===Rt.Invalid?t:e.inputString.length>vn?W(fe("max input exceeded")):t},[v.CONFIG]:Om,[v.YANK]:Bm,[v.DELETE]:e=>{let t=Fa();return t.validity==="invalid"?t:ds(e)},[v.CLOSE_ISSUE]:e=>ds(e),[v.RE_OPEN_ISSUE]:e=>ds(e),[v.MOVE]:e=>{let t=Fa();return t.validity==="invalid"?t:Gt({hint:ve({prefix:"hey hacker! These commands are blocked for you... ",wordList:ie(v.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[v.TAG]:e=>{let n=E.getExistingTags().slice(0,10).map(Yr).join("");return Gt({hint:n.length?q("create tag or reuse:")+n+q(""):q("create tag ...")})(e)},[v.UNTAG]:e=>{let t=Hr();if(a(t))return O({message:fe("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Yr).slice(0,10);return n.length?Gt({hint:q(" ... ")+n.join("")})(e):O({message:fe("Issue has no tags"),completionWordList:[]})},[v.ASSIGN]:e=>{let t=E.getExistingAssignees().map(Yr).slice(0,10);return Gt({hint:q("assignees... ")+t.join("")})(e)},[v.UNASSIGN]:e=>{let t=Vr();if(a(t))return O({message:fe("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Yr).slice(0,10);return n.length?Gt({hint:q("remove assignee... ")+n.join("")})(e):O({message:fe("Issue has no assignees"),completionWordList:[]})},[v.SYNC]:()=>W(Q),[v.COFFEE]:e=>{let{modifier:t}=e,n=ie(v.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?O({message:q("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):Gt({hint:ve({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},Ba=Object.fromEntries(Object.entries(_m).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]))});var Jr,_a=h(()=>{"use strict";Jr=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"]});var jm,$m,Wm,Hm,Vm,ja,$a,Wa,Ha=h(()=>{"use strict";C();T();_a();jm=3,$m=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),Wm=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let r=n.props;typeof r.description=="string"&&t.push(r.description),typeof r.value=="string"&&t.push(r.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},Hm=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=jm&&!$m.has(t)&&!/^\d+$/.test(t)),Vm=e=>{let t=new Map;for(let s of Wm(e))for(let d of Hm(s))t.set(d,(t.get(d)??0)+1);let n=[...t.entries()].sort((s,d)=>d[1]-s[1]||s[0].localeCompare(d[0])).map(([s])=>s),r=new Set(n),o=Jr.filter(s=>!r.has(s));return[...n,...o]},ja=Jr,$a=-1,Wa=()=>{let e=je();if(a(e))return Jr;let t=e.value,n=t.eventLog.length;return n!==$a&&(ja=Vm(t),$a=n),ja}});var Va,za,ls=h(()=>{"use strict";ki();St();Ht();cs();Ha();T();X();Va=e=>Object.values(v).includes(e),za=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:d,validity:l,completionWordList:u}=Ba[n].validate(n,r,s),m=n!==v.PEEK&&n!==v.REPLAY,p=o==="command"||o==="modifier"?ie(n):m?Wa():[],{mode:y}=g(),N=y===f.COMMAND_LINE?d??"":"",R=[...u,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:N,autoCompletion:t?Mi(e,R):{hint:"",hints:[],remainder:"",overlap:0}}}});var qa,zm,qm,Gm,Ga=h(()=>{"use strict";ls();St();qa=e=>{let t=e.trimStart(),n=qm(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),d=Gm(e),l=Va(r)?r:null,u=l!==null,m=r!=="",p=l?ie(l)??[]:[],y=l&&p.includes(o)?o:"",N="word";n.length===0||n.length===1&&!s?N="command":(n.length===1&&s||n.length===2&&!s)&&(N="modifier");let R=s?"":d,F=zm(t,l,y);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:s,modifier:y,target:N,inputToMatch:R,inputString:F}},zm=(e,t,n)=>{let r=e;return t&&r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/^\s+/,""),n&&r.startsWith(n)&&(r=r.slice(n.length),r=r.replace(/^\s+/,"")),r},qm=e=>e.trim()?e.trim().split(/\s+/):[],Gm=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as LI}from"react";var yn,us,hn,Km,Ka,rt,tr,ms,ps,Ya,Xa,Qr,Ja,$,Qa,Za,ed,Z,td,ue=h(()=>{"use strict";ls();Ga();C();Kr();yn=e=>e===us||e===":",us=" ",hn={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Rt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Km=new Set,Ka=()=>{for(let e of Km)e()},rt=e=>{let n=e(hn),r=qa(n.value),o=n.cursorPosition===n.value.length;hn={...n,commandMeta:za(r,o)},Ka()},tr=({message:e,status:t})=>{let n=structuredClone(hn);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,hn=n,Ka(),c(e,null)},ms=e=>{rt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},ps=e=>{rt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&yn(n[o-1]);)o--;for(;o>0&&!yn(n[o-1]);)o--}else{for(;o<n.length&&!yn(n[o]);)o++;for(;o<n.length&&yn(n[o]);)o++}return{...t,cursorPosition:o}})},Ya=()=>{rt(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},Xa=()=>{rt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&yn(t[r-1]);)r--;for(;r>0&&!yn(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Qr=e=>{rt(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),d=s+o,l=Math.max(0,Math.min(s.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},Ja=()=>{rt(e=>({...e,commandIsPending:!0}))},$=e=>{rt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Qa=({addToHistory:e=!0})=>{rt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Za=()=>{rt(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ed=()=>{rt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Z=()=>hn,td=()=>{let[e,...t]=hn.value.split(us);return t.join(us).trim()}});var A,Ft=h(()=>{"use strict";X();Ni();T();ue();Ne();A={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"}});var nd,M,gs=h(()=>{"use strict";T();Ht();nd=e=>{let{context:t}=g().contextNode;if(!t)return M.None;switch(e){case v.EXIT:return M.Exit;case v.EXPORT:return M.Export;case v.COFFEE:return M.Coffee;case v.INIT:return M.Init;case v.DELETE:return M.Delete;case v.EDIT:return M.Edit;case v.COMMENT:return M.Comment;case v.HELP:return M.ViewHelp;case v.RE_OPEN_ISSUE:return M.ReopenIssue;case v.CLOSE_ISSUE:return M.CloseIssue;case v.TAG:return M.TagTicket;case v.UNTAG:return M.UntagTicket;case v.ASSIGN:return M.AssignUserToTicket;case v.UNASSIGN:return M.UnassignUserFromTicket;case v.NEW:return M.NewItem;case v.FILTER:return M.Filter;case v.MOVE:return M.Move;case v.PEEK:return M.Peek;case v.REPLAY:return M.Replay;case v.CONFIG:return M.Config;case v.YANK:return M.Yank;case v.SYNC:return M.Sync;default:return M.None}},M={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export",Coffee:"coffee"}});import{Text as rd}from"ink";import od,{useEffect as sd,useState as Ym}from"react";var id,Me,xn=h(()=>{"use strict";T();Se();id={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Me=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=We(),r=id[n]??id.default,[o,s]=Ym(0);if(sd(()=>{s(0)},[r]),sd(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return od.createElement(rd,null,t);let d=r[o]??r[0]??t;return od.createElement(rd,{color:S.accent,dimColor:o===1},d)}});import{Box as fs,Text as Xm}from"ink";import Zr from"react";var In,eo=h(()=>{"use strict";Se();In=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),d=Math.max(1,Math.ceil(r)),l=Math.max(1,Math.floor(s/d)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-l),p=o?Math.min(m,Math.max(0,u-l+1)):Math.min(m,Math.floor(u/l)*l),y=p+l,N=e.slice(p,y),R=e.length>l,F=s,U=R?Math.max(1,Math.floor(l/e.length*F)):F,j=Math.max(0,F-U),ee=Math.max(1,e.length-l),te=R?Math.floor(p/ee*j):0;return Zr.createElement(fs,{flexDirection:"row",height:s,width:"100%"},Zr.createElement(fs,{flexDirection:"column",flexGrow:1,height:s},N),Zr.createElement(fs,{flexDirection:"column",width:1,height:F},Array.from({length:F}).map((L,H)=>Zr.createElement(Xm,{key:H,color:R&&H>=te&&H<te+U?S.accent:S.secondary},R?"\u2502":" "))))}});import{Text as Jm}from"ink";import Qm from"react";var Zm,ep,En,to=h(()=>{"use strict";Tr();ct();ae();Zm=e=>e.toLowerCase().trim(),ep=(e,t=dn)=>{let n=Zm(e);return t[n]?t[n]:Vn(n)},En=({id:e,isSelected:t})=>{let n=E.getContributor(e);if(n)return Qm.createElement(Jm,{underline:t,color:ep(n.name)},"@"+n.name)}});import{Text as tp}from"ink";import np from"react";var no,vs=h(()=>{"use strict";ae();Se();ct();no=({id:e,isSelected:t})=>{let n=E.getTag(e);if(n)return np.createElement(tp,{underline:t,backgroundColor:Re(n.name),color:S.secondary}," "+n.name+" ")}});import{useEffect as rp,useState as op}from"react";var sp,ad,ro,nr,ip,ap,bn,oo=h(()=>{"use strict";ct();sp=80,ad=1400,ro=new Set,nr=null,ip=e=>(ro.add(e),nr||(nr=setInterval(()=>{for(let t of ro)t()},sp)),()=>{ro.delete(e),ro.size===0&&nr&&(clearInterval(nr),nr=null)}),ap=()=>{let e=Date.now()%ad/ad;return e<.5?e*2:(1-e)*2},bn=e=>{let[,t]=op(0);return rp(()=>{if(e)return ip(()=>t(n=>n+1))},[e]),$i(ap())}});import{Box as Nn,Text as so}from"ink";import He from"react";var dp,dd,cd=h(()=>{"use strict";Se();tn();sn();Qn();to();vs();oo();dp=(e,t)=>{if(e.length<=t)return[e,null];let n=e.lastIndexOf(" ",t),r=n>0?n:t;return[e.slice(0,r),Hn(e.slice(r).trim(),t)]},dd=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=bn(r),s=e-4,[d,l]=dp(xt(t.title),s),u=l?null:Hn(xt(t.props.description),s)||null,m=Nt(t),p=Ct(t);return He.createElement(Nn,{borderStyle:"round",height:5,flexDirection:"column",borderDimColor:!n,borderColor:r?o:n?S.accent:S.secondary,justifyContent:"space-between"},He.createElement(Nn,{paddingLeft:1,flexDirection:"column"},He.createElement(so,{color:S.primary},d),l&&He.createElement(so,{color:S.primary},l),u&&He.createElement(so,{color:S.secondary2,dimColor:!0},u)),He.createElement(Nn,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1,paddingRight:1},He.createElement(Nn,{flexDirection:"row"},m.map(y=>He.createElement(Nn,{paddingRight:1,key:y.id},He.createElement(no,{key:y.id,id:y.id}))),p.map(y=>He.createElement(Nn,{paddingRight:1,key:y.id},He.createElement(En,{key:y.id,id:y.id})))),He.createElement(so,{wrap:"truncate",color:S.secondary2,dimColor:!0},"#",qe(t.id))))}});import{Box as Kt,Text as rr}from"ink";import ke from"react";var cp,ld,ud=h(()=>{"use strict";X();ae();Se();ct();xn();oo();cp=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,ld=({width:e,ticket:t,isSelected:n,isFlashing:r=!1,index:o,mode:s})=>{let d=bn(r),l=(t.props.tags??[]).map(L=>E.getTag(L)).filter(L=>!!L),u=(t.props.assignees??[]).map(L=>E.getContributor(L)).filter(L=>!!L),m=1,p=l.length*(1+m),y=u.length*(2+m),N=l.map(L=>ke.createElement(Kt,{key:L.id,paddingRight:m},ke.createElement(rr,{color:Re(L.name)},"\u25A0"))),R=u.map(L=>ke.createElement(Kt,{key:L.id,paddingRight:m},ke.createElement(rr,{color:Vn(L.name)},"@"+L.name.at(0)))),F=r?d:n?S.accent:s===f.MOVE?S.secondary:S.primary,U=4,j=E.getCommentsByIssue(t.id),ee=j.length?String(j.length).length+2+m:0,te=j.length?ke.createElement(Kt,{paddingRight:m},ke.createElement(rr,{color:S.accent},"[",j.length,"]")):null;return ke.createElement(Kt,{borderBottom:!0,justifyContent:"space-between"},ke.createElement(Kt,null,ke.createElement(Kt,{width:U},n?ke.createElement(Me,{isSelected:n}):ke.createElement(rr,{color:"gray",dimColor:!0},o+1)),ke.createElement(rr,{wrap:"truncate",color:F},cp(t.title,e-p-y-ee-18))),ke.createElement(Kt,null,N,R,te))}});import lp from"chalk";import{Box as ys,Text as up}from"ink";import ot from"react";var mp,md,pd=h(()=>{"use strict";ne();T();Se();xn();eo();cd();ud();oo();mp=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u,replay:m}=We(),p=u[e.id]??[],y=m?new Set(m.flashNodeIds):null,N=y?.has(e.id)??!1,R=bn(N),F=`${e.title} ${lp.hex(S.secondary2).dim("("+p.length+")")}`,U=3,j=o?1:5,ee=s&&d===-1,te=n-(ee?7:5),L=r-U-(o?2:1),H=ot.createElement(ys,{borderStyle:"round",borderColor:S.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},ot.createElement(Me,{isSelected:t}),ot.createElement(up,{bold:!0,color:N?R:t?S.accent:S.primary},F," ",e.readonly?"\u{1F512}":"")),An=(Ve,Jt)=>{let Tn=s&&d===Jt;if(!w(Ve))return null;let wn=y?.has(Ve.id)??!1;return o?ot.createElement(ld,{key:Ve.id,index:Jt,width:n,ticket:Ve,isSelected:Tn,isFlashing:wn,mode:l}):ot.createElement(dd,{key:Ve.id,width:te,ticket:Ve,isSelected:Tn,isFlashing:wn})};return ot.createElement(ys,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?S.accent:S.secondary,paddingRight:1,paddingLeft:1,height:r},H,ot.createElement(ys,{padding:o?1:0},p.length>0&&ot.createElement(In,{selectedIndex:d,height:L,itemHeight:j},p.map(An)),ee&&ot.createElement(Me,{isSelected:!0})))},md=ot.memo(mp)});var gd,fd,hs=h(()=>{"use strict";an();gd=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},fd=(e,t,n)=>he.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0})});import{Box as At,Text as ut}from"ink";import le,{useEffect as pp,useMemo as gp,useRef as fp}from"react";import{decodeTime as xs}from"ulid";function yd({ticket:e,width:t,height:n}){let r=gp(()=>yp(e),[e]),o=fp([]);pp(()=>(vd(o.current),o.current=hp(e,r),()=>{vd(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=We(),l=Math.max(1,n-4),u=Math.max(20,t-8);return r.length===0?le.createElement(At,{flexDirection:"column",width:t,height:n,padding:1},le.createElement(ut,{color:S.primary},"No comments yet."),le.createElement(At,{paddingTop:1},le.createElement(ut,{color:S.primary},"Use"),le.createElement(ut,{color:S.accent}," :comment "),le.createElement(ut,{color:S.primary},"to add the first one."))):le.createElement(At,{flexDirection:"column",width:t,height:n},le.createElement(At,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:S.secondary,borderStyle:"single",paddingBottom:1},le.createElement(ut,{color:S.secondary2},"Comments (",r.length,") ")),le.createElement(In,{height:l,itemHeight:4,selectedIndex:s},r.map((m,p)=>{let y=p===s;return le.createElement(At,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:S.secondary,borderStyle:"single"},le.createElement(At,{flexDirection:"row",paddingBottom:1},le.createElement(ut,{color:S.accent},y?"\u276F ":" "),le.createElement(At,{paddingLeft:1},le.createElement(ut,{color:S.secondary2},`#${p+1} `),le.createElement(En,{id:m.authorId}),le.createElement(ut,{color:S.secondary2}," "+kr(xs(m.id))))),le.createElement(At,{paddingLeft:3,paddingBottom:1},le.createElement(ut,{color:S.primary},xp(m.md,u))))})))}var vp,yp,vd,hp,xp,hd=h(()=>{"use strict";_e();ln();ne();C();ae();T();Se();zn();to();eo();hs();vp=e=>Ae(e,"comments"),yp=e=>E.getCommentsByIssue(e.id).sort((t,n)=>xs(t.id)-xs(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),vd=e=>{for(let t of e)E.deleteNode(t.id)},hp=(e,t)=>{let n=E.getNode(vp(e.id));if(!n||!Qe(n))return[];let r=t.map((o,s)=>fd(o,s,n.id)).map(E.createNode).filter(Lt).map(({value:o})=>o).filter(Wn);return t.length>0&&g().selectedIndex<0&&P.navigate({contextNode:n,selectedIndex:0}),r},xp=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`}});import{Box as io,Text as Ip}from"ink";import mt from"react";var xd,Id=h(()=>{"use strict";ne();ae();on();T();Se();to();xn();vs();xd=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=We(),{title:o}=t,s=t.parentNodeId?E.getNode(t.parentNodeId):void 0,d=s&&w(s)?o===Y.ASSIGNEES?s.props.assignees??[]:o===Y.TAGS?s.props.tags??[]:[]:[];return mt.createElement(io,{alignItems:"center",paddingTop:1},mt.createElement(io,{minWidth:12},mt.createElement(Me,{isSelected:n}),mt.createElement(Ip,{color:n?S.accent:S.secondary2},o,":")),mt.createElement(io,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=r.id===t.id&&u===e;return mt.createElement(io,{key:`${o}-${l}`,paddingRight:2,minHeight:1},mt.createElement(Me,{isSelected:m}),o===Y.ASSIGNEES?mt.createElement(En,{isSelected:m,id:l}):o===Y.TAGS?mt.createElement(no,{isSelected:m,id:l}):null)})))}});import{Box as ao,Text as Is}from"ink";import pt,{useEffect as Ep,useMemo as Ed}from"react";var bp,bd,Es,Nd,Np,bs,Cd=h(()=>{"use strict";ae();C();an();T();Se();tn();xn();eo();rn();bp="\u2029",bd=(e,t)=>`${e}::inline-line::${t}`,Es=new Map,Nd=e=>{let t=Es.get(e)??[];Es.delete(e);for(let n of t)E.deleteNode(n)},Np=(e,t)=>{Nd(e);let n=[];t.forEach((r,o)=>{let s=Be(BigInt(o+1));if(!Lt(s))return;let d=E.createNode(he.text({id:bd(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));Lt(d)&&n.push(d.value.id)}),Es.set(e,n)},bs=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:d,contextNode:l}=We(),u=Ed(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Ed(()=>u.join("\0"),[u]);Ep(()=>(Np(e,u),()=>{Nd(e)}),[e,m]);let p=N=>String(N).replace(/\r?\n/g,""),y=u.map((N,R)=>{let F=l.id===e&&d===R;return pt.createElement(ao,{key:bd(e,R)},pt.createElement(Is,{color:F?S.primary:S.secondary2,dimColor:!F},`${R+1} `.padStart(5,"\xA0")),pt.createElement(Is,{backgroundColor:F?"gray":void 0},p(N.length?Hn(N,s-10):bp)))});return pt.createElement(ao,{flexDirection:"column",paddingTop:1},pt.createElement(ao,null,pt.createElement(Me,{isSelected:o}),pt.createElement(Is,{color:o?S.accent:S.secondary2},t)),pt.createElement(ao,{flexDirection:"row",borderStyle:"round",borderColor:S.secondary,paddingLeft:1,marginLeft:1},pt.createElement(In,{scrollByOne:!0,height:r-3,selectedIndex:d,itemHeight:1},y)))}});import{Box as or,Text as Sd}from"ink";import Le,{useMemo as co}from"react";var Cp,Sp,Rp,Rd,Ad=h(()=>{"use strict";ne();ae();T();Se();hs();zn();hd();xn();Id();Cd();Cp=e=>Ae(e,"description"),Sp=e=>Ae(e,"comments"),Rp=e=>Ae(e,"history"),Rd=({ticket:e,height:t})=>{let n=co(()=>gd(e),[e]),{selectedIndex:r,contextNode:o}=We(),s=process.stdout.columns||120,d=co(()=>Cp(e.id),[e.id]),l=co(()=>Sp(e.id),[e.id]),u=co(()=>Rp(e.id),[e.id]),m=o.id===e.id,p=o.id===l||o.parentNodeId===l,y=o.id===u||o.parentNodeId===u,N=z(e.id);if(p){let H=t-3;return Le.createElement(or,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Le.createElement(yd,{ticket:e,width:s,height:H}))}if(y){let L=E.getNode(u),H=L&&Qe(L)?L.props.value??"":"",Ve=t-3;return Le.createElement(or,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},L?Le.createElement(bs,{id:L.id,label:"Event log",text:H,selected:!1,maxWidth:s,height:Ve}):null)}let R=N.reduce((L,H)=>jn(H)||H.id===l||H.id===u?L+1:L,0),F=2,U=3,j=R,ee=t-U-j-F,te=(L,H)=>L.id===d?Le.createElement(bs,{key:L.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:H,maxWidth:s,height:ee}):jn(L)?Le.createElement(xd,{key:L.id,parent:L,selected:H,selectedIndex:r}):L.id===l?Le.createElement(or,{key:L.id,paddingTop:1},Le.createElement(Me,{isSelected:H}),Le.createElement(Sd,{backgroundColor:S.secondary,color:H?S.accent:S.primary},` Comments (${n}) \u203A\u203A `)):L.id===u?Le.createElement(or,{key:L.id,paddingTop:1},Le.createElement(Me,{isSelected:H}),Le.createElement(Sd,{backgroundColor:S.secondary,color:H?S.accent:S.primary}," History \u203A\u203A ")):null;return Le.createElement(or,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},N.map((L,H)=>te(L,m&&r===H)))}});import{Box as Ap}from"ink";import lo from"react";var Tp,Td,wd=h(()=>{"use strict";ne();pd();Ad();Tp=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:d,width:l})=>{let u=t.context,m=u===k.TICKET||u===k.FIELD_LIST||u===k.FIELD,p=u===k.BOARD||u===k.SWIMLANE,y=u===k.TICKET?t:r.find(j=>j.context===k.TICKET),N=Math.floor(l/3),R=Math.floor(l/Math.max(e.length,1)),F=Math.min(R,N),U=s==="dense";return lo.createElement(Ap,{flexDirection:"row",height:d},p&&e.map((j,ee)=>{let te=t.id===j.id,L=te?n:-1,H=t.context===k.BOARD&&n===ee;return lo.createElement(md,{key:j.id,height:d,width:F,swimlane:j,isSelected:H,isDense:U,isFocused:te,listSelectedIndex:L,mode:o})}),m&&y&&lo.createElement(Rd,{height:d,ticket:y}))},Td=lo.memo(Tp)});import Md from"node:fs";import wp from"node:path";import Mp from"react";import{render as kp}from"ink";import{Writable as Lp}from"node:stream";var sr,Pp,Dp,Fp,Op,kd,Ld=h(()=>{"use strict";wd();ne();C();T();pe();Ne();sr=e=>String(e).padStart(2,"0"),Pp=e=>{let t=e.getUTCFullYear(),n=sr(e.getUTCMonth()+1),r=sr(e.getUTCDate()),o=sr(e.getUTCHours()),s=sr(e.getUTCMinutes()),d=sr(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${d}`},Dp=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Fp=async(e,{width:t,height:n})=>{let r="",o=new Lp({write(d,l,u){let m=Op(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=kp(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),r},Op=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),kd=async()=>{let{viewMode:e}=re(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=g(),d=r.find(ee=>ee.context==="BOARD");if(!d)return i("No board found to export");let l=120,u=40,m=await Fp(Mp.createElement(Td,{height:u,width:l,swimlanes:(s[d.id]??[]).filter(ee=>ee!==void 0&&$n(ee)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:u});if(!m)return i("Failed to render board export");let p=mr(process.cwd());if(a(p))return i("Unable to export, epiq root not found");let y=new Date,N=Pp(y),R=`board_${Dp(d.title)}_${N}.md`,F=Ys(p.value);Md.mkdirSync(F,{recursive:!0});let U=wp.join(F,R),j=`# Board - ${d.title}
45
+ Date: ${y.toISOString()}
46
46
 
47
47
  \`\`\`text
48
48
  ${m}
49
49
  \`\`\`
50
- `;return Ad.writeFileSync(O,j,"utf8"),c("Exported board layout",O)}});import{accessSync as Tp,copyFileSync as wp,existsSync as oo,mkdirSync as Md,readdirSync as Ld,readFileSync as Mp,renameSync as Lp,rmSync as kp,statSync as kd,unlinkSync as Pp,writeFileSync as Dp}from"node:fs";import In from"node:path";var ys,ke,hs=y(()=>{"use strict";ys=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",ke={writeToFile:(e,t)=>{try{let n=In.dirname(e);oo(n)||Md(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Dp(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Mp(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=ke.readFile(e);return t===null?null:JSON.parse(t)}catch(t){return logger.error(`Failed to read JSON at ${e}:`,t),null}},dirExists:e=>{try{return oo(e)&&kd(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Tp(e),!0}catch{return!1}},mkDir:e=>Md(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=In.parse(t);for(;;){let r=In.join(t,e);try{if(oo(r)&&kd(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=In.dirname(t)}return null},readFirstJSON(e){try{if(!ke.dirExists(e))return null;let t=Ld(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=In.join(e,t);return ke.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return ke.dirExists(e)?Ld(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Pp(e)}catch(t){(!ys(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{kp(e,{recursive:!0,force:!0})}catch(t){(!ys(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(In.dirname(t)),!n?.overwrite&&oo(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Lp(e,t)}catch(r){if(ys(r)&&r.code==="EXDEV"){wp(e,t),this.rmFile(e);return}throw r}}}});import Fp from"node:os";import Pd from"node:path";import{z as It}from"zod";var Op,Dd,Up,Fd,xs,Is,Bp,Od,Ud,ct,Bd,bn=y(()=>{"use strict";ue();C();hs();Op={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},Dd=It.object({logLevel:It.enum(["info","error","debug"]),preferredEditor:It.string().optional(),userName:It.string().optional(),userId:It.string().optional(),autoSync:It.boolean().nullable().optional(),autoSyncDebounceMs:It.number().optional(),viewMode:It.enum(["dense","wide"]).optional()}).partial(),Up="config.json",Fd=()=>Pd.join(Fp.homedir(),Fe),xs=()=>Pd.join(Fd(),Up),Is=()=>{try{return ke.mkDir(Fd()),c(`Ensured ~/${Fe} exists`,null)}catch{return i(`Unable to create ~/${Fe}`)}},Bp=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${Fe}/config.json JSON`)}let n=Dd.safeParse(t??{});return n.success?c("Parsed config",n.data):i(`Invalid ~/${Fe}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Od=()=>{let e=Is();if(a(e))return i(e.message);let t=xs(),n=ke.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Bp(n)},Ud=e=>{let t=Is();if(a(t))return i(t.message);let n=Dd.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=xs();try{return ke.writeToFile(r,JSON.stringify(n.data,null,2)+`
51
- `),c("Config written",null)}catch{return i(`Unable to write ~/${Fe}/config.json`)}},ct=e=>{let t=Od();if(a(t))return i("Failed to read existing config");let n={...t.value,...e};return Ud(n)},Bd=()=>{let e=xs(),t=Is();if(a(t))return i(`Unable to create ~/${Fe}`);if(!(ke.readFile(e)!==null)){let p=Ud(Op);if(a(p))throw new Error(`Unable to create ~/${Fe}/config.json`)}let r=Od();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:d,autoSync:l,autoSyncDebounceMs:u,logLevel:m}=r.value;return!s||!d?i(`User name or ID not configured in ~/${Fe}/config.json`):(process.env.EPIQ_LOG_LEVEL=m,c("successfully loaded settings",{logLevel:m??"debug",preferredEditor:o??"",userName:s,userId:d,autoSync:l??!1,autoSyncIntervalMs:u??1e4,viewMode:"dense"}))}});var so,bs=y(()=>{"use strict";so=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null}});import{useSyncExternalStore as CN}from"react";var Es,_p,jp,En,$p,bt,io=y(()=>{"use strict";C();_p=new Set,jp=()=>{for(let e of _p)e()},En=()=>{if(!Es)throw new Error("Ui state not initialized. Call initUiState() first.");return Es},$p=e=>{let t=En();return Es=e(t),jp(),c("UX state updated",null)},bt=e=>$p(t=>({...t,...e}))});import{spawn as Wp}from"node:child_process";function Ns(e){let t=process.platform,o=Wp(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}var _d=y(()=>{"use strict"});import{spawnSync as Hp}from"node:child_process";import zp from"node:os";import jd from"node:path";import{ulid as Vp}from"ulid";function qp(){let{preferredEditor:e}=ee(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Gp(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function $d(e){let t=jd.join(zp.tmpdir(),"epiq");ke.mkDir(t);let n=jd.join(t,Vp());ke.writeToFile(n,e??"");let r=qp();for(let o of r){let s=Gp(o,n),d=Hp(s,{stdio:"inherit",shell:!0});if(!d.error&&d.status===0){let l=ke.readFile(n);if(l==null)return i("Unable to read edited file");let u=l.replace(/\r?\n$/,"");return c("Successfully edited",u)}}return i("Unable to open editor")}var Wd=y(()=>{"use strict";C();Ee();hs()});import{ulid as Cs}from"ulid";var Hd,Kp,Yp,zd=y(()=>{"use strict";Wd();Ot();He();$t();Z();C();tn();ie();w();ue();mn();Hd=async e=>{let{contextNode:t,selectedIndex:n}=g(),r=V(t.id)[n];if(e.modifier===Ae.DESCRIPTION)return Yp();if(r&&Fn(r))return Kp(e);if(e.modifier===Ae.TITLE){let o=X();if(a(o))return i("Unable to resolve user ID");let s=r;if(!s)return i("Missing node");if(s.readonly)return i("Cannot rename readonly node");let d=e.inputString.trim();if(!d)return i("Provide a title");let l=await ze();return a(l)?l:B([{id:Cs(),action:"edit.title",payload:{id:s.id,name:d},...o.value}],l.value)}return i("Unknown edit command")},Kp=async e=>{let t=X();if(a(t))return i("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=g(),o=V(n.id)[r];if(!o||!Fn(o))return i("Select a comment first");if(o.readonly)return i("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return i("Unable to resolve comment issue");let d=g().nodes[s];if(!d||!T(d))return i("Unable to resolve comment issue");if(d.readonly)return i("Cannot edit readonly issue");let l=o.id.split(":").at(0)??"",u=b.getComment(l);if(!u||u.deleted)return i("Unable to resolve comment");if(u.issue!==d.id)return i("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return i("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return i("Provide a comment");let p=await ze();if(a(p))return p;let h=p.value;return B([{id:Cs(),action:"edit.issue.comment",payload:{id:u.id,issue:d.id,md:m},...t.value}],h)},Yp=async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let t=await ze();if(a(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=g(),s=Te([...r,o],"TICKET");if(a(s))return i("Edit target must be an issue");let d=s.value;if(!T(d))return i("Edit target must be an issue");if(d.readonly)return i("Cannot edit readonly issue");let l=V(d.id).find(h=>h.title===oe.DESCRIPTION);if(!l)return i("No target found");if(l.readonly)return i("Cannot edit readonly field");let u=d.props.description??"";if(typeof u!="string")return i("Selected field is not editable text");let m=$d(u);if(a(m))return i("Failed to edit field");let p=m.value;return p===u?c("No changes made",null):B([{id:Cs(),action:"edit.description",payload:{id:d.id,md:p},...e.value}],n)}});import Rs from"node:fs";import Xp from"node:path";var Vd,qd=y(()=>{"use strict";C();An();Vd=async e=>{let t=Xp.join(e,".gitignore"),n=Rs.existsSync(t)?Rs.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
50
+ `;return Md.writeFileSync(U,j,"utf8"),c("Exported board layout",U)}});import{accessSync as Up,copyFileSync as Bp,existsSync as uo,mkdirSync as Pd,readdirSync as Dd,readFileSync as _p,renameSync as jp,rmSync as $p,statSync as Fd,unlinkSync as Wp,writeFileSync as Hp}from"node:fs";import Cn from"node:path";var Ns,Pe,Cs=h(()=>{"use strict";Ns=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Pe={writeToFile:(e,t)=>{try{let n=Cn.dirname(e);uo(n)||Pd(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Hp(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return _p(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Pe.readFile(e);return t===null?null:JSON.parse(t)}catch(t){return logger.error(`Failed to read JSON at ${e}:`,t),null}},dirExists:e=>{try{return uo(e)&&Fd(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Up(e),!0}catch{return!1}},mkDir:e=>Pd(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Cn.parse(t);for(;;){let r=Cn.join(t,e);try{if(uo(r)&&Fd(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Cn.dirname(t)}return null},readFirstJSON(e){try{if(!Pe.dirExists(e))return null;let t=Dd(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Cn.join(e,t);return Pe.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Pe.dirExists(e)?Dd(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Wp(e)}catch(t){(!Ns(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{$p(e,{recursive:!0,force:!0})}catch(t){(!Ns(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Cn.dirname(t)),!n?.overwrite&&uo(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{jp(e,t)}catch(r){if(Ns(r)&&r.code==="EXDEV"){Bp(e,t),this.rmFile(e);return}throw r}}}});import Vp from"node:os";import Od from"node:path";import{z as Tt}from"zod";var zp,Ud,qp,Bd,Ss,Rs,Gp,_d,jd,st,$d,Sn=h(()=>{"use strict";pe();C();Cs();zp={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},Ud=Tt.object({logLevel:Tt.enum(["info","error","debug"]),preferredEditor:Tt.string().optional(),userName:Tt.string().optional(),userId:Tt.string().optional(),autoSync:Tt.boolean().nullable().optional(),autoSyncDebounceMs:Tt.number().optional(),viewMode:Tt.enum(["dense","wide"]).optional()}).partial(),qp="config.json",Bd=()=>Od.join(Vp.homedir(),Oe),Ss=()=>Od.join(Bd(),qp),Rs=()=>{try{return Pe.mkDir(Bd()),c(`Ensured ~/${Oe} exists`,null)}catch{return i(`Unable to create ~/${Oe}`)}},Gp=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${Oe}/config.json JSON`)}let n=Ud.safeParse(t??{});return n.success?c("Parsed config",n.data):i(`Invalid ~/${Oe}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},_d=()=>{let e=Rs();if(a(e))return i(e.message);let t=Ss(),n=Pe.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Gp(n)},jd=e=>{let t=Rs();if(a(t))return i(t.message);let n=Ud.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Ss();try{return Pe.writeToFile(r,JSON.stringify(n.data,null,2)+`
51
+ `),c("Config written",null)}catch{return i(`Unable to write ~/${Oe}/config.json`)}},st=e=>{let t=_d();if(a(t))return i("Failed to read existing config");let n={...t.value,...e};return jd(n)},$d=()=>{let e=Ss(),t=Rs();if(a(t))return i(`Unable to create ~/${Oe}`);if(!(Pe.readFile(e)!==null)){let y=jd(zp);if(a(y))throw new Error(`Unable to create ~/${Oe}/config.json`)}let r=_d();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:d,autoSync:l,autoSyncDebounceMs:u,logLevel:m,viewMode:p}=r.value;return!s||!d?i(`User name or ID not configured in ~/${Oe}/config.json`):(process.env.EPIQ_LOG_LEVEL=m,c("successfully loaded settings",{logLevel:m??"debug",preferredEditor:o??"",userName:s,userId:d,autoSync:l??!1,autoSyncIntervalMs:u??1e4,viewMode:p??"dense"}))}});var mo,As=h(()=>{"use strict";mo=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null}});import{useSyncExternalStore as ON}from"react";var Ts,Kp,Yp,Rn,Xp,wt,po=h(()=>{"use strict";C();Kp=new Set,Yp=()=>{for(let e of Kp)e()},Rn=()=>{if(!Ts)throw new Error("Ui state not initialized. Call initUiState() first.");return Ts},Xp=e=>{let t=Rn();return Ts=e(t),Yp(),c("UX state updated",null)},wt=e=>Xp(t=>({...t,...e}))});import{spawn as Jp}from"node:child_process";function ws(e){let t=process.platform,o=Jp(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}var Wd=h(()=>{"use strict"});import{spawnSync as Qp}from"node:child_process";import Zp from"node:os";import Hd from"node:path";import{ulid as eg}from"ulid";function tg(){let{preferredEditor:e}=re(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function ng(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function Vd(e){let t=Hd.join(Zp.tmpdir(),"epiq");Pe.mkDir(t);let n=Hd.join(t,eg());Pe.writeToFile(n,e??"");let r=tg();for(let o of r){let s=ng(o,n),d=Qp(s,{stdio:"inherit",shell:!0});if(!d.error&&d.status===0){let l=Pe.readFile(n);if(l==null)return i("Unable to read edited file");let u=l.replace(/\r?\n$/,"");return c("Successfully edited",u)}}return i("Unable to open editor")}var zd=h(()=>{"use strict";C();Ne();Cs()});import{ulid as Ms}from"ulid";var qd,rg,og,Gd=h(()=>{"use strict";zd();$t();Ge();qt();ne();C();on();ae();T();pe();St();qd=async e=>{let{contextNode:t,selectedIndex:n}=g(),r=z(t.id)[n];if(e.modifier===Te.DESCRIPTION)return og();if(r&&Wn(r))return rg(e);if(e.modifier===Te.TITLE){let o=J();if(a(o))return i("Unable to resolve user ID");let s=r;if(!s)return i("Missing node");if(s.readonly)return i("Cannot rename readonly node");let d=e.inputString.trim();if(!d)return i("Provide a title");let l=await Ke();return a(l)?l:B([{id:Ms(),action:"edit.title",payload:{id:s.id,name:d},...o.value}],l.value)}return i("Unknown edit command")},rg=async e=>{let t=J();if(a(t))return i("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=g(),o=z(n.id)[r];if(!o||!Wn(o))return i("Select a comment first");if(o.readonly)return i("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return i("Unable to resolve comment issue");let d=g().nodes[s];if(!d||!w(d))return i("Unable to resolve comment issue");if(d.readonly)return i("Cannot edit readonly issue");let l=o.id.split(":").at(0)??"",u=E.getComment(l);if(!u||u.deleted)return i("Unable to resolve comment");if(u.issue!==d.id)return i("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return i("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return i("Provide a comment");let p=await Ke();if(a(p))return p;let y=p.value;return B([{id:Ms(),action:"edit.issue.comment",payload:{id:u.id,issue:d.id,md:m},...t.value}],y)},og=async()=>{let e=J();if(a(e))return i("Unable to resolve user ID");let t=await Ke();if(a(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=g(),s=we([...r,o],"TICKET");if(a(s))return i("Edit target must be an issue");let d=s.value;if(!w(d))return i("Edit target must be an issue");if(d.readonly)return i("Cannot edit readonly issue");let l=z(d.id).find(y=>y.title===Y.DESCRIPTION);if(!l)return i("No target found");if(l.readonly)return i("Cannot edit readonly field");let u=d.props.description??"";if(typeof u!="string")return i("Selected field is not editable text");let m=Vd(u);if(a(m))return i("Failed to edit field");let p=m.value;return p===u?c("No changes made",null):B([{id:Ms(),action:"edit.description",payload:{id:d.id,md:p},...e.value}],n)}});import ks from"node:fs";import sg from"node:path";var Kd,Yd=h(()=>{"use strict";C();Dn();Kd=async e=>{let t=sg.join(e,".gitignore"),n=ks.existsSync(t)?ks.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
52
52
  `).map(u=>u.trim()),s=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(s.length===0)return c("Local epiq paths already ignored",!1);let l=["# [epiq]: local hydrated state is never committed",...s].join(`
53
53
  `);return n=n.trimEnd()+`
54
54
 
55
55
  ${l}
56
- `,Rs.writeFileSync(t,n,"utf8"),me.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)}});import Jp from"node:fs";import Gd from"node:path";var Qp,q,Kd,Yd=y(()=>{"use strict";qd();ir();pt();At();vr();Be();Hn();Mr();yt();He();Y();C();St();ce();Ee();w();ue();Qp=async e=>{let t=await _({cwd:e,args:["status","--porcelain"]});return a(t)?t:c("Checked git diff",t.value.stdout.trim().length>0)},q=(e,t)=>i(`[${e}] ${t}`),Kd=async()=>{W("");let e=sr(),t=await Ve(process.cwd());if(a(t))return q(1,t.message);let n=t.value,r=await cr(n);if(a(r))return q(2,r.message);if(r.value)return q(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await Qp(n);if(a(o))return q(2.5,o.message);if(o.value)return q(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(bo(n))return q(4,"Epiq project already initialized");let s=Fr();if(!s.isSetupDone||!s.userName)return q(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let d=ee(),l=d.userName,u=d.userId;if(!u||!l)return q(5,"Missing Epiq user id");let m=e.stateBranch,p=await ur({repoRoot:n,branch:m});if(a(p))return q(6,p.message);if(p.value)return q(6,`State branch already exists: ${m}`);let h=await Po({repoRoot:n,stateBranchName:m});if(a(h))return q(6,h.message);let N=gr();if(a(N))return q(7,N.message);let S=Gd.join(pr(),e.projectId),F=await Ln({repoRoot:n,stateBranchRoot:S,stateBranchName:m});if(a(F))return q(8,F.message);let O=Gd.join(S,".epiq");Jp.mkdirSync(O,{recursive:!0});let j=pa({userId:u,userName:l});if(a(j))return q(9,j.message);for(let Io of j.value){let zs=Ar({event:Io,rootDir:S});if(a(zs))return q(9,zs.message)}let ne=await fr({stateBranchRoot:S,eventFileName:Ft({userId:u,userName:l})});if(a(ne))return q(10,ne.message);let Q=await Xt({cwd:S,message:"[epiq:init]"});if(a(Q))return q(10,Q.message);let k=await Vd(n);if(a(k))return q(11,k.message);let $=Ks({repoRoot:n,fileContents:e});if(a($))return q(12,$.message);let Gt=await re.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(Gt))return q(13,Gt.message);let Ct=await re.commit({cwd:n,message:"[epiq:init-project]"});if(a(Ct))return q(13,Ct.message);let Kt="Project initialized!",js=await _({cwd:n,args:["push","-u","origin","HEAD"]});a(js)&&(Kt+=` Warn: [init:14] ${js.message}`);let $s=await kn({repoRoot:n,stateBranchRoot:S});a($s)&&(Kt+=` Warn: [init:15] ${$s.message}`);let Ws=vt(j.value).filter(a);if(Ws.length>0)return q(16,Ws.map(Io=>Io.message).join(`
57
- `));let xo=_e();if(a(xo))return q(16,xo.message);let{rootNodeId:Il,nodes:bl}=xo.value,Hs=bl[Il];return Hs?(P.navigate({contextNode:Hs,selectedIndex:0}),x({hasProjectDefinition:!0,mode:f.DEFAULT}),c(Kt,null)):q(16,"Unable to resolve initialized root node")}});import{ulid as Zp}from"ulid";function As(e){let t=Jd();if(a(t))return t;let{contextNode:n,nodes:r}=g();if(!n.parentNodeId)return i("Missing parent node id");let o=r[n.parentNodeId];if(!o)return i("Missing parent node");let s=G(o.id),d=s.findIndex(({id:m})=>m===n.id);if(d<0)return i("Current node not found among siblings");let l=s[d+e];if(!l)return i("Missing sibling node");let u=Qd({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Zd(u.value)}function Ts(e){let t=Jd();if(a(t))return t;let{contextNode:n,selectedIndex:r}=g(),s=G(n.id)[r+e];if(!s)return i("Missing sibling node");let d=Qd({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:Zd(d.value)}var Xd,Et,Qn,Jd,Ss,Qd,Zd,ws=y(()=>{"use strict";yt();He();C();Je();w();Xd=null,Et=()=>structuredClone(Xd),Qn=e=>{Xd=e},Jd=()=>{let{contextNode:e,selectedIndex:t}=g(),r=G(e.id)[t];return r?c("Resolved selected child",r):i("Target node not found")},Ss=({id:e,parentId:t,position:n={at:"end"}})=>{let r=G(t).filter(o=>o.id!==e);return Tr(r,n)},Qd=({id:e,parentId:t,position:n={at:"end"}})=>{let r=X();if(a(r))return i("Unable to resolve user ID");let o=Ss({parentId:t,id:e,position:n});return a(o)?o:c("Created pending move state",{id:Zp(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Zd=e=>{Qn(e);let t=ft(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as eg}from"ulid";var ec,ao,tc,nc=y(()=>{"use strict";Be();ws();Ot();He();Y();C();Je();ce();w();ue();ec=()=>{let e=Et();if(!e)return i("No pending move state");let t=e.payload.id,n=e.payload.parent,r=g().nodes[n];if(!r)return i("Move parent not found");let o=G(n).findIndex(s=>s.id===t);return o===-1?i("Moved node not found among rendered children"):(P.navigate({contextNode:r,selectedIndex:o}),c("Synchronized navigation to moved node",null))},ao=(e,t="Moved preview")=>{if(a(e))return e;let n=ec();return a(n)?n:(x({mode:f.MOVE}),c(t,null))},tc=async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=J().commandMeta,{contextNode:n,selectedIndex:r}=g(),o=G(n.id)[r];if(!o)return x({mode:f.DEFAULT}),i("No move target");if(t==="start"){if(o.readonly)return i("Target node is read-only");if(r===-1)return i("No item selected");if(!o.parentNodeId)return i("Target has no parent");let s=G(o.parentNodeId),d=s.findIndex(({id:h})=>h===o.id);if(d===-1)return i("Target not found among siblings");let l=s[d-1],u=s[d+1],m=u!=null?{at:"before",sibling:u.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},p=Ss({parentId:o.parentNodeId,id:o.id,position:m});return a(p)?p:(Qn({id:eg(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),x({mode:f.MOVE}),c("Move initialized",null))}if(t==="next")return ao(Ts(1));if(t==="previous")return ao(Ts(-1));if(t==="to-next")return ao(As(1));if(t==="to-previous")return ao(As(-1));if(t==="confirm"){let s=Et();if(!s)return i("No pending move to confirm");let d=await ze();if(a(d))return d;let l=B([s],d.value);if(a(l))return l;let u=ec();return a(u)?u:(Qn(null),x({mode:f.DEFAULT}),c("Moved item",null))}return t==="cancel"?(Qn(null),x({mode:f.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as tg,ulid as ng}from"ulid";var rg,co,Ms=y(()=>{"use strict";C();rg=tg(),co=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=rg();return c("Created issue events",[{id:ng(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as lo}from"ulid";var rc,oc=y(()=>{"use strict";Be();Ms();Ot();He();$t();C();ie();Je();w();ue();rc=async(e,t)=>{let n=X();if(a(n))return i("Unable to resolve user ID");let r=await ze();if(a(r))return r;let o=r.value;if(!t.inputString)return i(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:d,selectedIndex:l}=g(),u=m=>{let p=B([m],o);if(a(p))return p;let h=b.getNode(p.value[0].result.id);if(!h)return i("Created node not found");if(!h.parentNodeId)return p;let N=b.getNode(h.parentNodeId);return N?(P.navigate({contextNode:N,selectedIndex:b.getSiblings(h.parentNodeId).findIndex(({id:S})=>S===h.id)}),p):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=b.getNode(m);if(!p)return i("Workspace not found");let h=cn(p.id,n.value,o);return a(h)?h:u({id:lo(),action:"add.board",payload:{id:lo(),name:t.inputString,parent:p.id,rank:h.value},...n.value})}if(t.modifier==="swimlane"){let m=Te(s,"BOARD");if(a(m))return i("Unable to add swimlane in this context");let p=cn(m.value.id,n.value,o);return a(p)?p:u({id:lo(),action:"add.swimlane",payload:{id:lo(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=V(d.id)[l],p=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let Q=Te(s,"SWIMLANE");return a(Q)?null:Q.value})();if(!p)return i("Unable to add issue in this context");let h=cn(p.id,n.value,o);if(a(h))return h;let N=co({name:t.inputString,parent:p.id,rank:h.value,user:n.value});if(a(N))return N;let S=N.value,F=B([...S],o);if(a(F))return F;if(!F.value[0])return i("Issue creation failed");let ne=S.find(Q=>Q.action==="add.issue")?.payload.id;return ne?(P.navigate({contextNode:p,selectedIndex:b.getSiblings(p.id).findIndex(({id:Q})=>Q===ne)}),c("Issue created",null)):i("Unable to determine ticket id")}return c("Success",null)}});var uo,Ls=y(()=>{"use strict";Be();dn();yt();C();w();uo=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=g(),s=Ki(n,t);if(a(s))return i(s.message);let{appliedEvents:d,unappliedEvents:l}=s.value,u=Nt();if(a(u))return u;let p=vt(d).filter(a);if(p.length>0)return Nt(),x(o),i(p.map(N=>N.message).join(", "));let h=g().nodes[e];return h?(P.navigate({contextNode:h,selectedIndex:r}),c("",{unappliedEvents:l})):(Nt(),x(o),i("Board did not exist at that date"))}});var og,sg,ig,mo,po,Vt,sc,ag,ic,ks=y(()=>{"use strict";sn();_o();yt();Y();C();w();og=20,sg=16,ig=150,mo=null,po=null,Vt=()=>{mo!==null&&(clearInterval(mo),mo=null),po!==null&&(clearTimeout(po),po=null)},sc=()=>{Vt(),x({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},ag=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)},ic=({events:e,startTime:t,durationMs:n})=>{Vt();let r=e.length,o=e.map(h=>on(h)??t),s=o[r-1]??Date.now(),d=ag(o),l=Math.max(1,Math.round(n*og/1e3)),u=Math.max(Math.round(n/l),sg),m=0,p=0;x({mode:f.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),mo=setInterval(()=>{m++;let h=m/l,N=[],S;for(;p<r&&d[p]<=h;){let O=e[p],j=ft(O);if(a(j)){sc();return}N.push(...$o(O)),S=O,p++}if(p>=r||m>=l){for(;p<r;p++){let j=ft(e[p]);if(a(j))break}let O=g().replay;x({unappliedEvents:[],replay:O&&{...O,progress:1,appliedCount:r}}),Vt(),po=setTimeout(sc,ig);return}let F=g().replay;x({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,h),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:S?on(S)??F?.currentTime??t:F?.currentTime??t,currentLabel:S?Wi(S):F?.currentLabel??"",flashNodeIds:S?[...new Set(N)]:F?.flashNodeIds??[]}})},u)}});var ac,dc=y(()=>{"use strict";pt();sn();dn();yt();Y();$t();C();ce();w();qn();Ls();ks();ac=async()=>{let e=Te(g().breadCrumb,"BOARD");if(a(e))return e;let t=await Ve(process.cwd());if(a(t))return i("Unable to locate repo root");let n=We({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=J().commandMeta;if(Vt(),r==="now"){let l=Dt(n.value);if(a(l))return i(l.message);let u=Nt();if(a(u))return u;let p=vt(l.value).filter(a);return p.length>0?i(p.map(h=>h.message).join(", ")):(x({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),c("Peeking now",!0))}let s;if(r==="prev"){let l=g().eventLog.at(-1),u=on(l);if(u===null)return i("No previous event to peek");s=u}else if(r==="next"){let l=g().unappliedEvents.at(0),u=on(l);if(u===null)return i("No next event to peek");s=u+1}else{let l=_t(r||o.trim());if(!l)return i("Invalid peek date");s=l.getTime()}let d=uo({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(d)?d:(x({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:d.value.unappliedEvents,replay:null}),c("Peeking",!0))}});var cc,lc=y(()=>{"use strict";pt();$t();C();ce();w();qn();Ls();ks();cc=async()=>{let e=Te(g().breadCrumb,"BOARD");if(a(e))return e;let t=await Ve(process.cwd());if(a(t))return i("Unable to locate repo root");let n=We({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=J().commandMeta,{dateInput:s,durationInput:d}=jr(r,o);if(Vt(),g().syncStatus.status==="syncing")return i("Cannot replay while syncing, try again in a moment");let l=_t(s);if(!l)return i("Invalid replay date");let u=d?_r(d):15e3;if(u===null)return i("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=g(),h=uo({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(h))return h;let{unappliedEvents:N}=h.value;return N.length===0?(Nt(),x(p),c("Nothing to replay from that point",!0)):(ic({events:N,startTime:m,durationMs:u}),c("Replaying board history",!0))}});import cg from"zod";var uc,mc=y(()=>{"use strict";bn();Y();C();ce();Ee();w();uc=()=>{let e=J().commandMeta.inputString,t=cg.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return i("Auto sync duration must be a number of at least 3000 ms");let n=ct({autoSyncDebounceMs:t.data});return a(n)?n:(Ye({autoSyncIntervalMs:t.data}),x({mode:f.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))}});var pc,gc=y(()=>{"use strict";Hn();bn();Y();C();ce();Ee();w();pc=()=>{let e=J().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=ba(e),n=ct({autoSync:t});return a(n)?n:(Ye({autoSync:t}),x({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var fc,vc=y(()=>{"use strict";bn();Y();C();ce();Ee();w();fc=()=>{let e=J().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return i("Invalid response");let n=ct({logLevel:e});return a(n)?n:(Ye({logLevel:e}),x({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var yc,hc=y(()=>{"use strict";Ko();Y();C();ce();w();yc=async()=>{W(""),x({mode:f.DEFAULT});let e=_e();if(a(e))return i(e.message);if(e.value.syncStatus.status==="syncing")return i("Sync already in progress");x({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Lr();return a(t)?(x({syncStatus:{msg:t.message,status:"failed"}}),t):(x({mode:f.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as xe}from"ulid";var lg,xc,Ic,lt,bc,Ec=y(()=>{"use strict";wd();Be();bn();Ot();He();bs();an();Y();$t();Z();C();ie();Je();ce();Ee();w();io();ue();_d();Bt();ds();mn();rs();zd();Yd();nc();oc();dc();lc();mc();gc();vc();hc();lg=e=>e.action==="add.issue.comment",xc=e=>Object.values(g().tags).find(t=>t.name===e),Ic=e=>Object.values(g().contributors).find(t=>t.name===e),lt=async()=>{let e=await ze();return a(e)?e:c("Resolved persist root",e.value)},bc=[{systemOnly:!0,intent:L.Move,description:"Internal move-state command",mode:f.COMMAND_LINE,action:tc},{intent:L.Delete,description:"Delete the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=V(t.id)[n];if(!r)return i("Unable to resolve child to delete");let o=await lt();if(a(o))return o;if(r.context==="COMMENT"){let s=r.id,d=T(t)?t.id:t.parentNodeId;if(!d)return i("Unable to resolve comment issue");let l=g().nodes[d];if(!l||!T(l))return i("Unable to resolve comment issue");let u=l.log?.filter(lg).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):B([{id:xe(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],o.value):i("Unable to resolve comment")}return B([{id:xe(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:L.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:f.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=J().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(d=>pe(v.FILTER).map(l=>l.split(n)[0]).includes(d))(r))return i("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return ge(d=>({...d,filters:e==="clear"?[]:[...d.filters,s],mode:f.DEFAULT})),c("Filter updated",null)}},{intent:L.ViewHelp,description:"Open the help screen",mode:f.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return bt({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),x({mode:f.HELP}),c("Viewing help",null)}},{intent:L.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=V(t.id)[n];if(!r)return i("Unable to close issue, no target found");if(!T(r))return i("Cannot close in this context");let o=g().nodes[ae];if(!o)return i("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return i("Issue is already closed");let s=await lt();if(a(s))return s;let d=s.value,l=Ut(o.id,r.id,{at:"end"},e.value,d);if(a(l))return l;let u=B([{id:xe(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...e.value}],d);return a(u)?u:c("Issue closed",null)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:L.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=V(t.id)[n];if(!r)return i("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):Lt(r.id,"TICKET");if(a(o))return i("Cannot reopen in this context");let s=o.value,d=g().nodes[ae];if(!d)return i("Unable to locate closed swimlane");if(s.parentNodeId!==d.id)return i("Issue is not closed");if(!T(s))return i("Target node is not issue");let l=so(s);if(!l)return i("Unable to resolve previous parent from issue history");if(l===d.id)return i("Previous parent resolves to closed swimlane");let u=g().nodes[l];if(!u)return i("Previous parent no longer exists");let m=await lt();if(a(m))return m;let p=m.value,h=Ut(u.id,s.id,{at:"end"},e.value,p);if(a(h))return h;let N=B([{id:xe(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:h.value},...e.value}],p);return a(N)?N:c("Issue reopened",null)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:L.Init,description:"Initialize Epiq in the current git repository",mode:f.COMMAND_LINE,action:Kd},{intent:L.NewItem,description:"Create a new board, swimlane, or issue",mode:f.COMMAND_LINE,action:rc,onSuccess:()=>x({mode:f.DEFAULT})},{intent:L.Rename,description:"itle] Rename the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=V(t.id)[n];if(!r)return i("Missing node");if(r.readonly)return i("Cannot rename readonly node");let o=Qa();if(!o)return i("Provide a title");let s=await lt();return a(s)?s:B([{id:xe(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:L.UntagTicket,description:"Remove a tag from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=J().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let o=xc(r);if(!o)return i(`Tag "${r}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid untag target");let d=Lt(s.id,"TICKET");if(a(d))return i("Unable to untag issue in this context");let l=d.value;if(!T(l))return i("Target node is not issue");if(!(l.props.tags??[]).includes(o.id))return i("Issue is not tagged with that tag");let m=await lt();return a(m)?m:B([{id:xe(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:L.TagTicket,description:"Add or create a tag on the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=J().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let{selectedNode:o}=g();if(!o)return i("Invalid tag target");let s=Lt(o.id,"TICKET");if(a(s))return i("Unable to tag issue in this context");let d=s.value;if(!T(d))return i("Target node is not issue");let l=await lt();if(a(l))return l;let u=xc(r),m=u?.id??xe();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):B([...u?[]:[{id:xe(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:xe(),action:"add.issue.tag",payload:{id:d.id,tag:m},...e.value}],l.value)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:L.AssignUserToTicket,description:"Assign a user to the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=J().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee");let{selectedIndex:o,contextNode:s}=g(),d=V(s.id)[o];if(!d)return i("Invalid assign target");let l=Lt(d.id,"TICKET");if(a(l))return i("Unable to assign issue in this context");let u=l.value;if(!T(u))return i("Target node is not issue");let m=await lt();if(a(m))return m;let p=Ic(r),h=p?.id??xe();return(u.props.assignees??[]).includes(h)?i("Assignee already assigned"):B([...p?[]:[{id:xe(),action:"create.contributor",payload:{id:h,name:r},...e.value}],{id:xe(),action:"add.issue.assignee",payload:{id:u.id,assignee:h},...e.value}],m.value)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:L.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=J().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee to remove");let o=Ic(r);if(!o)return i(`Assignee "${r}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid unassign target");let d=Lt(s.id,"TICKET");if(a(d))return i("Unable to unassign in this context");let l=d.value;if(!T(l))return i("Target node is not issue");if(!(l.props.assignees??[]).includes(o.id))return i(`Issue is not assigned to "${r}"`);let m=await lt();return a(m)?m:B([{id:xe(),action:"remove.issue.assignee",payload:{id:l.id,assignee:o.id},...e.value}],m.value)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:L.Comment,description:"Add a comment to the selected issue",mode:f.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return i("Provide a comment");if(n.length>pn)return i(`Cannot exceed ${pn} characters`);let r=X();if(a(r))return i("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=g(),d=Te([...o,s],"TICKET");if(a(d))return i("Edit target must be an issue");let l=d.value;if(!l)return i("Invalid comment target");let u=l.context==="TICKET"?c("Resolved ticket",l):Lt(l.id,"TICKET");if(a(u))return i("Unable to comment on issue in this context");let m=u.value;if(!T(m))return i("Target node is not issue");let p=await lt();return a(p)?p:B([{id:xe(),action:"add.issue.comment",payload:{id:xe(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:L.Sync,description:"Pull, commit, and push Epiq state",mode:f.COMMAND_LINE,action:yc},{intent:L.Peek,description:"View board state at another point in time",mode:f.COMMAND_LINE,action:ac},{intent:L.Replay,description:"Replay board history forward from a point in time",mode:f.COMMAND_LINE,action:cc},{intent:L.Export,description:"Export the current board layout to markdown",mode:f.COMMAND_LINE,action:async()=>{let e=await Td();return a(e)?e:(x({mode:f.DEFAULT}),c("Export successful",!0))}},{intent:L.Exit,description:"Exit the application",mode:f.COMMAND_LINE,action:async()=>(P.exit(),c("Exit successful",!0))},{intent:L.Edit,description:"Edit title or description",mode:f.COMMAND_LINE,action:async(e,t)=>Hd(t),onSuccess:()=>x({mode:f.DEFAULT})},{intent:L.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:f.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case se.USERNAME:{let{userId:r,preferredEditor:o,userName:s}=ee(),d=n||s,l=r??xe();if(!d||!l)return i("Unable to resolve user name or id");let u=ct({userName:d,userId:l,preferredEditor:o??""});return a(u)?u:(Ye({userName:d,userId:l}),x({mode:f.DEFAULT}),c(`Username set to "${d}"`,null))}case se.EDITOR:{if(!n)return i("No editor provided");let r=ct({preferredEditor:n});return a(r)?r:(Ye({preferredEditor:n}),x({mode:f.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case se.VIEW:return n!=="wide"&&n!=="dense"?i("Invalid view mode"):(Ye({viewMode:n}),c(`View set to "${n}"`,null));case se.AUTOSYNC:return pc();case se.LOG_LEVEL:return fc();case se.SYNC_DEBOUNCE_MS:return uc();default:return i("Unknown config command")}}},{intent:L.Coffee,description:"Sponsor the development of Epiq!",mode:f.COMMAND_LINE,action:()=>{let e=J().commandMeta.modifier;return e==="custom"?Ns("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):Ns(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),W(""),c("Thanks you!",null)}}]});var ug,tt,Ps=y(()=>{"use strict";Dr();Wr();ds();Ec();C();ce();Ee();w();ug=new Set(["peek","replay","filter","view-help"]),tt=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=J();if(!t)return i("No command to confirm");if(!e&&n===ht.Invalid)return i("Invalid command");let s=Za(t);Ka();let{readOnly:d}=g();if(d&&!ug.has(s))return Gn({status:ut.Fail,message:"Command not available in readonly state",value:null});let l=bc.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return Gn({status:ut.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return Gn({status:ut.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?Gn(u):(Ya({addToHistory:!e}),l.onSuccess?.(),ee().autoSync&&ha(),u)}});var go,fo,Nc,Cc=y(()=>{"use strict";C();Y();w();Tt();Ps();ws();ce();go=[{intent:A.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(x({mode:f.COMMAND_LINE}),W("move cancel"),tt({isForceExecutedBySystem:!0}))},{intent:A.InitMove,mode:f.DEFAULT,description:"[m] move (init/confirm)",action:()=>(x({mode:f.COMMAND_LINE}),W("move start"),tt({isForceExecutedBySystem:!0}))},{intent:A.ConfirmMove,mode:f.MOVE,action:()=>(x({mode:f.COMMAND_LINE}),W("move confirm"),tt({isForceExecutedBySystem:!0}))}],fo=[{intent:A.MovePreviousItem,mode:f.MOVE,action:()=>Et()?(x({mode:f.COMMAND_LINE}),W("move previous"),tt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:A.MoveNextItem,mode:f.MOVE,action:()=>Et()?(x({mode:f.COMMAND_LINE}),W("move next"),tt({isForceExecutedBySystem:!0})):i("No pending move")}],Nc=[{intent:A.MoveToNextContainer,mode:f.MOVE,action:()=>Et()?(x({mode:f.COMMAND_LINE}),W("move to-next"),tt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:A.MoveToPreviousContainer,mode:f.MOVE,action:()=>Et()?(x({mode:f.COMMAND_LINE}),W("move to-previous"),tt({isForceExecutedBySystem:!0})):i("No pending move")}]});var Rc,Sc=y(()=>{"use strict";Z();Cc();Rc={[M.WORKSPACE]:[...go,...fo],[M.BOARD]:[...go,...fo],[M.SWIMLANE]:[...go,...fo,...Nc],[M.TICKET]:[],[M.FIELD]:[],[M.FIELD_LIST]:[],[M.TEXT]:[],[M.COMMENT]:[]}});var Ac,Tc,wc=y(()=>{"use strict";Y();C();ce();w();io();Tt();Be();Ac=()=>{W("");let{pendingNavTarget:e}=En();x({mode:f.DEFAULT}),e&&P.navigate(e),bt({pendingNavTarget:void 0})},Tc=[{intent:A.ExitCommandLine,mode:f.HELP,action:()=>(Ac(),c("Exiting help",null))},{intent:A.Exit,mode:f.HELP,action:()=>(Ac(),c("Closed help",null))},{intent:A.NavPreviousItem,mode:f.HELP,description:"[arrows/hjkl] navigate",action:()=>(P.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:A.NavNextItem,mode:f.HELP,action:()=>(P.navigateToNextItem(),c("Navigating to next help item",null))},{intent:A.NavToPreviousContainer,mode:f.HELP,action:()=>(P.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:A.NavToNextContainer,mode:f.HELP,action:()=>(P.navigateToNextContainer(),c("Navigating to next help container",null))}]});var mg,Mc,Lc,kc=y(()=>{"use strict";Y();Z();C();ce();w();io();Tt();Be();mg=e=>{x({mode:f.COMMAND_LINE});let{pendingNavTarget:t}=En();t&&P.navigate(t),bt({pendingNavTarget:void 0}),W(`${e} `)},Mc=()=>{W("");let{pendingNavTarget:e}=En();e&&P.navigate(e),bt({pendingNavTarget:void 0}),x({mode:f.DEFAULT})},Lc=[{intent:A.InitCommandPalette,mode:f.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{W("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return bt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),x({mode:f.PALETTE}),c("Opening command palette",null)}},{intent:A.Confirm,mode:f.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!hi(e))return i("Command only applicable on text nodes");if(e.props.disabled)return i("Command is not available in this context");let t=e.title;return t?(mg(t),c("Selected command",t)):c("No command selected",null)}},{intent:A.ExitCommandLine,mode:f.PALETTE,action:()=>(Mc(),c("Exiting palette",null))},{intent:A.Exit,mode:f.PALETTE,action:()=>(Mc(),c("Closed command palette",null))},{intent:A.NavPreviousItem,mode:f.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(P.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:A.NavNextItem,mode:f.PALETTE,action:()=>(P.navigateToNextItem(),c("Navigating to next item",null))},{intent:A.NavToPreviousContainer,mode:f.PALETTE,action:()=>(P.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:A.NavToNextContainer,mode:f.PALETTE,action:()=>(P.navigateToNextContainer(),c("Navigating to next container",null))}]});var Pc,Dc=y(()=>{"use strict";Bt();Y();C();tn();Je();ce();w();Tt();wc();kc();Be();Pc=[...Tc,...Lc,{intent:A.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(x({mode:f.COMMAND_LINE}),W(`${v.NEW} `),c("Adding new item",null))},{intent:A.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(x({mode:f.COMMAND_LINE}),W(`${v.DELETE} `),c("Deleting item",null))},{intent:A.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(x({mode:f.COMMAND_LINE}),W(""),c("Entering command line mode",null))},{intent:A.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!G(e?.id??"")?.length){if(e?.title===oe.DESCRIPTION)return x({mode:f.COMMAND_LINE}),W(`${v.EDIT} description `),c("Propose command",!0);if(e?.title===oe.ASSIGNEES)return x({mode:f.COMMAND_LINE}),W(`${v.ASSIGN} `),c("Propose command",!0);if(e?.title===oe.TAGS)return x({mode:f.COMMAND_LINE}),W(`${v.TAG} `),c("Propose command",!0);if(t.title===oe.DESCRIPTION&&e?.context==="TEXT")return x({mode:f.COMMAND_LINE}),W(`${v.EDIT} description `),c("Propose command",!0)}return P.enterChildNode(),c("Entering context",null)}},{intent:A.EditTitle,mode:f.DEFAULT,description:"[r] rename title",action:()=>(x({mode:f.COMMAND_LINE}),W(`${v.EDIT} title ${g().selectedNode?.title}`),c("Exiting context",null))},{intent:A.EditDescription,mode:f.DEFAULT,description:"[e] edit description",action:()=>(x({mode:f.COMMAND_LINE}),W(`${v.EDIT} description `),c("Exiting context",null))},{intent:A.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(P.enterParentNode(),c("Exiting context",null))},{intent:A.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(P.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:A.NavNextItem,mode:f.DEFAULT,action:()=>(P.navigateToNextItem(),c("Navigating to next item",null))},{intent:A.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(P.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:A.NavToNextContainer,mode:f.DEFAULT,action:()=>(P.navigateToNextContainer(),c("Navigating to next container",null))}]});var pg,gg,Fc,Oc=y(()=>{"use strict";ce();pg=500,gg=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Fc=e=>{let t=gg(e);t&&qr(n=>(n+t).slice(0,pg))}});var fg,vg,Uc,Bc=y(()=>{"use strict";Oc();Y();C();ce();w();Tt();Ps();fg=[f.COMMAND_LINE,f.PALETTE],vg=e=>[{intent:A.MoveCursorLeft,mode:e,action:()=>(is(-1),c("Moving cursor left",null))},{intent:A.MoveCursorRight,mode:e,action:()=>(is(1),c("Moving cursor right",null))},{intent:A.MoveCursorLeftOfWord,mode:e,action:()=>(as("left"),c("Moving cursor left of word",null))},{intent:A.MoveCursorRightOfWord,mode:e,action:()=>(as("right"),c("Moving cursor right of word",null))},{intent:A.AutoCompleteCommand,mode:e,action:()=>(qr((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=g().selectedNode?.title??""),r+o}),c("Auto-completing command",null))},{intent:A.CaptureInput,mode:e,action:(t,{sequence:n})=>(Fc(n??""),c("Capturing input",null))},{intent:A.EraseInput,mode:e,action:()=>(qa(),c("Erasing input",null))},{intent:A.EraseInputWord,mode:e,action:()=>(Ga(),c("Erasing input word",null))}],Uc=[{intent:A.Confirm,mode:f.COMMAND_LINE,action:()=>(tt(),c("Executing command",null))},{intent:A.ViewHelp,mode:f.DEFAULT,action:()=>(x({mode:f.HELP}),c("Viewing help",null))},...fg.flatMap(vg),{intent:A.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(x({mode:f.DEFAULT}),c("Exiting command line",null))},{intent:A.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Xa(),c("Getting last command from history",null))},{intent:A.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Ja(),c("Getting next command from history",null))}]});import $c from"chalk";var vo,_c,jc,Ds,Wc=y(()=>{"use strict";Y();Z();Ce();vo=$c.dim.hex(R.secondary2)(": for command line"),_c="q to exit",jc=`${$c.hex(R.accent)("m")} to confirm`,Ds={[M.WORKSPACE]:[vo],[M.BOARD]:[vo],[M.BOARD+f.COMMAND_LINE]:[vo],[M.SWIMLANE]:[vo],[M.TICKET+f.HELP]:[_c],[M.SWIMLANE+f.HELP]:[_c],[M.TICKET]:[],[M.FIELD]:[],[M.SWIMLANE+f.MOVE]:[jc],[M.TICKET+f.MOVE]:[jc]}});var Zn,yg,hg,Hc,zc=y(()=>{"use strict";w();Ir();Zn=e=>e.trim().toLocaleLowerCase(),yg=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},hg=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},Hc=(e,t)=>{let n=Zn(t.value);if(!n)return!0;switch(t.target){case"title":return Zn(e.title??"").includes(n);case"description":return Zn(e.props.description??"").includes(n);case"tag":return yg(e).map(Zn).some(o=>o.includes(n));case"assignee":return hg(e).map(Zn).some(o=>o.includes(n));case"ref":return Li(e.id,t.value);default:return!0}}});function Vc(e,t,n){let r=t[e];if(!r)return i("buildBreadCrumb(): current node not found");let o=[],s=r;for(;s&&(o.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let d=o[o.length-1];return!d||d.id!==n?i("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var qc=y(()=>{"use strict";C()});var Gc,Kc=y(()=>{"use strict";Gc=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t}});import{useSyncExternalStore as xg}from"react";function Xc(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return i("derive(): contextNodeId is missing");if(!r)return i("derive(): rootNode is missing");if(!o[r])return i("derive(): unable to find root node");let l=o[t];if(!l)return i("Unable to derive state, contextNode not found");let u=Vc(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,h=Ds[p+n]??Ds[p]??[],N=[...Pc,...Rc[p]??[],...Uc],S=Gc(N),F=bg(o,s),O=F[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:h,availableActions:N,actionIndex:S,selectedNode:O,renderedChildrenIndex:F})}function Bn(e){Fs=e;let t=mt(process.cwd()),n=!1;if(!a(t)){let s=gt(t.value);if(a(s))return i(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:f.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{}},o=Xc(r);return a(o)?o:(qt=o.value,Yc(),c("State initialized",null))}function ge(e){let t=g(),n=e(t),r=Xc(n);return a(r)?i(r.message??"Unable to update state"):(qt=r.value,Yc(),c("State updated",null))}var qt,Fs,Os,Yc,Ig,g,_e,x,$e,bg,V,Nt,un,w=y(()=>{"use strict";Sc();Dc();Bc();Wc();St();Y();Z();C();ue();zc();qc();Kc();Os=new Set,Yc=()=>{for(let e of Os)e()},Ig=e=>(Os.add(e),()=>Os.delete(e));g=()=>{if(!qt)throw new Error("State not initialized. Call initWorkspaceState() first.");return qt},_e=()=>qt?c("Retrieved state",qt):i("State not initialized. Call initWorkspaceState() first.");x=e=>ge(t=>({...t,...e})),$e=()=>xg(Ig,g,g),bg=(e,t)=>{let n={};for(let r of Object.values(e))T(r)&&t.length>0&&!t.every(o=>Hc(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,s)=>{let d=e[o.id],l=e[s.id];return!d||!l?0:d.rank.localeCompare(l.rank)});return n},V=e=>g()?.renderedChildrenIndex[e]??[],Nt=()=>Fs?Bn(Fs):i("Cannot reset state: no initial workspace found"),un=()=>qt!==void 0});var Us,yo,ho,Bs,je,kr=y(()=>{"use strict";yi();C();w();Us=e=>{un()&&(x({syncStatus:e}),vi({type:"sync-status",payload:e}))},yo=(e="Syncing...")=>{Us({status:"syncing",msg:e})},ho=(e="Synced")=>{Us({status:"synced",msg:e})},Bs=e=>{Us({status:"failed",msg:e})},je=e=>(Bs(e),i(e))});import{decodeTime as JT}from"ulid";var Jc=y(()=>{"use strict";C()});var Eg,Ng,Pr,Yo=y(()=>{"use strict";C();kr();Go();ar();pt();At();vr();Jc();Eg=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=z("getRepoRootDir",await Ve(e));if(a(n))return i(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=z("getStateBranchRoot",We({repoRoot:r}));if(a(o))return i(o.message);let s=o.value;logger.debug("[sync] state branch root",s);let d=z("ensureInitialCommit",await pi(r));if(a(d))return i(d.message);logger.debug("[sync] initial commit result",{created:d.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let l=z("bootstrapStateBranchStorage",await fi({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(a(l))return i(l.message);logger.debug("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let u=z("hasInProgressGitOperation(stateBranchRoot)",await cr(s));if(a(u))return i(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value)return logger.info("[sync] state branch git operation in progress"),i("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let m=z("ensureStateBranchLayout",li(r,s));return a(m)?i(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:l.value}),c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:l.value}))},Ng=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=z("stageStateBranchOwnEventFile",await fr({stateBranchRoot:t,eventFileName:n}));if(a(r))return i(r.message);let o=z("hasStagedChanges(after stage)",await oi(t));if(a(o))return i(o.message);if(logger.debug("[sync] state branch change check after stage result",{changed:o.value}),!o.value)return logger.info("[sync] no own event file changes to commit"),c("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let s=z("createStateBranchSyncCommit",await gi({repoRoot:e,stateBranchRoot:t}));return a(s)?i(s.message):(logger.debug("[sync] created sync commit",s.value),c("Committed own event file",{createdCommit:!0,commitSha:s.value}))},Pr=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),i("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),i("Own event file must end with .jsonl");yo();let n=z("ensureSyncReady",await Eg({cwd:e,ensureUpstream:!0}));if(a(n))return je(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,d=z("isDetachedHead(stateBranchRoot)",await si(o));if(a(d))return je(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return je("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,p=!1,h=z("getStateBranch",Yt(r));if(a(h))return je(h.message);let N=h.value;logger.debug("[sync] resolved state branch",{stateBranch:N,stateBranchRoot:o});let S=z("commitOwnEventFileToStateBranch",await Ng({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(a(S))return je(S.message);l=S.value.createdCommit,u=S.value.commitSha;let F=z("pullBranchRebaseIfPresent",await wo({cwd:o,branch:N}));if(a(F))return je(F.message);if(m=F.value,l||s){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:s,stateBranchRoot:o});let O=z("pushStateBranch",await kn({stateBranchRoot:o,repoRoot:r}));if(a(O)&&ri(O.message)){let j=z("pullBranchRebaseIfPresent(retry)",await wo({cwd:o,branch:N}));if(a(j))return je(j.message);m=m||j.value,O=z("pushStateBranch(retry)",await kn({stateBranchRoot:o,repoRoot:r}))}if(a(O))return je(O.message);p=O.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let O=z("git rev-parse HEAD",await _({args:["rev-parse","HEAD"],cwd:o}));if(a(O))return je(O.message);u=O.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return ho(p?"Synced and pushed":m||l?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),c("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,pulled:m,pushed:p,bootstrapped:s})}});import{decodeTime as vw,ulid as Ie}from"ulid";var _s,be,Pe,De,Cg,Rg,Qc,Zc,el,tl,nl,rl,ol,sl,il,al,dl,cl,ll,ul,ml,pl,gl,fl=y(()=>{"use strict";pt();At();vr();Yo();bn();Ms();Mr();dn();Ot();He();bs();an();Z();C();St();ie();Je();w();kr();ue();ot();Ir();Qt();An();_s=e=>{let t=mt(e??process.cwd());return a(t)?i(t.message):c("Resolved Epiq repo root",t.value)},be=async e=>{let t=_s(e);if(a(t))return t;let n=We({repoRoot:t.value});if(a(n))return i(n.message);let r=sr(),o=await Ln({repoRoot:t.value,stateBranchRoot:n.value,stateBranchName:r.stateBranch});if(a(o))return i(o.message);let s=await _({cwd:n.value,args:["pull","--ff-only"]});a(s)&&me.info(3,s.message);let d=Dt(n.value);if(a(d))return i(d.message);let l=$n(d.value);return a(l)?i(l.message):c("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:n.value})},Pe=()=>{let e=Bd();return a(e)?i(e.message):e.value.userId?e.value.userName?c("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):i("Unable to retrieve user name"):i("Unable to retrieve user id")},De=()=>{let e=_e();return a(e)?i(e.message):e},Cg=e=>(e.props.tags??[]).map(t=>b.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Re(t.name)})),Rg=e=>(e.props.assignees??[]).map(t=>b.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Re(t.name)})),Qc=async(e={})=>{let t=await be(e.repoRoot);if(a(t))return t;let n=De();if(a(n))return n;let r=Object.values(n.value.nodes).filter(o=>o.context==="BOARD").map(o=>({id:o.id,ref:kt(o.id),title:o.title,parentId:o.parentNodeId,readonly:!!o.readonly}));return c("Listed boards",r)},Zc=async(e={})=>{let t=await be(e.repoRoot);if(a(t))return t;let n=De();if(a(n))return n;let r=Object.values(n.value.nodes).filter(o=>o.context==="SWIMLANE").filter(o=>!e.boardId||o.parentNodeId===e.boardId).map(o=>({id:o.id,title:o.title,boardId:o.parentNodeId,isClosed:o.id===ae,readonly:!!o.readonly}));return c("Listed swimlanes",r)},el=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=De();if(a(n))return n;let r=Object.values(n.value.nodes).filter(T).filter(o=>e.includeClosed||o.parentNodeId!==ae).map(o=>({id:o.id,ref:kt(o.id),title:wt(o.title),description:o.props.description??"",parentNodeId:o.parentNodeId,isClosed:o.parentNodeId===ae,readonly:!!o.readonly,tags:Cg(o),assignees:Rg(o)}));return c("Listed issues",r)},tl=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Pe();if(a(n))return n;let r=cn(e.parentId,n.value,t.value.stateBranchRoot);if(a(r))return r;let o=co({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(a(o))return o;let s=o.value,d=B([...s],t.value.stateBranchRoot);if(a(d))return i(d.message);let l=s.find(u=>u.action==="add.issue")?.payload.id;return l?c("Created issue",{id:l,title:e.title,parentId:e.parentId}):i("Unable to determine created issue id")},nl=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Pe();if(a(n))return n;let r=Ut(ae,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(r))return r;let o={id:Ie(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ae,rank:r.value}},s=B([o],t.value.stateBranchRoot);return a(s)?i(s.message):c("Closed issue",{id:e.issueId})},rl=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Pe();if(a(n))return n;let r=De();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!T(o))return i("Target node is not issue");if(o.parentNodeId!==ae)return i("Issue is not closed");let s=so(o);if(!s)return i("Unable to resolve previous parent from issue history");if(s===ae)return i("Previous parent resolves to closed swimlane");let d=r.value.nodes[s];if(!d)return i("Previous parent no longer exists");let l=Ut(d.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(l))return l;let u={id:Ie(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:d.id,rank:l.value}},m=B([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Reopened issue",{id:o.id,parentId:d.id})},ol=async e=>{let t=_s(e.repoRoot);if(a(t))return t;let n=Pe();if(a(n))return n;let r=We({repoRoot:t.value});if(a(r))return r;let o=Dt(r.value);if(a(o))return o;let s=$n(o.value);if(a(s))return s;let d=Ut(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(a(d))return d;let l={id:Ie(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:d.value}},u=B([l],r.value);return a(u)?i(u.message):c("Moved issue",{id:e.issueId,parentId:e.parentId})},sl=async(e={})=>{yo();let t=_s(e.repoRoot);if(a(t))return i("Sync failed");let n=Pe();if(a(n))return n;let r=await Pr({cwd:t.value,ownEventFileName:Ft(n.value)});return a(r)?(Bs(r.message),r):(ho(),c("Synced",r.value))},il=async(e={})=>{let t=await be(e.repoRoot);if(a(t))return t;let n=De();return a(n)?n:c("Retrieved Epiq state",{root:t.value.repoRoot,stateBranchRoot:t.value.stateBranchRoot,nodes:n.value.nodes,rootNodeId:n.value.rootNodeId,contextNode:n.value.contextNode,selectedIndex:n.value.selectedIndex,eventLog:n.value.eventLog})},al=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Pe();if(a(n))return n;let r=De();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!T(o))return i("Edit target must be an issue");if(o.readonly)return i("Cannot edit readonly issue");let s=o.props.description??"";if(s===e.description)return c("No changes made",{id:e.issueId,description:s});let d={id:Ie(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},l=B([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited issue description",{id:e.issueId,description:e.description})},dl=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Pe();if(a(n))return n;let r=De();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!T(o))return i("Edit target must be an issue");if(o.readonly)return i("Cannot edit readonly issue");let s=wt(e.title);if(!s.trim())return i("Issue title cannot be empty");if(o.title===s)return c("No changes made",{id:e.issueId,title:s});let d={id:Ie(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},l=B([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited issue title",{id:e.issueId,title:s})},cl=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Pe();if(a(n))return n;let r=De();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!T(o))return i("Tag target must be an issue");if(o.readonly)return i("Cannot tag readonly issue");let s=wt(e.tagName).trim();if(!s)return i("Tag name cannot be empty");let d=Object.values(r.value.tags).find(p=>p.name===s),l=d?.id??Ie(),u=[...d?[]:[{id:Ie(),...n.value,action:"create.tag",payload:{id:l,name:s}}],{id:Ie(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:l}}],m=B(u,t.value.stateBranchRoot);return a(m)?i(m.message):c("Added issue tag",{id:e.issueId,tag:{id:l,name:s}})},ll=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Pe();if(a(n))return n;let r=De();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!T(o))return i("Untag target must be an issue");if(o.readonly)return i("Cannot untag readonly issue");if(!r.value.tags[e.tagId])return i("Tag not found");let s={id:Ie(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},d=B([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue tag",{id:e.issueId,tagId:e.tagId})},ul=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Pe();if(a(n))return n;let r=De();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!T(o))return i("Assign target must be an issue");if(o.readonly)return i("Cannot assign readonly issue");let s=wt(e.assigneeName).trim();if(!s)return i("Assignee name cannot be empty");let d=Object.values(r.value.contributors).find(p=>p.name===s),l=d?.id??Ie(),u=[...d?[]:[{id:Ie(),...n.value,action:"create.contributor",payload:{id:l,name:s}}],{id:Ie(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:l}}],m=B(u,t.value.stateBranchRoot);return a(m)?i(m.message):c("Added issue assignee",{id:e.issueId,assignee:{id:l,name:s}})},ml=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Pe();if(a(n))return n;let r=De();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!T(o))return i("Unassign target must be an issue");if(o.readonly)return i("Cannot unassign readonly issue");if(!r.value.contributors[e.assigneeId])return i("Assignee not found");let s={id:Ie(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},d=B([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},pl=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Pe();if(a(n))return n;let r=De();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!T(o))return i("Comment target must be an issue");if(o.readonly)return i("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return i("Comment cannot be empty");let d=Ie(),l={id:Ie(),...n.value,action:"add.issue.comment",payload:{id:d,issue:e.issueId,md:s,author:n.value.userId}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Added issue comment",{id:d,issueId:e.issueId,body:s})},gl=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Pe();if(a(n))return n;let r=De();if(a(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return i("Unable to resolve comment");if(o.payload.author!==n.value.userId)return i("You can only delete your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return i("Issue not found");if(!T(s))return i("Comment target must be an issue");if(s.readonly)return i("Cannot delete comment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return c("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let l={id:Ie(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})}});var hl={};Nl(hl,{createMcpServer:()=>vl,resultJson:()=>le,startMcpServer:()=>yl});import{McpServer as Sg}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Ag}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as E}from"zod";var le,vl,yl,xl=y(async()=>{"use strict";C();fl();le=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),vl=()=>{let e=new Sg({name:"epiq",version:"0.2.30"});return e.registerTool("epiq_state_get",{description:"Get the full current Epiq state, including nodes and event log",inputSchema:E.object({repoRoot:E.string().optional()})},async t=>le(await il(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:E.object({repoRoot:E.string().optional(),includeClosed:E.boolean().optional()})},async t=>le(await el(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:E.object({repoRoot:E.string().optional()})},async t=>le(await Qc(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:E.object({repoRoot:E.string().optional(),boardId:E.string().optional()})},async t=>le(await Zc(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue",inputSchema:E.object({title:E.string().min(1),parentId:E.string().min(1),repoRoot:E.string().optional()})},async t=>le(await tl(t))),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:E.object({issueId:E.string().min(1),description:E.string(),repoRoot:E.string().optional()})},async t=>le(await al(t))),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:E.object({issueId:E.string().min(1),title:E.string().min(1),repoRoot:E.string().optional()})},async t=>le(await dl(t))),e.registerTool("epiq_issue_tag_add",{description:"Add a tag to an Epiq issue, creating the tag if it does not exist",inputSchema:E.object({issueId:E.string().min(1),tagName:E.string().min(1),repoRoot:E.string().optional()})},async t=>le(await cl(t))),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:E.object({issueId:E.string().min(1),tagId:E.string().min(1),repoRoot:E.string().optional()})},async t=>le(await ll(t))),e.registerTool("epiq_issue_assignee_add",{description:"Assign a contributor to an Epiq issue, creating the contributor if they do not exist",inputSchema:E.object({issueId:E.string().min(1),assigneeName:E.string().min(1),repoRoot:E.string().optional()})},async t=>le(await ul(t))),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:E.object({issueId:E.string().min(1),assigneeId:E.string().min(1),repoRoot:E.string().optional()})},async t=>le(await ml(t))),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:E.object({issueId:E.string().min(1),body:E.string().min(1),repoRoot:E.string().optional()})},async t=>le(await pl(t))),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:E.object({commentId:E.string().min(1),repoRoot:E.string().optional()})},async t=>le(await gl(t))),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:E.object({issueId:E.string().min(1),repoRoot:E.string().optional()})},async t=>le(await rl(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:E.object({issueId:E.string().min(1),repoRoot:E.string().optional()})},async t=>le(await nl(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:E.object({issueId:E.string().min(1),parentId:E.string().min(1),position:E.discriminatedUnion("at",[E.object({at:E.literal("start")}),E.object({at:E.literal("end")}),E.object({at:E.literal("before"),sibling:E.string().min(1)}),E.object({at:E.literal("after"),sibling:E.string().min(1)})]).optional(),repoRoot:E.string().optional()})},async t=>le(await ol(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:E.object({repoRoot:E.string().optional()})},async t=>le(await sl(t))),e},yl=async()=>{let e=vl(),t=new Ag;await e.connect(t)};await yl()});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;await xl().then(()=>hl);
56
+ `,ks.writeFileSync(t,n,"utf8"),ge.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)}});import ig from"node:fs";import Xd from"node:path";var ag,G,Jd,Qd=h(()=>{"use strict";Yd();fr();yt();Dt();Sr();_e();Jn();Ur();bt();Ge();X();C();Pt();ue();Ne();T();pe();ag=async e=>{let t=await _({cwd:e,args:["status","--porcelain"]});return a(t)?t:c("Checked git diff",t.value.stdout.trim().length>0)},G=(e,t)=>i(`[${e}] ${t}`),Jd=async()=>{$("");let e=gr(),t=await Ye(process.cwd());if(a(t))return G(1,t.message);let n=t.value,r=await hr(n);if(a(r))return G(2,r.message);if(r.value)return G(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await ag(n);if(a(o))return G(2.5,o.message);if(o.value)return G(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(Ao(n))return G(4,"Epiq project already initialized");let s=Wr();if(!s.isSetupDone||!s.userName)return G(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let d=re(),l=d.userName,u=d.userId;if(!u||!l)return G(5,"Missing Epiq user id");let m=e.stateBranch,p=await Ir({repoRoot:n,branch:m});if(a(p))return G(6,p.message);if(p.value)return G(6,`State branch already exists: ${m}`);let y=await _o({repoRoot:n,stateBranchName:m});if(a(y))return G(6,y.message);let N=Nr();if(a(N))return G(7,N.message);let R=Xd.join(br(),e.projectId),F=await Bn({repoRoot:n,stateBranchRoot:R,stateBranchName:m});if(a(F))return G(8,F.message);let U=Xd.join(R,".epiq");ig.mkdirSync(U,{recursive:!0});let j=ya({userId:u,userName:l});if(a(j))return G(9,j.message);for(let Ro of j.value){let Ks=Dr({event:Ro,rootDir:R});if(a(Ks))return G(9,Ks.message)}let ee=await Cr({stateBranchRoot:R,eventFileName:jt({userId:u,userName:l})});if(a(ee))return G(10,ee.message);let te=await Zt({cwd:R,message:"[epiq:init]"});if(a(te))return G(10,te.message);let L=await Kd(n);if(a(L))return G(11,L.message);let H=Qs({repoRoot:n,fileContents:e});if(a(H))return G(12,H.message);let An=await oe.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(An))return G(13,An.message);let Ve=await oe.commit({cwd:n,message:"[epiq:init-project]"});if(a(Ve))return G(13,Ve.message);let Jt="Project initialized!",Tn=await _({cwd:n,args:["push","-u","origin","HEAD"]});a(Tn)&&(Jt+=` Warn: [init:14] ${Tn.message}`);let wn=await _n({repoRoot:n,stateBranchRoot:R});a(wn)&&(Jt+=` Warn: [init:15] ${wn.message}`);let qs=Et(j.value).filter(a);if(qs.length>0)return G(16,qs.map(Ro=>Ro.message).join(`
57
+ `));let So=je();if(a(So))return G(16,So.message);let{rootNodeId:Al,nodes:Tl}=So.value,Gs=Tl[Al];return Gs?(P.navigate({contextNode:Gs,selectedIndex:0}),x({hasProjectDefinition:!0,mode:f.DEFAULT}),c(Jt,null)):G(16,"Unable to resolve initialized root node")}});import{ulid as dg}from"ulid";function Ps(e){let t=ec();if(a(t))return t;let{contextNode:n,nodes:r}=g();if(!n.parentNodeId)return i("Missing parent node id");let o=r[n.parentNodeId];if(!o)return i("Missing parent node");let s=K(o.id),d=s.findIndex(({id:m})=>m===n.id);if(d<0)return i("Current node not found among siblings");let l=s[d+e];if(!l)return i("Missing sibling node");let u=tc({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:nc(u.value)}function Ds(e){let t=ec();if(a(t))return t;let{contextNode:n,selectedIndex:r}=g(),s=K(n.id)[r+e];if(!s)return i("Missing sibling node");let d=tc({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:nc(d.value)}var Zd,Mt,ir,ec,Ls,tc,nc,Fs=h(()=>{"use strict";bt();Ge();C();tt();T();Zd=null,Mt=()=>structuredClone(Zd),ir=e=>{Zd=e},ec=()=>{let{contextNode:e,selectedIndex:t}=g(),r=K(e.id)[t];return r?c("Resolved selected child",r):i("Target node not found")},Ls=({id:e,parentId:t,position:n={at:"end"}})=>{let r=K(t).filter(o=>o.id!==e);return Fr(r,n)},tc=({id:e,parentId:t,position:n={at:"end"}})=>{let r=J();if(a(r))return i("Unable to resolve user ID");let o=Ls({parentId:t,id:e,position:n});return a(o)?o:c("Created pending move state",{id:dg(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},nc=e=>{ir(e);let t=It(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as cg}from"ulid";var rc,go,oc,sc=h(()=>{"use strict";_e();Fs();$t();Ge();X();C();tt();ue();T();pe();rc=()=>{let e=Mt();if(!e)return i("No pending move state");let t=e.payload.id,n=e.payload.parent,r=g().nodes[n];if(!r)return i("Move parent not found");let o=K(n).findIndex(s=>s.id===t);return o===-1?i("Moved node not found among rendered children"):(P.navigate({contextNode:r,selectedIndex:o}),c("Synchronized navigation to moved node",null))},go=(e,t="Moved preview")=>{if(a(e))return e;let n=rc();return a(n)?n:(x({mode:f.MOVE}),c(t,null))},oc=async()=>{let e=J();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=Z().commandMeta,{contextNode:n,selectedIndex:r}=g(),o=K(n.id)[r];if(!o)return x({mode:f.DEFAULT}),i("No move target");if(t==="start"){if(o.readonly)return i("Target node is read-only");if(r===-1)return i("No item selected");if(!o.parentNodeId)return i("Target has no parent");let s=K(o.parentNodeId),d=s.findIndex(({id:y})=>y===o.id);if(d===-1)return i("Target not found among siblings");let l=s[d-1],u=s[d+1],m=u!=null?{at:"before",sibling:u.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},p=Ls({parentId:o.parentNodeId,id:o.id,position:m});return a(p)?p:(ir({id:cg(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),x({mode:f.MOVE}),c("Move initialized",null))}if(t==="next")return go(Ds(1));if(t==="previous")return go(Ds(-1));if(t==="to-next")return go(Ps(1));if(t==="to-previous")return go(Ps(-1));if(t==="confirm"){let s=Mt();if(!s)return i("No pending move to confirm");let d=await Ke();if(a(d))return d;let l=B([s],d.value);if(a(l))return l;let u=rc();return a(u)?u:(ir(null),x({mode:f.DEFAULT}),c("Moved item",null))}return t==="cancel"?(ir(null),x({mode:f.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as lg,ulid as ug}from"ulid";var mg,fo,Os=h(()=>{"use strict";C();mg=lg(),fo=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=mg();return c("Created issue events",[{id:ug(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as vo}from"ulid";var ic,ac=h(()=>{"use strict";_e();Os();$t();Ge();qt();C();ae();tt();T();pe();ic=async(e,t)=>{let n=J();if(a(n))return i("Unable to resolve user ID");let r=await Ke();if(a(r))return r;let o=r.value;if(!t.inputString)return i(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:d,selectedIndex:l}=g(),u=m=>{let p=B([m],o);if(a(p))return p;let y=E.getNode(p.value[0].result.id);if(!y)return i("Created node not found");if(!y.parentNodeId)return p;let N=E.getNode(y.parentNodeId);return N?(P.navigate({contextNode:N,selectedIndex:E.getSiblings(y.parentNodeId).findIndex(({id:R})=>R===y.id)}),p):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=E.getNode(m);if(!p)return i("Workspace not found");let y=pn(p.id,n.value,o);return a(y)?y:u({id:vo(),action:"add.board",payload:{id:vo(),name:t.inputString,parent:p.id,rank:y.value},...n.value})}if(t.modifier==="swimlane"){let m=we(s,"BOARD");if(a(m))return i("Unable to add swimlane in this context");let p=pn(m.value.id,n.value,o);return a(p)?p:u({id:vo(),action:"add.swimlane",payload:{id:vo(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=z(d.id)[l],p=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let te=we(s,"SWIMLANE");return a(te)?null:te.value})();if(!p)return i("Unable to add issue in this context");let y=pn(p.id,n.value,o);if(a(y))return y;let N=fo({name:t.inputString,parent:p.id,rank:y.value,user:n.value});if(a(N))return N;let R=N.value,F=B([...R],o);if(a(F))return F;if(!F.value[0])return i("Issue creation failed");let ee=R.find(te=>te.action==="add.issue")?.payload.id;return ee?(P.navigate({contextNode:p,selectedIndex:E.getSiblings(p.id).findIndex(({id:te})=>te===ee)}),c("Issue created",null)):i("Unable to determine ticket id")}return c("Success",null)}});var yo,Us=h(()=>{"use strict";_e();mn();bt();C();T();yo=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=g(),s=Qi(n,t);if(a(s))return i(s.message);let{appliedEvents:d,unappliedEvents:l}=s.value,u=kt();if(a(u))return u;let p=Et(d).filter(a);if(p.length>0)return kt(),x(o),i(p.map(N=>N.message).join(", "));let y=g().nodes[e];return y?(P.navigate({contextNode:y,selectedIndex:r}),c("",{unappliedEvents:l})):(kt(),x(o),i("Board did not exist at that date"))}});var pg,gg,fg,ho,xo,Yt,dc,vg,cc,Bs=h(()=>{"use strict";ln();zo();bt();X();C();T();pg=20,gg=16,fg=150,ho=null,xo=null,Yt=()=>{ho!==null&&(clearInterval(ho),ho=null),xo!==null&&(clearTimeout(xo),xo=null)},dc=()=>{Yt(),x({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},vg=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)},cc=({events:e,startTime:t,durationMs:n})=>{Yt();let r=e.length,o=e.map(y=>cn(y)??t),s=o[r-1]??Date.now(),d=vg(o),l=Math.max(1,Math.round(n*pg/1e3)),u=Math.max(Math.round(n/l),gg),m=0,p=0;x({mode:f.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),ho=setInterval(()=>{m++;let y=m/l,N=[],R;for(;p<r&&d[p]<=y;){let U=e[p],j=It(U);if(a(j)){dc();return}N.push(...Go(U)),R=U,p++}if(p>=r||m>=l){for(;p<r;p++){let j=It(e[p]);if(a(j))break}let U=g().replay;x({unappliedEvents:[],replay:U&&{...U,progress:1,appliedCount:r}}),Yt(),xo=setTimeout(dc,fg);return}let F=g().replay;x({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,y),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:R?cn(R)??F?.currentTime??t:F?.currentTime??t,currentLabel:R?qi(R):F?.currentLabel??"",flashNodeIds:R?[...new Set(N)]:F?.flashNodeIds??[]}})},u)}});var lc,uc=h(()=>{"use strict";yt();ln();mn();bt();X();qt();C();ue();T();Zn();Us();Bs();lc=async()=>{let e=we(g().breadCrumb,"BOARD");if(a(e))return e;let t=await Ye(process.cwd());if(a(t))return i("Unable to locate repo root");let n=ze({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=Z().commandMeta;if(Yt(),r==="now"){let l=_t(n.value);if(a(l))return i(l.message);let u=kt();if(a(u))return u;let p=Et(l.value).filter(a);return p.length>0?i(p.map(y=>y.message).join(", ")):(x({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),c("Peeking now",!0))}let s;if(r==="prev"){let l=g().eventLog.at(-1),u=cn(l);if(u===null)return i("No previous event to peek");s=u}else if(r==="next"){let l=g().unappliedEvents.at(0),u=cn(l);if(u===null)return i("No next event to peek");s=u+1}else{let l=Vt(r||o.trim());if(!l)return i("Invalid peek date");s=l.getTime()}let d=yo({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(d)?d:(x({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:d.value.unappliedEvents,replay:null}),c("Peeking",!0))}});var mc,pc=h(()=>{"use strict";yt();qt();C();ue();T();Zn();Us();Bs();mc=async()=>{let e=we(g().breadCrumb,"BOARD");if(a(e))return e;let t=await Ye(process.cwd());if(a(t))return i("Unable to locate repo root");let n=ze({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=Z().commandMeta,{dateInput:s,durationInput:d}=qr(r,o);if(Yt(),g().syncStatus.status==="syncing")return i("Cannot replay while syncing, try again in a moment");let l=Vt(s);if(!l)return i("Invalid replay date");let u=d?zr(d):15e3;if(u===null)return i("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=g(),y=yo({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(y))return y;let{unappliedEvents:N}=y.value;return N.length===0?(kt(),x(p),c("Nothing to replay from that point",!0)):(cc({events:N,startTime:m,durationMs:u}),c("Replaying board history",!0))}});import hg from"zod";var gc,fc=h(()=>{"use strict";Sn();X();C();ue();Ne();T();gc=()=>{let e=Z().commandMeta.inputString,t=hg.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return i("Auto sync duration must be a number of at least 3000 ms");let n=st({autoSyncDebounceMs:t.data});return a(n)?n:(Ze({autoSyncIntervalMs:t.data}),x({mode:f.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))}});var vc,yc=h(()=>{"use strict";Jn();Sn();X();C();ue();Ne();T();vc=()=>{let e=Z().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=Sa(e),n=st({autoSync:t});return a(n)?n:(Ze({autoSync:t}),x({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var hc,xc=h(()=>{"use strict";Sn();X();C();ue();Ne();T();hc=()=>{let e=Z().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return i("Invalid response");let n=st({logLevel:e});return a(n)?n:(Ze({logLevel:e}),x({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});import{spawn as xg}from"node:child_process";var Ig,Ic,Ec=h(()=>{"use strict";C();Ig=()=>{switch(process.platform){case"darwin":return{command:"pbcopy",args:[]};case"win32":return{command:"clip",args:[]};default:return process.env.WAYLAND_DISPLAY?{command:"wl-copy",args:[]}:{command:"xclip",args:["-selection","clipboard"]}}},Ic=async e=>new Promise(t=>{let{command:n,args:r}=Ig();try{let o=xg(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(i(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?c("Copied to clipboard",null):i(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(i(`Clipboard tool not available (${n})`))}})});var ar,bc,Nc=h(()=>{"use strict";C();T();Ec();sn();Qn();St();ar=async(e,t)=>{if(!e.trim())return i(`Nothing to copy: ${t} is empty`);let n=await Ic(e);return a(n)?n:c(`Copied ${t} to clipboard`,null)},bc=async e=>{let{breadCrumb:t,selectedNode:n}=g(),r=er({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return i("Nothing selected to copy from");switch(e.modifier){case ce.REF:return ar(qe(o.id),"ref");case ce.TITLE:return ar(o.title,"title");case ce.DESCRIPTION:return r?ar(r.props?.description??"","description"):i("No issue in scope");case ce.TAGS:{if(!r)return i("No issue in scope");let s=Nt(r).map(({name:d})=>d);return ar(s.join(", "),"tags")}case ce.ASSIGNEES:{if(!r)return i("No issue in scope");let s=Ct(r).map(({name:d})=>d);return ar(s.join(", "),"assignees")}default:return i("Yank one of: ref, title, description, tags, assignees")}}});var Cc,Sc=h(()=>{"use strict";es();X();C();ue();T();Cc=async()=>{$(""),x({mode:f.DEFAULT});let e=je();if(a(e))return i(e.message);if(e.value.syncStatus.status==="syncing")return i("Sync already in progress");x({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Br();return a(t)?(x({syncStatus:{msg:t.message,status:"failed"}}),t):(x({mode:f.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as Ie}from"ulid";var Eg,Rc,Ac,gt,Tc,wc=h(()=>{"use strict";Ld();_e();Sn();$t();Ge();As();un();X();qt();ne();C();ae();tt();ue();Ne();T();po();pe();Wd();Ht();gs();St();cs();Gd();Qd();sc();ac();uc();pc();fc();yc();xc();Nc();Sc();Eg=e=>e.action==="add.issue.comment",Rc=e=>Object.values(g().tags).find(t=>t.name===e),Ac=e=>Object.values(g().contributors).find(t=>t.name===e),gt=async()=>{let e=await Ke();return a(e)?e:c("Resolved persist root",e.value)},Tc=[{systemOnly:!0,intent:M.Move,description:"Internal move-state command",mode:f.COMMAND_LINE,action:oc},{intent:M.Delete,description:"Delete the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=z(t.id)[n];if(!r)return i("Unable to resolve child to delete");let o=await gt();if(a(o))return o;if(r.context==="COMMENT"){let s=r.id,d=w(t)?t.id:t.parentNodeId;if(!d)return i("Unable to resolve comment issue");let l=g().nodes[d];if(!l||!w(l))return i("Unable to resolve comment issue");let u=l.log?.filter(Eg).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):B([{id:Ie(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],o.value):i("Unable to resolve comment")}return B([{id:Ie(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:M.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:f.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=Z().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(d=>ie(v.FILTER).map(l=>l.split(n)[0]).includes(d))(r))return i("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return ye(d=>({...d,filters:e==="clear"?[]:[...d.filters,s],mode:f.DEFAULT})),c("Filter updated",null)}},{intent:M.ViewHelp,description:"Open the help screen",mode:f.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return wt({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),x({mode:f.HELP}),c("Viewing help",null)}},{intent:M.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=z(t.id)[n];if(!r)return i("Unable to close issue, no target found");if(!w(r))return i("Cannot close in this context");let o=g().nodes[de];if(!o)return i("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return i("Issue is already closed");let s=await gt();if(a(s))return s;let d=s.value,l=Wt(o.id,r.id,{at:"end"},e.value,d);if(a(l))return l;let u=B([{id:Ie(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...e.value}],d);return a(u)?u:c("Issue closed",null)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:M.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=z(t.id)[n];if(!r)return i("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):Ut(r.id,"TICKET");if(a(o))return i("Cannot reopen in this context");let s=o.value,d=g().nodes[de];if(!d)return i("Unable to locate closed swimlane");if(s.parentNodeId!==d.id)return i("Issue is not closed");if(!w(s))return i("Target node is not issue");let l=mo(s);if(!l)return i("Unable to resolve previous parent from issue history");if(l===d.id)return i("Previous parent resolves to closed swimlane");let u=g().nodes[l];if(!u)return i("Previous parent no longer exists");let m=await gt();if(a(m))return m;let p=m.value,y=Wt(u.id,s.id,{at:"end"},e.value,p);if(a(y))return y;let N=B([{id:Ie(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:y.value},...e.value}],p);return a(N)?N:c("Issue reopened",null)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:M.Init,description:"Initialize Epiq in the current git repository",mode:f.COMMAND_LINE,action:Jd},{intent:M.NewItem,description:"Create a new board, swimlane, or issue",mode:f.COMMAND_LINE,action:ic,onSuccess:()=>x({mode:f.DEFAULT})},{intent:M.Rename,description:"Rename the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=z(t.id)[n];if(!r)return i("Missing node");if(r.readonly)return i("Cannot rename readonly node");let o=td();if(!o)return i("Provide a title");let s=await gt();return a(s)?s:B([{id:Ie(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:M.UntagTicket,description:"Remove a tag from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Z().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let o=Rc(r);if(!o)return i(`Tag "${r}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid untag target");let d=Ut(s.id,"TICKET");if(a(d))return i("Unable to untag issue in this context");let l=d.value;if(!w(l))return i("Target node is not issue");if(!(l.props.tags??[]).includes(o.id))return i("Issue is not tagged with that tag");let m=await gt();return a(m)?m:B([{id:Ie(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:M.TagTicket,description:"Add or create a tag on the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Z().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let{selectedNode:o}=g();if(!o)return i("Invalid tag target");let s=Ut(o.id,"TICKET");if(a(s))return i("Unable to tag issue in this context");let d=s.value;if(!w(d))return i("Target node is not issue");let l=await gt();if(a(l))return l;let u=Rc(r),m=u?.id??Ie();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):B([...u?[]:[{id:Ie(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:Ie(),action:"add.issue.tag",payload:{id:d.id,tag:m},...e.value}],l.value)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:M.AssignUserToTicket,description:"Assign a user to the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Z().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee");let{selectedIndex:o,contextNode:s}=g(),d=z(s.id)[o];if(!d)return i("Invalid assign target");let l=Ut(d.id,"TICKET");if(a(l))return i("Unable to assign issue in this context");let u=l.value;if(!w(u))return i("Target node is not issue");let m=await gt();if(a(m))return m;let p=Ac(r),y=p?.id??Ie();return(u.props.assignees??[]).includes(y)?i("Assignee already assigned"):B([...p?[]:[{id:Ie(),action:"create.contributor",payload:{id:y,name:r},...e.value}],{id:Ie(),action:"add.issue.assignee",payload:{id:u.id,assignee:y},...e.value}],m.value)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:M.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Z().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee to remove");let o=Ac(r);if(!o)return i(`Assignee "${r}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid unassign target");let d=Ut(s.id,"TICKET");if(a(d))return i("Unable to unassign in this context");let l=d.value;if(!w(l))return i("Target node is not issue");if(!(l.props.assignees??[]).includes(o.id))return i(`Issue is not assigned to "${r}"`);let m=await gt();return a(m)?m:B([{id:Ie(),action:"remove.issue.assignee",payload:{id:l.id,assignee:o.id},...e.value}],m.value)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:M.Comment,description:"Add a comment to the selected issue",mode:f.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return i("Provide a comment");if(n.length>vn)return i(`Cannot exceed ${vn} characters`);let r=J();if(a(r))return i("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=g(),d=we([...o,s],"TICKET");if(a(d))return i("Edit target must be an issue");let l=d.value;if(!l)return i("Invalid comment target");let u=l.context==="TICKET"?c("Resolved ticket",l):Ut(l.id,"TICKET");if(a(u))return i("Unable to comment on issue in this context");let m=u.value;if(!w(m))return i("Target node is not issue");let p=await gt();return a(p)?p:B([{id:Ie(),action:"add.issue.comment",payload:{id:Ie(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>x({mode:f.DEFAULT})},{intent:M.Sync,description:"Pull, commit, and push Epiq state",mode:f.COMMAND_LINE,action:Cc},{intent:M.Peek,description:"View board state at another point in time",mode:f.COMMAND_LINE,action:lc},{intent:M.Replay,description:"Replay board history forward from a point in time",mode:f.COMMAND_LINE,action:mc},{intent:M.Export,description:"Export the current board layout to markdown",mode:f.COMMAND_LINE,action:async()=>{let e=await kd();return a(e)?e:(x({mode:f.DEFAULT}),c("Export successful",!0))}},{intent:M.Exit,description:"Exit the application",mode:f.COMMAND_LINE,action:async()=>(P.exit(),c("Exit successful",!0))},{intent:M.Edit,description:"Edit title or description",mode:f.COMMAND_LINE,action:async(e,t)=>qd(t),onSuccess:()=>x({mode:f.DEFAULT})},{intent:M.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:f.COMMAND_LINE,action:async(e,t)=>bc(t),onSuccess:()=>x({mode:f.DEFAULT})},{intent:M.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:f.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case se.USERNAME:{let{userId:r,preferredEditor:o,userName:s}=re(),d=n||s,l=r??Ie();if(!d||!l)return i("Unable to resolve user name or id");let u=st({userName:d,userId:l,preferredEditor:o??""});return a(u)?u:(Ze({userName:d,userId:l}),x({mode:f.DEFAULT}),c(`Username set to "${d}"`,null))}case se.EDITOR:{if(!n)return i("No editor provided");let r=st({preferredEditor:n});return a(r)?r:(Ze({preferredEditor:n}),x({mode:f.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case se.VIEW:{if(n!=="wide"&&n!=="dense")return i("Invalid view mode");let r=st({viewMode:n});return a(r)?r:(Ze({viewMode:n}),x({mode:f.DEFAULT}),c(`View set to "${n}"`,null))}case se.AUTOSYNC:return vc();case se.LOG_LEVEL:return hc();case se.SYNC_DEBOUNCE_MS:return gc();default:return i("Unknown config command")}}},{intent:M.Coffee,description:"Sponsor the development of Epiq!",mode:f.COMMAND_LINE,action:()=>{let e=Z().commandMeta.modifier;return e==="custom"?ws("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):ws(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),$(""),c("Thanks you!",null)}}]});var bg,it,_s=h(()=>{"use strict";$r();Kr();gs();wc();C();ue();Ne();T();bg=new Set(["peek","replay","filter","view-help","yank"]),it=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=Z();if(!t)return i("No command to confirm");if(!e&&n===Rt.Invalid)return i("Invalid command");let s=nd(t);Ja();let{readOnly:d}=g();if(d&&!bg.has(s))return tr({status:ft.Fail,message:"Command not available in readonly state",value:null});let l=Tc.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return tr({status:ft.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return tr({status:ft.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?tr(u):(Qa({addToHistory:!e}),l.onSuccess?.(),re().autoSync&&ba(),u)}});var Io,Eo,Mc,kc=h(()=>{"use strict";C();X();T();Ft();_s();Fs();ue();Io=[{intent:A.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(x({mode:f.COMMAND_LINE}),$("move cancel"),it({isForceExecutedBySystem:!0}))},{intent:A.InitMove,mode:f.DEFAULT,description:"[m] move (init/confirm)",action:()=>(x({mode:f.COMMAND_LINE}),$("move start"),it({isForceExecutedBySystem:!0}))},{intent:A.ConfirmMove,mode:f.MOVE,action:()=>(x({mode:f.COMMAND_LINE}),$("move confirm"),it({isForceExecutedBySystem:!0}))}],Eo=[{intent:A.MovePreviousItem,mode:f.MOVE,action:()=>Mt()?(x({mode:f.COMMAND_LINE}),$("move previous"),it({isForceExecutedBySystem:!0})):i("No pending move")},{intent:A.MoveNextItem,mode:f.MOVE,action:()=>Mt()?(x({mode:f.COMMAND_LINE}),$("move next"),it({isForceExecutedBySystem:!0})):i("No pending move")}],Mc=[{intent:A.MoveToNextContainer,mode:f.MOVE,action:()=>Mt()?(x({mode:f.COMMAND_LINE}),$("move to-next"),it({isForceExecutedBySystem:!0})):i("No pending move")},{intent:A.MoveToPreviousContainer,mode:f.MOVE,action:()=>Mt()?(x({mode:f.COMMAND_LINE}),$("move to-previous"),it({isForceExecutedBySystem:!0})):i("No pending move")}]});var Lc,Pc=h(()=>{"use strict";ne();kc();Lc={[k.WORKSPACE]:[...Io,...Eo],[k.BOARD]:[...Io,...Eo],[k.SWIMLANE]:[...Io,...Eo,...Mc],[k.TICKET]:[],[k.FIELD]:[],[k.FIELD_LIST]:[],[k.TEXT]:[],[k.COMMENT]:[]}});var Dc,Fc,Oc=h(()=>{"use strict";X();C();ue();T();po();Ft();_e();Dc=()=>{$("");let{pendingNavTarget:e}=Rn();x({mode:f.DEFAULT}),e&&P.navigate(e),wt({pendingNavTarget:void 0})},Fc=[{intent:A.ExitCommandLine,mode:f.HELP,action:()=>(Dc(),c("Exiting help",null))},{intent:A.Exit,mode:f.HELP,action:()=>(Dc(),c("Closed help",null))},{intent:A.NavPreviousItem,mode:f.HELP,description:"[arrows/hjkl] navigate",action:()=>(P.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:A.NavNextItem,mode:f.HELP,action:()=>(P.navigateToNextItem(),c("Navigating to next help item",null))},{intent:A.NavToPreviousContainer,mode:f.HELP,action:()=>(P.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:A.NavToNextContainer,mode:f.HELP,action:()=>(P.navigateToNextContainer(),c("Navigating to next help container",null))}]});var Ng,Uc,Bc,_c=h(()=>{"use strict";X();ne();C();ue();T();po();Ft();_e();Ng=e=>{x({mode:f.COMMAND_LINE});let{pendingNavTarget:t}=Rn();t&&P.navigate(t),wt({pendingNavTarget:void 0}),$(`${e} `)},Uc=()=>{$("");let{pendingNavTarget:e}=Rn();e&&P.navigate(e),wt({pendingNavTarget:void 0}),x({mode:f.DEFAULT})},Bc=[{intent:A.InitCommandPalette,mode:f.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{$("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return wt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),x({mode:f.PALETTE}),c("Opening command palette",null)}},{intent:A.Confirm,mode:f.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!bi(e))return i("Command only applicable on text nodes");if(e.props.disabled)return i("Command is not available in this context");let t=e.title;return t?(Ng(t),c("Selected command",t)):c("No command selected",null)}},{intent:A.ExitCommandLine,mode:f.PALETTE,action:()=>(Uc(),c("Exiting palette",null))},{intent:A.Exit,mode:f.PALETTE,action:()=>(Uc(),c("Closed command palette",null))},{intent:A.NavPreviousItem,mode:f.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(P.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:A.NavNextItem,mode:f.PALETTE,action:()=>(P.navigateToNextItem(),c("Navigating to next item",null))},{intent:A.NavToPreviousContainer,mode:f.PALETTE,action:()=>(P.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:A.NavToNextContainer,mode:f.PALETTE,action:()=>(P.navigateToNextContainer(),c("Navigating to next container",null))}]});var jc,$c=h(()=>{"use strict";Ht();St();X();C();on();tt();ue();T();Ft();Oc();_c();_e();jc=[...Fc,...Bc,{intent:A.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(x({mode:f.COMMAND_LINE}),$(`${v.NEW} `),c("Adding new item",null))},{intent:A.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(x({mode:f.COMMAND_LINE}),$(`${v.DELETE} `),c("Deleting item",null))},{intent:A.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(x({mode:f.COMMAND_LINE}),$(""),c("Entering command line mode",null))},{intent:A.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!K(e?.id??"")?.length){if(e?.title===Y.DESCRIPTION)return x({mode:f.COMMAND_LINE}),$(`${v.EDIT} description `),c("Propose command",!0);if(e?.title===Y.ASSIGNEES)return x({mode:f.COMMAND_LINE}),$(`${v.ASSIGN} `),c("Propose command",!0);if(e?.title===Y.TAGS)return x({mode:f.COMMAND_LINE}),$(`${v.TAG} `),c("Propose command",!0);if(t.title===Y.DESCRIPTION&&e?.context==="TEXT")return x({mode:f.COMMAND_LINE}),$(`${v.EDIT} description `),c("Propose command",!0)}return P.enterChildNode(),c("Entering context",null)}},{intent:A.Yank,mode:f.DEFAULT,description:"[y] yank to clipboard",action:()=>{let{selectedNode:e}=g(),t=e?.title===Y.DESCRIPTION?ce.DESCRIPTION:e?.title===Y.TAGS?ce.TAGS:e?.title===Y.ASSIGNEES?ce.ASSIGNEES:ce.REF,r=ie(v.YANK).includes(t)?t:ce.REF;return x({mode:f.COMMAND_LINE}),$(`${v.YANK} ${r}`),c("Propose command",!0)}},{intent:A.EditTitle,mode:f.DEFAULT,description:"[r] rename title",action:()=>(x({mode:f.COMMAND_LINE}),$(`${v.EDIT} title ${g().selectedNode?.title}`),c("Exiting context",null))},{intent:A.EditDescription,mode:f.DEFAULT,description:"[e] edit description",action:()=>(x({mode:f.COMMAND_LINE}),$(`${v.EDIT} description `),c("Exiting context",null))},{intent:A.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(P.enterParentNode(),c("Exiting context",null))},{intent:A.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(P.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:A.NavNextItem,mode:f.DEFAULT,action:()=>(P.navigateToNextItem(),c("Navigating to next item",null))},{intent:A.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(P.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:A.NavToNextContainer,mode:f.DEFAULT,action:()=>(P.navigateToNextContainer(),c("Navigating to next container",null))}]});var Cg,Sg,Wc,Hc=h(()=>{"use strict";ue();Cg=500,Sg=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Wc=e=>{let t=Sg(e);t&&Qr(n=>(n+t).slice(0,Cg))}});var Rg,Ag,Vc,zc=h(()=>{"use strict";Hc();X();C();ue();T();Ft();_s();Rg=[f.COMMAND_LINE,f.PALETTE],Ag=e=>[{intent:A.MoveCursorLeft,mode:e,action:()=>(ms(-1),c("Moving cursor left",null))},{intent:A.MoveCursorRight,mode:e,action:()=>(ms(1),c("Moving cursor right",null))},{intent:A.MoveCursorLeftOfWord,mode:e,action:()=>(ps("left"),c("Moving cursor left of word",null))},{intent:A.MoveCursorRightOfWord,mode:e,action:()=>(ps("right"),c("Moving cursor right of word",null))},{intent:A.AutoCompleteCommand,mode:e,action:()=>(Qr((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=g().selectedNode?.title??""),r+o}),c("Auto-completing command",null))},{intent:A.CaptureInput,mode:e,action:(t,{sequence:n})=>(Wc(n??""),c("Capturing input",null))},{intent:A.EraseInput,mode:e,action:()=>(Ya(),c("Erasing input",null))},{intent:A.EraseInputWord,mode:e,action:()=>(Xa(),c("Erasing input word",null))}],Vc=[{intent:A.Confirm,mode:f.COMMAND_LINE,action:()=>(it(),c("Executing command",null))},{intent:A.ViewHelp,mode:f.DEFAULT,action:()=>(x({mode:f.HELP}),c("Viewing help",null))},...Rg.flatMap(Ag),{intent:A.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(x({mode:f.DEFAULT}),c("Exiting command line",null))},{intent:A.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Za(),c("Getting last command from history",null))},{intent:A.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(ed(),c("Getting next command from history",null))}]});import Kc from"chalk";var bo,qc,Gc,js,Yc=h(()=>{"use strict";X();ne();Se();bo=Kc.dim.hex(S.secondary2)(": for command line"),qc="q to exit",Gc=`${Kc.hex(S.accent)("m")} to confirm`,js={[k.WORKSPACE]:[bo],[k.BOARD]:[bo],[k.BOARD+f.COMMAND_LINE]:[bo],[k.SWIMLANE]:[bo],[k.TICKET+f.HELP]:[qc],[k.SWIMLANE+f.HELP]:[qc],[k.TICKET]:[],[k.FIELD]:[],[k.SWIMLANE+f.MOVE]:[Gc],[k.TICKET+f.MOVE]:[Gc]}});var dr,Tg,wg,Xc,Jc=h(()=>{"use strict";T();sn();dr=e=>e.trim().toLocaleLowerCase(),Tg=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},wg=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},Xc=(e,t)=>{let n=dr(t.value);if(!n)return!0;switch(t.target){case"title":return dr(e.title??"").includes(n);case"description":return dr(e.props.description??"").includes(n);case"tag":return Tg(e).map(dr).some(o=>o.includes(n));case"assignee":return wg(e).map(dr).some(o=>o.includes(n));case"ref":return Fi(e.id,t.value);default:return!0}}});function Qc(e,t,n){let r=t[e];if(!r)return i("buildBreadCrumb(): current node not found");let o=[],s=r;for(;s&&(o.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let d=o[o.length-1];return!d||d.id!==n?i("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var Zc=h(()=>{"use strict";C()});var el,tl=h(()=>{"use strict";el=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t}});import{useSyncExternalStore as Mg}from"react";function rl(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return i("derive(): contextNodeId is missing");if(!r)return i("derive(): rootNode is missing");if(!o[r])return i("derive(): unable to find root node");let l=o[t];if(!l)return i("Unable to derive state, contextNode not found");let u=Qc(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,y=js[p+n]??js[p]??[],N=[...jc,...Lc[p]??[],...Vc],R=el(N),F=Lg(o,s),U=F[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:y,availableActions:N,actionIndex:R,selectedNode:U,renderedChildrenIndex:F})}function qn(e){$s=e;let t=vt(process.cwd()),n=!1;if(!a(t)){let s=ht(t.value);if(a(s))return i(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:f.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{}},o=rl(r);return a(o)?o:(Xt=o.value,nl(),c("State initialized",null))}function ye(e){let t=g(),n=e(t),r=rl(n);return a(r)?i(r.message??"Unable to update state"):(Xt=r.value,nl(),c("State updated",null))}var Xt,$s,Ws,nl,kg,g,je,x,We,Lg,z,kt,fn,T=h(()=>{"use strict";Pc();$c();zc();Yc();Pt();X();ne();C();pe();Jc();Zc();tl();Ws=new Set,nl=()=>{for(let e of Ws)e()},kg=e=>(Ws.add(e),()=>Ws.delete(e));g=()=>{if(!Xt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Xt},je=()=>Xt?c("Retrieved state",Xt):i("State not initialized. Call initWorkspaceState() first.");x=e=>ye(t=>({...t,...e})),We=()=>Mg(kg,g,g),Lg=(e,t)=>{let n={};for(let r of Object.values(e))w(r)&&t.length>0&&!t.every(o=>Xc(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,s)=>{let d=e[o.id],l=e[s.id];return!d||!l?0:d.rank.localeCompare(l.rank)});return n},z=e=>g()?.renderedChildrenIndex[e]??[],kt=()=>$s?qn($s):i("Cannot reset state: no initial workspace found"),fn=()=>Xt!==void 0});var Hs,No,Co,Vs,$e,_r=h(()=>{"use strict";Ei();C();T();Hs=e=>{fn()&&(x({syncStatus:e}),Ii({type:"sync-status",payload:e}))},No=(e="Syncing...")=>{Hs({status:"syncing",msg:e})},Co=(e="Synced")=>{Hs({status:"synced",msg:e})},Vs=e=>{Hs({status:"failed",msg:e})},$e=e=>(Vs(e),i(e))});import{decodeTime as Nw}from"ulid";var ol=h(()=>{"use strict";C()});var Pg,Dg,jr,ts=h(()=>{"use strict";C();_r();Zo();vr();yt();Dt();Sr();ol();Pg=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=V("getRepoRootDir",await Ye(e));if(a(n))return i(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=V("getStateBranchRoot",ze({repoRoot:r}));if(a(o))return i(o.message);let s=o.value;logger.debug("[sync] state branch root",s);let d=V("ensureInitialCommit",await yi(r));if(a(d))return i(d.message);logger.debug("[sync] initial commit result",{created:d.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let l=V("bootstrapStateBranchStorage",await xi({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(a(l))return i(l.message);logger.debug("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let u=V("hasInProgressGitOperation(stateBranchRoot)",await hr(s));if(a(u))return i(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value)return logger.info("[sync] state branch git operation in progress"),i("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let m=V("ensureStateBranchLayout",gi(r,s));return a(m)?i(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:l.value}),c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:l.value}))},Dg=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=V("stageStateBranchOwnEventFile",await Cr({stateBranchRoot:t,eventFileName:n}));if(a(r))return i(r.message);let o=V("hasStagedChanges(after stage)",await di(t));if(a(o))return i(o.message);if(logger.debug("[sync] state branch change check after stage result",{changed:o.value}),!o.value)return logger.info("[sync] no own event file changes to commit"),c("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let s=V("createStateBranchSyncCommit",await hi({repoRoot:e,stateBranchRoot:t}));return a(s)?i(s.message):(logger.debug("[sync] created sync commit",s.value),c("Committed own event file",{createdCommit:!0,commitSha:s.value}))},jr=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),i("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),i("Own event file must end with .jsonl");No();let n=V("ensureSyncReady",await Pg({cwd:e,ensureUpstream:!0}));if(a(n))return $e(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,d=V("isDetachedHead(stateBranchRoot)",await ci(o));if(a(d))return $e(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return $e("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,p=!1,y=V("getStateBranch",Qt(r));if(a(y))return $e(y.message);let N=y.value;logger.debug("[sync] resolved state branch",{stateBranch:N,stateBranchRoot:o});let R=V("commitOwnEventFileToStateBranch",await Dg({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(a(R))return $e(R.message);l=R.value.createdCommit,u=R.value.commitSha;let F=V("pullBranchRebaseIfPresent",await Fo({cwd:o,branch:N}));if(a(F))return $e(F.message);if(m=F.value,l||s){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:s,stateBranchRoot:o});let U=V("pushStateBranch",await _n({stateBranchRoot:o,repoRoot:r}));if(a(U)&&ai(U.message)){let j=V("pullBranchRebaseIfPresent(retry)",await Fo({cwd:o,branch:N}));if(a(j))return $e(j.message);m=m||j.value,U=V("pushStateBranch(retry)",await _n({stateBranchRoot:o,repoRoot:r}))}if(a(U))return $e(U.message);p=U.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let U=V("git rev-parse HEAD",await _({args:["rev-parse","HEAD"],cwd:o}));if(a(U))return $e(U.message);u=U.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Co(p?"Synced and pushed":m||l?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),c("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,pulled:m,pushed:p,bootstrapped:s})}});import{decodeTime as Ww,ulid as Ee}from"ulid";var zs,be,De,Fe,Fg,Og,sl,il,al,dl,cl,ll,ul,ml,pl,gl,fl,vl,yl,hl,xl,Il,El,bl=h(()=>{"use strict";yt();Dt();Sr();ts();Sn();Os();Ur();mn();$t();Ge();As();un();ne();C();Pt();ae();tt();T();_r();pe();ct();sn();tn();Dn();zs=e=>{let t=vt(e??process.cwd());return a(t)?i(t.message):c("Resolved Epiq repo root",t.value)},be=async e=>{let t=zs(e);if(a(t))return t;let n=ze({repoRoot:t.value});if(a(n))return i(n.message);let r=gr(),o=await Bn({repoRoot:t.value,stateBranchRoot:n.value,stateBranchName:r.stateBranch});if(a(o))return i(o.message);let s=await _({cwd:n.value,args:["pull","--ff-only"]});a(s)&&ge.info(3,s.message);let d=_t(n.value);if(a(d))return i(d.message);let l=Yn(d.value);return a(l)?i(l.message):c("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:n.value})},De=()=>{let e=$d();return a(e)?i(e.message):e.value.userId?e.value.userName?c("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):i("Unable to retrieve user name"):i("Unable to retrieve user id")},Fe=()=>{let e=je();return a(e)?i(e.message):e},Fg=e=>(e.props.tags??[]).map(t=>E.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Re(t.name)})),Og=e=>(e.props.assignees??[]).map(t=>E.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Re(t.name)})),sl=async(e={})=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Fe();if(a(n))return n;let r=Object.values(n.value.nodes).filter(o=>o.context==="BOARD").map(o=>({id:o.id,ref:qe(o.id),title:o.title,parentId:o.parentNodeId,readonly:!!o.readonly}));return c("Listed boards",r)},il=async(e={})=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Fe();if(a(n))return n;let r=Object.values(n.value.nodes).filter(o=>o.context==="SWIMLANE").filter(o=>!e.boardId||o.parentNodeId===e.boardId).map(o=>({id:o.id,title:o.title,boardId:o.parentNodeId,isClosed:o.id===de,readonly:!!o.readonly}));return c("Listed swimlanes",r)},al=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Fe();if(a(n))return n;let r=Object.values(n.value.nodes).filter(w).filter(o=>e.includeClosed||o.parentNodeId!==de).map(o=>({id:o.id,ref:qe(o.id),title:xt(o.title),description:o.props.description??"",parentNodeId:o.parentNodeId,isClosed:o.parentNodeId===de,readonly:!!o.readonly,tags:Fg(o),assignees:Og(o)}));return c("Listed issues",r)},dl=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=De();if(a(n))return n;let r=pn(e.parentId,n.value,t.value.stateBranchRoot);if(a(r))return r;let o=fo({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(a(o))return o;let s=o.value,d=B([...s],t.value.stateBranchRoot);if(a(d))return i(d.message);let l=s.find(u=>u.action==="add.issue")?.payload.id;return l?c("Created issue",{id:l,title:e.title,parentId:e.parentId}):i("Unable to determine created issue id")},cl=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=De();if(a(n))return n;let r=Wt(de,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(r))return r;let o={id:Ee(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:de,rank:r.value}},s=B([o],t.value.stateBranchRoot);return a(s)?i(s.message):c("Closed issue",{id:e.issueId})},ll=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=De();if(a(n))return n;let r=Fe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!w(o))return i("Target node is not issue");if(o.parentNodeId!==de)return i("Issue is not closed");let s=mo(o);if(!s)return i("Unable to resolve previous parent from issue history");if(s===de)return i("Previous parent resolves to closed swimlane");let d=r.value.nodes[s];if(!d)return i("Previous parent no longer exists");let l=Wt(d.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(l))return l;let u={id:Ee(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:d.id,rank:l.value}},m=B([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Reopened issue",{id:o.id,parentId:d.id})},ul=async e=>{let t=zs(e.repoRoot);if(a(t))return t;let n=De();if(a(n))return n;let r=ze({repoRoot:t.value});if(a(r))return r;let o=_t(r.value);if(a(o))return o;let s=Yn(o.value);if(a(s))return s;let d=Wt(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(a(d))return d;let l={id:Ee(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:d.value}},u=B([l],r.value);return a(u)?i(u.message):c("Moved issue",{id:e.issueId,parentId:e.parentId})},ml=async(e={})=>{No();let t=zs(e.repoRoot);if(a(t))return i("Sync failed");let n=De();if(a(n))return n;let r=await jr({cwd:t.value,ownEventFileName:jt(n.value)});return a(r)?(Vs(r.message),r):(Co(),c("Synced",r.value))},pl=async(e={})=>{let t=await be(e.repoRoot);if(a(t))return t;let n=Fe();return a(n)?n:c("Retrieved Epiq state",{root:t.value.repoRoot,stateBranchRoot:t.value.stateBranchRoot,nodes:n.value.nodes,rootNodeId:n.value.rootNodeId,contextNode:n.value.contextNode,selectedIndex:n.value.selectedIndex,eventLog:n.value.eventLog})},gl=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=De();if(a(n))return n;let r=Fe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!w(o))return i("Edit target must be an issue");if(o.readonly)return i("Cannot edit readonly issue");let s=o.props.description??"";if(s===e.description)return c("No changes made",{id:e.issueId,description:s});let d={id:Ee(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},l=B([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited issue description",{id:e.issueId,description:e.description})},fl=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=De();if(a(n))return n;let r=Fe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!w(o))return i("Edit target must be an issue");if(o.readonly)return i("Cannot edit readonly issue");let s=xt(e.title);if(!s.trim())return i("Issue title cannot be empty");if(o.title===s)return c("No changes made",{id:e.issueId,title:s});let d={id:Ee(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},l=B([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited issue title",{id:e.issueId,title:s})},vl=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=De();if(a(n))return n;let r=Fe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!w(o))return i("Tag target must be an issue");if(o.readonly)return i("Cannot tag readonly issue");let s=xt(e.tagName).trim();if(!s)return i("Tag name cannot be empty");let d=Object.values(r.value.tags).find(p=>p.name===s),l=d?.id??Ee(),u=[...d?[]:[{id:Ee(),...n.value,action:"create.tag",payload:{id:l,name:s}}],{id:Ee(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:l}}],m=B(u,t.value.stateBranchRoot);return a(m)?i(m.message):c("Added issue tag",{id:e.issueId,tag:{id:l,name:s}})},yl=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=De();if(a(n))return n;let r=Fe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!w(o))return i("Untag target must be an issue");if(o.readonly)return i("Cannot untag readonly issue");if(!r.value.tags[e.tagId])return i("Tag not found");let s={id:Ee(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},d=B([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue tag",{id:e.issueId,tagId:e.tagId})},hl=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=De();if(a(n))return n;let r=Fe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!w(o))return i("Assign target must be an issue");if(o.readonly)return i("Cannot assign readonly issue");let s=xt(e.assigneeName).trim();if(!s)return i("Assignee name cannot be empty");let d=Object.values(r.value.contributors).find(p=>p.name===s),l=d?.id??Ee(),u=[...d?[]:[{id:Ee(),...n.value,action:"create.contributor",payload:{id:l,name:s}}],{id:Ee(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:l}}],m=B(u,t.value.stateBranchRoot);return a(m)?i(m.message):c("Added issue assignee",{id:e.issueId,assignee:{id:l,name:s}})},xl=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=De();if(a(n))return n;let r=Fe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!w(o))return i("Unassign target must be an issue");if(o.readonly)return i("Cannot unassign readonly issue");if(!r.value.contributors[e.assigneeId])return i("Assignee not found");let s={id:Ee(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},d=B([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},Il=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=De();if(a(n))return n;let r=Fe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!w(o))return i("Comment target must be an issue");if(o.readonly)return i("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return i("Comment cannot be empty");let d=Ee(),l={id:Ee(),...n.value,action:"add.issue.comment",payload:{id:d,issue:e.issueId,md:s,author:n.value.userId}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Added issue comment",{id:d,issueId:e.issueId,body:s})},El=async e=>{let t=await be(e.repoRoot);if(a(t))return t;let n=De();if(a(n))return n;let r=Fe();if(a(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return i("Unable to resolve comment");if(o.payload.author!==n.value.userId)return i("You can only delete your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return i("Issue not found");if(!w(s))return i("Comment target must be an issue");if(s.readonly)return i("Cannot delete comment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return c("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let l={id:Ee(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})}});var Sl={};Ml(Sl,{createMcpServer:()=>Nl,resultJson:()=>me,startMcpServer:()=>Cl});import{McpServer as Ug}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Bg}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as b}from"zod";var me,Nl,Cl,Rl=h(async()=>{"use strict";C();bl();me=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Nl=()=>{let e=new Ug({name:"epiq",version:"0.2.30"});return e.registerTool("epiq_state_get",{description:"Get the full current Epiq state, including nodes and event log",inputSchema:b.object({repoRoot:b.string().optional()})},async t=>me(await pl(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:b.object({repoRoot:b.string().optional(),includeClosed:b.boolean().optional()})},async t=>me(await al(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:b.object({repoRoot:b.string().optional()})},async t=>me(await sl(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:b.object({repoRoot:b.string().optional(),boardId:b.string().optional()})},async t=>me(await il(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue",inputSchema:b.object({title:b.string().min(1),parentId:b.string().min(1),repoRoot:b.string().optional()})},async t=>me(await dl(t))),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),description:b.string(),repoRoot:b.string().optional()})},async t=>me(await gl(t))),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),title:b.string().min(1),repoRoot:b.string().optional()})},async t=>me(await fl(t))),e.registerTool("epiq_issue_tag_add",{description:"Add a tag to an Epiq issue, creating the tag if it does not exist",inputSchema:b.object({issueId:b.string().min(1),tagName:b.string().min(1),repoRoot:b.string().optional()})},async t=>me(await vl(t))),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),tagId:b.string().min(1),repoRoot:b.string().optional()})},async t=>me(await yl(t))),e.registerTool("epiq_issue_assignee_add",{description:"Assign a contributor to an Epiq issue, creating the contributor if they do not exist",inputSchema:b.object({issueId:b.string().min(1),assigneeName:b.string().min(1),repoRoot:b.string().optional()})},async t=>me(await hl(t))),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),assigneeId:b.string().min(1),repoRoot:b.string().optional()})},async t=>me(await xl(t))),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),body:b.string().min(1),repoRoot:b.string().optional()})},async t=>me(await Il(t))),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:b.object({commentId:b.string().min(1),repoRoot:b.string().optional()})},async t=>me(await El(t))),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:b.object({issueId:b.string().min(1),repoRoot:b.string().optional()})},async t=>me(await ll(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),repoRoot:b.string().optional()})},async t=>me(await cl(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:b.object({issueId:b.string().min(1),parentId:b.string().min(1),position:b.discriminatedUnion("at",[b.object({at:b.literal("start")}),b.object({at:b.literal("end")}),b.object({at:b.literal("before"),sibling:b.string().min(1)}),b.object({at:b.literal("after"),sibling:b.string().min(1)})]).optional(),repoRoot:b.string().optional()})},async t=>me(await ul(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:b.object({repoRoot:b.string().optional()})},async t=>me(await ml(t))),e},Cl=async()=>{let e=Nl(),t=new Bg;await e.connect(t)};await Cl()});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;await Rl().then(()=>Sl);