epiq 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,66 +1,66 @@
1
1
  #!/usr/bin/env node
2
- import jt from"chalk";import{render as rv}from"ink";import ov from"meow";import sv from"react";import zf from"chalk";var bt={Success:"success",Fail:"fail"},a=e=>({status:bt.Fail,message:e,value:null}),l=(e,t)=>({status:bt.Success,message:e,value:t}),d=e=>e.status==="fail",te=e=>e.status==="success";import{spawn as Dl}from"node:child_process";import Ho from"node:process";var li=e=>{let t=Ho.platform==="darwin"?"open":Ho.platform==="win32"?"cmd":"xdg-open",n=Ho.platform==="win32"?["/c","start","",e]:[e];Dl(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as Of}from"node:fs/promises";import _f from"node:http";import sn from"node:path";import{fileURLToPath as $f}from"node:url";import{decodeTime as Bf,ulid as Ie}from"ulid";import Qo from"node:fs";import ql from"node:os";import Je from"node:path";import wn from"node:fs";import{ulid as Ul}from"ulid";import{z as fr}from"zod";import An from"node:fs";import lt from"node:path";var hv=process.env.IS_LOCAL==="true",ut=".epiq",Ue=".epiq-global",lr="events",Fl="project.json",ur=e=>lt.join(e,ut),mr=e=>lt.join(ur(e),Fl),Tn=e=>lt.join(ur(e),lr),ui=e=>lt.join(e,ut),Bl=e=>{let t=lt.join(e,ut);return An.existsSync(t)&&An.statSync(t).isDirectory()},jo=e=>{let t=mr(e);return An.existsSync(t)&&An.statSync(t).isFile()},pr=e=>{let t=lt.resolve(e);for(;;){if(Bl(t))return l("Resolved closest .epiq root",t);let n=lt.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},Ke=e=>{let t=lt.resolve(e);for(;;){if(jo(t))return l("Resolved closest epiq project root",t);let n=lt.dirname(t);if(n===t)return a("No .epiq/project.json found in any parent");t=n}},mi=e=>{let t=Tn(e);try{return An.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")}},qe=async()=>{let e=await Ye(process.cwd());if(d(e))return e;let t=Te({repoRoot:e.value});return d(t)?t:l("Resolved persist root",t.value)};var Ol="__epiq_state__",_l=fr.object({projectId:fr.string().min(1),stateBranch:fr.string().min(1),createdAt:fr.iso.datetime()}),an=()=>({projectId:Ul(),stateBranch:Ol,createdAt:new Date().toISOString()}),Ct=e=>{let t=mr(e);if(!wn.existsSync(t))return a("Missing .epiq/project.json");try{let n=wn.readFileSync(t,"utf8"),r=JSON.parse(n),o=_l.safeParse(r);return o.success?l("Read project.json",o.data):a(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return a(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},pi=e=>{let t=Ct(e);return d(t)?a(t.message):l("Read projectId",t.value.projectId)},fi=({repoRoot:e,fileContents:t})=>{let n=ur(e),r=mr(e);try{if(wn.mkdirSync(n,{recursive:!0}),wn.existsSync(r)){let o=Ct(e);return d(o)?a(o.message):l("Project already initialized",null)}return wn.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 Vo=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let i=r(...s);if(!n.has(i)){let c=e(...s).then(u=>(d(u)&&n.delete(i),u));n.set(i,c)}return n.get(i)});return o.clear=()=>n.clear(),o};import Mn from"fs";import qo from"path";import $l from"util";var gi=1e3,Wl=50,Go=0,vi=()=>process.env.EPIQ_MCP==="true",yi=()=>{let e=process.cwd(),t=pr(e);return d(t)?vi()?qo.join(process.cwd(),".epiq-mcp.log"):void 0:qo.join(t.value,ut,"log","epiq.log")};function Hl(){let e=yi();if(!e||!Mn.existsSync(e))return;let n=Mn.readFileSync(e,"utf8").split(`
4
- `);if(n[n.length-1]===""&&n.pop(),n.length<=gi)return;let r=n.slice(-gi).join(`
2
+ import Vt from"chalk";import{render as iv}from"ink";import av from"meow";import dv from"react";import qf from"chalk";var Ct={Success:"success",Fail:"fail"},a=e=>({status:Ct.Fail,message:e,value:null}),l=(e,t)=>({status:Ct.Success,message:e,value:t}),d=e=>e.status==="fail",te=e=>e.status==="success";import{spawn as Bl}from"node:child_process";import jo from"node:process";var mi=e=>{let t=jo.platform==="darwin"?"open":jo.platform==="win32"?"cmd":"xdg-open",n=jo.platform==="win32"?["/c","start","",e]:[e];Bl(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as $f}from"node:fs/promises";import Wf from"node:http";import an from"node:path";import{fileURLToPath as Hf}from"node:url";import{decodeTime as Of,ulid as Ie}from"ulid";import Zo from"node:fs";import Xl from"node:os";import Je from"node:path";import Mn from"node:fs";import{ulid as _l}from"ulid";import{z as gr}from"zod";import Tn from"node:fs";import ut from"node:path";var bv=process.env.IS_LOCAL==="true",mt=".epiq",Ue=".epiq-global",ur="events",Ul="project.json",mr=e=>ut.join(e,mt),pr=e=>ut.join(mr(e),Ul),wn=e=>ut.join(mr(e),ur),pi=e=>ut.join(e,mt),Ol=e=>{let t=ut.join(e,mt);return Tn.existsSync(t)&&Tn.statSync(t).isDirectory()},Vo=e=>{let t=pr(e);return Tn.existsSync(t)&&Tn.statSync(t).isFile()},fr=e=>{let t=ut.resolve(e);for(;;){if(Ol(t))return l("Resolved closest .epiq root",t);let n=ut.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},Ke=e=>{let t=ut.resolve(e);for(;;){if(Vo(t))return l("Resolved closest epiq project root",t);let n=ut.dirname(t);if(n===t)return a("No .epiq/project.json found in any parent");t=n}},fi=e=>{let t=wn(e);try{return Tn.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")}},qe=async()=>{let e=await Ye(process.cwd());if(d(e))return e;let t=Te({repoRoot:e.value});return d(t)?t:l("Resolved persist root",t.value)};var $l="__epiq_state__",Wl=gr.object({projectId:gr.string().min(1),stateBranch:gr.string().min(1),createdAt:gr.iso.datetime()}),dn=()=>({projectId:_l(),stateBranch:$l,createdAt:new Date().toISOString()}),Et=e=>{let t=pr(e);if(!Mn.existsSync(t))return a("Missing .epiq/project.json");try{let n=Mn.readFileSync(t,"utf8"),r=JSON.parse(n),o=Wl.safeParse(r);return o.success?l("Read project.json",o.data):a(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return a(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},gi=e=>{let t=Et(e);return d(t)?a(t.message):l("Read projectId",t.value.projectId)},vi=({repoRoot:e,fileContents:t})=>{let n=mr(e),r=pr(e);try{if(Mn.mkdirSync(n,{recursive:!0}),Mn.existsSync(r)){let o=Et(e);return d(o)?a(o.message):l("Project already initialized",null)}return Mn.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 Go=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let i=r(...s);if(!n.has(i)){let c=e(...s).then(u=>(d(u)&&n.delete(i),u));n.set(i,c)}return n.get(i)});return o.clear=()=>n.clear(),o};import Pn from"fs";import Yo from"path";import Hl from"util";var yi=1e3,jl=50,zo=0,hi=()=>process.env.EPIQ_MCP==="true",xi=()=>{let e=process.cwd(),t=fr(e);return d(t)?hi()?Yo.join(process.cwd(),".epiq-mcp.log"):void 0:Yo.join(t.value,mt,"log","epiq.log")};function Vl(){let e=xi();if(!e||!Pn.existsSync(e))return;let n=Pn.readFileSync(e,"utf8").split(`
4
+ `);if(n[n.length-1]===""&&n.pop(),n.length<=yi)return;let r=n.slice(-yi).join(`
5
5
  `)+`
6
- `;Mn.writeFileSync(e,r,"utf8")}function zo(e,t,n=!1){let r=yi();if(!r)return;let o=$l.format(...t),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
7
- `;Mn.mkdirSync(qo.dirname(r),{recursive:!0}),Mn.appendFileSync(r,c,"utf8"),Go++,Go>=Wl&&(Go=0,Hl())}var Ko=()=>vi()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",re={info(...e){let t=Ko();(t==="info"||t==="debug")&&zo("[Info]",e,!1)},debug(...e){Ko()==="debug"&&zo("[Debug]",e,!0)},error(...e){let t=Ko();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;zo("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=re;import{spawn as jl}from"node:child_process";import gr from"node:fs";import Pn from"node:path";var oe={stage:({cwd:e,pathspec:t})=>U({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>U({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>U({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>U({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>U({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push",...r?["-u"]:[],t,n]:["push"];return U({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>U({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>U({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>U({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>U({args:["worktree","prune"],cwd:e})};var dn=e=>{let t=Ke(e);if(d(t))return a("Unable to resolve epiq project root");let n=Ct(t.value);return d(n)?a("Unable to read project.json"):l("Resolved state branch",n.value.stateBranch)},Oe="origin";var hi=1e4,Vl={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Ii=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!gr.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:p,exitCode:1});return}r(a(p));return}let o=jl("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Vl}),s=!1,i="",c="",u=p=>{s||(s=!0,clearTimeout(m),r(p))},m=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${hi}ms`].join(`
8
- `);u(n?{stdout:i,stderr:p,exitCode:124}:a(p))},hi);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{i+=p}),o.stderr.on("data",p=>{c+=p}),o.on("error",p=>{if(n){u({stdout:i,stderr:p.message,exitCode:1});return}u(a([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
6
+ `;Pn.writeFileSync(e,r,"utf8")}function Ko(e,t,n=!1){let r=xi();if(!r)return;let o=Hl.format(...t),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
7
+ `;Pn.mkdirSync(Yo.dirname(r),{recursive:!0}),Pn.appendFileSync(r,c,"utf8"),zo++,zo>=jl&&(zo=0,Vl())}var qo=()=>hi()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",re={info(...e){let t=qo();(t==="info"||t==="debug")&&Ko("[Info]",e,!1)},debug(...e){qo()==="debug"&&Ko("[Debug]",e,!0)},error(...e){let t=qo();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;Ko("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=re;import{spawn as Gl}from"node:child_process";import vr from"node:fs";import Ln from"node:path";var oe={stage:({cwd:e,pathspec:t})=>U({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>U({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>U({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>U({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>U({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push",...r?["-u"]:[],t,n]:["push"];return U({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>U({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>U({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>U({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>U({args:["worktree","prune"],cwd:e})};var cn=e=>{let t=Ke(e);if(d(t))return a("Unable to resolve epiq project root");let n=Et(t.value);return d(n)?a("Unable to read project.json"):l("Resolved state branch",n.value.stateBranch)},Oe="origin";var Ii=1e4,zl={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},bi=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!vr.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:p,exitCode:1});return}r(a(p));return}let o=Gl("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:zl}),s=!1,i="",c="",u=p=>{s||(s=!0,clearTimeout(m),r(p))},m=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${Ii}ms`].join(`
8
+ `);u(n?{stdout:i,stderr:p,exitCode:124}:a(p))},Ii);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{i+=p}),o.stderr.on("data",p=>{c+=p}),o.on("error",p=>{if(n){u({stdout:i,stderr:p.message,exitCode:1});return}u(a([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
9
9
  `)))}),o.on("close",p=>{let v=p??1;if(n){u({stdout:i,stderr:c,exitCode:v});return}if(v!==0){u(a([`git ${e.join(" ")}`,c.trim()||i.trim()||"Git command failed"].filter(Boolean).join(`
10
- `)));return}u(l("Git command succeeded",{stdout:i,stderr:c,exitCode:v}))})}),U=({args:e,cwd:t})=>Ii({args:e,cwd:t,allowFail:!1}),Xe=({args:e,cwd:t})=>Ii({args:e,cwd:t,allowFail:!0}),cn=async({cwd:e,message:t})=>{let n=await oe.commit({cwd:e,message:t});if(d(n))return a(`Failed to create commit
10
+ `)));return}u(l("Git command succeeded",{stdout:i,stderr:c,exitCode:v}))})}),U=({args:e,cwd:t})=>bi({args:e,cwd:t,allowFail:!1}),Xe=({args:e,cwd:t})=>bi({args:e,cwd:t,allowFail:!0}),ln=async({cwd:e,message:t})=>{let n=await oe.commit({cwd:e,message:t});if(d(n))return a(`Failed to create commit
11
11
  ${n.message}`);let r=await U({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())},Gl=async e=>{let t=await U({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",Pn.isAbsolute(n)?n:Pn.resolve(e,n))},zl=async e=>{let t=await Gl(e);if(d(t))return a(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(r))if(gr.existsSync(Pn.join(n,s)))return l("Checked for in-progress Git operation",i);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,i]of Object.entries(o))if(gr.existsSync(Pn.join(n,s)))return l("Checked for in-progress Git operation",i);return l("Checked for in-progress Git operation",null)},vr=async e=>{let t=await zl(e);return d(t)?a(t.message):l("Checked for in-progress Git operation",t.value!==null)},Yo=async({repoRoot:e})=>{let n=(await Xe({args:["remote","get-url",Oe],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},yr=async({repoRoot:e,branch:t})=>{let n=await Xe({args:["ls-remote","--heads",Oe,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${Oe}/${t}`):l("Checked remote branch",n.stdout.trim().length>0)},hr=async({repoRoot:e,branch:t})=>{let n=await Xe({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}`)},xi=e=>{try{return gr.realpathSync.native(e)}catch{return Pn.resolve(e)}},bi=async({repoRoot:e,worktreeRoot:t})=>{let n=await U({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=xi(t),o=n.value.stdout.split(`
13
- `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(xi).includes(r);return l("Checked worktree registration",o)},Xo=async e=>{let t=await Xe({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},xr=async e=>{let t=await U({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?a(t.message):l("Resolved current branch",t.value.stdout.trim())},Ci=async e=>{let t=await U({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"),Kl=async e=>(await Xe({cwd:e,args:["rebase","--abort"]})).exitCode===0?l("Aborted stale rebase",!0):l("No rebase to abort",!1);var Jo=async({cwd:e,branch:t})=>{let n=await yr({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 Kl(e);if(d(r))return a(r.message);let o=await oe.fetch({cwd:e,remote:Oe,branch:t});if(d(o))return a(`Failed to fetch ${t}
12
+ ${r.message}`):l("Created commit and resolved SHA",r.value.stdout.trim())},Kl=async e=>{let t=await U({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",Ln.isAbsolute(n)?n:Ln.resolve(e,n))},ql=async e=>{let t=await Kl(e);if(d(t))return a(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(r))if(vr.existsSync(Ln.join(n,s)))return l("Checked for in-progress Git operation",i);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,i]of Object.entries(o))if(vr.existsSync(Ln.join(n,s)))return l("Checked for in-progress Git operation",i);return l("Checked for in-progress Git operation",null)},yr=async e=>{let t=await ql(e);return d(t)?a(t.message):l("Checked for in-progress Git operation",t.value!==null)},Xo=async({repoRoot:e})=>{let n=(await Xe({args:["remote","get-url",Oe],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},hr=async({repoRoot:e,branch:t})=>{let n=await Xe({args:["ls-remote","--heads",Oe,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${Oe}/${t}`):l("Checked remote branch",n.stdout.trim().length>0)},xr=async({repoRoot:e,branch:t})=>{let n=await Xe({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}`)},kn=e=>{try{return vr.realpathSync.native(e)}catch{return Ln.resolve(e)}},Ci=async({repoRoot:e,worktreeRoot:t})=>{let n=await U({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=kn(t),o=n.value.stdout.split(`
13
+ `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(kn).includes(r);return l("Checked worktree registration",o)},Jo=async e=>{let t=await Xe({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Ir=async e=>{let t=await U({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?a(t.message):l("Resolved current branch",t.value.stdout.trim())},Ei=async e=>{let t=await U({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"),Yl=async e=>(await Xe({cwd:e,args:["rebase","--abort"]})).exitCode===0?l("Aborted stale rebase",!0):l("No rebase to abort",!1);var Qo=async({cwd:e,branch:t})=>{let n=await hr({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 Yl(e);if(d(r))return a(r.message);let o=await oe.fetch({cwd:e,remote:Oe,branch:t});if(d(o))return a(`Failed to fetch ${t}
14
14
  ${o.message}`);let s=await oe.pullRebase({cwd:e,remote:Oe,branch:t});return d(s)?a(`Failed during pull --rebase
15
- ${s.message}`):l("Pulled with rebase",!0)},Ei=async e=>{let t=await Xe({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 Ni=async e=>{let t=await xr(e);return d(t)?a(t.message):l("Checked detached HEAD state",t.value==="HEAD")};var Ai="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Zo=e=>Je.join(ut,lr,e),Ti=()=>Je.join(ql.homedir(),Ue),Ir=()=>Je.join(Ti(),"worktrees"),Te=({repoRoot:e})=>{let t=pi(e);return d(t)?a(t.message):l("Resolved state branch root",Je.join(Ir(),t.value))},Yl=e=>Je.join(e,ut),Ri=e=>Je.join(Yl(e),lr);var Ln=e=>{try{return Qo.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},br=()=>{let e=Ln(Ti());if(d(e))return a(`Ensure epiq home failed.
16
- `+e.message);let t=Ln(Ir());return d(t)?a(`Ensure worktrees dir failed.
17
- `+t.message):l("Ensured epiq storage",!0)},wi=e=>{Qo.existsSync(e)&&(re.debug("[sync] remove path",e),Qo.rmSync(e,{recursive:!0,force:!0}))};var Mi=(e,t)=>{for(let n of[Ri(e),Ri(t)]){let r=Ln(n);if(d(r))return a(r.message)}return l("Ensured state branch",void 0)},Pi=async e=>{let t=await U({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return a(`ensure state branch is storage only failed
15
+ ${s.message}`):l("Pulled with rebase",!0)},Ni=async e=>{let t=await Xe({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 Ri=async e=>{let t=await Ir(e);return d(t)?a(t.message):l("Checked detached HEAD state",t.value==="HEAD")};var Ti="4b825dc642cb6eb9a060e54bf8d69288fbee4904",es=e=>Je.join(mt,ur,e),wi=()=>Je.join(Xl.homedir(),Ue),br=()=>Je.join(wi(),"worktrees"),Te=({repoRoot:e})=>{let t=gi(e);return d(t)?a(t.message):l("Resolved state branch root",Je.join(br(),t.value))},Jl=e=>Je.join(e,mt),Ai=e=>Je.join(Jl(e),ur);var Dn=e=>{try{return Zo.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},Cr=()=>{let e=Dn(wi());if(d(e))return a(`Ensure epiq home failed.
16
+ `+e.message);let t=Dn(br());return d(t)?a(`Ensure worktrees dir failed.
17
+ `+t.message):l("Ensured epiq storage",!0)},Mi=e=>{Zo.existsSync(e)&&(re.debug("[sync] remove path",e),Zo.rmSync(e,{recursive:!0,force:!0}))};var Pi=(e,t)=>{for(let n of[Ai(e),Ai(t)]){let r=Dn(n);if(d(r))return a(r.message)}return l("Ensured state branch",void 0)},Li=async e=>{let t=await U({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(i=>i!==ut);if(r.length===0)return l("State branch is storage-only",!1);let o=await U({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return a(`Failed to clean storage branch
20
- ${o.message}`);let s=await cn({cwd:e,message:"[epiq:repair-storage-branch]"});return d(s)?a(s.message):l("Cleaned storage branch",!0)},Ye=Vo(async(e=process.cwd())=>{let t=await U({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=>Je.resolve(e)),ay=Vo(async e=>{let t=await U({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return a(t.message);let n=t.value.stdout.trim(),r=Je.isAbsolute(n)?n:Je.join(e,n);return l("Resolved git dir",r)},e=>Je.resolve(e));import ln from"node:fs";import kn from"node:path";var ki=async e=>{if((await Xe({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return l("Initial commit already exists",!1);re.info("Creating initial commit");let n=await oe.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?a(n.message):l("Created initial commit",!0)},Li=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Xl=async e=>{let t=await xr(e);if(d(t))return a(t.message);let n=await Ci(e);return d(n)?a(n.message):l("Built sync commit message",`[sync|branch:${Li(t.value)}:sha:${Li(n.value)}]`)},es=async({repoRoot:e,stateBranchName:t})=>{re.info(`Creating ${t}`);let n=await U({args:["commit-tree",Ai,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return a(`Failed to create state branch commit
19
+ `).filter(Boolean).filter(i=>i!==mt);if(r.length===0)return l("State branch is storage-only",!1);let o=await U({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return a(`Failed to clean storage branch
20
+ ${o.message}`);let s=await ln({cwd:e,message:"[epiq:repair-storage-branch]"});return d(s)?a(s.message):l("Cleaned storage branch",!0)},Ye=Go(async(e=process.cwd())=>{let t=await U({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=>Je.resolve(e)),ly=Go(async e=>{let t=await U({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return a(t.message);let n=t.value.stdout.trim(),r=Je.isAbsolute(n)?n:Je.join(e,n);return l("Resolved git dir",r)},e=>Je.resolve(e));import un from"node:fs";import ts from"node:path";var Di=async e=>{if((await Xe({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return l("Initial commit already exists",!1);re.info("Creating initial commit");let n=await oe.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?a(n.message):l("Created initial commit",!0)},ki=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Ql=async e=>{let t=await Ir(e);if(d(t))return a(t.message);let n=await Ei(e);return d(n)?a(n.message):l("Built sync commit message",`[sync|branch:${ki(t.value)}:sha:${ki(n.value)}]`)},ns=async({repoRoot:e,stateBranchName:t})=>{re.info(`Creating ${t}`);let n=await U({args:["commit-tree",Ti,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return a(`Failed to create state branch commit
21
21
  ${n.message}`);let r=n.value.stdout.trim(),o=await U({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return d(o)?a(`Failed to create ${t}
22
- ${o.message}`):l("Created state branch",!0)},Jl=async({repoRoot:e,stateBranchName:t})=>{let n=await Yo({repoRoot:e});if(d(n))return a(`Ensure local state branch failed
23
- `+n.message);let r=n.value,o=r?await yr({repoRoot:e,branch:t}):l("No remote, no remote state branch",!1);if(d(o))return a(`Ensure local state branch failed
22
+ ${o.message}`):l("Created state branch",!0)},Zl=async({repoRoot:e,stateBranchName:t})=>{let n=await Xo({repoRoot:e});if(d(n))return a(`Ensure local state branch failed
23
+ `+n.message);let r=n.value,o=r?await hr({repoRoot:e,branch:t}):l("No remote, no remote state branch",!1);if(d(o))return a(`Ensure local state branch failed
24
24
  `+o.message);let s=o.value;if(r&&s){let c=await oe.fetch({cwd:e,remote:Oe,branch:t});if(d(c))return a(`Failed to fetch ${t} from remote
25
- ${c.message}`)}let i=await hr({repoRoot:e,branch:t});if(d(i))return a(`Ensure local state branch failed
25
+ ${c.message}`)}let i=await xr({repoRoot:e,branch:t});if(d(i))return a(`Ensure local state branch failed
26
26
  `+i.message);if(i.value)return l("Local state branch already exists",!1);if(s){let c=await U({args:["branch","--track",t,`${Oe}/${t}`],cwd:e});return d(c)?a(`Failed to create local ${t} from remote
27
- ${c.message}`):l("Created local state branch from remote",!0)}return es({repoRoot:e,stateBranchName:t})},Ql=async({repoRoot:e,branch:t})=>{let n=await U({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=n.value.stdout.split(`
28
- `),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return l("Found worktree for branch",o)}return l("No worktree found for branch",null)},Zl=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Ln(kn.dirname(t));if(d(r))return a(`Failed to create state branch worktree
29
- `+r.message);ln.existsSync(t)&&!ln.existsSync(kn.join(t,".git"))&&(re.info("Removing broken state branch worktree path"),wi(t)),re.info("Creating state branch worktree");let o=await oe.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(o)?a(`Failed to create state branch worktree
30
- ${o.message}`):l("Created state branch worktree",!0)},Vt=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await Ql({repoRoot:e,branch:n});if(d(r))return a(r.message);let o=kn.resolve(t),s=r.value?kn.resolve(r.value):null;if(s&&s===o&&ln.existsSync(s))return l("State branch already checked out in expected worktree",!1);if(s&&s!==o){re.info("Moving state branch worktree to expected location");let u=await oe.worktreeRemove({cwd:e,worktreeRoot:s});if(d(u))return a(`Failed to remove existing state branch worktree
31
- ${u.message}`)}if(s&&!ln.existsSync(s)){re.info("Pruning stale state branch worktree");let u=await oe.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
32
- ${u.message}`)}let i=await bi({repoRoot:e,worktreeRoot:t});if(d(i))return a(i.message);let c=ln.existsSync(t);if(i.value&&c)return l("State branch worktree already exists",!1);if(i.value&&!c){re.info("Pruning missing registered state branch worktree");let u=await oe.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
33
- ${u.message}`)}return Zl({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},eu=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await xr(e);if(d(n))return a(n.message);if(n.value===t)return l("State branch already checked out",!1);(await Xe({cwd:e,args:["rebase","--abort"]})).exitCode===0&&re.info("Aborted stale state branch rebase");let o=await oe.checkout({cwd:e,branch:t});return d(o)?a(`Failed to checkout ${t}
34
- ${o.message}`):l("Checked out state branch",!0)},tu=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Xo(t);if(d(n))return a(n.message);if(n.value)return l("State branch upstream already configured",!1);let r=await Yo({repoRoot:t});if(d(r))return a(r.message);if(!r.value)return l("No remote available for state branch upstream",!1);let o=dn(e);if(d(o))return o;let s=o.value,i=await yr({repoRoot:t,branch:s});if(d(i))return a(i.message);if(!i.value)return l("Remote state branch missing; upstream will be configured on first push",!1);re.info(`Configuring ${s} upstream`);let c=await oe.fetch({cwd:t,remote:Oe,branch:s});if(d(c))return a(`Failed to fetch ${s}
27
+ ${c.message}`):l("Created local state branch from remote",!0)}return ns({repoRoot:e,stateBranchName:t})},eu=async({repoRoot:e,branch:t})=>{let n=await U({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=n.value.stdout.split(`
28
+ `),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return l("Found worktree for branch",o)}return l("No worktree found for branch",null)},tu=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Dn(ts.dirname(t));if(d(r))return a(`Failed to create state branch worktree
29
+ `+r.message);un.existsSync(t)&&!un.existsSync(ts.join(t,".git"))&&(re.info("Removing broken state branch worktree path"),Mi(t)),re.info("Creating state branch worktree");let o=await oe.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(o)?a(`Failed to create state branch worktree
30
+ ${o.message}`):l("Created state branch worktree",!0)},Gt=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await eu({repoRoot:e,branch:n});if(d(r))return a(r.message);let o=kn(t),s=r.value?kn(r.value):null;if(s&&s===o&&un.existsSync(s))return l("State branch already checked out in expected worktree",!1);if(s&&s!==o){re.info("Moving state branch worktree to expected location");let u=await oe.worktreeRemove({cwd:e,worktreeRoot:s});if(d(u))return a(`Failed to remove existing state branch worktree
31
+ ${u.message}`)}if(s&&!un.existsSync(s)){re.info("Pruning stale state branch worktree");let u=await oe.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
32
+ ${u.message}`)}let i=await Ci({repoRoot:e,worktreeRoot:t});if(d(i))return a(i.message);let c=un.existsSync(t);if(i.value&&c)return l("State branch worktree already exists",!1);if(i.value&&!c){re.info("Pruning missing registered state branch worktree");let u=await oe.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
33
+ ${u.message}`)}return tu({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},nu=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Ir(e);if(d(n))return a(n.message);if(n.value===t)return l("State branch already checked out",!1);(await Xe({cwd:e,args:["rebase","--abort"]})).exitCode===0&&re.info("Aborted stale state branch rebase");let o=await oe.checkout({cwd:e,branch:t});return d(o)?a(`Failed to checkout ${t}
34
+ ${o.message}`):l("Checked out state branch",!0)},ru=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Jo(t);if(d(n))return a(n.message);if(n.value)return l("State branch upstream already configured",!1);let r=await Xo({repoRoot:t});if(d(r))return a(r.message);if(!r.value)return l("No remote available for state branch upstream",!1);let o=cn(e);if(d(o))return o;let s=o.value,i=await hr({repoRoot:t,branch:s});if(d(i))return a(i.message);if(!i.value)return l("Remote state branch missing; upstream will be configured on first push",!1);re.info(`Configuring ${s} upstream`);let c=await oe.fetch({cwd:t,remote:Oe,branch:s});if(d(c))return a(`Failed to fetch ${s}
35
35
  ${c.message}`);let u=await oe.setUpstream({cwd:t,branch:s,upstream:`${Oe}/${s}`});return d(u)?a(`Failed to set state branch upstream
36
- ${u.message}`):l("Configured state branch upstream",!0)},Cr=async({stateBranchRoot:e,eventFileName:t})=>{let n=Zo(t),r=kn.join(e,n);if(!ln.existsSync(r))return l("No event file to stage",void 0);let o=await oe.stage({cwd:e,pathspec:[n]});return d(o)?a(`Failed to stage state branch event file
37
- ${o.message}`):l("Staged state branch event file",void 0)},Di=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Xl(e);return d(n)?a(`Create state branch sync commit failed
38
- `+n.message):cn({cwd:t,message:n.value})},Dn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Xo(t);if(d(n))return a(n.message);let r=dn(e);if(d(r))return r;let o=r.value,s=n.value?await oe.push({cwd:t}):await oe.push({cwd:t,remote:Oe,branch:o,setUpstream:!0});return d(s)?a(`Failed during state branch push
39
- ${s.message}`):l("Pushed state branch",!0)},Fi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=dn(e);if(d(o))return o;let s=o.value,i=[br(),await Jl({repoRoot:e,stateBranchName:s}),await Vt({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await eu({stateBranchRoot:t,stateBranchName:s}),await Pi(t),n?await tu({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(d(c))return a(c.message);r=r||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{WebSocket as nu}from"ws";var Sr=new Set,Bi=e=>{Sr.add(e),e.on("close",()=>{Sr.delete(e)}),e.on("error",()=>{Sr.delete(e)})},Gt=e=>{let t=JSON.stringify(e);for(let n of Sr)n.readyState===nu.OPEN&&n.send(t)};import{useSyncExternalStore as Pf}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function ts(e){return e.context===P.WORKSPACE}function w(e){return e.context===P.TICKET}function St(e){return e.context===P.TEXT}function Qe(e){return e.context===P.FIELD}function Fn(e){return e.context===P.FIELD_LIST}var Et=e=>e.context===P.SWIMLANE,Er=e=>e.context===P.BOARD,Bn=e=>e.context===P.COMMENT;var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var Ui=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Oi=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",_i=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",$i=(e,t)=>{if(Oi(e,e.sequence))return h.MoveCursorLeftOfWord;if(_i(e,e.sequence))return h.MoveCursorRightOfWord;if(Ui(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.GetLastCommandFromHistory;case"down":return h.GetNextCommandFromHistory;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}},Wi=(e,t)=>{if(Oi(e,e.sequence))return h.MoveCursorLeftOfWord;if(_i(e,e.sequence))return h.MoveCursorRightOfWord;if(Ui(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.NavPreviousItem;case"down":return h.NavNextItem;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}};function Nr(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var un=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Nt=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Hi=e=>e.charAt(0).toUpperCase()+e.slice(1);var ji=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},Vi=(e,t)=>t?e.get(t)??[]:[];var Gi=new WeakMap,ru=e=>{let t=Gi.get(e);return t||(t=ji(e),Gi.set(e,t)),t};var zi=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Vi(ru(e),r).filter(s=>Nr(r,s)>=n)};var ou={hint:"",hints:[],overlap:0,remainder:""},Ki=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return ou;let o=zi({wordList:r,inputToMatch:e,overlapThreshold:1});return su(t,o)},su=(e,t)=>{let n=t[0]??"",r=Nr(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,p=(c&&i?o:n)+(c&&i?":":" "),v=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:v}};import{useSyncExternalStore as iu}from"react";var Un={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},ns=new Set,au=()=>{for(let e of ns)e()},H=()=>Un,qi=()=>iu(e=>(ns.add(e),()=>{ns.delete(e)}),()=>Un),_e=e=>(Un={...Un,...e},au(),Un);import{ulid as lu}from"ulid";var mn=24n,du=mn*4n,Ze=(1n<<du)-1n,cu=/^[0-9a-f]+$/;function Yi(e){return!e||!cu.test(e)?a(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function $e(e,t=mn){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 Ee(e,t){if(!e&&!t)return $e(Ze/2n,mn);let n=e?Yi(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?Yi(t):l("Resolved upper bound",Ze);if(d(r))return r;let o=n.value,s=r.value;if(s<=o)return $e(Ze/2n,mn);let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):$e(i,mn)}function Xi(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Ze*BigInt(r+1)/(t+1n),s=$e(o,mn);if(d(s))return s;n.push(s.value)}return l("Resolved evenly spaced ranks",n)}var rs=(e,t)=>{let n=z(e),r=Xi(n.length);if(d(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],c=r.value[s];if(!i||!c)return a("Unable to assign rebalance rank");o[i.id]=c}return l("Created rebalance event",{id:lu(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as cm}from"ulid";var mt=(e,t)=>{let{nodes:n}=f(),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}`)},os=(e,t)=>{let{nodes:n}=f(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},zt=(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={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.userId&&n.userId!==t)return a("Contributor is already linked to another user");let r={...n,userId:t},o=fe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to link contributor to user"):l("Linked contributor to user",r)},deleteNode(e){fe(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create comment, missing issue");if(!w(t))return a("Can only comment on issues");let n=fe(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create comment"):l("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return a("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return a("Unable to edit comment, missing issue");if(!w(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=fe(i=>({...i,comments:{...i.comments??{},[e]:o}}));return d(s)?a("Unable to edit comment"):l("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return a("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=fe(o=>({...o,comments:{...o.comments??{},[e]:n}}));return d(r)?a("Unable to delete comment"):l("Deleted comment",n)},getComment(e){return f().comments?.[e]},getCommentsByIssue(e){return Object.values(f().comments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=f(),r=n[e];if(!r)return a("Edit target node not found");let o=zt(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),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=zt(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return z(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=f(),o=this.getNode(e),s=this.getNode(t);if(!o)return a("Node not found");if(!s)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 i=zt(o,"move");if(i)return i;if(os(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}=f(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=new Set,i=u=>{let m=t[u];if(!(!m||s.has(u))){s.add(u);for(let p of z(m.id))i(p.id)}};i(e);let c={...structuredClone(t)};for(let u of s){if(!c[u])return a("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(C({nodes:c}),l("Successfully tomb stoned",o)):a("Unable to delete undefined")},createContributor(e){let t=fe(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=zt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return a("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),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=zt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return l("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),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=zt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return a("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),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=zt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return l("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),l("Tag removed",{tag:t})},createTag(e){let t=fe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):l("Tag created",e)},createNode(e){let t=fe(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=fe(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):l("Locked node",n)},updateNode(e){let t=fe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return f().contributors[e]},getTag(e){return f().tags[e]},getNode(e){return f().nodes[e]},getSiblings(e){return z(e)}};var se={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments"};var Q={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.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:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};import Kt from"chalk";import ra from"string-width";import{decodeTime as vu}from"ulid";import fn from"chalk";var ge={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},y={accent:ge.cyan,accent2:ge.magenta,primary:ge.white,secondary:ge.grayDark,secondary2:ge.grayLight,gray:ge.gray,green:ge.green,yellow:ge.yellow,red:ge.red};var S={red:ge.red,yellow:ge.yellow,green:ge.green,blue:ge.blue,magenta:ge.magenta,cyan:ge.cyan},pn={urgent:S.red,critical:S.red,important:S.red,blocker:S.red,asap:S.red,immediate:S.red,fail:S.red,failure:S.red,broken:S.red,bug:S.red,error:S.red,incident:S.red,outage:S.red,production:S.red,crash:S.red,security:S.red,warning:S.yellow,warn:S.yellow,risky:S.yellow,risk:S.yellow,attention:S.yellow,pending:S.yellow,review:S.yellow,"needs-review":S.yellow,qa:S.yellow,testing:S.yellow,test:S.yellow,validate:S.yellow,verification:S.yellow,staging:S.yellow,check:S.yellow,"follow-up":S.yellow,followup:S.yellow,waiting:S.yellow,blocked:S.yellow,hold:S.yellow,done:S.green,complete:S.green,completed:S.green,success:S.green,ok:S.green,stable:S.green,resolved:S.green,fixed:S.green,closed:S.green,merged:S.green,released:S.green,deployed:S.green,approved:S.green,verified:S.green,working:S.green,healthy:S.green,pass:S.green,passing:S.green,info:S.blue,information:S.blue,note:S.blue,docs:S.blue,documentation:S.blue,doc:S.blue,guide:S.blue,help:S.blue,explanation:S.blue,detail:S.blue,details:S.blue,context:S.blue,design:S.blue,discussion:S.blue,proposal:S.blue,idea:S.blue,feature:S.magenta,enhancement:S.magenta,improvement:S.magenta,refactor:S.magenta,refactoring:S.magenta,cleanup:S.magenta,optimize:S.magenta,optimization:S.magenta,perf:S.magenta,performance:S.magenta,upgrade:S.magenta,migration:S.magenta,modernize:S.magenta,debt:S.magenta,todo:S.cyan,next:S.cyan,planned:S.cyan,plan:S.cyan,future:S.cyan,backlog:S.cyan,investigate:S.cyan,explore:S.cyan,prototype:S.cyan};var is={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Ji=(e,t,n)=>Math.max(t,Math.min(n,e)),ss=(e,t,n)=>e+(t-e)*n,Qi=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},uu=e=>e.toLowerCase().trim(),mu=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,c=s*(1-Math.abs(i%2-1)),u=0,m=0,p=0;i>=0&&i<1?(u=s,m=c):i>=1&&i<2?(u=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<5?(u=c,p=s):(u=s,p=c);let v=o-s/2;return[Math.round((u+v)*255),Math.round((m+v)*255),Math.round((p+v)*255)]},Zi=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var pu=(e,t,n)=>{let r=Ji(n,0,1);return[Math.round(ss(e[0],t[0],r)),Math.round(ss(e[1],t[1],r)),Math.round(ss(e[2],t[2],r))]};var fu=(e,t,n)=>pu(e,t,n),On=e=>{let n=Qi(e)%360,r=mu(n,is.stringColor.saturation,is.stringColor.lightness);return Zi(r)},ie=(e,t=pn)=>{let n=uu(e);return n&&t[n]?t[n]:On(n)};var ea=e=>{let t=is.gradient.stops,n=Ji(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,s=Math.min(Math.floor(o),r-1),i=o-s;return fu(t[s],t[s+1],i)},Rr=e=>Zi(ea(e)),Ar=e=>Qi(e.toLowerCase().trim())/4294967295,ta=e=>{let t=Ar(e);return ea(t)},gu=e=>{let[t,n,r]=ta(e);return{normal:o=>fn.bgRgb(t,n,r).black(o),cursor:o=>fn.bgRgb(t,n,r).white.bold(o)}},as=e=>{let[t,n,r]=ta(e);return{fg:o=>fn.rgb(t,n,r)(o),fgCursor:o=>fn.rgb(t,n,r).inverse(o),bg:o=>fn.bgRgb(t,n,r).black(o),bgCursor:o=>fn.bgRgb(t,n,r).white.bold(o)}},Tr=e=>gu(e).normal(` ${e} `);import{decodeTime as na}from"ulid";var wr=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 s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"},Mr=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())}`},Pr=e=>{try{return l("Decoded date",new Date(na(e)))}catch(t){return a("Decoding failed + "+t.message)}},gn=e=>{if(!e?.id)return null;try{return na(e.id)}catch{return null}};var yu=(e,t)=>e+" ".repeat(Math.max(0,t-ra(e))),hu=(e,t)=>" ".repeat(Math.max(0,t-ra(e)))+e,oa=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),xu=(e,t)=>t?e<t?"up":e>t?"down":null:null,Iu=(e,t)=>{let n=b.getNode(e.payload.parent),r=n?Kt.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=xu(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},bu=e=>{switch(e.action){case"add.issue.tag":{let t=f().tags[e.payload.tag];return t?Kt.bgHex(ie(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?Kt.bgHex(ie(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?Kt.hex(ie(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?Kt.hex(ie(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""}},Cu=e=>{let t=wr(vu(e));return Kt.gray(hu(t,8))},Su=12,Eu=e=>yu(`${e}`,Su),Nu=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?t.name:""}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}"`:"";case"move.node":{let t=b.getNode(e.payload.parent);return t?`to ${t.title}`:""}default:return""}},sa=e=>[oa(e.action),Nu(e)].filter(Boolean).join(" "),ia=(e,t)=>{let n=Cu(e.id),r=Eu(e.userName),o=Kt.dim("\u203A"),s=e.action==="move.node"?Iu(e,t):[oa(e.action),bu(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};import{createHash as Ru}from"node:crypto";var Au="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Tu=e=>{let t=Ru("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 s=BigInt((25-o)*5);r+=Au[Number(n>>s&31n)]}return r},Ne=(e,t)=>Tu(`${e}:virtual:${t}`);var wu=e=>Ne(e,"comments"),Mu=e=>Ne(e,"description"),Pu=e=>Ne(e,"assignees"),Lu=e=>Ne(e,"tags"),ku=e=>Ne(e,"history"),ds=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=b.getNode(e);if(!c){let p=b.createNode({...Q.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:l("Virtual field created",void 0)}if(!Qe(c))return a(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==i))return l("Virtual field unchanged",void 0);let m=b.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return d(m)?m:l("Virtual field updated",void 0)},aa=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=b.getNode(e);if(!i){let m=b.createNode({...Q.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return d(m)?m:l("Virtual field list created",void 0)}if(!Fn(i))return a(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return l("Virtual field list unchanged",void 0);let u=b.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return d(u)?u:l("Virtual field list updated",void 0)},da=e=>{let t=$e(Ze/4n),n=$e(Ze/2n),r=$e(Ze*3n/4n),o=$e(Ze*7n/8n),s=$e(Ze*13n/16n);if(d(t))return t;if(d(n))return n;if(d(r))return r;if(d(o))return o;if(d(s))return s;let i=ds({id:Mu(e.id),name:se.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(i))return i;let c=aa({id:Pu(e.id),name:se.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(c))return c;let u=aa({id:Lu(e.id),name:se.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(u))return u;let m=ds({id:wu(e.id),name:se.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(m))return m;let p=ds({id:ku(e.id),name:se.HISTORY,parentNodeId:e.id,rank:s.value,value:Du(e),readonly:!0,childRenderAxis:"vertical"});return d(p)?p:l("Ticket virtual nodes materialized",void 0)},Du=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=>ia(r,n.get(r.action)??[])).join(`
40
- `)};var Fu=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ce,Lr]=Fu;var D=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),ca=e=>{let t=b.getNode(e);if(!t||!w(t)||t.isDeleted)return null;let n=da(t);return d(n)?n:null},Bu=e=>{for(let t of e){let n=ca(t);if(n)return n;let r=f().nodes[t]?.parentNodeId;if(!r)continue;let o=ca(r);if(o)return o}return null},Uu=(e,t)=>{let n=b.getNode(e);n&&b.updateNode({...n,log:[...n.log??[],t]})},Ou=e=>{let t=[e],n=f().nodes[e]?.parentNodeId;return n&&t.push(n),t},cs=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":return[e.payload.issue];case"delete.node":case"edit.description":return Ou(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"create.contributor":case"link.contributor.user":default:return[]}},_u=e=>{fe(t=>({...t,eventLog:[...t.eventLog,e]}))},$u=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?D("Invalid user ID format",e):l("Valid user",null)},Wu=(e,t)=>{let n=$u(e);if(d(n))return n;let r=[...new Set(cs(e))];t||(r.forEach(s=>Uu(s,e)),_u(e));let o=Bu(r);return o||null},Hu={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Q.workspace(t,n,r),s=_n(o);if(d(s))return D(s.message,e);let i=b.createNode(o);return d(i)?D(i.message??"Failed to initialize workspace",e):ts(i.value)?l("Workspace initialized",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=b.createNode(Q.workspace(t,n,r));return d(o)?D(o.message??"Failed to add workspace",e):ts(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,s=b.createNode(Q.board(t,n,r,o));return d(s)?D(s.message??"Unable to create board",e):Er(s.value)?l("Added board",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=b.createNode(Q.swimlane(t,n,r,o));return d(s)?D(s.message??"Unable to create swimlane",e):Et(s.value)?l("Added swimlane",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=b.createNode(Q.ticket(t,n,r,o));return d(s)?D(s.message??"Unable to create issue",e):w(s.value)?l("Added issue",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=b.createNode(Q.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(se.DESCRIPTION)?"vertical":"horizontal"}));return d(i)?D(i.message??`Unable to create field: ${n}`,e):Qe(i.value)?l("Added field",{action:e.action,result:i.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!b.getNode(t))return D(`Unable to locate node with id ${t}`,e);let o=b.renameNode(t,n);return d(o)?D(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)?D(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)?D(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)?D(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)?D(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)?D(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)?D(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)?D(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)?D(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)?D(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 D("Unable to locate issue",e);if(!w(o))return D("Can only close issues",e);let s=b.getNode(ce);if(!s)return D("Unable to locate target swimlane",e);if(n!==s.id)return D("Close target must be closed swimlane",e);let i=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(i)?D(i.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 D("Unable to locate issue",e);if(!w(o))return D("Can only reopen issues",e);let s=b.getNode(ce);if(!s)return D("Unable to locate closed swimlane",e);if(n===s.id)return D("Cannot reopen issue into closed swimlane",e);if(!b.getNode(n))return D("Reopen parent no longer exists",e);let c=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?D(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)?D(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 s=b.getNode(r);if(!s)return D(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return D(`Node ${r} is not child of ${t}`,e);let i=b.updateNode({...s,rank:o});if(d(i))return D(i.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=b.createComment({id:t,issue:n,authorId:r,authorName:b.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return d(s)?D(s.message??"Unable to add comment",e):l("Comment added",{action:e.action,result:{id:t,issue:n,author:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=e.payload,o=b.getComment(t);if(!o)return D("Unable to locate comment",e);if(o.issue!==n)return D("Comment does not belong to issue",e);let s=b.editComment(t,r);return d(s)?D(s.message??"Unable to edit comment",e):l("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=b.getComment(t);if(!r)return D("Unable to locate comment",e);if(r.issue!==n)return D("Comment does not belong to issue",e);let o=b.deleteComment(t);return d(o)?D(o.message??"Unable to delete comment",e):l("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=b.linkUserId({contributorId:t,userId:e.userId});return d(n)?D(n.message??"Unable to link contributor",e):l("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function Rt(e,t=!1){let n=Hu[e.action](e);if(d(n))return n;let r=Wu(e,t);return r||n}var At=e=>e.map(t=>Rt(t));import Zu from"node:fs";import em from"node:path";import{decodeTime as tm,monotonicFactory as nm}from"ulid";import{z as $n}from"zod";import kr from"node:fs";import us from"node:path";import{decodeTime as ju}from"ulid";import{z as ls}from"zod";var Vu=ls.object({userId:ls.string().min(1).default("unknown"),userName:ls.string().min(1).default("unknown")}),Gu=e=>{let[t,n]=us.basename(e,".jsonl").split("."),r=Vu.safeParse({userId:t,userName:n});return r.success?l("Parsed event file actor",r.data):a(`Invalid event file name ${us.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},zu=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])},Ku=(e,t)=>t in e,qu=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Yu=e=>{let{userId:t,userName:n,...r}=e,o=zu(r);if(d(o))return a(o.message);let s=o.value,i=e.id?.[0];return i?Ku(r,s)?l("Decoded persisted event",qu({id:i,action:s,payload:r[s],userId:t,userName:n})):a(`Persisted event is missing payload for action: ${s}`):a("Persisted event is missing id")},ms=e=>{let t=[];for(let n of e){let r=Yu(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)},Xu=e=>{if(!kr.existsSync(e))return l("Event file missing",[]);let t=Gu(e);if(d(t))return a(t.message);let n=kr.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
41
- `)){let s=o.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{return a(`Failed to parse event JSON from ${e}: ${s}`)}let c=fs(i);if(d(c))return a(`${c.message} in ${e}: ${s}`);r.push({...c.value,userId:t.value.userId,userName:t.value.userName})}return l("Parsed persisted events file",r)};function ps(e){let t=Tn(e);if(!kr.existsSync(t))return l("No events found",[]);let n=kr.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>us.join(t,o)),r=[];for(let o of n){let s=Xu(o);if(d(s))return a(s.message);r.push(...s.value)}return l("All events loaded",Ju(r))}function pt(e){let t=ps(e);return d(t)?a(t.message):ms(t.value)}function la(e,t){let n=ps(e);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=Qu(n.value,t),s=ms(r);if(d(s))return a(s.message);let i=ms(o);return d(i)?a(i.message):l("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:i.value})}function ua(e=process.cwd()){let t=ps(e);return d(t)?a(t.message):l("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Ju=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],v=m.id[1]??null;t.set(p,m);let I=n.get(v)??[];I.push(m),n.set(v,I)}for(let m of n.values())m.sort((p,v)=>p.id[0].localeCompare(v.id[0]));let r=[],o=new Set,s=m=>{let p=m.id[0];if(o.has(p))return;r.push(m),o.add(p);let v=n.get(p)??[];for(let I of v)s(I)},i=n.get(null)??[];for(let m of i)s(m);let c=e.filter(m=>{let p=m.id[0],v=m.id[1]??null;return!o.has(p)&&v!==null&&!t.has(v)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of c)s(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)s(m);return r},Qu=(e,t)=>{let n=new Set,r=[],o=[];for(let s of e){let i=s.id[0],c=s.id[1],u=!1;try{u=ju(i)<t}catch{u=!1}!u||c&&n.has(c)?(n.add(i),o.push(s)):r.push(s)}return{appliedEvents:r,unappliedEvents:o}};var ma=e=>({action:e.action,payload:e.payload});var ga=1,pa=nm(),rm=$n.tuple([$n.string().min(1),$n.string().min(1).nullable()]),om=$n.looseObject({v:$n.literal(ga),id:rm}),fs=e=>{let t=om.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(", ")}`)},fa=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",sm=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),im=e=>e.trim().length>0&&e.length<=80,Z=()=>{let{userName:e,userId:t}=H();return e?t?sm(t)?im(e)?l("Successfully resolved actor ID",{userId:t,userName:e}):a("Invalid user name in config"):a("Invalid user ID in config"):a("User ID not configured"):a("User name not configured")},qt=({userId:e,userName:t})=>`${fa(e)}.${fa(t)}.jsonl`,am=(e,{userId:t,userName:n})=>{let r=qt({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return a(`Invalid event log file name: ${r}`);let s=em.join(Tn(e),r);return l("Successfully resolved event log path",s)},dm=(e,t)=>{let n={[e.action]:e.payload,v:ga,id:t};return fs(n)};function Dr({event:e,rootDir:t}){try{let n=mi(t);if(d(n))return n;let r=am(t,{userId:e.userId,userName:e.userName});if(d(r))return r;let o=ua(t);if(d(o))return a(o.message);let s=o.value?pa(Math.max(Date.now(),tm(o.value)+1)):pa(),i=dm(ma(e),[s,o.value]);return d(i)?a(i.message):(Zu.appendFileSync(r.value,`${JSON.stringify(i.value)}
42
- `,"utf8"),l("Event persisted",{path:r.value,entry:i.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return a(`Failed to persist event: ${r}`)}}function va(e,t){let n=Rt(e);if(n.status!==bt.Success)return n;let r=Dr({event:e,rootDir:t});return d(r)?r:n}function B(e,t){if(e.length===0||!e[0])return a("No events provided");let n=lm(e[0],t);if(d(n))return n;let r=e.map(s=>va(s,t)),o=r.filter(d);return o.length>0?a("Materialize and persist failed: "+o.map(s=>s.message).join(", ")):l("Materialization succeeded",r.map(s=>s.value))}var lm=(e,t)=>{if(e.action==="create.contributor")return l("Contributor already being created",void 0);if(b.getContributor(e.userId))return l("Contributor exists",void 0);let n={id:cm(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},r=va(n,t);return d(r)?a(r.message):l("Contributor created",void 0)};var ya=e=>Fr(z(e),{at:"end"}),Fr=(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(Ee(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(Ee(void 0,r.rank)):a("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(Ee(r.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let r=ha(e,t.sibling);if(r<0)return a("Sibling not found");let o=r>0?e[r-1]:void 0,s=e[r];return s?n(Ee(o?.rank,s.rank)):a("Sibling not found")}case"after":{let r=ha(e,t.sibling);if(r<0)return a("Sibling not found");let o=e[r],s=r<e.length-1?e[r+1]:void 0;return o?n(Ee(o.rank,s?.rank)):a("Sibling not found")}}},z=e=>Object.values(f().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),ha=(e,t)=>e.findIndex(n=>n.id===t),xa=(e,t,n={at:"end"})=>Fr(z(t).filter(r=>r.id!==e),n),Yt=(e,t,n,r,o)=>{let s=xa(t,e,n);if(d(s))return s;if(!s.value.needsRebalance)return l("Resolved rank",s.value.rank);let i=rs(e,r);if(d(i))return i;let c=B([i.value],o);if(d(c))return c;let u=xa(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)},vn=(e,t,n)=>{let r=ya(e);if(d(r))return r;if(!r.value.needsRebalance)return l("Resolved rank",r.value.rank);let o=rs(e,t);if(d(o))return o;let s=B([o.value],n);if(d(s))return s;let i=ya(e);return d(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)};var M={exit(){process.exit(0)},enterChildNode(){let e=f(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=W(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||M.navigate({contextNode:o,selectedIndex:W(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=f();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=W(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;M.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Ia(1),navigateToPreviousItem:()=>Ia(-1),navigateToNextContainer:()=>ba(1),navigateToPreviousContainer:()=>ba(-1),navigate:({contextNode:e,selectedIndex:t})=>{C({contextNodeId:e.id,selectedIndex:t})}},Ia=e=>{let{selectedIndex:t,contextNode:n}=f(),r=W(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;M.navigate({selectedIndex:s,contextNode:n})},ba=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=f();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=W(o.id),i=s.findIndex(I=>I.id===t.id);if(i<0)return;let c=s.at(i+e)??s.at(0);if(!c)return;let u=W(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),v=u.length?p:-1;M.navigate({contextNode:c,selectedIndex:v})};var Sa=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Ea=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=f();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},um=e=>{let t=f().nodes[e];return!!t&&!t.isDeleted&&Qe(t)&&t.childRenderAxis==="vertical"},Br=(e,t)=>{let{nodes:n}=f(),r=n[e];if(!r||r.isDeleted)return!1;let o=z(r.id);return M.navigate({contextNode:r,selectedIndex:Sa(t,o.length)}),!0},Na=e=>{let{nodes:t}=f(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Br(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=z(o.id).findIndex(c=>c.id===n.id);return i>=0?(M.navigate({contextNode:o,selectedIndex:i}),!0):Na(o.id)},Ca=e=>{let{nodes:t}=f(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Na(n))return!0;n=t[n]?.parentNodeId}return!1},mm=e=>{if(!e)return!1;let t=f().nodes[e];return!!t&&!t.isDeleted},Ra=e=>{let{nodes:t,rootNodeId:n}=f();if(um(e.contextNodeId)&&Br(e.contextNodeId,e.selectedIndex))return l("Restored navigation inside text container",null);if(mm(e.selectedNodeId)&&e.selectedNodeId&&Ca(e.selectedNodeId))return l("Restored navigation to selected node or ancestor",null);if(Br(e.contextNodeId,e.selectedIndex))return l("Restored navigation to previous container",null);if(e.parentNodeId&&Br(e.parentNodeId,e.selectedIndex))return l("Restored navigation to previous parent",null);if(Ca(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=z(r.id);return M.navigate({contextNode:r,selectedIndex:Sa(e.selectedIndex,o.length)}),l("Restored navigation to root",null)};import{monotonicFactory as pm,ulid as ft}from"ulid";var Wn=pm();function fm(){let e=We();if(d(e))return a("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)throw new Error("No workspace found in event log");let[r]=W(n.id),[o]=r?W(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return l("Resolved boot nav target",{contextNode:o,selectedIndex:s.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 gm(){let e=fm();return d(e)?e:M.navigate(e.value)}function Aa({userId:e,userName:t}){let n=Wn(),r=Wn(),o=Wn(),s=Wn(),i=Wn(),c=Ee(void 0,void 0);if(d(c))return c;let u=Ee(void 0,void 0);if(d(u))return u;let m=Ee(u.value,void 0);if(d(m))return m;let p=Ee(void 0,void 0);if(d(p))return p;let v=Ee(p.value,void 0);if(d(v))return v;let I=Ee(v.value,void 0);if(d(I))return I;let E=Ee(void 0,void 0);return d(E)?E:l("Created default events",[{id:ft(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:ft(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:v.value}},{id:ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:I.value}},{id:ft(),userId:e,userName:t,action:"add.board",payload:{id:Lr,name:"Closed",parent:n,rank:m.value}},{id:ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:ce,name:"Closed",parent:Lr,rank:E.value}},{id:ft(),userId:e,userName:t,action:"lock.node",payload:{id:Lr}},{id:ft(),userId:e,userName:t,action:"lock.node",payload:{id:ce}}])}function Xt(e){if(!e.length){let r=Q.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=_n(r);return d(o)?o:(C({hasProjectDefinition:!1,mode:g.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=At(e).filter(d);return n.length>0?a(`Materializing failed:
36
+ ${u.message}`):l("Configured state branch upstream",!0)},Er=async({stateBranchRoot:e,eventFileName:t})=>{let n=es(t),r=ts.join(e,n);if(!un.existsSync(r))return l("No event file to stage",void 0);let o=await oe.stage({cwd:e,pathspec:[n]});return d(o)?a(`Failed to stage state branch event file
37
+ ${o.message}`):l("Staged state branch event file",void 0)},Fi=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Ql(e);return d(n)?a(`Create state branch sync commit failed
38
+ `+n.message):ln({cwd:t,message:n.value})},Fn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Jo(t);if(d(n))return a(n.message);let r=cn(e);if(d(r))return r;let o=r.value,s=n.value?await oe.push({cwd:t}):await oe.push({cwd:t,remote:Oe,branch:o,setUpstream:!0});return d(s)?a(`Failed during state branch push
39
+ ${s.message}`):l("Pushed state branch",!0)},Bi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=cn(e);if(d(o))return o;let s=o.value,i=[Cr(),await Zl({repoRoot:e,stateBranchName:s}),await Gt({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await nu({stateBranchRoot:t,stateBranchName:s}),await Li(t),n?await ru({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(d(c))return a(c.message);r=r||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{WebSocket as ou}from"ws";var Sr=new Set,Ui=e=>{Sr.add(e),e.on("close",()=>{Sr.delete(e)}),e.on("error",()=>{Sr.delete(e)})},zt=e=>{let t=JSON.stringify(e);for(let n of Sr)n.readyState===ou.OPEN&&n.send(t)};import{useSyncExternalStore as kf}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function rs(e){return e.context===P.WORKSPACE}function w(e){return e.context===P.TICKET}function St(e){return e.context===P.TEXT}function Qe(e){return e.context===P.FIELD}function Bn(e){return e.context===P.FIELD_LIST}var Nt=e=>e.context===P.SWIMLANE,Nr=e=>e.context===P.BOARD,Un=e=>e.context===P.COMMENT;var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var Oi=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",_i=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",$i=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Wi=(e,t)=>{if(_i(e,e.sequence))return h.MoveCursorLeftOfWord;if($i(e,e.sequence))return h.MoveCursorRightOfWord;if(Oi(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.GetLastCommandFromHistory;case"down":return h.GetNextCommandFromHistory;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}},Hi=(e,t)=>{if(_i(e,e.sequence))return h.MoveCursorLeftOfWord;if($i(e,e.sequence))return h.MoveCursorRightOfWord;if(Oi(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.NavPreviousItem;case"down":return h.NavNextItem;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}};function Rr(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var mn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Rt=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),ji=e=>e.charAt(0).toUpperCase()+e.slice(1);var Vi=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},Gi=(e,t)=>t?e.get(t)??[]:[];var zi=new WeakMap,su=e=>{let t=zi.get(e);return t||(t=Vi(e),zi.set(e,t)),t};var Ki=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Gi(su(e),r).filter(s=>Rr(r,s)>=n)};var iu={hint:"",hints:[],overlap:0,remainder:""},qi=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return iu;let o=Ki({wordList:r,inputToMatch:e,overlapThreshold:1});return au(t,o)},au=(e,t)=>{let n=t[0]??"",r=Rr(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,p=(c&&i?o:n)+(c&&i?":":" "),v=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:v}};import{useSyncExternalStore as du}from"react";var On={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},os=new Set,cu=()=>{for(let e of os)e()},H=()=>On,Yi=()=>du(e=>(os.add(e),()=>{os.delete(e)}),()=>On),_e=e=>(On={...On,...e},cu(),On);import{ulid as mu}from"ulid";var pn=24n,lu=pn*4n,Ze=(1n<<lu)-1n,uu=/^[0-9a-f]+$/;function Xi(e){return!e||!uu.test(e)?a(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function $e(e,t=pn){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 Se(e,t){if(!e&&!t)return $e(Ze/2n,pn);let n=e?Xi(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?Xi(t):l("Resolved upper bound",Ze);if(d(r))return r;let o=n.value,s=r.value;if(s<=o)return $e(Ze/2n,pn);let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):$e(i,pn)}function Ji(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Ze*BigInt(r+1)/(t+1n),s=$e(o,pn);if(d(s))return s;n.push(s.value)}return l("Resolved evenly spaced ranks",n)}var ss=(e,t)=>{let n=z(e),r=Ji(n.length);if(d(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],c=r.value[s];if(!i||!c)return a("Unable to assign rebalance rank");o[i.id]=c}return l("Created rebalance event",{id:mu(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as um}from"ulid";var pt=(e,t)=>{let{nodes:n}=f(),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}`)},is=(e,t)=>{let{nodes:n}=f(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Kt=(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={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.userId&&n.userId!==t)return a("Contributor is already linked to another user");let r={...n,userId:t},o=fe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to link contributor to user"):l("Linked contributor to user",r)},deleteNode(e){fe(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create comment, missing issue");if(!w(t))return a("Can only comment on issues");let n=fe(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create comment"):l("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return a("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return a("Unable to edit comment, missing issue");if(!w(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=fe(i=>({...i,comments:{...i.comments??{},[e]:o}}));return d(s)?a("Unable to edit comment"):l("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return a("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=fe(o=>({...o,comments:{...o.comments??{},[e]:n}}));return d(r)?a("Unable to delete comment"):l("Deleted comment",n)},getComment(e){return f().comments?.[e]},getCommentsByIssue(e){return Object.values(f().comments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=f(),r=n[e];if(!r)return a("Edit target node not found");let o=Kt(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),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=Kt(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return z(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=f(),o=this.getNode(e),s=this.getNode(t);if(!o)return a("Node not found");if(!s)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 i=Kt(o,"move");if(i)return i;if(is(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}=f(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=new Set,i=u=>{let m=t[u];if(!(!m||s.has(u))){s.add(u);for(let p of z(m.id))i(p.id)}};i(e);let c={...structuredClone(t)};for(let u of s){if(!c[u])return a("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(C({nodes:c}),l("Successfully tomb stoned",o)):a("Unable to delete undefined")},createContributor(e){let t=fe(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=Kt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return a("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),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=Kt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return l("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),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=Kt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return a("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),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=Kt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return l("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),l("Tag removed",{tag:t})},createTag(e){let t=fe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):l("Tag created",e)},createNode(e){let t=fe(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=fe(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):l("Locked node",n)},updateNode(e){let t=fe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return f().contributors[e]},getTag(e){return f().tags[e]},getNode(e){return f().nodes[e]},getSiblings(e){return z(e)}};var se={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments"};var et=e=>e.slice(-7).toUpperCase(),Qi=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?et(e).includes(n):!0};var Q={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:et(e)},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:et(e)},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};import qt from"chalk";import sa from"string-width";import{decodeTime as hu}from"ulid";import gn from"chalk";var ge={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},y={accent:ge.cyan,accent2:ge.magenta,primary:ge.white,secondary:ge.grayDark,secondary2:ge.grayLight,gray:ge.gray,green:ge.green,yellow:ge.yellow,red:ge.red};var E={red:ge.red,yellow:ge.yellow,green:ge.green,blue:ge.blue,magenta:ge.magenta,cyan:ge.cyan},fn={urgent:E.red,critical:E.red,important:E.red,blocker:E.red,asap:E.red,immediate:E.red,fail:E.red,failure:E.red,broken:E.red,bug:E.red,error:E.red,incident:E.red,outage:E.red,production:E.red,crash:E.red,security:E.red,warning:E.yellow,warn:E.yellow,risky:E.yellow,risk:E.yellow,attention:E.yellow,pending:E.yellow,review:E.yellow,"needs-review":E.yellow,qa:E.yellow,testing:E.yellow,test:E.yellow,validate:E.yellow,verification:E.yellow,staging:E.yellow,check:E.yellow,"follow-up":E.yellow,followup:E.yellow,waiting:E.yellow,blocked:E.yellow,hold:E.yellow,done:E.green,complete:E.green,completed:E.green,success:E.green,ok:E.green,stable:E.green,resolved:E.green,fixed:E.green,closed:E.green,merged:E.green,released:E.green,deployed:E.green,approved:E.green,verified:E.green,working:E.green,healthy:E.green,pass:E.green,passing:E.green,info:E.blue,information:E.blue,note:E.blue,docs:E.blue,documentation:E.blue,doc:E.blue,guide:E.blue,help:E.blue,explanation:E.blue,detail:E.blue,details:E.blue,context:E.blue,design:E.blue,discussion:E.blue,proposal:E.blue,idea:E.blue,feature:E.magenta,enhancement:E.magenta,improvement:E.magenta,refactor:E.magenta,refactoring:E.magenta,cleanup:E.magenta,optimize:E.magenta,optimization:E.magenta,perf:E.magenta,performance:E.magenta,upgrade:E.magenta,migration:E.magenta,modernize:E.magenta,debt:E.magenta,todo:E.cyan,next:E.cyan,planned:E.cyan,plan:E.cyan,future:E.cyan,backlog:E.cyan,investigate:E.cyan,explore:E.cyan,prototype:E.cyan};var ds={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Zi=(e,t,n)=>Math.max(t,Math.min(n,e)),as=(e,t,n)=>e+(t-e)*n,ea=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},pu=e=>e.toLowerCase().trim(),fu=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,c=s*(1-Math.abs(i%2-1)),u=0,m=0,p=0;i>=0&&i<1?(u=s,m=c):i>=1&&i<2?(u=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<5?(u=c,p=s):(u=s,p=c);let v=o-s/2;return[Math.round((u+v)*255),Math.round((m+v)*255),Math.round((p+v)*255)]},ta=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var gu=(e,t,n)=>{let r=Zi(n,0,1);return[Math.round(as(e[0],t[0],r)),Math.round(as(e[1],t[1],r)),Math.round(as(e[2],t[2],r))]};var vu=(e,t,n)=>gu(e,t,n),_n=e=>{let n=ea(e)%360,r=fu(n,ds.stringColor.saturation,ds.stringColor.lightness);return ta(r)},ie=(e,t=fn)=>{let n=pu(e);return n&&t[n]?t[n]:_n(n)};var na=e=>{let t=ds.gradient.stops,n=Zi(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,s=Math.min(Math.floor(o),r-1),i=o-s;return vu(t[s],t[s+1],i)},Ar=e=>ta(na(e)),Tr=e=>ea(e.toLowerCase().trim())/4294967295,ra=e=>{let t=Tr(e);return na(t)},yu=e=>{let[t,n,r]=ra(e);return{normal:o=>gn.bgRgb(t,n,r).black(o),cursor:o=>gn.bgRgb(t,n,r).white.bold(o)}},cs=e=>{let[t,n,r]=ra(e);return{fg:o=>gn.rgb(t,n,r)(o),fgCursor:o=>gn.rgb(t,n,r).inverse(o),bg:o=>gn.bgRgb(t,n,r).black(o),bgCursor:o=>gn.bgRgb(t,n,r).white.bold(o)}},wr=e=>yu(e).normal(` ${e} `);import{decodeTime as oa}from"ulid";var Mr=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 s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"},Pr=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())}`},Lr=e=>{try{return l("Decoded date",new Date(oa(e)))}catch(t){return a("Decoding failed + "+t.message)}},vn=e=>{if(!e?.id)return null;try{return oa(e.id)}catch{return null}};var xu=(e,t)=>e+" ".repeat(Math.max(0,t-sa(e))),Iu=(e,t)=>" ".repeat(Math.max(0,t-sa(e)))+e,ia=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),bu=(e,t)=>t?e<t?"up":e>t?"down":null:null,Cu=(e,t)=>{let n=b.getNode(e.payload.parent),r=n?qt.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=bu(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Eu=e=>{switch(e.action){case"add.issue.tag":{let t=f().tags[e.payload.tag];return t?qt.bgHex(ie(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?qt.bgHex(ie(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?qt.hex(ie(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?qt.hex(ie(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""}},Su=e=>{let t=Mr(hu(e));return qt.gray(Iu(t,8))},Nu=12,Ru=e=>xu(`${e}`,Nu),Au=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?t.name:""}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}"`:"";case"move.node":{let t=b.getNode(e.payload.parent);return t?`to ${t.title}`:""}default:return""}},aa=e=>[ia(e.action),Au(e)].filter(Boolean).join(" "),da=(e,t)=>{let n=Su(e.id),r=Ru(e.userName),o=qt.dim("\u203A"),s=e.action==="move.node"?Cu(e,t):[ia(e.action),Eu(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};import{createHash as Tu}from"node:crypto";var wu="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Mu=e=>{let t=Tu("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 s=BigInt((25-o)*5);r+=wu[Number(n>>s&31n)]}return r},Ne=(e,t)=>Mu(`${e}:virtual:${t}`);var Pu=e=>Ne(e,"comments"),Lu=e=>Ne(e,"description"),ku=e=>Ne(e,"assignees"),Du=e=>Ne(e,"tags"),Fu=e=>Ne(e,"history"),ls=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=b.getNode(e);if(!c){let p=b.createNode({...Q.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:l("Virtual field created",void 0)}if(!Qe(c))return a(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==i))return l("Virtual field unchanged",void 0);let m=b.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return d(m)?m:l("Virtual field updated",void 0)},ca=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=b.getNode(e);if(!i){let m=b.createNode({...Q.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return d(m)?m:l("Virtual field list created",void 0)}if(!Bn(i))return a(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return l("Virtual field list unchanged",void 0);let u=b.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return d(u)?u:l("Virtual field list updated",void 0)},la=e=>{let t=$e(Ze/4n),n=$e(Ze/2n),r=$e(Ze*3n/4n),o=$e(Ze*7n/8n),s=$e(Ze*13n/16n);if(d(t))return t;if(d(n))return n;if(d(r))return r;if(d(o))return o;if(d(s))return s;let i=ls({id:Lu(e.id),name:se.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(i))return i;let c=ca({id:ku(e.id),name:se.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(c))return c;let u=ca({id:Du(e.id),name:se.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(u))return u;let m=ls({id:Pu(e.id),name:se.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(m))return m;let p=ls({id:Fu(e.id),name:se.HISTORY,parentNodeId:e.id,rank:s.value,value:Bu(e),readonly:!0,childRenderAxis:"vertical"});return d(p)?p:l("Ticket virtual nodes materialized",void 0)},Bu=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=>da(r,n.get(r.action)??[])).join(`
40
+ `)};var Uu=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ce,kr]=Uu;var D=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),ua=e=>{let t=b.getNode(e);if(!t||!w(t)||t.isDeleted)return null;let n=la(t);return d(n)?n:null},Ou=e=>{for(let t of e){let n=ua(t);if(n)return n;let r=f().nodes[t]?.parentNodeId;if(!r)continue;let o=ua(r);if(o)return o}return null},_u=(e,t)=>{let n=b.getNode(e);n&&b.updateNode({...n,log:[...n.log??[],t]})},$u=e=>{let t=[e],n=f().nodes[e]?.parentNodeId;return n&&t.push(n),t},us=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":return[e.payload.issue];case"delete.node":case"edit.description":return $u(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"create.contributor":case"link.contributor.user":default:return[]}},Wu=e=>{fe(t=>({...t,eventLog:[...t.eventLog,e]}))},Hu=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?D("Invalid user ID format",e):l("Valid user",null)},ju=(e,t)=>{let n=Hu(e);if(d(n))return n;let r=[...new Set(us(e))];t||(r.forEach(s=>_u(s,e)),Wu(e));let o=Ou(r);return o||null},Vu={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Q.workspace(t,n,r),s=$n(o);if(d(s))return D(s.message,e);let i=b.createNode(o);return d(i)?D(i.message??"Failed to initialize workspace",e):rs(i.value)?l("Workspace initialized",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=b.createNode(Q.workspace(t,n,r));return d(o)?D(o.message??"Failed to add workspace",e):rs(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,s=b.createNode(Q.board(t,n,r,o));return d(s)?D(s.message??"Unable to create board",e):Nr(s.value)?l("Added board",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=b.createNode(Q.swimlane(t,n,r,o));return d(s)?D(s.message??"Unable to create swimlane",e):Nt(s.value)?l("Added swimlane",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=b.createNode(Q.ticket(t,n,r,o));return d(s)?D(s.message??"Unable to create issue",e):w(s.value)?l("Added issue",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=b.createNode(Q.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(se.DESCRIPTION)?"vertical":"horizontal"}));return d(i)?D(i.message??`Unable to create field: ${n}`,e):Qe(i.value)?l("Added field",{action:e.action,result:i.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!b.getNode(t))return D(`Unable to locate node with id ${t}`,e);let o=b.renameNode(t,n);return d(o)?D(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)?D(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)?D(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)?D(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)?D(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)?D(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)?D(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)?D(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)?D(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)?D(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 D("Unable to locate issue",e);if(!w(o))return D("Can only close issues",e);let s=b.getNode(ce);if(!s)return D("Unable to locate target swimlane",e);if(n!==s.id)return D("Close target must be closed swimlane",e);let i=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(i)?D(i.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 D("Unable to locate issue",e);if(!w(o))return D("Can only reopen issues",e);let s=b.getNode(ce);if(!s)return D("Unable to locate closed swimlane",e);if(n===s.id)return D("Cannot reopen issue into closed swimlane",e);if(!b.getNode(n))return D("Reopen parent no longer exists",e);let c=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?D(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)?D(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 s=b.getNode(r);if(!s)return D(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return D(`Node ${r} is not child of ${t}`,e);let i=b.updateNode({...s,rank:o});if(d(i))return D(i.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=b.createComment({id:t,issue:n,authorId:r,authorName:b.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return d(s)?D(s.message??"Unable to add comment",e):l("Comment added",{action:e.action,result:{id:t,issue:n,author:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=e.payload,o=b.getComment(t);if(!o)return D("Unable to locate comment",e);if(o.issue!==n)return D("Comment does not belong to issue",e);let s=b.editComment(t,r);return d(s)?D(s.message??"Unable to edit comment",e):l("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=b.getComment(t);if(!r)return D("Unable to locate comment",e);if(r.issue!==n)return D("Comment does not belong to issue",e);let o=b.deleteComment(t);return d(o)?D(o.message??"Unable to delete comment",e):l("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=b.linkUserId({contributorId:t,userId:e.userId});return d(n)?D(n.message??"Unable to link contributor",e):l("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function At(e,t=!1){let n=Vu[e.action](e);if(d(n))return n;let r=ju(e,t);return r||n}var Tt=e=>e.map(t=>At(t));import tm from"node:fs";import nm from"node:path";import{decodeTime as rm,monotonicFactory as om}from"ulid";import{z as Wn}from"zod";import Dr from"node:fs";import ps from"node:path";import{decodeTime as Gu}from"ulid";import{z as ms}from"zod";var zu=ms.object({userId:ms.string().min(1).default("unknown"),userName:ms.string().min(1).default("unknown")}),Ku=e=>{let[t,n]=ps.basename(e,".jsonl").split("."),r=zu.safeParse({userId:t,userName:n});return r.success?l("Parsed event file actor",r.data):a(`Invalid event file name ${ps.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},qu=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])},Yu=(e,t)=>t in e,Xu=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Ju=e=>{let{userId:t,userName:n,...r}=e,o=qu(r);if(d(o))return a(o.message);let s=o.value,i=e.id?.[0];return i?Yu(r,s)?l("Decoded persisted event",Xu({id:i,action:s,payload:r[s],userId:t,userName:n})):a(`Persisted event is missing payload for action: ${s}`):a("Persisted event is missing id")},fs=e=>{let t=[];for(let n of e){let r=Ju(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)},Qu=e=>{if(!Dr.existsSync(e))return l("Event file missing",[]);let t=Ku(e);if(d(t))return a(t.message);let n=Dr.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
41
+ `)){let s=o.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{return a(`Failed to parse event JSON from ${e}: ${s}`)}let c=vs(i);if(d(c))return a(`${c.message} in ${e}: ${s}`);r.push({...c.value,userId:t.value.userId,userName:t.value.userName})}return l("Parsed persisted events file",r)};function gs(e){let t=wn(e);if(!Dr.existsSync(t))return l("No events found",[]);let n=Dr.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>ps.join(t,o)),r=[];for(let o of n){let s=Qu(o);if(d(s))return a(s.message);r.push(...s.value)}return l("All events loaded",Zu(r))}function ft(e){let t=gs(e);return d(t)?a(t.message):fs(t.value)}function ma(e,t){let n=gs(e);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=em(n.value,t),s=fs(r);if(d(s))return a(s.message);let i=fs(o);return d(i)?a(i.message):l("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:i.value})}function pa(e=process.cwd()){let t=gs(e);return d(t)?a(t.message):l("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Zu=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],v=m.id[1]??null;t.set(p,m);let I=n.get(v)??[];I.push(m),n.set(v,I)}for(let m of n.values())m.sort((p,v)=>p.id[0].localeCompare(v.id[0]));let r=[],o=new Set,s=m=>{let p=m.id[0];if(o.has(p))return;r.push(m),o.add(p);let v=n.get(p)??[];for(let I of v)s(I)},i=n.get(null)??[];for(let m of i)s(m);let c=e.filter(m=>{let p=m.id[0],v=m.id[1]??null;return!o.has(p)&&v!==null&&!t.has(v)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of c)s(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)s(m);return r},em=(e,t)=>{let n=new Set,r=[],o=[];for(let s of e){let i=s.id[0],c=s.id[1],u=!1;try{u=Gu(i)<t}catch{u=!1}!u||c&&n.has(c)?(n.add(i),o.push(s)):r.push(s)}return{appliedEvents:r,unappliedEvents:o}};var fa=e=>({action:e.action,payload:e.payload});var ya=1,ga=om(),sm=Wn.tuple([Wn.string().min(1),Wn.string().min(1).nullable()]),im=Wn.looseObject({v:Wn.literal(ya),id:sm}),vs=e=>{let t=im.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(", ")}`)},va=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",am=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),dm=e=>e.trim().length>0&&e.length<=80,Z=()=>{let{userName:e,userId:t}=H();return e?t?am(t)?dm(e)?l("Successfully resolved actor ID",{userId:t,userName:e}):a("Invalid user name in config"):a("Invalid user ID in config"):a("User ID not configured"):a("User name not configured")},Yt=({userId:e,userName:t})=>`${va(e)}.${va(t)}.jsonl`,cm=(e,{userId:t,userName:n})=>{let r=Yt({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return a(`Invalid event log file name: ${r}`);let s=nm.join(wn(e),r);return l("Successfully resolved event log path",s)},lm=(e,t)=>{let n={[e.action]:e.payload,v:ya,id:t};return vs(n)};function Fr({event:e,rootDir:t}){try{let n=fi(t);if(d(n))return n;let r=cm(t,{userId:e.userId,userName:e.userName});if(d(r))return r;let o=pa(t);if(d(o))return a(o.message);let s=o.value?ga(Math.max(Date.now(),rm(o.value)+1)):ga(),i=lm(fa(e),[s,o.value]);return d(i)?a(i.message):(tm.appendFileSync(r.value,`${JSON.stringify(i.value)}
42
+ `,"utf8"),l("Event persisted",{path:r.value,entry:i.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return a(`Failed to persist event: ${r}`)}}function ha(e,t){let n=At(e);if(n.status!==Ct.Success)return n;let r=Fr({event:e,rootDir:t});return d(r)?r:n}function B(e,t){if(e.length===0||!e[0])return a("No events provided");let n=mm(e[0],t);if(d(n))return n;let r=e.map(s=>ha(s,t)),o=r.filter(d);return o.length>0?a("Materialize and persist failed: "+o.map(s=>s.message).join(", ")):l("Materialization succeeded",r.map(s=>s.value))}var mm=(e,t)=>{if(e.action==="create.contributor")return l("Contributor already being created",void 0);if(b.getContributor(e.userId))return l("Contributor exists",void 0);let n={id:um(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},r=ha(n,t);return d(r)?a(r.message):l("Contributor created",void 0)};var xa=e=>Br(z(e),{at:"end"}),Br=(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(Se(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(Se(void 0,r.rank)):a("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(Se(r.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let r=Ia(e,t.sibling);if(r<0)return a("Sibling not found");let o=r>0?e[r-1]:void 0,s=e[r];return s?n(Se(o?.rank,s.rank)):a("Sibling not found")}case"after":{let r=Ia(e,t.sibling);if(r<0)return a("Sibling not found");let o=e[r],s=r<e.length-1?e[r+1]:void 0;return o?n(Se(o.rank,s?.rank)):a("Sibling not found")}}},z=e=>Object.values(f().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Ia=(e,t)=>e.findIndex(n=>n.id===t),ba=(e,t,n={at:"end"})=>Br(z(t).filter(r=>r.id!==e),n),Xt=(e,t,n,r,o)=>{let s=ba(t,e,n);if(d(s))return s;if(!s.value.needsRebalance)return l("Resolved rank",s.value.rank);let i=ss(e,r);if(d(i))return i;let c=B([i.value],o);if(d(c))return c;let u=ba(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)},yn=(e,t,n)=>{let r=xa(e);if(d(r))return r;if(!r.value.needsRebalance)return l("Resolved rank",r.value.rank);let o=ss(e,t);if(d(o))return o;let s=B([o.value],n);if(d(s))return s;let i=xa(e);return d(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)};var M={exit(){process.exit(0)},enterChildNode(){let e=f(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=W(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||M.navigate({contextNode:o,selectedIndex:W(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=f();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=W(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;M.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Ca(1),navigateToPreviousItem:()=>Ca(-1),navigateToNextContainer:()=>Ea(1),navigateToPreviousContainer:()=>Ea(-1),navigate:({contextNode:e,selectedIndex:t})=>{C({contextNodeId:e.id,selectedIndex:t})}},Ca=e=>{let{selectedIndex:t,contextNode:n}=f(),r=W(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;M.navigate({selectedIndex:s,contextNode:n})},Ea=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=f();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=W(o.id),i=s.findIndex(I=>I.id===t.id);if(i<0)return;let c=s.at(i+e)??s.at(0);if(!c)return;let u=W(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),v=u.length?p:-1;M.navigate({contextNode:c,selectedIndex:v})};var Na=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Ra=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=f();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},pm=e=>{let t=f().nodes[e];return!!t&&!t.isDeleted&&Qe(t)&&t.childRenderAxis==="vertical"},Ur=(e,t)=>{let{nodes:n}=f(),r=n[e];if(!r||r.isDeleted)return!1;let o=z(r.id);return M.navigate({contextNode:r,selectedIndex:Na(t,o.length)}),!0},Aa=e=>{let{nodes:t}=f(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Ur(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=z(o.id).findIndex(c=>c.id===n.id);return i>=0?(M.navigate({contextNode:o,selectedIndex:i}),!0):Aa(o.id)},Sa=e=>{let{nodes:t}=f(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Aa(n))return!0;n=t[n]?.parentNodeId}return!1},fm=e=>{if(!e)return!1;let t=f().nodes[e];return!!t&&!t.isDeleted},Ta=e=>{let{nodes:t,rootNodeId:n}=f();if(pm(e.contextNodeId)&&Ur(e.contextNodeId,e.selectedIndex))return l("Restored navigation inside text container",null);if(fm(e.selectedNodeId)&&e.selectedNodeId&&Sa(e.selectedNodeId))return l("Restored navigation to selected node or ancestor",null);if(Ur(e.contextNodeId,e.selectedIndex))return l("Restored navigation to previous container",null);if(e.parentNodeId&&Ur(e.parentNodeId,e.selectedIndex))return l("Restored navigation to previous parent",null);if(Sa(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=z(r.id);return M.navigate({contextNode:r,selectedIndex:Na(e.selectedIndex,o.length)}),l("Restored navigation to root",null)};import{monotonicFactory as gm,ulid as gt}from"ulid";var Hn=gm();function vm(){let e=We();if(d(e))return a("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)throw new Error("No workspace found in event log");let[r]=W(n.id),[o]=r?W(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return l("Resolved boot nav target",{contextNode:o,selectedIndex:s.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 ym(){let e=vm();return d(e)?e:M.navigate(e.value)}function wa({userId:e,userName:t}){let n=Hn(),r=Hn(),o=Hn(),s=Hn(),i=Hn(),c=Se(void 0,void 0);if(d(c))return c;let u=Se(void 0,void 0);if(d(u))return u;let m=Se(u.value,void 0);if(d(m))return m;let p=Se(void 0,void 0);if(d(p))return p;let v=Se(p.value,void 0);if(d(v))return v;let I=Se(v.value,void 0);if(d(I))return I;let S=Se(void 0,void 0);return d(S)?S:l("Created default events",[{id:gt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:gt(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:gt(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:gt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:v.value}},{id:gt(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:I.value}},{id:gt(),userId:e,userName:t,action:"add.board",payload:{id:kr,name:"Closed",parent:n,rank:m.value}},{id:gt(),userId:e,userName:t,action:"add.swimlane",payload:{id:ce,name:"Closed",parent:kr,rank:S.value}},{id:gt(),userId:e,userName:t,action:"lock.node",payload:{id:kr}},{id:gt(),userId:e,userName:t,action:"lock.node",payload:{id:ce}}])}function Jt(e){if(!e.length){let r=Q.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=$n(r);return d(o)?o:(C({hasProjectDefinition:!1,mode:g.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=Tt(e).filter(d);return n.length>0?a(`Materializing failed:
43
43
  ${n.map(r=>r.message).join(`
44
- `)}`):(gm(),C({hasProjectDefinition:!0}),l("State booted successfully",null))}var Jt=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),Ur=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)}},K=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);var et=null,Or=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!et,currentStatus:f().syncStatus?.status,currentMessage:f().syncStatus?.msg}),et)return logger.debug("[sync] syncAndReloadState joining existing promise"),et;logger.debug("[sync] syncAndReloadState creating promise"),et=vm();try{let e=await et;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:f().syncStatus?.status,statusMessageAfterResolve:f().syncStatus?.msg}),d(e)&&f().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),C({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),et||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:f().syncStatus?.status,statusMessageBeforeClear:f().syncStatus?.msg}),et=null}},vm=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:f().mode,syncStatus:f().syncStatus});let e=Ta();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:f().mode,message:e.message,syncStatus:f().syncStatus}),e;if(et)return et;logger.debug("[sync] syncAndReloadState:start");let t=K("resolveActorId",Z());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:d(t)?t.message:"Missing actor id"}),a("Unable to resolve event log path");C({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:f().syncStatus});let n=qt(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=K("syncEpiqWithRemote",await _r({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!d(r),message:(d(r),r.message)}),d(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),C({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:f().syncStatus}),He(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let s=K("loadMergedEvents",pt(o));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(s),message:(d(s),s.message),count:d(s)?void 0:s.value.length}),d(s))return C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:f().syncStatus}),a(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let i=Ta();if(i)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:f().mode,message:i.message,syncStatus:f().syncStatus}),i;let c=Ea(),u=f().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:c,selectedNodeId:f().selectedNode?.id,contextNodeId:f().contextNode?.id,selectedNodeIsVirtual:f().selectedNode?.isVirtual,contextNodeIsVirtual:f().contextNode?.isVirtual}),!f().selectedNode?.isVirtual&&!f().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let p=K("bootStateFromEventLog",Xt(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(p),message:(d(p),p.message)}),d(p))return C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:f().syncStatus}),a(`Unable to boot synced state. ${p.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:f().selectedNode?.isVirtual,contextNodeIsVirtual:f().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),C({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=K("restoreNavigationAnchor",Ra(c));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(m),message:d(m)?m.message:"Navigation restored",selectedNodeId:f().selectedNode?.id,contextNodeId:f().contextNode?.id}),d(m)?(C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:f().syncStatus}),m):(C({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:f().syncStatus}),l("Synced",!0))},Ta=()=>f().mode===g.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:f().mode,syncStatus:f().syncStatus}),C({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var yn=3e3,wa=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<yn?null:t},Ma=0,gs,vs=!1,Hn=!1,ys=()=>{if(vs)return!0;let e=We();return d(e)?!1:e.value.syncStatus.status==="syncing"},ym=()=>{let e=H().autoSyncIntervalMs??1e4,t=Date.now()-Ma;return Math.max(0,e-t)},Pa=()=>{gs||(gs=setTimeout(async()=>{if(gs=void 0,!!hn()){if(ys()){Hn=!0;return}Hn=!1,await hm()}},ym()))},hm=async()=>{if(f().readOnly||f().timeMode==="peek"||f().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!hn())return a("Cannot auto-sync before state is initialized");if(ys())return Hn=!0,a("Sync already in progress");vs=!0,Ma=Date.now(),C({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Or()}finally{vs=!1,Hn&&Pa()}},$r=()=>{hn()&&(Hn=!0,!ys()&&Pa())};var Tt=()=>{let e=H(),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}},La=()=>{let e=Ke(process.cwd());if(d(e))return!1;let t=Ct(e.value);return te(t)},ka=e=>e===!0?"on":e===!1?"off":null,Da=e=>e==="on"?!0:e==="off"?!1:null;var xm=e=>e.props.tags??[],Im=e=>e.props.assignees??[],jn=e=>xm(e).map(t=>b.getTag(t)).filter(t=>!!t),Vn=e=>Im(e).map(t=>b.getContributor(t)).filter(t=>!!t),Wr=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!w(n)?a("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",jn(n))},Hr=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!w(n)?a("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",Vn(n))};var x={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""};var bm=/^(\d+)(h|d|w|mo|y)$/,Cm=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Sm=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let s=new Date(e,t-1,n,r,o);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===r&&s.getMinutes()===o},Em=(e,t=new Date)=>{let n=e.match(bm);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(o){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},Nm=e=>{let t=e.match(Cm);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,v=i?Number(i):0;return Sm({year:c,month:u,day:m,hour:p,minute:v})?new Date(c,u-1,m,p,v):null},Qt=e=>{let t=e.trim().toLowerCase();return Em(t)??Nm(t)};var Fa=/^(\d+)(s|m)?$/,jr=e=>{let t=e.trim().toLowerCase().match(Fa);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Vr=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Fa.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Ba=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Rm=[{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}],hs=(e=Rm)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let s=r;s<=o;s++)t.push(`${s}${n}`);return t};var Am=["BOARD","TICKET","SWIMLANE","COMMENT"],ae={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},we={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Tm=[ae.EDITOR,ae.VIEW,ae.USERNAME,ae.AUTOSYNC,ae.SYNC_DEBOUNCE_MS,ae.LOG_LEVEL],wm=(e=f().selectedNode?.context)=>{switch(e){case"TICKET":return[we.TITLE,we.DESCRIPTION];case"BOARD":case"SWIMLANE":return[we.TITLE];case"COMMENT":return[we.COMMENT];default:return[]}},Is=[String(yn),"5000","15000","30000","60000"],_a=["10s","20s","30s","45s"],Zt=[x.COFFEE,x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG],Gr=[x.NEW,x.EDIT,x.DELETE,x.MOVE],xs=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT,x.COMMENT],Ua=[x.FILTER,x.PEEK,x.REPLAY],Mm={WORKSPACE:[...Zt,...Gr],BOARD:[...Ua,...Zt,...Gr],SWIMLANE:[...Ua,...Zt,...Gr],TICKET:[...Zt,...Gr,...xs],FIELD:[...Zt,...xs],FIELD_LIST:[...Zt,...xs],TEXT:[...Zt],COMMENT:[x.EDIT,x.DELETE]},Pm=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],$a=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&w(n)),Oa=e=>e.parentNodeId===ce,Lm=({selectedNode:e,breadCrumb:t})=>{let n=wm(e?.context);return $a({breadCrumb:t,selectedNode:e})?n.includes(we.DESCRIPTION)?n:[...n,we.DESCRIPTION]:n},km=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Tt();if(!r)return[x.HELP,x.CONFIG];if(!La())return[x.HELP,x.INIT];if(t)return[x.HELP,x.PEEK,x.REPLAY,x.EXPORT,x.CONFIG];let o=e?.context,s=o&&Am.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?Mm[u]:[]))],c=$a({breadCrumb:n,selectedNode:e});return i.filter(u=>u===x.MOVE?!1:u===x.EDIT?s||!!c:u===x.DELETE?s:u===x.UNTAG?!!(c&&jn(c).length>0):u===x.UNASSIGN?!!(c&&Vn(c).length>0):u===x.RE_OPEN_ISSUE?!!(c&&Oa(c)):u===x.CLOSE_ISSUE?!!(c&&!Oa(c)):!0)},le=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=f())=>{let s=t.context??"WORKSPACE";return{[x.NONE]:km({breadCrumb:o,readOnly:r,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.HELP]:[],[x.PEEK]:[...hs(),"now","prev","next"],[x.REPLAY]:[...hs()],[x.EDIT]:Lm({selectedNode:n,breadCrumb:o}),[x.COMMENT]:[],[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(pn),...b.getExistingTags()])],[x.UNTAG]:[...Wr()?.value?.map(({name:c})=>c)??[]],[x.UNASSIGN]:[...Hr()?.value?.map(({name:c})=>c)??[]],[x.ASSIGN]:b.getExistingAssignees(),[x.NEW]:Pm(s),[x.CONFIG]:[...Tm],[x.COFFEE]:["1","3","5","20","custom"]}[e]??[]};import Ga from"chalk";var Wa=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var be=(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 Ha from"chalk";var J=e=>Ha.dim(e),ve=e=>Ha.hex(y.primary)(e),ye=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(v=>v.startsWith(i))].sort((v,I)=>Ar(v)-Ar(I)).slice(0,r).map(v=>Tr(v)).join(" ");return p?`${J(e)}${p}${J(n)}`:""};var wt={None:"none",Invalid:"invalid",Valid:"valid"};var xn=140,Dm=["BOARD","TICKET","SWIMLANE"],ja=()=>{let e=f().selectedNode;if(!e?.context)return F({message:J("Missing target context")});if(Dm.includes(e.context))return j();if(e.parentNodeId){let t=f().nodes[e.parentNodeId];if(t?.id===Ne(t?.parentNodeId??"","comments"))return j()}return F({message:J("Command not available in this context")})},ne="<ENTER> to confirm",j=(e="",t=[])=>({message:J(e),validity:wt.Valid,completionWordList:t}),F=({message:e,completionWordList:t=[]})=>({validity:wt.Invalid,message:e,completionWordList:t}),Kr=e=>e.length===0,Va=(e,t)=>{let n=be(f().breadCrumb,"BOARD");if(d(n))return F({message:ve("Command is not applicable in this context")});let r=Pr(n.value.id);return d(r)?F({message:ve(`Unable to ${t}: board id is not a valid ULID`)}):Ba({date:e,horizonDate:r.value})?null:F({message:ve(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},zr=e=>` ${Ga.hex("#000").bgHex(ie(e))(` ${e} `)} `,bs=({modifier:e})=>{let t="confirm";return e===t?j(ne):F({message:Kr(e)?J("if you are certain, enter ")+Tr(t):"",completionWordList:[t]})},Fm=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?F({message:J(n)}):j():F({message:Kr(r)?t:"",completionWordList:[...e]}),en=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>Kr(n)&&Kr(r)?F({message:e,completionWordList:[]}):j(t??ne),Bm=({modifier:e,inputString:t})=>{let n=le(x.CONFIG);if(!n.includes(e))return F({message:ye({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ae.EDITOR:{let r=[...Wa];return t.trim()?r.includes(t.trim())?j(ne):F({message:ye({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):F({message:ye({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ae.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?j(ne):F({message:ye({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ae.USERNAME:return t.trim()?j(ne):F({message:ve("Enter a user name. Saved in ")+Ga.bgBlack("~/.epiq-global/config.json")});case ae.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?j(ne):F({message:ye({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ae.AUTOSYNC:{let r=["on","off"],o=H().autoSync;if(!r.includes(t.trim())){let s=ka(o);return F({message:ye({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return j(ne)}case ae.SYNC_DEBOUNCE_MS:{let r=H().autoSyncIntervalMs,o=wa(t);if(!t.trim()||o===null||o<yn){let s=ye({prefix:" examples: ",wordList:Is,minLengthForHints:0,inputString:t});return F({message:ve(`provide duration above ${yn}ms. current duration: ${r}ms.`)+s,completionWordList:Is})}return j(ne)}default:return F({message:ve("Unknown config option"),completionWordList:n})}},Um=({modifier:e,inputString:t})=>{let n=le(x.EDIT);if(!n.length)return F({message:ve("Command not available in this context")});if(!n.includes(e)){let r=ye({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return F({message:r||ve("Unknown edit option"),completionWordList:n})}switch(e){case we.COMMENT:return t.trim()?j(ne):F({message:J("write a comment...")});case we.TITLE:return j(ne);case we.DESCRIPTION:{let{preferredEditor:r}=H();return r?j(J("<ENTER> to edit in ")+r):F({message:"No editor selected"})}default:return F({message:ve("Unknown edit option"),completionWordList:n})}},Om={[x.EXPORT]:()=>j(ne+J(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return j(ne);let n={message:J("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Qt(r);if(!r||!o)return F(n);let s=Va(o,"peek");return s||j(ne)},[x.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Vr(e.modifier,e.inputString),r={message:J("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Qt(t);if(!t||!o)return F(r);let s=Va(o,"replay");return s||(n&&jr(n)===null?F({message:ve("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):j("<ENTER> to replay board history",n?_a:[]))},[x.EXIT]:()=>j(ne+J(" and exit the application")),[x.INIT]:()=>j(ne),[x.PALETTE]:()=>j(ne),[x.FILTER]:e=>{if(e.modifier==="clear")return j(ne);let t=s=>le(x.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return F({message:ye({wordList:le(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:le(x.FILTER)});let n=Object.values(f().tags).map(s=>s.name),r=Object.values(f().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?F({message:ye({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):j():F({message:ye({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[x.NONE]:e=>{let t=le(x.NONE);return F({message:ye({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>Fm({list:le(x.NEW),hint:ye({wordList:le(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>j(ne),[x.EDIT]:Um,[x.COMMENT]:e=>{let t=en({hint:J(`write a comment (max ${xn} char)...`),onOk:J(`(${e.inputString.length}/${xn})`)})(e);return t.validity===wt.Invalid?t:e.inputString.length>xn?j(ve("max input exceeded")):t},[x.CONFIG]:Bm,[x.DELETE]:e=>{let t=ja();return t.validity==="invalid"?t:bs(e)},[x.CLOSE_ISSUE]:e=>bs(e),[x.RE_OPEN_ISSUE]:e=>bs(e),[x.MOVE]:e=>{let t=ja();return t.validity==="invalid"?t:en({hint:ye({prefix:"hey hacker! These commands are blocked for you... ",wordList:le(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=b.getExistingTags().slice(0,10).map(zr).join("");return en({hint:n.length?J("create tag or reuse:")+n+J(""):J("create tag ...")})(e)},[x.UNTAG]:e=>{let t=Wr();if(d(t))return F({message:ve("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(zr).slice(0,10);return n.length?en({hint:J(" ... ")+n.join("")})(e):F({message:ve("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=b.getExistingAssignees().map(zr).slice(0,10);return en({hint:J("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=Hr();if(d(t))return F({message:ve("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(zr).slice(0,10);return n.length?en({hint:J("remove assignee... ")+n.join("")})(e):F({message:ve("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>j(ne),[x.COFFEE]:e=>{let{modifier:t}=e,n=le(x.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?F({message:J("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):en({hint:ye({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},za=Object.fromEntries(Object.entries(Om).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var qr=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"];var _m=3,$m=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),Wm=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let r=n.props;typeof r.description=="string"&&t.push(r.description),typeof r.value=="string"&&t.push(r.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},Hm=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=_m&&!$m.has(t)&&!/^\d+$/.test(t)),jm=e=>{let t=new Map;for(let s of Wm(e))for(let i of Hm(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),r=new Set(n),o=qr.filter(s=>!r.has(s));return[...n,...o]},Ka=qr,qa=-1,Ya=()=>{let e=We();if(d(e))return qr;let t=e.value,n=t.eventLog.length;return n!==qa&&(Ka=jm(t),qa=n),Ka};var Xa=e=>Object.values(x).includes(e),Ja=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:u}=za[n].validate(n,r,s),m=n!==x.PEEK&&n!==x.REPLAY,p=o==="command"||o==="modifier"?le(n):m?Ya():[],{mode:v}=f(),I=v===g.COMMAND_LINE?i??"":"",E=[...u,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:I,autoCompletion:t?Ki(e,E):{hint:"",hints:[],remainder:"",overlap:0}}};var Qa=e=>{let t=e.trimStart(),n=Gm(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=zm(e),c=Xa(r)?r:null,u=c!==null,m=r!=="",p=c?le(c)??[]:[],v=c&&p.includes(o)?o:"",I="word";n.length===0||n.length===1&&!s?I="command":(n.length===1&&s||n.length===2&&!s)&&(I="modifier");let E=s?"":i,N=Vm(t,c,v);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:v,target:I,inputToMatch:E,inputString:N}},Vm=(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},Gm=e=>e.trim()?e.trim().split(/\s+/):[],zm=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as Km}from"react";var In=e=>e===Cs||e===":",Cs=" ",he={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:wt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Ss=new Set,Za=()=>{for(let e of Ss)e()},Es=e=>(Ss.add(e),()=>Ss.delete(e)),tt=e=>{let n=e(he),r=Qa(n.value),o=n.cursorPosition===n.value.length;he={...n,commandMeta:Ja(r,o)},Za()},Gn=({message:e,status:t})=>{let n=structuredClone(he);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,he=n,Za(),l(e,null)},Ns=e=>{tt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Rs=e=>{tt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&In(n[o-1]);)o--;for(;o>0&&!In(n[o-1]);)o--}else{for(;o<n.length&&!In(n[o]);)o++;for(;o<n.length&&In(n[o]);)o++}return{...t,cursorPosition:o}})},ed=()=>{tt(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}})},td=()=>{tt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&In(t[r-1]);)r--;for(;r>0&&!In(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Yr=e=>{tt(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},nd=()=>{tt(e=>({...e,commandIsPending:!0}))},_=e=>{tt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},rd=({addToHistory:e=!0})=>{tt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},od=()=>{tt(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}})},sd=()=>{tt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},q=()=>he,id=()=>Km(Es,q,q),ad=()=>{let[e,...t]=he.value.split(Cs);return t.join(Cs).trim()};var h={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 qm(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function Ym(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function Xm(e,t,n){let r=f().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 dd(e,t){let n=q();if(e.sequence==="?"&&t!==g.PALETTE)return h.InitCommandPalette;if(e.sequence===":"&&t!==g.COMMAND_LINE)return h.InitCommandLine;if(t===g.MOVE)switch(e.name){case"m":case"return":return h.ConfirmMove}if(t===g.COMMAND_LINE)return $i(e,n.value);if(t===g.PALETTE)return Wi(e,n.value);let r=qm(e)||Ym(e);if(r)return Jm(r,t);if(e.ctrl&&e.name==="c")return h.Exit;switch(e.name){case"r":return h.EditTitle;case"e":return h.EditDescription;case"n":return h.AddItem;case"m":return h.InitMove;case"d":return h.Delete;case"return":return h.Confirm;case"space":return h.Confirm;case"v":return H().viewMode==="wide"?h.SetViewDense:h.SetViewWide;case"q":case"escape":return h.Exit;default:return null}}function Jm(e,t){let n=t===g.MOVE?{prevItem:h.MovePreviousItem,nextItem:h.MoveNextItem,prevContainer:h.MoveToPreviousContainer,nextContainer:h.MoveToNextContainer}:{prevItem:h.NavPreviousItem,nextItem:h.NavNextItem,prevContainer:h.NavToPreviousContainer,nextContainer:h.NavToNextContainer};return Xm(f().contextNode.childRenderAxis,e,n)}var Xr=e=>{let{context:t}=f().contextNode;if(!t)return L.None;switch(e){case x.EXIT:return L.Exit;case x.EXPORT:return L.Export;case x.COFFEE:return L.Coffee;case x.INIT:return L.Init;case x.DELETE:return L.Delete;case x.EDIT:return L.Edit;case x.COMMENT:return L.Comment;case x.HELP:return L.ViewHelp;case x.RE_OPEN_ISSUE:return L.ReopenIssue;case x.CLOSE_ISSUE:return L.CloseIssue;case x.TAG:return L.TagTicket;case x.UNTAG:return L.UntagTicket;case x.ASSIGN:return L.AssignUserToTicket;case x.UNASSIGN:return L.UnassignUserFromTicket;case x.NEW:return L.NewItem;case x.FILTER:return L.Filter;case x.MOVE:return L.Move;case x.PEEK:return L.Peek;case x.REPLAY:return L.Replay;case x.CONFIG:return L.Config;case x.SYNC:return L.Sync;default:return L.None}},L={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export",Coffee:"coffee"};import{ulid as xe}from"ulid";import Ad from"node:fs";import Lp from"node:path";import kp from"react";import{Box as Mp}from"ink";import ro from"react";import pp from"chalk";import{Box as Ts,Text as fp}from"ink";import rt from"react";import{Text as cd}from"ink";import ld,{useEffect as ud,useState as Qm}from"react";var md={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ce=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=$(),r=md[n]??md.default,[o,s]=Qm(0);if(ud(()=>{s(0)},[r]),ud(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return ld.createElement(cd,null,t);let i=r[o]??r[0]??t;return ld.createElement(cd,{color:y.accent,dimColor:o===1},i)};import{Box as As,Text as Zm}from"ink";import Jr from"react";var nt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),i=Math.max(1,Math.ceil(r)),c=Math.max(1,Math.floor(s/i)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),v=p+c,I=e.slice(p,v),E=e.length>c,N=s,T=E?Math.max(1,Math.floor(c/e.length*N)):N,k=Math.max(0,N-T),O=Math.max(1,e.length-c),V=E?Math.floor(p/O*k):0;return Jr.createElement(As,{flexDirection:"row",height:s,width:"100%"},Jr.createElement(As,{flexDirection:"column",flexGrow:1,height:s},I),Jr.createElement(As,{flexDirection:"column",width:1,height:N},Array.from({length:N}).map((R,A)=>Jr.createElement(Zm,{key:A,color:E&&A>=V&&A<V+T?y.accent:y.secondary},E?"\u2502":" "))))};import{Box as Zr,Text as up}from"ink";import tn from"react";import{Text as ep}from"ink";import tp from"react";var np=e=>e.toLowerCase().trim(),rp=(e,t=pn)=>{let n=np(e);return t[n]?t[n]:On(n)},Mt=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return tp.createElement(ep,{underline:t,color:rp(n.name)},"@"+n.name)};import{Text as op}from"ink";import sp from"react";var bn=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return sp.createElement(op,{underline:t,backgroundColor:ie(n.name),color:y.secondary}," "+n.name+" ")};import{useEffect as ip,useState as ap}from"react";var dp=80,pd=1400,Qr=new Set,zn=null,cp=e=>(Qr.add(e),zn||(zn=setInterval(()=>{for(let t of Qr)t()},dp)),()=>{Qr.delete(e),Qr.size===0&&zn&&(clearInterval(zn),zn=null)}),lp=()=>{let e=Date.now()%pd/pd;return e<.5?e*2:(1-e)*2},Cn=e=>{let[,t]=ap(0);return ip(()=>{if(e)return cp(()=>t(n=>n+1))},[e]),Rr(lp())};var fd=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Cn(r),s=e-14,i=un(Nt(t.title),s),c=jn(t),u=Vn(t);return tn.createElement(Zr,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:r?o:n?y.accent:y.secondary,justifyContent:"space-between"},tn.createElement(Zr,{borderBottom:!0},tn.createElement(Zr,{paddingLeft:1,flexDirection:"column"},tn.createElement(up,{color:y.primary},i))),tn.createElement(Zr,{flexDirection:"row",paddingLeft:1},c.map(m=>tn.createElement(bn,{key:m.id,id:m.id})),u.map(m=>tn.createElement(Mt,{key:m.id,id:m.id}))))};import{Box as nn,Text as Kn}from"ink";import Me from"react";var mp=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,gd=({width:e,ticket:t,isSelected:n,isFlashing:r=!1,index:o,mode:s})=>{let i=Cn(r),c=(t.props.tags??[]).map(R=>b.getTag(R)).filter(R=>!!R),u=(t.props.assignees??[]).map(R=>b.getContributor(R)).filter(R=>!!R),m=1,p=c.length*(1+m),v=u.length*(2+m),I=c.map(R=>Me.createElement(nn,{key:R.id,paddingRight:m},Me.createElement(Kn,{color:ie(R.name)},"\u25A0"))),E=u.map(R=>Me.createElement(nn,{key:R.id,paddingRight:m},Me.createElement(Kn,{color:On(R.name)},"@"+R.name.at(0)))),N=r?i:n?y.accent:s===g.MOVE?y.secondary:y.primary,T=4,k=b.getCommentsByIssue(t.id),O=k.length?String(k.length).length+2+m:0,V=k.length?Me.createElement(nn,{paddingRight:m},Me.createElement(Kn,{color:y.accent},"[",k.length,"]")):null;return Me.createElement(nn,{borderBottom:!0,justifyContent:"space-between"},Me.createElement(nn,null,Me.createElement(nn,{width:T},n?Me.createElement(Ce,{isSelected:n}):Me.createElement(Kn,{color:"gray",dimColor:!0},o+1)),Me.createElement(Kn,{wrap:"truncate",color:N},mp(t.title,e-p-v-O-18))),Me.createElement(nn,null,I,E,V))};var gp=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:m}=$(),p=u[e.id]??[],v=m?new Set(m.flashNodeIds):null,I=v?.has(e.id)??!1,E=Cn(I),N=`${e.title} ${pp.hex(y.secondary2).dim("("+p.length+")")}`,T=3,k=o?1:4,O=r-T-(o?2:1),V=rt.createElement(Ts,{borderStyle:"round",borderColor:y.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},rt.createElement(Ce,{isSelected:t}),rt.createElement(fp,{bold:!0,color:I?E:t?y.accent:y.primary},N," ",e.readonly?"\u{1F512}":"")),R=(A,G)=>{let Re=s&&i===G;if(!w(A))return null;let Ae=v?.has(A.id)??!1;return o?rt.createElement(gd,{key:A.id,index:G,width:n,ticket:A,isSelected:Re,isFlashing:Ae,mode:c}):rt.createElement(fd,{key:A.id,width:n,ticket:A,isSelected:Re,isFlashing:Ae})};return rt.createElement(Ts,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:1,paddingLeft:1,height:r},V,rt.createElement(Ts,{padding:o?1:0},p.length>0&&rt.createElement(nt,{selectedIndex:i,height:O,itemHeight:k},p.map(R)),rt.createElement(Ce,{isSelected:s&&i===-1})))},vd=rt.memo(gp);import{Box as qn,Text as Nd}from"ink";import Pe,{useMemo as no}from"react";import{Box as eo,Text as vp}from"ink";import gt from"react";var yd=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=$(),{title:o}=t,s=t.parentNodeId?b.getNode(t.parentNodeId):void 0,i=s&&w(s)?o===se.ASSIGNEES?s.props.assignees??[]:o===se.TAGS?s.props.tags??[]:[]:[];return gt.createElement(eo,{alignItems:"center",paddingTop:1},gt.createElement(eo,{minWidth:12},gt.createElement(Ce,{isSelected:n}),gt.createElement(vp,{color:n?y.accent:y.secondary2},o,":")),gt.createElement(eo,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let m=r.id===t.id&&u===e;return gt.createElement(eo,{key:`${o}-${c}`,paddingRight:2,minHeight:1},gt.createElement(Ce,{isSelected:m}),o===se.ASSIGNEES?gt.createElement(Mt,{isSelected:m,id:c}):o===se.TAGS?gt.createElement(bn,{isSelected:m,id:c}):null)})))};import{Box as to,Text as ws}from"ink";import vt,{useEffect as yp,useMemo as hd}from"react";var hp="\u2029",xd=(e,t)=>`${e}::inline-line::${t}`,Ms=new Map,Id=e=>{let t=Ms.get(e)??[];Ms.delete(e);for(let n of t)b.deleteNode(n)},xp=(e,t)=>{Id(e);let n=[];t.forEach((r,o)=>{let s=$e(BigInt(o+1));if(!te(s))return;let i=b.createNode(Q.text({id:xd(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));te(i)&&n.push(i.value.id)}),Ms.set(e,n)},Ps=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=$(),u=hd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=hd(()=>u.join("\0"),[u]);yp(()=>(xp(e,u),()=>{Id(e)}),[e,m]);let p=I=>String(I).replace(/\r?\n/g,""),v=u.map((I,E)=>{let N=c.id===e&&i===E;return vt.createElement(to,{key:xd(e,E)},vt.createElement(ws,{color:N?y.primary:y.secondary2,dimColor:!N},`${E+1} `.padStart(5,"\xA0")),vt.createElement(ws,{backgroundColor:N?"gray":void 0},p(I.length?un(I,s-10):hp)))});return vt.createElement(to,{flexDirection:"column",paddingTop:1},vt.createElement(to,null,vt.createElement(Ce,{isSelected:o}),vt.createElement(ws,{color:o?y.accent:y.secondary2},t)),vt.createElement(to,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1},vt.createElement(nt,{scrollByOne:!0,height:r-3,selectedIndex:i,itemHeight:1},v)))};import{Box as Pt,Text as yt}from"ink";import ue,{useEffect as Ip,useMemo as bp,useRef as Cp}from"react";import{decodeTime as Ls}from"ulid";var bd=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},Cd=(e,t,n)=>Q.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});var Sp=e=>Ne(e,"comments"),Ep=e=>b.getCommentsByIssue(e.id).sort((t,n)=>Ls(t.id)-Ls(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),Sd=e=>{for(let t of e)b.deleteNode(t.id)},Np=(e,t)=>{let n=b.getNode(Sp(e.id));if(!n||!Qe(n))return[];let r=t.map((o,s)=>Cd(o,s,n.id)).map(b.createNode).filter(te).map(({value:o})=>o).filter(Bn);return t.length>0&&f().selectedIndex<0&&M.navigate({contextNode:n,selectedIndex:0}),r},Rp=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`};function Ed({ticket:e,width:t,height:n}){let r=bp(()=>Ep(e),[e]),o=Cp([]);Ip(()=>(Sd(o.current),o.current=Np(e,r),()=>{Sd(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=$(),c=Math.max(1,n-4),u=Math.max(20,t-8);return r.length===0?ue.createElement(Pt,{flexDirection:"column",width:t,height:n,padding:1},ue.createElement(yt,{color:y.primary},"No comments yet."),ue.createElement(Pt,{paddingTop:1},ue.createElement(yt,{color:y.primary},"Use"),ue.createElement(yt,{color:y.accent}," :comment "),ue.createElement(yt,{color:y.primary},"to add the first one."))):ue.createElement(Pt,{flexDirection:"column",width:t,height:n},ue.createElement(Pt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},ue.createElement(yt,{color:y.secondary2},"Comments (",r.length,") ")),ue.createElement(nt,{height:c,itemHeight:4,selectedIndex:s},r.map((m,p)=>{let v=p===s;return ue.createElement(Pt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},ue.createElement(Pt,{flexDirection:"row",paddingBottom:1},ue.createElement(yt,{color:y.accent},v?"\u276F ":" "),ue.createElement(Pt,{paddingLeft:1},ue.createElement(yt,{color:y.secondary2},`#${p+1} `),ue.createElement(Mt,{id:m.authorId}),ue.createElement(yt,{color:y.secondary2}," "+wr(Ls(m.id))))),ue.createElement(Pt,{paddingLeft:3,paddingBottom:1},ue.createElement(yt,{color:y.primary},Rp(m.md,u))))})))}var Ap=e=>Ne(e,"description"),Tp=e=>Ne(e,"comments"),wp=e=>Ne(e,"history"),Rd=({ticket:e,height:t})=>{let n=no(()=>bd(e),[e]),{selectedIndex:r,contextNode:o}=$(),s=process.stdout.columns||120,i=no(()=>Ap(e.id),[e.id]),c=no(()=>Tp(e.id),[e.id]),u=no(()=>wp(e.id),[e.id]),m=o.id===e.id,p=o.id===c||o.parentNodeId===c,v=o.id===u||o.parentNodeId===u,I=W(e.id);if(p){let A=t-3;return Pe.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Pe.createElement(Ed,{ticket:e,width:s,height:A}))}if(v){let R=b.getNode(u),A=R&&Qe(R)?R.props.value??"":"",Re=t-3;return Pe.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R?Pe.createElement(Ps,{id:R.id,label:"Event log",text:A,selected:!1,maxWidth:s,height:Re}):null)}let E=I.reduce((R,A)=>Fn(A)||A.id===c||A.id===u?R+1:R,0),N=2,T=3,k=E,O=t-T-k-N,V=(R,A)=>R.id===i?Pe.createElement(Ps,{key:R.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:A,maxWidth:s,height:O}):Fn(R)?Pe.createElement(yd,{key:R.id,parent:R,selected:A,selectedIndex:r}):R.id===c?Pe.createElement(qn,{key:R.id,paddingTop:1},Pe.createElement(Ce,{isSelected:A}),Pe.createElement(Nd,{backgroundColor:y.secondary,color:A?y.accent:y.primary},` Comments (${n}) \u203A\u203A `)):R.id===u?Pe.createElement(qn,{key:R.id,paddingTop:1},Pe.createElement(Ce,{isSelected:A}),Pe.createElement(Nd,{backgroundColor:y.secondary,color:A?y.accent:y.primary}," History \u203A\u203A ")):null;return Pe.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},I.map((R,A)=>V(R,m&&r===A)))};var Pp=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,p=u===P.BOARD||u===P.SWIMLANE,v=u===P.TICKET?t:r.find(k=>k.context===P.TICKET),I=Math.floor(c/3),E=Math.floor(c/Math.max(e.length,1)),N=Math.min(E,I),T=s==="dense";return ro.createElement(Mp,{flexDirection:"row",height:i},p&&e.map((k,O)=>{let V=t.id===k.id,R=V?n:-1,A=t.context===P.BOARD&&n===O;return ro.createElement(vd,{key:k.id,height:i,width:N,swimlane:k,isSelected:A,isDense:T,isFocused:V,listSelectedIndex:R,mode:o})}),m&&v&&ro.createElement(Rd,{height:i,ticket:v}))},oo=ro.memo(Pp);import{render as Dp}from"ink";import{Writable as Fp}from"node:stream";var Yn=e=>String(e).padStart(2,"0"),Bp=e=>{let t=e.getUTCFullYear(),n=Yn(e.getUTCMonth()+1),r=Yn(e.getUTCDate()),o=Yn(e.getUTCHours()),s=Yn(e.getUTCMinutes()),i=Yn(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},Up=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Op=async(e,{width:t,height:n})=>{let r="",o=new Fp({write(i,c,u){let m=_p(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=Dp(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},_p=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Td=async()=>{let{viewMode:e}=H(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=f(),i=r.find(O=>O.context==="BOARD");if(!i)return a("No board found to export");let c=120,u=40,m=await Op(kp.createElement(oo,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(O=>O!==void 0&&Et(O)),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 p=pr(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let v=new Date,I=Bp(v),E=`board_${Up(i.title)}_${I}.md`,N=ui(p.value);Ad.mkdirSync(N,{recursive:!0});let T=Lp.join(N,E),k=`# Board - ${i.title}
44
+ `)}`):(ym(),C({hasProjectDefinition:!0}),l("State booted successfully",null))}var Qt=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),Or=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)}},K=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);var tt=null,_r=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!tt,currentStatus:f().syncStatus?.status,currentMessage:f().syncStatus?.msg}),tt)return logger.debug("[sync] syncAndReloadState joining existing promise"),tt;logger.debug("[sync] syncAndReloadState creating promise"),tt=hm();try{let e=await tt;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:f().syncStatus?.status,statusMessageAfterResolve:f().syncStatus?.msg}),d(e)&&f().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),C({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),tt||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:f().syncStatus?.status,statusMessageBeforeClear:f().syncStatus?.msg}),tt=null}},hm=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:f().mode,syncStatus:f().syncStatus});let e=Ma();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:f().mode,message:e.message,syncStatus:f().syncStatus}),e;if(tt)return tt;logger.debug("[sync] syncAndReloadState:start");let t=K("resolveActorId",Z());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:d(t)?t.message:"Missing actor id"}),a("Unable to resolve event log path");C({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:f().syncStatus});let n=Yt(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=K("syncEpiqWithRemote",await $r({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!d(r),message:(d(r),r.message)}),d(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),C({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:f().syncStatus}),He(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let s=K("loadMergedEvents",ft(o));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(s),message:(d(s),s.message),count:d(s)?void 0:s.value.length}),d(s))return C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:f().syncStatus}),a(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let i=Ma();if(i)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:f().mode,message:i.message,syncStatus:f().syncStatus}),i;let c=Ra(),u=f().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:c,selectedNodeId:f().selectedNode?.id,contextNodeId:f().contextNode?.id,selectedNodeIsVirtual:f().selectedNode?.isVirtual,contextNodeIsVirtual:f().contextNode?.isVirtual}),!f().selectedNode?.isVirtual&&!f().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let p=K("bootStateFromEventLog",Jt(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(p),message:(d(p),p.message)}),d(p))return C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:f().syncStatus}),a(`Unable to boot synced state. ${p.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:f().selectedNode?.isVirtual,contextNodeIsVirtual:f().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),C({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=K("restoreNavigationAnchor",Ta(c));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(m),message:d(m)?m.message:"Navigation restored",selectedNodeId:f().selectedNode?.id,contextNodeId:f().contextNode?.id}),d(m)?(C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:f().syncStatus}),m):(C({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:f().syncStatus}),l("Synced",!0))},Ma=()=>f().mode===g.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:f().mode,syncStatus:f().syncStatus}),C({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var hn=3e3,Pa=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<hn?null:t},La=0,ys,hs=!1,jn=!1,xs=()=>{if(hs)return!0;let e=We();return d(e)?!1:e.value.syncStatus.status==="syncing"},xm=()=>{let e=H().autoSyncIntervalMs??1e4,t=Date.now()-La;return Math.max(0,e-t)},ka=()=>{ys||(ys=setTimeout(async()=>{if(ys=void 0,!!xn()){if(xs()){jn=!0;return}jn=!1,await Im()}},xm()))},Im=async()=>{if(f().readOnly||f().timeMode==="peek"||f().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!xn())return a("Cannot auto-sync before state is initialized");if(xs())return jn=!0,a("Sync already in progress");hs=!0,La=Date.now(),C({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await _r()}finally{hs=!1,jn&&ka()}},Wr=()=>{xn()&&(jn=!0,!xs()&&ka())};var wt=()=>{let e=H(),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}},Da=()=>{let e=Ke(process.cwd());if(d(e))return!1;let t=Et(e.value);return te(t)},Fa=e=>e===!0?"on":e===!1?"off":null,Ba=e=>e==="on"?!0:e==="off"?!1:null;var bm=e=>e.props.tags??[],Cm=e=>e.props.assignees??[],Vn=e=>bm(e).map(t=>b.getTag(t)).filter(t=>!!t),Gn=e=>Cm(e).map(t=>b.getContributor(t)).filter(t=>!!t),Hr=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!w(n)?a("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Vn(n))},jr=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!w(n)?a("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",Gn(n))};var x={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""};var Em=/^(\d+)(h|d|w|mo|y)$/,Sm=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Nm=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let s=new Date(e,t-1,n,r,o);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===r&&s.getMinutes()===o},Rm=(e,t=new Date)=>{let n=e.match(Em);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(o){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},Am=e=>{let t=e.match(Sm);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,v=i?Number(i):0;return Nm({year:c,month:u,day:m,hour:p,minute:v})?new Date(c,u-1,m,p,v):null},Zt=e=>{let t=e.trim().toLowerCase();return Rm(t)??Am(t)};var Ua=/^(\d+)(s|m)?$/,Vr=e=>{let t=e.trim().toLowerCase().match(Ua);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Gr=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Ua.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Oa=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Tm=[{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}],Is=(e=Tm)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let s=r;s<=o;s++)t.push(`${s}${n}`);return t};var wm=["BOARD","TICKET","SWIMLANE","COMMENT"],ae={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},we={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Mm=[ae.EDITOR,ae.VIEW,ae.USERNAME,ae.AUTOSYNC,ae.SYNC_DEBOUNCE_MS,ae.LOG_LEVEL],Pm=(e=f().selectedNode?.context)=>{switch(e){case"TICKET":return[we.TITLE,we.DESCRIPTION];case"BOARD":case"SWIMLANE":return[we.TITLE];case"COMMENT":return[we.COMMENT];default:return[]}},Cs=[String(hn),"5000","15000","30000","60000"],Wa=["10s","20s","30s","45s"],en=[x.COFFEE,x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG],zr=[x.NEW,x.EDIT,x.DELETE,x.MOVE],bs=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT,x.COMMENT],_a=[x.FILTER,x.PEEK,x.REPLAY],Lm={WORKSPACE:[...en,...zr],BOARD:[..._a,...en,...zr],SWIMLANE:[..._a,...en,...zr],TICKET:[...en,...zr,...bs],FIELD:[...en,...bs],FIELD_LIST:[...en,...bs],TEXT:[...en],COMMENT:[x.EDIT,x.DELETE]},km=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Ha=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&w(n)),$a=e=>e.parentNodeId===ce,Dm=({selectedNode:e,breadCrumb:t})=>{let n=Pm(e?.context);return Ha({breadCrumb:t,selectedNode:e})?n.includes(we.DESCRIPTION)?n:[...n,we.DESCRIPTION]:n},Fm=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=wt();if(!r)return[x.HELP,x.CONFIG];if(!Da())return[x.HELP,x.INIT];if(t)return[x.HELP,x.PEEK,x.REPLAY,x.EXPORT,x.CONFIG];let o=e?.context,s=o&&wm.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?Lm[u]:[]))],c=Ha({breadCrumb:n,selectedNode:e});return i.filter(u=>u===x.MOVE?!1:u===x.EDIT?s||!!c:u===x.DELETE?s:u===x.UNTAG?!!(c&&Vn(c).length>0):u===x.UNASSIGN?!!(c&&Gn(c).length>0):u===x.RE_OPEN_ISSUE?!!(c&&$a(c)):u===x.CLOSE_ISSUE?!!(c&&!$a(c)):!0)},le=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=f())=>{let s=t.context??"WORKSPACE";return{[x.NONE]:Fm({breadCrumb:o,readOnly:r,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.HELP]:[],[x.PEEK]:[...Is(),"now","prev","next"],[x.REPLAY]:[...Is()],[x.EDIT]:Dm({selectedNode:n,breadCrumb:o}),[x.COMMENT]:[],[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","ref","clear"],[x.TAG]:[...new Set([...Object.keys(fn),...b.getExistingTags()])],[x.UNTAG]:[...Hr()?.value?.map(({name:c})=>c)??[]],[x.UNASSIGN]:[...jr()?.value?.map(({name:c})=>c)??[]],[x.ASSIGN]:b.getExistingAssignees(),[x.NEW]:km(s),[x.CONFIG]:[...Mm],[x.COFFEE]:["1","3","5","20","custom"]}[e]??[]};import Ka from"chalk";var ja=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var be=(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 Va from"chalk";var J=e=>Va.dim(e),ve=e=>Va.hex(y.primary)(e),ye=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(v=>v.startsWith(i))].sort((v,I)=>Tr(v)-Tr(I)).slice(0,r).map(v=>wr(v)).join(" ");return p?`${J(e)}${p}${J(n)}`:""};var Mt={None:"none",Invalid:"invalid",Valid:"valid"};var In=140,Bm=["BOARD","TICKET","SWIMLANE"],Ga=()=>{let e=f().selectedNode;if(!e?.context)return F({message:J("Missing target context")});if(Bm.includes(e.context))return j();if(e.parentNodeId){let t=f().nodes[e.parentNodeId];if(t?.id===Ne(t?.parentNodeId??"","comments"))return j()}return F({message:J("Command not available in this context")})},ne="<ENTER> to confirm",j=(e="",t=[])=>({message:J(e),validity:Mt.Valid,completionWordList:t}),F=({message:e,completionWordList:t=[]})=>({validity:Mt.Invalid,message:e,completionWordList:t}),qr=e=>e.length===0,za=(e,t)=>{let n=be(f().breadCrumb,"BOARD");if(d(n))return F({message:ve("Command is not applicable in this context")});let r=Lr(n.value.id);return d(r)?F({message:ve(`Unable to ${t}: board id is not a valid ULID`)}):Oa({date:e,horizonDate:r.value})?null:F({message:ve(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},Kr=e=>` ${Ka.hex("#000").bgHex(ie(e))(` ${e} `)} `,Es=({modifier:e})=>{let t="confirm";return e===t?j(ne):F({message:qr(e)?J("if you are certain, enter ")+wr(t):"",completionWordList:[t]})},Um=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?F({message:J(n)}):j():F({message:qr(r)?t:"",completionWordList:[...e]}),tn=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>qr(n)&&qr(r)?F({message:e,completionWordList:[]}):j(t??ne),Om=({modifier:e,inputString:t})=>{let n=le(x.CONFIG);if(!n.includes(e))return F({message:ye({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ae.EDITOR:{let r=[...ja];return t.trim()?r.includes(t.trim())?j(ne):F({message:ye({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):F({message:ye({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ae.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?j(ne):F({message:ye({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ae.USERNAME:return t.trim()?j(ne):F({message:ve("Enter a user name. Saved in ")+Ka.bgBlack("~/.epiq-global/config.json")});case ae.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?j(ne):F({message:ye({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ae.AUTOSYNC:{let r=["on","off"],o=H().autoSync;if(!r.includes(t.trim())){let s=Fa(o);return F({message:ye({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return j(ne)}case ae.SYNC_DEBOUNCE_MS:{let r=H().autoSyncIntervalMs,o=Pa(t);if(!t.trim()||o===null||o<hn){let s=ye({prefix:" examples: ",wordList:Cs,minLengthForHints:0,inputString:t});return F({message:ve(`provide duration above ${hn}ms. current duration: ${r}ms.`)+s,completionWordList:Cs})}return j(ne)}default:return F({message:ve("Unknown config option"),completionWordList:n})}},_m=({modifier:e,inputString:t})=>{let n=le(x.EDIT);if(!n.length)return F({message:ve("Command not available in this context")});if(!n.includes(e)){let r=ye({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return F({message:r||ve("Unknown edit option"),completionWordList:n})}switch(e){case we.COMMENT:return t.trim()?j(ne):F({message:J("write a comment...")});case we.TITLE:return j(ne);case we.DESCRIPTION:{let{preferredEditor:r}=H();return r?j(J("<ENTER> to edit in ")+r):F({message:"No editor selected"})}default:return F({message:ve("Unknown edit option"),completionWordList:n})}},$m={[x.EXPORT]:()=>j(ne+J(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return j(ne);let n={message:J("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Zt(r);if(!r||!o)return F(n);let s=za(o,"peek");return s||j(ne)},[x.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Gr(e.modifier,e.inputString),r={message:J("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Zt(t);if(!t||!o)return F(r);let s=za(o,"replay");return s||(n&&Vr(n)===null?F({message:ve("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):j("<ENTER> to replay board history",n?Wa:[]))},[x.EXIT]:()=>j(ne+J(" and exit the application")),[x.INIT]:()=>j(ne),[x.PALETTE]:()=>j(ne),[x.FILTER]:e=>{if(e.modifier==="clear")return j(ne);let t=s=>le(x.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return F({message:ye({wordList:le(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:le(x.FILTER)});let n=Object.values(f().tags).map(s=>s.name),r=Object.values(f().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?F({message:ye({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):j():F({message:ye({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[x.NONE]:e=>{let t=le(x.NONE);return F({message:ye({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>Um({list:le(x.NEW),hint:ye({wordList:le(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>j(ne),[x.EDIT]:_m,[x.COMMENT]:e=>{let t=tn({hint:J(`write a comment (max ${In} char)...`),onOk:J(`(${e.inputString.length}/${In})`)})(e);return t.validity===Mt.Invalid?t:e.inputString.length>In?j(ve("max input exceeded")):t},[x.CONFIG]:Om,[x.DELETE]:e=>{let t=Ga();return t.validity==="invalid"?t:Es(e)},[x.CLOSE_ISSUE]:e=>Es(e),[x.RE_OPEN_ISSUE]:e=>Es(e),[x.MOVE]:e=>{let t=Ga();return t.validity==="invalid"?t:tn({hint:ye({prefix:"hey hacker! These commands are blocked for you... ",wordList:le(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=b.getExistingTags().slice(0,10).map(Kr).join("");return tn({hint:n.length?J("create tag or reuse:")+n+J(""):J("create tag ...")})(e)},[x.UNTAG]:e=>{let t=Hr();if(d(t))return F({message:ve("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Kr).slice(0,10);return n.length?tn({hint:J(" ... ")+n.join("")})(e):F({message:ve("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=b.getExistingAssignees().map(Kr).slice(0,10);return tn({hint:J("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=jr();if(d(t))return F({message:ve("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Kr).slice(0,10);return n.length?tn({hint:J("remove assignee... ")+n.join("")})(e):F({message:ve("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>j(ne),[x.COFFEE]:e=>{let{modifier:t}=e,n=le(x.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?F({message:J("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):tn({hint:ye({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},qa=Object.fromEntries(Object.entries($m).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Yr=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"];var Wm=3,Hm=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),jm=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let r=n.props;typeof r.description=="string"&&t.push(r.description),typeof r.value=="string"&&t.push(r.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},Vm=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=Wm&&!Hm.has(t)&&!/^\d+$/.test(t)),Gm=e=>{let t=new Map;for(let s of jm(e))for(let i of Vm(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),r=new Set(n),o=Yr.filter(s=>!r.has(s));return[...n,...o]},Ya=Yr,Xa=-1,Ja=()=>{let e=We();if(d(e))return Yr;let t=e.value,n=t.eventLog.length;return n!==Xa&&(Ya=Gm(t),Xa=n),Ya};var Qa=e=>Object.values(x).includes(e),Za=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:u}=qa[n].validate(n,r,s),m=n!==x.PEEK&&n!==x.REPLAY,p=o==="command"||o==="modifier"?le(n):m?Ja():[],{mode:v}=f(),I=v===g.COMMAND_LINE?i??"":"",S=[...u,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:I,autoCompletion:t?qi(e,S):{hint:"",hints:[],remainder:"",overlap:0}}};var ed=e=>{let t=e.trimStart(),n=Km(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=qm(e),c=Qa(r)?r:null,u=c!==null,m=r!=="",p=c?le(c)??[]:[],v=c&&p.includes(o)?o:"",I="word";n.length===0||n.length===1&&!s?I="command":(n.length===1&&s||n.length===2&&!s)&&(I="modifier");let S=s?"":i,N=zm(t,c,v);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:v,target:I,inputToMatch:S,inputString:N}},zm=(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},Km=e=>e.trim()?e.trim().split(/\s+/):[],qm=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as Ym}from"react";var bn=e=>e===Ss||e===":",Ss=" ",he={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Mt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Ns=new Set,td=()=>{for(let e of Ns)e()},Rs=e=>(Ns.add(e),()=>Ns.delete(e)),nt=e=>{let n=e(he),r=ed(n.value),o=n.cursorPosition===n.value.length;he={...n,commandMeta:Za(r,o)},td()},zn=({message:e,status:t})=>{let n=structuredClone(he);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,he=n,td(),l(e,null)},As=e=>{nt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Ts=e=>{nt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&bn(n[o-1]);)o--;for(;o>0&&!bn(n[o-1]);)o--}else{for(;o<n.length&&!bn(n[o]);)o++;for(;o<n.length&&bn(n[o]);)o++}return{...t,cursorPosition:o}})},nd=()=>{nt(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}})},rd=()=>{nt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&bn(t[r-1]);)r--;for(;r>0&&!bn(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Xr=e=>{nt(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},od=()=>{nt(e=>({...e,commandIsPending:!0}))},_=e=>{nt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},sd=({addToHistory:e=!0})=>{nt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},id=()=>{nt(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}})},ad=()=>{nt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},q=()=>he,dd=()=>Ym(Rs,q,q),cd=()=>{let[e,...t]=he.value.split(Ss);return t.join(Ss).trim()};var h={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 Xm(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function Jm(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function Qm(e,t,n){let r=f().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 ld(e,t){let n=q();if(e.sequence==="?"&&t!==g.PALETTE)return h.InitCommandPalette;if(e.sequence===":"&&t!==g.COMMAND_LINE)return h.InitCommandLine;if(t===g.MOVE)switch(e.name){case"m":case"return":return h.ConfirmMove}if(t===g.COMMAND_LINE)return Wi(e,n.value);if(t===g.PALETTE)return Hi(e,n.value);let r=Xm(e)||Jm(e);if(r)return Zm(r,t);if(e.ctrl&&e.name==="c")return h.Exit;switch(e.name){case"r":return h.EditTitle;case"e":return h.EditDescription;case"n":return h.AddItem;case"m":return h.InitMove;case"d":return h.Delete;case"return":return h.Confirm;case"space":return h.Confirm;case"v":return H().viewMode==="wide"?h.SetViewDense:h.SetViewWide;case"q":case"escape":return h.Exit;default:return null}}function Zm(e,t){let n=t===g.MOVE?{prevItem:h.MovePreviousItem,nextItem:h.MoveNextItem,prevContainer:h.MoveToPreviousContainer,nextContainer:h.MoveToNextContainer}:{prevItem:h.NavPreviousItem,nextItem:h.NavNextItem,prevContainer:h.NavToPreviousContainer,nextContainer:h.NavToNextContainer};return Qm(f().contextNode.childRenderAxis,e,n)}var Jr=e=>{let{context:t}=f().contextNode;if(!t)return L.None;switch(e){case x.EXIT:return L.Exit;case x.EXPORT:return L.Export;case x.COFFEE:return L.Coffee;case x.INIT:return L.Init;case x.DELETE:return L.Delete;case x.EDIT:return L.Edit;case x.COMMENT:return L.Comment;case x.HELP:return L.ViewHelp;case x.RE_OPEN_ISSUE:return L.ReopenIssue;case x.CLOSE_ISSUE:return L.CloseIssue;case x.TAG:return L.TagTicket;case x.UNTAG:return L.UntagTicket;case x.ASSIGN:return L.AssignUserToTicket;case x.UNASSIGN:return L.UnassignUserFromTicket;case x.NEW:return L.NewItem;case x.FILTER:return L.Filter;case x.MOVE:return L.Move;case x.PEEK:return L.Peek;case x.REPLAY:return L.Replay;case x.CONFIG:return L.Config;case x.SYNC:return L.Sync;default:return L.None}},L={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export",Coffee:"coffee"};import{ulid as xe}from"ulid";import wd from"node:fs";import Dp from"node:path";import Fp from"react";import{Box as Lp}from"ink";import oo from"react";import gp from"chalk";import{Box as Ms,Text as vp}from"ink";import ot from"react";import{Text as ud}from"ink";import md,{useEffect as pd,useState as ep}from"react";var fd={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ce=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=$(),r=fd[n]??fd.default,[o,s]=ep(0);if(pd(()=>{s(0)},[r]),pd(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return md.createElement(ud,null,t);let i=r[o]??r[0]??t;return md.createElement(ud,{color:y.accent,dimColor:o===1},i)};import{Box as ws,Text as tp}from"ink";import Qr from"react";var rt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),i=Math.max(1,Math.ceil(r)),c=Math.max(1,Math.floor(s/i)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),v=p+c,I=e.slice(p,v),S=e.length>c,N=s,T=S?Math.max(1,Math.floor(c/e.length*N)):N,k=Math.max(0,N-T),O=Math.max(1,e.length-c),V=S?Math.floor(p/O*k):0;return Qr.createElement(ws,{flexDirection:"row",height:s,width:"100%"},Qr.createElement(ws,{flexDirection:"column",flexGrow:1,height:s},I),Qr.createElement(ws,{flexDirection:"column",width:1,height:N},Array.from({length:N}).map((R,A)=>Qr.createElement(tp,{key:A,color:S&&A>=V&&A<V+T?y.accent:y.secondary},S?"\u2502":" "))))};import{Box as eo,Text as pp}from"ink";import nn from"react";import{Text as np}from"ink";import rp from"react";var op=e=>e.toLowerCase().trim(),sp=(e,t=fn)=>{let n=op(e);return t[n]?t[n]:_n(n)},Pt=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return rp.createElement(np,{underline:t,color:sp(n.name)},"@"+n.name)};import{Text as ip}from"ink";import ap from"react";var Cn=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return ap.createElement(ip,{underline:t,backgroundColor:ie(n.name),color:y.secondary}," "+n.name+" ")};import{useEffect as dp,useState as cp}from"react";var lp=80,gd=1400,Zr=new Set,Kn=null,up=e=>(Zr.add(e),Kn||(Kn=setInterval(()=>{for(let t of Zr)t()},lp)),()=>{Zr.delete(e),Zr.size===0&&Kn&&(clearInterval(Kn),Kn=null)}),mp=()=>{let e=Date.now()%gd/gd;return e<.5?e*2:(1-e)*2},En=e=>{let[,t]=cp(0);return dp(()=>{if(e)return up(()=>t(n=>n+1))},[e]),Ar(mp())};var vd=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=En(r),s=e-14,i=mn(Rt(t.title),s),c=Vn(t),u=Gn(t);return nn.createElement(eo,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:r?o:n?y.accent:y.secondary,justifyContent:"space-between"},nn.createElement(eo,{borderBottom:!0},nn.createElement(eo,{paddingLeft:1,flexDirection:"column"},nn.createElement(pp,{color:y.primary},i))),nn.createElement(eo,{flexDirection:"row",paddingLeft:1},c.map(m=>nn.createElement(Cn,{key:m.id,id:m.id})),u.map(m=>nn.createElement(Pt,{key:m.id,id:m.id}))))};import{Box as rn,Text as qn}from"ink";import Me from"react";var fp=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,yd=({width:e,ticket:t,isSelected:n,isFlashing:r=!1,index:o,mode:s})=>{let i=En(r),c=(t.props.tags??[]).map(R=>b.getTag(R)).filter(R=>!!R),u=(t.props.assignees??[]).map(R=>b.getContributor(R)).filter(R=>!!R),m=1,p=c.length*(1+m),v=u.length*(2+m),I=c.map(R=>Me.createElement(rn,{key:R.id,paddingRight:m},Me.createElement(qn,{color:ie(R.name)},"\u25A0"))),S=u.map(R=>Me.createElement(rn,{key:R.id,paddingRight:m},Me.createElement(qn,{color:_n(R.name)},"@"+R.name.at(0)))),N=r?i:n?y.accent:s===g.MOVE?y.secondary:y.primary,T=4,k=b.getCommentsByIssue(t.id),O=k.length?String(k.length).length+2+m:0,V=k.length?Me.createElement(rn,{paddingRight:m},Me.createElement(qn,{color:y.accent},"[",k.length,"]")):null;return Me.createElement(rn,{borderBottom:!0,justifyContent:"space-between"},Me.createElement(rn,null,Me.createElement(rn,{width:T},n?Me.createElement(Ce,{isSelected:n}):Me.createElement(qn,{color:"gray",dimColor:!0},o+1)),Me.createElement(qn,{wrap:"truncate",color:N},fp(t.title,e-p-v-O-18))),Me.createElement(rn,null,I,S,V))};var yp=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:m}=$(),p=u[e.id]??[],v=m?new Set(m.flashNodeIds):null,I=v?.has(e.id)??!1,S=En(I),N=`${e.title} ${gp.hex(y.secondary2).dim("("+p.length+")")}`,T=3,k=o?1:4,O=r-T-(o?2:1),V=ot.createElement(Ms,{borderStyle:"round",borderColor:y.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},ot.createElement(Ce,{isSelected:t}),ot.createElement(vp,{bold:!0,color:I?S:t?y.accent:y.primary},N," ",e.readonly?"\u{1F512}":"")),R=(A,G)=>{let Re=s&&i===G;if(!w(A))return null;let Ae=v?.has(A.id)??!1;return o?ot.createElement(yd,{key:A.id,index:G,width:n,ticket:A,isSelected:Re,isFlashing:Ae,mode:c}):ot.createElement(vd,{key:A.id,width:n,ticket:A,isSelected:Re,isFlashing:Ae})};return ot.createElement(Ms,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:1,paddingLeft:1,height:r},V,ot.createElement(Ms,{padding:o?1:0},p.length>0&&ot.createElement(rt,{selectedIndex:i,height:O,itemHeight:k},p.map(R)),ot.createElement(Ce,{isSelected:s&&i===-1})))},hd=ot.memo(yp);import{Box as Yn,Text as Ad}from"ink";import Pe,{useMemo as ro}from"react";var xd=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},Id=(e,t,n)=>Q.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});import{Box as Lt,Text as vt}from"ink";import ue,{useEffect as hp,useMemo as xp,useRef as Ip}from"react";import{decodeTime as Ps}from"ulid";var bp=e=>Ne(e,"comments"),Cp=e=>b.getCommentsByIssue(e.id).sort((t,n)=>Ps(t.id)-Ps(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),bd=e=>{for(let t of e)b.deleteNode(t.id)},Ep=(e,t)=>{let n=b.getNode(bp(e.id));if(!n||!Qe(n))return[];let r=t.map((o,s)=>Id(o,s,n.id)).map(b.createNode).filter(te).map(({value:o})=>o).filter(Un);return t.length>0&&f().selectedIndex<0&&M.navigate({contextNode:n,selectedIndex:0}),r},Sp=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`};function Cd({ticket:e,width:t,height:n}){let r=xp(()=>Cp(e),[e]),o=Ip([]);hp(()=>(bd(o.current),o.current=Ep(e,r),()=>{bd(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=$(),c=Math.max(1,n-4),u=Math.max(20,t-8);return r.length===0?ue.createElement(Lt,{flexDirection:"column",width:t,height:n,padding:1},ue.createElement(vt,{color:y.primary},"No comments yet."),ue.createElement(Lt,{paddingTop:1},ue.createElement(vt,{color:y.primary},"Use"),ue.createElement(vt,{color:y.accent}," :comment "),ue.createElement(vt,{color:y.primary},"to add the first one."))):ue.createElement(Lt,{flexDirection:"column",width:t,height:n},ue.createElement(Lt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},ue.createElement(vt,{color:y.secondary2},"Comments (",r.length,") ")),ue.createElement(rt,{height:c,itemHeight:4,selectedIndex:s},r.map((m,p)=>{let v=p===s;return ue.createElement(Lt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},ue.createElement(Lt,{flexDirection:"row",paddingBottom:1},ue.createElement(vt,{color:y.accent},v?"\u276F ":" "),ue.createElement(Lt,{paddingLeft:1},ue.createElement(vt,{color:y.secondary2},`#${p+1} `),ue.createElement(Pt,{id:m.authorId}),ue.createElement(vt,{color:y.secondary2}," "+Mr(Ps(m.id))))),ue.createElement(Lt,{paddingLeft:3,paddingBottom:1},ue.createElement(vt,{color:y.primary},Sp(m.md,u))))})))}import{Box as to,Text as Np}from"ink";import yt from"react";var Ed=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=$(),{title:o}=t,s=t.parentNodeId?b.getNode(t.parentNodeId):void 0,i=s&&w(s)?o===se.ASSIGNEES?s.props.assignees??[]:o===se.TAGS?s.props.tags??[]:[]:[];return yt.createElement(to,{alignItems:"center",paddingTop:1},yt.createElement(to,{minWidth:12},yt.createElement(Ce,{isSelected:n}),yt.createElement(Np,{color:n?y.accent:y.secondary2},o,":")),yt.createElement(to,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let m=r.id===t.id&&u===e;return yt.createElement(to,{key:`${o}-${c}`,paddingRight:2,minHeight:1},yt.createElement(Ce,{isSelected:m}),o===se.ASSIGNEES?yt.createElement(Pt,{isSelected:m,id:c}):o===se.TAGS?yt.createElement(Cn,{isSelected:m,id:c}):null)})))};import{Box as no,Text as Ls}from"ink";import ht,{useEffect as Rp,useMemo as Sd}from"react";var Ap="\u2029",Nd=(e,t)=>`${e}::inline-line::${t}`,ks=new Map,Rd=e=>{let t=ks.get(e)??[];ks.delete(e);for(let n of t)b.deleteNode(n)},Tp=(e,t)=>{Rd(e);let n=[];t.forEach((r,o)=>{let s=$e(BigInt(o+1));if(!te(s))return;let i=b.createNode(Q.text({id:Nd(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));te(i)&&n.push(i.value.id)}),ks.set(e,n)},Ds=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=$(),u=Sd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Sd(()=>u.join("\0"),[u]);Rp(()=>(Tp(e,u),()=>{Rd(e)}),[e,m]);let p=I=>String(I).replace(/\r?\n/g,""),v=u.map((I,S)=>{let N=c.id===e&&i===S;return ht.createElement(no,{key:Nd(e,S)},ht.createElement(Ls,{color:N?y.primary:y.secondary2,dimColor:!N},`${S+1} `.padStart(5,"\xA0")),ht.createElement(Ls,{backgroundColor:N?"gray":void 0},p(I.length?mn(I,s-10):Ap)))});return ht.createElement(no,{flexDirection:"column",paddingTop:1},ht.createElement(no,null,ht.createElement(Ce,{isSelected:o}),ht.createElement(Ls,{color:o?y.accent:y.secondary2},t)),ht.createElement(no,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1},ht.createElement(rt,{scrollByOne:!0,height:r-3,selectedIndex:i,itemHeight:1},v)))};var wp=e=>Ne(e,"description"),Mp=e=>Ne(e,"comments"),Pp=e=>Ne(e,"history"),Td=({ticket:e,height:t})=>{let n=ro(()=>xd(e),[e]),{selectedIndex:r,contextNode:o}=$(),s=process.stdout.columns||120,i=ro(()=>wp(e.id),[e.id]),c=ro(()=>Mp(e.id),[e.id]),u=ro(()=>Pp(e.id),[e.id]),m=o.id===e.id,p=o.id===c||o.parentNodeId===c,v=o.id===u||o.parentNodeId===u,I=W(e.id);if(p){let A=t-3;return Pe.createElement(Yn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Pe.createElement(Cd,{ticket:e,width:s,height:A}))}if(v){let R=b.getNode(u),A=R&&Qe(R)?R.props.value??"":"",Re=t-3;return Pe.createElement(Yn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R?Pe.createElement(Ds,{id:R.id,label:"Event log",text:A,selected:!1,maxWidth:s,height:Re}):null)}let S=I.reduce((R,A)=>Bn(A)||A.id===c||A.id===u?R+1:R,0),N=2,T=3,k=S,O=t-T-k-N,V=(R,A)=>R.id===i?Pe.createElement(Ds,{key:R.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:A,maxWidth:s,height:O}):Bn(R)?Pe.createElement(Ed,{key:R.id,parent:R,selected:A,selectedIndex:r}):R.id===c?Pe.createElement(Yn,{key:R.id,paddingTop:1},Pe.createElement(Ce,{isSelected:A}),Pe.createElement(Ad,{backgroundColor:y.secondary,color:A?y.accent:y.primary},` Comments (${n}) \u203A\u203A `)):R.id===u?Pe.createElement(Yn,{key:R.id,paddingTop:1},Pe.createElement(Ce,{isSelected:A}),Pe.createElement(Ad,{backgroundColor:y.secondary,color:A?y.accent:y.primary}," History \u203A\u203A ")):null;return Pe.createElement(Yn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},I.map((R,A)=>V(R,m&&r===A)))};var kp=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,p=u===P.BOARD||u===P.SWIMLANE,v=u===P.TICKET?t:r.find(k=>k.context===P.TICKET),I=Math.floor(c/3),S=Math.floor(c/Math.max(e.length,1)),N=Math.min(S,I),T=s==="dense";return oo.createElement(Lp,{flexDirection:"row",height:i},p&&e.map((k,O)=>{let V=t.id===k.id,R=V?n:-1,A=t.context===P.BOARD&&n===O;return oo.createElement(hd,{key:k.id,height:i,width:N,swimlane:k,isSelected:A,isDense:T,isFocused:V,listSelectedIndex:R,mode:o})}),m&&v&&oo.createElement(Td,{height:i,ticket:v}))},so=oo.memo(kp);import{render as Bp}from"ink";import{Writable as Up}from"node:stream";var Xn=e=>String(e).padStart(2,"0"),Op=e=>{let t=e.getUTCFullYear(),n=Xn(e.getUTCMonth()+1),r=Xn(e.getUTCDate()),o=Xn(e.getUTCHours()),s=Xn(e.getUTCMinutes()),i=Xn(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},_p=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",$p=async(e,{width:t,height:n})=>{let r="",o=new Up({write(i,c,u){let m=Wp(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=Bp(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},Wp=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Md=async()=>{let{viewMode:e}=H(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=f(),i=r.find(O=>O.context==="BOARD");if(!i)return a("No board found to export");let c=120,u=40,m=await $p(Fp.createElement(so,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(O=>O!==void 0&&Nt(O)),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 p=fr(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let v=new Date,I=Op(v),S=`board_${_p(i.title)}_${I}.md`,N=pi(p.value);wd.mkdirSync(N,{recursive:!0});let T=Dp.join(N,S),k=`# Board - ${i.title}
45
45
  Date: ${v.toISOString()}
46
46
 
47
47
  \`\`\`text
48
48
  ${m}
49
49
  \`\`\`
50
- `;return Ad.writeFileSync(T,k,"utf8"),l("Exported board layout",T)};import Kp from"node:os";import Ld from"node:path";import{z as Lt}from"zod";import{accessSync as $p,copyFileSync as Wp,existsSync as so,mkdirSync as wd,readdirSync as Md,readFileSync as Hp,renameSync as jp,rmSync as Vp,statSync as Pd,unlinkSync as Gp,writeFileSync as zp}from"node:fs";import Sn from"node:path";var ks=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Le={writeToFile:(e,t)=>{try{let n=Sn.dirname(e);so(n)||wd(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);zp(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Hp(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Le.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 so(e)&&Pd(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await $p(e),!0}catch{return!1}},mkDir:e=>wd(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Sn.parse(t);for(;;){let r=Sn.join(t,e);try{if(so(r)&&Pd(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Sn.dirname(t)}return null},readFirstJSON(e){try{if(!Le.dirExists(e))return null;let t=Md(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Sn.join(e,t);return Le.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Le.dirExists(e)?Md(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Gp(e)}catch(t){(!ks(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Vp(e,{recursive:!0,force:!0})}catch(t){(!ks(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Sn.dirname(t)),!n?.overwrite&&so(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{jp(e,t)}catch(r){if(ks(r)&&r.code==="EXDEV"){Wp(e,t),this.rmFile(e);return}throw r}}};var qp={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},kd=Lt.object({logLevel:Lt.enum(["info","error","debug"]),preferredEditor:Lt.string().optional(),userName:Lt.string().optional(),userId:Lt.string().optional(),autoSync:Lt.boolean().nullable().optional(),autoSyncDebounceMs:Lt.number().optional(),viewMode:Lt.enum(["dense","wide"]).optional()}).partial(),Yp="config.json",Dd=()=>Ld.join(Kp.homedir(),Ue),Ds=()=>Ld.join(Dd(),Yp),Fs=()=>{try{return Le.mkDir(Dd()),l(`Ensured ~/${Ue} exists`,null)}catch{return a(`Unable to create ~/${Ue}`)}},Xp=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${Ue}/config.json JSON`)}let n=kd.safeParse(t??{});return n.success?l("Parsed config",n.data):a(`Invalid ~/${Ue}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Xn=()=>{let e=Fs();if(d(e))return a(e.message);let t=Ds(),n=Le.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Xp(n)},Fd=e=>{let t=Fs();if(d(t))return a(t.message);let n=kd.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Ds();try{return Le.writeToFile(r,JSON.stringify(n.data,null,2)+`
51
- `),l("Config written",null)}catch{return a(`Unable to write ~/${Ue}/config.json`)}},ht=e=>{let t=Xn();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return Fd(n)},Jn=()=>{let e=Ds(),t=Fs();if(d(t))return a(`Unable to create ~/${Ue}`);if(!(Le.readFile(e)!==null)){let p=Fd(qp);if(d(p))throw new Error(`Unable to create ~/${Ue}/config.json`)}let r=Xn();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:c,autoSyncDebounceMs:u,logLevel:m}=r.value;return!s||!i?a(`User name or ID not configured in ~/${Ue}/config.json`):(process.env.EPIQ_LOG_LEVEL=m,l("successfully loaded settings",{logLevel:m??"debug",preferredEditor:o??"",userName:s,userId:i,autoSync:c??!1,autoSyncIntervalMs:u??1e4,viewMode:"dense"}))};var io=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null};import{useSyncExternalStore as ZE}from"react";var ao,Jp=new Set,Bd=()=>{for(let e of Jp)e()};var kt=()=>{if(!ao)throw new Error("Ui state not initialized. Call initUiState() first.");return ao};var Ud=(e={})=>(ao=e,Bd(),l("UX state initialized",null)),Qp=e=>{let t=kt();return ao=e(t),Bd(),l("UX state updated",null)},Dt=e=>Qp(t=>({...t,...e}));import{spawn as Zp}from"node:child_process";function Bs(e){let t=process.platform,o=Zp(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}import{ulid as Us}from"ulid";import{spawnSync as ef}from"node:child_process";import tf from"node:os";import Od from"node:path";import{ulid as nf}from"ulid";function rf(){let{preferredEditor:e}=H(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function of(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function _d(e){let t=Od.join(tf.tmpdir(),"epiq");Le.mkDir(t);let n=Od.join(t,nf());Le.writeToFile(n,e??"");let r=rf();for(let o of r){let s=of(o,n),i=ef(s,{stdio:"inherit",shell:!0});if(!i.error&&i.status===0){let c=Le.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 $d=async e=>{let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(e.modifier===we.DESCRIPTION)return af();if(r&&Bn(r))return sf(e);if(e.modifier===we.TITLE){let o=Z();if(d(o))return a("Unable to resolve user ID");let s=r;if(!s)return a("Missing node");if(s.readonly)return a("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return a("Provide a title");let c=await qe();return d(c)?c:B([{id:Us(),action:"edit.title",payload:{id:s.id,name:i},...o.value}],c.value)}return a("Unknown edit command")},sf=async e=>{let t=Z();if(d(t))return a("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=f(),o=W(n.id)[r];if(!o||!Bn(o))return a("Select a comment first");if(o.readonly)return a("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return a("Unable to resolve comment issue");let i=f().nodes[s];if(!i||!w(i))return a("Unable to resolve comment issue");if(i.readonly)return a("Cannot edit readonly issue");let c=o.id.split(":").at(0)??"",u=b.getComment(c);if(!u||u.deleted)return a("Unable to resolve comment");if(u.issue!==i.id)return a("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return a("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return a("Provide a comment");let p=await qe();if(d(p))return p;let v=p.value;return B([{id:Us(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:m},...t.value}],v)},af=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let t=await qe();if(d(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=f(),s=be([...r,o],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!w(i))return a("Edit target must be an issue");if(i.readonly)return a("Cannot edit readonly issue");let c=W(i.id).find(v=>v.title===se.DESCRIPTION);if(!c)return a("No target found");if(c.readonly)return a("Cannot edit readonly field");let u=i.props.description??"";if(typeof u!="string")return a("Selected field is not editable text");let m=_d(u);if(d(m))return a("Failed to edit field");let p=m.value;return p===u?l("No changes made",null):B([{id:Us(),action:"edit.description",payload:{id:i.id,md:p},...e.value}],n)};import cf from"node:fs";import Hd from"node:path";import Os from"node:fs";import df from"node:path";var Wd=async e=>{let t=df.join(e,".gitignore"),n=Os.existsSync(t)?Os.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
50
+ `;return wd.writeFileSync(T,k,"utf8"),l("Exported board layout",T)};import Yp from"node:os";import Dd from"node:path";import{z as kt}from"zod";import{accessSync as Hp,copyFileSync as jp,existsSync as io,mkdirSync as Pd,readdirSync as Ld,readFileSync as Vp,renameSync as Gp,rmSync as zp,statSync as kd,unlinkSync as Kp,writeFileSync as qp}from"node:fs";import Sn from"node:path";var Fs=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Le={writeToFile:(e,t)=>{try{let n=Sn.dirname(e);io(n)||Pd(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);qp(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Vp(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Le.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 io(e)&&kd(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Hp(e),!0}catch{return!1}},mkDir:e=>Pd(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Sn.parse(t);for(;;){let r=Sn.join(t,e);try{if(io(r)&&kd(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Sn.dirname(t)}return null},readFirstJSON(e){try{if(!Le.dirExists(e))return null;let t=Ld(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Sn.join(e,t);return Le.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Le.dirExists(e)?Ld(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Kp(e)}catch(t){(!Fs(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{zp(e,{recursive:!0,force:!0})}catch(t){(!Fs(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Sn.dirname(t)),!n?.overwrite&&io(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Gp(e,t)}catch(r){if(Fs(r)&&r.code==="EXDEV"){jp(e,t),this.rmFile(e);return}throw r}}};var Xp={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},Fd=kt.object({logLevel:kt.enum(["info","error","debug"]),preferredEditor:kt.string().optional(),userName:kt.string().optional(),userId:kt.string().optional(),autoSync:kt.boolean().nullable().optional(),autoSyncDebounceMs:kt.number().optional(),viewMode:kt.enum(["dense","wide"]).optional()}).partial(),Jp="config.json",Bd=()=>Dd.join(Yp.homedir(),Ue),Bs=()=>Dd.join(Bd(),Jp),Us=()=>{try{return Le.mkDir(Bd()),l(`Ensured ~/${Ue} exists`,null)}catch{return a(`Unable to create ~/${Ue}`)}},Qp=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${Ue}/config.json JSON`)}let n=Fd.safeParse(t??{});return n.success?l("Parsed config",n.data):a(`Invalid ~/${Ue}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Jn=()=>{let e=Us();if(d(e))return a(e.message);let t=Bs(),n=Le.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Qp(n)},Ud=e=>{let t=Us();if(d(t))return a(t.message);let n=Fd.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Bs();try{return Le.writeToFile(r,JSON.stringify(n.data,null,2)+`
51
+ `),l("Config written",null)}catch{return a(`Unable to write ~/${Ue}/config.json`)}},xt=e=>{let t=Jn();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return Ud(n)},Qn=()=>{let e=Bs(),t=Us();if(d(t))return a(`Unable to create ~/${Ue}`);if(!(Le.readFile(e)!==null)){let p=Ud(Xp);if(d(p))throw new Error(`Unable to create ~/${Ue}/config.json`)}let r=Jn();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:c,autoSyncDebounceMs:u,logLevel:m}=r.value;return!s||!i?a(`User name or ID not configured in ~/${Ue}/config.json`):(process.env.EPIQ_LOG_LEVEL=m,l("successfully loaded settings",{logLevel:m??"debug",preferredEditor:o??"",userName:s,userId:i,autoSync:c??!1,autoSyncIntervalMs:u??1e4,viewMode:"dense"}))};var ao=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null};import{useSyncExternalStore as oN}from"react";var co,Zp=new Set,Od=()=>{for(let e of Zp)e()};var Dt=()=>{if(!co)throw new Error("Ui state not initialized. Call initUiState() first.");return co};var _d=(e={})=>(co=e,Od(),l("UX state initialized",null)),ef=e=>{let t=Dt();return co=e(t),Od(),l("UX state updated",null)},Ft=e=>ef(t=>({...t,...e}));import{spawn as tf}from"node:child_process";function Os(e){let t=process.platform,o=tf(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}import{ulid as _s}from"ulid";import{spawnSync as nf}from"node:child_process";import rf from"node:os";import $d from"node:path";import{ulid as of}from"ulid";function sf(){let{preferredEditor:e}=H(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function af(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function Wd(e){let t=$d.join(rf.tmpdir(),"epiq");Le.mkDir(t);let n=$d.join(t,of());Le.writeToFile(n,e??"");let r=sf();for(let o of r){let s=af(o,n),i=nf(s,{stdio:"inherit",shell:!0});if(!i.error&&i.status===0){let c=Le.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 Hd=async e=>{let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(e.modifier===we.DESCRIPTION)return cf();if(r&&Un(r))return df(e);if(e.modifier===we.TITLE){let o=Z();if(d(o))return a("Unable to resolve user ID");let s=r;if(!s)return a("Missing node");if(s.readonly)return a("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return a("Provide a title");let c=await qe();return d(c)?c:B([{id:_s(),action:"edit.title",payload:{id:s.id,name:i},...o.value}],c.value)}return a("Unknown edit command")},df=async e=>{let t=Z();if(d(t))return a("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=f(),o=W(n.id)[r];if(!o||!Un(o))return a("Select a comment first");if(o.readonly)return a("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return a("Unable to resolve comment issue");let i=f().nodes[s];if(!i||!w(i))return a("Unable to resolve comment issue");if(i.readonly)return a("Cannot edit readonly issue");let c=o.id.split(":").at(0)??"",u=b.getComment(c);if(!u||u.deleted)return a("Unable to resolve comment");if(u.issue!==i.id)return a("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return a("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return a("Provide a comment");let p=await qe();if(d(p))return p;let v=p.value;return B([{id:_s(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:m},...t.value}],v)},cf=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let t=await qe();if(d(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=f(),s=be([...r,o],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!w(i))return a("Edit target must be an issue");if(i.readonly)return a("Cannot edit readonly issue");let c=W(i.id).find(v=>v.title===se.DESCRIPTION);if(!c)return a("No target found");if(c.readonly)return a("Cannot edit readonly field");let u=i.props.description??"";if(typeof u!="string")return a("Selected field is not editable text");let m=Wd(u);if(d(m))return a("Failed to edit field");let p=m.value;return p===u?l("No changes made",null):B([{id:_s(),action:"edit.description",payload:{id:i.id,md:p},...e.value}],n)};import uf from"node:fs";import Vd from"node:path";import $s from"node:fs";import lf from"node:path";var jd=async e=>{let t=lf.join(e,".gitignore"),n=$s.existsSync(t)?$s.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
52
52
  `).map(u=>u.trim()),s=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(s.length===0)return l("Local epiq paths already ignored",!1);let c=["# [epiq]: local hydrated state is never committed",...s].join(`
53
53
  `);return n=n.trimEnd()+`
54
54
 
55
55
  ${c}
56
- `,Os.writeFileSync(t,n,"utf8"),re.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)};var lf=async e=>{let t=await U({cwd:e,args:["status","--porcelain"]});return d(t)?t:l("Checked git diff",t.value.stdout.trim().length>0)},Y=(e,t)=>a(`[${e}] ${t}`),jd=async()=>{_("");let e=an(),t=await Ye(process.cwd());if(d(t))return Y(1,t.message);let n=t.value,r=await vr(n);if(d(r))return Y(2,r.message);if(r.value)return Y(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await lf(n);if(d(o))return Y(2.5,o.message);if(o.value)return Y(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(jo(n))return Y(4,"Epiq project already initialized");let s=Tt();if(!s.isSetupDone||!s.userName)return Y(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let i=H(),c=i.userName,u=i.userId;if(!u||!c)return Y(5,"Missing Epiq user id");let m=e.stateBranch,p=await hr({repoRoot:n,branch:m});if(d(p))return Y(6,p.message);if(p.value)return Y(6,`State branch already exists: ${m}`);let v=await es({repoRoot:n,stateBranchName:m});if(d(v))return Y(6,v.message);let I=br();if(d(I))return Y(7,I.message);let E=Hd.join(Ir(),e.projectId),N=await Vt({repoRoot:n,stateBranchRoot:E,stateBranchName:m});if(d(N))return Y(8,N.message);let T=Hd.join(E,".epiq");cf.mkdirSync(T,{recursive:!0});let k=Aa({userId:u,userName:c});if(d(k))return Y(9,k.message);for(let Wo of k.value){let ci=Dr({event:Wo,rootDir:E});if(d(ci))return Y(9,ci.message)}let O=await Cr({stateBranchRoot:E,eventFileName:qt({userId:u,userName:c})});if(d(O))return Y(10,O.message);let V=await cn({cwd:E,message:"[epiq:init]"});if(d(V))return Y(10,V.message);let R=await Wd(n);if(d(R))return Y(11,R.message);let A=fi({repoRoot:n,fileContents:e});if(d(A))return Y(12,A.message);let G=await oe.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d(G))return Y(13,G.message);let Re=await oe.commit({cwd:n,message:"[epiq:init-project]"});if(d(Re))return Y(13,Re.message);let Ae="Project initialized!",Ge=await U({cwd:n,args:["push","-u","origin","HEAD"]});d(Ge)&&(Ae+=` Warn: [init:14] ${Ge.message}`);let de=await Dn({repoRoot:n,stateBranchRoot:E});d(de)&&(Ae+=` Warn: [init:15] ${de.message}`);let ct=At(k.value).filter(d);if(ct.length>0)return Y(16,ct.map(Wo=>Wo.message).join(`
57
- `));let ze=We();if(d(ze))return Y(16,ze.message);let{rootNodeId:Ll,nodes:kl}=ze.value,di=kl[Ll];return di?(M.navigate({contextNode:di,selectedIndex:0}),C({hasProjectDefinition:!0,mode:g.DEFAULT}),l(Ae,null)):Y(16,"Unable to resolve initialized root node")};import{ulid as mf}from"ulid";import{ulid as uf}from"ulid";var Vd=null,Ft=()=>structuredClone(Vd),Qn=e=>{Vd=e},Gd=()=>{let{contextNode:e,selectedIndex:t}=f(),r=z(e.id)[t];return r?l("Resolved selected child",r):a("Target node not found")},_s=({id:e,parentId:t,position:n={at:"end"}})=>{let r=z(t).filter(o=>o.id!==e);return Fr(r,n)},zd=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Z();if(d(r))return a("Unable to resolve user ID");let o=_s({parentId:t,id:e,position:n});return d(o)?o:l("Created pending move state",{id:uf(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Kd=e=>{Qn(e);let t=Rt(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function $s(e){let t=Gd();if(d(t))return t;let{contextNode:n,nodes:r}=f();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=z(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let c=s[i+e];if(!c)return a("Missing sibling node");let u=zd({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:Kd(u.value)}function Ws(e){let t=Gd();if(d(t))return t;let{contextNode:n,selectedIndex:r}=f(),s=z(n.id)[r+e];if(!s)return a("Missing sibling node");let i=zd({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:Kd(i.value)}var qd=()=>{let e=Ft();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=f().nodes[n];if(!r)return a("Move parent not found");let o=z(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(M.navigate({contextNode:r,selectedIndex:o}),l("Synchronized navigation to moved node",null))},co=(e,t="Moved preview")=>{if(d(e))return e;let n=qd();return d(n)?n:(C({mode:g.MOVE}),l(t,null))},Yd=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=q().commandMeta,{contextNode:n,selectedIndex:r}=f(),o=z(n.id)[r];if(!o)return C({mode:g.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 s=z(o.parentNodeId),i=s.findIndex(({id:v})=>v===o.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],u=s[i+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=_s({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(Qn({id:mf(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),C({mode:g.MOVE}),l("Move initialized",null))}if(t==="next")return co(Ws(1));if(t==="previous")return co(Ws(-1));if(t==="to-next")return co($s(1));if(t==="to-previous")return co($s(-1));if(t==="confirm"){let s=Ft();if(!s)return a("No pending move to confirm");let i=await qe();if(d(i))return i;let c=B([s],i.value);if(d(c))return c;let u=qd();return d(u)?u:(Qn(null),C({mode:g.DEFAULT}),l("Moved item",null))}return t==="cancel"?(Qn(null),C({mode:g.DEFAULT}),l("Cancelling move",null)):a("Invalid move modifier")};import{ulid as uo}from"ulid";import{monotonicFactory as pf,ulid as ff}from"ulid";var gf=pf(),lo=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=gf();return l("Created issue events",[{id:ff(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var Xd=async(e,t)=>{let n=Z();if(d(n))return a("Unable to resolve user ID");let r=await qe();if(d(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=f(),u=m=>{let p=B([m],o);if(d(p))return p;let v=b.getNode(p.value[0].result.id);if(!v)return a("Created node not found");if(!v.parentNodeId)return p;let I=b.getNode(v.parentNodeId);return I?(M.navigate({contextNode:I,selectedIndex:b.getSiblings(v.parentNodeId).findIndex(({id:E})=>E===v.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=f(),p=b.getNode(m);if(!p)return a("Workspace not found");let v=vn(p.id,n.value,o);return d(v)?v:u({id:uo(),action:"add.board",payload:{id:uo(),name:t.inputString,parent:p.id,rank:v.value},...n.value})}if(t.modifier==="swimlane"){let m=be(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=vn(m.value.id,n.value,o);return d(p)?p:u({id:uo(),action:"add.swimlane",payload:{id:uo(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=W(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let V=be(s,"SWIMLANE");return d(V)?null:V.value})();if(!p)return a("Unable to add issue in this context");let v=vn(p.id,n.value,o);if(d(v))return v;let I=lo({name:t.inputString,parent:p.id,rank:v.value,user:n.value});if(d(I))return I;let E=I.value,N=B([...E],o);if(d(N))return N;if(!N.value[0])return a("Issue creation failed");let O=E.find(V=>V.action==="add.issue")?.payload.id;return O?(M.navigate({contextNode:p,selectedIndex:b.getSiblings(p.id).findIndex(({id:V})=>V===O)}),l("Issue created",null)):a("Unable to determine ticket id")}return l("Success",null)};var mo=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=f(),s=la(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=Bt();if(d(u))return u;let p=At(i).filter(d);if(p.length>0)return Bt(),C(o),a(p.map(I=>I.message).join(", "));let v=f().nodes[e];return v?(M.navigate({contextNode:v,selectedIndex:r}),l("",{unappliedEvents:c})):(Bt(),C(o),a("Board did not exist at that date"))};var vf=20,yf=16,hf=150,po=null,fo=null;var rn=()=>{po!==null&&(clearInterval(po),po=null),fo!==null&&(clearTimeout(fo),fo=null)},Jd=()=>{rn(),C({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},xf=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)},Qd=({events:e,startTime:t,durationMs:n})=>{rn();let r=e.length,o=e.map(v=>gn(v)??t),s=o[r-1]??Date.now(),i=xf(o),c=Math.max(1,Math.round(n*vf/1e3)),u=Math.max(Math.round(n/c),yf),m=0,p=0;C({mode:g.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),po=setInterval(()=>{m++;let v=m/c,I=[],E;for(;p<r&&i[p]<=v;){let T=e[p],k=Rt(T);if(d(k)){Jd();return}I.push(...cs(T)),E=T,p++}if(p>=r||m>=c){for(;p<r;p++){let k=Rt(e[p]);if(d(k))break}let T=f().replay;C({unappliedEvents:[],replay:T&&{...T,progress:1,appliedCount:r}}),rn(),fo=setTimeout(Jd,hf);return}let N=f().replay;C({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,v),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:E?gn(E)??N?.currentTime??t:N?.currentTime??t,currentLabel:E?sa(E):N?.currentLabel??"",flashNodeIds:E?[...new Set(I)]:N?.flashNodeIds??[]}})},u)};var Zd=async()=>{let e=be(f().breadCrumb,"BOARD");if(d(e))return e;let t=await Ye(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Te({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=q().commandMeta;if(rn(),r==="now"){let c=pt(n.value);if(d(c))return a(c.message);let u=Bt();if(d(u))return u;let p=At(c.value).filter(d);return p.length>0?a(p.map(v=>v.message).join(", ")):(C({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),l("Peeking now",!0))}let s;if(r==="prev"){let c=f().eventLog.at(-1),u=gn(c);if(u===null)return a("No previous event to peek");s=u}else if(r==="next"){let c=f().unappliedEvents.at(0),u=gn(c);if(u===null)return a("No next event to peek");s=u+1}else{let c=Qt(r||o.trim());if(!c)return a("Invalid peek date");s=c.getTime()}let i=mo({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(C({mode:g.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),l("Peeking",!0))};var ec=async()=>{let e=be(f().breadCrumb,"BOARD");if(d(e))return e;let t=await Ye(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Te({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=q().commandMeta,{dateInput:s,durationInput:i}=Vr(r,o);if(rn(),f().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let c=Qt(s);if(!c)return a("Invalid replay date");let u=i?jr(i):15e3;if(u===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=f(),v=mo({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(d(v))return v;let{unappliedEvents:I}=v.value;return I.length===0?(Bt(),C(p),l("Nothing to replay from that point",!0)):(Qd({events:I,startTime:m,durationMs:u}),l("Replaying board history",!0))};import bf from"zod";var tc=()=>{let e=q().commandMeta.inputString,t=bf.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=ht({autoSyncDebounceMs:t.data});return d(n)?n:(_e({autoSyncIntervalMs:t.data}),C({mode:g.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))};var nc=()=>{let e=q().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Da(e),n=ht({autoSync:t});return d(n)?n:(_e({autoSync:t}),C({mode:g.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var rc=()=>{let e=q().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=ht({logLevel:e});return d(n)?n:(_e({logLevel:e}),C({mode:g.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var oc=async()=>{_(""),C({mode:g.DEFAULT});let e=We();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");C({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Or();return d(t)?(C({syncStatus:{msg:t.message,status:"failed"}}),t):(C({mode:g.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var Cf=e=>e.action==="add.issue.comment",sc=e=>Object.values(f().tags).find(t=>t.name===e),ic=e=>Object.values(f().contributors).find(t=>t.name===e),xt=async()=>{let e=await qe();return d(e)?e:l("Resolved persist root",e.value)},go=[{systemOnly:!0,intent:L.Move,description:"Internal move-state command",mode:g.COMMAND_LINE,action:Yd},{intent:L.Delete,description:"Delete the currently selected node",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await xt();if(d(o))return o;if(r.context==="COMMENT"){let s=r.id,i=w(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=f().nodes[i];if(!c||!w(c))return a("Unable to resolve comment issue");let u=c.log?.filter(Cf).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):B([{id:xe(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return B([{id:xe(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=q().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>le(x.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return fe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:g.DEFAULT})),l("Filter updated",null)}},{intent:L.ViewHelp,description:"Open the help screen",mode:g.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=f();return Dt({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),C({mode:g.HELP}),l("Viewing help",null)}},{intent:L.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!w(r))return a("Cannot close in this context");let o=f().nodes[ce];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await xt();if(d(s))return s;let i=s.value,c=Yt(o.id,r.id,{at:"end"},e.value,i);if(d(c))return c;let u=B([{id:xe(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value}],i);return d(u)?u:l("Issue closed",null)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):mt(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let s=o.value,i=f().nodes[ce];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!w(s))return a("Target node is not issue");let c=io(s);if(!c)return a("Unable to resolve previous parent from issue history");if(c===i.id)return a("Previous parent resolves to closed swimlane");let u=f().nodes[c];if(!u)return a("Previous parent no longer exists");let m=await xt();if(d(m))return m;let p=m.value,v=Yt(u.id,s.id,{at:"end"},e.value,p);if(d(v))return v;let I=B([{id:xe(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:v.value},...e.value}],p);return d(I)?I:l("Issue reopened",null)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Init,description:"Initialize Epiq in the current git repository",mode:g.COMMAND_LINE,action:jd},{intent:L.NewItem,description:"Create a new board, swimlane, or issue",mode:g.COMMAND_LINE,action:Xd,onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Rename,description:"itle] Rename the currently selected node",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=ad();if(!o)return a("Provide a title");let s=await xt();return d(s)?s:B([{id:xe(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.UntagTicket,description:"Remove a tag from the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=sc(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=f();if(!s)return a("Invalid untag target");let i=mt(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let c=i.value;if(!w(c))return a("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let m=await xt();return d(m)?m:B([{id:xe(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.TagTicket,description:"Add or create a tag on the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=f();if(!o)return a("Invalid tag target");let s=mt(o.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!w(i))return a("Target node is not issue");let c=await xt();if(d(c))return c;let u=sc(r),m=u?.id??xe();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):B([...u?[]:[{id:xe(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:xe(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.AssignUserToTicket,description:"Assign a user to the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let{selectedIndex:o,contextNode:s}=f(),i=W(s.id)[o];if(!i)return a("Invalid assign target");let c=mt(i.id,"TICKET");if(d(c))return a("Unable to assign issue in this context");let u=c.value;if(!w(u))return a("Target node is not issue");let m=await xt();if(d(m))return m;let p=ic(r),v=p?.id??xe();return(u.props.assignees??[]).includes(v)?a("Assignee already assigned"):B([...p?[]:[{id:xe(),action:"create.contributor",payload:{id:v,name:r},...e.value}],{id:xe(),action:"add.issue.assignee",payload:{id:u.id,assignee:v},...e.value}],m.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let o=ic(r);if(!o)return a(`Assignee "${r}" does not exist`);let{selectedNode:s}=f();if(!s)return a("Invalid unassign target");let i=mt(s.id,"TICKET");if(d(i))return a("Unable to unassign in this context");let c=i.value;if(!w(c))return a("Target node is not issue");if(!(c.props.assignees??[]).includes(o.id))return a(`Issue is not assigned to "${r}"`);let m=await xt();return d(m)?m:B([{id:xe(),action:"remove.issue.assignee",payload:{id:c.id,assignee:o.id},...e.value}],m.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Comment,description:"Add a comment to the selected issue",mode:g.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return a("Provide a comment");if(n.length>xn)return a(`Cannot exceed ${xn} characters`);let r=Z();if(d(r))return a("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=f(),i=be([...o,s],"TICKET");if(d(i))return a("Edit target must be an issue");let c=i.value;if(!c)return a("Invalid comment target");let u=c.context==="TICKET"?l("Resolved ticket",c):mt(c.id,"TICKET");if(d(u))return a("Unable to comment on issue in this context");let m=u.value;if(!w(m))return a("Target node is not issue");let p=await xt();return d(p)?p:B([{id:xe(),action:"add.issue.comment",payload:{id:xe(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Sync,description:"Pull, commit, and push Epiq state",mode:g.COMMAND_LINE,action:oc},{intent:L.Peek,description:"View board state at another point in time",mode:g.COMMAND_LINE,action:Zd},{intent:L.Replay,description:"Replay board history forward from a point in time",mode:g.COMMAND_LINE,action:ec},{intent:L.Export,description:"Export the current board layout to markdown",mode:g.COMMAND_LINE,action:async()=>{let e=await Td();return d(e)?e:(C({mode:g.DEFAULT}),l("Export successful",!0))}},{intent:L.Exit,description:"Exit the application",mode:g.COMMAND_LINE,action:async()=>(M.exit(),l("Exit successful",!0))},{intent:L.Edit,description:"Edit title or description",mode:g.COMMAND_LINE,action:async(e,t)=>$d(t),onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:g.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case ae.USERNAME:{let{userId:r,preferredEditor:o,userName:s}=H(),i=n||s,c=r??xe();if(!i||!c)return a("Unable to resolve user name or id");let u=ht({userName:i,userId:c,preferredEditor:o??""});return d(u)?u:(_e({userName:i,userId:c}),C({mode:g.DEFAULT}),l(`Username set to "${i}"`,null))}case ae.EDITOR:{if(!n)return a("No editor provided");let r=ht({preferredEditor:n});return d(r)?r:(_e({preferredEditor:n}),C({mode:g.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case ae.VIEW:return n!=="wide"&&n!=="dense"?a("Invalid view mode"):(_e({viewMode:n}),l(`View set to "${n}"`,null));case ae.AUTOSYNC:return nc();case ae.LOG_LEVEL:return rc();case ae.SYNC_DEBOUNCE_MS:return tc();default:return a("Unknown config command")}}},{intent:L.Coffee,description:"Sponsor the development of Epiq!",mode:g.COMMAND_LINE,action:()=>{let e=q().commandMeta.modifier;return e==="custom"?Bs("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):Bs(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),_(""),l("Thanks you!",null)}}];var Sf=new Set(["peek","replay","filter","view-help"]),ot=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=q();if(!t)return a("No command to confirm");if(!e&&n===wt.Invalid)return a("Invalid command");let s=Xr(t);nd();let{readOnly:i}=f();if(i&&!Sf.has(s))return Gn({status:bt.Fail,message:"Command not available in readonly state",value:null});let c=go.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return Gn({status:bt.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return Gn({status:bt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?Gn(u):(rd({addToHistory:!e}),c.onSuccess?.(),H().autoSync&&$r(),u)};var vo=[{intent:h.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(C({mode:g.COMMAND_LINE}),_("move cancel"),ot({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:g.DEFAULT,description:"[m] move (init/confirm)",action:()=>(C({mode:g.COMMAND_LINE}),_("move start"),ot({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:g.MOVE,action:()=>(C({mode:g.COMMAND_LINE}),_("move confirm"),ot({isForceExecutedBySystem:!0}))}],yo=[{intent:h.MovePreviousItem,mode:g.MOVE,action:()=>Ft()?(C({mode:g.COMMAND_LINE}),_("move previous"),ot({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveNextItem,mode:g.MOVE,action:()=>Ft()?(C({mode:g.COMMAND_LINE}),_("move next"),ot({isForceExecutedBySystem:!0})):a("No pending move")}],ac=[{intent:h.MoveToNextContainer,mode:g.MOVE,action:()=>Ft()?(C({mode:g.COMMAND_LINE}),_("move to-next"),ot({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveToPreviousContainer,mode:g.MOVE,action:()=>Ft()?(C({mode:g.COMMAND_LINE}),_("move to-previous"),ot({isForceExecutedBySystem:!0})):a("No pending move")}];var dc={[P.WORKSPACE]:[...vo,...yo],[P.BOARD]:[...vo,...yo],[P.SWIMLANE]:[...vo,...yo,...ac],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[],[P.COMMENT]:[]};var cc=()=>{_("");let{pendingNavTarget:e}=kt();C({mode:g.DEFAULT}),e&&M.navigate(e),Dt({pendingNavTarget:void 0})},lc=[{intent:h.ExitCommandLine,mode:g.HELP,action:()=>(cc(),l("Exiting help",null))},{intent:h.Exit,mode:g.HELP,action:()=>(cc(),l("Closed help",null))},{intent:h.NavPreviousItem,mode:g.HELP,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:h.NavNextItem,mode:g.HELP,action:()=>(M.navigateToNextItem(),l("Navigating to next help item",null))},{intent:h.NavToPreviousContainer,mode:g.HELP,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:h.NavToNextContainer,mode:g.HELP,action:()=>(M.navigateToNextContainer(),l("Navigating to next help container",null))}];var Ef=e=>{C({mode:g.COMMAND_LINE});let{pendingNavTarget:t}=kt();t&&M.navigate(t),Dt({pendingNavTarget:void 0}),_(`${e} `)},uc=()=>{_("");let{pendingNavTarget:e}=kt();e&&M.navigate(e),Dt({pendingNavTarget:void 0}),C({mode:g.DEFAULT})},mc=[{intent:h.InitCommandPalette,mode:g.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{_("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=f();return Dt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),C({mode:g.PALETTE}),l("Opening command palette",null)}},{intent:h.Confirm,mode:g.PALETTE,action:()=>{let{selectedNode:e}=f();if(!e||!St(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?(Ef(t),l("Selected command",t)):l("No command selected",null)}},{intent:h.ExitCommandLine,mode:g.PALETTE,action:()=>(uc(),l("Exiting palette",null))},{intent:h.Exit,mode:g.PALETTE,action:()=>(uc(),l("Closed command palette",null))},{intent:h.NavPreviousItem,mode:g.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:g.PALETTE,action:()=>(M.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:g.PALETTE,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:g.PALETTE,action:()=>(M.navigateToNextContainer(),l("Navigating to next container",null))}];var pc=[...lc,...mc,{intent:h.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.NEW} `),l("Adding new item",null))},{intent:h.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.DELETE} `),l("Deleting item",null))},{intent:h.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(C({mode:g.COMMAND_LINE}),_(""),l("Entering command line mode",null))},{intent:h.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=f();if(!z(e?.id??"")?.length){if(e?.title===se.DESCRIPTION)return C({mode:g.COMMAND_LINE}),_(`${x.EDIT} description `),l("Propose command",!0);if(e?.title===se.ASSIGNEES)return C({mode:g.COMMAND_LINE}),_(`${x.ASSIGN} `),l("Propose command",!0);if(e?.title===se.TAGS)return C({mode:g.COMMAND_LINE}),_(`${x.TAG} `),l("Propose command",!0);if(t.title===se.DESCRIPTION&&e?.context==="TEXT")return C({mode:g.COMMAND_LINE}),_(`${x.EDIT} description `),l("Propose command",!0)}return M.enterChildNode(),l("Entering context",null)}},{intent:h.EditTitle,mode:g.DEFAULT,description:"[r] rename title",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.EDIT} title ${f().selectedNode?.title}`),l("Exiting context",null))},{intent:h.EditDescription,mode:g.DEFAULT,description:"[e] edit description",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.EDIT} description `),l("Exiting context",null))},{intent:h.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(M.enterParentNode(),l("Exiting context",null))},{intent:h.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:g.DEFAULT,action:()=>(M.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:g.DEFAULT,action:()=>(M.navigateToNextContainer(),l("Navigating to next container",null))}];var Nf=500,Rf=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),fc=e=>{let t=Rf(e);t&&Yr(n=>(n+t).slice(0,Nf))};var Af=[g.COMMAND_LINE,g.PALETTE],Tf=e=>[{intent:h.MoveCursorLeft,mode:e,action:()=>(Ns(-1),l("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:e,action:()=>(Ns(1),l("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:e,action:()=>(Rs("left"),l("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:e,action:()=>(Rs("right"),l("Moving cursor right of word",null))},{intent:h.AutoCompleteCommand,mode:e,action:()=>(Yr((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=f().selectedNode?.title??""),r+o}),l("Auto-completing command",null))},{intent:h.CaptureInput,mode:e,action:(t,{sequence:n})=>(fc(n??""),l("Capturing input",null))},{intent:h.EraseInput,mode:e,action:()=>(ed(),l("Erasing input",null))},{intent:h.EraseInputWord,mode:e,action:()=>(td(),l("Erasing input word",null))}],gc=[{intent:h.Confirm,mode:g.COMMAND_LINE,action:()=>(ot(),l("Executing command",null))},{intent:h.ViewHelp,mode:g.DEFAULT,action:()=>(C({mode:g.HELP}),l("Viewing help",null))},...Af.flatMap(Tf),{intent:h.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(C({mode:g.DEFAULT}),l("Exiting command line",null))},{intent:h.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(od(),l("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(sd(),l("Getting next command from history",null))}];import hc from"chalk";var ho=hc.dim.hex(y.secondary2)(": for command line"),vc="q to exit",yc=`${hc.hex(y.accent)("m")} to confirm`,Hs={[P.WORKSPACE]:[ho],[P.BOARD]:[ho],[P.BOARD+g.COMMAND_LINE]:[ho],[P.SWIMLANE]:[ho],[P.TICKET+g.HELP]:[vc],[P.SWIMLANE+g.HELP]:[vc],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+g.MOVE]:[yc],[P.TICKET+g.MOVE]:[yc]};var Zn=e=>e.trim().toLocaleLowerCase(),wf=e=>{let{tags:t}=f();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Mf=e=>{let{contributors:t}=f();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},xc=(e,t)=>{let n=Zn(t.value);if(!n)return!0;switch(t.target){case"title":return Zn(e.title??"").includes(n);case"description":return Zn(e.props.description??"").includes(n);case"tag":return wf(e).map(Zn).some(o=>o.includes(n));case"assignee":return Mf(e).map(Zn).some(o=>o.includes(n));default:return!0}};function Ic(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=r;for(;s&&(o.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let i=o[o.length-1];return!i||i.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var bc=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 on,js,Vs=new Set,Cc=()=>{for(let e of Vs)e()},Lf=e=>(Vs.add(e),()=>Vs.delete(e));function Sc(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=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=Ic(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,v=Hs[p+n]??Hs[p]??[],I=[...pc,...dc[p]??[],...gc],E=bc(I),N=kf(o,s),T=N[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:v,availableActions:I,actionIndex:E,selectedNode:T,renderedChildrenIndex:N})}var f=()=>{if(!on)throw new Error("State not initialized. Call initWorkspaceState() first.");return on},We=()=>on?l("Retrieved state",on):a("State not initialized. Call initWorkspaceState() first.");function _n(e){js=e;let t=Ke(process.cwd()),n=!1;if(!d(t)){let s=Ct(t.value);if(d(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:g.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{}},o=Sc(r);return d(o)?o:(on=o.value,Cc(),l("State initialized",null))}function fe(e){let t=f(),n=e(t),r=Sc(n);return d(r)?a(r.message??"Unable to update state"):(on=r.value,Cc(),l("State updated",null))}var C=e=>fe(t=>({...t,...e}));var $=()=>Pf(Lf,f,f),kf=(e,t)=>{let n={};for(let r of Object.values(e))w(r)&&t.length>0&&!t.every(o=>xc(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,s)=>{let i=e[o.id],c=e[s.id];return!i||!c?0:i.rank.localeCompare(c.rank)});return n},W=e=>f()?.renderedChildrenIndex[e]??[],Bt=()=>js?_n(js):a("Cannot reset state: no initial workspace found"),hn=()=>on!==void 0;var Gs=e=>{hn()&&(C({syncStatus:e}),Gt({type:"sync-status",payload:e}))},xo=(e="Syncing...")=>{Gs({status:"syncing",msg:e})},Io=(e="Synced")=>{Gs({status:"synced",msg:e})},zs=e=>{Gs({status:"failed",msg:e})},He=e=>(zs(e),a(e));import{decodeTime as NM}from"ulid";var Df=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=K("getRepoRootDir",await Ye(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=K("getStateBranchRoot",Te({repoRoot:r}));if(d(o))return a(o.message);let s=o.value;logger.debug("[sync] state branch root",s);let i=K("ensureInitialCommit",await ki(r));if(d(i))return a(i.message);logger.debug("[sync] initial commit result",{created:i.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let c=K("bootstrapStateBranchStorage",await Fi({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(d(c))return a(c.message);logger.debug("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let u=K("hasInProgressGitOperation(stateBranchRoot)",await vr(s));if(d(u))return a(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value)return logger.info("[sync] state branch git operation in progress"),a("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let m=K("ensureStateBranchLayout",Mi(r,s));return d(m)?a(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}),l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}))},Ff=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=K("stageStateBranchOwnEventFile",await Cr({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=K("hasStagedChanges(after stage)",await Ei(t));if(d(o))return a(o.message);if(logger.debug("[sync] state branch change check after stage result",{changed:o.value}),!o.value)return logger.info("[sync] no own event file changes to commit"),l("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let s=K("createStateBranchSyncCommit",await Di({repoRoot:e,stateBranchRoot:t}));return d(s)?a(s.message):(logger.debug("[sync] created sync commit",s.value),l("Committed own event file",{createdCommit:!0,commitSha:s.value}))},_r=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),a("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),a("Own event file must end with .jsonl");xo();let n=K("ensureSyncReady",await Df({cwd:e,ensureUpstream:!0}));if(d(n))return He(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=K("isDetachedHead(stateBranchRoot)",await Ni(o));if(d(i))return He(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return He("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,v=K("getStateBranch",dn(r));if(d(v))return He(v.message);let I=v.value;logger.debug("[sync] resolved state branch",{stateBranch:I,stateBranchRoot:o});let E=K("commitOwnEventFileToStateBranch",await Ff({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(E))return He(E.message);c=E.value.createdCommit,u=E.value.commitSha;let N=K("pullBranchRebaseIfPresent",await Jo({cwd:o,branch:I}));if(d(N))return He(N.message);if(m=N.value,c||s){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:o});let T=K("pushStateBranch",await Dn({stateBranchRoot:o,repoRoot:r}));if(d(T)&&Si(T.message)){let k=K("pullBranchRebaseIfPresent(retry)",await Jo({cwd:o,branch:I}));if(d(k))return He(k.message);m=m||k.value,T=K("pushStateBranch(retry)",await Dn({stateBranchRoot:o,repoRoot:r}))}if(d(T))return He(T.message);p=T.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let T=K("git rev-parse HEAD",await U({args:["rev-parse","HEAD"],cwd:o}));if(d(T))return He(T.message);u=T.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Io(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:s})};var Ks=e=>{let t=Ke(e??process.cwd());return d(t)?a(t.message):l("Resolved Epiq repo root",t.value)},ke=async e=>{let t=Ks(e);if(d(t))return t;let n=Te({repoRoot:t.value});if(d(n))return a(n.message);let r=an(),o=await Vt({repoRoot:t.value,stateBranchRoot:n.value,stateBranchName:r.stateBranch});if(d(o))return a(o.message);let s=await U({cwd:n.value,args:["pull","--ff-only"]});d(s)&&re.info(3,s.message);let i=pt(n.value);if(d(i))return a(i.message);let c=Xt(i.value);return d(c)?a(c.message):l("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:n.value})},De=()=>{let e=Jn();return d(e)?a(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},je=()=>{let e=We();return d(e)?a(e.message):e},Ec=e=>(e.props.tags??[]).map(t=>b.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:ie(t.name)})),Nc=e=>(e.props.assignees??[]).map(t=>b.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:ie(t.name)}));var Rc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=je();if(d(n))return n;let r=Object.values(n.value.nodes).filter(w).filter(o=>e.includeClosed||o.parentNodeId!==ce).map(o=>({id:o.id,title:Nt(o.title),description:o.props.description??"",parentNodeId:o.parentNodeId,isClosed:o.parentNodeId===ce,readonly:!!o.readonly,tags:Ec(o),assignees:Nc(o)}));return l("Listed issues",r)},Ac=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=vn(e.parentId,n.value,t.value.stateBranchRoot);if(d(r))return r;let o=lo({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(d(o))return o;let s=o.value,i=B([...s],t.value.stateBranchRoot);if(d(i))return a(i.message);let c=s.find(u=>u.action==="add.issue")?.payload.id;return c?l("Created issue",{id:c,title:e.title,parentId:e.parentId}):a("Unable to determine created issue id")},Tc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=Yt(ce,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(d(r))return r;let o={id:Ie(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ce,rank:r.value}},s=B([o],t.value.stateBranchRoot);return d(s)?a(s.message):l("Closed issue",{id:e.issueId})},wc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Target node is not issue");if(o.parentNodeId!==ce)return a("Issue is not closed");let s=io(o);if(!s)return a("Unable to resolve previous parent from issue history");if(s===ce)return a("Previous parent resolves to closed swimlane");let i=r.value.nodes[s];if(!i)return a("Previous parent no longer exists");let c=Yt(i.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(c))return c;let u={id:Ie(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:i.id,rank:c.value}},m=B([u],t.value.stateBranchRoot);return d(m)?a(m.message):l("Reopened issue",{id:o.id,parentId:i.id})},Mc=async e=>{let t=Ks(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=Te({repoRoot:t.value});if(d(r))return r;let o=pt(r.value);if(d(o))return o;let s=Xt(o.value);if(d(s))return s;let i=Yt(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(d(i))return i;let c={id:Ie(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:i.value}},u=B([c],r.value);return d(u)?a(u.message):l("Moved issue",{id:e.issueId,parentId:e.parentId})},bo=async(e={})=>{xo();let t=Ks(e.repoRoot);if(d(t))return a("Sync failed");let n=De();if(d(n))return n;let r=await _r({cwd:t.value,ownEventFileName:qt(n.value)});return d(r)?(zs(r.message),r):(Io(),l("Synced",r.value))};var Ut=async(e={})=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=je();if(d(n))return n;let r=Object.values(n.value.nodes),o=r.filter(m=>Er(m)&&!m.isDeleted),s=new Map,i=new Map;for(let m of r)if(!m.isDeleted){if(Et(m)&&m.parentNodeId){let p=s.get(m.parentNodeId)??[];p.push(m),s.set(m.parentNodeId,p)}if(w(m)&&m.parentNodeId){let p=i.get(m.parentNodeId)??[];p.push(m),i.set(m.parentNodeId,p)}}let c=Jn();if(d(c))return c;let u={};for(let m of r.filter(w))m.isDeleted||(u[m.id]=b.getCommentsByIssue(m.id).map(p=>{let v=b.getContributor(p.authorId);return{id:p.id,issueId:p.issue,body:p.md,author:{id:p.authorId,name:v?.name??"Unknown",color:ie(v?.name??p.authorId)},createdAt:Bf(p.id)}}));return l("Retrieved Epiq GUI state",{boards:o.sort((m,p)=>m.rank.localeCompare(p.rank)).map(m=>({id:m.id,title:m.title,swimlanes:(s.get(m.id)??[]).sort((p,v)=>p.rank.localeCompare(v.rank)).map(p=>({id:p.id,title:p.title,readonly:!!p.readonly,issues:(i.get(p.id)??[]).sort((v,I)=>v.rank.localeCompare(I.rank)).map(v=>({id:v.id,title:Nt(v.title),description:v.props.description??"",readonly:!!v.readonly,tags:Ec(v),assignees:Nc(v),parentNodeId:v.parentNodeId,isClosed:v.parentNodeId===ce})),parentNodeId:p.parentNodeId}))})),tags:Object.values(n.value.tags).map(m=>({...m,color:ie(m.name)})),contributors:Object.values(n.value.contributors).map(m=>({...m,color:ie(m.name)})),user:{name:c.value.userName??"",id:c.value.userId??"",color:ie(c.value.userName??"")},commentsByIssueId:u})},Pc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=o.props.description??"";if(s===e.description)return l("No changes made",{id:e.issueId,description:s});let i={id:Ie(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=B([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue description",{id:e.issueId,description:e.description})},Lc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=Nt(e.title);if(!s.trim())return a("Issue title cannot be empty");if(o.title===s)return l("No changes made",{id:e.issueId,title:s});let i={id:Ie(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=B([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue title",{id:e.issueId,title:s})},kc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Tag target must be an issue");if(o.readonly)return a("Cannot tag readonly issue");let s=Nt(e.tagName).trim();if(!s)return a("Tag name cannot be empty");let i=Object.values(r.value.tags).find(p=>p.name===s),c=i?.id??Ie(),u=[...i?[]:[{id:Ie(),...n.value,action:"create.tag",payload:{id:c,name:s}}],{id:Ie(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:c}}],m=B(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue tag",{id:e.issueId,tag:{id:c,name:s}})},Dc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Untag target must be an issue");if(o.readonly)return a("Cannot untag readonly issue");if(!r.value.tags[e.tagId])return a("Tag not found");let s={id:Ie(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue tag",{id:e.issueId,tagId:e.tagId})},Fc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Assign target must be an issue");if(o.readonly)return a("Cannot assign readonly issue");let s=Nt(e.assigneeName).trim();if(!s)return a("Assignee name cannot be empty");let i=Object.values(r.value.contributors).find(p=>p.name===s),c=i?.id??Ie(),u=[...i?[]:[{id:Ie(),...n.value,action:"create.contributor",payload:{id:c,name:s}}],{id:Ie(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:c}}],m=B(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue assignee",{id:e.issueId,assignee:{id:c,name:s}})},Bc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Unassign target must be an issue");if(o.readonly)return a("Cannot unassign readonly issue");if(!r.value.contributors[e.assigneeId])return a("Assignee not found");let s={id:Ie(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},Co=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Comment target must be an issue");if(o.readonly)return a("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return a("Comment cannot be empty");let i=Ie(),c={id:Ie(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Added issue comment",{id:i,issueId:e.issueId,body:s})},So=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return a("Unable to resolve comment");if(o.payload.author!==n.value.userId)return a("You can only delete your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!w(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot delete comment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return l("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:Ie(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})};var Uc=e=>{let t,n,r=!1,o=!1,s=!1,i=()=>{let p=Xn();if(d(p))return re.error(p.message);let{autoSync:v,userName:I,preferredEditor:E}=p.value;return!!(v&&I&&E)},c=async()=>{if(!r){if(o){s=!0;return}o=!0;try{await bo({repoRoot:e.repoRoot}),Gt({type:"state",payload:await Ut({repoRoot:e.repoRoot})})}finally{o=!1,s&&(s=!1,c())}}},u=(p=750)=>{r||(n&&clearTimeout(n),n=setTimeout(()=>{c()},p))},m=()=>{if(r)return;let p=Xn();if(d(p))return re.error(p.message);let{autoSyncDebounceMs:v}=p.value;i()&&(t=setTimeout(()=>{c(),m()},v??15e3))};return m(),{scheduleSync:u,dispose:()=>{r=!0,t&&clearTimeout(t),n&&clearTimeout(n)}}};import{WebSocketServer as Uf}from"ws";var Fe=(e,t)=>{e.send(JSON.stringify(t))},er=async(e,t)=>Fe(e,{type:"state",payload:await Ut({repoRoot:t})}),st=async(e,t,n,r,o)=>{if(Fe(e,{type:r,payload:o}),d(o))return Fe(e,{type:"failed",payload:o.message});n(),er(e,t)},Oc=(e,t,{onStateChanged:n})=>{new Uf({server:e,path:"/ws"}).on("connection",o=>{Bi(o),o.on("message",async s=>{try{let i=JSON.parse(s.toString()),{type:c}=i;if(c==="state:get")return er(o,t);if(c==="sync"){let u=await bo({repoRoot:t});return Fe(o,{type:"sync:result",payload:u}),n(),er(o,t)}if(c==="issue:comment:add"){let u=await Co({repoRoot:t,...i.payload});return st(o,t,n,"issue:comment:add:result",u)}if(c==="issue:comment:delete"){let u=await So({repoRoot:t,...i.payload});return Fe(o,{type:"issue:comment:delete:result",payload:u}),d(u)?Fe(o,{type:"failed",payload:u.message}):(n(),er(o,t))}if(c==="issue:edit:description"){let u=await Pc({repoRoot:t,...i.payload});return st(o,t,n,"issue:edit:description:result",u)}if(c==="issue:edit:title"){let u=await Lc({repoRoot:t,...i.payload});return st(o,t,n,"issue:edit:title:result",u)}if(c==="issue:tag:add"){let u=await kc({repoRoot:t,...i.payload});return st(o,t,n,"issue:tag:add:result",u)}if(c==="issue:tag:remove"){let u=await Dc({repoRoot:t,...i.payload});return st(o,t,n,"issue:tag:remove:result",u)}if(c==="issue:assignee:add"){let u=await Fc({repoRoot:t,...i.payload});return st(o,t,n,"issue:assignee:add:result",u)}if(c==="issue:assignee:remove"){let u=await Bc({repoRoot:t,...i.payload});return st(o,t,n,"issue:assignee:remove:result",u)}if(c==="issues:list")return Fe(o,{type:"issues",payload:await Rc({repoRoot:t})});if(c==="issues:create"){let u=await Ac({...i.payload,repoRoot:t});return Fe(o,{type:"issues:create:result",payload:u}),d(u)?Gt({type:"failed",payload:u.message}):(Gt({type:"issue:created",payload:u.value}),n(),er(o,t))}if(c==="issues:move"){if(!i.payload.position)return Fe(o,{type:"error",message:"Missing move position"});let u=await Mc({...i.payload,repoRoot:t});return st(o,t,n,"issues:move:result",u)}if(c==="issue:close"){if(!i.payload.issueId)return Fe(o,{type:"error",message:"Missing issueId"});let u=await Tc({repoRoot:t,issueId:i.payload.issueId});return st(o,t,n,"issue:close:result",u)}if(c==="issue:reopen"){if(!i.payload.issueId)return Fe(o,{type:"error",message:"Missing issueId"});let u=await wc({repoRoot:t,issueId:i.payload.issueId});return st(o,t,n,"issue:reopen:result",u)}return Fe(o,{type:"error",message:"Unknown message type"})}catch(i){return Fe(o,{type:"error",message:i instanceof Error?i.message:String(i)})}})})};var Wf=sn.dirname($f(import.meta.url)),Hf=process.env.IS_LOCAL==="true"?sn.resolve(process.cwd(),"dist/gui"):sn.join(Wf,"gui"),it=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},jf=async e=>new Promise((t,n)=>{let r="";e.on("data",o=>{r+=o}),e.on("end",()=>{try{t(r?JSON.parse(r):{})}catch{n(new Error("Invalid JSON body"))}}),e.on("error",n)}),Vf=e=>e.endsWith(".html")?"text/html; charset=utf-8":e.endsWith(".js")?"text/javascript; charset=utf-8":e.endsWith(".css")?"text/css; charset=utf-8":e.endsWith(".json")?"application/json; charset=utf-8":e.endsWith(".ico")?"image/x-icon":"application/octet-stream",_c=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=sn.resolve(Hf),o=sn.resolve(r,n),s=sn.relative(r,o);if(s.startsWith("..")||sn.isAbsolute(s))return it(t,403,{isError:!0,message:"Forbidden"});try{let i=await Of(o);return t.writeHead(200,{"content-type":Vf(o)}),t.end(i)}catch{return it(t,404,{isError:!0,message:`Not found: ${n}`})}},Gf=async(e,t=3710)=>new Promise((n,r)=>{let o=s=>{let i=u=>{if(e.off("listening",c),u.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(u)},c=()=>{e.off("error",i);let u=e.address();if(!u||typeof u=="string"){r(new Error("Unable to resolve address"));return}n(u.port)};e.once("error",i),e.once("listening",c),e.listen(s,"127.0.0.1")};o(t)}),$c=async e=>{let t=_f.createServer(async(o,s)=>{let i=new URL(o.url??"/","http://127.0.0.1");if(i.pathname==="/api/state")return it(s,200,await Ut({repoRoot:e.repoRoot}));if(o.method==="POST"&&i.pathname==="/api/comments")try{let c=await jf(o);if(!c.issueId||!c.body?.trim())return it(s,400,{isError:!0,message:"Missing issueId or body"});let u=await Co({repoRoot:e.repoRoot,issueId:c.issueId,body:c.body});return"isError"in u&&u.isError?it(s,400,u):it(s,200,await Ut({repoRoot:e.repoRoot}))}catch(c){return it(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add comment"})}if(o.method==="DELETE"&&i.pathname.startsWith("/api/comments/")){let c=decodeURIComponent(i.pathname.replace("/api/comments/",""));if(!c)return it(s,400,{isError:!0,message:"Missing comment id"});let u=await So({repoRoot:e.repoRoot,commentId:c});return"isError"in u&&u.isError?it(s,400,u):it(s,200,await Ut({repoRoot:e.repoRoot}))}return i.pathname.startsWith("/board/")?_c("/",s):_c(i.pathname,s)});try{await Gf(t)}catch(o){return a(o instanceof Error?`Unable to start GUI server: ${o.message}`:`Unable to start GUI server: ${String(o)}`)}let n=Uc({repoRoot:e.repoRoot});Oc(t,e.repoRoot,{onStateChanged:()=>n.scheduleSync()}),t.on("close",n.dispose);let r=t.address();return!r||typeof r=="string"?(t.close(),a("Unable to resolve GUI server address")):l("Started GUI server",{url:`http://epiq.localhost:${r.port}${e.boardId?`/board/${e.boardId}`:""}`,server:t})};var Wc=async e=>{let t=await $c({...e,boardId:""});if(d(t))return t;let{url:n}=t.value;return console.log(`Epiq GUI running at ${zf.cyan(n)}`),li(n),l("Started GUI",{url:n})};import{Box as Ht}from"ink";import ee from"react";import{Box as qs,Text as tr}from"ink";import Ve,{useEffect as Kf,useMemo as qf}from"react";import{ulid as Yf}from"ulid";var Hc=({text:e,match:t,color:n,highlightColor:r=y.secondary,dimColor:o=!1})=>{if(!t)return Ve.createElement(tr,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),c=s.indexOf(i);return c===-1?Ve.createElement(tr,{color:n,dimColor:o},e):Ve.createElement(tr,{color:n,dimColor:o},e.slice(0,c),Ve.createElement(tr,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},jc=Yf(),Xf=e=>`${e}`,Jf=e=>{let{pendingNavTarget:t}=kt();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(le(x.NONE,{breadCrumb:n,contextNode:r,readOnly:f().readOnly,selectedNode:o}));return[...new Set(Object.values(x))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==x.PALETTE).map(i=>{let c=Xr(i),u=go.find(m=>m.intent===c);return{command:i,description:u?.description??`[${i}] Run command`,isAvailable:s.has(i)}}).filter(i=>i.command.toLowerCase().startsWith(e)||e.length>=2&&i.description.toLowerCase().includes(e)).sort((i,c)=>i.isAvailable!==c.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(c.command))},Qf=e=>Q.text({id:jc,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),Zf=(e,t,n)=>Q.text({id:Xf(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Ys=[],eg=e=>{Vc();let t=b.createNode(Qf(f().rootNodeId));d(t)||!St(t.value)||(Ys=[t.value,...e.map((n,r)=>Zf(n,r,jc)).map(b.createNode).filter(te).map(({value:n})=>n).filter(St)],M.navigate({contextNode:t.value,selectedIndex:0}))},Vc=()=>{let e=Ys.map(t=>t.id);Ys=[];for(let t of e)b.deleteNode(t)};function Gc({width:e,height:t}){let r=id().value.trim().toLowerCase(),o=qf(()=>Jf(r),[r]);Kf(()=>(eg(o),()=>{Vc()}),[o]);let s=f().selectedIndex;return Ve.createElement(qs,{flexDirection:"column",width:e,height:t-2},Ve.createElement(nt,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,c)=>{let u=c===s,m=i.isAvailable?y.accent:y.secondary2,p=i.isAvailable?"":"[unavailable] ";return Ve.createElement(qs,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Ve.createElement(tr,{color:m,dimColor:!i.isAvailable},u?"\u276F ":" ",Ve.createElement(Hc,{text:Hi(i.command),match:r,color:m,dimColor:!i.isAvailable})),Ve.createElement(qs,{paddingLeft:2},Ve.createElement(Hc,{text:p+i.description,match:r.length>=2?r:"",color:u&&i.isAvailable?y.primary:y.secondary2,dimColor:!i.isAvailable})))})))}import{Box as yg}from"ink";import Ro from"react";import rr from"chalk";import{Box as Xs,Text as zc}from"ink";import nr,{useEffect as tg,useMemo as ng,useState as rg}from"react";var Kc=rr.hex(y.secondary),og=rr.inverse,sg=rr.inverse.hex(y.secondary2),ig={hint:"",hints:[],overlap:0,remainder:""},Yc=({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}},ag=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=ie(t);return{bg:r=>rr.bgHex(n).black(r),bgCursor:r=>rr.bgHex(n).inverse.black(r)}}return as(t)},dg=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Yc({value:e,command:t});if(!r)return null;let s=e.slice(r.end).match(/^\s*/)?.[0].length??0,i=r.end+s;return e.slice(i,i+n.length)!==n?null:{start:i,end:i+n.length}},qc=()=>({value:he.value,cursorPosition:he.cursorPosition,commandIsPending:he.commandIsPending,autoCompletion:he.commandMeta.autoCompletion??ig,infoMessage:he.commandMeta.infoMessage,validationStatus:he.commandMeta.validity,command:he.commandMeta.command,inputString:he.commandMeta.inputString,modifier:he.commandMeta.modifier}),cg=(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,Xc=({width:e,mode:t})=>{let[n,r]=rg(qc());tg(()=>{let I=()=>{let N=qc();r(T=>cg(T,N)?T:N)},E=Es(I);return I(),()=>{E()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:c,autoCompletion:u,command:m,modifier:p}=n,v=ng(()=>{let I=Math.max(0,Math.min(s,o.length)),E=Yc({value:o,command:m}),N=dg({value:o,command:m,modifier:p}),T=m?as(m):null,k=ag({command:m,modifier:p}),O=(de,X)=>{let ct=E&&X>=E.start&&X<E.end,ze=N&&X>=N.start&&X<N.end;return ct&&T?T.fg(de):ze&&k?k.bg(de):de},V=(de,X)=>{let ct=E&&X>=E.start&&X<E.end,ze=N&&X>=N.start&&X<N.end;return ct&&T?T.fgCursor(de):ze&&k?k.bgCursor(de):og(de)},R=o.slice(0,I),A=o[I]??" ",G=I<o.length?o.slice(I+1):"",Re=Array.from(R).map((de,X)=>O(de,X)).join(""),Ae=V(A,I),Ge=Array.from(G).map((de,X)=>O(de,I+1+X)).join("");if(u.hint){let de=u.hint[u.overlap]??A;Ae=sg(de),Ge=Kc(u.remainder.slice(1)+G)}return Kc(t===g.PALETTE?"?":":")+Re+Ae+Ge},[o,s,u,m,p]);return nr.createElement(Xs,{flexDirection:"column",justifyContent:"flex-start"},nr.createElement(Xs,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},nr.createElement(Xs,null,nr.createElement(zc,null,v),i&&nr.createElement(zc,{wrap:"truncate",color:c?y.red:y.secondary2},` ${i} `))))};import{Box as lg,Text as ug}from"ink";import Jc from"react";var mg=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?" | ":"").length+o.length;if(r+i>t-4)break;n.push(o),r+=i}return n},Qc=({width:e,availableHints:t})=>{let n=mg(t,e).join(" | ");return Jc.createElement(lg,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1},Jc.createElement(ug,{color:y.secondary2},n.length?n:"\xA0"))};import{Box as pg,Text as Eo}from"ink";import or,{useEffect as fg,useRef as En,useState as gg}from"react";var vg=40,No=.3,Js="\u2500",Zc=1,el=16,tl=({width:e})=>{let{replay:t}=$(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*Zc,[c,u]=gg(0),m=En(r);m.current=r;let p=En(0),v=En(0),I=En(0),E=En(0),N=En(0);if(fg(()=>{if(!n){p.current=0,I.current=0,E.current=0,N.current=0,u(0);return}p.current=m.current,v.current=Date.now(),I.current=m.current;let R=setInterval(()=>{let A=Date.now(),G=m.current;if(G!==I.current){let X=G-I.current,ct=A-v.current;if(X<0)E.current=0,N.current=0;else if(X>0&&ct>0){let ze=X/ct;E.current=E.current===0?ze:E.current*(1-No)+ze*No,N.current=N.current===0?X:N.current*(1-No)+X*No}p.current=G,v.current=A,I.current=G}let Re=A-v.current,Ae=Math.min(N.current,E.current*Re),Ge=Math.min(1,p.current+Ae),de=Math.round(Ge*i);u(X=>X===de?X:de)},vg);return()=>clearInterval(R)},[n,i]),!t)return null;let T=R=>{let A=s>1?R/(s-1):0,G=Math.round(A*(el-1))/(el-1);return Rr(G)},k=Math.min(s,Math.floor(c/Zc)),O=[];for(let R=0;R<k;R++){let A=T(R),G=O[O.length-1];G&&G.color===A?G.text+=Js:O.push({text:Js,color:A})}let V=Js.repeat(Math.max(0,s-k));return or.createElement(pg,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1,columnGap:1},or.createElement(Eo,{color:y.secondary2},"\u25B6"),or.createElement(Eo,null,O.map((R,A)=>or.createElement(Eo,{key:A,color:R.color},R.text)),or.createElement(Eo,{color:y.secondary,dimColor:!0},V)))};var sr=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=$(),o=t===g.COMMAND_LINE||t===g.PALETTE;return Ro.createElement(yg,null,o?Ro.createElement(Xc,{width:e,mode:t}):r==="replay"?Ro.createElement(tl,{width:e}):Ro.createElement(Qc,{width:e,mode:t,availableHints:n}))};import{Box as Ot,Text as Nn}from"ink";import Se,{useEffect as hg,useMemo as xg}from"react";import{ulid as nl}from"ulid";var To=nl(),Ig=()=>[...new Set([...f().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})),bg=e=>Q.text({id:To,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),Cg=(e,t,n)=>Q.text({id:nl(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),Ao=[],rl=()=>{let e=Ao.filter(n=>n.id!==To).map(n=>n.id),t=Ao.filter(n=>n.id===To).map(n=>n.id);Ao=[];for(let n of[...e,...t])b.deleteNode(n)},Sg=e=>{rl();let t=b.createNode(bg(f().rootNodeId));if(d(t)||!St(t.value))return logger.error("Could not attach help nodes");Ao=[t.value,...e.map((n,r)=>Cg(n,r,To)).map(b.createNode).filter(te).map(({value:n})=>n).filter(St)],M.navigate({contextNode:t.value,selectedIndex:0})},ol=({width:e,height:t})=>{let n=xg(()=>Ig(),[]);hg(()=>(Sg(n),()=>{rl()}),[n]);let r=f().selectedIndex;return Se.createElement(Ot,{flexDirection:"column",marginTop:3,borderColor:y.secondary,borderStyle:"round",width:e,height:t-2},Se.createElement(Ot,{paddingX:1,justifyContent:"center"},Se.createElement(Nn,{color:y.accent},"Help"),Se.createElement(Nn,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),Se.createElement(Ot,{paddingX:1,marginTop:1},Se.createElement(Ot,{width:20,justifyContent:"flex-end"},Se.createElement(Nn,{color:y.secondary},"Key(s)")),Se.createElement(Ot,{flexGrow:1,width:40,paddingLeft:2},Se.createElement(Nn,{color:y.secondary},"Action"))),Se.createElement(nt,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let c=i===r;return Se.createElement(Ot,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},Se.createElement(Ot,{width:20,justifyContent:"flex-end"},Se.createElement(Nn,{color:y.accent},o)),Se.createElement(Ot,{flexGrow:1,width:40,paddingLeft:2},Se.createElement(Nn,{color:c?y.primary:y.secondary2},s)))})))};import Eg from"chalk";import{Box as wo,Text as It}from"ink";import Be from"react";var sl=({width:e,height:t})=>Be.createElement(wo,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},Be.createElement(It,{color:y.accent,bold:!0},"Initialize project"),Be.createElement(It,null,`This folder is not an ${Eg.hex(y.accent)("epiq")} project yet.`),Be.createElement(It,{color:y.primary},"To start tracking issues here, we need to initialize a new",Be.createElement(It,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json "),"file in this repository."),Be.createElement(wo,{marginTop:1,flexDirection:"column"},Be.createElement(wo,null,Be.createElement(It,{color:y.accent}," "),Be.createElement(It,{color:y.primary},"Type "),Be.createElement(It,{backgroundColor:y.secondary}," :init "))),Be.createElement(wo,{marginTop:1},Be.createElement(It,{color:y.secondary2},"This will create, commit and push "),Be.createElement(It,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json ")));import{Box as Mo,Text as at}from"ink";import pe from"react";var Ng=({isDone:e,command:t,value:n})=>pe.createElement(Mo,null,pe.createElement(at,{color:y.accent,dimColor:e},e?" \u2714 ":" "),pe.createElement(at,{dimColor:e},"Type "),pe.createElement(at,{backgroundColor:y.secondary,dimColor:e}," "+t+" "),n!==void 0&&pe.createElement(pe.Fragment,null,pe.createElement(at,{dimColor:e}," "),pe.createElement(at,{color:y.secondary,dimColor:e},"<"+n+">"))),Rg=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function Qs({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:c}=Tt(),u=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:s,message:"Nice. Now pick your editor."},{key:"autosync",done:c,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=u.findIndex(v=>!v.done),p=m===-1?void 0:u[m];return pe.createElement(Mo,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},pe.createElement(at,{color:y.accent,bold:!0},"Welcome! \u{1F539}"),pe.createElement(at,null,"Let's get you started - it's a breeze."),pe.createElement(at,{color:y.secondary2},"Remember - you can always search available commands by typing:",pe.createElement(at,{color:y.accent}," ? ")),p&&pe.createElement(at,{color:y.secondary2},p.message),pe.createElement(Mo,{flexDirection:"column"},u.map((v,I)=>m===-1||I<=m?pe.createElement(Mo,{key:v.key,marginBottom:1},pe.createElement(Ng,{isDone:v.done,command:v.command,value:v.done?Rg(v.value):void 0})):null)))}import Fo from"chalk";import{Box as ar,Text as Rn}from"ink";import me from"react";import{Box as Po,Text as il}from"ink";import _t from"react";var Ag=e=>(b.getTag(e)?.name??"").length+3,Tg=e=>(b.getContributor(e)?.name??"").length+3,al=({width:e})=>{let{viewMode:t}=H(),n=$(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,c=i[o.id]?.[s],u=mt(c?.id??o.id,"TICKET"),m=te(u)?u.value:void 0,p=m?.props.tags??[],v=m?.props.assignees??[],I=m?.parentNodeId?!os(o.id,m.parentNodeId)&&t==="dense":!1,E=r.map((A,G)=>{let Re=G===r.length-1,Ae=z(A.id),Ge=Re?Ae?.[s]?.title:void 0;return`${G?" / ":""}${A.title??""}${Ge?` \u25B8 ${Ge}`:""}`}).join(""),N=m?b.getCommentsByIssue(m.id):[],T=N.length?String(N.length).length+11:0,k=I?p.reduce((A,G)=>A+Ag(G),0)+v.reduce((A,G)=>A+Tg(G),0)+T:0,O=Math.max(0,e-k),V=E.substring(0,O),R=I?[...p.map(A=>_t.createElement(Po,{key:`tag-${A}`,paddingLeft:1},_t.createElement(bn,{id:A}))),...v.map(A=>_t.createElement(Po,{key:`assignee-${A}`,paddingLeft:1},_t.createElement(Mt,{id:A}))),N.length?_t.createElement(Po,{key:"comments",paddingLeft:1},_t.createElement(il,{color:y.accent},"[",N.length," comment",N.length===1?"":"s","]")):null]:[];return _t.createElement(Po,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},_t.createElement(il,{color:y.secondary2},V),R)};import{Box as wg,Text as dl}from"ink";import Lo from"react";var Mg=({filters:e})=>Lo.createElement(wg,{columnGap:1},Lo.createElement(dl,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Lo.createElement(dl,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),cl=Lo.memo(Mg);import{Box as Pg,Text as ko}from"ink";import ir from"react";function ll(){let{eventLog:e,unappliedEvents:t}=$(),n=e.at(-1)?.id,r=Pr(n??""),o=te(r)?Mr(r.value):"INVALID DATE";return ir.createElement(Pg,{paddingLeft:1},ir.createElement(ko,{backgroundColor:y.accent,color:y.secondary}," Readonly "),ir.createElement(ko,{color:y.accent}," "+t.length+" edits ago at "+o+"."),ir.createElement(ko,{color:y.accent}," Resume with "),ir.createElement(ko,{backgroundColor:y.accent,color:y.secondary}," ",":peek now"," "))}import{Box as Lg,Text as Zs}from"ink";import Do from"react";function ul(){let{replay:e}=$();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return Do.createElement(Lg,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},Do.createElement(Zs,{backgroundColor:y.accent,color:y.secondary}," \u25B6 REPLAY "),Do.createElement(Zs,{color:y.secondary2},Mr(new Date(r))),Do.createElement(Zs,{color:y.accent},`${t}/${n} edits`))}import ei from"chalk";import{Box as kg,Text as ml}from"ink";import ti,{useEffect as Dg,useState as Fg}from"react";var Bg=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Ug=150,pl=12,Og=.36,fl=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)}},_g=({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)}`},$g=(e,t,n)=>{let r=fl(e),o=fl(t);return _g({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Wg=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,s=e[r],i=e[Math.min(r+1,e.length-1)];return $g(s,i,o)};function gl({syncStatus:e,autoSync:t}){let[n,r]=Fg(0);Dg(()=>{if(e.status!=="syncing"){r(0);return}let c=0,u=setInterval(()=>{c+=1;let m=(Math.sin(c*Og)+1)/2,p=Math.round(m*(pl-1));r(v=>v===p?v:p)},Ug);return()=>clearInterval(u)},[e.status]);let o={synced:" ",failed:"---",syncing:"...",pending:"idle"},i={synced:y.secondary2,failed:y.yellow,pending:y.secondary2,syncing:Wg(Bg,n/(pl-1))??""}[e.status];return ti.createElement(kg,null,ti.createElement(ml,null,ei.hex(y.secondary2).dim(t?"Sync (auto): ":"Sync: ")),ti.createElement(ml,null,ei.hex(i)("\u25CF")+ei.hex(y.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import Il from"chalk";import{Text as bl}from"ink";import Cl,{useEffect as Gg,useState as zg}from"react";var $t="1.1.0";import ni from"chalk";var Hg="https://registry.npmjs.org/epiq/latest",ri=null,vl=0,jg=1e3*60*60*24,yl=e=>e.replace(/^v/,""),Vg=(e,t)=>{let n=yl(e).split(".").map(Number),r=yl(t).split(".").map(Number);for(let o=0;o<Math.max(n.length,r.length);o++){let s=n[o]??0,i=r[o]??0;if(s>i)return 1;if(s<i)return-1}return 0},hl=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(ri&&Date.now()-vl<jg)return ri;try{let t=await fetch(Hg);if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.status}`);let r=(await t.json()).version??null,o={current:e,latest:r,updateAvailable:r?Vg(r,e)>0:!1};return ri=o,vl=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},xl=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?ni.hex(y.accent).dim(s):ni.hex(y.secondary).dim(s)).join(ni.hex(y.secondary2).dim("."))};function Sl(){let[e,t]=zg({current:$t,latest:null,updateAvailable:!1});return Gg(()=>{let n=!0;return hl($t).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?Cl.createElement(bl,{dimColor:!0,color:y.secondary2},$t+" "):Cl.createElement(bl,null,Il.hex(y.secondary2).dim($t),Il.hex(y.accent).dim(" \u2197 "),xl($t,e.latest))}function dr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=$(),{userName:i,preferredEditor:c,autoSync:u}=H(),m=64,p=process.stdout.columns-m-8,v=t||n==="replay",I=s?un(s.currentLabel,Math.max(0,p)):"";return me.createElement(ar,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?me.createElement(ar,{paddingLeft:1},me.createElement(Rn,{color:y.secondary2},I)):v?me.createElement(Rn,null," "):o===g.PALETTE?me.createElement(ar,null,me.createElement(Rn,{color:y.accent},"Command Palette"),me.createElement(Rn,{dimColor:!0,color:y.secondary2}," ","- search, select and press enter")):me.createElement(ar,{paddingLeft:1},e.length>0?me.createElement(cl,{filters:e}):me.createElement(al,{width:p})),n==="live"?me.createElement(ar,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},me.createElement(gl,{autoSync:!!u,syncStatus:r}),me.createElement(Rn,null,Fo.hex(y.secondary2).dim("Mode: ")+Fo.hex(y.secondary2).dim(o.padEnd(8," "))," "),me.createElement(El,{icon:"@",value:i}),me.createElement(El,{icon:"\u276F",value:c}),me.createElement(Sl,null)):"",n==="peek"?me.createElement(ll,null):"",n==="replay"?me.createElement(ul,null):"")}function El({icon:e,value:t}){return me.createElement(Rn,null,Fo.dim(e)+Fo.hex(y.accent)(` ${t??"-"} `))}import{Box as Kg,Text as qg}from"ink";import cr from"react";import{Box as Bo,Text as oi}from"ink";import Wt from"react";function si(){let e=$(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?W(t?.id):[];return Wt.createElement(Bo,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:y.secondary,width:s},Wt.createElement(Bo,{padding:1,paddingTop:0,paddingBottom:0},Wt.createElement(oi,null,"Select a board:")),Wt.createElement(Bo,{padding:1,flexDirection:"column"},i.map((c,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,v=W(c.id).flatMap(({id:I})=>z(I)).length;return Wt.createElement(Bo,{key:c.id??u},Wt.createElement(oi,{color:m?y.accent:y.secondary2},Wt.createElement(Ce,{isSelected:m})),Wt.createElement(oi,{color:m?y.accent:y.secondary2},c.title," (",v," issues)",c.readonly?" \u{1F512}":""))})))}var Yg=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:c}=$(),u=n.find(({context:I})=>I==="BOARD"),v=s-1-3;return cr.createElement(Kg,{flexDirection:"row"},e.context==="WORKSPACE"?cr.createElement(si,null):u?cr.createElement(oo,{height:v,width:i,swimlanes:(c[u.id]??[]).filter(I=>I!==void 0&&Et(I)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):cr.createElement(qg,null))},Nl=cr.memo(Yg);import{useEffect as Xg}from"react";var Jg=e=>{Xg(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=H();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:c,mode:u}=f();u==="default"&&!c&&$r(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},Rl=({autoSync:e})=>(Jg(e),null);function ii({width:e,height:t}){let n=$(),{autoSync:r,viewMode:o}=qi(),s=n.filters;if(n.mode===g.HELP)return ee.createElement(Ht,{flexDirection:"column"},ee.createElement(ol,{width:e,height:t}));if(n.mode===g.PALETTE)return ee.createElement(Ht,{flexDirection:"column"},ee.createElement(dr,{filters:s}),ee.createElement(Gc,{width:e,height:t-2}),ee.createElement(sr,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Tt(),c=!i,u=i&&!n.hasProjectDefinition;if(c)return ee.createElement(Ht,{flexDirection:"column"},ee.createElement(Ht,{flexDirection:"column"},ee.createElement(dr,{hideBreadCrumb:!0,filters:s}),ee.createElement(Qs,{height:t,width:e})),ee.createElement(sr,{width:e,mode:n.mode,availableHints:n.availableHints}));if(u)return ee.createElement(Ht,{flexDirection:"column"},ee.createElement(Ht,{flexDirection:"column"},ee.createElement(dr,{hideBreadCrumb:!0,filters:s}),ee.createElement(sl,{height:t,width:e})),ee.createElement(sr,{width:e,mode:n.mode,availableHints:n.availableHints}));let m=be(n.breadCrumb??[],"BOARD");if(te(m)){let p=m.value.id,v=W(p).length,I=3,E=Math.floor(e/I),N=Math.floor(e/Math.max(v,1));e=Math.min(N,E)*Math.max(v,I)}return ee.createElement(Ht,{flexDirection:"column"},ee.createElement(Rl,{autoSync:r}),ee.createElement(Ht,{flexDirection:"column"},ee.createElement(dr,{filters:s}),ee.createElement(Nl,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),ee.createElement(sr,{width:e,mode:n.mode,availableHints:n.availableHints}))}import Qg from"readline";var Uo,Oo,dt,Zg=new Set([h.MoveCursorLeft,h.EraseInputWord,h.MoveCursorLeftOfWord,h.MoveCursorRight,h.MoveCursorRightOfWord,h.NavToPreviousContainer,h.NavToNextContainer,h.NavPreviousItem,h.NavNextItem,h.SetViewDense,h.SetViewWide,h.Confirm,h.Exit,h.InitCommandLine,h.InitCommandPalette,h.ExitCommandLine,h.CaptureInput,h.EraseInput,h.EraseInputWord,h.HideHelp,h.ViewHelp,h.SetViewDense,h.SetViewWide,h.GetLastCommandFromHistory,h.GetNextCommandFromHistory,h.AutoCompleteCommand]),ev=new Set([h.NavPreviousItem,h.NavNextItem,h.NavToPreviousContainer,h.NavToNextContainer,h.Confirm,h.Exit,h.InitCommandPalette,h.InitMove,h.MoveNextItem,h.MovePreviousItem,h.MoveToNextContainer,h.MoveToPreviousContainer,h.Delete,h.AddItem,h.EditTitle,h.EditDescription,h.ConfirmMove,h.Edit,h.ViewHelp]),Al=async e=>{if(e.ctrl&&e.name==="c")return M.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=f(),s=dd(e,n);if(!s||r&&!Zg.has(s)||o==="replay"&&n===g.DEFAULT&&ev.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(c){logger.error(c)}},tv=()=>async function(t,n){n.name!=="escape"&&(dt&&(clearTimeout(dt),dt=void 0),await Al(n))},nv=()=>async function(t){if(t.length===1&&t[0]===27){dt&&clearTimeout(dt),dt=setTimeout(()=>{Al({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),dt=void 0},25);return}dt&&(clearTimeout(dt),dt=void 0)};function Tl(){Uo&&process.stdin.removeListener("keypress",Uo),Oo&&process.stdin.removeListener("data",Oo),Uo=tv(),Oo=nv(),Qg.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Oo),process.stdin.on("keypress",Uo)}async function wl(){try{let e=Jn();te(e)&&_e(e.value);let t=Ke(process.cwd()),n=[];if(te(t)){let s=Te({repoRoot:t.value});if(d(s))return Jt(3,s.message);let i=an(),c=await Vt({repoRoot:t.value,stateBranchRoot:s.value,stateBranchName:i.stateBranch});if(d(c))return Jt(3,c.message);let u=await U({cwd:s.value,args:["pull","--ff-only"]});d(u)&&logger.info(3,u.message);let m=pt(s.value);if(d(m))return Jt(3,m.message);n=m.value}let r=Xt(n);if(d(r))return Jt(4,r.message);C({hasProjectDefinition:te(t),hasInitializingEvents:!!n.length});let o=ai();return d(o)?Jt(6,o.message):(Tl(),l("Booted Epiq",void 0))}catch(e){return Jt(0,Ur(e))}}Ud();var iv=`${jt.bold("Epiq CLI")}
56
+ `,$s.writeFileSync(t,n,"utf8"),re.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)};var mf=async e=>{let t=await U({cwd:e,args:["status","--porcelain"]});return d(t)?t:l("Checked git diff",t.value.stdout.trim().length>0)},Y=(e,t)=>a(`[${e}] ${t}`),Gd=async()=>{_("");let e=dn(),t=await Ye(process.cwd());if(d(t))return Y(1,t.message);let n=t.value,r=await yr(n);if(d(r))return Y(2,r.message);if(r.value)return Y(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await mf(n);if(d(o))return Y(2.5,o.message);if(o.value)return Y(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(Vo(n))return Y(4,"Epiq project already initialized");let s=wt();if(!s.isSetupDone||!s.userName)return Y(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let i=H(),c=i.userName,u=i.userId;if(!u||!c)return Y(5,"Missing Epiq user id");let m=e.stateBranch,p=await xr({repoRoot:n,branch:m});if(d(p))return Y(6,p.message);if(p.value)return Y(6,`State branch already exists: ${m}`);let v=await ns({repoRoot:n,stateBranchName:m});if(d(v))return Y(6,v.message);let I=Cr();if(d(I))return Y(7,I.message);let S=Vd.join(br(),e.projectId),N=await Gt({repoRoot:n,stateBranchRoot:S,stateBranchName:m});if(d(N))return Y(8,N.message);let T=Vd.join(S,".epiq");uf.mkdirSync(T,{recursive:!0});let k=wa({userId:u,userName:c});if(d(k))return Y(9,k.message);for(let Ho of k.value){let ui=Fr({event:Ho,rootDir:S});if(d(ui))return Y(9,ui.message)}let O=await Er({stateBranchRoot:S,eventFileName:Yt({userId:u,userName:c})});if(d(O))return Y(10,O.message);let V=await ln({cwd:S,message:"[epiq:init]"});if(d(V))return Y(10,V.message);let R=await jd(n);if(d(R))return Y(11,R.message);let A=vi({repoRoot:n,fileContents:e});if(d(A))return Y(12,A.message);let G=await oe.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d(G))return Y(13,G.message);let Re=await oe.commit({cwd:n,message:"[epiq:init-project]"});if(d(Re))return Y(13,Re.message);let Ae="Project initialized!",Ge=await U({cwd:n,args:["push","-u","origin","HEAD"]});d(Ge)&&(Ae+=` Warn: [init:14] ${Ge.message}`);let de=await Fn({repoRoot:n,stateBranchRoot:S});d(de)&&(Ae+=` Warn: [init:15] ${de.message}`);let lt=Tt(k.value).filter(d);if(lt.length>0)return Y(16,lt.map(Ho=>Ho.message).join(`
57
+ `));let ze=We();if(d(ze))return Y(16,ze.message);let{rootNodeId:Dl,nodes:Fl}=ze.value,li=Fl[Dl];return li?(M.navigate({contextNode:li,selectedIndex:0}),C({hasProjectDefinition:!0,mode:g.DEFAULT}),l(Ae,null)):Y(16,"Unable to resolve initialized root node")};import{ulid as ff}from"ulid";import{ulid as pf}from"ulid";var zd=null,Bt=()=>structuredClone(zd),Zn=e=>{zd=e},Kd=()=>{let{contextNode:e,selectedIndex:t}=f(),r=z(e.id)[t];return r?l("Resolved selected child",r):a("Target node not found")},Ws=({id:e,parentId:t,position:n={at:"end"}})=>{let r=z(t).filter(o=>o.id!==e);return Br(r,n)},qd=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Z();if(d(r))return a("Unable to resolve user ID");let o=Ws({parentId:t,id:e,position:n});return d(o)?o:l("Created pending move state",{id:pf(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Yd=e=>{Zn(e);let t=At(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function Hs(e){let t=Kd();if(d(t))return t;let{contextNode:n,nodes:r}=f();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=z(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let c=s[i+e];if(!c)return a("Missing sibling node");let u=qd({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:Yd(u.value)}function js(e){let t=Kd();if(d(t))return t;let{contextNode:n,selectedIndex:r}=f(),s=z(n.id)[r+e];if(!s)return a("Missing sibling node");let i=qd({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:Yd(i.value)}var Xd=()=>{let e=Bt();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=f().nodes[n];if(!r)return a("Move parent not found");let o=z(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(M.navigate({contextNode:r,selectedIndex:o}),l("Synchronized navigation to moved node",null))},lo=(e,t="Moved preview")=>{if(d(e))return e;let n=Xd();return d(n)?n:(C({mode:g.MOVE}),l(t,null))},Jd=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=q().commandMeta,{contextNode:n,selectedIndex:r}=f(),o=z(n.id)[r];if(!o)return C({mode:g.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 s=z(o.parentNodeId),i=s.findIndex(({id:v})=>v===o.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],u=s[i+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=Ws({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(Zn({id:ff(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),C({mode:g.MOVE}),l("Move initialized",null))}if(t==="next")return lo(js(1));if(t==="previous")return lo(js(-1));if(t==="to-next")return lo(Hs(1));if(t==="to-previous")return lo(Hs(-1));if(t==="confirm"){let s=Bt();if(!s)return a("No pending move to confirm");let i=await qe();if(d(i))return i;let c=B([s],i.value);if(d(c))return c;let u=Xd();return d(u)?u:(Zn(null),C({mode:g.DEFAULT}),l("Moved item",null))}return t==="cancel"?(Zn(null),C({mode:g.DEFAULT}),l("Cancelling move",null)):a("Invalid move modifier")};import{ulid as mo}from"ulid";import{monotonicFactory as gf,ulid as vf}from"ulid";var yf=gf(),uo=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=yf();return l("Created issue events",[{id:vf(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var Qd=async(e,t)=>{let n=Z();if(d(n))return a("Unable to resolve user ID");let r=await qe();if(d(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=f(),u=m=>{let p=B([m],o);if(d(p))return p;let v=b.getNode(p.value[0].result.id);if(!v)return a("Created node not found");if(!v.parentNodeId)return p;let I=b.getNode(v.parentNodeId);return I?(M.navigate({contextNode:I,selectedIndex:b.getSiblings(v.parentNodeId).findIndex(({id:S})=>S===v.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=f(),p=b.getNode(m);if(!p)return a("Workspace not found");let v=yn(p.id,n.value,o);return d(v)?v:u({id:mo(),action:"add.board",payload:{id:mo(),name:t.inputString,parent:p.id,rank:v.value},...n.value})}if(t.modifier==="swimlane"){let m=be(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=yn(m.value.id,n.value,o);return d(p)?p:u({id:mo(),action:"add.swimlane",payload:{id:mo(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=W(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let V=be(s,"SWIMLANE");return d(V)?null:V.value})();if(!p)return a("Unable to add issue in this context");let v=yn(p.id,n.value,o);if(d(v))return v;let I=uo({name:t.inputString,parent:p.id,rank:v.value,user:n.value});if(d(I))return I;let S=I.value,N=B([...S],o);if(d(N))return N;if(!N.value[0])return a("Issue creation failed");let O=S.find(V=>V.action==="add.issue")?.payload.id;return O?(M.navigate({contextNode:p,selectedIndex:b.getSiblings(p.id).findIndex(({id:V})=>V===O)}),l("Issue created",null)):a("Unable to determine ticket id")}return l("Success",null)};var po=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=f(),s=ma(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=Ut();if(d(u))return u;let p=Tt(i).filter(d);if(p.length>0)return Ut(),C(o),a(p.map(I=>I.message).join(", "));let v=f().nodes[e];return v?(M.navigate({contextNode:v,selectedIndex:r}),l("",{unappliedEvents:c})):(Ut(),C(o),a("Board did not exist at that date"))};var hf=20,xf=16,If=150,fo=null,go=null;var on=()=>{fo!==null&&(clearInterval(fo),fo=null),go!==null&&(clearTimeout(go),go=null)},Zd=()=>{on(),C({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},bf=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)},ec=({events:e,startTime:t,durationMs:n})=>{on();let r=e.length,o=e.map(v=>vn(v)??t),s=o[r-1]??Date.now(),i=bf(o),c=Math.max(1,Math.round(n*hf/1e3)),u=Math.max(Math.round(n/c),xf),m=0,p=0;C({mode:g.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),fo=setInterval(()=>{m++;let v=m/c,I=[],S;for(;p<r&&i[p]<=v;){let T=e[p],k=At(T);if(d(k)){Zd();return}I.push(...us(T)),S=T,p++}if(p>=r||m>=c){for(;p<r;p++){let k=At(e[p]);if(d(k))break}let T=f().replay;C({unappliedEvents:[],replay:T&&{...T,progress:1,appliedCount:r}}),on(),go=setTimeout(Zd,If);return}let N=f().replay;C({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,v),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:S?vn(S)??N?.currentTime??t:N?.currentTime??t,currentLabel:S?aa(S):N?.currentLabel??"",flashNodeIds:S?[...new Set(I)]:N?.flashNodeIds??[]}})},u)};var tc=async()=>{let e=be(f().breadCrumb,"BOARD");if(d(e))return e;let t=await Ye(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Te({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=q().commandMeta;if(on(),r==="now"){let c=ft(n.value);if(d(c))return a(c.message);let u=Ut();if(d(u))return u;let p=Tt(c.value).filter(d);return p.length>0?a(p.map(v=>v.message).join(", ")):(C({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),l("Peeking now",!0))}let s;if(r==="prev"){let c=f().eventLog.at(-1),u=vn(c);if(u===null)return a("No previous event to peek");s=u}else if(r==="next"){let c=f().unappliedEvents.at(0),u=vn(c);if(u===null)return a("No next event to peek");s=u+1}else{let c=Zt(r||o.trim());if(!c)return a("Invalid peek date");s=c.getTime()}let i=po({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(C({mode:g.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),l("Peeking",!0))};var nc=async()=>{let e=be(f().breadCrumb,"BOARD");if(d(e))return e;let t=await Ye(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Te({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=q().commandMeta,{dateInput:s,durationInput:i}=Gr(r,o);if(on(),f().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let c=Zt(s);if(!c)return a("Invalid replay date");let u=i?Vr(i):15e3;if(u===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=f(),v=po({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(d(v))return v;let{unappliedEvents:I}=v.value;return I.length===0?(Ut(),C(p),l("Nothing to replay from that point",!0)):(ec({events:I,startTime:m,durationMs:u}),l("Replaying board history",!0))};import Ef from"zod";var rc=()=>{let e=q().commandMeta.inputString,t=Ef.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=xt({autoSyncDebounceMs:t.data});return d(n)?n:(_e({autoSyncIntervalMs:t.data}),C({mode:g.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))};var oc=()=>{let e=q().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Ba(e),n=xt({autoSync:t});return d(n)?n:(_e({autoSync:t}),C({mode:g.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var sc=()=>{let e=q().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=xt({logLevel:e});return d(n)?n:(_e({logLevel:e}),C({mode:g.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var ic=async()=>{_(""),C({mode:g.DEFAULT});let e=We();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");C({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await _r();return d(t)?(C({syncStatus:{msg:t.message,status:"failed"}}),t):(C({mode:g.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var Sf=e=>e.action==="add.issue.comment",ac=e=>Object.values(f().tags).find(t=>t.name===e),dc=e=>Object.values(f().contributors).find(t=>t.name===e),It=async()=>{let e=await qe();return d(e)?e:l("Resolved persist root",e.value)},vo=[{systemOnly:!0,intent:L.Move,description:"Internal move-state command",mode:g.COMMAND_LINE,action:Jd},{intent:L.Delete,description:"Delete the currently selected node",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await It();if(d(o))return o;if(r.context==="COMMENT"){let s=r.id,i=w(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=f().nodes[i];if(!c||!w(c))return a("Unable to resolve comment issue");let u=c.log?.filter(Sf).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):B([{id:xe(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return B([{id:xe(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=q().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>le(x.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return fe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:g.DEFAULT})),l("Filter updated",null)}},{intent:L.ViewHelp,description:"Open the help screen",mode:g.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=f();return Ft({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),C({mode:g.HELP}),l("Viewing help",null)}},{intent:L.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!w(r))return a("Cannot close in this context");let o=f().nodes[ce];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await It();if(d(s))return s;let i=s.value,c=Xt(o.id,r.id,{at:"end"},e.value,i);if(d(c))return c;let u=B([{id:xe(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value}],i);return d(u)?u:l("Issue closed",null)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):pt(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let s=o.value,i=f().nodes[ce];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!w(s))return a("Target node is not issue");let c=ao(s);if(!c)return a("Unable to resolve previous parent from issue history");if(c===i.id)return a("Previous parent resolves to closed swimlane");let u=f().nodes[c];if(!u)return a("Previous parent no longer exists");let m=await It();if(d(m))return m;let p=m.value,v=Xt(u.id,s.id,{at:"end"},e.value,p);if(d(v))return v;let I=B([{id:xe(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:v.value},...e.value}],p);return d(I)?I:l("Issue reopened",null)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Init,description:"Initialize Epiq in the current git repository",mode:g.COMMAND_LINE,action:Gd},{intent:L.NewItem,description:"Create a new board, swimlane, or issue",mode:g.COMMAND_LINE,action:Qd,onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Rename,description:"itle] Rename the currently selected node",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=cd();if(!o)return a("Provide a title");let s=await It();return d(s)?s:B([{id:xe(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.UntagTicket,description:"Remove a tag from the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=ac(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=f();if(!s)return a("Invalid untag target");let i=pt(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let c=i.value;if(!w(c))return a("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let m=await It();return d(m)?m:B([{id:xe(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.TagTicket,description:"Add or create a tag on the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=f();if(!o)return a("Invalid tag target");let s=pt(o.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!w(i))return a("Target node is not issue");let c=await It();if(d(c))return c;let u=ac(r),m=u?.id??xe();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):B([...u?[]:[{id:xe(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:xe(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.AssignUserToTicket,description:"Assign a user to the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let{selectedIndex:o,contextNode:s}=f(),i=W(s.id)[o];if(!i)return a("Invalid assign target");let c=pt(i.id,"TICKET");if(d(c))return a("Unable to assign issue in this context");let u=c.value;if(!w(u))return a("Target node is not issue");let m=await It();if(d(m))return m;let p=dc(r),v=p?.id??xe();return(u.props.assignees??[]).includes(v)?a("Assignee already assigned"):B([...p?[]:[{id:xe(),action:"create.contributor",payload:{id:v,name:r},...e.value}],{id:xe(),action:"add.issue.assignee",payload:{id:u.id,assignee:v},...e.value}],m.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let o=dc(r);if(!o)return a(`Assignee "${r}" does not exist`);let{selectedNode:s}=f();if(!s)return a("Invalid unassign target");let i=pt(s.id,"TICKET");if(d(i))return a("Unable to unassign in this context");let c=i.value;if(!w(c))return a("Target node is not issue");if(!(c.props.assignees??[]).includes(o.id))return a(`Issue is not assigned to "${r}"`);let m=await It();return d(m)?m:B([{id:xe(),action:"remove.issue.assignee",payload:{id:c.id,assignee:o.id},...e.value}],m.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Comment,description:"Add a comment to the selected issue",mode:g.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return a("Provide a comment");if(n.length>In)return a(`Cannot exceed ${In} characters`);let r=Z();if(d(r))return a("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=f(),i=be([...o,s],"TICKET");if(d(i))return a("Edit target must be an issue");let c=i.value;if(!c)return a("Invalid comment target");let u=c.context==="TICKET"?l("Resolved ticket",c):pt(c.id,"TICKET");if(d(u))return a("Unable to comment on issue in this context");let m=u.value;if(!w(m))return a("Target node is not issue");let p=await It();return d(p)?p:B([{id:xe(),action:"add.issue.comment",payload:{id:xe(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Sync,description:"Pull, commit, and push Epiq state",mode:g.COMMAND_LINE,action:ic},{intent:L.Peek,description:"View board state at another point in time",mode:g.COMMAND_LINE,action:tc},{intent:L.Replay,description:"Replay board history forward from a point in time",mode:g.COMMAND_LINE,action:nc},{intent:L.Export,description:"Export the current board layout to markdown",mode:g.COMMAND_LINE,action:async()=>{let e=await Md();return d(e)?e:(C({mode:g.DEFAULT}),l("Export successful",!0))}},{intent:L.Exit,description:"Exit the application",mode:g.COMMAND_LINE,action:async()=>(M.exit(),l("Exit successful",!0))},{intent:L.Edit,description:"Edit title or description",mode:g.COMMAND_LINE,action:async(e,t)=>Hd(t),onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:g.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case ae.USERNAME:{let{userId:r,preferredEditor:o,userName:s}=H(),i=n||s,c=r??xe();if(!i||!c)return a("Unable to resolve user name or id");let u=xt({userName:i,userId:c,preferredEditor:o??""});return d(u)?u:(_e({userName:i,userId:c}),C({mode:g.DEFAULT}),l(`Username set to "${i}"`,null))}case ae.EDITOR:{if(!n)return a("No editor provided");let r=xt({preferredEditor:n});return d(r)?r:(_e({preferredEditor:n}),C({mode:g.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case ae.VIEW:return n!=="wide"&&n!=="dense"?a("Invalid view mode"):(_e({viewMode:n}),l(`View set to "${n}"`,null));case ae.AUTOSYNC:return oc();case ae.LOG_LEVEL:return sc();case ae.SYNC_DEBOUNCE_MS:return rc();default:return a("Unknown config command")}}},{intent:L.Coffee,description:"Sponsor the development of Epiq!",mode:g.COMMAND_LINE,action:()=>{let e=q().commandMeta.modifier;return e==="custom"?Os("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):Os(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),_(""),l("Thanks you!",null)}}];var Nf=new Set(["peek","replay","filter","view-help"]),st=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=q();if(!t)return a("No command to confirm");if(!e&&n===Mt.Invalid)return a("Invalid command");let s=Jr(t);od();let{readOnly:i}=f();if(i&&!Nf.has(s))return zn({status:Ct.Fail,message:"Command not available in readonly state",value:null});let c=vo.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return zn({status:Ct.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return zn({status:Ct.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?zn(u):(sd({addToHistory:!e}),c.onSuccess?.(),H().autoSync&&Wr(),u)};var yo=[{intent:h.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(C({mode:g.COMMAND_LINE}),_("move cancel"),st({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:g.DEFAULT,description:"[m] move (init/confirm)",action:()=>(C({mode:g.COMMAND_LINE}),_("move start"),st({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:g.MOVE,action:()=>(C({mode:g.COMMAND_LINE}),_("move confirm"),st({isForceExecutedBySystem:!0}))}],ho=[{intent:h.MovePreviousItem,mode:g.MOVE,action:()=>Bt()?(C({mode:g.COMMAND_LINE}),_("move previous"),st({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveNextItem,mode:g.MOVE,action:()=>Bt()?(C({mode:g.COMMAND_LINE}),_("move next"),st({isForceExecutedBySystem:!0})):a("No pending move")}],cc=[{intent:h.MoveToNextContainer,mode:g.MOVE,action:()=>Bt()?(C({mode:g.COMMAND_LINE}),_("move to-next"),st({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveToPreviousContainer,mode:g.MOVE,action:()=>Bt()?(C({mode:g.COMMAND_LINE}),_("move to-previous"),st({isForceExecutedBySystem:!0})):a("No pending move")}];var lc={[P.WORKSPACE]:[...yo,...ho],[P.BOARD]:[...yo,...ho],[P.SWIMLANE]:[...yo,...ho,...cc],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[],[P.COMMENT]:[]};var uc=()=>{_("");let{pendingNavTarget:e}=Dt();C({mode:g.DEFAULT}),e&&M.navigate(e),Ft({pendingNavTarget:void 0})},mc=[{intent:h.ExitCommandLine,mode:g.HELP,action:()=>(uc(),l("Exiting help",null))},{intent:h.Exit,mode:g.HELP,action:()=>(uc(),l("Closed help",null))},{intent:h.NavPreviousItem,mode:g.HELP,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:h.NavNextItem,mode:g.HELP,action:()=>(M.navigateToNextItem(),l("Navigating to next help item",null))},{intent:h.NavToPreviousContainer,mode:g.HELP,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:h.NavToNextContainer,mode:g.HELP,action:()=>(M.navigateToNextContainer(),l("Navigating to next help container",null))}];var Rf=e=>{C({mode:g.COMMAND_LINE});let{pendingNavTarget:t}=Dt();t&&M.navigate(t),Ft({pendingNavTarget:void 0}),_(`${e} `)},pc=()=>{_("");let{pendingNavTarget:e}=Dt();e&&M.navigate(e),Ft({pendingNavTarget:void 0}),C({mode:g.DEFAULT})},fc=[{intent:h.InitCommandPalette,mode:g.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{_("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=f();return Ft({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),C({mode:g.PALETTE}),l("Opening command palette",null)}},{intent:h.Confirm,mode:g.PALETTE,action:()=>{let{selectedNode:e}=f();if(!e||!St(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?(Rf(t),l("Selected command",t)):l("No command selected",null)}},{intent:h.ExitCommandLine,mode:g.PALETTE,action:()=>(pc(),l("Exiting palette",null))},{intent:h.Exit,mode:g.PALETTE,action:()=>(pc(),l("Closed command palette",null))},{intent:h.NavPreviousItem,mode:g.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:g.PALETTE,action:()=>(M.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:g.PALETTE,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:g.PALETTE,action:()=>(M.navigateToNextContainer(),l("Navigating to next container",null))}];var gc=[...mc,...fc,{intent:h.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.NEW} `),l("Adding new item",null))},{intent:h.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.DELETE} `),l("Deleting item",null))},{intent:h.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(C({mode:g.COMMAND_LINE}),_(""),l("Entering command line mode",null))},{intent:h.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=f();if(!z(e?.id??"")?.length){if(e?.title===se.DESCRIPTION)return C({mode:g.COMMAND_LINE}),_(`${x.EDIT} description `),l("Propose command",!0);if(e?.title===se.ASSIGNEES)return C({mode:g.COMMAND_LINE}),_(`${x.ASSIGN} `),l("Propose command",!0);if(e?.title===se.TAGS)return C({mode:g.COMMAND_LINE}),_(`${x.TAG} `),l("Propose command",!0);if(t.title===se.DESCRIPTION&&e?.context==="TEXT")return C({mode:g.COMMAND_LINE}),_(`${x.EDIT} description `),l("Propose command",!0)}return M.enterChildNode(),l("Entering context",null)}},{intent:h.EditTitle,mode:g.DEFAULT,description:"[r] rename title",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.EDIT} title ${f().selectedNode?.title}`),l("Exiting context",null))},{intent:h.EditDescription,mode:g.DEFAULT,description:"[e] edit description",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.EDIT} description `),l("Exiting context",null))},{intent:h.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(M.enterParentNode(),l("Exiting context",null))},{intent:h.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:g.DEFAULT,action:()=>(M.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:g.DEFAULT,action:()=>(M.navigateToNextContainer(),l("Navigating to next container",null))}];var Af=500,Tf=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),vc=e=>{let t=Tf(e);t&&Xr(n=>(n+t).slice(0,Af))};var wf=[g.COMMAND_LINE,g.PALETTE],Mf=e=>[{intent:h.MoveCursorLeft,mode:e,action:()=>(As(-1),l("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:e,action:()=>(As(1),l("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:e,action:()=>(Ts("left"),l("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:e,action:()=>(Ts("right"),l("Moving cursor right of word",null))},{intent:h.AutoCompleteCommand,mode:e,action:()=>(Xr((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=f().selectedNode?.title??""),r+o}),l("Auto-completing command",null))},{intent:h.CaptureInput,mode:e,action:(t,{sequence:n})=>(vc(n??""),l("Capturing input",null))},{intent:h.EraseInput,mode:e,action:()=>(nd(),l("Erasing input",null))},{intent:h.EraseInputWord,mode:e,action:()=>(rd(),l("Erasing input word",null))}],yc=[{intent:h.Confirm,mode:g.COMMAND_LINE,action:()=>(st(),l("Executing command",null))},{intent:h.ViewHelp,mode:g.DEFAULT,action:()=>(C({mode:g.HELP}),l("Viewing help",null))},...wf.flatMap(Mf),{intent:h.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(C({mode:g.DEFAULT}),l("Exiting command line",null))},{intent:h.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(id(),l("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(ad(),l("Getting next command from history",null))}];import Ic from"chalk";var xo=Ic.dim.hex(y.secondary2)(": for command line"),hc="q to exit",xc=`${Ic.hex(y.accent)("m")} to confirm`,Vs={[P.WORKSPACE]:[xo],[P.BOARD]:[xo],[P.BOARD+g.COMMAND_LINE]:[xo],[P.SWIMLANE]:[xo],[P.TICKET+g.HELP]:[hc],[P.SWIMLANE+g.HELP]:[hc],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+g.MOVE]:[xc],[P.TICKET+g.MOVE]:[xc]};var er=e=>e.trim().toLocaleLowerCase(),Pf=e=>{let{tags:t}=f();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Lf=e=>{let{contributors:t}=f();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},bc=(e,t)=>{let n=er(t.value);if(!n)return!0;switch(t.target){case"title":return er(e.title??"").includes(n);case"description":return er(e.props.description??"").includes(n);case"tag":return Pf(e).map(er).some(o=>o.includes(n));case"assignee":return Lf(e).map(er).some(o=>o.includes(n));case"ref":return Qi(e.id,t.value);default:return!0}};function Cc(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=r;for(;s&&(o.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let i=o[o.length-1];return!i||i.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var Ec=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 sn,Gs,zs=new Set,Sc=()=>{for(let e of zs)e()},Df=e=>(zs.add(e),()=>zs.delete(e));function Nc(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=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=Cc(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,v=Vs[p+n]??Vs[p]??[],I=[...gc,...lc[p]??[],...yc],S=Ec(I),N=Ff(o,s),T=N[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:v,availableActions:I,actionIndex:S,selectedNode:T,renderedChildrenIndex:N})}var f=()=>{if(!sn)throw new Error("State not initialized. Call initWorkspaceState() first.");return sn},We=()=>sn?l("Retrieved state",sn):a("State not initialized. Call initWorkspaceState() first.");function $n(e){Gs=e;let t=Ke(process.cwd()),n=!1;if(!d(t)){let s=Et(t.value);if(d(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:g.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{}},o=Nc(r);return d(o)?o:(sn=o.value,Sc(),l("State initialized",null))}function fe(e){let t=f(),n=e(t),r=Nc(n);return d(r)?a(r.message??"Unable to update state"):(sn=r.value,Sc(),l("State updated",null))}var C=e=>fe(t=>({...t,...e}));var $=()=>kf(Df,f,f),Ff=(e,t)=>{let n={};for(let r of Object.values(e))w(r)&&t.length>0&&!t.every(o=>bc(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,s)=>{let i=e[o.id],c=e[s.id];return!i||!c?0:i.rank.localeCompare(c.rank)});return n},W=e=>f()?.renderedChildrenIndex[e]??[],Ut=()=>Gs?$n(Gs):a("Cannot reset state: no initial workspace found"),xn=()=>sn!==void 0;var Ks=e=>{xn()&&(C({syncStatus:e}),zt({type:"sync-status",payload:e}))},Io=(e="Syncing...")=>{Ks({status:"syncing",msg:e})},bo=(e="Synced")=>{Ks({status:"synced",msg:e})},qs=e=>{Ks({status:"failed",msg:e})},He=e=>(qs(e),a(e));import{decodeTime as PM}from"ulid";var Bf=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=K("getRepoRootDir",await Ye(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=K("getStateBranchRoot",Te({repoRoot:r}));if(d(o))return a(o.message);let s=o.value;logger.debug("[sync] state branch root",s);let i=K("ensureInitialCommit",await Di(r));if(d(i))return a(i.message);logger.debug("[sync] initial commit result",{created:i.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let c=K("bootstrapStateBranchStorage",await Bi({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(d(c))return a(c.message);logger.debug("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let u=K("hasInProgressGitOperation(stateBranchRoot)",await yr(s));if(d(u))return a(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value)return logger.info("[sync] state branch git operation in progress"),a("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let m=K("ensureStateBranchLayout",Pi(r,s));return d(m)?a(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}),l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}))},Uf=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=K("stageStateBranchOwnEventFile",await Er({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=K("hasStagedChanges(after stage)",await Ni(t));if(d(o))return a(o.message);if(logger.debug("[sync] state branch change check after stage result",{changed:o.value}),!o.value)return logger.info("[sync] no own event file changes to commit"),l("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let s=K("createStateBranchSyncCommit",await Fi({repoRoot:e,stateBranchRoot:t}));return d(s)?a(s.message):(logger.debug("[sync] created sync commit",s.value),l("Committed own event file",{createdCommit:!0,commitSha:s.value}))},$r=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),a("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),a("Own event file must end with .jsonl");Io();let n=K("ensureSyncReady",await Bf({cwd:e,ensureUpstream:!0}));if(d(n))return He(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=K("isDetachedHead(stateBranchRoot)",await Ri(o));if(d(i))return He(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return He("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,v=K("getStateBranch",cn(r));if(d(v))return He(v.message);let I=v.value;logger.debug("[sync] resolved state branch",{stateBranch:I,stateBranchRoot:o});let S=K("commitOwnEventFileToStateBranch",await Uf({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(S))return He(S.message);c=S.value.createdCommit,u=S.value.commitSha;let N=K("pullBranchRebaseIfPresent",await Qo({cwd:o,branch:I}));if(d(N))return He(N.message);if(m=N.value,c||s){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:o});let T=K("pushStateBranch",await Fn({stateBranchRoot:o,repoRoot:r}));if(d(T)&&Si(T.message)){let k=K("pullBranchRebaseIfPresent(retry)",await Qo({cwd:o,branch:I}));if(d(k))return He(k.message);m=m||k.value,T=K("pushStateBranch(retry)",await Fn({stateBranchRoot:o,repoRoot:r}))}if(d(T))return He(T.message);p=T.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let T=K("git rev-parse HEAD",await U({args:["rev-parse","HEAD"],cwd:o}));if(d(T))return He(T.message);u=T.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return bo(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:s})};var Ys=e=>{let t=Ke(e??process.cwd());return d(t)?a(t.message):l("Resolved Epiq repo root",t.value)},ke=async e=>{let t=Ys(e);if(d(t))return t;let n=Te({repoRoot:t.value});if(d(n))return a(n.message);let r=dn(),o=await Gt({repoRoot:t.value,stateBranchRoot:n.value,stateBranchName:r.stateBranch});if(d(o))return a(o.message);let s=await U({cwd:n.value,args:["pull","--ff-only"]});d(s)&&re.info(3,s.message);let i=ft(n.value);if(d(i))return a(i.message);let c=Jt(i.value);return d(c)?a(c.message):l("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:n.value})},De=()=>{let e=Qn();return d(e)?a(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},je=()=>{let e=We();return d(e)?a(e.message):e},Rc=e=>(e.props.tags??[]).map(t=>b.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:ie(t.name)})),Ac=e=>(e.props.assignees??[]).map(t=>b.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:ie(t.name)}));var Tc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=je();if(d(n))return n;let r=Object.values(n.value.nodes).filter(w).filter(o=>e.includeClosed||o.parentNodeId!==ce).map(o=>({id:o.id,ref:et(o.id),title:Rt(o.title),description:o.props.description??"",parentNodeId:o.parentNodeId,isClosed:o.parentNodeId===ce,readonly:!!o.readonly,tags:Rc(o),assignees:Ac(o)}));return l("Listed issues",r)},wc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=yn(e.parentId,n.value,t.value.stateBranchRoot);if(d(r))return r;let o=uo({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(d(o))return o;let s=o.value,i=B([...s],t.value.stateBranchRoot);if(d(i))return a(i.message);let c=s.find(u=>u.action==="add.issue")?.payload.id;return c?l("Created issue",{id:c,title:e.title,parentId:e.parentId}):a("Unable to determine created issue id")},Mc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=Xt(ce,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(d(r))return r;let o={id:Ie(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ce,rank:r.value}},s=B([o],t.value.stateBranchRoot);return d(s)?a(s.message):l("Closed issue",{id:e.issueId})},Pc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Target node is not issue");if(o.parentNodeId!==ce)return a("Issue is not closed");let s=ao(o);if(!s)return a("Unable to resolve previous parent from issue history");if(s===ce)return a("Previous parent resolves to closed swimlane");let i=r.value.nodes[s];if(!i)return a("Previous parent no longer exists");let c=Xt(i.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(c))return c;let u={id:Ie(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:i.id,rank:c.value}},m=B([u],t.value.stateBranchRoot);return d(m)?a(m.message):l("Reopened issue",{id:o.id,parentId:i.id})},Lc=async e=>{let t=Ys(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=Te({repoRoot:t.value});if(d(r))return r;let o=ft(r.value);if(d(o))return o;let s=Jt(o.value);if(d(s))return s;let i=Xt(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(d(i))return i;let c={id:Ie(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:i.value}},u=B([c],r.value);return d(u)?a(u.message):l("Moved issue",{id:e.issueId,parentId:e.parentId})},Co=async(e={})=>{Io();let t=Ys(e.repoRoot);if(d(t))return a("Sync failed");let n=De();if(d(n))return n;let r=await $r({cwd:t.value,ownEventFileName:Yt(n.value)});return d(r)?(qs(r.message),r):(bo(),l("Synced",r.value))};var Ot=async(e={})=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=je();if(d(n))return n;let r=Object.values(n.value.nodes),o=r.filter(m=>Nr(m)&&!m.isDeleted),s=new Map,i=new Map;for(let m of r)if(!m.isDeleted){if(Nt(m)&&m.parentNodeId){let p=s.get(m.parentNodeId)??[];p.push(m),s.set(m.parentNodeId,p)}if(w(m)&&m.parentNodeId){let p=i.get(m.parentNodeId)??[];p.push(m),i.set(m.parentNodeId,p)}}let c=Qn();if(d(c))return c;let u={};for(let m of r.filter(w))m.isDeleted||(u[m.id]=b.getCommentsByIssue(m.id).map(p=>{let v=b.getContributor(p.authorId);return{id:p.id,issueId:p.issue,body:p.md,author:{id:p.authorId,name:v?.name??"Unknown",color:ie(v?.name??p.authorId)},createdAt:Of(p.id)}}));return l("Retrieved Epiq GUI state",{boards:o.sort((m,p)=>m.rank.localeCompare(p.rank)).map(m=>({id:m.id,ref:et(m.id),title:m.title,swimlanes:(s.get(m.id)??[]).sort((p,v)=>p.rank.localeCompare(v.rank)).map(p=>({id:p.id,title:p.title,readonly:!!p.readonly,issues:(i.get(p.id)??[]).sort((v,I)=>v.rank.localeCompare(I.rank)).map(v=>({id:v.id,ref:et(v.id),title:Rt(v.title),description:v.props.description??"",readonly:!!v.readonly,tags:Rc(v),assignees:Ac(v),parentNodeId:v.parentNodeId,isClosed:v.parentNodeId===ce})),parentNodeId:p.parentNodeId}))})),tags:Object.values(n.value.tags).map(m=>({...m,color:ie(m.name)})),contributors:Object.values(n.value.contributors).map(m=>({...m,color:ie(m.name)})),user:{name:c.value.userName??"",id:c.value.userId??"",color:ie(c.value.userName??"")},commentsByIssueId:u})},kc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=o.props.description??"";if(s===e.description)return l("No changes made",{id:e.issueId,description:s});let i={id:Ie(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=B([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue description",{id:e.issueId,description:e.description})},Dc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=Rt(e.title);if(!s.trim())return a("Issue title cannot be empty");if(o.title===s)return l("No changes made",{id:e.issueId,title:s});let i={id:Ie(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=B([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue title",{id:e.issueId,title:s})},Fc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Tag target must be an issue");if(o.readonly)return a("Cannot tag readonly issue");let s=Rt(e.tagName).trim();if(!s)return a("Tag name cannot be empty");let i=Object.values(r.value.tags).find(p=>p.name===s),c=i?.id??Ie(),u=[...i?[]:[{id:Ie(),...n.value,action:"create.tag",payload:{id:c,name:s}}],{id:Ie(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:c}}],m=B(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue tag",{id:e.issueId,tag:{id:c,name:s}})},Bc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Untag target must be an issue");if(o.readonly)return a("Cannot untag readonly issue");if(!r.value.tags[e.tagId])return a("Tag not found");let s={id:Ie(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue tag",{id:e.issueId,tagId:e.tagId})},Uc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Assign target must be an issue");if(o.readonly)return a("Cannot assign readonly issue");let s=Rt(e.assigneeName).trim();if(!s)return a("Assignee name cannot be empty");let i=Object.values(r.value.contributors).find(p=>p.name===s),c=i?.id??Ie(),u=[...i?[]:[{id:Ie(),...n.value,action:"create.contributor",payload:{id:c,name:s}}],{id:Ie(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:c}}],m=B(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue assignee",{id:e.issueId,assignee:{id:c,name:s}})},Oc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Unassign target must be an issue");if(o.readonly)return a("Cannot unassign readonly issue");if(!r.value.contributors[e.assigneeId])return a("Assignee not found");let s={id:Ie(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},Eo=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Comment target must be an issue");if(o.readonly)return a("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return a("Comment cannot be empty");let i=Ie(),c={id:Ie(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Added issue comment",{id:i,issueId:e.issueId,body:s})},So=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return a("Unable to resolve comment");if(o.payload.author!==n.value.userId)return a("You can only delete your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!w(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot delete comment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return l("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:Ie(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})};var _c=e=>{let t,n,r=!1,o=!1,s=!1,i=()=>{let p=Jn();if(d(p))return re.error(p.message);let{autoSync:v,userName:I,preferredEditor:S}=p.value;return!!(v&&I&&S)},c=async()=>{if(!r){if(o){s=!0;return}o=!0;try{await Co({repoRoot:e.repoRoot}),zt({type:"state",payload:await Ot({repoRoot:e.repoRoot})})}finally{o=!1,s&&(s=!1,c())}}},u=(p=750)=>{r||(n&&clearTimeout(n),n=setTimeout(()=>{c()},p))},m=()=>{if(r)return;let p=Jn();if(d(p))return re.error(p.message);let{autoSyncDebounceMs:v}=p.value;i()&&(t=setTimeout(()=>{c(),m()},v??15e3))};return m(),{scheduleSync:u,dispose:()=>{r=!0,t&&clearTimeout(t),n&&clearTimeout(n)}}};import{WebSocketServer as _f}from"ws";var Fe=(e,t)=>{e.send(JSON.stringify(t))},tr=async(e,t)=>Fe(e,{type:"state",payload:await Ot({repoRoot:t})}),it=async(e,t,n,r,o)=>{if(Fe(e,{type:r,payload:o}),d(o))return Fe(e,{type:"failed",payload:o.message});n(),tr(e,t)},$c=(e,t,{onStateChanged:n})=>{new _f({server:e,path:"/ws"}).on("connection",o=>{Ui(o),o.on("message",async s=>{try{let i=JSON.parse(s.toString()),{type:c}=i;if(c==="state:get")return tr(o,t);if(c==="sync"){let u=await Co({repoRoot:t});return Fe(o,{type:"sync:result",payload:u}),n(),tr(o,t)}if(c==="issue:comment:add"){let u=await Eo({repoRoot:t,...i.payload});return it(o,t,n,"issue:comment:add:result",u)}if(c==="issue:comment:delete"){let u=await So({repoRoot:t,...i.payload});return Fe(o,{type:"issue:comment:delete:result",payload:u}),d(u)?Fe(o,{type:"failed",payload:u.message}):(n(),tr(o,t))}if(c==="issue:edit:description"){let u=await kc({repoRoot:t,...i.payload});return it(o,t,n,"issue:edit:description:result",u)}if(c==="issue:edit:title"){let u=await Dc({repoRoot:t,...i.payload});return it(o,t,n,"issue:edit:title:result",u)}if(c==="issue:tag:add"){let u=await Fc({repoRoot:t,...i.payload});return it(o,t,n,"issue:tag:add:result",u)}if(c==="issue:tag:remove"){let u=await Bc({repoRoot:t,...i.payload});return it(o,t,n,"issue:tag:remove:result",u)}if(c==="issue:assignee:add"){let u=await Uc({repoRoot:t,...i.payload});return it(o,t,n,"issue:assignee:add:result",u)}if(c==="issue:assignee:remove"){let u=await Oc({repoRoot:t,...i.payload});return it(o,t,n,"issue:assignee:remove:result",u)}if(c==="issues:list")return Fe(o,{type:"issues",payload:await Tc({repoRoot:t})});if(c==="issues:create"){let u=await wc({...i.payload,repoRoot:t});return Fe(o,{type:"issues:create:result",payload:u}),d(u)?zt({type:"failed",payload:u.message}):(zt({type:"issue:created",payload:u.value}),n(),tr(o,t))}if(c==="issues:move"){if(!i.payload.position)return Fe(o,{type:"error",message:"Missing move position"});let u=await Lc({...i.payload,repoRoot:t});return it(o,t,n,"issues:move:result",u)}if(c==="issue:close"){if(!i.payload.issueId)return Fe(o,{type:"error",message:"Missing issueId"});let u=await Mc({repoRoot:t,issueId:i.payload.issueId});return it(o,t,n,"issue:close:result",u)}if(c==="issue:reopen"){if(!i.payload.issueId)return Fe(o,{type:"error",message:"Missing issueId"});let u=await Pc({repoRoot:t,issueId:i.payload.issueId});return it(o,t,n,"issue:reopen:result",u)}return Fe(o,{type:"error",message:"Unknown message type"})}catch(i){return Fe(o,{type:"error",message:i instanceof Error?i.message:String(i)})}})})};var jf=an.dirname(Hf(import.meta.url)),Vf=process.env.IS_LOCAL==="true"?an.resolve(process.cwd(),"dist/gui"):an.join(jf,"gui"),at=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},Gf=async e=>new Promise((t,n)=>{let r="";e.on("data",o=>{r+=o}),e.on("end",()=>{try{t(r?JSON.parse(r):{})}catch{n(new Error("Invalid JSON body"))}}),e.on("error",n)}),zf=e=>e.endsWith(".html")?"text/html; charset=utf-8":e.endsWith(".js")?"text/javascript; charset=utf-8":e.endsWith(".css")?"text/css; charset=utf-8":e.endsWith(".json")?"application/json; charset=utf-8":e.endsWith(".ico")?"image/x-icon":"application/octet-stream",Wc=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=an.resolve(Vf),o=an.resolve(r,n),s=an.relative(r,o);if(s.startsWith("..")||an.isAbsolute(s))return at(t,403,{isError:!0,message:"Forbidden"});try{let i=await $f(o);return t.writeHead(200,{"content-type":zf(o)}),t.end(i)}catch{return at(t,404,{isError:!0,message:`Not found: ${n}`})}},Kf=async(e,t=3710)=>new Promise((n,r)=>{let o=s=>{let i=u=>{if(e.off("listening",c),u.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(u)},c=()=>{e.off("error",i);let u=e.address();if(!u||typeof u=="string"){r(new Error("Unable to resolve address"));return}n(u.port)};e.once("error",i),e.once("listening",c),e.listen(s,"127.0.0.1")};o(t)}),Hc=async e=>{let t=Wf.createServer(async(o,s)=>{let i=new URL(o.url??"/","http://127.0.0.1");if(i.pathname==="/api/state")return at(s,200,await Ot({repoRoot:e.repoRoot}));if(o.method==="POST"&&i.pathname==="/api/comments")try{let c=await Gf(o);if(!c.issueId||!c.body?.trim())return at(s,400,{isError:!0,message:"Missing issueId or body"});let u=await Eo({repoRoot:e.repoRoot,issueId:c.issueId,body:c.body});return"isError"in u&&u.isError?at(s,400,u):at(s,200,await Ot({repoRoot:e.repoRoot}))}catch(c){return at(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add comment"})}if(o.method==="DELETE"&&i.pathname.startsWith("/api/comments/")){let c=decodeURIComponent(i.pathname.replace("/api/comments/",""));if(!c)return at(s,400,{isError:!0,message:"Missing comment id"});let u=await So({repoRoot:e.repoRoot,commentId:c});return"isError"in u&&u.isError?at(s,400,u):at(s,200,await Ot({repoRoot:e.repoRoot}))}return i.pathname.startsWith("/board/")?Wc("/",s):Wc(i.pathname,s)});try{await Kf(t)}catch(o){return a(o instanceof Error?`Unable to start GUI server: ${o.message}`:`Unable to start GUI server: ${String(o)}`)}let n=_c({repoRoot:e.repoRoot});$c(t,e.repoRoot,{onStateChanged:()=>n.scheduleSync()}),t.on("close",n.dispose);let r=t.address();return!r||typeof r=="string"?(t.close(),a("Unable to resolve GUI server address")):l("Started GUI server",{url:`http://epiq.localhost:${r.port}${e.boardId?`/board/${e.boardId}`:""}`,server:t})};var jc=async e=>{let t=await Hc({...e,boardId:""});if(d(t))return t;let{url:n}=t.value;return console.log(`Epiq GUI running at ${qf.cyan(n)}`),mi(n),l("Started GUI",{url:n})};import{Box as jt}from"ink";import ee from"react";import{Box as Xs,Text as nr}from"ink";import Ve,{useEffect as Yf,useMemo as Xf}from"react";import{ulid as Jf}from"ulid";var Vc=({text:e,match:t,color:n,highlightColor:r=y.secondary,dimColor:o=!1})=>{if(!t)return Ve.createElement(nr,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),c=s.indexOf(i);return c===-1?Ve.createElement(nr,{color:n,dimColor:o},e):Ve.createElement(nr,{color:n,dimColor:o},e.slice(0,c),Ve.createElement(nr,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},Gc=Jf(),Qf=e=>`${e}`,Zf=e=>{let{pendingNavTarget:t}=Dt();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(le(x.NONE,{breadCrumb:n,contextNode:r,readOnly:f().readOnly,selectedNode:o}));return[...new Set(Object.values(x))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==x.PALETTE).map(i=>{let c=Jr(i),u=vo.find(m=>m.intent===c);return{command:i,description:u?.description??`[${i}] Run command`,isAvailable:s.has(i)}}).filter(i=>i.command.toLowerCase().startsWith(e)||e.length>=2&&i.description.toLowerCase().includes(e)).sort((i,c)=>i.isAvailable!==c.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(c.command))},eg=e=>Q.text({id:Gc,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),tg=(e,t,n)=>Q.text({id:Qf(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Js=[],ng=e=>{zc();let t=b.createNode(eg(f().rootNodeId));d(t)||!St(t.value)||(Js=[t.value,...e.map((n,r)=>tg(n,r,Gc)).map(b.createNode).filter(te).map(({value:n})=>n).filter(St)],M.navigate({contextNode:t.value,selectedIndex:0}))},zc=()=>{let e=Js.map(t=>t.id);Js=[];for(let t of e)b.deleteNode(t)};function Kc({width:e,height:t}){let r=dd().value.trim().toLowerCase(),o=Xf(()=>Zf(r),[r]);Yf(()=>(ng(o),()=>{zc()}),[o]);let s=f().selectedIndex;return Ve.createElement(Xs,{flexDirection:"column",width:e,height:t-2},Ve.createElement(rt,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,c)=>{let u=c===s,m=i.isAvailable?y.accent:y.secondary2,p=i.isAvailable?"":"[unavailable] ";return Ve.createElement(Xs,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Ve.createElement(nr,{color:m,dimColor:!i.isAvailable},u?"\u276F ":" ",Ve.createElement(Vc,{text:ji(i.command),match:r,color:m,dimColor:!i.isAvailable})),Ve.createElement(Xs,{paddingLeft:2},Ve.createElement(Vc,{text:p+i.description,match:r.length>=2?r:"",color:u&&i.isAvailable?y.primary:y.secondary2,dimColor:!i.isAvailable})))})))}import{Box as xg}from"ink";import Ao from"react";import or from"chalk";import{Box as Qs,Text as qc}from"ink";import rr,{useEffect as rg,useMemo as og,useState as sg}from"react";var Yc=or.hex(y.secondary),ig=or.inverse,ag=or.inverse.hex(y.secondary2),dg={hint:"",hints:[],overlap:0,remainder:""},Jc=({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}},cg=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=ie(t);return{bg:r=>or.bgHex(n).black(r),bgCursor:r=>or.bgHex(n).inverse.black(r)}}return cs(t)},lg=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Jc({value:e,command:t});if(!r)return null;let s=e.slice(r.end).match(/^\s*/)?.[0].length??0,i=r.end+s;return e.slice(i,i+n.length)!==n?null:{start:i,end:i+n.length}},Xc=()=>({value:he.value,cursorPosition:he.cursorPosition,commandIsPending:he.commandIsPending,autoCompletion:he.commandMeta.autoCompletion??dg,infoMessage:he.commandMeta.infoMessage,validationStatus:he.commandMeta.validity,command:he.commandMeta.command,inputString:he.commandMeta.inputString,modifier:he.commandMeta.modifier}),ug=(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,Qc=({width:e,mode:t})=>{let[n,r]=sg(Xc());rg(()=>{let I=()=>{let N=Xc();r(T=>ug(T,N)?T:N)},S=Rs(I);return I(),()=>{S()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:c,autoCompletion:u,command:m,modifier:p}=n,v=og(()=>{let I=Math.max(0,Math.min(s,o.length)),S=Jc({value:o,command:m}),N=lg({value:o,command:m,modifier:p}),T=m?cs(m):null,k=cg({command:m,modifier:p}),O=(de,X)=>{let lt=S&&X>=S.start&&X<S.end,ze=N&&X>=N.start&&X<N.end;return lt&&T?T.fg(de):ze&&k?k.bg(de):de},V=(de,X)=>{let lt=S&&X>=S.start&&X<S.end,ze=N&&X>=N.start&&X<N.end;return lt&&T?T.fgCursor(de):ze&&k?k.bgCursor(de):ig(de)},R=o.slice(0,I),A=o[I]??" ",G=I<o.length?o.slice(I+1):"",Re=Array.from(R).map((de,X)=>O(de,X)).join(""),Ae=V(A,I),Ge=Array.from(G).map((de,X)=>O(de,I+1+X)).join("");if(u.hint){let de=u.hint[u.overlap]??A;Ae=ag(de),Ge=Yc(u.remainder.slice(1)+G)}return Yc(t===g.PALETTE?"?":":")+Re+Ae+Ge},[o,s,u,m,p]);return rr.createElement(Qs,{flexDirection:"column",justifyContent:"flex-start"},rr.createElement(Qs,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},rr.createElement(Qs,null,rr.createElement(qc,null,v),i&&rr.createElement(qc,{wrap:"truncate",color:c?y.red:y.secondary2},` ${i} `))))};import{Box as mg,Text as pg}from"ink";import Zc from"react";var fg=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?" | ":"").length+o.length;if(r+i>t-4)break;n.push(o),r+=i}return n},el=({width:e,availableHints:t})=>{let n=fg(t,e).join(" | ");return Zc.createElement(mg,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1},Zc.createElement(pg,{color:y.secondary2},n.length?n:"\xA0"))};import{Box as gg,Text as No}from"ink";import sr,{useEffect as vg,useRef as Nn,useState as yg}from"react";var hg=40,Ro=.3,Zs="\u2500",tl=1,nl=16,rl=({width:e})=>{let{replay:t}=$(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*tl,[c,u]=yg(0),m=Nn(r);m.current=r;let p=Nn(0),v=Nn(0),I=Nn(0),S=Nn(0),N=Nn(0);if(vg(()=>{if(!n){p.current=0,I.current=0,S.current=0,N.current=0,u(0);return}p.current=m.current,v.current=Date.now(),I.current=m.current;let R=setInterval(()=>{let A=Date.now(),G=m.current;if(G!==I.current){let X=G-I.current,lt=A-v.current;if(X<0)S.current=0,N.current=0;else if(X>0&&lt>0){let ze=X/lt;S.current=S.current===0?ze:S.current*(1-Ro)+ze*Ro,N.current=N.current===0?X:N.current*(1-Ro)+X*Ro}p.current=G,v.current=A,I.current=G}let Re=A-v.current,Ae=Math.min(N.current,S.current*Re),Ge=Math.min(1,p.current+Ae),de=Math.round(Ge*i);u(X=>X===de?X:de)},hg);return()=>clearInterval(R)},[n,i]),!t)return null;let T=R=>{let A=s>1?R/(s-1):0,G=Math.round(A*(nl-1))/(nl-1);return Ar(G)},k=Math.min(s,Math.floor(c/tl)),O=[];for(let R=0;R<k;R++){let A=T(R),G=O[O.length-1];G&&G.color===A?G.text+=Zs:O.push({text:Zs,color:A})}let V=Zs.repeat(Math.max(0,s-k));return sr.createElement(gg,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1,columnGap:1},sr.createElement(No,{color:y.secondary2},"\u25B6"),sr.createElement(No,null,O.map((R,A)=>sr.createElement(No,{key:A,color:R.color},R.text)),sr.createElement(No,{color:y.secondary,dimColor:!0},V)))};var ir=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=$(),o=t===g.COMMAND_LINE||t===g.PALETTE;return Ao.createElement(xg,null,o?Ao.createElement(Qc,{width:e,mode:t}):r==="replay"?Ao.createElement(rl,{width:e}):Ao.createElement(el,{width:e,mode:t,availableHints:n}))};import{Box as _t,Text as Rn}from"ink";import Ee,{useEffect as Ig,useMemo as bg}from"react";import{ulid as ol}from"ulid";var wo=ol(),Cg=()=>[...new Set([...f().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})),Eg=e=>Q.text({id:wo,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),Sg=(e,t,n)=>Q.text({id:ol(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),To=[],sl=()=>{let e=To.filter(n=>n.id!==wo).map(n=>n.id),t=To.filter(n=>n.id===wo).map(n=>n.id);To=[];for(let n of[...e,...t])b.deleteNode(n)},Ng=e=>{sl();let t=b.createNode(Eg(f().rootNodeId));if(d(t)||!St(t.value))return logger.error("Could not attach help nodes");To=[t.value,...e.map((n,r)=>Sg(n,r,wo)).map(b.createNode).filter(te).map(({value:n})=>n).filter(St)],M.navigate({contextNode:t.value,selectedIndex:0})},il=({width:e,height:t})=>{let n=bg(()=>Cg(),[]);Ig(()=>(Ng(n),()=>{sl()}),[n]);let r=f().selectedIndex;return Ee.createElement(_t,{flexDirection:"column",marginTop:3,borderColor:y.secondary,borderStyle:"round",width:e,height:t-2},Ee.createElement(_t,{paddingX:1,justifyContent:"center"},Ee.createElement(Rn,{color:y.accent},"Help"),Ee.createElement(Rn,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),Ee.createElement(_t,{paddingX:1,marginTop:1},Ee.createElement(_t,{width:20,justifyContent:"flex-end"},Ee.createElement(Rn,{color:y.secondary},"Key(s)")),Ee.createElement(_t,{flexGrow:1,width:40,paddingLeft:2},Ee.createElement(Rn,{color:y.secondary},"Action"))),Ee.createElement(rt,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let c=i===r;return Ee.createElement(_t,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},Ee.createElement(_t,{width:20,justifyContent:"flex-end"},Ee.createElement(Rn,{color:y.accent},o)),Ee.createElement(_t,{flexGrow:1,width:40,paddingLeft:2},Ee.createElement(Rn,{color:c?y.primary:y.secondary2},s)))})))};import Rg from"chalk";import{Box as Mo,Text as bt}from"ink";import Be from"react";var al=({width:e,height:t})=>Be.createElement(Mo,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},Be.createElement(bt,{color:y.accent,bold:!0},"Initialize project"),Be.createElement(bt,null,`This folder is not an ${Rg.hex(y.accent)("epiq")} project yet.`),Be.createElement(bt,{color:y.primary},"To start tracking issues here, we need to initialize a new",Be.createElement(bt,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json "),"file in this repository."),Be.createElement(Mo,{marginTop:1,flexDirection:"column"},Be.createElement(Mo,null,Be.createElement(bt,{color:y.accent}," "),Be.createElement(bt,{color:y.primary},"Type "),Be.createElement(bt,{backgroundColor:y.secondary}," :init "))),Be.createElement(Mo,{marginTop:1},Be.createElement(bt,{color:y.secondary2},"This will create, commit and push "),Be.createElement(bt,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json ")));import{Box as Po,Text as dt}from"ink";import pe from"react";var Ag=({isDone:e,command:t,value:n})=>pe.createElement(Po,null,pe.createElement(dt,{color:y.accent,dimColor:e},e?" \u2714 ":" "),pe.createElement(dt,{dimColor:e},"Type "),pe.createElement(dt,{backgroundColor:y.secondary,dimColor:e}," "+t+" "),n!==void 0&&pe.createElement(pe.Fragment,null,pe.createElement(dt,{dimColor:e}," "),pe.createElement(dt,{color:y.secondary,dimColor:e},"<"+n+">"))),Tg=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function ei({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:c}=wt(),u=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:s,message:"Nice. Now pick your editor."},{key:"autosync",done:c,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=u.findIndex(v=>!v.done),p=m===-1?void 0:u[m];return pe.createElement(Po,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},pe.createElement(dt,{color:y.accent,bold:!0},"Welcome! \u{1F539}"),pe.createElement(dt,null,"Let's get you started - it's a breeze."),pe.createElement(dt,{color:y.secondary2},"Remember - you can always search available commands by typing:",pe.createElement(dt,{color:y.accent}," ? ")),p&&pe.createElement(dt,{color:y.secondary2},p.message),pe.createElement(Po,{flexDirection:"column"},u.map((v,I)=>m===-1||I<=m?pe.createElement(Po,{key:v.key,marginBottom:1},pe.createElement(Ag,{isDone:v.done,command:v.command,value:v.done?Tg(v.value):void 0})):null)))}import Bo from"chalk";import{Box as dr,Text as An}from"ink";import me from"react";import{Box as Lo,Text as dl}from"ink";import $t from"react";import wg from"chalk";var Mg=e=>(b.getTag(e)?.name??"").length+3,Pg=e=>(b.getContributor(e)?.name??"").length+3,cl=({width:e})=>{let{viewMode:t}=H(),n=$(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,c=i[o.id]?.[s],u=pt(c?.id??o.id,"TICKET"),m=te(u)?u.value:void 0,p=m?.props.tags??[],v=m?.props.assignees??[],I=m?.parentNodeId?!is(o.id,m.parentNodeId)&&t==="dense":!1,S=r.map((A,G)=>{let Re=G===r.length-1,Ae=z(A.id),Ge=Re?Ae?.[s]?.title:void 0;return`${G?" / ":""}${A.title??""}${Ge?` \u25B8 ${Ge}`:""}`}).join(""),N=m?b.getCommentsByIssue(m.id):[],T=N.length?String(N.length).length+11:0,k=I?p.reduce((A,G)=>A+Mg(G),0)+v.reduce((A,G)=>A+Pg(G),0)+T:0,O=Math.max(0,e-k),V=S.substring(0,O)+(c?.id?wg.hex(y.secondary2).dim(` #${et(c.id)}`):""),R=I?[...p.map(A=>$t.createElement(Lo,{key:`tag-${A}`,paddingLeft:1},$t.createElement(Cn,{id:A}))),...v.map(A=>$t.createElement(Lo,{key:`assignee-${A}`,paddingLeft:1},$t.createElement(Pt,{id:A}))),N.length?$t.createElement(Lo,{key:"comments",paddingLeft:1},$t.createElement(dl,{color:y.accent},"[",N.length," comment",N.length===1?"":"s","]")):null]:[];return $t.createElement(Lo,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},$t.createElement(dl,{color:y.secondary2},V),R)};import{Box as Lg,Text as ll}from"ink";import ko from"react";var kg=({filters:e})=>ko.createElement(Lg,{columnGap:1},ko.createElement(ll,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>ko.createElement(ll,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),ul=ko.memo(kg);import{Box as Dg,Text as Do}from"ink";import ar from"react";function ml(){let{eventLog:e,unappliedEvents:t}=$(),n=e.at(-1)?.id,r=Lr(n??""),o=te(r)?Pr(r.value):"INVALID DATE";return ar.createElement(Dg,{paddingLeft:1},ar.createElement(Do,{backgroundColor:y.accent,color:y.secondary}," Readonly "),ar.createElement(Do,{color:y.accent}," "+t.length+" edits ago at "+o+"."),ar.createElement(Do,{color:y.accent}," Resume with "),ar.createElement(Do,{backgroundColor:y.accent,color:y.secondary}," ",":peek now"," "))}import{Box as Fg,Text as ti}from"ink";import Fo from"react";function pl(){let{replay:e}=$();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return Fo.createElement(Fg,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},Fo.createElement(ti,{backgroundColor:y.accent,color:y.secondary}," \u25B6 REPLAY "),Fo.createElement(ti,{color:y.secondary2},Pr(new Date(r))),Fo.createElement(ti,{color:y.accent},`${t}/${n} edits`))}import ni from"chalk";import{Box as Bg,Text as fl}from"ink";import ri,{useEffect as Ug,useState as Og}from"react";var _g=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],$g=150,gl=12,Wg=.36,vl=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)}},Hg=({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)}`},jg=(e,t,n)=>{let r=vl(e),o=vl(t);return Hg({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Vg=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,s=e[r],i=e[Math.min(r+1,e.length-1)];return jg(s,i,o)};function yl({syncStatus:e,autoSync:t}){let[n,r]=Og(0);Ug(()=>{if(e.status!=="syncing"){r(0);return}let c=0,u=setInterval(()=>{c+=1;let m=(Math.sin(c*Wg)+1)/2,p=Math.round(m*(gl-1));r(v=>v===p?v:p)},$g);return()=>clearInterval(u)},[e.status]);let o={synced:" ",failed:"---",syncing:"...",pending:"idle"},i={synced:y.secondary2,failed:y.yellow,pending:y.secondary2,syncing:Vg(_g,n/(gl-1))??""}[e.status];return ri.createElement(Bg,null,ri.createElement(fl,null,ni.hex(y.secondary2).dim(t?"Sync (auto): ":"Sync: ")),ri.createElement(fl,null,ni.hex(i)("\u25CF")+ni.hex(y.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import Cl from"chalk";import{Text as El}from"ink";import Sl,{useEffect as qg,useState as Yg}from"react";var Wt="1.2.0";import oi from"chalk";var Gg="https://registry.npmjs.org/epiq/latest",si=null,hl=0,zg=1e3*60*60*24,xl=e=>e.replace(/^v/,""),Kg=(e,t)=>{let n=xl(e).split(".").map(Number),r=xl(t).split(".").map(Number);for(let o=0;o<Math.max(n.length,r.length);o++){let s=n[o]??0,i=r[o]??0;if(s>i)return 1;if(s<i)return-1}return 0},Il=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(si&&Date.now()-hl<zg)return si;try{let t=await fetch(Gg);if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.status}`);let r=(await t.json()).version??null,o={current:e,latest:r,updateAvailable:r?Kg(r,e)>0:!1};return si=o,hl=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},bl=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?oi.hex(y.accent).dim(s):oi.hex(y.secondary).dim(s)).join(oi.hex(y.secondary2).dim("."))};function Nl(){let[e,t]=Yg({current:Wt,latest:null,updateAvailable:!1});return qg(()=>{let n=!0;return Il(Wt).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?Sl.createElement(El,{dimColor:!0,color:y.secondary2},Wt+" "):Sl.createElement(El,null,Cl.hex(y.secondary2).dim(Wt),Cl.hex(y.accent).dim(" \u2197 "),bl(Wt,e.latest))}function cr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=$(),{userName:i,preferredEditor:c,autoSync:u}=H(),m=64,p=process.stdout.columns-m-8,v=t||n==="replay",I=s?mn(s.currentLabel,Math.max(0,p)):"";return me.createElement(dr,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?me.createElement(dr,{paddingLeft:1},me.createElement(An,{color:y.secondary2},I)):v?me.createElement(An,null," "):o===g.PALETTE?me.createElement(dr,null,me.createElement(An,{color:y.accent},"Command Palette"),me.createElement(An,{dimColor:!0,color:y.secondary2}," ","- search, select and press enter")):me.createElement(dr,{paddingLeft:1},e.length>0?me.createElement(ul,{filters:e}):me.createElement(cl,{width:p})),n==="live"?me.createElement(dr,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},me.createElement(yl,{autoSync:!!u,syncStatus:r}),me.createElement(An,null,Bo.hex(y.secondary2).dim("Mode: ")+Bo.hex(y.secondary2).dim(o.padEnd(8," "))," "),me.createElement(Rl,{icon:"@",value:i}),me.createElement(Rl,{icon:"\u276F",value:c}),me.createElement(Nl,null)):"",n==="peek"?me.createElement(ml,null):"",n==="replay"?me.createElement(pl,null):"")}function Rl({icon:e,value:t}){return me.createElement(An,null,Bo.dim(e)+Bo.hex(y.accent)(` ${t??"-"} `))}import{Box as Xg,Text as Jg}from"ink";import lr from"react";import{Box as Uo,Text as ii}from"ink";import Ht from"react";function ai(){let e=$(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?W(t?.id):[];return Ht.createElement(Uo,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:y.secondary,width:s},Ht.createElement(Uo,{padding:1,paddingTop:0,paddingBottom:0},Ht.createElement(ii,null,"Select a board:")),Ht.createElement(Uo,{padding:1,flexDirection:"column"},i.map((c,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,v=W(c.id).flatMap(({id:I})=>z(I)).length;return Ht.createElement(Uo,{key:c.id??u},Ht.createElement(ii,{color:m?y.accent:y.secondary2},Ht.createElement(Ce,{isSelected:m})),Ht.createElement(ii,{color:m?y.accent:y.secondary2},c.title," (",v," issues)",c.readonly?" \u{1F512}":""))})))}var Qg=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:c}=$(),u=n.find(({context:I})=>I==="BOARD"),v=s-1-3;return lr.createElement(Xg,{flexDirection:"row"},e.context==="WORKSPACE"?lr.createElement(ai,null):u?lr.createElement(so,{height:v,width:i,swimlanes:(c[u.id]??[]).filter(I=>I!==void 0&&Nt(I)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):lr.createElement(Jg,null))},Al=lr.memo(Qg);import{useEffect as Zg}from"react";var ev=e=>{Zg(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=H();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:c,mode:u}=f();u==="default"&&!c&&Wr(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},Tl=({autoSync:e})=>(ev(e),null);function di({width:e,height:t}){let n=$(),{autoSync:r,viewMode:o}=Yi(),s=n.filters;if(n.mode===g.HELP)return ee.createElement(jt,{flexDirection:"column"},ee.createElement(il,{width:e,height:t}));if(n.mode===g.PALETTE)return ee.createElement(jt,{flexDirection:"column"},ee.createElement(cr,{filters:s}),ee.createElement(Kc,{width:e,height:t-2}),ee.createElement(ir,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=wt(),c=!i,u=i&&!n.hasProjectDefinition;if(c)return ee.createElement(jt,{flexDirection:"column"},ee.createElement(jt,{flexDirection:"column"},ee.createElement(cr,{hideBreadCrumb:!0,filters:s}),ee.createElement(ei,{height:t,width:e})),ee.createElement(ir,{width:e,mode:n.mode,availableHints:n.availableHints}));if(u)return ee.createElement(jt,{flexDirection:"column"},ee.createElement(jt,{flexDirection:"column"},ee.createElement(cr,{hideBreadCrumb:!0,filters:s}),ee.createElement(al,{height:t,width:e})),ee.createElement(ir,{width:e,mode:n.mode,availableHints:n.availableHints}));let m=be(n.breadCrumb??[],"BOARD");if(te(m)){let p=m.value.id,v=W(p).length,I=3,S=Math.floor(e/I),N=Math.floor(e/Math.max(v,1));e=Math.min(N,S)*Math.max(v,I)}return ee.createElement(jt,{flexDirection:"column"},ee.createElement(Tl,{autoSync:r}),ee.createElement(jt,{flexDirection:"column"},ee.createElement(cr,{filters:s}),ee.createElement(Al,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),ee.createElement(ir,{width:e,mode:n.mode,availableHints:n.availableHints}))}import tv from"readline";var Oo,_o,ct,nv=new Set([h.MoveCursorLeft,h.EraseInputWord,h.MoveCursorLeftOfWord,h.MoveCursorRight,h.MoveCursorRightOfWord,h.NavToPreviousContainer,h.NavToNextContainer,h.NavPreviousItem,h.NavNextItem,h.SetViewDense,h.SetViewWide,h.Confirm,h.Exit,h.InitCommandLine,h.InitCommandPalette,h.ExitCommandLine,h.CaptureInput,h.EraseInput,h.EraseInputWord,h.HideHelp,h.ViewHelp,h.SetViewDense,h.SetViewWide,h.GetLastCommandFromHistory,h.GetNextCommandFromHistory,h.AutoCompleteCommand]),rv=new Set([h.NavPreviousItem,h.NavNextItem,h.NavToPreviousContainer,h.NavToNextContainer,h.Confirm,h.Exit,h.InitCommandPalette,h.InitMove,h.MoveNextItem,h.MovePreviousItem,h.MoveToNextContainer,h.MoveToPreviousContainer,h.Delete,h.AddItem,h.EditTitle,h.EditDescription,h.ConfirmMove,h.Edit,h.ViewHelp]),wl=async e=>{if(e.ctrl&&e.name==="c")return M.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=f(),s=ld(e,n);if(!s||r&&!nv.has(s)||o==="replay"&&n===g.DEFAULT&&rv.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(c){logger.error(c)}},ov=()=>async function(t,n){n.name!=="escape"&&(ct&&(clearTimeout(ct),ct=void 0),await wl(n))},sv=()=>async function(t){if(t.length===1&&t[0]===27){ct&&clearTimeout(ct),ct=setTimeout(()=>{wl({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),ct=void 0},25);return}ct&&(clearTimeout(ct),ct=void 0)};function Ml(){Oo&&process.stdin.removeListener("keypress",Oo),_o&&process.stdin.removeListener("data",_o),Oo=ov(),_o=sv(),tv.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",_o),process.stdin.on("keypress",Oo)}async function Pl(){try{let e=Qn();te(e)&&_e(e.value);let t=Ke(process.cwd()),n=[];if(te(t)){let s=Te({repoRoot:t.value});if(d(s))return Qt(3,s.message);let i=dn(),c=await Gt({repoRoot:t.value,stateBranchRoot:s.value,stateBranchName:i.stateBranch});if(d(c))return Qt(3,c.message);let u=await U({cwd:s.value,args:["pull","--ff-only"]});d(u)&&logger.info(3,u.message);let m=ft(s.value);if(d(m))return Qt(3,m.message);n=m.value}let r=Jt(n);if(d(r))return Qt(4,r.message);C({hasProjectDefinition:te(t),hasInitializingEvents:!!n.length});let o=ci();return d(o)?Qt(6,o.message):(Ml(),l("Booted Epiq",void 0))}catch(e){return Qt(0,Or(e))}}_d();var cv=`${Vt.bold("Epiq CLI")}
58
58
 
59
- ${jt.dim("Boot in directory:")}
60
- ${jt.cyan("$ epiq")}
59
+ ${Vt.dim("Boot in directory:")}
60
+ ${Vt.cyan("$ epiq")}
61
61
 
62
- ${jt.dim("Launch GUI:")}
63
- ${jt.cyan("$ epiq gui")}
64
- `,av=ov(iv,{importMeta:import.meta,version:$t,flags:{init:{type:"boolean",default:!1}}}),_o=av.input[0];_o&&_o!=="gui"&&(console.error(jt.red(`Unknown command: ${_o}`)),process.exit(1));var Ml=process.stdout.columns||120,Pl=process.stdout.rows||20,$o=null,dv=e=>{try{return $o?($o.rerender(e),l("Rerendered app",void 0)):($o=rv(e),l("Rendered app",void 0))}catch(t){return a(`Unable to render app: ${Ur(t)}`)}},ai=()=>dv(sv.createElement(ii,{width:Ml,height:Pl}));process.stdout.on("resize",()=>{if(Ml=process.stdout.columns||120,Pl=process.stdout.rows||20,!$o)return;let e=ai();d(e)&&logger.info(`[boot:resize] ${e.message}`)});if(_o==="gui"){let e=await Wc({repoRoot:process.cwd()});d(e)&&(console.error(jt.red(`Failed to start Epiq GUI:
65
- ${e.message}`)),process.exitCode=1)}else{console.clear();let e=await wl();d(e)&&(logger.info(e.message),console.error(jt.red(`Failed to boot Epiq:
66
- ${e.message}`)),process.exitCode=1)}export{ai as renderApp};
62
+ ${Vt.dim("Launch GUI:")}
63
+ ${Vt.cyan("$ epiq gui")}
64
+ `,lv=av(cv,{importMeta:import.meta,version:Wt,flags:{init:{type:"boolean",default:!1}}}),$o=lv.input[0];$o&&$o!=="gui"&&(console.error(Vt.red(`Unknown command: ${$o}`)),process.exit(1));var Ll=process.stdout.columns||120,kl=process.stdout.rows||20,Wo=null,uv=e=>{try{return Wo?(Wo.rerender(e),l("Rerendered app",void 0)):(Wo=iv(e),l("Rendered app",void 0))}catch(t){return a(`Unable to render app: ${Or(t)}`)}},ci=()=>uv(dv.createElement(di,{width:Ll,height:kl}));process.stdout.on("resize",()=>{if(Ll=process.stdout.columns||120,kl=process.stdout.rows||20,!Wo)return;let e=ci();d(e)&&logger.info(`[boot:resize] ${e.message}`)});if($o==="gui"){let e=await jc({repoRoot:process.cwd()});d(e)&&(console.error(Vt.red(`Failed to start Epiq GUI:
65
+ ${e.message}`)),process.exitCode=1)}else{console.clear();let e=await Pl();d(e)&&(logger.info(e.message),console.error(Vt.red(`Failed to boot Epiq:
66
+ ${e.message}`)),process.exitCode=1)}export{ci as renderApp};