epiq 0.6.10 → 0.6.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +33 -33
  2. package/dist/mcp.js +40 -40
  3. package/package.json +1 -1
package/dist/mcp.js CHANGED
@@ -1,62 +1,62 @@
1
1
  #!/usr/bin/env node
2
- var Ac=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var wc=(e,t)=>{for(var n in t)Ac(e,n,{get:t[n],enumerable:!0})};var Je,s,c,a,Yt,S=y(()=>{"use strict";Je={None:"none",Success:"success",Fail:"fail"},s=e=>({status:Je.Fail,message:e,value:null}),c=(e,t)=>({status:Je.Success,message:e,value:t}),a=e=>e.status==="fail",Yt=e=>e.status==="success"});function Wr(e){return e.context===w.WORKSPACE}function $(e){return e.context===w.TICKET}function li(e){return e.context===w.TEXT}function Qe(e){return e.context===w.FIELD}function Xt(e){return e.context===w.FIELD_LIST}var w,wn,ui,te=y(()=>{"use strict";w={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};wn=e=>e.context===w.SWIMLANE,ui=e=>e.context===w.BOARD});function mi(e){return!e||!Mc.test(e)?s(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Se(e,t=Ct){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 Se(We/2n,Ct);let n=e?mi(e):c("Resolved lower bound",0n);if(a(n))return n;let r=t?mi(t):c("Resolved upper bound",We);if(a(r))return r;let o=n.value,i=r.value;if(i<=o)return Se(We/2n,Ct);let d=(o+i)/2n;return d===o||d===i?s("No rank space available between neighbors"):Se(d,Ct)}function pi(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=We*BigInt(r+1)/(t+1n),i=Se(o,Ct);if(a(i))return i;n.push(i.value)}return c("Resolved evenly spaced ranks",n)}var Ct,Tc,We,Mc,Rt=y(()=>{"use strict";S();Ct=24n,Tc=Ct*4n,We=(1n<<Tc)-1n,Mc=/^[0-9a-f]+$/});import{ulid as Lc}from"ulid";var jr,gi=y(()=>{"use strict";S();Ce();Rt();jr=(e,t)=>{let n=H(e),r=pi(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:Lc(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})}});import Jt from"node:fs";import{ulid as Pc}from"ulid";import{z as Tn}from"zod";var kc,Dc,fi,Ze,vi,yi,At=y(()=>{"use strict";S();ne();kc="__epiq_state__",Dc=Tn.object({projectId:Tn.string().min(1),stateBranch:Tn.string().min(1),createdAt:Tn.iso.datetime()}),fi=()=>({projectId:Pc(),stateBranch:kc,createdAt:new Date().toISOString()}),Ze=e=>{let t=Ln(e);if(!Jt.existsSync(t))return s("Missing .epiq/project.json");try{let n=Jt.readFileSync(t,"utf8"),r=JSON.parse(n),o=Dc.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")}},vi=e=>{let t=Ze(e);return a(t)?s(t.message):c("Read projectId",t.value.projectId)},yi=({repoRoot:e,fileContents:t})=>{let n=Mn(e),r=Ln(e);try{if(Jt.mkdirSync(n,{recursive:!0}),Jt.existsSync(r)){let o=Ze(e);return a(o)?s(o.message):c("Project already initialized",null)}return Jt.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 Hr,xi=y(()=>{"use strict";S();Hr=(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 Qt from"fs";import qr from"path";import Fc from"util";function Uc(){let e=Ni();if(!e||!Qt.existsSync(e))return;let n=Qt.readFileSync(e,"utf8").split(`
4
- `);if(n[n.length-1]===""&&n.pop(),n.length<=hi)return;let r=n.slice(-hi).join(`
2
+ var wc=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var Tc=(e,t)=>{for(var n in t)wc(e,n,{get:t[n],enumerable:!0})};var Qe,s,c,a,Xt,S=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",Xt=e=>e.status==="success"});function jr(e){return e.context===w.WORKSPACE}function $(e){return e.context===w.TICKET}function ui(e){return e.context===w.TEXT}function Ze(e){return e.context===w.FIELD}function Jt(e){return e.context===w.FIELD_LIST}var w,Mn,mi,te=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,mi=e=>e.context===w.BOARD});function pi(e){return!e||!Lc.test(e)?s(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Se(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 Se(He/2n,Rt);let n=e?pi(e):c("Resolved lower bound",0n);if(a(n))return n;let r=t?pi(t):c("Resolved upper bound",He);if(a(r))return r;let o=n.value,i=r.value;if(i<=o)return Se(He/2n,Rt);let d=(o+i)/2n;return d===o||d===i?s("No rank space available between neighbors"):Se(d,Rt)}function gi(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=Se(o,Rt);if(a(i))return i;n.push(i.value)}return c("Resolved evenly spaced ranks",n)}var Rt,Mc,He,Lc,At=y(()=>{"use strict";S();Rt=24n,Mc=Rt*4n,He=(1n<<Mc)-1n,Lc=/^[0-9a-f]+$/});import{ulid as Pc}from"ulid";var Hr,fi=y(()=>{"use strict";S();Ce();At();Hr=(e,t)=>{let n=H(e),r=gi(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:Pc(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})}});import Qt from"node:fs";import{ulid as kc}from"ulid";import{z as Ln}from"zod";var Dc,Fc,vi,et,yi,xi,wt=y(()=>{"use strict";S();ne();Dc="__epiq_state__",Fc=Ln.object({projectId:Ln.string().min(1),stateBranch:Ln.string().min(1),createdAt:Ln.iso.datetime()}),vi=()=>({projectId:kc(),stateBranch:Dc,createdAt:new Date().toISOString()}),et=e=>{let t=kn(e);if(!Qt.existsSync(t))return s("Missing .epiq/project.json");try{let n=Qt.readFileSync(t,"utf8"),r=JSON.parse(n),o=Fc.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")}},yi=e=>{let t=et(e);return a(t)?s(t.message):c("Read projectId",t.value.projectId)},xi=({repoRoot:e,fileContents:t})=>{let n=Pn(e),r=kn(e);try{if(Qt.mkdirSync(n,{recursive:!0}),Qt.existsSync(r)){let o=et(e);return a(o)?s(o.message):c("Project already initialized",null)}return Qt.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,hi=y(()=>{"use strict";S();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 Zt from"fs";import Gr from"path";import Oc from"util";function Bc(){let e=Ii();if(!e||!Zt.existsSync(e))return;let n=Zt.readFileSync(e,"utf8").split(`
4
+ `);if(n[n.length-1]===""&&n.pop(),n.length<=Ei)return;let r=n.slice(-Ei).join(`
5
5
  `)+`
6
- `;Qt.writeFileSync(e,r,"utf8")}function Vr(e,t,n=!1){let r=Ni();if(!r)return;let o=Fc.format(...t),i=new Date,l=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
7
- `;Qt.mkdirSync(qr.dirname(r),{recursive:!0}),Qt.appendFileSync(r,l,"utf8"),zr++,zr>=Oc&&(zr=0,Uc())}var hi,Oc,zr,Ei,Ni,Kr,ce,Pn=y(()=>{"use strict";S();ne();hi=1e3,Oc=50,zr=0,Ei=()=>process.env.EPIQ_MCP==="true",Ni=()=>{let e=process.cwd(),t=kn(e);return a(t)?Ei()?qr.join(process.cwd(),".epiq-mcp.log"):void 0:qr.join(t.value,je,"log","epiq.log")};Kr=()=>Ei()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",ce={info(...e){let t=Kr();(t==="info"||t==="debug")&&Vr("[Info]",e,!1)},debug(...e){Kr()==="debug"&&Vr("[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;Vr("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=ce});var q,Dn=y(()=>{"use strict";wt();q={stage:({cwd:e,pathspec:t})=>O({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>O({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>O({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>O({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>O({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 O({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>O({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>O({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>O({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>O({args:["worktree","prune"],cwd:e})}});var lt,pe,Fn=y(()=>{"use strict";At();S();ne();lt=e=>{let t=et(e);if(a(t))return s("Unable to resolve epiq project root");let n=Ze(t.value);return a(n)?s("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},pe="origin"});import{spawn as Bc}from"node:child_process";import On from"node:fs";import Zt from"node:path";var Ii,_c,Si,O,Re,Tt,$c,Wc,Un,Gr,en,Bn,bi,Ci,Yr,_n,Ri,Ai,wi,Ti,Xr,Mi,Li,wt=y(()=>{"use strict";S();Dn();Fn();Ii=1e4,_c={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Si=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!On.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=Bc("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:_c}),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 ${Ii}ms`].join(`
8
- `);u(n?{stdout:d,stderr:g,exitCode:124}:s(g))},Ii);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(`
6
+ `;Zt.writeFileSync(e,r,"utf8")}function Kr(e,t,n=!1){let r=Ii();if(!r)return;let o=Oc.format(...t),i=new Date,l=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
7
+ `;Zt.mkdirSync(Gr.dirname(r),{recursive:!0}),Zt.appendFileSync(r,l,"utf8"),Vr++,Vr>=Uc&&(Vr=0,Bc())}var Ei,Uc,Vr,Ni,Ii,qr,ce,Dn=y(()=>{"use strict";S();ne();Ei=1e3,Uc=50,Vr=0,Ni=()=>process.env.EPIQ_MCP==="true",Ii=()=>{let e=process.cwd(),t=Fn(e);return a(t)?Ni()?Gr.join(process.cwd(),".epiq-mcp.log"):void 0:Gr.join(t.value,ze,"log","epiq.log")};qr=()=>Ni()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",ce={info(...e){let t=qr();(t==="info"||t==="debug")&&Kr("[Info]",e,!1)},debug(...e){qr()==="debug"&&Kr("[Debug]",e,!0)},error(...e){let t=qr();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;Kr("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=ce});var q,On=y(()=>{"use strict";Tt();q={stage:({cwd:e,pathspec:t})=>O({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>O({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>O({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>O({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>O({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 O({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>O({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>O({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>O({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>O({args:["worktree","prune"],cwd:e})}});var ut,pe,Un=y(()=>{"use strict";wt();S();ne();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 _c}from"node:child_process";import Bn from"node:fs";import en from"node:path";var bi,$c,Ci,O,Re,Mt,Wc,jc,_n,Yr,tn,$n,Si,Ri,Xr,Wn,Ai,wi,Ti,Mi,Jr,Li,Pi,Tt=y(()=>{"use strict";S();On();Un();bi=1e4,$c={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Ci=({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=_c("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:$c}),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 ${bi}ms`].join(`
8
+ `);u(n?{stdout:d,stderr:g,exitCode:124}:s(g))},bi);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
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}))})}),O=({args:e,cwd:t})=>Si({args:e,cwd:t,allowFail:!1}),Re=({args:e,cwd:t})=>Si({args:e,cwd:t,allowFail:!0}),Tt=async({cwd:e,message:t})=>{let n=await q.commit({cwd:e,message:t});if(a(n))return s(`Failed to create commit
10
+ `)));return}u(c("Git command succeeded",{stdout:d,stderr:l,exitCode:x}))})}),O=({args:e,cwd:t})=>Ci({args:e,cwd:t,allowFail:!1}),Re=({args:e,cwd:t})=>Ci({args:e,cwd:t,allowFail:!0}),Mt=async({cwd:e,message:t})=>{let n=await q.commit({cwd:e,message:t});if(a(n))return s(`Failed to create commit
11
11
  ${n.message}`);let r=await O({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())},$c=async e=>{let t=await O({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",Zt.isAbsolute(n)?n:Zt.resolve(e,n))},Wc=async e=>{let t=await $c(e);if(a(t))return s(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress",REBASE_HEAD:"rebase in progress",CHERRY_PICK_HEAD:"cherry-pick in progress",REVERT_HEAD:"revert in progress",BISECT_LOG:"bisect in progress"};for(let[u,m]of Object.entries(r))if(On.existsSync(Zt.join(n,u)))return c("Checked for in-progress Git operation",m);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[u,m]of Object.entries(o))if(On.existsSync(Zt.join(n,u)))return c("Checked for in-progress Git operation",m);let i=await O({cwd:e,args:["status","--porcelain=v1","--branch"]});if(a(i))return s(i.message);let d=i.value.stdout.toLowerCase(),l=["rebase in progress","merge in progress","cherry-pick in progress","revert in progress","bisect in progress"].find(u=>d.includes(u));return c("Checked for in-progress Git operation",l??null)},Un=async e=>{let t=await Wc(e);return a(t)?s(t.message):c("Checked for in-progress Git operation",t.value!==null)},Gr=async({repoRoot:e})=>{let n=(await Re({args:["remote","get-url",pe],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},en=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)},Bn=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}`)},bi=e=>{try{return On.realpathSync.native(e)}catch{return Zt.resolve(e)}},Ci=async({repoRoot:e,worktreeRoot:t})=>{let n=await O({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return s(n.message);let r=bi(t),o=n.value.stdout.split(`
13
- `).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(bi).includes(r);return c("Checked worktree registration",o)},Yr=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)},_n=async e=>{let t=await O({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?s(t.message):c("Resolved current branch",t.value.stdout.trim())},Ri=async e=>{let t=await O({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?s(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},Ai=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),wi=async e=>(await Re({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1),Ti=async({cwd:e,branch:t})=>{let n=await en({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 q.fetch({cwd:e,remote:pe,branch:t});if(a(r))return s(`Failed to fetch ${t}
14
- ${r.message}`);let o=await wi(e);if(a(o))return s(o.message);let i=await O({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)},Xr=async({cwd:e,branch:t})=>{let n=await en({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 wi(e);if(a(r))return s(r.message);let o=await q.fetch({cwd:e,remote:pe,branch:t});if(a(o))return s(`Failed to fetch ${t}
12
+ ${r.message}`):c("Created commit and resolved SHA",r.value.stdout.trim())},Wc=async e=>{let t=await O({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",en.isAbsolute(n)?n:en.resolve(e,n))},jc=async e=>{let t=await Wc(e);if(a(t))return s(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress",REBASE_HEAD:"rebase in progress",CHERRY_PICK_HEAD:"cherry-pick in progress",REVERT_HEAD:"revert in progress",BISECT_LOG:"bisect in progress"};for(let[u,m]of Object.entries(r))if(Bn.existsSync(en.join(n,u)))return c("Checked for in-progress Git operation",m);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[u,m]of Object.entries(o))if(Bn.existsSync(en.join(n,u)))return c("Checked for in-progress Git operation",m);let i=await O({cwd:e,args:["status","--porcelain=v1","--branch"]});if(a(i))return s(i.message);let d=i.value.stdout.toLowerCase(),l=["rebase in progress","merge in progress","cherry-pick in progress","revert in progress","bisect in progress"].find(u=>d.includes(u));return c("Checked for in-progress Git operation",l??null)},_n=async e=>{let t=await jc(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)},tn=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}`)},Si=e=>{try{return Bn.realpathSync.native(e)}catch{return en.resolve(e)}},Ri=async({repoRoot:e,worktreeRoot:t})=>{let n=await O({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return s(n.message);let r=Si(t),o=n.value.stdout.split(`
13
+ `).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(Si).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 O({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?s(t.message):c("Resolved current branch",t.value.stdout.trim())},Ai=async e=>{let t=await O({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?s(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},wi=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Ti=async e=>(await Re({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1),Mi=async({cwd:e,branch:t})=>{let n=await tn({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 q.fetch({cwd:e,remote:pe,branch:t});if(a(r))return s(`Failed to fetch ${t}
14
+ ${r.message}`);let o=await Ti(e);if(a(o))return s(o.message);let i=await O({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 tn({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 Ti(e);if(a(r))return s(r.message);let o=await q.fetch({cwd:e,remote:pe,branch:t});if(a(o))return s(`Failed to fetch ${t}
16
16
  ${o.message}`);let i=await q.pullRebase({cwd:e,remote:pe,branch:t});return a(i)?s(`Failed during pull --rebase
17
- ${i.message}`):c("Pulled with rebase",!0)},Mi=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")},Li=async e=>{let t=await _n(e);return a(t)?s(t.message):c("Checked detached HEAD state",t.value==="HEAD")}});import Jr from"node:fs";import jc from"node:os";import Le from"node:path";var ki,nn,Di,$n,Mt,Hc,Pi,tn,Wn,Fi,Oi,Ui,tt,cg,Lt=y(()=>{"use strict";At();S();ne();xi();Pn();wt();ki="4b825dc642cb6eb9a060e54bf8d69288fbee4904",nn=e=>Le.join(je,jn,e),Di=()=>Le.join(jc.homedir(),Ee),$n=()=>Le.join(Di(),"worktrees"),Mt=({repoRoot:e})=>{let t=vi(e);return a(t)?s(t.message):c("Resolved state branch root",Le.join($n(),t.value))},Hc=e=>Le.join(e,je),Pi=e=>Le.join(Hc(e),jn),tn=e=>{try{return Jr.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return s(t instanceof Error?t.message:String(t))}},Wn=()=>{let e=tn(Di());if(a(e))return s(`Ensure epiq home failed.
18
- `+e.message);let t=tn($n());return a(t)?s(`Ensure worktrees dir failed.
19
- `+t.message):c("Ensured epiq storage",!0)},Fi=e=>{Jr.existsSync(e)&&(ce.debug("[sync] remove path",e),Jr.rmSync(e,{recursive:!0,force:!0}))},Oi=(e,t)=>{for(let n of[Pi(e),Pi(t)]){let r=tn(n);if(a(r))return s(r.message)}return c("Ensured state branch",void 0)},Ui=async e=>{let t=await O({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return s(`ensure state branch is storage only failed
17
+ ${i.message}`):c("Pulled with rebase",!0)},Li=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")},Pi=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 Hc from"node:os";import Pe from"node:path";var Di,rn,Fi,jn,Lt,zc,ki,nn,Hn,Oi,Ui,Bi,nt,cg,Pt=y(()=>{"use strict";wt();S();ne();hi();Dn();Tt();Di="4b825dc642cb6eb9a060e54bf8d69288fbee4904",rn=e=>Pe.join(ze,zn,e),Fi=()=>Pe.join(Hc.homedir(),Ee),jn=()=>Pe.join(Fi(),"worktrees"),Lt=({repoRoot:e})=>{let t=yi(e);return a(t)?s(t.message):c("Resolved state branch root",Pe.join(jn(),t.value))},zc=e=>Pe.join(e,ze),ki=e=>Pe.join(zc(e),zn),nn=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=nn(Fi());if(a(e))return s(`Ensure epiq home failed.
18
+ `+e.message);let t=nn(jn());return a(t)?s(`Ensure worktrees dir failed.
19
+ `+t.message):c("Ensured epiq storage",!0)},Oi=e=>{Qr.existsSync(e)&&(ce.debug("[sync] remove path",e),Qr.rmSync(e,{recursive:!0,force:!0}))},Ui=(e,t)=>{for(let n of[ki(e),ki(t)]){let r=nn(n);if(a(r))return s(r.message)}return c("Ensured state branch",void 0)},Bi=async e=>{let t=await O({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return s(`ensure state branch is storage only failed
20
20
  `+t.message);let r=t.value.stdout.trim().split(`
21
- `).filter(Boolean).filter(d=>d!==je);if(r.length===0)return c("State branch is storage-only",!1);let o=await O({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(a(o))return s(`Failed to clean storage branch
22
- ${o.message}`);let i=await Tt({cwd:e,message:"[epiq:repair-storage-branch]"});return a(i)?s(i.message):c("Cleaned storage branch",!0)},tt=Hr(async(e=process.cwd())=>{let t=await O({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=>Le.resolve(e)),cg=Hr(async e=>{let t=await O({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return s(t.message);let n=t.value.stdout.trim(),r=Le.isAbsolute(n)?n:Le.join(e,n);return c("Resolved git dir",r)},e=>Le.resolve(e))});import rn from"node:fs";import He from"node:path";var vg,je,Ee,jn,zc,Mn,Ln,on,Bi,Vc,Qr,kn,et,_i,Ae,ne=y(()=>{"use strict";S();Lt();vg=process.env.IS_LOCAL==="true",je=".epiq",Ee=".epiq-global",jn="events",zc="project.json",Mn=e=>He.join(e,je),Ln=e=>He.join(Mn(e),zc),on=e=>He.join(Mn(e),jn),Bi=e=>He.join(e,je),Vc=e=>{let t=He.join(e,je);return rn.existsSync(t)&&rn.statSync(t).isDirectory()},Qr=e=>{let t=Ln(e);return rn.existsSync(t)&&rn.statSync(t).isFile()},kn=e=>{let t=He.resolve(e);for(;;){if(Vc(t))return c("Resolved closest .epiq root",t);let n=He.dirname(t);if(n===t)return s("No .epiq directory found in any parent");t=n}},et=e=>{let t=He.resolve(e);for(;;){if(Qr(t))return c("Resolved closest epiq project root",t);let n=He.dirname(t);if(n===t)return s("No .epiq/project.json found in any parent");t=n}},_i=e=>{let t=on(e);try{return rn.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 tt(process.cwd());if(a(e))return e;let t=Mt({repoRoot:e.value});return a(t)?t:c("Resolved persist root",t.value)}});var Q,Pt=y(()=>{"use strict";Q={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 $i=y(()=>{"use strict";ut()});function Hn(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var zn,Vn,kt=y(()=>{"use strict";zn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Vn=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var Wi,ji,Hi=y(()=>{"use strict";Wi=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),i=t.get(o);i?i.push(n):t.set(o,[n])}return t},ji=(e,t)=>t?e.get(t)??[]:[]});var zi,Kc,Vi,Ki=y(()=>{"use strict";kt();Hi();zi=new WeakMap,Kc=e=>{let t=zi.get(e);return t||(t=Wi(e),zi.set(e,t)),t},Vi=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return ji(Kc(e),r).filter(i=>Hn(r,i)>=n)}});var qc,qi,Gc,Gi=y(()=>{"use strict";kt();Ki();qc={hint:"",hints:[],overlap:0,remainder:""},qi=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return qc;let o=Vi({wordList:r,inputToMatch:e,overlapThreshold:1});return Gc(t,o)},Gc=(e,t)=>{let n=t[0]??"",r=Hn(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 Pg}from"react";var Kn,Yc,Xc,Y,Pe,ge=y(()=>{"use strict";Kn={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Yc=new Set,Xc=()=>{for(let e of Yc)e()},Y=()=>Kn,Pe=e=>(Kn={...Kn,...e},Xc(),Kn)});var Dt,Yi,Xi,Zr,eo,sn,to,Jc,Ji,Qc,Qi,qn=y(()=>{"use strict";S();ge();T();Gn();Dt=3e3,Yi=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Dt?null:t},Xi=0,eo=!1,sn=!1,to=()=>{if(eo)return!0;let e=ke();return a(e)?!1:e.value.syncStatus.status==="syncing"},Jc=()=>{let e=Y().autoSyncIntervalMs??1e4,t=Date.now()-Xi;return Math.max(0,e-t)},Ji=()=>{Zr||(Zr=setTimeout(async()=>{if(Zr=void 0,!!Ft()){if(to()){sn=!0;return}sn=!1,await Qc()}},Jc()))},Qc=async()=>{if(v().readOnly||v().timeMode==="peek")return s("Cannot auto-sync while peeking");if(!Ft())return s("Cannot auto-sync before state is initialized");if(to())return sn=!0,s("Sync already in progress");eo=!0,Xi=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await nt()}finally{eo=!1,sn&&Ji()}},Qi=()=>{Ft()&&(sn=!0,!to()&&Ji())}});var Yn,Zi,es,ts,an=y(()=>{"use strict";S();At();ge();ne();Yn=()=>{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}},Zi=()=>{let e=et(process.cwd());if(a(e))return!1;let t=Ze(e.value);return Yt(t)},es=e=>e===!0?"on":e===!1?"off":null,ts=e=>e==="on"?!0:e==="off"?!1:null});var ie,L,xe=y(()=>{"use strict";ie={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"},L={accent:ie.cyan,accent2:ie.magenta,primary:ie.white,secondary:ie.grayDark,secondary2:ie.grayLight,gray:ie.gray,green:ie.green,yellow:ie.yellow,red:ie.red}});var h,mt,Xn=y(()=>{"use strict";xe();h={red:ie.red,yellow:ie.yellow,green:ie.green,blue:ie.blue,magenta:ie.magenta,cyan:ie.cyan},mt={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 Zc,el,no,ro,Jn,Qn,Zn=y(()=>{"use strict";te();S();se();T();Zc=e=>e.props.tags??[],el=e=>e.props.assignees??[],no=e=>Zc(e).map(t=>N.getTag(t)).filter(t=>!!t),ro=e=>el(e).map(t=>N.getContributor(t)).filter(t=>!!t),Jn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!$(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",no(n))},Qn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!$(n)?s("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",ro(n))}});var f,pt=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",NONE:""}});var tl,nl,rl,ol,il,er,ns,sl,rs,tr=y(()=>{"use strict";tl=/^(\d+)(h|d|w|mo|y)$/,nl=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,rl=({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},ol=(e,t=new Date)=>{let n=e.match(tl);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}},il=e=>{let t=e.match(nl);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 rl({year:l,month:u,day:m,hour:g,minute:x})?new Date(l,u-1,m,g,x):null},er=e=>{let t=e.trim().toLowerCase();return ol(t)??il(t)},ns=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,sl=[{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}],rs=(e=sl)=>{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 al,X,rt,dl,cl,io,gt,nr,oo,os,ll,ul,ml,ae,dn=y(()=>{"use strict";qn();an();se();T();Xn();Zn();pt();tr();al=["BOARD","TICKET","SWIMLANE"],X={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},rt={TITLE:"title",DESCRIPTION:"description"},dl=[X.EDITOR,X.VIEW,X.USERNAME,X.AUTOSYNC,X.SYNC_DEBOUNCE_MS,X.LOG_LEVEL],cl=[rt.TITLE,rt.DESCRIPTION],io=[String(Dt),"5000","15000","30000","60000"],gt=[f.EXIT,f.SYNC,f.HELP,f.EXPORT,f.CONFIG],nr=[f.NEW,f.EDIT,f.DELETE,f.MOVE],oo=[f.TAG,f.UNTAG,f.ASSIGN,f.UNASSIGN,f.CLOSE_ISSUE,f.RE_OPEN_ISSUE,f.EDIT],os=[f.FILTER,f.PEEK],ll={WORKSPACE:[...gt,...nr],BOARD:[...os,...gt,...nr],SWIMLANE:[...os,...gt,...nr],TICKET:[...gt,...nr,...oo],FIELD:[...gt,...oo],FIELD_LIST:[...gt,...oo],TEXT:[...gt]},ul=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],ml=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Yn();if(!r)return[f.HELP,f.CONFIG];if(!Zi())return[f.HELP,f.INIT];if(t)return[f.HELP,f.PEEK,f.EXPORT,f.CONFIG];let o=e?.context,i=o&&al.includes(o);return[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?ll[l]:[]))].filter(l=>l===f.MOVE?!1:l===f.EDIT||l===f.DELETE?i:!0)},ae=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let i=t.context??"WORKSPACE";return{[f.NONE]:ml({breadCrumb:o,readOnly:r,selectedNode:n}),[f.EXIT]:["confirm"],[f.EXPORT]:[],[f.SYNC]:[],[f.INIT]:[],[f.HELP]:[],[f.PEEK]:[...rs(),"now","prev","next"],[f.EDIT]:[...cl],[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(mt),...N.getExistingTags()])],[f.UNTAG]:[...Jn()?.value?.map(({name:l})=>l)??[]],[f.UNASSIGN]:[...Qn()?.value?.map(({name:l})=>l)??[]],[f.ASSIGN]:N.getExistingAssignees(),[f.NEW]:ul(i),[f.CONFIG]:[...dl]}[e]??[]}});var is,ss=y(()=>{"use strict";is=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{decodeTime as as}from"ulid";var ds,cs,so,rr=y(()=>{"use strict";S();ds=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"},cs=e=>{try{return c("Decoded date",new Date(as(e)))}catch(t){return s("Decoding failed + "+t.message)}},so=e=>{if(!e?.id)return null;try{return as(e.id)}catch{return null}}});var De,cn=y(()=>{"use strict";S();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 ls from"chalk";var pl,lo,co,us,ao,ms,gl,fl,ps,vl,gs,yl,xl,hl,ln,Fe,fs,El,or,Nl,Il,ir,ft=y(()=>{"use strict";Xn();pl=[0,0,0],lo=.2,co={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},us=(e,t,n)=>Math.max(t,Math.min(n,e)),ao=(e,t,n)=>e+(t-e)*n,ms=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},gl=e=>e.toLowerCase().trim(),fl=(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)]},ps=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,vl=e=>{let t=e.replace("#","");return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]},gs=(e,t,n)=>{let r=us(n,0,1);return[Math.round(ao(e[0],t[0],r)),Math.round(ao(e[1],t[1],r)),Math.round(ao(e[2],t[2],r))]},yl=(e,t=lo)=>gs(e,pl,t),xl=(e,t=lo)=>ps(yl(vl(e),t)),hl=(e,t,n)=>gs(e,t,n),ln=e=>{let n=ms(e)%360,r=fl(n,co.stringColor.saturation,co.stringColor.lightness);return ps(r)},Fe=(e,t=mt)=>{let n=gl(e);return n&&t[n]?t[n]:ln(n)},fs=(e,t=mt,n=lo)=>xl(Fe(e,t),n),El=e=>{let t=co.gradient.stops,n=us(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 hl(t[i],t[i+1],d)},or=e=>ms(e.toLowerCase().trim())/4294967295,Nl=e=>{let t=or(e);return El(t)},Il=e=>{let[t,n,r]=Nl(e);return{normal:o=>ls.bgRgb(t,n,r).black(o),cursor:o=>ls.bgRgb(t,n,r).white.bold(o)}},ir=e=>Il(e).normal(` ${e} `)});import vs from"chalk";var re,fe,le,ys=y(()=>{"use strict";ft();xe();re=e=>vs.dim(e),fe=e=>vs.hex(L.primary)(e),le=({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)=>or(x)-or(b)).slice(0,r).map(x=>ir(x)).join(" ");return g?`${re(e)}${g}${re(n)}`:""}});var vt,sr=y(()=>{"use strict";vt={None:"none",Invalid:"invalid",Valid:"valid"}});import hs from"chalk";var bl,xs,Z,z,B,dr,ar,uo,Sl,un,Cl,Rl,Al,Es,Ns=y(()=>{"use strict";qn();an();ss();rr();cn();S();se();ge();T();ft();Zn();ys();pt();sr();dn();tr();bl=["BOARD","TICKET","SWIMLANE"],xs=()=>{let e=v().selectedNode;return e?.context?bl.includes(e.context)?z():B({message:re("Command not available in this context")}):B({message:re("Missing target context")})},Z="<ENTER> to confirm",z=(e="",t=[])=>({message:re(e),validity:vt.Valid,completionWordList:t}),B=({message:e,completionWordList:t=[]})=>({validity:vt.Invalid,message:e,completionWordList:t}),dr=e=>e.length===0,ar=e=>` ${hs.dim.bgHex(fs(e))(` ${e} `)} `,uo=({modifier:e})=>{let t="confirm";return e===t?z(Z):B({message:dr(e)?re("if you are certain, enter ")+ir(t):"",completionWordList:[t]})},Sl=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?B({message:re(n)}):z():B({message:dr(r)?t:"",completionWordList:[...e]}),un=({hint:e})=>({modifier:t,inputString:n})=>dr(t)&&dr(n)?B({message:e,completionWordList:[]}):z(Z),Cl=({modifier:e,inputString:t})=>{let n=ae(f.CONFIG);if(!n.includes(e))return B({message:le({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case X.EDITOR:{let r=[...is];return t.trim()?r.includes(t.trim())?z(Z):B({message:le({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):B({message:le({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?z(Z):B({message:le({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.USERNAME:return t.trim()?z(Z):B({message:fe("Enter a user name. Saved in ")+hs.bgBlack("~/.epiq-global/config.json")});case X.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?z(Z):B({message:le({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=es(o);return B({message:le({prefix:`should auto-sync (recommended)${i!==null?", currently: "+i:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return z(Z)}case X.SYNC_DEBOUNCE_MS:{let r=Y().autoSyncIntervalMs,o=Yi(t);if(!t.trim()||o===null||o<Dt){let i=le({prefix:" examples: ",wordList:io,minLengthForHints:0,inputString:t});return B({message:fe(`provide duration above ${Dt}ms. current duration: ${r}ms.`)+i,completionWordList:io})}return z(Z)}default:return B({message:fe("Unknown config option"),completionWordList:n})}},Rl=({modifier:e})=>{let t=ae(f.EDIT);if(!t.includes(e)){let i=le({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return B({message:i||fe("Unknown edit option"),completionWordList:t})}let{breadCrumb:n,selectedNode:r}=v();if(!De([...n,r],"TICKET"))return B({message:fe("Command not available in this context")});switch(e){case rt.TITLE:return z(Z);case rt.DESCRIPTION:let{preferredEditor:i}=Y();return i?z(re("<ENTER> to edit in ")+i):B({message:"No editor selected"});default:return B({message:fe("Unknown edit option"),completionWordList:t})}},Al={[f.EXPORT]:()=>z(Z+re(", and create export markdown file")),[f.PEEK]:e=>{let t=e.modifier;if(t==="now")return z(Z);let n={message:re("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")};if(t==="prev"||t==="next")return z(Z);let r=er(t);if(!t||!r)return B(n);let o=De(v().breadCrumb,"BOARD");if(a(o))return B({message:fe("Command is not applicable in this context")});let i=cs(o.value.id);return a(i)?B({message:fe("Unable to peek: board id is not a valid ULID")}):ns({date:r,horizonDate:i.value})?z(Z):B({message:fe(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[f.EXIT]:()=>z(Z+re(" and exit the application")),[f.INIT]:()=>z(Z),[f.PALETTE]:()=>z(Z),[f.FILTER]:e=>{if(e.modifier==="clear")return z();let t=i=>ae(f.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return B({message:le({wordList:ae(f.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:ae(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())?B({message:le({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):z():B({message:le({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[f.NONE]:e=>{let t=ae(f.NONE);return B({message:le({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[f.NEW]:e=>Sl({list:ae(f.NEW),hint:le({wordList:ae(f.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[f.HELP]:()=>z(Z),[f.EDIT]:Rl,[f.CONFIG]:Cl,[f.DELETE]:e=>{let t=xs();return t.validity==="invalid"?t:uo(e)},[f.CLOSE_ISSUE]:e=>uo(e),[f.RE_OPEN_ISSUE]:e=>uo(e),[f.MOVE]:e=>{let t=xs();return t.validity==="invalid"?t:un({hint:le({prefix:"hey hacker! These commands are blocked for you... ",wordList:ae(f.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[f.TAG]:e=>{let n=N.getExistingTags().slice(0,10).map(ar).join("");return un({hint:n.length?re("create tag or reuse:")+n+re(""):re("create tag ...")})(e)},[f.UNTAG]:e=>{let t=Jn();if(a(t))return B({message:fe("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(ar).slice(0,10);return n.length?un({hint:re(" ... ")+n.join("")})(e):B({message:fe("Issue has no tags"),completionWordList:[]})},[f.ASSIGN]:e=>{let t=N.getExistingAssignees().map(ar).slice(0,10);return un({hint:re("assignees... ")+t.join("")})(e)},[f.UNASSIGN]:e=>{let t=Qn();if(a(t))return B({message:fe("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(ar).slice(0,10);return n.length?un({hint:re("remove assignee... ")+n.join("")})(e):B({message:fe("Issue has no assignees"),completionWordList:[]})},[f.SYNC]:()=>z(Z)},Es=Object.fromEntries(Object.entries(Al).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]))});var Is,bs=y(()=>{"use strict";Is=["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 Ss,Cs,mo=y(()=>{"use strict";Gi();dn();pt();Ns();bs();T();G();Ss=e=>Object.values(f).includes(e),Cs=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:d,validity:l,completionWordList:u}=Es[n].validate(n,r,i),m=o==="command"||o==="modifier"?ae(n):Is,{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?qi(e,b):{hint:"",hints:[],remainder:"",overlap:0}}}});var Rs,wl,Tl,Ml,As=y(()=>{"use strict";mo();dn();Rs=e=>{let t=e.trimStart(),n=Tl(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),d=Ml(e),l=Ss(r)?r:null,u=l!==null,m=r!=="",g=l?ae(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 I=i?"":d,R=wl(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:I,inputString:R}},wl=(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},Tl=e=>e.trim()?e.trim().split(/\s+/):[],Ml=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as xv}from"react";var Ot,po,Ut,Ll,ws,Oe,mn,go,fo,Ts,Ms,cr,Ls,W,Ps,ks,Ds,ee,Fs,oe=y(()=>{"use strict";mo();As();S();sr();Ot=e=>e===po||e===":",po=" ",Ut={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:vt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Ll=new Set,ws=()=>{for(let e of Ll)e()},Oe=e=>{let n=e(Ut),r=Rs(n.value),o=n.cursorPosition===n.value.length;Ut={...n,commandMeta:Cs(r,o)},ws()},mn=({message:e,status:t})=>{let n=structuredClone(Ut);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Ut=n,ws(),c(e,null)},go=e=>{Oe(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},fo=e=>{Oe(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Ot(n[o-1]);)o--;for(;o>0&&!Ot(n[o-1]);)o--}else{for(;o<n.length&&!Ot(n[o]);)o++;for(;o<n.length&&Ot(n[o]);)o++}return{...t,cursorPosition:o}})},Ts=()=>{Oe(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}})},Ms=()=>{Oe(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Ot(t[r-1]);)r--;for(;r>0&&!Ot(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},cr=e=>{Oe(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}})},Ls=()=>{Oe(e=>({...e,commandIsPending:!0}))},W=e=>{Oe(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Ps=({addToHistory:e=!0})=>{Oe(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},ks=()=>{Oe(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}})},Ds=()=>{Oe(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ee=()=>Ut,Fs=()=>{let[e,...t]=Ut.value.split(po);return t.join(po).trim()}});var C,ut=y(()=>{"use strict";G();$i();T();oe();ge();C={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 Os,P,vo=y(()=>{"use strict";T();pt();Os=e=>{let{context:t}=v().contextNode;if(!t)return P.None;switch(e){case f.EXIT:return P.Exit;case f.EXPORT:return P.Export;case f.INIT:return P.Init;case f.DELETE:return P.Delete;case f.EDIT:return P.Edit;case f.HELP:return P.ViewHelp;case f.RE_OPEN_ISSUE:return P.ReopenIssue;case f.CLOSE_ISSUE:return P.CloseIssue;case f.TAG:return P.TagTicket;case f.UNTAG:return P.UntagTicket;case f.ASSIGN:return P.AssignUserToTicket;case f.UNASSIGN:return P.UnassignUserFromTicket;case f.NEW:return P.NewItem;case f.FILTER:return P.Filter;case f.MOVE:return P.Move;case f.PEEK:return P.Peek;case f.CONFIG:return P.Config;case f.SYNC:return P.Sync;default:return P.None}},P={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"}});import{Text as Us}from"ink";import Bs,{useEffect as _s,useState as Pl}from"react";var $s,Ne,Bt=y(()=>{"use strict";T();xe();$s={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ne=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Ue(),r=$s[n]??$s.default,[o,i]=Pl(0);if(_s(()=>{i(0)},[r]),_s(()=>{if(!e)return;let l=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return Bs.createElement(Us,null,t);let d=r[o]??r[0]??t;return Bs.createElement(Us,{color:L.accent,dimColor:o===1},d)}});import{Box as yo,Text as kl}from"ink";import lr from"react";var ur,xo=y(()=>{"use strict";xe();ur=({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),I=e.length>l,R=i,k=I?Math.max(1,Math.floor(l/e.length*R)):R,A=Math.max(0,R-k),U=Math.max(1,e.length-l),j=I?Math.floor(g/U*A):0;return lr.createElement(yo,{flexDirection:"row",height:i,width:"100%"},lr.createElement(yo,{flexDirection:"column",flexGrow:1,height:i},b),lr.createElement(yo,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((ct,Xe)=>lr.createElement(kl,{key:Xe,color:I&&Xe>=j&&Xe<j+k?L.accent:L.secondary},I?"\u2502":" "))))}});import{Text as Dl}from"ink";import Fl from"react";var Ol,Ul,mr,ho=y(()=>{"use strict";Xn();ft();se();Ol=e=>e.toLowerCase().trim(),Ul=(e,t=mt)=>{let n=Ol(e);return t[n]?t[n]:ln(n)},mr=({id:e,isSelected:t})=>{let n=N.getContributor(e);if(n)return Fl.createElement(Dl,{underline:t,color:Ul(n.name)},"@"+n.name)}});import{Text as Bl}from"ink";import _l from"react";var pr,Eo=y(()=>{"use strict";se();xe();ft();pr=({id:e,isSelected:t})=>{let n=N.getTag(e);if(n)return _l.createElement(Bl,{underline:t,backgroundColor:Fe(n.name),color:L.primary}," "+n.name+" ")}});import{Box as gr,Text as $l}from"ink";import yt from"react";var Ws,js=y(()=>{"use strict";xe();kt();Zn();ho();Eo();Ws=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=zn(Vn(t.title),r),i=no(t),d=ro(t);return yt.createElement(gr,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?L.accent:L.secondary,justifyContent:"space-between"},yt.createElement(gr,{borderBottom:!0},yt.createElement(gr,{paddingLeft:1,flexDirection:"column"},yt.createElement($l,{color:L.primary},o))),yt.createElement(gr,{flexDirection:"row",paddingLeft:1},i.map(l=>yt.createElement(pr,{key:l.id,id:l.id})),d.map(l=>yt.createElement(mr,{key:l.id,id:l.id}))))}});import Wl from"chalk";import{Box as pn,Text as No}from"ink";import ze from"react";var jl,Hs,zs=y(()=>{"use strict";G();se();xe();ft();Bt();jl=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Hs=({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=>ze.createElement(pn,{key:I.id,paddingRight:l},ze.createElement(No,{color:Fe(I.name)},"\u25A0"))),x=d.map(I=>ze.createElement(pn,{key:I.id,paddingRight:l},ze.createElement(No,{color:ln(I.name)},"@"+I.name.at(0)))),b=n?L.accent:o===p.MOVE?L.secondary:L.primary;return ze.createElement(pn,{borderBottom:!0,justifyContent:"space-between"},ze.createElement(pn,null,ze.createElement(Ne,{isSelected:n,placeholder:Wl.dim.gray(r+1+" ")}),ze.createElement(No,{wrap:"truncate",color:b},jl(t.title,e-u-m-14))),ze.createElement(pn,null,g,x))}});import{Box as Io,Text as Hl}from"ink";import Be from"react";import zl from"chalk";var Vl,Vs,Ks=y(()=>{"use strict";T();xe();Bt();xo();js();zs();Vl=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u}=Ue(),m=u[e.id]??[],g=`${e.title} ${zl.hex(L.secondary2).dim("("+m.length+")")}`,x=3,b=o?1:4,I=r-x-(o?2:1),R=Be.createElement(Io,{borderStyle:"round",borderColor:L.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Be.createElement(Ne,{isSelected:t}),Be.createElement(Hl,{bold:!0,color:t?L.accent:L.primary},g," ",e.readonly?"\u{1F512}":"")),k=(A,U)=>{let j=i&&d===U;return o?Be.createElement(Hs,{key:A.id,index:U,width:n,ticket:A,isSelected:j,mode:l}):Be.createElement(Ws,{key:A.id,width:n,ticket:A,isSelected:j})};return Be.createElement(Io,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?L.accent:L.secondary,paddingRight:1,paddingLeft:1,height:r},R,Be.createElement(Io,{padding:o?1:0},m.length>0&&Be.createElement(ur,{selectedIndex:d,height:I,itemHeight:b},m.map(k)),Be.createElement(Ne,{isSelected:i&&d===-1})))},Vs=Be.memo(Vl)});import{createHash as Kl}from"node:crypto";var ql,Gl,ot,bo=y(()=>{"use strict";ql="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Gl=e=>{let t=Kl("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+=ql[Number(n>>i&31n)]}return r},ot=(e,t)=>Gl(`${e}:virtual:${t}`)});import{Box as fr,Text as Yl}from"ink";import Ve from"react";var qs,Gs=y(()=>{"use strict";te();se();Pt();T();xe();ho();Bt();Eo();qs=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Ue(),{title:o}=t,i=t.parentNodeId?N.getNode(t.parentNodeId):void 0,d=i&&$(i)?o===Q.ASSIGNEES?i.props.assignees??[]:o===Q.TAGS?i.props.tags??[]:[]:[];return Ve.createElement(fr,{alignItems:"center",paddingTop:1},Ve.createElement(fr,{minWidth:12},Ve.createElement(Ne,{isSelected:n}),Ve.createElement(Yl,{color:n?L.accent:L.secondary2},o,":")),Ve.createElement(fr,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=r.id===t.id&&u===e;return Ve.createElement(fr,{key:`${o}-${l}`,paddingRight:2,minHeight:1},Ve.createElement(Ne,{isSelected:m}),o===Q.ASSIGNEES?Ve.createElement(mr,{isSelected:m,id:l}):o===Q.TAGS?Ve.createElement(pr,{isSelected:m,id:l}):null)})))}});var ve,gn=y(()=>{"use strict";te();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 vr,Text as So}from"ink";import Ke,{useEffect as Xl,useMemo as Ys}from"react";var Jl,Xs,Co,Js,Ql,Ro,Qs=y(()=>{"use strict";se();S();gn();T();xe();kt();Bt();xo();Rt();Jl="\u2029",Xs=(e,t)=>`${e}::inline-line::${t}`,Co=new Map,Js=e=>{let t=Co.get(e)??[];Co.delete(e);for(let n of t)N.deleteNode(n)},Ql=(e,t)=>{Js(e);let n=[];t.forEach((r,o)=>{let i=Se(BigInt(o+1));if(!Yt(i))return;let d=N.createNode(ve.text({id:Xs(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:i.value,props:{value:r},readonly:!0,isVirtual:!0}));Yt(d)&&n.push(d.value.id)}),Co.set(e,n)},Ro=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:d,contextNode:l}=Ue(),u=Ys(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Ys(()=>u.join("\0"),[u]);Xl(()=>(Ql(e,u),()=>{Js(e)}),[e,m]);let g=b=>String(b).replace(/\r?\n/g,""),x=u.map((b,I)=>{let R=l.id===e&&d===I;return Ke.createElement(vr,{key:Xs(e,I)},Ke.createElement(So,{color:R?L.primary:L.secondary2,dimColor:!R},`${I+1} `.padStart(5,"\xA0")),Ke.createElement(So,{backgroundColor:R?"gray":void 0},g(b.length?zn(b,i-10):Jl)))});return Ke.createElement(vr,{flexDirection:"column",paddingTop:1},Ke.createElement(vr,null,Ke.createElement(Ne,{isSelected:o}),Ke.createElement(So,{color:o?L.accent:L.secondary2},t)),Ke.createElement(vr,{flexDirection:"row",borderStyle:"round",borderColor:L.secondary,paddingLeft:1,marginLeft:1},Ke.createElement(ur,{scrollByOne:!0,height:r-3,selectedIndex:d,itemHeight:1},x)))}});import{Box as Ao,Text as Zl}from"ink";import it,{useMemo as Zs}from"react";var eu,tu,ea,ta=y(()=>{"use strict";te();se();T();xe();bo();Bt();Gs();Qs();eu=e=>ot(e,"description"),tu=e=>ot(e,"history"),ea=({ticket:e,height:t})=>{let{selectedIndex:n,contextNode:r}=Ue(),o=process.stdout.columns||120,i=Zs(()=>eu(e.id),[e.id]),d=Zs(()=>tu(e.id),[e.id]),l=r.id===e.id,u=r.id===d||r.parentNodeId===d,m=K(e.id);if(u){let A=N.getNode(d),U=A&&Qe(A)?A.props.value??"":"",ct=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:ct}):null)}let g=m.reduce((A,U)=>Xt(U)||U.id===d?A+1:A,0),x=2,b=3,I=g,R=t-b-I-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:R}):Xt(A)?it.createElement(qs,{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(Zl,{backgroundColor:L.secondary,color:U?L.accent:L.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 nu}from"ink";import yr from"react";var ru,na,ra=y(()=>{"use strict";te();Ks();ta();ru=({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),I=Math.floor(l/Math.max(e.length,1)),R=Math.min(I,b),k=i==="dense";return yr.createElement(nu,{flexDirection:"row",height:d},g&&e.map((A,U)=>{let j=t.id===A.id,ct=j?n:-1,Xe=t.context===w.BOARD&&n===U;return yr.createElement(Vs,{key:A.id,height:d,width:R,swimlane:A,isSelected:Xe,isDense:k,isFocused:j,listSelectedIndex:ct,mode:o})}),m&&x&&yr.createElement(ea,{height:d,ticket:x}))},na=yr.memo(ru)});import oa from"node:fs";import ou from"node:path";import iu from"react";import{render as su}from"ink";import{Writable as au}from"node:stream";var fn,du,cu,lu,uu,ia,sa=y(()=>{"use strict";ra();te();S();T();ne();ge();fn=e=>String(e).padStart(2,"0"),du=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}`},cu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",lu=async(e,{width:t,height:n})=>{let r="",o=new au({write(d,l,u){let m=uu(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=su(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),i.unmount(),r},uu=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),ia=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 lu(iu.createElement(na,{height:u,width:l,swimlanes:(i[d.id]??[]).filter(U=>U!==void 0&&wn(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=kn(process.cwd());if(a(g))return s("Unable to export, epiq root not found");let x=new Date,b=du(x),I=`board_${cu(d.title)}_${b}.md`,R=Bi(g.value);oa.mkdirSync(R,{recursive:!0});let k=ou.join(R,I),A=`# Board - ${d.title}
21
+ `).filter(Boolean).filter(d=>d!==ze);if(r.length===0)return c("State branch is storage-only",!1);let o=await O({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 O({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)),cg=zr(async e=>{let t=await O({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 on from"node:fs";import Ve from"node:path";var vg,ze,Ee,zn,Vc,Pn,kn,sn,_i,Kc,Zr,Fn,tt,$i,Ae,ne=y(()=>{"use strict";S();Pt();vg=process.env.IS_LOCAL==="true",ze=".epiq",Ee=".epiq-global",zn="events",Vc="project.json",Pn=e=>Ve.join(e,ze),kn=e=>Ve.join(Pn(e),Vc),sn=e=>Ve.join(Pn(e),zn),_i=e=>Ve.join(e,ze),Kc=e=>{let t=Ve.join(e,ze);return on.existsSync(t)&&on.statSync(t).isDirectory()},Zr=e=>{let t=kn(e);return on.existsSync(t)&&on.statSync(t).isFile()},Fn=e=>{let t=Ve.resolve(e);for(;;){if(Kc(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}},$i=e=>{let t=sn(e);try{return on.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 Q,kt=y(()=>{"use strict";Q={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 Wi=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 Kn,qn,Dt=y(()=>{"use strict";Kn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",qn=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var ji,Hi,zi=y(()=>{"use strict";ji=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},Hi=(e,t)=>t?e.get(t)??[]:[]});var Vi,qc,Ki,qi=y(()=>{"use strict";Dt();zi();Vi=new WeakMap,qc=e=>{let t=Vi.get(e);return t||(t=ji(e),Vi.set(e,t)),t},Ki=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Hi(qc(e),r).filter(i=>Vn(r,i)>=n)}});var Gc,Gi,Yc,Yi=y(()=>{"use strict";Dt();qi();Gc={hint:"",hints:[],overlap:0,remainder:""},Gi=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Gc;let o=Ki({wordList:r,inputToMatch:e,overlapThreshold:1});return Yc(t,o)},Yc=(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 Pg}from"react";var Gn,Xc,Jc,Y,ke,ge=y(()=>{"use strict";Gn={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Xc=new Set,Jc=()=>{for(let e of Xc)e()},Y=()=>Gn,ke=e=>(Gn={...Gn,...e},Jc(),Gn)});var Ft,Xi,Ji,eo,to,an,no,Qc,Qi,Zc,Zi,Yn=y(()=>{"use strict";S();ge();T();Xn();Ft=3e3,Xi=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Ft?null:t},Ji=0,to=!1,an=!1,no=()=>{if(to)return!0;let e=De();return a(e)?!1:e.value.syncStatus.status==="syncing"},Qc=()=>{let e=Y().autoSyncIntervalMs??1e4,t=Date.now()-Ji;return Math.max(0,e-t)},Qi=()=>{eo||(eo=setTimeout(async()=>{if(eo=void 0,!!Ot()){if(no()){an=!0;return}an=!1,await Zc()}},Qc()))},Zc=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 an=!0,s("Sync already in progress");to=!0,Ji=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Ke()}finally{to=!1,an&&Qi()}},Zi=()=>{Ot()&&(an=!0,!no()&&Qi())}});var Jn,es,ts,ns,dn=y(()=>{"use strict";S();wt();ge();ne();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}},es=()=>{let e=tt(process.cwd());if(a(e))return!1;let t=et(e.value);return Xt(t)},ts=e=>e===!0?"on":e===!1?"off":null,ns=e=>e==="on"?!0:e==="off"?!1:null});var ie,L,xe=y(()=>{"use strict";ie={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"},L={accent:ie.cyan,accent2:ie.magenta,primary:ie.white,secondary:ie.grayDark,secondary2:ie.grayLight,gray:ie.gray,green:ie.green,yellow:ie.yellow,red:ie.red}});var h,pt,Qn=y(()=>{"use strict";xe();h={red:ie.red,yellow:ie.yellow,green:ie.green,blue:ie.blue,magenta:ie.magenta,cyan:ie.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 el,tl,ro,oo,Zn,er,tr=y(()=>{"use strict";te();S();se();T();el=e=>e.props.tags??[],tl=e=>e.props.assignees??[],ro=e=>el(e).map(t=>N.getTag(t)).filter(t=>!!t),oo=e=>tl(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||!$(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||!$(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",NONE:""}});var nl,rl,ol,il,sl,nr,rs,al,os,rr=y(()=>{"use strict";nl=/^(\d+)(h|d|w|mo|y)$/,rl=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,ol=({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},il=(e,t=new Date)=>{let n=e.match(nl);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}},sl=e=>{let t=e.match(rl);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 ol({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 il(t)??sl(t)},rs=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,al=[{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}],os=(e=al)=>{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 dl,X,rt,cl,ll,so,ft,or,io,is,ul,ml,pl,ae,cn=y(()=>{"use strict";Yn();dn();se();T();Qn();tr();gt();rr();dl=["BOARD","TICKET","SWIMLANE"],X={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},rt={TITLE:"title",DESCRIPTION:"description"},cl=[X.EDITOR,X.VIEW,X.USERNAME,X.AUTOSYNC,X.SYNC_DEBOUNCE_MS,X.LOG_LEVEL],ll=[rt.TITLE,rt.DESCRIPTION],so=[String(Ft),"5000","15000","30000","60000"],ft=[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],is=[f.FILTER,f.PEEK],ul={WORKSPACE:[...ft,...or],BOARD:[...is,...ft,...or],SWIMLANE:[...is,...ft,...or],TICKET:[...ft,...or,...io],FIELD:[...ft,...io],FIELD_LIST:[...ft,...io],TEXT:[...ft]},ml=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],pl=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Jn();if(!r)return[f.HELP,f.CONFIG];if(!es())return[f.HELP,f.INIT];if(t)return[f.HELP,f.PEEK,f.EXPORT,f.CONFIG];let o=e?.context,i=o&&dl.includes(o);return[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?ul[l]:[]))].filter(l=>l===f.MOVE?!1:l===f.EDIT||l===f.DELETE?i:!0)},ae=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let i=t.context??"WORKSPACE";return{[f.NONE]:pl({breadCrumb:o,readOnly:r,selectedNode:n}),[f.EXIT]:["confirm"],[f.EXPORT]:[],[f.SYNC]:[],[f.INIT]:[],[f.HELP]:[],[f.PEEK]:[...os(),"now","prev","next"],[f.EDIT]:[...ll],[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]:ml(i),[f.CONFIG]:[...cl]}[e]??[]}});var ss,as=y(()=>{"use strict";ss=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{decodeTime as ds}from"ulid";var cs,ls,ao,ir=y(()=>{"use strict";S();cs=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"},ls=e=>{try{return c("Decoded date",new Date(ds(e)))}catch(t){return s("Decoding failed + "+t.message)}},ao=e=>{if(!e?.id)return null;try{return ds(e.id)}catch{return null}}});var Fe,ln=y(()=>{"use strict";S();Fe=(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 us from"chalk";var gl,uo,lo,ms,co,ps,fl,vl,gs,yl,fs,xl,hl,El,un,Oe,vs,Nl,sr,Il,bl,ar,vt=y(()=>{"use strict";Qn();gl=[0,0,0],uo=.2,lo={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ms=(e,t,n)=>Math.max(t,Math.min(n,e)),co=(e,t,n)=>e+(t-e)*n,ps=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},fl=e=>e.toLowerCase().trim(),vl=(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)]},gs=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,yl=e=>{let t=e.replace("#","");return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]},fs=(e,t,n)=>{let r=ms(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))]},xl=(e,t=uo)=>fs(e,gl,t),hl=(e,t=uo)=>gs(xl(yl(e),t)),El=(e,t,n)=>fs(e,t,n),un=e=>{let n=ps(e)%360,r=vl(n,lo.stringColor.saturation,lo.stringColor.lightness);return gs(r)},Oe=(e,t=pt)=>{let n=fl(e);return n&&t[n]?t[n]:un(n)},vs=(e,t=pt,n=uo)=>hl(Oe(e,t),n),Nl=e=>{let t=lo.gradient.stops,n=ms(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 El(t[i],t[i+1],d)},sr=e=>ps(e.toLowerCase().trim())/4294967295,Il=e=>{let t=sr(e);return Nl(t)},bl=e=>{let[t,n,r]=Il(e);return{normal:o=>us.bgRgb(t,n,r).black(o),cursor:o=>us.bgRgb(t,n,r).white.bold(o)}},ar=e=>bl(e).normal(` ${e} `)});import ys from"chalk";var re,fe,le,xs=y(()=>{"use strict";vt();xe();re=e=>ys.dim(e),fe=e=>ys.hex(L.primary)(e),le=({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?`${re(e)}${g}${re(n)}`:""}});var yt,dr=y(()=>{"use strict";yt={None:"none",Invalid:"invalid",Valid:"valid"}});import Es from"chalk";var Sl,hs,Z,z,B,lr,cr,mo,Cl,mn,Rl,Al,wl,Ns,Is=y(()=>{"use strict";Yn();dn();as();ir();ln();S();se();ge();T();vt();tr();xs();gt();dr();cn();rr();Sl=["BOARD","TICKET","SWIMLANE"],hs=()=>{let e=v().selectedNode;return e?.context?Sl.includes(e.context)?z():B({message:re("Command not available in this context")}):B({message:re("Missing target context")})},Z="<ENTER> to confirm",z=(e="",t=[])=>({message:re(e),validity:yt.Valid,completionWordList:t}),B=({message:e,completionWordList:t=[]})=>({validity:yt.Invalid,message:e,completionWordList:t}),lr=e=>e.length===0,cr=e=>` ${Es.dim.bgHex(vs(e))(` ${e} `)} `,mo=({modifier:e})=>{let t="confirm";return e===t?z(Z):B({message:lr(e)?re("if you are certain, enter ")+ar(t):"",completionWordList:[t]})},Cl=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?B({message:re(n)}):z():B({message:lr(r)?t:"",completionWordList:[...e]}),mn=({hint:e})=>({modifier:t,inputString:n})=>lr(t)&&lr(n)?B({message:e,completionWordList:[]}):z(Z),Rl=({modifier:e,inputString:t})=>{let n=ae(f.CONFIG);if(!n.includes(e))return B({message:le({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case X.EDITOR:{let r=[...ss];return t.trim()?r.includes(t.trim())?z(Z):B({message:le({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):B({message:le({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?z(Z):B({message:le({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.USERNAME:return t.trim()?z(Z):B({message:fe("Enter a user name. Saved in ")+Es.bgBlack("~/.epiq-global/config.json")});case X.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?z(Z):B({message:le({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=ts(o);return B({message:le({prefix:`should auto-sync (recommended)${i!==null?", currently: "+i:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return z(Z)}case X.SYNC_DEBOUNCE_MS:{let r=Y().autoSyncIntervalMs,o=Xi(t);if(!t.trim()||o===null||o<Ft){let i=le({prefix:" examples: ",wordList:so,minLengthForHints:0,inputString:t});return B({message:fe(`provide duration above ${Ft}ms. current duration: ${r}ms.`)+i,completionWordList:so})}return z(Z)}default:return B({message:fe("Unknown config option"),completionWordList:n})}},Al=({modifier:e})=>{let t=ae(f.EDIT);if(!t.includes(e)){let i=le({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return B({message:i||fe("Unknown edit option"),completionWordList:t})}let{breadCrumb:n,selectedNode:r}=v();if(!Fe([...n,r],"TICKET"))return B({message:fe("Command not available in this context")});switch(e){case rt.TITLE:return z(Z);case rt.DESCRIPTION:let{preferredEditor:i}=Y();return i?z(re("<ENTER> to edit in ")+i):B({message:"No editor selected"});default:return B({message:fe("Unknown edit option"),completionWordList:t})}},wl={[f.EXPORT]:()=>z(Z+re(", and create export markdown file")),[f.PEEK]:e=>{let t=e.modifier;if(t==="now")return z(Z);let n={message:re("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")};if(t==="prev"||t==="next")return z(Z);let r=nr(t);if(!t||!r)return B(n);let o=Fe(v().breadCrumb,"BOARD");if(a(o))return B({message:fe("Command is not applicable in this context")});let i=ls(o.value.id);return a(i)?B({message:fe("Unable to peek: board id is not a valid ULID")}):rs({date:r,horizonDate:i.value})?z(Z):B({message:fe(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[f.EXIT]:()=>z(Z+re(" and exit the application")),[f.INIT]:()=>z(Z),[f.PALETTE]:()=>z(Z),[f.FILTER]:e=>{if(e.modifier==="clear")return z();let t=i=>ae(f.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return B({message:le({wordList:ae(f.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:ae(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())?B({message:le({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):z():B({message:le({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[f.NONE]:e=>{let t=ae(f.NONE);return B({message:le({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[f.NEW]:e=>Cl({list:ae(f.NEW),hint:le({wordList:ae(f.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[f.HELP]:()=>z(Z),[f.EDIT]:Al,[f.CONFIG]:Rl,[f.DELETE]:e=>{let t=hs();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=hs();return t.validity==="invalid"?t:mn({hint:le({prefix:"hey hacker! These commands are blocked for you... ",wordList:ae(f.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[f.TAG]:e=>{let n=N.getExistingTags().slice(0,10).map(cr).join("");return mn({hint:n.length?re("create tag or reuse:")+n+re(""):re("create tag ...")})(e)},[f.UNTAG]:e=>{let t=Zn();if(a(t))return B({message:fe("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(cr).slice(0,10);return n.length?mn({hint:re(" ... ")+n.join("")})(e):B({message:fe("Issue has no tags"),completionWordList:[]})},[f.ASSIGN]:e=>{let t=N.getExistingAssignees().map(cr).slice(0,10);return mn({hint:re("assignees... ")+t.join("")})(e)},[f.UNASSIGN]:e=>{let t=er();if(a(t))return B({message:fe("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(cr).slice(0,10);return n.length?mn({hint:re("remove assignee... ")+n.join("")})(e):B({message:fe("Issue has no assignees"),completionWordList:[]})},[f.SYNC]:()=>z(Z)},Ns=Object.fromEntries(Object.entries(wl).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]))});var bs,Ss=y(()=>{"use strict";bs=["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 Cs,Rs,po=y(()=>{"use strict";Yi();cn();gt();Is();Ss();T();G();Cs=e=>Object.values(f).includes(e),Rs=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:d,validity:l,completionWordList:u}=Ns[n].validate(n,r,i),m=o==="command"||o==="modifier"?ae(n):bs,{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?Gi(e,b):{hint:"",hints:[],remainder:"",overlap:0}}}});var As,Tl,Ml,Ll,ws=y(()=>{"use strict";po();cn();As=e=>{let t=e.trimStart(),n=Ml(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),d=Ll(e),l=Cs(r)?r:null,u=l!==null,m=r!=="",g=l?ae(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=Tl(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}},Tl=(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},Ml=e=>e.trim()?e.trim().split(/\s+/):[],Ll=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as xv}from"react";var Ut,go,Bt,Pl,Ts,Ue,pn,fo,vo,Ms,Ls,ur,Ps,W,ks,Ds,Fs,ee,Os,oe=y(()=>{"use strict";po();ws();S();dr();Ut=e=>e===go||e===":",go=" ",Bt={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:yt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Pl=new Set,Ts=()=>{for(let e of Pl)e()},Ue=e=>{let n=e(Bt),r=As(n.value),o=n.cursorPosition===n.value.length;Bt={...n,commandMeta:Rs(r,o)},Ts()},pn=({message:e,status:t})=>{let n=structuredClone(Bt);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Bt=n,Ts(),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&&Ut(n[o-1]);)o--;for(;o>0&&!Ut(n[o-1]);)o--}else{for(;o<n.length&&!Ut(n[o]);)o++;for(;o<n.length&&Ut(n[o]);)o++}return{...t,cursorPosition:o}})},Ms=()=>{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}})},Ls=()=>{Ue(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Ut(t[r-1]);)r--;for(;r>0&&!Ut(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}})},Ps=()=>{Ue(e=>({...e,commandIsPending:!0}))},W=e=>{Ue(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},ks=({addToHistory:e=!0})=>{Ue(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Ds=()=>{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}})},Fs=()=>{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}})},ee=()=>Bt,Os=()=>{let[e,...t]=Bt.value.split(go);return t.join(go).trim()}});var C,mt=y(()=>{"use strict";G();Wi();T();oe();ge();C={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 Us,P,yo=y(()=>{"use strict";T();gt();Us=e=>{let{context:t}=v().contextNode;if(!t)return P.None;switch(e){case f.EXIT:return P.Exit;case f.EXPORT:return P.Export;case f.INIT:return P.Init;case f.DELETE:return P.Delete;case f.EDIT:return P.Edit;case f.HELP:return P.ViewHelp;case f.RE_OPEN_ISSUE:return P.ReopenIssue;case f.CLOSE_ISSUE:return P.CloseIssue;case f.TAG:return P.TagTicket;case f.UNTAG:return P.UntagTicket;case f.ASSIGN:return P.AssignUserToTicket;case f.UNASSIGN:return P.UnassignUserFromTicket;case f.NEW:return P.NewItem;case f.FILTER:return P.Filter;case f.MOVE:return P.Move;case f.PEEK:return P.Peek;case f.CONFIG:return P.Config;case f.SYNC:return P.Sync;default:return P.None}},P={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"}});import{Text as Bs}from"ink";import _s,{useEffect as $s,useState as kl}from"react";var Ws,Ne,_t=y(()=>{"use strict";T();xe();Ws={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ne=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Be(),r=Ws[n]??Ws.default,[o,i]=kl(0);if($s(()=>{i(0)},[r]),$s(()=>{if(!e)return;let l=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return _s.createElement(Bs,null,t);let d=r[o]??r[0]??t;return _s.createElement(Bs,{color:L.accent,dimColor:o===1},d)}});import{Box as xo,Text as Dl}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(Dl,{key:Je,color:R&&Je>=j&&Je<j+k?L.accent:L.secondary},R?"\u2502":" "))))}});import{Text as Fl}from"ink";import Ol from"react";var Ul,Bl,gr,Eo=y(()=>{"use strict";Qn();vt();se();Ul=e=>e.toLowerCase().trim(),Bl=(e,t=pt)=>{let n=Ul(e);return t[n]?t[n]:un(n)},gr=({id:e,isSelected:t})=>{let n=N.getContributor(e);if(n)return Ol.createElement(Fl,{underline:t,color:Bl(n.name)},"@"+n.name)}});import{Text as _l}from"ink";import $l from"react";var fr,No=y(()=>{"use strict";se();xe();vt();fr=({id:e,isSelected:t})=>{let n=N.getTag(e);if(n)return $l.createElement(_l,{underline:t,backgroundColor:Oe(n.name),color:L.primary}," "+n.name+" ")}});import{Box as vr,Text as Wl}from"ink";import xt from"react";var js,Hs=y(()=>{"use strict";xe();Dt();tr();Eo();No();js=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=Kn(qn(t.title),r),i=ro(t),d=oo(t);return xt.createElement(vr,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?L.accent:L.secondary,justifyContent:"space-between"},xt.createElement(vr,{borderBottom:!0},xt.createElement(vr,{paddingLeft:1,flexDirection:"column"},xt.createElement(Wl,{color:L.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 $t,Text as yr}from"ink";import we from"react";var jl,zs,Vs=y(()=>{"use strict";G();se();xe();vt();_t();jl=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,zs=({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($t,{key:I.id,paddingRight:l},we.createElement(yr,{color:Oe(I.name)},"\u25A0"))),x=d.map(I=>we.createElement($t,{key:I.id,paddingRight:l},we.createElement(yr,{color:un(I.name)},"@"+I.name.at(0)))),b=n?L.accent:o===p.MOVE?L.secondary:L.primary;return we.createElement($t,{borderBottom:!0,justifyContent:"space-between"},we.createElement($t,null,we.createElement($t,{width:4},n?we.createElement(Ne,{isSelected:n}):we.createElement(yr,{color:"gray",dimColor:!0},r+1)),we.createElement(yr,{wrap:"truncate",color:b},jl(t.title,e-u-m-18))),we.createElement($t,null,g,x))}});import{Box as Io,Text as Hl}from"ink";import _e from"react";import zl from"chalk";var Vl,Ks,qs=y(()=>{"use strict";T();xe();_t();ho();Hs();Vs();Vl=({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} ${zl.hex(L.secondary2).dim("("+m.length+")")}`,x=3,b=o?1:4,R=r-x-(o?2:1),I=_e.createElement(Io,{borderStyle:"round",borderColor:L.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},_e.createElement(Ne,{isSelected:t}),_e.createElement(Hl,{bold:!0,color:t?L.accent:L.primary},g," ",e.readonly?"\u{1F512}":"")),k=(A,U)=>{let j=i&&d===U;return o?_e.createElement(zs,{key:A.id,index:U,width:n,ticket:A,isSelected:j,mode:l}):_e.createElement(js,{key:A.id,width:n,ticket:A,isSelected:j})};return _e.createElement(Io,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?L.accent:L.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})))},Ks=_e.memo(Vl)});import{createHash as Kl}from"node:crypto";var ql,Gl,ot,bo=y(()=>{"use strict";ql="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Gl=e=>{let t=Kl("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+=ql[Number(n>>i&31n)]}return r},ot=(e,t)=>Gl(`${e}:virtual:${t}`)});import{Box as xr,Text as Yl}from"ink";import qe from"react";var Gs,Ys=y(()=>{"use strict";te();se();kt();T();xe();Eo();_t();No();Gs=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Be(),{title:o}=t,i=t.parentNodeId?N.getNode(t.parentNodeId):void 0,d=i&&$(i)?o===Q.ASSIGNEES?i.props.assignees??[]:o===Q.TAGS?i.props.tags??[]:[]:[];return qe.createElement(xr,{alignItems:"center",paddingTop:1},qe.createElement(xr,{minWidth:12},qe.createElement(Ne,{isSelected:n}),qe.createElement(Yl,{color:n?L.accent:L.secondary2},o,":")),qe.createElement(xr,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=r.id===t.id&&u===e;return qe.createElement(xr,{key:`${o}-${l}`,paddingRight:2,minHeight:1},qe.createElement(Ne,{isSelected:m}),o===Q.ASSIGNEES?qe.createElement(gr,{isSelected:m,id:l}):o===Q.TAGS?qe.createElement(fr,{isSelected:m,id:l}):null)})))}});var ve,gn=y(()=>{"use strict";te();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 So}from"ink";import Ge,{useEffect as Xl,useMemo as Xs}from"react";var Jl,Js,Co,Qs,Ql,Ro,Zs=y(()=>{"use strict";se();S();gn();T();xe();Dt();_t();ho();At();Jl="\u2029",Js=(e,t)=>`${e}::inline-line::${t}`,Co=new Map,Qs=e=>{let t=Co.get(e)??[];Co.delete(e);for(let n of t)N.deleteNode(n)},Ql=(e,t)=>{Qs(e);let n=[];t.forEach((r,o)=>{let i=Se(BigInt(o+1));if(!Xt(i))return;let d=N.createNode(ve.text({id:Js(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:i.value,props:{value:r},readonly:!0,isVirtual:!0}));Xt(d)&&n.push(d.value.id)}),Co.set(e,n)},Ro=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:d,contextNode:l}=Be(),u=Xs(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Xs(()=>u.join("\0"),[u]);Xl(()=>(Ql(e,u),()=>{Qs(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:Js(e,R)},Ge.createElement(So,{color:I?L.primary:L.secondary2,dimColor:!I},`${R+1} `.padStart(5,"\xA0")),Ge.createElement(So,{backgroundColor:I?"gray":void 0},g(b.length?Kn(b,i-10):Jl)))});return Ge.createElement(hr,{flexDirection:"column",paddingTop:1},Ge.createElement(hr,null,Ge.createElement(Ne,{isSelected:o}),Ge.createElement(So,{color:o?L.accent:L.secondary2},t)),Ge.createElement(hr,{flexDirection:"row",borderStyle:"round",borderColor:L.secondary,paddingLeft:1,marginLeft:1},Ge.createElement(pr,{scrollByOne:!0,height:r-3,selectedIndex:d,itemHeight:1},x)))}});import{Box as Ao,Text as Zl}from"ink";import it,{useMemo as ea}from"react";var eu,tu,ta,na=y(()=>{"use strict";te();se();T();xe();bo();_t();Ys();Zs();eu=e=>ot(e,"description"),tu=e=>ot(e,"history"),ta=({ticket:e,height:t})=>{let{selectedIndex:n,contextNode:r}=Be(),o=process.stdout.columns||120,i=ea(()=>eu(e.id),[e.id]),d=ea(()=>tu(e.id),[e.id]),l=r.id===e.id,u=r.id===d||r.parentNodeId===d,m=K(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)=>Jt(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}):Jt(A)?it.createElement(Gs,{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(Zl,{backgroundColor:L.secondary,color:U?L.accent:L.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 nu}from"ink";import Er from"react";var ru,ra,oa=y(()=>{"use strict";te();qs();na();ru=({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(nu,{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(Ks,{key:A.id,height:d,width:I,swimlane:A,isSelected:Je,isDense:k,isFocused:j,listSelectedIndex:lt,mode:o})}),m&&x&&Er.createElement(ta,{height:d,ticket:x}))},ra=Er.memo(ru)});import ia from"node:fs";import ou from"node:path";import iu from"react";import{render as su}from"ink";import{Writable as au}from"node:stream";var fn,du,cu,lu,uu,sa,aa=y(()=>{"use strict";oa();te();S();T();ne();ge();fn=e=>String(e).padStart(2,"0"),du=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}`},cu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",lu=async(e,{width:t,height:n})=>{let r="",o=new au({write(d,l,u){let m=uu(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=su(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),i.unmount(),r},uu=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),sa=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 lu(iu.createElement(ra,{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=Fn(process.cwd());if(a(g))return s("Unable to export, epiq root not found");let x=new Date,b=du(x),R=`board_${cu(d.title)}_${b}.md`,I=_i(g.value);ia.mkdirSync(I,{recursive:!0});let k=ou.join(I,R),A=`# Board - ${d.title}
23
23
  Date: ${x.toISOString()}
24
24
 
25
25
  \`\`\`text
26
26
  ${m}
27
27
  \`\`\`
28
- `;return oa.writeFileSync(k,A,"utf8"),c("Exported board layout",k)}});var M,aa,da,we=y(()=>{"use strict";Ce();T();M={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"||M.navigate({contextNode:r,selectedIndex:K(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=K(n.id),o=r.findIndex(({id:d})=>d===e.id),i=r.length===0?-1:o>=0?o:0;M.navigate({contextNode:n,selectedIndex:i})},navigateToNextItem:()=>aa(1),navigateToPreviousItem:()=>aa(-1),navigateToNextContainer:()=>da(1),navigateToPreviousContainer:()=>da(-1),navigate:({contextNode:e,selectedIndex:t})=>{E({contextNodeId:e.id,selectedIndex:t})}},aa=e=>{let{selectedIndex:t,contextNode:n}=v(),r=K(n.id).length;if(r===0)return;let i=(Math.max(0,t)+e+r)%r;M.navigate({selectedIndex:i,contextNode:n})},da=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=K(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=K(l.id),m=Math.max(0,u.length-1),g=Math.min(Math.max(0,r),m),x=u.length?g:-1;M.navigate({contextNode:l,selectedIndex:x})}});import{accessSync as mu,copyFileSync as pu,existsSync as xr,mkdirSync as ca,readdirSync as la,readFileSync as gu,renameSync as fu,rmSync as vu,statSync as ua,unlinkSync as yu,writeFileSync as xu}from"node:fs";import _t from"node:path";var he,wo=y(()=>{"use strict";he={writeToFile:(e,t)=>{try{let n=_t.dirname(e);xr(n)||ca(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);xu(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return gu(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 xr(e)&&ua(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await mu(e),!0}catch{return!1}},mkDir:e=>ca(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=_t.parse(t);for(;;){let r=_t.join(t,e);try{if(xr(r)&&ua(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=_t.dirname(t)}return null},readFirstJSON(e){try{if(!he.dirExists(e))return null;let t=la(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=_t.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)?la(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{yu(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{vu(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(_t.dirname(t)),!n?.overwrite&&xr(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{fu(e,t)}catch(r){if(r?.code==="EXDEV"){pu(e,t),this.rmFile(e);return}throw r}}}});import hu from"node:os";import ma from"node:path";import{z as st}from"zod";var Eu,pa,Nu,ga,To,Mo,Iu,fa,va,qe,ya,$t=y(()=>{"use strict";ne();S();wo();Eu={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},pa=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(),Nu="config.json",ga=()=>ma.join(hu.homedir(),Ee),To=()=>ma.join(ga(),Nu),Mo=()=>{try{return he.mkDir(ga()),c(`Ensured ~/${Ee} exists`,null)}catch{return s(`Unable to create ~/${Ee}`)}},Iu=e=>{let t;try{t=JSON.parse(e)}catch{return s(`Invalid ~/${Ee}/config.json JSON`)}let n=pa.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(", ")}`)},fa=()=>{let e=Mo();if(a(e))return s(e.message);let t=To(),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}):Iu(n)},va=e=>{let t=Mo();if(a(t))return s(t.message);let n=pa.safeParse(e);if(!n.success)return s(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=To();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`)}},qe=e=>{let t=fa();if(a(t))return s("Failed to read existing config");let n={...t.value,...e};return va(n)},ya=()=>{let e=To(),t=Mo();if(a(t))return s(`Unable to create ~/${Ee}`);if(!(he.readFile(e)!==null)){let g=va(Eu);if(a(g))throw new Error(`Unable to create ~/${Ee}/config.json`)}let r=fa();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 hr from"node:fs";import Po from"node:path";import{decodeTime as bu}from"ulid";import{z as Lo}from"zod";function Do(e){let t=on(e);if(!hr.existsSync(t))return c("No events found",[]);let n=hr.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Po.join(t,o)),r=[];for(let o of n){let i=Mu(o);if(a(i))return s(i.message);r.push(...i.value)}return c("All events loaded",Lu(r))}function Wt(e){let t=Do(e);return a(t)?s(t.message):ko(t.value)}function xa(e,t){let n=Do(e);if(a(n))return s(n.message);let{appliedEvents:r,unappliedEvents:o}=Pu(n.value,t),i=ko(r);if(a(i))return s(i.message);let d=ko(o);return a(d)?s(d.message):c("Loaded merged events before time",{appliedEvents:i.value,unappliedEvents:d.value})}function ha(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 Su,Cu,Ru,Au,wu,Tu,ko,Mu,Lu,Pu,vn=y(()=>{"use strict";S();ne();Te();Su=Lo.object({userId:Lo.string().min(1).default("unknown"),userName:Lo.string().min(1).default("unknown")}),Cu=e=>{let[t,n]=Po.basename(e,".jsonl").split("."),r=Su.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):s(`Invalid event file name ${Po.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Ru=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])},Au=(e,t)=>t in e,wu=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Tu=e=>{let{userId:t,userName:n,...r}=e,o=Ru(r);if(a(o))return s(o.message);let i=o.value,d=e.id?.[0];return d?Au(r,i)?c("Decoded persisted event",wu({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")},ko=e=>{let t=[];for(let n of e){let r=Tu(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)},Mu=e=>{if(!hr.existsSync(e))return c("Event file missing",[]);let t=Cu(e);if(a(t))return s(t.message);let n=hr.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=Fo(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)};Lu=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},Pu=(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=bu(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 Ea,Na=y(()=>{"use strict";Ea=e=>({action:e.action,payload:e.payload})});import ku from"node:fs";import Du from"node:path";import{decodeTime as Fu,monotonicFactory as Ou}from"ulid";import{z as yn}from"zod";function Nr({event:e,rootDir:t}){try{let n=_i(t);if(a(n))return n;let r=_u(t,{userId:e.userId,userName:e.userName});if(a(r))return r;let o=ha(t);if(a(o))return s(o.message);let i=o.value?Ia(Math.max(Date.now(),Fu(o.value)+1)):Ia(),d=$u(Ea(e),[i,o.value]);return a(d)?s(d.message):(ku.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 ba,Ia,Uu,Bu,Fo,Er,J,xt,_u,$u,Te=y(()=>{"use strict";S();ge();ne();vn();Na();ba=1,Ia=Ou(),Uu=yn.tuple([yn.string().min(1),yn.string().min(1).nullable()]),Bu=yn.looseObject({v:yn.literal(ba),id:Uu}),Fo=e=>{let t=Bu.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(", ")}`)},Er=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",J=()=>{let{userName:e,userId:t}=Y();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:Er(t),userName:Er(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},xt=({userId:e,userName:t})=>`${Er(e)}.${Er(t)}.jsonl`,_u=(e,{userId:t,userName:n})=>{let r=xt({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return s(`Invalid event log file name: ${r}`);let i=Du.join(on(e),r);return c("Successfully resolved event log path",i)},$u=(e,t)=>{let n={[e.action]:e.payload,v:ba,id:t};return Fo(n)}});var Sa,Ca=y(()=>{"use strict";Sa=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)return r.payload.parent}return null}});var Wu,ue,Ir,xn=y(()=>{"use strict";Wu=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ue,Ir]=Wu});import{useSyncExternalStore as Rh}from"react";var Oo,ju,Hu,jt,zu,at,br=y(()=>{"use strict";S();ju=new Set,Hu=()=>{for(let e of ju)e()},jt=()=>{if(!Oo)throw new Error("Ui state not initialized. Call initUiState() first.");return Oo},zu=e=>{let t=jt();return Oo=e(t),Hu(),c("UX state updated",null)},at=e=>zu(t=>({...t,...e}))});import{spawnSync as Vu}from"node:child_process";import Ku from"node:os";import Ra from"node:path";import{ulid as qu}from"ulid";function Gu(){let{preferredEditor:e}=Y(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Yu(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function Aa(e){let t=Ra.join(Ku.tmpdir(),"epiq");he.mkDir(t);let n=Ra.join(t,qu());he.writeToFile(n,e??"");let r=Gu();for(let o of r){let i=Yu(o,n),d=Vu(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 wa=y(()=>{"use strict";S();ge();wo()});import{ulid as Xu}from"ulid";var Ta,Ma=y(()=>{"use strict";wa();ht();Te();cn();S();Pt();T();ne();te();Ta=async()=>{let e=J();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(!$(d))return s("Edit target must be an issue");if(d.readonly)return s("Cannot edit readonly issue");let l=K(d.id).find(x=>x.title===Q.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=Aa(u);if(a(m))return s("Failed to edit field");let g=m.value;return g===u?c("No changes made",null):Me({id:Xu(),action:"edit.description",payload:{id:d.id,md:g},...e.value},n)}});import Uo from"node:fs";import Ju from"node:path";var La,Pa=y(()=>{"use strict";S();Pn();La=async e=>{let t=Ju.join(e,".gitignore"),n=Uo.existsSync(t)?Uo.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
28
+ `;return ia.writeFileSync(k,A,"utf8"),c("Exported board layout",k)}});var M,da,ca,Te=y(()=>{"use strict";Ce();T();M={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"||M.navigate({contextNode:r,selectedIndex:K(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=K(n.id),o=r.findIndex(({id:d})=>d===e.id),i=r.length===0?-1:o>=0?o:0;M.navigate({contextNode:n,selectedIndex:i})},navigateToNextItem:()=>da(1),navigateToPreviousItem:()=>da(-1),navigateToNextContainer:()=>ca(1),navigateToPreviousContainer:()=>ca(-1),navigate:({contextNode:e,selectedIndex:t})=>{E({contextNodeId:e.id,selectedIndex:t})}},da=e=>{let{selectedIndex:t,contextNode:n}=v(),r=K(n.id).length;if(r===0)return;let i=(Math.max(0,t)+e+r)%r;M.navigate({selectedIndex:i,contextNode:n})},ca=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=K(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=K(l.id),m=Math.max(0,u.length-1),g=Math.min(Math.max(0,r),m),x=u.length?g:-1;M.navigate({contextNode:l,selectedIndex:x})}});import{accessSync as mu,copyFileSync as pu,existsSync as Nr,mkdirSync as la,readdirSync as ua,readFileSync as gu,renameSync as fu,rmSync as vu,statSync as ma,unlinkSync as yu,writeFileSync as xu}from"node:fs";import Wt from"node:path";var he,wo=y(()=>{"use strict";he={writeToFile:(e,t)=>{try{let n=Wt.dirname(e);Nr(n)||la(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);xu(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return gu(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)&&ma(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await mu(e),!0}catch{return!1}},mkDir:e=>la(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Wt.parse(t);for(;;){let r=Wt.join(t,e);try{if(Nr(r)&&ma(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Wt.dirname(t)}return null},readFirstJSON(e){try{if(!he.dirExists(e))return null;let t=ua(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Wt.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)?ua(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{yu(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{vu(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Wt.dirname(t)),!n?.overwrite&&Nr(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{fu(e,t)}catch(r){if(r?.code==="EXDEV"){pu(e,t),this.rmFile(e);return}throw r}}}});import hu from"node:os";import pa from"node:path";import{z as st}from"zod";var Eu,ga,Nu,fa,To,Mo,Iu,va,ya,Ye,xa,jt=y(()=>{"use strict";ne();S();wo();Eu={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},ga=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(),Nu="config.json",fa=()=>pa.join(hu.homedir(),Ee),To=()=>pa.join(fa(),Nu),Mo=()=>{try{return he.mkDir(fa()),c(`Ensured ~/${Ee} exists`,null)}catch{return s(`Unable to create ~/${Ee}`)}},Iu=e=>{let t;try{t=JSON.parse(e)}catch{return s(`Invalid ~/${Ee}/config.json JSON`)}let n=ga.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(", ")}`)},va=()=>{let e=Mo();if(a(e))return s(e.message);let t=To(),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}):Iu(n)},ya=e=>{let t=Mo();if(a(t))return s(t.message);let n=ga.safeParse(e);if(!n.success)return s(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=To();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=va();if(a(t))return s("Failed to read existing config");let n={...t.value,...e};return ya(n)},xa=()=>{let e=To(),t=Mo();if(a(t))return s(`Unable to create ~/${Ee}`);if(!(he.readFile(e)!==null)){let g=ya(Eu);if(a(g))throw new Error(`Unable to create ~/${Ee}/config.json`)}let r=va();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 Po from"node:path";import{decodeTime as bu}from"ulid";import{z as Lo}from"zod";function Do(e){let t=sn(e);if(!Ir.existsSync(t))return c("No events found",[]);let n=Ir.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Po.join(t,o)),r=[];for(let o of n){let i=Mu(o);if(a(i))return s(i.message);r.push(...i.value)}return c("All events loaded",Lu(r))}function Ht(e){let t=Do(e);return a(t)?s(t.message):ko(t.value)}function ha(e,t){let n=Do(e);if(a(n))return s(n.message);let{appliedEvents:r,unappliedEvents:o}=Pu(n.value,t),i=ko(r);if(a(i))return s(i.message);let d=ko(o);return a(d)?s(d.message):c("Loaded merged events before time",{appliedEvents:i.value,unappliedEvents:d.value})}function Ea(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 Su,Cu,Ru,Au,wu,Tu,ko,Mu,Lu,Pu,vn=y(()=>{"use strict";S();ne();Me();Su=Lo.object({userId:Lo.string().min(1).default("unknown"),userName:Lo.string().min(1).default("unknown")}),Cu=e=>{let[t,n]=Po.basename(e,".jsonl").split("."),r=Su.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):s(`Invalid event file name ${Po.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Ru=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])},Au=(e,t)=>t in e,wu=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Tu=e=>{let{userId:t,userName:n,...r}=e,o=Ru(r);if(a(o))return s(o.message);let i=o.value,d=e.id?.[0];return d?Au(r,i)?c("Decoded persisted event",wu({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")},ko=e=>{let t=[];for(let n of e){let r=Tu(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)},Mu=e=>{if(!Ir.existsSync(e))return c("Event file missing",[]);let t=Cu(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=Fo(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)};Lu=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},Pu=(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=bu(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 Na,Ia=y(()=>{"use strict";Na=e=>({action:e.action,payload:e.payload})});import ku from"node:fs";import Du from"node:path";import{decodeTime as Fu,monotonicFactory as Ou}from"ulid";import{z as yn}from"zod";function Sr({event:e,rootDir:t}){try{let n=$i(t);if(a(n))return n;let r=_u(t,{userId:e.userId,userName:e.userName});if(a(r))return r;let o=Ea(t);if(a(o))return s(o.message);let i=o.value?ba(Math.max(Date.now(),Fu(o.value)+1)):ba(),d=$u(Na(e),[i,o.value]);return a(d)?s(d.message):(ku.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 Sa,ba,Uu,Bu,Fo,br,J,ht,_u,$u,Me=y(()=>{"use strict";S();ge();ne();vn();Ia();Sa=1,ba=Ou(),Uu=yn.tuple([yn.string().min(1),yn.string().min(1).nullable()]),Bu=yn.looseObject({v:yn.literal(Sa),id:Uu}),Fo=e=>{let t=Bu.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",J=()=>{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`,_u=(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=Du.join(sn(e),r);return c("Successfully resolved event log path",i)},$u=(e,t)=>{let n={[e.action]:e.payload,v:Sa,id:t};return Fo(n)}});var Ca,Ra=y(()=>{"use strict";Ca=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)return r.payload.parent}return null}});var Wu,ue,Cr,xn=y(()=>{"use strict";Wu=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ue,Cr]=Wu});import{useSyncExternalStore as Ch}from"react";var Oo,ju,Hu,zt,zu,at,Rr=y(()=>{"use strict";S();ju=new Set,Hu=()=>{for(let e of ju)e()},zt=()=>{if(!Oo)throw new Error("Ui state not initialized. Call initUiState() first.");return Oo},zu=e=>{let t=zt();return Oo=e(t),Hu(),c("UX state updated",null)},at=e=>zu(t=>({...t,...e}))});import{spawnSync as Vu}from"node:child_process";import Ku from"node:os";import Aa from"node:path";import{ulid as qu}from"ulid";function Gu(){let{preferredEditor:e}=Y(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Yu(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function wa(e){let t=Aa.join(Ku.tmpdir(),"epiq");he.mkDir(t);let n=Aa.join(t,qu());he.writeToFile(n,e??"");let r=Gu();for(let o of r){let i=Yu(o,n),d=Vu(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 Ta=y(()=>{"use strict";S();ge();wo()});import{ulid as Xu}from"ulid";var Ma,La=y(()=>{"use strict";Ta();Et();Me();ln();S();kt();T();ne();te();Ma=async()=>{let e=J();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=Fe([...r,o],"TICKET");if(a(i))return s("Edit target must be an issue");let d=i.value;if(!$(d))return s("Edit target must be an issue");if(d.readonly)return s("Cannot edit readonly issue");let l=K(d.id).find(x=>x.title===Q.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=wa(u);if(a(m))return s("Failed to edit field");let g=m.value;return g===u?c("No changes made",null):Le({id:Xu(),action:"edit.description",payload:{id:d.id,md:g},...e.value},n)}});import Uo from"node:fs";import Ju from"node:path";var Pa,ka=y(()=>{"use strict";S();Dn();Pa=async e=>{let t=Ju.join(e,".gitignore"),n=Uo.existsSync(t)?Uo.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
32
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(`
33
33
  `);return n=n.trimEnd()+`
34
34
 
35
35
  ${l}
36
- `,Uo.writeFileSync(t,n,"utf8"),ce.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)}});import Ht from"node:fs";import hn from"node:path";var Da,ka,Qu,Bo,Zu,em,tm,_o,nm,rm,Sr,Fa,En,Oa,$o=y(()=>{"use strict";S();Pn();Dn();Fn();Lt();wt();Da=async e=>{if((await Re({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);ce.info("Creating initial commit");let n=await q.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return a(n)?s(n.message):c("Created initial commit",!0)},ka=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Qu=async e=>{let t=await _n(e);if(a(t))return s(t.message);let n=await Ri(e);return a(n)?s(n.message):c("Built sync commit message",`[sync|branch:${ka(t.value)}:sha:${ka(n.value)}]`)},Bo=async({repoRoot:e,stateBranchName:t})=>{ce.info(`Creating ${t}`);let n=await O({args:["commit-tree",ki,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return s(`Failed to create state branch commit
36
+ `,Uo.writeFileSync(t,n,"utf8"),ce.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)}});import Vt from"node:fs";import hn from"node:path";var Fa,Da,Qu,Bo,Zu,em,tm,_o,nm,rm,Ar,Oa,En,Ua,$o=y(()=>{"use strict";S();Dn();On();Un();Pt();Tt();Fa=async e=>{if((await Re({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);ce.info("Creating initial commit");let n=await q.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return a(n)?s(n.message):c("Created initial commit",!0)},Da=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Qu=async e=>{let t=await Wn(e);if(a(t))return s(t.message);let n=await Ai(e);return a(n)?s(n.message):c("Built sync commit message",`[sync|branch:${Da(t.value)}:sha:${Da(n.value)}]`)},Bo=async({repoRoot:e,stateBranchName:t})=>{ce.info(`Creating ${t}`);let n=await O({args:["commit-tree",Di,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return s(`Failed to create state branch commit
37
37
  ${n.message}`);let r=n.value.stdout.trim(),o=await O({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)},Zu=async({repoRoot:e,stateBranchName:t})=>{let n=await Gr({repoRoot:e});if(a(n))return s(`Ensure local state branch failed
39
- `+n.message);let r=n.value,o=r?await en({repoRoot:e,branch:t}):c("No remote, no remote state branch",!1);if(a(o))return s(`Ensure local state branch failed
38
+ ${o.message}`):c("Created state branch",!0)},Zu=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 tn({repoRoot:e,branch:t}):c("No remote, no remote state branch",!1);if(a(o))return s(`Ensure local state branch failed
40
40
  `+o.message);let i=o.value;if(r&&i){let l=await q.fetch({cwd:e,remote:pe,branch:t});if(a(l))return s(`Failed to fetch ${t} from remote
41
- ${l.message}`)}let d=await Bn({repoRoot:e,branch:t});if(a(d))return s(`Ensure local state branch failed
41
+ ${l.message}`)}let d=await $n({repoRoot:e,branch:t});if(a(d))return s(`Ensure local state branch failed
42
42
  `+d.message);if(d.value)return c("Local state branch already exists",!1);if(i){let l=await O({args:["branch","--track",t,`${pe}/${t}`],cwd:e});return a(l)?s(`Failed to create local ${t} from remote
43
43
  ${l.message}`):c("Created local state branch from remote",!0)}return Bo({repoRoot:e,stateBranchName:t})},em=async({repoRoot:e,branch:t})=>{let n=await O({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)},tm=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=tn(hn.dirname(t));if(a(r))return s(`Failed to create state branch worktree
45
- `+r.message);Ht.existsSync(t)&&!Ht.existsSync(hn.join(t,".git"))&&(ce.info("Removing broken state branch worktree path"),Fi(t)),ce.info("Creating state branch worktree");let o=await q.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)},_o=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await em({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&&Ht.existsSync(i))return c("State branch already checked out in expected worktree",!1);if(i&&i!==o){ce.info("Moving state branch worktree to expected location");let u=await q.worktreeRemove({cwd:e,worktreeRoot:i});if(a(u))return s(`Failed to remove existing state branch worktree
47
- ${u.message}`)}if(i&&!Ht.existsSync(i)){ce.info("Pruning stale state branch worktree");let u=await q.worktreePrune({cwd:e});if(a(u))return s(`Failed to prune stale worktrees
48
- ${u.message}`)}let d=await Ci({repoRoot:e,worktreeRoot:t});if(a(d))return s(d.message);let l=Ht.existsSync(t);if(d.value&&l)return c("State branch worktree already exists",!1);if(d.value&&!l){ce.info("Pruning missing registered state branch worktree");let u=await q.worktreePrune({cwd:e});if(a(u))return s(`Failed to prune stale worktrees
49
- ${u.message}`)}return tm({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},nm=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await _n(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&&ce.info("Aborted stale state branch rebase");let o=await q.checkout({cwd:e,branch:t});return a(o)?s(`Failed to checkout ${t}
50
- ${o.message}`):c("Checked out state branch",!0)},rm=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Yr(t);if(a(n))return s(n.message);if(n.value)return c("State branch upstream already configured",!1);let r=await Gr({repoRoot:t});if(a(r))return s(r.message);if(!r.value)return c("No remote available for state branch upstream",!1);let o=lt(e);if(a(o))return o;let i=o.value,d=await en({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);ce.info(`Configuring ${i} upstream`);let l=await q.fetch({cwd:t,remote:pe,branch:i});if(a(l))return s(`Failed to fetch ${i}
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)},tm=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=nn(hn.dirname(t));if(a(r))return s(`Failed to create state branch worktree
45
+ `+r.message);Vt.existsSync(t)&&!Vt.existsSync(hn.join(t,".git"))&&(ce.info("Removing broken state branch worktree path"),Oi(t)),ce.info("Creating state branch worktree");let o=await q.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)},_o=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await em({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&&Vt.existsSync(i))return c("State branch already checked out in expected worktree",!1);if(i&&i!==o){ce.info("Moving state branch worktree to expected location");let u=await q.worktreeRemove({cwd:e,worktreeRoot:i});if(a(u))return s(`Failed to remove existing state branch worktree
47
+ ${u.message}`)}if(i&&!Vt.existsSync(i)){ce.info("Pruning stale state branch worktree");let u=await q.worktreePrune({cwd:e});if(a(u))return s(`Failed to prune stale worktrees
48
+ ${u.message}`)}let d=await Ri({repoRoot:e,worktreeRoot:t});if(a(d))return s(d.message);let l=Vt.existsSync(t);if(d.value&&l)return c("State branch worktree already exists",!1);if(d.value&&!l){ce.info("Pruning missing registered state branch worktree");let u=await q.worktreePrune({cwd:e});if(a(u))return s(`Failed to prune stale worktrees
49
+ ${u.message}`)}return tm({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},nm=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&&ce.info("Aborted stale state branch rebase");let o=await q.checkout({cwd:e,branch:t});return a(o)?s(`Failed to checkout ${t}
50
+ ${o.message}`):c("Checked out state branch",!0)},rm=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 tn({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);ce.info(`Configuring ${i} upstream`);let l=await q.fetch({cwd:t,remote:pe,branch:i});if(a(l))return s(`Failed to fetch ${i}
51
51
  ${l.message}`);let u=await q.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)},Sr=async({stateBranchRoot:e,eventFileName:t})=>{let n=nn(t),r=hn.join(e,n);if(!Ht.existsSync(r))return c("No event file to stage",void 0);let o=await q.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)},Fa=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Qu(e);return a(n)?s(`Create state branch sync commit failed
54
- `+n.message):Tt({cwd:t,message:n.value})},En=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Yr(t);if(a(n))return s(n.message);let r=lt(e);if(a(r))return r;let o=r.value,i=n.value?await q.push({cwd:t}):await q.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)},Oa=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=lt(e);if(a(o))return o;let i=o.value,d=[Wn(),await Zu({repoRoot:e,stateBranchName:i}),await _o({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await nm({stateBranchRoot:t,stateBranchName:i}),await Ui(t),n?await rm({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 om,ulid as Ge}from"ulid";function im(){let e=ke();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]=K(n.id),[o]=r?K(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 sm(){let e=im();return a(e)?e:M.navigate(e.value)}function Ua({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 I=me(void 0,void 0);return a(I)?I:c("Created default events",[{id:Ge(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:Ge(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Ge(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:g.value}},{id:Ge(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"In progress",parent:r,rank:x.value}},{id:Ge(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:r,rank:b.value}},{id:Ge(),userId:e,userName:t,action:"add.board",payload:{id:Ir,name:"Closed",parent:n,rank:m.value}},{id:Ge(),userId:e,userName:t,action:"add.swimlane",payload:{id:ue,name:"Closed",parent:Ir,rank:I.value}},{id:Ge(),userId:e,userName:t,action:"lock.node",payload:{id:Ir}},{id:Ge(),userId:e,userName:t,action:"lock.node",payload:{id:ue}}])}function Cr(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=Et(e).filter(a);return n.length>0?s(`Materializing failed:
52
+ ${u.message}`):c("Configured state branch upstream",!0)},Ar=async({stateBranchRoot:e,eventFileName:t})=>{let n=rn(t),r=hn.join(e,n);if(!Vt.existsSync(r))return c("No event file to stage",void 0);let o=await q.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)},Oa=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Qu(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 q.push({cwd:t}):await q.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)},Ua=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 Zu({repoRoot:e,stateBranchName:i}),await _o({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await nm({stateBranchRoot:t,stateBranchName:i}),await Bi(t),n?await rm({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 om,ulid as Xe}from"ulid";function im(){let e=De();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]=K(n.id),[o]=r?K(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 sm(){let e=im();return a(e)?e:M.navigate(e.value)}function Ba({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:Cr,name:"Closed",parent:n,rank:m.value}},{id:Xe(),userId:e,userName:t,action:"add.swimlane",payload:{id:ue,name:"Closed",parent:Cr,rank:R.value}},{id:Xe(),userId:e,userName:t,action:"lock.node",payload:{id:Cr}},{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
56
  ${n.map(r=>r.message).join(`
57
- `)}`):(sm(),E({hasProjectDefinition:!0}),c("State booted successfully",null))}var Nn,Rr=y(()=>{"use strict";we();G();S();gn();T();Rt();zt();xn();Nn=om()});import am from"node:fs";import Ba from"node:path";var dm,V,_a,$a=y(()=>{"use strict";Pa();Dn();Lt();wt();$o();we();an();Rr();zt();Te();G();S();At();oe();ge();T();ne();dm=async e=>{let t=await O({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}`),_a=async()=>{W("");let e=fi(),t=await tt(process.cwd());if(a(t))return V(1,t.message);let n=t.value,r=await Un(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");let o=await dm(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(Qr(n))return V(4,"Epiq project already initialized");let i=Yn();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 Bn({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 Bo({repoRoot:n,stateBranchName:m});if(a(x))return V(6,x.message);let b=Wn();if(a(b))return V(7,b.message);let I=Ba.join($n(),e.projectId),R=await _o({repoRoot:n,stateBranchRoot:I,stateBranchName:m});if(a(R))return V(8,R.message);let k=Ba.join(I,".epiq");am.mkdirSync(k,{recursive:!0});let A=Ua({userId:u,userName:l});if(a(A))return V(9,A.message);for(let $r of A.value){let ci=Nr({event:$r,rootDir:I});if(a(ci))return V(9,ci.message)}let U=await Sr({stateBranchRoot:I,eventFileName:xt({userId:u,userName:l})});if(a(U))return V(10,U.message);let j=await Tt({cwd:I,message:"[epiq:init]"});if(a(j))return V(10,j.message);let ct=await La(n);if(a(ct))return V(11,ct.message);let Xe=yi({repoRoot:n,fileContents:e});if(a(Xe))return V(12,Xe.message);let ri=await q.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(ri))return V(13,ri.message);let oi=await q.commit({cwd:n,message:"[epiq:init-project]"});if(a(oi))return V(13,oi.message);let Br="Project initialized!",ii=await O({cwd:n,args:["push","-u","origin","HEAD"]});a(ii)&&(Br+=` Warn: [init:14] ${ii.message}`);let si=await En({repoRoot:n,stateBranchRoot:I});a(si)&&(Br+=` Warn: [init:15] ${si.message}`);let ai=Et(A.value).filter(a);if(ai.length>0)return V(16,ai.map($r=>$r.message).join(`
58
- `));let _r=ke();if(a(_r))return V(16,_r.message);let{rootNodeId:Cc,nodes:Rc}=_r.value,di=Rc[Cc];return di?(M.navigate({contextNode:di,selectedIndex:0}),E({hasProjectDefinition:!0,mode:p.DEFAULT}),c(Br,null)):V(16,"Unable to resolve initialized root node")}});import{ulid as cm}from"ulid";function jo(e){let t=ja();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=Ha({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:za(u.value)}function Ho(e){let t=ja();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=Ha({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return a(d)?d:za(d.value)}var Wa,dt,bn,ja,Wo,Ha,za,zo=y(()=>{"use strict";zt();Te();S();Ce();T();Wa=null,dt=()=>structuredClone(Wa),bn=e=>{Wa=e},ja=()=>{let{contextNode:e,selectedIndex:t}=v(),r=H(e.id)[t];return r?c("Resolved selected child",r):s("Target node not found")},Wo=({id:e,parentId:t,position:n={at:"end"}})=>{let r=H(t).filter(o=>o.id!==e);return Ar(r,n)},Ha=({id:e,parentId:t,position:n={at:"end"}})=>{let r=J();if(a(r))return s("Unable to resolve user ID");let o=Wo({parentId:t,id:e,position:n});return a(o)?o:c("Created pending move state",{id:cm(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},za=e=>{bn(e);let t=Sn(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as lm}from"ulid";var Va,wr,Ka,qa=y(()=>{"use strict";we();zo();ht();Te();G();S();Ce();oe();T();ne();Va=()=>{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"):(M.navigate({contextNode:r,selectedIndex:o}),c("Synchronized navigation to moved node",null))},wr=(e,t="Moved preview")=>{if(a(e))return e;let n=Va();return a(n)?n:(E({mode:p.MOVE}),c(t,null))},Ka=async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{modifier:t}=ee().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=Wo({parentId:o.parentNodeId,id:o.id,position:m});return a(g)?g:(bn({id:lm(),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 wr(Ho(1));if(t==="previous")return wr(Ho(-1));if(t==="to-next")return wr(jo(1));if(t==="to-previous")return wr(jo(-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=Me(i,d.value);if(a(l))return l;let u=Va();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 um,ulid as mm}from"ulid";var pm,Tr,Vo=y(()=>{"use strict";S();pm=um(),Tr=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=pm();return c("Created issue events",[{id:mm(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}}])}});import{ulid as Mr}from"ulid";var Ga,Ya=y(()=>{"use strict";we();Vo();ht();Te();cn();S();se();Ce();T();ne();Ga=async(e,t)=>{let n=J();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=Me(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?(M.navigate({contextNode:b,selectedIndex:N.getSiblings(x.parentNodeId).findIndex(({id:I})=>I===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=Vt(g.id,n.value,o);return a(x)?x:u({id:Mr(),action:"add.board",payload:{id:Mr(),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=Vt(m.value.id,n.value,o);return a(g)?g:u({id:Mr(),action:"add.swimlane",payload:{id:Mr(),name:t.inputString,parent:m.value.id,rank:g.value},...n.value})}if(t.modifier==="issue"){let m=K(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=Vt(g.id,n.value,o);if(a(x))return x;let b=Tr({name:t.inputString,parent:g.id,rank:x.value,user:n.value});if(a(b))return b;let I=b.value,R=Kt(I,o);if(R.some(j=>a(j)))return s("Issue create failed: "+R.filter(a).map(j=>j.message).filter(Boolean).join(", "));let k=R[0];if(!k||a(k))return s("Issue creation failed");let U=I.find(j=>j.action==="add.issue")?.payload.id;return U?(M.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 Xa,Ja=y(()=>{"use strict";Lt();we();rr();vn();zt();G();cn();S();oe();T();tr();Xa=async()=>{let e=De(v().breadCrumb,"BOARD");if(a(e))return e;let t=await tt(process.cwd());if(a(t))return s("Unable to locate repo root");let n=Mt({repoRoot:t.value});if(a(n))throw new Error(n.message);let{modifier:r}=ee().commandMeta;if(r==="now"){let R=Wt(n.value);if(a(R))return s(R.message);let k=Cn();if(a(k))return k;let U=Et(R.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 R=v().eventLog.at(-1),k=so(R);if(k===null)return s("No previous event to peek");o=k}else if(r==="next"){let R=v().unappliedEvents.at(0),k=so(R);if(k===null)return s("No next event to peek");o=k+1}else{let R=er(r);if(!R)return s("Invalid peek date");o=R.getTime()}let i=v(),d=e.value.id,l=xa(n.value,o);if(a(l))return s(l.message);let{appliedEvents:u,unappliedEvents:m}=l.value,g=Cn();if(a(g))return g;let b=Et(u).filter(a);if(b.length>0)return Cn(),E(i),s(b.map(R=>R.message).join(", "));let I=v().nodes[d];return I?(M.navigate({contextNode:I,selectedIndex:0}),E({mode:p.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:m}),c("Peeking",!0)):(Cn(),E(i),s("Board did not exist at peek date"))}});import gm from"zod";var Qa,Za=y(()=>{"use strict";$t();G();S();oe();ge();T();Qa=()=>{let e=ee().commandMeta.inputString,t=gm.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=qe({autoSyncDebounceMs:t.data});return a(n)?n:(Pe({autoSyncIntervalMs:t.data}),E({mode:p.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))}});var ed,td=y(()=>{"use strict";an();$t();G();S();oe();ge();T();ed=()=>{let e=ee().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return s("Invalid response");let t=ts(e),n=qe({autoSync:t});return a(n)?n:(Pe({autoSync:t}),E({mode:p.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var nd,rd=y(()=>{"use strict";$t();G();S();oe();ge();T();nd=()=>{let e=ee().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return s("Invalid response");let n=qe({logLevel:e});return a(n)?n:(Pe({logLevel:e}),E({mode:p.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var od,id=y(()=>{"use strict";Gn();G();S();oe();T();od=async()=>{W(""),E({mode:p.DEFAULT});let e=ke();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 nt();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 sd,ad,dd,cd=y(()=>{"use strict";sa();we();$t();ht();Te();Ca();xn();G();te();S();se();Ce();oe();ge();T();br();ne();pt();vo();dn();Ma();$a();qa();Ya();Ja();Za();td();rd();id();sd=e=>Object.values(v().tags).find(t=>t.name===e),ad=e=>Object.values(v().contributors).find(t=>t.name===e),dd=[{systemOnly:!0,intent:P.Move,description:"Internal move-state command",mode:p.COMMAND_LINE,action:Ka},{intent:P.Delete,description:"Delete the currently selected node",mode:p.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=K(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:P.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:p.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ee().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(d=>ae(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:P.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:P.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:p.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=K(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!$(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=Gt(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:P.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:p.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=K(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):qt(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(!$(i))return s("Target node is not issue");let l=Sa(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=Gt(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:P.Init,description:"Initialize Epiq in the current git repository",mode:p.COMMAND_LINE,action:_a},{intent:P.NewItem,description:"Create a new board, swimlane, or issue",mode:p.COMMAND_LINE,action:Ga,onSuccess:()=>E({mode:p.DEFAULT})},{intent:P.Rename,description:"itle] Rename the currently selected node",mode:p.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=K(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=Fs();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:P.UntagTicket,description:"Remove a tag from the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=sd(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid untag target");let d=qt(i.id,"TICKET");if(a(d))return s("Unable to untag issue in this context");let l=d.value;return $(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:P.TagTicket,description:"Add or create a tag on the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().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=qt(o.id,"TICKET");if(a(i))return s("Unable to tag issue in this context");let d=i.value;if(!$(d))return s("Target node is not issue");let l=sd(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:P.AssignUserToTicket,description:"Assign a user to the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,contextNode:i}=v(),d=K(i.id)[o];if(!d)return s("Invalid assign target");let l=qt(d.id,"TICKET");if(a(l))return s("Unable to assign issue in this context");let u=l.value;if(!$(u))return s("Target node is not issue");let m=ad(r),g;if(m)g=m.id;else{let b=ye(),I=await Ie({id:ye(),action:"create.contributor",payload:{id:b,name:r},...e.value});if(a(I))return I;g=I.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:P.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=ad(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid unassign target");let d=qt(i.id,"TICKET");if(a(d))return s("Unable to unassign in this context");let l=d.value;return $(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:P.Sync,description:"Pull, commit, and push Epiq state",mode:p.COMMAND_LINE,action:od},{intent:P.Peek,description:"View board state at another point in time",mode:p.COMMAND_LINE,action:Xa},{intent:P.Export,description:"Export the current board layout to markdown",mode:p.COMMAND_LINE,action:async()=>{let e=await ia();return a(e)?e:(E({mode:p.DEFAULT}),c("Export successful",!0))}},{intent:P.Exit,description:"Exit the application",mode:p.COMMAND_LINE,action:async()=>(M.exit(),c("Exit successful",!0))},{intent:P.Edit,description:"Edit title or description",mode:p.COMMAND_LINE,action:async(e,t)=>{if(t.modifier===rt.DESCRIPTION)return Ta();if(t.modifier===rt.TITLE){let n=J();if(a(n))return s("Unable to resolve user ID");let{contextNode:r,selectedIndex:o}=v(),i=K(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:P.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=qe({userName:d,userId:l,preferredEditor:o??""});return a(u)?u:(Pe({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=qe({preferredEditor:n});return a(r)?r:(Pe({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"):(Pe({viewMode:n}),c(`View set to "${n}"`,null));case X.AUTOSYNC:return ed();case X.LOG_LEVEL:return nd();case X.SYNC_DEBOUNCE_MS:return Qa();default:return s("Unknown config command")}}}]});var fm,_e,Ko=y(()=>{"use strict";qn();sr();vo();cd();S();oe();ge();T();fm=new Set(["peek","filter","view-help"]),_e=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ee();if(!t)return s("No command to confirm");if(!e&&n===vt.Invalid)return s("Invalid command");let i=Os(t);Ls();let{readOnly:d}=v();if(d&&!fm.has(i))return mn({status:Je.Fail,message:"Command not available in readonly state",value:null});let l=dd.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===i);if(!l)return mn({status:Je.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return mn({status:Je.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?mn(u):(Ps({addToHistory:!e}),l.onSuccess?.(),Y().autoSync&&Qi(),u)}});var Lr,Pr,ld,ud=y(()=>{"use strict";S();G();T();ut();Ko();zo();oe();Lr=[{intent:C.Exit,mode:p.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:p.COMMAND_LINE}),W("move cancel"),_e({isForceExecutedBySystem:!0}))},{intent:C.InitMove,mode:p.DEFAULT,description:"[m] move (init/confirm)",action:()=>(E({mode:p.COMMAND_LINE}),W("move start"),_e({isForceExecutedBySystem:!0}))},{intent:C.ConfirmMove,mode:p.MOVE,action:()=>(E({mode:p.COMMAND_LINE}),W("move confirm"),_e({isForceExecutedBySystem:!0}))}],Pr=[{intent:C.MovePreviousItem,mode:p.MOVE,action:()=>dt()?(E({mode:p.COMMAND_LINE}),W("move previous"),_e({isForceExecutedBySystem:!0})):s("No pending move")},{intent:C.MoveNextItem,mode:p.MOVE,action:()=>dt()?(E({mode:p.COMMAND_LINE}),W("move next"),_e({isForceExecutedBySystem:!0})):s("No pending move")}],ld=[{intent:C.MoveToNextContainer,mode:p.MOVE,action:()=>dt()?(E({mode:p.COMMAND_LINE}),W("move to-next"),_e({isForceExecutedBySystem:!0})):s("No pending move")},{intent:C.MoveToPreviousContainer,mode:p.MOVE,action:()=>dt()?(E({mode:p.COMMAND_LINE}),W("move to-previous"),_e({isForceExecutedBySystem:!0})):s("No pending move")}]});var md,pd=y(()=>{"use strict";te();ud();md={[w.WORKSPACE]:[...Lr,...Pr],[w.BOARD]:[...Lr,...Pr],[w.SWIMLANE]:[...Lr,...Pr,...ld],[w.TICKET]:[],[w.FIELD]:[],[w.FIELD_LIST]:[],[w.TEXT]:[]}});var gd,fd,vd=y(()=>{"use strict";G();S();oe();T();br();ut();we();gd=()=>{W("");let{pendingNavTarget:e}=jt();E({mode:p.DEFAULT}),e&&M.navigate(e),at({pendingNavTarget:void 0})},fd=[{intent:C.ExitCommandLine,mode:p.HELP,action:()=>(gd(),c("Exiting help",null))},{intent:C.Exit,mode:p.HELP,action:()=>(gd(),c("Closed help",null))},{intent:C.NavPreviousItem,mode:p.HELP,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:C.NavNextItem,mode:p.HELP,action:()=>(M.navigateToNextItem(),c("Navigating to next help item",null))},{intent:C.NavToPreviousContainer,mode:p.HELP,action:()=>(M.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:C.NavToNextContainer,mode:p.HELP,action:()=>(M.navigateToNextContainer(),c("Navigating to next help container",null))}]});var vm,yd,xd,hd=y(()=>{"use strict";G();te();S();oe();T();br();ut();we();vm=e=>{E({mode:p.COMMAND_LINE});let{pendingNavTarget:t}=jt();t&&M.navigate(t),at({pendingNavTarget:void 0}),W(`${e} `)},yd=()=>{W("");let{pendingNavTarget:e}=jt();e&&M.navigate(e),at({pendingNavTarget:void 0}),E({mode:p.DEFAULT})},xd=[{intent:C.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:C.Confirm,mode:p.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!li(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?(vm(t),c("Selected command",t)):c("No command selected",null)}},{intent:C.ExitCommandLine,mode:p.PALETTE,action:()=>(yd(),c("Exiting palette",null))},{intent:C.Exit,mode:p.PALETTE,action:()=>(yd(),c("Closed command palette",null))},{intent:C.NavPreviousItem,mode:p.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:C.NavNextItem,mode:p.PALETTE,action:()=>(M.navigateToNextItem(),c("Navigating to next item",null))},{intent:C.NavToPreviousContainer,mode:p.PALETTE,action:()=>(M.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:C.NavToNextContainer,mode:p.PALETTE,action:()=>(M.navigateToNextContainer(),c("Navigating to next container",null))}]});var Ed,Nd=y(()=>{"use strict";pt();G();S();Pt();Ce();oe();T();ut();vd();hd();we();Ed=[...fd,...xd,{intent:C.AddItem,mode:p.DEFAULT,description:"[n] new...",action:()=>(E({mode:p.COMMAND_LINE}),W(`${f.NEW} `),c("Adding new item",null))},{intent:C.Delete,mode:p.DEFAULT,description:"[d] delete",action:()=>(E({mode:p.COMMAND_LINE}),W(`${f.DELETE} `),c("Deleting item",null))},{intent:C.InitCommandLine,mode:p.DEFAULT,description:"[:] focus command line",action:()=>(E({mode:p.COMMAND_LINE}),W(""),c("Entering command line mode",null))},{intent:C.Confirm,mode:p.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!H(e?.id??"")?.length){if(e?.title===Q.DESCRIPTION)return E({mode:p.COMMAND_LINE}),W(`${f.EDIT} description `),c("Propose command",!0);if(e?.title===Q.ASSIGNEES)return E({mode:p.COMMAND_LINE}),W(`${f.ASSIGN} `),c("Propose command",!0);if(e?.title===Q.TAGS)return E({mode:p.COMMAND_LINE}),W(`${f.TAG} `),c("Propose command",!0);if(t.title===Q.DESCRIPTION&&e?.context==="TEXT")return E({mode:p.COMMAND_LINE}),W(`${f.EDIT} description `),c("Propose command",!0)}return M.enterChildNode(),c("Entering context",null)}},{intent:C.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:C.EditDescription,mode:p.DEFAULT,description:"[e] edit description",action:()=>(E({mode:p.COMMAND_LINE}),W(`${f.EDIT} description `),c("Exiting context",null))},{intent:C.Exit,mode:p.DEFAULT,description:"[q] exit context",action:()=>(M.enterParentNode(),c("Exiting context",null))},{intent:C.NavPreviousItem,mode:p.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:C.NavNextItem,mode:p.DEFAULT,action:()=>(M.navigateToNextItem(),c("Navigating to next item",null))},{intent:C.NavToPreviousContainer,mode:p.DEFAULT,action:()=>(M.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:C.NavToNextContainer,mode:p.DEFAULT,action:()=>(M.navigateToNextContainer(),c("Navigating to next container",null))}]});var ym,xm,Id,bd=y(()=>{"use strict";oe();ym=500,xm=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Id=e=>{let t=xm(e);t&&cr(n=>(n+t).slice(0,ym))}});var hm,Em,Sd,Cd=y(()=>{"use strict";bd();G();S();oe();T();ut();Ko();hm=[p.COMMAND_LINE,p.PALETTE],Em=e=>[{intent:C.MoveCursorLeft,mode:e,action:()=>(go(-1),c("Moving cursor left",null))},{intent:C.MoveCursorRight,mode:e,action:()=>(go(1),c("Moving cursor right",null))},{intent:C.MoveCursorLeftOfWord,mode:e,action:()=>(fo("left"),c("Moving cursor left of word",null))},{intent:C.MoveCursorRightOfWord,mode:e,action:()=>(fo("right"),c("Moving cursor right of word",null))},{intent:C.AutoCompleteCommand,mode:e,action:()=>(cr((t,{remainder:n})=>n?t+n:t),c("Auto-completing command",null))},{intent:C.CaptureInput,mode:e,action:(t,{sequence:n})=>(Id(n??""),c("Capturing input",null))},{intent:C.EraseInput,mode:e,action:()=>(Ts(),c("Erasing input",null))},{intent:C.EraseInputWord,mode:e,action:()=>(Ms(),c("Erasing input word",null))}],Sd=[{intent:C.Confirm,mode:p.COMMAND_LINE,action:()=>(_e(),c("Executing command",null))},{intent:C.ViewHelp,mode:p.DEFAULT,action:()=>(E({mode:p.HELP}),c("Viewing help",null))},...hm.flatMap(Em),{intent:C.ExitCommandLine,mode:p.COMMAND_LINE,action:()=>(E({mode:p.DEFAULT}),c("Exiting command line",null))},{intent:C.GetLastCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(ks(),c("Getting last command from history",null))},{intent:C.GetNextCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(Ds(),c("Getting next command from history",null))}]});import wd from"chalk";var kr,Rd,Ad,qo,Td=y(()=>{"use strict";G();te();xe();kr=wd.dim.hex(L.secondary2)(": for command line"),Rd="q to exit",Ad=`${wd.hex(L.accent)("m")} to confirm`,qo={[w.WORKSPACE]:[kr],[w.BOARD]:[kr],[w.BOARD+p.COMMAND_LINE]:[kr],[w.SWIMLANE]:[kr],[w.TICKET+p.HELP]:[Rd],[w.SWIMLANE+p.HELP]:[Rd],[w.TICKET]:[],[w.FIELD]:[],[w.SWIMLANE+p.MOVE]:[Ad],[w.TICKET+p.MOVE]:[Ad]}});var Rn,Nm,Im,Md,Ld=y(()=>{"use strict";T();Rn=e=>e.trim().toLocaleLowerCase(),Nm=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Im=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},Md=(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 Nm(e).map(Rn).some(o=>o.includes(n));case"assignee":return Im(e).map(Rn).some(o=>o.includes(n));default:return!0}}});function Pd(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 kd=y(()=>{"use strict";S()});var Dd,Fd=y(()=>{"use strict";Dd=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 bm}from"react";function Ud(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=Pd(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:g}=l,x=qo[g+n]??qo[g]??[],b=[...Ed,...md[g]??[],...Sd],I=Dd(b),R=Cm(o,i),k=R[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:x,availableActions:b,actionIndex:I,selectedNode:k,renderedChildrenIndex:R})}function In(e){Go=e;let t=et(process.cwd()),n=!1;if(!a(t)){let i=Ze(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=Ud(r);return a(o)?o:(Nt=o.value,Od(),c("State initialized",null))}function be(e){let t=v(),n=e(t),r=Ud(n);return a(r)?s(r.message??"Unable to update state"):(Nt=r.value,Od(),c("State updated",null))}var Nt,Go,Yo,Od,Sm,v,ke,E,Ue,Cm,K,Cn,Ft,T=y(()=>{"use strict";pd();Nd();Cd();Td();At();G();te();S();ne();Ld();kd();Fd();Yo=new Set,Od=()=>{for(let e of Yo)e()},Sm=e=>(Yo.add(e),()=>Yo.delete(e));v=()=>{if(!Nt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Nt},ke=()=>Nt?c("Retrieved state",Nt):s("State not initialized. Call initWorkspaceState() first.");E=e=>be(t=>({...t,...e})),Ue=()=>bm(Sm,v,v),Cm=(e,t)=>{let n={};for(let r of Object.values(e))$(r)&&t.length>0&&!t.every(o=>Md(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},K=e=>v()?.renderedChildrenIndex[e]??[],Cn=()=>Go?In(Go):s("Cannot reset state: no initial workspace found"),Ft=()=>Nt!==void 0});var qt,Rm,It,N,se=y(()=>{"use strict";te();S();T();Ce();qt=(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}`)},Rm=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},It=(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=It(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=It(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=It(o,"move");if(d)return d;if(Rm(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=It(r,"edit");if(o)return o;if(!$(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=It(r,"edit");if(o)return o;if(!$(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=It(r,"edit");if(o)return o;if(!$(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=It(r,"edit");if(o)return o;if(!$(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 bt from"chalk";import Bd from"string-width";import{decodeTime as Am}from"ulid";var wm,Tm,Mm,Lm,Pm,km,Dm,Fm,Om,_d,$d=y(()=>{"use strict";se();T();ft();rr();wm=(e,t)=>e+" ".repeat(Math.max(0,t-Bd(e))),Tm=(e,t)=>" ".repeat(Math.max(0,t-Bd(e)))+e,Mm=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`),Lm=(e,t)=>t?e<t?"up":e>t?"down":null:null,Pm=(e,t)=>{let n=N.getNode(e.payload.parent),r=n?bt.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let i=Lm(e.payload.rank,o.rank);if(i)return`Moved ${i} in ${r}`}return`Moved issue to ${r}`},km=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?bt.bgHex(Fe(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?bt.bgHex(Fe(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?bt.hex(Fe(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?bt.hex(Fe(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""}},Dm=e=>{let t=ds(Am(e));return bt.gray(Tm(t,8))},Fm=12,Om=e=>wm(`${e}`,Fm),_d=(e,t)=>{let n=Dm(e.id),r=Om(e.userName),o=bt.dim("\u203A"),i=e.action==="move.node"?Pm(e,t):[Mm(e.action),km(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${i}`}});var Um,Bm,_m,$m,Wd,jd,Hd,Wm,zd=y(()=>{"use strict";$d();te();S();Pt();se();gn();T();Rt();bo();Um=e=>ot(e,"description"),Bm=e=>ot(e,"assignees"),_m=e=>ot(e,"tags"),$m=e=>ot(e,"history"),Wd=({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(!Qe(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)},jd=({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(!Xt(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)},Hd=e=>{let t=Se(We/4n),n=Se(We/2n),r=Se(We*3n/4n),o=Se(We*7n/8n);if(a(t))return t;if(a(n))return n;if(a(r))return r;if(a(o))return o;let i=Wd({id:Um(e.id),name:Q.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(i))return i;let d=jd({id:Bm(e.id),name:Q.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(d))return d;let l=jd({id:_m(e.id),name:Q.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(a(l))return l;let u=Wd({id:$m(e.id),name:Q.HISTORY,parentNodeId:e.id,rank:o.value,value:Wm(e),readonly:!0,childRenderAxis:"vertical"});return a(u)?u:c("Ticket virtual nodes materialized",void 0)},Wm=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=>_d(r,n.get(r.action)??[])).join(`
59
- `)}});function Sn(e,t=!1){let n=Ym[e.action](e);if(a(n))return n;let r=Gm(e,t);return r||n}var D,Vd,jm,Hm,zm,Vm,Km,qm,Gm,Ym,Et,zt=y(()=>{"use strict";te();S();Pt();se();gn();T();zd();xn();D=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Vd=e=>{let t=N.getNode(e);if(!t||!$(t)||t.isDeleted)return null;let n=Hd(t);return a(n)?n:null},jm=e=>{for(let t of e){let n=Vd(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=Vd(r);if(o)return o}return null},Hm=(e,t)=>{let n=N.getNode(e);n&&N.updateNode({...n,log:[...n.log??[],t]})},zm=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},Vm=e=>{switch(e.action){case"delete.node":case"edit.description":return zm(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[]}},Km=e=>{be(t=>({...t,eventLog:[...t.eventLog,e]}))},qm=e=>{let t=e.userId,n=e.userName;if(!t?.length||!n?.length)return D("Invalid user ID format",e);let r=N.createContributor({id:t,name:n});return a(r)?D(r.message,e):null},Gm=(e,t)=>{let n=qm(e);if(n)return n;let r=[...new Set(Vm(e))];t||(r.forEach(i=>Hm(i,e)),Km(e));let o=jm(r);return o||null},Ym={"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):Wr(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):Wr(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):ui(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):wn(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):$(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(Q.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?D(d.message??`Unable to create field: ${n}`,e):Qe(d.value)?c("Added field",{action:e.action,result:d.value}):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(!$(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(!$(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}})}};Et=e=>e.map(t=>Sn(t))});function Me(e,t){let n=Sn(e);if(n.status!==Je.Success)return n;let r=Nr({event:e,rootDir:t});return a(r)?r:n}function Kt(e,t){return e.map(n=>Me(n,t))}var Ie,ht=y(()=>{"use strict";S();ne();zt();Te();Ie=async e=>{let t=await Ae();return a(t)?t:Me(e,t.value)}});var Kd,Ar,H,qd,Gd,Gt,Vt,Ce=y(()=>{"use strict";gi();ht();S();T();Rt();Kd=e=>Ar(H(e),{at:"end"}),Ar=(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=qd(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=qd(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)),qd=(e,t)=>e.findIndex(n=>n.id===t),Gd=(e,t,n={at:"end"})=>Ar(H(t).filter(r=>r.id!==e),n),Gt=(e,t,n,r,o)=>{let i=Gd(t,e,n);if(a(i))return i;if(!i.value.needsRebalance)return c("Resolved rank",i.value.rank);let d=jr(e,r);if(a(d))return d;let l=Me(d.value,o);if(a(l))return l;let u=Gd(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)},Vt=(e,t,n)=>{let r=Kd(e);if(a(r))return r;if(!r.value.needsRebalance)return c("Resolved rank",r.value.rank);let o=jr(e,t);if(a(o))return o;let i=Me(o.value,n);if(a(i))return i;let d=Kd(e);return a(d)?d:d.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",d.value.rank)}});var Xd,Jd,Xm,Dr,Qd,Yd,Jm,Zd,ec=y(()=>{"use strict";te();S();Ce();T();we();Xd=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Jd=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},Xm=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&&Qe(t)&&t.childRenderAxis==="vertical"},Dr=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=H(r.id);return M.navigate({contextNode:r,selectedIndex:Xd(t,o.length)}),!0},Qd=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Dr(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?(M.navigate({contextNode:o,selectedIndex:d}),!0):Qd(o.id)},Yd=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Qd(n))return!0;n=t[n]?.parentNodeId}return!1},Jm=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},Zd=e=>{let{nodes:t,rootNodeId:n}=v();if(Xm(e.contextNodeId)&&Dr(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(Jm(e.selectedNodeId)&&e.selectedNodeId&&Yd(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(Dr(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&Dr(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(Yd(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 M.navigate({contextNode:r,selectedIndex:Xd(e.selectedIndex,o.length)}),c("Restored navigation to root",null)}});var _,Xo=y(()=>{"use strict";S();_=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});var Jo,Qo,Zo,Qm,de,tc=y(()=>{"use strict";S();T();Jo=({status:e,msg:t})=>{Ft()&&E({syncStatus:{status:e,msg:t}})},Qo=(e="Syncing...")=>{Jo({status:"syncing",msg:e})},Zo=(e="Synced")=>{Jo({status:"synced",msg:e})},Qm=e=>{Jo({status:"failed",msg:e})},de=e=>(Qm(e),s(e))});import{decodeTime as Zm}from"ulid";var ti,ei,nc,rc,oc,ic=y(()=>{"use strict";S();ti=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)},ei=e=>{let[t,n]=e.id;return`${t}:${n??""}`},nc=e=>{try{return Zm(e.id[0])}catch{return 0}},rc=(e,t)=>{let n=new Map;for(let r of[...e,...t])n.set(ei(r),r);return[...n.values()].sort((r,o)=>{let i=nc(r)-nc(o);return i!==0?i:ei(r).localeCompare(ei(o))})},oc=e=>e.length===0?"":e.map(t=>JSON.stringify(t)).join(`
57
+ `)}`):(sm(),E({hasProjectDefinition:!0}),c("State booted successfully",null))}var Nn,Tr=y(()=>{"use strict";Te();G();S();gn();T();At();Kt();xn();Nn=om()});import am from"node:fs";import _a from"node:path";var dm,V,$a,Wa=y(()=>{"use strict";ka();On();Pt();Tt();$o();Te();dn();Tr();Kt();Me();G();S();wt();oe();ge();T();ne();dm=async e=>{let t=await O({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}`),$a=async()=>{W("");let e=vi(),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");let o=await dm(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 Bo({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=_a.join(jn(),e.projectId),I=await _o({repoRoot:n,stateBranchRoot:R,stateBranchName:m});if(a(I))return V(8,I.message);let k=_a.join(R,".epiq");am.mkdirSync(k,{recursive:!0});let A=Ba({userId:u,userName:l});if(a(A))return V(9,A.message);for(let Wr of A.value){let li=Sr({event:Wr,rootDir:R});if(a(li))return V(9,li.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 Pa(n);if(a(lt))return V(11,lt.message);let Je=xi({repoRoot:n,fileContents:e});if(a(Je))return V(12,Je.message);let oi=await q.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(oi))return V(13,oi.message);let ii=await q.commit({cwd:n,message:"[epiq:init-project]"});if(a(ii))return V(13,ii.message);let _r="Project initialized!",si=await O({cwd:n,args:["push","-u","origin","HEAD"]});a(si)&&(_r+=` Warn: [init:14] ${si.message}`);let ai=await En({repoRoot:n,stateBranchRoot:R});a(ai)&&(_r+=` Warn: [init:15] ${ai.message}`);let di=Nt(A.value).filter(a);if(di.length>0)return V(16,di.map(Wr=>Wr.message).join(`
58
+ `));let $r=De();if(a($r))return V(16,$r.message);let{rootNodeId:Rc,nodes:Ac}=$r.value,ci=Ac[Rc];return ci?(M.navigate({contextNode:ci,selectedIndex:0}),E({hasProjectDefinition:!0,mode:p.DEFAULT}),c(_r,null)):V(16,"Unable to resolve initialized root node")}});import{ulid as cm}from"ulid";function jo(e){let t=Ha();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=za({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Va(u.value)}function Ho(e){let t=Ha();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=za({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return a(d)?d:Va(d.value)}var ja,dt,bn,Ha,Wo,za,Va,zo=y(()=>{"use strict";Kt();Me();S();Ce();T();ja=null,dt=()=>structuredClone(ja),bn=e=>{ja=e},Ha=()=>{let{contextNode:e,selectedIndex:t}=v(),r=H(e.id)[t];return r?c("Resolved selected child",r):s("Target node not found")},Wo=({id:e,parentId:t,position:n={at:"end"}})=>{let r=H(t).filter(o=>o.id!==e);return Mr(r,n)},za=({id:e,parentId:t,position:n={at:"end"}})=>{let r=J();if(a(r))return s("Unable to resolve user ID");let o=Wo({parentId:t,id:e,position:n});return a(o)?o:c("Created pending move state",{id:cm(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Va=e=>{bn(e);let t=Sn(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as lm}from"ulid";var Ka,Lr,qa,Ga=y(()=>{"use strict";Te();zo();Et();Me();G();S();Ce();oe();T();ne();Ka=()=>{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"):(M.navigate({contextNode:r,selectedIndex:o}),c("Synchronized navigation to moved node",null))},Lr=(e,t="Moved preview")=>{if(a(e))return e;let n=Ka();return a(n)?n:(E({mode:p.MOVE}),c(t,null))},qa=async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{modifier:t}=ee().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=Wo({parentId:o.parentNodeId,id:o.id,position:m});return a(g)?g:(bn({id:lm(),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(Ho(1));if(t==="previous")return Lr(Ho(-1));if(t==="to-next")return Lr(jo(1));if(t==="to-previous")return Lr(jo(-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=Ka();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 um,ulid as mm}from"ulid";var pm,Pr,Vo=y(()=>{"use strict";S();pm=um(),Pr=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=pm();return c("Created issue events",[{id:mm(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}}])}});import{ulid as kr}from"ulid";var Ya,Xa=y(()=>{"use strict";Te();Vo();Et();Me();ln();S();se();Ce();T();ne();Ya=async(e,t)=>{let n=J();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?(M.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=qt(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=Fe(i,"BOARD");if(a(m))return s("Unable to add swimlane in this context");let g=qt(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=K(d.id)[l],g=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let j=Fe(i,"SWIMLANE");return a(j)?null:j.value})();if(!g)return s("Unable to add issue in this context");let x=qt(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?(M.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 Ja,Qa=y(()=>{"use strict";Pt();Te();ir();vn();Kt();G();ln();S();oe();T();rr();Ja=async()=>{let e=Fe(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}=ee().commandMeta;if(r==="now"){let I=Ht(n.value);if(a(I))return s(I.message);let k=Cn();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=ha(n.value,o);if(a(l))return s(l.message);let{appliedEvents:u,unappliedEvents:m}=l.value,g=Cn();if(a(g))return g;let b=Nt(u).filter(a);if(b.length>0)return Cn(),E(i),s(b.map(I=>I.message).join(", "));let R=v().nodes[d];return R?(M.navigate({contextNode:R,selectedIndex:0}),E({mode:p.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:m}),c("Peeking",!0)):(Cn(),E(i),s("Board did not exist at peek date"))}});import gm from"zod";var Za,ed=y(()=>{"use strict";jt();G();S();oe();ge();T();Za=()=>{let e=ee().commandMeta.inputString,t=gm.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 td,nd=y(()=>{"use strict";dn();jt();G();S();oe();ge();T();td=()=>{let e=ee().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return s("Invalid response");let t=ns(e),n=Ye({autoSync:t});return a(n)?n:(ke({autoSync:t}),E({mode:p.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var rd,od=y(()=>{"use strict";jt();G();S();oe();ge();T();rd=()=>{let e=ee().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 id,sd=y(()=>{"use strict";Xn();G();S();oe();T();id=async()=>{W(""),E({mode:p.DEFAULT});let e=De();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 Ke();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 ad,dd,cd,ld=y(()=>{"use strict";aa();Te();jt();Et();Me();Ra();xn();G();te();S();se();Ce();oe();ge();T();Rr();ne();gt();yo();cn();La();Wa();Ga();Xa();Qa();ed();nd();od();sd();ad=e=>Object.values(v().tags).find(t=>t.name===e),dd=e=>Object.values(v().contributors).find(t=>t.name===e),cd=[{systemOnly:!0,intent:P.Move,description:"Internal move-state command",mode:p.COMMAND_LINE,action:qa},{intent:P.Delete,description:"Delete the currently selected node",mode:p.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=K(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:P.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:p.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ee().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(d=>ae(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:P.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:P.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:p.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=K(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!$(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=Yt(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:P.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:p.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=K(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):Gt(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(!$(i))return s("Target node is not issue");let l=Ca(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=Yt(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:P.Init,description:"Initialize Epiq in the current git repository",mode:p.COMMAND_LINE,action:$a},{intent:P.NewItem,description:"Create a new board, swimlane, or issue",mode:p.COMMAND_LINE,action:Ya,onSuccess:()=>E({mode:p.DEFAULT})},{intent:P.Rename,description:"itle] Rename the currently selected node",mode:p.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=K(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=Os();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:P.UntagTicket,description:"Remove a tag from the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=ad(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid untag target");let d=Gt(i.id,"TICKET");if(a(d))return s("Unable to untag issue in this context");let l=d.value;return $(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:P.TagTicket,description:"Add or create a tag on the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().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=Gt(o.id,"TICKET");if(a(i))return s("Unable to tag issue in this context");let d=i.value;if(!$(d))return s("Target node is not issue");let l=ad(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:P.AssignUserToTicket,description:"Assign a user to the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,contextNode:i}=v(),d=K(i.id)[o];if(!d)return s("Invalid assign target");let l=Gt(d.id,"TICKET");if(a(l))return s("Unable to assign issue in this context");let u=l.value;if(!$(u))return s("Target node is not issue");let m=dd(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:P.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=J();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=dd(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid unassign target");let d=Gt(i.id,"TICKET");if(a(d))return s("Unable to unassign in this context");let l=d.value;return $(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:P.Sync,description:"Pull, commit, and push Epiq state",mode:p.COMMAND_LINE,action:id},{intent:P.Peek,description:"View board state at another point in time",mode:p.COMMAND_LINE,action:Ja},{intent:P.Export,description:"Export the current board layout to markdown",mode:p.COMMAND_LINE,action:async()=>{let e=await sa();return a(e)?e:(E({mode:p.DEFAULT}),c("Export successful",!0))}},{intent:P.Exit,description:"Exit the application",mode:p.COMMAND_LINE,action:async()=>(M.exit(),c("Exit successful",!0))},{intent:P.Edit,description:"Edit title or description",mode:p.COMMAND_LINE,action:async(e,t)=>{if(t.modifier===rt.DESCRIPTION)return Ma();if(t.modifier===rt.TITLE){let n=J();if(a(n))return s("Unable to resolve user ID");let{contextNode:r,selectedIndex:o}=v(),i=K(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:P.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 td();case X.LOG_LEVEL:return rd();case X.SYNC_DEBOUNCE_MS:return Za();default:return s("Unknown config command")}}}]});var fm,$e,Ko=y(()=>{"use strict";Yn();dr();yo();ld();S();oe();ge();T();fm=new Set(["peek","filter","view-help"]),$e=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ee();if(!t)return s("No command to confirm");if(!e&&n===yt.Invalid)return s("Invalid command");let i=Us(t);Ps();let{readOnly:d}=v();if(d&&!fm.has(i))return pn({status:Qe.Fail,message:"Command not available in readonly state",value:null});let l=cd.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):(ks({addToHistory:!e}),l.onSuccess?.(),Y().autoSync&&Zi(),u)}});var Dr,Fr,ud,md=y(()=>{"use strict";S();G();T();mt();Ko();zo();oe();Dr=[{intent:C.Exit,mode:p.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:p.COMMAND_LINE}),W("move cancel"),$e({isForceExecutedBySystem:!0}))},{intent:C.InitMove,mode:p.DEFAULT,description:"[m] move (init/confirm)",action:()=>(E({mode:p.COMMAND_LINE}),W("move start"),$e({isForceExecutedBySystem:!0}))},{intent:C.ConfirmMove,mode:p.MOVE,action:()=>(E({mode:p.COMMAND_LINE}),W("move confirm"),$e({isForceExecutedBySystem:!0}))}],Fr=[{intent:C.MovePreviousItem,mode:p.MOVE,action:()=>dt()?(E({mode:p.COMMAND_LINE}),W("move previous"),$e({isForceExecutedBySystem:!0})):s("No pending move")},{intent:C.MoveNextItem,mode:p.MOVE,action:()=>dt()?(E({mode:p.COMMAND_LINE}),W("move next"),$e({isForceExecutedBySystem:!0})):s("No pending move")}],ud=[{intent:C.MoveToNextContainer,mode:p.MOVE,action:()=>dt()?(E({mode:p.COMMAND_LINE}),W("move to-next"),$e({isForceExecutedBySystem:!0})):s("No pending move")},{intent:C.MoveToPreviousContainer,mode:p.MOVE,action:()=>dt()?(E({mode:p.COMMAND_LINE}),W("move to-previous"),$e({isForceExecutedBySystem:!0})):s("No pending move")}]});var pd,gd=y(()=>{"use strict";te();md();pd={[w.WORKSPACE]:[...Dr,...Fr],[w.BOARD]:[...Dr,...Fr],[w.SWIMLANE]:[...Dr,...Fr,...ud],[w.TICKET]:[],[w.FIELD]:[],[w.FIELD_LIST]:[],[w.TEXT]:[]}});var fd,vd,yd=y(()=>{"use strict";G();S();oe();T();Rr();mt();Te();fd=()=>{W("");let{pendingNavTarget:e}=zt();E({mode:p.DEFAULT}),e&&M.navigate(e),at({pendingNavTarget:void 0})},vd=[{intent:C.ExitCommandLine,mode:p.HELP,action:()=>(fd(),c("Exiting help",null))},{intent:C.Exit,mode:p.HELP,action:()=>(fd(),c("Closed help",null))},{intent:C.NavPreviousItem,mode:p.HELP,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:C.NavNextItem,mode:p.HELP,action:()=>(M.navigateToNextItem(),c("Navigating to next help item",null))},{intent:C.NavToPreviousContainer,mode:p.HELP,action:()=>(M.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:C.NavToNextContainer,mode:p.HELP,action:()=>(M.navigateToNextContainer(),c("Navigating to next help container",null))}]});var vm,xd,hd,Ed=y(()=>{"use strict";G();te();S();oe();T();Rr();mt();Te();vm=e=>{E({mode:p.COMMAND_LINE});let{pendingNavTarget:t}=zt();t&&M.navigate(t),at({pendingNavTarget:void 0}),W(`${e} `)},xd=()=>{W("");let{pendingNavTarget:e}=zt();e&&M.navigate(e),at({pendingNavTarget:void 0}),E({mode:p.DEFAULT})},hd=[{intent:C.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:C.Confirm,mode:p.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!ui(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?(vm(t),c("Selected command",t)):c("No command selected",null)}},{intent:C.ExitCommandLine,mode:p.PALETTE,action:()=>(xd(),c("Exiting palette",null))},{intent:C.Exit,mode:p.PALETTE,action:()=>(xd(),c("Closed command palette",null))},{intent:C.NavPreviousItem,mode:p.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:C.NavNextItem,mode:p.PALETTE,action:()=>(M.navigateToNextItem(),c("Navigating to next item",null))},{intent:C.NavToPreviousContainer,mode:p.PALETTE,action:()=>(M.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:C.NavToNextContainer,mode:p.PALETTE,action:()=>(M.navigateToNextContainer(),c("Navigating to next container",null))}]});var Nd,Id=y(()=>{"use strict";gt();G();S();kt();Ce();oe();T();mt();yd();Ed();Te();Nd=[...vd,...hd,{intent:C.AddItem,mode:p.DEFAULT,description:"[n] new...",action:()=>(E({mode:p.COMMAND_LINE}),W(`${f.NEW} `),c("Adding new item",null))},{intent:C.Delete,mode:p.DEFAULT,description:"[d] delete",action:()=>(E({mode:p.COMMAND_LINE}),W(`${f.DELETE} `),c("Deleting item",null))},{intent:C.InitCommandLine,mode:p.DEFAULT,description:"[:] focus command line",action:()=>(E({mode:p.COMMAND_LINE}),W(""),c("Entering command line mode",null))},{intent:C.Confirm,mode:p.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!H(e?.id??"")?.length){if(e?.title===Q.DESCRIPTION)return E({mode:p.COMMAND_LINE}),W(`${f.EDIT} description `),c("Propose command",!0);if(e?.title===Q.ASSIGNEES)return E({mode:p.COMMAND_LINE}),W(`${f.ASSIGN} `),c("Propose command",!0);if(e?.title===Q.TAGS)return E({mode:p.COMMAND_LINE}),W(`${f.TAG} `),c("Propose command",!0);if(t.title===Q.DESCRIPTION&&e?.context==="TEXT")return E({mode:p.COMMAND_LINE}),W(`${f.EDIT} description `),c("Propose command",!0)}return M.enterChildNode(),c("Entering context",null)}},{intent:C.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:C.EditDescription,mode:p.DEFAULT,description:"[e] edit description",action:()=>(E({mode:p.COMMAND_LINE}),W(`${f.EDIT} description `),c("Exiting context",null))},{intent:C.Exit,mode:p.DEFAULT,description:"[q] exit context",action:()=>(M.enterParentNode(),c("Exiting context",null))},{intent:C.NavPreviousItem,mode:p.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:C.NavNextItem,mode:p.DEFAULT,action:()=>(M.navigateToNextItem(),c("Navigating to next item",null))},{intent:C.NavToPreviousContainer,mode:p.DEFAULT,action:()=>(M.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:C.NavToNextContainer,mode:p.DEFAULT,action:()=>(M.navigateToNextContainer(),c("Navigating to next container",null))}]});var ym,xm,bd,Sd=y(()=>{"use strict";oe();ym=500,xm=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),bd=e=>{let t=xm(e);t&&ur(n=>(n+t).slice(0,ym))}});var hm,Em,Cd,Rd=y(()=>{"use strict";Sd();G();S();oe();T();mt();Ko();hm=[p.COMMAND_LINE,p.PALETTE],Em=e=>[{intent:C.MoveCursorLeft,mode:e,action:()=>(fo(-1),c("Moving cursor left",null))},{intent:C.MoveCursorRight,mode:e,action:()=>(fo(1),c("Moving cursor right",null))},{intent:C.MoveCursorLeftOfWord,mode:e,action:()=>(vo("left"),c("Moving cursor left of word",null))},{intent:C.MoveCursorRightOfWord,mode:e,action:()=>(vo("right"),c("Moving cursor right of word",null))},{intent:C.AutoCompleteCommand,mode:e,action:()=>(ur((t,{remainder:n})=>n?t+n:t),c("Auto-completing command",null))},{intent:C.CaptureInput,mode:e,action:(t,{sequence:n})=>(bd(n??""),c("Capturing input",null))},{intent:C.EraseInput,mode:e,action:()=>(Ms(),c("Erasing input",null))},{intent:C.EraseInputWord,mode:e,action:()=>(Ls(),c("Erasing input word",null))}],Cd=[{intent:C.Confirm,mode:p.COMMAND_LINE,action:()=>($e(),c("Executing command",null))},{intent:C.ViewHelp,mode:p.DEFAULT,action:()=>(E({mode:p.HELP}),c("Viewing help",null))},...hm.flatMap(Em),{intent:C.ExitCommandLine,mode:p.COMMAND_LINE,action:()=>(E({mode:p.DEFAULT}),c("Exiting command line",null))},{intent:C.GetLastCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(Ds(),c("Getting last command from history",null))},{intent:C.GetNextCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(Fs(),c("Getting next command from history",null))}]});import Td from"chalk";var Or,Ad,wd,qo,Md=y(()=>{"use strict";G();te();xe();Or=Td.dim.hex(L.secondary2)(": for command line"),Ad="q to exit",wd=`${Td.hex(L.accent)("m")} to confirm`,qo={[w.WORKSPACE]:[Or],[w.BOARD]:[Or],[w.BOARD+p.COMMAND_LINE]:[Or],[w.SWIMLANE]:[Or],[w.TICKET+p.HELP]:[Ad],[w.SWIMLANE+p.HELP]:[Ad],[w.TICKET]:[],[w.FIELD]:[],[w.SWIMLANE+p.MOVE]:[wd],[w.TICKET+p.MOVE]:[wd]}});var Rn,Nm,Im,Ld,Pd=y(()=>{"use strict";T();Rn=e=>e.trim().toLocaleLowerCase(),Nm=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Im=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},Ld=(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 Nm(e).map(Rn).some(o=>o.includes(n));case"assignee":return Im(e).map(Rn).some(o=>o.includes(n));default:return!0}}});function kd(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 Dd=y(()=>{"use strict";S()});var Fd,Od=y(()=>{"use strict";Fd=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 bm}from"react";function Bd(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=kd(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:g}=l,x=qo[g+n]??qo[g]??[],b=[...Nd,...pd[g]??[],...Cd],R=Fd(b),I=Cm(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){Go=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=Bd(r);return a(o)?o:(bt=o.value,Ud(),c("State initialized",null))}function be(e){let t=v(),n=e(t),r=Bd(n);return a(r)?s(r.message??"Unable to update state"):(bt=r.value,Ud(),c("State updated",null))}var bt,Go,Yo,Ud,Sm,v,De,E,Be,Cm,K,Cn,Ot,T=y(()=>{"use strict";gd();Id();Rd();Md();wt();G();te();S();ne();Pd();Dd();Od();Yo=new Set,Ud=()=>{for(let e of Yo)e()},Sm=e=>(Yo.add(e),()=>Yo.delete(e));v=()=>{if(!bt)throw new Error("State not initialized. Call initWorkspaceState() first.");return bt},De=()=>bt?c("Retrieved state",bt):s("State not initialized. Call initWorkspaceState() first.");E=e=>be(t=>({...t,...e})),Be=()=>bm(Sm,v,v),Cm=(e,t)=>{let n={};for(let r of Object.values(e))$(r)&&t.length>0&&!t.every(o=>Ld(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},K=e=>v()?.renderedChildrenIndex[e]??[],Cn=()=>Go?In(Go):s("Cannot reset state: no initial workspace found"),Ot=()=>bt!==void 0});var Gt,Rm,St,N,se=y(()=>{"use strict";te();S();T();Ce();Gt=(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}`)},Rm=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},St=(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=St(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=St(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=St(o,"move");if(d)return d;if(Rm(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=St(r,"edit");if(o)return o;if(!$(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=St(r,"edit");if(o)return o;if(!$(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=St(r,"edit");if(o)return o;if(!$(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=St(r,"edit");if(o)return o;if(!$(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 Ct from"chalk";import _d from"string-width";import{decodeTime as Am}from"ulid";var wm,Tm,Mm,Lm,Pm,km,Dm,Fm,Om,$d,Wd=y(()=>{"use strict";se();T();vt();ir();wm=(e,t)=>e+" ".repeat(Math.max(0,t-_d(e))),Tm=(e,t)=>" ".repeat(Math.max(0,t-_d(e)))+e,Mm=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`),Lm=(e,t)=>t?e<t?"up":e>t?"down":null:null,Pm=(e,t)=>{let n=N.getNode(e.payload.parent),r=n?Ct.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let i=Lm(e.payload.rank,o.rank);if(i)return`Moved ${i} in ${r}`}return`Moved issue to ${r}`},km=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?Ct.bgHex(Oe(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?Ct.bgHex(Oe(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Ct.hex(Oe(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Ct.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""}},Dm=e=>{let t=cs(Am(e));return Ct.gray(Tm(t,8))},Fm=12,Om=e=>wm(`${e}`,Fm),$d=(e,t)=>{let n=Dm(e.id),r=Om(e.userName),o=Ct.dim("\u203A"),i=e.action==="move.node"?Pm(e,t):[Mm(e.action),km(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${i}`}});var Um,Bm,_m,$m,jd,Hd,zd,Wm,Vd=y(()=>{"use strict";Wd();te();S();kt();se();gn();T();At();bo();Um=e=>ot(e,"description"),Bm=e=>ot(e,"assignees"),_m=e=>ot(e,"tags"),$m=e=>ot(e,"history"),jd=({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)},Hd=({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(!Jt(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)},zd=e=>{let t=Se(He/4n),n=Se(He/2n),r=Se(He*3n/4n),o=Se(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=jd({id:Um(e.id),name:Q.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(i))return i;let d=Hd({id:Bm(e.id),name:Q.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(d))return d;let l=Hd({id:_m(e.id),name:Q.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(a(l))return l;let u=jd({id:$m(e.id),name:Q.HISTORY,parentNodeId:e.id,rank:o.value,value:Wm(e),readonly:!0,childRenderAxis:"vertical"});return a(u)?u:c("Ticket virtual nodes materialized",void 0)},Wm=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=>$d(r,n.get(r.action)??[])).join(`
59
+ `)}});function Sn(e,t=!1){let n=Ym[e.action](e);if(a(n))return n;let r=Gm(e,t);return r||n}var F,Kd,jm,Hm,zm,Vm,Km,qm,Gm,Ym,Nt,Kt=y(()=>{"use strict";te();S();kt();se();gn();T();Vd();xn();F=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Kd=e=>{let t=N.getNode(e);if(!t||!$(t)||t.isDeleted)return null;let n=zd(t);return a(n)?n:null},jm=e=>{for(let t of e){let n=Kd(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=Kd(r);if(o)return o}return null},Hm=(e,t)=>{let n=N.getNode(e);n&&N.updateNode({...n,log:[...n.log??[],t]})},zm=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},Vm=e=>{switch(e.action){case"delete.node":case"edit.description":return zm(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[]}},Km=e=>{be(t=>({...t,eventLog:[...t.eventLog,e]}))},qm=e=>{let t=e.userId,n=e.userName;if(!t?.length||!n?.length)return F("Invalid user ID format",e);let r=N.createContributor({id:t,name:n});return a(r)?F(r.message,e):null},Gm=(e,t)=>{let n=qm(e);if(n)return n;let r=[...new Set(Vm(e))];t||(r.forEach(i=>Hm(i,e)),Km(e));let o=jm(r);return o||null},Ym={"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 F(i.message,e);let d=N.createNode(o);return a(d)?F(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)?F(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)?F(i.message??"Unable to create board",e):mi(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)?F(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)?F(i.message??"Unable to create issue",e):$(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(Q.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?F(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 F(`Unable to locate node with id ${t}`,e);let o=N.renameNode(t,n);return a(o)?F(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)?F(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)?F(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)?F(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)?F(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)?F(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)?F(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)?F(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)?F(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)?F(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 F("Unable to locate issue",e);if(!$(o))return F("Can only close issues",e);let i=N.getNode(ue);if(!i)return F("Unable to locate target swimlane",e);if(n!==i.id)return F("Close target must be closed swimlane",e);let d=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(d)?F(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 F("Unable to locate issue",e);if(!$(o))return F("Can only reopen issues",e);let i=N.getNode(ue);if(!i)return F("Unable to locate closed swimlane",e);if(n===i.id)return F("Cannot reopen issue into closed swimlane",e);if(!N.getNode(n))return F("Reopen parent no longer exists",e);let l=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(l)?F(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)?F(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 F(`Unable to locate node ${r}`,e);if(i.parentNodeId!==t)return F(`Node ${r} is not child of ${t}`,e);let d=N.updateNode({...i,rank:o});if(a(d))return F(d.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})}};Nt=e=>e.map(t=>Sn(t))});function Le(e,t){let n=Sn(e);if(n.status!==Qe.Success)return n;let r=Sr({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";S();ne();Kt();Me();Ie=async e=>{let t=await Ae();return a(t)?t:Le(e,t.value)}});var qd,Mr,H,Gd,Yd,Yt,qt,Ce=y(()=>{"use strict";fi();Et();S();T();At();qd=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=Gd(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=Gd(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)),Gd=(e,t)=>e.findIndex(n=>n.id===t),Yd=(e,t,n={at:"end"})=>Mr(H(t).filter(r=>r.id!==e),n),Yt=(e,t,n,r,o)=>{let i=Yd(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=Yd(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)},qt=(e,t,n)=>{let r=qd(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=qd(e);return a(d)?d:d.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",d.value.rank)}});var Jd,Qd,Xm,Ur,Zd,Xd,Jm,ec,tc=y(()=>{"use strict";te();S();Ce();T();Te();Jd=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Qd=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},Xm=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 M.navigate({contextNode:r,selectedIndex:Jd(t,o.length)}),!0},Zd=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?(M.navigate({contextNode:o,selectedIndex:d}),!0):Zd(o.id)},Xd=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Zd(n))return!0;n=t[n]?.parentNodeId}return!1},Jm=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},ec=e=>{let{nodes:t,rootNodeId:n}=v();if(Xm(e.contextNodeId)&&Ur(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(Jm(e.selectedNodeId)&&e.selectedNodeId&&Xd(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(Xd(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 M.navigate({contextNode:r,selectedIndex:Jd(e.selectedIndex,o.length)}),c("Restored navigation to root",null)}});var _,Xo=y(()=>{"use strict";S();_=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});var Jo,Qo,Zo,Qm,de,nc=y(()=>{"use strict";S();T();Jo=({status:e,msg:t})=>{Ot()&&E({syncStatus:{status:e,msg:t}})},Qo=(e="Syncing...")=>{Jo({status:"syncing",msg:e})},Zo=(e="Synced")=>{Jo({status:"synced",msg:e})},Qm=e=>{Jo({status:"failed",msg:e})},de=e=>(Qm(e),s(e))});import{decodeTime as Zm}from"ulid";var ti,ei,rc,oc,ic,sc=y(()=>{"use strict";S();ti=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)},ei=e=>{let[t,n]=e.id;return`${t}:${n??""}`},rc=e=>{try{return Zm(e.id[0])}catch{return 0}},oc=(e,t)=>{let n=new Map;for(let r of[...e,...t])n.set(ei(r),r);return[...n.values()].sort((r,o)=>{let i=rc(r)-rc(o);return i!==0?i:ei(r).localeCompare(ei(o))})},ic=e=>e.length===0?"":e.map(t=>JSON.stringify(t)).join(`
61
61
  `)+`
62
- `});import $e from"node:fs";import An from"node:path";var sc,ep,tp,np,rp,ac,dc,op,Fr,ni=y(()=>{"use strict";S();tc();Xo();Fn();Lt();wt();$o();ic();sc=e=>$e.existsSync(e)?$e.readFileSync(e,"utf8"):null,ep=(e,t)=>sc(e)===t?!1:($e.mkdirSync(An.dirname(e),{recursive:!0}),$e.writeFileSync(e,t,"utf8"),!0),tp=e=>{let t=An.join(e,".epiq","events"),n=new Map;if(!$e.existsSync(t))return c("No event files to snapshot",n);for(let r of $e.readdirSync(t)){if(!r.endsWith(".jsonl"))continue;let o=An.join(t,r);$e.statSync(o).isFile()&&n.set(r,$e.readFileSync(o,"utf8"))}return c("Snapshotted event files",n)},np=async e=>{if((await Re({cwd:e,args:["checkout","--",nn("")]})).exitCode!==0){let n=An.join(e,".epiq","events");$e.existsSync(n)&&$e.rmSync(n,{recursive:!0,force:!0})}return c("Restored event files to HEAD",null)},rp=({stateBranchRoot:e,snapshots:t})=>{let n=!1;for(let[r,o]of t){let i=An.join(e,nn(r)),d=sc(i)??"",l=ti(d);if(a(l))return s(l.message);let u=ti(o);if(a(u))return s(u.message);let m=rc(l.value,u.value);n=ep(i,oc(m))||n}return c("Merged event snapshots",n)},ac=async(e=process.cwd())=>{logger.debug("[sync] syncEpiqFromRemote:start",e),Qo("Syncing from remote");let t=_("ensureSyncReady",await dc({cwd:e,ensureUpstream:!1}));if(a(t))return de(t.message);let{repoRoot:n,stateBranchRoot:r}=t.value,o=_("getStateBranch",lt(n));if(a(o))return de(o.message);let i=o.value,d=_("snapshotEventFiles",tp(r));if(a(d))return de(d.message);let l=_("restoreEventFilesToHead",await np(r));if(a(l))return de(l.message);let u=_("resetBranchHardToRemote",await Ti({cwd:r,branch:i}));if(a(u))return de(u.message);let m=_("mergeEventSnapshots",rp({stateBranchRoot:r,snapshots:d.value}));return a(m)?de(m.message):(Zo(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}))},dc=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=_("getRepoRootDir",await tt(e));if(a(n))return s(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=_("getStateBranchRoot",Mt({repoRoot:r}));if(a(o))return s(o.message);let i=o.value;logger.debug("[sync] state branch root",i);let d=_("ensureInitialCommit",await Da(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 Oa({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 Un(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",Oi(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}))},op=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 Sr({stateBranchRoot:t,eventFileName:n}));if(a(r))return s(r.message);let o=_("hasStagedChanges(after stage)",await Mi(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 Fa({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}))},Fr=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");Qo();let n=_("ensureSyncReady",await dc({cwd:e,ensureUpstream:!0}));if(a(n))return de(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,d=_("isDetachedHead(stateBranchRoot)",await Li(o));if(a(d))return de(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return de("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,g=!1,x=_("getStateBranch",lt(r));if(a(x))return de(x.message);let b=x.value;logger.debug("[sync] resolved state branch",{stateBranch:b,stateBranchRoot:o});let I=_("commitOwnEventFileToStateBranch",await op({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(a(I))return de(I.message);l=I.value.createdCommit,u=I.value.commitSha;let R=_("pullBranchRebaseIfPresent",await Xr({cwd:o,branch:b}));if(a(R))return de(R.message);if(m=R.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)&&Ai(k.message)){let A=_("pullBranchRebaseIfPresent(retry)",await Xr({cwd:o,branch:b}));if(a(A))return de(A.message);m=m||A.value,k=_("pushStateBranch(retry)",await En({stateBranchRoot:o,repoRoot:r}))}if(a(k))return de(k.message);g=k.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let k=_("git rev-parse HEAD",await O({args:["rev-parse","HEAD"],cwd:o}));if(a(k))return de(k.message);u=k.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Zo(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 nt,cc,Gn=y(()=>{"use strict";ec();Rr();vn();Te();G();S();T();Xo();ni();nt=async()=>{let e=cc();if(e)return e;logger.debug("[sync] syncAndReloadState:start");let t=_("resolveActorId",J());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=xt(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n});let r=_("syncEpiqWithRemote",await Fr({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",Wt(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=cc();if(d)return d;let l=Jd();if(!v().selectedNode?.isVirtual&&!v().contextNode?.isVirtual){let m=_("bootStateFromEventLog",Cr(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",Zd(l));return a(u)?u:(E({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done"),c("Synced",!0))},cc=()=>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 lc}from"ulid";var uc,St,Or,Ur,ip,sp,mc,pc,gc,fc,vc,yc,xc,hc,Ec=y(()=>{"use strict";Gn();ni();$t();Vo();Rr();vn();ht();Te();xn();te();S();se();Ce();T();ne();kt();uc=e=>{let t=et(e??process.cwd());return a(t)?s(t.message):c("Resolved Epiq repo root",t.value)},St=async e=>{let t=uc(e);if(a(t))return t;let n=await ac(t.value);if(a(n))return s(n.message);let{stateBranchRoot:r}=n.value,o=Wt(r);if(a(o))return s(o.message);let i=Cr(o.value);return a(i)?s(i.message):c("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:r})},Or=()=>{let e=ya();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")},Ur=()=>{let e=ke();return a(e)?s(e.message):e},ip=e=>(e.props.tags??[]).map(t=>N.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),sp=e=>(e.props.assignees??[]).map(t=>N.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),mc=async(e={})=>{let t=await St(e.repoRoot);if(a(t))return t;let n=Ur();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)},pc=async(e={})=>{let t=await St(e.repoRoot);if(a(t))return t;let n=Ur();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)},gc=async e=>{let t=await St(e.repoRoot);if(a(t))return t;let n=Ur();if(a(n))return n;let r=Object.values(n.value.nodes).filter($).filter(o=>e.includeClosed||o.parentNodeId!==ue).map(o=>({id:o.id,title:Vn(o.title),description:o.props.description??"",parentId:o.parentNodeId,isClosed:o.parentNodeId===ue,readonly:!!o.readonly,tags:ip(o),assignees:sp(o)}));return c("Listed issues",r)},fc=async e=>{let t=await St(e.repoRoot);if(a(t))return t;let n=Or();if(a(n))return n;let r=Vt(e.parentId,n.value,t.value.stateBranchRoot);if(a(r))return r;let o=Tr({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(a(o))return o;let i=o.value,l=Kt(i,t.value.stateBranchRoot).find(a);if(l)return s(l.message);let u=await nt();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")},vc=async e=>{let t=await St(e.repoRoot);if(a(t))return t;let n=Or();if(a(n))return n;let r=Gt(ue,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(r))return r;let o={id:lc(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ue,rank:r.value}},d=Kt([o],t.value.stateBranchRoot).find(a);if(d)return s(d.message);let l=await nt();return a(l)?l:c("Closed issue",{id:e.issueId})},yc=async e=>{let t=await St(e.repoRoot);if(a(t))return t;let n=Or();if(a(n))return n;let r=Gt(e.parentId,e.issueId,e.position??{at:"end"},n.value,t.value.stateBranchRoot);if(a(r))return r;let o={id:lc(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:r.value}},d=Kt([o],t.value.stateBranchRoot).find(a);if(d)return s(d.message);let l=await nt();return a(l)?l:c("Moved issue",{id:e.issueId,parentId:e.parentId})},xc=async(e={})=>{let t=uc(e.repoRoot);if(a(t))return s("Sync failed");let n=Or();if(a(n))return n;let r=await Fr({cwd:t.value,ownEventFileName:xt(n.value)});return a(r)?r:c("Synced",r.value)},hc=async(e={})=>{let t=await St(e.repoRoot);if(a(t))return t;let n=Ur();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})}});var bc={};wc(bc,{createMcpServer:()=>Nc,resultJson:()=>Ye,startMcpServer:()=>Ic});import{McpServer as ap}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as dp}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as F}from"zod";var Ye,Nc,Ic,Sc=y(async()=>{"use strict";S();Ec();Ye=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Nc=()=>{let e=new ap({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 hc(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 gc(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>Ye(await mc(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 pc(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 fc(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 vc(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 yc(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 xc(t))),e},Ic=async()=>{let e=Nc(),t=new dp;await e.connect(t)};await Ic()});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;await Sc().then(()=>bc);
62
+ `});import We from"node:fs";import An from"node:path";var ac,ep,tp,np,rp,dc,cc,op,Br,ni=y(()=>{"use strict";S();nc();Xo();Un();Pt();Tt();$o();sc();ac=e=>We.existsSync(e)?We.readFileSync(e,"utf8"):null,ep=(e,t)=>ac(e)===t?!1:(We.mkdirSync(An.dirname(e),{recursive:!0}),We.writeFileSync(e,t,"utf8"),!0),tp=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)},np=async e=>{if((await Re({cwd:e,args:["checkout","--",rn("")]})).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)},rp=({stateBranchRoot:e,snapshots:t})=>{let n=!1;for(let[r,o]of t){let i=An.join(e,rn(r)),d=ac(i)??"",l=ti(d);if(a(l))return s(l.message);let u=ti(o);if(a(u))return s(u.message);let m=oc(l.value,u.value);n=ep(i,ic(m))||n}return c("Merged event snapshots",n)},dc=async(e=process.cwd())=>{logger.debug("[sync] syncEpiqFromRemote:start",e),Qo("Syncing from remote");let t=_("ensureSyncReady",await cc({cwd:e,ensureUpstream:!1}));if(a(t))return de(t.message);let{repoRoot:n,stateBranchRoot:r}=t.value,o=_("getStateBranch",ut(n));if(a(o))return de(o.message);let i=o.value,d=_("snapshotEventFiles",tp(r));if(a(d))return de(d.message);let l=_("restoreEventFilesToHead",await np(r));if(a(l))return de(l.message);let u=_("resetBranchHardToRemote",await Mi({cwd:r,branch:i}));if(a(u))return de(u.message);let m=_("mergeEventSnapshots",rp({stateBranchRoot:r,snapshots:d.value}));return a(m)?de(m.message):(Zo(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}))},cc=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 Fa(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 Ua({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",Ui(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}))},op=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 Li(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 Oa({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");Qo();let n=_("ensureSyncReady",await cc({cwd:e,ensureUpstream:!0}));if(a(n))return de(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,d=_("isDetachedHead(stateBranchRoot)",await Pi(o));if(a(d))return de(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return de("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 de(x.message);let b=x.value;logger.debug("[sync] resolved state branch",{stateBranch:b,stateBranchRoot:o});let R=_("commitOwnEventFileToStateBranch",await op({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(a(R))return de(R.message);l=R.value.createdCommit,u=R.value.commitSha;let I=_("pullBranchRebaseIfPresent",await Jr({cwd:o,branch:b}));if(a(I))return de(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)&&wi(k.message)){let A=_("pullBranchRebaseIfPresent(retry)",await Jr({cwd:o,branch:b}));if(a(A))return de(A.message);m=m||A.value,k=_("pushStateBranch(retry)",await En({stateBranchRoot:o,repoRoot:r}))}if(a(k))return de(k.message);g=k.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let k=_("git rev-parse HEAD",await O({args:["rev-parse","HEAD"],cwd:o}));if(a(k))return de(k.message);u=k.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Zo(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 Ke,lc,Xn=y(()=>{"use strict";tc();Tr();vn();Me();G();S();T();Xo();ni();Ke=async()=>{let e=lc();if(e)return e;logger.debug("[sync] syncAndReloadState:start");let t=_("resolveActorId",J());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",Ht(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=lc();if(d)return d;let l=Qd();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",ec(l));return a(u)?u:(E({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done"),c("Synced",!0))},lc=()=>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 ri}from"ulid";var uc,ct,wn,Tn,ip,sp,mc,pc,gc,fc,vc,yc,xc,hc,Ec,Nc=y(()=>{"use strict";Xn();ni();jt();Vo();Tr();vn();Et();Me();xn();te();S();se();Ce();T();ne();Dt();uc=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=uc(e);if(a(t))return t;let n=await dc(t.value);if(a(n))return s(n.message);let{stateBranchRoot:r}=n.value,o=Ht(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=xa();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=De();return a(e)?s(e.message):e},ip=e=>(e.props.tags??[]).map(t=>N.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),sp=e=>(e.props.assignees??[]).map(t=>N.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),mc=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)},pc=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)},gc=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($).filter(o=>e.includeClosed||o.parentNodeId!==ue).map(o=>({id:o.id,title:qn(o.title),description:o.props.description??"",parentId:o.parentNodeId,isClosed:o.parentNodeId===ue,readonly:!!o.readonly,tags:ip(o),assignees:sp(o)}));return c("Listed issues",r)},fc=async e=>{let t=await ct(e.repoRoot);if(a(t))return t;let n=wn();if(a(n))return n;let r=qt(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 Ke();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")},vc=async e=>{let t=await ct(e.repoRoot);if(a(t))return t;let n=wn();if(a(n))return n;let r=Yt(ue,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(r))return r;let o={id:ri(),...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 Ke();return a(l)?l:c("Closed issue",{id:e.issueId})},yc=async e=>{let t=await ct(e.repoRoot);if(a(t))return t;let n=wn();if(a(n))return n;let r=Yt(e.parentId,e.issueId,e.position??{at:"end"},n.value,t.value.stateBranchRoot);if(a(r))return r;let o={id:ri(),...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 Ke();return a(l)?l:c("Moved issue",{id:e.issueId,parentId:e.parentId})},xc=async(e={})=>{let t=uc(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)},hc=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})},Ec=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(!$(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:ri(),...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 Ke();return a(m)?m:c("Edited issue description",{id:e.issueId,description:e.description})}});var Sc={};Tc(Sc,{createMcpServer:()=>Ic,resultJson:()=>je,startMcpServer:()=>bc});import{McpServer as ap}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as dp}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as D}from"zod";var je,Ic,bc,Cc=y(async()=>{"use strict";S();Nc();je=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Ic=()=>{let e=new ap({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:D.object({repoRoot:D.string().optional()})},async t=>je(await hc(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:D.object({repoRoot:D.string().optional(),includeClosed:D.boolean().optional()})},async t=>je(await gc(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:D.object({repoRoot:D.string().optional()})},async t=>je(await mc(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:D.object({repoRoot:D.string().optional(),boardId:D.string().optional()})},async t=>je(await pc(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue",inputSchema:D.object({title:D.string().min(1),parentId:D.string().min(1),repoRoot:D.string().optional()})},async t=>je(await fc(t))),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:D.object({issueId:D.string().min(1),description:D.string(),repoRoot:D.string().optional()})},async t=>je(await Ec(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:D.object({issueId:D.string().min(1),repoRoot:D.string().optional()})},async t=>je(await vc(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:D.object({issueId:D.string().min(1),parentId:D.string().min(1),position:D.discriminatedUnion("at",[D.object({at:D.literal("start")}),D.object({at:D.literal("end")}),D.object({at:D.literal("before"),sibling:D.string().min(1)}),D.object({at:D.literal("after"),sibling:D.string().min(1)})]).optional(),repoRoot:D.string().optional()})},async t=>je(await yc(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:D.object({repoRoot:D.string().optional()})},async t=>je(await xc(t))),e},bc=async()=>{let e=Ic(),t=new dp;await e.connect(t)};await bc()});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;await Cc().then(()=>Sc);