epiq 1.4.3 → 1.4.5

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,69 +1,69 @@
1
1
  #!/usr/bin/env node
2
- import cn from"chalk";import{render as Uh}from"ink";import Oh from"meow";import _h from"react";import Ny from"chalk";import Vm from"node:path";import{z as Rt}from"zod";import tr from"node:fs";import vt from"node:path";var Ut={Success:"success",Fail:"fail"},a=e=>({status:Ut.Fail,message:e,value:null}),u=(e,t)=>({status:Ut.Success,message:e,value:t}),d=e=>e.status==="fail",Q=e=>e.status==="success";import Fs from"node:fs";import ft from"node:path";import qn from"node:fs";import{ulid as Im}from"ulid";import{z as _r}from"zod";var Em="__epiq_state__",Sm=_r.object({projectId:_r.string().min(1),stateBranch:_r.string().min(1),createdAt:_r.iso.datetime()}),Cn=()=>({projectId:Im(),stateBranch:Em,createdAt:new Date().toISOString()}),ut=e=>{let t=$r(e);if(!qn.existsSync(t))return a("Missing .epiq/project.json");try{let n=qn.readFileSync(t,"utf8"),r=JSON.parse(n),o=Sm.safeParse(r);return o.success?u("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")}},la=e=>{let t=ut(e);return d(t)?a(t.message):u("Read projectId",t.value.projectId)},ua=({repoRoot:e,fileContents:t})=>{let n=Yn(e),r=$r(e);try{if(qn.mkdirSync(n,{recursive:!0}),qn.existsSync(r)){let o=ut(e);return d(o)?a(o.message):u("Project already initialized",null)}return qn.writeFileSync(r,JSON.stringify(t,null,2)+`
3
- `,"utf8"),u("Created project.json",null)}catch(o){return a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};import Cm from"node:os";import Nm from"node:path";var rt=".epiq-global",Xn=()=>process.env.EPIQ_GLOBAL_DIR??Nm.join(Cm.homedir(),rt);var Ts=(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(l=>(d(l)&&n.delete(i),l));n.set(i,c)}return n.get(i)});return o.clear=()=>n.clear(),o};import Jn from"fs";import Ls from"path";import Rm from"util";var ma=1e3,Am=50,ws=0,pa=()=>process.env.EPIQ_MCP==="true",fa=()=>{let e=process.cwd(),t=Hr(e);return d(t)?pa()?Ls.join(process.cwd(),".epiq-mcp.log"):void 0:Ls.join(t.value,mt,"log","epiq.log")};function Tm(){let e=fa();if(!e||!Jn.existsSync(e))return;let n=Jn.readFileSync(e,"utf8").split(`
4
- `);if(n[n.length-1]===""&&n.pop(),n.length<=ma)return;let r=n.slice(-ma).join(`
2
+ import ln from"chalk";import{render as Hy}from"ink";import Wy from"meow";import jy from"react";import wh from"chalk";import Vm from"node:path";import{z as Tt}from"zod";import er from"node:fs";import ht from"node:path";var _t={Success:"success",Fail:"fail"},a=e=>({status:_t.Fail,message:e,value:null}),u=(e,t)=>({status:_t.Success,message:e,value:t}),d=e=>e.status==="fail",Q=e=>e.status==="success";import Us from"node:fs";import gt from"node:path";import zn from"node:fs";import{ulid as Em}from"ulid";import{z as $r}from"zod";var Sm="__epiq_state__",Cm=$r.object({projectId:$r.string().min(1),stateBranch:$r.string().min(1),createdAt:$r.iso.datetime()}),Cn=()=>({projectId:Em(),stateBranch:Sm,createdAt:new Date().toISOString()}),mt=e=>{let t=Hr(e);if(!zn.existsSync(t))return a("Missing .epiq/project.json");try{let n=zn.readFileSync(t,"utf8"),r=JSON.parse(n),o=Cm.safeParse(r);return o.success?u("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")}},ua=e=>{let t=mt(e);return d(t)?a(t.message):u("Read projectId",t.value.projectId)},ma=({repoRoot:e,fileContents:t})=>{let n=qn(e),r=Hr(e);try{if(zn.mkdirSync(n,{recursive:!0}),zn.existsSync(r)){let o=mt(e);return d(o)?a(o.message):u("Project already initialized",null)}return zn.writeFileSync(r,JSON.stringify(t,null,2)+`
3
+ `,"utf8"),u("Created project.json",null)}catch(o){return a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};import Nm from"node:os";import Rm from"node:path";var rt=".epiq-global",Yn=()=>process.env.EPIQ_GLOBAL_DIR??Rm.join(Nm.homedir(),rt);var ws=(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(l=>(d(l)&&n.delete(i),l));n.set(i,c)}return n.get(i)});return o.clear=()=>n.clear(),o};import Xn from"fs";import ks from"path";import Am from"util";var pa=1e3,Tm=50,Ms=0,fa=()=>process.env.EPIQ_MCP==="true",ga=()=>{let e=process.cwd(),t=Wr(e);return d(t)?fa()?ks.join(process.cwd(),".epiq-mcp.log"):void 0:ks.join(t.value,pt,"log","epiq.log")};function wm(){let e=ga();if(!e||!Xn.existsSync(e))return;let n=Xn.readFileSync(e,"utf8").split(`
4
+ `);if(n[n.length-1]===""&&n.pop(),n.length<=pa)return;let r=n.slice(-pa).join(`
5
5
  `)+`
6
- `;Jn.writeFileSync(e,r,"utf8")}function Ms(e,t,n=!1){let r=fa();if(!r)return;let o=Rm.format(...t),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
7
- `;Jn.mkdirSync(Ls.dirname(r),{recursive:!0}),Jn.appendFileSync(r,c,"utf8"),ws++,ws>=Am&&(ws=0,Tm())}var Ps=()=>pa()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",le={info(...e){let t=Ps();(t==="info"||t==="debug")&&Ms("[Info]",e,!1)},debug(...e){Ps()==="debug"&&Ms("[Debug]",e,!0)},error(...e){let t=Ps();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;Ms("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=le;import{spawn as wm}from"node:child_process";import jr from"node:fs";import Qn from"node:path";var ue={stage:({cwd:e,pathspec:t})=>F({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>F({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>F({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>F({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>F({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 F({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>F({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>F({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>F({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>F({args:["worktree","prune"],cwd:e})};var Nn=e=>{let t=$e(e);if(d(t))return a("Unable to resolve epiq project root");let n=ut(t.value);return d(n)?a("Unable to read project.json"):u("Resolved state branch",n.value.stateBranch)},Je="origin";var ga=1e4,Mm={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},va=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!jr.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=wm("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Mm}),s=!1,i="",c="",l=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 ${ga}ms`].join(`
8
- `);l(n?{stdout:i,stderr:p,exitCode:124}:a(p))},ga);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){l({stdout:i,stderr:p.message,exitCode:1});return}l(a([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
6
+ `;Xn.writeFileSync(e,r,"utf8")}function Ps(e,t,n=!1){let r=ga();if(!r)return;let o=Am.format(...t),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
7
+ `;Xn.mkdirSync(ks.dirname(r),{recursive:!0}),Xn.appendFileSync(r,c,"utf8"),Ms++,Ms>=Tm&&(Ms=0,wm())}var Ls=()=>fa()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",le={info(...e){let t=Ls();(t==="info"||t==="debug")&&Ps("[Info]",e,!1)},debug(...e){Ls()==="debug"&&Ps("[Debug]",e,!0)},error(...e){let t=Ls();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;Ps("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=le;import{spawn as Mm}from"node:child_process";import jr from"node:fs";import Jn from"node:path";var ue={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 Nn=e=>{let t=He(e);if(d(t))return a("Unable to resolve epiq project root");let n=mt(t.value);return d(n)?a("Unable to read project.json"):u("Resolved state branch",n.value.stateBranch)},Je="origin";var va=1e4,Pm={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},ha=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!jr.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=Mm("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Pm}),s=!1,i="",c="",l=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 ${va}ms`].join(`
8
+ `);l(n?{stdout:i,stderr:p,exitCode:124}:a(p))},va);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){l({stdout:i,stderr:p.message,exitCode:1});return}l(a([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
9
9
  `)))}),o.on("close",p=>{let f=p??1;if(n){l({stdout:i,stderr:c,exitCode:f});return}if(f!==0){l(a([`git ${e.join(" ")}`,c.trim()||i.trim()||"Git command failed"].filter(Boolean).join(`
10
- `)));return}l(u("Git command succeeded",{stdout:i,stderr:c,exitCode:f}))})}),F=({args:e,cwd:t})=>va({args:e,cwd:t,allowFail:!1}),pt=({args:e,cwd:t})=>va({args:e,cwd:t,allowFail:!0}),Rn=async({cwd:e,message:t})=>{let n=await ue.commit({cwd:e,message:t});if(d(n))return a(`Failed to create commit
11
- ${n.message}`);let r=await F({args:["rev-parse","HEAD"],cwd:e});return d(r)?a(`Commit created, but failed to read HEAD SHA
12
- ${r.message}`):u("Created commit and resolved SHA",r.value.stdout.trim())},Pm=async e=>{let t=await F({cwd:e,args:["rev-parse","--git-dir"]});if(d(t))return a(t.message);let n=t.value.stdout.trim();return u("Resolved git dir",Qn.isAbsolute(n)?n:Qn.resolve(e,n))},Lm=async e=>{let t=await Pm(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(jr.existsSync(Qn.join(n,s)))return u("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(jr.existsSync(Qn.join(n,s)))return u("Checked for in-progress Git operation",i);return u("Checked for in-progress Git operation",null)},Wr=async e=>{let t=await Lm(e);return d(t)?a(t.message):u("Checked for in-progress Git operation",t.value!==null)},ks=async({repoRoot:e})=>{let n=(await pt({args:["remote","get-url",Je],cwd:e})).exitCode===0;return u(`Checked remote ${n}`,n)},Vr=async({repoRoot:e,branch:t})=>{let n=await pt({args:["ls-remote","--heads",Je,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${Je}/${t}`):u("Checked remote branch",n.stdout.trim().length>0)},Gr=async({repoRoot:e,branch:t})=>{let n=await pt({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?u("Local branch exists",!0):n.exitCode===1?u("Local branch missing",!1):a(n.stderr.trim()||`Unable to inspect branch ${t}`)},Zn=e=>{try{return jr.realpathSync.native(e)}catch{return Qn.resolve(e)}},ya=async({repoRoot:e,worktreeRoot:t})=>{let n=await F({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=Zn(t),o=n.value.stdout.split(`
13
- `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Zn).includes(r);return u("Checked worktree registration",o)},Ds=async e=>{let t=await pt({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return u("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Kr=async e=>{let t=await F({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?a(t.message):u("Resolved current branch",t.value.stdout.trim())},ha=async e=>{let t=await F({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?a(t.message):u("Resolved short HEAD sha",t.value.stdout.trim())},xa=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),km=async e=>(await pt({cwd:e,args:["rebase","--abort"]})).exitCode===0?u("Aborted stale rebase",!0):u("No rebase to abort",!1);var Bs=async({cwd:e,branch:t})=>{let n=await Vr({repoRoot:e,branch:t});if(d(n))return a(n.message);if(!n.value)return u("Remote branch missing, skipped pull",!1);let r=await km(e);if(d(r))return a(r.message);let o=await ue.fetch({cwd:e,remote:Je,branch:t});if(d(o))return a(`Failed to fetch ${t}
10
+ `)));return}l(u("Git command succeeded",{stdout:i,stderr:c,exitCode:f}))})}),U=({args:e,cwd:t})=>ha({args:e,cwd:t,allowFail:!1}),ft=({args:e,cwd:t})=>ha({args:e,cwd:t,allowFail:!0}),Rn=async({cwd:e,message:t})=>{let n=await ue.commit({cwd:e,message:t});if(d(n))return a(`Failed to create commit
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}`):u("Created commit and resolved SHA",r.value.stdout.trim())},Lm=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 u("Resolved git dir",Jn.isAbsolute(n)?n:Jn.resolve(e,n))},km=async e=>{let t=await Lm(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(jr.existsSync(Jn.join(n,s)))return u("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(jr.existsSync(Jn.join(n,s)))return u("Checked for in-progress Git operation",i);return u("Checked for in-progress Git operation",null)},Gr=async e=>{let t=await km(e);return d(t)?a(t.message):u("Checked for in-progress Git operation",t.value!==null)},Ds=async({repoRoot:e})=>{let n=(await ft({args:["remote","get-url",Je],cwd:e})).exitCode===0;return u(`Checked remote ${n}`,n)},Vr=async({repoRoot:e,branch:t})=>{let n=await ft({args:["ls-remote","--heads",Je,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${Je}/${t}`):u("Checked remote branch",n.stdout.trim().length>0)},Kr=async({repoRoot:e,branch:t})=>{let n=await ft({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?u("Local branch exists",!0):n.exitCode===1?u("Local branch missing",!1):a(n.stderr.trim()||`Unable to inspect branch ${t}`)},Qn=e=>{try{return jr.realpathSync.native(e)}catch{return Jn.resolve(e)}},ya=async({repoRoot:e,worktreeRoot:t})=>{let n=await U({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=Qn(t),o=n.value.stdout.split(`
13
+ `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Qn).includes(r);return u("Checked worktree registration",o)},Bs=async e=>{let t=await ft({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return u("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},zr=async e=>{let t=await U({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?a(t.message):u("Resolved current branch",t.value.stdout.trim())},xa=async e=>{let t=await U({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?a(t.message):u("Resolved short HEAD sha",t.value.stdout.trim())},ba=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Dm=async e=>(await ft({cwd:e,args:["rebase","--abort"]})).exitCode===0?u("Aborted stale rebase",!0):u("No rebase to abort",!1);var Fs=async({cwd:e,branch:t})=>{let n=await Vr({repoRoot:e,branch:t});if(d(n))return a(n.message);if(!n.value)return u("Remote branch missing, skipped pull",!1);let r=await Dm(e);if(d(r))return a(r.message);let o=await ue.fetch({cwd:e,remote:Je,branch:t});if(d(o))return a(`Failed to fetch ${t}
14
14
  ${o.message}`);let s=await ue.pullRebase({cwd:e,remote:Je,branch:t});return d(s)?a(`Failed during pull --rebase
15
- ${s.message}`):u("Pulled with rebase",!0)},ba=async e=>{let t=await pt({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?u("No staged changes",!1):t.exitCode===1?u("Has staged changes",!0):a(t.stderr.trim()||"Unable to inspect staged changes")};var Ia=async e=>{let t=await Kr(e);return d(t)?a(t.message):u("Checked detached HEAD state",t.value==="HEAD")};var Sa="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Us=e=>ft.join(mt,Yr,e),Ca=()=>ft.join(mt,Os),Na=Xn,zr=()=>ft.join(Na(),"worktrees"),Re=({repoRoot:e})=>{let t=la(e);return d(t)?a(t.message):u("Resolved state branch root",ft.join(zr(),t.value))},Dm=e=>ft.join(e,mt),Ea=e=>ft.join(Dm(e),Yr);var er=e=>{try{return Fs.mkdirSync(e,{recursive:!0}),u("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},qr=()=>{let e=er(Na());if(d(e))return a(`Ensure epiq home failed.
16
- `+e.message);let t=er(zr());return d(t)?a(`Ensure worktrees dir failed.
17
- `+t.message):u("Ensured epiq storage",!0)},Ra=e=>{Fs.existsSync(e)&&(le.debug("[sync] remove path",e),Fs.rmSync(e,{recursive:!0,force:!0}))};var Aa=(e,t)=>{for(let n of[Ea(e),Ea(t)]){let r=er(n);if(d(r))return a(r.message)}return u("Ensured state branch",void 0)},Ta=async e=>{let t=await F({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return a(`ensure state branch is storage only failed
15
+ ${s.message}`):u("Pulled with rebase",!0)},Ia=async e=>{let t=await ft({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?u("No staged changes",!1):t.exitCode===1?u("Has staged changes",!0):a(t.stderr.trim()||"Unable to inspect staged changes")};var Ea=async e=>{let t=await zr(e);return d(t)?a(t.message):u("Checked detached HEAD state",t.value==="HEAD")};var Ca="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Os=e=>gt.join(pt,Xr,e),Na=()=>gt.join(pt,_s),Ra=Yn,qr=()=>gt.join(Ra(),"worktrees"),Re=({repoRoot:e})=>{let t=ua(e);return d(t)?a(t.message):u("Resolved state branch root",gt.join(qr(),t.value))},Bm=e=>gt.join(e,pt),Sa=e=>gt.join(Bm(e),Xr);var Zn=e=>{try{return Us.mkdirSync(e,{recursive:!0}),u("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},Yr=()=>{let e=Zn(Ra());if(d(e))return a(`Ensure epiq home failed.
16
+ `+e.message);let t=Zn(qr());return d(t)?a(`Ensure worktrees dir failed.
17
+ `+t.message):u("Ensured epiq storage",!0)},Aa=e=>{Us.existsSync(e)&&(le.debug("[sync] remove path",e),Us.rmSync(e,{recursive:!0,force:!0}))};var Ta=(e,t)=>{for(let n of[Sa(e),Sa(t)]){let r=Zn(n);if(d(r))return a(r.message)}return u("Ensured state branch",void 0)},wa=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!==mt);if(r.length===0)return u("State branch is storage-only",!1);let o=await F({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return a(`Failed to clean storage branch
20
- ${o.message}`);let s=await Rn({cwd:e,message:"[epiq:repair-storage-branch]"});return d(s)?a(s.message):u("Cleaned storage branch",!0)},gt=Ts(async(e=process.cwd())=>{let t=await F({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?a("Not inside a Git repository"):u("Resolved repo root",t.value.stdout.trim())},e=>ft.resolve(e)),Dx=Ts(async e=>{let t=await F({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return a(t.message);let n=t.value.stdout.trim(),r=ft.isAbsolute(n)?n:ft.join(e,n);return u("Resolved git dir",r)},e=>ft.resolve(e));var Hx=process.env.IS_LOCAL==="true",mt=".epiq",Yr="events",Os="media",Bm="project.json",Yn=e=>vt.join(e,mt),$r=e=>vt.join(Yn(e),Bm),nr=e=>vt.join(Yn(e),Yr),rr=e=>vt.join(Yn(e),Os),wa=e=>vt.join(e,mt),Fm=e=>{let t=vt.join(e,mt);return tr.existsSync(t)&&tr.statSync(t).isDirectory()},_s=e=>{let t=$r(e);return tr.existsSync(t)&&tr.statSync(t).isFile()},Hr=e=>{let t=vt.resolve(e);for(;;){if(Fm(t))return u("Resolved closest .epiq root",t);let n=vt.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},$e=e=>{let t=vt.resolve(e);for(;;){if(_s(t))return u("Resolved closest epiq project root",t);let n=vt.dirname(t);if(n===t)return a("No .epiq/project.json found in any parent");t=n}},Ma=e=>{let t=nr(e);try{return tr.mkdirSync(t,{recursive:!0}),u("Resolved events dir",t)}catch(n){return a(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},yt=async()=>{let e=await gt(process.cwd());if(d(e))return e;let t=Re({repoRoot:e.value});return d(t)?t:u("Resolved persist root",t.value)};import{accessSync as Um,copyFileSync as Om,existsSync as Xr,mkdirSync as Pa,readdirSync as La,readFileSync as _m,renameSync as $m,rmSync as Hm,statSync as ka,unlinkSync as jm,writeFileSync as Wm}from"node:fs";import An from"node:path";var $s=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",be={writeToFile:(e,t)=>{try{let n=An.dirname(e);Xr(n)||Pa(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Wm(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return _m(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=be.readFile(e);return t===null?null:JSON.parse(t)}catch(t){return logger.error(`Failed to read JSON at ${e}:`,t),null}},dirExists:e=>{try{return Xr(e)&&ka(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Um(e),!0}catch{return!1}},mkDir:e=>Pa(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=An.parse(t);for(;;){let r=An.join(t,e);try{if(Xr(r)&&ka(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=An.dirname(t)}return null},readFirstJSON(e){try{if(!be.dirExists(e))return null;let t=La(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=An.join(e,t);return be.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return be.dirExists(e)?La(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{jm(e)}catch(t){(!$s(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Hm(e,{recursive:!0,force:!0})}catch(t){(!$s(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(An.dirname(t)),!n?.overwrite&&Xr(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{$m(e,t)}catch(r){if($s(r)&&r.code==="EXDEV"){Om(e,t),this.rmFile(e);return}throw r}}};var Gm={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},Da=Rt.object({logLevel:Rt.enum(["info","error","debug"]),preferredEditor:Rt.string().optional(),userName:Rt.string().optional(),userId:Rt.string().optional(),autoSync:Rt.boolean().nullable().optional(),autoSyncDebounceMs:Rt.number().optional(),attachmentMaxKb:Rt.number().optional(),viewMode:Rt.enum(["dense","wide"]).optional()}).partial(),Km="config.json",Ba=Xn,Hs=()=>Vm.join(Ba(),Km),js=()=>{try{return be.mkDir(Ba()),u(`Ensured ~/${rt} exists`,null)}catch{return a(`Unable to create ~/${rt}`)}},zm=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${rt}/config.json JSON`)}let n=Da.safeParse(t??{});return n.success?u("Parsed config",n.data):a(`Invalid ~/${rt}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Jr=()=>{let e=js();if(d(e))return a(e.message);let t=Hs(),n=be.readFile(t);return n==null||n.trim()===""?u("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):zm(n)},Fa=e=>{let t=js();if(d(t))return a(t.message);let n=Da.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Hs();try{return be.writeToFile(r,JSON.stringify(n.data,null,2)+`
21
- `),u("Config written",null)}catch{return a(`Unable to write ~/${rt}/config.json`)}},Qe=e=>{let t=Jr();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return Fa(n)},Ot=()=>{let e=Hs(),t=js();if(d(t))return a(`Unable to create ~/${rt}`);if(!(be.readFile(e)!==null)){let g=Fa(Gm);if(d(g))throw new Error(`Unable to create ~/${rt}/config.json`)}let r=Jr();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:c,autoSyncDebounceMs:l,attachmentMaxKb:m,logLevel:p,viewMode:f}=r.value;return!s||!i?a(`User name or ID not configured in ~/${rt}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,u("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:s,userId:i,autoSync:c??!1,autoSyncIntervalMs:l??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))};import{useSyncExternalStore as qm}from"react";var or={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Ws=new Set,Ym=()=>{for(let e of Ws)e()},K=()=>or,Ua=()=>qm(e=>(Ws.add(e),()=>{Ws.delete(e)}),()=>or),Me=e=>(or={...or,...e},Ym(),or);import{spawn as Xm}from"node:child_process";import Vs from"node:process";var Oa=e=>{let t=Vs.platform==="darwin"?"open":Vs.platform==="win32"?"cmd":"xdg-open",n=Vs.platform==="win32"?["/c","start","",e]:[e];Xm(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as Tu}from"node:fs/promises";import gy from"node:http";import Sn from"node:path";import{fileURLToPath as vy}from"node:url";import{decodeTime as eu,ulid as q}from"ulid";import ln from"node:fs";import Qr from"node:path";var $a=async e=>{if((await pt({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return u("Initial commit already exists",!1);le.info("Creating initial commit");let n=await ue.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?a(n.message):u("Created initial commit",!0)},_a=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Jm=async e=>{let t=await Kr(e);if(d(t))return a(t.message);let n=await ha(e);return d(n)?a(n.message):u("Built sync commit message",`[sync|branch:${_a(t.value)}:sha:${_a(n.value)}]`)},Gs=async({repoRoot:e,stateBranchName:t})=>{le.info(`Creating ${t}`);let n=await F({args:["commit-tree",Sa,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return a(`Failed to create state branch commit
22
- ${n.message}`);let r=n.value.stdout.trim(),o=await F({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return d(o)?a(`Failed to create ${t}
23
- ${o.message}`):u("Created state branch",!0)},Qm=async({repoRoot:e,stateBranchName:t})=>{let n=await ks({repoRoot:e});if(d(n))return a(`Ensure local state branch failed
19
+ `).filter(Boolean).filter(i=>i!==pt);if(r.length===0)return u("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 Rn({cwd:e,message:"[epiq:repair-storage-branch]"});return d(s)?a(s.message):u("Cleaned storage branch",!0)},vt=ws(async(e=process.cwd())=>{let t=await U({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?a("Not inside a Git repository"):u("Resolved repo root",t.value.stdout.trim())},e=>gt.resolve(e)),Ox=ws(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=gt.isAbsolute(n)?n:gt.join(e,n);return u("Resolved git dir",r)},e=>gt.resolve(e));var Vx=process.env.IS_LOCAL==="true",pt=".epiq",Xr="events",_s="media",Fm="project.json",qn=e=>ht.join(e,pt),Hr=e=>ht.join(qn(e),Fm),tr=e=>ht.join(qn(e),Xr),nr=e=>ht.join(qn(e),_s),Ma=e=>ht.join(e,pt),Um=e=>{let t=ht.join(e,pt);return er.existsSync(t)&&er.statSync(t).isDirectory()},$s=e=>{let t=Hr(e);return er.existsSync(t)&&er.statSync(t).isFile()},Wr=e=>{let t=ht.resolve(e);for(;;){if(Um(t))return u("Resolved closest .epiq root",t);let n=ht.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},He=e=>{let t=ht.resolve(e);for(;;){if($s(t))return u("Resolved closest epiq project root",t);let n=ht.dirname(t);if(n===t)return a("No .epiq/project.json found in any parent");t=n}},Pa=e=>{let t=tr(e);try{return er.mkdirSync(t,{recursive:!0}),u("Resolved events dir",t)}catch(n){return a(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},yt=async()=>{let e=await vt(process.cwd());if(d(e))return e;let t=Re({repoRoot:e.value});return d(t)?t:u("Resolved persist root",t.value)};import{accessSync as Om,copyFileSync as _m,existsSync as Jr,mkdirSync as La,readdirSync as ka,readFileSync as $m,renameSync as Hm,rmSync as Wm,statSync as Da,unlinkSync as jm,writeFileSync as Gm}from"node:fs";import An from"node:path";var Hs=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",be={writeToFile:(e,t)=>{try{let n=An.dirname(e);Jr(n)||La(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Gm(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return $m(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=be.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 Jr(e)&&Da(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Om(e),!0}catch{return!1}},mkDir:e=>La(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=An.parse(t);for(;;){let r=An.join(t,e);try{if(Jr(r)&&Da(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=An.dirname(t)}return null},readFirstJSON(e){try{if(!be.dirExists(e))return null;let t=ka(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=An.join(e,t);return be.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return be.dirExists(e)?ka(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{jm(e)}catch(t){(!Hs(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Wm(e,{recursive:!0,force:!0})}catch(t){(!Hs(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(An.dirname(t)),!n?.overwrite&&Jr(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Hm(e,t)}catch(r){if(Hs(r)&&r.code==="EXDEV"){_m(e,t),this.rmFile(e);return}throw r}}};var Km={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},Ba=Tt.object({logLevel:Tt.enum(["info","error","debug"]),preferredEditor:Tt.string().optional(),userName:Tt.string().optional(),userId:Tt.string().optional(),autoSync:Tt.boolean().nullable().optional(),autoSyncDebounceMs:Tt.number().optional(),attachmentMaxKb:Tt.number().optional(),viewMode:Tt.enum(["dense","wide"]).optional()}).partial(),zm="config.json",Fa=Yn,Ws=()=>Vm.join(Fa(),zm),js=()=>{try{return be.mkDir(Fa()),u(`Ensured ~/${rt} exists`,null)}catch{return a(`Unable to create ~/${rt}`)}},qm=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${rt}/config.json JSON`)}let n=Ba.safeParse(t??{});return n.success?u("Parsed config",n.data):a(`Invalid ~/${rt}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Qr=()=>{let e=js();if(d(e))return a(e.message);let t=Ws(),n=be.readFile(t);return n==null||n.trim()===""?u("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):qm(n)},Ua=e=>{let t=js();if(d(t))return a(t.message);let n=Ba.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Ws();try{return be.writeToFile(r,JSON.stringify(n.data,null,2)+`
21
+ `),u("Config written",null)}catch{return a(`Unable to write ~/${rt}/config.json`)}},Qe=e=>{let t=Qr();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return Ua(n)},$t=()=>{let e=Ws(),t=js();if(d(t))return a(`Unable to create ~/${rt}`);if(!(be.readFile(e)!==null)){let g=Ua(Km);if(d(g))throw new Error(`Unable to create ~/${rt}/config.json`)}let r=Qr();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:c,autoSyncDebounceMs:l,attachmentMaxKb:m,logLevel:p,viewMode:f}=r.value;return!s||!i?a(`User name or ID not configured in ~/${rt}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,u("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:s,userId:i,autoSync:c??!1,autoSyncIntervalMs:l??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))};import{useSyncExternalStore as Ym}from"react";var rr={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Gs=new Set,Xm=()=>{for(let e of Gs)e()},K=()=>rr,Oa=()=>Ym(e=>(Gs.add(e),()=>{Gs.delete(e)}),()=>rr),Me=e=>(rr={...rr,...e},Xm(),rr);import{spawn as Jm}from"node:child_process";import Vs from"node:process";var _a=e=>{let t=Vs.platform==="darwin"?"open":Vs.platform==="win32"?"cmd":"xdg-open",n=Vs.platform==="win32"?["/c","start","",e]:[e];Jm(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as wu}from"node:fs/promises";import xh from"node:http";import Sn from"node:path";import{fileURLToPath as bh}from"node:url";import{decodeTime as tu,ulid as q}from"ulid";import un from"node:fs";import Zr from"node:path";var Ha=async e=>{if((await ft({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return u("Initial commit already exists",!1);le.info("Creating initial commit");let n=await ue.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?a(n.message):u("Created initial commit",!0)},$a=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Qm=async e=>{let t=await zr(e);if(d(t))return a(t.message);let n=await xa(e);return d(n)?a(n.message):u("Built sync commit message",`[sync|branch:${$a(t.value)}:sha:${$a(n.value)}]`)},Ks=async({repoRoot:e,stateBranchName:t})=>{le.info(`Creating ${t}`);let n=await U({args:["commit-tree",Ca,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return a(`Failed to create state branch commit
22
+ ${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}
23
+ ${o.message}`):u("Created state branch",!0)},Zm=async({repoRoot:e,stateBranchName:t})=>{let n=await Ds({repoRoot:e});if(d(n))return a(`Ensure local state branch failed
24
24
  `+n.message);let r=n.value,o=r?await Vr({repoRoot:e,branch:t}):u("No remote, no remote state branch",!1);if(d(o))return a(`Ensure local state branch failed
25
25
  `+o.message);let s=o.value;if(r&&s){let c=await ue.fetch({cwd:e,remote:Je,branch:t});if(d(c))return a(`Failed to fetch ${t} from remote
26
- ${c.message}`)}let i=await Gr({repoRoot:e,branch:t});if(d(i))return a(`Ensure local state branch failed
27
- `+i.message);if(i.value)return u("Local state branch already exists",!1);if(s){let c=await F({args:["branch","--track",t,`${Je}/${t}`],cwd:e});return d(c)?a(`Failed to create local ${t} from remote
28
- ${c.message}`):u("Created local state branch from remote",!0)}return Gs({repoRoot:e,stateBranchName:t})},Zm=async({repoRoot:e,branch:t})=>{let n=await F({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=n.value.stdout.split(`
29
- `),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return u("Found worktree for branch",o)}return u("No worktree found for branch",null)},ep=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=er(Qr.dirname(t));if(d(r))return a(`Failed to create state branch worktree
30
- `+r.message);ln.existsSync(t)&&!ln.existsSync(Qr.join(t,".git"))&&(le.info("Removing broken state branch worktree path"),Ra(t)),le.info("Creating state branch worktree");let o=await ue.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(o)?a(`Failed to create state branch worktree
31
- ${o.message}`):u("Created state branch worktree",!0)},un=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await Zm({repoRoot:e,branch:n});if(d(r))return a(r.message);let o=Zn(t),s=r.value?Zn(r.value):null;if(s&&s===o&&ln.existsSync(s))return u("State branch already checked out in expected worktree",!1);if(s&&s!==o){le.info("Moving state branch worktree to expected location");let l=await ue.worktreeRemove({cwd:e,worktreeRoot:s});if(d(l))return a(`Failed to remove existing state branch worktree
32
- ${l.message}`)}if(s&&!ln.existsSync(s)){le.info("Pruning stale state branch worktree");let l=await ue.worktreePrune({cwd:e});if(d(l))return a(`Failed to prune stale worktrees
33
- ${l.message}`)}let i=await ya({repoRoot:e,worktreeRoot:t});if(d(i))return a(i.message);let c=ln.existsSync(t);if(i.value&&c)return u("State branch worktree already exists",!1);if(i.value&&!c){le.info("Pruning missing registered state branch worktree");let l=await ue.worktreePrune({cwd:e});if(d(l))return a(`Failed to prune stale worktrees
34
- ${l.message}`)}return ep({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},tp=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Kr(e);if(d(n))return a(n.message);if(n.value===t)return u("State branch already checked out",!1);(await pt({cwd:e,args:["rebase","--abort"]})).exitCode===0&&le.info("Aborted stale state branch rebase");let o=await ue.checkout({cwd:e,branch:t});return d(o)?a(`Failed to checkout ${t}
35
- ${o.message}`):u("Checked out state branch",!0)},np=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Ds(t);if(d(n))return a(n.message);if(n.value)return u("State branch upstream already configured",!1);let r=await ks({repoRoot:t});if(d(r))return a(r.message);if(!r.value)return u("No remote available for state branch upstream",!1);let o=Nn(e);if(d(o))return o;let s=o.value,i=await Vr({repoRoot:t,branch:s});if(d(i))return a(i.message);if(!i.value)return u("Remote state branch missing; upstream will be configured on first push",!1);le.info(`Configuring ${s} upstream`);let c=await ue.fetch({cwd:t,remote:Je,branch:s});if(d(c))return a(`Failed to fetch ${s}
26
+ ${c.message}`)}let i=await Kr({repoRoot:e,branch:t});if(d(i))return a(`Ensure local state branch failed
27
+ `+i.message);if(i.value)return u("Local state branch already exists",!1);if(s){let c=await U({args:["branch","--track",t,`${Je}/${t}`],cwd:e});return d(c)?a(`Failed to create local ${t} from remote
28
+ ${c.message}`):u("Created local state branch from remote",!0)}return Ks({repoRoot:e,stateBranchName:t})},ep=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(`
29
+ `),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return u("Found worktree for branch",o)}return u("No worktree found for branch",null)},tp=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Zn(Zr.dirname(t));if(d(r))return a(`Failed to create state branch worktree
30
+ `+r.message);un.existsSync(t)&&!un.existsSync(Zr.join(t,".git"))&&(le.info("Removing broken state branch worktree path"),Aa(t)),le.info("Creating state branch worktree");let o=await ue.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(o)?a(`Failed to create state branch worktree
31
+ ${o.message}`):u("Created state branch worktree",!0)},mn=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await ep({repoRoot:e,branch:n});if(d(r))return a(r.message);let o=Qn(t),s=r.value?Qn(r.value):null;if(s&&s===o&&un.existsSync(s))return u("State branch already checked out in expected worktree",!1);if(s&&s!==o){le.info("Moving state branch worktree to expected location");let l=await ue.worktreeRemove({cwd:e,worktreeRoot:s});if(d(l))return a(`Failed to remove existing state branch worktree
32
+ ${l.message}`)}if(s&&!un.existsSync(s)){le.info("Pruning stale state branch worktree");let l=await ue.worktreePrune({cwd:e});if(d(l))return a(`Failed to prune stale worktrees
33
+ ${l.message}`)}let i=await ya({repoRoot:e,worktreeRoot:t});if(d(i))return a(i.message);let c=un.existsSync(t);if(i.value&&c)return u("State branch worktree already exists",!1);if(i.value&&!c){le.info("Pruning missing registered state branch worktree");let l=await ue.worktreePrune({cwd:e});if(d(l))return a(`Failed to prune stale worktrees
34
+ ${l.message}`)}return tp({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},np=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await zr(e);if(d(n))return a(n.message);if(n.value===t)return u("State branch already checked out",!1);(await ft({cwd:e,args:["rebase","--abort"]})).exitCode===0&&le.info("Aborted stale state branch rebase");let o=await ue.checkout({cwd:e,branch:t});return d(o)?a(`Failed to checkout ${t}
35
+ ${o.message}`):u("Checked out state branch",!0)},rp=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Bs(t);if(d(n))return a(n.message);if(n.value)return u("State branch upstream already configured",!1);let r=await Ds({repoRoot:t});if(d(r))return a(r.message);if(!r.value)return u("No remote available for state branch upstream",!1);let o=Nn(e);if(d(o))return o;let s=o.value,i=await Vr({repoRoot:t,branch:s});if(d(i))return a(i.message);if(!i.value)return u("Remote state branch missing; upstream will be configured on first push",!1);le.info(`Configuring ${s} upstream`);let c=await ue.fetch({cwd:t,remote:Je,branch:s});if(d(c))return a(`Failed to fetch ${s}
36
36
  ${c.message}`);let l=await ue.setUpstream({cwd:t,branch:s,upstream:`${Je}/${s}`});return d(l)?a(`Failed to set state branch upstream
37
- ${l.message}`):u("Configured state branch upstream",!0)},Zr=async({stateBranchRoot:e,eventFileName:t})=>{let n=Us(t),r=Qr.join(e,n);if(!ln.existsSync(r))return u("No event file to stage",void 0);let o=await ue.stage({cwd:e,pathspec:[n]});return d(o)?a(`Failed to stage state branch event file
38
- ${o.message}`):u("Staged state branch event file",void 0)},Ha=async({stateBranchRoot:e})=>{let t=Ca(),n=Qr.join(e,t);if(!ln.existsSync(n))return u("No media directory to stage",void 0);let r=await ue.stage({cwd:e,pathspec:[t]});return d(r)?a(`Failed to stage state branch media files
39
- ${r.message}`):u("Staged state branch media files",void 0)},ja=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Jm(e);return d(n)?a(`Create state branch sync commit failed
40
- `+n.message):Rn({cwd:t,message:n.value})},sr=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Ds(t);if(d(n))return a(n.message);let r=Nn(e);if(d(r))return r;let o=r.value,s=n.value?await ue.push({cwd:t}):await ue.push({cwd:t,remote:Je,branch:o,setUpstream:!0});return d(s)?a(`Failed during state branch push
41
- ${s.message}`):u("Pushed state branch",!0)},Wa=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Nn(e);if(d(o))return o;let s=o.value,i=[qr(),await Qm({repoRoot:e,stateBranchName:s}),await un({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await tp({stateBranchRoot:t,stateBranchName:s}),await Ta(t),n?await np({stateBranchRoot:t,repoRoot:e}):u("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(d(c))return a(c.message);r=r||!!c.value}return u(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{WebSocket as rp}from"ws";var eo=new Set,Va=e=>{eo.add(e),e.on("close",()=>{eo.delete(e)}),e.on("error",()=>{eo.delete(e)})},_t=e=>{let t=JSON.stringify(e);for(let n of eo)n.readyState===rp.OPEN&&n.send(t)};import{useSyncExternalStore as Xv}from"react";var B={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function Ks(e){return e.context===B.WORKSPACE}function T(e){return e.context===B.TICKET}function $t(e){return e.context===B.TEXT}function Ve(e){return e.context===B.FIELD}function ir(e){return e.context===B.FIELD_LIST}var Ht=e=>e.context===B.SWIMLANE,to=e=>e.context===B.BOARD,ar=e=>e.context===B.COMMENT;var y={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var Ga=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Ka=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",za=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",qa=(e,t)=>{if(Ka(e,e.sequence))return x.MoveCursorLeftOfWord;if(za(e,e.sequence))return x.MoveCursorRightOfWord;if(Ga(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.GetLastCommandFromHistory;case"down":return x.GetNextCommandFromHistory;case"left":return x.MoveCursorLeft;case"right":return x.MoveCursorRight;case"return":return x.Confirm;case"backspace":return t?x.EraseInput:x.ExitCommandLine;case"escape":return x.ExitCommandLine;default:return x.CaptureInput}},Ya=(e,t)=>{if(Ka(e,e.sequence))return x.MoveCursorLeftOfWord;if(za(e,e.sequence))return x.MoveCursorRightOfWord;if(Ga(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.NavPreviousItem;case"down":return x.NavNextItem;case"left":return x.MoveCursorLeft;case"right":return x.MoveCursorRight;case"return":return x.Confirm;case"backspace":return t?x.EraseInput:x.ExitCommandLine;case"escape":return x.ExitCommandLine;default:return x.CaptureInput}};function no(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)+"...",Ze=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Xa=e=>e.charAt(0).toUpperCase()+e.slice(1);var Ja=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},Qa=(e,t)=>t?e.get(t)??[]:[];var Za=new WeakMap,op=e=>{let t=Za.get(e);return t||(t=Ja(e),Za.set(e,t)),t};var ed=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Qa(op(e),r).filter(s=>no(r,s)>=n)};var sp={hint:"",hints:[],overlap:0,remainder:""},td=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return sp;let o=ed({wordList:r,inputToMatch:e,overlapThreshold:1});return ip(t,o)},ip=(e,t)=>{let n=t[0]??"",r=no(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,p=(c&&i?o:n)+(c&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}};import{ulid as cp}from"ulid";var Tn=24n,ap=Tn*4n,ot=(1n<<ap)-1n,dp=/^[0-9a-f]+$/;function nd(e){return!e||!dp.test(e)?a(`Invalid hex rank: ${e}`):u("Converted rank to bigint",BigInt("0x"+e))}function Ge(e,t=Tn){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return u("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Ue(e,t){if(!e&&!t)return Ge(ot/2n,Tn);let n=e?nd(e):u("Resolved lower bound",0n);if(d(n))return n;let r=t?nd(t):u("Resolved upper bound",ot);if(d(r))return r;let o=n.value,s=r.value;if(s<=o)return Ge(ot/2n,Tn);let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):Ge(i,Tn)}function rd(e){if(e<=0)return u("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=ot*BigInt(r+1)/(t+1n),s=Ge(o,Tn);if(d(s))return s;n.push(s.value)}return u("Resolved evenly spaced ranks",n)}var zs=(e,t)=>{let n=Y(e),r=rd(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 u("Created rebalance event",{id:cp(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as ff}from"ulid";var ro="removed",Oe=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?u("Found node",n):a("Unable to find node in breadcrumb")},od=["png","jpg","gif","webp"];var At=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return u("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return u("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},qs=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},jt=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:a("Node not found"),S={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=pe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to link contributor to user"):u("Linked contributor to user",r)},deleteNode(e){pe(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(!T(t))return a("Can only comment on issues");let n=pe(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create comment"):u("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(!T(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=pe(i=>({...i,comments:{...i.comments??{},[e]:o}}));return d(s)?a("Unable to edit comment"):u("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=pe(o=>({...o,comments:{...o.comments??{},[e]:n}}));return d(r)?a("Unable to delete comment"):u("Deleted comment",n)},getComment(e){return v().comments?.[e]},getCommentsByIssue(e){return Object.values(v().comments??{}).filter(t=>t.issue===e&&!t.deleted)},createAttachment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create attachment, missing issue");if(!T(t))return a("Can only attach to issues");let n=pe(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create attachment"):u("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return a("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=pe(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return d(r)?a("Unable to delete attachment"):u("Deleted attachment",n)},getAttachment(e){return v().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(v().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return a("Edit target node not found");let o=jt(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),u("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return a("Rename target node not found");let r=jt(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),u("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return Y(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),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=jt(o,"move");if(i)return i;if(qs(t,e))return a("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),u("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=jt(o,"delete");if(s)return s;let i=new Set,c=m=>{let p=t[m];if(!(!p||i.has(m))){i.add(m);for(let f of Y(p.id))c(f.id)}};c(e);let l={...structuredClone(t)};for(let m of i){if(!l[m])return a("Unable to locate node to delete");l[m]={...l[m],isDeleted:!0}}return n?(C({nodes:l}),u("Successfully tomb stoned",o)):a("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return a("Contributor not found");let n={...t,name:ro,tombstoned:!0},r=pe(o=>({...o,contributors:{...o.contributors,[e]:n}}));return d(r)?a("Unable to remove contributor"):u("Tombstoned contributor",n)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");let r={...n,name:t,tombstoned:!1},o=pe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to restore contributor"):u("Restored contributor",r)},createContributor(e){let t=pe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):u("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=jt(r,"edit");if(o)return o;if(!T(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),u("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=jt(r,"edit");if(o)return o;if(!T(r))return a("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return u("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),u("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=jt(r,"edit");if(o)return o;if(!T(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),u("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=jt(r,"edit");if(o)return o;if(!T(r))return a("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return u("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),u("Tag removed",{tag:t})},createTag(e){let t=pe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):u("Tag created",e)},createNode(e){let t=pe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?a("Unable to create node"):u("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=pe(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):u("Locked node",n)},updateNode(e){let t=pe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:u("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return Y(e)}};var Z={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var He=e=>e.slice(-7).toUpperCase(),sd=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?He(e).includes(n):!0};var ee={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:B.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:He(e)},context:B.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:B.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:B.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:B.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:He(e)},context:B.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:B.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:B.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};import Wt from"chalk";import ud from"string-width";import{decodeTime as gp}from"ulid";import Mn from"chalk";var Pe={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},h={accent:Pe.cyan,accent2:Pe.magenta,primary:Pe.white,secondary:Pe.grayDark,secondary2:Pe.grayLight,gray:Pe.gray,green:Pe.green,yellow:Pe.yellow,red:Pe.red};var N={red:Pe.red,yellow:Pe.yellow,green:Pe.green,blue:Pe.blue,magenta:Pe.magenta,cyan:Pe.cyan},wn={urgent:N.red,critical:N.red,important:N.red,blocker:N.red,asap:N.red,immediate:N.red,fail:N.red,failure:N.red,broken:N.red,bug:N.red,error:N.red,incident:N.red,outage:N.red,production:N.red,crash:N.red,security:N.red,warning:N.yellow,warn:N.yellow,risky:N.yellow,risk:N.yellow,attention:N.yellow,pending:N.yellow,review:N.yellow,"needs-review":N.yellow,qa:N.yellow,testing:N.yellow,test:N.yellow,validate:N.yellow,verification:N.yellow,staging:N.yellow,check:N.yellow,"follow-up":N.yellow,followup:N.yellow,waiting:N.yellow,blocked:N.yellow,hold:N.yellow,done:N.green,complete:N.green,completed:N.green,success:N.green,ok:N.green,stable:N.green,resolved:N.green,fixed:N.green,closed:N.green,merged:N.green,released:N.green,deployed:N.green,approved:N.green,verified:N.green,working:N.green,healthy:N.green,pass:N.green,passing:N.green,info:N.blue,information:N.blue,note:N.blue,docs:N.blue,documentation:N.blue,doc:N.blue,guide:N.blue,help:N.blue,explanation:N.blue,detail:N.blue,details:N.blue,context:N.blue,design:N.blue,discussion:N.blue,proposal:N.blue,idea:N.blue,feature:N.magenta,enhancement:N.magenta,improvement:N.magenta,refactor:N.magenta,refactoring:N.magenta,cleanup:N.magenta,optimize:N.magenta,optimization:N.magenta,perf:N.magenta,performance:N.magenta,upgrade:N.magenta,migration:N.magenta,modernize:N.magenta,debt:N.magenta,todo:N.cyan,next:N.cyan,planned:N.cyan,plan:N.cyan,future:N.cyan,backlog:N.cyan,investigate:N.cyan,explore:N.cyan,prototype:N.cyan};var Xs={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},id=(e,t,n)=>Math.max(t,Math.min(n,e)),Ys=(e,t,n)=>e+(t-e)*n,ad=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},lp=e=>e.toLowerCase().trim(),up=(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)),l=0,m=0,p=0;i>=0&&i<1?(l=s,m=c):i>=1&&i<2?(l=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<5?(l=c,p=s):(l=s,p=c);let f=o-s/2;return[Math.round((l+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},dd=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var mp=(e,t,n)=>{let r=id(n,0,1);return[Math.round(Ys(e[0],t[0],r)),Math.round(Ys(e[1],t[1],r)),Math.round(Ys(e[2],t[2],r))]};var pp=(e,t,n)=>mp(e,t,n),dr=e=>{let t=ad(e)%360,n=up(t,Xs.stringColor.saturation,Xs.stringColor.lightness);return dd(n)},te=(e,t=wn)=>{let n=lp(e);return n&&t[n]?t[n]:dr(n)};var cd=e=>{let t=Xs.gradient.stops,n=id(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 pp(t[s],t[s+1],i)},oo=e=>dd(cd(e)),so=e=>ad(e.toLowerCase().trim())/4294967295,ld=e=>{let t=so(e);return cd(t)},fp=e=>{let[t,n,r]=ld(e);return{normal:o=>Mn.bgRgb(t,n,r).black(o),cursor:o=>Mn.bgRgb(t,n,r).white.bold(o)}},Js=e=>{let[t,n,r]=ld(e);return{fg:o=>Mn.rgb(t,n,r)(o),fgCursor:o=>Mn.rgb(t,n,r).inverse(o),bg:o=>Mn.bgRgb(t,n,r).black(o),bgCursor:o=>Mn.bgRgb(t,n,r).white.bold(o)}},io=e=>fp(e).normal(` ${e} `);var Pn=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"},ao=e=>String(e).padStart(2,"0"),co=e=>`${e.getFullYear()}-${ao(e.getMonth()+1)}-${ao(e.getDate())} ${ao(e.getHours())}:${ao(e.getMinutes())}`;var vp=(e,t)=>e+" ".repeat(Math.max(0,t-ud(e))),yp=(e,t)=>" ".repeat(Math.max(0,t-ud(e)))+e,lo=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","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","create.contributor":"Added contributor","link.contributor.user":"Linked contributor","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),hp=(e,t)=>t?e<t?"up":e>t?"down":null:null,xp=(e,t)=>{let n=S.getNode(e.payload.parent),r=n?Wt.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=hp(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},md=e=>`${Math.max(1,Math.round(e/1024))} KB`,pd=e=>S.getAttachment(e)?.name??"",bp=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?Wt.bgHex(te(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?Wt.bgHex(te(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Wt.hex(te(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Wt.hex(te(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:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Wt.dim(`(${md(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=pd(e.payload.id);return t?`"${t}"`:""}default:return""}},Ip=e=>{let t=Pn(gp(e));return Wt.gray(yp(t,8))},Ep=12,Sp=e=>vp(`${e}`,Ep),Cp=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=v().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=S.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${md(e.payload.bytes)})`;case"delete.issue.attachment":{let t=pd(e.payload.id);return t?`"${t}"`:""}default:return""}},fd=e=>[lo(e.action),Cp(e)].filter(Boolean).join(" "),gd=(e,t)=>{let n=Ip(e.id),r=Sp(e.userName),o=Wt.dim("\u203A"),s=e.action==="move.node"?xp(e,t):[lo(e.action),bp(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};import{createHash as Np}from"node:crypto";var Rp="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ap=e=>{let t=Np("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+=Rp[Number(n>>s&31n)]}return r},Ie=(e,t)=>Ap(`${e}:virtual:${t}`);var Tp=e=>Ie(e,"comments"),wp=e=>Ie(e,"description"),Mp=e=>Ie(e,"assignees"),Pp=e=>Ie(e,"tags"),Lp=e=>Ie(e,"history"),kp=e=>Ie(e,"attachments"),uo=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=S.getNode(e);if(!c){let p=S.createNode({...ee.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:u("Virtual field created",void 0)}if(!Ve(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 u("Virtual field unchanged",void 0);let m=S.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return d(m)?m:u("Virtual field updated",void 0)},vd=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=S.getNode(e);if(!i){let m=S.createNode({...ee.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return d(m)?m:u("Virtual field list created",void 0)}if(!ir(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 u("Virtual field list unchanged",void 0);let l=S.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return d(l)?l:u("Virtual field list updated",void 0)},yd=e=>{let t=Ge(ot/4n),n=Ge(ot/2n),r=Ge(ot*3n/4n),o=Ge(ot*7n/8n),s=Ge(ot*15n/16n),i=Ge(ot*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;if(d(i))return i;let c=uo({id:wp(e.id),name:Z.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(c))return c;let l=vd({id:Mp(e.id),name:Z.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(l))return l;let m=vd({id:Pp(e.id),name:Z.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(m))return m;let p=uo({id:Tp(e.id),name:Z.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(p))return p;let f=uo({id:kp(e.id),name:Z.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(d(f))return f;let g=uo({id:Lp(e.id),name:Z.HISTORY,parentNodeId:e.id,rank:i.value,value:Dp(e),readonly:!0,childRenderAxis:"vertical"});return d(g)?g:u("Ticket virtual nodes materialized",void 0)},Dp=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=>gd(r,n.get(r.action)??[])).join(`
42
- `)};var Bp=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ve,mo]=Bp;var L=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),hd=e=>{let t=S.getNode(e);if(!t||!T(t)||t.isDeleted)return null;let n=yd(t);return d(n)?n:null},Fp=e=>{for(let t of e){let n=hd(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=hd(r);if(o)return o}return null},Up=(e,t)=>{let n=S.getNode(e);n&&S.updateNode({...n,log:[...n.log??[],t]})},Op=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},Qs=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":case"add.issue.attachment":case"delete.issue.attachment":return[e.payload.issue];case"delete.node":case"edit.description":return Op(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[]}},_p=e=>{pe(t=>({...t,eventLog:[...t.eventLog,e]}))},$p=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?L("Invalid user ID format",e):u("Valid user",null)},Hp=(e,t)=>{let n=$p(e);if(d(n))return n;let r=[...new Set(Qs(e))];t||(r.forEach(s=>Up(s,e)),_p(e));let o=Fp(r);return o||null},jp={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=ee.workspace(t,n,r),s=cr(o);if(d(s))return L(s.message,e);let i=S.createNode(o);return d(i)?L(i.message??"Failed to initialize workspace",e):Ks(i.value)?u("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=S.createNode(ee.workspace(t,n,r));return d(o)?L(o.message??"Failed to add workspace",e):Ks(o.value)?u("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=S.createNode(ee.board(t,n,r,o));return d(s)?L(s.message??"Unable to create board",e):to(s.value)?u("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=S.createNode(ee.swimlane(t,n,r,o));return d(s)?L(s.message??"Unable to create swimlane",e):Ht(s.value)?u("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=S.createNode(ee.ticket(t,n,r,o));return d(s)?L(s.message??"Unable to create issue",e):T(s.value)?u("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=S.createNode(ee.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(Z.DESCRIPTION)?"vertical":"horizontal"}));return d(i)?L(i.message??`Unable to create field: ${n}`,e):Ve(i.value)?u("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(!S.getNode(t))return L(`Unable to locate node with id ${t}`,e);let o=S.renameNode(t,n);return d(o)?L(o.message??"Unable to edit title",e):u("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=S.tombstoneNode(t);return d(n)?L(n.message??"Unable to delete node",e):u("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=S.createTag({id:t,name:n});return d(r)?L(r.message??"Unable to create tag",e):u("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=S.createContributor({id:t,name:n});return d(r)?L(r.message??"Unable to create contributor",e):u("Contributor created",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=S.tombstoneContributor(t);return d(n)?L(n.message??"Unable to remove contributor",e):u("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,r=S.restoreContributor(t,n);return d(r)?L(r.message??"Unable to restore contributor",e):u("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=S.tag(t,n);return d(r)?L(r.message??"Unable to tag issue",e):u("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=S.untag(t,n);return d(r)?L(r.message??"Unable to untag issue",e):u("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=S.assign(t,n);return d(r)?L(r.message??"Unable to assign issue",e):u("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=S.unassign(t,n);return d(r)?L(r.message??"Unable to unassign issue",e):u("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=S.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?L(o.message??"Failed to move node",e):u("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=S.editValue(t,n);return d(r)?L(r.message??"Unable to edit description",e):u("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=S.getNode(t);if(!o)return L("Unable to locate issue",e);if(!T(o))return L("Can only close issues",e);let s=S.getNode(ve);if(!s)return L("Unable to locate target swimlane",e);if(n!==s.id)return L("Close target must be closed swimlane",e);let i=S.moveNodeToRank({id:t,parentId:n,rank:r});return d(i)?L(i.message??"Unable to close issue",e):u("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=S.getNode(t);if(!o)return L("Unable to locate issue",e);if(!T(o))return L("Can only reopen issues",e);let s=S.getNode(ve);if(!s)return L("Unable to locate closed swimlane",e);if(n===s.id)return L("Cannot reopen issue into closed swimlane",e);if(!S.getNode(n))return L("Reopen parent no longer exists",e);let c=S.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?L(c.message??"Unable to reopen issue",e):u("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=S.lockNode(t);return d(n)?L(n.message??"Unable to lock node",e):u("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=S.getNode(r);if(!s)return L(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return L(`Node ${r} is not child of ${t}`,e);let i=S.updateNode({...s,rank:o});if(d(i))return L(i.message??"Unable to rebalance child",e)}return u("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=S.createComment({id:t,issue:n,authorId:r,authorName:S.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return d(s)?L(s.message??"Unable to add comment",e):u("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=S.getComment(t);if(!o)return L("Unable to locate comment",e);if(o.issue!==n)return L("Comment does not belong to issue",e);let s=S.editComment(t,r);return d(s)?L(s.message??"Unable to edit comment",e):u("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=S.getComment(t);if(!r)return L("Unable to locate comment",e);if(r.issue!==n)return L("Comment does not belong to issue",e);let o=S.deleteComment(t);return d(o)?L(o.message??"Unable to delete comment",e):u("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:r,ext:o,name:s,bytes:i}=e.payload,c=S.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return d(c)?L(c.message??"Unable to add attachment",e):u("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=S.getAttachment(t);if(!r)return L("Unable to locate attachment",e);if(r.issue!==n)return L("Attachment does not belong to issue",e);let o=S.deleteAttachment(t);return d(o)?L(o.message??"Unable to delete attachment",e):u("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=S.linkUserId({contributorId:t,userId:e.userId});return d(n)?L(n.message??"Unable to link contributor",e):u("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function Vt(e,t=!1){let n=jp[e.action];if(!n)return a(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);let r=n(e);if(d(r))return r;let o=Hp(e,t);return o||r}var st=e=>{let t=xd(()=>e.map(n=>Vt(n)));return d(t)?e.map(()=>a(t.message)):t.value};import rf from"node:fs";import of from"node:path";import{decodeTime as sf,monotonicFactory as af}from"ulid";import{z as ur}from"zod";var lr=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown";import po from"node:fs";import ei from"node:path";import{decodeTime as Gp}from"ulid";import{z as Zs}from"zod";var Wp=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","create.contributor","tombstone.contributor","restore.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","move.node","edit.description","add.issue.comment","edit.issue.comment","delete.issue.comment","add.issue.attachment","delete.issue.attachment","close.issue","reopen.issue","lock.node","rebalance.children","link.contributor.user"];var Vp=new Set(Wp),bd=e=>Vp.has(e),Id=e=>({action:e.action,payload:e.payload});var Kp=Zs.object({userId:Zs.string().min(1).default("unknown"),userName:Zs.string().min(1).default("unknown")}),zp=/^[0-9a-hjkmnp-tv-z]{26}$/i,qp=e=>zp.test(e)?e.toUpperCase():e,Yp=e=>{let t=ei.basename(e,".jsonl"),n=t.indexOf("."),r=n===-1?t:t.slice(0,n),o=n===-1?void 0:t.slice(n+1),s=Kp.safeParse({userId:qp(r),userName:o});return s.success?u("Parsed event file actor",s.data):a(`Invalid event file name ${ei.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},Xp=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"):u("Resolved persisted action",t[0])},Jp=(e,t)=>t in e,Qp=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Zp=e=>{let{userId:t,userName:n,...r}=e,o=Xp(r);if(d(o))return a(o.message);let s=o.value,i=e.id?.[0];return i?Jp(r,s)?u("Decoded persisted event",Qp({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")},ti=e=>{let t=[],n=new Map;for(let r of e){let o=Zp(r);if(d(o))return a(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);let s=o.value.action;if(!bd(s)){n.set(s,(n.get(s)??0)+1);continue}t.push(o.value)}if(n.size>0){let r=[...n.entries()].map(([o,s])=>`${o} (x${s})`).join(", ");le.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${r}. Upgrade to apply them.`)}return u("Decoded reconstructed events",t)},ef=e=>{if(!po.existsSync(e))return u("Event file missing",[]);let t=Yp(e);if(d(t))return a(t.message);let n=po.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
43
- `)){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=ri(i);if(d(c))return a(`${c.message} in ${e}: ${s}`);r.push({...c.value,userId:t.value.userId,userName:t.value.userName})}return u("Parsed persisted events file",r)};function ni(e){let t=nr(e);if(!po.existsSync(t))return u("No events found",[]);let n=po.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>ei.join(t,o)),r=[];for(let o of n){let s=ef(o);if(d(s))return a(s.message);r.push(...s.value)}return u("All events loaded",tf(r))}function je(e){let t=ni(e);return d(t)?a(t.message):ti(t.value)}function fo(e,t){let n=ni(e);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=nf(n.value,t),s=ti(r);if(d(s))return a(s.message);let i=ti(o);return d(i)?a(i.message):u("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:i.value})}function Ed(e=process.cwd()){let t=ni(e);return d(t)?a(t.message):u("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var tf=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],f=m.id[1]??null;t.set(p,m);let g=n.get(f)??[];g.push(m),n.set(f,g)}for(let m of n.values())m.sort((p,f)=>p.id[0].localeCompare(f.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 f=n.get(p)??[];for(let g of f)s(g)},i=n.get(null)??[];for(let m of i)s(m);let c=e.filter(m=>{let p=m.id[0],f=m.id[1]??null;return!o.has(p)&&f!==null&&!t.has(f)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of c)s(m);let l=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of l)s(m);return r},nf=(e,t)=>{let n=new Set,r=[],o=[];for(let s of e){let i=s.id[0],c=s.id[1],l=!1;try{l=Gp(i)<t}catch{l=!1}!l||c&&n.has(c)?(n.add(i),o.push(s)):r.push(s)}return{appliedEvents:r,unappliedEvents:o}};var Cd=1,Sd=af(),df=ur.tuple([ur.string().min(1),ur.string().min(1).nullable()]),cf=ur.looseObject({v:ur.literal(Cd),id:df}),ri=e=>{let t=cf.safeParse(e);return t.success?u("Parsed persisted event",t.data):a(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},lf=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),uf=e=>e.trim().length>0&&e.length<=80,ae=()=>{let{userName:e,userId:t}=K();return e?t?lf(t)?uf(e)?u("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")},pn=({userId:e,userName:t})=>`${lr(e)}.${lr(t)}.jsonl`,mf=(e,{userId:t,userName:n})=>{let r=pn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return a(`Invalid event log file name: ${r}`);let s=of.join(nr(e),r);return u("Successfully resolved event log path",s)},pf=(e,t)=>{let n={[e.action]:e.payload,v:Cd,id:t};return ri(n)};function go({event:e,rootDir:t}){try{let n=Ma(t);if(d(n))return n;let r=mf(t,{userId:e.userId,userName:e.userName});if(d(r))return r;let o=Ed(t);if(d(o))return a(o.message);let s=o.value?Sd(Math.max(Date.now(),sf(o.value)+1)):Sd(),i=pf(Id(e),[s,o.value]);return d(i)?a(i.message):(rf.appendFileSync(r.value,`${JSON.stringify(i.value)}
44
- `,"utf8"),u("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 Nd(e,t){let n=Vt(e);if(n.status!==Ut.Success)return n;let r=go({event:e,rootDir:t});return d(r)?r:n}function U(e,t){if(e.length===0||!e[0])return a("No events provided");let n=gf(e[0],t);if(d(n))return n;let r=e.map(s=>Nd(s,t)),o=r.filter(d);return o.length>0?a("Materialize and persist failed: "+o.map(s=>s.message).join(", ")):u("Materialization succeeded",r.map(s=>s.value))}var gf=(e,t)=>{if(e.action==="create.contributor")return u("Contributor already being created",void 0);if(S.getContributor(e.userId))return u("Contributor exists",void 0);let n={id:ff(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},r=Nd(n,t);return d(r)?a(r.message):u("Contributor created",void 0)};var Rd=e=>vo(Y(e),{at:"end"}),vo=(e,t={at:"end"})=>{let n=o=>d(o)?u("Rank space exhausted",{rank:"",needsRebalance:!0}):u("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(Ue(void 0,void 0));let r=()=>n(Ue(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(Ue(void 0,o.rank)):a("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(Ue(o.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let o=Ad(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o>0?e[o-1]:void 0;return n(Ue(i?.rank,s.rank))}case"after":{let o=Ad(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o<e.length-1?e[o+1]:void 0;return n(Ue(s.rank,i?.rank))}}},Y=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Ad=(e,t)=>e.findIndex(n=>n.id===t),Td=(e,t,n={at:"end"})=>vo(Y(t).filter(r=>r.id!==e),n),fn=(e,t,n,r,o)=>{let s=Td(t,e,n);if(d(s))return s;if(!s.value.needsRebalance)return u("Resolved rank",s.value.rank);let i=zs(e,r);if(d(i))return i;let c=U([i.value],o);if(d(c))return c;let l=Td(t,e,n);return d(l)?l:l.value.needsRebalance?a("Rank rebalance failed to create space"):u("Resolved rank after rebalance",l.value.rank)},Ln=(e,t,n)=>{let r=Rd(e);if(d(r))return r;if(!r.value.needsRebalance)return u("Resolved rank",r.value.rank);let o=zs(e,t);if(d(o))return o;let s=U([o.value],n);if(d(s))return s;let i=Rd(e);return d(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):u("Resolved rank after rebalance",i.value.rank)};var M={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=z(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||M.navigate({contextNode:o,selectedIndex:z(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=z(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:()=>wd(1),navigateToPreviousItem:()=>wd(-1),navigateToNextContainer:()=>Md(1),navigateToPreviousContainer:()=>Md(-1),navigate:({contextNode:e,selectedIndex:t})=>{C({contextNodeId:e.id,selectedIndex:t})}},wd=e=>{let{selectedIndex:t,contextNode:n}=v(),r=z(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;M.navigate({selectedIndex:s,contextNode:n})},Md=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=z(o.id),i=s.findIndex(g=>g.id===t.id);if(i<0)return;let c=s.at(i+e)??s.at(0);if(!c)return;let l=z(c.id),m=Math.max(0,l.length-1),p=Math.min(Math.max(0,r),m),f=l.length?p:-1;M.navigate({contextNode:c,selectedIndex:f})};var Ld=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),kd=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},vf=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&&Ve(t)&&t.childRenderAxis==="vertical"},yo=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=Y(r.id);return M.navigate({contextNode:r,selectedIndex:Ld(t,o.length)}),!0},Dd=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return yo(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=Y(o.id).findIndex(c=>c.id===n.id);return i>=0?(M.navigate({contextNode:o,selectedIndex:i}),!0):Dd(o.id)},Pd=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Dd(n))return!0;n=t[n]?.parentNodeId}return!1},yf=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},Bd=e=>{let{nodes:t,rootNodeId:n}=v();if(vf(e.contextNodeId)&&yo(e.contextNodeId,e.selectedIndex))return u("Restored navigation inside text container",null);if(yf(e.selectedNodeId)&&e.selectedNodeId&&Pd(e.selectedNodeId))return u("Restored navigation to selected node or ancestor",null);if(yo(e.contextNodeId,e.selectedIndex))return u("Restored navigation to previous container",null);if(e.parentNodeId&&yo(e.parentNodeId,e.selectedIndex))return u("Restored navigation to previous parent",null);if(Pd(e.contextNodeId))return u("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return a("Unable to restore navigation");let o=Y(r.id);return M.navigate({contextNode:r,selectedIndex:Ld(e.selectedIndex,o.length)}),u("Restored navigation to root",null)};import{monotonicFactory as hf,ulid as Tt}from"ulid";var mr=hf();function xf(){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]=z(n.id),[o]=r?z(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return u("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?u("Resolved boot nav target",{contextNode:r,selectedIndex:0}):n?u("Resolved boot nav target",{contextNode:n,selectedIndex:0}):u("Resolved boot nav target",{contextNode:t.nodes[t.rootNodeId],selectedIndex:0})}function bf(){let e=xf();return d(e)?e:M.navigate(e.value)}function Fd({userId:e,userName:t}){let n=mr(),r=mr(),o=mr(),s=mr(),i=mr(),c=Ue(void 0,void 0);if(d(c))return c;let l=Ue(void 0,void 0);if(d(l))return l;let m=Ue(l.value,void 0);if(d(m))return m;let p=Ue(void 0,void 0);if(d(p))return p;let f=Ue(p.value,void 0);if(d(f))return f;let g=Ue(f.value,void 0);if(d(g))return g;let E=Ue(void 0,void 0);return d(E)?E:u("Created default events",[{id:Tt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:Tt(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:l.value}},{id:Tt(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Tt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Tt(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:g.value}},{id:Tt(),userId:e,userName:t,action:"add.board",payload:{id:mo,name:"Closed",parent:n,rank:m.value}},{id:Tt(),userId:e,userName:t,action:"add.swimlane",payload:{id:ve,name:"Closed",parent:mo,rank:E.value}},{id:Tt(),userId:e,userName:t,action:"lock.node",payload:{id:mo}},{id:Tt(),userId:e,userName:t,action:"lock.node",payload:{id:ve}}])}var If=()=>{let e=We();if(d(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"};function gn(e){if(If())return u("Skipped boot while checked out at a historical point",null);if(!e.length){let r=ee.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=cr(r);return d(o)?o:(C({hasProjectDefinition:!1,mode:y.DEFAULT}),u("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=st(e).filter(d);return n.length>0?a(`Materializing failed:
37
+ ${l.message}`):u("Configured state branch upstream",!0)},eo=async({stateBranchRoot:e,eventFileName:t})=>{let n=Os(t),r=Zr.join(e,n);if(!un.existsSync(r))return u("No event file to stage",void 0);let o=await ue.stage({cwd:e,pathspec:[n]});return d(o)?a(`Failed to stage state branch event file
38
+ ${o.message}`):u("Staged state branch event file",void 0)},Wa=async({stateBranchRoot:e})=>{let t=Na(),n=Zr.join(e,t);if(!un.existsSync(n))return u("No media directory to stage",void 0);let r=await ue.stage({cwd:e,pathspec:[t]});return d(r)?a(`Failed to stage state branch media files
39
+ ${r.message}`):u("Staged state branch media files",void 0)},ja=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Qm(e);return d(n)?a(`Create state branch sync commit failed
40
+ `+n.message):Rn({cwd:t,message:n.value})},or=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Bs(t);if(d(n))return a(n.message);let r=Nn(e);if(d(r))return r;let o=r.value,s=n.value?await ue.push({cwd:t}):await ue.push({cwd:t,remote:Je,branch:o,setUpstream:!0});return d(s)?a(`Failed during state branch push
41
+ ${s.message}`):u("Pushed state branch",!0)},Ga=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Nn(e);if(d(o))return o;let s=o.value,i=[Yr(),await Zm({repoRoot:e,stateBranchName:s}),await mn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await np({stateBranchRoot:t,stateBranchName:s}),await wa(t),n?await rp({stateBranchRoot:t,repoRoot:e}):u("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(d(c))return a(c.message);r=r||!!c.value}return u(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{WebSocket as op}from"ws";var to=new Set,Va=e=>{to.add(e),e.on("close",()=>{to.delete(e)}),e.on("error",()=>{to.delete(e)})},Ht=e=>{let t=JSON.stringify(e);for(let n of to)n.readyState===op.OPEN&&n.send(t)};import{useSyncExternalStore as eh}from"react";var D={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function zs(e){return e.context===D.WORKSPACE}function T(e){return e.context===D.TICKET}function Wt(e){return e.context===D.TEXT}function Ve(e){return e.context===D.FIELD}function sr(e){return e.context===D.FIELD_LIST}var jt=e=>e.context===D.SWIMLANE,no=e=>e.context===D.BOARD,ir=e=>e.context===D.COMMENT;var h={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var Ka=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",za=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",qa=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Ya=(e,t)=>{if(za(e,e.sequence))return x.MoveCursorLeftOfWord;if(qa(e,e.sequence))return x.MoveCursorRightOfWord;if(Ka(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.GetLastCommandFromHistory;case"down":return x.GetNextCommandFromHistory;case"left":return x.MoveCursorLeft;case"right":return x.MoveCursorRight;case"return":return x.Confirm;case"backspace":return t?x.EraseInput:x.ExitCommandLine;case"escape":return x.ExitCommandLine;default:return x.CaptureInput}},Xa=(e,t)=>{if(za(e,e.sequence))return x.MoveCursorLeftOfWord;if(qa(e,e.sequence))return x.MoveCursorRightOfWord;if(Ka(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.NavPreviousItem;case"down":return x.NavNextItem;case"left":return x.MoveCursorLeft;case"right":return x.MoveCursorRight;case"return":return x.Confirm;case"backspace":return t?x.EraseInput:x.ExitCommandLine;case"escape":return x.ExitCommandLine;default:return x.CaptureInput}};function ro(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var ot=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Ze=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Ja=e=>e.charAt(0).toUpperCase()+e.slice(1);var Qa=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},Za=(e,t)=>t?e.get(t)??[]:[];var ed=new WeakMap,sp=e=>{let t=ed.get(e);return t||(t=Qa(e),ed.set(e,t)),t};var td=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Za(sp(e),r).filter(s=>ro(r,s)>=n)};var ip={hint:"",hints:[],overlap:0,remainder:""},nd=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return ip;let o=td({wordList:r,inputToMatch:e,overlapThreshold:1});return ap(t,o)},ap=(e,t)=>{let n=t[0]??"",r=ro(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,p=(c&&i?o:n)+(c&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}};import{ulid as lp}from"ulid";var Tn=24n,dp=Tn*4n,st=(1n<<dp)-1n,cp=/^[0-9a-f]+$/;function rd(e){return!e||!cp.test(e)?a(`Invalid hex rank: ${e}`):u("Converted rank to bigint",BigInt("0x"+e))}function Ke(e,t=Tn){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return u("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Oe(e,t){if(!e&&!t)return Ke(st/2n,Tn);let n=e?rd(e):u("Resolved lower bound",0n);if(d(n))return n;let r=t?rd(t):u("Resolved upper bound",st);if(d(r))return r;let o=n.value,s=r.value;if(s<=o)return Ke(st/2n,Tn);let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):Ke(i,Tn)}function od(e){if(e<=0)return u("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=st*BigInt(r+1)/(t+1n),s=Ke(o,Tn);if(d(s))return s;n.push(s.value)}return u("Resolved evenly spaced ranks",n)}var qs=(e,t)=>{let n=Y(e),r=od(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 u("Created rebalance event",{id:lp(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as gf}from"ulid";var oo="removed",_e=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?u("Found node",n):a("Unable to find node in breadcrumb")},sd=["png","jpg","gif","webp"];var wt=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return u("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return u("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},Ys=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Gt=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:a("Node not found"),S={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=pe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to link contributor to user"):u("Linked contributor to user",r)},deleteNode(e){pe(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(!T(t))return a("Can only comment on issues");let n=pe(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create comment"):u("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(!T(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=pe(i=>({...i,comments:{...i.comments??{},[e]:o}}));return d(s)?a("Unable to edit comment"):u("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=pe(o=>({...o,comments:{...o.comments??{},[e]:n}}));return d(r)?a("Unable to delete comment"):u("Deleted comment",n)},getComment(e){return v().comments?.[e]},getCommentsByIssue(e){return Object.values(v().comments??{}).filter(t=>t.issue===e&&!t.deleted)},createAttachment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create attachment, missing issue");if(!T(t))return a("Can only attach to issues");let n=pe(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create attachment"):u("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return a("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=pe(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return d(r)?a("Unable to delete attachment"):u("Deleted attachment",n)},getAttachment(e){return v().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(v().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return a("Edit target node not found");let o=Gt(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),u("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return a("Rename target node not found");let r=Gt(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),u("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return Y(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),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=Gt(o,"move");if(i)return i;if(Ys(t,e))return a("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),u("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=Gt(o,"delete");if(s)return s;let i=new Set,c=m=>{let p=t[m];if(!(!p||i.has(m))){i.add(m);for(let f of Y(p.id))c(f.id)}};c(e);let l={...structuredClone(t)};for(let m of i){if(!l[m])return a("Unable to locate node to delete");l[m]={...l[m],isDeleted:!0}}return n?(C({nodes:l}),u("Successfully tomb stoned",o)):a("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return a("Contributor not found");let n={...t,name:oo,tombstoned:!0},r=pe(o=>({...o,contributors:{...o.contributors,[e]:n}}));return d(r)?a("Unable to remove contributor"):u("Tombstoned contributor",n)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");let r={...n,name:t,tombstoned:!1},o=pe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to restore contributor"):u("Restored contributor",r)},createContributor(e){let t=pe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):u("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=Gt(r,"edit");if(o)return o;if(!T(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),u("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=Gt(r,"edit");if(o)return o;if(!T(r))return a("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return u("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),u("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=Gt(r,"edit");if(o)return o;if(!T(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),u("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=Gt(r,"edit");if(o)return o;if(!T(r))return a("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return u("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),u("Tag removed",{tag:t})},createTag(e){let t=pe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):u("Tag created",e)},createNode(e){let t=pe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?a("Unable to create node"):u("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=pe(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):u("Locked node",n)},updateNode(e){let t=pe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:u("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return Y(e)}};var Z={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var We=e=>e.slice(-7).toUpperCase(),id=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?We(e).includes(n):!0};var ee={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:D.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:We(e)},context:D.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:D.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:D.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:D.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:We(e)},context:D.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:D.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:D.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};import Vt from"chalk";import md from"string-width";import{decodeTime as vp}from"ulid";import Mn from"chalk";var Pe={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:Pe.cyan,accent2:Pe.magenta,primary:Pe.white,secondary:Pe.grayDark,secondary2:Pe.grayLight,gray:Pe.gray,green:Pe.green,yellow:Pe.yellow,red:Pe.red};var R={red:Pe.red,yellow:Pe.yellow,green:Pe.green,blue:Pe.blue,magenta:Pe.magenta,cyan:Pe.cyan},wn={urgent:R.red,critical:R.red,important:R.red,blocker:R.red,asap:R.red,immediate:R.red,fail:R.red,failure:R.red,broken:R.red,bug:R.red,error:R.red,incident:R.red,outage:R.red,production:R.red,crash:R.red,security:R.red,warning:R.yellow,warn:R.yellow,risky:R.yellow,risk:R.yellow,attention:R.yellow,pending:R.yellow,review:R.yellow,"needs-review":R.yellow,qa:R.yellow,testing:R.yellow,test:R.yellow,validate:R.yellow,verification:R.yellow,staging:R.yellow,check:R.yellow,"follow-up":R.yellow,followup:R.yellow,waiting:R.yellow,blocked:R.yellow,hold:R.yellow,done:R.green,complete:R.green,completed:R.green,success:R.green,ok:R.green,stable:R.green,resolved:R.green,fixed:R.green,closed:R.green,merged:R.green,released:R.green,deployed:R.green,approved:R.green,verified:R.green,working:R.green,healthy:R.green,pass:R.green,passing:R.green,info:R.blue,information:R.blue,note:R.blue,docs:R.blue,documentation:R.blue,doc:R.blue,guide:R.blue,help:R.blue,explanation:R.blue,detail:R.blue,details:R.blue,context:R.blue,design:R.blue,discussion:R.blue,proposal:R.blue,idea:R.blue,feature:R.magenta,enhancement:R.magenta,improvement:R.magenta,refactor:R.magenta,refactoring:R.magenta,cleanup:R.magenta,optimize:R.magenta,optimization:R.magenta,perf:R.magenta,performance:R.magenta,upgrade:R.magenta,migration:R.magenta,modernize:R.magenta,debt:R.magenta,todo:R.cyan,next:R.cyan,planned:R.cyan,plan:R.cyan,future:R.cyan,backlog:R.cyan,investigate:R.cyan,explore:R.cyan,prototype:R.cyan};var Js={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ad=(e,t,n)=>Math.max(t,Math.min(n,e)),Xs=(e,t,n)=>e+(t-e)*n,dd=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},up=e=>e.toLowerCase().trim(),mp=(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)),l=0,m=0,p=0;i>=0&&i<1?(l=s,m=c):i>=1&&i<2?(l=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<5?(l=c,p=s):(l=s,p=c);let f=o-s/2;return[Math.round((l+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},cd=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var pp=(e,t,n)=>{let r=ad(n,0,1);return[Math.round(Xs(e[0],t[0],r)),Math.round(Xs(e[1],t[1],r)),Math.round(Xs(e[2],t[2],r))]};var fp=(e,t,n)=>pp(e,t,n),ar=e=>{let t=dd(e)%360,n=mp(t,Js.stringColor.saturation,Js.stringColor.lightness);return cd(n)},te=(e,t=wn)=>{let n=up(e);return n&&t[n]?t[n]:ar(n)};var ld=e=>{let t=Js.gradient.stops,n=ad(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 fp(t[s],t[s+1],i)},so=e=>cd(ld(e)),io=e=>dd(e.toLowerCase().trim())/4294967295,ud=e=>{let t=io(e);return ld(t)},gp=e=>{let[t,n,r]=ud(e);return{normal:o=>Mn.bgRgb(t,n,r).black(o),cursor:o=>Mn.bgRgb(t,n,r).white.bold(o)}},Qs=e=>{let[t,n,r]=ud(e);return{fg:o=>Mn.rgb(t,n,r)(o),fgCursor:o=>Mn.rgb(t,n,r).inverse(o),bg:o=>Mn.bgRgb(t,n,r).black(o),bgCursor:o=>Mn.bgRgb(t,n,r).white.bold(o)}},ao=e=>gp(e).normal(` ${e} `);var Pn=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"},co=e=>String(e).padStart(2,"0"),lo=e=>`${e.getFullYear()}-${co(e.getMonth()+1)}-${co(e.getDate())} ${co(e.getHours())}:${co(e.getMinutes())}`;var hp=(e,t)=>e+" ".repeat(Math.max(0,t-md(e))),yp=(e,t)=>" ".repeat(Math.max(0,t-md(e)))+e,uo=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","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","create.contributor":"Added contributor","link.contributor.user":"Linked contributor","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),xp=(e,t)=>t?e<t?"up":e>t?"down":null:null,bp=(e,t)=>{let n=S.getNode(e.payload.parent),r=n?Vt.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=xp(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},pd=e=>`${Math.max(1,Math.round(e/1024))} KB`,fd=e=>S.getAttachment(e)?.name??"",Ip=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?Vt.bgHex(te(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?Vt.bgHex(te(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Vt.hex(te(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Vt.hex(te(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:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Vt.dim(`(${pd(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=fd(e.payload.id);return t?`"${t}"`:""}default:return""}},Ep=e=>{let t=Pn(vp(e));return Vt.gray(yp(t,8))},Sp=12,Cp=e=>hp(`${e}`,Sp),Np=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=v().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=S.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${pd(e.payload.bytes)})`;case"delete.issue.attachment":{let t=fd(e.payload.id);return t?`"${t}"`:""}default:return""}},gd=e=>[uo(e.action),Np(e)].filter(Boolean).join(" "),vd=(e,t)=>{let n=Ep(e.id),r=Cp(e.userName),o=Vt.dim("\u203A"),s=e.action==="move.node"?bp(e,t):[uo(e.action),Ip(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};import{createHash as Rp}from"node:crypto";var Ap="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Tp=e=>{let t=Rp("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+=Ap[Number(n>>s&31n)]}return r},Ie=(e,t)=>Tp(`${e}:virtual:${t}`);var wp=e=>Ie(e,"comments"),Mp=e=>Ie(e,"description"),Pp=e=>Ie(e,"assignees"),Lp=e=>Ie(e,"tags"),kp=e=>Ie(e,"history"),Dp=e=>Ie(e,"attachments"),mo=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=S.getNode(e);if(!c){let p=S.createNode({...ee.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:u("Virtual field created",void 0)}if(!Ve(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 u("Virtual field unchanged",void 0);let m=S.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return d(m)?m:u("Virtual field updated",void 0)},hd=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=S.getNode(e);if(!i){let m=S.createNode({...ee.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return d(m)?m:u("Virtual field list created",void 0)}if(!sr(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 u("Virtual field list unchanged",void 0);let l=S.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return d(l)?l:u("Virtual field list updated",void 0)},yd=e=>{let t=Ke(st/4n),n=Ke(st/2n),r=Ke(st*3n/4n),o=Ke(st*7n/8n),s=Ke(st*15n/16n),i=Ke(st*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;if(d(i))return i;let c=mo({id:Mp(e.id),name:Z.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(c))return c;let l=hd({id:Pp(e.id),name:Z.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(l))return l;let m=hd({id:Lp(e.id),name:Z.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(m))return m;let p=mo({id:wp(e.id),name:Z.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(p))return p;let f=mo({id:Dp(e.id),name:Z.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(d(f))return f;let g=mo({id:kp(e.id),name:Z.HISTORY,parentNodeId:e.id,rank:i.value,value:Bp(e),readonly:!0,childRenderAxis:"vertical"});return d(g)?g:u("Ticket virtual nodes materialized",void 0)},Bp=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=>vd(r,n.get(r.action)??[])).join(`
42
+ `)};var Fp=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ve,po]=Fp;var L=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),xd=e=>{let t=S.getNode(e);if(!t||!T(t)||t.isDeleted)return null;let n=yd(t);return d(n)?n:null},Up=e=>{for(let t of e){let n=xd(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=xd(r);if(o)return o}return null},Op=(e,t)=>{let n=S.getNode(e);n&&S.updateNode({...n,log:[...n.log??[],t]})},_p=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},Zs=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":case"add.issue.attachment":case"delete.issue.attachment":return[e.payload.issue];case"delete.node":case"edit.description":return _p(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[]}},$p=e=>{pe(t=>({...t,eventLog:[...t.eventLog,e]}))},Hp=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?L("Invalid user ID format",e):u("Valid user",null)},Wp=(e,t)=>{let n=Hp(e);if(d(n))return n;let r=[...new Set(Zs(e))];t||(r.forEach(s=>Op(s,e)),$p(e));let o=Up(r);return o||null},jp={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=ee.workspace(t,n,r),s=dr(o);if(d(s))return L(s.message,e);let i=S.createNode(o);return d(i)?L(i.message??"Failed to initialize workspace",e):zs(i.value)?u("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=S.createNode(ee.workspace(t,n,r));return d(o)?L(o.message??"Failed to add workspace",e):zs(o.value)?u("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=S.createNode(ee.board(t,n,r,o));return d(s)?L(s.message??"Unable to create board",e):no(s.value)?u("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=S.createNode(ee.swimlane(t,n,r,o));return d(s)?L(s.message??"Unable to create swimlane",e):jt(s.value)?u("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=S.createNode(ee.ticket(t,n,r,o));return d(s)?L(s.message??"Unable to create issue",e):T(s.value)?u("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=S.createNode(ee.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(Z.DESCRIPTION)?"vertical":"horizontal"}));return d(i)?L(i.message??`Unable to create field: ${n}`,e):Ve(i.value)?u("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(!S.getNode(t))return L(`Unable to locate node with id ${t}`,e);let o=S.renameNode(t,n);return d(o)?L(o.message??"Unable to edit title",e):u("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=S.tombstoneNode(t);return d(n)?L(n.message??"Unable to delete node",e):u("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=S.createTag({id:t,name:n});return d(r)?L(r.message??"Unable to create tag",e):u("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=S.createContributor({id:t,name:n});return d(r)?L(r.message??"Unable to create contributor",e):u("Contributor created",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=S.tombstoneContributor(t);return d(n)?L(n.message??"Unable to remove contributor",e):u("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,r=S.restoreContributor(t,n);return d(r)?L(r.message??"Unable to restore contributor",e):u("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=S.tag(t,n);return d(r)?L(r.message??"Unable to tag issue",e):u("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=S.untag(t,n);return d(r)?L(r.message??"Unable to untag issue",e):u("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=S.assign(t,n);return d(r)?L(r.message??"Unable to assign issue",e):u("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=S.unassign(t,n);return d(r)?L(r.message??"Unable to unassign issue",e):u("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=S.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?L(o.message??"Failed to move node",e):u("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=S.editValue(t,n);return d(r)?L(r.message??"Unable to edit description",e):u("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=S.getNode(t);if(!o)return L("Unable to locate issue",e);if(!T(o))return L("Can only close issues",e);let s=S.getNode(ve);if(!s)return L("Unable to locate target swimlane",e);if(n!==s.id)return L("Close target must be closed swimlane",e);let i=S.moveNodeToRank({id:t,parentId:n,rank:r});return d(i)?L(i.message??"Unable to close issue",e):u("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=S.getNode(t);if(!o)return L("Unable to locate issue",e);if(!T(o))return L("Can only reopen issues",e);let s=S.getNode(ve);if(!s)return L("Unable to locate closed swimlane",e);if(n===s.id)return L("Cannot reopen issue into closed swimlane",e);if(!S.getNode(n))return L("Reopen parent no longer exists",e);let c=S.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?L(c.message??"Unable to reopen issue",e):u("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=S.lockNode(t);return d(n)?L(n.message??"Unable to lock node",e):u("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=S.getNode(r);if(!s)return L(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return L(`Node ${r} is not child of ${t}`,e);let i=S.updateNode({...s,rank:o});if(d(i))return L(i.message??"Unable to rebalance child",e)}return u("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=S.createComment({id:t,issue:n,authorId:r,authorName:S.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return d(s)?L(s.message??"Unable to add comment",e):u("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=S.getComment(t);if(!o)return L("Unable to locate comment",e);if(o.issue!==n)return L("Comment does not belong to issue",e);let s=S.editComment(t,r);return d(s)?L(s.message??"Unable to edit comment",e):u("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=S.getComment(t);if(!r)return L("Unable to locate comment",e);if(r.issue!==n)return L("Comment does not belong to issue",e);let o=S.deleteComment(t);return d(o)?L(o.message??"Unable to delete comment",e):u("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:r,ext:o,name:s,bytes:i}=e.payload,c=S.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return d(c)?L(c.message??"Unable to add attachment",e):u("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=S.getAttachment(t);if(!r)return L("Unable to locate attachment",e);if(r.issue!==n)return L("Attachment does not belong to issue",e);let o=S.deleteAttachment(t);return d(o)?L(o.message??"Unable to delete attachment",e):u("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=S.linkUserId({contributorId:t,userId:e.userId});return d(n)?L(n.message??"Unable to link contributor",e):u("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function Kt(e,t=!1){let n=jp[e.action];if(!n)return a(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);let r=n(e);if(d(r))return r;let o=Wp(e,t);return o||r}var it=e=>{let t=bd(()=>e.map(n=>Kt(n)));return d(t)?e.map(()=>a(t.message)):t.value};import of from"node:fs";import sf from"node:path";import{decodeTime as af,monotonicFactory as df}from"ulid";import{z as lr}from"zod";var cr=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown";import fo from"node:fs";import ti from"node:path";import{decodeTime as Kp}from"ulid";import{z as ei}from"zod";var Gp=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","create.contributor","tombstone.contributor","restore.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","move.node","edit.description","add.issue.comment","edit.issue.comment","delete.issue.comment","add.issue.attachment","delete.issue.attachment","close.issue","reopen.issue","lock.node","rebalance.children","link.contributor.user"];var Vp=new Set(Gp),Id=e=>Vp.has(e),Ed=e=>({action:e.action,payload:e.payload});var zp=ei.object({userId:ei.string().min(1).default("unknown"),userName:ei.string().min(1).default("unknown")}),qp=/^[0-9a-hjkmnp-tv-z]{26}$/i,Yp=e=>qp.test(e)?e.toUpperCase():e,Xp=e=>{let t=ti.basename(e,".jsonl"),n=t.indexOf("."),r=n===-1?t:t.slice(0,n),o=n===-1?void 0:t.slice(n+1),s=zp.safeParse({userId:Yp(r),userName:o});return s.success?u("Parsed event file actor",s.data):a(`Invalid event file name ${ti.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},Jp=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"):u("Resolved persisted action",t[0])},Qp=(e,t)=>t in e,Zp=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),ef=e=>{let{userId:t,userName:n,...r}=e,o=Jp(r);if(d(o))return a(o.message);let s=o.value,i=e.id?.[0];return i?Qp(r,s)?u("Decoded persisted event",Zp({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")},ni=e=>{let t=[],n=new Map;for(let r of e){let o=ef(r);if(d(o))return a(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);let s=o.value.action;if(!Id(s)){n.set(s,(n.get(s)??0)+1);continue}t.push(o.value)}if(n.size>0){let r=[...n.entries()].map(([o,s])=>`${o} (x${s})`).join(", ");le.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${r}. Upgrade to apply them.`)}return u("Decoded reconstructed events",t)},tf=e=>{if(!fo.existsSync(e))return u("Event file missing",[]);let t=Xp(e);if(d(t))return a(t.message);let n=fo.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
43
+ `)){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=oi(i);if(d(c))return a(`${c.message} in ${e}: ${s}`);r.push({...c.value,userId:t.value.userId,userName:t.value.userName})}return u("Parsed persisted events file",r)};function ri(e){let t=tr(e);if(!fo.existsSync(t))return u("No events found",[]);let n=fo.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>ti.join(t,o)),r=[];for(let o of n){let s=tf(o);if(d(s))return a(s.message);r.push(...s.value)}return u("All events loaded",nf(r))}function je(e){let t=ri(e);return d(t)?a(t.message):ni(t.value)}function go(e,t){let n=ri(e);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=rf(n.value,t),s=ni(r);if(d(s))return a(s.message);let i=ni(o);return d(i)?a(i.message):u("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:i.value})}function Sd(e=process.cwd()){let t=ri(e);return d(t)?a(t.message):u("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var nf=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],f=m.id[1]??null;t.set(p,m);let g=n.get(f)??[];g.push(m),n.set(f,g)}for(let m of n.values())m.sort((p,f)=>p.id[0].localeCompare(f.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 f=n.get(p)??[];for(let g of f)s(g)},i=n.get(null)??[];for(let m of i)s(m);let c=e.filter(m=>{let p=m.id[0],f=m.id[1]??null;return!o.has(p)&&f!==null&&!t.has(f)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of c)s(m);let l=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of l)s(m);return r},rf=(e,t)=>{let n=new Set,r=[],o=[];for(let s of e){let i=s.id[0],c=s.id[1],l=!1;try{l=Kp(i)<t}catch{l=!1}!l||c&&n.has(c)?(n.add(i),o.push(s)):r.push(s)}return{appliedEvents:r,unappliedEvents:o}};var Nd=1,Cd=df(),cf=lr.tuple([lr.string().min(1),lr.string().min(1).nullable()]),lf=lr.looseObject({v:lr.literal(Nd),id:cf}),oi=e=>{let t=lf.safeParse(e);return t.success?u("Parsed persisted event",t.data):a(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},uf=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),mf=e=>e.trim().length>0&&e.length<=80,ae=()=>{let{userName:e,userId:t}=K();return e?t?uf(t)?mf(e)?u("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")},pn=({userId:e,userName:t})=>`${cr(e)}.${cr(t)}.jsonl`,pf=(e,{userId:t,userName:n})=>{let r=pn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return a(`Invalid event log file name: ${r}`);let s=sf.join(tr(e),r);return u("Successfully resolved event log path",s)},ff=(e,t)=>{let n={[e.action]:e.payload,v:Nd,id:t};return oi(n)};function vo({event:e,rootDir:t}){try{let n=Pa(t);if(d(n))return n;let r=pf(t,{userId:e.userId,userName:e.userName});if(d(r))return r;let o=Sd(t);if(d(o))return a(o.message);let s=o.value?Cd(Math.max(Date.now(),af(o.value)+1)):Cd(),i=ff(Ed(e),[s,o.value]);return d(i)?a(i.message):(of.appendFileSync(r.value,`${JSON.stringify(i.value)}
44
+ `,"utf8"),u("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 Rd(e,t){let n=Kt(e);if(n.status!==_t.Success)return n;let r=vo({event:e,rootDir:t});return d(r)?r:n}function O(e,t){if(e.length===0||!e[0])return a("No events provided");let n=vf(e[0],t);if(d(n))return n;let r=e.map(s=>Rd(s,t)),o=r.filter(d);return o.length>0?a("Materialize and persist failed: "+o.map(s=>s.message).join(", ")):u("Materialization succeeded",r.map(s=>s.value))}var vf=(e,t)=>{if(e.action==="create.contributor")return u("Contributor already being created",void 0);if(S.getContributor(e.userId))return u("Contributor exists",void 0);let n={id:gf(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},r=Rd(n,t);return d(r)?a(r.message):u("Contributor created",void 0)};var Ad=e=>ho(Y(e),{at:"end"}),ho=(e,t={at:"end"})=>{let n=o=>d(o)?u("Rank space exhausted",{rank:"",needsRebalance:!0}):u("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(Oe(void 0,void 0));let r=()=>n(Oe(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(Oe(void 0,o.rank)):a("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(Oe(o.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let o=Td(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o>0?e[o-1]:void 0;return n(Oe(i?.rank,s.rank))}case"after":{let o=Td(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o<e.length-1?e[o+1]:void 0;return n(Oe(s.rank,i?.rank))}}},Y=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Td=(e,t)=>e.findIndex(n=>n.id===t),wd=(e,t,n={at:"end"})=>ho(Y(t).filter(r=>r.id!==e),n),fn=(e,t,n,r,o)=>{let s=wd(t,e,n);if(d(s))return s;if(!s.value.needsRebalance)return u("Resolved rank",s.value.rank);let i=qs(e,r);if(d(i))return i;let c=O([i.value],o);if(d(c))return c;let l=wd(t,e,n);return d(l)?l:l.value.needsRebalance?a("Rank rebalance failed to create space"):u("Resolved rank after rebalance",l.value.rank)},Ln=(e,t,n)=>{let r=Ad(e);if(d(r))return r;if(!r.value.needsRebalance)return u("Resolved rank",r.value.rank);let o=qs(e,t);if(d(o))return o;let s=O([o.value],n);if(d(s))return s;let i=Ad(e);return d(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):u("Resolved rank after rebalance",i.value.rank)};var M={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=z(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||M.navigate({contextNode:o,selectedIndex:z(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=z(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:()=>Md(1),navigateToPreviousItem:()=>Md(-1),navigateToNextContainer:()=>Pd(1),navigateToPreviousContainer:()=>Pd(-1),navigate:({contextNode:e,selectedIndex:t})=>{C({contextNodeId:e.id,selectedIndex:t})}},Md=e=>{let{selectedIndex:t,contextNode:n}=v(),r=z(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;M.navigate({selectedIndex:s,contextNode:n})},Pd=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=z(o.id),i=s.findIndex(g=>g.id===t.id);if(i<0)return;let c=s.at(i+e)??s.at(0);if(!c)return;let l=z(c.id),m=Math.max(0,l.length-1),p=Math.min(Math.max(0,r),m),f=l.length?p:-1;M.navigate({contextNode:c,selectedIndex:f})};var kd=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Dd=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},hf=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&&Ve(t)&&t.childRenderAxis==="vertical"},yo=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=Y(r.id);return M.navigate({contextNode:r,selectedIndex:kd(t,o.length)}),!0},Bd=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return yo(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=Y(o.id).findIndex(c=>c.id===n.id);return i>=0?(M.navigate({contextNode:o,selectedIndex:i}),!0):Bd(o.id)},Ld=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Bd(n))return!0;n=t[n]?.parentNodeId}return!1},yf=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},Fd=e=>{let{nodes:t,rootNodeId:n}=v();if(hf(e.contextNodeId)&&yo(e.contextNodeId,e.selectedIndex))return u("Restored navigation inside text container",null);if(yf(e.selectedNodeId)&&e.selectedNodeId&&Ld(e.selectedNodeId))return u("Restored navigation to selected node or ancestor",null);if(yo(e.contextNodeId,e.selectedIndex))return u("Restored navigation to previous container",null);if(e.parentNodeId&&yo(e.parentNodeId,e.selectedIndex))return u("Restored navigation to previous parent",null);if(Ld(e.contextNodeId))return u("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return a("Unable to restore navigation");let o=Y(r.id);return M.navigate({contextNode:r,selectedIndex:kd(e.selectedIndex,o.length)}),u("Restored navigation to root",null)};import{monotonicFactory as xf,ulid as Mt}from"ulid";var ur=xf();function bf(){let e=Ge();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]=z(n.id),[o]=r?z(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return u("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?u("Resolved boot nav target",{contextNode:r,selectedIndex:0}):n?u("Resolved boot nav target",{contextNode:n,selectedIndex:0}):u("Resolved boot nav target",{contextNode:t.nodes[t.rootNodeId],selectedIndex:0})}function If(){let e=bf();return d(e)?e:M.navigate(e.value)}function Ud({userId:e,userName:t}){let n=ur(),r=ur(),o=ur(),s=ur(),i=ur(),c=Oe(void 0,void 0);if(d(c))return c;let l=Oe(void 0,void 0);if(d(l))return l;let m=Oe(l.value,void 0);if(d(m))return m;let p=Oe(void 0,void 0);if(d(p))return p;let f=Oe(p.value,void 0);if(d(f))return f;let g=Oe(f.value,void 0);if(d(g))return g;let E=Oe(void 0,void 0);return d(E)?E:u("Created default events",[{id:Mt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:Mt(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:l.value}},{id:Mt(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Mt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Mt(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:g.value}},{id:Mt(),userId:e,userName:t,action:"add.board",payload:{id:po,name:"Closed",parent:n,rank:m.value}},{id:Mt(),userId:e,userName:t,action:"add.swimlane",payload:{id:ve,name:"Closed",parent:po,rank:E.value}},{id:Mt(),userId:e,userName:t,action:"lock.node",payload:{id:po}},{id:Mt(),userId:e,userName:t,action:"lock.node",payload:{id:ve}}])}var Ef=()=>{let e=Ge();if(d(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"};function gn(e){if(Ef())return u("Skipped boot while checked out at a historical point",null);if(!e.length){let r=ee.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=dr(r);return d(o)?o:(C({hasProjectDefinition:!1,mode:h.DEFAULT}),u("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=it(e).filter(d);return n.length>0?a(`Materializing failed:
45
45
  ${n.map(r=>r.message).join(`
46
- `)}`):(bf(),C({hasProjectDefinition:!0}),u("State booted successfully",null))}var vn=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),ho=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)}},J=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);var ht=null,xo=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!ht,currentStatus:v().syncStatus?.status,currentMessage:v().syncStatus?.msg}),ht)return logger.debug("[sync] syncAndReloadState joining existing promise"),ht;logger.debug("[sync] syncAndReloadState creating promise"),ht=Ef();try{let e=await ht;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:v().syncStatus?.status,statusMessageAfterResolve:v().syncStatus?.msg}),d(e)&&v().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}),ht||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:v().syncStatus?.status,statusMessageBeforeClear:v().syncStatus?.msg}),ht=null}},Ef=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:v().mode,syncStatus:v().syncStatus});let e=Ud();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:v().mode,message:e.message,syncStatus:v().syncStatus}),e;if(ht)return ht;logger.debug("[sync] syncAndReloadState:start");let t=J("resolveActorId",ae());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:v().syncStatus});let n=pn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=J("syncEpiqWithRemote",await bo({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:v().syncStatus}),et(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let s=J("loadMergedEvents",je(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:v().syncStatus}),a(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let i=Ud();if(i)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:v().mode,message:i.message,syncStatus:v().syncStatus}),i;let c=kd(),l=v().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:c,selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id,selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual}),!v().selectedNode?.isVirtual&&!v().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let p=J("bootStateFromEventLog",gn(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:v().syncStatus}),a(`Unable to boot synced state. ${p.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),C({filters:l}),logger.debug("[sync] restoreNavigationAnchor:start");let m=J("restoreNavigationAnchor",Bd(c));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(m),message:d(m)?m.message:"Navigation restored",selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id}),d(m)?(C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:v().syncStatus}),m):(C({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:v().syncStatus}),u("Synced",!0))},Ud=()=>v().mode===y.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:v().mode,syncStatus:v().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 kn=3e3,Od=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<kn?null:t},_d=0,oi,si=!1,pr=!1,ii=()=>{if(si)return!0;let e=We();return d(e)?!1:e.value.syncStatus.status==="syncing"},Sf=()=>{let e=K().autoSyncIntervalMs??1e4,t=Date.now()-_d;return Math.max(0,e-t)},$d=()=>{oi||(oi=setTimeout(async()=>{if(oi=void 0,!!Gt()){if(ii()){pr=!0;return}pr=!1,await Cf()}},Sf()))},Cf=async()=>{if(v().readOnly||v().timeMode==="peek"||v().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!Gt())return a("Cannot auto-sync before state is initialized");if(ii())return pr=!0,a("Sync already in progress");si=!0,_d=Date.now(),C({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await xo()}finally{si=!1,pr&&$d()}},Io=()=>{Gt()&&(pr=!0,!ii()&&$d())};var Kt=()=>{let e=K(),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}},Hd=()=>{let e=$e(process.cwd());if(d(e))return!1;let t=ut(e.value);return Q(t)},jd=e=>e===!0?"on":e===!1?"off":null,Wd=e=>e==="on"?!0:e==="off"?!1:null;var Nf=e=>e.props.tags??[],Rf=e=>e.props.assignees??[],zt=e=>Nf(e).map(t=>S.getTag(t)).filter(t=>!!t),qt=e=>Rf(e).map(t=>S.getContributor(t)).filter(t=>!!t),Eo=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!T(n)?a("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",zt(n))},So=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!T(n)?a("Invalid unassign target"):u("Retrieved assignees from ticket in breadcrumb",qt(n))};var b={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",YANK:"yank",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""};var Af=/^(\d+)(h|d|w|mo|y)$/,Tf=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,wf=({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},Mf=(e,t=new Date)=>{let n=e.match(Af);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}},Pf=e=>{let t=e.match(Tf);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),l=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return wf({year:c,month:l,day:m,hour:p,minute:f})?new Date(c,l-1,m,p,f):null},yn=e=>{let t=e.trim().toLowerCase();return Mf(t)??Pf(t)};var Vd=/^(\d+)(s|m)?$/,Co=e=>{let t=e.trim().toLowerCase().match(Vd);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},No=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Vd.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Gd=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Lf=[{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}],ai=(e=Lf)=>{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 kf=["BOARD","TICKET","SWIMLANE","COMMENT"],oe={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},Ke={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},ye={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},Df=[oe.EDITOR,oe.VIEW,oe.USERNAME,oe.AUTOSYNC,oe.SYNC_DEBOUNCE_MS,oe.ATTACHMENT_MAX_KB,oe.LOG_LEVEL],Bf=(e=v().selectedNode?.context)=>{switch(e){case"TICKET":return[Ke.TITLE,Ke.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Ke.TITLE];case"COMMENT":return[Ke.COMMENT];default:return[]}},ci=[String(kn),"5000","15000","30000","60000"],li=["250","500","1000"],qd=["10s","20s","30s","45s"],hn=[b.COFFEE,b.EXIT,b.SYNC,b.HELP,b.EXPORT,b.CONFIG,b.YANK],Ro=[b.NEW,b.EDIT,b.DELETE,b.MOVE],di=[b.TAG,b.UNTAG,b.ASSIGN,b.UNASSIGN,b.CLOSE_ISSUE,b.RE_OPEN_ISSUE,b.EDIT,b.COMMENT],Kd=[b.FILTER,b.PEEK,b.REPLAY],Ff={WORKSPACE:[...hn,...Ro],BOARD:[...Kd,...hn,...Ro],SWIMLANE:[...Kd,...hn,...Ro],TICKET:[...hn,...Ro,...di],FIELD:[...hn,...di],FIELD_LIST:[...hn,...di],TEXT:[...hn],COMMENT:[b.EDIT,b.DELETE,b.YANK]},Uf=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],fr=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&T(n)),zd=e=>e.parentNodeId===ve,Of=({selectedNode:e,breadCrumb:t})=>{let n=Bf(e?.context);return fr({breadCrumb:t,selectedNode:e})?n.includes(Ke.DESCRIPTION)?n:[...n,Ke.DESCRIPTION]:n},_f=({selectedNode:e,breadCrumb:t})=>{let n=fr({breadCrumb:t,selectedNode:e});return n?[ye.REF,ye.TITLE,...n.props?.description?.trim()?[ye.DESCRIPTION]:[],...zt(n).length>0?[ye.TAGS]:[],...qt(n).length>0?[ye.ASSIGNEES]:[]]:e?[ye.REF,ye.TITLE]:[]},$f=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Kt();if(!r)return[b.HELP,b.CONFIG];if(!Hd())return[b.HELP,b.INIT];if(t)return[b.HELP,b.PEEK,b.REPLAY,b.EXPORT,b.CONFIG,b.YANK];let o=e?.context,s=o&&kf.includes(o),i=[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?Ff[l]:[]))],c=fr({breadCrumb:n,selectedNode:e});return i.filter(l=>l===b.MOVE?!1:l===b.YANK?!!(c??e):l===b.EDIT?s||!!c:l===b.DELETE?s:l===b.UNTAG?!!(c&&zt(c).length>0):l===b.UNASSIGN?!!(c&&qt(c).length>0):l===b.RE_OPEN_ISSUE?!!(c&&zd(c)):l===b.CLOSE_ISSUE?!!(c&&!zd(c)):!0)},de=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let s=t.context??"WORKSPACE";return{[b.NONE]:$f({breadCrumb:o,readOnly:r,selectedNode:n}),[b.EXIT]:["confirm"],[b.EXPORT]:[],[b.SYNC]:[],[b.INIT]:[],[b.HELP]:[],[b.PEEK]:[...ai(),"now","prev","next"],[b.REPLAY]:[...ai()],[b.EDIT]:Of({selectedNode:n,breadCrumb:o}),[b.YANK]:_f({selectedNode:n,breadCrumb:o}),[b.COMMENT]:[],[b.DELETE]:["confirm"],[b.RE_OPEN_ISSUE]:["confirm"],[b.CLOSE_ISSUE]:["confirm"],[b.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[b.FILTER]:["tag","assignee","description","title","ref","clear"],[b.TAG]:[...new Set([...Object.keys(wn),...S.getExistingTags()])],[b.UNTAG]:[...Eo()?.value?.map(({name:c})=>c)??[]],[b.UNASSIGN]:[...So()?.value?.map(({name:c})=>c)??[]],[b.ASSIGN]:S.getExistingAssignees(),[b.NEW]:Uf(s),[b.CONFIG]:[...Df],[b.COFFEE]:["1","3","5","20","custom"]}[e]??[]};import ic from"chalk";var Yd=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import{decodeTime as Xd}from"ulid";var Ao=e=>{try{return u("Decoded date",new Date(Xd(e)))}catch(t){return a("Decoding failed + "+t.message)}},Yt=e=>{if(!e?.id)return null;try{return Xd(e.id)}catch{return null}};import Gf from"zod";import Hf from"node:crypto";import gr from"node:fs";import Jd from"node:path";var xt=500,jf=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,Dn=(e,t)=>`${e}.${t}`,Wf=e=>jf.test(e),Qd=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?u("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?u("Sniffed image type","jpg"):e.length>=6&&(e.subarray(0,6).equals(Buffer.from("GIF87a","ascii"))||e.subarray(0,6).equals(Buffer.from("GIF89a","ascii")))?u("Sniffed image type","gif"):e.length>=12&&e.subarray(0,4).equals(Buffer.from("RIFF","ascii"))&&e.subarray(8,12).equals(Buffer.from("WEBP","ascii"))?u("Sniffed image type","webp"):a(`Unsupported image format. Allowed: ${od.join(", ")}`),Zd=e=>Hf.createHash("sha256").update(e).digest("hex"),Vf=(e,t=xt)=>{if(e.length===0)return a("Attachment is empty");if(e.length>t*1024)return a(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=Qd(e);return d(n)?n:u("Validated attachment data",{hash:Zd(e),ext:n.value,bytes:e.length})},ec=(e,t,n=xt)=>{let r=Vf(t,n);if(d(r))return r;let o=rr(e),s=Jd.join(o,Dn(r.value.hash,r.value.ext));try{gr.existsSync(s)||(gr.mkdirSync(o,{recursive:!0}),gr.writeFileSync(s,t))}catch(i){return a(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return u("Wrote attachment blob",r.value)},tc=(e,t,n=xt)=>{if(!Wf(t))return a("Invalid attachment file name");let r=Jd.join(rr(e),t);if(!gr.existsSync(r))return a("Attachment blob not found");let o;try{o=gr.readFileSync(r)}catch(l){return a(`Unable to read attachment blob: ${l instanceof Error?l.message:String(l)}`)}if(o.length>n*1024)return a(`Attachment exceeds the ${n} KB size cap and will not be served`);let[s,i]=t.split(".");if(Zd(o)!==s)return a("Attachment blob does not match its content hash");let c=Qd(o);return d(c)?c:c.value!==i?a("Attachment blob content does not match its extension"):u("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var vr=50,yr=5e3,nc=()=>{let e=X().commandMeta.inputString,t=Gf.coerce.number().int().min(vr).max(yr).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${vr}-${yr} KB (default ${xt})`);let n=Qe({attachmentMaxKb:t.data});return d(n)?n:(Me({attachmentMaxKb:t.data}),C({mode:y.DEFAULT}),u(`Attachment size cap set to ${t.data} KB`,null))};import rc from"chalk";var ne=e=>rc.dim(e),Ee=e=>rc.hex(h.primary)(e),Se=({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(f=>f.startsWith(i))].sort((f,g)=>so(f)-so(g)).slice(0,r).map(f=>io(f)).join(" ");return p?`${ne(e)}${p}${ne(n)}`:""};var bt={None:"none",Invalid:"invalid",Valid:"valid"};var Kf=["BOARD","TICKET","SWIMLANE"],oc=()=>{let e=v().selectedNode;if(!e?.context)return O({message:ne("Missing target context")});if(Kf.includes(e.context))return G();if(e.parentNodeId){let t=v().nodes[e.parentNodeId];if(t?.id===Ie(t?.parentNodeId??"","comments"))return G()}return O({message:ne("Command not available in this context")})},se="<ENTER> to confirm",G=(e="",t=[])=>({message:ne(e),validity:bt.Valid,completionWordList:t}),O=({message:e,completionWordList:t=[]})=>({validity:bt.Invalid,message:e,completionWordList:t}),wo=e=>e.length===0,sc=(e,t)=>{let n=Oe(v().breadCrumb,"BOARD");if(d(n))return O({message:Ee("Command is not applicable in this context")});let r=Ao(n.value.id);return d(r)?O({message:Ee(`Unable to ${t}: board id is not a valid ULID`)}):Gd({date:e,horizonDate:r.value})?null:O({message:Ee(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},To=e=>` ${ic.hex("#000").bgHex(te(e))(` ${e} `)} `,ui=({modifier:e})=>{let t="confirm";return e===t?G(se):O({message:wo(e)?ne("if you are certain, enter ")+io(t):"",completionWordList:[t]})},zf=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?O({message:ne(n)}):G():O({message:wo(r)?t:"",completionWordList:[...e]}),xn=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>wo(n)&&wo(r)?O({message:e,completionWordList:[]}):G(t??se),qf=({modifier:e,inputString:t})=>{let n=de(b.CONFIG);if(!n.includes(e))return O({message:Se({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case oe.EDITOR:{let r=[...Yd];return t.trim()?r.includes(t.trim())?G(se):O({message:Se({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):O({message:Se({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case oe.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?G(se):O({message:Se({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case oe.USERNAME:return t.trim()?G(se):O({message:Ee("Enter a user name. Saved in ")+ic.bgBlack("~/.epiq-global/config.json")});case oe.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?G(se):O({message:Se({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case oe.AUTOSYNC:{let r=["on","off"],o=K().autoSync;if(!r.includes(t.trim())){let s=jd(o);return O({message:Se({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return G(se)}case oe.ATTACHMENT_MAX_KB:{let r=K().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<vr||o>yr){let s=Se({prefix:" examples: ",wordList:li,minLengthForHints:0,inputString:t});return O({message:Ee(`provide a size cap in KB (${vr}-${yr}). current: ${r??xt} KB.`)+s,completionWordList:li})}return G(se)}case oe.SYNC_DEBOUNCE_MS:{let r=K().autoSyncIntervalMs,o=Od(t);if(!t.trim()||o===null||o<kn){let s=Se({prefix:" examples: ",wordList:ci,minLengthForHints:0,inputString:t});return O({message:Ee(`provide duration above ${kn}ms. current duration: ${r}ms.`)+s,completionWordList:ci})}return G(se)}default:return O({message:Ee("Unknown config option"),completionWordList:n})}},Yf=({modifier:e,inputString:t})=>{let n=de(b.EDIT);if(!n.length)return O({message:Ee("Command not available in this context")});if(!n.includes(e)){let r=Se({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return O({message:r||Ee("Unknown edit option"),completionWordList:n})}switch(e){case Ke.COMMENT:return t.trim()?G(se):O({message:ne("write a comment...")});case Ke.TITLE:return G(se);case Ke.DESCRIPTION:{let{preferredEditor:r}=K();return r?G(ne("<ENTER> to edit in ")+r):O({message:"No editor selected"})}default:return O({message:Ee("Unknown edit option"),completionWordList:n})}},Xf=({modifier:e})=>{let t=de(b.YANK);return t.length?t.includes(e)?G(se+ne(" and copy to clipboard")):O({message:Se({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):O({message:Ee("Nothing selected to copy from")})},Jf={[b.EXPORT]:()=>G(se+ne(", and create export markdown file")),[b.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return G(se);let n={message:ne("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=yn(r);if(!r||!o)return O(n);let s=sc(o,"peek");return s||G(se)},[b.REPLAY]:e=>{let{dateInput:t,durationInput:n}=No(e.modifier,e.inputString),r={message:ne("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=yn(t);if(!t||!o)return O(r);let s=sc(o,"replay");return s||(n&&Co(n)===null?O({message:Ee("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):G("<ENTER> to replay board history",n?qd:[]))},[b.EXIT]:()=>G(se+ne(" and exit the application")),[b.INIT]:()=>G(se),[b.PALETTE]:()=>G(se),[b.FILTER]:e=>{if(e.modifier==="clear")return G(se);let t=s=>de(b.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return O({message:Se({wordList:de(b.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:de(b.FILTER)});let n=Object.values(v().tags).map(s=>s.name),r=Object.values(v().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?O({message:Se({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):G():O({message:Se({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[b.NONE]:e=>{let t=de(b.NONE);return O({message:Se({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[b.NEW]:e=>zf({list:de(b.NEW),hint:Se({wordList:de(b.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[b.HELP]:()=>G(se),[b.EDIT]:Yf,[b.COMMENT]:e=>{let t=xn({hint:ne(`write a comment (max ${4e3} char)...`),onOk:ne(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===bt.Invalid?t:e.inputString.length>4e3?G(Ee("max input exceeded")):t},[b.CONFIG]:qf,[b.YANK]:Xf,[b.DELETE]:e=>{let t=oc();return t.validity==="invalid"?t:ui(e)},[b.CLOSE_ISSUE]:e=>ui(e),[b.RE_OPEN_ISSUE]:e=>ui(e),[b.MOVE]:e=>{let t=oc();return t.validity==="invalid"?t:xn({hint:Se({prefix:"hey hacker! These commands are blocked for you... ",wordList:de(b.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[b.TAG]:e=>{let n=S.getExistingTags().slice(0,10).map(To).join("");return xn({hint:n.length?ne("create tag or reuse:")+n+ne(""):ne("create tag ...")})(e)},[b.UNTAG]:e=>{let t=Eo();if(d(t))return O({message:Ee("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(To).slice(0,10);return n.length?xn({hint:ne(" ... ")+n.join("")})(e):O({message:Ee("Issue has no tags"),completionWordList:[]})},[b.ASSIGN]:e=>{let t=S.getExistingAssignees().map(To).slice(0,10);return xn({hint:ne("assignees... ")+t.join("")})(e)},[b.UNASSIGN]:e=>{let t=So();if(d(t))return O({message:Ee("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(To).slice(0,10);return n.length?xn({hint:ne("remove assignee... ")+n.join("")})(e):O({message:Ee("Issue has no assignees"),completionWordList:[]})},[b.SYNC]:()=>G(se),[b.COFFEE]:e=>{let{modifier:t}=e,n=de(b.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?O({message:ne("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):xn({hint:Se({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},ac=Object.fromEntries(Object.entries(Jf).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Mo=["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 Qf=3,Zf=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"]),eg=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},tg=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=Qf&&!Zf.has(t)&&!/^\d+$/.test(t)),ng=e=>{let t=new Map;for(let s of eg(e))for(let i of tg(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=Mo.filter(s=>!r.has(s));return[...n,...o]},dc=Mo,cc=-1,lc=()=>{let e=We();if(d(e))return Mo;let t=e.value,n=t.eventLog.length;return n!==cc&&(dc=ng(t),cc=n),dc};var uc=e=>Object.values(b).includes(e),mc=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:l}=ac[n].validate(n,r,s),m=n!==b.PEEK&&n!==b.REPLAY,p=o==="command"||o==="modifier"?de(n):m?lc():[],{mode:f}=v(),g=f===y.COMMAND_LINE?i??"":"",E=[...l,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?td(e,E):{hint:"",hints:[],remainder:"",overlap:0}}};var pc=e=>{let t=e.trimStart(),n=og(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=sg(e),c=uc(r)?r:null,l=c!==null,m=r!=="",p=c?de(c)??[]:[],f=c&&p.includes(o)?o:"",g="word";n.length===0||n.length===1&&!s?g="command":(n.length===1&&s||n.length===2&&!s)&&(g="modifier");let E=s?"":i,I=rg(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:c,isCommandKeyword:l,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:E,inputString:I}},rg=(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},og=e=>e.trim()?e.trim().split(/\s+/):[],sg=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as ig}from"react";var Bn=e=>e===mi||e===":",mi=" ",Le={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:bt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},pi=new Set,fc=()=>{for(let e of pi)e()},fi=e=>(pi.add(e),()=>pi.delete(e)),It=e=>{let n=e(Le),r=pc(n.value),o=n.cursorPosition===n.value.length;Le={...n,commandMeta:mc(r,o)},fc()},hr=({message:e,status:t})=>{let n=structuredClone(Le);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Le=n,fc(),u(e,null)},gi=e=>{It(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},vi=e=>{It(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}})},gc=()=>{It(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}})},vc=()=>{It(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}})},Po=e=>{It(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}})},yc=()=>{It(e=>({...e,commandIsPending:!0}))},V=e=>{It(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},hc=({addToHistory:e=!0})=>{It(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},xc=()=>{It(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}})},bc=()=>{It(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},X=()=>Le,Ic=()=>ig(fi,X,X),Ec=()=>{let[e,...t]=Le.value.split(mi);return t.join(mi).trim()};var x={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",Yank:"yank",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function ag(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function dg(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function cg(e,t,n){let r=v().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function Sc(e,t){let n=X();if(e.sequence==="?"&&t!==y.PALETTE)return x.InitCommandPalette;if(e.sequence===":"&&t!==y.COMMAND_LINE)return x.InitCommandLine;if(t===y.MOVE)switch(e.name){case"m":case"return":return x.ConfirmMove}if(t===y.COMMAND_LINE)return qa(e,n.value);if(t===y.PALETTE)return Ya(e,n.value);let r=ag(e)||dg(e);if(r)return lg(r,t);if(e.ctrl&&e.name==="c")return x.Exit;switch(e.name){case"r":return x.EditTitle;case"e":return x.EditDescription;case"n":return x.AddItem;case"m":return x.InitMove;case"d":return x.Delete;case"y":return x.Yank;case"return":return x.Confirm;case"space":return x.Confirm;case"v":return K().viewMode==="wide"?x.SetViewDense:x.SetViewWide;case"q":case"escape":return x.Exit;default:return null}}function lg(e,t){let n=t===y.MOVE?{prevItem:x.MovePreviousItem,nextItem:x.MoveNextItem,prevContainer:x.MoveToPreviousContainer,nextContainer:x.MoveToNextContainer}:{prevItem:x.NavPreviousItem,nextItem:x.NavNextItem,prevContainer:x.NavToPreviousContainer,nextContainer:x.NavToNextContainer};return cg(v().contextNode.childRenderAxis,e,n)}var Lo=e=>{let{context:t}=v().contextNode;if(!t)return k.None;switch(e){case b.EXIT:return k.Exit;case b.EXPORT:return k.Export;case b.COFFEE:return k.Coffee;case b.INIT:return k.Init;case b.DELETE:return k.Delete;case b.EDIT:return k.Edit;case b.COMMENT:return k.Comment;case b.HELP:return k.ViewHelp;case b.RE_OPEN_ISSUE:return k.ReopenIssue;case b.CLOSE_ISSUE:return k.CloseIssue;case b.TAG:return k.TagTicket;case b.UNTAG:return k.UntagTicket;case b.ASSIGN:return k.AssignUserToTicket;case b.UNASSIGN:return k.UnassignUserFromTicket;case b.NEW:return k.NewItem;case b.FILTER:return k.Filter;case b.MOVE:return k.Move;case b.PEEK:return k.Peek;case b.REPLAY:return k.Replay;case b.CONFIG:return k.Config;case b.YANK:return k.Yank;case b.SYNC:return k.Sync;default:return k.None}},k={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",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 Be}from"ulid";import Kc from"node:fs";import ev from"node:path";import tv from"react";import{Box as Qg}from"ink";import _o from"react";import Rg from"chalk";import{Box as hi,Text as Ag}from"ink";import Et from"react";import{Text as Cc}from"ink";import Nc,{useEffect as Rc,useState as ug}from"react";var Ac={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},ke=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=j(),r=Ac[n]??Ac.default,[o,s]=ug(0);if(Rc(()=>{s(0)},[r]),Rc(()=>{if(!e)return;let c=setInterval(()=>{s(l=>(l+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return Nc.createElement(Cc,null,t);let i=r[o]??r[0]??t;return Nc.createElement(Cc,{color:h.accent,dimColor:o===1},i)};import{Box as yi,Text as mg}from"ink";import ko from"react";var tt=({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)),l=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,l-c+1)):Math.min(m,Math.floor(l/c)*c),f=p+c,g=e.slice(p,f),E=e.length>c,I=s,R=E?Math.max(1,Math.floor(c/e.length*I)):I,A=Math.max(0,I-R),P=Math.max(1,e.length-c),_=E?Math.floor(p/P*A):0;return ko.createElement(yi,{flexDirection:"row",height:s,width:"100%"},ko.createElement(yi,{flexDirection:"column",flexGrow:1,height:s},g),ko.createElement(yi,{flexDirection:"column",width:1,height:I},Array.from({length:I}).map((w,W)=>ko.createElement(mg,{key:W,color:E&&W>=_&&W<_+R?h.accent:h.secondary},E?"\u2502":" "))))};import{Box as _n,Text as Fo}from"ink";import nt from"react";import{Text as pg}from"ink";import fg from"react";var Fn=(e,t)=>t?e&&lr(e)===t?e:t:e,Tc,Do,wc=()=>{let{eventLog:e=[]}=v();if(Do&&Tc===e)return Do;let t=new Map,n=new Set;for(let r of e)r?.userId&&(n.add(r.userId),r.userName&&t.set(r.userId,r.userName));return Tc=e,Do={latestNames:t,authors:n},Do},Xt=(e,t)=>{let{contributors:n={}}=v();return n[e]?.tombstoned?t:Fn(t,wc().latestNames.get(e))??t},Mc=e=>wc().authors.has(e);var gg=e=>e.toLowerCase().trim(),vg=(e,t=wn)=>{let n=gg(e);return t[n]?t[n]:dr(n)},Jt=({id:e,isSelected:t})=>{let n=S.getContributor(e);if(!n)return;let r=Xt(e,n.name);return fg.createElement(pg,{underline:t,color:vg(r)},"@"+r,Mc(e)?"":"\u2197")};import{Text as yg}from"ink";import hg from"react";var Un=({id:e,isSelected:t})=>{let n=S.getTag(e);if(n)return hg.createElement(yg,{underline:t,backgroundColor:te(n.name),color:h.secondary}," "+n.name+" ")};import{useEffect as xg,useState as bg}from"react";var Ig=80,Pc=1400,Bo=new Set,xr=null,Eg=e=>(Bo.add(e),xr||(xr=setInterval(()=>{for(let t of Bo)t()},Ig)),()=>{Bo.delete(e),Bo.size===0&&xr&&(clearInterval(xr),xr=null)}),Sg=()=>{let e=Date.now()%Pc/Pc;return e<.5?e*2:(1-e)*2},On=e=>{let[,t]=bg(0);return xg(()=>{if(e)return Eg(()=>t(n=>n+1))},[e]),oo(Sg())};var Cg=(e,t)=>{if(e.length<=t)return[e,null];let n=e.lastIndexOf(" ",t),r=n>0?n:t;return[e.slice(0,r),mn(e.slice(r).trim(),t)]},Lc=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=On(r),s=e-4,[i,c]=Cg(Ze(t.title),s),l=c?null:mn(Ze(t.props.description),s)||null,m=zt(t),p=qt(t);return nt.createElement(_n,{borderStyle:"round",height:5,flexDirection:"column",borderDimColor:!n,borderColor:r?o:n?h.accent:h.secondary,justifyContent:"space-between"},nt.createElement(_n,{paddingLeft:1,flexDirection:"column"},nt.createElement(Fo,{color:h.primary},i),c&&nt.createElement(Fo,{color:h.primary},c),l&&nt.createElement(Fo,{color:h.secondary2,dimColor:!0},l)),nt.createElement(_n,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1,paddingRight:1},nt.createElement(_n,{flexDirection:"row"},m.map(f=>nt.createElement(_n,{paddingRight:1,key:f.id},nt.createElement(Un,{key:f.id,id:f.id}))),p.map(f=>nt.createElement(_n,{paddingRight:1,key:f.id},nt.createElement(Jt,{key:f.id,id:f.id})))),nt.createElement(Fo,{wrap:"truncate",color:h.secondary2,dimColor:!0},He(t.id))))};import{Box as bn,Text as br}from"ink";import ze from"react";var Ng=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,kc=({width:e,ticket:t,isSelected:n,isFlashing:r=!1,index:o,mode:s})=>{let i=On(r),c=(t.props.tags??[]).map(w=>S.getTag(w)).filter(w=>!!w),l=(t.props.assignees??[]).map(w=>S.getContributor(w)).map(w=>w&&{...w,name:Xt(w.id,w.name)}).filter(w=>!!w),m=1,p=c.length*(1+m),f=l.length*(2+m),g=c.map(w=>ze.createElement(bn,{key:w.id,paddingRight:m},ze.createElement(br,{color:te(w.name)},"\u25A0"))),E=l.map(w=>ze.createElement(bn,{key:w.id,paddingRight:m},ze.createElement(br,{color:dr(w.name)},"@"+w.name.at(0)))),I=r?i:n?h.accent:s===y.MOVE?h.secondary:h.primary,R=4,A=S.getCommentsByIssue(t.id),P=A.length?String(A.length).length+2+m:0,_=A.length?ze.createElement(bn,{paddingRight:m},ze.createElement(br,{color:h.accent},"[",A.length,"]")):null;return ze.createElement(bn,{borderBottom:!0,justifyContent:"space-between"},ze.createElement(bn,null,ze.createElement(bn,{width:R},n?ze.createElement(ke,{isSelected:n}):ze.createElement(br,{color:"gray",dimColor:!0},o+1)),ze.createElement(br,{wrap:"truncate",color:I},Ng(t.title,e-p-f-P-18))),ze.createElement(bn,null,g,E,_))};var Tg=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:l,replay:m}=j(),p=l[e.id]??[],f=m?new Set(m.flashNodeIds):null,g=f?.has(e.id)??!1,E=On(g),I=`${e.title} ${Rg.hex(h.secondary2).dim("("+p.length+")")}`,R=3,A=o?1:5,P=s&&i===-1,_=n-(P?7:5),w=r-R-(o?2:1),W=Et.createElement(hi,{borderStyle:"round",borderColor:h.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Et.createElement(ke,{isSelected:t}),Et.createElement(Ag,{bold:!0,color:g?E:t?h.accent:h.primary},I," ",e.readonly?"\u{1F512}":"")),H=(D,$)=>{let Ye=s&&i===$;if(!T(D))return null;let we=f?.has(D.id)??!1;return o?Et.createElement(kc,{key:D.id,index:$,width:n,ticket:D,isSelected:Ye,isFlashing:we,mode:c}):Et.createElement(Lc,{key:D.id,width:_,ticket:D,isSelected:Ye,isFlashing:we})};return Et.createElement(hi,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?h.accent:h.secondary,paddingRight:1,paddingLeft:1,height:r},W,Et.createElement(hi,{padding:o?1:0},p.length>0&&Et.createElement(tt,{selectedIndex:i,height:w,itemHeight:A},p.map(H)),P&&Et.createElement(ke,{isSelected:!0})))},Dc=Et.memo(Tg);import{Box as In,Text as Ci}from"ink";import Ce,{useMemo as Ir}from"react";var Bc=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},Fc=(e,t,n)=>ee.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 $n,Text as Mt}from"ink";import De,{useEffect as wg,useMemo as Mg,useRef as Pg}from"react";import{decodeTime as xi}from"ulid";var Lg=e=>Ie(e,"attachments"),kg=e=>S.getAttachmentsByIssue(e.id).sort((t,n)=>xi(t.id)-xi(n.id)),Uc=e=>{for(let t of e)S.deleteNode(t.id)},Dg=(e,t,n)=>ee.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),Bg=(e,t)=>{let n=S.getNode(Lg(e.id));if(!n||!Ve(n))return[];let r=t.map((o,s)=>Dg(o,s,n.id)).map(o=>S.createNode(o)).filter(Q).map(({value:o})=>o).filter(Ve);return t.length>0&&v().selectedIndex<0&&M.navigate({contextNode:n,selectedIndex:0}),r},Fg=e=>`${Math.max(1,Math.round(e/1024))} KB`;function Oc({ticket:e,width:t,height:n}){let r=Mg(()=>kg(e),[e]),o=Pg([]);wg(()=>(Uc(o.current),o.current=Bg(e,r),()=>{Uc(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=j(),c=Math.max(1,n-4),l=Math.max(12,t-32);return r.length===0?De.createElement($n,{flexDirection:"column",width:t,height:n,padding:1},De.createElement(Mt,{color:h.primary},"No attachments yet."),De.createElement($n,{paddingTop:1},De.createElement(Mt,{color:h.primary},"Attach images from the browser GUI"),De.createElement(Mt,{color:h.accent}," epiq gui "),De.createElement(Mt,{color:h.primary},"by dropping or pasting them."))):De.createElement($n,{flexDirection:"column",width:t,height:n},De.createElement($n,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:h.secondary,borderStyle:"single",paddingBottom:1},De.createElement(Mt,{color:h.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),De.createElement(tt,{height:c,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,g=m.name.length>l?m.name.slice(0,l-1)+"\u2026":m.name;return De.createElement($n,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},De.createElement(Mt,{color:h.accent},f?"\u276F ":" "),De.createElement($n,{paddingLeft:1},De.createElement(Mt,{color:h.secondary2},`#${p+1} `),De.createElement(Mt,{color:f?h.accent:h.primary},g),De.createElement(Mt,{color:h.secondary2}," "+Fg(m.bytes)+" "+Pn(xi(m.id)))))})))}import{Box as Qt,Text as Pt}from"ink";import he,{useEffect as Ug,useMemo as Og,useRef as _g}from"react";import{decodeTime as bi}from"ulid";var $g=e=>Ie(e,"comments"),Hg=e=>S.getCommentsByIssue(e.id).sort((t,n)=>bi(t.id)-bi(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),_c=e=>{for(let t of e)S.deleteNode(t.id)},jg=(e,t)=>{let n=S.getNode($g(e.id));if(!n||!Ve(n))return[];let r=t.map((o,s)=>Fc(o,s,n.id)).map(S.createNode).filter(Q).map(({value:o})=>o).filter(ar);return t.length>0&&v().selectedIndex<0&&M.navigate({contextNode:n,selectedIndex:0}),r},Wg=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`};function $c({ticket:e,width:t,height:n}){let r=Og(()=>Hg(e),[e]),o=_g([]);Ug(()=>(_c(o.current),o.current=jg(e,r),()=>{_c(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=j(),c=Math.max(1,n-4),l=Math.max(20,t-8);return r.length===0?he.createElement(Qt,{flexDirection:"column",width:t,height:n,padding:1},he.createElement(Pt,{color:h.primary},"No comments yet."),he.createElement(Qt,{paddingTop:1},he.createElement(Pt,{color:h.primary},"Use"),he.createElement(Pt,{color:h.accent}," :comment "),he.createElement(Pt,{color:h.primary},"to add the first one."))):he.createElement(Qt,{flexDirection:"column",width:t,height:n},he.createElement(Qt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:h.secondary,borderStyle:"single",paddingBottom:1},he.createElement(Pt,{color:h.secondary2},"Comments (",r.length,") ")),he.createElement(tt,{height:c,itemHeight:4,selectedIndex:s},r.map((m,p)=>{let f=p===s;return he.createElement(Qt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:h.secondary,borderStyle:"single"},he.createElement(Qt,{flexDirection:"row",paddingBottom:1},he.createElement(Pt,{color:h.accent},f?"\u276F ":" "),he.createElement(Qt,{paddingLeft:1},he.createElement(Pt,{color:h.secondary2},`#${p+1} `),he.createElement(Jt,{id:m.authorId}),he.createElement(Pt,{color:h.secondary2}," "+Pn(bi(m.id))))),he.createElement(Qt,{paddingLeft:3,paddingBottom:1},he.createElement(Pt,{color:h.primary},Wg(m.md,l))))})))}import{Box as Uo,Text as Vg}from"ink";import Lt from"react";var Hc=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=j(),{title:o}=t,s=t.parentNodeId?S.getNode(t.parentNodeId):void 0,i=s&&T(s)?o===Z.ASSIGNEES?s.props.assignees??[]:o===Z.TAGS?s.props.tags??[]:[]:[];return Lt.createElement(Uo,{alignItems:"center",paddingTop:1},Lt.createElement(Uo,{minWidth:12},Lt.createElement(ke,{isSelected:n}),Lt.createElement(Vg,{color:n?h.accent:h.secondary2},o,":")),Lt.createElement(Uo,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,l)=>{let m=r.id===t.id&&l===e;return Lt.createElement(Uo,{key:`${o}-${c}`,paddingRight:2,minHeight:1},Lt.createElement(ke,{isSelected:m}),o===Z.ASSIGNEES?Lt.createElement(Jt,{isSelected:m,id:c}):o===Z.TAGS?Lt.createElement(Un,{isSelected:m,id:c}):null)})))};import{Box as Oo,Text as Ii}from"ink";import kt,{useEffect as Gg,useMemo as jc}from"react";var Kg="\u2029",Wc=(e,t)=>`${e}::inline-line::${t}`,Ei=new Map,Vc=e=>{let t=Ei.get(e)??[];Ei.delete(e);for(let n of t)S.deleteNode(n)},zg=(e,t)=>{Vc(e);let n=[];t.forEach((r,o)=>{let s=Ge(BigInt(o+1));if(!Q(s))return;let i=S.createNode(ee.text({id:Wc(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));Q(i)&&n.push(i.value.id)}),Ei.set(e,n)},Si=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=j(),l=jc(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=jc(()=>l.join("\0"),[l]);Gg(()=>(zg(e,l),()=>{Vc(e)}),[e,m]);let p=g=>String(g).replace(/\r?\n/g,""),f=l.map((g,E)=>{let I=c.id===e&&i===E;return kt.createElement(Oo,{key:Wc(e,E)},kt.createElement(Ii,{color:I?h.primary:h.secondary2,dimColor:!I},`${E+1} `.padStart(5,"\xA0")),kt.createElement(Ii,{backgroundColor:I?"gray":void 0},p(g.length?mn(g,s-10):Kg)))});return kt.createElement(Oo,{flexDirection:"column",paddingTop:1},kt.createElement(Oo,null,kt.createElement(ke,{isSelected:o}),kt.createElement(Ii,{color:o?h.accent:h.secondary2},t)),kt.createElement(Oo,{flexDirection:"row",borderStyle:"round",borderColor:h.secondary,paddingLeft:1,marginLeft:1},kt.createElement(tt,{scrollByOne:!0,height:r-3,selectedIndex:i,itemHeight:1},f)))};var qg=e=>Ie(e,"description"),Yg=e=>Ie(e,"comments"),Xg=e=>Ie(e,"history"),Jg=e=>Ie(e,"attachments"),Gc=({ticket:e,height:t})=>{let n=Ir(()=>Bc(e),[e]),{selectedIndex:r,contextNode:o}=j(),s=process.stdout.columns||120,i=Ir(()=>qg(e.id),[e.id]),c=Ir(()=>Yg(e.id),[e.id]),l=Ir(()=>Xg(e.id),[e.id]),m=Ir(()=>Jg(e.id),[e.id]),p=S.getAttachmentsByIssue(e.id).length,f=o.id===e.id,g=o.id===c||o.parentNodeId===c,E=o.id===l||o.parentNodeId===l,I=o.id===m||o.parentNodeId===m,R=z(e.id);if(g){let $=t-3;return Ce.createElement(In,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ce.createElement($c,{ticket:e,width:s,height:$}))}if(I){let $=t-3;return Ce.createElement(In,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ce.createElement(Oc,{ticket:e,width:s,height:$}))}if(E){let D=S.getNode(l),$=D&&Ve(D)?D.props.value??"":"",we=t-3;return Ce.createElement(In,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},D?Ce.createElement(Si,{id:D.id,label:"Event log",text:$,selected:!1,maxWidth:s,height:we}):null)}let A=R.reduce((D,$)=>ir($)||$.id===c||$.id===m||$.id===l?D+1:D,0),P=2,_=3,w=A,W=t-_-w-P,H=(D,$)=>D.id===i?Ce.createElement(Si,{key:D.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:$,maxWidth:s,height:W}):ir(D)?Ce.createElement(Hc,{key:D.id,parent:D,selected:$,selectedIndex:r}):D.id===c?Ce.createElement(In,{key:D.id,paddingTop:1},Ce.createElement(ke,{isSelected:$}),Ce.createElement(Ci,{backgroundColor:h.secondary,color:$?h.accent:h.primary},` Comments (${n}) \u203A\u203A `)):D.id===m?Ce.createElement(In,{key:D.id,paddingTop:1},Ce.createElement(ke,{isSelected:$}),Ce.createElement(Ci,{backgroundColor:h.secondary,color:$?h.accent:h.primary},` Attachments (${p}) \u203A\u203A `)):D.id===l?Ce.createElement(In,{key:D.id,paddingTop:1},Ce.createElement(ke,{isSelected:$}),Ce.createElement(Ci,{backgroundColor:h.secondary,color:$?h.accent:h.primary}," History \u203A\u203A ")):null;return Ce.createElement(In,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R.map((D,$)=>H(D,f&&r===$)))};var Zg=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let l=t.context,m=l===B.TICKET||l===B.FIELD_LIST||l===B.FIELD,p=l===B.BOARD||l===B.SWIMLANE,f=l===B.TICKET?t:r.find(A=>A.context===B.TICKET),g=Math.floor(c/3),E=Math.floor(c/Math.max(e.length,1)),I=Math.min(E,g),R=s==="dense";return _o.createElement(Qg,{flexDirection:"row",height:i},p&&e.map((A,P)=>{let _=t.id===A.id,w=_?n:-1,W=t.context===B.BOARD&&n===P;return _o.createElement(Dc,{key:A.id,height:i,width:I,swimlane:A,isSelected:W,isDense:R,isFocused:_,listSelectedIndex:w,mode:o})}),m&&f&&_o.createElement(Gc,{height:i,ticket:f}))},$o=_o.memo(Zg);import{render as nv}from"ink";import{Writable as rv}from"node:stream";var Er=e=>String(e).padStart(2,"0"),ov=e=>{let t=e.getUTCFullYear(),n=Er(e.getUTCMonth()+1),r=Er(e.getUTCDate()),o=Er(e.getUTCHours()),s=Er(e.getUTCMinutes()),i=Er(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},sv=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",iv=async(e,{width:t,height:n})=>{let r="",o=new rv({write(i,c,l){let m=av(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),l()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=nv(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},av=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),zc=async()=>{let{viewMode:e}=K(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=v(),i=r.find(P=>P.context==="BOARD");if(!i)return a("No board found to export");let c=120,l=40,m=await iv(tv.createElement($o,{height:l,width:c,swimlanes:(s[i.id]??[]).filter(P=>P!==void 0&&Ht(P)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:l});if(!m)return a("Failed to render board export");let p=Hr(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let f=new Date,g=ov(f),E=`board_${sv(i.title)}_${g}.md`,I=wa(p.value);Kc.mkdirSync(I,{recursive:!0});let R=ev.join(I,E),A=`# Board - ${i.title}
46
+ `)}`):(If(),C({hasProjectDefinition:!0}),u("State booted successfully",null))}var vn=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),xo=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)}},J=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);var xt=null,bo=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!xt,currentStatus:v().syncStatus?.status,currentMessage:v().syncStatus?.msg}),xt)return logger.debug("[sync] syncAndReloadState joining existing promise"),xt;logger.debug("[sync] syncAndReloadState creating promise"),xt=Sf();try{let e=await xt;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:v().syncStatus?.status,statusMessageAfterResolve:v().syncStatus?.msg}),d(e)&&v().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}),xt||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:v().syncStatus?.status,statusMessageBeforeClear:v().syncStatus?.msg}),xt=null}},Sf=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:v().mode,syncStatus:v().syncStatus});let e=Od();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:v().mode,message:e.message,syncStatus:v().syncStatus}),e;if(xt)return xt;logger.debug("[sync] syncAndReloadState:start");let t=J("resolveActorId",ae());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:v().syncStatus});let n=pn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=J("syncEpiqWithRemote",await Io({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:v().syncStatus}),et(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let s=J("loadMergedEvents",je(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:v().syncStatus}),a(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let i=Od();if(i)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:v().mode,message:i.message,syncStatus:v().syncStatus}),i;let c=Dd(),l=v().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:c,selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id,selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual}),!v().selectedNode?.isVirtual&&!v().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let p=J("bootStateFromEventLog",gn(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:v().syncStatus}),a(`Unable to boot synced state. ${p.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),C({filters:l}),logger.debug("[sync] restoreNavigationAnchor:start");let m=J("restoreNavigationAnchor",Fd(c));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(m),message:d(m)?m.message:"Navigation restored",selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id}),d(m)?(C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:v().syncStatus}),m):(C({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:v().syncStatus}),u("Synced",!0))},Od=()=>v().mode===h.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:v().mode,syncStatus:v().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 kn=3e3,_d=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<kn?null:t},$d=0,si,ii=!1,mr=!1,ai=()=>{if(ii)return!0;let e=Ge();return d(e)?!1:e.value.syncStatus.status==="syncing"},Cf=()=>{let e=K().autoSyncIntervalMs??1e4,t=Date.now()-$d;return Math.max(0,e-t)},Hd=()=>{si||(si=setTimeout(async()=>{if(si=void 0,!!zt()){if(ai()){mr=!0;return}mr=!1,await Nf()}},Cf()))},Nf=async()=>{if(v().readOnly||v().timeMode==="peek"||v().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!zt())return a("Cannot auto-sync before state is initialized");if(ai())return mr=!0,a("Sync already in progress");ii=!0,$d=Date.now(),C({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await bo()}finally{ii=!1,mr&&Hd()}},Eo=()=>{zt()&&(mr=!0,!ai()&&Hd())};var qt=()=>{let e=K(),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}},Wd=()=>{let e=He(process.cwd());if(d(e))return!1;let t=mt(e.value);return Q(t)},jd=e=>e===!0?"on":e===!1?"off":null,Gd=e=>e==="on"?!0:e==="off"?!1:null;var Rf=e=>e.props.tags??[],Af=e=>e.props.assignees??[],Yt=e=>Rf(e).map(t=>S.getTag(t)).filter(t=>!!t),Xt=e=>Af(e).map(t=>S.getContributor(t)).filter(t=>!!t),So=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!T(n)?a("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",Yt(n))},Co=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!T(n)?a("Invalid unassign target"):u("Retrieved assignees from ticket in breadcrumb",Xt(n))};var b={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",YANK:"yank",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""};var Tf=/^(\d+)(h|d|w|mo|y)$/,wf=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Mf=({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},Pf=(e,t=new Date)=>{let n=e.match(Tf);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}},Lf=e=>{let t=e.match(wf);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),l=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return Mf({year:c,month:l,day:m,hour:p,minute:f})?new Date(c,l-1,m,p,f):null},hn=e=>{let t=e.trim().toLowerCase();return Pf(t)??Lf(t)};var Vd=/^(\d+)(s|m)?$/,No=e=>{let t=e.trim().toLowerCase().match(Vd);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Ro=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Vd.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Kd=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,kf=[{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}],di=(e=kf)=>{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 Df=["BOARD","TICKET","SWIMLANE","COMMENT"],oe={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},ze={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},he={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},Bf=[oe.EDITOR,oe.VIEW,oe.USERNAME,oe.AUTOSYNC,oe.SYNC_DEBOUNCE_MS,oe.ATTACHMENT_MAX_KB,oe.LOG_LEVEL],Ff=(e=v().selectedNode?.context)=>{switch(e){case"TICKET":return[ze.TITLE,ze.DESCRIPTION];case"BOARD":case"SWIMLANE":return[ze.TITLE];case"COMMENT":return[ze.COMMENT];default:return[]}},li=[String(kn),"5000","15000","30000","60000"],ui=["250","500","1000"],Yd=["10s","20s","30s","45s"],yn=[b.COFFEE,b.EXIT,b.SYNC,b.HELP,b.EXPORT,b.CONFIG,b.YANK],Ao=[b.NEW,b.EDIT,b.DELETE,b.MOVE],ci=[b.TAG,b.UNTAG,b.ASSIGN,b.UNASSIGN,b.CLOSE_ISSUE,b.RE_OPEN_ISSUE,b.EDIT,b.COMMENT],zd=[b.FILTER,b.PEEK,b.REPLAY],Uf={WORKSPACE:[...yn,...Ao],BOARD:[...zd,...yn,...Ao],SWIMLANE:[...zd,...yn,...Ao],TICKET:[...yn,...Ao,...ci],FIELD:[...yn,...ci],FIELD_LIST:[...yn,...ci],TEXT:[...yn],COMMENT:[b.EDIT,b.DELETE,b.YANK]},Of=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],pr=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&T(n)),qd=e=>e.parentNodeId===ve,_f=({selectedNode:e,breadCrumb:t})=>{let n=Ff(e?.context);return pr({breadCrumb:t,selectedNode:e})?n.includes(ze.DESCRIPTION)?n:[...n,ze.DESCRIPTION]:n},$f=({selectedNode:e,breadCrumb:t})=>{let n=pr({breadCrumb:t,selectedNode:e});return n?[he.REF,he.TITLE,...n.props?.description?.trim()?[he.DESCRIPTION]:[],...Yt(n).length>0?[he.TAGS]:[],...Xt(n).length>0?[he.ASSIGNEES]:[]]:e?[he.REF,he.TITLE]:[]},Hf=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=qt();if(!r)return[b.HELP,b.CONFIG];if(!Wd())return[b.HELP,b.INIT];if(t)return[b.HELP,b.PEEK,b.REPLAY,b.EXPORT,b.CONFIG,b.YANK];let o=e?.context,s=o&&Df.includes(o),i=[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?Uf[l]:[]))],c=pr({breadCrumb:n,selectedNode:e});return i.filter(l=>l===b.MOVE?!1:l===b.YANK?!!(c??e):l===b.EDIT?s||!!c:l===b.DELETE?s:l===b.UNTAG?!!(c&&Yt(c).length>0):l===b.UNASSIGN?!!(c&&Xt(c).length>0):l===b.RE_OPEN_ISSUE?!!(c&&qd(c)):l===b.CLOSE_ISSUE?!!(c&&!qd(c)):!0)},de=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let s=t.context??"WORKSPACE";return{[b.NONE]:Hf({breadCrumb:o,readOnly:r,selectedNode:n}),[b.EXIT]:["confirm"],[b.EXPORT]:[],[b.SYNC]:[],[b.INIT]:[],[b.HELP]:[],[b.PEEK]:[...di(),"now","prev","next"],[b.REPLAY]:[...di()],[b.EDIT]:_f({selectedNode:n,breadCrumb:o}),[b.YANK]:$f({selectedNode:n,breadCrumb:o}),[b.COMMENT]:[],[b.DELETE]:["confirm"],[b.RE_OPEN_ISSUE]:["confirm"],[b.CLOSE_ISSUE]:["confirm"],[b.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[b.FILTER]:["tag","assignee","description","title","ref","clear"],[b.TAG]:[...new Set([...Object.keys(wn),...S.getExistingTags()])],[b.UNTAG]:[...So()?.value?.map(({name:c})=>c)??[]],[b.UNASSIGN]:[...Co()?.value?.map(({name:c})=>c)??[]],[b.ASSIGN]:S.getExistingAssignees(),[b.NEW]:Of(s),[b.CONFIG]:[...Bf],[b.COFFEE]:["1","3","5","20","custom"]}[e]??[]};import ac from"chalk";var Xd=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import{decodeTime as Jd}from"ulid";var To=e=>{try{return u("Decoded date",new Date(Jd(e)))}catch(t){return a("Decoding failed + "+t.message)}},Jt=e=>{if(!e?.id)return null;try{return Jd(e.id)}catch{return null}};import Kf from"zod";import Wf from"node:crypto";import fr from"node:fs";import Qd from"node:path";var bt=500,jf=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,Dn=(e,t)=>`${e}.${t}`,Gf=e=>jf.test(e),Zd=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?u("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?u("Sniffed image type","jpg"):e.length>=6&&(e.subarray(0,6).equals(Buffer.from("GIF87a","ascii"))||e.subarray(0,6).equals(Buffer.from("GIF89a","ascii")))?u("Sniffed image type","gif"):e.length>=12&&e.subarray(0,4).equals(Buffer.from("RIFF","ascii"))&&e.subarray(8,12).equals(Buffer.from("WEBP","ascii"))?u("Sniffed image type","webp"):a(`Unsupported image format. Allowed: ${sd.join(", ")}`),ec=e=>Wf.createHash("sha256").update(e).digest("hex"),Vf=(e,t=bt)=>{if(e.length===0)return a("Attachment is empty");if(e.length>t*1024)return a(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=Zd(e);return d(n)?n:u("Validated attachment data",{hash:ec(e),ext:n.value,bytes:e.length})},tc=(e,t,n=bt)=>{let r=Vf(t,n);if(d(r))return r;let o=nr(e),s=Qd.join(o,Dn(r.value.hash,r.value.ext));try{fr.existsSync(s)||(fr.mkdirSync(o,{recursive:!0}),fr.writeFileSync(s,t))}catch(i){return a(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return u("Wrote attachment blob",r.value)},nc=(e,t,n=bt)=>{if(!Gf(t))return a("Invalid attachment file name");let r=Qd.join(nr(e),t);if(!fr.existsSync(r))return a("Attachment blob not found");let o;try{o=fr.readFileSync(r)}catch(l){return a(`Unable to read attachment blob: ${l instanceof Error?l.message:String(l)}`)}if(o.length>n*1024)return a(`Attachment exceeds the ${n} KB size cap and will not be served`);let[s,i]=t.split(".");if(ec(o)!==s)return a("Attachment blob does not match its content hash");let c=Zd(o);return d(c)?c:c.value!==i?a("Attachment blob content does not match its extension"):u("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var gr=50,vr=5e3,rc=()=>{let e=X().commandMeta.inputString,t=Kf.coerce.number().int().min(gr).max(vr).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${gr}-${vr} KB (default ${bt})`);let n=Qe({attachmentMaxKb:t.data});return d(n)?n:(Me({attachmentMaxKb:t.data}),C({mode:h.DEFAULT}),u(`Attachment size cap set to ${t.data} KB`,null))};import oc from"chalk";var ne=e=>oc.dim(e),Ee=e=>oc.hex(y.primary)(e),Se=({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(f=>f.startsWith(i))].sort((f,g)=>io(f)-io(g)).slice(0,r).map(f=>ao(f)).join(" ");return p?`${ne(e)}${p}${ne(n)}`:""};var It={None:"none",Invalid:"invalid",Valid:"valid"};var zf=["BOARD","TICKET","SWIMLANE"],sc=()=>{let e=v().selectedNode;if(!e?.context)return _({message:ne("Missing target context")});if(zf.includes(e.context))return V();if(e.parentNodeId){let t=v().nodes[e.parentNodeId];if(t?.id===Ie(t?.parentNodeId??"","comments"))return V()}return _({message:ne("Command not available in this context")})},se="<ENTER> to confirm",V=(e="",t=[])=>({message:ne(e),validity:It.Valid,completionWordList:t}),_=({message:e,completionWordList:t=[]})=>({validity:It.Invalid,message:e,completionWordList:t}),Mo=e=>e.length===0,ic=(e,t)=>{let n=_e(v().breadCrumb,"BOARD");if(d(n))return _({message:Ee("Command is not applicable in this context")});let r=To(n.value.id);return d(r)?_({message:Ee(`Unable to ${t}: board id is not a valid ULID`)}):Kd({date:e,horizonDate:r.value})?null:_({message:Ee(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},wo=e=>` ${ac.hex("#000").bgHex(te(e))(` ${e} `)} `,mi=({modifier:e})=>{let t="confirm";return e===t?V(se):_({message:Mo(e)?ne("if you are certain, enter ")+ao(t):"",completionWordList:[t]})},qf=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?_({message:ne(n)}):V():_({message:Mo(r)?t:"",completionWordList:[...e]}),xn=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>Mo(n)&&Mo(r)?_({message:e,completionWordList:[]}):V(t??se),Yf=({modifier:e,inputString:t})=>{let n=de(b.CONFIG);if(!n.includes(e))return _({message:Se({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case oe.EDITOR:{let r=[...Xd];return t.trim()?r.includes(t.trim())?V(se):_({message:Se({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):_({message:Se({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case oe.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?V(se):_({message:Se({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case oe.USERNAME:return t.trim()?V(se):_({message:Ee("Enter a user name. Saved in ")+ac.bgBlack("~/.epiq-global/config.json")});case oe.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?V(se):_({message:Se({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case oe.AUTOSYNC:{let r=["on","off"],o=K().autoSync;if(!r.includes(t.trim())){let s=jd(o);return _({message:Se({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return V(se)}case oe.ATTACHMENT_MAX_KB:{let r=K().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<gr||o>vr){let s=Se({prefix:" examples: ",wordList:ui,minLengthForHints:0,inputString:t});return _({message:Ee(`provide a size cap in KB (${gr}-${vr}). current: ${r??bt} KB.`)+s,completionWordList:ui})}return V(se)}case oe.SYNC_DEBOUNCE_MS:{let r=K().autoSyncIntervalMs,o=_d(t);if(!t.trim()||o===null||o<kn){let s=Se({prefix:" examples: ",wordList:li,minLengthForHints:0,inputString:t});return _({message:Ee(`provide duration above ${kn}ms. current duration: ${r}ms.`)+s,completionWordList:li})}return V(se)}default:return _({message:Ee("Unknown config option"),completionWordList:n})}},Xf=({modifier:e,inputString:t})=>{let n=de(b.EDIT);if(!n.length)return _({message:Ee("Command not available in this context")});if(!n.includes(e)){let r=Se({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return _({message:r||Ee("Unknown edit option"),completionWordList:n})}switch(e){case ze.COMMENT:return t.trim()?V(se):_({message:ne("write a comment...")});case ze.TITLE:return V(se);case ze.DESCRIPTION:{let{preferredEditor:r}=K();return r?V(ne("<ENTER> to edit in ")+r):_({message:"No editor selected"})}default:return _({message:Ee("Unknown edit option"),completionWordList:n})}},Jf=({modifier:e})=>{let t=de(b.YANK);return t.length?t.includes(e)?V(se+ne(" and copy to clipboard")):_({message:Se({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):_({message:Ee("Nothing selected to copy from")})},Qf={[b.EXPORT]:()=>V(se+ne(", and create export markdown file")),[b.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return V(se);let n={message:ne("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=hn(r);if(!r||!o)return _(n);let s=ic(o,"peek");return s||V(se)},[b.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Ro(e.modifier,e.inputString),r={message:ne("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=hn(t);if(!t||!o)return _(r);let s=ic(o,"replay");return s||(n&&No(n)===null?_({message:Ee("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):V("<ENTER> to replay board history",n?Yd:[]))},[b.EXIT]:()=>V(se+ne(" and exit the application")),[b.INIT]:()=>V(se),[b.PALETTE]:()=>V(se),[b.FILTER]:e=>{if(e.modifier==="clear")return V(se);let t=s=>de(b.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return _({message:Se({wordList:de(b.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:de(b.FILTER)});let n=Object.values(v().tags).map(s=>s.name),r=Object.values(v().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?_({message:Se({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):V():_({message:Se({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[b.NONE]:e=>{let t=de(b.NONE);return _({message:Se({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[b.NEW]:e=>qf({list:de(b.NEW),hint:Se({wordList:de(b.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[b.HELP]:()=>V(se),[b.EDIT]:Xf,[b.COMMENT]:e=>{let t=xn({hint:ne(`write a comment (max ${4e3} char)...`),onOk:ne(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===It.Invalid?t:e.inputString.length>4e3?V(Ee("max input exceeded")):t},[b.CONFIG]:Yf,[b.YANK]:Jf,[b.DELETE]:e=>{let t=sc();return t.validity==="invalid"?t:mi(e)},[b.CLOSE_ISSUE]:e=>mi(e),[b.RE_OPEN_ISSUE]:e=>mi(e),[b.MOVE]:e=>{let t=sc();return t.validity==="invalid"?t:xn({hint:Se({prefix:"hey hacker! These commands are blocked for you... ",wordList:de(b.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[b.TAG]:e=>{let n=S.getExistingTags().slice(0,10).map(wo).join("");return xn({hint:n.length?ne("create tag or reuse:")+n+ne(""):ne("create tag ...")})(e)},[b.UNTAG]:e=>{let t=So();if(d(t))return _({message:Ee("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(wo).slice(0,10);return n.length?xn({hint:ne(" ... ")+n.join("")})(e):_({message:Ee("Issue has no tags"),completionWordList:[]})},[b.ASSIGN]:e=>{let t=S.getExistingAssignees().map(wo).slice(0,10);return xn({hint:ne("assignees... ")+t.join("")})(e)},[b.UNASSIGN]:e=>{let t=Co();if(d(t))return _({message:Ee("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(wo).slice(0,10);return n.length?xn({hint:ne("remove assignee... ")+n.join("")})(e):_({message:Ee("Issue has no assignees"),completionWordList:[]})},[b.SYNC]:()=>V(se),[b.COFFEE]:e=>{let{modifier:t}=e,n=de(b.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?_({message:ne("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):xn({hint:Se({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},dc=Object.fromEntries(Object.entries(Qf).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Po=["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 Zf=3,eg=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"]),tg=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},ng=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=Zf&&!eg.has(t)&&!/^\d+$/.test(t)),rg=e=>{let t=new Map;for(let s of tg(e))for(let i of ng(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=Po.filter(s=>!r.has(s));return[...n,...o]},cc=Po,lc=-1,uc=()=>{let e=Ge();if(d(e))return Po;let t=e.value,n=t.eventLog.length;return n!==lc&&(cc=rg(t),lc=n),cc};var mc=e=>Object.values(b).includes(e),pc=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:l}=dc[n].validate(n,r,s),m=n!==b.PEEK&&n!==b.REPLAY,p=o==="command"||o==="modifier"?de(n):m?uc():[],{mode:f}=v(),g=f===h.COMMAND_LINE?i??"":"",E=[...l,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?nd(e,E):{hint:"",hints:[],remainder:"",overlap:0}}};var fc=e=>{let t=e.trimStart(),n=sg(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=ig(e),c=mc(r)?r:null,l=c!==null,m=r!=="",p=c?de(c)??[]:[],f=c&&p.includes(o)?o:"",g="word";n.length===0||n.length===1&&!s?g="command":(n.length===1&&s||n.length===2&&!s)&&(g="modifier");let E=s?"":i,I=og(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:c,isCommandKeyword:l,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:E,inputString:I}},og=(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},sg=e=>e.trim()?e.trim().split(/\s+/):[],ig=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as ag}from"react";var Bn=e=>e===pi||e===":",pi=" ",Le={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:It.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},fi=new Set,gc=()=>{for(let e of fi)e()},gi=e=>(fi.add(e),()=>fi.delete(e)),Et=e=>{let n=e(Le),r=fc(n.value),o=n.cursorPosition===n.value.length;Le={...n,commandMeta:pc(r,o)},gc()},hr=({message:e,status:t})=>{let n=structuredClone(Le);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Le=n,gc(),u(e,null)},vi=e=>{Et(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},hi=e=>{Et(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}})},vc=()=>{Et(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}})},hc=()=>{Et(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}})},Lo=e=>{Et(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}})},yc=()=>{Et(e=>({...e,commandIsPending:!0}))},G=e=>{Et(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},xc=({addToHistory:e=!0})=>{Et(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},bc=()=>{Et(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}})},Ic=()=>{Et(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},X=()=>Le,Ec=()=>ag(gi,X,X),Sc=()=>{let[e,...t]=Le.value.split(pi);return t.join(pi).trim()};var x={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",Yank:"yank",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function dg(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function cg(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function lg(e,t,n){let r=v().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function Cc(e,t){let n=X();if(e.sequence==="?"&&t!==h.PALETTE)return x.InitCommandPalette;if(e.sequence===":"&&t!==h.COMMAND_LINE)return x.InitCommandLine;if(t===h.MOVE)switch(e.name){case"m":case"return":return x.ConfirmMove}if(t===h.COMMAND_LINE)return Ya(e,n.value);if(t===h.PALETTE)return Xa(e,n.value);let r=dg(e)||cg(e);if(r)return ug(r,t);if(e.ctrl&&e.name==="c")return x.Exit;switch(e.name){case"r":return x.EditTitle;case"e":return x.EditDescription;case"n":return x.AddItem;case"m":return x.InitMove;case"d":return x.Delete;case"y":return x.Yank;case"return":return x.Confirm;case"space":return x.Confirm;case"v":return K().viewMode==="wide"?x.SetViewDense:x.SetViewWide;case"q":case"escape":return x.Exit;default:return null}}function ug(e,t){let n=t===h.MOVE?{prevItem:x.MovePreviousItem,nextItem:x.MoveNextItem,prevContainer:x.MoveToPreviousContainer,nextContainer:x.MoveToNextContainer}:{prevItem:x.NavPreviousItem,nextItem:x.NavNextItem,prevContainer:x.NavToPreviousContainer,nextContainer:x.NavToNextContainer};return lg(v().contextNode.childRenderAxis,e,n)}var ko=e=>{let{context:t}=v().contextNode;if(!t)return k.None;switch(e){case b.EXIT:return k.Exit;case b.EXPORT:return k.Export;case b.COFFEE:return k.Coffee;case b.INIT:return k.Init;case b.DELETE:return k.Delete;case b.EDIT:return k.Edit;case b.COMMENT:return k.Comment;case b.HELP:return k.ViewHelp;case b.RE_OPEN_ISSUE:return k.ReopenIssue;case b.CLOSE_ISSUE:return k.CloseIssue;case b.TAG:return k.TagTicket;case b.UNTAG:return k.UntagTicket;case b.ASSIGN:return k.AssignUserToTicket;case b.UNASSIGN:return k.UnassignUserFromTicket;case b.NEW:return k.NewItem;case b.FILTER:return k.Filter;case b.MOVE:return k.Move;case b.PEEK:return k.Peek;case b.REPLAY:return k.Replay;case b.CONFIG:return k.Config;case b.YANK:return k.Yank;case b.SYNC:return k.Sync;default:return k.None}},k={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",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 Be}from"ulid";import zc from"node:fs";import ov from"node:path";import sv from"react";import{Box as nv}from"ink";import $o from"react";import Mg from"chalk";import{Box as xi,Text as Pg}from"ink";import Ct from"react";import{Text as Nc}from"ink";import Rc,{useEffect as Ac,useState as mg}from"react";var Tc={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},ke=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=j(),r=Tc[n]??Tc.default,[o,s]=mg(0);if(Ac(()=>{s(0)},[r]),Ac(()=>{if(!e)return;let c=setInterval(()=>{s(l=>(l+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return Rc.createElement(Nc,null,t);let i=r[o]??r[0]??t;return Rc.createElement(Nc,{color:y.accent,dimColor:o===1},i)};import{Box as yi,Text as pg}from"ink";import Do from"react";var tt=({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)),l=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,l-c+1)):Math.min(m,Math.floor(l/c)*c),f=p+c,g=e.slice(p,f),E=e.length>c,I=s,N=E?Math.max(1,Math.floor(c/e.length*I)):I,A=Math.max(0,I-N),P=Math.max(1,e.length-c),F=E?Math.floor(p/P*A):0;return Do.createElement(yi,{flexDirection:"row",height:s,width:"100%"},Do.createElement(yi,{flexDirection:"column",flexGrow:1,height:s},g),Do.createElement(yi,{flexDirection:"column",width:1,height:I},Array.from({length:I}).map((H,W)=>Do.createElement(pg,{key:W,color:E&&W>=F&&W<F+N?y.accent:y.secondary},E?"\u2502":" "))))};import{Box as xr,Text as br}from"ink";import nt from"react";var Fn=(e,t)=>t?e&&cr(e)===t?e:t:e,wc,Bo,Mc=()=>{let{eventLog:e=[]}=v();if(Bo&&wc===e)return Bo;let t=new Map,n=new Set;for(let r of e)r?.userId&&(n.add(r.userId),r.userName&&t.set(r.userId,r.userName));return wc=e,Bo={latestNames:t,authors:n},Bo},St=(e,t)=>{let{contributors:n={}}=v();return n[e]?.tombstoned?t:Fn(t,Mc().latestNames.get(e))??t},Fo=e=>Mc().authors.has(e);import{Text as fg}from"ink";import gg from"react";var vg=e=>e.toLowerCase().trim(),hg=(e,t=wn)=>{let n=vg(e);return t[n]?t[n]:ar(n)},Qt=({id:e,isSelected:t,maxWidth:n})=>{let r=S.getContributor(e);if(!r)return;let o=St(e,r.name),s=n===void 0?o:ot(o,n);return gg.createElement(fg,{underline:t,color:hg(s)},"@"+s,Fo(e)?"":"\u2197")};import{Text as yg}from"ink";import xg from"react";var Un=({id:e,isSelected:t,maxWidth:n})=>{let r=S.getTag(e);if(!r)return;let o=n===void 0?r.name:ot(r.name,n);return xg.createElement(yg,{underline:t,backgroundColor:te(r.name),color:y.secondary}," "+o+" ")};import{useEffect as bg,useState as Ig}from"react";var Eg=80,Pc=1400,Uo=new Set,yr=null,Sg=e=>(Uo.add(e),yr||(yr=setInterval(()=>{for(let t of Uo)t()},Eg)),()=>{Uo.delete(e),Uo.size===0&&yr&&(clearInterval(yr),yr=null)}),Cg=()=>{let e=Date.now()%Pc/Pc;return e<.5?e*2:(1-e)*2},On=e=>{let[,t]=Ig(0);return bg(()=>{if(e)return Sg(()=>t(n=>n+1))},[e]),so(Cg())};var Rg=(e,t,n)=>{if(e.length<=t)return[e,null];let r=e.lastIndexOf(" ",t),o=r>0?r:t;return[e.slice(0,o),ot(e.slice(o).trim(),n)]},Lc=3,Ag=2,Tg=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let i=e.length-o-1,c=i>0?String(i).length+1:0;if(r+s.width+c>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},kc=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=On(r),s=e-4,i=s-7-1,[c,l]=Rg(Ze(t.title),i,s),m=l?null:ot(Ze(t.props.description),s)||null,p=Yt(t),f=Xt(t).map(N=>({...N,name:St(N.id,N.name)})),g=Math.max(1,s-Lc),{shown:E,hidden:I}=Tg([...p.map(N=>({id:N.id,isTag:!0,width:Math.min(N.name.length,g)+Lc})),...f.map(N=>({id:N.id,isTag:!1,width:Math.min(N.name.length,g)+Ag+(Fo(N.id)?0:1)}))],s);return nt.createElement(xr,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?y.accent:y.secondary,justifyContent:"space-between"},nt.createElement(xr,{paddingLeft:1,paddingRight:1,flexDirection:"column"},nt.createElement(xr,{justifyContent:"space-between"},nt.createElement(br,{color:y.primary},c),nt.createElement(br,{color:y.secondary2,dimColor:!0},We(t.id))),l&&nt.createElement(br,{color:y.primary},l),m&&nt.createElement(br,{color:y.secondary2,dimColor:!0},m)),nt.createElement(xr,{flexDirection:"row",paddingLeft:1,paddingRight:1},E.map(N=>nt.createElement(xr,{paddingRight:1,key:N.id},N.isTag?nt.createElement(Un,{id:N.id,maxWidth:g}):nt.createElement(Qt,{id:N.id,maxWidth:g}))),I>0&&nt.createElement(br,{color:y.secondary2,dimColor:!0},"+",I)))};import{Box as bn,Text as Ir}from"ink";import qe from"react";var wg=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,Dc=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let c=On(s),l=(r.props.tags??[]).map(w=>S.getTag(w)).filter(w=>!!w),m=(r.props.assignees??[]).map(w=>S.getContributor(w)).map(w=>w&&{...w,name:St(w.id,w.name)}).filter(w=>!!w),p=1,f=l.length*(1+p),g=m.length*(2+p),E=l.map(w=>qe.createElement(bn,{key:w.id,paddingRight:p},qe.createElement(Ir,{color:te(w.name)},"\u25A0"))),I=m.map(w=>qe.createElement(bn,{key:w.id,paddingRight:p},qe.createElement(Ir,{color:ar(w.name)},"@"+w.name.at(0)))),N=s?c:o?y.accent:i===h.MOVE?y.secondary:y.primary,A=S.getCommentsByIssue(r.id),P=A.length?String(A.length).length+2+p:0,F=A.length?qe.createElement(bn,{paddingRight:p},qe.createElement(Ir,{color:y.accent},"[",A.length,"]")):null,H=f+g+P,W=Math.max(1,n-t-H-(H>0?1:0));return qe.createElement(bn,{justifyContent:"space-between"},qe.createElement(bn,null,qe.createElement(bn,{width:t},o?qe.createElement(ke,{isSelected:!0}):qe.createElement(Ir,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),qe.createElement(Ir,{wrap:"truncate",color:N},wg(r.title,W))),qe.createElement(bn,null,E,I,F))};var Lg=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:l,replay:m}=j(),p=l[e.id]??[],f=m?new Set(m.flashNodeIds):null,g=f?.has(e.id)??!1,E=On(g),I=`${e.title} ${Mg.hex(y.secondary2).dim("("+p.length+")")}`,N=3,A=o?1:5,P=s&&i===-1,F=n-3-(o?1:0)-(P?2:0),H=Math.max(2,String(p.length).length+1),W=r-N-1,w=Ct.createElement(xi,{borderStyle:"round",borderColor:y.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},Ct.createElement(ke,{isSelected:t}),Ct.createElement(Pg,{bold:!0,color:g?E:t?y.accent:y.primary},I," ",e.readonly?"\u{1F512}":"")),B=($,Xe)=>{let we=s&&i===Xe;if(!T($))return null;let Ue=f?.has($.id)??!1;return o?Ct.createElement(Dc,{key:$.id,index:Xe,labelWidth:H,width:F,ticket:$,isSelected:we,isFlashing:Ue,mode:c}):Ct.createElement(kc,{key:$.id,width:F,ticket:$,isSelected:we,isFlashing:Ue})};return Ct.createElement(xi,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},w,Ct.createElement(xi,null,p.length>0&&Ct.createElement(tt,{selectedIndex:i,height:W,itemHeight:A},p.map(B)),P&&Ct.createElement(ke,{isSelected:!0})))},Bc=Ct.memo(Lg);import{Box as In,Text as Ni}from"ink";import Ce,{useMemo as Er}from"react";var Fc=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},Uc=(e,t,n)=>ee.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 _n,Text as Lt}from"ink";import De,{useEffect as kg,useMemo as Dg,useRef as Bg}from"react";import{decodeTime as bi}from"ulid";var Fg=e=>Ie(e,"attachments"),Ug=e=>S.getAttachmentsByIssue(e.id).sort((t,n)=>bi(t.id)-bi(n.id)),Oc=e=>{for(let t of e)S.deleteNode(t.id)},Og=(e,t,n)=>ee.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),_g=(e,t)=>{let n=S.getNode(Fg(e.id));if(!n||!Ve(n))return[];let r=t.map((o,s)=>Og(o,s,n.id)).map(o=>S.createNode(o)).filter(Q).map(({value:o})=>o).filter(Ve);return t.length>0&&v().selectedIndex<0&&M.navigate({contextNode:n,selectedIndex:0}),r},$g=e=>`${Math.max(1,Math.round(e/1024))} KB`;function _c({ticket:e,width:t,height:n}){let r=Dg(()=>Ug(e),[e]),o=Bg([]);kg(()=>(Oc(o.current),o.current=_g(e,r),()=>{Oc(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=j(),c=Math.max(1,n-4),l=Math.max(12,t-32);return r.length===0?De.createElement(_n,{flexDirection:"column",width:t,height:n,padding:1},De.createElement(Lt,{color:y.primary},"No attachments yet."),De.createElement(_n,{paddingTop:1},De.createElement(Lt,{color:y.primary},"Attach images from the browser GUI"),De.createElement(Lt,{color:y.accent}," epiq gui "),De.createElement(Lt,{color:y.primary},"by dropping or pasting them."))):De.createElement(_n,{flexDirection:"column",width:t,height:n},De.createElement(_n,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},De.createElement(Lt,{color:y.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),De.createElement(tt,{height:c,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,g=m.name.length>l?m.name.slice(0,l-1)+"\u2026":m.name;return De.createElement(_n,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},De.createElement(Lt,{color:y.accent},f?"\u276F ":" "),De.createElement(_n,{paddingLeft:1},De.createElement(Lt,{color:y.secondary2},`#${p+1} `),De.createElement(Lt,{color:f?y.accent:y.primary},g),De.createElement(Lt,{color:y.secondary2}," "+$g(m.bytes)+" "+Pn(bi(m.id)))))})))}import{Box as Zt,Text as kt}from"ink";import ye,{useEffect as Hg,useMemo as Wg,useRef as jg}from"react";import{decodeTime as Ii}from"ulid";var Gg=e=>Ie(e,"comments"),Vg=e=>S.getCommentsByIssue(e.id).sort((t,n)=>Ii(t.id)-Ii(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),$c=e=>{for(let t of e)S.deleteNode(t.id)},Kg=(e,t)=>{let n=S.getNode(Gg(e.id));if(!n||!Ve(n))return[];let r=t.map((o,s)=>Uc(o,s,n.id)).map(S.createNode).filter(Q).map(({value:o})=>o).filter(ir);return t.length>0&&v().selectedIndex<0&&M.navigate({contextNode:n,selectedIndex:0}),r},zg=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`};function Hc({ticket:e,width:t,height:n}){let r=Wg(()=>Vg(e),[e]),o=jg([]);Hg(()=>($c(o.current),o.current=Kg(e,r),()=>{$c(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=j(),c=Math.max(1,n-4),l=Math.max(20,t-8);return r.length===0?ye.createElement(Zt,{flexDirection:"column",width:t,height:n,padding:1},ye.createElement(kt,{color:y.primary},"No comments yet."),ye.createElement(Zt,{paddingTop:1},ye.createElement(kt,{color:y.primary},"Use"),ye.createElement(kt,{color:y.accent}," :comment "),ye.createElement(kt,{color:y.primary},"to add the first one."))):ye.createElement(Zt,{flexDirection:"column",width:t,height:n},ye.createElement(Zt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},ye.createElement(kt,{color:y.secondary2},"Comments (",r.length,") ")),ye.createElement(tt,{height:c,itemHeight:4,selectedIndex:s},r.map((m,p)=>{let f=p===s;return ye.createElement(Zt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},ye.createElement(Zt,{flexDirection:"row",paddingBottom:1},ye.createElement(kt,{color:y.accent},f?"\u276F ":" "),ye.createElement(Zt,{paddingLeft:1},ye.createElement(kt,{color:y.secondary2},`#${p+1} `),ye.createElement(Qt,{id:m.authorId}),ye.createElement(kt,{color:y.secondary2}," "+Pn(Ii(m.id))))),ye.createElement(Zt,{paddingLeft:3,paddingBottom:1},ye.createElement(kt,{color:y.primary},zg(m.md,l))))})))}import{Box as Oo,Text as qg}from"ink";import Dt from"react";var Wc=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=j(),{title:o}=t,s=t.parentNodeId?S.getNode(t.parentNodeId):void 0,i=s&&T(s)?o===Z.ASSIGNEES?s.props.assignees??[]:o===Z.TAGS?s.props.tags??[]:[]:[];return Dt.createElement(Oo,{alignItems:"center",paddingTop:1},Dt.createElement(Oo,{minWidth:12},Dt.createElement(ke,{isSelected:n}),Dt.createElement(qg,{color:n?y.accent:y.secondary2},o,":")),Dt.createElement(Oo,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,l)=>{let m=r.id===t.id&&l===e;return Dt.createElement(Oo,{key:`${o}-${c}`,paddingRight:2,minHeight:1},Dt.createElement(ke,{isSelected:m}),o===Z.ASSIGNEES?Dt.createElement(Qt,{isSelected:m,id:c}):o===Z.TAGS?Dt.createElement(Un,{isSelected:m,id:c}):null)})))};import{Box as _o,Text as Ei}from"ink";import Bt,{useEffect as Yg,useMemo as jc}from"react";var Xg="\u2029",Gc=(e,t)=>`${e}::inline-line::${t}`,Si=new Map,Vc=e=>{let t=Si.get(e)??[];Si.delete(e);for(let n of t)S.deleteNode(n)},Jg=(e,t)=>{Vc(e);let n=[];t.forEach((r,o)=>{let s=Ke(BigInt(o+1));if(!Q(s))return;let i=S.createNode(ee.text({id:Gc(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));Q(i)&&n.push(i.value.id)}),Si.set(e,n)},Ci=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=j(),l=jc(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=jc(()=>l.join("\0"),[l]);Yg(()=>(Jg(e,l),()=>{Vc(e)}),[e,m]);let p=g=>String(g).replace(/\r?\n/g,""),f=l.map((g,E)=>{let I=c.id===e&&i===E;return Bt.createElement(_o,{key:Gc(e,E)},Bt.createElement(Ei,{color:I?y.primary:y.secondary2,dimColor:!I},`${E+1} `.padStart(5,"\xA0")),Bt.createElement(Ei,{backgroundColor:I?"gray":void 0},p(g.length?ot(g,s-10):Xg)))});return Bt.createElement(_o,{flexDirection:"column",paddingTop:1},Bt.createElement(_o,null,Bt.createElement(ke,{isSelected:o}),Bt.createElement(Ei,{color:o?y.accent:y.secondary2},t)),Bt.createElement(_o,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1},Bt.createElement(tt,{scrollByOne:!0,height:r-3,selectedIndex:i,itemHeight:1},f)))};var Qg=e=>Ie(e,"description"),Zg=e=>Ie(e,"comments"),ev=e=>Ie(e,"history"),tv=e=>Ie(e,"attachments"),Kc=({ticket:e,height:t})=>{let n=Er(()=>Fc(e),[e]),{selectedIndex:r,contextNode:o}=j(),s=process.stdout.columns||120,i=Er(()=>Qg(e.id),[e.id]),c=Er(()=>Zg(e.id),[e.id]),l=Er(()=>ev(e.id),[e.id]),m=Er(()=>tv(e.id),[e.id]),p=S.getAttachmentsByIssue(e.id).length,f=o.id===e.id,g=o.id===c||o.parentNodeId===c,E=o.id===l||o.parentNodeId===l,I=o.id===m||o.parentNodeId===m,N=z(e.id);if(g){let $=t-3;return Ce.createElement(In,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ce.createElement(Hc,{ticket:e,width:s,height:$}))}if(I){let $=t-3;return Ce.createElement(In,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ce.createElement(_c,{ticket:e,width:s,height:$}))}if(E){let B=S.getNode(l),$=B&&Ve(B)?B.props.value??"":"",we=t-3;return Ce.createElement(In,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},B?Ce.createElement(Ci,{id:B.id,label:"Event log",text:$,selected:!1,maxWidth:s,height:we}):null)}let A=N.reduce((B,$)=>sr($)||$.id===c||$.id===m||$.id===l?B+1:B,0),P=2,F=3,H=A,W=t-F-H-P,w=(B,$)=>B.id===i?Ce.createElement(Ci,{key:B.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:$,maxWidth:s,height:W}):sr(B)?Ce.createElement(Wc,{key:B.id,parent:B,selected:$,selectedIndex:r}):B.id===c?Ce.createElement(In,{key:B.id,paddingTop:1},Ce.createElement(ke,{isSelected:$}),Ce.createElement(Ni,{backgroundColor:y.secondary,color:$?y.accent:y.primary},` Comments (${n}) \u203A\u203A `)):B.id===m?Ce.createElement(In,{key:B.id,paddingTop:1},Ce.createElement(ke,{isSelected:$}),Ce.createElement(Ni,{backgroundColor:y.secondary,color:$?y.accent:y.primary},` Attachments (${p}) \u203A\u203A `)):B.id===l?Ce.createElement(In,{key:B.id,paddingTop:1},Ce.createElement(ke,{isSelected:$}),Ce.createElement(Ni,{backgroundColor:y.secondary,color:$?y.accent:y.primary}," History \u203A\u203A ")):null;return Ce.createElement(In,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},N.map((B,$)=>w(B,f&&r===$)))};var rv=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let l=t.context,m=l===D.TICKET||l===D.FIELD_LIST||l===D.FIELD,p=l===D.BOARD||l===D.SWIMLANE,f=l===D.TICKET?t:r.find(A=>A.context===D.TICKET),g=Math.floor(c/3),E=Math.floor(c/Math.max(e.length,1)),I=Math.min(E,g),N=s==="dense";return $o.createElement(nv,{flexDirection:"row",height:i},p&&e.map((A,P)=>{let F=t.id===A.id,H=F?n:-1,W=t.context===D.BOARD&&n===P;return $o.createElement(Bc,{key:A.id,height:i,width:I,swimlane:A,isSelected:W,isDense:N,isFocused:F,listSelectedIndex:H,mode:o})}),m&&f&&$o.createElement(Kc,{height:i,ticket:f}))},Ho=$o.memo(rv);import{render as iv}from"ink";import{Writable as av}from"node:stream";var Sr=e=>String(e).padStart(2,"0"),dv=e=>{let t=e.getUTCFullYear(),n=Sr(e.getUTCMonth()+1),r=Sr(e.getUTCDate()),o=Sr(e.getUTCHours()),s=Sr(e.getUTCMinutes()),i=Sr(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},cv=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",lv=async(e,{width:t,height:n})=>{let r="",o=new av({write(i,c,l){let m=uv(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),l()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=iv(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},uv=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),qc=async()=>{let{viewMode:e}=K(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=v(),i=r.find(P=>P.context==="BOARD");if(!i)return a("No board found to export");let c=120,l=40,m=await lv(sv.createElement(Ho,{height:l,width:c,swimlanes:(s[i.id]??[]).filter(P=>P!==void 0&&jt(P)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:l});if(!m)return a("Failed to render board export");let p=Wr(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let f=new Date,g=dv(f),E=`board_${cv(i.title)}_${g}.md`,I=Ma(p.value);zc.mkdirSync(I,{recursive:!0});let N=ov.join(I,E),A=`# Board - ${i.title}
47
47
  Date: ${f.toISOString()}
48
48
 
49
49
  \`\`\`text
50
50
  ${m}
51
51
  \`\`\`
52
- `;return Kc.writeFileSync(R,A,"utf8"),u("Exported board layout",R)};var Ho=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 $T}from"react";var jo,dv=new Set,qc=()=>{for(let e of dv)e()};var Zt=()=>{if(!jo)throw new Error("Ui state not initialized. Call initUiState() first.");return jo};var Yc=(e={})=>(jo=e,qc(),u("UX state initialized",null)),cv=e=>{let t=Zt();return jo=e(t),qc(),u("UX state updated",null)},en=e=>cv(t=>({...t,...e}));import{spawn as lv}from"node:child_process";function Sr(e){let t=process.platform,o=lv(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 Ti}from"ulid";import{spawn as uv,spawnSync as mv}from"node:child_process";import pv from"node:os";import Xc from"node:path";import{ulid as fv}from"ulid";function Ni(e){let t=[],n="",r=!1,o=null;for(let s of e.trim()){if(o){s===o?o=null:n+=s;continue}if(s==='"'||s==="'"){o=s,r=!0;continue}if(/\s/.test(s)){r&&t.push(n),n="",r=!1;continue}n+=s,r=!0}return r&&t.push(n),t}function gv(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Wo(){let{preferredEditor:e}=K(),t=[e?gv(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Ri(e){let[t=""]=Ni(e);return/(^|\/)code(-insiders)?$/.test(t)}function Jc(e,t){let[n="",...r]=Ni(e);return{command:n,args:[...r,...t]}}function Qc(e,t){return Jc(e,Ri(e)?["--wait",t]:[t])}function vv(e,t,n,r="new"){return Jc(e,[r==="new"?"--new-window":"--reuse-window","--diff",t,n])}function Zc(e){let t=Xc.join(pv.tmpdir(),"epiq");be.mkDir(t);let n=Xc.join(t,fv());be.writeToFile(n,e??"");let r=Wo();for(let o of r){let{command:s,args:i}=Qc(o,n);if(!s)continue;let c=mv(s,i,{stdio:"inherit"});if(!c.error&&c.status===0){let l=be.readFile(n);if(l==null)return a("Unable to read edited file");let m=l.replace(/\r?\n$/,"");return u("Successfully edited",m)}}return a("Unable to open editor")}var yv=new Set(["vim","vi","nvim","nano","pico","ed"]);function hv(e){let[t=""]=Ni(e),n=t.split("/").pop()??t;return yv.has(n)}var xv=600;function el({command:e,args:t},n){return new Promise(r=>{if(!e){r(a(`"${n}" is not a usable editor command`));return}let o=uv(e,t,{stdio:"ignore",detached:!0}),s=!1,i=l=>{s||(s=!0,clearTimeout(c),r(l))};o.on("error",l=>i(a(l.message))),o.on("exit",l=>{i(l===0?u("Opened editor",!0):a(`"${n}" exited with code ${l}`))});let c=setTimeout(()=>{o.unref(),i(u("Opened editor",!0))},xv)})}function bv(e,t){return hv(e)?Promise.resolve(a(`"${e}" is a terminal editor and can't open from the GUI (no terminal attached). Set preferredEditor to a GUI editor (e.g. "code"), or open the file yourself: ${t}`)):el(Qc(e,t),e)}function Ai(e,t,n,r="new"){return el(vv(e,t,n,r),e)}async function tl(e){let t=Wo();if(t.length===0)return a("No editor configured (preferredEditor, VISUAL, or EDITOR)");let n=a("Unable to open editor");for(let r of t){let o=await bv(r,e);if(!d(o))return o;n=o,logger.error(`Failed to open editor "${r}" for ${e}: ${o.message}`)}return n}var nl=async e=>{let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(e.modifier===Ke.DESCRIPTION)return Ev();if(r&&ar(r))return Iv(e);if(e.modifier===Ke.TITLE){let o=ae();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 yt();return d(c)?c:U([{id:Ti(),action:"edit.title",payload:{id:s.id,name:i},...o.value}],c.value)}return a("Unknown edit command")},Iv=async e=>{let t=ae();if(d(t))return a("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=v(),o=z(n.id)[r];if(!o||!ar(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=v().nodes[s];if(!i||!T(i))return a("Unable to resolve comment issue");if(i.readonly)return a("Cannot edit readonly issue");let c=o.id.split(":").at(0)??"",l=S.getComment(c);if(!l||l.deleted)return a("Unable to resolve comment");if(l.issue!==i.id)return a("Comment does not belong to selected issue");if(l.authorId!==t.value.userId)return a("You can only edit your own comments"+l.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return a("Provide a comment");let p=await yt();if(d(p))return p;let f=p.value;return U([{id:Ti(),action:"edit.issue.comment",payload:{id:l.id,issue:i.id,md:m},...t.value}],f)},Ev=async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let t=await yt();if(d(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=v(),s=Oe([...r,o],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!T(i))return a("Edit target must be an issue");if(i.readonly)return a("Cannot edit readonly issue");let c=z(i.id).find(f=>f.title===Z.DESCRIPTION);if(!c)return a("No target found");if(c.readonly)return a("Cannot edit readonly field");let l=i.props.description??"";if(typeof l!="string")return a("Selected field is not editable text");let m=Zc(l);if(d(m))return a("Failed to edit field");let p=m.value;return p===l?u("No changes made",null):U([{id:Ti(),action:"edit.description",payload:{id:i.id,md:p},...e.value}],n)};import Cv from"node:fs";import ol from"node:path";import wi from"node:fs";import Sv from"node:path";var rl=async e=>{let t=Sv.join(e,".gitignore"),n=wi.existsSync(t)?wi.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
52
+ `;return zc.writeFileSync(N,A,"utf8"),u("Exported board layout",N)};var Wo=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 zT}from"react";var jo,mv=new Set,Yc=()=>{for(let e of mv)e()};var en=()=>{if(!jo)throw new Error("Ui state not initialized. Call initUiState() first.");return jo};var Xc=(e={})=>(jo=e,Yc(),u("UX state initialized",null)),pv=e=>{let t=en();return jo=e(t),Yc(),u("UX state updated",null)},tn=e=>pv(t=>({...t,...e}));import{spawn as fv}from"node:child_process";function Cr(e){let t=process.platform,o=fv(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 wi}from"ulid";import{spawn as gv,spawnSync as vv}from"node:child_process";import hv from"node:os";import Jc from"node:path";import{ulid as yv}from"ulid";function Ri(e){let t=[],n="",r=!1,o=null;for(let s of e.trim()){if(o){s===o?o=null:n+=s;continue}if(s==='"'||s==="'"){o=s,r=!0;continue}if(/\s/.test(s)){r&&t.push(n),n="",r=!1;continue}n+=s,r=!0}return r&&t.push(n),t}function xv(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Go(){let{preferredEditor:e}=K(),t=[e?xv(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Ai(e){let[t=""]=Ri(e);return/(^|\/)code(-insiders)?$/.test(t)}function Qc(e,t){let[n="",...r]=Ri(e);return{command:n,args:[...r,...t]}}function Zc(e,t){return Qc(e,Ai(e)?["--wait",t]:[t])}function bv(e,t,n,r="new"){return Qc(e,[r==="new"?"--new-window":"--reuse-window","--diff",t,n])}function el(e){let t=Jc.join(hv.tmpdir(),"epiq");be.mkDir(t);let n=Jc.join(t,yv());be.writeToFile(n,e??"");let r=Go();for(let o of r){let{command:s,args:i}=Zc(o,n);if(!s)continue;let c=vv(s,i,{stdio:"inherit"});if(!c.error&&c.status===0){let l=be.readFile(n);if(l==null)return a("Unable to read edited file");let m=l.replace(/\r?\n$/,"");return u("Successfully edited",m)}}return a("Unable to open editor")}var Iv=new Set(["vim","vi","nvim","nano","pico","ed"]);function Ev(e){let[t=""]=Ri(e),n=t.split("/").pop()??t;return Iv.has(n)}var Sv=600;function tl({command:e,args:t},n){return new Promise(r=>{if(!e){r(a(`"${n}" is not a usable editor command`));return}let o=gv(e,t,{stdio:"ignore",detached:!0}),s=!1,i=l=>{s||(s=!0,clearTimeout(c),r(l))};o.on("error",l=>i(a(l.message))),o.on("exit",l=>{i(l===0?u("Opened editor",!0):a(`"${n}" exited with code ${l}`))});let c=setTimeout(()=>{o.unref(),i(u("Opened editor",!0))},Sv)})}function Cv(e,t){return Ev(e)?Promise.resolve(a(`"${e}" is a terminal editor and can't open from the GUI (no terminal attached). Set preferredEditor to a GUI editor (e.g. "code"), or open the file yourself: ${t}`)):tl(Zc(e,t),e)}function Ti(e,t,n,r="new"){return tl(bv(e,t,n,r),e)}async function nl(e){let t=Go();if(t.length===0)return a("No editor configured (preferredEditor, VISUAL, or EDITOR)");let n=a("Unable to open editor");for(let r of t){let o=await Cv(r,e);if(!d(o))return o;n=o,logger.error(`Failed to open editor "${r}" for ${e}: ${o.message}`)}return n}var rl=async e=>{let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(e.modifier===ze.DESCRIPTION)return Rv();if(r&&ir(r))return Nv(e);if(e.modifier===ze.TITLE){let o=ae();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 yt();return d(c)?c:O([{id:wi(),action:"edit.title",payload:{id:s.id,name:i},...o.value}],c.value)}return a("Unknown edit command")},Nv=async e=>{let t=ae();if(d(t))return a("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=v(),o=z(n.id)[r];if(!o||!ir(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=v().nodes[s];if(!i||!T(i))return a("Unable to resolve comment issue");if(i.readonly)return a("Cannot edit readonly issue");let c=o.id.split(":").at(0)??"",l=S.getComment(c);if(!l||l.deleted)return a("Unable to resolve comment");if(l.issue!==i.id)return a("Comment does not belong to selected issue");if(l.authorId!==t.value.userId)return a("You can only edit your own comments"+l.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return a("Provide a comment");let p=await yt();if(d(p))return p;let f=p.value;return O([{id:wi(),action:"edit.issue.comment",payload:{id:l.id,issue:i.id,md:m},...t.value}],f)},Rv=async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let t=await yt();if(d(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=v(),s=_e([...r,o],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!T(i))return a("Edit target must be an issue");if(i.readonly)return a("Cannot edit readonly issue");let c=z(i.id).find(f=>f.title===Z.DESCRIPTION);if(!c)return a("No target found");if(c.readonly)return a("Cannot edit readonly field");let l=i.props.description??"";if(typeof l!="string")return a("Selected field is not editable text");let m=el(l);if(d(m))return a("Failed to edit field");let p=m.value;return p===l?u("No changes made",null):O([{id:wi(),action:"edit.description",payload:{id:i.id,md:p},...e.value}],n)};import Tv from"node:fs";import sl from"node:path";import Mi from"node:fs";import Av from"node:path";var ol=async e=>{let t=Av.join(e,".gitignore"),n=Mi.existsSync(t)?Mi.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
53
53
  `).map(l=>l.trim()),s=r.filter(l=>!o.some(m=>m===l||m===l.replace(/\/$/,"")||m==="/"+l||m==="/"+l.replace(/\/$/,"")));if(s.length===0)return u("Local epiq paths already ignored",!1);let c=["# [epiq]: local hydrated state is never committed",...s].join(`
54
54
  `);return n=n.trimEnd()+`
55
55
 
56
56
  ${c}
57
- `,wi.writeFileSync(t,n,"utf8"),le.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),u("Local epiq paths ignored",!0)};var Nv=async e=>{let t=await F({cwd:e,args:["status","--porcelain"]});return d(t)?t:u("Checked git diff",t.value.stdout.trim().length>0)},re=(e,t)=>a(`[${e}] ${t}`),sl=async()=>{V("");let e=Cn(),t=await gt(process.cwd());if(d(t))return re(1,t.message);let n=t.value,r=await Wr(n);if(d(r))return re(2,r.message);if(r.value)return re(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await Nv(n);if(d(o))return re(2.5,o.message);if(o.value)return re(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(_s(n))return re(4,"Epiq project already initialized");let s=Kt();if(!s.isSetupDone||!s.userName)return re(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let i=K(),c=i.userName,l=i.userId;if(!l||!c)return re(5,"Missing Epiq user id");let m=e.stateBranch,p=await Gr({repoRoot:n,branch:m});if(d(p))return re(6,p.message);if(p.value)return re(6,`State branch already exists: ${m}`);let f=await Gs({repoRoot:n,stateBranchName:m});if(d(f))return re(6,f.message);let g=qr();if(d(g))return re(7,g.message);let E=ol.join(zr(),e.projectId),I=await un({repoRoot:n,stateBranchRoot:E,stateBranchName:m});if(d(I))return re(8,I.message);let R=ol.join(E,".epiq");Cv.mkdirSync(R,{recursive:!0});let A=Fd({userId:l,userName:c});if(d(A))return re(9,A.message);for(let As of A.value){let ca=go({event:As,rootDir:E});if(d(ca))return re(9,ca.message)}let P=await Zr({stateBranchRoot:E,eventFileName:pn({userId:l,userName:c})});if(d(P))return re(10,P.message);let _=await Rn({cwd:E,message:"[epiq:init]"});if(d(_))return re(10,_.message);let w=await rl(n);if(d(w))return re(11,w.message);let W=ua({repoRoot:n,fileContents:e});if(d(W))return re(12,W.message);let H=await ue.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d(H))return re(13,H.message);let D=await ue.commit({cwd:n,message:"[epiq:init-project]"});if(d(D))return re(13,D.message);let $="Project initialized!",Ye=await F({cwd:n,args:["push","-u","origin","HEAD"]});d(Ye)&&($+=` Warn: [init:14] ${Ye.message}`);let we=await sr({repoRoot:n,stateBranchRoot:E});d(we)&&($+=` Warn: [init:15] ${we.message}`);let ge=st(A.value).filter(d);if(ge.length>0)return re(16,ge.map(As=>As.message).join(`
58
- `));let me=We();if(d(me))return re(16,me.message);let{rootNodeId:Kn,nodes:zn}=me.value,da=zn[Kn];return da?(M.navigate({contextNode:da,selectedIndex:0}),C({hasProjectDefinition:!0,mode:y.DEFAULT}),u($,null)):re(16,"Unable to resolve initialized root node")};import{ulid as Av}from"ulid";import{ulid as Rv}from"ulid";var il=null,tn=()=>structuredClone(il),Cr=e=>{il=e},al=()=>{let{contextNode:e,selectedIndex:t}=v(),r=Y(e.id)[t];return r?u("Resolved selected child",r):a("Target node not found")},Mi=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Y(t).filter(o=>o.id!==e);return vo(r,n)},dl=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ae();if(d(r))return a("Unable to resolve user ID");let o=Mi({parentId:t,id:e,position:n});return d(o)?o:u("Created pending move state",{id:Rv(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},cl=e=>{Cr(e);let t=Vt(e,!0);return d(t)?t:u("Node moved successfully",t.value)};function Pi(e){let t=al();if(d(t))return t;let{contextNode:n,nodes:r}=v();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=Y(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 l=dl({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(l)?l:cl(l.value)}function Li(e){let t=al();if(d(t))return t;let{contextNode:n,selectedIndex:r}=v(),s=Y(n.id)[r+e];if(!s)return a("Missing sibling node");let i=dl({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:cl(i.value)}var ll=()=>{let e=tn();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=v().nodes[n];if(!r)return a("Move parent not found");let o=Y(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(M.navigate({contextNode:r,selectedIndex:o}),u("Synchronized navigation to moved node",null))},Vo=(e,t="Moved preview")=>{if(d(e))return e;let n=ll();return d(n)?n:(C({mode:y.MOVE}),u(t,null))},ul=async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=X().commandMeta,{contextNode:n,selectedIndex:r}=v(),o=Y(n.id)[r];if(!o)return C({mode:y.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=Y(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],l=s[i+1],m=l!=null?{at:"before",sibling:l.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=Mi({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(Cr({id:Av(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),C({mode:y.MOVE}),u("Move initialized",null))}if(t==="next")return Vo(Li(1));if(t==="previous")return Vo(Li(-1));if(t==="to-next")return Vo(Pi(1));if(t==="to-previous")return Vo(Pi(-1));if(t==="confirm"){let s=tn();if(!s)return a("No pending move to confirm");let i=await yt();if(d(i))return i;let c=U([s],i.value);if(d(c))return c;let l=ll();return d(l)?l:(Cr(null),C({mode:y.DEFAULT}),u("Moved item",null))}return t==="cancel"?(Cr(null),C({mode:y.DEFAULT}),u("Cancelling move",null)):a("Invalid move modifier")};import{ulid as Ko}from"ulid";import{monotonicFactory as Tv,ulid as wv}from"ulid";var Mv=Tv(),Go=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=Mv();return u("Created issue events",[{id:wv(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var ml=async(e,t)=>{let n=ae();if(d(n))return a("Unable to resolve user ID");let r=await yt();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}=v(),l=m=>{let p=U([m],o);if(d(p))return p;let f=S.getNode(p.value[0].result.id);if(!f)return a("Created node not found");if(!f.parentNodeId)return p;let g=S.getNode(f.parentNodeId);return g?(M.navigate({contextNode:g,selectedIndex:S.getSiblings(f.parentNodeId).findIndex(({id:E})=>E===f.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=v(),p=S.getNode(m);if(!p)return a("Workspace not found");let f=Ln(p.id,n.value,o);return d(f)?f:l({id:Ko(),action:"add.board",payload:{id:Ko(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=Oe(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=Ln(m.value.id,n.value,o);return d(p)?p:l({id:Ko(),action:"add.swimlane",payload:{id:Ko(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=z(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let _=Oe(s,"SWIMLANE");return d(_)?null:_.value})();if(!p)return a("Unable to add issue in this context");let f=Ln(p.id,n.value,o);if(d(f))return f;let g=Go({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(d(g))return g;let E=g.value,I=U([...E],o);if(d(I))return I;if(!I.value[0])return a("Issue creation failed");let P=E.find(_=>_.action==="add.issue")?.payload.id;return P?(M.navigate({contextNode:p,selectedIndex:S.getSiblings(p.id).findIndex(({id:_})=>_===P)}),u("Issue created",null)):a("Unable to determine ticket id")}return u("Success",null)};var zo=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=v(),s=fo(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,l=it();if(d(l))return l;let p=st(i).filter(d);if(p.length>0)return it(),C(o),a(p.map(g=>g.message).join(", "));let f=v().nodes[e];return f?(M.navigate({contextNode:f,selectedIndex:r}),u("",{unappliedEvents:c})):(it(),C(o),a("Board did not exist at that date"))};var Pv=20,Lv=16,kv=150,qo=null,Yo=null;var En=()=>{qo!==null&&(clearInterval(qo),qo=null),Yo!==null&&(clearTimeout(Yo),Yo=null)},pl=()=>{En(),C({mode:y.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Dv=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)},fl=({events:e,startTime:t,durationMs:n})=>{En();let r=e.length,o=e.map(f=>Yt(f)??t),s=o[r-1]??Date.now(),i=Dv(o),c=Math.max(1,Math.round(n*Pv/1e3)),l=Math.max(Math.round(n/c),Lv),m=0,p=0;C({mode:y.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),qo=setInterval(()=>{m++;let f=m/c,g=[],E;for(;p<r&&i[p]<=f;){let R=e[p],A=Vt(R);if(d(A)){pl();return}g.push(...Qs(R)),E=R,p++}if(p>=r||m>=c){for(;p<r;p++){let A=Vt(e[p]);if(d(A))break}let R=v().replay;C({unappliedEvents:[],replay:R&&{...R,progress:1,appliedCount:r}}),En(),Yo=setTimeout(pl,kv);return}let I=v().replay;C({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:E?Yt(E)??I?.currentTime??t:I?.currentTime??t,currentLabel:E?fd(E):I?.currentLabel??"",flashNodeIds:E?[...new Set(g)]:I?.flashNodeIds??[]}})},l)};var gl=async()=>{let e=Oe(v().breadCrumb,"BOARD");if(d(e))return e;let t=await gt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Re({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=X().commandMeta;if(En(),r==="now"){let c=je(n.value);if(d(c))return a(c.message);let l=it();if(d(l))return l;let p=st(c.value).filter(d);return p.length>0?a(p.map(f=>f.message).join(", ")):(C({mode:y.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),u("Peeking now",!0))}let s;if(r==="prev"){let c=v().eventLog.at(-1),l=Yt(c);if(l===null)return a("No previous event to peek");s=l}else if(r==="next"){let c=v().unappliedEvents.at(0),l=Yt(c);if(l===null)return a("No next event to peek");s=l+1}else{let c=yn(r||o.trim());if(!c)return a("Invalid peek date");s=c.getTime()}let i=zo({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(C({mode:y.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),u("Peeking",!0))};var vl=async()=>{let e=Oe(v().breadCrumb,"BOARD");if(d(e))return e;let t=await gt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Re({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=X().commandMeta,{dateInput:s,durationInput:i}=No(r,o);if(En(),v().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let c=yn(s);if(!c)return a("Invalid replay date");let l=i?Co(i):15e3;if(l===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=v(),f=zo({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(d(f))return f;let{unappliedEvents:g}=f.value;return g.length===0?(it(),C(p),u("Nothing to replay from that point",!0)):(fl({events:g,startTime:m,durationMs:l}),u("Replaying board history",!0))};import Fv from"zod";var yl=()=>{let e=X().commandMeta.inputString,t=Fv.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=Qe({autoSyncDebounceMs:t.data});return d(n)?n:(Me({autoSyncIntervalMs:t.data}),C({mode:y.DEFAULT}),u(`Auto sync interval set to ${t.data}ms`,null))};var hl=()=>{let e=X().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Wd(e),n=Qe({autoSync:t});return d(n)?n:(Me({autoSync:t}),C({mode:y.DEFAULT}),u(`Auto sync set to "${e}"`,null))};var xl=()=>{let e=X().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=Qe({logLevel:e});return d(n)?n:(Me({logLevel:e}),C({mode:y.DEFAULT}),u(`Auto sync set to "${e}"`,null))};import{spawn as Uv}from"node:child_process";var Ov=()=>{switch(process.platform){case"darwin":return{command:"pbcopy",args:[]};case"win32":return{command:"clip",args:[]};default:return process.env.WAYLAND_DISPLAY?{command:"wl-copy",args:[]}:{command:"xclip",args:["-selection","clipboard"]}}},bl=async e=>new Promise(t=>{let{command:n,args:r}=Ov();try{let o=Uv(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(a(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?u("Copied to clipboard",null):a(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(a(`Clipboard tool not available (${n})`))}});var Nr=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await bl(e);return d(n)?n:u(`Copied ${t} to clipboard`,null)},Il=async e=>{let{breadCrumb:t,selectedNode:n}=v(),r=fr({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return a("Nothing selected to copy from");switch(e.modifier){case ye.REF:return Nr(He(o.id),"ref");case ye.TITLE:return Nr(o.title,"title");case ye.DESCRIPTION:return r?Nr(r.props?.description??"","description"):a("No issue in scope");case ye.TAGS:{if(!r)return a("No issue in scope");let s=zt(r).map(({name:i})=>i);return Nr(s.join(", "),"tags")}case ye.ASSIGNEES:{if(!r)return a("No issue in scope");let s=qt(r).map(({name:i})=>i);return Nr(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}};var El=async()=>{V(""),C({mode:y.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 xo();return d(t)?(C({syncStatus:{msg:t.message,status:"failed"}}),t):(C({mode:y.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var _v=e=>e.action==="add.issue.comment",Sl=e=>Object.values(v().tags).find(t=>t.name===e),Cl=()=>{let{eventLog:e=[],contributors:t}=v(),n=new Map,r=new Set;for(let o of e)o.userId&&(n.set(o.userId,o.userName??""),r.add(o.userId));for(let o of Object.values(t)){if(o.tombstoned){n.set(o.id,o.name);continue}n.set(o.id,Fn(o.name,n.get(o.id))??o.name)}return[...n.entries()].map(([o,s])=>({id:o,name:s,isExternal:!r.has(o)}))},Dt=async()=>{let e=await yt();return d(e)?e:u("Resolved persist root",e.value)},Xo=[{systemOnly:!0,intent:k.Move,description:"Internal move-state command",mode:y.COMMAND_LINE,action:ul},{intent:k.Delete,description:"Delete the currently selected node",mode:y.COMMAND_LINE,action:async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await Dt();if(d(o))return o;if(r.context==="COMMENT"){let s=r.id,i=T(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=v().nodes[i];if(!c||!T(c))return a("Unable to resolve comment issue");let l=c.log?.filter(_v).find(m=>m.payload.id===s);return l?l.payload.author!==e.value.userId?a("You can only delete your own comments"):U([{id:Be(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return U([{id:Be(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:y.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=X().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>de(b.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return pe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:y.DEFAULT})),u("Filter updated",null)}},{intent:k.ViewHelp,description:"Open the help screen",mode:y.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return en({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),C({mode:y.HELP}),u("Viewing help",null)}},{intent:k.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:y.COMMAND_LINE,action:async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!T(r))return a("Cannot close in this context");let o=v().nodes[ve];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await Dt();if(d(s))return s;let i=s.value,c=fn(o.id,r.id,{at:"end"},e.value,i);if(d(c))return c;let l=U([{id:Be(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value}],i);return d(l)?l:u("Issue closed",null)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:y.COMMAND_LINE,action:async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?u("Resolved ticket",r):At(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let s=o.value,i=v().nodes[ve];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!T(s))return a("Target node is not issue");let c=Ho(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 l=v().nodes[c];if(!l)return a("Previous parent no longer exists");let m=await Dt();if(d(m))return m;let p=m.value,f=fn(l.id,s.id,{at:"end"},e.value,p);if(d(f))return f;let g=U([{id:Be(),action:"reopen.issue",payload:{id:s.id,parent:l.id,rank:f.value},...e.value}],p);return d(g)?g:u("Issue reopened",null)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Init,description:"Initialize Epiq in the current git repository",mode:y.COMMAND_LINE,action:sl},{intent:k.NewItem,description:"Create a new board, swimlane, or issue",mode:y.COMMAND_LINE,action:ml,onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Rename,description:"Rename the currently selected node",mode:y.COMMAND_LINE,action:async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=Ec();if(!o)return a("Provide a title");let s=await Dt();return d(s)?s:U([{id:Be(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.UntagTicket,description:"Remove a tag from the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=X().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=Sl(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=v();if(!s)return a("Invalid untag target");let i=At(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let c=i.value;if(!T(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 Dt();return d(m)?m:U([{id:Be(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.TagTicket,description:"Add or create a tag on the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=X().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=v();if(!o)return a("Invalid tag target");let s=At(o.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!T(i))return a("Target node is not issue");let c=await Dt();if(d(c))return c;let l=Sl(r),m=l?.id??Be();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):U([...l?[]:[{id:Be(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:Be(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.AssignUserToTicket,description:"Assign a user to the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=X().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return a("Provide an assignee");let{selectedIndex:i,contextNode:c}=v(),l=z(c.id)[i];if(!l)return a("Invalid assign target");let m=At(l.id,"TICKET");if(d(m))return a("Unable to assign issue in this context");let p=m.value;if(!T(p))return a("Target node is not issue");let f=await Dt();if(d(f))return f;let g=Cl(),E=!o&&s.toLowerCase()==="me",I,R;if(E)I=e.value.userId,R=g.find(_=>_.id===I)?.name??e.value.userName;else{let _=g.filter(W=>W.name===s);if(_.length>1)return a(`"${s}" matches ${_.length} contributors (${_.map(W=>W.id).join(", ")}). Assign from the GUI to choose by id.`);let w=_[0];if(!w&&!o)return a(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);I=w?.id??Be(),R=w?.name??s}if((p.props.assignees??[]).includes(I))return a("Assignee already assigned");let P=!!v().contributors[I];return U([...P?[]:[{id:Be(),action:"create.contributor",payload:{id:I,name:R},...e.value}],{id:Be(),action:"add.issue.assignee",payload:{id:p.id,assignee:I},...e.value}],f.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:y.COMMAND_LINE,action:async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=X().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let{selectedNode:o}=v();if(!o)return a("Invalid unassign target");let s=At(o.id,"TICKET");if(d(s))return a("Unable to unassign in this context");let i=s.value;if(!T(i))return a("Target node is not issue");let c=i.props.assignees??[],l=r.toLowerCase()==="me",m=l?c.filter(g=>g===e.value.userId):Cl().filter(g=>g.name===r&&c.includes(g.id)).map(g=>g.id);if(m.length>1)return a(`"${r}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return a(l?"Issue is not assigned to you":`Issue is not assigned to "${r}"`);let f=await Dt();return d(f)?f:U([{id:Be(),action:"remove.issue.assignee",payload:{id:i.id,assignee:p},...e.value}],f.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Comment,description:"Add a comment to the selected issue",mode:y.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return a("Provide a comment");if(n.length>4e3)return a(`Cannot exceed ${4e3} characters`);let r=ae();if(d(r))return a("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=v(),i=Oe([...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 l=c.context==="TICKET"?u("Resolved ticket",c):At(c.id,"TICKET");if(d(l))return a("Unable to comment on issue in this context");let m=l.value;if(!T(m))return a("Target node is not issue");let p=await Dt();return d(p)?p:U([{id:Be(),action:"add.issue.comment",payload:{id:Be(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Sync,description:"Pull, commit, and push Epiq state",mode:y.COMMAND_LINE,action:El},{intent:k.Peek,description:"View board state at another point in time",mode:y.COMMAND_LINE,action:gl},{intent:k.Replay,description:"Replay board history forward from a point in time",mode:y.COMMAND_LINE,action:vl},{intent:k.Export,description:"Export the current board layout to markdown",mode:y.COMMAND_LINE,action:async()=>{let e=await zc();return d(e)?e:(C({mode:y.DEFAULT}),u("Export successful",!0))}},{intent:k.Exit,description:"Exit the application",mode:y.COMMAND_LINE,action:async()=>(M.exit(),u("Exit successful",!0))},{intent:k.Edit,description:"Edit title or description",mode:y.COMMAND_LINE,action:async(e,t)=>nl(t),onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:y.COMMAND_LINE,action:async(e,t)=>Il(t),onSuccess:()=>C({mode:y.DEFAULT})},{intent:k.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:y.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case oe.USERNAME:{let{userId:r,preferredEditor:o,userName:s}=K(),i=n||s,c=r??Be();if(!i||!c)return a("Unable to resolve user name or id");let l=Qe({userName:i,userId:c,preferredEditor:o??""});return d(l)?l:(Me({userName:i,userId:c}),C({mode:y.DEFAULT}),u(`Username set to "${i}"`,null))}case oe.EDITOR:{if(!n)return a("No editor provided");let r=Qe({preferredEditor:n});return d(r)?r:(Me({preferredEditor:n}),C({mode:y.DEFAULT}),u(`Editor configuration set to "${n}"`,null))}case oe.VIEW:{if(n!=="wide"&&n!=="dense")return a("Invalid view mode");let r=Qe({viewMode:n});return d(r)?r:(Me({viewMode:n}),C({mode:y.DEFAULT}),u(`View set to "${n}"`,null))}case oe.AUTOSYNC:return hl();case oe.LOG_LEVEL:return xl();case oe.SYNC_DEBOUNCE_MS:return yl();case oe.ATTACHMENT_MAX_KB:return nc();default:return a("Unknown config command")}}},{intent:k.Coffee,description:"Sponsor the development of Epiq!",mode:y.COMMAND_LINE,action:()=>{let e=X().commandMeta.modifier;return e==="custom"?Sr("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):Sr(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),V(""),u("Thanks you!",null)}}];var $v=new Set(["peek","replay","filter","view-help","yank"]),St=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=X();if(!t)return a("No command to confirm");if(!e&&n===bt.Invalid)return a("Invalid command");let s=Lo(t);yc();let{readOnly:i}=v();if(i&&!$v.has(s))return hr({status:Ut.Fail,message:"Command not available in readonly state",value:null});let c=Xo.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return hr({status:Ut.Fail,message:"Command not found",value:null});let l;try{l=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return hr({status:Ut.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(l)?hr(l):(hc({addToHistory:!e}),c.onSuccess?.(),K().autoSync&&Io(),l)};var Jo=[{intent:x.Exit,mode:y.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(C({mode:y.COMMAND_LINE}),V("move cancel"),St({isForceExecutedBySystem:!0}))},{intent:x.InitMove,mode:y.DEFAULT,description:"[m] move (init/confirm)",action:()=>(C({mode:y.COMMAND_LINE}),V("move start"),St({isForceExecutedBySystem:!0}))},{intent:x.ConfirmMove,mode:y.MOVE,action:()=>(C({mode:y.COMMAND_LINE}),V("move confirm"),St({isForceExecutedBySystem:!0}))}],Qo=[{intent:x.MovePreviousItem,mode:y.MOVE,action:()=>tn()?(C({mode:y.COMMAND_LINE}),V("move previous"),St({isForceExecutedBySystem:!0})):a("No pending move")},{intent:x.MoveNextItem,mode:y.MOVE,action:()=>tn()?(C({mode:y.COMMAND_LINE}),V("move next"),St({isForceExecutedBySystem:!0})):a("No pending move")}],Nl=[{intent:x.MoveToNextContainer,mode:y.MOVE,action:()=>tn()?(C({mode:y.COMMAND_LINE}),V("move to-next"),St({isForceExecutedBySystem:!0})):a("No pending move")},{intent:x.MoveToPreviousContainer,mode:y.MOVE,action:()=>tn()?(C({mode:y.COMMAND_LINE}),V("move to-previous"),St({isForceExecutedBySystem:!0})):a("No pending move")}];var Rl={[B.WORKSPACE]:[...Jo,...Qo],[B.BOARD]:[...Jo,...Qo],[B.SWIMLANE]:[...Jo,...Qo,...Nl],[B.TICKET]:[],[B.FIELD]:[],[B.FIELD_LIST]:[],[B.TEXT]:[],[B.COMMENT]:[]};import Hv from"node:fs";import jv from"node:path";var Al=e=>{let t=$e(process.cwd());if(d(t))return a("Unable to resolve project root");let n=Re({repoRoot:t.value});if(d(n))return a(n.message);let r=Dn(e.hash,e.ext),o=jv.join(rr(n.value),r);return Hv.existsSync(o)?(Sr(o),u(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")};var Tl=()=>{V("");let{pendingNavTarget:e}=Zt();C({mode:y.DEFAULT}),e&&M.navigate(e),en({pendingNavTarget:void 0})},wl=[{intent:x.ExitCommandLine,mode:y.HELP,action:()=>(Tl(),u("Exiting help",null))},{intent:x.Exit,mode:y.HELP,action:()=>(Tl(),u("Closed help",null))},{intent:x.NavPreviousItem,mode:y.HELP,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),u("Navigating to previous help item",null))},{intent:x.NavNextItem,mode:y.HELP,action:()=>(M.navigateToNextItem(),u("Navigating to next help item",null))},{intent:x.NavToPreviousContainer,mode:y.HELP,action:()=>(M.navigateToPreviousContainer(),u("Navigating to previous help container",null))},{intent:x.NavToNextContainer,mode:y.HELP,action:()=>(M.navigateToNextContainer(),u("Navigating to next help container",null))}];var Wv=e=>{C({mode:y.COMMAND_LINE});let{pendingNavTarget:t}=Zt();t&&M.navigate(t),en({pendingNavTarget:void 0}),V(`${e} `)},Ml=()=>{V("");let{pendingNavTarget:e}=Zt();e&&M.navigate(e),en({pendingNavTarget:void 0}),C({mode:y.DEFAULT})},Pl=[{intent:x.InitCommandPalette,mode:y.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{V("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return en({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),C({mode:y.PALETTE}),u("Opening command palette",null)}},{intent:x.Confirm,mode:y.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!$t(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?(Wv(t),u("Selected command",t)):u("No command selected",null)}},{intent:x.ExitCommandLine,mode:y.PALETTE,action:()=>(Ml(),u("Exiting palette",null))},{intent:x.Exit,mode:y.PALETTE,action:()=>(Ml(),u("Closed command palette",null))},{intent:x.NavPreviousItem,mode:y.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:x.NavNextItem,mode:y.PALETTE,action:()=>(M.navigateToNextItem(),u("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:y.PALETTE,action:()=>(M.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:y.PALETTE,action:()=>(M.navigateToNextContainer(),u("Navigating to next container",null))}];var Ll=[...wl,...Pl,{intent:x.AddItem,mode:y.DEFAULT,description:"[n] new...",action:()=>(C({mode:y.COMMAND_LINE}),V(`${b.NEW} `),u("Adding new item",null))},{intent:x.Delete,mode:y.DEFAULT,description:"[d] delete",action:()=>(C({mode:y.COMMAND_LINE}),V(`${b.DELETE} `),u("Deleting item",null))},{intent:x.InitCommandLine,mode:y.DEFAULT,description:"[:] focus command line",action:()=>(C({mode:y.COMMAND_LINE}),V(""),u("Entering command line mode",null))},{intent:x.Confirm,mode:y.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!Y(e?.id??"")?.length){let r=e?S.getAttachment(e.id):void 0;if(r)return Al(r);if(e?.title===Z.DESCRIPTION)return C({mode:y.COMMAND_LINE}),V(`${b.EDIT} description `),u("Propose command",!0);if(e?.title===Z.ASSIGNEES)return C({mode:y.COMMAND_LINE}),V(`${b.ASSIGN} `),u("Propose command",!0);if(e?.title===Z.TAGS)return C({mode:y.COMMAND_LINE}),V(`${b.TAG} `),u("Propose command",!0);if(t.title===Z.DESCRIPTION&&e?.context==="TEXT")return C({mode:y.COMMAND_LINE}),V(`${b.EDIT} description `),u("Propose command",!0)}return M.enterChildNode(),u("Entering context",null)}},{intent:x.Yank,mode:y.DEFAULT,description:"[y] yank to clipboard",action:()=>{let{selectedNode:e}=v(),t=e?.title===Z.DESCRIPTION?ye.DESCRIPTION:e?.title===Z.TAGS?ye.TAGS:e?.title===Z.ASSIGNEES?ye.ASSIGNEES:ye.REF,r=de(b.YANK).includes(t)?t:ye.REF;return C({mode:y.COMMAND_LINE}),V(`${b.YANK} ${r}`),u("Propose command",!0)}},{intent:x.EditTitle,mode:y.DEFAULT,description:"[r] rename title",action:()=>(C({mode:y.COMMAND_LINE}),V(`${b.EDIT} title ${v().selectedNode?.title}`),u("Exiting context",null))},{intent:x.EditDescription,mode:y.DEFAULT,description:"[e] edit description",action:()=>(C({mode:y.COMMAND_LINE}),V(`${b.EDIT} description `),u("Exiting context",null))},{intent:x.Exit,mode:y.DEFAULT,description:"[q] exit context",action:()=>(M.enterParentNode(),u("Exiting context",null))},{intent:x.NavPreviousItem,mode:y.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:x.NavNextItem,mode:y.DEFAULT,action:()=>(M.navigateToNextItem(),u("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:y.DEFAULT,action:()=>(M.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:y.DEFAULT,action:()=>(M.navigateToNextContainer(),u("Navigating to next container",null))}];var Vv=500,Gv=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),kl=e=>{let t=Gv(e);t&&Po(n=>(n+t).slice(0,Vv))};var Kv=[y.COMMAND_LINE,y.PALETTE],zv=e=>[{intent:x.MoveCursorLeft,mode:e,action:()=>(gi(-1),u("Moving cursor left",null))},{intent:x.MoveCursorRight,mode:e,action:()=>(gi(1),u("Moving cursor right",null))},{intent:x.MoveCursorLeftOfWord,mode:e,action:()=>(vi("left"),u("Moving cursor left of word",null))},{intent:x.MoveCursorRightOfWord,mode:e,action:()=>(vi("right"),u("Moving cursor right of word",null))},{intent:x.AutoCompleteCommand,mode:e,action:()=>(Po((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=v().selectedNode?.title??""),r+o}),u("Auto-completing command",null))},{intent:x.CaptureInput,mode:e,action:(t,{sequence:n})=>(kl(n??""),u("Capturing input",null))},{intent:x.EraseInput,mode:e,action:()=>(gc(),u("Erasing input",null))},{intent:x.EraseInputWord,mode:e,action:()=>(vc(),u("Erasing input word",null))}],Dl=[{intent:x.Confirm,mode:y.COMMAND_LINE,action:()=>(St(),u("Executing command",null))},{intent:x.ViewHelp,mode:y.DEFAULT,action:()=>(C({mode:y.HELP}),u("Viewing help",null))},...Kv.flatMap(zv),{intent:x.ExitCommandLine,mode:y.COMMAND_LINE,action:()=>(C({mode:y.DEFAULT}),u("Exiting command line",null))},{intent:x.GetLastCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(xc(),u("Getting last command from history",null))},{intent:x.GetNextCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(bc(),u("Getting next command from history",null))}];import Ul from"chalk";var Zo=Ul.dim.hex(h.secondary2)(": for command line"),Bl="q to exit",Fl=`${Ul.hex(h.accent)("m")} to confirm`,ki={[B.WORKSPACE]:[Zo],[B.BOARD]:[Zo],[B.BOARD+y.COMMAND_LINE]:[Zo],[B.SWIMLANE]:[Zo],[B.TICKET+y.HELP]:[Bl],[B.SWIMLANE+y.HELP]:[Bl],[B.TICKET]:[],[B.FIELD]:[],[B.SWIMLANE+y.MOVE]:[Fl],[B.TICKET+y.MOVE]:[Fl]};var Rr=e=>e.trim().toLocaleLowerCase(),qv=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Yv=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?Xt(n,r.name):void 0}).filter(n=>!!n)},Ol=(e,t)=>{let n=Rr(t.value);if(!n)return!0;switch(t.target){case"title":return Rr(e.title??"").includes(n);case"description":return Rr(e.props.description??"").includes(n);case"tag":return qv(e).map(Rr).some(o=>o.includes(n));case"assignee":return Yv(e).map(Rr).some(o=>o.includes(n));case"ref":return sd(e.id,t.value);default:return!0}};function _l(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(),u("Breadcrumb built",o))}var $l=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var Bt,Di,Bi=new Set,Fi=()=>{for(let e of Bi)e()},Jv=e=>(Bi.add(e),()=>Bi.delete(e));function Ui(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 l=_l(t,o,r);if(d(l))return logger.error(l.message),l;let m=l.value,{context:p}=c,f=ki[p+n]??ki[p]??[],g=[...Ll,...Rl[p]??[],...Dl],E=$l(g),I=Qv(o,s),R=I[t]?.[e.selectedIndex]??null;return u("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:f,availableActions:g,actionIndex:E,selectedNode:R,renderedChildrenIndex:I})}var v=()=>{if(!Bt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Bt},We=()=>Bt?u("Retrieved state",Bt):a("State not initialized. Call initWorkspaceState() first.");function cr(e){Di=e;let t=$e(process.cwd()),n=!1;if(!d(t)){let s=ut(t.value);if(d(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:y.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:{},attachments:{}},o=Ui(r);return d(o)?o:(Bt=o.value,Fi(),u("State initialized",null))}var Ar=!1,es=null;function pe(e){let t=v(),n=e(t);if(Ar)return es=n,Bt={...t,...n},u("State updated",null);let r=Ui(n);return d(r)?a(r.message??"Unable to update state"):(Bt=r.value,Fi(),u("State updated",null))}function xd(e){if(Ar)return u("Joined batch",e());Ar=!0,es=null;let t=()=>{let n=es;if(Ar=!1,es=null,n===null)return null;let r=Ui(n);return d(r)?a(r.message??"Unable to update state"):(Bt=r.value,Fi(),u("State updated",null))};try{let n=e(),r=t();return r&&d(r)?a(r.message):u("State updated",n)}finally{Ar&&t()}}var C=e=>pe(t=>({...t,...e}));var j=()=>Xv(Jv,v,v),Qv=(e,t)=>{let n={};for(let r of Object.values(e))T(r)&&t.length>0&&!t.every(o=>Ol(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},z=e=>v()?.renderedChildrenIndex[e]??[],it=()=>Di?cr(Di):a("Cannot reset state: no initial workspace found"),Gt=()=>Bt!==void 0;var Oi=e=>{Gt()&&(C({syncStatus:e}),_t({type:"sync-status",payload:e}))},ts=(e="Syncing...")=>{Oi({status:"syncing",msg:e})},ns=(e="Synced")=>{Oi({status:"synced",msg:e})},_i=e=>{Oi({status:"failed",msg:e})},et=e=>(_i(e),a(e));import{decodeTime as HD}from"ulid";var Zv=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=J("getRepoRootDir",await gt(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=J("getStateBranchRoot",Re({repoRoot:r}));if(d(o))return a(o.message);let s=o.value;logger.debug("[sync] state branch root",s);let i=J("ensureInitialCommit",await $a(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=J("bootstrapStateBranchStorage",await Wa({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 l=J("hasInProgressGitOperation(stateBranchRoot)",await Wr(s));if(d(l))return a(l.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:l.value}),l.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=J("ensureStateBranchLayout",Aa(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}),u("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}))},ey=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=J("stageStateBranchOwnEventFile",await Zr({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=J("stageStateBranchMediaFiles",await Ha({stateBranchRoot:t}));if(d(o))return a(o.message);let s=J("hasStagedChanges(after stage)",await ba(t));if(d(s))return a(s.message);if(logger.debug("[sync] state branch change check after stage result",{changed:s.value}),!s.value)return logger.info("[sync] no own event file changes to commit"),u("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let i=J("createStateBranchSyncCommit",await ja({repoRoot:e,stateBranchRoot:t}));return d(i)?a(i.message):(logger.debug("[sync] created sync commit",i.value),u("Committed own event file",{createdCommit:!0,commitSha:i.value}))},bo=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");ts();let n=J("ensureSyncReady",await Zv({cwd:e,ensureUpstream:!0}));if(d(n))return et(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=J("isDetachedHead(stateBranchRoot)",await Ia(o));if(d(i))return et(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return et("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,l,m=!1,p=!1,f=J("getStateBranch",Nn(r));if(d(f))return et(f.message);let g=f.value;logger.debug("[sync] resolved state branch",{stateBranch:g,stateBranchRoot:o});let E=J("commitOwnEventFileToStateBranch",await ey({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(E))return et(E.message);c=E.value.createdCommit,l=E.value.commitSha;let I=J("pullBranchRebaseIfPresent",await Bs({cwd:o,branch:g}));if(d(I))return et(I.message);if(m=I.value,c||s){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:o});let R=J("pushStateBranch",await sr({stateBranchRoot:o,repoRoot:r}));if(d(R)&&xa(R.message)){let A=J("pullBranchRebaseIfPresent(retry)",await Bs({cwd:o,branch:g}));if(d(A))return et(A.message);m=m||A.value,R=J("pushStateBranch(retry)",await sr({stateBranchRoot:o,repoRoot:r}))}if(d(R))return et(R.message);p=R.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let R=J("git rev-parse HEAD",await F({args:["rev-parse","HEAD"],cwd:o}));if(d(R))return et(R.message);l=R.value.stdout.trim(),logger.debug("[sync] final sync commit sha",l)}return ns(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),u("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:l,pulled:m,pushed:p,bootstrapped:s})};import{existsSync as $i}from"node:fs";import{chmod as Hi}from"node:fs/promises";import zl from"node:os";import Hn from"node:path";var Hl=(e,t)=>e.reduce((n,r)=>r<n?r:n,t);var jl=1e5,ty=2e4,rs=null,Wl=Promise.resolve(),nn=e=>{let t=Wl.then(e,e);return Wl=t.then(()=>{},()=>{}),t},ji=e=>{let t=$e(e??process.cwd());return d(t)?a(t.message):u("Resolved Epiq repo root",t.value)},Wi=e=>{let t=ji(e);return d(t)?t:Re({repoRoot:t.value})},at=()=>{if(!Gt())return{mode:"live",asOfTime:null};let{timeMode:e}=v();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:rs}},ny=e=>{let t=new Map;for(let n of e){if(n.action!=="create.tag"&&n.action!=="create.contributor")continue;let r=n.payload;r?.id&&r.name&&t.set(r.id,r.name)}return t},ry=(e,t)=>{let n=e.payload,r=n?.tag!==void 0?t.get(n.tag)??"":n?.assignee!==void 0?t.get(n.assignee)??"":n?.name!==void 0?`"${n.name}"`:"";return[e.action?lo(e.action):"",r].filter(Boolean).join(" ")},Vl=(e,t)=>{if(!e)return null;let n=t.get(e)??e;return{id:e,name:n,color:te(n)}},oy=(e,t)=>{let n=e.payload;return{actor:e.userId?{id:e.userId,name:e.userName??e.userId,color:te(e.userName??e.userId)}:null,tag:Vl(n?.tag,t),assignee:Vl(n?.assignee,t)}},Vi=(e,t)=>{let n=new Map,r=new Set,o=i=>{let c=new Set,l=i;for(;l&&!c.has(l);){if(r.has(l))return l;c.add(l),l=n.get(l)}return null},s=[];for(let i of e){let c=i.payload,l=c?.id;if(!l)continue;i.action==="add.board"&&r.add(l);let m=c.parent??c.issue;m&&n.set(l,m),(l===t||o(l)===t)&&s.push(i)}return s},ql=async(e={})=>{let t=Wi(e.repoRoot);if(d(t))return a(t.message);let n=je(t.value);if(d(n))return a(n.message);let r=e.boardId?Vi(n.value,e.boardId):n.value,o=ny(n.value),s=r.flatMap(I=>{let R=Yt(I);return R===null?[]:[{t:R,action:I.action,label:ry(I,o),...oy(I,o)}]}),i=Date.now(),c=e.end??i,l=e.start??Hl(s.map(I=>I.t),c);if(c<=l)return u("Empty time window",{bucketMs:0,buckets:[],events:[],earliest:l,latest:c});let m=s.filter(I=>I.t>=l&&I.t<c).sort((I,R)=>I.t-R.t),p=m.map(I=>I.t),f=Math.max(1,Math.ceil((c-l)/jl)),g=new Map;for(let I of p){let R=Math.min(jl-1,Math.floor((I-l)/f)),A=l+R*f;g.set(A,(g.get(A)??0)+1)}let E=[...g.entries()].sort(([I],[R])=>I-R).map(([I,R])=>({t:I,count:R}));return u("Computed event timeline",{bucketMs:f,buckets:E,events:m.length>ty?[]:m,earliest:l,latest:c})},Tr="",Gl="",Yl=async(e={})=>{let t=ji(e.repoRoot);if(d(t))return a(t.message);let n=ut(t.value);if(d(n))return a(n.message);let r=await F({cwd:t.value,args:["log","--branches","--not",n.value.stateBranch,...e.start!==void 0?[`--since=@${Math.floor(e.start/1e3)}`]:[],...e.end!==void 0?[`--until=@${Math.floor(e.end/1e3)}`]:[],"--shortstat",`--format=${Gl}%H${Tr}%at${Tr}%an${Tr}%s`]});if(d(r))return a(r.message);let o=r.value.stdout.split(Gl).filter(s=>s.trim().length>0).map(s=>{let[i,...c]=s.split(`
59
- `),[l,m,p,...f]=(i??"").split(Tr);if(!l||!m)return null;let g=c.join(" "),E=Number(/(\d+) insertion/.exec(g)?.[1]??0),I=Number(/(\d+) deletion/.exec(g)?.[1]??0);return{sha:l,time:Number(m)*1e3,author:p??"unknown",subject:f.join(Tr),linesChanged:E+I}}).filter(s=>s!==null);return u("Computed commit timeline",o)},sy=e=>/^[0-9a-f]{7,40}$/i.test(e),iy=async(e,t)=>{let n=await F({cwd:e,args:["show",t]});if(d(n))return a(n.message);let r=Hn.join(zl.tmpdir(),"epiq","commit-diffs");be.mkDir(r);let o=Hn.join(r,`${t}.diff`);return $i(o)||(be.writeToFile(o,n.value.stdout),await Hi(o,292)),tl(o)},ay=12,dy=800,Kl=async(e,t,n)=>{let r=await F({cwd:e,args:["show",`${t}:${n}`]});return d(r)?"":r.value.stdout},cy=async(e,t,n)=>{let r=await F({cwd:e,args:["diff-tree","--no-commit-id","--name-only","-r",t]});if(d(r))return a(r.message);let o=r.value.stdout.split(`
60
- `).map(f=>f.trim()).filter(Boolean);if(o.length===0)return a("No changed files found for this commit");if(o.length>ay)return a(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=Hn.join(zl.tmpdir(),"epiq","commit-diffs",t),i=await Promise.all(o.map(async(f,g)=>{let[E,I]=await Promise.all([Kl(e,`${t}~1`,f),Kl(e,t,f)]),R=Hn.basename(f),A=Hn.join(s,String(g),"before",R),P=Hn.join(s,String(g),"after",R);return $i(A)||(be.writeToFile(A,E),await Hi(A,292)),$i(P)||(be.writeToFile(P,I),await Hi(P,292)),{beforePath:A,afterPath:P}})),[c,...l]=i;if(!c)return a("No changed files found for this commit");let m=await Ai(n,c.beforePath,c.afterPath,"new");if(d(m)||l.length===0)return m;await new Promise(f=>setTimeout(f,dy));let p=await Promise.all(l.map(({beforePath:f,afterPath:g})=>Ai(n,f,g,"reuse")));for(let f of p)d(f)&&logger.error(`Failed to open an additional diff tab for ${t}: ${f.message}`);return m},Xl=async e=>{if(!sy(e.sha))return a("Invalid commit sha");let t=ji(e.repoRoot);if(d(t))return a(t.message);let n=t.value,r=Wo()[0];if(r&&Ri(r)){let o=await cy(n,e.sha,r);if(!d(o))return o;logger.error(`Side-by-side diff failed for ${e.sha}, falling back to unified diff: ${o.message}`)}return iy(n,e.sha)},Jl=e=>{let t=je(e);if(d(t))return a(t.message);let n=it();if(d(n))return a(n.message);rs=null;let o=st(t.value).filter(d);return o.length>0?a(o.map(s=>s.message).join(", ")):(C({readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),u("Restored live state",!0))},ly=(e,t)=>{rs=null;let n=Jl(e);return d(n)?a(`${t} (recovery to live also failed: ${n.message})`):a(t)},Ql=e=>nn(async()=>{let t=Wi(e.repoRoot);if(d(t))return a(t.message);let n=fo(t.value,e.targetTime);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=n.value,s=it();if(d(s))return s;let c=st(r).filter(d);return c.length>0?ly(t.value,c.map(l=>l.message).join(", ")):(C({readOnly:!0,timeMode:"peek",unappliedEvents:o,replay:null}),rs=e.targetTime,u("Checked out historical state",{asOfTime:e.targetTime}))}),Zl=(e={})=>nn(async()=>{let t=Wi(e.repoRoot);if(d(t))return a(t.message);let n=Jl(t.value);return d(n)?a(n.message):u("Returned to live state",!0)});var Gi=()=>{let e=Ot();return d(e)?xt:e.value.attachmentMaxKb??xt},Ki=e=>{let t=$e(e??process.cwd());return d(t)?a(t.message):u("Resolved Epiq repo root",t.value)},Ne=async(e,t)=>{let n=Ki(e);if(d(n))return n;let r=Re({repoRoot:n.value});if(d(r))return a(r.message);let o=Cn(),s=await un({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.stateBranch});if(d(s))return a(s.message);if(t?.pull??!1){let l=await F({cwd:r.value,args:["pull","--ff-only"]});d(l)&&le.info(3,l.message)}let i=je(r.value);if(d(i))return a(i.message);let c=gn(i.value);return d(c)?a(c.message):u("Booted Epiq state",{repoRoot:n.value,stateBranchRoot:r.value})},Ae=()=>{let e=Ot();return d(e)?a(e.message):e.value.userId?e.value.userName?u("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},Fe=()=>{let e=We();return d(e)?a(e.message):e},tu=e=>(e.props.tags??[]).map(t=>S.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:te(t.name)})),zi=()=>{let e=We(),t=d(e)?[]:e.value.eventLog??[],n=new Map;for(let r of t)r.userId&&r.userName&&n.set(r.userId,r.userName);return n},nu=(e,t)=>{let n=new Map(e);for(let r of Object.values(t)){if(r.tombstoned){n.set(r.id,r.name);continue}n.set(r.id,Fn(r.name,n.get(r.id))??r.name)}return n},ru=(e,t=new Map)=>(e.props.assignees??[]).map(n=>S.getContributor(n)).filter(n=>n!=null).map(n=>{let r=n.tombstoned?n.name:Fn(n.name,t.get(n.id))??n.name;return{id:n.id,name:r,color:te(r)}});var ou=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Fe();if(d(n))return n;let r=n.value.nodes,o=zi(),s=Object.values(r).filter(T).filter(i=>!i.isDeleted).filter(i=>e.includeClosed||i.parentNodeId!==ve).filter(i=>e.boardId?(i.parentNodeId?r[i.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).map(i=>({id:i.id,ref:He(i.id),title:Ze(i.title),description:i.props.description??"",parentNodeId:i.parentNodeId,isClosed:i.parentNodeId===ve,readonly:!!i.readonly,tags:tu(i),assignees:ru(i,o)}));return u("Listed issues",s)},su=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=Ln(e.parentId,n.value,t.value.stateBranchRoot);if(d(o))return o;let s=Go({name:e.title,parent:e.parentId,user:n.value,rank:o.value});if(d(s))return s;let i=[...s.value],c=i.find(f=>f.action==="add.issue")?.payload.id;if(!c)return a("Unable to determine created issue id");e.description&&i.push({id:q(),...n.value,action:"edit.description",payload:{id:c,md:e.description}});let l=[];for(let f of e.tagNames??[]){let g=Ze(f).trim();if(!g||l.some(R=>R.name===g))continue;let E=Object.values(r.value.tags).find(R=>R.name===g),I=E?.id??q();E||i.push({id:q(),...n.value,action:"create.tag",payload:{id:I,name:g}}),i.push({id:q(),...n.value,action:"add.issue.tag",payload:{id:c,tag:I}}),l.push({id:I,name:g})}let m=[];for(let f of e.assigneeNames??[]){let g=Ze(f).trim();if(!g||m.some(R=>R.name===g))continue;let E=Object.values(r.value.contributors).find(R=>R.name===g),I=E?.id??q();E||i.push({id:q(),...n.value,action:"create.contributor",payload:{id:I,name:g}}),i.push({id:q(),...n.value,action:"add.issue.assignee",payload:{id:c,assignee:I}}),m.push({id:I,name:g})}let p=U(i,t.value.stateBranchRoot);return d(p)?a(p.message):u("Created issue",{id:c,title:e.title,parentId:e.parentId,description:e.description??"",tags:l,assignees:m})},iu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=fn(ve,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(d(r))return r;let o={id:q(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ve,rank:r.value}},s=U([o],t.value.stateBranchRoot);return d(s)?a(s.message):u("Closed issue",{id:e.issueId})},au=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Target node is not issue");if(o.parentNodeId!==ve)return a("Issue is not closed");let s=Ho(o);if(!s)return a("Unable to resolve previous parent from issue history");if(s===ve)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=fn(i.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(c))return c;let l={id:q(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:i.id,rank:c.value}},m=U([l],t.value.stateBranchRoot);return d(m)?a(m.message):u("Reopened issue",{id:o.id,parentId:i.id})},du=async e=>{let t=Ki(e.repoRoot);if(d(t))return t;let n=Ae();if(d(n))return n;let r=Re({repoRoot:t.value});if(d(r))return r;let o=je(r.value);if(d(o))return o;let s=gn(o.value);if(d(s))return s;let i=fn(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(d(i))return i;let c={id:q(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:i.value}},l=U([c],r.value);return d(l)?a(l.message):u("Moved issue",{id:e.issueId,parentId:e.parentId})};var os=async(e={})=>{ts();let t=Ki(e.repoRoot);if(d(t))return a("Sync failed");let n=Ae();if(d(n))return n;let r=await bo({cwd:t.value,ownEventFileName:pn(n.value)});return d(r)?(_i(r.message),r):(ns(),u("Synced",r.value))};var jn=()=>{let e=Fe();if(d(e))return e;let t=at(),n=t.mode!=="live",r=Object.values(e.value.nodes),o=r.filter(g=>to(g)&&!g.isDeleted),s=zi(),i=new Map,c=new Map;for(let g of r)if(!g.isDeleted){if(Ht(g)&&g.parentNodeId){let E=i.get(g.parentNodeId)??[];E.push(g),i.set(g.parentNodeId,E)}if(T(g)&&g.parentNodeId){let E=c.get(g.parentNodeId)??[];E.push(g),c.set(g.parentNodeId,E)}}let l=Ot();if(d(l))return l;let m={};for(let g of r.filter(T))g.isDeleted||(m[g.id]=S.getCommentsByIssue(g.id).map(E=>{let I=S.getContributor(E.authorId);return{id:E.id,issueId:E.issue,body:E.md,author:{id:E.authorId,name:I?.name??"Unknown",color:te(I?.name??E.authorId)},createdAt:eu(E.id)}}));let p=new Map;for(let g of e.value.eventLog)g.action==="add.issue.attachment"&&p.set(g.payload.id,g.payload.author);let f={};for(let g of r.filter(T))g.isDeleted||(f[g.id]=S.getAttachmentsByIssue(g.id).map(E=>({id:E.id,issueId:E.issue,name:E.name,fileName:Dn(E.hash,E.ext),bytes:E.bytes,createdAt:eu(E.id),canDelete:p.get(E.id)===l.value.userId})));return u("Retrieved Epiq GUI state",{boards:o.sort((g,E)=>g.rank.localeCompare(E.rank)).map(g=>({id:g.id,ref:He(g.id),title:g.title,swimlanes:(i.get(g.id)??[]).sort((E,I)=>E.rank.localeCompare(I.rank)).map(E=>({id:E.id,title:E.title,readonly:!!E.readonly||n,issues:(c.get(E.id)??[]).sort((I,R)=>I.rank.localeCompare(R.rank)).map(I=>({id:I.id,ref:He(I.id),title:Ze(I.title),description:I.props.description??"",readonly:!!I.readonly||n,tags:tu(I),assignees:ru(I,s),parentNodeId:I.parentNodeId,isClosed:I.parentNodeId===ve})),parentNodeId:E.parentNodeId}))})),tags:Object.values(e.value.tags).map(g=>({...g,color:te(g.name)})),contributors:Object.values(e.value.contributors).map(g=>({...g,color:te(g.name)})),user:{name:l.value.userName??"",id:l.value.userId??"",color:te(l.value.userName??"")},commentsByIssueId:m,attachmentsByIssueId:f,attachmentMaxKb:Gi(),timeTravel:t})},dt=async(e={})=>{if(at().mode!=="live")return jn();let t=await Ne(e.repoRoot,{pull:!1});return d(t)?t:jn()},cu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(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 u("No changes made",{id:e.issueId,description:s});let i={id:q(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=U([i],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited issue description",{id:e.issueId,description:e.description})},lu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=Ze(e.title);if(!s.trim())return a("Issue title cannot be empty");if(o.title===s)return u("No changes made",{id:e.issueId,title:s});let i={id:q(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=U([i],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited issue title",{id:e.issueId,title:s})},uu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Tag target must be an issue");if(o.readonly)return a("Cannot tag readonly issue");let s=Ze(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??q(),l=[...i?[]:[{id:q(),...n.value,action:"create.tag",payload:{id:c,name:s}}],{id:q(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:c}}],m=U(l,t.value.stateBranchRoot);return d(m)?a(m.message):u("Added issue tag",{id:e.issueId,tag:{id:c,name:s}})},mu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(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:q(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=U([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Removed issue tag",{id:e.issueId,tagId:e.tagId})},pu=async(e,t)=>{let n=je(e);if(d(n))return;let r;for(let o of n.value)o.userId===t&&(r=o.userName??r);return r===void 0?void 0:{id:t,name:r}},fu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Assign target must be an issue");if(o.readonly)return a("Cannot assign readonly issue");let s=e.self?n.value.userId:e.assigneeId;if(s){let R=r.value.contributors[s],A=R?void 0:await pu(t.value.stateBranchRoot,s);if(!R&&!A)return a("Unknown assignee id");let P=R??A,_=[...R?[]:[{id:q(),...n.value,action:"create.contributor",payload:{id:P.id,name:P.name}}],{id:q(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:P.id}}],w=U(_,t.value.stateBranchRoot);return d(w)?a(w.message):u("Added issue assignee",{id:e.issueId,assignee:{id:P.id,name:P.name}})}let i=Ze(e.assigneeName??"").trim();if(!i)return a("Provide assigneeId, self or assigneeName");let l=[...nu(zi(),r.value.contributors).entries()].filter(([,R])=>R===i);if(l.length>1)return a(`"${i}" matches ${l.length} contributors (${l.map(([R])=>R).join(", ")}). Assign by assigneeId to choose.`);let m=l[0];if(!m&&!e.createUnlinked)return a(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[p=q(),f=i]=m??[],E=[...!!r.value.contributors[p]?[]:[{id:q(),...n.value,action:"create.contributor",payload:{id:p,name:f}}],{id:q(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:p}}],I=U(E,t.value.stateBranchRoot);return d(I)?a(I.message):u("Added issue assignee",{id:e.issueId,assignee:{id:p,name:f}})},gu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;if(!r.value.contributors[e.contributorId])return a("Contributor not found");if(await pu(t.value.stateBranchRoot,e.contributorId))return a("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let i=[{id:q(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],c=U(i,t.value.stateBranchRoot);return d(c)?a(c.message):u("Tombstoned contributor",{id:e.contributorId,name:ro})};var vu=async(e={})=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=je(t.value.stateBranchRoot);if(d(o))return a(o.message);let s=e.boardId?Vi(o.value,e.boardId):o.value,i=new Map,c=new Set,l=new Set;for(let g of o.value)g.userId&&l.add(g.userId);for(let g of s)g.userId&&(i.set(g.userId,g.userName??""),c.add(g.userId));let m=r.value.contributors,f=[...nu(i,m).entries()].map(([g,E])=>({id:g,name:E,color:te(E),isSelf:g===n.value.userId,isExternal:!c.has(g),isRemoved:m[g]?.tombstoned===!0,hasAuthoredAnywhere:l.has(g)}));return u("Listed board contributors",f)},yu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(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:q(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=U([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},ss=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(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");if(s.length>4e3)return a(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i=q(),c={id:q(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},l=U([c],t.value.stateBranchRoot);return d(l)?a(l.message):u("Added issue comment",{id:i,issueId:e.issueId,body:s})},is=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();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(!T(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 u("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:q(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},l=U([c],t.value.stateBranchRoot);return d(l)?a(l.message):u("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},hu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Attachment target must be an issue");if(o.readonly)return a("Cannot attach to readonly issue");let s=Buffer.from(e.dataBase64??"","base64"),i=ec(t.value.stateBranchRoot,s,Gi());if(d(i))return i;let c=Ze(e.name??"").trim()||"image",l=q(),m={id:q(),...n.value,action:"add.issue.attachment",payload:{id:l,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:c,bytes:i.value.bytes}},p=U([m],t.value.stateBranchRoot);return d(p)?a(p.message):u("Added issue attachment",{id:l,issueId:e.issueId,fileName:Dn(i.value.hash,i.value.ext),bytes:i.value.bytes})},xu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.attachment"&&m.payload.id===e.attachmentId);if(!o)return a("Unable to resolve attachment");if(o.payload.author!==n.value.userId)return a("You can only delete your own attachments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!T(s))return a("Attachment target must be an issue");if(s.readonly)return a("Cannot delete attachment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.attachment"&&m.payload.id===e.attachmentId))return u("Attachment already deleted",{id:e.attachmentId,issueId:o.payload.issue});let c={id:q(),...n.value,action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:o.payload.issue}},l=U([c],t.value.stateBranchRoot);return d(l)?a(l.message):u("Deleted issue attachment",{id:e.attachmentId,issueId:o.payload.issue})},bu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});return d(t)?t:tc(t.value.stateBranchRoot,e.fileName,Gi())};var uy=15e3,Iu=e=>{let t,n=!1,r=!1,o=0,s=()=>{let p=Jr();return d(p)?(le.error(p.message),null):p.value},i=()=>{let p=s();if(!p)return!1;let{autoSync:f,userName:g,preferredEditor:E}=p;return!!(f&&g&&E)},c=()=>{let p=s()?.autoSyncDebounceMs??uy;return Math.max(0,p-(Date.now()-o))},l=async()=>{if(!(n||r)){r=!0,o=Date.now();try{await nn(async()=>{if(at().mode!=="live")return;let p=await os({repoRoot:e.repoRoot});if(d(p))return;let{pulled:f,createdCommit:g,bootstrapped:E}=p.value;!f&&!g&&!E||_t({type:"state",payload:await dt({repoRoot:e.repoRoot})})})}finally{r=!1,m()}}};function m(){n||!i()||r||t||(t=setTimeout(()=>{t=void 0,l()},c()))}return m(),{queueSync:m,dispose:()=>{n=!0,t&&clearTimeout(t)}}};import{WebSocketServer as py}from"ws";var Eu=new Set(["sync","issues:create","issues:move","issue:close","issue:reopen","issue:edit:title","issue:edit:description","issue:tag:add","issue:tag:remove","contributor:remove","issue:assignee:add","issue:assignee:remove","issue:comment:add","issue:comment:delete"]);var my=e=>({...e,boards:(e.boards??[]).map(t=>({...t,swimlanes:(t.swimlanes??[]).map(n=>({...n,issues:(n.issues??[]).map(r=>({...r,description:""}))}))})),commentsByIssueId:Object.fromEntries(Object.entries(e.commentsByIssueId??{}).filter(([,t])=>t.length>0).map(([t,n])=>[t,n.map(r=>({...r,body:""}))])),attachmentsByIssueId:Object.fromEntries(Object.entries(e.attachmentsByIssueId??{}).filter(([,t])=>t.length>0))}),wr=e=>d(e)?e:u(e.message,my(e.value)),Su=(e,t)=>{let n=(e.boards??[]).flatMap(r=>r.swimlanes??[]).flatMap(r=>r.issues??[]).find(r=>r.id===t);return{issueId:t,description:n?.description??"",comments:e.commentsByIssueId?.[t]??[]}};var Cu=()=>{_t({type:"state",payload:wr(jn())})},ie=(e,t)=>{e.send(JSON.stringify(t))},as=async(e,t)=>ie(e,{type:"state",payload:wr(await dt({repoRoot:t}))}),fy=async(e,t)=>{let n=()=>ie(e,{type:"state",payload:wr(jn())});if(at().mode!=="live")return n();let r=await dt({repoRoot:t});return at().mode!=="live"?n():ie(e,{type:"state",payload:wr(r)})},ct=async(e,t,n,r,o)=>{if(ie(e,{type:r,payload:o}),d(o))return ie(e,{type:"failed",payload:o.message});n(),fy(e,t)},Nu=(e,t,{onStateChanged:n})=>{new py({server:e,path:"/ws"}).on("connection",o=>{Va(o),o.on("message",async s=>{let i=async c=>{let{type:l}=c;if(l==="timeline:get"){let{requestId:m,...p}=c.payload??{};return ie(o,{type:"timeline",requestId:m,payload:await ql({repoRoot:t,...p})})}if(l==="issue:get"){let m=c.payload?.issueId,p=jn();return ie(o,{type:"issue",payload:d(p)?p:u("Issue detail",Su(p.value,m))})}if(l==="commits:get"){let{requestId:m,...p}=c.payload??{};return ie(o,{type:"commits",requestId:m,payload:await Yl({repoRoot:t,...p})})}if(l==="commit:inspect")return ie(o,{type:"commit:inspect:result",payload:await Xl({repoRoot:t,sha:c.payload.sha})});if(l==="time-travel:scrub"){let m=await Ql({repoRoot:t,targetTime:c.payload.targetTime});return ie(o,{type:"time-travel:result",payload:m}),d(m)?void 0:Cu()}if(l==="time-travel:live"){let m=await Zl({repoRoot:t});return ie(o,{type:"time-travel:result",payload:m}),d(m)?void 0:Cu()}if(l==="state:get")return as(o,t);if(l==="sync"){let m=await os({repoRoot:t});return ie(o,{type:"sync:result",payload:m}),n(),as(o,t)}if(l==="issue:comment:add"){let m=await ss({repoRoot:t,...c.payload});return ct(o,t,n,"issue:comment:add:result",m)}if(l==="issue:comment:delete"){let m=await is({repoRoot:t,...c.payload});return ie(o,{type:"issue:comment:delete:result",payload:m}),d(m)?ie(o,{type:"failed",payload:m.message}):(n(),as(o,t))}if(l==="issue:edit:description"){let m=await cu({repoRoot:t,...c.payload});return ct(o,t,n,"issue:edit:description:result",m)}if(l==="issue:edit:title"){let m=await lu({repoRoot:t,...c.payload});return ct(o,t,n,"issue:edit:title:result",m)}if(l==="issue:tag:add"){let m=await uu({repoRoot:t,...c.payload});return ct(o,t,n,"issue:tag:add:result",m)}if(l==="issue:tag:remove"){let m=await mu({repoRoot:t,...c.payload});return ct(o,t,n,"issue:tag:remove:result",m)}if(l==="contributor:remove"){let m=await gu({repoRoot:t,...c.payload});return ct(o,t,n,"contributor:remove:result",m)}if(l==="contributors:get")return ie(o,{type:"contributors",payload:await vu({repoRoot:t,...c.payload})});if(l==="issue:assignee:add"){let m=await fu({repoRoot:t,...c.payload});return ct(o,t,n,"issue:assignee:add:result",m)}if(l==="issue:assignee:remove"){let m=await yu({repoRoot:t,...c.payload});return ct(o,t,n,"issue:assignee:remove:result",m)}if(l==="issues:list")return ie(o,{type:"issues",payload:await ou({repoRoot:t})});if(l==="issues:create"){let m=await su({...c.payload,repoRoot:t});return ie(o,{type:"issues:create:result",payload:m}),d(m)?_t({type:"failed",payload:m.message}):(_t({type:"issue:created",payload:m.value}),n(),as(o,t))}if(l==="issues:move"){if(!c.payload.position)return ie(o,{type:"error",message:"Missing move position"});let m=await du({...c.payload,repoRoot:t});return ct(o,t,n,"issues:move:result",m)}if(l==="issue:close"){if(!c.payload.issueId)return ie(o,{type:"error",message:"Missing issueId"});let m=await iu({repoRoot:t,issueId:c.payload.issueId});return ct(o,t,n,"issue:close:result",m)}if(l==="issue:reopen"){if(!c.payload.issueId)return ie(o,{type:"error",message:"Missing issueId"});let m=await au({repoRoot:t,issueId:c.payload.issueId});return ct(o,t,n,"issue:reopen:result",m)}return ie(o,{type:"error",message:"Unknown message type"})};try{let c=JSON.parse(s.toString());return Eu.has(c.type)?await nn(async()=>at().mode!=="live"?ie(o,{type:"failed",payload:"Read-only while viewing history"}):i(c)):await i(c)}catch(c){return ie(o,{type:"error",message:c instanceof Error?c.message:String(c)})}})})};var yy=Sn.dirname(vy(import.meta.url)),hy=process.env.IS_LOCAL==="true"?Sn.resolve(process.cwd(),"dist/gui"):Sn.join(yy,"gui"),ds,xy=async()=>(ds===void 0&&(ds=await import("node:sea").catch(()=>null)),ds?.isSea()?ds:null),fe=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},by=e=>fe(e,409,{isError:!0,message:"Read-only while viewing history"}),cs=(e,t)=>nn(async()=>at().mode!=="live"?by(e):t()),Ru=async(e,t=1024*1024)=>new Promise((n,r)=>{let o="",s=0;e.on("data",i=>{if(s+=i.length,s>t){e.destroy(),r(new Error("Request body too large"));return}o+=i}),e.on("end",()=>{try{n(o?JSON.parse(o):{})}catch{r(new Error("Invalid JSON body"))}}),e.on("error",r)}),Iy=2*1024*1024,Ey={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},Sy=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",Au=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=Sn.resolve(hy),o=Sn.resolve(r,n),s=Sn.relative(r,o);if(s.startsWith("..")||Sn.isAbsolute(s))return fe(t,403,{isError:!0,message:"Forbidden"});let i=await xy();try{let c=i?Buffer.from(i.getAsset(`gui/${s}`)):await Tu(o);return t.writeHead(200,{"content-type":Sy(o)}),t.end(c)}catch{return fe(t,404,{isError:!0,message:`Not found: ${n}`})}},Cy=async(e,t=3710)=>new Promise((n,r)=>{let o=s=>{let i=l=>{if(e.off("listening",c),l.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(l)},c=()=>{e.off("error",i);let l=e.address();if(!l||typeof l=="string"){r(new Error("Unable to resolve address"));return}n(l.port)};e.once("error",i),e.once("listening",c),e.listen(s,"127.0.0.1")};o(t)}),wu=async e=>{let t=gy.createServer(async(o,s)=>{let i=new URL(o.url??"/","http://127.0.0.1");if(i.pathname==="/api/state")return fe(s,200,await dt({repoRoot:e.repoRoot}));if(o.method==="POST"&&i.pathname==="/api/comments")try{let c=await Ru(o);if(!c.issueId||!c.body?.trim())return fe(s,400,{isError:!0,message:"Missing issueId or body"});let l=c.issueId,m=c.body;return await cs(s,async()=>{let p=await ss({repoRoot:e.repoRoot,issueId:l,body:m});return d(p)?fe(s,400,{isError:!0,message:p.message}):fe(s,200,await dt({repoRoot:e.repoRoot}))})}catch(c){return fe(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add comment"})}if(o.method==="POST"&&i.pathname==="/api/attachments")try{let c=await Ru(o,Iy);if(!c.issueId||!c.dataBase64)return fe(s,400,{isError:!0,message:"Missing issueId or dataBase64"});let l=c.issueId,m=c.dataBase64,p=c.name??"";return await cs(s,async()=>{let f=await hu({repoRoot:e.repoRoot,issueId:l,name:p,dataBase64:m});return d(f)?fe(s,400,{isError:!0,message:f.message}):fe(s,200,await dt({repoRoot:e.repoRoot}))})}catch(c){return fe(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add attachment"})}if(o.method==="DELETE"&&i.pathname.startsWith("/api/attachments/")){let c=decodeURIComponent(i.pathname.replace("/api/attachments/",""));return c?cs(s,async()=>{let l=await xu({repoRoot:e.repoRoot,attachmentId:c});return d(l)?fe(s,400,{isError:!0,message:l.message}):fe(s,200,await dt({repoRoot:e.repoRoot}))}):fe(s,400,{isError:!0,message:"Missing attachment id"})}if(o.method==="GET"&&i.pathname.startsWith("/media/")){let c=decodeURIComponent(i.pathname.replace("/media/","")),l=await bu({repoRoot:e.repoRoot,fileName:c});if(d(l))return fe(s,404,{isError:!0,message:l.message});try{let m=await Tu(l.value.filePath);return s.writeHead(200,{"content-type":Ey[l.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),s.end(m)}catch{return fe(s,404,{isError:!0,message:"Attachment blob not found"})}}if(o.method==="DELETE"&&i.pathname.startsWith("/api/comments/")){let c=decodeURIComponent(i.pathname.replace("/api/comments/",""));return c?cs(s,async()=>{let l=await is({repoRoot:e.repoRoot,commentId:c});return d(l)?fe(s,400,{isError:!0,message:l.message}):fe(s,200,await dt({repoRoot:e.repoRoot}))}):fe(s,400,{isError:!0,message:"Missing comment id"})}return i.pathname.startsWith("/board/")?Au("/",s):Au(i.pathname,s)});try{await Cy(t)}catch(o){return a(o instanceof Error?`Unable to start GUI server: ${o.message}`:`Unable to start GUI server: ${String(o)}`)}let n=Iu({repoRoot:e.repoRoot});Nu(t,e.repoRoot,{onStateChanged:()=>n.queueSync()}),t.on("close",n.dispose);let r=t.address();return!r||typeof r=="string"?(t.close(),a("Unable to resolve GUI server address")):u("Started GUI server",{url:`http://epiq.localhost:${r.port}${e.boardId?`/board/${e.boardId}`:""}`,server:t})};var Mu=async e=>{let t=Ot();Q(t)&&Me(t.value);let n=await wu({...e,boardId:""});if(d(n))return n;let{url:r}=n.value;return console.log(`Epiq GUI running at ${Ny.cyan(r)}`),Oa(r),u("Started GUI",{url:r})};import{Box as dn}from"ink";import ce from"react";import{Box as qi,Text as Mr}from"ink";import lt,{useEffect as Ry,useMemo as Ay}from"react";import{ulid as Ty}from"ulid";var Pu=({text:e,match:t,color:n,highlightColor:r=h.secondary,dimColor:o=!1})=>{if(!t)return lt.createElement(Mr,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),c=s.indexOf(i);return c===-1?lt.createElement(Mr,{color:n,dimColor:o},e):lt.createElement(Mr,{color:n,dimColor:o},e.slice(0,c),lt.createElement(Mr,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},Lu=Ty(),wy=e=>`${e}`,My=e=>{let{pendingNavTarget:t}=Zt();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(de(b.NONE,{breadCrumb:n,contextNode:r,readOnly:v().readOnly,selectedNode:o}));return[...new Set(Object.values(b))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==b.PALETTE).map(i=>{let c=Lo(i),l=Xo.find(m=>m.intent===c);return{command:i,description:l?.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))},Py=e=>ee.text({id:Lu,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),Ly=(e,t,n)=>ee.text({id:wy(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Yi=[],ky=e=>{ku();let t=S.createNode(Py(v().rootNodeId));d(t)||!$t(t.value)||(Yi=[t.value,...e.map((n,r)=>Ly(n,r,Lu)).map(S.createNode).filter(Q).map(({value:n})=>n).filter($t)],M.navigate({contextNode:t.value,selectedIndex:0}))},ku=()=>{let e=Yi.map(t=>t.id);Yi=[];for(let t of e)S.deleteNode(t)};function Du({width:e,height:t}){let r=Ic().value.trim().toLowerCase(),o=Ay(()=>My(r),[r]);Ry(()=>(ky(o),()=>{ku()}),[o]);let s=v().selectedIndex;return lt.createElement(qi,{flexDirection:"column",width:e,height:t-2},lt.createElement(tt,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,c)=>{let l=c===s,m=i.isAvailable?h.accent:h.secondary2,p=i.isAvailable?"":"[unavailable] ";return lt.createElement(qi,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:h.secondary,borderStyle:"single"},lt.createElement(Mr,{color:m,dimColor:!i.isAvailable},l?"\u276F ":" ",lt.createElement(Pu,{text:Xa(i.command),match:r,color:m,dimColor:!i.isAvailable})),lt.createElement(qi,{paddingLeft:2},lt.createElement(Pu,{text:p+i.description,match:r.length>=2?r:"",color:l&&i.isAvailable?h.primary:h.secondary2,dimColor:!i.isAvailable})))})))}import{Box as Xy}from"ink";import ms from"react";import Lr from"chalk";import{Box as Xi,Text as Bu}from"ink";import Pr,{useEffect as Dy,useMemo as By,useState as Fy}from"react";var Fu=Lr.hex(h.secondary),Uy=Lr.inverse,Oy=Lr.inverse.hex(h.secondary2),_y={hint:"",hints:[],overlap:0,remainder:""},Ou=({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}},$y=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=te(t);return{bg:r=>Lr.bgHex(n).black(r),bgCursor:r=>Lr.bgHex(n).inverse.black(r)}}return Js(t)},Hy=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Ou({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}},Uu=()=>({value:Le.value,cursorPosition:Le.cursorPosition,commandIsPending:Le.commandIsPending,autoCompletion:Le.commandMeta.autoCompletion??_y,infoMessage:Le.commandMeta.infoMessage,validationStatus:Le.commandMeta.validity,command:Le.commandMeta.command,inputString:Le.commandMeta.inputString,modifier:Le.commandMeta.modifier}),jy=(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,_u=({width:e,mode:t})=>{let[n,r]=Fy(Uu());Dy(()=>{let I=()=>{let A=Uu();r(P=>jy(P,A)?P:A)},R=fi(I);return I(),()=>{R()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:c,autoCompletion:l,command:m,modifier:p,validationStatus:f}=n,g=c&&f===bt.Invalid,E=By(()=>{let I=Math.max(0,Math.min(s,o.length)),R=Ou({value:o,command:m}),A=Hy({value:o,command:m,modifier:p}),P=m?Js(m):null,_=$y({command:m,modifier:p}),w=(ge,me)=>{let Kn=R&&me>=R.start&&me<R.end,zn=A&&me>=A.start&&me<A.end;return Kn&&P?P.fg(ge):zn&&_?_.bg(ge):ge},W=(ge,me)=>{let Kn=R&&me>=R.start&&me<R.end,zn=A&&me>=A.start&&me<A.end;return Kn&&P?P.fgCursor(ge):zn&&_?_.bgCursor(ge):Uy(ge)},H=o.slice(0,I),D=o[I]??" ",$=I<o.length?o.slice(I+1):"",Ye=Array.from(H).map((ge,me)=>w(ge,me)).join(""),we=W(D,I),Xe=Array.from($).map((ge,me)=>w(ge,I+1+me)).join("");if(l.hint){let ge=l.hint[l.overlap]??D;we=Oy(ge),Xe=Fu(l.remainder.slice(1)+$)}return Fu(t===y.PALETTE?"?":":")+Ye+we+Xe},[o,s,l,m,p]);return Pr.createElement(Xi,{flexDirection:"column",justifyContent:"flex-start"},Pr.createElement(Xi,{flexDirection:"column",paddingX:1,borderColor:h.secondary,borderStyle:"round",width:e},Pr.createElement(Xi,null,Pr.createElement(Bu,null,E),i&&Pr.createElement(Bu,{wrap:"truncate",color:g?h.red:h.secondary2},` ${i} `))))};import{Box as Wy,Text as Vy}from"ink";import $u from"react";var Gy=(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},Hu=({width:e,availableHints:t})=>{let n=Gy(t,e).join(" | ");return $u.createElement(Wy,{width:e,borderStyle:"round",borderColor:h.secondary,paddingX:1},$u.createElement(Vy,{color:h.secondary2},n.length?n:"\xA0"))};import{Box as Ky,Text as ls}from"ink";import kr,{useEffect as zy,useRef as Wn,useState as qy}from"react";var Yy=40,us=.3,Ji="\u2500",ju=1,Wu=16,Vu=({width:e})=>{let{replay:t}=j(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*ju,[c,l]=qy(0),m=Wn(r);m.current=r;let p=Wn(0),f=Wn(0),g=Wn(0),E=Wn(0),I=Wn(0);if(zy(()=>{if(!n){p.current=0,g.current=0,E.current=0,I.current=0,l(0);return}p.current=m.current,f.current=Date.now(),g.current=m.current;let w=setInterval(()=>{let W=Date.now(),H=m.current;if(H!==g.current){let Xe=H-g.current,ge=W-f.current;if(Xe<0)E.current=0,I.current=0;else if(Xe>0&&ge>0){let me=Xe/ge;E.current=E.current===0?me:E.current*(1-us)+me*us,I.current=I.current===0?Xe:I.current*(1-us)+Xe*us}p.current=H,f.current=W,g.current=H}let D=W-f.current,$=Math.min(I.current,E.current*D),Ye=Math.min(1,p.current+$),we=Math.round(Ye*i);l(Xe=>Xe===we?Xe:we)},Yy);return()=>clearInterval(w)},[n,i]),!t)return null;let R=w=>{let W=s>1?w/(s-1):0,H=Math.round(W*(Wu-1))/(Wu-1);return oo(H)},A=Math.min(s,Math.floor(c/ju)),P=[];for(let w=0;w<A;w++){let W=R(w),H=P[P.length-1];H&&H.color===W?H.text+=Ji:P.push({text:Ji,color:W})}let _=Ji.repeat(Math.max(0,s-A));return kr.createElement(Ky,{width:e,borderStyle:"round",borderColor:h.secondary,paddingX:1,columnGap:1},kr.createElement(ls,{color:h.secondary2},"\u25B6"),kr.createElement(ls,null,P.map((w,W)=>kr.createElement(ls,{key:W,color:w.color},w.text)),kr.createElement(ls,{color:h.secondary,dimColor:!0},_)))};var Dr=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=j(),o=t===y.COMMAND_LINE||t===y.PALETTE;return ms.createElement(Xy,null,o?ms.createElement(_u,{width:e,mode:t}):r==="replay"?ms.createElement(Vu,{width:e}):ms.createElement(Hu,{width:e,mode:t,availableHints:n}))};import{Box as rn,Text as Vn}from"ink";import _e,{useEffect as Jy,useMemo as Qy}from"react";import{ulid as Gu}from"ulid";var fs=Gu(),Zy=()=>[...new Set([...v().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(e=>{let[t,n]=e.split("]"),r=t?.replace("[",""),o=n?.trim();return[r,o]}).filter(e=>e[0]!==void 0&&e[1]!==void 0).sort(([e],[t])=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(([e,t])=>({keys:e,action:t})),eh=e=>ee.text({id:fs,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),th=(e,t,n)=>ee.text({id:Gu(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),ps=[],Ku=()=>{let e=ps.filter(n=>n.id!==fs).map(n=>n.id),t=ps.filter(n=>n.id===fs).map(n=>n.id);ps=[];for(let n of[...e,...t])S.deleteNode(n)},nh=e=>{Ku();let t=S.createNode(eh(v().rootNodeId));if(d(t)||!$t(t.value))return logger.error("Could not attach help nodes");ps=[t.value,...e.map((n,r)=>th(n,r,fs)).map(S.createNode).filter(Q).map(({value:n})=>n).filter($t)],M.navigate({contextNode:t.value,selectedIndex:0})},zu=({width:e,height:t})=>{let n=Qy(()=>Zy(),[]);Jy(()=>(nh(n),()=>{Ku()}),[n]);let r=v().selectedIndex;return _e.createElement(rn,{flexDirection:"column",marginTop:3,borderColor:h.secondary,borderStyle:"round",width:e,height:t-2},_e.createElement(rn,{paddingX:1,justifyContent:"center"},_e.createElement(Vn,{color:h.accent},"Help"),_e.createElement(Vn,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),_e.createElement(rn,{paddingX:1,marginTop:1},_e.createElement(rn,{width:20,justifyContent:"flex-end"},_e.createElement(Vn,{color:h.secondary},"Key(s)")),_e.createElement(rn,{flexGrow:1,width:40,paddingLeft:2},_e.createElement(Vn,{color:h.secondary},"Action"))),_e.createElement(tt,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let c=i===r;return _e.createElement(rn,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},_e.createElement(rn,{width:20,justifyContent:"flex-end"},_e.createElement(Vn,{color:h.accent},o)),_e.createElement(rn,{flexGrow:1,width:40,paddingLeft:2},_e.createElement(Vn,{color:c?h.primary:h.secondary2},s)))})))};import rh from"chalk";import{Box as gs,Text as Ft}from"ink";import qe from"react";var qu=({width:e,height:t})=>qe.createElement(gs,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},qe.createElement(Ft,{color:h.accent,bold:!0},"Initialize project"),qe.createElement(Ft,null,`This folder is not an ${rh.hex(h.accent)("epiq")} project yet.`),qe.createElement(Ft,{color:h.primary},"To start tracking issues here, we need to initialize a new",qe.createElement(Ft,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json "),"file in this repository."),qe.createElement(gs,{marginTop:1,flexDirection:"column"},qe.createElement(gs,null,qe.createElement(Ft,{color:h.accent}," "),qe.createElement(Ft,{color:h.primary},"Type "),qe.createElement(Ft,{backgroundColor:h.secondary}," :init "))),qe.createElement(gs,{marginTop:1},qe.createElement(Ft,{color:h.secondary2},"This will create, commit and push "),qe.createElement(Ft,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json ")));import{Box as vs,Text as Ct}from"ink";import Te from"react";var oh=({isDone:e,command:t,value:n})=>Te.createElement(vs,null,Te.createElement(Ct,{color:h.accent,dimColor:e},e?" \u2714 ":" "),Te.createElement(Ct,{dimColor:e},"Type "),Te.createElement(Ct,{backgroundColor:h.secondary,dimColor:e}," "+t+" "),n!==void 0&&Te.createElement(Te.Fragment,null,Te.createElement(Ct,{dimColor:e}," "),Te.createElement(Ct,{color:h.secondary,dimColor:e},"<"+n+">"))),sh=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function Qi({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:c}=Kt(),l=[{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=l.findIndex(f=>!f.done),p=m===-1?void 0:l[m];return Te.createElement(vs,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},Te.createElement(Ct,{color:h.accent,bold:!0},"Welcome! \u{1F539}"),Te.createElement(Ct,null,"Let's get you started - it's a breeze."),Te.createElement(Ct,{color:h.secondary2},"Remember - you can always search available commands by typing:",Te.createElement(Ct,{color:h.accent}," ? ")),p&&Te.createElement(Ct,{color:h.secondary2},p.message),Te.createElement(vs,{flexDirection:"column"},l.map((f,g)=>m===-1||g<=m?Te.createElement(vs,{key:f.key,marginBottom:1},Te.createElement(oh,{isDone:f.done,command:f.command,value:f.done?sh(f.value):void 0})):null)))}import Is from"chalk";import{Box as Fr,Text as Gn}from"ink";import xe from"react";import{Box as ys,Text as Yu}from"ink";import on from"react";import ih from"chalk";var ah=e=>(S.getTag(e)?.name??"").length+3,dh=e=>{let t=S.getContributor(e);return(t?Xt(e,t.name):"").length+3},Xu=({width:e})=>{let{viewMode:t}=K(),n=j(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,c=i[o.id]?.[s],l=At(c?.id??o.id,"TICKET"),m=Q(l)?l.value:void 0,p=m?.props.tags??[],f=m?.props.assignees??[],g=m?.parentNodeId?!qs(o.id,m.parentNodeId)&&t==="dense":!1,E=r.map((H,D)=>{let $=D===r.length-1,Ye=Y(H.id),we=$?Ye?.[s]?.title:void 0;return`${D?" / ":""}${H.title??""}${we?` \u25B8 ${we}`:""}`}).join(""),I=m?S.getCommentsByIssue(m.id):[],R=I.length?String(I.length).length+11:0,A=g?p.reduce((H,D)=>H+ah(D),0)+f.reduce((H,D)=>H+dh(D),0)+R:0,P=c?.id!=null&&!(t==="wide"&&T(c)),_=Math.max(0,e-A),w=E.substring(0,_)+(P?ih.hex(h.secondary2).dim(` ${He(c.id)}`):""),W=g?[...p.map(H=>on.createElement(ys,{key:`tag-${H}`,paddingLeft:1},on.createElement(Un,{id:H}))),...f.map(H=>on.createElement(ys,{key:`assignee-${H}`,paddingLeft:1},on.createElement(Jt,{id:H}))),I.length?on.createElement(ys,{key:"comments",paddingLeft:1},on.createElement(Yu,{color:h.accent},"[",I.length," comment",I.length===1?"":"s","]")):null]:[];return on.createElement(ys,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},on.createElement(Yu,{color:h.secondary2},w),W)};import{Box as ch,Text as Ju}from"ink";import hs from"react";var lh=({filters:e})=>hs.createElement(ch,{columnGap:1},hs.createElement(Ju,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>hs.createElement(Ju,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Qu=hs.memo(lh);import{Box as uh,Text as xs}from"ink";import Br from"react";function Zu(){let{eventLog:e,unappliedEvents:t}=j(),n=e.at(-1)?.id,r=Ao(n??""),o=Q(r)?co(r.value):"INVALID DATE";return Br.createElement(uh,{paddingLeft:1},Br.createElement(xs,{backgroundColor:h.accent,color:h.secondary}," Readonly "),Br.createElement(xs,{color:h.accent}," "+t.length+" edits ago at "+o+"."),Br.createElement(xs,{color:h.accent}," Resume with "),Br.createElement(xs,{backgroundColor:h.accent,color:h.secondary}," ",":peek now"," "))}import{Box as mh,Text as Zi}from"ink";import bs from"react";function em(){let{replay:e}=j();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return bs.createElement(mh,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},bs.createElement(Zi,{backgroundColor:h.accent,color:h.secondary}," \u25B6 REPLAY "),bs.createElement(Zi,{color:h.secondary2},co(new Date(r))),bs.createElement(Zi,{color:h.accent},`${t}/${n} edits`))}import ea from"chalk";import{Box as ph,Text as tm}from"ink";import ta,{useEffect as fh,useState as gh}from"react";var vh=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],yh=150,nm=12,hh=.36,rm=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)}},xh=({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)}`},bh=(e,t,n)=>{let r=rm(e),o=rm(t);return xh({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Ih=(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 bh(s,i,o)};function om({syncStatus:e,autoSync:t}){let[n,r]=gh(0);fh(()=>{if(e.status!=="syncing"){r(0);return}let c=0,l=setInterval(()=>{c+=1;let m=(Math.sin(c*hh)+1)/2,p=Math.round(m*(nm-1));r(f=>f===p?f:p)},yh);return()=>clearInterval(l)},[e.status]);let o={synced:" ",failed:"---",syncing:"...",pending:"idle"},i={synced:h.secondary2,failed:h.yellow,pending:h.secondary2,syncing:Ih(vh,n/(nm-1))??""}[e.status];return ta.createElement(ph,null,ta.createElement(tm,null,ea.hex(h.secondary2).dim(t?"Sync (auto): ":"Sync: ")),ta.createElement(tm,null,ea.hex(i)("\u25CF")+ea.hex(h.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import cm from"chalk";import{Text as lm}from"ink";import um,{useEffect as Nh,useState as Rh}from"react";var sn="1.4.3";import na from"chalk";var Eh="https://registry.npmjs.org/epiq/latest",ra=null,sm=0,Sh=1e3*60*60*24,im=e=>e.replace(/^v/,""),Ch=(e,t)=>{let n=im(e).split(".").map(Number),r=im(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},am=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(ra&&Date.now()-sm<Sh)return ra;try{let t=await fetch(Eh);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?Ch(r,e)>0:!1};return ra=o,sm=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},dm=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?na.hex(h.accent).dim(s):na.hex(h.secondary).dim(s)).join(na.hex(h.secondary2).dim("."))};function mm(){let[e,t]=Rh({current:sn,latest:null,updateAvailable:!1});return Nh(()=>{let n=!0;return am(sn).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?um.createElement(lm,{dimColor:!0,color:h.secondary2},sn+" "):um.createElement(lm,null,cm.hex(h.secondary2).dim(sn),cm.hex(h.accent).dim(" \u2197 "),dm(sn,e.latest))}function Ur({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=j(),{userName:i,preferredEditor:c,autoSync:l}=K(),m=64,p=process.stdout.columns-m-8,f=t||n==="replay",g=s?mn(s.currentLabel,Math.max(0,p)):"";return xe.createElement(Fr,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?xe.createElement(Fr,{paddingLeft:1},xe.createElement(Gn,{color:h.secondary2},g)):f?xe.createElement(Gn,null," "):o===y.PALETTE?xe.createElement(Fr,null,xe.createElement(Gn,{color:h.accent},"Command Palette"),xe.createElement(Gn,{dimColor:!0,color:h.secondary2}," ","- search, select and press enter")):xe.createElement(Fr,{paddingLeft:1},e.length>0?xe.createElement(Qu,{filters:e}):xe.createElement(Xu,{width:p})),n==="live"?xe.createElement(Fr,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},xe.createElement(om,{autoSync:!!l,syncStatus:r}),xe.createElement(Gn,null,Is.hex(h.secondary2).dim("Mode: ")+Is.hex(h.secondary2).dim(o.padEnd(8," "))," "),xe.createElement(pm,{icon:"@",value:i}),xe.createElement(pm,{icon:"\u276F",value:c}),xe.createElement(mm,null)):"",n==="peek"?xe.createElement(Zu,null):"",n==="replay"?xe.createElement(em,null):"")}function pm({icon:e,value:t}){return xe.createElement(Gn,null,Is.dim(e)+Is.hex(h.accent)(` ${t??"-"} `))}import{Box as Ah,Text as Th}from"ink";import Or from"react";import{Box as Es,Text as oa}from"ink";import an from"react";function sa(){let e=j(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?z(t?.id):[];return an.createElement(Es,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:h.secondary,width:s},an.createElement(Es,{padding:1,paddingTop:0,paddingBottom:0},an.createElement(oa,null,"Select a board:")),an.createElement(Es,{padding:1,flexDirection:"column"},i.map((c,l)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===l,f=z(c.id).flatMap(({id:g})=>Y(g)).length;return an.createElement(Es,{key:c.id??l},an.createElement(oa,{color:m?h.accent:h.secondary2},an.createElement(ke,{isSelected:m})),an.createElement(oa,{color:m?h.accent:h.secondary2},c.title," (",f," issues)",c.readonly?" \u{1F512}":""))})))}var wh=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:c}=j(),l=n.find(({context:g})=>g==="BOARD"),f=s-1-3;return Or.createElement(Ah,{flexDirection:"row"},e.context==="WORKSPACE"?Or.createElement(sa,null):l?Or.createElement($o,{height:f,width:i,swimlanes:(c[l.id]??[]).filter(g=>g!==void 0&&Ht(g)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Or.createElement(Th,null))},fm=Or.memo(wh);import{useEffect as Mh}from"react";var Ph=e=>{Mh(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=K();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:c,mode:l}=v();l==="default"&&!c&&Io(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},gm=({autoSync:e})=>(Ph(e),null);function ia({width:e,height:t}){let n=j(),{autoSync:r,viewMode:o}=Ua(),s=n.filters;if(n.mode===y.HELP)return ce.createElement(dn,{flexDirection:"column"},ce.createElement(zu,{width:e,height:t}));if(n.mode===y.PALETTE)return ce.createElement(dn,{flexDirection:"column"},ce.createElement(Ur,{filters:s}),ce.createElement(Du,{width:e,height:t-2}),ce.createElement(Dr,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Kt(),c=!i,l=i&&!n.hasProjectDefinition;if(c)return ce.createElement(dn,{flexDirection:"column"},ce.createElement(dn,{flexDirection:"column"},ce.createElement(Ur,{hideBreadCrumb:!0,filters:s}),ce.createElement(Qi,{height:t,width:e})),ce.createElement(Dr,{width:e,mode:n.mode,availableHints:n.availableHints}));if(l)return ce.createElement(dn,{flexDirection:"column"},ce.createElement(dn,{flexDirection:"column"},ce.createElement(Ur,{hideBreadCrumb:!0,filters:s}),ce.createElement(qu,{height:t,width:e})),ce.createElement(Dr,{width:e,mode:n.mode,availableHints:n.availableHints}));let m=Oe(n.breadCrumb??[],"BOARD");if(Q(m)){let p=m.value.id,f=z(p).length,g=3,E=Math.floor(e/g),I=Math.floor(e/Math.max(f,1));e=Math.min(I,E)*Math.max(f,g)}return ce.createElement(dn,{flexDirection:"column"},ce.createElement(gm,{autoSync:r}),ce.createElement(dn,{flexDirection:"column"},ce.createElement(Ur,{filters:s}),ce.createElement(fm,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),ce.createElement(Dr,{width:e,mode:n.mode,availableHints:n.availableHints}))}import Lh from"readline";var Ss,Cs,Nt,kh=new Set([x.MoveCursorLeft,x.EraseInputWord,x.MoveCursorLeftOfWord,x.MoveCursorRight,x.MoveCursorRightOfWord,x.NavToPreviousContainer,x.NavToNextContainer,x.NavPreviousItem,x.NavNextItem,x.SetViewDense,x.SetViewWide,x.Confirm,x.Exit,x.Yank,x.InitCommandLine,x.InitCommandPalette,x.ExitCommandLine,x.CaptureInput,x.EraseInput,x.EraseInputWord,x.HideHelp,x.ViewHelp,x.SetViewDense,x.SetViewWide,x.GetLastCommandFromHistory,x.GetNextCommandFromHistory,x.AutoCompleteCommand]),Dh=new Set([x.NavPreviousItem,x.NavNextItem,x.NavToPreviousContainer,x.NavToNextContainer,x.Confirm,x.Exit,x.InitCommandPalette,x.InitMove,x.MoveNextItem,x.MovePreviousItem,x.MoveToNextContainer,x.MoveToPreviousContainer,x.Delete,x.AddItem,x.EditTitle,x.EditDescription,x.ConfirmMove,x.Edit,x.ViewHelp,x.Yank]),vm=async e=>{if(e.ctrl&&e.name==="c")return M.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=v(),s=Sc(e,n);if(!s||r&&!kh.has(s)||o==="replay"&&n===y.DEFAULT&&Dh.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(c){logger.error(c)}},Bh=()=>async function(t,n){n.name!=="escape"&&(Nt&&(clearTimeout(Nt),Nt=void 0),await vm(n))},Fh=()=>async function(t){if(t.length===1&&t[0]===27){Nt&&clearTimeout(Nt),Nt=setTimeout(()=>{vm({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),Nt=void 0},25);return}Nt&&(clearTimeout(Nt),Nt=void 0)};function ym(){Ss&&process.stdin.removeListener("keypress",Ss),Cs&&process.stdin.removeListener("data",Cs),Ss=Bh(),Cs=Fh(),Lh.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Cs),process.stdin.on("keypress",Ss)}async function hm(){try{let e=Ot();Q(e)&&Me(e.value);let t=$e(process.cwd()),n=[];if(Q(t)){let s=Re({repoRoot:t.value});if(d(s))return vn(3,s.message);let i=Cn(),c=await un({repoRoot:t.value,stateBranchRoot:s.value,stateBranchName:i.stateBranch});if(d(c))return vn(3,c.message);let l=await F({cwd:s.value,args:["pull","--ff-only"]});d(l)&&logger.info(3,l.message);let m=je(s.value);if(d(m))return vn(3,m.message);n=m.value}let r=gn(n);if(d(r))return vn(4,r.message);C({hasProjectDefinition:Q(t),hasInitializingEvents:!!n.length});let o=aa();return d(o)?vn(6,o.message):(ym(),u("Booted Epiq",void 0))}catch(e){return vn(0,ho(e))}}Yc();var $h=`${cn.bold("Epiq CLI")}
57
+ `,Mi.writeFileSync(t,n,"utf8"),le.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),u("Local epiq paths ignored",!0)};var wv=async e=>{let t=await U({cwd:e,args:["status","--porcelain"]});return d(t)?t:u("Checked git diff",t.value.stdout.trim().length>0)},re=(e,t)=>a(`[${e}] ${t}`),il=async()=>{G("");let e=Cn(),t=await vt(process.cwd());if(d(t))return re(1,t.message);let n=t.value,r=await Gr(n);if(d(r))return re(2,r.message);if(r.value)return re(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await wv(n);if(d(o))return re(2.5,o.message);if(o.value)return re(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if($s(n))return re(4,"Epiq project already initialized");let s=qt();if(!s.isSetupDone||!s.userName)return re(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let i=K(),c=i.userName,l=i.userId;if(!l||!c)return re(5,"Missing Epiq user id");let m=e.stateBranch,p=await Kr({repoRoot:n,branch:m});if(d(p))return re(6,p.message);if(p.value)return re(6,`State branch already exists: ${m}`);let f=await Ks({repoRoot:n,stateBranchName:m});if(d(f))return re(6,f.message);let g=Yr();if(d(g))return re(7,g.message);let E=sl.join(qr(),e.projectId),I=await mn({repoRoot:n,stateBranchRoot:E,stateBranchName:m});if(d(I))return re(8,I.message);let N=sl.join(E,".epiq");Tv.mkdirSync(N,{recursive:!0});let A=Ud({userId:l,userName:c});if(d(A))return re(9,A.message);for(let Ts of A.value){let la=vo({event:Ts,rootDir:E});if(d(la))return re(9,la.message)}let P=await eo({stateBranchRoot:E,eventFileName:pn({userId:l,userName:c})});if(d(P))return re(10,P.message);let F=await Rn({cwd:E,message:"[epiq:init]"});if(d(F))return re(10,F.message);let H=await ol(n);if(d(H))return re(11,H.message);let W=ma({repoRoot:n,fileContents:e});if(d(W))return re(12,W.message);let w=await ue.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d(w))return re(13,w.message);let B=await ue.commit({cwd:n,message:"[epiq:init-project]"});if(d(B))return re(13,B.message);let $="Project initialized!",Xe=await U({cwd:n,args:["push","-u","origin","HEAD"]});d(Xe)&&($+=` Warn: [init:14] ${Xe.message}`);let we=await or({repoRoot:n,stateBranchRoot:E});d(we)&&($+=` Warn: [init:15] ${we.message}`);let ge=it(A.value).filter(d);if(ge.length>0)return re(16,ge.map(Ts=>Ts.message).join(`
58
+ `));let me=Ge();if(d(me))return re(16,me.message);let{rootNodeId:Vn,nodes:Kn}=me.value,ca=Kn[Vn];return ca?(M.navigate({contextNode:ca,selectedIndex:0}),C({hasProjectDefinition:!0,mode:h.DEFAULT}),u($,null)):re(16,"Unable to resolve initialized root node")};import{ulid as Pv}from"ulid";import{ulid as Mv}from"ulid";var al=null,nn=()=>structuredClone(al),Nr=e=>{al=e},dl=()=>{let{contextNode:e,selectedIndex:t}=v(),r=Y(e.id)[t];return r?u("Resolved selected child",r):a("Target node not found")},Pi=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Y(t).filter(o=>o.id!==e);return ho(r,n)},cl=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ae();if(d(r))return a("Unable to resolve user ID");let o=Pi({parentId:t,id:e,position:n});return d(o)?o:u("Created pending move state",{id:Mv(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},ll=e=>{Nr(e);let t=Kt(e,!0);return d(t)?t:u("Node moved successfully",t.value)};function Li(e){let t=dl();if(d(t))return t;let{contextNode:n,nodes:r}=v();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=Y(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 l=cl({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(l)?l:ll(l.value)}function ki(e){let t=dl();if(d(t))return t;let{contextNode:n,selectedIndex:r}=v(),s=Y(n.id)[r+e];if(!s)return a("Missing sibling node");let i=cl({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:ll(i.value)}var ul=()=>{let e=nn();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=v().nodes[n];if(!r)return a("Move parent not found");let o=Y(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(M.navigate({contextNode:r,selectedIndex:o}),u("Synchronized navigation to moved node",null))},Vo=(e,t="Moved preview")=>{if(d(e))return e;let n=ul();return d(n)?n:(C({mode:h.MOVE}),u(t,null))},ml=async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=X().commandMeta,{contextNode:n,selectedIndex:r}=v(),o=Y(n.id)[r];if(!o)return C({mode:h.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=Y(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],l=s[i+1],m=l!=null?{at:"before",sibling:l.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=Pi({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(Nr({id:Pv(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),C({mode:h.MOVE}),u("Move initialized",null))}if(t==="next")return Vo(ki(1));if(t==="previous")return Vo(ki(-1));if(t==="to-next")return Vo(Li(1));if(t==="to-previous")return Vo(Li(-1));if(t==="confirm"){let s=nn();if(!s)return a("No pending move to confirm");let i=await yt();if(d(i))return i;let c=O([s],i.value);if(d(c))return c;let l=ul();return d(l)?l:(Nr(null),C({mode:h.DEFAULT}),u("Moved item",null))}return t==="cancel"?(Nr(null),C({mode:h.DEFAULT}),u("Cancelling move",null)):a("Invalid move modifier")};import{ulid as zo}from"ulid";import{monotonicFactory as Lv,ulid as kv}from"ulid";var Dv=Lv(),Ko=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=Dv();return u("Created issue events",[{id:kv(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var pl=async(e,t)=>{let n=ae();if(d(n))return a("Unable to resolve user ID");let r=await yt();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}=v(),l=m=>{let p=O([m],o);if(d(p))return p;let f=S.getNode(p.value[0].result.id);if(!f)return a("Created node not found");if(!f.parentNodeId)return p;let g=S.getNode(f.parentNodeId);return g?(M.navigate({contextNode:g,selectedIndex:S.getSiblings(f.parentNodeId).findIndex(({id:E})=>E===f.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=v(),p=S.getNode(m);if(!p)return a("Workspace not found");let f=Ln(p.id,n.value,o);return d(f)?f:l({id:zo(),action:"add.board",payload:{id:zo(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=_e(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=Ln(m.value.id,n.value,o);return d(p)?p:l({id:zo(),action:"add.swimlane",payload:{id:zo(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=z(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let F=_e(s,"SWIMLANE");return d(F)?null:F.value})();if(!p)return a("Unable to add issue in this context");let f=Ln(p.id,n.value,o);if(d(f))return f;let g=Ko({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(d(g))return g;let E=g.value,I=O([...E],o);if(d(I))return I;if(!I.value[0])return a("Issue creation failed");let P=E.find(F=>F.action==="add.issue")?.payload.id;return P?(M.navigate({contextNode:p,selectedIndex:S.getSiblings(p.id).findIndex(({id:F})=>F===P)}),u("Issue created",null)):a("Unable to determine ticket id")}return u("Success",null)};var qo=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=v(),s=go(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,l=at();if(d(l))return l;let p=it(i).filter(d);if(p.length>0)return at(),C(o),a(p.map(g=>g.message).join(", "));let f=v().nodes[e];return f?(M.navigate({contextNode:f,selectedIndex:r}),u("",{unappliedEvents:c})):(at(),C(o),a("Board did not exist at that date"))};var Bv=20,Fv=16,Uv=150,Yo=null,Xo=null;var En=()=>{Yo!==null&&(clearInterval(Yo),Yo=null),Xo!==null&&(clearTimeout(Xo),Xo=null)},fl=()=>{En(),C({mode:h.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Ov=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)},gl=({events:e,startTime:t,durationMs:n})=>{En();let r=e.length,o=e.map(f=>Jt(f)??t),s=o[r-1]??Date.now(),i=Ov(o),c=Math.max(1,Math.round(n*Bv/1e3)),l=Math.max(Math.round(n/c),Fv),m=0,p=0;C({mode:h.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Yo=setInterval(()=>{m++;let f=m/c,g=[],E;for(;p<r&&i[p]<=f;){let N=e[p],A=Kt(N);if(d(A)){fl();return}g.push(...Zs(N)),E=N,p++}if(p>=r||m>=c){for(;p<r;p++){let A=Kt(e[p]);if(d(A))break}let N=v().replay;C({unappliedEvents:[],replay:N&&{...N,progress:1,appliedCount:r}}),En(),Xo=setTimeout(fl,Uv);return}let I=v().replay;C({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:E?Jt(E)??I?.currentTime??t:I?.currentTime??t,currentLabel:E?gd(E):I?.currentLabel??"",flashNodeIds:E?[...new Set(g)]:I?.flashNodeIds??[]}})},l)};var vl=async()=>{let e=_e(v().breadCrumb,"BOARD");if(d(e))return e;let t=await vt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Re({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=X().commandMeta;if(En(),r==="now"){let c=je(n.value);if(d(c))return a(c.message);let l=at();if(d(l))return l;let p=it(c.value).filter(d);return p.length>0?a(p.map(f=>f.message).join(", ")):(C({mode:h.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),u("Peeking now",!0))}let s;if(r==="prev"){let c=v().eventLog.at(-1),l=Jt(c);if(l===null)return a("No previous event to peek");s=l}else if(r==="next"){let c=v().unappliedEvents.at(0),l=Jt(c);if(l===null)return a("No next event to peek");s=l+1}else{let c=hn(r||o.trim());if(!c)return a("Invalid peek date");s=c.getTime()}let i=qo({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(C({mode:h.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),u("Peeking",!0))};var hl=async()=>{let e=_e(v().breadCrumb,"BOARD");if(d(e))return e;let t=await vt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Re({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=X().commandMeta,{dateInput:s,durationInput:i}=Ro(r,o);if(En(),v().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let c=hn(s);if(!c)return a("Invalid replay date");let l=i?No(i):15e3;if(l===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=v(),f=qo({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(d(f))return f;let{unappliedEvents:g}=f.value;return g.length===0?(at(),C(p),u("Nothing to replay from that point",!0)):(gl({events:g,startTime:m,durationMs:l}),u("Replaying board history",!0))};import $v from"zod";var yl=()=>{let e=X().commandMeta.inputString,t=$v.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=Qe({autoSyncDebounceMs:t.data});return d(n)?n:(Me({autoSyncIntervalMs:t.data}),C({mode:h.DEFAULT}),u(`Auto sync interval set to ${t.data}ms`,null))};var xl=()=>{let e=X().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Gd(e),n=Qe({autoSync:t});return d(n)?n:(Me({autoSync:t}),C({mode:h.DEFAULT}),u(`Auto sync set to "${e}"`,null))};var bl=()=>{let e=X().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=Qe({logLevel:e});return d(n)?n:(Me({logLevel:e}),C({mode:h.DEFAULT}),u(`Auto sync set to "${e}"`,null))};import{spawn as Hv}from"node:child_process";var Wv=()=>{switch(process.platform){case"darwin":return{command:"pbcopy",args:[]};case"win32":return{command:"clip",args:[]};default:return process.env.WAYLAND_DISPLAY?{command:"wl-copy",args:[]}:{command:"xclip",args:["-selection","clipboard"]}}},Il=async e=>new Promise(t=>{let{command:n,args:r}=Wv();try{let o=Hv(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(a(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?u("Copied to clipboard",null):a(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(a(`Clipboard tool not available (${n})`))}});var Rr=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await Il(e);return d(n)?n:u(`Copied ${t} to clipboard`,null)},El=async e=>{let{breadCrumb:t,selectedNode:n}=v(),r=pr({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return a("Nothing selected to copy from");switch(e.modifier){case he.REF:return Rr(We(o.id),"ref");case he.TITLE:return Rr(o.title,"title");case he.DESCRIPTION:return r?Rr(r.props?.description??"","description"):a("No issue in scope");case he.TAGS:{if(!r)return a("No issue in scope");let s=Yt(r).map(({name:i})=>i);return Rr(s.join(", "),"tags")}case he.ASSIGNEES:{if(!r)return a("No issue in scope");let s=Xt(r).map(({name:i})=>i);return Rr(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}};var Sl=async()=>{G(""),C({mode:h.DEFAULT});let e=Ge();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 bo();return d(t)?(C({syncStatus:{msg:t.message,status:"failed"}}),t):(C({mode:h.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var jv=e=>e.action==="add.issue.comment",Cl=e=>Object.values(v().tags).find(t=>t.name===e),Nl=()=>{let{eventLog:e=[],contributors:t}=v(),n=new Map,r=new Set;for(let o of e)o.userId&&(n.set(o.userId,o.userName??""),r.add(o.userId));for(let o of Object.values(t)){if(o.tombstoned){n.set(o.id,o.name);continue}n.set(o.id,Fn(o.name,n.get(o.id))??o.name)}return[...n.entries()].map(([o,s])=>({id:o,name:s,isExternal:!r.has(o)}))},Ft=async()=>{let e=await yt();return d(e)?e:u("Resolved persist root",e.value)},Jo=[{systemOnly:!0,intent:k.Move,description:"Internal move-state command",mode:h.COMMAND_LINE,action:ml},{intent:k.Delete,description:"Delete the currently selected node",mode:h.COMMAND_LINE,action:async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await Ft();if(d(o))return o;if(r.context==="COMMENT"){let s=r.id,i=T(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=v().nodes[i];if(!c||!T(c))return a("Unable to resolve comment issue");let l=c.log?.filter(jv).find(m=>m.payload.id===s);return l?l.payload.author!==e.value.userId?a("You can only delete your own comments"):O([{id:Be(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return O([{id:Be(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>C({mode:h.DEFAULT})},{intent:k.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:h.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=X().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>de(b.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return pe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:h.DEFAULT})),u("Filter updated",null)}},{intent:k.ViewHelp,description:"Open the help screen",mode:h.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return tn({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),C({mode:h.HELP}),u("Viewing help",null)}},{intent:k.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:h.COMMAND_LINE,action:async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!T(r))return a("Cannot close in this context");let o=v().nodes[ve];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await Ft();if(d(s))return s;let i=s.value,c=fn(o.id,r.id,{at:"end"},e.value,i);if(d(c))return c;let l=O([{id:Be(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value}],i);return d(l)?l:u("Issue closed",null)},onSuccess:()=>C({mode:h.DEFAULT})},{intent:k.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:h.COMMAND_LINE,action:async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?u("Resolved ticket",r):wt(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let s=o.value,i=v().nodes[ve];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!T(s))return a("Target node is not issue");let c=Wo(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 l=v().nodes[c];if(!l)return a("Previous parent no longer exists");let m=await Ft();if(d(m))return m;let p=m.value,f=fn(l.id,s.id,{at:"end"},e.value,p);if(d(f))return f;let g=O([{id:Be(),action:"reopen.issue",payload:{id:s.id,parent:l.id,rank:f.value},...e.value}],p);return d(g)?g:u("Issue reopened",null)},onSuccess:()=>C({mode:h.DEFAULT})},{intent:k.Init,description:"Initialize Epiq in the current git repository",mode:h.COMMAND_LINE,action:il},{intent:k.NewItem,description:"Create a new board, swimlane, or issue",mode:h.COMMAND_LINE,action:pl,onSuccess:()=>C({mode:h.DEFAULT})},{intent:k.Rename,description:"Rename the currently selected node",mode:h.COMMAND_LINE,action:async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=z(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=Sc();if(!o)return a("Provide a title");let s=await Ft();return d(s)?s:O([{id:Be(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>C({mode:h.DEFAULT})},{intent:k.UntagTicket,description:"Remove a tag from the selected issue",mode:h.COMMAND_LINE,action:async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=X().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=Cl(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=v();if(!s)return a("Invalid untag target");let i=wt(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let c=i.value;if(!T(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 Ft();return d(m)?m:O([{id:Be(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>C({mode:h.DEFAULT})},{intent:k.TagTicket,description:"Add or create a tag on the selected issue",mode:h.COMMAND_LINE,action:async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=X().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=v();if(!o)return a("Invalid tag target");let s=wt(o.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!T(i))return a("Target node is not issue");let c=await Ft();if(d(c))return c;let l=Cl(r),m=l?.id??Be();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):O([...l?[]:[{id:Be(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:Be(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)},onSuccess:()=>C({mode:h.DEFAULT})},{intent:k.AssignUserToTicket,description:"Assign a user to the selected issue",mode:h.COMMAND_LINE,action:async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=X().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return a("Provide an assignee");let{selectedIndex:i,contextNode:c}=v(),l=z(c.id)[i];if(!l)return a("Invalid assign target");let m=wt(l.id,"TICKET");if(d(m))return a("Unable to assign issue in this context");let p=m.value;if(!T(p))return a("Target node is not issue");let f=await Ft();if(d(f))return f;let g=Nl(),E=!o&&s.toLowerCase()==="me",I,N;if(E)I=e.value.userId,N=g.find(F=>F.id===I)?.name??e.value.userName;else{let F=g.filter(W=>W.name===s);if(F.length>1)return a(`"${s}" matches ${F.length} contributors (${F.map(W=>W.id).join(", ")}). Assign from the GUI to choose by id.`);let H=F[0];if(!H&&!o)return a(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);I=H?.id??Be(),N=H?.name??s}if((p.props.assignees??[]).includes(I))return a("Assignee already assigned");let P=!!v().contributors[I];return O([...P?[]:[{id:Be(),action:"create.contributor",payload:{id:I,name:N},...e.value}],{id:Be(),action:"add.issue.assignee",payload:{id:p.id,assignee:I},...e.value}],f.value)},onSuccess:()=>C({mode:h.DEFAULT})},{intent:k.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:h.COMMAND_LINE,action:async()=>{let e=ae();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=X().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let{selectedNode:o}=v();if(!o)return a("Invalid unassign target");let s=wt(o.id,"TICKET");if(d(s))return a("Unable to unassign in this context");let i=s.value;if(!T(i))return a("Target node is not issue");let c=i.props.assignees??[],l=r.toLowerCase()==="me",m=l?c.filter(g=>g===e.value.userId):Nl().filter(g=>g.name===r&&c.includes(g.id)).map(g=>g.id);if(m.length>1)return a(`"${r}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return a(l?"Issue is not assigned to you":`Issue is not assigned to "${r}"`);let f=await Ft();return d(f)?f:O([{id:Be(),action:"remove.issue.assignee",payload:{id:i.id,assignee:p},...e.value}],f.value)},onSuccess:()=>C({mode:h.DEFAULT})},{intent:k.Comment,description:"Add a comment to the selected issue",mode:h.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return a("Provide a comment");if(n.length>4e3)return a(`Cannot exceed ${4e3} characters`);let r=ae();if(d(r))return a("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=v(),i=_e([...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 l=c.context==="TICKET"?u("Resolved ticket",c):wt(c.id,"TICKET");if(d(l))return a("Unable to comment on issue in this context");let m=l.value;if(!T(m))return a("Target node is not issue");let p=await Ft();return d(p)?p:O([{id:Be(),action:"add.issue.comment",payload:{id:Be(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>C({mode:h.DEFAULT})},{intent:k.Sync,description:"Pull, commit, and push Epiq state",mode:h.COMMAND_LINE,action:Sl},{intent:k.Peek,description:"View board state at another point in time",mode:h.COMMAND_LINE,action:vl},{intent:k.Replay,description:"Replay board history forward from a point in time",mode:h.COMMAND_LINE,action:hl},{intent:k.Export,description:"Export the current board layout to markdown",mode:h.COMMAND_LINE,action:async()=>{let e=await qc();return d(e)?e:(C({mode:h.DEFAULT}),u("Export successful",!0))}},{intent:k.Exit,description:"Exit the application",mode:h.COMMAND_LINE,action:async()=>(M.exit(),u("Exit successful",!0))},{intent:k.Edit,description:"Edit title or description",mode:h.COMMAND_LINE,action:async(e,t)=>rl(t),onSuccess:()=>C({mode:h.DEFAULT})},{intent:k.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:h.COMMAND_LINE,action:async(e,t)=>El(t),onSuccess:()=>C({mode:h.DEFAULT})},{intent:k.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:h.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case oe.USERNAME:{let{userId:r,preferredEditor:o,userName:s}=K(),i=n||s,c=r??Be();if(!i||!c)return a("Unable to resolve user name or id");let l=Qe({userName:i,userId:c,preferredEditor:o??""});return d(l)?l:(Me({userName:i,userId:c}),C({mode:h.DEFAULT}),u(`Username set to "${i}"`,null))}case oe.EDITOR:{if(!n)return a("No editor provided");let r=Qe({preferredEditor:n});return d(r)?r:(Me({preferredEditor:n}),C({mode:h.DEFAULT}),u(`Editor configuration set to "${n}"`,null))}case oe.VIEW:{if(n!=="wide"&&n!=="dense")return a("Invalid view mode");let r=Qe({viewMode:n});return d(r)?r:(Me({viewMode:n}),C({mode:h.DEFAULT}),u(`View set to "${n}"`,null))}case oe.AUTOSYNC:return xl();case oe.LOG_LEVEL:return bl();case oe.SYNC_DEBOUNCE_MS:return yl();case oe.ATTACHMENT_MAX_KB:return rc();default:return a("Unknown config command")}}},{intent:k.Coffee,description:"Sponsor the development of Epiq!",mode:h.COMMAND_LINE,action:()=>{let e=X().commandMeta.modifier;return e==="custom"?Cr("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):Cr(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),G(""),u("Thanks you!",null)}}];var Gv=new Set(["peek","replay","filter","view-help","yank"]),Nt=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=X();if(!t)return a("No command to confirm");if(!e&&n===It.Invalid)return a("Invalid command");let s=ko(t);yc();let{readOnly:i}=v();if(i&&!Gv.has(s))return hr({status:_t.Fail,message:"Command not available in readonly state",value:null});let c=Jo.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return hr({status:_t.Fail,message:"Command not found",value:null});let l;try{l=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return hr({status:_t.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(l)?hr(l):(xc({addToHistory:!e}),c.onSuccess?.(),K().autoSync&&Eo(),l)};var Qo=[{intent:x.Exit,mode:h.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(C({mode:h.COMMAND_LINE}),G("move cancel"),Nt({isForceExecutedBySystem:!0}))},{intent:x.InitMove,mode:h.DEFAULT,description:"[m] move (init/confirm)",action:()=>(C({mode:h.COMMAND_LINE}),G("move start"),Nt({isForceExecutedBySystem:!0}))},{intent:x.ConfirmMove,mode:h.MOVE,action:()=>(C({mode:h.COMMAND_LINE}),G("move confirm"),Nt({isForceExecutedBySystem:!0}))}],Zo=[{intent:x.MovePreviousItem,mode:h.MOVE,action:()=>nn()?(C({mode:h.COMMAND_LINE}),G("move previous"),Nt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:x.MoveNextItem,mode:h.MOVE,action:()=>nn()?(C({mode:h.COMMAND_LINE}),G("move next"),Nt({isForceExecutedBySystem:!0})):a("No pending move")}],Rl=[{intent:x.MoveToNextContainer,mode:h.MOVE,action:()=>nn()?(C({mode:h.COMMAND_LINE}),G("move to-next"),Nt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:x.MoveToPreviousContainer,mode:h.MOVE,action:()=>nn()?(C({mode:h.COMMAND_LINE}),G("move to-previous"),Nt({isForceExecutedBySystem:!0})):a("No pending move")}];var Al={[D.WORKSPACE]:[...Qo,...Zo],[D.BOARD]:[...Qo,...Zo],[D.SWIMLANE]:[...Qo,...Zo,...Rl],[D.TICKET]:[],[D.FIELD]:[],[D.FIELD_LIST]:[],[D.TEXT]:[],[D.COMMENT]:[]};import Vv from"node:fs";import Kv from"node:path";var Tl=e=>{let t=He(process.cwd());if(d(t))return a("Unable to resolve project root");let n=Re({repoRoot:t.value});if(d(n))return a(n.message);let r=Dn(e.hash,e.ext),o=Kv.join(nr(n.value),r);return Vv.existsSync(o)?(Cr(o),u(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")};var wl=()=>{G("");let{pendingNavTarget:e}=en();C({mode:h.DEFAULT}),e&&M.navigate(e),tn({pendingNavTarget:void 0})},Ml=[{intent:x.ExitCommandLine,mode:h.HELP,action:()=>(wl(),u("Exiting help",null))},{intent:x.Exit,mode:h.HELP,action:()=>(wl(),u("Closed help",null))},{intent:x.NavPreviousItem,mode:h.HELP,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),u("Navigating to previous help item",null))},{intent:x.NavNextItem,mode:h.HELP,action:()=>(M.navigateToNextItem(),u("Navigating to next help item",null))},{intent:x.NavToPreviousContainer,mode:h.HELP,action:()=>(M.navigateToPreviousContainer(),u("Navigating to previous help container",null))},{intent:x.NavToNextContainer,mode:h.HELP,action:()=>(M.navigateToNextContainer(),u("Navigating to next help container",null))}];var zv=e=>{C({mode:h.COMMAND_LINE});let{pendingNavTarget:t}=en();t&&M.navigate(t),tn({pendingNavTarget:void 0}),G(`${e} `)},Pl=()=>{G("");let{pendingNavTarget:e}=en();e&&M.navigate(e),tn({pendingNavTarget:void 0}),C({mode:h.DEFAULT})},Ll=[{intent:x.InitCommandPalette,mode:h.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{G("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return tn({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),C({mode:h.PALETTE}),u("Opening command palette",null)}},{intent:x.Confirm,mode:h.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!Wt(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?(zv(t),u("Selected command",t)):u("No command selected",null)}},{intent:x.ExitCommandLine,mode:h.PALETTE,action:()=>(Pl(),u("Exiting palette",null))},{intent:x.Exit,mode:h.PALETTE,action:()=>(Pl(),u("Closed command palette",null))},{intent:x.NavPreviousItem,mode:h.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:x.NavNextItem,mode:h.PALETTE,action:()=>(M.navigateToNextItem(),u("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:h.PALETTE,action:()=>(M.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:h.PALETTE,action:()=>(M.navigateToNextContainer(),u("Navigating to next container",null))}];var kl=[...Ml,...Ll,{intent:x.AddItem,mode:h.DEFAULT,description:"[n] new...",action:()=>(C({mode:h.COMMAND_LINE}),G(`${b.NEW} `),u("Adding new item",null))},{intent:x.Delete,mode:h.DEFAULT,description:"[d] delete",action:()=>(C({mode:h.COMMAND_LINE}),G(`${b.DELETE} `),u("Deleting item",null))},{intent:x.InitCommandLine,mode:h.DEFAULT,description:"[:] focus command line",action:()=>(C({mode:h.COMMAND_LINE}),G(""),u("Entering command line mode",null))},{intent:x.Confirm,mode:h.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!Y(e?.id??"")?.length){let r=e?S.getAttachment(e.id):void 0;if(r)return Tl(r);if(e?.title===Z.DESCRIPTION)return C({mode:h.COMMAND_LINE}),G(`${b.EDIT} description `),u("Propose command",!0);if(e?.title===Z.ASSIGNEES)return C({mode:h.COMMAND_LINE}),G(`${b.ASSIGN} `),u("Propose command",!0);if(e?.title===Z.TAGS)return C({mode:h.COMMAND_LINE}),G(`${b.TAG} `),u("Propose command",!0);if(t.title===Z.DESCRIPTION&&e?.context==="TEXT")return C({mode:h.COMMAND_LINE}),G(`${b.EDIT} description `),u("Propose command",!0)}return M.enterChildNode(),u("Entering context",null)}},{intent:x.Yank,mode:h.DEFAULT,description:"[y] yank to clipboard",action:()=>{let{selectedNode:e}=v(),t=e?.title===Z.DESCRIPTION?he.DESCRIPTION:e?.title===Z.TAGS?he.TAGS:e?.title===Z.ASSIGNEES?he.ASSIGNEES:he.REF,r=de(b.YANK).includes(t)?t:he.REF;return C({mode:h.COMMAND_LINE}),G(`${b.YANK} ${r}`),u("Propose command",!0)}},{intent:x.EditTitle,mode:h.DEFAULT,description:"[r] rename title",action:()=>(C({mode:h.COMMAND_LINE}),G(`${b.EDIT} title ${v().selectedNode?.title}`),u("Exiting context",null))},{intent:x.EditDescription,mode:h.DEFAULT,description:"[e] edit description",action:()=>(C({mode:h.COMMAND_LINE}),G(`${b.EDIT} description `),u("Exiting context",null))},{intent:x.Exit,mode:h.DEFAULT,description:"[q] exit context",action:()=>(M.enterParentNode(),u("Exiting context",null))},{intent:x.NavPreviousItem,mode:h.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:x.NavNextItem,mode:h.DEFAULT,action:()=>(M.navigateToNextItem(),u("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:h.DEFAULT,action:()=>(M.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:h.DEFAULT,action:()=>(M.navigateToNextContainer(),u("Navigating to next container",null))}];var qv=500,Yv=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Dl=e=>{let t=Yv(e);t&&Lo(n=>(n+t).slice(0,qv))};var Xv=[h.COMMAND_LINE,h.PALETTE],Jv=e=>[{intent:x.MoveCursorLeft,mode:e,action:()=>(vi(-1),u("Moving cursor left",null))},{intent:x.MoveCursorRight,mode:e,action:()=>(vi(1),u("Moving cursor right",null))},{intent:x.MoveCursorLeftOfWord,mode:e,action:()=>(hi("left"),u("Moving cursor left of word",null))},{intent:x.MoveCursorRightOfWord,mode:e,action:()=>(hi("right"),u("Moving cursor right of word",null))},{intent:x.AutoCompleteCommand,mode:e,action:()=>(Lo((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=v().selectedNode?.title??""),r+o}),u("Auto-completing command",null))},{intent:x.CaptureInput,mode:e,action:(t,{sequence:n})=>(Dl(n??""),u("Capturing input",null))},{intent:x.EraseInput,mode:e,action:()=>(vc(),u("Erasing input",null))},{intent:x.EraseInputWord,mode:e,action:()=>(hc(),u("Erasing input word",null))}],Bl=[{intent:x.Confirm,mode:h.COMMAND_LINE,action:()=>(Nt(),u("Executing command",null))},{intent:x.ViewHelp,mode:h.DEFAULT,action:()=>(C({mode:h.HELP}),u("Viewing help",null))},...Xv.flatMap(Jv),{intent:x.ExitCommandLine,mode:h.COMMAND_LINE,action:()=>(C({mode:h.DEFAULT}),u("Exiting command line",null))},{intent:x.GetLastCommandFromHistory,mode:h.COMMAND_LINE,action:()=>(bc(),u("Getting last command from history",null))},{intent:x.GetNextCommandFromHistory,mode:h.COMMAND_LINE,action:()=>(Ic(),u("Getting next command from history",null))}];import Ol from"chalk";var es=Ol.dim.hex(y.secondary2)(": for command line"),Fl="q to exit",Ul=`${Ol.hex(y.accent)("m")} to confirm`,Di={[D.WORKSPACE]:[es],[D.BOARD]:[es],[D.BOARD+h.COMMAND_LINE]:[es],[D.SWIMLANE]:[es],[D.TICKET+h.HELP]:[Fl],[D.SWIMLANE+h.HELP]:[Fl],[D.TICKET]:[],[D.FIELD]:[],[D.SWIMLANE+h.MOVE]:[Ul],[D.TICKET+h.MOVE]:[Ul]};var Ar=e=>e.trim().toLocaleLowerCase(),Qv=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Zv=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?St(n,r.name):void 0}).filter(n=>!!n)},_l=(e,t)=>{let n=Ar(t.value);if(!n)return!0;switch(t.target){case"title":return Ar(e.title??"").includes(n);case"description":return Ar(e.props.description??"").includes(n);case"tag":return Qv(e).map(Ar).some(o=>o.includes(n));case"assignee":return Zv(e).map(Ar).some(o=>o.includes(n));case"ref":return id(e.id,t.value);default:return!0}};function $l(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(),u("Breadcrumb built",o))}var Hl=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 Ut,Bi,Fi=new Set,Ui=()=>{for(let e of Fi)e()},th=e=>(Fi.add(e),()=>Fi.delete(e));function Oi(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 l=$l(t,o,r);if(d(l))return logger.error(l.message),l;let m=l.value,{context:p}=c,f=Di[p+n]??Di[p]??[],g=[...kl,...Al[p]??[],...Bl],E=Hl(g),I=nh(o,s),N=I[t]?.[e.selectedIndex]??null;return u("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:f,availableActions:g,actionIndex:E,selectedNode:N,renderedChildrenIndex:I})}var v=()=>{if(!Ut)throw new Error("State not initialized. Call initWorkspaceState() first.");return Ut},Ge=()=>Ut?u("Retrieved state",Ut):a("State not initialized. Call initWorkspaceState() first.");function dr(e){Bi=e;let t=He(process.cwd()),n=!1;if(!d(t)){let s=mt(t.value);if(d(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:h.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:{},attachments:{}},o=Oi(r);return d(o)?o:(Ut=o.value,Ui(),u("State initialized",null))}var Tr=!1,ts=null;function pe(e){let t=v(),n=e(t);if(Tr)return ts=n,Ut={...t,...n},u("State updated",null);let r=Oi(n);return d(r)?a(r.message??"Unable to update state"):(Ut=r.value,Ui(),u("State updated",null))}function bd(e){if(Tr)return u("Joined batch",e());Tr=!0,ts=null;let t=()=>{let n=ts;if(Tr=!1,ts=null,n===null)return null;let r=Oi(n);return d(r)?a(r.message??"Unable to update state"):(Ut=r.value,Ui(),u("State updated",null))};try{let n=e(),r=t();return r&&d(r)?a(r.message):u("State updated",n)}finally{Tr&&t()}}var C=e=>pe(t=>({...t,...e}));var j=()=>eh(th,v,v),nh=(e,t)=>{let n={};for(let r of Object.values(e))T(r)&&t.length>0&&!t.every(o=>_l(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},z=e=>v()?.renderedChildrenIndex[e]??[],at=()=>Bi?dr(Bi):a("Cannot reset state: no initial workspace found"),zt=()=>Ut!==void 0;var _i=e=>{zt()&&(C({syncStatus:e}),Ht({type:"sync-status",payload:e}))},ns=(e="Syncing...")=>{_i({status:"syncing",msg:e})},rs=(e="Synced")=>{_i({status:"synced",msg:e})},$i=e=>{_i({status:"failed",msg:e})},et=e=>($i(e),a(e));import{decodeTime as qD}from"ulid";var rh=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=J("getRepoRootDir",await vt(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=J("getStateBranchRoot",Re({repoRoot:r}));if(d(o))return a(o.message);let s=o.value;logger.debug("[sync] state branch root",s);let i=J("ensureInitialCommit",await Ha(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=J("bootstrapStateBranchStorage",await Ga({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 l=J("hasInProgressGitOperation(stateBranchRoot)",await Gr(s));if(d(l))return a(l.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:l.value}),l.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=J("ensureStateBranchLayout",Ta(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}),u("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}))},oh=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=J("stageStateBranchOwnEventFile",await eo({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=J("stageStateBranchMediaFiles",await Wa({stateBranchRoot:t}));if(d(o))return a(o.message);let s=J("hasStagedChanges(after stage)",await Ia(t));if(d(s))return a(s.message);if(logger.debug("[sync] state branch change check after stage result",{changed:s.value}),!s.value)return logger.info("[sync] no own event file changes to commit"),u("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let i=J("createStateBranchSyncCommit",await ja({repoRoot:e,stateBranchRoot:t}));return d(i)?a(i.message):(logger.debug("[sync] created sync commit",i.value),u("Committed own event file",{createdCommit:!0,commitSha:i.value}))},Io=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");ns();let n=J("ensureSyncReady",await rh({cwd:e,ensureUpstream:!0}));if(d(n))return et(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=J("isDetachedHead(stateBranchRoot)",await Ea(o));if(d(i))return et(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return et("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,l,m=!1,p=!1,f=J("getStateBranch",Nn(r));if(d(f))return et(f.message);let g=f.value;logger.debug("[sync] resolved state branch",{stateBranch:g,stateBranchRoot:o});let E=J("commitOwnEventFileToStateBranch",await oh({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(E))return et(E.message);c=E.value.createdCommit,l=E.value.commitSha;let I=J("pullBranchRebaseIfPresent",await Fs({cwd:o,branch:g}));if(d(I))return et(I.message);if(m=I.value,c||s){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:o});let N=J("pushStateBranch",await or({stateBranchRoot:o,repoRoot:r}));if(d(N)&&ba(N.message)){let A=J("pullBranchRebaseIfPresent(retry)",await Fs({cwd:o,branch:g}));if(d(A))return et(A.message);m=m||A.value,N=J("pushStateBranch(retry)",await or({stateBranchRoot:o,repoRoot:r}))}if(d(N))return et(N.message);p=N.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let N=J("git rev-parse HEAD",await U({args:["rev-parse","HEAD"],cwd:o}));if(d(N))return et(N.message);l=N.value.stdout.trim(),logger.debug("[sync] final sync commit sha",l)}return rs(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),u("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:l,pulled:m,pushed:p,bootstrapped:s})};import{existsSync as Hi}from"node:fs";import{chmod as Wi}from"node:fs/promises";import ql from"node:os";import $n from"node:path";var Wl=(e,t)=>e.reduce((n,r)=>r<n?r:n,t);var jl=1e5,sh=2e4,os=null,Gl=Promise.resolve(),rn=e=>{let t=Gl.then(e,e);return Gl=t.then(()=>{},()=>{}),t},ji=e=>{let t=He(e??process.cwd());return d(t)?a(t.message):u("Resolved Epiq repo root",t.value)},Gi=e=>{let t=ji(e);return d(t)?t:Re({repoRoot:t.value})},dt=()=>{if(!zt())return{mode:"live",asOfTime:null};let{timeMode:e}=v();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:os}},ih=e=>{let t=new Map;for(let n of e){if(n.action!=="create.tag"&&n.action!=="create.contributor")continue;let r=n.payload;r?.id&&r.name&&t.set(r.id,r.name)}return t},ah=(e,t)=>{let n=e.payload,r=n?.tag!==void 0?t.get(n.tag)??"":n?.assignee!==void 0?t.get(n.assignee)??"":n?.name!==void 0?`"${n.name}"`:"";return[e.action?uo(e.action):"",r].filter(Boolean).join(" ")},Vl=(e,t)=>{if(!e)return null;let n=t.get(e)??e;return{id:e,name:n,color:te(n)}},dh=(e,t)=>{let n=e.payload;return{actor:e.userId?{id:e.userId,name:e.userName??e.userId,color:te(e.userName??e.userId)}:null,tag:Vl(n?.tag,t),assignee:Vl(n?.assignee,t)}},Vi=(e,t)=>{let n=new Map,r=new Set,o=i=>{let c=new Set,l=i;for(;l&&!c.has(l);){if(r.has(l))return l;c.add(l),l=n.get(l)}return null},s=[];for(let i of e){let c=i.payload,l=c?.id;if(!l)continue;i.action==="add.board"&&r.add(l);let m=c.parent??c.issue;m&&n.set(l,m),(l===t||o(l)===t)&&s.push(i)}return s},Yl=async(e={})=>{let t=Gi(e.repoRoot);if(d(t))return a(t.message);let n=je(t.value);if(d(n))return a(n.message);let r=e.boardId?Vi(n.value,e.boardId):n.value,o=ih(n.value),s=r.flatMap(I=>{let N=Jt(I);return N===null?[]:[{t:N,action:I.action,label:ah(I,o),...dh(I,o)}]}),i=Date.now(),c=e.end??i,l=e.start??Wl(s.map(I=>I.t),c);if(c<=l)return u("Empty time window",{bucketMs:0,buckets:[],events:[],earliest:l,latest:c});let m=s.filter(I=>I.t>=l&&I.t<c).sort((I,N)=>I.t-N.t),p=m.map(I=>I.t),f=Math.max(1,Math.ceil((c-l)/jl)),g=new Map;for(let I of p){let N=Math.min(jl-1,Math.floor((I-l)/f)),A=l+N*f;g.set(A,(g.get(A)??0)+1)}let E=[...g.entries()].sort(([I],[N])=>I-N).map(([I,N])=>({t:I,count:N}));return u("Computed event timeline",{bucketMs:f,buckets:E,events:m.length>sh?[]:m,earliest:l,latest:c})},wr="",Kl="",Xl=async(e={})=>{let t=ji(e.repoRoot);if(d(t))return a(t.message);let n=mt(t.value);if(d(n))return a(n.message);let r=await U({cwd:t.value,args:["log","--branches","--not",n.value.stateBranch,...e.start!==void 0?[`--since=@${Math.floor(e.start/1e3)}`]:[],...e.end!==void 0?[`--until=@${Math.floor(e.end/1e3)}`]:[],"--shortstat",`--format=${Kl}%H${wr}%at${wr}%an${wr}%s`]});if(d(r))return a(r.message);let o=r.value.stdout.split(Kl).filter(s=>s.trim().length>0).map(s=>{let[i,...c]=s.split(`
59
+ `),[l,m,p,...f]=(i??"").split(wr);if(!l||!m)return null;let g=c.join(" "),E=Number(/(\d+) insertion/.exec(g)?.[1]??0),I=Number(/(\d+) deletion/.exec(g)?.[1]??0);return{sha:l,time:Number(m)*1e3,author:p??"unknown",subject:f.join(wr),linesChanged:E+I}}).filter(s=>s!==null);return u("Computed commit timeline",o)},ch=e=>/^[0-9a-f]{7,40}$/i.test(e),lh=async(e,t)=>{let n=await U({cwd:e,args:["show",t]});if(d(n))return a(n.message);let r=$n.join(ql.tmpdir(),"epiq","commit-diffs");be.mkDir(r);let o=$n.join(r,`${t}.diff`);return Hi(o)||(be.writeToFile(o,n.value.stdout),await Wi(o,292)),nl(o)},uh=12,mh=800,zl=async(e,t,n)=>{let r=await U({cwd:e,args:["show",`${t}:${n}`]});return d(r)?"":r.value.stdout},ph=async(e,t,n)=>{let r=await U({cwd:e,args:["diff-tree","--no-commit-id","--name-only","-r",t]});if(d(r))return a(r.message);let o=r.value.stdout.split(`
60
+ `).map(f=>f.trim()).filter(Boolean);if(o.length===0)return a("No changed files found for this commit");if(o.length>uh)return a(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=$n.join(ql.tmpdir(),"epiq","commit-diffs",t),i=await Promise.all(o.map(async(f,g)=>{let[E,I]=await Promise.all([zl(e,`${t}~1`,f),zl(e,t,f)]),N=$n.basename(f),A=$n.join(s,String(g),"before",N),P=$n.join(s,String(g),"after",N);return Hi(A)||(be.writeToFile(A,E),await Wi(A,292)),Hi(P)||(be.writeToFile(P,I),await Wi(P,292)),{beforePath:A,afterPath:P}})),[c,...l]=i;if(!c)return a("No changed files found for this commit");let m=await Ti(n,c.beforePath,c.afterPath,"new");if(d(m)||l.length===0)return m;await new Promise(f=>setTimeout(f,mh));let p=await Promise.all(l.map(({beforePath:f,afterPath:g})=>Ti(n,f,g,"reuse")));for(let f of p)d(f)&&logger.error(`Failed to open an additional diff tab for ${t}: ${f.message}`);return m},Jl=async e=>{if(!ch(e.sha))return a("Invalid commit sha");let t=ji(e.repoRoot);if(d(t))return a(t.message);let n=t.value,r=Go()[0];if(r&&Ai(r)){let o=await ph(n,e.sha,r);if(!d(o))return o;logger.error(`Side-by-side diff failed for ${e.sha}, falling back to unified diff: ${o.message}`)}return lh(n,e.sha)},Ql=e=>{let t=je(e);if(d(t))return a(t.message);let n=at();if(d(n))return a(n.message);os=null;let o=it(t.value).filter(d);return o.length>0?a(o.map(s=>s.message).join(", ")):(C({readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),u("Restored live state",!0))},fh=(e,t)=>{os=null;let n=Ql(e);return d(n)?a(`${t} (recovery to live also failed: ${n.message})`):a(t)},Zl=e=>rn(async()=>{let t=Gi(e.repoRoot);if(d(t))return a(t.message);let n=go(t.value,e.targetTime);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=n.value,s=at();if(d(s))return s;let c=it(r).filter(d);return c.length>0?fh(t.value,c.map(l=>l.message).join(", ")):(C({readOnly:!0,timeMode:"peek",unappliedEvents:o,replay:null}),os=e.targetTime,u("Checked out historical state",{asOfTime:e.targetTime}))}),eu=(e={})=>rn(async()=>{let t=Gi(e.repoRoot);if(d(t))return a(t.message);let n=Ql(t.value);return d(n)?a(n.message):u("Returned to live state",!0)});var Ki=()=>{let e=$t();return d(e)?bt:e.value.attachmentMaxKb??bt},zi=e=>{let t=He(e??process.cwd());return d(t)?a(t.message):u("Resolved Epiq repo root",t.value)},Ne=async(e,t)=>{let n=zi(e);if(d(n))return n;let r=Re({repoRoot:n.value});if(d(r))return a(r.message);let o=Cn(),s=await mn({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.stateBranch});if(d(s))return a(s.message);if(t?.pull??!1){let l=await U({cwd:r.value,args:["pull","--ff-only"]});d(l)&&le.info(3,l.message)}let i=je(r.value);if(d(i))return a(i.message);let c=gn(i.value);return d(c)?a(c.message):u("Booted Epiq state",{repoRoot:n.value,stateBranchRoot:r.value})},Ae=()=>{let e=$t();return d(e)?a(e.message):e.value.userId?e.value.userName?u("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},Fe=()=>{let e=Ge();return d(e)?a(e.message):e},nu=e=>(e.props.tags??[]).map(t=>S.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:te(t.name)})),qi=()=>{let e=Ge(),t=d(e)?[]:e.value.eventLog??[],n=new Map;for(let r of t)r.userId&&r.userName&&n.set(r.userId,r.userName);return n},ru=(e,t)=>{let n=new Map(e);for(let r of Object.values(t)){if(r.tombstoned){n.set(r.id,r.name);continue}n.set(r.id,Fn(r.name,n.get(r.id))??r.name)}return n},ou=(e,t=new Map)=>(e.props.assignees??[]).map(n=>S.getContributor(n)).filter(n=>n!=null).map(n=>{let r=n.tombstoned?n.name:Fn(n.name,t.get(n.id))??n.name;return{id:n.id,name:r,color:te(r)}});var su=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Fe();if(d(n))return n;let r=n.value.nodes,o=qi(),s=Object.values(r).filter(T).filter(i=>!i.isDeleted).filter(i=>e.includeClosed||i.parentNodeId!==ve).filter(i=>e.boardId?(i.parentNodeId?r[i.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).map(i=>({id:i.id,ref:We(i.id),title:Ze(i.title),description:i.props.description??"",parentNodeId:i.parentNodeId,isClosed:i.parentNodeId===ve,readonly:!!i.readonly,tags:nu(i),assignees:ou(i,o)}));return u("Listed issues",s)},iu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=Ln(e.parentId,n.value,t.value.stateBranchRoot);if(d(o))return o;let s=Ko({name:e.title,parent:e.parentId,user:n.value,rank:o.value});if(d(s))return s;let i=[...s.value],c=i.find(f=>f.action==="add.issue")?.payload.id;if(!c)return a("Unable to determine created issue id");e.description&&i.push({id:q(),...n.value,action:"edit.description",payload:{id:c,md:e.description}});let l=[];for(let f of e.tagNames??[]){let g=Ze(f).trim();if(!g||l.some(N=>N.name===g))continue;let E=Object.values(r.value.tags).find(N=>N.name===g),I=E?.id??q();E||i.push({id:q(),...n.value,action:"create.tag",payload:{id:I,name:g}}),i.push({id:q(),...n.value,action:"add.issue.tag",payload:{id:c,tag:I}}),l.push({id:I,name:g})}let m=[];for(let f of e.assigneeNames??[]){let g=Ze(f).trim();if(!g||m.some(N=>N.name===g))continue;let E=Object.values(r.value.contributors).find(N=>N.name===g),I=E?.id??q();E||i.push({id:q(),...n.value,action:"create.contributor",payload:{id:I,name:g}}),i.push({id:q(),...n.value,action:"add.issue.assignee",payload:{id:c,assignee:I}}),m.push({id:I,name:g})}let p=O(i,t.value.stateBranchRoot);return d(p)?a(p.message):u("Created issue",{id:c,title:e.title,parentId:e.parentId,description:e.description??"",tags:l,assignees:m})},au=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=fn(ve,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(d(r))return r;let o={id:q(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ve,rank:r.value}},s=O([o],t.value.stateBranchRoot);return d(s)?a(s.message):u("Closed issue",{id:e.issueId})},du=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Target node is not issue");if(o.parentNodeId!==ve)return a("Issue is not closed");let s=Wo(o);if(!s)return a("Unable to resolve previous parent from issue history");if(s===ve)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=fn(i.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(c))return c;let l={id:q(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:i.id,rank:c.value}},m=O([l],t.value.stateBranchRoot);return d(m)?a(m.message):u("Reopened issue",{id:o.id,parentId:i.id})},cu=async e=>{let t=zi(e.repoRoot);if(d(t))return t;let n=Ae();if(d(n))return n;let r=Re({repoRoot:t.value});if(d(r))return r;let o=je(r.value);if(d(o))return o;let s=gn(o.value);if(d(s))return s;let i=fn(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(d(i))return i;let c={id:q(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:i.value}},l=O([c],r.value);return d(l)?a(l.message):u("Moved issue",{id:e.issueId,parentId:e.parentId})};var ss=async(e={})=>{ns();let t=zi(e.repoRoot);if(d(t))return a("Sync failed");let n=Ae();if(d(n))return n;let r=await Io({cwd:t.value,ownEventFileName:pn(n.value)});return d(r)?($i(r.message),r):(rs(),u("Synced",r.value))};var Hn=()=>{let e=Fe();if(d(e))return e;let t=dt(),n=t.mode!=="live",r=Object.values(e.value.nodes),o=r.filter(g=>no(g)&&!g.isDeleted),s=qi(),i=new Map,c=new Map;for(let g of r)if(!g.isDeleted){if(jt(g)&&g.parentNodeId){let E=i.get(g.parentNodeId)??[];E.push(g),i.set(g.parentNodeId,E)}if(T(g)&&g.parentNodeId){let E=c.get(g.parentNodeId)??[];E.push(g),c.set(g.parentNodeId,E)}}let l=$t();if(d(l))return l;let m={};for(let g of r.filter(T))g.isDeleted||(m[g.id]=S.getCommentsByIssue(g.id).map(E=>{let I=S.getContributor(E.authorId);return{id:E.id,issueId:E.issue,body:E.md,author:{id:E.authorId,name:I?.name??"Unknown",color:te(I?.name??E.authorId)},createdAt:tu(E.id)}}));let p=new Map;for(let g of e.value.eventLog)g.action==="add.issue.attachment"&&p.set(g.payload.id,g.payload.author);let f={};for(let g of r.filter(T))g.isDeleted||(f[g.id]=S.getAttachmentsByIssue(g.id).map(E=>({id:E.id,issueId:E.issue,name:E.name,fileName:Dn(E.hash,E.ext),bytes:E.bytes,createdAt:tu(E.id),canDelete:p.get(E.id)===l.value.userId})));return u("Retrieved Epiq GUI state",{boards:o.sort((g,E)=>g.rank.localeCompare(E.rank)).map(g=>({id:g.id,ref:We(g.id),title:g.title,swimlanes:(i.get(g.id)??[]).sort((E,I)=>E.rank.localeCompare(I.rank)).map(E=>({id:E.id,title:E.title,readonly:!!E.readonly||n,issues:(c.get(E.id)??[]).sort((I,N)=>I.rank.localeCompare(N.rank)).map(I=>({id:I.id,ref:We(I.id),title:Ze(I.title),description:I.props.description??"",readonly:!!I.readonly||n,tags:nu(I),assignees:ou(I,s),parentNodeId:I.parentNodeId,isClosed:I.parentNodeId===ve})),parentNodeId:E.parentNodeId}))})),tags:Object.values(e.value.tags).map(g=>({...g,color:te(g.name)})),contributors:Object.values(e.value.contributors).map(g=>({...g,color:te(g.name)})),user:{name:l.value.userName??"",id:l.value.userId??"",color:te(l.value.userName??"")},commentsByIssueId:m,attachmentsByIssueId:f,attachmentMaxKb:Ki(),timeTravel:t})},ct=async(e={})=>{if(dt().mode!=="live")return Hn();let t=await Ne(e.repoRoot,{pull:!1});return d(t)?t:Hn()},lu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(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 u("No changes made",{id:e.issueId,description:s});let i={id:q(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=O([i],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited issue description",{id:e.issueId,description:e.description})},uu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=Ze(e.title);if(!s.trim())return a("Issue title cannot be empty");if(o.title===s)return u("No changes made",{id:e.issueId,title:s});let i={id:q(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=O([i],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited issue title",{id:e.issueId,title:s})},mu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Tag target must be an issue");if(o.readonly)return a("Cannot tag readonly issue");let s=Ze(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??q(),l=[...i?[]:[{id:q(),...n.value,action:"create.tag",payload:{id:c,name:s}}],{id:q(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:c}}],m=O(l,t.value.stateBranchRoot);return d(m)?a(m.message):u("Added issue tag",{id:e.issueId,tag:{id:c,name:s}})},pu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(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:q(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=O([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Removed issue tag",{id:e.issueId,tagId:e.tagId})},fu=async(e,t)=>{let n=je(e);if(d(n))return;let r;for(let o of n.value)o.userId===t&&(r=o.userName??r);return r===void 0?void 0:{id:t,name:r}},gu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Assign target must be an issue");if(o.readonly)return a("Cannot assign readonly issue");let s=e.self?n.value.userId:e.assigneeId;if(s){let N=r.value.contributors[s],A=N?void 0:await fu(t.value.stateBranchRoot,s);if(!N&&!A)return a("Unknown assignee id");let P=N??A,F=[...N?[]:[{id:q(),...n.value,action:"create.contributor",payload:{id:P.id,name:P.name}}],{id:q(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:P.id}}],H=O(F,t.value.stateBranchRoot);return d(H)?a(H.message):u("Added issue assignee",{id:e.issueId,assignee:{id:P.id,name:P.name}})}let i=Ze(e.assigneeName??"").trim();if(!i)return a("Provide assigneeId, self or assigneeName");let l=[...ru(qi(),r.value.contributors).entries()].filter(([,N])=>N===i);if(l.length>1)return a(`"${i}" matches ${l.length} contributors (${l.map(([N])=>N).join(", ")}). Assign by assigneeId to choose.`);let m=l[0];if(!m&&!e.createUnlinked)return a(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[p=q(),f=i]=m??[],E=[...!!r.value.contributors[p]?[]:[{id:q(),...n.value,action:"create.contributor",payload:{id:p,name:f}}],{id:q(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:p}}],I=O(E,t.value.stateBranchRoot);return d(I)?a(I.message):u("Added issue assignee",{id:e.issueId,assignee:{id:p,name:f}})},vu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;if(!r.value.contributors[e.contributorId])return a("Contributor not found");if(await fu(t.value.stateBranchRoot,e.contributorId))return a("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let i=[{id:q(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],c=O(i,t.value.stateBranchRoot);return d(c)?a(c.message):u("Tombstoned contributor",{id:e.contributorId,name:oo})};var hu=async(e={})=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=je(t.value.stateBranchRoot);if(d(o))return a(o.message);let s=e.boardId?Vi(o.value,e.boardId):o.value,i=new Map,c=new Set,l=new Set;for(let g of o.value)g.userId&&l.add(g.userId);for(let g of s)g.userId&&(i.set(g.userId,g.userName??""),c.add(g.userId));let m=r.value.contributors,f=[...ru(i,m).entries()].map(([g,E])=>({id:g,name:E,color:te(E),isSelf:g===n.value.userId,isExternal:!c.has(g),isRemoved:m[g]?.tombstoned===!0,hasAuthoredAnywhere:l.has(g)}));return u("Listed board contributors",f)},yu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(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:q(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=O([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},is=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(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");if(s.length>4e3)return a(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i=q(),c={id:q(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},l=O([c],t.value.stateBranchRoot);return d(l)?a(l.message):u("Added issue comment",{id:i,issueId:e.issueId,body:s})},as=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();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(!T(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 u("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:q(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},l=O([c],t.value.stateBranchRoot);return d(l)?a(l.message):u("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},xu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!T(o))return a("Attachment target must be an issue");if(o.readonly)return a("Cannot attach to readonly issue");let s=Buffer.from(e.dataBase64??"","base64"),i=tc(t.value.stateBranchRoot,s,Ki());if(d(i))return i;let c=Ze(e.name??"").trim()||"image",l=q(),m={id:q(),...n.value,action:"add.issue.attachment",payload:{id:l,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:c,bytes:i.value.bytes}},p=O([m],t.value.stateBranchRoot);return d(p)?a(p.message):u("Added issue attachment",{id:l,issueId:e.issueId,fileName:Dn(i.value.hash,i.value.ext),bytes:i.value.bytes})},bu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Ae();if(d(n))return n;let r=Fe();if(d(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.attachment"&&m.payload.id===e.attachmentId);if(!o)return a("Unable to resolve attachment");if(o.payload.author!==n.value.userId)return a("You can only delete your own attachments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!T(s))return a("Attachment target must be an issue");if(s.readonly)return a("Cannot delete attachment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.attachment"&&m.payload.id===e.attachmentId))return u("Attachment already deleted",{id:e.attachmentId,issueId:o.payload.issue});let c={id:q(),...n.value,action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:o.payload.issue}},l=O([c],t.value.stateBranchRoot);return d(l)?a(l.message):u("Deleted issue attachment",{id:e.attachmentId,issueId:o.payload.issue})},Iu=async e=>{let t=await Ne(e.repoRoot,{pull:!1});return d(t)?t:nc(t.value.stateBranchRoot,e.fileName,Ki())};var gh=15e3,Eu=e=>{let t,n=!1,r=!1,o=0,s=()=>{let p=Qr();return d(p)?(le.error(p.message),null):p.value},i=()=>{let p=s();if(!p)return!1;let{autoSync:f,userName:g,preferredEditor:E}=p;return!!(f&&g&&E)},c=()=>{let p=s()?.autoSyncDebounceMs??gh;return Math.max(0,p-(Date.now()-o))},l=async()=>{if(!(n||r)){r=!0,o=Date.now();try{await rn(async()=>{if(dt().mode!=="live")return;let p=await ss({repoRoot:e.repoRoot});if(d(p))return;let{pulled:f,createdCommit:g,bootstrapped:E}=p.value;!f&&!g&&!E||Ht({type:"state",payload:await ct({repoRoot:e.repoRoot})})})}finally{r=!1,m()}}};function m(){n||!i()||r||t||(t=setTimeout(()=>{t=void 0,l()},c()))}return m(),{queueSync:m,dispose:()=>{n=!0,t&&clearTimeout(t)}}};import{WebSocketServer as hh}from"ws";var Su=new Set(["sync","issues:create","issues:move","issue:close","issue:reopen","issue:edit:title","issue:edit:description","issue:tag:add","issue:tag:remove","contributor:remove","issue:assignee:add","issue:assignee:remove","issue:comment:add","issue:comment:delete"]);var vh=e=>({...e,boards:(e.boards??[]).map(t=>({...t,swimlanes:(t.swimlanes??[]).map(n=>({...n,issues:(n.issues??[]).map(r=>({...r,description:""}))}))})),commentsByIssueId:Object.fromEntries(Object.entries(e.commentsByIssueId??{}).filter(([,t])=>t.length>0).map(([t,n])=>[t,n.map(r=>({...r,body:""}))])),attachmentsByIssueId:Object.fromEntries(Object.entries(e.attachmentsByIssueId??{}).filter(([,t])=>t.length>0))}),Mr=e=>d(e)?e:u(e.message,vh(e.value)),Cu=(e,t)=>{let n=(e.boards??[]).flatMap(r=>r.swimlanes??[]).flatMap(r=>r.issues??[]).find(r=>r.id===t);return{issueId:t,description:n?.description??"",comments:e.commentsByIssueId?.[t]??[]}};var Nu=()=>{Ht({type:"state",payload:Mr(Hn())})},ie=(e,t)=>{e.send(JSON.stringify(t))},ds=async(e,t)=>ie(e,{type:"state",payload:Mr(await ct({repoRoot:t}))}),yh=async(e,t)=>{let n=()=>ie(e,{type:"state",payload:Mr(Hn())});if(dt().mode!=="live")return n();let r=await ct({repoRoot:t});return dt().mode!=="live"?n():ie(e,{type:"state",payload:Mr(r)})},lt=async(e,t,n,r,o)=>{if(ie(e,{type:r,payload:o}),d(o))return ie(e,{type:"failed",payload:o.message});n(),yh(e,t)},Ru=(e,t,{onStateChanged:n})=>{new hh({server:e,path:"/ws"}).on("connection",o=>{Va(o),o.on("message",async s=>{let i=async c=>{let{type:l}=c;if(l==="timeline:get"){let{requestId:m,...p}=c.payload??{};return ie(o,{type:"timeline",requestId:m,payload:await Yl({repoRoot:t,...p})})}if(l==="issue:get"){let m=c.payload?.issueId,p=Hn();return ie(o,{type:"issue",payload:d(p)?p:u("Issue detail",Cu(p.value,m))})}if(l==="commits:get"){let{requestId:m,...p}=c.payload??{};return ie(o,{type:"commits",requestId:m,payload:await Xl({repoRoot:t,...p})})}if(l==="commit:inspect")return ie(o,{type:"commit:inspect:result",payload:await Jl({repoRoot:t,sha:c.payload.sha})});if(l==="time-travel:scrub"){let m=await Zl({repoRoot:t,targetTime:c.payload.targetTime});return ie(o,{type:"time-travel:result",payload:m}),d(m)?void 0:Nu()}if(l==="time-travel:live"){let m=await eu({repoRoot:t});return ie(o,{type:"time-travel:result",payload:m}),d(m)?void 0:Nu()}if(l==="state:get")return ds(o,t);if(l==="sync"){let m=await ss({repoRoot:t});return ie(o,{type:"sync:result",payload:m}),n(),ds(o,t)}if(l==="issue:comment:add"){let m=await is({repoRoot:t,...c.payload});return lt(o,t,n,"issue:comment:add:result",m)}if(l==="issue:comment:delete"){let m=await as({repoRoot:t,...c.payload});return ie(o,{type:"issue:comment:delete:result",payload:m}),d(m)?ie(o,{type:"failed",payload:m.message}):(n(),ds(o,t))}if(l==="issue:edit:description"){let m=await lu({repoRoot:t,...c.payload});return lt(o,t,n,"issue:edit:description:result",m)}if(l==="issue:edit:title"){let m=await uu({repoRoot:t,...c.payload});return lt(o,t,n,"issue:edit:title:result",m)}if(l==="issue:tag:add"){let m=await mu({repoRoot:t,...c.payload});return lt(o,t,n,"issue:tag:add:result",m)}if(l==="issue:tag:remove"){let m=await pu({repoRoot:t,...c.payload});return lt(o,t,n,"issue:tag:remove:result",m)}if(l==="contributor:remove"){let m=await vu({repoRoot:t,...c.payload});return lt(o,t,n,"contributor:remove:result",m)}if(l==="contributors:get")return ie(o,{type:"contributors",payload:await hu({repoRoot:t,...c.payload})});if(l==="issue:assignee:add"){let m=await gu({repoRoot:t,...c.payload});return lt(o,t,n,"issue:assignee:add:result",m)}if(l==="issue:assignee:remove"){let m=await yu({repoRoot:t,...c.payload});return lt(o,t,n,"issue:assignee:remove:result",m)}if(l==="issues:list")return ie(o,{type:"issues",payload:await su({repoRoot:t})});if(l==="issues:create"){let m=await iu({...c.payload,repoRoot:t});return ie(o,{type:"issues:create:result",payload:m}),d(m)?Ht({type:"failed",payload:m.message}):(Ht({type:"issue:created",payload:m.value}),n(),ds(o,t))}if(l==="issues:move"){if(!c.payload.position)return ie(o,{type:"error",message:"Missing move position"});let m=await cu({...c.payload,repoRoot:t});return lt(o,t,n,"issues:move:result",m)}if(l==="issue:close"){if(!c.payload.issueId)return ie(o,{type:"error",message:"Missing issueId"});let m=await au({repoRoot:t,issueId:c.payload.issueId});return lt(o,t,n,"issue:close:result",m)}if(l==="issue:reopen"){if(!c.payload.issueId)return ie(o,{type:"error",message:"Missing issueId"});let m=await du({repoRoot:t,issueId:c.payload.issueId});return lt(o,t,n,"issue:reopen:result",m)}return ie(o,{type:"error",message:"Unknown message type"})};try{let c=JSON.parse(s.toString());return Su.has(c.type)?await rn(async()=>dt().mode!=="live"?ie(o,{type:"failed",payload:"Read-only while viewing history"}):i(c)):await i(c)}catch(c){return ie(o,{type:"error",message:c instanceof Error?c.message:String(c)})}})})};var Ih=Sn.dirname(bh(import.meta.url)),Eh=process.env.IS_LOCAL==="true"?Sn.resolve(process.cwd(),"dist/gui"):Sn.join(Ih,"gui"),cs,Sh=async()=>(cs===void 0&&(cs=await import("node:sea").catch(()=>null)),cs?.isSea()?cs:null),fe=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},Ch=e=>fe(e,409,{isError:!0,message:"Read-only while viewing history"}),ls=(e,t)=>rn(async()=>dt().mode!=="live"?Ch(e):t()),Au=async(e,t=1024*1024)=>new Promise((n,r)=>{let o="",s=0;e.on("data",i=>{if(s+=i.length,s>t){e.destroy(),r(new Error("Request body too large"));return}o+=i}),e.on("end",()=>{try{n(o?JSON.parse(o):{})}catch{r(new Error("Invalid JSON body"))}}),e.on("error",r)}),Nh=2*1024*1024,Rh={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},Ah=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",Tu=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=Sn.resolve(Eh),o=Sn.resolve(r,n),s=Sn.relative(r,o);if(s.startsWith("..")||Sn.isAbsolute(s))return fe(t,403,{isError:!0,message:"Forbidden"});let i=await Sh();try{let c=i?Buffer.from(i.getAsset(`gui/${s}`)):await wu(o);return t.writeHead(200,{"content-type":Ah(o)}),t.end(c)}catch{return fe(t,404,{isError:!0,message:`Not found: ${n}`})}},Th=async(e,t=3710)=>new Promise((n,r)=>{let o=s=>{let i=l=>{if(e.off("listening",c),l.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(l)},c=()=>{e.off("error",i);let l=e.address();if(!l||typeof l=="string"){r(new Error("Unable to resolve address"));return}n(l.port)};e.once("error",i),e.once("listening",c),e.listen(s,"127.0.0.1")};o(t)}),Mu=async e=>{let t=xh.createServer(async(o,s)=>{let i=new URL(o.url??"/","http://127.0.0.1");if(i.pathname==="/api/state")return fe(s,200,await ct({repoRoot:e.repoRoot}));if(o.method==="POST"&&i.pathname==="/api/comments")try{let c=await Au(o);if(!c.issueId||!c.body?.trim())return fe(s,400,{isError:!0,message:"Missing issueId or body"});let l=c.issueId,m=c.body;return await ls(s,async()=>{let p=await is({repoRoot:e.repoRoot,issueId:l,body:m});return d(p)?fe(s,400,{isError:!0,message:p.message}):fe(s,200,await ct({repoRoot:e.repoRoot}))})}catch(c){return fe(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add comment"})}if(o.method==="POST"&&i.pathname==="/api/attachments")try{let c=await Au(o,Nh);if(!c.issueId||!c.dataBase64)return fe(s,400,{isError:!0,message:"Missing issueId or dataBase64"});let l=c.issueId,m=c.dataBase64,p=c.name??"";return await ls(s,async()=>{let f=await xu({repoRoot:e.repoRoot,issueId:l,name:p,dataBase64:m});return d(f)?fe(s,400,{isError:!0,message:f.message}):fe(s,200,await ct({repoRoot:e.repoRoot}))})}catch(c){return fe(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add attachment"})}if(o.method==="DELETE"&&i.pathname.startsWith("/api/attachments/")){let c=decodeURIComponent(i.pathname.replace("/api/attachments/",""));return c?ls(s,async()=>{let l=await bu({repoRoot:e.repoRoot,attachmentId:c});return d(l)?fe(s,400,{isError:!0,message:l.message}):fe(s,200,await ct({repoRoot:e.repoRoot}))}):fe(s,400,{isError:!0,message:"Missing attachment id"})}if(o.method==="GET"&&i.pathname.startsWith("/media/")){let c=decodeURIComponent(i.pathname.replace("/media/","")),l=await Iu({repoRoot:e.repoRoot,fileName:c});if(d(l))return fe(s,404,{isError:!0,message:l.message});try{let m=await wu(l.value.filePath);return s.writeHead(200,{"content-type":Rh[l.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),s.end(m)}catch{return fe(s,404,{isError:!0,message:"Attachment blob not found"})}}if(o.method==="DELETE"&&i.pathname.startsWith("/api/comments/")){let c=decodeURIComponent(i.pathname.replace("/api/comments/",""));return c?ls(s,async()=>{let l=await as({repoRoot:e.repoRoot,commentId:c});return d(l)?fe(s,400,{isError:!0,message:l.message}):fe(s,200,await ct({repoRoot:e.repoRoot}))}):fe(s,400,{isError:!0,message:"Missing comment id"})}return i.pathname.startsWith("/board/")?Tu("/",s):Tu(i.pathname,s)});try{await Th(t)}catch(o){return a(o instanceof Error?`Unable to start GUI server: ${o.message}`:`Unable to start GUI server: ${String(o)}`)}let n=Eu({repoRoot:e.repoRoot});Ru(t,e.repoRoot,{onStateChanged:()=>n.queueSync()}),t.on("close",n.dispose);let r=t.address();return!r||typeof r=="string"?(t.close(),a("Unable to resolve GUI server address")):u("Started GUI server",{url:`http://epiq.localhost:${r.port}${e.boardId?`/board/${e.boardId}`:""}`,server:t})};var Pu=async e=>{let t=$t();Q(t)&&Me(t.value);let n=await Mu({...e,boardId:""});if(d(n))return n;let{url:r}=n.value;return console.log(`Epiq GUI running at ${wh.cyan(r)}`),_a(r),u("Started GUI",{url:r})};import{Box as cn}from"ink";import ce from"react";import{Box as Yi,Text as Pr}from"ink";import ut,{useEffect as Mh,useMemo as Ph}from"react";import{ulid as Lh}from"ulid";var Lu=({text:e,match:t,color:n,highlightColor:r=y.secondary,dimColor:o=!1})=>{if(!t)return ut.createElement(Pr,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),c=s.indexOf(i);return c===-1?ut.createElement(Pr,{color:n,dimColor:o},e):ut.createElement(Pr,{color:n,dimColor:o},e.slice(0,c),ut.createElement(Pr,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},ku=Lh(),kh=e=>`${e}`,Dh=e=>{let{pendingNavTarget:t}=en();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(de(b.NONE,{breadCrumb:n,contextNode:r,readOnly:v().readOnly,selectedNode:o}));return[...new Set(Object.values(b))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==b.PALETTE).map(i=>{let c=ko(i),l=Jo.find(m=>m.intent===c);return{command:i,description:l?.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))},Bh=e=>ee.text({id:ku,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),Fh=(e,t,n)=>ee.text({id:kh(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Xi=[],Uh=e=>{Du();let t=S.createNode(Bh(v().rootNodeId));d(t)||!Wt(t.value)||(Xi=[t.value,...e.map((n,r)=>Fh(n,r,ku)).map(S.createNode).filter(Q).map(({value:n})=>n).filter(Wt)],M.navigate({contextNode:t.value,selectedIndex:0}))},Du=()=>{let e=Xi.map(t=>t.id);Xi=[];for(let t of e)S.deleteNode(t)};function Bu({width:e,height:t}){let r=Ec().value.trim().toLowerCase(),o=Ph(()=>Dh(r),[r]);Mh(()=>(Uh(o),()=>{Du()}),[o]);let s=v().selectedIndex;return ut.createElement(Yi,{flexDirection:"column",width:e,height:t-2},ut.createElement(tt,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,c)=>{let l=c===s,m=i.isAvailable?y.accent:y.secondary2,p=i.isAvailable?"":"[unavailable] ";return ut.createElement(Yi,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},ut.createElement(Pr,{color:m,dimColor:!i.isAvailable},l?"\u276F ":" ",ut.createElement(Lu,{text:Ja(i.command),match:r,color:m,dimColor:!i.isAvailable})),ut.createElement(Yi,{paddingLeft:2},ut.createElement(Lu,{text:p+i.description,match:r.length>=2?r:"",color:l&&i.isAvailable?y.primary:y.secondary2,dimColor:!i.isAvailable})))})))}import{Box as ey}from"ink";import ps from"react";import kr from"chalk";import{Box as Ji,Text as Fu}from"ink";import Lr,{useEffect as Oh,useMemo as _h,useState as $h}from"react";var Uu=kr.hex(y.secondary),Hh=kr.inverse,Wh=kr.inverse.hex(y.secondary2),jh={hint:"",hints:[],overlap:0,remainder:""},_u=({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}},Gh=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=te(t);return{bg:r=>kr.bgHex(n).black(r),bgCursor:r=>kr.bgHex(n).inverse.black(r)}}return Qs(t)},Vh=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=_u({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}},Ou=()=>({value:Le.value,cursorPosition:Le.cursorPosition,commandIsPending:Le.commandIsPending,autoCompletion:Le.commandMeta.autoCompletion??jh,infoMessage:Le.commandMeta.infoMessage,validationStatus:Le.commandMeta.validity,command:Le.commandMeta.command,inputString:Le.commandMeta.inputString,modifier:Le.commandMeta.modifier}),Kh=(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,$u=({width:e,mode:t})=>{let[n,r]=$h(Ou());Oh(()=>{let I=()=>{let A=Ou();r(P=>Kh(P,A)?P:A)},N=gi(I);return I(),()=>{N()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:c,autoCompletion:l,command:m,modifier:p,validationStatus:f}=n,g=c&&f===It.Invalid,E=_h(()=>{let I=Math.max(0,Math.min(s,o.length)),N=_u({value:o,command:m}),A=Vh({value:o,command:m,modifier:p}),P=m?Qs(m):null,F=Gh({command:m,modifier:p}),H=(ge,me)=>{let Vn=N&&me>=N.start&&me<N.end,Kn=A&&me>=A.start&&me<A.end;return Vn&&P?P.fg(ge):Kn&&F?F.bg(ge):ge},W=(ge,me)=>{let Vn=N&&me>=N.start&&me<N.end,Kn=A&&me>=A.start&&me<A.end;return Vn&&P?P.fgCursor(ge):Kn&&F?F.bgCursor(ge):Hh(ge)},w=o.slice(0,I),B=o[I]??" ",$=I<o.length?o.slice(I+1):"",Xe=Array.from(w).map((ge,me)=>H(ge,me)).join(""),we=W(B,I),Ue=Array.from($).map((ge,me)=>H(ge,I+1+me)).join("");if(l.hint){let ge=l.hint[l.overlap]??B;we=Wh(ge),Ue=Uu(l.remainder.slice(1)+$)}return Uu(t===h.PALETTE?"?":":")+Xe+we+Ue},[o,s,l,m,p]);return Lr.createElement(Ji,{flexDirection:"column",justifyContent:"flex-start"},Lr.createElement(Ji,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},Lr.createElement(Ji,null,Lr.createElement(Fu,null,E),i&&Lr.createElement(Fu,{wrap:"truncate",color:g?y.red:y.secondary2},` ${i} `))))};import{Box as zh,Text as qh}from"ink";import Hu from"react";var Yh=(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},Wu=({width:e,availableHints:t})=>{let n=Yh(t,e).join(" | ");return Hu.createElement(zh,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1},Hu.createElement(qh,{color:y.secondary2},n.length?n:"\xA0"))};import{Box as Xh,Text as us}from"ink";import Dr,{useEffect as Jh,useRef as Wn,useState as Qh}from"react";var Zh=40,ms=.3,Qi="\u2500",ju=1,Gu=16,Vu=({width:e})=>{let{replay:t}=j(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*ju,[c,l]=Qh(0),m=Wn(r);m.current=r;let p=Wn(0),f=Wn(0),g=Wn(0),E=Wn(0),I=Wn(0);if(Jh(()=>{if(!n){p.current=0,g.current=0,E.current=0,I.current=0,l(0);return}p.current=m.current,f.current=Date.now(),g.current=m.current;let H=setInterval(()=>{let W=Date.now(),w=m.current;if(w!==g.current){let Ue=w-g.current,ge=W-f.current;if(Ue<0)E.current=0,I.current=0;else if(Ue>0&&ge>0){let me=Ue/ge;E.current=E.current===0?me:E.current*(1-ms)+me*ms,I.current=I.current===0?Ue:I.current*(1-ms)+Ue*ms}p.current=w,f.current=W,g.current=w}let B=W-f.current,$=Math.min(I.current,E.current*B),Xe=Math.min(1,p.current+$),we=Math.round(Xe*i);l(Ue=>Ue===we?Ue:we)},Zh);return()=>clearInterval(H)},[n,i]),!t)return null;let N=H=>{let W=s>1?H/(s-1):0,w=Math.round(W*(Gu-1))/(Gu-1);return so(w)},A=Math.min(s,Math.floor(c/ju)),P=[];for(let H=0;H<A;H++){let W=N(H),w=P[P.length-1];w&&w.color===W?w.text+=Qi:P.push({text:Qi,color:W})}let F=Qi.repeat(Math.max(0,s-A));return Dr.createElement(Xh,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1,columnGap:1},Dr.createElement(us,{color:y.secondary2},"\u25B6"),Dr.createElement(us,null,P.map((H,W)=>Dr.createElement(us,{key:W,color:H.color},H.text)),Dr.createElement(us,{color:y.secondary,dimColor:!0},F)))};var Br=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=j(),o=t===h.COMMAND_LINE||t===h.PALETTE;return ps.createElement(ey,null,o?ps.createElement($u,{width:e,mode:t}):r==="replay"?ps.createElement(Vu,{width:e}):ps.createElement(Wu,{width:e,mode:t,availableHints:n}))};import{Box as on,Text as jn}from"ink";import $e,{useEffect as ty,useMemo as ny}from"react";import{ulid as Ku}from"ulid";var gs=Ku(),ry=()=>[...new Set([...v().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(e=>{let[t,n]=e.split("]"),r=t?.replace("[",""),o=n?.trim();return[r,o]}).filter(e=>e[0]!==void 0&&e[1]!==void 0).sort(([e],[t])=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(([e,t])=>({keys:e,action:t})),oy=e=>ee.text({id:gs,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),sy=(e,t,n)=>ee.text({id:Ku(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),fs=[],zu=()=>{let e=fs.filter(n=>n.id!==gs).map(n=>n.id),t=fs.filter(n=>n.id===gs).map(n=>n.id);fs=[];for(let n of[...e,...t])S.deleteNode(n)},iy=e=>{zu();let t=S.createNode(oy(v().rootNodeId));if(d(t)||!Wt(t.value))return logger.error("Could not attach help nodes");fs=[t.value,...e.map((n,r)=>sy(n,r,gs)).map(S.createNode).filter(Q).map(({value:n})=>n).filter(Wt)],M.navigate({contextNode:t.value,selectedIndex:0})},qu=({width:e,height:t})=>{let n=ny(()=>ry(),[]);ty(()=>(iy(n),()=>{zu()}),[n]);let r=v().selectedIndex;return $e.createElement(on,{flexDirection:"column",marginTop:3,borderColor:y.secondary,borderStyle:"round",width:e,height:t-2},$e.createElement(on,{paddingX:1,justifyContent:"center"},$e.createElement(jn,{color:y.accent},"Help"),$e.createElement(jn,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),$e.createElement(on,{paddingX:1,marginTop:1},$e.createElement(on,{width:20,justifyContent:"flex-end"},$e.createElement(jn,{color:y.secondary},"Key(s)")),$e.createElement(on,{flexGrow:1,width:40,paddingLeft:2},$e.createElement(jn,{color:y.secondary},"Action"))),$e.createElement(tt,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let c=i===r;return $e.createElement(on,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},$e.createElement(on,{width:20,justifyContent:"flex-end"},$e.createElement(jn,{color:y.accent},o)),$e.createElement(on,{flexGrow:1,width:40,paddingLeft:2},$e.createElement(jn,{color:c?y.primary:y.secondary2},s)))})))};import ay from"chalk";import{Box as vs,Text as Ot}from"ink";import Ye from"react";var Yu=({width:e,height:t})=>Ye.createElement(vs,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},Ye.createElement(Ot,{color:y.accent,bold:!0},"Initialize project"),Ye.createElement(Ot,null,`This folder is not an ${ay.hex(y.accent)("epiq")} project yet.`),Ye.createElement(Ot,{color:y.primary},"To start tracking issues here, we need to initialize a new",Ye.createElement(Ot,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json "),"file in this repository."),Ye.createElement(vs,{marginTop:1,flexDirection:"column"},Ye.createElement(vs,null,Ye.createElement(Ot,{color:y.accent}," "),Ye.createElement(Ot,{color:y.primary},"Type "),Ye.createElement(Ot,{backgroundColor:y.secondary}," :init "))),Ye.createElement(vs,{marginTop:1},Ye.createElement(Ot,{color:y.secondary2},"This will create, commit and push "),Ye.createElement(Ot,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json ")));import{Box as hs,Text as Rt}from"ink";import Te from"react";var dy=({isDone:e,command:t,value:n})=>Te.createElement(hs,null,Te.createElement(Rt,{color:y.accent,dimColor:e},e?" \u2714 ":" "),Te.createElement(Rt,{dimColor:e},"Type "),Te.createElement(Rt,{backgroundColor:y.secondary,dimColor:e}," "+t+" "),n!==void 0&&Te.createElement(Te.Fragment,null,Te.createElement(Rt,{dimColor:e}," "),Te.createElement(Rt,{color:y.secondary,dimColor:e},"<"+n+">"))),cy=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function Zi({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:c}=qt(),l=[{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=l.findIndex(f=>!f.done),p=m===-1?void 0:l[m];return Te.createElement(hs,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},Te.createElement(Rt,{color:y.accent,bold:!0},"Welcome! \u{1F539}"),Te.createElement(Rt,null,"Let's get you started - it's a breeze."),Te.createElement(Rt,{color:y.secondary2},"Remember - you can always search available commands by typing:",Te.createElement(Rt,{color:y.accent}," ? ")),p&&Te.createElement(Rt,{color:y.secondary2},p.message),Te.createElement(hs,{flexDirection:"column"},l.map((f,g)=>m===-1||g<=m?Te.createElement(hs,{key:f.key,marginBottom:1},Te.createElement(dy,{isDone:f.done,command:f.command,value:f.done?cy(f.value):void 0})):null)))}import Es from"chalk";import{Box as Ur,Text as Gn}from"ink";import xe from"react";import{Box as ys,Text as Xu}from"ink";import sn from"react";import ly from"chalk";var uy=e=>(S.getTag(e)?.name??"").length+3,my=e=>{let t=S.getContributor(e);return(t?St(e,t.name):"").length+3},Ju=({width:e})=>{let{viewMode:t}=K(),n=j(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,c=i[o.id]?.[s],l=wt(c?.id??o.id,"TICKET"),m=Q(l)?l.value:void 0,p=m?.props.tags??[],f=m?.props.assignees??[],g=m?.parentNodeId?!Ys(o.id,m.parentNodeId)&&t==="dense":!1,E=r.map((w,B)=>{let $=B===r.length-1,Xe=Y(w.id),we=$?Xe?.[s]?.title:void 0;return`${B?" / ":""}${w.title??""}${we?` \u25B8 ${we}`:""}`}).join(""),I=m?S.getCommentsByIssue(m.id):[],N=I.length?String(I.length).length+11:0,A=g?p.reduce((w,B)=>w+uy(B),0)+f.reduce((w,B)=>w+my(B),0)+N:0,P=c?.id!=null&&!(t==="wide"&&T(c)),F=Math.max(0,e-A),H=E.substring(0,F)+(P?ly.hex(y.secondary2).dim(` ${We(c.id)}`):""),W=g?[...p.map(w=>sn.createElement(ys,{key:`tag-${w}`,paddingLeft:1},sn.createElement(Un,{id:w}))),...f.map(w=>sn.createElement(ys,{key:`assignee-${w}`,paddingLeft:1},sn.createElement(Qt,{id:w}))),I.length?sn.createElement(ys,{key:"comments",paddingLeft:1},sn.createElement(Xu,{color:y.accent},"[",I.length," comment",I.length===1?"":"s","]")):null]:[];return sn.createElement(ys,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},sn.createElement(Xu,{color:y.secondary2},H),W)};import{Box as py,Text as Qu}from"ink";import xs from"react";var fy=({filters:e})=>xs.createElement(py,{columnGap:1},xs.createElement(Qu,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>xs.createElement(Qu,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Zu=xs.memo(fy);import{Box as gy,Text as bs}from"ink";import Fr from"react";function em(){let{eventLog:e,unappliedEvents:t}=j(),n=e.at(-1)?.id,r=To(n??""),o=Q(r)?lo(r.value):"INVALID DATE";return Fr.createElement(gy,{paddingLeft:1},Fr.createElement(bs,{backgroundColor:y.accent,color:y.secondary}," Readonly "),Fr.createElement(bs,{color:y.accent}," "+t.length+" edits ago at "+o+"."),Fr.createElement(bs,{color:y.accent}," Resume with "),Fr.createElement(bs,{backgroundColor:y.accent,color:y.secondary}," ",":peek now"," "))}import{Box as vy,Text as ea}from"ink";import Is from"react";function tm(){let{replay:e}=j();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return Is.createElement(vy,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},Is.createElement(ea,{backgroundColor:y.accent,color:y.secondary}," \u25B6 REPLAY "),Is.createElement(ea,{color:y.secondary2},lo(new Date(r))),Is.createElement(ea,{color:y.accent},`${t}/${n} edits`))}import ta from"chalk";import{Box as hy,Text as nm}from"ink";import na,{useEffect as yy,useState as xy}from"react";var by=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Iy=150,rm=12,Ey=.36,om=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)}},Sy=({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)}`},Cy=(e,t,n)=>{let r=om(e),o=om(t);return Sy({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Ny=(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 Cy(s,i,o)};function sm({syncStatus:e,autoSync:t}){let[n,r]=xy(0);yy(()=>{if(e.status!=="syncing"){r(0);return}let c=0,l=setInterval(()=>{c+=1;let m=(Math.sin(c*Ey)+1)/2,p=Math.round(m*(rm-1));r(f=>f===p?f:p)},Iy);return()=>clearInterval(l)},[e.status]);let o={synced:" ",failed:"---",syncing:"...",pending:"idle"},i={synced:y.secondary2,failed:y.yellow,pending:y.secondary2,syncing:Ny(by,n/(rm-1))??""}[e.status];return na.createElement(hy,null,na.createElement(nm,null,ta.hex(y.secondary2).dim(t?"Sync (auto): ":"Sync: ")),na.createElement(nm,null,ta.hex(i)("\u25CF")+ta.hex(y.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import lm from"chalk";import{Text as um}from"ink";import mm,{useEffect as wy,useState as My}from"react";var an="1.4.5";import ra from"chalk";var Ry="https://registry.npmjs.org/epiq/latest",oa=null,im=0,Ay=1e3*60*60*24,am=e=>e.replace(/^v/,""),Ty=(e,t)=>{let n=am(e).split(".").map(Number),r=am(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},dm=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(oa&&Date.now()-im<Ay)return oa;try{let t=await fetch(Ry);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?Ty(r,e)>0:!1};return oa=o,im=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},cm=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?ra.hex(y.accent).dim(s):ra.hex(y.secondary).dim(s)).join(ra.hex(y.secondary2).dim("."))};function pm(){let[e,t]=My({current:an,latest:null,updateAvailable:!1});return wy(()=>{let n=!0;return dm(an).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?mm.createElement(um,{dimColor:!0,color:y.secondary2},an+" "):mm.createElement(um,null,lm.hex(y.secondary2).dim(an),lm.hex(y.accent).dim(" \u2197 "),cm(an,e.latest))}function Or({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=j(),{userName:i,preferredEditor:c,autoSync:l}=K(),m=64,p=process.stdout.columns-m-8,f=t||n==="replay",g=s?ot(s.currentLabel,Math.max(0,p)):"";return xe.createElement(Ur,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?xe.createElement(Ur,{paddingLeft:1},xe.createElement(Gn,{color:y.secondary2},g)):f?xe.createElement(Gn,null," "):o===h.PALETTE?xe.createElement(Ur,null,xe.createElement(Gn,{color:y.accent},"Command Palette"),xe.createElement(Gn,{dimColor:!0,color:y.secondary2}," ","- search, select and press enter")):xe.createElement(Ur,{paddingLeft:1},e.length>0?xe.createElement(Zu,{filters:e}):xe.createElement(Ju,{width:p})),n==="live"?xe.createElement(Ur,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},xe.createElement(sm,{autoSync:!!l,syncStatus:r}),xe.createElement(Gn,null,Es.hex(y.secondary2).dim("Mode: ")+Es.hex(y.secondary2).dim(o.padEnd(8," "))," "),xe.createElement(fm,{icon:"@",value:i}),xe.createElement(fm,{icon:"\u276F",value:c}),xe.createElement(pm,null)):"",n==="peek"?xe.createElement(em,null):"",n==="replay"?xe.createElement(tm,null):"")}function fm({icon:e,value:t}){return xe.createElement(Gn,null,Es.dim(e)+Es.hex(y.accent)(` ${t??"-"} `))}import{Box as Py,Text as Ly}from"ink";import _r from"react";import{Box as Ss,Text as sa}from"ink";import dn from"react";function ia(){let e=j(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?z(t?.id):[];return dn.createElement(Ss,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:y.secondary,width:s},dn.createElement(Ss,{padding:1,paddingTop:0,paddingBottom:0},dn.createElement(sa,null,"Select a board:")),dn.createElement(Ss,{padding:1,flexDirection:"column"},i.map((c,l)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===l,f=z(c.id).flatMap(({id:g})=>Y(g)).length;return dn.createElement(Ss,{key:c.id??l},dn.createElement(sa,{color:m?y.accent:y.secondary2},dn.createElement(ke,{isSelected:m})),dn.createElement(sa,{color:m?y.accent:y.secondary2},c.title," (",f," issues)",c.readonly?" \u{1F512}":""))})))}var ky=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:c}=j(),l=n.find(({context:g})=>g==="BOARD"),f=s-1-3;return _r.createElement(Py,{flexDirection:"row"},e.context==="WORKSPACE"?_r.createElement(ia,null):l?_r.createElement(Ho,{height:f,width:i,swimlanes:(c[l.id]??[]).filter(g=>g!==void 0&&jt(g)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):_r.createElement(Ly,null))},gm=_r.memo(ky);import{useEffect as Dy}from"react";var By=e=>{Dy(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=K();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:c,mode:l}=v();l==="default"&&!c&&Eo(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},vm=({autoSync:e})=>(By(e),null);function aa({width:e,height:t}){let n=j(),{autoSync:r,viewMode:o}=Oa(),s=n.filters;if(n.mode===h.HELP)return ce.createElement(cn,{flexDirection:"column"},ce.createElement(qu,{width:e,height:t}));if(n.mode===h.PALETTE)return ce.createElement(cn,{flexDirection:"column"},ce.createElement(Or,{filters:s}),ce.createElement(Bu,{width:e,height:t-2}),ce.createElement(Br,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=qt(),c=!i,l=i&&!n.hasProjectDefinition;if(c)return ce.createElement(cn,{flexDirection:"column"},ce.createElement(cn,{flexDirection:"column"},ce.createElement(Or,{hideBreadCrumb:!0,filters:s}),ce.createElement(Zi,{height:t,width:e})),ce.createElement(Br,{width:e,mode:n.mode,availableHints:n.availableHints}));if(l)return ce.createElement(cn,{flexDirection:"column"},ce.createElement(cn,{flexDirection:"column"},ce.createElement(Or,{hideBreadCrumb:!0,filters:s}),ce.createElement(Yu,{height:t,width:e})),ce.createElement(Br,{width:e,mode:n.mode,availableHints:n.availableHints}));let m=_e(n.breadCrumb??[],"BOARD");if(Q(m)){let p=m.value.id,f=z(p).length,g=3,E=Math.floor(e/g),I=Math.floor(e/Math.max(f,1));e=Math.min(I,E)*Math.max(f,g)}return ce.createElement(cn,{flexDirection:"column"},ce.createElement(vm,{autoSync:r}),ce.createElement(cn,{flexDirection:"column"},ce.createElement(Or,{filters:s}),ce.createElement(gm,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),ce.createElement(Br,{width:e,mode:n.mode,availableHints:n.availableHints}))}import Fy from"readline";var Cs,Ns,At,Uy=new Set([x.MoveCursorLeft,x.EraseInputWord,x.MoveCursorLeftOfWord,x.MoveCursorRight,x.MoveCursorRightOfWord,x.NavToPreviousContainer,x.NavToNextContainer,x.NavPreviousItem,x.NavNextItem,x.SetViewDense,x.SetViewWide,x.Confirm,x.Exit,x.Yank,x.InitCommandLine,x.InitCommandPalette,x.ExitCommandLine,x.CaptureInput,x.EraseInput,x.EraseInputWord,x.HideHelp,x.ViewHelp,x.SetViewDense,x.SetViewWide,x.GetLastCommandFromHistory,x.GetNextCommandFromHistory,x.AutoCompleteCommand]),Oy=new Set([x.NavPreviousItem,x.NavNextItem,x.NavToPreviousContainer,x.NavToNextContainer,x.Confirm,x.Exit,x.InitCommandPalette,x.InitMove,x.MoveNextItem,x.MovePreviousItem,x.MoveToNextContainer,x.MoveToPreviousContainer,x.Delete,x.AddItem,x.EditTitle,x.EditDescription,x.ConfirmMove,x.Edit,x.ViewHelp,x.Yank]),hm=async e=>{if(e.ctrl&&e.name==="c")return M.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=v(),s=Cc(e,n);if(!s||r&&!Uy.has(s)||o==="replay"&&n===h.DEFAULT&&Oy.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(c){logger.error(c)}},_y=()=>async function(t,n){n.name!=="escape"&&(At&&(clearTimeout(At),At=void 0),await hm(n))},$y=()=>async function(t){if(t.length===1&&t[0]===27){At&&clearTimeout(At),At=setTimeout(()=>{hm({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),At=void 0},25);return}At&&(clearTimeout(At),At=void 0)};function ym(){Cs&&process.stdin.removeListener("keypress",Cs),Ns&&process.stdin.removeListener("data",Ns),Cs=_y(),Ns=$y(),Fy.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Ns),process.stdin.on("keypress",Cs)}async function xm(){try{let e=$t();Q(e)&&Me(e.value);let t=He(process.cwd()),n=[];if(Q(t)){let s=Re({repoRoot:t.value});if(d(s))return vn(3,s.message);let i=Cn(),c=await mn({repoRoot:t.value,stateBranchRoot:s.value,stateBranchName:i.stateBranch});if(d(c))return vn(3,c.message);let l=await U({cwd:s.value,args:["pull","--ff-only"]});d(l)&&logger.info(3,l.message);let m=je(s.value);if(d(m))return vn(3,m.message);n=m.value}let r=gn(n);if(d(r))return vn(4,r.message);C({hasProjectDefinition:Q(t),hasInitializingEvents:!!n.length});let o=da();return d(o)?vn(6,o.message):(ym(),u("Booted Epiq",void 0))}catch(e){return vn(0,xo(e))}}Xc();var Gy=`${ln.bold("Epiq CLI")}
61
61
 
62
- ${cn.dim("Boot in directory:")}
63
- ${cn.cyan("$ epiq")}
62
+ ${ln.dim("Boot in directory:")}
63
+ ${ln.cyan("$ epiq")}
64
64
 
65
- ${cn.dim("Launch GUI:")}
66
- ${cn.cyan("$ epiq gui")}
67
- `,Hh=Oh($h,{importMeta:import.meta,version:sn,flags:{init:{type:"boolean",default:!1}}}),Ns=Hh.input[0];Ns&&Ns!=="gui"&&(console.error(cn.red(`Unknown command: ${Ns}`)),process.exit(1));var xm=process.stdout.columns||120,bm=process.stdout.rows||20,Rs=null,jh=e=>{try{return Rs?(Rs.rerender(e),u("Rerendered app",void 0)):(Rs=Uh(e),u("Rendered app",void 0))}catch(t){return a(`Unable to render app: ${ho(t)}`)}},aa=()=>jh(_h.createElement(ia,{width:xm,height:bm}));process.stdout.on("resize",()=>{if(xm=process.stdout.columns||120,bm=process.stdout.rows||20,!Rs)return;let e=aa();d(e)&&logger.info(`[boot:resize] ${e.message}`)});if(Ns==="gui"){let e=await Mu({repoRoot:process.cwd()});d(e)&&(console.error(cn.red(`Failed to start Epiq GUI:
68
- ${e.message}`)),process.exitCode=1)}else{console.clear();let e=await hm();d(e)&&(logger.info(e.message),console.error(cn.red(`Failed to boot Epiq:
69
- ${e.message}`)),process.exitCode=1)}export{aa as renderApp};
65
+ ${ln.dim("Launch GUI:")}
66
+ ${ln.cyan("$ epiq gui")}
67
+ `,Vy=Wy(Gy,{importMeta:import.meta,version:an,flags:{init:{type:"boolean",default:!1}}}),Rs=Vy.input[0];Rs&&Rs!=="gui"&&(console.error(ln.red(`Unknown command: ${Rs}`)),process.exit(1));var bm=process.stdout.columns||120,Im=process.stdout.rows||20,As=null,Ky=e=>{try{return As?(As.rerender(e),u("Rerendered app",void 0)):(As=Hy(e),u("Rendered app",void 0))}catch(t){return a(`Unable to render app: ${xo(t)}`)}},da=()=>Ky(jy.createElement(aa,{width:bm,height:Im}));process.stdout.on("resize",()=>{if(bm=process.stdout.columns||120,Im=process.stdout.rows||20,!As)return;let e=da();d(e)&&logger.info(`[boot:resize] ${e.message}`)});if(Rs==="gui"){let e=await Pu({repoRoot:process.cwd()});d(e)&&(console.error(ln.red(`Failed to start Epiq GUI:
68
+ ${e.message}`)),process.exitCode=1)}else{console.clear();let e=await xm();d(e)&&(logger.info(e.message),console.error(ln.red(`Failed to boot Epiq:
69
+ ${e.message}`)),process.exitCode=1)}export{da as renderApp};