epiq 1.8.4 → 1.8.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gui/main.js +628 -857
- package/dist/index.js +65 -65
- package/dist/mcp.js +1 -1
- 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{
|
|
5
|
-
`);if(n[n.length-1]===""&&n.pop(),t<=
|
|
2
|
+
import jt from"chalk";import{render as SN}from"ink";import EN from"meow";import CN from"react";import Wh from"chalk";import jy 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",bs="EPIQ_USER_ID",Ac="0123456789ABCDEFGHJKMNPQRSTVWXYZ",$y=26,Aa=80,Ta=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),xs=e=>e.trim().length>0&&e.length<=Aa,xr=e=>e.trim().toLowerCase(),Hy=e=>{let t=jy.createHash("sha256").update(`epiq:actor:${xr(e)}`).digest(),n="";for(let r=0;r<$y;r++)n+=Ac[(t[r]??0)%Ac.length];return n},Ir=(e,t=process.env)=>{let n=(t[dn]??"").trim(),r=(t[bs]??"").trim();return n?xs(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&&!Ta(r)?a(`${bs} must be 26 characters of Crockford base32`):r&&e.userId&&r===e.userId?a(`${bs} 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||Hy(n),userName:r?n:xr(n)}):a(`${dn} must be 1-${Aa} characters of text`):r?a(`${bs} is set without ${dn}`):u("No actor override",null)},wa=(e,t,n=process.env)=>{let r=e.trim();if(!xs(r))return a(`${t} must be 1-${Aa} 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 Ev 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 Wy}from"ulid";import{z as Is}from"zod";var Gy="__epiq_state__",Vy=Is.object({projectId:Is.string().min(1),stateBranch:Is.string().min(1),createdAt:Is.iso.datetime()}),Ss=()=>({projectId:Wy(),stateBranch:Gy,createdAt:new Date().toISOString()}),$t=e=>{let t=Es(e);if(!oo.existsSync(t))return a("Missing .epiq/project.json");try{let n=oo.readFileSync(t,"utf8"),r=JSON.parse(n),o=Vy.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)},Tc=({repoRoot:e,fileContents:t})=>{let n=Yn(e),r=Es(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 zy from"node:os";import Ky from"node:path";var At=".epiq-global",ln=()=>process.env.EPIQ_GLOBAL_DIR??Ky.join(zy.homedir(),At);var Ma=(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 Tt from"fs";import Ba from"path";import qy from"util";var wc=500,Fa=4*1024*1024,Pa=16*1024,Yy=50,La=0,Mc=()=>process.env.EPIQ_MCP==="true",Xy=()=>{let e=process.cwd(),t=Cs(e);return d(t)?Mc()?Ba.join(ln(),"epiq-mcp.log"):void 0:Ba.join(t.value,Je,"log","epiq.log")},Jy=(e,t)=>{let n=Tt.statSync(e).size;if(n<=t)return Tt.readFileSync(e,"utf8");let r=Tt.openSync(e,"r");try{let o=Buffer.alloc(t);Tt.readSync(r,o,0,t,n-t);let s=o.toString("utf8"),i=s.indexOf(`
|
|
4
|
+
`);return i===-1?"":s.slice(i+1)}finally{Tt.closeSync(r)}};function Qy(e){if(!Tt.existsSync(e))return;let t=Tt.statSync(e).size,n=Jy(e,Fa).split(`
|
|
5
|
+
`);if(n[n.length-1]===""&&n.pop(),t<=Fa&&n.length<=wc)return;let r=n.slice(-wc).join(`
|
|
6
6
|
`)+`
|
|
7
|
-
`;
|
|
8
|
-
`;try{
|
|
7
|
+
`;Tt.writeFileSync(e,r,"utf8")}var Zy=e=>{if(e.length<=Pa)return e;let t=e.length-Pa;return`${e.slice(0,Pa)} \u2026 [${t} more chars]`};function ka(e,t,n=!1){let r=Xy();if(!r)return;let o=Zy(qy.format(...t)),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
8
|
+
`;try{Tt.mkdirSync(Ba.dirname(r),{recursive:!0}),Tt.appendFileSync(r,l,"utf8"),La++,(La>=Yy||Tt.statSync(r).size>Fa)&&(La=0,Qy(r))}catch{}}var Da=()=>Mc()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",z={info(...e){let t=Da();(t==="info"||t==="debug")&&ka("[Info]",e,!1)},debug(...e){Da()==="debug"&&ka("[Debug]",e,!0)},error(...e){let t=Da();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;ka("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=z;import{spawn as Lc}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)},ft="origin";var Oa=1e4,ev=12e4,tv=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),nv=e=>{let t=e.find((n,r)=>!n.startsWith("-")&&e[r-1]!=="-c");return t&&tv.has(t)?ev:Oa},rv=()=>{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"},kc=rv(),Dc={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Bc=({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=Lc(kc,e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Dc}),s=!1,i="",l="",c=f=>{s||(s=!0,clearTimeout(p),r(f))},m=nv(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})=>
|
|
11
|
+
`)));return}c(u("Git command succeeded",{stdout:i,stderr:l,exitCode:g}))})}),j=({args:e,cwd:t})=>Bc({args:e,cwd:t,allowFail:!1}),je=({args:e,cwd:t})=>Bc({args:e,cwd:t,allowFail:!0}),Rs=(e,t)=>new Promise(n=>{if(e.length===0){n(u("No blobs to read",new Map));return}let r=Lc(kc,["cat-file","--batch"],{cwd:t,stdio:["pipe","pipe","pipe"],env:Dc}),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 ${Oa}ms`))},Oa);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
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())},
|
|
17
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(io).includes(r);return u("Checked worktree registration",o)}
|
|
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())},_a=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))},ov=async e=>{let t=await _a(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)},Ns=async e=>{let t=await ov(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",ft],cwd:e})).exitCode===0;return u(`Checked remote ${n}`,n)},Ua=async({repoRoot:e,branch:t})=>{let n=await je({args:["ls-remote","--heads",ft,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${ft}/${t}`):u("Checked remote branch",n.stdout.trim().length>0)},As=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)}},Fc=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)},ja=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)},Ts=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())},Oc=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())},_c=e=>e.includes("fetch first")||e.includes("non-fast-forward"),Uc=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},sv=3,iv=120,av=e=>new Promise(t=>setTimeout(t,e)),dv=async(e,t)=>{let n=await be.rebaseOnto({cwd:e,ref:t});for(let r=1;r<sv;r+=1){if(!d(n)||await Uc(e))return n;await av(iv),n=await be.rebaseOnto({cwd:e,ref:t})}return n},lv=async e=>{if(!await Uc(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)},Pc=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),cv=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),lo=async({cwd:e,branch:t})=>{let n=await lv(e);if(d(n))return a(n.message);let r=await Pc(e),o=await be.fetch({cwd:e,remote:ft,branch:t});if(d(o))return cv(o.message)?u("Remote branch missing, skipped pull",!1):a(`Failed to fetch ${t}
|
|
19
|
+
${o.message}`);let s=await dv(e,`${ft}/${t}`);if(d(s))return a(`Failed during rebase
|
|
20
|
+
${s.message}`);let i=await Pc(e),l=r!==null&&i!==null&&r!==i;return u(l?"Pulled with rebase":"Already up to date",l)},jc=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)},$c=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)},Hc=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 Wc=async e=>{let t=await Ts(e);return d(t)?a(t.message):u("Checked detached HEAD state",t.value==="HEAD")};var zc="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Kc=e=>rt.join(Je,mn,e),qc=()=>rt.join(Je,Wa),Yc=ln,ws=()=>rt.join(Yc(),"worktrees"),ue=({repoRoot:e})=>{let t=so(e);return d(t)?a(t.message):u("Resolved state branch root",rt.join(ws(),t.value))},uv=e=>rt.join(e,Je),Gc=e=>rt.join(uv(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))}},Ms=()=>{let e=Yc(),t=ws(),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
|
-
|
|
22
|
+
`+o.message):u("Ensured epiq storage",n)},Xc=e=>{Cn.existsSync(e)&&(z.debug("[sync] remove path",e),Cn.rmSync(e,{recursive:!0,force:!0}))};var mv=`*.jsonl merge=union
|
|
23
|
+
`,pv=`*~pending*.jsonl
|
|
24
|
+
`,$a=()=>rt.join(Je,mn,".gitattributes"),Ha=()=>rt.join(Je,mn,".gitignore"),Vc=(e,t)=>{try{Cn.readFileSync(e,"utf8")!==t&&Cn.writeFileSync(e,t)}catch{Cn.writeFileSync(e,t)}},Jc=(e,t)=>{for(let n of[Gc(e),Gc(t)]){let r=co(n);if(d(r))return a(r.message)}return Vc(rt.join(t,$a()),mv),Vc(rt.join(t,Ha()),pv),u("Ensured state branch",void 0)},Qc=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)},
|
|
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]===
|
|
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=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:
|
|
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)},wt=Ma(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)),SA=Ma(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 wA=process.env.IS_LOCAL==="true",Je=".epiq",mn="events",Wa="media",fv="project.json",Yn=e=>Wt.join(e,Je),Es=e=>Wt.join(Yn(e),fv),Mt=e=>Wt.join(Yn(e),mn),mo=e=>Wt.join(Yn(e),Wa),Zc=e=>Wt.join(e,Je),gv=e=>{let t=Wt.join(e,Je);return uo.existsSync(t)&&uo.statSync(t).isDirectory()},po=e=>{let t=Es(e);return uo.existsSync(t)&&uo.statSync(t).isFile()},Cs=e=>{let t=Wt.resolve(e);for(;;){if(gv(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}},Ga="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(Ga);t=n}},eu=e=>{let t=Mt(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 wt(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 hv,copyFileSync as yv,existsSync as Ps,mkdirSync as tu,readdirSync as nu,readFileSync as vv,renameSync as bv,rmSync as xv,statSync as ru,unlinkSync as Iv,writeFileSync as Sv}from"node:fs";import Er from"node:path";var Va=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",$e={writeToFile:(e,t)=>{try{let n=Er.dirname(e);Ps(n)||tu(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Sv(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return vv(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 Ps(e)&&ru(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await hv(e),!0}catch{return!1}},mkDir:e=>tu(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Er.parse(t);for(;;){let r=Er.join(t,e);try{if(Ps(r)&&ru(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=nu(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)?nu(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Iv(e)}catch(t){(!Va(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{xv(e,{recursive:!0,force:!0})}catch(t){(!Va(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Er.dirname(t)),!n?.overwrite&&Ps(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{bv(e,t)}catch(r){if(Va(r)&&r.code==="EXDEV"){yv(e,t),this.rmFile(e);return}throw r}}};var Cv={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},ou=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(),Rv="config.json",su=ln,za=()=>Ev.join(su(),Rv),Ka=()=>{try{return $e.mkDir(su()),u(`Ensured ~/${At} exists`,null)}catch{return a(`Unable to create ~/${At}`)}},Nv=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${At}/config.json JSON`)}let n=ou.safeParse(t??{});return n.success?u("Parsed config",n.data):a(`Invalid ~/${At}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Cr=()=>{let e=Ka();if(d(e))return a(e.message);let t=za(),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}):Nv(n)},iu=e=>{let t=Ka();if(d(t))return a(t.message);let n=ou.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=za();try{return $e.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
28
|
+
`),u("Config written",null)}catch{return a(`Unable to write ~/${At}/config.json`)}},gt=e=>{let t=Cr();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return iu(n)},ht=()=>{let e=za(),t=Ka();if(d(t))return a(`Unable to create ~/${At}`);if(!($e.readFile(e)!==null)){let x=iu(Cv);if(d(x))throw new Error(`Unable to create ~/${At}/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 ~/${At}/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 Av}from"react";var fo={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},qa=new Set,Tv=()=>{for(let e of qa)e()},ie=()=>fo,au=()=>Av(e=>(qa.add(e),()=>{qa.delete(e)}),()=>fo),ze=e=>(fo={...fo,...e},Tv(),fo);import{spawn as wv}from"node:child_process";import Ya from"node:process";var Xa=e=>{let t=Ya.platform==="darwin"?"open":Ya.platform==="win32"?"cmd":"xdg-open",n=Ya.platform==="win32"?["/c","start","",e]:[e];wv(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as $h}from"node:fs/promises";import Hn from"chalk";import Cg from"string-width";import{decodeTime as du}from"ulid";var Ls=1440*60*1e3,go=(e,t=Date.now())=>e>t+Ls?t:e,Re=e=>go(du(e)),Rr=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(Re(e)))}catch(t){return a("Decoding failed + "+t.message)}},Rn=e=>{if(!e?.id)return null;try{return du(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")},lu=["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 Ja(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 Pt=e=>e.context===V.SWIMLANE,Nr=e=>e.context===V.BOARD,yo=e=>e.context===V.COMMENT;import{useSyncExternalStore as uE}from"react";var b={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var cu=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",uu=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",mu=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",pu=(e,t)=>{if(uu(e,e.sequence))return S.MoveCursorLeftOfWord;if(mu(e,e.sequence))return S.MoveCursorRightOfWord;if(cu(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}},fu=(e,t)=>{if(uu(e,e.sequence))return S.MoveCursorLeftOfWord;if(mu(e,e.sequence))return S.MoveCursorRightOfWord;if(cu(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 gu 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)+"...",Mv=/\u001B\[[0-9;]*m/,Qa="\x1B[0m",Pv=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),Za=(e,t)=>{if(t<=0)return"";if(gu(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(Mv.test(l)){o+=l,i=l!==Qa&&l!=="\x1B[m";continue}for(let c of Pv(l)){let m=gu(c);if(s+m>r)return`${o}...${i?Qa:""}`;o+=c,s+=m}}return`${o}...${i?Qa:""}`},Ie=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),hu=e=>e.charAt(0).toUpperCase()+e.slice(1);var yu=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},vu=(e,t)=>t?e.get(t)??[]:[];var bu=new WeakMap,Lv=e=>{let t=bu.get(e);return t||(t=yu(e),bu.set(e,t)),t};var xu=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return vu(Lv(e),r).filter(s=>Bs(r,s)>=n)};var kv={hint:"",hints:[],overlap:0,remainder:""},Iu=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return kv;let o=xu({wordList:r,inputToMatch:e,overlapThreshold:1});return Dv(t,o)},Dv=(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 Ov}from"ulid";var vo=24n,Bv=vo*4n,Vt=(1n<<Bv)-1n,Fv=/^[0-9a-f]+$/;function Su(e){return!e||!Fv.test(e)?a(`Invalid hex rank: ${e}`):u("Converted rank to bigint",BigInt("0x"+e))}function yt(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 yt(Vt/2n,vo);let n=e?Su(e):u("Resolved lower bound",0n);if(d(n))return n;let r=t?Su(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"):yt(i,vo)}function Eu(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=yt(o,vo);if(d(s))return s;n.push(s.value)}return u("Resolved evenly spaced ranks",n)}var ed=(e,t)=>{let n=ae(e),r=Eu(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:Ov(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as Nb}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 _v=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[he,Os]=_v;var td=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),F=(e,t)=>({...td(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("; ")}`)},Cu=e=>{let t=C.getNode(e);if(!t||!P(t)||t.isDeleted)return null;let n=Au(t);return d(n)?n:null},Ru=e=>{if(!rd())return null;for(let t of e){let n=Cu(t);if(n)return n;let r=h().nodes[t]?.parentNodeId;if(!r)continue;let o=Cu(r);if(o)return o}return null},Uv=(e,t)=>{let n=C.getNode(e);n&&C.updateNode({...n,log:[...n.log??[],t]})},jv=e=>{let t=[e],n=h().nodes[e]?.parentNodeId;return n&&t.push(n),t},nd=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 jv(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[]}},$v=e=>{we(t=>({...t,eventLog:[...t.eventLog,e]}))},Hv=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?td("Invalid user ID format",e):u("Valid user",null)},ot=null,Wv=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]})),Ru([...e.virtualNodeIds])},Gv=(e,t)=>{let n=Hv(e);if(d(n))return n;let r=[...new Set(nd(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(rd()){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=>Uv(s,e)),$v(e));let o=Ru(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,Vv={"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 td(s.message,e);let i=C.createNode(o);return d(i)?F(i.message??"Failed to initialize workspace",e):Ja(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):Ja(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):Pt(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=Vv[e.action];if(!n)return a(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);if(!vt()&&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=Gv(e,t);return o||r}var Lt=e=>{let t=Nu(()=>{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=Wv(ot);if(o)return e.map(()=>o)}return r}finally{n&&(ot=null)}});return d(t)?e.map(()=>a(t.message)):t.value};import hd from"node:path";import{decodeTime as fb,monotonicFactory as gb}from"ulid";import{z as Qn}from"zod";var od=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 zv}from"ulid";var Us="~pending",sd=/~pending(-[0-9a-z]+)*$/i,wu=/-f(\d+)$/,Mu=e=>{let t=e.indexOf(".");return t===-1?`${e}${Us}`:e.slice(0,t)+Us+e.slice(t)},id=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},Pu=e=>{let[t,n]=id(e);return sd.test(t)?t.replace(sd,"")+n:null},Lu=e=>e.replace(sd,""),js=e=>e.endsWith(".jsonl")&&Pu(e)!==null,ku=e=>{let[t]=id(e),n=wu.exec(t);return n&&js(e)?Number(n[1]):null},Kv=e=>Mu(e).replace(Us,`${Us}-${zv().toLowerCase()}`),qv=(e,t)=>{let[n,r]=id(e);return`${n.replace(wu,"")}-f${t}${r}`},Du=(e,t)=>Jn.join(Mt(e),Mu(t)),Yv=(e,t)=>Math.max(0,Ae.statSync(e).size-(ku(t)??0)),Bu=e=>{let t=Mt(e);try{return Ae.existsSync(t)?Ae.readdirSync(t).filter(js).some(n=>Yv(Jn.join(t,n),n)>0):!1}catch{return!0}},Xv=3,Fu=(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>=Xv)return}},Jv=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,Tu=(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(Jv(e)?"":`
|
|
29
|
+
`),o,Buffer.from(o[o.length-1]===_s?"":`
|
|
30
|
+
`)]));let s=0;for(let i of o)i===_s&&s++;return o[o.length-1]!==_s&&s++,{bytes:r,lines:s}},$s=(e,t)=>{let n=Mt(e);if(!Ae.existsSync(n))return u("No events directory",0);try{let r=Ae.readdirSync(n).filter(i=>Pu(i)===t),o=Jn.join(n,t),s=0;for(let i of r){let l=ku(i);if(l!==null){let f=Jn.join(n,i),g=Ae.readFileSync(f).subarray(l);s+=Tu(o,g,!0).lines,Ae.rmSync(f,{force:!0});continue}let c=/~pending-/i.test(i)?i:Kv(t),m=Jn.join(n,c);c!==i&&Ae.renameSync(Jn.join(n,i),m);let p=Tu(o,Ae.readFileSync(m));s+=p.lines,Ae.renameSync(m,Jn.join(n,qv(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 Gu from"node:fs";import Gs from"node:path";import{decodeTime as nb}from"ulid";import{z as md}from"zod";import ad from"node:fs";import Qv from"node:path";var So=e=>e?.code==="ENOENT",dd=3,ld=e=>ad.readdirSync(e).filter(t=>t.endsWith(".jsonl")).sort(),zt=e=>{let t=Mt(e);for(let n=1;;n++){if(!ad.existsSync(t))return"none";let r=[],o=!1;for(let s of ld(t))try{let{size:i,mtimeMs:l}=ad.statSync(Qv.join(t,s));r.push(`${s}:${i}:${l}`)}catch(i){if(!So(i))throw i;if(n<dd){o=!0;break}}if(!o)return r.join("|")}},Ou=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),cd=(e,t,n)=>{let r=Ou(t),o=zt(e),s=Ou(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,_u=e=>Tn&&Tn.root===e?Tn.signature:null,Uu=(e,t)=>{Tn={root:e,signature:t}},ju=(e,t)=>{if(!Tn||Tn.root!==e)return;let n=cd(e,Tn.signature,t);Tn=n===null?null:{root:e,signature:n}};var Zv=["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 eb=new Set(Zv),$u=e=>eb.has(e),Hu=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(),Hs=G.looseObject({id:H}),ud=G.looseObject({id:H,name:kt,parent:H,rank:wn}),tb={"init.workspace":G.looseObject({id:H,name:kt,rank:wn}),"add.workspace":G.looseObject({id:H,name:kt,rank:wn}),"add.board":ud,"add.swimlane":ud,"add.issue":ud,"add.field":G.looseObject({id:H,name:kt,parent:H,rank:wn}),"edit.title":G.looseObject({id:H,name:kt}),"delete.node":Hs,"lock.node":Hs,"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":Hs,"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":Hs,"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)})},Wu=(e,t)=>{let r=tb[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 rb=md.object({userId:md.string().min(1).default("unknown"),userName:md.string().min(1).default("unknown")}),Ws=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},ob=/^[0-9a-hjkmnp-tv-z]{26}$/i,sb=e=>ob.test(e)?e.toUpperCase():e,ib=e=>{let t=Gs.basename(e,".jsonl"),n=t.indexOf("."),r=Lu(n===-1?t:t.slice(0,n)),o=n===-1?void 0:t.slice(n+1),s=rb.safeParse({userId:sb(r),userName:o});return s.success?u("Parsed event file actor",s.data):a(`Invalid event file name ${Gs.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},ab=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])},db=(e,t)=>t in e,lb=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),cb=e=>{let{userId:t,userName:n,...r}=e,o=ab(r);if(d(o))return a(o.message);let s=o.value,i=e.id?.[0];return i?db(r,s)?u("Decoded persisted event",lb({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")},fd=(e,t)=>{let n=[],r=new Map,o=new Map;for(let s of e){if(!Yu(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:Ws(s)});continue}let i=cb(s);if(d(i)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:i.message,targetNodeId:Ws(s)});continue}let l=i.value.action;if(!$u(l)){r.set(l,(r.get(l)??0)+1),t?.push({eventId:s.id[0],reason:"unknown-action",detail:l,targetNodeId:Ws(s)});continue}let c=Wu(l,i.value.payload);if(d(c)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:c.message,targetNodeId:Ws(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)},ub=(e,t)=>{let n=ib(e);if(d(n))return a(n.message);let r;try{r=Gu.readFileSync(e,"utf8")}catch(l){if(So(l))return u("Event file missing",null);throw l}let o=[],s=Gs.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=qu(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=Mt(e),r=zt(e);if(!Gu.existsSync(n))return u("No events found",[]);let o=[],s=[];for(let l=1;;l++){o=[],s=[];let c=!1;for(let m of ld(n)){let p=ub(Gs.join(n,m),s);if(d(p))return a(p.message);if(p.value===null){if(l<dd){c=!0;break}continue}o.push(...p.value)}if(!c)break}t?.push(...s);let i=mb(o);return yn={root:e,signature:r,edge:i.at(-1)?.id?.[0]??null},u("All events loaded",i)}function bt(e){let t=[],n=Eo(e,t);if(d(n))return a(n.message);let r=fd(n.value,t);return d(r)?a(r.message):u("Loaded merged events",{events:r.value,unreadable:t})}function gd(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=bt(e);return d(t)?a(t.message):u("Loaded merged events",t.value.events)}function Vs(e,t){let n=Eo(e);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=pb(n.value,t),s=fd(r);if(d(s))return a(s.message);let i=fd(o);return d(i)?a(i.message):u("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:i.value})}var yn=null;function Vu(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 zu(e,t,n){if(!yn||yn.root!==e)return;let r=cd(e,yn.signature,t);yn=r===null?null:{root:e,signature:r,edge:n}}var pd=(e,t)=>{let n=e.id[0].localeCompare(t.id[0]);return n!==0?n:JSON.stringify(e).localeCompare(JSON.stringify(t))},mb=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(pd);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(pd);for(let m of l)s(m);let c=e.filter(m=>!o.has(m.id[0])).sort(pd);for(let m of c)s(m);return r},Ku=e=>Rr(e.map(t=>{try{return nb(t.id[0])}catch{return null}}));function zs(e){let t=Eo(e);if(d(t))return a(t.message);let n=Ku(t.value);return u("Loaded effective event times",new Map(t.value.map((r,o)=>[r.id[0],n[o]??null])))}var pb=(e,t)=>{let n=new Set,r=[],o=[],s=Ku(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 Ju=1,Xu=gb(),hb=0xffffffffffff,yb=Ls,vb=e=>{let t=Date.now(),n;try{n=fb(e)}catch{return t}return n>=hb?t:n>t+yb?(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)},Qu=Qn.tuple([Qn.string().min(1),Qn.string().min(1).nullable()]),bb=Qn.looseObject({v:Qn.literal(Ju),id:Qu}),xb=Qn.looseObject({v:Qn.number().int().positive(),id:Qu}),qu=e=>{let t=xb.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(", ")}`)},Ib=[1];var Sb=new Set(Ib),Yu=e=>Sb.has(e),Eb=e=>{let t=bb.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(", ")}`)},Z=()=>{let{userName:e,userId:t}=ie();return e?t?Ta(t)?xs(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})=>`${od(e)}.${od(t)}.jsonl`,Cb=(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=hd.join(Mt(e),r);return u("Successfully resolved event log path",s)},Rb=(e,t)=>{let n={[e.action]:e.payload,v:Ju,id:t};return Eb(n)};function yd(e,t){let n;if(t&&t.current!==void 0)n=t.current;else{let o=Vu(e);if(d(o))return a(o.message);n=o.value}let r=n?Xu(vb(n)):Xu();return u("Minted event id",[r,n])}function Ks({event:e,rootDir:t,edge:n,id:r}){try{let o=eu(t);if(d(o))return o;let s=Cb(t,{userId:e.userId,userName:e.userName});if(d(s))return s;let i=u("Resolved pending event log path",Du(t,hd.basename(s.value))),l=r?u("Minted event id",r):yd(t,n);if(d(l))return a(l.message);let[c,m]=l.value,p=Rb(Hu(e),[c,m]);if(d(p))return a(p.message);Fu(i.value,`${JSON.stringify(p.value)}
|
|
32
|
+
`),n&&(n.current=c);let f=hd.basename(i.value);return zu(t,f,c),ju(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 Zu(e,t,n){let r=yd(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=Ks({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=Ab(e[0],t,n);if(d(r))return r;let o=e.map(i=>Zu(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 Ab=(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:Nb(),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=Zu(o,t,n);return d(s)?a(s.message):u("Contributor name recorded",void 0)};var er=e=>e.trim().toLocaleLowerCase(),vd=(e,t)=>er(e).includes(er(t));var Tb=e=>{let{tags:t}=h();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},wb=e=>{let{contributors:t}=h();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},em=null,tm=new Map,Mb=()=>{let e=h().eventLog??[];if(e===em)return tm;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 em=e,tm=t,t},Pb=e=>{let{contributors:t}=h(),n=Mb().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},nm=(e,t)=>{let n=er(t.value);if(!n)return!0;switch(t.target){case"title":return vd(e.title??"",n);case"description":return vd(e.props.description??"",n);case"tag":return Tb(e).map(er).some(o=>o.includes(n));case"assignee":return wb(e).map(er).some(o=>o.includes(n));case"actor":return Pb(e).map(er).some(o=>o.includes(n));case"ref":return Fs(e.id,t.value);default:return!0}};var rm=(e,t)=>e.rank.localeCompare(t.rank),Lb=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,om=(e,t)=>Object.values(e).filter(n=>Lb(n,t)).sort(rm),sm=(e,t)=>{let n={};for(let r of Object.values(e)){if(P(r)&&t.length>0&&!t.every(s=>nm(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(rm);return n};var im=e=>qs(ae(e),{at:"end"}),qs=(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=am(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=am(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(!lm()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return om(t.nodes,e)},am=(e,t)=>e.findIndex(n=>n.id===t),dm=(e,t,n={at:"end"})=>qs(ae(t).filter(r=>r.id!==e),n),Kt=(e,t,n,r,o)=>{let s=dm(t,e,n);if(d(s))return s;if(!s.value.needsRebalance)return u("Resolved rank",s.value.rank);let i=ed(e,r);if(d(i))return i;let l=B([i.value],o);if(d(l))return l;let c=dm(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=im(e);if(d(r))return r;if(!r.value.needsRebalance)return u("Resolved rank",r.value.rank);let o=ed(e,t);if(d(o))return o;let s=B([o.value],n);if(d(s))return s;let i=im(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:()=>cm(1),navigateToPreviousItem:()=>cm(-1),navigateToNextContainer:()=>um(1),navigateToPreviousContainer:()=>um(-1),navigate:({contextNode:e,selectedIndex:t})=>{N({contextNodeId:e.id,selectedIndex:t})}},cm=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})},um=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 pm=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),fm=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=h();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},kb=e=>{let t=h().nodes[e];return!!t&&!t.isDeleted&&ut(t)&&t.childRenderAxis==="vertical"},Ys=(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:pm(t,o.length)}),!0},gm=e=>{let{nodes:t}=h(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Ys(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):gm(o.id)},mm=e=>{let{nodes:t}=h(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),gm(n))return!0;n=t[n]?.parentNodeId}return!1},Db=e=>{if(!e)return!1;let t=h().nodes[e];return!!t&&!t.isDeleted},hm=e=>{let{nodes:t,rootNodeId:n}=h();if(kb(e.contextNodeId)&&Ys(e.contextNodeId,e.selectedIndex))return u("Restored navigation inside text container",null);if(Db(e.selectedNodeId)&&e.selectedNodeId&&mm(e.selectedNodeId))return u("Restored navigation to selected node or ancestor",null);if(Ys(e.contextNodeId,e.selectedIndex))return u("Restored navigation to previous container",null);if(e.parentNodeId&&Ys(e.parentNodeId,e.selectedIndex))return u("Restored navigation to previous parent",null);if(mm(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:pm(e.selectedIndex,o.length)}),u("Restored navigation to root",null)};import{monotonicFactory as Bb,ulid as qt}from"ulid";var Co=Bb();function Fb(){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 Ob(){let e=Fb();return d(e)?e:O.navigate(e.value)}function ym({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: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 _b=()=>{let e=et();if(d(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},Ub=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),Ob(),N({hasProjectDefinition:!0}),Ub(t),u("State booted successfully",null))}import{WebSocket as jb}from"ws";var Xs=new Set,vm=e=>{Xs.add(e),e.on("close",()=>{Xs.delete(e)}),e.on("error",()=>{Xs.delete(e)})},tr=e=>{let t=JSON.stringify(e);for(let n of Xs)n.readyState===jb.OPEN&&n.send(t)};var Js=e=>{vt()&&(N({syncStatus:e}),tr({type:"sync-status",payload:e}))},Ar=(e="Syncing...")=>{Js({status:"syncing",msg:e})},nr=(e="Synced")=>{Js({status:"synced",msg:e})},bd=e=>{Js({status:"failed",msg:e})},Qs=e=>{Js({status:"offline",msg:e})},Te=e=>(bd(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 nx 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),bm=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)}`)}},xm=e=>Ro.join(e,Je,mn),Im=e=>{let t=xm(e),n=new Map;try{if(!Yt.existsSync(t))return n;for(let r of Yt.readdirSync(t))if(r.endsWith(".jsonl")&&!js(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},$b=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},Sm=(e,t)=>{if(t.size===0)return[];let n=xm(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($b);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},Hb=(e,t)=>{let n=new Set(wr(t));return wr(e).filter(r=>!n.has(r))},Wb=(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
|
+
`),Em=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=Hb(r.stdout,n);return o.length>0?a(Wb(t,o,wr(r.stdout).length)):u("Event log only grew",void 0)};var Gb="[epiq:init-repo]",Rm=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",Gb],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)},Cm=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Vb=async e=>{let t=await Ts(e);if(d(t))return a(t.message);let n=await Oc(e);return d(n)?a(n.message):u("Built sync commit message",`[sync|branch:${Cm(t.value)}:sha:${Cm(n.value)}]`)},xd=async({repoRoot:e,stateBranchName:t})=>{z.info(`Creating ${t}`);let n=await j({args:["commit-tree",zc,"-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)},Id=async({repoRoot:e,stateBranchName:t})=>{let n=await As({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
|
-
`+r.message);let o=r.value,s=o?await
|
|
46
|
-
`+s.message);let i=s.value;if(o&&i){let l=await be.fetch({cwd:e,remote:
|
|
47
|
-
${l.message}`)}if(i){let l=await j({args:["branch","--track",t,`${
|
|
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(No.join(t,".git"))){let s=
|
|
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
|
|
45
|
+
`+r.message);let o=r.value,s=o?await Ua({repoRoot:e,branch:t}):u("No remote, no remote state branch",!1);if(d(s))return a(`Ensure local state branch failed
|
|
46
|
+
`+s.message);let i=s.value;if(o&&i){let l=await be.fetch({cwd:e,remote:ft,branch:t});if(d(l))return a(`Failed to fetch ${t} from remote
|
|
47
|
+
${l.message}`)}if(i){let l=await j({args:["branch","--track",t,`${ft}/${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 xd({repoRoot:e,stateBranchName:t})},zb=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)},Kb=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=bm(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"),Xc(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 zb({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 $c(s);if(d(c))return a(c.message);if(c.value||Bu(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)},
|
|
58
|
-
${l.message}`);let c=await be.setUpstream({cwd:t,branch:s,upstream:`${
|
|
59
|
-
${c.message}`):u("Configured state branch upstream",!0)},
|
|
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})},Ao=async({repoRoot:e,stateBranchRoot:t})=>{let n=await
|
|
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=
|
|
67
|
-
`).map(
|
|
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}
|
|
55
|
+
${c.message}`)}let i=await Fc({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 Kb({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},qb=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Ts(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)},Yb=async({repoRoot:e,stateBranchRoot:t})=>{let n=await ja(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 Ua({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:ft,branch:s});if(d(l))return a(`Failed to fetch ${s}
|
|
58
|
+
${l.message}`);let c=await be.setUpstream({cwd:t,branch:s,upstream:`${ft}/${s}`});return d(c)?a(`Failed to set state branch upstream
|
|
59
|
+
${c.message}`):u("Configured state branch upstream",!0)},Zs=async({stateBranchRoot:e,eventFileName:t})=>{let n=Kc(t),r=No.join(e,n);if(!vn.existsSync(r))return u("No event file to stage",null);let o=await Em({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)},Nm=async({stateBranchRoot:e})=>{let t=qc(),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)},Am=async({stateBranchRoot:e})=>{let t=[$a(),Ha()].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)},Tm=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let r=await Vb(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 ja(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:ft,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)},wm=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 Id({repoRoot:e,stateBranchName:s}),await rr({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await qb({stateBranchRoot:t,stateBranchName:s}),await Qc(t),n?await Yb({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 ei from"node:fs";import Ed from"node:os";import Xb from"node:path";var Jb="epiq-sync.lock",Mm=600*1e3,Qb=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}},Zb=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},ex=e=>e&&(e.hostname!==Ed.hostname()||Zb(e.pid))?Date.now()-e.startedAt>Mm:!0,Lm=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,Sd=e=>{try{return Qb(ei.readFileSync(e,"utf8"))}catch{return null}},Pm=(e,t)=>{let n={pid:process.pid,hostname:Ed.hostname(),startedAt:Date.now(),operation:t};try{return ei.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},tx=async({worktreeRoot:e,operation:t})=>{let n=await _a(e);if(d(n))return a(n.message);let r=Xb.join(n.value,Jb),o=()=>{try{let l=Sd(r);l&&l.pid===process.pid&&ei.rmSync(r)}catch{}};if(Pm(r,t))return u("Acquired sync lock",{acquired:!0,release:o});let s=Sd(r);if(!ex(s))return u("Sync lock is held",{acquired:!1,heldBy:s});z.info(`Breaking an abandoned sync lock: ${s?Lm(s):"unreadable lock file"}`);try{ei.rmSync(r,{force:!0})}catch{}if(Pm(r,t))return u("Acquired sync lock after breaking a stale one",{acquired:!0,release:o});let i=Sd(r);return u("Sync lock taken by another process",{acquired:!1,heldBy:i??{pid:-1,hostname:Ed.hostname(),startedAt:Date.now(),operation:"unknown"}})},ti=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await tx({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 ${Lm(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 rx=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=oe("getRepoRootDir",await wt(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 wm({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",Jc(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}))},ox=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 Zs({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=oe("stageStateBranchMediaFiles",await Nm({stateBranchRoot:t}));if(d(o))return a(o.message);let s=oe("stageStateBranchEventConfig",await Am({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 Hc(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 Tm({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}))},Cd=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return Qs(n),u(n,{...e,pulled:!1,pushed:!1,offline:!0})},km=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 rx({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 Wc(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 ox({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 Cd({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)?Cd({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:c,bootstrapped:s}):Te(R.message);m=R.value;let A=oe("isAheadOfUpstream",await jc(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)&&_c(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)?Cd({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})},Rd=async(e,t)=>{let n=Im(e);try{return await t()}finally{let r=Sm(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},ni=async e=>{let t=e.cwd??process.cwd(),n=await wt(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(!nx.existsSync(o))return km(e);let s=await ti({worktreeRoot:o,operation:"sync",fn:()=>Rd(o,()=>km(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,ri=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=sx();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}},sx=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:h().mode,syncStatus:h().syncStatus});let e=Dm();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",Z());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:d(t)?t.message:"Missing actor id"}),a("Unable to resolve event log path");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 ni({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=Nd(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))},Nd=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=oe("loadMergedEvents",bt(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=Dm();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:h().mode,message:n.message,syncStatus:h().syncStatus}),n;let r=fm(),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",hm(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)},Dm=()=>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,Bm=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Mr?null:t},Fm=0,Ad,Td=!1,To=!1,wd=()=>{if(Td)return!0;let e=et();return d(e)?!1:e.value.syncStatus.status==="syncing"},ix=()=>{let e=ie().autoSyncIntervalMs??1e4,t=Date.now()-Fm;return Math.max(0,e-t)},Om=()=>{Ad||(Ad=setTimeout(async()=>{if(Ad=void 0,!!vt()){if(wd()){To=!0;return}To=!1,await ax()}},ix()))},ax=async()=>{if(h().readOnly||h().timeMode==="peek"||h().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!vt())return a("Cannot auto-sync before state is initialized");if(wd())return To=!0,a("Sync already in progress");Td=!0,Fm=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await ri()}finally{Td=!1,To&&Om()}},oi=()=>{vt()&&(To=!0,!wd()&&Om())};import wo from"node:fs";import Mo from"node:path";import{z as Pr}from"zod";var si="recent-projects.json",dx=20,lx=Pr.object({projectId:Pr.string().min(1),root:Pr.string().min(1),lastOpenedAt:Pr.number().finite()}),cx=Pr.object({projects:Pr.array(lx)}),Um=()=>Mo.join(ln(),si),Lr=e=>Mo.basename(e)||e,_m=e=>{let t=Mo.resolve(e);try{return wo.realpathSync(t)}catch{return t}},jm=(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},Hm=()=>{let e=Um();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 ${si}: ${r instanceof Error?r.message:String(r)}`)}let n=cx.safeParse(t);return n.success?u("Read recent projects",n.data.projects):a(`Invalid ${si} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},ux=e=>{let t=Um();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 ${si}: ${n instanceof Error?n.message:String(n)}`)}return u("Recorded recent project",e)},bn=({exclude:e}={})=>{let t=Hm();if(d(t))return t;let n=e===void 0?null:_m(e);return u("Listed recent projects",t.value.filter(r=>n===null||_m(r.root)!==n).filter($m).sort(jm))},ii=({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=Hm(),i=d(s)?[]:s.value,l=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(c=>c.projectId!==o&&c.root!==n)].filter($m).sort(jm).slice(0,dx);return ux(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}},Wm=()=>{let e=xe(process.cwd());if(d(e))return!1;let t=$t(e.value);return ce(t)},Gm=e=>e===!0?"on":e===!1?"off":null,Vm=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 mx=e=>e.props.tags??[],px=e=>e.props.assignees??[],kn=e=>mx(e).map(t=>C.getTag(t)).filter(t=>!!t),Dn=e=>px(e).map(t=>C.getContributor(t)).filter(t=>!!t),ai=()=>{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))},di=()=>{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 fx=/^(\d+)(h|d|w|mo|y)$/,gx=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,hx=({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},yx=(e,t=new Date)=>{let n=e.match(fx);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}},vx=e=>{let t=e.match(gx);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 hx({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 yx(t)??vx(t)};var zm=/^(\d+)(s|m)?$/,li=e=>{let t=e.trim().toLowerCase().match(zm);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},ci=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&zm.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Km=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,bx=[{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}],Md=(e=bx)=>{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 xx=["BOARD","TICKET","SWIMLANE","COMMENT"],ye={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},mt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Me={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},Ix=[ye.EDITOR,ye.VIEW,ye.USERNAME,ye.AUTOSYNC,ye.SYNC_DEBOUNCE_MS,ye.ATTACHMENT_MAX_KB,ye.LOG_LEVEL],Sx=(e=h().selectedNode?.context)=>{switch(e){case"TICKET":return[mt.TITLE,mt.DESCRIPTION];case"BOARD":case"SWIMLANE":return[mt.TITLE];case"COMMENT":return[mt.COMMENT];default:return[]}},Ld=[String(Mr),"5000","15000","30000","60000"],kd=["250","500","1000"],Xm=["10s","20s","30s","45s"],sr=[E.EXIT,E.SYNC,E.HELP,E.EXPORT,E.CONFIG,E.YANK],ui=[E.NEW,E.EDIT,E.DELETE,E.MOVE],Pd=[E.TAG,E.UNTAG,E.ASSIGN,E.UNASSIGN,E.CLOSE_ISSUE,E.RE_OPEN_ISSUE,E.EDIT,E.COMMENT],qm=[E.FILTER,E.PEEK,E.REPLAY],Ex={WORKSPACE:[...sr,...ui],BOARD:[...qm,...sr,...ui],SWIMLANE:[...qm,...sr,...ui],TICKET:[...sr,...ui,...Pd],FIELD:[...sr,...Pd],FIELD_LIST:[...sr,...Pd],TEXT:[...sr],COMMENT:[E.EDIT,E.DELETE,E.YANK]},Cx=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Po=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&P(n)),Ym=e=>e.parentNodeId===he,Rx=({selectedNode:e,breadCrumb:t})=>{let n=Sx(e?.context);return Po({breadCrumb:t,selectedNode:e})?n.includes(mt.DESCRIPTION)?n:[...n,mt.DESCRIPTION]:n},Nx=({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]:[]},Dd=()=>{let e=bn({exclude:process.cwd()});return d(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},Ax=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Ln();if(!r)return[E.HELP,E.CONFIG];if(!Wm())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&&xx.includes(o),i=[...new Set([...n,e].map(c=>c?.context).flatMap(c=>c?Ex[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&&Ym(l)):c===E.CLOSE_ISSUE?!!(l&&!Ym(l)):!0)},Ne=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=h())=>{let s=t.context??"WORKSPACE";return{[E.NONE]:Ax({breadCrumb:o,readOnly:r,selectedNode:n}),[E.EXIT]:["confirm"],[E.EXPORT]:[],[E.SYNC]:[],[E.INIT]:[],[E.OPEN]:e===E.OPEN?Dd():[],[E.HELP]:[],[E.PEEK]:[...Md(),"now","prev","next"],[E.REPLAY]:[...Md()],[E.EDIT]:Rx({selectedNode:n,breadCrumb:o}),[E.YANK]:Nx({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]:[...ai()?.value?.map(({name:l})=>l)??[]],[E.UNASSIGN]:[...di()?.value?.map(({name:l})=>l)??[]],[E.ASSIGN]:C.getExistingAssignees(),[E.NEW]:Cx(s),[E.CONFIG]:[...Ix]}[e]??[]};import fp from"chalk";var Jm=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import Lx from"zod";import Tx from"node:crypto";import Lo from"node:fs";import ep from"node:path";var Qm="/media/",Zm=e=>`${Qm}${e}`,Bd=(e,t)=>`})`;var Jt=500,wx=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,ir=(e,t)=>`${e}.${t}`,Mx=e=>wx.test(e),tp=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: ${lu.join(", ")}`),np=e=>Tx.createHash("sha256").update(e).digest("hex"),Px=(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=tp(e);return d(n)?n:u("Validated attachment data",{hash:np(e),ext:n.value,bytes:e.length})},rp=(e,t,n=Jt)=>{let r=Px(t,n);if(d(r))return r;let o=mo(e),s=ep.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)},op=(e,t,n=Jt)=>{if(!Mx(t))return a("Invalid attachment file name");let r=ep.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(np(o)!==s)return a("Attachment blob does not match its content hash");let l=tp(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,sp=()=>{let e=ee().commandMeta.inputString,t=Lx.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=gt({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 Od={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ip=(e,t,n)=>Math.max(t,Math.min(n,e)),Fd=(e,t,n)=>e+(t-e)*n,ap=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},kx=e=>e.toLowerCase().trim(),Dx=(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)]},dp=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var Bx=(e,t,n)=>{let r=ip(n,0,1);return[Math.round(Fd(e[0],t[0],r)),Math.round(Fd(e[1],t[1],r)),Math.round(Fd(e[2],t[2],r))]};var Fx=(e,t,n)=>Bx(e,t,n),Bo=e=>{let t=ap(e)%360,n=Dx(t,Od.stringColor.saturation,Od.stringColor.lightness);return dp(n)},de=(e,t=kr)=>{let n=kx(e??"");return n&&t[n]?t[n]:Bo(n)};var lp=e=>{let t=Od.gradient.stops,n=ip(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 Fx(t[s],t[s+1],i)},mi=e=>dp(lp(e)),pi=e=>ap(e.toLowerCase().trim())/4294967295,cp=e=>{let t=pi(e);return lp(t)},Ox=e=>{let[t,n,r]=cp(e);return{normal:o=>Dr.bgRgb(t,n,r).black(o),cursor:o=>Dr.bgRgb(t,n,r).white.bold(o)}},_d=e=>{let[t,n,r]=cp(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)}},fi=e=>Ox(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 Ux="0123456789ABCDEFGHJKMNPQRSTVWXYZ",jx=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+=Ux[Number(n>>s&31n)]}return r},De=(e,t)=>jx(`${e}:virtual:${t}`);import up from"chalk";var me=e=>up.dim(e),Be=e=>up.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)=>pi(f)-pi(g)).slice(0,r).map(f=>fi(f)).join(" ");return p?`${me(e)}${p}${me(n)}`:""};var Qt={None:"none",Invalid:"invalid",Valid:"valid"};var $x=["BOARD","TICKET","SWIMLANE"],mp=()=>{let e=h().selectedNode;if(!e?.context)return W({message:me("Missing target context")});if($x.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,pp=(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`)}):Km({date:e,horizonDate:r.value})?null:W({message:Be(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},gi=e=>` ${fp.hex("#000").bgHex(de(e))(` ${e} `)} `,Ud=({modifier:e})=>{let t="confirm";return e===t?J(le):W({message:Fr(e)?me("if you are certain, enter ")+fi(t):"",completionWordList:[t]})},Hx=({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),Wx=({modifier:e,inputString:t})=>{let n=Dd();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})},Gx=({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=[...Jm];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 ")+fp.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=Gm(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:kd,minLengthForHints:0,inputString:t});return W({message:Be(`provide a size cap in KB (${ko}-${Do}). current: ${r??Jt} KB.`)+s,completionWordList:kd})}return J(le)}case ye.SYNC_DEBOUNCE_MS:{let r=ie().autoSyncIntervalMs,o=Bm(t);if(!t.trim()||o===null||o<Mr){let s=He({prefix:" examples: ",wordList:Ld,minLengthForHints:0,inputString:t});return W({message:Be(`provide duration above ${Mr}ms. current duration: ${r}ms.`)+s,completionWordList:Ld})}return J(le)}default:return W({message:Be("Unknown config option"),completionWordList:n})}},Vx=({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 mt.COMMENT:return t.trim()?J(le):W({message:me("write a comment...")});case mt.TITLE:return J(le);case mt.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})}},zx=({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")})},Kx={[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=pp(o,"peek");return s||J(le)},[E.REPLAY]:e=>{let{dateInput:t,durationInput:n}=ci(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=pp(o,"replay");return s||(n&&li(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?Xm:[]))},[E.EXIT]:()=>J(le+me(" and exit the application")),[E.INIT]:()=>J(le),[E.OPEN]:Wx,[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=>Hx({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]:Vx,[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]:Gx,[E.YANK]:zx,[E.DELETE]:e=>{let t=mp();return t.validity==="invalid"?t:Ud(e)},[E.CLOSE_ISSUE]:e=>Ud(e),[E.RE_OPEN_ISSUE]:e=>Ud(e),[E.MOVE]:e=>{let t=mp();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(gi).join("");return Br({hint:n.length?me("create tag or reuse:")+n+me(""):me("create tag ...")})(e)},[E.UNTAG]:e=>{let t=ai();if(d(t))return W({message:Be("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(gi).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(gi).slice(0,10);return Br({hint:me("assignees... ")+t.join("")})(e)},[E.UNASSIGN]:e=>{let t=di();if(d(t))return W({message:Be("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(gi).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)},gp=Object.fromEntries(Object.entries(Kx).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var hi=["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 qx=3,Yx=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"]),Xx=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},Jx=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=qx&&!Yx.has(t)&&!/^\d+$/.test(t)),Qx=e=>{let t=new Map;for(let s of Xx(e))for(let i of Jx(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=hi.filter(s=>!r.has(s));return[...n,...o]},hp=hi,yp=-1,vp=()=>{let e=et();if(d(e))return hi;let t=e.value,n=t.eventLog.length;return n!==yp&&(hp=Qx(t),yp=n),hp};var bp=e=>Object.values(E).includes(e),xp=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:l,completionWordList:c}=gp[n].validate(n,r,s),m=n!==E.PEEK&&n!==E.REPLAY,p=o==="command"||o==="modifier"?Ne(n):m?vp():[],{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?Iu(e,v):{hint:"",hints:[],remainder:"",overlap:0}}};var Ip=e=>{let t=e.trimStart(),n=eI(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=tI(e),l=bp(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=Zx(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}},Zx=(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},eI=e=>e.trim()?e.trim().split(/\s+/):[],tI=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as nI}from"react";var Or=e=>e===jd||e===":",jd=" ",qe={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Qt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},$d=new Set,Sp=()=>{for(let e of $d)e()},Hd=e=>($d.add(e),()=>$d.delete(e)),Zt=e=>{let n=e(qe),r=Ip(n.value),o=n.cursorPosition===n.value.length;qe={...n,commandMeta:xp(r,o)},Sp()},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,Sp(),u(e,null)},Wd=e=>{Zt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Gd=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}})},Ep=()=>{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}})},Cp=()=>{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}})},yi=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}})},Rp=()=>{Zt(e=>({...e,commandIsPending:!0}))},Q=e=>{Zt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Np=({addToHistory:e=!0})=>{Zt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Ap=()=>{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}})},Tp=()=>{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}})},ee=()=>qe,wp=()=>nI(Hd,ee,ee),vi=()=>{let[e,...t]=qe.value.split(jd);return t.join(jd).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 rI(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function oI(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function sI(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 Mp(e,t){let n=ee();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 pu(e,n.value);if(t===b.PALETTE)return fu(e,n.value);let r=rI(e)||oI(e);if(r)return iI(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 iI(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 sI(h().contextNode.childRenderAxis,e,n)}var bi=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 ff from"node:fs";import iS from"node:path";import aS from"react";import{Box as oS}from"ink";import Ni from"react";import NI from"chalk";import{Box as Kd,Text as AI}from"ink";import en from"react";import{Text as Pp}from"ink";import Lp,{useEffect as kp,useState as aI}from"react";var Dp={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ye=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Y(),r=Dp[n]??Dp.default,[o,s]=aI(0);if(kp(()=>{s(0)},[r]),kp(()=>{if(!e)return;let l=setInterval(()=>{s(c=>(c+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return Lp.createElement(Pp,null,t);let i=r[o]??r[0]??t;return Lp.createElement(Pp,{color:y.accent,dimColor:o===1},i)};import{Box as Vd,Text as dI}from"ink";import xi from"react";var lI=(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}},xt=({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?lI(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 xi.createElement(Vd,{flexDirection:"row",height:i,width:"100%"},xi.createElement(Vd,{flexDirection:"column",flexGrow:1,height:i},x),xi.createElement(Vd,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((D,ve)=>xi.createElement(dI,{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 Bp,zd,cI=()=>{let{eventLog:e=[]}=h();if(zd&&Bp===e)return zd;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Bp=e,zd=t,t},Ii=e=>cI().has(e);import{Text as uI}from"ink";import mI from"react";var pI=e=>e.toLowerCase().trim(),fI=(e,t=kr)=>{let n=pI(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 mI.createElement(uI,{underline:t,color:fI(o)},"@"+s,Ii(e)?"":"\u2197")};import{Text as gI}from"ink";import hI 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 hI.createElement(gI,{underline:t,backgroundColor:de(r.name),color:y.secondary}," "+o+" ")};import{useEffect as yI,useState as vI}from"react";var bI=80,Fp=1400,Si=new Set,Oo=null,xI=e=>(Si.add(e),Oo||(Oo=setInterval(()=>{for(let t of Si)t()},bI)),()=>{Si.delete(e),Si.size===0&&Oo&&(clearInterval(Oo),Oo=null)}),II=()=>{let e=Date.now()%Fp/Fp;return e<.5?e*2:(1-e)*2},Ur=e=>{let[,t]=vI(0);return yI(()=>{if(e)return xI(()=>t(n=>n+1))},[e]),mi(II())};var SI=(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)]},Op=3,EI=2,CI=(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}},_p=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Ur(r),s=e-4,i=s-7-1,[l,c]=SI(Ie(t.title),i,s),m=c?null:fn(Ie(t.props.description),s)||null,p=kn(t),f=Dn(t).map(A=>({...A,name:A.name})),g=Math.max(1,s-Op),v=C.getCommentsByIssue(t.id),x=v.length?String(v.length).length+2+1:0,{shown:I,hidden:R}=CI([...p.map(A=>({id:A.id,isTag:!0,width:Math.min(A.name.length,g)+Op})),...f.map(A=>({id:A.id,isTag:!1,width:Math.min(A.name.length,g)+EI+(Ii(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 pt from"react";var RI=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,Up=({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=>pt.createElement(ar,{key:D.id,paddingRight:p},pt.createElement(_o,{color:de(D.name)},"\u25A0"))),x=m.map(D=>pt.createElement(ar,{key:D.id,paddingRight:p},pt.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?pt.createElement(ar,{paddingRight:p},pt.createElement(_o,{color:y.accent},"[",R.length,"]")):null,M=f+g+A,k=Math.max(1,n-t-M-(M>0?1:0));return pt.createElement(ar,{justifyContent:"space-between"},pt.createElement(ar,null,pt.createElement(ar,{width:t},o?pt.createElement(Ye,{isSelected:!0}):pt.createElement(_o,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),pt.createElement(_o,{wrap:"truncate",color:I},RI(r.title,k))),pt.createElement(ar,null,v,x,w))};var TI=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:l})=>{let{renderedChildrenIndex:c,replay:m}=Y(),p=c[e.id]??[],f=m?new Set(m.flashNodeIds):null,g=f?.has(e.id)??!1,v=Ur(g),x=`${e.title} ${NI.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(Kd,{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(AI,{bold:!0,color:g?v:t?y.accent:y.primary},x," ",e.readonly?"\u{1F512}":"")),ve=(Ve,Nt)=>{let dt=s&&i===Nt;if(!P(Ve))return null;let ke=f?.has(Ve.id)??!1;return o?en.createElement(Up,{key:Ve.id,index:Nt,labelWidth:M,width:w,ticket:Ve,isSelected:dt,isFlashing:ke,mode:l}):en.createElement(_p,{key:Ve.id,width:w,ticket:Ve,isSelected:dt,isFlashing:ke})};return en.createElement(Kd,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},D,en.createElement(Kd,null,p.length>0&&en.createElement(xt,{selectedIndex:i,height:k,itemHeight:R},p.map(ve)),A&&en.createElement(Ye,{isSelected:!0})))},jp=en.memo(TI);import{Box as lr,Text as sl}from"ink";import Fe,{useMemo as jo}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},Hp=(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 wI,useMemo as MI,useRef as PI}from"react";import{decodeTime as Wp}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"},Ei=e=>String(e).padStart(2,"0"),Ci=e=>`${e.getFullYear()}-${Ei(e.getMonth()+1)}-${Ei(e.getDate())} ${Ei(e.getHours())}:${Ei(e.getMinutes())}`;var LI=e=>De(e,"attachments"),kI=e=>C.getAttachmentsByIssue(e.id).sort((t,n)=>Wp(t.id)-Wp(n.id)),Gp=e=>{for(let t of e)C.deleteNode(t.id)},DI=(e,t,n)=>ge.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),BI=(e,t)=>{let n=C.getNode(LI(e.id));if(!n||!ut(n))return[];let r=t.map((o,s)=>DI(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},FI=e=>`${Math.max(1,Math.round(e/1024))} KB`;function Vp({ticket:e,width:t,height:n}){let r=MI(()=>kI(e),[e]),o=PI([]);wI(()=>(Gp(o.current),o.current=BI(e,r),()=>{Gp(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Y(),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(xt,{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}," "+FI(m.bytes)+" "+Wr(Re(m.id)))))})))}import{Box as Fn,Text as On}from"ink";import Pe,{useEffect as GI,useMemo as of,useRef as VI}from"react";import{decodeTime as sf}from"ulid";var Kp=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,qd=e=>e.replace(Kp,"");var zp=e=>e==="additions"||e==="deletions",Yd=e=>{let t=Kp.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"||!zp(r.side)||!zp(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r};var qp=/```\n([\s\S]*?)\n?```\s*$/,Yp=e=>qp.exec(e)?.[1]??null,OI=/`[^`\n]+`[^\n]*\n?$/,Xp=e=>qd(e).replace(qp,"").replace(OI,"").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})`},Xd=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${_I(e)}`;var UI=(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)},jI=/!\[([^\]]*)\]\([^)]*\)/g,$I=e=>e.replace(jI,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),HI=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),WI=4,Qp=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(WI)),Jd=e=>{let t=!1;return e.map(Qp).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=Yd(n);if(r)return{kind:"caption",text:Xd(r)};let o=$I(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)}})},Zp=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Jp=(e,t)=>{let n=[];for(let r of Jd(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 Zp(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of UI(HI(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},ef=(e,t)=>{let n=Yd(e),r=n?Yp(e):null;if(!n||r===null)return Jp(qd(e).split(`
|
|
66
|
+
`),t);let o=Xp(e),s=r.split(`
|
|
67
|
+
`).map(Qp),i=n.side===n.endSide?n.start:void 0,l=i===void 0?0:String(i+s.length-1).length+3;return[...o?[...Jp(o.split(`
|
|
68
|
+
`),t),{kind:"blank"}]:[],{kind:"caption",text:Xd(n)},...s.flatMap((c,m)=>Zp(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 tf,Text as dr}from"ink";import It from"react";var nf=({spans:e,bold:t,wrap:n})=>It.createElement(dr,{color:y.primary,bold:t,wrap:n},e.map((r,o)=>r.code?It.createElement(dr,{key:o,color:y.yellow},r.text):It.createElement(dr,{key:o},r.text))),Qd=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return It.createElement(dr,null," ");case"fence":return It.createElement(dr,{color:y.secondary2},"```");case"caption":return It.createElement(dr,{color:y.accent,wrap:r},e.text);case"heading":return It.createElement(nf,{spans:e.spans,bold:!0,wrap:r});case"text":return It.createElement(nf,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return It.createElement(dr,{backgroundColor:y.secondary,color:y.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},rf=({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 It.createElement(tf,{flexDirection:"column"},e.map((o,s)=>It.createElement(tf,{key:s},It.createElement(Qd,{line:o,width:t,gutter:r}))))};var zI=4,KI=e=>De(e,"comments"),qI=e=>C.getCommentsByIssue(e.id).sort((t,n)=>sf(t.id)-sf(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),af=e=>{for(let t of e)C.deleteNode(t.id)},YI=(e,t)=>{let n=C.getNode(KI(e.id));if(!n||!ut(n))return[];let r=t.map((o,s)=>Hp(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 df({ticket:e,width:t,height:n}){let r=of(()=>qI(e),[e]),o=VI([]);GI(()=>(af(o.current),o.current=YI(e,r),()=>{af(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Y(),l=Math.max(1,n-4),c=Math.max(20,t-8),m=of(()=>r.map(f=>{let g=ef(f.md,c);return g.length>0?g:[{kind:"blank"}]}),[r,c]),p=m.map(f=>f.length+zI);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(xt,{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(Re(f.id))))),Pe.createElement(Fn,{paddingLeft:3,paddingBottom:1},Pe.createElement(rf,{lines:m[g]??[],width:c})))})))}import{Box as Ri,Text as XI}from"ink";import In from"react";var lf=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Y(),{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(Ri,{alignItems:"center",paddingTop:1},In.createElement(Ri,{minWidth:12},In.createElement(Ye,{isSelected:n}),In.createElement(XI,{color:n?y.accent:y.secondary2},o,":")),In.createElement(Ri,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((l,c)=>{let m=r.id===t.id&&c===e;return In.createElement(Ri,{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 tl}from"ink";import St,{useEffect as JI,useMemo as nl}from"react";var Zd=e=>Math.max(5,String(Math.max(e,1)).length+3),cf=(e,t)=>Math.max(0,e-6-Zd(t));var el=(e,t=0)=>Math.max(1,e-5-2*t);var QI="\u2029",uf=(e,t)=>`${e}::inline-line::${t}`,rl=new Map,mf=e=>{let t=rl.get(e)??[];rl.delete(e);for(let n of t)C.deleteNode(n)},ZI=(e,t)=>{mf(e);let n=[];t.forEach((r,o)=>{let s=yt(BigInt(o+1));if(!ce(s))return;let i=C.createNode(ge.text({id:uf(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)}),rl.set(e,n)},ol=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:l}=Y(),c=nl(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=nl(()=>c.join("\0"),[c]);JI(()=>(ZI(e,c),()=>{mf(e)}),[e,m]);let p=Zd(c.length),f=cf(s,c.length),v=nl(()=>Jd(c).map(x=>{if(x.kind==="code"||x.kind==="caption")return{...x,text:Za(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(Za(I,f))}}return x}),[c,f]).map((x,I)=>{let R=l.id===e&&i===I;return St.createElement(Vr,{key:uf(e,I)},St.createElement(Vr,{flexShrink:0},St.createElement(tl,{color:R?y.primary:y.secondary2,dimColor:!R},`${I+1} `.padStart(p,"\xA0"))),x.kind==="blank"?St.createElement(tl,{backgroundColor:R?"gray":void 0},QI):St.createElement(Vr,null,St.createElement(Qd,{line:x,width:x.kind==="code"?f:0,wrap:"truncate-end"})))});return St.createElement(Vr,{flexDirection:"column",paddingTop:1},St.createElement(Vr,null,St.createElement(Ye,{isSelected:o}),St.createElement(tl,{color:o?y.accent:y.secondary2},t)),St.createElement(Vr,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},St.createElement(xt,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},v)))};var eS=e=>De(e,"description"),tS=e=>De(e,"comments"),nS=e=>De(e,"history"),rS=e=>De(e,"attachments"),pf=({ticket:e,height:t})=>{let n=jo(()=>$p(e),[e]),{selectedIndex:r,contextNode:o}=Y(),s=process.stdout.columns||120,i=jo(()=>eS(e.id),[e.id]),l=jo(()=>tS(e.id),[e.id]),c=jo(()=>nS(e.id),[e.id]),m=jo(()=>rS(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(df,{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(Vp,{ticket:e,width:s,height:k}))}if(v){let M=C.getNode(c),k=M&&ut(M)?M.props.value??"":"",D=el(t);return Fe.createElement(lr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},M?Fe.createElement(ol,{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=el(t,R),w=(M,k)=>M.id===i?Fe.createElement(ol,{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(lf,{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(sl,{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(sl,{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(sl,{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 sS=({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 Ni.createElement(oS,{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 Ni.createElement(jp,{key:R.id,height:i,width:x,swimlane:R,isSelected:k,isDense:I,isFocused:w,listSelectedIndex:M,mode:o})}),m&&f&&Ni.createElement(pf,{height:i,ticket:f}))},Ai=Ni.memo(sS);import{render as dS}from"ink";import{Writable as lS}from"node:stream";var $o=e=>String(e).padStart(2,"0"),cS=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}`},uS=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",mS=async(e,{width:t,height:n})=>{let r="",o=new lS({write(i,l,c){let m=pS(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),c()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=dS(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},pS=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),gf=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 mS(aS.createElement(Ai,{height:c,width:l,swimlanes:(s[i.id]??[]).filter(A=>A!==void 0&&Pt(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=Cs(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let f=new Date,g=cS(f),v=`board_${uS(i.title)}_${g}.md`,x=Zc(p.value);ff.mkdirSync(x,{recursive:!0});let I=iS.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 ff.writeFileSync(I,R,"utf8"),u("Exported board layout",I)};import{useSyncExternalStore as qF}from"react";var Ti,fS=new Set,hf=()=>{for(let e of fS)e()};var _n=()=>{if(!Ti)throw new Error("Ui state not initialized. Call initUiState() first.");return Ti};var yf=(e={})=>(Ti=e,hf(),u("UX state initialized",null)),gS=e=>{let t=_n();return Ti=e(t),hf(),u("UX state updated",null)},Un=e=>gS(t=>({...t,...e}));import{ulid as ll}from"ulid";import{spawn as hS,spawnSync as yS}from"node:child_process";import vS from"node:os";import vf from"node:path";import{ulid as bS}from"ulid";function il(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 xS(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function wi(){let{preferredEditor:e}=ie(),t=[e?xS(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function al(e){let[t=""]=il(e);return/(^|\/)code(-insiders)?$/.test(t)}function bf(e,t){let[n="",...r]=il(e);return{command:n,args:[...r,...t]}}function xf(e,t){return bf(e,al(e)?["--wait",t]:[t])}function IS(e,t,n,r="new"){return bf(e,[r==="new"?"--new-window":"--reuse-window","--diff",t,n])}function If(e){let t=vf.join(vS.tmpdir(),"epiq");$e.mkDir(t);let n=vf.join(t,bS());$e.writeToFile(n,e??"");let r=wi();for(let o of r){let{command:s,args:i}=xf(o,n);if(!s)continue;let l=yS(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 SS=new Set(["vim","vi","nvim","nano","pico","ed"]);function ES(e){let[t=""]=il(e),n=t.split("/").pop()??t;return SS.has(n)}var CS=600;function Sf({command:e,args:t},n){return new Promise(r=>{if(!e){r(a(`"${n}" is not a usable editor command`));return}let o=hS(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))},CS)})}function RS(e,t){return ES(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}`)):Sf(xf(e,t),e)}function dl(e,t,n,r="new"){return Sf(IS(e,t,n,r),e)}async function Ef(e){let t=wi();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 RS(r,e);if(!d(o))return o;n=o,logger.error(`Failed to open editor "${r}" for ${e}: ${o.message}`)}return n}var Cf=async e=>{let{contextNode:t,selectedIndex:n}=h(),r=q(t.id)[n];if(e.modifier===mt.DESCRIPTION)return AS();if(r&&yo(r))return NS(e);if(e.modifier===mt.TITLE){let o=Z();if(d(o))return a("Unable to resolve user ID");let s=r;if(!s)return a("Missing node");if(s.readonly)return a("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return a("Provide a title");let l=await Gt();return d(l)?l:B([{id:ll(),action:"edit.title",payload:{id:s.id,name:i},...o.value}],l.value)}return a("Unknown edit command")},NS=async e=>{let t=Z();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:ll(),action:"edit.issue.comment",payload:{id:c.id,issue:i.id,md:m},...t.value}],f)},AS=async()=>{let e=Z();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=If(c);if(d(m))return a("Failed to edit field");let p=m.value;return p===c?u("No changes made",null):B([{id:ll(),action:"edit.description",payload:{id:i.id,md:p},...e.value}],n)};import wS from"node:fs";import Nf from"node:path";import cl from"node:fs";import TS from"node:path";var Rf=async e=>{let t=TS.join(e,".gitignore"),n=cl.existsSync(t)?cl.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)))},
|
|
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
|
-
`)},
|
|
83
|
-
`)[0]?.trim()??"";return t.length>
|
|
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)},
|
|
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=>!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<
|
|
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=
|
|
89
|
-
`)){let f
|
|
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")}
|
|
79
|
+
`,cl.writeFileSync(t,n,"utf8"),z.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),u("Local epiq paths ignored",!0)};var MS=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)))},Se=(e,t)=>a(`[${e}] ${t}`),Af=async({cwd:e,user:t})=>{let n=Ss(),r=await wt(e);if(d(r))return Se(1,r.message);let o=r.value,s=await Ns(o);if(d(s))return Se(2,s.message);if(s.value)return Se(2,`Cannot initialize Epiq while a git operation is in progress: ${s.value}`);let i=await MS(o);if(d(i))return Se(2.5,i.message);if(i.value.length>0)return Se(3,`Cannot initialize Epiq with uncommitted changes (${i.value.join(", ")}). Commit or stash your changes first.`);if(po(o))return Se(4,"Epiq project already initialized");let{userId:l,userName:c}=t;if(!l||!c)return Se(5,"Missing Epiq user id");let m=await Rm(o);if(d(m))return Se(6,m.message);let p=n.stateBranch,f=await As({repoRoot:o,branch:p});if(d(f))return Se(6,f.message);if(f.value)return Se(6,`State branch already exists: ${p}`);let g=await xd({repoRoot:o,stateBranchName:p});if(d(g))return Se(6,g.message);let v=Ms();if(d(v))return Se(7,v.message);let x=Nf.join(ws(),n.projectId),I=await rr({repoRoot:o,stateBranchRoot:x,stateBranchName:p});if(d(I))return Se(8,I.message);let R=Nf.join(x,".epiq");wS.mkdirSync(R,{recursive:!0});let A=ym({userId:l,userName:c});if(d(A))return Se(9,A.message);for(let vs of A.value){let ro=Ks({event:vs,rootDir:x});if(d(ro))return Se(9,ro.message)}let w=Zn({userId:l,userName:c}),M=$s(x,w);if(d(M))return Se(9,M.message);let k=await Zs({stateBranchRoot:x,eventFileName:w});if(d(k))return Se(10,k.message);let D=await Sr({cwd:x,message:"[epiq:init]"});if(d(D))return Se(10,D.message);let ve=await Rf(o);if(d(ve))return Se(11,ve.message);let Ve=Tc({repoRoot:o,fileContents:n});if(d(Ve))return Se(12,Ve.message);let Nt=await be.stage({cwd:o,pathspec:[".epiq/project.json",".gitignore"]});if(d(Nt))return Se(13,Nt.message);let dt=await be.commit({cwd:o,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(d(dt))return Se(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}`),Tf=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 Af({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 LS}from"ulid";import{ulid as PS}from"ulid";var wf=null,jn=()=>structuredClone(wf),Wo=e=>{wf=e},Mf=()=>{let{contextNode:e,selectedIndex:t}=h(),r=ae(e.id)[t];return r?u("Resolved selected child",r):a("Target node not found")},ul=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ae(t).filter(o=>o.id!==e);return qs(r,n)},Pf=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Z();if(d(r))return a("Unable to resolve user ID");let o=ul({parentId:t,id:e,position:n});return d(o)?o:u("Created pending move state",{id:PS(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Lf=e=>{Wo(e);let t=An(e,!0);return d(t)?t:u("Node moved successfully",t.value)};function ml(e){let t=Mf();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=Pf({id:t.value.id,parentId:l.id,position:{at:"end"}});return d(c)?c:Lf(c.value)}function pl(e){let t=Mf();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=Pf({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:Lf(i.value)}var kf=()=>{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))},Mi=(e,t="Moved preview")=>{if(d(e))return e;let n=kf();return d(n)?n:(N({mode:b.MOVE}),u(t,null))},Df=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=ee().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=ul({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(Wo({id:LS(),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 Mi(pl(1));if(t==="previous")return Mi(pl(-1));if(t==="to-next")return Mi(ml(1));if(t==="to-previous")return Mi(ml(-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=kf();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 Li}from"ulid";import{monotonicFactory as kS,ulid as DS}from"ulid";var BS=kS(),Pi=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=BS();return u("Created issue events",[{id:DS(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var Bf=async(e,t)=>{let n=Z();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:Li(),action:"add.board",payload:{id:Li(),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:Li(),action:"add.swimlane",payload:{id:Li(),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=Pi({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 US from"node:os";import _f from"node:path";var FS=e=>e.some(t=>t.action==="init.workspace"),Ff=async(e,t)=>{let n=Ht(e);return d(n)?a(n.message):lo({cwd:t,branch:n.value})},OS=e=>{let t=xe(process.cwd());if(d(t))return!1;let n=ue({repoRoot:t.value});return!d(n)&&n.value===e},ki=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=bt(n);if(d(o))return Bt(3,o.message);if(!FS(o.value.events)){let m=await Ff(e,n);if(d(m)&&logger.info(3,m.message),o=bt(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=ii({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 ti({worktreeRoot:n,operation:"boot pull",fn:()=>Rd(n,()=>(Ar("Pulling"),Ff(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)?(Qs("Offline"),u("Offline",void 0)):Te(s.message);if(!s.value)return nr("Already synced"),u("Already synced",void 0);if(!OS(n))return u("Project changed during the pull",void 0);let i=Nd(n);return d(i)?i:(nr("Pulled"),u("Pulled and reloaded",void 0))},Di=e=>{_S(e).then(t=>{d(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${Tr(t)}`)})},Of=()=>{let e=Dt([]);return d(e)?Bt(4,e.message):(N({hasProjectDefinition:!1,hasInitializingEvents:!1}),u("Booted without a project",void 0))};var jS=e=>e==="~"||e.startsWith("~/")?_f.join(US.homedir(),e.slice(1)):e,$S=(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(_f.resolve(jS(n)));return d(r)?a(`No epiq project at ${n}`):u("Resolved project path",r.value)},Uf=async()=>{let e=vi();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=$S(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 ki(o);return d(i)?(process.chdir(s),a(i.message)):(Di(o),u(`Opened ${Lr(o)}`,null))};var Bi=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=h(),s=Vs(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 jf=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 HS=20,WS=16,GS=150,Fi=null,Oi=null;var cr=()=>{Fi!==null&&(clearInterval(Fi),Fi=null),Oi!==null&&(clearTimeout(Oi),Oi=null)},$f=()=>{cr(),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Hf=({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=jf(o),l=Math.max(1,Math.round(n*HS/1e3)),c=Math.max(Math.round(n/l),WS),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:[]}}),Fi=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}$f();return}g.push(...nd(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(),Oi=setTimeout($f,GS);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?_i(v):I?.currentLabel??"",flashNodeIds:v?[...new Set(g)]:I?.flashNodeIds??[]}})},c)};var Wf=async()=>{let e=Qe(h().breadCrumb,"BOARD");if(d(e))return e;let t=await wt(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}=ee().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=zs(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=Bi({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 Gf=async()=>{let e=Qe(h().breadCrumb,"BOARD");if(d(e))return e;let t=await wt(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}=ee().commandMeta,{dateInput:s,durationInput:i}=ci(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?li(i):15e3;if(c===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=h(),f=Bi({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)):(Hf({events:g,startTime:m,durationMs:c}),u("Replaying board history",!0))};import{spawn as zS}from"node:child_process";var KS=()=>{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"]}}},Vf=async e=>new Promise(t=>{let{command:n,args:r}=KS();try{let o=zS(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 Vf(e);return d(n)?n:u(`Copied ${t} to clipboard`,null)},zf=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 Kf=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 ri();return d(t)?(N({syncStatus:{msg:t.message,status:"failed"}}),t):(N({mode:b.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{ulid as qf}from"ulid";var Oe=async()=>{let e=await Gt();return d(e)?e:u("Resolved persist root",e.value)};var qS=e=>e.action==="add.issue.comment",Yf=async()=>{let e=Z();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(qS).find(m=>m.payload.id===s);return c?c.payload.author!==e.value.userId?a("You can only delete your own comments"):B([{id:qf(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return B([{id:qf(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)};import{ulid as YS}from"ulid";var Xf=async()=>{let e=Z();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:YS(),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 XS}from"ulid";var Ui=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 Jf=async()=>{let e=Z();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=Ui(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:XS(),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 JS}from"ulid";var Qf=async()=>{let e=Z();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=vi();if(!o)return a("Provide a title");let s=await Oe();return d(s)?s:B([{id:JS(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)};import{ulid as QS}from"ulid";var Zf=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().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:QS(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...e.value}],m.value)};import{ulid as fl}from"ulid";var eg=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().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??fl();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):B([...c?[]:[{id:fl(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:fl(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],l.value)};import{ulid as gl}from"ulid";var ji=()=>{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 tg=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().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=ji(),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??gl(),I=M?.name??s}if((p.props.assignees??[]).includes(x))return a("Assignee already assigned");let A=!!h().contributors[x];return B([...A?[]:[{id:gl(),action:"create.contributor",payload:{id:x,name:I},...e.value}],{id:gl(),action:"add.issue.assignee",payload:{id:p.id,assignee:x},...e.value}],f.value)};import{ulid as ZS}from"ulid";var ng=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().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):ji().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:ZS(),action:"remove.issue.assignee",payload:{id:i.id,assignee:p},...e.value}],f.value)};import{ulid as rg}from"ulid";var og=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=Z();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:rg(),action:"add.issue.comment",payload:{id:rg(),issue:c.id,author:n.value.userId,md:t},...n.value}],m.value)};import{ulid as tE}from"ulid";import eE from"zod";var sg=()=>{let e=ee().commandMeta.inputString,t=eE.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=gt({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 ig=()=>{let e=ee().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Vm(e),n=gt({autoSync:t});return d(n)?n:(ze({autoSync:t}),N({mode:b.DEFAULT}),u(`Auto sync set to "${e}"`,null))};var ag=()=>{let e=ee().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=gt({logLevel:e});return d(n)?n:(ze({logLevel:e}),N({mode:b.DEFAULT}),u(`Auto sync set to "${e}"`,null))};var dg=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||tE();if(!i||!l)return a("Unable to resolve user name or id");let c=gt({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=gt({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=gt({viewMode:t});return d(n)?n:(ze({viewMode:t}),N({mode:b.DEFAULT}),u(`View set to "${t}"`,null))}case ye.AUTOSYNC:return ig();case ye.LOG_LEVEL:return ag();case ye.SYNC_DEBOUNCE_MS:return sg();case ye.ATTACHMENT_MAX_KB:return sp();default:return a("Unknown config command")}};var $i=[{systemOnly:!0,intent:U.Move,description:"Internal move-state command",mode:b.COMMAND_LINE,action:Df},{intent:U.Delete,description:"Delete the currently selected node",mode:b.COMMAND_LINE,action:Yf,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}=ee().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:Xf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:b.COMMAND_LINE,action:Jf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Init,description:"Initialize Epiq in the current git repository",mode:b.COMMAND_LINE,action:Tf},{intent:U.OpenProject,description:"Open a recently used epiq project, by number or path",mode:b.COMMAND_LINE,action:Uf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.NewItem,description:"Create a new board, swimlane, or issue",mode:b.COMMAND_LINE,action:Bf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Rename,description:"Rename the currently selected node",mode:b.COMMAND_LINE,action:Qf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.UntagTicket,description:"Remove a tag from the selected issue",mode:b.COMMAND_LINE,action:Zf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.TagTicket,description:"Add or create a tag on the selected issue",mode:b.COMMAND_LINE,action:eg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.AssignUserToTicket,description:"Assign a user to the selected issue",mode:b.COMMAND_LINE,action:tg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:b.COMMAND_LINE,action:ng,onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Comment,description:"Add a comment to the selected issue",mode:b.COMMAND_LINE,action:async(e,t)=>og(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:U.Sync,description:"Pull, commit, and push Epiq state",mode:b.COMMAND_LINE,action:Kf},{intent:U.Peek,description:"View board state at another point in time",mode:b.COMMAND_LINE,action:Wf},{intent:U.Replay,description:"Replay board history forward from a point in time",mode:b.COMMAND_LINE,action:Gf},{intent:U.Export,description:"Export the current board layout to markdown",mode:b.COMMAND_LINE,action:async()=>{let e=await gf();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)=>Cf(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)=>zf(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)=>dg(t)}];var nE=new Set(["peek","replay","filter","view-help","yank"]),tn=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ee();if(!t)return a("No command to confirm");if(!e&&n===Qt.Invalid)return a("Invalid command");let s=bi(t);Rp();let{readOnly:i}=h();if(i&&!nE.has(s))return Fo({status:En.Fail,message:"Command not available in readonly state",value:null});let l=$i.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):(Np({addToHistory:!e}),l.onSuccess?.(),ie().autoSync&&oi(),c)};var Hi=[{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}))}],Wi=[{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")}],lg=[{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 cg={[V.WORKSPACE]:[...Hi,...Wi],[V.BOARD]:[...Hi,...Wi],[V.SWIMLANE]:[...Hi,...Wi,...lg],[V.TICKET]:[],[V.FIELD]:[],[V.FIELD_LIST]:[],[V.TEXT]:[],[V.COMMENT]:[]};import oE from"node:fs";import sE from"node:path";import{spawn as rE}from"node:child_process";function ug(e){let t=process.platform,o=rE(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 mg=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=sE.join(mo(n.value),r);return oE.existsSync(o)?(ug(o),u(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")};var pg=()=>{Q("");let{pendingNavTarget:e}=_n();N({mode:b.DEFAULT}),e&&O.navigate(e),Un({pendingNavTarget:void 0})},fg=[{intent:S.ExitCommandLine,mode:b.HELP,action:()=>(pg(),u("Exiting help",null))},{intent:S.Exit,mode:b.HELP,action:()=>(pg(),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 iE=e=>{N({mode:b.COMMAND_LINE});let{pendingNavTarget:t}=_n();t&&O.navigate(t),Un({pendingNavTarget:void 0}),Q(`${e} `)},gg=()=>{Q("");let{pendingNavTarget:e}=_n();e&&O.navigate(e),Un({pendingNavTarget:void 0}),N({mode:b.DEFAULT})},hg=[{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?(iE(t),u("Selected command",t)):u("No command selected",null)}},{intent:S.ExitCommandLine,mode:b.PALETTE,action:()=>(gg(),u("Exiting palette",null))},{intent:S.Exit,mode:b.PALETTE,action:()=>(gg(),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 yg=[{intent:S.InitCommandLine,mode:b.DEFAULT,description:"[:] write command",action:()=>(N({mode:b.COMMAND_LINE}),Q(""),u("Entering command line mode",null))},...fg,...hg,{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 mg(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 aE=500,dE=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),vg=e=>{let t=dE(e);t&&yi(n=>(n+t).slice(0,aE))};var lE=[b.COMMAND_LINE,b.PALETTE],cE=e=>[{intent:S.MoveCursorLeft,mode:e,action:()=>(Wd(-1),u("Moving cursor left",null))},{intent:S.MoveCursorRight,mode:e,action:()=>(Wd(1),u("Moving cursor right",null))},{intent:S.MoveCursorLeftOfWord,mode:e,action:()=>(Gd("left"),u("Moving cursor left of word",null))},{intent:S.MoveCursorRightOfWord,mode:e,action:()=>(Gd("right"),u("Moving cursor right of word",null))},{intent:S.AutoCompleteCommand,mode:e,action:()=>(yi((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})=>(vg(n??""),u("Capturing input",null))},{intent:S.EraseInput,mode:e,action:()=>(Ep(),u("Erasing input",null))},{intent:S.EraseInputWord,mode:e,action:()=>(Cp(),u("Erasing input word",null))}],bg=[{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))},...lE.flatMap(cE),{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:()=>(Ap(),u("Getting last command from history",null))},{intent:S.GetNextCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Tp(),u("Getting next command from history",null))}];var hl=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},xg=({keys:e})=>e.length===1?0:1,Ig=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(hl).filter(r=>r!==null).sort((r,o)=>xg(r)-xg(o))};function Sg(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 Eg=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,yl,vl=new Set,bl=()=>{for(let e of vl)e()},mE=e=>(vl.add(e),()=>vl.delete(e));function xl(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=Sg(t,o,r);if(d(c))return logger.error(c.message),c;let m=c.value,{context:p}=l,f=[...yg,...cg[p]??[],...bg],g=Ig(f,n),v=Eg(f),x=pE(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){yl=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=xl(r);return d(o)?o:(nn=o.value,bl(),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=xl(n);return d(r)?a(r.message??"Unable to update state"):(nn=r.value,bl(),u("State updated",null))}function Nu(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=xl(n);return d(r)?a(r.message??"Unable to update state"):(nn=r.value,bl(),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 lm=()=>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 Y=()=>uE(mE,h,h),pE=sm,q=e=>h()?.renderedChildrenIndex[e]??[],Ot=()=>yl?Io(yl):a("Cannot reset state: no initial workspace found"),vt=()=>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}`)},Il=(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(Il(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 fE=(e,t)=>e+" ".repeat(Math.max(0,t-Cg(e))),gE=(e,t)=>" ".repeat(Math.max(0,t-Cg(e)))+e,Gi=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`),hE=(e,t)=>t?e<t?"up":e>t?"down":null:null,yE=(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=hE(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Rg=e=>`${Math.max(1,Math.round(e/1024))} KB`,Ng=e=>C.getAttachment(e)?.name??"",vE=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(`(${Rg(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Ng(e.payload.id);return t?`"${t}"`:""}default:return""}},bE=e=>{let t=Wr(Re(e));return Hn.gray(gE(t,8))},xE=12,IE=e=>fE(`${e}`,xE),SE=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}" (${Rg(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Ng(e.payload.id);return t?`"${t}"`:""}default:return""}},_i=e=>[Gi(e.action),SE(e)].filter(Boolean).join(" "),Ag=(e,t)=>{let n=bE(e.id),r=IE(e.userName),o=Hn.dim("\u203A"),s=e.action==="move.node"?yE(e,t):[Gi(e.action),vE(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};var EE=e=>De(e,"comments"),CE=e=>De(e,"description"),RE=e=>De(e,"assignees"),NE=e=>De(e,"tags"),AE=e=>De(e,"history"),TE=e=>De(e,"attachments"),Vi=({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)},Tg=({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)},Au=e=>{let t=yt(Vt/4n),n=yt(Vt/2n),r=yt(Vt*3n/4n),o=yt(Vt*7n/8n),s=yt(Vt*15n/16n),i=yt(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=Vi({id:CE(e.id),name:fe.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(l))return l;let c=Tg({id:RE(e.id),name:fe.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(c))return c;let m=Tg({id:NE(e.id),name:fe.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(m))return m;let p=Vi({id:EE(e.id),name:fe.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(p))return p;let f=Vi({id:TE(e.id),name:fe.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(d(f))return f;let g=Vi({id:AE(e.id),name:fe.HISTORY,parentNodeId:e.id,rank:i.value,value:wE(e),readonly:!0,childRenderAxis:"vertical"});return d(g)?g:u("Ticket virtual nodes materialized",void 0)},wE=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=>Ag(r,n.get(r.action)??[])).join(`
|
|
82
|
+
`)},wg=!0,Mg=e=>{wg=e},rd=()=>wg;import tR from"node:http";import vr from"node:path";import{fileURLToPath as nR}from"node:url";var ME=e=>{switch(e.action){case"add.issue":case"move.node":case"close.issue":case"reopen.issue":return e.payload.parent;default:return null}},Sl=(e,t)=>{let n=[];for(let r of e){let o=ME(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},zi=(e,t)=>Sl(e,t).at(-1)?.enteredAt??t;import{existsSync as Nl}from"node:fs";import{chmod as Al}from"node:fs/promises";import Ki from"node:path";import{chmodSync as PE,existsSync as LE,lstatSync as kE,mkdirSync as DE}from"node:fs";import BE from"node:os";import FE from"node:path";var El=(...e)=>{let t=FE.join(BE.tmpdir(),"epiq",...e);try{return LE(t)&&kE(t).isSymbolicLink()?a(`Refusing to write through a symlink at ${t}`):(DE(t,{recursive:!0,mode:448}),PE(t,448),u("Prepared private temp dir",t))}catch(n){return a(`Unable to prepare ${t}: ${n instanceof Error?n.message:String(n)}`)}};var OE=new Set(["create.tag","create.contributor","add.swimlane"]),_E=e=>{let t=new Map;for(let n of e){if(!OE.has(n.action))continue;let r=n.payload;r?.id&&r.name&&t.set(r.id,r.name)}return t},UE=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},Lg=e=>{let t=e.payload;return e.action==="tombstone.tag"||e.action==="restore.tag"?t?.id:t?.tag},jE=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}},$E=(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},Pg=90,HE=e=>{let t=e.trim().split(`
|
|
83
|
+
`)[0]?.trim()??"";return t.length>Pg?`${t.slice(0,Pg).trimEnd()}\u2026`:t},WE=(e,t,n)=>{let r=e.payload,o=Lg(e),s=e.action?Gi(e.action):"";if(r?.md!==void 0){let l=HE(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)}},GE=(e,t)=>{let n=e.payload;return{actor:Cl(e.userId,t,e.userName),tag:Cl(Lg(e),t),assignee:Cl(n?.assignee,t)}},kg=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)})},Dg=(e,t)=>{let n=kg(e);return e.filter((r,o)=>n[o]===t)},VE=e=>{let t=_E(e),n=UE(e),r=jE(e),o=kg(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:WE(l,t,n),issue:$E(l,r),board:o[c]??null,...GE(l,t)}]}).sort((l,c)=>l.t-c.t)},zo=null,Bg=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=VE(n.value);return zo={root:e,signature:t,entries:r},u("Timeline entries, built",r)};var Fg=1e5,zE=2e4,qi=null,Og=Promise.resolve(),Wn=e=>{let t=Og.then(e,e);return Og=t.then(()=>{},()=>{}),t},Yi=e=>{let t=xe(e??process.cwd());return d(t)?a(t.message):u("Resolved Epiq repo root",t.value)},Xi=e=>{let t=Yi(e);return d(t)?t:ue({repoRoot:t.value})},tt=()=>{if(!vt())return{mode:"live",asOfTime:null};let{timeMode:e}=h();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:qi}},_g=(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},Wg=async(e={})=>{let t=Xi(e.repoRoot);if(d(t))return a(t.message);let n=Bg(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=_g(r,i),c=_g(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)/Fg)),g=new Map;for(let x of p){let I=Math.min(Fg-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>zE?[]:m,earliest:i,latest:s})},Ko="",Ug="",KE=5e3,zr=null;var Tl=async(e={})=>{let t=Yi(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<KE)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=${Ug}%H${Ko}%at${Ko}%an${Ko}%s`]});if(d(o))return a(o.message);let s=o.value.stdout.split(Ug).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)},Ji=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)},Gg=e=>/^[0-9a-f]{7,40}$/i.test(e),qE=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=Ki.join(r.value,`${t}.diff`);return Nl(o)||($e.writeToFile(o,n.value.stdout),await Al(o,292)),Ef(o)},YE=12,XE=800,jg=async(e,t,n)=>{let r=await j({cwd:e,args:["show",`${t}:${n}`]});return d(r)?"":r.value.stdout},JE=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)},QE=async(e,t,n)=>{let r=await JE(e,t);if(d(r))return a(r.message);let o=r.value;if(o.length>YE)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([jg(e,`${t}~1`,g),jg(e,t,g)]),R=Ki.basename(g),A=Ki.join(i,String(v),"before",R),w=Ki.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 dl(n,c.beforePath,c.afterPath,"new");if(d(p)||m.length===0)return p;await new Promise(g=>setTimeout(g,XE));let f=await Promise.all(m.map(({beforePath:g,afterPath:v})=>dl(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},Vg=async e=>{if(!Gg(e.sha))return a("Invalid commit sha");let t=Yi(e.repoRoot);if(d(t))return a(t.message);let n=t.value,r=wi()[0];if(r&&al(r)){let o=await QE(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 qE(n,e.sha)},ZE=200,$g=e=>/^0+$/.test(e),Rl=/^:\d{6} \d{6} ([0-9a-f]{40}) ([0-9a-f]{40}) [A-Z]\d*\t(.+)$/,Hg=/^(\d+|-)\t(\d+|-)\t(.+)$/,eC=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)&&!Hg.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=Hg.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:$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)},zg=async e=>{if(!Gg(e.sha))return a("Invalid commit sha");let t=Yi(e.repoRoot);if(d(t))return a(t.message);let n=t.value,r=await eC(n,e.sha);if(d(r))return a(r.message);let o=r.value;if(o.length>ZE)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 Rs(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})},Kg=e=>{let t=Mn(e);if(d(t))return a(t.message);let n=Ot();if(d(n))return a(n.message);qi=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))},tC=(e,t)=>{qi=null;let n=Kg(e);return d(n)?a(`${t} (recovery to live also failed: ${n.message})`):a(t)},wl=e=>Wn(async()=>{let t=Xi(e.repoRoot);if(d(t))return a(t.message);let n=Vs(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?tC(t.value,l.map(m=>m.message).join(", ")):(hn(c),N({readOnly:!0,timeMode:"peek",unappliedEvents:o,replay:null}),qi=e.targetTime,u("Checked out historical state",{asOfTime:e.targetTime}))}),qg=async e=>{let t=Xi(e.repoRoot);if(d(t))return a(t.message);let n=zs(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})},Yg=(e={})=>Wn(async()=>{let t=Xi(e.repoRoot);if(d(t))return a(t.message);let n=Kg(t.value);return d(n)?a(n.message):u("Returned to live state",!0)});import nC 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)},Qi=null,te=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(!(Qi!==null&&Qi.repoRoot===n.value&&Qi.stateBranchRoot===r.value&&nC.existsSync(Yn(r.value)))){let p=await Id({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);Qi={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(_u(r.value)===l&&vt()&&tt().mode==="live")return u("Booted Epiq state, unchanged",i);let c=bt(r.value);if(d(c))return a(c.message);let m=Dt(c.value.events,c.value.unreadable);return d(m)?a(m.message):(Uu(r.value,l),u("Booted Epiq state",i))},ne=()=>{let e=ht();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")},X=()=>{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 rC from"node:fs";import oC from"node:path";import{ulid as Ml}from"ulid";var sC=e=>{if(e.filePath)try{return u("Read attachment file",{data:rC.readFileSync(e.filePath),name:e.name??oC.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")},Zi=()=>{let e=ht();return d(e)?Jt:e.value.attachmentMaxKb??Jt},Pl=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();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=sC(e);if(d(s))return s;let i=rp(t.value.stateBranchRoot,s.value.data,Zi());if(d(i))return i;let l=Ie(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:Bd(l,f)})},Ll=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();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 te(e.repoRoot,{pull:!1});return d(t)?t:op(t.value.stateBranchRoot,e.fileName,Zi())};var iC=365*24*60*60*1e3,fr=()=>{let e=X();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()-iC,i=new Map,l=new Map;for(let I of r)if(!I.isDeleted){if(Pt(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&&Re(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=ht();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:Re(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:Re(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:Ie(A.title),description:A.props.description??"",createdAt:Re(A.id),enteredLaneAt:zi(A.log??[],Re(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:Zi(),timeTravel:t})},Xg=null,aC=e=>{if(e===Xg)return;let t=ii({root:e});if(d(t)){z.info(t.message);return}Xg=e},Et=async(e={})=>{if(tt().mode!=="live")return fr();let t=await te(e.repoRoot,{pull:!1});return d(t)?t:(aC(t.value.repoRoot),fr())},qo=async(e={})=>{Ar();let t=pr(e.repoRoot);if(d(t))return a("Sync failed");let n=ne();if(d(n))return n;let r=await ni({cwd:t.value,ownEventFileName:Zn(n.value)});return d(r)?(bd(r.message),r):(nr(),u("Synced",r.value))};import{ulid as Ct}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=X();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 Zg=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();async function Ol(e){let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=X();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=>Zg(c.name,e.tag))).filter(l=>!e.assignee||qr(l).some(c=>Zg(c.name,e.assignee))).filter(l=>!o||l.title.toLowerCase().includes(o)||(l.props.description??"").toLowerCase().includes(o)),i=l=>Ie((l.parentNodeId?r[l.parentNodeId]?.title:void 0)??"");return e.brief?u("Listed issues",s.map(l=>({id:l.id,ref:_(l.id),title:Ie(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:Ie(l.title),description:l.props.description??"",createdAt:Re(l.id),enteredLaneAt:zi(l.log??[],Re(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 te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=Ie(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=Pi({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=Ie(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??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=Ie(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??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})},dC=(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: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 Ul(e){let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=Yo(e);if(d(r))return r;let o=s=>dC(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 te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();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=Ui(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})},lC=(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: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=ne();if(d(n))return n;let r=ue({repoRoot:t.value});if(d(r))return r;let o=bt(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=>lC(c,e,n.value,r.value);return e.issueIds?Yr("Moved",Dl(i.value,l)):l(i.value[0])}var Hl=e=>{let t=X();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:Re(r.id),action:r.action,label:_i(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 te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();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})},Gl=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();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=Ie(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 Qo}from"ulid";var Vl=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();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=Ie(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 te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.nodes[e.swimlaneId];if(!o)return a("Swimlane not found");if(!Pt(o))return a("Edit target must be a swimlane");if(o.readonly)return a("Cannot edit readonly swimlane");let s=Ie(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=ne();if(d(n))return n;let r=ue({repoRoot:t.value});if(d(r))return r;let o=bt(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 te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=r.value.nodes[e.swimlaneId];if(!o)return a("Swimlane not found");if(!Pt(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 te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=Yo(e);if(d(r))return r;let o=Ie(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 te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();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 te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();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 cC=()=>{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},th=(e,t)=>{let n=new Map(e);for(let r of Object.values(t))n.set(r.id,r.name);return n};var nh=async(e,t)=>{let n=gd(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 te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();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 nh(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=Ie(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=[...th(cC(),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 te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;if(!r.value.contributors[e.contributorId])return a("Contributor not found");if(await nh(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 ec=async(e={})=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();if(d(r))return r;let o=Mn(t.value.stateBranchRoot);if(d(o))return a(o.message);let s=e.boardId?Dg(o.value,e.boardId):o.value,i=new Map,l=new Set,c=new Set,m=gd(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=[...th(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 te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();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 ea}from"ulid";var es=async e=>{let t=await te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();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=ea(),l={id:ea(),...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 te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();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:ea(),...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 te(e.repoRoot,{pull:!1});if(d(t))return t;let n=ne();if(d(n))return n;let r=X();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:ea(),...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.5";import uC from"node:fs";import rh from"node:path";var ns=Number(process.env.EPIQ_GUI_PORT)||3710,rc="/api/instance",oc="epiq",ta=e=>{try{return uC.realpathSync(rh.resolve(e))}catch{return rh.resolve(e)}},mC=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"},oh=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 mC(s)?s:null}catch{return null}finally{clearTimeout(r)}};var pC=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,pC(e.value)),sh=(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 fC=15e3,ih=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=ht(),R=d(I)?null:I.value.userName;return!!(v&&R&&x)},m=()=>{let g=l()?.autoSyncDebounceMs??fC;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 Et({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 gC=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:!gC.has(n.hostname)},ah=(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 QC}from"ws";var on=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""});var hC=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},dh=({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=>hC(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:[["/*","*/"]]},Rt={line:["#"],block:[]},ic={line:["--"],block:[]},Xr={line:[],block:[["<!--","-->"]]},yC={line:[],block:[]},$=(e,t)=>({name:e,comment:t}),na=$("TypeScript",_e),ra=$("JavaScript",_e),lh={ts:na,tsx:na,mts:na,cts:na,js:ra,jsx:ra,mjs:ra,cjs:ra,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",Rt),exs:$("Elixir",Rt),pl:$("Perl",Rt),r:$("R",Rt),jl:$("Julia",Rt),sh:$("Shell",Rt),bash:$("Shell",Rt),zsh:$("Shell",Rt),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",Rt),yaml:$("YAML",Rt),toml:$("TOML",Rt),ini:$("INI",Rt),json:$("JSON",yC)},vC="Other",ch=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},yr=e=>lh[ch(e)]?.name??vC,rs=e=>lh[ch(e)]?.comment??null,bC=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],xC=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,Jr=e=>xC.test(e)||bC.some(t=>t.test(e)),IC=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,SC=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,EC=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,_t=e=>IC.test(e)||SC.test(e)||EC.test(e),uh=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),mh=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),ph=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),CC=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,RC=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,fh=e=>CC.test(e),gh=e=>RC.test(e);var hh=/\b(TODO|FIXME|HACK|XXX)\b/,NC=/[;{}]\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"},AC=(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},yh=({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(hh.test(x)&&i++,I==="blank"){s++;continue}if(I==="comment"){r++,v.comment++,f&&NC.test(AC(x,f))&&c++;continue}o++,v.code++}for(let{text:x}of p.removedLines)hh.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 TC=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,oa=6,dc=10,wC=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)},MC=(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)},PC=e=>{if(e.length<oa*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let r=0;r+oa<=e.length;r++){let o=e.slice(r,r+oa);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<oa;l++)n[i.at+l]=!0,n[r+l]=!0}return n.filter(Boolean).length},vh=({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)),uh(p.path)&&n.push(on(p)),mh(p.path)&&r.push(on(p)),ph(p.path)&&(o=!0),p.binary||_t(p.path))continue;let f=p.added.map(x=>x.text),g=wC(f),v=p.status!=="deleted";for(let x of f){TC.test(x)&&s++;let I=MC(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:PC(c)}};var bh=({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 LC=200,lc=2e5,kC=5e4,xh=25,DC=64*1024*1024,cc="",BC=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/,FC=/^diff --git a\/(.+) b\/\1$/,Ih=(e,t)=>e==="/dev/null"?null:e.startsWith(t)?e.slice(2):e,Sh=(e,t)=>e===null?"added":t===null?"deleted":"modified",OC=()=>({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=FC.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,Sh(x==="/dev/null"?null:x,I==="/dev/null"?null:I)),o.entry.binary=!0;continue}if(l&&f.startsWith("--- ")){i=Ih(f.slice(4),"a/");continue}if(l&&f.startsWith("+++ ")){let v=Ih(f.slice(4),"b/"),x=v??i??s;x&&(o=p(x,Sh(i,v)));continue}let g=BC.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<kC&&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))}}}},UC=e=>({files:[...e.byPath.values()].map(t=>t.entry),insertions:e.insertions,deletions:e.deletions,selfChurn:e.selfChurn,retainedLines:e.retainedLines});var Eh=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,LC).reverse(),r=OC(),o=0,s=0,i=!1;for(let c=0;c<n.length;c+=xh){let m=n.slice(c,c+xh),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>DC){i=!0;break}}let l=UC(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 jC=40,$C=/^\d{6} blob ([0-9a-f]{40})\t(.+)$/,Ch=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=$C.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<jC&&(I.push({blob:g,path:v}),o.set(x,I))}let s=[...o.values()].flat(),i=await Rs(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 Rh=({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)fh(c)&&s++,gh(c)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:r,deletedTestFiles:o,skippedTestLinesAdded:s,focusedTestLinesAdded:i}};var HC=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,Nh=async({repoRoot:e,ref:t,commits:n})=>{let r=await Eh({repoRoot:e,shas:n.map(l=>l.sha)});if(d(r))return a(r.message);let o=r.value,s=HC(n),i=s?await Ch({repoRoot:e,sha:s}):null;return u("Derived issue stats",{ref:t,shape:dh({commits:n,patch:o}),languages:bh({patch:o,languagesBefore:i?.languages??null}),tests:Rh({patch:o}),comments:yh({patch:o,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:vh({patch:o})})};var WC=32,os=new Map;var GC=(e,t)=>{if(os.set(e,t),os.size>WC){let n=os.keys().next();n.done||os.delete(n.value)}return t},sa=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 Ji({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 Nh({repoRoot:o,ref:n,commits:i});return d(m)?a(m.message):u("Derived issue stats",GC(l,m.value))};var VC="Filed here",Ah=(e,t)=>e.set(t,(e.get(t)??0)+1),Th=(e,t,n)=>[...e.entries()].map(([r,o])=>({laneId:r,title:r===null?VC:n(r),count:o,share:t===0?0:o/t})).sort((r,o)=>o.count-r.count||r.title.localeCompare(o.title)),wh=(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++,Ah(r,l[c-1]??null);let p=l[c+1];p!==void 0&&(i++,Ah(o,p))}return{arrived:s,departed:i,arrivesFrom:Th(r,s,n),movesOnTo:Th(o,i,n)}};var Mh=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,zC=({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:Mh(c.sort((p,f)=>p-f)),count:c.length}))]))},Ph=({laneId:e,journeys:t,now:n,days:r})=>zC({laneIds:[e],journeys:t,now:n,days:r})[e];var KC=40,qC=30,YC=()=>({tickets:0,commits:0,insertions:0,deletions:0}),XC=async(e,t)=>{let n=YC();for(let r of t.slice(0,KC)){let o=await sa({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},Lh=async e=>{let t=X();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=>Sl(c.log??[],Re(c.id))),i=wh(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:Re(e.swimlaneId),...i,stayTrend:Ph({laneId:e.swimlaneId,journeys:s,now:Date.now(),days:qC}),code:await XC(e.repoRoot,l)})};var kh=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 Dh=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}))},Bh=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),Fh=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}),ia=e=>L.object({type:L.literal(e)}),JC=L.discriminatedUnion("type",[ia("state:get"),ia("issues:list"),ia("sync"),ia("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:Fh.optional()})),se("issues:move",L.object({issueId:K,parentId:K,position:Fh.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}))]);var Oh=e=>{let t=JC.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 ZC=1024*1024,uc=()=>{tr({type:"state",payload:hr(fr())})},re=(e,t)=>{e.send(JSON.stringify(t))},as=async(e,t)=>{let n=hr(await Et({repoRoot:t}));return d(n)&&n.message===Ga?re(e,{type:"state:unavailable",payload:{message:n.message,repoRoot:t,recentProjects:Dh(t)}}):re(e,{type:"state",payload:n})},eR=async(e,t)=>{let n=()=>re(e,{type:"state",payload:hr(fr())});if(tt().mode!=="live")return n();let r=await Et({repoRoot:t});return tt().mode!=="live"?n():re(e,{type:"state",payload:hr(r)})},We=async(e,t,n,r,o)=>{if(re(e,{type:r,payload:o}),d(o))return re(e,{type:"failed",payload:o.message});n(),eR(e,t)},_h=(e,t,{onStateChanged:n,getPort:r})=>{new QC({server:e,path:"/ws",maxPayload:ZC,verifyClient:s=>!sc(s.origin,r())}).on("connection",s=>{vm(s),s.on("message",async i=>{let l=async c=>{let{type:m}=c,p=t.repoRoot;if(m==="project:open"){let f=Bh(c.payload.root);return re(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 re(s,{type:"timeline",requestId:f,payload:await Wg({repoRoot:p,...g})})}if(m==="issue:get"){let f=c.payload?.issueId,g=fr(),v=Hl(f);return re(s,{type:"issue",payload:d(g)?g:u("Issue detail",{...sh(g.value,f),history:d(v)?[]:v.value})})}if(m==="commits:get"){let{requestId:f,...g}=c.payload??{};return re(s,{type:"commits",requestId:f,payload:await Tl({repoRoot:p,...g})})}if(m==="commit:inspect")return re(s,{type:"commit:inspect:result",payload:await Vg({repoRoot:p,sha:c.payload.sha})});if(m==="commit:diff:get"){let{sha:f}=c.payload;return re(s,{type:"commit:diff:result",payload:{sha:f,result:await zg({repoRoot:p,sha:f})}})}if(m==="issue:commits:get"){let{issueId:f}=c.payload;return re(s,{type:"issue:commits:result",payload:{issueId:f,result:await Ji({repoRoot:p,ref:_(f)})}})}if(m==="issue:stats:get"){let{issueId:f}=c.payload;return re(s,{type:"issue:stats:result",payload:{issueId:f,result:await sa({repoRoot:p,idOrRef:_(f)})}})}if(m==="swimlane:stats:get"){let{swimlaneId:f}=c.payload;return re(s,{type:"swimlane:stats:result",payload:{swimlaneId:f,result:await Lh({repoRoot:p,swimlaneId:f})}})}if(m==="time-travel:scrub"){let f=await wl({repoRoot:p,targetTime:c.payload.targetTime});return re(s,{type:"time-travel:result",payload:f}),d(f)?void 0:uc()}if(m==="time-travel:checkout-event"){let f=await qg({repoRoot:p,eventId:c.payload.eventId});return re(s,{type:"time-travel:result",payload:f}),d(f)?void 0:uc()}if(m==="time-travel:live"){let f=await Yg({repoRoot:p});return re(s,{type:"time-travel:result",payload:f}),d(f)?void 0:uc()}if(m==="state:get")return as(s,p);if(m==="sync"){let f=await qo({repoRoot:p});return re(s,{type:"sync:result",payload:f}),n(),as(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 re(s,{type:"issue:comment:delete:result",payload:f}),d(f)?re(s,{type:"failed",payload:f.message}):(n(),as(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 re(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 re(s,{type:"issues",payload:await Ol({repoRoot:p})});if(m==="issues:create"){let f=await _l({...c.payload,repoRoot:p});return re(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 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 re(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 re(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 re(s,{type:"error",message:"Unknown message type"})};try{let c=Oh(JSON.parse(i.toString()));if(!c.ok)return re(s,{type:"error",message:c.error});let m=c.message;return kh.has(m.type)?await Wn(async()=>tt().mode!=="live"?re(s,{type:"failed",payload:"Read-only while viewing history"}):l(m)):await l(m)}catch(c){return re(s,{type:"error",message:c instanceof Error?c.message:String(c)})}})})};var rR=vr.dirname(nR(import.meta.url)),oR=process.env.IS_LOCAL==="true"?vr.resolve(process.cwd(),"dist/gui"):vr.join(rR,"gui"),aa,sR=async()=>(aa===void 0&&(aa=await import("node:sea").catch(()=>null)),aa?.isSea()?aa:null),Ee=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},iR=e=>Ee(e,409,{isError:!0,message:"Read-only while viewing history"}),da=(e,t)=>Wn(async()=>tt().mode!=="live"?iR(e):t()),Uh=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)}),aR=2*1024*1024,dR={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},lR=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",jh=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=vr.resolve(oR),o=vr.resolve(r,n),s=vr.relative(r,o);if(s.startsWith("..")||vr.isAbsolute(s))return Ee(t,403,{isError:!0,message:"Forbidden"});let i=await sR();try{let l=i?Buffer.from(i.getAsset(`gui/${s}`)):await $h(o);return t.writeHead(200,{"content-type":lR(o)}),t.end(l)}catch{return Ee(t,404,{isError:!0,message:`Not found: ${n}`})}},cR=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)}),Hh=async e=>{Mg(!1);let t=0,n={repoRoot:e.repoRoot},r=tR.createServer(async(i,l)=>{let c=new URL(i.url??"/","http://127.0.0.1"),m=ah({method:i.method,origin:i.headers.origin,contentType:i.headers["content-type"]},t);if(m)return Ee(l,m.status,{isError:!0,message:m.message});if(i.method==="GET"&&c.pathname===rc)return Ee(l,200,{app:oc,repoRoot:ta(n.repoRoot),version:rn,pid:process.pid});if(c.pathname==="/api/state")return Ee(l,200,await Et({repoRoot:n.repoRoot}));if(i.method==="POST"&&c.pathname==="/api/comments")try{let p=await Uh(i);if(!p.issueId||!p.body?.trim())return Ee(l,400,{isError:!0,message:"Missing issueId or body"});let f=p.issueId,g=p.body;return await da(l,async()=>{let v=await es({repoRoot:n.repoRoot,issueId:f,body:g});return d(v)?Ee(l,400,{isError:!0,message:v.message}):Ee(l,200,await Et({repoRoot:n.repoRoot}))})}catch(p){return Ee(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 Uh(i,aR);if(!p.issueId||!p.dataBase64)return Ee(l,400,{isError:!0,message:"Missing issueId or dataBase64"});let f=p.issueId,g=p.dataBase64,v=p.name??"";return await da(l,async()=>{let x=await Pl({repoRoot:n.repoRoot,issueId:f,name:v,dataBase64:g});return d(x)?Ee(l,400,{isError:!0,message:x.message}):Ee(l,200,{...await Et({repoRoot:n.repoRoot}),attachment:x.value})})}catch(p){return Ee(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?da(l,async()=>{let f=await Ll({repoRoot:n.repoRoot,attachmentId:p});return d(f)?Ee(l,400,{isError:!0,message:f.message}):Ee(l,200,await Et({repoRoot:n.repoRoot}))}):Ee(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 Ee(l,404,{isError:!0,message:f.message});try{let g=await $h(f.value.filePath);return l.writeHead(200,{"content-type":dR[f.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),l.end(g)}catch{return Ee(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?da(l,async()=>{let f=await ts({repoRoot:n.repoRoot,commentId:p});return d(f)?Ee(l,400,{isError:!0,message:f.message}):Ee(l,200,await Et({repoRoot:n.repoRoot}))}):Ee(l,400,{isError:!0,message:"Missing comment id"})}return c.pathname.startsWith("/board/")?jh("/",l):jh(c.pathname,l)});try{t=await cR(r)}catch(i){return a(i instanceof Error?`Unable to start GUI server: ${i.message}`:`Unable to start GUI server: ${String(i)}`)}let o=ih({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 Gh=async e=>{let t=Ir({});if(d(t))return a(t.message);let n=ht();ce(n)&&ze(n.value);let r=await oh(ns);if(r&&r.repoRoot===ta(e.repoRoot)){let i=`http://127.0.0.1:${ns}`;return console.log(`Epiq GUI already running for this project at ${Wh.cyan(i)}`),Xa(i),u("Reused running GUI",{url:i})}let o=await Hh({...e,boardId:""});if(d(o))return o;let{url:s}=o.value;return console.log(`Epiq GUI running at ${Wh.cyan(s)}`),Xa(s),u("Started GUI",{url:s})};import{Box as Kn}from"ink";import Ce from"react";import{Box as mc,Text as ds}from"ink";import Ut,{useEffect as uR,useMemo as mR}from"react";import{ulid as pR}from"ulid";var Vh=({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))},zh=pR(),fR=e=>`${e}`,gR=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=bi(i),c=$i.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))},hR=e=>ge.text({id:zh,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),yR=(e,t,n)=>ge.text({id:fR(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),pc=[],vR=e=>{Kh();let t=C.createNode(hR(h().rootNodeId));d(t)||!Nn(t.value)||(pc=[t.value,...e.map((n,r)=>yR(n,r,zh)).map(C.createNode).filter(ce).map(({value:n})=>n).filter(Nn)],O.navigate({contextNode:t.value,selectedIndex:0}))},Kh=()=>{let e=pc.map(t=>t.id);pc=[];for(let t of e)C.deleteNode(t)};function qh({width:e,height:t}){let r=wp().value.trim().toLowerCase(),o=mR(()=>gR(r),[r]);uR(()=>(vR(o),()=>{Kh()}),[o]);let s=h().selectedIndex;return Ut.createElement(mc,{flexDirection:"column",width:e,height:t-2},Ut.createElement(xt,{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(mc,{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(Vh,{text:hu(i.command),match:r,color:m,dimColor:!i.isAvailable})),Ut.createElement(mc,{paddingLeft:2},Ut.createElement(Vh,{text:p+i.description,match:r.length>=2?r:"",color:c&&i.isAvailable?y.primary:y.secondary2,dimColor:!i.isAvailable})))})))}import{Box as kR}from"ink";import ua from"react";import cs from"chalk";import{Box as fc,Text as Qh}from"ink";import ls,{useEffect as Zh,useMemo as bR,useState as ey}from"react";var Qr=["\u2803","\u2806","\u2830","\u2818"],Yh=120,Xh=({isPalette:e,isPending:t,frame:n})=>{if(t){let r=(n%Qr.length+Qr.length)%Qr.length;return Qr[r]}return e?"?":":"},Jh=({infoMessage:e,isPending:t})=>t&&e.includes(le)?"":e;var ty=cs.hex(y.secondary),xR=cs.inverse,IR=cs.inverse.hex(y.secondary2),SR={hint:"",hints:[],overlap:0,remainder:""},ry=({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}},ER=({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 _d(t)},CR=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=ry({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}},ny=()=>({value:qe.value,cursorPosition:qe.cursorPosition,commandIsPending:qe.commandIsPending,autoCompletion:qe.commandMeta.autoCompletion??SR,infoMessage:qe.commandMeta.infoMessage,validationStatus:qe.commandMeta.validity,command:qe.commandMeta.command,inputString:qe.commandMeta.inputString,modifier:qe.commandMeta.modifier}),RR=(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,oy=({width:e,mode:t})=>{let[n,r]=ey(ny());Zh(()=>{let w=()=>{let k=ny();r(D=>RR(D,k)?D:k)},M=Hd(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=Jh({infoMessage:i,isPending:l}),[x,I]=ey(0);Zh(()=>{if(!l){I(0);return}let w=setInterval(()=>{I(M=>(M+1)%Qr.length)},Yh);return()=>{clearInterval(w)}},[l]);let R=Xh({isPalette:t===b.PALETTE,isPending:l,frame:x}),A=bR(()=>{let w=Math.max(0,Math.min(s,o.length)),M=ry({value:o,command:m}),k=CR({value:o,command:m,modifier:p}),D=m?_d(m):null,ve=ER({command:m,modifier:p}),Ve=(lt,ct)=>{let Ra=M&&ct>=M.start&&ct<M.end,Na=k&&ct>=k.start&&ct<k.end;return Ra&&D?D.fg(lt):Na&&ve?ve.bg(lt):lt},Nt=(lt,ct)=>{let Ra=M&&ct>=M.start&&ct<M.end,Na=k&&ct>=k.start&&ct<k.end;return Ra&&D?D.fgCursor(lt):Na&&ve?ve.bgCursor(lt):xR(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=Nt(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=IR(lt),ro=ty(c.remainder.slice(1)+Sn)}return qn+vs+ro},[o,s,c,m,p]);return ls.createElement(fc,{flexDirection:"column",justifyContent:"flex-start"},ls.createElement(fc,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},ls.createElement(fc,null,ls.createElement(Qh,null,ty(R),A),v&&ls.createElement(Qh,{wrap:"truncate",color:g?y.red:y.secondary2},` ${v} `))))};import{Box as NR,Text as us}from"ink";import Zr from"react";var sy=" ",AR=({keys:e,label:t})=>e.length+1+t.length,TR=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?sy.length:0)+AR(o);if(r+i>t-4)break;n.push(o),r+=i}return n},iy=({width:e,availableHints:t})=>{let n=TR(t,e);return Zr.createElement(NR,{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?sy:"",Zr.createElement(us,{color:y.accent},o),Zr.createElement(us,{color:y.secondary2}," ",s)))):Zr.createElement(us,{color:y.secondary2},"\xA0"))};import{Box as wR,Text as la}from"ink";import ms,{useEffect as MR,useRef as eo,useState as PR}from"react";var LR=40,ca=.3,gc="\u2500",ay=1,dy=16,ly=({width:e})=>{let{replay:t}=Y(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*ay,[l,c]=PR(0),m=eo(r);m.current=r;let p=eo(0),f=eo(0),g=eo(0),v=eo(0),x=eo(0);if(MR(()=>{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-ca)+qn*ca,x.current=x.current===0?ke:x.current*(1-ca)+ke*ca}p.current=D,f.current=k,g.current=D}let ve=k-f.current,Ve=Math.min(x.current,v.current*ve),Nt=Math.min(1,p.current+Ve),dt=Math.round(Nt*i);c(ke=>ke===dt?ke:dt)},LR);return()=>clearInterval(M)},[n,i]),!t)return null;let I=M=>{let k=s>1?M/(s-1):0,D=Math.round(k*(dy-1))/(dy-1);return mi(D)},R=Math.min(s,Math.floor(l/ay)),A=[];for(let M=0;M<R;M++){let k=I(M),D=A[A.length-1];D&&D.color===k?D.text+=gc:A.push({text:gc,color:k})}let w=gc.repeat(Math.max(0,s-R));return ms.createElement(wR,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1,columnGap:1},ms.createElement(la,{color:y.secondary2},"\u25B6"),ms.createElement(la,null,A.map((M,k)=>ms.createElement(la,{key:k,color:M.color},M.text)),ms.createElement(la,{color:y.secondary,dimColor:!0},w)))};var ps=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=Y(),o=t===b.COMMAND_LINE||t===b.PALETTE;return ua.createElement(kR,null,o?ua.createElement(oy,{width:e,mode:t}):r==="replay"?ua.createElement(ly,{width:e}):ua.createElement(iy,{width:e,mode:t,availableHints:n}))};import{Box as Gn,Text as to}from"ink";import nt,{useEffect as DR,useMemo as BR}from"react";import{ulid as cy}from"ulid";var pa=cy(),FR=()=>[...new Set([...h().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(hl).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})),OR=e=>ge.text({id:pa,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),_R=(e,t,n)=>ge.text({id:cy(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),ma=[],uy=()=>{let e=ma.filter(n=>n.id!==pa).map(n=>n.id),t=ma.filter(n=>n.id===pa).map(n=>n.id);ma=[];for(let n of[...e,...t])C.deleteNode(n)},UR=e=>{uy();let t=C.createNode(OR(h().rootNodeId));if(d(t)||!Nn(t.value))return logger.error("Could not attach help nodes");ma=[t.value,...e.map((n,r)=>_R(n,r,pa)).map(C.createNode).filter(ce).map(({value:n})=>n).filter(Nn)],O.navigate({contextNode:t.value,selectedIndex:0})},my=({width:e,height:t})=>{let n=BR(()=>FR(),[]);DR(()=>(UR(n),()=>{uy()}),[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(xt,{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 jR from"chalk";import{Box as br,Text as Ue}from"ink";import pe from"react";var $R=8,HR=()=>{let e=bn({exclude:process.cwd()});return d(e)?[]:e.value.slice(0,$R)},py=({width:e,height:t})=>{let n=HR();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 ${jR.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 fa,Text as sn}from"ink";import Ge from"react";var WR=({isDone:e,command:t,value:n})=>Ge.createElement(fa,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+">"))),GR=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function hc({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(fa,{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(fa,{flexDirection:"column"},c.map((f,g)=>m===-1||g<=m?Ge.createElement(fa,{key:f.key,marginBottom:1},Ge.createElement(WR,{isDone:f.done,command:f.command,value:f.done?GR(f.value):void 0})):null)))}import ba from"chalk";import{Box as gs,Text as no}from"ink";import Le from"react";import{Box as ga,Text as fy}from"ink";import Vn from"react";import VR from"chalk";var zR=e=>(C.getTag(e)?.name??"").length+3,KR=e=>{let t=C.getContributor(e);return(t?t.name:"").length+3},gy=({width:e})=>{let{viewMode:t}=ie(),n=Y(),{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?!Il(o.id,m.parentNodeId)&&t==="dense":!1,v=r.map((D,ve)=>{let Ve=ve===r.length-1,Nt=ae(D.id),dt=Ve?Nt?.[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+zR(ve),0)+f.reduce((D,ve)=>D+KR(ve),0)+I:0,A=l?.id!=null&&!(t==="wide"&&P(l)),w=Math.max(0,e-R),M=v.substring(0,w)+(A?VR.hex(y.secondary2).dim(` ${_(l.id)}`):""),k=g?[...p.map(D=>Vn.createElement(ga,{key:`tag-${D}`,paddingLeft:1},Vn.createElement(_r,{id:D}))),...f.map(D=>Vn.createElement(ga,{key:`assignee-${D}`,paddingLeft:1},Vn.createElement(Bn,{id:D}))),x.length?Vn.createElement(ga,{key:"comments",paddingLeft:1},Vn.createElement(fy,{color:y.accent},"[",x.length," comment",x.length===1?"":"s","]")):null]:[];return Vn.createElement(ga,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},Vn.createElement(fy,{color:y.secondary2},M),k)};import{Box as qR,Text as hy}from"ink";import ha from"react";var YR=({filters:e})=>ha.createElement(qR,{columnGap:1},ha.createElement(hy,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>ha.createElement(hy,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),yy=ha.memo(YR);import{Box as XR,Text as ya}from"ink";import fs from"react";function vy(){let{eventLog:e,unappliedEvents:t}=Y(),n=e.at(-1)?.id,r=ks(n??""),o=ce(r)?Ci(r.value):"INVALID DATE";return fs.createElement(XR,{paddingLeft:1},fs.createElement(ya,{backgroundColor:y.accent,color:y.secondary}," Readonly "),fs.createElement(ya,{color:y.accent}," "+t.length+" edits ago at "+o+"."),fs.createElement(ya,{color:y.accent}," Resume with "),fs.createElement(ya,{backgroundColor:y.accent,color:y.secondary}," ",":peek now"," "))}import{Box as JR,Text as yc}from"ink";import va from"react";function by(){let{replay:e}=Y();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return va.createElement(JR,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},va.createElement(yc,{backgroundColor:y.accent,color:y.secondary}," \u25B6 REPLAY "),va.createElement(yc,{color:y.secondary2},Ci(new Date(r))),va.createElement(yc,{color:y.accent},`${t}/${n} edits`))}import vc from"chalk";import{Box as QR,Text as xy}from"ink";import bc,{useEffect as ZR,useState as eN}from"react";var tN=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],nN=150,Iy=12,rN=.36,Sy=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=Sy(e),o=Sy(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 Ey({syncStatus:e,autoSync:t}){let[n,r]=eN(0);ZR(()=>{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*(Iy-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/(Iy-1))??""}[e.status];return bc.createElement(QR,null,bc.createElement(xy,null,vc.hex(y.secondary2).dim(t?"Sync (auto): ":"Sync: ")),bc.createElement(xy,null,vc.hex(i)("\u25CF")+vc.hex(y.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import Ty from"chalk";import{Text as wy}from"ink";import My,{useEffect as cN,useState as uN}from"react";import xc from"chalk";var aN="https://registry.npmjs.org/epiq/latest",Ic=null,Cy=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},Ny=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(Ic&&Date.now()-Cy<dN)return Ic;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 Ic=o,Cy=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},Ay=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?xc.hex(y.accent).dim(s):xc.hex(y.secondary).dim(s)).join(xc.hex(y.secondary2).dim("."))};function Py(){let[e,t]=uN({current:rn,latest:null,updateAvailable:!1});return cN(()=>{let n=!0;return Ny(rn).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?My.createElement(wy,{dimColor:!0,color:y.secondary2},rn+" "):My.createElement(wy,null,Ty.hex(y.secondary2).dim(rn),Ty.hex(y.accent).dim(" \u2197 "),Ay(rn,e.latest))}function hs({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=Y(),{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(yy,{filters:e}):Le.createElement(gy,{width:p})),n==="live"?Le.createElement(gs,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},Le.createElement(Ey,{autoSync:!!c,syncStatus:r}),Le.createElement(no,null,ba.hex(y.secondary2).dim("Mode: ")+ba.hex(y.secondary2).dim(o.padEnd(8," "))," "),Le.createElement(Ly,{icon:"@",value:i}),Le.createElement(Ly,{icon:"\u276F",value:l}),Le.createElement(Py,null)):"",n==="peek"?Le.createElement(vy,null):"",n==="replay"?Le.createElement(by,null):"")}function Ly({icon:e,value:t}){return Le.createElement(no,null,ba.dim(e)+ba.hex(y.accent)(` ${t??"-"} `))}import{Box as mN,Text as pN}from"ink";import ys from"react";import{Box as xa,Text as Sc}from"ink";import zn from"react";function Ec(){let e=Y(),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(xa,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:y.secondary,width:s},zn.createElement(xa,{padding:1,paddingTop:0,paddingBottom:0},zn.createElement(Sc,null,"Select a board:")),zn.createElement(xa,{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(xa,{key:l.id??c},zn.createElement(Sc,{color:m?y.accent:y.secondary2},zn.createElement(Ye,{isSelected:m})),zn.createElement(Sc,{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}=Y(),c=n.find(({context:g})=>g==="BOARD"),f=s-1-3;return ys.createElement(mN,{flexDirection:"row"},e.context==="WORKSPACE"?ys.createElement(Ec,null):c?ys.createElement(Ai,{height:f,width:i,swimlanes:(l[c.id]??[]).filter(g=>g!==void 0&&Pt(g)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):ys.createElement(pN,null))},ky=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&&oi(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},Dy=({autoSync:e})=>(hN(e),null);function Cc({width:e,height:t}){let n=Y(),{autoSync:r,viewMode:o}=au(),s=n.filters;if(n.mode===b.HELP)return Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(my,{width:e,height:t}));if(n.mode===b.PALETTE)return Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(hs,{filters:s}),Ce.createElement(qh,{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(hc,{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(py,{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(Dy,{autoSync:r}),Ce.createElement(Kn,{flexDirection:"column"},Ce.createElement(hs,{filters:s}),Ce.createElement(ky,{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 Ia,Sa,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]),By=async e=>{if(e.ctrl&&e.name==="c")return O.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=h(),s=Mp(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 By(n))},IN=()=>async function(t){if(t.length===1&&t[0]===27){an&&clearTimeout(an),an=setTimeout(()=>{By({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),an=void 0},25);return}an&&(clearTimeout(an),an=void 0)};function Fy(){Ia&&process.stdin.removeListener("keypress",Ia),Sa&&process.stdin.removeListener("data",Sa),Ia=xN(),Sa=IN(),yN.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Sa),process.stdin.on("keypress",Ia)}async function Oy(){try{let e=Ir({});if(d(e))return Bt(0,e.message);let t=ht();ce(t)&&ze(t.value);let n=xe(process.cwd()),r=ce(n)?await ki(n.value):Of();if(d(r))return r;let o=Rc();return d(o)?Bt(6,o.message):(Fy(),ce(n)&&Di(n.value),u("Booted Epiq",void 0))}catch(e){return Bt(0,Tr(e))}}yf();var RN=`${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
|
+
`,Nc=EN(RN,{importMeta:import.meta,version:rn,flags:{init:{type:"boolean",default:!1},as:{type:"string"}}}),Ea=Nc.input[0];Ea&&Ea!=="gui"&&(console.error(jt.red(`Unknown command: ${Ea}`)),process.exit(1));if(Nc.flags.as!==void 0){let e=wa(Nc.flags.as,"--as");d(e)&&(console.error(jt.red(e.message)),process.exit(1))}var _y=process.stdout.columns||120,Uy=process.stdout.rows||20,Ca=null,NN=e=>{try{return Ca?(Ca.rerender(e),u("Rerendered app",void 0)):(Ca=SN(e),u("Rendered app",void 0))}catch(t){return a(`Unable to render app: ${Tr(t)}`)}},Rc=()=>NN(CN.createElement(Cc,{width:_y,height:Uy}));process.stdout.on("resize",()=>{if(_y=process.stdout.columns||120,Uy=process.stdout.rows||20,!Ca)return;let e=Rc();d(e)&&logger.info(`[boot:resize] ${e.message}`)});if(Ea==="gui"){let e=await Gh({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 Oy();d(e)&&(logger.info(e.message),console.error(jt.red(`Failed to boot Epiq:
|
|
102
|
+
${e.message}`)),process.exitCode=1)}export{Rc as renderApp};
|