epiq 0.6.20 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -1,62 +1,57 @@
1
1
  #!/usr/bin/env node
2
- var Lc=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var Pc=(e,t)=>{for(var n in t)Lc(e,n,{get:t[n],enumerable:!0})};var Qe,s,c,a,Jt,C=y(()=>{"use strict";Qe={None:"none",Success:"success",Fail:"fail"},s=e=>({status:Qe.Fail,message:e,value:null}),c=(e,t)=>({status:Qe.Success,message:e,value:t}),a=e=>e.status==="fail",Jt=e=>e.status==="success"});function jr(e){return e.context===w.WORKSPACE}function B(e){return e.context===w.TICKET}function pi(e){return e.context===w.TEXT}function Ze(e){return e.context===w.FIELD}function Qt(e){return e.context===w.FIELD_LIST}var w,Mn,gi,Z=y(()=>{"use strict";w={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};Mn=e=>e.context===w.SWIMLANE,gi=e=>e.context===w.BOARD});function fi(e){return!e||!Fc.test(e)?s(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Ce(e,t=Rt){if(e<0n)return s("Negative rank not allowed");let n=e.toString(16);return c("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function me(e,t){if(!e&&!t)return Ce(He/2n,Rt);let n=e?fi(e):c("Resolved lower bound",0n);if(a(n))return n;let r=t?fi(t):c("Resolved upper bound",He);if(a(r))return r;let o=n.value,i=r.value;if(i<=o)return Ce(He/2n,Rt);let d=(o+i)/2n;return d===o||d===i?s("No rank space available between neighbors"):Ce(d,Rt)}function vi(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=He*BigInt(r+1)/(t+1n),i=Ce(o,Rt);if(a(i))return i;n.push(i.value)}return c("Resolved evenly spaced ranks",n)}var Rt,kc,He,Fc,At=y(()=>{"use strict";C();Rt=24n,kc=Rt*4n,He=(1n<<kc)-1n,Fc=/^[0-9a-f]+$/});import{ulid as Dc}from"ulid";var Hr,yi=y(()=>{"use strict";C();Se();At();Hr=(e,t)=>{let n=H(e),r=vi(n.length);if(a(r))return r;let o={};for(let i=0;i<n.length;i++){let d=n[i],l=r.value[i];if(!d||!l)return s("Unable to assign rebalance rank");o[d.id]=l}return c("Created rebalance event",{id:Dc(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})}});import Zt from"node:fs";import{ulid as Oc}from"ulid";import{z as Ln}from"zod";var Uc,Bc,xi,et,hi,Ei,wt=y(()=>{"use strict";C();re();Uc="__epiq_state__",Bc=Ln.object({projectId:Ln.string().min(1),stateBranch:Ln.string().min(1),createdAt:Ln.iso.datetime()}),xi=()=>({projectId:Oc(),stateBranch:Uc,createdAt:new Date().toISOString()}),et=e=>{let t=kn(e);if(!Zt.existsSync(t))return s("Missing .epiq/project.json");try{let n=Zt.readFileSync(t,"utf8"),r=JSON.parse(n),o=Bc.safeParse(r);return o.success?c("Read project.json",o.data):s(`Invalid .epiq/project.json: ${o.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(", ")}`)}catch(n){return s(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},hi=e=>{let t=et(e);return a(t)?s(t.message):c("Read projectId",t.value.projectId)},Ei=({repoRoot:e,fileContents:t})=>{let n=Pn(e),r=kn(e);try{if(Zt.mkdirSync(n,{recursive:!0}),Zt.existsSync(r)){let o=et(e);return a(o)?s(o.message):c("Project already initialized",null)}return Zt.writeFileSync(r,JSON.stringify(t,null,2)+`
3
- `,"utf8"),c("Created project.json",null)}catch(o){return s(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}}});var zr,Ni=y(()=>{"use strict";C();zr=(e,t)=>{let n=new Map,r=t??((...i)=>JSON.stringify(i)),o=((...i)=>{let d=r(...i);if(!n.has(d)){let l=e(...i).then(u=>(a(u)&&n.delete(d),u));n.set(d,l)}return n.get(d)});return o.clear=()=>n.clear(),o}});import en from"fs";import Gr from"path";import _c from"util";function Wc(){let e=Ci();if(!e||!en.existsSync(e))return;let n=en.readFileSync(e,"utf8").split(`
4
- `);if(n[n.length-1]===""&&n.pop(),n.length<=Ii)return;let r=n.slice(-Ii).join(`
2
+ var kc=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var Dc=(e,t)=>{for(var n in t)kc(e,n,{get:t[n],enumerable:!0})};var st,i,c,a,ft,b=y(()=>{"use strict";st={None:"none",Success:"success",Fail:"fail"},i=e=>({status:st.Fail,message:e,value:null}),c=(e,t)=>({status:st.Success,message:e,value:t}),a=e=>e.status==="fail",ft=e=>e.status==="success"});import an from"node:fs";import Xe from"node:path";var Dp,Je,Te,Wn,Fc,Hn,Vn,dn,Rs,Oc,or,zn,it,As,Oe,ce=y(()=>{"use strict";b();vt();Dp=process.env.IS_LOCAL==="true",Je=".epiq",Te=".epiq-global",Wn="events",Fc="project.json",Hn=e=>Xe.join(e,Je),Vn=e=>Xe.join(Hn(e),Fc),dn=e=>Xe.join(Hn(e),Wn),Rs=e=>Xe.join(e,Je),Oc=e=>{let t=Xe.join(e,Je);return an.existsSync(t)&&an.statSync(t).isDirectory()},or=e=>{let t=Vn(e);return an.existsSync(t)&&an.statSync(t).isFile()},zn=e=>{let t=Xe.resolve(e);for(;;){if(Oc(t))return c("Resolved closest .epiq root",t);let n=Xe.dirname(t);if(n===t)return i("No .epiq directory found in any parent");t=n}},it=e=>{let t=Xe.resolve(e);for(;;){if(or(t))return c("Resolved closest epiq project root",t);let n=Xe.dirname(t);if(n===t)return i("No .epiq/project.json found in any parent");t=n}},As=e=>{let t=dn(e);try{return an.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")}},Oe=async()=>{let e=await at(process.cwd());if(a(e))return e;let t=Qe({repoRoot:e.value});return a(t)?t:c("Resolved persist root",t.value)}});import cn from"node:fs";import{ulid as Uc}from"ulid";import{z as qn}from"zod";var Bc,_c,Gn,dt,Ts,ws,yt=y(()=>{"use strict";b();ce();Bc="__epiq_state__",_c=qn.object({projectId:qn.string().min(1),stateBranch:qn.string().min(1),createdAt:qn.iso.datetime()}),Gn=()=>({projectId:Uc(),stateBranch:Bc,createdAt:new Date().toISOString()}),dt=e=>{let t=Vn(e);if(!cn.existsSync(t))return i("Missing .epiq/project.json");try{let n=cn.readFileSync(t,"utf8"),o=JSON.parse(n),r=_c.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")}},Ts=e=>{let t=dt(e);return a(t)?i(t.message):c("Read projectId",t.value.projectId)},ws=({repoRoot:e,fileContents:t})=>{let n=Hn(e),o=Vn(e);try{if(cn.mkdirSync(n,{recursive:!0}),cn.existsSync(o)){let r=dt(e);return a(r)?i(r.message):c("Project already initialized",null)}return cn.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 rr,Ms=y(()=>{"use strict";b();rr=(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 ln from"fs";import dr from"path";import $c from"util";function Wc(){let e=ks();if(!e||!ln.existsSync(e))return;let n=ln.readFileSync(e,"utf8").split(`
4
+ `);if(n[n.length-1]===""&&n.pop(),n.length<=Ls)return;let o=n.slice(-Ls).join(`
5
5
  `)+`
6
- `;en.writeFileSync(e,r,"utf8")}function qr(e,t,n=!1){let r=Ci();if(!r)return;let o=_c.format(...t),i=new Date,l=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
7
- `;en.mkdirSync(Gr.dirname(r),{recursive:!0}),en.appendFileSync(r,l,"utf8"),Vr++,Vr>=$c&&(Vr=0,Wc())}var Ii,$c,Vr,bi,Ci,Kr,le,Fn=y(()=>{"use strict";C();re();Ii=1e3,$c=50,Vr=0,bi=()=>process.env.EPIQ_MCP==="true",Ci=()=>{let e=process.cwd(),t=Dn(e);return a(t)?bi()?Gr.join(process.cwd(),".epiq-mcp.log"):void 0:Gr.join(t.value,ze,"log","epiq.log")};Kr=()=>bi()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",le={info(...e){let t=Kr();(t==="info"||t==="debug")&&qr("[Info]",e,!1)},debug(...e){Kr()==="debug"&&qr("[Debug]",e,!0)},error(...e){let t=Kr();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;qr("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=le});var K,On=y(()=>{"use strict";Tt();K={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 ut,pe,Un=y(()=>{"use strict";wt();C();re();ut=e=>{let t=tt(e);if(a(t))return s("Unable to resolve epiq project root");let n=et(t.value);return a(n)?s("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},pe="origin"});import{spawn as jc}from"node:child_process";import Bn from"node:fs";import tn from"node:path";var Si,Hc,Ai,_,Re,Mt,zc,Vc,_n,Yr,nn,$n,Ri,wi,Xr,Wn,Ti,Mi,Li,Pi,Jr,ki,Fi,Tt=y(()=>{"use strict";C();On();Un();Si=1e4,Hc={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Ai=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Bn.existsSync(t)){let g=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:g,exitCode:1});return}r(s(g));return}let o=jc("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Hc}),i=!1,d="",l="",u=g=>{i||(i=!0,clearTimeout(m),r(g))},m=setTimeout(()=>{o.kill("SIGTERM");let g=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${Si}ms`].join(`
8
- `);u(n?{stdout:d,stderr:g,exitCode:124}:s(g))},Si);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",g=>{d+=g}),o.stderr.on("data",g=>{l+=g}),o.on("error",g=>{if(n){u({stdout:d,stderr:g.message,exitCode:1});return}u(s([`git ${e.join(" ")}`,`cwd=${t}`,g.message].join(`
9
- `)))}),o.on("close",g=>{let x=g??1;if(n){u({stdout:d,stderr:l,exitCode:x});return}if(x!==0){u(s([`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:x}))})}),_=({args:e,cwd:t})=>Ai({args:e,cwd:t,allowFail:!1}),Re=({args:e,cwd:t})=>Ai({args:e,cwd:t,allowFail:!0}),Mt=async({cwd:e,message:t})=>{let n=await K.commit({cwd:e,message:t});if(a(n))return s(`Failed to create commit
11
- ${n.message}`);let r=await _({args:["rev-parse","HEAD"],cwd:e});return a(r)?s(`Commit created, but failed to read HEAD SHA
12
- ${r.message}`):c("Created commit and resolved SHA",r.value.stdout.trim())},zc=async e=>{let t=await _({cwd:e,args:["rev-parse","--git-dir"]});if(a(t))return s(t.message);let n=t.value.stdout.trim();return c("Resolved git dir",tn.isAbsolute(n)?n:tn.resolve(e,n))},Vc=async e=>{let t=await zc(e);if(a(t))return s(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[i,d]of Object.entries(r))if(Bn.existsSync(tn.join(n,i)))return c("Checked for in-progress Git operation",d);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[i,d]of Object.entries(o))if(Bn.existsSync(tn.join(n,i)))return c("Checked for in-progress Git operation",d);return c("Checked for in-progress Git operation",null)},_n=async e=>{let t=await Vc(e);return a(t)?s(t.message):c("Checked for in-progress Git operation",t.value!==null)},Yr=async({repoRoot:e})=>{let n=(await Re({args:["remote","get-url",pe],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},nn=async({repoRoot:e,branch:t})=>{let n=await Re({args:["ls-remote","--heads",pe,t],cwd:e});return n.exitCode!==0?s(n.stderr.trim()||`Unable to inspect remote branch ${pe}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},$n=async({repoRoot:e,branch:t})=>{let n=await Re({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):s(n.stderr.trim()||`Unable to inspect branch ${t}`)},Ri=e=>{try{return Bn.realpathSync.native(e)}catch{return tn.resolve(e)}},wi=async({repoRoot:e,worktreeRoot:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return s(n.message);let r=Ri(t),o=n.value.stdout.split(`
13
- `).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(Ri).includes(r);return c("Checked worktree registration",o)},Xr=async e=>{let t=await Re({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Wn=async e=>{let t=await _({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?s(t.message):c("Resolved current branch",t.value.stdout.trim())},Ti=async e=>{let t=await _({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?s(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},Mi=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Li=async e=>(await Re({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1),Pi=async({cwd:e,branch:t})=>{let n=await nn({repoRoot:e,branch:t});if(a(n))return s(n.message);if(!n.value)return c("Remote branch missing, skipped reset",!1);let r=await K.fetch({cwd:e,remote:pe,branch:t});if(a(r))return s(`Failed to fetch ${t}
14
- ${r.message}`);let o=await Li(e);if(a(o))return s(o.message);let i=await _({cwd:e,args:["reset","--hard",`${pe}/${t}`]});return a(i)?s(`Failed to reset ${t} from remote
15
- ${i.message}`):c("Reset branch from remote",!0)},Jr=async({cwd:e,branch:t})=>{let n=await nn({repoRoot:e,branch:t});if(a(n))return s(n.message);if(!n.value)return c("Remote branch missing, skipped pull",!1);let r=await Li(e);if(a(r))return s(r.message);let o=await K.fetch({cwd:e,remote:pe,branch:t});if(a(o))return s(`Failed to fetch ${t}
16
- ${o.message}`);let i=await K.pullRebase({cwd:e,remote:pe,branch:t});return a(i)?s(`Failed during pull --rebase
17
- ${i.message}`):c("Pulled with rebase",!0)},ki=async e=>{let t=await Re({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?c("No staged changes",!1):t.exitCode===1?c("Has staged changes",!0):s(t.stderr.trim()||"Unable to inspect staged changes")},Fi=async e=>{let t=await Wn(e);return a(t)?s(t.message):c("Checked detached HEAD state",t.value==="HEAD")}});import Qr from"node:fs";import qc from"node:os";import Pe from"node:path";var Oi,on,Ui,jn,Lt,Kc,Di,rn,Hn,Bi,_i,$i,nt,pg,Pt=y(()=>{"use strict";wt();C();re();Ni();Fn();Tt();Oi="4b825dc642cb6eb9a060e54bf8d69288fbee4904",on=e=>Pe.join(ze,zn,e),Ui=()=>Pe.join(qc.homedir(),Ee),jn=()=>Pe.join(Ui(),"worktrees"),Lt=({repoRoot:e})=>{let t=hi(e);return a(t)?s(t.message):c("Resolved state branch root",Pe.join(jn(),t.value))},Kc=e=>Pe.join(e,ze),Di=e=>Pe.join(Kc(e),zn),rn=e=>{try{return Qr.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return s(t instanceof Error?t.message:String(t))}},Hn=()=>{let e=rn(Ui());if(a(e))return s(`Ensure epiq home failed.
18
- `+e.message);let t=rn(jn());return a(t)?s(`Ensure worktrees dir failed.
19
- `+t.message):c("Ensured epiq storage",!0)},Bi=e=>{Qr.existsSync(e)&&(le.debug("[sync] remove path",e),Qr.rmSync(e,{recursive:!0,force:!0}))},_i=(e,t)=>{for(let n of[Di(e),Di(t)]){let r=rn(n);if(a(r))return s(r.message)}return c("Ensured state branch",void 0)},$i=async e=>{let t=await _({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return s(`ensure state branch is storage only failed
20
- `+t.message);let r=t.value.stdout.trim().split(`
21
- `).filter(Boolean).filter(d=>d!==ze);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 s(`Failed to clean storage branch
22
- ${o.message}`);let i=await Mt({cwd:e,message:"[epiq:repair-storage-branch]"});return a(i)?s(i.message):c("Cleaned storage branch",!0)},nt=zr(async(e=process.cwd())=>{let t=await _({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?s("Not inside a Git repository"):c("Resolved repo root",t.value.stdout.trim())},e=>Pe.resolve(e)),pg=zr(async e=>{let t=await _({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return s(t.message);let n=t.value.stdout.trim(),r=Pe.isAbsolute(n)?n:Pe.join(e,n);return c("Resolved git dir",r)},e=>Pe.resolve(e))});import sn from"node:fs";import Ve from"node:path";var Eg,ze,Ee,zn,Gc,Pn,kn,an,Wi,Yc,Zr,Dn,tt,ji,Ae,re=y(()=>{"use strict";C();Pt();Eg=process.env.IS_LOCAL==="true",ze=".epiq",Ee=".epiq-global",zn="events",Gc="project.json",Pn=e=>Ve.join(e,ze),kn=e=>Ve.join(Pn(e),Gc),an=e=>Ve.join(Pn(e),zn),Wi=e=>Ve.join(e,ze),Yc=e=>{let t=Ve.join(e,ze);return sn.existsSync(t)&&sn.statSync(t).isDirectory()},Zr=e=>{let t=kn(e);return sn.existsSync(t)&&sn.statSync(t).isFile()},Dn=e=>{let t=Ve.resolve(e);for(;;){if(Yc(t))return c("Resolved closest .epiq root",t);let n=Ve.dirname(t);if(n===t)return s("No .epiq directory found in any parent");t=n}},tt=e=>{let t=Ve.resolve(e);for(;;){if(Zr(t))return c("Resolved closest epiq project root",t);let n=Ve.dirname(t);if(n===t)return s("No .epiq/project.json found in any parent");t=n}},ji=e=>{let t=an(e);try{return sn.mkdirSync(t,{recursive:!0}),c("Resolved events dir",t)}catch(n){return s(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},Ae=async()=>{let e=await nt(process.cwd());if(a(e))return e;let t=Lt({repoRoot:e.value});return a(t)?t:c("Resolved persist root",t.value)}});var ee,kt=y(()=>{"use strict";ee={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History"}});var p,G=y(()=>{"use strict";p={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var Hi=y(()=>{"use strict";mt()});function Vn(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var qn,Kn,Ft=y(()=>{"use strict";qn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Kn=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var zi,Vi,qi=y(()=>{"use strict";zi=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),i=t.get(o);i?i.push(n):t.set(o,[n])}return t},Vi=(e,t)=>t?e.get(t)??[]:[]});var Ki,Xc,Gi,Yi=y(()=>{"use strict";Ft();qi();Ki=new WeakMap,Xc=e=>{let t=Ki.get(e);return t||(t=zi(e),Ki.set(e,t)),t},Gi=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Vi(Xc(e),r).filter(i=>Vn(r,i)>=n)}});var Jc,Xi,Qc,Ji=y(()=>{"use strict";Ft();Yi();Jc={hint:"",hints:[],overlap:0,remainder:""},Xi=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Jc;let o=Gi({wordList:r,inputToMatch:e,overlapThreshold:1});return Qc(t,o)},Qc=(e,t)=>{let n=t[0]??"",r=Vn(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),d=r<(o??"").length,l=!!i,g=(l&&d?o:n)+(l&&d?":":" "),x=g.slice(r);return{hint:g,hints:t,overlap:r,remainder:x}}});import{useSyncExternalStore as Og}from"react";var Gn,Zc,el,Y,ke,ge=y(()=>{"use strict";Gn={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Zc=new Set,el=()=>{for(let e of Zc)e()},Y=()=>Gn,ke=e=>(Gn={...Gn,...e},el(),Gn)});var Dt,Qi,Zi,eo,to,dn,no,tl,es,nl,ts,Yn=y(()=>{"use strict";C();ge();T();Xn();Dt=3e3,Qi=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Dt?null:t},Zi=0,to=!1,dn=!1,no=()=>{if(to)return!0;let e=Fe();return a(e)?!1:e.value.syncStatus.status==="syncing"},tl=()=>{let e=Y().autoSyncIntervalMs??1e4,t=Date.now()-Zi;return Math.max(0,e-t)},es=()=>{eo||(eo=setTimeout(async()=>{if(eo=void 0,!!Ot()){if(no()){dn=!0;return}dn=!1,await nl()}},tl()))},nl=async()=>{if(v().readOnly||v().timeMode==="peek")return s("Cannot auto-sync while peeking");if(!Ot())return s("Cannot auto-sync before state is initialized");if(no())return dn=!0,s("Sync already in progress");to=!0,Zi=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await qe()}finally{to=!1,dn&&es()}},ts=()=>{Ot()&&(dn=!0,!no()&&es())}});var Jn,ns,rs,os,cn=y(()=>{"use strict";C();wt();ge();re();Jn=()=>{let e=Y(),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}},ns=()=>{let e=tt(process.cwd());if(a(e))return!1;let t=et(e.value);return Jt(t)},rs=e=>e===!0?"on":e===!1?"off":null,os=e=>e==="on"?!0:e==="off"?!1:null});var se,P,xe=y(()=>{"use strict";se={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"},P={accent:se.cyan,accent2:se.magenta,primary:se.white,secondary:se.grayDark,secondary2:se.grayLight,gray:se.gray,green:se.green,yellow:se.yellow,red:se.red}});var h,pt,Qn=y(()=>{"use strict";xe();h={red:se.red,yellow:se.yellow,green:se.green,blue:se.blue,magenta:se.magenta,cyan:se.cyan},pt={urgent:h.red,critical:h.red,important:h.red,blocker:h.red,asap:h.red,immediate:h.red,fail:h.red,failure:h.red,broken:h.red,bug:h.red,error:h.red,incident:h.red,outage:h.red,production:h.red,crash:h.red,security:h.red,warning:h.yellow,warn:h.yellow,risky:h.yellow,risk:h.yellow,attention:h.yellow,pending:h.yellow,review:h.yellow,"needs-review":h.yellow,qa:h.yellow,testing:h.yellow,test:h.yellow,validate:h.yellow,verification:h.yellow,staging:h.yellow,check:h.yellow,"follow-up":h.yellow,followup:h.yellow,waiting:h.yellow,blocked:h.yellow,hold:h.yellow,done:h.green,complete:h.green,completed:h.green,success:h.green,ok:h.green,stable:h.green,resolved:h.green,fixed:h.green,closed:h.green,merged:h.green,released:h.green,deployed:h.green,approved:h.green,verified:h.green,working:h.green,healthy:h.green,pass:h.green,passing:h.green,info:h.blue,information:h.blue,note:h.blue,docs:h.blue,documentation:h.blue,doc:h.blue,guide:h.blue,help:h.blue,explanation:h.blue,detail:h.blue,details:h.blue,context:h.blue,design:h.blue,discussion:h.blue,proposal:h.blue,idea:h.blue,feature:h.magenta,enhancement:h.magenta,improvement:h.magenta,refactor:h.magenta,refactoring:h.magenta,cleanup:h.magenta,optimize:h.magenta,optimization:h.magenta,perf:h.magenta,performance:h.magenta,upgrade:h.magenta,migration:h.magenta,modernize:h.magenta,debt:h.magenta,todo:h.cyan,next:h.cyan,planned:h.cyan,plan:h.cyan,future:h.cyan,backlog:h.cyan,investigate:h.cyan,explore:h.cyan,prototype:h.cyan}});var rl,ol,ro,oo,Zn,er,tr=y(()=>{"use strict";Z();C();ae();T();rl=e=>e.props.tags??[],ol=e=>e.props.assignees??[],ro=e=>rl(e).map(t=>N.getTag(t)).filter(t=>!!t),oo=e=>ol(e).map(t=>N.getContributor(t)).filter(t=>!!t),Zn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!B(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",ro(n))},er=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!B(n)?s("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",oo(n))}});var f,gt=y(()=>{"use strict";f={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""}});var il,sl,al,dl,cl,nr,is,ll,ss,rr=y(()=>{"use strict";il=/^(\d+)(h|d|w|mo|y)$/,sl=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,al=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let i=new Date(e,t-1,n,r,o);return i.getFullYear()===e&&i.getMonth()===t-1&&i.getDate()===n&&i.getHours()===r&&i.getMinutes()===o},dl=(e,t=new Date)=>{let n=e.match(il);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let d=new Date(t);switch(o){case"h":return d.setHours(d.getHours()-i),d;case"d":return d.setDate(d.getDate()-i),d;case"w":return d.setDate(d.getDate()-i*7),d;case"mo":return d.setMonth(d.getMonth()-i),d;case"y":return d.setFullYear(d.getFullYear()-i),d;default:return null}},cl=e=>{let t=e.match(sl);if(!t)return null;let[,n,r,o,i,d]=t,l=Number(n),u=Number(r),m=Number(o),g=i?Number(i):0,x=d?Number(d):0;return al({year:l,month:u,day:m,hour:g,minute:x})?new Date(l,u-1,m,g,x):null},nr=e=>{let t=e.trim().toLowerCase();return dl(t)??cl(t)},is=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,ll=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],ss=(e=ll)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let i=r;i<=o;i++)t.push(`${i}${n}`);return t}});var ul,X,rt,ml,pl,so,ft,or,io,as,gl,fl,vl,oe,ln=y(()=>{"use strict";Yn();cn();ae();T();Qn();tr();gt();rr();ul=["BOARD","TICKET","SWIMLANE"],X={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},rt={TITLE:"title",DESCRIPTION:"description"},ml=[X.EDITOR,X.VIEW,X.USERNAME,X.AUTOSYNC,X.SYNC_DEBOUNCE_MS,X.LOG_LEVEL],pl=[rt.TITLE,rt.DESCRIPTION],so=[String(Dt),"5000","15000","30000","60000"],ft=[f.COFFEE,f.EXIT,f.SYNC,f.HELP,f.EXPORT,f.CONFIG],or=[f.NEW,f.EDIT,f.DELETE,f.MOVE],io=[f.TAG,f.UNTAG,f.ASSIGN,f.UNASSIGN,f.CLOSE_ISSUE,f.RE_OPEN_ISSUE,f.EDIT],as=[f.FILTER,f.PEEK],gl={WORKSPACE:[...ft,...or],BOARD:[...as,...ft,...or],SWIMLANE:[...as,...ft,...or],TICKET:[...ft,...or,...io],FIELD:[...ft,...io],FIELD_LIST:[...ft,...io],TEXT:[...ft]},fl=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],vl=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Jn();if(!r)return[f.HELP,f.CONFIG];if(!ns())return[f.HELP,f.INIT];if(t)return[f.HELP,f.PEEK,f.EXPORT,f.CONFIG];let o=e?.context,i=o&&ul.includes(o);return[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?gl[l]:[]))].filter(l=>l===f.MOVE?!1:l===f.EDIT||l===f.DELETE?i:!0)},oe=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let i=t.context??"WORKSPACE";return{[f.NONE]:vl({breadCrumb:o,readOnly:r,selectedNode:n}),[f.EXIT]:["confirm"],[f.EXPORT]:[],[f.SYNC]:[],[f.INIT]:[],[f.HELP]:[],[f.PEEK]:[...ss(),"now","prev","next"],[f.EDIT]:[...pl],[f.DELETE]:["confirm"],[f.RE_OPEN_ISSUE]:["confirm"],[f.CLOSE_ISSUE]:["confirm"],[f.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[f.FILTER]:["tag","assignee","description","title","clear"],[f.TAG]:[...new Set([...Object.keys(pt),...N.getExistingTags()])],[f.UNTAG]:[...Zn()?.value?.map(({name:l})=>l)??[]],[f.UNASSIGN]:[...er()?.value?.map(({name:l})=>l)??[]],[f.ASSIGN]:N.getExistingAssignees(),[f.NEW]:fl(i),[f.CONFIG]:[...ml],[f.COFFEE]:["1","3","5","20","custom"]}[e]??[]}});var ds,cs=y(()=>{"use strict";ds=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{decodeTime as ls}from"ulid";var us,ms,ao,ir=y(()=>{"use strict";C();us=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 i=Math.floor(t/o);if(i>=1)return`${i}${r} ago`}return"just now"},ms=e=>{try{return c("Decoded date",new Date(ls(e)))}catch(t){return s("Decoding failed + "+t.message)}},ao=e=>{if(!e?.id)return null;try{return ls(e.id)}catch{return null}}});var De,un=y(()=>{"use strict";C();De=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?c("Found node",n):s("Unable to find node in breadcrumb")}});import ps from"chalk";var yl,uo,lo,gs,co,fs,xl,hl,vs,El,ys,Nl,Il,bl,mn,Oe,xs,Cl,sr,Sl,Rl,ar,vt=y(()=>{"use strict";Qn();yl=[0,0,0],uo=.2,lo={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},gs=(e,t,n)=>Math.max(t,Math.min(n,e)),co=(e,t,n)=>e+(t-e)*n,fs=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},xl=e=>e.toLowerCase().trim(),hl=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,d=e/60,l=i*(1-Math.abs(d%2-1)),u=0,m=0,g=0;d>=0&&d<1?(u=i,m=l):d>=1&&d<2?(u=l,m=i):d>=2&&d<3?(m=i,g=l):d>=3&&d<4?(m=l,g=i):d>=4&&d<5?(u=l,g=i):(u=i,g=l);let x=o-i/2;return[Math.round((u+x)*255),Math.round((m+x)*255),Math.round((g+x)*255)]},vs=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,El=e=>{let t=e.replace("#","");return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]},ys=(e,t,n)=>{let r=gs(n,0,1);return[Math.round(co(e[0],t[0],r)),Math.round(co(e[1],t[1],r)),Math.round(co(e[2],t[2],r))]},Nl=(e,t=uo)=>ys(e,yl,t),Il=(e,t=uo)=>vs(Nl(El(e),t)),bl=(e,t,n)=>ys(e,t,n),mn=e=>{let n=fs(e)%360,r=hl(n,lo.stringColor.saturation,lo.stringColor.lightness);return vs(r)},Oe=(e,t=pt)=>{let n=xl(e);return n&&t[n]?t[n]:mn(n)},xs=(e,t=pt,n=uo)=>Il(Oe(e,t),n),Cl=e=>{let t=lo.gradient.stops,n=gs(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,i=Math.min(Math.floor(o),r-1),d=o-i;return bl(t[i],t[i+1],d)},sr=e=>fs(e.toLowerCase().trim())/4294967295,Sl=e=>{let t=sr(e);return Cl(t)},Rl=e=>{let[t,n,r]=Sl(e);return{normal:o=>ps.bgRgb(t,n,r).black(o),cursor:o=>ps.bgRgb(t,n,r).white.bold(o)}},ar=e=>Rl(e).normal(` ${e} `)});import hs from"chalk";var te,fe,de,Es=y(()=>{"use strict";vt();xe();te=e=>hs.dim(e),fe=e=>hs.hex(P.primary)(e),de=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let d=o.trim();if(d.length<i)return"";let g=[...t.filter(Boolean).filter(x=>x.startsWith(d))].sort((x,b)=>sr(x)-sr(b)).slice(0,r).map(x=>ar(x)).join(" ");return g?`${te(e)}${g}${te(n)}`:""}});var yt,dr=y(()=>{"use strict";yt={None:"none",Invalid:"invalid",Valid:"valid"}});import Is from"chalk";var Al,Ns,ne,z,O,lr,cr,mo,wl,Ut,Tl,Ml,Ll,bs,Cs=y(()=>{"use strict";Yn();cn();cs();ir();un();C();ae();ge();T();vt();tr();Es();gt();dr();ln();rr();Al=["BOARD","TICKET","SWIMLANE"],Ns=()=>{let e=v().selectedNode;return e?.context?Al.includes(e.context)?z():O({message:te("Command not available in this context")}):O({message:te("Missing target context")})},ne="<ENTER> to confirm",z=(e="",t=[])=>({message:te(e),validity:yt.Valid,completionWordList:t}),O=({message:e,completionWordList:t=[]})=>({validity:yt.Invalid,message:e,completionWordList:t}),lr=e=>e.length===0,cr=e=>` ${Is.dim.bgHex(xs(e))(` ${e} `)} `,mo=({modifier:e})=>{let t="confirm";return e===t?z(ne):O({message:lr(e)?te("if you are certain, enter ")+ar(t):"",completionWordList:[t]})},wl=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?O({message:te(n)}):z():O({message:lr(r)?t:"",completionWordList:[...e]}),Ut=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>lr(n)&&lr(r)?O({message:e,completionWordList:[]}):z(t??ne),Tl=({modifier:e,inputString:t})=>{let n=oe(f.CONFIG);if(!n.includes(e))return O({message:de({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case X.EDITOR:{let r=[...ds];return t.trim()?r.includes(t.trim())?z(ne):O({message:de({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):O({message:de({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?z(ne):O({message:de({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.USERNAME:return t.trim()?z(ne):O({message:fe("Enter a user name. Saved in ")+Is.bgBlack("~/.epiq-global/config.json")});case X.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?z(ne):O({message:de({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case X.AUTOSYNC:{let r=["on","off"],o=Y().autoSync;if(!r.includes(t.trim())){let i=rs(o);return O({message:de({prefix:`should auto-sync (recommended)${i!==null?", currently: "+i:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return z(ne)}case X.SYNC_DEBOUNCE_MS:{let r=Y().autoSyncIntervalMs,o=Qi(t);if(!t.trim()||o===null||o<Dt){let i=de({prefix:" examples: ",wordList:so,minLengthForHints:0,inputString:t});return O({message:fe(`provide duration above ${Dt}ms. current duration: ${r}ms.`)+i,completionWordList:so})}return z(ne)}default:return O({message:fe("Unknown config option"),completionWordList:n})}},Ml=({modifier:e})=>{let t=oe(f.EDIT);if(!t.includes(e)){let i=de({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return O({message:i||fe("Unknown edit option"),completionWordList:t})}let{breadCrumb:n,selectedNode:r}=v();if(!De([...n,r],"TICKET"))return O({message:fe("Command not available in this context")});switch(e){case rt.TITLE:return z(ne);case rt.DESCRIPTION:let{preferredEditor:i}=Y();return i?z(te("<ENTER> to edit in ")+i):O({message:"No editor selected"});default:return O({message:fe("Unknown edit option"),completionWordList:t})}},Ll={[f.EXPORT]:()=>z(ne+te(", and create export markdown file")),[f.PEEK]:e=>{let t=e.modifier;if(t==="now")return z(ne);let n={message:te("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")};if(t==="prev"||t==="next")return z(ne);let r=nr(t);if(!t||!r)return O(n);let o=De(v().breadCrumb,"BOARD");if(a(o))return O({message:fe("Command is not applicable in this context")});let i=ms(o.value.id);return a(i)?O({message:fe("Unable to peek: board id is not a valid ULID")}):is({date:r,horizonDate:i.value})?z(ne):O({message:fe(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[f.EXIT]:()=>z(ne+te(" and exit the application")),[f.INIT]:()=>z(ne),[f.PALETTE]:()=>z(ne),[f.FILTER]:e=>{if(e.modifier==="clear")return z();let t=i=>oe(f.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return O({message:de({wordList:oe(f.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:oe(f.FILTER)});let n=Object.values(v().tags).map(i=>i.name),r=Object.values(v().contributors).map(i=>i.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?O({message:de({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):z():O({message:de({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[f.NONE]:e=>{let t=oe(f.NONE);return O({message:de({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[f.NEW]:e=>wl({list:oe(f.NEW),hint:de({wordList:oe(f.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[f.HELP]:()=>z(ne),[f.EDIT]:Ml,[f.CONFIG]:Tl,[f.DELETE]:e=>{let t=Ns();return t.validity==="invalid"?t:mo(e)},[f.CLOSE_ISSUE]:e=>mo(e),[f.RE_OPEN_ISSUE]:e=>mo(e),[f.MOVE]:e=>{let t=Ns();return t.validity==="invalid"?t:Ut({hint:de({prefix:"hey hacker! These commands are blocked for you... ",wordList:oe(f.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[f.TAG]:e=>{let n=N.getExistingTags().slice(0,10).map(cr).join("");return Ut({hint:n.length?te("create tag or reuse:")+n+te(""):te("create tag ...")})(e)},[f.UNTAG]:e=>{let t=Zn();if(a(t))return O({message:fe("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(cr).slice(0,10);return n.length?Ut({hint:te(" ... ")+n.join("")})(e):O({message:fe("Issue has no tags"),completionWordList:[]})},[f.ASSIGN]:e=>{let t=N.getExistingAssignees().map(cr).slice(0,10);return Ut({hint:te("assignees... ")+t.join("")})(e)},[f.UNASSIGN]:e=>{let t=er();if(a(t))return O({message:fe("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(cr).slice(0,10);return n.length?Ut({hint:te("remove assignee... ")+n.join("")})(e):O({message:fe("Issue has no assignees"),completionWordList:[]})},[f.SYNC]:()=>z(ne),[f.COFFEE]:e=>{let{modifier:t}=e,n=oe(f.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?O({message:te("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):Ut({hint:de({prefix:"Fuel continued development with ... ",wordList:["$1"," $3 ","$5","$20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},bs=Object.fromEntries(Object.entries(Ll).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]))});var Ss,Rs=y(()=>{"use strict";Ss=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"]});var As,ws,po=y(()=>{"use strict";Ji();ln();gt();Cs();Rs();T();G();As=e=>Object.values(f).includes(e),ws=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:d,validity:l,completionWordList:u}=bs[n].validate(n,r,i),m=o==="command"||o==="modifier"?oe(n):Ss,{mode:g}=v(),x=g===p.COMMAND_LINE?d??"":"",b=[...u,...m];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:x,autoCompletion:t?Xi(e,b):{hint:"",hints:[],remainder:"",overlap:0}}}});var Ts,Pl,kl,Fl,Ms=y(()=>{"use strict";po();ln();Ts=e=>{let t=e.trimStart(),n=kl(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),d=Fl(e),l=As(r)?r:null,u=l!==null,m=r!=="",g=l?oe(l)??[]:[],x=l&&g.includes(o)?o:"",b="word";n.length===0||n.length===1&&!i?b="command":(n.length===1&&i||n.length===2&&!i)&&(b="modifier");let R=i?"":d,I=Pl(t,l,x);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:i,modifier:x,target:b,inputToMatch:R,inputString:I}},Pl=(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},kl=e=>e.trim()?e.trim().split(/\s+/):[],Fl=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as Iv}from"react";var Bt,go,_t,Dl,Ls,Ue,pn,fo,vo,Ps,ks,ur,Fs,W,Ds,Os,Us,J,Bs,ie=y(()=>{"use strict";po();Ms();C();dr();Bt=e=>e===go||e===":",go=" ",_t={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:yt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Dl=new Set,Ls=()=>{for(let e of Dl)e()},Ue=e=>{let n=e(_t),r=Ts(n.value),o=n.cursorPosition===n.value.length;_t={...n,commandMeta:ws(r,o)},Ls()},pn=({message:e,status:t})=>{let n=structuredClone(_t);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,_t=n,Ls(),c(e,null)},fo=e=>{Ue(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},vo=e=>{Ue(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Bt(n[o-1]);)o--;for(;o>0&&!Bt(n[o-1]);)o--}else{for(;o<n.length&&!Bt(n[o]);)o++;for(;o<n.length&&Bt(n[o]);)o++}return{...t,cursorPosition:o}})},Ps=()=>{Ue(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}})},ks=()=>{Ue(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Bt(t[r-1]);)r--;for(;r>0&&!Bt(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},ur=e=>{Ue(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),i=e(r,t.commandMeta.autoCompletion),d=i+o,l=Math.max(0,Math.min(i.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},Fs=()=>{Ue(e=>({...e,commandIsPending:!0}))},W=e=>{Ue(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Ds=({addToHistory:e=!0})=>{Ue(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Os=()=>{Ue(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}})},Us=()=>{Ue(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},J=()=>_t,Bs=()=>{let[e,...t]=_t.value.split(go);return t.join(go).trim()}});var S,mt=y(()=>{"use strict";G();Hi();T();ie();ge();S={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"}});var _s,M,yo=y(()=>{"use strict";T();gt();_s=e=>{let{context:t}=v().contextNode;if(!t)return M.None;switch(e){case f.EXIT:return M.Exit;case f.EXPORT:return M.Export;case f.COFFEE:return M.Coffee;case f.INIT:return M.Init;case f.DELETE:return M.Delete;case f.EDIT:return M.Edit;case f.HELP:return M.ViewHelp;case f.RE_OPEN_ISSUE:return M.ReopenIssue;case f.CLOSE_ISSUE:return M.CloseIssue;case f.TAG:return M.TagTicket;case f.UNTAG:return M.UntagTicket;case f.ASSIGN:return M.AssignUserToTicket;case f.UNASSIGN:return M.UnassignUserFromTicket;case f.NEW:return M.NewItem;case f.FILTER:return M.Filter;case f.MOVE:return M.Move;case f.PEEK:return M.Peek;case f.CONFIG:return M.Config;case f.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",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",Sync:"sync",Export:"export",Coffee:"coffee"}});import{Text as $s}from"ink";import Ws,{useEffect as js,useState as Ol}from"react";var Hs,Ne,$t=y(()=>{"use strict";T();xe();Hs={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ne=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Be(),r=Hs[n]??Hs.default,[o,i]=Ol(0);if(js(()=>{i(0)},[r]),js(()=>{if(!e)return;let l=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return Ws.createElement($s,null,t);let d=r[o]??r[0]??t;return Ws.createElement($s,{color:P.accent,dimColor:o===1},d)}});import{Box as xo,Text as Ul}from"ink";import mr from"react";var pr,ho=y(()=>{"use strict";xe();pr=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),d=Math.max(1,Math.ceil(r)),l=Math.max(1,Math.floor(i/d)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-l),g=o?Math.min(m,Math.max(0,u-l+1)):Math.min(m,Math.floor(u/l)*l),x=g+l,b=e.slice(g,x),R=e.length>l,I=i,k=R?Math.max(1,Math.floor(l/e.length*I)):I,A=Math.max(0,I-k),U=Math.max(1,e.length-l),j=R?Math.floor(g/U*A):0;return mr.createElement(xo,{flexDirection:"row",height:i,width:"100%"},mr.createElement(xo,{flexDirection:"column",flexGrow:1,height:i},b),mr.createElement(xo,{flexDirection:"column",width:1,height:I},Array.from({length:I}).map((lt,Je)=>mr.createElement(Ul,{key:Je,color:R&&Je>=j&&Je<j+k?P.accent:P.secondary},R?"\u2502":" "))))}});import{Text as Bl}from"ink";import _l from"react";var $l,Wl,gr,Eo=y(()=>{"use strict";Qn();vt();ae();$l=e=>e.toLowerCase().trim(),Wl=(e,t=pt)=>{let n=$l(e);return t[n]?t[n]:mn(n)},gr=({id:e,isSelected:t})=>{let n=N.getContributor(e);if(n)return _l.createElement(Bl,{underline:t,color:Wl(n.name)},"@"+n.name)}});import{Text as jl}from"ink";import Hl from"react";var fr,No=y(()=>{"use strict";ae();xe();vt();fr=({id:e,isSelected:t})=>{let n=N.getTag(e);if(n)return Hl.createElement(jl,{underline:t,backgroundColor:Oe(n.name),color:P.primary}," "+n.name+" ")}});import{Box as vr,Text as zl}from"ink";import xt from"react";var zs,Vs=y(()=>{"use strict";xe();Ft();tr();Eo();No();zs=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=qn(Kn(t.title),r),i=ro(t),d=oo(t);return xt.createElement(vr,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?P.accent:P.secondary,justifyContent:"space-between"},xt.createElement(vr,{borderBottom:!0},xt.createElement(vr,{paddingLeft:1,flexDirection:"column"},xt.createElement(zl,{color:P.primary},o))),xt.createElement(vr,{flexDirection:"row",paddingLeft:1},i.map(l=>xt.createElement(fr,{key:l.id,id:l.id})),d.map(l=>xt.createElement(gr,{key:l.id,id:l.id}))))}});import{Box as Wt,Text as yr}from"ink";import we from"react";var Vl,qs,Ks=y(()=>{"use strict";G();ae();xe();vt();$t();Vl=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,qs=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=(t.props.tags??[]).map(I=>N.getTag(I)).filter(I=>!!I),d=(t.props.assignees??[]).map(I=>N.getContributor(I)).filter(I=>!!I),l=1,u=i.length*(1+l),m=d.length*(2+l),g=i.map(I=>we.createElement(Wt,{key:I.id,paddingRight:l},we.createElement(yr,{color:Oe(I.name)},"\u25A0"))),x=d.map(I=>we.createElement(Wt,{key:I.id,paddingRight:l},we.createElement(yr,{color:mn(I.name)},"@"+I.name.at(0)))),b=n?P.accent:o===p.MOVE?P.secondary:P.primary;return we.createElement(Wt,{borderBottom:!0,justifyContent:"space-between"},we.createElement(Wt,null,we.createElement(Wt,{width:4},n?we.createElement(Ne,{isSelected:n}):we.createElement(yr,{color:"gray",dimColor:!0},r+1)),we.createElement(yr,{wrap:"truncate",color:b},Vl(t.title,e-u-m-18))),we.createElement(Wt,null,g,x))}});import ql from"chalk";import{Box as Io,Text as Kl}from"ink";import _e from"react";var Gl,Gs,Ys=y(()=>{"use strict";Z();T();xe();$t();ho();Vs();Ks();Gl=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u}=Be(),m=u[e.id]??[],g=`${e.title} ${ql.hex(P.secondary2).dim("("+m.length+")")}`,x=3,b=o?1:4,R=r-x-(o?2:1),I=_e.createElement(Io,{borderStyle:"round",borderColor:P.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},_e.createElement(Ne,{isSelected:t}),_e.createElement(Kl,{bold:!0,color:t?P.accent:P.primary},g," ",e.readonly?"\u{1F512}":"")),k=(A,U)=>{let j=i&&d===U;return B(A)?o?_e.createElement(qs,{key:A.id,index:U,width:n,ticket:A,isSelected:j,mode:l}):_e.createElement(zs,{key:A.id,width:n,ticket:A,isSelected:j}):null};return _e.createElement(Io,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?P.accent:P.secondary,paddingRight:1,paddingLeft:1,height:r},I,_e.createElement(Io,{padding:o?1:0},m.length>0&&_e.createElement(pr,{selectedIndex:d,height:R,itemHeight:b},m.map(k)),_e.createElement(Ne,{isSelected:i&&d===-1})))},Gs=_e.memo(Gl)});import{createHash as Yl}from"node:crypto";var Xl,Jl,ot,bo=y(()=>{"use strict";Xl="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Jl=e=>{let t=Yl("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 i=BigInt((25-o)*5);r+=Xl[Number(n>>i&31n)]}return r},ot=(e,t)=>Jl(`${e}:virtual:${t}`)});import{Box as xr,Text as Ql}from"ink";import Ke from"react";var Xs,Js=y(()=>{"use strict";Z();ae();kt();T();xe();Eo();$t();No();Xs=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Be(),{title:o}=t,i=t.parentNodeId?N.getNode(t.parentNodeId):void 0,d=i&&B(i)?o===ee.ASSIGNEES?i.props.assignees??[]:o===ee.TAGS?i.props.tags??[]:[]:[];return Ke.createElement(xr,{alignItems:"center",paddingTop:1},Ke.createElement(xr,{minWidth:12},Ke.createElement(Ne,{isSelected:n}),Ke.createElement(Ql,{color:n?P.accent:P.secondary2},o,":")),Ke.createElement(xr,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=r.id===t.id&&u===e;return Ke.createElement(xr,{key:`${o}-${l}`,paddingRight:2,minHeight:1},Ke.createElement(Ne,{isSelected:m}),o===ee.ASSIGNEES?Ke.createElement(gr,{isSelected:m,id:l}):o===ee.TAGS?Ke.createElement(fr,{isSelected:m,id:l}):null)})))}});var ve,gn=y(()=>{"use strict";Z();ve={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:w.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:w.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:w.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:i="horizontal",isVirtual:d=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:w.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[],isVirtual:d}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:w.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:w.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:i=!0,isVirtual:d=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:w.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[],isVirtual:d})}});import{Box as hr,Text as Co}from"ink";import Ge,{useEffect as Zl,useMemo as Qs}from"react";var eu,Zs,So,ea,tu,Ro,ta=y(()=>{"use strict";ae();C();gn();T();xe();Ft();$t();ho();At();eu="\u2029",Zs=(e,t)=>`${e}::inline-line::${t}`,So=new Map,ea=e=>{let t=So.get(e)??[];So.delete(e);for(let n of t)N.deleteNode(n)},tu=(e,t)=>{ea(e);let n=[];t.forEach((r,o)=>{let i=Ce(BigInt(o+1));if(!Jt(i))return;let d=N.createNode(ve.text({id:Zs(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:i.value,props:{value:r},readonly:!0,isVirtual:!0}));Jt(d)&&n.push(d.value.id)}),So.set(e,n)},Ro=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:d,contextNode:l}=Be(),u=Qs(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Qs(()=>u.join("\0"),[u]);Zl(()=>(tu(e,u),()=>{ea(e)}),[e,m]);let g=b=>String(b).replace(/\r?\n/g,""),x=u.map((b,R)=>{let I=l.id===e&&d===R;return Ge.createElement(hr,{key:Zs(e,R)},Ge.createElement(Co,{color:I?P.primary:P.secondary2,dimColor:!I},`${R+1} `.padStart(5,"\xA0")),Ge.createElement(Co,{backgroundColor:I?"gray":void 0},g(b.length?qn(b,i-10):eu)))});return Ge.createElement(hr,{flexDirection:"column",paddingTop:1},Ge.createElement(hr,null,Ge.createElement(Ne,{isSelected:o}),Ge.createElement(Co,{color:o?P.accent:P.secondary2},t)),Ge.createElement(hr,{flexDirection:"row",borderStyle:"round",borderColor:P.secondary,paddingLeft:1,marginLeft:1},Ge.createElement(pr,{scrollByOne:!0,height:r-3,selectedIndex:d,itemHeight:1},x)))}});import{Box as Ao,Text as nu}from"ink";import it,{useMemo as na}from"react";var ru,ou,ra,oa=y(()=>{"use strict";Z();ae();T();xe();bo();$t();Js();ta();ru=e=>ot(e,"description"),ou=e=>ot(e,"history"),ra=({ticket:e,height:t})=>{let{selectedIndex:n,contextNode:r}=Be(),o=process.stdout.columns||120,i=na(()=>ru(e.id),[e.id]),d=na(()=>ou(e.id),[e.id]),l=r.id===e.id,u=r.id===d||r.parentNodeId===d,m=q(e.id);if(u){let A=N.getNode(d),U=A&&Ze(A)?A.props.value??"":"",lt=t-3;return it.createElement(Ao,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},A?it.createElement(Ro,{id:A.id,label:"Event log",text:U,selected:!1,maxWidth:o,height:lt}):null)}let g=m.reduce((A,U)=>Qt(U)||U.id===d?A+1:A,0),x=2,b=3,R=g,I=t-b-R-x,k=(A,U)=>A.id===i?it.createElement(Ro,{key:A.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:U,maxWidth:o,height:I}):Qt(A)?it.createElement(Xs,{key:A.id,parent:A,selected:U,selectedIndex:n}):A.id===d?it.createElement(Ao,{key:A.id,paddingTop:1},it.createElement(Ne,{isSelected:U}),it.createElement(nu,{backgroundColor:P.secondary,color:U?P.accent:P.primary}," History \u203A\u203A ")):null;return it.createElement(Ao,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((A,U)=>k(A,l&&n===U)))}});import{Box as iu}from"ink";import Er from"react";var su,ia,sa=y(()=>{"use strict";Z();Ys();oa();su=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:d,width:l})=>{let u=t.context,m=u===w.TICKET||u===w.FIELD_LIST||u===w.FIELD,g=u===w.BOARD||u===w.SWIMLANE,x=u===w.TICKET?t:r.find(A=>A.context===w.TICKET),b=Math.floor(l/3),R=Math.floor(l/Math.max(e.length,1)),I=Math.min(R,b),k=i==="dense";return Er.createElement(iu,{flexDirection:"row",height:d},g&&e.map((A,U)=>{let j=t.id===A.id,lt=j?n:-1,Je=t.context===w.BOARD&&n===U;return Er.createElement(Gs,{key:A.id,height:d,width:I,swimlane:A,isSelected:Je,isDense:k,isFocused:j,listSelectedIndex:lt,mode:o})}),m&&x&&Er.createElement(ra,{height:d,ticket:x}))},ia=Er.memo(su)});import aa from"node:fs";import au from"node:path";import du from"react";import{render as cu}from"ink";import{Writable as lu}from"node:stream";var fn,uu,mu,pu,gu,da,ca=y(()=>{"use strict";sa();Z();C();T();re();ge();fn=e=>String(e).padStart(2,"0"),uu=e=>{let t=e.getUTCFullYear(),n=fn(e.getUTCMonth()+1),r=fn(e.getUTCDate()),o=fn(e.getUTCHours()),i=fn(e.getUTCMinutes()),d=fn(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${d}`},mu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",pu=async(e,{width:t,height:n})=>{let r="",o=new lu({write(d,l,u){let m=gu(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=cu(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),i.unmount(),r},gu=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),da=async()=>{let{viewMode:e}=Y(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:i}=v(),d=r.find(U=>U.context==="BOARD");if(!d)return s("No board found to export");let l=120,u=40,m=await pu(du.createElement(ia,{height:u,width:l,swimlanes:(i[d.id]??[]).filter(U=>U!==void 0&&Mn(U)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:u});if(!m)return s("Failed to render board export");let g=Dn(process.cwd());if(a(g))return s("Unable to export, epiq root not found");let x=new Date,b=uu(x),R=`board_${mu(d.title)}_${b}.md`,I=Wi(g.value);aa.mkdirSync(I,{recursive:!0});let k=au.join(I,R),A=`# Board - ${d.title}
6
+ `;ln.writeFileSync(e,o,"utf8")}function ir(e,t,n=!1){let o=ks();if(!o)return;let r=$c.format(...t),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${r}
7
+ `;ln.mkdirSync(dr.dirname(o),{recursive:!0}),ln.appendFileSync(o,l,"utf8"),sr++,sr>=jc&&(sr=0,Wc())}var Ls,jc,sr,Ps,ks,ar,le,un=y(()=>{"use strict";b();ce();Ls=1e3,jc=50,sr=0,Ps=()=>process.env.EPIQ_MCP==="true",ks=()=>{let e=process.cwd(),t=zn(e);return a(t)?Ps()?dr.join(process.cwd(),".epiq-mcp.log"):void 0:dr.join(t.value,Je,"log","epiq.log")};ar=()=>Ps()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",le={info(...e){let t=ar();(t==="info"||t==="debug")&&ir("[Info]",e,!1)},debug(...e){ar()==="debug"&&ir("[Debug]",e,!0)},error(...e){let t=ar();if(t==="error"||t==="info"||t==="debug"){let o=e.some(r=>r instanceof Error)?void 0:new Error().stack;ir("[Error]",[...e,o].filter(Boolean),!1)}}};globalThis.logger=le});var ee,Kn=y(()=>{"use strict";xt();ee={stage:({cwd:e,pathspec:t})=>U({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>U({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>U({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>U({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>U({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 U({args:r,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>U({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>U({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>U({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>U({args:["worktree","prune"],cwd:e})}});var Dt,we,Yn=y(()=>{"use strict";yt();b();ce();Dt=e=>{let t=it(e);if(a(t))return i("Unable to resolve epiq project root");let n=dt(t.value);return a(n)?i("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},we="origin"});import{spawn as Hc}from"node:child_process";import Xn from"node:fs";import mn from"node:path";var Ds,Vc,Os,U,Ue,Ft,zc,qc,Jn,cr,Qn,Zn,Fs,Us,lr,eo,Bs,_s,Gc,ur,$s,js,xt=y(()=>{"use strict";b();Kn();Yn();Ds=1e4,Vc={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Os=({args:e,cwd:t,allowFail:n})=>new Promise(o=>{if(!Xn.existsSync(t)){let g=`Git cwd does not exist: ${t}`;if(n){o({stdout:"",stderr:g,exitCode:1});return}o(i(g));return}let r=Hc("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Vc}),s=!1,d="",l="",u=g=>{s||(s=!0,clearTimeout(m),o(g))},m=setTimeout(()=>{r.kill("SIGTERM");let g=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${Ds}ms`].join(`
8
+ `);u(n?{stdout:d,stderr:g,exitCode:124}:i(g))},Ds);r.stdout.setEncoding("utf8"),r.stderr.setEncoding("utf8"),r.stdout.on("data",g=>{d+=g}),r.stderr.on("data",g=>{l+=g}),r.on("error",g=>{if(n){u({stdout:d,stderr:g.message,exitCode:1});return}u(i([`git ${e.join(" ")}`,`cwd=${t}`,g.message].join(`
9
+ `)))}),r.on("close",g=>{let x=g??1;if(n){u({stdout:d,stderr:l,exitCode:x});return}if(x!==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:x}))})}),U=({args:e,cwd:t})=>Os({args:e,cwd:t,allowFail:!1}),Ue=({args:e,cwd:t})=>Os({args:e,cwd:t,allowFail:!0}),Ft=async({cwd:e,message:t})=>{let n=await ee.commit({cwd:e,message:t});if(a(n))return i(`Failed to create commit
11
+ ${n.message}`);let o=await U({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())},zc=async e=>{let t=await U({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",mn.isAbsolute(n)?n:mn.resolve(e,n))},qc=async e=>{let t=await zc(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(Xn.existsSync(mn.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(Xn.existsSync(mn.join(n,s)))return c("Checked for in-progress Git operation",d);return c("Checked for in-progress Git operation",null)},Jn=async e=>{let t=await qc(e);return a(t)?i(t.message):c("Checked for in-progress Git operation",t.value!==null)},cr=async({repoRoot:e})=>{let n=(await Ue({args:["remote","get-url",we],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},Qn=async({repoRoot:e,branch:t})=>{let n=await Ue({args:["ls-remote","--heads",we,t],cwd:e});return n.exitCode!==0?i(n.stderr.trim()||`Unable to inspect remote branch ${we}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},Zn=async({repoRoot:e,branch:t})=>{let n=await Ue({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}`)},Fs=e=>{try{return Xn.realpathSync.native(e)}catch{return mn.resolve(e)}},Us=async({repoRoot:e,worktreeRoot:t})=>{let n=await U({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let o=Fs(t),r=n.value.stdout.split(`
13
+ `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Fs).includes(o);return c("Checked worktree registration",r)},lr=async e=>{let t=await Ue({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},eo=async e=>{let t=await U({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved current branch",t.value.stdout.trim())},Bs=async e=>{let t=await U({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},_s=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Gc=async e=>(await Ue({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1),ur=async({cwd:e,branch:t})=>{let n=await Qn({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 Gc(e);if(a(o))return i(o.message);let r=await ee.fetch({cwd:e,remote:we,branch:t});if(a(r))return i(`Failed to fetch ${t}
14
+ ${r.message}`);let s=await ee.pullRebase({cwd:e,remote:we,branch:t});return a(s)?i(`Failed during pull --rebase
15
+ ${s.message}`):c("Pulled with rebase",!0)},$s=async e=>{let t=await Ue({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")},js=async e=>{let t=await eo(e);return a(t)?i(t.message):c("Checked detached HEAD state",t.value==="HEAD")}});import mr from"node:fs";import Kc from"node:os";import Be from"node:path";var Hs,pr,Vs,to,Qe,Yc,Ws,pn,no,zs,qs,Gs,at,bg,vt=y(()=>{"use strict";yt();b();ce();Ms();un();xt();Hs="4b825dc642cb6eb9a060e54bf8d69288fbee4904",pr=e=>Be.join(Je,Wn,e),Vs=()=>Be.join(Kc.homedir(),Te),to=()=>Be.join(Vs(),"worktrees"),Qe=({repoRoot:e})=>{let t=Ts(e);return a(t)?i(t.message):c("Resolved state branch root",Be.join(to(),t.value))},Yc=e=>Be.join(e,Je),Ws=e=>Be.join(Yc(e),Wn),pn=e=>{try{return mr.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return i(t instanceof Error?t.message:String(t))}},no=()=>{let e=pn(Vs());if(a(e))return i(`Ensure epiq home failed.
16
+ `+e.message);let t=pn(to());return a(t)?i(`Ensure worktrees dir failed.
17
+ `+t.message):c("Ensured epiq storage",!0)},zs=e=>{mr.existsSync(e)&&(le.debug("[sync] remove path",e),mr.rmSync(e,{recursive:!0,force:!0}))},qs=(e,t)=>{for(let n of[Ws(e),Ws(t)]){let o=pn(n);if(a(o))return i(o.message)}return c("Ensured state branch",void 0)},Gs=async e=>{let t=await U({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!==Je);if(o.length===0)return c("State branch is storage-only",!1);let r=await U({args:["rm","-r","--ignore-unmatch","--",...o],cwd:e});if(a(r))return i(`Failed to clean storage branch
20
+ ${r.message}`);let s=await Ft({cwd:e,message:"[epiq:repair-storage-branch]"});return a(s)?i(s.message):c("Cleaned storage branch",!0)},at=rr(async(e=process.cwd())=>{let t=await U({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=>Be.resolve(e)),bg=rr(async e=>{let t=await U({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return i(t.message);let n=t.value.stdout.trim(),o=Be.isAbsolute(n)?n:Be.join(e,n);return c("Resolved git dir",o)},e=>Be.resolve(e))});import Ot from"node:fs";import gn from"node:path";var Ys,Ks,Xc,gr,Jc,Qc,Zc,fn,el,tl,oo,Xs,vn,Js,ro=y(()=>{"use strict";b();un();Kn();Yn();vt();xt();Ys=async e=>{if((await Ue({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);le.info("Creating initial commit");let n=await ee.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return a(n)?i(n.message):c("Created initial commit",!0)},Ks=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Xc=async e=>{let t=await eo(e);if(a(t))return i(t.message);let n=await Bs(e);return a(n)?i(n.message):c("Built sync commit message",`[sync|branch:${Ks(t.value)}:sha:${Ks(n.value)}]`)},gr=async({repoRoot:e,stateBranchName:t})=>{le.info(`Creating ${t}`);let n=await U({args:["commit-tree",Hs,"-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 U({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)},Jc=async({repoRoot:e,stateBranchName:t})=>{let n=await cr({repoRoot:e});if(a(n))return i(`Ensure local state branch failed
23
+ `+n.message);let o=n.value,r=o?await Qn({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 ee.fetch({cwd:e,remote:we,branch:t});if(a(l))return i(`Failed to fetch ${t} from remote
25
+ ${l.message}`)}let d=await Zn({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 U({args:["branch","--track",t,`${we}/${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 gr({repoRoot:e,stateBranchName:t})},Qc=async({repoRoot:e,branch:t})=>{let n=await U({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)},Zc=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=pn(gn.dirname(t));if(a(o))return i(`Failed to create state branch worktree
29
+ `+o.message);Ot.existsSync(t)&&!Ot.existsSync(gn.join(t,".git"))&&(le.info("Removing broken state branch worktree path"),zs(t)),le.info("Creating state branch worktree");let r=await ee.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)},fn=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=await Qc({repoRoot:e,branch:n});if(a(o))return i(o.message);let r=gn.resolve(t),s=o.value?gn.resolve(o.value):null;if(s&&s===r&&Ot.existsSync(s))return c("State branch already checked out in expected worktree",!1);if(s&&s!==r){le.info("Moving state branch worktree to expected location");let u=await ee.worktreeRemove({cwd:e,worktreeRoot:s});if(a(u))return i(`Failed to remove existing state branch worktree
31
+ ${u.message}`)}if(s&&!Ot.existsSync(s)){le.info("Pruning stale state branch worktree");let u=await ee.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
32
+ ${u.message}`)}let d=await Us({repoRoot:e,worktreeRoot:t});if(a(d))return i(d.message);let l=Ot.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 ee.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
33
+ ${u.message}`)}return Zc({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},el=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await eo(e);if(a(n))return i(n.message);if(n.value===t)return c("State branch already checked out",!1);(await Ue({cwd:e,args:["rebase","--abort"]})).exitCode===0&&le.info("Aborted stale state branch rebase");let r=await ee.checkout({cwd:e,branch:t});return a(r)?i(`Failed to checkout ${t}
34
+ ${r.message}`):c("Checked out state branch",!0)},tl=async({repoRoot:e,stateBranchRoot:t})=>{let n=await lr(t);if(a(n))return i(n.message);if(n.value)return c("State branch upstream already configured",!1);let o=await cr({repoRoot:t});if(a(o))return i(o.message);if(!o.value)return c("No remote available for state branch upstream",!1);let r=Dt(e);if(a(r))return r;let s=r.value,d=await Qn({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 ee.fetch({cwd:t,remote:we,branch:s});if(a(l))return i(`Failed to fetch ${s}
35
+ ${l.message}`);let u=await ee.setUpstream({cwd:t,branch:s,upstream:`${we}/${s}`});return a(u)?i(`Failed to set state branch upstream
36
+ ${u.message}`):c("Configured state branch upstream",!0)},oo=async({stateBranchRoot:e,eventFileName:t})=>{let n=pr(t),o=gn.join(e,n);if(!Ot.existsSync(o))return c("No event file to stage",void 0);let r=await ee.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)},Xs=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Xc(e);return a(n)?i(`Create state branch sync commit failed
38
+ `+n.message):Ft({cwd:t,message:n.value})},vn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await lr(t);if(a(n))return i(n.message);let o=Dt(e);if(a(o))return o;let r=o.value,s=n.value?await ee.push({cwd:t}):await ee.push({cwd:t,remote:we,branch:r,setUpstream:!0});return a(s)?i(`Failed during state branch push
39
+ ${s.message}`):c("Pushed state branch",!0)},Js=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let o=!1,r=Dt(e);if(a(r))return r;let s=r.value,d=[no(),await Jc({repoRoot:e,stateBranchName:s}),await fn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await el({stateBranchRoot:t,stateBranchName:s}),await Gs(t),n?await tl({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 nl}from"ws";var ol,Qs,Zs=y(()=>{"use strict";ol=new Set,Qs=e=>{let t=JSON.stringify(e);for(let n of ol)n.readyState===nl.OPEN&&n.send(t)}});function fr(e){return e.context===T.WORKSPACE}function D(e){return e.context===T.TICKET}function ei(e){return e.context===T.TEXT}function _e(e){return e.context===T.FIELD}function yn(e){return e.context===T.FIELD_LIST}var T,xn,vr,hn,te=y(()=>{"use strict";T={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};xn=e=>e.context===T.SWIMLANE,vr=e=>e.context===T.BOARD,hn=e=>e.context===T.COMMENT});var f,J=y(()=>{"use strict";f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var ti=y(()=>{"use strict";ht()});function so(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}var io,ao,Ut=y(()=>{"use strict";io=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",ao=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var ni,oi,ri=y(()=>{"use strict";ni=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},oi=(e,t)=>t?e.get(t)??[]:[]});var si,rl,ii,ai=y(()=>{"use strict";Ut();ri();si=new WeakMap,rl=e=>{let t=si.get(e);return t||(t=ni(e),si.set(e,t)),t},ii=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let o=t.toLowerCase();return oi(rl(e),o).filter(s=>so(o,s)>=n)}});var sl,di,il,ci=y(()=>{"use strict";Ut();ai();sl={hint:"",hints:[],overlap:0,remainder:""},di=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},o)=>{if(n||e==="")return sl;let r=ii({wordList:o,inputToMatch:e,overlapThreshold:1});return il(t,r)},il=(e,t)=>{let n=t[0]??"",o=so(e.toLowerCase(),n.toLowerCase()),[r,s]=n.split(":"),d=o<(r??"").length,l=!!s,g=(l&&d?r:n)+(l&&d?":":" "),x=g.slice(o);return{hint:g,hints:t,overlap:o,remainder:x}}});import{useSyncExternalStore as Jg}from"react";var co,al,dl,Q,$e,he=y(()=>{"use strict";co={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},al=new Set,dl=()=>{for(let e of al)e()},Q=()=>co,$e=e=>(co={...co,...e},dl(),co)});function li(e){return!e||!ll.test(e)?i(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Me(e,t=Bt){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 Ie(e,t){if(!e&&!t)return Me(je/2n,Bt);let n=e?li(e):c("Resolved lower bound",0n);if(a(n))return n;let o=t?li(t):c("Resolved upper bound",je);if(a(o))return o;let r=n.value,s=o.value;if(s<=r)return Me(je/2n,Bt);let d=(r+s)/2n;return d===r||d===s?i("No rank space available between neighbors"):Me(d,Bt)}function ui(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let o=0;o<e;o++){let r=je*BigInt(o+1)/(t+1n),s=Me(r,Bt);if(a(s))return s;n.push(s.value)}return c("Resolved evenly spaced ranks",n)}var Bt,cl,je,ll,_t=y(()=>{"use strict";b();Bt=24n,cl=Bt*4n,je=(1n<<cl)-1n,ll=/^[0-9a-f]+$/});import{ulid as ul}from"ulid";var yr,mi=y(()=>{"use strict";b();We();_t();yr=(e,t)=>{let n=K(e),o=ui(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:ul(),action:"rebalance.children",payload:{parent:e,ranks:r},...t})}});var Nt,ml,It,I,ie=y(()=>{"use strict";te();b();w();We();Nt=(e,t)=>{let{nodes:n}=p(),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}`)},ml=(e,t)=>{let{nodes:n}=p(),o=n[e];for(;o?.parentNodeId;){if(o.parentNodeId===t)return!0;o=n[o.parentNodeId]}return!1},It=(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"),I={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=me(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){me(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(!D(t))return i("Can only comment on issues");let n=me(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(!D(o))return i("Can only edit issue comments");let r={...n,md:t,deleted:!1},s=me(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=me(r=>({...r,comments:{...r.comments??{},[e]:n}}));return a(o)?i("Unable to delete comment"):c("Deleted comment",n)},getComment(e){return p().comments?.[e]},getCommentsByIssue(e){return Object.values(p().comments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=p(),o=n[e];if(!o)return i("Edit target node not found");let r=It(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=It(n,"rename");if(o)return o;let r={...n,title:t};return this.updateNode(r),c("Renamed node",r)},getExistingTags(){let{tags:e}=p();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=p();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return K(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:o}=p(),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=It(r,"move");if(d)return d;if(ml(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}=p(),r=this.getNode(e);if(!r)return i("Node not found");if(o===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 g of K(m.id))d(g.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?(N({nodes:l}),c("Successfully tomb stoned",r)):i("Unable to delete undefined")},createContributor(e){let t=me(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=It(o,"edit");if(r)return r;if(!D(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=It(o,"edit");if(r)return r;if(!D(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=It(o,"edit");if(r)return r;if(!D(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=It(o,"edit");if(r)return r;if(!D(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=me(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?i("Could not create tag"):c("Tag created",e)},createNode(e){let t=me(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=me(r=>({...r,nodes:{...r.nodes,[e]:n}}));return a(o)?i(o.message):c("Locked node",n)},updateNode(e){let t=me(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?t:c("Updated node",e)},getContributor(e){return p().contributors[e]},getTag(e){return p().tags[e]},getNode(e){return p().nodes[e]},getSiblings(e){return K(e)}}});var ne,$t=y(()=>{"use strict";ne={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments"}});var pe,jt=y(()=>{"use strict";te();pe={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:T.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,o,r=!1)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:T.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:T.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:T.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:T.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:{},context:T.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:T.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:T.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:d})}});var ge,C,Ne=y(()=>{"use strict";ge={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"},C={accent:ge.cyan,accent2:ge.magenta,primary:ge.white,secondary:ge.grayDark,secondary2:ge.grayLight,gray:ge.gray,green:ge.green,yellow:ge.yellow,red:ge.red}});var h,Wt,lo=y(()=>{"use strict";Ne();h={red:ge.red,yellow:ge.yellow,green:ge.green,blue:ge.blue,magenta:ge.magenta,cyan:ge.cyan},Wt={urgent:h.red,critical:h.red,important:h.red,blocker:h.red,asap:h.red,immediate:h.red,fail:h.red,failure:h.red,broken:h.red,bug:h.red,error:h.red,incident:h.red,outage:h.red,production:h.red,crash:h.red,security:h.red,warning:h.yellow,warn:h.yellow,risky:h.yellow,risk:h.yellow,attention:h.yellow,pending:h.yellow,review:h.yellow,"needs-review":h.yellow,qa:h.yellow,testing:h.yellow,test:h.yellow,validate:h.yellow,verification:h.yellow,staging:h.yellow,check:h.yellow,"follow-up":h.yellow,followup:h.yellow,waiting:h.yellow,blocked:h.yellow,hold:h.yellow,done:h.green,complete:h.green,completed:h.green,success:h.green,ok:h.green,stable:h.green,resolved:h.green,fixed:h.green,closed:h.green,merged:h.green,released:h.green,deployed:h.green,approved:h.green,verified:h.green,working:h.green,healthy:h.green,pass:h.green,passing:h.green,info:h.blue,information:h.blue,note:h.blue,docs:h.blue,documentation:h.blue,doc:h.blue,guide:h.blue,help:h.blue,explanation:h.blue,detail:h.blue,details:h.blue,context:h.blue,design:h.blue,discussion:h.blue,proposal:h.blue,idea:h.blue,feature:h.magenta,enhancement:h.magenta,improvement:h.magenta,refactor:h.magenta,refactoring:h.magenta,cleanup:h.magenta,optimize:h.magenta,optimization:h.magenta,perf:h.magenta,performance:h.magenta,upgrade:h.magenta,migration:h.magenta,modernize:h.magenta,debt:h.magenta,todo:h.cyan,next:h.cyan,planned:h.cyan,plan:h.cyan,future:h.cyan,backlog:h.cyan,investigate:h.cyan,explore:h.cyan,prototype:h.cyan}});import pi from"chalk";var hr,gi,xr,fi,pl,gl,fl,vl,yl,In,Ee,xl,uo,hl,Il,mo,ct=y(()=>{"use strict";lo();hr={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},gi=(e,t,n)=>Math.max(t,Math.min(n,e)),xr=(e,t,n)=>e+(t-e)*n,fi=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},pl=e=>e.toLowerCase().trim(),gl=(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,g=0;d>=0&&d<1?(u=s,m=l):d>=1&&d<2?(u=l,m=s):d>=2&&d<3?(m=s,g=l):d>=3&&d<4?(m=l,g=s):d>=4&&d<5?(u=l,g=s):(u=s,g=l);let x=r-s/2;return[Math.round((u+x)*255),Math.round((m+x)*255),Math.round((g+x)*255)]},fl=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,vl=(e,t,n)=>{let o=gi(n,0,1);return[Math.round(xr(e[0],t[0],o)),Math.round(xr(e[1],t[1],o)),Math.round(xr(e[2],t[2],o))]},yl=(e,t,n)=>vl(e,t,n),In=e=>{let n=fi(e)%360,o=gl(n,hr.stringColor.saturation,hr.stringColor.lightness);return fl(o)},Ee=(e,t=Wt)=>{let n=pl(e);return n&&t[n]?t[n]:In(n)},xl=e=>{let t=hr.gradient.stops,n=gi(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 yl(t[s],t[s+1],d)},uo=e=>fi(e.toLowerCase().trim())/4294967295,hl=e=>{let t=uo(e);return xl(t)},Il=e=>{let[t,n,o]=hl(e);return{normal:r=>pi.bgRgb(t,n,o).black(r),cursor:r=>pi.bgRgb(t,n,o).white.bold(r)}},mo=e=>Il(e).normal(` ${e} `)});import{decodeTime as vi}from"ulid";var po,yi,Ir,Nn=y(()=>{"use strict";b();po=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"},yi=e=>{try{return c("Decoded date",new Date(vi(e)))}catch(t){return i("Decoding failed + "+t.message)}},Ir=e=>{if(!e?.id)return null;try{return vi(e.id)}catch{return null}}});import Et from"chalk";import xi from"string-width";import{decodeTime as Nl}from"ulid";var El,bl,Cl,Sl,Rl,Al,Tl,wl,Ml,hi,Ii=y(()=>{"use strict";ie();w();ct();Nn();El=(e,t)=>e+" ".repeat(Math.max(0,t-xi(e))),bl=(e,t)=>" ".repeat(Math.max(0,t-xi(e)))+e,Cl=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),Sl=(e,t)=>t?e<t?"up":e>t?"down":null:null,Rl=(e,t)=>{let n=I.getNode(e.payload.parent),o=n?Et.dim.bgBlack(` ${n.title} `):"unknown",r=t.at(-1);if(r&&"parent"in r&&"rank"in r&&r.parent===e.payload.parent){let s=Sl(e.payload.rank,r.rank);if(s)return`Moved ${s} in ${o}`}return`Moved issue to ${o}`},Al=e=>{switch(e.action){case"add.issue.tag":{let t=p().tags[e.payload.tag];return t?Et.bgHex(Ee(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=p().tags[e.payload.tag];return t?Et.bgHex(Ee(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=p().contributors[e.payload.assignee];return t?Et.hex(Ee(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=p().contributors[e.payload.assignee];return t?Et.hex(Ee(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;default:return""}},Tl=e=>{let t=po(Nl(e));return Et.gray(bl(t,8))},wl=12,Ml=e=>El(`${e}`,wl),hi=(e,t)=>{let n=Tl(e.id),o=Ml(e.userName),r=Et.dim("\u203A"),s=e.action==="move.node"?Rl(e,t):[Cl(e.action),Al(e)].filter(Boolean).join(" ");return`${o} ${n} ${r} ${s}`}});import{createHash as Ll}from"node:crypto";var Pl,kl,be,En=y(()=>{"use strict";Pl="0123456789ABCDEFGHJKMNPQRSTVWXYZ",kl=e=>{let t=Ll("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+=Pl[Number(n>>s&31n)]}return o},be=(e,t)=>kl(`${e}:virtual:${t}`)});var Dl,Fl,Ol,Ul,Bl,Nr,Ni,Ei,_l,bi=y(()=>{"use strict";Ii();te();b();$t();ie();jt();w();_t();En();Dl=e=>be(e,"comments"),Fl=e=>be(e,"description"),Ol=e=>be(e,"assignees"),Ul=e=>be(e,"tags"),Bl=e=>be(e,"history"),Nr=({id:e,name:t,parentNodeId:n,rank:o,value:r,readonly:s=!1,childRenderAxis:d="horizontal"})=>{let l=I.getNode(e);if(!l){let g=I.createNode({...pe.field({id:e,name:t,parentNodeId:n,rank:o,props:{value:r},isVirtual:!0}),readonly:s,childRenderAxis:d});return a(g)?g:c("Virtual field created",void 0)}if(!_e(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=I.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)},Ni=({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!1,childRenderAxis:s="horizontal"})=>{let d=I.getNode(e);if(!d){let m=I.createNode({...pe.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(!yn(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=I.updateNode({...d,title:t,parentNodeId:n,rank:o,readonly:r,childRenderAxis:s});return a(u)?u:c("Virtual field list updated",void 0)},Ei=e=>{let t=Me(je/4n),n=Me(je/2n),o=Me(je*3n/4n),r=Me(je*7n/8n),s=Me(je*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;let d=Nr({id:Fl(e.id),name:ne.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(d))return d;let l=Ni({id:Ol(e.id),name:ne.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(l))return l;let u=Ni({id:Ul(e.id),name:ne.TAGS,parentNodeId:e.id,rank:o.value,readonly:!0});if(a(u))return u;let m=Nr({id:Dl(e.id),name:ne.COMMENTS,parentNodeId:e.id,rank:r.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(m))return m;let g=Nr({id:Bl(e.id),name:ne.HISTORY,parentNodeId:e.id,rank:s.value,value:_l(e),readonly:!0,childRenderAxis:"vertical"});return a(g)?g:c("Ticket virtual nodes materialized",void 0)},_l=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=>hi(o,n.get(o.action)??[])).join(`
40
+ `)}});var $l,ye,go,bn=y(()=>{"use strict";$l=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ye,go]=$l});function Cn(e,t=!1){let n=Kl[e.action](e);if(a(n))return n;let o=Gl(e,t);return o||n}var P,Ci,jl,Wl,Hl,Vl,zl,ql,Gl,Kl,bt,Ht=y(()=>{"use strict";te();b();$t();ie();jt();w();bi();bn();P=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Ci=e=>{let t=I.getNode(e);if(!t||!D(t)||t.isDeleted)return null;let n=Ei(t);return a(n)?n:null},jl=e=>{for(let t of e){let n=Ci(t);if(n)return n;let o=p().nodes[t]?.parentNodeId;if(!o)continue;let r=Ci(o);if(r)return r}return null},Wl=(e,t)=>{let n=I.getNode(e);n&&I.updateNode({...n,log:[...n.log??[],t]})},Hl=e=>{let t=[e],n=p().nodes[e]?.parentNodeId;return n&&t.push(n),t},Vl=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":return[e.payload.issue];case"delete.node":case"edit.description":return Hl(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[]}},zl=e=>{me(t=>({...t,eventLog:[...t.eventLog,e]}))},ql=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?P("Invalid user ID format",e):c("Valid user",null)},Gl=(e,t)=>{let n=ql(e);if(a(n))return n;let o=[...new Set(Vl(e))];t||(o.forEach(s=>Wl(s,e)),zl(e));let r=jl(o);return r||null},Kl={"init.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=pe.workspace(t,n,o),s=Sn(r);if(a(s))return P(s.message,e);let d=I.createNode(r);return a(d)?P(d.message??"Failed to initialize workspace",e):fr(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=I.createNode(pe.workspace(t,n,o));return a(r)?P(r.message??"Failed to add workspace",e):fr(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=I.createNode(pe.board(t,n,o,r));return a(s)?P(s.message??"Unable to create board",e):vr(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=I.createNode(pe.swimlane(t,n,o,r));return a(s)?P(s.message??"Unable to create swimlane",e):xn(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=I.createNode(pe.ticket(t,n,o,r));return a(s)?P(s.message??"Unable to create issue",e):D(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=I.createNode(pe.field({id:t,name:n,parentNodeId:o,rank:s,props:{value:r},childRenderAxis:n.includes(ne.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?P(d.message??`Unable to create field: ${n}`,e):_e(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(!I.getNode(t))return P(`Unable to locate node with id ${t}`,e);let r=I.renameNode(t,n);return a(r)?P(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=I.tombstoneNode(t);return a(n)?P(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=I.createTag({id:t,name:n});return a(o)?P(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=I.createContributor({id:t,name:n});return a(o)?P(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=I.tag(t,n);return a(o)?P(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=I.untag(t,n);return a(o)?P(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=I.assign(t,n);return a(o)?P(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=I.unassign(t,n);return a(o)?P(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=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(r)?P(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=I.editValue(t,n);return a(o)?P(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=I.getNode(t);if(!r)return P("Unable to locate issue",e);if(!D(r))return P("Can only close issues",e);let s=I.getNode(ye);if(!s)return P("Unable to locate target swimlane",e);if(n!==s.id)return P("Close target must be closed swimlane",e);let d=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(d)?P(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=I.getNode(t);if(!r)return P("Unable to locate issue",e);if(!D(r))return P("Can only reopen issues",e);let s=I.getNode(ye);if(!s)return P("Unable to locate closed swimlane",e);if(n===s.id)return P("Cannot reopen issue into closed swimlane",e);if(!I.getNode(n))return P("Reopen parent no longer exists",e);let l=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(l)?P(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=I.lockNode(t);return a(n)?P(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=I.getNode(o);if(!s)return P(`Unable to locate node ${o}`,e);if(s.parentNodeId!==t)return P(`Node ${o} is not child of ${t}`,e);let d=I.updateNode({...s,rank:r});if(a(d))return P(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=I.createComment({id:t,issue:n,authorId:o,authorName:I.getContributor(o)?.name??"Unknown",md:r,deleted:!1});return a(s)?P(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=I.getComment(t);if(!r)return P("Unable to locate comment",e);if(r.issue!==n)return P("Comment does not belong to issue",e);let s=I.editComment(t,o);return a(s)?P(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=I.getComment(t);if(!o)return P("Unable to locate comment",e);if(o.issue!==n)return P("Comment does not belong to issue",e);let r=I.deleteComment(t);return a(r)?P(r.message??"Unable to delete comment",e):c("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=I.linkUserId({contributorId:t,userId:e.userId});return a(n)?P(n.message??"Unable to link contributor",e):c("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};bt=e=>e.map(t=>Cn(t))});import fo from"node:fs";import br from"node:path";import{decodeTime as Yl}from"ulid";import{z as Er}from"zod";function Sr(e){let t=dn(e);if(!fo.existsSync(t))return c("No events found",[]);let n=fo.readdirSync(t).filter(r=>r.endsWith(".jsonl")).map(r=>br.join(t,r)),o=[];for(let r of n){let s=nu(r);if(a(s))return i(s.message);o.push(...s.value)}return c("All events loaded",ou(o))}function Ct(e){let t=Sr(e);return a(t)?i(t.message):Cr(t.value)}function Si(e,t){let n=Sr(e);if(a(n))return i(n.message);let{appliedEvents:o,unappliedEvents:r}=ru(n.value,t),s=Cr(o);if(a(s))return i(s.message);let d=Cr(r);return a(d)?i(d.message):c("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function Ri(e=process.cwd()){let t=Sr(e);return a(t)?i(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Xl,Jl,Ql,Zl,eu,tu,Cr,nu,ou,ru,Rn=y(()=>{"use strict";b();ce();Fe();Xl=Er.object({userId:Er.string().min(1).default("unknown"),userName:Er.string().min(1).default("unknown")}),Jl=e=>{let[t,n]=br.basename(e,".jsonl").split("."),o=Xl.safeParse({userId:t,userName:n});return o.success?c("Parsed event file actor",o.data):i(`Invalid event file name ${br.basename(e)}: ${o.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Ql=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])},Zl=(e,t)=>t in e,eu=({id:e,action:t,payload:n,userId:o,userName:r})=>({id:e,action:t,payload:n,userId:o,userName:r}),tu=e=>{let{userId:t,userName:n,...o}=e,r=Ql(o);if(a(r))return i(r.message);let s=r.value,d=e.id?.[0];return d?Zl(o,s)?c("Decoded persisted event",eu({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")},Cr=e=>{let t=[];for(let n of e){let o=tu(n);if(a(o))return i(`Failed to decode event ${n.id?.[0]??"<unknown>"}: ${o.message}`);t.push(o.value)}return c("Decoded reconstructed events",t)},nu=e=>{if(!fo.existsSync(e))return c("Event file missing",[]);let t=Jl(e);if(a(t))return i(t.message);let n=fo.readFileSync(e,"utf8"),o=[];for(let r of n.split(`
41
+ `)){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=Rr(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)};ou=e=>{let t=new Map,n=new Map;for(let m of e){let g=m.id[0],x=m.id[1]??null;t.set(g,m);let E=n.get(x)??[];E.push(m),n.set(x,E)}for(let m of n.values())m.sort((g,x)=>g.id[0].localeCompare(x.id[0]));let o=[],r=new Set,s=m=>{let g=m.id[0];if(r.has(g))return;o.push(m),r.add(g);let x=n.get(g)??[];for(let E of x)s(E)},d=n.get(null)??[];for(let m of d)s(m);let l=e.filter(m=>{let g=m.id[0],x=m.id[1]??null;return!r.has(g)&&x!==null&&!t.has(x)}).sort((m,g)=>m.id[0].localeCompare(g.id[0]));for(let m of l)s(m);let u=e.filter(m=>!r.has(m.id[0])).sort((m,g)=>m.id[0].localeCompare(g.id[0]));for(let m of u)s(m);return o},ru=(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=Yl(d)<t}catch{u=!1}!u||l&&n.has(l)?(n.add(d),r.push(s)):o.push(s)}return{appliedEvents:o,unappliedEvents:r}}});var Ai,Ti=y(()=>{"use strict";Ai=e=>({action:e.action,payload:e.payload})});import su from"node:fs";import iu from"node:path";import{decodeTime as au,monotonicFactory as du}from"ulid";import{z as An}from"zod";function vo({event:e,rootDir:t}){try{let n=As(t);if(a(n))return n;let o=pu(t,{userId:e.userId,userName:e.userName});if(a(o))return o;let r=Ri(t);if(a(r))return i(r.message);let s=r.value?wi(Math.max(Date.now(),au(r.value)+1)):wi(),d=gu(Ai(e),[s,r.value]);return a(d)?i(d.message):(su.appendFileSync(o.value,`${JSON.stringify(d.value)}
42
+ `,"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 Li,wi,cu,lu,Rr,Mi,uu,mu,X,St,pu,gu,Fe=y(()=>{"use strict";b();he();ce();Rn();Ti();Li=1,wi=du(),cu=An.tuple([An.string().min(1),An.string().min(1).nullable()]),lu=An.looseObject({v:An.literal(Li),id:cu}),Rr=e=>{let t=lu.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(", ")}`)},Mi=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",uu=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),mu=e=>e.trim().length>0&&e.length<=80,X=()=>{let{userName:e,userId:t}=Q();return e?t?uu(t)?mu(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")},St=({userId:e,userName:t})=>`${Mi(e)}.${Mi(t)}.jsonl`,pu=(e,{userId:t,userName:n})=>{let o=St({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(o))return i(`Invalid event log file name: ${o}`);let s=iu.join(dn(e),o);return c("Successfully resolved event log path",s)},gu=(e,t)=>{let n={[e.action]:e.payload,v:Li,id:t};return Rr(n)}});import{ulid as fu}from"ulid";function Pi(e,t){let n=Cn(e);if(n.status!==st.Success)return n;let o=vo({event:e,rootDir:t});return a(o)?o:n}function j(e,t){if(e.length===0||!e[0])return i("No events provided");let n=vu(e[0],t);if(a(n))return n;let o=e.map(s=>Pi(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 vu,Rt=y(()=>{"use strict";b();ie();Ht();Fe();vu=(e,t)=>{if(e.action==="create.contributor")return c("Contributor already being created",void 0);if(I.getContributor(e.userId))return c("Contributor exists",void 0);let n={id:fu(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},o=Pi(n,t);return a(o)?i(o.message):c("Contributor created",void 0)}});var ki,yo,K,Di,Fi,Vt,zt,We=y(()=>{"use strict";mi();Rt();b();w();_t();ki=e=>yo(K(e),{at:"end"}),yo=(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(Ie(void 0,void 0));switch(t.at){case"start":{let o=e[0];return o?n(Ie(void 0,o.rank)):i("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(Ie(o.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let o=Di(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(Ie(r?.rank,s.rank)):i("Sibling not found")}case"after":{let o=Di(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(Ie(r.rank,s?.rank)):i("Sibling not found")}}},K=e=>Object.values(p().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Di=(e,t)=>e.findIndex(n=>n.id===t),Fi=(e,t,n={at:"end"})=>yo(K(t).filter(o=>o.id!==e),n),Vt=(e,t,n,o,r)=>{let s=Fi(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return c("Resolved rank",s.value.rank);let d=yr(e,o);if(a(d))return d;let l=j([d.value],r);if(a(l))return l;let u=Fi(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=ki(e);if(a(o))return o;if(!o.value.needsRebalance)return c("Resolved rank",o.value.rank);let r=yr(e,t);if(a(r))return r;let s=j([r.value],n);if(a(s))return s;let d=ki(e);return a(d)?d:d.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",d.value.rank)}});var L,Oi,Ui,Le=y(()=>{"use strict";w();L={exit(){process.exit(0)},enterChildNode(){let e=p(),t=e.contextNode,n=Math.max(0,e.selectedIndex),o=q(t.id),r=o[n];r&&(t.context==="FIELD"&&o.length===0||r.context==="COMMENT"||r.context==="TEXT"||L.navigate({contextNode:r,selectedIndex:q(r.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=p();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=q(n.id),r=o.findIndex(({id:d})=>d===e.id),s=o.length===0?-1:r>=0?r:0;L.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Oi(1),navigateToPreviousItem:()=>Oi(-1),navigateToNextContainer:()=>Ui(1),navigateToPreviousContainer:()=>Ui(-1),navigate:({contextNode:e,selectedIndex:t})=>{N({contextNodeId:e.id,selectedIndex:t})}},Oi=e=>{let{selectedIndex:t,contextNode:n}=p(),o=q(n.id).length;if(o===0)return;let s=(Math.max(0,t)+e+o)%o;L.navigate({selectedIndex:s,contextNode:n})},Ui=e=>{let{contextNode:t,nodes:n,selectedIndex:o}=p();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let r=n[t.parentNodeId];if(!r)return;let s=q(r.id),d=s.findIndex(E=>E.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),g=Math.min(Math.max(0,o),m),x=u.length?g:-1;L.navigate({contextNode:l,selectedIndex:x})}});var _i,$i,yu,xo,ji,Bi,xu,Wi,Hi=y(()=>{"use strict";te();b();We();w();Le();_i=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),$i=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=p();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},yu=e=>{let t=p().nodes[e];return!!t&&!t.isDeleted&&_e(t)&&t.childRenderAxis==="vertical"},xo=(e,t)=>{let{nodes:n}=p(),o=n[e];if(!o||o.isDeleted)return!1;let r=K(o.id);return L.navigate({contextNode:o,selectedIndex:_i(t,r.length)}),!0},ji=e=>{let{nodes:t}=p(),n=t[e];if(!n||n.isDeleted)return!1;let o=n.parentNodeId;if(!o)return xo(n.id,0);let r=t[o];if(!r||r.isDeleted)return!1;let d=K(r.id).findIndex(l=>l.id===n.id);return d>=0?(L.navigate({contextNode:r,selectedIndex:d}),!0):ji(r.id)},Bi=e=>{let{nodes:t}=p(),n=e,o=new Set;for(;n&&!o.has(n);){if(o.add(n),ji(n))return!0;n=t[n]?.parentNodeId}return!1},xu=e=>{if(!e)return!1;let t=p().nodes[e];return!!t&&!t.isDeleted},Wi=e=>{let{nodes:t,rootNodeId:n}=p();if(yu(e.contextNodeId)&&xo(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(xu(e.selectedNodeId)&&e.selectedNodeId&&Bi(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(xo(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&xo(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(Bi(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=K(o.id);return L.navigate({contextNode:o,selectedIndex:_i(e.selectedIndex,r.length)}),c("Restored navigation to root",null)}});import{monotonicFactory as hu,ulid as Ze}from"ulid";function Iu(){let e=He();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]=q(n.id),[r]=o?q(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 Nu(){let e=Iu();return a(e)?e:L.navigate(e.value)}function Vi({userId:e,userName:t}){let n=Tn(),o=Tn(),r=Tn(),s=Tn(),d=Tn(),l=Ie(void 0,void 0);if(a(l))return l;let u=Ie(void 0,void 0);if(a(u))return u;let m=Ie(u.value,void 0);if(a(m))return m;let g=Ie(void 0,void 0);if(a(g))return g;let x=Ie(g.value,void 0);if(a(x))return x;let E=Ie(x.value,void 0);if(a(E))return E;let A=Ie(void 0,void 0);return a(A)?A:c("Created default events",[{id:Ze(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:Ze(),userId:e,userName:t,action:"add.board",payload:{id:o,name:"Default",parent:n,rank:u.value}},{id:Ze(),userId:e,userName:t,action:"add.swimlane",payload:{id:r,name:"Todo",parent:o,rank:g.value}},{id:Ze(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:o,rank:x.value}},{id:Ze(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:o,rank:E.value}},{id:Ze(),userId:e,userName:t,action:"add.board",payload:{id:go,name:"Closed",parent:n,rank:m.value}},{id:Ze(),userId:e,userName:t,action:"add.swimlane",payload:{id:ye,name:"Closed",parent:go,rank:A.value}},{id:Ze(),userId:e,userName:t,action:"lock.node",payload:{id:go}},{id:Ze(),userId:e,userName:t,action:"lock.node",payload:{id:ye}}])}function wn(e){if(!e.length){let o=pe.workspace("temporary-uninitialized-workspace","Workspace","a0"),r=Sn(o);return a(r)?r:(N({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=bt(e).filter(a);return n.length>0?i(`Materializing failed:
43
+ ${n.map(o=>o.message).join(`
44
+ `)}`):(Nu(),N({hasProjectDefinition:!0}),c("State booted successfully",null))}var Tn,ho=y(()=>{"use strict";Le();J();b();jt();w();_t();Ht();bn();Tn=hu()});var z,Ar=y(()=>{"use strict";b();z=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});var Ve,Io,Eu,zi,Tr=y(()=>{"use strict";Hi();ho();Rn();Fe();J();b();w();No();Ar();wr();Ve=null,Io=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Ve,currentStatus:p().syncStatus?.status,currentMessage:p().syncStatus?.msg}),Ve)return logger.debug("[sync] syncAndReloadState joining existing promise"),Ve;logger.debug("[sync] syncAndReloadState creating promise"),Ve=Eu();try{let e=await Ve;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:p().syncStatus?.status,statusMessageAfterResolve:p().syncStatus?.msg}),a(e)&&p().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),N({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}),Ve||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:p().syncStatus?.status,statusMessageBeforeClear:p().syncStatus?.msg}),Ve=null}},Eu=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:p().mode,syncStatus:p().syncStatus});let e=zi();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:p().mode,message:e.message,syncStatus:p().syncStatus}),e;if(Ve)return Ve;logger.debug("[sync] syncAndReloadState:start");let t=z("resolveActorId",X());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),i("Unable to resolve event log path");N({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:p().syncStatus});let n=St(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let o=z("syncEpiqWithRemote",await Eo({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),N({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:p().syncStatus}),Pe(`Unable to sync state. ${o.message}`);let{stateBranchRoot:r}=o.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:r});let s=z("loadMergedEvents",Ct(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 N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:p().syncStatus}),i(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let d=zi();if(d)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:p().mode,message:d.message,syncStatus:p().syncStatus}),d;let l=$i();if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:l,selectedNodeId:p().selectedNode?.id,contextNodeId:p().contextNode?.id,selectedNodeIsVirtual:p().selectedNode?.isVirtual,contextNodeIsVirtual:p().contextNode?.isVirtual}),!p().selectedNode?.isVirtual&&!p().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let m=z("bootStateFromEventLog",wn(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(m),message:(a(m),m.message)}),a(m))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:p().syncStatus}),i(`Unable to boot synced state. ${m.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:p().selectedNode?.isVirtual,contextNodeIsVirtual:p().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),logger.debug("[sync] restoreNavigationAnchor:start");let u=z("restoreNavigationAnchor",Wi(l));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(u),message:a(u)?u.message:"Navigation restored",selectedNodeId:p().selectedNode?.id,contextNodeId:p().contextNode?.id}),a(u)?(N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:p().syncStatus}),u):(N({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:p().syncStatus}),c("Synced",!0))},zi=()=>p().mode===f.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:p().mode,syncStatus:p().syncStatus}),N({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),i("Will not re-materialize if not in default mode, to not lose edit data"))});var qt,qi,Gi,Mr,Lr,Mn,Pr,bu,Ki,Cu,Yi,bo=y(()=>{"use strict";b();he();w();Tr();qt=3e3,qi=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<qt?null:t},Gi=0,Lr=!1,Mn=!1,Pr=()=>{if(Lr)return!0;let e=He();return a(e)?!1:e.value.syncStatus.status==="syncing"},bu=()=>{let e=Q().autoSyncIntervalMs??1e4,t=Date.now()-Gi;return Math.max(0,e-t)},Ki=()=>{Mr||(Mr=setTimeout(async()=>{if(Mr=void 0,!!Gt()){if(Pr()){Mn=!0;return}Mn=!1,await Cu()}},bu()))},Cu=async()=>{if(p().readOnly||p().timeMode==="peek")return i("Cannot auto-sync while peeking");if(!Gt())return i("Cannot auto-sync before state is initialized");if(Pr())return Mn=!0,i("Sync already in progress");Lr=!0,Gi=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Io()}finally{Lr=!1,Mn&&Ki()}},Yi=()=>{Gt()&&(Mn=!0,!Pr()&&Ki())}});var Co,Xi,Ji,Qi,Ln=y(()=>{"use strict";b();yt();he();ce();Co=()=>{let e=Q(),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}},Xi=()=>{let e=it(process.cwd());if(a(e))return!1;let t=dt(e.value);return ft(t)},Ji=e=>e===!0?"on":e===!1?"off":null,Qi=e=>e==="on"?!0:e==="off"?!1:null});var Su,Ru,kr,Dr,So,Ro,Ao=y(()=>{"use strict";te();b();ie();w();Su=e=>e.props.tags??[],Ru=e=>e.props.assignees??[],kr=e=>Su(e).map(t=>I.getTag(t)).filter(t=>!!t),Dr=e=>Ru(e).map(t=>I.getContributor(t)).filter(t=>!!t),So=()=>{let{breadCrumb:e,selectedNode:t}=p(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!D(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",kr(n))},Ro=()=>{let{breadCrumb:e,selectedNode:t}=p(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!D(n)?i("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",Dr(n))}});var v,At=y(()=>{"use strict";v={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""}});var Au,Tu,wu,Mu,Lu,To,Zi,Pu,ea,wo=y(()=>{"use strict";Au=/^(\d+)(h|d|w|mo|y)$/,Tu=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,wu=({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},Mu=(e,t=new Date)=>{let n=e.match(Au);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}},Lu=e=>{let t=e.match(Tu);if(!t)return null;let[,n,o,r,s,d]=t,l=Number(n),u=Number(o),m=Number(r),g=s?Number(s):0,x=d?Number(d):0;return wu({year:l,month:u,day:m,hour:g,minute:x})?new Date(l,u-1,m,g,x):null},To=e=>{let t=e.trim().toLowerCase();return Mu(t)??Lu(t)},Zi=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Pu=[{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}],ea=(e=Pu)=>{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 ku,oe,ze,Du,Fu,Or,Tt,Mo,Fr,ta,Ou,Uu,Bu,ue,Kt=y(()=>{"use strict";bo();Ln();ie();w();lo();Ao();At();wo();ku=["BOARD","TICKET","SWIMLANE","COMMENT"],oe={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},ze={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Du=[oe.EDITOR,oe.VIEW,oe.USERNAME,oe.AUTOSYNC,oe.SYNC_DEBOUNCE_MS,oe.LOG_LEVEL],Fu=[ze.TITLE,ze.DESCRIPTION,ze.COMMENT],Or=[String(qt),"5000","15000","30000","60000"],Tt=[v.COFFEE,v.EXIT,v.SYNC,v.HELP,v.EXPORT,v.CONFIG],Mo=[v.NEW,v.EDIT,v.DELETE,v.MOVE],Fr=[v.TAG,v.UNTAG,v.ASSIGN,v.UNASSIGN,v.CLOSE_ISSUE,v.RE_OPEN_ISSUE,v.EDIT,v.COMMENT],ta=[v.FILTER,v.PEEK],Ou={WORKSPACE:[...Tt,...Mo],BOARD:[...ta,...Tt,...Mo],SWIMLANE:[...ta,...Tt,...Mo],TICKET:[...Tt,...Mo,...Fr],FIELD:[...Tt,...Fr],FIELD_LIST:[...Tt,...Fr],TEXT:[...Tt],COMMENT:[v.EDIT,v.DELETE]},Uu=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Bu=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:o}=Co();if(!o)return[v.HELP,v.CONFIG];if(!Xi())return[v.HELP,v.INIT];if(t)return[v.HELP,v.PEEK,v.EXPORT,v.CONFIG];let r=e?.context,s=r&&ku.includes(r);return[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?Ou[l]:[]))].filter(l=>l===v.MOVE?!1:l===v.EDIT||l===v.DELETE?s:!0)},ue=(e,{contextNode:t,selectedNode:n,readOnly:o,breadCrumb:r}=p())=>{let s=t.context??"WORKSPACE";return{[v.NONE]:Bu({breadCrumb:r,readOnly:o,selectedNode:n}),[v.EXIT]:["confirm"],[v.EXPORT]:[],[v.SYNC]:[],[v.INIT]:[],[v.HELP]:[],[v.PEEK]:[...ea(),"now","prev","next"],[v.EDIT]:[...Fu],[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","clear"],[v.TAG]:[...new Set([...Object.keys(Wt),...I.getExistingTags()])],[v.UNTAG]:[...So()?.value?.map(({name:l})=>l)??[]],[v.UNASSIGN]:[...Ro()?.value?.map(({name:l})=>l)??[]],[v.ASSIGN]:I.getExistingAssignees(),[v.NEW]:Uu(s),[v.CONFIG]:[...Du],[v.COFFEE]:["1","3","5","20","custom"]}[e]??[]}});var na,oa=y(()=>{"use strict";na=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});var ke,Yt=y(()=>{"use strict";b();ke=(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 ra from"chalk";var Z,xe,fe,sa=y(()=>{"use strict";ct();Ne();Z=e=>ra.dim(e),xe=e=>ra.hex(C.primary)(e),fe=({prefix:e="",wordList:t,postfix:n="",noOfHints:o=100,inputString:r,minLengthForHints:s=1})=>{let d=r.trim();if(d.length<s)return"";let g=[...t.filter(Boolean).filter(x=>x.startsWith(d))].sort((x,E)=>uo(x)-uo(E)).slice(0,o).map(x=>mo(x)).join(" ");return g?`${Z(e)}${g}${Z(n)}`:""}});var lt,Lo=y(()=>{"use strict";lt={None:"none",Invalid:"invalid",Valid:"valid"}});import aa from"chalk";var Xt,_u,ia,re,H,B,ko,Po,Ur,$u,wt,ju,Wu,Hu,da,Br=y(()=>{"use strict";bo();Ln();oa();Nn();Yt();b();ie();de();he();w();ct();Ao();En();sa();At();Lo();Kt();wo();Xt=140,_u=["BOARD","TICKET","SWIMLANE"],ia=()=>{let e=p().selectedNode;if(!e?.context)return B({message:Z("Missing target context")});if(_u.includes(e.context))return H();if(e.parentNodeId){let t=p().nodes[e.parentNodeId];if(t?.id===be(t?.parentNodeId??"","comments"))return H()}return B({message:Z("Command not available in this context")})},re="<ENTER> to confirm",H=(e="",t=[])=>({message:Z(e),validity:lt.Valid,completionWordList:t}),B=({message:e,completionWordList:t=[]})=>({validity:lt.Invalid,message:e,completionWordList:t}),ko=e=>e.length===0,Po=e=>` ${aa.hex("#000").bgHex(Ee(e))(` ${e} `)} `,Ur=({modifier:e})=>{let t="confirm";return e===t?H(re):B({message:ko(e)?Z("if you are certain, enter ")+mo(t):"",completionWordList:[t]})},$u=({list:e,hint:t,onValue:n})=>({modifier:o,inputString:r})=>e.includes(o)?r.trim().length<1?B({message:Z(n)}):H():B({message:ko(o)?t:"",completionWordList:[...e]}),wt=({hint:e,onOk:t})=>({modifier:n,inputString:o})=>ko(n)&&ko(o)?B({message:e,completionWordList:[]}):H(t??re),ju=({modifier:e,inputString:t})=>{let n=ue(v.CONFIG);if(!n.includes(e))return B({message:fe({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case oe.EDITOR:{let o=[...na];return t.trim()?o.includes(t.trim())?H(re):B({message:fe({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o}):B({message:fe({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case oe.VIEW:{let o=["dense","wide"];return o.includes(t.trim())?H(re):B({message:fe({prefix:"view... ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case oe.USERNAME:return t.trim()?H(re):B({message:xe("Enter a user name. Saved in ")+aa.bgBlack("~/.epiq-global/config.json")});case oe.LOG_LEVEL:{let o=["debug","error","info"],r=t.trim();return o.includes(r)?H(re):B({message:fe({prefix:"one of: ",wordList:[...o],inputString:r,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...o]})}case oe.AUTOSYNC:{let o=["on","off"],r=Q().autoSync;if(!o.includes(t.trim())){let s=Ji(r);return B({message:fe({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:o,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:o})}return H(re)}case oe.SYNC_DEBOUNCE_MS:{let o=Q().autoSyncIntervalMs,r=qi(t);if(!t.trim()||r===null||r<qt){let s=fe({prefix:" examples: ",wordList:Or,minLengthForHints:0,inputString:t});return B({message:xe(`provide duration above ${qt}ms. current duration: ${o}ms.`)+s,completionWordList:Or})}return H(re)}default:return B({message:xe("Unknown config option"),completionWordList:n})}},Wu=({modifier:e,inputString:t})=>{let n=ue(v.EDIT);if(!n.includes(e)){let d=fe({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return B({message:d||xe("Unknown edit option"),completionWordList:n})}let{breadCrumb:o,selectedNode:r}=p(),s=ke([...o,r],"TICKET");if(a(s))return B({message:xe("Command not available in this context")});switch(e){case ze.COMMENT:return t||Jt(()=>"hahah"),H(re);case ze.TITLE:return H(re);case ze.DESCRIPTION:{let{preferredEditor:d}=Q();return d?H(Z("<ENTER> to edit in ")+d):B({message:"No editor selected"})}default:return B({message:xe("Unknown edit option"),completionWordList:n})}},Hu={[v.EXPORT]:()=>H(re+Z(", and create export markdown file")),[v.PEEK]:e=>{let t=e.modifier;if(t==="now")return H(re);let n={message:Z("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")};if(t==="prev"||t==="next")return H(re);let o=To(t);if(!t||!o)return B(n);let r=ke(p().breadCrumb,"BOARD");if(a(r))return B({message:xe("Command is not applicable in this context")});let s=yi(r.value.id);return a(s)?B({message:xe("Unable to peek: board id is not a valid ULID")}):Zi({date:o,horizonDate:s.value})?H(re):B({message:xe(`nothing to peek before ${s.value.toISOString().slice(0,16).replace("T"," ")}`)})},[v.EXIT]:()=>H(re+Z(" and exit the application")),[v.INIT]:()=>H(re),[v.PALETTE]:()=>H(re),[v.FILTER]:e=>{if(e.modifier==="clear")return H();let t=s=>ue(v.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return B({message:fe({wordList:ue(v.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:ue(v.FILTER)});let n=Object.values(p().tags).map(s=>s.name),o=Object.values(p().contributors).map(s=>s.name),r=e.modifier==="tag"?n:e.modifier==="assignee"?o:[];return e.inputString?r.length&&!r.includes(e.inputString.trim())?B({message:fe({prefix:`existing ${e.modifier}s... `,wordList:r,noOfHints:10,inputString:e.inputString}),completionWordList:r}):H():B({message:fe({prefix:"one of... ",wordList:r,noOfHints:10,inputString:e.inputString}),completionWordList:r})},[v.NONE]:e=>{let t=ue(v.NONE);return B({message:fe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[v.NEW]:e=>$u({list:ue(v.NEW),hint:fe({wordList:ue(v.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[v.HELP]:()=>H(re),[v.EDIT]:Wu,[v.COMMENT]:e=>{let t=wt({hint:Z(`write a comment (max ${Xt} char)...`),onOk:Z(`(${e.inputString.length}/${Xt})`)})(e);return t.validity===lt.Invalid?t:e.inputString.length>Xt?H(xe("max input exceeded")):t},[v.CONFIG]:ju,[v.DELETE]:e=>{let t=ia();return t.validity==="invalid"?t:Ur(e)},[v.CLOSE_ISSUE]:e=>Ur(e),[v.RE_OPEN_ISSUE]:e=>Ur(e),[v.MOVE]:e=>{let t=ia();return t.validity==="invalid"?t:wt({hint:fe({prefix:"hey hacker! These commands are blocked for you... ",wordList:ue(v.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[v.TAG]:e=>{let n=I.getExistingTags().slice(0,10).map(Po).join("");return wt({hint:n.length?Z("create tag or reuse:")+n+Z(""):Z("create tag ...")})(e)},[v.UNTAG]:e=>{let t=So();if(a(t))return B({message:xe("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(Po).slice(0,10);return n.length?wt({hint:Z(" ... ")+n.join("")})(e):B({message:xe("Issue has no tags"),completionWordList:[]})},[v.ASSIGN]:e=>{let t=I.getExistingAssignees().map(Po).slice(0,10);return wt({hint:Z("assignees... ")+t.join("")})(e)},[v.UNASSIGN]:e=>{let t=Ro();if(a(t))return B({message:xe("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(Po).slice(0,10);return n.length?wt({hint:Z("remove assignee... ")+n.join("")})(e):B({message:xe("Issue has no assignees"),completionWordList:[]})},[v.SYNC]:()=>H(re),[v.COFFEE]:e=>{let{modifier:t}=e,n=ue(v.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?B({message:Z("enter an amount ... "),completionWordList:n.filter(o=>o.startsWith(t))}):wt({hint:fe({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},da=Object.fromEntries(Object.entries(Hu).map(([e,t])=>[e,{validate:(n,o,r)=>t({modifier:o,command:n,inputString:r})}]))});var ca,la=y(()=>{"use strict";ca=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"]});var ua,ma,_r=y(()=>{"use strict";ci();Kt();At();Br();la();w();J();ua=e=>Object.values(v).includes(e),ma=(e,t)=>{let n=e.command??"",{modifier:o,target:r,inputString:s}=e,{message:d,validity:l,completionWordList:u}=da[n].validate(n,o,s),m=r==="command"||r==="modifier"?ue(n):ca,{mode:g}=p(),x=g===f.COMMAND_LINE?d??"":"",E=[...u,...m];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:x,autoCompletion:t?di(e,E):{hint:"",hints:[],remainder:"",overlap:0}}}});var pa,Vu,zu,qu,ga=y(()=>{"use strict";_r();Kt();pa=e=>{let t=e.trimStart(),n=zu(t),o=n[0]??"",r=n[1]??"",s=/\s$/.test(e),d=qu(e),l=ua(o)?o:null,u=l!==null,m=o!=="",g=l?ue(l)??[]:[],x=l&&g.includes(r)?r:"",E="word";n.length===0||n.length===1&&!s?E="command":(n.length===1&&s||n.length===2&&!s)&&(E="modifier");let A=s?"":d,S=Vu(t,l,x);return{raw:e,trimmedStart:t,words:n,firstWord:o,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:s,modifier:x,target:E,inputToMatch:A,inputString:S}},Vu=(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},zu=e=>e.trim()?e.trim().split(/\s+/):[],qu=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as lh}from"react";var Qt,$r,Zt,Gu,fa,qe,Pn,jr,Wr,va,ya,Jt,xa,$,ha,Ia,Na,se,Ea,de=y(()=>{"use strict";_r();ga();b();Lo();Qt=e=>e===$r||e===":",$r=" ",Zt={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:lt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Gu=new Set,fa=()=>{for(let e of Gu)e()},qe=e=>{let n=e(Zt),o=pa(n.value),r=n.cursorPosition===n.value.length;Zt={...n,commandMeta:ma(o,r)},fa()},Pn=({message:e,status:t})=>{let n=structuredClone(Zt);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Zt=n,fa(),c(e,null)},jr=e=>{qe(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Wr=e=>{qe(t=>{let{value:n,cursorPosition:o}=t,r=o;if(e==="left"){for(;r>0&&Qt(n[r-1]);)r--;for(;r>0&&!Qt(n[r-1]);)r--}else{for(;r<n.length&&!Qt(n[r]);)r++;for(;r<n.length&&Qt(n[r]);)r++}return{...t,cursorPosition:r}})},va=()=>{qe(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}})},ya=()=>{qe(e=>{let{value:t,cursorPosition:n}=e,o=n;for(;o>0&&Qt(t[o-1]);)o--;for(;o>0&&!Qt(t[o-1]);)o--;let r=t.slice(n);return{...e,value:t.slice(0,o)+r,cursorPosition:o,commandIsPending:!1}})},Jt=e=>{qe(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}})},xa=()=>{qe(e=>({...e,commandIsPending:!0}))},$=e=>{qe(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},ha=({addToHistory:e=!0})=>{qe(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Ia=()=>{qe(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}})},Na=()=>{qe(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},se=()=>Zt,Ea=()=>{let[e,...t]=Zt.value.split($r);return t.join($r).trim()}});var R,ht=y(()=>{"use strict";J();ti();w();de();he();R={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"}});var ba,M,Hr=y(()=>{"use strict";w();At();ba=e=>{let{context:t}=p().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.CONFIG:return M.Config;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",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 Ca}from"ink";import Sa,{useEffect as Ra,useState as Ku}from"react";var Aa,Ce,en=y(()=>{"use strict";w();Ne();Aa={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ce=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=De(),o=Aa[n]??Aa.default,[r,s]=Ku(0);if(Ra(()=>{s(0)},[o]),Ra(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%o.length)},500);return()=>clearInterval(l)},[e,o]),!e)return Sa.createElement(Ca,null,t);let d=o[r]??o[0]??t;return Sa.createElement(Ca,{color:C.accent,dimColor:r===1},d)}});import{Box as Vr,Text as Yu}from"ink";import Do from"react";var tn,Fo=y(()=>{"use strict";Ne();tn=({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),g=r?Math.min(m,Math.max(0,u-l+1)):Math.min(m,Math.floor(u/l)*l),x=g+l,E=e.slice(g,x),A=e.length>l,S=s,k=A?Math.max(1,Math.floor(l/e.length*S)):S,_=Math.max(0,S-k),O=Math.max(1,e.length-l),Y=A?Math.floor(g/O*_):0;return Do.createElement(Vr,{flexDirection:"row",height:s,width:"100%"},Do.createElement(Vr,{flexDirection:"column",flexGrow:1,height:s},E),Do.createElement(Vr,{flexDirection:"column",width:1,height:S},Array.from({length:S}).map((W,V)=>Do.createElement(Yu,{key:V,color:A&&V>=Y&&V<Y+k?C.accent:C.secondary},A?"\u2502":" "))))}});import{Text as Xu}from"ink";import Ju from"react";var Qu,Zu,nn,Oo=y(()=>{"use strict";lo();ct();ie();Qu=e=>e.toLowerCase().trim(),Zu=(e,t=Wt)=>{let n=Qu(e);return t[n]?t[n]:In(n)},nn=({id:e,isSelected:t})=>{let n=I.getContributor(e);if(n)return Ju.createElement(Xu,{underline:t,color:Zu(n.name)},"@"+n.name)}});import{Text as em}from"ink";import tm from"react";var Uo,zr=y(()=>{"use strict";ie();Ne();ct();Uo=({id:e,isSelected:t})=>{let n=I.getTag(e);if(n)return tm.createElement(em,{underline:t,backgroundColor:Ee(n.name),color:C.secondary}," "+n.name+" ")}});import{Box as Bo,Text as nm}from"ink";import Mt from"react";var Ta,wa=y(()=>{"use strict";Ne();Ut();Ao();Oo();zr();Ta=({width:e,ticket:t,isSelected:n})=>{let o=e-14,r=io(ao(t.title),o),s=kr(t),d=Dr(t);return Mt.createElement(Bo,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?C.accent:C.secondary,justifyContent:"space-between"},Mt.createElement(Bo,{borderBottom:!0},Mt.createElement(Bo,{paddingLeft:1,flexDirection:"column"},Mt.createElement(nm,{color:C.primary},r))),Mt.createElement(Bo,{flexDirection:"row",paddingLeft:1},s.map(l=>Mt.createElement(Uo,{key:l.id,id:l.id})),d.map(l=>Mt.createElement(nn,{key:l.id,id:l.id}))))}});import{Box as Lt,Text as kn}from"ink";import Se from"react";var om,Ma,La=y(()=>{"use strict";J();ie();Ne();ct();en();om=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Ma=({width:e,ticket:t,isSelected:n,index:o,mode:r})=>{let s=(t.props.tags??[]).map(O=>I.getTag(O)).filter(O=>!!O),d=(t.props.assignees??[]).map(O=>I.getContributor(O)).filter(O=>!!O),l=1,u=s.length*(1+l),m=d.length*(2+l),g=s.map(O=>Se.createElement(Lt,{key:O.id,paddingRight:l},Se.createElement(kn,{color:Ee(O.name)},"\u25A0"))),x=d.map(O=>Se.createElement(Lt,{key:O.id,paddingRight:l},Se.createElement(kn,{color:In(O.name)},"@"+O.name.at(0)))),E=n?C.accent:r===f.MOVE?C.secondary:C.primary,A=4,S=I.getCommentsByIssue(t.id),k=S.length?String(S.length).length+2+l:0,_=S.length?Se.createElement(Lt,{paddingRight:l},Se.createElement(kn,{color:C.accent},"[",S.length,"]")):null;return Se.createElement(Lt,{borderBottom:!0,justifyContent:"space-between"},Se.createElement(Lt,null,Se.createElement(Lt,{width:A},n?Se.createElement(Ce,{isSelected:n}):Se.createElement(kn,{color:"gray",dimColor:!0},o+1)),Se.createElement(kn,{wrap:"truncate",color:E},om(t.title,e-u-m-k-18))),Se.createElement(Lt,null,g,x,_))}});import rm from"chalk";import{Box as qr,Text as sm}from"ink";import Ge from"react";var im,Pa,ka=y(()=>{"use strict";te();w();Ne();en();Fo();wa();La();im=({swimlane:e,isSelected:t,width:n,height:o,isDense:r,isFocused:s,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u}=De(),m=u[e.id]??[],g=`${e.title} ${rm.hex(C.secondary2).dim("("+m.length+")")}`,x=3,E=r?1:4,A=o-x-(r?2:1),S=Ge.createElement(qr,{borderStyle:"round",borderColor:C.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Ge.createElement(Ce,{isSelected:t}),Ge.createElement(sm,{bold:!0,color:t?C.accent:C.primary},g," ",e.readonly?"\u{1F512}":"")),k=(_,O)=>{let Y=s&&d===O;return D(_)?r?Ge.createElement(Ma,{key:_.id,index:O,width:n,ticket:_,isSelected:Y,mode:l}):Ge.createElement(Ta,{key:_.id,width:n,ticket:_,isSelected:Y}):null};return Ge.createElement(qr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?C.accent:C.secondary,paddingRight:1,paddingLeft:1,height:o},S,Ge.createElement(qr,{padding:r?1:0},m.length>0&&Ge.createElement(tn,{selectedIndex:d,height:A,itemHeight:E},m.map(k)),Ge.createElement(Ce,{isSelected:s&&d===-1})))},Pa=Ge.memo(im)});import{Box as _o,Text as am}from"ink";import et from"react";var Da,Fa=y(()=>{"use strict";te();ie();$t();w();Ne();Oo();en();zr();Da=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:o}=De(),{title:r}=t,s=t.parentNodeId?I.getNode(t.parentNodeId):void 0,d=s&&D(s)?r===ne.ASSIGNEES?s.props.assignees??[]:r===ne.TAGS?s.props.tags??[]:[]:[];return et.createElement(_o,{alignItems:"center",paddingTop:1},et.createElement(_o,{minWidth:12},et.createElement(Ce,{isSelected:n}),et.createElement(am,{color:n?C.accent:C.secondary2},r,":")),et.createElement(_o,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=o.id===t.id&&u===e;return et.createElement(_o,{key:`${r}-${l}`,paddingRight:2,minHeight:1},et.createElement(Ce,{isSelected:m}),r===ne.ASSIGNEES?et.createElement(nn,{isSelected:m,id:l}):r===ne.TAGS?et.createElement(Uo,{isSelected:m,id:l}):null)})))}});import{Box as $o,Text as Gr}from"ink";import tt,{useEffect as dm,useMemo as Oa}from"react";var cm,Ua,Kr,Ba,lm,Yr,_a=y(()=>{"use strict";ie();b();jt();w();Ne();Ut();en();Fo();_t();cm="\u2029",Ua=(e,t)=>`${e}::inline-line::${t}`,Kr=new Map,Ba=e=>{let t=Kr.get(e)??[];Kr.delete(e);for(let n of t)I.deleteNode(n)},lm=(e,t)=>{Ba(e);let n=[];t.forEach((o,r)=>{let s=Me(BigInt(r+1));if(!ft(s))return;let d=I.createNode(pe.text({id:Ua(e,r),name:`Line ${r+1}`,parentNodeId:e,rank:s.value,props:{value:o},readonly:!0,isVirtual:!0}));ft(d)&&n.push(d.value.id)}),Kr.set(e,n)},Yr=({id:e,label:t,text:n,height:o,selected:r,maxWidth:s})=>{let{selectedIndex:d,contextNode:l}=De(),u=Oa(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Oa(()=>u.join("\0"),[u]);dm(()=>(lm(e,u),()=>{Ba(e)}),[e,m]);let g=E=>String(E).replace(/\r?\n/g,""),x=u.map((E,A)=>{let S=l.id===e&&d===A;return tt.createElement($o,{key:Ua(e,A)},tt.createElement(Gr,{color:S?C.primary:C.secondary2,dimColor:!S},`${A+1} `.padStart(5,"\xA0")),tt.createElement(Gr,{backgroundColor:S?"gray":void 0},g(E.length?io(E,s-10):cm)))});return tt.createElement($o,{flexDirection:"column",paddingTop:1},tt.createElement($o,null,tt.createElement(Ce,{isSelected:r}),tt.createElement(Gr,{color:r?C.accent:C.secondary2},t)),tt.createElement($o,{flexDirection:"row",borderStyle:"round",borderColor:C.secondary,paddingLeft:1,marginLeft:1},tt.createElement(tn,{scrollByOne:!0,height:o-3,selectedIndex:d,itemHeight:1},x)))}});var $a,ja,Xr=y(()=>{"use strict";jt();$a=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},ja=(e,t,n)=>pe.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 ut,Text as nt}from"ink";import ae,{useEffect as um,useMemo as mm,useRef as pm}from"react";import{decodeTime as Jr}from"ulid";function Ha({ticket:e,width:t,height:n}){let o=mm(()=>fm(e),[e]),r=pm([]);um(()=>(Wa(r.current),r.current=vm(e,o),()=>{Wa(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=De(),l=Math.max(1,n-4),u=Math.max(20,t-8);return o.length===0?ae.createElement(ut,{flexDirection:"column",width:t,height:n,padding:1},ae.createElement(nt,{color:C.primary},"No comments yet."),ae.createElement(ut,{paddingTop:1},ae.createElement(nt,{color:C.primary},"Use"),ae.createElement(nt,{color:C.accent}," :comment "),ae.createElement(nt,{color:C.primary},"to add the first one."))):ae.createElement(ut,{flexDirection:"column",width:t,height:n},ae.createElement(ut,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:C.secondary,borderStyle:"single",paddingBottom:1},ae.createElement(nt,{color:C.secondary2},"Comments (",o.length,") ")),ae.createElement(tn,{height:l,itemHeight:4,selectedIndex:s},o.map((m,g)=>{let x=g===s;return ae.createElement(ut,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:C.secondary,borderStyle:"single"},ae.createElement(ut,{flexDirection:"row",paddingBottom:1},ae.createElement(nt,{color:C.accent},x?"\u276F ":" "),ae.createElement(ut,{paddingLeft:1},ae.createElement(nt,{color:C.secondary2},`#${g+1} `),ae.createElement(nn,{id:m.authorId}),ae.createElement(nt,{color:C.secondary2}," "+po(Jr(m.id))))),ae.createElement(ut,{paddingLeft:3,paddingBottom:1},ae.createElement(nt,{color:C.primary},ym(m.md,u))))})))}var gm,fm,Wa,vm,ym,Va=y(()=>{"use strict";Le();Nn();te();b();ie();w();Ne();En();Oo();Fo();Xr();gm=e=>be(e,"comments"),fm=e=>I.getCommentsByIssue(e.id).sort((t,n)=>Jr(t.id)-Jr(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),Wa=e=>{for(let t of e)I.deleteNode(t.id)},vm=(e,t)=>{let n=I.getNode(gm(e.id));if(!n||!_e(n))return[];let o=t.map((r,s)=>ja(r,s,n.id)).map(I.createNode).filter(ft).map(({value:r})=>r).filter(hn);return t.length>0&&p().selectedIndex<0&&L.navigate({contextNode:n,selectedIndex:0}),o},ym=(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 Dn,Text as za}from"ink";import Re,{useMemo as jo}from"react";var xm,hm,Im,qa,Ga=y(()=>{"use strict";te();ie();w();Ne();En();en();Fa();_a();Va();Xr();xm=e=>be(e,"description"),hm=e=>be(e,"comments"),Im=e=>be(e,"history"),qa=({ticket:e,height:t})=>{let n=jo(()=>$a(e),[e]),{selectedIndex:o,contextNode:r}=De(),s=process.stdout.columns||120,d=jo(()=>xm(e.id),[e.id]),l=jo(()=>hm(e.id),[e.id]),u=jo(()=>Im(e.id),[e.id]),m=r.id===e.id,g=r.id===l||r.parentNodeId===l,x=r.id===u||r.parentNodeId===u,E=q(e.id);if(g){let V=t-3;return Re.createElement(Dn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Re.createElement(Ha,{ticket:e,width:s,height:V}))}if(x){let W=I.getNode(u),V=W&&_e(W)?W.props.value??"":"",jn=t-3;return Re.createElement(Dn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},W?Re.createElement(Yr,{id:W.id,label:"Event log",text:V,selected:!1,maxWidth:s,height:jn}):null)}let A=E.reduce((W,V)=>yn(V)||V.id===l||V.id===u?W+1:W,0),S=2,k=3,_=A,O=t-k-_-S,Y=(W,V)=>W.id===d?Re.createElement(Yr,{key:W.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:V,maxWidth:s,height:O}):yn(W)?Re.createElement(Da,{key:W.id,parent:W,selected:V,selectedIndex:o}):W.id===l?Re.createElement(Dn,{key:W.id,paddingTop:1},Re.createElement(Ce,{isSelected:V}),Re.createElement(za,{backgroundColor:C.secondary,color:V?C.accent:C.primary},` Comments (${n}) \u203A\u203A `)):W.id===u?Re.createElement(Dn,{key:W.id,paddingTop:1},Re.createElement(Ce,{isSelected:V}),Re.createElement(za,{backgroundColor:C.secondary,color:V?C.accent:C.primary}," History \u203A\u203A ")):null;return Re.createElement(Dn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},E.map((W,V)=>Y(W,m&&o===V)))}});import{Box as Nm}from"ink";import Wo from"react";var Em,Ka,Ya=y(()=>{"use strict";te();ka();Ga();Em=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,viewMode:s,height:d,width:l})=>{let u=t.context,m=u===T.TICKET||u===T.FIELD_LIST||u===T.FIELD,g=u===T.BOARD||u===T.SWIMLANE,x=u===T.TICKET?t:o.find(_=>_.context===T.TICKET),E=Math.floor(l/3),A=Math.floor(l/Math.max(e.length,1)),S=Math.min(A,E),k=s==="dense";return Wo.createElement(Nm,{flexDirection:"row",height:d},g&&e.map((_,O)=>{let Y=t.id===_.id,W=Y?n:-1,V=t.context===T.BOARD&&n===O;return Wo.createElement(Pa,{key:_.id,height:d,width:S,swimlane:_,isSelected:V,isDense:k,isFocused:Y,listSelectedIndex:W,mode:r})}),m&&x&&Wo.createElement(qa,{height:d,ticket:x}))},Ka=Wo.memo(Em)});import Xa from"node:fs";import bm from"node:path";import Cm from"react";import{render as Sm}from"ink";import{Writable as Rm}from"node:stream";var Fn,Am,Tm,wm,Mm,Ja,Qa=y(()=>{"use strict";Ya();te();b();w();ce();he();Fn=e=>String(e).padStart(2,"0"),Am=e=>{let t=e.getUTCFullYear(),n=Fn(e.getUTCMonth()+1),o=Fn(e.getUTCDate()),r=Fn(e.getUTCHours()),s=Fn(e.getUTCMinutes()),d=Fn(e.getUTCSeconds());return`${t}-${n}-${o}_${r}-${s}-${d}`},Tm=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",wm=async(e,{width:t,height:n})=>{let o="",r=new Rm({write(d,l,u){let m=Mm(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(o=m),u()}});r.columns=t,r.rows=n,r.isTTY=!0;let s=Sm(e,{stdout:r,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),o},Mm=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Ja=async()=>{let{viewMode:e}=Q(),{contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,renderedChildrenIndex:s}=p(),d=o.find(O=>O.context==="BOARD");if(!d)return i("No board found to export");let l=120,u=40,m=await wm(Cm.createElement(Ka,{height:u,width:l,swimlanes:(s[d.id]??[]).filter(O=>O!==void 0&&xn(O)),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 g=zn(process.cwd());if(a(g))return i("Unable to export, epiq root not found");let x=new Date,E=Am(x),A=`board_${Tm(d.title)}_${E}.md`,S=Rs(g.value);Xa.mkdirSync(S,{recursive:!0});let k=bm.join(S,A),_=`# Board - ${d.title}
23
45
  Date: ${x.toISOString()}
24
46
 
25
47
  \`\`\`text
26
48
  ${m}
27
49
  \`\`\`
28
- `;return aa.writeFileSync(k,A,"utf8"),c("Exported board layout",k)}});var L,la,ua,Te=y(()=>{"use strict";Se();T();L={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=H(t.id)[n];!r||t.context==="FIELD"||L.navigate({contextNode:r,selectedIndex:q(r.id).length?0:-1})},enterParentNode(){let{contextNode:e,nodes:t}=v();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),i=r.length===0?-1:o>=0?o:0;L.navigate({contextNode:n,selectedIndex:i})},navigateToNextItem:()=>la(1),navigateToPreviousItem:()=>la(-1),navigateToNextContainer:()=>ua(1),navigateToPreviousContainer:()=>ua(-1),navigate:({contextNode:e,selectedIndex:t})=>{E({contextNodeId:e.id,selectedIndex:t})}},la=e=>{let{selectedIndex:t,contextNode:n}=v(),r=q(n.id).length;if(r===0)return;let i=(Math.max(0,t)+e+r)%r;L.navigate({selectedIndex:i,contextNode:n})},ua=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let i=q(o.id),d=i.findIndex(b=>b.id===t.id);if(d<0)return;let l=i.at(d+e)??i.at(0);if(!l)return;let u=q(l.id),m=Math.max(0,u.length-1),g=Math.min(Math.max(0,r),m),x=u.length?g:-1;L.navigate({contextNode:l,selectedIndex:x})}});import{accessSync as fu,copyFileSync as vu,existsSync as Nr,mkdirSync as ma,readdirSync as pa,readFileSync as yu,renameSync as xu,rmSync as hu,statSync as ga,unlinkSync as Eu,writeFileSync as Nu}from"node:fs";import jt from"node:path";var wo,he,To=y(()=>{"use strict";wo=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",he={writeToFile:(e,t)=>{try{let n=jt.dirname(e);Nr(n)||ma(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Nu(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return yu(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=he.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 Nr(e)&&ga(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await fu(e),!0}catch{return!1}},mkDir:e=>ma(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=jt.parse(t);for(;;){let r=jt.join(t,e);try{if(Nr(r)&&ga(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=jt.dirname(t)}return null},readFirstJSON(e){try{if(!he.dirExists(e))return null;let t=pa(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=jt.join(e,t);return he.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return he.dirExists(e)?pa(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Eu(e)}catch(t){(!wo(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{hu(e,{recursive:!0,force:!0})}catch(t){(!wo(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(jt.dirname(t)),!n?.overwrite&&Nr(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{xu(e,t)}catch(r){if(wo(r)&&r.code==="EXDEV"){vu(e,t),this.rmFile(e);return}throw r}}}});import Iu from"node:os";import fa from"node:path";import{z as st}from"zod";var bu,va,Cu,ya,Mo,Lo,Su,xa,ha,Ye,Ea,Ht=y(()=>{"use strict";re();C();To();bu={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},va=st.object({logLevel:st.enum(["info","error","debug"]),preferredEditor:st.string().optional(),userName:st.string().optional(),userId:st.string().optional(),autoSync:st.boolean().nullable().optional(),autoSyncDebounceMs:st.number().optional(),viewMode:st.enum(["dense","wide"]).optional()}).partial(),Cu="config.json",ya=()=>fa.join(Iu.homedir(),Ee),Mo=()=>fa.join(ya(),Cu),Lo=()=>{try{return he.mkDir(ya()),c(`Ensured ~/${Ee} exists`,null)}catch{return s(`Unable to create ~/${Ee}`)}},Su=e=>{let t;try{t=JSON.parse(e)}catch{return s(`Invalid ~/${Ee}/config.json JSON`)}let n=va.safeParse(t??{});return n.success?c("Parsed config",n.data):s(`Invalid ~/${Ee}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},xa=()=>{let e=Lo();if(a(e))return s(e.message);let t=Mo(),n=he.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Su(n)},ha=e=>{let t=Lo();if(a(t))return s(t.message);let n=va.safeParse(e);if(!n.success)return s(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Mo();try{return he.writeToFile(r,JSON.stringify(n.data,null,2)+`
29
- `),c("Config written",null)}catch{return s(`Unable to write ~/${Ee}/config.json`)}},Ye=e=>{let t=xa();if(a(t))return s("Failed to read existing config");let n={...t.value,...e};return ha(n)},Ea=()=>{let e=Mo(),t=Lo();if(a(t))return s(`Unable to create ~/${Ee}`);if(!(he.readFile(e)!==null)){let g=ha(bu);if(a(g))throw new Error(`Unable to create ~/${Ee}/config.json`)}let r=xa();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:d,autoSync:l,autoSyncDebounceMs:u,logLevel:m}=r.value;return!i||!d?s(`User name or ID not configured in ~/${Ee}/config.json`):(process.env.EPIQ_LOG_LEVEL=m,c("successfully loaded settings",{logLevel:m??"debug",preferredEditor:o??"",userName:i,userId:d,autoSync:l??!1,autoSyncIntervalMs:u??1e4,viewMode:"dense"}))}});import Ir from"node:fs";import ko from"node:path";import{decodeTime as Ru}from"ulid";import{z as Po}from"zod";function Do(e){let t=an(e);if(!Ir.existsSync(t))return c("No events found",[]);let n=Ir.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>ko.join(t,o)),r=[];for(let o of n){let i=ku(o);if(a(i))return s(i.message);r.push(...i.value)}return c("All events loaded",Fu(r))}function zt(e){let t=Do(e);return a(t)?s(t.message):Fo(t.value)}function Na(e,t){let n=Do(e);if(a(n))return s(n.message);let{appliedEvents:r,unappliedEvents:o}=Du(n.value,t),i=Fo(r);if(a(i))return s(i.message);let d=Fo(o);return a(d)?s(d.message):c("Loaded merged events before time",{appliedEvents:i.value,unappliedEvents:d.value})}function Ia(e=process.cwd()){let t=Do(e);return a(t)?s(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Au,wu,Tu,Mu,Lu,Pu,Fo,ku,Fu,Du,vn=y(()=>{"use strict";C();re();Me();Au=Po.object({userId:Po.string().min(1).default("unknown"),userName:Po.string().min(1).default("unknown")}),wu=e=>{let[t,n]=ko.basename(e,".jsonl").split("."),r=Au.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):s(`Invalid event file name ${ko.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Tu=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?s(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?s("Invalid persisted event: action key is missing or invalid"):c("Resolved persisted action",t[0])},Mu=(e,t)=>t in e,Lu=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Pu=e=>{let{userId:t,userName:n,...r}=e,o=Tu(r);if(a(o))return s(o.message);let i=o.value,d=e.id?.[0];return d?Mu(r,i)?c("Decoded persisted event",Lu({id:d,action:i,payload:r[i],userId:t,userName:n})):s(`Persisted event is missing payload for action: ${i}`):s("Persisted event is missing id")},Fo=e=>{let t=[];for(let n of e){let r=Pu(n);if(a(r))return s(`Failed to decode event ${n.id?.[0]??"<unknown>"}: ${r.message}`);t.push(r.value)}return c("Decoded reconstructed events",t)},ku=e=>{if(!Ir.existsSync(e))return c("Event file missing",[]);let t=wu(e);if(a(t))return s(t.message);let n=Ir.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
30
- `)){let i=o.trim();if(!i)continue;let d;try{d=JSON.parse(i)}catch{return s(`Failed to parse event JSON from ${e}: ${i}`)}let l=Oo(d);if(a(l))return s(`${l.message} in ${e}: ${i}`);r.push({...l.value,userId:t.value.userId,userName:t.value.userName})}return c("Parsed persisted events file",r)};Fu=e=>{let t=new Map,n=new Map;for(let m of e){let g=m.id[0],x=m.id[1]??null;t.set(g,m);let b=n.get(x)??[];b.push(m),n.set(x,b)}for(let m of n.values())m.sort((g,x)=>g.id[0].localeCompare(x.id[0]));let r=[],o=new Set,i=m=>{let g=m.id[0];if(o.has(g))return;r.push(m),o.add(g);let x=n.get(g)??[];for(let b of x)i(b)},d=n.get(null)??[];for(let m of d)i(m);let l=e.filter(m=>{let g=m.id[0],x=m.id[1]??null;return!o.has(g)&&x!==null&&!t.has(x)}).sort((m,g)=>m.id[0].localeCompare(g.id[0]));for(let m of l)i(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,g)=>m.id[0].localeCompare(g.id[0]));for(let m of u)i(m);return r},Du=(e,t)=>{let n=new Set,r=[],o=[];for(let i of e){let d=i.id[0],l=i.id[1],u=!1;try{u=Ru(d)<t}catch{u=!1}!u||l&&n.has(l)?(n.add(d),o.push(i)):r.push(i)}return{appliedEvents:r,unappliedEvents:o}}});var ba,Ca=y(()=>{"use strict";ba=e=>({action:e.action,payload:e.payload})});import Ou from"node:fs";import Uu from"node:path";import{decodeTime as Bu,monotonicFactory as _u}from"ulid";import{z as yn}from"zod";function Cr({event:e,rootDir:t}){try{let n=ji(t);if(a(n))return n;let r=ju(t,{userId:e.userId,userName:e.userName});if(a(r))return r;let o=Ia(t);if(a(o))return s(o.message);let i=o.value?Sa(Math.max(Date.now(),Bu(o.value)+1)):Sa(),d=Hu(ba(e),[i,o.value]);return a(d)?s(d.message):(Ou.appendFileSync(r.value,`${JSON.stringify(d.value)}
31
- `,"utf8"),c("Event persisted",{path:r.value,entry:d.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return s(`Failed to persist event: ${r}`)}}var Ra,Sa,$u,Wu,Oo,br,Q,ht,ju,Hu,Me=y(()=>{"use strict";C();ge();re();vn();Ca();Ra=1,Sa=_u(),$u=yn.tuple([yn.string().min(1),yn.string().min(1).nullable()]),Wu=yn.looseObject({v:yn.literal(Ra),id:$u}),Oo=e=>{let t=Wu.safeParse(e);return t.success?c("Parsed persisted event",t.data):s(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},br=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",Q=()=>{let{userName:e,userId:t}=Y();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:br(t),userName:br(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},ht=({userId:e,userName:t})=>`${br(e)}.${br(t)}.jsonl`,ju=(e,{userId:t,userName:n})=>{let r=ht({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return s(`Invalid event log file name: ${r}`);let i=Uu.join(an(e),r);return c("Successfully resolved event log path",i)},Hu=(e,t)=>{let n={[e.action]:e.payload,v:Ra,id:t};return Oo(n)}});var Aa,wa=y(()=>{"use strict";Aa=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 i=t[o];if(i&&"id"in i.payload&&i.payload.id===e.id&&"parent"in i.payload&&i.payload.parent)return i.payload.parent}return null}}return null}});var zu,ue,Sr,xn=y(()=>{"use strict";zu=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ue,Sr]=zu});import{useSyncExternalStore as Ph}from"react";var Uo,Vu,qu,Vt,Ku,at,Rr=y(()=>{"use strict";C();Vu=new Set,qu=()=>{for(let e of Vu)e()},Vt=()=>{if(!Uo)throw new Error("Ui state not initialized. Call initUiState() first.");return Uo},Ku=e=>{let t=Vt();return Uo=e(t),qu(),c("UX state updated",null)},at=e=>Ku(t=>({...t,...e}))});import{spawn as Gu}from"node:child_process";function Bo(e){let t=process.platform,o=Gu(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 Ta=y(()=>{"use strict"});import{spawnSync as Yu}from"node:child_process";import Xu from"node:os";import Ma from"node:path";import{ulid as Ju}from"ulid";function Qu(){let{preferredEditor:e}=Y(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Zu(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function La(e){let t=Ma.join(Xu.tmpdir(),"epiq");he.mkDir(t);let n=Ma.join(t,Ju());he.writeToFile(n,e??"");let r=Qu();for(let o of r){let i=Zu(o,n),d=Yu(i,{stdio:"inherit",shell:!0});if(!d.error&&d.status===0){let l=he.readFile(n);if(l==null)return s("Unable to read edited file");let u=l.replace(/\r?\n$/,"");return c("Successfully edited",u)}}return s("Unable to open editor")}var Pa=y(()=>{"use strict";C();ge();To()});import{ulid as em}from"ulid";var ka,Fa=y(()=>{"use strict";Pa();Et();Me();un();C();kt();T();re();Z();ka=async()=>{let e=Q();if(a(e))return s("Unable to resolve user ID");let t=await Ae();if(a(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=v(),i=De([...r,o],"TICKET");if(a(i))return s("Edit target must be an issue");let d=i.value;if(!B(d))return s("Edit target must be an issue");if(d.readonly)return s("Cannot edit readonly issue");let l=q(d.id).find(x=>x.title===ee.DESCRIPTION);if(!l)return s("No target found");if(l.readonly)return s("Cannot edit readonly field");let u=d.props.description??"";if(typeof u!="string")return s("Selected field is not editable text");let m=La(u);if(a(m))return s("Failed to edit field");let g=m.value;return g===u?c("No changes made",null):Le({id:em(),action:"edit.description",payload:{id:d.id,md:g},...e.value},n)}});import _o from"node:fs";import tm from"node:path";var Da,Oa=y(()=>{"use strict";C();Fn();Da=async e=>{let t=tm.join(e,".gitignore"),n=_o.existsSync(t)?_o.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
32
- `).map(u=>u.trim()),i=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(i.length===0)return c("Local epiq paths already ignored",!1);let l=["# [epiq]: local hydrated state is never committed",...i].join(`
50
+ `;return Xa.writeFileSync(k,_,"utf8"),c("Exported board layout",k)}});import{accessSync as Lm,copyFileSync as Pm,existsSync as Ho,mkdirSync as Za,readdirSync as ed,readFileSync as km,renameSync as Dm,rmSync as Fm,statSync as td,unlinkSync as Om,writeFileSync as Um}from"node:fs";import on from"node:path";var Qr,Ae,Zr=y(()=>{"use strict";Qr=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Ae={writeToFile:(e,t)=>{try{let n=on.dirname(e);Ho(n)||Za(n,{recursive:!0});let o=typeof t=="string"?t:JSON.stringify(t,null,2);Um(e,o,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return km(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Ae.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 Ho(e)&&td(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Lm(e),!0}catch{return!1}},mkDir:e=>Za(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=on.parse(t);for(;;){let o=on.join(t,e);try{if(Ho(o)&&td(o).isDirectory())return o}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=on.dirname(t)}return null},readFirstJSON(e){try{if(!Ae.dirExists(e))return null;let t=ed(e).filter(o=>o.endsWith(".json")).sort()[0];if(!t)return null;let n=on.join(e,t);return Ae.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Ae.dirExists(e)?ed(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Om(e)}catch(t){(!Qr(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Fm(e,{recursive:!0,force:!0})}catch(t){(!Qr(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(on.dirname(t)),!n?.overwrite&&Ho(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Dm(e,t)}catch(o){if(Qr(o)&&o.code==="EXDEV"){Pm(e,t),this.rmFile(e);return}throw o}}}});import Bm from"node:os";import nd from"node:path";import{z as mt}from"zod";var _m,od,$m,rd,es,ts,jm,sd,id,ot,ad,rn=y(()=>{"use strict";ce();b();Zr();_m={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},od=mt.object({logLevel:mt.enum(["info","error","debug"]),preferredEditor:mt.string().optional(),userName:mt.string().optional(),userId:mt.string().optional(),autoSync:mt.boolean().nullable().optional(),autoSyncDebounceMs:mt.number().optional(),viewMode:mt.enum(["dense","wide"]).optional()}).partial(),$m="config.json",rd=()=>nd.join(Bm.homedir(),Te),es=()=>nd.join(rd(),$m),ts=()=>{try{return Ae.mkDir(rd()),c(`Ensured ~/${Te} exists`,null)}catch{return i(`Unable to create ~/${Te}`)}},jm=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${Te}/config.json JSON`)}let n=od.safeParse(t??{});return n.success?c("Parsed config",n.data):i(`Invalid ~/${Te}/config.json shape: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},sd=()=>{let e=ts();if(a(e))return i(e.message);let t=es(),n=Ae.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):jm(n)},id=e=>{let t=ts();if(a(t))return i(t.message);let n=od.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`);let o=es();try{return Ae.writeToFile(o,JSON.stringify(n.data,null,2)+`
51
+ `),c("Config written",null)}catch{return i(`Unable to write ~/${Te}/config.json`)}},ot=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=ts();if(a(t))return i(`Unable to create ~/${Te}`);if(!(Ae.readFile(e)!==null)){let g=id(_m);if(a(g))throw new Error(`Unable to create ~/${Te}/config.json`)}let o=sd();if(a(o))throw new Error(o.message||"Unable to load settings");let{preferredEditor:r,userName:s,userId:d,autoSync:l,autoSyncDebounceMs:u,logLevel:m}=o.value;return!s||!d?i(`User name or ID not configured in ~/${Te}/config.json`):(process.env.EPIQ_LOG_LEVEL=m,c("successfully loaded settings",{logLevel:m??"debug",preferredEditor:r??"",userName:s,userId:d,autoSync:l??!1,autoSyncIntervalMs:u??1e4,viewMode:"dense"}))}});var ns,os=y(()=>{"use strict";ns=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 aE}from"react";var rs,Wm,Hm,sn,Vm,pt,Vo=y(()=>{"use strict";b();Wm=new Set,Hm=()=>{for(let e of Wm)e()},sn=()=>{if(!rs)throw new Error("Ui state not initialized. Call initUiState() first.");return rs},Vm=e=>{let t=sn();return rs=e(t),Hm(),c("UX state updated",null)},pt=e=>Vm(t=>({...t,...e}))});import{spawn as zm}from"node:child_process";function ss(e){let t=process.platform,r=zm(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 dd=y(()=>{"use strict"});import{spawnSync as qm}from"node:child_process";import Gm from"node:os";import cd from"node:path";import{ulid as Km}from"ulid";function Ym(){let{preferredEditor:e}=Q(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Xm(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function ld(e){let t=cd.join(Gm.tmpdir(),"epiq");Ae.mkDir(t);let n=cd.join(t,Km());Ae.writeToFile(n,e??"");let o=Ym();for(let r of o){let s=Xm(r,n),d=qm(s,{stdio:"inherit",shell:!0});if(!d.error&&d.status===0){let l=Ae.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 ud=y(()=>{"use strict";b();he();Zr()});import{ulid as is}from"ulid";var md,Jm,Qm,pd=y(()=>{"use strict";ud();Rt();Fe();Yt();te();b();$t();ie();w();ce();Kt();md=async e=>{let{contextNode:t,selectedIndex:n}=p(),o=q(t.id)[n];if(o&&hn(o))return Jm(e);if(e.modifier===ze.DESCRIPTION)return Qm();if(e.modifier===ze.TITLE){let r=X();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 Oe();return a(l)?l:j([{id:is(),action:"edit.title",payload:{id:s.id,name:d},...r.value}],l.value)}return i("Unknown edit command")},Jm=async e=>{let t=X();if(a(t))return i("Unable to resolve user ID");let{contextNode:n,selectedIndex:o}=p(),r=q(n.id)[o];if(!r||!hn(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=p().nodes[s];if(!d||!D(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=I.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 g=await Oe();if(a(g))return g;let x=g.value;return j([{id:is(),action:"edit.issue.comment",payload:{id:u.id,issue:d.id,md:m},...t.value}],x)},Qm=async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let t=await Oe();if(a(t))return t;let n=t.value,{breadCrumb:o,selectedNode:r}=p(),s=ke([...o,r],"TICKET");if(a(s))return i("Edit target must be an issue");let d=s.value;if(!D(d))return i("Edit target must be an issue");if(d.readonly)return i("Cannot edit readonly issue");let l=q(d.id).find(x=>x.title===ne.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=ld(u);if(a(m))return i("Failed to edit field");let g=m.value;return g===u?c("No changes made",null):j([{id:is(),action:"edit.description",payload:{id:d.id,md:g},...e.value}],n)}});import as from"node:fs";import Zm from"node:path";var gd,fd=y(()=>{"use strict";b();un();gd=async e=>{let t=Zm.join(e,".gitignore"),n=as.existsSync(t)?as.readFileSync(t,"utf8"):"",o=[".epiq/events/",".epiq/log/"],r=n.split(`
52
+ `).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(`
33
53
  `);return n=n.trimEnd()+`
34
54
 
35
55
  ${l}
36
- `,_o.writeFileSync(t,n,"utf8"),le.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)}});import qt from"node:fs";import hn from"node:path";var Ba,Ua,nm,$o,rm,om,im,Wo,sm,am,Ar,_a,En,$a,jo=y(()=>{"use strict";C();Fn();On();Un();Pt();Tt();Ba=async e=>{if((await Re({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);le.info("Creating initial commit");let n=await K.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return a(n)?s(n.message):c("Created initial commit",!0)},Ua=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",nm=async e=>{let t=await Wn(e);if(a(t))return s(t.message);let n=await Ti(e);return a(n)?s(n.message):c("Built sync commit message",`[sync|branch:${Ua(t.value)}:sha:${Ua(n.value)}]`)},$o=async({repoRoot:e,stateBranchName:t})=>{le.info(`Creating ${t}`);let n=await _({args:["commit-tree",Oi,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return s(`Failed to create state branch commit
37
- ${n.message}`);let r=n.value.stdout.trim(),o=await _({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return a(o)?s(`Failed to create ${t}
38
- ${o.message}`):c("Created state branch",!0)},rm=async({repoRoot:e,stateBranchName:t})=>{let n=await Yr({repoRoot:e});if(a(n))return s(`Ensure local state branch failed
39
- `+n.message);let r=n.value,o=r?await nn({repoRoot:e,branch:t}):c("No remote, no remote state branch",!1);if(a(o))return s(`Ensure local state branch failed
40
- `+o.message);let i=o.value;if(r&&i){let l=await K.fetch({cwd:e,remote:pe,branch:t});if(a(l))return s(`Failed to fetch ${t} from remote
41
- ${l.message}`)}let d=await $n({repoRoot:e,branch:t});if(a(d))return s(`Ensure local state branch failed
42
- `+d.message);if(d.value)return c("Local state branch already exists",!1);if(i){let l=await _({args:["branch","--track",t,`${pe}/${t}`],cwd:e});return a(l)?s(`Failed to create local ${t} from remote
43
- ${l.message}`):c("Created local state branch from remote",!0)}return $o({repoRoot:e,stateBranchName:t})},om=async({repoRoot:e,branch:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return s(n.message);let r=n.value.stdout.split(`
44
- `),o=null;for(let i of r){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return c("Found worktree for branch",o)}return c("No worktree found for branch",null)},im=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=rn(hn.dirname(t));if(a(r))return s(`Failed to create state branch worktree
45
- `+r.message);qt.existsSync(t)&&!qt.existsSync(hn.join(t,".git"))&&(le.info("Removing broken state branch worktree path"),Bi(t)),le.info("Creating state branch worktree");let o=await K.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(o)?s(`Failed to create state branch worktree
46
- ${o.message}`):c("Created state branch worktree",!0)},Wo=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await om({repoRoot:e,branch:n});if(a(r))return s(r.message);let o=hn.resolve(t),i=r.value?hn.resolve(r.value):null;if(i&&i===o&&qt.existsSync(i))return c("State branch already checked out in expected worktree",!1);if(i&&i!==o){le.info("Moving state branch worktree to expected location");let u=await K.worktreeRemove({cwd:e,worktreeRoot:i});if(a(u))return s(`Failed to remove existing state branch worktree
47
- ${u.message}`)}if(i&&!qt.existsSync(i)){le.info("Pruning stale state branch worktree");let u=await K.worktreePrune({cwd:e});if(a(u))return s(`Failed to prune stale worktrees
48
- ${u.message}`)}let d=await wi({repoRoot:e,worktreeRoot:t});if(a(d))return s(d.message);let l=qt.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 K.worktreePrune({cwd:e});if(a(u))return s(`Failed to prune stale worktrees
49
- ${u.message}`)}return im({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},sm=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Wn(e);if(a(n))return s(n.message);if(n.value===t)return c("State branch already checked out",!1);(await Re({cwd:e,args:["rebase","--abort"]})).exitCode===0&&le.info("Aborted stale state branch rebase");let o=await K.checkout({cwd:e,branch:t});return a(o)?s(`Failed to checkout ${t}
50
- ${o.message}`):c("Checked out state branch",!0)},am=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Xr(t);if(a(n))return s(n.message);if(n.value)return c("State branch upstream already configured",!1);let r=await Yr({repoRoot:t});if(a(r))return s(r.message);if(!r.value)return c("No remote available for state branch upstream",!1);let o=ut(e);if(a(o))return o;let i=o.value,d=await nn({repoRoot:t,branch:i});if(a(d))return s(d.message);if(!d.value)return c("Remote state branch missing; upstream will be configured on first push",!1);le.info(`Configuring ${i} upstream`);let l=await K.fetch({cwd:t,remote:pe,branch:i});if(a(l))return s(`Failed to fetch ${i}
51
- ${l.message}`);let u=await K.setUpstream({cwd:t,branch:i,upstream:`${pe}/${i}`});return a(u)?s(`Failed to set state branch upstream
52
- ${u.message}`):c("Configured state branch upstream",!0)},Ar=async({stateBranchRoot:e,eventFileName:t})=>{let n=on(t),r=hn.join(e,n);if(!qt.existsSync(r))return c("No event file to stage",void 0);let o=await K.stage({cwd:e,pathspec:[n]});return a(o)?s(`Failed to stage state branch event file
53
- ${o.message}`):c("Staged state branch event file",void 0)},_a=async({repoRoot:e,stateBranchRoot:t})=>{let n=await nm(e);return a(n)?s(`Create state branch sync commit failed
54
- `+n.message):Mt({cwd:t,message:n.value})},En=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Xr(t);if(a(n))return s(n.message);let r=ut(e);if(a(r))return r;let o=r.value,i=n.value?await K.push({cwd:t}):await K.push({cwd:t,remote:pe,branch:o,setUpstream:!0});return a(i)?s(`Failed during state branch push
55
- ${i.message}`):c("Pushed state branch",!0)},$a=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=ut(e);if(a(o))return o;let i=o.value,d=[Hn(),await rm({repoRoot:e,stateBranchName:i}),await Wo({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await sm({stateBranchRoot:t,stateBranchName:i}),await $i(t),n?await am({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of d){if(a(l))return s(l.message);r=r||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)}});import{monotonicFactory as dm,ulid as Xe}from"ulid";function cm(){let e=Fe();if(a(e))return s("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(i=>i.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 i=t.renderedChildrenIndex?.[o.id]??[];return c("Resolved boot nav target",{contextNode:o,selectedIndex:i.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 lm(){let e=cm();return a(e)?e:L.navigate(e.value)}function Wa({userId:e,userName:t}){let n=Nn(),r=Nn(),o=Nn(),i=Nn(),d=Nn(),l=me(void 0,void 0);if(a(l))return l;let u=me(void 0,void 0);if(a(u))return u;let m=me(u.value,void 0);if(a(m))return m;let g=me(void 0,void 0);if(a(g))return g;let x=me(g.value,void 0);if(a(x))return x;let b=me(x.value,void 0);if(a(b))return b;let R=me(void 0,void 0);return a(R)?R:c("Created default events",[{id:Xe(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:Xe(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Xe(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:g.value}},{id:Xe(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"In progress",parent:r,rank:x.value}},{id:Xe(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:r,rank:b.value}},{id:Xe(),userId:e,userName:t,action:"add.board",payload:{id:Sr,name:"Closed",parent:n,rank:m.value}},{id:Xe(),userId:e,userName:t,action:"add.swimlane",payload:{id:ue,name:"Closed",parent:Sr,rank:R.value}},{id:Xe(),userId:e,userName:t,action:"lock.node",payload:{id:Sr}},{id:Xe(),userId:e,userName:t,action:"lock.node",payload:{id:ue}}])}function wr(e){if(!e.length){let r=ve.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=In(r);return a(o)?o:(E({hasProjectDefinition:!1,mode:p.DEFAULT}),c("Booted uninitialized workspace placeholder",null))}if(!e.some(r=>r.action==="init.workspace"))return s("Initialized Epiq project has no workspace init event");let n=Nt(e).filter(a);return n.length>0?s(`Materializing failed:
56
- ${n.map(r=>r.message).join(`
57
- `)}`):(lm(),E({hasProjectDefinition:!0}),c("State booted successfully",null))}var Nn,Tr=y(()=>{"use strict";Te();G();C();gn();T();At();Kt();xn();Nn=dm()});import um from"node:fs";import ja from"node:path";var mm,V,Ha,za=y(()=>{"use strict";Oa();On();Pt();Tt();jo();Te();cn();Tr();Kt();Me();G();C();wt();ie();ge();T();re();mm=async e=>{let t=await _({cwd:e,args:["status","--porcelain"]});return a(t)?t:c("Checked git diff",t.value.stdout.trim().length>0)},V=(e,t)=>s(`[${e}] ${t}`),Ha=async()=>{W("");let e=xi(),t=await nt(process.cwd());if(a(t))return V(1,t.message);let n=t.value,r=await _n(n);if(a(r))return V(2,r.message);if(r.value)return V(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await mm(n);if(a(o))return V(2.5,o.message);if(o.value)return V(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(Zr(n))return V(4,"Epiq project already initialized");let i=Jn();if(!i.isSetupDone||!i.userName)return V(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let d=Y(),l=d.userName,u=d.userId;if(!u||!l)return V(5,"Missing Epiq user id");let m=e.stateBranch,g=await $n({repoRoot:n,branch:m});if(a(g))return V(6,g.message);if(g.value)return V(6,`State branch already exists: ${m}`);let x=await $o({repoRoot:n,stateBranchName:m});if(a(x))return V(6,x.message);let b=Hn();if(a(b))return V(7,b.message);let R=ja.join(jn(),e.projectId),I=await Wo({repoRoot:n,stateBranchRoot:R,stateBranchName:m});if(a(I))return V(8,I.message);let k=ja.join(R,".epiq");um.mkdirSync(k,{recursive:!0});let A=Wa({userId:u,userName:l});if(a(A))return V(9,A.message);for(let Wr of A.value){let mi=Cr({event:Wr,rootDir:R});if(a(mi))return V(9,mi.message)}let U=await Ar({stateBranchRoot:R,eventFileName:ht({userId:u,userName:l})});if(a(U))return V(10,U.message);let j=await Mt({cwd:R,message:"[epiq:init]"});if(a(j))return V(10,j.message);let lt=await Da(n);if(a(lt))return V(11,lt.message);let Je=Ei({repoRoot:n,fileContents:e});if(a(Je))return V(12,Je.message);let si=await K.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(si))return V(13,si.message);let ai=await K.commit({cwd:n,message:"[epiq:init-project]"});if(a(ai))return V(13,ai.message);let _r="Project initialized!",di=await _({cwd:n,args:["push","-u","origin","HEAD"]});a(di)&&(_r+=` Warn: [init:14] ${di.message}`);let ci=await En({repoRoot:n,stateBranchRoot:R});a(ci)&&(_r+=` Warn: [init:15] ${ci.message}`);let li=Nt(A.value).filter(a);if(li.length>0)return V(16,li.map(Wr=>Wr.message).join(`
58
- `));let $r=Fe();if(a($r))return V(16,$r.message);let{rootNodeId:Tc,nodes:Mc}=$r.value,ui=Mc[Tc];return ui?(L.navigate({contextNode:ui,selectedIndex:0}),E({hasProjectDefinition:!0,mode:p.DEFAULT}),c(_r,null)):V(16,"Unable to resolve initialized root node")}});import{ulid as pm}from"ulid";function zo(e){let t=qa();if(a(t))return t;let{contextNode:n,nodes:r}=v();if(!n.parentNodeId)return s("Missing parent node id");let o=r[n.parentNodeId];if(!o)return s("Missing parent node");let i=H(o.id),d=i.findIndex(({id:m})=>m===n.id);if(d<0)return s("Current node not found among siblings");let l=i[d+e];if(!l)return s("Missing sibling node");let u=Ka({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Ga(u.value)}function Vo(e){let t=qa();if(a(t))return t;let{contextNode:n,selectedIndex:r}=v(),i=H(n.id)[r+e];if(!i)return s("Missing sibling node");let d=Ka({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return a(d)?d:Ga(d.value)}var Va,dt,bn,qa,Ho,Ka,Ga,qo=y(()=>{"use strict";Kt();Me();C();Se();T();Va=null,dt=()=>structuredClone(Va),bn=e=>{Va=e},qa=()=>{let{contextNode:e,selectedIndex:t}=v(),r=H(e.id)[t];return r?c("Resolved selected child",r):s("Target node not found")},Ho=({id:e,parentId:t,position:n={at:"end"}})=>{let r=H(t).filter(o=>o.id!==e);return Mr(r,n)},Ka=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Q();if(a(r))return s("Unable to resolve user ID");let o=Ho({parentId:t,id:e,position:n});return a(o)?o:c("Created pending move state",{id:pm(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Ga=e=>{bn(e);let t=Cn(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as gm}from"ulid";var Ya,Lr,Xa,Ja=y(()=>{"use strict";Te();qo();Et();Me();G();C();Se();ie();T();re();Ya=()=>{let e=dt();if(!e)return s("No pending move state");let t=e.payload.id,n=e.payload.parent,r=v().nodes[n];if(!r)return s("Move parent not found");let o=H(n).findIndex(i=>i.id===t);return o===-1?s("Moved node not found among rendered children"):(L.navigate({contextNode:r,selectedIndex:o}),c("Synchronized navigation to moved node",null))},Lr=(e,t="Moved preview")=>{if(a(e))return e;let n=Ya();return a(n)?n:(E({mode:p.MOVE}),c(t,null))},Xa=async()=>{let e=Q();if(a(e))return s("Unable to resolve user ID");let{modifier:t}=J().commandMeta,{contextNode:n,selectedIndex:r}=v(),o=H(n.id)[r];if(!o)return E({mode:p.DEFAULT}),s("No move target");if(t==="start"){if(o.readonly)return s("Target node is read-only");if(r===-1)return s("No item selected");if(!o.parentNodeId)return s("Target has no parent");let i=H(o.parentNodeId),d=i.findIndex(({id:x})=>x===o.id);if(d===-1)return s("Target not found among siblings");let l=i[d-1],u=i[d+1],m=u!=null?{at:"before",sibling:u.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},g=Ho({parentId:o.parentNodeId,id:o.id,position:m});return a(g)?g:(bn({id:gm(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:g.value.rank},...e.value}),E({mode:p.MOVE}),c("Move initialized",null))}if(t==="next")return Lr(Vo(1));if(t==="previous")return Lr(Vo(-1));if(t==="to-next")return Lr(zo(1));if(t==="to-previous")return Lr(zo(-1));if(t==="confirm"){let i=dt();if(!i)return s("No pending move to confirm");let d=await Ae();if(a(d))return d;let l=Le(i,d.value);if(a(l))return l;let u=Ya();return a(u)?u:(bn(null),E({mode:p.DEFAULT}),c("Moved item",null))}return t==="cancel"?(bn(null),E({mode:p.DEFAULT}),c("Cancelling move",null)):s("Invalid move modifier")}});import{monotonicFactory as fm,ulid as vm}from"ulid";var ym,Pr,Ko=y(()=>{"use strict";C();ym=fm(),Pr=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=ym();return c("Created issue events",[{id:vm(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}}])}});import{ulid as kr}from"ulid";var Qa,Za=y(()=>{"use strict";Te();Ko();Et();Me();un();C();ae();Se();T();re();Qa=async(e,t)=>{let n=Q();if(a(n))return s("Unable to resolve user ID");let r=await Ae();if(a(r))return r;let o=r.value;if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:i,contextNode:d,selectedIndex:l}=v(),u=m=>{let g=Le(m,o);if(a(g))return g;let x=N.getNode(g.value.result.id);if(!x)return s("Created node not found");if(!x.parentNodeId)return g;let b=N.getNode(x.parentNodeId);return b?(L.navigate({contextNode:b,selectedIndex:N.getSiblings(x.parentNodeId).findIndex(({id:R})=>R===x.id)}),g):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=v(),g=N.getNode(m);if(!g)return s("Workspace not found");let x=Gt(g.id,n.value,o);return a(x)?x:u({id:kr(),action:"add.board",payload:{id:kr(),name:t.inputString,parent:g.id,rank:x.value},...n.value})}if(t.modifier==="swimlane"){let m=De(i,"BOARD");if(a(m))return s("Unable to add swimlane in this context");let g=Gt(m.value.id,n.value,o);return a(g)?g:u({id:kr(),action:"add.swimlane",payload:{id:kr(),name:t.inputString,parent:m.value.id,rank:g.value},...n.value})}if(t.modifier==="issue"){let m=q(d.id)[l],g=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let j=De(i,"SWIMLANE");return a(j)?null:j.value})();if(!g)return s("Unable to add issue in this context");let x=Gt(g.id,n.value,o);if(a(x))return x;let b=Pr({name:t.inputString,parent:g.id,rank:x.value,user:n.value});if(a(b))return b;let R=b.value,I=It(R,o);if(I.some(j=>a(j)))return s("Issue create failed: "+I.filter(a).map(j=>j.message).filter(Boolean).join(", "));let k=I[0];if(!k||a(k))return s("Issue creation failed");let U=R.find(j=>j.action==="add.issue")?.payload.id;return U?(L.navigate({contextNode:g,selectedIndex:N.getSiblings(g.id).findIndex(({id:j})=>j===U)}),c("Issue created",null)):s("Unable to determine ticket id")}return c("Success",null)}});var ed,td=y(()=>{"use strict";Pt();Te();ir();vn();Kt();G();un();C();ie();T();rr();ed=async()=>{let e=De(v().breadCrumb,"BOARD");if(a(e))return e;let t=await nt(process.cwd());if(a(t))return s("Unable to locate repo root");let n=Lt({repoRoot:t.value});if(a(n))throw new Error(n.message);let{modifier:r}=J().commandMeta;if(r==="now"){let I=zt(n.value);if(a(I))return s(I.message);let k=Sn();if(a(k))return k;let U=Nt(I.value).filter(a);return U.length>0?s(U.map(j=>j.message).join(", ")):(E({mode:p.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}let o;if(r==="prev"){let I=v().eventLog.at(-1),k=ao(I);if(k===null)return s("No previous event to peek");o=k}else if(r==="next"){let I=v().unappliedEvents.at(0),k=ao(I);if(k===null)return s("No next event to peek");o=k+1}else{let I=nr(r);if(!I)return s("Invalid peek date");o=I.getTime()}let i=v(),d=e.value.id,l=Na(n.value,o);if(a(l))return s(l.message);let{appliedEvents:u,unappliedEvents:m}=l.value,g=Sn();if(a(g))return g;let b=Nt(u).filter(a);if(b.length>0)return Sn(),E(i),s(b.map(I=>I.message).join(", "));let R=v().nodes[d];return R?(L.navigate({contextNode:R,selectedIndex:0}),E({mode:p.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:m}),c("Peeking",!0)):(Sn(),E(i),s("Board did not exist at peek date"))}});import xm from"zod";var nd,rd=y(()=>{"use strict";Ht();G();C();ie();ge();T();nd=()=>{let e=J().commandMeta.inputString,t=xm.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return s("Auto sync duration must be a number of at least 3000 ms");let n=Ye({autoSyncDebounceMs:t.data});return a(n)?n:(ke({autoSyncIntervalMs:t.data}),E({mode:p.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))}});var od,id=y(()=>{"use strict";cn();Ht();G();C();ie();ge();T();od=()=>{let e=J().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return s("Invalid response");let t=os(e),n=Ye({autoSync:t});return a(n)?n:(ke({autoSync:t}),E({mode:p.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var sd,ad=y(()=>{"use strict";Ht();G();C();ie();ge();T();sd=()=>{let e=J().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return s("Invalid response");let n=Ye({logLevel:e});return a(n)?n:(ke({logLevel:e}),E({mode:p.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var dd,cd=y(()=>{"use strict";Xn();G();C();ie();T();dd=async()=>{W(""),E({mode:p.DEFAULT});let e=Fe();if(a(e))return s(e.message);if(e.value.syncStatus.status==="syncing")return s("Sync already in progress");E({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await qe();return a(t)?(E({syncStatus:{msg:t.message,status:"failed"}}),t):(E({mode:p.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as ye}from"ulid";var ld,ud,md,pd=y(()=>{"use strict";ca();Te();Ht();Et();Me();wa();xn();G();Z();C();ae();Se();ie();ge();T();Rr();re();Ta();gt();yo();ln();Fa();za();Ja();Za();td();rd();id();ad();cd();ld=e=>Object.values(v().tags).find(t=>t.name===e),ud=e=>Object.values(v().contributors).find(t=>t.name===e),md=[{systemOnly:!0,intent:M.Move,description:"Internal move-state command",mode:p.COMMAND_LINE,action:Xa},{intent:M.Delete,description:"Delete the currently selected node",mode:p.COMMAND_LINE,action:async()=>{let e=Q();if(a(e))return s("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=q(t.id)[n];return r?Ie({id:ye(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>E({mode:p.DEFAULT})},{intent:M.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:p.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=J().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(d=>oe(f.FILTER).map(l=>l.split(n)[0]).includes(d))(r))return s("Invalid filter modifier");let i={target:r,operator:"=",value:t.trim()};return be(d=>({...d,filters:e==="clear"?[]:[...d.filters,i],mode:p.DEFAULT})),c("Filter updated",null)}},{intent:M.ViewHelp,description:"Open the help screen",mode:p.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return at({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),E({mode:p.HELP}),c("Viewing help",null)}},{intent:M.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:p.COMMAND_LINE,action:async()=>{let e=Q();if(a(e))return s("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=q(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!B(r))return s("Cannot close in this context");let o=v().nodes[ue];if(!o)return s("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return s("Issue is already closed");let i=await Ae();if(a(i))return i;let d=i.value,l=Xt(o.id,r.id,{at:"end"},e.value,d);if(a(l))return l;let u=await Ie({id:ye(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...e.value});return a(u)?u:c("Issue closed",null)},onSuccess:()=>E({mode:p.DEFAULT})},{intent:M.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:p.COMMAND_LINE,action:async()=>{let e=Q();if(a(e))return s("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=q(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):Yt(r.id,"TICKET");if(a(o))return s("Cannot reopen in this context");let i=o.value,d=v().nodes[ue];if(!d)return s("Unable to locate closed swimlane");if(i.parentNodeId!==d.id)return s("Issue is not closed");if(!B(i))return s("Target node is not issue");let l=Aa(i);if(!l)return s("Unable to resolve previous parent from issue history");if(l===d.id)return s("Previous parent resolves to closed swimlane");let u=v().nodes[l];if(!u)return s("Previous parent no longer exists");let m=await Ae();if(a(m))return m;let g=m.value,x=Xt(u.id,i.id,{at:"end"},e.value,g);if(a(x))return x;let b=await Ie({id:ye(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:x.value},...e.value});return a(b)?b:c("Issue reopened",null)},onSuccess:()=>E({mode:p.DEFAULT})},{intent:M.Init,description:"Initialize Epiq in the current git repository",mode:p.COMMAND_LINE,action:Ha},{intent:M.NewItem,description:"Create a new board, swimlane, or issue",mode:p.COMMAND_LINE,action:Qa,onSuccess:()=>E({mode:p.DEFAULT})},{intent:M.Rename,description:"itle] Rename the currently selected node",mode:p.COMMAND_LINE,action:async()=>{let e=Q();if(a(e))return s("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=q(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=Bs();return o?Ie({id:ye(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a title")},onSuccess:()=>E({mode:p.DEFAULT})},{intent:M.UntagTicket,description:"Remove a tag from the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=Q();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=J().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=ld(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid untag target");let d=Yt(i.id,"TICKET");if(a(d))return s("Unable to untag issue in this context");let l=d.value;return B(l)?(l.props.tags??[]).includes(o.id)?Ie({id:ye(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...e.value}):s("Issue is not tagged with that tag"):s("Target node is not issue")},onSuccess:()=>E({mode:p.DEFAULT})},{intent:M.TagTicket,description:"Add or create a tag on the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=Q();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=J().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedNode:o}=v();if(!o)return s("Invalid tag target");let i=Yt(o.id,"TICKET");if(a(i))return s("Unable to tag issue in this context");let d=i.value;if(!B(d))return s("Target node is not issue");let l=ld(r),u;if(l)u=l.id;else{let g=ye(),x=await Ie({id:ye(),action:"create.tag",payload:{id:g,name:r},...e.value});if(a(x))return x;u=x.value.result.id}return(d.props.tags??[]).includes(u)?s("Already tagged with that tag"):Ie({id:ye(),action:"add.issue.tag",payload:{id:d.id,tag:u},...e.value})},onSuccess:()=>E({mode:p.DEFAULT})},{intent:M.AssignUserToTicket,description:"Assign a user to the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=Q();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=J().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,contextNode:i}=v(),d=q(i.id)[o];if(!d)return s("Invalid assign target");let l=Yt(d.id,"TICKET");if(a(l))return s("Unable to assign issue in this context");let u=l.value;if(!B(u))return s("Target node is not issue");let m=ud(r),g;if(m)g=m.id;else{let b=ye(),R=await Ie({id:ye(),action:"create.contributor",payload:{id:b,name:r},...e.value});if(a(R))return R;g=R.value.result.id}return(u.props.assignees??[]).includes(g)?s("Assignee already assigned"):Ie({id:ye(),action:"add.issue.assignee",payload:{id:u.id,assignee:g},...e.value})},onSuccess:()=>E({mode:p.DEFAULT})},{intent:M.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=Q();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=J().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=ud(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid unassign target");let d=Yt(i.id,"TICKET");if(a(d))return s("Unable to unassign in this context");let l=d.value;return B(l)?(l.props.assignees??[]).includes(o.id)?Ie({id:ye(),action:"remove.issue.assignee",payload:{id:l.id,assignee:o.id},...e.value}):s(`Issue is not assigned to "${r}"`):s("Target node is not issue")},onSuccess:()=>E({mode:p.DEFAULT})},{intent:M.Sync,description:"Pull, commit, and push Epiq state",mode:p.COMMAND_LINE,action:dd},{intent:M.Peek,description:"View board state at another point in time",mode:p.COMMAND_LINE,action:ed},{intent:M.Export,description:"Export the current board layout to markdown",mode:p.COMMAND_LINE,action:async()=>{let e=await da();return a(e)?e:(E({mode:p.DEFAULT}),c("Export successful",!0))}},{intent:M.Exit,description:"Exit the application",mode:p.COMMAND_LINE,action:async()=>(L.exit(),c("Exit successful",!0))},{intent:M.Edit,description:"Edit title or description",mode:p.COMMAND_LINE,action:async(e,t)=>{if(t.modifier===rt.DESCRIPTION)return ka();if(t.modifier===rt.TITLE){let n=Q();if(a(n))return s("Unable to resolve user ID");let{contextNode:r,selectedIndex:o}=v(),i=q(r.id)[o];if(!i)return s("Missing node");if(i.readonly)return s("Cannot rename readonly node");let d=t.inputString.trim();return d?Ie({id:ye(),action:"edit.title",payload:{id:i.id,name:d},...n.value}):s("Provide a title")}return s("Unknown edit command")},onSuccess:()=>E({mode:p.DEFAULT})},{intent:M.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:p.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case X.USERNAME:{let{userId:r,preferredEditor:o,userName:i}=Y(),d=n||i,l=r??ye();if(!d||!l)return s("Unable to resolve user name or id");let u=Ye({userName:d,userId:l,preferredEditor:o??""});return a(u)?u:(ke({userName:d,userId:l}),E({mode:p.DEFAULT}),c(`Username set to "${d}"`,null))}case X.EDITOR:{if(!n)return s("No editor provided");let r=Ye({preferredEditor:n});return a(r)?r:(ke({preferredEditor:n}),E({mode:p.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case X.VIEW:return n!=="wide"&&n!=="dense"?s("Invalid view mode"):(ke({viewMode:n}),c(`View set to "${n}"`,null));case X.AUTOSYNC:return od();case X.LOG_LEVEL:return sd();case X.SYNC_DEBOUNCE_MS:return nd();default:return s("Unknown config command")}}},{intent:M.Coffee,description:"Sponsor the development of Epiq!",mode:p.COMMAND_LINE,action:()=>{let e=J().commandMeta.modifier;return e==="custom"?Bo("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):Bo(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),W(""),c("Thanks you!",null)}}]});var hm,$e,Go=y(()=>{"use strict";Yn();dr();yo();pd();C();ie();ge();T();hm=new Set(["peek","filter","view-help"]),$e=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=J();if(!t)return s("No command to confirm");if(!e&&n===yt.Invalid)return s("Invalid command");let i=_s(t);Fs();let{readOnly:d}=v();if(d&&!hm.has(i))return pn({status:Qe.Fail,message:"Command not available in readonly state",value:null});let l=md.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===i);if(!l)return pn({status:Qe.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return pn({status:Qe.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?pn(u):(Ds({addToHistory:!e}),l.onSuccess?.(),Y().autoSync&&ts(),u)}});var Fr,Dr,gd,fd=y(()=>{"use strict";C();G();T();mt();Go();qo();ie();Fr=[{intent:S.Exit,mode:p.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:p.COMMAND_LINE}),W("move cancel"),$e({isForceExecutedBySystem:!0}))},{intent:S.InitMove,mode:p.DEFAULT,description:"[m] move (init/confirm)",action:()=>(E({mode:p.COMMAND_LINE}),W("move start"),$e({isForceExecutedBySystem:!0}))},{intent:S.ConfirmMove,mode:p.MOVE,action:()=>(E({mode:p.COMMAND_LINE}),W("move confirm"),$e({isForceExecutedBySystem:!0}))}],Dr=[{intent:S.MovePreviousItem,mode:p.MOVE,action:()=>dt()?(E({mode:p.COMMAND_LINE}),W("move previous"),$e({isForceExecutedBySystem:!0})):s("No pending move")},{intent:S.MoveNextItem,mode:p.MOVE,action:()=>dt()?(E({mode:p.COMMAND_LINE}),W("move next"),$e({isForceExecutedBySystem:!0})):s("No pending move")}],gd=[{intent:S.MoveToNextContainer,mode:p.MOVE,action:()=>dt()?(E({mode:p.COMMAND_LINE}),W("move to-next"),$e({isForceExecutedBySystem:!0})):s("No pending move")},{intent:S.MoveToPreviousContainer,mode:p.MOVE,action:()=>dt()?(E({mode:p.COMMAND_LINE}),W("move to-previous"),$e({isForceExecutedBySystem:!0})):s("No pending move")}]});var vd,yd=y(()=>{"use strict";Z();fd();vd={[w.WORKSPACE]:[...Fr,...Dr],[w.BOARD]:[...Fr,...Dr],[w.SWIMLANE]:[...Fr,...Dr,...gd],[w.TICKET]:[],[w.FIELD]:[],[w.FIELD_LIST]:[],[w.TEXT]:[]}});var xd,hd,Ed=y(()=>{"use strict";G();C();ie();T();Rr();mt();Te();xd=()=>{W("");let{pendingNavTarget:e}=Vt();E({mode:p.DEFAULT}),e&&L.navigate(e),at({pendingNavTarget:void 0})},hd=[{intent:S.ExitCommandLine,mode:p.HELP,action:()=>(xd(),c("Exiting help",null))},{intent:S.Exit,mode:p.HELP,action:()=>(xd(),c("Closed help",null))},{intent:S.NavPreviousItem,mode:p.HELP,description:"[arrows/hjkl] navigate",action:()=>(L.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:S.NavNextItem,mode:p.HELP,action:()=>(L.navigateToNextItem(),c("Navigating to next help item",null))},{intent:S.NavToPreviousContainer,mode:p.HELP,action:()=>(L.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:S.NavToNextContainer,mode:p.HELP,action:()=>(L.navigateToNextContainer(),c("Navigating to next help container",null))}]});var Em,Nd,Id,bd=y(()=>{"use strict";G();Z();C();ie();T();Rr();mt();Te();Em=e=>{E({mode:p.COMMAND_LINE});let{pendingNavTarget:t}=Vt();t&&L.navigate(t),at({pendingNavTarget:void 0}),W(`${e} `)},Nd=()=>{W("");let{pendingNavTarget:e}=Vt();e&&L.navigate(e),at({pendingNavTarget:void 0}),E({mode:p.DEFAULT})},Id=[{intent:S.InitCommandPalette,mode:p.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{W("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return at({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),E({mode:p.PALETTE}),c("Opening command palette",null)}},{intent:S.Confirm,mode:p.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!pi(e))return s("Command only applicable on text nodes");if(e.props.disabled)return s("Command is not available in this context");let t=e.title;return t?(Em(t),c("Selected command",t)):c("No command selected",null)}},{intent:S.ExitCommandLine,mode:p.PALETTE,action:()=>(Nd(),c("Exiting palette",null))},{intent:S.Exit,mode:p.PALETTE,action:()=>(Nd(),c("Closed command palette",null))},{intent:S.NavPreviousItem,mode:p.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(L.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:S.NavNextItem,mode:p.PALETTE,action:()=>(L.navigateToNextItem(),c("Navigating to next item",null))},{intent:S.NavToPreviousContainer,mode:p.PALETTE,action:()=>(L.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:S.NavToNextContainer,mode:p.PALETTE,action:()=>(L.navigateToNextContainer(),c("Navigating to next container",null))}]});var Cd,Sd=y(()=>{"use strict";gt();G();C();kt();Se();ie();T();mt();Ed();bd();Te();Cd=[...hd,...Id,{intent:S.AddItem,mode:p.DEFAULT,description:"[n] new...",action:()=>(E({mode:p.COMMAND_LINE}),W(`${f.NEW} `),c("Adding new item",null))},{intent:S.Delete,mode:p.DEFAULT,description:"[d] delete",action:()=>(E({mode:p.COMMAND_LINE}),W(`${f.DELETE} `),c("Deleting item",null))},{intent:S.InitCommandLine,mode:p.DEFAULT,description:"[:] focus command line",action:()=>(E({mode:p.COMMAND_LINE}),W(""),c("Entering command line mode",null))},{intent:S.Confirm,mode:p.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!H(e?.id??"")?.length){if(e?.title===ee.DESCRIPTION)return E({mode:p.COMMAND_LINE}),W(`${f.EDIT} description `),c("Propose command",!0);if(e?.title===ee.ASSIGNEES)return E({mode:p.COMMAND_LINE}),W(`${f.ASSIGN} `),c("Propose command",!0);if(e?.title===ee.TAGS)return E({mode:p.COMMAND_LINE}),W(`${f.TAG} `),c("Propose command",!0);if(t.title===ee.DESCRIPTION&&e?.context==="TEXT")return E({mode:p.COMMAND_LINE}),W(`${f.EDIT} description `),c("Propose command",!0)}return L.enterChildNode(),c("Entering context",null)}},{intent:S.EditTitle,mode:p.DEFAULT,description:"[r] rename title",action:()=>(E({mode:p.COMMAND_LINE}),W(`${f.EDIT} title ${v().selectedNode?.title}`),c("Exiting context",null))},{intent:S.EditDescription,mode:p.DEFAULT,description:"[e] edit description",action:()=>(E({mode:p.COMMAND_LINE}),W(`${f.EDIT} description `),c("Exiting context",null))},{intent:S.Exit,mode:p.DEFAULT,description:"[q] exit context",action:()=>(L.enterParentNode(),c("Exiting context",null))},{intent:S.NavPreviousItem,mode:p.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(L.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:S.NavNextItem,mode:p.DEFAULT,action:()=>(L.navigateToNextItem(),c("Navigating to next item",null))},{intent:S.NavToPreviousContainer,mode:p.DEFAULT,action:()=>(L.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:S.NavToNextContainer,mode:p.DEFAULT,action:()=>(L.navigateToNextContainer(),c("Navigating to next container",null))}]});var Nm,Im,Rd,Ad=y(()=>{"use strict";ie();Nm=500,Im=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Rd=e=>{let t=Im(e);t&&ur(n=>(n+t).slice(0,Nm))}});var bm,Cm,wd,Td=y(()=>{"use strict";Ad();G();C();ie();T();mt();Go();bm=[p.COMMAND_LINE,p.PALETTE],Cm=e=>[{intent:S.MoveCursorLeft,mode:e,action:()=>(fo(-1),c("Moving cursor left",null))},{intent:S.MoveCursorRight,mode:e,action:()=>(fo(1),c("Moving cursor right",null))},{intent:S.MoveCursorLeftOfWord,mode:e,action:()=>(vo("left"),c("Moving cursor left of word",null))},{intent:S.MoveCursorRightOfWord,mode:e,action:()=>(vo("right"),c("Moving cursor right of word",null))},{intent:S.AutoCompleteCommand,mode:e,action:()=>(ur((t,{remainder:n})=>n?t+n:t),c("Auto-completing command",null))},{intent:S.CaptureInput,mode:e,action:(t,{sequence:n})=>(Rd(n??""),c("Capturing input",null))},{intent:S.EraseInput,mode:e,action:()=>(Ps(),c("Erasing input",null))},{intent:S.EraseInputWord,mode:e,action:()=>(ks(),c("Erasing input word",null))}],wd=[{intent:S.Confirm,mode:p.COMMAND_LINE,action:()=>($e(),c("Executing command",null))},{intent:S.ViewHelp,mode:p.DEFAULT,action:()=>(E({mode:p.HELP}),c("Viewing help",null))},...bm.flatMap(Cm),{intent:S.ExitCommandLine,mode:p.COMMAND_LINE,action:()=>(E({mode:p.DEFAULT}),c("Exiting command line",null))},{intent:S.GetLastCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(Os(),c("Getting last command from history",null))},{intent:S.GetNextCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(Us(),c("Getting next command from history",null))}]});import Pd from"chalk";var Or,Md,Ld,Yo,kd=y(()=>{"use strict";G();Z();xe();Or=Pd.dim.hex(P.secondary2)(": for command line"),Md="q to exit",Ld=`${Pd.hex(P.accent)("m")} to confirm`,Yo={[w.WORKSPACE]:[Or],[w.BOARD]:[Or],[w.BOARD+p.COMMAND_LINE]:[Or],[w.SWIMLANE]:[Or],[w.TICKET+p.HELP]:[Md],[w.SWIMLANE+p.HELP]:[Md],[w.TICKET]:[],[w.FIELD]:[],[w.SWIMLANE+p.MOVE]:[Ld],[w.TICKET+p.MOVE]:[Ld]}});var Rn,Sm,Rm,Fd,Dd=y(()=>{"use strict";T();Rn=e=>e.trim().toLocaleLowerCase(),Sm=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Rm=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},Fd=(e,t)=>{let n=Rn(t.value);if(!n)return!0;switch(t.target){case"title":return Rn(e.title??"").includes(n);case"description":return Rn(e.props.description??"").includes(n);case"tag":return Sm(e).map(Rn).some(o=>o.includes(n));case"assignee":return Rm(e).map(Rn).some(o=>o.includes(n));default:return!0}}});function Od(e,t,n){let r=t[e];if(!r)return s("buildBreadCrumb(): current node not found");let o=[],i=r;for(;i&&(o.push(i),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let d=o[o.length-1];return!d||d.id!==n?s("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var Ud=y(()=>{"use strict";C()});var Bd,_d=y(()=>{"use strict";Bd=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 Am}from"react";function Wd(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return s("derive(): contextNodeId is missing");if(!r)return s("derive(): rootNode is missing");if(!o[r])return s("derive(): unable to find root node");let l=o[t];if(!l)return s("Unable to derive state, contextNode not found");let u=Od(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:g}=l,x=Yo[g+n]??Yo[g]??[],b=[...Cd,...vd[g]??[],...wd],R=Bd(b),I=Tm(o,i),k=I[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:x,availableActions:b,actionIndex:R,selectedNode:k,renderedChildrenIndex:I})}function In(e){Xo=e;let t=tt(process.cwd()),n=!1;if(!a(t)){let i=et(t.value);if(a(i))return s(i.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:p.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1},o=Wd(r);return a(o)?o:(bt=o.value,$d(),c("State initialized",null))}function be(e){let t=v(),n=e(t),r=Wd(n);return a(r)?s(r.message??"Unable to update state"):(bt=r.value,$d(),c("State updated",null))}var bt,Xo,Jo,$d,wm,v,Fe,E,Be,Tm,q,Sn,Ot,T=y(()=>{"use strict";yd();Sd();Td();kd();wt();G();Z();C();re();Dd();Ud();_d();Jo=new Set,$d=()=>{for(let e of Jo)e()},wm=e=>(Jo.add(e),()=>Jo.delete(e));v=()=>{if(!bt)throw new Error("State not initialized. Call initWorkspaceState() first.");return bt},Fe=()=>bt?c("Retrieved state",bt):s("State not initialized. Call initWorkspaceState() first.");E=e=>be(t=>({...t,...e})),Be=()=>Am(wm,v,v),Tm=(e,t)=>{let n={};for(let r of Object.values(e))B(r)&&t.length>0&&!t.every(o=>Fd(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,i)=>{let d=e[o.id],l=e[i.id];return!d||!l?0:d.rank.localeCompare(l.rank)});return n},q=e=>v()?.renderedChildrenIndex[e]??[],Sn=()=>Xo?In(Xo):s("Cannot reset state: no initial workspace found"),Ot=()=>bt!==void 0});var Yt,Mm,Ct,N,ae=y(()=>{"use strict";Z();C();T();Se();Yt=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return s("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 s(`No ancestor found for context: ${t}`)},Mm=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Ct=(e,t)=>e?e.readonly?s({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:s("Node not found"),N={deleteNode(e){be(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return s("Edit target node not found");let o=Ct(r,"edit");if(o)return o;let i={...r,props:{...r.props,description:t}};return this.updateNode(i),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return s("Rename target node not found");let r=Ct(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return H(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let d=Ct(o,"move");if(d)return d;if(Mm(t,e))return s("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}=v(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,d=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let g of H(m.id))d(g.id)}};d(e);let l={...structuredClone(t)};for(let u of i){if(!l[u])return s("Unable to locate node to delete");l[u]={...l[u],isDeleted:!0}}return n?(E({nodes:l}),c("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=be(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?s("Unable to create contributor"):c("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return s("Unable to assign contributor, missing contributor");if(!r)return s("Unable to assign contributor, missing target");let o=Ct(r,"edit");if(o)return o;if(!B(r))return s("Target is not an issue");let i=r.props.assignees??[];if(i.includes(t))return s("Contributor already assigned");let d={...r,props:{...r.props,assignees:[...i,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 s("Unable to unassign, missing contributor");if(!r)return s("Unable to unassign, missing target");let o=Ct(r,"edit");if(o)return o;if(!B(r))return s("Target is not an issue");let i=r.props.assignees??[];if(!i.includes(t))return c("Issue is not assigned to that contributor",{assignee:t});let d={...r,props:{...r.props,assignees:i.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 s("Unable to add tag, missing tag");if(!r)return s("Unable to add tag, missing target");let o=Ct(r,"edit");if(o)return o;if(!B(r))return s("Target is not an issue");let i=r.props.tags??[];if(i.includes(t))return s("Tag already assigned");let d={...r,props:{...r.props,tags:[...i,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 s("Unable to remove tag, missing tag");if(!r)return s("Unable to remove tag, missing target");let o=Ct(r,"edit");if(o)return o;if(!B(r))return s("Target is not an issue");let i=r.props.tags??[];if(!i.includes(t))return c("Issue is not tagged with that tag",{tag:t});let d={...r,props:{...r.props,tags:i.filter(l=>l!==t)}};return this.updateNode(d),c("Tag removed",{tag:t})},createTag(e){let t=be(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?s("Could not create tag"):c("Tag created",e)},createNode(e){let t=be(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?s("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let n={...t,readonly:!0},r=be(o=>({...o,nodes:{...o.nodes,[e]:n}}));return a(r)?s(r.message):c("Locked node",n)},updateNode(e){let t=be(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?t:c("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return H(e)}}});import St from"chalk";import jd from"string-width";import{decodeTime as Lm}from"ulid";var Pm,km,Fm,Dm,Om,Um,Bm,_m,$m,Hd,zd=y(()=>{"use strict";ae();T();vt();ir();Pm=(e,t)=>e+" ".repeat(Math.max(0,t-jd(e))),km=(e,t)=>" ".repeat(Math.max(0,t-jd(e)))+e,Fm=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"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),Dm=(e,t)=>t?e<t?"up":e>t?"down":null:null,Om=(e,t)=>{let n=N.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 i=Dm(e.payload.rank,o.rank);if(i)return`Moved ${i} in ${r}`}return`Moved issue to ${r}`},Um=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?St.bgHex(Oe(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?St.bgHex(Oe(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?St.hex(Oe(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?St.hex(Oe(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;default:return""}},Bm=e=>{let t=us(Lm(e));return St.gray(km(t,8))},_m=12,$m=e=>Pm(`${e}`,_m),Hd=(e,t)=>{let n=Bm(e.id),r=$m(e.userName),o=St.dim("\u203A"),i=e.action==="move.node"?Om(e,t):[Fm(e.action),Um(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${i}`}});var Wm,jm,Hm,zm,Vd,qd,Kd,Vm,Gd=y(()=>{"use strict";zd();Z();C();kt();ae();gn();T();At();bo();Wm=e=>ot(e,"description"),jm=e=>ot(e,"assignees"),Hm=e=>ot(e,"tags"),zm=e=>ot(e,"history"),Vd=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:i=!1,childRenderAxis:d="horizontal"})=>{let l=N.getNode(e);if(!l){let g=N.createNode({...ve.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:i,childRenderAxis:d});return a(g)?g:c("Virtual field created",void 0)}if(!Ze(l))return s(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==r||l.props.value!==o||l.readonly!==i||l.childRenderAxis!==d))return c("Virtual field unchanged",void 0);let m=N.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:i,childRenderAxis:d});return a(m)?m:c("Virtual field updated",void 0)},qd=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:i="horizontal"})=>{let d=N.getNode(e);if(!d){let m=N.createNode({...ve.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:i});return a(m)?m:c("Virtual field list created",void 0)}if(!Qt(d))return s(`Existing virtual node ${e} is not a field list`);if(!(d.title!==t||d.parentNodeId!==n||d.rank!==r||d.readonly!==o||d.childRenderAxis!==i))return c("Virtual field list unchanged",void 0);let u=N.updateNode({...d,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:i});return a(u)?u:c("Virtual field list updated",void 0)},Kd=e=>{let t=Ce(He/4n),n=Ce(He/2n),r=Ce(He*3n/4n),o=Ce(He*7n/8n);if(a(t))return t;if(a(n))return n;if(a(r))return r;if(a(o))return o;let i=Vd({id:Wm(e.id),name:ee.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(i))return i;let d=qd({id:jm(e.id),name:ee.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(d))return d;let l=qd({id:Hm(e.id),name:ee.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(a(l))return l;let u=Vd({id:zm(e.id),name:ee.HISTORY,parentNodeId:e.id,rank:o.value,value:Vm(e),readonly:!0,childRenderAxis:"vertical"});return a(u)?u:c("Ticket virtual nodes materialized",void 0)},Vm=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=>Hd(r,n.get(r.action)??[])).join(`
59
- `)}});function Cn(e,t=!1){let n=Zm[e.action](e);if(a(n))return n;let r=Qm(e,t);return r||n}var D,Yd,qm,Km,Gm,Ym,Xm,Jm,Qm,Zm,Nt,Kt=y(()=>{"use strict";Z();C();kt();ae();gn();T();Gd();xn();D=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Yd=e=>{let t=N.getNode(e);if(!t||!B(t)||t.isDeleted)return null;let n=Kd(t);return a(n)?n:null},qm=e=>{for(let t of e){let n=Yd(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=Yd(r);if(o)return o}return null},Km=(e,t)=>{let n=N.getNode(e);n&&N.updateNode({...n,log:[...n.log??[],t]})},Gm=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},Ym=e=>{switch(e.action){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":default:return[]}},Xm=e=>{be(t=>({...t,eventLog:[...t.eventLog,e]}))},Jm=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?D("Invalid user ID format",e):c("Valid user",null)},Qm=(e,t)=>{let n=Jm(e);if(a(n))return n;let r=[...new Set(Ym(e))];t||(r.forEach(i=>Km(i,e)),Xm(e));let o=qm(r);return o||null},Zm={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=ve.workspace(t,n,r),i=In(o);if(a(i))return D(i.message,e);let d=N.createNode(o);return a(d)?D(d.message??"Failed to initialize workspace",e):jr(d.value)?c("Workspace initialized",{action:e.action,result:d.value}):s("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=N.createNode(ve.workspace(t,n,r));return a(o)?D(o.message??"Failed to add workspace",e):jr(o.value)?c("Added workspace",{action:e.action,result:o.value}):s("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=N.createNode(ve.board(t,n,r,o));return a(i)?D(i.message??"Unable to create board",e):gi(i.value)?c("Added board",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=N.createNode(ve.swimlane(t,n,r,o));return a(i)?D(i.message??"Unable to create swimlane",e):Mn(i.value)?c("Added swimlane",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=N.createNode(ve.ticket(t,n,r,o));return a(i)?D(i.message??"Unable to create issue",e):B(i.value)?c("Added issue",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:i}=e.payload,d=N.createNode(ve.field({id:t,name:n,parentNodeId:r,rank:i,props:{value:o},childRenderAxis:n.includes(ee.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?D(d.message??`Unable to create field: ${n}`,e):Ze(d.value)?c("Added field",{action:e.action,result:d.value}):s("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!N.getNode(t))return D(`Unable to locate node with id ${t}`,e);let o=N.renameNode(t,n);return a(o)?D(o.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=N.tombstoneNode(t);return a(n)?D(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=N.createTag({id:t,name:n});return a(r)?D(r.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=N.createContributor({id:t,name:n});return a(r)?D(r.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=N.tag(t,n);return a(r)?D(r.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=N.untag(t,n);return a(r)?D(r.message??"Unable to untag issue",e):c("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=N.assign(t,n);return a(r)?D(r.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=N.unassign(t,n);return a(r)?D(r.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?D(o.message??"Failed to move node",e):c("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=N.editValue(t,n);return a(r)?D(r.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.getNode(t);if(!o)return D("Unable to locate issue",e);if(!B(o))return D("Can only close issues",e);let i=N.getNode(ue);if(!i)return D("Unable to locate target swimlane",e);if(n!==i.id)return D("Close target must be closed swimlane",e);let d=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(d)?D(d.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.getNode(t);if(!o)return D("Unable to locate issue",e);if(!B(o))return D("Can only reopen issues",e);let i=N.getNode(ue);if(!i)return D("Unable to locate closed swimlane",e);if(n===i.id)return D("Cannot reopen issue into closed swimlane",e);if(!N.getNode(n))return D("Reopen parent no longer exists",e);let l=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(l)?D(l.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=N.lockNode(t);return a(n)?D(n.message??"Unable to lock node",e):c("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let i=N.getNode(r);if(!i)return D(`Unable to locate node ${r}`,e);if(i.parentNodeId!==t)return D(`Node ${r} is not child of ${t}`,e);let d=N.updateNode({...i,rank:o});if(a(d))return D(d.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})}};Nt=e=>e.map(t=>Cn(t))});function Le(e,t){let n=Cn(e);if(n.status!==Qe.Success)return n;let r=Cr({event:e,rootDir:t});return a(r)?r:n}function It(e,t){return e.map(n=>Le(n,t))}var Ie,Et=y(()=>{"use strict";C();re();Kt();Me();Ie=async e=>{let t=await Ae();return a(t)?t:Le(e,t.value)}});var Xd,Mr,H,Jd,Qd,Xt,Gt,Se=y(()=>{"use strict";yi();Et();C();T();At();Xd=e=>Mr(H(e),{at:"end"}),Mr=(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(me(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(me(void 0,r.rank)):s("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(me(r.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let r=Jd(e,t.sibling);if(r<0)return s("Sibling not found");let o=r>0?e[r-1]:void 0,i=e[r];return i?n(me(o?.rank,i.rank)):s("Sibling not found")}case"after":{let r=Jd(e,t.sibling);if(r<0)return s("Sibling not found");let o=e[r],i=r<e.length-1?e[r+1]:void 0;return o?n(me(o.rank,i?.rank)):s("Sibling not found")}}},H=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Jd=(e,t)=>e.findIndex(n=>n.id===t),Qd=(e,t,n={at:"end"})=>Mr(H(t).filter(r=>r.id!==e),n),Xt=(e,t,n,r,o)=>{let i=Qd(t,e,n);if(a(i))return i;if(!i.value.needsRebalance)return c("Resolved rank",i.value.rank);let d=Hr(e,r);if(a(d))return d;let l=Le(d.value,o);if(a(l))return l;let u=Qd(t,e,n);return a(u)?u:u.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",u.value.rank)},Gt=(e,t,n)=>{let r=Xd(e);if(a(r))return r;if(!r.value.needsRebalance)return c("Resolved rank",r.value.rank);let o=Hr(e,t);if(a(o))return o;let i=Le(o.value,n);if(a(i))return i;let d=Xd(e);return a(d)?d:d.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",d.value.rank)}});var ec,tc,ep,Ur,nc,Zd,tp,rc,oc=y(()=>{"use strict";Z();C();Se();T();Te();ec=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),tc=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},ep=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&&Ze(t)&&t.childRenderAxis==="vertical"},Ur=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=H(r.id);return L.navigate({contextNode:r,selectedIndex:ec(t,o.length)}),!0},nc=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Ur(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let d=H(o.id).findIndex(l=>l.id===n.id);return d>=0?(L.navigate({contextNode:o,selectedIndex:d}),!0):nc(o.id)},Zd=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),nc(n))return!0;n=t[n]?.parentNodeId}return!1},tp=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},rc=e=>{let{nodes:t,rootNodeId:n}=v();if(ep(e.contextNodeId)&&Ur(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(tp(e.selectedNodeId)&&e.selectedNodeId&&Zd(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(Ur(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&Ur(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(Zd(e.contextNodeId))return c("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return s("Unable to restore navigation");let o=H(r.id);return L.navigate({contextNode:r,selectedIndex:ec(e.selectedIndex,o.length)}),c("Restored navigation to root",null)}});var $,Qo=y(()=>{"use strict";C();$=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});var Zo,ei,ti,np,ce,ic=y(()=>{"use strict";C();T();Zo=({status:e,msg:t})=>{Ot()&&E({syncStatus:{status:e,msg:t}})},ei=(e="Syncing...")=>{Zo({status:"syncing",msg:e})},ti=(e="Synced")=>{Zo({status:"synced",msg:e})},np=e=>{Zo({status:"failed",msg:e})},ce=e=>(np(e),s(e))});import{decodeTime as rp}from"ulid";var ri,ni,sc,ac,dc,cc=y(()=>{"use strict";C();ri=e=>{let t=[];for(let n of e.split(`
60
- `)){let r=n.trim();if(r)try{t.push(JSON.parse(r))}catch{return s("Failed to parse persisted events")}}return c("Parsed persisted events",t)},ni=e=>{let[t,n]=e.id;return`${t}:${n??""}`},sc=e=>{try{return rp(e.id[0])}catch{return 0}},ac=(e,t)=>{let n=new Map;for(let r of[...e,...t])n.set(ni(r),r);return[...n.values()].sort((r,o)=>{let i=sc(r)-sc(o);return i!==0?i:ni(r).localeCompare(ni(o))})},dc=e=>e.length===0?"":e.map(t=>JSON.stringify(t)).join(`
61
- `)+`
62
- `});import We from"node:fs";import An from"node:path";var lc,op,ip,sp,ap,uc,mc,dp,Br,oi=y(()=>{"use strict";C();ic();Qo();Un();Pt();Tt();jo();cc();lc=e=>We.existsSync(e)?We.readFileSync(e,"utf8"):null,op=(e,t)=>lc(e)===t?!1:(We.mkdirSync(An.dirname(e),{recursive:!0}),We.writeFileSync(e,t,"utf8"),!0),ip=e=>{let t=An.join(e,".epiq","events"),n=new Map;if(!We.existsSync(t))return c("No event files to snapshot",n);for(let r of We.readdirSync(t)){if(!r.endsWith(".jsonl"))continue;let o=An.join(t,r);We.statSync(o).isFile()&&n.set(r,We.readFileSync(o,"utf8"))}return c("Snapshotted event files",n)},sp=async e=>{if((await Re({cwd:e,args:["checkout","--",on("")]})).exitCode!==0){let n=An.join(e,".epiq","events");We.existsSync(n)&&We.rmSync(n,{recursive:!0,force:!0})}return c("Restored event files to HEAD",null)},ap=({stateBranchRoot:e,snapshots:t})=>{let n=!1;for(let[r,o]of t){let i=An.join(e,on(r)),d=lc(i)??"",l=ri(d);if(a(l))return s(l.message);let u=ri(o);if(a(u))return s(u.message);let m=ac(l.value,u.value);n=op(i,dc(m))||n}return c("Merged event snapshots",n)},uc=async(e=process.cwd())=>{logger.debug("[sync] syncEpiqFromRemote:start",e),ei("Syncing from remote");let t=$("ensureSyncReady",await mc({cwd:e,ensureUpstream:!1}));if(a(t))return ce(t.message);let{repoRoot:n,stateBranchRoot:r}=t.value,o=$("getStateBranch",ut(n));if(a(o))return ce(o.message);let i=o.value,d=$("snapshotEventFiles",ip(r));if(a(d))return ce(d.message);let l=$("restoreEventFilesToHead",await sp(r));if(a(l))return ce(l.message);let u=$("resetBranchHardToRemote",await Pi({cwd:r,branch:i}));if(a(u))return ce(u.message);let m=$("mergeEventSnapshots",ap({stateBranchRoot:r,snapshots:d.value}));return a(m)?ce(m.message):(ti(m.value?"Synced and merged local state":"Synced from remote"),logger.debug("[sync] syncEpiqFromRemote:done"),c("Synced state branch from remote",{repoRoot:n,stateBranchRoot:r}))},mc=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=$("getRepoRootDir",await nt(e));if(a(n))return s(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=$("getStateBranchRoot",Lt({repoRoot:r}));if(a(o))return s(o.message);let i=o.value;logger.debug("[sync] state branch root",i);let d=$("ensureInitialCommit",await Ba(r));if(a(d))return s(d.message);logger.debug("[sync] initial commit result",{created:d.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:i,ensureUpstream:t});let l=$("bootstrapStateBranchStorage",await $a({repoRoot:r,stateBranchRoot:i,ensureUpstream:t}));if(a(l))return s(l.message);logger.debug("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:i}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:i});let u=$("hasInProgressGitOperation(stateBranchRoot)",await _n(i));if(a(u))return s(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"),s("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:i});let m=$("ensureStateBranchLayout",_i(r,i));return a(m)?s(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:i,bootstrapped:l.value}),c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:i,bootstrapped:l.value}))},dp=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=$("stageStateBranchOwnEventFile",await Ar({stateBranchRoot:t,eventFileName:n}));if(a(r))return s(r.message);let o=$("hasStagedChanges(after stage)",await ki(t));if(a(o))return s(o.message);if(logger.debug("[sync] state branch change check after stage result",{changed:o.value}),!o.value)return logger.info("[sync] no own event file changes to commit"),c("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let i=$("createStateBranchSyncCommit",await _a({repoRoot:e,stateBranchRoot:t}));return a(i)?s(i.message):(logger.debug("[sync] created sync commit",i.value),c("Committed own event file",{createdCommit:!0,commitSha:i.value}))},Br=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}),s("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}),s("Own event file must end with .jsonl");ei();let n=$("ensureSyncReady",await mc({cwd:e,ensureUpstream:!0}));if(a(n))return ce(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,d=$("isDetachedHead(stateBranchRoot)",await Fi(o));if(a(d))return ce(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return ce("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,g=!1,x=$("getStateBranch",ut(r));if(a(x))return ce(x.message);let b=x.value;logger.debug("[sync] resolved state branch",{stateBranch:b,stateBranchRoot:o});let R=$("commitOwnEventFileToStateBranch",await dp({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(a(R))return ce(R.message);l=R.value.createdCommit,u=R.value.commitSha;let I=$("pullBranchRebaseIfPresent",await Jr({cwd:o,branch:b}));if(a(I))return ce(I.message);if(m=I.value,l||i){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:i,stateBranchRoot:o});let k=$("pushStateBranch",await En({stateBranchRoot:o,repoRoot:r}));if(a(k)&&Mi(k.message)){let A=$("pullBranchRebaseIfPresent(retry)",await Jr({cwd:o,branch:b}));if(a(A))return ce(A.message);m=m||A.value,k=$("pushStateBranch(retry)",await En({stateBranchRoot:o,repoRoot:r}))}if(a(k))return ce(k.message);g=k.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let k=$("git rev-parse HEAD",await _({args:["rev-parse","HEAD"],cwd:o}));if(a(k))return ce(k.message);u=k.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return ti(g?"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:g,bootstrapped:i})}});var qe,pc,Xn=y(()=>{"use strict";oc();Tr();vn();Me();G();C();T();Qo();oi();qe=async()=>{let e=pc();if(e)return e;logger.debug("[sync] syncAndReloadState:start");let t=$("resolveActorId",Q());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id"),s("Unable to resolve event log path");E({syncStatus:{msg:"Reloading synced state",status:"syncing"}});let n=ht(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n});let r=$("syncEpiqWithRemote",await Br({ownEventFileName:n}));if(a(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),s(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let i=$("loadMergedEvents",zt(o));if(a(i))return s(`Unable to load events. ${i.message}`);logger.debug("[sync] loaded merged events after sync",{count:i.value.length});let d=pc();if(d)return d;let l=tc();if(!v().selectedNode?.isVirtual&&!v().contextNode?.isVirtual){let m=$("bootStateFromEventLog",wr(i.value));if(a(m))return s(`Unable to boot synced state. ${m.message}`)}logger.debug("[sync] booted state from synced events");let u=$("restoreNavigationAnchor",rc(l));return a(u)?u:(E({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done"),c("Synced",!0))},pc=()=>v().mode===p.DEFAULT?null:(E({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),s("Will not re-materialize if not in default mode, to not lose edit data"))});import{ulid as ii}from"ulid";var gc,ct,wn,Tn,cp,lp,fc,vc,yc,xc,hc,Ec,Nc,Ic,bc,Cc=y(()=>{"use strict";Xn();oi();Ht();Ko();Tr();vn();Et();Me();xn();Z();C();ae();Se();T();re();Ft();gc=e=>{let t=tt(e??process.cwd());return a(t)?s(t.message):c("Resolved Epiq repo root",t.value)},ct=async e=>{let t=gc(e);if(a(t))return t;let n=await uc(t.value);if(a(n))return s(n.message);let{stateBranchRoot:r}=n.value,o=zt(r);if(a(o))return s(o.message);let i=wr(o.value);return a(i)?s(i.message):c("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:r})},wn=()=>{let e=Ea();return a(e)?s(e.message):e.value.userId?e.value.userName?c("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):s("Unable to retrieve user name"):s("Unable to retrieve user id")},Tn=()=>{let e=Fe();return a(e)?s(e.message):e},cp=e=>(e.props.tags??[]).map(t=>N.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),lp=e=>(e.props.assignees??[]).map(t=>N.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),fc=async(e={})=>{let t=await ct(e.repoRoot);if(a(t))return t;let n=Tn();if(a(n))return n;let r=Object.values(n.value.nodes).filter(o=>o.context==="BOARD").map(o=>({id:o.id,title:o.title,parentId:o.parentNodeId,readonly:!!o.readonly}));return c("Listed boards",r)},vc=async(e={})=>{let t=await ct(e.repoRoot);if(a(t))return t;let n=Tn();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)},yc=async e=>{let t=await ct(e.repoRoot);if(a(t))return t;let n=Tn();if(a(n))return n;let r=Object.values(n.value.nodes).filter(B).filter(o=>e.includeClosed||o.parentNodeId!==ue).map(o=>({id:o.id,title:Kn(o.title),description:o.props.description??"",parentId:o.parentNodeId,isClosed:o.parentNodeId===ue,readonly:!!o.readonly,tags:cp(o),assignees:lp(o)}));return c("Listed issues",r)},xc=async e=>{let t=await ct(e.repoRoot);if(a(t))return t;let n=wn();if(a(n))return n;let r=Gt(e.parentId,n.value,t.value.stateBranchRoot);if(a(r))return r;let o=Pr({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(a(o))return o;let i=o.value,l=It(i,t.value.stateBranchRoot).find(a);if(l)return s(l.message);let u=await qe();if(a(u))return u;let m=i.find(g=>g.action==="add.issue")?.payload.id;return m?c("Created issue",{id:m,title:e.title,parentId:e.parentId}):s("Unable to determine created issue id")},hc=async e=>{let t=await ct(e.repoRoot);if(a(t))return t;let n=wn();if(a(n))return n;let r=Xt(ue,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(r))return r;let o={id:ii(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ue,rank:r.value}},d=It([o],t.value.stateBranchRoot).find(a);if(d)return s(d.message);let l=await qe();return a(l)?l:c("Closed issue",{id:e.issueId})},Ec=async e=>{let t=await ct(e.repoRoot);if(a(t))return t;let n=wn();if(a(n))return n;let r=Xt(e.parentId,e.issueId,e.position??{at:"end"},n.value,t.value.stateBranchRoot);if(a(r))return r;let o={id:ii(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:r.value}},d=It([o],t.value.stateBranchRoot).find(a);if(d)return s(d.message);let l=await qe();return a(l)?l:c("Moved issue",{id:e.issueId,parentId:e.parentId})},Nc=async(e={})=>{let t=gc(e.repoRoot);if(a(t))return s("Sync failed");let n=wn();if(a(n))return n;let r=await Br({cwd:t.value,ownEventFileName:ht(n.value)});return a(r)?r:c("Synced",r.value)},Ic=async(e={})=>{let t=await ct(e.repoRoot);if(a(t))return t;let n=Tn();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})},bc=async e=>{let t=await ct(e.repoRoot);if(a(t))return t;let n=wn();if(a(n))return n;let r=Tn();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return s("Issue not found");if(!B(o))return s("Edit target must be an issue");if(o.readonly)return s("Cannot edit readonly issue");let i=o.props.description??"";if(i===e.description)return c("No changes made",{id:e.issueId,description:i});let d={id:ii(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},u=It([d],t.value.stateBranchRoot).find(a);if(u)return s(u.message);let m=await qe();return a(m)?m:c("Edited issue description",{id:e.issueId,description:e.description})}});var Ac={};Pc(Ac,{createMcpServer:()=>Sc,resultJson:()=>je,startMcpServer:()=>Rc});import{McpServer as up}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as mp}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as F}from"zod";var je,Sc,Rc,wc=y(async()=>{"use strict";C();Cc();je=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Sc=()=>{let e=new up({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:F.object({repoRoot:F.string().optional()})},async t=>je(await Ic(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:F.object({repoRoot:F.string().optional(),includeClosed:F.boolean().optional()})},async t=>je(await yc(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>je(await fc(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:F.object({repoRoot:F.string().optional(),boardId:F.string().optional()})},async t=>je(await vc(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue",inputSchema:F.object({title:F.string().min(1),parentId:F.string().min(1),repoRoot:F.string().optional()})},async t=>je(await xc(t))),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:F.object({issueId:F.string().min(1),description:F.string(),repoRoot:F.string().optional()})},async t=>je(await bc(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:F.object({issueId:F.string().min(1),repoRoot:F.string().optional()})},async t=>je(await hc(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:F.object({issueId:F.string().min(1),parentId:F.string().min(1),position:F.discriminatedUnion("at",[F.object({at:F.literal("start")}),F.object({at:F.literal("end")}),F.object({at:F.literal("before"),sibling:F.string().min(1)}),F.object({at:F.literal("after"),sibling:F.string().min(1)})]).optional(),repoRoot:F.string().optional()})},async t=>je(await Ec(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>je(await Nc(t))),e},Rc=async()=>{let e=Sc(),t=new mp;await e.connect(t)};await Rc()});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;await wc().then(()=>Ac);
56
+ `,as.writeFileSync(t,n,"utf8"),le.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)}});import ep from"node:fs";import vd from"node:path";var tp,G,yd,xd=y(()=>{"use strict";fd();Kn();vt();xt();ro();Le();Ln();ho();Ht();Fe();J();b();yt();de();he();w();ce();tp=async e=>{let t=await U({cwd:e,args:["status","--porcelain"]});return a(t)?t:c("Checked git diff",t.value.stdout.trim().length>0)},G=(e,t)=>i(`[${e}] ${t}`),yd=async()=>{$("");let e=Gn(),t=await at(process.cwd());if(a(t))return G(1,t.message);let n=t.value,o=await Jn(n);if(a(o))return G(2,o.message);if(o.value)return G(2,`Cannot initialize Epiq while a git operation is in progress: ${o.value}`);let r=await tp(n);if(a(r))return G(2.5,r.message);if(r.value)return G(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(or(n))return G(4,"Epiq project already initialized");let s=Co();if(!s.isSetupDone||!s.userName)return G(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let d=Q(),l=d.userName,u=d.userId;if(!u||!l)return G(5,"Missing Epiq user id");let m=e.stateBranch,g=await Zn({repoRoot:n,branch:m});if(a(g))return G(6,g.message);if(g.value)return G(6,`State branch already exists: ${m}`);let x=await gr({repoRoot:n,stateBranchName:m});if(a(x))return G(6,x.message);let E=no();if(a(E))return G(7,E.message);let A=vd.join(to(),e.projectId),S=await fn({repoRoot:n,stateBranchRoot:A,stateBranchName:m});if(a(S))return G(8,S.message);let k=vd.join(A,".epiq");ep.mkdirSync(k,{recursive:!0});let _=Vi({userId:u,userName:l});if(a(_))return G(9,_.message);for(let nr of _.value){let Ss=vo({event:nr,rootDir:A});if(a(Ss))return G(9,Ss.message)}let O=await oo({stateBranchRoot:A,eventFileName:St({userId:u,userName:l})});if(a(O))return G(10,O.message);let Y=await Ft({cwd:A,message:"[epiq:init]"});if(a(Y))return G(10,Y.message);let W=await gd(n);if(a(W))return G(11,W.message);let V=ws({repoRoot:n,fileContents:e});if(a(V))return G(12,V.message);let Zo=await ee.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(Zo))return G(13,Zo.message);let jn=await ee.commit({cwd:n,message:"[epiq:init-project]"});if(a(jn))return G(13,jn.message);let er="Project initialized!",Ns=await U({cwd:n,args:["push","-u","origin","HEAD"]});a(Ns)&&(er+=` Warn: [init:14] ${Ns.message}`);let Es=await vn({repoRoot:n,stateBranchRoot:A});a(Es)&&(er+=` Warn: [init:15] ${Es.message}`);let bs=bt(_.value).filter(a);if(bs.length>0)return G(16,bs.map(nr=>nr.message).join(`
57
+ `));let tr=He();if(a(tr))return G(16,tr.message);let{rootNodeId:Lc,nodes:Pc}=tr.value,Cs=Pc[Lc];return Cs?(L.navigate({contextNode:Cs,selectedIndex:0}),N({hasProjectDefinition:!0,mode:f.DEFAULT}),c(er,null)):G(16,"Unable to resolve initialized root node")}});import{ulid as np}from"ulid";function cs(e){let t=Id();if(a(t))return t;let{contextNode:n,nodes:o}=p();if(!n.parentNodeId)return i("Missing parent node id");let r=o[n.parentNodeId];if(!r)return i("Missing parent node");let s=K(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=Nd({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Ed(u.value)}function ls(e){let t=Id();if(a(t))return t;let{contextNode:n,selectedIndex:o}=p(),s=K(n.id)[o+e];if(!s)return i("Missing sibling node");let d=Nd({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:Ed(d.value)}var hd,gt,On,Id,ds,Nd,Ed,us=y(()=>{"use strict";Ht();Fe();b();We();w();hd=null,gt=()=>structuredClone(hd),On=e=>{hd=e},Id=()=>{let{contextNode:e,selectedIndex:t}=p(),o=K(e.id)[t];return o?c("Resolved selected child",o):i("Target node not found")},ds=({id:e,parentId:t,position:n={at:"end"}})=>{let o=K(t).filter(r=>r.id!==e);return yo(o,n)},Nd=({id:e,parentId:t,position:n={at:"end"}})=>{let o=X();if(a(o))return i("Unable to resolve user ID");let r=ds({parentId:t,id:e,position:n});return a(r)?r:c("Created pending move state",{id:np(),...o.value,action:"move.node",payload:{id:e,parent:t,rank:r.value.rank}})},Ed=e=>{On(e);let t=Cn(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as op}from"ulid";var bd,zo,Cd,Sd=y(()=>{"use strict";Le();us();Rt();Fe();J();b();We();de();w();ce();bd=()=>{let e=gt();if(!e)return i("No pending move state");let t=e.payload.id,n=e.payload.parent,o=p().nodes[n];if(!o)return i("Move parent not found");let r=K(n).findIndex(s=>s.id===t);return r===-1?i("Moved node not found among rendered children"):(L.navigate({contextNode:o,selectedIndex:r}),c("Synchronized navigation to moved node",null))},zo=(e,t="Moved preview")=>{if(a(e))return e;let n=bd();return a(n)?n:(N({mode:f.MOVE}),c(t,null))},Cd=async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=se().commandMeta,{contextNode:n,selectedIndex:o}=p(),r=K(n.id)[o];if(!r)return N({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=K(r.parentNodeId),d=s.findIndex(({id:x})=>x===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"},g=ds({parentId:r.parentNodeId,id:r.id,position:m});return a(g)?g:(On({id:op(),action:"move.node",payload:{id:r.id,parent:r.parentNodeId,rank:g.value.rank},...e.value}),N({mode:f.MOVE}),c("Move initialized",null))}if(t==="next")return zo(ls(1));if(t==="previous")return zo(ls(-1));if(t==="to-next")return zo(cs(1));if(t==="to-previous")return zo(cs(-1));if(t==="confirm"){let s=gt();if(!s)return i("No pending move to confirm");let d=await Oe();if(a(d))return d;let l=j([s],d.value);if(a(l))return l;let u=bd();return a(u)?u:(On(null),N({mode:f.DEFAULT}),c("Moved item",null))}return t==="cancel"?(On(null),N({mode:f.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as rp,ulid as sp}from"ulid";var ip,qo,ms=y(()=>{"use strict";b();ip=rp(),qo=({name:e,parent:t,rank:n,user:{userId:o,userName:r}})=>{let s=ip();return c("Created issue events",[{id:sp(),userId:o,userName:r,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as Go}from"ulid";var Rd,Ad=y(()=>{"use strict";Le();ms();Rt();Fe();Yt();b();ie();We();w();ce();Rd=async(e,t)=>{let n=X();if(a(n))return i("Unable to resolve user ID");let o=await Oe();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}=p(),u=m=>{let g=j([m],r);if(a(g))return g;let x=I.getNode(g.value[0].result.id);if(!x)return i("Created node not found");if(!x.parentNodeId)return g;let E=I.getNode(x.parentNodeId);return E?(L.navigate({contextNode:E,selectedIndex:I.getSiblings(x.parentNodeId).findIndex(({id:A})=>A===x.id)}),g):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=p(),g=I.getNode(m);if(!g)return i("Workspace not found");let x=zt(g.id,n.value,r);return a(x)?x:u({id:Go(),action:"add.board",payload:{id:Go(),name:t.inputString,parent:g.id,rank:x.value},...n.value})}if(t.modifier==="swimlane"){let m=ke(s,"BOARD");if(a(m))return i("Unable to add swimlane in this context");let g=zt(m.value.id,n.value,r);return a(g)?g:u({id:Go(),action:"add.swimlane",payload:{id:Go(),name:t.inputString,parent:m.value.id,rank:g.value},...n.value})}if(t.modifier==="issue"){let m=q(d.id)[l],g=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let Y=ke(s,"SWIMLANE");return a(Y)?null:Y.value})();if(!g)return i("Unable to add issue in this context");let x=zt(g.id,n.value,r);if(a(x))return x;let E=qo({name:t.inputString,parent:g.id,rank:x.value,user:n.value});if(a(E))return E;let A=E.value,S=j([...A],r);if(a(S))return S;if(!S.value[0])return i("Issue creation failed");let O=A.find(Y=>Y.action==="add.issue")?.payload.id;return O?(L.navigate({contextNode:g,selectedIndex:I.getSiblings(g.id).findIndex(({id:Y})=>Y===O)}),c("Issue created",null)):i("Unable to determine ticket id")}return c("Success",null)}});var Td,wd=y(()=>{"use strict";vt();Le();Nn();Rn();Ht();J();Yt();b();de();w();wo();Td=async()=>{let e=ke(p().breadCrumb,"BOARD");if(a(e))return e;let t=await at(process.cwd());if(a(t))return i("Unable to locate repo root");let n=Qe({repoRoot:t.value});if(a(n))throw new Error(n.message);let{modifier:o}=se().commandMeta;if(o==="now"){let S=Ct(n.value);if(a(S))return i(S.message);let k=Un();if(a(k))return k;let O=bt(S.value).filter(a);return O.length>0?i(O.map(Y=>Y.message).join(", ")):(N({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}let r;if(o==="prev"){let S=p().eventLog.at(-1),k=Ir(S);if(k===null)return i("No previous event to peek");r=k}else if(o==="next"){let S=p().unappliedEvents.at(0),k=Ir(S);if(k===null)return i("No next event to peek");r=k+1}else{let S=To(o);if(!S)return i("Invalid peek date");r=S.getTime()}let s=p(),d=e.value.id,l=Si(n.value,r);if(a(l))return i(l.message);let{appliedEvents:u,unappliedEvents:m}=l.value,g=Un();if(a(g))return g;let E=bt(u).filter(a);if(E.length>0)return Un(),N(s),i(E.map(S=>S.message).join(", "));let A=p().nodes[d];return A?(L.navigate({contextNode:A,selectedIndex:0}),N({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:m}),c("Peeking",!0)):(Un(),N(s),i("Board did not exist at peek date"))}});import ap from"zod";var Md,Ld=y(()=>{"use strict";rn();J();b();de();he();w();Md=()=>{let e=se().commandMeta.inputString,t=ap.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=ot({autoSyncDebounceMs:t.data});return a(n)?n:($e({autoSyncIntervalMs:t.data}),N({mode:f.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))}});var Pd,kd=y(()=>{"use strict";Ln();rn();J();b();de();he();w();Pd=()=>{let e=se().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=Qi(e),n=ot({autoSync:t});return a(n)?n:($e({autoSync:t}),N({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var Dd,Fd=y(()=>{"use strict";rn();J();b();de();he();w();Dd=()=>{let e=se().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return i("Invalid response");let n=ot({logLevel:e});return a(n)?n:($e({logLevel:e}),N({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var Od,Ud=y(()=>{"use strict";Tr();J();b();de();w();Od=async()=>{$(""),N({mode:f.DEFAULT});let e=He();if(a(e))return i(e.message);if(e.value.syncStatus.status==="syncing")return i("Sync already in progress");N({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Io();return a(t)?(N({syncStatus:{msg:t.message,status:"failed"}}),t):(N({mode:f.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as ve}from"ulid";var dp,Bd,_d,rt,$d,jd=y(()=>{"use strict";Qa();Le();rn();Rt();Fe();os();bn();J();Yt();te();b();ie();We();de();he();w();Vo();ce();dd();At();Hr();Kt();Br();pd();xd();Sd();Ad();wd();Ld();kd();Fd();Ud();dp=e=>e.action==="add.issue.comment",Bd=e=>Object.values(p().tags).find(t=>t.name===e),_d=e=>Object.values(p().contributors).find(t=>t.name===e),rt=async()=>{let e=await Oe();return a(e)?e:c("Resolved persist root",e.value)},$d=[{systemOnly:!0,intent:M.Move,description:"Internal move-state command",mode:f.COMMAND_LINE,action:Cd},{intent:M.Delete,description:"Delete the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=p(),o=q(t.id)[n];if(!o)return i("Unable to resolve child to delete");let r=await rt();if(a(r))return r;if(o.context==="COMMENT"){let s=o.id,d=D(t)?t.id:t.parentNodeId;if(!d)return i("Unable to resolve comment issue");let l=p().nodes[d];if(!l||!D(l))return i("Unable to resolve comment issue");let u=l.log?.filter(dp).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):j([{id:ve(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],r.value):i("Unable to resolve comment")}return j([{id:ve(),action:"delete.node",payload:{id:o.id},...e.value}],r.value)},onSuccess:()=>N({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}=se().commandMeta,n=/(!=|=)/,[o]=e.split(n);if(!o||!(d=>ue(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 me(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:o}=p();return pt({pendingNavTarget:{contextNode:e,breadCrumb:o,selectedIndex:t,selectedNode:n}}),N({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=X();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=p(),o=q(t.id)[n];if(!o)return i("Unable to close issue, no target found");if(!D(o))return i("Cannot close in this context");let r=p().nodes[ye];if(!r)return i("Unable to locate closed swimlane");if(o.parentNodeId===r.id)return i("Issue is already closed");let s=await rt();if(a(s))return s;let d=s.value,l=Vt(r.id,o.id,{at:"end"},e.value,d);if(a(l))return l;let u=j([{id:ve(),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:()=>N({mode:f.DEFAULT})},{intent:M.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=p(),o=q(t.id)[n];if(!o)return i("Unable to reopen issue, no target found");let r=o.context==="TICKET"?c("Resolved ticket",o):Nt(o.id,"TICKET");if(a(r))return i("Cannot reopen in this context");let s=r.value,d=p().nodes[ye];if(!d)return i("Unable to locate closed swimlane");if(s.parentNodeId!==d.id)return i("Issue is not closed");if(!D(s))return i("Target node is not issue");let l=ns(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=p().nodes[l];if(!u)return i("Previous parent no longer exists");let m=await rt();if(a(m))return m;let g=m.value,x=Vt(u.id,s.id,{at:"end"},e.value,g);if(a(x))return x;let E=j([{id:ve(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:x.value},...e.value}],g);return a(E)?E:c("Issue reopened",null)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:M.Init,description:"Initialize Epiq in the current git repository",mode:f.COMMAND_LINE,action:yd},{intent:M.NewItem,description:"Create a new board, swimlane, or issue",mode:f.COMMAND_LINE,action:Rd,onSuccess:()=>N({mode:f.DEFAULT})},{intent:M.Rename,description:"itle] Rename the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=p(),o=q(t.id)[n];if(!o)return i("Missing node");if(o.readonly)return i("Cannot rename readonly node");let r=Ea();if(!r)return i("Provide a title");let s=await rt();return a(s)?s:j([{id:ve(),action:"edit.title",payload:{id:o.id,name:r},...e.value}],s.value)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:M.UntagTicket,description:"Remove a tag from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=se().commandMeta,o=(t||n).trim();if(!o)return i("Provide a tag");let r=Bd(o);if(!r)return i(`Tag "${o}" does not exist`);let{selectedNode:s}=p();if(!s)return i("Invalid untag target");let d=Nt(s.id,"TICKET");if(a(d))return i("Unable to untag issue in this context");let l=d.value;if(!D(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 rt();return a(m)?m:j([{id:ve(),action:"remove.issue.tag",payload:{id:l.id,tag:r.id},...e.value}],m.value)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:M.TagTicket,description:"Add or create a tag on the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=se().commandMeta,o=(t||n).trim();if(!o)return i("Provide a tag");let{selectedNode:r}=p();if(!r)return i("Invalid tag target");let s=Nt(r.id,"TICKET");if(a(s))return i("Unable to tag issue in this context");let d=s.value;if(!D(d))return i("Target node is not issue");let l=await rt();if(a(l))return l;let u=Bd(o),m=u?.id??ve();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):j([...u?[]:[{id:ve(),action:"create.tag",payload:{id:m,name:o},...e.value}],{id:ve(),action:"add.issue.tag",payload:{id:d.id,tag:m},...e.value}],l.value)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:M.AssignUserToTicket,description:"Assign a user to the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=se().commandMeta,o=(t||n).trim();if(!o)return i("Provide an assignee");let{selectedIndex:r,contextNode:s}=p(),d=q(s.id)[r];if(!d)return i("Invalid assign target");let l=Nt(d.id,"TICKET");if(a(l))return i("Unable to assign issue in this context");let u=l.value;if(!D(u))return i("Target node is not issue");let m=await rt();if(a(m))return m;let g=_d(o),x=g?.id??ve();return(u.props.assignees??[]).includes(x)?i("Assignee already assigned"):j([...g?[]:[{id:ve(),action:"create.contributor",payload:{id:x,name:o},...e.value}],{id:ve(),action:"add.issue.assignee",payload:{id:u.id,assignee:x},...e.value}],m.value)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:M.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=se().commandMeta,o=(t||n).trim();if(!o)return i("Provide an assignee to remove");let r=_d(o);if(!r)return i(`Assignee "${o}" does not exist`);let{selectedNode:s}=p();if(!s)return i("Invalid unassign target");let d=Nt(s.id,"TICKET");if(a(d))return i("Unable to unassign in this context");let l=d.value;if(!D(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 rt();return a(m)?m:j([{id:ve(),action:"remove.issue.assignee",payload:{id:l.id,assignee:r.id},...e.value}],m.value)},onSuccess:()=>N({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>Xt)return i(`Cannot exceed ${Xt} characters`);let o=X();if(a(o))return i("Unable to resolve user ID");let{breadCrumb:r,selectedNode:s}=p(),d=ke([...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):Nt(l.id,"TICKET");if(a(u))return i("Unable to comment on issue in this context");let m=u.value;if(!D(m))return i("Target node is not issue");let g=await rt();return a(g)?g:j([{id:ve(),action:"add.issue.comment",payload:{id:ve(),issue:m.id,author:o.value.userId,md:n},...o.value}],g.value)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:M.Sync,description:"Pull, commit, and push Epiq state",mode:f.COMMAND_LINE,action:Od},{intent:M.Peek,description:"View board state at another point in time",mode:f.COMMAND_LINE,action:Td},{intent:M.Export,description:"Export the current board layout to markdown",mode:f.COMMAND_LINE,action:async()=>{let e=await Ja();return a(e)?e:(N({mode:f.DEFAULT}),c("Export successful",!0))}},{intent:M.Exit,description:"Exit the application",mode:f.COMMAND_LINE,action:async()=>(L.exit(),c("Exit successful",!0))},{intent:M.Edit,description:"Edit title or description",mode:f.COMMAND_LINE,action:async(e,t)=>md(t),onSuccess:()=>N({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 oe.USERNAME:{let{userId:o,preferredEditor:r,userName:s}=Q(),d=n||s,l=o??ve();if(!d||!l)return i("Unable to resolve user name or id");let u=ot({userName:d,userId:l,preferredEditor:r??""});return a(u)?u:($e({userName:d,userId:l}),N({mode:f.DEFAULT}),c(`Username set to "${d}"`,null))}case oe.EDITOR:{if(!n)return i("No editor provided");let o=ot({preferredEditor:n});return a(o)?o:($e({preferredEditor:n}),N({mode:f.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case oe.VIEW:return n!=="wide"&&n!=="dense"?i("Invalid view mode"):($e({viewMode:n}),c(`View set to "${n}"`,null));case oe.AUTOSYNC:return Pd();case oe.LOG_LEVEL:return Dd();case oe.SYNC_DEBOUNCE_MS:return Md();default:return i("Unknown config command")}}},{intent:M.Coffee,description:"Sponsor the development of Epiq!",mode:f.COMMAND_LINE,action:()=>{let e=se().commandMeta.modifier;return e==="custom"?ss("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):ss(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),$(""),c("Thanks you!",null)}}]});var cp,Ke,ps=y(()=>{"use strict";bo();Lo();Hr();jd();b();de();he();w();cp=new Set(["peek","filter","view-help"]),Ke=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:o,inputString:r}}=se();if(!t)return i("No command to confirm");if(!e&&n===lt.Invalid)return i("Invalid command");let s=ba(t);xa();let{readOnly:d}=p();if(d&&!cp.has(s))return Pn({status:st.Fail,message:"Command not available in readonly state",value:null});let l=$d.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return Pn({status:st.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:r,modifier:o})}catch(m){return Pn({status:st.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?Pn(u):(ha({addToHistory:!e}),l.onSuccess?.(),Q().autoSync&&Yi(),u)}});var Ko,Yo,Wd,Hd=y(()=>{"use strict";b();J();w();ht();ps();us();de();Ko=[{intent:R.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(N({mode:f.COMMAND_LINE}),$("move cancel"),Ke({isForceExecutedBySystem:!0}))},{intent:R.InitMove,mode:f.DEFAULT,description:"[m] move (init/confirm)",action:()=>(N({mode:f.COMMAND_LINE}),$("move start"),Ke({isForceExecutedBySystem:!0}))},{intent:R.ConfirmMove,mode:f.MOVE,action:()=>(N({mode:f.COMMAND_LINE}),$("move confirm"),Ke({isForceExecutedBySystem:!0}))}],Yo=[{intent:R.MovePreviousItem,mode:f.MOVE,action:()=>gt()?(N({mode:f.COMMAND_LINE}),$("move previous"),Ke({isForceExecutedBySystem:!0})):i("No pending move")},{intent:R.MoveNextItem,mode:f.MOVE,action:()=>gt()?(N({mode:f.COMMAND_LINE}),$("move next"),Ke({isForceExecutedBySystem:!0})):i("No pending move")}],Wd=[{intent:R.MoveToNextContainer,mode:f.MOVE,action:()=>gt()?(N({mode:f.COMMAND_LINE}),$("move to-next"),Ke({isForceExecutedBySystem:!0})):i("No pending move")},{intent:R.MoveToPreviousContainer,mode:f.MOVE,action:()=>gt()?(N({mode:f.COMMAND_LINE}),$("move to-previous"),Ke({isForceExecutedBySystem:!0})):i("No pending move")}]});var Vd,zd=y(()=>{"use strict";te();Hd();Vd={[T.WORKSPACE]:[...Ko,...Yo],[T.BOARD]:[...Ko,...Yo],[T.SWIMLANE]:[...Ko,...Yo,...Wd],[T.TICKET]:[],[T.FIELD]:[],[T.FIELD_LIST]:[],[T.TEXT]:[],[T.COMMENT]:[]}});var qd,Gd,Kd=y(()=>{"use strict";J();b();de();w();Vo();ht();Le();qd=()=>{$("");let{pendingNavTarget:e}=sn();N({mode:f.DEFAULT}),e&&L.navigate(e),pt({pendingNavTarget:void 0})},Gd=[{intent:R.ExitCommandLine,mode:f.HELP,action:()=>(qd(),c("Exiting help",null))},{intent:R.Exit,mode:f.HELP,action:()=>(qd(),c("Closed help",null))},{intent:R.NavPreviousItem,mode:f.HELP,description:"[arrows/hjkl] navigate",action:()=>(L.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:R.NavNextItem,mode:f.HELP,action:()=>(L.navigateToNextItem(),c("Navigating to next help item",null))},{intent:R.NavToPreviousContainer,mode:f.HELP,action:()=>(L.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:R.NavToNextContainer,mode:f.HELP,action:()=>(L.navigateToNextContainer(),c("Navigating to next help container",null))}]});var lp,Yd,Xd,Jd=y(()=>{"use strict";J();te();b();de();w();Vo();ht();Le();lp=e=>{N({mode:f.COMMAND_LINE});let{pendingNavTarget:t}=sn();t&&L.navigate(t),pt({pendingNavTarget:void 0}),$(`${e} `)},Yd=()=>{$("");let{pendingNavTarget:e}=sn();e&&L.navigate(e),pt({pendingNavTarget:void 0}),N({mode:f.DEFAULT})},Xd=[{intent:R.InitCommandPalette,mode:f.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{$("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=p();return pt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}}),N({mode:f.PALETTE}),c("Opening command palette",null)}},{intent:R.Confirm,mode:f.PALETTE,action:()=>{let{selectedNode:e}=p();if(!e||!ei(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?(lp(t),c("Selected command",t)):c("No command selected",null)}},{intent:R.ExitCommandLine,mode:f.PALETTE,action:()=>(Yd(),c("Exiting palette",null))},{intent:R.Exit,mode:f.PALETTE,action:()=>(Yd(),c("Closed command palette",null))},{intent:R.NavPreviousItem,mode:f.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(L.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:R.NavNextItem,mode:f.PALETTE,action:()=>(L.navigateToNextItem(),c("Navigating to next item",null))},{intent:R.NavToPreviousContainer,mode:f.PALETTE,action:()=>(L.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:R.NavToNextContainer,mode:f.PALETTE,action:()=>(L.navigateToNextContainer(),c("Navigating to next container",null))}]});var Qd,Zd=y(()=>{"use strict";At();J();b();$t();We();de();w();ht();Kd();Jd();Le();Qd=[...Gd,...Xd,{intent:R.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(N({mode:f.COMMAND_LINE}),$(`${v.NEW} `),c("Adding new item",null))},{intent:R.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(N({mode:f.COMMAND_LINE}),$(`${v.DELETE} `),c("Deleting item",null))},{intent:R.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(N({mode:f.COMMAND_LINE}),$(""),c("Entering command line mode",null))},{intent:R.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=p();if(!K(e?.id??"")?.length){if(e?.title===ne.DESCRIPTION)return N({mode:f.COMMAND_LINE}),$(`${v.EDIT} description `),c("Propose command",!0);if(e?.title===ne.ASSIGNEES)return N({mode:f.COMMAND_LINE}),$(`${v.ASSIGN} `),c("Propose command",!0);if(e?.title===ne.TAGS)return N({mode:f.COMMAND_LINE}),$(`${v.TAG} `),c("Propose command",!0);if(t.title===ne.DESCRIPTION&&e?.context==="TEXT")return N({mode:f.COMMAND_LINE}),$(`${v.EDIT} description `),c("Propose command",!0)}return L.enterChildNode(),c("Entering context",null)}},{intent:R.EditTitle,mode:f.DEFAULT,description:"[r] rename title",action:()=>(N({mode:f.COMMAND_LINE}),$(`${v.EDIT} title ${p().selectedNode?.title}`),c("Exiting context",null))},{intent:R.EditDescription,mode:f.DEFAULT,description:"[e] edit description",action:()=>(N({mode:f.COMMAND_LINE}),$(`${v.EDIT} description `),c("Exiting context",null))},{intent:R.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(L.enterParentNode(),c("Exiting context",null))},{intent:R.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(L.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:R.NavNextItem,mode:f.DEFAULT,action:()=>(L.navigateToNextItem(),c("Navigating to next item",null))},{intent:R.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(L.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:R.NavToNextContainer,mode:f.DEFAULT,action:()=>(L.navigateToNextContainer(),c("Navigating to next container",null))}]});var up,mp,ec,tc=y(()=>{"use strict";de();up=500,mp=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),ec=e=>{let t=mp(e);t&&Jt(n=>(n+t).slice(0,up))}});var pp,gp,nc,oc=y(()=>{"use strict";tc();J();b();de();w();ht();ps();pp=[f.COMMAND_LINE,f.PALETTE],gp=e=>[{intent:R.MoveCursorLeft,mode:e,action:()=>(jr(-1),c("Moving cursor left",null))},{intent:R.MoveCursorRight,mode:e,action:()=>(jr(1),c("Moving cursor right",null))},{intent:R.MoveCursorLeftOfWord,mode:e,action:()=>(Wr("left"),c("Moving cursor left of word",null))},{intent:R.MoveCursorRightOfWord,mode:e,action:()=>(Wr("right"),c("Moving cursor right of word",null))},{intent:R.AutoCompleteCommand,mode:e,action:()=>(Jt((t,{remainder:n})=>{let o=n?t+n:t,r="";return o==="edit title "&&(r=p().selectedNode?.title??""),o+r}),c("Auto-completing command",null))},{intent:R.CaptureInput,mode:e,action:(t,{sequence:n})=>(ec(n??""),c("Capturing input",null))},{intent:R.EraseInput,mode:e,action:()=>(va(),c("Erasing input",null))},{intent:R.EraseInputWord,mode:e,action:()=>(ya(),c("Erasing input word",null))}],nc=[{intent:R.Confirm,mode:f.COMMAND_LINE,action:()=>(Ke(),c("Executing command",null))},{intent:R.ViewHelp,mode:f.DEFAULT,action:()=>(N({mode:f.HELP}),c("Viewing help",null))},...pp.flatMap(gp),{intent:R.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(N({mode:f.DEFAULT}),c("Exiting command line",null))},{intent:R.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Ia(),c("Getting last command from history",null))},{intent:R.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Na(),c("Getting next command from history",null))}]});import ic from"chalk";var Xo,rc,sc,gs,ac=y(()=>{"use strict";J();te();Ne();Xo=ic.dim.hex(C.secondary2)(": for command line"),rc="q to exit",sc=`${ic.hex(C.accent)("m")} to confirm`,gs={[T.WORKSPACE]:[Xo],[T.BOARD]:[Xo],[T.BOARD+f.COMMAND_LINE]:[Xo],[T.SWIMLANE]:[Xo],[T.TICKET+f.HELP]:[rc],[T.SWIMLANE+f.HELP]:[rc],[T.TICKET]:[],[T.FIELD]:[],[T.SWIMLANE+f.MOVE]:[sc],[T.TICKET+f.MOVE]:[sc]}});var Bn,fp,vp,dc,cc=y(()=>{"use strict";w();Bn=e=>e.trim().toLocaleLowerCase(),fp=e=>{let{tags:t}=p();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},vp=e=>{let{contributors:t}=p();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},dc=(e,t)=>{let n=Bn(t.value);if(!n)return!0;switch(t.target){case"title":return Bn(e.title??"").includes(n);case"description":return Bn(e.props.description??"").includes(n);case"tag":return fp(e).map(Bn).some(r=>r.includes(n));case"assignee":return vp(e).map(Bn).some(r=>r.includes(n));default:return!0}}});function lc(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 uc=y(()=>{"use strict";b()});var mc,pc=y(()=>{"use strict";mc=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 yp}from"react";function fc(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=lc(t,r,o);if(a(u))return logger.error(u.message),u;let m=u.value,{context:g}=l,x=gs[g+n]??gs[g]??[],E=[...Qd,...Vd[g]??[],...nc],A=mc(E),S=hp(r,s),k=S[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:x,availableActions:E,actionIndex:A,selectedNode:k,renderedChildrenIndex:S})}function Sn(e){fs=e;let t=it(process.cwd()),n=!1;if(!a(t)){let s=dt(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:[],timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{}},r=fc(o);return a(r)?r:(Pt=r.value,gc(),c("State initialized",null))}function me(e){let t=p(),n=e(t),o=fc(n);return a(o)?i(o.message??"Unable to update state"):(Pt=o.value,gc(),c("State updated",null))}var Pt,fs,vs,gc,xp,p,He,N,De,hp,q,Un,Gt,w=y(()=>{"use strict";zd();Zd();oc();ac();yt();J();te();b();ce();cc();uc();pc();vs=new Set,gc=()=>{for(let e of vs)e()},xp=e=>(vs.add(e),()=>vs.delete(e));p=()=>{if(!Pt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Pt},He=()=>Pt?c("Retrieved state",Pt):i("State not initialized. Call initWorkspaceState() first.");N=e=>me(t=>({...t,...e})),De=()=>yp(xp,p,p),hp=(e,t)=>{let n={};for(let o of Object.values(e))D(o)&&t.length>0&&!t.every(r=>dc(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},q=e=>p()?.renderedChildrenIndex[e]??[],Un=()=>fs?Sn(fs):i("Cannot reset state: no initial workspace found"),Gt=()=>Pt!==void 0});var ys,Jo,Qo,xs,Pe,No=y(()=>{"use strict";Zs();b();w();ys=e=>{Gt()&&(N({syncStatus:e}),Qs({type:"sync-status",payload:e}))},Jo=(e="Syncing...")=>{ys({status:"syncing",msg:e})},Qo=(e="Synced")=>{ys({status:"synced",msg:e})},xs=e=>{ys({status:"failed",msg:e})},Pe=e=>(xs(e),i(e))});import{decodeTime as dA}from"ulid";var vc=y(()=>{"use strict";b()});var Ip,Np,Eo,wr=y(()=>{"use strict";b();No();Ar();Yn();vt();xt();ro();vc();Ip=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=z("getRepoRootDir",await at(e));if(a(n))return i(n.message);let o=n.value;logger.debug("[sync] repo root",o);let r=z("getStateBranchRoot",Qe({repoRoot:o}));if(a(r))return i(r.message);let s=r.value;logger.debug("[sync] state branch root",s);let d=z("ensureInitialCommit",await Ys(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=z("bootstrapStateBranchStorage",await Js({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=z("hasInProgressGitOperation(stateBranchRoot)",await Jn(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=z("ensureStateBranchLayout",qs(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}))},Np=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=z("stageStateBranchOwnEventFile",await oo({stateBranchRoot:t,eventFileName:n}));if(a(o))return i(o.message);let r=z("hasStagedChanges(after stage)",await $s(t));if(a(r))return i(r.message);if(logger.debug("[sync] state branch change check after stage result",{changed:r.value}),!r.value)return logger.info("[sync] no own event file changes to commit"),c("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let s=z("createStateBranchSyncCommit",await Xs({repoRoot:e,stateBranchRoot:t}));return a(s)?i(s.message):(logger.debug("[sync] created sync commit",s.value),c("Committed own event file",{createdCommit:!0,commitSha:s.value}))},Eo=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");Jo();let n=z("ensureSyncReady",await Ip({cwd:e,ensureUpstream:!0}));if(a(n))return Pe(n.message);let{repoRoot:o,stateBranchRoot:r,bootstrapped:s}=n.value,d=z("isDetachedHead(stateBranchRoot)",await js(r));if(a(d))return Pe(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return Pe("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,g=!1,x=z("getStateBranch",Dt(o));if(a(x))return Pe(x.message);let E=x.value;logger.debug("[sync] resolved state branch",{stateBranch:E,stateBranchRoot:r});let A=z("commitOwnEventFileToStateBranch",await Np({repoRoot:o,stateBranchRoot:r,ownEventFileName:t}));if(a(A))return Pe(A.message);l=A.value.createdCommit,u=A.value.commitSha;let S=z("pullBranchRebaseIfPresent",await ur({cwd:r,branch:E}));if(a(S))return Pe(S.message);if(m=S.value,l||s){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:s,stateBranchRoot:r});let k=z("pushStateBranch",await vn({stateBranchRoot:r,repoRoot:o}));if(a(k)&&_s(k.message)){let _=z("pullBranchRebaseIfPresent(retry)",await ur({cwd:r,branch:E}));if(a(_))return Pe(_.message);m=m||_.value,k=z("pushStateBranch(retry)",await vn({stateBranchRoot:r,repoRoot:o}))}if(a(k))return Pe(k.message);g=k.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:r});let k=z("git rev-parse HEAD",await U({args:["rev-parse","HEAD"],cwd:r}));if(a(k))return Pe(k.message);u=k.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Qo(g?"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:g,bootstrapped:s})}});import{decodeTime as AA,ulid as hs}from"ulid";var Is,kt,_n,$n,Ep,bp,yc,xc,hc,Ic,Nc,Ec,bc,Cc,Sc,Rc=y(()=>{"use strict";vt();xt();ro();wr();rn();ms();ho();Rn();Rt();Fe();os();bn();te();b();yt();ie();We();w();No();ce();ct();Ut();un();Is=e=>{let t=it(e??process.cwd());return a(t)?i(t.message):c("Resolved Epiq repo root",t.value)},kt=async e=>{let t=Is(e);if(a(t))return t;let n=Qe({repoRoot:t.value});if(a(n))return i(n.message);let o=Gn(),r=await fn({repoRoot:t.value,stateBranchRoot:n.value,stateBranchName:o.stateBranch});if(a(r))return i(r.message);let s=await U({cwd:n.value,args:["pull","--ff-only"]});a(s)&&le.info(3,s.message);let d=Ct(n.value);if(a(d))return i(d.message);let l=wn(d.value);return a(l)?i(l.message):c("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:n.value})},_n=()=>{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")},$n=()=>{let e=He();return a(e)?i(e.message):e},Ep=e=>(e.props.tags??[]).map(t=>I.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Ee(t.name)})),bp=e=>(e.props.assignees??[]).map(t=>I.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Ee(t.name)})),yc=async(e={})=>{let t=await kt(e.repoRoot);if(a(t))return t;let n=$n();if(a(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="BOARD").map(r=>({id:r.id,title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return c("Listed boards",o)},xc=async(e={})=>{let t=await kt(e.repoRoot);if(a(t))return t;let n=$n();if(a(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="SWIMLANE").filter(r=>!e.boardId||r.parentNodeId===e.boardId).map(r=>({id:r.id,title:r.title,boardId:r.parentNodeId,isClosed:r.id===ye,readonly:!!r.readonly}));return c("Listed swimlanes",o)},hc=async e=>{let t=await kt(e.repoRoot);if(a(t))return t;let n=$n();if(a(n))return n;let o=Object.values(n.value.nodes).filter(D).filter(r=>e.includeClosed||r.parentNodeId!==ye).map(r=>({id:r.id,title:ao(r.title),description:r.props.description??"",parentNodeId:r.parentNodeId,isClosed:r.parentNodeId===ye,readonly:!!r.readonly,tags:Ep(r),assignees:bp(r)}));return c("Listed issues",o)},Ic=async e=>{let t=await kt(e.repoRoot);if(a(t))return t;let n=_n();if(a(n))return n;let o=zt(e.parentId,n.value,t.value.stateBranchRoot);if(a(o))return o;let r=qo({name:e.title,parent:e.parentId,user:n.value,rank:o.value});if(a(r))return r;let s=r.value,d=j([...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")},Nc=async e=>{let t=await kt(e.repoRoot);if(a(t))return t;let n=_n();if(a(n))return n;let o=Vt(ye,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(o))return o;let r={id:hs(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ye,rank:o.value}},s=j([r],t.value.stateBranchRoot);return a(s)?i(s.message):c("Closed issue",{id:e.issueId})},Ec=async e=>{let t=Is(e.repoRoot);if(a(t))return t;let n=_n();if(a(n))return n;let o=Qe({repoRoot:t.value});if(a(o))return o;let r=Ct(o.value);if(a(r))return r;let s=wn(r.value);if(a(s))return s;let d=Vt(e.parentId,e.issueId,e.position??{at:"end"},n.value,o.value);if(a(d))return d;let l={id:hs(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:d.value}},u=j([l],o.value);return a(u)?i(u.message):c("Moved issue",{id:e.issueId,parentId:e.parentId})},bc=async(e={})=>{Jo();let t=Is(e.repoRoot);if(a(t))return i("Sync failed");let n=_n();if(a(n))return n;let o=await Eo({cwd:t.value,ownEventFileName:St(n.value)});return a(o)?(xs(o.message),o):(Qo(),c("Synced",o.value))},Cc=async(e={})=>{let t=await kt(e.repoRoot);if(a(t))return t;let n=$n();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})},Sc=async e=>{let t=await kt(e.repoRoot);if(a(t))return t;let n=_n();if(a(n))return n;let o=$n();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!D(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:hs(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},l=j([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited issue description",{id:e.issueId,description:e.description})}});var wc={};Dc(wc,{createMcpServer:()=>Ac,resultJson:()=>Ye,startMcpServer:()=>Tc});import{McpServer as Cp}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Sp}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as F}from"zod";var Ye,Ac,Tc,Mc=y(async()=>{"use strict";b();Rc();Ye=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Ac=()=>{let e=new Cp({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:F.object({repoRoot:F.string().optional()})},async t=>Ye(await Cc(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:F.object({repoRoot:F.string().optional(),includeClosed:F.boolean().optional()})},async t=>Ye(await hc(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>Ye(await yc(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:F.object({repoRoot:F.string().optional(),boardId:F.string().optional()})},async t=>Ye(await xc(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue",inputSchema:F.object({title:F.string().min(1),parentId:F.string().min(1),repoRoot:F.string().optional()})},async t=>Ye(await Ic(t))),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:F.object({issueId:F.string().min(1),description:F.string(),repoRoot:F.string().optional()})},async t=>Ye(await Sc(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:F.object({issueId:F.string().min(1),repoRoot:F.string().optional()})},async t=>Ye(await Nc(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:F.object({issueId:F.string().min(1),parentId:F.string().min(1),position:F.discriminatedUnion("at",[F.object({at:F.literal("start")}),F.object({at:F.literal("end")}),F.object({at:F.literal("before"),sibling:F.string().min(1)}),F.object({at:F.literal("after"),sibling:F.string().min(1)})]).optional(),repoRoot:F.string().optional()})},async t=>Ye(await Ec(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>Ye(await bc(t))),e},Tc=async()=>{let e=Ac(),t=new Sp;await e.connect(t)};await Tc()});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;await Mc().then(()=>wc);