epiq 0.6.7 → 0.6.9

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