epiq 0.6.16 → 0.6.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,63 +1,63 @@
1
1
  #!/usr/bin/env node
2
- import kr from"chalk";import{render as cp}from"ink";import lp from"meow";import up from"react";import Kr from"node:fs";import ec from"node:os";import Le from"node:path";import qt from"node:fs";import{ulid as jd}from"ulid";import{z as Tn}from"zod";var qe={None:"none",Success:"success",Fail:"fail"},a=e=>({status:qe.Fail,message:e,value:null}),c=(e,t)=>({status:qe.Success,message:e,value:t}),d=e=>e.status==="fail",J=e=>e.status==="success";import zt from"node:fs";import $e from"node:path";var Ep=process.env.IS_LOCAL==="true",_e=".epiq",ye=".epiq-global",Sn="events",Wd="project.json",In=e=>$e.join(e,_e),Rn=e=>$e.join(In(e),Wd),Gt=e=>$e.join(In(e),Sn),Zo=e=>$e.join(e,_e),Hd=e=>{let t=$e.join(e,_e);return zt.existsSync(t)&&zt.statSync(t).isDirectory()},Br=e=>{let t=Rn(e);return zt.existsSync(t)&&zt.statSync(t).isFile()},An=e=>{let t=$e.resolve(e);for(;;){if(Hd(t))return c("Resolved closest .epiq root",t);let n=$e.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},Ye=e=>{let t=$e.resolve(e);for(;;){if(Br(t))return c("Resolved closest epiq project root",t);let n=$e.dirname(t);if(n===t)return a("No .epiq/project.json found in any parent");t=n}},ei=e=>{let t=Gt(e);try{return zt.mkdirSync(t,{recursive:!0}),c("Resolved events dir",t)}catch(n){return a(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},Re=async()=>{let e=await Je(process.cwd());if(d(e))return e;let t=Xe({repoRoot:e.value});return d(t)?t:c("Resolved persist root",t.value)};var Vd="__epiq_state__",Kd=Tn.object({projectId:Tn.string().min(1),stateBranch:Tn.string().min(1),createdAt:Tn.iso.datetime()}),ti=()=>({projectId:jd(),stateBranch:Vd,createdAt:new Date().toISOString()}),Qe=e=>{let t=Rn(e);if(!qt.existsSync(t))return a("Missing .epiq/project.json");try{let n=qt.readFileSync(t,"utf8"),r=JSON.parse(n),o=Kd.safeParse(r);return o.success?c("Read project.json",o.data):a(`Invalid .epiq/project.json: ${o.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(", ")}`)}catch(n){return a(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},ni=e=>{let t=Qe(e);return d(t)?a(t.message):c("Read projectId",t.value.projectId)},ri=({repoRoot:e,fileContents:t})=>{let n=In(e),r=Rn(e);try{if(qt.mkdirSync(n,{recursive:!0}),qt.existsSync(r)){let o=Qe(e);return d(o)?a(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 a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var Ur=(e,t)=>{let n=new Map,r=t??((...i)=>JSON.stringify(i)),o=((...i)=>{let s=r(...i);if(!n.has(s)){let l=e(...i).then(u=>(d(u)&&n.delete(s),u));n.set(s,l)}return n.get(s)});return o.clear=()=>n.clear(),o};import Yt from"fs";import Wr from"path";import zd from"util";var oi=1e3,Gd=50,Or=0,ii=()=>process.env.EPIQ_MCP==="true",si=()=>{let e=process.cwd(),t=An(e);return d(t)?ii()?Wr.join(process.cwd(),".epiq-mcp.log"):void 0:Wr.join(t.value,_e,"log","epiq.log")};function qd(){let e=si();if(!e||!Yt.existsSync(e))return;let n=Yt.readFileSync(e,"utf8").split(`
4
- `);if(n[n.length-1]===""&&n.pop(),n.length<=oi)return;let r=n.slice(-oi).join(`
2
+ import Fr from"chalk";import{render as pp}from"ink";import gp from"meow";import fp from"react";import Gr from"node:fs";import nc from"node:os";import Le from"node:path";import Yt from"node:fs";import{ulid as Kd}from"ulid";import{z as wn}from"zod";var qe={None:"none",Success:"success",Fail:"fail"},a=e=>({status:qe.Fail,message:e,value:null}),c=(e,t)=>({status:qe.Success,message:e,value:t}),d=e=>e.status==="fail",J=e=>e.status==="success";import Gt from"node:fs";import $e from"node:path";var Sp=process.env.IS_LOCAL==="true",_e=".epiq",he=".epiq-global",In="events",jd="project.json",Rn=e=>$e.join(e,_e),An=e=>$e.join(Rn(e),jd),qt=e=>$e.join(Rn(e),In),ni=e=>$e.join(e,_e),Vd=e=>{let t=$e.join(e,_e);return Gt.existsSync(t)&&Gt.statSync(t).isDirectory()},Ur=e=>{let t=An(e);return Gt.existsSync(t)&&Gt.statSync(t).isFile()},Tn=e=>{let t=$e.resolve(e);for(;;){if(Vd(t))return c("Resolved closest .epiq root",t);let n=$e.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},Ye=e=>{let t=$e.resolve(e);for(;;){if(Ur(t))return c("Resolved closest epiq project root",t);let n=$e.dirname(t);if(n===t)return a("No .epiq/project.json found in any parent");t=n}},ri=e=>{let t=qt(e);try{return Gt.mkdirSync(t,{recursive:!0}),c("Resolved events dir",t)}catch(n){return a(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},Re=async()=>{let e=await Je(process.cwd());if(d(e))return e;let t=Xe({repoRoot:e.value});return d(t)?t:c("Resolved persist root",t.value)};var zd="__epiq_state__",Gd=wn.object({projectId:wn.string().min(1),stateBranch:wn.string().min(1),createdAt:wn.iso.datetime()}),Mn=()=>({projectId:Kd(),stateBranch:zd,createdAt:new Date().toISOString()}),Qe=e=>{let t=An(e);if(!Yt.existsSync(t))return a("Missing .epiq/project.json");try{let n=Yt.readFileSync(t,"utf8"),r=JSON.parse(n),o=Gd.safeParse(r);return o.success?c("Read project.json",o.data):a(`Invalid .epiq/project.json: ${o.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(", ")}`)}catch(n){return a(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},oi=e=>{let t=Qe(e);return d(t)?a(t.message):c("Read projectId",t.value.projectId)},ii=({repoRoot:e,fileContents:t})=>{let n=Rn(e),r=An(e);try{if(Yt.mkdirSync(n,{recursive:!0}),Yt.existsSync(r)){let o=Qe(e);return d(o)?a(o.message):c("Project already initialized",null)}return Yt.writeFileSync(r,JSON.stringify(t,null,2)+`
3
+ `,"utf8"),c("Created project.json",null)}catch(o){return a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var $r=(e,t)=>{let n=new Map,r=t??((...i)=>JSON.stringify(i)),o=((...i)=>{let s=r(...i);if(!n.has(s)){let l=e(...i).then(u=>(d(u)&&n.delete(s),u));n.set(s,l)}return n.get(s)});return o.clear=()=>n.clear(),o};import Xt from"fs";import jr from"path";import qd from"util";var si=1e3,Yd=50,_r=0,ai=()=>process.env.EPIQ_MCP==="true",di=()=>{let e=process.cwd(),t=Tn(e);return d(t)?ai()?jr.join(process.cwd(),".epiq-mcp.log"):void 0:jr.join(t.value,_e,"log","epiq.log")};function Xd(){let e=di();if(!e||!Xt.existsSync(e))return;let n=Xt.readFileSync(e,"utf8").split(`
4
+ `);if(n[n.length-1]===""&&n.pop(),n.length<=si)return;let r=n.slice(-si).join(`
5
5
  `)+`
6
- `;Yt.writeFileSync(e,r,"utf8")}function $r(e,t,n=!1){let r=si();if(!r)return;let o=zd.format(...t),i=new Date,l=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
7
- `;Yt.mkdirSync(Wr.dirname(r),{recursive:!0}),Yt.appendFileSync(r,l,"utf8"),Or++,Or>=Gd&&(Or=0,qd())}var _r=()=>ii()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",ae={info(...e){let t=_r();(t==="info"||t==="debug")&&$r("[Info]",e,!1)},debug(...e){_r()==="debug"&&$r("[Debug]",e,!0)},error(...e){let t=_r();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;$r("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=ae;import{spawn as Yd}from"node:child_process";import wn from"node:fs";import Xt from"node:path";var G={stage:({cwd:e,pathspec:t})=>D({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>D({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>D({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>D({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>D({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 D({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>D({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>D({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>D({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>D({args:["worktree","prune"],cwd:e})};var At=e=>{let t=Ye(e);if(d(t))return a("Unable to resolve epiq project root");let n=Qe(t.value);return d(n)?a("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},he="origin";var ai=1e4,Xd={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},ci=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!wn.existsSync(t)){let g=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:g,exitCode:1});return}r(a(g));return}let o=Yd("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Xd}),i=!1,s="",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 ${ai}ms`].join(`
8
- `);u(n?{stdout:s,stderr:g,exitCode:124}:a(g))},ai);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",g=>{s+=g}),o.stderr.on("data",g=>{l+=g}),o.on("error",g=>{if(n){u({stdout:s,stderr:g.message,exitCode:1});return}u(a([`git ${e.join(" ")}`,`cwd=${t}`,g.message].join(`
9
- `)))}),o.on("close",g=>{let y=g??1;if(n){u({stdout:s,stderr:l,exitCode:y});return}if(y!==0){u(a([`git ${e.join(" ")}`,l.trim()||s.trim()||"Git command failed"].filter(Boolean).join(`
10
- `)));return}u(c("Git command succeeded",{stdout:s,stderr:l,exitCode:y}))})}),D=({args:e,cwd:t})=>ci({args:e,cwd:t,allowFail:!1}),Pe=({args:e,cwd:t})=>ci({args:e,cwd:t,allowFail:!0}),Tt=async({cwd:e,message:t})=>{let n=await G.commit({cwd:e,message:t});if(d(n))return a(`Failed to create commit
11
- ${n.message}`);let r=await D({args:["rev-parse","HEAD"],cwd:e});return d(r)?a(`Commit created, but failed to read HEAD SHA
12
- ${r.message}`):c("Created commit and resolved SHA",r.value.stdout.trim())},Jd=async e=>{let t=await D({cwd:e,args:["rev-parse","--git-dir"]});if(d(t))return a(t.message);let n=t.value.stdout.trim();return c("Resolved git dir",Xt.isAbsolute(n)?n:Xt.resolve(e,n))},Qd=async e=>{let t=await Jd(e);if(d(t))return a(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress",REBASE_HEAD:"rebase in progress"};for(let[i,s]of Object.entries(r))if(wn.existsSync(Xt.join(n,i)))return c("Checked for in-progress Git operation",s);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[i,s]of Object.entries(o))if(wn.existsSync(Xt.join(n,i)))return c("Checked for in-progress Git operation",s);return c("Checked for in-progress Git operation",null)},Mn=async e=>{let t=await Qd(e);return d(t)?a(t.message):c("Checked for in-progress Git operation",t.value!==null)},Hr=async({repoRoot:e})=>{let n=(await Pe({args:["remote","get-url",he],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},Pn=async({repoRoot:e,branch:t})=>{let n=await Pe({args:["ls-remote","--heads",he,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${he}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},Ln=async({repoRoot:e,branch:t})=>{let n=await Pe({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):a(n.stderr.trim()||`Unable to inspect branch ${t}`)},di=e=>{try{return wn.realpathSync.native(e)}catch{return Xt.resolve(e)}},li=async({repoRoot:e,worktreeRoot:t})=>{let n=await D({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=di(t),o=n.value.stdout.split(`
13
- `).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(di).includes(r);return c("Checked worktree registration",o)},jr=async e=>{let t=await Pe({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},kn=async e=>{let t=await D({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?a(t.message):c("Resolved current branch",t.value.stdout.trim())},ui=async e=>{let t=await D({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?a(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},mi=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Zd=async e=>(await Pe({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1);var Vr=async({cwd:e,branch:t})=>{let n=await Pn({repoRoot:e,branch:t});if(d(n))return a(n.message);if(!n.value)return c("Remote branch missing, skipped pull",!1);let r=await Zd(e);if(d(r))return a(r.message);let o=await G.fetch({cwd:e,remote:he,branch:t});if(d(o))return a(`Failed to fetch ${t}
14
- ${o.message}`);let i=await G.pullRebase({cwd:e,remote:he,branch:t});return d(i)?a(`Failed during pull --rebase
15
- ${i.message}`):c("Pulled with rebase",!0)},pi=async e=>{let t=await Pe({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?c("No staged changes",!1):t.exitCode===1?c("Has staged changes",!0):a(t.stderr.trim()||"Unable to inspect staged changes")};var gi=async e=>{let t=await kn(e);return d(t)?a(t.message):c("Checked detached HEAD state",t.value==="HEAD")};var vi="4b825dc642cb6eb9a060e54bf8d69288fbee4904",zr=e=>Le.join(_e,Sn,e),xi=()=>Le.join(ec.homedir(),ye),Dn=()=>Le.join(xi(),"worktrees"),Xe=({repoRoot:e})=>{let t=ni(e);return d(t)?a(t.message):c("Resolved state branch root",Le.join(Dn(),t.value))},tc=e=>Le.join(e,_e),fi=e=>Le.join(tc(e),Sn);var Jt=e=>{try{return Kr.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},Fn=()=>{let e=Jt(xi());if(d(e))return a(`Ensure epiq home failed.
16
- `+e.message);let t=Jt(Dn());return d(t)?a(`Ensure worktrees dir failed.
17
- `+t.message):c("Ensured epiq storage",!0)},yi=e=>{Kr.existsSync(e)&&(ae.debug("[sync] remove path",e),Kr.rmSync(e,{recursive:!0,force:!0}))};var hi=(e,t)=>{for(let n of[fi(e),fi(t)]){let r=Jt(n);if(d(r))return a(r.message)}return c("Ensured state branch",void 0)},Ei=async e=>{let t=await D({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return a(`ensure state branch is storage only failed
6
+ `;Xt.writeFileSync(e,r,"utf8")}function Wr(e,t,n=!1){let r=di();if(!r)return;let o=qd.format(...t),i=new Date,l=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
7
+ `;Xt.mkdirSync(jr.dirname(r),{recursive:!0}),Xt.appendFileSync(r,l,"utf8"),_r++,_r>=Yd&&(_r=0,Xd())}var Hr=()=>ai()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",de={info(...e){let t=Hr();(t==="info"||t==="debug")&&Wr("[Info]",e,!1)},debug(...e){Hr()==="debug"&&Wr("[Debug]",e,!0)},error(...e){let t=Hr();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;Wr("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=de;import{spawn as Jd}from"node:child_process";import Pn from"node:fs";import Jt from"node:path";var G={stage:({cwd:e,pathspec:t})=>k({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>k({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>k({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>k({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>k({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 k({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>k({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>k({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>k({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>k({args:["worktree","prune"],cwd:e})};var Tt=e=>{let t=Ye(e);if(d(t))return a("Unable to resolve epiq project root");let n=Qe(t.value);return d(n)?a("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},ye="origin";var ci=1e4,Qd={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},ui=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Pn.existsSync(t)){let g=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:g,exitCode:1});return}r(a(g));return}let o=Jd("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Qd}),i=!1,s="",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 ${ci}ms`].join(`
8
+ `);u(n?{stdout:s,stderr:g,exitCode:124}:a(g))},ci);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",g=>{s+=g}),o.stderr.on("data",g=>{l+=g}),o.on("error",g=>{if(n){u({stdout:s,stderr:g.message,exitCode:1});return}u(a([`git ${e.join(" ")}`,`cwd=${t}`,g.message].join(`
9
+ `)))}),o.on("close",g=>{let h=g??1;if(n){u({stdout:s,stderr:l,exitCode:h});return}if(h!==0){u(a([`git ${e.join(" ")}`,l.trim()||s.trim()||"Git command failed"].filter(Boolean).join(`
10
+ `)));return}u(c("Git command succeeded",{stdout:s,stderr:l,exitCode:h}))})}),k=({args:e,cwd:t})=>ui({args:e,cwd:t,allowFail:!1}),Pe=({args:e,cwd:t})=>ui({args:e,cwd:t,allowFail:!0}),wt=async({cwd:e,message:t})=>{let n=await G.commit({cwd:e,message:t});if(d(n))return a(`Failed to create commit
11
+ ${n.message}`);let r=await k({args:["rev-parse","HEAD"],cwd:e});return d(r)?a(`Commit created, but failed to read HEAD SHA
12
+ ${r.message}`):c("Created commit and resolved SHA",r.value.stdout.trim())},Zd=async e=>{let t=await k({cwd:e,args:["rev-parse","--git-dir"]});if(d(t))return a(t.message);let n=t.value.stdout.trim();return c("Resolved git dir",Jt.isAbsolute(n)?n:Jt.resolve(e,n))},ec=async e=>{let t=await Zd(e);if(d(t))return a(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[i,s]of Object.entries(r))if(Pn.existsSync(Jt.join(n,i)))return c("Checked for in-progress Git operation",s);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[i,s]of Object.entries(o))if(Pn.existsSync(Jt.join(n,i)))return c("Checked for in-progress Git operation",s);return c("Checked for in-progress Git operation",null)},Ln=async e=>{let t=await ec(e);return d(t)?a(t.message):c("Checked for in-progress Git operation",t.value!==null)},Vr=async({repoRoot:e})=>{let n=(await Pe({args:["remote","get-url",ye],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},kn=async({repoRoot:e,branch:t})=>{let n=await Pe({args:["ls-remote","--heads",ye,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${ye}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},Dn=async({repoRoot:e,branch:t})=>{let n=await Pe({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):a(n.stderr.trim()||`Unable to inspect branch ${t}`)},li=e=>{try{return Pn.realpathSync.native(e)}catch{return Jt.resolve(e)}},mi=async({repoRoot:e,worktreeRoot:t})=>{let n=await k({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=li(t),o=n.value.stdout.split(`
13
+ `).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(li).includes(r);return c("Checked worktree registration",o)},Kr=async e=>{let t=await Pe({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Fn=async e=>{let t=await k({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?a(t.message):c("Resolved current branch",t.value.stdout.trim())},pi=async e=>{let t=await k({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?a(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},gi=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),tc=async e=>(await Pe({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1);var zr=async({cwd:e,branch:t})=>{let n=await kn({repoRoot:e,branch:t});if(d(n))return a(n.message);if(!n.value)return c("Remote branch missing, skipped pull",!1);let r=await tc(e);if(d(r))return a(r.message);let o=await G.fetch({cwd:e,remote:ye,branch:t});if(d(o))return a(`Failed to fetch ${t}
14
+ ${o.message}`);let i=await G.pullRebase({cwd:e,remote:ye,branch:t});return d(i)?a(`Failed during pull --rebase
15
+ ${i.message}`):c("Pulled with rebase",!0)},fi=async e=>{let t=await Pe({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?c("No staged changes",!1):t.exitCode===1?c("Has staged changes",!0):a(t.stderr.trim()||"Unable to inspect staged changes")};var vi=async e=>{let t=await Fn(e);return d(t)?a(t.message):c("Checked detached HEAD state",t.value==="HEAD")};var hi="4b825dc642cb6eb9a060e54bf8d69288fbee4904",qr=e=>Le.join(_e,In,e),yi=()=>Le.join(nc.homedir(),he),On=()=>Le.join(yi(),"worktrees"),Xe=({repoRoot:e})=>{let t=oi(e);return d(t)?a(t.message):c("Resolved state branch root",Le.join(On(),t.value))},rc=e=>Le.join(e,_e),xi=e=>Le.join(rc(e),In);var Qt=e=>{try{return Gr.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},Bn=()=>{let e=Qt(yi());if(d(e))return a(`Ensure epiq home failed.
16
+ `+e.message);let t=Qt(On());return d(t)?a(`Ensure worktrees dir failed.
17
+ `+t.message):c("Ensured epiq storage",!0)},Ci=e=>{Gr.existsSync(e)&&(de.debug("[sync] remove path",e),Gr.rmSync(e,{recursive:!0,force:!0}))};var Ei=(e,t)=>{for(let n of[xi(e),xi(t)]){let r=Qt(n);if(d(r))return a(r.message)}return c("Ensured state branch",void 0)},Ni=async e=>{let t=await k({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return a(`ensure state branch is storage only failed
18
18
  `+t.message);let r=t.value.stdout.trim().split(`
19
- `).filter(Boolean).filter(s=>s!==_e);if(r.length===0)return c("State branch is storage-only",!1);let o=await D({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return a(`Failed to clean storage branch
20
- ${o.message}`);let i=await Tt({cwd:e,message:"[epiq:repair-storage-branch]"});return d(i)?a(i.message):c("Cleaned storage branch",!0)},Je=Ur(async(e=process.cwd())=>{let t=await D({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?a("Not inside a Git repository"):c("Resolved repo root",t.value.stdout.trim())},e=>Le.resolve(e)),cg=Ur(async e=>{let t=await D({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return a(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{Box as gt}from"ink";import z from"react";import{useSyncExternalStore as nc}from"react";var Qt={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Gr=new Set,rc=()=>{for(let e of Gr)e()},U=()=>Qt,Ci=()=>nc(e=>(Gr.add(e),()=>{Gr.delete(e)}),()=>Qt),Ee=e=>(Qt={...Qt,...e},rc(),Qt);var Ze=()=>{let e=U(),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}},Ni=()=>{let e=Ye(process.cwd());if(d(e))return!1;let t=Qe(e.value);return J(t)},bi=e=>e===!0?"on":e===!1?"off":null,Si=e=>e==="on"?!0:e==="off"?!1:null;var p={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var Ce=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?c("Found node",n):a("Unable to find node in breadcrumb")};import{useSyncExternalStore as lm}from"react";var w={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function qr(e){return e.context===w.WORKSPACE}function $(e){return e.context===w.TICKET}function et(e){return e.context===w.TEXT}function tt(e){return e.context===w.FIELD}function Zt(e){return e.context===w.FIELD_LIST}var wt=e=>e.context===w.SWIMLANE,Ii=e=>e.context===w.BOARD;var Ri=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Ai=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",Ti=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",wi=(e,t)=>{if(Ai(e,e.sequence))return f.MoveCursorLeftOfWord;if(Ti(e,e.sequence))return f.MoveCursorRightOfWord;if(Ri(e,e.sequence))return f.EraseInputWord;switch(e.name){case"tab":return f.AutoCompleteCommand;case"up":return f.GetLastCommandFromHistory;case"down":return f.GetNextCommandFromHistory;case"left":return f.MoveCursorLeft;case"right":return f.MoveCursorRight;case"return":return f.Confirm;case"backspace":return t?f.EraseInput:f.ExitCommandLine;case"escape":return f.ExitCommandLine;default:return f.CaptureInput}},Mi=(e,t)=>{if(Ai(e,e.sequence))return f.MoveCursorLeftOfWord;if(Ti(e,e.sequence))return f.MoveCursorRightOfWord;if(Ri(e,e.sequence))return f.EraseInputWord;switch(e.name){case"tab":return f.AutoCompleteCommand;case"up":return f.NavPreviousItem;case"down":return f.NavNextItem;case"left":return f.MoveCursorLeft;case"right":return f.MoveCursorRight;case"return":return f.Confirm;case"backspace":return t?f.EraseInput:f.ExitCommandLine;case"escape":return f.ExitCommandLine;default:return f.CaptureInput}};function Bn(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Un=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Pi=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Li=e=>e.charAt(0).toUpperCase()+e.slice(1);var ki=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},Di=(e,t)=>t?e.get(t)??[]:[];var Fi=new WeakMap,oc=e=>{let t=Fi.get(e);return t||(t=ki(e),Fi.set(e,t)),t};var Bi=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Di(oc(e),r).filter(i=>Bn(r,i)>=n)};var ic={hint:"",hints:[],overlap:0,remainder:""},Ui=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return ic;let o=Bi({wordList:r,inputToMatch:e,overlapThreshold:1});return sc(t,o)},sc=(e,t)=>{let n=t[0]??"",r=Bn(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),s=r<(o??"").length,l=!!i,g=(l&&s?o:n)+(l&&s?":":" "),y=g.slice(r);return{hint:g,hints:t,overlap:r,remainder:y}};import{ulid as cc}from"ulid";var Mt=24n,ac=Mt*4n,We=(1n<<ac)-1n,dc=/^[0-9a-f]+$/;function Oi(e){return!e||!dc.test(e)?a(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Ae(e,t=Mt){if(e<0n)return a("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 Ae(We/2n,Mt);let n=e?Oi(e):c("Resolved lower bound",0n);if(d(n))return n;let r=t?Oi(t):c("Resolved upper bound",We);if(d(r))return r;let o=n.value,i=r.value;if(i<=o)return Ae(We/2n,Mt);let s=(o+i)/2n;return s===o||s===i?a("No rank space available between neighbors"):Ae(s,Mt)}function $i(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=Ae(o,Mt);if(d(i))return i;n.push(i.value)}return c("Resolved evenly spaced ranks",n)}var Yr=(e,t)=>{let n=B(e),r=$i(n.length);if(d(r))return r;let o={};for(let i=0;i<n.length;i++){let s=n[i],l=r.value[i];if(!s||!l)return a("Unable to assign rebalance rank");o[s.id]=l}return c("Created rebalance event",{id:cc(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var Q={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History"};var nt=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return a("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 a(`No ancestor found for context: ${t}`)},Xr=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},vt=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:a("Node not found"),b={deleteNode(e){Ne(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 a("Edit target node not found");let o=vt(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 a("Rename target node not found");let r=vt(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 B(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 a("Node not found");if(!i)return a("Target parent not found");if(r===e)return a("Cannot move root node");if(e===t)return a("Cannot move node into itself");let s=vt(o,"move");if(s)return s;if(Xr(t,e))return a("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 a("Node not found");if(r===e)return a("Cannot delete root node");let i=new Set,s=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let g of B(m.id))s(g.id)}};s(e);let l={...structuredClone(t)};for(let u of i){if(!l[u])return a("Unable to locate node to delete");l[u]={...l[u],isDeleted:!0}}return n?(N({nodes:l}),c("Successfully tomb stoned",o)):a("Unable to delete undefined")},createContributor(e){let t=Ne(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):c("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to assign contributor, missing contributor");if(!r)return a("Unable to assign contributor, missing target");let o=vt(r,"edit");if(o)return o;if(!$(r))return a("Target is not an issue");let i=r.props.assignees??[];if(i.includes(t))return a("Contributor already assigned");let s={...r,props:{...r.props,assignees:[...i,t]}};return this.updateNode(s),c("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to unassign, missing contributor");if(!r)return a("Unable to unassign, missing target");let o=vt(r,"edit");if(o)return o;if(!$(r))return a("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 s={...r,props:{...r.props,assignees:i.filter(l=>l!==t)}};return this.updateNode(s),c("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to add tag, missing tag");if(!r)return a("Unable to add tag, missing target");let o=vt(r,"edit");if(o)return o;if(!$(r))return a("Target is not an issue");let i=r.props.tags??[];if(i.includes(t))return a("Tag already assigned");let s={...r,props:{...r.props,tags:[...i,t]}};return this.updateNode(s),c("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to remove tag, missing tag");if(!r)return a("Unable to remove tag, missing target");let o=vt(r,"edit");if(o)return o;if(!$(r))return a("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 s={...r,props:{...r.props,tags:i.filter(l=>l!==t)}};return this.updateNode(s),c("Tag removed",{tag:t})},createTag(e){let t=Ne(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):c("Tag created",e)},createNode(e){let t=Ne(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?a("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=Ne(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):c("Locked node",n)},updateNode(e){let t=Ne(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(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 B(e)}};var q={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:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:w.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),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:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:w.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[],isVirtual:s})};import yt from"chalk";import Yi from"string-width";import{decodeTime as hc}from"ulid";import Pt from"chalk";var oe={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"},h={accent:oe.cyan,accent2:oe.magenta,primary:oe.white,secondary:oe.grayDark,secondary2:oe.grayLight,gray:oe.gray,green:oe.green,yellow:oe.yellow,red:oe.red};var E={red:oe.red,yellow:oe.yellow,green:oe.green,blue:oe.blue,magenta:oe.magenta,cyan:oe.cyan},xt={urgent:E.red,critical:E.red,important:E.red,blocker:E.red,asap:E.red,immediate:E.red,fail:E.red,failure:E.red,broken:E.red,bug:E.red,error:E.red,incident:E.red,outage:E.red,production:E.red,crash:E.red,security:E.red,warning:E.yellow,warn:E.yellow,risky:E.yellow,risk:E.yellow,attention:E.yellow,pending:E.yellow,review:E.yellow,"needs-review":E.yellow,qa:E.yellow,testing:E.yellow,test:E.yellow,validate:E.yellow,verification:E.yellow,staging:E.yellow,check:E.yellow,"follow-up":E.yellow,followup:E.yellow,waiting:E.yellow,blocked:E.yellow,hold:E.yellow,done:E.green,complete:E.green,completed:E.green,success:E.green,ok:E.green,stable:E.green,resolved:E.green,fixed:E.green,closed:E.green,merged:E.green,released:E.green,deployed:E.green,approved:E.green,verified:E.green,working:E.green,healthy:E.green,pass:E.green,passing:E.green,info:E.blue,information:E.blue,note:E.blue,docs:E.blue,documentation:E.blue,doc:E.blue,guide:E.blue,help:E.blue,explanation:E.blue,detail:E.blue,details:E.blue,context:E.blue,design:E.blue,discussion:E.blue,proposal:E.blue,idea:E.blue,feature:E.magenta,enhancement:E.magenta,improvement:E.magenta,refactor:E.magenta,refactoring:E.magenta,cleanup:E.magenta,optimize:E.magenta,optimization:E.magenta,perf:E.magenta,performance:E.magenta,upgrade:E.magenta,migration:E.magenta,modernize:E.magenta,debt:E.magenta,todo:E.cyan,next:E.cyan,planned:E.cyan,plan:E.cyan,future:E.cyan,backlog:E.cyan,investigate:E.cyan,explore:E.cyan,prototype:E.cyan};var lc=[0,0,0],Zr=.2,Qr={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},_i=(e,t,n)=>Math.max(t,Math.min(n,e)),Jr=(e,t,n)=>e+(t-e)*n,Wi=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},uc=e=>e.toLowerCase().trim(),mc=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,s=e/60,l=i*(1-Math.abs(s%2-1)),u=0,m=0,g=0;s>=0&&s<1?(u=i,m=l):s>=1&&s<2?(u=l,m=i):s>=2&&s<3?(m=i,g=l):s>=3&&s<4?(m=l,g=i):s>=4&&s<5?(u=l,g=i):(u=i,g=l);let y=o-i/2;return[Math.round((u+y)*255),Math.round((m+y)*255),Math.round((g+y)*255)]},Hi=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,pc=e=>{let t=e.replace("#","");return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]},ji=(e,t,n)=>{let r=_i(n,0,1);return[Math.round(Jr(e[0],t[0],r)),Math.round(Jr(e[1],t[1],r)),Math.round(Jr(e[2],t[2],r))]},gc=(e,t=Zr)=>ji(e,lc,t),fc=(e,t=Zr)=>Hi(gc(pc(e),t)),vc=(e,t,n)=>ji(e,t,n),en=e=>{let n=Wi(e)%360,r=mc(n,Qr.stringColor.saturation,Qr.stringColor.lightness);return Hi(r)},be=(e,t=xt)=>{let n=uc(e);return n&&t[n]?t[n]:en(n)},Vi=(e,t=xt,n=Zr)=>fc(be(e,t),n),xc=e=>{let t=Qr.gradient.stops,n=_i(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),s=o-i;return vc(t[i],t[i+1],s)},On=e=>Wi(e.toLowerCase().trim())/4294967295,Ki=e=>{let t=On(e);return xc(t)},yc=e=>{let[t,n,r]=Ki(e);return{normal:o=>Pt.bgRgb(t,n,r).black(o),cursor:o=>Pt.bgRgb(t,n,r).white.bold(o)}},eo=e=>{let[t,n,r]=Ki(e);return{fg:o=>Pt.rgb(t,n,r)(o),fgCursor:o=>Pt.rgb(t,n,r).inverse(o),bg:o=>Pt.bgRgb(t,n,r).black(o),bgCursor:o=>Pt.bgRgb(t,n,r).white.bold(o)}},$n=e=>yc(e).normal(` ${e} `);import{decodeTime as zi}from"ulid";var Gi=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"},qi=e=>{let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},_n=e=>{try{return c("Decoded date",new Date(zi(e)))}catch(t){return a("Decoding failed + "+t.message)}},to=e=>{if(!e?.id)return null;try{return zi(e.id)}catch{return null}};var Ec=(e,t)=>e+" ".repeat(Math.max(0,t-Yi(e))),Cc=(e,t)=>" ".repeat(Math.max(0,t-Yi(e)))+e,Nc=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`),bc=(e,t)=>t?e<t?"up":e>t?"down":null:null,Sc=(e,t)=>{let n=b.getNode(e.payload.parent),r=n?yt.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let i=bc(e.payload.rank,o.rank);if(i)return`Moved ${i} in ${r}`}return`Moved issue to ${r}`},Ic=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?yt.bgHex(be(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?yt.bgHex(be(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?yt.hex(be(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?yt.hex(be(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""}},Rc=e=>{let t=Gi(hc(e));return yt.gray(Cc(t,8))},Ac=12,Tc=e=>Ec(`${e}`,Ac),Xi=(e,t)=>{let n=Rc(e.id),r=Tc(e.userName),o=yt.dim("\u203A"),i=e.action==="move.node"?Sc(e,t):[Nc(e.action),Ic(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${i}`};import{createHash as wc}from"node:crypto";var Mc="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Pc=e=>{let t=wc("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+=Mc[Number(n>>i&31n)]}return r},rt=(e,t)=>Pc(`${e}:virtual:${t}`);var Lc=e=>rt(e,"description"),kc=e=>rt(e,"assignees"),Dc=e=>rt(e,"tags"),Fc=e=>rt(e,"history"),Ji=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:i=!1,childRenderAxis:s="horizontal"})=>{let l=b.getNode(e);if(!l){let g=b.createNode({...q.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:i,childRenderAxis:s});return d(g)?g:c("Virtual field created",void 0)}if(!tt(l))return a(`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!==s))return c("Virtual field unchanged",void 0);let m=b.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:i,childRenderAxis:s});return d(m)?m:c("Virtual field updated",void 0)},Qi=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:i="horizontal"})=>{let s=b.getNode(e);if(!s){let m=b.createNode({...q.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:i});return d(m)?m:c("Virtual field list created",void 0)}if(!Zt(s))return a(`Existing virtual node ${e} is not a field list`);if(!(s.title!==t||s.parentNodeId!==n||s.rank!==r||s.readonly!==o||s.childRenderAxis!==i))return c("Virtual field list unchanged",void 0);let u=b.updateNode({...s,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:i});return d(u)?u:c("Virtual field list updated",void 0)},Zi=e=>{let t=Ae(We/4n),n=Ae(We/2n),r=Ae(We*3n/4n),o=Ae(We*7n/8n);if(d(t))return t;if(d(n))return n;if(d(r))return r;if(d(o))return o;let i=Ji({id:Lc(e.id),name:Q.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(i))return i;let s=Qi({id:kc(e.id),name:Q.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(s))return s;let l=Qi({id:Dc(e.id),name:Q.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(l))return l;let u=Ji({id:Fc(e.id),name:Q.HISTORY,parentNodeId:e.id,rank:o.value,value:Bc(e),readonly:!0,childRenderAxis:"vertical"});return d(u)?u:c("Ticket virtual nodes materialized",void 0)},Bc=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=>Xi(r,n.get(r.action)??[])).join(`
21
- `)};var Uc=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[He,Wn]=Uc;var L=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),es=e=>{let t=b.getNode(e);if(!t||!$(t)||t.isDeleted)return null;let n=Zi(t);return d(n)?n:null},Oc=e=>{for(let t of e){let n=es(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=es(r);if(o)return o}return null},$c=(e,t)=>{let n=b.getNode(e);n&&b.updateNode({...n,log:[...n.log??[],t]})},_c=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},Wc=e=>{switch(e.action){case"delete.node":case"edit.description":return _c(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[]}},Hc=e=>{Ne(t=>({...t,eventLog:[...t.eventLog,e]}))},jc=(e,t)=>{let n=[...new Set(Wc(e))];t||(n.forEach(o=>$c(o,e)),Hc(e));let r=Oc(n);return r||null},Vc={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=q.workspace(t,n,r),i=nn(o);if(d(i))return L(i.message,e);let s=b.createNode(o);return d(s)?L(s.message??"Failed to initialize workspace",e):qr(s.value)?c("Workspace initialized",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=b.createNode(q.workspace(t,n,r));return d(o)?L(o.message??"Failed to add workspace",e):qr(o.value)?c("Added workspace",{action:e.action,result:o.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=b.createNode(q.board(t,n,r,o));return d(i)?L(i.message??"Unable to create board",e):Ii(i.value)?c("Added board",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=b.createNode(q.swimlane(t,n,r,o));return d(i)?L(i.message??"Unable to create swimlane",e):wt(i.value)?c("Added swimlane",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=b.createNode(q.ticket(t,n,r,o));return d(i)?L(i.message??"Unable to create issue",e):$(i.value)?c("Added issue",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:i}=e.payload,s=b.createNode(q.field({id:t,name:n,parentNodeId:r,rank:i,props:{value:o},childRenderAxis:n.includes(Q.DESCRIPTION)?"vertical":"horizontal"}));return d(s)?L(s.message??`Unable to create field: ${n}`,e):tt(s.value)?c("Added field",{action:e.action,result:s.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!b.getNode(t))return L(`Unable to locate node with id ${t}`,e);let o=b.renameNode(t,n);return d(o)?L(o.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=b.tombstoneNode(t);return d(n)?L(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=b.createTag({id:t,name:n});return d(r)?L(r.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=b.createContributor({id:t,name:n});return d(r)?L(r.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=b.tag(t,n);return d(r)?L(r.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=b.untag(t,n);return d(r)?L(r.message??"Unable to untag issue",e):c("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=b.assign(t,n);return d(r)?L(r.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=b.unassign(t,n);return d(r)?L(r.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?L(o.message??"Failed to move node",e):c("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=b.editValue(t,n);return d(r)?L(r.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return L("Unable to locate issue",e);if(!$(o))return L("Can only close issues",e);let i=b.getNode(He);if(!i)return L("Unable to locate target swimlane",e);if(n!==i.id)return L("Close target must be closed swimlane",e);let s=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(s)?L(s.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return L("Unable to locate issue",e);if(!$(o))return L("Can only reopen issues",e);let i=b.getNode(He);if(!i)return L("Unable to locate closed swimlane",e);if(n===i.id)return L("Cannot reopen issue into closed swimlane",e);if(!b.getNode(n))return L("Reopen parent no longer exists",e);let l=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(l)?L(l.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=b.lockNode(t);return d(n)?L(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=b.getNode(r);if(!i)return L(`Unable to locate node ${r}`,e);if(i.parentNodeId!==t)return L(`Node ${r} is not child of ${t}`,e);let s=b.updateNode({...i,rank:o});if(d(s))return L(s.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})}};function tn(e,t=!1){let n=Vc[e.action](e);if(d(n))return n;let r=jc(e,t);return r||n}var ht=e=>e.map(t=>tn(t));import tl from"node:fs";import nl from"node:path";import{decodeTime as rl,monotonicFactory as ol}from"ulid";import{z as rn}from"zod";import Hn from"node:fs";import ro from"node:path";import{decodeTime as Kc}from"ulid";import{z as no}from"zod";var zc=no.object({userId:no.string().min(1).default("unknown"),userName:no.string().min(1).default("unknown")}),Gc=e=>{let[t,n]=ro.basename(e,".jsonl").split("."),r=zc.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):a(`Invalid event file name ${ro.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},qc=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?a(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?a("Invalid persisted event: action key is missing or invalid"):c("Resolved persisted action",t[0])},Yc=(e,t)=>t in e,Xc=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Jc=e=>{let{userId:t,userName:n,...r}=e,o=qc(r);if(d(o))return a(o.message);let i=o.value,s=e.id?.[0];return s?Yc(r,i)?c("Decoded persisted event",Xc({id:s,action:i,payload:r[i],userId:t,userName:n})):a(`Persisted event is missing payload for action: ${i}`):a("Persisted event is missing id")},oo=e=>{let t=[];for(let n of e){let r=Jc(n);if(d(r))return a(`Failed to decode event ${n.id?.[0]??"<unknown>"}: ${r.message}`);t.push(r.value)}return c("Decoded reconstructed events",t)},Qc=e=>{if(!Hn.existsSync(e))return c("Event file missing",[]);let t=Gc(e);if(d(t))return a(t.message);let n=Hn.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
22
- `)){let i=o.trim();if(!i)continue;let s;try{s=JSON.parse(i)}catch{return a(`Failed to parse event JSON from ${e}: ${i}`)}let l=so(s);if(d(l))return a(`${l.message} in ${e}: ${i}`);r.push({...l.value,userId:t.value.userId,userName:t.value.userName})}return c("Parsed persisted events file",r)};function io(e){let t=Gt(e);if(!Hn.existsSync(t))return c("No events found",[]);let n=Hn.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>ro.join(t,o)),r=[];for(let o of n){let i=Qc(o);if(d(i))return a(i.message);r.push(...i.value)}return c("All events loaded",Zc(r))}function Lt(e){let t=io(e);return d(t)?a(t.message):oo(t.value)}function ts(e,t){let n=io(e);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=el(n.value,t),i=oo(r);if(d(i))return a(i.message);let s=oo(o);return d(s)?a(s.message):c("Loaded merged events before time",{appliedEvents:i.value,unappliedEvents:s.value})}function ns(e=process.cwd()){let t=io(e);return d(t)?a(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Zc=e=>{let t=new Map,n=new Map;for(let m of e){let g=m.id[0],y=m.id[1]??null;t.set(g,m);let C=n.get(y)??[];C.push(m),n.set(y,C)}for(let m of n.values())m.sort((g,y)=>g.id[0].localeCompare(y.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 y=n.get(g)??[];for(let C of y)i(C)},s=n.get(null)??[];for(let m of s)i(m);let l=e.filter(m=>{let g=m.id[0],y=m.id[1]??null;return!o.has(g)&&y!==null&&!t.has(y)}).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},el=(e,t)=>{let n=new Set,r=[],o=[];for(let i of e){let s=i.id[0],l=i.id[1],u=!1;try{u=Kc(s)<t}catch{u=!1}!u||l&&n.has(l)?(n.add(s),o.push(i)):r.push(i)}return{appliedEvents:r,unappliedEvents:o}};var rs=e=>({action:e.action,payload:e.payload});var is=1,os=ol(),il=rn.tuple([rn.string().min(1),rn.string().min(1).nullable()]),sl=rn.looseObject({v:rn.literal(is),id:il}),so=e=>{let t=sl.safeParse(e);return t.success?c("Parsed persisted event",t.data):a(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},jn=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",Y=()=>{let{userName:e,userId:t}=U();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:jn(t),userName:jn(e)}):a("Unable to resolve actor ID from settings or OS user info"):a("User ID not configured"):a("User name not configured")},on=({userId:e,userName:t})=>`${jn(e)}.${jn(t)}.jsonl`,al=(e,{userId:t,userName:n})=>{let r=on({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return a(`Invalid event log file name: ${r}`);let i=nl.join(Gt(e),r);return c("Successfully resolved event log path",i)},dl=(e,t)=>{let n={[e.action]:e.payload,v:is,id:t};return so(n)};function Vn({event:e,rootDir:t}){try{let n=ei(t);if(d(n))return n;let r=al(t,{userId:e.userId,userName:e.userName});if(d(r))return r;let o=ns(t);if(d(o))return a(o.message);let i=o.value?os(Math.max(Date.now(),rl(o.value)+1)):os(),s=dl(rs(e),[i,o.value]);return d(s)?a(s.message):(tl.appendFileSync(r.value,`${JSON.stringify(s.value)}
23
- `,"utf8"),c("Event persisted",{path:r.value,entry:s.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return a(`Failed to persist event: ${r}`)}}function Te(e,t){let n=tn(e);if(n.status!==qe.Success)return n;let r=Vn({event:e,rootDir:t});return d(r)?r:n}function ss(e,t){return e.map(n=>Te(n,t))}var Se=async e=>{let t=await Re();return d(t)?t:Te(e,t.value)};var as=e=>Kn(B(e),{at:"end"}),Kn=(e,t={at:"end"})=>{let n=r=>d(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)):a("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(me(r.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let r=ds(e,t.sibling);if(r<0)return a("Sibling not found");let o=r>0?e[r-1]:void 0,i=e[r];return i?n(me(o?.rank,i.rank)):a("Sibling not found")}case"after":{let r=ds(e,t.sibling);if(r<0)return a("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)):a("Sibling not found")}}},B=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),ds=(e,t)=>e.findIndex(n=>n.id===t),cs=(e,t,n={at:"end"})=>Kn(B(t).filter(r=>r.id!==e),n),ao=(e,t,n,r,o)=>{let i=cs(t,e,n);if(d(i))return i;if(!i.value.needsRebalance)return c("Resolved rank",i.value.rank);let s=Yr(e,r);if(d(s))return s;let l=Te(s.value,o);if(d(l))return l;let u=cs(t,e,n);return d(u)?u:u.value.needsRebalance?a("Rank rebalance failed to create space"):c("Resolved rank after rebalance",u.value.rank)},zn=(e,t,n)=>{let r=as(e);if(d(r))return r;if(!r.value.needsRebalance)return c("Resolved rank",r.value.rank);let o=Yr(e,t);if(d(o))return o;let i=Te(o.value,n);if(d(i))return i;let s=as(e);return d(s)?s:s.value.needsRebalance?a("Rank rebalance failed to create space"):c("Resolved rank after rebalance",s.value.rank)};var T={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=B(t.id)[n];!r||t.context==="FIELD"||T.navigate({contextNode:r,selectedIndex:_(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=_(n.id),o=r.findIndex(({id:s})=>s===e.id),i=r.length===0?-1:o>=0?o:0;T.navigate({contextNode:n,selectedIndex:i})},navigateToNextItem:()=>ls(1),navigateToPreviousItem:()=>ls(-1),navigateToNextContainer:()=>us(1),navigateToPreviousContainer:()=>us(-1),navigate:({contextNode:e,selectedIndex:t})=>{N({contextNodeId:e.id,selectedIndex:t})}},ls=e=>{let{selectedIndex:t,contextNode:n}=v(),r=_(n.id).length;if(r===0)return;let i=(Math.max(0,t)+e+r)%r;T.navigate({selectedIndex:i,contextNode:n})},us=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=_(o.id),s=i.findIndex(C=>C.id===t.id);if(s<0)return;let l=i.at(s+e)??i.at(0);if(!l)return;let u=_(l.id),m=Math.max(0,u.length-1),g=Math.min(Math.max(0,r),m),y=u.length?g:-1;T.navigate({contextNode:l,selectedIndex:y})};var ps=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),gs=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},cl=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&&tt(t)&&t.childRenderAxis==="vertical"},Gn=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=B(r.id);return T.navigate({contextNode:r,selectedIndex:ps(t,o.length)}),!0},fs=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Gn(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let s=B(o.id).findIndex(l=>l.id===n.id);return s>=0?(T.navigate({contextNode:o,selectedIndex:s}),!0):fs(o.id)},ms=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),fs(n))return!0;n=t[n]?.parentNodeId}return!1},ll=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},vs=e=>{let{nodes:t,rootNodeId:n}=v();if(cl(e.contextNodeId)&&Gn(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(ll(e.selectedNodeId)&&e.selectedNodeId&&ms(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(Gn(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&Gn(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(ms(e.contextNodeId))return c("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return a("Unable to restore navigation");let o=B(r.id);return T.navigate({contextNode:r,selectedIndex:ps(e.selectedIndex,o.length)}),c("Restored navigation to root",null)};import{monotonicFactory as ul,ulid as je}from"ulid";var sn=ul();function ml(){let e=ot();if(d(e))return a("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]=_(n.id),[o]=r?_(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 pl(){let e=ml();return d(e)?e:T.navigate(e.value)}function xs({userId:e,userName:t}){let n=sn(),r=sn(),o=sn(),i=sn(),s=sn(),l=me(void 0,void 0);if(d(l))return l;let u=me(void 0,void 0);if(d(u))return u;let m=me(u.value,void 0);if(d(m))return m;let g=me(void 0,void 0);if(d(g))return g;let y=me(g.value,void 0);if(d(y))return y;let C=me(y.value,void 0);if(d(C))return C;let I=me(void 0,void 0);return d(I)?I:c("Created default events",[{id:je(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:je(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:je(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:g.value}},{id:je(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"In progress",parent:r,rank:y.value}},{id:je(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"Done",parent:r,rank:C.value}},{id:je(),userId:e,userName:t,action:"add.board",payload:{id:Wn,name:"Closed",parent:n,rank:m.value}},{id:je(),userId:e,userName:t,action:"add.swimlane",payload:{id:He,name:"Closed",parent:Wn,rank:I.value}},{id:je(),userId:e,userName:t,action:"lock.node",payload:{id:Wn}},{id:je(),userId:e,userName:t,action:"lock.node",payload:{id:He}}])}function qn(e){if(!e.length){let r=q.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=nn(r);return d(o)?o:(N({hasProjectDefinition:!1,mode:p.DEFAULT}),c("Booted uninitialized workspace placeholder",null))}if(!e.some(r=>r.action==="init.workspace"))return a("Initialized Epiq project has no workspace init event");let n=ht(e).filter(d);return n.length>0?a(`Materializing failed:
19
+ `).filter(Boolean).filter(s=>s!==_e);if(r.length===0)return c("State branch is storage-only",!1);let o=await k({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return a(`Failed to clean storage branch
20
+ ${o.message}`);let i=await wt({cwd:e,message:"[epiq:repair-storage-branch]"});return d(i)?a(i.message):c("Cleaned storage branch",!0)},Je=$r(async(e=process.cwd())=>{let t=await k({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?a("Not inside a Git repository"):c("Resolved repo root",t.value.stdout.trim())},e=>Le.resolve(e)),pg=$r(async e=>{let t=await k({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return a(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{Box as gt}from"ink";import z from"react";import{useSyncExternalStore as oc}from"react";var Zt={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Yr=new Set,ic=()=>{for(let e of Yr)e()},$=()=>Zt,bi=()=>oc(e=>(Yr.add(e),()=>{Yr.delete(e)}),()=>Zt),Ce=e=>(Zt={...Zt,...e},ic(),Zt);var Ze=()=>{let e=$(),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}},Si=()=>{let e=Ye(process.cwd());if(d(e))return!1;let t=Qe(e.value);return J(t)},Ii=e=>e===!0?"on":e===!1?"off":null,Ri=e=>e==="on"?!0:e==="off"?!1:null;var p={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var Ee=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?c("Found node",n):a("Unable to find node in breadcrumb")};import{useSyncExternalStore as gm}from"react";var w={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function Xr(e){return e.context===w.WORKSPACE}function B(e){return e.context===w.TICKET}function et(e){return e.context===w.TEXT}function tt(e){return e.context===w.FIELD}function en(e){return e.context===w.FIELD_LIST}var Mt=e=>e.context===w.SWIMLANE,Ai=e=>e.context===w.BOARD;var Ti=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",wi=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",Mi=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Pi=(e,t)=>{if(wi(e,e.sequence))return f.MoveCursorLeftOfWord;if(Mi(e,e.sequence))return f.MoveCursorRightOfWord;if(Ti(e,e.sequence))return f.EraseInputWord;switch(e.name){case"tab":return f.AutoCompleteCommand;case"up":return f.GetLastCommandFromHistory;case"down":return f.GetNextCommandFromHistory;case"left":return f.MoveCursorLeft;case"right":return f.MoveCursorRight;case"return":return f.Confirm;case"backspace":return t?f.EraseInput:f.ExitCommandLine;case"escape":return f.ExitCommandLine;default:return f.CaptureInput}},Li=(e,t)=>{if(wi(e,e.sequence))return f.MoveCursorLeftOfWord;if(Mi(e,e.sequence))return f.MoveCursorRightOfWord;if(Ti(e,e.sequence))return f.EraseInputWord;switch(e.name){case"tab":return f.AutoCompleteCommand;case"up":return f.NavPreviousItem;case"down":return f.NavNextItem;case"left":return f.MoveCursorLeft;case"right":return f.MoveCursorRight;case"return":return f.Confirm;case"backspace":return t?f.EraseInput:f.ExitCommandLine;case"escape":return f.ExitCommandLine;default:return f.CaptureInput}};function Un(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var $n=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",ki=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Di=e=>e.charAt(0).toUpperCase()+e.slice(1);var Fi=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},Oi=(e,t)=>t?e.get(t)??[]:[];var Bi=new WeakMap,sc=e=>{let t=Bi.get(e);return t||(t=Fi(e),Bi.set(e,t)),t};var Ui=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Oi(sc(e),r).filter(i=>Un(r,i)>=n)};var ac={hint:"",hints:[],overlap:0,remainder:""},$i=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return ac;let o=Ui({wordList:r,inputToMatch:e,overlapThreshold:1});return dc(t,o)},dc=(e,t)=>{let n=t[0]??"",r=Un(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),s=r<(o??"").length,l=!!i,g=(l&&s?o:n)+(l&&s?":":" "),h=g.slice(r);return{hint:g,hints:t,overlap:r,remainder:h}};import{ulid as uc}from"ulid";var Pt=24n,cc=Pt*4n,We=(1n<<cc)-1n,lc=/^[0-9a-f]+$/;function _i(e){return!e||!lc.test(e)?a(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Ae(e,t=Pt){if(e<0n)return a("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 Ae(We/2n,Pt);let n=e?_i(e):c("Resolved lower bound",0n);if(d(n))return n;let r=t?_i(t):c("Resolved upper bound",We);if(d(r))return r;let o=n.value,i=r.value;if(i<=o)return Ae(We/2n,Pt);let s=(o+i)/2n;return s===o||s===i?a("No rank space available between neighbors"):Ae(s,Pt)}function Wi(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=We*BigInt(r+1)/(t+1n),i=Ae(o,Pt);if(d(i))return i;n.push(i.value)}return c("Resolved evenly spaced ranks",n)}var Jr=(e,t)=>{let n=U(e),r=Wi(n.length);if(d(r))return r;let o={};for(let i=0;i<n.length;i++){let s=n[i],l=r.value[i];if(!s||!l)return a("Unable to assign rebalance rank");o[s.id]=l}return c("Created rebalance event",{id:uc(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var Q={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History"};var nt=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return a("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 a(`No ancestor found for context: ${t}`)},Qr=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},vt=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:a("Node not found"),b={deleteNode(e){Ne(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 a("Edit target node not found");let o=vt(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 a("Rename target node not found");let r=vt(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 U(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 a("Node not found");if(!i)return a("Target parent not found");if(r===e)return a("Cannot move root node");if(e===t)return a("Cannot move node into itself");let s=vt(o,"move");if(s)return s;if(Qr(t,e))return a("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 a("Node not found");if(r===e)return a("Cannot delete root node");let i=new Set,s=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let g of U(m.id))s(g.id)}};s(e);let l={...structuredClone(t)};for(let u of i){if(!l[u])return a("Unable to locate node to delete");l[u]={...l[u],isDeleted:!0}}return n?(N({nodes:l}),c("Successfully tomb stoned",o)):a("Unable to delete undefined")},createContributor(e){let t=Ne(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):c("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to assign contributor, missing contributor");if(!r)return a("Unable to assign contributor, missing target");let o=vt(r,"edit");if(o)return o;if(!B(r))return a("Target is not an issue");let i=r.props.assignees??[];if(i.includes(t))return a("Contributor already assigned");let s={...r,props:{...r.props,assignees:[...i,t]}};return this.updateNode(s),c("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to unassign, missing contributor");if(!r)return a("Unable to unassign, missing target");let o=vt(r,"edit");if(o)return o;if(!B(r))return a("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 s={...r,props:{...r.props,assignees:i.filter(l=>l!==t)}};return this.updateNode(s),c("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to add tag, missing tag");if(!r)return a("Unable to add tag, missing target");let o=vt(r,"edit");if(o)return o;if(!B(r))return a("Target is not an issue");let i=r.props.tags??[];if(i.includes(t))return a("Tag already assigned");let s={...r,props:{...r.props,tags:[...i,t]}};return this.updateNode(s),c("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to remove tag, missing tag");if(!r)return a("Unable to remove tag, missing target");let o=vt(r,"edit");if(o)return o;if(!B(r))return a("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 s={...r,props:{...r.props,tags:i.filter(l=>l!==t)}};return this.updateNode(s),c("Tag removed",{tag:t})},createTag(e){let t=Ne(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):c("Tag created",e)},createNode(e){let t=Ne(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?a("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=Ne(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):c("Locked node",n)},updateNode(e){let t=Ne(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(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 U(e)}};var q={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:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:w.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),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:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:w.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[],isVirtual:s})};import ht from"chalk";import Ji from"string-width";import{decodeTime as Ec}from"ulid";import Lt from"chalk";var oe={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"},y={accent:oe.cyan,accent2:oe.magenta,primary:oe.white,secondary:oe.grayDark,secondary2:oe.grayLight,gray:oe.gray,green:oe.green,yellow:oe.yellow,red:oe.red};var C={red:oe.red,yellow:oe.yellow,green:oe.green,blue:oe.blue,magenta:oe.magenta,cyan:oe.cyan},xt={urgent:C.red,critical:C.red,important:C.red,blocker:C.red,asap:C.red,immediate:C.red,fail:C.red,failure:C.red,broken:C.red,bug:C.red,error:C.red,incident:C.red,outage:C.red,production:C.red,crash:C.red,security:C.red,warning:C.yellow,warn:C.yellow,risky:C.yellow,risk:C.yellow,attention:C.yellow,pending:C.yellow,review:C.yellow,"needs-review":C.yellow,qa:C.yellow,testing:C.yellow,test:C.yellow,validate:C.yellow,verification:C.yellow,staging:C.yellow,check:C.yellow,"follow-up":C.yellow,followup:C.yellow,waiting:C.yellow,blocked:C.yellow,hold:C.yellow,done:C.green,complete:C.green,completed:C.green,success:C.green,ok:C.green,stable:C.green,resolved:C.green,fixed:C.green,closed:C.green,merged:C.green,released:C.green,deployed:C.green,approved:C.green,verified:C.green,working:C.green,healthy:C.green,pass:C.green,passing:C.green,info:C.blue,information:C.blue,note:C.blue,docs:C.blue,documentation:C.blue,doc:C.blue,guide:C.blue,help:C.blue,explanation:C.blue,detail:C.blue,details:C.blue,context:C.blue,design:C.blue,discussion:C.blue,proposal:C.blue,idea:C.blue,feature:C.magenta,enhancement:C.magenta,improvement:C.magenta,refactor:C.magenta,refactoring:C.magenta,cleanup:C.magenta,optimize:C.magenta,optimization:C.magenta,perf:C.magenta,performance:C.magenta,upgrade:C.magenta,migration:C.magenta,modernize:C.magenta,debt:C.magenta,todo:C.cyan,next:C.cyan,planned:C.cyan,plan:C.cyan,future:C.cyan,backlog:C.cyan,investigate:C.cyan,explore:C.cyan,prototype:C.cyan};var mc=[0,0,0],to=.2,eo={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Hi=(e,t,n)=>Math.max(t,Math.min(n,e)),Zr=(e,t,n)=>e+(t-e)*n,ji=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},pc=e=>e.toLowerCase().trim(),gc=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,s=e/60,l=i*(1-Math.abs(s%2-1)),u=0,m=0,g=0;s>=0&&s<1?(u=i,m=l):s>=1&&s<2?(u=l,m=i):s>=2&&s<3?(m=i,g=l):s>=3&&s<4?(m=l,g=i):s>=4&&s<5?(u=l,g=i):(u=i,g=l);let h=o-i/2;return[Math.round((u+h)*255),Math.round((m+h)*255),Math.round((g+h)*255)]},Vi=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,fc=e=>{let t=e.replace("#","");return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]},Ki=(e,t,n)=>{let r=Hi(n,0,1);return[Math.round(Zr(e[0],t[0],r)),Math.round(Zr(e[1],t[1],r)),Math.round(Zr(e[2],t[2],r))]},vc=(e,t=to)=>Ki(e,mc,t),xc=(e,t=to)=>Vi(vc(fc(e),t)),hc=(e,t,n)=>Ki(e,t,n),tn=e=>{let n=ji(e)%360,r=gc(n,eo.stringColor.saturation,eo.stringColor.lightness);return Vi(r)},be=(e,t=xt)=>{let n=pc(e);return n&&t[n]?t[n]:tn(n)},zi=(e,t=xt,n=to)=>xc(be(e,t),n),yc=e=>{let t=eo.gradient.stops,n=Hi(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),s=o-i;return hc(t[i],t[i+1],s)},_n=e=>ji(e.toLowerCase().trim())/4294967295,Gi=e=>{let t=_n(e);return yc(t)},Cc=e=>{let[t,n,r]=Gi(e);return{normal:o=>Lt.bgRgb(t,n,r).black(o),cursor:o=>Lt.bgRgb(t,n,r).white.bold(o)}},no=e=>{let[t,n,r]=Gi(e);return{fg:o=>Lt.rgb(t,n,r)(o),fgCursor:o=>Lt.rgb(t,n,r).inverse(o),bg:o=>Lt.bgRgb(t,n,r).black(o),bgCursor:o=>Lt.bgRgb(t,n,r).white.bold(o)}},Wn=e=>Cc(e).normal(` ${e} `);import{decodeTime as qi}from"ulid";var Yi=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"},Xi=e=>{let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},Hn=e=>{try{return c("Decoded date",new Date(qi(e)))}catch(t){return a("Decoding failed + "+t.message)}},ro=e=>{if(!e?.id)return null;try{return qi(e.id)}catch{return null}};var Nc=(e,t)=>e+" ".repeat(Math.max(0,t-Ji(e))),bc=(e,t)=>" ".repeat(Math.max(0,t-Ji(e)))+e,Sc=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`),Ic=(e,t)=>t?e<t?"up":e>t?"down":null:null,Rc=(e,t)=>{let n=b.getNode(e.payload.parent),r=n?ht.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let i=Ic(e.payload.rank,o.rank);if(i)return`Moved ${i} in ${r}`}return`Moved issue to ${r}`},Ac=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?ht.bgHex(be(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?ht.bgHex(be(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?ht.hex(be(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?ht.hex(be(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""}},Tc=e=>{let t=Yi(Ec(e));return ht.gray(bc(t,8))},wc=12,Mc=e=>Nc(`${e}`,wc),Qi=(e,t)=>{let n=Tc(e.id),r=Mc(e.userName),o=ht.dim("\u203A"),i=e.action==="move.node"?Rc(e,t):[Sc(e.action),Ac(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${i}`};import{createHash as Pc}from"node:crypto";var Lc="0123456789ABCDEFGHJKMNPQRSTVWXYZ",kc=e=>{let t=Pc("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+=Lc[Number(n>>i&31n)]}return r},rt=(e,t)=>kc(`${e}:virtual:${t}`);var Dc=e=>rt(e,"description"),Fc=e=>rt(e,"assignees"),Oc=e=>rt(e,"tags"),Bc=e=>rt(e,"history"),Zi=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:i=!1,childRenderAxis:s="horizontal"})=>{let l=b.getNode(e);if(!l){let g=b.createNode({...q.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:i,childRenderAxis:s});return d(g)?g:c("Virtual field created",void 0)}if(!tt(l))return a(`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!==s))return c("Virtual field unchanged",void 0);let m=b.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:i,childRenderAxis:s});return d(m)?m:c("Virtual field updated",void 0)},es=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:i="horizontal"})=>{let s=b.getNode(e);if(!s){let m=b.createNode({...q.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:i});return d(m)?m:c("Virtual field list created",void 0)}if(!en(s))return a(`Existing virtual node ${e} is not a field list`);if(!(s.title!==t||s.parentNodeId!==n||s.rank!==r||s.readonly!==o||s.childRenderAxis!==i))return c("Virtual field list unchanged",void 0);let u=b.updateNode({...s,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:i});return d(u)?u:c("Virtual field list updated",void 0)},ts=e=>{let t=Ae(We/4n),n=Ae(We/2n),r=Ae(We*3n/4n),o=Ae(We*7n/8n);if(d(t))return t;if(d(n))return n;if(d(r))return r;if(d(o))return o;let i=Zi({id:Dc(e.id),name:Q.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(i))return i;let s=es({id:Fc(e.id),name:Q.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(s))return s;let l=es({id:Oc(e.id),name:Q.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(l))return l;let u=Zi({id:Bc(e.id),name:Q.HISTORY,parentNodeId:e.id,rank:o.value,value:Uc(e),readonly:!0,childRenderAxis:"vertical"});return d(u)?u:c("Ticket virtual nodes materialized",void 0)},Uc=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=>Qi(r,n.get(r.action)??[])).join(`
21
+ `)};var $c=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[He,jn]=$c;var L=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),ns=e=>{let t=b.getNode(e);if(!t||!B(t)||t.isDeleted)return null;let n=ts(t);return d(n)?n:null},_c=e=>{for(let t of e){let n=ns(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=ns(r);if(o)return o}return null},Wc=(e,t)=>{let n=b.getNode(e);n&&b.updateNode({...n,log:[...n.log??[],t]})},Hc=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},jc=e=>{switch(e.action){case"delete.node":case"edit.description":return Hc(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[]}},Vc=e=>{Ne(t=>({...t,eventLog:[...t.eventLog,e]}))},Kc=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?L("Invalid user ID format",e):c("Valid user",null)},zc=(e,t)=>{let n=Kc(e);if(d(n))return n;let r=[...new Set(jc(e))];t||(r.forEach(i=>Wc(i,e)),Vc(e));let o=_c(r);return o||null},Gc={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=q.workspace(t,n,r),i=rn(o);if(d(i))return L(i.message,e);let s=b.createNode(o);return d(s)?L(s.message??"Failed to initialize workspace",e):Xr(s.value)?c("Workspace initialized",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=b.createNode(q.workspace(t,n,r));return d(o)?L(o.message??"Failed to add workspace",e):Xr(o.value)?c("Added workspace",{action:e.action,result:o.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=b.createNode(q.board(t,n,r,o));return d(i)?L(i.message??"Unable to create board",e):Ai(i.value)?c("Added board",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=b.createNode(q.swimlane(t,n,r,o));return d(i)?L(i.message??"Unable to create swimlane",e):Mt(i.value)?c("Added swimlane",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=b.createNode(q.ticket(t,n,r,o));return d(i)?L(i.message??"Unable to create issue",e):B(i.value)?c("Added issue",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:i}=e.payload,s=b.createNode(q.field({id:t,name:n,parentNodeId:r,rank:i,props:{value:o},childRenderAxis:n.includes(Q.DESCRIPTION)?"vertical":"horizontal"}));return d(s)?L(s.message??`Unable to create field: ${n}`,e):tt(s.value)?c("Added field",{action:e.action,result:s.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!b.getNode(t))return L(`Unable to locate node with id ${t}`,e);let o=b.renameNode(t,n);return d(o)?L(o.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=b.tombstoneNode(t);return d(n)?L(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=b.createTag({id:t,name:n});return d(r)?L(r.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=b.createContributor({id:t,name:n});return d(r)?L(r.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=b.tag(t,n);return d(r)?L(r.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=b.untag(t,n);return d(r)?L(r.message??"Unable to untag issue",e):c("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=b.assign(t,n);return d(r)?L(r.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=b.unassign(t,n);return d(r)?L(r.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?L(o.message??"Failed to move node",e):c("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=b.editValue(t,n);return d(r)?L(r.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return L("Unable to locate issue",e);if(!B(o))return L("Can only close issues",e);let i=b.getNode(He);if(!i)return L("Unable to locate target swimlane",e);if(n!==i.id)return L("Close target must be closed swimlane",e);let s=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(s)?L(s.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return L("Unable to locate issue",e);if(!B(o))return L("Can only reopen issues",e);let i=b.getNode(He);if(!i)return L("Unable to locate closed swimlane",e);if(n===i.id)return L("Cannot reopen issue into closed swimlane",e);if(!b.getNode(n))return L("Reopen parent no longer exists",e);let l=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(l)?L(l.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=b.lockNode(t);return d(n)?L(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=b.getNode(r);if(!i)return L(`Unable to locate node ${r}`,e);if(i.parentNodeId!==t)return L(`Node ${r} is not child of ${t}`,e);let s=b.updateNode({...i,rank:o});if(d(s))return L(s.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})}};function nn(e,t=!1){let n=Gc[e.action](e);if(d(n))return n;let r=zc(e,t);return r||n}var yt=e=>e.map(t=>nn(t));import ol from"node:fs";import il from"node:path";import{decodeTime as sl,monotonicFactory as al}from"ulid";import{z as on}from"zod";import Vn from"node:fs";import io from"node:path";import{decodeTime as qc}from"ulid";import{z as oo}from"zod";var Yc=oo.object({userId:oo.string().min(1).default("unknown"),userName:oo.string().min(1).default("unknown")}),Xc=e=>{let[t,n]=io.basename(e,".jsonl").split("."),r=Yc.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):a(`Invalid event file name ${io.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Jc=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?a(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?a("Invalid persisted event: action key is missing or invalid"):c("Resolved persisted action",t[0])},Qc=(e,t)=>t in e,Zc=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),el=e=>{let{userId:t,userName:n,...r}=e,o=Jc(r);if(d(o))return a(o.message);let i=o.value,s=e.id?.[0];return s?Qc(r,i)?c("Decoded persisted event",Zc({id:s,action:i,payload:r[i],userId:t,userName:n})):a(`Persisted event is missing payload for action: ${i}`):a("Persisted event is missing id")},so=e=>{let t=[];for(let n of e){let r=el(n);if(d(r))return a(`Failed to decode event ${n.id?.[0]??"<unknown>"}: ${r.message}`);t.push(r.value)}return c("Decoded reconstructed events",t)},tl=e=>{if(!Vn.existsSync(e))return c("Event file missing",[]);let t=Xc(e);if(d(t))return a(t.message);let n=Vn.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
22
+ `)){let i=o.trim();if(!i)continue;let s;try{s=JSON.parse(i)}catch{return a(`Failed to parse event JSON from ${e}: ${i}`)}let l=co(s);if(d(l))return a(`${l.message} in ${e}: ${i}`);r.push({...l.value,userId:t.value.userId,userName:t.value.userName})}return c("Parsed persisted events file",r)};function ao(e){let t=qt(e);if(!Vn.existsSync(t))return c("No events found",[]);let n=Vn.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>io.join(t,o)),r=[];for(let o of n){let i=tl(o);if(d(i))return a(i.message);r.push(...i.value)}return c("All events loaded",nl(r))}function kt(e){let t=ao(e);return d(t)?a(t.message):so(t.value)}function rs(e,t){let n=ao(e);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=rl(n.value,t),i=so(r);if(d(i))return a(i.message);let s=so(o);return d(s)?a(s.message):c("Loaded merged events before time",{appliedEvents:i.value,unappliedEvents:s.value})}function os(e=process.cwd()){let t=ao(e);return d(t)?a(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var nl=e=>{let t=new Map,n=new Map;for(let m of e){let g=m.id[0],h=m.id[1]??null;t.set(g,m);let E=n.get(h)??[];E.push(m),n.set(h,E)}for(let m of n.values())m.sort((g,h)=>g.id[0].localeCompare(h.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 h=n.get(g)??[];for(let E of h)i(E)},s=n.get(null)??[];for(let m of s)i(m);let l=e.filter(m=>{let g=m.id[0],h=m.id[1]??null;return!o.has(g)&&h!==null&&!t.has(h)}).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},rl=(e,t)=>{let n=new Set,r=[],o=[];for(let i of e){let s=i.id[0],l=i.id[1],u=!1;try{u=qc(s)<t}catch{u=!1}!u||l&&n.has(l)?(n.add(s),o.push(i)):r.push(i)}return{appliedEvents:r,unappliedEvents:o}};var is=e=>({action:e.action,payload:e.payload});var as=1,ss=al(),dl=on.tuple([on.string().min(1),on.string().min(1).nullable()]),cl=on.looseObject({v:on.literal(as),id:dl}),co=e=>{let t=cl.safeParse(e);return t.success?c("Parsed persisted event",t.data):a(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Kn=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",Y=()=>{let{userName:e,userId:t}=$();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:Kn(t),userName:Kn(e)}):a("Unable to resolve actor ID from settings or OS user info"):a("User ID not configured"):a("User name not configured")},sn=({userId:e,userName:t})=>`${Kn(e)}.${Kn(t)}.jsonl`,ll=(e,{userId:t,userName:n})=>{let r=sn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return a(`Invalid event log file name: ${r}`);let i=il.join(qt(e),r);return c("Successfully resolved event log path",i)},ul=(e,t)=>{let n={[e.action]:e.payload,v:as,id:t};return co(n)};function zn({event:e,rootDir:t}){try{let n=ri(t);if(d(n))return n;let r=ll(t,{userId:e.userId,userName:e.userName});if(d(r))return r;let o=os(t);if(d(o))return a(o.message);let i=o.value?ss(Math.max(Date.now(),sl(o.value)+1)):ss(),s=ul(is(e),[i,o.value]);return d(s)?a(s.message):(ol.appendFileSync(r.value,`${JSON.stringify(s.value)}
23
+ `,"utf8"),c("Event persisted",{path:r.value,entry:s.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return a(`Failed to persist event: ${r}`)}}function Te(e,t){let n=nn(e);if(n.status!==qe.Success)return n;let r=zn({event:e,rootDir:t});return d(r)?r:n}function ds(e,t){return e.map(n=>Te(n,t))}var Se=async e=>{let t=await Re();return d(t)?t:Te(e,t.value)};var cs=e=>Gn(U(e),{at:"end"}),Gn=(e,t={at:"end"})=>{let n=r=>d(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)):a("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(me(r.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let r=ls(e,t.sibling);if(r<0)return a("Sibling not found");let o=r>0?e[r-1]:void 0,i=e[r];return i?n(me(o?.rank,i.rank)):a("Sibling not found")}case"after":{let r=ls(e,t.sibling);if(r<0)return a("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)):a("Sibling not found")}}},U=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),ls=(e,t)=>e.findIndex(n=>n.id===t),us=(e,t,n={at:"end"})=>Gn(U(t).filter(r=>r.id!==e),n),lo=(e,t,n,r,o)=>{let i=us(t,e,n);if(d(i))return i;if(!i.value.needsRebalance)return c("Resolved rank",i.value.rank);let s=Jr(e,r);if(d(s))return s;let l=Te(s.value,o);if(d(l))return l;let u=us(t,e,n);return d(u)?u:u.value.needsRebalance?a("Rank rebalance failed to create space"):c("Resolved rank after rebalance",u.value.rank)},qn=(e,t,n)=>{let r=cs(e);if(d(r))return r;if(!r.value.needsRebalance)return c("Resolved rank",r.value.rank);let o=Jr(e,t);if(d(o))return o;let i=Te(o.value,n);if(d(i))return i;let s=cs(e);return d(s)?s:s.value.needsRebalance?a("Rank rebalance failed to create space"):c("Resolved rank after rebalance",s.value.rank)};var T={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=U(t.id)[n];!r||t.context==="FIELD"||T.navigate({contextNode:r,selectedIndex:_(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=_(n.id),o=r.findIndex(({id:s})=>s===e.id),i=r.length===0?-1:o>=0?o:0;T.navigate({contextNode:n,selectedIndex:i})},navigateToNextItem:()=>ms(1),navigateToPreviousItem:()=>ms(-1),navigateToNextContainer:()=>ps(1),navigateToPreviousContainer:()=>ps(-1),navigate:({contextNode:e,selectedIndex:t})=>{N({contextNodeId:e.id,selectedIndex:t})}},ms=e=>{let{selectedIndex:t,contextNode:n}=v(),r=_(n.id).length;if(r===0)return;let i=(Math.max(0,t)+e+r)%r;T.navigate({selectedIndex:i,contextNode:n})},ps=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=_(o.id),s=i.findIndex(E=>E.id===t.id);if(s<0)return;let l=i.at(s+e)??i.at(0);if(!l)return;let u=_(l.id),m=Math.max(0,u.length-1),g=Math.min(Math.max(0,r),m),h=u.length?g:-1;T.navigate({contextNode:l,selectedIndex:h})};var fs=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),vs=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},ml=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&&tt(t)&&t.childRenderAxis==="vertical"},Yn=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=U(r.id);return T.navigate({contextNode:r,selectedIndex:fs(t,o.length)}),!0},xs=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Yn(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let s=U(o.id).findIndex(l=>l.id===n.id);return s>=0?(T.navigate({contextNode:o,selectedIndex:s}),!0):xs(o.id)},gs=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),xs(n))return!0;n=t[n]?.parentNodeId}return!1},pl=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},hs=e=>{let{nodes:t,rootNodeId:n}=v();if(ml(e.contextNodeId)&&Yn(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(pl(e.selectedNodeId)&&e.selectedNodeId&&gs(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(Yn(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&Yn(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(gs(e.contextNodeId))return c("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return a("Unable to restore navigation");let o=U(r.id);return T.navigate({contextNode:r,selectedIndex:fs(e.selectedIndex,o.length)}),c("Restored navigation to root",null)};import{monotonicFactory as gl,ulid as je}from"ulid";var an=gl();function fl(){let e=ot();if(d(e))return a("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]=_(n.id),[o]=r?_(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 vl(){let e=fl();return d(e)?e:T.navigate(e.value)}function ys({userId:e,userName:t}){let n=an(),r=an(),o=an(),i=an(),s=an(),l=me(void 0,void 0);if(d(l))return l;let u=me(void 0,void 0);if(d(u))return u;let m=me(u.value,void 0);if(d(m))return m;let g=me(void 0,void 0);if(d(g))return g;let h=me(g.value,void 0);if(d(h))return h;let E=me(h.value,void 0);if(d(E))return E;let I=me(void 0,void 0);return d(I)?I:c("Created default events",[{id:je(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:je(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:je(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:g.value}},{id:je(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"In progress",parent:r,rank:h.value}},{id:je(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"Done",parent:r,rank:E.value}},{id:je(),userId:e,userName:t,action:"add.board",payload:{id:jn,name:"Closed",parent:n,rank:m.value}},{id:je(),userId:e,userName:t,action:"add.swimlane",payload:{id:He,name:"Closed",parent:jn,rank:I.value}},{id:je(),userId:e,userName:t,action:"lock.node",payload:{id:jn}},{id:je(),userId:e,userName:t,action:"lock.node",payload:{id:He}}])}function Xn(e){if(!e.length){let r=q.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=rn(r);return d(o)?o:(N({hasProjectDefinition:!1,mode:p.DEFAULT}),c("Booted uninitialized workspace placeholder",null))}if(!e.some(r=>r.action==="init.workspace"))return a("Initialized Epiq project has no workspace init event");let n=yt(e).filter(d);return n.length>0?a(`Materializing failed:
24
24
  ${n.map(r=>r.message).join(`
25
- `)}`):(pl(),N({hasProjectDefinition:!0}),c("State booted successfully",null))}var kt=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),co=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}},W=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);var lo=({status:e,msg:t})=>{Dt()&&N({syncStatus:{status:e,msg:t}})},ys=(e="Syncing...")=>{lo({status:"syncing",msg:e})},hs=(e="Synced")=>{lo({status:"synced",msg:e})},gl=e=>{lo({status:"failed",msg:e})},ke=e=>(gl(e),a(e));import Ft from"node:fs";import an from"node:path";var Cs=async e=>{if((await Pe({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);ae.info("Creating initial commit");let n=await G.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?a(n.message):c("Created initial commit",!0)},Es=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",fl=async e=>{let t=await kn(e);if(d(t))return a(t.message);let n=await ui(e);return d(n)?a(n.message):c("Built sync commit message",`[sync|branch:${Es(t.value)}:sha:${Es(n.value)}]`)},uo=async({repoRoot:e,stateBranchName:t})=>{ae.info(`Creating ${t}`);let n=await D({args:["commit-tree",vi,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return a(`Failed to create state branch commit
26
- ${n.message}`);let r=n.value.stdout.trim(),o=await D({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return d(o)?a(`Failed to create ${t}
27
- ${o.message}`):c("Created state branch",!0)},vl=async({repoRoot:e,stateBranchName:t})=>{let n=await Hr({repoRoot:e});if(d(n))return a(`Ensure local state branch failed
28
- `+n.message);let r=n.value,o=r?await Pn({repoRoot:e,branch:t}):c("No remote, no remote state branch",!1);if(d(o))return a(`Ensure local state branch failed
29
- `+o.message);let i=o.value;if(r&&i){let l=await G.fetch({cwd:e,remote:he,branch:t});if(d(l))return a(`Failed to fetch ${t} from remote
30
- ${l.message}`)}let s=await Ln({repoRoot:e,branch:t});if(d(s))return a(`Ensure local state branch failed
31
- `+s.message);if(s.value)return c("Local state branch already exists",!1);if(i){let l=await D({args:["branch","--track",t,`${he}/${t}`],cwd:e});return d(l)?a(`Failed to create local ${t} from remote
32
- ${l.message}`):c("Created local state branch from remote",!0)}return uo({repoRoot:e,stateBranchName:t})},xl=async({repoRoot:e,branch:t})=>{let n=await D({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=n.value.stdout.split(`
33
- `),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)},yl=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Jt(an.dirname(t));if(d(r))return a(`Failed to create state branch worktree
34
- `+r.message);Ft.existsSync(t)&&!Ft.existsSync(an.join(t,".git"))&&(ae.info("Removing broken state branch worktree path"),yi(t)),ae.info("Creating state branch worktree");let o=await G.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(o)?a(`Failed to create state branch worktree
35
- ${o.message}`):c("Created state branch worktree",!0)},mo=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await xl({repoRoot:e,branch:n});if(d(r))return a(r.message);let o=an.resolve(t),i=r.value?an.resolve(r.value):null;if(i&&i===o&&Ft.existsSync(i))return c("State branch already checked out in expected worktree",!1);if(i&&i!==o){ae.info("Moving state branch worktree to expected location");let u=await G.worktreeRemove({cwd:e,worktreeRoot:i});if(d(u))return a(`Failed to remove existing state branch worktree
36
- ${u.message}`)}if(i&&!Ft.existsSync(i)){ae.info("Pruning stale state branch worktree");let u=await G.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
37
- ${u.message}`)}let s=await li({repoRoot:e,worktreeRoot:t});if(d(s))return a(s.message);let l=Ft.existsSync(t);if(s.value&&l)return c("State branch worktree already exists",!1);if(s.value&&!l){ae.info("Pruning missing registered state branch worktree");let u=await G.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
38
- ${u.message}`)}return yl({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},hl=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await kn(e);if(d(n))return a(n.message);if(n.value===t)return c("State branch already checked out",!1);(await Pe({cwd:e,args:["rebase","--abort"]})).exitCode===0&&ae.info("Aborted stale state branch rebase");let o=await G.checkout({cwd:e,branch:t});return d(o)?a(`Failed to checkout ${t}
39
- ${o.message}`):c("Checked out state branch",!0)},El=async({repoRoot:e,stateBranchRoot:t})=>{let n=await jr(t);if(d(n))return a(n.message);if(n.value)return c("State branch upstream already configured",!1);let r=await Hr({repoRoot:t});if(d(r))return a(r.message);if(!r.value)return c("No remote available for state branch upstream",!1);let o=At(e);if(d(o))return o;let i=o.value,s=await Pn({repoRoot:t,branch:i});if(d(s))return a(s.message);if(!s.value)return c("Remote state branch missing; upstream will be configured on first push",!1);ae.info(`Configuring ${i} upstream`);let l=await G.fetch({cwd:t,remote:he,branch:i});if(d(l))return a(`Failed to fetch ${i}
40
- ${l.message}`);let u=await G.setUpstream({cwd:t,branch:i,upstream:`${he}/${i}`});return d(u)?a(`Failed to set state branch upstream
41
- ${u.message}`):c("Configured state branch upstream",!0)},Yn=async({stateBranchRoot:e,eventFileName:t})=>{let n=zr(t),r=an.join(e,n);if(!Ft.existsSync(r))return c("No event file to stage",void 0);let o=await G.stage({cwd:e,pathspec:[n]});return d(o)?a(`Failed to stage state branch event file
42
- ${o.message}`):c("Staged state branch event file",void 0)},Ns=async({repoRoot:e,stateBranchRoot:t})=>{let n=await fl(e);return d(n)?a(`Create state branch sync commit failed
43
- `+n.message):Tt({cwd:t,message:n.value})},dn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await jr(t);if(d(n))return a(n.message);let r=At(e);if(d(r))return r;let o=r.value,i=n.value?await G.push({cwd:t}):await G.push({cwd:t,remote:he,branch:o,setUpstream:!0});return d(i)?a(`Failed during state branch push
44
- ${i.message}`):c("Pushed state branch",!0)},bs=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=At(e);if(d(o))return o;let i=o.value,s=[Fn(),await vl({repoRoot:e,stateBranchName:i}),await mo({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await hl({stateBranchRoot:t,stateBranchName:i}),await Ei(t),n?await El({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of s){if(d(l))return a(l.message);r=r||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{decodeTime as fx}from"ulid";var Cl=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=W("getRepoRootDir",await Je(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=W("getStateBranchRoot",Xe({repoRoot:r}));if(d(o))return a(o.message);let i=o.value;logger.debug("[sync] state branch root",i);let s=W("ensureInitialCommit",await Cs(r));if(d(s))return a(s.message);logger.debug("[sync] initial commit result",{created:s.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:i,ensureUpstream:t});let l=W("bootstrapStateBranchStorage",await bs({repoRoot:r,stateBranchRoot:i,ensureUpstream:t}));if(d(l))return a(l.message);logger.debug("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:i}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:i});let u=W("hasInProgressGitOperation(stateBranchRoot)",await Mn(i));if(d(u))return a(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"),a("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=W("ensureStateBranchLayout",hi(r,i));return d(m)?a(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}))},Nl=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=W("stageStateBranchOwnEventFile",await Yn({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=W("hasStagedChanges(after stage)",await pi(t));if(d(o))return a(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=W("createStateBranchSyncCommit",await Ns({repoRoot:e,stateBranchRoot:t}));return d(i)?a(i.message):(logger.debug("[sync] created sync commit",i.value),c("Committed own event file",{createdCommit:!0,commitSha:i.value}))},Ss=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}),a("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}),a("Own event file must end with .jsonl");ys();let n=W("ensureSyncReady",await Cl({cwd:e,ensureUpstream:!0}));if(d(n))return ke(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,s=W("isDetachedHead(stateBranchRoot)",await gi(o));if(d(s))return ke(s.message);if(logger.debug("[sync] detached state branch check result",{detached:s.value}),s.value)return ke("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,g=!1,y=W("getStateBranch",At(r));if(d(y))return ke(y.message);let C=y.value;logger.debug("[sync] resolved state branch",{stateBranch:C,stateBranchRoot:o});let I=W("commitOwnEventFileToStateBranch",await Nl({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(I))return ke(I.message);l=I.value.createdCommit,u=I.value.commitSha;let S=W("pullBranchRebaseIfPresent",await Vr({cwd:o,branch:C}));if(d(S))return ke(S.message);if(m=S.value,l||i){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:i,stateBranchRoot:o});let A=W("pushStateBranch",await dn({stateBranchRoot:o,repoRoot:r}));if(d(A)&&mi(A.message)){let R=W("pullBranchRebaseIfPresent(retry)",await Vr({cwd:o,branch:C}));if(d(R))return ke(R.message);m=m||R.value,A=W("pushStateBranch(retry)",await dn({stateBranchRoot:o,repoRoot:r}))}if(d(A))return ke(A.message);g=A.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let A=W("git rev-parse HEAD",await D({args:["rev-parse","HEAD"],cwd:o}));if(d(A))return ke(A.message);u=A.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return hs(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 Xn=async()=>{let e=Is();if(e)return e;logger.debug("[sync] syncAndReloadState:start");let t=W("resolveActorId",Y());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id"),a("Unable to resolve event log path");N({syncStatus:{msg:"Reloading synced state",status:"syncing"}});let n=on(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n});let r=W("syncEpiqWithRemote",await Ss({ownEventFileName:n}));if(d(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),a(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let i=W("loadMergedEvents",Lt(o));if(d(i))return a(`Unable to load events. ${i.message}`);logger.debug("[sync] loaded merged events after sync",{count:i.value.length});let s=Is();if(s)return s;let l=gs();if(!v().selectedNode?.isVirtual&&!v().contextNode?.isVirtual){let m=W("bootStateFromEventLog",qn(i.value));if(d(m))return a(`Unable to boot synced state. ${m.message}`)}logger.debug("[sync] booted state from synced events");let u=W("restoreNavigationAnchor",vs(l));return d(u)?u:(N({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done"),c("Synced",!0))},Is=()=>v().mode===p.DEFAULT?null:(N({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var Bt=3e3,Rs=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Bt?null:t},As=0,po,go=!1,cn=!1,fo=()=>{if(go)return!0;let e=ot();return d(e)?!1:e.value.syncStatus.status==="syncing"},bl=()=>{let e=U().autoSyncIntervalMs??1e4,t=Date.now()-As;return Math.max(0,e-t)},Ts=()=>{po||(po=setTimeout(async()=>{if(po=void 0,!!Dt()){if(fo()){cn=!0;return}cn=!1,await Sl()}},bl()))},Sl=async()=>{if(v().readOnly||v().timeMode==="peek")return a("Cannot auto-sync while peeking");if(!Dt())return a("Cannot auto-sync before state is initialized");if(fo())return cn=!0,a("Sync already in progress");go=!0,As=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Xn()}finally{go=!1,cn&&Ts()}},Jn=()=>{Dt()&&(cn=!0,!fo()&&Ts())};var Il=e=>e.props.tags??[],Rl=e=>e.props.assignees??[],vo=e=>Il(e).map(t=>b.getTag(t)).filter(t=>!!t),xo=e=>Rl(e).map(t=>b.getContributor(t)).filter(t=>!!t),Qn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!$(n)?a("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",vo(n))},Zn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!$(n)?a("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",xo(n))};var x={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 Al=/^(\d+)(h|d|w|mo|y)$/,Tl=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,wl=({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},Ml=(e,t=new Date)=>{let n=e.match(Al);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let s=new Date(t);switch(o){case"h":return s.setHours(s.getHours()-i),s;case"d":return s.setDate(s.getDate()-i),s;case"w":return s.setDate(s.getDate()-i*7),s;case"mo":return s.setMonth(s.getMonth()-i),s;case"y":return s.setFullYear(s.getFullYear()-i),s;default:return null}},Pl=e=>{let t=e.match(Tl);if(!t)return null;let[,n,r,o,i,s]=t,l=Number(n),u=Number(r),m=Number(o),g=i?Number(i):0,y=s?Number(s):0;return wl({year:l,month:u,day:m,hour:g,minute:y})?new Date(l,u-1,m,g,y):null},er=e=>{let t=e.trim().toLowerCase();return Ml(t)??Pl(t)},ws=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Ll=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],Ms=(e=Ll)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let i=r;i<=o;i++)t.push(`${i}${n}`);return t};var kl=["BOARD","TICKET","SWIMLANE"],X={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},it={TITLE:"title",DESCRIPTION:"description"},Dl=[X.EDITOR,X.VIEW,X.USERNAME,X.AUTOSYNC,X.SYNC_DEBOUNCE_MS,X.LOG_LEVEL],Fl=[it.TITLE,it.DESCRIPTION],ho=[String(Bt),"5000","15000","30000","60000"],Et=[x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG],tr=[x.NEW,x.EDIT,x.DELETE,x.MOVE],yo=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT],Ps=[x.FILTER,x.PEEK],Bl={WORKSPACE:[...Et,...tr],BOARD:[...Ps,...Et,...tr],SWIMLANE:[...Ps,...Et,...tr],TICKET:[...Et,...tr,...yo],FIELD:[...Et,...yo],FIELD_LIST:[...Et,...yo],TEXT:[...Et]},Ul=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Ol=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Ze();if(!r)return[x.HELP,x.CONFIG];if(!Ni())return[x.HELP,x.INIT];if(t)return[x.HELP,x.PEEK,x.EXPORT,x.CONFIG];let o=e?.context,i=o&&kl.includes(o);return[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?Bl[l]:[]))].filter(l=>l===x.MOVE?!1:l===x.EDIT||l===x.DELETE?i:!0)},ee=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let i=t.context??"WORKSPACE";return{[x.NONE]:Ol({breadCrumb:o,readOnly:r,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.HELP]:[],[x.PEEK]:[...Ms(),"now","prev","next"],[x.EDIT]:[...Fl],[x.DELETE]:["confirm"],[x.RE_OPEN_ISSUE]:["confirm"],[x.CLOSE_ISSUE]:["confirm"],[x.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[x.FILTER]:["tag","assignee","description","title","clear"],[x.TAG]:[...new Set([...Object.keys(xt),...b.getExistingTags()])],[x.UNTAG]:[...Qn()?.value?.map(({name:l})=>l)??[]],[x.UNASSIGN]:[...Zn()?.value?.map(({name:l})=>l)??[]],[x.ASSIGN]:b.getExistingAssignees(),[x.NEW]:Ul(i),[x.CONFIG]:[...Dl]}[e]??[]};import Fs from"chalk";var Ls=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import ks from"chalk";var te=e=>ks.dim(e),pe=e=>ks.hex(h.primary)(e),de=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let s=o.trim();if(s.length<i)return"";let g=[...t.filter(Boolean).filter(y=>y.startsWith(s))].sort((y,C)=>On(y)-On(C)).slice(0,r).map(y=>$n(y)).join(" ");return g?`${te(e)}${g}${te(n)}`:""};var Ct={None:"none",Invalid:"invalid",Valid:"valid"};var $l=["BOARD","TICKET","SWIMLANE"],Ds=()=>{let e=v().selectedNode;return e?.context?$l.includes(e.context)?H():k({message:te("Command not available in this context")}):k({message:te("Missing target context")})},Z="<ENTER> to confirm",H=(e="",t=[])=>({message:te(e),validity:Ct.Valid,completionWordList:t}),k=({message:e,completionWordList:t=[]})=>({validity:Ct.Invalid,message:e,completionWordList:t}),rr=e=>e.length===0,nr=e=>` ${Fs.dim.bgHex(Vi(e))(` ${e} `)} `,Eo=({modifier:e})=>{let t="confirm";return e===t?H(Z):k({message:rr(e)?te("if you are certain, enter ")+$n(t):"",completionWordList:[t]})},_l=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?k({message:te(n)}):H():k({message:rr(r)?t:"",completionWordList:[...e]}),ln=({hint:e})=>({modifier:t,inputString:n})=>rr(t)&&rr(n)?k({message:e,completionWordList:[]}):H(Z),Wl=({modifier:e,inputString:t})=>{let n=ee(x.CONFIG);if(!n.includes(e))return k({message:de({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case X.EDITOR:{let r=[...Ls];return t.trim()?r.includes(t.trim())?H(Z):k({message:de({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):k({message:de({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?H(Z):k({message:de({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.USERNAME:return t.trim()?H(Z):k({message:pe("Enter a user name. Saved in ")+Fs.bgBlack("~/.epiq-global/config.json")});case X.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?H(Z):k({message:de({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case X.AUTOSYNC:{let r=["on","off"],o=U().autoSync;if(!r.includes(t.trim())){let i=bi(o);return k({message:de({prefix:`should auto-sync (recommended)${i!==null?", currently: "+i:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return H(Z)}case X.SYNC_DEBOUNCE_MS:{let r=U().autoSyncIntervalMs,o=Rs(t);if(!t.trim()||o===null||o<Bt){let i=de({prefix:" examples: ",wordList:ho,minLengthForHints:0,inputString:t});return k({message:pe(`provide duration above ${Bt}ms. current duration: ${r}ms.`)+i,completionWordList:ho})}return H(Z)}default:return k({message:pe("Unknown config option"),completionWordList:n})}},Hl=({modifier:e})=>{let t=ee(x.EDIT);if(!t.includes(e)){let i=de({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return k({message:i||pe("Unknown edit option"),completionWordList:t})}let{breadCrumb:n,selectedNode:r}=v();if(!Ce([...n,r],"TICKET"))return k({message:pe("Command not available in this context")});switch(e){case it.TITLE:return H(Z);case it.DESCRIPTION:let{preferredEditor:i}=U();return i?H(te("<ENTER> to edit in ")+i):k({message:"No editor selected"});default:return k({message:pe("Unknown edit option"),completionWordList:t})}},jl={[x.EXPORT]:()=>H(Z+te(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now")return H(Z);let n={message:te("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")};if(t==="prev"||t==="next")return H(Z);let r=er(t);if(!t||!r)return k(n);let o=Ce(v().breadCrumb,"BOARD");if(d(o))return k({message:pe("Command is not applicable in this context")});let i=_n(o.value.id);return d(i)?k({message:pe("Unable to peek: board id is not a valid ULID")}):ws({date:r,horizonDate:i.value})?H(Z):k({message:pe(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[x.EXIT]:()=>H(Z+te(" and exit the application")),[x.INIT]:()=>H(Z),[x.PALETTE]:()=>H(Z),[x.FILTER]:e=>{if(e.modifier==="clear")return H();let t=i=>ee(x.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return k({message:de({wordList:ee(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:ee(x.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())?k({message:de({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):H():k({message:de({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[x.NONE]:e=>{let t=ee(x.NONE);return k({message:de({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>_l({list:ee(x.NEW),hint:de({wordList:ee(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>H(Z),[x.EDIT]:Hl,[x.CONFIG]:Wl,[x.DELETE]:e=>{let t=Ds();return t.validity==="invalid"?t:Eo(e)},[x.CLOSE_ISSUE]:e=>Eo(e),[x.RE_OPEN_ISSUE]:e=>Eo(e),[x.MOVE]:e=>{let t=Ds();return t.validity==="invalid"?t:ln({hint:de({prefix:"hey hacker! These commands are blocked for you... ",wordList:ee(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=b.getExistingTags().slice(0,10).map(nr).join("");return ln({hint:n.length?te("create tag or reuse:")+n+te(""):te("create tag ...")})(e)},[x.UNTAG]:e=>{let t=Qn();if(d(t))return k({message:pe("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(nr).slice(0,10);return n.length?ln({hint:te(" ... ")+n.join("")})(e):k({message:pe("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=b.getExistingAssignees().map(nr).slice(0,10);return ln({hint:te("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=Zn();if(d(t))return k({message:pe("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(nr).slice(0,10);return n.length?ln({hint:te("remove assignee... ")+n.join("")})(e):k({message:pe("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>H(Z)},Bs=Object.fromEntries(Object.entries(jl).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Us=["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 Os=e=>Object.values(x).includes(e),$s=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:s,validity:l,completionWordList:u}=Bs[n].validate(n,r,i),m=o==="command"||o==="modifier"?ee(n):Us,{mode:g}=v(),y=g===p.COMMAND_LINE?s??"":"",C=[...u,...m];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:y,autoCompletion:t?Ui(e,C):{hint:"",hints:[],remainder:"",overlap:0}}};var _s=e=>{let t=e.trimStart(),n=Kl(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),s=zl(e),l=Os(r)?r:null,u=l!==null,m=r!=="",g=l?ee(l)??[]:[],y=l&&g.includes(o)?o:"",C="word";n.length===0||n.length===1&&!i?C="command":(n.length===1&&i||n.length===2&&!i)&&(C="modifier");let I=i?"":s,S=Vl(t,l,y);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:s,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:i,modifier:y,target:C,inputToMatch:I,inputString:S}},Vl=(e,t,n)=>{let r=e;return t&&r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/^\s+/,""),n&&r.startsWith(n)&&(r=r.slice(n.length),r=r.replace(/^\s+/,"")),r},Kl=e=>e.trim()?e.trim().split(/\s+/):[],zl=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as Gl}from"react";var Ut=e=>e===Co||e===":",Co=" ",ie={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Ct.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},No=new Set,Ws=()=>{for(let e of No)e()},bo=e=>(No.add(e),()=>No.delete(e)),De=e=>{let n=e(ie),r=_s(n.value),o=n.cursorPosition===n.value.length;ie={...n,commandMeta:$s(r,o)},Ws()},un=({message:e,status:t})=>{let n=structuredClone(ie);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,ie=n,Ws(),c(e,null)},So=e=>{De(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Io=e=>{De(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}})},Hs=()=>{De(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}})},js=()=>{De(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}})},or=e=>{De(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),s=i+o,l=Math.max(0,Math.min(i.length,s.length));return{...t,value:s,cursorPosition:l,commandIsPending:!1}})},Vs=()=>{De(e=>({...e,commandIsPending:!0}))},O=e=>{De(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Ks=({addToHistory:e=!0})=>{De(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},zs=()=>{De(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}})},Gs=()=>{De(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},V=()=>ie,qs=()=>Gl(bo,V,V),Ys=()=>{let[e,...t]=ie.value.split(Co);return t.join(Co).trim()};var f={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"};function ql(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function Yl(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function Xl(e,t,n){let r=v().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function Xs(e,t){let n=V();if(e.sequence==="?"&&t!==p.PALETTE)return f.InitCommandPalette;if(e.sequence===":"&&t!==p.COMMAND_LINE)return f.InitCommandLine;if(t===p.MOVE)switch(e.name){case"m":case"return":return f.ConfirmMove}if(t===p.COMMAND_LINE)return wi(e,n.value);if(t===p.PALETTE)return Mi(e,n.value);let r=ql(e)||Yl(e);if(r)return Jl(r,t);if(e.ctrl&&e.name==="c")return f.Exit;switch(e.name){case"r":return f.EditTitle;case"e":return f.EditDescription;case"n":return f.AddItem;case"m":return f.InitMove;case"d":return f.Delete;case"return":return f.Confirm;case"space":return f.Confirm;case"v":return U().viewMode==="wide"?f.SetViewDense:f.SetViewWide;case"q":case"escape":return f.Exit;default:return null}}function Jl(e,t){let n=t===p.MOVE?{prevItem:f.MovePreviousItem,nextItem:f.MoveNextItem,prevContainer:f.MoveToPreviousContainer,nextContainer:f.MoveToNextContainer}:{prevItem:f.NavPreviousItem,nextItem:f.NavNextItem,prevContainer:f.NavToPreviousContainer,nextContainer:f.NavToNextContainer};return Xl(v().contextNode.childRenderAxis,e,n)}var ir=e=>{let{context:t}=v().contextNode;if(!t)return P.None;switch(e){case x.EXIT:return P.Exit;case x.EXPORT:return P.Export;case x.INIT:return P.Init;case x.DELETE:return P.Delete;case x.EDIT:return P.Edit;case x.HELP:return P.ViewHelp;case x.RE_OPEN_ISSUE:return P.ReopenIssue;case x.CLOSE_ISSUE:return P.CloseIssue;case x.TAG:return P.TagTicket;case x.UNTAG:return P.UntagTicket;case x.ASSIGN:return P.AssignUserToTicket;case x.UNASSIGN:return P.UnassignUserFromTicket;case x.NEW:return P.NewItem;case x.FILTER:return P.Filter;case x.MOVE:return P.Move;case x.PEEK:return P.Peek;case x.CONFIG:return P.Config;case x.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{ulid as fe}from"ulid";import la from"node:fs";import Eu from"node:path";import Cu from"react";import{Box as yu}from"ink";import ur from"react";import{Box as Ao,Text as du}from"ink";import Fe from"react";import{Text as Js}from"ink";import Qs,{useEffect as Zs,useState as Ql}from"react";var ea={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},ge=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=K(),r=ea[n]??ea.default,[o,i]=Ql(0);if(Zs(()=>{i(0)},[r]),Zs(()=>{if(!e)return;let l=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return Qs.createElement(Js,null,t);let s=r[o]??r[0]??t;return Qs.createElement(Js,{color:h.accent,dimColor:o===1},s)};import{Box as Ro,Text as Zl}from"ink";import sr from"react";var st=({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)),s=Math.max(1,Math.ceil(r)),l=Math.max(1,Math.floor(i/s)),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),y=g+l,C=e.slice(g,y),I=e.length>l,S=i,A=I?Math.max(1,Math.floor(l/e.length*S)):S,R=Math.max(0,S-A),M=Math.max(1,e.length-l),F=I?Math.floor(g/M*R):0;return sr.createElement(Ro,{flexDirection:"row",height:i,width:"100%"},sr.createElement(Ro,{flexDirection:"column",flexGrow:1,height:i},C),sr.createElement(Ro,{flexDirection:"column",width:1,height:S},Array.from({length:S}).map((Ie,le)=>sr.createElement(Zl,{key:le,color:I&&le>=F&&le<F+A?h.accent:h.secondary},I?"\u2502":" "))))};import{Box as ar,Text as su}from"ink";import Nt from"react";import{Text as eu}from"ink";import tu from"react";var nu=e=>e.toLowerCase().trim(),ru=(e,t=xt)=>{let n=nu(e);return t[n]?t[n]:en(n)},Ot=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return tu.createElement(eu,{underline:t,color:ru(n.name)},"@"+n.name)};import{Text as ou}from"ink";import iu from"react";var $t=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return iu.createElement(ou,{underline:t,backgroundColor:be(n.name),color:h.primary}," "+n.name+" ")};var ta=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=Un(Pi(t.title),r),i=vo(t),s=xo(t);return Nt.createElement(ar,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?h.accent:h.secondary,justifyContent:"space-between"},Nt.createElement(ar,{borderBottom:!0},Nt.createElement(ar,{paddingLeft:1,flexDirection:"column"},Nt.createElement(su,{color:h.primary},o))),Nt.createElement(ar,{flexDirection:"row",paddingLeft:1},i.map(l=>Nt.createElement($t,{key:l.id,id:l.id})),s.map(l=>Nt.createElement(Ot,{key:l.id,id:l.id}))))};import{Box as _t,Text as dr}from"ink";import we from"react";var au=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,na=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=(t.props.tags??[]).map(S=>b.getTag(S)).filter(S=>!!S),s=(t.props.assignees??[]).map(S=>b.getContributor(S)).filter(S=>!!S),l=1,u=i.length*(1+l),m=s.length*(2+l),g=i.map(S=>we.createElement(_t,{key:S.id,paddingRight:l},we.createElement(dr,{color:be(S.name)},"\u25A0"))),y=s.map(S=>we.createElement(_t,{key:S.id,paddingRight:l},we.createElement(dr,{color:en(S.name)},"@"+S.name.at(0)))),C=n?h.accent:o===p.MOVE?h.secondary:h.primary;return we.createElement(_t,{borderBottom:!0,justifyContent:"space-between"},we.createElement(_t,null,we.createElement(_t,{width:4},n?we.createElement(ge,{isSelected:n}):we.createElement(dr,{color:"gray",dimColor:!0},r+1)),we.createElement(dr,{wrap:"truncate",color:C},au(t.title,e-u-m-18))),we.createElement(_t,null,g,y))};import cu from"chalk";var lu=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:s,mode:l})=>{let{renderedChildrenIndex:u}=K(),m=u[e.id]??[],g=`${e.title} ${cu.hex(h.secondary2).dim("("+m.length+")")}`,y=3,C=o?1:4,I=r-y-(o?2:1),S=Fe.createElement(Ao,{borderStyle:"round",borderColor:h.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Fe.createElement(ge,{isSelected:t}),Fe.createElement(du,{bold:!0,color:t?h.accent:h.primary},g," ",e.readonly?"\u{1F512}":"")),A=(R,M)=>{let F=i&&s===M;return o?Fe.createElement(na,{key:R.id,index:M,width:n,ticket:R,isSelected:F,mode:l}):Fe.createElement(ta,{key:R.id,width:n,ticket:R,isSelected:F})};return Fe.createElement(Ao,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?h.accent:h.secondary,paddingRight:1,paddingLeft:1,height:r},S,Fe.createElement(Ao,{padding:o?1:0},m.length>0&&Fe.createElement(st,{selectedIndex:s,height:I,itemHeight:C},m.map(A)),Fe.createElement(ge,{isSelected:i&&s===-1})))},ra=Fe.memo(lu);import{Box as Po,Text as fu}from"ink";import at,{useMemo as da}from"react";import{Box as cr,Text as uu}from"ink";import Ve from"react";var oa=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=K(),{title:o}=t,i=t.parentNodeId?b.getNode(t.parentNodeId):void 0,s=i&&$(i)?o===Q.ASSIGNEES?i.props.assignees??[]:o===Q.TAGS?i.props.tags??[]:[]:[];return Ve.createElement(cr,{alignItems:"center",paddingTop:1},Ve.createElement(cr,{minWidth:12},Ve.createElement(ge,{isSelected:n}),Ve.createElement(uu,{color:n?h.accent:h.secondary2},o,":")),Ve.createElement(cr,{flexDirection:"row",marginLeft:1,paddingRight:1},s.map((l,u)=>{let m=r.id===t.id&&u===e;return Ve.createElement(cr,{key:`${o}-${l}`,paddingRight:2,minHeight:1},Ve.createElement(ge,{isSelected:m}),o===Q.ASSIGNEES?Ve.createElement(Ot,{isSelected:m,id:l}):o===Q.TAGS?Ve.createElement($t,{isSelected:m,id:l}):null)})))};import{Box as lr,Text as To}from"ink";import Ke,{useEffect as mu,useMemo as ia}from"react";var pu="\u2029",sa=(e,t)=>`${e}::inline-line::${t}`,wo=new Map,aa=e=>{let t=wo.get(e)??[];wo.delete(e);for(let n of t)b.deleteNode(n)},gu=(e,t)=>{aa(e);let n=[];t.forEach((r,o)=>{let i=Ae(BigInt(o+1));if(!J(i))return;let s=b.createNode(q.text({id:sa(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:i.value,props:{value:r},readonly:!0,isVirtual:!0}));J(s)&&n.push(s.value.id)}),wo.set(e,n)},Mo=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:s,contextNode:l}=K(),u=ia(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=ia(()=>u.join("\0"),[u]);mu(()=>(gu(e,u),()=>{aa(e)}),[e,m]);let g=C=>String(C).replace(/\r?\n/g,""),y=u.map((C,I)=>{let S=l.id===e&&s===I;return Ke.createElement(lr,{key:sa(e,I)},Ke.createElement(To,{color:S?h.primary:h.secondary2,dimColor:!S},`${I+1} `.padStart(5,"\xA0")),Ke.createElement(To,{backgroundColor:S?"gray":void 0},g(C.length?Un(C,i-10):pu)))});return Ke.createElement(lr,{flexDirection:"column",paddingTop:1},Ke.createElement(lr,null,Ke.createElement(ge,{isSelected:o}),Ke.createElement(To,{color:o?h.accent:h.secondary2},t)),Ke.createElement(lr,{flexDirection:"row",borderStyle:"round",borderColor:h.secondary,paddingLeft:1,marginLeft:1},Ke.createElement(st,{scrollByOne:!0,height:r-3,selectedIndex:s,itemHeight:1},y)))};var vu=e=>rt(e,"description"),xu=e=>rt(e,"history"),ca=({ticket:e,height:t})=>{let{selectedIndex:n,contextNode:r}=K(),o=process.stdout.columns||120,i=da(()=>vu(e.id),[e.id]),s=da(()=>xu(e.id),[e.id]),l=r.id===e.id,u=r.id===s||r.parentNodeId===s,m=_(e.id);if(u){let R=b.getNode(s),M=R&&tt(R)?R.props.value??"":"",Ie=t-3;return at.createElement(Po,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R?at.createElement(Mo,{id:R.id,label:"Event log",text:M,selected:!1,maxWidth:o,height:Ie}):null)}let g=m.reduce((R,M)=>Zt(M)||M.id===s?R+1:R,0),y=2,C=3,I=g,S=t-C-I-y,A=(R,M)=>R.id===i?at.createElement(Mo,{key:R.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:M,maxWidth:o,height:S}):Zt(R)?at.createElement(oa,{key:R.id,parent:R,selected:M,selectedIndex:n}):R.id===s?at.createElement(Po,{key:R.id,paddingTop:1},at.createElement(ge,{isSelected:M}),at.createElement(fu,{backgroundColor:h.secondary,color:M?h.accent:h.primary}," History \u203A\u203A ")):null;return at.createElement(Po,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((R,M)=>A(R,l&&n===M)))};var hu=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:s,width:l})=>{let u=t.context,m=u===w.TICKET||u===w.FIELD_LIST||u===w.FIELD,g=u===w.BOARD||u===w.SWIMLANE,y=u===w.TICKET?t:r.find(R=>R.context===w.TICKET),C=Math.floor(l/3),I=Math.floor(l/Math.max(e.length,1)),S=Math.min(I,C),A=i==="dense";return ur.createElement(yu,{flexDirection:"row",height:s},g&&e.map((R,M)=>{let F=t.id===R.id,Ie=F?n:-1,le=t.context===w.BOARD&&n===M;return ur.createElement(ra,{key:R.id,height:s,width:S,swimlane:R,isSelected:le,isDense:A,isFocused:F,listSelectedIndex:Ie,mode:o})}),m&&y&&ur.createElement(ca,{height:s,ticket:y}))},mr=ur.memo(hu);import{render as Nu}from"ink";import{Writable as bu}from"node:stream";var mn=e=>String(e).padStart(2,"0"),Su=e=>{let t=e.getUTCFullYear(),n=mn(e.getUTCMonth()+1),r=mn(e.getUTCDate()),o=mn(e.getUTCHours()),i=mn(e.getUTCMinutes()),s=mn(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${s}`},Iu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Ru=async(e,{width:t,height:n})=>{let r="",o=new bu({write(s,l,u){let m=Au(s.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=Nu(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(s=>setTimeout(s,0)),i.unmount(),r},Au=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),ua=async()=>{let{viewMode:e}=U(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:i}=v(),s=r.find(M=>M.context==="BOARD");if(!s)return a("No board found to export");let l=120,u=40,m=await Ru(Cu.createElement(mr,{height:u,width:l,swimlanes:(i[s.id]??[]).filter(M=>M!==void 0&&wt(M)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:u});if(!m)return a("Failed to render board export");let g=An(process.cwd());if(d(g))return a("Unable to export, epiq root not found");let y=new Date,C=Su(y),I=`board_${Iu(s.title)}_${C}.md`,S=Zo(g.value);la.mkdirSync(S,{recursive:!0});let A=Eu.join(S,I),R=`# Board - ${s.title}
45
- Date: ${y.toISOString()}
25
+ `)}`):(vl(),N({hasProjectDefinition:!0}),c("State booted successfully",null))}var Ct=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),uo=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}},W=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);var mo=({status:e,msg:t})=>{Dt()&&N({syncStatus:{status:e,msg:t}})},Cs=(e="Syncing...")=>{mo({status:"syncing",msg:e})},Es=(e="Synced")=>{mo({status:"synced",msg:e})},xl=e=>{mo({status:"failed",msg:e})},ke=e=>(xl(e),a(e));import Ft from"node:fs";import dn from"node:path";var bs=async e=>{if((await Pe({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);de.info("Creating initial commit");let n=await G.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?a(n.message):c("Created initial commit",!0)},Ns=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",hl=async e=>{let t=await Fn(e);if(d(t))return a(t.message);let n=await pi(e);return d(n)?a(n.message):c("Built sync commit message",`[sync|branch:${Ns(t.value)}:sha:${Ns(n.value)}]`)},po=async({repoRoot:e,stateBranchName:t})=>{de.info(`Creating ${t}`);let n=await k({args:["commit-tree",hi,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return a(`Failed to create state branch commit
26
+ ${n.message}`);let r=n.value.stdout.trim(),o=await k({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return d(o)?a(`Failed to create ${t}
27
+ ${o.message}`):c("Created state branch",!0)},yl=async({repoRoot:e,stateBranchName:t})=>{let n=await Vr({repoRoot:e});if(d(n))return a(`Ensure local state branch failed
28
+ `+n.message);let r=n.value,o=r?await kn({repoRoot:e,branch:t}):c("No remote, no remote state branch",!1);if(d(o))return a(`Ensure local state branch failed
29
+ `+o.message);let i=o.value;if(r&&i){let l=await G.fetch({cwd:e,remote:ye,branch:t});if(d(l))return a(`Failed to fetch ${t} from remote
30
+ ${l.message}`)}let s=await Dn({repoRoot:e,branch:t});if(d(s))return a(`Ensure local state branch failed
31
+ `+s.message);if(s.value)return c("Local state branch already exists",!1);if(i){let l=await k({args:["branch","--track",t,`${ye}/${t}`],cwd:e});return d(l)?a(`Failed to create local ${t} from remote
32
+ ${l.message}`):c("Created local state branch from remote",!0)}return po({repoRoot:e,stateBranchName:t})},Cl=async({repoRoot:e,branch:t})=>{let n=await k({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=n.value.stdout.split(`
33
+ `),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)},El=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Qt(dn.dirname(t));if(d(r))return a(`Failed to create state branch worktree
34
+ `+r.message);Ft.existsSync(t)&&!Ft.existsSync(dn.join(t,".git"))&&(de.info("Removing broken state branch worktree path"),Ci(t)),de.info("Creating state branch worktree");let o=await G.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(o)?a(`Failed to create state branch worktree
35
+ ${o.message}`):c("Created state branch worktree",!0)},cn=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await Cl({repoRoot:e,branch:n});if(d(r))return a(r.message);let o=dn.resolve(t),i=r.value?dn.resolve(r.value):null;if(i&&i===o&&Ft.existsSync(i))return c("State branch already checked out in expected worktree",!1);if(i&&i!==o){de.info("Moving state branch worktree to expected location");let u=await G.worktreeRemove({cwd:e,worktreeRoot:i});if(d(u))return a(`Failed to remove existing state branch worktree
36
+ ${u.message}`)}if(i&&!Ft.existsSync(i)){de.info("Pruning stale state branch worktree");let u=await G.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
37
+ ${u.message}`)}let s=await mi({repoRoot:e,worktreeRoot:t});if(d(s))return a(s.message);let l=Ft.existsSync(t);if(s.value&&l)return c("State branch worktree already exists",!1);if(s.value&&!l){de.info("Pruning missing registered state branch worktree");let u=await G.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
38
+ ${u.message}`)}return El({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Nl=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Fn(e);if(d(n))return a(n.message);if(n.value===t)return c("State branch already checked out",!1);(await Pe({cwd:e,args:["rebase","--abort"]})).exitCode===0&&de.info("Aborted stale state branch rebase");let o=await G.checkout({cwd:e,branch:t});return d(o)?a(`Failed to checkout ${t}
39
+ ${o.message}`):c("Checked out state branch",!0)},bl=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Kr(t);if(d(n))return a(n.message);if(n.value)return c("State branch upstream already configured",!1);let r=await Vr({repoRoot:t});if(d(r))return a(r.message);if(!r.value)return c("No remote available for state branch upstream",!1);let o=Tt(e);if(d(o))return o;let i=o.value,s=await kn({repoRoot:t,branch:i});if(d(s))return a(s.message);if(!s.value)return c("Remote state branch missing; upstream will be configured on first push",!1);de.info(`Configuring ${i} upstream`);let l=await G.fetch({cwd:t,remote:ye,branch:i});if(d(l))return a(`Failed to fetch ${i}
40
+ ${l.message}`);let u=await G.setUpstream({cwd:t,branch:i,upstream:`${ye}/${i}`});return d(u)?a(`Failed to set state branch upstream
41
+ ${u.message}`):c("Configured state branch upstream",!0)},Jn=async({stateBranchRoot:e,eventFileName:t})=>{let n=qr(t),r=dn.join(e,n);if(!Ft.existsSync(r))return c("No event file to stage",void 0);let o=await G.stage({cwd:e,pathspec:[n]});return d(o)?a(`Failed to stage state branch event file
42
+ ${o.message}`):c("Staged state branch event file",void 0)},Ss=async({repoRoot:e,stateBranchRoot:t})=>{let n=await hl(e);return d(n)?a(`Create state branch sync commit failed
43
+ `+n.message):wt({cwd:t,message:n.value})},ln=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Kr(t);if(d(n))return a(n.message);let r=Tt(e);if(d(r))return r;let o=r.value,i=n.value?await G.push({cwd:t}):await G.push({cwd:t,remote:ye,branch:o,setUpstream:!0});return d(i)?a(`Failed during state branch push
44
+ ${i.message}`):c("Pushed state branch",!0)},Is=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Tt(e);if(d(o))return o;let i=o.value,s=[Bn(),await yl({repoRoot:e,stateBranchName:i}),await cn({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await Nl({stateBranchRoot:t,stateBranchName:i}),await Ni(t),n?await bl({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of s){if(d(l))return a(l.message);r=r||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{decodeTime as Cx}from"ulid";var Sl=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=W("getRepoRootDir",await Je(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=W("getStateBranchRoot",Xe({repoRoot:r}));if(d(o))return a(o.message);let i=o.value;logger.debug("[sync] state branch root",i);let s=W("ensureInitialCommit",await bs(r));if(d(s))return a(s.message);logger.debug("[sync] initial commit result",{created:s.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:i,ensureUpstream:t});let l=W("bootstrapStateBranchStorage",await Is({repoRoot:r,stateBranchRoot:i,ensureUpstream:t}));if(d(l))return a(l.message);logger.debug("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:i}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:i});let u=W("hasInProgressGitOperation(stateBranchRoot)",await Ln(i));if(d(u))return a(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"),a("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=W("ensureStateBranchLayout",Ei(r,i));return d(m)?a(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}))},Il=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=W("stageStateBranchOwnEventFile",await Jn({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=W("hasStagedChanges(after stage)",await fi(t));if(d(o))return a(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=W("createStateBranchSyncCommit",await Ss({repoRoot:e,stateBranchRoot:t}));return d(i)?a(i.message):(logger.debug("[sync] created sync commit",i.value),c("Committed own event file",{createdCommit:!0,commitSha:i.value}))},Rs=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}),a("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}),a("Own event file must end with .jsonl");Cs();let n=W("ensureSyncReady",await Sl({cwd:e,ensureUpstream:!0}));if(d(n))return ke(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,s=W("isDetachedHead(stateBranchRoot)",await vi(o));if(d(s))return ke(s.message);if(logger.debug("[sync] detached state branch check result",{detached:s.value}),s.value)return ke("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,g=!1,h=W("getStateBranch",Tt(r));if(d(h))return ke(h.message);let E=h.value;logger.debug("[sync] resolved state branch",{stateBranch:E,stateBranchRoot:o});let I=W("commitOwnEventFileToStateBranch",await Il({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(I))return ke(I.message);l=I.value.createdCommit,u=I.value.commitSha;let S=W("pullBranchRebaseIfPresent",await zr({cwd:o,branch:E}));if(d(S))return ke(S.message);if(m=S.value,l||i){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:i,stateBranchRoot:o});let A=W("pushStateBranch",await ln({stateBranchRoot:o,repoRoot:r}));if(d(A)&&gi(A.message)){let R=W("pullBranchRebaseIfPresent(retry)",await zr({cwd:o,branch:E}));if(d(R))return ke(R.message);m=m||R.value,A=W("pushStateBranch(retry)",await ln({stateBranchRoot:o,repoRoot:r}))}if(d(A))return ke(A.message);g=A.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let A=W("git rev-parse HEAD",await k({args:["rev-parse","HEAD"],cwd:o}));if(d(A))return ke(A.message);u=A.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Es(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 Qn=async()=>{let e=As();if(e)return e;logger.debug("[sync] syncAndReloadState:start");let t=W("resolveActorId",Y());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id"),a("Unable to resolve event log path");N({syncStatus:{msg:"Reloading synced state",status:"syncing"}});let n=sn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n});let r=W("syncEpiqWithRemote",await Rs({ownEventFileName:n}));if(d(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),a(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let i=W("loadMergedEvents",kt(o));if(d(i))return a(`Unable to load events. ${i.message}`);logger.debug("[sync] loaded merged events after sync",{count:i.value.length});let s=As();if(s)return s;let l=vs();if(!v().selectedNode?.isVirtual&&!v().contextNode?.isVirtual){let m=W("bootStateFromEventLog",Xn(i.value));if(d(m))return a(`Unable to boot synced state. ${m.message}`)}logger.debug("[sync] booted state from synced events");let u=W("restoreNavigationAnchor",hs(l));return d(u)?u:(N({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done"),c("Synced",!0))},As=()=>v().mode===p.DEFAULT?null:(N({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var Ot=3e3,Ts=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Ot?null:t},ws=0,go,fo=!1,un=!1,vo=()=>{if(fo)return!0;let e=ot();return d(e)?!1:e.value.syncStatus.status==="syncing"},Rl=()=>{let e=$().autoSyncIntervalMs??1e4,t=Date.now()-ws;return Math.max(0,e-t)},Ms=()=>{go||(go=setTimeout(async()=>{if(go=void 0,!!Dt()){if(vo()){un=!0;return}un=!1,await Al()}},Rl()))},Al=async()=>{if(v().readOnly||v().timeMode==="peek")return a("Cannot auto-sync while peeking");if(!Dt())return a("Cannot auto-sync before state is initialized");if(vo())return un=!0,a("Sync already in progress");fo=!0,ws=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Qn()}finally{fo=!1,un&&Ms()}},Zn=()=>{Dt()&&(un=!0,!vo()&&Ms())};var Tl=e=>e.props.tags??[],wl=e=>e.props.assignees??[],xo=e=>Tl(e).map(t=>b.getTag(t)).filter(t=>!!t),ho=e=>wl(e).map(t=>b.getContributor(t)).filter(t=>!!t),er=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!B(n)?a("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",xo(n))},tr=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!B(n)?a("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",ho(n))};var x={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""};var Ml=/^(\d+)(h|d|w|mo|y)$/,Pl=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Ll=({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},kl=(e,t=new Date)=>{let n=e.match(Ml);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let s=new Date(t);switch(o){case"h":return s.setHours(s.getHours()-i),s;case"d":return s.setDate(s.getDate()-i),s;case"w":return s.setDate(s.getDate()-i*7),s;case"mo":return s.setMonth(s.getMonth()-i),s;case"y":return s.setFullYear(s.getFullYear()-i),s;default:return null}},Dl=e=>{let t=e.match(Pl);if(!t)return null;let[,n,r,o,i,s]=t,l=Number(n),u=Number(r),m=Number(o),g=i?Number(i):0,h=s?Number(s):0;return Ll({year:l,month:u,day:m,hour:g,minute:h})?new Date(l,u-1,m,g,h):null},nr=e=>{let t=e.trim().toLowerCase();return kl(t)??Dl(t)},Ps=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Fl=[{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}],Ls=(e=Fl)=>{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 Ol=["BOARD","TICKET","SWIMLANE"],X={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},it={TITLE:"title",DESCRIPTION:"description"},Bl=[X.EDITOR,X.VIEW,X.USERNAME,X.AUTOSYNC,X.SYNC_DEBOUNCE_MS,X.LOG_LEVEL],Ul=[it.TITLE,it.DESCRIPTION],Co=[String(Ot),"5000","15000","30000","60000"],Et=[x.COFFEE,x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG],rr=[x.NEW,x.EDIT,x.DELETE,x.MOVE],yo=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT],ks=[x.FILTER,x.PEEK],$l={WORKSPACE:[...Et,...rr],BOARD:[...ks,...Et,...rr],SWIMLANE:[...ks,...Et,...rr],TICKET:[...Et,...rr,...yo],FIELD:[...Et,...yo],FIELD_LIST:[...Et,...yo],TEXT:[...Et]},_l=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Wl=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Ze();if(!r)return[x.HELP,x.CONFIG];if(!Si())return[x.HELP,x.INIT];if(t)return[x.HELP,x.PEEK,x.EXPORT,x.CONFIG];let o=e?.context,i=o&&Ol.includes(o);return[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?$l[l]:[]))].filter(l=>l===x.MOVE?!1:l===x.EDIT||l===x.DELETE?i:!0)},Z=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let i=t.context??"WORKSPACE";return{[x.NONE]:Wl({breadCrumb:o,readOnly:r,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.HELP]:[],[x.PEEK]:[...Ls(),"now","prev","next"],[x.EDIT]:[...Ul],[x.DELETE]:["confirm"],[x.RE_OPEN_ISSUE]:["confirm"],[x.CLOSE_ISSUE]:["confirm"],[x.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[x.FILTER]:["tag","assignee","description","title","clear"],[x.TAG]:[...new Set([...Object.keys(xt),...b.getExistingTags()])],[x.UNTAG]:[...er()?.value?.map(({name:l})=>l)??[]],[x.UNASSIGN]:[...tr()?.value?.map(({name:l})=>l)??[]],[x.ASSIGN]:b.getExistingAssignees(),[x.NEW]:_l(i),[x.CONFIG]:[...Bl],[x.COFFEE]:["1","3","5","20","custom"]}[e]??[]};import Bs from"chalk";var Ds=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import Fs from"chalk";var ee=e=>Fs.dim(e),pe=e=>Fs.hex(y.primary)(e),ie=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let s=o.trim();if(s.length<i)return"";let g=[...t.filter(Boolean).filter(h=>h.startsWith(s))].sort((h,E)=>_n(h)-_n(E)).slice(0,r).map(h=>Wn(h)).join(" ");return g?`${ee(e)}${g}${ee(n)}`:""};var Nt={None:"none",Invalid:"invalid",Valid:"valid"};var Hl=["BOARD","TICKET","SWIMLANE"],Os=()=>{let e=v().selectedNode;return e?.context?Hl.includes(e.context)?H():D({message:ee("Command not available in this context")}):D({message:ee("Missing target context")})},te="<ENTER> to confirm",H=(e="",t=[])=>({message:ee(e),validity:Nt.Valid,completionWordList:t}),D=({message:e,completionWordList:t=[]})=>({validity:Nt.Invalid,message:e,completionWordList:t}),ir=e=>e.length===0,or=e=>` ${Bs.dim.bgHex(zi(e))(` ${e} `)} `,Eo=({modifier:e})=>{let t="confirm";return e===t?H(te):D({message:ir(e)?ee("if you are certain, enter ")+Wn(t):"",completionWordList:[t]})},jl=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?D({message:ee(n)}):H():D({message:ir(r)?t:"",completionWordList:[...e]}),Bt=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>ir(n)&&ir(r)?D({message:e,completionWordList:[]}):H(t??te),Vl=({modifier:e,inputString:t})=>{let n=Z(x.CONFIG);if(!n.includes(e))return D({message:ie({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case X.EDITOR:{let r=[...Ds];return t.trim()?r.includes(t.trim())?H(te):D({message:ie({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):D({message:ie({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?H(te):D({message:ie({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case X.USERNAME:return t.trim()?H(te):D({message:pe("Enter a user name. Saved in ")+Bs.bgBlack("~/.epiq-global/config.json")});case X.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?H(te):D({message:ie({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=$().autoSync;if(!r.includes(t.trim())){let i=Ii(o);return D({message:ie({prefix:`should auto-sync (recommended)${i!==null?", currently: "+i:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return H(te)}case X.SYNC_DEBOUNCE_MS:{let r=$().autoSyncIntervalMs,o=Ts(t);if(!t.trim()||o===null||o<Ot){let i=ie({prefix:" examples: ",wordList:Co,minLengthForHints:0,inputString:t});return D({message:pe(`provide duration above ${Ot}ms. current duration: ${r}ms.`)+i,completionWordList:Co})}return H(te)}default:return D({message:pe("Unknown config option"),completionWordList:n})}},Kl=({modifier:e})=>{let t=Z(x.EDIT);if(!t.includes(e)){let i=ie({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return D({message:i||pe("Unknown edit option"),completionWordList:t})}let{breadCrumb:n,selectedNode:r}=v();if(!Ee([...n,r],"TICKET"))return D({message:pe("Command not available in this context")});switch(e){case it.TITLE:return H(te);case it.DESCRIPTION:let{preferredEditor:i}=$();return i?H(ee("<ENTER> to edit in ")+i):D({message:"No editor selected"});default:return D({message:pe("Unknown edit option"),completionWordList:t})}},zl={[x.EXPORT]:()=>H(te+ee(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now")return H(te);let n={message:ee("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")};if(t==="prev"||t==="next")return H(te);let r=nr(t);if(!t||!r)return D(n);let o=Ee(v().breadCrumb,"BOARD");if(d(o))return D({message:pe("Command is not applicable in this context")});let i=Hn(o.value.id);return d(i)?D({message:pe("Unable to peek: board id is not a valid ULID")}):Ps({date:r,horizonDate:i.value})?H(te):D({message:pe(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[x.EXIT]:()=>H(te+ee(" and exit the application")),[x.INIT]:()=>H(te),[x.PALETTE]:()=>H(te),[x.FILTER]:e=>{if(e.modifier==="clear")return H();let t=i=>Z(x.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return D({message:ie({wordList:Z(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Z(x.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())?D({message:ie({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):H():D({message:ie({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[x.NONE]:e=>{let t=Z(x.NONE);return D({message:ie({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>jl({list:Z(x.NEW),hint:ie({wordList:Z(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>H(te),[x.EDIT]:Kl,[x.CONFIG]:Vl,[x.DELETE]:e=>{let t=Os();return t.validity==="invalid"?t:Eo(e)},[x.CLOSE_ISSUE]:e=>Eo(e),[x.RE_OPEN_ISSUE]:e=>Eo(e),[x.MOVE]:e=>{let t=Os();return t.validity==="invalid"?t:Bt({hint:ie({prefix:"hey hacker! These commands are blocked for you... ",wordList:Z(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=b.getExistingTags().slice(0,10).map(or).join("");return Bt({hint:n.length?ee("create tag or reuse:")+n+ee(""):ee("create tag ...")})(e)},[x.UNTAG]:e=>{let t=er();if(d(t))return D({message:pe("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(or).slice(0,10);return n.length?Bt({hint:ee(" ... ")+n.join("")})(e):D({message:pe("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=b.getExistingAssignees().map(or).slice(0,10);return Bt({hint:ee("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=tr();if(d(t))return D({message:pe("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(or).slice(0,10);return n.length?Bt({hint:ee("remove assignee... ")+n.join("")})(e):D({message:pe("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>H(te),[x.COFFEE]:e=>{let{modifier:t}=e,n=Z(x.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?D({message:ee("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):Bt({hint:ie({prefix:"Fuel continued development with ... ",wordList:["$1"," $3 ","$5","$20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},Us=Object.fromEntries(Object.entries(zl).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var $s=["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 _s=e=>Object.values(x).includes(e),Ws=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:s,validity:l,completionWordList:u}=Us[n].validate(n,r,i),m=o==="command"||o==="modifier"?Z(n):$s,{mode:g}=v(),h=g===p.COMMAND_LINE?s??"":"",E=[...u,...m];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:h,autoCompletion:t?$i(e,E):{hint:"",hints:[],remainder:"",overlap:0}}};var Hs=e=>{let t=e.trimStart(),n=ql(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),s=Yl(e),l=_s(r)?r:null,u=l!==null,m=r!=="",g=l?Z(l)??[]:[],h=l&&g.includes(o)?o:"",E="word";n.length===0||n.length===1&&!i?E="command":(n.length===1&&i||n.length===2&&!i)&&(E="modifier");let I=i?"":s,S=Gl(t,l,h);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:s,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:i,modifier:h,target:E,inputToMatch:I,inputString:S}},Gl=(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},ql=e=>e.trim()?e.trim().split(/\s+/):[],Yl=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as Xl}from"react";var Ut=e=>e===No||e===":",No=" ",se={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Nt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},bo=new Set,js=()=>{for(let e of bo)e()},So=e=>(bo.add(e),()=>bo.delete(e)),De=e=>{let n=e(se),r=Hs(n.value),o=n.cursorPosition===n.value.length;se={...n,commandMeta:Ws(r,o)},js()},mn=({message:e,status:t})=>{let n=structuredClone(se);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,se=n,js(),c(e,null)},Io=e=>{De(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Ro=e=>{De(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}})},Vs=()=>{De(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},Ks=()=>{De(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}})},sr=e=>{De(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),s=i+o,l=Math.max(0,Math.min(i.length,s.length));return{...t,value:s,cursorPosition:l,commandIsPending:!1}})},zs=()=>{De(e=>({...e,commandIsPending:!0}))},F=e=>{De(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Gs=({addToHistory:e=!0})=>{De(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},qs=()=>{De(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}})},Ys=()=>{De(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},V=()=>se,Xs=()=>Xl(So,V,V),Js=()=>{let[e,...t]=se.value.split(No);return t.join(No).trim()};var f={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"};function Jl(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function Ql(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function Zl(e,t,n){let r=v().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function Qs(e,t){let n=V();if(e.sequence==="?"&&t!==p.PALETTE)return f.InitCommandPalette;if(e.sequence===":"&&t!==p.COMMAND_LINE)return f.InitCommandLine;if(t===p.MOVE)switch(e.name){case"m":case"return":return f.ConfirmMove}if(t===p.COMMAND_LINE)return Pi(e,n.value);if(t===p.PALETTE)return Li(e,n.value);let r=Jl(e)||Ql(e);if(r)return eu(r,t);if(e.ctrl&&e.name==="c")return f.Exit;switch(e.name){case"r":return f.EditTitle;case"e":return f.EditDescription;case"n":return f.AddItem;case"m":return f.InitMove;case"d":return f.Delete;case"return":return f.Confirm;case"space":return f.Confirm;case"v":return $().viewMode==="wide"?f.SetViewDense:f.SetViewWide;case"q":case"escape":return f.Exit;default:return null}}function eu(e,t){let n=t===p.MOVE?{prevItem:f.MovePreviousItem,nextItem:f.MoveNextItem,prevContainer:f.MoveToPreviousContainer,nextContainer:f.MoveToNextContainer}:{prevItem:f.NavPreviousItem,nextItem:f.NavNextItem,prevContainer:f.NavToPreviousContainer,nextContainer:f.NavToNextContainer};return Zl(v().contextNode.childRenderAxis,e,n)}var ar=e=>{let{context:t}=v().contextNode;if(!t)return P.None;switch(e){case x.EXIT:return P.Exit;case x.EXPORT:return P.Export;case x.COFFEE:return P.Coffee;case x.INIT:return P.Init;case x.DELETE:return P.Delete;case x.EDIT:return P.Edit;case x.HELP:return P.ViewHelp;case x.RE_OPEN_ISSUE:return P.ReopenIssue;case x.CLOSE_ISSUE:return P.CloseIssue;case x.TAG:return P.TagTicket;case x.UNTAG:return P.UntagTicket;case x.ASSIGN:return P.AssignUserToTicket;case x.UNASSIGN:return P.UnassignUserFromTicket;case x.NEW:return P.NewItem;case x.FILTER:return P.Filter;case x.MOVE:return P.Move;case x.PEEK:return P.Peek;case x.CONFIG:return P.Config;case x.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",Coffee:"coffee"};import{ulid as fe}from"ulid";import ma from"node:fs";import bu from"node:path";import Su from"react";import{Box as Eu}from"ink";import pr from"react";import uu from"chalk";import{Box as To,Text as mu}from"ink";import Fe from"react";import{Text as Zs}from"ink";import ea,{useEffect as ta,useState as tu}from"react";var na={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},ge=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=K(),r=na[n]??na.default,[o,i]=tu(0);if(ta(()=>{i(0)},[r]),ta(()=>{if(!e)return;let l=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return ea.createElement(Zs,null,t);let s=r[o]??r[0]??t;return ea.createElement(Zs,{color:y.accent,dimColor:o===1},s)};import{Box as Ao,Text as nu}from"ink";import dr from"react";var st=({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)),s=Math.max(1,Math.ceil(r)),l=Math.max(1,Math.floor(i/s)),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),h=g+l,E=e.slice(g,h),I=e.length>l,S=i,A=I?Math.max(1,Math.floor(l/e.length*S)):S,R=Math.max(0,S-A),M=Math.max(1,e.length-l),O=I?Math.floor(g/M*R):0;return dr.createElement(Ao,{flexDirection:"row",height:i,width:"100%"},dr.createElement(Ao,{flexDirection:"column",flexGrow:1,height:i},E),dr.createElement(Ao,{flexDirection:"column",width:1,height:S},Array.from({length:S}).map((Ie,le)=>dr.createElement(nu,{key:le,color:I&&le>=O&&le<O+A?y.accent:y.secondary},I?"\u2502":" "))))};import{Box as cr,Text as cu}from"ink";import bt from"react";import{Text as ru}from"ink";import ou from"react";var iu=e=>e.toLowerCase().trim(),su=(e,t=xt)=>{let n=iu(e);return t[n]?t[n]:tn(n)},$t=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return ou.createElement(ru,{underline:t,color:su(n.name)},"@"+n.name)};import{Text as au}from"ink";import du from"react";var _t=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return du.createElement(au,{underline:t,backgroundColor:be(n.name),color:y.primary}," "+n.name+" ")};var ra=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=$n(ki(t.title),r),i=xo(t),s=ho(t);return bt.createElement(cr,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?y.accent:y.secondary,justifyContent:"space-between"},bt.createElement(cr,{borderBottom:!0},bt.createElement(cr,{paddingLeft:1,flexDirection:"column"},bt.createElement(cu,{color:y.primary},o))),bt.createElement(cr,{flexDirection:"row",paddingLeft:1},i.map(l=>bt.createElement(_t,{key:l.id,id:l.id})),s.map(l=>bt.createElement($t,{key:l.id,id:l.id}))))};import{Box as Wt,Text as lr}from"ink";import we from"react";var lu=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,oa=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=(t.props.tags??[]).map(S=>b.getTag(S)).filter(S=>!!S),s=(t.props.assignees??[]).map(S=>b.getContributor(S)).filter(S=>!!S),l=1,u=i.length*(1+l),m=s.length*(2+l),g=i.map(S=>we.createElement(Wt,{key:S.id,paddingRight:l},we.createElement(lr,{color:be(S.name)},"\u25A0"))),h=s.map(S=>we.createElement(Wt,{key:S.id,paddingRight:l},we.createElement(lr,{color:tn(S.name)},"@"+S.name.at(0)))),E=n?y.accent:o===p.MOVE?y.secondary:y.primary;return we.createElement(Wt,{borderBottom:!0,justifyContent:"space-between"},we.createElement(Wt,null,we.createElement(Wt,{width:4},n?we.createElement(ge,{isSelected:n}):we.createElement(lr,{color:"gray",dimColor:!0},r+1)),we.createElement(lr,{wrap:"truncate",color:E},lu(t.title,e-u-m-18))),we.createElement(Wt,null,g,h))};var pu=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:s,mode:l})=>{let{renderedChildrenIndex:u}=K(),m=u[e.id]??[],g=`${e.title} ${uu.hex(y.secondary2).dim("("+m.length+")")}`,h=3,E=o?1:4,I=r-h-(o?2:1),S=Fe.createElement(To,{borderStyle:"round",borderColor:y.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Fe.createElement(ge,{isSelected:t}),Fe.createElement(mu,{bold:!0,color:t?y.accent:y.primary},g," ",e.readonly?"\u{1F512}":"")),A=(R,M)=>{let O=i&&s===M;return B(R)?o?Fe.createElement(oa,{key:R.id,index:M,width:n,ticket:R,isSelected:O,mode:l}):Fe.createElement(ra,{key:R.id,width:n,ticket:R,isSelected:O}):null};return Fe.createElement(To,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:1,paddingLeft:1,height:r},S,Fe.createElement(To,{padding:o?1:0},m.length>0&&Fe.createElement(st,{selectedIndex:s,height:I,itemHeight:E},m.map(A)),Fe.createElement(ge,{isSelected:i&&s===-1})))},ia=Fe.memo(pu);import{Box as Lo,Text as hu}from"ink";import at,{useMemo as la}from"react";import{Box as ur,Text as gu}from"ink";import Ve from"react";var sa=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=K(),{title:o}=t,i=t.parentNodeId?b.getNode(t.parentNodeId):void 0,s=i&&B(i)?o===Q.ASSIGNEES?i.props.assignees??[]:o===Q.TAGS?i.props.tags??[]:[]:[];return Ve.createElement(ur,{alignItems:"center",paddingTop:1},Ve.createElement(ur,{minWidth:12},Ve.createElement(ge,{isSelected:n}),Ve.createElement(gu,{color:n?y.accent:y.secondary2},o,":")),Ve.createElement(ur,{flexDirection:"row",marginLeft:1,paddingRight:1},s.map((l,u)=>{let m=r.id===t.id&&u===e;return Ve.createElement(ur,{key:`${o}-${l}`,paddingRight:2,minHeight:1},Ve.createElement(ge,{isSelected:m}),o===Q.ASSIGNEES?Ve.createElement($t,{isSelected:m,id:l}):o===Q.TAGS?Ve.createElement(_t,{isSelected:m,id:l}):null)})))};import{Box as mr,Text as wo}from"ink";import Ke,{useEffect as fu,useMemo as aa}from"react";var vu="\u2029",da=(e,t)=>`${e}::inline-line::${t}`,Mo=new Map,ca=e=>{let t=Mo.get(e)??[];Mo.delete(e);for(let n of t)b.deleteNode(n)},xu=(e,t)=>{ca(e);let n=[];t.forEach((r,o)=>{let i=Ae(BigInt(o+1));if(!J(i))return;let s=b.createNode(q.text({id:da(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:i.value,props:{value:r},readonly:!0,isVirtual:!0}));J(s)&&n.push(s.value.id)}),Mo.set(e,n)},Po=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:s,contextNode:l}=K(),u=aa(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=aa(()=>u.join("\0"),[u]);fu(()=>(xu(e,u),()=>{ca(e)}),[e,m]);let g=E=>String(E).replace(/\r?\n/g,""),h=u.map((E,I)=>{let S=l.id===e&&s===I;return Ke.createElement(mr,{key:da(e,I)},Ke.createElement(wo,{color:S?y.primary:y.secondary2,dimColor:!S},`${I+1} `.padStart(5,"\xA0")),Ke.createElement(wo,{backgroundColor:S?"gray":void 0},g(E.length?$n(E,i-10):vu)))});return Ke.createElement(mr,{flexDirection:"column",paddingTop:1},Ke.createElement(mr,null,Ke.createElement(ge,{isSelected:o}),Ke.createElement(wo,{color:o?y.accent:y.secondary2},t)),Ke.createElement(mr,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1},Ke.createElement(st,{scrollByOne:!0,height:r-3,selectedIndex:s,itemHeight:1},h)))};var yu=e=>rt(e,"description"),Cu=e=>rt(e,"history"),ua=({ticket:e,height:t})=>{let{selectedIndex:n,contextNode:r}=K(),o=process.stdout.columns||120,i=la(()=>yu(e.id),[e.id]),s=la(()=>Cu(e.id),[e.id]),l=r.id===e.id,u=r.id===s||r.parentNodeId===s,m=_(e.id);if(u){let R=b.getNode(s),M=R&&tt(R)?R.props.value??"":"",Ie=t-3;return at.createElement(Lo,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R?at.createElement(Po,{id:R.id,label:"Event log",text:M,selected:!1,maxWidth:o,height:Ie}):null)}let g=m.reduce((R,M)=>en(M)||M.id===s?R+1:R,0),h=2,E=3,I=g,S=t-E-I-h,A=(R,M)=>R.id===i?at.createElement(Po,{key:R.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:M,maxWidth:o,height:S}):en(R)?at.createElement(sa,{key:R.id,parent:R,selected:M,selectedIndex:n}):R.id===s?at.createElement(Lo,{key:R.id,paddingTop:1},at.createElement(ge,{isSelected:M}),at.createElement(hu,{backgroundColor:y.secondary,color:M?y.accent:y.primary}," History \u203A\u203A ")):null;return at.createElement(Lo,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((R,M)=>A(R,l&&n===M)))};var Nu=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:s,width:l})=>{let u=t.context,m=u===w.TICKET||u===w.FIELD_LIST||u===w.FIELD,g=u===w.BOARD||u===w.SWIMLANE,h=u===w.TICKET?t:r.find(R=>R.context===w.TICKET),E=Math.floor(l/3),I=Math.floor(l/Math.max(e.length,1)),S=Math.min(I,E),A=i==="dense";return pr.createElement(Eu,{flexDirection:"row",height:s},g&&e.map((R,M)=>{let O=t.id===R.id,Ie=O?n:-1,le=t.context===w.BOARD&&n===M;return pr.createElement(ia,{key:R.id,height:s,width:S,swimlane:R,isSelected:le,isDense:A,isFocused:O,listSelectedIndex:Ie,mode:o})}),m&&h&&pr.createElement(ua,{height:s,ticket:h}))},gr=pr.memo(Nu);import{render as Iu}from"ink";import{Writable as Ru}from"node:stream";var pn=e=>String(e).padStart(2,"0"),Au=e=>{let t=e.getUTCFullYear(),n=pn(e.getUTCMonth()+1),r=pn(e.getUTCDate()),o=pn(e.getUTCHours()),i=pn(e.getUTCMinutes()),s=pn(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${s}`},Tu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",wu=async(e,{width:t,height:n})=>{let r="",o=new Ru({write(s,l,u){let m=Mu(s.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=Iu(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(s=>setTimeout(s,0)),i.unmount(),r},Mu=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),pa=async()=>{let{viewMode:e}=$(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:i}=v(),s=r.find(M=>M.context==="BOARD");if(!s)return a("No board found to export");let l=120,u=40,m=await wu(Su.createElement(gr,{height:u,width:l,swimlanes:(i[s.id]??[]).filter(M=>M!==void 0&&Mt(M)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:u});if(!m)return a("Failed to render board export");let g=Tn(process.cwd());if(d(g))return a("Unable to export, epiq root not found");let h=new Date,E=Au(h),I=`board_${Tu(s.title)}_${E}.md`,S=ni(g.value);ma.mkdirSync(S,{recursive:!0});let A=bu.join(S,I),R=`# Board - ${s.title}
45
+ Date: ${h.toISOString()}
46
46
 
47
47
  \`\`\`text
48
48
  ${m}
49
49
  \`\`\`
50
- `;return la.writeFileSync(A,R,"utf8"),c("Exported board layout",A)};import Fu from"node:os";import fa from"node:path";import{z as dt}from"zod";import{accessSync as Tu,copyFileSync as wu,existsSync as pr,mkdirSync as ma,readdirSync as pa,readFileSync as Mu,renameSync as Pu,rmSync as Lu,statSync as ga,unlinkSync as ku,writeFileSync as Du}from"node:fs";import Wt from"node:path";var ve={writeToFile:(e,t)=>{try{let n=Wt.dirname(e);pr(n)||ma(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Du(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Mu(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=ve.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 pr(e)&&ga(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Tu(e),!0}catch{return!1}},mkDir:e=>ma(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Wt.parse(t);for(;;){let r=Wt.join(t,e);try{if(pr(r)&&ga(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(!ve.dirExists(e))return null;let t=pa(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Wt.join(e,t);return ve.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return ve.dirExists(e)?pa(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{ku(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Lu(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&&pr(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Pu(e,t)}catch(r){if(r?.code==="EXDEV"){wu(e,t),this.rmFile(e);return}throw r}}};var Bu={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},va=dt.object({logLevel:dt.enum(["info","error","debug"]),preferredEditor:dt.string().optional(),userName:dt.string().optional(),userId:dt.string().optional(),autoSync:dt.boolean().nullable().optional(),autoSyncDebounceMs:dt.number().optional(),viewMode:dt.enum(["dense","wide"]).optional()}).partial(),Uu="config.json",xa=()=>fa.join(Fu.homedir(),ye),Lo=()=>fa.join(xa(),Uu),ko=()=>{try{return ve.mkDir(xa()),c(`Ensured ~/${ye} exists`,null)}catch{return a(`Unable to create ~/${ye}`)}},Ou=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${ye}/config.json JSON`)}let n=va.safeParse(t??{});return n.success?c("Parsed config",n.data):a(`Invalid ~/${ye}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},ya=()=>{let e=ko();if(d(e))return a(e.message);let t=Lo(),n=ve.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Ou(n)},ha=e=>{let t=ko();if(d(t))return a(t.message);let n=va.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Lo();try{return ve.writeToFile(r,JSON.stringify(n.data,null,2)+`
51
- `),c("Config written",null)}catch{return a(`Unable to write ~/${ye}/config.json`)}},ze=e=>{let t=ya();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return ha(n)},Ea=()=>{let e=Lo(),t=ko();if(d(t))return a(`Unable to create ~/${ye}`);if(!(ve.readFile(e)!==null)){let g=ha(Bu);if(d(g))throw new Error(`Unable to create ~/${ye}/config.json`)}let r=ya();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:s,autoSync:l,autoSyncDebounceMs:u,logLevel:m}=r.value;return!i||!s?a(`User name or ID not configured in ~/${ye}/config.json`):(process.env.EPIQ_LOG_LEVEL=m,c("successfully loaded settings",{logLevel:m??"debug",preferredEditor:o??"",userName:i,userId:s,autoSync:l??!1,autoSyncIntervalMs:u??1e4,viewMode:"dense"}))};var 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};import{useSyncExternalStore as LC}from"react";var gr,$u=new Set,Na=()=>{for(let e of $u)e()};var ct=()=>{if(!gr)throw new Error("Ui state not initialized. Call initUiState() first.");return gr};var ba=(e={})=>(gr=e,Na(),c("UX state initialized",null)),_u=e=>{let t=ct();return gr=e(t),Na(),c("UX state updated",null)},lt=e=>_u(t=>({...t,...e}));import{ulid as zu}from"ulid";import{spawnSync as Wu}from"node:child_process";import Hu from"node:os";import Sa from"node:path";import{ulid as ju}from"ulid";function Vu(){let{preferredEditor:e}=U(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Ku(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function Ia(e){let t=Sa.join(Hu.tmpdir(),"epiq");ve.mkDir(t);let n=Sa.join(t,ju());ve.writeToFile(n,e??"");let r=Vu();for(let o of r){let i=Ku(o,n),s=Wu(i,{stdio:"inherit",shell:!0});if(!s.error&&s.status===0){let l=ve.readFile(n);if(l==null)return a("Unable to read edited file");let u=l.replace(/\r?\n$/,"");return c("Successfully edited",u)}}return a("Unable to open editor")}var Ra=async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let t=await Re();if(d(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=v(),i=Ce([...r,o],"TICKET");if(d(i))return a("Edit target must be an issue");let s=i.value;if(!$(s))return a("Edit target must be an issue");if(s.readonly)return a("Cannot edit readonly issue");let l=_(s.id).find(y=>y.title===Q.DESCRIPTION);if(!l)return a("No target found");if(l.readonly)return a("Cannot edit readonly field");let u=s.props.description??"";if(typeof u!="string")return a("Selected field is not editable text");let m=Ia(u);if(d(m))return a("Failed to edit field");let g=m.value;return g===u?c("No changes made",null):Te({id:zu(),action:"edit.description",payload:{id:s.id,md:g},...e.value},n)};import qu from"node:fs";import Ta from"node:path";import Do from"node:fs";import Gu from"node:path";var Aa=async e=>{let t=Gu.join(e,".gitignore"),n=Do.existsSync(t)?Do.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
50
+ `;return ma.writeFileSync(A,R,"utf8"),c("Exported board layout",A)};import Uu from"node:os";import xa from"node:path";import{z as dt}from"zod";import{accessSync as Pu,copyFileSync as Lu,existsSync as fr,mkdirSync as ga,readdirSync as fa,readFileSync as ku,renameSync as Du,rmSync as Fu,statSync as va,unlinkSync as Ou,writeFileSync as Bu}from"node:fs";import Ht from"node:path";var ko=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",ve={writeToFile:(e,t)=>{try{let n=Ht.dirname(e);fr(n)||ga(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Bu(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return ku(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=ve.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 fr(e)&&va(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Pu(e),!0}catch{return!1}},mkDir:e=>ga(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Ht.parse(t);for(;;){let r=Ht.join(t,e);try{if(fr(r)&&va(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Ht.dirname(t)}return null},readFirstJSON(e){try{if(!ve.dirExists(e))return null;let t=fa(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Ht.join(e,t);return ve.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return ve.dirExists(e)?fa(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Ou(e)}catch(t){(!ko(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Fu(e,{recursive:!0,force:!0})}catch(t){(!ko(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Ht.dirname(t)),!n?.overwrite&&fr(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Du(e,t)}catch(r){if(ko(r)&&r.code==="EXDEV"){Lu(e,t),this.rmFile(e);return}throw r}}};var $u={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},ha=dt.object({logLevel:dt.enum(["info","error","debug"]),preferredEditor:dt.string().optional(),userName:dt.string().optional(),userId:dt.string().optional(),autoSync:dt.boolean().nullable().optional(),autoSyncDebounceMs:dt.number().optional(),viewMode:dt.enum(["dense","wide"]).optional()}).partial(),_u="config.json",ya=()=>xa.join(Uu.homedir(),he),Do=()=>xa.join(ya(),_u),Fo=()=>{try{return ve.mkDir(ya()),c(`Ensured ~/${he} exists`,null)}catch{return a(`Unable to create ~/${he}`)}},Wu=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${he}/config.json JSON`)}let n=ha.safeParse(t??{});return n.success?c("Parsed config",n.data):a(`Invalid ~/${he}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Ca=()=>{let e=Fo();if(d(e))return a(e.message);let t=Do(),n=ve.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Wu(n)},Ea=e=>{let t=Fo();if(d(t))return a(t.message);let n=ha.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Do();try{return ve.writeToFile(r,JSON.stringify(n.data,null,2)+`
51
+ `),c("Config written",null)}catch{return a(`Unable to write ~/${he}/config.json`)}},ze=e=>{let t=Ca();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return Ea(n)},Na=()=>{let e=Do(),t=Fo();if(d(t))return a(`Unable to create ~/${he}`);if(!(ve.readFile(e)!==null)){let g=Ea($u);if(d(g))throw new Error(`Unable to create ~/${he}/config.json`)}let r=Ca();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:s,autoSync:l,autoSyncDebounceMs:u,logLevel:m}=r.value;return!i||!s?a(`User name or ID not configured in ~/${he}/config.json`):(process.env.EPIQ_LOG_LEVEL=m,c("successfully loaded settings",{logLevel:m??"debug",preferredEditor:o??"",userName:i,userId:s,autoSync:l??!1,autoSyncIntervalMs:u??1e4,viewMode:"dense"}))};var ba=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};import{useSyncExternalStore as _E}from"react";var vr,Hu=new Set,Sa=()=>{for(let e of Hu)e()};var ct=()=>{if(!vr)throw new Error("Ui state not initialized. Call initUiState() first.");return vr};var Ia=(e={})=>(vr=e,Sa(),c("UX state initialized",null)),ju=e=>{let t=ct();return vr=e(t),Sa(),c("UX state updated",null)},lt=e=>ju(t=>({...t,...e}));import{spawn as Vu}from"node:child_process";function Oo(e){let t=process.platform,o=Vu(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}import{ulid as Xu}from"ulid";import{spawnSync as Ku}from"node:child_process";import zu from"node:os";import Ra from"node:path";import{ulid as Gu}from"ulid";function qu(){let{preferredEditor:e}=$(),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(zu.tmpdir(),"epiq");ve.mkDir(t);let n=Ra.join(t,Gu());ve.writeToFile(n,e??"");let r=qu();for(let o of r){let i=Yu(o,n),s=Ku(i,{stdio:"inherit",shell:!0});if(!s.error&&s.status===0){let l=ve.readFile(n);if(l==null)return a("Unable to read edited file");let u=l.replace(/\r?\n$/,"");return c("Successfully edited",u)}}return a("Unable to open editor")}var Ta=async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let t=await Re();if(d(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=v(),i=Ee([...r,o],"TICKET");if(d(i))return a("Edit target must be an issue");let s=i.value;if(!B(s))return a("Edit target must be an issue");if(s.readonly)return a("Cannot edit readonly issue");let l=_(s.id).find(h=>h.title===Q.DESCRIPTION);if(!l)return a("No target found");if(l.readonly)return a("Cannot edit readonly field");let u=s.props.description??"";if(typeof u!="string")return a("Selected field is not editable text");let m=Aa(u);if(d(m))return a("Failed to edit field");let g=m.value;return g===u?c("No changes made",null):Te({id:Xu(),action:"edit.description",payload:{id:s.id,md:g},...e.value},n)};import Qu from"node:fs";import Ma from"node:path";import Bo from"node:fs";import Ju from"node:path";var wa=async e=>{let t=Ju.join(e,".gitignore"),n=Bo.existsSync(t)?Bo.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
52
52
  `).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(`
53
53
  `);return n=n.trimEnd()+`
54
54
 
55
55
  ${l}
56
- `,Do.writeFileSync(t,n,"utf8"),ae.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)};var Yu=async e=>{let t=await D({cwd:e,args:["status","--porcelain"]});return d(t)?t:c("Checked git diff",t.value.stdout.trim().length>0)},j=(e,t)=>a(`[${e}] ${t}`),wa=async()=>{O("");let e=ti(),t=await Je(process.cwd());if(d(t))return j(1,t.message);let n=t.value,r=await Mn(n);if(d(r))return j(2,r.message);if(r.value)return j(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await Yu(n);if(d(o))return j(2.5,o.message);if(o.value)return j(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(Br(n))return j(4,"Epiq project already initialized");let i=Ze();if(!i.isSetupDone||!i.userName)return j(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let s=U(),l=s.userName,u=s.userId;if(!u||!l)return j(5,"Missing Epiq user id");let m=e.stateBranch,g=await Ln({repoRoot:n,branch:m});if(d(g))return j(6,g.message);if(g.value)return j(6,`State branch already exists: ${m}`);let y=await uo({repoRoot:n,stateBranchName:m});if(d(y))return j(6,y.message);let C=Fn();if(d(C))return j(7,C.message);let I=Ta.join(Dn(),e.projectId),S=await mo({repoRoot:n,stateBranchRoot:I,stateBranchName:m});if(d(S))return j(8,S.message);let A=Ta.join(I,".epiq");qu.mkdirSync(A,{recursive:!0});let R=xs({userId:u,userName:l});if(d(R))return j(9,R.message);for(let Fr of R.value){let Qo=Vn({event:Fr,rootDir:I});if(d(Qo))return j(9,Qo.message)}let M=await Yn({stateBranchRoot:I,eventFileName:on({userId:u,userName:l})});if(d(M))return j(10,M.message);let F=await Tt({cwd:I,message:"[epiq:init]"});if(d(F))return j(10,F.message);let Ie=await Aa(n);if(d(Ie))return j(11,Ie.message);let le=ri({repoRoot:n,fileContents:e});if(d(le))return j(12,le.message);let Vt=await G.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d(Vt))return j(13,Vt.message);let bn=await G.commit({cwd:n,message:"[epiq:init-project]"});if(d(bn))return j(13,bn.message);let It="Project initialized!",Kt=await D({cwd:n,args:["push","-u","origin","HEAD"]});d(Kt)&&(It+=` Warn: [init:14] ${Kt.message}`);let re=await dn({repoRoot:n,stateBranchRoot:I});d(re)&&(It+=` Warn: [init:15] ${re.message}`);let Rt=ht(R.value).filter(d);if(Rt.length>0)return j(16,Rt.map(Fr=>Fr.message).join(`
57
- `));let ft=ot();if(d(ft))return j(16,ft.message);let{rootNodeId:$d,nodes:_d}=ft.value,Jo=_d[$d];return Jo?(T.navigate({contextNode:Jo,selectedIndex:0}),N({hasProjectDefinition:!0,mode:p.DEFAULT}),c(It,null)):j(16,"Unable to resolve initialized root node")};import{ulid as Ju}from"ulid";import{ulid as Xu}from"ulid";var Ma=null,ut=()=>structuredClone(Ma),pn=e=>{Ma=e},Pa=()=>{let{contextNode:e,selectedIndex:t}=v(),r=B(e.id)[t];return r?c("Resolved selected child",r):a("Target node not found")},Fo=({id:e,parentId:t,position:n={at:"end"}})=>{let r=B(t).filter(o=>o.id!==e);return Kn(r,n)},La=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Y();if(d(r))return a("Unable to resolve user ID");let o=Fo({parentId:t,id:e,position:n});return d(o)?o:c("Created pending move state",{id:Xu(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},ka=e=>{pn(e);let t=tn(e,!0);return d(t)?t:c("Node moved successfully",t.value)};function Bo(e){let t=Pa();if(d(t))return t;let{contextNode:n,nodes:r}=v();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let i=B(o.id),s=i.findIndex(({id:m})=>m===n.id);if(s<0)return a("Current node not found among siblings");let l=i[s+e];if(!l)return a("Missing sibling node");let u=La({id:t.value.id,parentId:l.id,position:{at:"end"}});return d(u)?u:ka(u.value)}function Uo(e){let t=Pa();if(d(t))return t;let{contextNode:n,selectedIndex:r}=v(),i=B(n.id)[r+e];if(!i)return a("Missing sibling node");let s=La({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(s)?s:ka(s.value)}var Da=()=>{let e=ut();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=v().nodes[n];if(!r)return a("Move parent not found");let o=B(n).findIndex(i=>i.id===t);return o===-1?a("Moved node not found among rendered children"):(T.navigate({contextNode:r,selectedIndex:o}),c("Synchronized navigation to moved node",null))},fr=(e,t="Moved preview")=>{if(d(e))return e;let n=Da();return d(n)?n:(N({mode:p.MOVE}),c(t,null))},Fa=async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=V().commandMeta,{contextNode:n,selectedIndex:r}=v(),o=B(n.id)[r];if(!o)return N({mode:p.DEFAULT}),a("No move target");if(t==="start"){if(o.readonly)return a("Target node is read-only");if(r===-1)return a("No item selected");if(!o.parentNodeId)return a("Target has no parent");let i=B(o.parentNodeId),s=i.findIndex(({id:y})=>y===o.id);if(s===-1)return a("Target not found among siblings");let l=i[s-1],u=i[s+1],m=u!=null?{at:"before",sibling:u.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},g=Fo({parentId:o.parentNodeId,id:o.id,position:m});return d(g)?g:(pn({id:Ju(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:g.value.rank},...e.value}),N({mode:p.MOVE}),c("Move initialized",null))}if(t==="next")return fr(Uo(1));if(t==="previous")return fr(Uo(-1));if(t==="to-next")return fr(Bo(1));if(t==="to-previous")return fr(Bo(-1));if(t==="confirm"){let i=ut();if(!i)return a("No pending move to confirm");let s=await Re();if(d(s))return s;let l=Te(i,s.value);if(d(l))return l;let u=Da();return d(u)?u:(pn(null),N({mode:p.DEFAULT}),c("Moved item",null))}return t==="cancel"?(pn(null),N({mode:p.DEFAULT}),c("Cancelling move",null)):a("Invalid move modifier")};import{ulid as vr}from"ulid";import{monotonicFactory as Qu,ulid as Zu}from"ulid";var em=Qu(),Ba=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=em();return c("Created issue events",[{id:Zu(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}}])};var Ua=async(e,t)=>{let n=Y();if(d(n))return a("Unable to resolve user ID");let r=await Re();if(d(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:i,contextNode:s,selectedIndex:l}=v(),u=m=>{let g=Te(m,o);if(d(g))return g;let y=b.getNode(g.value.result.id);if(!y)return a("Created node not found");if(!y.parentNodeId)return g;let C=b.getNode(y.parentNodeId);return C?(T.navigate({contextNode:C,selectedIndex:b.getSiblings(y.parentNodeId).findIndex(({id:I})=>I===y.id)}),g):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=v(),g=b.getNode(m);if(!g)return a("Workspace not found");let y=zn(g.id,n.value,o);return d(y)?y:u({id:vr(),action:"add.board",payload:{id:vr(),name:t.inputString,parent:g.id,rank:y.value},...n.value})}if(t.modifier==="swimlane"){let m=Ce(i,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let g=zn(m.value.id,n.value,o);return d(g)?g:u({id:vr(),action:"add.swimlane",payload:{id:vr(),name:t.inputString,parent:m.value.id,rank:g.value},...n.value})}if(t.modifier==="issue"){let m=_(s.id)[l],g=s.context==="SWIMLANE"?s:s.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let F=Ce(i,"SWIMLANE");return d(F)?null:F.value})();if(!g)return a("Unable to add issue in this context");let y=zn(g.id,n.value,o);if(d(y))return y;let C=Ba({name:t.inputString,parent:g.id,rank:y.value,user:n.value});if(d(C))return C;let I=C.value,S=ss(I,o);if(S.some(F=>d(F)))return a("Issue create failed: "+S.filter(d).map(F=>F.message).filter(Boolean).join(", "));let A=S[0];if(!A||d(A))return a("Issue creation failed");let M=I.find(F=>F.action==="add.issue")?.payload.id;return M?(T.navigate({contextNode:g,selectedIndex:b.getSiblings(g.id).findIndex(({id:F})=>F===M)}),c("Issue created",null)):a("Unable to determine ticket id")}return c("Success",null)};var Oa=async()=>{let e=Ce(v().breadCrumb,"BOARD");if(d(e))return e;let t=await Je(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Xe({repoRoot:t.value});if(d(n))throw new Error(n.message);let{modifier:r}=V().commandMeta;if(r==="now"){let S=Lt(n.value);if(d(S))return a(S.message);let A=gn();if(d(A))return A;let M=ht(S.value).filter(d);return M.length>0?a(M.map(F=>F.message).join(", ")):(N({mode:p.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}let o;if(r==="prev"){let S=v().eventLog.at(-1),A=to(S);if(A===null)return a("No previous event to peek");o=A}else if(r==="next"){let S=v().unappliedEvents.at(0),A=to(S);if(A===null)return a("No next event to peek");o=A+1}else{let S=er(r);if(!S)return a("Invalid peek date");o=S.getTime()}let i=v(),s=e.value.id,l=ts(n.value,o);if(d(l))return a(l.message);let{appliedEvents:u,unappliedEvents:m}=l.value,g=gn();if(d(g))return g;let C=ht(u).filter(d);if(C.length>0)return gn(),N(i),a(C.map(S=>S.message).join(", "));let I=v().nodes[s];return I?(T.navigate({contextNode:I,selectedIndex:0}),N({mode:p.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:m}),c("Peeking",!0)):(gn(),N(i),a("Board did not exist at peek date"))};import tm from"zod";var $a=()=>{let e=V().commandMeta.inputString,t=tm.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return a("Auto sync duration must be a number of at least 3000 ms");let n=ze({autoSyncDebounceMs:t.data});return d(n)?n:(Ee({autoSyncIntervalMs:t.data}),N({mode:p.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))};var _a=()=>{let e=V().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Si(e),n=ze({autoSync:t});return d(n)?n:(Ee({autoSync:t}),N({mode:p.DEFAULT}),c(`Auto sync set to "${e}"`,null))};var Wa=()=>{let e=V().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=ze({logLevel:e});return d(n)?n:(Ee({logLevel:e}),N({mode:p.DEFAULT}),c(`Auto sync set to "${e}"`,null))};var Ha=async()=>{O(""),N({mode:p.DEFAULT});let e=ot();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");N({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Xn();return d(t)?(N({syncStatus:{msg:t.message,status:"failed"}}),t):(N({mode:p.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var ja=e=>Object.values(v().tags).find(t=>t.name===e),Va=e=>Object.values(v().contributors).find(t=>t.name===e),xr=[{systemOnly:!0,intent:P.Move,description:"Internal move-state command",mode:p.COMMAND_LINE,action:Fa},{intent:P.Delete,description:"Delete the currently selected node",mode:p.COMMAND_LINE,action:async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=_(t.id)[n];return r?Se({id:fe(),action:"delete.node",payload:{id:r.id},...e.value}):a("Unable to resolve child to delete")},onSuccess:()=>N({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}=V().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(s=>ee(x.FILTER).map(l=>l.split(n)[0]).includes(s))(r))return a("Invalid filter modifier");let i={target:r,operator:"=",value:t.trim()};return Ne(s=>({...s,filters:e==="clear"?[]:[...s.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 lt({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),N({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=Y();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=_(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!$(r))return a("Cannot close in this context");let o=v().nodes[He];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let i=await Re();if(d(i))return i;let s=i.value,l=ao(o.id,r.id,{at:"end"},e.value,s);if(d(l))return l;let u=await Se({id:fe(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...e.value});return d(u)?u:c("Issue closed",null)},onSuccess:()=>N({mode:p.DEFAULT})},{intent:P.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:p.COMMAND_LINE,action:async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=_(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):nt(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let i=o.value,s=v().nodes[He];if(!s)return a("Unable to locate closed swimlane");if(i.parentNodeId!==s.id)return a("Issue is not closed");if(!$(i))return a("Target node is not issue");let l=Ca(i);if(!l)return a("Unable to resolve previous parent from issue history");if(l===s.id)return a("Previous parent resolves to closed swimlane");let u=v().nodes[l];if(!u)return a("Previous parent no longer exists");let m=await Re();if(d(m))return m;let g=m.value,y=ao(u.id,i.id,{at:"end"},e.value,g);if(d(y))return y;let C=await Se({id:fe(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:y.value},...e.value});return d(C)?C:c("Issue reopened",null)},onSuccess:()=>N({mode:p.DEFAULT})},{intent:P.Init,description:"Initialize Epiq in the current git repository",mode:p.COMMAND_LINE,action:wa},{intent:P.NewItem,description:"Create a new board, swimlane, or issue",mode:p.COMMAND_LINE,action:Ua,onSuccess:()=>N({mode:p.DEFAULT})},{intent:P.Rename,description:"itle] Rename the currently selected node",mode:p.COMMAND_LINE,action:async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=_(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=Ys();return o?Se({id:fe(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):a("Provide a title")},onSuccess:()=>N({mode:p.DEFAULT})},{intent:P.UntagTicket,description:"Remove a tag from the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=V().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=ja(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return a("Invalid untag target");let s=nt(i.id,"TICKET");if(d(s))return a("Unable to untag issue in this context");let l=s.value;return $(l)?(l.props.tags??[]).includes(o.id)?Se({id:fe(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...e.value}):a("Issue is not tagged with that tag"):a("Target node is not issue")},onSuccess:()=>N({mode:p.DEFAULT})},{intent:P.TagTicket,description:"Add or create a tag on the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=V().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=v();if(!o)return a("Invalid tag target");let i=nt(o.id,"TICKET");if(d(i))return a("Unable to tag issue in this context");let s=i.value;if(!$(s))return a("Target node is not issue");let l=ja(r),u;if(l)u=l.id;else{let g=fe(),y=await Se({id:fe(),action:"create.tag",payload:{id:g,name:r},...e.value});if(d(y))return y;u=y.value.result.id}return(s.props.tags??[]).includes(u)?a("Already tagged with that tag"):Se({id:fe(),action:"add.issue.tag",payload:{id:s.id,tag:u},...e.value})},onSuccess:()=>N({mode:p.DEFAULT})},{intent:P.AssignUserToTicket,description:"Assign a user to the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=V().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let{selectedIndex:o,contextNode:i}=v(),s=_(i.id)[o];if(!s)return a("Invalid assign target");let l=nt(s.id,"TICKET");if(d(l))return a("Unable to assign issue in this context");let u=l.value;if(!$(u))return a("Target node is not issue");let m=Va(r),g;if(m)g=m.id;else{let C=fe(),I=await Se({id:fe(),action:"create.contributor",payload:{id:C,name:r},...e.value});if(d(I))return I;g=I.value.result.id}return(u.props.assignees??[]).includes(g)?a("Assignee already assigned"):Se({id:fe(),action:"add.issue.assignee",payload:{id:u.id,assignee:g},...e.value})},onSuccess:()=>N({mode:p.DEFAULT})},{intent:P.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=V().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let o=Va(r);if(!o)return a(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return a("Invalid unassign target");let s=nt(i.id,"TICKET");if(d(s))return a("Unable to unassign in this context");let l=s.value;return $(l)?(l.props.assignees??[]).includes(o.id)?Se({id:fe(),action:"remove.issue.assignee",payload:{id:l.id,assignee:o.id},...e.value}):a(`Issue is not assigned to "${r}"`):a("Target node is not issue")},onSuccess:()=>N({mode:p.DEFAULT})},{intent:P.Sync,description:"Pull, commit, and push Epiq state",mode:p.COMMAND_LINE,action:Ha},{intent:P.Peek,description:"View board state at another point in time",mode:p.COMMAND_LINE,action:Oa},{intent:P.Export,description:"Export the current board layout to markdown",mode:p.COMMAND_LINE,action:async()=>{let e=await ua();return d(e)?e:(N({mode:p.DEFAULT}),c("Export successful",!0))}},{intent:P.Exit,description:"Exit the application",mode:p.COMMAND_LINE,action:async()=>(T.exit(),c("Exit successful",!0))},{intent:P.Edit,description:"Edit title or description",mode:p.COMMAND_LINE,action:async(e,t)=>{if(t.modifier===it.DESCRIPTION)return Ra();if(t.modifier===it.TITLE){let n=Y();if(d(n))return a("Unable to resolve user ID");let{contextNode:r,selectedIndex:o}=v(),i=_(r.id)[o];if(!i)return a("Missing node");if(i.readonly)return a("Cannot rename readonly node");let s=t.inputString.trim();return s?Se({id:fe(),action:"edit.title",payload:{id:i.id,name:s},...n.value}):a("Provide a title")}return a("Unknown edit command")},onSuccess:()=>N({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}=U(),s=n||i,l=r??fe();if(!s||!l)return a("Unable to resolve user name or id");let u=ze({userName:s,userId:l,preferredEditor:o??""});return d(u)?u:(Ee({userName:s,userId:l}),N({mode:p.DEFAULT}),c(`Username set to "${s}"`,null))}case X.EDITOR:{if(!n)return a("No editor provided");let r=ze({preferredEditor:n});return d(r)?r:(Ee({preferredEditor:n}),N({mode:p.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case X.VIEW:return n!=="wide"&&n!=="dense"?a("Invalid view mode"):(Ee({viewMode:n}),c(`View set to "${n}"`,null));case X.AUTOSYNC:return _a();case X.LOG_LEVEL:return Wa();case X.SYNC_DEBOUNCE_MS:return $a();default:return a("Unknown config command")}}}];var nm=new Set(["peek","filter","view-help"]),Be=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=V();if(!t)return a("No command to confirm");if(!e&&n===Ct.Invalid)return a("Invalid command");let i=ir(t);Vs();let{readOnly:s}=v();if(s&&!nm.has(i))return un({status:qe.Fail,message:"Command not available in readonly state",value:null});let l=xr.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===i);if(!l)return un({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 un({status:qe.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?un(u):(Ks({addToHistory:!e}),l.onSuccess?.(),U().autoSync&&Jn(),u)};var yr=[{intent:f.Exit,mode:p.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(N({mode:p.COMMAND_LINE}),O("move cancel"),Be({isForceExecutedBySystem:!0}))},{intent:f.InitMove,mode:p.DEFAULT,description:"[m] move (init/confirm)",action:()=>(N({mode:p.COMMAND_LINE}),O("move start"),Be({isForceExecutedBySystem:!0}))},{intent:f.ConfirmMove,mode:p.MOVE,action:()=>(N({mode:p.COMMAND_LINE}),O("move confirm"),Be({isForceExecutedBySystem:!0}))}],hr=[{intent:f.MovePreviousItem,mode:p.MOVE,action:()=>ut()?(N({mode:p.COMMAND_LINE}),O("move previous"),Be({isForceExecutedBySystem:!0})):a("No pending move")},{intent:f.MoveNextItem,mode:p.MOVE,action:()=>ut()?(N({mode:p.COMMAND_LINE}),O("move next"),Be({isForceExecutedBySystem:!0})):a("No pending move")}],Ka=[{intent:f.MoveToNextContainer,mode:p.MOVE,action:()=>ut()?(N({mode:p.COMMAND_LINE}),O("move to-next"),Be({isForceExecutedBySystem:!0})):a("No pending move")},{intent:f.MoveToPreviousContainer,mode:p.MOVE,action:()=>ut()?(N({mode:p.COMMAND_LINE}),O("move to-previous"),Be({isForceExecutedBySystem:!0})):a("No pending move")}];var za={[w.WORKSPACE]:[...yr,...hr],[w.BOARD]:[...yr,...hr],[w.SWIMLANE]:[...yr,...hr,...Ka],[w.TICKET]:[],[w.FIELD]:[],[w.FIELD_LIST]:[],[w.TEXT]:[]};var Ga=()=>{O("");let{pendingNavTarget:e}=ct();N({mode:p.DEFAULT}),e&&T.navigate(e),lt({pendingNavTarget:void 0})},qa=[{intent:f.ExitCommandLine,mode:p.HELP,action:()=>(Ga(),c("Exiting help",null))},{intent:f.Exit,mode:p.HELP,action:()=>(Ga(),c("Closed help",null))},{intent:f.NavPreviousItem,mode:p.HELP,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:f.NavNextItem,mode:p.HELP,action:()=>(T.navigateToNextItem(),c("Navigating to next help item",null))},{intent:f.NavToPreviousContainer,mode:p.HELP,action:()=>(T.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:f.NavToNextContainer,mode:p.HELP,action:()=>(T.navigateToNextContainer(),c("Navigating to next help container",null))}];var rm=e=>{N({mode:p.COMMAND_LINE});let{pendingNavTarget:t}=ct();t&&T.navigate(t),lt({pendingNavTarget:void 0}),O(`${e} `)},Ya=()=>{O("");let{pendingNavTarget:e}=ct();e&&T.navigate(e),lt({pendingNavTarget:void 0}),N({mode:p.DEFAULT})},Xa=[{intent:f.InitCommandPalette,mode:p.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{O("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return lt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),N({mode:p.PALETTE}),c("Opening command palette",null)}},{intent:f.Confirm,mode:p.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!et(e))return a("Command only applicable on text nodes");if(e.props.disabled)return a("Command is not available in this context");let t=e.title;return t?(rm(t),c("Selected command",t)):c("No command selected",null)}},{intent:f.ExitCommandLine,mode:p.PALETTE,action:()=>(Ya(),c("Exiting palette",null))},{intent:f.Exit,mode:p.PALETTE,action:()=>(Ya(),c("Closed command palette",null))},{intent:f.NavPreviousItem,mode:p.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:f.NavNextItem,mode:p.PALETTE,action:()=>(T.navigateToNextItem(),c("Navigating to next item",null))},{intent:f.NavToPreviousContainer,mode:p.PALETTE,action:()=>(T.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:f.NavToNextContainer,mode:p.PALETTE,action:()=>(T.navigateToNextContainer(),c("Navigating to next container",null))}];var Ja=[...qa,...Xa,{intent:f.AddItem,mode:p.DEFAULT,description:"[n] new...",action:()=>(N({mode:p.COMMAND_LINE}),O(`${x.NEW} `),c("Adding new item",null))},{intent:f.Delete,mode:p.DEFAULT,description:"[d] delete",action:()=>(N({mode:p.COMMAND_LINE}),O(`${x.DELETE} `),c("Deleting item",null))},{intent:f.InitCommandLine,mode:p.DEFAULT,description:"[:] focus command line",action:()=>(N({mode:p.COMMAND_LINE}),O(""),c("Entering command line mode",null))},{intent:f.Confirm,mode:p.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!B(e?.id??"")?.length){if(e?.title===Q.DESCRIPTION)return N({mode:p.COMMAND_LINE}),O(`${x.EDIT} description `),c("Propose command",!0);if(e?.title===Q.ASSIGNEES)return N({mode:p.COMMAND_LINE}),O(`${x.ASSIGN} `),c("Propose command",!0);if(e?.title===Q.TAGS)return N({mode:p.COMMAND_LINE}),O(`${x.TAG} `),c("Propose command",!0);if(t.title===Q.DESCRIPTION&&e?.context==="TEXT")return N({mode:p.COMMAND_LINE}),O(`${x.EDIT} description `),c("Propose command",!0)}return T.enterChildNode(),c("Entering context",null)}},{intent:f.EditTitle,mode:p.DEFAULT,description:"[r] rename title",action:()=>(N({mode:p.COMMAND_LINE}),O(`${x.EDIT} title ${v().selectedNode?.title}`),c("Exiting context",null))},{intent:f.EditDescription,mode:p.DEFAULT,description:"[e] edit description",action:()=>(N({mode:p.COMMAND_LINE}),O(`${x.EDIT} description `),c("Exiting context",null))},{intent:f.Exit,mode:p.DEFAULT,description:"[q] exit context",action:()=>(T.enterParentNode(),c("Exiting context",null))},{intent:f.NavPreviousItem,mode:p.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:f.NavNextItem,mode:p.DEFAULT,action:()=>(T.navigateToNextItem(),c("Navigating to next item",null))},{intent:f.NavToPreviousContainer,mode:p.DEFAULT,action:()=>(T.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:f.NavToNextContainer,mode:p.DEFAULT,action:()=>(T.navigateToNextContainer(),c("Navigating to next container",null))}];var om=500,im=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Qa=e=>{let t=im(e);t&&or(n=>(n+t).slice(0,om))};var sm=[p.COMMAND_LINE,p.PALETTE],am=e=>[{intent:f.MoveCursorLeft,mode:e,action:()=>(So(-1),c("Moving cursor left",null))},{intent:f.MoveCursorRight,mode:e,action:()=>(So(1),c("Moving cursor right",null))},{intent:f.MoveCursorLeftOfWord,mode:e,action:()=>(Io("left"),c("Moving cursor left of word",null))},{intent:f.MoveCursorRightOfWord,mode:e,action:()=>(Io("right"),c("Moving cursor right of word",null))},{intent:f.AutoCompleteCommand,mode:e,action:()=>(or((t,{remainder:n})=>n?t+n:t),c("Auto-completing command",null))},{intent:f.CaptureInput,mode:e,action:(t,{sequence:n})=>(Qa(n??""),c("Capturing input",null))},{intent:f.EraseInput,mode:e,action:()=>(Hs(),c("Erasing input",null))},{intent:f.EraseInputWord,mode:e,action:()=>(js(),c("Erasing input word",null))}],Za=[{intent:f.Confirm,mode:p.COMMAND_LINE,action:()=>(Be(),c("Executing command",null))},{intent:f.ViewHelp,mode:p.DEFAULT,action:()=>(N({mode:p.HELP}),c("Viewing help",null))},...sm.flatMap(am),{intent:f.ExitCommandLine,mode:p.COMMAND_LINE,action:()=>(N({mode:p.DEFAULT}),c("Exiting command line",null))},{intent:f.GetLastCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(zs(),c("Getting last command from history",null))},{intent:f.GetNextCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(Gs(),c("Getting next command from history",null))}];import nd from"chalk";var Er=nd.dim.hex(h.secondary2)(": for command line"),ed="q to exit",td=`${nd.hex(h.accent)("m")} to confirm`,Oo={[w.WORKSPACE]:[Er],[w.BOARD]:[Er],[w.BOARD+p.COMMAND_LINE]:[Er],[w.SWIMLANE]:[Er],[w.TICKET+p.HELP]:[ed],[w.SWIMLANE+p.HELP]:[ed],[w.TICKET]:[],[w.FIELD]:[],[w.SWIMLANE+p.MOVE]:[td],[w.TICKET+p.MOVE]:[td]};var fn=e=>e.trim().toLocaleLowerCase(),dm=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},cm=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},rd=(e,t)=>{let n=fn(t.value);if(!n)return!0;switch(t.target){case"title":return fn(e.title??"").includes(n);case"description":return fn(e.props.description??"").includes(n);case"tag":return dm(e).map(fn).some(o=>o.includes(n));case"assignee":return cm(e).map(fn).some(o=>o.includes(n));default:return!0}};function od(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],i=r;for(;i&&(o.push(i),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let s=o[o.length-1];return!s||s.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var id=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var bt,$o,_o=new Set,sd=()=>{for(let e of _o)e()},um=e=>(_o.add(e),()=>_o.delete(e));function ad(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return a("derive(): contextNodeId is missing");if(!r)return a("derive(): rootNode is missing");if(!o[r])return a("derive(): unable to find root node");let l=o[t];if(!l)return a("Unable to derive state, contextNode not found");let u=od(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:g}=l,y=Oo[g+n]??Oo[g]??[],C=[...Ja,...za[g]??[],...Za],I=id(C),S=mm(o,i),A=S[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:y,availableActions:C,actionIndex:I,selectedNode:A,renderedChildrenIndex:S})}var v=()=>{if(!bt)throw new Error("State not initialized. Call initWorkspaceState() first.");return bt},ot=()=>bt?c("Retrieved state",bt):a("State not initialized. Call initWorkspaceState() first.");function nn(e){$o=e;let t=Ye(process.cwd()),n=!1;if(!d(t)){let i=Qe(t.value);if(d(i))return a(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=ad(r);return d(o)?o:(bt=o.value,sd(),c("State initialized",null))}function Ne(e){let t=v(),n=e(t),r=ad(n);return d(r)?a(r.message??"Unable to update state"):(bt=r.value,sd(),c("State updated",null))}var N=e=>Ne(t=>({...t,...e}));var K=()=>lm(um,v,v),mm=(e,t)=>{let n={};for(let r of Object.values(e))$(r)&&t.length>0&&!t.every(o=>rd(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 s=e[o.id],l=e[i.id];return!s||!l?0:s.rank.localeCompare(l.rank)});return n},_=e=>v()?.renderedChildrenIndex[e]??[],gn=()=>$o?nn($o):a("Cannot reset state: no initial workspace found"),Dt=()=>bt!==void 0;import{Box as Wo,Text as vn}from"ink";import Me,{useEffect as pm,useMemo as gm}from"react";import{ulid as fm}from"ulid";var dd=({text:e,match:t,color:n,highlightColor:r=h.secondary,dimColor:o=!1})=>{if(!t)return Me.createElement(vn,{color:n,dimColor:o},e);let i=e.toLowerCase(),s=t.toLowerCase(),l=i.indexOf(s);return l===-1?Me.createElement(vn,{color:n,dimColor:o},e):Me.createElement(vn,{color:n,dimColor:o},e.slice(0,l),Me.createElement(vn,{backgroundColor:r,bold:!0},e.slice(l,l+t.length)),e.slice(l+t.length))},cd=fm(),vm=e=>`${e}`,xm=e=>{let{pendingNavTarget:t}=ct();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,i=new Set(ee(x.NONE,{breadCrumb:n,contextNode:r,readOnly:v().readOnly,selectedNode:o}));return[...new Set(Object.values(x))].filter(s=>s!=="move").filter(s=>s.length>0).filter(s=>s!==x.PALETTE).map(s=>{let l=ir(s),u=xr.find(m=>m.intent===l);return{command:s,description:u?.description??`[${s}] Run command`,isAvailable:i.has(s)}}).filter(s=>s.command.toLowerCase().startsWith(e)||e.length>=2&&s.description.toLowerCase().includes(e)).sort((s,l)=>s.isAvailable!==l.isAvailable?s.isAvailable?-1:1:s.command.localeCompare(l.command))},ym=e=>q.text({id:cd,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),hm=(e,t,n)=>q.text({id:vm(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Ho=[],Em=e=>{ld();let t=b.createNode(ym(v().rootNodeId));d(t)||!et(t.value)||(Ho=[t.value,...e.map((n,r)=>hm(n,r,cd)).map(b.createNode).filter(J).map(({value:n})=>n).filter(et)],T.navigate({contextNode:t.value,selectedIndex:0}))},ld=()=>{let e=Ho.map(t=>t.id);Ho=[];for(let t of e)b.deleteNode(t)};function ud({width:e,height:t}){let r=qs().value.trim().toLowerCase(),o=gm(()=>xm(r),[r]);pm(()=>(Em(o),()=>{ld()}),[o]);let i=v().selectedIndex;return Me.createElement(Wo,{flexDirection:"column",width:e,height:t-2},Me.createElement(st,{height:t-4,itemHeight:3,selectedIndex:i},o.map((s,l)=>{let u=l===i,m=s.isAvailable?h.accent:h.secondary2,g=s.isAvailable?"":"[unavailable] ";return Me.createElement(Wo,{key:s.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:h.secondary,borderStyle:"single"},Me.createElement(vn,{color:m,dimColor:!s.isAvailable},u?"\u276F ":" ",Me.createElement(dd,{text:Li(s.command),match:r,color:m,dimColor:!s.isAvailable})),Me.createElement(Wo,{paddingLeft:2},Me.createElement(dd,{text:g+s.description,match:r.length>=2?r:"",color:u&&s.isAvailable?h.primary:h.secondary2,dimColor:!s.isAvailable})))})))}import{Box as km}from"ink";import Vo from"react";import yn from"chalk";import{Box as jo,Text as md}from"ink";import xn,{useEffect as Cm,useMemo as Nm,useState as bm}from"react";var pd=yn.gray,Sm=yn.inverse,Im=yn.inverse.gray,Rm={hint:"",hints:[],overlap:0,remainder:""},fd=({value:e,command:t})=>{if(!t)return null;let n=e.trimStart(),o=e.length-n.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},Am=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=be(t);return{bg:r=>yn.bgHex(n).black(r),bgCursor:r=>yn.bgHex(n).inverse.black(r)}}return eo(t)},Tm=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=fd({value:e,command:t});if(!r)return null;let i=e.slice(r.end).match(/^\s*/)?.[0].length??0,s=r.end+i;return e.slice(s,s+n.length)!==n?null:{start:s,end:s+n.length}},gd=()=>({value:ie.value,cursorPosition:ie.cursorPosition,commandIsPending:ie.commandIsPending,autoCompletion:ie.commandMeta.autoCompletion??Rm,infoMessage:ie.commandMeta.infoMessage,validationStatus:ie.commandMeta.validity,command:ie.commandMeta.command,inputString:ie.commandMeta.inputString,modifier:ie.commandMeta.modifier}),wm=(e,t)=>e.value===t.value&&e.cursorPosition===t.cursorPosition&&e.commandIsPending===t.commandIsPending&&e.infoMessage===t.infoMessage&&e.autoCompletion.hint===t.autoCompletion.hint&&e.autoCompletion.overlap===t.autoCompletion.overlap&&e.autoCompletion.remainder===t.autoCompletion.remainder&&e.validationStatus===t.validationStatus&&e.command===t.command&&e.modifier===t.modifier&&e.inputString===t.inputString,vd=({width:e,mode:t})=>{let[n,r]=bm(gd());Cm(()=>{let C=()=>{let S=gd();r(A=>wm(A,S)?A:S)},I=bo(C);return C(),()=>{I()}},[]);let{value:o,cursorPosition:i,infoMessage:s,commandIsPending:l,autoCompletion:u,command:m,modifier:g}=n,y=Nm(()=>{let C=Math.max(0,Math.min(i,o.length)),I=fd({value:o,command:m}),S=Tm({value:o,command:m,modifier:g}),A=m?eo(m):null,R=Am({command:m,modifier:g}),M=(re,ue)=>{let Rt=I&&ue>=I.start&&ue<I.end,ft=S&&ue>=S.start&&ue<S.end;return Rt&&A?A.fg(re):ft&&R?R.bg(re):re},F=(re,ue)=>{let Rt=I&&ue>=I.start&&ue<I.end,ft=S&&ue>=S.start&&ue<S.end;return Rt&&A?A.fgCursor(re):ft&&R?R.bgCursor(re):Sm(re)},Ie=o.slice(0,C),le=o[C]??" ",Vt=C<o.length?o.slice(C+1):"",bn=Array.from(Ie).map((re,ue)=>M(re,ue)).join(""),It=F(le,C),Kt=Array.from(Vt).map((re,ue)=>M(re,C+1+ue)).join("");if(u.hint){let re=u.hint[u.overlap]??le;It=Im(re),Kt=pd(u.remainder.slice(1)+Vt)}return pd(t===p.PALETTE?"?":":")+bn+It+Kt},[o,i,u,m,g]);return xn.createElement(jo,{flexDirection:"column",justifyContent:"flex-start"},xn.createElement(jo,{flexDirection:"column",paddingX:1,borderColor:h.secondary,borderStyle:"round",width:e},xn.createElement(jo,null,xn.createElement(md,null,y),s&&xn.createElement(md,{wrap:"truncate",color:l?h.red:h.secondary2},` ${s} `))))};import{Box as Mm,Text as Pm}from"ink";import xd from"react";var Lm=(e,t)=>{let n=[],r=0;for(let o of e){let s=(n.length>0?" | ":"").length+o.length;if(r+s>t-4)break;n.push(o),r+=s}return n},yd=({width:e,availableHints:t})=>{let n=Lm(t,e).join(" | ");return xd.createElement(Mm,{width:e,borderStyle:"round",borderColor:h.secondary,paddingX:1},xd.createElement(Pm,{color:h.secondary2},n.length?n:"\xA0"))};var hn=({width:e,mode:t,availableHints:n})=>{let r=[],o=0;for(let i of n){let l=(r.length>0?" | ":"").length+i.length;if(o+l>e+2)break;r.push(i),o+=l}return Vo.createElement(km,null,t===p.COMMAND_LINE||t===p.PALETTE?Vo.createElement(vd,{width:e,mode:t}):Vo.createElement(yd,{width:e,mode:t,availableHints:n}))};import{Box as mt,Text as Ht}from"ink";import ce,{useEffect as Dm,useMemo as Fm}from"react";import{ulid as hd}from"ulid";var Nr=hd(),Bm=()=>[...new Set([...v().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(e=>{let[t,n]=e.split("]"),r=t?.replace("[",""),o=n?.trim();return[r,o]}).filter(e=>e[0]!==void 0&&e[1]!==void 0).sort(([e],[t])=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(([e,t])=>({keys:e,action:t})),Um=e=>q.text({id:Nr,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),Om=(e,t,n)=>q.text({id:hd(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),Cr=[],Ed=()=>{let e=Cr.filter(n=>n.id!==Nr).map(n=>n.id),t=Cr.filter(n=>n.id===Nr).map(n=>n.id);Cr=[];for(let n of[...e,...t])b.deleteNode(n)},$m=e=>{Ed();let t=b.createNode(Um(v().rootNodeId));if(d(t)||!et(t.value))return logger.error("Could not attach help nodes");Cr=[t.value,...e.map((n,r)=>Om(n,r,Nr)).map(b.createNode).filter(J).map(({value:n})=>n).filter(et)],T.navigate({contextNode:t.value,selectedIndex:0})},Cd=({width:e,height:t})=>{let n=Fm(()=>Bm(),[]);Dm(()=>($m(n),()=>{Ed()}),[n]);let r=v().selectedIndex;return ce.createElement(mt,{flexDirection:"column",marginTop:3,borderColor:h.secondary,borderStyle:"round",width:e,height:t-2},ce.createElement(mt,{paddingX:1,justifyContent:"center"},ce.createElement(Ht,{color:h.accent},"Help"),ce.createElement(Ht,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),ce.createElement(mt,{paddingX:1,marginTop:1},ce.createElement(mt,{width:20,justifyContent:"flex-end"},ce.createElement(Ht,{color:h.secondary},"Key(s)")),ce.createElement(mt,{flexGrow:1,width:40,paddingLeft:2},ce.createElement(Ht,{color:h.secondary},"Action"))),ce.createElement(st,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:i},s)=>{let l=s===r;return ce.createElement(mt,{paddingX:1,key:`${o}-${i}-${s}`,flexDirection:"row"},ce.createElement(mt,{width:20,justifyContent:"flex-end"},ce.createElement(Ht,{color:h.accent},o)),ce.createElement(mt,{flexGrow:1,width:40,paddingLeft:2},ce.createElement(Ht,{color:l?h.primary:h.secondary2},i)))})))};import _m from"chalk";import{Box as br,Text as Ge}from"ink";import xe from"react";var Nd=({width:e,height:t})=>xe.createElement(br,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},xe.createElement(Ge,{color:h.accent,bold:!0},"Initialize project"),xe.createElement(Ge,null,`This folder is not an ${_m.hex(h.accent)("epiq")} project yet.`),xe.createElement(Ge,{color:h.primary},"To start tracking issues here, we need to initialize a new",xe.createElement(Ge,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json "),"file in this repository."),xe.createElement(br,{marginTop:1,flexDirection:"column"},xe.createElement(br,null,xe.createElement(Ge,{color:h.accent}," "),xe.createElement(Ge,{color:h.primary},"Type "),xe.createElement(Ge,{backgroundColor:h.secondary}," :init "))),xe.createElement(br,{marginTop:1},xe.createElement(Ge,{color:h.secondary2},"This will create, commit and push "),xe.createElement(Ge,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json ")));import{Box as Sr,Text as Ue}from"ink";import ne from"react";var Wm=({isDone:e,command:t,value:n})=>ne.createElement(Sr,null,ne.createElement(Ue,{color:h.accent,dimColor:e},e?" \u2714 ":" "),ne.createElement(Ue,{dimColor:e},"Type "),ne.createElement(Ue,{backgroundColor:h.secondary,dimColor:e}," "+t+" "),n!==void 0&&ne.createElement(ne.Fragment,null,ne.createElement(Ue,{dimColor:e}," "),ne.createElement(Ue,{color:h.secondary,dimColor:e},"<"+n+">"))),Hm=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function Ko({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:i,autoSync:s,isSetAutoSync:l}=Ze(),u=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:i,message:"Nice. Now pick your editor."},{key:"autosync",done:l,command:":config autosync",value:s,message:"Almost there. Configure auto sync."}],m=u.findIndex(y=>!y.done),g=m===-1?void 0:u[m];return ne.createElement(Sr,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},ne.createElement(Ue,{color:h.accent,bold:!0},"Welcome! \u{1F539}"),ne.createElement(Ue,null,"Let's get you started - it's a breeze."),ne.createElement(Ue,{color:h.secondary2},"Remember - you can always search available commands by typing:",ne.createElement(Ue,{color:h.accent}," ? ")),g&&ne.createElement(Ue,{color:h.secondary2},g.message),ne.createElement(Sr,{flexDirection:"column"},u.map((y,C)=>m===-1||C<=m?ne.createElement(Sr,{key:y.key,marginBottom:1},ne.createElement(Wm,{isDone:y.done,command:y.command,value:y.done?Hm(y.value):void 0})):null)))}import wr from"chalk";import{Box as Tr,Text as jt}from"ink";import se from"react";var bd="0.6.16";import{Box as Ir,Text as jm}from"ink";import St from"react";var Sd=({width:e})=>{let{viewMode:t}=U(),n=K(),{breadCrumb:r,contextNode:o,selectedIndex:i,renderedChildrenIndex:s}=n,l=s[o.id]?.[i],u=nt(l?.id??o.id,"TICKET"),m=J(u)?u.value:void 0,g=m?.props.tags??[],y=m?.props.assignees??[],C=m?.parentNodeId?!Xr(o.id,m.parentNodeId)&&t==="dense":!1,I=r.map((R,M)=>{let F=M===r.length-1,Ie=B(R.id),le=F?Ie?.[i]?.title:void 0;return`${M?" / ":""}${R.title??""}${le?` \u25B8 ${le}`:""}`}).join(""),S=g.reduce((R,M)=>R+(b.getTag(M)?.name.length??0)+4,0)+y.reduce((R,M)=>R+(b.getContributor(M)?.name.length??0)+4,0),A=e-S;return St.createElement(Ir,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},St.createElement(Ir,{overflow:"hidden",width:A},St.createElement(jm,{wrap:"truncate-end",color:h.secondary2},I)),C?g.map(R=>St.createElement(Ir,{key:R,paddingLeft:1},St.createElement($t,{id:R}))):null,C?y.map(R=>St.createElement(Ir,{key:R,paddingLeft:1},St.createElement(Ot,{id:R}))):null)};import{Box as Vm,Text as Id}from"ink";import Rr from"react";var Km=({filters:e})=>Rr.createElement(Vm,{columnGap:1},Rr.createElement(Id,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Rr.createElement(Id,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Rd=Rr.memo(Km);import{Box as zm,Text as Ar}from"ink";import En from"react";function Ad(){let{eventLog:e,unappliedEvents:t}=K(),n=e.at(-1)?.id,r=_n(n??""),o=J(r)?qi(r.value):"INVALID DATE";return En.createElement(zm,{paddingLeft:1},En.createElement(Ar,{backgroundColor:h.accent}," Readonly "),En.createElement(Ar,{color:h.accent}," "+t.length+" edits ago at "+o+"."),En.createElement(Ar,{color:h.accent}," Resume with "),En.createElement(Ar,{backgroundColor:h.accent}," :peek now "))}import zo from"chalk";import{Box as Gm,Text as Td}from"ink";import Go,{useEffect as qm,useState as Ym}from"react";var Xm=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],wd=e=>{let t=e.replace("#","");return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}},Jm=({r:e,g:t,b:n})=>{let r=o=>Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0");return`#${r(e)}${r(t)}${r(n)}`},Qm=(e,t,n)=>{let r=wd(e),o=wd(t);return Jm({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Zm=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,i=e[r],s=e[Math.min(r+1,e.length-1)];return Qm(i,s,o)};function Md({syncStatus:e,autoSync:t}){let[n,r]=Ym(0);qm(()=>{if(e.status!=="syncing"){r(0);return}let l=setInterval(()=>{r(u=>u+1)},50);return()=>clearInterval(l)},[e.status]);let o={synced:" ",failed:"retry",syncing:"...",pending:"wait"},s={synced:h.secondary2,failed:h.yellow,pending:h.secondary2,syncing:Zm(Xm,(Math.sin(n*.12)+1)/2)??""}[e.status];return Go.createElement(Gm,null,Go.createElement(Td,null,zo.hex(h.secondary2).dim(t?"AutoSync: ":"Sync: ")),Go.createElement(Td,null,zo.hex(s)("\u25CF")+zo.hex(h.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}function Cn({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o}=K(),{userName:i,preferredEditor:s,autoSync:l}=U(),u=64,m=process.stdout.columns-u-8;return se.createElement(Tr,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?se.createElement(jt,null," "):o===p.PALETTE?se.createElement(Tr,null,se.createElement(jt,{color:h.accent},"Command Palette"),se.createElement(jt,{dimColor:!0,color:h.secondary2}," ","- search, select and press enter")):se.createElement(Tr,{paddingLeft:1},e.length>0?se.createElement(Rd,{filters:e}):se.createElement(Sd,{width:m})),n==="live"?se.createElement(Tr,{columnGap:1,paddingRight:2,"max-width":u,overflow:"hidden",justifyContent:"flex-end"},se.createElement(Md,{autoSync:!!l,syncStatus:r}),se.createElement(jt,null,wr.hex(h.secondary2).dim("Mode: ")+wr.hex(h.secondary2).dim(o.padEnd(8," "))," "),se.createElement(Pd,{icon:"@",value:i}),se.createElement(Pd,{icon:"\u276F",value:s}),se.createElement(jt,{dimColor:!0,color:h.secondary2},bd+" ")):"",n==="peek"?se.createElement(Ad,null):"")}function Pd({icon:e,value:t}){return se.createElement(jt,null,wr.dim(e)+wr.hex(h.accent)(` ${t??"-"} `))}import{Box as ep,Text as tp}from"ink";import Nn from"react";import{Box as Mr,Text as qo}from"ink";import pt from"react";function Yo(){let e=K(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,s=t?.id?_(t?.id):[];return pt.createElement(Mr,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:h.secondary,width:i},pt.createElement(Mr,{padding:1,paddingTop:0,paddingBottom:0},pt.createElement(qo,null,"Select a board:")),pt.createElement(Mr,{padding:1,flexDirection:"column"},s.map((l,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,y=_(l.id).flatMap(({id:C})=>B(C)).length;return pt.createElement(Mr,{key:l.id??u},pt.createElement(qo,{color:m?h.accent:h.secondary2},pt.createElement(ge,{isSelected:m})),pt.createElement(qo,{color:m?h.accent:h.secondary2},l.title," (",y," issues)",l.readonly?" \u{1F512}":""))})))}var np=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:s})=>{let{renderedChildrenIndex:l}=K(),u=n.find(({context:C})=>C==="BOARD"),y=i-1-3;return Nn.createElement(ep,{flexDirection:"row"},e.context==="WORKSPACE"?Nn.createElement(Yo,null):u?Nn.createElement(mr,{height:y,width:s,swimlanes:(l[u.id]??[]).filter(C=>C!==void 0&&wt(C)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Nn.createElement(tp,null))},Ld=Nn.memo(np);import{useEffect as rp}from"react";var op=e=>{rp(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:i,preferredEditor:s}=U();s&&i&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:l,mode:u}=v();u==="default"&&!l&&Jn(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},kd=({autoSync:e})=>(op(e),null);function Xo({width:e,height:t}){let n=K(),{autoSync:r,viewMode:o}=Ci(),i=n.filters;if(n.mode===p.HELP)return z.createElement(gt,{flexDirection:"column"},z.createElement(Cd,{width:e,height:t}));if(n.mode===p.PALETTE)return z.createElement(gt,{flexDirection:"column"},z.createElement(Cn,{filters:i}),z.createElement(ud,{width:e,height:t-2}),z.createElement(hn,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:s}=Ze(),l=!s,u=s&&!n.hasProjectDefinition;if(l)return z.createElement(gt,{flexDirection:"column"},z.createElement(gt,{flexDirection:"column"},z.createElement(Cn,{hideBreadCrumb:!0,filters:i}),z.createElement(Ko,{height:t,width:e})),z.createElement(hn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(u)return z.createElement(gt,{flexDirection:"column"},z.createElement(gt,{flexDirection:"column"},z.createElement(Cn,{hideBreadCrumb:!0,filters:i}),z.createElement(Nd,{height:t,width:e})),z.createElement(hn,{width:e,mode:n.mode,availableHints:n.availableHints}));let m=Ce(n.breadCrumb??[],"BOARD");if(J(m)){let g=m.value.id,y=_(g).length,C=3,I=Math.floor(e/C),S=Math.floor(e/Math.max(y,1));e=Math.min(S,I)*Math.max(y,C)}return z.createElement(gt,{flexDirection:"column"},z.createElement(kd,{autoSync:r}),z.createElement(gt,{flexDirection:"column"},z.createElement(Cn,{filters:i}),z.createElement(Ld,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),z.createElement(hn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import ip from"readline";var Pr,Lr,Oe,sp=new Set([f.MoveCursorLeft,f.EraseInputWord,f.MoveCursorLeftOfWord,f.MoveCursorRight,f.MoveCursorRightOfWord,f.NavToPreviousContainer,f.NavToNextContainer,f.NavPreviousItem,f.NavNextItem,f.SetViewDense,f.SetViewWide,f.Confirm,f.Exit,f.InitCommandLine,f.InitCommandPalette,f.ExitCommandLine,f.CaptureInput,f.EraseInput,f.EraseInputWord,f.HideHelp,f.ViewHelp,f.SetViewDense,f.SetViewWide,f.GetLastCommandFromHistory,f.GetNextCommandFromHistory,f.AutoCompleteCommand]),Dd=async e=>{if(e.ctrl&&e.name==="c")return T.exit();let{actionIndex:t,mode:n,readOnly:r}=v(),o=Xs(e,n);if(!o||r&&!sp.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(s){logger.error(s)}},ap=()=>async function(t,n){n.name!=="escape"&&(Oe&&(clearTimeout(Oe),Oe=void 0),await Dd(n))},dp=()=>async function(t){if(t.length===1&&t[0]===27){Oe&&clearTimeout(Oe),Oe=setTimeout(()=>{Dd({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),Oe=void 0},25);return}Oe&&(clearTimeout(Oe),Oe=void 0)};function Fd(){Pr&&process.stdin.removeListener("keypress",Pr),Lr&&process.stdin.removeListener("data",Lr),Pr=ap(),Lr=dp(),ip.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Lr),process.stdin.on("keypress",Pr)}ba();lp(`${kr.bold("Epiq CLI")}
56
+ `,Bo.writeFileSync(t,n,"utf8"),de.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)};var Zu=async e=>{let t=await k({cwd:e,args:["status","--porcelain"]});return d(t)?t:c("Checked git diff",t.value.stdout.trim().length>0)},j=(e,t)=>a(`[${e}] ${t}`),Pa=async()=>{F("");let e=Mn(),t=await Je(process.cwd());if(d(t))return j(1,t.message);let n=t.value,r=await Ln(n);if(d(r))return j(2,r.message);if(r.value)return j(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await Zu(n);if(d(o))return j(2.5,o.message);if(o.value)return j(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(Ur(n))return j(4,"Epiq project already initialized");let i=Ze();if(!i.isSetupDone||!i.userName)return j(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let s=$(),l=s.userName,u=s.userId;if(!u||!l)return j(5,"Missing Epiq user id");let m=e.stateBranch,g=await Dn({repoRoot:n,branch:m});if(d(g))return j(6,g.message);if(g.value)return j(6,`State branch already exists: ${m}`);let h=await po({repoRoot:n,stateBranchName:m});if(d(h))return j(6,h.message);let E=Bn();if(d(E))return j(7,E.message);let I=Ma.join(On(),e.projectId),S=await cn({repoRoot:n,stateBranchRoot:I,stateBranchName:m});if(d(S))return j(8,S.message);let A=Ma.join(I,".epiq");Qu.mkdirSync(A,{recursive:!0});let R=ys({userId:u,userName:l});if(d(R))return j(9,R.message);for(let Br of R.value){let ti=zn({event:Br,rootDir:I});if(d(ti))return j(9,ti.message)}let M=await Jn({stateBranchRoot:I,eventFileName:sn({userId:u,userName:l})});if(d(M))return j(10,M.message);let O=await wt({cwd:I,message:"[epiq:init]"});if(d(O))return j(10,O.message);let Ie=await wa(n);if(d(Ie))return j(11,Ie.message);let le=ii({repoRoot:n,fileContents:e});if(d(le))return j(12,le.message);let Kt=await G.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d(Kt))return j(13,Kt.message);let Sn=await G.commit({cwd:n,message:"[epiq:init-project]"});if(d(Sn))return j(13,Sn.message);let Rt="Project initialized!",zt=await k({cwd:n,args:["push","-u","origin","HEAD"]});d(zt)&&(Rt+=` Warn: [init:14] ${zt.message}`);let re=await ln({repoRoot:n,stateBranchRoot:I});d(re)&&(Rt+=` Warn: [init:15] ${re.message}`);let At=yt(R.value).filter(d);if(At.length>0)return j(16,At.map(Br=>Br.message).join(`
57
+ `));let ft=ot();if(d(ft))return j(16,ft.message);let{rootNodeId:Wd,nodes:Hd}=ft.value,ei=Hd[Wd];return ei?(T.navigate({contextNode:ei,selectedIndex:0}),N({hasProjectDefinition:!0,mode:p.DEFAULT}),c(Rt,null)):j(16,"Unable to resolve initialized root node")};import{ulid as tm}from"ulid";import{ulid as em}from"ulid";var La=null,ut=()=>structuredClone(La),gn=e=>{La=e},ka=()=>{let{contextNode:e,selectedIndex:t}=v(),r=U(e.id)[t];return r?c("Resolved selected child",r):a("Target node not found")},Uo=({id:e,parentId:t,position:n={at:"end"}})=>{let r=U(t).filter(o=>o.id!==e);return Gn(r,n)},Da=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Y();if(d(r))return a("Unable to resolve user ID");let o=Uo({parentId:t,id:e,position:n});return d(o)?o:c("Created pending move state",{id:em(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Fa=e=>{gn(e);let t=nn(e,!0);return d(t)?t:c("Node moved successfully",t.value)};function $o(e){let t=ka();if(d(t))return t;let{contextNode:n,nodes:r}=v();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let i=U(o.id),s=i.findIndex(({id:m})=>m===n.id);if(s<0)return a("Current node not found among siblings");let l=i[s+e];if(!l)return a("Missing sibling node");let u=Da({id:t.value.id,parentId:l.id,position:{at:"end"}});return d(u)?u:Fa(u.value)}function _o(e){let t=ka();if(d(t))return t;let{contextNode:n,selectedIndex:r}=v(),i=U(n.id)[r+e];if(!i)return a("Missing sibling node");let s=Da({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(s)?s:Fa(s.value)}var Oa=()=>{let e=ut();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=v().nodes[n];if(!r)return a("Move parent not found");let o=U(n).findIndex(i=>i.id===t);return o===-1?a("Moved node not found among rendered children"):(T.navigate({contextNode:r,selectedIndex:o}),c("Synchronized navigation to moved node",null))},xr=(e,t="Moved preview")=>{if(d(e))return e;let n=Oa();return d(n)?n:(N({mode:p.MOVE}),c(t,null))},Ba=async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=V().commandMeta,{contextNode:n,selectedIndex:r}=v(),o=U(n.id)[r];if(!o)return N({mode:p.DEFAULT}),a("No move target");if(t==="start"){if(o.readonly)return a("Target node is read-only");if(r===-1)return a("No item selected");if(!o.parentNodeId)return a("Target has no parent");let i=U(o.parentNodeId),s=i.findIndex(({id:h})=>h===o.id);if(s===-1)return a("Target not found among siblings");let l=i[s-1],u=i[s+1],m=u!=null?{at:"before",sibling:u.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},g=Uo({parentId:o.parentNodeId,id:o.id,position:m});return d(g)?g:(gn({id:tm(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:g.value.rank},...e.value}),N({mode:p.MOVE}),c("Move initialized",null))}if(t==="next")return xr(_o(1));if(t==="previous")return xr(_o(-1));if(t==="to-next")return xr($o(1));if(t==="to-previous")return xr($o(-1));if(t==="confirm"){let i=ut();if(!i)return a("No pending move to confirm");let s=await Re();if(d(s))return s;let l=Te(i,s.value);if(d(l))return l;let u=Oa();return d(u)?u:(gn(null),N({mode:p.DEFAULT}),c("Moved item",null))}return t==="cancel"?(gn(null),N({mode:p.DEFAULT}),c("Cancelling move",null)):a("Invalid move modifier")};import{ulid as hr}from"ulid";import{monotonicFactory as nm,ulid as rm}from"ulid";var om=nm(),Ua=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=om();return c("Created issue events",[{id:rm(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}}])};var $a=async(e,t)=>{let n=Y();if(d(n))return a("Unable to resolve user ID");let r=await Re();if(d(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:i,contextNode:s,selectedIndex:l}=v(),u=m=>{let g=Te(m,o);if(d(g))return g;let h=b.getNode(g.value.result.id);if(!h)return a("Created node not found");if(!h.parentNodeId)return g;let E=b.getNode(h.parentNodeId);return E?(T.navigate({contextNode:E,selectedIndex:b.getSiblings(h.parentNodeId).findIndex(({id:I})=>I===h.id)}),g):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=v(),g=b.getNode(m);if(!g)return a("Workspace not found");let h=qn(g.id,n.value,o);return d(h)?h:u({id:hr(),action:"add.board",payload:{id:hr(),name:t.inputString,parent:g.id,rank:h.value},...n.value})}if(t.modifier==="swimlane"){let m=Ee(i,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let g=qn(m.value.id,n.value,o);return d(g)?g:u({id:hr(),action:"add.swimlane",payload:{id:hr(),name:t.inputString,parent:m.value.id,rank:g.value},...n.value})}if(t.modifier==="issue"){let m=_(s.id)[l],g=s.context==="SWIMLANE"?s:s.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let O=Ee(i,"SWIMLANE");return d(O)?null:O.value})();if(!g)return a("Unable to add issue in this context");let h=qn(g.id,n.value,o);if(d(h))return h;let E=Ua({name:t.inputString,parent:g.id,rank:h.value,user:n.value});if(d(E))return E;let I=E.value,S=ds(I,o);if(S.some(O=>d(O)))return a("Issue create failed: "+S.filter(d).map(O=>O.message).filter(Boolean).join(", "));let A=S[0];if(!A||d(A))return a("Issue creation failed");let M=I.find(O=>O.action==="add.issue")?.payload.id;return M?(T.navigate({contextNode:g,selectedIndex:b.getSiblings(g.id).findIndex(({id:O})=>O===M)}),c("Issue created",null)):a("Unable to determine ticket id")}return c("Success",null)};var _a=async()=>{let e=Ee(v().breadCrumb,"BOARD");if(d(e))return e;let t=await Je(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Xe({repoRoot:t.value});if(d(n))throw new Error(n.message);let{modifier:r}=V().commandMeta;if(r==="now"){let S=kt(n.value);if(d(S))return a(S.message);let A=fn();if(d(A))return A;let M=yt(S.value).filter(d);return M.length>0?a(M.map(O=>O.message).join(", ")):(N({mode:p.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}let o;if(r==="prev"){let S=v().eventLog.at(-1),A=ro(S);if(A===null)return a("No previous event to peek");o=A}else if(r==="next"){let S=v().unappliedEvents.at(0),A=ro(S);if(A===null)return a("No next event to peek");o=A+1}else{let S=nr(r);if(!S)return a("Invalid peek date");o=S.getTime()}let i=v(),s=e.value.id,l=rs(n.value,o);if(d(l))return a(l.message);let{appliedEvents:u,unappliedEvents:m}=l.value,g=fn();if(d(g))return g;let E=yt(u).filter(d);if(E.length>0)return fn(),N(i),a(E.map(S=>S.message).join(", "));let I=v().nodes[s];return I?(T.navigate({contextNode:I,selectedIndex:0}),N({mode:p.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:m}),c("Peeking",!0)):(fn(),N(i),a("Board did not exist at peek date"))};import im from"zod";var Wa=()=>{let e=V().commandMeta.inputString,t=im.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return a("Auto sync duration must be a number of at least 3000 ms");let n=ze({autoSyncDebounceMs:t.data});return d(n)?n:(Ce({autoSyncIntervalMs:t.data}),N({mode:p.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))};var Ha=()=>{let e=V().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Ri(e),n=ze({autoSync:t});return d(n)?n:(Ce({autoSync:t}),N({mode:p.DEFAULT}),c(`Auto sync set to "${e}"`,null))};var ja=()=>{let e=V().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=ze({logLevel:e});return d(n)?n:(Ce({logLevel:e}),N({mode:p.DEFAULT}),c(`Auto sync set to "${e}"`,null))};var Va=async()=>{F(""),N({mode:p.DEFAULT});let e=ot();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");N({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Qn();return d(t)?(N({syncStatus:{msg:t.message,status:"failed"}}),t):(N({mode:p.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var Ka=e=>Object.values(v().tags).find(t=>t.name===e),za=e=>Object.values(v().contributors).find(t=>t.name===e),yr=[{systemOnly:!0,intent:P.Move,description:"Internal move-state command",mode:p.COMMAND_LINE,action:Ba},{intent:P.Delete,description:"Delete the currently selected node",mode:p.COMMAND_LINE,action:async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=_(t.id)[n];return r?Se({id:fe(),action:"delete.node",payload:{id:r.id},...e.value}):a("Unable to resolve child to delete")},onSuccess:()=>N({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}=V().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(s=>Z(x.FILTER).map(l=>l.split(n)[0]).includes(s))(r))return a("Invalid filter modifier");let i={target:r,operator:"=",value:t.trim()};return Ne(s=>({...s,filters:e==="clear"?[]:[...s.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 lt({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),N({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=Y();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=_(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!B(r))return a("Cannot close in this context");let o=v().nodes[He];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let i=await Re();if(d(i))return i;let s=i.value,l=lo(o.id,r.id,{at:"end"},e.value,s);if(d(l))return l;let u=await Se({id:fe(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...e.value});return d(u)?u:c("Issue closed",null)},onSuccess:()=>N({mode:p.DEFAULT})},{intent:P.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:p.COMMAND_LINE,action:async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=_(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):nt(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let i=o.value,s=v().nodes[He];if(!s)return a("Unable to locate closed swimlane");if(i.parentNodeId!==s.id)return a("Issue is not closed");if(!B(i))return a("Target node is not issue");let l=ba(i);if(!l)return a("Unable to resolve previous parent from issue history");if(l===s.id)return a("Previous parent resolves to closed swimlane");let u=v().nodes[l];if(!u)return a("Previous parent no longer exists");let m=await Re();if(d(m))return m;let g=m.value,h=lo(u.id,i.id,{at:"end"},e.value,g);if(d(h))return h;let E=await Se({id:fe(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:h.value},...e.value});return d(E)?E:c("Issue reopened",null)},onSuccess:()=>N({mode:p.DEFAULT})},{intent:P.Init,description:"Initialize Epiq in the current git repository",mode:p.COMMAND_LINE,action:Pa},{intent:P.NewItem,description:"Create a new board, swimlane, or issue",mode:p.COMMAND_LINE,action:$a,onSuccess:()=>N({mode:p.DEFAULT})},{intent:P.Rename,description:"itle] Rename the currently selected node",mode:p.COMMAND_LINE,action:async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=_(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=Js();return o?Se({id:fe(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):a("Provide a title")},onSuccess:()=>N({mode:p.DEFAULT})},{intent:P.UntagTicket,description:"Remove a tag from the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=V().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=Ka(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return a("Invalid untag target");let s=nt(i.id,"TICKET");if(d(s))return a("Unable to untag issue in this context");let l=s.value;return B(l)?(l.props.tags??[]).includes(o.id)?Se({id:fe(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...e.value}):a("Issue is not tagged with that tag"):a("Target node is not issue")},onSuccess:()=>N({mode:p.DEFAULT})},{intent:P.TagTicket,description:"Add or create a tag on the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=V().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=v();if(!o)return a("Invalid tag target");let i=nt(o.id,"TICKET");if(d(i))return a("Unable to tag issue in this context");let s=i.value;if(!B(s))return a("Target node is not issue");let l=Ka(r),u;if(l)u=l.id;else{let g=fe(),h=await Se({id:fe(),action:"create.tag",payload:{id:g,name:r},...e.value});if(d(h))return h;u=h.value.result.id}return(s.props.tags??[]).includes(u)?a("Already tagged with that tag"):Se({id:fe(),action:"add.issue.tag",payload:{id:s.id,tag:u},...e.value})},onSuccess:()=>N({mode:p.DEFAULT})},{intent:P.AssignUserToTicket,description:"Assign a user to the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=V().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let{selectedIndex:o,contextNode:i}=v(),s=_(i.id)[o];if(!s)return a("Invalid assign target");let l=nt(s.id,"TICKET");if(d(l))return a("Unable to assign issue in this context");let u=l.value;if(!B(u))return a("Target node is not issue");let m=za(r),g;if(m)g=m.id;else{let E=fe(),I=await Se({id:fe(),action:"create.contributor",payload:{id:E,name:r},...e.value});if(d(I))return I;g=I.value.result.id}return(u.props.assignees??[]).includes(g)?a("Assignee already assigned"):Se({id:fe(),action:"add.issue.assignee",payload:{id:u.id,assignee:g},...e.value})},onSuccess:()=>N({mode:p.DEFAULT})},{intent:P.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=Y();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=V().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let o=za(r);if(!o)return a(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return a("Invalid unassign target");let s=nt(i.id,"TICKET");if(d(s))return a("Unable to unassign in this context");let l=s.value;return B(l)?(l.props.assignees??[]).includes(o.id)?Se({id:fe(),action:"remove.issue.assignee",payload:{id:l.id,assignee:o.id},...e.value}):a(`Issue is not assigned to "${r}"`):a("Target node is not issue")},onSuccess:()=>N({mode:p.DEFAULT})},{intent:P.Sync,description:"Pull, commit, and push Epiq state",mode:p.COMMAND_LINE,action:Va},{intent:P.Peek,description:"View board state at another point in time",mode:p.COMMAND_LINE,action:_a},{intent:P.Export,description:"Export the current board layout to markdown",mode:p.COMMAND_LINE,action:async()=>{let e=await pa();return d(e)?e:(N({mode:p.DEFAULT}),c("Export successful",!0))}},{intent:P.Exit,description:"Exit the application",mode:p.COMMAND_LINE,action:async()=>(T.exit(),c("Exit successful",!0))},{intent:P.Edit,description:"Edit title or description",mode:p.COMMAND_LINE,action:async(e,t)=>{if(t.modifier===it.DESCRIPTION)return Ta();if(t.modifier===it.TITLE){let n=Y();if(d(n))return a("Unable to resolve user ID");let{contextNode:r,selectedIndex:o}=v(),i=_(r.id)[o];if(!i)return a("Missing node");if(i.readonly)return a("Cannot rename readonly node");let s=t.inputString.trim();return s?Se({id:fe(),action:"edit.title",payload:{id:i.id,name:s},...n.value}):a("Provide a title")}return a("Unknown edit command")},onSuccess:()=>N({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}=$(),s=n||i,l=r??fe();if(!s||!l)return a("Unable to resolve user name or id");let u=ze({userName:s,userId:l,preferredEditor:o??""});return d(u)?u:(Ce({userName:s,userId:l}),N({mode:p.DEFAULT}),c(`Username set to "${s}"`,null))}case X.EDITOR:{if(!n)return a("No editor provided");let r=ze({preferredEditor:n});return d(r)?r:(Ce({preferredEditor:n}),N({mode:p.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case X.VIEW:return n!=="wide"&&n!=="dense"?a("Invalid view mode"):(Ce({viewMode:n}),c(`View set to "${n}"`,null));case X.AUTOSYNC:return Ha();case X.LOG_LEVEL:return ja();case X.SYNC_DEBOUNCE_MS:return Wa();default:return a("Unknown config command")}}},{intent:P.Coffee,description:"Sponsor the development of Epiq!",mode:p.COMMAND_LINE,action:()=>{let e=V().commandMeta.modifier;return e==="custom"?Oo("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):Oo(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),F(""),c("Thanks you!",null)}}];var sm=new Set(["peek","filter","view-help"]),Oe=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=V();if(!t)return a("No command to confirm");if(!e&&n===Nt.Invalid)return a("Invalid command");let i=ar(t);zs();let{readOnly:s}=v();if(s&&!sm.has(i))return mn({status:qe.Fail,message:"Command not available in readonly state",value:null});let l=yr.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===i);if(!l)return mn({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 mn({status:qe.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?mn(u):(Gs({addToHistory:!e}),l.onSuccess?.(),$().autoSync&&Zn(),u)};var Cr=[{intent:f.Exit,mode:p.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(N({mode:p.COMMAND_LINE}),F("move cancel"),Oe({isForceExecutedBySystem:!0}))},{intent:f.InitMove,mode:p.DEFAULT,description:"[m] move (init/confirm)",action:()=>(N({mode:p.COMMAND_LINE}),F("move start"),Oe({isForceExecutedBySystem:!0}))},{intent:f.ConfirmMove,mode:p.MOVE,action:()=>(N({mode:p.COMMAND_LINE}),F("move confirm"),Oe({isForceExecutedBySystem:!0}))}],Er=[{intent:f.MovePreviousItem,mode:p.MOVE,action:()=>ut()?(N({mode:p.COMMAND_LINE}),F("move previous"),Oe({isForceExecutedBySystem:!0})):a("No pending move")},{intent:f.MoveNextItem,mode:p.MOVE,action:()=>ut()?(N({mode:p.COMMAND_LINE}),F("move next"),Oe({isForceExecutedBySystem:!0})):a("No pending move")}],Ga=[{intent:f.MoveToNextContainer,mode:p.MOVE,action:()=>ut()?(N({mode:p.COMMAND_LINE}),F("move to-next"),Oe({isForceExecutedBySystem:!0})):a("No pending move")},{intent:f.MoveToPreviousContainer,mode:p.MOVE,action:()=>ut()?(N({mode:p.COMMAND_LINE}),F("move to-previous"),Oe({isForceExecutedBySystem:!0})):a("No pending move")}];var qa={[w.WORKSPACE]:[...Cr,...Er],[w.BOARD]:[...Cr,...Er],[w.SWIMLANE]:[...Cr,...Er,...Ga],[w.TICKET]:[],[w.FIELD]:[],[w.FIELD_LIST]:[],[w.TEXT]:[]};var Ya=()=>{F("");let{pendingNavTarget:e}=ct();N({mode:p.DEFAULT}),e&&T.navigate(e),lt({pendingNavTarget:void 0})},Xa=[{intent:f.ExitCommandLine,mode:p.HELP,action:()=>(Ya(),c("Exiting help",null))},{intent:f.Exit,mode:p.HELP,action:()=>(Ya(),c("Closed help",null))},{intent:f.NavPreviousItem,mode:p.HELP,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:f.NavNextItem,mode:p.HELP,action:()=>(T.navigateToNextItem(),c("Navigating to next help item",null))},{intent:f.NavToPreviousContainer,mode:p.HELP,action:()=>(T.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:f.NavToNextContainer,mode:p.HELP,action:()=>(T.navigateToNextContainer(),c("Navigating to next help container",null))}];var am=e=>{N({mode:p.COMMAND_LINE});let{pendingNavTarget:t}=ct();t&&T.navigate(t),lt({pendingNavTarget:void 0}),F(`${e} `)},Ja=()=>{F("");let{pendingNavTarget:e}=ct();e&&T.navigate(e),lt({pendingNavTarget:void 0}),N({mode:p.DEFAULT})},Qa=[{intent:f.InitCommandPalette,mode:p.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{F("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return lt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),N({mode:p.PALETTE}),c("Opening command palette",null)}},{intent:f.Confirm,mode:p.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!et(e))return a("Command only applicable on text nodes");if(e.props.disabled)return a("Command is not available in this context");let t=e.title;return t?(am(t),c("Selected command",t)):c("No command selected",null)}},{intent:f.ExitCommandLine,mode:p.PALETTE,action:()=>(Ja(),c("Exiting palette",null))},{intent:f.Exit,mode:p.PALETTE,action:()=>(Ja(),c("Closed command palette",null))},{intent:f.NavPreviousItem,mode:p.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:f.NavNextItem,mode:p.PALETTE,action:()=>(T.navigateToNextItem(),c("Navigating to next item",null))},{intent:f.NavToPreviousContainer,mode:p.PALETTE,action:()=>(T.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:f.NavToNextContainer,mode:p.PALETTE,action:()=>(T.navigateToNextContainer(),c("Navigating to next container",null))}];var Za=[...Xa,...Qa,{intent:f.AddItem,mode:p.DEFAULT,description:"[n] new...",action:()=>(N({mode:p.COMMAND_LINE}),F(`${x.NEW} `),c("Adding new item",null))},{intent:f.Delete,mode:p.DEFAULT,description:"[d] delete",action:()=>(N({mode:p.COMMAND_LINE}),F(`${x.DELETE} `),c("Deleting item",null))},{intent:f.InitCommandLine,mode:p.DEFAULT,description:"[:] focus command line",action:()=>(N({mode:p.COMMAND_LINE}),F(""),c("Entering command line mode",null))},{intent:f.Confirm,mode:p.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!U(e?.id??"")?.length){if(e?.title===Q.DESCRIPTION)return N({mode:p.COMMAND_LINE}),F(`${x.EDIT} description `),c("Propose command",!0);if(e?.title===Q.ASSIGNEES)return N({mode:p.COMMAND_LINE}),F(`${x.ASSIGN} `),c("Propose command",!0);if(e?.title===Q.TAGS)return N({mode:p.COMMAND_LINE}),F(`${x.TAG} `),c("Propose command",!0);if(t.title===Q.DESCRIPTION&&e?.context==="TEXT")return N({mode:p.COMMAND_LINE}),F(`${x.EDIT} description `),c("Propose command",!0)}return T.enterChildNode(),c("Entering context",null)}},{intent:f.EditTitle,mode:p.DEFAULT,description:"[r] rename title",action:()=>(N({mode:p.COMMAND_LINE}),F(`${x.EDIT} title ${v().selectedNode?.title}`),c("Exiting context",null))},{intent:f.EditDescription,mode:p.DEFAULT,description:"[e] edit description",action:()=>(N({mode:p.COMMAND_LINE}),F(`${x.EDIT} description `),c("Exiting context",null))},{intent:f.Exit,mode:p.DEFAULT,description:"[q] exit context",action:()=>(T.enterParentNode(),c("Exiting context",null))},{intent:f.NavPreviousItem,mode:p.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(T.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:f.NavNextItem,mode:p.DEFAULT,action:()=>(T.navigateToNextItem(),c("Navigating to next item",null))},{intent:f.NavToPreviousContainer,mode:p.DEFAULT,action:()=>(T.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:f.NavToNextContainer,mode:p.DEFAULT,action:()=>(T.navigateToNextContainer(),c("Navigating to next container",null))}];var dm=500,cm=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),ed=e=>{let t=cm(e);t&&sr(n=>(n+t).slice(0,dm))};var lm=[p.COMMAND_LINE,p.PALETTE],um=e=>[{intent:f.MoveCursorLeft,mode:e,action:()=>(Io(-1),c("Moving cursor left",null))},{intent:f.MoveCursorRight,mode:e,action:()=>(Io(1),c("Moving cursor right",null))},{intent:f.MoveCursorLeftOfWord,mode:e,action:()=>(Ro("left"),c("Moving cursor left of word",null))},{intent:f.MoveCursorRightOfWord,mode:e,action:()=>(Ro("right"),c("Moving cursor right of word",null))},{intent:f.AutoCompleteCommand,mode:e,action:()=>(sr((t,{remainder:n})=>n?t+n:t),c("Auto-completing command",null))},{intent:f.CaptureInput,mode:e,action:(t,{sequence:n})=>(ed(n??""),c("Capturing input",null))},{intent:f.EraseInput,mode:e,action:()=>(Vs(),c("Erasing input",null))},{intent:f.EraseInputWord,mode:e,action:()=>(Ks(),c("Erasing input word",null))}],td=[{intent:f.Confirm,mode:p.COMMAND_LINE,action:()=>(Oe(),c("Executing command",null))},{intent:f.ViewHelp,mode:p.DEFAULT,action:()=>(N({mode:p.HELP}),c("Viewing help",null))},...lm.flatMap(um),{intent:f.ExitCommandLine,mode:p.COMMAND_LINE,action:()=>(N({mode:p.DEFAULT}),c("Exiting command line",null))},{intent:f.GetLastCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(qs(),c("Getting last command from history",null))},{intent:f.GetNextCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(Ys(),c("Getting next command from history",null))}];import od from"chalk";var Nr=od.dim.hex(y.secondary2)(": for command line"),nd="q to exit",rd=`${od.hex(y.accent)("m")} to confirm`,Wo={[w.WORKSPACE]:[Nr],[w.BOARD]:[Nr],[w.BOARD+p.COMMAND_LINE]:[Nr],[w.SWIMLANE]:[Nr],[w.TICKET+p.HELP]:[nd],[w.SWIMLANE+p.HELP]:[nd],[w.TICKET]:[],[w.FIELD]:[],[w.SWIMLANE+p.MOVE]:[rd],[w.TICKET+p.MOVE]:[rd]};var vn=e=>e.trim().toLocaleLowerCase(),mm=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},pm=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},id=(e,t)=>{let n=vn(t.value);if(!n)return!0;switch(t.target){case"title":return vn(e.title??"").includes(n);case"description":return vn(e.props.description??"").includes(n);case"tag":return mm(e).map(vn).some(o=>o.includes(n));case"assignee":return pm(e).map(vn).some(o=>o.includes(n));default:return!0}};function sd(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],i=r;for(;i&&(o.push(i),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let s=o[o.length-1];return!s||s.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var ad=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var St,Ho,jo=new Set,dd=()=>{for(let e of jo)e()},fm=e=>(jo.add(e),()=>jo.delete(e));function cd(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return a("derive(): contextNodeId is missing");if(!r)return a("derive(): rootNode is missing");if(!o[r])return a("derive(): unable to find root node");let l=o[t];if(!l)return a("Unable to derive state, contextNode not found");let u=sd(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:g}=l,h=Wo[g+n]??Wo[g]??[],E=[...Za,...qa[g]??[],...td],I=ad(E),S=vm(o,i),A=S[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:h,availableActions:E,actionIndex:I,selectedNode:A,renderedChildrenIndex:S})}var v=()=>{if(!St)throw new Error("State not initialized. Call initWorkspaceState() first.");return St},ot=()=>St?c("Retrieved state",St):a("State not initialized. Call initWorkspaceState() first.");function rn(e){Ho=e;let t=Ye(process.cwd()),n=!1;if(!d(t)){let i=Qe(t.value);if(d(i))return a(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=cd(r);return d(o)?o:(St=o.value,dd(),c("State initialized",null))}function Ne(e){let t=v(),n=e(t),r=cd(n);return d(r)?a(r.message??"Unable to update state"):(St=r.value,dd(),c("State updated",null))}var N=e=>Ne(t=>({...t,...e}));var K=()=>gm(fm,v,v),vm=(e,t)=>{let n={};for(let r of Object.values(e))B(r)&&t.length>0&&!t.every(o=>id(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 s=e[o.id],l=e[i.id];return!s||!l?0:s.rank.localeCompare(l.rank)});return n},_=e=>v()?.renderedChildrenIndex[e]??[],fn=()=>Ho?rn(Ho):a("Cannot reset state: no initial workspace found"),Dt=()=>St!==void 0;import{Box as Vo,Text as xn}from"ink";import Me,{useEffect as xm,useMemo as hm}from"react";import{ulid as ym}from"ulid";var ld=({text:e,match:t,color:n,highlightColor:r=y.secondary,dimColor:o=!1})=>{if(!t)return Me.createElement(xn,{color:n,dimColor:o},e);let i=e.toLowerCase(),s=t.toLowerCase(),l=i.indexOf(s);return l===-1?Me.createElement(xn,{color:n,dimColor:o},e):Me.createElement(xn,{color:n,dimColor:o},e.slice(0,l),Me.createElement(xn,{backgroundColor:r,bold:!0},e.slice(l,l+t.length)),e.slice(l+t.length))},ud=ym(),Cm=e=>`${e}`,Em=e=>{let{pendingNavTarget:t}=ct();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,i=new Set(Z(x.NONE,{breadCrumb:n,contextNode:r,readOnly:v().readOnly,selectedNode:o}));return[...new Set(Object.values(x))].filter(s=>s!=="move").filter(s=>s.length>0).filter(s=>s!==x.PALETTE).map(s=>{let l=ar(s),u=yr.find(m=>m.intent===l);return{command:s,description:u?.description??`[${s}] Run command`,isAvailable:i.has(s)}}).filter(s=>s.command.toLowerCase().startsWith(e)||e.length>=2&&s.description.toLowerCase().includes(e)).sort((s,l)=>s.isAvailable!==l.isAvailable?s.isAvailable?-1:1:s.command.localeCompare(l.command))},Nm=e=>q.text({id:ud,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),bm=(e,t,n)=>q.text({id:Cm(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Ko=[],Sm=e=>{md();let t=b.createNode(Nm(v().rootNodeId));d(t)||!et(t.value)||(Ko=[t.value,...e.map((n,r)=>bm(n,r,ud)).map(b.createNode).filter(J).map(({value:n})=>n).filter(et)],T.navigate({contextNode:t.value,selectedIndex:0}))},md=()=>{let e=Ko.map(t=>t.id);Ko=[];for(let t of e)b.deleteNode(t)};function pd({width:e,height:t}){let r=Xs().value.trim().toLowerCase(),o=hm(()=>Em(r),[r]);xm(()=>(Sm(o),()=>{md()}),[o]);let i=v().selectedIndex;return Me.createElement(Vo,{flexDirection:"column",width:e,height:t-2},Me.createElement(st,{height:t-4,itemHeight:3,selectedIndex:i},o.map((s,l)=>{let u=l===i,m=s.isAvailable?y.accent:y.secondary2,g=s.isAvailable?"":"[unavailable] ";return Me.createElement(Vo,{key:s.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Me.createElement(xn,{color:m,dimColor:!s.isAvailable},u?"\u276F ":" ",Me.createElement(ld,{text:Di(s.command),match:r,color:m,dimColor:!s.isAvailable})),Me.createElement(Vo,{paddingLeft:2},Me.createElement(ld,{text:g+s.description,match:r.length>=2?r:"",color:u&&s.isAvailable?y.primary:y.secondary2,dimColor:!s.isAvailable})))})))}import{Box as Bm}from"ink";import Go from"react";import yn from"chalk";import{Box as zo,Text as gd}from"ink";import hn,{useEffect as Im,useMemo as Rm,useState as Am}from"react";var fd=yn.gray,Tm=yn.inverse,wm=yn.inverse.gray,Mm={hint:"",hints:[],overlap:0,remainder:""},xd=({value:e,command:t})=>{if(!t)return null;let n=e.trimStart(),o=e.length-n.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},Pm=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=be(t);return{bg:r=>yn.bgHex(n).black(r),bgCursor:r=>yn.bgHex(n).inverse.black(r)}}return no(t)},Lm=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=xd({value:e,command:t});if(!r)return null;let i=e.slice(r.end).match(/^\s*/)?.[0].length??0,s=r.end+i;return e.slice(s,s+n.length)!==n?null:{start:s,end:s+n.length}},vd=()=>({value:se.value,cursorPosition:se.cursorPosition,commandIsPending:se.commandIsPending,autoCompletion:se.commandMeta.autoCompletion??Mm,infoMessage:se.commandMeta.infoMessage,validationStatus:se.commandMeta.validity,command:se.commandMeta.command,inputString:se.commandMeta.inputString,modifier:se.commandMeta.modifier}),km=(e,t)=>e.value===t.value&&e.cursorPosition===t.cursorPosition&&e.commandIsPending===t.commandIsPending&&e.infoMessage===t.infoMessage&&e.autoCompletion.hint===t.autoCompletion.hint&&e.autoCompletion.overlap===t.autoCompletion.overlap&&e.autoCompletion.remainder===t.autoCompletion.remainder&&e.validationStatus===t.validationStatus&&e.command===t.command&&e.modifier===t.modifier&&e.inputString===t.inputString,hd=({width:e,mode:t})=>{let[n,r]=Am(vd());Im(()=>{let E=()=>{let S=vd();r(A=>km(A,S)?A:S)},I=So(E);return E(),()=>{I()}},[]);let{value:o,cursorPosition:i,infoMessage:s,commandIsPending:l,autoCompletion:u,command:m,modifier:g}=n,h=Rm(()=>{let E=Math.max(0,Math.min(i,o.length)),I=xd({value:o,command:m}),S=Lm({value:o,command:m,modifier:g}),A=m?no(m):null,R=Pm({command:m,modifier:g}),M=(re,ue)=>{let At=I&&ue>=I.start&&ue<I.end,ft=S&&ue>=S.start&&ue<S.end;return At&&A?A.fg(re):ft&&R?R.bg(re):re},O=(re,ue)=>{let At=I&&ue>=I.start&&ue<I.end,ft=S&&ue>=S.start&&ue<S.end;return At&&A?A.fgCursor(re):ft&&R?R.bgCursor(re):Tm(re)},Ie=o.slice(0,E),le=o[E]??" ",Kt=E<o.length?o.slice(E+1):"",Sn=Array.from(Ie).map((re,ue)=>M(re,ue)).join(""),Rt=O(le,E),zt=Array.from(Kt).map((re,ue)=>M(re,E+1+ue)).join("");if(u.hint){let re=u.hint[u.overlap]??le;Rt=wm(re),zt=fd(u.remainder.slice(1)+Kt)}return fd(t===p.PALETTE?"?":":")+Sn+Rt+zt},[o,i,u,m,g]);return hn.createElement(zo,{flexDirection:"column",justifyContent:"flex-start"},hn.createElement(zo,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},hn.createElement(zo,null,hn.createElement(gd,null,h),s&&hn.createElement(gd,{wrap:"truncate",color:l?y.red:y.secondary2},` ${s} `))))};import{Box as Dm,Text as Fm}from"ink";import yd from"react";var Om=(e,t)=>{let n=[],r=0;for(let o of e){let s=(n.length>0?" | ":"").length+o.length;if(r+s>t-4)break;n.push(o),r+=s}return n},Cd=({width:e,availableHints:t})=>{let n=Om(t,e).join(" | ");return yd.createElement(Dm,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1},yd.createElement(Fm,{color:y.secondary2},n.length?n:"\xA0"))};var Cn=({width:e,mode:t,availableHints:n})=>{let r=[],o=0;for(let i of n){let l=(r.length>0?" | ":"").length+i.length;if(o+l>e+2)break;r.push(i),o+=l}return Go.createElement(Bm,null,t===p.COMMAND_LINE||t===p.PALETTE?Go.createElement(hd,{width:e,mode:t}):Go.createElement(Cd,{width:e,mode:t,availableHints:n}))};import{Box as mt,Text as jt}from"ink";import ce,{useEffect as Um,useMemo as $m}from"react";import{ulid as Ed}from"ulid";var Sr=Ed(),_m=()=>[...new Set([...v().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(e=>{let[t,n]=e.split("]"),r=t?.replace("[",""),o=n?.trim();return[r,o]}).filter(e=>e[0]!==void 0&&e[1]!==void 0).sort(([e],[t])=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(([e,t])=>({keys:e,action:t})),Wm=e=>q.text({id:Sr,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),Hm=(e,t,n)=>q.text({id:Ed(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),br=[],Nd=()=>{let e=br.filter(n=>n.id!==Sr).map(n=>n.id),t=br.filter(n=>n.id===Sr).map(n=>n.id);br=[];for(let n of[...e,...t])b.deleteNode(n)},jm=e=>{Nd();let t=b.createNode(Wm(v().rootNodeId));if(d(t)||!et(t.value))return logger.error("Could not attach help nodes");br=[t.value,...e.map((n,r)=>Hm(n,r,Sr)).map(b.createNode).filter(J).map(({value:n})=>n).filter(et)],T.navigate({contextNode:t.value,selectedIndex:0})},bd=({width:e,height:t})=>{let n=$m(()=>_m(),[]);Um(()=>(jm(n),()=>{Nd()}),[n]);let r=v().selectedIndex;return ce.createElement(mt,{flexDirection:"column",marginTop:3,borderColor:y.secondary,borderStyle:"round",width:e,height:t-2},ce.createElement(mt,{paddingX:1,justifyContent:"center"},ce.createElement(jt,{color:y.accent},"Help"),ce.createElement(jt,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),ce.createElement(mt,{paddingX:1,marginTop:1},ce.createElement(mt,{width:20,justifyContent:"flex-end"},ce.createElement(jt,{color:y.secondary},"Key(s)")),ce.createElement(mt,{flexGrow:1,width:40,paddingLeft:2},ce.createElement(jt,{color:y.secondary},"Action"))),ce.createElement(st,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:i},s)=>{let l=s===r;return ce.createElement(mt,{paddingX:1,key:`${o}-${i}-${s}`,flexDirection:"row"},ce.createElement(mt,{width:20,justifyContent:"flex-end"},ce.createElement(jt,{color:y.accent},o)),ce.createElement(mt,{flexGrow:1,width:40,paddingLeft:2},ce.createElement(jt,{color:l?y.primary:y.secondary2},i)))})))};import Vm from"chalk";import{Box as Ir,Text as Ge}from"ink";import xe from"react";var Sd=({width:e,height:t})=>xe.createElement(Ir,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},xe.createElement(Ge,{color:y.accent,bold:!0},"Initialize project"),xe.createElement(Ge,null,`This folder is not an ${Vm.hex(y.accent)("epiq")} project yet.`),xe.createElement(Ge,{color:y.primary},"To start tracking issues here, we need to initialize a new",xe.createElement(Ge,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json "),"file in this repository."),xe.createElement(Ir,{marginTop:1,flexDirection:"column"},xe.createElement(Ir,null,xe.createElement(Ge,{color:y.accent}," "),xe.createElement(Ge,{color:y.primary},"Type "),xe.createElement(Ge,{backgroundColor:y.secondary}," :init "))),xe.createElement(Ir,{marginTop:1},xe.createElement(Ge,{color:y.secondary2},"This will create, commit and push "),xe.createElement(Ge,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json ")));import{Box as Rr,Text as Be}from"ink";import ne from"react";var Km=({isDone:e,command:t,value:n})=>ne.createElement(Rr,null,ne.createElement(Be,{color:y.accent,dimColor:e},e?" \u2714 ":" "),ne.createElement(Be,{dimColor:e},"Type "),ne.createElement(Be,{backgroundColor:y.secondary,dimColor:e}," "+t+" "),n!==void 0&&ne.createElement(ne.Fragment,null,ne.createElement(Be,{dimColor:e}," "),ne.createElement(Be,{color:y.secondary,dimColor:e},"<"+n+">"))),zm=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function qo({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:i,autoSync:s,isSetAutoSync:l}=Ze(),u=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:i,message:"Nice. Now pick your editor."},{key:"autosync",done:l,command:":config autosync",value:s,message:"Almost there. Configure auto sync."}],m=u.findIndex(h=>!h.done),g=m===-1?void 0:u[m];return ne.createElement(Rr,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},ne.createElement(Be,{color:y.accent,bold:!0},"Welcome! \u{1F539}"),ne.createElement(Be,null,"Let's get you started - it's a breeze."),ne.createElement(Be,{color:y.secondary2},"Remember - you can always search available commands by typing:",ne.createElement(Be,{color:y.accent}," ? ")),g&&ne.createElement(Be,{color:y.secondary2},g.message),ne.createElement(Rr,{flexDirection:"column"},u.map((h,E)=>m===-1||E<=m?ne.createElement(Rr,{key:h.key,marginBottom:1},ne.createElement(Km,{isDone:h.done,command:h.command,value:h.done?zm(h.value):void 0})):null)))}import Pr from"chalk";import{Box as Mr,Text as Vt}from"ink";import ae from"react";var Id="0.6.18";import{Box as Ar,Text as Gm}from"ink";import It from"react";var Rd=({width:e})=>{let{viewMode:t}=$(),n=K(),{breadCrumb:r,contextNode:o,selectedIndex:i,renderedChildrenIndex:s}=n,l=s[o.id]?.[i],u=nt(l?.id??o.id,"TICKET"),m=J(u)?u.value:void 0,g=m?.props.tags??[],h=m?.props.assignees??[],E=m?.parentNodeId?!Qr(o.id,m.parentNodeId)&&t==="dense":!1,I=r.map((R,M)=>{let O=M===r.length-1,Ie=U(R.id),le=O?Ie?.[i]?.title:void 0;return`${M?" / ":""}${R.title??""}${le?` \u25B8 ${le}`:""}`}).join(""),S=g.reduce((R,M)=>R+(b.getTag(M)?.name.length??0)+4,0)+h.reduce((R,M)=>R+(b.getContributor(M)?.name.length??0)+4,0),A=e-S;return It.createElement(Ar,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},It.createElement(Ar,{overflow:"hidden",width:A},It.createElement(Gm,{wrap:"truncate-end",color:y.secondary2},I)),E?g.map(R=>It.createElement(Ar,{key:R,paddingLeft:1},It.createElement(_t,{id:R}))):null,E?h.map(R=>It.createElement(Ar,{key:R,paddingLeft:1},It.createElement($t,{id:R}))):null)};import{Box as qm,Text as Ad}from"ink";import Tr from"react";var Ym=({filters:e})=>Tr.createElement(qm,{columnGap:1},Tr.createElement(Ad,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Tr.createElement(Ad,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Td=Tr.memo(Ym);import{Box as Xm,Text as wr}from"ink";import En from"react";function wd(){let{eventLog:e,unappliedEvents:t}=K(),n=e.at(-1)?.id,r=Hn(n??""),o=J(r)?Xi(r.value):"INVALID DATE";return En.createElement(Xm,{paddingLeft:1},En.createElement(wr,{backgroundColor:y.accent}," Readonly "),En.createElement(wr,{color:y.accent}," "+t.length+" edits ago at "+o+"."),En.createElement(wr,{color:y.accent}," Resume with "),En.createElement(wr,{backgroundColor:y.accent}," :peek now "))}import Yo from"chalk";import{Box as Jm,Text as Md}from"ink";import Xo,{useEffect as Qm,useState as Zm}from"react";var ep=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Pd=e=>{let t=e.replace("#","");return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}},tp=({r:e,g:t,b:n})=>{let r=o=>Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0");return`#${r(e)}${r(t)}${r(n)}`},np=(e,t,n)=>{let r=Pd(e),o=Pd(t);return tp({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},rp=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,i=e[r],s=e[Math.min(r+1,e.length-1)];return np(i,s,o)};function Ld({syncStatus:e,autoSync:t}){let[n,r]=Zm(0);Qm(()=>{if(e.status!=="syncing"){r(0);return}let l=setInterval(()=>{r(u=>u+1)},50);return()=>clearInterval(l)},[e.status]);let o={synced:" ",failed:"---",syncing:"...",pending:"idle"},s={synced:y.secondary2,failed:y.yellow,pending:y.secondary2,syncing:rp(ep,(Math.sin(n*.12)+1)/2)??""}[e.status];return Xo.createElement(Jm,null,Xo.createElement(Md,null,Yo.hex(y.secondary2).dim(t?"AutoSync: ":"Sync: ")),Xo.createElement(Md,null,Yo.hex(s)("\u25CF")+Yo.hex(y.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}function Nn({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o}=K(),{userName:i,preferredEditor:s,autoSync:l}=$(),u=64,m=process.stdout.columns-u-8;return ae.createElement(Mr,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?ae.createElement(Vt,null," "):o===p.PALETTE?ae.createElement(Mr,null,ae.createElement(Vt,{color:y.accent},"Command Palette"),ae.createElement(Vt,{dimColor:!0,color:y.secondary2}," ","- search, select and press enter")):ae.createElement(Mr,{paddingLeft:1},e.length>0?ae.createElement(Td,{filters:e}):ae.createElement(Rd,{width:m})),n==="live"?ae.createElement(Mr,{columnGap:1,paddingRight:2,"max-width":u,overflow:"hidden",justifyContent:"flex-end"},ae.createElement(Ld,{autoSync:!!l,syncStatus:r}),ae.createElement(Vt,null,Pr.hex(y.secondary2).dim("Mode: ")+Pr.hex(y.secondary2).dim(o.padEnd(8," "))," "),ae.createElement(kd,{icon:"@",value:i}),ae.createElement(kd,{icon:"\u276F",value:s}),ae.createElement(Vt,{dimColor:!0,color:y.secondary2},Id+" ")):"",n==="peek"?ae.createElement(wd,null):"")}function kd({icon:e,value:t}){return ae.createElement(Vt,null,Pr.dim(e)+Pr.hex(y.accent)(` ${t??"-"} `))}import{Box as op,Text as ip}from"ink";import bn from"react";import{Box as Lr,Text as Jo}from"ink";import pt from"react";function Qo(){let e=K(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,s=t?.id?_(t?.id):[];return pt.createElement(Lr,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:y.secondary,width:i},pt.createElement(Lr,{padding:1,paddingTop:0,paddingBottom:0},pt.createElement(Jo,null,"Select a board:")),pt.createElement(Lr,{padding:1,flexDirection:"column"},s.map((l,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,h=_(l.id).flatMap(({id:E})=>U(E)).length;return pt.createElement(Lr,{key:l.id??u},pt.createElement(Jo,{color:m?y.accent:y.secondary2},pt.createElement(ge,{isSelected:m})),pt.createElement(Jo,{color:m?y.accent:y.secondary2},l.title," (",h," issues)",l.readonly?" \u{1F512}":""))})))}var sp=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:s})=>{let{renderedChildrenIndex:l}=K(),u=n.find(({context:E})=>E==="BOARD"),h=i-1-3;return bn.createElement(op,{flexDirection:"row"},e.context==="WORKSPACE"?bn.createElement(Qo,null):u?bn.createElement(gr,{height:h,width:s,swimlanes:(l[u.id]??[]).filter(E=>E!==void 0&&Mt(E)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):bn.createElement(ip,null))},Dd=bn.memo(sp);import{useEffect as ap}from"react";var dp=e=>{ap(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:i,preferredEditor:s}=$();s&&i&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:l,mode:u}=v();u==="default"&&!l&&Zn(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},Fd=({autoSync:e})=>(dp(e),null);function Zo({width:e,height:t}){let n=K(),{autoSync:r,viewMode:o}=bi(),i=n.filters;if(n.mode===p.HELP)return z.createElement(gt,{flexDirection:"column"},z.createElement(bd,{width:e,height:t}));if(n.mode===p.PALETTE)return z.createElement(gt,{flexDirection:"column"},z.createElement(Nn,{filters:i}),z.createElement(pd,{width:e,height:t-2}),z.createElement(Cn,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:s}=Ze(),l=!s,u=s&&!n.hasProjectDefinition;if(l)return z.createElement(gt,{flexDirection:"column"},z.createElement(gt,{flexDirection:"column"},z.createElement(Nn,{hideBreadCrumb:!0,filters:i}),z.createElement(qo,{height:t,width:e})),z.createElement(Cn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(u)return z.createElement(gt,{flexDirection:"column"},z.createElement(gt,{flexDirection:"column"},z.createElement(Nn,{hideBreadCrumb:!0,filters:i}),z.createElement(Sd,{height:t,width:e})),z.createElement(Cn,{width:e,mode:n.mode,availableHints:n.availableHints}));let m=Ee(n.breadCrumb??[],"BOARD");if(J(m)){let g=m.value.id,h=_(g).length,E=3,I=Math.floor(e/E),S=Math.floor(e/Math.max(h,1));e=Math.min(S,I)*Math.max(h,E)}return z.createElement(gt,{flexDirection:"column"},z.createElement(Fd,{autoSync:r}),z.createElement(gt,{flexDirection:"column"},z.createElement(Nn,{filters:i}),z.createElement(Dd,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),z.createElement(Cn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import cp from"readline";var kr,Dr,Ue,lp=new Set([f.MoveCursorLeft,f.EraseInputWord,f.MoveCursorLeftOfWord,f.MoveCursorRight,f.MoveCursorRightOfWord,f.NavToPreviousContainer,f.NavToNextContainer,f.NavPreviousItem,f.NavNextItem,f.SetViewDense,f.SetViewWide,f.Confirm,f.Exit,f.InitCommandLine,f.InitCommandPalette,f.ExitCommandLine,f.CaptureInput,f.EraseInput,f.EraseInputWord,f.HideHelp,f.ViewHelp,f.SetViewDense,f.SetViewWide,f.GetLastCommandFromHistory,f.GetNextCommandFromHistory,f.AutoCompleteCommand]),Od=async e=>{if(e.ctrl&&e.name==="c")return T.exit();let{actionIndex:t,mode:n,readOnly:r}=v(),o=Qs(e,n);if(!o||r&&!lp.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(s){logger.error(s)}},up=()=>async function(t,n){n.name!=="escape"&&(Ue&&(clearTimeout(Ue),Ue=void 0),await Od(n))},mp=()=>async function(t){if(t.length===1&&t[0]===27){Ue&&clearTimeout(Ue),Ue=setTimeout(()=>{Od({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),Ue=void 0},25);return}Ue&&(clearTimeout(Ue),Ue=void 0)};function Bd(){kr&&process.stdin.removeListener("keypress",kr),Dr&&process.stdin.removeListener("data",Dr),kr=up(),Dr=mp(),cp.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Dr),process.stdin.on("keypress",kr)}Ia();gp(`${Fr.bold("Epiq CLI")}
58
58
 
59
- ${kr.dim("Boot in directory:")}
60
- ${kr.cyan("$ epiq")}
59
+ ${Fr.dim("Boot in directory:")}
60
+ ${Fr.cyan("$ epiq")}
61
61
 
62
- `,{importMeta:import.meta,flags:{init:{type:"boolean",default:!1}}});var Bd=process.stdout.columns||120,Ud=process.stdout.rows||20,Dr=null,mp=e=>{try{return Dr?(Dr.rerender(e),c("Rerendered app",void 0)):(Dr=cp(e),c("Rendered app",void 0))}catch(t){return a(`Unable to render app: ${co(t)}`)}},Od=()=>mp(up.createElement(Xo,{width:Bd,height:Ud}));async function pp(){try{let e=Ea();J(e)&&Ee(e.value);let t=Ye(process.cwd()),n=[];if(J(t)){let i=Xe({repoRoot:t.value});if(d(i))return kt(3,i.message);let s=Lt(i.value);if(d(s))return kt(3,s.message);n=s.value}let r=qn(n);if(d(r))return kt(4,r.message);N({hasProjectDefinition:J(t),hasInitializingEvents:!!n.length});let o=Od();return d(o)?kt(6,o.message):(Fd(),c("Booted Epiq",void 0))}catch(e){return kt(0,co(e))}}process.stdout.on("resize",()=>{if(Bd=process.stdout.columns||120,Ud=process.stdout.rows||20,!Dr)return;let e=Od();d(e)&&logger.info(`[boot:resize] ${e.message}`)});(async()=>{console.clear();let e=await pp();d(e)&&(logger.info(e.message),console.error(kr.red(`Failed to boot Epiq:
62
+ `,{importMeta:import.meta,flags:{init:{type:"boolean",default:!1}}});var Ud=process.stdout.columns||120,$d=process.stdout.rows||20,Or=null,vp=e=>{try{return Or?(Or.rerender(e),c("Rerendered app",void 0)):(Or=pp(e),c("Rendered app",void 0))}catch(t){return a(`Unable to render app: ${uo(t)}`)}},_d=()=>vp(fp.createElement(Zo,{width:Ud,height:$d}));async function xp(){try{let e=Na();J(e)&&Ce(e.value);let t=Ye(process.cwd()),n=[];if(J(t)){let i=Xe({repoRoot:t.value});if(d(i))return Ct(3,i.message);let s=Mn(),l=await cn({repoRoot:t.value,stateBranchRoot:i.value,stateBranchName:s.stateBranch});if(d(l))return Ct(3,l.message);let u=await k({cwd:i.value,args:["pull","--ff-only"]});d(u)&&logger.info(3,u.message);let m=kt(i.value);if(d(m))return Ct(3,m.message);n=m.value}let r=Xn(n);if(d(r))return Ct(4,r.message);N({hasProjectDefinition:J(t),hasInitializingEvents:!!n.length});let o=_d();return d(o)?Ct(6,o.message):(Bd(),c("Booted Epiq",void 0))}catch(e){return Ct(0,uo(e))}}process.stdout.on("resize",()=>{if(Ud=process.stdout.columns||120,$d=process.stdout.rows||20,!Or)return;let e=_d();d(e)&&logger.info(`[boot:resize] ${e.message}`)});(async()=>{console.clear();let e=await xp();d(e)&&(logger.info(e.message),console.error(Fr.red(`Failed to boot Epiq:
63
63
  ${e.message}`)),process.exitCode=1)})();