epiq 1.3.3 → 1.3.4

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,58 +1,58 @@
1
1
  #!/usr/bin/env node
2
- var Zl=Object.defineProperty;var h=(e,t)=>()=>(e&&(t=e(e=0)),t);var eu=(e,t)=>{for(var n in t)Zl(e,n,{get:t[n],enumerable:!0})};var Et,i,c,a,mt,C=h(()=>{"use strict";Et={Success:"success",Fail:"fail"},i=e=>({status:Et.Fail,message:e,value:null}),c=(e,t)=>({status:Et.Success,message:e,value:t}),a=e=>e.status==="fail",mt=e=>e.status==="success"});import On from"node:fs";import tt from"node:path";var Pf,nt,Ke,br,Oo,tu,Un,Er,_n,Uo,ui,nu,_o,Nr,rt,mi,ot,ce=h(()=>{"use strict";C();pt();Pf=process.env.IS_LOCAL==="true",nt=".epiq",Ke=".epiq-global",br="events",Oo="media",tu="project.json",Un=e=>tt.join(e,nt),Er=e=>tt.join(Un(e),tu),_n=e=>tt.join(Un(e),br),Uo=e=>tt.join(Un(e),Oo),ui=e=>tt.join(e,nt),nu=e=>{let t=tt.join(e,nt);return On.existsSync(t)&&On.statSync(t).isDirectory()},_o=e=>{let t=Er(e);return On.existsSync(t)&&On.statSync(t).isFile()},Nr=e=>{let t=tt.resolve(e);for(;;){if(nu(t))return c("Resolved closest .epiq root",t);let n=tt.dirname(t);if(n===t)return i("No .epiq directory found in any parent");t=n}},rt=e=>{let t=tt.resolve(e);for(;;){if(_o(t))return c("Resolved closest epiq project root",t);let n=tt.dirname(t);if(n===t)return i("No .epiq/project.json found in any parent");t=n}},mi=e=>{let t=_n(e);try{return On.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")}},ot=async()=>{let e=await st(process.cwd());if(a(e))return e;let t=Pe({repoRoot:e.value});return a(t)?t:c("Resolved persist root",t.value)}});import $n from"node:fs";import{ulid as ru}from"ulid";import{z as Cr}from"zod";var ou,su,Sr,Nt,pi,gi,$t=h(()=>{"use strict";C();ce();ou="__epiq_state__",su=Cr.object({projectId:Cr.string().min(1),stateBranch:Cr.string().min(1),createdAt:Cr.iso.datetime()}),Sr=()=>({projectId:ru(),stateBranch:ou,createdAt:new Date().toISOString()}),Nt=e=>{let t=Er(e);if(!$n.existsSync(t))return i("Missing .epiq/project.json");try{let n=$n.readFileSync(t,"utf8"),r=JSON.parse(n),o=su.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")}},pi=e=>{let t=Nt(e);return a(t)?i(t.message):c("Read projectId",t.value.projectId)},gi=({repoRoot:e,fileContents:t})=>{let n=Un(e),r=Er(e);try{if($n.mkdirSync(n,{recursive:!0}),$n.existsSync(r)){let o=Nt(e);return a(o)?i(o.message):c("Project already initialized",null)}return $n.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 $o,fi=h(()=>{"use strict";C();$o=(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 jn from"fs";import Ko from"path";import iu from"util";function du(){let e=hi();if(!e||!jn.existsSync(e))return;let n=jn.readFileSync(e,"utf8").split(`
4
- `);if(n[n.length-1]===""&&n.pop(),n.length<=vi)return;let r=n.slice(-vi).join(`
2
+ var ru=Object.defineProperty;var h=(e,t)=>()=>(e&&(t=e(e=0)),t);var su=(e,t)=>{for(var n in t)ru(e,n,{get:t[n],enumerable:!0})};var Nt,i,c,a,pt,C=h(()=>{"use strict";Nt={Success:"success",Fail:"fail"},i=e=>({status:Nt.Fail,message:e,value:null}),c=(e,t)=>({status:Nt.Success,message:e,value:t}),a=e=>e.status==="fail",pt=e=>e.status==="success"});import iu from"node:os";import au from"node:path";var Je,_n,$r=h(()=>{"use strict";Je=".epiq-global",_n=()=>process.env.EPIQ_GLOBAL_DIR??au.join(iu.homedir(),Je)});import $n from"node:fs";import tt from"node:path";var Wf,nt,No,jr,du,jn,So,Wn,Wr,pi,cu,Hr,Co,ot,gi,rt,ue=h(()=>{"use strict";C();gt();$r();Wf=process.env.IS_LOCAL==="true",nt=".epiq",No="events",jr="media",du="project.json",jn=e=>tt.join(e,nt),So=e=>tt.join(jn(e),du),Wn=e=>tt.join(jn(e),No),Wr=e=>tt.join(jn(e),jr),pi=e=>tt.join(e,nt),cu=e=>{let t=tt.join(e,nt);return $n.existsSync(t)&&$n.statSync(t).isDirectory()},Hr=e=>{let t=So(e);return $n.existsSync(t)&&$n.statSync(t).isFile()},Co=e=>{let t=tt.resolve(e);for(;;){if(cu(t))return c("Resolved closest .epiq root",t);let n=tt.dirname(t);if(n===t)return i("No .epiq directory found in any parent");t=n}},ot=e=>{let t=tt.resolve(e);for(;;){if(Hr(t))return c("Resolved closest epiq project root",t);let n=tt.dirname(t);if(n===t)return i("No .epiq/project.json found in any parent");t=n}},gi=e=>{let t=Wn(e);try{return $n.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")}},rt=async()=>{let e=await st(process.cwd());if(a(e))return e;let t=ke({repoRoot:e.value});return a(t)?t:c("Resolved persist root",t.value)}});import Hn from"node:fs";import{ulid as lu}from"ulid";import{z as Ro}from"zod";var uu,mu,Ao,St,fi,vi,Ht=h(()=>{"use strict";C();ue();uu="__epiq_state__",mu=Ro.object({projectId:Ro.string().min(1),stateBranch:Ro.string().min(1),createdAt:Ro.iso.datetime()}),Ao=()=>({projectId:lu(),stateBranch:uu,createdAt:new Date().toISOString()}),St=e=>{let t=So(e);if(!Hn.existsSync(t))return i("Missing .epiq/project.json");try{let n=Hn.readFileSync(t,"utf8"),o=JSON.parse(n),r=mu.safeParse(o);return r.success?c("Read project.json",r.data):i(`Invalid .epiq/project.json: ${r.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")}},fi=e=>{let t=St(e);return a(t)?i(t.message):c("Read projectId",t.value.projectId)},vi=({repoRoot:e,fileContents:t})=>{let n=jn(e),o=So(e);try{if(Hn.mkdirSync(n,{recursive:!0}),Hn.existsSync(o)){let r=St(e);return a(r)?i(r.message):c("Project already initialized",null)}return Hn.writeFileSync(o,JSON.stringify(t,null,2)+`
3
+ `,"utf8"),c("Created project.json",null)}catch(r){return i(r instanceof Error?`Failed to initialize project: ${r.message}`:"Failed to initialize project")}}});var Kr,yi=h(()=>{"use strict";C();Kr=(e,t)=>{let n=new Map,o=t??((...s)=>JSON.stringify(s)),r=((...s)=>{let d=o(...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 r.clear=()=>n.clear(),r}});import Kn from"fs";import Gr from"path";import pu from"util";function fu(){let e=Ii();if(!e||!Kn.existsSync(e))return;let n=Kn.readFileSync(e,"utf8").split(`
4
+ `);if(n[n.length-1]===""&&n.pop(),n.length<=hi)return;let o=n.slice(-hi).join(`
5
5
  `)+`
6
- `;jn.writeFileSync(e,r,"utf8")}function Wo(e,t,n=!1){let r=hi();if(!r)return;let o=iu.format(...t),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
7
- `;jn.mkdirSync(Ko.dirname(r),{recursive:!0}),jn.appendFileSync(r,l,"utf8"),jo++,jo>=au&&(jo=0,du())}var vi,au,jo,yi,hi,Ho,le,ln=h(()=>{"use strict";C();ce();vi=1e3,au=50,jo=0,yi=()=>process.env.EPIQ_MCP==="true",hi=()=>{let e=process.cwd(),t=Nr(e);return a(t)?yi()?Ko.join(process.cwd(),".epiq-mcp.log"):void 0:Ko.join(t.value,nt,"log","epiq.log")};Ho=()=>yi()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",le={info(...e){let t=Ho();(t==="info"||t==="debug")&&Wo("[Info]",e,!1)},debug(...e){Ho()==="debug"&&Wo("[Debug]",e,!0)},error(...e){let t=Ho();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;Wo("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=le});var ie,Rr=h(()=>{"use strict";jt();ie={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 un,Ve,Ar=h(()=>{"use strict";$t();C();ce();un=e=>{let t=rt(e);if(a(t))return i("Unable to resolve epiq project root");let n=Nt(t.value);return a(n)?i("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},Ve="origin"});import{spawn as cu}from"node:child_process";import Tr from"node:fs";import Wn from"node:path";var xi,lu,Ii,_,it,mn,uu,mu,wr,Vo,Mr,Lr,Hn,bi,zo,kr,Ei,Ni,pu,qo,Ci,Si,jt=h(()=>{"use strict";C();Rr();Ar();xi=1e4,lu={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Ii=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Tr.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=cu("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:lu}),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 ${xi}ms`].join(`
8
- `);u(n?{stdout:d,stderr:p,exitCode:124}:i(p))},xi);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})=>Ii({args:e,cwd:t,allowFail:!1}),it=({args:e,cwd:t})=>Ii({args:e,cwd:t,allowFail:!0}),mn=async({cwd:e,message:t})=>{let n=await ie.commit({cwd:e,message:t});if(a(n))return i(`Failed to create commit
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())},uu=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",Wn.isAbsolute(n)?n:Wn.resolve(e,n))},mu=async e=>{let t=await uu(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(Tr.existsSync(Wn.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(Tr.existsSync(Wn.join(n,s)))return c("Checked for in-progress Git operation",d);return c("Checked for in-progress Git operation",null)},wr=async e=>{let t=await mu(e);return a(t)?i(t.message):c("Checked for in-progress Git operation",t.value!==null)},Vo=async({repoRoot:e})=>{let n=(await it({args:["remote","get-url",Ve],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},Mr=async({repoRoot:e,branch:t})=>{let n=await it({args:["ls-remote","--heads",Ve,t],cwd:e});return n.exitCode!==0?i(n.stderr.trim()||`Unable to inspect remote branch ${Ve}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},Lr=async({repoRoot:e,branch:t})=>{let n=await it({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}`)},Hn=e=>{try{return Tr.realpathSync.native(e)}catch{return Wn.resolve(e)}},bi=async({repoRoot:e,worktreeRoot:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let r=Hn(t),o=n.value.stdout.split(`
13
- `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Hn).includes(r);return c("Checked worktree registration",o)},zo=async e=>{let t=await it({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},kr=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())},Ei=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())},Ni=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),pu=async e=>(await it({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1),qo=async({cwd:e,branch:t})=>{let n=await Mr({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 pu(e);if(a(r))return i(r.message);let o=await ie.fetch({cwd:e,remote:Ve,branch:t});if(a(o))return i(`Failed to fetch ${t}
14
- ${o.message}`);let s=await ie.pullRebase({cwd:e,remote:Ve,branch:t});return a(s)?i(`Failed during pull --rebase
15
- ${s.message}`):c("Pulled with rebase",!0)},Ci=async e=>{let t=await it({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 kr(e);return a(t)?i(t.message):c("Checked detached HEAD state",t.value==="HEAD")}});import Go from"node:fs";import gu from"node:os";import Je from"node:path";var Ai,Yo,Ti,wi,Pr,Pe,fu,Ri,Kn,Dr,Mi,Li,ki,st,Ev,pt=h(()=>{"use strict";$t();C();ce();fi();ln();jt();Ai="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Yo=e=>Je.join(nt,br,e),Ti=()=>Je.join(nt,Oo),wi=()=>Je.join(gu.homedir(),Ke),Pr=()=>Je.join(wi(),"worktrees"),Pe=({repoRoot:e})=>{let t=pi(e);return a(t)?i(t.message):c("Resolved state branch root",Je.join(Pr(),t.value))},fu=e=>Je.join(e,nt),Ri=e=>Je.join(fu(e),br),Kn=e=>{try{return Go.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return i(t instanceof Error?t.message:String(t))}},Dr=()=>{let e=Kn(wi());if(a(e))return i(`Ensure epiq home failed.
16
- `+e.message);let t=Kn(Pr());return a(t)?i(`Ensure worktrees dir failed.
17
- `+t.message):c("Ensured epiq storage",!0)},Mi=e=>{Go.existsSync(e)&&(le.debug("[sync] remove path",e),Go.rmSync(e,{recursive:!0,force:!0}))},Li=(e,t)=>{for(let n of[Ri(e),Ri(t)]){let r=Kn(n);if(a(r))return i(r.message)}return c("Ensured state branch",void 0)},ki=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
- `+t.message);let r=t.value.stdout.trim().split(`
19
- `).filter(Boolean).filter(d=>d!==nt);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 mn({cwd:e,message:"[epiq:repair-storage-branch]"});return a(s)?i(s.message):c("Cleaned storage branch",!0)},st=$o(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)),Ev=$o(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 Wt from"node:fs";import Fr from"node:path";var Di,Pi,vu,Xo,yu,hu,xu,Vn,Iu,bu,Br,Fi,Bi,zn,Oi,Or=h(()=>{"use strict";C();ln();Rr();Ar();pt();jt();Di=async e=>{if((await it({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);le.info("Creating initial commit");let n=await ie.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return a(n)?i(n.message):c("Created initial commit",!0)},Pi=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",vu=async e=>{let t=await kr(e);if(a(t))return i(t.message);let n=await Ei(e);return a(n)?i(n.message):c("Built sync commit message",`[sync|branch:${Pi(t.value)}:sha:${Pi(n.value)}]`)},Xo=async({repoRoot:e,stateBranchName:t})=>{le.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
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)},yu=async({repoRoot:e,stateBranchName:t})=>{let n=await Vo({repoRoot:e});if(a(n))return i(`Ensure local state branch failed
23
- `+n.message);let r=n.value,o=r?await Mr({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 ie.fetch({cwd:e,remote:Ve,branch:t});if(a(l))return i(`Failed to fetch ${t} from remote
25
- ${l.message}`)}let d=await Lr({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,`${Ve}/${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 Xo({repoRoot:e,stateBranchName:t})},hu=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)},xu=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Kn(Fr.dirname(t));if(a(r))return i(`Failed to create state branch worktree
29
- `+r.message);Wt.existsSync(t)&&!Wt.existsSync(Fr.join(t,".git"))&&(le.info("Removing broken state branch worktree path"),Mi(t)),le.info("Creating state branch worktree");let o=await ie.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)},Vn=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await hu({repoRoot:e,branch:n});if(a(r))return i(r.message);let o=Hn(t),s=r.value?Hn(r.value):null;if(s&&s===o&&Wt.existsSync(s))return c("State branch already checked out in expected worktree",!1);if(s&&s!==o){le.info("Moving state branch worktree to expected location");let u=await ie.worktreeRemove({cwd:e,worktreeRoot:s});if(a(u))return i(`Failed to remove existing state branch worktree
31
- ${u.message}`)}if(s&&!Wt.existsSync(s)){le.info("Pruning stale state branch worktree");let u=await ie.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
32
- ${u.message}`)}let d=await bi({repoRoot:e,worktreeRoot:t});if(a(d))return i(d.message);let l=Wt.existsSync(t);if(d.value&&l)return c("State branch worktree already exists",!1);if(d.value&&!l){le.info("Pruning missing registered state branch worktree");let u=await ie.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
33
- ${u.message}`)}return xu({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Iu=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await kr(e);if(a(n))return i(n.message);if(n.value===t)return c("State branch already checked out",!1);(await it({cwd:e,args:["rebase","--abort"]})).exitCode===0&&le.info("Aborted stale state branch rebase");let o=await ie.checkout({cwd:e,branch:t});return a(o)?i(`Failed to checkout ${t}
34
- ${o.message}`):c("Checked out state branch",!0)},bu=async({repoRoot:e,stateBranchRoot:t})=>{let n=await zo(t);if(a(n))return i(n.message);if(n.value)return c("State branch upstream already configured",!1);let r=await Vo({repoRoot:t});if(a(r))return i(r.message);if(!r.value)return c("No remote available for state branch upstream",!1);let o=un(e);if(a(o))return o;let s=o.value,d=await Mr({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);le.info(`Configuring ${s} upstream`);let l=await ie.fetch({cwd:t,remote:Ve,branch:s});if(a(l))return i(`Failed to fetch ${s}
35
- ${l.message}`);let u=await ie.setUpstream({cwd:t,branch:s,upstream:`${Ve}/${s}`});return a(u)?i(`Failed to set state branch upstream
36
- ${u.message}`):c("Configured state branch upstream",!0)},Br=async({stateBranchRoot:e,eventFileName:t})=>{let n=Yo(t),r=Fr.join(e,n);if(!Wt.existsSync(r))return c("No event file to stage",void 0);let o=await ie.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)},Fi=async({stateBranchRoot:e})=>{let t=Ti(),n=Fr.join(e,t);if(!Wt.existsSync(n))return c("No media directory to stage",void 0);let r=await ie.stage({cwd:e,pathspec:[t]});return a(r)?i(`Failed to stage state branch media files
38
- ${r.message}`):c("Staged state branch media files",void 0)},Bi=async({repoRoot:e,stateBranchRoot:t})=>{let n=await vu(e);return a(n)?i(`Create state branch sync commit failed
39
- `+n.message):mn({cwd:t,message:n.value})},zn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await zo(t);if(a(n))return i(n.message);let r=un(e);if(a(r))return r;let o=r.value,s=n.value?await ie.push({cwd:t}):await ie.push({cwd:t,remote:Ve,branch:o,setUpstream:!0});return a(s)?i(`Failed during state branch push
40
- ${s.message}`):c("Pushed state branch",!0)},Oi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=un(e);if(a(o))return o;let s=o.value,d=[Dr(),await yu({repoRoot:e,stateBranchName:s}),await Vn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Iu({stateBranchRoot:t,stateBranchName:s}),await ki(t),n?await bu({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 Eu}from"ws";var Nu,Ui,_i=h(()=>{"use strict";Nu=new Set,Ui=e=>{let t=JSON.stringify(e);for(let n of Nu)n.readyState===Eu.OPEN&&n.send(t)}});function Jo(e){return e.context===L.WORKSPACE}function w(e){return e.context===L.TICKET}function $i(e){return e.context===L.TEXT}function De(e){return e.context===L.FIELD}function qn(e){return e.context===L.FIELD_LIST}var L,Gn,Qo,Yn,te=h(()=>{"use strict";L={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};Gn=e=>e.context===L.SWIMLANE,Qo=e=>e.context===L.BOARD,Yn=e=>e.context===L.COMMENT});var f,J=h(()=>{"use strict";f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var ji=h(()=>{"use strict";Ht()});function Ur(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Xn,Ct,pn=h(()=>{"use strict";Xn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Ct=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var Wi,Hi,Ki=h(()=>{"use strict";Wi=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},Hi=(e,t)=>t?e.get(t)??[]:[]});var Vi,Cu,zi,qi=h(()=>{"use strict";pn();Ki();Vi=new WeakMap,Cu=e=>{let t=Vi.get(e);return t||(t=Wi(e),Vi.set(e,t)),t},zi=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Hi(Cu(e),r).filter(s=>Ur(r,s)>=n)}});var Su,Gi,Ru,Yi=h(()=>{"use strict";pn();qi();Su={hint:"",hints:[],overlap:0,remainder:""},Gi=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Su;let o=zi({wordList:r,inputToMatch:e,overlapThreshold:1});return Ru(t,o)},Ru=(e,t)=>{let n=t[0]??"",r=Ur(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 Xv}from"react";var _r,Au,Tu,ne,ze,Re=h(()=>{"use strict";_r={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Au=new Set,Tu=()=>{for(let e of Au)e()},ne=()=>_r,ze=e=>(_r={..._r,...e},Tu(),_r)});function Xi(e){return!e||!Mu.test(e)?i(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Fe(e,t=gn){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 we(e,t){if(!e&&!t)return Fe(Qe/2n,gn);let n=e?Xi(e):c("Resolved lower bound",0n);if(a(n))return n;let r=t?Xi(t):c("Resolved upper bound",Qe);if(a(r))return r;let o=n.value,s=r.value;if(s<=o)return Fe(Qe/2n,gn);let d=(o+s)/2n;return d===o||d===s?i("No rank space available between neighbors"):Fe(d,gn)}function Ji(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Qe*BigInt(r+1)/(t+1n),s=Fe(o,gn);if(a(s))return s;n.push(s.value)}return c("Resolved evenly spaced ranks",n)}var gn,wu,Qe,Mu,fn=h(()=>{"use strict";C();gn=24n,wu=gn*4n,Qe=(1n<<wu)-1n,Mu=/^[0-9a-f]+$/});import{ulid as Lu}from"ulid";var Zo,Qi=h(()=>{"use strict";C();at();fn();Zo=(e,t)=>{let n=Q(e),r=Ji(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:Lu(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})}});var Vt,ku,Kt,x,ae=h(()=>{"use strict";te();C();T();at();Vt=(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}`)},ku=(e,t)=>{let{nodes:n}=g(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Kt=(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"),x={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=fe(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){fe(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=fe(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=fe(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=fe(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)},createAttachment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create attachment, missing issue");if(!w(t))return i("Can only attach to issues");let n=fe(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?i("Unable to create attachment"):c("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return i("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=fe(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return a(r)?i("Unable to delete attachment"):c("Deleted attachment",n)},getAttachment(e){return g().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(g().attachments??{}).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=Kt(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=Kt(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 Q(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=Kt(o,"move");if(d)return d;if(ku(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 Q(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?(I({nodes:l}),c("Successfully tomb stoned",o)):i("Unable to delete undefined")},createContributor(e){let t=fe(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=Kt(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=Kt(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=Kt(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=Kt(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=fe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?i("Could not create tag"):c("Tag created",e)},createNode(e){let t=fe(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=fe(o=>({...o,nodes:{...o.nodes,[e]:n}}));return a(r)?i(r.message):c("Locked node",n)},updateNode(e){let t=fe(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 Q(e)}}});var z,vn=h(()=>{"use strict";z={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var Ze,Zi,yn=h(()=>{"use strict";Ze=e=>e.slice(-7).toUpperCase(),Zi=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?Ze(e).includes(n):!0}});var ve,zt=h(()=>{"use strict";te();yn();ve={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:L.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:Ze(e)},context:L.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:L.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:L.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:L.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:Ze(e)},context:L.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:L.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:L.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:d})}});var Ee,E,Ae=h(()=>{"use strict";Ee={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"},E={accent:Ee.cyan,accent2:Ee.magenta,primary:Ee.white,secondary:Ee.grayDark,secondary2:Ee.grayLight,gray:Ee.gray,green:Ee.green,yellow:Ee.yellow,red:Ee.red}});var b,hn,$r=h(()=>{"use strict";Ae();b={red:Ee.red,yellow:Ee.yellow,green:Ee.green,blue:Ee.blue,magenta:Ee.magenta,cyan:Ee.cyan},hn={urgent:b.red,critical:b.red,important:b.red,blocker:b.red,asap:b.red,immediate:b.red,fail:b.red,failure:b.red,broken:b.red,bug:b.red,error:b.red,incident:b.red,outage:b.red,production:b.red,crash:b.red,security:b.red,warning:b.yellow,warn:b.yellow,risky:b.yellow,risk:b.yellow,attention:b.yellow,pending:b.yellow,review:b.yellow,"needs-review":b.yellow,qa:b.yellow,testing:b.yellow,test:b.yellow,validate:b.yellow,verification:b.yellow,staging:b.yellow,check:b.yellow,"follow-up":b.yellow,followup:b.yellow,waiting:b.yellow,blocked:b.yellow,hold:b.yellow,done:b.green,complete:b.green,completed:b.green,success:b.green,ok:b.green,stable:b.green,resolved:b.green,fixed:b.green,closed:b.green,merged:b.green,released:b.green,deployed:b.green,approved:b.green,verified:b.green,working:b.green,healthy:b.green,pass:b.green,passing:b.green,info:b.blue,information:b.blue,note:b.blue,docs:b.blue,documentation:b.blue,doc:b.blue,guide:b.blue,help:b.blue,explanation:b.blue,detail:b.blue,details:b.blue,context:b.blue,design:b.blue,discussion:b.blue,proposal:b.blue,idea:b.blue,feature:b.magenta,enhancement:b.magenta,improvement:b.magenta,refactor:b.magenta,refactoring:b.magenta,cleanup:b.magenta,optimize:b.magenta,optimization:b.magenta,perf:b.magenta,performance:b.magenta,upgrade:b.magenta,migration:b.magenta,modernize:b.magenta,debt:b.magenta,todo:b.cyan,next:b.cyan,planned:b.cyan,plan:b.cyan,future:b.cyan,backlog:b.cyan,investigate:b.cyan,explore:b.cyan,prototype:b.cyan}});import ea from"chalk";var ts,ta,es,na,Pu,Du,ra,Fu,Bu,Jn,Me,oa,sa,jr,Ou,Uu,Wr,gt=h(()=>{"use strict";$r();ts={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ta=(e,t,n)=>Math.max(t,Math.min(n,e)),es=(e,t,n)=>e+(t-e)*n,na=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Pu=e=>e.toLowerCase().trim(),Du=(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)]},ra=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Fu=(e,t,n)=>{let r=ta(n,0,1);return[Math.round(es(e[0],t[0],r)),Math.round(es(e[1],t[1],r)),Math.round(es(e[2],t[2],r))]},Bu=(e,t,n)=>Fu(e,t,n),Jn=e=>{let n=na(e)%360,r=Du(n,ts.stringColor.saturation,ts.stringColor.lightness);return ra(r)},Me=(e,t=hn)=>{let n=Pu(e);return n&&t[n]?t[n]:Jn(n)},oa=e=>{let t=ts.gradient.stops,n=ta(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 Bu(t[s],t[s+1],d)},sa=e=>ra(oa(e)),jr=e=>na(e.toLowerCase().trim())/4294967295,Ou=e=>{let t=jr(e);return oa(t)},Uu=e=>{let[t,n,r]=Ou(e);return{normal:o=>ea.bgRgb(t,n,r).black(o),cursor:o=>ea.bgRgb(t,n,r).white.bold(o)}},Wr=e=>Uu(e).normal(` ${e} `)});import{decodeTime as ia}from"ulid";var xn,aa,In,qt=h(()=>{"use strict";C();xn=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"},aa=e=>{try{return c("Decoded date",new Date(ia(e)))}catch(t){return i("Decoding failed + "+t.message)}},In=e=>{if(!e?.id)return null;try{return ia(e.id)}catch{return null}}});import St from"chalk";import da from"string-width";import{decodeTime as _u}from"ulid";var $u,ju,ca,Wu,Hu,la,ua,Ku,Vu,zu,qu,Gu,ma,pa,ns=h(()=>{"use strict";ae();T();gt();qt();$u=(e,t)=>e+" ".repeat(Math.max(0,t-da(e))),ju=(e,t)=>" ".repeat(Math.max(0,t-da(e)))+e,ca=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","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),Wu=(e,t)=>t?e<t?"up":e>t?"down":null:null,Hu=(e,t)=>{let n=x.getNode(e.payload.parent),r=n?St.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=Wu(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},la=e=>`${Math.max(1,Math.round(e/1024))} KB`,ua=e=>x.getAttachment(e)?.name??"",Ku=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?St.bgHex(Me(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?St.bgHex(Me(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?St.hex(Me(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?St.hex(Me(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:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${St.dim(`(${la(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=ua(e.payload.id);return t?`"${t}"`:""}default:return""}},Vu=e=>{let t=xn(_u(e));return St.gray(ju(t,8))},zu=12,qu=e=>$u(`${e}`,zu),Gu=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=x.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${la(e.payload.bytes)})`;case"delete.issue.attachment":{let t=ua(e.payload.id);return t?`"${t}"`:""}default:return""}},ma=e=>[ca(e.action),Gu(e)].filter(Boolean).join(" "),pa=(e,t)=>{let n=Vu(e.id),r=qu(e.userName),o=St.dim("\u203A"),s=e.action==="move.node"?Hu(e,t):[ca(e.action),Ku(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`}});import{createHash as Yu}from"node:crypto";var Xu,Ju,ye,bn=h(()=>{"use strict";Xu="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ju=e=>{let t=Yu("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},ye=(e,t)=>Ju(`${e}:virtual:${t}`)});var Qu,Zu,em,tm,nm,rm,Hr,ga,fa,om,va=h(()=>{"use strict";ns();te();C();vn();ae();zt();T();fn();bn();Qu=e=>ye(e,"comments"),Zu=e=>ye(e,"description"),em=e=>ye(e,"assignees"),tm=e=>ye(e,"tags"),nm=e=>ye(e,"history"),rm=e=>ye(e,"attachments"),Hr=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:d="horizontal"})=>{let l=x.getNode(e);if(!l){let p=x.createNode({...ve.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(!De(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=x.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)},ga=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let d=x.getNode(e);if(!d){let m=x.createNode({...ve.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(!qn(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=x.updateNode({...d,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(u)?u:c("Virtual field list updated",void 0)},fa=e=>{let t=Fe(Qe/4n),n=Fe(Qe/2n),r=Fe(Qe*3n/4n),o=Fe(Qe*7n/8n),s=Fe(Qe*15n/16n),d=Fe(Qe*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;if(a(d))return d;let l=Hr({id:Zu(e.id),name:z.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(l))return l;let u=ga({id:em(e.id),name:z.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(u))return u;let m=ga({id:tm(e.id),name:z.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(a(m))return m;let p=Hr({id:Qu(e.id),name:z.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(p))return p;let y=Hr({id:rm(e.id),name:z.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(y))return y;let N=Hr({id:nm(e.id),name:z.HISTORY,parentNodeId:e.id,rank:d.value,value:om(e),readonly:!0,childRenderAxis:"vertical"});return a(N)?N:c("Ticket virtual nodes materialized",void 0)},om=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=>pa(r,n.get(r.action)??[])).join(`
41
- `)}});var sm,ue,Kr,En=h(()=>{"use strict";sm=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ue,Kr]=sm});function Rt(e,t=!1){let n=mm[e.action];if(!n)return i(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);let r=n(e);if(a(r))return r;let o=um(e,t);return o||r}var k,ya,im,am,dm,rs,cm,lm,um,mm,At,Tt=h(()=>{"use strict";te();C();vn();ae();zt();T();va();En();k=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),ya=e=>{let t=x.getNode(e);if(!t||!w(t)||t.isDeleted)return null;let n=fa(t);return a(n)?n:null},im=e=>{for(let t of e){let n=ya(t);if(n)return n;let r=g().nodes[t]?.parentNodeId;if(!r)continue;let o=ya(r);if(o)return o}return null},am=(e,t)=>{let n=x.getNode(e);n&&x.updateNode({...n,log:[...n.log??[],t]})},dm=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},rs=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":case"add.issue.attachment":case"delete.issue.attachment":return[e.payload.issue];case"delete.node":case"edit.description":return dm(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[]}},cm=e=>{fe(t=>({...t,eventLog:[...t.eventLog,e]}))},lm=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?k("Invalid user ID format",e):c("Valid user",null)},um=(e,t)=>{let n=lm(e);if(a(n))return n;let r=[...new Set(rs(e))];t||(r.forEach(s=>am(s,e)),cm(e));let o=im(r);return o||null},mm={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=ve.workspace(t,n,r),s=Qn(o);if(a(s))return k(s.message,e);let d=x.createNode(o);return a(d)?k(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=x.createNode(ve.workspace(t,n,r));return a(o)?k(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=x.createNode(ve.board(t,n,r,o));return a(s)?k(s.message??"Unable to create board",e):Qo(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=x.createNode(ve.swimlane(t,n,r,o));return a(s)?k(s.message??"Unable to create swimlane",e):Gn(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=x.createNode(ve.ticket(t,n,r,o));return a(s)?k(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=x.createNode(ve.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(z.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?k(d.message??`Unable to create field: ${n}`,e):De(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(!x.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=x.renameNode(t,n);return a(o)?k(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=x.tombstoneNode(t);return a(n)?k(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=x.createTag({id:t,name:n});return a(r)?k(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=x.createContributor({id:t,name:n});return a(r)?k(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=x.tag(t,n);return a(r)?k(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=x.untag(t,n);return a(r)?k(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=x.assign(t,n);return a(r)?k(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=x.unassign(t,n);return a(r)?k(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=x.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?k(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=x.editValue(t,n);return a(r)?k(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=x.getNode(t);if(!o)return k("Unable to locate issue",e);if(!w(o))return k("Can only close issues",e);let s=x.getNode(ue);if(!s)return k("Unable to locate target swimlane",e);if(n!==s.id)return k("Close target must be closed swimlane",e);let d=x.moveNodeToRank({id:t,parentId:n,rank:r});return a(d)?k(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=x.getNode(t);if(!o)return k("Unable to locate issue",e);if(!w(o))return k("Can only reopen issues",e);let s=x.getNode(ue);if(!s)return k("Unable to locate closed swimlane",e);if(n===s.id)return k("Cannot reopen issue into closed swimlane",e);if(!x.getNode(n))return k("Reopen parent no longer exists",e);let l=x.moveNodeToRank({id:t,parentId:n,rank:r});return a(l)?k(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=x.lockNode(t);return a(n)?k(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=x.getNode(r);if(!s)return k(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return k(`Node ${r} is not child of ${t}`,e);let d=x.updateNode({...s,rank:o});if(a(d))return k(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=x.createComment({id:t,issue:n,authorId:r,authorName:x.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return a(s)?k(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=x.getComment(t);if(!o)return k("Unable to locate comment",e);if(o.issue!==n)return k("Comment does not belong to issue",e);let s=x.editComment(t,r);return a(s)?k(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=x.getComment(t);if(!r)return k("Unable to locate comment",e);if(r.issue!==n)return k("Comment does not belong to issue",e);let o=x.deleteComment(t);return a(o)?k(o.message??"Unable to delete comment",e):c("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:r,ext:o,name:s,bytes:d}=e.payload,l=x.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:d,deleted:!1});return a(l)?k(l.message??"Unable to add attachment",e):c("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=x.getAttachment(t);if(!r)return k("Unable to locate attachment",e);if(r.issue!==n)return k("Attachment does not belong to issue",e);let o=x.deleteAttachment(t);return a(o)?k(o.message??"Unable to delete attachment",e):c("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=x.linkUserId({contributorId:t,userId:e.userId});return a(n)?k(n.message??"Unable to link contributor",e):c("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};At=e=>e.map(t=>Rt(t))});var pm,gm,ha,xa,os=h(()=>{"use strict";pm=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","create.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","move.node","edit.description","add.issue.comment","edit.issue.comment","delete.issue.comment","add.issue.attachment","delete.issue.attachment","close.issue","reopen.issue","lock.node","rebalance.children","link.contributor.user"],gm=new Set(pm),ha=e=>gm.has(e),xa=e=>({action:e.action,payload:e.payload})});import Vr from"node:fs";import is from"node:path";import{decodeTime as fm}from"ulid";import{z as ss}from"zod";function ds(e){let t=_n(e);if(!Vr.existsSync(t))return c("No events found",[]);let n=Vr.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>is.join(t,o)),r=[];for(let o of n){let s=Em(o);if(a(s))return i(s.message);r.push(...s.value)}return c("All events loaded",Nm(r))}function Gt(e){let t=ds(e);return a(t)?i(t.message):as(t.value)}function Ia(e,t){let n=ds(e);if(a(n))return i(n.message);let{appliedEvents:r,unappliedEvents:o}=Cm(n.value,t),s=as(r);if(a(s))return i(s.message);let d=as(o);return a(d)?i(d.message):c("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function ba(e=process.cwd()){let t=ds(e);return a(t)?i(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var vm,ym,hm,xm,Im,bm,as,Em,Nm,Cm,Nn=h(()=>{"use strict";ln();C();ce();os();et();vm=ss.object({userId:ss.string().min(1).default("unknown"),userName:ss.string().min(1).default("unknown")}),ym=e=>{let[t,n]=is.basename(e,".jsonl").split("."),r=vm.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):i(`Invalid event file name ${is.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},hm=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])},xm=(e,t)=>t in e,Im=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),bm=e=>{let{userId:t,userName:n,...r}=e,o=hm(r);if(a(o))return i(o.message);let s=o.value,d=e.id?.[0];return d?xm(r,s)?c("Decoded persisted event",Im({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")},as=e=>{let t=[],n=new Map;for(let r of e){let o=bm(r);if(a(o))return i(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);let s=o.value.action;if(!ha(s)){n.set(s,(n.get(s)??0)+1);continue}t.push(o.value)}if(n.size>0){let r=[...n.entries()].map(([o,s])=>`${o} (x${s})`).join(", ");le.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${r}. Upgrade to apply them.`)}return c("Decoded reconstructed events",t)},Em=e=>{if(!Vr.existsSync(e))return c("Event file missing",[]);let t=ym(e);if(a(t))return i(t.message);let n=Vr.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
42
- `)){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=cs(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)};Nm=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},Cm=(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=fm(d)<t}catch{u=!1}!u||l&&n.has(l)?(n.add(d),o.push(s)):r.push(s)}return{appliedEvents:r,unappliedEvents:o}}});import Sm from"node:fs";import Rm from"node:path";import{decodeTime as Am,monotonicFactory as Tm}from"ulid";import{z as Zn}from"zod";function zr({event:e,rootDir:t}){try{let n=mi(t);if(a(n))return n;let r=Pm(t,{userId:e.userId,userName:e.userName});if(a(r))return r;let o=ba(t);if(a(o))return i(o.message);let s=o.value?Ea(Math.max(Date.now(),Am(o.value)+1)):Ea(),d=Dm(xa(e),[s,o.value]);return a(d)?i(d.message):(Sm.appendFileSync(r.value,`${JSON.stringify(d.value)}
43
- `,"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 Ca,Ea,wm,Mm,cs,Na,Lm,km,re,Yt,Pm,Dm,et=h(()=>{"use strict";C();Re();ce();Nn();os();Ca=1,Ea=Tm(),wm=Zn.tuple([Zn.string().min(1),Zn.string().min(1).nullable()]),Mm=Zn.looseObject({v:Zn.literal(Ca),id:wm}),cs=e=>{let t=Mm.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(", ")}`)},Na=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",Lm=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),km=e=>e.trim().length>0&&e.length<=80,re=()=>{let{userName:e,userId:t}=ne();return e?t?Lm(t)?km(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")},Yt=({userId:e,userName:t})=>`${Na(e)}.${Na(t)}.jsonl`,Pm=(e,{userId:t,userName:n})=>{let r=Yt({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return i(`Invalid event log file name: ${r}`);let s=Rm.join(_n(e),r);return c("Successfully resolved event log path",s)},Dm=(e,t)=>{let n={[e.action]:e.payload,v:Ca,id:t};return cs(n)}});import{ulid as Fm}from"ulid";function Sa(e,t){let n=Rt(e);if(n.status!==Et.Success)return n;let r=zr({event:e,rootDir:t});return a(r)?r:n}function O(e,t){if(e.length===0||!e[0])return i("No events provided");let n=Bm(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 Bm,Xt=h(()=>{"use strict";C();ae();Tt();et();Bm=(e,t)=>{if(e.action==="create.contributor")return c("Contributor already being created",void 0);if(x.getContributor(e.userId))return c("Contributor exists",void 0);let n={id:Fm(),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 Ra,qr,Q,Aa,Ta,Jt,Cn,at=h(()=>{"use strict";Qi();Xt();C();T();fn();Ra=e=>qr(Q(e),{at:"end"}),qr=(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(we(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(we(void 0,r.rank)):i("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(we(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(we(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(we(o.rank,s?.rank)):i("Sibling not found")}}},Q=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),Ta=(e,t,n={at:"end"})=>qr(Q(t).filter(r=>r.id!==e),n),Jt=(e,t,n,r,o)=>{let s=Ta(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return c("Resolved rank",s.value.rank);let d=Zo(e,r);if(a(d))return d;let l=O([d.value],o);if(a(l))return l;let u=Ta(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=Ra(e);if(a(r))return r;if(!r.value.needsRebalance)return c("Resolved rank",r.value.rank);let o=Zo(e,t);if(a(o))return o;let s=O([o.value],n);if(a(s))return s;let d=Ra(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,wa,Ma,Be=h(()=>{"use strict";T();P={exit(){process.exit(0)},enterChildNode(){let e=g(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=q(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||P.navigate({contextNode:o,selectedIndex:q(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=q(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:()=>wa(1),navigateToPreviousItem:()=>wa(-1),navigateToNextContainer:()=>Ma(1),navigateToPreviousContainer:()=>Ma(-1),navigate:({contextNode:e,selectedIndex:t})=>{I({contextNodeId:e.id,selectedIndex:t})}},wa=e=>{let{selectedIndex:t,contextNode:n}=g(),r=q(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;P.navigate({selectedIndex:s,contextNode:n})},Ma=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=q(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=q(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 ka,Pa,Om,Gr,Da,La,Um,Fa,Ba=h(()=>{"use strict";te();C();at();T();Be();ka=(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}},Om=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&De(t)&&t.childRenderAxis==="vertical"},Gr=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r||r.isDeleted)return!1;let o=Q(r.id);return P.navigate({contextNode:r,selectedIndex:ka(t,o.length)}),!0},Da=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Gr(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let d=Q(o.id).findIndex(l=>l.id===n.id);return d>=0?(P.navigate({contextNode:o,selectedIndex:d}),!0):Da(o.id)},La=e=>{let{nodes:t}=g(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Da(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(Om(e.contextNodeId)&&Gr(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(Um(e.selectedNodeId)&&e.selectedNodeId&&La(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(Gr(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&Gr(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(La(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=Q(r.id);return P.navigate({contextNode:r,selectedIndex:ka(e.selectedIndex,o.length)}),c("Restored navigation to root",null)}});import{monotonicFactory as _m,ulid as ft}from"ulid";function $m(){let e=qe();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]=q(n.id),[o]=r?q(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 jm(){let e=$m();return a(e)?e:P.navigate(e.value)}function Oa({userId:e,userName:t}){let n=er(),r=er(),o=er(),s=er(),d=er(),l=we(void 0,void 0);if(a(l))return l;let u=we(void 0,void 0);if(a(u))return u;let m=we(u.value,void 0);if(a(m))return m;let p=we(void 0,void 0);if(a(p))return p;let y=we(p.value,void 0);if(a(y))return y;let N=we(y.value,void 0);if(a(N))return N;let R=we(void 0,void 0);return a(R)?R:c("Created default events",[{id:ft(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:ft(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:y.value}},{id:ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:r,rank:N.value}},{id:ft(),userId:e,userName:t,action:"add.board",payload:{id:Kr,name:"Closed",parent:n,rank:m.value}},{id:ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:ue,name:"Closed",parent:Kr,rank:R.value}},{id:ft(),userId:e,userName:t,action:"lock.node",payload:{id:Kr}},{id:ft(),userId:e,userName:t,action:"lock.node",payload:{id:ue}}])}function tr(e){if(!e.length){let r=ve.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=Qn(r);return a(o)?o:(I({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=At(e).filter(a);return n.length>0?i(`Materializing failed:
44
- ${n.map(r=>r.message).join(`
45
- `)}`):(jm(),I({hasProjectDefinition:!0}),c("State booted successfully",null))}var er,Yr=h(()=>{"use strict";Be();J();C();zt();T();fn();Tt();En();er=_m()});var K,ls=h(()=>{"use strict";C();K=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});var dt,Xr,Wm,Ua,us=h(()=>{"use strict";Ba();Yr();Nn();et();J();C();T();Jr();ls();ms();dt=null,Xr=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!dt,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),dt)return logger.debug("[sync] syncAndReloadState joining existing promise"),dt;logger.debug("[sync] syncAndReloadState creating promise"),dt=Wm();try{let e=await dt;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"),I({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}),dt||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),dt=null}},Wm=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=Ua();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(dt)return dt;logger.debug("[sync] syncAndReloadState:start");let t=K("resolveActorId",re());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");I({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:g().syncStatus});let n=Yt(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=K("syncEpiqWithRemote",await Qr({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),I({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),Ge(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let s=K("loadMergedEvents",Gt(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 I({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=Ua();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=K("bootStateFromEventLog",tr(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(p),message:(a(p),p.message)}),a(p))return I({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"),I({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=K("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)?(I({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),m):(I({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),c("Synced",!0))},Ua=()=>g().mode===f.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),I({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),i("Will not re-materialize if not in default mode, to not lose edit data"))});var Sn,_a,$a,ps,gs,nr,fs,Hm,ja,Km,Wa,Zr=h(()=>{"use strict";C();Re();T();us();Sn=3e3,_a=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Sn?null:t},$a=0,gs=!1,nr=!1,fs=()=>{if(gs)return!0;let e=qe();return a(e)?!1:e.value.syncStatus.status==="syncing"},Hm=()=>{let e=ne().autoSyncIntervalMs??1e4,t=Date.now()-$a;return Math.max(0,e-t)},ja=()=>{ps||(ps=setTimeout(async()=>{if(ps=void 0,!!Rn()){if(fs()){nr=!0;return}nr=!1,await Km()}},Hm()))},Km=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return i("Cannot auto-sync while peeking");if(!Rn())return i("Cannot auto-sync before state is initialized");if(fs())return nr=!0,i("Sync already in progress");gs=!0,$a=Date.now(),I({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Xr()}finally{gs=!1,nr&&ja()}},Wa=()=>{Rn()&&(nr=!0,!fs()&&ja())}});var eo,Ha,Ka,Va,rr=h(()=>{"use strict";C();$t();Re();ce();eo=()=>{let e=ne(),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}},Ha=()=>{let e=rt(process.cwd());if(a(e))return!1;let t=Nt(e.value);return mt(t)},Ka=e=>e===!0?"on":e===!1?"off":null,Va=e=>e==="on"?!0:e==="off"?!1:null});var Vm,zm,wt,Mt,to,no,or=h(()=>{"use strict";te();C();ae();T();Vm=e=>e.props.tags??[],zm=e=>e.props.assignees??[],wt=e=>Vm(e).map(t=>x.getTag(t)).filter(t=>!!t),Mt=e=>zm(e).map(t=>x.getContributor(t)).filter(t=>!!t),to=()=>{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",wt(n))},no=()=>{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",Mt(n))}});var v,Qt=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 qm,Gm,Ym,Xm,Jm,Zt,za,ro,oo,qa,Qm,vs,sr=h(()=>{"use strict";qm=/^(\d+)(h|d|w|mo|y)$/,Gm=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Ym=({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},Xm=(e,t=new Date)=>{let n=e.match(qm);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}},Jm=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,y=d?Number(d):0;return Ym({year:l,month:u,day:m,hour:p,minute:y})?new Date(l,u-1,m,p,y):null},Zt=e=>{let t=e.trim().toLowerCase();return Xm(t)??Jm(t)},za=/^(\d+)(s|m)?$/,ro=e=>{let t=e.trim().toLowerCase().match(za);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},oo=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&za.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},qa=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Qm=[{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}],vs=(e=Qm)=>{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 Zm,Z,Oe,me,ep,tp,hs,xs,Xa,en,so,ys,Ga,np,rp,ir,Ya,op,sp,ip,de,Lt=h(()=>{"use strict";Zr();rr();En();te();ae();T();$r();or();Qt();sr();Zm=["BOARD","TICKET","SWIMLANE","COMMENT"],Z={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},Oe={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},me={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},ep=[Z.EDITOR,Z.VIEW,Z.USERNAME,Z.AUTOSYNC,Z.SYNC_DEBOUNCE_MS,Z.ATTACHMENT_MAX_KB,Z.LOG_LEVEL],tp=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[Oe.TITLE,Oe.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Oe.TITLE];case"COMMENT":return[Oe.COMMENT];default:return[]}},hs=[String(Sn),"5000","15000","30000","60000"],xs=["250","500","1000"],Xa=["10s","20s","30s","45s"],en=[v.COFFEE,v.EXIT,v.SYNC,v.HELP,v.EXPORT,v.CONFIG,v.YANK],so=[v.NEW,v.EDIT,v.DELETE,v.MOVE],ys=[v.TAG,v.UNTAG,v.ASSIGN,v.UNASSIGN,v.CLOSE_ISSUE,v.RE_OPEN_ISSUE,v.EDIT,v.COMMENT],Ga=[v.FILTER,v.PEEK,v.REPLAY],np={WORKSPACE:[...en,...so],BOARD:[...Ga,...en,...so],SWIMLANE:[...Ga,...en,...so],TICKET:[...en,...so,...ys],FIELD:[...en,...ys],FIELD_LIST:[...en,...ys],TEXT:[...en],COMMENT:[v.EDIT,v.DELETE,v.YANK]},rp=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],ir=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&w(n)),Ya=e=>e.parentNodeId===ue,op=({selectedNode:e,breadCrumb:t})=>{let n=tp(e?.context);return ir({breadCrumb:t,selectedNode:e})?n.includes(Oe.DESCRIPTION)?n:[...n,Oe.DESCRIPTION]:n},sp=({selectedNode:e,breadCrumb:t})=>{let n=ir({breadCrumb:t,selectedNode:e});return n?[me.REF,me.TITLE,...n.props?.description?.trim()?[me.DESCRIPTION]:[],...wt(n).length>0?[me.TAGS]:[],...Mt(n).length>0?[me.ASSIGNEES]:[]]:e?[me.REF,me.TITLE]:[]},ip=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=eo();if(!r)return[v.HELP,v.CONFIG];if(!Ha())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&&Zm.includes(o),d=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?np[u]:[]))],l=ir({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&&wt(l).length>0):u===v.UNASSIGN?!!(l&&Mt(l).length>0):u===v.RE_OPEN_ISSUE?!!(l&&Ya(l)):u===v.CLOSE_ISSUE?!!(l&&!Ya(l)):!0)},de=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=g())=>{let s=t.context??"WORKSPACE";return{[v.NONE]:ip({breadCrumb:o,readOnly:r,selectedNode:n}),[v.EXIT]:["confirm"],[v.EXPORT]:[],[v.SYNC]:[],[v.INIT]:[],[v.HELP]:[],[v.PEEK]:[...vs(),"now","prev","next"],[v.REPLAY]:[...vs()],[v.EDIT]:op({selectedNode:n,breadCrumb:o}),[v.YANK]:sp({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(hn),...x.getExistingTags()])],[v.UNTAG]:[...to()?.value?.map(({name:l})=>l)??[]],[v.UNASSIGN]:[...no()?.value?.map(({name:l})=>l)??[]],[v.ASSIGN]:x.getExistingAssignees(),[v.NEW]:rp(s),[v.CONFIG]:[...ep],[v.COFFEE]:["1","3","5","20","custom"]}[e]??[]}});var Ja,Qa=h(()=>{"use strict";Ja=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});var Ue,kt=h(()=>{"use strict";C();Ue=(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{accessSync as ap,copyFileSync as dp,existsSync as io,mkdirSync as Za,readdirSync as ed,readFileSync as cp,renameSync as lp,rmSync as up,statSync as td,unlinkSync as mp,writeFileSync as pp}from"node:fs";import An from"node:path";var Is,_e,bs=h(()=>{"use strict";Is=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",_e={writeToFile:(e,t)=>{try{let n=An.dirname(e);io(n)||Za(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);pp(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return cp(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=_e.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 io(e)&&td(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await ap(e),!0}catch{return!1}},mkDir:e=>Za(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=An.parse(t);for(;;){let r=An.join(t,e);try{if(io(r)&&td(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=An.dirname(t)}return null},readFirstJSON(e){try{if(!_e.dirExists(e))return null;let t=ed(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=An.join(e,t);return _e.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return _e.dirExists(e)?ed(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{mp(e)}catch(t){(!Is(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{up(e,{recursive:!0,force:!0})}catch(t){(!Is(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(An.dirname(t)),!n?.overwrite&&io(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{lp(e,t)}catch(r){if(Is(r)&&r.code==="EXDEV"){dp(e,t),this.rmFile(e);return}throw r}}}});import gp from"node:os";import nd from"node:path";import{z as vt}from"zod";var fp,rd,vp,od,Es,Ns,yp,sd,id,Ye,ad,tn=h(()=>{"use strict";ce();C();bs();fp={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},rd=vt.object({logLevel:vt.enum(["info","error","debug"]),preferredEditor:vt.string().optional(),userName:vt.string().optional(),userId:vt.string().optional(),autoSync:vt.boolean().nullable().optional(),autoSyncDebounceMs:vt.number().optional(),attachmentMaxKb:vt.number().optional(),viewMode:vt.enum(["dense","wide"]).optional()}).partial(),vp="config.json",od=()=>nd.join(gp.homedir(),Ke),Es=()=>nd.join(od(),vp),Ns=()=>{try{return _e.mkDir(od()),c(`Ensured ~/${Ke} exists`,null)}catch{return i(`Unable to create ~/${Ke}`)}},yp=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${Ke}/config.json JSON`)}let n=rd.safeParse(t??{});return n.success?c("Parsed config",n.data):i(`Invalid ~/${Ke}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},sd=()=>{let e=Ns();if(a(e))return i(e.message);let t=Es(),n=_e.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):yp(n)},id=e=>{let t=Ns();if(a(t))return i(t.message);let n=rd.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Es();try{return _e.writeToFile(r,JSON.stringify(n.data,null,2)+`
46
- `),c("Config written",null)}catch{return i(`Unable to write ~/${Ke}/config.json`)}},Ye=e=>{let t=sd();if(a(t))return i("Failed to read existing config");let n={...t.value,...e};return id(n)},ad=()=>{let e=Es(),t=Ns();if(a(t))return i(`Unable to create ~/${Ke}`);if(!(_e.readFile(e)!==null)){let N=id(fp);if(a(N))throw new Error(`Unable to create ~/${Ke}/config.json`)}let r=sd();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:d,autoSync:l,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:y}=r.value;return!s||!d?i(`User name or ID not configured in ~/${Ke}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,c("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:s,userId:d,autoSync:l??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:y??"dense"}))}});var ar,Cs,dr=h(()=>{"use strict";kt();C();ce();ar=500,Cs=(e,t)=>`${e}.${t}`});import hp from"zod";var cr,lr,dd,Ss=h(()=>{"use strict";tn();dr();J();C();pe();Re();T();cr=50,lr=5e3,dd=()=>{let e=G().commandMeta.inputString,t=hp.coerce.number().int().min(cr).max(lr).safeParse(e);if(!t.success)return i(`Attachment size cap must be ${cr}-${lr} KB (default ${ar})`);let n=Ye({attachmentMaxKb:t.data});return a(n)?n:(ze({attachmentMaxKb:t.data}),I({mode:f.DEFAULT}),c(`Attachment size cap set to ${t.data} KB`,null))}});import cd from"chalk";var Y,he,xe,ld=h(()=>{"use strict";gt();Ae();Y=e=>cd.dim(e),he=e=>cd.hex(E.primary)(e),xe=({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)=>jr(y)-jr(N)).slice(0,r).map(y=>Wr(y)).join(" ");return p?`${Y(e)}${p}${Y(n)}`:""}});var Pt,ao=h(()=>{"use strict";Pt={None:"none",Invalid:"invalid",Valid:"valid"}});import pd from"chalk";var Tn,xp,ud,ee,W,F,lo,md,co,Rs,Ip,nn,bp,Ep,Np,Cp,gd,As=h(()=>{"use strict";Zr();rr();Qa();qt();kt();C();ae();Re();Ss();dr();T();gt();or();bn();ld();Qt();ao();Lt();sr();Tn=140,xp=["BOARD","TICKET","SWIMLANE"],ud=()=>{let e=g().selectedNode;if(!e?.context)return F({message:Y("Missing target context")});if(xp.includes(e.context))return W();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===ye(t?.parentNodeId??"","comments"))return W()}return F({message:Y("Command not available in this context")})},ee="<ENTER> to confirm",W=(e="",t=[])=>({message:Y(e),validity:Pt.Valid,completionWordList:t}),F=({message:e,completionWordList:t=[]})=>({validity:Pt.Invalid,message:e,completionWordList:t}),lo=e=>e.length===0,md=(e,t)=>{let n=Ue(g().breadCrumb,"BOARD");if(a(n))return F({message:he("Command is not applicable in this context")});let r=aa(n.value.id);return a(r)?F({message:he(`Unable to ${t}: board id is not a valid ULID`)}):qa({date:e,horizonDate:r.value})?null:F({message:he(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},co=e=>` ${pd.hex("#000").bgHex(Me(e))(` ${e} `)} `,Rs=({modifier:e})=>{let t="confirm";return e===t?W(ee):F({message:lo(e)?Y("if you are certain, enter ")+Wr(t):"",completionWordList:[t]})},Ip=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?F({message:Y(n)}):W():F({message:lo(r)?t:"",completionWordList:[...e]}),nn=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>lo(n)&&lo(r)?F({message:e,completionWordList:[]}):W(t??ee),bp=({modifier:e,inputString:t})=>{let n=de(v.CONFIG);if(!n.includes(e))return F({message:xe({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case Z.EDITOR:{let r=[...Ja];return t.trim()?r.includes(t.trim())?W(ee):F({message:xe({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):F({message:xe({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case Z.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?W(ee):F({message:xe({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case Z.USERNAME:return t.trim()?W(ee):F({message:he("Enter a user name. Saved in ")+pd.bgBlack("~/.epiq-global/config.json")});case Z.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?W(ee):F({message:xe({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case Z.AUTOSYNC:{let r=["on","off"],o=ne().autoSync;if(!r.includes(t.trim())){let s=Ka(o);return F({message:xe({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return W(ee)}case Z.ATTACHMENT_MAX_KB:{let r=ne().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<cr||o>lr){let s=xe({prefix:" examples: ",wordList:xs,minLengthForHints:0,inputString:t});return F({message:he(`provide a size cap in KB (${cr}-${lr}). current: ${r??ar} KB.`)+s,completionWordList:xs})}return W(ee)}case Z.SYNC_DEBOUNCE_MS:{let r=ne().autoSyncIntervalMs,o=_a(t);if(!t.trim()||o===null||o<Sn){let s=xe({prefix:" examples: ",wordList:hs,minLengthForHints:0,inputString:t});return F({message:he(`provide duration above ${Sn}ms. current duration: ${r}ms.`)+s,completionWordList:hs})}return W(ee)}default:return F({message:he("Unknown config option"),completionWordList:n})}},Ep=({modifier:e,inputString:t})=>{let n=de(v.EDIT);if(!n.length)return F({message:he("Command not available in this context")});if(!n.includes(e)){let r=xe({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return F({message:r||he("Unknown edit option"),completionWordList:n})}switch(e){case Oe.COMMENT:return t.trim()?W(ee):F({message:Y("write a comment...")});case Oe.TITLE:return W(ee);case Oe.DESCRIPTION:{let{preferredEditor:r}=ne();return r?W(Y("<ENTER> to edit in ")+r):F({message:"No editor selected"})}default:return F({message:he("Unknown edit option"),completionWordList:n})}},Np=({modifier:e})=>{let t=de(v.YANK);return t.length?t.includes(e)?W(ee+Y(" and copy to clipboard")):F({message:xe({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):F({message:he("Nothing selected to copy from")})},Cp={[v.EXPORT]:()=>W(ee+Y(", and create export markdown file")),[v.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return W(ee);let n={message:Y("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Zt(r);if(!r||!o)return F(n);let s=md(o,"peek");return s||W(ee)},[v.REPLAY]:e=>{let{dateInput:t,durationInput:n}=oo(e.modifier,e.inputString),r={message:Y("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Zt(t);if(!t||!o)return F(r);let s=md(o,"replay");return s||(n&&ro(n)===null?F({message:he("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):W("<ENTER> to replay board history",n?Xa:[]))},[v.EXIT]:()=>W(ee+Y(" and exit the application")),[v.INIT]:()=>W(ee),[v.PALETTE]:()=>W(ee),[v.FILTER]:e=>{if(e.modifier==="clear")return W(ee);let t=s=>de(v.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return F({message:xe({wordList:de(v.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:de(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())?F({message:xe({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):W():F({message:xe({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[v.NONE]:e=>{let t=de(v.NONE);return F({message:xe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[v.NEW]:e=>Ip({list:de(v.NEW),hint:xe({wordList:de(v.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[v.HELP]:()=>W(ee),[v.EDIT]:Ep,[v.COMMENT]:e=>{let t=nn({hint:Y(`write a comment (max ${Tn} char)...`),onOk:Y(`(${e.inputString.length}/${Tn})`)})(e);return t.validity===Pt.Invalid?t:e.inputString.length>Tn?W(he("max input exceeded")):t},[v.CONFIG]:bp,[v.YANK]:Np,[v.DELETE]:e=>{let t=ud();return t.validity==="invalid"?t:Rs(e)},[v.CLOSE_ISSUE]:e=>Rs(e),[v.RE_OPEN_ISSUE]:e=>Rs(e),[v.MOVE]:e=>{let t=ud();return t.validity==="invalid"?t:nn({hint:xe({prefix:"hey hacker! These commands are blocked for you... ",wordList:de(v.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[v.TAG]:e=>{let n=x.getExistingTags().slice(0,10).map(co).join("");return nn({hint:n.length?Y("create tag or reuse:")+n+Y(""):Y("create tag ...")})(e)},[v.UNTAG]:e=>{let t=to();if(a(t))return F({message:he("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(co).slice(0,10);return n.length?nn({hint:Y(" ... ")+n.join("")})(e):F({message:he("Issue has no tags"),completionWordList:[]})},[v.ASSIGN]:e=>{let t=x.getExistingAssignees().map(co).slice(0,10);return nn({hint:Y("assignees... ")+t.join("")})(e)},[v.UNASSIGN]:e=>{let t=no();if(a(t))return F({message:he("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(co).slice(0,10);return n.length?nn({hint:Y("remove assignee... ")+n.join("")})(e):F({message:he("Issue has no assignees"),completionWordList:[]})},[v.SYNC]:()=>W(ee),[v.COFFEE]:e=>{let{modifier:t}=e,n=de(v.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?F({message:Y("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):nn({hint:xe({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},gd=Object.fromEntries(Object.entries(Cp).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]))});var uo,fd=h(()=>{"use strict";uo=["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 Sp,Rp,Ap,Tp,wp,vd,yd,hd,xd=h(()=>{"use strict";C();T();fd();Sp=3,Rp=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"]),Ap=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},Tp=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=Sp&&!Rp.has(t)&&!/^\d+$/.test(t)),wp=e=>{let t=new Map;for(let s of Ap(e))for(let d of Tp(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=uo.filter(s=>!r.has(s));return[...n,...o]},vd=uo,yd=-1,hd=()=>{let e=qe();if(a(e))return uo;let t=e.value,n=t.eventLog.length;return n!==yd&&(vd=wp(t),yd=n),vd}});var Id,bd,Ts=h(()=>{"use strict";Yi();Lt();Qt();As();xd();T();J();Id=e=>Object.values(v).includes(e),bd=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:d,validity:l,completionWordList:u}=gd[n].validate(n,r,s),m=n!==v.PEEK&&n!==v.REPLAY,p=o==="command"||o==="modifier"?de(n):m?hd():[],{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?Gi(e,R):{hint:"",hints:[],remainder:"",overlap:0}}}});var Ed,Mp,Lp,kp,Nd=h(()=>{"use strict";Ts();Lt();Ed=e=>{let t=e.trimStart(),n=Lp(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),d=kp(e),l=Id(r)?r:null,u=l!==null,m=r!=="",p=l?de(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,D=Mp(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:D}},Mp=(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},Lp=e=>e.trim()?e.trim().split(/\s+/):[],kp=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as Xb}from"react";var wn,ws,Mn,Pp,Cd,ct,ur,Ms,Ls,Sd,Rd,mo,Ad,j,Td,wd,Md,G,Ld,pe=h(()=>{"use strict";Ts();Nd();C();ao();wn=e=>e===ws||e===":",ws=" ",Mn={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Pt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Pp=new Set,Cd=()=>{for(let e of Pp)e()},ct=e=>{let n=e(Mn),r=Ed(n.value),o=n.cursorPosition===n.value.length;Mn={...n,commandMeta:bd(r,o)},Cd()},ur=({message:e,status:t})=>{let n=structuredClone(Mn);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Mn=n,Cd(),c(e,null)},Ms=e=>{ct(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Ls=e=>{ct(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&wn(n[o-1]);)o--;for(;o>0&&!wn(n[o-1]);)o--}else{for(;o<n.length&&!wn(n[o]);)o++;for(;o<n.length&&wn(n[o]);)o++}return{...t,cursorPosition:o}})},Sd=()=>{ct(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}})},Rd=()=>{ct(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&wn(t[r-1]);)r--;for(;r>0&&!wn(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},mo=e=>{ct(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}})},Ad=()=>{ct(e=>({...e,commandIsPending:!0}))},j=e=>{ct(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Td=({addToHistory:e=!0})=>{ct(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},wd=()=>{ct(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}})},Md=()=>{ct(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},G=()=>Mn,Ld=()=>{let[e,...t]=Mn.value.split(ws);return t.join(ws).trim()}});var A,Ht=h(()=>{"use strict";J();ji();T();pe();Re();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 kd,M,ks=h(()=>{"use strict";T();Qt();kd=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 Pd}from"ink";import Dd,{useEffect as Fd,useState as Dp}from"react";var Bd,Le,Ln=h(()=>{"use strict";T();Ae();Bd={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Le=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=ke(),r=Bd[n]??Bd.default,[o,s]=Dp(0);if(Fd(()=>{s(0)},[r]),Fd(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return Dd.createElement(Pd,null,t);let d=r[o]??r[0]??t;return Dd.createElement(Pd,{color:E.accent,dimColor:o===1},d)}});import{Box as Ps,Text as Fp}from"ink";import po from"react";var Dt,mr=h(()=>{"use strict";Ae();Dt=({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,D=s,B=R?Math.max(1,Math.floor(l/e.length*D)):D,$=Math.max(0,D-B),oe=Math.max(1,e.length-l),se=R?Math.floor(p/oe*$):0;return po.createElement(Ps,{flexDirection:"row",height:s,width:"100%"},po.createElement(Ps,{flexDirection:"column",flexGrow:1,height:s},N),po.createElement(Ps,{flexDirection:"column",width:1,height:D},Array.from({length:D}).map((V,He)=>po.createElement(Fp,{key:He,color:R&&He>=se&&He<se+B?E.accent:E.secondary},R?"\u2502":" "))))}});import{Text as Bp}from"ink";import Op from"react";var Up,_p,kn,go=h(()=>{"use strict";$r();gt();ae();Up=e=>e.toLowerCase().trim(),_p=(e,t=hn)=>{let n=Up(e);return t[n]?t[n]:Jn(n)},kn=({id:e,isSelected:t})=>{let n=x.getContributor(e);if(n)return Op.createElement(Bp,{underline:t,color:_p(n.name)},"@"+n.name)}});import{Text as $p}from"ink";import jp from"react";var fo,Ds=h(()=>{"use strict";ae();Ae();gt();fo=({id:e,isSelected:t})=>{let n=x.getTag(e);if(n)return jp.createElement($p,{underline:t,backgroundColor:Me(n.name),color:E.secondary}," "+n.name+" ")}});import{useEffect as Wp,useState as Hp}from"react";var Kp,Od,vo,pr,Vp,zp,Pn,yo=h(()=>{"use strict";gt();Kp=80,Od=1400,vo=new Set,pr=null,Vp=e=>(vo.add(e),pr||(pr=setInterval(()=>{for(let t of vo)t()},Kp)),()=>{vo.delete(e),vo.size===0&&pr&&(clearInterval(pr),pr=null)}),zp=()=>{let e=Date.now()%Od/Od;return e<.5?e*2:(1-e)*2},Pn=e=>{let[,t]=Hp(0);return Wp(()=>{if(e)return Vp(()=>t(n=>n+1))},[e]),sa(zp())}});import{Box as Dn,Text as ho}from"ink";import Xe from"react";var qp,Ud,_d=h(()=>{"use strict";Ae();pn();yn();or();go();Ds();yo();qp=(e,t)=>{if(e.length<=t)return[e,null];let n=e.lastIndexOf(" ",t),r=n>0?n:t;return[e.slice(0,r),Xn(e.slice(r).trim(),t)]},Ud=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Pn(r),s=e-4,[d,l]=qp(Ct(t.title),s),u=l?null:Xn(Ct(t.props.description),s)||null,m=wt(t),p=Mt(t);return Xe.createElement(Dn,{borderStyle:"round",height:5,flexDirection:"column",borderDimColor:!n,borderColor:r?o:n?E.accent:E.secondary,justifyContent:"space-between"},Xe.createElement(Dn,{paddingLeft:1,flexDirection:"column"},Xe.createElement(ho,{color:E.primary},d),l&&Xe.createElement(ho,{color:E.primary},l),u&&Xe.createElement(ho,{color:E.secondary2,dimColor:!0},u)),Xe.createElement(Dn,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1,paddingRight:1},Xe.createElement(Dn,{flexDirection:"row"},m.map(y=>Xe.createElement(Dn,{paddingRight:1,key:y.id},Xe.createElement(fo,{key:y.id,id:y.id}))),p.map(y=>Xe.createElement(Dn,{paddingRight:1,key:y.id},Xe.createElement(kn,{key:y.id,id:y.id})))),Xe.createElement(ho,{wrap:"truncate",color:E.secondary2,dimColor:!0},Ze(t.id))))}});import{Box as rn,Text as gr}from"ink";import $e from"react";var Gp,$d,jd=h(()=>{"use strict";J();ae();Ae();gt();Ln();yo();Gp=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,$d=({width:e,ticket:t,isSelected:n,isFlashing:r=!1,index:o,mode:s})=>{let d=Pn(r),l=(t.props.tags??[]).map(V=>x.getTag(V)).filter(V=>!!V),u=(t.props.assignees??[]).map(V=>x.getContributor(V)).filter(V=>!!V),m=1,p=l.length*(1+m),y=u.length*(2+m),N=l.map(V=>$e.createElement(rn,{key:V.id,paddingRight:m},$e.createElement(gr,{color:Me(V.name)},"\u25A0"))),R=u.map(V=>$e.createElement(rn,{key:V.id,paddingRight:m},$e.createElement(gr,{color:Jn(V.name)},"@"+V.name.at(0)))),D=r?d:n?E.accent:s===f.MOVE?E.secondary:E.primary,B=4,$=x.getCommentsByIssue(t.id),oe=$.length?String($.length).length+2+m:0,se=$.length?$e.createElement(rn,{paddingRight:m},$e.createElement(gr,{color:E.accent},"[",$.length,"]")):null;return $e.createElement(rn,{borderBottom:!0,justifyContent:"space-between"},$e.createElement(rn,null,$e.createElement(rn,{width:B},n?$e.createElement(Le,{isSelected:n}):$e.createElement(gr,{color:"gray",dimColor:!0},o+1)),$e.createElement(gr,{wrap:"truncate",color:D},Gp(t.title,e-p-y-oe-18))),$e.createElement(rn,null,N,R,se))}});import Yp from"chalk";import{Box as Fs,Text as Xp}from"ink";import lt from"react";var Jp,Wd,Hd=h(()=>{"use strict";te();T();Ae();Ln();mr();_d();jd();yo();Jp=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u,replay:m}=ke(),p=u[e.id]??[],y=m?new Set(m.flashNodeIds):null,N=y?.has(e.id)??!1,R=Pn(N),D=`${e.title} ${Yp.hex(E.secondary2).dim("("+p.length+")")}`,B=3,$=o?1:5,oe=s&&d===-1,se=n-(oe?7:5),V=r-B-(o?2:1),He=lt.createElement(Fs,{borderStyle:"round",borderColor:E.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},lt.createElement(Le,{isSelected:t}),lt.createElement(Xp,{bold:!0,color:N?R:t?E.accent:E.primary},D," ",e.readonly?"\u{1F512}":"")),dn=(U,H)=>{let cn=s&&d===H;if(!w(U))return null;let _t=y?.has(U.id)??!1;return o?lt.createElement($d,{key:U.id,index:H,width:n,ticket:U,isSelected:cn,isFlashing:_t,mode:l}):lt.createElement(Ud,{key:U.id,width:se,ticket:U,isSelected:cn,isFlashing:_t})};return lt.createElement(Fs,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?E.accent:E.secondary,paddingRight:1,paddingLeft:1,height:r},He,lt.createElement(Fs,{padding:o?1:0},p.length>0&&lt.createElement(Dt,{selectedIndex:d,height:V,itemHeight:$},p.map(dn)),oe&&lt.createElement(Le,{isSelected:!0})))},Wd=lt.memo(Jp)});var Kd,Vd,Bs=h(()=>{"use strict";zt();Kd=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},Vd=(e,t,n)=>ve.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 Fn,Text as yt}from"ink";import Ne,{useEffect as Qp,useMemo as Zp,useRef as eg}from"react";import{decodeTime as Os}from"ulid";function qd({ticket:e,width:t,height:n}){let r=Zp(()=>ng(e),[e]),o=eg([]);Qp(()=>(zd(o.current),o.current=og(e,r),()=>{zd(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=ke(),l=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?Ne.createElement(Fn,{flexDirection:"column",width:t,height:n,padding:1},Ne.createElement(yt,{color:E.primary},"No attachments yet."),Ne.createElement(Fn,{paddingTop:1},Ne.createElement(yt,{color:E.primary},"Attach images from the browser GUI"),Ne.createElement(yt,{color:E.accent}," epiq gui "),Ne.createElement(yt,{color:E.primary},"by dropping or pasting them."))):Ne.createElement(Fn,{flexDirection:"column",width:t,height:n},Ne.createElement(Fn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:E.secondary,borderStyle:"single",paddingBottom:1},Ne.createElement(yt,{color:E.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),Ne.createElement(Dt,{height:l,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let y=p===s,N=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return Ne.createElement(Fn,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},Ne.createElement(yt,{color:E.accent},y?"\u276F ":" "),Ne.createElement(Fn,{paddingLeft:1},Ne.createElement(yt,{color:E.secondary2},`#${p+1} `),Ne.createElement(yt,{color:y?E.accent:E.primary},N),Ne.createElement(yt,{color:E.secondary2}," "+sg(m.bytes)+" "+xn(Os(m.id)))))})))}var tg,ng,zd,rg,og,sg,Gd=h(()=>{"use strict";Be();qt();te();C();ae();zt();T();Ae();bn();mr();tg=e=>ye(e,"attachments"),ng=e=>x.getAttachmentsByIssue(e.id).sort((t,n)=>Os(t.id)-Os(n.id)),zd=e=>{for(let t of e)x.deleteNode(t.id)},rg=(e,t,n)=>ve.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),og=(e,t)=>{let n=x.getNode(tg(e.id));if(!n||!De(n))return[];let r=t.map((o,s)=>rg(o,s,n.id)).map(o=>x.createNode(o)).filter(mt).map(({value:o})=>o).filter(De);return t.length>0&&g().selectedIndex<0&&P.navigate({contextNode:n,selectedIndex:0}),r},sg=e=>`${Math.max(1,Math.round(e/1024))} KB`});import{Box as Ft,Text as ht}from"ink";import ge,{useEffect as ig,useMemo as ag,useRef as dg}from"react";import{decodeTime as Us}from"ulid";function Xd({ticket:e,width:t,height:n}){let r=ag(()=>lg(e),[e]),o=dg([]);ig(()=>(Yd(o.current),o.current=ug(e,r),()=>{Yd(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=ke(),l=Math.max(1,n-4),u=Math.max(20,t-8);return r.length===0?ge.createElement(Ft,{flexDirection:"column",width:t,height:n,padding:1},ge.createElement(ht,{color:E.primary},"No comments yet."),ge.createElement(Ft,{paddingTop:1},ge.createElement(ht,{color:E.primary},"Use"),ge.createElement(ht,{color:E.accent}," :comment "),ge.createElement(ht,{color:E.primary},"to add the first one."))):ge.createElement(Ft,{flexDirection:"column",width:t,height:n},ge.createElement(Ft,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:E.secondary,borderStyle:"single",paddingBottom:1},ge.createElement(ht,{color:E.secondary2},"Comments (",r.length,") ")),ge.createElement(Dt,{height:l,itemHeight:4,selectedIndex:s},r.map((m,p)=>{let y=p===s;return ge.createElement(Ft,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:E.secondary,borderStyle:"single"},ge.createElement(Ft,{flexDirection:"row",paddingBottom:1},ge.createElement(ht,{color:E.accent},y?"\u276F ":" "),ge.createElement(Ft,{paddingLeft:1},ge.createElement(ht,{color:E.secondary2},`#${p+1} `),ge.createElement(kn,{id:m.authorId}),ge.createElement(ht,{color:E.secondary2}," "+xn(Us(m.id))))),ge.createElement(Ft,{paddingLeft:3,paddingBottom:1},ge.createElement(ht,{color:E.primary},mg(m.md,u))))})))}var cg,lg,Yd,ug,mg,Jd=h(()=>{"use strict";Be();qt();te();C();ae();T();Ae();bn();go();mr();Bs();cg=e=>ye(e,"comments"),lg=e=>x.getCommentsByIssue(e.id).sort((t,n)=>Us(t.id)-Us(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),Yd=e=>{for(let t of e)x.deleteNode(t.id)},ug=(e,t)=>{let n=x.getNode(cg(e.id));if(!n||!De(n))return[];let r=t.map((o,s)=>Vd(o,s,n.id)).map(x.createNode).filter(mt).map(({value:o})=>o).filter(Yn);return t.length>0&&g().selectedIndex<0&&P.navigate({contextNode:n,selectedIndex:0}),r},mg=(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 xo,Text as pg}from"ink";import xt from"react";var Qd,Zd=h(()=>{"use strict";te();ae();vn();T();Ae();go();Ln();Ds();Qd=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=ke(),{title:o}=t,s=t.parentNodeId?x.getNode(t.parentNodeId):void 0,d=s&&w(s)?o===z.ASSIGNEES?s.props.assignees??[]:o===z.TAGS?s.props.tags??[]:[]:[];return xt.createElement(xo,{alignItems:"center",paddingTop:1},xt.createElement(xo,{minWidth:12},xt.createElement(Le,{isSelected:n}),xt.createElement(pg,{color:n?E.accent:E.secondary2},o,":")),xt.createElement(xo,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=r.id===t.id&&u===e;return xt.createElement(xo,{key:`${o}-${l}`,paddingRight:2,minHeight:1},xt.createElement(Le,{isSelected:m}),o===z.ASSIGNEES?xt.createElement(kn,{isSelected:m,id:l}):o===z.TAGS?xt.createElement(fo,{isSelected:m,id:l}):null)})))}});import{Box as Io,Text as _s}from"ink";import It,{useEffect as gg,useMemo as ec}from"react";var fg,tc,$s,nc,vg,js,rc=h(()=>{"use strict";ae();C();zt();T();Ae();pn();Ln();mr();fn();fg="\u2029",tc=(e,t)=>`${e}::inline-line::${t}`,$s=new Map,nc=e=>{let t=$s.get(e)??[];$s.delete(e);for(let n of t)x.deleteNode(n)},vg=(e,t)=>{nc(e);let n=[];t.forEach((r,o)=>{let s=Fe(BigInt(o+1));if(!mt(s))return;let d=x.createNode(ve.text({id:tc(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));mt(d)&&n.push(d.value.id)}),$s.set(e,n)},js=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:d,contextNode:l}=ke(),u=ec(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=ec(()=>u.join("\0"),[u]);gg(()=>(vg(e,u),()=>{nc(e)}),[e,m]);let p=N=>String(N).replace(/\r?\n/g,""),y=u.map((N,R)=>{let D=l.id===e&&d===R;return It.createElement(Io,{key:tc(e,R)},It.createElement(_s,{color:D?E.primary:E.secondary2,dimColor:!D},`${R+1} `.padStart(5,"\xA0")),It.createElement(_s,{backgroundColor:D?"gray":void 0},p(N.length?Xn(N,s-10):fg)))});return It.createElement(Io,{flexDirection:"column",paddingTop:1},It.createElement(Io,null,It.createElement(Le,{isSelected:o}),It.createElement(_s,{color:o?E.accent:E.secondary2},t)),It.createElement(Io,{flexDirection:"row",borderStyle:"round",borderColor:E.secondary,paddingLeft:1,marginLeft:1},It.createElement(Dt,{scrollByOne:!0,height:r-3,selectedIndex:d,itemHeight:1},y)))}});import{Box as on,Text as Ws}from"ink";import Ie,{useMemo as fr}from"react";var yg,hg,xg,Ig,oc,sc=h(()=>{"use strict";te();ae();T();Ae();Bs();bn();Gd();Jd();Ln();Zd();rc();yg=e=>ye(e,"description"),hg=e=>ye(e,"comments"),xg=e=>ye(e,"history"),Ig=e=>ye(e,"attachments"),oc=({ticket:e,height:t})=>{let n=fr(()=>Kd(e),[e]),{selectedIndex:r,contextNode:o}=ke(),s=process.stdout.columns||120,d=fr(()=>yg(e.id),[e.id]),l=fr(()=>hg(e.id),[e.id]),u=fr(()=>xg(e.id),[e.id]),m=fr(()=>Ig(e.id),[e.id]),p=x.getAttachmentsByIssue(e.id).length,y=o.id===e.id,N=o.id===l||o.parentNodeId===l,R=o.id===u||o.parentNodeId===u,D=o.id===m||o.parentNodeId===m,B=q(e.id);if(N){let H=t-3;return Ie.createElement(on,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ie.createElement(Xd,{ticket:e,width:s,height:H}))}if(D){let H=t-3;return Ie.createElement(on,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ie.createElement(qd,{ticket:e,width:s,height:H}))}if(R){let U=x.getNode(u),H=U&&De(U)?U.props.value??"":"",_t=t-3;return Ie.createElement(on,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},U?Ie.createElement(js,{id:U.id,label:"Event log",text:H,selected:!1,maxWidth:s,height:_t}):null)}let $=B.reduce((U,H)=>qn(H)||H.id===l||H.id===m||H.id===u?U+1:U,0),oe=2,se=3,V=$,He=t-se-V-oe,dn=(U,H)=>U.id===d?Ie.createElement(js,{key:U.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:H,maxWidth:s,height:He}):qn(U)?Ie.createElement(Qd,{key:U.id,parent:U,selected:H,selectedIndex:r}):U.id===l?Ie.createElement(on,{key:U.id,paddingTop:1},Ie.createElement(Le,{isSelected:H}),Ie.createElement(Ws,{backgroundColor:E.secondary,color:H?E.accent:E.primary},` Comments (${n}) \u203A\u203A `)):U.id===m?Ie.createElement(on,{key:U.id,paddingTop:1},Ie.createElement(Le,{isSelected:H}),Ie.createElement(Ws,{backgroundColor:E.secondary,color:H?E.accent:E.primary},` Attachments (${p}) \u203A\u203A `)):U.id===u?Ie.createElement(on,{key:U.id,paddingTop:1},Ie.createElement(Le,{isSelected:H}),Ie.createElement(Ws,{backgroundColor:E.secondary,color:H?E.accent:E.primary}," History \u203A\u203A ")):null;return Ie.createElement(on,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},B.map((U,H)=>dn(U,y&&r===H)))}});import{Box as bg}from"ink";import bo from"react";var Eg,ic,ac=h(()=>{"use strict";te();Hd();sc();Eg=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:d,width:l})=>{let u=t.context,m=u===L.TICKET||u===L.FIELD_LIST||u===L.FIELD,p=u===L.BOARD||u===L.SWIMLANE,y=u===L.TICKET?t:r.find($=>$.context===L.TICKET),N=Math.floor(l/3),R=Math.floor(l/Math.max(e.length,1)),D=Math.min(R,N),B=s==="dense";return bo.createElement(bg,{flexDirection:"row",height:d},p&&e.map(($,oe)=>{let se=t.id===$.id,V=se?n:-1,He=t.context===L.BOARD&&n===oe;return bo.createElement(Wd,{key:$.id,height:d,width:D,swimlane:$,isSelected:He,isDense:B,isFocused:se,listSelectedIndex:V,mode:o})}),m&&y&&bo.createElement(oc,{height:d,ticket:y}))},ic=bo.memo(Eg)});import dc from"node:fs";import Ng from"node:path";import Cg from"react";import{render as Sg}from"ink";import{Writable as Rg}from"node:stream";var vr,Ag,Tg,wg,Mg,cc,lc=h(()=>{"use strict";ac();te();C();T();ce();Re();vr=e=>String(e).padStart(2,"0"),Ag=e=>{let t=e.getUTCFullYear(),n=vr(e.getUTCMonth()+1),r=vr(e.getUTCDate()),o=vr(e.getUTCHours()),s=vr(e.getUTCMinutes()),d=vr(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${d}`},Tg=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",wg=async(e,{width:t,height:n})=>{let r="",o=new Rg({write(d,l,u){let m=Mg(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=Sg(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),r},Mg=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),cc=async()=>{let{viewMode:e}=ne(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=g(),d=r.find(oe=>oe.context==="BOARD");if(!d)return i("No board found to export");let l=120,u=40,m=await wg(Cg.createElement(ic,{height:u,width:l,swimlanes:(s[d.id]??[]).filter(oe=>oe!==void 0&&Gn(oe)),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=Nr(process.cwd());if(a(p))return i("Unable to export, epiq root not found");let y=new Date,N=Ag(y),R=`board_${Tg(d.title)}_${N}.md`,D=ui(p.value);dc.mkdirSync(D,{recursive:!0});let B=Ng.join(D,R),$=`# Board - ${d.title}
6
+ `;Kn.writeFileSync(e,o,"utf8")}function Vr(e,t,n=!1){let o=Ii();if(!o)return;let r=pu.format(...t),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${r}
7
+ `;Kn.mkdirSync(Gr.dirname(o),{recursive:!0}),Kn.appendFileSync(o,l,"utf8"),qr++,qr>=gu&&(qr=0,fu())}var hi,gu,qr,xi,Ii,zr,me,mn=h(()=>{"use strict";C();ue();hi=1e3,gu=50,qr=0,xi=()=>process.env.EPIQ_MCP==="true",Ii=()=>{let e=process.cwd(),t=Co(e);return a(t)?xi()?Gr.join(process.cwd(),".epiq-mcp.log"):void 0:Gr.join(t.value,nt,"log","epiq.log")};zr=()=>xi()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",me={info(...e){let t=zr();(t==="info"||t==="debug")&&Vr("[Info]",e,!1)},debug(...e){zr()==="debug"&&Vr("[Debug]",e,!0)},error(...e){let t=zr();if(t==="error"||t==="info"||t==="debug"){let o=e.some(r=>r instanceof Error)?void 0:new Error().stack;Vr("[Error]",[...e,o].filter(Boolean),!1)}}};globalThis.logger=me});var de,To=h(()=>{"use strict";Kt();de={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:o=!1})=>{let r=t&&n?["push",...o?["-u"]:[],t,n]:["push"];return _({args:r,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 pn,Ke,wo=h(()=>{"use strict";Ht();C();ue();pn=e=>{let t=ot(e);if(a(t))return i("Unable to resolve epiq project root");let n=St(t.value);return a(n)?i("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},Ke="origin"});import{spawn as vu}from"node:child_process";import Mo from"node:fs";import qn from"node:path";var bi,yu,Ei,_,it,gn,hu,xu,ko,Yr,Lo,Po,Vn,Ni,Xr,Do,Si,Ci,Iu,Jr,Ri,Ai,Kt=h(()=>{"use strict";C();To();wo();bi=1e4,yu={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Ei=({args:e,cwd:t,allowFail:n})=>new Promise(o=>{if(!Mo.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){o({stdout:"",stderr:p,exitCode:1});return}o(i(p));return}let r=vu("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:yu}),s=!1,d="",l="",u=p=>{s||(s=!0,clearTimeout(m),o(p))},m=setTimeout(()=>{r.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${bi}ms`].join(`
8
+ `);u(n?{stdout:d,stderr:p,exitCode:124}:i(p))},bi);r.stdout.setEncoding("utf8"),r.stderr.setEncoding("utf8"),r.stdout.on("data",p=>{d+=p}),r.stderr.on("data",p=>{l+=p}),r.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
+ `)))}),r.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})=>Ei({args:e,cwd:t,allowFail:!1}),it=({args:e,cwd:t})=>Ei({args:e,cwd:t,allowFail:!0}),gn=async({cwd:e,message:t})=>{let n=await de.commit({cwd:e,message:t});if(a(n))return i(`Failed to create commit
11
+ ${n.message}`);let o=await _({args:["rev-parse","HEAD"],cwd:e});return a(o)?i(`Commit created, but failed to read HEAD SHA
12
+ ${o.message}`):c("Created commit and resolved SHA",o.value.stdout.trim())},hu=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",qn.isAbsolute(n)?n:qn.resolve(e,n))},xu=async e=>{let t=await hu(e);if(a(t))return i(t.message);let n=t.value,o={MERGE_HEAD:"merge in progress"};for(let[s,d]of Object.entries(o))if(Mo.existsSync(qn.join(n,s)))return c("Checked for in-progress Git operation",d);let r={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,d]of Object.entries(r))if(Mo.existsSync(qn.join(n,s)))return c("Checked for in-progress Git operation",d);return c("Checked for in-progress Git operation",null)},ko=async e=>{let t=await xu(e);return a(t)?i(t.message):c("Checked for in-progress Git operation",t.value!==null)},Yr=async({repoRoot:e})=>{let n=(await it({args:["remote","get-url",Ke],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},Lo=async({repoRoot:e,branch:t})=>{let n=await it({args:["ls-remote","--heads",Ke,t],cwd:e});return n.exitCode!==0?i(n.stderr.trim()||`Unable to inspect remote branch ${Ke}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},Po=async({repoRoot:e,branch:t})=>{let n=await it({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}`)},Vn=e=>{try{return Mo.realpathSync.native(e)}catch{return qn.resolve(e)}},Ni=async({repoRoot:e,worktreeRoot:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let o=Vn(t),r=n.value.stdout.split(`
13
+ `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Vn).includes(o);return c("Checked worktree registration",r)},Xr=async e=>{let t=await it({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Do=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())},Si=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())},Ci=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Iu=async e=>(await it({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1),Jr=async({cwd:e,branch:t})=>{let n=await Lo({repoRoot:e,branch:t});if(a(n))return i(n.message);if(!n.value)return c("Remote branch missing, skipped pull",!1);let o=await Iu(e);if(a(o))return i(o.message);let r=await de.fetch({cwd:e,remote:Ke,branch:t});if(a(r))return i(`Failed to fetch ${t}
14
+ ${r.message}`);let s=await de.pullRebase({cwd:e,remote:Ke,branch:t});return a(s)?i(`Failed during pull --rebase
15
+ ${s.message}`):c("Pulled with rebase",!0)},Ri=async e=>{let t=await it({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")},Ai=async e=>{let t=await Do(e);return a(t)?i(t.message):c("Checked detached HEAD state",t.value==="HEAD")}});import Qr from"node:fs";import at from"node:path";var wi,Zr,Mi,ki,Fo,ke,bu,Ti,zn,Bo,Li,Pi,Di,st,Lv,gt=h(()=>{"use strict";Ht();C();$r();ue();yi();mn();Kt();wi="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Zr=e=>at.join(nt,No,e),Mi=()=>at.join(nt,jr),ki=_n,Fo=()=>at.join(ki(),"worktrees"),ke=({repoRoot:e})=>{let t=fi(e);return a(t)?i(t.message):c("Resolved state branch root",at.join(Fo(),t.value))},bu=e=>at.join(e,nt),Ti=e=>at.join(bu(e),No),zn=e=>{try{return Qr.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return i(t instanceof Error?t.message:String(t))}},Bo=()=>{let e=zn(ki());if(a(e))return i(`Ensure epiq home failed.
16
+ `+e.message);let t=zn(Fo());return a(t)?i(`Ensure worktrees dir failed.
17
+ `+t.message):c("Ensured epiq storage",!0)},Li=e=>{Qr.existsSync(e)&&(me.debug("[sync] remove path",e),Qr.rmSync(e,{recursive:!0,force:!0}))},Pi=(e,t)=>{for(let n of[Ti(e),Ti(t)]){let o=zn(n);if(a(o))return i(o.message)}return c("Ensured state branch",void 0)},Di=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
+ `+t.message);let o=t.value.stdout.trim().split(`
19
+ `).filter(Boolean).filter(d=>d!==nt);if(o.length===0)return c("State branch is storage-only",!1);let r=await _({args:["rm","-r","--ignore-unmatch","--",...o],cwd:e});if(a(r))return i(`Failed to clean storage branch
20
+ ${r.message}`);let s=await gn({cwd:e,message:"[epiq:repair-storage-branch]"});return a(s)?i(s.message):c("Cleaned storage branch",!0)},st=Kr(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=>at.resolve(e)),Lv=Kr(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(),o=at.isAbsolute(n)?n:at.join(e,n);return c("Resolved git dir",o)},e=>at.resolve(e))});import qt from"node:fs";import Oo from"node:path";var Bi,Fi,Eu,es,Nu,Su,Cu,Gn,Ru,Au,Uo,Oi,Ui,Yn,_i,_o=h(()=>{"use strict";C();mn();To();wo();gt();Kt();Bi=async e=>{if((await it({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);me.info("Creating initial commit");let n=await de.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return a(n)?i(n.message):c("Created initial commit",!0)},Fi=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Eu=async e=>{let t=await Do(e);if(a(t))return i(t.message);let n=await Si(e);return a(n)?i(n.message):c("Built sync commit message",`[sync|branch:${Fi(t.value)}:sha:${Fi(n.value)}]`)},es=async({repoRoot:e,stateBranchName:t})=>{me.info(`Creating ${t}`);let n=await _({args:["commit-tree",wi,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return i(`Failed to create state branch commit
21
+ ${n.message}`);let o=n.value.stdout.trim(),r=await _({args:["update-ref",`refs/heads/${t}`,o],cwd:e});return a(r)?i(`Failed to create ${t}
22
+ ${r.message}`):c("Created state branch",!0)},Nu=async({repoRoot:e,stateBranchName:t})=>{let n=await Yr({repoRoot:e});if(a(n))return i(`Ensure local state branch failed
23
+ `+n.message);let o=n.value,r=o?await Lo({repoRoot:e,branch:t}):c("No remote, no remote state branch",!1);if(a(r))return i(`Ensure local state branch failed
24
+ `+r.message);let s=r.value;if(o&&s){let l=await de.fetch({cwd:e,remote:Ke,branch:t});if(a(l))return i(`Failed to fetch ${t} from remote
25
+ ${l.message}`)}let d=await Po({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,`${Ke}/${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 es({repoRoot:e,stateBranchName:t})},Su=async({repoRoot:e,branch:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let o=n.value.stdout.split(`
28
+ `),r=null;for(let s of o){if(s.startsWith("worktree ")){r=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&r)return c("Found worktree for branch",r)}return c("No worktree found for branch",null)},Cu=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=zn(Oo.dirname(t));if(a(o))return i(`Failed to create state branch worktree
29
+ `+o.message);qt.existsSync(t)&&!qt.existsSync(Oo.join(t,".git"))&&(me.info("Removing broken state branch worktree path"),Li(t)),me.info("Creating state branch worktree");let r=await de.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(r)?i(`Failed to create state branch worktree
30
+ ${r.message}`):c("Created state branch worktree",!0)},Gn=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=await Su({repoRoot:e,branch:n});if(a(o))return i(o.message);let r=Vn(t),s=o.value?Vn(o.value):null;if(s&&s===r&&qt.existsSync(s))return c("State branch already checked out in expected worktree",!1);if(s&&s!==r){me.info("Moving state branch worktree to expected location");let u=await de.worktreeRemove({cwd:e,worktreeRoot:s});if(a(u))return i(`Failed to remove existing state branch worktree
31
+ ${u.message}`)}if(s&&!qt.existsSync(s)){me.info("Pruning stale state branch worktree");let u=await de.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
32
+ ${u.message}`)}let d=await Ni({repoRoot:e,worktreeRoot:t});if(a(d))return i(d.message);let l=qt.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 de.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
33
+ ${u.message}`)}return Cu({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Ru=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Do(e);if(a(n))return i(n.message);if(n.value===t)return c("State branch already checked out",!1);(await it({cwd:e,args:["rebase","--abort"]})).exitCode===0&&me.info("Aborted stale state branch rebase");let r=await de.checkout({cwd:e,branch:t});return a(r)?i(`Failed to checkout ${t}
34
+ ${r.message}`):c("Checked out state branch",!0)},Au=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Xr(t);if(a(n))return i(n.message);if(n.value)return c("State branch upstream already configured",!1);let o=await Yr({repoRoot:t});if(a(o))return i(o.message);if(!o.value)return c("No remote available for state branch upstream",!1);let r=pn(e);if(a(r))return r;let s=r.value,d=await Lo({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 de.fetch({cwd:t,remote:Ke,branch:s});if(a(l))return i(`Failed to fetch ${s}
35
+ ${l.message}`);let u=await de.setUpstream({cwd:t,branch:s,upstream:`${Ke}/${s}`});return a(u)?i(`Failed to set state branch upstream
36
+ ${u.message}`):c("Configured state branch upstream",!0)},Uo=async({stateBranchRoot:e,eventFileName:t})=>{let n=Zr(t),o=Oo.join(e,n);if(!qt.existsSync(o))return c("No event file to stage",void 0);let r=await de.stage({cwd:e,pathspec:[n]});return a(r)?i(`Failed to stage state branch event file
37
+ ${r.message}`):c("Staged state branch event file",void 0)},Oi=async({stateBranchRoot:e})=>{let t=Mi(),n=Oo.join(e,t);if(!qt.existsSync(n))return c("No media directory to stage",void 0);let o=await de.stage({cwd:e,pathspec:[t]});return a(o)?i(`Failed to stage state branch media files
38
+ ${o.message}`):c("Staged state branch media files",void 0)},Ui=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Eu(e);return a(n)?i(`Create state branch sync commit failed
39
+ `+n.message):gn({cwd:t,message:n.value})},Yn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Xr(t);if(a(n))return i(n.message);let o=pn(e);if(a(o))return o;let r=o.value,s=n.value?await de.push({cwd:t}):await de.push({cwd:t,remote:Ke,branch:r,setUpstream:!0});return a(s)?i(`Failed during state branch push
40
+ ${s.message}`):c("Pushed state branch",!0)},_i=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let o=!1,r=pn(e);if(a(r))return r;let s=r.value,d=[Bo(),await Nu({repoRoot:e,stateBranchName:s}),await Gn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Ru({stateBranchRoot:t,stateBranchName:s}),await Di(t),n?await Au({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of d){if(a(l))return i(l.message);o=o||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",o)}});import{WebSocket as Tu}from"ws";var wu,$i,ji=h(()=>{"use strict";wu=new Set,$i=e=>{let t=JSON.stringify(e);for(let n of wu)n.readyState===Tu.OPEN&&n.send(t)}});function ts(e){return e.context===P.WORKSPACE}function M(e){return e.context===P.TICKET}function Wi(e){return e.context===P.TEXT}function Be(e){return e.context===P.FIELD}function Xn(e){return e.context===P.FIELD_LIST}var P,Vt,$o,Jn,ne=h(()=>{"use strict";P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};Vt=e=>e.context===P.SWIMLANE,$o=e=>e.context===P.BOARD,Jn=e=>e.context===P.COMMENT});var f,Q=h(()=>{"use strict";f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var Hi=h(()=>{"use strict";zt()});function jo(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}var Qn,qe,fn=h(()=>{"use strict";Qn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",qe=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var Ki,qi,Vi=h(()=>{"use strict";Ki=e=>{let t=new Map;for(let n of e)for(let o=1;o<=n.length;o++){let r=n.slice(0,o),s=t.get(r);s?s.push(n):t.set(r,[n])}return t},qi=(e,t)=>t?e.get(t)??[]:[]});var zi,Mu,Gi,Yi=h(()=>{"use strict";fn();Vi();zi=new WeakMap,Mu=e=>{let t=zi.get(e);return t||(t=Ki(e),zi.set(e,t)),t},Gi=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let o=t.toLowerCase();return qi(Mu(e),o).filter(s=>jo(o,s)>=n)}});var ku,Xi,Lu,Ji=h(()=>{"use strict";fn();Yi();ku={hint:"",hints:[],overlap:0,remainder:""},Xi=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},o)=>{if(n||e==="")return ku;let r=Gi({wordList:o,inputToMatch:e,overlapThreshold:1});return Lu(t,r)},Lu=(e,t)=>{let n=t[0]??"",o=jo(e.toLowerCase(),n.toLowerCase()),[r,s]=n.split(":"),d=o<(r??"").length,l=!!s,p=(l&&d?r:n)+(l&&d?":":" "),y=p.slice(o);return{hint:p,hints:t,overlap:o,remainder:y}}});import{useSyncExternalStore as iy}from"react";var Wo,Pu,Du,oe,Ve,we=h(()=>{"use strict";Wo={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Pu=new Set,Du=()=>{for(let e of Pu)e()},oe=()=>Wo,Ve=e=>(Wo={...Wo,...e},Du(),Wo)});function Qi(e){return!e||!Bu.test(e)?i(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Oe(e,t=vn){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 Le(e,t){if(!e&&!t)return Oe(Qe/2n,vn);let n=e?Qi(e):c("Resolved lower bound",0n);if(a(n))return n;let o=t?Qi(t):c("Resolved upper bound",Qe);if(a(o))return o;let r=n.value,s=o.value;if(s<=r)return Oe(Qe/2n,vn);let d=(r+s)/2n;return d===r||d===s?i("No rank space available between neighbors"):Oe(d,vn)}function Zi(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let o=0;o<e;o++){let r=Qe*BigInt(o+1)/(t+1n),s=Oe(r,vn);if(a(s))return s;n.push(s.value)}return c("Resolved evenly spaced ranks",n)}var vn,Fu,Qe,Bu,yn=h(()=>{"use strict";C();vn=24n,Fu=vn*4n,Qe=(1n<<Fu)-1n,Bu=/^[0-9a-f]+$/});import{ulid as Ou}from"ulid";var ns,ea=h(()=>{"use strict";C();dt();yn();ns=(e,t)=>{let n=Z(e),o=Zi(n.length);if(a(o))return o;let r={};for(let s=0;s<n.length;s++){let d=n[s],l=o.value[s];if(!d||!l)return i("Unable to assign rebalance rank");r[d.id]=l}return c("Created rebalance event",{id:Ou(),action:"rebalance.children",payload:{parent:e,ranks:r},...t})}});var Gt,Uu,Ct,x,ce=h(()=>{"use strict";ne();C();T();dt();Gt=(e,t)=>{let{nodes:n}=g(),o=n[e];if(!o)return i("Node not found");if(o.context===t)return c("Resolved ancestor node",o);let r=o.parentNodeId?n[o.parentNodeId]:void 0;for(;r;){if(r.context===t)return c("Resolved ancestor node",r);r=r.parentNodeId?n[r.parentNodeId]:void 0}return i(`No ancestor found for context: ${t}`)},Uu=(e,t)=>{let{nodes:n}=g(),o=n[e];for(;o?.parentNodeId;){if(o.parentNodeId===t)return!0;o=n[o.parentNodeId]}return!1},Ct=(e,t)=>e?e.readonly?i({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:i("Node not found"),x={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 o={...n,userId:t},r=ye(s=>({...s,contributors:{...s.contributors,[e]:o}}));return a(r)?i("Unable to link contributor to user"):c("Linked contributor to user",o)},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(!M(t))return i("Can only comment on issues");let n=ye(o=>({...o,comments:{...o.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 o=this.getNode(n.issue);if(!o)return i("Unable to edit comment, missing issue");if(!M(o))return i("Can only edit issue comments");let r={...n,md:t,deleted:!1},s=ye(d=>({...d,comments:{...d.comments??{},[e]:r}}));return a(s)?i("Unable to edit comment"):c("Edited comment",r)},deleteComment(e){let t=this.getComment(e);if(!t)return i("Unable to delete comment, missing comment");let n={...t,deleted:!0},o=ye(r=>({...r,comments:{...r.comments??{},[e]:n}}));return a(o)?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)},createAttachment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create attachment, missing issue");if(!M(t))return i("Can only attach to issues");let n=ye(o=>({...o,attachments:{...o.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?i("Unable to create attachment"):c("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return i("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},o=ye(r=>({...r,attachments:{...r.attachments??{},[e]:n}}));return a(o)?i("Unable to delete attachment"):c("Deleted attachment",n)},getAttachment(e){return g().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(g().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=g(),o=n[e];if(!o)return i("Edit target node not found");let r=Ct(o,"edit");if(r)return r;let s={...o,props:{...o.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 o=Ct(n,"rename");if(o)return o;let r={...n,title:t};return this.updateNode(r),c("Renamed node",r)},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 Z(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:o}=g(),r=this.getNode(e),s=this.getNode(t);if(!r)return i("Node not found");if(!s)return i("Target parent not found");if(o===e)return i("Cannot move root node");if(e===t)return i("Cannot move node into itself");let d=Ct(r,"move");if(d)return d;if(Uu(t,e))return i("Cannot move node into its own descendant");let l={...r,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:o}=g(),r=this.getNode(e);if(!r)return i("Node not found");if(o===e)return i("Cannot delete root node");let s=Ct(r,"delete");if(s)return s;let d=new Set,l=m=>{let p=t[m];if(!(!p||d.has(m))){d.add(m);for(let y of Z(p.id))l(y.id)}};l(e);let u={...structuredClone(t)};for(let m of d){if(!u[m])return i("Unable to locate node to delete");u[m]={...u[m],isDeleted:!0}}return n?(I({nodes:u}),c("Successfully tomb stoned",r)):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),o=this.getNode(e);if(!n)return i("Unable to assign contributor, missing contributor");if(!o)return i("Unable to assign contributor, missing target");let r=Ct(o,"edit");if(r)return r;if(!M(o))return i("Target is not an issue");let s=o.props.assignees??[];if(s.includes(t))return i("Contributor already assigned");let d={...o,props:{...o.props,assignees:[...s,t]}};return this.updateNode(d),c("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return i("Unable to unassign, missing contributor");if(!o)return i("Unable to unassign, missing target");let r=Ct(o,"edit");if(r)return r;if(!M(o))return i("Target is not an issue");let s=o.props.assignees??[];if(!s.includes(t))return c("Issue is not assigned to that contributor",{assignee:t});let d={...o,props:{...o.props,assignees:s.filter(l=>l!==t)}};return this.updateNode(d),c("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),o=this.getNode(e);if(!n)return i("Unable to add tag, missing tag");if(!o)return i("Unable to add tag, missing target");let r=Ct(o,"edit");if(r)return r;if(!M(o))return i("Target is not an issue");let s=o.props.tags??[];if(s.includes(t))return i("Tag already assigned");let d={...o,props:{...o.props,tags:[...s,t]}};return this.updateNode(d),c("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),o=this.getNode(e);if(!n)return i("Unable to remove tag, missing tag");if(!o)return i("Unable to remove tag, missing target");let r=Ct(o,"edit");if(r)return r;if(!M(o))return i("Target is not an issue");let s=o.props.tags??[];if(!s.includes(t))return c("Issue is not tagged with that tag",{tag:t});let d={...o,props:{...o.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},o=ye(r=>({...r,nodes:{...r.nodes,[e]:n}}));return a(o)?i(o.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 Z(e)}}});var z,hn=h(()=>{"use strict";z={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var Ze,ta,xn=h(()=>{"use strict";Ze=e=>e.slice(-7).toUpperCase(),ta=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?Ze(e).includes(n):!0}});var he,Yt=h(()=>{"use strict";ne();xn();he={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,o,r=!1)=>({id:e,title:t,rank:o,isDeleted:!1,props:{ref:Ze(e)},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:o,props:r={},childRenderAxis:s="horizontal",isVirtual:d=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:P.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:d}),fieldList:({id:e,name:t,parentNodeId:n,rank:o,childRenderAxis:r="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:P.FIELD_LIST,childRenderAxis:r,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{ref:Ze(e)},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!0,isVirtual:s=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:r,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:o,props:r={},readonly:s=!0,isVirtual:d=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:P.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:d})}});var Re,S,Me=h(()=>{"use strict";Re={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:Re.cyan,accent2:Re.magenta,primary:Re.white,secondary:Re.grayDark,secondary2:Re.grayLight,gray:Re.gray,green:Re.green,yellow:Re.yellow,red:Re.red}});var E,In,Ho=h(()=>{"use strict";Me();E={red:Re.red,yellow:Re.yellow,green:Re.green,blue:Re.blue,magenta:Re.magenta,cyan:Re.cyan},In={urgent:E.red,critical:E.red,important:E.red,blocker:E.red,asap:E.red,immediate:E.red,fail:E.red,failure:E.red,broken:E.red,bug:E.red,error:E.red,incident:E.red,outage:E.red,production:E.red,crash:E.red,security:E.red,warning:E.yellow,warn:E.yellow,risky:E.yellow,risk:E.yellow,attention:E.yellow,pending:E.yellow,review:E.yellow,"needs-review":E.yellow,qa:E.yellow,testing:E.yellow,test:E.yellow,validate:E.yellow,verification:E.yellow,staging:E.yellow,check:E.yellow,"follow-up":E.yellow,followup:E.yellow,waiting:E.yellow,blocked:E.yellow,hold:E.yellow,done:E.green,complete:E.green,completed:E.green,success:E.green,ok:E.green,stable:E.green,resolved:E.green,fixed:E.green,closed:E.green,merged:E.green,released:E.green,deployed:E.green,approved:E.green,verified:E.green,working:E.green,healthy:E.green,pass:E.green,passing:E.green,info:E.blue,information:E.blue,note:E.blue,docs:E.blue,documentation:E.blue,doc:E.blue,guide:E.blue,help:E.blue,explanation:E.blue,detail:E.blue,details:E.blue,context:E.blue,design:E.blue,discussion:E.blue,proposal:E.blue,idea:E.blue,feature:E.magenta,enhancement:E.magenta,improvement:E.magenta,refactor:E.magenta,refactoring:E.magenta,cleanup:E.magenta,optimize:E.magenta,optimization:E.magenta,perf:E.magenta,performance:E.magenta,upgrade:E.magenta,migration:E.magenta,modernize:E.magenta,debt:E.magenta,todo:E.cyan,next:E.cyan,planned:E.cyan,plan:E.cyan,future:E.cyan,backlog:E.cyan,investigate:E.cyan,explore:E.cyan,prototype:E.cyan}});import na from"chalk";var rs,oa,os,ra,_u,$u,sa,ju,Wu,Zn,Pe,ia,aa,Ko,Hu,Ku,qo,ft=h(()=>{"use strict";Ho();rs={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},oa=(e,t,n)=>Math.max(t,Math.min(n,e)),os=(e,t,n)=>e+(t-e)*n,ra=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},_u=e=>e.toLowerCase().trim(),$u=(e,t,n)=>{let o=t/100,r=n/100,s=(1-Math.abs(2*r-1))*o,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=r-s/2;return[Math.round((u+y)*255),Math.round((m+y)*255),Math.round((p+y)*255)]},sa=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,ju=(e,t,n)=>{let o=oa(n,0,1);return[Math.round(os(e[0],t[0],o)),Math.round(os(e[1],t[1],o)),Math.round(os(e[2],t[2],o))]},Wu=(e,t,n)=>ju(e,t,n),Zn=e=>{let n=ra(e)%360,o=$u(n,rs.stringColor.saturation,rs.stringColor.lightness);return sa(o)},Pe=(e,t=In)=>{let n=_u(e);return n&&t[n]?t[n]:Zn(n)},ia=e=>{let t=rs.gradient.stops,n=oa(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let o=t.length-1,r=n*o,s=Math.min(Math.floor(r),o-1),d=r-s;return Wu(t[s],t[s+1],d)},aa=e=>sa(ia(e)),Ko=e=>ra(e.toLowerCase().trim())/4294967295,Hu=e=>{let t=Ko(e);return ia(t)},Ku=e=>{let[t,n,o]=Hu(e);return{normal:r=>na.bgRgb(t,n,o).black(r),cursor:r=>na.bgRgb(t,n,o).white.bold(r)}},qo=e=>Ku(e).normal(` ${e} `)});import{decodeTime as da}from"ulid";var bn,ca,En,Xt=h(()=>{"use strict";C();bn=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:o,ms:r}of n){let s=Math.floor(t/r);if(s>=1)return`${s}${o} ago`}return"just now"},ca=e=>{try{return c("Decoded date",new Date(da(e)))}catch(t){return i("Decoding failed + "+t.message)}},En=e=>{if(!e?.id)return null;try{return da(e.id)}catch{return null}}});import Rt from"chalk";import la from"string-width";import{decodeTime as qu}from"ulid";var Vu,zu,ua,Gu,Yu,ma,pa,Xu,Ju,Qu,Zu,em,ga,fa,ss=h(()=>{"use strict";ce();T();ft();Xt();Vu=(e,t)=>e+" ".repeat(Math.max(0,t-la(e))),zu=(e,t)=>" ".repeat(Math.max(0,t-la(e)))+e,ua=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","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),Gu=(e,t)=>t?e<t?"up":e>t?"down":null:null,Yu=(e,t)=>{let n=x.getNode(e.payload.parent),o=n?Rt.dim.bgBlack(` ${n.title} `):"unknown",r=t.at(-1);if(r&&"parent"in r&&"rank"in r&&r.parent===e.payload.parent){let s=Gu(e.payload.rank,r.rank);if(s)return`Moved ${s} in ${o}`}return`Moved issue to ${o}`},ma=e=>`${Math.max(1,Math.round(e/1024))} KB`,pa=e=>x.getAttachment(e)?.name??"",Xu=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Rt.bgHex(Pe(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Rt.bgHex(Pe(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Rt.hex(Pe(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Rt.hex(Pe(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:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Rt.dim(`(${ma(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=pa(e.payload.id);return t?`"${t}"`:""}default:return""}},Ju=e=>{let t=bn(qu(e));return Rt.gray(zu(t,8))},Qu=12,Zu=e=>Vu(`${e}`,Qu),em=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=x.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${ma(e.payload.bytes)})`;case"delete.issue.attachment":{let t=pa(e.payload.id);return t?`"${t}"`:""}default:return""}},ga=e=>[ua(e.action),em(e)].filter(Boolean).join(" "),fa=(e,t)=>{let n=Ju(e.id),o=Zu(e.userName),r=Rt.dim("\u203A"),s=e.action==="move.node"?Yu(e,t):[ua(e.action),Xu(e)].filter(Boolean).join(" ");return`${o} ${n} ${r} ${s}`}});import{createHash as tm}from"node:crypto";var nm,om,xe,Nn=h(()=>{"use strict";nm="0123456789ABCDEFGHJKMNPQRSTVWXYZ",om=e=>{let t=tm("sha256").update(e).digest(),n=0n;for(let r=0;r<16;r++)n=n<<8n|BigInt(t[r]);let o="";for(let r=0;r<26;r++){let s=BigInt((25-r)*5);o+=nm[Number(n>>s&31n)]}return o},xe=(e,t)=>om(`${e}:virtual:${t}`)});var rm,sm,im,am,dm,cm,Vo,va,ya,lm,ha=h(()=>{"use strict";ss();ne();C();hn();ce();Yt();T();yn();Nn();rm=e=>xe(e,"comments"),sm=e=>xe(e,"description"),im=e=>xe(e,"assignees"),am=e=>xe(e,"tags"),dm=e=>xe(e,"history"),cm=e=>xe(e,"attachments"),Vo=({id:e,name:t,parentNodeId:n,rank:o,value:r,readonly:s=!1,childRenderAxis:d="horizontal"})=>{let l=x.getNode(e);if(!l){let p=x.createNode({...he.field({id:e,name:t,parentNodeId:n,rank:o,props:{value:r},isVirtual:!0}),readonly:s,childRenderAxis:d});return a(p)?p:c("Virtual field created",void 0)}if(!Be(l))return i(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==o||l.props.value!==r||l.readonly!==s||l.childRenderAxis!==d))return c("Virtual field unchanged",void 0);let m=x.updateNode({...l,title:t,parentNodeId:n,rank:o,props:{...l.props,value:r},readonly:s,childRenderAxis:d});return a(m)?m:c("Virtual field updated",void 0)},va=({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!1,childRenderAxis:s="horizontal"})=>{let d=x.getNode(e);if(!d){let m=x.createNode({...he.fieldList({id:e,name:t,parentNodeId:n,rank:o,isVirtual:!0}),readonly:r,childRenderAxis:s});return a(m)?m:c("Virtual field list created",void 0)}if(!Xn(d))return i(`Existing virtual node ${e} is not a field list`);if(!(d.title!==t||d.parentNodeId!==n||d.rank!==o||d.readonly!==r||d.childRenderAxis!==s))return c("Virtual field list unchanged",void 0);let u=x.updateNode({...d,title:t,parentNodeId:n,rank:o,readonly:r,childRenderAxis:s});return a(u)?u:c("Virtual field list updated",void 0)},ya=e=>{let t=Oe(Qe/4n),n=Oe(Qe/2n),o=Oe(Qe*3n/4n),r=Oe(Qe*7n/8n),s=Oe(Qe*15n/16n),d=Oe(Qe*13n/16n);if(a(t))return t;if(a(n))return n;if(a(o))return o;if(a(r))return r;if(a(s))return s;if(a(d))return d;let l=Vo({id:sm(e.id),name:z.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(l))return l;let u=va({id:im(e.id),name:z.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(u))return u;let m=va({id:am(e.id),name:z.TAGS,parentNodeId:e.id,rank:o.value,readonly:!0});if(a(m))return m;let p=Vo({id:rm(e.id),name:z.COMMENTS,parentNodeId:e.id,rank:r.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(p))return p;let y=Vo({id:cm(e.id),name:z.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(y))return y;let N=Vo({id:dm(e.id),name:z.HISTORY,parentNodeId:e.id,rank:d.value,value:lm(e),readonly:!0,childRenderAxis:"vertical"});return a(N)?N:c("Ticket virtual nodes materialized",void 0)},lm=e=>{let t=[...e.log].reverse(),n=new Map;for(let o of t){let r=n.get(o.action)??[];r.push(o.payload),n.set(o.action,r)}return t.map(o=>fa(o,n.get(o.action)??[])).join(`
41
+ `)}});var um,pe,zo,Sn=h(()=>{"use strict";um=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[pe,zo]=um});function At(e,t=!1){let n=hm[e.action];if(!n)return i(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);let o=n(e);if(a(o))return o;let r=ym(e,t);return r||o}var D,xa,mm,pm,gm,is,fm,vm,ym,hm,Tt,wt=h(()=>{"use strict";ne();C();hn();ce();Yt();T();ha();Sn();D=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),xa=e=>{let t=x.getNode(e);if(!t||!M(t)||t.isDeleted)return null;let n=ya(t);return a(n)?n:null},mm=e=>{for(let t of e){let n=xa(t);if(n)return n;let o=g().nodes[t]?.parentNodeId;if(!o)continue;let r=xa(o);if(r)return r}return null},pm=(e,t)=>{let n=x.getNode(e);n&&x.updateNode({...n,log:[...n.log??[],t]})},gm=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},is=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":case"add.issue.attachment":case"delete.issue.attachment":return[e.payload.issue];case"delete.node":case"edit.description":return gm(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[]}},fm=e=>{ye(t=>({...t,eventLog:[...t.eventLog,e]}))},vm=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?D("Invalid user ID format",e):c("Valid user",null)},ym=(e,t)=>{let n=vm(e);if(a(n))return n;let o=[...new Set(is(e))];t||(o.forEach(s=>pm(s,e)),fm(e));let r=mm(o);return r||null},hm={"init.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=he.workspace(t,n,o),s=eo(r);if(a(s))return D(s.message,e);let d=x.createNode(r);return a(d)?D(d.message??"Failed to initialize workspace",e):ts(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:o}=e.payload,r=x.createNode(he.workspace(t,n,o));return a(r)?D(r.message??"Failed to add workspace",e):ts(r.value)?c("Added workspace",{action:e.action,result:r.value}):i("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=x.createNode(he.board(t,n,o,r));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:o,rank:r}=e.payload,s=x.createNode(he.swimlane(t,n,o,r));return a(s)?D(s.message??"Unable to create swimlane",e):Vt(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:o,rank:r}=e.payload,s=x.createNode(he.ticket(t,n,o,r));return a(s)?D(s.message??"Unable to create issue",e):M(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:o,val:r,rank:s}=e.payload,d=x.createNode(he.field({id:t,name:n,parentNodeId:o,rank:s,props:{value:r},childRenderAxis:n.includes(z.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?D(d.message??`Unable to create field: ${n}`,e):Be(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(!x.getNode(t))return D(`Unable to locate node with id ${t}`,e);let r=x.renameNode(t,n);return a(r)?D(r.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:r.value})},"delete.node":e=>{let{id:t}=e.payload,n=x.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,o=x.createTag({id:t,name:n});return a(o)?D(o.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:o.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,o=x.createContributor({id:t,name:n});return a(o)?D(o.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:o.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,o=x.tag(t,n);return a(o)?D(o.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,o=x.untag(t,n);return a(o)?D(o.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,o=x.assign(t,n);return a(o)?D(o.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,o=x.unassign(t,n);return a(o)?D(o.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:o}=e.payload,r=x.moveNodeToRank({id:t,parentId:n,rank:o});return a(r)?D(r.message??"Failed to move node",e):c("Moved node",{action:e.action,result:r.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,o=x.editValue(t,n);return a(o)?D(o.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:o.value})},"close.issue":e=>{let{id:t,parent:n,rank:o}=e.payload,r=x.getNode(t);if(!r)return D("Unable to locate issue",e);if(!M(r))return D("Can only close issues",e);let s=x.getNode(pe);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=x.moveNodeToRank({id:t,parentId:n,rank:o});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:o}=e.payload,r=x.getNode(t);if(!r)return D("Unable to locate issue",e);if(!M(r))return D("Can only reopen issues",e);let s=x.getNode(pe);if(!s)return D("Unable to locate closed swimlane",e);if(n===s.id)return D("Cannot reopen issue into closed swimlane",e);if(!x.getNode(n))return D("Reopen parent no longer exists",e);let l=x.moveNodeToRank({id:t,parentId:n,rank:o});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=x.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[o,r]of Object.entries(n)){let s=x.getNode(o);if(!s)return D(`Unable to locate node ${o}`,e);if(s.parentNodeId!==t)return D(`Node ${o} is not child of ${t}`,e);let d=x.updateNode({...s,rank:r});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:o,md:r}=e.payload,s=x.createComment({id:t,issue:n,authorId:o,authorName:x.getContributor(o)?.name??"Unknown",md:r,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:o,md:r}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:o}=e.payload,r=x.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 s=x.editComment(t,o);return a(s)?D(s.message??"Unable to edit comment",e):c("Comment edited",{action:e.action,result:{id:t,issue:n,md:o}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,o=x.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 r=x.deleteComment(t);return a(r)?D(r.message??"Unable to delete comment",e):c("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:o,ext:r,name:s,bytes:d}=e.payload,l=x.createAttachment({id:t,issue:n,hash:o,ext:r,name:s,bytes:d,deleted:!1});return a(l)?D(l.message??"Unable to add attachment",e):c("Attachment added",{action:e.action,result:{id:t,issue:n,hash:o}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,o=x.getAttachment(t);if(!o)return D("Unable to locate attachment",e);if(o.issue!==n)return D("Attachment does not belong to issue",e);let r=x.deleteAttachment(t);return a(r)?D(r.message??"Unable to delete attachment",e):c("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=x.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}})}};Tt=e=>e.map(t=>At(t))});var xm,Im,Ia,ba,as=h(()=>{"use strict";xm=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","create.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","move.node","edit.description","add.issue.comment","edit.issue.comment","delete.issue.comment","add.issue.attachment","delete.issue.attachment","close.issue","reopen.issue","lock.node","rebalance.children","link.contributor.user"],Im=new Set(xm),Ia=e=>Im.has(e),ba=e=>({action:e.action,payload:e.payload})});import Go from"node:fs";import cs from"node:path";import{decodeTime as bm}from"ulid";import{z as ds}from"zod";function us(e){let t=Wn(e);if(!Go.existsSync(t))return c("No events found",[]);let n=Go.readdirSync(t).filter(r=>r.endsWith(".jsonl")).map(r=>cs.join(t,r)),o=[];for(let r of n){let s=Tm(r);if(a(s))return i(s.message);o.push(...s.value)}return c("All events loaded",wm(o))}function Mt(e){let t=us(e);return a(t)?i(t.message):ls(t.value)}function Ea(e,t){let n=us(e);if(a(n))return i(n.message);let{appliedEvents:o,unappliedEvents:r}=Mm(n.value,t),s=ls(o);if(a(s))return i(s.message);let d=ls(r);return a(d)?i(d.message):c("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function Na(e=process.cwd()){let t=us(e);return a(t)?i(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Em,Nm,Sm,Cm,Rm,Am,ls,Tm,wm,Mm,Cn=h(()=>{"use strict";mn();C();ue();as();et();Em=ds.object({userId:ds.string().min(1).default("unknown"),userName:ds.string().min(1).default("unknown")}),Nm=e=>{let[t,n]=cs.basename(e,".jsonl").split("."),o=Em.safeParse({userId:t,userName:n});return o.success?c("Parsed event file actor",o.data):i(`Invalid event file name ${cs.basename(e)}: ${o.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Sm=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])},Cm=(e,t)=>t in e,Rm=({id:e,action:t,payload:n,userId:o,userName:r})=>({id:e,action:t,payload:n,userId:o,userName:r}),Am=e=>{let{userId:t,userName:n,...o}=e,r=Sm(o);if(a(r))return i(r.message);let s=r.value,d=e.id?.[0];return d?Cm(o,s)?c("Decoded persisted event",Rm({id:d,action:s,payload:o[s],userId:t,userName:n})):i(`Persisted event is missing payload for action: ${s}`):i("Persisted event is missing id")},ls=e=>{let t=[],n=new Map;for(let o of e){let r=Am(o);if(a(r))return i(`Failed to decode event ${o.id?.[0]??"<unknown>"}: ${r.message}`);let s=r.value.action;if(!Ia(s)){n.set(s,(n.get(s)??0)+1);continue}t.push(r.value)}if(n.size>0){let o=[...n.entries()].map(([r,s])=>`${r} (x${s})`).join(", ");me.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${o}. Upgrade to apply them.`)}return c("Decoded reconstructed events",t)},Tm=e=>{if(!Go.existsSync(e))return c("Event file missing",[]);let t=Nm(e);if(a(t))return i(t.message);let n=Go.readFileSync(e,"utf8"),o=[];for(let r of n.split(`
42
+ `)){let s=r.trim();if(!s)continue;let d;try{d=JSON.parse(s)}catch{return i(`Failed to parse event JSON from ${e}: ${s}`)}let l=ms(d);if(a(l))return i(`${l.message} in ${e}: ${s}`);o.push({...l.value,userId:t.value.userId,userName:t.value.userName})}return c("Parsed persisted events file",o)};wm=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 o=[],r=new Set,s=m=>{let p=m.id[0];if(r.has(p))return;o.push(m),r.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!r.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=>!r.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)s(m);return o},Mm=(e,t)=>{let n=new Set,o=[],r=[];for(let s of e){let d=s.id[0],l=s.id[1],u=!1;try{u=bm(d)<t}catch{u=!1}!u||l&&n.has(l)?(n.add(d),r.push(s)):o.push(s)}return{appliedEvents:o,unappliedEvents:r}}});import km from"node:fs";import Lm from"node:path";import{decodeTime as Pm,monotonicFactory as Dm}from"ulid";import{z as to}from"zod";function Yo({event:e,rootDir:t}){try{let n=gi(t);if(a(n))return n;let o=_m(t,{userId:e.userId,userName:e.userName});if(a(o))return o;let r=Na(t);if(a(r))return i(r.message);let s=r.value?Sa(Math.max(Date.now(),Pm(r.value)+1)):Sa(),d=$m(ba(e),[s,r.value]);return a(d)?i(d.message):(km.appendFileSync(o.value,`${JSON.stringify(d.value)}
43
+ `,"utf8"),c("Event persisted",{path:o.value,entry:d.value}))}catch(n){let o=n instanceof Error?n.message:"Unknown persist error";return i(`Failed to persist event: ${o}`)}}var Ra,Sa,Fm,Bm,ms,Ca,Om,Um,re,Jt,_m,$m,et=h(()=>{"use strict";C();we();ue();Cn();as();Ra=1,Sa=Dm(),Fm=to.tuple([to.string().min(1),to.string().min(1).nullable()]),Bm=to.looseObject({v:to.literal(Ra),id:Fm}),ms=e=>{let t=Bm.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(", ")}`)},Ca=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",Om=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),Um=e=>e.trim().length>0&&e.length<=80,re=()=>{let{userName:e,userId:t}=oe();return e?t?Om(t)?Um(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})=>`${Ca(e)}.${Ca(t)}.jsonl`,_m=(e,{userId:t,userName:n})=>{let o=Jt({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(o))return i(`Invalid event log file name: ${o}`);let s=Lm.join(Wn(e),o);return c("Successfully resolved event log path",s)},$m=(e,t)=>{let n={[e.action]:e.payload,v:Ra,id:t};return ms(n)}});import{ulid as jm}from"ulid";function Aa(e,t){let n=At(e);if(n.status!==Nt.Success)return n;let o=Yo({event:e,rootDir:t});return a(o)?o:n}function B(e,t){if(e.length===0||!e[0])return i("No events provided");let n=Wm(e[0],t);if(a(n))return n;let o=e.map(s=>Aa(s,t)),r=o.filter(a);return r.length>0?i("Materialize and persist failed: "+r.map(s=>s.message).join(", ")):c("Materialization succeeded",o.map(s=>s.value))}var Wm,Qt=h(()=>{"use strict";C();ce();wt();et();Wm=(e,t)=>{if(e.action==="create.contributor")return c("Contributor already being created",void 0);if(x.getContributor(e.userId))return c("Contributor exists",void 0);let n={id:jm(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},o=Aa(n,t);return a(o)?i(o.message):c("Contributor created",void 0)}});var Ta,Xo,Z,wa,Ma,kt,Zt,dt=h(()=>{"use strict";ea();Qt();C();T();yn();Ta=e=>Xo(Z(e),{at:"end"}),Xo=(e,t={at:"end"})=>{let n=o=>a(o)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(Le(void 0,void 0));switch(t.at){case"start":{let o=e[0];return o?n(Le(void 0,o.rank)):i("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(Le(o.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let o=wa(e,t.sibling);if(o<0)return i("Sibling not found");let r=o>0?e[o-1]:void 0,s=e[o];return s?n(Le(r?.rank,s.rank)):i("Sibling not found")}case"after":{let o=wa(e,t.sibling);if(o<0)return i("Sibling not found");let r=e[o],s=o<e.length-1?e[o+1]:void 0;return r?n(Le(r.rank,s?.rank)):i("Sibling not found")}}},Z=e=>Object.values(g().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),wa=(e,t)=>e.findIndex(n=>n.id===t),Ma=(e,t,n={at:"end"})=>Xo(Z(t).filter(o=>o.id!==e),n),kt=(e,t,n,o,r)=>{let s=Ma(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return c("Resolved rank",s.value.rank);let d=ns(e,o);if(a(d))return d;let l=B([d.value],r);if(a(l))return l;let u=Ma(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)},Zt=(e,t,n)=>{let o=Ta(e);if(a(o))return o;if(!o.value.needsRebalance)return c("Resolved rank",o.value.rank);let r=ns(e,t);if(a(r))return r;let s=B([r.value],n);if(a(s))return s;let d=Ta(e);return a(d)?d:d.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",d.value.rank)}});var F,ka,La,Ue=h(()=>{"use strict";T();F={exit(){process.exit(0)},enterChildNode(){let e=g(),t=e.contextNode,n=Math.max(0,e.selectedIndex),o=G(t.id),r=o[n];r&&(t.context==="FIELD"&&o.length===0||r.context==="COMMENT"||r.context==="TEXT"||F.navigate({contextNode:r,selectedIndex:G(r.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 o=G(n.id),r=o.findIndex(({id:d})=>d===e.id),s=o.length===0?-1:r>=0?r:0;F.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>ka(1),navigateToPreviousItem:()=>ka(-1),navigateToNextContainer:()=>La(1),navigateToPreviousContainer:()=>La(-1),navigate:({contextNode:e,selectedIndex:t})=>{I({contextNodeId:e.id,selectedIndex:t})}},ka=e=>{let{selectedIndex:t,contextNode:n}=g(),o=G(n.id).length;if(o===0)return;let s=(Math.max(0,t)+e+o)%o;F.navigate({selectedIndex:s,contextNode:n})},La=e=>{let{contextNode:t,nodes:n,selectedIndex:o}=g();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let r=n[t.parentNodeId];if(!r)return;let s=G(r.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=G(l.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,o),m),y=u.length?p:-1;F.navigate({contextNode:l,selectedIndex:y})}});var Da,Fa,Hm,Jo,Ba,Pa,Km,Oa,Ua=h(()=>{"use strict";ne();C();dt();T();Ue();Da=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Fa=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},Hm=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&Be(t)&&t.childRenderAxis==="vertical"},Jo=(e,t)=>{let{nodes:n}=g(),o=n[e];if(!o||o.isDeleted)return!1;let r=Z(o.id);return F.navigate({contextNode:o,selectedIndex:Da(t,r.length)}),!0},Ba=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let o=n.parentNodeId;if(!o)return Jo(n.id,0);let r=t[o];if(!r||r.isDeleted)return!1;let d=Z(r.id).findIndex(l=>l.id===n.id);return d>=0?(F.navigate({contextNode:r,selectedIndex:d}),!0):Ba(r.id)},Pa=e=>{let{nodes:t}=g(),n=e,o=new Set;for(;n&&!o.has(n);){if(o.add(n),Ba(n))return!0;n=t[n]?.parentNodeId}return!1},Km=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},Oa=e=>{let{nodes:t,rootNodeId:n}=g();if(Hm(e.contextNodeId)&&Jo(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(Km(e.selectedNodeId)&&e.selectedNodeId&&Pa(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(Jo(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&Jo(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(Pa(e.contextNodeId))return c("Restored navigation to previous container or ancestor",null);let o=t[n];if(!o||o.isDeleted)return i("Unable to restore navigation");let r=Z(o.id);return F.navigate({contextNode:o,selectedIndex:Da(e.selectedIndex,r.length)}),c("Restored navigation to root",null)}});import{monotonicFactory as qm,ulid as vt}from"ulid";function Vm(){let e=ze();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[o]=G(n.id),[r]=o?G(o.id):[];if(r){let s=t.renderedChildrenIndex?.[r.id]??[];return c("Resolved boot nav target",{contextNode:r,selectedIndex:s.length>0?0:-1})}else return o?c("Resolved boot nav target",{contextNode:o,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 zm(){let e=Vm();return a(e)?e:F.navigate(e.value)}function _a({userId:e,userName:t}){let n=no(),o=no(),r=no(),s=no(),d=no(),l=Le(void 0,void 0);if(a(l))return l;let u=Le(void 0,void 0);if(a(u))return u;let m=Le(u.value,void 0);if(a(m))return m;let p=Le(void 0,void 0);if(a(p))return p;let y=Le(p.value,void 0);if(a(y))return y;let N=Le(y.value,void 0);if(a(N))return N;let R=Le(void 0,void 0);return a(R)?R:c("Created default events",[{id:vt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:vt(),userId:e,userName:t,action:"add.board",payload:{id:o,name:"Default",parent:n,rank:u.value}},{id:vt(),userId:e,userName:t,action:"add.swimlane",payload:{id:r,name:"Todo",parent:o,rank:p.value}},{id:vt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:o,rank:y.value}},{id:vt(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:o,rank:N.value}},{id:vt(),userId:e,userName:t,action:"add.board",payload:{id:zo,name:"Closed",parent:n,rank:m.value}},{id:vt(),userId:e,userName:t,action:"add.swimlane",payload:{id:pe,name:"Closed",parent:zo,rank:R.value}},{id:vt(),userId:e,userName:t,action:"lock.node",payload:{id:zo}},{id:vt(),userId:e,userName:t,action:"lock.node",payload:{id:pe}}])}function Rn(e){if(!e.length){let o=he.workspace("temporary-uninitialized-workspace","Workspace","a0"),r=eo(o);return a(r)?r:(I({hasProjectDefinition:!1,mode:f.DEFAULT}),c("Booted uninitialized workspace placeholder",null))}if(!e.some(o=>o.action==="init.workspace"))return i("Initialized Epiq project has no workspace init event");let n=Tt(e).filter(a);return n.length>0?i(`Materializing failed:
44
+ ${n.map(o=>o.message).join(`
45
+ `)}`):(zm(),I({hasProjectDefinition:!0}),c("State booted successfully",null))}var no,Qo=h(()=>{"use strict";Ue();Q();C();Yt();T();yn();wt();Sn();no=qm()});var q,ps=h(()=>{"use strict";C();q=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});var ct,Zo,Gm,$a,gs=h(()=>{"use strict";Ua();Qo();Cn();et();Q();C();T();er();ps();fs();ct=null,Zo=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!ct,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),ct)return logger.debug("[sync] syncAndReloadState joining existing promise"),ct;logger.debug("[sync] syncAndReloadState creating promise"),ct=Gm();try{let e=await ct;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"),I({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}),ct||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),ct=null}},Gm=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=$a();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(ct)return ct;logger.debug("[sync] syncAndReloadState:start");let t=q("resolveActorId",re());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");I({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 o=q("syncEpiqWithRemote",await tr({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(o),message:(a(o),o.message)}),a(o))return logger.error("[sync] syncAndReloadState:sync failed",o.message),I({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),Ge(`Unable to sync state. ${o.message}`);let{stateBranchRoot:r}=o.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:r});let s=q("loadMergedEvents",Mt(r));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 I({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=$a();if(d)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:d.message,syncStatus:g().syncStatus}),d;let l=Fa(),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=q("bootStateFromEventLog",Rn(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(p),message:(a(p),p.message)}),a(p))return I({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"),I({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=q("restoreNavigationAnchor",Oa(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)?(I({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),m):(I({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),c("Synced",!0))},$a=()=>g().mode===f.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),I({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),i("Will not re-materialize if not in default mode, to not lose edit data"))});var An,ja,Wa,vs,ys,oo,hs,Ym,Ha,Xm,Ka,nr=h(()=>{"use strict";C();we();T();gs();An=3e3,ja=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<An?null:t},Wa=0,ys=!1,oo=!1,hs=()=>{if(ys)return!0;let e=ze();return a(e)?!1:e.value.syncStatus.status==="syncing"},Ym=()=>{let e=oe().autoSyncIntervalMs??1e4,t=Date.now()-Wa;return Math.max(0,e-t)},Ha=()=>{vs||(vs=setTimeout(async()=>{if(vs=void 0,!!Tn()){if(hs()){oo=!0;return}oo=!1,await Xm()}},Ym()))},Xm=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return i("Cannot auto-sync while peeking");if(!Tn())return i("Cannot auto-sync before state is initialized");if(hs())return oo=!0,i("Sync already in progress");ys=!0,Wa=Date.now(),I({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Zo()}finally{ys=!1,oo&&Ha()}},Ka=()=>{Tn()&&(oo=!0,!hs()&&Ha())}});var or,qa,Va,za,ro=h(()=>{"use strict";C();Ht();we();ue();or=()=>{let e=oe(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),o=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&o,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:o}},qa=()=>{let e=ot(process.cwd());if(a(e))return!1;let t=St(e.value);return pt(t)},Va=e=>e===!0?"on":e===!1?"off":null,za=e=>e==="on"?!0:e==="off"?!1:null});var Jm,Qm,Lt,Pt,rr,sr,so=h(()=>{"use strict";ne();C();ce();T();Jm=e=>e.props.tags??[],Qm=e=>e.props.assignees??[],Lt=e=>Jm(e).map(t=>x.getTag(t)).filter(t=>!!t),Pt=e=>Qm(e).map(t=>x.getContributor(t)).filter(t=>!!t),rr=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!M(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Lt(n))},sr=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!M(n)?i("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",Pt(n))}});var v,en=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 Zm,ep,tp,np,op,tn,Ga,ir,ar,Ya,rp,xs,io=h(()=>{"use strict";Zm=/^(\d+)(h|d|w|mo|y)$/,ep=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,tp=({year:e,month:t,day:n,hour:o=0,minute:r=0})=>{let s=new Date(e,t-1,n,o,r);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===o&&s.getMinutes()===r},np=(e,t=new Date)=>{let n=e.match(Zm);if(!n)return null;let[,o,r]=n,s=Number(o);if(!Number.isInteger(s)||s<=0)return null;let d=new Date(t);switch(r){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}},op=e=>{let t=e.match(ep);if(!t)return null;let[,n,o,r,s,d]=t,l=Number(n),u=Number(o),m=Number(r),p=s?Number(s):0,y=d?Number(d):0;return tp({year:l,month:u,day:m,hour:p,minute:y})?new Date(l,u-1,m,p,y):null},tn=e=>{let t=e.trim().toLowerCase();return np(t)??op(t)},Ga=/^(\d+)(s|m)?$/,ir=e=>{let t=e.trim().toLowerCase().match(Ga);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},ar=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),o=n.length>0&&Ga.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:o}},Ya=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,rp=[{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}],xs=(e=rp)=>{let t=[];for(let{unit:n,from:o,to:r}of e)for(let s=o;s<=r;s++)t.push(`${s}${n}`);return t}});var sp,ee,_e,ge,ip,ap,bs,Es,Qa,nn,dr,Is,Xa,dp,cp,ao,Ja,lp,up,mp,le,Dt=h(()=>{"use strict";nr();ro();Sn();ne();ce();T();Ho();so();en();io();sp=["BOARD","TICKET","SWIMLANE","COMMENT"],ee={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},_e={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},ge={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},ip=[ee.EDITOR,ee.VIEW,ee.USERNAME,ee.AUTOSYNC,ee.SYNC_DEBOUNCE_MS,ee.ATTACHMENT_MAX_KB,ee.LOG_LEVEL],ap=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[_e.TITLE,_e.DESCRIPTION];case"BOARD":case"SWIMLANE":return[_e.TITLE];case"COMMENT":return[_e.COMMENT];default:return[]}},bs=[String(An),"5000","15000","30000","60000"],Es=["250","500","1000"],Qa=["10s","20s","30s","45s"],nn=[v.COFFEE,v.EXIT,v.SYNC,v.HELP,v.EXPORT,v.CONFIG,v.YANK],dr=[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],Xa=[v.FILTER,v.PEEK,v.REPLAY],dp={WORKSPACE:[...nn,...dr],BOARD:[...Xa,...nn,...dr],SWIMLANE:[...Xa,...nn,...dr],TICKET:[...nn,...dr,...Is],FIELD:[...nn,...Is],FIELD_LIST:[...nn,...Is],TEXT:[...nn],COMMENT:[v.EDIT,v.DELETE,v.YANK]},cp=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],ao=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&M(n)),Ja=e=>e.parentNodeId===pe,lp=({selectedNode:e,breadCrumb:t})=>{let n=ap(e?.context);return ao({breadCrumb:t,selectedNode:e})?n.includes(_e.DESCRIPTION)?n:[...n,_e.DESCRIPTION]:n},up=({selectedNode:e,breadCrumb:t})=>{let n=ao({breadCrumb:t,selectedNode:e});return n?[ge.REF,ge.TITLE,...n.props?.description?.trim()?[ge.DESCRIPTION]:[],...Lt(n).length>0?[ge.TAGS]:[],...Pt(n).length>0?[ge.ASSIGNEES]:[]]:e?[ge.REF,ge.TITLE]:[]},mp=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:o}=or();if(!o)return[v.HELP,v.CONFIG];if(!qa())return[v.HELP,v.INIT];if(t)return[v.HELP,v.PEEK,v.REPLAY,v.EXPORT,v.CONFIG,v.YANK];let r=e?.context,s=r&&sp.includes(r),d=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?dp[u]:[]))],l=ao({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&&Lt(l).length>0):u===v.UNASSIGN?!!(l&&Pt(l).length>0):u===v.RE_OPEN_ISSUE?!!(l&&Ja(l)):u===v.CLOSE_ISSUE?!!(l&&!Ja(l)):!0)},le=(e,{contextNode:t,selectedNode:n,readOnly:o,breadCrumb:r}=g())=>{let s=t.context??"WORKSPACE";return{[v.NONE]:mp({breadCrumb:r,readOnly:o,selectedNode:n}),[v.EXIT]:["confirm"],[v.EXPORT]:[],[v.SYNC]:[],[v.INIT]:[],[v.HELP]:[],[v.PEEK]:[...xs(),"now","prev","next"],[v.REPLAY]:[...xs()],[v.EDIT]:lp({selectedNode:n,breadCrumb:r}),[v.YANK]:up({selectedNode:n,breadCrumb:r}),[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(In),...x.getExistingTags()])],[v.UNTAG]:[...rr()?.value?.map(({name:l})=>l)??[]],[v.UNASSIGN]:[...sr()?.value?.map(({name:l})=>l)??[]],[v.ASSIGN]:x.getExistingAssignees(),[v.NEW]:cp(s),[v.CONFIG]:[...ip],[v.COFFEE]:["1","3","5","20","custom"]}[e]??[]}});var Za,ed=h(()=>{"use strict";Za=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});var $e,Ft=h(()=>{"use strict";C();$e=(e,t)=>{let n=e.find(o=>o.context===t);return n!==void 0?c("Found node",n):i("Unable to find node in breadcrumb")}});import{accessSync as pp,copyFileSync as gp,existsSync as cr,mkdirSync as td,readdirSync as nd,readFileSync as fp,renameSync as vp,rmSync as yp,statSync as od,unlinkSync as hp,writeFileSync as xp}from"node:fs";import wn from"node:path";var Ns,je,Ss=h(()=>{"use strict";Ns=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",je={writeToFile:(e,t)=>{try{let n=wn.dirname(e);cr(n)||td(n,{recursive:!0});let o=typeof t=="string"?t:JSON.stringify(t,null,2);xp(e,o,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return fp(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=je.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 cr(e)&&od(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await pp(e),!0}catch{return!1}},mkDir:e=>td(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=wn.parse(t);for(;;){let o=wn.join(t,e);try{if(cr(o)&&od(o).isDirectory())return o}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=wn.dirname(t)}return null},readFirstJSON(e){try{if(!je.dirExists(e))return null;let t=nd(e).filter(o=>o.endsWith(".json")).sort()[0];if(!t)return null;let n=wn.join(e,t);return je.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return je.dirExists(e)?nd(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{hp(e)}catch(t){(!Ns(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{yp(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(wn.dirname(t)),!n?.overwrite&&cr(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{vp(e,t)}catch(o){if(Ns(o)&&o.code==="EXDEV"){gp(e,t),this.rmFile(e);return}throw o}}}});import Ip from"node:path";import{z as yt}from"zod";var bp,rd,Ep,sd,Cs,Rs,Np,id,ad,Ye,dd,on=h(()=>{"use strict";ue();C();Ss();bp={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},rd=yt.object({logLevel:yt.enum(["info","error","debug"]),preferredEditor:yt.string().optional(),userName:yt.string().optional(),userId:yt.string().optional(),autoSync:yt.boolean().nullable().optional(),autoSyncDebounceMs:yt.number().optional(),attachmentMaxKb:yt.number().optional(),viewMode:yt.enum(["dense","wide"]).optional()}).partial(),Ep="config.json",sd=_n,Cs=()=>Ip.join(sd(),Ep),Rs=()=>{try{return je.mkDir(sd()),c(`Ensured ~/${Je} exists`,null)}catch{return i(`Unable to create ~/${Je}`)}},Np=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${Je}/config.json JSON`)}let n=rd.safeParse(t??{});return n.success?c("Parsed config",n.data):i(`Invalid ~/${Je}/config.json shape: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},id=()=>{let e=Rs();if(a(e))return i(e.message);let t=Cs(),n=je.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Np(n)},ad=e=>{let t=Rs();if(a(t))return i(t.message);let n=rd.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`);let o=Cs();try{return je.writeToFile(o,JSON.stringify(n.data,null,2)+`
46
+ `),c("Config written",null)}catch{return i(`Unable to write ~/${Je}/config.json`)}},Ye=e=>{let t=id();if(a(t))return i("Failed to read existing config");let n={...t.value,...e};return ad(n)},dd=()=>{let e=Cs(),t=Rs();if(a(t))return i(`Unable to create ~/${Je}`);if(!(je.readFile(e)!==null)){let N=ad(bp);if(a(N))throw new Error(`Unable to create ~/${Je}/config.json`)}let o=id();if(a(o))throw new Error(o.message||"Unable to load settings");let{preferredEditor:r,userName:s,userId:d,autoSync:l,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:y}=o.value;return!s||!d?i(`User name or ID not configured in ~/${Je}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,c("successfully loaded settings",{logLevel:p??"debug",preferredEditor:r??"",userName:s,userId:d,autoSync:l??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:y??"dense"}))}});var co,As,lo=h(()=>{"use strict";Ft();C();ue();co=500,As=(e,t)=>`${e}.${t}`});import Sp from"zod";var uo,mo,cd,Ts=h(()=>{"use strict";on();lo();Q();C();fe();we();T();uo=50,mo=5e3,cd=()=>{let e=Y().commandMeta.inputString,t=Sp.coerce.number().int().min(uo).max(mo).safeParse(e);if(!t.success)return i(`Attachment size cap must be ${uo}-${mo} KB (default ${co})`);let n=Ye({attachmentMaxKb:t.data});return a(n)?n:(Ve({attachmentMaxKb:t.data}),I({mode:f.DEFAULT}),c(`Attachment size cap set to ${t.data} KB`,null))}});import ld from"chalk";var X,Ie,be,ud=h(()=>{"use strict";ft();Me();X=e=>ld.dim(e),Ie=e=>ld.hex(S.primary)(e),be=({prefix:e="",wordList:t,postfix:n="",noOfHints:o=100,inputString:r,minLengthForHints:s=1})=>{let d=r.trim();if(d.length<s)return"";let p=[...t.filter(Boolean).filter(y=>y.startsWith(d))].sort((y,N)=>Ko(y)-Ko(N)).slice(0,o).map(y=>qo(y)).join(" ");return p?`${X(e)}${p}${X(n)}`:""}});var Bt,lr=h(()=>{"use strict";Bt={None:"none",Invalid:"invalid",Valid:"valid"}});import gd from"chalk";var Mn,Cp,md,te,W,O,mr,pd,ur,ws,Rp,rn,Ap,Tp,wp,Mp,fd,Ms=h(()=>{"use strict";nr();ro();ed();Xt();Ft();C();ce();we();Ts();lo();T();ft();so();Nn();ud();en();lr();Dt();io();Mn=140,Cp=["BOARD","TICKET","SWIMLANE"],md=()=>{let e=g().selectedNode;if(!e?.context)return O({message:X("Missing target context")});if(Cp.includes(e.context))return W();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===xe(t?.parentNodeId??"","comments"))return W()}return O({message:X("Command not available in this context")})},te="<ENTER> to confirm",W=(e="",t=[])=>({message:X(e),validity:Bt.Valid,completionWordList:t}),O=({message:e,completionWordList:t=[]})=>({validity:Bt.Invalid,message:e,completionWordList:t}),mr=e=>e.length===0,pd=(e,t)=>{let n=$e(g().breadCrumb,"BOARD");if(a(n))return O({message:Ie("Command is not applicable in this context")});let o=ca(n.value.id);return a(o)?O({message:Ie(`Unable to ${t}: board id is not a valid ULID`)}):Ya({date:e,horizonDate:o.value})?null:O({message:Ie(`nothing to ${t} before ${o.value.toISOString().slice(0,16).replace("T"," ")}`)})},ur=e=>` ${gd.hex("#000").bgHex(Pe(e))(` ${e} `)} `,ws=({modifier:e})=>{let t="confirm";return e===t?W(te):O({message:mr(e)?X("if you are certain, enter ")+qo(t):"",completionWordList:[t]})},Rp=({list:e,hint:t,onValue:n})=>({modifier:o,inputString:r})=>e.includes(o)?r.trim().length<1?O({message:X(n)}):W():O({message:mr(o)?t:"",completionWordList:[...e]}),rn=({hint:e,onOk:t})=>({modifier:n,inputString:o})=>mr(n)&&mr(o)?O({message:e,completionWordList:[]}):W(t??te),Ap=({modifier:e,inputString:t})=>{let n=le(v.CONFIG);if(!n.includes(e))return O({message:be({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ee.EDITOR:{let o=[...Za];return t.trim()?o.includes(t.trim())?W(te):O({message:be({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o}):O({message:be({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case ee.VIEW:{let o=["dense","wide"];return o.includes(t.trim())?W(te):O({message:be({prefix:"view... ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case ee.USERNAME:return t.trim()?W(te):O({message:Ie("Enter a user name. Saved in ")+gd.bgBlack("~/.epiq-global/config.json")});case ee.LOG_LEVEL:{let o=["debug","error","info"],r=t.trim();return o.includes(r)?W(te):O({message:be({prefix:"one of: ",wordList:[...o],inputString:r,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...o]})}case ee.AUTOSYNC:{let o=["on","off"],r=oe().autoSync;if(!o.includes(t.trim())){let s=Va(r);return O({message:be({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:o,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:o})}return W(te)}case ee.ATTACHMENT_MAX_KB:{let o=oe().attachmentMaxKb,r=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(r)||r<uo||r>mo){let s=be({prefix:" examples: ",wordList:Es,minLengthForHints:0,inputString:t});return O({message:Ie(`provide a size cap in KB (${uo}-${mo}). current: ${o??co} KB.`)+s,completionWordList:Es})}return W(te)}case ee.SYNC_DEBOUNCE_MS:{let o=oe().autoSyncIntervalMs,r=ja(t);if(!t.trim()||r===null||r<An){let s=be({prefix:" examples: ",wordList:bs,minLengthForHints:0,inputString:t});return O({message:Ie(`provide duration above ${An}ms. current duration: ${o}ms.`)+s,completionWordList:bs})}return W(te)}default:return O({message:Ie("Unknown config option"),completionWordList:n})}},Tp=({modifier:e,inputString:t})=>{let n=le(v.EDIT);if(!n.length)return O({message:Ie("Command not available in this context")});if(!n.includes(e)){let o=be({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return O({message:o||Ie("Unknown edit option"),completionWordList:n})}switch(e){case _e.COMMENT:return t.trim()?W(te):O({message:X("write a comment...")});case _e.TITLE:return W(te);case _e.DESCRIPTION:{let{preferredEditor:o}=oe();return o?W(X("<ENTER> to edit in ")+o):O({message:"No editor selected"})}default:return O({message:Ie("Unknown edit option"),completionWordList:n})}},wp=({modifier:e})=>{let t=le(v.YANK);return t.length?t.includes(e)?W(te+X(" and copy to clipboard")):O({message:be({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):O({message:Ie("Nothing selected to copy from")})},Mp={[v.EXPORT]:()=>W(te+X(", and create export markdown file")),[v.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return W(te);let n={message:X("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},o=t||e.inputString.trim(),r=tn(o);if(!o||!r)return O(n);let s=pd(r,"peek");return s||W(te)},[v.REPLAY]:e=>{let{dateInput:t,durationInput:n}=ar(e.modifier,e.inputString),o={message:X("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},r=tn(t);if(!t||!r)return O(o);let s=pd(r,"replay");return s||(n&&ir(n)===null?O({message:Ie("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):W("<ENTER> to replay board history",n?Qa:[]))},[v.EXIT]:()=>W(te+X(" and exit the application")),[v.INIT]:()=>W(te),[v.PALETTE]:()=>W(te),[v.FILTER]:e=>{if(e.modifier==="clear")return W(te);let t=s=>le(v.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return O({message:be({wordList:le(v.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:le(v.FILTER)});let n=Object.values(g().tags).map(s=>s.name),o=Object.values(g().contributors).map(s=>s.name),r=e.modifier==="tag"?n:e.modifier==="assignee"?o:[];return e.inputString?r.length&&!r.includes(e.inputString.trim())?O({message:be({prefix:`existing ${e.modifier}s... `,wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r}):W():O({message:be({prefix:"one of... ",wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r})},[v.NONE]:e=>{let t=le(v.NONE);return O({message:be({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[v.NEW]:e=>Rp({list:le(v.NEW),hint:be({wordList:le(v.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[v.HELP]:()=>W(te),[v.EDIT]:Tp,[v.COMMENT]:e=>{let t=rn({hint:X(`write a comment (max ${Mn} char)...`),onOk:X(`(${e.inputString.length}/${Mn})`)})(e);return t.validity===Bt.Invalid?t:e.inputString.length>Mn?W(Ie("max input exceeded")):t},[v.CONFIG]:Ap,[v.YANK]:wp,[v.DELETE]:e=>{let t=md();return t.validity==="invalid"?t:ws(e)},[v.CLOSE_ISSUE]:e=>ws(e),[v.RE_OPEN_ISSUE]:e=>ws(e),[v.MOVE]:e=>{let t=md();return t.validity==="invalid"?t:rn({hint:be({prefix:"hey hacker! These commands are blocked for you... ",wordList:le(v.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[v.TAG]:e=>{let n=x.getExistingTags().slice(0,10).map(ur).join("");return rn({hint:n.length?X("create tag or reuse:")+n+X(""):X("create tag ...")})(e)},[v.UNTAG]:e=>{let t=rr();if(a(t))return O({message:Ie("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(ur).slice(0,10);return n.length?rn({hint:X(" ... ")+n.join("")})(e):O({message:Ie("Issue has no tags"),completionWordList:[]})},[v.ASSIGN]:e=>{let t=x.getExistingAssignees().map(ur).slice(0,10);return rn({hint:X("assignees... ")+t.join("")})(e)},[v.UNASSIGN]:e=>{let t=sr();if(a(t))return O({message:Ie("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(ur).slice(0,10);return n.length?rn({hint:X("remove assignee... ")+n.join("")})(e):O({message:Ie("Issue has no assignees"),completionWordList:[]})},[v.SYNC]:()=>W(te),[v.COFFEE]:e=>{let{modifier:t}=e,n=le(v.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?O({message:X("enter an amount ... "),completionWordList:n.filter(o=>o.startsWith(t))}):rn({hint:be({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},fd=Object.fromEntries(Object.entries(Mp).map(([e,t])=>[e,{validate:(n,o,r)=>t({modifier:o,command:n,inputString:r})}]))});var pr,vd=h(()=>{"use strict";pr=["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 kp,Lp,Pp,Dp,Fp,yd,hd,xd,Id=h(()=>{"use strict";C();T();vd();kp=3,Lp=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"]),Pp=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let o=n.props;typeof o.description=="string"&&t.push(o.description),typeof o.value=="string"&&t.push(o.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},Dp=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=kp&&!Lp.has(t)&&!/^\d+$/.test(t)),Fp=e=>{let t=new Map;for(let s of Pp(e))for(let d of Dp(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),o=new Set(n),r=pr.filter(s=>!o.has(s));return[...n,...r]},yd=pr,hd=-1,xd=()=>{let e=ze();if(a(e))return pr;let t=e.value,n=t.eventLog.length;return n!==hd&&(yd=Fp(t),hd=n),yd}});var bd,Ed,ks=h(()=>{"use strict";Ji();Dt();en();Ms();Id();T();Q();bd=e=>Object.values(v).includes(e),Ed=(e,t)=>{let n=e.command??"",{modifier:o,target:r,inputString:s}=e,{message:d,validity:l,completionWordList:u}=fd[n].validate(n,o,s),m=n!==v.PEEK&&n!==v.REPLAY,p=r==="command"||r==="modifier"?le(n):m?xd():[],{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?Xi(e,R):{hint:"",hints:[],remainder:"",overlap:0}}}});var Nd,Bp,Op,Up,Sd=h(()=>{"use strict";ks();Dt();Nd=e=>{let t=e.trimStart(),n=Op(t),o=n[0]??"",r=n[1]??"",s=/\s$/.test(e),d=Up(e),l=bd(o)?o:null,u=l!==null,m=o!=="",p=l?le(l)??[]:[],y=l&&p.includes(r)?r:"",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,w=Bp(t,l,y);return{raw:e,trimmedStart:t,words:n,firstWord:o,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:s,modifier:y,target:N,inputToMatch:R,inputString:w}},Bp=(e,t,n)=>{let o=e;return t&&o.startsWith(t)&&(o=o.slice(t.length)),o=o.replace(/^\s+/,""),n&&o.startsWith(n)&&(o=o.slice(n.length),o=o.replace(/^\s+/,"")),o},Op=e=>e.trim()?e.trim().split(/\s+/):[],Up=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as sE}from"react";var kn,Ls,Ln,_p,Cd,lt,po,Ps,Ds,Rd,Ad,gr,Td,j,wd,Md,kd,Y,Ld,fe=h(()=>{"use strict";ks();Sd();C();lr();kn=e=>e===Ls||e===":",Ls=" ",Ln={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Bt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},_p=new Set,Cd=()=>{for(let e of _p)e()},lt=e=>{let n=e(Ln),o=Nd(n.value),r=n.cursorPosition===n.value.length;Ln={...n,commandMeta:Ed(o,r)},Cd()},po=({message:e,status:t})=>{let n=structuredClone(Ln);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Ln=n,Cd(),c(e,null)},Ps=e=>{lt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Ds=e=>{lt(t=>{let{value:n,cursorPosition:o}=t,r=o;if(e==="left"){for(;r>0&&kn(n[r-1]);)r--;for(;r>0&&!kn(n[r-1]);)r--}else{for(;r<n.length&&!kn(n[r]);)r++;for(;r<n.length&&kn(n[r]);)r++}return{...t,cursorPosition:r}})},Rd=()=>{lt(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}})},Ad=()=>{lt(e=>{let{value:t,cursorPosition:n}=e,o=n;for(;o>0&&kn(t[o-1]);)o--;for(;o>0&&!kn(t[o-1]);)o--;let r=t.slice(n);return{...e,value:t.slice(0,o)+r,cursorPosition:o,commandIsPending:!1}})},gr=e=>{lt(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),o=t.value.slice(0,n),r=t.value.slice(n),s=e(o,t.commandMeta.autoCompletion),d=s+r,l=Math.max(0,Math.min(s.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},Td=()=>{lt(e=>({...e,commandIsPending:!0}))},j=e=>{lt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},wd=({addToHistory:e=!0})=>{lt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Md=()=>{lt(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}})},kd=()=>{lt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Y=()=>Ln,Ld=()=>{let[e,...t]=Ln.value.split(Ls);return t.join(Ls).trim()}});var A,zt=h(()=>{"use strict";Q();Hi();T();fe();we();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 Pd,k,Fs=h(()=>{"use strict";T();en();Pd=e=>{let{context:t}=g().contextNode;if(!t)return k.None;switch(e){case v.EXIT:return k.Exit;case v.EXPORT:return k.Export;case v.COFFEE:return k.Coffee;case v.INIT:return k.Init;case v.DELETE:return k.Delete;case v.EDIT:return k.Edit;case v.COMMENT:return k.Comment;case v.HELP:return k.ViewHelp;case v.RE_OPEN_ISSUE:return k.ReopenIssue;case v.CLOSE_ISSUE:return k.CloseIssue;case v.TAG:return k.TagTicket;case v.UNTAG:return k.UntagTicket;case v.ASSIGN:return k.AssignUserToTicket;case v.UNASSIGN:return k.UnassignUserFromTicket;case v.NEW:return k.NewItem;case v.FILTER:return k.Filter;case v.MOVE:return k.Move;case v.PEEK:return k.Peek;case v.REPLAY:return k.Replay;case v.CONFIG:return k.Config;case v.YANK:return k.Yank;case v.SYNC:return k.Sync;default:return k.None}},k={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 Dd}from"ink";import Fd,{useEffect as Bd,useState as $p}from"react";var Od,De,Pn=h(()=>{"use strict";T();Me();Od={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},De=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Fe(),o=Od[n]??Od.default,[r,s]=$p(0);if(Bd(()=>{s(0)},[o]),Bd(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%o.length)},500);return()=>clearInterval(l)},[e,o]),!e)return Fd.createElement(Dd,null,t);let d=o[r]??o[0]??t;return Fd.createElement(Dd,{color:S.accent,dimColor:r===1},d)}});import{Box as Bs,Text as jp}from"ink";import fr from"react";var Ot,go=h(()=>{"use strict";Me();Ot=({children:e=[],height:t,selectedIndex:n,itemHeight:o=1,scrollByOne:r=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),d=Math.max(1,Math.ceil(o)),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=r?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,w=s,L=R?Math.max(1,Math.floor(l/e.length*w)):w,$=Math.max(0,w-L),ie=Math.max(1,e.length-l),ae=R?Math.floor(p/ie*$):0;return fr.createElement(Bs,{flexDirection:"row",height:s,width:"100%"},fr.createElement(Bs,{flexDirection:"column",flexGrow:1,height:s},N),fr.createElement(Bs,{flexDirection:"column",width:1,height:w},Array.from({length:w}).map((V,He)=>fr.createElement(jp,{key:He,color:R&&He>=ae&&He<ae+L?S.accent:S.secondary},R?"\u2502":" "))))}});import{Text as Wp}from"ink";import Hp from"react";var Kp,qp,Dn,vr=h(()=>{"use strict";Ho();ft();ce();Kp=e=>e.toLowerCase().trim(),qp=(e,t=In)=>{let n=Kp(e);return t[n]?t[n]:Zn(n)},Dn=({id:e,isSelected:t})=>{let n=x.getContributor(e);if(n)return Hp.createElement(Wp,{underline:t,color:qp(n.name)},"@"+n.name)}});import{Text as Vp}from"ink";import zp from"react";var yr,Os=h(()=>{"use strict";ce();Me();ft();yr=({id:e,isSelected:t})=>{let n=x.getTag(e);if(n)return zp.createElement(Vp,{underline:t,backgroundColor:Pe(n.name),color:S.secondary}," "+n.name+" ")}});import{useEffect as Gp,useState as Yp}from"react";var Xp,Ud,hr,fo,Jp,Qp,Fn,xr=h(()=>{"use strict";ft();Xp=80,Ud=1400,hr=new Set,fo=null,Jp=e=>(hr.add(e),fo||(fo=setInterval(()=>{for(let t of hr)t()},Xp)),()=>{hr.delete(e),hr.size===0&&fo&&(clearInterval(fo),fo=null)}),Qp=()=>{let e=Date.now()%Ud/Ud;return e<.5?e*2:(1-e)*2},Fn=e=>{let[,t]=Yp(0);return Gp(()=>{if(e)return Jp(()=>t(n=>n+1))},[e]),aa(Qp())}});import{Box as Bn,Text as Ir}from"ink";import Xe from"react";var Zp,_d,$d=h(()=>{"use strict";Me();fn();xn();so();vr();Os();xr();Zp=(e,t)=>{if(e.length<=t)return[e,null];let n=e.lastIndexOf(" ",t),o=n>0?n:t;return[e.slice(0,o),Qn(e.slice(o).trim(),t)]},_d=({width:e,ticket:t,isSelected:n,isFlashing:o=!1})=>{let r=Fn(o),s=e-4,[d,l]=Zp(qe(t.title),s),u=l?null:Qn(qe(t.props.description),s)||null,m=Lt(t),p=Pt(t);return Xe.createElement(Bn,{borderStyle:"round",height:5,flexDirection:"column",borderDimColor:!n,borderColor:o?r:n?S.accent:S.secondary,justifyContent:"space-between"},Xe.createElement(Bn,{paddingLeft:1,flexDirection:"column"},Xe.createElement(Ir,{color:S.primary},d),l&&Xe.createElement(Ir,{color:S.primary},l),u&&Xe.createElement(Ir,{color:S.secondary2,dimColor:!0},u)),Xe.createElement(Bn,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1,paddingRight:1},Xe.createElement(Bn,{flexDirection:"row"},m.map(y=>Xe.createElement(Bn,{paddingRight:1,key:y.id},Xe.createElement(yr,{key:y.id,id:y.id}))),p.map(y=>Xe.createElement(Bn,{paddingRight:1,key:y.id},Xe.createElement(Dn,{key:y.id,id:y.id})))),Xe.createElement(Ir,{wrap:"truncate",color:S.secondary2,dimColor:!0},Ze(t.id))))}});import{Box as sn,Text as vo}from"ink";import We from"react";var eg,jd,Wd=h(()=>{"use strict";Q();ce();Me();ft();Pn();xr();eg=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,jd=({width:e,ticket:t,isSelected:n,isFlashing:o=!1,index:r,mode:s})=>{let d=Fn(o),l=(t.props.tags??[]).map(V=>x.getTag(V)).filter(V=>!!V),u=(t.props.assignees??[]).map(V=>x.getContributor(V)).filter(V=>!!V),m=1,p=l.length*(1+m),y=u.length*(2+m),N=l.map(V=>We.createElement(sn,{key:V.id,paddingRight:m},We.createElement(vo,{color:Pe(V.name)},"\u25A0"))),R=u.map(V=>We.createElement(sn,{key:V.id,paddingRight:m},We.createElement(vo,{color:Zn(V.name)},"@"+V.name.at(0)))),w=o?d:n?S.accent:s===f.MOVE?S.secondary:S.primary,L=4,$=x.getCommentsByIssue(t.id),ie=$.length?String($.length).length+2+m:0,ae=$.length?We.createElement(sn,{paddingRight:m},We.createElement(vo,{color:S.accent},"[",$.length,"]")):null;return We.createElement(sn,{borderBottom:!0,justifyContent:"space-between"},We.createElement(sn,null,We.createElement(sn,{width:L},n?We.createElement(De,{isSelected:n}):We.createElement(vo,{color:"gray",dimColor:!0},r+1)),We.createElement(vo,{wrap:"truncate",color:w},eg(t.title,e-p-y-ie-18))),We.createElement(sn,null,N,R,ae))}});import tg from"chalk";import{Box as Us,Text as ng}from"ink";import ut from"react";var og,Hd,Kd=h(()=>{"use strict";ne();T();Me();Pn();go();$d();Wd();xr();og=({swimlane:e,isSelected:t,width:n,height:o,isDense:r,isFocused:s,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u,replay:m}=Fe(),p=u[e.id]??[],y=m?new Set(m.flashNodeIds):null,N=y?.has(e.id)??!1,R=Fn(N),w=`${e.title} ${tg.hex(S.secondary2).dim("("+p.length+")")}`,L=3,$=r?1:5,ie=s&&d===-1,ae=n-(ie?7:5),V=o-L-(r?2:1),He=ut.createElement(Us,{borderStyle:"round",borderColor:S.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},ut.createElement(De,{isSelected:t}),ut.createElement(ng,{bold:!0,color:N?R:t?S.accent:S.primary},w," ",e.readonly?"\u{1F512}":"")),ln=(U,H)=>{let un=s&&d===H;if(!M(U))return null;let Wt=y?.has(U.id)??!1;return r?ut.createElement(jd,{key:U.id,index:H,width:n,ticket:U,isSelected:un,isFlashing:Wt,mode:l}):ut.createElement(_d,{key:U.id,width:ae,ticket:U,isSelected:un,isFlashing:Wt})};return ut.createElement(Us,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?S.accent:S.secondary,paddingRight:1,paddingLeft:1,height:o},He,ut.createElement(Us,{padding:r?1:0},p.length>0&&ut.createElement(Ot,{selectedIndex:d,height:V,itemHeight:$},p.map(ln)),ie&&ut.createElement(De,{isSelected:!0})))},Hd=ut.memo(og)});var qd,Vd,_s=h(()=>{"use strict";Yt();qd=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},Vd=(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 On,Text as ht}from"ink";import Ae,{useEffect as rg,useMemo as sg,useRef as ig}from"react";import{decodeTime as $s}from"ulid";function Gd({ticket:e,width:t,height:n}){let o=sg(()=>dg(e),[e]),r=ig([]);rg(()=>(zd(r.current),r.current=lg(e,o),()=>{zd(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=Fe(),l=Math.max(1,n-4),u=Math.max(12,t-32);return o.length===0?Ae.createElement(On,{flexDirection:"column",width:t,height:n,padding:1},Ae.createElement(ht,{color:S.primary},"No attachments yet."),Ae.createElement(On,{paddingTop:1},Ae.createElement(ht,{color:S.primary},"Attach images from the browser GUI"),Ae.createElement(ht,{color:S.accent}," epiq gui "),Ae.createElement(ht,{color:S.primary},"by dropping or pasting them."))):Ae.createElement(On,{flexDirection:"column",width:t,height:n},Ae.createElement(On,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:S.secondary,borderStyle:"single",paddingBottom:1},Ae.createElement(ht,{color:S.secondary2},"Attachments (",o.length,") \u2014 enter to open"," ")),Ae.createElement(Ot,{height:l,itemHeight:2,selectedIndex:s},o.map((m,p)=>{let y=p===s,N=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return Ae.createElement(On,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},Ae.createElement(ht,{color:S.accent},y?"\u276F ":" "),Ae.createElement(On,{paddingLeft:1},Ae.createElement(ht,{color:S.secondary2},`#${p+1} `),Ae.createElement(ht,{color:y?S.accent:S.primary},N),Ae.createElement(ht,{color:S.secondary2}," "+ug(m.bytes)+" "+bn($s(m.id)))))})))}var ag,dg,zd,cg,lg,ug,Yd=h(()=>{"use strict";Ue();Xt();ne();C();ce();Yt();T();Me();Nn();go();ag=e=>xe(e,"attachments"),dg=e=>x.getAttachmentsByIssue(e.id).sort((t,n)=>$s(t.id)-$s(n.id)),zd=e=>{for(let t of e)x.deleteNode(t.id)},cg=(e,t,n)=>he.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),lg=(e,t)=>{let n=x.getNode(ag(e.id));if(!n||!Be(n))return[];let o=t.map((r,s)=>cg(r,s,n.id)).map(r=>x.createNode(r)).filter(pt).map(({value:r})=>r).filter(Be);return t.length>0&&g().selectedIndex<0&&F.navigate({contextNode:n,selectedIndex:0}),o},ug=e=>`${Math.max(1,Math.round(e/1024))} KB`});import{Box as Ut,Text as xt}from"ink";import ve,{useEffect as mg,useMemo as pg,useRef as gg}from"react";import{decodeTime as js}from"ulid";function Jd({ticket:e,width:t,height:n}){let o=pg(()=>vg(e),[e]),r=gg([]);mg(()=>(Xd(r.current),r.current=yg(e,o),()=>{Xd(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=Fe(),l=Math.max(1,n-4),u=Math.max(20,t-8);return o.length===0?ve.createElement(Ut,{flexDirection:"column",width:t,height:n,padding:1},ve.createElement(xt,{color:S.primary},"No comments yet."),ve.createElement(Ut,{paddingTop:1},ve.createElement(xt,{color:S.primary},"Use"),ve.createElement(xt,{color:S.accent}," :comment "),ve.createElement(xt,{color:S.primary},"to add the first one."))):ve.createElement(Ut,{flexDirection:"column",width:t,height:n},ve.createElement(Ut,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:S.secondary,borderStyle:"single",paddingBottom:1},ve.createElement(xt,{color:S.secondary2},"Comments (",o.length,") ")),ve.createElement(Ot,{height:l,itemHeight:4,selectedIndex:s},o.map((m,p)=>{let y=p===s;return ve.createElement(Ut,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:S.secondary,borderStyle:"single"},ve.createElement(Ut,{flexDirection:"row",paddingBottom:1},ve.createElement(xt,{color:S.accent},y?"\u276F ":" "),ve.createElement(Ut,{paddingLeft:1},ve.createElement(xt,{color:S.secondary2},`#${p+1} `),ve.createElement(Dn,{id:m.authorId}),ve.createElement(xt,{color:S.secondary2}," "+bn(js(m.id))))),ve.createElement(Ut,{paddingLeft:3,paddingBottom:1},ve.createElement(xt,{color:S.primary},hg(m.md,u))))})))}var fg,vg,Xd,yg,hg,Qd=h(()=>{"use strict";Ue();Xt();ne();C();ce();T();Me();Nn();vr();go();_s();fg=e=>xe(e,"comments"),vg=e=>x.getCommentsByIssue(e.id).sort((t,n)=>js(t.id)-js(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),Xd=e=>{for(let t of e)x.deleteNode(t.id)},yg=(e,t)=>{let n=x.getNode(fg(e.id));if(!n||!Be(n))return[];let o=t.map((r,s)=>Vd(r,s,n.id)).map(x.createNode).filter(pt).map(({value:r})=>r).filter(Jn);return t.length>0&&g().selectedIndex<0&&F.navigate({contextNode:n,selectedIndex:0}),o},hg=(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 br,Text as xg}from"ink";import It from"react";var Zd,ec=h(()=>{"use strict";ne();ce();hn();T();Me();vr();Pn();Os();Zd=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:o}=Fe(),{title:r}=t,s=t.parentNodeId?x.getNode(t.parentNodeId):void 0,d=s&&M(s)?r===z.ASSIGNEES?s.props.assignees??[]:r===z.TAGS?s.props.tags??[]:[]:[];return It.createElement(br,{alignItems:"center",paddingTop:1},It.createElement(br,{minWidth:12},It.createElement(De,{isSelected:n}),It.createElement(xg,{color:n?S.accent:S.secondary2},r,":")),It.createElement(br,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=o.id===t.id&&u===e;return It.createElement(br,{key:`${r}-${l}`,paddingRight:2,minHeight:1},It.createElement(De,{isSelected:m}),r===z.ASSIGNEES?It.createElement(Dn,{isSelected:m,id:l}):r===z.TAGS?It.createElement(yr,{isSelected:m,id:l}):null)})))}});import{Box as Er,Text as Ws}from"ink";import bt,{useEffect as Ig,useMemo as tc}from"react";var bg,nc,Hs,oc,Eg,Ks,rc=h(()=>{"use strict";ce();C();Yt();T();Me();fn();Pn();go();yn();bg="\u2029",nc=(e,t)=>`${e}::inline-line::${t}`,Hs=new Map,oc=e=>{let t=Hs.get(e)??[];Hs.delete(e);for(let n of t)x.deleteNode(n)},Eg=(e,t)=>{oc(e);let n=[];t.forEach((o,r)=>{let s=Oe(BigInt(r+1));if(!pt(s))return;let d=x.createNode(he.text({id:nc(e,r),name:`Line ${r+1}`,parentNodeId:e,rank:s.value,props:{value:o},readonly:!0,isVirtual:!0}));pt(d)&&n.push(d.value.id)}),Hs.set(e,n)},Ks=({id:e,label:t,text:n,height:o,selected:r,maxWidth:s})=>{let{selectedIndex:d,contextNode:l}=Fe(),u=tc(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=tc(()=>u.join("\0"),[u]);Ig(()=>(Eg(e,u),()=>{oc(e)}),[e,m]);let p=N=>String(N).replace(/\r?\n/g,""),y=u.map((N,R)=>{let w=l.id===e&&d===R;return bt.createElement(Er,{key:nc(e,R)},bt.createElement(Ws,{color:w?S.primary:S.secondary2,dimColor:!w},`${R+1} `.padStart(5,"\xA0")),bt.createElement(Ws,{backgroundColor:w?"gray":void 0},p(N.length?Qn(N,s-10):bg)))});return bt.createElement(Er,{flexDirection:"column",paddingTop:1},bt.createElement(Er,null,bt.createElement(De,{isSelected:r}),bt.createElement(Ws,{color:r?S.accent:S.secondary2},t)),bt.createElement(Er,{flexDirection:"row",borderStyle:"round",borderColor:S.secondary,paddingLeft:1,marginLeft:1},bt.createElement(Ot,{scrollByOne:!0,height:o-3,selectedIndex:d,itemHeight:1},y)))}});import{Box as an,Text as qs}from"ink";import Ee,{useMemo as yo}from"react";var Ng,Sg,Cg,Rg,sc,ic=h(()=>{"use strict";ne();ce();T();Me();_s();Nn();Yd();Qd();Pn();ec();rc();Ng=e=>xe(e,"description"),Sg=e=>xe(e,"comments"),Cg=e=>xe(e,"history"),Rg=e=>xe(e,"attachments"),sc=({ticket:e,height:t})=>{let n=yo(()=>qd(e),[e]),{selectedIndex:o,contextNode:r}=Fe(),s=process.stdout.columns||120,d=yo(()=>Ng(e.id),[e.id]),l=yo(()=>Sg(e.id),[e.id]),u=yo(()=>Cg(e.id),[e.id]),m=yo(()=>Rg(e.id),[e.id]),p=x.getAttachmentsByIssue(e.id).length,y=r.id===e.id,N=r.id===l||r.parentNodeId===l,R=r.id===u||r.parentNodeId===u,w=r.id===m||r.parentNodeId===m,L=G(e.id);if(N){let H=t-3;return Ee.createElement(an,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ee.createElement(Jd,{ticket:e,width:s,height:H}))}if(w){let H=t-3;return Ee.createElement(an,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ee.createElement(Gd,{ticket:e,width:s,height:H}))}if(R){let U=x.getNode(u),H=U&&Be(U)?U.props.value??"":"",Wt=t-3;return Ee.createElement(an,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},U?Ee.createElement(Ks,{id:U.id,label:"Event log",text:H,selected:!1,maxWidth:s,height:Wt}):null)}let $=L.reduce((U,H)=>Xn(H)||H.id===l||H.id===m||H.id===u?U+1:U,0),ie=2,ae=3,V=$,He=t-ae-V-ie,ln=(U,H)=>U.id===d?Ee.createElement(Ks,{key:U.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:H,maxWidth:s,height:He}):Xn(U)?Ee.createElement(Zd,{key:U.id,parent:U,selected:H,selectedIndex:o}):U.id===l?Ee.createElement(an,{key:U.id,paddingTop:1},Ee.createElement(De,{isSelected:H}),Ee.createElement(qs,{backgroundColor:S.secondary,color:H?S.accent:S.primary},` Comments (${n}) \u203A\u203A `)):U.id===m?Ee.createElement(an,{key:U.id,paddingTop:1},Ee.createElement(De,{isSelected:H}),Ee.createElement(qs,{backgroundColor:S.secondary,color:H?S.accent:S.primary},` Attachments (${p}) \u203A\u203A `)):U.id===u?Ee.createElement(an,{key:U.id,paddingTop:1},Ee.createElement(De,{isSelected:H}),Ee.createElement(qs,{backgroundColor:S.secondary,color:H?S.accent:S.primary}," History \u203A\u203A ")):null;return Ee.createElement(an,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},L.map((U,H)=>ln(U,y&&o===H)))}});import{Box as Ag}from"ink";import Nr from"react";var Tg,ac,dc=h(()=>{"use strict";ne();Kd();ic();Tg=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,viewMode:s,height:d,width:l})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,p=u===P.BOARD||u===P.SWIMLANE,y=u===P.TICKET?t:o.find($=>$.context===P.TICKET),N=Math.floor(l/3),R=Math.floor(l/Math.max(e.length,1)),w=Math.min(R,N),L=s==="dense";return Nr.createElement(Ag,{flexDirection:"row",height:d},p&&e.map(($,ie)=>{let ae=t.id===$.id,V=ae?n:-1,He=t.context===P.BOARD&&n===ie;return Nr.createElement(Hd,{key:$.id,height:d,width:w,swimlane:$,isSelected:He,isDense:L,isFocused:ae,listSelectedIndex:V,mode:r})}),m&&y&&Nr.createElement(sc,{height:d,ticket:y}))},ac=Nr.memo(Tg)});import cc from"node:fs";import wg from"node:path";import Mg from"react";import{render as kg}from"ink";import{Writable as Lg}from"node:stream";var ho,Pg,Dg,Fg,Bg,lc,uc=h(()=>{"use strict";dc();ne();C();T();ue();we();ho=e=>String(e).padStart(2,"0"),Pg=e=>{let t=e.getUTCFullYear(),n=ho(e.getUTCMonth()+1),o=ho(e.getUTCDate()),r=ho(e.getUTCHours()),s=ho(e.getUTCMinutes()),d=ho(e.getUTCSeconds());return`${t}-${n}-${o}_${r}-${s}-${d}`},Dg=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Fg=async(e,{width:t,height:n})=>{let o="",r=new Lg({write(d,l,u){let m=Bg(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(o=m),u()}});r.columns=t,r.rows=n,r.isTTY=!0;let s=kg(e,{stdout:r,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),o},Bg=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),lc=async()=>{let{viewMode:e}=oe(),{contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,renderedChildrenIndex:s}=g(),d=o.find(ie=>ie.context==="BOARD");if(!d)return i("No board found to export");let l=120,u=40,m=await Fg(Mg.createElement(ac,{height:u,width:l,swimlanes:(s[d.id]??[]).filter(ie=>ie!==void 0&&Vt(ie)),contextNode:t,selectedIndex:n,breadCrumb:o,viewMode:e??"dense",mode:r}),{width:l,height:u});if(!m)return i("Failed to render board export");let p=Co(process.cwd());if(a(p))return i("Unable to export, epiq root not found");let y=new Date,N=Pg(y),R=`board_${Dg(d.title)}_${N}.md`,w=pi(p.value);cc.mkdirSync(w,{recursive:!0});let L=wg.join(w,R),$=`# Board - ${d.title}
47
47
  Date: ${y.toISOString()}
48
48
 
49
49
  \`\`\`text
50
50
  ${m}
51
51
  \`\`\`
52
- `;return dc.writeFileSync(B,$,"utf8"),c("Exported board layout",B)}});var Eo,Hs=h(()=>{"use strict";Eo=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 sS}from"react";var Ks,Lg,kg,Bn,Pg,Bt,No=h(()=>{"use strict";C();Lg=new Set,kg=()=>{for(let e of Lg)e()},Bn=()=>{if(!Ks)throw new Error("Ui state not initialized. Call initUiState() first.");return Ks},Pg=e=>{let t=Bn();return Ks=e(t),kg(),c("UX state updated",null)},Bt=e=>Pg(t=>({...t,...e}))});import{spawn as Dg}from"node:child_process";function yr(e){let t=process.platform,o=Dg(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 Vs=h(()=>{"use strict"});import{spawnSync as Fg}from"node:child_process";import Bg from"node:os";import uc from"node:path";import{ulid as Og}from"ulid";function Ug(){let{preferredEditor:e}=ne(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function _g(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function mc(e){let t=uc.join(Bg.tmpdir(),"epiq");_e.mkDir(t);let n=uc.join(t,Og());_e.writeToFile(n,e??"");let r=Ug();for(let o of r){let s=_g(o,n),d=Fg(s,{stdio:"inherit",shell:!0});if(!d.error&&d.status===0){let l=_e.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 pc=h(()=>{"use strict";C();Re();bs()});import{ulid as zs}from"ulid";var gc,$g,jg,fc=h(()=>{"use strict";pc();Xt();et();kt();te();C();vn();ae();T();ce();Lt();gc=async e=>{let{contextNode:t,selectedIndex:n}=g(),r=q(t.id)[n];if(e.modifier===Oe.DESCRIPTION)return jg();if(r&&Yn(r))return $g(e);if(e.modifier===Oe.TITLE){let o=re();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 ot();return a(l)?l:O([{id:zs(),action:"edit.title",payload:{id:s.id,name:d},...o.value}],l.value)}return i("Unknown edit command")},$g=async e=>{let t=re();if(a(t))return i("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=g(),o=q(n.id)[r];if(!o||!Yn(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=x.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 ot();if(a(p))return p;let y=p.value;return O([{id:zs(),action:"edit.issue.comment",payload:{id:u.id,issue:d.id,md:m},...t.value}],y)},jg=async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let t=await ot();if(a(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=g(),s=Ue([...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=q(d.id).find(y=>y.title===z.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=mc(u);if(a(m))return i("Failed to edit field");let p=m.value;return p===u?c("No changes made",null):O([{id:zs(),action:"edit.description",payload:{id:d.id,md:p},...e.value}],n)}});import qs from"node:fs";import Wg from"node:path";var vc,yc=h(()=>{"use strict";C();ln();vc=async e=>{let t=Wg.join(e,".gitignore"),n=qs.existsSync(t)?qs.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
53
- `).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(`
52
+ `;return cc.writeFileSync(L,$,"utf8"),c("Exported board layout",L)}});var Sr,Vs=h(()=>{"use strict";Sr=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let o=t[n];if(o&&o.action==="close.issue"&&o.payload.id===e.id){for(let r=n-1;r>=0;r--){let s=t[r];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 gC}from"react";var zs,Og,Ug,Un,_g,_t,Cr=h(()=>{"use strict";C();Og=new Set,Ug=()=>{for(let e of Og)e()},Un=()=>{if(!zs)throw new Error("Ui state not initialized. Call initUiState() first.");return zs},_g=e=>{let t=Un();return zs=e(t),Ug(),c("UX state updated",null)},_t=e=>_g(t=>({...t,...e}))});import{spawn as $g}from"node:child_process";function xo(e){let t=process.platform,r=$g(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return r.unref(),r.on("error",()=>{}),!0}var Gs=h(()=>{"use strict"});import{spawnSync as jg}from"node:child_process";import Wg from"node:os";import mc from"node:path";import{ulid as Hg}from"ulid";function Kg(){let{preferredEditor:e}=oe(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function qg(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function pc(e){let t=mc.join(Wg.tmpdir(),"epiq");je.mkDir(t);let n=mc.join(t,Hg());je.writeToFile(n,e??"");let o=Kg();for(let r of o){let s=qg(r,n),d=jg(s,{stdio:"inherit",shell:!0});if(!d.error&&d.status===0){let l=je.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 gc=h(()=>{"use strict";C();we();Ss()});import{ulid as Ys}from"ulid";var fc,Vg,zg,vc=h(()=>{"use strict";gc();Qt();et();Ft();ne();C();hn();ce();T();ue();Dt();fc=async e=>{let{contextNode:t,selectedIndex:n}=g(),o=G(t.id)[n];if(e.modifier===_e.DESCRIPTION)return zg();if(o&&Jn(o))return Vg(e);if(e.modifier===_e.TITLE){let r=re();if(a(r))return i("Unable to resolve user ID");let s=o;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 rt();return a(l)?l:B([{id:Ys(),action:"edit.title",payload:{id:s.id,name:d},...r.value}],l.value)}return i("Unknown edit command")},Vg=async e=>{let t=re();if(a(t))return i("Unable to resolve user ID");let{contextNode:n,selectedIndex:o}=g(),r=G(n.id)[o];if(!r||!Jn(r))return i("Select a comment first");if(r.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||!M(d))return i("Unable to resolve comment issue");if(d.readonly)return i("Cannot edit readonly issue");let l=r.id.split(":").at(0)??"",u=x.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 rt();if(a(p))return p;let y=p.value;return B([{id:Ys(),action:"edit.issue.comment",payload:{id:u.id,issue:d.id,md:m},...t.value}],y)},zg=async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let t=await rt();if(a(t))return t;let n=t.value,{breadCrumb:o,selectedNode:r}=g(),s=$e([...o,r],"TICKET");if(a(s))return i("Edit target must be an issue");let d=s.value;if(!M(d))return i("Edit target must be an issue");if(d.readonly)return i("Cannot edit readonly issue");let l=G(d.id).find(y=>y.title===z.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=pc(u);if(a(m))return i("Failed to edit field");let p=m.value;return p===u?c("No changes made",null):B([{id:Ys(),action:"edit.description",payload:{id:d.id,md:p},...e.value}],n)}});import Xs from"node:fs";import Gg from"node:path";var yc,hc=h(()=>{"use strict";C();mn();yc=async e=>{let t=Gg.join(e,".gitignore"),n=Xs.existsSync(t)?Xs.readFileSync(t,"utf8"):"",o=[".epiq/events/",".epiq/log/"],r=n.split(`
53
+ `).map(u=>u.trim()),s=o.filter(u=>!r.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(`
54
54
  `);return n=n.trimEnd()+`
55
55
 
56
56
  ${l}
57
- `,qs.writeFileSync(t,n,"utf8"),le.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)}});import Hg from"node:fs";import hc from"node:path";var Kg,X,xc,Ic=h(()=>{"use strict";yc();Rr();pt();jt();Or();Be();rr();Yr();Tt();et();J();C();$t();pe();Re();T();ce();Kg=async e=>{let t=await _({cwd:e,args:["status","--porcelain"]});return a(t)?t:c("Checked git diff",t.value.stdout.trim().length>0)},X=(e,t)=>i(`[${e}] ${t}`),xc=async()=>{j("");let e=Sr(),t=await st(process.cwd());if(a(t))return X(1,t.message);let n=t.value,r=await wr(n);if(a(r))return X(2,r.message);if(r.value)return X(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await Kg(n);if(a(o))return X(2.5,o.message);if(o.value)return X(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(_o(n))return X(4,"Epiq project already initialized");let s=eo();if(!s.isSetupDone||!s.userName)return X(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let d=ne(),l=d.userName,u=d.userId;if(!u||!l)return X(5,"Missing Epiq user id");let m=e.stateBranch,p=await Lr({repoRoot:n,branch:m});if(a(p))return X(6,p.message);if(p.value)return X(6,`State branch already exists: ${m}`);let y=await Xo({repoRoot:n,stateBranchName:m});if(a(y))return X(6,y.message);let N=Dr();if(a(N))return X(7,N.message);let R=hc.join(Pr(),e.projectId),D=await Vn({repoRoot:n,stateBranchRoot:R,stateBranchName:m});if(a(D))return X(8,D.message);let B=hc.join(R,".epiq");Hg.mkdirSync(B,{recursive:!0});let $=Oa({userId:u,userName:l});if(a($))return X(9,$.message);for(let Bo of $.value){let li=zr({event:Bo,rootDir:R});if(a(li))return X(9,li.message)}let oe=await Br({stateBranchRoot:R,eventFileName:Yt({userId:u,userName:l})});if(a(oe))return X(10,oe.message);let se=await mn({cwd:R,message:"[epiq:init]"});if(a(se))return X(10,se.message);let V=await vc(n);if(a(V))return X(11,V.message);let He=gi({repoRoot:n,fileContents:e});if(a(He))return X(12,He.message);let dn=await ie.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(dn))return X(13,dn.message);let U=await ie.commit({cwd:n,message:"[epiq:init-project]"});if(a(U))return X(13,U.message);let H="Project initialized!",cn=await _({cwd:n,args:["push","-u","origin","HEAD"]});a(cn)&&(H+=` Warn: [init:14] ${cn.message}`);let _t=await zn({repoRoot:n,stateBranchRoot:R});a(_t)&&(H+=` Warn: [init:15] ${_t.message}`);let di=At($.value).filter(a);if(di.length>0)return X(16,di.map(Bo=>Bo.message).join(`
58
- `));let Fo=qe();if(a(Fo))return X(16,Fo.message);let{rootNodeId:Jl,nodes:Ql}=Fo.value,ci=Ql[Jl];return ci?(P.navigate({contextNode:ci,selectedIndex:0}),I({hasProjectDefinition:!0,mode:f.DEFAULT}),c(H,null)):X(16,"Unable to resolve initialized root node")}});import{ulid as Vg}from"ulid";function Ys(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=Q(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=Nc({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Cc(u.value)}function Xs(e){let t=Ec();if(a(t))return t;let{contextNode:n,selectedIndex:r}=g(),s=Q(n.id)[r+e];if(!s)return i("Missing sibling node");let d=Nc({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:Cc(d.value)}var bc,Ot,hr,Ec,Gs,Nc,Cc,Js=h(()=>{"use strict";Tt();et();C();at();T();bc=null,Ot=()=>structuredClone(bc),hr=e=>{bc=e},Ec=()=>{let{contextNode:e,selectedIndex:t}=g(),r=Q(e.id)[t];return r?c("Resolved selected child",r):i("Target node not found")},Gs=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Q(t).filter(o=>o.id!==e);return qr(r,n)},Nc=({id:e,parentId:t,position:n={at:"end"}})=>{let r=re();if(a(r))return i("Unable to resolve user ID");let o=Gs({parentId:t,id:e,position:n});return a(o)?o:c("Created pending move state",{id:Vg(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Cc=e=>{hr(e);let t=Rt(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as zg}from"ulid";var Sc,Co,Rc,Ac=h(()=>{"use strict";Be();Js();Xt();et();J();C();at();pe();T();ce();Sc=()=>{let e=Ot();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=Q(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))},Co=(e,t="Moved preview")=>{if(a(e))return e;let n=Sc();return a(n)?n:(I({mode:f.MOVE}),c(t,null))},Rc=async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=G().commandMeta,{contextNode:n,selectedIndex:r}=g(),o=Q(n.id)[r];if(!o)return I({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=Q(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=Gs({parentId:o.parentNodeId,id:o.id,position:m});return a(p)?p:(hr({id:zg(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),I({mode:f.MOVE}),c("Move initialized",null))}if(t==="next")return Co(Xs(1));if(t==="previous")return Co(Xs(-1));if(t==="to-next")return Co(Ys(1));if(t==="to-previous")return Co(Ys(-1));if(t==="confirm"){let s=Ot();if(!s)return i("No pending move to confirm");let d=await ot();if(a(d))return d;let l=O([s],d.value);if(a(l))return l;let u=Sc();return a(u)?u:(hr(null),I({mode:f.DEFAULT}),c("Moved item",null))}return t==="cancel"?(hr(null),I({mode:f.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as qg,ulid as Gg}from"ulid";var Yg,So,Qs=h(()=>{"use strict";C();Yg=qg(),So=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=Yg();return c("Created issue events",[{id:Gg(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as Ro}from"ulid";var Tc,wc=h(()=>{"use strict";Be();Qs();Xt();et();kt();C();ae();at();T();ce();Tc=async(e,t)=>{let n=re();if(a(n))return i("Unable to resolve user ID");let r=await ot();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=O([m],o);if(a(p))return p;let y=x.getNode(p.value[0].result.id);if(!y)return i("Created node not found");if(!y.parentNodeId)return p;let N=x.getNode(y.parentNodeId);return N?(P.navigate({contextNode:N,selectedIndex:x.getSiblings(y.parentNodeId).findIndex(({id:R})=>R===y.id)}),p):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=x.getNode(m);if(!p)return i("Workspace not found");let y=Cn(p.id,n.value,o);return a(y)?y:u({id:Ro(),action:"add.board",payload:{id:Ro(),name:t.inputString,parent:p.id,rank:y.value},...n.value})}if(t.modifier==="swimlane"){let m=Ue(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:Ro(),action:"add.swimlane",payload:{id:Ro(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=q(d.id)[l],p=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let se=Ue(s,"SWIMLANE");return a(se)?null:se.value})();if(!p)return i("Unable to add issue in this context");let y=Cn(p.id,n.value,o);if(a(y))return y;let N=So({name:t.inputString,parent:p.id,rank:y.value,user:n.value});if(a(N))return N;let R=N.value,D=O([...R],o);if(a(D))return D;if(!D.value[0])return i("Issue creation failed");let oe=R.find(se=>se.action==="add.issue")?.payload.id;return oe?(P.navigate({contextNode:p,selectedIndex:x.getSiblings(p.id).findIndex(({id:se})=>se===oe)}),c("Issue created",null)):i("Unable to determine ticket id")}return c("Success",null)}});var Ao,Zs=h(()=>{"use strict";Be();Nn();Tt();C();T();Ao=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=g(),s=Ia(n,t);if(a(s))return i(s.message);let{appliedEvents:d,unappliedEvents:l}=s.value,u=Ut();if(a(u))return u;let p=At(d).filter(a);if(p.length>0)return Ut(),I(o),i(p.map(N=>N.message).join(", "));let y=g().nodes[e];return y?(P.navigate({contextNode:y,selectedIndex:r}),c("",{unappliedEvents:l})):(Ut(),I(o),i("Board did not exist at that date"))}});var Xg,Jg,Qg,To,wo,sn,Mc,Zg,Lc,ei=h(()=>{"use strict";qt();ns();Tt();J();C();T();Xg=20,Jg=16,Qg=150,To=null,wo=null,sn=()=>{To!==null&&(clearInterval(To),To=null),wo!==null&&(clearTimeout(wo),wo=null)},Mc=()=>{sn(),I({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Zg=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)},Lc=({events:e,startTime:t,durationMs:n})=>{sn();let r=e.length,o=e.map(y=>In(y)??t),s=o[r-1]??Date.now(),d=Zg(o),l=Math.max(1,Math.round(n*Xg/1e3)),u=Math.max(Math.round(n/l),Jg),m=0,p=0;I({mode:f.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),To=setInterval(()=>{m++;let y=m/l,N=[],R;for(;p<r&&d[p]<=y;){let B=e[p],$=Rt(B);if(a($)){Mc();return}N.push(...rs(B)),R=B,p++}if(p>=r||m>=l){for(;p<r;p++){let $=Rt(e[p]);if(a($))break}let B=g().replay;I({unappliedEvents:[],replay:B&&{...B,progress:1,appliedCount:r}}),sn(),wo=setTimeout(Mc,Qg);return}let D=g().replay;I({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,y),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:R?In(R)??D?.currentTime??t:D?.currentTime??t,currentLabel:R?ma(R):D?.currentLabel??"",flashNodeIds:R?[...new Set(N)]:D?.flashNodeIds??[]}})},u)}});var kc,Pc=h(()=>{"use strict";pt();qt();Nn();Tt();J();kt();C();pe();T();sr();Zs();ei();kc=async()=>{let e=Ue(g().breadCrumb,"BOARD");if(a(e))return e;let t=await st(process.cwd());if(a(t))return i("Unable to locate repo root");let n=Pe({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=G().commandMeta;if(sn(),r==="now"){let l=Gt(n.value);if(a(l))return i(l.message);let u=Ut();if(a(u))return u;let p=At(l.value).filter(a);return p.length>0?i(p.map(y=>y.message).join(", ")):(I({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=In(l);if(u===null)return i("No previous event to peek");s=u}else if(r==="next"){let l=g().unappliedEvents.at(0),u=In(l);if(u===null)return i("No next event to peek");s=u+1}else{let l=Zt(r||o.trim());if(!l)return i("Invalid peek date");s=l.getTime()}let d=Ao({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(d)?d:(I({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:d.value.unappliedEvents,replay:null}),c("Peeking",!0))}});var Dc,Fc=h(()=>{"use strict";pt();kt();C();pe();T();sr();Zs();ei();Dc=async()=>{let e=Ue(g().breadCrumb,"BOARD");if(a(e))return e;let t=await st(process.cwd());if(a(t))return i("Unable to locate repo root");let n=Pe({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=G().commandMeta,{dateInput:s,durationInput:d}=oo(r,o);if(sn(),g().syncStatus.status==="syncing")return i("Cannot replay while syncing, try again in a moment");let l=Zt(s);if(!l)return i("Invalid replay date");let u=d?ro(d):15e3;if(u===null)return i("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=g(),y=Ao({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?(Ut(),I(p),c("Nothing to replay from that point",!0)):(Lc({events:N,startTime:m,durationMs:u}),c("Replaying board history",!0))}});import tf from"zod";var Bc,Oc=h(()=>{"use strict";tn();J();C();pe();Re();T();Bc=()=>{let e=G().commandMeta.inputString,t=tf.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=Ye({autoSyncDebounceMs:t.data});return a(n)?n:(ze({autoSyncIntervalMs:t.data}),I({mode:f.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))}});var Uc,_c=h(()=>{"use strict";rr();tn();J();C();pe();Re();T();Uc=()=>{let e=G().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=Va(e),n=Ye({autoSync:t});return a(n)?n:(ze({autoSync:t}),I({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var $c,jc=h(()=>{"use strict";tn();J();C();pe();Re();T();$c=()=>{let e=G().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return i("Invalid response");let n=Ye({logLevel:e});return a(n)?n:(ze({logLevel:e}),I({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});import{spawn as nf}from"node:child_process";var rf,Wc,Hc=h(()=>{"use strict";C();rf=()=>{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"]}}},Wc=async e=>new Promise(t=>{let{command:n,args:r}=rf();try{let o=nf(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 xr,Kc,Vc=h(()=>{"use strict";C();T();Hc();yn();or();Lt();xr=async(e,t)=>{if(!e.trim())return i(`Nothing to copy: ${t} is empty`);let n=await Wc(e);return a(n)?n:c(`Copied ${t} to clipboard`,null)},Kc=async e=>{let{breadCrumb:t,selectedNode:n}=g(),r=ir({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return i("Nothing selected to copy from");switch(e.modifier){case me.REF:return xr(Ze(o.id),"ref");case me.TITLE:return xr(o.title,"title");case me.DESCRIPTION:return r?xr(r.props?.description??"","description"):i("No issue in scope");case me.TAGS:{if(!r)return i("No issue in scope");let s=wt(r).map(({name:d})=>d);return xr(s.join(", "),"tags")}case me.ASSIGNEES:{if(!r)return i("No issue in scope");let s=Mt(r).map(({name:d})=>d);return xr(s.join(", "),"assignees")}default:return i("Yank one of: ref, title, description, tags, assignees")}}});var zc,qc=h(()=>{"use strict";us();J();C();pe();T();zc=async()=>{j(""),I({mode:f.DEFAULT});let e=qe();if(a(e))return i(e.message);if(e.value.syncStatus.status==="syncing")return i("Sync already in progress");I({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Xr();return a(t)?(I({syncStatus:{msg:t.message,status:"failed"}}),t):(I({mode:f.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as Ce}from"ulid";var of,Gc,Yc,bt,Xc,Jc=h(()=>{"use strict";lc();Be();tn();Xt();et();Hs();En();J();kt();te();C();ae();at();pe();Re();T();No();ce();Vs();Qt();ks();Lt();As();fc();Ic();Ac();wc();Pc();Fc();Oc();Ss();_c();jc();Vc();qc();of=e=>e.action==="add.issue.comment",Gc=e=>Object.values(g().tags).find(t=>t.name===e),Yc=e=>Object.values(g().contributors).find(t=>t.name===e),bt=async()=>{let e=await ot();return a(e)?e:c("Resolved persist root",e.value)},Xc=[{systemOnly:!0,intent:M.Move,description:"Internal move-state command",mode:f.COMMAND_LINE,action:Rc},{intent:M.Delete,description:"Delete the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=q(t.id)[n];if(!r)return i("Unable to resolve child to delete");let o=await bt();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(of).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):O([{id:Ce(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],o.value):i("Unable to resolve comment")}return O([{id:Ce(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>I({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}=G().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(d=>de(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 fe(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 Bt({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),I({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=re();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=q(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[ue];if(!o)return i("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return i("Issue is already closed");let s=await bt();if(a(s))return s;let d=s.value,l=Jt(o.id,r.id,{at:"end"},e.value,d);if(a(l))return l;let u=O([{id:Ce(),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:()=>I({mode:f.DEFAULT})},{intent:M.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=q(t.id)[n];if(!r)return i("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):Vt(r.id,"TICKET");if(a(o))return i("Cannot reopen in this context");let s=o.value,d=g().nodes[ue];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=Eo(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 bt();if(a(m))return m;let p=m.value,y=Jt(u.id,s.id,{at:"end"},e.value,p);if(a(y))return y;let N=O([{id:Ce(),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:()=>I({mode:f.DEFAULT})},{intent:M.Init,description:"Initialize Epiq in the current git repository",mode:f.COMMAND_LINE,action:xc},{intent:M.NewItem,description:"Create a new board, swimlane, or issue",mode:f.COMMAND_LINE,action:Tc,onSuccess:()=>I({mode:f.DEFAULT})},{intent:M.Rename,description:"Rename the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=q(t.id)[n];if(!r)return i("Missing node");if(r.readonly)return i("Cannot rename readonly node");let o=Ld();if(!o)return i("Provide a title");let s=await bt();return a(s)?s:O([{id:Ce(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>I({mode:f.DEFAULT})},{intent:M.UntagTicket,description:"Remove a tag from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=G().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let o=Gc(r);if(!o)return i(`Tag "${r}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid untag target");let d=Vt(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 bt();return a(m)?m:O([{id:Ce(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>I({mode:f.DEFAULT})},{intent:M.TagTicket,description:"Add or create a tag on the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=G().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=Vt(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 bt();if(a(l))return l;let u=Gc(r),m=u?.id??Ce();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):O([...u?[]:[{id:Ce(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:Ce(),action:"add.issue.tag",payload:{id:d.id,tag:m},...e.value}],l.value)},onSuccess:()=>I({mode:f.DEFAULT})},{intent:M.AssignUserToTicket,description:"Assign a user to the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=G().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee");let{selectedIndex:o,contextNode:s}=g(),d=q(s.id)[o];if(!d)return i("Invalid assign target");let l=Vt(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 bt();if(a(m))return m;let p=Yc(r),y=p?.id??Ce();return(u.props.assignees??[]).includes(y)?i("Assignee already assigned"):O([...p?[]:[{id:Ce(),action:"create.contributor",payload:{id:y,name:r},...e.value}],{id:Ce(),action:"add.issue.assignee",payload:{id:u.id,assignee:y},...e.value}],m.value)},onSuccess:()=>I({mode:f.DEFAULT})},{intent:M.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=G().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee to remove");let o=Yc(r);if(!o)return i(`Assignee "${r}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid unassign target");let d=Vt(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 bt();return a(m)?m:O([{id:Ce(),action:"remove.issue.assignee",payload:{id:l.id,assignee:o.id},...e.value}],m.value)},onSuccess:()=>I({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>Tn)return i(`Cannot exceed ${Tn} characters`);let r=re();if(a(r))return i("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=g(),d=Ue([...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):Vt(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 bt();return a(p)?p:O([{id:Ce(),action:"add.issue.comment",payload:{id:Ce(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>I({mode:f.DEFAULT})},{intent:M.Sync,description:"Pull, commit, and push Epiq state",mode:f.COMMAND_LINE,action:zc},{intent:M.Peek,description:"View board state at another point in time",mode:f.COMMAND_LINE,action:kc},{intent:M.Replay,description:"Replay board history forward from a point in time",mode:f.COMMAND_LINE,action:Dc},{intent:M.Export,description:"Export the current board layout to markdown",mode:f.COMMAND_LINE,action:async()=>{let e=await cc();return a(e)?e:(I({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)=>gc(t),onSuccess:()=>I({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)=>Kc(t),onSuccess:()=>I({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 Z.USERNAME:{let{userId:r,preferredEditor:o,userName:s}=ne(),d=n||s,l=r??Ce();if(!d||!l)return i("Unable to resolve user name or id");let u=Ye({userName:d,userId:l,preferredEditor:o??""});return a(u)?u:(ze({userName:d,userId:l}),I({mode:f.DEFAULT}),c(`Username set to "${d}"`,null))}case Z.EDITOR:{if(!n)return i("No editor provided");let r=Ye({preferredEditor:n});return a(r)?r:(ze({preferredEditor:n}),I({mode:f.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case Z.VIEW:{if(n!=="wide"&&n!=="dense")return i("Invalid view mode");let r=Ye({viewMode:n});return a(r)?r:(ze({viewMode:n}),I({mode:f.DEFAULT}),c(`View set to "${n}"`,null))}case Z.AUTOSYNC:return Uc();case Z.LOG_LEVEL:return $c();case Z.SYNC_DEBOUNCE_MS:return Bc();case Z.ATTACHMENT_MAX_KB:return dd();default:return i("Unknown config command")}}},{intent:M.Coffee,description:"Sponsor the development of Epiq!",mode:f.COMMAND_LINE,action:()=>{let e=G().commandMeta.modifier;return e==="custom"?yr("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):yr(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),j(""),c("Thanks you!",null)}}]});var sf,ut,ti=h(()=>{"use strict";Zr();ao();ks();Jc();C();pe();Re();T();sf=new Set(["peek","replay","filter","view-help","yank"]),ut=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=G();if(!t)return i("No command to confirm");if(!e&&n===Pt.Invalid)return i("Invalid command");let s=kd(t);Ad();let{readOnly:d}=g();if(d&&!sf.has(s))return ur({status:Et.Fail,message:"Command not available in readonly state",value:null});let l=Xc.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return ur({status:Et.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return ur({status:Et.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?ur(u):(Td({addToHistory:!e}),l.onSuccess?.(),ne().autoSync&&Wa(),u)}});var Mo,Lo,Qc,Zc=h(()=>{"use strict";C();J();T();Ht();ti();Js();pe();Mo=[{intent:A.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(I({mode:f.COMMAND_LINE}),j("move cancel"),ut({isForceExecutedBySystem:!0}))},{intent:A.InitMove,mode:f.DEFAULT,description:"[m] move (init/confirm)",action:()=>(I({mode:f.COMMAND_LINE}),j("move start"),ut({isForceExecutedBySystem:!0}))},{intent:A.ConfirmMove,mode:f.MOVE,action:()=>(I({mode:f.COMMAND_LINE}),j("move confirm"),ut({isForceExecutedBySystem:!0}))}],Lo=[{intent:A.MovePreviousItem,mode:f.MOVE,action:()=>Ot()?(I({mode:f.COMMAND_LINE}),j("move previous"),ut({isForceExecutedBySystem:!0})):i("No pending move")},{intent:A.MoveNextItem,mode:f.MOVE,action:()=>Ot()?(I({mode:f.COMMAND_LINE}),j("move next"),ut({isForceExecutedBySystem:!0})):i("No pending move")}],Qc=[{intent:A.MoveToNextContainer,mode:f.MOVE,action:()=>Ot()?(I({mode:f.COMMAND_LINE}),j("move to-next"),ut({isForceExecutedBySystem:!0})):i("No pending move")},{intent:A.MoveToPreviousContainer,mode:f.MOVE,action:()=>Ot()?(I({mode:f.COMMAND_LINE}),j("move to-previous"),ut({isForceExecutedBySystem:!0})):i("No pending move")}]});var el,tl=h(()=>{"use strict";te();Zc();el={[L.WORKSPACE]:[...Mo,...Lo],[L.BOARD]:[...Mo,...Lo],[L.SWIMLANE]:[...Mo,...Lo,...Qc],[L.TICKET]:[],[L.FIELD]:[],[L.FIELD_LIST]:[],[L.TEXT]:[],[L.COMMENT]:[]}});import af from"node:fs";import df from"node:path";var nl,rl=h(()=>{"use strict";pt();dr();C();ce();Vs();nl=e=>{let t=rt(process.cwd());if(a(t))return i("Unable to resolve project root");let n=Pe({repoRoot:t.value});if(a(n))return i(n.message);let r=Cs(e.hash,e.ext),o=df.join(Uo(n.value),r);return af.existsSync(o)?(yr(o),c(`Opened ${e.name}`,null)):i("Attachment file not found \u2014 run :sync to fetch it")}});var ol,sl,il=h(()=>{"use strict";J();C();pe();T();No();Ht();Be();ol=()=>{j("");let{pendingNavTarget:e}=Bn();I({mode:f.DEFAULT}),e&&P.navigate(e),Bt({pendingNavTarget:void 0})},sl=[{intent:A.ExitCommandLine,mode:f.HELP,action:()=>(ol(),c("Exiting help",null))},{intent:A.Exit,mode:f.HELP,action:()=>(ol(),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 cf,al,dl,cl=h(()=>{"use strict";J();te();C();pe();T();No();Ht();Be();cf=e=>{I({mode:f.COMMAND_LINE});let{pendingNavTarget:t}=Bn();t&&P.navigate(t),Bt({pendingNavTarget:void 0}),j(`${e} `)},al=()=>{j("");let{pendingNavTarget:e}=Bn();e&&P.navigate(e),Bt({pendingNavTarget:void 0}),I({mode:f.DEFAULT})},dl=[{intent:A.InitCommandPalette,mode:f.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{j("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return Bt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),I({mode:f.PALETTE}),c("Opening command palette",null)}},{intent:A.Confirm,mode:f.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!$i(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?(cf(t),c("Selected command",t)):c("No command selected",null)}},{intent:A.ExitCommandLine,mode:f.PALETTE,action:()=>(al(),c("Exiting palette",null))},{intent:A.Exit,mode:f.PALETTE,action:()=>(al(),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 ll,ul=h(()=>{"use strict";Qt();Lt();J();C();vn();ae();at();pe();T();rl();Ht();il();cl();Be();ll=[...sl,...dl,{intent:A.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(I({mode:f.COMMAND_LINE}),j(`${v.NEW} `),c("Adding new item",null))},{intent:A.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(I({mode:f.COMMAND_LINE}),j(`${v.DELETE} `),c("Deleting item",null))},{intent:A.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(I({mode:f.COMMAND_LINE}),j(""),c("Entering command line mode",null))},{intent:A.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!Q(e?.id??"")?.length){let r=e?x.getAttachment(e.id):void 0;if(r)return nl(r);if(e?.title===z.DESCRIPTION)return I({mode:f.COMMAND_LINE}),j(`${v.EDIT} description `),c("Propose command",!0);if(e?.title===z.ASSIGNEES)return I({mode:f.COMMAND_LINE}),j(`${v.ASSIGN} `),c("Propose command",!0);if(e?.title===z.TAGS)return I({mode:f.COMMAND_LINE}),j(`${v.TAG} `),c("Propose command",!0);if(t.title===z.DESCRIPTION&&e?.context==="TEXT")return I({mode:f.COMMAND_LINE}),j(`${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===z.DESCRIPTION?me.DESCRIPTION:e?.title===z.TAGS?me.TAGS:e?.title===z.ASSIGNEES?me.ASSIGNEES:me.REF,r=de(v.YANK).includes(t)?t:me.REF;return I({mode:f.COMMAND_LINE}),j(`${v.YANK} ${r}`),c("Propose command",!0)}},{intent:A.EditTitle,mode:f.DEFAULT,description:"[r] rename title",action:()=>(I({mode:f.COMMAND_LINE}),j(`${v.EDIT} title ${g().selectedNode?.title}`),c("Exiting context",null))},{intent:A.EditDescription,mode:f.DEFAULT,description:"[e] edit description",action:()=>(I({mode:f.COMMAND_LINE}),j(`${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 lf,uf,ml,pl=h(()=>{"use strict";pe();lf=500,uf=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),ml=e=>{let t=uf(e);t&&mo(n=>(n+t).slice(0,lf))}});var mf,pf,gl,fl=h(()=>{"use strict";pl();J();C();pe();T();Ht();ti();mf=[f.COMMAND_LINE,f.PALETTE],pf=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:()=>(Ls("left"),c("Moving cursor left of word",null))},{intent:A.MoveCursorRightOfWord,mode:e,action:()=>(Ls("right"),c("Moving cursor right of word",null))},{intent:A.AutoCompleteCommand,mode:e,action:()=>(mo((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})=>(ml(n??""),c("Capturing input",null))},{intent:A.EraseInput,mode:e,action:()=>(Sd(),c("Erasing input",null))},{intent:A.EraseInputWord,mode:e,action:()=>(Rd(),c("Erasing input word",null))}],gl=[{intent:A.Confirm,mode:f.COMMAND_LINE,action:()=>(ut(),c("Executing command",null))},{intent:A.ViewHelp,mode:f.DEFAULT,action:()=>(I({mode:f.HELP}),c("Viewing help",null))},...mf.flatMap(pf),{intent:A.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(I({mode:f.DEFAULT}),c("Exiting command line",null))},{intent:A.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(wd(),c("Getting last command from history",null))},{intent:A.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Md(),c("Getting next command from history",null))}]});import hl from"chalk";var ko,vl,yl,ni,xl=h(()=>{"use strict";J();te();Ae();ko=hl.dim.hex(E.secondary2)(": for command line"),vl="q to exit",yl=`${hl.hex(E.accent)("m")} to confirm`,ni={[L.WORKSPACE]:[ko],[L.BOARD]:[ko],[L.BOARD+f.COMMAND_LINE]:[ko],[L.SWIMLANE]:[ko],[L.TICKET+f.HELP]:[vl],[L.SWIMLANE+f.HELP]:[vl],[L.TICKET]:[],[L.FIELD]:[],[L.SWIMLANE+f.MOVE]:[yl],[L.TICKET+f.MOVE]:[yl]}});var Ir,gf,ff,Il,bl=h(()=>{"use strict";T();yn();Ir=e=>e.trim().toLocaleLowerCase(),gf=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},ff=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},Il=(e,t)=>{let n=Ir(t.value);if(!n)return!0;switch(t.target){case"title":return Ir(e.title??"").includes(n);case"description":return Ir(e.props.description??"").includes(n);case"tag":return gf(e).map(Ir).some(o=>o.includes(n));case"assignee":return ff(e).map(Ir).some(o=>o.includes(n));case"ref":return Zi(e.id,t.value);default:return!0}}});function El(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 Nl=h(()=>{"use strict";C()});var Cl,Sl=h(()=>{"use strict";Cl=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 vf}from"react";function Al(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=El(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,y=ni[p+n]??ni[p]??[],N=[...ll,...el[p]??[],...gl],R=Cl(N),D=hf(o,s),B=D[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:y,availableActions:N,actionIndex:R,selectedNode:B,renderedChildrenIndex:D})}function Qn(e){ri=e;let t=rt(process.cwd()),n=!1;if(!a(t)){let s=Nt(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:{},attachments:{}},o=Al(r);return a(o)?o:(an=o.value,Rl(),c("State initialized",null))}function fe(e){let t=g(),n=e(t),r=Al(n);return a(r)?i(r.message??"Unable to update state"):(an=r.value,Rl(),c("State updated",null))}var an,ri,oi,Rl,yf,g,qe,I,ke,hf,q,Ut,Rn,T=h(()=>{"use strict";tl();ul();fl();xl();$t();J();te();C();ce();bl();Nl();Sl();oi=new Set,Rl=()=>{for(let e of oi)e()},yf=e=>(oi.add(e),()=>oi.delete(e));g=()=>{if(!an)throw new Error("State not initialized. Call initWorkspaceState() first.");return an},qe=()=>an?c("Retrieved state",an):i("State not initialized. Call initWorkspaceState() first.");I=e=>fe(t=>({...t,...e})),ke=()=>vf(yf,g,g),hf=(e,t)=>{let n={};for(let r of Object.values(e))w(r)&&t.length>0&&!t.every(o=>Il(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},q=e=>g()?.renderedChildrenIndex[e]??[],Ut=()=>ri?Qn(ri):i("Cannot reset state: no initial workspace found"),Rn=()=>an!==void 0});var si,Po,Do,ii,Ge,Jr=h(()=>{"use strict";_i();C();T();si=e=>{Rn()&&(I({syncStatus:e}),Ui({type:"sync-status",payload:e}))},Po=(e="Syncing...")=>{si({status:"syncing",msg:e})},Do=(e="Synced")=>{si({status:"synced",msg:e})},ii=e=>{si({status:"failed",msg:e})},Ge=e=>(ii(e),i(e))});import{decodeTime as oL}from"ulid";var Tl=h(()=>{"use strict";C()});var xf,If,Qr,ms=h(()=>{"use strict";C();Jr();ls();Ar();pt();jt();Or();Tl();xf=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=K("getRepoRootDir",await st(e));if(a(n))return i(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=K("getStateBranchRoot",Pe({repoRoot:r}));if(a(o))return i(o.message);let s=o.value;logger.debug("[sync] state branch root",s);let d=K("ensureInitialCommit",await Di(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=K("bootstrapStateBranchStorage",await Oi({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=K("hasInProgressGitOperation(stateBranchRoot)",await wr(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=K("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}))},If=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=K("stageStateBranchOwnEventFile",await Br({stateBranchRoot:t,eventFileName:n}));if(a(r))return i(r.message);let o=K("stageStateBranchMediaFiles",await Fi({stateBranchRoot:t}));if(a(o))return i(o.message);let s=K("hasStagedChanges(after stage)",await Ci(t));if(a(s))return i(s.message);if(logger.debug("[sync] state branch change check after stage result",{changed:s.value}),!s.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 d=K("createStateBranchSyncCommit",await Bi({repoRoot:e,stateBranchRoot:t}));return a(d)?i(d.message):(logger.debug("[sync] created sync commit",d.value),c("Committed own event file",{createdCommit:!0,commitSha:d.value}))},Qr=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");Po();let n=K("ensureSyncReady",await xf({cwd:e,ensureUpstream:!0}));if(a(n))return Ge(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,d=K("isDetachedHead(stateBranchRoot)",await Si(o));if(a(d))return Ge(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return Ge("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,p=!1,y=K("getStateBranch",un(r));if(a(y))return Ge(y.message);let N=y.value;logger.debug("[sync] resolved state branch",{stateBranch:N,stateBranchRoot:o});let R=K("commitOwnEventFileToStateBranch",await If({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(a(R))return Ge(R.message);l=R.value.createdCommit,u=R.value.commitSha;let D=K("pullBranchRebaseIfPresent",await qo({cwd:o,branch:N}));if(a(D))return Ge(D.message);if(m=D.value,l||s){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:s,stateBranchRoot:o});let B=K("pushStateBranch",await zn({stateBranchRoot:o,repoRoot:r}));if(a(B)&&Ni(B.message)){let $=K("pullBranchRebaseIfPresent(retry)",await qo({cwd:o,branch:N}));if(a($))return Ge($.message);m=m||$.value,B=K("pushStateBranch(retry)",await zn({stateBranchRoot:o,repoRoot:r}))}if(a(B))return Ge(B.message);p=B.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let B=K("git rev-parse HEAD",await _({args:["rev-parse","HEAD"],cwd:o}));if(a(B))return Ge(B.message);u=B.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Do(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 SL,ulid as Se}from"ulid";var ai,Te,je,We,bf,Ef,wl,Ml,Ll,kl,Pl,Dl,Fl,Bl,Ol,Ul,_l,$l,jl,Wl,Hl,Kl,Vl,zl=h(()=>{"use strict";pt();jt();Or();ms();tn();Qs();Yr();Nn();Xt();et();Hs();En();te();C();$t();ae();at();T();Jr();ce();gt();yn();pn();dr();ln();ai=e=>{let t=rt(e??process.cwd());return a(t)?i(t.message):c("Resolved Epiq repo root",t.value)},Te=async e=>{let t=ai(e);if(a(t))return t;let n=Pe({repoRoot:t.value});if(a(n))return i(n.message);let r=Sr(),o=await Vn({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)&&le.info(3,s.message);let d=Gt(n.value);if(a(d))return i(d.message);let l=tr(d.value);return a(l)?i(l.message):c("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:n.value})},je=()=>{let e=ad();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")},We=()=>{let e=qe();return a(e)?i(e.message):e},bf=e=>(e.props.tags??[]).map(t=>x.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Me(t.name)})),Ef=e=>(e.props.assignees??[]).map(t=>x.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Me(t.name)})),wl=async(e={})=>{let t=await Te(e.repoRoot);if(a(t))return t;let n=We();if(a(n))return n;let r=Object.values(n.value.nodes).filter(o=>o.context==="BOARD").map(o=>({id:o.id,ref:Ze(o.id),title:o.title,parentId:o.parentNodeId,readonly:!!o.readonly}));return c("Listed boards",r)},Ml=async(e={})=>{let t=await Te(e.repoRoot);if(a(t))return t;let n=We();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===ue,readonly:!!o.readonly}));return c("Listed swimlanes",r)},Ll=async e=>{let t=await Te(e.repoRoot);if(a(t))return t;let n=We();if(a(n))return n;let r=Object.values(n.value.nodes).filter(w).filter(o=>e.includeClosed||o.parentNodeId!==ue).map(o=>({id:o.id,ref:Ze(o.id),title:Ct(o.title),description:o.props.description??"",parentNodeId:o.parentNodeId,isClosed:o.parentNodeId===ue,readonly:!!o.readonly,tags:bf(o),assignees:Ef(o)}));return c("Listed issues",r)},kl=async e=>{let t=await Te(e.repoRoot);if(a(t))return t;let n=je();if(a(n))return n;let r=Cn(e.parentId,n.value,t.value.stateBranchRoot);if(a(r))return r;let o=So({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(a(o))return o;let s=o.value,d=O([...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")},Pl=async e=>{let t=await Te(e.repoRoot);if(a(t))return t;let n=je();if(a(n))return n;let r=Jt(ue,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(r))return r;let o={id:Se(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ue,rank:r.value}},s=O([o],t.value.stateBranchRoot);return a(s)?i(s.message):c("Closed issue",{id:e.issueId})},Dl=async e=>{let t=await Te(e.repoRoot);if(a(t))return t;let n=je();if(a(n))return n;let r=We();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!==ue)return i("Issue is not closed");let s=Eo(o);if(!s)return i("Unable to resolve previous parent from issue history");if(s===ue)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=Jt(d.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(l))return l;let u={id:Se(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:d.id,rank:l.value}},m=O([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Reopened issue",{id:o.id,parentId:d.id})},Fl=async e=>{let t=ai(e.repoRoot);if(a(t))return t;let n=je();if(a(n))return n;let r=Pe({repoRoot:t.value});if(a(r))return r;let o=Gt(r.value);if(a(o))return o;let s=tr(o.value);if(a(s))return s;let d=Jt(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(a(d))return d;let l={id:Se(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:d.value}},u=O([l],r.value);return a(u)?i(u.message):c("Moved issue",{id:e.issueId,parentId:e.parentId})},Bl=async(e={})=>{Po();let t=ai(e.repoRoot);if(a(t))return i("Sync failed");let n=je();if(a(n))return n;let r=await Qr({cwd:t.value,ownEventFileName:Yt(n.value)});return a(r)?(ii(r.message),r):(Do(),c("Synced",r.value))},Ol=async(e={})=>{let t=await Te(e.repoRoot);if(a(t))return t;let n=We();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})},Ul=async e=>{let t=await Te(e.repoRoot);if(a(t))return t;let n=je();if(a(n))return n;let r=We();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:Se(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},l=O([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited issue description",{id:e.issueId,description:e.description})},_l=async e=>{let t=await Te(e.repoRoot);if(a(t))return t;let n=je();if(a(n))return n;let r=We();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=Ct(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:Se(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},l=O([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited issue title",{id:e.issueId,title:s})},$l=async e=>{let t=await Te(e.repoRoot);if(a(t))return t;let n=je();if(a(n))return n;let r=We();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=Ct(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??Se(),u=[...d?[]:[{id:Se(),...n.value,action:"create.tag",payload:{id:l,name:s}}],{id:Se(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:l}}],m=O(u,t.value.stateBranchRoot);return a(m)?i(m.message):c("Added issue tag",{id:e.issueId,tag:{id:l,name:s}})},jl=async e=>{let t=await Te(e.repoRoot);if(a(t))return t;let n=je();if(a(n))return n;let r=We();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:Se(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},d=O([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue tag",{id:e.issueId,tagId:e.tagId})},Wl=async e=>{let t=await Te(e.repoRoot);if(a(t))return t;let n=je();if(a(n))return n;let r=We();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=Ct(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??Se(),u=[...d?[]:[{id:Se(),...n.value,action:"create.contributor",payload:{id:l,name:s}}],{id:Se(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:l}}],m=O(u,t.value.stateBranchRoot);return a(m)?i(m.message):c("Added issue assignee",{id:e.issueId,assignee:{id:l,name:s}})},Hl=async e=>{let t=await Te(e.repoRoot);if(a(t))return t;let n=je();if(a(n))return n;let r=We();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:Se(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},d=O([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},Kl=async e=>{let t=await Te(e.repoRoot);if(a(t))return t;let n=je();if(a(n))return n;let r=We();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=Se(),l={id:Se(),...n.value,action:"add.issue.comment",payload:{id:d,issue:e.issueId,md:s,author:n.value.userId}},u=O([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Added issue comment",{id:d,issueId:e.issueId,body:s})},Vl=async e=>{let t=await Te(e.repoRoot);if(a(t))return t;let n=je();if(a(n))return n;let r=We();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:Se(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=O([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})}});var Yl={};eu(Yl,{createMcpServer:()=>ql,resultJson:()=>be,startMcpServer:()=>Gl});import{McpServer as Nf}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Cf}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as S}from"zod";var be,ql,Gl,Xl=h(async()=>{"use strict";C();zl();be=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),ql=()=>{let e=new Nf({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:S.object({repoRoot:S.string().optional()})},async t=>be(await Ol(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:S.object({repoRoot:S.string().optional(),includeClosed:S.boolean().optional()})},async t=>be(await Ll(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:S.object({repoRoot:S.string().optional()})},async t=>be(await wl(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:S.object({repoRoot:S.string().optional(),boardId:S.string().optional()})},async t=>be(await Ml(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue",inputSchema:S.object({title:S.string().min(1),parentId:S.string().min(1),repoRoot:S.string().optional()})},async t=>be(await kl(t))),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:S.object({issueId:S.string().min(1),description:S.string(),repoRoot:S.string().optional()})},async t=>be(await Ul(t))),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:S.object({issueId:S.string().min(1),title:S.string().min(1),repoRoot:S.string().optional()})},async t=>be(await _l(t))),e.registerTool("epiq_issue_tag_add",{description:"Add a tag to an Epiq issue, creating the tag if it does not exist",inputSchema:S.object({issueId:S.string().min(1),tagName:S.string().min(1),repoRoot:S.string().optional()})},async t=>be(await $l(t))),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:S.object({issueId:S.string().min(1),tagId:S.string().min(1),repoRoot:S.string().optional()})},async t=>be(await jl(t))),e.registerTool("epiq_issue_assignee_add",{description:"Assign a contributor to an Epiq issue, creating the contributor if they do not exist",inputSchema:S.object({issueId:S.string().min(1),assigneeName:S.string().min(1),repoRoot:S.string().optional()})},async t=>be(await Wl(t))),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:S.object({issueId:S.string().min(1),assigneeId:S.string().min(1),repoRoot:S.string().optional()})},async t=>be(await Hl(t))),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:S.object({issueId:S.string().min(1),body:S.string().min(1),repoRoot:S.string().optional()})},async t=>be(await Kl(t))),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:S.object({commentId:S.string().min(1),repoRoot:S.string().optional()})},async t=>be(await Vl(t))),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:S.object({issueId:S.string().min(1),repoRoot:S.string().optional()})},async t=>be(await Dl(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:S.object({issueId:S.string().min(1),repoRoot:S.string().optional()})},async t=>be(await Pl(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:S.object({issueId:S.string().min(1),parentId:S.string().min(1),position:S.discriminatedUnion("at",[S.object({at:S.literal("start")}),S.object({at:S.literal("end")}),S.object({at:S.literal("before"),sibling:S.string().min(1)}),S.object({at:S.literal("after"),sibling:S.string().min(1)})]).optional(),repoRoot:S.string().optional()})},async t=>be(await Fl(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:S.object({repoRoot:S.string().optional()})},async t=>be(await Bl(t))),e},Gl=async()=>{let e=ql(),t=new Cf;await e.connect(t)};await Gl()});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;await Xl().then(()=>Yl);
57
+ `,Xs.writeFileSync(t,n,"utf8"),me.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)}});import Yg from"node:fs";import xc from"node:path";var Xg,J,Ic,bc=h(()=>{"use strict";hc();To();gt();Kt();_o();Ue();ro();Qo();wt();et();Q();C();Ht();fe();we();T();ue();Xg=async e=>{let t=await _({cwd:e,args:["status","--porcelain"]});return a(t)?t:c("Checked git diff",t.value.stdout.trim().length>0)},J=(e,t)=>i(`[${e}] ${t}`),Ic=async()=>{j("");let e=Ao(),t=await st(process.cwd());if(a(t))return J(1,t.message);let n=t.value,o=await ko(n);if(a(o))return J(2,o.message);if(o.value)return J(2,`Cannot initialize Epiq while a git operation is in progress: ${o.value}`);let r=await Xg(n);if(a(r))return J(2.5,r.message);if(r.value)return J(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(Hr(n))return J(4,"Epiq project already initialized");let s=or();if(!s.isSetupDone||!s.userName)return J(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let d=oe(),l=d.userName,u=d.userId;if(!u||!l)return J(5,"Missing Epiq user id");let m=e.stateBranch,p=await Po({repoRoot:n,branch:m});if(a(p))return J(6,p.message);if(p.value)return J(6,`State branch already exists: ${m}`);let y=await es({repoRoot:n,stateBranchName:m});if(a(y))return J(6,y.message);let N=Bo();if(a(N))return J(7,N.message);let R=xc.join(Fo(),e.projectId),w=await Gn({repoRoot:n,stateBranchRoot:R,stateBranchName:m});if(a(w))return J(8,w.message);let L=xc.join(R,".epiq");Yg.mkdirSync(L,{recursive:!0});let $=_a({userId:u,userName:l});if(a($))return J(9,$.message);for(let _r of $.value){let mi=Yo({event:_r,rootDir:R});if(a(mi))return J(9,mi.message)}let ie=await Uo({stateBranchRoot:R,eventFileName:Jt({userId:u,userName:l})});if(a(ie))return J(10,ie.message);let ae=await gn({cwd:R,message:"[epiq:init]"});if(a(ae))return J(10,ae.message);let V=await yc(n);if(a(V))return J(11,V.message);let He=vi({repoRoot:n,fileContents:e});if(a(He))return J(12,He.message);let ln=await de.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(ln))return J(13,ln.message);let U=await de.commit({cwd:n,message:"[epiq:init-project]"});if(a(U))return J(13,U.message);let H="Project initialized!",un=await _({cwd:n,args:["push","-u","origin","HEAD"]});a(un)&&(H+=` Warn: [init:14] ${un.message}`);let Wt=await Yn({repoRoot:n,stateBranchRoot:R});a(Wt)&&(H+=` Warn: [init:15] ${Wt.message}`);let li=Tt($.value).filter(a);if(li.length>0)return J(16,li.map(_r=>_r.message).join(`
58
+ `));let Ur=ze();if(a(Ur))return J(16,Ur.message);let{rootNodeId:nu,nodes:ou}=Ur.value,ui=ou[nu];return ui?(F.navigate({contextNode:ui,selectedIndex:0}),I({hasProjectDefinition:!0,mode:f.DEFAULT}),c(H,null)):J(16,"Unable to resolve initialized root node")}});import{ulid as Jg}from"ulid";function Qs(e){let t=Nc();if(a(t))return t;let{contextNode:n,nodes:o}=g();if(!n.parentNodeId)return i("Missing parent node id");let r=o[n.parentNodeId];if(!r)return i("Missing parent node");let s=Z(r.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=Sc({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Cc(u.value)}function Zs(e){let t=Nc();if(a(t))return t;let{contextNode:n,selectedIndex:o}=g(),s=Z(n.id)[o+e];if(!s)return i("Missing sibling node");let d=Sc({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:Cc(d.value)}var Ec,$t,Io,Nc,Js,Sc,Cc,ei=h(()=>{"use strict";wt();et();C();dt();T();Ec=null,$t=()=>structuredClone(Ec),Io=e=>{Ec=e},Nc=()=>{let{contextNode:e,selectedIndex:t}=g(),o=Z(e.id)[t];return o?c("Resolved selected child",o):i("Target node not found")},Js=({id:e,parentId:t,position:n={at:"end"}})=>{let o=Z(t).filter(r=>r.id!==e);return Xo(o,n)},Sc=({id:e,parentId:t,position:n={at:"end"}})=>{let o=re();if(a(o))return i("Unable to resolve user ID");let r=Js({parentId:t,id:e,position:n});return a(r)?r:c("Created pending move state",{id:Jg(),...o.value,action:"move.node",payload:{id:e,parent:t,rank:r.value.rank}})},Cc=e=>{Io(e);let t=At(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as Qg}from"ulid";var Rc,Rr,Ac,Tc=h(()=>{"use strict";Ue();ei();Qt();et();Q();C();dt();fe();T();ue();Rc=()=>{let e=$t();if(!e)return i("No pending move state");let t=e.payload.id,n=e.payload.parent,o=g().nodes[n];if(!o)return i("Move parent not found");let r=Z(n).findIndex(s=>s.id===t);return r===-1?i("Moved node not found among rendered children"):(F.navigate({contextNode:o,selectedIndex:r}),c("Synchronized navigation to moved node",null))},Rr=(e,t="Moved preview")=>{if(a(e))return e;let n=Rc();return a(n)?n:(I({mode:f.MOVE}),c(t,null))},Ac=async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=Y().commandMeta,{contextNode:n,selectedIndex:o}=g(),r=Z(n.id)[o];if(!r)return I({mode:f.DEFAULT}),i("No move target");if(t==="start"){if(r.readonly)return i("Target node is read-only");if(o===-1)return i("No item selected");if(!r.parentNodeId)return i("Target has no parent");let s=Z(r.parentNodeId),d=s.findIndex(({id:y})=>y===r.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=Js({parentId:r.parentNodeId,id:r.id,position:m});return a(p)?p:(Io({id:Qg(),action:"move.node",payload:{id:r.id,parent:r.parentNodeId,rank:p.value.rank},...e.value}),I({mode:f.MOVE}),c("Move initialized",null))}if(t==="next")return Rr(Zs(1));if(t==="previous")return Rr(Zs(-1));if(t==="to-next")return Rr(Qs(1));if(t==="to-previous")return Rr(Qs(-1));if(t==="confirm"){let s=$t();if(!s)return i("No pending move to confirm");let d=await rt();if(a(d))return d;let l=B([s],d.value);if(a(l))return l;let u=Rc();return a(u)?u:(Io(null),I({mode:f.DEFAULT}),c("Moved item",null))}return t==="cancel"?(Io(null),I({mode:f.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as Zg,ulid as ef}from"ulid";var tf,Ar,ti=h(()=>{"use strict";C();tf=Zg(),Ar=({name:e,parent:t,rank:n,user:{userId:o,userName:r}})=>{let s=tf();return c("Created issue events",[{id:ef(),userId:o,userName:r,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as Tr}from"ulid";var wc,Mc=h(()=>{"use strict";Ue();ti();Qt();et();Ft();C();ce();dt();T();ue();wc=async(e,t)=>{let n=re();if(a(n))return i("Unable to resolve user ID");let o=await rt();if(a(o))return o;let r=o.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],r);if(a(p))return p;let y=x.getNode(p.value[0].result.id);if(!y)return i("Created node not found");if(!y.parentNodeId)return p;let N=x.getNode(y.parentNodeId);return N?(F.navigate({contextNode:N,selectedIndex:x.getSiblings(y.parentNodeId).findIndex(({id:R})=>R===y.id)}),p):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=x.getNode(m);if(!p)return i("Workspace not found");let y=Zt(p.id,n.value,r);return a(y)?y:u({id:Tr(),action:"add.board",payload:{id:Tr(),name:t.inputString,parent:p.id,rank:y.value},...n.value})}if(t.modifier==="swimlane"){let m=$e(s,"BOARD");if(a(m))return i("Unable to add swimlane in this context");let p=Zt(m.value.id,n.value,r);return a(p)?p:u({id:Tr(),action:"add.swimlane",payload:{id:Tr(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=G(d.id)[l],p=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let ae=$e(s,"SWIMLANE");return a(ae)?null:ae.value})();if(!p)return i("Unable to add issue in this context");let y=Zt(p.id,n.value,r);if(a(y))return y;let N=Ar({name:t.inputString,parent:p.id,rank:y.value,user:n.value});if(a(N))return N;let R=N.value,w=B([...R],r);if(a(w))return w;if(!w.value[0])return i("Issue creation failed");let ie=R.find(ae=>ae.action==="add.issue")?.payload.id;return ie?(F.navigate({contextNode:p,selectedIndex:x.getSiblings(p.id).findIndex(({id:ae})=>ae===ie)}),c("Issue created",null)):i("Unable to determine ticket id")}return c("Success",null)}});var wr,ni=h(()=>{"use strict";Ue();Cn();wt();C();T();wr=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:o})=>{let r=g(),s=Ea(n,t);if(a(s))return i(s.message);let{appliedEvents:d,unappliedEvents:l}=s.value,u=jt();if(a(u))return u;let p=Tt(d).filter(a);if(p.length>0)return jt(),I(r),i(p.map(N=>N.message).join(", "));let y=g().nodes[e];return y?(F.navigate({contextNode:y,selectedIndex:o}),c("",{unappliedEvents:l})):(jt(),I(r),i("Board did not exist at that date"))}});var nf,of,rf,Mr,kr,dn,kc,sf,Lc,oi=h(()=>{"use strict";Xt();ss();wt();Q();C();T();nf=20,of=16,rf=150,Mr=null,kr=null,dn=()=>{Mr!==null&&(clearInterval(Mr),Mr=null),kr!==null&&(clearTimeout(kr),kr=null)},kc=()=>{dn(),I({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},sf=e=>{let t=[],n=0;for(let r=0;r<e.length;r++){let s=r===0?0:Math.max(0,e[r]-e[r-1]);n+=Math.sqrt(s),t[r]=n}let o=n;return t.map((r,s)=>o>0?r/o:(s+1)/e.length)},Lc=({events:e,startTime:t,durationMs:n})=>{dn();let o=e.length,r=e.map(y=>En(y)??t),s=r[o-1]??Date.now(),d=sf(r),l=Math.max(1,Math.round(n*nf/1e3)),u=Math.max(Math.round(n/l),of),m=0,p=0;I({mode:f.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:o,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Mr=setInterval(()=>{m++;let y=m/l,N=[],R;for(;p<o&&d[p]<=y;){let L=e[p],$=At(L);if(a($)){kc();return}N.push(...is(L)),R=L,p++}if(p>=o||m>=l){for(;p<o;p++){let $=At(e[p]);if(a($))break}let L=g().replay;I({unappliedEvents:[],replay:L&&{...L,progress:1,appliedCount:o}}),dn(),kr=setTimeout(kc,rf);return}let w=g().replay;I({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,y),appliedCount:p,totalCount:o,startTime:t,endTime:s,currentTime:R?En(R)??w?.currentTime??t:w?.currentTime??t,currentLabel:R?ga(R):w?.currentLabel??"",flashNodeIds:R?[...new Set(N)]:w?.flashNodeIds??[]}})},u)}});var Pc,Dc=h(()=>{"use strict";gt();Xt();Cn();wt();Q();Ft();C();fe();T();io();ni();oi();Pc=async()=>{let e=$e(g().breadCrumb,"BOARD");if(a(e))return e;let t=await st(process.cwd());if(a(t))return i("Unable to locate repo root");let n=ke({repoRoot:t.value});if(a(n))return n;let{modifier:o,inputString:r}=Y().commandMeta;if(dn(),o==="now"){let l=Mt(n.value);if(a(l))return i(l.message);let u=jt();if(a(u))return u;let p=Tt(l.value).filter(a);return p.length>0?i(p.map(y=>y.message).join(", ")):(I({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),c("Peeking now",!0))}let s;if(o==="prev"){let l=g().eventLog.at(-1),u=En(l);if(u===null)return i("No previous event to peek");s=u}else if(o==="next"){let l=g().unappliedEvents.at(0),u=En(l);if(u===null)return i("No next event to peek");s=u+1}else{let l=tn(o||r.trim());if(!l)return i("Invalid peek date");s=l.getTime()}let d=wr({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(d)?d:(I({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:d.value.unappliedEvents,replay:null}),c("Peeking",!0))}});var Fc,Bc=h(()=>{"use strict";gt();Ft();C();fe();T();io();ni();oi();Fc=async()=>{let e=$e(g().breadCrumb,"BOARD");if(a(e))return e;let t=await st(process.cwd());if(a(t))return i("Unable to locate repo root");let n=ke({repoRoot:t.value});if(a(n))return n;let{modifier:o,inputString:r}=Y().commandMeta,{dateInput:s,durationInput:d}=ar(o,r);if(dn(),g().syncStatus.status==="syncing")return i("Cannot replay while syncing, try again in a moment");let l=tn(s);if(!l)return i("Invalid replay date");let u=d?ir(d):15e3;if(u===null)return i("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=g(),y=wr({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?(jt(),I(p),c("Nothing to replay from that point",!0)):(Lc({events:N,startTime:m,durationMs:u}),c("Replaying board history",!0))}});import df from"zod";var Oc,Uc=h(()=>{"use strict";on();Q();C();fe();we();T();Oc=()=>{let e=Y().commandMeta.inputString,t=df.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=Ye({autoSyncDebounceMs:t.data});return a(n)?n:(Ve({autoSyncIntervalMs:t.data}),I({mode:f.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))}});var _c,$c=h(()=>{"use strict";ro();on();Q();C();fe();we();T();_c=()=>{let e=Y().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=za(e),n=Ye({autoSync:t});return a(n)?n:(Ve({autoSync:t}),I({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var jc,Wc=h(()=>{"use strict";on();Q();C();fe();we();T();jc=()=>{let e=Y().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return i("Invalid response");let n=Ye({logLevel:e});return a(n)?n:(Ve({logLevel:e}),I({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});import{spawn as cf}from"node:child_process";var lf,Hc,Kc=h(()=>{"use strict";C();lf=()=>{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"]}}},Hc=async e=>new Promise(t=>{let{command:n,args:o}=lf();try{let r=cf(n,o,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>t(i(`Clipboard tool not available (${n})`))),r.on("close",s=>t(s===0?c("Copied to clipboard",null):i(`Clipboard tool failed (${n})`))),r.stdin.on("error",()=>{}),r.stdin.write(e),r.stdin.end()}catch{t(i(`Clipboard tool not available (${n})`))}})});var bo,qc,Vc=h(()=>{"use strict";C();T();Kc();xn();so();Dt();bo=async(e,t)=>{if(!e.trim())return i(`Nothing to copy: ${t} is empty`);let n=await Hc(e);return a(n)?n:c(`Copied ${t} to clipboard`,null)},qc=async e=>{let{breadCrumb:t,selectedNode:n}=g(),o=ao({breadCrumb:t,selectedNode:n}),r=o??n;if(!r)return i("Nothing selected to copy from");switch(e.modifier){case ge.REF:return bo(Ze(r.id),"ref");case ge.TITLE:return bo(r.title,"title");case ge.DESCRIPTION:return o?bo(o.props?.description??"","description"):i("No issue in scope");case ge.TAGS:{if(!o)return i("No issue in scope");let s=Lt(o).map(({name:d})=>d);return bo(s.join(", "),"tags")}case ge.ASSIGNEES:{if(!o)return i("No issue in scope");let s=Pt(o).map(({name:d})=>d);return bo(s.join(", "),"assignees")}default:return i("Yank one of: ref, title, description, tags, assignees")}}});var zc,Gc=h(()=>{"use strict";gs();Q();C();fe();T();zc=async()=>{j(""),I({mode:f.DEFAULT});let e=ze();if(a(e))return i(e.message);if(e.value.syncStatus.status==="syncing")return i("Sync already in progress");I({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Zo();return a(t)?(I({syncStatus:{msg:t.message,status:"failed"}}),t):(I({mode:f.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as Te}from"ulid";var uf,Yc,Xc,Et,Jc,Qc=h(()=>{"use strict";uc();Ue();on();Qt();et();Vs();Sn();Q();Ft();ne();C();ce();dt();fe();we();T();Cr();ue();Gs();en();Fs();Dt();Ms();vc();bc();Tc();Mc();Dc();Bc();Uc();Ts();$c();Wc();Vc();Gc();uf=e=>e.action==="add.issue.comment",Yc=e=>Object.values(g().tags).find(t=>t.name===e),Xc=e=>Object.values(g().contributors).find(t=>t.name===e),Et=async()=>{let e=await rt();return a(e)?e:c("Resolved persist root",e.value)},Jc=[{systemOnly:!0,intent:k.Move,description:"Internal move-state command",mode:f.COMMAND_LINE,action:Ac},{intent:k.Delete,description:"Delete the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=G(t.id)[n];if(!o)return i("Unable to resolve child to delete");let r=await Et();if(a(r))return r;if(o.context==="COMMENT"){let s=o.id,d=M(t)?t.id:t.parentNodeId;if(!d)return i("Unable to resolve comment issue");let l=g().nodes[d];if(!l||!M(l))return i("Unable to resolve comment issue");let u=l.log?.filter(uf).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):B([{id:Te(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],r.value):i("Unable to resolve comment")}return B([{id:Te(),action:"delete.node",payload:{id:o.id},...e.value}],r.value)},onSuccess:()=>I({mode:f.DEFAULT})},{intent:k.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:f.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=Y().commandMeta,n=/(!=|=)/,[o]=e.split(n);if(!o||!(d=>le(v.FILTER).map(l=>l.split(n)[0]).includes(d))(o))return i("Invalid filter modifier");let s={target:o,operator:"=",value:t.trim()};return ye(d=>({...d,filters:e==="clear"?[]:[...d.filters,s],mode:f.DEFAULT})),c("Filter updated",null)}},{intent:k.ViewHelp,description:"Open the help screen",mode:f.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return _t({pendingNavTarget:{contextNode:e,breadCrumb:o,selectedIndex:t,selectedNode:n}}),I({mode:f.HELP}),c("Viewing help",null)}},{intent:k.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=G(t.id)[n];if(!o)return i("Unable to close issue, no target found");if(!M(o))return i("Cannot close in this context");let r=g().nodes[pe];if(!r)return i("Unable to locate closed swimlane");if(o.parentNodeId===r.id)return i("Issue is already closed");let s=await Et();if(a(s))return s;let d=s.value,l=kt(r.id,o.id,{at:"end"},e.value,d);if(a(l))return l;let u=B([{id:Te(),action:"close.issue",payload:{id:o.id,parent:r.id,rank:l.value},...e.value}],d);return a(u)?u:c("Issue closed",null)},onSuccess:()=>I({mode:f.DEFAULT})},{intent:k.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=G(t.id)[n];if(!o)return i("Unable to reopen issue, no target found");let r=o.context==="TICKET"?c("Resolved ticket",o):Gt(o.id,"TICKET");if(a(r))return i("Cannot reopen in this context");let s=r.value,d=g().nodes[pe];if(!d)return i("Unable to locate closed swimlane");if(s.parentNodeId!==d.id)return i("Issue is not closed");if(!M(s))return i("Target node is not issue");let l=Sr(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 Et();if(a(m))return m;let p=m.value,y=kt(u.id,s.id,{at:"end"},e.value,p);if(a(y))return y;let N=B([{id:Te(),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:()=>I({mode:f.DEFAULT})},{intent:k.Init,description:"Initialize Epiq in the current git repository",mode:f.COMMAND_LINE,action:Ic},{intent:k.NewItem,description:"Create a new board, swimlane, or issue",mode:f.COMMAND_LINE,action:wc,onSuccess:()=>I({mode:f.DEFAULT})},{intent:k.Rename,description:"Rename the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=G(t.id)[n];if(!o)return i("Missing node");if(o.readonly)return i("Cannot rename readonly node");let r=Ld();if(!r)return i("Provide a title");let s=await Et();return a(s)?s:B([{id:Te(),action:"edit.title",payload:{id:o.id,name:r},...e.value}],s.value)},onSuccess:()=>I({mode:f.DEFAULT})},{intent:k.UntagTicket,description:"Remove a tag from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,o=(t||n).trim();if(!o)return i("Provide a tag");let r=Yc(o);if(!r)return i(`Tag "${o}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid untag target");let d=Gt(s.id,"TICKET");if(a(d))return i("Unable to untag issue in this context");let l=d.value;if(!M(l))return i("Target node is not issue");if(!(l.props.tags??[]).includes(r.id))return i("Issue is not tagged with that tag");let m=await Et();return a(m)?m:B([{id:Te(),action:"remove.issue.tag",payload:{id:l.id,tag:r.id},...e.value}],m.value)},onSuccess:()=>I({mode:f.DEFAULT})},{intent:k.TagTicket,description:"Add or create a tag on the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,o=(t||n).trim();if(!o)return i("Provide a tag");let{selectedNode:r}=g();if(!r)return i("Invalid tag target");let s=Gt(r.id,"TICKET");if(a(s))return i("Unable to tag issue in this context");let d=s.value;if(!M(d))return i("Target node is not issue");let l=await Et();if(a(l))return l;let u=Yc(o),m=u?.id??Te();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):B([...u?[]:[{id:Te(),action:"create.tag",payload:{id:m,name:o},...e.value}],{id:Te(),action:"add.issue.tag",payload:{id:d.id,tag:m},...e.value}],l.value)},onSuccess:()=>I({mode:f.DEFAULT})},{intent:k.AssignUserToTicket,description:"Assign a user to the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,o=(t||n).trim();if(!o)return i("Provide an assignee");let{selectedIndex:r,contextNode:s}=g(),d=G(s.id)[r];if(!d)return i("Invalid assign target");let l=Gt(d.id,"TICKET");if(a(l))return i("Unable to assign issue in this context");let u=l.value;if(!M(u))return i("Target node is not issue");let m=await Et();if(a(m))return m;let p=Xc(o),y=p?.id??Te();return(u.props.assignees??[]).includes(y)?i("Assignee already assigned"):B([...p?[]:[{id:Te(),action:"create.contributor",payload:{id:y,name:o},...e.value}],{id:Te(),action:"add.issue.assignee",payload:{id:u.id,assignee:y},...e.value}],m.value)},onSuccess:()=>I({mode:f.DEFAULT})},{intent:k.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=re();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Y().commandMeta,o=(t||n).trim();if(!o)return i("Provide an assignee to remove");let r=Xc(o);if(!r)return i(`Assignee "${o}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid unassign target");let d=Gt(s.id,"TICKET");if(a(d))return i("Unable to unassign in this context");let l=d.value;if(!M(l))return i("Target node is not issue");if(!(l.props.assignees??[]).includes(r.id))return i(`Issue is not assigned to "${o}"`);let m=await Et();return a(m)?m:B([{id:Te(),action:"remove.issue.assignee",payload:{id:l.id,assignee:r.id},...e.value}],m.value)},onSuccess:()=>I({mode:f.DEFAULT})},{intent:k.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>Mn)return i(`Cannot exceed ${Mn} characters`);let o=re();if(a(o))return i("Unable to resolve user ID");let{breadCrumb:r,selectedNode:s}=g(),d=$e([...r,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):Gt(l.id,"TICKET");if(a(u))return i("Unable to comment on issue in this context");let m=u.value;if(!M(m))return i("Target node is not issue");let p=await Et();return a(p)?p:B([{id:Te(),action:"add.issue.comment",payload:{id:Te(),issue:m.id,author:o.value.userId,md:n},...o.value}],p.value)},onSuccess:()=>I({mode:f.DEFAULT})},{intent:k.Sync,description:"Pull, commit, and push Epiq state",mode:f.COMMAND_LINE,action:zc},{intent:k.Peek,description:"View board state at another point in time",mode:f.COMMAND_LINE,action:Pc},{intent:k.Replay,description:"Replay board history forward from a point in time",mode:f.COMMAND_LINE,action:Fc},{intent:k.Export,description:"Export the current board layout to markdown",mode:f.COMMAND_LINE,action:async()=>{let e=await lc();return a(e)?e:(I({mode:f.DEFAULT}),c("Export successful",!0))}},{intent:k.Exit,description:"Exit the application",mode:f.COMMAND_LINE,action:async()=>(F.exit(),c("Exit successful",!0))},{intent:k.Edit,description:"Edit title or description",mode:f.COMMAND_LINE,action:async(e,t)=>fc(t),onSuccess:()=>I({mode:f.DEFAULT})},{intent:k.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:f.COMMAND_LINE,action:async(e,t)=>qc(t),onSuccess:()=>I({mode:f.DEFAULT})},{intent:k.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 ee.USERNAME:{let{userId:o,preferredEditor:r,userName:s}=oe(),d=n||s,l=o??Te();if(!d||!l)return i("Unable to resolve user name or id");let u=Ye({userName:d,userId:l,preferredEditor:r??""});return a(u)?u:(Ve({userName:d,userId:l}),I({mode:f.DEFAULT}),c(`Username set to "${d}"`,null))}case ee.EDITOR:{if(!n)return i("No editor provided");let o=Ye({preferredEditor:n});return a(o)?o:(Ve({preferredEditor:n}),I({mode:f.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case ee.VIEW:{if(n!=="wide"&&n!=="dense")return i("Invalid view mode");let o=Ye({viewMode:n});return a(o)?o:(Ve({viewMode:n}),I({mode:f.DEFAULT}),c(`View set to "${n}"`,null))}case ee.AUTOSYNC:return _c();case ee.LOG_LEVEL:return jc();case ee.SYNC_DEBOUNCE_MS:return Oc();case ee.ATTACHMENT_MAX_KB:return cd();default:return i("Unknown config command")}}},{intent:k.Coffee,description:"Sponsor the development of Epiq!",mode:f.COMMAND_LINE,action:()=>{let e=Y().commandMeta.modifier;return e==="custom"?xo("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):xo(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),j(""),c("Thanks you!",null)}}]});var mf,mt,ri=h(()=>{"use strict";nr();lr();Fs();Qc();C();fe();we();T();mf=new Set(["peek","replay","filter","view-help","yank"]),mt=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:o,inputString:r}}=Y();if(!t)return i("No command to confirm");if(!e&&n===Bt.Invalid)return i("Invalid command");let s=Pd(t);Td();let{readOnly:d}=g();if(d&&!mf.has(s))return po({status:Nt.Fail,message:"Command not available in readonly state",value:null});let l=Jc.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return po({status:Nt.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:r,modifier:o})}catch(m){return po({status:Nt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?po(u):(wd({addToHistory:!e}),l.onSuccess?.(),oe().autoSync&&Ka(),u)}});var Lr,Pr,Zc,el=h(()=>{"use strict";C();Q();T();zt();ri();ei();fe();Lr=[{intent:A.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(I({mode:f.COMMAND_LINE}),j("move cancel"),mt({isForceExecutedBySystem:!0}))},{intent:A.InitMove,mode:f.DEFAULT,description:"[m] move (init/confirm)",action:()=>(I({mode:f.COMMAND_LINE}),j("move start"),mt({isForceExecutedBySystem:!0}))},{intent:A.ConfirmMove,mode:f.MOVE,action:()=>(I({mode:f.COMMAND_LINE}),j("move confirm"),mt({isForceExecutedBySystem:!0}))}],Pr=[{intent:A.MovePreviousItem,mode:f.MOVE,action:()=>$t()?(I({mode:f.COMMAND_LINE}),j("move previous"),mt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:A.MoveNextItem,mode:f.MOVE,action:()=>$t()?(I({mode:f.COMMAND_LINE}),j("move next"),mt({isForceExecutedBySystem:!0})):i("No pending move")}],Zc=[{intent:A.MoveToNextContainer,mode:f.MOVE,action:()=>$t()?(I({mode:f.COMMAND_LINE}),j("move to-next"),mt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:A.MoveToPreviousContainer,mode:f.MOVE,action:()=>$t()?(I({mode:f.COMMAND_LINE}),j("move to-previous"),mt({isForceExecutedBySystem:!0})):i("No pending move")}]});var tl,nl=h(()=>{"use strict";ne();el();tl={[P.WORKSPACE]:[...Lr,...Pr],[P.BOARD]:[...Lr,...Pr],[P.SWIMLANE]:[...Lr,...Pr,...Zc],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[],[P.COMMENT]:[]}});import pf from"node:fs";import gf from"node:path";var ol,rl=h(()=>{"use strict";gt();lo();C();ue();Gs();ol=e=>{let t=ot(process.cwd());if(a(t))return i("Unable to resolve project root");let n=ke({repoRoot:t.value});if(a(n))return i(n.message);let o=As(e.hash,e.ext),r=gf.join(Wr(n.value),o);return pf.existsSync(r)?(xo(r),c(`Opened ${e.name}`,null)):i("Attachment file not found \u2014 run :sync to fetch it")}});var sl,il,al=h(()=>{"use strict";Q();C();fe();T();Cr();zt();Ue();sl=()=>{j("");let{pendingNavTarget:e}=Un();I({mode:f.DEFAULT}),e&&F.navigate(e),_t({pendingNavTarget:void 0})},il=[{intent:A.ExitCommandLine,mode:f.HELP,action:()=>(sl(),c("Exiting help",null))},{intent:A.Exit,mode:f.HELP,action:()=>(sl(),c("Closed help",null))},{intent:A.NavPreviousItem,mode:f.HELP,description:"[arrows/hjkl] navigate",action:()=>(F.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:A.NavNextItem,mode:f.HELP,action:()=>(F.navigateToNextItem(),c("Navigating to next help item",null))},{intent:A.NavToPreviousContainer,mode:f.HELP,action:()=>(F.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:A.NavToNextContainer,mode:f.HELP,action:()=>(F.navigateToNextContainer(),c("Navigating to next help container",null))}]});var ff,dl,cl,ll=h(()=>{"use strict";Q();ne();C();fe();T();Cr();zt();Ue();ff=e=>{I({mode:f.COMMAND_LINE});let{pendingNavTarget:t}=Un();t&&F.navigate(t),_t({pendingNavTarget:void 0}),j(`${e} `)},dl=()=>{j("");let{pendingNavTarget:e}=Un();e&&F.navigate(e),_t({pendingNavTarget:void 0}),I({mode:f.DEFAULT})},cl=[{intent:A.InitCommandPalette,mode:f.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{j("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return _t({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}}),I({mode:f.PALETTE}),c("Opening command palette",null)}},{intent:A.Confirm,mode:f.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!Wi(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?(ff(t),c("Selected command",t)):c("No command selected",null)}},{intent:A.ExitCommandLine,mode:f.PALETTE,action:()=>(dl(),c("Exiting palette",null))},{intent:A.Exit,mode:f.PALETTE,action:()=>(dl(),c("Closed command palette",null))},{intent:A.NavPreviousItem,mode:f.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(F.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:A.NavNextItem,mode:f.PALETTE,action:()=>(F.navigateToNextItem(),c("Navigating to next item",null))},{intent:A.NavToPreviousContainer,mode:f.PALETTE,action:()=>(F.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:A.NavToNextContainer,mode:f.PALETTE,action:()=>(F.navigateToNextContainer(),c("Navigating to next container",null))}]});var ul,ml=h(()=>{"use strict";en();Dt();Q();C();hn();ce();dt();fe();T();rl();zt();al();ll();Ue();ul=[...il,...cl,{intent:A.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(I({mode:f.COMMAND_LINE}),j(`${v.NEW} `),c("Adding new item",null))},{intent:A.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(I({mode:f.COMMAND_LINE}),j(`${v.DELETE} `),c("Deleting item",null))},{intent:A.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(I({mode:f.COMMAND_LINE}),j(""),c("Entering command line mode",null))},{intent:A.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!Z(e?.id??"")?.length){let o=e?x.getAttachment(e.id):void 0;if(o)return ol(o);if(e?.title===z.DESCRIPTION)return I({mode:f.COMMAND_LINE}),j(`${v.EDIT} description `),c("Propose command",!0);if(e?.title===z.ASSIGNEES)return I({mode:f.COMMAND_LINE}),j(`${v.ASSIGN} `),c("Propose command",!0);if(e?.title===z.TAGS)return I({mode:f.COMMAND_LINE}),j(`${v.TAG} `),c("Propose command",!0);if(t.title===z.DESCRIPTION&&e?.context==="TEXT")return I({mode:f.COMMAND_LINE}),j(`${v.EDIT} description `),c("Propose command",!0)}return F.enterChildNode(),c("Entering context",null)}},{intent:A.Yank,mode:f.DEFAULT,description:"[y] yank to clipboard",action:()=>{let{selectedNode:e}=g(),t=e?.title===z.DESCRIPTION?ge.DESCRIPTION:e?.title===z.TAGS?ge.TAGS:e?.title===z.ASSIGNEES?ge.ASSIGNEES:ge.REF,o=le(v.YANK).includes(t)?t:ge.REF;return I({mode:f.COMMAND_LINE}),j(`${v.YANK} ${o}`),c("Propose command",!0)}},{intent:A.EditTitle,mode:f.DEFAULT,description:"[r] rename title",action:()=>(I({mode:f.COMMAND_LINE}),j(`${v.EDIT} title ${g().selectedNode?.title}`),c("Exiting context",null))},{intent:A.EditDescription,mode:f.DEFAULT,description:"[e] edit description",action:()=>(I({mode:f.COMMAND_LINE}),j(`${v.EDIT} description `),c("Exiting context",null))},{intent:A.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(F.enterParentNode(),c("Exiting context",null))},{intent:A.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(F.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:A.NavNextItem,mode:f.DEFAULT,action:()=>(F.navigateToNextItem(),c("Navigating to next item",null))},{intent:A.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(F.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:A.NavToNextContainer,mode:f.DEFAULT,action:()=>(F.navigateToNextContainer(),c("Navigating to next container",null))}]});var vf,yf,pl,gl=h(()=>{"use strict";fe();vf=500,yf=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),pl=e=>{let t=yf(e);t&&gr(n=>(n+t).slice(0,vf))}});var hf,xf,fl,vl=h(()=>{"use strict";gl();Q();C();fe();T();zt();ri();hf=[f.COMMAND_LINE,f.PALETTE],xf=e=>[{intent:A.MoveCursorLeft,mode:e,action:()=>(Ps(-1),c("Moving cursor left",null))},{intent:A.MoveCursorRight,mode:e,action:()=>(Ps(1),c("Moving cursor right",null))},{intent:A.MoveCursorLeftOfWord,mode:e,action:()=>(Ds("left"),c("Moving cursor left of word",null))},{intent:A.MoveCursorRightOfWord,mode:e,action:()=>(Ds("right"),c("Moving cursor right of word",null))},{intent:A.AutoCompleteCommand,mode:e,action:()=>(gr((t,{remainder:n})=>{let o=n?t+n:t,r="";return o==="edit title "&&(r=g().selectedNode?.title??""),o+r}),c("Auto-completing command",null))},{intent:A.CaptureInput,mode:e,action:(t,{sequence:n})=>(pl(n??""),c("Capturing input",null))},{intent:A.EraseInput,mode:e,action:()=>(Rd(),c("Erasing input",null))},{intent:A.EraseInputWord,mode:e,action:()=>(Ad(),c("Erasing input word",null))}],fl=[{intent:A.Confirm,mode:f.COMMAND_LINE,action:()=>(mt(),c("Executing command",null))},{intent:A.ViewHelp,mode:f.DEFAULT,action:()=>(I({mode:f.HELP}),c("Viewing help",null))},...hf.flatMap(xf),{intent:A.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(I({mode:f.DEFAULT}),c("Exiting command line",null))},{intent:A.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Md(),c("Getting last command from history",null))},{intent:A.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(kd(),c("Getting next command from history",null))}]});import xl from"chalk";var Dr,yl,hl,si,Il=h(()=>{"use strict";Q();ne();Me();Dr=xl.dim.hex(S.secondary2)(": for command line"),yl="q to exit",hl=`${xl.hex(S.accent)("m")} to confirm`,si={[P.WORKSPACE]:[Dr],[P.BOARD]:[Dr],[P.BOARD+f.COMMAND_LINE]:[Dr],[P.SWIMLANE]:[Dr],[P.TICKET+f.HELP]:[yl],[P.SWIMLANE+f.HELP]:[yl],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+f.MOVE]:[hl],[P.TICKET+f.MOVE]:[hl]}});var Eo,If,bf,bl,El=h(()=>{"use strict";T();xn();Eo=e=>e.trim().toLocaleLowerCase(),If=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},bf=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},bl=(e,t)=>{let n=Eo(t.value);if(!n)return!0;switch(t.target){case"title":return Eo(e.title??"").includes(n);case"description":return Eo(e.props.description??"").includes(n);case"tag":return If(e).map(Eo).some(r=>r.includes(n));case"assignee":return bf(e).map(Eo).some(r=>r.includes(n));case"ref":return ta(e.id,t.value);default:return!0}}});function Nl(e,t,n){let o=t[e];if(!o)return i("buildBreadCrumb(): current node not found");let r=[],s=o;for(;s&&(r.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let d=r[r.length-1];return!d||d.id!==n?i("buildBreadCrumb(): node is not connected to root"):(r.reverse(),c("Breadcrumb built",r))}var Sl=h(()=>{"use strict";C()});var Cl,Rl=h(()=>{"use strict";Cl=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 Ef}from"react";function Tl(e){let{contextNodeId:t,mode:n,rootNodeId:o,nodes:r,filters:s}=e;if(!t)return i("derive(): contextNodeId is missing");if(!o)return i("derive(): rootNode is missing");if(!r[o])return i("derive(): unable to find root node");let l=r[t];if(!l)return i("Unable to derive state, contextNode not found");let u=Nl(t,r,o);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,y=si[p+n]??si[p]??[],N=[...ul,...tl[p]??[],...fl],R=Cl(N),w=Sf(r,s),L=w[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:y,availableActions:N,actionIndex:R,selectedNode:L,renderedChildrenIndex:w})}function eo(e){ii=e;let t=ot(process.cwd()),n=!1;if(!a(t)){let s=St(t.value);if(a(s))return i(s.message);n=!0}let o={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:{},attachments:{}},r=Tl(o);return a(r)?r:(cn=r.value,Al(),c("State initialized",null))}function ye(e){let t=g(),n=e(t),o=Tl(n);return a(o)?i(o.message??"Unable to update state"):(cn=o.value,Al(),c("State updated",null))}var cn,ii,ai,Al,Nf,g,ze,I,Fe,Sf,G,jt,Tn,T=h(()=>{"use strict";nl();ml();vl();Il();Ht();Q();ne();C();ue();El();Sl();Rl();ai=new Set,Al=()=>{for(let e of ai)e()},Nf=e=>(ai.add(e),()=>ai.delete(e));g=()=>{if(!cn)throw new Error("State not initialized. Call initWorkspaceState() first.");return cn},ze=()=>cn?c("Retrieved state",cn):i("State not initialized. Call initWorkspaceState() first.");I=e=>ye(t=>({...t,...e})),Fe=()=>Ef(Nf,g,g),Sf=(e,t)=>{let n={};for(let o of Object.values(e))M(o)&&t.length>0&&!t.every(r=>bl(o,r))||!o.parentNodeId||o.isDeleted||((!o.parentNodeId||!n[o.parentNodeId])&&(n[o.parentNodeId]=[]),n[o.parentNodeId].push(o));for(let o of Object.keys(n))n[o].sort((r,s)=>{let d=e[r.id],l=e[s.id];return!d||!l?0:d.rank.localeCompare(l.rank)});return n},G=e=>g()?.renderedChildrenIndex[e]??[],jt=()=>ii?eo(ii):i("Cannot reset state: no initial workspace found"),Tn=()=>cn!==void 0});var di,Fr,Br,ci,Ge,er=h(()=>{"use strict";ji();C();T();di=e=>{Tn()&&(I({syncStatus:e}),$i({type:"sync-status",payload:e}))},Fr=(e="Syncing...")=>{di({status:"syncing",msg:e})},Br=(e="Synced")=>{di({status:"synced",msg:e})},ci=e=>{di({status:"failed",msg:e})},Ge=e=>(ci(e),i(e))});import{decodeTime as pk}from"ulid";var wl=h(()=>{"use strict";C()});var Cf,Rf,tr,fs=h(()=>{"use strict";C();er();ps();wo();gt();Kt();_o();wl();Cf=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=q("getRepoRootDir",await st(e));if(a(n))return i(n.message);let o=n.value;logger.debug("[sync] repo root",o);let r=q("getStateBranchRoot",ke({repoRoot:o}));if(a(r))return i(r.message);let s=r.value;logger.debug("[sync] state branch root",s);let d=q("ensureInitialCommit",await Bi(o));if(a(d))return i(d.message);logger.debug("[sync] initial commit result",{created:d.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:s,ensureUpstream:t});let l=q("bootstrapStateBranchStorage",await _i({repoRoot:o,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=q("hasInProgressGitOperation(stateBranchRoot)",await ko(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:o,stateBranchRoot:s});let m=q("ensureStateBranchLayout",Pi(o,s));return a(m)?i(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:s,bootstrapped:l.value}),c("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:s,bootstrapped:l.value}))},Rf=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 o=q("stageStateBranchOwnEventFile",await Uo({stateBranchRoot:t,eventFileName:n}));if(a(o))return i(o.message);let r=q("stageStateBranchMediaFiles",await Oi({stateBranchRoot:t}));if(a(r))return i(r.message);let s=q("hasStagedChanges(after stage)",await Ri(t));if(a(s))return i(s.message);if(logger.debug("[sync] state branch change check after stage result",{changed:s.value}),!s.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 d=q("createStateBranchSyncCommit",await Ui({repoRoot:e,stateBranchRoot:t}));return a(d)?i(d.message):(logger.debug("[sync] created sync commit",d.value),c("Committed own event file",{createdCommit:!0,commitSha:d.value}))},tr=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");Fr();let n=q("ensureSyncReady",await Cf({cwd:e,ensureUpstream:!0}));if(a(n))return Ge(n.message);let{repoRoot:o,stateBranchRoot:r,bootstrapped:s}=n.value,d=q("isDetachedHead(stateBranchRoot)",await Ai(r));if(a(d))return Ge(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return Ge("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,p=!1,y=q("getStateBranch",pn(o));if(a(y))return Ge(y.message);let N=y.value;logger.debug("[sync] resolved state branch",{stateBranch:N,stateBranchRoot:r});let R=q("commitOwnEventFileToStateBranch",await Rf({repoRoot:o,stateBranchRoot:r,ownEventFileName:t}));if(a(R))return Ge(R.message);l=R.value.createdCommit,u=R.value.commitSha;let w=q("pullBranchRebaseIfPresent",await Jr({cwd:r,branch:N}));if(a(w))return Ge(w.message);if(m=w.value,l||s){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:s,stateBranchRoot:r});let L=q("pushStateBranch",await Yn({stateBranchRoot:r,repoRoot:o}));if(a(L)&&Ci(L.message)){let $=q("pullBranchRebaseIfPresent(retry)",await Jr({cwd:r,branch:N}));if(a($))return Ge($.message);m=m||$.value,L=q("pushStateBranch(retry)",await Yn({stateBranchRoot:r,repoRoot:o}))}if(a(L))return Ge(L.message);p=L.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:r});let L=q("git rev-parse HEAD",await _({args:["rev-parse","HEAD"],cwd:r}));if(a(L))return Ge(L.message);u=L.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Br(p?"Synced and pushed":m||l?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),c("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:r,createdCommit:l,commitSha:u,pulled:m,pushed:p,bootstrapped:s})}});import{decodeTime as Dk,ulid as K}from"ulid";var Or,Ne,Se,Ce,Af,Tf,Ml,kl,Ll,Pl,Dl,Fl,Bl,Ol,Ul,_l,$l,jl,Wl,Hl,Kl,ql,Vl,zl,Gl,Yl,Xl,Jl=h(()=>{"use strict";gt();Kt();_o();fs();on();ti();Qo();Cn();Qt();et();Vs();Sn();ne();C();Ht();ce();dt();T();er();ue();ft();xn();fn();lo();mn();Or=e=>{let t=ot(e??process.cwd());return a(t)?i(t.message):c("Resolved Epiq repo root",t.value)},Ne=async(e,t)=>{let n=Or(e);if(a(n))return n;let o=ke({repoRoot:n.value});if(a(o))return i(o.message);let r=Ao(),s=await Gn({repoRoot:n.value,stateBranchRoot:o.value,stateBranchName:r.stateBranch});if(a(s))return i(s.message);if(t?.pull??!1){let u=await _({cwd:o.value,args:["pull","--ff-only"]});a(u)&&me.info(3,u.message)}let d=Mt(o.value);if(a(d))return i(d.message);let l=Rn(d.value);return a(l)?i(l.message):c("Booted Epiq state",{repoRoot:n.value,stateBranchRoot:o.value})},Se=()=>{let e=dd();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")},Ce=()=>{let e=ze();return a(e)?i(e.message):e},Af=e=>(e.props.tags??[]).map(t=>x.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Pe(t.name)})),Tf=e=>(e.props.assignees??[]).map(t=>x.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Pe(t.name)})),Ml=async(e={})=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Ce();if(a(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="BOARD"&&!r.isDeleted).map(r=>({id:r.id,ref:Ze(r.id),title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return c("Listed boards",o)},kl=async(e={})=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Ce();if(a(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="SWIMLANE"&&!r.isDeleted).filter(r=>!e.boardId||r.parentNodeId===e.boardId).map(r=>({id:r.id,title:r.title,boardId:r.parentNodeId,isClosed:r.id===pe,readonly:!!r.readonly}));return c("Listed swimlanes",o)},Ll=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Ce();if(a(n))return n;let o=n.value.nodes,r=Object.values(o).filter(M).filter(s=>!s.isDeleted).filter(s=>e.includeClosed||s.parentNodeId!==pe).filter(s=>e.boardId?(s.parentNodeId?o[s.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).map(s=>({id:s.id,ref:Ze(s.id),title:qe(s.title),description:s.props.description??"",parentNodeId:s.parentNodeId,isClosed:s.parentNodeId===pe,readonly:!!s.readonly,tags:Af(s),assignees:Tf(s)}));return c("Listed issues",r)},Pl=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Se();if(a(n))return n;let o=Ce();if(a(o))return o;let r=Zt(e.parentId,n.value,t.value.stateBranchRoot);if(a(r))return r;let s=Ar({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(a(s))return s;let d=[...s.value],l=d.find(y=>y.action==="add.issue")?.payload.id;if(!l)return i("Unable to determine created issue id");e.description&&d.push({id:K(),...n.value,action:"edit.description",payload:{id:l,md:e.description}});let u=[];for(let y of e.tagNames??[]){let N=qe(y).trim();if(!N||u.some(L=>L.name===N))continue;let R=Object.values(o.value.tags).find(L=>L.name===N),w=R?.id??K();R||d.push({id:K(),...n.value,action:"create.tag",payload:{id:w,name:N}}),d.push({id:K(),...n.value,action:"add.issue.tag",payload:{id:l,tag:w}}),u.push({id:w,name:N})}let m=[];for(let y of e.assigneeNames??[]){let N=qe(y).trim();if(!N||m.some(L=>L.name===N))continue;let R=Object.values(o.value.contributors).find(L=>L.name===N),w=R?.id??K();R||d.push({id:K(),...n.value,action:"create.contributor",payload:{id:w,name:N}}),d.push({id:K(),...n.value,action:"add.issue.assignee",payload:{id:l,assignee:w}}),m.push({id:w,name:N})}let p=B(d,t.value.stateBranchRoot);return a(p)?i(p.message):c("Created issue",{id:l,title:e.title,parentId:e.parentId,description:e.description??"",tags:u,assignees:m})},Dl=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Se();if(a(n))return n;let o=kt(pe,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(o))return o;let r={id:K(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:pe,rank:o.value}},s=B([r],t.value.stateBranchRoot);return a(s)?i(s.message):c("Closed issue",{id:e.issueId})},Fl=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Se();if(a(n))return n;let o=Ce();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!M(r))return i("Target node is not issue");if(r.parentNodeId!==pe)return i("Issue is not closed");let s=Sr(r);if(!s)return i("Unable to resolve previous parent from issue history");if(s===pe)return i("Previous parent resolves to closed swimlane");let d=o.value.nodes[s];if(!d)return i("Previous parent no longer exists");let l=kt(d.id,r.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(l))return l;let u={id:K(),...n.value,action:"reopen.issue",payload:{id:r.id,parent:d.id,rank:l.value}},m=B([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Reopened issue",{id:r.id,parentId:d.id})},Bl=async e=>{let t=Or(e.repoRoot);if(a(t))return t;let n=Se();if(a(n))return n;let o=ke({repoRoot:t.value});if(a(o))return o;let r=Mt(o.value);if(a(r))return r;let s=Rn(r.value);if(a(s))return s;let d=kt(e.parentId,e.issueId,e.position??{at:"end"},n.value,o.value);if(a(d))return d;let l={id:K(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:d.value}},u=B([l],o.value);return a(u)?i(u.message):c("Moved issue",{id:e.issueId,parentId:e.parentId})},Ol=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Se();if(a(n))return n;let o=Ce();if(a(o))return o;let r=o.value.nodes[e.boardId];if(!r)return i("Board not found");if(!$o(r))return i("Target parent must be a board");let s=qe(e.title);if(!s.trim())return i("Swimlane title cannot be empty");let d=Zt(e.boardId,n.value,t.value.stateBranchRoot);if(a(d))return d;let l=K(),u={id:K(),...n.value,action:"add.swimlane",payload:{id:l,name:s,parent:e.boardId,rank:d.value}},m=B([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Created swimlane",{id:l,title:s,boardId:e.boardId})},Ul=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Se();if(a(n))return n;let o=Ce();if(a(o))return o;let r=o.value.nodes[e.swimlaneId];if(!r)return i("Swimlane not found");if(!Vt(r))return i("Edit target must be a swimlane");if(r.readonly)return i("Cannot edit readonly swimlane");let s=qe(e.title);if(!s.trim())return i("Swimlane title cannot be empty");if(r.title===s)return c("No changes made",{id:e.swimlaneId,title:s});let d={id:K(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:s}},l=B([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited swimlane title",{id:e.swimlaneId,title:s})},_l=async e=>{let t=Or(e.repoRoot);if(a(t))return t;let n=Se();if(a(n))return n;let o=ke({repoRoot:t.value});if(a(o))return o;let r=Mt(o.value);if(a(r))return r;let s=Rn(r.value);if(a(s))return s;let d=kt(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,o.value);if(a(d))return d;let l={id:K(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:d.value}},u=B([l],o.value);return a(u)?i(u.message):c("Moved swimlane",{id:e.swimlaneId,boardId:e.boardId})},$l=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Se();if(a(n))return n;let o=Ce();if(a(o))return o;let r=o.value.nodes[e.swimlaneId];if(!r)return i("Swimlane not found");if(!Vt(r))return i("Delete target must be a swimlane");let s={id:K(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},d=B([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Deleted swimlane",{id:e.swimlaneId})},jl=async(e={})=>{Fr();let t=Or(e.repoRoot);if(a(t))return i("Sync failed");let n=Se();if(a(n))return n;let o=await tr({cwd:t.value,ownEventFileName:Jt(n.value)});return a(o)?(ci(o.message),o):(Br(),c("Synced",o.value))},Wl=async(e={})=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Ce();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})},Hl=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Se();if(a(n))return n;let o=Ce();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!M(r))return i("Edit target must be an issue");if(r.readonly)return i("Cannot edit readonly issue");let s=r.props.description??"";if(s===e.description)return c("No changes made",{id:e.issueId,description:s});let d={id:K(),...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})},Kl=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Se();if(a(n))return n;let o=Ce();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!M(r))return i("Edit target must be an issue");if(r.readonly)return i("Cannot edit readonly issue");let s=qe(e.title);if(!s.trim())return i("Issue title cannot be empty");if(r.title===s)return c("No changes made",{id:e.issueId,title:s});let d={id:K(),...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})},ql=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Se();if(a(n))return n;let o=Ce();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!M(r))return i("Tag target must be an issue");if(r.readonly)return i("Cannot tag readonly issue");let s=qe(e.tagName).trim();if(!s)return i("Tag name cannot be empty");let d=Object.values(o.value.tags).find(p=>p.name===s),l=d?.id??K(),u=[...d?[]:[{id:K(),...n.value,action:"create.tag",payload:{id:l,name:s}}],{id:K(),...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}})},Vl=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Se();if(a(n))return n;let o=Ce();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!M(r))return i("Untag target must be an issue");if(r.readonly)return i("Cannot untag readonly issue");if(!o.value.tags[e.tagId])return i("Tag not found");let s={id:K(),...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})},zl=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Se();if(a(n))return n;let o=Ce();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!M(r))return i("Assign target must be an issue");if(r.readonly)return i("Cannot assign readonly issue");let s=qe(e.assigneeName).trim();if(!s)return i("Assignee name cannot be empty");let d=Object.values(o.value.contributors).find(p=>p.name===s),l=d?.id??K(),u=[...d?[]:[{id:K(),...n.value,action:"create.contributor",payload:{id:l,name:s}}],{id:K(),...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}})},Gl=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Se();if(a(n))return n;let o=Ce();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!M(r))return i("Unassign target must be an issue");if(r.readonly)return i("Cannot unassign readonly issue");if(!o.value.contributors[e.assigneeId])return i("Assignee not found");let s={id:K(),...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})},Yl=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Se();if(a(n))return n;let o=Ce();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!M(r))return i("Comment target must be an issue");if(r.readonly)return i("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return i("Comment cannot be empty");let d=K(),l={id:K(),...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})},Xl=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(a(t))return t;let n=Se();if(a(n))return n;let o=Ce();if(a(o))return o;let r=o.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!r)return i("Unable to resolve comment");if(r.payload.author!==n.value.userId)return i("You can only delete your own comments");let s=o.value.nodes[r.payload.issue];if(!s)return i("Issue not found");if(!M(s))return i("Comment target must be an issue");if(s.readonly)return i("Cannot delete comment on readonly issue");if(o.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return c("Comment already deleted",{id:e.commentId,issueId:r.payload.issue});let l={id:K(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:r.payload.issue}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Deleted issue comment",{id:e.commentId,issueId:r.payload.issue})}});var eu={};su(eu,{createMcpServer:()=>Ql,resultJson:()=>se,startMcpServer:()=>Zl});import{McpServer as wf}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Mf}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as b}from"zod";var se,Ql,Zl,tu=h(async()=>{"use strict";C();Jl();se=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Ql=()=>{let e=new wf({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=>se(await Wl(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues. Pass boardId to scope results to a single board and reduce response size.",inputSchema:b.object({repoRoot:b.string().optional(),includeClosed:b.boolean().optional(),boardId:b.string().optional()})},async t=>se(await Ll(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:b.object({repoRoot:b.string().optional()})},async t=>se(await Ml(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:b.object({repoRoot:b.string().optional(),boardId:b.string().optional()})},async t=>se(await kl(t))),e.registerTool("epiq_swimlane_create",{description:"Create an Epiq swimlane on a board",inputSchema:b.object({repoRoot:b.string().optional(),boardId:b.string().min(1),title:b.string().min(1)})},async t=>se(await Ol(t))),e.registerTool("epiq_swimlane_title_edit",{description:"Edit an Epiq swimlane title",inputSchema:b.object({repoRoot:b.string().optional(),swimlaneId:b.string().min(1),title:b.string().min(1)})},async t=>se(await Ul(t))),e.registerTool("epiq_swimlane_move",{description:"Move/reorder an Epiq swimlane, optionally to another board",inputSchema:b.object({repoRoot:b.string().optional(),swimlaneId:b.string().min(1),boardId: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()})},async t=>se(await _l(t))),e.registerTool("epiq_swimlane_delete",{description:"Delete (archive) an Epiq swimlane. This also archives every issue contained in it.",inputSchema:b.object({repoRoot:b.string().optional(),swimlaneId:b.string().min(1)})},async t=>se(await $l(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue. Optionally set description, tags, and assignees atomically in the same call instead of separate follow-up edits.",inputSchema:b.object({title:b.string().min(1),parentId:b.string().min(1),repoRoot:b.string().optional(),description:b.string().optional(),tagNames:b.array(b.string()).optional(),assigneeNames:b.array(b.string()).optional()})},async t=>se(await Pl(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=>se(await Hl(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=>se(await Kl(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=>se(await ql(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=>se(await Vl(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=>se(await zl(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=>se(await Gl(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=>se(await Yl(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=>se(await Xl(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=>se(await Fl(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=>se(await Dl(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=>se(await Bl(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote (pull remote changes and push local ones). Other Epiq MCP tools only read and write local state and never sync automatically \u2014 call this on demand when you need to see or publish the latest remote changes.",inputSchema:b.object({repoRoot:b.string().optional()})},async t=>se(await jl(t))),e},Zl=async()=>{let e=Ql(),t=new Mf;await e.connect(t)};await Zl()});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;await tu().then(()=>eu);