epiq 1.8.3 → 1.8.4
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/gui/main.js +1 -1
- package/dist/index.js +62 -62
- package/dist/mcp.js +58 -58
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,93 +1,93 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import jt from"chalk";import{render as
|
|
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
|
|
4
|
-
`);return i===-1?"":s.slice(i+1)}finally{wt.closeSync(r)}};function
|
|
5
|
-
`);if(n[n.length-1]===""&&n.pop(),t<=Oa&&n.length<=
|
|
2
|
+
import jt from"chalk";import{render as EN}from"ink";import CN from"meow";import RN from"react";import zh from"chalk";import Wy from"node:crypto";var En={Success:"success",Fail:"fail"},a=e=>({status:En.Fail,message:e,value:null}),u=(e,t)=>({status:En.Success,message:e,value:t}),d=e=>e.status==="fail",ce=e=>e.status==="success";var dn="EPIQ_USER_NAME",xs="EPIQ_USER_ID",Tc="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Gy=26,Ta=80,wa=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),Is=e=>e.trim().length>0&&e.length<=Ta,xr=e=>e.trim().toLowerCase(),Vy=e=>{let t=Wy.createHash("sha256").update(`epiq:actor:${xr(e)}`).digest(),n="";for(let r=0;r<Gy;r++)n+=Tc[(t[r]??0)%Tc.length];return n},Ir=(e,t=process.env)=>{let n=(t[dn]??"").trim(),r=(t[xs]??"").trim();return n?Is(n)?!r&&e.userId&&e.userName&&xr(e.userName)===xr(n)?u("Actor override names the configured user",{userId:e.userId,userName:e.userName}):r&&!wa(r)?a(`${xs} must be 26 characters of Crockford base32`):r&&e.userId&&r===e.userId?a(`${xs} is the configured user's own id; using it under a different name would rename them on the board`):u("Resolved actor from environment",{userId:r||Vy(n),userName:r?n:xr(n)}):a(`${dn} must be 1-${Ta} characters of text`):r?a(`${xs} is set without ${dn}`):u("No actor override",null)},Ma=(e,t,n=process.env)=>{let r=e.trim();if(!Is(r))return a(`${t} must be 1-${Ta} characters of text`);let o=(n[dn]??"").trim();return o&&xr(o)!==xr(r)?a(`${t} names ${r}, but ${dn} names ${o}`):(o||(n[dn]=r),u("Applied actor name argument",o||r))};import Nv from"node:path";import{z as pn}from"zod";import uo from"node:fs";import Wt from"node:path";import Cn from"node:fs";import rt from"node:path";import oo from"node:fs";import{ulid as zy}from"ulid";import{z as Ss}from"zod";var Ky="__epiq_state__",qy=Ss.object({projectId:Ss.string().min(1),stateBranch:Ss.string().min(1),createdAt:Ss.iso.datetime()}),Es=()=>({projectId:zy(),stateBranch:Ky,createdAt:new Date().toISOString()}),$t=e=>{let t=Cs(e);if(!oo.existsSync(t))return a("Missing .epiq/project.json");try{let n=oo.readFileSync(t,"utf8"),r=JSON.parse(n),o=qy.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")}},so=e=>{let t=$t(e);return d(t)?a(t.message):u("Read projectId",t.value.projectId)},wc=({repoRoot:e,fileContents:t})=>{let n=Yn(e),r=Cs(e);try{if(oo.mkdirSync(n,{recursive:!0}),oo.existsSync(r)){let o=$t(e);return d(o)?a(o.message):u("Project already initialized",null)}return oo.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 Yy from"node:os";import Xy from"node:path";var Tt=".epiq-global",ln=()=>process.env.EPIQ_GLOBAL_DIR??Xy.join(Yy.homedir(),Tt);var Pa=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let i=r(...s);if(!n.has(i)){let l=e(...s).then(c=>(d(c)&&n.delete(i),c));n.set(i,l)}return n.get(i)});return o.clear=()=>n.clear(),o};import wt from"fs";import Fa from"path";import Jy from"util";var Mc=500,Oa=4*1024*1024,La=16*1024,Qy=50,ka=0,Pc=()=>process.env.EPIQ_MCP==="true",Zy=()=>{let e=process.cwd(),t=Rs(e);return d(t)?Pc()?Fa.join(ln(),"epiq-mcp.log"):void 0:Fa.join(t.value,Je,"log","epiq.log")},ev=(e,t)=>{let n=wt.statSync(e).size;if(n<=t)return wt.readFileSync(e,"utf8");let r=wt.openSync(e,"r");try{let o=Buffer.alloc(t);wt.readSync(r,o,0,t,n-t);let s=o.toString("utf8"),i=s.indexOf(`
|
|
4
|
+
`);return i===-1?"":s.slice(i+1)}finally{wt.closeSync(r)}};function tv(e){if(!wt.existsSync(e))return;let t=wt.statSync(e).size,n=ev(e,Oa).split(`
|
|
5
|
+
`);if(n[n.length-1]===""&&n.pop(),t<=Oa&&n.length<=Mc)return;let r=n.slice(-Mc).join(`
|
|
6
6
|
`)+`
|
|
7
|
-
`;wt.writeFileSync(e,r,"utf8")}var
|
|
8
|
-
`;try{wt.mkdirSync(Fa.dirname(r),{recursive:!0}),wt.appendFileSync(r,l,"utf8"),ka++,(ka>=
|
|
7
|
+
`;wt.writeFileSync(e,r,"utf8")}var nv=e=>{if(e.length<=La)return e;let t=e.length-La;return`${e.slice(0,La)} \u2026 [${t} more chars]`};function Da(e,t,n=!1){let r=Zy();if(!r)return;let o=nv(Jy.format(...t)),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
8
|
+
`;try{wt.mkdirSync(Fa.dirname(r),{recursive:!0}),wt.appendFileSync(r,l,"utf8"),ka++,(ka>=Qy||wt.statSync(r).size>Oa)&&(ka=0,tv(r))}catch{}}var Ba=()=>Pc()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",z={info(...e){let t=Ba();(t==="info"||t==="debug")&&Da("[Info]",e,!1)},debug(...e){Ba()==="debug"&&Da("[Debug]",e,!0)},error(...e){let t=Ba();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;Da("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=z;import{spawn as kc}from"node:child_process";import cn from"node:fs";import un from"node:path";var be={stage:({cwd:e,pathspec:t,ignoreRemoval:n=!1})=>j({args:["add",...n?["--ignore-removal"]:[],...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1,pathspec:r})=>j({args:["commit","--no-verify",...n?["--allow-empty"]:[],"-m",t,...r?.length?["--",...r]:[]],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>j({args:["fetch",t,`+refs/heads/${n}:refs/remotes/${t}/${n}`],cwd:e}),rebaseOnto:({cwd:e,ref:t})=>j({args:["-c","rebase.autoStash=true","rebase",t],cwd:e}),checkout:({cwd:e,branch:t})=>j({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push","--no-verify",...r?["-u"]:[],t,n]:["push","--no-verify"];return j({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>j({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>j({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>j({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>j({args:["worktree","prune"],cwd:e})};var Ht=e=>{let t=xe(e);if(d(t))return a("Unable to resolve epiq project root");let n=$t(t.value);return d(n)?a("Unable to read project.json"):u("Resolved state branch",n.value.stateBranch)},gt="origin";var _a=1e4,rv=12e4,ov=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),sv=e=>{let t=e.find((n,r)=>!n.startsWith("-")&&e[r-1]!=="-c");return t&&ov.has(t)?rv:_a},iv=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(un.delimiter))if(t)for(let n of e){let r=un.join(t,n);try{if(!cn.statSync(r).isFile())continue;return cn.accessSync(r,cn.constants.X_OK),r}catch{continue}}return"git"},Dc=iv(),Bc={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Fc=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!cn.existsSync(t)){let f=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:f,exitCode:1});return}r(a(f));return}let o=kc(Dc,e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Bc}),s=!1,i="",l="",c=f=>{s||(s=!0,clearTimeout(p),r(f))},m=sv(e),p=setTimeout(()=>{o.kill("SIGTERM");let f=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${m}ms`].join(`
|
|
9
9
|
`);c(n?{stdout:i,stderr:f,exitCode:124}:a(f))},m);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",f=>{i+=f}),o.stderr.on("data",f=>{l+=f}),o.on("error",f=>{if(n){c({stdout:i,stderr:f.message,exitCode:1});return}c(a([`git ${e.join(" ")}`,`cwd=${t}`,f.message].join(`
|
|
10
10
|
`)))}),o.on("close",f=>{let g=f??1;if(n){c({stdout:i,stderr:l,exitCode:g});return}if(g!==0){c(a([`git ${e.join(" ")}`,l.trim()||i.trim()||"Git command failed"].filter(Boolean).join(`
|
|
11
|
-
`)));return}c(u("Git command succeeded",{stdout:i,stderr:l,exitCode:g}))})}),j=({args:e,cwd:t})=>
|
|
12
|
-
${s}`:""}`));return}let p=Buffer.concat(o),f=new Map,g=0;for(let v of e){let x=p.indexOf(10,g);if(x===-1){l(a(`git cat-file --batch output ended before a header for ${v}`));return}let I=p.toString("utf8",g,x);g=x+1;let
|
|
11
|
+
`)));return}c(u("Git command succeeded",{stdout:i,stderr:l,exitCode:g}))})}),j=({args:e,cwd:t})=>Fc({args:e,cwd:t,allowFail:!1}),je=({args:e,cwd:t})=>Fc({args:e,cwd:t,allowFail:!0}),Ns=(e,t)=>new Promise(n=>{if(e.length===0){n(u("No blobs to read",new Map));return}let r=kc(Dc,["cat-file","--batch"],{cwd:t,stdio:["pipe","pipe","pipe"],env:Bc}),o=[],s="",i=!1,l=m=>{i||(i=!0,clearTimeout(c),n(m))},c=setTimeout(()=>{r.kill("SIGTERM"),l(a(`git cat-file --batch timed out after ${_a}ms`))},_a);r.stdout.on("data",m=>o.push(m)),r.stderr.setEncoding("utf8"),r.stderr.on("data",m=>{s+=m}),r.on("error",m=>l(a(m.message))),r.on("close",m=>{if(m!==0){l(a(`git cat-file --batch exited ${m}${s?`
|
|
12
|
+
${s}`:""}`));return}let p=Buffer.concat(o),f=new Map,g=0;for(let v of e){let x=p.indexOf(10,g);if(x===-1){l(a(`git cat-file --batch output ended before a header for ${v}`));return}let I=p.toString("utf8",g,x);g=x+1;let R=/^[0-9a-f]{4,64} \S+ (\d+)$/.exec(I);if(!R||!R[1]){l(a(`Unexpected git cat-file --batch header: "${I}"`));return}let A=Number(R[1]);f.set(v,p.toString("utf8",g,g+A)),g+=A+1}l(u("Read blobs",f))}),r.stdin.write(e.join(`
|
|
13
13
|
`)+`
|
|
14
14
|
`),r.stdin.end()}),Sr=async({cwd:e,message:t,pathspec:n})=>{let r=await be.commit({cwd:e,message:t,pathspec:n});if(d(r))return a(`Failed to create commit
|
|
15
15
|
${r.message}`);let o=await j({args:["rev-parse","HEAD"],cwd:e});return d(o)?a(`Commit created, but failed to read HEAD SHA
|
|
16
|
-
${o.message}`):u("Created commit and resolved SHA",o.value.stdout.trim())},Ua=async e=>{let t=await j({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",un.isAbsolute(n)?n:un.resolve(e,n))},
|
|
17
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(io).includes(r);return u("Checked worktree registration",o)},$a=async e=>{let t=await je({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return u("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},
|
|
18
|
-
${t.stderr.trim()}`):u("Aborted stale rebase",!0)},
|
|
19
|
-
${o.message}`);let s=await
|
|
20
|
-
${s.message}`);let i=await
|
|
16
|
+
${o.message}`):u("Created commit and resolved SHA",o.value.stdout.trim())},Ua=async e=>{let t=await j({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",un.isAbsolute(n)?n:un.resolve(e,n))},av=async e=>{let t=await Ua(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(cn.existsSync(un.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(cn.existsSync(un.join(n,s)))return u("Checked for in-progress Git operation",i);return u("Checked for in-progress Git operation",null)},As=async e=>{let t=await av(e);return d(t)?a(t.message):u("Checked for in-progress Git operation",t.value!==null)},Xn=async({repoRoot:e})=>{let n=(await je({args:["remote","get-url",gt],cwd:e})).exitCode===0;return u(`Checked remote ${n}`,n)},ja=async({repoRoot:e,branch:t})=>{let n=await je({args:["ls-remote","--heads",gt,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${gt}/${t}`):u("Checked remote branch",n.stdout.trim().length>0)},Ts=async({repoRoot:e,branch:t})=>{let n=await je({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}`)},io=e=>{try{return cn.realpathSync.native(e)}catch{return un.resolve(e)}},Oc=async({repoRoot:e,worktreeRoot:t})=>{let n=await j({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=io(t),o=n.value.stdout.split(`
|
|
17
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(io).includes(r);return u("Checked worktree registration",o)},$a=async e=>{let t=await je({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return u("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},ws=async e=>{let t=await j({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?a(t.message):u("Resolved current branch",t.value.stdout.trim())},_c=async e=>{let t=await j({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?a(t.message):u("Resolved short HEAD sha",t.value.stdout.trim())},Uc=e=>e.includes("fetch first")||e.includes("non-fast-forward"),jc=async e=>{let t=await je({cwd:e,args:["rev-parse","--absolute-git-dir"]});if(t.exitCode!==0)return!1;let n=t.stdout.trim();return n?cn.existsSync(un.join(n,"rebase-merge"))||cn.existsSync(un.join(n,"rebase-apply")):!1},dv=3,lv=120,cv=e=>new Promise(t=>setTimeout(t,e)),uv=async(e,t)=>{let n=await be.rebaseOnto({cwd:e,ref:t});for(let r=1;r<dv;r+=1){if(!d(n)||await jc(e))return n;await cv(lv),n=await be.rebaseOnto({cwd:e,ref:t})}return n},mv=async e=>{if(!await jc(e))return u("No rebase to abort",!1);let t=await je({cwd:e,args:["rebase","--abort"]});return t.exitCode!==0?a(`Failed to abort the rebase in progress at ${e}
|
|
18
|
+
${t.stderr.trim()}`):u("Aborted stale rebase",!0)},Lc=async e=>{let t=await je({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},ao=e=>/could not resolve host/i.test(e)||/connection refused|connection timed out|operation timed out/i.test(e)||/network is unreachable|no route to host/i.test(e)||/failed to connect to/i.test(e),pv=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),lo=async({cwd:e,branch:t})=>{let n=await mv(e);if(d(n))return a(n.message);let r=await Lc(e),o=await be.fetch({cwd:e,remote:gt,branch:t});if(d(o))return pv(o.message)?u("Remote branch missing, skipped pull",!1):a(`Failed to fetch ${t}
|
|
19
|
+
${o.message}`);let s=await uv(e,`${gt}/${t}`);if(d(s))return a(`Failed during rebase
|
|
20
|
+
${s.message}`);let i=await Lc(e),l=r!==null&&i!==null&&r!==i;return u(l?"Pulled with rebase":"Already up to date",l)},$c=async e=>{let t=await je({args:["rev-list","--count","@{u}..HEAD"],cwd:e});return t.exitCode!==0?u("No upstream to compare against",!1):u("Compared against upstream",Number(t.stdout.trim())>0)},Hc=async e=>{let t=await je({args:["status","--porcelain","--untracked-files=all"],cwd:e});return t.exitCode!==0?a(t.stderr.trim()||"Unable to inspect the worktree for changes"):u("Inspected worktree for changes",t.stdout.trim().length>0)},Wc=async(e,t)=>{let n=await je({args:["diff","--cached","--quiet",...t?.length?["--",...t]:[]],cwd:e});return n.exitCode===0?u("No staged changes",!1):n.exitCode===1?u("Has staged changes",!0):a(n.stderr.trim()||"Unable to inspect staged changes")};var Gc=async e=>{let t=await ws(e);return d(t)?a(t.message):u("Checked detached HEAD state",t.value==="HEAD")};var Kc="4b825dc642cb6eb9a060e54bf8d69288fbee4904",qc=e=>rt.join(Je,mn,e),Yc=()=>rt.join(Je,Ga),Xc=ln,Ms=()=>rt.join(Xc(),"worktrees"),ue=({repoRoot:e})=>{let t=so(e);return d(t)?a(t.message):u("Resolved state branch root",rt.join(Ms(),t.value))},fv=e=>rt.join(e,Je),Vc=e=>rt.join(fv(e),mn);var co=e=>{try{return Cn.mkdirSync(e,{recursive:!0}),u("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},Ps=()=>{let e=Xc(),t=Ms(),n=!Cn.existsSync(e)||!Cn.existsSync(t),r=co(e);if(d(r))return a(`Ensure epiq home failed.
|
|
21
21
|
`+r.message);let o=co(t);return d(o)?a(`Ensure worktrees dir failed.
|
|
22
|
-
`+o.message):u("Ensured epiq storage",n)},
|
|
23
|
-
`,
|
|
24
|
-
`,Ha=()=>rt.join(Je,mn,".gitattributes"),Wa=()=>rt.join(Je,mn,".gitignore"),
|
|
22
|
+
`+o.message):u("Ensured epiq storage",n)},Jc=e=>{Cn.existsSync(e)&&(z.debug("[sync] remove path",e),Cn.rmSync(e,{recursive:!0,force:!0}))};var gv=`*.jsonl merge=union
|
|
23
|
+
`,hv=`*~pending*.jsonl
|
|
24
|
+
`,Ha=()=>rt.join(Je,mn,".gitattributes"),Wa=()=>rt.join(Je,mn,".gitignore"),zc=(e,t)=>{try{Cn.readFileSync(e,"utf8")!==t&&Cn.writeFileSync(e,t)}catch{Cn.writeFileSync(e,t)}},Qc=(e,t)=>{for(let n of[Vc(e),Vc(t)]){let r=co(n);if(d(r))return a(r.message)}return zc(rt.join(t,Ha()),gv),zc(rt.join(t,Wa()),hv),u("Ensured state branch",void 0)},Zc=async e=>{let t=await j({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return a(`ensure state branch is storage only failed
|
|
25
25
|
`+t.message);let r=t.value.stdout.trim().split(`
|
|
26
26
|
`).filter(Boolean).filter(i=>i!==Je);if(r.length===0)return u("State branch is storage-only",!1);let o=await j({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return a(`Failed to clean storage branch
|
|
27
|
-
${o.message}`);let s=await Sr({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:r});return d(s)?a(s.message):u("Cleaned storage branch",!0)},Mt=Pa(async(e=process.cwd())=>{let t=await j({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=>rt.resolve(e)),
|
|
28
|
-
`),u("Config written",null)}catch{return a(`Unable to write ~/${Tt}/config.json`)}},ht=e=>{let t=Rr();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return ou(n)},yt=()=>{let e=Ka(),t=qa();if(d(t))return a(`Unable to create ~/${Tt}`);if(!($e.readFile(e)!==null)){let x=ou(Ev);if(d(x))throw new Error(`Unable to create ~/${Tt}/config.json`)}let r=Rr();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:l,autoSyncDebounceMs:c,attachmentMaxKb:m,logLevel:p,viewMode:f}=r.value,g=Ir({userId:i,userName:s});if(d(g))return a(g.message);let v=g.value??{userId:i,userName:s};return!v.userName||!v.userId?a(`User name or ID not configured in ~/${Tt}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,u("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:v.userName,userId:v.userId,autoSync:l??!1,autoSyncIntervalMs:c??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))};import{useSyncExternalStore as Nv}from"react";var fo={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Ya=new Set,Av=()=>{for(let e of Ya)e()},ie=()=>fo,su=()=>Nv(e=>(Ya.add(e),()=>{Ya.delete(e)}),()=>fo),ze=e=>(fo={...fo,...e},Av(),fo);import{spawn as Tv}from"node:child_process";import Xa from"node:process";var Ja=e=>{let t=Xa.platform==="darwin"?"open":Xa.platform==="win32"?"cmd":"xdg-open",n=Xa.platform==="win32"?["/c","start","",e]:[e];Tv(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as jh}from"node:fs/promises";import Hn from"chalk";import Ig from"string-width";import{decodeTime as iu}from"ulid";var Ls=1440*60*1e3,go=(e,t=Date.now())=>e>t+Ls?t:e,Ie=e=>go(iu(e)),Cr=e=>{let t=Date.now()+Ls,n=e.find(o=>o!==null&&o<=t)??null;if(n===null)return[...e];let r=null;return e.map(o=>{if(o===null)return null;let s=o<=t?o:r??n;return r=s,s})},ks=e=>{try{return u("Decoded date",new Date(Ie(e)))}catch(t){return a("Decoding failed + "+t.message)}},Cn=e=>{if(!e?.id)return null;try{return iu(e.id)}catch{return null}};var Ds="removed",Qe=(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")},au=["png","jpg","gif","webp"];var V={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function Qa(e){return e.context===V.WORKSPACE}function P(e){return e.context===V.TICKET}function Nn(e){return e.context===V.TEXT}function ut(e){return e.context===V.FIELD}function ho(e){return e.context===V.FIELD_LIST}var mt=e=>e.context===V.SWIMLANE,Nr=e=>e.context===V.BOARD,yo=e=>e.context===V.COMMENT;import{useSyncExternalStore as pE}from"react";var b={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var du=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",lu=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",cu=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",uu=(e,t)=>{if(lu(e,e.sequence))return S.MoveCursorLeftOfWord;if(cu(e,e.sequence))return S.MoveCursorRightOfWord;if(du(e,e.sequence))return S.EraseInputWord;switch(e.name){case"tab":return S.AutoCompleteCommand;case"up":return S.GetLastCommandFromHistory;case"down":return S.GetNextCommandFromHistory;case"left":return S.MoveCursorLeft;case"right":return S.MoveCursorRight;case"return":return S.Confirm;case"backspace":return t?S.EraseInput:S.ExitCommandLine;case"escape":return S.ExitCommandLine;default:return S.CaptureInput}},mu=(e,t)=>{if(lu(e,e.sequence))return S.MoveCursorLeftOfWord;if(cu(e,e.sequence))return S.MoveCursorRightOfWord;if(du(e,e.sequence))return S.EraseInputWord;switch(e.name){case"tab":return S.AutoCompleteCommand;case"up":return S.NavPreviousItem;case"down":return S.NavNextItem;case"left":return S.MoveCursorLeft;case"right":return S.MoveCursorRight;case"return":return S.Confirm;case"backspace":return t?S.EraseInput:S.ExitCommandLine;case"escape":return S.ExitCommandLine;default:return S.CaptureInput}};import pu from"string-width";function Bs(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var fn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",wv=/\u001B\[[0-9;]*m/,Za="\x1B[0m",Mv=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),ed=(e,t)=>{if(t<=0)return"";if(pu(e)<=t)return e;if(t<=3)return"...".slice(0,t);let r=t-3,o="",s=0,i=!1;for(let l of e.split(/(\u001B\[[0-9;]*m)/))if(l!==""){if(wv.test(l)){o+=l,i=l!==Za&&l!=="\x1B[m";continue}for(let c of Mv(l)){let m=pu(c);if(s+m>r)return`${o}...${i?Za:""}`;o+=c,s+=m}}return`${o}...${i?Za:""}`},Se=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),fu=e=>e.charAt(0).toUpperCase()+e.slice(1);var gu=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},hu=(e,t)=>t?e.get(t)??[]:[];var yu=new WeakMap,Pv=e=>{let t=yu.get(e);return t||(t=gu(e),yu.set(e,t)),t};var vu=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return hu(Pv(e),r).filter(s=>Bs(r,s)>=n)};var Lv={hint:"",hints:[],overlap:0,remainder:""},bu=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Lv;let o=vu({wordList:r,inputToMatch:e,overlapThreshold:1});return kv(t,o)},kv=(e,t)=>{let n=t[0]??"",r=Bs(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,l=!!s,p=(l&&i?o:n)+(l&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}};import{ulid as Fv}from"ulid";var vo=24n,Dv=vo*4n,Vt=(1n<<Dv)-1n,Bv=/^[0-9a-f]+$/;function xu(e){return!e||!Bv.test(e)?a(`Invalid hex rank: ${e}`):u("Converted rank to bigint",BigInt("0x"+e))}function vt(e,t=vo){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 Ze(e,t){if(!e&&!t)return vt(Vt/2n,vo);let n=e?xu(e):u("Resolved lower bound",0n);if(d(n))return n;let r=t?xu(t):u("Resolved upper bound",Vt);if(d(r))return r;let o=n.value,s=r.value;if(s<=o)return a("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):vt(i,vo)}function Iu(e){if(e<=0)return u("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Vt*BigInt(r+1)/(t+1n),s=vt(o,vo);if(d(s))return s;n.push(s.value)}return u("Resolved evenly spaced ranks",n)}var td=(e,t)=>{let n=ae(e),r=Iu(n.length);if(d(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],l=r.value[s];if(!i||!l)return a("Unable to assign rebalance rank");o[i.id]=l}return u("Created rebalance event",{id:Fv(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as Tb}from"ulid";var fe={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var _=e=>e.slice(-7).toUpperCase(),Fs=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?_(e).includes(n):!0};var ge={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:V.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:_(e)},context:V.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:V.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:V.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:V.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:_(e)},context:V.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:V.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:V.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};var Ov=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[he,Os]=Ov;var nd=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),F=(e,t)=>({...nd(e,t),convergence:!0}),xo=e=>d(e)&&e.convergence===!0,gn=e=>{let t=e.filter(d);return{fatal:t.filter(n=>!xo(n)),skipped:t.filter(xo)}},hn=e=>{e.length!==0&&z.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},Su=e=>{let t=R.getNode(e);if(!t||!P(t)||t.isDeleted)return null;let n=Cu(t);return d(n)?n:null},Eu=e=>{if(!od())return null;for(let t of e){let n=Su(t);if(n)return n;let r=h().nodes[t]?.parentNodeId;if(!r)continue;let o=Su(r);if(o)return o}return null},_v=(e,t)=>{let n=R.getNode(e);n&&R.updateNode({...n,log:[...n.log??[],t]})},Uv=e=>{let t=[e],n=h().nodes[e]?.parentNodeId;return n&&t.push(n),t},rd=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 Uv(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"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":default:return[]}},jv=e=>{we(t=>({...t,eventLog:[...t.eventLog,e]}))},$v=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?nd("Invalid user ID format",e):u("Valid user",null)},ot=null,Hv=e=>{for(let[t,n]of e.nodeLog){let r=R.getNode(t);r&&R.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&we(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),Eu([...e.virtualNodeIds])},Wv=(e,t)=>{let n=$v(e);if(d(n))return n;let r=[...new Set(rd(e))];if(ot){for(let s of r){if(!t){let i=ot.nodeLog.get(s);i?i.push(e):ot.nodeLog.set(s,[e])}if(od()){ot.virtualNodeIds.add(s);let i=h().nodes[s]?.parentNodeId;i&&ot.virtualNodeIds.add(i)}}return t||ot.appLog.push(e),null}t||(r.forEach(s=>_v(s,e)),jv(e));let o=Eu(r);return o||null},bo=(e,t,n)=>R.getNode(e)?F(`a node with id ${e} already exists`,n):t===e?F("a node cannot be its own parent",n):null,Gv={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=ge.workspace(t,n,r),s=Io(o);if(d(s))return nd(s.message,e);let i=R.createNode(o);return d(i)?F(i.message??"Failed to initialize workspace",e):Qa(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=bo(t,void 0,e);if(o)return o;let s=R.createNode(ge.workspace(t,n,r));return d(s)?F(s.message??"Failed to add workspace",e):Qa(s.value)?u("Added workspace",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=bo(t,r,e);if(s)return s;let i=R.createNode(ge.board(t,n,r,o));return d(i)?F(i.message??"Unable to create board",e):Nr(i.value)?u("Added board",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=bo(t,r,e);if(s)return s;let i=R.createNode(ge.swimlane(t,n,r,o));return d(i)?F(i.message??"Unable to create swimlane",e):mt(i.value)?u("Added swimlane",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=bo(t,r,e);if(s)return s;let i=R.createNode(ge.ticket(t,n,r,o));return d(i)?F(i.message??"Unable to create issue",e):P(i.value)?u("Added issue",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=bo(t,r,e);if(i)return i;let l=R.createNode(ge.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(fe.DESCRIPTION)?"vertical":"horizontal"}));return d(l)?F(l.message??`Unable to create field: ${n}`,e):ut(l.value)?u("Added field",{action:e.action,result:l.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!R.getNode(t))return F(`Unable to locate node with id ${t}`,e);let o=R.renameNode(t,n);return d(o)?F(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=R.tombstoneNode(t);return d(n)?F(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=R.createTag({id:t,name:n});return d(r)?F(r.message??"Unable to create tag",e):u("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=R.tombstoneTag(t);return d(n)?F(n.message??"Unable to delete tag",e):u("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=R.restoreTag(t,n);return d(r)?F(r.message??"Unable to restore tag",e):u("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=R.createContributor({id:t,name:n});return d(r)?F(r.message??"Unable to create contributor",e):u("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=R.renameContributor(t,n);return d(r)?F(r.message??"Unable to rename contributor",e):u("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=R.tombstoneContributor(t);return d(n)?F(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=R.restoreContributor(t,n);return d(r)?F(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=R.tag(t,n);return d(r)?F(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=R.untag(t,n);return d(r)?F(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=R.assign(t,n);return d(r)?F(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=R.unassign(t,n);return d(r)?F(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=R.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?F(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=R.editValue(t,n);return d(r)?F(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=R.getNode(t);if(!o)return F("Unable to locate issue",e);if(!P(o))return F("Can only close issues",e);let s=R.getNode(he);if(!s)return F("Unable to locate target swimlane",e);if(n!==s.id)return F("Close target must be closed swimlane",e);let i=R.moveNodeToRank({id:t,parentId:n,rank:r});return d(i)?F(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=R.getNode(t);if(!o)return F("Unable to locate issue",e);if(!P(o))return F("Can only reopen issues",e);let s=R.getNode(he);if(!s)return F("Unable to locate closed swimlane",e);if(n===s.id)return F("Cannot reopen issue into closed swimlane",e);if(!R.getNode(n))return F("Reopen parent no longer exists",e);let l=R.moveNodeToRank({id:t,parentId:n,rank:r});return d(l)?F(l.message??"Unable to reopen issue",e):u("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=R.lockNode(t);return d(n)?F(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=R.getNode(r);if(!s)return F(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return F(`Node ${r} is not child of ${t}`,e);let i=R.updateNode({...s,rank:o});if(d(i))return F(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=R.createComment({id:t,issue:n,authorId:r,authorName:R.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return d(s)?F(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=R.getComment(t);if(!o)return F("Unable to locate comment",e);if(o.issue!==n)return F("Comment does not belong to issue",e);let s=R.editComment(t,r);return d(s)?F(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=R.getComment(t);if(!r)return F("Unable to locate comment",e);if(r.issue!==n)return F("Comment does not belong to issue",e);let o=R.deleteComment(t);return d(o)?F(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,l=R.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return d(l)?F(l.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=R.getAttachment(t);if(!r)return F("Unable to locate attachment",e);if(r.issue!==n)return F("Attachment does not belong to issue",e);let o=R.deleteAttachment(t);return d(o)?F(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=R.linkUserId({contributorId:t,userId:e.userId});return d(n)?F(n.message??"Unable to link contributor",e):u("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function An(e,t=!1){let n=Gv[e.action];if(!n)return a(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);if(!bt()&&e.action!=="init.workspace")return F(`${e.action} arrived before the workspace was initialized`,e);if(e.action==="init.workspace"&&ot){if(ot.genesisApplied)return F("the workspace is already initialized",e);ot.genesisApplied=!0}let r;try{r=n(e)}catch(s){return F(`threw while materializing (${s instanceof Error?s.message:String(s)})`,e)}if(d(r))return r;let o=Wv(e,t);return o||r}var Lt=e=>{let t=Ru(()=>{let n=ot===null;n&&(ot={appLog:[],nodeLog:new Map,virtualNodeIds:new Set,genesisApplied:!1});try{let r=e.map(o=>An(o));if(n&&ot){let o=Hv(ot);if(o)return e.map(()=>o)}return r}finally{n&&(ot=null)}});return d(t)?e.map(()=>a(t.message)):t.value};import fd from"node:path";import{decodeTime as hb,monotonicFactory as yb}from"ulid";import{z as Qn}from"zod";var sd=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown";import Ae from"node:fs";import Jn from"node:path";import{ulid as Vv}from"ulid";var Us="~pending",id=/~pending(-[0-9a-z]+)*$/i,Au=/-f(\d+)$/,Tu=e=>{let t=e.indexOf(".");return t===-1?`${e}${Us}`:e.slice(0,t)+Us+e.slice(t)},ad=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},wu=e=>{let[t,n]=ad(e);return id.test(t)?t.replace(id,"")+n:null},Mu=e=>e.replace(id,""),js=e=>e.endsWith(".jsonl")&&wu(e)!==null,Pu=e=>{let[t]=ad(e),n=Au.exec(t);return n&&js(e)?Number(n[1]):null},zv=e=>Tu(e).replace(Us,`${Us}-${Vv().toLowerCase()}`),Kv=(e,t)=>{let[n,r]=ad(e);return`${n.replace(Au,"")}-f${t}${r}`},Lu=(e,t)=>Jn.join(Pt(e),Tu(t)),qv=(e,t)=>Math.max(0,Ae.statSync(e).size-(Pu(t)??0)),ku=e=>{let t=Pt(e);try{return Ae.existsSync(t)?Ae.readdirSync(t).filter(js).some(n=>qv(Jn.join(t,n),n)>0):!1}catch{return!0}},Yv=3,Du=(e,t)=>{for(let n=1;;n++){let r=Ae.openSync(e,"a"),o;try{Ae.writeSync(r,t),o=Ae.fstatSync(r).ino}finally{Ae.closeSync(r)}let s;try{s=Ae.statSync(e).ino}catch{s=null}if(s===o||n>=Yv)return}},Xv=e=>{let t;try{t=Ae.openSync(e,"r")}catch{return!0}try{let{size:n}=Ae.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return Ae.readSync(t,r,0,1,n-1),r[0]===10}finally{Ae.closeSync(t)}},_s=10,Nu=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(_s)+1;if(r===0)return{bytes:0,lines:0};let o=t.subarray(0,r);if(o.toString("utf8").trim().length===0)return{bytes:r,lines:0};Ae.appendFileSync(e,Buffer.concat([Buffer.from(Xv(e)?"":`
|
|
29
|
-
`),o,Buffer.from(o[o.length-1]===
|
|
30
|
-
`)]));let s=0;for(let i of o)i===
|
|
31
|
-
`).entries()){let m=c.trim();if(!m)continue;let p;try{p=JSON.parse(m)}catch{i(l+1,"invalid JSON");continue}let f=
|
|
32
|
-
`),n&&(n.current=c);let f=fd.basename(i.value);return Wu(t,f,c),_u(t,f),u("Event persisted",{path:i.value,entry:p.value})}catch(o){let s=o instanceof Error?o.message:"Unknown persist error";return a(`Failed to persist event: ${s}`)}}function Xu(e,t,n){let r=gd(t,n);if(d(r))return a(r.message);let o={...e,id:r.value[0]},s=An(o);if(s.status!==En.Success)return s;let i=qs({event:o,rootDir:t,edge:n,id:r.value});return d(i)?i:s}function B(e,t){if(e.length===0||!e[0])return a("No events provided");if(h().readOnly)return a(h().readOnlyReason??"Cannot change the board while time travelling");let n={},r=wb(e[0],t,n);if(d(r))return r;let o=e.map(i=>Xu(i,t,n)),s=o.filter(d);return s.length>0?a("Materialize and persist failed: "+s.map(i=>i.message).join(", ")):u("Materialization succeeded",o.map(i=>i.value))}var wb=(e,t,n)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return u("Contributor write already in flight",void 0);let r=R.getContributor(e.userId),o={id:Tb(),action:r?"rename.contributor":"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName};if(r&&(r.tombstoned||r.name===e.userName))return u("Contributor name is current",void 0);let s=Xu(o,t,n);return d(s)?a(s.message):u("Contributor name recorded",void 0)};var er=e=>e.trim().toLocaleLowerCase(),hd=(e,t)=>er(e).includes(er(t));var Mb=e=>{let{tags:t}=h();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},Pb=e=>{let{contributors:t}=h();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},Ju=null,Qu=new Map,Lb=()=>{let e=h().eventLog??[];if(e===Ju)return Qu;let t=new Map;for(let n of e){if(!n.userId)continue;let r=n.payload;for(let o of[r.id,r.issue]){if(typeof o!="string")continue;let s=t.get(o)??new Set;s.add(n.userId),t.set(o,s)}}return Ju=e,Qu=t,t},kb=e=>{let{contributors:t}=h(),n=Lb().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},Zu=(e,t)=>{let n=er(t.value);if(!n)return!0;switch(t.target){case"title":return hd(e.title??"",n);case"description":return hd(e.props.description??"",n);case"tag":return Mb(e).map(er).some(o=>o.includes(n));case"assignee":return Pb(e).map(er).some(o=>o.includes(n));case"actor":return kb(e).map(er).some(o=>o.includes(n));case"ref":return Fs(e.id,t.value);default:return!0}};var em=(e,t)=>e.rank.localeCompare(t.rank),Db=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,tm=(e,t)=>Object.values(e).filter(n=>Db(n,t)).sort(em),nm=(e,t)=>{let n={};for(let r of Object.values(e)){if(P(r)&&t.length>0&&!t.every(s=>Zu(r,s))||!r.parentNodeId||r.isDeleted)continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(em);return n};var rm=e=>Ys(ae(e),{at:"end"}),Ys=(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(Ze(void 0,void 0));let r=()=>n(Ze(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(Ze(void 0,o.rank)):a("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(Ze(o.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let o=om(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(Ze(i?.rank,s.rank))}case"after":{let o=om(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(Ze(s.rank,i?.rank))}}},ae=e=>{let t=h();if(!im()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return tm(t.nodes,e)},om=(e,t)=>e.findIndex(n=>n.id===t),sm=(e,t,n={at:"end"})=>Ys(ae(t).filter(r=>r.id!==e),n),Kt=(e,t,n,r,o)=>{let s=sm(t,e,n);if(d(s))return s;if(!s.value.needsRebalance)return u("Resolved rank",s.value.rank);let i=td(e,r);if(d(i))return i;let l=B([i.value],o);if(d(l))return l;let c=sm(t,e,n);return d(c)?c:c.value.needsRebalance?a("Rank rebalance failed to create space"):u("Resolved rank after rebalance",c.value.rank)},Pn=(e,t,n)=>{let r=rm(e);if(d(r))return r;if(!r.value.needsRebalance)return u("Resolved rank",r.value.rank);let o=td(e,t);if(d(o))return o;let s=B([o.value],n);if(d(s))return s;let i=rm(e);return d(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):u("Resolved rank after rebalance",i.value.rank)};var O={exit(){process.exit(0)},enterChildNode(){let e=h(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=q(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||O.navigate({contextNode:o,selectedIndex:q(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=h();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=q(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;O.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>am(1),navigateToPreviousItem:()=>am(-1),navigateToNextContainer:()=>dm(1),navigateToPreviousContainer:()=>dm(-1),navigate:({contextNode:e,selectedIndex:t})=>{N({contextNodeId:e.id,selectedIndex:t})}},am=e=>{let{selectedIndex:t,contextNode:n}=h(),r=q(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;O.navigate({selectedIndex:s,contextNode:n})},dm=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=h();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=q(o.id),i=s.findIndex(g=>g.id===t.id);if(i<0)return;let l=s.at(i+e)??s.at(0);if(!l)return;let c=q(l.id),m=Math.max(0,c.length-1),p=Math.min(Math.max(0,r),m),f=c.length?p:-1;O.navigate({contextNode:l,selectedIndex:f})};var cm=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),um=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=h();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},Bb=e=>{let t=h().nodes[e];return!!t&&!t.isDeleted&&ut(t)&&t.childRenderAxis==="vertical"},Xs=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r||r.isDeleted)return!1;let o=ae(r.id);return O.navigate({contextNode:r,selectedIndex:cm(t,o.length)}),!0},mm=e=>{let{nodes:t}=h(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Xs(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=ae(o.id).findIndex(l=>l.id===n.id);return i>=0?(O.navigate({contextNode:o,selectedIndex:i}),!0):mm(o.id)},lm=e=>{let{nodes:t}=h(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),mm(n))return!0;n=t[n]?.parentNodeId}return!1},Fb=e=>{if(!e)return!1;let t=h().nodes[e];return!!t&&!t.isDeleted},pm=e=>{let{nodes:t,rootNodeId:n}=h();if(Bb(e.contextNodeId)&&Xs(e.contextNodeId,e.selectedIndex))return u("Restored navigation inside text container",null);if(Fb(e.selectedNodeId)&&e.selectedNodeId&&lm(e.selectedNodeId))return u("Restored navigation to selected node or ancestor",null);if(Xs(e.contextNodeId,e.selectedIndex))return u("Restored navigation to previous container",null);if(e.parentNodeId&&Xs(e.parentNodeId,e.selectedIndex))return u("Restored navigation to previous parent",null);if(lm(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=ae(r.id);return O.navigate({contextNode:r,selectedIndex:cm(e.selectedIndex,o.length)}),u("Restored navigation to root",null)};import{monotonicFactory as Ob,ulid as qt}from"ulid";var Eo=Ob();function _b(){let e=et();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)return a("No workspace found in event log");let[r]=q(n.id),[o]=r?q(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}):u("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function Ub(){let e=_b();return d(e)?e:O.navigate(e.value)}function fm({userId:e,userName:t}){let n=Eo(),r=Eo(),o=Eo(),s=Eo(),i=Eo(),l=Ze(void 0,void 0);if(d(l))return l;let c=Ze(void 0,void 0);if(d(c))return c;let m=Ze(c.value,void 0);if(d(m))return m;let p=Ze(void 0,void 0);if(d(p))return p;let f=Ze(p.value,void 0);if(d(f))return f;let g=Ze(f.value,void 0);if(d(g))return g;let v=Ze(void 0,void 0);return d(v)?v:u("Created default events",[{id:qt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:qt(),userId:e,userName:t,action:"create.contributor",payload:{id:e,name:t}},{id:qt(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:c.value}},{id:qt(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:qt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:qt(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:g.value}},{id:qt(),userId:e,userName:t,action:"add.board",payload:{id:Os,name:"Closed",parent:n,rank:m.value}},{id:qt(),userId:e,userName:t,action:"add.swimlane",payload:{id:he,name:"Closed",parent:Os,rank:v.value}},{id:qt(),userId:e,userName:t,action:"lock.node",payload:{id:Os}},{id:qt(),userId:e,userName:t,action:"lock.node",payload:{id:he}}])}var jb=()=>{let e=et();if(d(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},$b=e=>{if(e.length===0)return;let t=e.filter(r=>r.reason==="corrupt-line"||r.reason==="invalid-payload"),n=e.filter(r=>r.reason==="unsupported-schema-version"||r.reason==="unknown-action");if(n.length>0){let r=[...new Set(n.map(o=>o.detail))].join(", ");z.info(`This build cannot read ${n.length} event(s) in the log (${r}). They are skipped, so anything they changed may be out of date until you upgrade.`)}if(t.length>0){let r=[...new Set(t.map(o=>o.detail))].join(", ");z.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}};function Dt(e,t=[]){if(jb())return u("Skipped boot while checked out at a historical point",null);if(!e.length){let s=ge.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=Io(s);return d(i)?i:(N({hasProjectDefinition:!1,mode:b.DEFAULT}),u("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return a("Initialized Epiq project has no workspace init event");let n=Lt(e),{fatal:r,skipped:o}=gn(n);return r.length>0?a(`Materializing failed:
|
|
27
|
+
${o.message}`);let s=await Sr({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:r});return d(s)?a(s.message):u("Cleaned storage branch",!0)},Mt=Pa(async(e=process.cwd())=>{let t=await j({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=>rt.resolve(e)),EA=Pa(async e=>{let t=await j({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return a(t.message);let n=t.value.stdout.trim(),r=rt.isAbsolute(n)?n:rt.join(e,n);return u("Resolved git dir",r)},e=>rt.resolve(e));var MA=process.env.IS_LOCAL==="true",Je=".epiq",mn="events",Ga="media",yv="project.json",Yn=e=>Wt.join(e,Je),Cs=e=>Wt.join(Yn(e),yv),Pt=e=>Wt.join(Yn(e),mn),mo=e=>Wt.join(Yn(e),Ga),eu=e=>Wt.join(e,Je),vv=e=>{let t=Wt.join(e,Je);return uo.existsSync(t)&&uo.statSync(t).isDirectory()},po=e=>{let t=Cs(e);return uo.existsSync(t)&&uo.statSync(t).isFile()},Rs=e=>{let t=Wt.resolve(e);for(;;){if(vv(t))return u("Resolved closest .epiq root",t);let n=Wt.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},Va="No .epiq/project.json found in any parent",xe=e=>{let t=Wt.resolve(e);for(;;){if(po(t))return u("Resolved closest epiq project root",t);let n=Wt.dirname(t);if(n===t)return a(Va);t=n}},tu=e=>{let t=Pt(e);try{return uo.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")}},Gt=async()=>{let e=await Mt(process.cwd());if(d(e))return e;let t=ue({repoRoot:e.value});return d(t)?t:u("Resolved persist root",t.value)};import{accessSync as bv,copyFileSync as xv,existsSync as Ls,mkdirSync as nu,readdirSync as ru,readFileSync as Iv,renameSync as Sv,rmSync as Ev,statSync as ou,unlinkSync as Cv,writeFileSync as Rv}from"node:fs";import Er from"node:path";var za=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",$e={writeToFile:(e,t)=>{try{let n=Er.dirname(e);Ls(n)||nu(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Rv(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Iv(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=$e.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 Ls(e)&&ou(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await bv(e),!0}catch{return!1}},mkDir:e=>nu(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Er.parse(t);for(;;){let r=Er.join(t,e);try{if(Ls(r)&&ou(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Er.dirname(t)}return null},readFirstJSON(e){try{if(!$e.dirExists(e))return null;let t=ru(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Er.join(e,t);return $e.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return $e.dirExists(e)?ru(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Cv(e)}catch(t){(!za(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Ev(e,{recursive:!0,force:!0})}catch(t){(!za(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Er.dirname(t)),!n?.overwrite&&Ls(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Sv(e,t)}catch(r){if(za(r)&&r.code==="EXDEV"){xv(e,t),this.rmFile(e);return}throw r}}};var Av={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},su=pn.object({logLevel:pn.enum(["info","error","debug"]),preferredEditor:pn.string().optional(),userName:pn.string().optional(),userId:pn.string().optional(),autoSync:pn.boolean().nullable().optional(),autoSyncDebounceMs:pn.number().optional(),attachmentMaxKb:pn.number().optional(),viewMode:pn.enum(["dense","wide"]).optional()}).partial(),Tv="config.json",iu=ln,Ka=()=>Nv.join(iu(),Tv),qa=()=>{try{return $e.mkDir(iu()),u(`Ensured ~/${Tt} exists`,null)}catch{return a(`Unable to create ~/${Tt}`)}},wv=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${Tt}/config.json JSON`)}let n=su.safeParse(t??{});return n.success?u("Parsed config",n.data):a(`Invalid ~/${Tt}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Cr=()=>{let e=qa();if(d(e))return a(e.message);let t=Ka(),n=$e.readFile(t);return n==null||n.trim()===""?u("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):wv(n)},au=e=>{let t=qa();if(d(t))return a(t.message);let n=su.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Ka();try{return $e.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
28
|
+
`),u("Config written",null)}catch{return a(`Unable to write ~/${Tt}/config.json`)}},ht=e=>{let t=Cr();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return au(n)},yt=()=>{let e=Ka(),t=qa();if(d(t))return a(`Unable to create ~/${Tt}`);if(!($e.readFile(e)!==null)){let x=au(Av);if(d(x))throw new Error(`Unable to create ~/${Tt}/config.json`)}let r=Cr();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:l,autoSyncDebounceMs:c,attachmentMaxKb:m,logLevel:p,viewMode:f}=r.value,g=Ir({userId:i,userName:s});if(d(g))return a(g.message);let v=g.value??{userId:i,userName:s};return!v.userName||!v.userId?a(`User name or ID not configured in ~/${Tt}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,u("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:v.userName,userId:v.userId,autoSync:l??!1,autoSyncIntervalMs:c??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))};import{useSyncExternalStore as Mv}from"react";var fo={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Ya=new Set,Pv=()=>{for(let e of Ya)e()},ie=()=>fo,du=()=>Mv(e=>(Ya.add(e),()=>{Ya.delete(e)}),()=>fo),ze=e=>(fo={...fo,...e},Pv(),fo);import{spawn as Lv}from"node:child_process";import Xa from"node:process";var Ja=e=>{let t=Xa.platform==="darwin"?"open":Xa.platform==="win32"?"cmd":"xdg-open",n=Xa.platform==="win32"?["/c","start","",e]:[e];Lv(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as Gh}from"node:fs/promises";import Hn from"chalk";import Rg from"string-width";import{decodeTime as lu}from"ulid";var ks=1440*60*1e3,go=(e,t=Date.now())=>e>t+ks?t:e,Ie=e=>go(lu(e)),Rr=e=>{let t=Date.now()+ks,n=e.find(o=>o!==null&&o<=t)??null;if(n===null)return[...e];let r=null;return e.map(o=>{if(o===null)return null;let s=o<=t?o:r??n;return r=s,s})},Ds=e=>{try{return u("Decoded date",new Date(Ie(e)))}catch(t){return a("Decoding failed + "+t.message)}},Rn=e=>{if(!e?.id)return null;try{return lu(e.id)}catch{return null}};var Bs="removed",Qe=(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")},cu=["png","jpg","gif","webp"];var V={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function Qa(e){return e.context===V.WORKSPACE}function P(e){return e.context===V.TICKET}function Nn(e){return e.context===V.TEXT}function ut(e){return e.context===V.FIELD}function ho(e){return e.context===V.FIELD_LIST}var mt=e=>e.context===V.SWIMLANE,Nr=e=>e.context===V.BOARD,yo=e=>e.context===V.COMMENT;import{useSyncExternalStore as fE}from"react";var b={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var uu=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",mu=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",pu=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",fu=(e,t)=>{if(mu(e,e.sequence))return S.MoveCursorLeftOfWord;if(pu(e,e.sequence))return S.MoveCursorRightOfWord;if(uu(e,e.sequence))return S.EraseInputWord;switch(e.name){case"tab":return S.AutoCompleteCommand;case"up":return S.GetLastCommandFromHistory;case"down":return S.GetNextCommandFromHistory;case"left":return S.MoveCursorLeft;case"right":return S.MoveCursorRight;case"return":return S.Confirm;case"backspace":return t?S.EraseInput:S.ExitCommandLine;case"escape":return S.ExitCommandLine;default:return S.CaptureInput}},gu=(e,t)=>{if(mu(e,e.sequence))return S.MoveCursorLeftOfWord;if(pu(e,e.sequence))return S.MoveCursorRightOfWord;if(uu(e,e.sequence))return S.EraseInputWord;switch(e.name){case"tab":return S.AutoCompleteCommand;case"up":return S.NavPreviousItem;case"down":return S.NavNextItem;case"left":return S.MoveCursorLeft;case"right":return S.MoveCursorRight;case"return":return S.Confirm;case"backspace":return t?S.EraseInput:S.ExitCommandLine;case"escape":return S.ExitCommandLine;default:return S.CaptureInput}};import hu from"string-width";function Fs(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var fn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",kv=/\u001B\[[0-9;]*m/,Za="\x1B[0m",Dv=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),ed=(e,t)=>{if(t<=0)return"";if(hu(e)<=t)return e;if(t<=3)return"...".slice(0,t);let r=t-3,o="",s=0,i=!1;for(let l of e.split(/(\u001B\[[0-9;]*m)/))if(l!==""){if(kv.test(l)){o+=l,i=l!==Za&&l!=="\x1B[m";continue}for(let c of Dv(l)){let m=hu(c);if(s+m>r)return`${o}...${i?Za:""}`;o+=c,s+=m}}return`${o}...${i?Za:""}`},Se=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),yu=e=>e.charAt(0).toUpperCase()+e.slice(1);var vu=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},bu=(e,t)=>t?e.get(t)??[]:[];var xu=new WeakMap,Bv=e=>{let t=xu.get(e);return t||(t=vu(e),xu.set(e,t)),t};var Iu=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return bu(Bv(e),r).filter(s=>Fs(r,s)>=n)};var Fv={hint:"",hints:[],overlap:0,remainder:""},Su=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Fv;let o=Iu({wordList:r,inputToMatch:e,overlapThreshold:1});return Ov(t,o)},Ov=(e,t)=>{let n=t[0]??"",r=Fs(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,l=!!s,p=(l&&i?o:n)+(l&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}};import{ulid as jv}from"ulid";var vo=24n,_v=vo*4n,Vt=(1n<<_v)-1n,Uv=/^[0-9a-f]+$/;function Eu(e){return!e||!Uv.test(e)?a(`Invalid hex rank: ${e}`):u("Converted rank to bigint",BigInt("0x"+e))}function vt(e,t=vo){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 Ze(e,t){if(!e&&!t)return vt(Vt/2n,vo);let n=e?Eu(e):u("Resolved lower bound",0n);if(d(n))return n;let r=t?Eu(t):u("Resolved upper bound",Vt);if(d(r))return r;let o=n.value,s=r.value;if(s<=o)return a("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):vt(i,vo)}function Cu(e){if(e<=0)return u("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Vt*BigInt(r+1)/(t+1n),s=vt(o,vo);if(d(s))return s;n.push(s.value)}return u("Resolved evenly spaced ranks",n)}var td=(e,t)=>{let n=ae(e),r=Cu(n.length);if(d(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],l=r.value[s];if(!i||!l)return a("Unable to assign rebalance rank");o[i.id]=l}return u("Created rebalance event",{id:jv(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as wb}from"ulid";var fe={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var _=e=>e.slice(-7).toUpperCase(),Os=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?_(e).includes(n):!0};var ge={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:V.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:_(e)},context:V.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:V.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:V.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:V.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:_(e)},context:V.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:V.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:V.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};var $v=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[he,_s]=$v;var nd=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),F=(e,t)=>({...nd(e,t),convergence:!0}),xo=e=>d(e)&&e.convergence===!0,gn=e=>{let t=e.filter(d);return{fatal:t.filter(n=>!xo(n)),skipped:t.filter(xo)}},hn=e=>{e.length!==0&&z.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},Ru=e=>{let t=C.getNode(e);if(!t||!P(t)||t.isDeleted)return null;let n=Tu(t);return d(n)?n:null},Nu=e=>{if(!od())return null;for(let t of e){let n=Ru(t);if(n)return n;let r=h().nodes[t]?.parentNodeId;if(!r)continue;let o=Ru(r);if(o)return o}return null},Hv=(e,t)=>{let n=C.getNode(e);n&&C.updateNode({...n,log:[...n.log??[],t]})},Wv=e=>{let t=[e],n=h().nodes[e]?.parentNodeId;return n&&t.push(n),t},rd=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 Wv(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"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":default:return[]}},Gv=e=>{we(t=>({...t,eventLog:[...t.eventLog,e]}))},Vv=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?nd("Invalid user ID format",e):u("Valid user",null)},ot=null,zv=e=>{for(let[t,n]of e.nodeLog){let r=C.getNode(t);r&&C.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&we(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),Nu([...e.virtualNodeIds])},Kv=(e,t)=>{let n=Vv(e);if(d(n))return n;let r=[...new Set(rd(e))];if(ot){for(let s of r){if(!t){let i=ot.nodeLog.get(s);i?i.push(e):ot.nodeLog.set(s,[e])}if(od()){ot.virtualNodeIds.add(s);let i=h().nodes[s]?.parentNodeId;i&&ot.virtualNodeIds.add(i)}}return t||ot.appLog.push(e),null}t||(r.forEach(s=>Hv(s,e)),Gv(e));let o=Nu(r);return o||null},bo=(e,t,n)=>C.getNode(e)?F(`a node with id ${e} already exists`,n):t===e?F("a node cannot be its own parent",n):null,qv={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=ge.workspace(t,n,r),s=Io(o);if(d(s))return nd(s.message,e);let i=C.createNode(o);return d(i)?F(i.message??"Failed to initialize workspace",e):Qa(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=bo(t,void 0,e);if(o)return o;let s=C.createNode(ge.workspace(t,n,r));return d(s)?F(s.message??"Failed to add workspace",e):Qa(s.value)?u("Added workspace",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=bo(t,r,e);if(s)return s;let i=C.createNode(ge.board(t,n,r,o));return d(i)?F(i.message??"Unable to create board",e):Nr(i.value)?u("Added board",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=bo(t,r,e);if(s)return s;let i=C.createNode(ge.swimlane(t,n,r,o));return d(i)?F(i.message??"Unable to create swimlane",e):mt(i.value)?u("Added swimlane",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=bo(t,r,e);if(s)return s;let i=C.createNode(ge.ticket(t,n,r,o));return d(i)?F(i.message??"Unable to create issue",e):P(i.value)?u("Added issue",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=bo(t,r,e);if(i)return i;let l=C.createNode(ge.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(fe.DESCRIPTION)?"vertical":"horizontal"}));return d(l)?F(l.message??`Unable to create field: ${n}`,e):ut(l.value)?u("Added field",{action:e.action,result:l.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!C.getNode(t))return F(`Unable to locate node with id ${t}`,e);let o=C.renameNode(t,n);return d(o)?F(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=C.tombstoneNode(t);return d(n)?F(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=C.createTag({id:t,name:n});return d(r)?F(r.message??"Unable to create tag",e):u("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=C.tombstoneTag(t);return d(n)?F(n.message??"Unable to delete tag",e):u("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=C.restoreTag(t,n);return d(r)?F(r.message??"Unable to restore tag",e):u("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=C.createContributor({id:t,name:n});return d(r)?F(r.message??"Unable to create contributor",e):u("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=C.renameContributor(t,n);return d(r)?F(r.message??"Unable to rename contributor",e):u("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=C.tombstoneContributor(t);return d(n)?F(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=C.restoreContributor(t,n);return d(r)?F(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=C.tag(t,n);return d(r)?F(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=C.untag(t,n);return d(r)?F(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=C.assign(t,n);return d(r)?F(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=C.unassign(t,n);return d(r)?F(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=C.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?F(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=C.editValue(t,n);return d(r)?F(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=C.getNode(t);if(!o)return F("Unable to locate issue",e);if(!P(o))return F("Can only close issues",e);let s=C.getNode(he);if(!s)return F("Unable to locate target swimlane",e);if(n!==s.id)return F("Close target must be closed swimlane",e);let i=C.moveNodeToRank({id:t,parentId:n,rank:r});return d(i)?F(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=C.getNode(t);if(!o)return F("Unable to locate issue",e);if(!P(o))return F("Can only reopen issues",e);let s=C.getNode(he);if(!s)return F("Unable to locate closed swimlane",e);if(n===s.id)return F("Cannot reopen issue into closed swimlane",e);if(!C.getNode(n))return F("Reopen parent no longer exists",e);let l=C.moveNodeToRank({id:t,parentId:n,rank:r});return d(l)?F(l.message??"Unable to reopen issue",e):u("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=C.lockNode(t);return d(n)?F(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=C.getNode(r);if(!s)return F(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return F(`Node ${r} is not child of ${t}`,e);let i=C.updateNode({...s,rank:o});if(d(i))return F(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=C.createComment({id:t,issue:n,authorId:r,authorName:C.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return d(s)?F(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=C.getComment(t);if(!o)return F("Unable to locate comment",e);if(o.issue!==n)return F("Comment does not belong to issue",e);let s=C.editComment(t,r);return d(s)?F(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=C.getComment(t);if(!r)return F("Unable to locate comment",e);if(r.issue!==n)return F("Comment does not belong to issue",e);let o=C.deleteComment(t);return d(o)?F(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,l=C.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return d(l)?F(l.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=C.getAttachment(t);if(!r)return F("Unable to locate attachment",e);if(r.issue!==n)return F("Attachment does not belong to issue",e);let o=C.deleteAttachment(t);return d(o)?F(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=C.linkUserId({contributorId:t,userId:e.userId});return d(n)?F(n.message??"Unable to link contributor",e):u("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function An(e,t=!1){let n=qv[e.action];if(!n)return a(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);if(!bt()&&e.action!=="init.workspace")return F(`${e.action} arrived before the workspace was initialized`,e);if(e.action==="init.workspace"&&ot){if(ot.genesisApplied)return F("the workspace is already initialized",e);ot.genesisApplied=!0}let r;try{r=n(e)}catch(s){return F(`threw while materializing (${s instanceof Error?s.message:String(s)})`,e)}if(d(r))return r;let o=Kv(e,t);return o||r}var Lt=e=>{let t=Au(()=>{let n=ot===null;n&&(ot={appLog:[],nodeLog:new Map,virtualNodeIds:new Set,genesisApplied:!1});try{let r=e.map(o=>An(o));if(n&&ot){let o=zv(ot);if(o)return e.map(()=>o)}return r}finally{n&&(ot=null)}});return d(t)?e.map(()=>a(t.message)):t.value};import yd from"node:path";import{decodeTime as yb,monotonicFactory as vb}from"ulid";import{z as Qn}from"zod";var sd=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown";import Ae from"node:fs";import Jn from"node:path";import{ulid as Yv}from"ulid";var js="~pending",id=/~pending(-[0-9a-z]+)*$/i,Mu=/-f(\d+)$/,Pu=e=>{let t=e.indexOf(".");return t===-1?`${e}${js}`:e.slice(0,t)+js+e.slice(t)},ad=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},Lu=e=>{let[t,n]=ad(e);return id.test(t)?t.replace(id,"")+n:null},ku=e=>e.replace(id,""),$s=e=>e.endsWith(".jsonl")&&Lu(e)!==null,Du=e=>{let[t]=ad(e),n=Mu.exec(t);return n&&$s(e)?Number(n[1]):null},Xv=e=>Pu(e).replace(js,`${js}-${Yv().toLowerCase()}`),Jv=(e,t)=>{let[n,r]=ad(e);return`${n.replace(Mu,"")}-f${t}${r}`},Bu=(e,t)=>Jn.join(Pt(e),Pu(t)),Qv=(e,t)=>Math.max(0,Ae.statSync(e).size-(Du(t)??0)),Fu=e=>{let t=Pt(e);try{return Ae.existsSync(t)?Ae.readdirSync(t).filter($s).some(n=>Qv(Jn.join(t,n),n)>0):!1}catch{return!0}},Zv=3,Ou=(e,t)=>{for(let n=1;;n++){let r=Ae.openSync(e,"a"),o;try{Ae.writeSync(r,t),o=Ae.fstatSync(r).ino}finally{Ae.closeSync(r)}let s;try{s=Ae.statSync(e).ino}catch{s=null}if(s===o||n>=Zv)return}},eb=e=>{let t;try{t=Ae.openSync(e,"r")}catch{return!0}try{let{size:n}=Ae.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return Ae.readSync(t,r,0,1,n-1),r[0]===10}finally{Ae.closeSync(t)}},Us=10,wu=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(Us)+1;if(r===0)return{bytes:0,lines:0};let o=t.subarray(0,r);if(o.toString("utf8").trim().length===0)return{bytes:r,lines:0};Ae.appendFileSync(e,Buffer.concat([Buffer.from(eb(e)?"":`
|
|
29
|
+
`),o,Buffer.from(o[o.length-1]===Us?"":`
|
|
30
|
+
`)]));let s=0;for(let i of o)i===Us&&s++;return o[o.length-1]!==Us&&s++,{bytes:r,lines:s}},Hs=(e,t)=>{let n=Pt(e);if(!Ae.existsSync(n))return u("No events directory",0);try{let r=Ae.readdirSync(n).filter(i=>Lu(i)===t),o=Jn.join(n,t),s=0;for(let i of r){let l=Du(i);if(l!==null){let f=Jn.join(n,i),g=Ae.readFileSync(f).subarray(l);s+=wu(o,g,!0).lines,Ae.rmSync(f,{force:!0});continue}let c=/~pending-/i.test(i)?i:Xv(t),m=Jn.join(n,c);c!==i&&Ae.renameSync(Jn.join(n,i),m);let p=wu(o,Ae.readFileSync(m));s+=p.lines,Ae.renameSync(m,Jn.join(n,Jv(c,p.bytes)))}return u("Folded pending logs",s)}catch(r){return a(`Unable to fold pending event logs in ${n}: ${r instanceof Error?r.message:String(r)}`)}};import Vu from"node:fs";import Vs from"node:path";import{decodeTime as sb}from"ulid";import{z as pd}from"zod";import dd from"node:fs";import tb from"node:path";var So=e=>e?.code==="ENOENT",ld=3,cd=e=>dd.readdirSync(e).filter(t=>t.endsWith(".jsonl")).sort(),zt=e=>{let t=Pt(e);for(let n=1;;n++){if(!dd.existsSync(t))return"none";let r=[],o=!1;for(let s of cd(t))try{let{size:i,mtimeMs:l}=dd.statSync(tb.join(t,s));r.push(`${s}:${i}:${l}`)}catch(i){if(!So(i))throw i;if(n<ld){o=!0;break}}if(!o)return r.join("|")}},_u=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),ud=(e,t,n)=>{let r=_u(t),o=zt(e),s=_u(o);for(let[i,l]of s)if(i!==n&&r.get(i)!==l)return null;for(let i of r.keys())if(i!==n&&!s.has(i))return null;return o},Tn=null,Uu=e=>Tn&&Tn.root===e?Tn.signature:null,ju=(e,t)=>{Tn={root:e,signature:t}},$u=(e,t)=>{if(!Tn||Tn.root!==e)return;let n=ud(e,Tn.signature,t);Tn=n===null?null:{root:e,signature:n}};var nb=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","tombstone.tag","restore.tag","create.contributor","rename.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 rb=new Set(nb),Hu=e=>rb.has(e),Wu=e=>({action:e.action,payload:e.payload});import{z as G}from"zod";var H=G.string().min(1),kt=G.string(),wn=G.string(),Ws=G.looseObject({id:H}),md=G.looseObject({id:H,name:kt,parent:H,rank:wn}),ob={"init.workspace":G.looseObject({id:H,name:kt,rank:wn}),"add.workspace":G.looseObject({id:H,name:kt,rank:wn}),"add.board":md,"add.swimlane":md,"add.issue":md,"add.field":G.looseObject({id:H,name:kt,parent:H,rank:wn}),"edit.title":G.looseObject({id:H,name:kt}),"delete.node":Ws,"lock.node":Ws,"move.node":G.looseObject({id:H,parent:H,rank:wn}),"edit.description":G.looseObject({id:H,md:G.string()}),"close.issue":G.looseObject({id:H,parent:H,rank:wn}),"reopen.issue":G.looseObject({id:H,parent:H,rank:wn}),"create.tag":G.looseObject({id:H,name:kt}),"tombstone.tag":Ws,"restore.tag":G.looseObject({id:H,name:kt}),"create.contributor":G.looseObject({id:H,name:kt}),"rename.contributor":G.looseObject({id:H,name:kt}),"tombstone.contributor":Ws,"restore.contributor":G.looseObject({id:H,name:kt}),"link.contributor.user":G.looseObject({contributor:H}),"add.issue.assignee":G.looseObject({id:H,assignee:H}),"remove.issue.assignee":G.looseObject({id:H,assignee:H}),"add.issue.tag":G.looseObject({id:H,tag:H}),"remove.issue.tag":G.looseObject({id:H,tag:H}),"add.issue.comment":G.looseObject({id:H,issue:H,md:G.string()}),"edit.issue.comment":G.looseObject({id:H,issue:H,md:G.string()}),"delete.issue.comment":G.looseObject({id:H,issue:H}),"add.issue.attachment":G.looseObject({id:H,issue:H,hash:G.string().min(1),ext:G.string().min(1),name:kt,bytes:G.number()}),"delete.issue.attachment":G.looseObject({id:H,issue:H}),"rebalance.children":G.looseObject({parent:H,ranks:G.record(G.string(),wn)})},Gu=(e,t)=>{let r=ob[e].safeParse(t);return r.success?u("Payload is readable",void 0):a(`${e}: ${r.error.issues.map(o=>`${o.path.join(".")||"payload"} ${o.message}`).join(", ")}`)};var ib=pd.object({userId:pd.string().min(1).default("unknown"),userName:pd.string().min(1).default("unknown")}),Gs=e=>{let t=Object.entries(e).filter(([o])=>o!=="id"&&o!=="v"&&o!=="userId"&&o!=="userName");if(t.length!==1)return null;let n=t[0]?.[1];if(typeof n!="object"||n===null)return null;let r=n.id;return typeof r=="string"&&r.length>0?r:null},ab=/^[0-9a-hjkmnp-tv-z]{26}$/i,db=e=>ab.test(e)?e.toUpperCase():e,lb=e=>{let t=Vs.basename(e,".jsonl"),n=t.indexOf("."),r=ku(n===-1?t:t.slice(0,n)),o=n===-1?void 0:t.slice(n+1),s=ib.safeParse({userId:db(r),userName:o});return s.success?u("Parsed event file actor",s.data):a(`Invalid event file name ${Vs.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},cb=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])},ub=(e,t)=>t in e,mb=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),pb=e=>{let{userId:t,userName:n,...r}=e,o=cb(r);if(d(o))return a(o.message);let s=o.value,i=e.id?.[0];return i?ub(r,s)?u("Decoded persisted event",mb({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")},gd=(e,t)=>{let n=[],r=new Map,o=new Map;for(let s of e){if(!Xu(s.v)){o.set(s.v,(o.get(s.v)??0)+1),t?.push({eventId:s.id[0],reason:"unsupported-schema-version",detail:`v${s.v}`,targetNodeId:Gs(s)});continue}let i=pb(s);if(d(i)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:i.message,targetNodeId:Gs(s)});continue}let l=i.value.action;if(!Hu(l)){r.set(l,(r.get(l)??0)+1),t?.push({eventId:s.id[0],reason:"unknown-action",detail:l,targetNodeId:Gs(s)});continue}let c=Gu(l,i.value.payload);if(d(c)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:c.message,targetNodeId:Gs(s)});continue}n.push(i.value)}if(r.size>0){let s=[...r.entries()].map(([i,l])=>`${i} (x${l})`).join(", ");z.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${s}. Upgrade to apply them.`)}if(o.size>0){let s=[...o.entries()].map(([i,l])=>`v${i} (x${l})`).join(", ");z.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${s}. Upgrade to apply them.`)}return u("Decoded reconstructed events",n)},fb=(e,t)=>{let n=lb(e);if(d(n))return a(n.message);let r;try{r=Vu.readFileSync(e,"utf8")}catch(l){if(So(l))return u("Event file missing",null);throw l}let o=[],s=Vs.basename(e),i=(l,c)=>{t?.push({eventId:null,reason:"corrupt-line",detail:`${s}:${l} (${c})`,targetNodeId:null})};for(let[l,c]of r.split(`
|
|
31
|
+
`).entries()){let m=c.trim();if(!m)continue;let p;try{p=JSON.parse(m)}catch{i(l+1,"invalid JSON");continue}let f=Yu(p);if(d(f)){i(l+1,f.message);continue}o.push({...f.value,userId:n.value.userId,userName:n.value.userName})}return u("Parsed persisted events file",o)};function Eo(e,t){let n=Pt(e),r=zt(e);if(!Vu.existsSync(n))return u("No events found",[]);let o=[],s=[];for(let l=1;;l++){o=[],s=[];let c=!1;for(let m of cd(n)){let p=fb(Vs.join(n,m),s);if(d(p))return a(p.message);if(p.value===null){if(l<ld){c=!0;break}continue}o.push(...p.value)}if(!c)break}t?.push(...s);let i=gb(o);return yn={root:e,signature:r,edge:i.at(-1)?.id?.[0]??null},u("All events loaded",i)}function xt(e){let t=[],n=Eo(e,t);if(d(n))return a(n.message);let r=gd(n.value,t);return d(r)?a(r.message):u("Loaded merged events",{events:r.value,unreadable:t})}function hd(e){let t=Eo(e);return d(t)?a(t.message):u("Loaded event actors",t.value.map(({userId:n,userName:r})=>({userId:n,userName:r})))}function Mn(e){let t=xt(e);return d(t)?a(t.message):u("Loaded merged events",t.value.events)}function zs(e,t){let n=Eo(e);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=hb(n.value,t),s=gd(r);if(d(s))return a(s.message);let i=gd(o);return d(i)?a(i.message):u("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:i.value})}var yn=null;function zu(e=process.cwd()){let t=zt(e);if(yn&&yn.root===e&&yn.signature===t)return u("Loaded edge reference, unchanged",yn.edge);let n=Eo(e);return d(n)?a(n.message):u("Loaded edge reference",n.value.at(-1)?.id?.[0]??null)}function Ku(e,t,n){if(!yn||yn.root!==e)return;let r=ud(e,yn.signature,t);yn=r===null?null:{root:e,signature:r,edge:n}}var fd=(e,t)=>{let n=e.id[0].localeCompare(t.id[0]);return n!==0?n:JSON.stringify(e).localeCompare(JSON.stringify(t))},gb=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(fd);let r=[],o=new Set,s=m=>{let p=[m];for(;p.length>0;){let f=p.pop(),g=f.id[0];if(o.has(g))continue;r.push(f),o.add(g);let v=n.get(g)??[];for(let x=v.length-1;x>=0;x--)p.push(v[x])}},i=(n.get(null)??[]).filter(m=>{let p=Object.keys(m).filter(f=>f!=="id"&&f!=="v"&&f!=="userId"&&f!=="userName");return p.length===1&&p[0]==="init.workspace"});for(let m of i)s(m);let l=e.filter(m=>{let p=m.id[0],f=m.id[1]??null;return o.has(p)?!1:f===null||!t.has(f)}).sort(fd);for(let m of l)s(m);let c=e.filter(m=>!o.has(m.id[0])).sort(fd);for(let m of c)s(m);return r},qu=e=>Rr(e.map(t=>{try{return sb(t.id[0])}catch{return null}}));function Ks(e){let t=Eo(e);if(d(t))return a(t.message);let n=qu(t.value);return u("Loaded effective event times",new Map(t.value.map((r,o)=>[r.id[0],n[o]??null])))}var hb=(e,t)=>{let n=new Set,r=[],o=[],s=qu(e);for(let i=0;i<e.length;i++){let l=e[i],c=l.id[0],m=l.id[1],p=s[i]??null;!(p!==null&&p<t)||m&&n.has(m)?(n.add(c),o.push(l)):r.push(l)}return{appliedEvents:r,unappliedEvents:o}};var Qu=1,Ju=vb(),bb=0xffffffffffff,xb=ks,Ib=e=>{let t=Date.now(),n;try{n=yb(e)}catch{return t}return n>=bb?t:n>t+xb?(z.error("[persist] edge id is too far in the future; seeding from the wall clock instead",{edgeRef:e,edgeTime:n,now:t}),t):Math.max(t,n+1)},Zu=Qn.tuple([Qn.string().min(1),Qn.string().min(1).nullable()]),Sb=Qn.looseObject({v:Qn.literal(Qu),id:Zu}),Eb=Qn.looseObject({v:Qn.number().int().positive(),id:Zu}),Yu=e=>{let t=Eb.safeParse(e);return t.success?u("Parsed persisted event envelope",t.data):a(`Invalid persisted event envelope: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Cb=[1];var Rb=new Set(Cb),Xu=e=>Rb.has(e),Nb=e=>{let t=Sb.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(", ")}`)},ee=()=>{let{userName:e,userId:t}=ie();return e?t?wa(t)?Is(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")},Zn=({userId:e,userName:t})=>`${sd(e)}.${sd(t)}.jsonl`,Ab=(e,{userId:t,userName:n})=>{let r=Zn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return a(`Invalid event log file name: ${r}`);let s=yd.join(Pt(e),r);return u("Successfully resolved event log path",s)},Tb=(e,t)=>{let n={[e.action]:e.payload,v:Qu,id:t};return Nb(n)};function vd(e,t){let n;if(t&&t.current!==void 0)n=t.current;else{let o=zu(e);if(d(o))return a(o.message);n=o.value}let r=n?Ju(Ib(n)):Ju();return u("Minted event id",[r,n])}function qs({event:e,rootDir:t,edge:n,id:r}){try{let o=tu(t);if(d(o))return o;let s=Ab(t,{userId:e.userId,userName:e.userName});if(d(s))return s;let i=u("Resolved pending event log path",Bu(t,yd.basename(s.value))),l=r?u("Minted event id",r):vd(t,n);if(d(l))return a(l.message);let[c,m]=l.value,p=Tb(Wu(e),[c,m]);if(d(p))return a(p.message);Ou(i.value,`${JSON.stringify(p.value)}
|
|
32
|
+
`),n&&(n.current=c);let f=yd.basename(i.value);return Ku(t,f,c),$u(t,f),u("Event persisted",{path:i.value,entry:p.value})}catch(o){let s=o instanceof Error?o.message:"Unknown persist error";return a(`Failed to persist event: ${s}`)}}function em(e,t,n){let r=vd(t,n);if(d(r))return a(r.message);let o={...e,id:r.value[0]},s=An(o);if(s.status!==En.Success)return s;let i=qs({event:o,rootDir:t,edge:n,id:r.value});return d(i)?i:s}function B(e,t){if(e.length===0||!e[0])return a("No events provided");if(h().readOnly)return a(h().readOnlyReason??"Cannot change the board while time travelling");let n={},r=Mb(e[0],t,n);if(d(r))return r;let o=e.map(i=>em(i,t,n)),s=o.filter(d);return s.length>0?a("Materialize and persist failed: "+s.map(i=>i.message).join(", ")):u("Materialization succeeded",o.map(i=>i.value))}var Mb=(e,t,n)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return u("Contributor write already in flight",void 0);let r=C.getContributor(e.userId),o={id:wb(),action:r?"rename.contributor":"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName};if(r&&(r.tombstoned||r.name===e.userName))return u("Contributor name is current",void 0);let s=em(o,t,n);return d(s)?a(s.message):u("Contributor name recorded",void 0)};var er=e=>e.trim().toLocaleLowerCase(),bd=(e,t)=>er(e).includes(er(t));var Pb=e=>{let{tags:t}=h();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},Lb=e=>{let{contributors:t}=h();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},tm=null,nm=new Map,kb=()=>{let e=h().eventLog??[];if(e===tm)return nm;let t=new Map;for(let n of e){if(!n.userId)continue;let r=n.payload;for(let o of[r.id,r.issue]){if(typeof o!="string")continue;let s=t.get(o)??new Set;s.add(n.userId),t.set(o,s)}}return tm=e,nm=t,t},Db=e=>{let{contributors:t}=h(),n=kb().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},rm=(e,t)=>{let n=er(t.value);if(!n)return!0;switch(t.target){case"title":return bd(e.title??"",n);case"description":return bd(e.props.description??"",n);case"tag":return Pb(e).map(er).some(o=>o.includes(n));case"assignee":return Lb(e).map(er).some(o=>o.includes(n));case"actor":return Db(e).map(er).some(o=>o.includes(n));case"ref":return Os(e.id,t.value);default:return!0}};var om=(e,t)=>e.rank.localeCompare(t.rank),Bb=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,sm=(e,t)=>Object.values(e).filter(n=>Bb(n,t)).sort(om),im=(e,t)=>{let n={};for(let r of Object.values(e)){if(P(r)&&t.length>0&&!t.every(s=>rm(r,s))||!r.parentNodeId||r.isDeleted)continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(om);return n};var am=e=>Ys(ae(e),{at:"end"}),Ys=(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(Ze(void 0,void 0));let r=()=>n(Ze(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(Ze(void 0,o.rank)):a("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(Ze(o.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let o=dm(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(Ze(i?.rank,s.rank))}case"after":{let o=dm(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(Ze(s.rank,i?.rank))}}},ae=e=>{let t=h();if(!cm()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return sm(t.nodes,e)},dm=(e,t)=>e.findIndex(n=>n.id===t),lm=(e,t,n={at:"end"})=>Ys(ae(t).filter(r=>r.id!==e),n),Kt=(e,t,n,r,o)=>{let s=lm(t,e,n);if(d(s))return s;if(!s.value.needsRebalance)return u("Resolved rank",s.value.rank);let i=td(e,r);if(d(i))return i;let l=B([i.value],o);if(d(l))return l;let c=lm(t,e,n);return d(c)?c:c.value.needsRebalance?a("Rank rebalance failed to create space"):u("Resolved rank after rebalance",c.value.rank)},Pn=(e,t,n)=>{let r=am(e);if(d(r))return r;if(!r.value.needsRebalance)return u("Resolved rank",r.value.rank);let o=td(e,t);if(d(o))return o;let s=B([o.value],n);if(d(s))return s;let i=am(e);return d(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):u("Resolved rank after rebalance",i.value.rank)};var O={exit(){process.exit(0)},enterChildNode(){let e=h(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=q(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||O.navigate({contextNode:o,selectedIndex:q(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=h();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=q(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;O.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>um(1),navigateToPreviousItem:()=>um(-1),navigateToNextContainer:()=>mm(1),navigateToPreviousContainer:()=>mm(-1),navigate:({contextNode:e,selectedIndex:t})=>{N({contextNodeId:e.id,selectedIndex:t})}},um=e=>{let{selectedIndex:t,contextNode:n}=h(),r=q(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;O.navigate({selectedIndex:s,contextNode:n})},mm=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=h();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=q(o.id),i=s.findIndex(g=>g.id===t.id);if(i<0)return;let l=s.at(i+e)??s.at(0);if(!l)return;let c=q(l.id),m=Math.max(0,c.length-1),p=Math.min(Math.max(0,r),m),f=c.length?p:-1;O.navigate({contextNode:l,selectedIndex:f})};var fm=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),gm=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=h();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},Fb=e=>{let t=h().nodes[e];return!!t&&!t.isDeleted&&ut(t)&&t.childRenderAxis==="vertical"},Xs=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r||r.isDeleted)return!1;let o=ae(r.id);return O.navigate({contextNode:r,selectedIndex:fm(t,o.length)}),!0},hm=e=>{let{nodes:t}=h(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Xs(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=ae(o.id).findIndex(l=>l.id===n.id);return i>=0?(O.navigate({contextNode:o,selectedIndex:i}),!0):hm(o.id)},pm=e=>{let{nodes:t}=h(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),hm(n))return!0;n=t[n]?.parentNodeId}return!1},Ob=e=>{if(!e)return!1;let t=h().nodes[e];return!!t&&!t.isDeleted},ym=e=>{let{nodes:t,rootNodeId:n}=h();if(Fb(e.contextNodeId)&&Xs(e.contextNodeId,e.selectedIndex))return u("Restored navigation inside text container",null);if(Ob(e.selectedNodeId)&&e.selectedNodeId&&pm(e.selectedNodeId))return u("Restored navigation to selected node or ancestor",null);if(Xs(e.contextNodeId,e.selectedIndex))return u("Restored navigation to previous container",null);if(e.parentNodeId&&Xs(e.parentNodeId,e.selectedIndex))return u("Restored navigation to previous parent",null);if(pm(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=ae(r.id);return O.navigate({contextNode:r,selectedIndex:fm(e.selectedIndex,o.length)}),u("Restored navigation to root",null)};import{monotonicFactory as _b,ulid as qt}from"ulid";var Co=_b();function Ub(){let e=et();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)return a("No workspace found in event log");let[r]=q(n.id),[o]=r?q(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}):u("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function jb(){let e=Ub();return d(e)?e:O.navigate(e.value)}function vm({userId:e,userName:t}){let n=Co(),r=Co(),o=Co(),s=Co(),i=Co(),l=Ze(void 0,void 0);if(d(l))return l;let c=Ze(void 0,void 0);if(d(c))return c;let m=Ze(c.value,void 0);if(d(m))return m;let p=Ze(void 0,void 0);if(d(p))return p;let f=Ze(p.value,void 0);if(d(f))return f;let g=Ze(f.value,void 0);if(d(g))return g;let v=Ze(void 0,void 0);return d(v)?v:u("Created default events",[{id:qt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:qt(),userId:e,userName:t,action:"create.contributor",payload:{id:e,name:t}},{id:qt(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:c.value}},{id:qt(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:qt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:qt(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:g.value}},{id:qt(),userId:e,userName:t,action:"add.board",payload:{id:_s,name:"Closed",parent:n,rank:m.value}},{id:qt(),userId:e,userName:t,action:"add.swimlane",payload:{id:he,name:"Closed",parent:_s,rank:v.value}},{id:qt(),userId:e,userName:t,action:"lock.node",payload:{id:_s}},{id:qt(),userId:e,userName:t,action:"lock.node",payload:{id:he}}])}var $b=()=>{let e=et();if(d(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},Hb=e=>{if(e.length===0)return;let t=e.filter(r=>r.reason==="corrupt-line"||r.reason==="invalid-payload"),n=e.filter(r=>r.reason==="unsupported-schema-version"||r.reason==="unknown-action");if(n.length>0){let r=[...new Set(n.map(o=>o.detail))].join(", ");z.info(`This build cannot read ${n.length} event(s) in the log (${r}). They are skipped, so anything they changed may be out of date until you upgrade.`)}if(t.length>0){let r=[...new Set(t.map(o=>o.detail))].join(", ");z.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}};function Dt(e,t=[]){if($b())return u("Skipped boot while checked out at a historical point",null);if(!e.length){let s=ge.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=Io(s);return d(i)?i:(N({hasProjectDefinition:!1,mode:b.DEFAULT}),u("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return a("Initialized Epiq project has no workspace init event");let n=Lt(e),{fatal:r,skipped:o}=gn(n);return r.length>0?a(`Materializing failed:
|
|
33
33
|
${r.map(s=>s.message).join(`
|
|
34
|
-
`)}`):(hn(o),
|
|
35
|
-
`).filter(t=>t.trim().length>0),
|
|
34
|
+
`)}`):(hn(o),jb(),N({hasProjectDefinition:!0}),Hb(t),u("State booted successfully",null))}import{WebSocket as Wb}from"ws";var Js=new Set,bm=e=>{Js.add(e),e.on("close",()=>{Js.delete(e)}),e.on("error",()=>{Js.delete(e)})},tr=e=>{let t=JSON.stringify(e);for(let n of Js)n.readyState===Wb.OPEN&&n.send(t)};var Qs=e=>{bt()&&(N({syncStatus:e}),tr({type:"sync-status",payload:e}))},Ar=(e="Syncing...")=>{Qs({status:"syncing",msg:e})},nr=(e="Synced")=>{Qs({status:"synced",msg:e})},xd=e=>{Qs({status:"failed",msg:e})},Zs=e=>{Qs({status:"offline",msg:e})},Te=e=>(xd(e),a(e));var Bt=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),Tr=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)}},oe=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);import sx from"node:fs";import vn from"node:fs";import No from"node:path";import Yt from"node:fs";import Ro from"node:path";var wr=e=>e.split(`
|
|
35
|
+
`).filter(t=>t.trim().length>0),xm=e=>{let t=Ro.join(e,Je,mn);try{if(!Yt.existsSync(t))return u("No events directory",[]);let n=Yt.readdirSync(t).filter(r=>r.endsWith(".jsonl")).filter(r=>wr(Yt.readFileSync(Ro.join(t,r),"utf8")).length>0);return u("Looked for stranded event logs",n)}catch(n){return a(`Unable to check ${t} for event logs before deleting it: ${n instanceof Error?n.message:String(n)}`)}},Im=e=>Ro.join(e,Je,mn),Sm=e=>{let t=Im(e),n=new Map;try{if(!Yt.existsSync(t))return n;for(let r of Yt.readdirSync(t))if(r.endsWith(".jsonl")&&!$s(r))try{n.set(r,wr(Yt.readFileSync(Ro.join(t,r),"utf8")))}catch(o){if(!So(o))throw o}}catch{return n}return n},Gb=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},Em=(e,t)=>{if(t.size===0)return[];let n=Im(e),r=[];for(let[o,s]of t){if(s.length===0)continue;let i=Ro.join(n,o);try{let l=Yt.existsSync(i)?Yt.readFileSync(i,"utf8"):null,c=new Set(l===null?[]:wr(l)),m=s.filter(f=>!c.has(f)).filter(Gb);if(m.length===0)continue;Yt.mkdirSync(n,{recursive:!0});let p=l!==null&&l.length>0&&!l.endsWith(`
|
|
36
36
|
`);Yt.appendFileSync(i,`${p?`
|
|
37
37
|
`:""}${m.join(`
|
|
38
38
|
`)}
|
|
39
|
-
`,"utf8"),r.push(`${o} (${m.length})`)}catch{continue}}return r},
|
|
40
|
-
`),
|
|
41
|
-
`));z.info("Creating initial commit");let r=await j({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(d(r))return a(r.message);let o=await j({args:["commit-tree",r.value.stdout.trim(),"-m",
|
|
39
|
+
`,"utf8"),r.push(`${o} (${m.length})`)}catch{continue}}return r},Vb=(e,t)=>{let n=new Set(wr(t));return wr(e).filter(r=>!n.has(r))},zb=(e,t,n)=>[`Refusing to commit ${e}: it is missing ${t.length} of the ${n} event(s) already committed.`,"","The event log is append-only, so a line can never legitimately go","missing. The working copy on disk is damaged; committing it would","publish that damage to everyone who pulls, and the log carries no way","to undo it.","","Nothing has been committed. The committed history is intact \u2014 recover","the file from it before syncing again:",` git show HEAD:${e}`,"","First dropped event:",` ${t[0]?.slice(0,200)??"<none>"}`].join(`
|
|
40
|
+
`),Cm=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let r=await je({args:["show",`HEAD:${t}`],cwd:e});if(r.exitCode!==0)return u("No committed log to compare against",void 0);let o=Vb(r.stdout,n);return o.length>0?a(zb(t,o,wr(r.stdout).length)):u("Event log only grew",void 0)};var Kb="[epiq:init-repo]",Nm=async e=>{let t=await je({args:["rev-parse","--verify","--quiet","HEAD"],cwd:e});if(t.exitCode===0)return u("Initial commit already exists",!1);if(!(t.exitCode===1&&t.stdout.trim()===""&&t.stderr.trim()===""))return a(["Could not determine whether the repository has any commits, so nothing was written.",`git rev-parse exited ${t.exitCode}`,t.stderr.trim()].filter(Boolean).join(`
|
|
41
|
+
`));z.info("Creating initial commit");let r=await j({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(d(r))return a(r.message);let o=await j({args:["commit-tree",r.value.stdout.trim(),"-m",Kb],cwd:e});if(d(o))return a(o.message);let s=await j({args:["update-ref","HEAD",o.value.stdout.trim()],cwd:e});return d(s)?a(s.message):u("Created initial commit",!0)},Rm=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",qb=async e=>{let t=await ws(e);if(d(t))return a(t.message);let n=await _c(e);return d(n)?a(n.message):u("Built sync commit message",`[sync|branch:${Rm(t.value)}:sha:${Rm(n.value)}]`)},Id=async({repoRoot:e,stateBranchName:t})=>{z.info(`Creating ${t}`);let n=await j({args:["commit-tree",Kc,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return a(`Failed to create state branch commit
|
|
42
42
|
${n.message}`);let r=n.value.stdout.trim(),o=await j({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return d(o)?a(`Failed to create ${t}
|
|
43
|
-
${o.message}`):u("Created state branch",!0)},
|
|
43
|
+
${o.message}`):u("Created state branch",!0)},Sd=async({repoRoot:e,stateBranchName:t})=>{let n=await Ts({repoRoot:e,branch:t});if(d(n))return a(`Ensure local state branch failed
|
|
44
44
|
`+n.message);if(n.value)return u("Local state branch already exists",!1);let r=await Xn({repoRoot:e});if(d(r))return a(`Ensure local state branch failed
|
|
45
45
|
`+r.message);let o=r.value,s=o?await ja({repoRoot:e,branch:t}):u("No remote, no remote state branch",!1);if(d(s))return a(`Ensure local state branch failed
|
|
46
46
|
`+s.message);let i=s.value;if(o&&i){let l=await be.fetch({cwd:e,remote:gt,branch:t});if(d(l))return a(`Failed to fetch ${t} from remote
|
|
47
47
|
${l.message}`)}if(i){let l=await j({args:["branch","--track",t,`${gt}/${t}`],cwd:e});return d(l)?a(`Failed to create local ${t} from remote
|
|
48
|
-
${l.message}`):u("Created local state branch from remote",!0)}return
|
|
49
|
-
`),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)},
|
|
50
|
-
`+r.message);if(vn.existsSync(t)&&!vn.existsSync(
|
|
51
|
-
`));z.info("Removing broken state branch worktree path"),
|
|
52
|
-
${o.message}`):u("Created state branch worktree",!0)},rr=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await
|
|
48
|
+
${l.message}`):u("Created local state branch from remote",!0)}return Id({repoRoot:e,stateBranchName:t})},Yb=async({repoRoot:e,branch:t})=>{let n=await j({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=n.value.stdout.split(`
|
|
49
|
+
`),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)},Xb=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=co(No.dirname(t));if(d(r))return a(`Failed to create state branch worktree
|
|
50
|
+
`+r.message);if(vn.existsSync(t)&&!vn.existsSync(No.join(t,".git"))){let s=xm(t);if(d(s))return a(s.message);if(s.value.length>0)return a([`Refusing to delete ${t}.`,"","It is not a usable worktree \u2014 it has no .git \u2014 but it still holds",`${s.value.length} event log(s) with content:`,...s.value.map(i=>` ${i}`),"","Deleting it would destroy them, and with no .git here there is no","committed copy to recover from. Move the directory aside and","salvage the logs before letting epiq recreate the worktree."].join(`
|
|
51
|
+
`));z.info("Removing broken state branch worktree path"),Jc(t)}z.info("Creating state branch worktree");let o=await be.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(o)?a(`Failed to create state branch worktree
|
|
52
|
+
${o.message}`):u("Created state branch worktree",!0)},rr=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await Yb({repoRoot:e,branch:n});if(d(r))return a(r.message);let o=io(t),s=r.value?io(r.value):null;if(s&&s===o&&vn.existsSync(s))return u("State branch already checked out in expected worktree",!1);if(s&&s!==o){let c=await Hc(s);if(d(c))return a(c.message);if(c.value||Fu(s))return a([`Refusing to move the state branch worktree away from ${s}.`,"","It holds changes that are not committed yet, which for this","branch means events no sync has published. Removing it would","destroy them outright \u2014 there is no stash or reflog to recover","a deleted worktree from.","",`This worktree is expected at ${o}, so something else is`,"using a different EPIQ_GLOBAL_DIR against the same repository.","Sync from that location first, or point both at the same one."].join(`
|
|
53
53
|
`));z.info("Moving state branch worktree to expected location");let m=await be.worktreeRemove({cwd:e,worktreeRoot:s});if(d(m))return a(`Failed to remove existing state branch worktree
|
|
54
54
|
${m.message}`)}if(s&&!vn.existsSync(s)){z.info("Pruning stale state branch worktree");let c=await be.worktreePrune({cwd:e});if(d(c))return a(`Failed to prune stale worktrees
|
|
55
|
-
${c.message}`)}let i=await
|
|
56
|
-
${c.message}`)}return
|
|
57
|
-
${o.message}`):u("Checked out state branch",!0)},
|
|
55
|
+
${c.message}`)}let i=await Oc({repoRoot:e,worktreeRoot:t});if(d(i))return a(i.message);let l=vn.existsSync(t);if(i.value&&l)return u("State branch worktree already exists",!1);if(i.value&&!l){z.info("Pruning missing registered state branch worktree");let c=await be.worktreePrune({cwd:e});if(d(c))return a(`Failed to prune stale worktrees
|
|
56
|
+
${c.message}`)}return Xb({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Jb=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await ws(e);if(d(n))return a(n.message);if(n.value===t)return u("State branch already checked out",!1);(await je({cwd:e,args:["rebase","--abort"]})).exitCode===0&&z.info("Aborted stale state branch rebase");let o=await be.checkout({cwd:e,branch:t});return d(o)?a(`Failed to checkout ${t}
|
|
57
|
+
${o.message}`):u("Checked out state branch",!0)},Qb=async({repoRoot:e,stateBranchRoot:t})=>{let n=await $a(t);if(d(n))return a(n.message);if(n.value)return u("State branch upstream already configured",!1);let r=await Xn({repoRoot:t});if(d(r))return a(r.message);if(!r.value)return u("No remote available for state branch upstream",!1);let o=Ht(e);if(d(o))return o;let s=o.value,i=await ja({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);z.info(`Configuring ${s} upstream`);let l=await be.fetch({cwd:t,remote:gt,branch:s});if(d(l))return a(`Failed to fetch ${s}
|
|
58
58
|
${l.message}`);let c=await be.setUpstream({cwd:t,branch:s,upstream:`${gt}/${s}`});return d(c)?a(`Failed to set state branch upstream
|
|
59
|
-
${c.message}`):u("Configured state branch upstream",!0)},ei=async({stateBranchRoot:e,eventFileName:t})=>{let n=
|
|
60
|
-
${s.message}`):u("Staged state branch event file",n)},
|
|
61
|
-
${r.message}`):u("Staged state branch media files",t)},
|
|
62
|
-
${n.message}`):u("Staged event log config",t)},
|
|
63
|
-
`+r.message):Sr({cwd:t,message:r.value,pathspec:n})},
|
|
64
|
-
${s.message}`);let i=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return u(i?"Pushed state branch":"Remote already up to date",i)},Nm=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Ht(e);if(d(o))return o;let s=o.value,i=[Ms(),await bd({repoRoot:e,stateBranchName:s}),await rr({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Xb({stateBranchRoot:t,stateBranchName:s}),await Xc(t),n?await Jb({stateBranchRoot:t,repoRoot:e}):u("Skipped state branch upstream bootstrap",!1)];for(let l of i){if(d(l))return a(l.message);r=r||!!l.value}return u(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import ti from"node:fs";import Id from"node:os";import Qb from"node:path";var Zb="epiq-sync.lock",Am=600*1e3,ex=e=>{try{let t=JSON.parse(e);return typeof t.pid!="number"||typeof t.hostname!="string"||typeof t.startedAt!="number"||typeof t.operation!="string"?null:t}catch{return null}},tx=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},nx=e=>e&&(e.hostname!==Id.hostname()||tx(e.pid))?Date.now()-e.startedAt>Am:!0,wm=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,xd=e=>{try{return ex(ti.readFileSync(e,"utf8"))}catch{return null}},Tm=(e,t)=>{let n={pid:process.pid,hostname:Id.hostname(),startedAt:Date.now(),operation:t};try{return ti.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},rx=async({worktreeRoot:e,operation:t})=>{let n=await Ua(e);if(d(n))return a(n.message);let r=Qb.join(n.value,Zb),o=()=>{try{let l=xd(r);l&&l.pid===process.pid&&ti.rmSync(r)}catch{}};if(Tm(r,t))return u("Acquired sync lock",{acquired:!0,release:o});let s=xd(r);if(!nx(s))return u("Sync lock is held",{acquired:!1,heldBy:s});z.info(`Breaking an abandoned sync lock: ${s?wm(s):"unreadable lock file"}`);try{ti.rmSync(r,{force:!0})}catch{}if(Tm(r,t))return u("Acquired sync lock after breaking a stale one",{acquired:!0,release:o});let i=xd(r);return u("Sync lock taken by another process",{acquired:!1,heldBy:i??{pid:-1,hostname:Id.hostname(),startedAt:Date.now(),operation:"unknown"}})},ni=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await rx({worktreeRoot:e,operation:t});if(d(r))return a(r.message);if(!r.value.acquired)return z.info(`Skipping ${t}: the state worktree is held by ${wm(r.value.heldBy)}`),u("State worktree is held by another process",null);let{release:o}=r.value;try{return u("Ran under the sync lock",await n())}finally{o()}};var sx=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=oe("getRepoRootDir",await Mt(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=oe("getStateBranchRoot",ue({repoRoot:r}));if(d(o))return a(o.message);let s=o.value;logger.debug("[sync] state branch root",s),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let i=oe("bootstrapStateBranchStorage",await Nm({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(d(i))return a(i.message);logger.debug("[sync] bootstrap result",{bootstrapped:i.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let l=oe("hasInProgressGitOperation(stateBranchRoot)",await Ns(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 c=oe("ensureStateBranchLayout",Yc(r,s));return d(c)?a(c.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:i.value}),u("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:i.value}))},ix=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=oe("stageStateBranchOwnEventFile",await ei({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=oe("stageStateBranchMediaFiles",await Em({stateBranchRoot:t}));if(d(o))return a(o.message);let s=oe("stageStateBranchEventConfig",await Rm({stateBranchRoot:t}));if(d(s))return a(s.message);let i=[r.value,o.value,...s.value].filter(m=>m!==null);if(i.length===0)return u("Nothing to stage",{createdCommit:!1});let l=oe("hasStagedChanges(after stage)",await jc(t,i));if(d(l))return a(l.message);if(logger.debug("[sync] state branch change check after stage result",{changed:l.value}),!l.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 c=oe("createStateBranchSyncCommit",await Cm({repoRoot:e,stateBranchRoot:t,pathspec:i}));return d(c)?a(c.message):(logger.debug("[sync] created sync commit",c.value),u("Committed own event file",{createdCommit:!0,commitSha:c.value}))},Sd=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return Zs(n),u(n,{...e,pulled:!1,pushed:!1,offline:!0})},Mm=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");Ar();let n=oe("ensureSyncReady",await sx({cwd:e,ensureUpstream:!0}));if(d(n))return Te(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=oe("isDetachedHead(stateBranchRoot)",await $c(o));if(d(i))return Te(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return Te("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,c,m=!1,p=!1,f=oe("getStateBranch",Ht(r));if(d(f))return Te(f.message);let g=f.value;logger.debug("[sync] resolved state branch",{stateBranch:g,stateBranchRoot:o});let v=oe("flushPendingLogs",$s(o,t));d(v)&&logger.error(`[sync] ${v.message}`);let x=oe("commitOwnEventFileToStateBranch",await ix({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(x))return Te(x.message);l=x.value.createdCommit,c=x.value.commitSha;let I=oe("hasRemote",await Xn({repoRoot:o}));if(d(I))return Te(I.message);if(!I.value)return Sd({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:c,bootstrapped:s},"no remote");let C=oe("pullBranchRebaseIfPresent",await lo({cwd:o,branch:g}));if(d(C))return ao(C.message)?Sd({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:c,bootstrapped:s}):Te(C.message);m=C.value;let A=oe("isAheadOfUpstream",await _c(o));if(d(A))return Te(A.message);if(l||s||A.value){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:s,stateBranchRoot:o});let w=oe("pushStateBranch",await No({stateBranchRoot:o,repoRoot:r}));if(d(w)&&Fc(w.message)){let M=oe("pullBranchRebaseIfPresent(retry)",await lo({cwd:o,branch:g}));if(d(M))return Te(M.message);m=m||M.value,w=oe("pushStateBranch(retry)",await No({stateBranchRoot:o,repoRoot:r}))}if(d(w))return ao(w.message)?Sd({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:c,bootstrapped:s}):Te(w.message);p=w.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let w=oe("git rev-parse HEAD",await j({args:["rev-parse","HEAD"],cwd:o}));if(d(w))return Te(w.message);c=w.value.stdout.trim(),logger.debug("[sync] final sync commit sha",c)}return nr(p?"Synced and pushed":m||l?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),u("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:c,pulled:m,pushed:p,bootstrapped:s,offline:!1})},Ed=async(e,t)=>{let n=vm(e);try{return await t()}finally{let r=bm(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},ri=async e=>{let t=e.cwd??process.cwd(),n=await Mt(t);if(d(n))return Te(n.message);let r=ue({repoRoot:n.value});if(d(r))return Te(r.message);let o=r.value;if(!ox.existsSync(o))return Mm(e);let s=await ni({worktreeRoot:o,operation:"sync",fn:()=>Ed(o,()=>Mm(e))});return d(s)?Te(s.message):s.value===null?u("Another process is syncing this board",{repoRoot:n.value,stateBranchRoot:o,createdCommit:!1,pulled:!1,pushed:!1,bootstrapped:!1,offline:!1,skipped:!0}):s.value};var Xt=null,oi=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Xt,currentStatus:h().syncStatus?.status,currentMessage:h().syncStatus?.msg}),Xt)return logger.debug("[sync] syncAndReloadState joining existing promise"),Xt;logger.debug("[sync] syncAndReloadState creating promise"),Xt=ax();try{let e=await Xt;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:h().syncStatus?.status,statusMessageAfterResolve:h().syncStatus?.msg}),d(e)&&h().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),N({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:h().syncStatus?.status,statusMessageBeforeClear:h().syncStatus?.msg}),Xt=null}},ax=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:h().mode,syncStatus:h().syncStatus});let e=Pm();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:h().mode,message:e.message,syncStatus:h().syncStatus}),e;if(Xt)return Xt;logger.debug("[sync] syncAndReloadState:start");let t=oe("resolveActorId",ee());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");N({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:h().syncStatus});let n=Zn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=oe("syncEpiqWithRemote",await ri({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),N({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:h().syncStatus}),Te(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value,i=Rd(o);return d(i)?i:(N({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:h().syncStatus}),u("Synced",!0))},Rd=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=oe("loadMergedEvents",xt(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(t),message:(d(t),t.message),count:d(t)?void 0:t.value.events.length}),d(t))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:h().syncStatus}),a(`Unable to load events. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=Pm();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:h().mode,message:n.message,syncStatus:h().syncStatus}),n;let r=um(),o=h().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:r,selectedNodeId:h().selectedNode?.id,contextNodeId:h().contextNode?.id,selectedNodeIsVirtual:h().selectedNode?.isVirtual,contextNodeIsVirtual:h().contextNode?.isVirtual}),!h().selectedNode?.isVirtual&&!h().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:t.value.events.length});let i=oe("bootStateFromEventLog",Dt(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(i),message:(d(i),i.message)}),d(i))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:h().syncStatus}),a(`Unable to boot synced state. ${i.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:h().selectedNode?.isVirtual,contextNodeIsVirtual:h().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),N({filters:o}),logger.debug("[sync] restoreNavigationAnchor:start");let s=oe("restoreNavigationAnchor",pm(r));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(s),message:d(s)?s.message:"Navigation restored",selectedNodeId:h().selectedNode?.id,contextNodeId:h().contextNode?.id}),d(s)?(N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:h().syncStatus}),s):u("Reloaded state from event log",null)},Pm=()=>h().mode===b.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:h().mode,syncStatus:h().syncStatus}),N({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var Mr=3e3,Lm=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Mr?null:t},km=0,Cd,Nd=!1,Ao=!1,Ad=()=>{if(Nd)return!0;let e=et();return d(e)?!1:e.value.syncStatus.status==="syncing"},dx=()=>{let e=ie().autoSyncIntervalMs??1e4,t=Date.now()-km;return Math.max(0,e-t)},Dm=()=>{Cd||(Cd=setTimeout(async()=>{if(Cd=void 0,!!bt()){if(Ad()){Ao=!0;return}Ao=!1,await lx()}},dx()))},lx=async()=>{if(h().readOnly||h().timeMode==="peek"||h().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!bt())return a("Cannot auto-sync before state is initialized");if(Ad())return Ao=!0,a("Sync already in progress");Nd=!0,km=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await oi()}finally{Nd=!1,Ao&&Dm()}},si=()=>{bt()&&(Ao=!0,!Ad()&&Dm())};import To from"node:fs";import wo from"node:path";import{z as Pr}from"zod";var ii="recent-projects.json",cx=20,ux=Pr.object({projectId:Pr.string().min(1),root:Pr.string().min(1),lastOpenedAt:Pr.number().finite()}),mx=Pr.object({projects:Pr.array(ux)}),Fm=()=>wo.join(ln(),ii),Lr=e=>wo.basename(e)||e,Bm=e=>{let t=wo.resolve(e);try{return To.realpathSync(t)}catch{return t}},Om=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,_m=e=>{if(!po(e.root))return!1;let t=so(e.root);return!d(t)&&t.value===e.projectId},Um=()=>{let e=Fm();if(!To.existsSync(e))return u("No recent projects recorded",[]);let t;try{t=JSON.parse(To.readFileSync(e,"utf8"))}catch(r){return a(`Invalid ${ii}: ${r instanceof Error?r.message:String(r)}`)}let n=mx.safeParse(t);return n.success?u("Read recent projects",n.data.projects):a(`Invalid ${ii} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},px=e=>{let t=Fm();try{To.mkdirSync(wo.dirname(t),{recursive:!0}),To.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
65
|
-
`,"utf8")}catch(n){return a(`Unable to write ${ii}: ${n instanceof Error?n.message:String(n)}`)}return u("Recorded recent project",e)},bn=({exclude:e}={})=>{let t=Um();if(d(t))return t;let n=e===void 0?null:Bm(e);return u("Listed recent projects",t.value.filter(r=>n===null||Bm(r.root)!==n).filter(_m).sort(Om))},ai=({root:e,now:t=Date.now()})=>{let n=wo.resolve(e),r=so(n);if(d(r))return a(r.message);let o=r.value,s=Um(),i=d(s)?[]:s.value,l=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(c=>c.projectId!==o&&c.root!==n)].filter(_m).sort(Om).slice(0,cx);return px(l)};var Ln=()=>{let e=ie(),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}},jm=()=>{let e=xe(process.cwd());if(d(e))return!1;let t=$t(e.value);return ce(t)},$m=e=>e===!0?"on":e===!1?"off":null,Hm=e=>e==="on"?!0:e==="off"?!1:null;var Ke={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:Ke.cyan,accent2:Ke.magenta,primary:Ke.white,secondary:Ke.grayDark,secondary2:Ke.grayLight,gray:Ke.gray,green:Ke.green,yellow:Ke.yellow,red:Ke.red};var T={red:Ke.red,yellow:Ke.yellow,green:Ke.green,blue:Ke.blue,magenta:Ke.magenta,cyan:Ke.cyan},kr={urgent:T.red,critical:T.red,important:T.red,blocker:T.red,asap:T.red,immediate:T.red,fail:T.red,failure:T.red,broken:T.red,bug:T.red,error:T.red,incident:T.red,outage:T.red,production:T.red,crash:T.red,security:T.red,warning:T.yellow,warn:T.yellow,risky:T.yellow,risk:T.yellow,attention:T.yellow,pending:T.yellow,review:T.yellow,"needs-review":T.yellow,qa:T.yellow,testing:T.yellow,test:T.yellow,validate:T.yellow,verification:T.yellow,staging:T.yellow,check:T.yellow,"follow-up":T.yellow,followup:T.yellow,waiting:T.yellow,blocked:T.yellow,hold:T.yellow,done:T.green,complete:T.green,completed:T.green,success:T.green,ok:T.green,stable:T.green,resolved:T.green,fixed:T.green,closed:T.green,merged:T.green,released:T.green,deployed:T.green,approved:T.green,verified:T.green,working:T.green,healthy:T.green,pass:T.green,passing:T.green,info:T.blue,information:T.blue,note:T.blue,docs:T.blue,documentation:T.blue,doc:T.blue,guide:T.blue,help:T.blue,explanation:T.blue,detail:T.blue,details:T.blue,context:T.blue,design:T.blue,discussion:T.blue,proposal:T.blue,idea:T.blue,feature:T.magenta,enhancement:T.magenta,improvement:T.magenta,refactor:T.magenta,refactoring:T.magenta,cleanup:T.magenta,optimize:T.magenta,optimization:T.magenta,perf:T.magenta,performance:T.magenta,upgrade:T.magenta,migration:T.magenta,modernize:T.magenta,debt:T.magenta,todo:T.cyan,next:T.cyan,planned:T.cyan,plan:T.cyan,future:T.cyan,backlog:T.cyan,investigate:T.cyan,explore:T.cyan,prototype:T.cyan};var fx=e=>e.props.tags??[],gx=e=>e.props.assignees??[],kn=e=>fx(e).map(t=>R.getTag(t)).filter(t=>!!t),Dn=e=>gx(e).map(t=>R.getContributor(t)).filter(t=>!!t),di=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!P(n)?a("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",kn(n))},li=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!P(n)?a("Invalid unassign target"):u("Retrieved assignees from ticket in breadcrumb",Dn(n))};var E={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",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",NONE:""};var hx=/^(\d+)(h|d|w|mo|y)$/,yx=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,vx=({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},bx=(e,t=new Date)=>{let n=e.match(hx);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}},xx=e=>{let t=e.match(yx);if(!t)return null;let[,n,r,o,s,i]=t,l=Number(n),c=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return vx({year:l,month:c,day:m,hour:p,minute:f})?new Date(l,c-1,m,p,f):null},or=e=>{let t=e.trim().toLowerCase();return bx(t)??xx(t)};var Wm=/^(\d+)(s|m)?$/,ci=e=>{let t=e.trim().toLowerCase().match(Wm);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},ui=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Wm.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Gm=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Ix=[{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}],Td=(e=Ix)=>{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 Sx=["BOARD","TICKET","SWIMLANE","COMMENT"],ye={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},pt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Me={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},Ex=[ye.EDITOR,ye.VIEW,ye.USERNAME,ye.AUTOSYNC,ye.SYNC_DEBOUNCE_MS,ye.ATTACHMENT_MAX_KB,ye.LOG_LEVEL],Rx=(e=h().selectedNode?.context)=>{switch(e){case"TICKET":return[pt.TITLE,pt.DESCRIPTION];case"BOARD":case"SWIMLANE":return[pt.TITLE];case"COMMENT":return[pt.COMMENT];default:return[]}},Md=[String(Mr),"5000","15000","30000","60000"],Pd=["250","500","1000"],Km=["10s","20s","30s","45s"],sr=[E.EXIT,E.SYNC,E.HELP,E.EXPORT,E.CONFIG,E.YANK],mi=[E.NEW,E.EDIT,E.DELETE,E.MOVE],wd=[E.TAG,E.UNTAG,E.ASSIGN,E.UNASSIGN,E.CLOSE_ISSUE,E.RE_OPEN_ISSUE,E.EDIT,E.COMMENT],Vm=[E.FILTER,E.PEEK,E.REPLAY],Cx={WORKSPACE:[...sr,...mi],BOARD:[...Vm,...sr,...mi],SWIMLANE:[...Vm,...sr,...mi],TICKET:[...sr,...mi,...wd],FIELD:[...sr,...wd],FIELD_LIST:[...sr,...wd],TEXT:[...sr],COMMENT:[E.EDIT,E.DELETE,E.YANK]},Nx=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Mo=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&P(n)),zm=e=>e.parentNodeId===he,Ax=({selectedNode:e,breadCrumb:t})=>{let n=Rx(e?.context);return Mo({breadCrumb:t,selectedNode:e})?n.includes(pt.DESCRIPTION)?n:[...n,pt.DESCRIPTION]:n},Tx=({selectedNode:e,breadCrumb:t})=>{let n=Mo({breadCrumb:t,selectedNode:e});return n?[Me.REF,Me.TITLE,...n.props?.description?.trim()?[Me.DESCRIPTION]:[],...kn(n).length>0?[Me.TAGS]:[],...Dn(n).length>0?[Me.ASSIGNEES]:[]]:e?[Me.REF,Me.TITLE]:[]},Ld=()=>{let e=bn({exclude:process.cwd()});return d(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},wx=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Ln();if(!r)return[E.HELP,E.CONFIG];if(!jm())return[E.HELP,E.INIT,E.OPEN];if(t)return[E.HELP,E.PEEK,E.REPLAY,E.EXPORT,E.CONFIG,E.YANK];let o=e?.context,s=o&&Sx.includes(o),i=[...new Set([...n,e].map(c=>c?.context).flatMap(c=>c?Cx[c]:[]))],l=Mo({breadCrumb:n,selectedNode:e});return i.filter(c=>c===E.MOVE?!1:c===E.YANK?!!(l??e):c===E.EDIT?s||!!l:c===E.DELETE?s:c===E.UNTAG?!!(l&&kn(l).length>0):c===E.UNASSIGN?!!(l&&Dn(l).length>0):c===E.RE_OPEN_ISSUE?!!(l&&zm(l)):c===E.CLOSE_ISSUE?!!(l&&!zm(l)):!0)},Ne=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=h())=>{let s=t.context??"WORKSPACE";return{[E.NONE]:wx({breadCrumb:o,readOnly:r,selectedNode:n}),[E.EXIT]:["confirm"],[E.EXPORT]:[],[E.SYNC]:[],[E.INIT]:[],[E.OPEN]:e===E.OPEN?Ld():[],[E.HELP]:[],[E.PEEK]:[...Td(),"now","prev","next"],[E.REPLAY]:[...Td()],[E.EDIT]:Ax({selectedNode:n,breadCrumb:o}),[E.YANK]:Tx({selectedNode:n,breadCrumb:o}),[E.COMMENT]:[],[E.DELETE]:["confirm"],[E.RE_OPEN_ISSUE]:["confirm"],[E.CLOSE_ISSUE]:["confirm"],[E.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[E.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[E.TAG]:[...new Set([...Object.keys(kr),...R.getExistingTags()])],[E.UNTAG]:[...di()?.value?.map(({name:l})=>l)??[]],[E.UNASSIGN]:[...li()?.value?.map(({name:l})=>l)??[]],[E.ASSIGN]:R.getExistingAssignees(),[E.NEW]:Nx(s),[E.CONFIG]:[...Ex]}[e]??[]};import up from"chalk";var qm=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import Dx from"zod";import Mx from"node:crypto";import Po from"node:fs";import Jm from"node:path";var Ym="/media/",Xm=e=>`${Ym}${e}`,kd=(e,t)=>`})`;var Jt=500,Px=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,ir=(e,t)=>`${e}.${t}`,Lx=e=>Px.test(e),Qm=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: ${au.join(", ")}`),Zm=e=>Mx.createHash("sha256").update(e).digest("hex"),kx=(e,t=Jt)=>{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=Qm(e);return d(n)?n:u("Validated attachment data",{hash:Zm(e),ext:n.value,bytes:e.length})},ep=(e,t,n=Jt)=>{let r=kx(t,n);if(d(r))return r;let o=mo(e),s=Jm.join(o,ir(r.value.hash,r.value.ext));try{Po.existsSync(s)||(Po.mkdirSync(o,{recursive:!0}),Po.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)},tp=(e,t,n=Jt)=>{if(!Lx(t))return a("Invalid attachment file name");let r=Jm.join(mo(e),t);if(!Po.existsSync(r))return a("Attachment blob not found");let o;try{o=Po.readFileSync(r)}catch(c){return a(`Unable to read attachment blob: ${c instanceof Error?c.message:String(c)}`)}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(Zm(o)!==s)return a("Attachment blob does not match its content hash");let l=Qm(o);return d(l)?l:l.value!==i?a("Attachment blob content does not match its extension"):u("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var Lo=50,ko=5e3,np=()=>{let e=te().commandMeta.inputString,t=Dx.coerce.number().int().min(Lo).max(ko).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${Lo}-${ko} KB (default ${Jt})`);let n=ht({attachmentMaxKb:t.data});return d(n)?n:(ze({attachmentMaxKb:t.data}),N({mode:b.DEFAULT}),u(`Attachment size cap set to ${t.data} KB`,null))};import Dr from"chalk";var Bd={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},rp=(e,t,n)=>Math.max(t,Math.min(n,e)),Dd=(e,t,n)=>e+(t-e)*n,op=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Bx=e=>e.toLowerCase().trim(),Fx=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,l=s*(1-Math.abs(i%2-1)),c=0,m=0,p=0;i>=0&&i<1?(c=s,m=l):i>=1&&i<2?(c=l,m=s):i>=2&&i<3?(m=s,p=l):i>=3&&i<4?(m=l,p=s):i>=4&&i<5?(c=l,p=s):(c=s,p=l);let f=o-s/2;return[Math.round((c+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},sp=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var Ox=(e,t,n)=>{let r=rp(n,0,1);return[Math.round(Dd(e[0],t[0],r)),Math.round(Dd(e[1],t[1],r)),Math.round(Dd(e[2],t[2],r))]};var _x=(e,t,n)=>Ox(e,t,n),Do=e=>{let t=op(e)%360,n=Fx(t,Bd.stringColor.saturation,Bd.stringColor.lightness);return sp(n)},de=(e,t=kr)=>{let n=Bx(e??"");return n&&t[n]?t[n]:Do(n)};var ip=e=>{let t=Bd.gradient.stops,n=rp(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 _x(t[s],t[s+1],i)},pi=e=>sp(ip(e)),fi=e=>op(e.toLowerCase().trim())/4294967295,ap=e=>{let t=fi(e);return ip(t)},Ux=e=>{let[t,n,r]=ap(e);return{normal:o=>Dr.bgRgb(t,n,r).black(o),cursor:o=>Dr.bgRgb(t,n,r).white.bold(o)}},Fd=e=>{let[t,n,r]=ap(e);return{fg:o=>Dr.rgb(t,n,r)(o),fgCursor:o=>Dr.rgb(t,n,r).inverse(o),bg:o=>Dr.bgRgb(t,n,r).black(o),bgCursor:o=>Dr.bgRgb(t,n,r).white.bold(o)}},gi=e=>Ux(e).normal(` ${e} `);var st=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null;import{createHash as jx}from"node:crypto";var $x="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Hx=e=>{let t=jx("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+=$x[Number(n>>s&31n)]}return r},De=(e,t)=>Hx(`${e}:virtual:${t}`);import dp from"chalk";var me=e=>dp.dim(e),Be=e=>dp.hex(y.primary)(e),He=({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)=>fi(f)-fi(g)).slice(0,r).map(f=>gi(f)).join(" ");return p?`${me(e)}${p}${me(n)}`:""};var Qt={None:"none",Invalid:"invalid",Valid:"valid"};var Wx=["BOARD","TICKET","SWIMLANE"],lp=()=>{let e=h().selectedNode;if(!e?.context)return W({message:me("Missing target context")});if(Wx.includes(e.context))return J();if(e.parentNodeId){let t=h().nodes[e.parentNodeId];if(t?.id===De(t?.parentNodeId??"","comments"))return J()}return W({message:me("Command not available in this context")})},le="<ENTER> to confirm",J=(e="",t=[])=>({message:me(e),validity:Qt.Valid,completionWordList:t}),W=({message:e,completionWordList:t=[]})=>({validity:Qt.Invalid,message:e,completionWordList:t}),Fr=e=>e.length===0,cp=(e,t)=>{let n=Qe(h().breadCrumb,"BOARD");if(d(n))return W({message:Be("Command is not applicable in this context")});let r=ks(n.value.id);return d(r)?W({message:Be(`Unable to ${t}: board id is not a valid ULID`)}):Gm({date:e,horizonDate:r.value})?null:W({message:Be(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},hi=e=>` ${up.hex("#000").bgHex(de(e))(` ${e} `)} `,Od=({modifier:e})=>{let t="confirm";return e===t?J(le):W({message:Fr(e)?me("if you are certain, enter ")+gi(t):"",completionWordList:[t]})},Gx=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?W({message:me(n)}):J():W({message:Fr(r)?t:"",completionWordList:[...e]}),Br=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>Fr(n)&&Fr(r)?W({message:e,completionWordList:[]}):J(t??le),Vx=({modifier:e,inputString:t})=>{let n=Ld();return!Fr(e)||!Fr(t)?J(le):W({message:n.length?me("number from the list, or a path"):me("path to an epiq project"),completionWordList:n})},zx=({modifier:e,inputString:t})=>{let n=Ne(E.CONFIG);if(!n.includes(e))return W({message:He({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ye.EDITOR:{let r=[...qm];return t.trim()?r.includes(t.trim())?J(le):W({message:He({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):W({message:He({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ye.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?J(le):W({message:He({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ye.USERNAME:return t.trim()?J(le):W({message:Be("Enter a user name. Saved in ")+up.bgBlack("~/.epiq-global/config.json")});case ye.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?J(le):W({message:He({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ye.AUTOSYNC:{let r=["on","off"],o=ie().autoSync;if(!r.includes(t.trim())){let s=$m(o);return W({message:He({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return J(le)}case ye.ATTACHMENT_MAX_KB:{let r=ie().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<Lo||o>ko){let s=He({prefix:" examples: ",wordList:Pd,minLengthForHints:0,inputString:t});return W({message:Be(`provide a size cap in KB (${Lo}-${ko}). current: ${r??Jt} KB.`)+s,completionWordList:Pd})}return J(le)}case ye.SYNC_DEBOUNCE_MS:{let r=ie().autoSyncIntervalMs,o=Lm(t);if(!t.trim()||o===null||o<Mr){let s=He({prefix:" examples: ",wordList:Md,minLengthForHints:0,inputString:t});return W({message:Be(`provide duration above ${Mr}ms. current duration: ${r}ms.`)+s,completionWordList:Md})}return J(le)}default:return W({message:Be("Unknown config option"),completionWordList:n})}},Kx=({modifier:e,inputString:t})=>{let n=Ne(E.EDIT);if(!n.length)return W({message:Be("Command not available in this context")});if(!n.includes(e)){let r=He({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return W({message:r||Be("Unknown edit option"),completionWordList:n})}switch(e){case pt.COMMENT:return t.trim()?J(le):W({message:me("write a comment...")});case pt.TITLE:return J(le);case pt.DESCRIPTION:{let{preferredEditor:r}=ie();return r?J(me("<ENTER> to edit in ")+r):W({message:"No editor selected"})}default:return W({message:Be("Unknown edit option"),completionWordList:n})}},qx=({modifier:e})=>{let t=Ne(E.YANK);return t.length?t.includes(e)?J(le+me(" and copy to clipboard")):W({message:He({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):W({message:Be("Nothing selected to copy from")})},Yx={[E.EXPORT]:()=>J(le+me(", and create export markdown file")),[E.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return J(le);let n={message:me("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=or(r);if(!r||!o)return W(n);let s=cp(o,"peek");return s||J(le)},[E.REPLAY]:e=>{let{dateInput:t,durationInput:n}=ui(e.modifier,e.inputString),r={message:me("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=or(t);if(!t||!o)return W(r);let s=cp(o,"replay");return s||(n&&ci(n)===null?W({message:Be("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):J("<ENTER> to replay board history",n?Km:[]))},[E.EXIT]:()=>J(le+me(" and exit the application")),[E.INIT]:()=>J(le),[E.OPEN]:Vx,[E.PALETTE]:()=>J(le),[E.FILTER]:e=>{if(e.modifier==="clear")return J(le);let t=s=>Ne(E.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return W({message:He({wordList:Ne(E.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Ne(E.FILTER)});let n=Object.values(h().tags).map(s=>s.name),r=Object.values(h().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?W({message:He({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):J():W({message:He({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[E.NONE]:e=>{let t=Ne(E.NONE);return W({message:He({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[E.NEW]:e=>Gx({list:Ne(E.NEW),hint:He({wordList:Ne(E.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[E.HELP]:()=>J(le),[E.EDIT]:Kx,[E.COMMENT]:e=>{let t=Br({hint:me(`write a comment (max ${4e3} char)...`),onOk:me(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===Qt.Invalid?t:e.inputString.length>4e3?J(Be("max input exceeded")):t},[E.CONFIG]:zx,[E.YANK]:qx,[E.DELETE]:e=>{let t=lp();return t.validity==="invalid"?t:Od(e)},[E.CLOSE_ISSUE]:e=>Od(e),[E.RE_OPEN_ISSUE]:e=>Od(e),[E.MOVE]:e=>{let t=lp();return t.validity==="invalid"?t:Br({hint:He({prefix:"hey hacker! These commands are blocked for you... ",wordList:Ne(E.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[E.TAG]:e=>{let n=R.getExistingTags().slice(0,10).map(hi).join("");return Br({hint:n.length?me("create tag or reuse:")+n+me(""):me("create tag ...")})(e)},[E.UNTAG]:e=>{let t=di();if(d(t))return W({message:Be("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(hi).slice(0,10);return n.length?Br({hint:me(" ... ")+n.join("")})(e):W({message:Be("Issue has no tags"),completionWordList:[]})},[E.ASSIGN]:e=>{let t=R.getExistingAssignees().map(hi).slice(0,10);return Br({hint:me("assignees... ")+t.join("")})(e)},[E.UNASSIGN]:e=>{let t=li();if(d(t))return W({message:Be("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(hi).slice(0,10);return n.length?Br({hint:me("remove assignee... ")+n.join("")})(e):W({message:Be("Issue has no assignees"),completionWordList:[]})},[E.SYNC]:()=>J(le)},mp=Object.fromEntries(Object.entries(Yx).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var yi=["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 Xx=3,Jx=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"]),Qx=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},Zx=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=Xx&&!Jx.has(t)&&!/^\d+$/.test(t)),eI=e=>{let t=new Map;for(let s of Qx(e))for(let i of Zx(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=yi.filter(s=>!r.has(s));return[...n,...o]},pp=yi,fp=-1,gp=()=>{let e=et();if(d(e))return yi;let t=e.value,n=t.eventLog.length;return n!==fp&&(pp=eI(t),fp=n),pp};var hp=e=>Object.values(E).includes(e),yp=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:l,completionWordList:c}=mp[n].validate(n,r,s),m=n!==E.PEEK&&n!==E.REPLAY,p=o==="command"||o==="modifier"?Ne(n):m?gp():[],{mode:f}=h(),g=f===b.COMMAND_LINE?i??"":"",v=[...c,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?bu(e,v):{hint:"",hints:[],remainder:"",overlap:0}}};var vp=e=>{let t=e.trimStart(),n=nI(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=rI(e),l=hp(r)?r:null,c=l!==null,m=r!=="",p=l?Ne(l)??[]:[],f=l&&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 v=s?"":i,x=tI(t,l,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:l,isCommandKeyword:c,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:v,inputString:x}},tI=(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},nI=e=>e.trim()?e.trim().split(/\s+/):[],rI=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as oI}from"react";var Or=e=>e===_d||e===":",_d=" ",qe={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Qt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Ud=new Set,bp=()=>{for(let e of Ud)e()},jd=e=>(Ud.add(e),()=>Ud.delete(e)),Zt=e=>{let n=e(qe),r=vp(n.value),o=n.cursorPosition===n.value.length;qe={...n,commandMeta:yp(r,o)},bp()},Bo=({message:e,status:t})=>{let n=structuredClone(qe);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,qe=n,bp(),u(e,null)},$d=e=>{Zt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Hd=e=>{Zt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Or(n[o-1]);)o--;for(;o>0&&!Or(n[o-1]);)o--}else{for(;o<n.length&&!Or(n[o]);)o++;for(;o<n.length&&Or(n[o]);)o++}return{...t,cursorPosition:o}})},xp=()=>{Zt(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}})},Ip=()=>{Zt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Or(t[r-1]);)r--;for(;r>0&&!Or(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},vi=e=>{Zt(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,l=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:l,commandIsPending:!1}})},Sp=()=>{Zt(e=>({...e,commandIsPending:!0}))},Q=e=>{Zt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Ep=({addToHistory:e=!0})=>{Zt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Rp=()=>{Zt(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}})},Cp=()=>{Zt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},te=()=>qe,Np=()=>oI(jd,te,te),bi=()=>{let[e,...t]=qe.value.split(_d);return t.join(_d).trim()};var S={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 sI(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function iI(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function aI(e,t,n){let r=h().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 Ap(e,t){let n=te();if(e.sequence==="?"&&t!==b.PALETTE)return S.InitCommandPalette;if(e.sequence===":"&&t!==b.COMMAND_LINE)return S.InitCommandLine;if(t===b.MOVE)switch(e.name){case"m":case"return":return S.ConfirmMove}if(t===b.COMMAND_LINE)return uu(e,n.value);if(t===b.PALETTE)return mu(e,n.value);let r=sI(e)||iI(e);if(r)return dI(r,t);if(e.ctrl&&e.name==="c")return S.Exit;switch(e.name){case"r":return S.EditTitle;case"e":return S.EditDescription;case"n":return S.AddItem;case"m":return S.InitMove;case"d":return S.Delete;case"y":return S.Yank;case"return":return S.Confirm;case"space":return S.Confirm;case"v":return ie().viewMode==="wide"?S.SetViewDense:S.SetViewWide;case"q":case"escape":return S.Exit;default:return null}}function dI(e,t){let n=t===b.MOVE?{prevItem:S.MovePreviousItem,nextItem:S.MoveNextItem,prevContainer:S.MoveToPreviousContainer,nextContainer:S.MoveToNextContainer}:{prevItem:S.NavPreviousItem,nextItem:S.NavNextItem,prevContainer:S.NavToPreviousContainer,nextContainer:S.NavToNextContainer};return aI(h().contextNode.childRenderAxis,e,n)}var xi=e=>{let{context:t}=h().contextNode;if(!t)return U.None;switch(e){case E.EXIT:return U.Exit;case E.EXPORT:return U.Export;case E.INIT:return U.Init;case E.OPEN:return U.OpenProject;case E.DELETE:return U.Delete;case E.EDIT:return U.Edit;case E.COMMENT:return U.Comment;case E.HELP:return U.ViewHelp;case E.RE_OPEN_ISSUE:return U.ReopenIssue;case E.CLOSE_ISSUE:return U.CloseIssue;case E.TAG:return U.TagTicket;case E.UNTAG:return U.UntagTicket;case E.ASSIGN:return U.AssignUserToTicket;case E.UNASSIGN:return U.UnassignUserFromTicket;case E.NEW:return U.NewItem;case E.FILTER:return U.Filter;case E.MOVE:return U.Move;case E.PEEK:return U.Peek;case E.REPLAY:return U.Replay;case E.CONFIG:return U.Config;case E.YANK:return U.Yank;case E.SYNC:return U.Sync;default:return U.None}},U={Exit:"exit",Init:"init",OpenProject:"open-project",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"};import uf from"node:fs";import dS from"node:path";import lS from"react";import{Box as iS}from"ink";import Ai from"react";import TI from"chalk";import{Box as Vd,Text as wI}from"ink";import en from"react";import{Text as Tp}from"ink";import wp,{useEffect as Mp,useState as lI}from"react";var Pp={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ye=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=X(),r=Pp[n]??Pp.default,[o,s]=lI(0);if(Mp(()=>{s(0)},[r]),Mp(()=>{if(!e)return;let l=setInterval(()=>{s(c=>(c+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return wp.createElement(Tp,null,t);let i=r[o]??r[0]??t;return wp.createElement(Tp,{color:y.accent,dimColor:o===1},i)};import{Box as Wd,Text as cI}from"ink";import Ii from"react";var uI=(e,t,n,r)=>{let o=c=>Math.max(1,e[c]??1),s=n,i=n+1,l=o(n);for(;i<t&&l+o(i)<=r;)l+=o(i),i++;for(;s>0&&l+o(s-1)<=r;)s--,l+=o(s);return{start:s,end:i}},It=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),l=Math.max(1,Math.ceil(r)),c=Math.max(0,Math.min(n,e.length-1)),m=Math.max(1,Math.floor(i/l)),p=Math.max(0,e.length-m),{start:f,end:g}=o?uI(o,e.length,c,i):s?{start:Math.min(p,Math.max(0,c-m+1)),end:Math.min(p,Math.max(0,c-m+1))+m}:{start:Math.min(p,Math.floor(c/m)*m),end:Math.min(p,Math.floor(c/m)*m)+m},v=Math.max(1,g-f),x=e.slice(f,g),I=e.length>v,C=i,A=I?Math.max(1,Math.floor(v/e.length*C)):C,w=Math.max(0,C-A),M=Math.max(1,e.length-v),k=I?Math.floor(f/M*w):0;return Ii.createElement(Wd,{flexDirection:"row",height:i,width:"100%"},Ii.createElement(Wd,{flexDirection:"column",flexGrow:1,height:i},x),Ii.createElement(Wd,{flexDirection:"column",width:1,height:C},Array.from({length:C}).map((D,ve)=>Ii.createElement(cI,{key:ve,color:I&&ve>=k&&ve<k+A?y.accent:y.secondary},I?"\u2502":" "))))};import{Box as jr,Text as $r}from"ink";import it from"react";var Lp,Gd,mI=()=>{let{eventLog:e=[]}=h();if(Gd&&Lp===e)return Gd;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Lp=e,Gd=t,t},Si=e=>mI().has(e);import{Text as pI}from"ink";import fI from"react";var gI=e=>e.toLowerCase().trim(),hI=(e,t=kr)=>{let n=gI(e);return t[n]?t[n]:Do(n)},Bn=({id:e,isSelected:t,maxWidth:n})=>{let r=R.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:fn(o,n);return fI.createElement(pI,{underline:t,color:hI(o)},"@"+s,Si(e)?"":"\u2197")};import{Text as yI}from"ink";import vI from"react";var _r=({id:e,isSelected:t,maxWidth:n})=>{let r=R.getTag(e);if(!r)return;let o=n===void 0?r.name:fn(r.name,n);return vI.createElement(yI,{underline:t,backgroundColor:de(r.name),color:y.secondary}," "+o+" ")};import{useEffect as bI,useState as xI}from"react";var II=80,kp=1400,Ei=new Set,Fo=null,SI=e=>(Ei.add(e),Fo||(Fo=setInterval(()=>{for(let t of Ei)t()},II)),()=>{Ei.delete(e),Ei.size===0&&Fo&&(clearInterval(Fo),Fo=null)}),EI=()=>{let e=Date.now()%kp/kp;return e<.5?e*2:(1-e)*2},Ur=e=>{let[,t]=xI(0);return bI(()=>{if(e)return SI(()=>t(n=>n+1))},[e]),pi(EI())};var RI=(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),fn(e.slice(o).trim(),n)]},Dp=3,CI=2,NI=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let i=e.length-o-1,l=i>0?String(i).length+1:0;if(r+s.width+l>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},Bp=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Ur(r),s=e-4,i=s-7-1,[l,c]=RI(Se(t.title),i,s),m=c?null:fn(Se(t.props.description),s)||null,p=kn(t),f=Dn(t).map(A=>({...A,name:A.name})),g=Math.max(1,s-Dp),v=R.getCommentsByIssue(t.id),x=v.length?String(v.length).length+2+1:0,{shown:I,hidden:C}=NI([...p.map(A=>({id:A.id,isTag:!0,width:Math.min(A.name.length,g)+Dp})),...f.map(A=>({id:A.id,isTag:!1,width:Math.min(A.name.length,g)+CI+(Si(A.id)?0:1)}))],s-x);return it.createElement(jr,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?y.accent:y.secondary,justifyContent:"space-between"},it.createElement(jr,{paddingLeft:1,paddingRight:1,flexDirection:"column"},it.createElement(jr,{justifyContent:"space-between"},it.createElement($r,{color:y.primary},l),it.createElement($r,{color:y.secondary2,dimColor:!0},_(t.id))),c&&it.createElement($r,{color:y.primary},c),m&&it.createElement($r,{color:y.secondary2,dimColor:!0},m)),it.createElement(jr,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},it.createElement(jr,{flexDirection:"row"},I.map(A=>it.createElement(jr,{paddingRight:1,key:A.id},A.isTag?it.createElement(_r,{id:A.id,maxWidth:g}):it.createElement(Bn,{id:A.id,maxWidth:g}))),C>0&&it.createElement($r,{color:y.secondary2,dimColor:!0},"+",C)),v.length>0&&it.createElement($r,{color:y.accent},"[",v.length,"]")))};import{Box as ar,Text as Oo}from"ink";import ft from"react";var AI=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,Fp=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let l=Ur(s),c=(r.props.tags??[]).map(D=>R.getTag(D)).filter(D=>!!D),m=(r.props.assignees??[]).map(D=>R.getContributor(D)).map(D=>D&&{...D,name:D.name}).filter(D=>!!D),p=1,f=c.length*(1+p),g=m.length*(2+p),v=c.map(D=>ft.createElement(ar,{key:D.id,paddingRight:p},ft.createElement(Oo,{color:de(D.name)},"\u25A0"))),x=m.map(D=>ft.createElement(ar,{key:D.id,paddingRight:p},ft.createElement(Oo,{color:Do(D.name)},"@"+D.name.at(0)))),I=s?l:o?y.accent:i===b.MOVE?y.secondary:y.primary,C=R.getCommentsByIssue(r.id),A=C.length?String(C.length).length+2+p:0,w=C.length?ft.createElement(ar,{paddingRight:p},ft.createElement(Oo,{color:y.accent},"[",C.length,"]")):null,M=f+g+A,k=Math.max(1,n-t-M-(M>0?1:0));return ft.createElement(ar,{justifyContent:"space-between"},ft.createElement(ar,null,ft.createElement(ar,{width:t},o?ft.createElement(Ye,{isSelected:!0}):ft.createElement(Oo,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),ft.createElement(Oo,{wrap:"truncate",color:I},AI(r.title,k))),ft.createElement(ar,null,v,x,w))};var MI=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:l})=>{let{renderedChildrenIndex:c,replay:m}=X(),p=c[e.id]??[],f=m?new Set(m.flashNodeIds):null,g=f?.has(e.id)??!1,v=Ur(g),x=`${e.title} ${TI.hex(y.secondary2).dim("("+p.length+")")}`,I=3,C=o?1:5,A=s&&i===-1,w=n-3-(o?1:0)-(A?2:0),M=Math.max(2,String(p.length).length+1),k=r-I-1,D=en.createElement(Vd,{borderStyle:"round",borderColor:y.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},en.createElement(Ye,{isSelected:t}),en.createElement(wI,{bold:!0,color:g?v:t?y.accent:y.primary},x," ",e.readonly?"\u{1F512}":"")),ve=(Ve,At)=>{let dt=s&&i===At;if(!P(Ve))return null;let ke=f?.has(Ve.id)??!1;return o?en.createElement(Fp,{key:Ve.id,index:At,labelWidth:M,width:w,ticket:Ve,isSelected:dt,isFlashing:ke,mode:l}):en.createElement(Bp,{key:Ve.id,width:w,ticket:Ve,isSelected:dt,isFlashing:ke})};return en.createElement(Vd,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},D,en.createElement(Vd,null,p.length>0&&en.createElement(It,{selectedIndex:i,height:k,itemHeight:C},p.map(ve)),A&&en.createElement(Ye,{isSelected:!0})))},Op=en.memo(MI);import{Box as lr,Text as rl}from"ink";import Fe,{useMemo as Uo}from"react";var _p=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},Up=(e,t,n)=>ge.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 Gr,Text as xn}from"ink";import Xe,{useEffect as PI,useMemo as LI,useRef as kI}from"react";import{decodeTime as jp}from"ulid";var Wr=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"},Ri=e=>String(e).padStart(2,"0"),Ci=e=>`${e.getFullYear()}-${Ri(e.getMonth()+1)}-${Ri(e.getDate())} ${Ri(e.getHours())}:${Ri(e.getMinutes())}`;var DI=e=>De(e,"attachments"),BI=e=>R.getAttachmentsByIssue(e.id).sort((t,n)=>jp(t.id)-jp(n.id)),$p=e=>{for(let t of e)R.deleteNode(t.id)},FI=(e,t,n)=>ge.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),OI=(e,t)=>{let n=R.getNode(DI(e.id));if(!n||!ut(n))return[];let r=t.map((o,s)=>FI(o,s,n.id)).map(o=>R.createNode(o)).filter(ce).map(({value:o})=>o).filter(ut);return t.length>0&&h().selectedIndex<0&&O.navigate({contextNode:n,selectedIndex:0}),r},_I=e=>`${Math.max(1,Math.round(e/1024))} KB`;function Hp({ticket:e,width:t,height:n}){let r=LI(()=>BI(e),[e]),o=kI([]);PI(()=>($p(o.current),o.current=OI(e,r),()=>{$p(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=X(),l=Math.max(1,n-4),c=Math.max(12,t-32);return r.length===0?Xe.createElement(Gr,{flexDirection:"column",width:t,height:n,padding:1},Xe.createElement(xn,{color:y.primary},"No attachments yet."),Xe.createElement(Gr,{paddingTop:1},Xe.createElement(xn,{color:y.primary},"Attach images from the browser GUI"),Xe.createElement(xn,{color:y.accent}," epiq gui "),Xe.createElement(xn,{color:y.primary},"by dropping or pasting them."))):Xe.createElement(Gr,{flexDirection:"column",width:t,height:n},Xe.createElement(Gr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},Xe.createElement(xn,{color:y.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),Xe.createElement(It,{height:l,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,g=m.name.length>c?m.name.slice(0,c-1)+"\u2026":m.name;return Xe.createElement(Gr,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},Xe.createElement(xn,{color:y.accent},f?"\u276F ":" "),Xe.createElement(Gr,{paddingLeft:1},Xe.createElement(xn,{color:y.secondary2},`#${p+1} `),Xe.createElement(xn,{color:f?y.accent:y.primary},g),Xe.createElement(xn,{color:y.secondary2}," "+_I(m.bytes)+" "+Wr(Ie(m.id)))))})))}import{Box as Fn,Text as On}from"ink";import Pe,{useEffect as zI,useMemo as tf,useRef as KI}from"react";import{decodeTime as nf}from"ulid";var Gp=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,zd=e=>e.replace(Gp,"");var Wp=e=>e==="additions"||e==="deletions",Kd=e=>{let t=Gp.exec(e);if(!t?.[1])return null;let n;try{n=JSON.parse(t[1])}catch{return null}let r=n;return typeof r?.filePath!="string"||typeof r.start!="number"||typeof r.end!="number"||typeof r.note!="string"||!Wp(r.side)||!Wp(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r};var Vp=/```\n([\s\S]*?)\n?```\s*$/,zp=e=>Vp.exec(e)?.[1]??null,UI=/`[^`\n]+`[^\n]*\n?$/,Kp=e=>zd(e).replace(Vp,"").replace(UI,"").trim(),jI=e=>{let n=(e.endSide??e.side)==="deletions"?"removed":"added";return e.start===e.end?`line ${e.start} (${n})`:`lines ${e.start}-${e.end} (${n})`},qd=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${jI(e)}`;var $I=(e,t)=>{let n=Math.max(1,Math.floor(t)),r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[""];let o=[],s="";for(let i of r){let l=i;for(;l.length>n;)s&&(o.push(s),s=""),o.push(l.slice(0,n)),l=l.slice(n);s?s.length+1+l.length<=n?s=`${s} ${l}`:(o.push(s),s=l):s=l}return s&&o.push(s),o},_o=e=>{let t=e.split("`");return t.length%2===0?[{text:e}]:t.map((n,r)=>r%2===1?{text:n,code:!0}:{text:n}).filter(n=>n.text.length>0)},HI=/!\[([^\]]*)\]\([^)]*\)/g,WI=e=>e.replace(HI,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),GI=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),VI=4,Yp=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(VI)),Yd=e=>{let t=!1;return e.map(Yp).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=Kd(n);if(r)return{kind:"caption",text:qd(r)};let o=WI(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:_o(s[1]??"")}:{kind:"text",spans:_o(o)}})},Xp=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],qp=(e,t)=>{let n=[];for(let r of Yd(e))if(r.kind!=="fence"){if(r.kind==="blank"){n.length>0&&n[n.length-1]?.kind!=="blank"&&n.push(r);continue}if(r.kind==="code"){for(let o of Xp(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of $I(GI(r.spans),t))n.push({kind:r.kind,spans:_o(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},Jp=(e,t)=>{let n=Kd(e),r=n?zp(e):null;if(!n||r===null)return qp(zd(e).split(`
|
|
66
|
-
`),t);let o=
|
|
67
|
-
`).map(
|
|
68
|
-
`),t),{kind:"blank"}]:[],{kind:"caption",text:qd(n)},...s.flatMap((c,m)=>Xp(c,Math.max(1,t-l)).map((p,f)=>({kind:"code",text:p,number:i===void 0||f>0?void 0:i+m})))]};import{Box as Qp,Text as dr}from"ink";import St from"react";var Zp=({spans:e,bold:t,wrap:n})=>St.createElement(dr,{color:y.primary,bold:t,wrap:n},e.map((r,o)=>r.code?St.createElement(dr,{key:o,color:y.yellow},r.text):St.createElement(dr,{key:o},r.text))),Xd=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return St.createElement(dr,null," ");case"fence":return St.createElement(dr,{color:y.secondary2},"```");case"caption":return St.createElement(dr,{color:y.accent,wrap:r},e.text);case"heading":return St.createElement(Zp,{spans:e.spans,bold:!0,wrap:r});case"text":return St.createElement(Zp,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return St.createElement(dr,{backgroundColor:y.secondary,color:y.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},ef=({lines:e,width:t})=>{let n=e.flatMap(o=>o.kind==="code"&&o.number!==void 0?[o.number]:[]),r=n.length>0?String(Math.max(...n)).length+3:0;return St.createElement(Qp,{flexDirection:"column"},e.map((o,s)=>St.createElement(Qp,{key:s},St.createElement(Xd,{line:o,width:t,gutter:r}))))};var qI=4,YI=e=>De(e,"comments"),XI=e=>R.getCommentsByIssue(e.id).sort((t,n)=>nf(t.id)-nf(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),rf=e=>{for(let t of e)R.deleteNode(t.id)},JI=(e,t)=>{let n=R.getNode(YI(e.id));if(!n||!ut(n))return[];let r=t.map((o,s)=>Up(o,s,n.id)).map(R.createNode).filter(ce).map(({value:o})=>o).filter(yo);return t.length>0&&h().selectedIndex<0&&O.navigate({contextNode:n,selectedIndex:0}),r};function of({ticket:e,width:t,height:n}){let r=tf(()=>XI(e),[e]),o=KI([]);zI(()=>(rf(o.current),o.current=JI(e,r),()=>{rf(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=X(),l=Math.max(1,n-4),c=Math.max(20,t-8),m=tf(()=>r.map(f=>{let g=Jp(f.md,c);return g.length>0?g:[{kind:"blank"}]}),[r,c]),p=m.map(f=>f.length+qI);return r.length===0?Pe.createElement(Fn,{flexDirection:"column",width:t,height:n,padding:1},Pe.createElement(On,{color:y.primary},"No comments yet."),Pe.createElement(Fn,{paddingTop:1},Pe.createElement(On,{color:y.primary},"Use"),Pe.createElement(On,{color:y.accent}," :comment "),Pe.createElement(On,{color:y.primary},"to add the first one."))):Pe.createElement(Fn,{flexDirection:"column",width:t,height:n},Pe.createElement(Fn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},Pe.createElement(On,{color:y.secondary2},"Comments (",r.length,") ")),Pe.createElement(It,{height:l,itemHeights:p,selectedIndex:s},r.map((f,g)=>{let v=g===s;return Pe.createElement(Fn,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Pe.createElement(Fn,{flexDirection:"row",paddingBottom:1},Pe.createElement(On,{color:y.accent},v?"\u276F ":" "),Pe.createElement(Fn,{paddingLeft:1},Pe.createElement(On,{color:y.secondary2},`#${g+1} `),Pe.createElement(Bn,{id:f.authorId}),Pe.createElement(On,{color:y.secondary2}," "+Wr(Ie(f.id))))),Pe.createElement(Fn,{paddingLeft:3,paddingBottom:1},Pe.createElement(ef,{lines:m[g]??[],width:c})))})))}import{Box as Ni,Text as QI}from"ink";import In from"react";var sf=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=X(),{title:o}=t,s=t.parentNodeId?R.getNode(t.parentNodeId):void 0,i=s&&P(s)?o===fe.ASSIGNEES?s.props.assignees??[]:o===fe.TAGS?(s.props.tags??[]).filter(l=>R.getTag(l)):[]:[];return In.createElement(Ni,{alignItems:"center",paddingTop:1},In.createElement(Ni,{minWidth:12},In.createElement(Ye,{isSelected:n}),In.createElement(QI,{color:n?y.accent:y.secondary2},o,":")),In.createElement(Ni,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((l,c)=>{let m=r.id===t.id&&c===e;return In.createElement(Ni,{key:`${o}-${l}`,paddingRight:2,minHeight:1},In.createElement(Ye,{isSelected:m}),o===fe.ASSIGNEES?In.createElement(Bn,{isSelected:m,id:l}):o===fe.TAGS?In.createElement(_r,{isSelected:m,id:l}):null)})))};import{Box as Vr,Text as Zd}from"ink";import Et,{useEffect as ZI,useMemo as el}from"react";var Jd=e=>Math.max(5,String(Math.max(e,1)).length+3),af=(e,t)=>Math.max(0,e-6-Jd(t));var Qd=(e,t=0)=>Math.max(1,e-5-2*t);var eS="\u2029",df=(e,t)=>`${e}::inline-line::${t}`,tl=new Map,lf=e=>{let t=tl.get(e)??[];tl.delete(e);for(let n of t)R.deleteNode(n)},tS=(e,t)=>{lf(e);let n=[];t.forEach((r,o)=>{let s=vt(BigInt(o+1));if(!ce(s))return;let i=R.createNode(ge.text({id:df(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));ce(i)&&n.push(i.value.id)}),tl.set(e,n)},nl=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:l}=X(),c=el(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=el(()=>c.join("\0"),[c]);ZI(()=>(tS(e,c),()=>{lf(e)}),[e,m]);let p=Jd(c.length),f=af(s,c.length),v=el(()=>Yd(c).map(x=>{if(x.kind==="code"||x.kind==="caption")return{...x,text:ed(x.text,f)};if(x.kind==="text"||x.kind==="heading"){let I=x.spans.map(C=>C.code?`\`${C.text}\``:C.text).join("");return{...x,spans:_o(ed(I,f))}}return x}),[c,f]).map((x,I)=>{let C=l.id===e&&i===I;return Et.createElement(Vr,{key:df(e,I)},Et.createElement(Vr,{flexShrink:0},Et.createElement(Zd,{color:C?y.primary:y.secondary2,dimColor:!C},`${I+1} `.padStart(p,"\xA0"))),x.kind==="blank"?Et.createElement(Zd,{backgroundColor:C?"gray":void 0},eS):Et.createElement(Vr,null,Et.createElement(Xd,{line:x,width:x.kind==="code"?f:0,wrap:"truncate-end"})))});return Et.createElement(Vr,{flexDirection:"column",paddingTop:1},Et.createElement(Vr,null,Et.createElement(Ye,{isSelected:o}),Et.createElement(Zd,{color:o?y.accent:y.secondary2},t)),Et.createElement(Vr,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},Et.createElement(It,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},v)))};var nS=e=>De(e,"description"),rS=e=>De(e,"comments"),oS=e=>De(e,"history"),sS=e=>De(e,"attachments"),cf=({ticket:e,height:t})=>{let n=Uo(()=>_p(e),[e]),{selectedIndex:r,contextNode:o}=X(),s=process.stdout.columns||120,i=Uo(()=>nS(e.id),[e.id]),l=Uo(()=>rS(e.id),[e.id]),c=Uo(()=>oS(e.id),[e.id]),m=Uo(()=>sS(e.id),[e.id]),p=R.getAttachmentsByIssue(e.id).length,f=o.id===e.id,g=o.id===l||o.parentNodeId===l,v=o.id===c||o.parentNodeId===c,x=o.id===m||o.parentNodeId===m,I=q(e.id);if(g){let k=t-3;return Fe.createElement(lr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Fe.createElement(of,{ticket:e,width:s,height:k}))}if(x){let k=t-3;return Fe.createElement(lr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Fe.createElement(Hp,{ticket:e,width:s,height:k}))}if(v){let M=R.getNode(c),k=M&&ut(M)?M.props.value??"":"",D=Qd(t);return Fe.createElement(lr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},M?Fe.createElement(nl,{id:M.id,label:"Event log",text:k,selected:!1,maxWidth:s,rows:D}):null)}let C=I.reduce((M,k)=>ho(k)||k.id===l||k.id===m||k.id===c?M+1:M,0),A=Qd(t,C),w=(M,k)=>M.id===i?Fe.createElement(nl,{key:M.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:k,maxWidth:s,rows:A}):ho(M)?Fe.createElement(sf,{key:M.id,parent:M,selected:k,selectedIndex:r}):M.id===l?Fe.createElement(lr,{key:M.id,paddingTop:1},Fe.createElement(Ye,{isSelected:k}),Fe.createElement(rl,{backgroundColor:y.secondary,color:k?y.accent:y.primary},` Comments (${n}) \u203A\u203A `)):M.id===m?Fe.createElement(lr,{key:M.id,paddingTop:1},Fe.createElement(Ye,{isSelected:k}),Fe.createElement(rl,{backgroundColor:y.secondary,color:k?y.accent:y.primary},` Attachments (${p}) \u203A\u203A `)):M.id===c?Fe.createElement(lr,{key:M.id,paddingTop:1},Fe.createElement(Ye,{isSelected:k}),Fe.createElement(rl,{backgroundColor:y.secondary,color:k?y.accent:y.primary}," History \u203A\u203A ")):null;return Fe.createElement(lr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},I.map((M,k)=>w(M,f&&r===k)))};var aS=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:l})=>{let c=t.context,m=c===V.TICKET||c===V.FIELD_LIST||c===V.FIELD,p=c===V.BOARD||c===V.SWIMLANE,f=c===V.TICKET?t:r.find(C=>C.context===V.TICKET),g=Math.floor(l/3),v=Math.floor(l/Math.max(e.length,1)),x=Math.min(v,g),I=s==="dense";return Ai.createElement(iS,{flexDirection:"row",height:i},p&&e.map((C,A)=>{let w=t.id===C.id,M=w?n:-1,k=t.context===V.BOARD&&n===A;return Ai.createElement(Op,{key:C.id,height:i,width:x,swimlane:C,isSelected:k,isDense:I,isFocused:w,listSelectedIndex:M,mode:o})}),m&&f&&Ai.createElement(cf,{height:i,ticket:f}))},Ti=Ai.memo(aS);import{render as cS}from"ink";import{Writable as uS}from"node:stream";var jo=e=>String(e).padStart(2,"0"),mS=e=>{let t=e.getUTCFullYear(),n=jo(e.getUTCMonth()+1),r=jo(e.getUTCDate()),o=jo(e.getUTCHours()),s=jo(e.getUTCMinutes()),i=jo(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},pS=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",fS=async(e,{width:t,height:n})=>{let r="",o=new uS({write(i,l,c){let m=gS(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),c()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=cS(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},gS=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),mf=async()=>{let{viewMode:e}=ie(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=h(),i=r.find(A=>A.context==="BOARD");if(!i)return a("No board found to export");let l=120,c=40,m=await fS(lS.createElement(Ti,{height:c,width:l,swimlanes:(s[i.id]??[]).filter(A=>A!==void 0&&mt(A)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:c});if(!m)return a("Failed to render board export");let p=Rs(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let f=new Date,g=mS(f),v=`board_${pS(i.title)}_${g}.md`,x=Jc(p.value);uf.mkdirSync(x,{recursive:!0});let I=dS.join(x,v),C=`# Board - ${i.title}
|
|
59
|
+
${c.message}`):u("Configured state branch upstream",!0)},ei=async({stateBranchRoot:e,eventFileName:t})=>{let n=qc(t),r=No.join(e,n);if(!vn.existsSync(r))return u("No event file to stage",null);let o=await Cm({stateBranchRoot:e,relativePath:n,workingContent:vn.readFileSync(r,"utf8")});if(d(o))return a(o.message);let s=await be.stage({cwd:e,pathspec:[n]});return d(s)?a(`Failed to stage state branch event file
|
|
60
|
+
${s.message}`):u("Staged state branch event file",n)},Am=async({stateBranchRoot:e})=>{let t=Yc(),n=No.join(e,t);if(!vn.existsSync(n))return u("No media directory to stage",null);let r=await be.stage({cwd:e,pathspec:[t],ignoreRemoval:!0});return d(r)?a(`Failed to stage state branch media files
|
|
61
|
+
${r.message}`):u("Staged state branch media files",t)},Tm=async({stateBranchRoot:e})=>{let t=[Ha(),Wa()].filter(r=>vn.existsSync(No.join(e,r)));if(t.length===0)return u("No event log config to stage",[]);let n=await be.stage({cwd:e,pathspec:t});return d(n)?a(`Failed to stage event log config
|
|
62
|
+
${n.message}`):u("Staged event log config",t)},wm=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let r=await qb(e);return d(r)?a(`Create state branch sync commit failed
|
|
63
|
+
`+r.message):Sr({cwd:t,message:r.value,pathspec:n})},Ao=async({repoRoot:e,stateBranchRoot:t})=>{let n=await $a(t);if(d(n))return a(n.message);let r=Ht(e);if(d(r))return r;let o=r.value,s=n.value?await be.push({cwd:t}):await be.push({cwd:t,remote:gt,branch:o,setUpstream:!0});if(d(s))return a(`Failed during state branch push
|
|
64
|
+
${s.message}`);let i=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return u(i?"Pushed state branch":"Remote already up to date",i)},Mm=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Ht(e);if(d(o))return o;let s=o.value,i=[Ps(),await Sd({repoRoot:e,stateBranchName:s}),await rr({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Jb({stateBranchRoot:t,stateBranchName:s}),await Zc(t),n?await Qb({stateBranchRoot:t,repoRoot:e}):u("Skipped state branch upstream bootstrap",!1)];for(let l of i){if(d(l))return a(l.message);r=r||!!l.value}return u(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import ti from"node:fs";import Cd from"node:os";import Zb from"node:path";var ex="epiq-sync.lock",Pm=600*1e3,tx=e=>{try{let t=JSON.parse(e);return typeof t.pid!="number"||typeof t.hostname!="string"||typeof t.startedAt!="number"||typeof t.operation!="string"?null:t}catch{return null}},nx=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},rx=e=>e&&(e.hostname!==Cd.hostname()||nx(e.pid))?Date.now()-e.startedAt>Pm:!0,km=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,Ed=e=>{try{return tx(ti.readFileSync(e,"utf8"))}catch{return null}},Lm=(e,t)=>{let n={pid:process.pid,hostname:Cd.hostname(),startedAt:Date.now(),operation:t};try{return ti.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},ox=async({worktreeRoot:e,operation:t})=>{let n=await Ua(e);if(d(n))return a(n.message);let r=Zb.join(n.value,ex),o=()=>{try{let l=Ed(r);l&&l.pid===process.pid&&ti.rmSync(r)}catch{}};if(Lm(r,t))return u("Acquired sync lock",{acquired:!0,release:o});let s=Ed(r);if(!rx(s))return u("Sync lock is held",{acquired:!1,heldBy:s});z.info(`Breaking an abandoned sync lock: ${s?km(s):"unreadable lock file"}`);try{ti.rmSync(r,{force:!0})}catch{}if(Lm(r,t))return u("Acquired sync lock after breaking a stale one",{acquired:!0,release:o});let i=Ed(r);return u("Sync lock taken by another process",{acquired:!1,heldBy:i??{pid:-1,hostname:Cd.hostname(),startedAt:Date.now(),operation:"unknown"}})},ni=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await ox({worktreeRoot:e,operation:t});if(d(r))return a(r.message);if(!r.value.acquired)return z.info(`Skipping ${t}: the state worktree is held by ${km(r.value.heldBy)}`),u("State worktree is held by another process",null);let{release:o}=r.value;try{return u("Ran under the sync lock",await n())}finally{o()}};var ix=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=oe("getRepoRootDir",await Mt(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=oe("getStateBranchRoot",ue({repoRoot:r}));if(d(o))return a(o.message);let s=o.value;logger.debug("[sync] state branch root",s),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let i=oe("bootstrapStateBranchStorage",await Mm({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(d(i))return a(i.message);logger.debug("[sync] bootstrap result",{bootstrapped:i.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let l=oe("hasInProgressGitOperation(stateBranchRoot)",await As(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 c=oe("ensureStateBranchLayout",Qc(r,s));return d(c)?a(c.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:i.value}),u("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:i.value}))},ax=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=oe("stageStateBranchOwnEventFile",await ei({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=oe("stageStateBranchMediaFiles",await Am({stateBranchRoot:t}));if(d(o))return a(o.message);let s=oe("stageStateBranchEventConfig",await Tm({stateBranchRoot:t}));if(d(s))return a(s.message);let i=[r.value,o.value,...s.value].filter(m=>m!==null);if(i.length===0)return u("Nothing to stage",{createdCommit:!1});let l=oe("hasStagedChanges(after stage)",await Wc(t,i));if(d(l))return a(l.message);if(logger.debug("[sync] state branch change check after stage result",{changed:l.value}),!l.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 c=oe("createStateBranchSyncCommit",await wm({repoRoot:e,stateBranchRoot:t,pathspec:i}));return d(c)?a(c.message):(logger.debug("[sync] created sync commit",c.value),u("Committed own event file",{createdCommit:!0,commitSha:c.value}))},Rd=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return Zs(n),u(n,{...e,pulled:!1,pushed:!1,offline:!0})},Dm=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");Ar();let n=oe("ensureSyncReady",await ix({cwd:e,ensureUpstream:!0}));if(d(n))return Te(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=oe("isDetachedHead(stateBranchRoot)",await Gc(o));if(d(i))return Te(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return Te("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,c,m=!1,p=!1,f=oe("getStateBranch",Ht(r));if(d(f))return Te(f.message);let g=f.value;logger.debug("[sync] resolved state branch",{stateBranch:g,stateBranchRoot:o});let v=oe("flushPendingLogs",Hs(o,t));d(v)&&logger.error(`[sync] ${v.message}`);let x=oe("commitOwnEventFileToStateBranch",await ax({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(x))return Te(x.message);l=x.value.createdCommit,c=x.value.commitSha;let I=oe("hasRemote",await Xn({repoRoot:o}));if(d(I))return Te(I.message);if(!I.value)return Rd({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:c,bootstrapped:s},"no remote");let R=oe("pullBranchRebaseIfPresent",await lo({cwd:o,branch:g}));if(d(R))return ao(R.message)?Rd({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:c,bootstrapped:s}):Te(R.message);m=R.value;let A=oe("isAheadOfUpstream",await $c(o));if(d(A))return Te(A.message);if(l||s||A.value){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:s,stateBranchRoot:o});let w=oe("pushStateBranch",await Ao({stateBranchRoot:o,repoRoot:r}));if(d(w)&&Uc(w.message)){let M=oe("pullBranchRebaseIfPresent(retry)",await lo({cwd:o,branch:g}));if(d(M))return Te(M.message);m=m||M.value,w=oe("pushStateBranch(retry)",await Ao({stateBranchRoot:o,repoRoot:r}))}if(d(w))return ao(w.message)?Rd({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:c,bootstrapped:s}):Te(w.message);p=w.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let w=oe("git rev-parse HEAD",await j({args:["rev-parse","HEAD"],cwd:o}));if(d(w))return Te(w.message);c=w.value.stdout.trim(),logger.debug("[sync] final sync commit sha",c)}return nr(p?"Synced and pushed":m||l?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),u("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:c,pulled:m,pushed:p,bootstrapped:s,offline:!1})},Nd=async(e,t)=>{let n=Sm(e);try{return await t()}finally{let r=Em(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},ri=async e=>{let t=e.cwd??process.cwd(),n=await Mt(t);if(d(n))return Te(n.message);let r=ue({repoRoot:n.value});if(d(r))return Te(r.message);let o=r.value;if(!sx.existsSync(o))return Dm(e);let s=await ni({worktreeRoot:o,operation:"sync",fn:()=>Nd(o,()=>Dm(e))});return d(s)?Te(s.message):s.value===null?u("Another process is syncing this board",{repoRoot:n.value,stateBranchRoot:o,createdCommit:!1,pulled:!1,pushed:!1,bootstrapped:!1,offline:!1,skipped:!0}):s.value};var Xt=null,oi=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Xt,currentStatus:h().syncStatus?.status,currentMessage:h().syncStatus?.msg}),Xt)return logger.debug("[sync] syncAndReloadState joining existing promise"),Xt;logger.debug("[sync] syncAndReloadState creating promise"),Xt=dx();try{let e=await Xt;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:h().syncStatus?.status,statusMessageAfterResolve:h().syncStatus?.msg}),d(e)&&h().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),N({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:h().syncStatus?.status,statusMessageBeforeClear:h().syncStatus?.msg}),Xt=null}},dx=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:h().mode,syncStatus:h().syncStatus});let e=Bm();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:h().mode,message:e.message,syncStatus:h().syncStatus}),e;if(Xt)return Xt;logger.debug("[sync] syncAndReloadState:start");let t=oe("resolveActorId",ee());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");N({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:h().syncStatus});let n=Zn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=oe("syncEpiqWithRemote",await ri({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),N({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:h().syncStatus}),Te(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value,i=Ad(o);return d(i)?i:(N({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:h().syncStatus}),u("Synced",!0))},Ad=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=oe("loadMergedEvents",xt(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(t),message:(d(t),t.message),count:d(t)?void 0:t.value.events.length}),d(t))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:h().syncStatus}),a(`Unable to load events. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=Bm();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:h().mode,message:n.message,syncStatus:h().syncStatus}),n;let r=gm(),o=h().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:r,selectedNodeId:h().selectedNode?.id,contextNodeId:h().contextNode?.id,selectedNodeIsVirtual:h().selectedNode?.isVirtual,contextNodeIsVirtual:h().contextNode?.isVirtual}),!h().selectedNode?.isVirtual&&!h().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:t.value.events.length});let i=oe("bootStateFromEventLog",Dt(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(i),message:(d(i),i.message)}),d(i))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:h().syncStatus}),a(`Unable to boot synced state. ${i.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:h().selectedNode?.isVirtual,contextNodeIsVirtual:h().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),N({filters:o}),logger.debug("[sync] restoreNavigationAnchor:start");let s=oe("restoreNavigationAnchor",ym(r));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(s),message:d(s)?s.message:"Navigation restored",selectedNodeId:h().selectedNode?.id,contextNodeId:h().contextNode?.id}),d(s)?(N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:h().syncStatus}),s):u("Reloaded state from event log",null)},Bm=()=>h().mode===b.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:h().mode,syncStatus:h().syncStatus}),N({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var Mr=3e3,Fm=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Mr?null:t},Om=0,Td,wd=!1,To=!1,Md=()=>{if(wd)return!0;let e=et();return d(e)?!1:e.value.syncStatus.status==="syncing"},lx=()=>{let e=ie().autoSyncIntervalMs??1e4,t=Date.now()-Om;return Math.max(0,e-t)},_m=()=>{Td||(Td=setTimeout(async()=>{if(Td=void 0,!!bt()){if(Md()){To=!0;return}To=!1,await cx()}},lx()))},cx=async()=>{if(h().readOnly||h().timeMode==="peek"||h().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!bt())return a("Cannot auto-sync before state is initialized");if(Md())return To=!0,a("Sync already in progress");wd=!0,Om=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await oi()}finally{wd=!1,To&&_m()}},si=()=>{bt()&&(To=!0,!Md()&&_m())};import wo from"node:fs";import Mo from"node:path";import{z as Pr}from"zod";var ii="recent-projects.json",ux=20,mx=Pr.object({projectId:Pr.string().min(1),root:Pr.string().min(1),lastOpenedAt:Pr.number().finite()}),px=Pr.object({projects:Pr.array(mx)}),jm=()=>Mo.join(ln(),ii),Lr=e=>Mo.basename(e)||e,Um=e=>{let t=Mo.resolve(e);try{return wo.realpathSync(t)}catch{return t}},$m=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Hm=e=>{if(!po(e.root))return!1;let t=so(e.root);return!d(t)&&t.value===e.projectId},Wm=()=>{let e=jm();if(!wo.existsSync(e))return u("No recent projects recorded",[]);let t;try{t=JSON.parse(wo.readFileSync(e,"utf8"))}catch(r){return a(`Invalid ${ii}: ${r instanceof Error?r.message:String(r)}`)}let n=px.safeParse(t);return n.success?u("Read recent projects",n.data.projects):a(`Invalid ${ii} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},fx=e=>{let t=jm();try{wo.mkdirSync(Mo.dirname(t),{recursive:!0}),wo.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
65
|
+
`,"utf8")}catch(n){return a(`Unable to write ${ii}: ${n instanceof Error?n.message:String(n)}`)}return u("Recorded recent project",e)},bn=({exclude:e}={})=>{let t=Wm();if(d(t))return t;let n=e===void 0?null:Um(e);return u("Listed recent projects",t.value.filter(r=>n===null||Um(r.root)!==n).filter(Hm).sort($m))},ai=({root:e,now:t=Date.now()})=>{let n=Mo.resolve(e),r=so(n);if(d(r))return a(r.message);let o=r.value,s=Wm(),i=d(s)?[]:s.value,l=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(c=>c.projectId!==o&&c.root!==n)].filter(Hm).sort($m).slice(0,ux);return fx(l)};var Ln=()=>{let e=ie(),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}},Gm=()=>{let e=xe(process.cwd());if(d(e))return!1;let t=$t(e.value);return ce(t)},Vm=e=>e===!0?"on":e===!1?"off":null,zm=e=>e==="on"?!0:e==="off"?!1:null;var Ke={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:Ke.cyan,accent2:Ke.magenta,primary:Ke.white,secondary:Ke.grayDark,secondary2:Ke.grayLight,gray:Ke.gray,green:Ke.green,yellow:Ke.yellow,red:Ke.red};var T={red:Ke.red,yellow:Ke.yellow,green:Ke.green,blue:Ke.blue,magenta:Ke.magenta,cyan:Ke.cyan},kr={urgent:T.red,critical:T.red,important:T.red,blocker:T.red,asap:T.red,immediate:T.red,fail:T.red,failure:T.red,broken:T.red,bug:T.red,error:T.red,incident:T.red,outage:T.red,production:T.red,crash:T.red,security:T.red,warning:T.yellow,warn:T.yellow,risky:T.yellow,risk:T.yellow,attention:T.yellow,pending:T.yellow,review:T.yellow,"needs-review":T.yellow,qa:T.yellow,testing:T.yellow,test:T.yellow,validate:T.yellow,verification:T.yellow,staging:T.yellow,check:T.yellow,"follow-up":T.yellow,followup:T.yellow,waiting:T.yellow,blocked:T.yellow,hold:T.yellow,done:T.green,complete:T.green,completed:T.green,success:T.green,ok:T.green,stable:T.green,resolved:T.green,fixed:T.green,closed:T.green,merged:T.green,released:T.green,deployed:T.green,approved:T.green,verified:T.green,working:T.green,healthy:T.green,pass:T.green,passing:T.green,info:T.blue,information:T.blue,note:T.blue,docs:T.blue,documentation:T.blue,doc:T.blue,guide:T.blue,help:T.blue,explanation:T.blue,detail:T.blue,details:T.blue,context:T.blue,design:T.blue,discussion:T.blue,proposal:T.blue,idea:T.blue,feature:T.magenta,enhancement:T.magenta,improvement:T.magenta,refactor:T.magenta,refactoring:T.magenta,cleanup:T.magenta,optimize:T.magenta,optimization:T.magenta,perf:T.magenta,performance:T.magenta,upgrade:T.magenta,migration:T.magenta,modernize:T.magenta,debt:T.magenta,todo:T.cyan,next:T.cyan,planned:T.cyan,plan:T.cyan,future:T.cyan,backlog:T.cyan,investigate:T.cyan,explore:T.cyan,prototype:T.cyan};var gx=e=>e.props.tags??[],hx=e=>e.props.assignees??[],kn=e=>gx(e).map(t=>C.getTag(t)).filter(t=>!!t),Dn=e=>hx(e).map(t=>C.getContributor(t)).filter(t=>!!t),di=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!P(n)?a("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",kn(n))},li=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!P(n)?a("Invalid unassign target"):u("Retrieved assignees from ticket in breadcrumb",Dn(n))};var E={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",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",NONE:""};var yx=/^(\d+)(h|d|w|mo|y)$/,vx=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,bx=({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},xx=(e,t=new Date)=>{let n=e.match(yx);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}},Ix=e=>{let t=e.match(vx);if(!t)return null;let[,n,r,o,s,i]=t,l=Number(n),c=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return bx({year:l,month:c,day:m,hour:p,minute:f})?new Date(l,c-1,m,p,f):null},or=e=>{let t=e.trim().toLowerCase();return xx(t)??Ix(t)};var Km=/^(\d+)(s|m)?$/,ci=e=>{let t=e.trim().toLowerCase().match(Km);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},ui=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Km.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},qm=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Sx=[{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}],Pd=(e=Sx)=>{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 Ex=["BOARD","TICKET","SWIMLANE","COMMENT"],ye={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},pt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Me={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},Cx=[ye.EDITOR,ye.VIEW,ye.USERNAME,ye.AUTOSYNC,ye.SYNC_DEBOUNCE_MS,ye.ATTACHMENT_MAX_KB,ye.LOG_LEVEL],Rx=(e=h().selectedNode?.context)=>{switch(e){case"TICKET":return[pt.TITLE,pt.DESCRIPTION];case"BOARD":case"SWIMLANE":return[pt.TITLE];case"COMMENT":return[pt.COMMENT];default:return[]}},kd=[String(Mr),"5000","15000","30000","60000"],Dd=["250","500","1000"],Jm=["10s","20s","30s","45s"],sr=[E.EXIT,E.SYNC,E.HELP,E.EXPORT,E.CONFIG,E.YANK],mi=[E.NEW,E.EDIT,E.DELETE,E.MOVE],Ld=[E.TAG,E.UNTAG,E.ASSIGN,E.UNASSIGN,E.CLOSE_ISSUE,E.RE_OPEN_ISSUE,E.EDIT,E.COMMENT],Ym=[E.FILTER,E.PEEK,E.REPLAY],Nx={WORKSPACE:[...sr,...mi],BOARD:[...Ym,...sr,...mi],SWIMLANE:[...Ym,...sr,...mi],TICKET:[...sr,...mi,...Ld],FIELD:[...sr,...Ld],FIELD_LIST:[...sr,...Ld],TEXT:[...sr],COMMENT:[E.EDIT,E.DELETE,E.YANK]},Ax=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Po=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&P(n)),Xm=e=>e.parentNodeId===he,Tx=({selectedNode:e,breadCrumb:t})=>{let n=Rx(e?.context);return Po({breadCrumb:t,selectedNode:e})?n.includes(pt.DESCRIPTION)?n:[...n,pt.DESCRIPTION]:n},wx=({selectedNode:e,breadCrumb:t})=>{let n=Po({breadCrumb:t,selectedNode:e});return n?[Me.REF,Me.TITLE,...n.props?.description?.trim()?[Me.DESCRIPTION]:[],...kn(n).length>0?[Me.TAGS]:[],...Dn(n).length>0?[Me.ASSIGNEES]:[]]:e?[Me.REF,Me.TITLE]:[]},Bd=()=>{let e=bn({exclude:process.cwd()});return d(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},Mx=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Ln();if(!r)return[E.HELP,E.CONFIG];if(!Gm())return[E.HELP,E.INIT,E.OPEN];if(t)return[E.HELP,E.PEEK,E.REPLAY,E.EXPORT,E.CONFIG,E.YANK];let o=e?.context,s=o&&Ex.includes(o),i=[...new Set([...n,e].map(c=>c?.context).flatMap(c=>c?Nx[c]:[]))],l=Po({breadCrumb:n,selectedNode:e});return i.filter(c=>c===E.MOVE?!1:c===E.YANK?!!(l??e):c===E.EDIT?s||!!l:c===E.DELETE?s:c===E.UNTAG?!!(l&&kn(l).length>0):c===E.UNASSIGN?!!(l&&Dn(l).length>0):c===E.RE_OPEN_ISSUE?!!(l&&Xm(l)):c===E.CLOSE_ISSUE?!!(l&&!Xm(l)):!0)},Ne=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=h())=>{let s=t.context??"WORKSPACE";return{[E.NONE]:Mx({breadCrumb:o,readOnly:r,selectedNode:n}),[E.EXIT]:["confirm"],[E.EXPORT]:[],[E.SYNC]:[],[E.INIT]:[],[E.OPEN]:e===E.OPEN?Bd():[],[E.HELP]:[],[E.PEEK]:[...Pd(),"now","prev","next"],[E.REPLAY]:[...Pd()],[E.EDIT]:Tx({selectedNode:n,breadCrumb:o}),[E.YANK]:wx({selectedNode:n,breadCrumb:o}),[E.COMMENT]:[],[E.DELETE]:["confirm"],[E.RE_OPEN_ISSUE]:["confirm"],[E.CLOSE_ISSUE]:["confirm"],[E.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[E.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[E.TAG]:[...new Set([...Object.keys(kr),...C.getExistingTags()])],[E.UNTAG]:[...di()?.value?.map(({name:l})=>l)??[]],[E.UNASSIGN]:[...li()?.value?.map(({name:l})=>l)??[]],[E.ASSIGN]:C.getExistingAssignees(),[E.NEW]:Ax(s),[E.CONFIG]:[...Cx]}[e]??[]};import gp from"chalk";var Qm=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import Bx from"zod";import Px from"node:crypto";import Lo from"node:fs";import tp from"node:path";var Zm="/media/",ep=e=>`${Zm}${e}`,Fd=(e,t)=>`})`;var Jt=500,Lx=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,ir=(e,t)=>`${e}.${t}`,kx=e=>Lx.test(e),np=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: ${cu.join(", ")}`),rp=e=>Px.createHash("sha256").update(e).digest("hex"),Dx=(e,t=Jt)=>{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=np(e);return d(n)?n:u("Validated attachment data",{hash:rp(e),ext:n.value,bytes:e.length})},op=(e,t,n=Jt)=>{let r=Dx(t,n);if(d(r))return r;let o=mo(e),s=tp.join(o,ir(r.value.hash,r.value.ext));try{Lo.existsSync(s)||(Lo.mkdirSync(o,{recursive:!0}),Lo.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)},sp=(e,t,n=Jt)=>{if(!kx(t))return a("Invalid attachment file name");let r=tp.join(mo(e),t);if(!Lo.existsSync(r))return a("Attachment blob not found");let o;try{o=Lo.readFileSync(r)}catch(c){return a(`Unable to read attachment blob: ${c instanceof Error?c.message:String(c)}`)}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(rp(o)!==s)return a("Attachment blob does not match its content hash");let l=np(o);return d(l)?l:l.value!==i?a("Attachment blob content does not match its extension"):u("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var ko=50,Do=5e3,ip=()=>{let e=te().commandMeta.inputString,t=Bx.coerce.number().int().min(ko).max(Do).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${ko}-${Do} KB (default ${Jt})`);let n=ht({attachmentMaxKb:t.data});return d(n)?n:(ze({attachmentMaxKb:t.data}),N({mode:b.DEFAULT}),u(`Attachment size cap set to ${t.data} KB`,null))};import Dr from"chalk";var _d={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ap=(e,t,n)=>Math.max(t,Math.min(n,e)),Od=(e,t,n)=>e+(t-e)*n,dp=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Fx=e=>e.toLowerCase().trim(),Ox=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,l=s*(1-Math.abs(i%2-1)),c=0,m=0,p=0;i>=0&&i<1?(c=s,m=l):i>=1&&i<2?(c=l,m=s):i>=2&&i<3?(m=s,p=l):i>=3&&i<4?(m=l,p=s):i>=4&&i<5?(c=l,p=s):(c=s,p=l);let f=o-s/2;return[Math.round((c+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},lp=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var _x=(e,t,n)=>{let r=ap(n,0,1);return[Math.round(Od(e[0],t[0],r)),Math.round(Od(e[1],t[1],r)),Math.round(Od(e[2],t[2],r))]};var Ux=(e,t,n)=>_x(e,t,n),Bo=e=>{let t=dp(e)%360,n=Ox(t,_d.stringColor.saturation,_d.stringColor.lightness);return lp(n)},de=(e,t=kr)=>{let n=Fx(e??"");return n&&t[n]?t[n]:Bo(n)};var cp=e=>{let t=_d.gradient.stops,n=ap(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 Ux(t[s],t[s+1],i)},pi=e=>lp(cp(e)),fi=e=>dp(e.toLowerCase().trim())/4294967295,up=e=>{let t=fi(e);return cp(t)},jx=e=>{let[t,n,r]=up(e);return{normal:o=>Dr.bgRgb(t,n,r).black(o),cursor:o=>Dr.bgRgb(t,n,r).white.bold(o)}},Ud=e=>{let[t,n,r]=up(e);return{fg:o=>Dr.rgb(t,n,r)(o),fgCursor:o=>Dr.rgb(t,n,r).inverse(o),bg:o=>Dr.bgRgb(t,n,r).black(o),bgCursor:o=>Dr.bgRgb(t,n,r).white.bold(o)}},gi=e=>jx(e).normal(` ${e} `);var st=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null;import{createHash as $x}from"node:crypto";var Hx="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Wx=e=>{let t=$x("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+=Hx[Number(n>>s&31n)]}return r},De=(e,t)=>Wx(`${e}:virtual:${t}`);import mp from"chalk";var me=e=>mp.dim(e),Be=e=>mp.hex(y.primary)(e),He=({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)=>fi(f)-fi(g)).slice(0,r).map(f=>gi(f)).join(" ");return p?`${me(e)}${p}${me(n)}`:""};var Qt={None:"none",Invalid:"invalid",Valid:"valid"};var Gx=["BOARD","TICKET","SWIMLANE"],pp=()=>{let e=h().selectedNode;if(!e?.context)return W({message:me("Missing target context")});if(Gx.includes(e.context))return J();if(e.parentNodeId){let t=h().nodes[e.parentNodeId];if(t?.id===De(t?.parentNodeId??"","comments"))return J()}return W({message:me("Command not available in this context")})},le="<ENTER> to confirm",J=(e="",t=[])=>({message:me(e),validity:Qt.Valid,completionWordList:t}),W=({message:e,completionWordList:t=[]})=>({validity:Qt.Invalid,message:e,completionWordList:t}),Fr=e=>e.length===0,fp=(e,t)=>{let n=Qe(h().breadCrumb,"BOARD");if(d(n))return W({message:Be("Command is not applicable in this context")});let r=Ds(n.value.id);return d(r)?W({message:Be(`Unable to ${t}: board id is not a valid ULID`)}):qm({date:e,horizonDate:r.value})?null:W({message:Be(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},hi=e=>` ${gp.hex("#000").bgHex(de(e))(` ${e} `)} `,jd=({modifier:e})=>{let t="confirm";return e===t?J(le):W({message:Fr(e)?me("if you are certain, enter ")+gi(t):"",completionWordList:[t]})},Vx=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?W({message:me(n)}):J():W({message:Fr(r)?t:"",completionWordList:[...e]}),Br=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>Fr(n)&&Fr(r)?W({message:e,completionWordList:[]}):J(t??le),zx=({modifier:e,inputString:t})=>{let n=Bd();return!Fr(e)||!Fr(t)?J(le):W({message:n.length?me("number from the list, or a path"):me("path to an epiq project"),completionWordList:n})},Kx=({modifier:e,inputString:t})=>{let n=Ne(E.CONFIG);if(!n.includes(e))return W({message:He({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ye.EDITOR:{let r=[...Qm];return t.trim()?r.includes(t.trim())?J(le):W({message:He({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):W({message:He({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ye.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?J(le):W({message:He({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ye.USERNAME:return t.trim()?J(le):W({message:Be("Enter a user name. Saved in ")+gp.bgBlack("~/.epiq-global/config.json")});case ye.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?J(le):W({message:He({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ye.AUTOSYNC:{let r=["on","off"],o=ie().autoSync;if(!r.includes(t.trim())){let s=Vm(o);return W({message:He({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return J(le)}case ye.ATTACHMENT_MAX_KB:{let r=ie().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<ko||o>Do){let s=He({prefix:" examples: ",wordList:Dd,minLengthForHints:0,inputString:t});return W({message:Be(`provide a size cap in KB (${ko}-${Do}). current: ${r??Jt} KB.`)+s,completionWordList:Dd})}return J(le)}case ye.SYNC_DEBOUNCE_MS:{let r=ie().autoSyncIntervalMs,o=Fm(t);if(!t.trim()||o===null||o<Mr){let s=He({prefix:" examples: ",wordList:kd,minLengthForHints:0,inputString:t});return W({message:Be(`provide duration above ${Mr}ms. current duration: ${r}ms.`)+s,completionWordList:kd})}return J(le)}default:return W({message:Be("Unknown config option"),completionWordList:n})}},qx=({modifier:e,inputString:t})=>{let n=Ne(E.EDIT);if(!n.length)return W({message:Be("Command not available in this context")});if(!n.includes(e)){let r=He({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return W({message:r||Be("Unknown edit option"),completionWordList:n})}switch(e){case pt.COMMENT:return t.trim()?J(le):W({message:me("write a comment...")});case pt.TITLE:return J(le);case pt.DESCRIPTION:{let{preferredEditor:r}=ie();return r?J(me("<ENTER> to edit in ")+r):W({message:"No editor selected"})}default:return W({message:Be("Unknown edit option"),completionWordList:n})}},Yx=({modifier:e})=>{let t=Ne(E.YANK);return t.length?t.includes(e)?J(le+me(" and copy to clipboard")):W({message:He({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):W({message:Be("Nothing selected to copy from")})},Xx={[E.EXPORT]:()=>J(le+me(", and create export markdown file")),[E.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return J(le);let n={message:me("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=or(r);if(!r||!o)return W(n);let s=fp(o,"peek");return s||J(le)},[E.REPLAY]:e=>{let{dateInput:t,durationInput:n}=ui(e.modifier,e.inputString),r={message:me("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=or(t);if(!t||!o)return W(r);let s=fp(o,"replay");return s||(n&&ci(n)===null?W({message:Be("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):J("<ENTER> to replay board history",n?Jm:[]))},[E.EXIT]:()=>J(le+me(" and exit the application")),[E.INIT]:()=>J(le),[E.OPEN]:zx,[E.PALETTE]:()=>J(le),[E.FILTER]:e=>{if(e.modifier==="clear")return J(le);let t=s=>Ne(E.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return W({message:He({wordList:Ne(E.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Ne(E.FILTER)});let n=Object.values(h().tags).map(s=>s.name),r=Object.values(h().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?W({message:He({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):J():W({message:He({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[E.NONE]:e=>{let t=Ne(E.NONE);return W({message:He({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[E.NEW]:e=>Vx({list:Ne(E.NEW),hint:He({wordList:Ne(E.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[E.HELP]:()=>J(le),[E.EDIT]:qx,[E.COMMENT]:e=>{let t=Br({hint:me(`write a comment (max ${4e3} char)...`),onOk:me(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===Qt.Invalid?t:e.inputString.length>4e3?J(Be("max input exceeded")):t},[E.CONFIG]:Kx,[E.YANK]:Yx,[E.DELETE]:e=>{let t=pp();return t.validity==="invalid"?t:jd(e)},[E.CLOSE_ISSUE]:e=>jd(e),[E.RE_OPEN_ISSUE]:e=>jd(e),[E.MOVE]:e=>{let t=pp();return t.validity==="invalid"?t:Br({hint:He({prefix:"hey hacker! These commands are blocked for you... ",wordList:Ne(E.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[E.TAG]:e=>{let n=C.getExistingTags().slice(0,10).map(hi).join("");return Br({hint:n.length?me("create tag or reuse:")+n+me(""):me("create tag ...")})(e)},[E.UNTAG]:e=>{let t=di();if(d(t))return W({message:Be("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(hi).slice(0,10);return n.length?Br({hint:me(" ... ")+n.join("")})(e):W({message:Be("Issue has no tags"),completionWordList:[]})},[E.ASSIGN]:e=>{let t=C.getExistingAssignees().map(hi).slice(0,10);return Br({hint:me("assignees... ")+t.join("")})(e)},[E.UNASSIGN]:e=>{let t=li();if(d(t))return W({message:Be("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(hi).slice(0,10);return n.length?Br({hint:me("remove assignee... ")+n.join("")})(e):W({message:Be("Issue has no assignees"),completionWordList:[]})},[E.SYNC]:()=>J(le)},hp=Object.fromEntries(Object.entries(Xx).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var yi=["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 Jx=3,Qx=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"]),Zx=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},eI=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=Jx&&!Qx.has(t)&&!/^\d+$/.test(t)),tI=e=>{let t=new Map;for(let s of Zx(e))for(let i of eI(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=yi.filter(s=>!r.has(s));return[...n,...o]},yp=yi,vp=-1,bp=()=>{let e=et();if(d(e))return yi;let t=e.value,n=t.eventLog.length;return n!==vp&&(yp=tI(t),vp=n),yp};var xp=e=>Object.values(E).includes(e),Ip=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:l,completionWordList:c}=hp[n].validate(n,r,s),m=n!==E.PEEK&&n!==E.REPLAY,p=o==="command"||o==="modifier"?Ne(n):m?bp():[],{mode:f}=h(),g=f===b.COMMAND_LINE?i??"":"",v=[...c,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?Su(e,v):{hint:"",hints:[],remainder:"",overlap:0}}};var Sp=e=>{let t=e.trimStart(),n=rI(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=oI(e),l=xp(r)?r:null,c=l!==null,m=r!=="",p=l?Ne(l)??[]:[],f=l&&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 v=s?"":i,x=nI(t,l,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:l,isCommandKeyword:c,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:v,inputString:x}},nI=(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},rI=e=>e.trim()?e.trim().split(/\s+/):[],oI=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as sI}from"react";var Or=e=>e===$d||e===":",$d=" ",qe={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Qt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Hd=new Set,Ep=()=>{for(let e of Hd)e()},Wd=e=>(Hd.add(e),()=>Hd.delete(e)),Zt=e=>{let n=e(qe),r=Sp(n.value),o=n.cursorPosition===n.value.length;qe={...n,commandMeta:Ip(r,o)},Ep()},Fo=({message:e,status:t})=>{let n=structuredClone(qe);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,qe=n,Ep(),u(e,null)},Gd=e=>{Zt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Vd=e=>{Zt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Or(n[o-1]);)o--;for(;o>0&&!Or(n[o-1]);)o--}else{for(;o<n.length&&!Or(n[o]);)o++;for(;o<n.length&&Or(n[o]);)o++}return{...t,cursorPosition:o}})},Cp=()=>{Zt(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}})},Rp=()=>{Zt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Or(t[r-1]);)r--;for(;r>0&&!Or(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},vi=e=>{Zt(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,l=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:l,commandIsPending:!1}})},Np=()=>{Zt(e=>({...e,commandIsPending:!0}))},Q=e=>{Zt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Ap=({addToHistory:e=!0})=>{Zt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Tp=()=>{Zt(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}})},wp=()=>{Zt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},te=()=>qe,Mp=()=>sI(Wd,te,te),bi=()=>{let[e,...t]=qe.value.split($d);return t.join($d).trim()};var S={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 iI(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function aI(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function dI(e,t,n){let r=h().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 Pp(e,t){let n=te();if(e.sequence==="?"&&t!==b.PALETTE)return S.InitCommandPalette;if(e.sequence===":"&&t!==b.COMMAND_LINE)return S.InitCommandLine;if(t===b.MOVE)switch(e.name){case"m":case"return":return S.ConfirmMove}if(t===b.COMMAND_LINE)return fu(e,n.value);if(t===b.PALETTE)return gu(e,n.value);let r=iI(e)||aI(e);if(r)return lI(r,t);if(e.ctrl&&e.name==="c")return S.Exit;switch(e.name){case"r":return S.EditTitle;case"e":return S.EditDescription;case"n":return S.AddItem;case"m":return S.InitMove;case"d":return S.Delete;case"y":return S.Yank;case"return":return S.Confirm;case"space":return S.Confirm;case"v":return ie().viewMode==="wide"?S.SetViewDense:S.SetViewWide;case"q":case"escape":return S.Exit;default:return null}}function lI(e,t){let n=t===b.MOVE?{prevItem:S.MovePreviousItem,nextItem:S.MoveNextItem,prevContainer:S.MoveToPreviousContainer,nextContainer:S.MoveToNextContainer}:{prevItem:S.NavPreviousItem,nextItem:S.NavNextItem,prevContainer:S.NavToPreviousContainer,nextContainer:S.NavToNextContainer};return dI(h().contextNode.childRenderAxis,e,n)}var xi=e=>{let{context:t}=h().contextNode;if(!t)return U.None;switch(e){case E.EXIT:return U.Exit;case E.EXPORT:return U.Export;case E.INIT:return U.Init;case E.OPEN:return U.OpenProject;case E.DELETE:return U.Delete;case E.EDIT:return U.Edit;case E.COMMENT:return U.Comment;case E.HELP:return U.ViewHelp;case E.RE_OPEN_ISSUE:return U.ReopenIssue;case E.CLOSE_ISSUE:return U.CloseIssue;case E.TAG:return U.TagTicket;case E.UNTAG:return U.UntagTicket;case E.ASSIGN:return U.AssignUserToTicket;case E.UNASSIGN:return U.UnassignUserFromTicket;case E.NEW:return U.NewItem;case E.FILTER:return U.Filter;case E.MOVE:return U.Move;case E.PEEK:return U.Peek;case E.REPLAY:return U.Replay;case E.CONFIG:return U.Config;case E.YANK:return U.Yank;case E.SYNC:return U.Sync;default:return U.None}},U={Exit:"exit",Init:"init",OpenProject:"open-project",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"};import gf from"node:fs";import lS from"node:path";import cS from"react";import{Box as aS}from"ink";import Ai from"react";import wI from"chalk";import{Box as qd,Text as MI}from"ink";import en from"react";import{Text as Lp}from"ink";import kp,{useEffect as Dp,useState as cI}from"react";var Bp={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ye=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=X(),r=Bp[n]??Bp.default,[o,s]=cI(0);if(Dp(()=>{s(0)},[r]),Dp(()=>{if(!e)return;let l=setInterval(()=>{s(c=>(c+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return kp.createElement(Lp,null,t);let i=r[o]??r[0]??t;return kp.createElement(Lp,{color:y.accent,dimColor:o===1},i)};import{Box as zd,Text as uI}from"ink";import Ii from"react";var mI=(e,t,n,r)=>{let o=c=>Math.max(1,e[c]??1),s=n,i=n+1,l=o(n);for(;i<t&&l+o(i)<=r;)l+=o(i),i++;for(;s>0&&l+o(s-1)<=r;)s--,l+=o(s);return{start:s,end:i}},It=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),l=Math.max(1,Math.ceil(r)),c=Math.max(0,Math.min(n,e.length-1)),m=Math.max(1,Math.floor(i/l)),p=Math.max(0,e.length-m),{start:f,end:g}=o?mI(o,e.length,c,i):s?{start:Math.min(p,Math.max(0,c-m+1)),end:Math.min(p,Math.max(0,c-m+1))+m}:{start:Math.min(p,Math.floor(c/m)*m),end:Math.min(p,Math.floor(c/m)*m)+m},v=Math.max(1,g-f),x=e.slice(f,g),I=e.length>v,R=i,A=I?Math.max(1,Math.floor(v/e.length*R)):R,w=Math.max(0,R-A),M=Math.max(1,e.length-v),k=I?Math.floor(f/M*w):0;return Ii.createElement(zd,{flexDirection:"row",height:i,width:"100%"},Ii.createElement(zd,{flexDirection:"column",flexGrow:1,height:i},x),Ii.createElement(zd,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((D,ve)=>Ii.createElement(uI,{key:ve,color:I&&ve>=k&&ve<k+A?y.accent:y.secondary},I?"\u2502":" "))))};import{Box as jr,Text as $r}from"ink";import it from"react";var Fp,Kd,pI=()=>{let{eventLog:e=[]}=h();if(Kd&&Fp===e)return Kd;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Fp=e,Kd=t,t},Si=e=>pI().has(e);import{Text as fI}from"ink";import gI from"react";var hI=e=>e.toLowerCase().trim(),yI=(e,t=kr)=>{let n=hI(e);return t[n]?t[n]:Bo(n)},Bn=({id:e,isSelected:t,maxWidth:n})=>{let r=C.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:fn(o,n);return gI.createElement(fI,{underline:t,color:yI(o)},"@"+s,Si(e)?"":"\u2197")};import{Text as vI}from"ink";import bI from"react";var _r=({id:e,isSelected:t,maxWidth:n})=>{let r=C.getTag(e);if(!r)return;let o=n===void 0?r.name:fn(r.name,n);return bI.createElement(vI,{underline:t,backgroundColor:de(r.name),color:y.secondary}," "+o+" ")};import{useEffect as xI,useState as II}from"react";var SI=80,Op=1400,Ei=new Set,Oo=null,EI=e=>(Ei.add(e),Oo||(Oo=setInterval(()=>{for(let t of Ei)t()},SI)),()=>{Ei.delete(e),Ei.size===0&&Oo&&(clearInterval(Oo),Oo=null)}),CI=()=>{let e=Date.now()%Op/Op;return e<.5?e*2:(1-e)*2},Ur=e=>{let[,t]=II(0);return xI(()=>{if(e)return EI(()=>t(n=>n+1))},[e]),pi(CI())};var RI=(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),fn(e.slice(o).trim(),n)]},_p=3,NI=2,AI=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let i=e.length-o-1,l=i>0?String(i).length+1:0;if(r+s.width+l>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},Up=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Ur(r),s=e-4,i=s-7-1,[l,c]=RI(Se(t.title),i,s),m=c?null:fn(Se(t.props.description),s)||null,p=kn(t),f=Dn(t).map(A=>({...A,name:A.name})),g=Math.max(1,s-_p),v=C.getCommentsByIssue(t.id),x=v.length?String(v.length).length+2+1:0,{shown:I,hidden:R}=AI([...p.map(A=>({id:A.id,isTag:!0,width:Math.min(A.name.length,g)+_p})),...f.map(A=>({id:A.id,isTag:!1,width:Math.min(A.name.length,g)+NI+(Si(A.id)?0:1)}))],s-x);return it.createElement(jr,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?y.accent:y.secondary,justifyContent:"space-between"},it.createElement(jr,{paddingLeft:1,paddingRight:1,flexDirection:"column"},it.createElement(jr,{justifyContent:"space-between"},it.createElement($r,{color:y.primary},l),it.createElement($r,{color:y.secondary2,dimColor:!0},_(t.id))),c&&it.createElement($r,{color:y.primary},c),m&&it.createElement($r,{color:y.secondary2,dimColor:!0},m)),it.createElement(jr,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},it.createElement(jr,{flexDirection:"row"},I.map(A=>it.createElement(jr,{paddingRight:1,key:A.id},A.isTag?it.createElement(_r,{id:A.id,maxWidth:g}):it.createElement(Bn,{id:A.id,maxWidth:g}))),R>0&&it.createElement($r,{color:y.secondary2,dimColor:!0},"+",R)),v.length>0&&it.createElement($r,{color:y.accent},"[",v.length,"]")))};import{Box as ar,Text as _o}from"ink";import ft from"react";var TI=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,jp=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let l=Ur(s),c=(r.props.tags??[]).map(D=>C.getTag(D)).filter(D=>!!D),m=(r.props.assignees??[]).map(D=>C.getContributor(D)).map(D=>D&&{...D,name:D.name}).filter(D=>!!D),p=1,f=c.length*(1+p),g=m.length*(2+p),v=c.map(D=>ft.createElement(ar,{key:D.id,paddingRight:p},ft.createElement(_o,{color:de(D.name)},"\u25A0"))),x=m.map(D=>ft.createElement(ar,{key:D.id,paddingRight:p},ft.createElement(_o,{color:Bo(D.name)},"@"+D.name.at(0)))),I=s?l:o?y.accent:i===b.MOVE?y.secondary:y.primary,R=C.getCommentsByIssue(r.id),A=R.length?String(R.length).length+2+p:0,w=R.length?ft.createElement(ar,{paddingRight:p},ft.createElement(_o,{color:y.accent},"[",R.length,"]")):null,M=f+g+A,k=Math.max(1,n-t-M-(M>0?1:0));return ft.createElement(ar,{justifyContent:"space-between"},ft.createElement(ar,null,ft.createElement(ar,{width:t},o?ft.createElement(Ye,{isSelected:!0}):ft.createElement(_o,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),ft.createElement(_o,{wrap:"truncate",color:I},TI(r.title,k))),ft.createElement(ar,null,v,x,w))};var PI=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:l})=>{let{renderedChildrenIndex:c,replay:m}=X(),p=c[e.id]??[],f=m?new Set(m.flashNodeIds):null,g=f?.has(e.id)??!1,v=Ur(g),x=`${e.title} ${wI.hex(y.secondary2).dim("("+p.length+")")}`,I=3,R=o?1:5,A=s&&i===-1,w=n-3-(o?1:0)-(A?2:0),M=Math.max(2,String(p.length).length+1),k=r-I-1,D=en.createElement(qd,{borderStyle:"round",borderColor:y.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},en.createElement(Ye,{isSelected:t}),en.createElement(MI,{bold:!0,color:g?v:t?y.accent:y.primary},x," ",e.readonly?"\u{1F512}":"")),ve=(Ve,At)=>{let dt=s&&i===At;if(!P(Ve))return null;let ke=f?.has(Ve.id)??!1;return o?en.createElement(jp,{key:Ve.id,index:At,labelWidth:M,width:w,ticket:Ve,isSelected:dt,isFlashing:ke,mode:l}):en.createElement(Up,{key:Ve.id,width:w,ticket:Ve,isSelected:dt,isFlashing:ke})};return en.createElement(qd,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},D,en.createElement(qd,null,p.length>0&&en.createElement(It,{selectedIndex:i,height:k,itemHeight:R},p.map(ve)),A&&en.createElement(Ye,{isSelected:!0})))},$p=en.memo(PI);import{Box as lr,Text as il}from"ink";import Fe,{useMemo as jo}from"react";var Hp=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},Wp=(e,t,n)=>ge.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 Gr,Text as xn}from"ink";import Xe,{useEffect as LI,useMemo as kI,useRef as DI}from"react";import{decodeTime as Gp}from"ulid";var Wr=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"},Ci=e=>String(e).padStart(2,"0"),Ri=e=>`${e.getFullYear()}-${Ci(e.getMonth()+1)}-${Ci(e.getDate())} ${Ci(e.getHours())}:${Ci(e.getMinutes())}`;var BI=e=>De(e,"attachments"),FI=e=>C.getAttachmentsByIssue(e.id).sort((t,n)=>Gp(t.id)-Gp(n.id)),Vp=e=>{for(let t of e)C.deleteNode(t.id)},OI=(e,t,n)=>ge.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),_I=(e,t)=>{let n=C.getNode(BI(e.id));if(!n||!ut(n))return[];let r=t.map((o,s)=>OI(o,s,n.id)).map(o=>C.createNode(o)).filter(ce).map(({value:o})=>o).filter(ut);return t.length>0&&h().selectedIndex<0&&O.navigate({contextNode:n,selectedIndex:0}),r},UI=e=>`${Math.max(1,Math.round(e/1024))} KB`;function zp({ticket:e,width:t,height:n}){let r=kI(()=>FI(e),[e]),o=DI([]);LI(()=>(Vp(o.current),o.current=_I(e,r),()=>{Vp(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=X(),l=Math.max(1,n-4),c=Math.max(12,t-32);return r.length===0?Xe.createElement(Gr,{flexDirection:"column",width:t,height:n,padding:1},Xe.createElement(xn,{color:y.primary},"No attachments yet."),Xe.createElement(Gr,{paddingTop:1},Xe.createElement(xn,{color:y.primary},"Attach images from the browser GUI"),Xe.createElement(xn,{color:y.accent}," epiq gui "),Xe.createElement(xn,{color:y.primary},"by dropping or pasting them."))):Xe.createElement(Gr,{flexDirection:"column",width:t,height:n},Xe.createElement(Gr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},Xe.createElement(xn,{color:y.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),Xe.createElement(It,{height:l,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,g=m.name.length>c?m.name.slice(0,c-1)+"\u2026":m.name;return Xe.createElement(Gr,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},Xe.createElement(xn,{color:y.accent},f?"\u276F ":" "),Xe.createElement(Gr,{paddingLeft:1},Xe.createElement(xn,{color:y.secondary2},`#${p+1} `),Xe.createElement(xn,{color:f?y.accent:y.primary},g),Xe.createElement(xn,{color:y.secondary2}," "+UI(m.bytes)+" "+Wr(Ie(m.id)))))})))}import{Box as Fn,Text as On}from"ink";import Pe,{useEffect as KI,useMemo as sf,useRef as qI}from"react";import{decodeTime as af}from"ulid";var qp=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,Yd=e=>e.replace(qp,"");var Kp=e=>e==="additions"||e==="deletions",Xd=e=>{let t=qp.exec(e);if(!t?.[1])return null;let n;try{n=JSON.parse(t[1])}catch{return null}let r=n;return typeof r?.filePath!="string"||typeof r.start!="number"||typeof r.end!="number"||typeof r.note!="string"||!Kp(r.side)||!Kp(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r};var Yp=/```\n([\s\S]*?)\n?```\s*$/,Xp=e=>Yp.exec(e)?.[1]??null,jI=/`[^`\n]+`[^\n]*\n?$/,Jp=e=>Yd(e).replace(Yp,"").replace(jI,"").trim(),$I=e=>{let n=(e.endSide??e.side)==="deletions"?"removed":"added";return e.start===e.end?`line ${e.start} (${n})`:`lines ${e.start}-${e.end} (${n})`},Jd=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${$I(e)}`;var HI=(e,t)=>{let n=Math.max(1,Math.floor(t)),r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[""];let o=[],s="";for(let i of r){let l=i;for(;l.length>n;)s&&(o.push(s),s=""),o.push(l.slice(0,n)),l=l.slice(n);s?s.length+1+l.length<=n?s=`${s} ${l}`:(o.push(s),s=l):s=l}return s&&o.push(s),o},Uo=e=>{let t=e.split("`");return t.length%2===0?[{text:e}]:t.map((n,r)=>r%2===1?{text:n,code:!0}:{text:n}).filter(n=>n.text.length>0)},WI=/!\[([^\]]*)\]\([^)]*\)/g,GI=e=>e.replace(WI,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),VI=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),zI=4,Zp=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(zI)),Qd=e=>{let t=!1;return e.map(Zp).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=Xd(n);if(r)return{kind:"caption",text:Jd(r)};let o=GI(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:Uo(s[1]??"")}:{kind:"text",spans:Uo(o)}})},ef=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Qp=(e,t)=>{let n=[];for(let r of Qd(e))if(r.kind!=="fence"){if(r.kind==="blank"){n.length>0&&n[n.length-1]?.kind!=="blank"&&n.push(r);continue}if(r.kind==="code"){for(let o of ef(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of HI(VI(r.spans),t))n.push({kind:r.kind,spans:Uo(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},tf=(e,t)=>{let n=Xd(e),r=n?Xp(e):null;if(!n||r===null)return Qp(Yd(e).split(`
|
|
66
|
+
`),t);let o=Jp(e),s=r.split(`
|
|
67
|
+
`).map(Zp),i=n.side===n.endSide?n.start:void 0,l=i===void 0?0:String(i+s.length-1).length+3;return[...o?[...Qp(o.split(`
|
|
68
|
+
`),t),{kind:"blank"}]:[],{kind:"caption",text:Jd(n)},...s.flatMap((c,m)=>ef(c,Math.max(1,t-l)).map((p,f)=>({kind:"code",text:p,number:i===void 0||f>0?void 0:i+m})))]};import{Box as nf,Text as dr}from"ink";import St from"react";var rf=({spans:e,bold:t,wrap:n})=>St.createElement(dr,{color:y.primary,bold:t,wrap:n},e.map((r,o)=>r.code?St.createElement(dr,{key:o,color:y.yellow},r.text):St.createElement(dr,{key:o},r.text))),Zd=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return St.createElement(dr,null," ");case"fence":return St.createElement(dr,{color:y.secondary2},"```");case"caption":return St.createElement(dr,{color:y.accent,wrap:r},e.text);case"heading":return St.createElement(rf,{spans:e.spans,bold:!0,wrap:r});case"text":return St.createElement(rf,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return St.createElement(dr,{backgroundColor:y.secondary,color:y.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},of=({lines:e,width:t})=>{let n=e.flatMap(o=>o.kind==="code"&&o.number!==void 0?[o.number]:[]),r=n.length>0?String(Math.max(...n)).length+3:0;return St.createElement(nf,{flexDirection:"column"},e.map((o,s)=>St.createElement(nf,{key:s},St.createElement(Zd,{line:o,width:t,gutter:r}))))};var YI=4,XI=e=>De(e,"comments"),JI=e=>C.getCommentsByIssue(e.id).sort((t,n)=>af(t.id)-af(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),df=e=>{for(let t of e)C.deleteNode(t.id)},QI=(e,t)=>{let n=C.getNode(XI(e.id));if(!n||!ut(n))return[];let r=t.map((o,s)=>Wp(o,s,n.id)).map(C.createNode).filter(ce).map(({value:o})=>o).filter(yo);return t.length>0&&h().selectedIndex<0&&O.navigate({contextNode:n,selectedIndex:0}),r};function lf({ticket:e,width:t,height:n}){let r=sf(()=>JI(e),[e]),o=qI([]);KI(()=>(df(o.current),o.current=QI(e,r),()=>{df(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=X(),l=Math.max(1,n-4),c=Math.max(20,t-8),m=sf(()=>r.map(f=>{let g=tf(f.md,c);return g.length>0?g:[{kind:"blank"}]}),[r,c]),p=m.map(f=>f.length+YI);return r.length===0?Pe.createElement(Fn,{flexDirection:"column",width:t,height:n,padding:1},Pe.createElement(On,{color:y.primary},"No comments yet."),Pe.createElement(Fn,{paddingTop:1},Pe.createElement(On,{color:y.primary},"Use"),Pe.createElement(On,{color:y.accent}," :comment "),Pe.createElement(On,{color:y.primary},"to add the first one."))):Pe.createElement(Fn,{flexDirection:"column",width:t,height:n},Pe.createElement(Fn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},Pe.createElement(On,{color:y.secondary2},"Comments (",r.length,") ")),Pe.createElement(It,{height:l,itemHeights:p,selectedIndex:s},r.map((f,g)=>{let v=g===s;return Pe.createElement(Fn,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Pe.createElement(Fn,{flexDirection:"row",paddingBottom:1},Pe.createElement(On,{color:y.accent},v?"\u276F ":" "),Pe.createElement(Fn,{paddingLeft:1},Pe.createElement(On,{color:y.secondary2},`#${g+1} `),Pe.createElement(Bn,{id:f.authorId}),Pe.createElement(On,{color:y.secondary2}," "+Wr(Ie(f.id))))),Pe.createElement(Fn,{paddingLeft:3,paddingBottom:1},Pe.createElement(of,{lines:m[g]??[],width:c})))})))}import{Box as Ni,Text as ZI}from"ink";import In from"react";var cf=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=X(),{title:o}=t,s=t.parentNodeId?C.getNode(t.parentNodeId):void 0,i=s&&P(s)?o===fe.ASSIGNEES?s.props.assignees??[]:o===fe.TAGS?(s.props.tags??[]).filter(l=>C.getTag(l)):[]:[];return In.createElement(Ni,{alignItems:"center",paddingTop:1},In.createElement(Ni,{minWidth:12},In.createElement(Ye,{isSelected:n}),In.createElement(ZI,{color:n?y.accent:y.secondary2},o,":")),In.createElement(Ni,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((l,c)=>{let m=r.id===t.id&&c===e;return In.createElement(Ni,{key:`${o}-${l}`,paddingRight:2,minHeight:1},In.createElement(Ye,{isSelected:m}),o===fe.ASSIGNEES?In.createElement(Bn,{isSelected:m,id:l}):o===fe.TAGS?In.createElement(_r,{isSelected:m,id:l}):null)})))};import{Box as Vr,Text as nl}from"ink";import Et,{useEffect as eS,useMemo as rl}from"react";var el=e=>Math.max(5,String(Math.max(e,1)).length+3),uf=(e,t)=>Math.max(0,e-6-el(t));var tl=(e,t=0)=>Math.max(1,e-5-2*t);var tS="\u2029",mf=(e,t)=>`${e}::inline-line::${t}`,ol=new Map,pf=e=>{let t=ol.get(e)??[];ol.delete(e);for(let n of t)C.deleteNode(n)},nS=(e,t)=>{pf(e);let n=[];t.forEach((r,o)=>{let s=vt(BigInt(o+1));if(!ce(s))return;let i=C.createNode(ge.text({id:mf(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));ce(i)&&n.push(i.value.id)}),ol.set(e,n)},sl=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:l}=X(),c=rl(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=rl(()=>c.join("\0"),[c]);eS(()=>(nS(e,c),()=>{pf(e)}),[e,m]);let p=el(c.length),f=uf(s,c.length),v=rl(()=>Qd(c).map(x=>{if(x.kind==="code"||x.kind==="caption")return{...x,text:ed(x.text,f)};if(x.kind==="text"||x.kind==="heading"){let I=x.spans.map(R=>R.code?`\`${R.text}\``:R.text).join("");return{...x,spans:Uo(ed(I,f))}}return x}),[c,f]).map((x,I)=>{let R=l.id===e&&i===I;return Et.createElement(Vr,{key:mf(e,I)},Et.createElement(Vr,{flexShrink:0},Et.createElement(nl,{color:R?y.primary:y.secondary2,dimColor:!R},`${I+1} `.padStart(p,"\xA0"))),x.kind==="blank"?Et.createElement(nl,{backgroundColor:R?"gray":void 0},tS):Et.createElement(Vr,null,Et.createElement(Zd,{line:x,width:x.kind==="code"?f:0,wrap:"truncate-end"})))});return Et.createElement(Vr,{flexDirection:"column",paddingTop:1},Et.createElement(Vr,null,Et.createElement(Ye,{isSelected:o}),Et.createElement(nl,{color:o?y.accent:y.secondary2},t)),Et.createElement(Vr,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},Et.createElement(It,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},v)))};var rS=e=>De(e,"description"),oS=e=>De(e,"comments"),sS=e=>De(e,"history"),iS=e=>De(e,"attachments"),ff=({ticket:e,height:t})=>{let n=jo(()=>Hp(e),[e]),{selectedIndex:r,contextNode:o}=X(),s=process.stdout.columns||120,i=jo(()=>rS(e.id),[e.id]),l=jo(()=>oS(e.id),[e.id]),c=jo(()=>sS(e.id),[e.id]),m=jo(()=>iS(e.id),[e.id]),p=C.getAttachmentsByIssue(e.id).length,f=o.id===e.id,g=o.id===l||o.parentNodeId===l,v=o.id===c||o.parentNodeId===c,x=o.id===m||o.parentNodeId===m,I=q(e.id);if(g){let k=t-3;return Fe.createElement(lr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Fe.createElement(lf,{ticket:e,width:s,height:k}))}if(x){let k=t-3;return Fe.createElement(lr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Fe.createElement(zp,{ticket:e,width:s,height:k}))}if(v){let M=C.getNode(c),k=M&&ut(M)?M.props.value??"":"",D=tl(t);return Fe.createElement(lr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},M?Fe.createElement(sl,{id:M.id,label:"Event log",text:k,selected:!1,maxWidth:s,rows:D}):null)}let R=I.reduce((M,k)=>ho(k)||k.id===l||k.id===m||k.id===c?M+1:M,0),A=tl(t,R),w=(M,k)=>M.id===i?Fe.createElement(sl,{key:M.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:k,maxWidth:s,rows:A}):ho(M)?Fe.createElement(cf,{key:M.id,parent:M,selected:k,selectedIndex:r}):M.id===l?Fe.createElement(lr,{key:M.id,paddingTop:1},Fe.createElement(Ye,{isSelected:k}),Fe.createElement(il,{backgroundColor:y.secondary,color:k?y.accent:y.primary},` Comments (${n}) \u203A\u203A `)):M.id===m?Fe.createElement(lr,{key:M.id,paddingTop:1},Fe.createElement(Ye,{isSelected:k}),Fe.createElement(il,{backgroundColor:y.secondary,color:k?y.accent:y.primary},` Attachments (${p}) \u203A\u203A `)):M.id===c?Fe.createElement(lr,{key:M.id,paddingTop:1},Fe.createElement(Ye,{isSelected:k}),Fe.createElement(il,{backgroundColor:y.secondary,color:k?y.accent:y.primary}," History \u203A\u203A ")):null;return Fe.createElement(lr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},I.map((M,k)=>w(M,f&&r===k)))};var dS=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:l})=>{let c=t.context,m=c===V.TICKET||c===V.FIELD_LIST||c===V.FIELD,p=c===V.BOARD||c===V.SWIMLANE,f=c===V.TICKET?t:r.find(R=>R.context===V.TICKET),g=Math.floor(l/3),v=Math.floor(l/Math.max(e.length,1)),x=Math.min(v,g),I=s==="dense";return Ai.createElement(aS,{flexDirection:"row",height:i},p&&e.map((R,A)=>{let w=t.id===R.id,M=w?n:-1,k=t.context===V.BOARD&&n===A;return Ai.createElement($p,{key:R.id,height:i,width:x,swimlane:R,isSelected:k,isDense:I,isFocused:w,listSelectedIndex:M,mode:o})}),m&&f&&Ai.createElement(ff,{height:i,ticket:f}))},Ti=Ai.memo(dS);import{render as uS}from"ink";import{Writable as mS}from"node:stream";var $o=e=>String(e).padStart(2,"0"),pS=e=>{let t=e.getUTCFullYear(),n=$o(e.getUTCMonth()+1),r=$o(e.getUTCDate()),o=$o(e.getUTCHours()),s=$o(e.getUTCMinutes()),i=$o(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},fS=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",gS=async(e,{width:t,height:n})=>{let r="",o=new mS({write(i,l,c){let m=hS(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),c()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=uS(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},hS=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),hf=async()=>{let{viewMode:e}=ie(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=h(),i=r.find(A=>A.context==="BOARD");if(!i)return a("No board found to export");let l=120,c=40,m=await gS(cS.createElement(Ti,{height:c,width:l,swimlanes:(s[i.id]??[]).filter(A=>A!==void 0&&mt(A)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:c});if(!m)return a("Failed to render board export");let p=Rs(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let f=new Date,g=pS(f),v=`board_${fS(i.title)}_${g}.md`,x=eu(p.value);gf.mkdirSync(x,{recursive:!0});let I=lS.join(x,v),R=`# Board - ${i.title}
|
|
69
69
|
Date: ${f.toISOString()}
|
|
70
70
|
|
|
71
71
|
\`\`\`text
|
|
72
72
|
${m}
|
|
73
73
|
\`\`\`
|
|
74
|
-
`;return
|
|
74
|
+
`;return gf.writeFileSync(I,R,"utf8"),u("Exported board layout",I)};import{useSyncExternalStore as YF}from"react";var wi,yS=new Set,yf=()=>{for(let e of yS)e()};var _n=()=>{if(!wi)throw new Error("Ui state not initialized. Call initUiState() first.");return wi};var vf=(e={})=>(wi=e,yf(),u("UX state initialized",null)),vS=e=>{let t=_n();return wi=e(t),yf(),u("UX state updated",null)},Un=e=>vS(t=>({...t,...e}));import{ulid as cl}from"ulid";import{spawn as bS,spawnSync as xS}from"node:child_process";import IS from"node:os";import bf from"node:path";import{ulid as SS}from"ulid";function al(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 ES(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Mi(){let{preferredEditor:e}=ie(),t=[e?ES(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function dl(e){let[t=""]=al(e);return/(^|\/)code(-insiders)?$/.test(t)}function xf(e,t){let[n="",...r]=al(e);return{command:n,args:[...r,...t]}}function If(e,t){return xf(e,dl(e)?["--wait",t]:[t])}function CS(e,t,n,r="new"){return xf(e,[r==="new"?"--new-window":"--reuse-window","--diff",t,n])}function Sf(e){let t=bf.join(IS.tmpdir(),"epiq");$e.mkDir(t);let n=bf.join(t,SS());$e.writeToFile(n,e??"");let r=Mi();for(let o of r){let{command:s,args:i}=If(o,n);if(!s)continue;let l=xS(s,i,{stdio:"inherit"});if(!l.error&&l.status===0){let c=$e.readFile(n);if(c==null)return a("Unable to read edited file");let m=c.replace(/\r?\n$/,"");return u("Successfully edited",m)}}return a("Unable to open editor")}var RS=new Set(["vim","vi","nvim","nano","pico","ed"]);function NS(e){let[t=""]=al(e),n=t.split("/").pop()??t;return RS.has(n)}var AS=600;function Ef({command:e,args:t},n){return new Promise(r=>{if(!e){r(a(`"${n}" is not a usable editor command`));return}let o=bS(e,t,{stdio:"ignore",detached:!0}),s=!1,i=c=>{s||(s=!0,clearTimeout(l),r(c))};o.on("error",c=>i(a(c.message))),o.on("exit",c=>{i(c===0?u("Opened editor",!0):a(`"${n}" exited with code ${c}`))});let l=setTimeout(()=>{o.unref(),i(u("Opened editor",!0))},AS)})}function TS(e,t){return NS(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}`)):Ef(If(e,t),e)}function ll(e,t,n,r="new"){return Ef(CS(e,t,n,r),e)}async function Cf(e){let t=Mi();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 TS(r,e);if(!d(o))return o;n=o,logger.error(`Failed to open editor "${r}" for ${e}: ${o.message}`)}return n}var Rf=async e=>{let{contextNode:t,selectedIndex:n}=h(),r=q(t.id)[n];if(e.modifier===pt.DESCRIPTION)return MS();if(r&&yo(r))return wS(e);if(e.modifier===pt.TITLE){let o=ee();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 l=await Gt();return d(l)?l:B([{id:cl(),action:"edit.title",payload:{id:s.id,name:i},...o.value}],l.value)}return a("Unknown edit command")},wS=async e=>{let t=ee();if(d(t))return a("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=h(),o=q(n.id)[r];if(!o||!yo(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=h().nodes[s];if(!i||!P(i))return a("Unable to resolve comment issue");if(i.readonly)return a("Cannot edit readonly issue");let l=o.id.split(":").at(0)??"",c=C.getComment(l);if(!c||c.deleted)return a("Unable to resolve comment");if(c.issue!==i.id)return a("Comment does not belong to selected issue");if(c.authorId!==t.value.userId)return a("You can only edit your own comments"+c.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return a("Provide a comment");let p=await Gt();if(d(p))return p;let f=p.value;return B([{id:cl(),action:"edit.issue.comment",payload:{id:c.id,issue:i.id,md:m},...t.value}],f)},MS=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let t=await Gt();if(d(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=h(),s=Qe([...r,o],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!P(i))return a("Edit target must be an issue");if(i.readonly)return a("Cannot edit readonly issue");let l=q(i.id).find(f=>f.title===fe.DESCRIPTION);if(!l)return a("No target found");if(l.readonly)return a("Cannot edit readonly field");let c=i.props.description??"";if(typeof c!="string")return a("Selected field is not editable text");let m=Sf(c);if(d(m))return a("Failed to edit field");let p=m.value;return p===c?u("No changes made",null):B([{id:cl(),action:"edit.description",payload:{id:i.id,md:p},...e.value}],n)};import LS from"node:fs";import Af from"node:path";import ul from"node:fs";import PS from"node:path";var Nf=async e=>{let t=PS.join(e,".gitignore"),n=ul.existsSync(t)?ul.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
75
75
|
`).map(c=>c.trim()),s=r.filter(c=>!o.some(m=>m===c||m===c.replace(/\/$/,"")||m==="/"+c||m==="/"+c.replace(/\/$/,"")));if(s.length===0)return u("Local epiq paths already ignored",!1);let l=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
76
76
|
`);return n=n.trimEnd()+`
|
|
77
77
|
|
|
78
78
|
${l}
|
|
79
|
-
`,
|
|
80
|
-
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},Ee=(e,t)=>a(`[${e}] ${t}`),
|
|
81
|
-
`));let c=et();if(d(c))return $o(16,c.message);let{rootNodeId:m,nodes:p}=c.value,f=p[m];return f?(O.navigate({contextNode:f,selectedIndex:0}),N({hasProjectDefinition:!0,mode:b.DEFAULT}),u(s,null)):$o(16,"Unable to resolve initialized root node")};import{ulid as DS}from"ulid";import{ulid as kS}from"ulid";var Nf=null,jn=()=>structuredClone(Nf),Ho=e=>{Nf=e},Af=()=>{let{contextNode:e,selectedIndex:t}=h(),r=ae(e.id)[t];return r?u("Resolved selected child",r):a("Target node not found")},ll=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ae(t).filter(o=>o.id!==e);return Ys(r,n)},Tf=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ee();if(d(r))return a("Unable to resolve user ID");let o=ll({parentId:t,id:e,position:n});return d(o)?o:u("Created pending move state",{id:kS(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},wf=e=>{Ho(e);let t=An(e,!0);return d(t)?t:u("Node moved successfully",t.value)};function cl(e){let t=Af();if(d(t))return t;let{contextNode:n,nodes:r}=h();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=ae(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let l=s[i+e];if(!l)return a("Missing sibling node");let c=Tf({id:t.value.id,parentId:l.id,position:{at:"end"}});return d(c)?c:wf(c.value)}function ul(e){let t=Af();if(d(t))return t;let{contextNode:n,selectedIndex:r}=h(),s=ae(n.id)[r+e];if(!s)return a("Missing sibling node");let i=Tf({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:wf(i.value)}var Mf=()=>{let e=jn();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=h().nodes[n];if(!r)return a("Move parent not found");let o=ae(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(O.navigate({contextNode:r,selectedIndex:o}),u("Synchronized navigation to moved node",null))},Pi=(e,t="Moved preview")=>{if(d(e))return e;let n=Mf();return d(n)?n:(N({mode:b.MOVE}),u(t,null))},Pf=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=te().commandMeta,{contextNode:n,selectedIndex:r}=h(),o=ae(n.id)[r];if(!o)return N({mode:b.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=ae(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return a("Target not found among siblings");let l=s[i-1],c=s[i+1],m=c!=null?{at:"before",sibling:c.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},p=ll({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(Ho({id:DS(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),N({mode:b.MOVE}),u("Move initialized",null))}if(t==="next")return Pi(ul(1));if(t==="previous")return Pi(ul(-1));if(t==="to-next")return Pi(cl(1));if(t==="to-previous")return Pi(cl(-1));if(t==="confirm"){let s=jn();if(!s)return a("No pending move to confirm");let i=await Gt();if(d(i))return i;let l=B([s],i.value);if(d(l))return l;let c=Mf();return d(c)?c:(Ho(null),N({mode:b.DEFAULT}),u("Moved item",null))}return t==="cancel"?(Ho(null),N({mode:b.DEFAULT}),u("Cancelling move",null)):a("Invalid move modifier")};import{ulid as ki}from"ulid";import{monotonicFactory as BS,ulid as FS}from"ulid";var OS=BS(),Li=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=OS();return u("Created issue events",[{id:FS(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var Lf=async(e,t)=>{let n=ee();if(d(n))return a("Unable to resolve user ID");let r=await Gt();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:l}=h(),c=m=>{let p=B([m],o);if(d(p))return p;let f=R.getNode(p.value[0].result.id);if(!f)return a("Created node not found");if(!f.parentNodeId)return p;let g=R.getNode(f.parentNodeId);return g?(O.navigate({contextNode:g,selectedIndex:R.getSiblings(f.parentNodeId).findIndex(({id:v})=>v===f.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=h(),p=R.getNode(m);if(!p)return a("Workspace not found");let f=Pn(p.id,n.value,o);return d(f)?f:c({id:ki(),action:"add.board",payload:{id:ki(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=Qe(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=Pn(m.value.id,n.value,o);return d(p)?p:c({id:ki(),action:"add.swimlane",payload:{id:ki(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=q(i.id)[l],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let w=Qe(s,"SWIMLANE");return d(w)?null:w.value})();if(!p)return a("Unable to add issue in this context");let f=Pn(p.id,n.value,o);if(d(f))return f;let g=Li({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(d(g))return g;let v=g.value,x=B([...v],o);if(d(x))return x;if(!x.value[0])return a("Issue creation failed");let A=v.find(w=>w.action==="add.issue")?.payload.id;return A?(O.navigate({contextNode:p,selectedIndex:R.getSiblings(p.id).findIndex(({id:w})=>w===A)}),u("Issue created",null)):a("Unable to determine ticket id")}return u("Success",null)};import $S from"node:os";import Bf from"node:path";var _S=e=>e.some(t=>t.action==="init.workspace"),kf=async(e,t)=>{let n=Ht(e);return d(n)?a(n.message):lo({cwd:t,branch:n.value})},US=e=>{let t=xe(process.cwd());if(d(t))return!1;let n=ue({repoRoot:t.value});return!d(n)&&n.value===e},Di=async e=>{let t=ue({repoRoot:e});if(d(t))return Bt(3,t.message);let n=t.value,r=await rr({repoRoot:e,stateBranchRoot:n,stateBranchName:Ss().stateBranch});if(d(r))return Bt(3,r.message);let o=xt(n);if(d(o))return Bt(3,o.message);if(!_S(o.value.events)){let m=await kf(e,n);if(d(m)&&logger.info(3,m.message),o=xt(n),d(o))return Bt(3,o.message)}let{events:s,unreadable:i}=o.value,l=Dt(s,i);if(d(l))return Bt(4,l.message);N({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let c=ai({root:e});return d(c)&&logger.info(c.message),u("Loaded project",void 0)},jS=async e=>{let t=ue({repoRoot:e});if(d(t))return a(t.message);let n=t.value,r=await Xn({repoRoot:n});if(d(r))return a(r.message);if(!r.value)return u("No remote to pull",void 0);let o=await ni({worktreeRoot:n,operation:"boot pull",fn:()=>Ed(n,()=>(Ar("Pulling"),kf(e,n)))});if(d(o))return Te(o.message);if(o.value===null)return u("Another process holds the state worktree",void 0);let s=o.value;if(d(s))return ao(s.message)?(Zs("Offline"),u("Offline",void 0)):Te(s.message);if(!s.value)return nr("Already synced"),u("Already synced",void 0);if(!US(n))return u("Project changed during the pull",void 0);let i=Rd(n);return d(i)?i:(nr("Pulled"),u("Pulled and reloaded",void 0))},Bi=e=>{jS(e).then(t=>{d(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${Tr(t)}`)})},Df=()=>{let e=Dt([]);return d(e)?Bt(4,e.message):(N({hasProjectDefinition:!1,hasInitializingEvents:!1}),u("Booted without a project",void 0))};var HS=e=>e==="~"||e.startsWith("~/")?Bf.join($S.homedir(),e.slice(1)):e,WS=(e,t)=>{let n=e.trim();if(!n)return a("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?u("Resolved recent project",o.root):a(`No recent project #${n}`)}let r=xe(Bf.resolve(HS(n)));return d(r)?a(`No epiq project at ${n}`):u("Resolved project path",r.value)},Ff=async()=>{let e=bi();if(Q(""),h().hasProjectDefinition)return a("Already in a project; run epiq from another directory");let t=bn({exclude:process.cwd()}),n=d(t)?[]:t.value,r=WS(e,n);if(d(r))return a(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(l){return a(`Unable to enter ${o}: ${l instanceof Error?l.message:String(l)}`)}let i=await Di(o);return d(i)?(process.chdir(s),a(i.message)):(Bi(o),u(`Opened ${Lr(o)}`,null))};var Fi=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=h(),s=zs(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:l}=s.value,c=Ot();if(d(c))return c;let m=Lt(i),{fatal:p,skipped:f}=gn(m);if(p.length>0)return Ot(),N(o),a(p.map(v=>v.message).join(", "));hn(f);let g=h().nodes[e];return g?(O.navigate({contextNode:g,selectedIndex:r}),u("",{unappliedEvents:l})):(Ot(),N(o),a("Board did not exist at that date"))};var Of=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)};var GS=20,VS=16,zS=150,Oi=null,_i=null;var cr=()=>{Oi!==null&&(clearInterval(Oi),Oi=null),_i!==null&&(clearTimeout(_i),_i=null)},_f=()=>{cr(),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Uf=({events:e,startTime:t,durationMs:n})=>{cr();let r=e.length,o=Cr(e.map(f=>Cn(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=Of(o),l=Math.max(1,Math.round(n*GS/1e3)),c=Math.max(Math.round(n/l),VS),m=0,p=0;N({mode:b.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Oi=setInterval(()=>{m++;let f=m/l,g=[],v,x;for(;p<r&&i[p]<=f;){let C=e[p],A=An(C);if(d(A)){if(xo(A)){p++;continue}_f();return}g.push(...rd(C)),v=C,x=o[p],p++}if(p>=r||m>=l){for(;p<r;p++){let A=An(e[p]);if(d(A)&&!xo(A))break}let C=h().replay;N({unappliedEvents:[],replay:C&&{...C,progress:1,appliedCount:r}}),cr(),_i=setTimeout(_f,zS);return}let I=h().replay;N({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:v?x??I?.currentTime??t:I?.currentTime??t,currentLabel:v?Ui(v):I?.currentLabel??"",flashNodeIds:v?[...new Set(g)]:I?.flashNodeIds??[]}})},c)};var jf=async()=>{let e=Qe(h().breadCrumb,"BOARD");if(d(e))return e;let t=await Mt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=ue({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=te().commandMeta;if(cr(),r==="now"){let l=Mn(n.value);if(d(l))return a(l.message);let c=Ot();if(d(c))return c;let m=Lt(l.value),{fatal:p,skipped:f}=gn(m);return p.length>0?a(p.map(g=>g.message).join(", ")):(hn(f),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),u("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let l=Ks(n.value);if(d(l))return l;let c=r==="prev"?h().eventLog.at(-1):h().unappliedEvents.at(0),m=c===void 0?null:Cn(c),p=(c===void 0?null:l.value.get(c.id)??null)??(m===null?null:go(m));if(p===null)return a(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?p:p+1}else{let l=or(r||o.trim());if(!l)return a("Invalid peek date");s=l.getTime()}let i=Fi({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(N({mode:b.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),u("Peeking",!0))};var $f=async()=>{let e=Qe(h().breadCrumb,"BOARD");if(d(e))return e;let t=await Mt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=ue({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=te().commandMeta,{dateInput:s,durationInput:i}=ui(r,o);if(cr(),h().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let l=or(s);if(!l)return a("Invalid replay date");let c=i?ci(i):15e3;if(c===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=h(),f=Fi({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?(Ot(),N(p),u("Nothing to replay from that point",!0)):(Uf({events:g,startTime:m,durationMs:c}),u("Replaying board history",!0))};import{spawn as qS}from"node:child_process";var YS=()=>{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"]}}},Hf=async e=>new Promise(t=>{let{command:n,args:r}=YS();try{let o=qS(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 Wo=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await Hf(e);return d(n)?n:u(`Copied ${t} to clipboard`,null)},Wf=async e=>{let{breadCrumb:t,selectedNode:n}=h(),r=Mo({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return a("Nothing selected to copy from");switch(e.modifier){case Me.REF:return Wo(_(o.id),"ref");case Me.TITLE:return Wo(o.title,"title");case Me.DESCRIPTION:return r?Wo(r.props?.description??"","description"):a("No issue in scope");case Me.TAGS:{if(!r)return a("No issue in scope");let s=kn(r).map(({name:i})=>i);return Wo(s.join(", "),"tags")}case Me.ASSIGNEES:{if(!r)return a("No issue in scope");let s=Dn(r).map(({name:i})=>i);return Wo(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}};var Gf=async()=>{Q(""),N({mode:b.DEFAULT});let e=et();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");N({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await oi();return d(t)?(N({syncStatus:{msg:t.message,status:"failed"}}),t):(N({mode:b.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{ulid as Vf}from"ulid";var Oe=async()=>{let e=await Gt();return d(e)?e:u("Resolved persist root",e.value)};var XS=e=>e.action==="add.issue.comment",zf=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=q(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await Oe();if(d(o))return o;if(r.context==="COMMENT"){let s=r.id,i=P(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let l=h().nodes[i];if(!l||!P(l))return a("Unable to resolve comment issue");let c=l.log?.filter(XS).find(m=>m.payload.id===s);return c?c.payload.author!==e.value.userId?a("You can only delete your own comments"):B([{id:Vf(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return B([{id:Vf(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)};import{ulid as JS}from"ulid";var Kf=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=q(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!P(r))return a("Cannot close in this context");let o=h().nodes[he];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await Oe();if(d(s))return s;let i=s.value,l=Kt(o.id,r.id,{at:"end"},e.value,i);if(d(l))return l;let c=B([{id:JS(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...e.value}],i);return d(c)?c:u("Issue closed",null)};import{ulid as QS}from"ulid";var ji=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};var qf=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=q(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=h().nodes[he];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!P(s))return a("Target node is not issue");let l=ji(s);if(!l)return a("Unable to resolve previous parent from issue history");if(l===i.id)return a("Previous parent resolves to closed swimlane");let c=h().nodes[l];if(!c)return a("Previous parent no longer exists");let m=await Oe();if(d(m))return m;let p=m.value,f=Kt(c.id,s.id,{at:"end"},e.value,p);if(d(f))return f;let g=B([{id:QS(),action:"reopen.issue",payload:{id:s.id,parent:c.id,rank:f.value},...e.value}],p);return d(g)?g:u("Issue reopened",null)};import{ulid as ZS}from"ulid";var Yf=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=q(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=bi();if(!o)return a("Provide a title");let s=await Oe();return d(s)?s:B([{id:ZS(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)};import{ulid as eE}from"ulid";var Xf=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=te().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=R.findTagByName(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=h();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 l=i.value;if(!P(l))return a("Target node is not issue");if(!(l.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let m=await Oe();return d(m)?m:B([{id:eE(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...e.value}],m.value)};import{ulid as ml}from"ulid";var Jf=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=te().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=h();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(!P(i))return a("Target node is not issue");let l=await Oe();if(d(l))return l;let c=R.findTagByName(r),m=c?.id??ml();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):B([...c?[]:[{id:ml(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:ml(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],l.value)};import{ulid as pl}from"ulid";var $i=()=>{let{eventLog:e=[],contributors:t}=h(),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))n.set(o.id,o.name);return[...n.entries()].map(([o,s])=>({id:o,name:s,isExternal:!r.has(o)}))};var Qf=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=te().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:l}=h(),c=q(l.id)[i];if(!c)return a("Invalid assign target");let m=at(c.id,"TICKET");if(d(m))return a("Unable to assign issue in this context");let p=m.value;if(!P(p))return a("Target node is not issue");let f=await Oe();if(d(f))return f;let g=$i(),v=!o&&s.toLowerCase()==="me",x,I;if(v)x=e.value.userId,I=g.find(w=>w.id===x)?.name??e.value.userName;else{let w=g.filter(k=>k.name===s);if(w.length>1)return a(`"${s}" matches ${w.length} contributors (${w.map(k=>k.id).join(", ")}). Assign from the GUI to choose by id.`);let M=w[0];if(!M&&!o)return a(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);x=M?.id??pl(),I=M?.name??s}if((p.props.assignees??[]).includes(x))return a("Assignee already assigned");let A=!!h().contributors[x];return B([...A?[]:[{id:pl(),action:"create.contributor",payload:{id:x,name:I},...e.value}],{id:pl(),action:"add.issue.assignee",payload:{id:p.id,assignee:x},...e.value}],f.value)};import{ulid as tE}from"ulid";var Zf=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=te().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let{selectedNode:o}=h();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(!P(i))return a("Target node is not issue");let l=i.props.assignees??[],c=r.toLowerCase()==="me",m=c?l.filter(g=>g===e.value.userId):$i().filter(g=>g.name===r&&l.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(c?"Issue is not assigned to you":`Issue is not assigned to "${r}"`);let f=await Oe();return d(f)?f:B([{id:tE(),action:"remove.issue.assignee",payload:{id:i.id,assignee:p},...e.value}],f.value)};import{ulid as eg}from"ulid";var tg=async e=>{let t=e.inputString.trim();if(!t)return a("Provide a comment");if(t.length>4e3)return a(`Cannot exceed ${4e3} characters`);let n=ee();if(d(n))return a("Unable to resolve user ID");let{breadCrumb:r,selectedNode:o}=h(),s=Qe([...r,o],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!i)return a("Invalid comment target");let l=i.context==="TICKET"?u("Resolved ticket",i):at(i.id,"TICKET");if(d(l))return a("Unable to comment on issue in this context");let c=l.value;if(!P(c))return a("Target node is not issue");let m=await Oe();return d(m)?m:B([{id:eg(),action:"add.issue.comment",payload:{id:eg(),issue:c.id,author:n.value.userId,md:t},...n.value}],m.value)};import{ulid as rE}from"ulid";import nE from"zod";var ng=()=>{let e=te().commandMeta.inputString,t=nE.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return a("Auto sync duration must be a number of at least 3000 ms");let n=ht({autoSyncDebounceMs:t.data});return d(n)?n:(ze({autoSyncIntervalMs:t.data}),N({mode:b.DEFAULT}),u(`Auto sync interval set to ${t.data}ms`,null))};var rg=()=>{let e=te().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Hm(e),n=ht({autoSync:t});return d(n)?n:(ze({autoSync:t}),N({mode:b.DEFAULT}),u(`Auto sync set to "${e}"`,null))};var og=()=>{let e=te().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=ht({logLevel:e});return d(n)?n:(ze({logLevel:e}),N({mode:b.DEFAULT}),u(`Auto sync set to "${e}"`,null))};var sg=e=>{let t=e.inputString.trim();switch(e.modifier){case ye.USERNAME:{if(process.env[dn])return a(`Cannot change the configured user while ${dn} names this process`);let n=Rr();if(d(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,l=r||rE();if(!i||!l)return a("Unable to resolve user name or id");let c=ht({userName:i,userId:l,preferredEditor:o??""});return d(c)?c:(ze({userName:i,userId:l}),N({mode:b.DEFAULT}),u(`Username set to "${i}"`,null))}case ye.EDITOR:{if(!t)return a("No editor provided");let n=ht({preferredEditor:t});return d(n)?n:(ze({preferredEditor:t}),N({mode:b.DEFAULT}),u(`Editor configuration set to "${t}"`,null))}case ye.VIEW:{if(t!=="wide"&&t!=="dense")return a("Invalid view mode");let n=ht({viewMode:t});return d(n)?n:(ze({viewMode:t}),N({mode:b.DEFAULT}),u(`View set to "${t}"`,null))}case ye.AUTOSYNC:return rg();case ye.LOG_LEVEL:return og();case ye.SYNC_DEBOUNCE_MS:return ng();case ye.ATTACHMENT_MAX_KB:return np();default:return a("Unknown config command")}};var Hi=[{systemOnly:!0,intent:U.Move,description:"Internal move-state command",mode:b.COMMAND_LINE,action:Pf},{intent:U.Delete,description:"Delete the currently selected node",mode:b.COMMAND_LINE,action:zf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:b.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=te().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>Ne(E.FILTER).map(l=>l.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return we(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:b.DEFAULT})),u("Filter updated",null)}},{intent:U.ViewHelp,description:"Open the help screen",mode:b.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=h();return Un({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),N({mode:b.HELP}),u("Viewing help",null)}},{intent:U.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:b.COMMAND_LINE,action:Kf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:b.COMMAND_LINE,action:qf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Init,description:"Initialize Epiq in the current git repository",mode:b.COMMAND_LINE,action:Cf},{intent:U.OpenProject,description:"Open a recently used epiq project, by number or path",mode:b.COMMAND_LINE,action:Ff,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.NewItem,description:"Create a new board, swimlane, or issue",mode:b.COMMAND_LINE,action:Lf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Rename,description:"Rename the currently selected node",mode:b.COMMAND_LINE,action:Yf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.UntagTicket,description:"Remove a tag from the selected issue",mode:b.COMMAND_LINE,action:Xf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.TagTicket,description:"Add or create a tag on the selected issue",mode:b.COMMAND_LINE,action:Jf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.AssignUserToTicket,description:"Assign a user to the selected issue",mode:b.COMMAND_LINE,action:Qf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:b.COMMAND_LINE,action:Zf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Comment,description:"Add a comment to the selected issue",mode:b.COMMAND_LINE,action:async(e,t)=>tg(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Sync,description:"Pull, commit, and push Epiq state",mode:b.COMMAND_LINE,action:Gf},{intent:U.Peek,description:"View board state at another point in time",mode:b.COMMAND_LINE,action:jf},{intent:U.Replay,description:"Replay board history forward from a point in time",mode:b.COMMAND_LINE,action:$f},{intent:U.Export,description:"Export the current board layout to markdown",mode:b.COMMAND_LINE,action:async()=>{let e=await mf();return d(e)?e:(N({mode:b.DEFAULT}),u("Export successful",!0))}},{intent:U.Exit,description:"Exit the application",mode:b.COMMAND_LINE,action:async()=>(O.exit(),u("Exit successful",!0))},{intent:U.Edit,description:"Edit title or description",mode:b.COMMAND_LINE,action:async(e,t)=>If(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:b.COMMAND_LINE,action:async(e,t)=>Wf(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:b.COMMAND_LINE,action:(e,t)=>sg(t)}];var oE=new Set(["peek","replay","filter","view-help","yank"]),tn=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=te();if(!t)return a("No command to confirm");if(!e&&n===Qt.Invalid)return a("Invalid command");let s=xi(t);Sp();let{readOnly:i}=h();if(i&&!oE.has(s))return Bo({status:En.Fail,message:"Command not available in readonly state",value:null});let l=Hi.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return Bo({status:En.Fail,message:"Command not found",value:null});let c;try{c=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return Bo({status:En.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(c)?Bo(c):(Ep({addToHistory:!e}),l.onSuccess?.(),ie().autoSync&&si(),c)};var Wi=[{intent:S.Exit,mode:b.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(N({mode:b.COMMAND_LINE}),Q("move cancel"),tn({isForceExecutedBySystem:!0}))},{intent:S.InitMove,mode:b.DEFAULT,description:"[m] move",action:()=>(N({mode:b.COMMAND_LINE}),Q("move start"),tn({isForceExecutedBySystem:!0}))},{intent:S.ConfirmMove,mode:b.MOVE,description:"[m] confirm move",action:()=>(N({mode:b.COMMAND_LINE}),Q("move confirm"),tn({isForceExecutedBySystem:!0}))}],Gi=[{intent:S.MovePreviousItem,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),Q("move previous"),tn({isForceExecutedBySystem:!0})):a("No pending move")},{intent:S.MoveNextItem,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),Q("move next"),tn({isForceExecutedBySystem:!0})):a("No pending move")}],ig=[{intent:S.MoveToNextContainer,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),Q("move to-next"),tn({isForceExecutedBySystem:!0})):a("No pending move")},{intent:S.MoveToPreviousContainer,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),Q("move to-previous"),tn({isForceExecutedBySystem:!0})):a("No pending move")}];var ag={[V.WORKSPACE]:[...Wi,...Gi],[V.BOARD]:[...Wi,...Gi],[V.SWIMLANE]:[...Wi,...Gi,...ig],[V.TICKET]:[],[V.FIELD]:[],[V.FIELD_LIST]:[],[V.TEXT]:[],[V.COMMENT]:[]};import iE from"node:fs";import aE from"node:path";import{spawn as sE}from"node:child_process";function dg(e){let t=process.platform,o=sE(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}var lg=e=>{let t=xe(process.cwd());if(d(t))return a("Unable to resolve project root");let n=ue({repoRoot:t.value});if(d(n))return a(n.message);let r=ir(e.hash,e.ext),o=aE.join(mo(n.value),r);return iE.existsSync(o)?(dg(o),u(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")};var cg=()=>{Q("");let{pendingNavTarget:e}=_n();N({mode:b.DEFAULT}),e&&O.navigate(e),Un({pendingNavTarget:void 0})},ug=[{intent:S.ExitCommandLine,mode:b.HELP,action:()=>(cg(),u("Exiting help",null))},{intent:S.Exit,mode:b.HELP,action:()=>(cg(),u("Closed help",null))},{intent:S.NavPreviousItem,mode:b.HELP,description:"[arrows/hjkl] navigate",action:()=>(O.navigateToPreviousItem(),u("Navigating to previous help item",null))},{intent:S.NavNextItem,mode:b.HELP,action:()=>(O.navigateToNextItem(),u("Navigating to next help item",null))},{intent:S.NavToPreviousContainer,mode:b.HELP,action:()=>(O.navigateToPreviousContainer(),u("Navigating to previous help container",null))},{intent:S.NavToNextContainer,mode:b.HELP,action:()=>(O.navigateToNextContainer(),u("Navigating to next help container",null))}];var dE=e=>{N({mode:b.COMMAND_LINE});let{pendingNavTarget:t}=_n();t&&O.navigate(t),Un({pendingNavTarget:void 0}),Q(`${e} `)},mg=()=>{Q("");let{pendingNavTarget:e}=_n();e&&O.navigate(e),Un({pendingNavTarget:void 0}),N({mode:b.DEFAULT})},pg=[{intent:S.InitCommandPalette,mode:b.DEFAULT,description:"[?] command palette",action:()=>{Q("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=h();return Un({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),N({mode:b.PALETTE}),u("Opening command palette",null)}},{intent:S.Confirm,mode:b.PALETTE,action:()=>{let{selectedNode:e}=h();if(!e||!Nn(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?(dE(t),u("Selected command",t)):u("No command selected",null)}},{intent:S.ExitCommandLine,mode:b.PALETTE,action:()=>(mg(),u("Exiting palette",null))},{intent:S.Exit,mode:b.PALETTE,action:()=>(mg(),u("Closed command palette",null))},{intent:S.NavPreviousItem,mode:b.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(O.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:S.NavNextItem,mode:b.PALETTE,action:()=>(O.navigateToNextItem(),u("Navigating to next item",null))},{intent:S.NavToPreviousContainer,mode:b.PALETTE,action:()=>(O.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:S.NavToNextContainer,mode:b.PALETTE,action:()=>(O.navigateToNextContainer(),u("Navigating to next container",null))}];var fg=[{intent:S.InitCommandLine,mode:b.DEFAULT,description:"[:] write command",action:()=>(N({mode:b.COMMAND_LINE}),Q(""),u("Entering command line mode",null))},...ug,...pg,{intent:S.AddItem,mode:b.DEFAULT,description:"[n] new...",action:()=>(N({mode:b.COMMAND_LINE}),Q(`${E.NEW} `),u("Adding new item",null))},{intent:S.Delete,mode:b.DEFAULT,description:"[d] delete",action:()=>(N({mode:b.COMMAND_LINE}),Q(`${E.DELETE} `),u("Deleting item",null))},{intent:S.Confirm,mode:b.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=h();if(!ae(e?.id??"")?.length){let r=e?R.getAttachment(e.id):void 0;if(r)return lg(r);if(e?.title===fe.DESCRIPTION)return N({mode:b.COMMAND_LINE}),Q(`${E.EDIT} description `),u("Propose command",!0);if(e?.title===fe.ASSIGNEES)return N({mode:b.COMMAND_LINE}),Q(`${E.ASSIGN} `),u("Propose command",!0);if(e?.title===fe.TAGS)return N({mode:b.COMMAND_LINE}),Q(`${E.TAG} `),u("Propose command",!0);if(t.title===fe.DESCRIPTION&&e?.context==="TEXT")return N({mode:b.COMMAND_LINE}),Q(`${E.EDIT} description `),u("Propose command",!0)}return O.enterChildNode(),u("Entering context",null)}},{intent:S.Yank,mode:b.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=h(),t=e?.title===fe.DESCRIPTION?Me.DESCRIPTION:e?.title===fe.TAGS?Me.TAGS:e?.title===fe.ASSIGNEES?Me.ASSIGNEES:Me.REF,r=Ne(E.YANK).includes(t)?t:Me.REF;return N({mode:b.COMMAND_LINE}),Q(`${E.YANK} ${r}`),u("Propose command",!0)}},{intent:S.EditTitle,mode:b.DEFAULT,description:"[r] rename title",action:()=>(N({mode:b.COMMAND_LINE}),Q(`${E.EDIT} title ${h().selectedNode?.title}`),u("Exiting context",null))},{intent:S.EditDescription,mode:b.DEFAULT,description:"[e] edit desc",action:()=>(N({mode:b.COMMAND_LINE}),Q(`${E.EDIT} description `),u("Exiting context",null))},{intent:S.Exit,mode:b.DEFAULT,description:"[q] exit context",action:()=>(O.enterParentNode(),u("Exiting context",null))},{intent:S.NavPreviousItem,mode:b.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(O.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:S.NavNextItem,mode:b.DEFAULT,action:()=>(O.navigateToNextItem(),u("Navigating to next item",null))},{intent:S.NavToPreviousContainer,mode:b.DEFAULT,action:()=>(O.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:S.NavToNextContainer,mode:b.DEFAULT,action:()=>(O.navigateToNextContainer(),u("Navigating to next container",null))}];var lE=500,cE=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),gg=e=>{let t=cE(e);t&&vi(n=>(n+t).slice(0,lE))};var uE=[b.COMMAND_LINE,b.PALETTE],mE=e=>[{intent:S.MoveCursorLeft,mode:e,action:()=>($d(-1),u("Moving cursor left",null))},{intent:S.MoveCursorRight,mode:e,action:()=>($d(1),u("Moving cursor right",null))},{intent:S.MoveCursorLeftOfWord,mode:e,action:()=>(Hd("left"),u("Moving cursor left of word",null))},{intent:S.MoveCursorRightOfWord,mode:e,action:()=>(Hd("right"),u("Moving cursor right of word",null))},{intent:S.AutoCompleteCommand,mode:e,action:()=>(vi((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=h().selectedNode?.title??""),r+o}),u("Auto-completing command",null))},{intent:S.CaptureInput,mode:e,action:(t,{sequence:n})=>(gg(n??""),u("Capturing input",null))},{intent:S.EraseInput,mode:e,action:()=>(xp(),u("Erasing input",null))},{intent:S.EraseInputWord,mode:e,action:()=>(Ip(),u("Erasing input word",null))}],hg=[{intent:S.Confirm,mode:b.COMMAND_LINE,action:()=>(tn(),u("Executing command",null))},{intent:S.ViewHelp,mode:b.DEFAULT,action:()=>(N({mode:b.HELP}),u("Viewing help",null))},...uE.flatMap(mE),{intent:S.ExitCommandLine,mode:b.COMMAND_LINE,action:()=>(N({mode:b.DEFAULT}),u("Exiting command line",null))},{intent:S.GetLastCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Rp(),u("Getting last command from history",null))},{intent:S.GetNextCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Cp(),u("Getting next command from history",null))}];var fl=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},yg=({keys:e})=>e.length===1?0:1,vg=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(fl).filter(r=>r!==null).sort((r,o)=>yg(r)-yg(o))};function bg(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=new Set,i=r;for(;i&&!s.has(i.id)&&(o.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let l=o[o.length-1];return!l||l.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),u("Breadcrumb built",o))}var xg=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 nn,gl,hl=new Set,yl=()=>{for(let e of hl)e()},fE=e=>(hl.add(e),()=>hl.delete(e));function vl(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 l=o[t];if(!l)return a("Unable to derive state, contextNode not found");let c=bg(t,o,r);if(d(c))return logger.error(c.message),c;let m=c.value,{context:p}=l,f=[...fg,...ag[p]??[],...hg],g=vg(f,n),v=xg(f),x=gE(o,s),I=x[t]?.[e.selectedIndex]??null;return u("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:g,availableActions:f,actionIndex:v,selectedNode:I,renderedChildrenIndex:x})}var h=()=>{if(!nn)throw new Error("State not initialized. Call initWorkspaceState() first.");return nn},et=()=>nn?u("Retrieved state",nn):a("State not initialized. Call initWorkspaceState() first.");function Io(e){gl=e;let t=xe(process.cwd()),n=!1;if(!d(t)){let s=$t(t.value);if(d(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:b.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=vl(r);return d(o)?o:(nn=o.value,yl(),u("State initialized",null))}var ur=!1,Go=null;function we(e){let t=h(),n=e(t);if(ur)return Go=n,nn={...t,...n},u("State updated",null);let r=vl(n);return d(r)?a(r.message??"Unable to update state"):(nn=r.value,yl(),u("State updated",null))}function Ru(e){if(ur)return u("Joined batch",e());ur=!0,Go=null;let t=()=>{let n=Go;if(ur=!1,Go=null,n===null)return null;let r=vl(n);return d(r)?a(r.message??"Unable to update state"):(nn=r.value,yl(),u("State updated",null))};try{let n=e(),r=t();return r&&d(r)?a(r.message):u("State updated",n)}finally{ur&&t()}}var im=()=>ur,N=e=>we(t=>({...t,...e}));function mr(e,t,n){if(!ur)return we(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=h(),o=r[e]??{};o[t]=n;let s={...r,[e]:o};return Go=s,nn={...r,...s},u("State updated",null)}var X=()=>pE(fE,h,h),gE=nm,q=e=>h()?.renderedChildrenIndex[e]??[],Ot=()=>gl?Io(gl):a("Cannot reset state: no initial workspace found"),bt=()=>nn!==void 0;var at=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return u("Resolved ancestor node",r);let o=new Set([r.id]),s=r.parentNodeId?n[r.parentNodeId]:void 0;for(;s&&!o.has(s.id);){if(s.context===t)return u("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},bl=(e,t)=>{let{nodes:n}=h(),r=new Set,o=n[e];for(;o?.parentNodeId&&!r.has(o.id);){if(o.parentNodeId===t)return!0;r.add(o.id),o=n[o.parentNodeId]}return!1},$n=(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"),R={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=we(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){we(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(!P(t))return a("Can only comment on issues");let n=mr("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(!P(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=mr("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=mr("comments",e,n);return d(r)?a("Unable to delete comment"):u("Deleted comment",n)},getComment(e){return h().comments?.[e]},getCommentsByIssue(e){return Object.values(h().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(h().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create attachment, missing issue");if(!P(t))return a("Can only attach to issues");let n=we(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=we(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return d(r)?a("Unable to delete attachment"):u("Deleted attachment",n)},getAttachment(e){return h().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(h().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(h().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=h(),r=n[e];if(!r)return a("Edit target node not found");let o=$n(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=$n(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),u("Renamed node",o)},getExistingTags(){let{tags:e}=h();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=h();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return ae(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=h(),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=$n(o,"move");if(i)return i;if(bl(t,e))return a("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),u("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=h(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=$n(o,"delete");if(s)return s;let i=new Set,l=m=>{let p=t[m];if(!(!p||i.has(m))){i.add(m);for(let f of ae(p.id))l(f.id)}};l(e);let c={...structuredClone(t)};for(let m of i){if(!c[m])return a("Unable to locate node to delete");c[m]={...c[m],isDeleted:!0}}return n?(N({nodes:c}),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:Ds,tombstoned:!0},r=we(o=>({...o,contributors:{...o.contributors,[e]:n}}));return d(r)?a("Unable to remove contributor"):u("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.tombstoned)return a("Cannot rename a removed contributor");let r={...n,name:t},o=we(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to rename contributor"):u("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");let r={...n,name:t,tombstoned:!1},o=we(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to restore contributor"):u("Restored contributor",r)},createContributor(e){let t=we(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=$n(r,"edit");if(o)return o;if(!P(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=$n(r,"edit");if(o)return o;if(!P(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(l=>l!==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=$n(r,"edit");if(o)return o;if(!P(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.getTagRecord(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=$n(r,"edit");if(o)return o;if(!P(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(l=>l!==t)}};return this.updateNode(i),u("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return a("Tag not found");let n={...t,tombstoned:!0},r=we(o=>({...o,tags:{...o.tags,[e]:n}}));return d(r)?a("Unable to delete tag"):u("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return a("Tag not found");let r={...n,name:t,tombstoned:!1},o=we(s=>({...s,tags:{...s.tags,[e]:r}}));return d(o)?a("Unable to restore tag"):u("Restored tag",r)},createTag(e){let t=we(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):u("Tag created",e)},createNode(e){let t=mr("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=mr("nodes",e,n);return d(r)?a(r.message):u("Locked node",n)},updateNode(e){let t=mr("nodes",e.id,e);return d(t)?t:u("Updated node",e)},getContributor(e){return h().contributors[e]},getTag(e){let t=h().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return h().tags[e]},getTags(){return Object.values(h().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return h().nodes[e]},getSiblings(e){return ae(e)}};var hE=(e,t)=>e+" ".repeat(Math.max(0,t-Ig(e))),yE=(e,t)=>" ".repeat(Math.max(0,t-Ig(e)))+e,Vi=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","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed 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`),vE=(e,t)=>t?e<t?"up":e>t?"down":null:null,bE=(e,t)=>{let n=R.getNode(e.payload.parent),r=n?Hn.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=vE(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Sg=e=>`${Math.max(1,Math.round(e/1024))} KB`,Eg=e=>R.getAttachment(e)?.name??"",xE=e=>{switch(e.action){case"add.issue.tag":{let t=h().tags[e.payload.tag];return t?Hn.bgHex(de(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=h().tags[e.payload.tag];return t?Hn.bgHex(de(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=h().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?Hn.hex(de(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?Hn.hex(de(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Hn.dim(`(${Sg(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Eg(e.payload.id);return t?`"${t}"`:""}default:return""}},IE=e=>{let t=Wr(Ie(e));return Hn.gray(yE(t,8))},SE=12,EE=e=>hE(`${e}`,SE),RE=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=h().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=h().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=R.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Sg(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Eg(e.payload.id);return t?`"${t}"`:""}default:return""}},Ui=e=>[Vi(e.action),RE(e)].filter(Boolean).join(" "),Rg=(e,t)=>{let n=IE(e.id),r=EE(e.userName),o=Hn.dim("\u203A"),s=e.action==="move.node"?bE(e,t):[Vi(e.action),xE(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};var CE=e=>De(e,"comments"),NE=e=>De(e,"description"),AE=e=>De(e,"assignees"),TE=e=>De(e,"tags"),wE=e=>De(e,"history"),ME=e=>De(e,"attachments"),zi=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let l=R.getNode(e);if(!l){let p=R.createNode({...ge.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(!ut(l))return a(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==r||l.props.value!==o||l.readonly!==s||l.childRenderAxis!==i))return u("Virtual field unchanged",void 0);let m=R.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:s,childRenderAxis:i});return d(m)?m:u("Virtual field updated",void 0)},Cg=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=R.getNode(e);if(!i){let m=R.createNode({...ge.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(!ho(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 c=R.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return d(c)?c:u("Virtual field list updated",void 0)},Cu=e=>{let t=vt(Vt/4n),n=vt(Vt/2n),r=vt(Vt*3n/4n),o=vt(Vt*7n/8n),s=vt(Vt*15n/16n),i=vt(Vt*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 l=zi({id:NE(e.id),name:fe.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(l))return l;let c=Cg({id:AE(e.id),name:fe.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(c))return c;let m=Cg({id:TE(e.id),name:fe.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(m))return m;let p=zi({id:CE(e.id),name:fe.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(p))return p;let f=zi({id:ME(e.id),name:fe.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(d(f))return f;let g=zi({id:wE(e.id),name:fe.HISTORY,parentNodeId:e.id,rank:i.value,value:PE(e),readonly:!0,childRenderAxis:"vertical"});return d(g)?g:u("Ticket virtual nodes materialized",void 0)},PE=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=>Rg(r,n.get(r.action)??[])).join(`
|
|
82
|
-
`)},
|
|
83
|
-
`)[0]?.trim()??"";return t.length>
|
|
84
|
-
`),[m,p,f,...g]=(l??"").split(
|
|
85
|
-
`).map(o=>o.trim()).filter(Boolean);return r.length===0?a("No changed files found for this commit"):u("Listed changed files",r)},
|
|
86
|
-
`).filter(l=>l!==""),o=r.filter(l=>!Sl.test(l)&&!Ug.test(l));if(o.length>0)return a(`Could not parse ${o.length} line(s) of "git diff --raw --numstat" output, e.g. "${o[0]}"`);let s=new Map;for(let l of r){let c=Ug.exec(l);c&&s.set(c[3]??"",{insertions:c[1]==="-"?0:Number(c[1]),deletions:c[2]==="-"?0:Number(c[2])})}let i=r.filter(l=>Sl.test(l)).map(l=>{let c=Sl.exec(l),m=c?.[1]??"",p=c?.[2]??"",f=c?.[3]??"";return{path:f,beforeBlob:_g(m)?null:m,afterBlob:_g(p)?null:p,...s.get(f)??{insertions:0,deletions:0}}});return i.length===0?a("No changed files found for this commit"):u("Listed changed files with blob hashes",i)},Wg=async e=>{if(!$g(e.sha))return a("Invalid commit sha");let t=Ji(e.repoRoot);if(d(t))return a(t.message);let n=t.value,r=await nR(n,e.sha);if(d(r))return a(r.message);let o=r.value;if(o.length>tR)return a(`Commit touches ${o.length} files \u2014 too many to show as a diff`);let s=o.flatMap(m=>[m.beforeBlob,m.afterBlob].filter(p=>p!==null)),i=await Cs(s,n);if(d(i))return a(i.message);let l=i.value,c=o.map(m=>({path:m.path,before:m.beforeBlob?l.get(m.beforeBlob)??"":"",after:m.afterBlob?l.get(m.afterBlob)??"":"",insertions:m.insertions,deletions:m.deletions}));return u("Loaded commit diff",{sha:e.sha,files:c})},Gg=e=>{let t=Mn(e);if(d(t))return a(t.message);let n=Ot();if(d(n))return a(n.message);Xi=null;let r=Lt(t.value),{fatal:o,skipped:s}=gn(r);return o.length>0?a(o.map(i=>i.message).join(", ")):(hn(s),N({readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),u("Restored live state",!0))},rR=(e,t)=>{Xi=null;let n=Gg(e);return d(n)?a(`${t} (recovery to live also failed: ${n.message})`):a(t)},Nl=e=>Wn(async()=>{let t=Qi(e.repoRoot);if(d(t))return a(t.message);let n=zs(t.value,e.targetTime);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=n.value,s=Ot();if(d(s))return s;let i=Lt(r),{fatal:l,skipped:c}=gn(i);return l.length>0?rR(t.value,l.map(m=>m.message).join(", ")):(hn(c),N({readOnly:!0,timeMode:"peek",unappliedEvents:o,replay:null}),Xi=e.targetTime,u("Checked out historical state",{asOfTime:e.targetTime}))}),Vg=async e=>{let t=Qi(e.repoRoot);if(d(t))return a(t.message);let n=Ks(t.value);if(d(n))return a(n.message);let r=n.value.get(e.eventId)??null;return r===null?a("Event not found in the log"):Nl({repoRoot:e.repoRoot,targetTime:r+1})},zg=(e={})=>Wn(async()=>{let t=Qi(e.repoRoot);if(d(t))return a(t.message);let n=Gg(t.value);return d(n)?a(n.message):u("Returned to live state",!0)});import oR from"node:fs";var pr=e=>{let t=xe(e??process.cwd());return d(t)?a(t.message):u("Resolved Epiq repo root",t.value)},ea=null,ne=async(e,t)=>{let n=pr(e);if(d(n))return n;let r=ue({repoRoot:n.value});if(d(r))return a(r.message);let o=Ht(n.value);if(d(o))return a(o.message);if(!(ea!==null&&ea.repoRoot===n.value&&ea.stateBranchRoot===r.value&&oR.existsSync(Yn(r.value)))){let p=await bd({repoRoot:n.value,stateBranchName:o.value});if(d(p))return a(p.message);let f=await rr({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(d(f))return a(f.message);ea={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let p=await j({cwd:r.value,args:["pull","--ff-only"]});d(p)&&z.info(3,p.message)}let i={repoRoot:n.value,stateBranchRoot:r.value},l=zt(r.value);if(Fu(r.value)===l&&bt()&&tt().mode==="live")return u("Booted Epiq state, unchanged",i);let c=xt(r.value);if(d(c))return a(c.message);let m=Dt(c.value.events,c.value.unreadable);return d(m)?a(m.message):(Ou(r.value,l),u("Booted Epiq state",i))},re=()=>{let e=yt();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")},Y=()=>{let e=et();return d(e)?a(e.message):e};var Kr=e=>(e.props.tags??[]).map(t=>R.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:de(t.name)}));var qr=e=>(e.props.assignees??[]).map(t=>R.getContributor(t)).filter(t=>t!=null).map(({id:t,name:n})=>({id:t,name:n,color:de(n)}));import sR from"node:fs";import iR from"node:path";import{ulid as Al}from"ulid";var aR=e=>{if(e.filePath)try{return u("Read attachment file",{data:sR.readFileSync(e.filePath),name:e.name??iR.basename(e.filePath)})}catch(t){return a(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?u("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):a("Provide either filePath or dataBase64")},ta=()=>{let e=yt();return d(e)?Jt:e.value.attachmentMaxKb??Jt},Tl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(o))return a("Attachment target must be an issue");if(o.readonly)return a("Cannot attach to readonly issue");let s=aR(e);if(d(s))return s;let i=ep(t.value.stateBranchRoot,s.value.data,ta());if(d(i))return i;let l=Se(s.value.name).trim()||"image",c=Al(),m={id:Al(),...n.value,action:"add.issue.attachment",payload:{id:c,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:l,bytes:i.value.bytes}},p=B([m],t.value.stateBranchRoot);if(d(p))return a(p.message);let f=ir(i.value.hash,i.value.ext);return u("Added issue attachment",{id:c,issueId:e.issueId,fileName:f,bytes:i.value.bytes,markdown:kd(l,f)})},wl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();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(!P(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 l={id:Al(),...n.value,action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:o.payload.issue}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Deleted issue attachment",{id:e.attachmentId,issueId:o.payload.issue})},Ml=async e=>{let t=await ne(e.repoRoot,{pull:!1});return d(t)?t:tp(t.value.stateBranchRoot,e.fileName,ta())};var dR=365*24*60*60*1e3,fr=()=>{let e=Y();if(d(e))return e;let t=tt(),n=t.mode!=="live",r=Object.values(e.value.nodes),o=r.filter(I=>Nr(I)&&!I.isDeleted),s=Date.now()-dR,i=new Map,l=new Map;for(let I of r)if(!I.isDeleted){if(mt(I)&&I.parentNodeId){let C=i.get(I.parentNodeId)??[];C.push(I),i.set(I.parentNodeId,C)}if(P(I)&&I.parentNodeId){if(I.parentNodeId===he&&Ie(I.id)<s)continue;let C=l.get(I.parentNodeId)??[];C.push(I),l.set(I.parentNodeId,C)}}let c=new Set;for(let I of l.values())for(let C of I)c.add(C.id);let m=yt();if(d(m))return m;let p={},f=R.getCommentsGroupedByIssue();for(let I of r.filter(P))I.isDeleted||!c.has(I.id)||(p[I.id]=(f.get(I.id)??[]).map(C=>{let A=R.getContributor(C.authorId);return{id:C.id,issueId:C.issue,body:C.md,author:{id:C.authorId,name:A?.name??"Unknown",color:de(A?.name??C.authorId??"Unknown")},createdAt:Ie(C.id)}}));let g=new Map;for(let I of e.value.eventLog)I.action==="add.issue.attachment"&&g.set(I.payload.id,I.payload.author);let v={},x=R.getAttachmentsGroupedByIssue();for(let I of r.filter(P))I.isDeleted||!c.has(I.id)||(v[I.id]=(x.get(I.id)??[]).map(C=>({id:C.id,issueId:C.issue,name:C.name,fileName:ir(C.hash,C.ext),bytes:C.bytes,createdAt:Ie(C.id),canDelete:g.get(C.id)===m.value.userId})));return u("Retrieved Epiq GUI state",{boards:o.sort((I,C)=>I.rank.localeCompare(C.rank)).map(I=>({id:I.id,ref:_(I.id),title:I.title,readonly:!!I.readonly||n,swimlanes:(i.get(I.id)??[]).sort((C,A)=>C.rank.localeCompare(A.rank)).map(C=>({id:C.id,title:C.title,readonly:!!C.readonly||n,issues:(l.get(C.id)??[]).sort((A,w)=>A.rank.localeCompare(w.rank)).map(A=>({id:A.id,ref:_(A.id),title:Se(A.title),description:A.props.description??"",createdAt:Ie(A.id),enteredLaneAt:qi(A.log??[],Ie(A.id)),readonly:!!A.readonly||n,tags:Kr(A),assignees:qr(A),parentNodeId:A.parentNodeId,isClosed:A.parentNodeId===he})),parentNodeId:C.parentNodeId}))})),tags:R.getTags().map(I=>({...I,color:de(I.name)})),contributors:Object.values(e.value.contributors).map(I=>({...I,color:de(I.name)})),user:{name:m.value.userName??"",id:m.value.userId??"",color:de(m.value.userName??"")},commentsByIssueId:p,attachmentsByIssueId:v,attachmentMaxKb:ta(),timeTravel:t})},Kg=null,lR=e=>{if(e===Kg)return;let t=ai({root:e});if(d(t)){z.info(t.message);return}Kg=e},Rt=async(e={})=>{if(tt().mode!=="live")return fr();let t=await ne(e.repoRoot,{pull:!1});return d(t)?t:(lR(t.value.repoRoot),fr())},Ko=async(e={})=>{Ar();let t=pr(e.repoRoot);if(d(t))return a("Sync failed");let n=re();if(d(n))return n;let r=await ri({cwd:t.value,ownEventFileName:Zn(n.value)});return d(r)?(yd(r.message),r):(nr(),u("Synced",r.value))};import{ulid as Ct}from"ulid";var qo=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?u("Resolved targets",t):a("Provide issueId or issueIds")},Yr=(e,t)=>{let n=t.done.length,r=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?u(r,t):a(`${r}: ${t.failed.map(o=>`${o.ref} ${o.reason}`).join("; ")}`)},Pl=(e,t)=>{let n={done:[],failed:[]};for(let r of e){let o=t(r);d(o)?n.failed.push({id:r,ref:_(r),reason:o.message}):n.done.push({id:r,ref:_(r)})}return n},Yo=e=>{let t=Y();if(d(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?a("Issue not found"):P(n)?n.readonly?a("Issue is readonly"):u("Found issue",n):a("Target must be an issue")};var Xg=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();async function Dl(e){let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Y();if(d(n))return n;let r=n.value.nodes,o=e.query?.trim().toLowerCase(),s=Object.values(r).filter(P).filter(l=>!l.isDeleted).filter(l=>e.includeClosed||l.parentNodeId!==he).filter(l=>e.boardId?(l.parentNodeId?r[l.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(l=>!e.swimlaneId||l.parentNodeId===e.swimlaneId).filter(l=>!e.tag||Kr(l).some(c=>Xg(c.name,e.tag))).filter(l=>!e.assignee||qr(l).some(c=>Xg(c.name,e.assignee))).filter(l=>!o||l.title.toLowerCase().includes(o)||(l.props.description??"").toLowerCase().includes(o)),i=l=>Se((l.parentNodeId?r[l.parentNodeId]?.title:void 0)??"");return e.brief?u("Listed issues",s.map(l=>({id:l.id,ref:_(l.id),title:Se(l.title),swimlane:i(l),tags:Kr(l).map(c=>c.name),assignees:qr(l).map(c=>c.name)}))):u("Listed issues",s.map(l=>({id:l.id,ref:_(l.id),title:Se(l.title),description:l.props.description??"",createdAt:Ie(l.id),enteredLaneAt:qi(l.log??[],Ie(l.id)),parentNodeId:l.parentNodeId,isClosed:l.parentNodeId===he,readonly:!!l.readonly,tags:Kr(l),assignees:qr(l)})))}var Bl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=Se(e.title);if(!o)return a("Issue title cannot be empty");let s=e.description??"",i=st("Issue title",o,300)??st("Issue description",s,2e4);if(i)return a(i);if((e.tagNames?.length??0)>20)return a(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return a(`Cannot set more than ${20} assignees at once`);let l=Pn(e.parentId,n.value,t.value.stateBranchRoot);if(d(l))return l;let c=Li({name:o,parent:e.parentId,user:n.value,rank:l.value});if(d(c))return c;let m=[...c.value],p=m.find(x=>x.action==="add.issue")?.payload.id;if(!p)return a("Unable to determine created issue id");s&&m.push({id:Ct(),...n.value,action:"edit.description",payload:{id:p,md:s}});let f=[];for(let x of e.tagNames??[]){let I=Se(x).trim();if(!I||f.some(M=>M.name===I))continue;let C=st("Tag name",I,60);if(C)return a(C);let A=R.findTagByName(I),w=A?.id??Ct();A||m.push({id:Ct(),...n.value,action:"create.tag",payload:{id:w,name:I}}),m.push({id:Ct(),...n.value,action:"add.issue.tag",payload:{id:p,tag:w}}),f.push({id:w,name:I})}let g=[];for(let x of e.assigneeNames??[]){let I=Se(x).trim();if(!I||g.some(M=>M.name===I))continue;let C=st("Assignee name",I,80);if(C)return a(C);let A=Object.values(r.value.contributors).find(M=>M.name===I),w=A?.id??Ct();A||m.push({id:Ct(),...n.value,action:"create.contributor",payload:{id:w,name:I}}),m.push({id:Ct(),...n.value,action:"add.issue.assignee",payload:{id:p,assignee:w}}),g.push({id:w,name:I})}let v=B(m,t.value.stateBranchRoot);return d(v)?a(v.message):u("Created issue",{id:p,ref:_(p),title:o,parentId:e.parentId,description:s,tags:f,assignees:g})},cR=(e,t,n)=>{let r=Yo(e);if(d(r))return r;let o=Kt(he,e,{at:"end"},t,n);if(d(o))return o;let s={id:Ct(),...t,action:"close.issue",payload:{id:e,parent:he,rank:o.value}},i=B([s],n);return d(i)?a(i.message):u("Closed issue",{id:e,ref:_(e)})};async function Fl(e){let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=qo(e);if(d(r))return r;let o=s=>cR(s,n.value,t.value.stateBranchRoot);return e.issueIds?Yr("Closed",Pl(r.value,o)):o(r.value[0])}var Ol=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(o))return a("Target node is not issue");if(o.parentNodeId!==he)return a("Issue is not closed");let s=ji(o);if(!s)return a("Unable to resolve previous parent from issue history");if(s===he)return a("Previous parent resolves to closed swimlane");let i=r.value.nodes[s];if(!i)return a("Previous parent no longer exists");let l=Kt(i.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(l))return l;let c={id:Ct(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:i.id,rank:l.value}},m=B([c],t.value.stateBranchRoot);return d(m)?a(m.message):u("Reopened issue",{id:o.id,ref:_(o.id),parentId:i.id})},uR=(e,t,n,r)=>{let o=Yo(e);if(d(o))return o;let s=Kt(t.parentId,e,t.position??{at:"end"},n,r);if(d(s))return s;let i={id:Ct(),...n,action:"move.node",payload:{id:e,parent:t.parentId,rank:s.value}},l=B([i],r);return d(l)?a(l.message):u("Moved issue",{id:e,ref:_(e),parentId:t.parentId})};async function _l(e){let t=pr(e.repoRoot);if(d(t))return t;let n=re();if(d(n))return n;let r=ue({repoRoot:t.value});if(d(r))return r;let o=xt(r.value);if(d(o))return o;let s=Dt(o.value.events,o.value.unreadable);if(d(s))return s;let i=qo(e);if(d(i))return i;let l=c=>uR(c,e,n.value,r.value);return e.issueIds?Yr("Moved",Pl(i.value,l)):l(i.value[0])}var Ul=e=>{let t=Y();if(d(t))return t;let n=t.value.nodes[e];return n?u("Read issue history",(n.log??[]).map(r=>({id:r.id,t:Ie(r.id),action:r.action,label:Ui(r),...r.action==="move.node"?{parentId:r.payload.parent}:{},actor:{id:r.userId,name:r.userName,color:de(r.userName)}}))):a("Issue not found")},jl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=st("Issue description",e.description,2e4);if(s)return a(s);let i=o.props.description??"";if(i===e.description)return u("No changes made",{id:e.issueId,ref:_(e.issueId),description:i});let l={id:Ct(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited issue description",{id:e.issueId,ref:_(e.issueId),description:e.description})},$l=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=Se(e.title);if(!s.trim())return a("Issue title cannot be empty");let i=st("Issue title",s,300);if(i)return a(i);if(o.title===s)return u("No changes made",{id:e.issueId,ref:_(e.issueId),title:s});let l={id:Ct(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited issue title",{id:e.issueId,ref:_(e.issueId),title:s})};import{ulid as Jo}from"ulid";var Hl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.boardId];if(!o)return a("Board not found");if(!Nr(o))return a("Target parent must be a board");if(o.readonly)return a("Cannot add a swimlane to a readonly board");if(tt().mode!=="live")return a("Cannot add a swimlane while time travelling");let s=Se(e.title);if(!s.trim())return a("Swimlane title cannot be empty");let i=st("Swimlane title",s,300);if(i)return a(i);let l=Pn(e.boardId,n.value,t.value.stateBranchRoot);if(d(l))return l;let c=Jo(),m={id:Jo(),...n.value,action:"add.swimlane",payload:{id:c,name:s,parent:e.boardId,rank:l.value}},p=B([m],t.value.stateBranchRoot);return d(p)?a(p.message):u("Created swimlane",{id:c,ref:_(c),title:s,boardId:e.boardId})},Wl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.swimlaneId];if(!o)return a("Swimlane not found");if(!mt(o))return a("Edit target must be a swimlane");if(o.readonly)return a("Cannot edit readonly swimlane");let s=Se(e.title);if(!s.trim())return a("Swimlane title cannot be empty");let i=st("Swimlane title",s,300);if(i)return a(i);if(o.title===s)return u("No changes made",{id:e.swimlaneId,ref:_(e.swimlaneId),title:s});let l={id:Jo(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:s}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited swimlane title",{id:e.swimlaneId,ref:_(e.swimlaneId),title:s})},Gl=async e=>{let t=pr(e.repoRoot);if(d(t))return t;let n=re();if(d(n))return n;let r=ue({repoRoot:t.value});if(d(r))return r;let o=xt(r.value);if(d(o))return o;let s=Dt(o.value.events,o.value.unreadable);if(d(s))return s;let i=Kt(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(d(i))return i;let l={id:Jo(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:i.value}},c=B([l],r.value);return d(c)?a(c.message):u("Moved swimlane",{id:e.swimlaneId,ref:_(e.swimlaneId),boardId:e.boardId})},Vl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.swimlaneId];if(!o)return a("Swimlane not found");if(!mt(o))return a("Delete target must be a swimlane");let s={id:Jo(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Deleted swimlane",{id:e.swimlaneId,ref:_(e.swimlaneId)})};import{ulid as Qo}from"ulid";async function zl(e){let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=qo(e);if(d(r))return r;let o=Se(e.tagName).trim();if(!o)return a("Tag name cannot be empty");let s=st("Tag name",o,60);if(s)return a(s);let i={done:[],failed:[]};for(let v of r.value){let x=Yo(v);d(x)?i.failed.push({id:v,ref:_(v),reason:x.message}):i.done.push({id:v,ref:_(v)})}if(!e.issueIds&&i.failed[0])return a(i.failed[0].reason);if(i.done.length===0)return a(Yr("Tagged",i).message);let l=R.findTagByName(o),c=l?.id??Qo(),m=[...l?[]:[{id:Qo(),...n.value,action:"create.tag",payload:{id:c,name:o}}],...i.done.map(({id:v})=>({id:Qo(),...n.value,action:"add.issue.tag",payload:{id:v,tag:c}}))],p=B(m,t.value.stateBranchRoot);if(d(p))return a(p.message);let f={id:c,name:o};if(!e.issueIds)return u("Added issue tag",{...i.done[0],tag:f});let g=Yr("Tagged",i);return d(g)?g:u(g.message,{...g.value,tag:f})}var Kl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.tags[e.tagId];if(!o)return a("Tag not found");if(o.tombstoned)return a("Tag is already deleted");let s=[{id:Qo(),...n.value,action:"tombstone.tag",payload:{id:e.tagId}}],i=B(s,t.value.stateBranchRoot);return d(i)?a(i.message):u("Deleted tag",{id:o.id,name:o.name})};var ql=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(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:Qo(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Removed issue tag",{id:e.issueId,ref:_(e.issueId),tagId:e.tagId})};import{ulid as gr}from"ulid";var mR=()=>{let e=et(),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},Qg=(e,t)=>{let n=new Map(e);for(let r of Object.values(t))n.set(r.id,r.name);return n};var Zg=async(e,t)=>{let n=pd(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}},Yl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(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 C=r.value.contributors[s],A=C?void 0:await Zg(t.value.stateBranchRoot,s);if(!C&&!A)return a("Unknown assignee id");let w=C??A,M=[...C?[]:[{id:gr(),...n.value,action:"create.contributor",payload:{id:w.id,name:w.name}}],{id:gr(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:w.id}}],k=B(M,t.value.stateBranchRoot);return d(k)?a(k.message):u("Added issue assignee",{id:e.issueId,ref:_(e.issueId),assignee:{id:w.id,name:w.name}})}let i=Se(e.assigneeName??"").trim();if(!i)return a("Provide assigneeId, self or assigneeName");let l=st("Assignee name",i,80);if(l)return a(l);let m=[...Qg(mR(),r.value.contributors).entries()].filter(([,C])=>C===i);if(m.length>1)return a(`"${i}" matches ${m.length} contributors (${m.map(([C])=>C).join(", ")}). Assign by assigneeId to choose.`);let p=m[0];if(!p&&!e.createUnlinked)return a(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[f=gr(),g=i]=p??[],x=[...!!r.value.contributors[f]?[]:[{id:gr(),...n.value,action:"create.contributor",payload:{id:f,name:g}}],{id:gr(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:f}}],I=B(x,t.value.stateBranchRoot);return d(I)?a(I.message):u("Added issue assignee",{id:e.issueId,ref:_(e.issueId),assignee:{id:f,name:g}})},Xl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;if(!r.value.contributors[e.contributorId])return a("Contributor not found");if(await Zg(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:gr(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],l=B(i,t.value.stateBranchRoot);return d(l)?a(l.message):u("Tombstoned contributor",{id:e.contributorId,name:Ds})};var Jl=async(e={})=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=Mn(t.value.stateBranchRoot);if(d(o))return a(o.message);let s=e.boardId?Pg(o.value,e.boardId):o.value,i=new Map,l=new Set,c=new Set,m=pd(t.value.stateBranchRoot);if(d(m))return a(m.message);for(let v of m.value)v.userId&&c.add(v.userId);for(let v of s)v.userId&&(i.set(v.userId,v.userName??""),l.add(v.userId));let p=r.value.contributors,g=[...Qg(i,p).entries()].map(([v,x])=>({id:v,name:x,color:de(x),isSelf:v===n.value.userId,isExternal:!l.has(v),isRemoved:p[v]?.tombstoned===!0,hasAuthoredAnywhere:c.has(v)}));return u("Listed board contributors",g)},Ql=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(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:gr(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Removed issue assignee",{id:e.issueId,ref:_(e.issueId),assigneeId:e.assigneeId})};import{ulid as na}from"ulid";var Zo=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(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=na(),l={id:na(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Added issue comment",{id:i,issueId:e.issueId,body:s})},es=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();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(!P(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 l={id:na(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},Zl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.eventLog.find(p=>p.action==="add.issue.comment"&&p.payload.id===e.commentId);if(!o)return a("Unable to resolve comment");if(o.payload.author!==n.value.userId)return a("You can only edit your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!P(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot edit comment on readonly issue");if(r.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return a("Comment was deleted");let l=e.body.trim();if(!l)return a("Comment cannot be empty");if(l.length>4e3)return a(`Comment cannot exceed ${4e3} characters (got ${l.length})`);let c={id:na(),...n.value,action:"edit.issue.comment",payload:{id:e.commentId,issue:o.payload.issue,md:l}},m=B([c],t.value.stateBranchRoot);return d(m)?a(m.message):u("Edited issue comment",{id:e.commentId,issueId:o.payload.issue,body:l})};var rn="1.8.3";import pR from"node:fs";import eh from"node:path";var ts=Number(process.env.EPIQ_GUI_PORT)||3710,ec="/api/instance",tc="epiq",ra=e=>{try{return pR.realpathSync(eh.resolve(e))}catch{return eh.resolve(e)}},fR=e=>{let t=e;return typeof t=="object"&&t!==null&&t.app===tc&&typeof t.repoRoot=="string"&&typeof t.version=="string"&&typeof t.pid=="number"},th=async(e,t=500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}${ec}`,{signal:n.signal});if(!o.ok)return null;let s=await o.json();return fR(s)?s:null}catch{return null}finally{clearTimeout(r)}};var gR=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))}),hr=e=>d(e)?e:u(e.message,gR(e.value)),nh=(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 hR=15e3,rh=e=>{let t,n=!1,r=!1,o=0,s=i();function i(){let g=xe(e.project.repoRoot);if(d(g))return null;let v=ue({repoRoot:g.value});return d(v)?null:zt(v.value)}let l=()=>{let g=Rr();return d(g)?(z.error(g.message),null):g.value},c=()=>{let g=l();if(!g)return!1;let{autoSync:v,preferredEditor:x}=g,I=yt(),C=d(I)?null:I.value.userName;return!!(v&&C&&x)},m=()=>{let g=l()?.autoSyncDebounceMs??hR;return Math.max(0,g-(Date.now()-o))},p=async()=>{if(!(n||r)){r=!0,o=Date.now();try{await Wn(async()=>{if(tt().mode!=="live")return;await Ko({repoRoot:e.project.repoRoot});let g=i();if(g===null||g===s)return;s=g;let v=hr(await Rt({repoRoot:e.project.repoRoot}));d(v)||tr({type:"state",payload:v})})}finally{r=!1,f()}}};function f(){n||!c()||r||t||(t=setTimeout(()=>{t=void 0,p()},m()))}return f(),{queueSync:f,dispose:()=>{n=!0,t&&clearTimeout(t)}}};var yR=new Set(["127.0.0.1","[::1]","localhost","epiq.localhost"]),nc=(e,t)=>{if(!e)return!1;if(e==="null")return!0;let n;try{n=new URL(e)}catch{return!0}return n.protocol!=="http:"||n.port!==String(t)?!0:!yR.has(n.hostname)},oh=(e,t)=>e.method==="GET"||e.method==="HEAD"?null:nc(e.origin,t)?{status:403,message:"Cross-origin request"}:e.method==="POST"&&!(e.contentType??"").toLowerCase().startsWith("application/json")?{status:415,message:"Expected content-type: application/json"}:null;import{WebSocketServer as QR}from"ws";var on=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""});var vR=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},sh=({commits:e,patch:t})=>{let n=e.map(i=>i.time),o=t.files.map(i=>({...on(i),changed:i.addedCount+i.removed})).reduce((i,l)=>i===null||l.changed>i.changed?l:i,null),s=t.insertions+t.deletions;return{commits:e.length,authors:[...new Set(e.map(i=>i.author))].sort(),firstCommitAt:n.length?Math.min(...n):null,lastCommitAt:n.length?Math.max(...n):null,files:t.files.length,filesAdded:t.files.filter(i=>i.status==="added").length,filesModified:t.files.filter(i=>i.status==="modified").length,filesDeleted:t.files.filter(i=>i.status==="deleted").length,binaryFiles:t.files.filter(i=>i.binary).length,directories:new Set(t.files.map(i=>vR(i.path))).size,insertions:t.insertions,deletions:t.deletions,net:t.insertions-t.deletions,largestFile:o,concentration:o&&s>0?o.changed/s:0,selfChurn:t.selfChurn,truncated:t.truncated}};var _e={line:["//"],block:[["/*","*/"]]},Nt={line:["#"],block:[]},rc={line:["--"],block:[]},Xr={line:[],block:[["<!--","-->"]]},bR={line:[],block:[]},$=(e,t)=>({name:e,comment:t}),oa=$("TypeScript",_e),sa=$("JavaScript",_e),ih={ts:oa,tsx:oa,mts:oa,cts:oa,js:sa,jsx:sa,mjs:sa,cjs:sa,py:$("Python",{line:["#"],block:[['"""','"""']]}),rb:$("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:$("Go",_e),rs:$("Rust",_e),java:$("Java",_e),kt:$("Kotlin",_e),swift:$("Swift",_e),c:$("C",_e),h:$("C",_e),cc:$("C++",_e),cpp:$("C++",_e),hpp:$("C++",_e),cs:$("C#",_e),php:$("PHP",_e),scala:$("Scala",_e),dart:$("Dart",_e),lua:$("Lua",rc),hs:$("Haskell",rc),sql:$("SQL",rc),ex:$("Elixir",Nt),exs:$("Elixir",Nt),pl:$("Perl",Nt),r:$("R",Nt),jl:$("Julia",Nt),sh:$("Shell",Nt),bash:$("Shell",Nt),zsh:$("Shell",Nt),vue:$("Vue",Xr),svelte:$("Svelte",Xr),html:$("HTML",Xr),xml:$("XML",Xr),md:$("Markdown",Xr),mdx:$("Markdown",Xr),css:$("CSS",{line:[],block:[["/*","*/"]]}),scss:$("CSS",_e),less:$("CSS",_e),yml:$("YAML",Nt),yaml:$("YAML",Nt),toml:$("TOML",Nt),ini:$("INI",Nt),json:$("JSON",bR)},xR="Other",ah=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},yr=e=>ih[ah(e)]?.name??xR,ns=e=>ih[ah(e)]?.comment??null,IR=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],SR=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,Jr=e=>SR.test(e)||IR.some(t=>t.test(e)),ER=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,RR=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,CR=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,_t=e=>ER.test(e)||RR.test(e)||CR.test(e),dh=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),lh=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),ch=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),NR=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,AR=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,uh=e=>NR.test(e),mh=e=>AR.test(e);var ph=/\b(TODO|FIXME|HACK|XXX)\b/,TR=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,oc=(e,t)=>{let n=e.trim();return n===""?"blank":t&&(t.line.some(r=>n.startsWith(r))||t.block.some(([r])=>n.startsWith(r))||t.block.some(([r])=>r==="/*")&&(n.startsWith("*")||n.startsWith("*/")))?"comment":"code"},wR=(e,t)=>{let n=e.trim();for(let r of[...t.line,...t.block.flat(),"*"])if(n.startsWith(r)){n=n.slice(r.length).trim();break}return n},fh=({patch:e,repoShareByLanguage:t})=>{let n=new Map,r=0,o=0,s=0,i=0,l=0,c=0;for(let p of e.files){if(p.binary||_t(p.path))continue;let f=ns(p.path);if(!f||f.line.length===0&&f.block.length===0)continue;let g=yr(p.path),v=n.get(g)??{comment:0,code:0};for(let{text:x}of p.added){let I=oc(x,f);if(ph.test(x)&&i++,I==="blank"){s++;continue}if(I==="comment"){r++,v.comment++,f&&TR.test(wR(x,f))&&c++;continue}o++,v.code++}for(let{text:x}of p.removedLines)ph.test(x)&&l++;n.set(g,v)}let m=r+o;return{byLanguage:[...n.entries()].map(([p,f])=>({name:p,commentLines:f.comment,codeLines:f.code,share:f.comment+f.code===0?0:f.comment/(f.comment+f.code),repoShare:t?.get(p)??null})).sort((p,f)=>f.commentLines+f.codeLines-(p.commentLines+p.codeLines)),commentLines:r,codeLines:o,blankLines:s,share:m===0?0:r/m,todoLinesAdded:i,todoLinesRemoved:l,commentedOutCodeLines:c}};var MR=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,ia=6,sc=10,PR=e=>{let t=0;for(let n of e){if(n.trim()===""||n.startsWith(" "))continue;let r=n.length-n.trimStart().length;r>0&&(t===0||r<t)&&(t=r)}return Math.min(Math.max(t,2),8)},LR=(e,t)=>{let n=e.length-e.trimStart().length;if(n===0)return 0;let r=e.slice(0,n).split(" ").length-1;return r>0?r:Math.floor(n/t)},kR=e=>{if(e.length<ia*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let r=0;r+ia<=e.length;r++){let o=e.slice(r,r+ia);if(o.some(l=>l.text.length<3))continue;let s=o.map(l=>l.text).join(`
|
|
87
|
-
`),i=t.get(s);if(i===void 0){t.set(s,{...o[0],at:r});continue}if(i.file!==o[0]?.file)for(let l=0;l<ia;l++)n[i.at+l]=!0,n[r+l]=!0}return n.filter(Boolean).length},
|
|
88
|
-
`)){if(f.startsWith(
|
|
89
|
-
`)){let f=
|
|
90
|
-
`)){let A=oc(C,v);A==="comment"&&I.comment++,A==="code"&&I.code++}c.set(x,I)}let m=new Map;for(let[p,f]of c){let g=f.comment+f.code;g>0&&m.set(p,f.comment/g)}return{languages:r,commentShareByLanguage:m}};var Sh=({patch:e})=>{let t=0,n=0,r=[],o=[],s=0,i=0;for(let l of e.files)if(!(l.binary||_t(l.path))&&Jr(l.path)){t+=l.addedCount,n+=l.removed,l.status==="added"&&r.push(on(l)),l.status==="deleted"&&o.push(on(l));for(let{text:c}of l.added)uh(c)&&s++,mh(c)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:r,deletedTestFiles:o,skippedTestLinesAdded:s,focusedTestLinesAdded:i}};var GR=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,Eh=async({repoRoot:e,ref:t,commits:n})=>{let r=await xh({repoRoot:e,shas:n.map(l=>l.sha)});if(d(r))return a(r.message);let o=r.value,s=GR(n),i=s?await Ih({repoRoot:e,sha:s}):null;return u("Derived issue stats",{ref:t,shape:sh({commits:n,patch:o}),languages:hh({patch:o,languagesBefore:i?.languages??null}),tests:Sh({patch:o}),comments:fh({patch:o,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:gh({patch:o})})};var VR=32,rs=new Map;var zR=(e,t)=>{if(rs.set(e,t),rs.size>VR){let n=rs.keys().next();n.done||rs.delete(n.value)}return t},aa=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return a("idOrRef must not be empty");let n=t.length>7?_(t):t.toUpperCase(),r=xe(e.repoRoot??process.cwd());if(d(r))return a(r.message);let o=r.value,s=await Zi({repoRoot:o,ref:n});if(d(s))return a(s.message);let i=s.value.map(p=>({sha:p.sha,time:p.time,author:p.author,subject:p.subject})),l=[o,n,i.map(p=>p.sha).join(",")].join(" "),c=rs.get(l);if(c)return u("Derived issue stats",c);let m=await Eh({repoRoot:o,ref:n,commits:i});return d(m)?a(m.message):u("Derived issue stats",zR(l,m.value))};var KR="Filed here",Rh=(e,t)=>e.set(t,(e.get(t)??0)+1),Ch=(e,t,n)=>[...e.entries()].map(([r,o])=>({laneId:r,title:r===null?KR:n(r),count:o,share:t===0?0:o/t})).sort((r,o)=>o.count-r.count||r.title.localeCompare(o.title)),Nh=(e,t,n)=>{let r=new Map,o=new Map,s=0,i=0;for(let l of t)for(let[c,m]of l.entries()){if(m!==e)continue;s++,Rh(r,l[c-1]??null);let p=l[c+1];p!==void 0&&(i++,Rh(o,p))}return{arrived:s,departed:i,arrivesFrom:Ch(r,s,n),movesOnTo:Ch(o,i,n)}};var Ah=e=>{if(e.length===0)return null;let t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2:e[t]};var os=1440*60*1e3,dc=({laneIds:e,journeys:t,now:n,days:r})=>{let o=n-(r-1)*os,s=new Map(e.map(i=>[i,Array.from({length:r},()=>[])]));for(let i of t)for(let[l,c]of i.entries()){let m=s.get(c.laneId);if(!m)continue;let p=i[l+1]?.enteredAt,f=Math.max(0,Math.ceil((c.enteredAt-o)/os)),g=p===void 0?r-1:Math.min(r-1,Math.ceil((p-o)/os)-1);for(let v=f;v<=g;v++)m[v].push(o+v*os-c.enteredAt)}return Object.fromEntries([...s].map(([i,l])=>[i,l.map((c,m)=>({t:o+m*os,median:Ah(c.sort((p,f)=>p-f)),count:c.length}))]))},Th=({laneId:e,journeys:t,now:n,days:r})=>dc({laneIds:[e],journeys:t,now:n,days:r})[e];var qR=40,wh=30,YR=()=>({tickets:0,commits:0,insertions:0,deletions:0}),XR=async(e,t)=>{let n=YR();for(let r of t.slice(0,qR)){let o=await aa({repoRoot:e,idOrRef:_(r)});d(o)||o.value.shape.commits===0||(n.tickets++,n.commits+=o.value.shape.commits,n.insertions+=o.value.shape.insertions,n.deletions+=o.value.shape.deletions)}return n},Mh=()=>{let e=Y();if(d(e))return e;let{nodes:t}=e.value,n=Date.now(),r=Object.values(t).filter(P).map(s=>Ki(s.log??[],Ie(s.id))),o=Object.values(t).filter(mt).map(s=>s.id);return u("Derived board stay trends",dc({laneIds:o,journeys:r,now:n,days:wh}))},Ph=async e=>{let t=Y();if(d(t))return t;let{nodes:n}=t.value;if(!n[e.swimlaneId])return a("Swimlane not found");let o=Object.values(n).filter(P),s=o.map(c=>Ki(c.log??[],Ie(c.id))),i=Nh(e.swimlaneId,s.map(c=>c.map(m=>m.laneId)),c=>n[c]?.title??"Elsewhere"),l=o.filter(c=>c.parentNodeId===e.swimlaneId).map(c=>c.id);return u("Derived swimlane stats",{swimlaneId:e.swimlaneId,createdAt:Ie(e.swimlaneId),...i,stayTrend:Th({laneId:e.swimlaneId,journeys:s,now:Date.now(),days:wh}),code:await XR(e.repoRoot,l)})};var Lh=new Set(["sync","issues:create","swimlane:create","swimlane:edit:title","swimlane:delete","swimlane:move","issues:move","issue:close","issue:reopen","issue:edit:title","issue:edit:description","issue:tag:add","issue:tag:remove","contributor:remove","tag:remove","issue:assignee:add","issue:assignee:remove","issue:comment:add","issue:comment:delete"]);var kh=e=>{let t=bn({exclude:e});return d(t)?[]:t.value.map(n=>({projectId:n.projectId,name:Lr(n.root),root:n.root,lastOpenedAt:n.lastOpenedAt}))},Dh=e=>{let t=bn();if(d(t))return a(t.message);let n=t.value.find(r=>r.root===e);return n?u("Resolved recent project",n.root):a(`Not a recent project: ${e}`)};import{z as L}from"zod";var K=L.string().min(1),Bh=L.discriminatedUnion("at",[L.object({at:L.literal("start")}),L.object({at:L.literal("end")}),L.object({at:L.literal("before"),sibling:K}),L.object({at:L.literal("after"),sibling:K})]),ss=L.number().finite(),se=(e,t)=>L.object({type:L.literal(e),payload:t}),is=e=>L.object({type:L.literal(e)}),JR=L.discriminatedUnion("type",[is("state:get"),is("issues:list"),is("sync"),is("time-travel:live"),se("project:open",L.object({root:L.string().min(1)})),se("issues:create",L.object({title:L.string(),parentId:K,description:L.string().optional(),tagNames:L.array(L.string()).optional()})),se("swimlane:create",L.object({title:L.string(),boardId:K})),se("swimlane:edit:title",L.object({swimlaneId:K,title:L.string()})),se("swimlane:delete",L.object({swimlaneId:K})),se("swimlane:move",L.object({swimlaneId:K,boardId:K,position:Bh.optional()})),se("issues:move",L.object({issueId:K,parentId:K,position:Bh.optional()})),se("issue:edit:title",L.object({issueId:K,title:L.string()})),se("issue:edit:description",L.object({issueId:K,description:L.string()})),se("issue:tag:add",L.object({issueId:K,tagName:L.string()})),se("issue:tag:remove",L.object({issueId:K,tagId:K})),se("contributor:remove",L.object({contributorId:K})),se("tag:remove",L.object({tagId:K})),L.object({type:L.literal("contributors:get"),payload:L.object({boardId:K.optional()}).optional()}),se("issue:assignee:add",L.object({issueId:K,assigneeId:K.optional(),assigneeName:L.string().optional(),createUnlinked:L.boolean().optional()})),se("issue:assignee:remove",L.object({issueId:K,assigneeId:K})),se("issue:close",L.object({issueId:K})),se("issue:reopen",L.object({issueId:K})),se("issue:comment:add",L.object({issueId:K,body:L.string()})),se("issue:comment:delete",L.object({issueId:K,commentId:K})),se("issue:comment:edit",L.object({issueId:K,commentId:K,body:L.string()})),se("issue:get",L.object({issueId:K})),L.object({type:L.literal("timeline:get"),payload:L.object({start:ss.optional(),end:ss.optional(),boardId:K.optional(),requestId:L.number().finite().optional()}).optional()}),L.object({type:L.literal("commits:get"),payload:L.object({start:ss.optional(),end:ss.optional(),requestId:L.number().finite().optional()}).optional()}),se("time-travel:scrub",L.object({targetTime:ss})),se("time-travel:checkout-event",L.object({eventId:L.string().min(1)})),se("commit:inspect",L.object({sha:L.string()})),se("commit:diff:get",L.object({sha:L.string()})),se("issue:commits:get",L.object({issueId:K})),se("issue:stats:get",L.object({issueId:K})),se("swimlane:stats:get",L.object({swimlaneId:K})),is("board:stay-trends:get")]);var Fh=e=>{let t=JR.safeParse(e);return t.success?{ok:!0,message:t.data}:{ok:!1,error:`Invalid message: ${t.error.issues.map(r=>`${r.path.join(".")||"<root>"}: ${r.message}`).join(", ")}`}};var ZR=1024*1024,lc=()=>{tr({type:"state",payload:hr(fr())})},Z=(e,t)=>{e.send(JSON.stringify(t))},as=async(e,t)=>{let n=hr(await Rt({repoRoot:t}));return d(n)&&n.message===Va?Z(e,{type:"state:unavailable",payload:{message:n.message,repoRoot:t,recentProjects:kh(t)}}):Z(e,{type:"state",payload:n})},eC=async(e,t)=>{let n=()=>Z(e,{type:"state",payload:hr(fr())});if(tt().mode!=="live")return n();let r=await Rt({repoRoot:t});return tt().mode!=="live"?n():Z(e,{type:"state",payload:hr(r)})},We=async(e,t,n,r,o)=>{if(Z(e,{type:r,payload:o}),d(o))return Z(e,{type:"failed",payload:o.message});n(),eC(e,t)},Oh=(e,t,{onStateChanged:n,getPort:r})=>{new QR({server:e,path:"/ws",maxPayload:ZR,verifyClient:s=>!nc(s.origin,r())}).on("connection",s=>{gm(s),s.on("message",async i=>{let l=async c=>{let{type:m}=c,p=t.repoRoot;if(m==="project:open"){let f=Dh(c.payload.root);return Z(s,{type:"project:open:result",payload:f}),d(f)?void 0:(t.repoRoot=f.value,as(s,f.value))}if(m==="timeline:get"){let{requestId:f,...g}=c.payload??{};return Z(s,{type:"timeline",requestId:f,payload:await jg({repoRoot:p,...g})})}if(m==="issue:get"){let f=c.payload?.issueId,g=fr(),v=Ul(f);return Z(s,{type:"issue",payload:d(g)?g:u("Issue detail",{...nh(g.value,f),history:d(v)?[]:v.value})})}if(m==="commits:get"){let{requestId:f,...g}=c.payload??{};return Z(s,{type:"commits",requestId:f,payload:await Cl({repoRoot:p,...g})})}if(m==="commit:inspect")return Z(s,{type:"commit:inspect:result",payload:await Hg({repoRoot:p,sha:c.payload.sha})});if(m==="commit:diff:get"){let{sha:f}=c.payload;return Z(s,{type:"commit:diff:result",payload:{sha:f,result:await Wg({repoRoot:p,sha:f})}})}if(m==="issue:commits:get"){let{issueId:f}=c.payload;return Z(s,{type:"issue:commits:result",payload:{issueId:f,result:await Zi({repoRoot:p,ref:_(f)})}})}if(m==="issue:stats:get"){let{issueId:f}=c.payload;return Z(s,{type:"issue:stats:result",payload:{issueId:f,result:await aa({repoRoot:p,idOrRef:_(f)})}})}if(m==="swimlane:stats:get"){let{swimlaneId:f}=c.payload;return Z(s,{type:"swimlane:stats:result",payload:{swimlaneId:f,result:await Ph({repoRoot:p,swimlaneId:f})}})}if(m==="board:stay-trends:get")return Z(s,{type:"board:stay-trends:result",payload:Mh()});if(m==="time-travel:scrub"){let f=await Nl({repoRoot:p,targetTime:c.payload.targetTime});return Z(s,{type:"time-travel:result",payload:f}),d(f)?void 0:lc()}if(m==="time-travel:checkout-event"){let f=await Vg({repoRoot:p,eventId:c.payload.eventId});return Z(s,{type:"time-travel:result",payload:f}),d(f)?void 0:lc()}if(m==="time-travel:live"){let f=await zg({repoRoot:p});return Z(s,{type:"time-travel:result",payload:f}),d(f)?void 0:lc()}if(m==="state:get")return as(s,p);if(m==="sync"){let f=await Ko({repoRoot:p});return Z(s,{type:"sync:result",payload:f}),n(),as(s,p)}if(m==="issue:comment:add"){let f=await Zo({repoRoot:p,...c.payload});return We(s,p,n,"issue:comment:add:result",f)}if(m==="issue:comment:edit"){let f=await Zl({repoRoot:p,...c.payload});return We(s,p,n,"issue:comment:edit:result",f)}if(m==="issue:comment:delete"){let f=await es({repoRoot:p,...c.payload});return Z(s,{type:"issue:comment:delete:result",payload:f}),d(f)?Z(s,{type:"failed",payload:f.message}):(n(),as(s,p))}if(m==="issue:edit:description"){let f=await jl({repoRoot:p,...c.payload});return We(s,p,n,"issue:edit:description:result",f)}if(m==="issue:edit:title"){let f=await $l({repoRoot:p,...c.payload});return We(s,p,n,"issue:edit:title:result",f)}if(m==="issue:tag:add"){let f=await zl({repoRoot:p,...c.payload});return We(s,p,n,"issue:tag:add:result",f)}if(m==="issue:tag:remove"){let f=await ql({repoRoot:p,...c.payload});return We(s,p,n,"issue:tag:remove:result",f)}if(m==="contributor:remove"){let f=await Xl({repoRoot:p,...c.payload});return We(s,p,n,"contributor:remove:result",f)}if(m==="tag:remove"){let f=await Kl({repoRoot:p,...c.payload});return We(s,p,n,"tag:remove:result",f)}if(m==="contributors:get")return Z(s,{type:"contributors",payload:await Jl({repoRoot:p,...c.payload})});if(m==="issue:assignee:add"){let f=await Yl({repoRoot:p,...c.payload});return We(s,p,n,"issue:assignee:add:result",f)}if(m==="issue:assignee:remove"){let f=await Ql({repoRoot:p,...c.payload});return We(s,p,n,"issue:assignee:remove:result",f)}if(m==="issues:list")return Z(s,{type:"issues",payload:await Dl({repoRoot:p})});if(m==="issues:create"){let f=await Bl({...c.payload,repoRoot:p});return Z(s,{type:"issues:create:result",payload:f}),d(f)?tr({type:"failed",payload:f.message}):(n(),as(s,p))}if(m==="swimlane:create"){let f=await Hl({...c.payload,repoRoot:p});return We(s,p,n,"swimlane:create:result",f)}if(m==="swimlane:edit:title"){let f=await Wl({...c.payload,repoRoot:p});return We(s,p,n,"swimlane:edit:title:result",f)}if(m==="swimlane:delete"){let f=await Vl({...c.payload,repoRoot:p});return We(s,p,n,"swimlane:delete:result",f)}if(m==="swimlane:move"){if(!c.payload.position)return Z(s,{type:"error",message:"Missing move position"});let f=await Gl({...c.payload,repoRoot:p});return We(s,p,n,"swimlane:move:result",f)}if(m==="issues:move"){if(!c.payload.position)return Z(s,{type:"error",message:"Missing move position"});let f=await _l({...c.payload,repoRoot:p});return We(s,p,n,"issues:move:result",f)}if(m==="issue:close"){let f=await Fl({repoRoot:p,issueId:c.payload.issueId});return We(s,p,n,"issue:close:result",f)}if(m==="issue:reopen"){let f=await Ol({repoRoot:p,issueId:c.payload.issueId});return We(s,p,n,"issue:reopen:result",f)}return Z(s,{type:"error",message:"Unknown message type"})};try{let c=Fh(JSON.parse(i.toString()));if(!c.ok)return Z(s,{type:"error",message:c.error});let m=c.message;return Lh.has(m.type)?await Wn(async()=>tt().mode!=="live"?Z(s,{type:"failed",payload:"Read-only while viewing history"}):l(m)):await l(m)}catch(c){return Z(s,{type:"error",message:c instanceof Error?c.message:String(c)})}})})};var rC=vr.dirname(nC(import.meta.url)),oC=process.env.IS_LOCAL==="true"?vr.resolve(process.cwd(),"dist/gui"):vr.join(rC,"gui"),da,sC=async()=>(da===void 0&&(da=await import("node:sea").catch(()=>null)),da?.isSea()?da:null),Re=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},iC=e=>Re(e,409,{isError:!0,message:"Read-only while viewing history"}),la=(e,t)=>Wn(async()=>tt().mode!=="live"?iC(e):t()),_h=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.push(i)}),e.on("end",()=>{let i=Buffer.concat(o).toString("utf8");try{n(i?JSON.parse(i):{})}catch{r(new Error("Invalid JSON body"))}}),e.on("error",r)}),aC=2*1024*1024,dC={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},lC=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",Uh=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=vr.resolve(oC),o=vr.resolve(r,n),s=vr.relative(r,o);if(s.startsWith("..")||vr.isAbsolute(s))return Re(t,403,{isError:!0,message:"Forbidden"});let i=await sC();try{let l=i?Buffer.from(i.getAsset(`gui/${s}`)):await jh(o);return t.writeHead(200,{"content-type":lC(o)}),t.end(l)}catch{return Re(t,404,{isError:!0,message:`Not found: ${n}`})}},cC=async(e,t=ts)=>new Promise((n,r)=>{let o=s=>{let i=c=>{if(e.off("listening",l),c.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(c)},l=()=>{e.off("error",i);let c=e.address();if(!c||typeof c=="string"){r(new Error("Unable to resolve address"));return}n(c.port)};e.once("error",i),e.once("listening",l),e.listen(s,"127.0.0.1")};o(t)}),$h=async e=>{Ag(!1);let t=0,n={repoRoot:e.repoRoot},r=tC.createServer(async(i,l)=>{let c=new URL(i.url??"/","http://127.0.0.1"),m=oh({method:i.method,origin:i.headers.origin,contentType:i.headers["content-type"]},t);if(m)return Re(l,m.status,{isError:!0,message:m.message});if(i.method==="GET"&&c.pathname===ec)return Re(l,200,{app:tc,repoRoot:ra(n.repoRoot),version:rn,pid:process.pid});if(c.pathname==="/api/state")return Re(l,200,await Rt({repoRoot:n.repoRoot}));if(i.method==="POST"&&c.pathname==="/api/comments")try{let p=await _h(i);if(!p.issueId||!p.body?.trim())return Re(l,400,{isError:!0,message:"Missing issueId or body"});let f=p.issueId,g=p.body;return await la(l,async()=>{let v=await Zo({repoRoot:n.repoRoot,issueId:f,body:g});return d(v)?Re(l,400,{isError:!0,message:v.message}):Re(l,200,await Rt({repoRoot:n.repoRoot}))})}catch(p){return Re(l,400,{isError:!0,message:p instanceof Error?p.message:"Unable to add comment"})}if(i.method==="POST"&&c.pathname==="/api/attachments")try{let p=await _h(i,aC);if(!p.issueId||!p.dataBase64)return Re(l,400,{isError:!0,message:"Missing issueId or dataBase64"});let f=p.issueId,g=p.dataBase64,v=p.name??"";return await la(l,async()=>{let x=await Tl({repoRoot:n.repoRoot,issueId:f,name:v,dataBase64:g});return d(x)?Re(l,400,{isError:!0,message:x.message}):Re(l,200,{...await Rt({repoRoot:n.repoRoot}),attachment:x.value})})}catch(p){return Re(l,400,{isError:!0,message:p instanceof Error?p.message:"Unable to add attachment"})}if(i.method==="DELETE"&&c.pathname.startsWith("/api/attachments/")){let p=decodeURIComponent(c.pathname.replace("/api/attachments/",""));return p?la(l,async()=>{let f=await wl({repoRoot:n.repoRoot,attachmentId:p});return d(f)?Re(l,400,{isError:!0,message:f.message}):Re(l,200,await Rt({repoRoot:n.repoRoot}))}):Re(l,400,{isError:!0,message:"Missing attachment id"})}if(i.method==="GET"&&c.pathname.startsWith("/media/")){let p=decodeURIComponent(c.pathname.replace("/media/","")),f=await Ml({repoRoot:n.repoRoot,fileName:p});if(d(f))return Re(l,404,{isError:!0,message:f.message});try{let g=await jh(f.value.filePath);return l.writeHead(200,{"content-type":dC[f.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),l.end(g)}catch{return Re(l,404,{isError:!0,message:"Attachment blob not found"})}}if(i.method==="DELETE"&&c.pathname.startsWith("/api/comments/")){let p=decodeURIComponent(c.pathname.replace("/api/comments/",""));return p?la(l,async()=>{let f=await es({repoRoot:n.repoRoot,commentId:p});return d(f)?Re(l,400,{isError:!0,message:f.message}):Re(l,200,await Rt({repoRoot:n.repoRoot}))}):Re(l,400,{isError:!0,message:"Missing comment id"})}return c.pathname.startsWith("/board/")?Uh("/",l):Uh(c.pathname,l)});try{t=await cC(r)}catch(i){return a(i instanceof Error?`Unable to start GUI server: ${i.message}`:`Unable to start GUI server: ${String(i)}`)}let o=rh({project:n});Oh(r,n,{onStateChanged:()=>o.queueSync(),getPort:()=>t}),r.on("close",o.dispose);let s=r.address();return!s||typeof s=="string"?(r.close(),a("Unable to resolve GUI server address")):u("Started GUI server",{url:`http://epiq.localhost:${s.port}${e.boardId?`/board/${e.boardId}`:""}`,server:r})};var Wh=async e=>{let t=Ir({});if(d(t))return a(t.message);let n=yt();ce(n)&&ze(n.value);let r=await th(ts);if(r&&r.repoRoot===ra(e.repoRoot)){let i=`http://127.0.0.1:${ts}`;return console.log(`Epiq GUI already running for this project at ${Hh.cyan(i)}`),Ja(i),u("Reused running GUI",{url:i})}let o=await $h({...e,boardId:""});if(d(o))return o;let{url:s}=o.value;return console.log(`Epiq GUI running at ${Hh.cyan(s)}`),Ja(s),u("Started GUI",{url:s})};import{Box as Kn}from"ink";import Ce from"react";import{Box as cc,Text as ds}from"ink";import Ut,{useEffect as uC,useMemo as mC}from"react";import{ulid as pC}from"ulid";var Gh=({text:e,match:t,color:n,highlightColor:r=y.secondary,dimColor:o=!1})=>{if(!t)return Ut.createElement(ds,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),l=s.indexOf(i);return l===-1?Ut.createElement(ds,{color:n,dimColor:o},e):Ut.createElement(ds,{color:n,dimColor:o},e.slice(0,l),Ut.createElement(ds,{backgroundColor:r,bold:!0},e.slice(l,l+t.length)),e.slice(l+t.length))},Vh=pC(),fC=e=>`${e}`,gC=e=>{let{pendingNavTarget:t}=_n();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(Ne(E.NONE,{breadCrumb:n,contextNode:r,readOnly:h().readOnly,selectedNode:o}));return[...new Set(Object.values(E))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==E.PALETTE).map(i=>{let l=xi(i),c=Hi.find(m=>m.intent===l);return{command:i,description:c?.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,l)=>i.isAvailable!==l.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(l.command))},hC=e=>ge.text({id:Vh,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),yC=(e,t,n)=>ge.text({id:fC(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),uc=[],vC=e=>{zh();let t=R.createNode(hC(h().rootNodeId));d(t)||!Nn(t.value)||(uc=[t.value,...e.map((n,r)=>yC(n,r,Vh)).map(R.createNode).filter(ce).map(({value:n})=>n).filter(Nn)],O.navigate({contextNode:t.value,selectedIndex:0}))},zh=()=>{let e=uc.map(t=>t.id);uc=[];for(let t of e)R.deleteNode(t)};function Kh({width:e,height:t}){let r=Np().value.trim().toLowerCase(),o=mC(()=>gC(r),[r]);uC(()=>(vC(o),()=>{zh()}),[o]);let s=h().selectedIndex;return Ut.createElement(cc,{flexDirection:"column",width:e,height:t-2},Ut.createElement(It,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,l)=>{let c=l===s,m=i.isAvailable?y.accent:y.secondary2,p=i.isAvailable?"":"[unavailable] ";return Ut.createElement(cc,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Ut.createElement(ds,{color:m,dimColor:!i.isAvailable},c?"\u276F ":" ",Ut.createElement(Gh,{text:fu(i.command),match:r,color:m,dimColor:!i.isAvailable})),Ut.createElement(cc,{paddingLeft:2},Ut.createElement(Gh,{text:p+i.description,match:r.length>=2?r:"",color:c&&i.isAvailable?y.primary:y.secondary2,dimColor:!i.isAvailable})))})))}import{Box as kC}from"ink";import ma from"react";import cs from"chalk";import{Box as mc,Text as Jh}from"ink";import ls,{useEffect as Qh,useMemo as bC,useState as Zh}from"react";var Qr=["\u2803","\u2806","\u2830","\u2818"],qh=120,Yh=({isPalette:e,isPending:t,frame:n})=>{if(t){let r=(n%Qr.length+Qr.length)%Qr.length;return Qr[r]}return e?"?":":"},Xh=({infoMessage:e,isPending:t})=>t&&e.includes(le)?"":e;var ey=cs.hex(y.secondary),xC=cs.inverse,IC=cs.inverse.hex(y.secondary2),SC={hint:"",hints:[],overlap:0,remainder:""},ny=({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}},EC=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=de(t);return{bg:r=>cs.bgHex(n).black(r),bgCursor:r=>cs.bgHex(n).inverse.black(r)}}return Fd(t)},RC=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=ny({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}},ty=()=>({value:qe.value,cursorPosition:qe.cursorPosition,commandIsPending:qe.commandIsPending,autoCompletion:qe.commandMeta.autoCompletion??SC,infoMessage:qe.commandMeta.infoMessage,validationStatus:qe.commandMeta.validity,command:qe.commandMeta.command,inputString:qe.commandMeta.inputString,modifier:qe.commandMeta.modifier}),CC=(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,ry=({width:e,mode:t})=>{let[n,r]=Zh(ty());Qh(()=>{let w=()=>{let k=ty();r(D=>CC(D,k)?D:k)},M=jd(w);return w(),()=>{M()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:l,autoCompletion:c,command:m,modifier:p,validationStatus:f}=n,g=l&&f===Qt.Invalid,v=Xh({infoMessage:i,isPending:l}),[x,I]=Zh(0);Qh(()=>{if(!l){I(0);return}let w=setInterval(()=>{I(M=>(M+1)%Qr.length)},qh);return()=>{clearInterval(w)}},[l]);let C=Yh({isPalette:t===b.PALETTE,isPending:l,frame:x}),A=bC(()=>{let w=Math.max(0,Math.min(s,o.length)),M=ny({value:o,command:m}),k=RC({value:o,command:m,modifier:p}),D=m?Fd(m):null,ve=EC({command:m,modifier:p}),Ve=(lt,ct)=>{let Na=M&&ct>=M.start&&ct<M.end,Aa=k&&ct>=k.start&&ct<k.end;return Na&&D?D.fg(lt):Aa&&ve?ve.bg(lt):lt},At=(lt,ct)=>{let Na=M&&ct>=M.start&&ct<M.end,Aa=k&&ct>=k.start&&ct<k.end;return Na&&D?D.fgCursor(lt):Aa&&ve?ve.bgCursor(lt):xC(lt)},dt=o.slice(0,w),ke=o[w]??" ",Sn=w<o.length?o.slice(w+1):"",qn=Array.from(dt).map((lt,ct)=>Ve(lt,ct)).join(""),vs=At(ke,w),ro=Array.from(Sn).map((lt,ct)=>Ve(lt,w+1+ct)).join("");if(c.hint){let lt=c.hint[c.overlap]??ke;vs=IC(lt),ro=ey(c.remainder.slice(1)+Sn)}return qn+vs+ro},[o,s,c,m,p]);return ls.createElement(mc,{flexDirection:"column",justifyContent:"flex-start"},ls.createElement(mc,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},ls.createElement(mc,null,ls.createElement(Jh,null,ey(C),A),v&&ls.createElement(Jh,{wrap:"truncate",color:g?y.red:y.secondary2},` ${v} `))))};import{Box as NC,Text as us}from"ink";import Zr from"react";var oy=" ",AC=({keys:e,label:t})=>e.length+1+t.length,TC=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?oy.length:0)+AC(o);if(r+i>t-4)break;n.push(o),r+=i}return n},sy=({width:e,availableHints:t})=>{let n=TC(t,e);return Zr.createElement(NC,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1},n.length?Zr.createElement(us,{wrap:"truncate"},n.map(({keys:o,label:s},i)=>Zr.createElement(us,{key:`${o}-${s}`},i>0?oy:"",Zr.createElement(us,{color:y.accent},o),Zr.createElement(us,{color:y.secondary2}," ",s)))):Zr.createElement(us,{color:y.secondary2},"\xA0"))};import{Box as wC,Text as ca}from"ink";import ms,{useEffect as MC,useRef as eo,useState as PC}from"react";var LC=40,ua=.3,pc="\u2500",iy=1,ay=16,dy=({width:e})=>{let{replay:t}=X(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*iy,[l,c]=PC(0),m=eo(r);m.current=r;let p=eo(0),f=eo(0),g=eo(0),v=eo(0),x=eo(0);if(MC(()=>{if(!n){p.current=0,g.current=0,v.current=0,x.current=0,c(0);return}p.current=m.current,f.current=Date.now(),g.current=m.current;let M=setInterval(()=>{let k=Date.now(),D=m.current;if(D!==g.current){let ke=D-g.current,Sn=k-f.current;if(ke<0)v.current=0,x.current=0;else if(ke>0&&Sn>0){let qn=ke/Sn;v.current=v.current===0?qn:v.current*(1-ua)+qn*ua,x.current=x.current===0?ke:x.current*(1-ua)+ke*ua}p.current=D,f.current=k,g.current=D}let ve=k-f.current,Ve=Math.min(x.current,v.current*ve),At=Math.min(1,p.current+Ve),dt=Math.round(At*i);c(ke=>ke===dt?ke:dt)},LC);return()=>clearInterval(M)},[n,i]),!t)return null;let I=M=>{let k=s>1?M/(s-1):0,D=Math.round(k*(ay-1))/(ay-1);return pi(D)},C=Math.min(s,Math.floor(l/iy)),A=[];for(let M=0;M<C;M++){let k=I(M),D=A[A.length-1];D&&D.color===k?D.text+=pc:A.push({text:pc,color:k})}let w=pc.repeat(Math.max(0,s-C));return ms.createElement(wC,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1,columnGap:1},ms.createElement(ca,{color:y.secondary2},"\u25B6"),ms.createElement(ca,null,A.map((M,k)=>ms.createElement(ca,{key:k,color:M.color},M.text)),ms.createElement(ca,{color:y.secondary,dimColor:!0},w)))};var ps=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=X(),o=t===b.COMMAND_LINE||t===b.PALETTE;return ma.createElement(kC,null,o?ma.createElement(ry,{width:e,mode:t}):r==="replay"?ma.createElement(dy,{width:e}):ma.createElement(sy,{width:e,mode:t,availableHints:n}))};import{Box as Gn,Text as to}from"ink";import nt,{useEffect as DC,useMemo as BC}from"react";import{ulid as ly}from"ulid";var fa=ly(),FC=()=>[...new Set([...h().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(fl).filter(e=>e!==null).sort(({keys:e},{keys:t})=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(({keys:e,label:t})=>({keys:e,action:t})),OC=e=>ge.text({id:fa,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),_C=(e,t,n)=>ge.text({id:ly(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),pa=[],cy=()=>{let e=pa.filter(n=>n.id!==fa).map(n=>n.id),t=pa.filter(n=>n.id===fa).map(n=>n.id);pa=[];for(let n of[...e,...t])R.deleteNode(n)},UC=e=>{cy();let t=R.createNode(OC(h().rootNodeId));if(d(t)||!Nn(t.value))return logger.error("Could not attach help nodes");pa=[t.value,...e.map((n,r)=>_C(n,r,fa)).map(R.createNode).filter(ce).map(({value:n})=>n).filter(Nn)],O.navigate({contextNode:t.value,selectedIndex:0})},uy=({width:e,height:t})=>{let n=BC(()=>FC(),[]);DC(()=>(UC(n),()=>{cy()}),[n]);let r=h().selectedIndex;return nt.createElement(Gn,{flexDirection:"column",marginTop:3,borderColor:y.secondary,borderStyle:"round",width:e,height:t-2},nt.createElement(Gn,{paddingX:1,justifyContent:"center"},nt.createElement(to,{color:y.accent},"Help"),nt.createElement(to,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),nt.createElement(Gn,{paddingX:1,marginTop:1},nt.createElement(Gn,{width:20,justifyContent:"flex-end"},nt.createElement(to,{color:y.secondary},"Key(s)")),nt.createElement(Gn,{flexGrow:1,width:40,paddingLeft:2},nt.createElement(to,{color:y.secondary},"Action"))),nt.createElement(It,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let l=i===r;return nt.createElement(Gn,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},nt.createElement(Gn,{width:20,justifyContent:"flex-end"},nt.createElement(to,{color:y.accent},o)),nt.createElement(Gn,{flexGrow:1,width:40,paddingLeft:2},nt.createElement(to,{color:l?y.primary:y.secondary2},s)))})))};import jC from"chalk";import{Box as br,Text as Ue}from"ink";import pe from"react";var $C=8,HC=()=>{let e=bn({exclude:process.cwd()});return d(e)?[]:e.value.slice(0,$C)},my=({width:e,height:t})=>{let n=HC();return pe.createElement(br,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},pe.createElement(Ue,{color:y.accent,bold:!0},"Initialize project"),pe.createElement(Ue,null,`This folder is not an ${jC.hex(y.accent)("epiq")} project yet.`),pe.createElement(Ue,{color:y.primary},"To start tracking issues here, we need to initialize a new",pe.createElement(Ue,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json "),"file in this repository."),pe.createElement(br,{marginTop:1,flexDirection:"column"},pe.createElement(br,null,pe.createElement(Ue,{color:y.accent}," "),pe.createElement(Ue,{color:y.primary},"Type "),pe.createElement(Ue,{backgroundColor:y.secondary}," :init "))),pe.createElement(br,{marginTop:1},pe.createElement(Ue,{color:y.secondary2},"This will create, commit and push "),pe.createElement(Ue,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json ")),n.length>0&&pe.createElement(br,{marginTop:1,flexDirection:"column"},pe.createElement(Ue,{color:y.accent,bold:!0},"Or open a recent project"),n.map((r,o)=>pe.createElement(br,{key:r.projectId},pe.createElement(Ue,{color:y.accent},` ${o+1} `),pe.createElement(Ue,{color:y.primary},Lr(r.root)),pe.createElement(Ue,{color:y.secondary2},` ${r.root}`))),pe.createElement(br,{marginTop:1},pe.createElement(Ue,{color:y.accent}," "),pe.createElement(Ue,{color:y.primary},"Type "),pe.createElement(Ue,{backgroundColor:y.secondary}," :open 1 "),pe.createElement(Ue,{color:y.secondary2}," or "),pe.createElement(Ue,{backgroundColor:y.secondary}," :open <path> "))))};import{Box as ga,Text as sn}from"ink";import Ge from"react";var WC=({isDone:e,command:t,value:n})=>Ge.createElement(ga,null,Ge.createElement(sn,{color:y.accent,dimColor:e},e?" \u2714 ":" "),Ge.createElement(sn,{dimColor:e},"Type "),Ge.createElement(sn,{backgroundColor:y.secondary,dimColor:e}," "+t+" "),n!==void 0&&Ge.createElement(Ge.Fragment,null,Ge.createElement(sn,{dimColor:e}," "),Ge.createElement(sn,{color:y.secondary,dimColor:e},"<"+n+">"))),GC=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function fc({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:l}=Ln(),c=[{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:l,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=c.findIndex(f=>!f.done),p=m===-1?void 0:c[m];return Ge.createElement(ga,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},Ge.createElement(sn,{color:y.accent,bold:!0},"Welcome! \u{1F539}"),Ge.createElement(sn,null,"Let's get you started - it's a breeze."),Ge.createElement(sn,{color:y.secondary2},"Remember - you can always search available commands by typing:",Ge.createElement(sn,{color:y.accent}," ? ")),p&&Ge.createElement(sn,{color:y.secondary2},p.message),Ge.createElement(ga,{flexDirection:"column"},c.map((f,g)=>m===-1||g<=m?Ge.createElement(ga,{key:f.key,marginBottom:1},Ge.createElement(WC,{isDone:f.done,command:f.command,value:f.done?GC(f.value):void 0})):null)))}import xa from"chalk";import{Box as gs,Text as no}from"ink";import Le from"react";import{Box as ha,Text as py}from"ink";import Vn from"react";import VC from"chalk";var zC=e=>(R.getTag(e)?.name??"").length+3,KC=e=>{let t=R.getContributor(e);return(t?t.name:"").length+3},fy=({width:e})=>{let{viewMode:t}=ie(),n=X(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,l=i[o.id]?.[s],c=at(l?.id??o.id,"TICKET"),m=ce(c)?c.value:void 0,p=(m?.props.tags??[]).filter(D=>R.getTag(D)),f=m?.props.assignees??[],g=m?.parentNodeId?!bl(o.id,m.parentNodeId)&&t==="dense":!1,v=r.map((D,ve)=>{let Ve=ve===r.length-1,At=ae(D.id),dt=Ve?At?.[s]?.title:void 0;return`${ve?" / ":""}${D.title??""}${dt?` \u25B8 ${dt}`:""}`}).join(""),x=m?R.getCommentsByIssue(m.id):[],I=x.length?String(x.length).length+11:0,C=g?p.reduce((D,ve)=>D+zC(ve),0)+f.reduce((D,ve)=>D+KC(ve),0)+I:0,A=l?.id!=null&&!(t==="wide"&&P(l)),w=Math.max(0,e-C),M=v.substring(0,w)+(A?VC.hex(y.secondary2).dim(` ${_(l.id)}`):""),k=g?[...p.map(D=>Vn.createElement(ha,{key:`tag-${D}`,paddingLeft:1},Vn.createElement(_r,{id:D}))),...f.map(D=>Vn.createElement(ha,{key:`assignee-${D}`,paddingLeft:1},Vn.createElement(Bn,{id:D}))),x.length?Vn.createElement(ha,{key:"comments",paddingLeft:1},Vn.createElement(py,{color:y.accent},"[",x.length," comment",x.length===1?"":"s","]")):null]:[];return Vn.createElement(ha,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},Vn.createElement(py,{color:y.secondary2},M),k)};import{Box as qC,Text as gy}from"ink";import ya from"react";var YC=({filters:e})=>ya.createElement(qC,{columnGap:1},ya.createElement(gy,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>ya.createElement(gy,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),hy=ya.memo(YC);import{Box as XC,Text as va}from"ink";import fs from"react";function yy(){let{eventLog:e,unappliedEvents:t}=X(),n=e.at(-1)?.id,r=ks(n??""),o=ce(r)?Ci(r.value):"INVALID DATE";return fs.createElement(XC,{paddingLeft:1},fs.createElement(va,{backgroundColor:y.accent,color:y.secondary}," Readonly "),fs.createElement(va,{color:y.accent}," "+t.length+" edits ago at "+o+"."),fs.createElement(va,{color:y.accent}," Resume with "),fs.createElement(va,{backgroundColor:y.accent,color:y.secondary}," ",":peek now"," "))}import{Box as JC,Text as gc}from"ink";import ba from"react";function vy(){let{replay:e}=X();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return ba.createElement(JC,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},ba.createElement(gc,{backgroundColor:y.accent,color:y.secondary}," \u25B6 REPLAY "),ba.createElement(gc,{color:y.secondary2},Ci(new Date(r))),ba.createElement(gc,{color:y.accent},`${t}/${n} edits`))}import hc from"chalk";import{Box as QC,Text as by}from"ink";import yc,{useEffect as ZC,useState as eN}from"react";var tN=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],nN=150,xy=12,rN=.36,Iy=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)}},oN=({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)}`},sN=(e,t,n)=>{let r=Iy(e),o=Iy(t);return oN({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},iN=(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 sN(s,i,o)};function Sy({syncStatus:e,autoSync:t}){let[n,r]=eN(0);ZC(()=>{if(e.status!=="syncing"){r(0);return}let l=0,c=setInterval(()=>{l+=1;let m=(Math.sin(l*rN)+1)/2,p=Math.round(m*(xy-1));r(f=>f===p?f:p)},nN);return()=>clearInterval(c)},[e.status]);let o={synced:" ",failed:"---",offline:"off",syncing:"...",pending:"idle"},i={synced:y.secondary2,failed:y.yellow,offline:y.secondary2,pending:y.secondary2,syncing:iN(tN,n/(xy-1))??""}[e.status];return yc.createElement(QC,null,yc.createElement(by,null,hc.hex(y.secondary2).dim(t?"Sync (auto): ":"Sync: ")),yc.createElement(by,null,hc.hex(i)("\u25CF")+hc.hex(y.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import Ay from"chalk";import{Text as Ty}from"ink";import wy,{useEffect as cN,useState as uN}from"react";import vc from"chalk";var aN="https://registry.npmjs.org/epiq/latest",bc=null,Ey=0,dN=1e3*60*60*24,Ry=e=>e.replace(/^v/,""),lN=(e,t)=>{let n=Ry(e).split(".").map(Number),r=Ry(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},Cy=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(bc&&Date.now()-Ey<dN)return bc;try{let t=await fetch(aN);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?lN(r,e)>0:!1};return bc=o,Ey=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},Ny=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?vc.hex(y.accent).dim(s):vc.hex(y.secondary).dim(s)).join(vc.hex(y.secondary2).dim("."))};function My(){let[e,t]=uN({current:rn,latest:null,updateAvailable:!1});return cN(()=>{let n=!0;return Cy(rn).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?wy.createElement(Ty,{dimColor:!0,color:y.secondary2},rn+" "):wy.createElement(Ty,null,Ay.hex(y.secondary2).dim(rn),Ay.hex(y.accent).dim(" \u2197 "),Ny(rn,e.latest))}function hs({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=X(),{userName:i,preferredEditor:l,autoSync:c}=ie(),m=64,p=process.stdout.columns-m-8,f=t||n==="replay",g=s?fn(s.currentLabel,Math.max(0,p)):"";return Le.createElement(gs,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?Le.createElement(gs,{paddingLeft:1},Le.createElement(no,{color:y.secondary2},g)):f?Le.createElement(no,null," "):o===b.PALETTE?Le.createElement(gs,null,Le.createElement(no,{color:y.accent},"Command Palette"),Le.createElement(no,{dimColor:!0,color:y.secondary2}," ","- search, select and press enter")):Le.createElement(gs,{paddingLeft:1},e.length>0?Le.createElement(hy,{filters:e}):Le.createElement(fy,{width:p})),n==="live"?Le.createElement(gs,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},Le.createElement(Sy,{autoSync:!!c,syncStatus:r}),Le.createElement(no,null,xa.hex(y.secondary2).dim("Mode: ")+xa.hex(y.secondary2).dim(o.padEnd(8," "))," "),Le.createElement(Py,{icon:"@",value:i}),Le.createElement(Py,{icon:"\u276F",value:l}),Le.createElement(My,null)):"",n==="peek"?Le.createElement(yy,null):"",n==="replay"?Le.createElement(vy,null):"")}function Py({icon:e,value:t}){return Le.createElement(no,null,xa.dim(e)+xa.hex(y.accent)(` ${t??"-"} `))}import{Box as mN,Text as pN}from"ink";import ys from"react";import{Box as Ia,Text as xc}from"ink";import zn from"react";function Ic(){let e=X(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?q(t?.id):[];return zn.createElement(Ia,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:y.secondary,width:s},zn.createElement(Ia,{padding:1,paddingTop:0,paddingBottom:0},zn.createElement(xc,null,"Select a board:")),zn.createElement(Ia,{padding:1,flexDirection:"column"},i.map((l,c)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===c,f=q(l.id).flatMap(({id:g})=>ae(g)).length;return zn.createElement(Ia,{key:l.id??c},zn.createElement(xc,{color:m?y.accent:y.secondary2},zn.createElement(Ye,{isSelected:m})),zn.createElement(xc,{color:m?y.accent:y.secondary2},l.title," (",f," issues)",l.readonly?" \u{1F512}":""))})))}var fN=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:l}=X(),c=n.find(({context:g})=>g==="BOARD"),f=s-1-3;return ys.createElement(mN,{flexDirection:"row"},e.context==="WORKSPACE"?ys.createElement(Ic,null):c?ys.createElement(Ti,{height:f,width:i,swimlanes:(l[c.id]??[]).filter(g=>g!==void 0&&mt(g)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):ys.createElement(pN,null))},Ly=ys.memo(fN);import{useEffect as gN}from"react";var hN=e=>{gN(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=ie();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:l,mode:c}=h();c==="default"&&!l&&si(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},ky=({autoSync:e})=>(hN(e),null);function Sc({width:e,height:t}){let n=X(),{autoSync:r,viewMode:o}=su(),s=n.filters;if(n.mode===b.HELP)return Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(uy,{width:e,height:t}));if(n.mode===b.PALETTE)return Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(hs,{filters:s}),Ce.createElement(Kh,{width:e,height:t-2}),Ce.createElement(ps,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Ln(),l=!i,c=i&&!n.hasProjectDefinition;if(l)return Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(hs,{hideBreadCrumb:!0,filters:s}),Ce.createElement(fc,{height:t,width:e})),Ce.createElement(ps,{width:e,mode:n.mode,availableHints:[]}));if(c)return Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(hs,{hideBreadCrumb:!0,filters:s}),Ce.createElement(my,{height:t,width:e})),Ce.createElement(ps,{width:e,mode:n.mode,availableHints:[]}));let m=Qe(n.breadCrumb??[],"BOARD");if(ce(m)){let p=m.value.id,f=q(p).length,g=3,v=Math.floor(e/g),x=Math.floor(e/Math.max(f,1));e=Math.min(x,v)*Math.max(f,g)}return Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(ky,{autoSync:r}),Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(hs,{filters:s}),Ce.createElement(Ly,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),Ce.createElement(ps,{width:e,mode:n.mode,availableHints:n.availableHints}))}import yN from"readline";var Sa,Ea,an,vN=new Set([S.MoveCursorLeft,S.EraseInputWord,S.MoveCursorLeftOfWord,S.MoveCursorRight,S.MoveCursorRightOfWord,S.NavToPreviousContainer,S.NavToNextContainer,S.NavPreviousItem,S.NavNextItem,S.SetViewDense,S.SetViewWide,S.Confirm,S.Exit,S.Yank,S.InitCommandLine,S.InitCommandPalette,S.ExitCommandLine,S.CaptureInput,S.EraseInput,S.EraseInputWord,S.HideHelp,S.ViewHelp,S.SetViewDense,S.SetViewWide,S.GetLastCommandFromHistory,S.GetNextCommandFromHistory,S.AutoCompleteCommand]),bN=new Set([S.NavPreviousItem,S.NavNextItem,S.NavToPreviousContainer,S.NavToNextContainer,S.Confirm,S.Exit,S.InitCommandPalette,S.InitMove,S.MoveNextItem,S.MovePreviousItem,S.MoveToNextContainer,S.MoveToPreviousContainer,S.Delete,S.AddItem,S.EditTitle,S.EditDescription,S.ConfirmMove,S.Edit,S.ViewHelp,S.Yank]),Dy=async e=>{if(e.ctrl&&e.name==="c")return O.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=h(),s=Ap(e,n);if(!s||r&&!vN.has(s)||o==="replay"&&n===b.DEFAULT&&bN.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(l){logger.error(l)}},xN=()=>async function(t,n){n.name!=="escape"&&(an&&(clearTimeout(an),an=void 0),await Dy(n))},IN=()=>async function(t){if(t.length===1&&t[0]===27){an&&clearTimeout(an),an=setTimeout(()=>{Dy({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),an=void 0},25);return}an&&(clearTimeout(an),an=void 0)};function By(){Sa&&process.stdin.removeListener("keypress",Sa),Ea&&process.stdin.removeListener("data",Ea),Sa=xN(),Ea=IN(),yN.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Ea),process.stdin.on("keypress",Sa)}async function Fy(){try{let e=Ir({});if(d(e))return Bt(0,e.message);let t=yt();ce(t)&&ze(t.value);let n=xe(process.cwd()),r=ce(n)?await Di(n.value):Df();if(d(r))return r;let o=Ec();return d(o)?Bt(6,o.message):(By(),ce(n)&&Bi(n.value),u("Booted Epiq",void 0))}catch(e){return Bt(0,Tr(e))}}ff();var CN=`${jt.bold("Epiq CLI")}
|
|
79
|
+
`,ul.writeFileSync(t,n,"utf8"),z.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),u("Local epiq paths ignored",!0)};var kS=async e=>{let t=await j({cwd:e,args:["status","--porcelain"]});return d(t)?t:u("Checked git diff",t.value.stdout.split(`
|
|
80
|
+
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},Ee=(e,t)=>a(`[${e}] ${t}`),Tf=async({cwd:e,user:t})=>{let n=Es(),r=await Mt(e);if(d(r))return Ee(1,r.message);let o=r.value,s=await As(o);if(d(s))return Ee(2,s.message);if(s.value)return Ee(2,`Cannot initialize Epiq while a git operation is in progress: ${s.value}`);let i=await kS(o);if(d(i))return Ee(2.5,i.message);if(i.value.length>0)return Ee(3,`Cannot initialize Epiq with uncommitted changes (${i.value.join(", ")}). Commit or stash your changes first.`);if(po(o))return Ee(4,"Epiq project already initialized");let{userId:l,userName:c}=t;if(!l||!c)return Ee(5,"Missing Epiq user id");let m=await Nm(o);if(d(m))return Ee(6,m.message);let p=n.stateBranch,f=await Ts({repoRoot:o,branch:p});if(d(f))return Ee(6,f.message);if(f.value)return Ee(6,`State branch already exists: ${p}`);let g=await Id({repoRoot:o,stateBranchName:p});if(d(g))return Ee(6,g.message);let v=Ps();if(d(v))return Ee(7,v.message);let x=Af.join(Ms(),n.projectId),I=await rr({repoRoot:o,stateBranchRoot:x,stateBranchName:p});if(d(I))return Ee(8,I.message);let R=Af.join(x,".epiq");LS.mkdirSync(R,{recursive:!0});let A=vm({userId:l,userName:c});if(d(A))return Ee(9,A.message);for(let bs of A.value){let ro=qs({event:bs,rootDir:x});if(d(ro))return Ee(9,ro.message)}let w=Zn({userId:l,userName:c}),M=Hs(x,w);if(d(M))return Ee(9,M.message);let k=await ei({stateBranchRoot:x,eventFileName:w});if(d(k))return Ee(10,k.message);let D=await Sr({cwd:x,message:"[epiq:init]"});if(d(D))return Ee(10,D.message);let ve=await Nf(o);if(d(ve))return Ee(11,ve.message);let Ve=wc({repoRoot:o,fileContents:n});if(d(Ve))return Ee(12,Ve.message);let At=await be.stage({cwd:o,pathspec:[".epiq/project.json",".gitignore"]});if(d(At))return Ee(13,At.message);let dt=await be.commit({cwd:o,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(d(dt))return Ee(13,dt.message);let ke=[],Sn=await j({cwd:o,args:["push","-u","origin","HEAD"]});d(Sn)&&ke.push(`[init:14] ${Sn.message}`);let qn=await Ao({repoRoot:o,stateBranchRoot:x});return d(qn)&&ke.push(`[init:15] ${qn.message}`),u("Project initialized",{repoRoot:o,projectId:n.projectId,stateBranch:p,stateBranchRoot:x,defaultEvents:A.value,warnings:ke})};var Ho=(e,t)=>a(`[${e}] ${t}`),wf=async()=>{Q("");let e=Ln();if(!e.isSetupDone||!e.userName)return Ho(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let t=ie(),n=t.userName,r=t.userId;if(!r||!n)return Ho(5,"Missing Epiq user id");let o=await Tf({cwd:process.cwd(),user:{userId:r,userName:n}});if(d(o))return o;let s="Project initialized!";for(let g of o.value.warnings)s+=` Warn: ${g}`;let l=Lt(o.value.defaultEvents).filter(d);if(l.length>0)return Ho(16,l.map(g=>g.message).join(`
|
|
81
|
+
`));let c=et();if(d(c))return Ho(16,c.message);let{rootNodeId:m,nodes:p}=c.value,f=p[m];return f?(O.navigate({contextNode:f,selectedIndex:0}),N({hasProjectDefinition:!0,mode:b.DEFAULT}),u(s,null)):Ho(16,"Unable to resolve initialized root node")};import{ulid as BS}from"ulid";import{ulid as DS}from"ulid";var Mf=null,jn=()=>structuredClone(Mf),Wo=e=>{Mf=e},Pf=()=>{let{contextNode:e,selectedIndex:t}=h(),r=ae(e.id)[t];return r?u("Resolved selected child",r):a("Target node not found")},ml=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ae(t).filter(o=>o.id!==e);return Ys(r,n)},Lf=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ee();if(d(r))return a("Unable to resolve user ID");let o=ml({parentId:t,id:e,position:n});return d(o)?o:u("Created pending move state",{id:DS(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},kf=e=>{Wo(e);let t=An(e,!0);return d(t)?t:u("Node moved successfully",t.value)};function pl(e){let t=Pf();if(d(t))return t;let{contextNode:n,nodes:r}=h();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=ae(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let l=s[i+e];if(!l)return a("Missing sibling node");let c=Lf({id:t.value.id,parentId:l.id,position:{at:"end"}});return d(c)?c:kf(c.value)}function fl(e){let t=Pf();if(d(t))return t;let{contextNode:n,selectedIndex:r}=h(),s=ae(n.id)[r+e];if(!s)return a("Missing sibling node");let i=Lf({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:kf(i.value)}var Df=()=>{let e=jn();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=h().nodes[n];if(!r)return a("Move parent not found");let o=ae(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(O.navigate({contextNode:r,selectedIndex:o}),u("Synchronized navigation to moved node",null))},Pi=(e,t="Moved preview")=>{if(d(e))return e;let n=Df();return d(n)?n:(N({mode:b.MOVE}),u(t,null))},Bf=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=te().commandMeta,{contextNode:n,selectedIndex:r}=h(),o=ae(n.id)[r];if(!o)return N({mode:b.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=ae(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return a("Target not found among siblings");let l=s[i-1],c=s[i+1],m=c!=null?{at:"before",sibling:c.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},p=ml({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(Wo({id:BS(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),N({mode:b.MOVE}),u("Move initialized",null))}if(t==="next")return Pi(fl(1));if(t==="previous")return Pi(fl(-1));if(t==="to-next")return Pi(pl(1));if(t==="to-previous")return Pi(pl(-1));if(t==="confirm"){let s=jn();if(!s)return a("No pending move to confirm");let i=await Gt();if(d(i))return i;let l=B([s],i.value);if(d(l))return l;let c=Df();return d(c)?c:(Wo(null),N({mode:b.DEFAULT}),u("Moved item",null))}return t==="cancel"?(Wo(null),N({mode:b.DEFAULT}),u("Cancelling move",null)):a("Invalid move modifier")};import{ulid as ki}from"ulid";import{monotonicFactory as FS,ulid as OS}from"ulid";var _S=FS(),Li=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=_S();return u("Created issue events",[{id:OS(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var Ff=async(e,t)=>{let n=ee();if(d(n))return a("Unable to resolve user ID");let r=await Gt();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:l}=h(),c=m=>{let p=B([m],o);if(d(p))return p;let f=C.getNode(p.value[0].result.id);if(!f)return a("Created node not found");if(!f.parentNodeId)return p;let g=C.getNode(f.parentNodeId);return g?(O.navigate({contextNode:g,selectedIndex:C.getSiblings(f.parentNodeId).findIndex(({id:v})=>v===f.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=h(),p=C.getNode(m);if(!p)return a("Workspace not found");let f=Pn(p.id,n.value,o);return d(f)?f:c({id:ki(),action:"add.board",payload:{id:ki(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=Qe(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=Pn(m.value.id,n.value,o);return d(p)?p:c({id:ki(),action:"add.swimlane",payload:{id:ki(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=q(i.id)[l],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let w=Qe(s,"SWIMLANE");return d(w)?null:w.value})();if(!p)return a("Unable to add issue in this context");let f=Pn(p.id,n.value,o);if(d(f))return f;let g=Li({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(d(g))return g;let v=g.value,x=B([...v],o);if(d(x))return x;if(!x.value[0])return a("Issue creation failed");let A=v.find(w=>w.action==="add.issue")?.payload.id;return A?(O.navigate({contextNode:p,selectedIndex:C.getSiblings(p.id).findIndex(({id:w})=>w===A)}),u("Issue created",null)):a("Unable to determine ticket id")}return u("Success",null)};import HS from"node:os";import Uf from"node:path";var US=e=>e.some(t=>t.action==="init.workspace"),Of=async(e,t)=>{let n=Ht(e);return d(n)?a(n.message):lo({cwd:t,branch:n.value})},jS=e=>{let t=xe(process.cwd());if(d(t))return!1;let n=ue({repoRoot:t.value});return!d(n)&&n.value===e},Di=async e=>{let t=ue({repoRoot:e});if(d(t))return Bt(3,t.message);let n=t.value,r=await rr({repoRoot:e,stateBranchRoot:n,stateBranchName:Es().stateBranch});if(d(r))return Bt(3,r.message);let o=xt(n);if(d(o))return Bt(3,o.message);if(!US(o.value.events)){let m=await Of(e,n);if(d(m)&&logger.info(3,m.message),o=xt(n),d(o))return Bt(3,o.message)}let{events:s,unreadable:i}=o.value,l=Dt(s,i);if(d(l))return Bt(4,l.message);N({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let c=ai({root:e});return d(c)&&logger.info(c.message),u("Loaded project",void 0)},$S=async e=>{let t=ue({repoRoot:e});if(d(t))return a(t.message);let n=t.value,r=await Xn({repoRoot:n});if(d(r))return a(r.message);if(!r.value)return u("No remote to pull",void 0);let o=await ni({worktreeRoot:n,operation:"boot pull",fn:()=>Nd(n,()=>(Ar("Pulling"),Of(e,n)))});if(d(o))return Te(o.message);if(o.value===null)return u("Another process holds the state worktree",void 0);let s=o.value;if(d(s))return ao(s.message)?(Zs("Offline"),u("Offline",void 0)):Te(s.message);if(!s.value)return nr("Already synced"),u("Already synced",void 0);if(!jS(n))return u("Project changed during the pull",void 0);let i=Ad(n);return d(i)?i:(nr("Pulled"),u("Pulled and reloaded",void 0))},Bi=e=>{$S(e).then(t=>{d(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${Tr(t)}`)})},_f=()=>{let e=Dt([]);return d(e)?Bt(4,e.message):(N({hasProjectDefinition:!1,hasInitializingEvents:!1}),u("Booted without a project",void 0))};var WS=e=>e==="~"||e.startsWith("~/")?Uf.join(HS.homedir(),e.slice(1)):e,GS=(e,t)=>{let n=e.trim();if(!n)return a("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?u("Resolved recent project",o.root):a(`No recent project #${n}`)}let r=xe(Uf.resolve(WS(n)));return d(r)?a(`No epiq project at ${n}`):u("Resolved project path",r.value)},jf=async()=>{let e=bi();if(Q(""),h().hasProjectDefinition)return a("Already in a project; run epiq from another directory");let t=bn({exclude:process.cwd()}),n=d(t)?[]:t.value,r=GS(e,n);if(d(r))return a(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(l){return a(`Unable to enter ${o}: ${l instanceof Error?l.message:String(l)}`)}let i=await Di(o);return d(i)?(process.chdir(s),a(i.message)):(Bi(o),u(`Opened ${Lr(o)}`,null))};var Fi=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=h(),s=zs(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:l}=s.value,c=Ot();if(d(c))return c;let m=Lt(i),{fatal:p,skipped:f}=gn(m);if(p.length>0)return Ot(),N(o),a(p.map(v=>v.message).join(", "));hn(f);let g=h().nodes[e];return g?(O.navigate({contextNode:g,selectedIndex:r}),u("",{unappliedEvents:l})):(Ot(),N(o),a("Board did not exist at that date"))};var $f=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)};var VS=20,zS=16,KS=150,Oi=null,_i=null;var cr=()=>{Oi!==null&&(clearInterval(Oi),Oi=null),_i!==null&&(clearTimeout(_i),_i=null)},Hf=()=>{cr(),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Wf=({events:e,startTime:t,durationMs:n})=>{cr();let r=e.length,o=Rr(e.map(f=>Rn(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=$f(o),l=Math.max(1,Math.round(n*VS/1e3)),c=Math.max(Math.round(n/l),zS),m=0,p=0;N({mode:b.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Oi=setInterval(()=>{m++;let f=m/l,g=[],v,x;for(;p<r&&i[p]<=f;){let R=e[p],A=An(R);if(d(A)){if(xo(A)){p++;continue}Hf();return}g.push(...rd(R)),v=R,x=o[p],p++}if(p>=r||m>=l){for(;p<r;p++){let A=An(e[p]);if(d(A)&&!xo(A))break}let R=h().replay;N({unappliedEvents:[],replay:R&&{...R,progress:1,appliedCount:r}}),cr(),_i=setTimeout(Hf,KS);return}let I=h().replay;N({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:v?x??I?.currentTime??t:I?.currentTime??t,currentLabel:v?Ui(v):I?.currentLabel??"",flashNodeIds:v?[...new Set(g)]:I?.flashNodeIds??[]}})},c)};var Gf=async()=>{let e=Qe(h().breadCrumb,"BOARD");if(d(e))return e;let t=await Mt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=ue({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=te().commandMeta;if(cr(),r==="now"){let l=Mn(n.value);if(d(l))return a(l.message);let c=Ot();if(d(c))return c;let m=Lt(l.value),{fatal:p,skipped:f}=gn(m);return p.length>0?a(p.map(g=>g.message).join(", ")):(hn(f),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),u("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let l=Ks(n.value);if(d(l))return l;let c=r==="prev"?h().eventLog.at(-1):h().unappliedEvents.at(0),m=c===void 0?null:Rn(c),p=(c===void 0?null:l.value.get(c.id)??null)??(m===null?null:go(m));if(p===null)return a(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?p:p+1}else{let l=or(r||o.trim());if(!l)return a("Invalid peek date");s=l.getTime()}let i=Fi({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(N({mode:b.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),u("Peeking",!0))};var Vf=async()=>{let e=Qe(h().breadCrumb,"BOARD");if(d(e))return e;let t=await Mt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=ue({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=te().commandMeta,{dateInput:s,durationInput:i}=ui(r,o);if(cr(),h().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let l=or(s);if(!l)return a("Invalid replay date");let c=i?ci(i):15e3;if(c===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=h(),f=Fi({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?(Ot(),N(p),u("Nothing to replay from that point",!0)):(Wf({events:g,startTime:m,durationMs:c}),u("Replaying board history",!0))};import{spawn as YS}from"node:child_process";var XS=()=>{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"]}}},zf=async e=>new Promise(t=>{let{command:n,args:r}=XS();try{let o=YS(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 Go=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await zf(e);return d(n)?n:u(`Copied ${t} to clipboard`,null)},Kf=async e=>{let{breadCrumb:t,selectedNode:n}=h(),r=Po({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return a("Nothing selected to copy from");switch(e.modifier){case Me.REF:return Go(_(o.id),"ref");case Me.TITLE:return Go(o.title,"title");case Me.DESCRIPTION:return r?Go(r.props?.description??"","description"):a("No issue in scope");case Me.TAGS:{if(!r)return a("No issue in scope");let s=kn(r).map(({name:i})=>i);return Go(s.join(", "),"tags")}case Me.ASSIGNEES:{if(!r)return a("No issue in scope");let s=Dn(r).map(({name:i})=>i);return Go(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}};var qf=async()=>{Q(""),N({mode:b.DEFAULT});let e=et();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");N({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await oi();return d(t)?(N({syncStatus:{msg:t.message,status:"failed"}}),t):(N({mode:b.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{ulid as Yf}from"ulid";var Oe=async()=>{let e=await Gt();return d(e)?e:u("Resolved persist root",e.value)};var JS=e=>e.action==="add.issue.comment",Xf=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=q(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await Oe();if(d(o))return o;if(r.context==="COMMENT"){let s=r.id,i=P(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let l=h().nodes[i];if(!l||!P(l))return a("Unable to resolve comment issue");let c=l.log?.filter(JS).find(m=>m.payload.id===s);return c?c.payload.author!==e.value.userId?a("You can only delete your own comments"):B([{id:Yf(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return B([{id:Yf(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)};import{ulid as QS}from"ulid";var Jf=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=q(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!P(r))return a("Cannot close in this context");let o=h().nodes[he];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await Oe();if(d(s))return s;let i=s.value,l=Kt(o.id,r.id,{at:"end"},e.value,i);if(d(l))return l;let c=B([{id:QS(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...e.value}],i);return d(c)?c:u("Issue closed",null)};import{ulid as ZS}from"ulid";var ji=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};var Qf=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=q(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=h().nodes[he];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!P(s))return a("Target node is not issue");let l=ji(s);if(!l)return a("Unable to resolve previous parent from issue history");if(l===i.id)return a("Previous parent resolves to closed swimlane");let c=h().nodes[l];if(!c)return a("Previous parent no longer exists");let m=await Oe();if(d(m))return m;let p=m.value,f=Kt(c.id,s.id,{at:"end"},e.value,p);if(d(f))return f;let g=B([{id:ZS(),action:"reopen.issue",payload:{id:s.id,parent:c.id,rank:f.value},...e.value}],p);return d(g)?g:u("Issue reopened",null)};import{ulid as eE}from"ulid";var Zf=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=q(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=bi();if(!o)return a("Provide a title");let s=await Oe();return d(s)?s:B([{id:eE(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)};import{ulid as tE}from"ulid";var eg=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=te().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=C.findTagByName(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=h();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 l=i.value;if(!P(l))return a("Target node is not issue");if(!(l.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let m=await Oe();return d(m)?m:B([{id:tE(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...e.value}],m.value)};import{ulid as gl}from"ulid";var tg=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=te().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=h();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(!P(i))return a("Target node is not issue");let l=await Oe();if(d(l))return l;let c=C.findTagByName(r),m=c?.id??gl();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):B([...c?[]:[{id:gl(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:gl(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],l.value)};import{ulid as hl}from"ulid";var $i=()=>{let{eventLog:e=[],contributors:t}=h(),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))n.set(o.id,o.name);return[...n.entries()].map(([o,s])=>({id:o,name:s,isExternal:!r.has(o)}))};var ng=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=te().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:l}=h(),c=q(l.id)[i];if(!c)return a("Invalid assign target");let m=at(c.id,"TICKET");if(d(m))return a("Unable to assign issue in this context");let p=m.value;if(!P(p))return a("Target node is not issue");let f=await Oe();if(d(f))return f;let g=$i(),v=!o&&s.toLowerCase()==="me",x,I;if(v)x=e.value.userId,I=g.find(w=>w.id===x)?.name??e.value.userName;else{let w=g.filter(k=>k.name===s);if(w.length>1)return a(`"${s}" matches ${w.length} contributors (${w.map(k=>k.id).join(", ")}). Assign from the GUI to choose by id.`);let M=w[0];if(!M&&!o)return a(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);x=M?.id??hl(),I=M?.name??s}if((p.props.assignees??[]).includes(x))return a("Assignee already assigned");let A=!!h().contributors[x];return B([...A?[]:[{id:hl(),action:"create.contributor",payload:{id:x,name:I},...e.value}],{id:hl(),action:"add.issue.assignee",payload:{id:p.id,assignee:x},...e.value}],f.value)};import{ulid as nE}from"ulid";var rg=async()=>{let e=ee();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=te().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let{selectedNode:o}=h();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(!P(i))return a("Target node is not issue");let l=i.props.assignees??[],c=r.toLowerCase()==="me",m=c?l.filter(g=>g===e.value.userId):$i().filter(g=>g.name===r&&l.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(c?"Issue is not assigned to you":`Issue is not assigned to "${r}"`);let f=await Oe();return d(f)?f:B([{id:nE(),action:"remove.issue.assignee",payload:{id:i.id,assignee:p},...e.value}],f.value)};import{ulid as og}from"ulid";var sg=async e=>{let t=e.inputString.trim();if(!t)return a("Provide a comment");if(t.length>4e3)return a(`Cannot exceed ${4e3} characters`);let n=ee();if(d(n))return a("Unable to resolve user ID");let{breadCrumb:r,selectedNode:o}=h(),s=Qe([...r,o],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!i)return a("Invalid comment target");let l=i.context==="TICKET"?u("Resolved ticket",i):at(i.id,"TICKET");if(d(l))return a("Unable to comment on issue in this context");let c=l.value;if(!P(c))return a("Target node is not issue");let m=await Oe();return d(m)?m:B([{id:og(),action:"add.issue.comment",payload:{id:og(),issue:c.id,author:n.value.userId,md:t},...n.value}],m.value)};import{ulid as oE}from"ulid";import rE from"zod";var ig=()=>{let e=te().commandMeta.inputString,t=rE.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return a("Auto sync duration must be a number of at least 3000 ms");let n=ht({autoSyncDebounceMs:t.data});return d(n)?n:(ze({autoSyncIntervalMs:t.data}),N({mode:b.DEFAULT}),u(`Auto sync interval set to ${t.data}ms`,null))};var ag=()=>{let e=te().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=zm(e),n=ht({autoSync:t});return d(n)?n:(ze({autoSync:t}),N({mode:b.DEFAULT}),u(`Auto sync set to "${e}"`,null))};var dg=()=>{let e=te().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=ht({logLevel:e});return d(n)?n:(ze({logLevel:e}),N({mode:b.DEFAULT}),u(`Auto sync set to "${e}"`,null))};var lg=e=>{let t=e.inputString.trim();switch(e.modifier){case ye.USERNAME:{if(process.env[dn])return a(`Cannot change the configured user while ${dn} names this process`);let n=Cr();if(d(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,l=r||oE();if(!i||!l)return a("Unable to resolve user name or id");let c=ht({userName:i,userId:l,preferredEditor:o??""});return d(c)?c:(ze({userName:i,userId:l}),N({mode:b.DEFAULT}),u(`Username set to "${i}"`,null))}case ye.EDITOR:{if(!t)return a("No editor provided");let n=ht({preferredEditor:t});return d(n)?n:(ze({preferredEditor:t}),N({mode:b.DEFAULT}),u(`Editor configuration set to "${t}"`,null))}case ye.VIEW:{if(t!=="wide"&&t!=="dense")return a("Invalid view mode");let n=ht({viewMode:t});return d(n)?n:(ze({viewMode:t}),N({mode:b.DEFAULT}),u(`View set to "${t}"`,null))}case ye.AUTOSYNC:return ag();case ye.LOG_LEVEL:return dg();case ye.SYNC_DEBOUNCE_MS:return ig();case ye.ATTACHMENT_MAX_KB:return ip();default:return a("Unknown config command")}};var Hi=[{systemOnly:!0,intent:U.Move,description:"Internal move-state command",mode:b.COMMAND_LINE,action:Bf},{intent:U.Delete,description:"Delete the currently selected node",mode:b.COMMAND_LINE,action:Xf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:b.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=te().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>Ne(E.FILTER).map(l=>l.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return we(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:b.DEFAULT})),u("Filter updated",null)}},{intent:U.ViewHelp,description:"Open the help screen",mode:b.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=h();return Un({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),N({mode:b.HELP}),u("Viewing help",null)}},{intent:U.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:b.COMMAND_LINE,action:Jf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:b.COMMAND_LINE,action:Qf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Init,description:"Initialize Epiq in the current git repository",mode:b.COMMAND_LINE,action:wf},{intent:U.OpenProject,description:"Open a recently used epiq project, by number or path",mode:b.COMMAND_LINE,action:jf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.NewItem,description:"Create a new board, swimlane, or issue",mode:b.COMMAND_LINE,action:Ff,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Rename,description:"Rename the currently selected node",mode:b.COMMAND_LINE,action:Zf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.UntagTicket,description:"Remove a tag from the selected issue",mode:b.COMMAND_LINE,action:eg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.TagTicket,description:"Add or create a tag on the selected issue",mode:b.COMMAND_LINE,action:tg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.AssignUserToTicket,description:"Assign a user to the selected issue",mode:b.COMMAND_LINE,action:ng,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:b.COMMAND_LINE,action:rg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Comment,description:"Add a comment to the selected issue",mode:b.COMMAND_LINE,action:async(e,t)=>sg(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Sync,description:"Pull, commit, and push Epiq state",mode:b.COMMAND_LINE,action:qf},{intent:U.Peek,description:"View board state at another point in time",mode:b.COMMAND_LINE,action:Gf},{intent:U.Replay,description:"Replay board history forward from a point in time",mode:b.COMMAND_LINE,action:Vf},{intent:U.Export,description:"Export the current board layout to markdown",mode:b.COMMAND_LINE,action:async()=>{let e=await hf();return d(e)?e:(N({mode:b.DEFAULT}),u("Export successful",!0))}},{intent:U.Exit,description:"Exit the application",mode:b.COMMAND_LINE,action:async()=>(O.exit(),u("Exit successful",!0))},{intent:U.Edit,description:"Edit title or description",mode:b.COMMAND_LINE,action:async(e,t)=>Rf(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:b.COMMAND_LINE,action:async(e,t)=>Kf(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:b.COMMAND_LINE,action:(e,t)=>lg(t)}];var sE=new Set(["peek","replay","filter","view-help","yank"]),tn=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=te();if(!t)return a("No command to confirm");if(!e&&n===Qt.Invalid)return a("Invalid command");let s=xi(t);Np();let{readOnly:i}=h();if(i&&!sE.has(s))return Fo({status:En.Fail,message:"Command not available in readonly state",value:null});let l=Hi.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return Fo({status:En.Fail,message:"Command not found",value:null});let c;try{c=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return Fo({status:En.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(c)?Fo(c):(Ap({addToHistory:!e}),l.onSuccess?.(),ie().autoSync&&si(),c)};var Wi=[{intent:S.Exit,mode:b.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(N({mode:b.COMMAND_LINE}),Q("move cancel"),tn({isForceExecutedBySystem:!0}))},{intent:S.InitMove,mode:b.DEFAULT,description:"[m] move",action:()=>(N({mode:b.COMMAND_LINE}),Q("move start"),tn({isForceExecutedBySystem:!0}))},{intent:S.ConfirmMove,mode:b.MOVE,description:"[m] confirm move",action:()=>(N({mode:b.COMMAND_LINE}),Q("move confirm"),tn({isForceExecutedBySystem:!0}))}],Gi=[{intent:S.MovePreviousItem,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),Q("move previous"),tn({isForceExecutedBySystem:!0})):a("No pending move")},{intent:S.MoveNextItem,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),Q("move next"),tn({isForceExecutedBySystem:!0})):a("No pending move")}],cg=[{intent:S.MoveToNextContainer,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),Q("move to-next"),tn({isForceExecutedBySystem:!0})):a("No pending move")},{intent:S.MoveToPreviousContainer,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),Q("move to-previous"),tn({isForceExecutedBySystem:!0})):a("No pending move")}];var ug={[V.WORKSPACE]:[...Wi,...Gi],[V.BOARD]:[...Wi,...Gi],[V.SWIMLANE]:[...Wi,...Gi,...cg],[V.TICKET]:[],[V.FIELD]:[],[V.FIELD_LIST]:[],[V.TEXT]:[],[V.COMMENT]:[]};import aE from"node:fs";import dE from"node:path";import{spawn as iE}from"node:child_process";function mg(e){let t=process.platform,o=iE(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}var pg=e=>{let t=xe(process.cwd());if(d(t))return a("Unable to resolve project root");let n=ue({repoRoot:t.value});if(d(n))return a(n.message);let r=ir(e.hash,e.ext),o=dE.join(mo(n.value),r);return aE.existsSync(o)?(mg(o),u(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")};var fg=()=>{Q("");let{pendingNavTarget:e}=_n();N({mode:b.DEFAULT}),e&&O.navigate(e),Un({pendingNavTarget:void 0})},gg=[{intent:S.ExitCommandLine,mode:b.HELP,action:()=>(fg(),u("Exiting help",null))},{intent:S.Exit,mode:b.HELP,action:()=>(fg(),u("Closed help",null))},{intent:S.NavPreviousItem,mode:b.HELP,description:"[arrows/hjkl] navigate",action:()=>(O.navigateToPreviousItem(),u("Navigating to previous help item",null))},{intent:S.NavNextItem,mode:b.HELP,action:()=>(O.navigateToNextItem(),u("Navigating to next help item",null))},{intent:S.NavToPreviousContainer,mode:b.HELP,action:()=>(O.navigateToPreviousContainer(),u("Navigating to previous help container",null))},{intent:S.NavToNextContainer,mode:b.HELP,action:()=>(O.navigateToNextContainer(),u("Navigating to next help container",null))}];var lE=e=>{N({mode:b.COMMAND_LINE});let{pendingNavTarget:t}=_n();t&&O.navigate(t),Un({pendingNavTarget:void 0}),Q(`${e} `)},hg=()=>{Q("");let{pendingNavTarget:e}=_n();e&&O.navigate(e),Un({pendingNavTarget:void 0}),N({mode:b.DEFAULT})},yg=[{intent:S.InitCommandPalette,mode:b.DEFAULT,description:"[?] command palette",action:()=>{Q("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=h();return Un({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),N({mode:b.PALETTE}),u("Opening command palette",null)}},{intent:S.Confirm,mode:b.PALETTE,action:()=>{let{selectedNode:e}=h();if(!e||!Nn(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?(lE(t),u("Selected command",t)):u("No command selected",null)}},{intent:S.ExitCommandLine,mode:b.PALETTE,action:()=>(hg(),u("Exiting palette",null))},{intent:S.Exit,mode:b.PALETTE,action:()=>(hg(),u("Closed command palette",null))},{intent:S.NavPreviousItem,mode:b.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(O.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:S.NavNextItem,mode:b.PALETTE,action:()=>(O.navigateToNextItem(),u("Navigating to next item",null))},{intent:S.NavToPreviousContainer,mode:b.PALETTE,action:()=>(O.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:S.NavToNextContainer,mode:b.PALETTE,action:()=>(O.navigateToNextContainer(),u("Navigating to next container",null))}];var vg=[{intent:S.InitCommandLine,mode:b.DEFAULT,description:"[:] write command",action:()=>(N({mode:b.COMMAND_LINE}),Q(""),u("Entering command line mode",null))},...gg,...yg,{intent:S.AddItem,mode:b.DEFAULT,description:"[n] new...",action:()=>(N({mode:b.COMMAND_LINE}),Q(`${E.NEW} `),u("Adding new item",null))},{intent:S.Delete,mode:b.DEFAULT,description:"[d] delete",action:()=>(N({mode:b.COMMAND_LINE}),Q(`${E.DELETE} `),u("Deleting item",null))},{intent:S.Confirm,mode:b.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=h();if(!ae(e?.id??"")?.length){let r=e?C.getAttachment(e.id):void 0;if(r)return pg(r);if(e?.title===fe.DESCRIPTION)return N({mode:b.COMMAND_LINE}),Q(`${E.EDIT} description `),u("Propose command",!0);if(e?.title===fe.ASSIGNEES)return N({mode:b.COMMAND_LINE}),Q(`${E.ASSIGN} `),u("Propose command",!0);if(e?.title===fe.TAGS)return N({mode:b.COMMAND_LINE}),Q(`${E.TAG} `),u("Propose command",!0);if(t.title===fe.DESCRIPTION&&e?.context==="TEXT")return N({mode:b.COMMAND_LINE}),Q(`${E.EDIT} description `),u("Propose command",!0)}return O.enterChildNode(),u("Entering context",null)}},{intent:S.Yank,mode:b.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=h(),t=e?.title===fe.DESCRIPTION?Me.DESCRIPTION:e?.title===fe.TAGS?Me.TAGS:e?.title===fe.ASSIGNEES?Me.ASSIGNEES:Me.REF,r=Ne(E.YANK).includes(t)?t:Me.REF;return N({mode:b.COMMAND_LINE}),Q(`${E.YANK} ${r}`),u("Propose command",!0)}},{intent:S.EditTitle,mode:b.DEFAULT,description:"[r] rename title",action:()=>(N({mode:b.COMMAND_LINE}),Q(`${E.EDIT} title ${h().selectedNode?.title}`),u("Exiting context",null))},{intent:S.EditDescription,mode:b.DEFAULT,description:"[e] edit desc",action:()=>(N({mode:b.COMMAND_LINE}),Q(`${E.EDIT} description `),u("Exiting context",null))},{intent:S.Exit,mode:b.DEFAULT,description:"[q] exit context",action:()=>(O.enterParentNode(),u("Exiting context",null))},{intent:S.NavPreviousItem,mode:b.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(O.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:S.NavNextItem,mode:b.DEFAULT,action:()=>(O.navigateToNextItem(),u("Navigating to next item",null))},{intent:S.NavToPreviousContainer,mode:b.DEFAULT,action:()=>(O.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:S.NavToNextContainer,mode:b.DEFAULT,action:()=>(O.navigateToNextContainer(),u("Navigating to next container",null))}];var cE=500,uE=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),bg=e=>{let t=uE(e);t&&vi(n=>(n+t).slice(0,cE))};var mE=[b.COMMAND_LINE,b.PALETTE],pE=e=>[{intent:S.MoveCursorLeft,mode:e,action:()=>(Gd(-1),u("Moving cursor left",null))},{intent:S.MoveCursorRight,mode:e,action:()=>(Gd(1),u("Moving cursor right",null))},{intent:S.MoveCursorLeftOfWord,mode:e,action:()=>(Vd("left"),u("Moving cursor left of word",null))},{intent:S.MoveCursorRightOfWord,mode:e,action:()=>(Vd("right"),u("Moving cursor right of word",null))},{intent:S.AutoCompleteCommand,mode:e,action:()=>(vi((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=h().selectedNode?.title??""),r+o}),u("Auto-completing command",null))},{intent:S.CaptureInput,mode:e,action:(t,{sequence:n})=>(bg(n??""),u("Capturing input",null))},{intent:S.EraseInput,mode:e,action:()=>(Cp(),u("Erasing input",null))},{intent:S.EraseInputWord,mode:e,action:()=>(Rp(),u("Erasing input word",null))}],xg=[{intent:S.Confirm,mode:b.COMMAND_LINE,action:()=>(tn(),u("Executing command",null))},{intent:S.ViewHelp,mode:b.DEFAULT,action:()=>(N({mode:b.HELP}),u("Viewing help",null))},...mE.flatMap(pE),{intent:S.ExitCommandLine,mode:b.COMMAND_LINE,action:()=>(N({mode:b.DEFAULT}),u("Exiting command line",null))},{intent:S.GetLastCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Tp(),u("Getting last command from history",null))},{intent:S.GetNextCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(wp(),u("Getting next command from history",null))}];var yl=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},Ig=({keys:e})=>e.length===1?0:1,Sg=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(yl).filter(r=>r!==null).sort((r,o)=>Ig(r)-Ig(o))};function Eg(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=new Set,i=r;for(;i&&!s.has(i.id)&&(o.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let l=o[o.length-1];return!l||l.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),u("Breadcrumb built",o))}var Cg=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 nn,vl,bl=new Set,xl=()=>{for(let e of bl)e()},gE=e=>(bl.add(e),()=>bl.delete(e));function Il(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 l=o[t];if(!l)return a("Unable to derive state, contextNode not found");let c=Eg(t,o,r);if(d(c))return logger.error(c.message),c;let m=c.value,{context:p}=l,f=[...vg,...ug[p]??[],...xg],g=Sg(f,n),v=Cg(f),x=hE(o,s),I=x[t]?.[e.selectedIndex]??null;return u("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:g,availableActions:f,actionIndex:v,selectedNode:I,renderedChildrenIndex:x})}var h=()=>{if(!nn)throw new Error("State not initialized. Call initWorkspaceState() first.");return nn},et=()=>nn?u("Retrieved state",nn):a("State not initialized. Call initWorkspaceState() first.");function Io(e){vl=e;let t=xe(process.cwd()),n=!1;if(!d(t)){let s=$t(t.value);if(d(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:b.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=Il(r);return d(o)?o:(nn=o.value,xl(),u("State initialized",null))}var ur=!1,Vo=null;function we(e){let t=h(),n=e(t);if(ur)return Vo=n,nn={...t,...n},u("State updated",null);let r=Il(n);return d(r)?a(r.message??"Unable to update state"):(nn=r.value,xl(),u("State updated",null))}function Au(e){if(ur)return u("Joined batch",e());ur=!0,Vo=null;let t=()=>{let n=Vo;if(ur=!1,Vo=null,n===null)return null;let r=Il(n);return d(r)?a(r.message??"Unable to update state"):(nn=r.value,xl(),u("State updated",null))};try{let n=e(),r=t();return r&&d(r)?a(r.message):u("State updated",n)}finally{ur&&t()}}var cm=()=>ur,N=e=>we(t=>({...t,...e}));function mr(e,t,n){if(!ur)return we(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=h(),o=r[e]??{};o[t]=n;let s={...r,[e]:o};return Vo=s,nn={...r,...s},u("State updated",null)}var X=()=>fE(gE,h,h),hE=im,q=e=>h()?.renderedChildrenIndex[e]??[],Ot=()=>vl?Io(vl):a("Cannot reset state: no initial workspace found"),bt=()=>nn!==void 0;var at=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return u("Resolved ancestor node",r);let o=new Set([r.id]),s=r.parentNodeId?n[r.parentNodeId]:void 0;for(;s&&!o.has(s.id);){if(s.context===t)return u("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},Sl=(e,t)=>{let{nodes:n}=h(),r=new Set,o=n[e];for(;o?.parentNodeId&&!r.has(o.id);){if(o.parentNodeId===t)return!0;r.add(o.id),o=n[o.parentNodeId]}return!1},$n=(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"),C={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=we(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){we(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(!P(t))return a("Can only comment on issues");let n=mr("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(!P(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=mr("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=mr("comments",e,n);return d(r)?a("Unable to delete comment"):u("Deleted comment",n)},getComment(e){return h().comments?.[e]},getCommentsByIssue(e){return Object.values(h().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(h().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create attachment, missing issue");if(!P(t))return a("Can only attach to issues");let n=we(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=we(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return d(r)?a("Unable to delete attachment"):u("Deleted attachment",n)},getAttachment(e){return h().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(h().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(h().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=h(),r=n[e];if(!r)return a("Edit target node not found");let o=$n(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=$n(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),u("Renamed node",o)},getExistingTags(){let{tags:e}=h();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=h();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return ae(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=h(),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=$n(o,"move");if(i)return i;if(Sl(t,e))return a("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),u("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=h(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=$n(o,"delete");if(s)return s;let i=new Set,l=m=>{let p=t[m];if(!(!p||i.has(m))){i.add(m);for(let f of ae(p.id))l(f.id)}};l(e);let c={...structuredClone(t)};for(let m of i){if(!c[m])return a("Unable to locate node to delete");c[m]={...c[m],isDeleted:!0}}return n?(N({nodes:c}),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:Bs,tombstoned:!0},r=we(o=>({...o,contributors:{...o.contributors,[e]:n}}));return d(r)?a("Unable to remove contributor"):u("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.tombstoned)return a("Cannot rename a removed contributor");let r={...n,name:t},o=we(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to rename contributor"):u("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");let r={...n,name:t,tombstoned:!1},o=we(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to restore contributor"):u("Restored contributor",r)},createContributor(e){let t=we(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=$n(r,"edit");if(o)return o;if(!P(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=$n(r,"edit");if(o)return o;if(!P(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(l=>l!==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=$n(r,"edit");if(o)return o;if(!P(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.getTagRecord(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=$n(r,"edit");if(o)return o;if(!P(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(l=>l!==t)}};return this.updateNode(i),u("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return a("Tag not found");let n={...t,tombstoned:!0},r=we(o=>({...o,tags:{...o.tags,[e]:n}}));return d(r)?a("Unable to delete tag"):u("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return a("Tag not found");let r={...n,name:t,tombstoned:!1},o=we(s=>({...s,tags:{...s.tags,[e]:r}}));return d(o)?a("Unable to restore tag"):u("Restored tag",r)},createTag(e){let t=we(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):u("Tag created",e)},createNode(e){let t=mr("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=mr("nodes",e,n);return d(r)?a(r.message):u("Locked node",n)},updateNode(e){let t=mr("nodes",e.id,e);return d(t)?t:u("Updated node",e)},getContributor(e){return h().contributors[e]},getTag(e){let t=h().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return h().tags[e]},getTags(){return Object.values(h().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return h().nodes[e]},getSiblings(e){return ae(e)}};var yE=(e,t)=>e+" ".repeat(Math.max(0,t-Rg(e))),vE=(e,t)=>" ".repeat(Math.max(0,t-Rg(e)))+e,Vi=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","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed 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`),bE=(e,t)=>t?e<t?"up":e>t?"down":null:null,xE=(e,t)=>{let n=C.getNode(e.payload.parent),r=n?Hn.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=bE(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Ng=e=>`${Math.max(1,Math.round(e/1024))} KB`,Ag=e=>C.getAttachment(e)?.name??"",IE=e=>{switch(e.action){case"add.issue.tag":{let t=h().tags[e.payload.tag];return t?Hn.bgHex(de(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=h().tags[e.payload.tag];return t?Hn.bgHex(de(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=h().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?Hn.hex(de(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?Hn.hex(de(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Hn.dim(`(${Ng(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Ag(e.payload.id);return t?`"${t}"`:""}default:return""}},SE=e=>{let t=Wr(Ie(e));return Hn.gray(vE(t,8))},EE=12,CE=e=>yE(`${e}`,EE),RE=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=h().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=h().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=C.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Ng(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Ag(e.payload.id);return t?`"${t}"`:""}default:return""}},Ui=e=>[Vi(e.action),RE(e)].filter(Boolean).join(" "),Tg=(e,t)=>{let n=SE(e.id),r=CE(e.userName),o=Hn.dim("\u203A"),s=e.action==="move.node"?xE(e,t):[Vi(e.action),IE(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};var NE=e=>De(e,"comments"),AE=e=>De(e,"description"),TE=e=>De(e,"assignees"),wE=e=>De(e,"tags"),ME=e=>De(e,"history"),PE=e=>De(e,"attachments"),zi=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let l=C.getNode(e);if(!l){let p=C.createNode({...ge.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(!ut(l))return a(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==r||l.props.value!==o||l.readonly!==s||l.childRenderAxis!==i))return u("Virtual field unchanged",void 0);let m=C.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:s,childRenderAxis:i});return d(m)?m:u("Virtual field updated",void 0)},wg=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=C.getNode(e);if(!i){let m=C.createNode({...ge.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(!ho(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 c=C.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return d(c)?c:u("Virtual field list updated",void 0)},Tu=e=>{let t=vt(Vt/4n),n=vt(Vt/2n),r=vt(Vt*3n/4n),o=vt(Vt*7n/8n),s=vt(Vt*15n/16n),i=vt(Vt*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 l=zi({id:AE(e.id),name:fe.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(l))return l;let c=wg({id:TE(e.id),name:fe.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(c))return c;let m=wg({id:wE(e.id),name:fe.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(m))return m;let p=zi({id:NE(e.id),name:fe.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(p))return p;let f=zi({id:PE(e.id),name:fe.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(d(f))return f;let g=zi({id:ME(e.id),name:fe.HISTORY,parentNodeId:e.id,rank:i.value,value:LE(e),readonly:!0,childRenderAxis:"vertical"});return d(g)?g:u("Ticket virtual nodes materialized",void 0)},LE=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=>Tg(r,n.get(r.action)??[])).join(`
|
|
82
|
+
`)},Mg=!0,Pg=e=>{Mg=e},od=()=>Mg;import nR from"node:http";import vr from"node:path";import{fileURLToPath as rR}from"node:url";var kE=e=>{switch(e.action){case"add.issue":case"move.node":case"close.issue":case"reopen.issue":return e.payload.parent;default:return null}},Ki=(e,t)=>{let n=[];for(let r of e){let o=kE(r);if(o===null||o===n.at(-1)?.laneId)continue;let s=Rn(r);n.push({laneId:o,enteredAt:s===null?t:go(s)})}return n},qi=(e,t)=>Ki(e,t).at(-1)?.enteredAt??t;import{existsSync as Nl}from"node:fs";import{chmod as Al}from"node:fs/promises";import Yi from"node:path";import{chmodSync as DE,existsSync as BE,lstatSync as FE,mkdirSync as OE}from"node:fs";import _E from"node:os";import UE from"node:path";var El=(...e)=>{let t=UE.join(_E.tmpdir(),"epiq",...e);try{return BE(t)&&FE(t).isSymbolicLink()?a(`Refusing to write through a symlink at ${t}`):(OE(t,{recursive:!0,mode:448}),DE(t,448),u("Prepared private temp dir",t))}catch(n){return a(`Unable to prepare ${t}: ${n instanceof Error?n.message:String(n)}`)}};var jE=new Set(["create.tag","create.contributor","add.swimlane"]),$E=e=>{let t=new Map;for(let n of e){if(!jE.has(n.action))continue;let r=n.payload;r?.id&&r.name&&t.set(r.id,r.name)}return t},HE=e=>{let t=new Map,n=new Map;for(let r of e){let o=r.payload;!o?.id||!o.parent||(r.action==="move.node"&&t.set(r.id,n.get(o.id)),n.set(o.id,o.parent))}return t},kg=e=>{let t=e.payload;return e.action==="tombstone.tag"||e.action==="restore.tag"?t?.id:t?.tag},WE=e=>{let t=new Set,n=new Map;for(let r of e){let o=r.payload,s=o?.id;s&&(r.action==="add.issue"&&t.add(s),o.parent&&n.set(s,o.parent))}return{issueIds:t,parentById:n}},GE=(e,{issueIds:t,parentById:n})=>{let r=e.payload;if(r?.issue)return r.issue;let o=new Set,s=r?.id;for(;s!==void 0&&!o.has(s);){if(t.has(s))return s;o.add(s),s=n.get(s)}return null},Lg=90,VE=e=>{let t=e.trim().split(`
|
|
83
|
+
`)[0]?.trim()??"";return t.length>Lg?`${t.slice(0,Lg).trimEnd()}\u2026`:t},zE=(e,t,n)=>{let r=e.payload,o=kg(e),s=e.action?Vi(e.action):"";if(r?.md!==void 0){let l=VE(r.md);return l?`${s}: ${l}`:s}if(e.action==="move.node"&&r?.parent){let l=t.get(r.parent);return l?n.get(e.id)===r.parent?`Moved within ${l}`:`Moved to ${l}`:s}let i=o!==void 0?t.get(o)??"":r?.assignee!==void 0?t.get(r.assignee)??"":r?.name!==void 0?`"${r.name}"`:"";return[s,i].filter(Boolean).join(" ")},Cl=(e,t,n)=>{if(!e)return null;let r=t.get(e)??n??e;return{id:e,name:r,color:de(r)}},KE=(e,t)=>{let n=e.payload;return{actor:Cl(e.userId,t,e.userName),tag:Cl(kg(e),t),assignee:Cl(n?.assignee,t)}},Dg=e=>{let t=new Map,n=new Set,r=o=>{let s=new Set,i=o;for(;i&&!s.has(i);){if(n.has(i))return i;s.add(i),i=t.get(i)}return null};return e.map(o=>{let s=o.payload,i=s?.id;if(!i)return null;o.action==="add.board"&&n.add(i);let l=s.parent??s.issue;return l&&t.set(i,l),n.has(i)?i:r(i)})},Bg=(e,t)=>{let n=Dg(e);return e.filter((r,o)=>n[o]===t)},qE=e=>{let t=$E(e),n=HE(e),r=WE(e),o=Dg(e),s=Rr(e.map(l=>Rn(l)));return e.flatMap((l,c)=>{let m=s[c]??null;return m===null?[]:[{id:l.id,t:m,action:l.action,label:zE(l,t,n),issue:GE(l,r),board:o[c]??null,...KE(l,t)}]}).sort((l,c)=>l.t-c.t)},zo=null,Fg=e=>{let t=zt(e);if(zo&&zo.root===e&&zo.signature===t)return u("Timeline entries, cached",zo.entries);let n=Mn(e);if(d(n))return a(n.message);let r=qE(n.value);return zo={root:e,signature:t,entries:r},u("Timeline entries, built",r)};var Og=1e5,YE=2e4,Xi=null,_g=Promise.resolve(),Wn=e=>{let t=_g.then(e,e);return _g=t.then(()=>{},()=>{}),t},Ji=e=>{let t=xe(e??process.cwd());return d(t)?a(t.message):u("Resolved Epiq repo root",t.value)},Qi=e=>{let t=Ji(e);return d(t)?t:ue({repoRoot:t.value})},tt=()=>{if(!bt())return{mode:"live",asOfTime:null};let{timeMode:e}=h();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:Xi}},Ug=(e,t)=>{let n=0,r=e.length;for(;n<r;){let o=n+r>>1;e[o].t<t?n=o+1:r=o}return n},Gg=async(e={})=>{let t=Qi(e.repoRoot);if(d(t))return a(t.message);let n=Fg(t.value);if(d(n))return a(n.message);let r=n.value,o=Date.now(),s=e.end??o,i=e.start??r[0]?.t??s;if(s<=i)return u("Empty time window",{bucketMs:0,buckets:[],events:[],earliest:i,latest:s});let l=Ug(r,i),c=Ug(r,s),m=r.slice(l,c).filter(x=>!e.boardId||x.board===e.boardId).map(({board:x,...I})=>I),p=m.map(x=>x.t),f=Math.max(1,Math.ceil((s-i)/Og)),g=new Map;for(let x of p){let I=Math.min(Og-1,Math.floor((x-i)/f)),R=i+I*f;g.set(R,(g.get(R)??0)+1)}let v=[...g.entries()].sort(([x],[I])=>x-I).map(([x,I])=>({t:x,count:I}));return u("Computed event timeline",{bucketMs:f,buckets:v,events:m.length>YE?[]:m,earliest:i,latest:s})},Ko="",jg="",XE=5e3,zr=null;var Tl=async(e={})=>{let t=Ji(e.repoRoot);if(d(t))return a(t.message);let n=$t(t.value);if(d(n))return a(n.message);let r=e.start===void 0&&e.end===void 0;if(r&&zr&&zr.repoRoot===t.value&&zr.stateBranch===n.value.stateBranch&&Date.now()-zr.fetchedAt<XE)return u("Computed commit timeline",zr.result);let o=await j({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=${jg}%H${Ko}%at${Ko}%an${Ko}%s`]});if(d(o))return a(o.message);let s=o.value.stdout.split(jg).filter(i=>i.trim().length>0).map(i=>{let[l,...c]=i.split(`
|
|
84
|
+
`),[m,p,f,...g]=(l??"").split(Ko);if(!m||!p)return null;let v=c.join(" "),x=Number(/(\d+) insertion/.exec(v)?.[1]??0),I=Number(/(\d+) deletion/.exec(v)?.[1]??0);return{sha:m,time:Number(p)*1e3,author:f??"unknown",subject:g.join(Ko),linesChanged:x+I,insertions:x,deletions:I}}).filter(i=>i!==null).filter(i=>(e.start===void 0||i.time>=e.start)&&(e.end===void 0||i.time<=e.end));return r&&(zr={repoRoot:t.value,stateBranch:n.value.stateBranch,fetchedAt:Date.now(),result:s}),u("Computed commit timeline",s)},Zi=async e=>{let t=e.ref.trim();if(!t)return a("ref must not be empty");if(t.length!==7)return a(`"${t}" is ${t.length} characters; a ref is ${7}. Read it off the issue rather than slicing the id by hand.`);let n=await Tl({repoRoot:e.repoRoot});if(d(n))return a(n.message);let r=`${t.toUpperCase()} `,o=l=>l.subject.toUpperCase().startsWith(r),s=n.value,i=[];for(let[l,c]of s.entries()){if(!o(c))continue;let m=s[l+1];i.push({...c,precedingSha:m&&o(m)?m.sha:null})}return u("Matched commits by ref",i)},Vg=e=>/^[0-9a-f]{7,40}$/i.test(e),JE=async(e,t)=>{let n=await j({cwd:e,args:["show",t]});if(d(n))return a(n.message);let r=El("commit-diffs");if(d(r))return a(r.message);let o=Yi.join(r.value,`${t}.diff`);return Nl(o)||($e.writeToFile(o,n.value.stdout),await Al(o,292)),Cf(o)},QE=12,ZE=800,$g=async(e,t,n)=>{let r=await j({cwd:e,args:["show",`${t}:${n}`]});return d(r)?"":r.value.stdout},eC=async(e,t)=>{let n=await j({cwd:e,args:["diff","--name-only",`${t}~1`,t]});if(d(n))return a(n.message);let r=n.value.stdout.split(`
|
|
85
|
+
`).map(o=>o.trim()).filter(Boolean);return r.length===0?a("No changed files found for this commit"):u("Listed changed files",r)},tC=async(e,t,n)=>{let r=await eC(e,t);if(d(r))return a(r.message);let o=r.value;if(o.length>QE)return a(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=El("commit-diffs",t);if(d(s))return a(s.message);let i=s.value,l=await Promise.all(o.map(async(g,v)=>{let[x,I]=await Promise.all([$g(e,`${t}~1`,g),$g(e,t,g)]),R=Yi.basename(g),A=Yi.join(i,String(v),"before",R),w=Yi.join(i,String(v),"after",R);return Nl(A)||($e.writeToFile(A,x),await Al(A,292)),Nl(w)||($e.writeToFile(w,I),await Al(w,292)),{beforePath:A,afterPath:w}})),[c,...m]=l;if(!c)return a("No changed files found for this commit");let p=await ll(n,c.beforePath,c.afterPath,"new");if(d(p)||m.length===0)return p;await new Promise(g=>setTimeout(g,ZE));let f=await Promise.all(m.map(({beforePath:g,afterPath:v})=>ll(n,g,v,"reuse")));for(let g of f)d(g)&&logger.error(`Failed to open an additional diff tab for ${t}: ${g.message}`);return p},zg=async e=>{if(!Vg(e.sha))return a("Invalid commit sha");let t=Ji(e.repoRoot);if(d(t))return a(t.message);let n=t.value,r=Mi()[0];if(r&&dl(r)){let o=await tC(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 JE(n,e.sha)},nC=200,Hg=e=>/^0+$/.test(e),Rl=/^:\d{6} \d{6} ([0-9a-f]{40}) ([0-9a-f]{40}) [A-Z]\d*\t(.+)$/,Wg=/^(\d+|-)\t(\d+|-)\t(.+)$/,rC=async(e,t)=>{let n=await j({cwd:e,args:["diff","--raw","--numstat","--no-renames","--abbrev=40",`${t}~1`,t]});if(d(n))return a(n.message);let r=n.value.stdout.split(`
|
|
86
|
+
`).filter(l=>l!==""),o=r.filter(l=>!Rl.test(l)&&!Wg.test(l));if(o.length>0)return a(`Could not parse ${o.length} line(s) of "git diff --raw --numstat" output, e.g. "${o[0]}"`);let s=new Map;for(let l of r){let c=Wg.exec(l);c&&s.set(c[3]??"",{insertions:c[1]==="-"?0:Number(c[1]),deletions:c[2]==="-"?0:Number(c[2])})}let i=r.filter(l=>Rl.test(l)).map(l=>{let c=Rl.exec(l),m=c?.[1]??"",p=c?.[2]??"",f=c?.[3]??"";return{path:f,beforeBlob:Hg(m)?null:m,afterBlob:Hg(p)?null:p,...s.get(f)??{insertions:0,deletions:0}}});return i.length===0?a("No changed files found for this commit"):u("Listed changed files with blob hashes",i)},Kg=async e=>{if(!Vg(e.sha))return a("Invalid commit sha");let t=Ji(e.repoRoot);if(d(t))return a(t.message);let n=t.value,r=await rC(n,e.sha);if(d(r))return a(r.message);let o=r.value;if(o.length>nC)return a(`Commit touches ${o.length} files \u2014 too many to show as a diff`);let s=o.flatMap(m=>[m.beforeBlob,m.afterBlob].filter(p=>p!==null)),i=await Ns(s,n);if(d(i))return a(i.message);let l=i.value,c=o.map(m=>({path:m.path,before:m.beforeBlob?l.get(m.beforeBlob)??"":"",after:m.afterBlob?l.get(m.afterBlob)??"":"",insertions:m.insertions,deletions:m.deletions}));return u("Loaded commit diff",{sha:e.sha,files:c})},qg=e=>{let t=Mn(e);if(d(t))return a(t.message);let n=Ot();if(d(n))return a(n.message);Xi=null;let r=Lt(t.value),{fatal:o,skipped:s}=gn(r);return o.length>0?a(o.map(i=>i.message).join(", ")):(hn(s),N({readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),u("Restored live state",!0))},oC=(e,t)=>{Xi=null;let n=qg(e);return d(n)?a(`${t} (recovery to live also failed: ${n.message})`):a(t)},wl=e=>Wn(async()=>{let t=Qi(e.repoRoot);if(d(t))return a(t.message);let n=zs(t.value,e.targetTime);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=n.value,s=Ot();if(d(s))return s;let i=Lt(r),{fatal:l,skipped:c}=gn(i);return l.length>0?oC(t.value,l.map(m=>m.message).join(", ")):(hn(c),N({readOnly:!0,timeMode:"peek",unappliedEvents:o,replay:null}),Xi=e.targetTime,u("Checked out historical state",{asOfTime:e.targetTime}))}),Yg=async e=>{let t=Qi(e.repoRoot);if(d(t))return a(t.message);let n=Ks(t.value);if(d(n))return a(n.message);let r=n.value.get(e.eventId)??null;return r===null?a("Event not found in the log"):wl({repoRoot:e.repoRoot,targetTime:r+1})},Xg=(e={})=>Wn(async()=>{let t=Qi(e.repoRoot);if(d(t))return a(t.message);let n=qg(t.value);return d(n)?a(n.message):u("Returned to live state",!0)});import sC from"node:fs";var pr=e=>{let t=xe(e??process.cwd());return d(t)?a(t.message):u("Resolved Epiq repo root",t.value)},ea=null,ne=async(e,t)=>{let n=pr(e);if(d(n))return n;let r=ue({repoRoot:n.value});if(d(r))return a(r.message);let o=Ht(n.value);if(d(o))return a(o.message);if(!(ea!==null&&ea.repoRoot===n.value&&ea.stateBranchRoot===r.value&&sC.existsSync(Yn(r.value)))){let p=await Sd({repoRoot:n.value,stateBranchName:o.value});if(d(p))return a(p.message);let f=await rr({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(d(f))return a(f.message);ea={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let p=await j({cwd:r.value,args:["pull","--ff-only"]});d(p)&&z.info(3,p.message)}let i={repoRoot:n.value,stateBranchRoot:r.value},l=zt(r.value);if(Uu(r.value)===l&&bt()&&tt().mode==="live")return u("Booted Epiq state, unchanged",i);let c=xt(r.value);if(d(c))return a(c.message);let m=Dt(c.value.events,c.value.unreadable);return d(m)?a(m.message):(ju(r.value,l),u("Booted Epiq state",i))},re=()=>{let e=yt();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")},Y=()=>{let e=et();return d(e)?a(e.message):e};var Kr=e=>(e.props.tags??[]).map(t=>C.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:de(t.name)}));var qr=e=>(e.props.assignees??[]).map(t=>C.getContributor(t)).filter(t=>t!=null).map(({id:t,name:n})=>({id:t,name:n,color:de(n)}));import iC from"node:fs";import aC from"node:path";import{ulid as Ml}from"ulid";var dC=e=>{if(e.filePath)try{return u("Read attachment file",{data:iC.readFileSync(e.filePath),name:e.name??aC.basename(e.filePath)})}catch(t){return a(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?u("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):a("Provide either filePath or dataBase64")},ta=()=>{let e=yt();return d(e)?Jt:e.value.attachmentMaxKb??Jt},Pl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(o))return a("Attachment target must be an issue");if(o.readonly)return a("Cannot attach to readonly issue");let s=dC(e);if(d(s))return s;let i=op(t.value.stateBranchRoot,s.value.data,ta());if(d(i))return i;let l=Se(s.value.name).trim()||"image",c=Ml(),m={id:Ml(),...n.value,action:"add.issue.attachment",payload:{id:c,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:l,bytes:i.value.bytes}},p=B([m],t.value.stateBranchRoot);if(d(p))return a(p.message);let f=ir(i.value.hash,i.value.ext);return u("Added issue attachment",{id:c,issueId:e.issueId,fileName:f,bytes:i.value.bytes,markdown:Fd(l,f)})},Ll=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();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(!P(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 l={id:Ml(),...n.value,action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:o.payload.issue}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Deleted issue attachment",{id:e.attachmentId,issueId:o.payload.issue})},kl=async e=>{let t=await ne(e.repoRoot,{pull:!1});return d(t)?t:sp(t.value.stateBranchRoot,e.fileName,ta())};var lC=365*24*60*60*1e3,fr=()=>{let e=Y();if(d(e))return e;let t=tt(),n=t.mode!=="live",r=Object.values(e.value.nodes),o=r.filter(I=>Nr(I)&&!I.isDeleted),s=Date.now()-lC,i=new Map,l=new Map;for(let I of r)if(!I.isDeleted){if(mt(I)&&I.parentNodeId){let R=i.get(I.parentNodeId)??[];R.push(I),i.set(I.parentNodeId,R)}if(P(I)&&I.parentNodeId){if(I.parentNodeId===he&&Ie(I.id)<s)continue;let R=l.get(I.parentNodeId)??[];R.push(I),l.set(I.parentNodeId,R)}}let c=new Set;for(let I of l.values())for(let R of I)c.add(R.id);let m=yt();if(d(m))return m;let p={},f=C.getCommentsGroupedByIssue();for(let I of r.filter(P))I.isDeleted||!c.has(I.id)||(p[I.id]=(f.get(I.id)??[]).map(R=>{let A=C.getContributor(R.authorId);return{id:R.id,issueId:R.issue,body:R.md,author:{id:R.authorId,name:A?.name??"Unknown",color:de(A?.name??R.authorId??"Unknown")},createdAt:Ie(R.id)}}));let g=new Map;for(let I of e.value.eventLog)I.action==="add.issue.attachment"&&g.set(I.payload.id,I.payload.author);let v={},x=C.getAttachmentsGroupedByIssue();for(let I of r.filter(P))I.isDeleted||!c.has(I.id)||(v[I.id]=(x.get(I.id)??[]).map(R=>({id:R.id,issueId:R.issue,name:R.name,fileName:ir(R.hash,R.ext),bytes:R.bytes,createdAt:Ie(R.id),canDelete:g.get(R.id)===m.value.userId})));return u("Retrieved Epiq GUI state",{boards:o.sort((I,R)=>I.rank.localeCompare(R.rank)).map(I=>({id:I.id,ref:_(I.id),title:I.title,readonly:!!I.readonly||n,swimlanes:(i.get(I.id)??[]).sort((R,A)=>R.rank.localeCompare(A.rank)).map(R=>({id:R.id,title:R.title,readonly:!!R.readonly||n,issues:(l.get(R.id)??[]).sort((A,w)=>A.rank.localeCompare(w.rank)).map(A=>({id:A.id,ref:_(A.id),title:Se(A.title),description:A.props.description??"",createdAt:Ie(A.id),enteredLaneAt:qi(A.log??[],Ie(A.id)),readonly:!!A.readonly||n,tags:Kr(A),assignees:qr(A),parentNodeId:A.parentNodeId,isClosed:A.parentNodeId===he})),parentNodeId:R.parentNodeId}))})),tags:C.getTags().map(I=>({...I,color:de(I.name)})),contributors:Object.values(e.value.contributors).map(I=>({...I,color:de(I.name)})),user:{name:m.value.userName??"",id:m.value.userId??"",color:de(m.value.userName??"")},commentsByIssueId:p,attachmentsByIssueId:v,attachmentMaxKb:ta(),timeTravel:t})},Jg=null,cC=e=>{if(e===Jg)return;let t=ai({root:e});if(d(t)){z.info(t.message);return}Jg=e},Ct=async(e={})=>{if(tt().mode!=="live")return fr();let t=await ne(e.repoRoot,{pull:!1});return d(t)?t:(cC(t.value.repoRoot),fr())},qo=async(e={})=>{Ar();let t=pr(e.repoRoot);if(d(t))return a("Sync failed");let n=re();if(d(n))return n;let r=await ri({cwd:t.value,ownEventFileName:Zn(n.value)});return d(r)?(xd(r.message),r):(nr(),u("Synced",r.value))};import{ulid as Rt}from"ulid";var Yo=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?u("Resolved targets",t):a("Provide issueId or issueIds")},Yr=(e,t)=>{let n=t.done.length,r=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?u(r,t):a(`${r}: ${t.failed.map(o=>`${o.ref} ${o.reason}`).join("; ")}`)},Dl=(e,t)=>{let n={done:[],failed:[]};for(let r of e){let o=t(r);d(o)?n.failed.push({id:r,ref:_(r),reason:o.message}):n.done.push({id:r,ref:_(r)})}return n},Xo=e=>{let t=Y();if(d(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?a("Issue not found"):P(n)?n.readonly?a("Issue is readonly"):u("Found issue",n):a("Target must be an issue")};var eh=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();async function Ol(e){let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=Y();if(d(n))return n;let r=n.value.nodes,o=e.query?.trim().toLowerCase(),s=Object.values(r).filter(P).filter(l=>!l.isDeleted).filter(l=>e.includeClosed||l.parentNodeId!==he).filter(l=>e.boardId?(l.parentNodeId?r[l.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(l=>!e.swimlaneId||l.parentNodeId===e.swimlaneId).filter(l=>!e.tag||Kr(l).some(c=>eh(c.name,e.tag))).filter(l=>!e.assignee||qr(l).some(c=>eh(c.name,e.assignee))).filter(l=>!o||l.title.toLowerCase().includes(o)||(l.props.description??"").toLowerCase().includes(o)),i=l=>Se((l.parentNodeId?r[l.parentNodeId]?.title:void 0)??"");return e.brief?u("Listed issues",s.map(l=>({id:l.id,ref:_(l.id),title:Se(l.title),swimlane:i(l),tags:Kr(l).map(c=>c.name),assignees:qr(l).map(c=>c.name)}))):u("Listed issues",s.map(l=>({id:l.id,ref:_(l.id),title:Se(l.title),description:l.props.description??"",createdAt:Ie(l.id),enteredLaneAt:qi(l.log??[],Ie(l.id)),parentNodeId:l.parentNodeId,isClosed:l.parentNodeId===he,readonly:!!l.readonly,tags:Kr(l),assignees:qr(l)})))}var _l=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=Se(e.title);if(!o)return a("Issue title cannot be empty");let s=e.description??"",i=st("Issue title",o,300)??st("Issue description",s,2e4);if(i)return a(i);if((e.tagNames?.length??0)>20)return a(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return a(`Cannot set more than ${20} assignees at once`);let l=Pn(e.parentId,n.value,t.value.stateBranchRoot);if(d(l))return l;let c=Li({name:o,parent:e.parentId,user:n.value,rank:l.value});if(d(c))return c;let m=[...c.value],p=m.find(x=>x.action==="add.issue")?.payload.id;if(!p)return a("Unable to determine created issue id");s&&m.push({id:Rt(),...n.value,action:"edit.description",payload:{id:p,md:s}});let f=[];for(let x of e.tagNames??[]){let I=Se(x).trim();if(!I||f.some(M=>M.name===I))continue;let R=st("Tag name",I,60);if(R)return a(R);let A=C.findTagByName(I),w=A?.id??Rt();A||m.push({id:Rt(),...n.value,action:"create.tag",payload:{id:w,name:I}}),m.push({id:Rt(),...n.value,action:"add.issue.tag",payload:{id:p,tag:w}}),f.push({id:w,name:I})}let g=[];for(let x of e.assigneeNames??[]){let I=Se(x).trim();if(!I||g.some(M=>M.name===I))continue;let R=st("Assignee name",I,80);if(R)return a(R);let A=Object.values(r.value.contributors).find(M=>M.name===I),w=A?.id??Rt();A||m.push({id:Rt(),...n.value,action:"create.contributor",payload:{id:w,name:I}}),m.push({id:Rt(),...n.value,action:"add.issue.assignee",payload:{id:p,assignee:w}}),g.push({id:w,name:I})}let v=B(m,t.value.stateBranchRoot);return d(v)?a(v.message):u("Created issue",{id:p,ref:_(p),title:o,parentId:e.parentId,description:s,tags:f,assignees:g})},uC=(e,t,n)=>{let r=Xo(e);if(d(r))return r;let o=Kt(he,e,{at:"end"},t,n);if(d(o))return o;let s={id:Rt(),...t,action:"close.issue",payload:{id:e,parent:he,rank:o.value}},i=B([s],n);return d(i)?a(i.message):u("Closed issue",{id:e,ref:_(e)})};async function Ul(e){let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Yo(e);if(d(r))return r;let o=s=>uC(s,n.value,t.value.stateBranchRoot);return e.issueIds?Yr("Closed",Dl(r.value,o)):o(r.value[0])}var jl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(o))return a("Target node is not issue");if(o.parentNodeId!==he)return a("Issue is not closed");let s=ji(o);if(!s)return a("Unable to resolve previous parent from issue history");if(s===he)return a("Previous parent resolves to closed swimlane");let i=r.value.nodes[s];if(!i)return a("Previous parent no longer exists");let l=Kt(i.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(l))return l;let c={id:Rt(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:i.id,rank:l.value}},m=B([c],t.value.stateBranchRoot);return d(m)?a(m.message):u("Reopened issue",{id:o.id,ref:_(o.id),parentId:i.id})},mC=(e,t,n,r)=>{let o=Xo(e);if(d(o))return o;let s=Kt(t.parentId,e,t.position??{at:"end"},n,r);if(d(s))return s;let i={id:Rt(),...n,action:"move.node",payload:{id:e,parent:t.parentId,rank:s.value}},l=B([i],r);return d(l)?a(l.message):u("Moved issue",{id:e,ref:_(e),parentId:t.parentId})};async function $l(e){let t=pr(e.repoRoot);if(d(t))return t;let n=re();if(d(n))return n;let r=ue({repoRoot:t.value});if(d(r))return r;let o=xt(r.value);if(d(o))return o;let s=Dt(o.value.events,o.value.unreadable);if(d(s))return s;let i=Yo(e);if(d(i))return i;let l=c=>mC(c,e,n.value,r.value);return e.issueIds?Yr("Moved",Dl(i.value,l)):l(i.value[0])}var Hl=e=>{let t=Y();if(d(t))return t;let n=t.value.nodes[e];return n?u("Read issue history",(n.log??[]).map(r=>({id:r.id,t:Ie(r.id),action:r.action,label:Ui(r),...r.action==="move.node"?{parentId:r.payload.parent}:{},actor:{id:r.userId,name:r.userName,color:de(r.userName)}}))):a("Issue not found")},Wl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=st("Issue description",e.description,2e4);if(s)return a(s);let i=o.props.description??"";if(i===e.description)return u("No changes made",{id:e.issueId,ref:_(e.issueId),description:i});let l={id:Rt(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited issue description",{id:e.issueId,ref:_(e.issueId),description:e.description})},Gl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=Se(e.title);if(!s.trim())return a("Issue title cannot be empty");let i=st("Issue title",s,300);if(i)return a(i);if(o.title===s)return u("No changes made",{id:e.issueId,ref:_(e.issueId),title:s});let l={id:Rt(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited issue title",{id:e.issueId,ref:_(e.issueId),title:s})};import{ulid as Qo}from"ulid";var Vl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.boardId];if(!o)return a("Board not found");if(!Nr(o))return a("Target parent must be a board");if(o.readonly)return a("Cannot add a swimlane to a readonly board");if(tt().mode!=="live")return a("Cannot add a swimlane while time travelling");let s=Se(e.title);if(!s.trim())return a("Swimlane title cannot be empty");let i=st("Swimlane title",s,300);if(i)return a(i);let l=Pn(e.boardId,n.value,t.value.stateBranchRoot);if(d(l))return l;let c=Qo(),m={id:Qo(),...n.value,action:"add.swimlane",payload:{id:c,name:s,parent:e.boardId,rank:l.value}},p=B([m],t.value.stateBranchRoot);return d(p)?a(p.message):u("Created swimlane",{id:c,ref:_(c),title:s,boardId:e.boardId})},zl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.swimlaneId];if(!o)return a("Swimlane not found");if(!mt(o))return a("Edit target must be a swimlane");if(o.readonly)return a("Cannot edit readonly swimlane");let s=Se(e.title);if(!s.trim())return a("Swimlane title cannot be empty");let i=st("Swimlane title",s,300);if(i)return a(i);if(o.title===s)return u("No changes made",{id:e.swimlaneId,ref:_(e.swimlaneId),title:s});let l={id:Qo(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:s}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Edited swimlane title",{id:e.swimlaneId,ref:_(e.swimlaneId),title:s})},Kl=async e=>{let t=pr(e.repoRoot);if(d(t))return t;let n=re();if(d(n))return n;let r=ue({repoRoot:t.value});if(d(r))return r;let o=xt(r.value);if(d(o))return o;let s=Dt(o.value.events,o.value.unreadable);if(d(s))return s;let i=Kt(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(d(i))return i;let l={id:Qo(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:i.value}},c=B([l],r.value);return d(c)?a(c.message):u("Moved swimlane",{id:e.swimlaneId,ref:_(e.swimlaneId),boardId:e.boardId})},ql=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.swimlaneId];if(!o)return a("Swimlane not found");if(!mt(o))return a("Delete target must be a swimlane");let s={id:Qo(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Deleted swimlane",{id:e.swimlaneId,ref:_(e.swimlaneId)})};import{ulid as Zo}from"ulid";async function Yl(e){let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Yo(e);if(d(r))return r;let o=Se(e.tagName).trim();if(!o)return a("Tag name cannot be empty");let s=st("Tag name",o,60);if(s)return a(s);let i={done:[],failed:[]};for(let v of r.value){let x=Xo(v);d(x)?i.failed.push({id:v,ref:_(v),reason:x.message}):i.done.push({id:v,ref:_(v)})}if(!e.issueIds&&i.failed[0])return a(i.failed[0].reason);if(i.done.length===0)return a(Yr("Tagged",i).message);let l=C.findTagByName(o),c=l?.id??Zo(),m=[...l?[]:[{id:Zo(),...n.value,action:"create.tag",payload:{id:c,name:o}}],...i.done.map(({id:v})=>({id:Zo(),...n.value,action:"add.issue.tag",payload:{id:v,tag:c}}))],p=B(m,t.value.stateBranchRoot);if(d(p))return a(p.message);let f={id:c,name:o};if(!e.issueIds)return u("Added issue tag",{...i.done[0],tag:f});let g=Yr("Tagged",i);return d(g)?g:u(g.message,{...g.value,tag:f})}var Xl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.tags[e.tagId];if(!o)return a("Tag not found");if(o.tombstoned)return a("Tag is already deleted");let s=[{id:Zo(),...n.value,action:"tombstone.tag",payload:{id:e.tagId}}],i=B(s,t.value.stateBranchRoot);return d(i)?a(i.message):u("Deleted tag",{id:o.id,name:o.name})};var Jl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(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:Zo(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Removed issue tag",{id:e.issueId,ref:_(e.issueId),tagId:e.tagId})};import{ulid as gr}from"ulid";var pC=()=>{let e=et(),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},nh=(e,t)=>{let n=new Map(e);for(let r of Object.values(t))n.set(r.id,r.name);return n};var rh=async(e,t)=>{let n=hd(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}},Ql=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(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 rh(t.value.stateBranchRoot,s);if(!R&&!A)return a("Unknown assignee id");let w=R??A,M=[...R?[]:[{id:gr(),...n.value,action:"create.contributor",payload:{id:w.id,name:w.name}}],{id:gr(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:w.id}}],k=B(M,t.value.stateBranchRoot);return d(k)?a(k.message):u("Added issue assignee",{id:e.issueId,ref:_(e.issueId),assignee:{id:w.id,name:w.name}})}let i=Se(e.assigneeName??"").trim();if(!i)return a("Provide assigneeId, self or assigneeName");let l=st("Assignee name",i,80);if(l)return a(l);let m=[...nh(pC(),r.value.contributors).entries()].filter(([,R])=>R===i);if(m.length>1)return a(`"${i}" matches ${m.length} contributors (${m.map(([R])=>R).join(", ")}). Assign by assigneeId to choose.`);let p=m[0];if(!p&&!e.createUnlinked)return a(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[f=gr(),g=i]=p??[],x=[...!!r.value.contributors[f]?[]:[{id:gr(),...n.value,action:"create.contributor",payload:{id:f,name:g}}],{id:gr(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:f}}],I=B(x,t.value.stateBranchRoot);return d(I)?a(I.message):u("Added issue assignee",{id:e.issueId,ref:_(e.issueId),assignee:{id:f,name:g}})},Zl=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;if(!r.value.contributors[e.contributorId])return a("Contributor not found");if(await rh(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:gr(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],l=B(i,t.value.stateBranchRoot);return d(l)?a(l.message):u("Tombstoned contributor",{id:e.contributorId,name:Bs})};var ec=async(e={})=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=Mn(t.value.stateBranchRoot);if(d(o))return a(o.message);let s=e.boardId?Bg(o.value,e.boardId):o.value,i=new Map,l=new Set,c=new Set,m=hd(t.value.stateBranchRoot);if(d(m))return a(m.message);for(let v of m.value)v.userId&&c.add(v.userId);for(let v of s)v.userId&&(i.set(v.userId,v.userName??""),l.add(v.userId));let p=r.value.contributors,g=[...nh(i,p).entries()].map(([v,x])=>({id:v,name:x,color:de(x),isSelf:v===n.value.userId,isExternal:!l.has(v),isRemoved:p[v]?.tombstoned===!0,hasAuthoredAnywhere:c.has(v)}));return u("Listed board contributors",g)},tc=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(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:gr(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):u("Removed issue assignee",{id:e.issueId,ref:_(e.issueId),assigneeId:e.assigneeId})};import{ulid as na}from"ulid";var es=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!P(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=na(),l={id:na(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Added issue comment",{id:i,issueId:e.issueId,body:s})},ts=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();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(!P(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 l={id:na(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},c=B([l],t.value.stateBranchRoot);return d(c)?a(c.message):u("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},nc=async e=>{let t=await ne(e.repoRoot,{pull:!1});if(d(t))return t;let n=re();if(d(n))return n;let r=Y();if(d(r))return r;let o=r.value.eventLog.find(p=>p.action==="add.issue.comment"&&p.payload.id===e.commentId);if(!o)return a("Unable to resolve comment");if(o.payload.author!==n.value.userId)return a("You can only edit your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!P(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot edit comment on readonly issue");if(r.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return a("Comment was deleted");let l=e.body.trim();if(!l)return a("Comment cannot be empty");if(l.length>4e3)return a(`Comment cannot exceed ${4e3} characters (got ${l.length})`);let c={id:na(),...n.value,action:"edit.issue.comment",payload:{id:e.commentId,issue:o.payload.issue,md:l}},m=B([c],t.value.stateBranchRoot);return d(m)?a(m.message):u("Edited issue comment",{id:e.commentId,issueId:o.payload.issue,body:l})};var rn="1.8.4";import fC from"node:fs";import oh from"node:path";var ns=Number(process.env.EPIQ_GUI_PORT)||3710,rc="/api/instance",oc="epiq",ra=e=>{try{return fC.realpathSync(oh.resolve(e))}catch{return oh.resolve(e)}},gC=e=>{let t=e;return typeof t=="object"&&t!==null&&t.app===oc&&typeof t.repoRoot=="string"&&typeof t.version=="string"&&typeof t.pid=="number"},sh=async(e,t=500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}${rc}`,{signal:n.signal});if(!o.ok)return null;let s=await o.json();return gC(s)?s:null}catch{return null}finally{clearTimeout(r)}};var hC=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))}),hr=e=>d(e)?e:u(e.message,hC(e.value)),ih=(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 yC=15e3,ah=e=>{let t,n=!1,r=!1,o=0,s=i();function i(){let g=xe(e.project.repoRoot);if(d(g))return null;let v=ue({repoRoot:g.value});return d(v)?null:zt(v.value)}let l=()=>{let g=Cr();return d(g)?(z.error(g.message),null):g.value},c=()=>{let g=l();if(!g)return!1;let{autoSync:v,preferredEditor:x}=g,I=yt(),R=d(I)?null:I.value.userName;return!!(v&&R&&x)},m=()=>{let g=l()?.autoSyncDebounceMs??yC;return Math.max(0,g-(Date.now()-o))},p=async()=>{if(!(n||r)){r=!0,o=Date.now();try{await Wn(async()=>{if(tt().mode!=="live")return;await qo({repoRoot:e.project.repoRoot});let g=i();if(g===null||g===s)return;s=g;let v=hr(await Ct({repoRoot:e.project.repoRoot}));d(v)||tr({type:"state",payload:v})})}finally{r=!1,f()}}};function f(){n||!c()||r||t||(t=setTimeout(()=>{t=void 0,p()},m()))}return f(),{queueSync:f,dispose:()=>{n=!0,t&&clearTimeout(t)}}};var vC=new Set(["127.0.0.1","[::1]","localhost","epiq.localhost"]),sc=(e,t)=>{if(!e)return!1;if(e==="null")return!0;let n;try{n=new URL(e)}catch{return!0}return n.protocol!=="http:"||n.port!==String(t)?!0:!vC.has(n.hostname)},dh=(e,t)=>e.method==="GET"||e.method==="HEAD"?null:sc(e.origin,t)?{status:403,message:"Cross-origin request"}:e.method==="POST"&&!(e.contentType??"").toLowerCase().startsWith("application/json")?{status:415,message:"Expected content-type: application/json"}:null;import{WebSocketServer as ZC}from"ws";var on=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""});var bC=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},lh=({commits:e,patch:t})=>{let n=e.map(i=>i.time),o=t.files.map(i=>({...on(i),changed:i.addedCount+i.removed})).reduce((i,l)=>i===null||l.changed>i.changed?l:i,null),s=t.insertions+t.deletions;return{commits:e.length,authors:[...new Set(e.map(i=>i.author))].sort(),firstCommitAt:n.length?Math.min(...n):null,lastCommitAt:n.length?Math.max(...n):null,files:t.files.length,filesAdded:t.files.filter(i=>i.status==="added").length,filesModified:t.files.filter(i=>i.status==="modified").length,filesDeleted:t.files.filter(i=>i.status==="deleted").length,binaryFiles:t.files.filter(i=>i.binary).length,directories:new Set(t.files.map(i=>bC(i.path))).size,insertions:t.insertions,deletions:t.deletions,net:t.insertions-t.deletions,largestFile:o,concentration:o&&s>0?o.changed/s:0,selfChurn:t.selfChurn,truncated:t.truncated}};var _e={line:["//"],block:[["/*","*/"]]},Nt={line:["#"],block:[]},ic={line:["--"],block:[]},Xr={line:[],block:[["<!--","-->"]]},xC={line:[],block:[]},$=(e,t)=>({name:e,comment:t}),oa=$("TypeScript",_e),sa=$("JavaScript",_e),ch={ts:oa,tsx:oa,mts:oa,cts:oa,js:sa,jsx:sa,mjs:sa,cjs:sa,py:$("Python",{line:["#"],block:[['"""','"""']]}),rb:$("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:$("Go",_e),rs:$("Rust",_e),java:$("Java",_e),kt:$("Kotlin",_e),swift:$("Swift",_e),c:$("C",_e),h:$("C",_e),cc:$("C++",_e),cpp:$("C++",_e),hpp:$("C++",_e),cs:$("C#",_e),php:$("PHP",_e),scala:$("Scala",_e),dart:$("Dart",_e),lua:$("Lua",ic),hs:$("Haskell",ic),sql:$("SQL",ic),ex:$("Elixir",Nt),exs:$("Elixir",Nt),pl:$("Perl",Nt),r:$("R",Nt),jl:$("Julia",Nt),sh:$("Shell",Nt),bash:$("Shell",Nt),zsh:$("Shell",Nt),vue:$("Vue",Xr),svelte:$("Svelte",Xr),html:$("HTML",Xr),xml:$("XML",Xr),md:$("Markdown",Xr),mdx:$("Markdown",Xr),css:$("CSS",{line:[],block:[["/*","*/"]]}),scss:$("CSS",_e),less:$("CSS",_e),yml:$("YAML",Nt),yaml:$("YAML",Nt),toml:$("TOML",Nt),ini:$("INI",Nt),json:$("JSON",xC)},IC="Other",uh=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},yr=e=>ch[uh(e)]?.name??IC,rs=e=>ch[uh(e)]?.comment??null,SC=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],EC=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,Jr=e=>EC.test(e)||SC.some(t=>t.test(e)),CC=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,RC=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,NC=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,_t=e=>CC.test(e)||RC.test(e)||NC.test(e),mh=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),ph=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),fh=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),AC=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,TC=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,gh=e=>AC.test(e),hh=e=>TC.test(e);var yh=/\b(TODO|FIXME|HACK|XXX)\b/,wC=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,ac=(e,t)=>{let n=e.trim();return n===""?"blank":t&&(t.line.some(r=>n.startsWith(r))||t.block.some(([r])=>n.startsWith(r))||t.block.some(([r])=>r==="/*")&&(n.startsWith("*")||n.startsWith("*/")))?"comment":"code"},MC=(e,t)=>{let n=e.trim();for(let r of[...t.line,...t.block.flat(),"*"])if(n.startsWith(r)){n=n.slice(r.length).trim();break}return n},vh=({patch:e,repoShareByLanguage:t})=>{let n=new Map,r=0,o=0,s=0,i=0,l=0,c=0;for(let p of e.files){if(p.binary||_t(p.path))continue;let f=rs(p.path);if(!f||f.line.length===0&&f.block.length===0)continue;let g=yr(p.path),v=n.get(g)??{comment:0,code:0};for(let{text:x}of p.added){let I=ac(x,f);if(yh.test(x)&&i++,I==="blank"){s++;continue}if(I==="comment"){r++,v.comment++,f&&wC.test(MC(x,f))&&c++;continue}o++,v.code++}for(let{text:x}of p.removedLines)yh.test(x)&&l++;n.set(g,v)}let m=r+o;return{byLanguage:[...n.entries()].map(([p,f])=>({name:p,commentLines:f.comment,codeLines:f.code,share:f.comment+f.code===0?0:f.comment/(f.comment+f.code),repoShare:t?.get(p)??null})).sort((p,f)=>f.commentLines+f.codeLines-(p.commentLines+p.codeLines)),commentLines:r,codeLines:o,blankLines:s,share:m===0?0:r/m,todoLinesAdded:i,todoLinesRemoved:l,commentedOutCodeLines:c}};var PC=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,ia=6,dc=10,LC=e=>{let t=0;for(let n of e){if(n.trim()===""||n.startsWith(" "))continue;let r=n.length-n.trimStart().length;r>0&&(t===0||r<t)&&(t=r)}return Math.min(Math.max(t,2),8)},kC=(e,t)=>{let n=e.length-e.trimStart().length;if(n===0)return 0;let r=e.slice(0,n).split(" ").length-1;return r>0?r:Math.floor(n/t)},DC=e=>{if(e.length<ia*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let r=0;r+ia<=e.length;r++){let o=e.slice(r,r+ia);if(o.some(l=>l.text.length<3))continue;let s=o.map(l=>l.text).join(`
|
|
87
|
+
`),i=t.get(s);if(i===void 0){t.set(s,{...o[0],at:r});continue}if(i.file!==o[0]?.file)for(let l=0;l<ia;l++)n[i.at+l]=!0,n[r+l]=!0}return n.filter(Boolean).length},bh=({patch:e})=>{let t=[],n=[],r=[],o=!1,s=0,i=0,l=null,c=[];for(let[m,p]of e.files.entries()){if(_t(p.path)&&t.push(on(p)),mh(p.path)&&n.push(on(p)),ph(p.path)&&r.push(on(p)),fh(p.path)&&(o=!0),p.binary||_t(p.path))continue;let f=p.added.map(x=>x.text),g=LC(f),v=p.status!=="deleted";for(let x of f){PC.test(x)&&s++;let I=kC(x,g);I>i&&(i=I,l=on(p)),v&&c.push({text:x.trim(),file:m})}c.push({text:" ",file:m})}return{generatedPaths:t.slice(0,dc),dependencyManifests:n.slice(0,dc),buildOrCiPaths:r.slice(0,dc),docsTouched:o,debugPrintLinesAdded:s,maxIndentLevels:i,deepestFile:l,duplicatedLines:DC(c)}};var xh=({patch:e,languagesBefore:t})=>{let n=new Map,r=0;for(let i of e.files){if(i.binary)continue;let l=i.addedCount+i.removed;if(_t(i.path)){r+=l;continue}let c=yr(i.path),m=n.get(c)??{name:c,added:0,removed:0,addedInTests:0,share:0};m.added+=i.addedCount,m.removed+=i.removed,Jr(i.path)&&(m.addedInTests+=i.addedCount),n.set(c,m)}let o=[...n.values()].reduce((i,l)=>i+l.added+l.removed,0),s=[...n.values()].map(i=>({...i,share:o===0?0:(i.added+i.removed)/o})).sort((i,l)=>l.added+l.removed-(i.added+i.removed));return{languages:s,introduced:t===null?[]:s.filter(i=>!t.has(i.name)).map(i=>i.name),generatedLines:r}};var BC=200,lc=2e5,FC=5e4,Ih=25,OC=64*1024*1024,cc="",_C=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/,UC=/^diff --git a\/(.+) b\/\1$/,Sh=(e,t)=>e==="/dev/null"?null:e.startsWith(t)?e.slice(2):e,Eh=(e,t)=>e===null?"added":t===null?"deleted":"modified",jC=()=>({byPath:new Map,insertions:0,deletions:0,selfChurn:0,retainedLines:0}),$C=(e,t)=>{let n=e.byPath,r="",o=null,s=null,i=null,l=!1,c=0,m=(f,g)=>g==="modified"&&f==="added"?"added":g,p=(f,g)=>{let v=n.get(f);if(v)return v.entry.status=m(v.entry.status,g),v.entry.shas.includes(r)||v.entry.shas.push(r),v;let I={entry:{path:f,status:g,binary:!1,added:[],addedCount:0,removed:0,removedLines:[],shas:[r]},pendingByText:new Map};return n.set(f,I),I};for(let f of t.split(`
|
|
88
|
+
`)){if(f.startsWith(cc)){r=f.slice(cc.length).trim(),o=null,s=null,i=null,l=!1;continue}if(f.startsWith("diff --git ")){o=null,i=null,l=!0,s=UC.exec(f)?.[1]??null;continue}if(l&&f.startsWith("Binary files ")&&s){let[,v=""]=/^Binary files (.*) differ$/.exec(f)??[],[x="",I=""]=v.split(" and ");o=p(s,Eh(x==="/dev/null"?null:x,I==="/dev/null"?null:I)),o.entry.binary=!0;continue}if(l&&f.startsWith("--- ")){i=Sh(f.slice(4),"a/");continue}if(l&&f.startsWith("+++ ")){let v=Sh(f.slice(4),"b/"),x=v??i??s;x&&(o=p(x,Eh(i,v)));continue}let g=_C.exec(f);if(g){c=Number(g[1]),l=!1;continue}if(o){if(f.startsWith("+")){let v=f.slice(1);e.insertions++,o.entry.addedCount++,e.retainedLines<lc&&(o.entry.added.push({sha:r,line:c,text:v}),e.retainedLines++),o.pendingByText.size<FC&&o.pendingByText.set(v,(o.pendingByText.get(v)??0)+1),c++;continue}if(f.startsWith("-")){let v=f.slice(1);e.deletions++,o.entry.removed++,e.retainedLines<lc&&(o.entry.removedLines.push({sha:r,line:0,text:v}),e.retainedLines++);let x=o.pendingByText.get(v)??0;x>0&&v.trim().length>2&&(e.selfChurn++,o.pendingByText.set(v,x-1))}}}},HC=e=>({files:[...e.byPath.values()].map(t=>t.entry),insertions:e.insertions,deletions:e.deletions,selfChurn:e.selfChurn,retainedLines:e.retainedLines});var Ch=async({repoRoot:e,shas:t})=>{if(t.length===0)return u("No commits to scan",{files:[],insertions:0,deletions:0,selfChurn:0,scannedCommits:0,truncated:!1});let n=t.slice(0,BC).reverse(),r=jC(),o=0,s=0,i=!1;for(let c=0;c<n.length;c+=Ih){let m=n.slice(c,c+Ih),p=await j({cwd:e,args:["-c","core.quotePath=false","show","--unified=0","--no-renames","--no-color",`--format=${cc}%H`,...m]});if(d(p))return a(p.message);if($C(r,p.value.stdout),o+=p.value.stdout.length,s+=m.length,o>OC){i=!0;break}}let l=HC(r);return u("Scanned ticket patch",{files:l.files,insertions:l.insertions,deletions:l.deletions,selfChurn:l.selfChurn,scannedCommits:s,truncated:i||s<t.length||l.retainedLines>=lc})};var WC=40,GC=/^\d{6} blob ([0-9a-f]{40})\t(.+)$/,Rh=async({repoRoot:e,sha:t})=>{let n=await je({cwd:e,args:["-c","core.quotePath=false","ls-tree","-r",`${t}~1`]});if(n.exitCode!==0)return null;let r=new Set,o=new Map;for(let p of n.stdout.split(`
|
|
89
|
+
`)){let f=GC.exec(p);if(!f)continue;let[,g="",v=""]=f;if(_t(v))continue;let x=yr(v);if(r.add(x),Jr(v)||!rs(v))continue;let I=o.get(x)??[];I.length<WC&&(I.push({blob:g,path:v}),o.set(x,I))}let s=[...o.values()].flat(),i=await Ns(s.map(p=>p.blob),e);if(d(i))return{languages:r,commentShareByLanguage:new Map};let l=i.value,c=new Map;for(let{blob:p,path:f}of s){let g=l.get(p);if(g===void 0)continue;let v=rs(f),x=yr(f),I=c.get(x)??{comment:0,code:0};for(let R of g.split(`
|
|
90
|
+
`)){let A=ac(R,v);A==="comment"&&I.comment++,A==="code"&&I.code++}c.set(x,I)}let m=new Map;for(let[p,f]of c){let g=f.comment+f.code;g>0&&m.set(p,f.comment/g)}return{languages:r,commentShareByLanguage:m}};var Nh=({patch:e})=>{let t=0,n=0,r=[],o=[],s=0,i=0;for(let l of e.files)if(!(l.binary||_t(l.path))&&Jr(l.path)){t+=l.addedCount,n+=l.removed,l.status==="added"&&r.push(on(l)),l.status==="deleted"&&o.push(on(l));for(let{text:c}of l.added)gh(c)&&s++,hh(c)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:r,deletedTestFiles:o,skippedTestLinesAdded:s,focusedTestLinesAdded:i}};var VC=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,Ah=async({repoRoot:e,ref:t,commits:n})=>{let r=await Ch({repoRoot:e,shas:n.map(l=>l.sha)});if(d(r))return a(r.message);let o=r.value,s=VC(n),i=s?await Rh({repoRoot:e,sha:s}):null;return u("Derived issue stats",{ref:t,shape:lh({commits:n,patch:o}),languages:xh({patch:o,languagesBefore:i?.languages??null}),tests:Nh({patch:o}),comments:vh({patch:o,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:bh({patch:o})})};var zC=32,os=new Map;var KC=(e,t)=>{if(os.set(e,t),os.size>zC){let n=os.keys().next();n.done||os.delete(n.value)}return t},aa=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return a("idOrRef must not be empty");let n=t.length>7?_(t):t.toUpperCase(),r=xe(e.repoRoot??process.cwd());if(d(r))return a(r.message);let o=r.value,s=await Zi({repoRoot:o,ref:n});if(d(s))return a(s.message);let i=s.value.map(p=>({sha:p.sha,time:p.time,author:p.author,subject:p.subject})),l=[o,n,i.map(p=>p.sha).join(",")].join(" "),c=os.get(l);if(c)return u("Derived issue stats",c);let m=await Ah({repoRoot:o,ref:n,commits:i});return d(m)?a(m.message):u("Derived issue stats",KC(l,m.value))};var qC="Filed here",Th=(e,t)=>e.set(t,(e.get(t)??0)+1),wh=(e,t,n)=>[...e.entries()].map(([r,o])=>({laneId:r,title:r===null?qC:n(r),count:o,share:t===0?0:o/t})).sort((r,o)=>o.count-r.count||r.title.localeCompare(o.title)),Mh=(e,t,n)=>{let r=new Map,o=new Map,s=0,i=0;for(let l of t)for(let[c,m]of l.entries()){if(m!==e)continue;s++,Th(r,l[c-1]??null);let p=l[c+1];p!==void 0&&(i++,Th(o,p))}return{arrived:s,departed:i,arrivesFrom:wh(r,s,n),movesOnTo:wh(o,i,n)}};var Ph=e=>{if(e.length===0)return null;let t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2:e[t]};var ss=1440*60*1e3,uc=({laneIds:e,journeys:t,now:n,days:r})=>{let o=n-(r-1)*ss,s=new Map(e.map(i=>[i,Array.from({length:r},()=>[])]));for(let i of t)for(let[l,c]of i.entries()){let m=s.get(c.laneId);if(!m)continue;let p=i[l+1]?.enteredAt,f=Math.max(0,Math.ceil((c.enteredAt-o)/ss)),g=p===void 0?r-1:Math.min(r-1,Math.ceil((p-o)/ss)-1);for(let v=f;v<=g;v++)m[v].push(o+v*ss-c.enteredAt)}return Object.fromEntries([...s].map(([i,l])=>[i,l.map((c,m)=>({t:o+m*ss,median:Ph(c.sort((p,f)=>p-f)),count:c.length}))]))},Lh=({laneId:e,journeys:t,now:n,days:r})=>uc({laneIds:[e],journeys:t,now:n,days:r})[e];var YC=40,kh=30,XC=()=>({tickets:0,commits:0,insertions:0,deletions:0}),JC=async(e,t)=>{let n=XC();for(let r of t.slice(0,YC)){let o=await aa({repoRoot:e,idOrRef:_(r)});d(o)||o.value.shape.commits===0||(n.tickets++,n.commits+=o.value.shape.commits,n.insertions+=o.value.shape.insertions,n.deletions+=o.value.shape.deletions)}return n},Dh=()=>{let e=Y();if(d(e))return e;let{nodes:t}=e.value,n=Date.now(),r=Object.values(t).filter(P).map(s=>Ki(s.log??[],Ie(s.id))),o=Object.values(t).filter(mt).map(s=>s.id);return u("Derived board stay trends",uc({laneIds:o,journeys:r,now:n,days:kh}))},Bh=async e=>{let t=Y();if(d(t))return t;let{nodes:n}=t.value;if(!n[e.swimlaneId])return a("Swimlane not found");let o=Object.values(n).filter(P),s=o.map(c=>Ki(c.log??[],Ie(c.id))),i=Mh(e.swimlaneId,s.map(c=>c.map(m=>m.laneId)),c=>n[c]?.title??"Elsewhere"),l=o.filter(c=>c.parentNodeId===e.swimlaneId).map(c=>c.id);return u("Derived swimlane stats",{swimlaneId:e.swimlaneId,createdAt:Ie(e.swimlaneId),...i,stayTrend:Lh({laneId:e.swimlaneId,journeys:s,now:Date.now(),days:kh}),code:await JC(e.repoRoot,l)})};var Fh=new Set(["sync","issues:create","swimlane:create","swimlane:edit:title","swimlane:delete","swimlane:move","issues:move","issue:close","issue:reopen","issue:edit:title","issue:edit:description","issue:tag:add","issue:tag:remove","contributor:remove","tag:remove","issue:assignee:add","issue:assignee:remove","issue:comment:add","issue:comment:delete"]);var Oh=e=>{let t=bn({exclude:e});return d(t)?[]:t.value.map(n=>({projectId:n.projectId,name:Lr(n.root),root:n.root,lastOpenedAt:n.lastOpenedAt}))},_h=e=>{let t=bn();if(d(t))return a(t.message);let n=t.value.find(r=>r.root===e);return n?u("Resolved recent project",n.root):a(`Not a recent project: ${e}`)};import{z as L}from"zod";var K=L.string().min(1),Uh=L.discriminatedUnion("at",[L.object({at:L.literal("start")}),L.object({at:L.literal("end")}),L.object({at:L.literal("before"),sibling:K}),L.object({at:L.literal("after"),sibling:K})]),is=L.number().finite(),se=(e,t)=>L.object({type:L.literal(e),payload:t}),as=e=>L.object({type:L.literal(e)}),QC=L.discriminatedUnion("type",[as("state:get"),as("issues:list"),as("sync"),as("time-travel:live"),se("project:open",L.object({root:L.string().min(1)})),se("issues:create",L.object({title:L.string(),parentId:K,description:L.string().optional(),tagNames:L.array(L.string()).optional()})),se("swimlane:create",L.object({title:L.string(),boardId:K})),se("swimlane:edit:title",L.object({swimlaneId:K,title:L.string()})),se("swimlane:delete",L.object({swimlaneId:K})),se("swimlane:move",L.object({swimlaneId:K,boardId:K,position:Uh.optional()})),se("issues:move",L.object({issueId:K,parentId:K,position:Uh.optional()})),se("issue:edit:title",L.object({issueId:K,title:L.string()})),se("issue:edit:description",L.object({issueId:K,description:L.string()})),se("issue:tag:add",L.object({issueId:K,tagName:L.string()})),se("issue:tag:remove",L.object({issueId:K,tagId:K})),se("contributor:remove",L.object({contributorId:K})),se("tag:remove",L.object({tagId:K})),L.object({type:L.literal("contributors:get"),payload:L.object({boardId:K.optional()}).optional()}),se("issue:assignee:add",L.object({issueId:K,assigneeId:K.optional(),assigneeName:L.string().optional(),createUnlinked:L.boolean().optional()})),se("issue:assignee:remove",L.object({issueId:K,assigneeId:K})),se("issue:close",L.object({issueId:K})),se("issue:reopen",L.object({issueId:K})),se("issue:comment:add",L.object({issueId:K,body:L.string()})),se("issue:comment:delete",L.object({issueId:K,commentId:K})),se("issue:comment:edit",L.object({issueId:K,commentId:K,body:L.string()})),se("issue:get",L.object({issueId:K})),L.object({type:L.literal("timeline:get"),payload:L.object({start:is.optional(),end:is.optional(),boardId:K.optional(),requestId:L.number().finite().optional()}).optional()}),L.object({type:L.literal("commits:get"),payload:L.object({start:is.optional(),end:is.optional(),requestId:L.number().finite().optional()}).optional()}),se("time-travel:scrub",L.object({targetTime:is})),se("time-travel:checkout-event",L.object({eventId:L.string().min(1)})),se("commit:inspect",L.object({sha:L.string()})),se("commit:diff:get",L.object({sha:L.string()})),se("issue:commits:get",L.object({issueId:K})),se("issue:stats:get",L.object({issueId:K})),se("swimlane:stats:get",L.object({swimlaneId:K})),as("board:stay-trends:get")]);var jh=e=>{let t=QC.safeParse(e);return t.success?{ok:!0,message:t.data}:{ok:!1,error:`Invalid message: ${t.error.issues.map(r=>`${r.path.join(".")||"<root>"}: ${r.message}`).join(", ")}`}};var eR=1024*1024,mc=()=>{tr({type:"state",payload:hr(fr())})},Z=(e,t)=>{e.send(JSON.stringify(t))},ds=async(e,t)=>{let n=hr(await Ct({repoRoot:t}));return d(n)&&n.message===Va?Z(e,{type:"state:unavailable",payload:{message:n.message,repoRoot:t,recentProjects:Oh(t)}}):Z(e,{type:"state",payload:n})},tR=async(e,t)=>{let n=()=>Z(e,{type:"state",payload:hr(fr())});if(tt().mode!=="live")return n();let r=await Ct({repoRoot:t});return tt().mode!=="live"?n():Z(e,{type:"state",payload:hr(r)})},We=async(e,t,n,r,o)=>{if(Z(e,{type:r,payload:o}),d(o))return Z(e,{type:"failed",payload:o.message});n(),tR(e,t)},$h=(e,t,{onStateChanged:n,getPort:r})=>{new ZC({server:e,path:"/ws",maxPayload:eR,verifyClient:s=>!sc(s.origin,r())}).on("connection",s=>{bm(s),s.on("message",async i=>{let l=async c=>{let{type:m}=c,p=t.repoRoot;if(m==="project:open"){let f=_h(c.payload.root);return Z(s,{type:"project:open:result",payload:f}),d(f)?void 0:(t.repoRoot=f.value,ds(s,f.value))}if(m==="timeline:get"){let{requestId:f,...g}=c.payload??{};return Z(s,{type:"timeline",requestId:f,payload:await Gg({repoRoot:p,...g})})}if(m==="issue:get"){let f=c.payload?.issueId,g=fr(),v=Hl(f);return Z(s,{type:"issue",payload:d(g)?g:u("Issue detail",{...ih(g.value,f),history:d(v)?[]:v.value})})}if(m==="commits:get"){let{requestId:f,...g}=c.payload??{};return Z(s,{type:"commits",requestId:f,payload:await Tl({repoRoot:p,...g})})}if(m==="commit:inspect")return Z(s,{type:"commit:inspect:result",payload:await zg({repoRoot:p,sha:c.payload.sha})});if(m==="commit:diff:get"){let{sha:f}=c.payload;return Z(s,{type:"commit:diff:result",payload:{sha:f,result:await Kg({repoRoot:p,sha:f})}})}if(m==="issue:commits:get"){let{issueId:f}=c.payload;return Z(s,{type:"issue:commits:result",payload:{issueId:f,result:await Zi({repoRoot:p,ref:_(f)})}})}if(m==="issue:stats:get"){let{issueId:f}=c.payload;return Z(s,{type:"issue:stats:result",payload:{issueId:f,result:await aa({repoRoot:p,idOrRef:_(f)})}})}if(m==="swimlane:stats:get"){let{swimlaneId:f}=c.payload;return Z(s,{type:"swimlane:stats:result",payload:{swimlaneId:f,result:await Bh({repoRoot:p,swimlaneId:f})}})}if(m==="board:stay-trends:get")return Z(s,{type:"board:stay-trends:result",payload:Dh()});if(m==="time-travel:scrub"){let f=await wl({repoRoot:p,targetTime:c.payload.targetTime});return Z(s,{type:"time-travel:result",payload:f}),d(f)?void 0:mc()}if(m==="time-travel:checkout-event"){let f=await Yg({repoRoot:p,eventId:c.payload.eventId});return Z(s,{type:"time-travel:result",payload:f}),d(f)?void 0:mc()}if(m==="time-travel:live"){let f=await Xg({repoRoot:p});return Z(s,{type:"time-travel:result",payload:f}),d(f)?void 0:mc()}if(m==="state:get")return ds(s,p);if(m==="sync"){let f=await qo({repoRoot:p});return Z(s,{type:"sync:result",payload:f}),n(),ds(s,p)}if(m==="issue:comment:add"){let f=await es({repoRoot:p,...c.payload});return We(s,p,n,"issue:comment:add:result",f)}if(m==="issue:comment:edit"){let f=await nc({repoRoot:p,...c.payload});return We(s,p,n,"issue:comment:edit:result",f)}if(m==="issue:comment:delete"){let f=await ts({repoRoot:p,...c.payload});return Z(s,{type:"issue:comment:delete:result",payload:f}),d(f)?Z(s,{type:"failed",payload:f.message}):(n(),ds(s,p))}if(m==="issue:edit:description"){let f=await Wl({repoRoot:p,...c.payload});return We(s,p,n,"issue:edit:description:result",f)}if(m==="issue:edit:title"){let f=await Gl({repoRoot:p,...c.payload});return We(s,p,n,"issue:edit:title:result",f)}if(m==="issue:tag:add"){let f=await Yl({repoRoot:p,...c.payload});return We(s,p,n,"issue:tag:add:result",f)}if(m==="issue:tag:remove"){let f=await Jl({repoRoot:p,...c.payload});return We(s,p,n,"issue:tag:remove:result",f)}if(m==="contributor:remove"){let f=await Zl({repoRoot:p,...c.payload});return We(s,p,n,"contributor:remove:result",f)}if(m==="tag:remove"){let f=await Xl({repoRoot:p,...c.payload});return We(s,p,n,"tag:remove:result",f)}if(m==="contributors:get")return Z(s,{type:"contributors",payload:await ec({repoRoot:p,...c.payload})});if(m==="issue:assignee:add"){let f=await Ql({repoRoot:p,...c.payload});return We(s,p,n,"issue:assignee:add:result",f)}if(m==="issue:assignee:remove"){let f=await tc({repoRoot:p,...c.payload});return We(s,p,n,"issue:assignee:remove:result",f)}if(m==="issues:list")return Z(s,{type:"issues",payload:await Ol({repoRoot:p})});if(m==="issues:create"){let f=await _l({...c.payload,repoRoot:p});return Z(s,{type:"issues:create:result",payload:f}),d(f)?tr({type:"failed",payload:f.message}):(n(),ds(s,p))}if(m==="swimlane:create"){let f=await Vl({...c.payload,repoRoot:p});return We(s,p,n,"swimlane:create:result",f)}if(m==="swimlane:edit:title"){let f=await zl({...c.payload,repoRoot:p});return We(s,p,n,"swimlane:edit:title:result",f)}if(m==="swimlane:delete"){let f=await ql({...c.payload,repoRoot:p});return We(s,p,n,"swimlane:delete:result",f)}if(m==="swimlane:move"){if(!c.payload.position)return Z(s,{type:"error",message:"Missing move position"});let f=await Kl({...c.payload,repoRoot:p});return We(s,p,n,"swimlane:move:result",f)}if(m==="issues:move"){if(!c.payload.position)return Z(s,{type:"error",message:"Missing move position"});let f=await $l({...c.payload,repoRoot:p});return We(s,p,n,"issues:move:result",f)}if(m==="issue:close"){let f=await Ul({repoRoot:p,issueId:c.payload.issueId});return We(s,p,n,"issue:close:result",f)}if(m==="issue:reopen"){let f=await jl({repoRoot:p,issueId:c.payload.issueId});return We(s,p,n,"issue:reopen:result",f)}return Z(s,{type:"error",message:"Unknown message type"})};try{let c=jh(JSON.parse(i.toString()));if(!c.ok)return Z(s,{type:"error",message:c.error});let m=c.message;return Fh.has(m.type)?await Wn(async()=>tt().mode!=="live"?Z(s,{type:"failed",payload:"Read-only while viewing history"}):l(m)):await l(m)}catch(c){return Z(s,{type:"error",message:c instanceof Error?c.message:String(c)})}})})};var oR=vr.dirname(rR(import.meta.url)),sR=process.env.IS_LOCAL==="true"?vr.resolve(process.cwd(),"dist/gui"):vr.join(oR,"gui"),da,iR=async()=>(da===void 0&&(da=await import("node:sea").catch(()=>null)),da?.isSea()?da:null),Ce=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},aR=e=>Ce(e,409,{isError:!0,message:"Read-only while viewing history"}),la=(e,t)=>Wn(async()=>tt().mode!=="live"?aR(e):t()),Hh=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.push(i)}),e.on("end",()=>{let i=Buffer.concat(o).toString("utf8");try{n(i?JSON.parse(i):{})}catch{r(new Error("Invalid JSON body"))}}),e.on("error",r)}),dR=2*1024*1024,lR={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},cR=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",Wh=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=vr.resolve(sR),o=vr.resolve(r,n),s=vr.relative(r,o);if(s.startsWith("..")||vr.isAbsolute(s))return Ce(t,403,{isError:!0,message:"Forbidden"});let i=await iR();try{let l=i?Buffer.from(i.getAsset(`gui/${s}`)):await Gh(o);return t.writeHead(200,{"content-type":cR(o)}),t.end(l)}catch{return Ce(t,404,{isError:!0,message:`Not found: ${n}`})}},uR=async(e,t=ns)=>new Promise((n,r)=>{let o=s=>{let i=c=>{if(e.off("listening",l),c.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(c)},l=()=>{e.off("error",i);let c=e.address();if(!c||typeof c=="string"){r(new Error("Unable to resolve address"));return}n(c.port)};e.once("error",i),e.once("listening",l),e.listen(s,"127.0.0.1")};o(t)}),Vh=async e=>{Pg(!1);let t=0,n={repoRoot:e.repoRoot},r=nR.createServer(async(i,l)=>{let c=new URL(i.url??"/","http://127.0.0.1"),m=dh({method:i.method,origin:i.headers.origin,contentType:i.headers["content-type"]},t);if(m)return Ce(l,m.status,{isError:!0,message:m.message});if(i.method==="GET"&&c.pathname===rc)return Ce(l,200,{app:oc,repoRoot:ra(n.repoRoot),version:rn,pid:process.pid});if(c.pathname==="/api/state")return Ce(l,200,await Ct({repoRoot:n.repoRoot}));if(i.method==="POST"&&c.pathname==="/api/comments")try{let p=await Hh(i);if(!p.issueId||!p.body?.trim())return Ce(l,400,{isError:!0,message:"Missing issueId or body"});let f=p.issueId,g=p.body;return await la(l,async()=>{let v=await es({repoRoot:n.repoRoot,issueId:f,body:g});return d(v)?Ce(l,400,{isError:!0,message:v.message}):Ce(l,200,await Ct({repoRoot:n.repoRoot}))})}catch(p){return Ce(l,400,{isError:!0,message:p instanceof Error?p.message:"Unable to add comment"})}if(i.method==="POST"&&c.pathname==="/api/attachments")try{let p=await Hh(i,dR);if(!p.issueId||!p.dataBase64)return Ce(l,400,{isError:!0,message:"Missing issueId or dataBase64"});let f=p.issueId,g=p.dataBase64,v=p.name??"";return await la(l,async()=>{let x=await Pl({repoRoot:n.repoRoot,issueId:f,name:v,dataBase64:g});return d(x)?Ce(l,400,{isError:!0,message:x.message}):Ce(l,200,{...await Ct({repoRoot:n.repoRoot}),attachment:x.value})})}catch(p){return Ce(l,400,{isError:!0,message:p instanceof Error?p.message:"Unable to add attachment"})}if(i.method==="DELETE"&&c.pathname.startsWith("/api/attachments/")){let p=decodeURIComponent(c.pathname.replace("/api/attachments/",""));return p?la(l,async()=>{let f=await Ll({repoRoot:n.repoRoot,attachmentId:p});return d(f)?Ce(l,400,{isError:!0,message:f.message}):Ce(l,200,await Ct({repoRoot:n.repoRoot}))}):Ce(l,400,{isError:!0,message:"Missing attachment id"})}if(i.method==="GET"&&c.pathname.startsWith("/media/")){let p=decodeURIComponent(c.pathname.replace("/media/","")),f=await kl({repoRoot:n.repoRoot,fileName:p});if(d(f))return Ce(l,404,{isError:!0,message:f.message});try{let g=await Gh(f.value.filePath);return l.writeHead(200,{"content-type":lR[f.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),l.end(g)}catch{return Ce(l,404,{isError:!0,message:"Attachment blob not found"})}}if(i.method==="DELETE"&&c.pathname.startsWith("/api/comments/")){let p=decodeURIComponent(c.pathname.replace("/api/comments/",""));return p?la(l,async()=>{let f=await ts({repoRoot:n.repoRoot,commentId:p});return d(f)?Ce(l,400,{isError:!0,message:f.message}):Ce(l,200,await Ct({repoRoot:n.repoRoot}))}):Ce(l,400,{isError:!0,message:"Missing comment id"})}return c.pathname.startsWith("/board/")?Wh("/",l):Wh(c.pathname,l)});try{t=await uR(r)}catch(i){return a(i instanceof Error?`Unable to start GUI server: ${i.message}`:`Unable to start GUI server: ${String(i)}`)}let o=ah({project:n});$h(r,n,{onStateChanged:()=>o.queueSync(),getPort:()=>t}),r.on("close",o.dispose);let s=r.address();return!s||typeof s=="string"?(r.close(),a("Unable to resolve GUI server address")):u("Started GUI server",{url:`http://epiq.localhost:${s.port}${e.boardId?`/board/${e.boardId}`:""}`,server:r})};var Kh=async e=>{let t=Ir({});if(d(t))return a(t.message);let n=yt();ce(n)&&ze(n.value);let r=await sh(ns);if(r&&r.repoRoot===ra(e.repoRoot)){let i=`http://127.0.0.1:${ns}`;return console.log(`Epiq GUI already running for this project at ${zh.cyan(i)}`),Ja(i),u("Reused running GUI",{url:i})}let o=await Vh({...e,boardId:""});if(d(o))return o;let{url:s}=o.value;return console.log(`Epiq GUI running at ${zh.cyan(s)}`),Ja(s),u("Started GUI",{url:s})};import{Box as Kn}from"ink";import Re from"react";import{Box as pc,Text as ls}from"ink";import Ut,{useEffect as mR,useMemo as pR}from"react";import{ulid as fR}from"ulid";var qh=({text:e,match:t,color:n,highlightColor:r=y.secondary,dimColor:o=!1})=>{if(!t)return Ut.createElement(ls,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),l=s.indexOf(i);return l===-1?Ut.createElement(ls,{color:n,dimColor:o},e):Ut.createElement(ls,{color:n,dimColor:o},e.slice(0,l),Ut.createElement(ls,{backgroundColor:r,bold:!0},e.slice(l,l+t.length)),e.slice(l+t.length))},Yh=fR(),gR=e=>`${e}`,hR=e=>{let{pendingNavTarget:t}=_n();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(Ne(E.NONE,{breadCrumb:n,contextNode:r,readOnly:h().readOnly,selectedNode:o}));return[...new Set(Object.values(E))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==E.PALETTE).map(i=>{let l=xi(i),c=Hi.find(m=>m.intent===l);return{command:i,description:c?.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,l)=>i.isAvailable!==l.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(l.command))},yR=e=>ge.text({id:Yh,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),vR=(e,t,n)=>ge.text({id:gR(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),fc=[],bR=e=>{Xh();let t=C.createNode(yR(h().rootNodeId));d(t)||!Nn(t.value)||(fc=[t.value,...e.map((n,r)=>vR(n,r,Yh)).map(C.createNode).filter(ce).map(({value:n})=>n).filter(Nn)],O.navigate({contextNode:t.value,selectedIndex:0}))},Xh=()=>{let e=fc.map(t=>t.id);fc=[];for(let t of e)C.deleteNode(t)};function Jh({width:e,height:t}){let r=Mp().value.trim().toLowerCase(),o=pR(()=>hR(r),[r]);mR(()=>(bR(o),()=>{Xh()}),[o]);let s=h().selectedIndex;return Ut.createElement(pc,{flexDirection:"column",width:e,height:t-2},Ut.createElement(It,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,l)=>{let c=l===s,m=i.isAvailable?y.accent:y.secondary2,p=i.isAvailable?"":"[unavailable] ";return Ut.createElement(pc,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Ut.createElement(ls,{color:m,dimColor:!i.isAvailable},c?"\u276F ":" ",Ut.createElement(qh,{text:yu(i.command),match:r,color:m,dimColor:!i.isAvailable})),Ut.createElement(pc,{paddingLeft:2},Ut.createElement(qh,{text:p+i.description,match:r.length>=2?r:"",color:c&&i.isAvailable?y.primary:y.secondary2,dimColor:!i.isAvailable})))})))}import{Box as DR}from"ink";import ma from"react";import us from"chalk";import{Box as gc,Text as ty}from"ink";import cs,{useEffect as ny,useMemo as xR,useState as ry}from"react";var Qr=["\u2803","\u2806","\u2830","\u2818"],Qh=120,Zh=({isPalette:e,isPending:t,frame:n})=>{if(t){let r=(n%Qr.length+Qr.length)%Qr.length;return Qr[r]}return e?"?":":"},ey=({infoMessage:e,isPending:t})=>t&&e.includes(le)?"":e;var oy=us.hex(y.secondary),IR=us.inverse,SR=us.inverse.hex(y.secondary2),ER={hint:"",hints:[],overlap:0,remainder:""},iy=({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}},CR=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=de(t);return{bg:r=>us.bgHex(n).black(r),bgCursor:r=>us.bgHex(n).inverse.black(r)}}return Ud(t)},RR=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=iy({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}},sy=()=>({value:qe.value,cursorPosition:qe.cursorPosition,commandIsPending:qe.commandIsPending,autoCompletion:qe.commandMeta.autoCompletion??ER,infoMessage:qe.commandMeta.infoMessage,validationStatus:qe.commandMeta.validity,command:qe.commandMeta.command,inputString:qe.commandMeta.inputString,modifier:qe.commandMeta.modifier}),NR=(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,ay=({width:e,mode:t})=>{let[n,r]=ry(sy());ny(()=>{let w=()=>{let k=sy();r(D=>NR(D,k)?D:k)},M=Wd(w);return w(),()=>{M()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:l,autoCompletion:c,command:m,modifier:p,validationStatus:f}=n,g=l&&f===Qt.Invalid,v=ey({infoMessage:i,isPending:l}),[x,I]=ry(0);ny(()=>{if(!l){I(0);return}let w=setInterval(()=>{I(M=>(M+1)%Qr.length)},Qh);return()=>{clearInterval(w)}},[l]);let R=Zh({isPalette:t===b.PALETTE,isPending:l,frame:x}),A=xR(()=>{let w=Math.max(0,Math.min(s,o.length)),M=iy({value:o,command:m}),k=RR({value:o,command:m,modifier:p}),D=m?Ud(m):null,ve=CR({command:m,modifier:p}),Ve=(lt,ct)=>{let Na=M&&ct>=M.start&&ct<M.end,Aa=k&&ct>=k.start&&ct<k.end;return Na&&D?D.fg(lt):Aa&&ve?ve.bg(lt):lt},At=(lt,ct)=>{let Na=M&&ct>=M.start&&ct<M.end,Aa=k&&ct>=k.start&&ct<k.end;return Na&&D?D.fgCursor(lt):Aa&&ve?ve.bgCursor(lt):IR(lt)},dt=o.slice(0,w),ke=o[w]??" ",Sn=w<o.length?o.slice(w+1):"",qn=Array.from(dt).map((lt,ct)=>Ve(lt,ct)).join(""),bs=At(ke,w),ro=Array.from(Sn).map((lt,ct)=>Ve(lt,w+1+ct)).join("");if(c.hint){let lt=c.hint[c.overlap]??ke;bs=SR(lt),ro=oy(c.remainder.slice(1)+Sn)}return qn+bs+ro},[o,s,c,m,p]);return cs.createElement(gc,{flexDirection:"column",justifyContent:"flex-start"},cs.createElement(gc,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},cs.createElement(gc,null,cs.createElement(ty,null,oy(R),A),v&&cs.createElement(ty,{wrap:"truncate",color:g?y.red:y.secondary2},` ${v} `))))};import{Box as AR,Text as ms}from"ink";import Zr from"react";var dy=" ",TR=({keys:e,label:t})=>e.length+1+t.length,wR=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?dy.length:0)+TR(o);if(r+i>t-4)break;n.push(o),r+=i}return n},ly=({width:e,availableHints:t})=>{let n=wR(t,e);return Zr.createElement(AR,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1},n.length?Zr.createElement(ms,{wrap:"truncate"},n.map(({keys:o,label:s},i)=>Zr.createElement(ms,{key:`${o}-${s}`},i>0?dy:"",Zr.createElement(ms,{color:y.accent},o),Zr.createElement(ms,{color:y.secondary2}," ",s)))):Zr.createElement(ms,{color:y.secondary2},"\xA0"))};import{Box as MR,Text as ca}from"ink";import ps,{useEffect as PR,useRef as eo,useState as LR}from"react";var kR=40,ua=.3,hc="\u2500",cy=1,uy=16,my=({width:e})=>{let{replay:t}=X(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*cy,[l,c]=LR(0),m=eo(r);m.current=r;let p=eo(0),f=eo(0),g=eo(0),v=eo(0),x=eo(0);if(PR(()=>{if(!n){p.current=0,g.current=0,v.current=0,x.current=0,c(0);return}p.current=m.current,f.current=Date.now(),g.current=m.current;let M=setInterval(()=>{let k=Date.now(),D=m.current;if(D!==g.current){let ke=D-g.current,Sn=k-f.current;if(ke<0)v.current=0,x.current=0;else if(ke>0&&Sn>0){let qn=ke/Sn;v.current=v.current===0?qn:v.current*(1-ua)+qn*ua,x.current=x.current===0?ke:x.current*(1-ua)+ke*ua}p.current=D,f.current=k,g.current=D}let ve=k-f.current,Ve=Math.min(x.current,v.current*ve),At=Math.min(1,p.current+Ve),dt=Math.round(At*i);c(ke=>ke===dt?ke:dt)},kR);return()=>clearInterval(M)},[n,i]),!t)return null;let I=M=>{let k=s>1?M/(s-1):0,D=Math.round(k*(uy-1))/(uy-1);return pi(D)},R=Math.min(s,Math.floor(l/cy)),A=[];for(let M=0;M<R;M++){let k=I(M),D=A[A.length-1];D&&D.color===k?D.text+=hc:A.push({text:hc,color:k})}let w=hc.repeat(Math.max(0,s-R));return ps.createElement(MR,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1,columnGap:1},ps.createElement(ca,{color:y.secondary2},"\u25B6"),ps.createElement(ca,null,A.map((M,k)=>ps.createElement(ca,{key:k,color:M.color},M.text)),ps.createElement(ca,{color:y.secondary,dimColor:!0},w)))};var fs=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=X(),o=t===b.COMMAND_LINE||t===b.PALETTE;return ma.createElement(DR,null,o?ma.createElement(ay,{width:e,mode:t}):r==="replay"?ma.createElement(my,{width:e}):ma.createElement(ly,{width:e,mode:t,availableHints:n}))};import{Box as Gn,Text as to}from"ink";import nt,{useEffect as BR,useMemo as FR}from"react";import{ulid as py}from"ulid";var fa=py(),OR=()=>[...new Set([...h().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(yl).filter(e=>e!==null).sort(({keys:e},{keys:t})=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(({keys:e,label:t})=>({keys:e,action:t})),_R=e=>ge.text({id:fa,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),UR=(e,t,n)=>ge.text({id:py(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),pa=[],fy=()=>{let e=pa.filter(n=>n.id!==fa).map(n=>n.id),t=pa.filter(n=>n.id===fa).map(n=>n.id);pa=[];for(let n of[...e,...t])C.deleteNode(n)},jR=e=>{fy();let t=C.createNode(_R(h().rootNodeId));if(d(t)||!Nn(t.value))return logger.error("Could not attach help nodes");pa=[t.value,...e.map((n,r)=>UR(n,r,fa)).map(C.createNode).filter(ce).map(({value:n})=>n).filter(Nn)],O.navigate({contextNode:t.value,selectedIndex:0})},gy=({width:e,height:t})=>{let n=FR(()=>OR(),[]);BR(()=>(jR(n),()=>{fy()}),[n]);let r=h().selectedIndex;return nt.createElement(Gn,{flexDirection:"column",marginTop:3,borderColor:y.secondary,borderStyle:"round",width:e,height:t-2},nt.createElement(Gn,{paddingX:1,justifyContent:"center"},nt.createElement(to,{color:y.accent},"Help"),nt.createElement(to,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),nt.createElement(Gn,{paddingX:1,marginTop:1},nt.createElement(Gn,{width:20,justifyContent:"flex-end"},nt.createElement(to,{color:y.secondary},"Key(s)")),nt.createElement(Gn,{flexGrow:1,width:40,paddingLeft:2},nt.createElement(to,{color:y.secondary},"Action"))),nt.createElement(It,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let l=i===r;return nt.createElement(Gn,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},nt.createElement(Gn,{width:20,justifyContent:"flex-end"},nt.createElement(to,{color:y.accent},o)),nt.createElement(Gn,{flexGrow:1,width:40,paddingLeft:2},nt.createElement(to,{color:l?y.primary:y.secondary2},s)))})))};import $R from"chalk";import{Box as br,Text as Ue}from"ink";import pe from"react";var HR=8,WR=()=>{let e=bn({exclude:process.cwd()});return d(e)?[]:e.value.slice(0,HR)},hy=({width:e,height:t})=>{let n=WR();return pe.createElement(br,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},pe.createElement(Ue,{color:y.accent,bold:!0},"Initialize project"),pe.createElement(Ue,null,`This folder is not an ${$R.hex(y.accent)("epiq")} project yet.`),pe.createElement(Ue,{color:y.primary},"To start tracking issues here, we need to initialize a new",pe.createElement(Ue,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json "),"file in this repository."),pe.createElement(br,{marginTop:1,flexDirection:"column"},pe.createElement(br,null,pe.createElement(Ue,{color:y.accent}," "),pe.createElement(Ue,{color:y.primary},"Type "),pe.createElement(Ue,{backgroundColor:y.secondary}," :init "))),pe.createElement(br,{marginTop:1},pe.createElement(Ue,{color:y.secondary2},"This will create, commit and push "),pe.createElement(Ue,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json ")),n.length>0&&pe.createElement(br,{marginTop:1,flexDirection:"column"},pe.createElement(Ue,{color:y.accent,bold:!0},"Or open a recent project"),n.map((r,o)=>pe.createElement(br,{key:r.projectId},pe.createElement(Ue,{color:y.accent},` ${o+1} `),pe.createElement(Ue,{color:y.primary},Lr(r.root)),pe.createElement(Ue,{color:y.secondary2},` ${r.root}`))),pe.createElement(br,{marginTop:1},pe.createElement(Ue,{color:y.accent}," "),pe.createElement(Ue,{color:y.primary},"Type "),pe.createElement(Ue,{backgroundColor:y.secondary}," :open 1 "),pe.createElement(Ue,{color:y.secondary2}," or "),pe.createElement(Ue,{backgroundColor:y.secondary}," :open <path> "))))};import{Box as ga,Text as sn}from"ink";import Ge from"react";var GR=({isDone:e,command:t,value:n})=>Ge.createElement(ga,null,Ge.createElement(sn,{color:y.accent,dimColor:e},e?" \u2714 ":" "),Ge.createElement(sn,{dimColor:e},"Type "),Ge.createElement(sn,{backgroundColor:y.secondary,dimColor:e}," "+t+" "),n!==void 0&&Ge.createElement(Ge.Fragment,null,Ge.createElement(sn,{dimColor:e}," "),Ge.createElement(sn,{color:y.secondary,dimColor:e},"<"+n+">"))),VR=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function yc({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:l}=Ln(),c=[{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:l,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=c.findIndex(f=>!f.done),p=m===-1?void 0:c[m];return Ge.createElement(ga,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},Ge.createElement(sn,{color:y.accent,bold:!0},"Welcome! \u{1F539}"),Ge.createElement(sn,null,"Let's get you started - it's a breeze."),Ge.createElement(sn,{color:y.secondary2},"Remember - you can always search available commands by typing:",Ge.createElement(sn,{color:y.accent}," ? ")),p&&Ge.createElement(sn,{color:y.secondary2},p.message),Ge.createElement(ga,{flexDirection:"column"},c.map((f,g)=>m===-1||g<=m?Ge.createElement(ga,{key:f.key,marginBottom:1},Ge.createElement(GR,{isDone:f.done,command:f.command,value:f.done?VR(f.value):void 0})):null)))}import xa from"chalk";import{Box as hs,Text as no}from"ink";import Le from"react";import{Box as ha,Text as yy}from"ink";import Vn from"react";import zR from"chalk";var KR=e=>(C.getTag(e)?.name??"").length+3,qR=e=>{let t=C.getContributor(e);return(t?t.name:"").length+3},vy=({width:e})=>{let{viewMode:t}=ie(),n=X(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,l=i[o.id]?.[s],c=at(l?.id??o.id,"TICKET"),m=ce(c)?c.value:void 0,p=(m?.props.tags??[]).filter(D=>C.getTag(D)),f=m?.props.assignees??[],g=m?.parentNodeId?!Sl(o.id,m.parentNodeId)&&t==="dense":!1,v=r.map((D,ve)=>{let Ve=ve===r.length-1,At=ae(D.id),dt=Ve?At?.[s]?.title:void 0;return`${ve?" / ":""}${D.title??""}${dt?` \u25B8 ${dt}`:""}`}).join(""),x=m?C.getCommentsByIssue(m.id):[],I=x.length?String(x.length).length+11:0,R=g?p.reduce((D,ve)=>D+KR(ve),0)+f.reduce((D,ve)=>D+qR(ve),0)+I:0,A=l?.id!=null&&!(t==="wide"&&P(l)),w=Math.max(0,e-R),M=v.substring(0,w)+(A?zR.hex(y.secondary2).dim(` ${_(l.id)}`):""),k=g?[...p.map(D=>Vn.createElement(ha,{key:`tag-${D}`,paddingLeft:1},Vn.createElement(_r,{id:D}))),...f.map(D=>Vn.createElement(ha,{key:`assignee-${D}`,paddingLeft:1},Vn.createElement(Bn,{id:D}))),x.length?Vn.createElement(ha,{key:"comments",paddingLeft:1},Vn.createElement(yy,{color:y.accent},"[",x.length," comment",x.length===1?"":"s","]")):null]:[];return Vn.createElement(ha,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},Vn.createElement(yy,{color:y.secondary2},M),k)};import{Box as YR,Text as by}from"ink";import ya from"react";var XR=({filters:e})=>ya.createElement(YR,{columnGap:1},ya.createElement(by,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>ya.createElement(by,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),xy=ya.memo(XR);import{Box as JR,Text as va}from"ink";import gs from"react";function Iy(){let{eventLog:e,unappliedEvents:t}=X(),n=e.at(-1)?.id,r=Ds(n??""),o=ce(r)?Ri(r.value):"INVALID DATE";return gs.createElement(JR,{paddingLeft:1},gs.createElement(va,{backgroundColor:y.accent,color:y.secondary}," Readonly "),gs.createElement(va,{color:y.accent}," "+t.length+" edits ago at "+o+"."),gs.createElement(va,{color:y.accent}," Resume with "),gs.createElement(va,{backgroundColor:y.accent,color:y.secondary}," ",":peek now"," "))}import{Box as QR,Text as vc}from"ink";import ba from"react";function Sy(){let{replay:e}=X();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return ba.createElement(QR,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},ba.createElement(vc,{backgroundColor:y.accent,color:y.secondary}," \u25B6 REPLAY "),ba.createElement(vc,{color:y.secondary2},Ri(new Date(r))),ba.createElement(vc,{color:y.accent},`${t}/${n} edits`))}import bc from"chalk";import{Box as ZR,Text as Ey}from"ink";import xc,{useEffect as eN,useState as tN}from"react";var nN=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],rN=150,Cy=12,oN=.36,Ry=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)}},sN=({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)}`},iN=(e,t,n)=>{let r=Ry(e),o=Ry(t);return sN({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},aN=(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 iN(s,i,o)};function Ny({syncStatus:e,autoSync:t}){let[n,r]=tN(0);eN(()=>{if(e.status!=="syncing"){r(0);return}let l=0,c=setInterval(()=>{l+=1;let m=(Math.sin(l*oN)+1)/2,p=Math.round(m*(Cy-1));r(f=>f===p?f:p)},rN);return()=>clearInterval(c)},[e.status]);let o={synced:" ",failed:"---",offline:"off",syncing:"...",pending:"idle"},i={synced:y.secondary2,failed:y.yellow,offline:y.secondary2,pending:y.secondary2,syncing:aN(nN,n/(Cy-1))??""}[e.status];return xc.createElement(ZR,null,xc.createElement(Ey,null,bc.hex(y.secondary2).dim(t?"Sync (auto): ":"Sync: ")),xc.createElement(Ey,null,bc.hex(i)("\u25CF")+bc.hex(y.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import Py from"chalk";import{Text as Ly}from"ink";import ky,{useEffect as uN,useState as mN}from"react";import Ic from"chalk";var dN="https://registry.npmjs.org/epiq/latest",Sc=null,Ay=0,lN=1e3*60*60*24,Ty=e=>e.replace(/^v/,""),cN=(e,t)=>{let n=Ty(e).split(".").map(Number),r=Ty(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},wy=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(Sc&&Date.now()-Ay<lN)return Sc;try{let t=await fetch(dN);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?cN(r,e)>0:!1};return Sc=o,Ay=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},My=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?Ic.hex(y.accent).dim(s):Ic.hex(y.secondary).dim(s)).join(Ic.hex(y.secondary2).dim("."))};function Dy(){let[e,t]=mN({current:rn,latest:null,updateAvailable:!1});return uN(()=>{let n=!0;return wy(rn).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?ky.createElement(Ly,{dimColor:!0,color:y.secondary2},rn+" "):ky.createElement(Ly,null,Py.hex(y.secondary2).dim(rn),Py.hex(y.accent).dim(" \u2197 "),My(rn,e.latest))}function ys({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=X(),{userName:i,preferredEditor:l,autoSync:c}=ie(),m=64,p=process.stdout.columns-m-8,f=t||n==="replay",g=s?fn(s.currentLabel,Math.max(0,p)):"";return Le.createElement(hs,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?Le.createElement(hs,{paddingLeft:1},Le.createElement(no,{color:y.secondary2},g)):f?Le.createElement(no,null," "):o===b.PALETTE?Le.createElement(hs,null,Le.createElement(no,{color:y.accent},"Command Palette"),Le.createElement(no,{dimColor:!0,color:y.secondary2}," ","- search, select and press enter")):Le.createElement(hs,{paddingLeft:1},e.length>0?Le.createElement(xy,{filters:e}):Le.createElement(vy,{width:p})),n==="live"?Le.createElement(hs,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},Le.createElement(Ny,{autoSync:!!c,syncStatus:r}),Le.createElement(no,null,xa.hex(y.secondary2).dim("Mode: ")+xa.hex(y.secondary2).dim(o.padEnd(8," "))," "),Le.createElement(By,{icon:"@",value:i}),Le.createElement(By,{icon:"\u276F",value:l}),Le.createElement(Dy,null)):"",n==="peek"?Le.createElement(Iy,null):"",n==="replay"?Le.createElement(Sy,null):"")}function By({icon:e,value:t}){return Le.createElement(no,null,xa.dim(e)+xa.hex(y.accent)(` ${t??"-"} `))}import{Box as pN,Text as fN}from"ink";import vs from"react";import{Box as Ia,Text as Ec}from"ink";import zn from"react";function Cc(){let e=X(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?q(t?.id):[];return zn.createElement(Ia,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:y.secondary,width:s},zn.createElement(Ia,{padding:1,paddingTop:0,paddingBottom:0},zn.createElement(Ec,null,"Select a board:")),zn.createElement(Ia,{padding:1,flexDirection:"column"},i.map((l,c)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===c,f=q(l.id).flatMap(({id:g})=>ae(g)).length;return zn.createElement(Ia,{key:l.id??c},zn.createElement(Ec,{color:m?y.accent:y.secondary2},zn.createElement(Ye,{isSelected:m})),zn.createElement(Ec,{color:m?y.accent:y.secondary2},l.title," (",f," issues)",l.readonly?" \u{1F512}":""))})))}var gN=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:l}=X(),c=n.find(({context:g})=>g==="BOARD"),f=s-1-3;return vs.createElement(pN,{flexDirection:"row"},e.context==="WORKSPACE"?vs.createElement(Cc,null):c?vs.createElement(Ti,{height:f,width:i,swimlanes:(l[c.id]??[]).filter(g=>g!==void 0&&mt(g)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):vs.createElement(fN,null))},Fy=vs.memo(gN);import{useEffect as hN}from"react";var yN=e=>{hN(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=ie();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:l,mode:c}=h();c==="default"&&!l&&si(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},Oy=({autoSync:e})=>(yN(e),null);function Rc({width:e,height:t}){let n=X(),{autoSync:r,viewMode:o}=du(),s=n.filters;if(n.mode===b.HELP)return Re.createElement(Kn,{flexDirection:"column"},Re.createElement(gy,{width:e,height:t}));if(n.mode===b.PALETTE)return Re.createElement(Kn,{flexDirection:"column"},Re.createElement(ys,{filters:s}),Re.createElement(Jh,{width:e,height:t-2}),Re.createElement(fs,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Ln(),l=!i,c=i&&!n.hasProjectDefinition;if(l)return Re.createElement(Kn,{flexDirection:"column"},Re.createElement(Kn,{flexDirection:"column"},Re.createElement(ys,{hideBreadCrumb:!0,filters:s}),Re.createElement(yc,{height:t,width:e})),Re.createElement(fs,{width:e,mode:n.mode,availableHints:[]}));if(c)return Re.createElement(Kn,{flexDirection:"column"},Re.createElement(Kn,{flexDirection:"column"},Re.createElement(ys,{hideBreadCrumb:!0,filters:s}),Re.createElement(hy,{height:t,width:e})),Re.createElement(fs,{width:e,mode:n.mode,availableHints:[]}));let m=Qe(n.breadCrumb??[],"BOARD");if(ce(m)){let p=m.value.id,f=q(p).length,g=3,v=Math.floor(e/g),x=Math.floor(e/Math.max(f,1));e=Math.min(x,v)*Math.max(f,g)}return Re.createElement(Kn,{flexDirection:"column"},Re.createElement(Oy,{autoSync:r}),Re.createElement(Kn,{flexDirection:"column"},Re.createElement(ys,{filters:s}),Re.createElement(Fy,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),Re.createElement(fs,{width:e,mode:n.mode,availableHints:n.availableHints}))}import vN from"readline";var Sa,Ea,an,bN=new Set([S.MoveCursorLeft,S.EraseInputWord,S.MoveCursorLeftOfWord,S.MoveCursorRight,S.MoveCursorRightOfWord,S.NavToPreviousContainer,S.NavToNextContainer,S.NavPreviousItem,S.NavNextItem,S.SetViewDense,S.SetViewWide,S.Confirm,S.Exit,S.Yank,S.InitCommandLine,S.InitCommandPalette,S.ExitCommandLine,S.CaptureInput,S.EraseInput,S.EraseInputWord,S.HideHelp,S.ViewHelp,S.SetViewDense,S.SetViewWide,S.GetLastCommandFromHistory,S.GetNextCommandFromHistory,S.AutoCompleteCommand]),xN=new Set([S.NavPreviousItem,S.NavNextItem,S.NavToPreviousContainer,S.NavToNextContainer,S.Confirm,S.Exit,S.InitCommandPalette,S.InitMove,S.MoveNextItem,S.MovePreviousItem,S.MoveToNextContainer,S.MoveToPreviousContainer,S.Delete,S.AddItem,S.EditTitle,S.EditDescription,S.ConfirmMove,S.Edit,S.ViewHelp,S.Yank]),_y=async e=>{if(e.ctrl&&e.name==="c")return O.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=h(),s=Pp(e,n);if(!s||r&&!bN.has(s)||o==="replay"&&n===b.DEFAULT&&xN.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(l){logger.error(l)}},IN=()=>async function(t,n){n.name!=="escape"&&(an&&(clearTimeout(an),an=void 0),await _y(n))},SN=()=>async function(t){if(t.length===1&&t[0]===27){an&&clearTimeout(an),an=setTimeout(()=>{_y({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),an=void 0},25);return}an&&(clearTimeout(an),an=void 0)};function Uy(){Sa&&process.stdin.removeListener("keypress",Sa),Ea&&process.stdin.removeListener("data",Ea),Sa=IN(),Ea=SN(),vN.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Ea),process.stdin.on("keypress",Sa)}async function jy(){try{let e=Ir({});if(d(e))return Bt(0,e.message);let t=yt();ce(t)&&ze(t.value);let n=xe(process.cwd()),r=ce(n)?await Di(n.value):_f();if(d(r))return r;let o=Nc();return d(o)?Bt(6,o.message):(Uy(),ce(n)&&Bi(n.value),u("Booted Epiq",void 0))}catch(e){return Bt(0,Tr(e))}}vf();var NN=`${jt.bold("Epiq CLI")}
|
|
91
91
|
|
|
92
92
|
${jt.dim("Boot in directory:")}
|
|
93
93
|
${jt.cyan("$ epiq")}
|
|
@@ -97,6 +97,6 @@ ${jt.dim("Launch GUI:")}
|
|
|
97
97
|
|
|
98
98
|
${jt.dim("Act as somebody other than the configured user:")}
|
|
99
99
|
${jt.cyan("$ epiq --as claude")}
|
|
100
|
-
`,
|
|
101
|
-
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await
|
|
102
|
-
${e.message}`)),process.exitCode=1)}export{
|
|
100
|
+
`,Ac=CN(NN,{importMeta:import.meta,version:rn,flags:{init:{type:"boolean",default:!1},as:{type:"string"}}}),Ca=Ac.input[0];Ca&&Ca!=="gui"&&(console.error(jt.red(`Unknown command: ${Ca}`)),process.exit(1));if(Ac.flags.as!==void 0){let e=Ma(Ac.flags.as,"--as");d(e)&&(console.error(jt.red(e.message)),process.exit(1))}var $y=process.stdout.columns||120,Hy=process.stdout.rows||20,Ra=null,AN=e=>{try{return Ra?(Ra.rerender(e),u("Rerendered app",void 0)):(Ra=EN(e),u("Rendered app",void 0))}catch(t){return a(`Unable to render app: ${Tr(t)}`)}},Nc=()=>AN(RN.createElement(Rc,{width:$y,height:Hy}));process.stdout.on("resize",()=>{if($y=process.stdout.columns||120,Hy=process.stdout.rows||20,!Ra)return;let e=Nc();d(e)&&logger.info(`[boot:resize] ${e.message}`)});if(Ca==="gui"){let e=await Kh({repoRoot:process.cwd()});d(e)&&(console.error(jt.red(`Failed to start Epiq GUI:
|
|
101
|
+
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await jy();d(e)&&(logger.info(e.message),console.error(jt.red(`Failed to boot Epiq:
|
|
102
|
+
${e.message}`)),process.exitCode=1)}export{Nc as renderApp};
|