epiq 0.6.9 → 0.6.10

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