epiq 1.10.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gui/main.js +113 -113
- package/dist/index.js +91 -91
- package/dist/mcp.js +89 -89
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,116 +1,116 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`,"utf8"),u("Created project.json",null)}catch(o){return c(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 un from"chalk";import{render as HM}from"ink";import WM from"meow";import GM from"react";import Jb from"chalk";import Xx from"node:crypto";var Zn={Success:"success",Fail:"fail"},c=e=>({status:Zn.Fail,message:e,value:null}),u=(e,t)=>({status:Zn.Success,message:e,value:t}),a=e=>e.status==="fail",ye=e=>e.status==="success";var Dn="EPIQ_USER_NAME",ki="EPIQ_USER_ID",Im="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Jx=26,Jl=80,Ql=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),Di=e=>e.trim().length>0&&e.length<=Jl,lo=e=>e.trim().toLowerCase(),Qx=e=>{let t=Xx.createHash("sha256").update(`epiq:actor:${lo(e)}`).digest(),n="";for(let r=0;r<Jx;r++)n+=Im[(t[r]??0)%Im.length];return n},co=(e,t=process.env)=>{let n=(t[Dn]??"").trim(),r=(t[ki]??"").trim();return n?Di(n)?!r&&e.userId&&e.userName&&lo(e.userName)===lo(n)?u("Actor override names the configured user",{userId:e.userId,userName:e.userName}):r&&!Ql(r)?c(`${ki} must be 26 characters of Crockford base32`):r&&e.userId&&r===e.userId?c(`${ki} 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||Qx(n),userName:r?n:lo(n)}):c(`${Dn} must be 1-${Jl} characters of text`):r?c(`${ki} is set without ${Dn}`):u("No actor override",null)},Zl=(e,t,n=process.env)=>{let r=e.trim();if(!Di(r))return c(`${t} must be 1-${Jl} characters of text`);let o=(n[Dn]??"").trim();return o&&lo(o)!==lo(r)?c(`${t} names ${r}, but ${Dn} names ${o}`):(o||(n[Dn]=r),u("Applied actor name argument",o||r))};import PI from"node:path";import{z as Jt}from"zod";var uo=e=>{let t=typeof e=="number"?e:Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<3e3||t>864e5?null:t},mo=e=>e==null||!Number.isFinite(e)?1e4:Math.min(864e5,Math.max(1,e));import ms from"node:fs";import pn from"node:path";import er from"node:fs";import It from"node:path";import is from"node:fs";import{ulid as Zx}from"ulid";import{z as Bi}from"zod";var eI="__epiq_state__",tI=Bi.object({projectId:Bi.string().min(1),stateBranch:Bi.string().min(1),createdAt:Bi.iso.datetime()}),Oi=()=>({projectId:Zx(),stateBranch:eI,createdAt:new Date().toISOString()}),Tt=e=>{let t=po(e);if(!is.existsSync(t))return c("Missing .epiq/project.json");try{let n=is.readFileSync(t,"utf8"),r=JSON.parse(n),o=tI.safeParse(r);return o.success?u("Read project.json",o.data):c(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return c(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},mn=e=>{let t=Tt(e);return a(t)?c(t.message):u("Read projectId",t.value.projectId)},ec=({repoRoot:e,fileContents:t})=>{let n=Pr(e),r=po(e);try{if(is.mkdirSync(n,{recursive:!0}),is.existsSync(r)){let o=Tt(e);return a(o)?c(o.message):u("Project already initialized",null)}return is.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,"utf8"),u("Created project.json",null)}catch(o){return c(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};import nI from"node:os";import rI from"node:path";var qt=".epiq-global",Bn=()=>process.env.EPIQ_GLOBAL_DIR??rI.join(nI.homedir(),qt);var tc=(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(d=>(a(d)&&n.delete(i),d));n.set(i,l)}return n.get(i)});return o.clear=()=>n.clear(),o};import Yt from"fs";import ic from"path";import oI from"util";var Em=500,ac=4*1024*1024,nc=16*1024,sI=50,rc=0,Sm=()=>process.env.EPIQ_MCP==="true",iI=()=>{let e=process.cwd(),t=Fi(e);return a(t)?Sm()?ic.join(Bn(),"epiq-mcp.log"):void 0:ic.join(t.value,ft,"log","epiq.log")},aI=(e,t)=>{let n=Yt.statSync(e).size;if(n<=t)return Yt.readFileSync(e,"utf8");let r=Yt.openSync(e,"r");try{let o=Buffer.alloc(t);Yt.readSync(r,o,0,t,n-t);let s=o.toString("utf8"),i=s.indexOf(`
|
|
4
|
+
`);return i===-1?"":s.slice(i+1)}finally{Yt.closeSync(r)}};function lI(e){if(!Yt.existsSync(e))return;let t=Yt.statSync(e).size,n=aI(e,ac).split(`
|
|
5
|
+
`);if(n[n.length-1]===""&&n.pop(),t<=ac&&n.length<=Em)return;let r=n.slice(-Em).join(`
|
|
6
6
|
`)+`
|
|
7
|
-
`;
|
|
8
|
-
`;try{
|
|
7
|
+
`;Yt.writeFileSync(e,r,"utf8")}var cI=e=>{if(e.length<=nc)return e;let t=e.length-nc;return`${e.slice(0,nc)} \u2026 [${t} more chars]`};function oc(e,t,n=!1){let r=iI();if(!r)return;let o=cI(oI.format(...t)),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
8
|
+
`;try{Yt.mkdirSync(ic.dirname(r),{recursive:!0}),Yt.appendFileSync(r,l,"utf8"),rc++,(rc>=sI||Yt.statSync(r).size>ac)&&(rc=0,lI(r))}catch{}}var sc=()=>Sm()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",ne={info(...e){let t=sc();(t==="info"||t==="debug")&&oc("[Info]",e,!1)},debug(...e){sc()==="debug"&&oc("[Debug]",e,!0)},error(...e){let t=sc();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;oc("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=ne;import{spawn as Cm}from"node:child_process";import Mt from"node:fs";import xt from"node:path";var Ce={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 ke=e=>{let t=ce(e);if(a(t))return c("Unable to resolve epiq project root");let n=Tt(t.value);return a(n)?c("Unable to read project.json"):u("Resolved state branch",n.value.stateBranch)},wt="origin";var lc=1e4,dI=12e4,uI=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),mI=e=>{let t=e.find((n,r)=>!n.startsWith("-")&&e[r-1]!=="-c");return t&&uI.has(t)?dI:lc},pI=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(xt.delimiter))if(t)for(let n of e){let r=xt.join(t,n);try{if(!Mt.statSync(r).isFile())continue;return Mt.accessSync(r,Mt.constants.X_OK),r}catch{continue}}return"git"},Nm=pI(),Am={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Tm=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Mt.existsSync(t)){let f=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:f,exitCode:1});return}r(c(f));return}let o=Cm(Nm,e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Am}),s=!1,i="",l="",d=f=>{s||(s=!0,clearTimeout(p),r(f))},m=mI(e),p=setTimeout(()=>{o.kill("SIGTERM");let f=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${m}ms`].join(`
|
|
9
9
|
`);d(n?{stdout:i,stderr:f,exitCode:124}:c(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){d({stdout:i,stderr:f.message,exitCode:1});return}d(c([`git ${e.join(" ")}`,`cwd=${t}`,f.message].join(`
|
|
10
10
|
`)))}),o.on("close",f=>{let g=f??1;if(n){d({stdout:i,stderr:l,exitCode:g});return}if(g!==0){d(c([`git ${e.join(" ")}`,l.trim()||i.trim()||"Git command failed"].filter(Boolean).join(`
|
|
11
|
-
`)));return}d(u("Git command succeeded",{stdout:i,stderr:l,exitCode:g}))})}),j=({args:e,cwd:t})=>
|
|
12
|
-
${s}`:""}`));return}let p=Buffer.concat(o),f=new Map,g=0;for(let
|
|
11
|
+
`)));return}d(u("Git command succeeded",{stdout:i,stderr:l,exitCode:g}))})}),j=({args:e,cwd:t})=>Tm({args:e,cwd:t,allowFail:!1}),Le=({args:e,cwd:t})=>Tm({args:e,cwd:t,allowFail:!0}),_i=(e,t)=>new Promise(n=>{if(e.length===0){n(u("No blobs to read",new Map));return}let r=Cm(Nm,["cat-file","--batch"],{cwd:t,stdio:["pipe","pipe","pipe"],env:Am}),o=[],s="",i=!1,l=m=>{i||(i=!0,clearTimeout(d),n(m))},d=setTimeout(()=>{r.kill("SIGTERM"),l(c(`git cat-file --batch timed out after ${lc}ms`))},lc);r.stdout.on("data",m=>o.push(m)),r.stderr.setEncoding("utf8"),r.stderr.on("data",m=>{s+=m}),r.on("error",m=>l(c(m.message))),r.on("close",m=>{if(m!==0){l(c(`git cat-file --batch exited ${m}${s?`
|
|
12
|
+
${s}`:""}`));return}let p=Buffer.concat(o),f=new Map,g=0;for(let h of e){let x=p.indexOf(10,g);if(x===-1){l(c(`git cat-file --batch output ended before a header for ${h}`));return}let b=p.toString("utf8",g,x);g=x+1;let N=/^[0-9a-f]{4,64} \S+ (\d+)$/.exec(b);if(!N||!N[1]){l(c(`Unexpected git cat-file --batch header: "${b}"`));return}let S=Number(N[1]);f.set(h,p.toString("utf8",g,g+S)),g+=S+1}l(u("Read blobs",f))}),r.stdin.write(e.join(`
|
|
13
13
|
`)+`
|
|
14
|
-
`),r.stdin.end()}),
|
|
14
|
+
`),r.stdin.end()}),go=async({cwd:e,message:t,pathspec:n})=>{let r=await Ce.commit({cwd:e,message:t,pathspec:n});if(a(r))return c(`Failed to create commit
|
|
15
15
|
${r.message}`);let o=await j({args:["rev-parse","HEAD"],cwd:e});return a(o)?c(`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(
|
|
18
|
-
${t.stderr.trim()}`):u("Aborted stale rebase",!0)},
|
|
19
|
-
${o.message}`);let s=await
|
|
20
|
-
${s.message}`);let i=await
|
|
21
|
-
`+r.message);let o=
|
|
22
|
-
`+o.message):u("Ensured epiq storage",n)},
|
|
23
|
-
`,
|
|
24
|
-
`,
|
|
16
|
+
${o.message}`):u("Created commit and resolved SHA",o.value.stdout.trim())},$i=async e=>{let t=await j({cwd:e,args:["rev-parse","--git-dir"]});if(a(t))return c(t.message);let n=t.value.stdout.trim();return u("Resolved git dir",xt.isAbsolute(n)?n:xt.resolve(e,n))},cc=async e=>{let t=await $i(e);if(a(t))return c(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(r))if(Mt.existsSync(xt.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(Mt.existsSync(xt.join(n,s)))return u("Checked for in-progress Git operation",i);return u("Checked for in-progress Git operation",null)},wm=async e=>{let t=await cc(e);return a(t)?c(t.message):u("Checked for in-progress Git operation",t.value!==null)},On=async({repoRoot:e})=>{let n=(await Le({args:["remote","get-url",wt],cwd:e})).exitCode===0;return u(`Checked remote ${n}`,n)},as=async({repoRoot:e,branch:t})=>{let n=await Le({args:["ls-remote","--heads",wt,t],cwd:e});return n.exitCode!==0?c(n.stderr.trim()||`Unable to inspect remote branch ${wt}/${t}`):u("Checked remote branch",n.stdout.trim().length>0)},Ui=async({repoRoot:e,branch:t})=>{let n=await Le({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):c(n.stderr.trim()||`Unable to inspect branch ${t}`)},fo=e=>{try{return Mt.realpathSync.native(e)}catch{return xt.resolve(e)}},Mm=async({repoRoot:e,worktreeRoot:t})=>{let n=await j({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return c(n.message);let r=fo(t),o=n.value.stdout.split(`
|
|
17
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(fo).includes(r);return u("Checked worktree registration",o)},dc=async e=>{let t=await Le({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return u("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},ji=async e=>{let t=await j({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?c(t.message):u("Resolved current branch",t.value.stdout.trim())},Pm=async e=>{let t=await j({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?c(t.message):u("Resolved short HEAD sha",t.value.stdout.trim())},Lm=e=>e.includes("fetch first")||e.includes("non-fast-forward"),km=async e=>{let t=await Le({cwd:e,args:["rev-parse","--absolute-git-dir"]});if(t.exitCode!==0)return!1;let n=t.stdout.trim();return n?Mt.existsSync(xt.join(n,"rebase-merge"))||Mt.existsSync(xt.join(n,"rebase-apply")):!1},fI=3,gI=120,hI=e=>new Promise(t=>setTimeout(t,e)),yI=async(e,t)=>{let n=await Ce.rebaseOnto({cwd:e,ref:t});for(let r=1;r<fI;r+=1){if(!a(n)||await km(e))return n;await hI(gI),n=await Ce.rebaseOnto({cwd:e,ref:t})}return n},Dm=async(e,{preserve:t=[]}={})=>{let n=await $i(e);if(a(n))return c(n.message);let r=n.value,o=[];for(let s of Mt.readdirSync(r))if(s.endsWith(".lock")&&!t.includes(s))try{Mt.rmSync(xt.join(r,s),{force:!0}),o.push(s)}catch{}return u("Cleared stale git lock files",o)},Bm=async(e,t)=>{let n=await Le({cwd:e,args:["rev-parse","--git-common-dir"]});if(n.exitCode!==0)return c(`Unable to resolve the common git directory at ${e}`);let r=xt.resolve(e,n.stdout.trim()),o=xt.join(r,"refs","heads"),s=xt.resolve(o,`${t}.lock`);if(!s.startsWith(`${o}${xt.sep}`))return c(`Refusing to clear a ref lock outside ${o}`);if(!Mt.existsSync(s))return u("No ref lock to clear",!1);try{Mt.rmSync(s,{force:!0})}catch{return u("Ref lock could not be cleared",!1)}return u("Cleared a stale ref lock",!0)},uc=async e=>{if(!await km(e))return u("No rebase to abort",!1);let t=await Le({cwd:e,args:["rebase","--abort"]});return t.exitCode!==0?c(`Failed to abort the rebase in progress at ${e}
|
|
18
|
+
${t.stderr.trim()}`):u("Aborted stale rebase",!0)},Rm=async e=>{let t=await Le({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},ls=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),vI=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),cs=async({cwd:e,branch:t})=>{let n=await uc(e);if(a(n))return c(n.message);let r=await Rm(e),o=await Ce.fetch({cwd:e,remote:wt,branch:t});if(a(o))return vI(o.message)?u("Remote branch missing, skipped pull",!1):c(`Failed to fetch ${t}
|
|
19
|
+
${o.message}`);let s=await yI(e,`${wt}/${t}`);if(a(s))return c(`Failed during rebase
|
|
20
|
+
${s.message}`);let i=await Rm(e),l=r!==null&&i!==null&&r!==i;return u(l?"Pulled with rebase":"Already up to date",l)},Om=async e=>{let t=await Le({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)},Fm=async e=>{let t=await Le({args:["status","--porcelain","--untracked-files=all"],cwd:e});return t.exitCode!==0?c(t.stderr.trim()||"Unable to inspect the worktree for changes"):u("Inspected worktree for changes",t.stdout.trim().length>0)},_m=async(e,t)=>{let n=await Le({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):c(n.stderr.trim()||"Unable to inspect staged changes")};var $m=async e=>{let t=await ji(e);return a(t)?c(t.message):u("Checked detached HEAD state",t.value==="HEAD")};var Hm="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Wm=e=>It.join(ft,Fn,e),Gm=()=>It.join(ft,fc),Vm=Bn,Lr=()=>It.join(Vm(),"worktrees"),fe=({repoRoot:e})=>{let t=mn(e);return a(t)?c(t.message):u("Resolved state branch root",It.join(Lr(),t.value))},bI=e=>It.join(e,ft),Um=e=>It.join(bI(e),Fn);var ds=e=>{try{return er.mkdirSync(e,{recursive:!0}),u("Ensured directory",void 0)}catch(t){return c(t instanceof Error?t.message:String(t))}},us=()=>{let e=Vm(),t=Lr(),n=!er.existsSync(e)||!er.existsSync(t),r=ds(e);if(a(r))return c(`Ensure epiq home failed.
|
|
21
|
+
`+r.message);let o=ds(t);return a(o)?c(`Ensure worktrees dir failed.
|
|
22
|
+
`+o.message):u("Ensured epiq storage",n)},zm=e=>{er.existsSync(e)&&(ne.debug("[sync] remove path",e),er.rmSync(e,{recursive:!0,force:!0}))};var xI=`*.jsonl merge=union
|
|
23
|
+
`,II=`*~pending*.jsonl
|
|
24
|
+
`,mc=()=>It.join(ft,Fn,".gitattributes"),pc=()=>It.join(ft,Fn,".gitignore"),jm=(e,t)=>{try{er.readFileSync(e,"utf8")!==t&&er.writeFileSync(e,t)}catch{er.writeFileSync(e,t)}},Km=(e,t)=>{for(let n of[Um(e),Um(t)]){let r=ds(n);if(a(r))return c(r.message)}return jm(It.join(t,mc()),xI),jm(It.join(t,pc()),II),u("Ensured state branch",void 0)},qm=async e=>{let t=await j({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return c(`ensure state branch is storage only failed
|
|
25
25
|
`+t.message);let r=t.value.stdout.trim().split(`
|
|
26
|
-
`).filter(Boolean).filter(i=>i!==
|
|
27
|
-
${o.message}`);let s=await
|
|
28
|
-
`),u("Config written",null)}catch{return c(`Unable to write ~/${Vt}/config.json`)}},Bt=e=>{let t=pn();if(a(t))return c("Failed to read existing config");let n={...t.value,...e};return Qm(n)},ht=()=>{let e=gc(),t=hc();if(a(t))return c(`Unable to create ~/${Vt}`);if(!(ot.readFile(e)!==null)){let b=Qm(AI);if(a(b))throw new Error(`Unable to create ~/${Vt}/config.json`)}let r=pn();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,declinedEmailBoards:l,autoSync:d,autoSyncDebounceMs:m,attachmentMaxKb:p,logLevel:f,viewMode:g}=r.value,y=lo({userId:i,userName:s});if(a(y))return c(y.message);let x=y.value??{userId:i,userName:s};return!x.userName||!x.userId?c(`User name or ID not configured in ~/${Vt}/config.json`):(process.env.EPIQ_LOG_LEVEL=f,u("successfully loaded settings",{gitEmail:null,gitName:null,declinedEmailBoards:l??[],logLevel:f??"debug",preferredEditor:o??"",userName:x.userName,userId:x.userId,autoSync:d??!1,autoSyncIntervalMs:m??1e4,attachmentMaxKb:p??null,viewMode:g??"dense"}))};import{useSyncExternalStore as MI}from"react";var fs={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,gitEmail:null,gitName:null,declinedEmailBoards:[],viewMode:null},yc=new Set,PI=()=>{for(let e of yc)e()},V=()=>fs,Zm=()=>MI(e=>(yc.add(e),()=>{yc.delete(e)}),()=>fs),je=e=>(fs={...fs,...e},PI(),fs);import{spawn as LI}from"node:child_process";import vc from"node:process";var bc=e=>{let t=vc.platform==="darwin"?"open":vc.platform==="win32"?"cmd":"xdg-open",n=vc.platform==="win32"?["/c","start","",e]:[e];LI(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as Wb,stat as dw}from"node:fs/promises";import{createHash as uw}from"node:crypto";import Er from"chalk";import Rv from"string-width";import{decodeTime as ep}from"ulid";var Hi=1440*60*1e3,gs=(e,t=Date.now())=>e>t+Hi?t:e,Be=e=>gs(ep(e)),ho=e=>{let t=Date.now()+Hi,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})},yo=e=>{try{return u("Decoded date",new Date(Be(e)))}catch(t){return c("Decoding failed + "+t.message)}},er=e=>{if(!e?.id)return null;try{return ep(e.id)}catch{return null}};import vo from"chalk";var at={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},h={accent:at.cyan,accent2:at.magenta,primary:at.white,secondary:at.grayDark,secondary2:at.grayLight,gray:at.gray,green:at.green,yellow:at.yellow,red:at.red};var L={red:at.red,yellow:at.yellow,green:at.green,blue:at.blue,magenta:at.magenta,cyan:at.cyan},Wi={urgent:L.red,critical:L.red,important:L.red,blocker:L.red,asap:L.red,immediate:L.red,fail:L.red,failure:L.red,broken:L.red,bug:L.red,error:L.red,incident:L.red,outage:L.red,production:L.red,crash:L.red,security:L.red,warning:L.yellow,warn:L.yellow,risky:L.yellow,risk:L.yellow,attention:L.yellow,pending:L.yellow,review:L.yellow,"needs-review":L.yellow,qa:L.yellow,testing:L.yellow,test:L.yellow,validate:L.yellow,verification:L.yellow,staging:L.yellow,check:L.yellow,"follow-up":L.yellow,followup:L.yellow,waiting:L.yellow,blocked:L.yellow,hold:L.yellow,done:L.green,complete:L.green,completed:L.green,success:L.green,ok:L.green,stable:L.green,resolved:L.green,fixed:L.green,closed:L.green,merged:L.green,released:L.green,deployed:L.green,approved:L.green,verified:L.green,working:L.green,healthy:L.green,pass:L.green,passing:L.green,info:L.blue,information:L.blue,note:L.blue,docs:L.blue,documentation:L.blue,doc:L.blue,guide:L.blue,help:L.blue,explanation:L.blue,detail:L.blue,details:L.blue,context:L.blue,design:L.blue,discussion:L.blue,proposal:L.blue,idea:L.blue,feature:L.magenta,enhancement:L.magenta,improvement:L.magenta,refactor:L.magenta,refactoring:L.magenta,cleanup:L.magenta,optimize:L.magenta,optimization:L.magenta,perf:L.magenta,performance:L.magenta,upgrade:L.magenta,migration:L.magenta,modernize:L.magenta,debt:L.magenta,todo:L.cyan,next:L.cyan,planned:L.cyan,plan:L.cyan,future:L.cyan,backlog:L.cyan,investigate:L.cyan,explore:L.cyan,prototype:L.cyan};var Ic={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},tp=(e,t,n)=>Math.max(t,Math.min(n,e)),xc=(e,t,n)=>e+(t-e)*n,np=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},kI=e=>e.toLowerCase().trim(),DI=(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)),d=0,m=0,p=0;i>=0&&i<1?(d=s,m=l):i>=1&&i<2?(d=l,m=s):i>=2&&i<3?(m=s,p=l):i>=3&&i<4?(m=l,p=s):i>=4&&i<5?(d=l,p=s):(d=s,p=l);let f=o-s/2;return[Math.round((d+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},rp=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var BI=(e,t,n)=>{let r=tp(n,0,1);return[Math.round(xc(e[0],t[0],r)),Math.round(xc(e[1],t[1],r)),Math.round(xc(e[2],t[2],r))]};var OI=(e,t,n)=>BI(e,t,n),Ec=e=>{let t=np(e)%360,n=DI(t,Ic.stringColor.saturation,Ic.stringColor.lightness);return rp(n)},qe=(e,t=Wi)=>{let n=kI(e??"");return n&&t[n]?t[n]:Ec(n)};var op=e=>{let t=Ic.gradient.stops,n=tp(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 OI(t[s],t[s+1],i)},Gi=e=>rp(op(e)),Vi=e=>np(e.toLowerCase().trim())/4294967295,sp=e=>{let t=Vi(e);return op(t)},FI=e=>{let[t,n,r]=sp(e);return{normal:o=>vo.bgRgb(t,n,r).black(o),cursor:o=>vo.bgRgb(t,n,r).white.bold(o)}},Sc=e=>{let[t,n,r]=sp(e);return{fg:o=>vo.rgb(t,n,r)(o),fgCursor:o=>vo.rgb(t,n,r).inverse(o),bg:o=>vo.bgRgb(t,n,r).black(o),bgCursor:o=>vo.bgRgb(t,n,r).white.bold(o)}},zi=e=>FI(e).normal(` ${e} `);var _I="Unknown",Ki=(e,t)=>t?.length?t:e?.length?e:_I,Ye=(e,t)=>{let n=Ki(e,t);return{id:e?.length?e:n,name:n,color:qe(n)}};var bo="removed",yt=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?u("Found node",n):c("Unable to find node in breadcrumb")},ip=["png","jpg","gif","webp"];var et=e=>e.trim().toLowerCase(),tr=e=>{let t=et(e);return t.length>0&&t.length<=254&&/^[^\s@]+@[^\s@]+$/.test(t)},hs=(e,t)=>`${et(e)} ${t}`,Rc=e=>!e.tombstoned,ys=(e,t)=>{let n=et(t),r=new Set;for(let o of Object.values(e))Rc(o)&&o.email===n&&r.add(o.contributor);return[...r]},fn=(e,t)=>{let n=new Set;for(let r of Object.values(e))Rc(r)&&r.contributor===t&&n.add(r.email);return[...n]},ap=e=>{let t=new Map;for(let r of Object.values(e)){if(!Rc(r))continue;let o=t.get(r.email)??new Set;o.add(r.contributor),t.set(r.email,o)}let n=new Map;for(let[r,o]of t){let[s]=[...o];o.size===1&&s&&n.set(r,s)}return n};var qi=(e,t)=>e===t.authorId||e===t.contributor;var ie={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function Cc(e){return e.context===ie.WORKSPACE}function _(e){return e.context===ie.TICKET}function nr(e){return e.context===ie.TEXT}function lt(e){return e.context===ie.FIELD}function vs(e){return e.context===ie.FIELD_LIST}var gn=e=>e.context===ie.SWIMLANE,rr=e=>e.context===ie.BOARD,bs=e=>e.context===ie.COMMENT;import{useSyncExternalStore as lA}from"react";var I={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette",IDENTITY:"identity"};var lp=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",cp=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",dp=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",up=(e,t)=>{if(cp(e,e.sequence))return E.MoveCursorLeftOfWord;if(dp(e,e.sequence))return E.MoveCursorRightOfWord;if(lp(e,e.sequence))return E.EraseInputWord;switch(e.name){case"tab":return E.AutoCompleteCommand;case"up":return E.GetLastCommandFromHistory;case"down":return E.GetNextCommandFromHistory;case"left":return E.MoveCursorLeft;case"right":return E.MoveCursorRight;case"return":return E.Confirm;case"backspace":return t?E.EraseInput:E.ExitCommandLine;case"escape":return E.ExitCommandLine;default:return E.CaptureInput}},mp=(e,t)=>{if(cp(e,e.sequence))return E.MoveCursorLeftOfWord;if(dp(e,e.sequence))return E.MoveCursorRightOfWord;if(lp(e,e.sequence))return E.EraseInputWord;switch(e.name){case"tab":return E.AutoCompleteCommand;case"up":return E.NavPreviousItem;case"down":return E.NavNextItem;case"left":return E.MoveCursorLeft;case"right":return E.MoveCursorRight;case"return":return E.Confirm;case"backspace":return t?E.EraseInput:E.ExitCommandLine;case"escape":return E.ExitCommandLine;default:return E.CaptureInput}};import pp from"string-width";function Yi(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)+"...",$I=/\u001B\[[0-9;]*m/,Nc="\x1B[0m",UI=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),_n=(e,t)=>{if(t<=0)return"";if(pp(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($I.test(l)){o+=l,i=l!==Nc&&l!=="\x1B[m";continue}for(let d of UI(l)){let m=pp(d);if(s+m>r)return`${o}...${i?Nc:""}`;o+=d,s+=m}}return`${o}...${i?Nc:""}`},Re=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),fp=e=>e.charAt(0).toUpperCase()+e.slice(1);var gp=e=>{let t=new Map;for(let n of e){let r=n.toLowerCase();for(let o=1;o<=n.length;o++){let s=r.slice(0,o),i=t.get(s);i?i.push(n):t.set(s,[n])}}return t},hp=(e,t)=>t?e.get(t)??[]:[];var yp=new WeakMap,jI=e=>{let t=yp.get(e);return t||(t=gp(e),yp.set(e,t)),t};var vp=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return hp(jI(e),r).filter(s=>Yi(r,s.toLowerCase())>=n)};var HI={hint:"",hints:[],overlap:0,remainder:""},xp=({inputToMatch:e,lastWord:t,isLastWordCompleted:n,inputString:r},o,s=[])=>{if(n||e===""){let[l]=s;return s.length===1&&l&&!r.trim()?bp("",[l]):HI}let i=vp({wordList:o,inputToMatch:e,overlapThreshold:1});return bp(t,i)},bp=(e,t)=>{let n=t[0]??"",r=Yi(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 xs from"node:fs";import Is from"node:path";import{z as xo}from"zod";var Xi="recent-projects.json",WI=20,GI=xo.object({projectId:xo.string().min(1),root:xo.string().min(1),lastOpenedAt:xo.number().finite()}),VI=xo.object({projects:xo.array(GI)}),Ep=()=>Is.join(Dn(),Xi),Io=e=>Is.basename(e)||e,Ip=e=>{let t=Is.resolve(e);try{return xs.realpathSync(t)}catch{return t}},Sp=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Rp=e=>{if(!ps(e.root))return!1;let t=dn(e.root);return!a(t)&&t.value===e.projectId},Cp=()=>{let e=Ep();if(!xs.existsSync(e))return u("No recent projects recorded",[]);let t;try{t=JSON.parse(xs.readFileSync(e,"utf8"))}catch(r){return c(`Invalid ${Xi}: ${r instanceof Error?r.message:String(r)}`)}let n=VI.safeParse(t);return n.success?u("Read recent projects",n.data.projects):c(`Invalid ${Xi} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},zI=e=>{let t=Ep();try{xs.mkdirSync(Is.dirname(t),{recursive:!0}),xs.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
29
|
-
`,"utf8")}catch(n){return c(`Unable to write ${Xi}: ${n instanceof Error?n.message:String(n)}`)}return u("Recorded recent project",e)},$n=({exclude:e}={})=>{let t=Cp();if(a(t))return t;let n=e===void 0?null:Ip(e);return u("Listed recent projects",t.value.filter(r=>n===null||Ip(r.root)!==n).filter(Rp).sort(Sp))},Ji=({root:e,now:t=Date.now()})=>{let n=Is.resolve(e),r=dn(n);if(a(r))return c(r.message);let o=r.value,s=Cp(),i=a(s)?[]:s.value,l=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(d=>d.projectId!==o&&d.root!==n)].filter(Rp).sort(Sp).slice(0,WI);return zI(l)};var Ac=null,Np=e=>{Ac=e},Ap=e=>Ac?Ac(e):[];var Tp=[],Eo=e=>{Tp=e},So=()=>Tp;var Un=()=>{let e=V(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1,o=wp(),s=o.length>0?null:Tc(),i=s!==null&&(e.declinedEmailBoards??[]).includes(s),l=o.length>0||i||s===null;return{isSetupDone:n&&t&&r&&l,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r,isSetEmails:l,claimedEmails:o,emailSetupDeclined:i}},Tc=()=>{let e=me(process.cwd());if(a(e))return null;let t=dn(e.value);return a(t)?null:t.value||null},wp=()=>{let{userId:e}=V();return e?Ap(e):[]},Mp=()=>wp().length>0;var wc=()=>{let e=me(process.cwd());if(a(e))return!1;let t=Tt(e.value);return be(t)},Pp=e=>e===!0?"on":e===!1?"off":null,Lp=e=>e==="on"?!0:e==="off"?!1:null,kp=()=>{let e=Un();if(!e.isSetUserName)return"config username ";if(!e.isSetPreferredEditor)return"config editor ";if(!e.isSetAutoSync)return"config autoSync ";if(!wc())return"init";if(!e.isSetEmails){let{gitEmail:t}=V(),n=So()[0]??t;return n&&tr(n)?`config emails ${n}`:"config emails "}return null};var KI=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ye,Qi]=KI;var qI=e=>e.props.tags??[],YI=e=>e.props.assignees??[],hn=e=>qI(e).map(t=>N.getTag(t)).filter(t=>!!t),yn=e=>YI(e).map(t=>N.getContributor(t)).filter(t=>!!t),Zi=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!_(n)?c("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",hn(n))},ea=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!_(n)?c("Invalid unassign target"):u("Retrieved assignees from ticket in breadcrumb",yn(n))};var C={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 XI=/^(\d+)(h|d|w|mo|y)$/,JI=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,QI=({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},ZI=(e,t=new Date)=>{let n=e.match(XI);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}},eE=e=>{let t=e.match(JI);if(!t)return null;let[,n,r,o,s,i]=t,l=Number(n),d=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return QI({year:l,month:d,day:m,hour:p,minute:f})?new Date(l,d-1,m,p,f):null},Lr=e=>{let t=e.trim().toLowerCase();return ZI(t)??eE(t)};var Dp=/^(\d+)(s|m)?$/,ta=e=>{let t=e.trim().toLowerCase().match(Dp);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},na=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Dp.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Bp=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,tE=[{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}],Mc=(e=tE)=>{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 nE=["BOARD","TICKET","SWIMLANE","COMMENT"],ve={EDITOR:"editor",VIEW:"view",USERNAME:"username",EMAILS:"emails",EMAILS_UNCLAIM:"emails-unclaim",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},Mt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Xe={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},rE=[ve.EDITOR,ve.VIEW,ve.USERNAME,ve.EMAILS,ve.EMAILS_UNCLAIM,ve.AUTOSYNC,ve.SYNC_DEBOUNCE_MS,ve.ATTACHMENT_MAX_KB,ve.LOG_LEVEL],oE=(e=v().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[]}},Lc=[String(3e3),"5000","15000","30000","60000"],kc=["250","500","1000"],_p=["10s","20s","30s","45s"],kr=[C.EXIT,C.SYNC,C.HELP,C.EXPORT,C.CONFIG,C.YANK],ra=[C.NEW,C.EDIT,C.DELETE,C.MOVE],Pc=[C.TAG,C.UNTAG,C.ASSIGN,C.UNASSIGN,C.CLOSE_ISSUE,C.RE_OPEN_ISSUE,C.EDIT,C.COMMENT],Op=[C.FILTER,C.PEEK,C.REPLAY],sE={WORKSPACE:[...kr,...ra],BOARD:[...Op,...kr,...ra],SWIMLANE:[...Op,...kr,...ra],TICKET:[...kr,...ra,...Pc],FIELD:[...kr,...Pc],FIELD_LIST:[...kr,...Pc],TEXT:[...kr],COMMENT:[C.EDIT,C.DELETE,C.YANK]},iE=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Es=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&_(n)),Fp=e=>e.parentNodeId===ye,aE=({selectedNode:e,breadCrumb:t})=>{let n=oE(e?.context);return Es({breadCrumb:t,selectedNode:e})?n.includes(Mt.DESCRIPTION)?n:[...n,Mt.DESCRIPTION]:n},lE=({selectedNode:e,breadCrumb:t})=>{let n=Es({breadCrumb:t,selectedNode:e});return n?[Xe.REF,Xe.TITLE,...n.props?.description?.trim()?[Xe.DESCRIPTION]:[],...hn(n).length>0?[Xe.TAGS]:[],...yn(n).length>0?[Xe.ASSIGNEES]:[]]:e?[Xe.REF,Xe.TITLE]:[]},Dc=()=>{let e=$n({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},cE=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Un();if(!r)return[C.HELP,C.CONFIG];if(!wc())return[C.HELP,C.INIT,C.OPEN];if(t)return[C.HELP,C.PEEK,C.REPLAY,C.EXPORT,C.CONFIG,C.YANK];let o=e?.context,s=o&&nE.includes(o),i=[...new Set([...n,e].map(d=>d?.context).flatMap(d=>d?sE[d]:[]))],l=Es({breadCrumb:n,selectedNode:e});return i.filter(d=>d===C.MOVE?!1:d===C.YANK?!!(l??e):d===C.EDIT?s||!!l:d===C.DELETE?s:d===C.UNTAG?!!(l&&hn(l).length>0):d===C.UNASSIGN?!!(l&&yn(l).length>0):d===C.RE_OPEN_ISSUE?!!(l&&Fp(l)):d===C.CLOSE_ISSUE?!!(l&&!Fp(l)):!0)},Oe=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let s=t.context??"WORKSPACE";return{[C.NONE]:cE({breadCrumb:o,readOnly:r,selectedNode:n}),[C.EXIT]:["confirm"],[C.EXPORT]:[],[C.SYNC]:[],[C.INIT]:[],[C.OPEN]:e===C.OPEN?Dc():[],[C.HELP]:[],[C.PEEK]:[...Mc(),"now","prev","next"],[C.REPLAY]:[...Mc()],[C.EDIT]:aE({selectedNode:n,breadCrumb:o}),[C.YANK]:lE({selectedNode:n,breadCrumb:o}),[C.COMMENT]:[],[C.DELETE]:["confirm"],[C.RE_OPEN_ISSUE]:["confirm"],[C.CLOSE_ISSUE]:["confirm"],[C.MOVE]:["start","confirm","next","previous","jump-next","jump-previous","to-next","to-previous","cancel"],[C.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[C.TAG]:[...new Set([...Object.keys(Wi),...N.getExistingTags()])],[C.UNTAG]:[...Zi()?.value?.map(({name:l})=>l)??[]],[C.UNASSIGN]:[...ea()?.value?.map(({name:l})=>l)??[]],[C.ASSIGN]:N.getExistingAssignees(),[C.NEW]:iE(s),[C.CONFIG]:[...rE]}[e]??[]};import Qp from"chalk";var $p=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import fE from"zod";import dE from"node:crypto";import Ss from"node:fs";import Hp from"node:path";var Up="/media/",jp=e=>`${Up}${e}`,Bc=(e,t)=>`})`;var vn=500,uE=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,Br=(e,t)=>`${e}.${t}`,mE=e=>uE.test(e),Wp=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"):c(`Unsupported image format. Allowed: ${ip.join(", ")}`),Gp=e=>dE.createHash("sha256").update(e).digest("hex"),pE=(e,t=vn)=>{if(e.length===0)return c("Attachment is empty");if(e.length>t*1024)return c(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=Wp(e);return a(n)?n:u("Validated attachment data",{hash:Gp(e),ext:n.value,bytes:e.length})},Vp=(e,t,n=vn)=>{let r=pE(t,n);if(a(r))return r;let o=ms(e),s=Hp.join(o,Br(r.value.hash,r.value.ext));try{Ss.existsSync(s)||(Ss.mkdirSync(o,{recursive:!0}),Ss.writeFileSync(s,t))}catch(i){return c(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return u("Wrote attachment blob",r.value)},zp=(e,t,n=vn)=>{if(!mE(t))return c("Invalid attachment file name");let r=Hp.join(ms(e),t);if(!Ss.existsSync(r))return c("Attachment blob not found");let o;try{o=Ss.readFileSync(r)}catch(d){return c(`Unable to read attachment blob: ${d instanceof Error?d.message:String(d)}`)}if(o.length>n*1024)return c(`Attachment exceeds the ${n} KB size cap and will not be served`);let[s,i]=t.split(".");if(Gp(o)!==s)return c("Attachment blob does not match its content hash");let l=Wp(o);return a(l)?l:l.value!==i?c("Attachment blob content does not match its extension"):u("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var Rs=50,Cs=5e3,Kp=()=>{let e=ae().commandMeta.inputString,t=fE.coerce.number().int().min(Rs).max(Cs).safeParse(e);if(!t.success)return c(`Attachment size cap must be ${Rs}-${Cs} KB (default ${vn})`);let n=Bt({attachmentMaxKb:t.data});return a(n)?n:(je({attachmentMaxKb:t.data}),u(`Attachment size cap set to ${t.data} KB`,null))};var ct=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null;import{createHash as gE}from"node:crypto";var hE="0123456789ABCDEFGHJKMNPQRSTVWXYZ",yE=e=>{let t=gE("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+=hE[Number(n>>s&31n)]}return r},qp=new Map,Pe=(e,t)=>{let n=`${e}:virtual:${t}`,r=qp.get(n);if(r!==void 0)return r;let o=yE(n);return qp.set(n,o),o};import Yp from"chalk";var Ce=e=>Yp.dim(e),He=e=>Yp.hex(h.primary)(e),We=({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)=>Vi(f)-Vi(g)).slice(0,r).map(f=>zi(f)).join(" ");return p?`${Ce(e)}${p}${Ce(n)}`:""};var bn={None:"none",Invalid:"invalid",Valid:"valid"};var vE=["BOARD","TICKET","SWIMLANE"],Xp=()=>{let e=v().selectedNode;if(!e?.context)return z({message:Ce("Missing target context")});if(vE.includes(e.context))return le();if(e.parentNodeId){let t=v().nodes[e.parentNodeId];if(t?.id===Pe(t?.parentNodeId??"","comments"))return le()}return z({message:Ce("Command not available in this context")})},fe="<ENTER> to confirm",bE=()=>{let{userId:e}=V(),t=xe();return!e||a(t)?[]:fn(t.value.emailLinks,e)},le=(e="",t=[],n=!0)=>({message:n?Ce(e):e,validity:bn.Valid,completionWordList:t}),z=({message:e,completionWordList:t=[]})=>({validity:bn.Invalid,message:e,completionWordList:t}),Co=e=>e.length===0,Jp=(e,t)=>{let n=yt(v().breadCrumb,"BOARD");if(a(n))return z({message:He("Command is not applicable in this context")});let r=yo(n.value.id);return a(r)?z({message:He(`Unable to ${t}: board id is not a valid ULID`)}):Bp({date:e,horizonDate:r.value})?null:z({message:He(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},oa=e=>` ${Qp.hex("#000").bgHex(qe(e))(` ${e} `)} `,Oc=({modifier:e})=>{let t="confirm";return e===t?le(fe):z({message:Co(e)?Ce("if you are certain, enter ")+zi(t):"",completionWordList:[t]})},xE=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?z({message:Ce(n)}):le():z({message:Co(r)?t:"",completionWordList:[...e]}),Ro=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>Co(n)&&Co(r)?z({message:e,completionWordList:[]}):le(t??fe),IE=({modifier:e,inputString:t})=>{let n=Dc();return!Co(e)||!Co(t)?le(fe):z({message:n.length?Ce("number from the list, or a path"):Ce("path to an epiq project"),completionWordList:n})},EE=({modifier:e,inputString:t})=>{let n=Oe(C.CONFIG);if(!n.includes(e))return z({message:We({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ve.EDITOR:{let r=[...$p];return t.trim()?r.includes(t.trim())?le(fe):z({message:We({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):z({message:We({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ve.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?le(fe):z({message:We({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ve.USERNAME:{let r=V().gitName,o=r?[r]:[],s=t.trim(),i=o.filter(m=>m.startsWith(s)),d=i.length===1&&i[0]===s?"":We({prefix:"name: ",wordList:o,inputString:s,minLengthForHints:0});return s?d?le(`${d} ${Ce(fe)}`,o,!1):le(fe,o):z({message:d||He("Enter a user name. Saved in ")+Qp.bgBlack("~/.epiq-global/config.json"),completionWordList:o})}case ve.EMAILS:{let r=V().gitEmail,o=So(),s=o.length>0||!r?o:[r],i=[...s,"none"],l=t.trim(),d=(x,b)=>z({message:We({prefix:x,wordList:i,noOfHints:3,inputString:b,minLengthForHints:0}),completionWordList:i});if(!l)return le(`${fe} to see your addresses, or name one`,i);let m=l.split(/[,\s]+/).filter(Boolean),p=m[m.length-1]??"",f=x=>x==="none"||s.includes(x.toLowerCase()),g=x=>i.some(b=>b.startsWith(x.toLowerCase())),y=m.filter(x=>!f(x)&&!g(x));return y.length>0?z({message:He(`no address here matches ${y.join(", ")} \u2014 pick one from the list, or its number`),completionWordList:i}):f(p)?le(fe):d("",p)}case ve.EMAILS_UNCLAIM:{let r=bE(),o=t.trim();return r.length===0?z({message:He("you have not claimed any addresses"),completionWordList:[]}):o&&r.includes(o.toLowerCase())?le(fe):z({message:We({prefix:"give an address back ",wordList:r,noOfHints:3,inputString:o,minLengthForHints:0}),completionWordList:r})}case ve.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?le(fe):z({message:We({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ve.AUTOSYNC:{let r=["on","off"],o=V().autoSync;if(!r.includes(t.trim())){let s=Pp(o);return z({message:We({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return le(fe)}case ve.ATTACHMENT_MAX_KB:{let r=V().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<Rs||o>Cs){let s=We({prefix:" examples: ",wordList:kc,minLengthForHints:0,inputString:t});return z({message:He(`provide a size cap in KB (${Rs}-${Cs}). current: ${r??vn} KB.`)+s,completionWordList:kc})}return le(fe)}case ve.SYNC_DEBOUNCE_MS:{let r=V().autoSyncIntervalMs,o=co(t);if(!t.trim()||o===null){let s=We({prefix:" examples: ",wordList:Lc,minLengthForHints:0,inputString:t});return z({message:He(`provide a duration between ${3e3}ms and ${864e5}ms. current duration: ${r}ms.`)+s,completionWordList:Lc})}return le(fe)}default:return z({message:He("Unknown config option"),completionWordList:n})}},SE=({modifier:e,inputString:t})=>{let n=Oe(C.EDIT);if(!n.length)return z({message:He("Command not available in this context")});if(!n.includes(e)){let r=We({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return z({message:r||He("Unknown edit option"),completionWordList:n})}switch(e){case Mt.COMMENT:return t.trim()?le(fe):z({message:Ce("write a comment...")});case Mt.TITLE:return le(fe);case Mt.DESCRIPTION:{let{preferredEditor:r}=V();return r?le(Ce("<ENTER> to edit in ")+r):z({message:"No editor selected"})}default:return z({message:He("Unknown edit option"),completionWordList:n})}},RE=({modifier:e})=>{let t=Oe(C.YANK);return t.length?t.includes(e)?le(fe+Ce(" and copy to clipboard")):z({message:We({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):z({message:He("Nothing selected to copy from")})},CE={[C.EXPORT]:()=>le(fe+Ce(", and create export markdown file")),[C.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return le(fe);let n={message:Ce("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Lr(r);if(!r||!o)return z(n);let s=Jp(o,"peek");return s||le(fe)},[C.REPLAY]:e=>{let{dateInput:t,durationInput:n}=na(e.modifier,e.inputString),r={message:Ce("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Lr(t);if(!t||!o)return z(r);let s=Jp(o,"replay");return s||(n&&ta(n)===null?z({message:He("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):le("<ENTER> to replay board history",n?_p:[]))},[C.EXIT]:()=>le(fe+Ce(" and exit the application")),[C.INIT]:()=>le(fe),[C.OPEN]:IE,[C.PALETTE]:()=>le(fe),[C.FILTER]:e=>{if(e.modifier==="clear")return le(fe);let t=s=>Oe(C.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return z({message:We({wordList:Oe(C.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Oe(C.FILTER)});let n=Object.values(v().tags).map(s=>s.name),r=Object.values(v().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?z({message:We({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):le():z({message:We({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[C.NONE]:e=>{let t=Oe(C.NONE);return z({message:We({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[C.NEW]:e=>xE({list:Oe(C.NEW),hint:We({wordList:Oe(C.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[C.HELP]:()=>le(fe),[C.EDIT]:SE,[C.COMMENT]:e=>{let t=Ro({hint:Ce(`write a comment (max ${4e3} char)...`),onOk:Ce(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===bn.Invalid?t:e.inputString.length>4e3?le(He("max input exceeded")):t},[C.CONFIG]:EE,[C.YANK]:RE,[C.DELETE]:e=>{let t=Xp();return t.validity==="invalid"?t:Oc(e)},[C.CLOSE_ISSUE]:e=>Oc(e),[C.RE_OPEN_ISSUE]:e=>Oc(e),[C.MOVE]:e=>{let t=Xp();return t.validity==="invalid"?t:Ro({hint:We({prefix:"hey hacker! These commands are blocked for you... ",wordList:Oe(C.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[C.TAG]:e=>{let n=N.getExistingTags().slice(0,10).map(oa).join("");return Ro({hint:n.length?Ce("create tag or reuse:")+n+Ce(""):Ce("create tag ...")})(e)},[C.UNTAG]:e=>{let t=Zi();if(a(t))return z({message:He("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(oa).slice(0,10);return n.length?Ro({hint:Ce(" ... ")+n.join("")})(e):z({message:He("Issue has no tags"),completionWordList:[]})},[C.ASSIGN]:e=>{let t=N.getExistingAssignees().map(oa).slice(0,10);return Ro({hint:Ce("assignees... ")+t.join("")})(e)},[C.UNASSIGN]:e=>{let t=ea();if(a(t))return z({message:He("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(oa).slice(0,10);return n.length?Ro({hint:Ce("remove assignee... ")+n.join("")})(e):z({message:He("Issue has no assignees"),completionWordList:[]})},[C.SYNC]:()=>le(fe)},Zp=Object.fromEntries(Object.entries(CE).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var sa=["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 NE=3,AE=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"]),TE=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},wE=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=NE&&!AE.has(t)&&!/^\d+$/.test(t)),ME=e=>{let t=new Map;for(let s of TE(e))for(let i of wE(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=sa.filter(s=>!r.has(s));return[...n,...o]},ef=sa,tf=-1,nf=()=>{let e=xe();if(a(e))return sa;let t=e.value,n=t.eventLog.length;return n!==tf&&(ef=ME(t),tf=n),ef};var rf=e=>Object.values(C).includes(e),of=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:l,completionWordList:d}=Zp[n].validate(n,r,s),m=n!==C.PEEK&&n!==C.REPLAY,p=o==="command"||o==="modifier"?Oe(n):m?nf():[],{mode:f}=v(),g=f===I.COMMAND_LINE?i??"":"",y=[...d,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?xp(e,y,d):{hint:"",hints:[],remainder:"",overlap:0}}};var sf=e=>{let t=e.trimStart(),n=LE(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=kE(e),l=rf(r)?r:null,d=l!==null,m=r!=="",p=l?Oe(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 y=s?"":i,x=PE(t,l,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:l,isCommandKeyword:d,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:y,inputString:x}},PE=(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},LE=e=>e.trim()?e.trim().split(/\s+/):[],kE=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as DE}from"react";var No=e=>e===Fc||e===":",Fc=" ",As=40,dt={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:bn.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},_c=new Set,af=()=>{for(let e of _c)e()},$c=e=>(_c.add(e),()=>_c.delete(e)),Ft=e=>{let n=e(dt),r=sf(n.value),o=n.cursorPosition===n.value.length;dt={...n,commandMeta:of(r,o)},af()},Ts=({message:e,status:t})=>{let n=structuredClone(dt);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,dt=n,af(),u(e,null)},Uc=e=>{Ft(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},jc=e=>{Ft(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&No(n[o-1]);)o--;for(;o>0&&!No(n[o-1]);)o--}else{for(;o<n.length&&!No(n[o]);)o++;for(;o<n.length&&No(n[o]);)o++}return{...t,cursorPosition:o}})},lf=()=>{Ft(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}})},cf=()=>{Ft(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&No(t[r-1]);)r--;for(;r>0&&!No(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},ia=e=>{Ft(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}})},df=()=>{Ft(e=>({...e,commandIsPending:!0}))},Q=e=>{Ft(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},uf=({addToHistory:e=!0,line:t})=>{Ft(n=>{let r=t??n.value;return{...n,commandHistory:e&&r.trim()?[r,...n.commandHistory].slice(0,As):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}})},mf=e=>{Ft(t=>({...t,commandHistory:e.slice(0,As),commandHistoryIndex:-1}))},pf=()=>{Ft(e=>e.commandHistoryIndex===-1?e:{...e,commandHistoryIndex:-1})},ff=()=>{Ft(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}})},gf=()=>{Ft(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ae=()=>dt,hf=()=>DE($c,ae,ae),aa=()=>{let[e,...t]=dt.value.split(Fc);return t.join(Fc).trim()};var E={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavPreviousItemJump:"navPreviousItemJump",NavNextItemJump:"navNextItemJump",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MovePreviousItemJump:"movePreviousItemJump",MoveNextItemJump:"moveNextItemJump",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",OpenInEditor:"openInEditor",MarkDiffLine:"markDiffLine",CommentOnDiffLine:"commentOnDiffLine",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"},BE=e=>e.shift===!0,OE={[E.NavPreviousItem]:E.NavPreviousItemJump,[E.NavNextItem]:E.NavNextItemJump,[E.MovePreviousItem]:E.MovePreviousItemJump,[E.MoveNextItem]:E.MoveNextItemJump};function FE(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function _E(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function $E(e,t,n){let r=v().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function yf(e,t){let n=ae();if(e.sequence==="?"&&t!==I.PALETTE)return E.InitCommandPalette;if(e.sequence===":"&&t!==I.COMMAND_LINE)return E.InitCommandLine;if(t===I.MOVE)switch(e.name){case"m":case"return":return E.ConfirmMove}if(t===I.COMMAND_LINE)return up(e,n.value);if(t===I.PALETTE)return mp(e,n.value);let r=FE(e)||_E(e);if(r)return UE(r,t,BE(e));if(e.ctrl&&e.name==="c")return E.Exit;switch(e.name){case"r":return E.EditTitle;case"e":return E.EditDescription;case"n":return E.AddItem;case"m":return E.InitMove;case"d":return E.Delete;case"y":return E.Yank;case"o":return E.OpenInEditor;case"s":return E.MarkDiffLine;case"c":return E.CommentOnDiffLine;case"return":return E.Confirm;case"space":return E.Confirm;case"v":return V().viewMode==="wide"?E.SetViewDense:E.SetViewWide;case"q":case"escape":return E.Exit;default:return null}}function UE(e,t,n=!1){let r=t===I.MOVE?{prevItem:E.MovePreviousItem,nextItem:E.MoveNextItem,prevContainer:E.MoveToPreviousContainer,nextContainer:E.MoveToNextContainer}:{prevItem:E.NavPreviousItem,nextItem:E.NavNextItem,prevContainer:E.NavToPreviousContainer,nextContainer:E.NavToNextContainer},o=$E(v().contextNode.childRenderAxis,e,r);return!o||!n?o:OE[o]??o}import{ulid as WE}from"ulid";var ws=24n,jE=ws*4n,Xt=(1n<<jE)-1n,HE=/^[0-9a-f]+$/;function vf(e){return!e||!HE.test(e)?c(`Invalid hex rank: ${e}`):u("Converted rank to bigint",BigInt("0x"+e))}function Pt(e,t=ws){if(e<0n)return c("Negative rank not allowed");let n=e.toString(16);return u("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function vt(e,t){if(!e&&!t)return Pt(Xt/2n,ws);let n=e?vf(e):u("Resolved lower bound",0n);if(a(n))return n;let r=t?vf(t):u("Resolved upper bound",Xt);if(a(r))return r;let o=n.value,s=r.value;if(s<=o)return c("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?c("No rank space available between neighbors"):Pt(i,ws)}function bf(e){if(e<=0)return u("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Xt*BigInt(r+1)/(t+1n),s=Pt(o,ws);if(a(s))return s;n.push(s.value)}return u("Resolved evenly spaced ranks",n)}var D=({userId:e})=>({userId:e}),xf=e=>({action:e.action,payload:e.payload});var Hc=["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","link.contributor.email","unlink.contributor.email"];var SD=new Set(Hc);var Wc=(e,t)=>{let n=Ie(e),r=bf(n.length);if(a(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 c("Unable to assign rebalance rank");o[i.id]=l}return u("Created rebalance event",{id:WE(),action:"rebalance.children",payload:{parent:e,ranks:o},...D(t)})};import{z as Or}from"zod";var If=1,Ef=Or.tuple([Or.string().min(1),Or.string().min(1).nullable()]),GE=Or.looseObject({v:Or.literal(If),id:Ef}),FD=Or.looseObject({v:Or.number().int().positive(),id:Ef}),VE=e=>Object.prototype.hasOwnProperty.call(e,"__proto__"),zE=e=>{let t={};for(let n of Object.keys(e))n!=="__proto__"&&(t[n]=e[n]);return t},Sf=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return c("Invalid persisted event envelope: expected an object");let{v:t,id:n}=e;if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return c("Invalid persisted event envelope: v");if(!Array.isArray(n)||n.length!==2)return c("Invalid persisted event envelope: id");let[r,o]=n;return typeof r!="string"||r.length===0?c("Invalid persisted event envelope: id.0"):o!==null&&(typeof o!="string"||o.length===0)?c("Invalid persisted event envelope: id.1"):u("Parsed persisted event envelope",VE(e)?zE(e):e)};var KE=[1];var qE=new Set(KE),Gc=e=>qE.has(e),Rf=e=>{let t=GE.safeParse(e);return t.success?u("Parsed persisted event",t.data):c(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Vc=(e,t)=>{let n={[e.action]:e.payload,v:If,id:t};return Rf(n)};import ks from"node:fs";import pa from"node:path";import{decodeTime as rS}from"ulid";import{z as Qc}from"zod";import zc from"node:fs";import YE from"node:path";var Ms=e=>e?.code==="ENOENT",Kc=3,qc=e=>zc.readdirSync(e).filter(t=>t.endsWith(".jsonl")).sort(),xn=e=>{let t=Et(e);for(let n=1;;n++){if(!zc.existsSync(t))return"none";let r=[],o=!1;for(let s of qc(t))try{let{size:i,mtimeMs:l}=zc.statSync(YE.join(t,s));r.push(`${s}:${i}:${l}`)}catch(i){if(!Ms(i))throw i;if(n<Kc){o=!0;break}}if(!o)return r.join("|")}},Cf=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),Yc=(e,t,n)=>{let r=Cf(t),o=xn(e),s=Cf(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},or=null,Nf=e=>or&&or.root===e?or.signature:null,Af=(e,t)=>{or={root:e,signature:t}},Tf=(e,t)=>{if(!or||or.root!==e)return;let n=Yc(e,or.signature,t);or=n===null?null:{root:e,signature:n}};import Ge from"node:fs";import Fr from"node:path";import{ulid as XE}from"ulid";var ca="~pending",Xc=/~pending(-[0-9a-z]+)*$/i,Mf=/-f(\d+)$/,Pf=e=>{let t=e.indexOf(".");return t===-1?`${e}${ca}`:e.slice(0,t)+ca+e.slice(t)},da=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},JE=e=>{let[t,n]=da(e);return Xc.test(t)?t.replace(Xc,"")+n:null},Jc=e=>e.replace(Xc,""),_r=e=>e.endsWith(".jsonl")&&JE(e)!==null,Ps=e=>Jc(da(e)[0]),Lf=e=>{let[t]=da(e),n=Mf.exec(t);return n&&_r(e)?Number(n[1]):null},QE=e=>Pf(e).replace(ca,`${ca}-${XE().toLowerCase()}`),ZE=(e,t)=>{let[n,r]=da(e);return`${n.replace(Mf,"")}-f${t}${r}`},kf=(e,t)=>Fr.join(Et(e),Pf(t)),eS=(e,t)=>Math.max(0,Ge.statSync(e).size-(Lf(t)??0)),Df=e=>{let t=Et(e);try{return Ge.existsSync(t)?Ge.readdirSync(t).filter(_r).some(n=>eS(Fr.join(t,n),n)>0):!1}catch{return!0}},tS=3,Bf=(e,t)=>{for(let n=1;;n++){let r=Ge.openSync(e,"a"),o;try{Ge.writeSync(r,t),o=Ge.fstatSync(r).ino}finally{Ge.closeSync(r)}let s;try{s=Ge.statSync(e).ino}catch{s=null}if(s===o||n>=tS)return}},nS=e=>{let t;try{t=Ge.openSync(e,"r")}catch{return!0}try{let{size:n}=Ge.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return Ge.readSync(t,r,0,1,n-1),r[0]===10}finally{Ge.closeSync(t)}},la=10,wf=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(la)+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};Ge.appendFileSync(e,Buffer.concat([Buffer.from(nS(e)?"":`
|
|
30
|
-
`),o,Buffer.from(o[o.length-1]===
|
|
31
|
-
`)]));let s=0;for(let i of o)i===
|
|
32
|
-
`).entries()){let g=f.trim();if(!g)continue;let
|
|
33
|
-
`),i&&(i.current=g);let b=nd.basename(p);return e.advanceEdgeRef(s,b,g),Tf(s,b),u("Event persisted",{path:p,entry:x.value})}catch(d){let m=d instanceof Error?d.message:"Unknown persist error";return c(`Failed to persist event: ${m}`)}}return{mintEventId:n,persist:r}};var Xf=(e,t,n)=>{function r(s,i,l){let d=n.mintEventId(i,l);if(a(d))return c(d.message);let m={...s,id:d.value[0]},p=t.materialize(m);if(p.status!==Qn.Success)return p;let f=n.persist({event:m,rootDir:i,edge:l,id:d.value});return a(f)?f:p}function o(s,i){if(s.length===0||!s[0])return c("No events provided");let l=e.write.readOnlyReason();if(l)return c(l);let d=e.replay.batch(()=>{let m={},p=e.write.beforeWrite(s[0],y=>r(y,i,m));if(a(p))return c(p.message);let f=s.map(y=>r(y,i,m)),g=f.filter(a);return g.length>0?c("Materialize and persist failed: "+g.map(y=>y.message).join(", ")):u("Materialization succeeded",f.map(y=>y.value))});return a(d)?c(d.message):d.value??c("Materialize and persist produced nothing")}return{materializeAndPersist:r,materializeAndPersistAll:o}};var Jf=e=>{let t=Gf(e),n=Wf(e),r=Yf(n),o=Xf(e,t,r);return{...t,...n,...r,...o}};import{z as Z}from"zod";var K=Z.string().min(1),Jt=Z.string(),ar=Z.string(),ha=Z.looseObject({id:K}),rd=Z.looseObject({id:K,name:Jt,parent:K,rank:ar}),IS={"init.workspace":Z.looseObject({id:K,name:Jt,rank:ar}),"add.workspace":Z.looseObject({id:K,name:Jt,rank:ar}),"add.board":rd,"add.swimlane":rd,"add.issue":rd,"add.field":Z.looseObject({id:K,name:Jt,parent:K,rank:ar}),"edit.title":Z.looseObject({id:K,name:Jt}),"delete.node":ha,"lock.node":ha,"move.node":Z.looseObject({id:K,parent:K,rank:ar}),"edit.description":Z.looseObject({id:K,md:Z.string()}),"close.issue":Z.looseObject({id:K,parent:K,rank:ar}),"reopen.issue":Z.looseObject({id:K,parent:K,rank:ar}),"create.tag":Z.looseObject({id:K,name:Jt}),"tombstone.tag":ha,"restore.tag":Z.looseObject({id:K,name:Jt}),"create.contributor":Z.looseObject({id:K,name:Jt}),"rename.contributor":Z.looseObject({id:K,name:Jt}),"tombstone.contributor":ha,"restore.contributor":Z.looseObject({id:K,name:Jt}),"link.contributor.user":Z.looseObject({contributor:K}),"link.contributor.email":Z.looseObject({contributor:K,email:K}),"unlink.contributor.email":Z.looseObject({contributor:K,email:K}),"add.issue.assignee":Z.looseObject({id:K,assignee:K}),"remove.issue.assignee":Z.looseObject({id:K,assignee:K}),"add.issue.tag":Z.looseObject({id:K,tag:K}),"remove.issue.tag":Z.looseObject({id:K,tag:K}),"add.issue.comment":Z.looseObject({id:K,issue:K,md:Z.string()}),"edit.issue.comment":Z.looseObject({id:K,issue:K,md:Z.string()}),"delete.issue.comment":Z.looseObject({id:K,issue:K}),"add.issue.attachment":Z.looseObject({id:K,issue:K,hash:Z.string().min(1),ext:Z.string().min(1),name:Jt,bytes:Z.number()}),"delete.issue.attachment":Z.looseObject({id:K,issue:K}),"rebalance.children":Z.looseObject({parent:K,ranks:Z.record(Z.string(),ar)})},Qf=(e,t)=>{let r=IS[e].safeParse(t);return r.success?u("Payload is readable",void 0):c(`${e}: ${r.error.issues.map(o=>`${o.path.join(".")||"payload"} ${o.message}`).join(", ")}`)};import{ulid as ES}from"ulid";var Zf=(e,t)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return u("Contributor write already in flight",void 0);let{userId:n,userName:r}=V();if(!r||n!==e.userId)return u("Not this actor own write",void 0);let o=N.getContributor(e.userId),s={id:ES(),action:o?"rename.contributor":"create.contributor",payload:{id:e.userId,name:r},userId:e.userId};if(o&&(o.tombstoned||o.name===r))return u("Contributor name is current",void 0);let i=t(s);return a(i)?c(i.message):u("Contributor name recorded",void 0)};var Te={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",DIFF:"Diff",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var H=e=>e.slice(-7).toUpperCase(),ya=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?H(e).includes(n):!0};var Ne={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:ie.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:H(e)},context:ie.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:ie.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:ie.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:ie.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:H(e)},context:ie.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0,disabled:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:i?{disabled:!0}:{},context:ie.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:ie.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};var Ds=(e,t,n)=>N.getNode(e)?$(`a node with id ${e} already exists`,n):t===e?$("a node cannot be its own parent",n):null,eg={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Ne.workspace(t,n,r),s=Bs(o);if(a(s))return ga(s.message,e);let i=N.createNode(o);return a(i)?$(i.message??"Failed to initialize workspace",e):Cc(i.value)?u("Workspace initialized",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Ds(t,void 0,e);if(o)return o;let s=N.createNode(Ne.workspace(t,n,r));return a(s)?$(s.message??"Failed to add workspace",e):Cc(s.value)?u("Added workspace",{action:e.action,result:s.value}):c("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Ds(t,r,e);if(s)return s;let i=N.createNode(Ne.board(t,n,r,o));return a(i)?$(i.message??"Unable to create board",e):rr(i.value)?u("Added board",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Ds(t,r,e);if(s)return s;let i=N.createNode(Ne.swimlane(t,n,r,o));return a(i)?$(i.message??"Unable to create swimlane",e):gn(i.value)?u("Added swimlane",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Ds(t,r,e);if(s)return s;let i=N.createNode(Ne.ticket(t,n,r,o));return a(i)?$(i.message??"Unable to create issue",e):_(i.value)?u("Added issue",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=Ds(t,r,e);if(i)return i;let l=N.createNode(Ne.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(Te.DESCRIPTION)?"vertical":"horizontal"}));return a(l)?$(l.message??`Unable to create field: ${n}`,e):lt(l.value)?u("Added field",{action:e.action,result:l.value}):c("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!N.getNode(t))return $(`Unable to locate node with id ${t}`,e);let o=N.renameNode(t,n);return a(o)?$(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=N.tombstoneNode(t);return a(n)?$(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=N.createTag({id:t,name:n});return a(r)?$(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=N.tombstoneTag(t);return a(n)?$(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=N.restoreTag(t,n);return a(r)?$(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=N.createContributor({id:t,name:n});return a(r)?$(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=N.renameContributor(t,n);return a(r)?$(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=N.tombstoneContributor(t);return a(n)?$(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=N.restoreContributor(t,n);return a(r)?$(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=N.tag(t,n);return a(r)?$(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=N.untag(t,n);return a(r)?$(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=N.assign(t,n);return a(r)?$(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=N.unassign(t,n);return a(r)?$(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=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?$(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=N.editValue(t,n);return a(r)?$(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=N.getNode(t);if(!o)return $("Unable to locate issue",e);if(!_(o))return $("Can only close issues",e);let s=N.getNode(ye);if(!s)return $("Unable to locate target swimlane",e);if(n!==s.id)return $("Close target must be closed swimlane",e);let i=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(i)?$(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=N.getNode(t);if(!o)return $("Unable to locate issue",e);if(!_(o))return $("Can only reopen issues",e);let s=N.getNode(ye);if(!s)return $("Unable to locate closed swimlane",e);if(n===s.id)return $("Cannot reopen issue into closed swimlane",e);if(!N.getNode(n))return $("Reopen parent no longer exists",e);let l=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(l)?$(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=N.lockNode(t);return a(n)?$(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=N.getNode(r);if(!s)return $(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return $(`Node ${r} is not child of ${t}`,e);let i=N.updateNode({...s,rank:o});if(a(i))return $(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=N.createComment({id:t,issue:n,authorId:r,md:o,deleted:!1});return a(s)?$(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=N.getComment(t);if(!o)return $("Unable to locate comment",e);if(o.issue!==n)return $("Comment does not belong to issue",e);let s=N.editComment(t,r);return a(s)?$(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=N.getComment(t);if(!r)return $("Unable to locate comment",e);if(r.issue!==n)return $("Comment does not belong to issue",e);let o=N.deleteComment(t);return a(o)?$(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=N.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return a(l)?$(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=N.getAttachment(t);if(!r)return $("Unable to locate attachment",e);if(r.issue!==n)return $("Attachment does not belong to issue",e);let o=N.deleteAttachment(t);return a(o)?$(o.message??"Unable to delete attachment",e):u("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.email":e=>{let{contributor:t,email:n}=e.payload;if(!tr(n))return $(`not an email address: ${n}`,e);let r=N.linkContributorEmail({email:n,contributor:t,authorId:e.userId});return a(r)?$(r.message??"Unable to link email",e):u("Email linked to contributor",{action:e.action,result:r.value})},"unlink.contributor.email":e=>{let{contributor:t,email:n}=e.payload,r=N.unlinkContributorEmail(n,t,e.userId);return a(r)?$(r.message??"Unable to unlink email",e):u("Email unlinked from contributor",{action:e.action,result:r.value})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=N.linkUserId({contributorId:t,userId:e.userId});return a(n)?$(n.message??"Unable to link contributor",e):u("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};var tg=e=>{let t=N.getNode(e);if(!t||!_(t)||t.isDeleted)return null;let n=og(t);return a(n)?n:null},ng=e=>{if(!sd())return null;for(let t of e){let n=tg(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=tg(r);if(o)return o}return null},SS=(e,t)=>{let n=N.getNode(e);n&&N.updateNode({...n,log:[...n.log??[],t]})},RS=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},od=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 RS(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":case"link.contributor.email":case"unlink.contributor.email":default:return[]}},CS=e=>{Fe(t=>({...t,eventLog:[...t.eventLog,e]}))},jn=null,NS=e=>{for(let[t,n]of e.nodeLog){let r=N.getNode(t);r&&N.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&Fe(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),ng([...e.virtualNodeIds])},rg={isInitialized:()=>_t(),batch:e=>va(e),afterApply(e,{batched:t,bypassLogging:n}){let r=[...new Set(od(e))];if(t){jn??={appLog:[],nodeLog:new Map,virtualNodeIds:new Set};for(let o of r){if(!n){let s=jn.nodeLog.get(o);s?s.push(e):jn.nodeLog.set(o,[e])}if(sd()){jn.virtualNodeIds.add(o);let s=v().nodes[o]?.parentNodeId;s&&jn.virtualNodeIds.add(s)}}return n||jn.appLog.push(e),null}return n||(r.forEach(o=>SS(o,e)),CS(e)),ng(r)},flush(){if(!jn)return null;let e=jn;return jn=null,NS(e)}};var pe=()=>{let{userName:e,userId:t}=V();return e?t?Xl(t)?ki(e)?u("Successfully resolved actor ID",{userId:t,userName:e}):c("Invalid user name in config"):c("Invalid user ID in config"):c("User ID not configured"):c("User name not configured")};var AS={genesis:"init.workspace",actions:Hc,readPayload:Qf,apply:eg,replay:rg,write:{readOnlyReason:()=>{let e=v();return e.readOnly?e.readOnlyReason??"Cannot change the board while time travelling":null},beforeWrite:Zf}},TS=Jf(AS),{materialize:Os,materializeAll:Qt,fromPersistedEvent:WO,decodeReconstructedEvents:GO,loadMergedEventsWithUnreadable:Zt,loadEventActors:sg,loadActorNames:lr,loadMergedEvents:cr,loadMergedEventsBefore:ba,getEdgeRef:VO,advanceEdgeRef:zO,clearEdgeCache:KO,getSortedEvents:qO,loadEffectiveEventTimes:xa,mintEventId:YO,persist:ig,materializeAndPersist:XO,materializeAndPersistAll:B}=TS;var $r=e=>e.trim().toLocaleLowerCase(),id=(e,t)=>$r(e).includes($r(t));var wS=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},MS=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},ag=null,lg=new Map,PS=()=>{let e=v().eventLog??[];if(e===ag)return lg;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 ag=e,lg=t,t},LS=e=>{let{contributors:t}=v(),n=PS().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},cg=(e,t)=>{let n=$r(t.value);if(!n)return!0;switch(t.target){case"title":return id(e.title??"",n);case"description":return id(e.props.description??"",n);case"tag":return wS(e).map($r).some(o=>o.includes(n));case"assignee":return MS(e).map($r).some(o=>o.includes(n));case"actor":return LS(e).map($r).some(o=>o.includes(n));case"ref":return ya(e.id,t.value);default:return!0}};var ad=(e,t)=>e.rank<t.rank?-1:e.rank>t.rank?1:0,kS=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,dg=(e,t)=>Object.values(e).filter(n=>kS(n,t)).sort(ad),ug=(e,t)=>{let n={};for(let r of Object.values(e)){if(_(r)&&t.length>0&&!t.every(s=>cg(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(ad);return n},mg=(e,t)=>{let n={};for(let r of Object.values(e)){if(!r.parentNodeId||r.isDeleted||!t.has(r.parentNodeId))continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(ad);return n};var pg=e=>Ia(Ie(e),{at:"end"}),Ia=(e,t={at:"end"})=>{let n=o=>a(o)?u("Rank space exhausted",{rank:"",needsRebalance:!0}):u("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(vt(void 0,void 0));let r=()=>n(vt(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(vt(void 0,o.rank)):c("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(vt(o.rank,void 0)):c("Unable to resolve last sibling")}case"before":{let o=fg(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(vt(i?.rank,s.rank))}case"after":{let o=fg(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(vt(s.rank,i?.rank))}}},Ie=e=>{let t=v();if(!hg()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return dg(t.nodes,e)},fg=(e,t)=>e.findIndex(n=>n.id===t),gg=(e,t,n={at:"end"})=>Ia(Ie(t).filter(r=>r.id!==e),n),Sn=(e,t,n,r,o)=>{let s=gg(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return u("Resolved rank",s.value.rank);let i=Wc(e,r);if(a(i))return i;let l=B([i.value],o);if(a(l))return l;let d=gg(t,e,n);return a(d)?d:d.value.needsRebalance?c("Rank rebalance failed to create space"):u("Resolved rank after rebalance",d.value.rank)},Hn=(e,t,n)=>{let r=pg(e);if(a(r))return r;if(!r.value.needsRebalance)return u("Resolved rank",r.value.rank);let o=Wc(e,t);if(a(o))return o;let s=B([o.value],n);if(a(s))return s;let i=pg(e);return a(i)?i:i.value.needsRebalance?c("Rank rebalance failed to create space"):u("Resolved rank after rebalance",i.value.rank)};var Fs=5,U={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=de(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||U.navigate({contextNode:o,selectedIndex:de(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=de(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;U.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>yg(1),navigateToPreviousItem:()=>yg(-1),jumpToNextItem:()=>vg(Fs),jumpToPreviousItem:()=>vg(-Fs),navigateToNextContainer:()=>bg(1),navigateToPreviousContainer:()=>bg(-1),navigate:({contextNode:e,selectedIndex:t})=>{w({contextNodeId:e.id,selectedIndex:t})}},yg=e=>{let{selectedIndex:t,contextNode:n}=v(),r=de(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;U.navigate({selectedIndex:s,contextNode:n})},vg=e=>{let{selectedIndex:t,contextNode:n}=v(),r=de(n.id).length;if(r===0)return;let o=Math.max(0,t),s=Math.min(Math.max(o+e,0),r-1);U.navigate({selectedIndex:s,contextNode:n})},bg=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=de(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 d=de(l.id),m=Math.max(0,d.length-1),p=Math.min(Math.max(0,r),m),f=d.length?p:-1;U.navigate({contextNode:l,selectedIndex:f})};var Ig=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Eg=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},DS=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&<(t)&&t.childRenderAxis==="vertical"},Ea=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=Ie(r.id);return U.navigate({contextNode:r,selectedIndex:Ig(t,o.length)}),!0},Sg=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Ea(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=Ie(o.id).findIndex(l=>l.id===n.id);return i>=0?(U.navigate({contextNode:o,selectedIndex:i}),!0):Sg(o.id)},xg=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Sg(n))return!0;n=t[n]?.parentNodeId}return!1},BS=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},Rg=e=>{let{nodes:t,rootNodeId:n}=v();if(DS(e.contextNodeId)&&Ea(e.contextNodeId,e.selectedIndex))return u("Restored navigation inside text container",null);if(BS(e.selectedNodeId)&&e.selectedNodeId&&xg(e.selectedNodeId))return u("Restored navigation to selected node or ancestor",null);if(Ea(e.contextNodeId,e.selectedIndex))return u("Restored navigation to previous container",null);if(e.parentNodeId&&Ea(e.parentNodeId,e.selectedIndex))return u("Restored navigation to previous parent",null);if(xg(e.contextNodeId))return u("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return c("Unable to restore navigation");let o=Ie(r.id);return U.navigate({contextNode:r,selectedIndex:Ig(e.selectedIndex,o.length)}),u("Restored navigation to root",null)};import{monotonicFactory as OS,ulid as Rn}from"ulid";var _s=OS();function FS(){let e=xe();if(a(e))return c("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return c("No workspace found in event log");let[r]=de(n.id),[o]=r?de(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 _S(){let e=FS();return a(e)?e:U.navigate(e.value)}function Cg({userId:e,userName:t}){let n=_s(),r=_s(),o=_s(),s=_s(),i=_s(),l=vt(void 0,void 0);if(a(l))return l;let d=vt(void 0,void 0);if(a(d))return d;let m=vt(d.value,void 0);if(a(m))return m;let p=vt(void 0,void 0);if(a(p))return p;let f=vt(p.value,void 0);if(a(f))return f;let g=vt(f.value,void 0);if(a(g))return g;let y=vt(void 0,void 0);return a(y)?y:u("Created default events",[{id:Rn(),userId:e,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:Rn(),userId:e,action:"create.contributor",payload:{id:e,name:t}},{id:Rn(),userId:e,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:d.value}},{id:Rn(),userId:e,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Rn(),userId:e,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Rn(),userId:e,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:g.value}},{id:Rn(),userId:e,action:"add.board",payload:{id:Qi,name:"Closed",parent:n,rank:m.value}},{id:Rn(),userId:e,action:"add.swimlane",payload:{id:ye,name:"Closed",parent:Qi,rank:y.value}},{id:Rn(),userId:e,action:"lock.node",payload:{id:Qi}},{id:Rn(),userId:e,action:"lock.node",payload:{id:ye}}])}var $S=()=>{let e=xe();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},US=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(", ");se.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(", ");se.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}};function en(e,t=[]){if($S())return u("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Ne.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=Bs(s);return a(i)?i:(w({hasProjectDefinition:!1,mode:I.DEFAULT}),u("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return c("Initialized Epiq project has no workspace init event");let n=Qt(e),{fatal:r,skipped:o}=In(n);return r.length>0?c(`Materializing failed:
|
|
26
|
+
`).filter(Boolean).filter(i=>i!==ft);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(a(o))return c(`Failed to clean storage branch
|
|
27
|
+
${o.message}`);let s=await go({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:r});return a(s)?c(s.message):u("Cleaned storage branch",!0)},Xt=tc(async(e=process.cwd())=>{let t=await j({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?c("Not inside a Git repository"):u("Resolved repo root",t.value.stdout.trim())},e=>It.resolve(e)),WP=tc(async e=>{let t=await j({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return c(t.message);let n=t.value.stdout.trim(),r=It.isAbsolute(n)?n:It.join(e,n);return u("Resolved git dir",r)},e=>It.resolve(e));var XP=process.env.IS_LOCAL==="true",ft=".epiq",Fn="events",fc="media",EI="project.json",Pr=e=>pn.join(e,ft),po=e=>pn.join(Pr(e),EI),Et=e=>pn.join(Pr(e),Fn),ps=e=>pn.join(Pr(e),fc),Ym=e=>pn.join(e,ft),SI=e=>{let t=pn.join(e,ft);return ms.existsSync(t)&&ms.statSync(t).isDirectory()},fs=e=>{let t=po(e);return ms.existsSync(t)&&ms.statSync(t).isFile()},Fi=e=>{let t=pn.resolve(e);for(;;){if(SI(t))return u("Resolved closest .epiq root",t);let n=pn.dirname(t);if(n===t)return c("No .epiq directory found in any parent");t=n}},gc="No .epiq/project.json found in any parent",ce=e=>{let t=pn.resolve(e);for(;;){if(fs(t))return u("Resolved closest epiq project root",t);let n=pn.dirname(t);if(n===t)return c(gc);t=n}},Xm=e=>{let t=Et(e);try{return ms.mkdirSync(t,{recursive:!0}),u("Resolved events dir",t)}catch(n){return c(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},Ie=async()=>{let e=await Xt(process.cwd());if(a(e))return e;let t=fe({repoRoot:e.value});return a(t)?t:u("Resolved persist root",t.value)};import{accessSync as RI,copyFileSync as CI,existsSync as Hi,mkdirSync as Jm,readdirSync as Qm,readFileSync as NI,renameSync as AI,rmSync as TI,statSync as Zm,unlinkSync as wI,writeFileSync as MI}from"node:fs";import ho from"node:path";var hc=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",nt={writeToFile:(e,t)=>{try{let n=ho.dirname(e);Hi(n)||Jm(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);MI(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return NI(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=nt.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 Hi(e)&&Zm(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await RI(e),!0}catch{return!1}},mkDir:e=>Jm(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=ho.parse(t);for(;;){let r=ho.join(t,e);try{if(Hi(r)&&Zm(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=ho.dirname(t)}return null},readFirstJSON(e){try{if(!nt.dirExists(e))return null;let t=Qm(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=ho.join(e,t);return nt.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return nt.dirExists(e)?Qm(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{wI(e)}catch(t){(!hc(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{TI(e,{recursive:!0,force:!0})}catch(t){(!hc(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(ho.dirname(t)),!n?.overwrite&&Hi(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{AI(e,t)}catch(r){if(hc(r)&&r.code==="EXDEV"){CI(e,t),this.rmFile(e);return}throw r}}};var LI={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},tp=Jt.object({logLevel:Jt.enum(["info","error","debug"]),preferredEditor:Jt.string().optional(),userName:Jt.string().optional(),userId:Jt.string().optional(),autoSync:Jt.boolean().nullable().optional(),autoSyncDebounceMs:Jt.number().optional(),attachmentMaxKb:Jt.number().optional(),viewMode:Jt.enum(["dense","wide"]).optional(),declinedEmailBoards:Jt.array(Jt.string()).optional()}).partial(),kI="config.json",np=Bn,yc=()=>PI.join(np(),kI),vc=()=>{try{return nt.mkDir(np()),u(`Ensured ~/${qt} exists`,null)}catch{return c(`Unable to create ~/${qt}`)}},DI=e=>{let t;try{t=JSON.parse(e)}catch{return c(`Invalid ~/${qt}/config.json JSON`)}let n=tp.safeParse(t??{});return n.success?u("Parsed config",n.data):c(`Invalid ~/${qt}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},fn=()=>{let e=vc();if(a(e))return c(e.message);let t=yc(),n=nt.readFile(t);return n==null||n.trim()===""?u("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):DI(n)},rp=e=>{let t=vc();if(a(t))return c(t.message);let n=tp.safeParse(e);if(!n.success)return c(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=yc();try{return nt.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
28
|
+
`),u("Config written",null)}catch{return c(`Unable to write ~/${qt}/config.json`)}},Ft=e=>{let t=fn();if(a(t))return c("Failed to read existing config");let n={...t.value,...e};return rp(n)},gt=()=>{let e=yc(),t=vc();if(a(t))return c(`Unable to create ~/${qt}`);if(!(nt.readFile(e)!==null)){let b=rp(LI);if(a(b))throw new Error(`Unable to create ~/${qt}/config.json`)}let r=fn();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,declinedEmailBoards:l,autoSync:d,autoSyncDebounceMs:m,attachmentMaxKb:p,logLevel:f,viewMode:g}=r.value,h=co({userId:i,userName:s});if(a(h))return c(h.message);let x=h.value??{userId:i,userName:s};return!x.userName||!x.userId?c(`User name or ID not configured in ~/${qt}/config.json`):(process.env.EPIQ_LOG_LEVEL=f,u("successfully loaded settings",{gitEmail:null,gitName:null,declinedEmailBoards:l??[],logLevel:f??"debug",preferredEditor:o??"",userName:x.userName,userId:x.userId,autoSync:d??!1,autoSyncIntervalMs:m??1e4,attachmentMaxKb:p??null,viewMode:g??"dense"}))};import{useSyncExternalStore as BI}from"react";var gs={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,gitEmail:null,gitName:null,declinedEmailBoards:[],viewMode:null},bc=new Set,OI=()=>{for(let e of bc)e()},V=()=>gs,op=()=>BI(e=>(bc.add(e),()=>{bc.delete(e)}),()=>gs),$e=e=>(gs={...gs,...e},OI(),gs);import{spawn as FI}from"node:child_process";import xc from"node:process";var Ic=e=>{let t=xc.platform==="darwin"?"open":xc.platform==="win32"?"cmd":"xdg-open",n=xc.platform==="win32"?["/c","start","",e]:[e];FI(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as Yb,stat as hw}from"node:fs/promises";import{createHash as yw}from"node:crypto";import Sr from"chalk";import Mv from"string-width";import{decodeTime as sp}from"ulid";var Wi=1440*60*1e3,hs=(e,t=Date.now())=>e>t+Wi?t:e,De=e=>hs(sp(e)),yo=e=>{let t=Date.now()+Wi,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})},vo=e=>{try{return u("Decoded date",new Date(De(e)))}catch(t){return c("Decoding failed + "+t.message)}},tr=e=>{if(!e?.id)return null;try{return sp(e.id)}catch{return null}};import bo from"chalk";var st={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:st.cyan,accent2:st.magenta,primary:st.white,secondary:st.grayDark,secondary2:st.grayLight,gray:st.gray,green:st.green,yellow:st.yellow,red:st.red};var L={red:st.red,yellow:st.yellow,green:st.green,blue:st.blue,magenta:st.magenta,cyan:st.cyan},Gi={urgent:L.red,critical:L.red,important:L.red,blocker:L.red,asap:L.red,immediate:L.red,fail:L.red,failure:L.red,broken:L.red,bug:L.red,error:L.red,incident:L.red,outage:L.red,production:L.red,crash:L.red,security:L.red,warning:L.yellow,warn:L.yellow,risky:L.yellow,risk:L.yellow,attention:L.yellow,pending:L.yellow,review:L.yellow,"needs-review":L.yellow,qa:L.yellow,testing:L.yellow,test:L.yellow,validate:L.yellow,verification:L.yellow,staging:L.yellow,check:L.yellow,"follow-up":L.yellow,followup:L.yellow,waiting:L.yellow,blocked:L.yellow,hold:L.yellow,done:L.green,complete:L.green,completed:L.green,success:L.green,ok:L.green,stable:L.green,resolved:L.green,fixed:L.green,closed:L.green,merged:L.green,released:L.green,deployed:L.green,approved:L.green,verified:L.green,working:L.green,healthy:L.green,pass:L.green,passing:L.green,info:L.blue,information:L.blue,note:L.blue,docs:L.blue,documentation:L.blue,doc:L.blue,guide:L.blue,help:L.blue,explanation:L.blue,detail:L.blue,details:L.blue,context:L.blue,design:L.blue,discussion:L.blue,proposal:L.blue,idea:L.blue,feature:L.magenta,enhancement:L.magenta,improvement:L.magenta,refactor:L.magenta,refactoring:L.magenta,cleanup:L.magenta,optimize:L.magenta,optimization:L.magenta,perf:L.magenta,performance:L.magenta,upgrade:L.magenta,migration:L.magenta,modernize:L.magenta,debt:L.magenta,todo:L.cyan,next:L.cyan,planned:L.cyan,plan:L.cyan,future:L.cyan,backlog:L.cyan,investigate:L.cyan,explore:L.cyan,prototype:L.cyan};var Sc={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Rc=(e,t,n)=>Math.max(t,Math.min(n,e)),Ec=(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},_I=e=>e.toLowerCase().trim(),$I=(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)),d=0,m=0,p=0;i>=0&&i<1?(d=s,m=l):i>=1&&i<2?(d=l,m=s):i>=2&&i<3?(m=s,p=l):i>=3&&i<4?(m=l,p=s):i>=4&&i<5?(d=l,p=s):(d=s,p=l);let f=o-s/2;return[Math.round((d+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},Cc=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,ip=e=>{let t=e.replace("#","");return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]},lp=(e,t,n)=>{let r=Rc(n,0,1);return[Math.round(Ec(e[0],t[0],r)),Math.round(Ec(e[1],t[1],r)),Math.round(Ec(e[2],t[2],r))]};var UI=(e,t,n)=>lp(e,t,n),Nc=e=>{let t=ap(e)%360,n=$I(t,Sc.stringColor.saturation,Sc.stringColor.lightness);return Cc(n)},ze=(e,t=Gi)=>{let n=_I(e??"");return n&&t[n]?t[n]:Nc(n)};var cp=e=>{let t=Sc.gradient.stops,n=Rc(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 UI(t[s],t[s+1],i)},dp=(e,t)=>{if(e.length===0)return"#000000";if(e.length===1)return e[0];let n=e.length-1,r=Rc(t,0,1)*n,o=Math.min(Math.floor(r),n-1);return Cc(lp(ip(e[o]),ip(e[o+1]),r-o))},Vi=e=>Cc(cp(e)),zi=e=>ap(e.toLowerCase().trim())/4294967295,up=e=>{let t=zi(e);return cp(t)},jI=e=>{let[t,n,r]=up(e);return{normal:o=>bo.bgRgb(t,n,r).black(o),cursor:o=>bo.bgRgb(t,n,r).white.bold(o)}},Ac=e=>{let[t,n,r]=up(e);return{fg:o=>bo.rgb(t,n,r)(o),fgCursor:o=>bo.rgb(t,n,r).inverse(o),bg:o=>bo.bgRgb(t,n,r).black(o),bgCursor:o=>bo.bgRgb(t,n,r).white.bold(o)}},Ki=e=>jI(e).normal(` ${e} `);var HI="Unknown",qi=(e,t)=>t?.length?t:e?.length?e:HI,Ke=(e,t)=>{let n=qi(e,t);return{id:e?.length?e:n,name:n,color:ze(n)}};var xo="removed",ht=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?u("Found node",n):c("Unable to find node in breadcrumb")},mp=["png","jpg","gif","webp"];var Qe=e=>e.trim().toLowerCase(),nr=e=>{let t=Qe(e);return t.length>0&&t.length<=254&&/^[^\s@]+@[^\s@]+$/.test(t)},ys=(e,t)=>`${Qe(e)} ${t}`,Tc=e=>!e.tombstoned,vs=(e,t)=>{let n=Qe(t),r=new Set;for(let o of Object.values(e))Tc(o)&&o.email===n&&r.add(o.contributor);return[...r]},gn=(e,t)=>{let n=new Set;for(let r of Object.values(e))Tc(r)&&r.contributor===t&&n.add(r.email);return[...n]},pp=e=>{let t=new Map;for(let r of Object.values(e)){if(!Tc(r))continue;let o=t.get(r.email)??new Set;o.add(r.contributor),t.set(r.email,o)}let n=new Map;for(let[r,o]of t){let[s]=[...o];o.size===1&&s&&n.set(r,s)}return n};var Yi=(e,t)=>e===t.authorId||e===t.contributor;var re={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function wc(e){return e.context===re.WORKSPACE}function _(e){return e.context===re.TICKET}function rr(e){return e.context===re.TEXT}function it(e){return e.context===re.FIELD}function bs(e){return e.context===re.FIELD_LIST}var hn=e=>e.context===re.SWIMLANE,or=e=>e.context===re.BOARD,xs=e=>e.context===re.COMMENT;import{useSyncExternalStore as mA}from"react";var I={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette",IDENTITY:"identity"};var fp=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",gp=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",hp=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",yp=(e,t)=>{if(gp(e,e.sequence))return E.MoveCursorLeftOfWord;if(hp(e,e.sequence))return E.MoveCursorRightOfWord;if(fp(e,e.sequence))return E.EraseInputWord;switch(e.name){case"tab":return E.AutoCompleteCommand;case"up":return E.GetLastCommandFromHistory;case"down":return E.GetNextCommandFromHistory;case"left":return E.MoveCursorLeft;case"right":return E.MoveCursorRight;case"return":return E.Confirm;case"backspace":return t?E.EraseInput:E.ExitCommandLine;case"escape":return E.ExitCommandLine;default:return E.CaptureInput}},vp=(e,t)=>{if(gp(e,e.sequence))return E.MoveCursorLeftOfWord;if(hp(e,e.sequence))return E.MoveCursorRightOfWord;if(fp(e,e.sequence))return E.EraseInputWord;switch(e.name){case"tab":return E.AutoCompleteCommand;case"up":return E.NavPreviousItem;case"down":return E.NavNextItem;case"left":return E.MoveCursorLeft;case"right":return E.MoveCursorRight;case"return":return E.Confirm;case"backspace":return t?E.EraseInput:E.ExitCommandLine;case"escape":return E.ExitCommandLine;default:return E.CaptureInput}};import bp from"string-width";function Xi(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var _n=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",WI=/\u001B\[[0-9;]*m/,Mc="\x1B[0m",GI=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),$n=(e,t)=>{if(t<=0)return"";if(bp(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(WI.test(l)){o+=l,i=l!==Mc&&l!=="\x1B[m";continue}for(let d of GI(l)){let m=bp(d);if(s+m>r)return`${o}...${i?Mc:""}`;o+=d,s+=m}}return`${o}...${i?Mc:""}`},Ee=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),xp=e=>e.charAt(0).toUpperCase()+e.slice(1);var Ip=e=>{let t=new Map;for(let n of e){let r=n.toLowerCase();for(let o=1;o<=n.length;o++){let s=r.slice(0,o),i=t.get(s);i?i.push(n):t.set(s,[n])}}return t},Ep=(e,t)=>t?e.get(t)??[]:[];var Sp=new WeakMap,VI=e=>{let t=Sp.get(e);return t||(t=Ip(e),Sp.set(e,t)),t};var Rp=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Ep(VI(e),r).filter(s=>Xi(r,s.toLowerCase())>=n)};var zI={hint:"",hints:[],overlap:0,remainder:""},Np=({inputToMatch:e,lastWord:t,isLastWordCompleted:n,inputString:r},o,s=[])=>{if(n||e===""){let[l]=s;return s.length===1&&l&&!r.trim()?Cp("",[l]):zI}let i=Rp({wordList:o,inputToMatch:e,overlapThreshold:1});return Cp(t,i)},Cp=(e,t)=>{let n=t[0]??"",r=Xi(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 Is from"node:fs";import Es from"node:path";import{z as Io}from"zod";var Ji="recent-projects.json",KI=20,qI=Io.object({projectId:Io.string().min(1),root:Io.string().min(1),lastOpenedAt:Io.number().finite()}),YI=Io.object({projects:Io.array(qI)}),Tp=()=>Es.join(Bn(),Ji),Eo=e=>Es.basename(e)||e,Ap=e=>{let t=Es.resolve(e);try{return Is.realpathSync(t)}catch{return t}},wp=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Mp=e=>{if(!fs(e.root))return!1;let t=mn(e.root);return!a(t)&&t.value===e.projectId},Pp=()=>{let e=Tp();if(!Is.existsSync(e))return u("No recent projects recorded",[]);let t;try{t=JSON.parse(Is.readFileSync(e,"utf8"))}catch(r){return c(`Invalid ${Ji}: ${r instanceof Error?r.message:String(r)}`)}let n=YI.safeParse(t);return n.success?u("Read recent projects",n.data.projects):c(`Invalid ${Ji} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},XI=e=>{let t=Tp();try{Is.mkdirSync(Es.dirname(t),{recursive:!0}),Is.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
29
|
+
`,"utf8")}catch(n){return c(`Unable to write ${Ji}: ${n instanceof Error?n.message:String(n)}`)}return u("Recorded recent project",e)},Un=({exclude:e}={})=>{let t=Pp();if(a(t))return t;let n=e===void 0?null:Ap(e);return u("Listed recent projects",t.value.filter(r=>n===null||Ap(r.root)!==n).filter(Mp).sort(wp))},Qi=({root:e,now:t=Date.now()})=>{let n=Es.resolve(e),r=mn(n);if(a(r))return c(r.message);let o=r.value,s=Pp(),i=a(s)?[]:s.value,l=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(d=>d.projectId!==o&&d.root!==n)].filter(Mp).sort(wp).slice(0,KI);return XI(l)};var Pc=null,Lp=e=>{Pc=e},kp=e=>Pc?Pc(e):[];var Dp=[],So=e=>{Dp=e},Ro=()=>Dp;var jn=()=>{let e=V(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1,o=Bp(),s=o.length>0?null:Lc(),i=s!==null&&(e.declinedEmailBoards??[]).includes(s),l=o.length>0||i||s===null;return{isSetupDone:n&&t&&r&&l,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r,isSetEmails:l,claimedEmails:o,emailSetupDeclined:i}},Lc=()=>{let e=ce(process.cwd());if(a(e))return null;let t=mn(e.value);return a(t)?null:t.value||null},Bp=()=>{let{userId:e}=V();return e?kp(e):[]},Op=()=>Bp().length>0;var kc=()=>{let e=ce(process.cwd());if(a(e))return!1;let t=Tt(e.value);return ye(t)},Fp=e=>e===!0?"on":e===!1?"off":null,_p=e=>e==="on"?!0:e==="off"?!1:null,$p=()=>{let e=jn();if(!e.isSetUserName)return"config username ";if(!e.isSetPreferredEditor)return"config editor ";if(!e.isSetAutoSync)return"config autoSync ";if(!kc())return"init";if(!e.isSetEmails){let{gitEmail:t}=V(),n=Ro()[0]??t;return n&&nr(n)?`config emails ${n}`:"config emails "}return null};var JI=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ge,Zi]=JI;var QI=e=>e.props.tags??[],ZI=e=>e.props.assignees??[],yn=e=>QI(e).map(t=>C.getTag(t)).filter(t=>!!t),vn=e=>ZI(e).map(t=>C.getContributor(t)).filter(t=>!!t),ea=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!_(n)?c("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",yn(n))},ta=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!_(n)?c("Invalid unassign target"):u("Retrieved assignees from ticket in breadcrumb",vn(n))};var R={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 eE=/^(\d+)(h|d|w|mo|y)$/,tE=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,nE=({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},rE=(e,t=new Date)=>{let n=e.match(eE);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}},oE=e=>{let t=e.match(tE);if(!t)return null;let[,n,r,o,s,i]=t,l=Number(n),d=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return nE({year:l,month:d,day:m,hour:p,minute:f})?new Date(l,d-1,m,p,f):null},kr=e=>{let t=e.trim().toLowerCase();return rE(t)??oE(t)};var Up=/^(\d+)(s|m)?$/,na=e=>{let t=e.trim().toLowerCase().match(Up);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},ra=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Up.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},jp=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,sE=[{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}],Dc=(e=sE)=>{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 iE=["BOARD","TICKET","SWIMLANE","COMMENT"],he={EDITOR:"editor",VIEW:"view",USERNAME:"username",EMAILS:"emails",EMAILS_UNCLAIM:"emails-unclaim",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},Pt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},qe={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},aE=[he.EDITOR,he.VIEW,he.USERNAME,he.EMAILS,he.EMAILS_UNCLAIM,he.AUTOSYNC,he.SYNC_DEBOUNCE_MS,he.ATTACHMENT_MAX_KB,he.LOG_LEVEL],lE=(e=v().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[]}},Oc=[String(3e3),"5000","15000","30000","60000"],Fc=["250","500","1000"],Gp=["10s","20s","30s","45s"],Dr=[R.EXIT,R.SYNC,R.HELP,R.EXPORT,R.CONFIG,R.YANK],oa=[R.NEW,R.EDIT,R.DELETE,R.MOVE],Bc=[R.TAG,R.UNTAG,R.ASSIGN,R.UNASSIGN,R.CLOSE_ISSUE,R.RE_OPEN_ISSUE,R.EDIT,R.COMMENT],Hp=[R.FILTER,R.PEEK,R.REPLAY],cE={WORKSPACE:[...Dr,...oa],BOARD:[...Hp,...Dr,...oa],SWIMLANE:[...Hp,...Dr,...oa],TICKET:[...Dr,...oa,...Bc],FIELD:[...Dr,...Bc],FIELD_LIST:[...Dr,...Bc],TEXT:[...Dr],COMMENT:[R.EDIT,R.DELETE,R.YANK]},dE=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Ss=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&_(n)),Wp=e=>e.parentNodeId===ge,uE=({selectedNode:e,breadCrumb:t})=>{let n=lE(e?.context);return Ss({breadCrumb:t,selectedNode:e})?n.includes(Pt.DESCRIPTION)?n:[...n,Pt.DESCRIPTION]:n},mE=({selectedNode:e,breadCrumb:t})=>{let n=Ss({breadCrumb:t,selectedNode:e});return n?[qe.REF,qe.TITLE,...n.props?.description?.trim()?[qe.DESCRIPTION]:[],...yn(n).length>0?[qe.TAGS]:[],...vn(n).length>0?[qe.ASSIGNEES]:[]]:e?[qe.REF,qe.TITLE]:[]},_c=()=>{let e=Un({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},pE=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=jn();if(!r)return[R.HELP,R.CONFIG];if(!kc())return[R.HELP,R.INIT,R.OPEN];if(t)return[R.HELP,R.PEEK,R.REPLAY,R.EXPORT,R.CONFIG,R.YANK];let o=e?.context,s=o&&iE.includes(o),i=[...new Set([...n,e].map(d=>d?.context).flatMap(d=>d?cE[d]:[]))],l=Ss({breadCrumb:n,selectedNode:e});return i.filter(d=>d===R.MOVE?!1:d===R.YANK?!!(l??e):d===R.EDIT?s||!!l:d===R.DELETE?s:d===R.UNTAG?!!(l&&yn(l).length>0):d===R.UNASSIGN?!!(l&&vn(l).length>0):d===R.RE_OPEN_ISSUE?!!(l&&Wp(l)):d===R.CLOSE_ISSUE?!!(l&&!Wp(l)):!0)},Be=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let s=t.context??"WORKSPACE";return{[R.NONE]:pE({breadCrumb:o,readOnly:r,selectedNode:n}),[R.EXIT]:["confirm"],[R.EXPORT]:[],[R.SYNC]:[],[R.INIT]:[],[R.OPEN]:e===R.OPEN?_c():[],[R.HELP]:[],[R.PEEK]:[...Dc(),"now","prev","next"],[R.REPLAY]:[...Dc()],[R.EDIT]:uE({selectedNode:n,breadCrumb:o}),[R.YANK]:mE({selectedNode:n,breadCrumb:o}),[R.COMMENT]:[],[R.DELETE]:["confirm"],[R.RE_OPEN_ISSUE]:["confirm"],[R.CLOSE_ISSUE]:["confirm"],[R.MOVE]:["start","confirm","next","previous","jump-next","jump-previous","to-next","to-previous","cancel"],[R.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[R.TAG]:[...new Set([...Object.keys(Gi),...C.getExistingTags()])],[R.UNTAG]:[...ea()?.value?.map(({name:l})=>l)??[]],[R.UNASSIGN]:[...ta()?.value?.map(({name:l})=>l)??[]],[R.ASSIGN]:C.getExistingAssignees(),[R.NEW]:dE(s),[R.CONFIG]:[...aE]}[e]??[]};import of from"chalk";var Vp=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import vE from"zod";import fE from"node:crypto";import Rs from"node:fs";import qp from"node:path";var zp="/media/",Kp=e=>`${zp}${e}`,$c=(e,t)=>`})`;var bn=500,gE=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,Or=(e,t)=>`${e}.${t}`,hE=e=>gE.test(e),Yp=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"):c(`Unsupported image format. Allowed: ${mp.join(", ")}`),Xp=e=>fE.createHash("sha256").update(e).digest("hex"),yE=(e,t=bn)=>{if(e.length===0)return c("Attachment is empty");if(e.length>t*1024)return c(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=Yp(e);return a(n)?n:u("Validated attachment data",{hash:Xp(e),ext:n.value,bytes:e.length})},Jp=(e,t,n=bn)=>{let r=yE(t,n);if(a(r))return r;let o=ps(e),s=qp.join(o,Or(r.value.hash,r.value.ext));try{Rs.existsSync(s)||(Rs.mkdirSync(o,{recursive:!0}),Rs.writeFileSync(s,t))}catch(i){return c(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return u("Wrote attachment blob",r.value)},Qp=(e,t,n=bn)=>{if(!hE(t))return c("Invalid attachment file name");let r=qp.join(ps(e),t);if(!Rs.existsSync(r))return c("Attachment blob not found");let o;try{o=Rs.readFileSync(r)}catch(d){return c(`Unable to read attachment blob: ${d instanceof Error?d.message:String(d)}`)}if(o.length>n*1024)return c(`Attachment exceeds the ${n} KB size cap and will not be served`);let[s,i]=t.split(".");if(Xp(o)!==s)return c("Attachment blob does not match its content hash");let l=Yp(o);return a(l)?l:l.value!==i?c("Attachment blob content does not match its extension"):u("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var Cs=50,Ns=5e3,Zp=()=>{let e=oe().commandMeta.inputString,t=vE.coerce.number().int().min(Cs).max(Ns).safeParse(e);if(!t.success)return c(`Attachment size cap must be ${Cs}-${Ns} KB (default ${bn})`);let n=Ft({attachmentMaxKb:t.data});return a(n)?n:($e({attachmentMaxKb:t.data}),u(`Attachment size cap set to ${t.data} KB`,null))};var at=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null;import{createHash as bE}from"node:crypto";var xE="0123456789ABCDEFGHJKMNPQRSTVWXYZ",IE=e=>{let t=bE("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+=xE[Number(n>>s&31n)]}return r},ef=new Map,we=(e,t)=>{let n=`${e}:virtual:${t}`,r=ef.get(n);if(r!==void 0)return r;let o=IE(n);return ef.set(n,o),o};import tf from"chalk";var Se=e=>tf.dim(e),Ue=e=>tf.hex(y.primary)(e),je=({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)=>zi(f)-zi(g)).slice(0,r).map(f=>Ki(f)).join(" ");return p?`${Se(e)}${p}${Se(n)}`:""};var xn={None:"none",Invalid:"invalid",Valid:"valid"};var EE=["BOARD","TICKET","SWIMLANE"],nf=()=>{let e=v().selectedNode;if(!e?.context)return z({message:Se("Missing target context")});if(EE.includes(e.context))return se();if(e.parentNodeId){let t=v().nodes[e.parentNodeId];if(t?.id===we(t?.parentNodeId??"","comments"))return se()}return z({message:Se("Command not available in this context")})},me="<ENTER> to confirm",SE=()=>{let{userId:e}=V(),t=ve();return!e||a(t)?[]:gn(t.value.emailLinks,e)},se=(e="",t=[],n=!0)=>({message:n?Se(e):e,validity:xn.Valid,completionWordList:t}),z=({message:e,completionWordList:t=[]})=>({validity:xn.Invalid,message:e,completionWordList:t}),No=e=>e.length===0,rf=(e,t)=>{let n=ht(v().breadCrumb,"BOARD");if(a(n))return z({message:Ue("Command is not applicable in this context")});let r=vo(n.value.id);return a(r)?z({message:Ue(`Unable to ${t}: board id is not a valid ULID`)}):jp({date:e,horizonDate:r.value})?null:z({message:Ue(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},sa=e=>` ${of.hex("#000").bgHex(ze(e))(` ${e} `)} `,Uc=({modifier:e})=>{let t="confirm";return e===t?se(me):z({message:No(e)?Se("if you are certain, enter ")+Ki(t):"",completionWordList:[t]})},RE=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?z({message:Se(n)}):se():z({message:No(r)?t:"",completionWordList:[...e]}),Co=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>No(n)&&No(r)?z({message:e,completionWordList:[]}):se(t??me),CE=({modifier:e,inputString:t})=>{let n=_c();return!No(e)||!No(t)?se(me):z({message:n.length?Se("number from the list, or a path"):Se("path to an epiq project"),completionWordList:n})},NE=({modifier:e,inputString:t})=>{let n=Be(R.CONFIG);if(!n.includes(e))return z({message:je({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case he.EDITOR:{let r=[...Vp];return t.trim()?r.includes(t.trim())?se(me):z({message:je({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):z({message:je({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case he.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?se(me):z({message:je({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case he.USERNAME:{let r=V().gitName,o=r?[r]:[],s=t.trim(),i=o.filter(m=>m.startsWith(s)),d=i.length===1&&i[0]===s?"":je({prefix:"name: ",wordList:o,inputString:s,minLengthForHints:0});return s?d?se(`${d} ${Se(me)}`,o,!1):se(me,o):z({message:d||Ue("Enter a user name. Saved in ")+of.bgBlack("~/.epiq-global/config.json"),completionWordList:o})}case he.EMAILS:{let r=V().gitEmail,o=Ro(),s=o.length>0||!r?o:[r],i=[...s,"none"],l=t.trim(),d=(x,b)=>z({message:je({prefix:x,wordList:i,noOfHints:3,inputString:b,minLengthForHints:0}),completionWordList:i});if(!l)return se(`${me} to see your addresses, or name one`,i);let m=l.split(/[,\s]+/).filter(Boolean),p=m[m.length-1]??"",f=x=>x==="none"||s.includes(x.toLowerCase()),g=x=>i.some(b=>b.startsWith(x.toLowerCase())),h=m.filter(x=>!f(x)&&!g(x));return h.length>0?z({message:Ue(`no address here matches ${h.join(", ")} \u2014 pick one from the list, or its number`),completionWordList:i}):f(p)?se(me):d("",p)}case he.EMAILS_UNCLAIM:{let r=SE(),o=t.trim();return r.length===0?z({message:Ue("you have not claimed any addresses"),completionWordList:[]}):o&&r.includes(o.toLowerCase())?se(me):z({message:je({prefix:"give an address back ",wordList:r,noOfHints:3,inputString:o,minLengthForHints:0}),completionWordList:r})}case he.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?se(me):z({message:je({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case he.AUTOSYNC:{let r=["on","off"],o=V().autoSync;if(!r.includes(t.trim())){let s=Fp(o);return z({message:je({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return se(me)}case he.ATTACHMENT_MAX_KB:{let r=V().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<Cs||o>Ns){let s=je({prefix:" examples: ",wordList:Fc,minLengthForHints:0,inputString:t});return z({message:Ue(`provide a size cap in KB (${Cs}-${Ns}). current: ${r??bn} KB.`)+s,completionWordList:Fc})}return se(me)}case he.SYNC_DEBOUNCE_MS:{let r=V().autoSyncIntervalMs,o=uo(t);if(!t.trim()||o===null){let s=je({prefix:" examples: ",wordList:Oc,minLengthForHints:0,inputString:t});return z({message:Ue(`provide a duration between ${3e3}ms and ${864e5}ms. current duration: ${r}ms.`)+s,completionWordList:Oc})}return se(me)}default:return z({message:Ue("Unknown config option"),completionWordList:n})}},AE=({modifier:e,inputString:t})=>{let n=Be(R.EDIT);if(!n.length)return z({message:Ue("Command not available in this context")});if(!n.includes(e)){let r=je({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return z({message:r||Ue("Unknown edit option"),completionWordList:n})}switch(e){case Pt.COMMENT:return t.trim()?se(me):z({message:Se("write a comment...")});case Pt.TITLE:return se(me);case Pt.DESCRIPTION:{let{preferredEditor:r}=V();return r?se(Se("<ENTER> to edit in ")+r):z({message:"No editor selected"})}default:return z({message:Ue("Unknown edit option"),completionWordList:n})}},TE=({modifier:e})=>{let t=Be(R.YANK);return t.length?t.includes(e)?se(me+Se(" and copy to clipboard")):z({message:je({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):z({message:Ue("Nothing selected to copy from")})},wE={[R.EXPORT]:()=>se(me+Se(", and create export markdown file")),[R.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return se(me);let n={message:Se("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=kr(r);if(!r||!o)return z(n);let s=rf(o,"peek");return s||se(me)},[R.REPLAY]:e=>{let{dateInput:t,durationInput:n}=ra(e.modifier,e.inputString),r={message:Se("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=kr(t);if(!t||!o)return z(r);let s=rf(o,"replay");return s||(n&&na(n)===null?z({message:Ue("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):se("<ENTER> to replay board history",n?Gp:[]))},[R.EXIT]:()=>se(me+Se(" and exit the application")),[R.INIT]:()=>se(me),[R.OPEN]:CE,[R.PALETTE]:()=>se(me),[R.FILTER]:e=>{if(e.modifier==="clear")return se(me);let t=s=>Be(R.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return z({message:je({wordList:Be(R.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Be(R.FILTER)});let n=Object.values(v().tags).map(s=>s.name),r=Object.values(v().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?z({message:je({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):se():z({message:je({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[R.NONE]:e=>{let t=Be(R.NONE);return z({message:je({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[R.NEW]:e=>RE({list:Be(R.NEW),hint:je({wordList:Be(R.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[R.HELP]:()=>se(me),[R.EDIT]:AE,[R.COMMENT]:e=>{let t=Co({hint:Se(`write a comment (max ${4e3} char)...`),onOk:Se(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===xn.Invalid?t:e.inputString.length>4e3?se(Ue("max input exceeded")):t},[R.CONFIG]:NE,[R.YANK]:TE,[R.DELETE]:e=>{let t=nf();return t.validity==="invalid"?t:Uc(e)},[R.CLOSE_ISSUE]:e=>Uc(e),[R.RE_OPEN_ISSUE]:e=>Uc(e),[R.MOVE]:e=>{let t=nf();return t.validity==="invalid"?t:Co({hint:je({prefix:"hey hacker! These commands are blocked for you... ",wordList:Be(R.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[R.TAG]:e=>{let n=C.getExistingTags().slice(0,10).map(sa).join("");return Co({hint:n.length?Se("create tag or reuse:")+n+Se(""):Se("create tag ...")})(e)},[R.UNTAG]:e=>{let t=ea();if(a(t))return z({message:Ue("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(sa).slice(0,10);return n.length?Co({hint:Se(" ... ")+n.join("")})(e):z({message:Ue("Issue has no tags"),completionWordList:[]})},[R.ASSIGN]:e=>{let t=C.getExistingAssignees().map(sa).slice(0,10);return Co({hint:Se("assignees... ")+t.join("")})(e)},[R.UNASSIGN]:e=>{let t=ta();if(a(t))return z({message:Ue("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(sa).slice(0,10);return n.length?Co({hint:Se("remove assignee... ")+n.join("")})(e):z({message:Ue("Issue has no assignees"),completionWordList:[]})},[R.SYNC]:()=>se(me)},sf=Object.fromEntries(Object.entries(wE).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var ia=["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 ME=3,PE=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"]),LE=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},kE=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=ME&&!PE.has(t)&&!/^\d+$/.test(t)),DE=e=>{let t=new Map;for(let s of LE(e))for(let i of kE(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=ia.filter(s=>!r.has(s));return[...n,...o]},af=ia,lf=-1,cf=()=>{let e=ve();if(a(e))return ia;let t=e.value,n=t.eventLog.length;return n!==lf&&(af=DE(t),lf=n),af};var df=e=>Object.values(R).includes(e),uf=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:l,completionWordList:d}=sf[n].validate(n,r,s),m=n!==R.PEEK&&n!==R.REPLAY,p=o==="command"||o==="modifier"?Be(n):m?cf():[],{mode:f}=v(),g=f===I.COMMAND_LINE?i??"":"",h=[...d,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?Np(e,h,d):{hint:"",hints:[],remainder:"",overlap:0}}};var mf=e=>{let t=e.trimStart(),n=OE(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=FE(e),l=df(r)?r:null,d=l!==null,m=r!=="",p=l?Be(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 h=s?"":i,x=BE(t,l,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:l,isCommandKeyword:d,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:h,inputString:x}},BE=(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},OE=e=>e.trim()?e.trim().split(/\s+/):[],FE=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as _E}from"react";var Ao=e=>e===jc||e===":",jc=" ",Ts=40,lt={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:xn.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Hc=new Set,pf=()=>{for(let e of Hc)e()},Wc=e=>(Hc.add(e),()=>Hc.delete(e)),$t=e=>{let n=e(lt),r=mf(n.value),o=n.cursorPosition===n.value.length;lt={...n,commandMeta:uf(r,o)},pf()},ws=({message:e,status:t})=>{let n=structuredClone(lt);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,lt=n,pf(),u(e,null)},Gc=e=>{$t(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Vc=e=>{$t(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Ao(n[o-1]);)o--;for(;o>0&&!Ao(n[o-1]);)o--}else{for(;o<n.length&&!Ao(n[o]);)o++;for(;o<n.length&&Ao(n[o]);)o++}return{...t,cursorPosition:o}})},ff=()=>{$t(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}})},gf=()=>{$t(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Ao(t[r-1]);)r--;for(;r>0&&!Ao(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},aa=e=>{$t(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}})},hf=()=>{$t(e=>({...e,commandIsPending:!0}))},J=e=>{$t(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},yf=({addToHistory:e=!0,line:t})=>{$t(n=>{let r=t??n.value;return{...n,commandHistory:e&&r.trim()?[r,...n.commandHistory].slice(0,Ts):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}})},vf=e=>{$t(t=>({...t,commandHistory:e.slice(0,Ts),commandHistoryIndex:-1}))},bf=()=>{$t(e=>e.commandHistoryIndex===-1?e:{...e,commandHistoryIndex:-1})},xf=()=>{$t(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}})},If=()=>{$t(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},oe=()=>lt,Ef=()=>_E(Wc,oe,oe),la=()=>{let[e,...t]=lt.value.split(jc);return t.join(jc).trim()};var E={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavPreviousItemJump:"navPreviousItemJump",NavNextItemJump:"navNextItemJump",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MovePreviousItemJump:"movePreviousItemJump",MoveNextItemJump:"moveNextItemJump",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",OpenInEditor:"openInEditor",MarkDiffLine:"markDiffLine",CommentOnDiffLine:"commentOnDiffLine",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"},$E=e=>e.shift===!0,UE={[E.NavPreviousItem]:E.NavPreviousItemJump,[E.NavNextItem]:E.NavNextItemJump,[E.MovePreviousItem]:E.MovePreviousItemJump,[E.MoveNextItem]:E.MoveNextItemJump};function jE(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function HE(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function WE(e,t,n){let r=v().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function Sf(e,t){let n=oe();if(e.sequence==="?"&&t!==I.PALETTE)return E.InitCommandPalette;if(e.sequence===":"&&t!==I.COMMAND_LINE)return E.InitCommandLine;if(t===I.MOVE)switch(e.name){case"m":case"return":return E.ConfirmMove}if(t===I.COMMAND_LINE)return yp(e,n.value);if(t===I.PALETTE)return vp(e,n.value);let r=jE(e)||HE(e);if(r)return GE(r,t,$E(e));if(e.ctrl&&e.name==="c")return E.Exit;switch(e.name){case"r":return E.EditTitle;case"e":return E.EditDescription;case"n":return E.AddItem;case"m":return E.InitMove;case"d":return E.Delete;case"y":return E.Yank;case"o":return E.OpenInEditor;case"s":return E.MarkDiffLine;case"c":return E.CommentOnDiffLine;case"return":return E.Confirm;case"space":return E.Confirm;case"v":return V().viewMode==="wide"?E.SetViewDense:E.SetViewWide;case"q":case"escape":return E.Exit;default:return null}}function GE(e,t,n=!1){let r=t===I.MOVE?{prevItem:E.MovePreviousItem,nextItem:E.MoveNextItem,prevContainer:E.MoveToPreviousContainer,nextContainer:E.MoveToNextContainer}:{prevItem:E.NavPreviousItem,nextItem:E.NavNextItem,prevContainer:E.NavToPreviousContainer,nextContainer:E.NavToNextContainer},o=WE(v().contextNode.childRenderAxis,e,r);return!o||!n?o:UE[o]??o}import{ulid as KE}from"ulid";var Ms=24n,VE=Ms*4n,Qt=(1n<<VE)-1n,zE=/^[0-9a-f]+$/;function Rf(e){return!e||!zE.test(e)?c(`Invalid hex rank: ${e}`):u("Converted rank to bigint",BigInt("0x"+e))}function Lt(e,t=Ms){if(e<0n)return c("Negative rank not allowed");let n=e.toString(16);return u("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function yt(e,t){if(!e&&!t)return Lt(Qt/2n,Ms);let n=e?Rf(e):u("Resolved lower bound",0n);if(a(n))return n;let r=t?Rf(t):u("Resolved upper bound",Qt);if(a(r))return r;let o=n.value,s=r.value;if(s<=o)return c("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?c("No rank space available between neighbors"):Lt(i,Ms)}function Cf(e){if(e<=0)return u("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Qt*BigInt(r+1)/(t+1n),s=Lt(o,Ms);if(a(s))return s;n.push(s.value)}return u("Resolved evenly spaced ranks",n)}var D=({userId:e})=>({userId:e}),Nf=e=>({action:e.action,payload:e.payload});var zc=["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","link.contributor.email","unlink.contributor.email"];var ND=new Set(zc);var Kc=(e,t)=>{let n=be(e),r=Cf(n.length);if(a(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 c("Unable to assign rebalance rank");o[i.id]=l}return u("Created rebalance event",{id:KE(),action:"rebalance.children",payload:{parent:e,ranks:o},...D(t)})};import{z as Fr}from"zod";var Af=1,Tf=Fr.tuple([Fr.string().min(1),Fr.string().min(1).nullable()]),qE=Fr.looseObject({v:Fr.literal(Af),id:Tf}),UD=Fr.looseObject({v:Fr.number().int().positive(),id:Tf}),YE=e=>Object.prototype.hasOwnProperty.call(e,"__proto__"),XE=e=>{let t={};for(let n of Object.keys(e))n!=="__proto__"&&(t[n]=e[n]);return t},wf=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return c("Invalid persisted event envelope: expected an object");let{v:t,id:n}=e;if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return c("Invalid persisted event envelope: v");if(!Array.isArray(n)||n.length!==2)return c("Invalid persisted event envelope: id");let[r,o]=n;return typeof r!="string"||r.length===0?c("Invalid persisted event envelope: id.0"):o!==null&&(typeof o!="string"||o.length===0)?c("Invalid persisted event envelope: id.1"):u("Parsed persisted event envelope",YE(e)?XE(e):e)};var JE=[1];var QE=new Set(JE),qc=e=>QE.has(e),Mf=e=>{let t=qE.safeParse(e);return t.success?u("Parsed persisted event",t.data):c(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Yc=(e,t)=>{let n={[e.action]:e.payload,v:Af,id:t};return Mf(n)};import Ds from"node:fs";import fa from"node:path";import{decodeTime as aS}from"ulid";import{z as nd}from"zod";import Xc from"node:fs";import ZE from"node:path";var Ps=e=>e?.code==="ENOENT",Jc=3,Qc=e=>Xc.readdirSync(e).filter(t=>t.endsWith(".jsonl")).sort(),In=e=>{let t=Et(e);for(let n=1;;n++){if(!Xc.existsSync(t))return"none";let r=[],o=!1;for(let s of Qc(t))try{let{size:i,mtimeMs:l}=Xc.statSync(ZE.join(t,s));r.push(`${s}:${i}:${l}`)}catch(i){if(!Ps(i))throw i;if(n<Jc){o=!0;break}}if(!o)return r.join("|")}},Pf=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),Zc=(e,t,n)=>{let r=Pf(t),o=In(e),s=Pf(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},sr=null,Lf=e=>sr&&sr.root===e?sr.signature:null,kf=(e,t)=>{sr={root:e,signature:t}},Df=(e,t)=>{if(!sr||sr.root!==e)return;let n=Zc(e,sr.signature,t);sr=n===null?null:{root:e,signature:n}};import He from"node:fs";import _r from"node:path";import{ulid as eS}from"ulid";var da="~pending",ed=/~pending(-[0-9a-z]+)*$/i,Of=/-f(\d+)$/,Ff=e=>{let t=e.indexOf(".");return t===-1?`${e}${da}`:e.slice(0,t)+da+e.slice(t)},ua=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},tS=e=>{let[t,n]=ua(e);return ed.test(t)?t.replace(ed,"")+n:null},td=e=>e.replace(ed,""),$r=e=>e.endsWith(".jsonl")&&tS(e)!==null,Ls=e=>td(ua(e)[0]),_f=e=>{let[t]=ua(e),n=Of.exec(t);return n&&$r(e)?Number(n[1]):null},nS=e=>Ff(e).replace(da,`${da}-${eS().toLowerCase()}`),rS=(e,t)=>{let[n,r]=ua(e);return`${n.replace(Of,"")}-f${t}${r}`},$f=(e,t)=>_r.join(Et(e),Ff(t)),oS=(e,t)=>Math.max(0,He.statSync(e).size-(_f(t)??0)),Uf=e=>{let t=Et(e);try{return He.existsSync(t)?He.readdirSync(t).filter($r).some(n=>oS(_r.join(t,n),n)>0):!1}catch{return!0}},sS=3,jf=(e,t)=>{for(let n=1;;n++){let r=He.openSync(e,"a"),o;try{He.writeSync(r,t),o=He.fstatSync(r).ino}finally{He.closeSync(r)}let s;try{s=He.statSync(e).ino}catch{s=null}if(s===o||n>=sS)return}},iS=e=>{let t;try{t=He.openSync(e,"r")}catch{return!0}try{let{size:n}=He.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return He.readSync(t,r,0,1,n-1),r[0]===10}finally{He.closeSync(t)}},ca=10,Bf=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(ca)+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};He.appendFileSync(e,Buffer.concat([Buffer.from(iS(e)?"":`
|
|
30
|
+
`),o,Buffer.from(o[o.length-1]===ca?"":`
|
|
31
|
+
`)]));let s=0;for(let i of o)i===ca&&s++;return o[o.length-1]!==ca&&s++,{bytes:r,lines:s}},ma=(e,t)=>{let n=Et(e);if(!He.existsSync(n))return u("No events directory",0);try{let r=Ls(t),o=He.readdirSync(n).filter(l=>$r(l)&&Ls(l)===r),s=_r.join(n,t),i=0;for(let l of o){let d=_f(l);if(d!==null){let g=_r.join(n,l),h=He.readFileSync(g).subarray(d);i+=Bf(s,h,!0).lines,He.rmSync(g,{force:!0});continue}let m=/~pending-/i.test(l)?l:nS(t),p=_r.join(n,m);m!==l&&He.renameSync(_r.join(n,l),p);let f=Bf(s,He.readFileSync(p));i+=f.lines,He.renameSync(p,_r.join(n,rS(m,f.bytes)))}return u("Folded pending logs",i)}catch(r){return c(`Unable to fold pending event logs in ${n}: ${r instanceof Error?r.message:String(r)}`)}};var ga="unknown",lS=nd.object({userId:nd.string().min(1).default(ga),userName:nd.string().min(1).default(ga)}),Vf=new Set(["id","v","userId","userName"]),pa=e=>{let t=Object.entries(e).filter(([o])=>!Vf.has(o));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},cS=/^[0-9a-hjkmnp-tv-z]{26}$/i,dS=e=>cS.test(e)?e.toUpperCase():e,zf=e=>{let t=fa.basename(e,".jsonl"),n=t.indexOf("."),r=td(n===-1?t:t.slice(0,n)),o=n===-1?void 0:t.slice(n+1),s=lS.safeParse({userId:dS(r),userName:o});return s.success?u("Parsed event file actor",s.data):c(`Invalid event file name ${fa.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},uS=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?c(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?c("Invalid persisted event: action key is missing or invalid"):u("Resolved persisted action",t[0])},mS=(e,t)=>t in e,ir=new Map,pS=3e5,fS=512,ks=0,rd=e=>e.entries.length+e.quarantined.length,gS=(e,t,n,r)=>{let o=ir.get(e);o&&(ks-=rd(o));let s={stamp:t,entries:n,quarantined:r};ir.delete(e),ir.set(e,s),ks+=rd(s);for(let[i,l]of ir){if(ks<=pS&&ir.size<=fS)break;i!==e&&(ir.delete(i),ks-=rd(l))}},hS=()=>{ir.clear(),ks=0},yS=2n,Hf=1000000n,vS=e=>{try{let{size:t,mtimeNs:n}=Ds.statSync(e,{bigint:!0});return{value:`${t}:${n}`,settled:BigInt(Date.now())*Hf-n>yS*Hf}}catch{return null}},Kf=(e,t)=>{let n=zf(e);if(a(n))return c(n.message);let r=vS(e),o=r?ir.get(e):void 0;if(r&&o&&o.stamp===r.value){if(t)for(let p of o.quarantined)t.push(p);return u("Parsed persisted events file",[...o.entries])}let s;try{s=Ds.readFileSync(e,"utf8")}catch(p){if(Ps(p))return u("Event file missing",null);throw p}let i=[],l=fa.basename(e),d=[],m=(p,f)=>{d.push({eventId:null,reason:"corrupt-line",detail:`${l}:${p} (${f})`,targetNodeId:null})};for(let[p,f]of s.split(`
|
|
32
|
+
`).entries()){let g=f.trim();if(!g)continue;let h;try{h=JSON.parse(g)}catch{m(p+1,"invalid JSON");continue}let x=wf(h);if(a(x)){m(p+1,x.message);continue}i.push({...x.value,userId:n.value.userId,userName:n.value.userName})}if(t)for(let p of d)t.push(p);return r?.settled&&gS(e,r.value,i,d),u("Parsed persisted events file",[...i])},Wf=(e,t)=>e<t?-1:e>t?1:0,od=(e,t)=>{let n=Wf(e.id[0],t.id[0]);return n!==0?n:Wf(JSON.stringify(e),JSON.stringify(t))},Gf=(e,t)=>{let n=new Map,r=new Map;for(let p of e){let f=p.id[0],g=p.id[1]??null;n.set(f,p);let h=r.get(g)??[];h.push(p),r.set(g,h)}for(let p of r.values())p.sort(od);let o=[],s=new Set,i=p=>{let f=[p];for(;f.length>0;){let g=f.pop(),h=g.id[0];if(s.has(h))continue;o.push(g),s.add(h);let x=r.get(h)??[];for(let b=x.length-1;b>=0;b--)f.push(x[b])}},l=(r.get(null)??[]).filter(p=>{let f=Object.keys(p).filter(g=>!Vf.has(g));return f.length===1&&f[0]===t});for(let p of l)i(p);let d=e.filter(p=>{let f=p.id[0],g=p.id[1]??null;return s.has(f)?!1:g===null||!n.has(g)}).sort(od);for(let p of d)i(p);let m=e.filter(p=>!s.has(p.id[0])).sort(od);for(let p of m)i(p);return o},sd=e=>yo(e.map(t=>{try{return aS(t.id[0])}catch{return null}})),qf=(e,t)=>{let n=new Set,r=[],o=[],s=sd(e);for(let i=0;i<e.length;i++){let l=e[i],d=l.id[0],m=l.id[1],p=s[i]??null;!(p!==null&&p<t)||m&&n.has(m)?(n.add(d),o.push(l)):r.push(l)}return{appliedEvents:r,unappliedEvents:o}},Yf=e=>{let t=new Set(e.actions),n=S=>t.has(S),r=S=>{let{userId:A,userName:T,...P}=S,M=uS(P);if(a(M))return c(M.message);let O=M.value,W=S.id?.[0];return W?mS(P,O)?u("Decoded persisted event",{id:W,action:O,payload:P[O],userId:A}):c(`Persisted event is missing payload for action: ${O}`):c("Persisted event is missing id")},o=(S,A)=>{let T=[],P=new Map,M=new Map;for(let O of S){if(!qc(O.v)){M.set(O.v,(M.get(O.v)??0)+1),A?.push({eventId:O.id[0],reason:"unsupported-schema-version",detail:`v${O.v}`,targetNodeId:pa(O)});continue}let W=r(O);if(a(W)){A?.push({eventId:O.id[0],reason:"invalid-payload",detail:W.message,targetNodeId:pa(O)});continue}let Y=W.value.action;if(!n(Y)){P.set(Y,(P.get(Y)??0)+1),A?.push({eventId:O.id[0],reason:"unknown-action",detail:Y,targetNodeId:pa(O)});continue}let xe=e.readPayload(Y,W.value.payload);if(a(xe)){A?.push({eventId:O.id[0],reason:"invalid-payload",detail:xe.message,targetNodeId:pa(O)});continue}T.push(W.value)}if(P.size>0){let O=[...P.entries()].map(([W,Y])=>`${W} (x${Y})`).join(", ");ne.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${O}. Upgrade to apply them.`)}if(M.size>0){let O=[...M.entries()].map(([W,Y])=>`v${W} (x${Y})`).join(", ");ne.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${O}. Upgrade to apply them.`)}return u("Decoded reconstructed events",T)},s=null;function i(S,A){let T=Et(S),P=In(S);if(!Ds.existsSync(T))return u("No events found",[]);let M=[],O=[];for(let Y=1;;Y++){M=[],O=[];let xe=!1;for(let F of Qc(T)){let X=Kf(fa.join(T,F),O);if(a(X))return c(X.message);if(X.value===null){if(Y<Jc){xe=!0;break}continue}for(let Ve of X.value)M.push(Ve)}if(!xe)break}if(A)for(let Y of O)A.push(Y);let W=Gf(M,e.genesis);return s={root:S,signature:P,edge:W.at(-1)?.id?.[0]??null},u("All events loaded",W)}function l(S){let A=[],T=i(S,A);if(a(T))return c(T.message);let P=o(T.value,A);return a(P)?c(P.message):u("Loaded merged events",{events:P.value,unreadable:A})}function d(S){let A=i(S);return a(A)?c(A.message):u("Loaded event actors",A.value.map(({userId:T,userName:P})=>({userId:T,userName:P})))}function m(S){let A=new Map,T=Et(S),P;try{if(!Ds.existsSync(T))return A;P=Ds.readdirSync(T)}catch{return A}let M=new Set;for(let W of P){if(!W.endsWith(".jsonl"))continue;let Y=zf(W);if(a(Y))continue;let{userId:xe,userName:F}=Y.value;if(!xe||!F||F===ga)continue;let X=A.get(xe);X!==void 0&&X!==F&&M.add(xe),A.set(xe,F)}if(M.size===0)return A;let O=d(S);if(a(O))return A;for(let{userId:W,userName:Y}of O.value)M.has(W)&&(!Y||Y===ga||A.set(W,Y));return A}function p(S){let A=l(S);return a(A)?c(A.message):u("Loaded merged events",A.value.events)}function f(S,A){let T=i(S);if(a(T))return c(T.message);let{appliedEvents:P,unappliedEvents:M}=qf(T.value,A),O=o(P);if(a(O))return c(O.message);let W=o(M);return a(W)?c(W.message):u("Loaded merged events before time",{appliedEvents:O.value,unappliedEvents:W.value})}function g(S=process.cwd()){let A=In(S);if(s&&s.root===S&&s.signature===A)return u("Loaded edge reference, unchanged",s.edge);let T=i(S);return a(T)?c(T.message):u("Loaded edge reference",T.value.at(-1)?.id?.[0]??null)}function h(S,A,T){if(!s||s.root!==S)return;let P=Zc(S,s.signature,A);s=P===null?null:{root:S,signature:P,edge:T}}function x(){s=null,hS()}let b=S=>Gf(S,e.genesis);function N(S){let A=i(S);if(a(A))return c(A.message);let T=sd(A.value);return u("Loaded effective event times",new Map(A.value.map((P,M)=>[P.id[0],T[M]??null])))}return{fromPersistedEvent:r,decodeReconstructedEvents:o,loadMergedEventsWithUnreadable:l,loadEventActors:d,loadActorNames:m,loadMergedEvents:p,loadMergedEventsBefore:f,getEdgeRef:g,advanceEdgeRef:h,clearEdgeCache:x,getSortedEvents:b,loadEffectiveEventTimes:N}};var ha=(e,t)=>c(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),$=(e,t)=>({...ha(e,t),convergence:!0}),To=e=>a(e)&&e.convergence===!0,En=e=>{let t=e.filter(a);return{fatal:t.filter(n=>!To(n)),skipped:t.filter(To)}},Sn=e=>{e.length!==0&&ne.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},bS=e=>e.userId?.length?null:ha("Invalid user ID format",e),Xf=e=>{let t=null;function n(o,s=!1){let i=e.apply[o.action];if(!i)return c(`Unknown event action "${o.action}", likely created by a newer epiq version. Evt id: ${o.id}`);if(!e.replay.isInitialized()&&o.action!==e.genesis)return $(`${o.action} arrived before the state was initialized`,o);if(o.action===e.genesis&&t){if(t.genesisApplied)return $("the state is already initialized",o);t.genesisApplied=!0}let l;try{l=i(o)}catch(p){return $(`threw while materializing (${p instanceof Error?p.message:String(p)})`,o)}if(a(l))return l;let d=bS(o);if(d)return d;let m=e.replay.afterApply(o,{batched:t!==null,bypassLogging:s});return m||l}return{materialize:n,materializeAll:o=>{let s=e.replay.batch(()=>{let i=t===null;i&&(t={genesisApplied:!1});let l=!1;try{let d=o.map(m=>n(m));if(i){l=!0;let m=e.replay.flush();if(m)return o.map(()=>m)}return d}finally{i&&(t=null,l||e.replay.flush())}});return a(s)?o.map(()=>c(s.message)):s.value}}};import Qf from"node:fs";import id from"node:path";import{decodeTime as xS,monotonicFactory as IS}from"ulid";var Jf=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown";var ES=0xffffffffffff,SS=Wi,RS=e=>{let t=Date.now(),n;try{n=xS(e)}catch{return t}return n>=ES?t:n>t+SS?(ne.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)},ar=({userId:e})=>`${Jf(e)}.jsonl`,Zf=(e,t)=>{let n;try{if(!Qf.existsSync(e))return[t];n=Qf.readdirSync(e)}catch{return[t]}let r=Ls(t);return[...n.filter(s=>!s.endsWith(".jsonl")||s===t||$r(s)?!1:Ls(s)===r).sort(),t]},eg=(e,{userId:t})=>{let n=ar({userId:t});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(n))return c(`Invalid event log file name: ${n}`);let o=id.join(Et(e),n);return u("Successfully resolved event log path",o)},tg=e=>{let t=IS();function n(o,s){let i;if(s&&s.current!==void 0)i=s.current;else{let d=e.getEdgeRef(o);if(a(d))return c(d.message);i=d.value}let l=i?t(RS(i)):t();return u("Minted event id",[l,i])}function r({event:o,rootDir:s,edge:i,id:l}){try{let d=Xm(s);if(a(d))return d;let m=eg(s,{userId:o.userId});if(a(m))return m;let p=$f(s,id.basename(m.value)),f=l?u("Minted event id",l):n(s,i);if(a(f))return c(f.message);let[g,h]=f.value,x=Yc(Nf(o),[g,h]);if(a(x))return c(x.message);jf(p,`${JSON.stringify(x.value)}
|
|
33
|
+
`),i&&(i.current=g);let b=id.basename(p);return e.advanceEdgeRef(s,b,g),Df(s,b),u("Event persisted",{path:p,entry:x.value})}catch(d){let m=d instanceof Error?d.message:"Unknown persist error";return c(`Failed to persist event: ${m}`)}}return{mintEventId:n,persist:r}};var ng=(e,t,n)=>{function r(s,i,l){let d=n.mintEventId(i,l);if(a(d))return c(d.message);let m={...s,id:d.value[0]},p=t.materialize(m);if(p.status!==Zn.Success)return p;let f=n.persist({event:m,rootDir:i,edge:l,id:d.value});return a(f)?f:p}function o(s,i){if(s.length===0||!s[0])return c("No events provided");let l=e.write.readOnlyReason();if(l)return c(l);let d=e.replay.batch(()=>{let m={},p=e.write.beforeWrite(s[0],h=>r(h,i,m));if(a(p))return c(p.message);let f=s.map(h=>r(h,i,m)),g=f.filter(a);return g.length>0?c("Materialize and persist failed: "+g.map(h=>h.message).join(", ")):u("Materialization succeeded",f.map(h=>h.value))});return a(d)?c(d.message):d.value??c("Materialize and persist produced nothing")}return{materializeAndPersist:r,materializeAndPersistAll:o}};var rg=e=>{let t=Xf(e),n=Yf(e),r=tg(n),o=ng(e,t,r);return{...t,...n,...r,...o}};import{z as Q}from"zod";var K=Q.string().min(1),Zt=Q.string(),lr=Q.string(),ya=Q.looseObject({id:K}),ad=Q.looseObject({id:K,name:Zt,parent:K,rank:lr}),CS={"init.workspace":Q.looseObject({id:K,name:Zt,rank:lr}),"add.workspace":Q.looseObject({id:K,name:Zt,rank:lr}),"add.board":ad,"add.swimlane":ad,"add.issue":ad,"add.field":Q.looseObject({id:K,name:Zt,parent:K,rank:lr}),"edit.title":Q.looseObject({id:K,name:Zt}),"delete.node":ya,"lock.node":ya,"move.node":Q.looseObject({id:K,parent:K,rank:lr}),"edit.description":Q.looseObject({id:K,md:Q.string()}),"close.issue":Q.looseObject({id:K,parent:K,rank:lr}),"reopen.issue":Q.looseObject({id:K,parent:K,rank:lr}),"create.tag":Q.looseObject({id:K,name:Zt}),"tombstone.tag":ya,"restore.tag":Q.looseObject({id:K,name:Zt}),"create.contributor":Q.looseObject({id:K,name:Zt}),"rename.contributor":Q.looseObject({id:K,name:Zt}),"tombstone.contributor":ya,"restore.contributor":Q.looseObject({id:K,name:Zt}),"link.contributor.user":Q.looseObject({contributor:K}),"link.contributor.email":Q.looseObject({contributor:K,email:K}),"unlink.contributor.email":Q.looseObject({contributor:K,email:K}),"add.issue.assignee":Q.looseObject({id:K,assignee:K}),"remove.issue.assignee":Q.looseObject({id:K,assignee:K}),"add.issue.tag":Q.looseObject({id:K,tag:K}),"remove.issue.tag":Q.looseObject({id:K,tag:K}),"add.issue.comment":Q.looseObject({id:K,issue:K,md:Q.string()}),"edit.issue.comment":Q.looseObject({id:K,issue:K,md:Q.string()}),"delete.issue.comment":Q.looseObject({id:K,issue:K}),"add.issue.attachment":Q.looseObject({id:K,issue:K,hash:Q.string().min(1),ext:Q.string().min(1),name:Zt,bytes:Q.number()}),"delete.issue.attachment":Q.looseObject({id:K,issue:K}),"rebalance.children":Q.looseObject({parent:K,ranks:Q.record(Q.string(),lr)})},og=(e,t)=>{let r=CS[e].safeParse(t);return r.success?u("Payload is readable",void 0):c(`${e}: ${r.error.issues.map(o=>`${o.path.join(".")||"payload"} ${o.message}`).join(", ")}`)};import{ulid as NS}from"ulid";var sg=(e,t)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return u("Contributor write already in flight",void 0);let{userId:n,userName:r}=V();if(!r||n!==e.userId)return u("Not this actor own write",void 0);let o=C.getContributor(e.userId),s={id:NS(),action:o?"rename.contributor":"create.contributor",payload:{id:e.userId,name:r},userId:e.userId};if(o&&(o.tombstoned||o.name===r))return u("Contributor name is current",void 0);let i=t(s);return a(i)?c(i.message):u("Contributor name recorded",void 0)};var Ne={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",DIFF:"Diff",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var H=e=>e.slice(-7).toUpperCase(),va=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?H(e).includes(n):!0};var Re={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:re.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:H(e)},context:re.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:re.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:re.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:re.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:H(e)},context:re.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0,disabled:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:i?{disabled:!0}:{},context:re.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:re.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};var Bs=(e,t,n)=>C.getNode(e)?$(`a node with id ${e} already exists`,n):t===e?$("a node cannot be its own parent",n):null,ig={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Re.workspace(t,n,r),s=Os(o);if(a(s))return ha(s.message,e);let i=C.createNode(o);return a(i)?$(i.message??"Failed to initialize workspace",e):wc(i.value)?u("Workspace initialized",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Bs(t,void 0,e);if(o)return o;let s=C.createNode(Re.workspace(t,n,r));return a(s)?$(s.message??"Failed to add workspace",e):wc(s.value)?u("Added workspace",{action:e.action,result:s.value}):c("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Bs(t,r,e);if(s)return s;let i=C.createNode(Re.board(t,n,r,o));return a(i)?$(i.message??"Unable to create board",e):or(i.value)?u("Added board",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Bs(t,r,e);if(s)return s;let i=C.createNode(Re.swimlane(t,n,r,o));return a(i)?$(i.message??"Unable to create swimlane",e):hn(i.value)?u("Added swimlane",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Bs(t,r,e);if(s)return s;let i=C.createNode(Re.ticket(t,n,r,o));return a(i)?$(i.message??"Unable to create issue",e):_(i.value)?u("Added issue",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=Bs(t,r,e);if(i)return i;let l=C.createNode(Re.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(Ne.DESCRIPTION)?"vertical":"horizontal"}));return a(l)?$(l.message??`Unable to create field: ${n}`,e):it(l.value)?u("Added field",{action:e.action,result:l.value}):c("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!C.getNode(t))return $(`Unable to locate node with id ${t}`,e);let o=C.renameNode(t,n);return a(o)?$(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 a(n)?$(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 a(r)?$(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 a(n)?$(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 a(r)?$(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 a(r)?$(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 a(r)?$(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 a(n)?$(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 a(r)?$(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 a(r)?$(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 a(r)?$(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 a(r)?$(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 a(r)?$(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 a(o)?$(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 a(r)?$(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 $("Unable to locate issue",e);if(!_(o))return $("Can only close issues",e);let s=C.getNode(ge);if(!s)return $("Unable to locate target swimlane",e);if(n!==s.id)return $("Close target must be closed swimlane",e);let i=C.moveNodeToRank({id:t,parentId:n,rank:r});return a(i)?$(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 $("Unable to locate issue",e);if(!_(o))return $("Can only reopen issues",e);let s=C.getNode(ge);if(!s)return $("Unable to locate closed swimlane",e);if(n===s.id)return $("Cannot reopen issue into closed swimlane",e);if(!C.getNode(n))return $("Reopen parent no longer exists",e);let l=C.moveNodeToRank({id:t,parentId:n,rank:r});return a(l)?$(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 a(n)?$(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 $(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return $(`Node ${r} is not child of ${t}`,e);let i=C.updateNode({...s,rank:o});if(a(i))return $(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,md:o,deleted:!1});return a(s)?$(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 $("Unable to locate comment",e);if(o.issue!==n)return $("Comment does not belong to issue",e);let s=C.editComment(t,r);return a(s)?$(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 $("Unable to locate comment",e);if(r.issue!==n)return $("Comment does not belong to issue",e);let o=C.deleteComment(t);return a(o)?$(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 a(l)?$(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 $("Unable to locate attachment",e);if(r.issue!==n)return $("Attachment does not belong to issue",e);let o=C.deleteAttachment(t);return a(o)?$(o.message??"Unable to delete attachment",e):u("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.email":e=>{let{contributor:t,email:n}=e.payload;if(!nr(n))return $(`not an email address: ${n}`,e);let r=C.linkContributorEmail({email:n,contributor:t,authorId:e.userId});return a(r)?$(r.message??"Unable to link email",e):u("Email linked to contributor",{action:e.action,result:r.value})},"unlink.contributor.email":e=>{let{contributor:t,email:n}=e.payload,r=C.unlinkContributorEmail(n,t,e.userId);return a(r)?$(r.message??"Unable to unlink email",e):u("Email unlinked from contributor",{action:e.action,result:r.value})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=C.linkUserId({contributorId:t,userId:e.userId});return a(n)?$(n.message??"Unable to link contributor",e):u("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};var ag=e=>{let t=C.getNode(e);if(!t||!_(t)||t.isDeleted)return null;let n=dg(t);return a(n)?n:null},lg=e=>{if(!cd())return null;for(let t of e){let n=ag(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=ag(r);if(o)return o}return null},AS=(e,t)=>{let n=C.getNode(e);n&&C.updateNode({...n,log:[...n.log??[],t]})},TS=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},ld=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 TS(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":case"link.contributor.email":case"unlink.contributor.email":default:return[]}},wS=e=>{Oe(t=>({...t,eventLog:[...t.eventLog,e]}))},Hn=null,MS=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&&Oe(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),lg([...e.virtualNodeIds])},cg={isInitialized:()=>Ut(),batch:e=>ba(e),afterApply(e,{batched:t,bypassLogging:n}){let r=[...new Set(ld(e))];if(t){Hn??={appLog:[],nodeLog:new Map,virtualNodeIds:new Set};for(let o of r){if(!n){let s=Hn.nodeLog.get(o);s?s.push(e):Hn.nodeLog.set(o,[e])}if(cd()){Hn.virtualNodeIds.add(o);let s=v().nodes[o]?.parentNodeId;s&&Hn.virtualNodeIds.add(s)}}return n||Hn.appLog.push(e),null}return n||(r.forEach(o=>AS(o,e)),wS(e)),lg(r)},flush(){if(!Hn)return null;let e=Hn;return Hn=null,MS(e)}};var ue=()=>{let{userName:e,userId:t}=V();return e?t?Ql(t)?Di(e)?u("Successfully resolved actor ID",{userId:t,userName:e}):c("Invalid user name in config"):c("Invalid user ID in config"):c("User ID not configured"):c("User name not configured")};var PS={genesis:"init.workspace",actions:zc,readPayload:og,apply:ig,replay:cg,write:{readOnlyReason:()=>{let e=v();return e.readOnly?e.readOnlyReason??"Cannot change the board while time travelling":null},beforeWrite:sg}},LS=rg(PS),{materialize:Fs,materializeAll:en,fromPersistedEvent:zO,decodeReconstructedEvents:KO,loadMergedEventsWithUnreadable:tn,loadEventActors:ug,loadActorNames:cr,loadMergedEvents:dr,loadMergedEventsBefore:xa,getEdgeRef:qO,advanceEdgeRef:YO,clearEdgeCache:XO,getSortedEvents:JO,loadEffectiveEventTimes:Ia,mintEventId:QO,persist:mg,materializeAndPersist:ZO,materializeAndPersistAll:B}=LS;var Ur=e=>e.trim().toLocaleLowerCase(),dd=(e,t)=>Ur(e).includes(Ur(t));var kS=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},DS=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},pg=null,fg=new Map,BS=()=>{let e=v().eventLog??[];if(e===pg)return fg;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 pg=e,fg=t,t},OS=e=>{let{contributors:t}=v(),n=BS().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},gg=(e,t)=>{let n=Ur(t.value);if(!n)return!0;switch(t.target){case"title":return dd(e.title??"",n);case"description":return dd(e.props.description??"",n);case"tag":return kS(e).map(Ur).some(o=>o.includes(n));case"assignee":return DS(e).map(Ur).some(o=>o.includes(n));case"actor":return OS(e).map(Ur).some(o=>o.includes(n));case"ref":return va(e.id,t.value);default:return!0}};var ud=(e,t)=>e.rank<t.rank?-1:e.rank>t.rank?1:0,FS=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,hg=(e,t)=>Object.values(e).filter(n=>FS(n,t)).sort(ud),yg=(e,t)=>{let n={};for(let r of Object.values(e)){if(_(r)&&t.length>0&&!t.every(s=>gg(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(ud);return n},vg=(e,t)=>{let n={};for(let r of Object.values(e)){if(!r.parentNodeId||r.isDeleted||!t.has(r.parentNodeId))continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(ud);return n};var bg=e=>Ea(be(e),{at:"end"}),Ea=(e,t={at:"end"})=>{let n=o=>a(o)?u("Rank space exhausted",{rank:"",needsRebalance:!0}):u("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(yt(void 0,void 0));let r=()=>n(yt(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(yt(void 0,o.rank)):c("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(yt(o.rank,void 0)):c("Unable to resolve last sibling")}case"before":{let o=xg(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(yt(i?.rank,s.rank))}case"after":{let o=xg(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(yt(s.rank,i?.rank))}}},be=e=>{let t=v();if(!Eg()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return hg(t.nodes,e)},xg=(e,t)=>e.findIndex(n=>n.id===t),Ig=(e,t,n={at:"end"})=>Ea(be(t).filter(r=>r.id!==e),n),Rn=(e,t,n,r,o)=>{let s=Ig(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return u("Resolved rank",s.value.rank);let i=Kc(e,r);if(a(i))return i;let l=B([i.value],o);if(a(l))return l;let d=Ig(t,e,n);return a(d)?d:d.value.needsRebalance?c("Rank rebalance failed to create space"):u("Resolved rank after rebalance",d.value.rank)},Wn=(e,t,n)=>{let r=bg(e);if(a(r))return r;if(!r.value.needsRebalance)return u("Resolved rank",r.value.rank);let o=Kc(e,t);if(a(o))return o;let s=B([o.value],n);if(a(s))return s;let i=bg(e);return a(i)?i:i.value.needsRebalance?c("Rank rebalance failed to create space"):u("Resolved rank after rebalance",i.value.rank)};var _s=5,U={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=ae(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||U.navigate({contextNode:o,selectedIndex:ae(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=ae(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;U.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Sg(1),navigateToPreviousItem:()=>Sg(-1),jumpToNextItem:()=>Rg(_s),jumpToPreviousItem:()=>Rg(-_s),navigateToNextContainer:()=>Cg(1),navigateToPreviousContainer:()=>Cg(-1),navigate:({contextNode:e,selectedIndex:t})=>{w({contextNodeId:e.id,selectedIndex:t})}},Sg=e=>{let{selectedIndex:t,contextNode:n}=v(),r=ae(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;U.navigate({selectedIndex:s,contextNode:n})},Rg=e=>{let{selectedIndex:t,contextNode:n}=v(),r=ae(n.id).length;if(r===0)return;let o=Math.max(0,t),s=Math.min(Math.max(o+e,0),r-1);U.navigate({selectedIndex:s,contextNode:n})},Cg=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=ae(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 d=ae(l.id),m=Math.max(0,d.length-1),p=Math.min(Math.max(0,r),m),f=d.length?p:-1;U.navigate({contextNode:l,selectedIndex:f})};var Ag=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Tg=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},_S=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&&it(t)&&t.childRenderAxis==="vertical"},Sa=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=be(r.id);return U.navigate({contextNode:r,selectedIndex:Ag(t,o.length)}),!0},wg=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Sa(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=be(o.id).findIndex(l=>l.id===n.id);return i>=0?(U.navigate({contextNode:o,selectedIndex:i}),!0):wg(o.id)},Ng=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),wg(n))return!0;n=t[n]?.parentNodeId}return!1},$S=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},Mg=e=>{let{nodes:t,rootNodeId:n}=v();if(_S(e.contextNodeId)&&Sa(e.contextNodeId,e.selectedIndex))return u("Restored navigation inside text container",null);if($S(e.selectedNodeId)&&e.selectedNodeId&&Ng(e.selectedNodeId))return u("Restored navigation to selected node or ancestor",null);if(Sa(e.contextNodeId,e.selectedIndex))return u("Restored navigation to previous container",null);if(e.parentNodeId&&Sa(e.parentNodeId,e.selectedIndex))return u("Restored navigation to previous parent",null);if(Ng(e.contextNodeId))return u("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return c("Unable to restore navigation");let o=be(r.id);return U.navigate({contextNode:r,selectedIndex:Ag(e.selectedIndex,o.length)}),u("Restored navigation to root",null)};import{monotonicFactory as US,ulid as Cn}from"ulid";var $s=US();function jS(){let e=ve();if(a(e))return c("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return c("No workspace found in event log");let[r]=ae(n.id),[o]=r?ae(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 HS(){let e=jS();return a(e)?e:U.navigate(e.value)}function Pg({userId:e,userName:t}){let n=$s(),r=$s(),o=$s(),s=$s(),i=$s(),l=yt(void 0,void 0);if(a(l))return l;let d=yt(void 0,void 0);if(a(d))return d;let m=yt(d.value,void 0);if(a(m))return m;let p=yt(void 0,void 0);if(a(p))return p;let f=yt(p.value,void 0);if(a(f))return f;let g=yt(f.value,void 0);if(a(g))return g;let h=yt(void 0,void 0);return a(h)?h:u("Created default events",[{id:Cn(),userId:e,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:Cn(),userId:e,action:"create.contributor",payload:{id:e,name:t}},{id:Cn(),userId:e,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:d.value}},{id:Cn(),userId:e,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Cn(),userId:e,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Cn(),userId:e,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:g.value}},{id:Cn(),userId:e,action:"add.board",payload:{id:Zi,name:"Closed",parent:n,rank:m.value}},{id:Cn(),userId:e,action:"add.swimlane",payload:{id:ge,name:"Closed",parent:Zi,rank:h.value}},{id:Cn(),userId:e,action:"lock.node",payload:{id:Zi}},{id:Cn(),userId:e,action:"lock.node",payload:{id:ge}}])}var WS=()=>{let e=ve();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},GS=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(", ");ne.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(", ");ne.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}};function nn(e,t=[]){if(WS())return u("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Re.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=Os(s);return a(i)?i:(w({hasProjectDefinition:!1,mode:I.DEFAULT}),u("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return c("Initialized Epiq project has no workspace init event");let n=en(e),{fatal:r,skipped:o}=En(n);return r.length>0?c(`Materializing failed:
|
|
34
34
|
${r.map(s=>s.message).join(`
|
|
35
|
-
`)}`):(
|
|
36
|
-
`,"utf8"),u("Wrote the state branch identity",void 0)}catch(n){return c(n instanceof Error?`Failed to write the state branch identity: ${n.message}`:"Failed to write the state branch identity")}},
|
|
37
|
-
`);var
|
|
38
|
-
`).filter(t=>t.trim().length>0),
|
|
39
|
-
`);
|
|
35
|
+
`)}`):(Sn(o),HS(),w({hasProjectDefinition:!0}),GS(t),u("State booted successfully",null))}import{WebSocket as VS}from"ws";var Ra=new Set,Lg=e=>{Ra.add(e),e.on("close",()=>{Ra.delete(e)}),e.on("error",()=>{Ra.delete(e)})},jr=e=>{let t=JSON.stringify(e);for(let n of Ra)n.readyState===VS.OPEN&&n.send(t)};var Ca=e=>{Ut()&&(w({syncStatus:e}),jr({type:"sync-status",payload:e}))},wo=(e="Syncing...")=>{Ca({status:"syncing",msg:e})},Hr=(e="Synced")=>{Ca({status:"synced",msg:e})},md=e=>{Ca({status:"failed",msg:e})},Na=e=>{Ca({status:"offline",msg:e})},We=e=>(md(e),c(e));var rn=(e,t)=>(logger.error(`[boot:${e}] ${t}`),c(`[boot:${e}] ${t}`)),Mo=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)}},pe=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t);import Jg from"node:fs";import Gn from"node:fs";import Vn from"node:path";import Aa from"node:fs";import kg from"node:path";var ct=".epiq/project.json",Dg=e=>kg.join(e,ct),zS=e=>{if(!Aa.existsSync(Dg(e)))return u("State branch carries no identity yet",null);let t=Tt(e);return a(t)?c(`On the state branch: ${t.message}`):u("Read the state branch identity",t.value)},pd=(e,t)=>{try{let n=Dg(e);return Aa.mkdirSync(kg.dirname(n),{recursive:!0}),Aa.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
36
|
+
`,"utf8"),u("Wrote the state branch identity",void 0)}catch(n){return c(n instanceof Error?`Failed to write the state branch identity: ${n.message}`:"Failed to write the state branch identity")}},KS=({checkout:e,branch:t,stateBranch:n})=>[`This checkout's ${ct} names project ${e.projectId}`,`(created ${e.createdAt}), but the state branch ${n}`,`belongs to project ${t.projectId} (created ${t.createdAt}).`,"","The branch holds the board, so its id is the one that counts. Point the","checkout at it and commit the change:","",` git show ${n}:${ct} > ${ct}`,"","A second id is minted when init runs in a checkout that has no","project file while the state branch already exists; nothing on the","board is lost by it, but every checkout has to agree on one."].join(`
|
|
37
|
+
`);var Bg=({repoRoot:e,stateBranchRoot:t,stateBranch:n})=>{if(!Aa.existsSync(po(e)))return u("No project file to compare","no-checkout-file");let r=Tt(e);if(a(r))return c(r.message);let o=zS(t);if(a(o))return c(o.message);if(o.value===null){let s=pd(t,r.value);return a(s)?c(s.message):u("Stamped the state branch with this project","stamped")}return o.value.projectId!==r.value.projectId?c(KS({checkout:r.value,branch:o.value,stateBranch:n})):u("The checkout and the state branch agree","matched")};import Nn from"node:fs";import Us from"node:path";var Po=e=>e.split(`
|
|
38
|
+
`).filter(t=>t.trim().length>0),Og=e=>{let t=Us.join(e,ft,Fn);try{if(!Nn.existsSync(t))return u("No events directory",[]);let n=Nn.readdirSync(t).filter(r=>r.endsWith(".jsonl")).filter(r=>Po(Nn.readFileSync(Us.join(t,r),"utf8")).length>0);return u("Looked for stranded event logs",n)}catch(n){return c(`Unable to check ${t} for event logs before deleting it: ${n instanceof Error?n.message:String(n)}`)}},Fg=e=>Us.join(e,ft,Fn),_g=e=>{let t=Fg(e),n=new Map;try{if(!Nn.existsSync(t))return n;for(let r of Nn.readdirSync(t))if(r.endsWith(".jsonl")&&!$r(r))try{n.set(r,Po(Nn.readFileSync(Us.join(t,r),"utf8")))}catch(o){if(!Ps(o))throw o}}catch{return n}return n},qS=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},$g=(e,t)=>{if(t.size===0)return[];let n=Fg(e),r=[];for(let[o,s]of t){if(s.length===0)continue;let i=Us.join(n,o);try{let l=Nn.existsSync(i)?Nn.readFileSync(i,"utf8"):null,d=new Set(l===null?[]:Po(l)),m=s.filter(f=>!d.has(f)).filter(qS);if(m.length===0)continue;Nn.mkdirSync(n,{recursive:!0});let p=l!==null&&l.length>0&&!l.endsWith(`
|
|
39
|
+
`);Nn.appendFileSync(i,`${p?`
|
|
40
40
|
`:""}${m.join(`
|
|
41
41
|
`)}
|
|
42
|
-
`,"utf8"),r.push(`${o} (${m.length})`)}catch{continue}}return r},
|
|
43
|
-
`),
|
|
44
|
-
`));
|
|
42
|
+
`,"utf8"),r.push(`${o} (${m.length})`)}catch{continue}}return r},YS=(e,t)=>{let n=new Set(Po(t));return Po(e).filter(r=>!n.has(r))},XS=(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(`
|
|
43
|
+
`),Ug=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let r=await Le({args:["show",`HEAD:${t}`],cwd:e});if(r.exitCode!==0)return u("No committed log to compare against",void 0);let o=YS(r.stdout,n);return o.length>0?c(XS(t,o,Po(r.stdout).length)):u("Event log only grew",void 0)};var JS="[epiq:init-repo]",Hg=async e=>{let t=await Le({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 c(["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(`
|
|
44
|
+
`));ne.info("Creating initial commit");let r=await j({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(a(r))return c(r.message);let o=await j({args:["commit-tree",r.value.stdout.trim(),"-m",JS],cwd:e});if(a(o))return c(o.message);let s=await j({args:["update-ref","HEAD",o.value.stdout.trim()],cwd:e});return a(s)?c(s.message):u("Created initial commit",!0)},jg=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",QS=async e=>{let t=await ji(e);if(a(t))return c(t.message);let n=await Pm(e);return a(n)?c(n.message):u("Built sync commit message",`[sync|branch:${jg(t.value)}:sha:${jg(n.value)}]`)},fd=async({repoRoot:e,stateBranchName:t})=>{ne.info(`Creating ${t}`);let n=await j({args:["commit-tree",Hm,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return c(`Failed to create state branch commit
|
|
45
45
|
${n.message}`);let r=n.value.stdout.trim(),o=await j({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return a(o)?c(`Failed to create ${t}
|
|
46
|
-
${o.message}`):u("Created state branch",!0)},
|
|
47
|
-
`+n.message);if(n.value)return u("Local state branch already exists",!1);let r=await
|
|
48
|
-
`+r.message);let o=r.value,s=o?await
|
|
49
|
-
`+s.message);let i=s.value;if(o&&i){let l=await
|
|
46
|
+
${o.message}`):u("Created state branch",!0)},js=async({repoRoot:e,stateBranchName:t})=>{let n=await Ui({repoRoot:e,branch:t});if(a(n))return c(`Ensure local state branch failed
|
|
47
|
+
`+n.message);if(n.value)return u("Local state branch already exists",!1);let r=await On({repoRoot:e});if(a(r))return c(`Ensure local state branch failed
|
|
48
|
+
`+r.message);let o=r.value,s=o?await as({repoRoot:e,branch:t}):u("No remote, no remote state branch",!1);if(a(s))return c(`Ensure local state branch failed
|
|
49
|
+
`+s.message);let i=s.value;if(o&&i){let l=await Ce.fetch({cwd:e,remote:wt,branch:t});if(a(l))return c(`Failed to fetch ${t} from remote
|
|
50
50
|
${l.message}`)}if(i){let l=await j({args:["branch","--track",t,`${wt}/${t}`],cwd:e});return a(l)?c(`Failed to create local ${t} from remote
|
|
51
|
-
${l.message}`):u("Created local state branch from remote",!0)}return
|
|
52
|
-
`),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)},
|
|
53
|
-
`+r.message);if(
|
|
54
|
-
`));
|
|
55
|
-
${o.message}`):u("Created state branch worktree",!0)},
|
|
56
|
-
`));if(s&&s!==o){let d=await
|
|
57
|
-
`));
|
|
58
|
-
${m.message}`)}if(s&&!
|
|
59
|
-
${d.message}`)}let i=await
|
|
60
|
-
${d.message}`)}return
|
|
61
|
-
${o.message}`):u("Checked out state branch",!0)},
|
|
62
|
-
${l.message}`);let d=await
|
|
63
|
-
${d.message}`):u("Configured state branch upstream",!0)},
|
|
64
|
-
${s.message}`):u("Staged state branch event file",n)},
|
|
65
|
-
${r.message}`):u("Staged state branch media files",t)},
|
|
66
|
-
${n.message}`):u("Staged event log config",t)}
|
|
67
|
-
`+r.message):
|
|
68
|
-
${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)},Ug=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Ue(e);if(a(o))return o;let s=o.value,i=[ds(),await Us({repoRoot:e,stateBranchName:s}),await dr({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await ZS({stateBranchRoot:t,stateBranchName:s}),await Wm(t),n?await eR({stateBranchRoot:t,repoRoot:e}):u("Skipped state branch upstream bootstrap",!1)];for(let l of i){if(a(l))return c(l.message);r=r||!!l.value}return u(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import Po from"node:fs";import md from"node:os";import tR from"node:path";var pd="epiq-sync.lock",jg=600*1e3,nR=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}},rR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},oR=e=>e?e.hostname!==md.hostname()||rR(e.pid)?Date.now()-e.startedAt>jg?"stale":null:"dead":"stale",Wg=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,ud=e=>{try{return nR(Po.readFileSync(e,"utf8"))}catch{return null}},Hg=(e,t)=>{let n={pid:process.pid,hostname:md.hostname(),startedAt:Date.now(),operation:t},r=`${e}.${process.pid}.pending.lock`;try{return Po.writeFileSync(r,JSON.stringify(n)),Po.linkSync(r,e),!0}catch{return!1}finally{try{Po.rmSync(r,{force:!0})}catch{}}},sR=async({worktreeRoot:e,operation:t})=>{let n=await _i(e);if(a(n))return c(n.message);let r=tR.join(n.value,pd),o=()=>{try{let d=ud(r);d&&d.pid===process.pid&&Po.rmSync(r)}catch{}};if(Hg(r,t))return u("Acquired sync lock",{acquired:!0,claim:"clean",release:o});let s=ud(r),i=oR(s);if(i===null)return u("Sync lock is held",{acquired:!1,heldBy:s});se.info(`Breaking an abandoned sync lock: ${s?Wg(s):"unreadable lock file"}`);try{Po.rmSync(r,{force:!0})}catch{}if(Hg(r,t))return u("Acquired sync lock after breaking a stale one",{acquired:!0,claim:i,release:o});let l=ud(r);return u("Sync lock taken by another process",{acquired:!1,heldBy:l??{pid:-1,hostname:md.hostname(),startedAt:Date.now(),operation:"unknown"}})},Hs=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await sR({worktreeRoot:e,operation:t});if(a(r))return c(r.message);if(!r.value.acquired)return se.info(`Skipping ${t}: the state worktree is held by ${Wg(r.value.heldBy)}`),u("State worktree is held by another process",null);let{claim:o,release:s}=r.value;try{return u("Ran under the sync lock",await n(o))}finally{s()}};var iR=async({claim:e,cwd:t,ensureUpstream:n})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:t,ensureUpstream:n});let r=ge("getRepoRootDir",await qt(t));if(a(r))return c(r.message);let o=r.value;logger.debug("[sync] repo root",o);let s=ge("getStateBranchRoot",he({repoRoot:o}));if(a(s))return c(s.message);let i=s.value;if(logger.debug("[sync] state branch root",i),e!=="stale"&&Vg.existsSync(i)){let p=await Mm(i,{preserve:[pd]});if(a(p))return c(p.message);p.value.length>0&&logger.info("[sync] cleared git lock files left by a dead process",{removed:p.value,stateBranchRoot:i});let f=ge("abortRebaseIfPresent(stateBranchRoot)",await cc(i));if(a(f))return c(f.message)}logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:i,ensureUpstream:n});let l=ge("bootstrapStateBranchStorage",await Ug({repoRoot:o,stateBranchRoot:i,ensureUpstream:n}));if(a(l))return c(l.message);logger.debug("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:i}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:i});let d=ge("getInProgressGitOperation(stateBranchRoot)",await ac(i));if(a(d))return c(d.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:d.value}),d.value!==null)return logger.info("[sync] state branch git operation in progress",{claim:e}),c(`Cannot sync while there is a ${d.value} in the state branch at ${i}`);logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:i});let m=ge("ensureStateBranchLayout",Hm(o,i));return a(m)?c(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:i,bootstrapped:l.value}),u("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:i,bootstrapped:l.value}))},aR=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=[];for(let m of Kf(Et(t),n)){let p=ge("stageStateBranchOwnEventFile",await Aa({stateBranchRoot:t,eventFileName:m}));if(a(p))return c(p.message);r.push(p.value)}let o=ge("stageStateBranchMediaFiles",await Fg({stateBranchRoot:t}));if(a(o))return c(o.message);let s=ge("stageStateBranchEventConfig",await _g({stateBranchRoot:t}));if(a(s))return c(s.message);let i=[...r,o.value,...s.value].filter(m=>m!==null);if(i.length===0)return u("Nothing to stage",{createdCommit:!1});let l=ge("hasStagedChanges(after stage)",await km(t,i));if(a(l))return c(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 d=ge("createStateBranchSyncCommit",await $g({repoRoot:e,stateBranchRoot:t,pathspec:i}));return a(d)?c(d.message):(logger.debug("[sync] created sync commit",d.value),u("Committed own event file",{createdCommit:!0,commitSha:d.value}))},fd=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return Ca(n),u(n,{...e,pulled:!1,pushed:!1,offline:!0})},Gg=async({cwd:e=process.cwd(),ownEventFileName:t},n)=>{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}),c("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}),c("Own event file must end with .jsonl");To();let r=ge("ensureSyncReady",await iR({claim:n,cwd:e,ensureUpstream:!0}));if(a(r))return Ve(r.message);let{repoRoot:o,stateBranchRoot:s,bootstrapped:i}=r.value,l=ge("isDetachedHead(stateBranchRoot)",await Dm(s));if(a(l))return Ve(l.message);if(logger.debug("[sync] detached state branch check result",{detached:l.value}),l.value)return Ve("Cannot run :sync while the state branch is in detached HEAD state");let d=!1,m,p=!1,f=!1,g=ge("getStateBranch",Ue(o));if(a(g))return Ve(g.message);let y=g.value;logger.debug("[sync] resolved state branch",{stateBranch:y,stateBranchRoot:s});let x=ge("flushPendingLogs",ua(s,t));a(x)&&logger.error(`[sync] ${x.message}`);let b=ge("commitOwnEventFileToStateBranch",await aR({repoRoot:o,stateBranchRoot:s,ownEventFileName:t}));if(a(b))return Ve(b.message);d=b.value.createdCommit,m=b.value.commitSha;let R=ge("hasRemote",await Bn({repoRoot:s}));if(a(R))return Ve(R.message);if(!R.value)return fd({repoRoot:o,stateBranchRoot:s,createdCommit:d,commitSha:m,bootstrapped:i},"no remote");let S=ge("pullBranchRebaseIfPresent",await ls({cwd:s,branch:y}));if(a(S))return as(S.message)?fd({repoRoot:o,stateBranchRoot:s,createdCommit:d,commitSha:m,bootstrapped:i}):Ve(S.message);p=S.value;let T=ge("isAheadOfUpstream",await Pm(s));if(a(T))return Ve(T.message);if(d||i||T.value){logger.info("[sync] pushing state branch",{createdCommit:d,bootstrapped:i,stateBranchRoot:s});let A=ge("pushStateBranch",await js({stateBranchRoot:s,repoRoot:o}));if(a(A)&&Tm(A.message)){let P=ge("pullBranchRebaseIfPresent(retry)",await ls({cwd:s,branch:y}));if(a(P))return Ve(P.message);p=p||P.value,A=ge("pushStateBranch(retry)",await js({stateBranchRoot:s,repoRoot:o}))}if(a(A))return as(A.message)?fd({repoRoot:o,stateBranchRoot:s,createdCommit:d,commitSha:m,bootstrapped:i}):Ve(A.message);f=A.value}if(d){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:s});let A=ge("git rev-parse HEAD",await j({args:["rev-parse","HEAD"],cwd:s}));if(a(A))return Ve(A.message);m=A.value.stdout.trim(),logger.debug("[sync] final sync commit sha",m)}return jr(f?"Synced and pushed":p||d?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),u("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:s,createdCommit:d,commitSha:m,pulled:p,pushed:f,bootstrapped:i,offline:!1})},Ta=async(e,t)=>{let n=Lg(e);try{return await t()}finally{let r=kg(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},wa=async e=>{let t=e.cwd??process.cwd(),n=await qt(t);if(a(n))return Ve(n.message);let r=he({repoRoot:n.value});if(a(r))return Ve(r.message);let o=r.value;if(!Vg.existsSync(o))return Gg(e,"clean");let s=await Hs({worktreeRoot:o,operation:"sync",fn:i=>Ta(o,()=>Gg(e,i))});return a(s)?Ve(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 Nn=null,Ma=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Nn,currentStatus:v().syncStatus?.status,currentMessage:v().syncStatus?.msg}),Nn)return logger.debug("[sync] syncAndReloadState joining existing promise"),Nn;logger.debug("[sync] syncAndReloadState creating promise"),Nn=lR();try{let e=await Nn;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:v().syncStatus?.status,statusMessageAfterResolve:v().syncStatus?.msg}),a(e)&&v().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),w({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}),Nn||c(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:v().syncStatus?.status,statusMessageBeforeClear:v().syncStatus?.msg}),Nn=null}},lR=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:v().mode,syncStatus:v().syncStatus});let e=zg();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:v().mode,message:e.message,syncStatus:v().syncStatus}),e;if(Nn)return Nn;logger.debug("[sync] syncAndReloadState:start");let t=ge("resolveActorId",pe());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),c("Unable to resolve event log path");w({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:v().syncStatus});let n=ir(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=ge("syncEpiqWithRemote",await wa({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(r),message:(a(r),r.message)}),a(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),w({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:v().syncStatus}),Ve(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value,i=gd(o);return a(i)?i:(w({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:v().syncStatus}),u("Synced",!0))},gd=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=ge("loadMergedEvents",Zt(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(t),message:(a(t),t.message),count:a(t)?void 0:t.value.events.length}),a(t))return w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:v().syncStatus}),c(`Unable to load events. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=zg();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:v().mode,message:n.message,syncStatus:v().syncStatus}),n;let r=Eg(),o=v().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:r,selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id,selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual}),!v().selectedNode?.isVirtual&&!v().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:t.value.events.length});let i=ge("bootStateFromEventLog",en(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(i),message:(a(i),i.message)}),a(i))return w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:v().syncStatus}),c(`Unable to boot synced state. ${i.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),w({filters:o}),logger.debug("[sync] restoreNavigationAnchor:start");let s=ge("restoreNavigationAnchor",Rg(r));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(s),message:a(s)?s.message:"Navigation restored",selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id}),a(s)?(w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:v().syncStatus}),s):u("Reloaded state from event log",null)},zg=()=>v().mode===I.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:v().mode,syncStatus:v().syncStatus}),w({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),c("Will not re-materialize if not in default mode, to not lose edit data"));var Kg=0,hd,yd=!1,Ws=!1,vd=()=>{if(yd)return!0;let e=xe();return a(e)?!1:e.value.syncStatus.status==="syncing"},cR=()=>{let e=uo(V().autoSyncIntervalMs),t=Date.now()-Kg;return Math.max(0,e-t)},qg=()=>{hd||(hd=setTimeout(async()=>{if(hd=void 0,!!_t()){if(vd()){Ws=!0;return}Ws=!1,await dR()}},cR()))},dR=async()=>{if(v().readOnly||v().timeMode==="peek"||v().timeMode==="replay")return c("Cannot auto-sync while peeking");if(!_t())return c("Cannot auto-sync before state is initialized");if(vd())return Ws=!0,c("Sync already in progress");yd=!0,Kg=Date.now(),w({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Ma()}finally{yd=!1,Ws&&qg()}},Pa=()=>{_t()&&(Ws=!0,!vd()&&qg())};var La=e=>{let{context:t}=v().contextNode;if(!t)return G.None;switch(e){case C.EXIT:return G.Exit;case C.EXPORT:return G.Export;case C.INIT:return G.Init;case C.OPEN:return G.OpenProject;case C.DELETE:return G.Delete;case C.EDIT:return G.Edit;case C.COMMENT:return G.Comment;case C.HELP:return G.ViewHelp;case C.RE_OPEN_ISSUE:return G.ReopenIssue;case C.CLOSE_ISSUE:return G.CloseIssue;case C.TAG:return G.TagTicket;case C.UNTAG:return G.UntagTicket;case C.ASSIGN:return G.AssignUserToTicket;case C.UNASSIGN:return G.UnassignUserFromTicket;case C.NEW:return G.NewItem;case C.FILTER:return G.Filter;case C.MOVE:return G.Move;case C.PEEK:return G.Peek;case C.REPLAY:return G.Replay;case C.CONFIG:return G.Config;case C.YANK:return G.Yank;case C.SYNC:return G.Sync;default:return G.None}},G={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 ay from"node:fs";import tN from"node:path";import nN from"react";import{Box as ZC}from"ink";import Ya from"react";import TR from"chalk";import{Box as Id,Text as wR}from"ink";import An from"react";import{Text as Yg}from"ink";import Xg,{useEffect as Jg,useState as uR}from"react";var Qg={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "],identity:["\u276F "]},St=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=oe(),r=Qg[n]??Qg.default,[o,s]=uR(0);if(Jg(()=>{s(0)},[r]),Jg(()=>{if(!e)return;let l=setInterval(()=>{s(d=>(d+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return Xg.createElement(Yg,null,t);let i=r[o]??r[0]??t;return Xg.createElement(Yg,{color:h.accent,dimColor:o===1},i)};import{Box as bd,Text as mR}from"ink";import ka from"react";var pR=(e,t,n,r)=>{let o=d=>Math.max(1,e[d]??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}},mt=({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)),d=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?pR(o,e.length,d,i):s?{start:Math.min(p,Math.max(0,d-m+1)),end:Math.min(p,Math.max(0,d-m+1))+m}:{start:Math.min(p,Math.floor(d/m)*m),end:Math.min(p,Math.floor(d/m)*m)+m},y=Math.max(1,g-f),x=e.slice(f,g),b=e.length>y,R=i,S=b?Math.max(1,Math.floor(y/e.length*R)):R,T=Math.max(0,R-S),A=Math.max(1,e.length-y),P=b?Math.floor(f/A*T):0;return ka.createElement(bd,{flexDirection:"row",height:i,width:"100%"},ka.createElement(bd,{flexDirection:"column",flexGrow:1,height:i},x),ka.createElement(bd,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((M,O)=>ka.createElement(mR,{key:O,color:b&&O>=P&&O<P+S?h.accent:h.secondary},b?"\u2502":" "))))};import{Box as Do,Text as Bo}from"ink";import Rt from"react";var Zg,xd,fR=()=>{let{eventLog:e=[]}=v();if(xd&&Zg===e)return xd;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Zg=e,xd=t,t},Da=e=>fR().has(e);import{Text as gR}from"ink";import hR from"react";var ur=({id:e,isSelected:t,maxWidth:n})=>{let r=N.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:Fn(o,n);return hR.createElement(gR,{underline:t,color:qe(o)},"@"+s,Da(e)?"":"\u2197")};import{Text as yR}from"ink";import vR from"react";var Lo=({id:e,isSelected:t,maxWidth:n})=>{let r=N.getTag(e);if(!r)return;let o=n===void 0?r.name:Fn(r.name,n);return vR.createElement(yR,{underline:t,backgroundColor:qe(r.name),color:h.secondary}," "+o+" ")};import{useEffect as bR,useState as xR}from"react";var IR=80,eh=1400,Ba=new Set,Gs=null,ER=e=>(Ba.add(e),Gs||(Gs=setInterval(()=>{for(let t of Ba)t()},IR)),()=>{Ba.delete(e),Ba.size===0&&Gs&&(clearInterval(Gs),Gs=null)}),SR=()=>{let e=Date.now()%eh/eh;return e<.5?e*2:(1-e)*2},ko=e=>{let[,t]=xR(0);return bR(()=>{if(e)return ER(()=>t(n=>n+1))},[e]),Gi(SR())};var RR=(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)]},th=3,CR=2,NR=(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}},nh=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=ko(r),s=e-4,i=s-7-1,[l,d]=RR(Re(t.title),i,s),m=d?null:Fn(Re(t.props.description),s)||null,p=hn(t),f=yn(t).map(S=>({...S,name:S.name})),g=Math.max(1,s-th),y=N.getCommentsByIssue(t.id),x=y.length?String(y.length).length+2+1:0,{shown:b,hidden:R}=NR([...p.map(S=>({id:S.id,isTag:!0,width:Math.min(S.name.length,g)+th})),...f.map(S=>({id:S.id,isTag:!1,width:Math.min(S.name.length,g)+CR+(Da(S.id)?0:1)}))],s-x);return Rt.createElement(Do,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?h.accent:h.secondary,justifyContent:"space-between"},Rt.createElement(Do,{paddingLeft:1,paddingRight:1,flexDirection:"column"},Rt.createElement(Do,{justifyContent:"space-between"},Rt.createElement(Bo,{color:h.primary},l),Rt.createElement(Bo,{color:h.secondary2,dimColor:!0},H(t.id))),d&&Rt.createElement(Bo,{color:h.primary},d),m&&Rt.createElement(Bo,{color:h.secondary2,dimColor:!0},m)),Rt.createElement(Do,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},Rt.createElement(Do,{flexDirection:"row"},b.map(S=>Rt.createElement(Do,{paddingRight:1,key:S.id},S.isTag?Rt.createElement(Lo,{id:S.id,maxWidth:g}):Rt.createElement(ur,{id:S.id,maxWidth:g}))),R>0&&Rt.createElement(Bo,{color:h.secondary2,dimColor:!0},"+",R)),y.length>0&&Rt.createElement(Bo,{color:h.accent},"[",y.length,"]")))};import{Box as Hr,Text as Vs}from"ink";import Lt from"react";var AR=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,rh=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let l=ko(s),d=(r.props.tags??[]).map(M=>N.getTag(M)).filter(M=>!!M),m=(r.props.assignees??[]).map(M=>N.getContributor(M)).map(M=>M&&{...M,name:M.name}).filter(M=>!!M),p=1,f=d.length*(1+p),g=m.length*(2+p),y=d.map(M=>Lt.createElement(Hr,{key:M.id,paddingRight:p},Lt.createElement(Vs,{color:qe(M.name)},"\u25A0"))),x=m.map(M=>Lt.createElement(Hr,{key:M.id,paddingRight:p},Lt.createElement(Vs,{color:Ec(M.name)},"@"+M.name.at(0)))),b=s?l:o?h.accent:i===I.MOVE?h.secondary:h.primary,R=N.getCommentsByIssue(r.id),S=R.length?String(R.length).length+2+p:0,T=R.length?Lt.createElement(Hr,{paddingRight:p},Lt.createElement(Vs,{color:h.accent},"[",R.length,"]")):null,A=f+g+S,P=Math.max(1,n-t-A-(A>0?1:0));return Lt.createElement(Hr,{justifyContent:"space-between"},Lt.createElement(Hr,null,Lt.createElement(Hr,{width:t},o?Lt.createElement(St,{isSelected:!0}):Lt.createElement(Vs,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),Lt.createElement(Vs,{wrap:"truncate",color:b},AR(r.title,P))),Lt.createElement(Hr,null,y,x,T))};var MR=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:l})=>{let{renderedChildrenIndex:d,replay:m}=oe(),p=d[e.id]??[],f=m?new Set(m.flashNodeIds):null,g=f?.has(e.id)??!1,y=ko(g),x=`${e.title} ${TR.hex(h.secondary2).dim("("+p.length+")")}`,b=3,R=o?1:5,S=s&&i===-1,T=n-3-(o?1:0)-(S?2:0),A=Math.max(2,String(p.length).length+1),P=r-b-1,M=An.createElement(Id,{borderStyle:"round",borderColor:h.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},An.createElement(St,{isSelected:t}),An.createElement(wR,{bold:!0,color:g?y:t?h.accent:h.primary},x," ",e.readonly?"\u{1F512}":"")),O=(W,X)=>{let Ee=s&&i===X;if(!_(W))return null;let F=f?.has(W.id)??!1;return o?An.createElement(rh,{key:W.id,index:X,labelWidth:A,width:T,ticket:W,isSelected:Ee,isFlashing:F,mode:l}):An.createElement(nh,{key:W.id,width:T,ticket:W,isSelected:Ee,isFlashing:F})};return An.createElement(Id,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?h.accent:h.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},M,An.createElement(Id,null,p.length>0&&An.createElement(mt,{selectedIndex:i,height:P,itemHeight:R},p.map(O)),S&&An.createElement(St,{isSelected:!0})))},oh=An.memo(MR);import{Box as Wo,Text as KC}from"ink";import Ct,{useMemo as Go}from"react";var sh=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},ih=(e,t,n)=>Ne.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});var ah=e=>e.action==="add.issue.comment";import{Box as Oo,Text as Vn}from"ink";import pt,{useEffect as PR,useMemo as LR,useRef as kR}from"react";import{decodeTime as lh}from"ulid";var pr=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"},Oa=e=>String(e).padStart(2,"0"),Fa=e=>`${e.getFullYear()}-${Oa(e.getMonth()+1)}-${Oa(e.getDate())} ${Oa(e.getHours())}:${Oa(e.getMinutes())}`;var DR=e=>Pe(e,"attachments"),BR=e=>N.getAttachmentsByIssue(e.id).sort((t,n)=>lh(t.id)-lh(n.id)),ch=e=>{for(let t of e)N.deleteNode(t.id)},OR=(e,t,n)=>Ne.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),FR=(e,t)=>{let n=N.getNode(DR(e.id));if(!n||!lt(n))return[];let r=t.map((o,s)=>OR(o,s,n.id)).map(o=>N.createNode(o)).filter(be).map(({value:o})=>o).filter(lt);return t.length>0&&v().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),r},_R=e=>`${Math.max(1,Math.round(e/1024))} KB`;function dh({ticket:e,width:t,height:n}){let r=LR(()=>BR(e),[e]),o=kR([]);PR(()=>(ch(o.current),o.current=FR(e,r),()=>{ch(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=oe(),l=Math.max(1,n-4),d=Math.max(12,t-32);return r.length===0?pt.createElement(Oo,{flexDirection:"column",width:t,height:n,padding:1},pt.createElement(Vn,{color:h.primary},"No attachments yet."),pt.createElement(Oo,{paddingTop:1},pt.createElement(Vn,{color:h.primary},"Attach images from the browser GUI"),pt.createElement(Vn,{color:h.accent}," epiq gui "),pt.createElement(Vn,{color:h.primary},"by dropping or pasting them."))):pt.createElement(Oo,{flexDirection:"column",width:t,height:n},pt.createElement(Oo,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:h.secondary,borderStyle:"single",paddingBottom:1},pt.createElement(Vn,{color:h.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),pt.createElement(mt,{height:l,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,g=m.name.length>d?m.name.slice(0,d-1)+"\u2026":m.name;return pt.createElement(Oo,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},pt.createElement(Vn,{color:h.accent},f?"\u276F ":" "),pt.createElement(Oo,{paddingLeft:1},pt.createElement(Vn,{color:h.secondary2},`#${p+1} `),pt.createElement(Vn,{color:f?h.accent:h.primary},g),pt.createElement(Vn,{color:h.secondary2}," "+_R(m.bytes)+" "+pr(Be(m.id)))))})))}import{Box as fr,Text as gr}from"ink";import Je,{useEffect as KR,useMemo as Rh,useRef as qR}from"react";import{decodeTime as Ch}from"ulid";var mh=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,Ed=e=>e.replace(mh,""),$R=e=>`<!-- epiq-diff-comment:${JSON.stringify(e).replaceAll(">","\\u003e")} -->`,uh=e=>e==="additions"||e==="deletions",zs=e=>{let t=mh.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"||!uh(r.side)||!uh(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r};var ph=/```\n([\s\S]*?)\n?```\s*$/,fh=e=>ph.exec(e)?.[1]??null,UR=/`[^`\n]+`[^\n]*\n?$/,gh=e=>Ed(e).replace(ph,"").replace(UR,"").trim(),hh=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})`},Sd=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${hh(e)}`;var jR=e=>{let t=e.split(`
|
|
51
|
+
${l.message}`):u("Created local state branch from remote",!0)}return fd({repoRoot:e,stateBranchName:t})},ZS=async({repoRoot:e,branch:t})=>{let n=await j({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return c(n.message);let r=n.value.stdout.split(`
|
|
52
|
+
`),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)},eR=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=ds(Vn.dirname(t));if(a(r))return c(`Failed to create state branch worktree
|
|
53
|
+
`+r.message);if(Gn.existsSync(t)&&!Gn.existsSync(Vn.join(t,".git"))){let s=Og(t);if(a(s))return c(s.message);if(s.value.length>0)return c([`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(`
|
|
54
|
+
`));ne.info("Removing broken state branch worktree path"),zm(t)}ne.info("Creating state branch worktree");let o=await Ce.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(o)?c(`Failed to create state branch worktree
|
|
55
|
+
${o.message}`):u("Created state branch worktree",!0)},ur=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await nR({repoRoot:e,stateBranchRoot:t,stateBranchName:n});if(a(r))return r;let o=Bg({repoRoot:e,stateBranchRoot:t,stateBranch:n});return a(o)?c(o.message):(o.value==="stamped"&&ne.info("Stamped the state branch with this project\u2019s identity"),r)},tR=(e,t)=>{let n=fo(Lr());return Vn.dirname(e)===n&&Vn.dirname(t)===n},nR=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await ZS({repoRoot:e,branch:n});if(a(r))return c(r.message);let o=fo(t),s=r.value?fo(r.value):null;if(s&&s===o&&Gn.existsSync(s))return u("State branch already checked out in expected worktree",!1);if(s&&s!==o&&tR(s,o))return c([`The state branch ${n} is checked out under project ${Vn.basename(s)}, but this checkout names project ${Vn.basename(o)}.`,"","Two ids for one branch means a checkout minted a second identity for","a board that already existed. Nothing on the board is lost by it, but",`every checkout has to agree on one: compare ${ct} here`,`with \`git show ${n}:${ct}\`, and keep the branch's.`].join(`
|
|
56
|
+
`));if(s&&s!==o){let d=await Fm(s);if(a(d))return c(d.message);if(d.value||Uf(s))return c([`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(`
|
|
57
|
+
`));ne.info("Moving state branch worktree to expected location");let m=await Ce.worktreeRemove({cwd:e,worktreeRoot:s});if(a(m))return c(`Failed to remove existing state branch worktree
|
|
58
|
+
${m.message}`)}if(s&&!Gn.existsSync(s)){ne.info("Pruning stale state branch worktree");let d=await Ce.worktreePrune({cwd:e});if(a(d))return c(`Failed to prune stale worktrees
|
|
59
|
+
${d.message}`)}let i=await Mm({repoRoot:e,worktreeRoot:t});if(a(i))return c(i.message);let l=Gn.existsSync(t);if(i.value&&l)return u("State branch worktree already exists",!1);if(i.value&&!l){ne.info("Pruning missing registered state branch worktree");let d=await Ce.worktreePrune({cwd:e});if(a(d))return c(`Failed to prune stale worktrees
|
|
60
|
+
${d.message}`)}return eR({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},rR=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await ji(e);if(a(n))return c(n.message);if(n.value===t)return u("State branch already checked out",!1);(await Le({cwd:e,args:["rebase","--abort"]})).exitCode===0&&ne.info("Aborted stale state branch rebase");let o=await Ce.checkout({cwd:e,branch:t});return a(o)?c(`Failed to checkout ${t}
|
|
61
|
+
${o.message}`):u("Checked out state branch",!0)},oR=async({repoRoot:e,stateBranchRoot:t})=>{let n=await dc(t);if(a(n))return c(n.message);if(n.value)return u("State branch upstream already configured",!1);let r=await On({repoRoot:t});if(a(r))return c(r.message);if(!r.value)return u("No remote available for state branch upstream",!1);let o=ke(e);if(a(o))return o;let s=o.value,i=await as({repoRoot:t,branch:s});if(a(i))return c(i.message);if(!i.value)return u("Remote state branch missing; upstream will be configured on first push",!1);ne.info(`Configuring ${s} upstream`);let l=await Ce.fetch({cwd:t,remote:wt,branch:s});if(a(l))return c(`Failed to fetch ${s}
|
|
62
|
+
${l.message}`);let d=await Ce.setUpstream({cwd:t,branch:s,upstream:`${wt}/${s}`});return a(d)?c(`Failed to set state branch upstream
|
|
63
|
+
${d.message}`):u("Configured state branch upstream",!0)},Ta=async({stateBranchRoot:e,eventFileName:t})=>{let n=Wm(t),r=Vn.join(e,n);if(!Gn.existsSync(r))return u("No event file to stage",null);let o=await Ug({stateBranchRoot:e,relativePath:n,workingContent:Gn.readFileSync(r,"utf8")});if(a(o))return c(o.message);let s=await Ce.stage({cwd:e,pathspec:[n]});return a(s)?c(`Failed to stage state branch event file
|
|
64
|
+
${s.message}`):u("Staged state branch event file",n)},Wg=async({stateBranchRoot:e})=>{let t=Gm(),n=Vn.join(e,t);if(!Gn.existsSync(n))return u("No media directory to stage",null);let r=await Ce.stage({cwd:e,pathspec:[t],ignoreRemoval:!0});return a(r)?c(`Failed to stage state branch media files
|
|
65
|
+
${r.message}`):u("Staged state branch media files",t)},Gg=async({stateBranchRoot:e})=>{let t=[mc(),pc(),ct].filter(r=>Gn.existsSync(Vn.join(e,r)));if(t.length===0)return u("No event log config to stage",[]);let n=await Ce.stage({cwd:e,pathspec:t});return a(n)?c(`Failed to stage event log config
|
|
66
|
+
${n.message}`):u("Staged event log config",t)},Vg=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let r=await QS(e);return a(r)?c(`Create state branch sync commit failed
|
|
67
|
+
`+r.message):go({cwd:t,message:r.value,pathspec:n})},Hs=async({repoRoot:e,stateBranchRoot:t})=>{let n=await dc(t);if(a(n))return c(n.message);let r=ke(e);if(a(r))return r;let o=r.value,s=n.value?await Ce.push({cwd:t}):await Ce.push({cwd:t,remote:wt,branch:o,setUpstream:!0});if(a(s))return c(`Failed during state branch push
|
|
68
|
+
${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)},zg=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=ke(e);if(a(o))return o;let s=o.value,i=[us(),await js({repoRoot:e,stateBranchName:s}),await ur({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await rR({stateBranchRoot:t,stateBranchName:s}),await qm(t),n?await oR({stateBranchRoot:t,repoRoot:e}):u("Skipped state branch upstream bootstrap",!1)];for(let l of i){if(a(l))return c(l.message);r=r||!!l.value}return u(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import Lo from"node:fs";import hd from"node:os";import sR from"node:path";var yd="epiq-sync.lock",Kg=600*1e3,iR=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}},aR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},lR=e=>e?e.hostname!==hd.hostname()||aR(e.pid)?Date.now()-e.startedAt>Kg?"stale":null:"dead":"stale",Yg=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,gd=e=>{try{return iR(Lo.readFileSync(e,"utf8"))}catch{return null}},qg=(e,t)=>{let n={pid:process.pid,hostname:hd.hostname(),startedAt:Date.now(),operation:t},r=`${e}.${process.pid}.pending.lock`;try{return Lo.writeFileSync(r,JSON.stringify(n)),Lo.linkSync(r,e),!0}catch{return!1}finally{try{Lo.rmSync(r,{force:!0})}catch{}}},cR=async({worktreeRoot:e,operation:t})=>{let n=await $i(e);if(a(n))return c(n.message);let r=sR.join(n.value,yd),o=()=>{try{let d=gd(r);d&&d.pid===process.pid&&Lo.rmSync(r)}catch{}};if(qg(r,t))return u("Acquired sync lock",{acquired:!0,claim:"clean",release:o});let s=gd(r),i=lR(s);if(i===null)return u("Sync lock is held",{acquired:!1,heldBy:s});ne.info(`Breaking an abandoned sync lock: ${s?Yg(s):"unreadable lock file"}`);try{Lo.rmSync(r,{force:!0})}catch{}if(qg(r,t))return u("Acquired sync lock after breaking a stale one",{acquired:!0,claim:i,release:o});let l=gd(r);return u("Sync lock taken by another process",{acquired:!1,heldBy:l??{pid:-1,hostname:hd.hostname(),startedAt:Date.now(),operation:"unknown"}})},Ws=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await cR({worktreeRoot:e,operation:t});if(a(r))return c(r.message);if(!r.value.acquired)return ne.info(`Skipping ${t}: the state worktree is held by ${Yg(r.value.heldBy)}`),u("State worktree is held by another process",null);let{claim:o,release:s}=r.value;try{return u("Ran under the sync lock",await n(o))}finally{s()}};var dR=async({claim:e,cwd:t,ensureUpstream:n})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:t,ensureUpstream:n});let r=pe("getRepoRootDir",await Xt(t));if(a(r))return c(r.message);let o=r.value;logger.debug("[sync] repo root",o);let s=pe("getStateBranchRoot",fe({repoRoot:o}));if(a(s))return c(s.message);let i=s.value;if(logger.debug("[sync] state branch root",i),e!=="stale"&&Jg.existsSync(i)){let p=await Dm(i,{preserve:[yd]});if(a(p))return c(p.message);p.value.length>0&&logger.info("[sync] cleared git lock files left by a dead process",{removed:p.value,stateBranchRoot:i});let f=ke(o);if(a(f))return c(f.message);let g=await Bm(i,f.value);if(a(g))return c(g.message);g.value&&logger.info("[sync] cleared a ref lock left by a dead process",{branch:f.value,stateBranchRoot:i});let h=pe("abortRebaseIfPresent(stateBranchRoot)",await uc(i));if(a(h))return c(h.message)}logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:i,ensureUpstream:n});let l=pe("bootstrapStateBranchStorage",await zg({repoRoot:o,stateBranchRoot:i,ensureUpstream:n}));if(a(l))return c(l.message);logger.debug("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:i}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:i});let d=pe("getInProgressGitOperation(stateBranchRoot)",await cc(i));if(a(d))return c(d.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:d.value}),d.value!==null)return logger.info("[sync] state branch git operation in progress",{claim:e}),c(`Cannot sync while there is a ${d.value} in the state branch at ${i}`);logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:i});let m=pe("ensureStateBranchLayout",Km(o,i));return a(m)?c(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:i,bootstrapped:l.value}),u("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:i,bootstrapped:l.value}))},uR=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=[];for(let m of Zf(Et(t),n)){let p=pe("stageStateBranchOwnEventFile",await Ta({stateBranchRoot:t,eventFileName:m}));if(a(p))return c(p.message);r.push(p.value)}let o=pe("stageStateBranchMediaFiles",await Wg({stateBranchRoot:t}));if(a(o))return c(o.message);let s=pe("stageStateBranchEventConfig",await Gg({stateBranchRoot:t}));if(a(s))return c(s.message);let i=[...r,o.value,...s.value].filter(m=>m!==null);if(i.length===0)return u("Nothing to stage",{createdCommit:!1});let l=pe("hasStagedChanges(after stage)",await _m(t,i));if(a(l))return c(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 d=pe("createStateBranchSyncCommit",await Vg({repoRoot:e,stateBranchRoot:t,pathspec:i}));return a(d)?c(d.message):(logger.debug("[sync] created sync commit",d.value),u("Committed own event file",{createdCommit:!0,commitSha:d.value}))},vd=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return Na(n),u(n,{...e,pulled:!1,pushed:!1,offline:!0})},Xg=async({cwd:e=process.cwd(),ownEventFileName:t},n)=>{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}),c("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}),c("Own event file must end with .jsonl");wo();let r=pe("ensureSyncReady",await dR({claim:n,cwd:e,ensureUpstream:!0}));if(a(r))return We(r.message);let{repoRoot:o,stateBranchRoot:s,bootstrapped:i}=r.value,l=pe("isDetachedHead(stateBranchRoot)",await $m(s));if(a(l))return We(l.message);if(logger.debug("[sync] detached state branch check result",{detached:l.value}),l.value)return We("Cannot run :sync while the state branch is in detached HEAD state");let d=!1,m,p=!1,f=!1,g=pe("getStateBranch",ke(o));if(a(g))return We(g.message);let h=g.value;logger.debug("[sync] resolved state branch",{stateBranch:h,stateBranchRoot:s});let x=pe("flushPendingLogs",ma(s,t));a(x)&&logger.error(`[sync] ${x.message}`);let b=pe("commitOwnEventFileToStateBranch",await uR({repoRoot:o,stateBranchRoot:s,ownEventFileName:t}));if(a(b))return We(b.message);d=b.value.createdCommit,m=b.value.commitSha;let N=pe("hasRemote",await On({repoRoot:s}));if(a(N))return We(N.message);if(!N.value)return vd({repoRoot:o,stateBranchRoot:s,createdCommit:d,commitSha:m,bootstrapped:i},"no remote");let S=pe("pullBranchRebaseIfPresent",await cs({cwd:s,branch:h}));if(a(S))return ls(S.message)?vd({repoRoot:o,stateBranchRoot:s,createdCommit:d,commitSha:m,bootstrapped:i}):We(S.message);p=S.value;let A=pe("isAheadOfUpstream",await Om(s));if(a(A))return We(A.message);if(d||i||A.value){logger.info("[sync] pushing state branch",{createdCommit:d,bootstrapped:i,stateBranchRoot:s});let T=pe("pushStateBranch",await Hs({stateBranchRoot:s,repoRoot:o}));if(a(T)&&Lm(T.message)){let P=pe("pullBranchRebaseIfPresent(retry)",await cs({cwd:s,branch:h}));if(a(P))return We(P.message);p=p||P.value,T=pe("pushStateBranch(retry)",await Hs({stateBranchRoot:s,repoRoot:o}))}if(a(T))return ls(T.message)?vd({repoRoot:o,stateBranchRoot:s,createdCommit:d,commitSha:m,bootstrapped:i}):We(T.message);f=T.value}if(d){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:s});let T=pe("git rev-parse HEAD",await j({args:["rev-parse","HEAD"],cwd:s}));if(a(T))return We(T.message);m=T.value.stdout.trim(),logger.debug("[sync] final sync commit sha",m)}return Hr(f?"Synced and pushed":p||d?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),u("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:s,createdCommit:d,commitSha:m,pulled:p,pushed:f,bootstrapped:i,offline:!1})},wa=async(e,t)=>{let n=_g(e);try{return await t()}finally{let r=$g(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},Ma=async e=>{let t=e.cwd??process.cwd(),n=await Xt(t);if(a(n))return We(n.message);let r=fe({repoRoot:n.value});if(a(r))return We(r.message);let o=r.value;if(!Jg.existsSync(o))return Xg(e,"clean");let s=await Ws({worktreeRoot:o,operation:"sync",fn:i=>wa(o,()=>Xg(e,i))});return a(s)?We(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 An=null,Pa=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!An,currentStatus:v().syncStatus?.status,currentMessage:v().syncStatus?.msg}),An)return logger.debug("[sync] syncAndReloadState joining existing promise"),An;logger.debug("[sync] syncAndReloadState creating promise"),An=mR();try{let e=await An;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:v().syncStatus?.status,statusMessageAfterResolve:v().syncStatus?.msg}),a(e)&&v().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),w({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}),An||c(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:v().syncStatus?.status,statusMessageBeforeClear:v().syncStatus?.msg}),An=null}},mR=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:v().mode,syncStatus:v().syncStatus});let e=Qg();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:v().mode,message:e.message,syncStatus:v().syncStatus}),e;if(An)return An;logger.debug("[sync] syncAndReloadState:start");let t=pe("resolveActorId",ue());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),c("Unable to resolve event log path");w({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:v().syncStatus});let n=ar(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=pe("syncEpiqWithRemote",await Ma({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(r),message:(a(r),r.message)}),a(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),w({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:v().syncStatus}),We(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value,i=bd(o);return a(i)?i:(w({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:v().syncStatus}),u("Synced",!0))},bd=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=pe("loadMergedEvents",tn(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(t),message:(a(t),t.message),count:a(t)?void 0:t.value.events.length}),a(t))return w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:v().syncStatus}),c(`Unable to load events. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=Qg();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:v().mode,message:n.message,syncStatus:v().syncStatus}),n;let r=Tg(),o=v().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:r,selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id,selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual}),!v().selectedNode?.isVirtual&&!v().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:t.value.events.length});let i=pe("bootStateFromEventLog",nn(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(i),message:(a(i),i.message)}),a(i))return w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:v().syncStatus}),c(`Unable to boot synced state. ${i.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),w({filters:o}),logger.debug("[sync] restoreNavigationAnchor:start");let s=pe("restoreNavigationAnchor",Mg(r));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(s),message:a(s)?s.message:"Navigation restored",selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id}),a(s)?(w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:v().syncStatus}),s):u("Reloaded state from event log",null)},Qg=()=>v().mode===I.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:v().mode,syncStatus:v().syncStatus}),w({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),c("Will not re-materialize if not in default mode, to not lose edit data"));var Zg=0,xd,Id=!1,Gs=!1,Ed=()=>{if(Id)return!0;let e=ve();return a(e)?!1:e.value.syncStatus.status==="syncing"},pR=()=>{let e=mo(V().autoSyncIntervalMs),t=Date.now()-Zg;return Math.max(0,e-t)},eh=()=>{xd||(xd=setTimeout(async()=>{if(xd=void 0,!!Ut()){if(Ed()){Gs=!0;return}Gs=!1,await fR()}},pR()))},fR=async()=>{if(v().readOnly||v().timeMode==="peek"||v().timeMode==="replay")return c("Cannot auto-sync while peeking");if(!Ut())return c("Cannot auto-sync before state is initialized");if(Ed())return Gs=!0,c("Sync already in progress");Id=!0,Zg=Date.now(),w({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Pa()}finally{Id=!1,Gs&&eh()}},La=()=>{Ut()&&(Gs=!0,!Ed()&&eh())};var ka=e=>{let{context:t}=v().contextNode;if(!t)return G.None;switch(e){case R.EXIT:return G.Exit;case R.EXPORT:return G.Export;case R.INIT:return G.Init;case R.OPEN:return G.OpenProject;case R.DELETE:return G.Delete;case R.EDIT:return G.Edit;case R.COMMENT:return G.Comment;case R.HELP:return G.ViewHelp;case R.RE_OPEN_ISSUE:return G.ReopenIssue;case R.CLOSE_ISSUE:return G.CloseIssue;case R.TAG:return G.TagTicket;case R.UNTAG:return G.UntagTicket;case R.ASSIGN:return G.AssignUserToTicket;case R.UNASSIGN:return G.UnassignUserFromTicket;case R.NEW:return G.NewItem;case R.FILTER:return G.Filter;case R.MOVE:return G.Move;case R.PEEK:return G.Peek;case R.REPLAY:return G.Replay;case R.CONFIG:return G.Config;case R.YANK:return G.Yank;case R.SYNC:return G.Sync;default:return G.None}},G={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 py from"node:fs";import sN from"node:path";import iN from"react";import{Box as rN}from"ink";import Xa from"react";import LR from"chalk";import{Box as Cd,Text as kR}from"ink";import Tn from"react";import{Text as th}from"ink";import nh,{useEffect as rh,useState as gR}from"react";var oh={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "],identity:["\u276F "]},St=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=te(),r=oh[n]??oh.default,[o,s]=gR(0);if(rh(()=>{s(0)},[r]),rh(()=>{if(!e)return;let l=setInterval(()=>{s(d=>(d+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return nh.createElement(th,null,t);let i=r[o]??r[0]??t;return nh.createElement(th,{color:y.accent,dimColor:o===1},i)};import{Box as Sd,Text as hR}from"ink";import Da from"react";var yR=(e,t,n,r)=>{let o=d=>Math.max(1,e[d]??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}},dt=({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)),d=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?yR(o,e.length,d,i):s?{start:Math.min(p,Math.max(0,d-m+1)),end:Math.min(p,Math.max(0,d-m+1))+m}:{start:Math.min(p,Math.floor(d/m)*m),end:Math.min(p,Math.floor(d/m)*m)+m},h=Math.max(1,g-f),x=e.slice(f,g),b=e.length>h,N=i,S=b?Math.max(1,Math.floor(h/e.length*N)):N,A=Math.max(0,N-S),T=Math.max(1,e.length-h),P=b?Math.floor(f/T*A):0;return Da.createElement(Sd,{flexDirection:"row",height:i,width:"100%"},Da.createElement(Sd,{flexDirection:"column",flexGrow:1,height:i},x),Da.createElement(Sd,{flexDirection:"column",width:1,height:N},Array.from({length:N}).map((M,O)=>Da.createElement(hR,{key:O,color:b&&O>=P&&O<P+S?y.accent:y.secondary},b?"\u2502":" "))))};import{Box as Bo,Text as Oo}from"ink";import Rt from"react";var sh,Rd,vR=()=>{let{eventLog:e=[]}=v();if(Rd&&sh===e)return Rd;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return sh=e,Rd=t,t},Ba=e=>vR().has(e);import{Text as bR}from"ink";import xR from"react";var mr=({id:e,isSelected:t,maxWidth:n})=>{let r=C.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:_n(o,n);return xR.createElement(bR,{underline:t,color:ze(o)},"@"+s,Ba(e)?"":"\u2197")};import{Text as IR}from"ink";import ER from"react";var ko=({id:e,isSelected:t,maxWidth:n})=>{let r=C.getTag(e);if(!r)return;let o=n===void 0?r.name:_n(r.name,n);return ER.createElement(IR,{underline:t,backgroundColor:ze(r.name),color:y.secondary}," "+o+" ")};import{useEffect as SR,useState as RR}from"react";var CR=80,ih=1400,Oa=new Set,Vs=null,NR=e=>(Oa.add(e),Vs||(Vs=setInterval(()=>{for(let t of Oa)t()},CR)),()=>{Oa.delete(e),Oa.size===0&&Vs&&(clearInterval(Vs),Vs=null)}),AR=()=>{let e=Date.now()%ih/ih;return e<.5?e*2:(1-e)*2},Do=e=>{let[,t]=RR(0);return SR(()=>{if(e)return NR(()=>t(n=>n+1))},[e]),Vi(AR())};var TR=(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),_n(e.slice(o).trim(),n)]},ah=3,wR=2,MR=(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}},lh=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Do(r),s=e-4,i=s-7-1,[l,d]=TR(Ee(t.title),i,s),m=d?null:_n(Ee(t.props.description),s)||null,p=yn(t),f=vn(t).map(S=>({...S,name:S.name})),g=Math.max(1,s-ah),h=C.getCommentsByIssue(t.id),x=h.length?String(h.length).length+2+1:0,{shown:b,hidden:N}=MR([...p.map(S=>({id:S.id,isTag:!0,width:Math.min(S.name.length,g)+ah})),...f.map(S=>({id:S.id,isTag:!1,width:Math.min(S.name.length,g)+wR+(Ba(S.id)?0:1)}))],s-x);return Rt.createElement(Bo,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?y.accent:y.secondary,justifyContent:"space-between"},Rt.createElement(Bo,{paddingLeft:1,paddingRight:1,flexDirection:"column"},Rt.createElement(Bo,{justifyContent:"space-between"},Rt.createElement(Oo,{color:y.primary},l),Rt.createElement(Oo,{color:y.secondary2,dimColor:!0},H(t.id))),d&&Rt.createElement(Oo,{color:y.primary},d),m&&Rt.createElement(Oo,{color:y.secondary2,dimColor:!0},m)),Rt.createElement(Bo,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},Rt.createElement(Bo,{flexDirection:"row"},b.map(S=>Rt.createElement(Bo,{paddingRight:1,key:S.id},S.isTag?Rt.createElement(ko,{id:S.id,maxWidth:g}):Rt.createElement(mr,{id:S.id,maxWidth:g}))),N>0&&Rt.createElement(Oo,{color:y.secondary2,dimColor:!0},"+",N)),h.length>0&&Rt.createElement(Oo,{color:y.accent},"[",h.length,"]")))};import{Box as Wr,Text as zs}from"ink";import kt from"react";var PR=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,ch=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let l=Do(s),d=(r.props.tags??[]).map(M=>C.getTag(M)).filter(M=>!!M),m=(r.props.assignees??[]).map(M=>C.getContributor(M)).map(M=>M&&{...M,name:M.name}).filter(M=>!!M),p=1,f=d.length*(1+p),g=m.length*(2+p),h=d.map(M=>kt.createElement(Wr,{key:M.id,paddingRight:p},kt.createElement(zs,{color:ze(M.name)},"\u25A0"))),x=m.map(M=>kt.createElement(Wr,{key:M.id,paddingRight:p},kt.createElement(zs,{color:Nc(M.name)},"@"+M.name.at(0)))),b=s?l:o?y.accent:i===I.MOVE?y.secondary:y.primary,N=C.getCommentsByIssue(r.id),S=N.length?String(N.length).length+2+p:0,A=N.length?kt.createElement(Wr,{paddingRight:p},kt.createElement(zs,{color:y.accent},"[",N.length,"]")):null,T=f+g+S,P=Math.max(1,n-t-T-(T>0?1:0));return kt.createElement(Wr,{justifyContent:"space-between"},kt.createElement(Wr,null,kt.createElement(Wr,{width:t},o?kt.createElement(St,{isSelected:!0}):kt.createElement(zs,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),kt.createElement(zs,{wrap:"truncate",color:b},PR(r.title,P))),kt.createElement(Wr,null,h,x,A))};var DR=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:l})=>{let{renderedChildrenIndex:d,replay:m}=te(),p=d[e.id]??[],f=m?new Set(m.flashNodeIds):null,g=f?.has(e.id)??!1,h=Do(g),x=`${e.title} ${LR.hex(y.secondary2).dim("("+p.length+")")}`,b=3,N=o?1:5,S=s&&i===-1,A=n-3-(o?1:0)-(S?2:0),T=Math.max(2,String(p.length).length+1),P=r-b-1,M=Tn.createElement(Cd,{borderStyle:"round",borderColor:y.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},Tn.createElement(St,{isSelected:t}),Tn.createElement(kR,{bold:!0,color:g?h:t?y.accent:y.primary},x," ",e.readonly?"\u{1F512}":"")),O=(W,Y)=>{let xe=s&&i===Y;if(!_(W))return null;let F=f?.has(W.id)??!1;return o?Tn.createElement(ch,{key:W.id,index:Y,labelWidth:T,width:A,ticket:W,isSelected:xe,isFlashing:F,mode:l}):Tn.createElement(lh,{key:W.id,width:A,ticket:W,isSelected:xe,isFlashing:F})};return Tn.createElement(Cd,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},M,Tn.createElement(Cd,null,p.length>0&&Tn.createElement(dt,{selectedIndex:i,height:P,itemHeight:N},p.map(O)),S&&Tn.createElement(St,{isSelected:!0})))},dh=Tn.memo(DR);import{Box as Go,Text as JC}from"ink";import Ct,{useMemo as Vo}from"react";var uh=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},mh=(e,t,n)=>Re.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});var ph=e=>e.action==="add.issue.comment";import{Box as Fo,Text as zn}from"ink";import ut,{useEffect as BR,useMemo as OR,useRef as FR}from"react";import{decodeTime as fh}from"ulid";var fr=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"},Fa=e=>String(e).padStart(2,"0"),_a=e=>`${e.getFullYear()}-${Fa(e.getMonth()+1)}-${Fa(e.getDate())} ${Fa(e.getHours())}:${Fa(e.getMinutes())}`;var _R=e=>we(e,"attachments"),$R=e=>C.getAttachmentsByIssue(e.id).sort((t,n)=>fh(t.id)-fh(n.id)),gh=e=>{for(let t of e)C.deleteNode(t.id)},UR=(e,t,n)=>Re.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),jR=(e,t)=>{let n=C.getNode(_R(e.id));if(!n||!it(n))return[];let r=t.map((o,s)=>UR(o,s,n.id)).map(o=>C.createNode(o)).filter(ye).map(({value:o})=>o).filter(it);return t.length>0&&v().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),r},HR=e=>`${Math.max(1,Math.round(e/1024))} KB`;function hh({ticket:e,width:t,height:n}){let r=OR(()=>$R(e),[e]),o=FR([]);BR(()=>(gh(o.current),o.current=jR(e,r),()=>{gh(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=te(),l=Math.max(1,n-4),d=Math.max(12,t-32);return r.length===0?ut.createElement(Fo,{flexDirection:"column",width:t,height:n,padding:1},ut.createElement(zn,{color:y.primary},"No attachments yet."),ut.createElement(Fo,{paddingTop:1},ut.createElement(zn,{color:y.primary},"Attach images from the browser GUI"),ut.createElement(zn,{color:y.accent}," epiq gui "),ut.createElement(zn,{color:y.primary},"by dropping or pasting them."))):ut.createElement(Fo,{flexDirection:"column",width:t,height:n},ut.createElement(Fo,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},ut.createElement(zn,{color:y.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),ut.createElement(dt,{height:l,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,g=m.name.length>d?m.name.slice(0,d-1)+"\u2026":m.name;return ut.createElement(Fo,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},ut.createElement(zn,{color:y.accent},f?"\u276F ":" "),ut.createElement(Fo,{paddingLeft:1},ut.createElement(zn,{color:y.secondary2},`#${p+1} `),ut.createElement(zn,{color:f?y.accent:y.primary},g),ut.createElement(zn,{color:y.secondary2}," "+HR(m.bytes)+" "+fr(De(m.id)))))})))}import{Box as gr,Text as hr}from"ink";import Ye,{useEffect as JR,useMemo as Mh,useRef as QR}from"react";import{decodeTime as Ph}from"ulid";var vh=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,Nd=e=>e.replace(vh,""),WR=e=>`<!-- epiq-diff-comment:${JSON.stringify(e).replaceAll(">","\\u003e")} -->`,yh=e=>e==="additions"||e==="deletions",Ks=e=>{let t=vh.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"||!yh(r.side)||!yh(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r};var bh=/```\n([\s\S]*?)\n?```\s*$/,xh=e=>bh.exec(e)?.[1]??null,GR=/`[^`\n]+`[^\n]*\n?$/,Ih=e=>Nd(e).replace(bh,"").replace(GR,"").trim(),Eh=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})`},Ad=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${Eh(e)}`;var VR=e=>{let t=e.split(`
|
|
69
69
|
`),n=t.filter(r=>r.trim()!=="").reduce((r,o)=>{let s=/^[ \t]*/.exec(o)?.[0].length??0;return r===null?s:Math.min(r,s)},null);return n?t.map(r=>r.slice(n)).join(`
|
|
70
|
-
`):e},
|
|
71
|
-
`)};var
|
|
72
|
-
`),t);let o=
|
|
73
|
-
`).map(
|
|
74
|
-
`),t),{kind:"blank"}]:[],{kind:"caption",text:
|
|
75
|
-
`),[m,p,f,g,...
|
|
76
|
-
`).filter(m=>m!==""),i=s.filter(m
|
|
77
|
-
`)){if(
|
|
78
|
-
`;else if(o==="t")n+=" ";else if(o==='"'||o==="\\")n+=o;else if(o&&/[0-7]/.test(o)){let s=t.slice(r,r+3);n+=String.fromCharCode(parseInt(s,8)),r+=2}else o!==void 0&&(n+=o)}try{return decodeURIComponent(escape(n))}catch{return n}},
|
|
79
|
-
`)){if(i.startsWith("diff --git ")){n=s();let p=i.slice(11),f=p.lastIndexOf(" b/");f!==-1&&(n.path=
|
|
80
|
-
`)}}};import{existsSync as
|
|
81
|
-
`).map(o=>o.trim()).filter(Boolean);return r.length===0?c("No changed files found for this commit"):u("Listed changed files",r)},wC=async(e,t,n)=>{let r=await TC(e,t);if(a(r))return c(r.message);let o=r.value;if(o.length>NC)return c(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=Ys("commit-diffs",t);if(a(s))return c(s.message);let i=s.value,l=await Promise.all(o.map(async(g,y)=>{let[x,b]=await Promise.all([zh(e,`${t}~1`,g),zh(e,t,g)]),R=Wa.basename(g),S=Wa.join(i,String(y),"before",R),T=Wa.join(i,String(y),"after",R);return Fd(S)||(ot.writeToFile(S,x),await _d(S,292)),Fd(T)||(ot.writeToFile(T,b),await _d(T,292)),{beforePath:S,afterPath:T}})),[d,...m]=l;if(!d)return c("No changed files found for this commit");let p=await Od(n,d.beforePath,d.afterPath,"new");if(a(p)||m.length===0)return p;await new Promise(g=>setTimeout(g,AC));let f=await Promise.all(m.map(({beforePath:g,afterPath:y})=>Od(n,g,y,"reuse")));for(let g of f)a(g)&&logger.error(`Failed to open an additional diff tab for ${t}: ${g.message}`);return p},Xs=async e=>{if(!Fo(e.sha))return c("Invalid commit sha");let t=nn(e.repoRoot);if(a(t))return c(t.message);let n=t.value,r=Ha()[0];if(r&&Bd(r)){let o=await wC(n,e.sha,r);if(!a(o))return o;logger.error(`Side-by-side diff failed for ${e.sha}, falling back to unified diff: ${o.message}`)}return CC(n,e.sha)};import{Box as rn,Text as Kn}from"ink";import _e,{useEffect as Hd,useMemo as Xh,useRef as LC,useState as kC}from"react";var Ga=(e,t,n)=>{let r=[],o=va(()=>{for(let s=0;s<t;s++){let i=Pt(BigInt(s+1));if(!be(i))continue;let l=N.createNode(Ne.text({id:n(s),name:`Line ${s+1}`,parentNodeId:e,rank:i.value,readonly:!0,isVirtual:!0}));be(l)&&r.push(l.value)}});return a(o)&&logger.error(`Line nodes: ${o.message}`),r},jo=e=>{N.deleteNodes(e.map(t=>t.id))};import{useSyncExternalStore as MC}from"react";var za=null,Va=null,$d=new Set,Kh=()=>{for(let e of $d)e()},Ud=e=>{za=e,Kh()},Ka=()=>za,qh={mark:null},Gr=e=>{Va=e,qh={mark:e},Kh()};var jd=e=>Va&&Va.sha===e?Va.row:null,Yh=()=>MC(e=>($d.add(e),()=>{$d.delete(e)}),()=>qh),hr=()=>{let{contextNode:e}=v();return za&&za.sha===e.id?e.id:null};import DC from"string-width";var Wd=(e,t)=>`${e}::patch::${t}`,BC=e=>{switch(e){case"added":return h.green;case"removed":return h.red;case"hunk":return h.accent;case"file":return h.primary;default:return h.secondary2}},Jh=(e,t)=>{let n=DC(e);return n>=t?e:e+"\xA0".repeat(t-n)},OC=e=>e==="added"?"+":e==="removed"?"-":" ",Qh=e=>e.kind==="file"||e.kind==="hunk"||e.kind==="note"||e.newLine===void 0?"":String(e.newLine);function Zh({ticket:e,sha:t,subject:n,width:r,height:o}){let[s,i]=kC({state:"loading"});Hd(()=>{let A=!0;return i({state:"loading"}),Nd({sha:t}).then(P=>{A&&i(a(P)?{state:"failed",message:P.message}:{state:"loaded",rows:Pd(Md(P.value))})}),()=>{A=!1}},[t]);let l=s.state==="loaded"?s.rows:null,d=l!==null&&l.length>4e3,m=LC([]);Hd(()=>(jo(m.current),m.current=l&&!d?Ga(t,l.length,A=>Wd(t,A)):[],()=>{jo(m.current),m.current=[]}),[t,l,d]),Hd(()=>(Ud(l?{sha:t,rows:l}:null),Gr(null),()=>{Ud(null),Gr(null)}),[t,l]);let{selectedIndex:p}=oe(),{mark:f}=Yh(),g=Xh(()=>l?Ld(l,N.getCommentsByIssue(e.id),t):new Set,[l,t,e]),y=f&&f.sha===t?f.row:null,x=A=>y!==null&&A>=Math.min(y,p)&&A<=Math.max(y,p),b=Xh(()=>l?Math.max(5,l.reduce((A,P)=>Math.max(A,Qh(P).length),0)+2):5,[l]),R=Math.max(1,o-4),S=Math.max(8,r-b-6);if(s.state!=="loaded")return _e.createElement(rn,{flexDirection:"column",width:r,height:o,padding:1},_e.createElement(Kn,{color:h.primary},s.state==="loading"?"Reading the diff\u2026":`Could not read the diff: ${s.message}`));let T=A=>_e.createElement(rn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:h.secondary,borderStyle:"single",paddingBottom:1},_e.createElement(Kn,{color:h.secondary2,wrap:"truncate-end"},_n(`${t.slice(0,7)} ${n} \u2014 ${A}`,Math.max(8,r-6))));return s.rows.length===0?_e.createElement(rn,{flexDirection:"column",width:r,height:o},T("no changes"),_e.createElement(rn,{paddingX:1},_e.createElement(Kn,{color:h.primary},"This commit changed no files."))):d?_e.createElement(rn,{flexDirection:"column",width:r,height:o},T("too large to draw here"),_e.createElement(rn,{paddingX:1,flexDirection:"column"},_e.createElement(Kn,{color:h.primary},`${s.rows.length.toLocaleString()} lines of diff.`),_e.createElement(Kn,{color:h.secondary2},"Press o to open it in your editor."))):_e.createElement(rn,{flexDirection:"column",width:r,height:o},T(y===null?"enter to comment on a line, s to start a range, o editor, q back":"move to the other end, then enter to comment \u2014 s clears the mark"),_e.createElement(mt,{scrollByOne:!0,height:R,selectedIndex:p,itemHeight:1},s.rows.map((A,P)=>{let M=P===p,O=BC(A.kind);if(A.kind==="file")return _e.createElement(rn,{key:Wd(t,P),paddingX:1},_e.createElement(Kn,{backgroundColor:h.secondary,color:M?h.accent:O,bold:!0,wrap:"truncate-end"},Jh(` ${_n(qs(A.text),S)}`,S+b+1)));let W=x(P),X=`${OC(A.kind)}${_n(qs(A.text),S)}`;return _e.createElement(rn,{key:Wd(t,P),paddingX:1},_e.createElement(rn,{flexShrink:0},_e.createElement(Kn,{color:M||W?h.accent:h.secondary2,dimColor:!M&&!W,wrap:"truncate-end"},`${M?"\u276F":"\xA0"}${W?"\u258C":"\xA0"}${Qh(A).padStart(b-2,"\xA0")}`)),_e.createElement(rn,{flexShrink:0},_e.createElement(Kn,{color:h.yellow,wrap:"truncate-end"},g.has(P)?"\u2502":"\xA0")),_e.createElement(Kn,{color:M?h.accent:O,backgroundColor:M||W?h.secondary:void 0,wrap:"truncate-end"},M||W?Jh(X,S+1):X))})))}var $C=e=>Pe(e,"diff"),ty=e=>{for(let t of e)N.deleteNode(t.id)},UC=(e,t,n)=>Ne.field({id:e.sha,name:e.subject,parentNodeId:n,rank:String(t).padStart(6,"0"),childRenderAxis:"vertical",isVirtual:!0}),jC=(e,t)=>{let n=N.getNode($C(e.id));if(!n||!lt(n))return[];let r=t.map((o,s)=>UC(o,s,n.id)).map(o=>N.createNode(o)).filter(be).map(({value:o})=>o).filter(lt);return t.length>0&&v().selectedIndex<0&&v().contextNode.id===n.id&&U.navigate({contextNode:n,selectedIndex:0}),r},HC=e=>`+${e.insertions} -${e.deletions}`;function ny({ticket:e,width:t,height:n}){let[r,o]=_C({state:"loading"}),s=H(e.id);ey(()=>{let x=!0;return o({state:"loading"}),zn({ref:s}).then(b=>{x&&o(a(b)?{state:"failed",message:b.message}:{state:"loaded",commits:b.value})}),()=>{x=!1}},[s]);let i=FC([]),l=r.state==="loaded"?r.commits:null;ey(()=>(ty(i.current),i.current=l?jC(e,l):[],()=>{ty(i.current),i.current=[]}),[e,l]);let{selectedIndex:d,contextNode:m}=oe(),p=l?.find(x=>x.sha===m.id)??null,g=Math.max(1,n-4),y=Math.max(12,t-34);return r.state!=="loaded"?Qe.createElement(Vr,{flexDirection:"column",width:t,height:n,padding:1},Qe.createElement(Tn,{color:h.primary},r.state==="loading"?"Reading commits\u2026":`Could not read commits: ${r.message}`)):p?Qe.createElement(Zh,{ticket:e,sha:p.sha,subject:p.subject,width:t,height:n}):r.commits.length===0?Qe.createElement(Vr,{flexDirection:"column",width:t,height:n,padding:1},Qe.createElement(Tn,{color:h.primary},"No commits reference this ticket."),Qe.createElement(Vr,{paddingTop:1},Qe.createElement(Tn,{color:h.primary},"Commits are matched by the"),Qe.createElement(Tn,{color:h.accent},` ${s} `),Qe.createElement(Tn,{color:h.primary},"prefix on their subject line."))):Qe.createElement(Vr,{flexDirection:"column",width:t,height:n},Qe.createElement(Vr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:h.secondary,borderStyle:"single",paddingBottom:1},Qe.createElement(Tn,{color:h.secondary2},`Diff (${r.commits.length}) \u2014 enter to read, o to open in your editor `)),Qe.createElement(mt,{height:g,itemHeight:2,selectedIndex:d},r.commits.map((x,b)=>{let R=b===d,S=x.subject.length>y?x.subject.slice(0,y-1)+"\u2026":x.subject;return Qe.createElement(Vr,{key:x.sha,flexDirection:"row",paddingX:1,paddingBottom:1},Qe.createElement(Tn,{color:h.accent},R?"\u276F ":" "),Qe.createElement(Vr,{paddingLeft:1},Qe.createElement(Tn,{color:h.secondary2},`${x.sha.slice(0,7)} `),Qe.createElement(Tn,{color:R?h.accent:h.primary},S),Qe.createElement(Tn,{color:h.secondary2},` ${HC(x)} ${pr(x.time)}`)))})))}import{Box as qa,Text as WC}from"ink";import qn from"react";var ry=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=oe(),{title:o}=t,s=t.parentNodeId?N.getNode(t.parentNodeId):void 0,i=s&&_(s)?o===Te.ASSIGNEES?s.props.assignees??[]:o===Te.TAGS?(s.props.tags??[]).filter(l=>N.getTag(l)):[]:[];return qn.createElement(qa,{alignItems:"center",paddingTop:1},qn.createElement(qa,{minWidth:12},qn.createElement(St,{isSelected:n}),qn.createElement(WC,{color:n?h.accent:h.secondary2},o,":")),qn.createElement(qa,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((l,d)=>{let m=r.id===t.id&&d===e;return qn.createElement(qa,{key:`${o}-${l}`,paddingRight:2,minHeight:1},qn.createElement(St,{isSelected:m}),o===Te.ASSIGNEES?qn.createElement(ur,{isSelected:m,id:l}):o===Te.TAGS?qn.createElement(Lo,{isSelected:m,id:l}):null)})))};import{Box as Ho,Text as zd}from"ink";import Ut,{useEffect as GC,useMemo as Kd,useRef as VC}from"react";var Gd=e=>Math.max(5,String(Math.max(e,1)).length+3),oy=(e,t)=>Math.max(0,e-6-Gd(t));var Vd=(e,t=0,n=0)=>Math.max(1,e-5-2*t-(n>0?1+n:0));var zC="\u2029",sy=(e,t)=>`${e}::inline-line::${t}`,qd=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:l}=oe(),d=Kd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Kd(()=>d.join("\0"),[d]),p=VC([]);GC(()=>(jo(p.current),p.current=Ga(e,d.length,b=>sy(e,b)),()=>{jo(p.current),p.current=[]}),[e,m]);let f=Gd(d.length),g=oy(s,d.length),x=Kd(()=>Rd(d).map(b=>{if(b.kind==="code"||b.kind==="caption")return{...b,text:_n(b.text,g)};if(b.kind==="text"||b.kind==="heading"){let R=b.spans.map(S=>S.code?`\`${S.text}\``:S.text).join("");return{...b,spans:Ks(_n(R,g))}}return b}),[d,g]).map((b,R)=>{let S=l.id===e&&i===R;return Ut.createElement(Ho,{key:sy(e,R)},Ut.createElement(Ho,{flexShrink:0},Ut.createElement(zd,{color:S?h.primary:h.secondary2,dimColor:!S},`${R+1} `.padStart(f,"\xA0"))),b.kind==="blank"?Ut.createElement(zd,{backgroundColor:S?"gray":void 0},zC):Ut.createElement(Ho,null,Ut.createElement(Cd,{line:b,width:b.kind==="code"?g:0,wrap:"truncate-end"})))});return Ut.createElement(Ho,{flexDirection:"column",paddingTop:1},Ut.createElement(Ho,null,Ut.createElement(St,{isSelected:o}),Ut.createElement(zd,{color:o?h.accent:h.secondary2},t)),Ut.createElement(Ho,{flexDirection:"row",borderStyle:"round",borderColor:h.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},Ut.createElement(mt,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},x)))};var qC=e=>Pe(e,"description"),YC=e=>Pe(e,"comments"),XC=e=>Pe(e,"history"),JC=e=>Pe(e,"diff"),QC=e=>Pe(e,"attachments"),iy=({ticket:e,height:t})=>{let n=Go(()=>sh(e),[e]),{selectedIndex:r,contextNode:o}=oe(),s=process.stdout.columns||120,i=Go(()=>qC(e.id),[e.id]),l=Go(()=>YC(e.id),[e.id]),d=Go(()=>XC(e.id),[e.id]),m=Go(()=>JC(e.id),[e.id]),p=Go(()=>QC(e.id),[e.id]),f=N.getAttachmentsByIssue(e.id).length,g=o.id===e.id,y=o.id===l||o.parentNodeId===l,x=o.id===d||o.parentNodeId===d,b=o.id===p||o.parentNodeId===p,R=o.id===m||o.parentNodeId===m,S=de(e.id);if(y){let J=t-3;return Ct.createElement(Wo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ct.createElement(Ah,{ticket:e,width:s,height:J}))}if(b){let J=t-3;return Ct.createElement(Wo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ct.createElement(dh,{ticket:e,width:s,height:J}))}if(R){let J=t-3;return Ct.createElement(Wo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ct.createElement(ny,{ticket:e,width:s,height:J}))}if(x){let F=N.getNode(d),J=F&<(F)?F.props.value??"":"",Ke=Vd(t);return Ct.createElement(Wo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},F?Ct.createElement(qd,{id:F.id,label:"Event log",text:J,selected:!1,maxWidth:s,rows:Ke}):null)}let T=[d,m,l,p],A=F=>T.includes(F),P=S.reduce((F,J)=>vs(J)?F+1:F,0),M=S.reduce((F,J)=>A(J.id)?F+1:F,0),O=S.findIndex(F=>A(F.id)),W=Vd(t,P,M),X=(F,J,Ke,Jn)=>Ct.createElement(Wo,{key:F.id,paddingTop:J===O?1:0},Ct.createElement(St,{isSelected:Ke}),Ct.createElement(KC,{backgroundColor:h.secondary,color:Ke?h.accent:h.primary},Jn)),Ee=(F,J,Ke)=>F.id===i?Ct.createElement(qd,{key:F.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:J,maxWidth:s,rows:W}):vs(F)?Ct.createElement(ry,{key:F.id,parent:F,selected:J,selectedIndex:r}):F.id===l?X(F,Ke,J,` Comments (${n}) \u203A\u203A `):F.id===p?X(F,Ke,J,` Attachments (${f}) \u203A\u203A `):F.id===d?X(F,Ke,J," History \u203A\u203A "):F.id===m?X(F,Ke,J," Diff \u203A\u203A "):null;return Ct.createElement(Wo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},S.map((F,J)=>Ee(F,g&&r===J,J)))};var eN=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:l})=>{let d=t.context,m=d===ie.TICKET||d===ie.FIELD_LIST||d===ie.FIELD,p=d===ie.BOARD||d===ie.SWIMLANE,f=d===ie.TICKET?t:r.find(R=>R.context===ie.TICKET),g=Math.floor(l/3),y=Math.floor(l/Math.max(e.length,1)),x=Math.min(y,g),b=s==="dense";return Ya.createElement(ZC,{flexDirection:"row",height:i},p&&e.map((R,S)=>{let T=t.id===R.id,A=T?n:-1,P=t.context===ie.BOARD&&n===S;return Ya.createElement(oh,{key:R.id,height:i,width:x,swimlane:R,isSelected:P,isDense:b,isFocused:T,listSelectedIndex:A,mode:o})}),m&&f&&Ya.createElement(iy,{height:i,ticket:f}))},Xa=Ya.memo(eN);import{render as rN}from"ink";import{Writable as oN}from"node:stream";var Js=e=>String(e).padStart(2,"0"),sN=e=>{let t=e.getUTCFullYear(),n=Js(e.getUTCMonth()+1),r=Js(e.getUTCDate()),o=Js(e.getUTCHours()),s=Js(e.getUTCMinutes()),i=Js(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},iN=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",aN=async(e,{width:t,height:n})=>{let r="",o=new oN({write(i,l,d){let m=lN(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),d()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=rN(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},lN=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),ly=async()=>{let{viewMode:e}=V(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=v(),i=r.find(S=>S.context==="BOARD");if(!i)return c("No board found to export");let l=120,d=40,m=await aN(nN.createElement(Xa,{height:d,width:l,swimlanes:(s[i.id]??[]).filter(S=>S!==void 0&&gn(S)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:d});if(!m)return c("Failed to render board export");let p=Oi(process.cwd());if(a(p))return c("Unable to export, epiq root not found");let f=new Date,g=sN(f),y=`board_${iN(i.title)}_${g}.md`,x=Gm(p.value);ay.mkdirSync(x,{recursive:!0});let b=tN.join(x,y),R=`# Board - ${i.title}
|
|
70
|
+
`):e},Sh=({snippet:e,...t})=>{let n=t.note.trim();return[...n?[n,""]:[],WR({...t,note:n}),`\`${t.filePath}\` ${Eh(t)}`,"```",VR(e),"```"].join(`
|
|
71
|
+
`)};var zR=(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},qs=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)},KR=/!\[([^\]]*)\]\([^)]*\)/g,qR=e=>e.replace(KR,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),YR=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),XR=4,Ys=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(XR)),Td=e=>{let t=!1;return e.map(Ys).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=Ks(n);if(r)return{kind:"caption",text:Ad(r)};let o=qR(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:qs(s[1]??"")}:{kind:"text",spans:qs(o)}})},Ch=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Rh=(e,t)=>{let n=[];for(let r of Td(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 Ch(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of zR(YR(r.spans),t))n.push({kind:r.kind,spans:qs(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},Nh=(e,t)=>{let n=Ks(e),r=n?xh(e):null;if(!n||r===null)return Rh(Nd(e).split(`
|
|
72
|
+
`),t);let o=Ih(e),s=r.split(`
|
|
73
|
+
`).map(Ys),i=n.side===n.endSide?n.start:void 0,l=i===void 0?0:String(i+s.length-1).length+3;return[...o?[...Rh(o.split(`
|
|
74
|
+
`),t),{kind:"blank"}]:[],{kind:"caption",text:Ad(n)},...s.flatMap((d,m)=>Ch(d,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 Ah,Text as Gr}from"ink";import jt from"react";var Th=({spans:e,bold:t,wrap:n})=>jt.createElement(Gr,{color:y.primary,bold:t,wrap:n},e.map((r,o)=>r.code?jt.createElement(Gr,{key:o,color:y.yellow},r.text):jt.createElement(Gr,{key:o},r.text))),wd=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return jt.createElement(Gr,null," ");case"fence":return jt.createElement(Gr,{color:y.secondary2},"```");case"caption":return jt.createElement(Gr,{color:y.accent,wrap:r},e.text);case"heading":return jt.createElement(Th,{spans:e.spans,bold:!0,wrap:r});case"text":return jt.createElement(Th,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return jt.createElement(Gr,{backgroundColor:y.secondary,color:y.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},wh=({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 jt.createElement(Ah,{flexDirection:"column"},e.map((o,s)=>jt.createElement(Ah,{key:s},jt.createElement(wd,{line:o,width:t,gutter:r}))))};var ZR=4,eC=e=>we(e,"comments"),tC=e=>C.getCommentsByIssue(e.id).sort((t,n)=>Ph(t.id)-Ph(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,md:t.md})),Lh=e=>{for(let t of e)C.deleteNode(t.id)},nC=(e,t)=>{let n=C.getNode(eC(e.id));if(!n||!it(n))return[];let r=t.map((o,s)=>mh(o,s,n.id)).map(C.createNode).filter(ye).map(({value:o})=>o).filter(xs);return t.length>0&&v().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),r};function kh({ticket:e,width:t,height:n}){let r=Mh(()=>tC(e),[e]),o=QR([]);JR(()=>(Lh(o.current),o.current=nC(e,r),()=>{Lh(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=te(),l=Math.max(1,n-4),d=Math.max(20,t-8),m=Mh(()=>r.map(f=>{let g=Nh(f.md,d);return g.length>0?g:[{kind:"blank"}]}),[r,d]),p=m.map(f=>f.length+ZR);return r.length===0?Ye.createElement(gr,{flexDirection:"column",width:t,height:n,padding:1},Ye.createElement(hr,{color:y.primary},"No comments yet."),Ye.createElement(gr,{paddingTop:1},Ye.createElement(hr,{color:y.primary},"Use"),Ye.createElement(hr,{color:y.accent}," :comment "),Ye.createElement(hr,{color:y.primary},"to add the first one."))):Ye.createElement(gr,{flexDirection:"column",width:t,height:n},Ye.createElement(gr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},Ye.createElement(hr,{color:y.secondary2},"Comments (",r.length,") ")),Ye.createElement(dt,{height:l,itemHeights:p,selectedIndex:s},r.map((f,g)=>{let h=g===s;return Ye.createElement(gr,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Ye.createElement(gr,{flexDirection:"row",paddingBottom:1},Ye.createElement(hr,{color:y.accent},h?"\u276F ":" "),Ye.createElement(gr,{paddingLeft:1},Ye.createElement(hr,{color:y.secondary2},`#${g+1} `),Ye.createElement(mr,{id:f.authorId}),Ye.createElement(hr,{color:y.secondary2}," "+fr(De(f.id))))),Ye.createElement(gr,{paddingLeft:3,paddingBottom:1},Ye.createElement(wh,{lines:m[g]??[],width:d})))})))}import{Box as zr,Text as wn}from"ink";import Xe,{useEffect as iy,useRef as jC,useState as HC}from"react";var on=e=>{let t=ce(e??process.cwd());return a(t)?c(t.message):u("Resolved Epiq repo root",t.value)},_o=e=>/^[0-9a-f]{7,40}$/i.test(e);var rC="EPIQ_CACHE_MS",$a=e=>{let t=process.env[rC];if(t===void 0||t.trim()==="")return e;let n=Number(t);return Number.isFinite(n)&&n>=0?n:e};var $o="",Dh="",Bh=5e3,Uo=null;var oC=(e,t,n)=>(t===void 0||e>=Math.floor(t/1e3)*1e3)&&(n===void 0||e<=n),jo=async(e={})=>{let t=on(e.repoRoot);if(a(t))return c(t.message);let n=Tt(t.value);if(a(n))return c(n.message);let r=e.start===void 0&&e.end===void 0;if(r&&Uo&&Uo.repoRoot===t.value&&Uo.stateBranch===n.value.stateBranch&&Date.now()-Uo.fetchedAt<$a(Bh))return u("Computed commit timeline",Uo.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=${Dh}%H${$o}%at${$o}%an${$o}%ae${$o}%s`]});if(a(o))return c(o.message);let s=o.value.stdout.split(Dh).filter(i=>i.trim().length>0).map(i=>{let[l,...d]=i.split(`
|
|
75
|
+
`),[m,p,f,g,...h]=(l??"").split($o);if(!m||!p)return null;let x=d.join(" "),b=Number(/(\d+) insertion/.exec(x)?.[1]??0),N=Number(/(\d+) deletion/.exec(x)?.[1]??0);return{sha:m,time:Number(p)*1e3,author:f??"unknown",authorEmail:g??"",subject:h.join($o),linesChanged:b+N,insertions:b,deletions:N}}).filter(i=>i!==null).filter(i=>oC(i.time,e.start,e.end));return r&&(Uo={repoRoot:t.value,stateBranch:n.value.stateBranch,fetchedAt:Date.now(),result:s}),u("Computed commit timeline",s)},Kn=async e=>{let t=e.ref.trim();if(!t)return c("ref must not be empty");if(t.length!==7)return c(`"${t}" is ${t.length} characters; a ref is ${7}. Read it off the issue rather than slicing the id by hand.`);let n=await jo({repoRoot:e.repoRoot});if(a(n))return c(n.message);let r=`${t.toUpperCase()} `,o=l=>l.subject.toUpperCase().startsWith(r),s=n.value,i=[];for(let[l,d]of s.entries()){if(!o(d))continue;let m=s[l+1];i.push({...d,precedingSha:m&&o(m)?m.sha:null})}return u("Matched commits by ref",i)};var Md=async e=>{if(!_o(e.sha))return c("Invalid commit sha");let t=on(e.repoRoot);if(a(t))return c(t.message);let n=await j({cwd:t.value,args:["show","--no-ext-diff","--no-color","--patch","--find-renames","--format=",e.sha]});return a(n)?c(n.message):u("Read commit patch",n.value.stdout)},sC=200,Oh=e=>/^0+$/.test(e),Ua=/^:\d{6} \d{6} ([0-9a-f]{40}) ([0-9a-f]{40}) [A-Z]\d*\t(.+)$/,Fh=/^(\d+|-)\t(\d+|-)\t(.+)$/,$h=async(e,t,n,r)=>{let o=await j({cwd:e,args:["diff","--raw","--numstat","--no-renames","--abbrev=40",t,n,...r&&r.length>0?["--",...r]:[]]});if(a(o))return c(o.message);let s=o.value.stdout.split(`
|
|
76
|
+
`).filter(m=>m!==""),i=s.filter(m=>!Ua.test(m)&&!Fh.test(m));if(i.length>0)return c(`Could not parse ${i.length} line(s) of "git diff --raw --numstat" output, e.g. "${i[0]}"`);let l=new Map;for(let m of s){let p=Fh.exec(m);p&&l.set(p[3]??"",{insertions:p[1]==="-"?0:Number(p[1]),deletions:p[2]==="-"?0:Number(p[2]),isBinary:p[1]==="-"&&p[2]==="-"})}let d=s.filter(m=>Ua.test(m)).map(m=>{let p=Ua.exec(m),f=p?.[1]??"",g=p?.[2]??"",h=p?.[3]??"";return{path:h,beforeBlob:Oh(f)?null:f,afterBlob:Oh(g)?null:g,...l.get(h)??{insertions:0,deletions:0,isBinary:!1}}});return u("Listed changed files with blob hashes",d)},Uh=async(e,t)=>{if(t.length>sC)return c(`${t.length} files changed \u2014 too many to show as a diff`);let n=t.flatMap(s=>s.isBinary?[]:[s.beforeBlob,s.afterBlob].filter(i=>i!==null)),r=await _i(n,e);if(a(r))return c(r.message);let o=r.value;return u("Read changed file contents",t.map(s=>({path:s.path,before:s.isBinary||!s.beforeBlob?"":o.get(s.beforeBlob)??"",after:s.isBinary||!s.afterBlob?"":o.get(s.afterBlob)??"",insertions:s.insertions,deletions:s.deletions,isBinary:s.isBinary})))},Pd=async e=>{if(!_o(e.sha))return c("Invalid commit sha");let t=on(e.repoRoot);if(a(t))return c(t.message);let n=t.value,r=await $h(n,`${e.sha}~1`,e.sha);if(a(r))return c(r.message);if(r.value.length===0)return c("No changed files found for this commit");let o=await Uh(n,r.value);if(a(o))return c(o.message);let s=o.value;return u("Loaded commit diff",{sha:e.sha,files:s})},iC=/^[0-9a-f]{40}$/,aC=async(e,t,n)=>{let r=await j({cwd:e,args:["log","--raw","--no-renames","--abbrev=40","--format=%H",`${t}..${n}`]});if(a(r))return c(r.message);let o=new Map,s=null;for(let i of r.value.stdout.split(`
|
|
77
|
+
`)){if(iC.test(i)){s=new Set,o.set(i,s);continue}let l=Ua.exec(i);l&&s&&s.add(l[3]??"")}return u("Listed changed paths per commit",o)},_h=e=>{let t=new Set;for(let n of e)for(let r of n)t.add(r);return t},lC=async(e,t,n)=>{if(t===n)return!0;let r=await j({cwd:e,args:["merge-base","--is-ancestor",t,n]});return!a(r)},cC="4b825dc642cb6eb9a060e54bf8d69288fbee4904",dC=async(e,t)=>{let n=await j({cwd:e,args:["rev-parse","--verify","--quiet",`${t}^1`]});return a(n)?cC:`${t}~1`},Ld=async e=>{let t=on(e.repoRoot);if(a(t))return c(t.message);let n=t.value,r=await Kn({repoRoot:n,ref:e.ref});if(a(r))return c(r.message);let o=r.value;if(o.length===0)return c("No commits reference this ticket");let s=o[0].sha,i=s;for(let T=o.length-1;T>0;T--){let P=o[T].sha;if(await lC(n,P,s)){i=P;break}}let l=await dC(n,i),d=await aC(n,l,s);if(a(d))return c(d.message);let m=d.value,p=new Set(o.map(T=>T.sha)),f=[...m.keys()].filter(T=>p.has(T)),g=f.length===m.size,h=new Map;for(let T of f)for(let P of m.get(T)??[])h.has(P)||h.set(P,T);let x=(T,P)=>u("Loaded squashed diff",{ref:e.ref.trim().toUpperCase(),from:l,to:s,commits:f.length,files:T.map(M=>({...M,sha:h.get(M.path)??s})),contiguous:g,overlappingPaths:P}),b,N=[];if(!g){let T=_h(f.map(M=>m.get(M)??new Set)),P=_h([...m.entries()].filter(([M])=>!p.has(M)).map(([,M])=>M));if(T.size===0)return x([],[]);b=[...T],N=[...T].filter(M=>P.has(M)).sort()}let S=await $h(n,l,s,b);if(a(S))return c(S.message);let A=await Uh(n,S.value);return a(A)?c(A.message):x(A.value,N)};var uC=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/,ja=e=>{if(!e.startsWith('"')||!e.endsWith('"'))return e;let t=e.slice(1,-1),n="";for(let r=0;r<t.length;r++){if(t[r]!=="\\"){n+=t[r];continue}let o=t[++r];if(o==="n")n+=`
|
|
78
|
+
`;else if(o==="t")n+=" ";else if(o==='"'||o==="\\")n+=o;else if(o&&/[0-7]/.test(o)){let s=t.slice(r,r+3);n+=String.fromCharCode(parseInt(s,8)),r+=2}else o!==void 0&&(n+=o)}try{return decodeURIComponent(escape(n))}catch{return n}},jh=e=>{let t=ja(e.trim());return t==="/dev/null"?null:t.replace(/^[ab]\//,"")},Dd=e=>{let t=[],n=null,r=0,o=0,s=()=>{let i={path:"",oldPath:null,binary:!1,added:0,removed:0,lines:[]};return t.push(i),i};for(let i of e.split(`
|
|
79
|
+
`)){if(i.startsWith("diff --git ")){n=s();let p=i.slice(11),f=p.lastIndexOf(" b/");f!==-1&&(n.path=ja(p.slice(f+1)).replace(/^b\//,""));continue}if(!n){if(!i.trim())continue;n=s()}let l=n,d=l.lines.length===0;if(d&&i.startsWith("--- ")){let p=jh(i.slice(4));p&&(l.oldPath=p);continue}if(d&&i.startsWith("+++ ")){let p=jh(i.slice(4));p&&(l.path=p);continue}if(d&&i.startsWith("rename from ")){l.oldPath=ja(i.slice(12));continue}if(d&&i.startsWith("rename to ")){l.path=ja(i.slice(10));continue}if(d&&(i.startsWith("Binary files ")||i.startsWith("GIT binary patch"))){l.binary=!0,l.lines.push({kind:"note",text:"Binary file"});continue}let m=uC.exec(i);if(m){r=Number(m[1]),o=Number(m[3]),l.lines.push({kind:"hunk",text:i});continue}if(!d){if(i.startsWith("\\")){l.lines.push({kind:"note",text:i.slice(1).trim()});continue}if(i.startsWith("+")){l.added++,l.lines.push({kind:"added",text:i.slice(1),newLine:o++});continue}if(i.startsWith("-")){l.removed++,l.lines.push({kind:"removed",text:i.slice(1),oldLine:r++});continue}if(i.startsWith(" ")){l.lines.push({kind:"context",text:i.slice(1),oldLine:r++,newLine:o++});continue}i===""&&l.lines.push({kind:"context",text:"",oldLine:r++,newLine:o++})}}for(let i of t)!i.path&&i.oldPath&&(i.path=i.oldPath);return t.filter(i=>i.path!=="")},kd=e=>e.oldPath&&e.oldPath!==e.path?e.oldPath:null;var Bd=e=>e.flatMap(t=>[{kind:"file",text:`${kd(t)?`${kd(t)} \u2192 `:""}${t.path}`,file:t},...t.lines]),Ha=e=>{let t="",n=-1;return e.map(r=>(r.kind==="file"&&(t=r.file.path),r.kind==="hunk"&&n++,{file:t,hunk:n}))},Od=(e,t,n)=>{let r=t.map(i=>Ks(i.md)).filter(i=>i!==null&&i.sha===n&&i.side==="additions");if(r.length===0)return new Set;let o=Ha(e),s=new Set;return e.forEach((i,l)=>{let d=i.newLine;if(d===void 0)return;let m=o[l]?.file;r.some(p=>p.filePath===m&&p.start<=d&&d<=p.end)&&s.add(l)}),s},Hh=(e,t)=>e===t?`line:${e}`:`lines:${e}-${t}`,mC=/^lines?:(\d+)(?:-(\d+))?(?:\s+|$)/,Wh=e=>{let t=mC.exec(e);if(!t)return null;let n=Number(t[1]),r=t[2]===void 0?n:Number(t[2]);return{start:Math.min(n,r),end:Math.max(n,r),note:e.slice(t[0].length)}},Gh=(e,t)=>Ha(e)[t]?.file??null,Vh=(e,t,n,r)=>{let o=Ha(e),s=d=>e.findIndex((m,p)=>o[p]?.file===t&&(m.kind==="added"||m.kind==="context")&&m.newLine===d),i=s(n),l=s(r);return i===-1||l===-1?{ok:!1,reason:`${t} has no line ${i===-1?n:r} on the new side`}:Fd(e,i,l)},Fd=(e,t,n)=>{let[r,o]=t<=n?[t,n]:[n,t],s=e[r],i=e[o];if(!s||!i)return{ok:!1,reason:"That line is not in the diff"};let l=g=>(g.kind==="added"||g.kind==="context")&&g.newLine!==void 0;if(!l(s)||!l(i))return{ok:!1,reason:"Comments anchor to the new side: pick an added or unchanged line"};let d=Ha(e),m=d[r],p=d[o];if(m.file!==p.file)return{ok:!1,reason:"A comment covers one file at a time"};if(m.hunk!==p.hunk)return{ok:!1,reason:"A comment covers one hunk at a time"};let f=e.slice(r,o+1).filter(l);return{ok:!0,value:{filePath:m.file,start:f[0].newLine,end:f[f.length-1].newLine,snippet:f.map(g=>g.text).join(`
|
|
80
|
+
`)}}};import{existsSync as jd}from"node:fs";import{chmod as Hd}from"node:fs/promises";import Ga from"node:path";import{spawn as pC,spawnSync as fC}from"node:child_process";import gC from"node:os";import zh from"node:path";import{ulid as hC}from"ulid";function _d(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 yC(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Wa(){let{preferredEditor:e}=V(),t=[e?yC(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function $d(e){let[t=""]=_d(e);return/(^|\/)code(-insiders)?$/.test(t)}function Kh(e,t){let[n="",...r]=_d(e);return{command:n,args:[...r,...t]}}function qh(e,t){return Kh(e,$d(e)?["--wait",t]:[t])}function vC(e,t,n,r="new"){return Kh(e,[r==="new"?"--new-window":"--reuse-window","--diff",t,n])}function Yh(e){let t=zh.join(gC.tmpdir(),"epiq");nt.mkDir(t);let n=zh.join(t,hC());nt.writeToFile(n,e??"");let r=Wa();for(let o of r){let{command:s,args:i}=qh(o,n);if(!s)continue;let l=fC(s,i,{stdio:"inherit"});if(!l.error&&l.status===0){let d=nt.readFile(n);if(d==null)return c("Unable to read edited file");let m=d.replace(/\r?\n$/,"");return u("Successfully edited",m)}}return c("Unable to open editor")}var bC=new Set(["vim","vi","nvim","nano","pico","ed"]);function xC(e){let[t=""]=_d(e),n=t.split("/").pop()??t;return bC.has(n)}var IC=600;function Xh({command:e,args:t},n){return new Promise(r=>{if(!e){r(c(`"${n}" is not a usable editor command`));return}let o=pC(e,t,{stdio:"ignore",detached:!0}),s=!1,i=d=>{s||(s=!0,clearTimeout(l),r(d))};o.on("error",d=>i(c(d.message))),o.on("exit",d=>{i(d===0?u("Opened editor",!0):c(`"${n}" exited with code ${d}`))});let l=setTimeout(()=>{o.unref(),i(u("Opened editor",!0))},IC)})}function EC(e,t){return xC(e)?Promise.resolve(c(`"${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}`)):Xh(qh(e,t),e)}function Ud(e,t,n,r="new"){return Xh(vC(e,t,n,r),e)}async function Jh(e){let t=Wa();if(t.length===0)return c("No editor configured (preferredEditor, VISUAL, or EDITOR)");let n=c("Unable to open editor");for(let r of t){let o=await EC(r,e);if(!a(o))return o;n=o,logger.error(`Failed to open editor "${r}" for ${e}: ${o.message}`)}return n}import{chmodSync as SC,existsSync as RC,lstatSync as CC,mkdirSync as NC}from"node:fs";import AC from"node:os";import TC from"node:path";var Xs=(...e)=>{let t=TC.join(AC.tmpdir(),"epiq",...e);try{return RC(t)&&CC(t).isSymbolicLink()?c(`Refusing to write through a symlink at ${t}`):(NC(t,{recursive:!0,mode:448}),SC(t,448),u("Prepared private temp dir",t))}catch(n){return c(`Unable to prepare ${t}: ${n instanceof Error?n.message:String(n)}`)}};var wC=async(e,t)=>{let n=await j({cwd:e,args:["show",t]});if(a(n))return c(n.message);let r=Xs("commit-diffs");if(a(r))return c(r.message);let o=Ga.join(r.value,`${t}.diff`);return jd(o)||(nt.writeToFile(o,n.value.stdout),await Hd(o,292)),Jh(o)},MC=12,PC=800,Qh=async(e,t,n)=>{let r=await j({cwd:e,args:["show",`${t}:${n}`]});return a(r)?"":r.value.stdout},LC=async(e,t)=>{let n=await j({cwd:e,args:["diff","--name-only",`${t}~1`,t]});if(a(n))return c(n.message);let r=n.value.stdout.split(`
|
|
81
|
+
`).map(o=>o.trim()).filter(Boolean);return r.length===0?c("No changed files found for this commit"):u("Listed changed files",r)},kC=async(e,t,n)=>{let r=await LC(e,t);if(a(r))return c(r.message);let o=r.value;if(o.length>MC)return c(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=Xs("commit-diffs",t);if(a(s))return c(s.message);let i=s.value,l=await Promise.all(o.map(async(g,h)=>{let[x,b]=await Promise.all([Qh(e,`${t}~1`,g),Qh(e,t,g)]),N=Ga.basename(g),S=Ga.join(i,String(h),"before",N),A=Ga.join(i,String(h),"after",N);return jd(S)||(nt.writeToFile(S,x),await Hd(S,292)),jd(A)||(nt.writeToFile(A,b),await Hd(A,292)),{beforePath:S,afterPath:A}})),[d,...m]=l;if(!d)return c("No changed files found for this commit");let p=await Ud(n,d.beforePath,d.afterPath,"new");if(a(p)||m.length===0)return p;await new Promise(g=>setTimeout(g,PC));let f=await Promise.all(m.map(({beforePath:g,afterPath:h})=>Ud(n,g,h,"reuse")));for(let g of f)a(g)&&logger.error(`Failed to open an additional diff tab for ${t}: ${g.message}`);return p},Js=async e=>{if(!_o(e.sha))return c("Invalid commit sha");let t=on(e.repoRoot);if(a(t))return c(t.message);let n=t.value,r=Wa()[0];if(r&&$d(r)){let o=await kC(n,e.sha,r);if(!a(o))return o;logger.error(`Side-by-side diff failed for ${e.sha}, falling back to unified diff: ${o.message}`)}return wC(n,e.sha)};import{Box as sn,Text as qn}from"ink";import Fe,{useEffect as zd,useMemo as ny,useRef as OC,useState as FC}from"react";var Va=(e,t,n)=>{let r=[],o=ba(()=>{for(let s=0;s<t;s++){let i=Lt(BigInt(s+1));if(!ye(i))continue;let l=C.createNode(Re.text({id:n(s),name:`Line ${s+1}`,parentNodeId:e,rank:i.value,readonly:!0,isVirtual:!0}));ye(l)&&r.push(l.value)}});return a(o)&&logger.error(`Line nodes: ${o.message}`),r},Ho=e=>{C.deleteNodes(e.map(t=>t.id))};import{useSyncExternalStore as DC}from"react";var Ka=null,za=null,Wd=new Set,Zh=()=>{for(let e of Wd)e()},Gd=e=>{Ka=e,Zh()},qa=()=>Ka,ey={mark:null},Vr=e=>{za=e,ey={mark:e},Zh()};var Vd=e=>za&&za.sha===e?za.row:null,ty=()=>DC(e=>(Wd.add(e),()=>{Wd.delete(e)}),()=>ey),yr=()=>{let{contextNode:e}=v();return Ka&&Ka.sha===e.id?e.id:null};import _C from"string-width";var Kd=(e,t)=>`${e}::patch::${t}`,$C=e=>{switch(e){case"added":return y.green;case"removed":return y.red;case"hunk":return y.accent;case"file":return y.primary;default:return y.secondary2}},ry=(e,t)=>{let n=_C(e);return n>=t?e:e+"\xA0".repeat(t-n)},UC=e=>e==="added"?"+":e==="removed"?"-":" ",oy=e=>e.kind==="file"||e.kind==="hunk"||e.kind==="note"||e.newLine===void 0?"":String(e.newLine);function sy({ticket:e,sha:t,subject:n,width:r,height:o}){let[s,i]=FC({state:"loading"});zd(()=>{let T=!0;return i({state:"loading"}),Md({sha:t}).then(P=>{T&&i(a(P)?{state:"failed",message:P.message}:{state:"loaded",rows:Bd(Dd(P.value))})}),()=>{T=!1}},[t]);let l=s.state==="loaded"?s.rows:null,d=l!==null&&l.length>4e3,m=OC([]);zd(()=>(Ho(m.current),m.current=l&&!d?Va(t,l.length,T=>Kd(t,T)):[],()=>{Ho(m.current),m.current=[]}),[t,l,d]),zd(()=>(Gd(l?{sha:t,rows:l}:null),Vr(null),()=>{Gd(null),Vr(null)}),[t,l]);let{selectedIndex:p}=te(),{mark:f}=ty(),g=ny(()=>l?Od(l,C.getCommentsByIssue(e.id),t):new Set,[l,t,e]),h=f&&f.sha===t?f.row:null,x=T=>h!==null&&T>=Math.min(h,p)&&T<=Math.max(h,p),b=ny(()=>l?Math.max(5,l.reduce((T,P)=>Math.max(T,oy(P).length),0)+2):5,[l]),N=Math.max(1,o-4),S=Math.max(8,r-b-6);if(s.state!=="loaded")return Fe.createElement(sn,{flexDirection:"column",width:r,height:o,padding:1},Fe.createElement(qn,{color:y.primary},s.state==="loading"?"Reading the diff\u2026":`Could not read the diff: ${s.message}`));let A=T=>Fe.createElement(sn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},Fe.createElement(qn,{color:y.secondary2,wrap:"truncate-end"},$n(`${t.slice(0,7)} ${n} \u2014 ${T}`,Math.max(8,r-6))));return s.rows.length===0?Fe.createElement(sn,{flexDirection:"column",width:r,height:o},A("no changes"),Fe.createElement(sn,{paddingX:1},Fe.createElement(qn,{color:y.primary},"This commit changed no files."))):d?Fe.createElement(sn,{flexDirection:"column",width:r,height:o},A("too large to draw here"),Fe.createElement(sn,{paddingX:1,flexDirection:"column"},Fe.createElement(qn,{color:y.primary},`${s.rows.length.toLocaleString()} lines of diff.`),Fe.createElement(qn,{color:y.secondary2},"Press o to open it in your editor."))):Fe.createElement(sn,{flexDirection:"column",width:r,height:o},A(h===null?"enter to comment on a line, s to start a range, o editor, q back":"move to the other end, then enter to comment \u2014 s clears the mark"),Fe.createElement(dt,{scrollByOne:!0,height:N,selectedIndex:p,itemHeight:1},s.rows.map((T,P)=>{let M=P===p,O=$C(T.kind);if(T.kind==="file")return Fe.createElement(sn,{key:Kd(t,P),paddingX:1},Fe.createElement(qn,{backgroundColor:y.secondary,color:M?y.accent:O,bold:!0,wrap:"truncate-end"},ry(` ${$n(Ys(T.text),S)}`,S+b+1)));let W=x(P),Y=`${UC(T.kind)}${$n(Ys(T.text),S)}`;return Fe.createElement(sn,{key:Kd(t,P),paddingX:1},Fe.createElement(sn,{flexShrink:0},Fe.createElement(qn,{color:M||W?y.accent:y.secondary2,dimColor:!M&&!W,wrap:"truncate-end"},`${M?"\u276F":"\xA0"}${W?"\u258C":"\xA0"}${oy(T).padStart(b-2,"\xA0")}`)),Fe.createElement(sn,{flexShrink:0},Fe.createElement(qn,{color:y.yellow,wrap:"truncate-end"},g.has(P)?"\u2502":"\xA0")),Fe.createElement(qn,{color:M?y.accent:O,backgroundColor:M||W?y.secondary:void 0,wrap:"truncate-end"},M||W?ry(Y,S+1):Y))})))}var WC=e=>we(e,"diff"),ay=e=>{for(let t of e)C.deleteNode(t.id)},GC=(e,t,n)=>Re.field({id:e.sha,name:e.subject,parentNodeId:n,rank:String(t).padStart(6,"0"),childRenderAxis:"vertical",isVirtual:!0}),VC=(e,t)=>{let n=C.getNode(WC(e.id));if(!n||!it(n))return[];let r=t.map((o,s)=>GC(o,s,n.id)).map(o=>C.createNode(o)).filter(ye).map(({value:o})=>o).filter(it);return t.length>0&&v().selectedIndex<0&&v().contextNode.id===n.id&&U.navigate({contextNode:n,selectedIndex:0}),r},zC=e=>`+${e.insertions} -${e.deletions}`;function ly({ticket:e,width:t,height:n}){let[r,o]=HC({state:"loading"}),s=H(e.id);iy(()=>{let x=!0;return o({state:"loading"}),Kn({ref:s}).then(b=>{x&&o(a(b)?{state:"failed",message:b.message}:{state:"loaded",commits:b.value})}),()=>{x=!1}},[s]);let i=jC([]),l=r.state==="loaded"?r.commits:null;iy(()=>(ay(i.current),i.current=l?VC(e,l):[],()=>{ay(i.current),i.current=[]}),[e,l]);let{selectedIndex:d,contextNode:m}=te(),p=l?.find(x=>x.sha===m.id)??null,g=Math.max(1,n-4),h=Math.max(12,t-34);return r.state!=="loaded"?Xe.createElement(zr,{flexDirection:"column",width:t,height:n,padding:1},Xe.createElement(wn,{color:y.primary},r.state==="loading"?"Reading commits\u2026":`Could not read commits: ${r.message}`)):p?Xe.createElement(sy,{ticket:e,sha:p.sha,subject:p.subject,width:t,height:n}):r.commits.length===0?Xe.createElement(zr,{flexDirection:"column",width:t,height:n,padding:1},Xe.createElement(wn,{color:y.primary},"No commits reference this ticket."),Xe.createElement(zr,{paddingTop:1},Xe.createElement(wn,{color:y.primary},"Commits are matched by the"),Xe.createElement(wn,{color:y.accent},` ${s} `),Xe.createElement(wn,{color:y.primary},"prefix on their subject line."))):Xe.createElement(zr,{flexDirection:"column",width:t,height:n},Xe.createElement(zr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},Xe.createElement(wn,{color:y.secondary2},`Diff (${r.commits.length}) \u2014 enter to read, o to open in your editor `)),Xe.createElement(dt,{height:g,itemHeight:2,selectedIndex:d},r.commits.map((x,b)=>{let N=b===d,S=x.subject.length>h?x.subject.slice(0,h-1)+"\u2026":x.subject;return Xe.createElement(zr,{key:x.sha,flexDirection:"row",paddingX:1,paddingBottom:1},Xe.createElement(wn,{color:y.accent},N?"\u276F ":" "),Xe.createElement(zr,{paddingLeft:1},Xe.createElement(wn,{color:y.secondary2},`${x.sha.slice(0,7)} `),Xe.createElement(wn,{color:N?y.accent:y.primary},S),Xe.createElement(wn,{color:y.secondary2},` ${zC(x)} ${fr(x.time)}`)))})))}import{Box as Ya,Text as KC}from"ink";import Yn from"react";var cy=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=te(),{title:o}=t,s=t.parentNodeId?C.getNode(t.parentNodeId):void 0,i=s&&_(s)?o===Ne.ASSIGNEES?s.props.assignees??[]:o===Ne.TAGS?(s.props.tags??[]).filter(l=>C.getTag(l)):[]:[];return Yn.createElement(Ya,{alignItems:"center",paddingTop:1},Yn.createElement(Ya,{minWidth:12},Yn.createElement(St,{isSelected:n}),Yn.createElement(KC,{color:n?y.accent:y.secondary2},o,":")),Yn.createElement(Ya,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((l,d)=>{let m=r.id===t.id&&d===e;return Yn.createElement(Ya,{key:`${o}-${l}`,paddingRight:2,minHeight:1},Yn.createElement(St,{isSelected:m}),o===Ne.ASSIGNEES?Yn.createElement(mr,{isSelected:m,id:l}):o===Ne.TAGS?Yn.createElement(ko,{isSelected:m,id:l}):null)})))};import{Box as Wo,Text as Xd}from"ink";import Ht,{useEffect as qC,useMemo as Jd,useRef as YC}from"react";var qd=e=>Math.max(5,String(Math.max(e,1)).length+3),dy=(e,t)=>Math.max(0,e-6-qd(t));var Yd=(e,t=0,n=0)=>Math.max(1,e-5-2*t-(n>0?1+n:0));var XC="\u2029",uy=(e,t)=>`${e}::inline-line::${t}`,Qd=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:l}=te(),d=Jd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Jd(()=>d.join("\0"),[d]),p=YC([]);qC(()=>(Ho(p.current),p.current=Va(e,d.length,b=>uy(e,b)),()=>{Ho(p.current),p.current=[]}),[e,m]);let f=qd(d.length),g=dy(s,d.length),x=Jd(()=>Td(d).map(b=>{if(b.kind==="code"||b.kind==="caption")return{...b,text:$n(b.text,g)};if(b.kind==="text"||b.kind==="heading"){let N=b.spans.map(S=>S.code?`\`${S.text}\``:S.text).join("");return{...b,spans:qs($n(N,g))}}return b}),[d,g]).map((b,N)=>{let S=l.id===e&&i===N;return Ht.createElement(Wo,{key:uy(e,N)},Ht.createElement(Wo,{flexShrink:0},Ht.createElement(Xd,{color:S?y.primary:y.secondary2,dimColor:!S},`${N+1} `.padStart(f,"\xA0"))),b.kind==="blank"?Ht.createElement(Xd,{backgroundColor:S?"gray":void 0},XC):Ht.createElement(Wo,null,Ht.createElement(wd,{line:b,width:b.kind==="code"?g:0,wrap:"truncate-end"})))});return Ht.createElement(Wo,{flexDirection:"column",paddingTop:1},Ht.createElement(Wo,null,Ht.createElement(St,{isSelected:o}),Ht.createElement(Xd,{color:o?y.accent:y.secondary2},t)),Ht.createElement(Wo,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},Ht.createElement(dt,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},x)))};var QC=e=>we(e,"description"),ZC=e=>we(e,"comments"),eN=e=>we(e,"history"),tN=e=>we(e,"diff"),nN=e=>we(e,"attachments"),my=({ticket:e,height:t})=>{let n=Vo(()=>uh(e),[e]),{selectedIndex:r,contextNode:o}=te(),s=process.stdout.columns||120,i=Vo(()=>QC(e.id),[e.id]),l=Vo(()=>ZC(e.id),[e.id]),d=Vo(()=>eN(e.id),[e.id]),m=Vo(()=>tN(e.id),[e.id]),p=Vo(()=>nN(e.id),[e.id]),f=C.getAttachmentsByIssue(e.id).length,g=o.id===e.id,h=o.id===l||o.parentNodeId===l,x=o.id===d||o.parentNodeId===d,b=o.id===p||o.parentNodeId===p,N=o.id===m||o.parentNodeId===m,S=ae(e.id);if(h){let X=t-3;return Ct.createElement(Go,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ct.createElement(kh,{ticket:e,width:s,height:X}))}if(b){let X=t-3;return Ct.createElement(Go,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ct.createElement(hh,{ticket:e,width:s,height:X}))}if(N){let X=t-3;return Ct.createElement(Go,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ct.createElement(ly,{ticket:e,width:s,height:X}))}if(x){let F=C.getNode(d),X=F&&it(F)?F.props.value??"":"",Ve=Yd(t);return Ct.createElement(Go,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},F?Ct.createElement(Qd,{id:F.id,label:"Event log",text:X,selected:!1,maxWidth:s,rows:Ve}):null)}let A=[d,m,l,p],T=F=>A.includes(F),P=S.reduce((F,X)=>bs(X)?F+1:F,0),M=S.reduce((F,X)=>T(X.id)?F+1:F,0),O=S.findIndex(F=>T(F.id)),W=Yd(t,P,M),Y=(F,X,Ve,Qn)=>Ct.createElement(Go,{key:F.id,paddingTop:X===O?1:0},Ct.createElement(St,{isSelected:Ve}),Ct.createElement(JC,{backgroundColor:y.secondary,color:Ve?y.accent:y.primary},Qn)),xe=(F,X,Ve)=>F.id===i?Ct.createElement(Qd,{key:F.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:X,maxWidth:s,rows:W}):bs(F)?Ct.createElement(cy,{key:F.id,parent:F,selected:X,selectedIndex:r}):F.id===l?Y(F,Ve,X,` Comments (${n}) \u203A\u203A `):F.id===p?Y(F,Ve,X,` Attachments (${f}) \u203A\u203A `):F.id===d?Y(F,Ve,X," History \u203A\u203A "):F.id===m?Y(F,Ve,X," Diff \u203A\u203A "):null;return Ct.createElement(Go,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},S.map((F,X)=>xe(F,g&&r===X,X)))};var oN=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:l})=>{let d=t.context,m=d===re.TICKET||d===re.FIELD_LIST||d===re.FIELD,p=d===re.BOARD||d===re.SWIMLANE,f=d===re.TICKET?t:r.find(N=>N.context===re.TICKET),g=Math.floor(l/3),h=Math.floor(l/Math.max(e.length,1)),x=Math.min(h,g),b=s==="dense";return Xa.createElement(rN,{flexDirection:"row",height:i},p&&e.map((N,S)=>{let A=t.id===N.id,T=A?n:-1,P=t.context===re.BOARD&&n===S;return Xa.createElement(dh,{key:N.id,height:i,width:x,swimlane:N,isSelected:P,isDense:b,isFocused:A,listSelectedIndex:T,mode:o})}),m&&f&&Xa.createElement(my,{height:i,ticket:f}))},Ja=Xa.memo(oN);import{render as aN}from"ink";import{Writable as lN}from"node:stream";var Qs=e=>String(e).padStart(2,"0"),cN=e=>{let t=e.getUTCFullYear(),n=Qs(e.getUTCMonth()+1),r=Qs(e.getUTCDate()),o=Qs(e.getUTCHours()),s=Qs(e.getUTCMinutes()),i=Qs(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},dN=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",uN=async(e,{width:t,height:n})=>{let r="",o=new lN({write(i,l,d){let m=mN(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),d()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=aN(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},mN=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),fy=async()=>{let{viewMode:e}=V(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=v(),i=r.find(S=>S.context==="BOARD");if(!i)return c("No board found to export");let l=120,d=40,m=await uN(iN.createElement(Ja,{height:d,width:l,swimlanes:(s[i.id]??[]).filter(S=>S!==void 0&&hn(S)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:d});if(!m)return c("Failed to render board export");let p=Fi(process.cwd());if(a(p))return c("Unable to export, epiq root not found");let f=new Date,g=cN(f),h=`board_${dN(i.title)}_${g}.md`,x=Ym(p.value);py.mkdirSync(x,{recursive:!0});let b=sN.join(x,h),N=`# Board - ${i.title}
|
|
82
82
|
Date: ${f.toISOString()}
|
|
83
83
|
|
|
84
84
|
\`\`\`text
|
|
85
85
|
${m}
|
|
86
86
|
\`\`\`
|
|
87
|
-
`;return
|
|
87
|
+
`;return py.writeFileSync(b,N,"utf8"),u("Exported board layout",b)};import{useSyncExternalStore as DW}from"react";var Qa,pN=new Set,gy=()=>{for(let e of pN)e()};var vr=()=>{if(!Qa)throw new Error("Ui state not initialized. Call initUiState() first.");return Qa};var hy=(e={})=>(Qa=e,gy(),u("UX state initialized",null)),fN=e=>{let t=vr();return Qa=e(t),gy(),u("UX state updated",null)},br=e=>fN(t=>({...t,...e}));import{ulid as Zd}from"ulid";var yy=async e=>{let{contextNode:t,selectedIndex:n}=v(),r=ae(t.id)[n];if(e.modifier===Pt.DESCRIPTION)return hN();if(r&&xs(r))return gN(e);if(e.modifier===Pt.TITLE){let o=ue();if(a(o))return c("Unable to resolve user ID");let s=r;if(!s)return c("Missing node");if(s.readonly)return c("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return c("Provide a title");let l=await Ie();return a(l)?l:B([{id:Zd(),action:"edit.title",payload:{id:s.id,name:i},...D(o.value)}],l.value)}return c("Unknown edit command")},gN=async e=>{let t=ue();if(a(t))return c("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=v(),o=ae(n.id)[r];if(!o||!xs(o))return c("Select a comment first");if(o.readonly)return c("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return c("Unable to resolve comment issue");let i=v().nodes[s];if(!i||!_(i))return c("Unable to resolve comment issue");if(i.readonly)return c("Cannot edit readonly issue");let l=o.id.split(":").at(0)??"",d=C.getComment(l);if(!d||d.deleted)return c("Unable to resolve comment");if(d.issue!==i.id)return c("Comment does not belong to selected issue");if(d.authorId!==t.value.userId)return c("You can only edit your own comments"+d.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return c("Provide a comment");let p=await Ie();if(a(p))return p;let f=p.value;return B([{id:Zd(),action:"edit.issue.comment",payload:{id:d.id,issue:i.id,md:m},...D(t.value)}],f)},hN=async()=>{let e=ue();if(a(e))return c("Unable to resolve user ID");let t=await Ie();if(a(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=v(),s=ht([...r,o],"TICKET");if(a(s))return c("Edit target must be an issue");let i=s.value;if(!_(i))return c("Edit target must be an issue");if(i.readonly)return c("Cannot edit readonly issue");let l=ae(i.id).find(f=>f.title===Ne.DESCRIPTION);if(!l)return c("No target found");if(l.readonly)return c("Cannot edit readonly field");let d=i.props.description??"";if(typeof d!="string")return c("Selected field is not editable text");let m=Yh(d);if(a(m))return c("Failed to edit field");let p=m.value;return p===d?u("No changes made",null):B([{id:Zd(),action:"edit.description",payload:{id:i.id,md:p},...D(e.value)}],n)};import vN from"node:fs";import tu from"node:path";import eu from"node:fs";import yN from"node:path";var vy=async e=>{let t=yN.join(e,".gitignore"),n=eu.existsSync(t)?eu.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
88
88
|
`).map(d=>d.trim()),s=r.filter(d=>!o.some(m=>m===d||m===d.replace(/\/$/,"")||m==="/"+d||m==="/"+d.replace(/\/$/,"")));if(s.length===0)return u("Local epiq paths already ignored",!1);let l=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
89
89
|
`);return n=n.trimEnd()+`
|
|
90
90
|
|
|
91
91
|
${l}
|
|
92
|
-
`,
|
|
93
|
-
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},
|
|
94
|
-
`));let o;try{o=JSON.parse(r.value.stdout)}catch(x){return
|
|
95
|
-
`));let d=
|
|
96
|
-
`,"utf8"),ti.renameSync(p,s)}catch(f){try{ti.rmSync(p,{force:!0})}catch{}return c(`Unable to write ${ni}: ${f instanceof Error?f.message:String(f)}`)}return u("Stored command history",null)};var TN=e=>e.some(t=>t.action==="init.workspace"),Ny=async(e,t)=>{let n=Ue(e);return a(n)?c(n.message):ls({cwd:t,branch:n.value})},wN=e=>{let t=me(process.cwd());if(a(t))return!1;let n=he({repoRoot:t.value});return!a(n)&&n.value===e},el=async e=>{let t=he({repoRoot:e});if(a(t))return tn(3,t.message);let n=t.value,r=await dr({repoRoot:e,stateBranchRoot:n,stateBranchName:Bi().stateBranch});if(a(r))return tn(3,r.message);let o=Zt(n);if(a(o))return tn(3,o.message);if(!TN(o.value.events)){let p=await Hs({worktreeRoot:n,operation:"boot pull",fn:()=>Ta(n,()=>Ny(e,n))});if(a(p)?logger.info(3,p.message):p.value===null?logger.info(3,"Another process holds the state worktree, skipped pull"):a(p.value)&&logger.info(3,p.value.message),o=Zt(n),a(o))return tn(3,o.message)}let{events:s,unreadable:i}=o.value,l=en(s,i);if(a(l))return tn(4,l.message);w({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let d=Ji({root:e});a(d)&&logger.info(d.message);let m=Ry({root:e});return a(m)&&logger.info(m.message),mf(a(m)?[]:m.value),u("Loaded project",void 0)},MN=async e=>{let t=he({repoRoot:e});if(a(t))return c(t.message);let n=t.value,r=await Bn({repoRoot:n});if(a(r))return c(r.message);if(!r.value)return u("No remote to pull",void 0);let o=await Hs({worktreeRoot:n,operation:"boot pull",fn:()=>Ta(n,()=>(To("Pulling"),Ny(e,n)))});if(a(o))return Ve(o.message);if(o.value===null)return u("Another process holds the state worktree",void 0);let s=o.value;if(a(s))return as(s.message)?(Ca("Offline"),u("Offline",void 0)):Ve(s.message);if(!s.value)return jr("Already synced"),u("Already synced",void 0);if(!wN(n))return u("Project changed during the pull",void 0);let i=gd(n);return a(i)?i:(jr("Pulled"),u("Pulled and reloaded",void 0))},tl=e=>{MN(e).then(t=>{a(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${wo(t)}`)})},Ay=()=>{let e=en([]);return a(e)?tn(4,e.message):(w({hasProjectDefinition:!1,hasInitializingEvents:!1}),u("Booted without a project",void 0))};var LN=e=>e==="~"||e.startsWith("~/")?Ty.join(PN.homedir(),e.slice(1)):e,kN=(e,t)=>{let n=e.trim();if(!n)return c("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):c(`No recent project #${n}`)}let r=me(Ty.resolve(LN(n)));return a(r)?c(`No epiq project at ${n}`):u("Resolved project path",r.value)},wy=async()=>{let e=aa();if(Q(""),v().hasProjectDefinition)return c("Already in a project; run epiq from another directory");let t=$n({exclude:process.cwd()}),n=a(t)?[]:t.value,r=kN(e,n);if(a(r))return c(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(l){return c(`Unable to enter ${o}: ${l instanceof Error?l.message:String(l)}`)}let i=await el(o);return a(i)?(process.chdir(s),c(i.message)):(tl(o),u(`Opened ${Io(o)}`,null))};var nl=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=v(),s=ba(n,t);if(a(s))return c(s.message);let{appliedEvents:i,unappliedEvents:l}=s.value,d=sn();if(a(d))return d;let m=Qt(i),{fatal:p,skipped:f}=In(m);if(p.length>0)return sn(),w(o),c(p.map(y=>y.message).join(", "));En(f);let g=v().nodes[e];return g?(U.navigate({contextNode:g,selectedIndex:r}),u("",{unappliedEvents:l})):(sn(),w(o),c("Board did not exist at that date"))};var My=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 DN=20,BN=16,ON=150,rl=null,ol=null;var Kr=()=>{rl!==null&&(clearInterval(rl),rl=null),ol!==null&&(clearTimeout(ol),ol=null)},Py=()=>{Kr(),w({mode:I.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Ly=({events:e,startTime:t,durationMs:n})=>{Kr();let r=e.length,o=ho(e.map(f=>er(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=My(o),l=Math.max(1,Math.round(n*DN/1e3)),d=Math.max(Math.round(n/l),BN),m=0,p=0;w({mode:I.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),rl=setInterval(()=>{m++;let f=m/l,g=[],y,x;for(;p<r&&i[p]<=f;){let R=e[p],S=Os(R);if(a(S)){if(Ao(S)){p++;continue}Py();return}g.push(...od(R)),y=R,x=o[p],p++}if(p>=r||m>=l){for(;p<r;p++){let S=Os(e[p]);if(a(S)&&!Ao(S))break}let R=v().replay;w({unappliedEvents:[],replay:R&&{...R,progress:1,appliedCount:r}}),Kr(),ol=setTimeout(Py,ON);return}let b=v().replay;w({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:y?x??b?.currentTime??t:b?.currentTime??t,currentLabel:y?sl(y):b?.currentLabel??"",flashNodeIds:y?[...new Set(g)]:b?.flashNodeIds??[]}})},d)};var ky=async()=>{let e=yt(v().breadCrumb,"BOARD");if(a(e))return e;let t=await qt(process.cwd());if(a(t))return c("Unable to locate repo root");let n=he({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=ae().commandMeta;if(Kr(),r==="now"){let l=cr(n.value);if(a(l))return c(l.message);let d=sn();if(a(d))return d;let m=Qt(l.value),{fatal:p,skipped:f}=In(m);return p.length>0?c(p.map(g=>g.message).join(", ")):(En(f),w({mode:I.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),u("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let l=xa(n.value);if(a(l))return l;let d=r==="prev"?v().eventLog.at(-1):v().unappliedEvents.at(0),m=d===void 0?null:er(d),p=(d===void 0?null:l.value.get(d.id)??null)??(m===null?null:gs(m));if(p===null)return c(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?p:p+1}else{let l=Lr(r||o.trim());if(!l)return c("Invalid peek date");s=l.getTime()}let i=nl({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(i)?i:(w({mode:I.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),u("Peeking",!0))};var Dy=async()=>{let e=yt(v().breadCrumb,"BOARD");if(a(e))return e;let t=await qt(process.cwd());if(a(t))return c("Unable to locate repo root");let n=he({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=ae().commandMeta,{dateInput:s,durationInput:i}=na(r,o);if(Kr(),v().syncStatus.status==="syncing")return c("Cannot replay while syncing, try again in a moment");let l=Lr(s);if(!l)return c("Invalid replay date");let d=i?ta(i):15e3;if(d===null)return c("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=v(),f=nl({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(f))return f;let{unappliedEvents:g}=f.value;return g.length===0?(sn(),w(p),u("Nothing to replay from that point",!0)):(Ly({events:g,startTime:m,durationMs:d}),u("Replaying board history",!0))};import{spawn as _N}from"node:child_process";var $N=()=>{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"]}}},By=async e=>new Promise(t=>{let{command:n,args:r}=$N();try{let o=_N(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(c(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?u("Copied to clipboard",null):c(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(c(`Clipboard tool not available (${n})`))}});var ri=async(e,t)=>{if(!e.trim())return c(`Nothing to copy: ${t} is empty`);let n=await By(e);return a(n)?n:u(`Copied ${t} to clipboard`,null)},Oy=async e=>{let{breadCrumb:t,selectedNode:n}=v(),r=Es({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return c("Nothing selected to copy from");switch(e.modifier){case Xe.REF:return ri(H(o.id),"ref");case Xe.TITLE:return ri(o.title,"title");case Xe.DESCRIPTION:return r?ri(r.props?.description??"","description"):c("No issue in scope");case Xe.TAGS:{if(!r)return c("No issue in scope");let s=hn(r).map(({name:i})=>i);return ri(s.join(", "),"tags")}case Xe.ASSIGNEES:{if(!r)return c("No issue in scope");let s=yn(r).map(({name:i})=>i);return ri(s.join(", "),"assignees")}default:return c("Yank one of: ref, title, description, tags, assignees")}};var Fy=async()=>{Q(""),w({mode:I.DEFAULT});let e=xe();if(a(e))return c(e.message);if(e.value.syncStatus.status==="syncing")return c("Sync already in progress");w({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Ma();return a(t)?(w({syncStatus:{msg:t.message,status:"failed"}}),t):(w({mode:I.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{ulid as _y}from"ulid";var $y=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=de(t.id)[n];if(!r)return c("Unable to resolve child to delete");let o=await Se();if(a(o))return o;if(r.context==="COMMENT"){let s=r.id,i=_(t)?t.id:t.parentNodeId;if(!i)return c("Unable to resolve comment issue");let l=v().nodes[i];if(!l||!_(l))return c("Unable to resolve comment issue");let d=l.log?.filter(ah).find(m=>m.payload.id===s);return d?d.payload.author!==e.value.userId?c("You can only delete your own comments"):B([{id:_y(),action:"delete.issue.comment",payload:{id:s,issue:i},...D(e.value)}],o.value):c("Unable to resolve comment")}return B([{id:_y(),action:"delete.node",payload:{id:r.id},...D(e.value)}],o.value)};import{ulid as UN}from"ulid";var Uy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=de(t.id)[n];if(!r)return c("Unable to close issue, no target found");if(!_(r))return c("Cannot close in this context");let o=v().nodes[ye];if(!o)return c("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return c("Issue is already closed");let s=await Se();if(a(s))return s;let i=s.value,l=Sn(o.id,r.id,{at:"end"},e.value,i);if(a(l))return l;let d=B([{id:UN(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...D(e.value)}],i);return a(d)?d:u("Issue closed",null)};import{ulid as jN}from"ulid";var il=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 jy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=de(t.id)[n];if(!r)return c("Unable to reopen issue, no target found");let o=r.context==="TICKET"?u("Resolved ticket",r):Nt(r.id,"TICKET");if(a(o))return c("Cannot reopen in this context");let s=o.value,i=v().nodes[ye];if(!i)return c("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return c("Issue is not closed");if(!_(s))return c("Target node is not issue");let l=il(s);if(!l)return c("Unable to resolve previous parent from issue history");if(l===i.id)return c("Previous parent resolves to closed swimlane");let d=v().nodes[l];if(!d)return c("Previous parent no longer exists");let m=await Se();if(a(m))return m;let p=m.value,f=Sn(d.id,s.id,{at:"end"},e.value,p);if(a(f))return f;let g=B([{id:jN(),action:"reopen.issue",payload:{id:s.id,parent:d.id,rank:f.value},...D(e.value)}],p);return a(g)?g:u("Issue reopened",null)};import{ulid as HN}from"ulid";var Hy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=de(t.id)[n];if(!r)return c("Missing node");if(r.readonly)return c("Cannot rename readonly node");let o=aa();if(!o)return c("Provide a title");let s=await Se();return a(s)?s:B([{id:HN(),action:"edit.title",payload:{id:r.id,name:o},...D(e.value)}],s.value)};import{ulid as WN}from"ulid";var Wy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=ae().commandMeta,r=(t||n).trim();if(!r)return c("Provide a tag");let o=N.findTagByName(r);if(!o)return c(`Tag "${r}" does not exist`);let{selectedNode:s}=v();if(!s)return c("Invalid untag target");let i=Nt(s.id,"TICKET");if(a(i))return c("Unable to untag issue in this context");let l=i.value;if(!_(l))return c("Target node is not issue");if(!(l.props.tags??[]).includes(o.id))return c("Issue is not tagged with that tag");let m=await Se();return a(m)?m:B([{id:WN(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...D(e.value)}],m.value)};import{ulid as eu}from"ulid";var Gy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=ae().commandMeta,r=(t||n).trim();if(!r)return c("Provide a tag");let{selectedNode:o}=v();if(!o)return c("Invalid tag target");let s=Nt(o.id,"TICKET");if(a(s))return c("Unable to tag issue in this context");let i=s.value;if(!_(i))return c("Target node is not issue");let l=await Se();if(a(l))return l;let d=N.findTagByName(r),m=d?.id??eu();return(i.props.tags??[]).includes(m)?c("Already tagged with that tag"):B([...d?[]:[{id:eu(),action:"create.tag",payload:{id:m,name:r},...D(e.value)}],{id:eu(),action:"add.issue.tag",payload:{id:i.id,tag:m},...D(e.value)}],l.value)};import{ulid as tu}from"ulid";var oi=({events:e,registry:t,logFileNames:n})=>{let r=new Map(n),o=new Set;for(let s of e)s.userId&&(r.has(s.userId)||r.set(s.userId,""),o.add(s.userId));for(let s of Object.values(t))r.set(s.id,s.name);return[...r.entries()].map(([s,i])=>({id:s,name:i,isExternal:!o.has(s)}))},Vy=({authorName:e,authorEmail:t,owners:n,registry:r})=>{let o=et(t),s=n.get(o),i=s?r[s]:void 0;return s?{...Ye(s,i?.name),resolved:!0}:{...Ye(o||e,e),resolved:!1}};var al=e=>{let{eventLog:t=[],contributors:n}=v();return oi({events:t,registry:n,logFileNames:lr(e)})};var zy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=ae().commandMeta,r=(t||n).trim();if(!r)return c("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return c("Provide an assignee");let{selectedIndex:i,contextNode:l}=v(),d=de(l.id)[i];if(!d)return c("Invalid assign target");let m=Nt(d.id,"TICKET");if(a(m))return c("Unable to assign issue in this context");let p=m.value;if(!_(p))return c("Target node is not issue");let f=await Se();if(a(f))return f;let g=al(f.value),y=!o&&s.toLowerCase()==="me",x,b;if(y)x=e.value.userId,b=g.find(T=>T.id===x)?.name??e.value.userName;else{let T=g.filter(P=>P.name===s);if(T.length>1)return c(`"${s}" matches ${T.length} contributors (${T.map(P=>P.id).join(", ")}). Assign from the GUI to choose by id.`);let A=T[0];if(!A&&!o)return c(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);x=A?.id??tu(),b=A?.name??s}if((p.props.assignees??[]).includes(x))return c("Assignee already assigned");let S=!!v().contributors[x];return B([...S?[]:[{id:tu(),action:"create.contributor",payload:{id:x,name:b},...D(e.value)}],{id:tu(),action:"add.issue.assignee",payload:{id:p.id,assignee:x},...D(e.value)}],f.value)};import{ulid as GN}from"ulid";var Ky=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=ae().commandMeta,r=(t||n).trim();if(!r)return c("Provide an assignee to remove");let{selectedNode:o}=v();if(!o)return c("Invalid unassign target");let s=Nt(o.id,"TICKET");if(a(s))return c("Unable to unassign in this context");let i=s.value;if(!_(i))return c("Target node is not issue");let l=i.props.assignees??[],d=r.toLowerCase()==="me",m=await Se();if(a(m))return m;let p=d?l.filter(g=>g===e.value.userId):al(m.value).filter(g=>g.name===r&&l.includes(g.id)).map(g=>g.id);if(p.length>1)return c(`"${r}" matches ${p.length} assignees (${p.join(", ")}). Unassign from the GUI to choose by id.`);let f=p[0];return f?B([{id:GN(),action:"remove.issue.assignee",payload:{id:i.id,assignee:f},...D(e.value)}],m.value):c(d?"Issue is not assigned to you":`Issue is not assigned to "${r}"`)};import{ulid as qy}from"ulid";var VN=e=>{let t=e.trim(),n=hr(),r=n?Fh(t):null;if(!n||!r)return{ok:!0,md:t,anchored:!1};let o=Ka();if(!o||o.sha!==n)return{ok:!1,reason:"No diff is open"};let s=_h(o.rows,Math.max(0,v().selectedIndex));if(!s)return{ok:!1,reason:"That line is not in a file"};let i=$h(o.rows,s,r.start,r.end);return i.ok?{ok:!0,anchored:!0,md:yh({filePath:i.value.filePath,start:i.value.start,end:i.value.end,side:"additions",endSide:"additions",note:r.note,sha:n,snippet:i.value.snippet})}:{ok:!1,reason:i.reason}},Yy=async e=>{let t=VN(e.inputString);if(!t.ok)return c(t.reason);let{md:n,anchored:r}=t;if(!n)return c("Provide a comment");if(n.length>4e3)return c(r?`The note and the ${n.length} characters of quoted lines exceed ${4e3}; comment on fewer lines`:`Cannot exceed ${4e3} characters`);let o=pe();if(a(o))return c("Unable to resolve user ID");let{breadCrumb:s,selectedNode:i}=v(),l=yt([...s,i],"TICKET");if(a(l))return c("Edit target must be an issue");let d=l.value;if(!d)return c("Invalid comment target");let m=d.context==="TICKET"?u("Resolved ticket",d):Nt(d.id,"TICKET");if(a(m))return c("Unable to comment on issue in this context");let p=m.value;if(!_(p))return c("Target node is not issue");let f=await Se();if(a(f))return f;let g=await B([{id:qy(),action:"add.issue.comment",payload:{id:qy(),issue:p.id,author:o.value.userId,md:n},...D(o.value)}],f.value);return r&&!a(g)&&Gr(null),g};import{ulid as JN}from"ulid";var ll=e=>e.userName?.trim()?e.preferredEditor?.trim()?null:"no editor configured":"no username configured",zN=e=>{let t=ht();return a(t)?ll({userName:e.userName,preferredEditor:e.preferredEditor})??t.message:ll(t.value)},si=()=>{let e=pn();return a(e)?c(e.message):u("Read auto sync settings",{enabled:e.value.autoSync===!0,intervalMs:uo(e.value.autoSyncDebounceMs),blockedReason:zN(e.value)})},zo=e=>{let t=e.intervalMs===void 0?void 0:co(e.intervalMs);if(e.intervalMs!==void 0&&t===null)return c(`Auto sync interval must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=si();if(a(n))return n;let r=Bt({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncDebounceMs:t}});if(a(r))return c(r.message);je({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncIntervalMs:t}});let o=si();return a(o)?u("Changed auto sync settings",{...n.value,...e.enabled===void 0?{}:{enabled:e.enabled},...t==null?{}:{intervalMs:t}}):o};var Xy=()=>{let e=ae().commandMeta.inputString,t=co(e);if(t===null)return c(`Auto sync duration must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=zo({intervalMs:t});return a(n)?n:u(`Auto sync interval set to ${t}ms`,null)};var Jy=()=>{let e=ae().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return c("Invalid response");let t=Lp(e),n=zo({enabled:t===!0});return a(n)?n:u(`Auto sync set to "${e}"`,null)};import{ulid as YN}from"ulid";var nu=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=2),Qy="",Zy=new Map,KN=15e3;var qN=async(e,t)=>{let n=`${e} ${t??""}`,r=Zy.get(n);if(r&&Date.now()-r.at<_a(KN))return u("Cached author scan",r.authors);let o=await De({cwd:e,args:["log","--branches",...t?["--not",t]:[],`--format=%an${Qy}%ae`]});if(o.exitCode!==0)return c(`Could not read this repository's history: ${(o.stderr??"").trim()||`git exited ${o.exitCode}`}`);let s=new Map;for(let i of(o.stdout??"").split(`
|
|
97
|
-
`)){let l=i.lastIndexOf(Qy);if(l===-1)continue;let d=i.slice(0,l),m=et(i.slice(l+1));if(!tr(m))continue;let p=s.get(m)??{names:new Set,commits:0};d&&p.names.add(d),p.commits+=1,s.set(m,p)}return Zy.set(n,{at:Date.now(),authors:s}),u("Scanned repository authors",s)},wn=async({repoRoot:e,stateBranch:t,names:n,links:r})=>{let o=await qN(e,t);if(a(o))return c(o.message);let s=o.value,i=new Map;for(let d of Object.values(r)){if(d.tombstoned)continue;let m=i.get(d.email)??new Set;m.add(d.contributor),i.set(d.email,m)}let l=new Set(n.flatMap(d=>nu(d??"")));return u("Found candidates",[...s.entries()].map(([d,m])=>({email:d,names:[...m.names],commits:m.commits,looksLikeYours:[...m.names].some(p=>nu(p).some(f=>l.has(f)))||nu(d.split("@")[0]??"").some(p=>l.has(p)),claimedBy:[...i.get(d)??[]]})).sort((d,m)=>d.looksLikeYours===m.looksLikeYours?m.commits-d.commits:Number(m.looksLikeYours)-Number(d.looksLikeYours)))},br=e=>e.filter(t=>t.claimedBy.length===0);var ev=()=>{let e=Tc();if(!e)return u("Nothing here to decline",null);let t=pn(),n=a(t)?[]:t.value.declinedEmailBoards??[],r=[...new Set([...n,e])],o=Bt({declinedEmailBoards:r});return a(o)?c(o.message):(je({declinedEmailBoards:[...new Set([...V().declinedEmailBoards??[],e])]}),u("Declined",null))},tv=async()=>{let e=ae().commandMeta.inputString.trim();if(e==="none"){let R=ev();return a(R)?R:u("Left unlinked. Your commits will show the name git signed them with. Run :config emails again to change that.",null)}let{userId:t,userName:n,gitName:r}=V();if(!t)return c("Set a username first with :config username");let o=xe();if(a(o))return c("Board is not loaded");let s=me(process.cwd());if(a(s))return c(s.message);let i=Ue(s.value),l=await wn({repoRoot:s.value,stateBranch:a(i)?void 0:i.value,names:[n,r],links:o.value.emailLinks});if(a(l))return l;let m=br(l.value);if(Eo(m.map(R=>R.email)),m.length===0){if(!Mp()){let R=ev();if(a(R))return R}return u("No unclaimed addresses in this history.",null)}if(!e)return w({mode:I.IDENTITY}),u("Opened identity",null);let p=e.split(/[,\s]+/).filter(Boolean),f=[],g=[];for(let R of p){let S=m.find(T=>T.email===et(R));if(!S){g.push(R);continue}f.includes(S)||f.push(S)}if(g.length>0)return c(`Not on the list: ${g.join(", ")}. Pick one of ${m.map(R=>R.email).join(", ")}.`);let y=he({repoRoot:s.value});if(a(y))return y;let x=f.map(R=>({id:YN(),action:"link.contributor.email",payload:{contributor:t,email:R.email},userId:t})),b=B(x,y.value);return a(b)?c(b.message):u(`Claimed ${f.map(R=>R.email).join(", ")}. Every commit by ${f.length===1?"that address":"those addresses"} is now yours.`,null)};import{ulid as XN}from"ulid";var nv=()=>{let e=ae().commandMeta.inputString.trim(),{userId:t}=V();if(!t)return c("Set a username first with :config username");let n=xe();if(a(n))return c("Board is not loaded");let r=fn(n.value.emailLinks,t);if(r.length===0)return c("You have not claimed any addresses.");if(!e)return c(`Which one? ${r.join(", ")}.`);let o=r.find(d=>d===et(e));if(!o)return c(`You have not claimed ${e}. Yours: ${r.join(", ")}.`);let s=me(process.cwd());if(a(s))return s;let i=he({repoRoot:s.value});if(a(i))return i;let l=B([{id:XN(),action:"unlink.contributor.email",payload:{contributor:t,email:o},userId:t}],i.value);return a(l)?c(l.message):u(`Unclaimed ${o}`,null)};var rv=()=>{let e=ae().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return c("Invalid response");let n=Bt({logLevel:e});return a(n)?n:(je({logLevel:e}),u(`Auto sync set to "${e}"`,null))};var ov=e=>{let t=e.inputString.trim();switch(e.modifier){case ve.USERNAME:{if(process.env[kn])return c(`Cannot change the configured user while ${kn} names this process`);let n=pn();if(a(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,l=r||JN();if(!i||!l)return c("Unable to resolve user name or id");let d=Bt({userName:i,userId:l,preferredEditor:o??""});return a(d)?d:(je({userName:i,userId:l}),u(`Username set to "${i}"`,null))}case ve.EDITOR:{if(!t)return c("No editor provided");let n=Bt({preferredEditor:t});return a(n)?n:(je({preferredEditor:t}),u(`Editor configuration set to "${t}"`,null))}case ve.VIEW:{if(t!=="wide"&&t!=="dense")return c("Invalid view mode");let n=Bt({viewMode:t});return a(n)?n:(je({viewMode:t}),u(`View set to "${t}"`,null))}case ve.EMAILS:return tv();case ve.EMAILS_UNCLAIM:return nv();case ve.AUTOSYNC:return Jy();case ve.LOG_LEVEL:return rv();case ve.SYNC_DEBOUNCE_MS:return Xy();case ve.ATTACHMENT_MAX_KB:return Kp();default:return c("Unknown config command")}};var ru=()=>{let e=kp(),t=v().mode;if(!(t!==I.COMMAND_LINE&&t!==I.DEFAULT)){if(!e){w({mode:I.DEFAULT});return}w({mode:I.COMMAND_LINE}),Q(e)}};var cl=[{systemOnly:!0,intent:G.Move,description:"Internal move-state command",mode:I.COMMAND_LINE,action:xy},{intent:G.Delete,description:"Delete the currently selected node",mode:I.COMMAND_LINE,action:$y,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:I.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ae().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>Oe(C.FILTER).map(l=>l.split(n)[0]).includes(i))(r))return c("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return Fe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:I.DEFAULT})),u("Filter updated",null)}},{intent:G.ViewHelp,description:"Open the help screen",mode:I.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return vr({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),w({mode:I.HELP}),u("Viewing help",null)}},{intent:G.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:I.COMMAND_LINE,action:Uy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:I.COMMAND_LINE,action:jy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Init,description:"Initialize Epiq in the current git repository",mode:I.COMMAND_LINE,action:fy,onSuccess:ru},{intent:G.OpenProject,description:"Open a recently used epiq project, by number or path",mode:I.COMMAND_LINE,action:wy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.NewItem,description:"Create a new board, swimlane, or issue",mode:I.COMMAND_LINE,action:Iy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Rename,description:"Rename the currently selected node",mode:I.COMMAND_LINE,action:Hy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.UntagTicket,description:"Remove a tag from the selected issue",mode:I.COMMAND_LINE,action:Wy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.TagTicket,description:"Add or create a tag on the selected issue",mode:I.COMMAND_LINE,action:Gy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.AssignUserToTicket,description:"Assign a user to the selected issue",mode:I.COMMAND_LINE,action:zy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:I.COMMAND_LINE,action:Ky,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Comment,description:"Add a comment to the selected issue",mode:I.COMMAND_LINE,action:async(e,t)=>Yy(t),onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Sync,description:"Pull, commit, and push Epiq state",mode:I.COMMAND_LINE,action:Fy},{intent:G.Peek,description:"View board state at another point in time",mode:I.COMMAND_LINE,action:ky},{intent:G.Replay,description:"Replay board history forward from a point in time",mode:I.COMMAND_LINE,action:Dy},{intent:G.Export,description:"Export the current board layout to markdown",mode:I.COMMAND_LINE,action:async()=>{let e=await ly();return a(e)?e:(w({mode:I.DEFAULT}),u("Export successful",!0))}},{intent:G.Exit,description:"Exit the application",mode:I.COMMAND_LINE,action:async()=>(U.exit(),u("Exit successful",!0))},{intent:G.Edit,description:"Edit title or description",mode:I.COMMAND_LINE,action:async(e,t)=>uy(t),onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:I.COMMAND_LINE,action:async(e,t)=>Oy(t),onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:I.COMMAND_LINE,action:(e,t)=>ov(t),onSuccess:ru}];var QN=new Set(["peek","replay","filter","view-help","yank"]),jt=async({isForceExecutedBySystem:e=!1}={})=>{let{value:t,commandMeta:{command:n,validity:r,modifier:o,inputString:s}}=ae();if(!n)return c("No command to confirm");if(!e&&r===bn.Invalid)return c("Invalid command");let i=La(n);df();let{readOnly:l}=v();if(l&&!QN.has(i))return Ts({status:Qn.Fail,message:"Command not available in readonly state",value:null});let d=cl.filter(f=>e||f.systemOnly!==!0).find(f=>f.intent===i);if(!d)return Ts({status:Qn.Fail,message:"Command not found",value:null});let m;try{m=await d.action(d,{command:n,inputString:s,modifier:o})}catch(f){return Ts({status:Qn.Fail,message:f instanceof Error?f.message:"Command failed",value:null})}if(a(m))return Ts(m);let p=!e;if(uf({addToHistory:p,line:t}),p){let f=Cy({commands:ae().commandHistory});a(f)&&logger.info(f.message)}return d.onSuccess?.(),V().autoSync&&Pa(),m};var dl=[{intent:E.Exit,mode:I.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(w({mode:I.COMMAND_LINE}),Q("move cancel"),jt({isForceExecutedBySystem:!0}))},{intent:E.InitMove,mode:I.DEFAULT,description:"[m] move",action:()=>(w({mode:I.COMMAND_LINE}),Q("move start"),jt({isForceExecutedBySystem:!0}))},{intent:E.ConfirmMove,mode:I.MOVE,description:"[m] confirm move",action:()=>(w({mode:I.COMMAND_LINE}),Q("move confirm"),jt({isForceExecutedBySystem:!0}))}],ul=[{intent:E.MovePreviousItem,mode:I.MOVE,action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move previous"),jt({isForceExecutedBySystem:!0})):c("No pending move")},{intent:E.MoveNextItem,mode:I.MOVE,description:"[arrows/hjkl] move (shift x5)",action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move next"),jt({isForceExecutedBySystem:!0})):c("No pending move")},{intent:E.MovePreviousItemJump,mode:I.MOVE,action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move jump-previous"),jt({isForceExecutedBySystem:!0})):c("No pending move")},{intent:E.MoveNextItemJump,mode:I.MOVE,action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move jump-next"),jt({isForceExecutedBySystem:!0})):c("No pending move")}],sv=[{intent:E.MoveToNextContainer,mode:I.MOVE,action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move to-next"),jt({isForceExecutedBySystem:!0})):c("No pending move")},{intent:E.MoveToPreviousContainer,mode:I.MOVE,action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move to-previous"),jt({isForceExecutedBySystem:!0})):c("No pending move")}];var iv={[ie.WORKSPACE]:[...dl,...ul],[ie.BOARD]:[...dl,...ul],[ie.SWIMLANE]:[...dl,...ul,...sv],[ie.TICKET]:[],[ie.FIELD]:[],[ie.FIELD_LIST]:[],[ie.TEXT]:[],[ie.COMMENT]:[]};import eA from"node:fs";import tA from"node:path";import{spawn as ZN}from"node:child_process";function av(e){let t=process.platform,o=ZN(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 lv=e=>{let t=me(process.cwd());if(a(t))return c("Unable to resolve project root");let n=he({repoRoot:t.value});if(a(n))return c(n.message);let r=Br(e.hash,e.ext),o=tA.join(ms(n.value),r);return eA.existsSync(o)?(av(o),u(`Opened ${e.name}`,null)):c("Attachment file not found \u2014 run :sync to fetch it")};var cv=()=>{Q("");let{pendingNavTarget:e}=yr();w({mode:I.DEFAULT}),e&&U.navigate(e),vr({pendingNavTarget:void 0})},dv=[{intent:E.ExitCommandLine,mode:I.HELP,action:()=>(cv(),u("Exiting help",null))},{intent:E.Exit,mode:I.HELP,action:()=>(cv(),u("Closed help",null))},{intent:E.NavPreviousItem,mode:I.HELP,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(U.navigateToPreviousItem(),u("Navigating to previous help item",null))},{intent:E.NavNextItem,mode:I.HELP,action:()=>(U.navigateToNextItem(),u("Navigating to next help item",null))},{intent:E.NavPreviousItemJump,mode:I.HELP,action:()=>(U.jumpToPreviousItem(),u("Jumping to previous help item",null))},{intent:E.NavNextItemJump,mode:I.HELP,action:()=>(U.jumpToNextItem(),u("Jumping to next help item",null))},{intent:E.NavToPreviousContainer,mode:I.HELP,action:()=>(U.navigateToPreviousContainer(),u("Navigating to previous help container",null))},{intent:E.NavToNextContainer,mode:I.HELP,action:()=>(U.navigateToNextContainer(),u("Navigating to next help container",null))}];var uv=()=>{Q(""),w({mode:I.DEFAULT})},mv=[{intent:E.Confirm,mode:I.IDENTITY,description:"[enter] claim the first",action:()=>{let[e]=So();return e?(w({mode:I.COMMAND_LINE}),Q(`config emails ${e}`),u("Proposed claim",null)):u("Nothing left to claim",null)}},{intent:E.ExitCommandLine,mode:I.IDENTITY,action:()=>(uv(),u("Closed identity",null))},{intent:E.Exit,mode:I.IDENTITY,description:"[esc] close",action:()=>(uv(),u("Closed identity",null))}];var nA=e=>{w({mode:I.COMMAND_LINE});let{pendingNavTarget:t}=yr();t&&U.navigate(t),vr({pendingNavTarget:void 0}),Q(`${e} `)},pv=()=>{Q("");let{pendingNavTarget:e}=yr();e&&U.navigate(e),vr({pendingNavTarget:void 0}),w({mode:I.DEFAULT})},fv=[{intent:E.InitCommandPalette,mode:I.DEFAULT,description:"[?] command palette",action:()=>{Q("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return vr({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),w({mode:I.PALETTE}),u("Opening command palette",null)}},{intent:E.Confirm,mode:I.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!nr(e))return c("Command only applicable on text nodes");if(e.props.disabled)return c("Command is not available in this context");let t=e.title;return t?(nA(t),u("Selected command",t)):u("No command selected",null)}},{intent:E.ExitCommandLine,mode:I.PALETTE,action:()=>(pv(),u("Exiting palette",null))},{intent:E.Exit,mode:I.PALETTE,action:()=>(pv(),u("Closed command palette",null))},{intent:E.NavPreviousItem,mode:I.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:E.NavNextItem,mode:I.PALETTE,action:()=>(U.navigateToNextItem(),u("Navigating to next item",null))},{intent:E.NavToPreviousContainer,mode:I.PALETTE,action:()=>(U.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:E.NavToNextContainer,mode:I.PALETTE,action:()=>(U.navigateToNextContainer(),u("Navigating to next container",null))}];var gv=()=>{let e=hr();if(!e)return u("Nothing to comment on here",null);let t=Ka();if(!t||t.sha!==e)return c("The diff is still loading");let{selectedIndex:n}=v(),r=Math.max(0,n),o=kd(t.rows,jd(e)??r,r);return o.ok?(w({mode:I.COMMAND_LINE}),Q(`${C.COMMENT} ${Oh(o.value.start,o.value.end)} `),u("Commenting on a diff line",null)):c(o.reason)},hv=[{intent:E.InitCommandLine,mode:I.DEFAULT,description:"[:] write command",action:()=>(w({mode:I.COMMAND_LINE}),Q(""),u("Entering command line mode",null))},...dv,...mv,...fv,{intent:E.AddItem,mode:I.DEFAULT,description:"[n] new...",action:()=>(w({mode:I.COMMAND_LINE}),Q(`${C.NEW} `),u("Adding new item",null))},{intent:E.Delete,mode:I.DEFAULT,description:"[d] delete",action:()=>(w({mode:I.COMMAND_LINE}),Q(`${C.DELETE} `),u("Deleting item",null))},{intent:E.Confirm,mode:I.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!Ie(e?.id??"")?.length){let r=e?N.getAttachment(e.id):void 0;if(r)return lv(r);if(hr())return gv();if(e?.title===Te.DESCRIPTION)return w({mode:I.COMMAND_LINE}),Q(`${C.EDIT} description `),u("Propose command",!0);if(e?.title===Te.ASSIGNEES)return w({mode:I.COMMAND_LINE}),Q(`${C.ASSIGN} `),u("Propose command",!0);if(e?.title===Te.TAGS)return w({mode:I.COMMAND_LINE}),Q(`${C.TAG} `),u("Propose command",!0);if(t.title===Te.DESCRIPTION&&e?.context==="TEXT")return w({mode:I.COMMAND_LINE}),Q(`${C.EDIT} description `),u("Propose command",!0)}return U.enterChildNode(),u("Entering context",null)}},{intent:E.OpenInEditor,mode:I.DEFAULT,action:()=>{let{selectedNode:e,contextNode:t}=v(),n=t.parentNodeId,o=!!n&&t.id===Pe(n,"diff")?e?.id:hr()??void 0;return o?Xs({sha:o}):u("Nothing here opens in an editor",null)}},{intent:E.MarkDiffLine,mode:I.DEFAULT,action:()=>{let e=hr();if(!e)return u("Nothing to mark here",null);let{selectedIndex:t}=v(),n=jd(e);return Gr(n===t?null:{sha:e,row:Math.max(0,t)}),u("Marked diff line",null)}},{intent:E.CommentOnDiffLine,mode:I.DEFAULT,action:()=>hr()?gv():u("Nothing to comment on here",null)},{intent:E.Yank,mode:I.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=v(),t=e?.title===Te.DESCRIPTION?Xe.DESCRIPTION:e?.title===Te.TAGS?Xe.TAGS:e?.title===Te.ASSIGNEES?Xe.ASSIGNEES:Xe.REF,r=Oe(C.YANK).includes(t)?t:Xe.REF;return w({mode:I.COMMAND_LINE}),Q(`${C.YANK} ${r}`),u("Propose command",!0)}},{intent:E.EditTitle,mode:I.DEFAULT,description:"[r] rename title",action:()=>(w({mode:I.COMMAND_LINE}),Q(`${C.EDIT} title ${v().selectedNode?.title}`),u("Exiting context",null))},{intent:E.EditDescription,mode:I.DEFAULT,description:"[e] edit desc",action:()=>(w({mode:I.COMMAND_LINE}),Q(`${C.EDIT} description `),u("Exiting context",null))},{intent:E.Exit,mode:I.DEFAULT,description:"[q] exit context",action:()=>(U.enterParentNode(),u("Exiting context",null))},{intent:E.NavPreviousItem,mode:I.DEFAULT,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(U.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:E.NavNextItem,mode:I.DEFAULT,action:()=>(U.navigateToNextItem(),u("Navigating to next item",null))},{intent:E.NavPreviousItemJump,mode:I.DEFAULT,action:()=>(U.jumpToPreviousItem(),u("Jumping to previous item",null))},{intent:E.NavNextItemJump,mode:I.DEFAULT,action:()=>(U.jumpToNextItem(),u("Jumping to next item",null))},{intent:E.NavToPreviousContainer,mode:I.DEFAULT,action:()=>(U.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:E.NavToNextContainer,mode:I.DEFAULT,action:()=>(U.navigateToNextContainer(),u("Navigating to next container",null))}];var rA=500,oA=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),yv=e=>{let t=oA(e);t&&ia(n=>(n+t).slice(0,rA))};var sA=[I.COMMAND_LINE,I.PALETTE],iA=e=>e==="edit title "?v().selectedNode?.title??"":"",aA=e=>[{intent:E.MoveCursorLeft,mode:e,action:()=>(Uc(-1),u("Moving cursor left",null))},{intent:E.MoveCursorRight,mode:e,action:()=>(Uc(1),u("Moving cursor right",null))},{intent:E.MoveCursorLeftOfWord,mode:e,action:()=>(jc("left"),u("Moving cursor left of word",null))},{intent:E.MoveCursorRightOfWord,mode:e,action:()=>(jc("right"),u("Moving cursor right of word",null))},{intent:E.AutoCompleteCommand,mode:e,action:()=>(ia((t,{remainder:n})=>{let r=n?t+n:t;return r+iA(r)}),u("Auto-completing command",null))},{intent:E.CaptureInput,mode:e,action:(t,{sequence:n})=>(yv(n??""),u("Capturing input",null))},{intent:E.EraseInput,mode:e,action:()=>(lf(),u("Erasing input",null))},{intent:E.EraseInputWord,mode:e,action:()=>(cf(),u("Erasing input word",null))}],vv=[{intent:E.Confirm,mode:I.COMMAND_LINE,action:()=>(jt(),u("Executing command",null))},{intent:E.ViewHelp,mode:I.DEFAULT,action:()=>(w({mode:I.HELP}),u("Viewing help",null))},...sA.flatMap(aA),{intent:E.ExitCommandLine,mode:I.COMMAND_LINE,action:()=>(pf(),w({mode:I.DEFAULT}),u("Exiting command line",null))},{intent:E.GetLastCommandFromHistory,mode:I.COMMAND_LINE,action:()=>(ff(),u("Getting last command from history",null))},{intent:E.GetNextCommandFromHistory,mode:I.COMMAND_LINE,action:()=>(gf(),u("Getting next command from history",null))}];var ou=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},bv=({keys:e})=>e.length===1?0:1,xv=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(ou).filter(r=>r!==null).sort((r,o)=>bv(r)-bv(o))};function Iv(e,t,n){let r=t[e];if(!r)return c("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?c("buildBreadCrumb(): node is not connected to root"):(o.reverse(),u("Breadcrumb built",o))}var Ev=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 At,su,iu=new Set,au=()=>{for(let e of iu)e()},cA=e=>(iu.add(e),()=>iu.delete(e));function lu(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return c("derive(): contextNodeId is missing");if(!r)return c("derive(): rootNode is missing");if(!o[r])return c("derive(): unable to find root node");let l=o[t];if(!l)return c("Unable to derive state, contextNode not found");let d=Iv(t,o,r);if(a(d))return logger.error(d.message),d;let m=d.value,{context:p}=l,f=[...hv,...iv[p]??[],...vv],g=xv(f,n),y=Ev(f),x=dA(o,s),b=x[t]?.[e.selectedIndex]??null;return u("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:g,availableActions:f,actionIndex:y,selectedNode:b,renderedChildrenIndex:x})}var v=()=>{if(!At)throw new Error("State not initialized. Call initWorkspaceState() first.");return At},xe=()=>At?u("Retrieved state",At):c("State not initialized. Call initWorkspaceState() first.");Np(e=>At?fn(At.emailLinks,e):[]);function Bs(e){su=e;let t=me(process.cwd()),n=!1;if(!a(t)){let s=Tt(t.value);if(a(s))return c(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},emailLinks:{},mode:I.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=lu(r);return a(o)?o:(At=o.value,au(),u("State initialized",null))}var qr=!1,ii=null;function Fe(e){let t=v(),n=e(t);if(qr)return n.nodes!==t.nodes&&(xr=null),ii=n,At={...t,...n},u("State updated",null);let r=lu(n);return a(r)?c(r.message??"Unable to update state"):(At=r.value,au(),u("State updated",null))}function va(e){if(qr)return u("Joined batch",e());qr=!0,ii=null,xr=new Set;let t=()=>{let n=ii;if(qr=!1,ii=null,n===null)return null;let r=lu(n);return a(r)?c(r.message??"Unable to update state"):(At=r.value,au(),u("State updated",null))};try{let n=e(),r=t();return r&&a(r)?c(r.message):u("State updated",n)}finally{qr&&t()}}var hg=()=>qr,w=e=>Fe(t=>({...t,...e}));function Yr(e,t,n){if(!qr)return Fe(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=v(),o=r[e]??{};if(e==="nodes"){let i=o[t],l=n;i?.parentNodeId&&xr?.add(i.parentNodeId),l.parentNodeId&&xr?.add(l.parentNodeId)}o[t]=n;let s={...r,[e]:o};return ii=s,At={...r,...s},u("State updated",null)}var oe=()=>lA(cA,v,v),xr=null,Sv=null,dA=(e,t)=>{let n=At?.renderedChildrenIndex,r=n!==void 0&&xr!==null&&e===Sv&&t.length===0&&At?.filters.length===0,o;if(r){o={...n};let s=mg(e,xr);for(let i of xr){let l=s[i];l?o[i]=l:delete o[i]}}else o=ug(e,t);return Sv=e,xr=new Set,o},de=e=>v()?.renderedChildrenIndex[e]??[],sn=()=>su?Bs(su):c("Cannot reset state: no initial workspace found"),_t=()=>At!==void 0;var Nt=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return c("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 c(`No ancestor found for context: ${t}`)},cu=(e,t)=>{let{nodes:n}=v(),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},Ir=(e,t)=>e?e.readonly?c({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:c("Node not found"),N={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return c("Contributor not found");if(n.userId&&n.userId!==t)return c("Contributor is already linked to another user");let r={...n,userId:t},o=Fe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?c("Unable to link contributor to user"):u("Linked contributor to user",r)},deleteNode(e){N.deleteNodes([e])},deleteNodes(e){e.length!==0&&Fe(t=>{let n={...t.nodes};for(let r of e)delete n[r];return{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return c("Unable to create comment, missing issue");if(!_(t))return c("Can only comment on issues");let n=Yr("comments",e.id,{...e,deleted:!1});return a(n)?c("Unable to create comment"):u("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return c("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return c("Unable to edit comment, missing issue");if(!_(r))return c("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=Yr("comments",e,o);return a(s)?c("Unable to edit comment"):u("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return c("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=Yr("comments",e,n);return a(r)?c("Unable to delete comment"):u("Deleted comment",n)},getComment(e){return v().comments?.[e]},getCommentsByIssue(e){return Object.values(v().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(v().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 c("Unable to create attachment, missing issue");if(!_(t))return c("Can only attach to issues");let n=Fe(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?c("Unable to create attachment"):u("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return c("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=Fe(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return a(r)?c("Unable to delete attachment"):u("Deleted attachment",n)},getAttachment(e){return v().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(v().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(v().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}=v(),r=n[e];if(!r)return c("Edit target node not found");let o=Ir(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 c("Rename target node not found");let r=Ir(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),u("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return Ie(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),s=this.getNode(t);if(!o)return c("Node not found");if(!s)return c("Target parent not found");if(r===e)return c("Cannot move root node");if(e===t)return c("Cannot move node into itself");let i=Ir(o,"move");if(i)return i;if(cu(t,e))return c("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}=v(),o=this.getNode(e);if(!o)return c("Node not found");if(r===e)return c("Cannot delete root node");let s=Ir(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 Ie(p.id))l(f.id)}};l(e);let d={...structuredClone(t)};for(let m of i){if(!d[m])return c("Unable to locate node to delete");d[m]={...d[m],isDeleted:!0}}return n?(w({nodes:d}),u("Successfully tomb stoned",o)):c("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return c("Contributor not found");let n={...t,name:bo,tombstoned:!0},r=Fe(o=>({...o,contributors:{...o.contributors,[e]:n}}));return a(r)?c("Unable to remove contributor"):u("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return c("Contributor not found");if(n.tombstoned)return c("Cannot rename a removed contributor");let r={...n,name:t},o=Fe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?c("Unable to rename contributor"):u("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return c("Contributor not found");let r={...n,name:t,tombstoned:!1},o=Fe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?c("Unable to restore contributor"):u("Restored contributor",r)},linkContributorEmail({email:e,contributor:t,authorId:n}){if(!this.getContributor(t))return c("Unable to link email, missing contributor");let r={email:et(e),contributor:t,authorId:n},o=hs(r.email,t),s=v().emailLinks[o];if(s&&!s.tombstoned)return u("Email already linked",s);let i=Fe(l=>({...l,emailLinks:{...l.emailLinks,[o]:r}}));return a(i)?c("Unable to link email"):u("Linked email to contributor",r)},unlinkContributorEmail(e,t,n){let r=hs(e,t),o=v().emailLinks[r];if(!o)return c("Unable to unlink, no such link");if(o.tombstoned)return u("Email already unlinked",o);if(!qi(n,o))return c("Only the author of a link or the contributor it names may remove it");let s={...o,tombstoned:!0},i=Fe(l=>({...l,emailLinks:{...l.emailLinks,[r]:s}}));return a(i)?c("Unable to unlink email"):u("Unlinked email from contributor",s)},getEmailLinks(){return v().emailLinks},createContributor(e){let t=Fe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?c("Unable to create contributor"):u("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return c("Unable to assign contributor, missing contributor");if(!r)return c("Unable to assign contributor, missing target");let o=Ir(r,"edit");if(o)return o;if(!_(r))return c("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return c("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 c("Unable to unassign, missing contributor");if(!r)return c("Unable to unassign, missing target");let o=Ir(r,"edit");if(o)return o;if(!_(r))return c("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 c("Unable to add tag, missing tag");if(!r)return c("Unable to add tag, missing target");let o=Ir(r,"edit");if(o)return o;if(!_(r))return c("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return c("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 c("Unable to remove tag, missing tag");if(!r)return c("Unable to remove tag, missing target");let o=Ir(r,"edit");if(o)return o;if(!_(r))return c("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 c("Tag not found");let n={...t,tombstoned:!0},r=Fe(o=>({...o,tags:{...o.tags,[e]:n}}));return a(r)?c("Unable to delete tag"):u("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return c("Tag not found");let r={...n,name:t,tombstoned:!1},o=Fe(s=>({...s,tags:{...s.tags,[e]:r}}));return a(o)?c("Unable to restore tag"):u("Restored tag",r)},createTag(e){let t=Fe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?c("Could not create tag"):u("Tag created",e)},createNode(e){let t=Yr("nodes",e.id,e);return a(t)?c("Unable to create node"):u("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return c("Failed to locate node");let n={...t,readonly:!0},r=Yr("nodes",e,n);return a(r)?c(r.message):u("Locked node",n)},updateNode(e){let t=Yr("nodes",e.id,e);return a(t)?t:u("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){let t=v().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return v().tags[e]},getTags(){return Object.values(v().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return v().nodes[e]},getSiblings(e){return Ie(e)}};var uA=(e,t)=>e+" ".repeat(Math.max(0,t-Rv(e))),mA=(e,t)=>" ".repeat(Math.max(0,t-Rv(e)))+e,ml=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","link.contributor.email":"Claimed","unlink.contributor.email":"Unclaimed","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),pA=(e,t)=>t?e<t?"up":e>t?"down":null:null,fA=(e,t)=>{let n=N.getNode(e.payload.parent),r=n?Er.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=pA(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Cv=e=>`${Math.max(1,Math.round(e/1024))} KB`,Nv=e=>N.getAttachment(e)?.name??"",gA=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?Er.bgHex(qe(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?Er.bgHex(qe(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=v().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Er.hex(qe(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Er.hex(qe(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"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"add.issue.attachment":return`"${e.payload.name}" ${Er.dim(`(${Cv(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Nv(e.payload.id);return t?`"${t}"`:""}default:return""}},hA=e=>{let t=pr(Be(e));return Er.gray(mA(t,8))},yA=12,vA=e=>uA(`${e}`,yA),bA=e=>{let t=xe();return a(t)?e:Ki(e,t.value.contributors[e]?.name)},xA=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=v().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"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"move.node":{let t=N.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Cv(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Nv(e.payload.id);return t?`"${t}"`:""}default:return""}},sl=e=>[ml(e.action),xA(e)].filter(Boolean).join(" "),Av=(e,t)=>{let n=hA(e.id),r=vA(bA(e.userId)),o=Er.dim("\u203A"),s=e.action==="move.node"?fA(e,t):[ml(e.action),gA(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};var IA=e=>Pe(e,"comments"),EA=e=>Pe(e,"description"),SA=e=>Pe(e,"assignees"),RA=e=>Pe(e,"tags"),CA=e=>Pe(e,"history"),NA=e=>Pe(e,"diff"),AA=e=>Pe(e,"attachments"),ai=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let l=N.getNode(e);if(!l){let p=N.createNode({...Ne.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return a(p)?p:u("Virtual field created",void 0)}if(!lt(l))return c(`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=N.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:s,childRenderAxis:i});return a(m)?m:u("Virtual field updated",void 0)},Tv=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=N.getNode(e);if(!i){let m=N.createNode({...Ne.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return a(m)?m:u("Virtual field list created",void 0)}if(!vs(i))return c(`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 d=N.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(d)?d:u("Virtual field list updated",void 0)},pl=null,TA=()=>{if(pl)return u("Virtual field ranks",pl);let e=Pt(Xt/4n),t=Pt(Xt/2n),n=Pt(Xt*3n/4n),r=Pt(Xt*7n/8n),o=Pt(Xt*15n/16n),s=Pt(Xt*13n/16n),i=Pt(Xt*27n/32n);return a(e)?e:a(t)?t:a(n)?n:a(r)?r:a(o)?o:a(s)?s:a(i)?i:(pl={description:e.value,assignees:t.value,tags:n.value,comments:r.value,attachments:o.value,log:s.value,diff:i.value},u("Virtual field ranks",pl))},og=e=>{let t=TA();if(a(t))return t;let n=t.value,r=ai({id:EA(e.id),name:Te.DESCRIPTION,parentNodeId:e.id,rank:n.description,value:e.props.description??"",childRenderAxis:"vertical"});if(a(r))return r;let o=Tv({id:SA(e.id),name:Te.ASSIGNEES,parentNodeId:e.id,rank:n.assignees,readonly:!0});if(a(o))return o;let s=Tv({id:RA(e.id),name:Te.TAGS,parentNodeId:e.id,rank:n.tags,readonly:!0});if(a(s))return s;let i=ai({id:IA(e.id),name:Te.COMMENTS,parentNodeId:e.id,rank:n.comments,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(i))return i;let l=ai({id:AA(e.id),name:Te.ATTACHMENTS,parentNodeId:e.id,rank:n.attachments,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(l))return l;let d=ai({id:CA(e.id),name:Te.HISTORY,parentNodeId:e.id,rank:n.log,value:wA(e),readonly:!0,childRenderAxis:"vertical"});if(a(d))return d;let m=ai({id:NA(e.id),name:Te.DIFF,parentNodeId:e.id,rank:n.diff,value:"",readonly:!0,childRenderAxis:"vertical"});return a(m)?m:u("Ticket virtual nodes materialized",void 0)},wA=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=>Av(r,n.get(r.action)??[])).join(`
|
|
98
|
-
`)},
|
|
99
|
-
`)[0]?.trim()??"";return t.length>
|
|
100
|
-
`)){let i=s.indexOf(" ");if(i===-1)continue;let l=s.slice(0,i),d=s.slice(i+1);l==="user.name"&&(r=d.trim()||null),l==="user.email"&&(o=et(d)||null)}return Vv.set(e,{name:r,email:o,readAt:Date.now()}),{name:r,email:o}},yl=async e=>(await zv(e)).email,Rr=async e=>(await zv(e)).name;var Xr=e=>{let t=me(e??process.cwd());return a(t)?c(t.message):u("Resolved Epiq repo root",t.value)},vl=null,ee=async(e,t)=>{let n=Xr(e);if(a(n))return n;let r=he({repoRoot:n.value});if(a(r))return c(r.message);let o=Ue(n.value);if(a(o))return c(o.message);if(!(vl!==null&&vl.repoRoot===n.value&&vl.stateBranchRoot===r.value&&XA.existsSync(Mr(r.value)))){let f=await Us({repoRoot:n.value,stateBranchName:o.value});if(a(f))return c(f.message);let g=await dr({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(a(g))return c(g.message);vl={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let f=await j({cwd:r.value,args:["pull","--ff-only"]});a(f)&&se.info(3,f.message)}let i={repoRoot:n.value,stateBranchRoot:r.value},l=ht();a(l)||je(l.value),je({gitEmail:await yl(n.value),gitName:await Rr(n.value)});let d=xn(r.value);if(Nf(r.value)===d&&_t()&&st().mode==="live")return u("Booted Epiq state, unchanged",i);let m=Zt(r.value);if(a(m))return c(m.message);let p=en(m.value.events,m.value.unreadable);return a(p)?c(p.message):(Af(r.value,d),u("Booted Epiq state",i))},te=()=>{let e=ht();return a(e)?c(e.message):e.value.userId?e.value.userName?u("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):c("Unable to retrieve user name"):c("Unable to retrieve user id")},q=()=>{let e=xe();return a(e)?c(e.message):e};var Ko=e=>hn(e).map(t=>Ye(t.id,t.name));var qo=e=>yn(e).map(({id:t,name:n})=>Ye(t,n));import JA from"node:fs";import QA from"node:path";import{ulid as gu}from"ulid";var tt=e=>{let t=q();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?c("Issue not found"):_(n)?n.readonly?c("Issue is readonly"):u("Found issue",n):c("Target must be an issue")},Cr=e=>{let t=q();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?c("Swimlane not found"):gn(n)?n.readonly?c("Swimlane is readonly"):u("Found swimlane",n):c("Target must be a swimlane")},fu=e=>{let t=q();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?c("Board not found"):rr(n)?n.readonly?c("Board is readonly"):u("Found board",n):c("Target must be a board")};var ZA=e=>{if(e.filePath)try{return u("Read attachment file",{data:JA.readFileSync(e.filePath),name:e.name??QA.basename(e.filePath)})}catch(t){return c(`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"}):c("Provide either filePath or dataBase64")},bl=()=>{let e=ht();return a(e)?vn:e.value.attachmentMaxKb??vn},hu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;let s=ZA(e);if(a(s))return s;let i=Vp(t.value.stateBranchRoot,s.value.data,bl());if(a(i))return i;let l=Re(s.value.name).trim()||"image",d=gu(),m={id:gu(),...D(n.value),action:"add.issue.attachment",payload:{id:d,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(a(p))return c(p.message);let f=Br(i.value.hash,i.value.ext);return u("Added issue attachment",{id:d,issueId:e.issueId,fileName:f,bytes:i.value.bytes,markdown:Bc(l,f)})},yu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.attachment"&&m.payload.id===e.attachmentId);if(!o)return c("Unable to resolve attachment");if(o.payload.author!==n.value.userId)return c("You can only delete your own attachments");let s=tt(o.payload.issue);if(a(s))return s;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:gu(),...D(n.value),action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:o.payload.issue}},d=B([l],t.value.stateBranchRoot);return a(d)?c(d.message):u("Deleted issue attachment",{id:e.attachmentId,issueId:o.payload.issue})},vu=async e=>{let t=await ee(e.repoRoot,{pull:!1});return a(t)?t:zp(t.value.stateBranchRoot,e.fileName,bl())};var eT=365*24*60*60*1e3,bu=e=>{let t=q();if(a(t))return t;let n=t.value.nodes[e];return u("Issue description",n&&_(n)&&!n.isDeleted?n.props.description??"":"")},Jr=()=>{let e=q();if(a(e))return e;let t=st(),n=t.mode!=="live",r=Object.values(e.value.nodes),o=r.filter(b=>rr(b)&&!b.isDeleted),s=Date.now()-eT,i=new Map,l=new Map;for(let b of r)if(!b.isDeleted){if(gn(b)&&b.parentNodeId){let R=i.get(b.parentNodeId)??[];R.push(b),i.set(b.parentNodeId,R)}if(_(b)&&b.parentNodeId){if(b.parentNodeId===ye&&Be(b.id)<s)continue;let R=l.get(b.parentNodeId)??[];R.push(b),l.set(b.parentNodeId,R)}}let d=new Set;for(let b of l.values())for(let R of b)d.add(R.id);let m=ht();if(a(m))return m;let p={},f=N.getCommentsGroupedByIssue();for(let b of r.filter(_))b.isDeleted||!d.has(b.id)||(p[b.id]=(f.get(b.id)??[]).map(R=>{let S=N.getContributor(R.authorId);return{id:R.id,issueId:R.issue,body:R.md,author:Ye(R.authorId,S?.name),createdAt:Be(R.id)}}));let g=new Map;for(let b of e.value.eventLog)b.action==="add.issue.attachment"&&g.set(b.payload.id,b.payload.author);let y={},x=N.getAttachmentsGroupedByIssue();for(let b of r.filter(_))b.isDeleted||!d.has(b.id)||(y[b.id]=(x.get(b.id)??[]).map(R=>({id:R.id,issueId:R.issue,name:R.name,fileName:Br(R.hash,R.ext),bytes:R.bytes,createdAt:Be(R.id),canDelete:g.get(R.id)===m.value.userId})));return u("Retrieved Epiq GUI state",{boards:o.sort((b,R)=>b.rank.localeCompare(R.rank)).map(b=>({id:b.id,ref:H(b.id),title:b.title,readonly:!!b.readonly||n,swimlanes:(i.get(b.id)??[]).sort((R,S)=>R.rank.localeCompare(S.rank)).map(R=>({id:R.id,title:R.title,readonly:!!R.readonly||n,issues:(l.get(R.id)??[]).sort((S,T)=>S.rank.localeCompare(T.rank)).map(S=>({id:S.id,ref:H(S.id),title:Re(S.title),description:S.props.description??"",createdAt:Be(S.id),enteredLaneAt:fl(S.log??[],Be(S.id)),readonly:!!S.readonly||n,tags:Ko(S),assignees:qo(S),parentNodeId:S.parentNodeId,isClosed:S.parentNodeId===ye})),parentNodeId:R.parentNodeId}))})),tags:N.getTags().map(b=>({...b,...Ye(b.id,b.name)})),contributors:Object.values(e.value.contributors).map(b=>({...b,...Ye(b.id,b.name)})),user:{id:m.value.userId??"",name:m.value.userName??"",color:qe(m.value.userName??"")},commentsByIssueId:p,attachmentsByIssueId:y,attachmentMaxKb:bl(),timeTravel:t})},Kv=null,tT=e=>{if(e===Kv)return;let t=Ji({root:e});if(a(t)){se.info(t.message);return}Kv=e},Ht=async(e={})=>{if(st().mode!=="live")return Jr();let t=await ee(e.repoRoot,{pull:!1});return a(t)?t:(tT(t.value.repoRoot),Jr())},ci=async(e={})=>{To();let t=Xr(e.repoRoot);if(a(t))return c("Sync failed");let n=te();if(a(n))return n;let r=await wa({cwd:t.value,ownEventFileName:ir(n.value)});return a(r)?(ld(r.message),r):(jr(),u("Synced",r.value))};import{ulid as Wt}from"ulid";var di=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?u("Resolved targets",t):c("Provide issueId or issueIds")},Yo=(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):c(`${r}: ${t.failed.map(o=>`${o.ref} ${o.reason}`).join("; ")}`)},ui=(e,t)=>{let n={done:[],failed:[]};for(let r of e){let o=t(r);a(o)?n.failed.push({id:r,ref:H(r),reason:o.message}):n.done.push({id:r,ref:H(r)})}return n};var Xv=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();async function Eu(e){let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=q();if(a(n))return n;let r=n.value.nodes,o=e.query?.trim().toLowerCase(),s=Object.values(r).filter(_).filter(l=>!l.isDeleted).filter(l=>e.includeClosed||l.parentNodeId!==ye).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||Ko(l).some(d=>Xv(d.name,e.tag))).filter(l=>!e.assignee||qo(l).some(d=>Xv(d.name,e.assignee))).filter(l=>!o||l.title.toLowerCase().includes(o)||(l.props.description??"").toLowerCase().includes(o)),i=l=>Re((l.parentNodeId?r[l.parentNodeId]?.title:void 0)??"");return e.brief?u("Listed issues",s.map(l=>({id:l.id,ref:H(l.id),title:Re(l.title),swimlane:i(l),tags:Ko(l).map(d=>d.name),assignees:qo(l).map(d=>d.name)}))):u("Listed issues",s.map(l=>({id:l.id,ref:H(l.id),title:Re(l.title),description:l.props.description??"",createdAt:Be(l.id),enteredLaneAt:fl(l.log??[],Be(l.id)),parentNodeId:l.parentNodeId,isClosed:l.parentNodeId===ye,readonly:!!l.readonly,tags:Ko(l),assignees:qo(l)})))}var Su=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=Re(e.title);if(!o)return c("Issue title cannot be empty");let s=e.description??"",i=ct("Issue title",o,300)??ct("Issue description",s,2e4);if(i)return c(i);if((e.tagNames?.length??0)>20)return c(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return c(`Cannot set more than ${20} assignees at once`);let l=Cr(e.parentId);if(a(l))return l;let d=Hn(e.parentId,n.value,t.value.stateBranchRoot);if(a(d))return d;let m=Qa({name:o,parent:e.parentId,user:n.value,rank:d.value});if(a(m))return m;let p=[...m.value],f=p.find(b=>b.action==="add.issue")?.payload.id;if(!f)return c("Unable to determine created issue id");s&&p.push({id:Wt(),...D(n.value),action:"edit.description",payload:{id:f,md:s}});let g=[];for(let b of e.tagNames??[]){let R=Re(b).trim();if(!R||g.some(P=>P.name===R))continue;let S=ct("Tag name",R,60);if(S)return c(S);let T=N.findTagByName(R),A=T?.id??Wt();T||p.push({id:Wt(),...D(n.value),action:"create.tag",payload:{id:A,name:R}}),p.push({id:Wt(),...D(n.value),action:"add.issue.tag",payload:{id:f,tag:A}}),g.push({id:A,name:R})}let y=[];for(let b of e.assigneeNames??[]){let R=Re(b).trim();if(!R||y.some(P=>P.name===R))continue;let S=ct("Assignee name",R,80);if(S)return c(S);let T=Object.values(r.value.contributors).find(P=>P.name===R),A=T?.id??Wt();T||p.push({id:Wt(),...D(n.value),action:"create.contributor",payload:{id:A,name:R}}),p.push({id:Wt(),...D(n.value),action:"add.issue.assignee",payload:{id:f,assignee:A}}),y.push({id:A,name:R})}let x=B(p,t.value.stateBranchRoot);return a(x)?c(x.message):u("Created issue",{id:f,ref:H(f),title:o,parentId:e.parentId,description:s,tags:g,assignees:y})},nT=(e,t,n)=>{let r=tt(e);if(a(r))return r;let o=Sn(ye,e,{at:"end"},t,n);if(a(o))return o;let s={id:Wt(),...D(t),action:"close.issue",payload:{id:e,parent:ye,rank:o.value}},i=B([s],n);return a(i)?c(i.message):u("Closed issue",{id:e,ref:H(e)})};async function Ru(e){let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=di(e);if(a(r))return r;let o=s=>nT(s,n.value,t.value.stateBranchRoot);return e.issueIds?Yo("Closed",ui(r.value,o)):o(r.value[0])}var Cu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o||o.isDeleted)return c("Issue not found");if(!_(o))return c("Target must be an issue");if(o.parentNodeId!==ye)return c("Issue is not closed");let s=il(o);if(!s)return c("Unable to resolve previous parent from issue history");if(s===ye)return c("Previous parent resolves to closed swimlane");let i=Cr(s);if(a(i))return i;let l=i.value,d=Sn(l.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(d))return d;let m={id:Wt(),...D(n.value),action:"reopen.issue",payload:{id:o.id,parent:l.id,rank:d.value}},p=B([m],t.value.stateBranchRoot);return a(p)?c(p.message):u("Reopened issue",{id:o.id,ref:H(o.id),parentId:l.id})},rT=(e,t,n,r)=>{let o=tt(e);if(a(o))return o;let s=Cr(t.parentId);if(a(s))return s;let i=Sn(t.parentId,e,t.position??{at:"end"},n,r);if(a(i))return i;let l={id:Wt(),...D(n),action:"move.node",payload:{id:e,parent:t.parentId,rank:i.value}},d=B([l],r);return a(d)?c(d.message):u("Moved issue",{id:e,ref:H(e),parentId:t.parentId})};async function Nu(e){let t=Xr(e.repoRoot);if(a(t))return t;let n=te();if(a(n))return n;let r=he({repoRoot:t.value});if(a(r))return r;let o=Zt(r.value);if(a(o))return o;let s=en(o.value.events,o.value.unreadable);if(a(s))return s;let i=di(e);if(a(i))return i;let l=d=>rT(d,e,n.value,r.value);return e.issueIds?Yo("Moved",ui(i.value,l)):l(i.value[0])}var Au=e=>{let t=q();if(a(t))return t;let n=t.value.nodes[e];return n?u("Read issue history",(n.log??[]).map(r=>({id:r.id,t:Be(r.id),action:r.action,label:sl(r),...r.action==="move.node"?{parentId:r.payload.parent}:{},actor:Ye(r.userId,t.value.contributors[r.userId]?.name)}))):c("Issue not found")},Tu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;let s=o.value,i=ct("Issue description",e.description,2e4);if(i)return c(i);let l=s.props.description??"";if(l===e.description)return u("No changes made",{id:e.issueId,ref:H(e.issueId),description:l});let d={id:Wt(),...D(n.value),action:"edit.description",payload:{id:e.issueId,md:e.description}},m=B([d],t.value.stateBranchRoot);return a(m)?c(m.message):u("Edited issue description",{id:e.issueId,ref:H(e.issueId),description:e.description})},wu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;let s=o.value,i=Re(e.title);if(!i.trim())return c("Issue title cannot be empty");let l=ct("Issue title",i,300);if(l)return c(l);if(s.title===i)return u("No changes made",{id:e.issueId,ref:H(e.issueId),title:i});let d={id:Wt(),...D(n.value),action:"edit.title",payload:{id:e.issueId,name:i}},m=B([d],t.value.stateBranchRoot);return a(m)?c(m.message):u("Edited issue title",{id:e.issueId,ref:H(e.issueId),title:i})};import{ulid as Nr}from"ulid";var Mu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.nodes[r.value.rootNodeId];if(!o)return c("Workspace not found");if(st().mode!=="live")return c("Cannot add a board while time travelling");let s=Re(e.title);if(!s.trim())return c("Board title cannot be empty");let i=ct("Board title",s,300);if(i)return c(i);let l=Hn(o.id,n.value,t.value.stateBranchRoot);if(a(l))return l;let d=Nr(),m={id:Nr(),...D(n.value),action:"add.board",payload:{id:d,name:s,parent:o.id,rank:l.value}},p=B([m],t.value.stateBranchRoot);return a(p)?c(p.message):u("Created board",{id:d,ref:H(d),title:s})},Pu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.nodes[e.boardId];if(!o||o.isDeleted)return c("Board not found");if(!rr(o))return c("Edit target must be a board");if(o.readonly)return c("Cannot edit readonly board");if(st().mode!=="live")return c("Cannot rename a board while time travelling");let s=Re(e.title);if(!s.trim())return c("Board title cannot be empty");let i=ct("Board title",s,300);if(i)return c(i);if(o.title===s)return u("No changes made",{id:e.boardId,ref:H(e.boardId),title:s});let l={id:Nr(),...D(n.value),action:"edit.title",payload:{id:e.boardId,name:s}},d=B([l],t.value.stateBranchRoot);return a(d)?c(d.message):u("Edited board title",{id:e.boardId,ref:H(e.boardId),title:s})};var Lu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=fu(e.boardId);if(a(o))return o;if(st().mode!=="live")return c("Cannot add a swimlane while time travelling");let s=Re(e.title);if(!s.trim())return c("Swimlane title cannot be empty");let i=ct("Swimlane title",s,300);if(i)return c(i);let l=Hn(e.boardId,n.value,t.value.stateBranchRoot);if(a(l))return l;let d=Nr(),m={id:Nr(),...D(n.value),action:"add.swimlane",payload:{id:d,name:s,parent:e.boardId,rank:l.value}},p=B([m],t.value.stateBranchRoot);return a(p)?c(p.message):u("Created swimlane",{id:d,ref:H(d),title:s,boardId:e.boardId})},ku=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=Cr(e.swimlaneId);if(a(o))return o;let s=o.value,i=Re(e.title);if(!i.trim())return c("Swimlane title cannot be empty");let l=ct("Swimlane title",i,300);if(l)return c(l);if(s.title===i)return u("No changes made",{id:e.swimlaneId,ref:H(e.swimlaneId),title:i});let d={id:Nr(),...D(n.value),action:"edit.title",payload:{id:e.swimlaneId,name:i}},m=B([d],t.value.stateBranchRoot);return a(m)?c(m.message):u("Edited swimlane title",{id:e.swimlaneId,ref:H(e.swimlaneId),title:i})},Du=async e=>{let t=Xr(e.repoRoot);if(a(t))return t;let n=te();if(a(n))return n;let r=he({repoRoot:t.value});if(a(r))return r;let o=Zt(r.value);if(a(o))return o;let s=en(o.value.events,o.value.unreadable);if(a(s))return s;let i=Cr(e.swimlaneId);if(a(i))return i;let l=fu(e.boardId);if(a(l))return l;let d=Sn(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(a(d))return d;let m={id:Nr(),...D(n.value),action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:d.value}},p=B([m],r.value);return a(p)?c(p.message):u("Moved swimlane",{id:e.swimlaneId,ref:H(e.swimlaneId),boardId:e.boardId})},Bu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=Cr(e.swimlaneId);if(a(o))return o;let s={id:Nr(),...D(n.value),action:"delete.node",payload:{id:e.swimlaneId}},i=B([s],t.value.stateBranchRoot);return a(i)?c(i.message):u("Deleted swimlane",{id:e.swimlaneId,ref:H(e.swimlaneId)})};import{ulid as mi}from"ulid";async function Ou(e){let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=di(e);if(a(r))return r;let o=Re(e.tagName).trim();if(!o)return c("Tag name cannot be empty");let s=ct("Tag name",o,60);if(s)return c(s);let i=ui(r.value,tt);if(!e.issueIds&&i.failed[0])return c(i.failed[0].reason);if(i.done.length===0)return c(Yo("Tagged",i).message);let l=N.findTagByName(o),d=l?.id??mi(),m=[...l?[]:[{id:mi(),...D(n.value),action:"create.tag",payload:{id:d,name:o}}],...i.done.map(({id:y})=>({id:mi(),...D(n.value),action:"add.issue.tag",payload:{id:y,tag:d}}))],p=B(m,t.value.stateBranchRoot);if(a(p))return c(p.message);let f={id:d,name:o};if(!e.issueIds)return u("Added issue tag",{...i.done[0],tag:f});let g=Yo("Tagged",i);return a(g)?g:u(g.message,{...g.value,tag:f})}var Fu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return c("Tag not found");if(o.tombstoned)return c("Tag is already deleted");let s=[{id:mi(),...D(n.value),action:"tombstone.tag",payload:{id:e.tagId}}],i=B(s,t.value.stateBranchRoot);return a(i)?c(i.message):u("Deleted tag",{id:o.id,name:o.name})};var _u=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;if(!r.value.tags[e.tagId])return c("Tag not found");let s={id:mi(),...D(n.value),action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=B([s],t.value.stateBranchRoot);return a(i)?c(i.message):u("Removed issue tag",{id:e.issueId,ref:H(e.issueId),tagId:e.tagId})};import{ulid as Zr}from"ulid";var Qv=async(e,t)=>{let n=lr(e).get(t);return n===void 0?void 0:{id:t,name:n}},$u=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;let s=e.self?n.value.userId:e.assigneeId;if(s){let b=r.value.contributors[s],R=b?void 0:await Qv(t.value.stateBranchRoot,s);if(!b&&!R)return c("Unknown assignee id");let S=b??R,T=[...b?[]:[{id:Zr(),...D(n.value),action:"create.contributor",payload:{id:S.id,name:S.name}}],{id:Zr(),...D(n.value),action:"add.issue.assignee",payload:{id:e.issueId,assignee:S.id}}],A=B(T,t.value.stateBranchRoot);return a(A)?c(A.message):u("Added issue assignee",{id:e.issueId,ref:H(e.issueId),assignee:{id:S.id,name:S.name}})}let i=Re(e.assigneeName??"").trim();if(!i)return c("Provide assigneeId, self or assigneeName");let l=ct("Assignee name",i,80);if(l)return c(l);let d=oi({events:r.value.eventLog??[],registry:r.value.contributors,logFileNames:lr(t.value.stateBranchRoot)}).filter(b=>b.name===i);if(d.length>1)return c(`"${i}" matches ${d.length} contributors (${d.map(({id:b})=>b).join(", ")}). Assign by assigneeId to choose.`);let m=d[0];if(!m&&!e.createUnlinked)return c(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let p=m?.id??Zr(),f=m?.name??i,y=[...!!r.value.contributors[p]?[]:[{id:Zr(),...D(n.value),action:"create.contributor",payload:{id:p,name:f}}],{id:Zr(),...D(n.value),action:"add.issue.assignee",payload:{id:e.issueId,assignee:p}}],x=B(y,t.value.stateBranchRoot);return a(x)?c(x.message):u("Added issue assignee",{id:e.issueId,ref:H(e.issueId),assignee:{id:p,name:f}})},Uu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;if(!r.value.contributors[e.contributorId])return c("Contributor not found");if(await Qv(t.value.stateBranchRoot,e.contributorId))return c("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let i=[{id:Zr(),...D(n.value),action:"tombstone.contributor",payload:{id:e.contributorId}}],l=B(i,t.value.stateBranchRoot);return a(l)?c(l.message):u("Tombstoned contributor",{id:e.contributorId,name:bo})};var ju=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=cr(t.value.stateBranchRoot);if(a(o))return c(o.message);let s=e.boardId?Bv(o.value,e.boardId):o.value,i=new Set,l=sg(t.value.stateBranchRoot);if(a(l))return c(l.message);for(let p of l.value)p.userId&&i.add(p.userId);let d=r.value.contributors,m=oi({events:s,registry:d,logFileNames:lr(t.value.stateBranchRoot)}).map(({id:p,name:f,isExternal:g})=>({...Ye(p,f),isSelf:p===n.value.userId,isExternal:g,isRemoved:d[p]?.tombstoned===!0,hasAuthoredAnywhere:i.has(p)}));return u("Listed board contributors",m)},Hu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;if(!r.value.contributors[e.assigneeId])return c("Assignee not found");let s={id:Zr(),...D(n.value),action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=B([s],t.value.stateBranchRoot);return a(i)?c(i.message):u("Removed issue assignee",{id:e.issueId,ref:H(e.issueId),assigneeId:e.assigneeId})};import{ulid as xl}from"ulid";var pi=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;let s=e.body.trim();if(!s)return c("Comment cannot be empty");if(s.length>4e3)return c(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i=xl(),l={id:xl(),...D(n.value),action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},d=B([l],t.value.stateBranchRoot);return a(d)?c(d.message):u("Added issue comment",{id:i,issueId:e.issueId,body:s})},fi=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return c("Unable to resolve comment");if(o.payload.author!==n.value.userId)return c("You can only delete your own comments");let s=tt(o.payload.issue);if(a(s))return s;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:xl(),...D(n.value),action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},d=B([l],t.value.stateBranchRoot);return a(d)?c(d.message):u("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},Wu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.eventLog.find(p=>p.action==="add.issue.comment"&&p.payload.id===e.commentId);if(!o)return c("Unable to resolve comment");if(o.payload.author!==n.value.userId)return c("You can only edit your own comments");let s=tt(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return c("Comment was deleted");let l=e.body.trim();if(!l)return c("Comment cannot be empty");if(l.length>4e3)return c(`Comment cannot exceed ${4e3} characters (got ${l.length})`);let d={id:xl(),...D(n.value),action:"edit.issue.comment",payload:{id:e.commentId,issue:o.payload.issue,md:l}},m=B([d],t.value.stateBranchRoot);return a(m)?c(m.message):u("Edited issue comment",{id:e.commentId,issueId:o.payload.issue,body:l})};import{ulid as Zv}from"ulid";var Gu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;if(!tr(e.email))return c(`Not an email address: ${e.email}`);let o=et(e.email),s=e.contributorId??n.value.userId;if(!r.value.contributors[s])return c(`Unknown contributor: ${s}`);let i=ys(r.value.emailLinks,o);if(i.includes(s))return u(`${o} is already yours`,{contributor:s,email:o,contested:i.filter(d=>d!==s)});let l=B([{id:Zv(),action:"link.contributor.email",payload:{contributor:s,email:o},userId:n.value.userId}],t.value.stateBranchRoot);return a(l)?c(l.message):u(i.length>0?`Claimed ${o}, but somebody else claims it too, so it now resolves to neither of you`:`Claimed ${o}`,{contributor:s,email:o,contested:i})},Vu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=et(e.email),s=e.contributorId??n.value.userId,i=r.value.emailLinks[hs(o,s)];if(!i||i.tombstoned)return c(`No such link: ${o} to ${s}`);if(!qi(n.value.userId,i))return c("Only whoever made a claim, or the contributor it names, may undo it");let l=B([{id:Zv(),action:"unlink.contributor.email",payload:{contributor:s,email:o},userId:n.value.userId}],t.value.stateBranchRoot);return a(l)?c(l.message):u(`Unclaimed ${o}`,{contributor:s,email:o})},Il=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=q();if(a(n))return n;let{emailLinks:r,contributors:o}=n.value,s=new Map;for(let f of Object.values(r)){if(f.tombstoned)continue;let g=s.get(f.email)??new Set;g.add(f.contributor),s.set(f.email,g)}let i=[...s.entries()].map(([f,g])=>({email:f,contested:g.size>1,claimants:[...g].map(y=>Ye(y,o[y]?.name))})).sort((f,g)=>f.email.localeCompare(g.email)),l=te(),d=a(l)?[]:fn(r,l.value.userId),m=V().gitEmail,p=m?ys(r,m).filter(f=>a(l)||f!==l.value.userId):[];return u("Listed contributor emails",{emails:i,mine:d,git:m?{email:m,linkedToMe:d.includes(m),heldByOthers:p.map(f=>Ye(f,o[f]?.name))}:null})},El=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let{userId:o,userName:s}=n.value,i=Ue(t.value.repoRoot),l=await wn({repoRoot:t.value.repoRoot,stateBranch:a(i)?void 0:i.value,names:[s,await Rr(t.value.repoRoot)],links:r.value.emailLinks});if(a(l))return l;let d=br(l.value),m=d.filter(p=>p.looksLikeYours);return u(d.length===0?"No unclaimed addresses in this history":`${d.length} unclaimed address(es) in this history, ${m.length>0?`${m.length} of which look like yours`:"none obviously yours"}. Show them to the user and link only the ones they confirm; each is a permanent event that replicates to every clone.`,{contributor:o,candidates:d,likely:m.length})};var eb=(e,t)=>{let n=0,r=0,o=null;for(let s of e){if(s.userId!==t)continue;s.action==="add.issue"&&n++,s.action==="add.issue.comment"&&r++;let i=yo(s.id);if(a(i))continue;let l=i.value.getTime();(o===null||l<o)&&(o=l)}return{tickets:n,comments:r,joinedAt:o}};var zu=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let{userId:o,userName:s}=n.value,i=eb(r.value.eventLog,o),l=Ue(t.value.repoRoot),d=await wn({repoRoot:t.value.repoRoot,stateBranch:a(l)?void 0:l.value,names:[s,await Rr(t.value.repoRoot)],links:r.value.emailLinks}),m=a(d)?[]:d.value.filter(p=>p.claimedBy.length===1&&p.claimedBy[0]===o);return u("Derived personal stats",{...i,scanned:!a(d),commits:m.reduce((p,f)=>p+f.commits,0),claimedEmails:m.length})};var Mn="1.10.0";import oT from"node:fs";import tb from"node:path";var gi=Number(process.env.EPIQ_GUI_PORT)||3710,Ku="/api/instance",qu="epiq",Sl=e=>{try{return oT.realpathSync(tb.resolve(e))}catch{return tb.resolve(e)}},sT=e=>{let t=e;return typeof t=="object"&&t!==null&&t.app===qu&&typeof t.repoRoot=="string"&&typeof t.version=="string"&&typeof t.pid=="number"},nb=async(e,t=500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}${Ku}`,{signal:n.signal});if(!o.ok)return null;let s=await o.json();return sT(s)?s:null}catch{return null}finally{clearTimeout(r)}};var iT=/^(```|~~~)[^\n]*\n[\s\S]*?\n\1[ \t]*$/gm,aT=/^(?:```|~~~)[\s\S]*$/m,lT=/^[ \t]*\|?[ \t]*:?-{2,}:?[ \t]*(?:\|[ \t]*:?-{2,}:?[ \t]*)*\|?[ \t]*$/gm,cT=/^[ \t]*\|.*$/gm,dT=/!\[[^\]]*\]\([^)]*\)/g,uT=/\[([^\]]*)\]\([^)]*\)/g,mT=/^[ \t]*(?:[#>]+[ \t]*|[-*+][ \t]+|\d+[.)][ \t]+)/gm,pT=/^[ \t]*(?:-{3,}|\*{3,}|_{3,})[ \t]*$/gm,fT=/[*`~]/g,gT=/(?<![0-9A-Za-z])_|_(?![0-9A-Za-z])/g,hT=e=>Re(e.replace(iT," ").replace(aT," ").replace(dT," ").replace(uT,"$1").replace(pT," ").replace(lT," ").replace(cT,t=>t.replaceAll("|"," ")).replace(mT,"").replace(fT,"").replace(gT,"")),yT=.5,rb=(e,t)=>{if(t<=0)return"";let n=hT(e);if(n.length<=t)return n;let r="\u2026",o=t-r.length;if(o<=0)return r.slice(0,t);let s=n.slice(0,o),i=s.lastIndexOf(" ");return`${(i>=o*yT?s.slice(0,i):s).trimEnd()}${r}`};var vT=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))}),eo=e=>a(e)?e:u(e.message,vT(e.value)),bT=(e,t)=>(e.boards??[]).flatMap(n=>n.swimlanes??[]).flatMap(n=>n.issues??[]).find(n=>n.id===t),ob=(e,t)=>{let n=bT(e,t);return{issueId:t,description:n?.description??"",comments:e.commentsByIssueId?.[t]??[]}},xT=280,sb=(e,t)=>({issueId:e,excerpt:rb(t,xT)});var ib=e=>{let t,n=!1,r=!1,o=0,s=i();function i(){let g=me(e.project.repoRoot);if(a(g))return null;let y=he({repoRoot:g.value});return a(y)?null:xn(y.value)}let l=()=>{let g=pn();return a(g)?(se.error(g.message),null):g.value},d=()=>{let g=l();if(!g)return!1;let y=ht();return a(y)?!1:!!g.autoSync&&ll(y.value)===null},m=()=>{let g=uo(l()?.autoSyncDebounceMs);return Math.max(0,g-(Date.now()-o))},p=async()=>{if(!(n||r)&&d()){r=!0,o=Date.now();try{await Sr(async()=>{if(st().mode!=="live")return;await ci({repoRoot:e.project.repoRoot});let g=i();if(g===null||g===s)return;s=g;let y=eo(await Ht({repoRoot:e.project.repoRoot}));a(y)||Ur({type:"state",payload:y})})}finally{r=!1,f()}}};function f(){n||!d()||r||t||(t=setTimeout(()=>{t=void 0,p()},m()))}return f(),{queueSync:f,reschedule:()=>{t&&(clearTimeout(t),t=void 0),f()},dispose:()=>{n=!0,t&&clearTimeout(t)}}};var IT=new Set(["127.0.0.1","[::1]","localhost","epiq.localhost"]),Yu=(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:!IT.has(n.hostname)},ab=(e,t)=>e.method==="GET"||e.method==="HEAD"?null:Yu(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 aw}from"ws";var Pn=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""});var ET=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},lb=({commits:e,patch:t})=>{let n=e.map(i=>i.time),o=t.files.map(i=>({...Pn(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=>ET(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 nt={line:["//"],block:[["/*","*/"]]},Gt={line:["#"],block:[]},Xu={line:["--"],block:[]},Xo={line:[],block:[["<!--","-->"]]},ST={line:[],block:[]},Y=(e,t)=>({name:e,comment:t}),Rl=Y("TypeScript",nt),Cl=Y("JavaScript",nt),cb={ts:Rl,tsx:Rl,mts:Rl,cts:Rl,js:Cl,jsx:Cl,mjs:Cl,cjs:Cl,py:Y("Python",{line:["#"],block:[['"""','"""']]}),rb:Y("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:Y("Go",nt),rs:Y("Rust",nt),java:Y("Java",nt),kt:Y("Kotlin",nt),swift:Y("Swift",nt),c:Y("C",nt),h:Y("C",nt),cc:Y("C++",nt),cpp:Y("C++",nt),hpp:Y("C++",nt),cs:Y("C#",nt),php:Y("PHP",nt),scala:Y("Scala",nt),dart:Y("Dart",nt),lua:Y("Lua",Xu),hs:Y("Haskell",Xu),sql:Y("SQL",Xu),ex:Y("Elixir",Gt),exs:Y("Elixir",Gt),pl:Y("Perl",Gt),r:Y("R",Gt),jl:Y("Julia",Gt),sh:Y("Shell",Gt),bash:Y("Shell",Gt),zsh:Y("Shell",Gt),vue:Y("Vue",Xo),svelte:Y("Svelte",Xo),html:Y("HTML",Xo),xml:Y("XML",Xo),md:Y("Markdown",Xo),mdx:Y("Markdown",Xo),css:Y("CSS",{line:[],block:[["/*","*/"]]}),scss:Y("CSS",nt),less:Y("CSS",nt),yml:Y("YAML",Gt),yaml:Y("YAML",Gt),toml:Y("TOML",Gt),ini:Y("INI",Gt),json:Y("JSON",ST)},RT="Other",db=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},to=e=>cb[db(e)]?.name??RT,hi=e=>cb[db(e)]?.comment??null,CT=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],NT=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,Jo=e=>NT.test(e)||CT.some(t=>t.test(e)),AT=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,TT=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,wT=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,an=e=>AT.test(e)||TT.test(e)||wT.test(e),ub=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),mb=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),pb=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),MT=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,PT=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,fb=e=>MT.test(e),gb=e=>PT.test(e);var hb=/\b(TODO|FIXME|HACK|XXX)\b/,LT=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,Ju=(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"},kT=(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},yb=({patch:e,repoShareByLanguage:t})=>{let n=new Map,r=0,o=0,s=0,i=0,l=0,d=0;for(let p of e.files){if(p.binary||an(p.path))continue;let f=hi(p.path);if(!f||f.line.length===0&&f.block.length===0)continue;let g=to(p.path),y=n.get(g)??{comment:0,code:0};for(let{text:x}of p.added){let b=Ju(x,f);if(hb.test(x)&&i++,b==="blank"){s++;continue}if(b==="comment"){r++,y.comment++,f&<.test(kT(x,f))&&d++;continue}o++,y.code++}for(let{text:x}of p.removedLines)hb.test(x)&&l++;n.set(g,y)}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:d}};var DT=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,Nl=6,Qu=10,BT=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)},OT=(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)},FT=e=>{if(e.length<Nl*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let r=0;r+Nl<=e.length;r++){let o=e.slice(r,r+Nl);if(o.some(l=>l.text.length<3))continue;let s=o.map(l=>l.text).join(`
|
|
101
|
-
`),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<
|
|
102
|
-
`)){if(f.startsWith(
|
|
103
|
-
`)){let f=
|
|
104
|
-
`)){let S=Ju(R,y);S==="comment"&&b.comment++,S==="code"&&b.code++}d.set(x,b)}let m=new Map;for(let[p,f]of d){let g=f.comment+f.code;g>0&&m.set(p,f.comment/g)}return{languages:r,commentShareByLanguage:m}};var Cb=({patch:e})=>{let t=0,n=0,r=[],o=[],s=0,i=0;for(let l of e.files)if(!(l.binary||an(l.path))&&Jo(l.path)){t+=l.addedCount,n+=l.removed,l.status==="added"&&r.push(Pn(l)),l.status==="deleted"&&o.push(Pn(l));for(let{text:d}of l.added)fb(d)&&s++,gb(d)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:r,deletedTestFiles:o,skippedTestLinesAdded:s,focusedTestLinesAdded:i}};var qT=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,Nb=async({repoRoot:e,ref:t,commits:n})=>{let r=await Sb({repoRoot:e,shas:n.map(l=>l.sha)});if(a(r))return c(r.message);let o=r.value,s=qT(n),i=s?await Rb({repoRoot:e,sha:s}):null;return u("Derived issue stats",{ref:t,shape:lb({commits:n,patch:o}),languages:bb({patch:o,languagesBefore:i?.languages??null}),tests:Cb({patch:o}),comments:yb({patch:o,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:vb({patch:o})})};var yi=e=>{if(a(e))return e;let t=xe(),n=a(t)?{}:t.value.emailLinks,r=a(t)?{}:t.value.contributors,o=ap(n),s=e.value.map(i=>({...i,authorIdentity:Vy({authorName:i.author,authorEmail:i.authorEmail,owners:o,registry:r})}));return u(e.message,s)};var YT=32,vi=new Map;var XT=(e,t)=>{if(vi.set(e,t),vi.size>YT){let n=vi.keys().next();n.done||vi.delete(n.value)}return t},Al=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return c("idOrRef must not be empty");let n=t.length>7?H(t):t.toUpperCase(),r=me(e.repoRoot??process.cwd());if(a(r))return c(r.message);let o=r.value,s=yi(await zn({repoRoot:o,ref:n}));if(a(s))return c(s.message);let i=s.value.map(p=>({sha:p.sha,time:p.time,author:p.authorIdentity?.resolved?p.authorIdentity.name:p.author,subject:p.subject})),l=[o,n,i.map(p=>`${p.sha}:${p.author}`).join(",")].join(" "),d=vi.get(l);if(d)return u("Derived issue stats",d);let m=await Nb({repoRoot:o,ref:n,commits:i});return a(m)?c(m.message):u("Derived issue stats",XT(l,m.value))};var JT=new RegExp(`^[0-9A-Z]{${7}}$`),QT=e=>{let t=e.indexOf(" ");if(t===-1)return null;let n=e.slice(0,t).toUpperCase();return JT.test(n)?n:null},ZT=e=>{let t={};for(let n of e){let r=QT(n.subject);if(!r)continue;let o=t[r]??={commits:0,insertions:0,deletions:0};o.commits++,o.insertions+=n.insertions,o.deletions+=n.deletions}return t},Ab=async(e={})=>{let t=await Uo({repoRoot:e.repoRoot});return a(t)?t:u("Collected diff stats by ref",ZT(t.value))};var ew="Filed here",Tb=(e,t)=>e.set(t,(e.get(t)??0)+1),wb=(e,t,n)=>[...e.entries()].map(([r,o])=>({laneId:r,title:r===null?ew:n(r),count:o,share:t===0?0:o/t})).sort((r,o)=>o.count-r.count||r.title.localeCompare(o.title)),Mb=(e,t,n)=>{let r=new Map,o=new Map,s=0,i=0;for(let l of t)for(let[d,m]of l.entries()){if(m!==e)continue;s++,Tb(r,l[d-1]??null);let p=l[d+1];p!==void 0&&(i++,Tb(o,p))}return{arrived:s,departed:i,arrivesFrom:wb(r,s,n),movesOnTo:wb(o,i,n)}};var Pb=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 bi=1440*60*1e3,tw=({laneIds:e,journeys:t,now:n,days:r})=>{let o=n-(r-1)*bi,s=new Map(e.map(i=>[i,Array.from({length:r},()=>[])]));for(let i of t)for(let[l,d]of i.entries()){let m=s.get(d.laneId);if(!m)continue;let p=i[l+1]?.enteredAt,f=Math.max(0,Math.ceil((d.enteredAt-o)/bi)),g=p===void 0?r-1:Math.min(r-1,Math.ceil((p-o)/bi)-1);for(let y=f;y<=g;y++)m[y].push(o+y*bi-d.enteredAt)}return Object.fromEntries([...s].map(([i,l])=>[i,l.map((d,m)=>({t:o+m*bi,median:Pb(d.sort((p,f)=>p-f)),count:d.length}))]))},Lb=({laneId:e,journeys:t,now:n,days:r})=>tw({laneIds:[e],journeys:t,now:n,days:r})[e];var nw=40,rw=30,ow=()=>({tickets:0,commits:0,insertions:0,deletions:0}),sw=async(e,t)=>{let n=ow();for(let r of t.slice(0,nw)){let o=await Al({repoRoot:e,idOrRef:H(r)});a(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},kb=async e=>{let t=q();if(a(t))return t;let{nodes:n}=t.value;if(!n[e.swimlaneId])return c("Swimlane not found");let o=Object.values(n).filter(_),s=o.map(d=>du(d.log??[],Be(d.id))),i=Mb(e.swimlaneId,s.map(d=>d.map(m=>m.laneId)),d=>n[d]?.title??"Elsewhere"),l=o.filter(d=>d.parentNodeId===e.swimlaneId).map(d=>d.id);return u("Derived swimlane stats",{swimlaneId:e.swimlaneId,createdAt:Be(e.swimlaneId),...i,stayTrend:Lb({laneId:e.swimlaneId,journeys:s,now:Date.now(),days:rw}),code:await sw(e.repoRoot,l)})};var Db=new Set(["sync","email:link","email:unlink","issues:create","board:create","board:edit:title","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 Bb=e=>{let t=$n({exclude:e});return a(t)?[]:t.value.map(n=>({projectId:n.projectId,name:Io(n.root),root:n.root,lastOpenedAt:n.lastOpenedAt}))},Ob=e=>{let t=$n();if(a(t))return c(t.message);let n=t.value.find(r=>r.root===e);return n?u("Resolved recent project",n.root):c(`Not a recent project: ${e}`)};import{z as k}from"zod";var re=k.string().min(1),Fb=k.discriminatedUnion("at",[k.object({at:k.literal("start")}),k.object({at:k.literal("end")}),k.object({at:k.literal("before"),sibling:re}),k.object({at:k.literal("after"),sibling:re})]),xi=k.number().finite(),ce=(e,t)=>k.object({type:k.literal(e),payload:t}),no=e=>k.object({type:k.literal(e)}),iw=k.discriminatedUnion("type",[no("state:get"),no("issues:list"),no("sync"),no("time-travel:live"),no("diff-stats:get"),ce("project:open",k.object({root:k.string().min(1)})),ce("issues:create",k.object({title:k.string(),parentId:re,description:k.string().optional(),tagNames:k.array(k.string()).optional()})),ce("board:create",k.object({title:k.string()})),ce("board:edit:title",k.object({boardId:re,title:k.string()})),ce("swimlane:create",k.object({title:k.string(),boardId:re})),ce("swimlane:edit:title",k.object({swimlaneId:re,title:k.string()})),ce("swimlane:delete",k.object({swimlaneId:re})),ce("swimlane:move",k.object({swimlaneId:re,boardId:re,position:Fb.optional()})),ce("issues:move",k.object({issueId:re,parentId:re,position:Fb.optional()})),ce("issue:edit:title",k.object({issueId:re,title:k.string()})),ce("issue:edit:description",k.object({issueId:re,description:k.string()})),ce("issue:tag:add",k.object({issueId:re,tagName:k.string()})),ce("issue:tag:remove",k.object({issueId:re,tagId:re})),ce("contributor:remove",k.object({contributorId:re})),ce("tag:remove",k.object({tagId:re})),k.object({type:k.literal("contributors:get"),payload:k.object({boardId:re.optional()}).optional()}),ce("issue:assignee:add",k.object({issueId:re,assigneeId:re.optional(),assigneeName:k.string().optional(),createUnlinked:k.boolean().optional()})),ce("issue:assignee:remove",k.object({issueId:re,assigneeId:re})),ce("issue:close",k.object({issueId:re})),ce("issue:reopen",k.object({issueId:re})),ce("issue:comment:add",k.object({issueId:re,body:k.string()})),ce("issue:comment:delete",k.object({issueId:re,commentId:re})),ce("issue:comment:edit",k.object({issueId:re,commentId:re,body:k.string()})),ce("issue:get",k.object({issueId:re})),ce("issue:preview:get",k.object({issueId:re})),k.object({type:k.literal("timeline:get"),payload:k.object({start:xi.optional(),end:xi.optional(),boardId:re.optional(),requestId:k.number().finite().optional()}).optional()}),k.object({type:k.literal("commits:get"),payload:k.object({start:xi.optional(),end:xi.optional(),requestId:k.number().finite().optional()}).optional()}),ce("time-travel:scrub",k.object({targetTime:xi})),ce("time-travel:checkout-event",k.object({eventId:k.string().min(1)})),ce("commit:inspect",k.object({sha:k.string()})),k.object({type:k.literal("emails:get")}),ce("email:link",k.object({email:k.string().min(1).max(254),contributorId:k.string().min(1).optional()})),ce("email:unlink",k.object({email:k.string().min(1).max(254),contributorId:k.string().min(1).optional()})),ce("commit:diff:get",k.object({sha:k.string()})),ce("issue:commits:get",k.object({issueId:re})),ce("issue:squashed-diff:get",k.object({issueId:re})),ce("issue:stats:get",k.object({issueId:re})),ce("swimlane:stats:get",k.object({swimlaneId:re})),no("me:stats:get"),no("settings:get"),ce("settings:set",k.object({autoSync:k.boolean().optional(),autoSyncIntervalMs:k.number().finite().optional()}))]);var _b=e=>{let t=iw.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 lw=1024*1024,tm=()=>{Ur({type:"state",payload:eo(Jr())})},ne=(e,t)=>{e.send(JSON.stringify(t))},Ii=async(e,t)=>{let n=eo(await Ht({repoRoot:t}));return a(n)&&n.message===pc?ne(e,{type:"state:unavailable",payload:{message:n.message,repoRoot:t,recentProjects:Bb(t)}}):ne(e,{type:"state",payload:n})},cw=async(e,t)=>{let n=()=>ne(e,{type:"state",payload:eo(Jr())});if(st().mode!=="live")return n();let r=await Ht({repoRoot:t});return st().mode!=="live"?n():ne(e,{type:"state",payload:eo(r)})},ze=async(e,t,n,r,o)=>{if(ne(e,{type:r,payload:o}),a(o))return ne(e,{type:"failed",payload:o.message});n(),cw(e,t)},$b=(e,t,{onStateChanged:n,onSyncSettingsChanged:r,getPort:o})=>{new aw({server:e,path:"/ws",maxPayload:lw,verifyClient:i=>!Yu(i.origin,o())}).on("connection",i=>{Ng(i),i.on("message",async l=>{let d=async m=>{let{type:p}=m,f=t.repoRoot;if(p==="project:open"){let g=Ob(m.payload.root);return ne(i,{type:"project:open:result",payload:g}),a(g)?void 0:(t.repoRoot=g.value,Ii(i,g.value))}if(p==="timeline:get"){let{requestId:g,...y}=m.payload??{};return ne(i,{type:"timeline",requestId:g,payload:await jv({repoRoot:f,...y})})}if(p==="issue:get"){let g=m.payload?.issueId,y=Jr(),x=Au(g);return ne(i,{type:"issue",payload:a(y)?y:u("Issue detail",{...ob(y.value,g),history:a(x)?[]:x.value})})}if(p==="issue:preview:get"){let{issueId:g}=m.payload,y=bu(g);return ne(i,{type:"issue:preview:result",payload:{issueId:g,result:a(y)?y:u("Issue preview",sb(g,y.value))}})}if(p==="commits:get"){let{requestId:g,...y}=m.payload??{};return ne(i,{type:"commits",requestId:g,payload:yi(await Uo({repoRoot:f,...y}))})}if(p==="emails:get")return ne(i,{type:"emails",payload:await Il({repoRoot:f}),suggestions:await El({repoRoot:f})});if(p==="email:link"||p==="email:unlink"){let y=await(p==="email:link"?Gu:Vu)({repoRoot:f,...m.payload});return ne(i,{type:"emails",payload:await Il({repoRoot:f}),suggestions:await El({repoRoot:f}),lastAction:a(y)?{ok:!1,message:y.message}:{ok:!0,message:y.message}}),ze(i,f,n,`${p}:result`,y)}if(p==="me:stats:get")return ne(i,{type:"me:stats",payload:await zu({repoRoot:f})});if(p==="settings:get")return ne(i,{type:"settings",payload:si()});if(p==="settings:set"){let g=zo({enabled:m.payload.autoSync,intervalMs:m.payload.autoSyncIntervalMs});return a(g)||r(),ne(i,{type:"settings",payload:a(g)?si():g,lastAction:a(g)?{ok:!1,message:g.message}:{ok:!0,message:g.message}})}if(p==="commit:inspect")return ne(i,{type:"commit:inspect:result",payload:await Xs({repoRoot:f,sha:m.payload.sha})});if(p==="commit:diff:get"){let{sha:g}=m.payload;return ne(i,{type:"commit:diff:result",payload:{sha:g,result:await Ad({repoRoot:f,sha:g})}})}if(p==="issue:commits:get"){let{issueId:g}=m.payload;return ne(i,{type:"issue:commits:result",payload:{issueId:g,result:yi(await zn({repoRoot:f,ref:H(g)}))}})}if(p==="issue:squashed-diff:get"){let{issueId:g}=m.payload;return ne(i,{type:"issue:squashed-diff:result",payload:{issueId:g,result:await Td({repoRoot:f,ref:H(g)})}})}if(p==="issue:stats:get"){let{issueId:g}=m.payload;return ne(i,{type:"issue:stats:result",payload:{issueId:g,result:await Al({repoRoot:f,idOrRef:H(g)})}})}if(p==="diff-stats:get")return ne(i,{type:"diff-stats",payload:await Ab({repoRoot:f})});if(p==="swimlane:stats:get"){let{swimlaneId:g}=m.payload;return ne(i,{type:"swimlane:stats:result",payload:{swimlaneId:g,result:await kb({repoRoot:f,swimlaneId:g})}})}if(p==="time-travel:scrub"){let g=await pu({repoRoot:f,targetTime:m.payload.targetTime});return ne(i,{type:"time-travel:result",payload:g}),a(g)?void 0:tm()}if(p==="time-travel:checkout-event"){let g=await Wv({repoRoot:f,eventId:m.payload.eventId});return ne(i,{type:"time-travel:result",payload:g}),a(g)?void 0:tm()}if(p==="time-travel:live"){let g=await Gv({repoRoot:f});return ne(i,{type:"time-travel:result",payload:g}),a(g)?void 0:tm()}if(p==="state:get")return Ii(i,f);if(p==="sync"){let g=await ci({repoRoot:f});return ne(i,{type:"sync:result",payload:g}),n(),Ii(i,f)}if(p==="issue:comment:add"){let g=await pi({repoRoot:f,...m.payload});return ze(i,f,n,"issue:comment:add:result",g)}if(p==="issue:comment:edit"){let g=await Wu({repoRoot:f,...m.payload});return ze(i,f,n,"issue:comment:edit:result",g)}if(p==="issue:comment:delete"){let g=await fi({repoRoot:f,...m.payload});return ne(i,{type:"issue:comment:delete:result",payload:g}),a(g)?ne(i,{type:"failed",payload:g.message}):(n(),Ii(i,f))}if(p==="issue:edit:description"){let g=await Tu({repoRoot:f,...m.payload});return ze(i,f,n,"issue:edit:description:result",g)}if(p==="issue:edit:title"){let g=await wu({repoRoot:f,...m.payload});return ze(i,f,n,"issue:edit:title:result",g)}if(p==="issue:tag:add"){let g=await Ou({repoRoot:f,...m.payload});return ze(i,f,n,"issue:tag:add:result",g)}if(p==="issue:tag:remove"){let g=await _u({repoRoot:f,...m.payload});return ze(i,f,n,"issue:tag:remove:result",g)}if(p==="contributor:remove"){let g=await Uu({repoRoot:f,...m.payload});return ze(i,f,n,"contributor:remove:result",g)}if(p==="tag:remove"){let g=await Fu({repoRoot:f,...m.payload});return ze(i,f,n,"tag:remove:result",g)}if(p==="contributors:get")return ne(i,{type:"contributors",payload:await ju({repoRoot:f,...m.payload})});if(p==="issue:assignee:add"){let g=await $u({repoRoot:f,...m.payload});return ze(i,f,n,"issue:assignee:add:result",g)}if(p==="issue:assignee:remove"){let g=await Hu({repoRoot:f,...m.payload});return ze(i,f,n,"issue:assignee:remove:result",g)}if(p==="issues:list")return ne(i,{type:"issues",payload:await Eu({repoRoot:f})});if(p==="issues:create"){let g=await Su({...m.payload,repoRoot:f});return ne(i,{type:"issues:create:result",payload:g}),a(g)?Ur({type:"failed",payload:g.message}):(n(),Ii(i,f))}if(p==="board:create"){let g=await Mu({...m.payload,repoRoot:f});return ze(i,f,n,"board:create:result",g)}if(p==="board:edit:title"){let g=await Pu({...m.payload,repoRoot:f});return ze(i,f,n,"board:edit:title:result",g)}if(p==="swimlane:create"){let g=await Lu({...m.payload,repoRoot:f});return ze(i,f,n,"swimlane:create:result",g)}if(p==="swimlane:edit:title"){let g=await ku({...m.payload,repoRoot:f});return ze(i,f,n,"swimlane:edit:title:result",g)}if(p==="swimlane:delete"){let g=await Bu({...m.payload,repoRoot:f});return ze(i,f,n,"swimlane:delete:result",g)}if(p==="swimlane:move"){if(!m.payload.position)return ne(i,{type:"error",message:"Missing move position"});let g=await Du({...m.payload,repoRoot:f});return ze(i,f,n,"swimlane:move:result",g)}if(p==="issues:move"){if(!m.payload.position)return ne(i,{type:"error",message:"Missing move position"});let g=await Nu({...m.payload,repoRoot:f});return ze(i,f,n,"issues:move:result",g)}if(p==="issue:close"){let g=await Ru({repoRoot:f,issueId:m.payload.issueId});return ze(i,f,n,"issue:close:result",g)}if(p==="issue:reopen"){let g=await Cu({repoRoot:f,issueId:m.payload.issueId});return ze(i,f,n,"issue:reopen:result",g)}return ne(i,{type:"error",message:"Unknown message type"})};try{let m=_b(JSON.parse(l.toString()));if(!m.ok)return ne(i,{type:"error",message:m.error});let p=m.message;return Db.has(p.type)?await Sr(async()=>st().mode!=="live"?ne(i,{type:"failed",payload:"Read-only while viewing history"}):d(p)):await d(p)}catch(m){return ne(i,{type:"error",message:m instanceof Error?m.message:String(m)})}})})};var fw=ro.dirname(pw(import.meta.url)),gw=process.env.IS_LOCAL==="true"?ro.resolve(process.cwd(),"dist/gui"):ro.join(fw,"gui"),Tl,hw=async()=>(Tl===void 0&&(Tl=await import("node:sea").catch(()=>null)),Tl?.isSea()?Tl:null),Le=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},yw=e=>Le(e,409,{isError:!0,message:"Read-only while viewing history"}),wl=(e,t)=>Sr(async()=>st().mode!=="live"?yw(e):t()),Ub=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)}),vw=2*1024*1024,bw={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},xw=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",jb=new Map,Iw=e=>`"${uw("sha1").update(e).digest("base64url")}"`,Ew=async e=>{try{let{size:t,mtimeMs:n}=await dw(e);return`${t}:${n}`}catch{return null}},Sw=e=>{try{return decodeURIComponent(e)}catch{return null}},Hb=async(e,t,n)=>{let r=e==="/"?"/index.html":Sw(e);if(r===null)return Le(n,404,{isError:!0,message:"Not found"});let o=r.replace(/^\/+/,""),s=ro.resolve(gw),i=ro.resolve(s,o),l=ro.relative(s,i);if(l.startsWith("..")||ro.isAbsolute(l))return Le(n,403,{isError:!0,message:"Forbidden"});let d=await hw(),m=d?"sea":await Ew(i),p=m===null?void 0:jb.get(l),f=p&&p.stamp===m?p.etag:null;if(f&&t.headers["if-none-match"]===f)return n.writeHead(304,{etag:f,"cache-control":"no-cache"}),n.end();try{let g=d?Buffer.from(d.getAsset(`gui/${l}`)):await Wb(i),y=f??Iw(g);return m!==null&&jb.set(l,{stamp:m,etag:y}),n.writeHead(200,{"content-type":xw(i),etag:y,"cache-control":"no-cache"}),n.end(g)}catch{return Le(n,404,{isError:!0,message:`Not found: ${o}`})}},Rw=async(e,t=gi)=>new Promise((n,r)=>{let o=s=>{let i=d=>{if(e.off("listening",l),d.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(d)},l=()=>{e.off("error",i);let d=e.address();if(!d||typeof d=="string"){r(new Error("Unable to resolve address"));return}n(d.port)};e.once("error",i),e.once("listening",l),e.listen(s,"127.0.0.1")};o(t)}),Gb=async e=>{Mv(!1);let t=0,n={repoRoot:e.repoRoot},r=mw.createServer((l,d)=>{o(l,d).catch(m=>(logger.error(`[gui] ${l.method} ${l.url}: ${m instanceof Error?m.message:String(m)}`),d.headersSent?d.end():Le(d,500,{isError:!0,message:"Internal error"})))});async function o(l,d){let m=new URL(l.url??"/","http://127.0.0.1"),p=ab({method:l.method,origin:l.headers.origin,contentType:l.headers["content-type"]},t);if(p)return Le(d,p.status,{isError:!0,message:p.message});if(l.method==="GET"&&m.pathname===Ku)return Le(d,200,{app:qu,repoRoot:Sl(n.repoRoot),version:Mn,pid:process.pid});if(m.pathname==="/api/state")return Le(d,200,await Ht({repoRoot:n.repoRoot}));if(l.method==="POST"&&m.pathname==="/api/comments")try{let f=await Ub(l);if(!f.issueId||!f.body?.trim())return Le(d,400,{isError:!0,message:"Missing issueId or body"});let g=f.issueId,y=f.body;return await wl(d,async()=>{let x=await pi({repoRoot:n.repoRoot,issueId:g,body:y});return a(x)?Le(d,400,{isError:!0,message:x.message}):Le(d,200,await Ht({repoRoot:n.repoRoot}))})}catch(f){return Le(d,400,{isError:!0,message:f instanceof Error?f.message:"Unable to add comment"})}if(l.method==="POST"&&m.pathname==="/api/attachments")try{let f=await Ub(l,vw);if(!f.issueId||!f.dataBase64)return Le(d,400,{isError:!0,message:"Missing issueId or dataBase64"});let g=f.issueId,y=f.dataBase64,x=f.name??"";return await wl(d,async()=>{let b=await hu({repoRoot:n.repoRoot,issueId:g,name:x,dataBase64:y});return a(b)?Le(d,400,{isError:!0,message:b.message}):Le(d,200,{...await Ht({repoRoot:n.repoRoot}),attachment:b.value})})}catch(f){return Le(d,400,{isError:!0,message:f instanceof Error?f.message:"Unable to add attachment"})}if(l.method==="DELETE"&&m.pathname.startsWith("/api/attachments/")){let f=decodeURIComponent(m.pathname.replace("/api/attachments/",""));return f?wl(d,async()=>{let g=await yu({repoRoot:n.repoRoot,attachmentId:f});return a(g)?Le(d,400,{isError:!0,message:g.message}):Le(d,200,await Ht({repoRoot:n.repoRoot}))}):Le(d,400,{isError:!0,message:"Missing attachment id"})}if(l.method==="GET"&&m.pathname.startsWith("/media/")){let f=decodeURIComponent(m.pathname.replace("/media/","")),g=await vu({repoRoot:n.repoRoot,fileName:f});if(a(g))return Le(d,404,{isError:!0,message:g.message});try{let y=await Wb(g.value.filePath);return d.writeHead(200,{"content-type":bw[g.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),d.end(y)}catch{return Le(d,404,{isError:!0,message:"Attachment blob not found"})}}if(l.method==="DELETE"&&m.pathname.startsWith("/api/comments/")){let f=decodeURIComponent(m.pathname.replace("/api/comments/",""));return f?wl(d,async()=>{let g=await fi({repoRoot:n.repoRoot,commentId:f});return a(g)?Le(d,400,{isError:!0,message:g.message}):Le(d,200,await Ht({repoRoot:n.repoRoot}))}):Le(d,400,{isError:!0,message:"Missing comment id"})}return m.pathname.startsWith("/board/")||m.pathname==="/log"?Hb("/",l,d):Hb(m.pathname,l,d)}try{t=await Rw(r)}catch(l){return c(l instanceof Error?`Unable to start GUI server: ${l.message}`:`Unable to start GUI server: ${String(l)}`)}let s=ib({project:n});$b(r,n,{onStateChanged:()=>s.queueSync(),onSyncSettingsChanged:()=>s.reschedule(),getPort:()=>t}),r.on("close",s.dispose);let i=r.address();return!i||typeof i=="string"?(r.close(),c("Unable to resolve GUI server address")):u("Started GUI server",{url:`http://epiq.localhost:${i.port}${e.boardId?`/board/${e.boardId}`:""}`,server:r})};var zb=async e=>{let t=lo({});if(a(t))return c(t.message);let n=ht();be(n)&&je(n.value);let r=await nb(gi);if(r&&r.repoRoot===Sl(e.repoRoot)){let i=`http://127.0.0.1:${gi}`;return console.log(`Epiq GUI already running for this project at ${Vb.cyan(i)}`),bc(i),u("Reused running GUI",{url:i})}let o=await Gb({...e,boardId:""});if(a(o))return o;let{url:s}=o.value;return console.log(`Epiq GUI running at ${Vb.cyan(s)}`),bc(s),u("Started GUI",{url:s})};import{Box as Xn}from"ink";import ke from"react";import{Box as nm,Text as Ei}from"ink";import ln,{useEffect as Cw,useMemo as Nw}from"react";import{ulid as Aw}from"ulid";var Kb=({text:e,match:t,color:n,highlightColor:r=h.secondary,dimColor:o=!1})=>{if(!t)return ln.createElement(Ei,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),l=s.indexOf(i);return l===-1?ln.createElement(Ei,{color:n,dimColor:o},e):ln.createElement(Ei,{color:n,dimColor:o},e.slice(0,l),ln.createElement(Ei,{backgroundColor:r,bold:!0},e.slice(l,l+t.length)),e.slice(l+t.length))},qb=Aw(),Tw=e=>`${e}`,ww=e=>{let{pendingNavTarget:t}=yr();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(Oe(C.NONE,{breadCrumb:n,contextNode:r,readOnly:v().readOnly,selectedNode:o}));return[...new Set(Object.values(C))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==C.PALETTE).map(i=>{let l=La(i),d=cl.find(m=>m.intent===l);return{command:i,description:d?.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))},Mw=e=>Ne.text({id:qb,parentNodeId:e,rank:"000000",name:"Command Palette",readonly:!0,isVirtual:!0}),Pw=(e,t,n)=>Ne.text({id:Tw(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,disabled:!e.isAvailable,readonly:!0,isVirtual:!0}),rm=[],Lw=e=>{Yb();let t=N.createNode(Mw(v().rootNodeId));a(t)||!nr(t.value)||(rm=[t.value,...e.map((n,r)=>Pw(n,r,qb)).map(N.createNode).filter(be).map(({value:n})=>n).filter(nr)],U.navigate({contextNode:t.value,selectedIndex:0}))},Yb=()=>{let e=rm.map(t=>t.id);rm=[];for(let t of e)N.deleteNode(t)};function Xb({width:e,height:t}){let r=hf().value.trim().toLowerCase(),o=Nw(()=>ww(r),[r]);Cw(()=>(Lw(o),()=>{Yb()}),[o]);let s=v().selectedIndex;return ln.createElement(nm,{flexDirection:"column",width:e,height:t-2},ln.createElement(mt,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,l)=>{let d=l===s,m=i.isAvailable?h.accent:h.secondary2,p=i.isAvailable?"":"[unavailable] ";return ln.createElement(nm,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:h.secondary,borderStyle:"single"},ln.createElement(Ei,{color:m,dimColor:!i.isAvailable},d?"\u276F ":" ",ln.createElement(Kb,{text:fp(i.command),match:r,color:m,dimColor:!i.isAvailable})),ln.createElement(nm,{paddingLeft:2},ln.createElement(Kb,{text:p+i.description,match:r.length>=2?r:"",color:d&&i.isAvailable?h.primary:h.secondary2,dimColor:!i.isAvailable})))})))}import{Box as Kw}from"ink";import Ll from"react";import Ri from"chalk";import{Box as Si,Text as ex}from"ink";import oo,{useEffect as tx,useMemo as kw,useState as nx}from"react";var Qo=["\u2803","\u2806","\u2830","\u2818"],Jb=120,Qb=({isPalette:e,isPending:t,frame:n})=>{if(t){let r=(n%Qo.length+Qo.length)%Qo.length;return Qo[r]}return e?"?":":"},Zb=({infoMessage:e,isPending:t})=>t&&e.includes(fe)?"":e;var rx=Ri.hex(h.secondary),Dw=Ri.inverse,Bw=Ri.inverse.hex(h.secondary2),Ow={hint:"",hints:[],overlap:0,remainder:""},sx=({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}},Fw=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=qe(t);return{bg:r=>Ri.bgHex(n).black(r),bgCursor:r=>Ri.bgHex(n).inverse.black(r)}}return Sc(t)},_w=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=sx({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}},ox=()=>({value:dt.value,cursorPosition:dt.cursorPosition,commandIsPending:dt.commandIsPending,autoCompletion:dt.commandMeta.autoCompletion??Ow,infoMessage:dt.commandMeta.infoMessage,validationStatus:dt.commandMeta.validity,command:dt.commandMeta.command,inputString:dt.commandMeta.inputString,modifier:dt.commandMeta.modifier}),$w=(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,ix=({width:e,mode:t})=>{let[n,r]=nx(ox());tx(()=>{let T=()=>{let P=ox();r(M=>$w(M,P)?M:P)},A=$c(T);return T(),()=>{A()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:l,autoCompletion:d,command:m,modifier:p,validationStatus:f}=n,g=l&&f===bn.Invalid,y=Zb({infoMessage:i,isPending:l}),[x,b]=nx(0);tx(()=>{if(!l){b(0);return}let T=setInterval(()=>{b(A=>(A+1)%Qo.length)},Jb);return()=>{clearInterval(T)}},[l]);let R=Qb({isPalette:t===I.PALETTE,isPending:l,frame:x}),S=kw(()=>{let T=Math.max(0,Math.min(s,o.length)),A=sx({value:o,command:m}),P=_w({value:o,command:m,modifier:p}),M=m?Sc(m):null,O=Fw({command:m,modifier:p}),W=(it,ft)=>{let io=A&&ft>=A.start&&ft<A.end,ql=P&&ft>=P.start&&ft<P.end;return io&&M?M.fg(it):ql&&O?O.bg(it):it},X=(it,ft)=>{let io=A&&ft>=A.start&&ft<A.end,ql=P&&ft>=P.start&&ft<P.end;return io&&M?M.fgCursor(it):ql&&O?O.bgCursor(it):Dw(it)},Ee=o.slice(0,T),F=o[T]??" ",J=T<o.length?o.slice(T+1):"",Ke=Array.from(Ee).map((it,ft)=>W(it,ft)).join(""),Jn=X(F,T),os=Array.from(J).map((it,ft)=>W(it,T+1+ft)).join("");if(d.hint){let it=d.hint[d.overlap]??F;Jn=Bw(it),os=rx(d.remainder.slice(1)+J)}return Ke+Jn+os},[o,s,d,m,p]);return oo.createElement(Si,{flexDirection:"column",justifyContent:"flex-start"},oo.createElement(Si,{flexDirection:"column",paddingX:1,borderColor:h.secondary,borderStyle:"round",width:e},oo.createElement(Si,{height:1,flexWrap:"nowrap"},oo.createElement(Si,{flexShrink:0},oo.createElement(ex,{wrap:"truncate-start"},rx(R),S)),y&&oo.createElement(Si,{flexShrink:1,minWidth:0},oo.createElement(ex,{wrap:"truncate",color:g?h.red:h.secondary2},` ${y} `)))))};import{Box as Uw,Text as Ci}from"ink";import Zo from"react";var ax=" ",jw=({keys:e,label:t})=>e.length+1+t.length,Hw=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?ax.length:0)+jw(o);if(r+i>t-4)break;n.push(o),r+=i}return n},lx=({width:e,availableHints:t})=>{let n=Hw(t,e);return Zo.createElement(Uw,{width:e,borderStyle:"round",borderColor:h.secondary,paddingX:1},n.length?Zo.createElement(Ci,{wrap:"truncate"},n.map(({keys:o,label:s},i)=>Zo.createElement(Ci,{key:`${o}-${s}`},i>0?ax:"",Zo.createElement(Ci,{color:h.accent},o),Zo.createElement(Ci,{color:h.secondary2}," ",s)))):Zo.createElement(Ci,{color:h.secondary2},"\xA0"))};import{Box as Ww,Text as Ml}from"ink";import Ni,{useEffect as Gw,useRef as es,useState as Vw}from"react";var zw=40,Pl=.3,om="\u2500",cx=1,dx=16,ux=({width:e})=>{let{replay:t}=oe(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*cx,[l,d]=Vw(0),m=es(r);m.current=r;let p=es(0),f=es(0),g=es(0),y=es(0),x=es(0);if(Gw(()=>{if(!n){p.current=0,g.current=0,y.current=0,x.current=0,d(0);return}p.current=m.current,f.current=Date.now(),g.current=m.current;let A=setInterval(()=>{let P=Date.now(),M=m.current;if(M!==g.current){let F=M-g.current,J=P-f.current;if(F<0)y.current=0,x.current=0;else if(F>0&&J>0){let Ke=F/J;y.current=y.current===0?Ke:y.current*(1-Pl)+Ke*Pl,x.current=x.current===0?F:x.current*(1-Pl)+F*Pl}p.current=M,f.current=P,g.current=M}let O=P-f.current,W=Math.min(x.current,y.current*O),X=Math.min(1,p.current+W),Ee=Math.round(X*i);d(F=>F===Ee?F:Ee)},zw);return()=>clearInterval(A)},[n,i]),!t)return null;let b=A=>{let P=s>1?A/(s-1):0,M=Math.round(P*(dx-1))/(dx-1);return Gi(M)},R=Math.min(s,Math.floor(l/cx)),S=[];for(let A=0;A<R;A++){let P=b(A),M=S[S.length-1];M&&M.color===P?M.text+=om:S.push({text:om,color:P})}let T=om.repeat(Math.max(0,s-R));return Ni.createElement(Ww,{width:e,borderStyle:"round",borderColor:h.secondary,paddingX:1,columnGap:1},Ni.createElement(Ml,{color:h.secondary2},"\u25B6"),Ni.createElement(Ml,null,S.map((A,P)=>Ni.createElement(Ml,{key:P,color:A.color},A.text)),Ni.createElement(Ml,{color:h.secondary,dimColor:!0},T)))};var Ai=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=oe(),o=t===I.COMMAND_LINE||t===I.PALETTE;return Ll.createElement(Kw,null,o?Ll.createElement(ix,{width:e,mode:t}):r==="replay"?Ll.createElement(ux,{width:e}):Ll.createElement(lx,{width:e,mode:t,availableHints:n}))};import{Box as Ar,Text as ts}from"ink";import bt,{useEffect as qw,useMemo as Yw}from"react";import{ulid as mx}from"ulid";var Dl=mx(),Xw=()=>[...new Set([...v().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(ou).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})),Jw=e=>Ne.text({id:Dl,parentNodeId:e,rank:"000000",name:"Help",isVirtual:!0,readonly:!0}),Qw=(e,t,n)=>Ne.text({id:mx(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,readonly:!0,isVirtual:!0}),kl=[],px=()=>{let e=kl.filter(n=>n.id!==Dl).map(n=>n.id),t=kl.filter(n=>n.id===Dl).map(n=>n.id);kl=[];for(let n of[...e,...t])N.deleteNode(n)},Zw=e=>{px();let t=N.createNode(Jw(v().rootNodeId));if(a(t)||!nr(t.value))return logger.error("Could not attach help nodes");kl=[t.value,...e.map((n,r)=>Qw(n,r,Dl)).map(N.createNode).filter(be).map(({value:n})=>n).filter(nr)],U.navigate({contextNode:t.value,selectedIndex:0})},fx=({width:e,height:t})=>{let n=Yw(()=>Xw(),[]);qw(()=>(Zw(n),()=>{px()}),[n]);let r=v().selectedIndex;return bt.createElement(Ar,{flexDirection:"column",marginTop:3,borderColor:h.secondary,borderStyle:"round",width:e,height:t-2},bt.createElement(Ar,{paddingX:1,justifyContent:"center"},bt.createElement(ts,{color:h.accent},"Help"),bt.createElement(ts,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),bt.createElement(Ar,{paddingX:1,marginTop:1},bt.createElement(Ar,{width:20,justifyContent:"flex-end"},bt.createElement(ts,{color:h.secondary},"Key(s)")),bt.createElement(Ar,{flexGrow:1,width:40,paddingLeft:2},bt.createElement(ts,{color:h.secondary},"Action"))),bt.createElement(mt,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let l=i===r;return bt.createElement(Ar,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},bt.createElement(Ar,{width:20,justifyContent:"flex-end"},bt.createElement(ts,{color:h.accent},o)),bt.createElement(Ar,{flexGrow:1,width:40,paddingLeft:2},bt.createElement(ts,{color:l?h.primary:h.secondary2},s)))})))};import{Box as ns,Text as xt}from"ink";import we,{useEffect as eM,useState as sm}from"react";var Bl=({index:e,email:t,note:n,noteColor:r})=>we.createElement(ns,null,we.createElement(xt,{color:h.accent},e===void 0?" ":` ${e}.`),we.createElement(xt,null," ",t),n&&we.createElement(xt,{color:r??h.secondary2},` ${n}`)),gx=({height:e})=>{let[t,n]=sm([]),[r,o]=sm([]),[s,i]=sm(null),{userName:l,gitEmail:d,gitName:m,userId:p}=V();return eM(()=>{let f=!0;return(async()=>{let y=xe(),x=me(process.cwd());if(a(y)||a(x)||!p)return;let b=y.value.emailLinks,R=fn(b,p);n(R.map(P=>({email:P,others:ys(b,P).filter(M=>M!==p).map(M=>y.value.contributors[M]?.name??M)})));let S=Ue(x.value),T=await wn({repoRoot:x.value,stateBranch:a(S)?void 0:S.value,names:[l,m],links:b});if(!f)return;if(a(T)){i(T.message);return}let A=br(T.value);Eo(A.map(P=>P.email)),o(A)})(),()=>{f=!1}},[p,l,m,d]),we.createElement(ns,{height:e-4,flexDirection:"column",paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},we.createElement(ns,null,we.createElement(xt,{color:h.accent,bold:!0},l??"Not configured"),we.createElement(xt,{color:h.secondary2}," on this board")),s&&we.createElement(xt,{color:h.red},s),we.createElement(ns,{flexDirection:"column"},we.createElement(xt,{color:h.secondary2},"CLAIMED"),t.length===0?we.createElement(Bl,{email:"Nothing claimed \u2014 your commits show the name git signed them with.",note:""}):t.map(f=>we.createElement(Bl,{key:f.email,email:f.email,note:f.others.length>0?`CONTESTED: also ${f.others.join(", ")}, resolves to nobody`:f.email===d?"your git identity here":void 0,noteColor:f.others.length>0?h.yellow:void 0}))),we.createElement(ns,{flexDirection:"column"},we.createElement(xt,{color:h.secondary2},"UNCLAIMED IN THIS HISTORY"),r.length===0?we.createElement(Bl,{email:"Nothing left to claim here."}):r.map(f=>we.createElement(Bl,{key:f.email,email:f.email,note:`${f.commits} commit${f.commits===1?"":"s"} as ${f.names.join(", ")||"unknown"}`}))),we.createElement(ns,{flexDirection:"column"},we.createElement(xt,{color:h.secondary2},we.createElement(xt,{color:h.accent},"[enter]")," writes a claim for the first into the command line, to confirm or change."),we.createElement(xt,{color:h.secondary2},we.createElement(xt,{color:h.accent},":config emails")," claims by address,",we.createElement(xt,{color:h.accent}," :config emails-unclaim "),"gives one back."),we.createElement(xt,{color:h.secondary2},we.createElement(xt,{color:h.accent},"[esc]")," to close")))};import tM from"chalk";import{Box as so,Text as rt}from"ink";import Me from"react";var nM=8,rM=()=>{let e=$n({exclude:process.cwd()});return a(e)?[]:e.value.slice(0,nM)},hx=({width:e,height:t})=>{let n=rM();return Me.createElement(so,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},Me.createElement(rt,{color:h.accent,bold:!0},"Initialize project"),Me.createElement(rt,null,`This folder is not an ${tM.hex(h.accent)("epiq")} project yet.`),Me.createElement(rt,{color:h.primary},"To start tracking issues here, we need to initialize a new",Me.createElement(rt,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json "),"file in this repository."),Me.createElement(so,{marginTop:1,flexDirection:"column"},Me.createElement(so,null,Me.createElement(rt,{color:h.accent}," "),Me.createElement(rt,{color:h.primary},"Type "),Me.createElement(rt,{backgroundColor:h.secondary}," :init "))),Me.createElement(so,{marginTop:1},Me.createElement(rt,{color:h.secondary2},"This will create, commit and push "),Me.createElement(rt,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json ")),n.length>0&&Me.createElement(so,{marginTop:1,flexDirection:"column"},Me.createElement(rt,{color:h.accent,bold:!0},"Or open a recent project"),n.map((r,o)=>Me.createElement(so,{key:r.projectId},Me.createElement(rt,{color:h.accent},` ${o+1} `),Me.createElement(rt,{color:h.primary},Io(r.root)),Me.createElement(rt,{color:h.secondary2},` ${r.root}`))),Me.createElement(so,{marginTop:1},Me.createElement(rt,{color:h.accent}," "),Me.createElement(rt,{color:h.primary},"Type "),Me.createElement(rt,{backgroundColor:h.secondary}," :open 1 "),Me.createElement(rt,{color:h.secondary2}," or "),Me.createElement(rt,{backgroundColor:h.secondary}," :open <path> "))))};import{Box as Fl,Text as Dt}from"ink";import $e from"react";import{Box as Ol,Text as Yn}from"ink";import kt,{useEffect as oM,useState as yx}from"react";var vx=()=>{let[e,t]=yx(null),[n,r]=yx(null);return oM(()=>{let o=!0;return(async()=>{let i=xe(),l=me(process.cwd());if(a(i)||a(l))return;let d=Ue(l.value),{userName:m,gitName:p}=V(),f=await wn({repoRoot:l.value,stateBranch:a(d)?void 0:d.value,names:[m,p],links:i.value.emailLinks});if(!o)return;if(a(f)){r(f.message);return}let g=br(f.value);Eo(g.map(y=>y.email)),t(g)})(),()=>{o=!1}},[]),n?kt.createElement(Ol,{marginTop:1},kt.createElement(Yn,{color:h.red},n)):e===null?null:e.length===0?kt.createElement(Ol,{marginTop:1},kt.createElement(Yn,{color:h.secondary2},"No unclaimed addresses in this history \u2014 type",kt.createElement(Yn,{color:h.accent}," :config emails none "),"to move on.")):kt.createElement(Ol,{flexDirection:"column",marginTop:1},e.map(o=>kt.createElement(Yn,{key:o.email},kt.createElement(Yn,{color:h.accent}," \xB7 "),kt.createElement(Yn,null,o.email),kt.createElement(Yn,{color:h.secondary2},` ${o.commits} commit${o.commits===1?"":"s"} as ${o.names.join(", ")||"unknown"}`))),kt.createElement(Ol,{marginTop:1},kt.createElement(Yn,{color:h.secondary2},"Claim yours by address, or",kt.createElement(Yn,{color:h.accent}," none "),"to skip.")))};var sM=({isDone:e,command:t,value:n,verb:r="Type",hint:o})=>$e.createElement(Fl,null,$e.createElement(Dt,{color:h.accent,dimColor:e},e?" \u2714 ":" "),$e.createElement(Dt,{dimColor:e},r," "),$e.createElement(Dt,{backgroundColor:h.secondary,dimColor:e}," "+t+" "),n!==void 0&&$e.createElement($e.Fragment,null,$e.createElement(Dt,{dimColor:e}," "),$e.createElement(Dt,{color:h.secondary,dimColor:e},"<"+n+">")),o),iM=(e,t)=>e.length===0?void 0:_n(e.join(", "),Math.max(12,t-34)),aM=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function im({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:l,isSetEmails:d,claimedEmails:m,emailSetupDeclined:p}=Un(),f=[{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."},{key:"emails",done:d,command:":config emails",value:p?"declined":iM(m,e),message:"Last one. Claim the git addresses whose commits are yours, so the board calls them by your name."}],g=f.findIndex(x=>!x.done),y=g===-1?void 0:f[g];return $e.createElement(Fl,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},$e.createElement(Dt,{color:h.accent,bold:!0},"Welcome! \u{1F539}"),$e.createElement(Dt,null,"Let's get you started - it's a breeze."),$e.createElement(Dt,{color:h.secondary2},"Remember - you can always search available commands by typing:",$e.createElement(Dt,{color:h.accent}," ? ")),y&&$e.createElement(Dt,{color:h.secondary2},y.message),$e.createElement(Fl,{flexDirection:"column"},f.map((x,b)=>{if(!(g===-1||b<=g))return null;let S=b===g,T=S&&g===0;return $e.createElement(Fl,{key:x.key,flexDirection:"column",marginBottom:1},$e.createElement(sM,{isDone:x.done,command:T?":config us":x.command,value:x.done?aM(x.value):void 0,verb:S&&!T?"Waiting:":"Type",hint:T?$e.createElement(Dt,{color:h.secondary2}," then ",$e.createElement(Dt,{color:h.accent},"tab")," to auto-complete ",$e.createElement(Dt,{backgroundColor:h.secondary},` ${x.command.split(" ").pop()} `)):void 0}),x.key==="emails"&&!x.done&&$e.createElement(vx,null))})))}import Hl from"chalk";import{Box as wi,Text as rs}from"ink";import Ze from"react";import{Box as _l,Text as bx}from"ink";import Tr from"react";import lM from"chalk";var cM=e=>(N.getTag(e)?.name??"").length+3,dM=e=>{let t=N.getContributor(e);return(t?t.name:"").length+3},xx=({width:e})=>{let{viewMode:t}=V(),n=oe(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,l=i[o.id]?.[s],d=Nt(l?.id??o.id,"TICKET"),m=be(d)?d.value:void 0,p=(m?.props.tags??[]).filter(M=>N.getTag(M)),f=m?.props.assignees??[],g=m?.parentNodeId?!cu(o.id,m.parentNodeId)&&t==="dense":!1,y=r.map((M,O)=>{let W=O===r.length-1,X=Ie(M.id),Ee=W?X?.[s]?.title:void 0;return`${O?" / ":""}${M.title??""}${Ee?` \u25B8 ${Ee}`:""}`}).join(""),x=m?N.getCommentsByIssue(m.id):[],b=x.length?String(x.length).length+11:0,R=g?p.reduce((M,O)=>M+cM(O),0)+f.reduce((M,O)=>M+dM(O),0)+b:0,S=l?.id!=null&&!(t==="wide"&&_(l)),T=Math.max(0,e-R),A=y.substring(0,T)+(S?lM.hex(h.secondary2).dim(` ${H(l.id)}`):""),P=g?[...p.map(M=>Tr.createElement(_l,{key:`tag-${M}`,paddingLeft:1},Tr.createElement(Lo,{id:M}))),...f.map(M=>Tr.createElement(_l,{key:`assignee-${M}`,paddingLeft:1},Tr.createElement(ur,{id:M}))),x.length?Tr.createElement(_l,{key:"comments",paddingLeft:1},Tr.createElement(bx,{color:h.accent},"[",x.length," comment",x.length===1?"":"s","]")):null]:[];return Tr.createElement(_l,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},Tr.createElement(bx,{color:h.secondary2},A),P)};import{Box as uM,Text as Ix}from"ink";import $l from"react";var mM=({filters:e})=>$l.createElement(uM,{columnGap:1},$l.createElement(Ix,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>$l.createElement(Ix,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Ex=$l.memo(mM);import{Box as pM,Text as Ul}from"ink";import Ti from"react";function Sx(){let{eventLog:e,unappliedEvents:t}=oe(),n=e.at(-1)?.id,r=yo(n??""),o=be(r)?Fa(r.value):"INVALID DATE";return Ti.createElement(pM,{paddingLeft:1},Ti.createElement(Ul,{backgroundColor:h.accent,color:h.secondary}," Readonly "),Ti.createElement(Ul,{color:h.accent}," "+t.length+" edits ago at "+o+"."),Ti.createElement(Ul,{color:h.accent}," Resume with "),Ti.createElement(Ul,{backgroundColor:h.accent,color:h.secondary}," ",":peek now"," "))}import{Box as fM,Text as am}from"ink";import jl from"react";function Rx(){let{replay:e}=oe();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return jl.createElement(fM,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},jl.createElement(am,{backgroundColor:h.accent,color:h.secondary}," \u25B6 REPLAY "),jl.createElement(am,{color:h.secondary2},Fa(new Date(r))),jl.createElement(am,{color:h.accent},`${t}/${n} edits`))}import lm from"chalk";import{Box as gM,Text as Cx}from"ink";import cm,{useEffect as hM,useState as yM}from"react";var vM=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],bM=150,Nx=12,xM=.36,Ax=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)}},IM=({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)}`},EM=(e,t,n)=>{let r=Ax(e),o=Ax(t);return IM({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},SM=(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 EM(s,i,o)};function Tx({syncStatus:e,autoSync:t}){let[n,r]=yM(0);hM(()=>{if(e.status!=="syncing"){r(0);return}let l=0,d=setInterval(()=>{l+=1;let m=(Math.sin(l*xM)+1)/2,p=Math.round(m*(Nx-1));r(f=>f===p?f:p)},bM);return()=>clearInterval(d)},[e.status]);let o={synced:" ",failed:"---",offline:"off",syncing:"...",pending:"idle"},i={synced:h.secondary2,failed:h.yellow,offline:h.secondary2,pending:h.secondary2,syncing:SM(vM,n/(Nx-1))??""}[e.status];return cm.createElement(gM,null,cm.createElement(Cx,null,lm.hex(h.secondary2).dim(t?"Sync (auto): ":"Sync: ")),cm.createElement(Cx,null,lm.hex(i)("\u25CF")+lm.hex(h.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import kx from"chalk";import{Text as Dx}from"ink";import Bx,{useEffect as AM,useState as TM}from"react";import dm from"chalk";var RM="https://registry.npmjs.org/epiq/latest",um=null,wx=0,CM=1e3*60*60*24,Mx=e=>e.replace(/^v/,""),NM=(e,t)=>{let n=Mx(e).split(".").map(Number),r=Mx(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},Px=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(um&&Date.now()-wx<CM)return um;try{let t=await fetch(RM);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?NM(r,e)>0:!1};return um=o,wx=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},Lx=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?dm.hex(h.accent).dim(s):dm.hex(h.secondary).dim(s)).join(dm.hex(h.secondary2).dim("."))};function Ox(){let[e,t]=TM({current:Mn,latest:null,updateAvailable:!1});return AM(()=>{let n=!0;return Px(Mn).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?Bx.createElement(Dx,{dimColor:!0,color:h.secondary2},Mn+" "):Bx.createElement(Dx,null,kx.hex(h.secondary2).dim(Mn),kx.hex(h.accent).dim(" \u2197 "),Lx(Mn,e.latest))}function Mi({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=oe(),{userName:i,preferredEditor:l,autoSync:d}=V(),m=64,p=process.stdout.columns-m-8,f=t||n==="replay",g=s?Fn(s.currentLabel,Math.max(0,p)):"";return Ze.createElement(wi,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?Ze.createElement(wi,{paddingLeft:1},Ze.createElement(rs,{color:h.secondary2},g)):f?Ze.createElement(rs,null," "):o===I.PALETTE?Ze.createElement(wi,null,Ze.createElement(rs,{color:h.accent},"Command Palette"),Ze.createElement(rs,{dimColor:!0,color:h.secondary2}," ","- search, select and press enter")):Ze.createElement(wi,{paddingLeft:1},e.length>0?Ze.createElement(Ex,{filters:e}):Ze.createElement(xx,{width:p})),n==="live"?Ze.createElement(wi,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},Ze.createElement(Tx,{autoSync:!!d,syncStatus:r}),Ze.createElement(rs,null,Hl.hex(h.secondary2).dim("Mode: ")+Hl.hex(h.secondary2).dim(o.padEnd(8," "))," "),Ze.createElement(Fx,{icon:"@",value:i}),Ze.createElement(Fx,{icon:"\u276F",value:l}),Ze.createElement(Ox,null)):"",n==="peek"?Ze.createElement(Sx,null):"",n==="replay"?Ze.createElement(Rx,null):"")}function Fx({icon:e,value:t}){return Ze.createElement(rs,null,Hl.dim(e)+Hl.hex(h.accent)(` ${t??"-"} `))}import{Box as wM,Text as MM}from"ink";import Pi from"react";import{Box as Wl,Text as mm}from"ink";import wr from"react";function pm(){let e=oe(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?de(t?.id):[];return wr.createElement(Wl,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:h.secondary,width:s},wr.createElement(Wl,{padding:1,paddingTop:0,paddingBottom:0},wr.createElement(mm,null,"Select a board:")),wr.createElement(Wl,{padding:1,flexDirection:"column"},i.map((l,d)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===d,f=de(l.id).flatMap(({id:g})=>Ie(g)).length;return wr.createElement(Wl,{key:l.id??d},wr.createElement(mm,{color:m?h.accent:h.secondary2},wr.createElement(St,{isSelected:m})),wr.createElement(mm,{color:m?h.accent:h.secondary2},l.title," (",f," issues)",l.readonly?" \u{1F512}":""))})))}var PM=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:l}=oe(),d=n.find(({context:g})=>g==="BOARD"),f=s-1-3;return Pi.createElement(wM,{flexDirection:"row"},e.context==="WORKSPACE"?Pi.createElement(pm,null):d?Pi.createElement(Xa,{height:f,width:i,swimlanes:(l[d.id]??[]).filter(g=>g!==void 0&&gn(g)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Pi.createElement(MM,null))},_x=Pi.memo(PM);import{useEffect as LM}from"react";var kM=e=>{LM(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=V();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:l,mode:d}=v();d==="default"&&!l&&Pa(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},$x=({autoSync:e})=>(kM(e),null);function fm({width:e,height:t}){let n=oe(),{autoSync:r,viewMode:o}=Zm(),s=n.filters;if(n.mode===I.HELP)return ke.createElement(Xn,{flexDirection:"column"},ke.createElement(fx,{width:e,height:t}));if(n.mode===I.IDENTITY)return ke.createElement(Xn,{flexDirection:"column"},ke.createElement(gx,{width:e,height:t}));if(n.mode===I.PALETTE)return ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Mi,{filters:s}),ke.createElement(Xb,{width:e,height:t-2}),ke.createElement(Ai,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Un(),l=!i,d=i&&!n.hasProjectDefinition;if(l)return ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Mi,{hideBreadCrumb:!0,filters:s}),ke.createElement(im,{height:t,width:e})),ke.createElement(Ai,{width:e,mode:n.mode,availableHints:[]}));if(d)return ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Mi,{hideBreadCrumb:!0,filters:s}),ke.createElement(hx,{height:t,width:e})),ke.createElement(Ai,{width:e,mode:n.mode,availableHints:[]}));let m=yt(n.breadCrumb??[],"BOARD");if(be(m)){let p=m.value.id,f=de(p).length,g=3,y=Math.floor(e/g),x=Math.floor(e/Math.max(f,1));e=Math.min(x,y)*Math.max(f,g)}return ke.createElement(Xn,{flexDirection:"column"},ke.createElement($x,{autoSync:r}),ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Mi,{filters:s}),ke.createElement(_x,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),ke.createElement(Ai,{width:e,mode:n.mode,availableHints:n.availableHints}))}import DM from"readline";var Gl,Vl,Ln,BM=new Set([E.MoveCursorLeft,E.EraseInputWord,E.MoveCursorLeftOfWord,E.MoveCursorRight,E.MoveCursorRightOfWord,E.NavToPreviousContainer,E.NavToNextContainer,E.NavPreviousItem,E.NavNextItem,E.NavPreviousItemJump,E.NavNextItemJump,E.SetViewDense,E.SetViewWide,E.Confirm,E.Exit,E.Yank,E.InitCommandLine,E.InitCommandPalette,E.ExitCommandLine,E.CaptureInput,E.EraseInput,E.EraseInputWord,E.HideHelp,E.ViewHelp,E.SetViewDense,E.SetViewWide,E.GetLastCommandFromHistory,E.GetNextCommandFromHistory,E.AutoCompleteCommand]),OM=new Set([E.NavPreviousItem,E.NavNextItem,E.NavPreviousItemJump,E.NavNextItemJump,E.NavToPreviousContainer,E.NavToNextContainer,E.Confirm,E.Exit,E.InitCommandPalette,E.InitMove,E.MoveNextItem,E.MovePreviousItem,E.MoveNextItemJump,E.MovePreviousItemJump,E.MoveToNextContainer,E.MoveToPreviousContainer,E.Delete,E.AddItem,E.EditTitle,E.EditDescription,E.ConfirmMove,E.Edit,E.ViewHelp,E.Yank]),Ux=async e=>{if(e.ctrl&&e.name==="c")return U.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=v(),s=yf(e,n);if(!s||r&&!BM.has(s)||o==="replay"&&n===I.DEFAULT&&OM.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(l){logger.error(l)}},FM=()=>async function(t,n){n.name!=="escape"&&(Ln&&(clearTimeout(Ln),Ln=void 0),await Ux(n))},_M=()=>async function(t){if(t.length===1&&t[0]===27){Ln&&clearTimeout(Ln),Ln=setTimeout(()=>{Ux({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),Ln=void 0},25);return}Ln&&(clearTimeout(Ln),Ln=void 0)};function jx(){Gl&&process.stdin.removeListener("keypress",Gl),Vl&&process.stdin.removeListener("data",Vl),Gl=FM(),Vl=_M(),DM.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Vl),process.stdin.on("keypress",Gl)}async function Hx(){try{let e=lo({});if(a(e))return tn(0,e.message);let t=ht();be(t)&&je(t.value);let n=me(process.cwd());je({gitEmail:await yl(process.cwd()),gitName:await Rr(process.cwd())});let r=be(n)?await el(n.value):Ay();if(a(r))return r;let o=gm();return a(o)?tn(6,o.message):(jx(),be(n)&&tl(n.value),u("Booted Epiq",void 0))}catch(e){return tn(0,wo(e))}}dy();var HM=`${cn.bold("Epiq CLI")}
|
|
92
|
+
`,eu.writeFileSync(t,n,"utf8"),ne.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),u("Local epiq paths ignored",!0)};var bN=async e=>{let t=await j({cwd:e,args:["status","--porcelain"]});return a(t)?t:u("Checked git diff",t.value.stdout.split(`
|
|
93
|
+
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},le=(e,t)=>c(`[${e}] ${t}`),by=async({cwd:e,user:t})=>{let n=Oi(),r=await Xt(e);if(a(r))return le(1,r.message);let o=r.value,s=await wm(o);if(a(s))return le(2,s.message);if(s.value)return le(2,`Cannot initialize Epiq while a git operation is in progress: ${s.value}`);let i=await bN(o);if(a(i))return le(2.5,i.message);if(i.value.length>0)return le(3,`Cannot initialize Epiq with uncommitted changes (${i.value.join(", ")}). Commit or stash your changes first.`);if(fs(o))return le(4,"Epiq project already initialized");let{userId:l,userName:d}=t;if(!l||!d)return le(5,"Missing Epiq user id");let m=await Hg(o);if(a(m))return le(6,m.message);let p=n.stateBranch,f=await Ui({repoRoot:o,branch:p});if(a(f))return le(6,f.message);if(f.value)return le(6,`State branch already exists: ${p}`);let g=await xN({repoRoot:o,stateBranch:p});if(a(g))return le(6,g.message);if(g.value)return IN({repoRoot:o,stateBranch:p});let h=await fd({repoRoot:o,stateBranchName:p});if(a(h))return le(6,h.message);let x=us();if(a(x))return le(7,x.message);let b=tu.join(Lr(),n.projectId),N=await ur({repoRoot:o,stateBranchRoot:b,stateBranchName:p});if(a(N))return le(8,N.message);let S=tu.join(b,".epiq");vN.mkdirSync(S,{recursive:!0});let A=Pg({userId:l,userName:d});if(a(A))return le(9,A.message);for(let pt of A.value){let ao=mg({event:pt,rootDir:b});if(a(ao))return le(9,ao.message)}let T=ar({userId:l}),P=ma(b,T);if(a(P))return le(9,P.message);let M=pd(b,n);if(a(M))return le(9,M.message);let O=await Ta({stateBranchRoot:b,eventFileName:T});if(a(O))return le(10,O.message);let W=await Ce.stage({cwd:b,pathspec:[ct]});if(a(W))return le(10,W.message);let Y=await go({cwd:b,message:"[epiq:init]"});if(a(Y))return le(10,Y.message);let xe=await vy(o);if(a(xe))return le(11,xe.message);let F=ec({repoRoot:o,fileContents:n});if(a(F))return le(12,F.message);let X=await Ce.stage({cwd:o,pathspec:[".epiq/project.json",".gitignore"]});if(a(X))return le(13,X.message);let Ve=await Ce.commit({cwd:o,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(a(Ve))return le(13,Ve.message);let Qn=[],ss=await j({cwd:o,args:["push","-u","origin","HEAD"]});a(ss)&&Qn.push(`[init:14] ${ss.message}`);let ot=await Hs({repoRoot:o,stateBranchRoot:b});return a(ot)&&Qn.push(`[init:15] ${ot.message}`),u("Project initialized",{repoRoot:o,projectId:n.projectId,stateBranch:p,stateBranchRoot:b,defaultEvents:A.value,warnings:Qn})},xN=async({repoRoot:e,stateBranch:t})=>{let n=await On({repoRoot:e});if(a(n))return c(n.message);if(!n.value)return u("No remote",!1);let r=await as({repoRoot:e,branch:t});return a(r)?c(`Could not ask origin whether ${t} exists: ${r.message}`):r},IN=async({repoRoot:e,stateBranch:t})=>{let n=await j({cwd:e,args:["fetch","origin",t]});if(a(n))return le(6,n.message);let r=await j({cwd:e,args:["show",`origin/${t}:${ct}`]});if(a(r))return le(6,[`This repository is already an epiq project: origin has the state branch ${t}.`,"Initialising again would mint a second id for the same board.","","The branch was written before branches carried their identity, so restore",`${ct} from a checkout that has it, for example:`,"",` git show origin/main:${ct} > ${ct}`,"","and commit it; every later boot then stamps the branch, and the next clone adopts it."].join(`
|
|
94
|
+
`));let o;try{o=JSON.parse(r.value.stdout)}catch(x){return le(6,`The identity on origin/${t} is not readable: ${x instanceof Error?x.message:String(x)}`)}let s=ec({repoRoot:e,fileContents:o});if(a(s))return le(12,s.message);let i=await Ce.stage({cwd:e,pathspec:[ct]});if(a(i))return le(13,i.message);let l=await Ce.commit({cwd:e,message:"[epiq:adopt-project]",pathspec:[ct]});if(a(l))return le(13,l.message);let d=us();if(a(d))return le(7,d.message);let m=tu.join(Lr(),o.projectId),p=await js({repoRoot:e,stateBranchName:t});if(a(p))return le(8,p.message);let f=await ur({repoRoot:e,stateBranchRoot:m,stateBranchName:t});if(a(f))return le(8,f.message);let g=[],h=await j({cwd:e,args:["push","-u","origin","HEAD"]});return a(h)&&g.push(`[init:14] ${h.message}`),u("Adopted the project origin already holds",{repoRoot:e,projectId:o.projectId,stateBranch:o.stateBranch,stateBranchRoot:m,defaultEvents:[],warnings:g})};var Zs=(e,t)=>c(`[${e}] ${t}`),xy=async()=>{J("");let e=jn();if(!e.isSetupDone||!e.userName)return Zs(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let t=V(),n=t.userName,r=t.userId;if(!r||!n)return Zs(5,"Missing Epiq user id");let o=await by({cwd:process.cwd(),user:{userId:r,userName:n}});if(a(o))return o;let s="Project initialized!";for(let g of o.value.warnings)s+=` Warn: ${g}`;let l=en(o.value.defaultEvents).filter(a);if(l.length>0)return Zs(16,l.map(g=>g.message).join(`
|
|
95
|
+
`));let d=ve();if(a(d))return Zs(16,d.message);let{rootNodeId:m,nodes:p}=d.value,f=p[m];return f?(U.navigate({contextNode:f,selectedIndex:0}),w({hasProjectDefinition:!0}),u(s,null)):Zs(16,"Unable to resolve initialized root node")};import{ulid as SN}from"ulid";import{ulid as EN}from"ulid";var Iy=null,an=()=>structuredClone(Iy),ei=e=>{Iy=e},Ey=()=>{let{contextNode:e,selectedIndex:t}=v(),r=be(e.id)[t];return r?u("Resolved selected child",r):c("Target node not found")},nu=({id:e,parentId:t,position:n={at:"end"}})=>{let r=be(t).filter(o=>o.id!==e);return Ea(r,n)},Sy=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ue();if(a(r))return c("Unable to resolve user ID");let o=nu({parentId:t,id:e,position:n});return a(o)?o:u("Created pending move state",{id:EN(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Ry=e=>{ei(e);let t=Fs(e,!0);return a(t)?t:u("Node moved successfully",t.value)};function ru(e){let t=Ey();if(a(t))return t;let{contextNode:n,nodes:r}=v();if(!n.parentNodeId)return c("Missing parent node id");let o=r[n.parentNodeId];if(!o)return c("Missing parent node");let s=be(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return c("Current node not found among siblings");let l=s[i+e];if(!l)return c("Missing sibling node");let d=Sy({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(d)?d:Ry(d.value)}function ti(e,t=1){let n=Ey();if(a(n))return n;let{contextNode:r,selectedIndex:o}=v(),s=be(r.id),i=Math.min(Math.max(o+e*t,0),s.length-1),l=i===o?void 0:s[i];if(!l)return c("Missing sibling node");let d=Sy({id:n.value.id,parentId:r.id,position:{at:e===1?"after":"before",sibling:l.id}});return a(d)?d:Ry(d.value)}var Cy=()=>{let e=an();if(!e)return c("No pending move state");let t=e.payload.id,n=e.payload.parent,r=v().nodes[n];if(!r)return c("Move parent not found");let o=be(n).findIndex(s=>s.id===t);return o===-1?c("Moved node not found among rendered children"):(U.navigate({contextNode:r,selectedIndex:o}),u("Synchronized navigation to moved node",null))},zo=(e,t="Moved preview")=>{if(a(e))return an()&&w({mode:I.MOVE}),e;let n=Cy();return a(n)?n:(w({mode:I.MOVE}),u(t,null))},Ny=async()=>{let e=ue();if(a(e))return c("Unable to resolve user ID");let{modifier:t}=oe().commandMeta,{contextNode:n,selectedIndex:r}=v(),o=be(n.id)[r];if(!o)return w({mode:I.DEFAULT}),c("No move target");if(t==="start"){if(o.readonly)return c("Target node is read-only");if(r===-1)return c("No item selected");if(!o.parentNodeId)return c("Target has no parent");let s=be(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return c("Target not found among siblings");let l=s[i-1],d=s[i+1],m=d!=null?{at:"before",sibling:d.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},p=nu({parentId:o.parentNodeId,id:o.id,position:m});return a(p)?p:(ei({id:SN(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...D(e.value)}),w({mode:I.MOVE}),u("Move initialized",null))}if(t==="next")return zo(ti(1));if(t==="previous")return zo(ti(-1));if(t==="jump-next")return zo(ti(1,_s));if(t==="jump-previous")return zo(ti(-1,_s));if(t==="to-next")return zo(ru(1));if(t==="to-previous")return zo(ru(-1));if(t==="confirm"){let s=an();if(!s)return c("No pending move to confirm");let i=await Ie();if(a(i))return i;let l=B([s],i.value);if(a(l))return l;let d=Cy();return a(d)?d:(ei(null),w({mode:I.DEFAULT}),u("Moved item",null))}return t==="cancel"?(ei(null),w({mode:I.DEFAULT}),u("Cancelling move",null)):c("Invalid move modifier")};import{ulid as el}from"ulid";import{monotonicFactory as RN,ulid as CN}from"ulid";var NN=RN(),Za=({name:e,parent:t,rank:n,user:{userId:r}})=>{let o=NN();return u("Created issue events",[{id:CN(),userId:r,action:"add.issue",payload:{id:o,parent:t,name:e,rank:n}}])};var Ay=async(e,t)=>{let n=ue();if(a(n))return c("Unable to resolve user ID");let r=await Ie();if(a(r))return r;let o=r.value;if(!t.inputString)return c(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:l}=v(),d=m=>{let p=B([m],o);if(a(p))return p;let f=C.getNode(p.value[0].result.id);if(!f)return c("Created node not found");if(!f.parentNodeId)return p;let g=C.getNode(f.parentNodeId);return g?(U.navigate({contextNode:g,selectedIndex:C.getSiblings(f.parentNodeId).findIndex(({id:h})=>h===f.id)}),p):c("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=v(),p=C.getNode(m);if(!p)return c("Workspace not found");let f=Wn(p.id,n.value,o);return a(f)?f:d({id:el(),action:"add.board",payload:{id:el(),name:t.inputString,parent:p.id,rank:f.value},...D(n.value)})}if(t.modifier==="swimlane"){let m=ht(s,"BOARD");if(a(m))return c("Unable to add swimlane in this context");let p=Wn(m.value.id,n.value,o);return a(p)?p:d({id:el(),action:"add.swimlane",payload:{id:el(),name:t.inputString,parent:m.value.id,rank:p.value},...D(n.value)})}if(t.modifier==="issue"){let m=ae(i.id)[l],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let A=ht(s,"SWIMLANE");return a(A)?null:A.value})();if(!p)return c("Unable to add issue in this context");let f=Wn(p.id,n.value,o);if(a(f))return f;let g=Za({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(a(g))return g;let h=g.value,x=B([...h],o);if(a(x))return x;if(!x.value[0])return c("Issue creation failed");let S=h.find(A=>A.action==="add.issue")?.payload.id;return S?(U.navigate({contextNode:p,selectedIndex:C.getSiblings(p.id).findIndex(({id:A})=>A===S)}),u("Issue created",null)):c("Unable to determine ticket id")}return u("Success",null)};import BN from"node:os";import Dy from"node:path";import ni from"node:fs";import AN from"node:path";import{z as Kr}from"zod";var ri="command-history.json",TN=20,wN=Kr.object({projectId:Kr.string().min(1),commands:Kr.array(Kr.string()),lastUsedAt:Kr.number().finite()}),MN=Kr.object({projects:Kr.array(wN)}),Ty=()=>{let e=Xs();return a(e)?e:u("Resolved command history path",AN.join(e.value,ri))},PN=()=>{try{let e=ce(process.cwd());return a(e)?null:e.value}catch{return null}},wy=e=>{if(!ni.existsSync(e))return u("No command history recorded",{state:"read",projects:[]});let t;try{t=ni.readFileSync(e,"utf8")}catch(o){return c(`Unable to read ${ri}: ${o instanceof Error?o.message:String(o)}`)}let n;try{n=JSON.parse(t)}catch(o){return u("Unparsable command history",{state:"corrupt",reason:`Invalid ${ri}: ${o instanceof Error?o.message:String(o)}`})}let r=MN.safeParse(n);return r.success?u("Read command history",{state:"read",projects:r.data.projects}):u("Command history in an unknown shape",{state:"corrupt",reason:`Invalid ${ri} shape: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`})},My=({root:e})=>{let t=mn(e);if(a(t))return c(t.message);let n=Ty();if(a(n))return n;let r=wy(n.value);if(a(r))return r;let o=r.value;if(o.state==="corrupt")return c(o.reason);let s=o.projects.find(i=>i.projectId===t.value);return u("Read command history",s?.commands.slice(0,Ts)??[])},Py=({commands:e,root:t=PN(),now:n=Date.now()})=>{if(t===null)return u("No project; command history not stored",null);let r=mn(t);if(a(r))return c(r.message);let o=Ty();if(a(o))return o;let s=o.value,i=wy(s);if(a(i))return i;let l=i.value,d=l.state==="read"?l.projects:[],m=[{projectId:r.value,commands:e.slice(0,Ts),lastUsedAt:n},...d.filter(f=>f.projectId!==r.value)].sort((f,g)=>g.lastUsedAt-f.lastUsedAt).slice(0,TN),p=`${s}.${process.pid}.tmp`;try{ni.writeFileSync(p,JSON.stringify({projects:m},null,2)+`
|
|
96
|
+
`,"utf8"),ni.renameSync(p,s)}catch(f){try{ni.rmSync(p,{force:!0})}catch{}return c(`Unable to write ${ri}: ${f instanceof Error?f.message:String(f)}`)}return u("Stored command history",null)};var LN=e=>e.some(t=>t.action==="init.workspace"),Ly=async(e,t)=>{let n=ke(e);return a(n)?c(n.message):cs({cwd:t,branch:n.value})},kN=e=>{let t=ce(process.cwd());if(a(t))return!1;let n=fe({repoRoot:t.value});return!a(n)&&n.value===e},tl=async e=>{let t=fe({repoRoot:e});if(a(t))return rn(3,t.message);let n=t.value,r=await ur({repoRoot:e,stateBranchRoot:n,stateBranchName:Oi().stateBranch});if(a(r))return rn(3,r.message);let o=tn(n);if(a(o))return rn(3,o.message);if(!LN(o.value.events)){let p=await Ws({worktreeRoot:n,operation:"boot pull",fn:()=>wa(n,()=>Ly(e,n))});if(a(p)?logger.info(3,p.message):p.value===null?logger.info(3,"Another process holds the state worktree, skipped pull"):a(p.value)&&logger.info(3,p.value.message),o=tn(n),a(o))return rn(3,o.message)}let{events:s,unreadable:i}=o.value,l=nn(s,i);if(a(l))return rn(4,l.message);w({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let d=Qi({root:e});a(d)&&logger.info(d.message);let m=My({root:e});return a(m)&&logger.info(m.message),vf(a(m)?[]:m.value),u("Loaded project",void 0)},DN=async e=>{let t=fe({repoRoot:e});if(a(t))return c(t.message);let n=t.value,r=await On({repoRoot:n});if(a(r))return c(r.message);if(!r.value)return u("No remote to pull",void 0);let o=await Ws({worktreeRoot:n,operation:"boot pull",fn:()=>wa(n,()=>(wo("Pulling"),Ly(e,n)))});if(a(o))return We(o.message);if(o.value===null)return u("Another process holds the state worktree",void 0);let s=o.value;if(a(s))return ls(s.message)?(Na("Offline"),u("Offline",void 0)):We(s.message);if(!s.value)return Hr("Already synced"),u("Already synced",void 0);if(!kN(n))return u("Project changed during the pull",void 0);let i=bd(n);return a(i)?i:(Hr("Pulled"),u("Pulled and reloaded",void 0))},nl=e=>{DN(e).then(t=>{a(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${Mo(t)}`)})},ky=()=>{let e=nn([]);return a(e)?rn(4,e.message):(w({hasProjectDefinition:!1,hasInitializingEvents:!1}),u("Booted without a project",void 0))};var ON=e=>e==="~"||e.startsWith("~/")?Dy.join(BN.homedir(),e.slice(1)):e,FN=(e,t)=>{let n=e.trim();if(!n)return c("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):c(`No recent project #${n}`)}let r=ce(Dy.resolve(ON(n)));return a(r)?c(`No epiq project at ${n}`):u("Resolved project path",r.value)},By=async()=>{let e=la();if(J(""),v().hasProjectDefinition)return c("Already in a project; run epiq from another directory");let t=Un({exclude:process.cwd()}),n=a(t)?[]:t.value,r=FN(e,n);if(a(r))return c(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(l){return c(`Unable to enter ${o}: ${l instanceof Error?l.message:String(l)}`)}let i=await tl(o);return a(i)?(process.chdir(s),c(i.message)):(nl(o),u(`Opened ${Eo(o)}`,null))};var rl=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=v(),s=xa(n,t);if(a(s))return c(s.message);let{appliedEvents:i,unappliedEvents:l}=s.value,d=ln();if(a(d))return d;let m=en(i),{fatal:p,skipped:f}=En(m);if(p.length>0)return ln(),w(o),c(p.map(h=>h.message).join(", "));Sn(f);let g=v().nodes[e];return g?(U.navigate({contextNode:g,selectedIndex:r}),u("",{unappliedEvents:l})):(ln(),w(o),c("Board did not exist at that date"))};var Oy=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 _N=20,$N=16,UN=150,ol=null,sl=null;var qr=()=>{ol!==null&&(clearInterval(ol),ol=null),sl!==null&&(clearTimeout(sl),sl=null)},Fy=()=>{qr(),w({mode:I.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},_y=({events:e,startTime:t,durationMs:n})=>{qr();let r=e.length,o=yo(e.map(f=>tr(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=Oy(o),l=Math.max(1,Math.round(n*_N/1e3)),d=Math.max(Math.round(n/l),$N),m=0,p=0;w({mode:I.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),ol=setInterval(()=>{m++;let f=m/l,g=[],h,x;for(;p<r&&i[p]<=f;){let N=e[p],S=Fs(N);if(a(S)){if(To(S)){p++;continue}Fy();return}g.push(...ld(N)),h=N,x=o[p],p++}if(p>=r||m>=l){for(;p<r;p++){let S=Fs(e[p]);if(a(S)&&!To(S))break}let N=v().replay;w({unappliedEvents:[],replay:N&&{...N,progress:1,appliedCount:r}}),qr(),sl=setTimeout(Fy,UN);return}let b=v().replay;w({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:h?x??b?.currentTime??t:b?.currentTime??t,currentLabel:h?il(h):b?.currentLabel??"",flashNodeIds:h?[...new Set(g)]:b?.flashNodeIds??[]}})},d)};var $y=async()=>{let e=ht(v().breadCrumb,"BOARD");if(a(e))return e;let t=await Xt(process.cwd());if(a(t))return c("Unable to locate repo root");let n=fe({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=oe().commandMeta;if(qr(),r==="now"){let l=dr(n.value);if(a(l))return c(l.message);let d=ln();if(a(d))return d;let m=en(l.value),{fatal:p,skipped:f}=En(m);return p.length>0?c(p.map(g=>g.message).join(", ")):(Sn(f),w({mode:I.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),u("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let l=Ia(n.value);if(a(l))return l;let d=r==="prev"?v().eventLog.at(-1):v().unappliedEvents.at(0),m=d===void 0?null:tr(d),p=(d===void 0?null:l.value.get(d.id)??null)??(m===null?null:hs(m));if(p===null)return c(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?p:p+1}else{let l=kr(r||o.trim());if(!l)return c("Invalid peek date");s=l.getTime()}let i=rl({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(i)?i:(w({mode:I.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),u("Peeking",!0))};var Uy=async()=>{let e=ht(v().breadCrumb,"BOARD");if(a(e))return e;let t=await Xt(process.cwd());if(a(t))return c("Unable to locate repo root");let n=fe({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=oe().commandMeta,{dateInput:s,durationInput:i}=ra(r,o);if(qr(),v().syncStatus.status==="syncing")return c("Cannot replay while syncing, try again in a moment");let l=kr(s);if(!l)return c("Invalid replay date");let d=i?na(i):15e3;if(d===null)return c("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=v(),f=rl({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(f))return f;let{unappliedEvents:g}=f.value;return g.length===0?(ln(),w(p),u("Nothing to replay from that point",!0)):(_y({events:g,startTime:m,durationMs:d}),u("Replaying board history",!0))};import{spawn as HN}from"node:child_process";var WN=()=>{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"]}}},jy=async e=>new Promise(t=>{let{command:n,args:r}=WN();try{let o=HN(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(c(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?u("Copied to clipboard",null):c(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(c(`Clipboard tool not available (${n})`))}});var oi=async(e,t)=>{if(!e.trim())return c(`Nothing to copy: ${t} is empty`);let n=await jy(e);return a(n)?n:u(`Copied ${t} to clipboard`,null)},Hy=async e=>{let{breadCrumb:t,selectedNode:n}=v(),r=Ss({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return c("Nothing selected to copy from");switch(e.modifier){case qe.REF:return oi(H(o.id),"ref");case qe.TITLE:return oi(o.title,"title");case qe.DESCRIPTION:return r?oi(r.props?.description??"","description"):c("No issue in scope");case qe.TAGS:{if(!r)return c("No issue in scope");let s=yn(r).map(({name:i})=>i);return oi(s.join(", "),"tags")}case qe.ASSIGNEES:{if(!r)return c("No issue in scope");let s=vn(r).map(({name:i})=>i);return oi(s.join(", "),"assignees")}default:return c("Yank one of: ref, title, description, tags, assignees")}};var Wy=async()=>{J(""),w({mode:I.DEFAULT});let e=ve();if(a(e))return c(e.message);if(e.value.syncStatus.status==="syncing")return c("Sync already in progress");w({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Pa();return a(t)?(w({syncStatus:{msg:t.message,status:"failed"}}),t):(w({mode:I.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{ulid as Gy}from"ulid";var Vy=async()=>{let e=ue();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=ae(t.id)[n];if(!r)return c("Unable to resolve child to delete");let o=await Ie();if(a(o))return o;if(r.context==="COMMENT"){let s=r.id,i=_(t)?t.id:t.parentNodeId;if(!i)return c("Unable to resolve comment issue");let l=v().nodes[i];if(!l||!_(l))return c("Unable to resolve comment issue");let d=l.log?.filter(ph).find(m=>m.payload.id===s);return d?d.payload.author!==e.value.userId?c("You can only delete your own comments"):B([{id:Gy(),action:"delete.issue.comment",payload:{id:s,issue:i},...D(e.value)}],o.value):c("Unable to resolve comment")}return B([{id:Gy(),action:"delete.node",payload:{id:r.id},...D(e.value)}],o.value)};import{ulid as GN}from"ulid";var zy=async()=>{let e=ue();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=ae(t.id)[n];if(!r)return c("Unable to close issue, no target found");if(!_(r))return c("Cannot close in this context");let o=v().nodes[ge];if(!o)return c("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return c("Issue is already closed");let s=await Ie();if(a(s))return s;let i=s.value,l=Rn(o.id,r.id,{at:"end"},e.value,i);if(a(l))return l;let d=B([{id:GN(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...D(e.value)}],i);return a(d)?d:u("Issue closed",null)};import{ulid as VN}from"ulid";var al=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 Ky=async()=>{let e=ue();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=ae(t.id)[n];if(!r)return c("Unable to reopen issue, no target found");let o=r.context==="TICKET"?u("Resolved ticket",r):Nt(r.id,"TICKET");if(a(o))return c("Cannot reopen in this context");let s=o.value,i=v().nodes[ge];if(!i)return c("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return c("Issue is not closed");if(!_(s))return c("Target node is not issue");let l=al(s);if(!l)return c("Unable to resolve previous parent from issue history");if(l===i.id)return c("Previous parent resolves to closed swimlane");let d=v().nodes[l];if(!d)return c("Previous parent no longer exists");let m=await Ie();if(a(m))return m;let p=m.value,f=Rn(d.id,s.id,{at:"end"},e.value,p);if(a(f))return f;let g=B([{id:VN(),action:"reopen.issue",payload:{id:s.id,parent:d.id,rank:f.value},...D(e.value)}],p);return a(g)?g:u("Issue reopened",null)};import{ulid as zN}from"ulid";var qy=async()=>{let e=ue();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=ae(t.id)[n];if(!r)return c("Missing node");if(r.readonly)return c("Cannot rename readonly node");let o=la();if(!o)return c("Provide a title");let s=await Ie();return a(s)?s:B([{id:zN(),action:"edit.title",payload:{id:r.id,name:o},...D(e.value)}],s.value)};import{ulid as KN}from"ulid";var Yy=async()=>{let e=ue();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=oe().commandMeta,r=(t||n).trim();if(!r)return c("Provide a tag");let o=C.findTagByName(r);if(!o)return c(`Tag "${r}" does not exist`);let{selectedNode:s}=v();if(!s)return c("Invalid untag target");let i=Nt(s.id,"TICKET");if(a(i))return c("Unable to untag issue in this context");let l=i.value;if(!_(l))return c("Target node is not issue");if(!(l.props.tags??[]).includes(o.id))return c("Issue is not tagged with that tag");let m=await Ie();return a(m)?m:B([{id:KN(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...D(e.value)}],m.value)};import{ulid as ou}from"ulid";var Xy=async()=>{let e=ue();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=oe().commandMeta,r=(t||n).trim();if(!r)return c("Provide a tag");let{selectedNode:o}=v();if(!o)return c("Invalid tag target");let s=Nt(o.id,"TICKET");if(a(s))return c("Unable to tag issue in this context");let i=s.value;if(!_(i))return c("Target node is not issue");let l=await Ie();if(a(l))return l;let d=C.findTagByName(r),m=d?.id??ou();return(i.props.tags??[]).includes(m)?c("Already tagged with that tag"):B([...d?[]:[{id:ou(),action:"create.tag",payload:{id:m,name:r},...D(e.value)}],{id:ou(),action:"add.issue.tag",payload:{id:i.id,tag:m},...D(e.value)}],l.value)};import{ulid as su}from"ulid";var si=({events:e,registry:t,logFileNames:n})=>{let r=new Map(n),o=new Set;for(let s of e)s.userId&&(r.has(s.userId)||r.set(s.userId,""),o.add(s.userId));for(let s of Object.values(t))r.set(s.id,s.name);return[...r.entries()].map(([s,i])=>({id:s,name:i,isExternal:!o.has(s)}))},Jy=({authorName:e,authorEmail:t,owners:n,registry:r})=>{let o=Qe(t),s=n.get(o),i=s?r[s]:void 0;return s?{...Ke(s,i?.name),resolved:!0}:{...Ke(o||e,e),resolved:!1}};var ll=e=>{let{eventLog:t=[],contributors:n}=v();return si({events:t,registry:n,logFileNames:cr(e)})};var Qy=async()=>{let e=ue();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=oe().commandMeta,r=(t||n).trim();if(!r)return c("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return c("Provide an assignee");let{selectedIndex:i,contextNode:l}=v(),d=ae(l.id)[i];if(!d)return c("Invalid assign target");let m=Nt(d.id,"TICKET");if(a(m))return c("Unable to assign issue in this context");let p=m.value;if(!_(p))return c("Target node is not issue");let f=await Ie();if(a(f))return f;let g=ll(f.value),h=!o&&s.toLowerCase()==="me",x,b;if(h)x=e.value.userId,b=g.find(A=>A.id===x)?.name??e.value.userName;else{let A=g.filter(P=>P.name===s);if(A.length>1)return c(`"${s}" matches ${A.length} contributors (${A.map(P=>P.id).join(", ")}). Assign from the GUI to choose by id.`);let T=A[0];if(!T&&!o)return c(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);x=T?.id??su(),b=T?.name??s}if((p.props.assignees??[]).includes(x))return c("Assignee already assigned");let S=!!v().contributors[x];return B([...S?[]:[{id:su(),action:"create.contributor",payload:{id:x,name:b},...D(e.value)}],{id:su(),action:"add.issue.assignee",payload:{id:p.id,assignee:x},...D(e.value)}],f.value)};import{ulid as qN}from"ulid";var Zy=async()=>{let e=ue();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=oe().commandMeta,r=(t||n).trim();if(!r)return c("Provide an assignee to remove");let{selectedNode:o}=v();if(!o)return c("Invalid unassign target");let s=Nt(o.id,"TICKET");if(a(s))return c("Unable to unassign in this context");let i=s.value;if(!_(i))return c("Target node is not issue");let l=i.props.assignees??[],d=r.toLowerCase()==="me",m=await Ie();if(a(m))return m;let p=d?l.filter(g=>g===e.value.userId):ll(m.value).filter(g=>g.name===r&&l.includes(g.id)).map(g=>g.id);if(p.length>1)return c(`"${r}" matches ${p.length} assignees (${p.join(", ")}). Unassign from the GUI to choose by id.`);let f=p[0];return f?B([{id:qN(),action:"remove.issue.assignee",payload:{id:i.id,assignee:f},...D(e.value)}],m.value):c(d?"Issue is not assigned to you":`Issue is not assigned to "${r}"`)};import{ulid as ev}from"ulid";var YN=e=>{let t=e.trim(),n=yr(),r=n?Wh(t):null;if(!n||!r)return{ok:!0,md:t,anchored:!1};let o=qa();if(!o||o.sha!==n)return{ok:!1,reason:"No diff is open"};let s=Gh(o.rows,Math.max(0,v().selectedIndex));if(!s)return{ok:!1,reason:"That line is not in a file"};let i=Vh(o.rows,s,r.start,r.end);return i.ok?{ok:!0,anchored:!0,md:Sh({filePath:i.value.filePath,start:i.value.start,end:i.value.end,side:"additions",endSide:"additions",note:r.note,sha:n,snippet:i.value.snippet})}:{ok:!1,reason:i.reason}},tv=async e=>{let t=YN(e.inputString);if(!t.ok)return c(t.reason);let{md:n,anchored:r}=t;if(!n)return c("Provide a comment");if(n.length>4e3)return c(r?`The note and the ${n.length} characters of quoted lines exceed ${4e3}; comment on fewer lines`:`Cannot exceed ${4e3} characters`);let o=ue();if(a(o))return c("Unable to resolve user ID");let{breadCrumb:s,selectedNode:i}=v(),l=ht([...s,i],"TICKET");if(a(l))return c("Edit target must be an issue");let d=l.value;if(!d)return c("Invalid comment target");let m=d.context==="TICKET"?u("Resolved ticket",d):Nt(d.id,"TICKET");if(a(m))return c("Unable to comment on issue in this context");let p=m.value;if(!_(p))return c("Target node is not issue");let f=await Ie();if(a(f))return f;let g=await B([{id:ev(),action:"add.issue.comment",payload:{id:ev(),issue:p.id,author:o.value.userId,md:n},...D(o.value)}],f.value);return r&&!a(g)&&Vr(null),g};import{ulid as tA}from"ulid";var cl=e=>e.userName?.trim()?e.preferredEditor?.trim()?null:"no editor configured":"no username configured",XN=e=>{let t=gt();return a(t)?cl({userName:e.userName,preferredEditor:e.preferredEditor})??t.message:cl(t.value)},ii=()=>{let e=fn();return a(e)?c(e.message):u("Read auto sync settings",{enabled:e.value.autoSync===!0,intervalMs:mo(e.value.autoSyncDebounceMs),blockedReason:XN(e.value)})},Ko=e=>{let t=e.intervalMs===void 0?void 0:uo(e.intervalMs);if(e.intervalMs!==void 0&&t===null)return c(`Auto sync interval must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=ii();if(a(n))return n;let r=Ft({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncDebounceMs:t}});if(a(r))return c(r.message);$e({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncIntervalMs:t}});let o=ii();return a(o)?u("Changed auto sync settings",{...n.value,...e.enabled===void 0?{}:{enabled:e.enabled},...t==null?{}:{intervalMs:t}}):o};var nv=()=>{let e=oe().commandMeta.inputString,t=uo(e);if(t===null)return c(`Auto sync duration must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=Ko({intervalMs:t});return a(n)?n:u(`Auto sync interval set to ${t}ms`,null)};var rv=()=>{let e=oe().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return c("Invalid response");let t=_p(e),n=Ko({enabled:t===!0});return a(n)?n:u(`Auto sync set to "${e}"`,null)};import{ulid as ZN}from"ulid";var iu=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=2),ov="",sv=new Map,JN=15e3;var QN=async(e,t)=>{let n=`${e} ${t??""}`,r=sv.get(n);if(r&&Date.now()-r.at<$a(JN))return u("Cached author scan",r.authors);let o=await Le({cwd:e,args:["log","--branches",...t?["--not",t]:[],`--format=%an${ov}%ae`]});if(o.exitCode!==0)return c(`Could not read this repository's history: ${(o.stderr??"").trim()||`git exited ${o.exitCode}`}`);let s=new Map;for(let i of(o.stdout??"").split(`
|
|
97
|
+
`)){let l=i.lastIndexOf(ov);if(l===-1)continue;let d=i.slice(0,l),m=Qe(i.slice(l+1));if(!nr(m))continue;let p=s.get(m)??{names:new Set,commits:0};d&&p.names.add(d),p.commits+=1,s.set(m,p)}return sv.set(n,{at:Date.now(),authors:s}),u("Scanned repository authors",s)},Mn=async({repoRoot:e,stateBranch:t,names:n,links:r})=>{let o=await QN(e,t);if(a(o))return c(o.message);let s=o.value,i=new Map;for(let d of Object.values(r)){if(d.tombstoned)continue;let m=i.get(d.email)??new Set;m.add(d.contributor),i.set(d.email,m)}let l=new Set(n.flatMap(d=>iu(d??"")));return u("Found candidates",[...s.entries()].map(([d,m])=>({email:d,names:[...m.names],commits:m.commits,looksLikeYours:[...m.names].some(p=>iu(p).some(f=>l.has(f)))||iu(d.split("@")[0]??"").some(p=>l.has(p)),claimedBy:[...i.get(d)??[]]})).sort((d,m)=>d.looksLikeYours===m.looksLikeYours?m.commits-d.commits:Number(m.looksLikeYours)-Number(d.looksLikeYours)))},xr=e=>e.filter(t=>t.claimedBy.length===0);var iv=()=>{let e=Lc();if(!e)return u("Nothing here to decline",null);let t=fn(),n=a(t)?[]:t.value.declinedEmailBoards??[],r=[...new Set([...n,e])],o=Ft({declinedEmailBoards:r});return a(o)?c(o.message):($e({declinedEmailBoards:[...new Set([...V().declinedEmailBoards??[],e])]}),u("Declined",null))},av=async()=>{let e=oe().commandMeta.inputString.trim();if(e==="none"){let N=iv();return a(N)?N:u("Left unlinked. Your commits will show the name git signed them with. Run :config emails again to change that.",null)}let{userId:t,userName:n,gitName:r}=V();if(!t)return c("Set a username first with :config username");let o=ve();if(a(o))return c("Board is not loaded");let s=ce(process.cwd());if(a(s))return c(s.message);let i=ke(s.value),l=await Mn({repoRoot:s.value,stateBranch:a(i)?void 0:i.value,names:[n,r],links:o.value.emailLinks});if(a(l))return l;let m=xr(l.value);if(So(m.map(N=>N.email)),m.length===0){if(!Op()){let N=iv();if(a(N))return N}return u("No unclaimed addresses in this history.",null)}if(!e)return w({mode:I.IDENTITY}),u("Opened identity",null);let p=e.split(/[,\s]+/).filter(Boolean),f=[],g=[];for(let N of p){let S=m.find(A=>A.email===Qe(N));if(!S){g.push(N);continue}f.includes(S)||f.push(S)}if(g.length>0)return c(`Not on the list: ${g.join(", ")}. Pick one of ${m.map(N=>N.email).join(", ")}.`);let h=fe({repoRoot:s.value});if(a(h))return h;let x=f.map(N=>({id:ZN(),action:"link.contributor.email",payload:{contributor:t,email:N.email},userId:t})),b=B(x,h.value);return a(b)?c(b.message):u(`Claimed ${f.map(N=>N.email).join(", ")}. Every commit by ${f.length===1?"that address":"those addresses"} is now yours.`,null)};import{ulid as eA}from"ulid";var lv=()=>{let e=oe().commandMeta.inputString.trim(),{userId:t}=V();if(!t)return c("Set a username first with :config username");let n=ve();if(a(n))return c("Board is not loaded");let r=gn(n.value.emailLinks,t);if(r.length===0)return c("You have not claimed any addresses.");if(!e)return c(`Which one? ${r.join(", ")}.`);let o=r.find(d=>d===Qe(e));if(!o)return c(`You have not claimed ${e}. Yours: ${r.join(", ")}.`);let s=ce(process.cwd());if(a(s))return s;let i=fe({repoRoot:s.value});if(a(i))return i;let l=B([{id:eA(),action:"unlink.contributor.email",payload:{contributor:t,email:o},userId:t}],i.value);return a(l)?c(l.message):u(`Unclaimed ${o}`,null)};var cv=()=>{let e=oe().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return c("Invalid response");let n=Ft({logLevel:e});return a(n)?n:($e({logLevel:e}),u(`Auto sync set to "${e}"`,null))};var dv=e=>{let t=e.inputString.trim();switch(e.modifier){case he.USERNAME:{if(process.env[Dn])return c(`Cannot change the configured user while ${Dn} names this process`);let n=fn();if(a(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,l=r||tA();if(!i||!l)return c("Unable to resolve user name or id");let d=Ft({userName:i,userId:l,preferredEditor:o??""});return a(d)?d:($e({userName:i,userId:l}),u(`Username set to "${i}"`,null))}case he.EDITOR:{if(!t)return c("No editor provided");let n=Ft({preferredEditor:t});return a(n)?n:($e({preferredEditor:t}),u(`Editor configuration set to "${t}"`,null))}case he.VIEW:{if(t!=="wide"&&t!=="dense")return c("Invalid view mode");let n=Ft({viewMode:t});return a(n)?n:($e({viewMode:t}),u(`View set to "${t}"`,null))}case he.EMAILS:return av();case he.EMAILS_UNCLAIM:return lv();case he.AUTOSYNC:return rv();case he.LOG_LEVEL:return cv();case he.SYNC_DEBOUNCE_MS:return nv();case he.ATTACHMENT_MAX_KB:return Zp();default:return c("Unknown config command")}};var au=()=>{let e=$p(),t=v().mode;if(!(t!==I.COMMAND_LINE&&t!==I.DEFAULT)){if(!e){w({mode:I.DEFAULT});return}w({mode:I.COMMAND_LINE}),J(e)}};var dl=[{systemOnly:!0,intent:G.Move,description:"Internal move-state command",mode:I.COMMAND_LINE,action:Ny},{intent:G.Delete,description:"Delete the currently selected node",mode:I.COMMAND_LINE,action:Vy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:I.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=oe().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>Be(R.FILTER).map(l=>l.split(n)[0]).includes(i))(r))return c("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return Oe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:I.DEFAULT})),u("Filter updated",null)}},{intent:G.ViewHelp,description:"Open the help screen",mode:I.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return br({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),w({mode:I.HELP}),u("Viewing help",null)}},{intent:G.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:I.COMMAND_LINE,action:zy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:I.COMMAND_LINE,action:Ky,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Init,description:"Initialize Epiq in the current git repository",mode:I.COMMAND_LINE,action:xy,onSuccess:au},{intent:G.OpenProject,description:"Open a recently used epiq project, by number or path",mode:I.COMMAND_LINE,action:By,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.NewItem,description:"Create a new board, swimlane, or issue",mode:I.COMMAND_LINE,action:Ay,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Rename,description:"Rename the currently selected node",mode:I.COMMAND_LINE,action:qy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.UntagTicket,description:"Remove a tag from the selected issue",mode:I.COMMAND_LINE,action:Yy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.TagTicket,description:"Add or create a tag on the selected issue",mode:I.COMMAND_LINE,action:Xy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.AssignUserToTicket,description:"Assign a user to the selected issue",mode:I.COMMAND_LINE,action:Qy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:I.COMMAND_LINE,action:Zy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Comment,description:"Add a comment to the selected issue",mode:I.COMMAND_LINE,action:async(e,t)=>tv(t),onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Sync,description:"Pull, commit, and push Epiq state",mode:I.COMMAND_LINE,action:Wy},{intent:G.Peek,description:"View board state at another point in time",mode:I.COMMAND_LINE,action:$y},{intent:G.Replay,description:"Replay board history forward from a point in time",mode:I.COMMAND_LINE,action:Uy},{intent:G.Export,description:"Export the current board layout to markdown",mode:I.COMMAND_LINE,action:async()=>{let e=await fy();return a(e)?e:(w({mode:I.DEFAULT}),u("Export successful",!0))}},{intent:G.Exit,description:"Exit the application",mode:I.COMMAND_LINE,action:async()=>(U.exit(),u("Exit successful",!0))},{intent:G.Edit,description:"Edit title or description",mode:I.COMMAND_LINE,action:async(e,t)=>yy(t),onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:I.COMMAND_LINE,action:async(e,t)=>Hy(t),onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:I.COMMAND_LINE,action:(e,t)=>dv(t),onSuccess:au}];var nA=new Set(["peek","replay","filter","view-help","yank"]),Wt=async({isForceExecutedBySystem:e=!1}={})=>{let{value:t,commandMeta:{command:n,validity:r,modifier:o,inputString:s}}=oe();if(!n)return c("No command to confirm");if(!e&&r===xn.Invalid)return c("Invalid command");let i=ka(n);hf();let{readOnly:l}=v();if(l&&!nA.has(i))return ws({status:Zn.Fail,message:"Command not available in readonly state",value:null});let d=dl.filter(f=>e||f.systemOnly!==!0).find(f=>f.intent===i);if(!d)return ws({status:Zn.Fail,message:"Command not found",value:null});let m;try{m=await d.action(d,{command:n,inputString:s,modifier:o})}catch(f){return ws({status:Zn.Fail,message:f instanceof Error?f.message:"Command failed",value:null})}if(a(m))return ws(m);let p=!e;if(yf({addToHistory:p,line:t}),p){let f=Py({commands:oe().commandHistory});a(f)&&logger.info(f.message)}return d.onSuccess?.(),V().autoSync&&La(),m};var ul=[{intent:E.Exit,mode:I.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(w({mode:I.COMMAND_LINE}),J("move cancel"),Wt({isForceExecutedBySystem:!0}))},{intent:E.InitMove,mode:I.DEFAULT,description:"[m] move",action:()=>(w({mode:I.COMMAND_LINE}),J("move start"),Wt({isForceExecutedBySystem:!0}))},{intent:E.ConfirmMove,mode:I.MOVE,description:"[m] confirm move",action:()=>(w({mode:I.COMMAND_LINE}),J("move confirm"),Wt({isForceExecutedBySystem:!0}))}],ml=[{intent:E.MovePreviousItem,mode:I.MOVE,action:()=>an()?(w({mode:I.COMMAND_LINE}),J("move previous"),Wt({isForceExecutedBySystem:!0})):c("No pending move")},{intent:E.MoveNextItem,mode:I.MOVE,description:"[arrows/hjkl] move (shift x5)",action:()=>an()?(w({mode:I.COMMAND_LINE}),J("move next"),Wt({isForceExecutedBySystem:!0})):c("No pending move")},{intent:E.MovePreviousItemJump,mode:I.MOVE,action:()=>an()?(w({mode:I.COMMAND_LINE}),J("move jump-previous"),Wt({isForceExecutedBySystem:!0})):c("No pending move")},{intent:E.MoveNextItemJump,mode:I.MOVE,action:()=>an()?(w({mode:I.COMMAND_LINE}),J("move jump-next"),Wt({isForceExecutedBySystem:!0})):c("No pending move")}],uv=[{intent:E.MoveToNextContainer,mode:I.MOVE,action:()=>an()?(w({mode:I.COMMAND_LINE}),J("move to-next"),Wt({isForceExecutedBySystem:!0})):c("No pending move")},{intent:E.MoveToPreviousContainer,mode:I.MOVE,action:()=>an()?(w({mode:I.COMMAND_LINE}),J("move to-previous"),Wt({isForceExecutedBySystem:!0})):c("No pending move")}];var mv={[re.WORKSPACE]:[...ul,...ml],[re.BOARD]:[...ul,...ml],[re.SWIMLANE]:[...ul,...ml,...uv],[re.TICKET]:[],[re.FIELD]:[],[re.FIELD_LIST]:[],[re.TEXT]:[],[re.COMMENT]:[]};import oA from"node:fs";import sA from"node:path";import{spawn as rA}from"node:child_process";function pv(e){let t=process.platform,o=rA(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 fv=e=>{let t=ce(process.cwd());if(a(t))return c("Unable to resolve project root");let n=fe({repoRoot:t.value});if(a(n))return c(n.message);let r=Or(e.hash,e.ext),o=sA.join(ps(n.value),r);return oA.existsSync(o)?(pv(o),u(`Opened ${e.name}`,null)):c("Attachment file not found \u2014 run :sync to fetch it")};var gv=()=>{J("");let{pendingNavTarget:e}=vr();w({mode:I.DEFAULT}),e&&U.navigate(e),br({pendingNavTarget:void 0})},hv=[{intent:E.ExitCommandLine,mode:I.HELP,action:()=>(gv(),u("Exiting help",null))},{intent:E.Exit,mode:I.HELP,action:()=>(gv(),u("Closed help",null))},{intent:E.NavPreviousItem,mode:I.HELP,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(U.navigateToPreviousItem(),u("Navigating to previous help item",null))},{intent:E.NavNextItem,mode:I.HELP,action:()=>(U.navigateToNextItem(),u("Navigating to next help item",null))},{intent:E.NavPreviousItemJump,mode:I.HELP,action:()=>(U.jumpToPreviousItem(),u("Jumping to previous help item",null))},{intent:E.NavNextItemJump,mode:I.HELP,action:()=>(U.jumpToNextItem(),u("Jumping to next help item",null))},{intent:E.NavToPreviousContainer,mode:I.HELP,action:()=>(U.navigateToPreviousContainer(),u("Navigating to previous help container",null))},{intent:E.NavToNextContainer,mode:I.HELP,action:()=>(U.navigateToNextContainer(),u("Navigating to next help container",null))}];var yv=()=>{J(""),w({mode:I.DEFAULT})},vv=[{intent:E.Confirm,mode:I.IDENTITY,description:"[enter] claim the first",action:()=>{let[e]=Ro();return e?(w({mode:I.COMMAND_LINE}),J(`config emails ${e}`),u("Proposed claim",null)):u("Nothing left to claim",null)}},{intent:E.ExitCommandLine,mode:I.IDENTITY,action:()=>(yv(),u("Closed identity",null))},{intent:E.Exit,mode:I.IDENTITY,description:"[esc] close",action:()=>(yv(),u("Closed identity",null))}];var iA=e=>{w({mode:I.COMMAND_LINE});let{pendingNavTarget:t}=vr();t&&U.navigate(t),br({pendingNavTarget:void 0}),J(`${e} `)},bv=()=>{J("");let{pendingNavTarget:e}=vr();e&&U.navigate(e),br({pendingNavTarget:void 0}),w({mode:I.DEFAULT})},xv=[{intent:E.InitCommandPalette,mode:I.DEFAULT,description:"[?] command palette",action:()=>{J("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return br({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),w({mode:I.PALETTE}),u("Opening command palette",null)}},{intent:E.Confirm,mode:I.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!rr(e))return c("Command only applicable on text nodes");if(e.props.disabled)return c("Command is not available in this context");let t=e.title;return t?(iA(t),u("Selected command",t)):u("No command selected",null)}},{intent:E.ExitCommandLine,mode:I.PALETTE,action:()=>(bv(),u("Exiting palette",null))},{intent:E.Exit,mode:I.PALETTE,action:()=>(bv(),u("Closed command palette",null))},{intent:E.NavPreviousItem,mode:I.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:E.NavNextItem,mode:I.PALETTE,action:()=>(U.navigateToNextItem(),u("Navigating to next item",null))},{intent:E.NavToPreviousContainer,mode:I.PALETTE,action:()=>(U.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:E.NavToNextContainer,mode:I.PALETTE,action:()=>(U.navigateToNextContainer(),u("Navigating to next container",null))}];var Iv=()=>{let e=yr();if(!e)return u("Nothing to comment on here",null);let t=qa();if(!t||t.sha!==e)return c("The diff is still loading");let{selectedIndex:n}=v(),r=Math.max(0,n),o=Fd(t.rows,Vd(e)??r,r);return o.ok?(w({mode:I.COMMAND_LINE}),J(`${R.COMMENT} ${Hh(o.value.start,o.value.end)} `),u("Commenting on a diff line",null)):c(o.reason)},Ev=[{intent:E.InitCommandLine,mode:I.DEFAULT,description:"[:] write command",action:()=>(w({mode:I.COMMAND_LINE}),J(""),u("Entering command line mode",null))},...hv,...vv,...xv,{intent:E.AddItem,mode:I.DEFAULT,description:"[n] new...",action:()=>(w({mode:I.COMMAND_LINE}),J(`${R.NEW} `),u("Adding new item",null))},{intent:E.Delete,mode:I.DEFAULT,description:"[d] delete",action:()=>(w({mode:I.COMMAND_LINE}),J(`${R.DELETE} `),u("Deleting item",null))},{intent:E.Confirm,mode:I.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!be(e?.id??"")?.length){let r=e?C.getAttachment(e.id):void 0;if(r)return fv(r);if(yr())return Iv();if(e?.title===Ne.DESCRIPTION)return w({mode:I.COMMAND_LINE}),J(`${R.EDIT} description `),u("Propose command",!0);if(e?.title===Ne.ASSIGNEES)return w({mode:I.COMMAND_LINE}),J(`${R.ASSIGN} `),u("Propose command",!0);if(e?.title===Ne.TAGS)return w({mode:I.COMMAND_LINE}),J(`${R.TAG} `),u("Propose command",!0);if(t.title===Ne.DESCRIPTION&&e?.context==="TEXT")return w({mode:I.COMMAND_LINE}),J(`${R.EDIT} description `),u("Propose command",!0)}return U.enterChildNode(),u("Entering context",null)}},{intent:E.OpenInEditor,mode:I.DEFAULT,action:()=>{let{selectedNode:e,contextNode:t}=v(),n=t.parentNodeId,o=!!n&&t.id===we(n,"diff")?e?.id:yr()??void 0;return o?Js({sha:o}):u("Nothing here opens in an editor",null)}},{intent:E.MarkDiffLine,mode:I.DEFAULT,action:()=>{let e=yr();if(!e)return u("Nothing to mark here",null);let{selectedIndex:t}=v(),n=Vd(e);return Vr(n===t?null:{sha:e,row:Math.max(0,t)}),u("Marked diff line",null)}},{intent:E.CommentOnDiffLine,mode:I.DEFAULT,action:()=>yr()?Iv():u("Nothing to comment on here",null)},{intent:E.Yank,mode:I.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=v(),t=e?.title===Ne.DESCRIPTION?qe.DESCRIPTION:e?.title===Ne.TAGS?qe.TAGS:e?.title===Ne.ASSIGNEES?qe.ASSIGNEES:qe.REF,r=Be(R.YANK).includes(t)?t:qe.REF;return w({mode:I.COMMAND_LINE}),J(`${R.YANK} ${r}`),u("Propose command",!0)}},{intent:E.EditTitle,mode:I.DEFAULT,description:"[r] rename title",action:()=>(w({mode:I.COMMAND_LINE}),J(`${R.EDIT} title ${v().selectedNode?.title}`),u("Exiting context",null))},{intent:E.EditDescription,mode:I.DEFAULT,description:"[e] edit desc",action:()=>(w({mode:I.COMMAND_LINE}),J(`${R.EDIT} description `),u("Exiting context",null))},{intent:E.Exit,mode:I.DEFAULT,description:"[q] exit context",action:()=>(U.enterParentNode(),u("Exiting context",null))},{intent:E.NavPreviousItem,mode:I.DEFAULT,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(U.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:E.NavNextItem,mode:I.DEFAULT,action:()=>(U.navigateToNextItem(),u("Navigating to next item",null))},{intent:E.NavPreviousItemJump,mode:I.DEFAULT,action:()=>(U.jumpToPreviousItem(),u("Jumping to previous item",null))},{intent:E.NavNextItemJump,mode:I.DEFAULT,action:()=>(U.jumpToNextItem(),u("Jumping to next item",null))},{intent:E.NavToPreviousContainer,mode:I.DEFAULT,action:()=>(U.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:E.NavToNextContainer,mode:I.DEFAULT,action:()=>(U.navigateToNextContainer(),u("Navigating to next container",null))}];var aA=500,lA=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Sv=e=>{let t=lA(e);t&&aa(n=>(n+t).slice(0,aA))};var cA=[I.COMMAND_LINE,I.PALETTE],dA=e=>e==="edit title "?v().selectedNode?.title??"":"",uA=e=>[{intent:E.MoveCursorLeft,mode:e,action:()=>(Gc(-1),u("Moving cursor left",null))},{intent:E.MoveCursorRight,mode:e,action:()=>(Gc(1),u("Moving cursor right",null))},{intent:E.MoveCursorLeftOfWord,mode:e,action:()=>(Vc("left"),u("Moving cursor left of word",null))},{intent:E.MoveCursorRightOfWord,mode:e,action:()=>(Vc("right"),u("Moving cursor right of word",null))},{intent:E.AutoCompleteCommand,mode:e,action:()=>(aa((t,{remainder:n})=>{let r=n?t+n:t;return r+dA(r)}),u("Auto-completing command",null))},{intent:E.CaptureInput,mode:e,action:(t,{sequence:n})=>(Sv(n??""),u("Capturing input",null))},{intent:E.EraseInput,mode:e,action:()=>(ff(),u("Erasing input",null))},{intent:E.EraseInputWord,mode:e,action:()=>(gf(),u("Erasing input word",null))}],Rv=[{intent:E.Confirm,mode:I.COMMAND_LINE,action:()=>(Wt(),u("Executing command",null))},{intent:E.ViewHelp,mode:I.DEFAULT,action:()=>(w({mode:I.HELP}),u("Viewing help",null))},...cA.flatMap(uA),{intent:E.ExitCommandLine,mode:I.COMMAND_LINE,action:()=>(bf(),w({mode:I.DEFAULT}),u("Exiting command line",null))},{intent:E.GetLastCommandFromHistory,mode:I.COMMAND_LINE,action:()=>(xf(),u("Getting last command from history",null))},{intent:E.GetNextCommandFromHistory,mode:I.COMMAND_LINE,action:()=>(If(),u("Getting next command from history",null))}];var lu=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},Cv=({keys:e})=>e.length===1?0:1,Nv=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(lu).filter(r=>r!==null).sort((r,o)=>Cv(r)-Cv(o))};function Av(e,t,n){let r=t[e];if(!r)return c("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?c("buildBreadCrumb(): node is not connected to root"):(o.reverse(),u("Breadcrumb built",o))}var Tv=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 At,cu,du=new Set,uu=()=>{for(let e of du)e()},pA=e=>(du.add(e),()=>du.delete(e));function mu(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return c("derive(): contextNodeId is missing");if(!r)return c("derive(): rootNode is missing");if(!o[r])return c("derive(): unable to find root node");let l=o[t];if(!l)return c("Unable to derive state, contextNode not found");let d=Av(t,o,r);if(a(d))return logger.error(d.message),d;let m=d.value,{context:p}=l,f=[...Ev,...mv[p]??[],...Rv],g=Nv(f,n),h=Tv(f),x=fA(o,s),b=x[t]?.[e.selectedIndex]??null;return u("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:g,availableActions:f,actionIndex:h,selectedNode:b,renderedChildrenIndex:x})}var v=()=>{if(!At)throw new Error("State not initialized. Call initWorkspaceState() first.");return At},ve=()=>At?u("Retrieved state",At):c("State not initialized. Call initWorkspaceState() first.");Lp(e=>At?gn(At.emailLinks,e):[]);function Os(e){cu=e;let t=ce(process.cwd()),n=!1;if(!a(t)){let s=Tt(t.value);if(a(s))return c(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},emailLinks:{},mode:I.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=mu(r);return a(o)?o:(At=o.value,uu(),u("State initialized",null))}var Yr=!1,ai=null;function Oe(e){let t=v(),n=e(t);if(Yr)return n.nodes!==t.nodes&&(Ir=null),ai=n,At={...t,...n},u("State updated",null);let r=mu(n);return a(r)?c(r.message??"Unable to update state"):(At=r.value,uu(),u("State updated",null))}function ba(e){if(Yr)return u("Joined batch",e());Yr=!0,ai=null,Ir=new Set;let t=()=>{let n=ai;if(Yr=!1,ai=null,n===null)return null;let r=mu(n);return a(r)?c(r.message??"Unable to update state"):(At=r.value,uu(),u("State updated",null))};try{let n=e(),r=t();return r&&a(r)?c(r.message):u("State updated",n)}finally{Yr&&t()}}var Eg=()=>Yr,w=e=>Oe(t=>({...t,...e}));function Xr(e,t,n){if(!Yr)return Oe(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=v(),o=r[e]??{};if(e==="nodes"){let i=o[t],l=n;i?.parentNodeId&&Ir?.add(i.parentNodeId),l.parentNodeId&&Ir?.add(l.parentNodeId)}o[t]=n;let s={...r,[e]:o};return ai=s,At={...r,...s},u("State updated",null)}var te=()=>mA(pA,v,v),Ir=null,wv=null,fA=(e,t)=>{let n=At?.renderedChildrenIndex,r=n!==void 0&&Ir!==null&&e===wv&&t.length===0&&At?.filters.length===0,o;if(r){o={...n};let s=vg(e,Ir);for(let i of Ir){let l=s[i];l?o[i]=l:delete o[i]}}else o=yg(e,t);return wv=e,Ir=new Set,o},ae=e=>v()?.renderedChildrenIndex[e]??[],ln=()=>cu?Os(cu):c("Cannot reset state: no initial workspace found"),Ut=()=>At!==void 0;var Nt=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return c("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 c(`No ancestor found for context: ${t}`)},pu=(e,t)=>{let{nodes:n}=v(),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},Er=(e,t)=>e?e.readonly?c({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:c("Node not found"),C={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return c("Contributor not found");if(n.userId&&n.userId!==t)return c("Contributor is already linked to another user");let r={...n,userId:t},o=Oe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?c("Unable to link contributor to user"):u("Linked contributor to user",r)},deleteNode(e){C.deleteNodes([e])},deleteNodes(e){e.length!==0&&Oe(t=>{let n={...t.nodes};for(let r of e)delete n[r];return{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return c("Unable to create comment, missing issue");if(!_(t))return c("Can only comment on issues");let n=Xr("comments",e.id,{...e,deleted:!1});return a(n)?c("Unable to create comment"):u("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return c("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return c("Unable to edit comment, missing issue");if(!_(r))return c("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=Xr("comments",e,o);return a(s)?c("Unable to edit comment"):u("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return c("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=Xr("comments",e,n);return a(r)?c("Unable to delete comment"):u("Deleted comment",n)},getComment(e){return v().comments?.[e]},getCommentsByIssue(e){return Object.values(v().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(v().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 c("Unable to create attachment, missing issue");if(!_(t))return c("Can only attach to issues");let n=Oe(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?c("Unable to create attachment"):u("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return c("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=Oe(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return a(r)?c("Unable to delete attachment"):u("Deleted attachment",n)},getAttachment(e){return v().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(v().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(v().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}=v(),r=n[e];if(!r)return c("Edit target node not found");let o=Er(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 c("Rename target node not found");let r=Er(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),u("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return be(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),s=this.getNode(t);if(!o)return c("Node not found");if(!s)return c("Target parent not found");if(r===e)return c("Cannot move root node");if(e===t)return c("Cannot move node into itself");let i=Er(o,"move");if(i)return i;if(pu(t,e))return c("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}=v(),o=this.getNode(e);if(!o)return c("Node not found");if(r===e)return c("Cannot delete root node");let s=Er(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 be(p.id))l(f.id)}};l(e);let d={...structuredClone(t)};for(let m of i){if(!d[m])return c("Unable to locate node to delete");d[m]={...d[m],isDeleted:!0}}return n?(w({nodes:d}),u("Successfully tomb stoned",o)):c("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return c("Contributor not found");let n={...t,name:xo,tombstoned:!0},r=Oe(o=>({...o,contributors:{...o.contributors,[e]:n}}));return a(r)?c("Unable to remove contributor"):u("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return c("Contributor not found");if(n.tombstoned)return c("Cannot rename a removed contributor");let r={...n,name:t},o=Oe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?c("Unable to rename contributor"):u("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return c("Contributor not found");let r={...n,name:t,tombstoned:!1},o=Oe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?c("Unable to restore contributor"):u("Restored contributor",r)},linkContributorEmail({email:e,contributor:t,authorId:n}){if(!this.getContributor(t))return c("Unable to link email, missing contributor");let r={email:Qe(e),contributor:t,authorId:n},o=ys(r.email,t),s=v().emailLinks[o];if(s&&!s.tombstoned)return u("Email already linked",s);let i=Oe(l=>({...l,emailLinks:{...l.emailLinks,[o]:r}}));return a(i)?c("Unable to link email"):u("Linked email to contributor",r)},unlinkContributorEmail(e,t,n){let r=ys(e,t),o=v().emailLinks[r];if(!o)return c("Unable to unlink, no such link");if(o.tombstoned)return u("Email already unlinked",o);if(!Yi(n,o))return c("Only the author of a link or the contributor it names may remove it");let s={...o,tombstoned:!0},i=Oe(l=>({...l,emailLinks:{...l.emailLinks,[r]:s}}));return a(i)?c("Unable to unlink email"):u("Unlinked email from contributor",s)},getEmailLinks(){return v().emailLinks},createContributor(e){let t=Oe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?c("Unable to create contributor"):u("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return c("Unable to assign contributor, missing contributor");if(!r)return c("Unable to assign contributor, missing target");let o=Er(r,"edit");if(o)return o;if(!_(r))return c("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return c("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 c("Unable to unassign, missing contributor");if(!r)return c("Unable to unassign, missing target");let o=Er(r,"edit");if(o)return o;if(!_(r))return c("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 c("Unable to add tag, missing tag");if(!r)return c("Unable to add tag, missing target");let o=Er(r,"edit");if(o)return o;if(!_(r))return c("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return c("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 c("Unable to remove tag, missing tag");if(!r)return c("Unable to remove tag, missing target");let o=Er(r,"edit");if(o)return o;if(!_(r))return c("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 c("Tag not found");let n={...t,tombstoned:!0},r=Oe(o=>({...o,tags:{...o.tags,[e]:n}}));return a(r)?c("Unable to delete tag"):u("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return c("Tag not found");let r={...n,name:t,tombstoned:!1},o=Oe(s=>({...s,tags:{...s.tags,[e]:r}}));return a(o)?c("Unable to restore tag"):u("Restored tag",r)},createTag(e){let t=Oe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?c("Could not create tag"):u("Tag created",e)},createNode(e){let t=Xr("nodes",e.id,e);return a(t)?c("Unable to create node"):u("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return c("Failed to locate node");let n={...t,readonly:!0},r=Xr("nodes",e,n);return a(r)?c(r.message):u("Locked node",n)},updateNode(e){let t=Xr("nodes",e.id,e);return a(t)?t:u("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){let t=v().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return v().tags[e]},getTags(){return Object.values(v().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return v().nodes[e]},getSiblings(e){return be(e)}};var gA=(e,t)=>e+" ".repeat(Math.max(0,t-Mv(e))),hA=(e,t)=>" ".repeat(Math.max(0,t-Mv(e)))+e,pl=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","link.contributor.email":"Claimed","unlink.contributor.email":"Unclaimed","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),yA=(e,t)=>t?e<t?"up":e>t?"down":null:null,vA=(e,t)=>{let n=C.getNode(e.payload.parent),r=n?Sr.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=yA(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Pv=e=>`${Math.max(1,Math.round(e/1024))} KB`,Lv=e=>C.getAttachment(e)?.name??"",bA=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?Sr.bgHex(ze(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?Sr.bgHex(ze(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=v().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Sr.hex(ze(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Sr.hex(ze(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"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"add.issue.attachment":return`"${e.payload.name}" ${Sr.dim(`(${Pv(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Lv(e.payload.id);return t?`"${t}"`:""}default:return""}},xA=e=>{let t=fr(De(e));return Sr.gray(hA(t,8))},IA=12,EA=e=>gA(`${e}`,IA),SA=e=>{let t=ve();return a(t)?e:qi(e,t.value.contributors[e]?.name)},RA=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=v().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"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"move.node":{let t=C.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Pv(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Lv(e.payload.id);return t?`"${t}"`:""}default:return""}},il=e=>[pl(e.action),RA(e)].filter(Boolean).join(" "),kv=(e,t)=>{let n=xA(e.id),r=EA(SA(e.userId)),o=Sr.dim("\u203A"),s=e.action==="move.node"?vA(e,t):[pl(e.action),bA(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};var CA=e=>we(e,"comments"),NA=e=>we(e,"description"),AA=e=>we(e,"assignees"),TA=e=>we(e,"tags"),wA=e=>we(e,"history"),MA=e=>we(e,"diff"),PA=e=>we(e,"attachments"),li=({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({...Re.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return a(p)?p:u("Virtual field created",void 0)}if(!it(l))return c(`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 a(m)?m:u("Virtual field updated",void 0)},Dv=({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({...Re.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return a(m)?m:u("Virtual field list created",void 0)}if(!bs(i))return c(`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 d=C.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(d)?d:u("Virtual field list updated",void 0)},fl=null,LA=()=>{if(fl)return u("Virtual field ranks",fl);let e=Lt(Qt/4n),t=Lt(Qt/2n),n=Lt(Qt*3n/4n),r=Lt(Qt*7n/8n),o=Lt(Qt*15n/16n),s=Lt(Qt*13n/16n),i=Lt(Qt*27n/32n);return a(e)?e:a(t)?t:a(n)?n:a(r)?r:a(o)?o:a(s)?s:a(i)?i:(fl={description:e.value,assignees:t.value,tags:n.value,comments:r.value,attachments:o.value,log:s.value,diff:i.value},u("Virtual field ranks",fl))},dg=e=>{let t=LA();if(a(t))return t;let n=t.value,r=li({id:NA(e.id),name:Ne.DESCRIPTION,parentNodeId:e.id,rank:n.description,value:e.props.description??"",childRenderAxis:"vertical"});if(a(r))return r;let o=Dv({id:AA(e.id),name:Ne.ASSIGNEES,parentNodeId:e.id,rank:n.assignees,readonly:!0});if(a(o))return o;let s=Dv({id:TA(e.id),name:Ne.TAGS,parentNodeId:e.id,rank:n.tags,readonly:!0});if(a(s))return s;let i=li({id:CA(e.id),name:Ne.COMMENTS,parentNodeId:e.id,rank:n.comments,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(i))return i;let l=li({id:PA(e.id),name:Ne.ATTACHMENTS,parentNodeId:e.id,rank:n.attachments,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(l))return l;let d=li({id:wA(e.id),name:Ne.HISTORY,parentNodeId:e.id,rank:n.log,value:kA(e),readonly:!0,childRenderAxis:"vertical"});if(a(d))return d;let m=li({id:MA(e.id),name:Ne.DIFF,parentNodeId:e.id,rank:n.diff,value:"",readonly:!0,childRenderAxis:"vertical"});return a(m)?m:u("Ticket virtual nodes materialized",void 0)},kA=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=>kv(r,n.get(r.action)??[])).join(`
|
|
98
|
+
`)},Bv=!0,Ov=e=>{Bv=e},cd=()=>Bv;import vw from"node:http";import oo from"node:path";import{fileURLToPath as bw}from"node:url";var DA=e=>{switch(e.action){case"add.issue":case"move.node":case"close.issue":case"reopen.issue":return e.payload.parent;default:return null}},fu=(e,t)=>{let n=[];for(let r of e){let o=DA(r);if(o===null||o===n.at(-1)?.laneId)continue;let s=tr(r);n.push({laneId:o,enteredAt:s===null?t:hs(s)})}return n},gl=(e,t)=>fu(e,t).at(-1)?.enteredAt??t;var BA=e=>e.payload??{},gu=e=>{let t=new Map,n={},r=new Set,o=new Set,s=new Set;for(let i of e){let{id:l,name:d}=BA(i);if(l)switch(i.action){case"create.contributor":case"create.tag":t.set(l,d??""),r.add(l),o.delete(l);break;case"rename.contributor":d!==void 0&&r.has(l)&&!o.has(l)&&t.set(l,d);break;case"tombstone.contributor":r.has(l)&&(t.set(l,xo),o.add(l));break;case"restore.contributor":case"restore.tag":d!==void 0&&r.has(l)&&(t.set(l,d),o.delete(l));break;case"add.board":d!==void 0&&(t.set(l,d),s.add(l));break;case"add.swimlane":d!==void 0&&(t.set(l,d),s.add(l),n[l]=d);break;case"edit.title":d!==void 0&&s.has(l)&&(t.set(l,d),l in n&&(n[l]=d));break;default:break}}return{byId:t,lanes:n}};var OA=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},_v=e=>{let t=e.payload;return e.action==="tombstone.tag"||e.action==="restore.tag"?t?.id:t?.tag},FA=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}},_A=(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},$A=new Set(["add.issue.comment","edit.issue.comment","delete.issue.comment"]),UA=e=>$A.has(e.action)?e.payload?.id??null:null,jA=new Set(["add.issue","move.node","close.issue","reopen.issue"]),HA=(e,t)=>{let n=new Map;return e.map((r,o)=>{let s=t[o]??null;if(s===null)return{lane:null,laneBefore:null};let i=r.payload,l=null;if(jA.has(r.action)&&i?.id===s&&i.parent){let d=n.get(s);d!==void 0&&d!==i.parent&&(l=d),n.set(s,i.parent)}return{lane:n.get(s)??null,laneBefore:l}})},Fv=90,WA=e=>{let t=e.trim().split(`
|
|
99
|
+
`)[0]?.trim()??"";return t.length>Fv?`${t.slice(0,Fv).trimEnd()}\u2026`:t},GA=(e,t,n)=>{let r=e.payload,o=_v(e),s=e.action?pl(e.action):"";if(r?.md!==void 0){let l=WA(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?.email!==void 0?r.email:r?.name!==void 0?`"${r.name}"`:"";return[s,i].filter(Boolean).join(" ")},hu=(e,t)=>e?Ke(e,t.get(e)):null,VA=(e,t)=>{let n=e.payload;return{actor:hu(e.userId,t),tag:hu(_v(e),t),assignee:hu(n?.assignee,t)}},$v=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=o.action==="close.issue"?r(i):null,d=s.parent??s.issue;return d&&t.set(i,d),l!==null?l:n.has(i)?i:r(i)})},Uv=e=>zA.has(e),zA=new Set(["create.contributor","rename.contributor","tombstone.contributor","restore.contributor","link.contributor.user","link.contributor.email","unlink.contributor.email"]),jv=(e,t)=>{let n=$v(e);return e.filter((r,o)=>n[o]===t)},KA=(e,t=new Map)=>{let n=new Map([...t,...gu(e).byId]),r=OA(e),o=FA(e),s=e.map(p=>_A(p,o)),i=HA(e,s),l=$v(e),d=yo(e.map(p=>tr(p)));return e.flatMap((p,f)=>{let g=d[f]??null;return g===null?[]:[{id:p.id,t:g,action:p.action,label:GA(p,n,r),issue:s[f]??null,target:UA(p),...i[f],board:l[f]??null,...VA(p,n)}]}).sort((p,f)=>p.t-f.t)},qA=e=>{let t=new Map;for(let r of e){if(r.issue===null||r.lane===null)continue;let o=t.get(r.issue)??[],s=o[o.length-1];(s===void 0||s.lane!==r.lane)&&(o.push({t:r.t,lane:r.lane,board:r.board}),t.set(r.issue,o))}let n=new Map;for(let[r,o]of t){let s=o[o.length-1];n.set(r,{changes:o,from:o[0].t,closedFrom:s.lane===ge?s.t:null})}return n},YA=(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 e[n-1]},Hv=(e,t,n)=>{let r={};for(let[o,s]of e){if(s.from>=t||s.closedFrom!==null&&s.closedFrom<t)continue;let i=YA(s.changes,t);i===void 0||i.lane===ge||n&&i.board!==n||(r[o]=i.lane)}return r},XA=e=>gu(e).lanes,ci=null,Wv=e=>{let t=In(e);if(ci&&ci.root===e&&ci.signature===t)return u("Timeline entries, cached",ci.index);let n=dr(e);if(a(n))return c(n.message);let r=KA(n.value,cr(e)),o={entries:r,lanes:qA(r),laneNames:XA(n.value)};return ci={root:e,signature:t,index:o},u("Timeline entries, built",o)};var Gv=1e5,JA=2e4,hl=null,Vv=Promise.resolve(),Rr=e=>{let t=Vv.then(e,e);return Vv=t.then(()=>{},()=>{}),t},yl=e=>{let t=on(e);return a(t)?t:fe({repoRoot:t.value})},rt=()=>{if(!Ut())return{mode:"live",asOfTime:null};let{timeMode:e}=v();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:hl}},zv=(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},Kv=async(e={})=>{let t=yl(e.repoRoot);if(a(t))return c(t.message);let n=Wv(t.value);if(a(n))return c(n.message);let r=n.value.entries,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:[],capped:!1,events:[],lanesAtStart:{},laneNames:n.value.laneNames,closedLane:ge,earliest:i,latest:s});let l=zv(r,i),d=zv(r,s),m=r.slice(l,d).filter(b=>!e.boardId||b.board===e.boardId||Uv(b.action)),p=m.map(b=>b.t),f=Math.max(1,Math.ceil((s-i)/Gv)),g=new Map;for(let b of p){let N=Math.min(Gv-1,Math.floor((b-i)/f)),S=i+N*f;g.set(S,(g.get(S)??0)+1)}let h=[...g.entries()].sort(([b],[N])=>b-N).map(([b,N])=>({t:b,count:N})),x=m.length>JA;return u("Computed event timeline",{bucketMs:f,buckets:h,capped:x,events:x?[]:m,lanesAtStart:Hv(n.value.lanes,i,e.boardId),laneNames:n.value.laneNames,closedLane:ge,earliest:i,latest:s})},qv=e=>{let t=dr(e);if(a(t))return c(t.message);let n=ln();if(a(n))return c(n.message);hl=null;let r=en(t.value),{fatal:o,skipped:s}=En(r);return o.length>0?c(o.map(i=>i.message).join(", ")):(Sn(s),w({readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),u("Restored live state",!0))},QA=(e,t)=>{hl=null;let n=qv(e);return a(n)?c(`${t} (recovery to live also failed: ${n.message})`):c(t)},yu=e=>Rr(async()=>{let t=yl(e.repoRoot);if(a(t))return c(t.message);let n=xa(t.value,e.targetTime);if(a(n))return c(n.message);let{appliedEvents:r,unappliedEvents:o}=n.value,s=ln();if(a(s))return s;let i=en(r),{fatal:l,skipped:d}=En(i);return l.length>0?QA(t.value,l.map(m=>m.message).join(", ")):(Sn(d),w({readOnly:!0,timeMode:"peek",unappliedEvents:o,replay:null}),hl=e.targetTime,u("Checked out historical state",{asOfTime:e.targetTime}))}),Yv=async e=>{let t=yl(e.repoRoot);if(a(t))return c(t.message);let n=Ia(t.value);if(a(n))return c(n.message);let r=n.value.get(e.eventId)??null;return r===null?c("Event not found in the log"):yu({repoRoot:e.repoRoot,targetTime:r+1})},Xv=(e={})=>Rr(async()=>{let t=yl(e.repoRoot);if(a(t))return c(t.message);let n=qv(t.value);return a(n)?c(n.message):u("Returned to live state",!0)});import eT from"node:fs";var Jv=new Map,ZA=3e4,Qv=async e=>{let t=Jv.get(e);if(t&&Date.now()-t.readAt<ZA)return{name:t.name,email:t.email};let n=await Le({args:["config","--get-regexp","^user\\.(name|email)$"],cwd:e}),r=null,o=null;if(n.exitCode===0)for(let s of(n.stdout??"").split(`
|
|
100
|
+
`)){let i=s.indexOf(" ");if(i===-1)continue;let l=s.slice(0,i),d=s.slice(i+1);l==="user.name"&&(r=d.trim()||null),l==="user.email"&&(o=Qe(d)||null)}return Jv.set(e,{name:r,email:o,readAt:Date.now()}),{name:r,email:o}},vl=async e=>(await Qv(e)).email,Cr=async e=>(await Qv(e)).name;var Jr=e=>{let t=ce(e??process.cwd());return a(t)?c(t.message):u("Resolved Epiq repo root",t.value)},bl=null,tT=async(e,t)=>{let n=Jr(e);if(a(n))return n;let r=fe({repoRoot:n.value});if(a(r))return c(r.message);let o=ke(n.value);if(a(o))return c(o.message);if(!(bl!==null&&bl.repoRoot===n.value&&bl.stateBranchRoot===r.value&&eT.existsSync(Pr(r.value)))){let f=await js({repoRoot:n.value,stateBranchName:o.value});if(a(f))return c(f.message);let g=await ur({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(a(g))return c(g.message);bl={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let f=await j({cwd:r.value,args:["pull","--ff-only"]});a(f)&&ne.info(3,f.message)}let i={repoRoot:n.value,stateBranchRoot:r.value},l=gt();a(l)||$e(l.value),$e({gitEmail:await vl(n.value),gitName:await Cr(n.value)});let d=In(r.value);if(Lf(r.value)===d&&Ut()&&rt().mode==="live")return u("Booted Epiq state, unchanged",i);let m=tn(r.value);if(a(m))return c(m.message);let p=nn(m.value.events,m.value.unreadable);return a(p)?c(p.message):(kf(r.value,d),u("Booted Epiq state",i))},Gt=()=>{let e=gt();return a(e)?c(e.message):e.value.userId?e.value.userName?u("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):c("Unable to retrieve user name"):c("Unable to retrieve user id")},mt=()=>{let e=ve();return a(e)?c(e.message):e},Dt=e=>tT(e,{pull:!1}),de=async e=>{let t=await Dt(e);if(a(t))return t;let n=Gt();if(a(n))return n;let r=mt();return a(r)?r:u("Booted",{boot:t.value,actor:n.value,state:r.value})};var nT=e=>{let t=C.getNode(e);if(!t)return[];let n=new Set;t.parentNodeId&&n.add(t.parentNodeId);for(let r of t.log??[]){let o=r.payload;o.id===e&&o.parent&&n.add(o.parent)}return[...n]},xl=e=>{let t=new Set;e.parentNodeId&&t.add(e.parentNodeId);for(let r of e.log??[]){let o=r.payload;o.id===e.id&&o.parent&&t.add(o.parent)}let n=new Set;for(let r of t)for(let o of nT(r))n.add(o);return[...n]},qo=e=>yn(e).map(t=>Ke(t.id,t.name));var Yo=e=>vn(e).map(({id:t,name:n})=>Ke(t,n));import rT from"node:fs";import oT from"node:path";import{ulid as bu}from"ulid";var Ze=e=>{let t=mt();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?c("Issue not found"):_(n)?n.readonly?c("Issue is readonly"):u("Found issue",n):c("Target must be an issue")},Nr=e=>{let t=mt();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?c("Swimlane not found"):hn(n)?n.readonly?c("Swimlane is readonly"):u("Found swimlane",n):c("Target must be a swimlane")},vu=e=>{let t=mt();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?c("Board not found"):or(n)?n.readonly?c("Board is readonly"):u("Found board",n):c("Target must be a board")};var sT=e=>{if(e.filePath)try{return u("Read attachment file",{data:rT.readFileSync(e.filePath),name:e.name??oT.basename(e.filePath)})}catch(t){return c(`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"}):c("Provide either filePath or dataBase64")},Il=()=>{let e=gt();return a(e)?bn:e.value.attachmentMaxKb??bn},xu=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=Ze(e.issueId);if(a(n))return n;let r=sT(e);if(a(r))return r;let o=Jp(t.value.boot.stateBranchRoot,r.value.data,Il());if(a(o))return o;let s=Ee(r.value.name).trim()||"image",i=bu(),l={id:bu(),...D(t.value.actor),action:"add.issue.attachment",payload:{id:i,issue:e.issueId,author:t.value.actor.userId,hash:o.value.hash,ext:o.value.ext,name:s,bytes:o.value.bytes}},d=B([l],t.value.boot.stateBranchRoot);if(a(d))return c(d.message);let m=Or(o.value.hash,o.value.ext);return u("Added issue attachment",{id:i,issueId:e.issueId,fileName:m,bytes:o.value.bytes,markdown:$c(s,m)})},Iu=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=t.value.state.eventLog.find(l=>l.action==="add.issue.attachment"&&l.payload.id===e.attachmentId);if(!n)return c("Unable to resolve attachment");if(n.payload.author!==t.value.actor.userId)return c("You can only delete your own attachments");let r=Ze(n.payload.issue);if(a(r))return r;if(t.value.state.eventLog.some(l=>l.action==="delete.issue.attachment"&&l.payload.id===e.attachmentId))return u("Attachment already deleted",{id:e.attachmentId,issueId:n.payload.issue});let s={id:bu(),...D(t.value.actor),action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:n.payload.issue}},i=B([s],t.value.boot.stateBranchRoot);return a(i)?c(i.message):u("Deleted issue attachment",{id:e.attachmentId,issueId:n.payload.issue})},Eu=async e=>{let t=await Dt(e.repoRoot);return a(t)?t:Qp(t.value.stateBranchRoot,e.fileName,Il())};var iT=365*24*60*60*1e3,Su=e=>{let t=mt();if(a(t))return t;let n=t.value.nodes[e];return u("Issue description",n&&_(n)&&!n.isDeleted?n.props.description??"":"")},Qr=()=>{let e=mt();if(a(e))return e;let t=rt(),n=t.mode!=="live",r=Object.values(e.value.nodes),o=r.filter(b=>or(b)&&!b.isDeleted),s=Date.now()-iT,i=new Map,l=new Map;for(let b of r)if(!b.isDeleted){if(hn(b)&&b.parentNodeId){let N=i.get(b.parentNodeId)??[];N.push(b),i.set(b.parentNodeId,N)}if(_(b)&&b.parentNodeId){if(b.parentNodeId===ge&&De(b.id)<s)continue;let N=l.get(b.parentNodeId)??[];N.push(b),l.set(b.parentNodeId,N)}}let d=new Set;for(let b of l.values())for(let N of b)d.add(N.id);let m=gt();if(a(m))return m;let p={},f=C.getCommentsGroupedByIssue();for(let b of r.filter(_))b.isDeleted||!d.has(b.id)||(p[b.id]=(f.get(b.id)??[]).map(N=>{let S=C.getContributor(N.authorId);return{id:N.id,issueId:N.issue,body:N.md,author:Ke(N.authorId,S?.name),createdAt:De(N.id)}}));let g=new Map;for(let b of e.value.eventLog)b.action==="add.issue.attachment"&&g.set(b.payload.id,b.payload.author);let h={},x=C.getAttachmentsGroupedByIssue();for(let b of r.filter(_))b.isDeleted||!d.has(b.id)||(h[b.id]=(x.get(b.id)??[]).map(N=>({id:N.id,issueId:N.issue,name:N.name,fileName:Or(N.hash,N.ext),bytes:N.bytes,createdAt:De(N.id),canDelete:g.get(N.id)===m.value.userId})));return u("Retrieved Epiq GUI state",{boards:o.sort((b,N)=>b.rank.localeCompare(N.rank)).map(b=>({id:b.id,ref:H(b.id),title:b.title,readonly:!!b.readonly||n,swimlanes:(i.get(b.id)??[]).sort((N,S)=>N.rank.localeCompare(S.rank)).map(N=>({id:N.id,title:N.title,readonly:!!N.readonly||n,issues:(l.get(N.id)??[]).sort((S,A)=>S.rank.localeCompare(A.rank)).map(S=>({id:S.id,ref:H(S.id),title:Ee(S.title),description:S.props.description??"",createdAt:De(S.id),enteredLaneAt:gl(S.log??[],De(S.id)),readonly:!!S.readonly||n,tags:qo(S),assignees:Yo(S),parentNodeId:S.parentNodeId,isClosed:S.parentNodeId===ge,boardIds:xl(S)})),parentNodeId:N.parentNodeId}))})),tags:C.getTags().map(b=>({...b,...Ke(b.id,b.name)})),contributors:Object.values(e.value.contributors).map(b=>({...b,...Ke(b.id,b.name)})),user:{id:m.value.userId??"",name:m.value.userName??"",color:ze(m.value.userName??"")},commentsByIssueId:p,attachmentsByIssueId:h,attachmentMaxKb:Il(),timeTravel:t})},Zv=null,aT=e=>{if(e===Zv)return;let t=Qi({root:e});if(a(t)){ne.info(t.message);return}Zv=e},Vt=async(e={})=>{if(rt().mode!=="live")return Qr();let t=await Dt(e.repoRoot);return a(t)?t:(aT(t.value.repoRoot),Qr())},di=async(e={})=>{wo();let t=Jr(e.repoRoot);if(a(t))return c("Sync failed");let n=Gt();if(a(n))return n;let r=await Ma({cwd:t.value,ownEventFileName:ar(n.value)});return a(r)?(md(r.message),r):(Hr(),u("Synced",r.value))};import{ulid as zt}from"ulid";var ui=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?u("Resolved targets",t):c("Provide issueId or issueIds")},Xo=(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):c(`${r}: ${t.failed.map(o=>`${o.ref} ${o.reason}`).join("; ")}`)},mi=(e,t)=>{let n={done:[],failed:[]};for(let r of e){let o=t(r);a(o)?n.failed.push({id:r,ref:H(r),reason:o.message}):n.done.push({id:r,ref:H(r)})}return n};var nb=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();async function Nu(e){let t=await Dt(e.repoRoot);if(a(t))return t;let n=mt();if(a(n))return n;let r=n.value.nodes,o=e.query?.trim().toLowerCase(),s=Object.values(r).filter(_).filter(l=>!l.isDeleted).filter(l=>e.includeClosed||l.parentNodeId!==ge).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||qo(l).some(d=>nb(d.name,e.tag))).filter(l=>!e.assignee||Yo(l).some(d=>nb(d.name,e.assignee))).filter(l=>!o||l.title.toLowerCase().includes(o)||(l.props.description??"").toLowerCase().includes(o)),i=l=>Ee((l.parentNodeId?r[l.parentNodeId]?.title:void 0)??"");return e.brief?u("Listed issues",s.map(l=>({id:l.id,ref:H(l.id),title:Ee(l.title),swimlane:i(l),tags:qo(l).map(d=>d.name),assignees:Yo(l).map(d=>d.name)}))):u("Listed issues",s.map(l=>({id:l.id,ref:H(l.id),title:Ee(l.title),description:l.props.description??"",createdAt:De(l.id),enteredLaneAt:gl(l.log??[],De(l.id)),parentNodeId:l.parentNodeId,isClosed:l.parentNodeId===ge,boardIds:xl(l),readonly:!!l.readonly,tags:qo(l),assignees:Yo(l)})))}var Au=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=Ee(e.title);if(!n)return c("Issue title cannot be empty");let r=e.description??"",o=at("Issue title",n,300)??at("Issue description",r,2e4);if(o)return c(o);if((e.tagNames?.length??0)>20)return c(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return c(`Cannot set more than ${20} assignees at once`);let s=Nr(e.parentId);if(a(s))return s;let i=Wn(e.parentId,t.value.actor,t.value.boot.stateBranchRoot);if(a(i))return i;let l=Za({name:n,parent:e.parentId,user:t.value.actor,rank:i.value});if(a(l))return l;let d=[...l.value],m=d.find(h=>h.action==="add.issue")?.payload.id;if(!m)return c("Unable to determine created issue id");r&&d.push({id:zt(),...D(t.value.actor),action:"edit.description",payload:{id:m,md:r}});let p=[];for(let h of e.tagNames??[]){let x=Ee(h).trim();if(!x||p.some(A=>A.name===x))continue;let b=at("Tag name",x,60);if(b)return c(b);let N=C.findTagByName(x),S=N?.id??zt();N||d.push({id:zt(),...D(t.value.actor),action:"create.tag",payload:{id:S,name:x}}),d.push({id:zt(),...D(t.value.actor),action:"add.issue.tag",payload:{id:m,tag:S}}),p.push({id:S,name:x})}let f=[];for(let h of e.assigneeNames??[]){let x=Ee(h).trim();if(!x||f.some(A=>A.name===x))continue;let b=at("Assignee name",x,80);if(b)return c(b);let N=Object.values(t.value.state.contributors).find(A=>A.name===x),S=N?.id??zt();N||d.push({id:zt(),...D(t.value.actor),action:"create.contributor",payload:{id:S,name:x}}),d.push({id:zt(),...D(t.value.actor),action:"add.issue.assignee",payload:{id:m,assignee:S}}),f.push({id:S,name:x})}let g=B(d,t.value.boot.stateBranchRoot);return a(g)?c(g.message):u("Created issue",{id:m,ref:H(m),title:n,parentId:e.parentId,description:r,tags:p,assignees:f})},lT=(e,t,n)=>{let r=Ze(e);if(a(r))return r;let o=Rn(ge,e,{at:"end"},t,n);if(a(o))return o;let s={id:zt(),...D(t),action:"close.issue",payload:{id:e,parent:ge,rank:o.value}},i=B([s],n);return a(i)?c(i.message):u("Closed issue",{id:e,ref:H(e)})};async function Tu(e){let t=await Dt(e.repoRoot);if(a(t))return t;let n=Gt();if(a(n))return n;let r=ui(e);if(a(r))return r;let o=s=>lT(s,n.value,t.value.stateBranchRoot);return e.issueIds?Xo("Closed",mi(r.value,o)):o(r.value[0])}var wu=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=t.value.state.nodes[e.issueId];if(!n||n.isDeleted)return c("Issue not found");if(!_(n))return c("Target must be an issue");if(n.parentNodeId!==ge)return c("Issue is not closed");let r=al(n);if(!r)return c("Unable to resolve previous parent from issue history");if(r===ge)return c("Previous parent resolves to closed swimlane");let o=Nr(r);if(a(o))return o;let s=o.value,i=Rn(s.id,n.id,{at:"end"},t.value.actor,t.value.boot.stateBranchRoot);if(a(i))return i;let l={id:zt(),...D(t.value.actor),action:"reopen.issue",payload:{id:n.id,parent:s.id,rank:i.value}},d=B([l],t.value.boot.stateBranchRoot);return a(d)?c(d.message):u("Reopened issue",{id:n.id,ref:H(n.id),parentId:s.id})},cT=(e,t,n,r)=>{let o=Ze(e);if(a(o))return o;let s=Nr(t.parentId);if(a(s))return s;let i=Rn(t.parentId,e,t.position??{at:"end"},n,r);if(a(i))return i;let l={id:zt(),...D(n),action:"move.node",payload:{id:e,parent:t.parentId,rank:i.value}},d=B([l],r);return a(d)?c(d.message):u("Moved issue",{id:e,ref:H(e),parentId:t.parentId})};async function Mu(e){let t=Jr(e.repoRoot);if(a(t))return t;let n=Gt();if(a(n))return n;let r=fe({repoRoot:t.value});if(a(r))return r;let o=tn(r.value);if(a(o))return o;let s=nn(o.value.events,o.value.unreadable);if(a(s))return s;let i=ui(e);if(a(i))return i;let l=d=>cT(d,e,n.value,r.value);return e.issueIds?Xo("Moved",mi(i.value,l)):l(i.value[0])}var Pu=e=>{let t=mt();if(a(t))return t;let n=t.value.nodes[e];return n?u("Read issue history",(n.log??[]).map(r=>({id:r.id,t:De(r.id),action:r.action,label:il(r),...r.action==="move.node"?{parentId:r.payload.parent}:{},actor:Ke(r.userId,t.value.contributors[r.userId]?.name)}))):c("Issue not found")},Lu=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=Ze(e.issueId);if(a(n))return n;let r=n.value,o=at("Issue description",e.description,2e4);if(o)return c(o);let s=r.props.description??"";if(s===e.description)return u("No changes made",{id:e.issueId,ref:H(e.issueId),description:s});let i={id:zt(),...D(t.value.actor),action:"edit.description",payload:{id:e.issueId,md:e.description}},l=B([i],t.value.boot.stateBranchRoot);return a(l)?c(l.message):u("Edited issue description",{id:e.issueId,ref:H(e.issueId),description:e.description})},ku=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=Ze(e.issueId);if(a(n))return n;let r=n.value,o=Ee(e.title);if(!o.trim())return c("Issue title cannot be empty");let s=at("Issue title",o,300);if(s)return c(s);if(r.title===o)return u("No changes made",{id:e.issueId,ref:H(e.issueId),title:o});let i={id:zt(),...D(t.value.actor),action:"edit.title",payload:{id:e.issueId,name:o}},l=B([i],t.value.boot.stateBranchRoot);return a(l)?c(l.message):u("Edited issue title",{id:e.issueId,ref:H(e.issueId),title:o})};import{ulid as Ar}from"ulid";var Du=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=t.value.state.nodes[t.value.state.rootNodeId];if(!n)return c("Workspace not found");if(rt().mode!=="live")return c("Cannot add a board while time travelling");let r=Ee(e.title);if(!r.trim())return c("Board title cannot be empty");let o=at("Board title",r,300);if(o)return c(o);let s=Wn(n.id,t.value.actor,t.value.boot.stateBranchRoot);if(a(s))return s;let i=Ar(),l={id:Ar(),...D(t.value.actor),action:"add.board",payload:{id:i,name:r,parent:n.id,rank:s.value}},d=B([l],t.value.boot.stateBranchRoot);return a(d)?c(d.message):u("Created board",{id:i,ref:H(i),title:r})},Bu=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=t.value.state.nodes[e.boardId];if(!n||n.isDeleted)return c("Board not found");if(!or(n))return c("Edit target must be a board");if(n.readonly)return c("Cannot edit readonly board");if(rt().mode!=="live")return c("Cannot rename a board while time travelling");let r=Ee(e.title);if(!r.trim())return c("Board title cannot be empty");let o=at("Board title",r,300);if(o)return c(o);if(n.title===r)return u("No changes made",{id:e.boardId,ref:H(e.boardId),title:r});let s={id:Ar(),...D(t.value.actor),action:"edit.title",payload:{id:e.boardId,name:r}},i=B([s],t.value.boot.stateBranchRoot);return a(i)?c(i.message):u("Edited board title",{id:e.boardId,ref:H(e.boardId),title:r})};var Ou=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=vu(e.boardId);if(a(n))return n;if(rt().mode!=="live")return c("Cannot add a swimlane while time travelling");let r=Ee(e.title);if(!r.trim())return c("Swimlane title cannot be empty");let o=at("Swimlane title",r,300);if(o)return c(o);let s=Wn(e.boardId,t.value.actor,t.value.boot.stateBranchRoot);if(a(s))return s;let i=Ar(),l={id:Ar(),...D(t.value.actor),action:"add.swimlane",payload:{id:i,name:r,parent:e.boardId,rank:s.value}},d=B([l],t.value.boot.stateBranchRoot);return a(d)?c(d.message):u("Created swimlane",{id:i,ref:H(i),title:r,boardId:e.boardId})},Fu=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=Nr(e.swimlaneId);if(a(n))return n;let r=n.value,o=Ee(e.title);if(!o.trim())return c("Swimlane title cannot be empty");let s=at("Swimlane title",o,300);if(s)return c(s);if(r.title===o)return u("No changes made",{id:e.swimlaneId,ref:H(e.swimlaneId),title:o});let i={id:Ar(),...D(t.value.actor),action:"edit.title",payload:{id:e.swimlaneId,name:o}},l=B([i],t.value.boot.stateBranchRoot);return a(l)?c(l.message):u("Edited swimlane title",{id:e.swimlaneId,ref:H(e.swimlaneId),title:o})},_u=async e=>{let t=Jr(e.repoRoot);if(a(t))return t;let n=Gt();if(a(n))return n;let r=fe({repoRoot:t.value});if(a(r))return r;let o=tn(r.value);if(a(o))return o;let s=nn(o.value.events,o.value.unreadable);if(a(s))return s;let i=Nr(e.swimlaneId);if(a(i))return i;let l=vu(e.boardId);if(a(l))return l;let d=Rn(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(a(d))return d;let m={id:Ar(),...D(n.value),action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:d.value}},p=B([m],r.value);return a(p)?c(p.message):u("Moved swimlane",{id:e.swimlaneId,ref:H(e.swimlaneId),boardId:e.boardId})},$u=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=Nr(e.swimlaneId);if(a(n))return n;let r={id:Ar(),...D(t.value.actor),action:"delete.node",payload:{id:e.swimlaneId}},o=B([r],t.value.boot.stateBranchRoot);return a(o)?c(o.message):u("Deleted swimlane",{id:e.swimlaneId,ref:H(e.swimlaneId)})};import{ulid as pi}from"ulid";async function Uu(e){let t=await Dt(e.repoRoot);if(a(t))return t;let n=Gt();if(a(n))return n;let r=ui(e);if(a(r))return r;let o=Ee(e.tagName).trim();if(!o)return c("Tag name cannot be empty");let s=at("Tag name",o,60);if(s)return c(s);let i=mi(r.value,Ze);if(!e.issueIds&&i.failed[0])return c(i.failed[0].reason);if(i.done.length===0)return c(Xo("Tagged",i).message);let l=C.findTagByName(o),d=l?.id??pi(),m=[...l?[]:[{id:pi(),...D(n.value),action:"create.tag",payload:{id:d,name:o}}],...i.done.map(({id:h})=>({id:pi(),...D(n.value),action:"add.issue.tag",payload:{id:h,tag:d}}))],p=B(m,t.value.stateBranchRoot);if(a(p))return c(p.message);let f={id:d,name:o};if(!e.issueIds)return u("Added issue tag",{...i.done[0],tag:f});let g=Xo("Tagged",i);return a(g)?g:u(g.message,{...g.value,tag:f})}var ju=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=t.value.state.tags[e.tagId];if(!n)return c("Tag not found");if(n.tombstoned)return c("Tag is already deleted");let r=[{id:pi(),...D(t.value.actor),action:"tombstone.tag",payload:{id:e.tagId}}],o=B(r,t.value.boot.stateBranchRoot);return a(o)?c(o.message):u("Deleted tag",{id:n.id,name:n.name})};var Hu=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=Ze(e.issueId);if(a(n))return n;if(!t.value.state.tags[e.tagId])return c("Tag not found");let r={id:pi(),...D(t.value.actor),action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},o=B([r],t.value.boot.stateBranchRoot);return a(o)?c(o.message):u("Removed issue tag",{id:e.issueId,ref:H(e.issueId),tagId:e.tagId})};import{ulid as eo}from"ulid";var ob=async(e,t)=>{let n=cr(e).get(t);return n===void 0?void 0:{id:t,name:n}},Wu=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=Ze(e.issueId);if(a(n))return n;let r=e.self?t.value.actor.userId:e.assigneeId;if(r){let h=t.value.state.contributors[r],x=h?void 0:await ob(t.value.boot.stateBranchRoot,r);if(!h&&!x)return c("Unknown assignee id");let b=h??x,N=[...h?[]:[{id:eo(),...D(t.value.actor),action:"create.contributor",payload:{id:b.id,name:b.name}}],{id:eo(),...D(t.value.actor),action:"add.issue.assignee",payload:{id:e.issueId,assignee:b.id}}],S=B(N,t.value.boot.stateBranchRoot);return a(S)?c(S.message):u("Added issue assignee",{id:e.issueId,ref:H(e.issueId),assignee:{id:b.id,name:b.name}})}let o=Ee(e.assigneeName??"").trim();if(!o)return c("Provide assigneeId, self or assigneeName");let s=at("Assignee name",o,80);if(s)return c(s);let i=si({events:t.value.state.eventLog??[],registry:t.value.state.contributors,logFileNames:cr(t.value.boot.stateBranchRoot)}).filter(h=>h.name===o);if(i.length>1)return c(`"${o}" matches ${i.length} contributors (${i.map(({id:h})=>h).join(", ")}). Assign by assigneeId to choose.`);let l=i[0];if(!l&&!e.createUnlinked)return c(`No contributor named "${o}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let d=l?.id??eo(),m=l?.name??o,f=[...!!t.value.state.contributors[d]?[]:[{id:eo(),...D(t.value.actor),action:"create.contributor",payload:{id:d,name:m}}],{id:eo(),...D(t.value.actor),action:"add.issue.assignee",payload:{id:e.issueId,assignee:d}}],g=B(f,t.value.boot.stateBranchRoot);return a(g)?c(g.message):u("Added issue assignee",{id:e.issueId,ref:H(e.issueId),assignee:{id:d,name:m}})},Gu=async e=>{let t=await de(e.repoRoot);if(a(t))return t;if(!t.value.state.contributors[e.contributorId])return c("Contributor not found");if(await ob(t.value.boot.stateBranchRoot,e.contributorId))return c("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let o=[{id:eo(),...D(t.value.actor),action:"tombstone.contributor",payload:{id:e.contributorId}}],s=B(o,t.value.boot.stateBranchRoot);return a(s)?c(s.message):u("Tombstoned contributor",{id:e.contributorId,name:xo})};var Vu=async(e={})=>{let t=await de(e.repoRoot);if(a(t))return t;let n=dr(t.value.boot.stateBranchRoot);if(a(n))return c(n.message);let r=e.boardId?jv(n.value,e.boardId):n.value,o=new Set,s=ug(t.value.boot.stateBranchRoot);if(a(s))return c(s.message);for(let d of s.value)d.userId&&o.add(d.userId);let i=t.value.state.contributors,l=si({events:r,registry:i,logFileNames:cr(t.value.boot.stateBranchRoot)}).map(({id:d,name:m,isExternal:p})=>({...Ke(d,m),isSelf:d===t.value.actor.userId,isExternal:p,isRemoved:i[d]?.tombstoned===!0,hasAuthoredAnywhere:o.has(d)}));return u("Listed board contributors",l)},zu=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=Ze(e.issueId);if(a(n))return n;if(!t.value.state.contributors[e.assigneeId])return c("Assignee not found");let r={id:eo(),...D(t.value.actor),action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},o=B([r],t.value.boot.stateBranchRoot);return a(o)?c(o.message):u("Removed issue assignee",{id:e.issueId,ref:H(e.issueId),assigneeId:e.assigneeId})};import{ulid as El}from"ulid";var fi=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=Ze(e.issueId);if(a(n))return n;let r=e.body.trim();if(!r)return c("Comment cannot be empty");if(r.length>4e3)return c(`Comment cannot exceed ${4e3} characters (got ${r.length})`);let o=El(),s={id:El(),...D(t.value.actor),action:"add.issue.comment",payload:{id:o,issue:e.issueId,md:r,author:t.value.actor.userId}},i=B([s],t.value.boot.stateBranchRoot);return a(i)?c(i.message):u("Added issue comment",{id:o,issueId:e.issueId,body:r})},gi=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=t.value.state.eventLog.find(l=>l.action==="add.issue.comment"&&l.payload.id===e.commentId);if(!n)return c("Unable to resolve comment");if(n.payload.author!==t.value.actor.userId)return c("You can only delete your own comments");let r=Ze(n.payload.issue);if(a(r))return r;if(t.value.state.eventLog.some(l=>l.action==="delete.issue.comment"&&l.payload.id===e.commentId))return u("Comment already deleted",{id:e.commentId,issueId:n.payload.issue});let s={id:El(),...D(t.value.actor),action:"delete.issue.comment",payload:{id:e.commentId,issue:n.payload.issue}},i=B([s],t.value.boot.stateBranchRoot);return a(i)?c(i.message):u("Deleted issue comment",{id:e.commentId,issueId:n.payload.issue})},Ku=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=t.value.state.eventLog.find(d=>d.action==="add.issue.comment"&&d.payload.id===e.commentId);if(!n)return c("Unable to resolve comment");if(n.payload.author!==t.value.actor.userId)return c("You can only edit your own comments");let r=Ze(n.payload.issue);if(a(r))return r;if(t.value.state.eventLog.some(d=>d.action==="delete.issue.comment"&&d.payload.id===e.commentId))return c("Comment was deleted");let s=e.body.trim();if(!s)return c("Comment cannot be empty");if(s.length>4e3)return c(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i={id:El(),...D(t.value.actor),action:"edit.issue.comment",payload:{id:e.commentId,issue:n.payload.issue,md:s}},l=B([i],t.value.boot.stateBranchRoot);return a(l)?c(l.message):u("Edited issue comment",{id:e.commentId,issueId:n.payload.issue,body:s})};import{ulid as sb}from"ulid";var qu=async e=>{let t=await de(e.repoRoot);if(a(t))return t;if(!nr(e.email))return c(`Not an email address: ${e.email}`);let n=Qe(e.email),r=e.contributorId??t.value.actor.userId;if(!t.value.state.contributors[r])return c(`Unknown contributor: ${r}`);let o=vs(t.value.state.emailLinks,n);if(o.includes(r))return u(`${n} is already yours`,{contributor:r,email:n,contested:o.filter(i=>i!==r)});let s=B([{id:sb(),action:"link.contributor.email",payload:{contributor:r,email:n},userId:t.value.actor.userId}],t.value.boot.stateBranchRoot);return a(s)?c(s.message):u(o.length>0?`Claimed ${n}, but somebody else claims it too, so it now resolves to neither of you`:`Claimed ${n}`,{contributor:r,email:n,contested:o})},Yu=async e=>{let t=await de(e.repoRoot);if(a(t))return t;let n=Qe(e.email),r=e.contributorId??t.value.actor.userId,o=t.value.state.emailLinks[ys(n,r)];if(!o||o.tombstoned)return c(`No such link: ${n} to ${r}`);if(!Yi(t.value.actor.userId,o))return c("Only whoever made a claim, or the contributor it names, may undo it");let s=B([{id:sb(),action:"unlink.contributor.email",payload:{contributor:r,email:n},userId:t.value.actor.userId}],t.value.boot.stateBranchRoot);return a(s)?c(s.message):u(`Unclaimed ${n}`,{contributor:r,email:n})},Sl=async(e={})=>{let t=await Dt(e.repoRoot);if(a(t))return t;let n=mt();if(a(n))return n;let{emailLinks:r,contributors:o}=n.value,s=new Map;for(let f of Object.values(r)){if(f.tombstoned)continue;let g=s.get(f.email)??new Set;g.add(f.contributor),s.set(f.email,g)}let i=[...s.entries()].map(([f,g])=>({email:f,contested:g.size>1,claimants:[...g].map(h=>Ke(h,o[h]?.name))})).sort((f,g)=>f.email.localeCompare(g.email)),l=Gt(),d=a(l)?[]:gn(r,l.value.userId),m=V().gitEmail,p=m?vs(r,m).filter(f=>a(l)||f!==l.value.userId):[];return u("Listed contributor emails",{emails:i,mine:d,git:m?{email:m,linkedToMe:d.includes(m),heldByOthers:p.map(f=>Ke(f,o[f]?.name))}:null})},Rl=async(e={})=>{let t=await de(e.repoRoot);if(a(t))return t;let{userId:n,userName:r}=t.value.actor,o=ke(t.value.boot.repoRoot),s=await Mn({repoRoot:t.value.boot.repoRoot,stateBranch:a(o)?void 0:o.value,names:[r,await Cr(t.value.boot.repoRoot)],links:t.value.state.emailLinks});if(a(s))return s;let i=xr(s.value),l=i.filter(d=>d.looksLikeYours);return u(i.length===0?"No unclaimed addresses in this history":`${i.length} unclaimed address(es) in this history, ${l.length>0?`${l.length} of which look like yours`:"none obviously yours"}. Show them to the user and link only the ones they confirm; each is a permanent event that replicates to every clone.`,{contributor:n,candidates:i,likely:l.length})};var ib=(e,t)=>{let n=0,r=0,o=null;for(let s of e){if(s.userId!==t)continue;s.action==="add.issue"&&n++,s.action==="add.issue.comment"&&r++;let i=vo(s.id);if(a(i))continue;let l=i.value.getTime();(o===null||l<o)&&(o=l)}return{tickets:n,comments:r,joinedAt:o}};var Xu=async(e={})=>{let t=await de(e.repoRoot);if(a(t))return t;let{userId:n,userName:r}=t.value.actor,o=ib(t.value.state.eventLog,n),s=ke(t.value.boot.repoRoot),i=await Mn({repoRoot:t.value.boot.repoRoot,stateBranch:a(s)?void 0:s.value,names:[r,await Cr(t.value.boot.repoRoot)],links:t.value.state.emailLinks}),l=a(i)?[]:i.value.filter(d=>d.claimedBy.length===1&&d.claimedBy[0]===n);return u("Derived personal stats",{...o,scanned:!a(i),commits:l.reduce((d,m)=>d+m.commits,0),claimedEmails:l.length})};var Pn="1.11.0";import dT from"node:fs";import ab from"node:path";var hi=Number(process.env.EPIQ_GUI_PORT)||3710,Ju="/api/instance",Qu="epiq",Cl=e=>{try{return dT.realpathSync(ab.resolve(e))}catch{return ab.resolve(e)}},uT=e=>{let t=e;return typeof t=="object"&&t!==null&&t.app===Qu&&typeof t.repoRoot=="string"&&typeof t.version=="string"&&typeof t.pid=="number"},lb=async(e,t=500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}${Ju}`,{signal:n.signal});if(!o.ok)return null;let s=await o.json();return uT(s)?s:null}catch{return null}finally{clearTimeout(r)}};var mT=/^(```|~~~)[^\n]*\n[\s\S]*?\n\1[ \t]*$/gm,pT=/^(?:```|~~~)[\s\S]*$/m,fT=/^[ \t]*\|?[ \t]*:?-{2,}:?[ \t]*(?:\|[ \t]*:?-{2,}:?[ \t]*)*\|?[ \t]*$/gm,gT=/^[ \t]*\|.*$/gm,hT=/!\[[^\]]*\]\([^)]*\)/g,yT=/\[([^\]]*)\]\([^)]*\)/g,vT=/^[ \t]*(?:[#>]+[ \t]*|[-*+][ \t]+|\d+[.)][ \t]+)/gm,bT=/^[ \t]*(?:-{3,}|\*{3,}|_{3,})[ \t]*$/gm,xT=/[*`~]/g,IT=/(?<![0-9A-Za-z])_|_(?![0-9A-Za-z])/g,ET=e=>Ee(e.replace(mT," ").replace(pT," ").replace(hT," ").replace(yT,"$1").replace(bT," ").replace(fT," ").replace(gT,t=>t.replaceAll("|"," ")).replace(vT,"").replace(xT,"").replace(IT,"")),ST=.5,cb=(e,t)=>{if(t<=0)return"";let n=ET(e);if(n.length<=t)return n;let r="\u2026",o=t-r.length;if(o<=0)return r.slice(0,t);let s=n.slice(0,o),i=s.lastIndexOf(" ");return`${(i>=o*ST?s.slice(0,i):s).trimEnd()}${r}`};var RT=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))}),to=e=>a(e)?e:u(e.message,RT(e.value)),CT=(e,t)=>(e.boards??[]).flatMap(n=>n.swimlanes??[]).flatMap(n=>n.issues??[]).find(n=>n.id===t),db=(e,t)=>{let n=CT(e,t);return{issueId:t,description:n?.description??"",comments:e.commentsByIssueId?.[t]??[]}},NT=280,ub=(e,t)=>({issueId:e,excerpt:cb(t,NT)});var mb=e=>{let t,n=!1,r=!1,o=0,s=i();function i(){let g=ce(e.project.repoRoot);if(a(g))return null;let h=fe({repoRoot:g.value});return a(h)?null:In(h.value)}let l=()=>{let g=fn();return a(g)?(ne.error(g.message),null):g.value},d=()=>{let g=l();if(!g)return!1;let h=gt();return a(h)?!1:!!g.autoSync&&cl(h.value)===null},m=()=>{let g=mo(l()?.autoSyncDebounceMs);return Math.max(0,g-(Date.now()-o))},p=async()=>{if(!(n||r)&&d()){r=!0,o=Date.now();try{await Rr(async()=>{if(rt().mode!=="live")return;await di({repoRoot:e.project.repoRoot});let g=i();if(g===null||g===s)return;s=g;let h=to(await Vt({repoRoot:e.project.repoRoot}));a(h)||jr({type:"state",payload:h})})}finally{r=!1,f()}}};function f(){n||!d()||r||t||(t=setTimeout(()=>{t=void 0,p()},m()))}return f(),{queueSync:f,reschedule:()=>{t&&(clearTimeout(t),t=void 0),f()},dispose:()=>{n=!0,t&&clearTimeout(t)}}};var AT=new Set(["127.0.0.1","[::1]","localhost","epiq.localhost"]),Zu=(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:!AT.has(n.hostname)},pb=(e,t)=>e.method==="GET"||e.method==="HEAD"?null:Zu(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 pw}from"ws";var Ln=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""});var TT=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},fb=({commits:e,patch:t})=>{let n=e.map(i=>i.time),o=t.files.map(i=>({...Ln(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=>TT(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 et={line:["//"],block:[["/*","*/"]]},Kt={line:["#"],block:[]},em={line:["--"],block:[]},Jo={line:[],block:[["<!--","-->"]]},wT={line:[],block:[]},q=(e,t)=>({name:e,comment:t}),Nl=q("TypeScript",et),Al=q("JavaScript",et),gb={ts:Nl,tsx:Nl,mts:Nl,cts:Nl,js:Al,jsx:Al,mjs:Al,cjs:Al,py:q("Python",{line:["#"],block:[['"""','"""']]}),rb:q("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:q("Go",et),rs:q("Rust",et),java:q("Java",et),kt:q("Kotlin",et),swift:q("Swift",et),c:q("C",et),h:q("C",et),cc:q("C++",et),cpp:q("C++",et),hpp:q("C++",et),cs:q("C#",et),php:q("PHP",et),scala:q("Scala",et),dart:q("Dart",et),lua:q("Lua",em),hs:q("Haskell",em),sql:q("SQL",em),ex:q("Elixir",Kt),exs:q("Elixir",Kt),pl:q("Perl",Kt),r:q("R",Kt),jl:q("Julia",Kt),sh:q("Shell",Kt),bash:q("Shell",Kt),zsh:q("Shell",Kt),vue:q("Vue",Jo),svelte:q("Svelte",Jo),html:q("HTML",Jo),xml:q("XML",Jo),md:q("Markdown",Jo),mdx:q("Markdown",Jo),css:q("CSS",{line:[],block:[["/*","*/"]]}),scss:q("CSS",et),less:q("CSS",et),yml:q("YAML",Kt),yaml:q("YAML",Kt),toml:q("TOML",Kt),ini:q("INI",Kt),json:q("JSON",wT)},MT="Other",hb=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},no=e=>gb[hb(e)]?.name??MT,yi=e=>gb[hb(e)]?.comment??null,PT=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],LT=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,Qo=e=>LT.test(e)||PT.some(t=>t.test(e)),kT=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,DT=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,BT=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,cn=e=>kT.test(e)||DT.test(e)||BT.test(e),yb=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),vb=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),bb=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),OT=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,FT=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,xb=e=>OT.test(e),Ib=e=>FT.test(e);var Eb=/\b(TODO|FIXME|HACK|XXX)\b/,_T=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,tm=(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"},$T=(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},Sb=({patch:e,repoShareByLanguage:t})=>{let n=new Map,r=0,o=0,s=0,i=0,l=0,d=0;for(let p of e.files){if(p.binary||cn(p.path))continue;let f=yi(p.path);if(!f||f.line.length===0&&f.block.length===0)continue;let g=no(p.path),h=n.get(g)??{comment:0,code:0};for(let{text:x}of p.added){let b=tm(x,f);if(Eb.test(x)&&i++,b==="blank"){s++;continue}if(b==="comment"){r++,h.comment++,f&&_T.test($T(x,f))&&d++;continue}o++,h.code++}for(let{text:x}of p.removedLines)Eb.test(x)&&l++;n.set(g,h)}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:d}};var UT=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,Tl=6,nm=10,jT=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)},HT=(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)},WT=e=>{if(e.length<Tl*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let r=0;r+Tl<=e.length;r++){let o=e.slice(r,r+Tl);if(o.some(l=>l.text.length<3))continue;let s=o.map(l=>l.text).join(`
|
|
101
|
+
`),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<Tl;l++)n[i.at+l]=!0,n[r+l]=!0}return n.filter(Boolean).length},Rb=({patch:e})=>{let t=[],n=[],r=[],o=!1,s=0,i=0,l=null,d=[];for(let[m,p]of e.files.entries()){if(cn(p.path)&&t.push(Ln(p)),yb(p.path)&&n.push(Ln(p)),vb(p.path)&&r.push(Ln(p)),bb(p.path)&&(o=!0),p.binary||cn(p.path))continue;let f=p.added.map(x=>x.text),g=jT(f),h=p.status!=="deleted";for(let x of f){UT.test(x)&&s++;let b=HT(x,g);b>i&&(i=b,l=Ln(p)),h&&d.push({text:x.trim(),file:m})}d.push({text:" ",file:m})}return{generatedPaths:t.slice(0,nm),dependencyManifests:n.slice(0,nm),buildOrCiPaths:r.slice(0,nm),docsTouched:o,debugPrintLinesAdded:s,maxIndentLevels:i,deepestFile:l,duplicatedLines:WT(d)}};var Cb=({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(cn(i.path)){r+=l;continue}let d=no(i.path),m=n.get(d)??{name:d,added:0,removed:0,addedInTests:0,share:0};m.added+=i.addedCount,m.removed+=i.removed,Qo(i.path)&&(m.addedInTests+=i.addedCount),n.set(d,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 GT=200,rm=2e5,VT=5e4,Nb=25,zT=64*1024*1024,om="",KT=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/,qT=/^diff --git a\/(.+) b\/\1$/,Ab=(e,t)=>e==="/dev/null"?null:e.startsWith(t)?e.slice(2):e,Tb=(e,t)=>e===null?"added":t===null?"deleted":"modified",YT=()=>({byPath:new Map,insertions:0,deletions:0,selfChurn:0,retainedLines:0}),XT=(e,t)=>{let n=e.byPath,r="",o=null,s=null,i=null,l=!1,d=0,m=(f,g)=>g==="modified"&&f==="added"?"added":g,p=(f,g)=>{let h=n.get(f);if(h)return h.entry.status=m(h.entry.status,g),h.entry.shas.includes(r)||h.entry.shas.push(r),h;let b={entry:{path:f,status:g,binary:!1,added:[],addedCount:0,removed:0,removedLines:[],shas:[r]},pendingByText:new Map};return n.set(f,b),b};for(let f of t.split(`
|
|
102
|
+
`)){if(f.startsWith(om)){r=f.slice(om.length).trim(),o=null,s=null,i=null,l=!1;continue}if(f.startsWith("diff --git ")){o=null,i=null,l=!0,s=qT.exec(f)?.[1]??null;continue}if(l&&f.startsWith("Binary files ")&&s){let[,h=""]=/^Binary files (.*) differ$/.exec(f)??[],[x="",b=""]=h.split(" and ");o=p(s,Tb(x==="/dev/null"?null:x,b==="/dev/null"?null:b)),o.entry.binary=!0;continue}if(l&&f.startsWith("--- ")){i=Ab(f.slice(4),"a/");continue}if(l&&f.startsWith("+++ ")){let h=Ab(f.slice(4),"b/"),x=h??i??s;x&&(o=p(x,Tb(i,h)));continue}let g=KT.exec(f);if(g){d=Number(g[1]),l=!1;continue}if(o){if(f.startsWith("+")){let h=f.slice(1);e.insertions++,o.entry.addedCount++,e.retainedLines<rm&&(o.entry.added.push({sha:r,line:d,text:h}),e.retainedLines++),o.pendingByText.size<VT&&o.pendingByText.set(h,(o.pendingByText.get(h)??0)+1),d++;continue}if(f.startsWith("-")){let h=f.slice(1);e.deletions++,o.entry.removed++,e.retainedLines<rm&&(o.entry.removedLines.push({sha:r,line:0,text:h}),e.retainedLines++);let x=o.pendingByText.get(h)??0;x>0&&h.trim().length>2&&(e.selfChurn++,o.pendingByText.set(h,x-1))}}}},JT=e=>({files:[...e.byPath.values()].map(t=>t.entry),insertions:e.insertions,deletions:e.deletions,selfChurn:e.selfChurn,retainedLines:e.retainedLines});var wb=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,GT).reverse(),r=YT(),o=0,s=0,i=!1;for(let d=0;d<n.length;d+=Nb){let m=n.slice(d,d+Nb),p=await j({cwd:e,args:["-c","core.quotePath=false","show","--unified=0","--no-renames","--no-color",`--format=${om}%H`,...m]});if(a(p))return c(p.message);if(XT(r,p.value.stdout),o+=p.value.stdout.length,s+=m.length,o>zT){i=!0;break}}let l=JT(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>=rm})};var QT=40,ZT=/^\d{6} blob ([0-9a-f]{40})\t(.+)$/,Mb=async({repoRoot:e,sha:t})=>{let n=await Le({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(`
|
|
103
|
+
`)){let f=ZT.exec(p);if(!f)continue;let[,g="",h=""]=f;if(cn(h))continue;let x=no(h);if(r.add(x),Qo(h)||!yi(h))continue;let b=o.get(x)??[];b.length<QT&&(b.push({blob:g,path:h}),o.set(x,b))}let s=[...o.values()].flat(),i=await _i(s.map(p=>p.blob),e);if(a(i))return{languages:r,commentShareByLanguage:new Map};let l=i.value,d=new Map;for(let{blob:p,path:f}of s){let g=l.get(p);if(g===void 0)continue;let h=yi(f),x=no(f),b=d.get(x)??{comment:0,code:0};for(let N of g.split(`
|
|
104
|
+
`)){let S=tm(N,h);S==="comment"&&b.comment++,S==="code"&&b.code++}d.set(x,b)}let m=new Map;for(let[p,f]of d){let g=f.comment+f.code;g>0&&m.set(p,f.comment/g)}return{languages:r,commentShareByLanguage:m}};var Pb=({patch:e})=>{let t=0,n=0,r=[],o=[],s=0,i=0;for(let l of e.files)if(!(l.binary||cn(l.path))&&Qo(l.path)){t+=l.addedCount,n+=l.removed,l.status==="added"&&r.push(Ln(l)),l.status==="deleted"&&o.push(Ln(l));for(let{text:d}of l.added)xb(d)&&s++,Ib(d)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:r,deletedTestFiles:o,skippedTestLinesAdded:s,focusedTestLinesAdded:i}};var ew=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,Lb=async({repoRoot:e,ref:t,commits:n})=>{let r=await wb({repoRoot:e,shas:n.map(l=>l.sha)});if(a(r))return c(r.message);let o=r.value,s=ew(n),i=s?await Mb({repoRoot:e,sha:s}):null;return u("Derived issue stats",{ref:t,shape:fb({commits:n,patch:o}),languages:Cb({patch:o,languagesBefore:i?.languages??null}),tests:Pb({patch:o}),comments:Sb({patch:o,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:Rb({patch:o})})};var vi=e=>{if(a(e))return e;let t=ve(),n=a(t)?{}:t.value.emailLinks,r=a(t)?{}:t.value.contributors,o=pp(n),s=e.value.map(i=>({...i,authorIdentity:Jy({authorName:i.author,authorEmail:i.authorEmail,owners:o,registry:r})}));return u(e.message,s)};var tw=32,bi=new Map;var nw=(e,t)=>{if(bi.set(e,t),bi.size>tw){let n=bi.keys().next();n.done||bi.delete(n.value)}return t},wl=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return c("idOrRef must not be empty");let n=t.length>7?H(t):t.toUpperCase(),r=ce(e.repoRoot??process.cwd());if(a(r))return c(r.message);let o=r.value,s=vi(await Kn({repoRoot:o,ref:n}));if(a(s))return c(s.message);let i=s.value.map(p=>({sha:p.sha,time:p.time,author:p.authorIdentity?.resolved?p.authorIdentity.name:p.author,subject:p.subject})),l=[o,n,i.map(p=>`${p.sha}:${p.author}`).join(",")].join(" "),d=bi.get(l);if(d)return u("Derived issue stats",d);let m=await Lb({repoRoot:o,ref:n,commits:i});return a(m)?c(m.message):u("Derived issue stats",nw(l,m.value))};var rw=new RegExp(`^[0-9A-Z]{${7}}$`),ow=e=>{let t=e.indexOf(" ");if(t===-1)return null;let n=e.slice(0,t).toUpperCase();return rw.test(n)?n:null},sw=e=>{let t={};for(let n of e){let r=ow(n.subject);if(!r)continue;let o=t[r]??={commits:0,insertions:0,deletions:0};o.commits++,o.insertions+=n.insertions,o.deletions+=n.deletions}return t},kb=async(e={})=>{let t=await jo({repoRoot:e.repoRoot});return a(t)?t:u("Collected diff stats by ref",sw(t.value))};var iw="Filed here",Db=(e,t)=>e.set(t,(e.get(t)??0)+1),Bb=(e,t,n)=>[...e.entries()].map(([r,o])=>({laneId:r,title:r===null?iw:n(r),count:o,share:t===0?0:o/t})).sort((r,o)=>o.count-r.count||r.title.localeCompare(o.title)),Ob=(e,t,n)=>{let r=new Map,o=new Map,s=0,i=0;for(let l of t)for(let[d,m]of l.entries()){if(m!==e)continue;s++,Db(r,l[d-1]??null);let p=l[d+1];p!==void 0&&(i++,Db(o,p))}return{arrived:s,departed:i,arrivesFrom:Bb(r,s,n),movesOnTo:Bb(o,i,n)}};var Fb=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 xi=1440*60*1e3,aw=({laneIds:e,journeys:t,now:n,days:r})=>{let o=n-(r-1)*xi,s=new Map(e.map(i=>[i,Array.from({length:r},()=>[])]));for(let i of t)for(let[l,d]of i.entries()){let m=s.get(d.laneId);if(!m)continue;let p=i[l+1]?.enteredAt,f=Math.max(0,Math.ceil((d.enteredAt-o)/xi)),g=p===void 0?r-1:Math.min(r-1,Math.ceil((p-o)/xi)-1);for(let h=f;h<=g;h++)m[h].push(o+h*xi-d.enteredAt)}return Object.fromEntries([...s].map(([i,l])=>[i,l.map((d,m)=>({t:o+m*xi,median:Fb(d.sort((p,f)=>p-f)),count:d.length}))]))},_b=({laneId:e,journeys:t,now:n,days:r})=>aw({laneIds:[e],journeys:t,now:n,days:r})[e];var lw=40,cw=30,dw=()=>({tickets:0,commits:0,insertions:0,deletions:0}),uw=async(e,t)=>{let n=dw();for(let r of t.slice(0,lw)){let o=await wl({repoRoot:e,idOrRef:H(r)});a(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},$b=async e=>{let t=mt();if(a(t))return t;let{nodes:n}=t.value;if(!n[e.swimlaneId])return c("Swimlane not found");let o=Object.values(n).filter(_),s=o.map(d=>fu(d.log??[],De(d.id))),i=Ob(e.swimlaneId,s.map(d=>d.map(m=>m.laneId)),d=>n[d]?.title??"Elsewhere"),l=o.filter(d=>d.parentNodeId===e.swimlaneId).map(d=>d.id);return u("Derived swimlane stats",{swimlaneId:e.swimlaneId,createdAt:De(e.swimlaneId),...i,stayTrend:_b({laneId:e.swimlaneId,journeys:s,now:Date.now(),days:cw}),code:await uw(e.repoRoot,l)})};var Ub=new Set(["sync","email:link","email:unlink","issues:create","board:create","board:edit:title","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 jb=e=>{let t=Un({exclude:e});return a(t)?[]:t.value.map(n=>({projectId:n.projectId,name:Eo(n.root),root:n.root,lastOpenedAt:n.lastOpenedAt}))},Hb=e=>{let t=Un();if(a(t))return c(t.message);let n=t.value.find(r=>r.root===e);return n?u("Resolved recent project",n.root):c(`Not a recent project: ${e}`)};import{z as k}from"zod";var ee=k.string().min(1),Wb=k.discriminatedUnion("at",[k.object({at:k.literal("start")}),k.object({at:k.literal("end")}),k.object({at:k.literal("before"),sibling:ee}),k.object({at:k.literal("after"),sibling:ee})]),Ii=k.number().finite(),ie=(e,t)=>k.object({type:k.literal(e),payload:t}),ro=e=>k.object({type:k.literal(e)}),mw=k.discriminatedUnion("type",[ro("state:get"),ro("issues:list"),ro("sync"),ro("time-travel:live"),ro("diff-stats:get"),ie("project:open",k.object({root:k.string().min(1)})),ie("issues:create",k.object({title:k.string(),parentId:ee,description:k.string().optional(),tagNames:k.array(k.string()).optional()})),ie("board:create",k.object({title:k.string()})),ie("board:edit:title",k.object({boardId:ee,title:k.string()})),ie("swimlane:create",k.object({title:k.string(),boardId:ee})),ie("swimlane:edit:title",k.object({swimlaneId:ee,title:k.string()})),ie("swimlane:delete",k.object({swimlaneId:ee})),ie("swimlane:move",k.object({swimlaneId:ee,boardId:ee,position:Wb.optional()})),ie("issues:move",k.object({issueId:ee,parentId:ee,position:Wb.optional()})),ie("issue:edit:title",k.object({issueId:ee,title:k.string()})),ie("issue:edit:description",k.object({issueId:ee,description:k.string()})),ie("issue:tag:add",k.object({issueId:ee,tagName:k.string()})),ie("issue:tag:remove",k.object({issueId:ee,tagId:ee})),ie("contributor:remove",k.object({contributorId:ee})),ie("tag:remove",k.object({tagId:ee})),k.object({type:k.literal("contributors:get"),payload:k.object({boardId:ee.optional()}).optional()}),ie("issue:assignee:add",k.object({issueId:ee,assigneeId:ee.optional(),assigneeName:k.string().optional(),createUnlinked:k.boolean().optional()})),ie("issue:assignee:remove",k.object({issueId:ee,assigneeId:ee})),ie("issue:close",k.object({issueId:ee})),ie("issue:reopen",k.object({issueId:ee})),ie("issue:comment:add",k.object({issueId:ee,body:k.string()})),ie("issue:comment:delete",k.object({issueId:ee,commentId:ee})),ie("issue:comment:edit",k.object({issueId:ee,commentId:ee,body:k.string()})),ie("issue:get",k.object({issueId:ee})),ie("issue:preview:get",k.object({issueId:ee})),k.object({type:k.literal("timeline:get"),payload:k.object({start:Ii.optional(),end:Ii.optional(),boardId:ee.optional(),requestId:k.number().finite().optional()}).optional()}),k.object({type:k.literal("commits:get"),payload:k.object({start:Ii.optional(),end:Ii.optional(),requestId:k.number().finite().optional()}).optional()}),ie("time-travel:scrub",k.object({targetTime:Ii})),ie("time-travel:checkout-event",k.object({eventId:k.string().min(1)})),ie("commit:inspect",k.object({sha:k.string()})),k.object({type:k.literal("emails:get")}),ie("email:link",k.object({email:k.string().min(1).max(254),contributorId:k.string().min(1).optional()})),ie("email:unlink",k.object({email:k.string().min(1).max(254),contributorId:k.string().min(1).optional()})),ie("commit:diff:get",k.object({sha:k.string()})),ie("issue:commits:get",k.object({issueId:ee})),ie("issue:squashed-diff:get",k.object({issueId:ee})),ie("issue:stats:get",k.object({issueId:ee})),ie("swimlane:stats:get",k.object({swimlaneId:ee})),ro("me:stats:get"),ro("settings:get"),ie("settings:set",k.object({autoSync:k.boolean().optional(),autoSyncIntervalMs:k.number().finite().optional()}))]);var Gb=e=>{let t=mw.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 fw=1024*1024,sm=()=>{jr({type:"state",payload:to(Qr())})},Z=(e,t)=>{e.send(JSON.stringify(t))},Ei=async(e,t)=>{let n=to(await Vt({repoRoot:t}));return a(n)&&n.message===gc?Z(e,{type:"state:unavailable",payload:{message:n.message,repoRoot:t,recentProjects:jb(t)}}):Z(e,{type:"state",payload:n})},gw=async(e,t)=>{let n=()=>Z(e,{type:"state",payload:to(Qr())});if(rt().mode!=="live")return n();let r=await Vt({repoRoot:t});return rt().mode!=="live"?n():Z(e,{type:"state",payload:to(r)})},Ge=async(e,t,n,r,o)=>{if(Z(e,{type:r,payload:o}),a(o))return Z(e,{type:"failed",payload:o.message});n(),gw(e,t)},Vb=(e,t,{onStateChanged:n,onSyncSettingsChanged:r,getPort:o})=>{new pw({server:e,path:"/ws",maxPayload:fw,verifyClient:i=>!Zu(i.origin,o())}).on("connection",i=>{Lg(i),i.on("message",async l=>{let d=async m=>{let{type:p}=m,f=t.repoRoot;if(p==="project:open"){let g=Hb(m.payload.root);return Z(i,{type:"project:open:result",payload:g}),a(g)?void 0:(t.repoRoot=g.value,Ei(i,g.value))}if(p==="timeline:get"){let{requestId:g,...h}=m.payload??{};return Z(i,{type:"timeline",requestId:g,payload:await Kv({repoRoot:f,...h})})}if(p==="issue:get"){let g=m.payload?.issueId,h=Qr(),x=Pu(g);return Z(i,{type:"issue",payload:a(h)?h:u("Issue detail",{...db(h.value,g),history:a(x)?[]:x.value})})}if(p==="issue:preview:get"){let{issueId:g}=m.payload,h=Su(g);return Z(i,{type:"issue:preview:result",payload:{issueId:g,result:a(h)?h:u("Issue preview",ub(g,h.value))}})}if(p==="commits:get"){let{requestId:g,...h}=m.payload??{};return Z(i,{type:"commits",requestId:g,payload:vi(await jo({repoRoot:f,...h}))})}if(p==="emails:get")return Z(i,{type:"emails",payload:await Sl({repoRoot:f}),suggestions:await Rl({repoRoot:f})});if(p==="email:link"||p==="email:unlink"){let h=await(p==="email:link"?qu:Yu)({repoRoot:f,...m.payload});return Z(i,{type:"emails",payload:await Sl({repoRoot:f}),suggestions:await Rl({repoRoot:f}),lastAction:a(h)?{ok:!1,message:h.message}:{ok:!0,message:h.message}}),Ge(i,f,n,`${p}:result`,h)}if(p==="me:stats:get")return Z(i,{type:"me:stats",payload:await Xu({repoRoot:f})});if(p==="settings:get")return Z(i,{type:"settings",payload:ii()});if(p==="settings:set"){let g=Ko({enabled:m.payload.autoSync,intervalMs:m.payload.autoSyncIntervalMs});return a(g)||r(),Z(i,{type:"settings",payload:a(g)?ii():g,lastAction:a(g)?{ok:!1,message:g.message}:{ok:!0,message:g.message}})}if(p==="commit:inspect")return Z(i,{type:"commit:inspect:result",payload:await Js({repoRoot:f,sha:m.payload.sha})});if(p==="commit:diff:get"){let{sha:g}=m.payload;return Z(i,{type:"commit:diff:result",payload:{sha:g,result:await Pd({repoRoot:f,sha:g})}})}if(p==="issue:commits:get"){let{issueId:g}=m.payload;return Z(i,{type:"issue:commits:result",payload:{issueId:g,result:vi(await Kn({repoRoot:f,ref:H(g)}))}})}if(p==="issue:squashed-diff:get"){let{issueId:g}=m.payload;return Z(i,{type:"issue:squashed-diff:result",payload:{issueId:g,result:await Ld({repoRoot:f,ref:H(g)})}})}if(p==="issue:stats:get"){let{issueId:g}=m.payload;return Z(i,{type:"issue:stats:result",payload:{issueId:g,result:await wl({repoRoot:f,idOrRef:H(g)})}})}if(p==="diff-stats:get")return Z(i,{type:"diff-stats",payload:await kb({repoRoot:f})});if(p==="swimlane:stats:get"){let{swimlaneId:g}=m.payload;return Z(i,{type:"swimlane:stats:result",payload:{swimlaneId:g,result:await $b({repoRoot:f,swimlaneId:g})}})}if(p==="time-travel:scrub"){let g=await yu({repoRoot:f,targetTime:m.payload.targetTime});return Z(i,{type:"time-travel:result",payload:g}),a(g)?void 0:sm()}if(p==="time-travel:checkout-event"){let g=await Yv({repoRoot:f,eventId:m.payload.eventId});return Z(i,{type:"time-travel:result",payload:g}),a(g)?void 0:sm()}if(p==="time-travel:live"){let g=await Xv({repoRoot:f});return Z(i,{type:"time-travel:result",payload:g}),a(g)?void 0:sm()}if(p==="state:get")return Ei(i,f);if(p==="sync"){let g=await di({repoRoot:f});return Z(i,{type:"sync:result",payload:g}),n(),Ei(i,f)}if(p==="issue:comment:add"){let g=await fi({repoRoot:f,...m.payload});return Ge(i,f,n,"issue:comment:add:result",g)}if(p==="issue:comment:edit"){let g=await Ku({repoRoot:f,...m.payload});return Ge(i,f,n,"issue:comment:edit:result",g)}if(p==="issue:comment:delete"){let g=await gi({repoRoot:f,...m.payload});return Z(i,{type:"issue:comment:delete:result",payload:g}),a(g)?Z(i,{type:"failed",payload:g.message}):(n(),Ei(i,f))}if(p==="issue:edit:description"){let g=await Lu({repoRoot:f,...m.payload});return Ge(i,f,n,"issue:edit:description:result",g)}if(p==="issue:edit:title"){let g=await ku({repoRoot:f,...m.payload});return Ge(i,f,n,"issue:edit:title:result",g)}if(p==="issue:tag:add"){let g=await Uu({repoRoot:f,...m.payload});return Ge(i,f,n,"issue:tag:add:result",g)}if(p==="issue:tag:remove"){let g=await Hu({repoRoot:f,...m.payload});return Ge(i,f,n,"issue:tag:remove:result",g)}if(p==="contributor:remove"){let g=await Gu({repoRoot:f,...m.payload});return Ge(i,f,n,"contributor:remove:result",g)}if(p==="tag:remove"){let g=await ju({repoRoot:f,...m.payload});return Ge(i,f,n,"tag:remove:result",g)}if(p==="contributors:get")return Z(i,{type:"contributors",boardId:m.payload?.boardId,payload:await Vu({repoRoot:f,...m.payload})});if(p==="issue:assignee:add"){let g=await Wu({repoRoot:f,...m.payload});return Ge(i,f,n,"issue:assignee:add:result",g)}if(p==="issue:assignee:remove"){let g=await zu({repoRoot:f,...m.payload});return Ge(i,f,n,"issue:assignee:remove:result",g)}if(p==="issues:list")return Z(i,{type:"issues",payload:await Nu({repoRoot:f})});if(p==="issues:create"){let g=await Au({...m.payload,repoRoot:f});return Z(i,{type:"issues:create:result",payload:g}),a(g)?jr({type:"failed",payload:g.message}):(n(),Ei(i,f))}if(p==="board:create"){let g=await Du({...m.payload,repoRoot:f});return Ge(i,f,n,"board:create:result",g)}if(p==="board:edit:title"){let g=await Bu({...m.payload,repoRoot:f});return Ge(i,f,n,"board:edit:title:result",g)}if(p==="swimlane:create"){let g=await Ou({...m.payload,repoRoot:f});return Ge(i,f,n,"swimlane:create:result",g)}if(p==="swimlane:edit:title"){let g=await Fu({...m.payload,repoRoot:f});return Ge(i,f,n,"swimlane:edit:title:result",g)}if(p==="swimlane:delete"){let g=await $u({...m.payload,repoRoot:f});return Ge(i,f,n,"swimlane:delete:result",g)}if(p==="swimlane:move"){if(!m.payload.position)return Z(i,{type:"error",message:"Missing move position"});let g=await _u({...m.payload,repoRoot:f});return Ge(i,f,n,"swimlane:move:result",g)}if(p==="issues:move"){if(!m.payload.position)return Z(i,{type:"error",message:"Missing move position"});let g=await Mu({...m.payload,repoRoot:f});return Ge(i,f,n,"issues:move:result",g)}if(p==="issue:close"){let g=await Tu({repoRoot:f,issueId:m.payload.issueId});return Ge(i,f,n,"issue:close:result",g)}if(p==="issue:reopen"){let g=await wu({repoRoot:f,issueId:m.payload.issueId});return Ge(i,f,n,"issue:reopen:result",g)}return Z(i,{type:"error",message:"Unknown message type"})};try{let m=Gb(JSON.parse(l.toString()));if(!m.ok)return Z(i,{type:"error",message:m.error});let p=m.message;return Ub.has(p.type)?await Rr(async()=>rt().mode!=="live"?Z(i,{type:"failed",payload:"Read-only while viewing history"}):d(p)):await d(p)}catch(m){return Z(i,{type:"error",message:m instanceof Error?m.message:String(m)})}})})};var xw=oo.dirname(bw(import.meta.url)),Iw=process.env.IS_LOCAL==="true"?oo.resolve(process.cwd(),"dist/gui"):oo.join(xw,"gui"),Ml,Ew=async()=>(Ml===void 0&&(Ml=await import("node:sea").catch(()=>null)),Ml?.isSea()?Ml:null),Me=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},Sw=e=>Me(e,409,{isError:!0,message:"Read-only while viewing history"}),Pl=(e,t)=>Rr(async()=>rt().mode!=="live"?Sw(e):t()),zb=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)}),Rw=2*1024*1024,Cw={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},Nw=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",Kb=new Map,Aw=e=>`"${yw("sha1").update(e).digest("base64url")}"`,Tw=async e=>{try{let{size:t,mtimeMs:n}=await hw(e);return`${t}:${n}`}catch{return null}},ww=e=>{try{return decodeURIComponent(e)}catch{return null}},qb=async(e,t,n)=>{let r=e==="/"?"/index.html":ww(e);if(r===null)return Me(n,404,{isError:!0,message:"Not found"});let o=r.replace(/^\/+/,""),s=oo.resolve(Iw),i=oo.resolve(s,o),l=oo.relative(s,i);if(l.startsWith("..")||oo.isAbsolute(l))return Me(n,403,{isError:!0,message:"Forbidden"});let d=await Ew(),m=d?"sea":await Tw(i),p=m===null?void 0:Kb.get(l),f=p&&p.stamp===m?p.etag:null;if(f&&t.headers["if-none-match"]===f)return n.writeHead(304,{etag:f,"cache-control":"no-cache"}),n.end();try{let g=d?Buffer.from(d.getAsset(`gui/${l}`)):await Yb(i),h=f??Aw(g);return m!==null&&Kb.set(l,{stamp:m,etag:h}),n.writeHead(200,{"content-type":Nw(i),etag:h,"cache-control":"no-cache"}),n.end(g)}catch{return Me(n,404,{isError:!0,message:`Not found: ${o}`})}},Mw=async(e,t=hi)=>new Promise((n,r)=>{let o=s=>{let i=d=>{if(e.off("listening",l),d.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(d)},l=()=>{e.off("error",i);let d=e.address();if(!d||typeof d=="string"){r(new Error("Unable to resolve address"));return}n(d.port)};e.once("error",i),e.once("listening",l),e.listen(s,"127.0.0.1")};o(t)}),Xb=async e=>{Ov(!1);let t=0,n={repoRoot:e.repoRoot},r=vw.createServer((l,d)=>{o(l,d).catch(m=>(logger.error(`[gui] ${l.method} ${l.url}: ${m instanceof Error?m.message:String(m)}`),d.headersSent?d.end():Me(d,500,{isError:!0,message:"Internal error"})))});async function o(l,d){let m=new URL(l.url??"/","http://127.0.0.1"),p=pb({method:l.method,origin:l.headers.origin,contentType:l.headers["content-type"]},t);if(p)return Me(d,p.status,{isError:!0,message:p.message});if(l.method==="GET"&&m.pathname===Ju)return Me(d,200,{app:Qu,repoRoot:Cl(n.repoRoot),version:Pn,pid:process.pid});if(m.pathname==="/api/state")return Me(d,200,await Vt({repoRoot:n.repoRoot}));if(l.method==="POST"&&m.pathname==="/api/comments")try{let f=await zb(l);if(!f.issueId||!f.body?.trim())return Me(d,400,{isError:!0,message:"Missing issueId or body"});let g=f.issueId,h=f.body;return await Pl(d,async()=>{let x=await fi({repoRoot:n.repoRoot,issueId:g,body:h});return a(x)?Me(d,400,{isError:!0,message:x.message}):Me(d,200,await Vt({repoRoot:n.repoRoot}))})}catch(f){return Me(d,400,{isError:!0,message:f instanceof Error?f.message:"Unable to add comment"})}if(l.method==="POST"&&m.pathname==="/api/attachments")try{let f=await zb(l,Rw);if(!f.issueId||!f.dataBase64)return Me(d,400,{isError:!0,message:"Missing issueId or dataBase64"});let g=f.issueId,h=f.dataBase64,x=f.name??"";return await Pl(d,async()=>{let b=await xu({repoRoot:n.repoRoot,issueId:g,name:x,dataBase64:h});return a(b)?Me(d,400,{isError:!0,message:b.message}):Me(d,200,{...await Vt({repoRoot:n.repoRoot}),attachment:b.value})})}catch(f){return Me(d,400,{isError:!0,message:f instanceof Error?f.message:"Unable to add attachment"})}if(l.method==="DELETE"&&m.pathname.startsWith("/api/attachments/")){let f=decodeURIComponent(m.pathname.replace("/api/attachments/",""));return f?Pl(d,async()=>{let g=await Iu({repoRoot:n.repoRoot,attachmentId:f});return a(g)?Me(d,400,{isError:!0,message:g.message}):Me(d,200,await Vt({repoRoot:n.repoRoot}))}):Me(d,400,{isError:!0,message:"Missing attachment id"})}if(l.method==="GET"&&m.pathname.startsWith("/media/")){let f=decodeURIComponent(m.pathname.replace("/media/","")),g=await Eu({repoRoot:n.repoRoot,fileName:f});if(a(g))return Me(d,404,{isError:!0,message:g.message});try{let h=await Yb(g.value.filePath);return d.writeHead(200,{"content-type":Cw[g.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),d.end(h)}catch{return Me(d,404,{isError:!0,message:"Attachment blob not found"})}}if(l.method==="DELETE"&&m.pathname.startsWith("/api/comments/")){let f=decodeURIComponent(m.pathname.replace("/api/comments/",""));return f?Pl(d,async()=>{let g=await gi({repoRoot:n.repoRoot,commentId:f});return a(g)?Me(d,400,{isError:!0,message:g.message}):Me(d,200,await Vt({repoRoot:n.repoRoot}))}):Me(d,400,{isError:!0,message:"Missing comment id"})}return m.pathname.startsWith("/board/")||m.pathname==="/log"?qb("/",l,d):qb(m.pathname,l,d)}try{t=await Mw(r)}catch(l){return c(l instanceof Error?`Unable to start GUI server: ${l.message}`:`Unable to start GUI server: ${String(l)}`)}let s=mb({project:n});Vb(r,n,{onStateChanged:()=>s.queueSync(),onSyncSettingsChanged:()=>s.reschedule(),getPort:()=>t}),r.on("close",s.dispose);let i=r.address();return!i||typeof i=="string"?(r.close(),c("Unable to resolve GUI server address")):u("Started GUI server",{url:`http://epiq.localhost:${i.port}${e.boardId?`/board/${e.boardId}`:""}`,server:r})};var Qb=async e=>{let t=co({});if(a(t))return c(t.message);let n=gt();ye(n)&&$e(n.value);let r=await lb(hi);if(r&&r.repoRoot===Cl(e.repoRoot)){let i=`http://127.0.0.1:${hi}`;return console.log(`Epiq GUI already running for this project at ${Jb.cyan(i)}`),Ic(i),u("Reused running GUI",{url:i})}let o=await Xb({...e,boardId:""});if(a(o))return o;let{url:s}=o.value;return console.log(`Epiq GUI running at ${Jb.cyan(s)}`),Ic(s),u("Started GUI",{url:s})};import{Box as Jn}from"ink";import Pe from"react";import{Box as im,Text as Si}from"ink";import dn,{useEffect as Pw,useMemo as Lw}from"react";import{ulid as kw}from"ulid";var Zb=({text:e,match:t,color:n,highlightColor:r=y.secondary,dimColor:o=!1})=>{if(!t)return dn.createElement(Si,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),l=s.indexOf(i);return l===-1?dn.createElement(Si,{color:n,dimColor:o},e):dn.createElement(Si,{color:n,dimColor:o},e.slice(0,l),dn.createElement(Si,{backgroundColor:r,bold:!0},e.slice(l,l+t.length)),e.slice(l+t.length))},ex=kw(),Dw=e=>`${e}`,Bw=e=>{let{pendingNavTarget:t}=vr();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(Be(R.NONE,{breadCrumb:n,contextNode:r,readOnly:v().readOnly,selectedNode:o}));return[...new Set(Object.values(R))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==R.PALETTE).map(i=>{let l=ka(i),d=dl.find(m=>m.intent===l);return{command:i,description:d?.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))},Ow=e=>Re.text({id:ex,parentNodeId:e,rank:"000000",name:"Command Palette",readonly:!0,isVirtual:!0}),Fw=(e,t,n)=>Re.text({id:Dw(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,disabled:!e.isAvailable,readonly:!0,isVirtual:!0}),am=[],_w=e=>{tx();let t=C.createNode(Ow(v().rootNodeId));a(t)||!rr(t.value)||(am=[t.value,...e.map((n,r)=>Fw(n,r,ex)).map(C.createNode).filter(ye).map(({value:n})=>n).filter(rr)],U.navigate({contextNode:t.value,selectedIndex:0}))},tx=()=>{let e=am.map(t=>t.id);am=[];for(let t of e)C.deleteNode(t)};function nx({width:e,height:t}){let r=Ef().value.trim().toLowerCase(),o=Lw(()=>Bw(r),[r]);Pw(()=>(_w(o),()=>{tx()}),[o]);let s=v().selectedIndex;return dn.createElement(im,{flexDirection:"column",width:e,height:t-2},dn.createElement(dt,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,l)=>{let d=l===s,m=i.isAvailable?y.accent:y.secondary2,p=i.isAvailable?"":"[unavailable] ";return dn.createElement(im,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},dn.createElement(Si,{color:m,dimColor:!i.isAvailable},d?"\u276F ":" ",dn.createElement(Zb,{text:xp(i.command),match:r,color:m,dimColor:!i.isAvailable})),dn.createElement(im,{paddingLeft:2},dn.createElement(Zb,{text:p+i.description,match:r.length>=2?r:"",color:d&&i.isAvailable?y.primary:y.secondary2,dimColor:!i.isAvailable})))})))}import{Box as Zw}from"ink";import Dl from"react";import Ci from"chalk";import{Box as Ri,Text as ix}from"ink";import so,{useEffect as ax,useMemo as $w,useState as lx}from"react";var Zo=["\u2803","\u2806","\u2830","\u2818"],rx=120,ox=({isPalette:e,isPending:t,frame:n})=>{if(t){let r=(n%Zo.length+Zo.length)%Zo.length;return Zo[r]}return e?"?":":"},sx=({infoMessage:e,isPending:t})=>t&&e.includes(me)?"":e;var cx=Ci.hex(y.secondary),Uw=Ci.inverse,jw=Ci.inverse.hex(y.secondary2),Hw={hint:"",hints:[],overlap:0,remainder:""},ux=({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}},Ww=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=ze(t);return{bg:r=>Ci.bgHex(n).black(r),bgCursor:r=>Ci.bgHex(n).inverse.black(r)}}return Ac(t)},Gw=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=ux({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}},dx=()=>({value:lt.value,cursorPosition:lt.cursorPosition,commandIsPending:lt.commandIsPending,autoCompletion:lt.commandMeta.autoCompletion??Hw,infoMessage:lt.commandMeta.infoMessage,validationStatus:lt.commandMeta.validity,command:lt.commandMeta.command,inputString:lt.commandMeta.inputString,modifier:lt.commandMeta.modifier}),Vw=(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,mx=({width:e,mode:t})=>{let[n,r]=lx(dx());ax(()=>{let A=()=>{let P=dx();r(M=>Vw(M,P)?M:P)},T=Wc(A);return A(),()=>{T()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:l,autoCompletion:d,command:m,modifier:p,validationStatus:f}=n,g=l&&f===xn.Invalid,h=sx({infoMessage:i,isPending:l}),[x,b]=lx(0);ax(()=>{if(!l){b(0);return}let A=setInterval(()=>{b(T=>(T+1)%Zo.length)},rx);return()=>{clearInterval(A)}},[l]);let N=ox({isPalette:t===I.PALETTE,isPending:l,frame:x}),S=$w(()=>{let A=Math.max(0,Math.min(s,o.length)),T=ux({value:o,command:m}),P=Gw({value:o,command:m,modifier:p}),M=m?Ac(m):null,O=Ww({command:m,modifier:p}),W=(ot,pt)=>{let ao=T&&pt>=T.start&&pt<T.end,Xl=P&&pt>=P.start&&pt<P.end;return ao&&M?M.fg(ot):Xl&&O?O.bg(ot):ot},Y=(ot,pt)=>{let ao=T&&pt>=T.start&&pt<T.end,Xl=P&&pt>=P.start&&pt<P.end;return ao&&M?M.fgCursor(ot):Xl&&O?O.bgCursor(ot):Uw(ot)},xe=o.slice(0,A),F=o[A]??" ",X=A<o.length?o.slice(A+1):"",Ve=Array.from(xe).map((ot,pt)=>W(ot,pt)).join(""),Qn=Y(F,A),ss=Array.from(X).map((ot,pt)=>W(ot,A+1+pt)).join("");if(d.hint){let ot=d.hint[d.overlap]??F;Qn=jw(ot),ss=cx(d.remainder.slice(1)+X)}return Ve+Qn+ss},[o,s,d,m,p]);return so.createElement(Ri,{flexDirection:"column",justifyContent:"flex-start"},so.createElement(Ri,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},so.createElement(Ri,{height:1,flexWrap:"nowrap"},so.createElement(Ri,{flexShrink:0},so.createElement(ix,{wrap:"truncate-start"},cx(N),S)),h&&so.createElement(Ri,{flexShrink:1,minWidth:0},so.createElement(ix,{wrap:"truncate",color:g?y.red:y.secondary2},` ${h} `)))))};import{Box as zw,Text as Ni}from"ink";import es from"react";var px=" ",Kw=({keys:e,label:t})=>e.length+1+t.length,qw=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?px.length:0)+Kw(o);if(r+i>t-4)break;n.push(o),r+=i}return n},fx=({width:e,availableHints:t})=>{let n=qw(t,e);return es.createElement(zw,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1},n.length?es.createElement(Ni,{wrap:"truncate"},n.map(({keys:o,label:s},i)=>es.createElement(Ni,{key:`${o}-${s}`},i>0?px:"",es.createElement(Ni,{color:y.accent},o),es.createElement(Ni,{color:y.secondary2}," ",s)))):es.createElement(Ni,{color:y.secondary2},"\xA0"))};import{Box as Yw,Text as Ll}from"ink";import Ai,{useEffect as Xw,useRef as ts,useState as Jw}from"react";var Qw=40,kl=.3,lm="\u2500",gx=1,hx=16,yx=({width:e})=>{let{replay:t}=te(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*gx,[l,d]=Jw(0),m=ts(r);m.current=r;let p=ts(0),f=ts(0),g=ts(0),h=ts(0),x=ts(0);if(Xw(()=>{if(!n){p.current=0,g.current=0,h.current=0,x.current=0,d(0);return}p.current=m.current,f.current=Date.now(),g.current=m.current;let T=setInterval(()=>{let P=Date.now(),M=m.current;if(M!==g.current){let F=M-g.current,X=P-f.current;if(F<0)h.current=0,x.current=0;else if(F>0&&X>0){let Ve=F/X;h.current=h.current===0?Ve:h.current*(1-kl)+Ve*kl,x.current=x.current===0?F:x.current*(1-kl)+F*kl}p.current=M,f.current=P,g.current=M}let O=P-f.current,W=Math.min(x.current,h.current*O),Y=Math.min(1,p.current+W),xe=Math.round(Y*i);d(F=>F===xe?F:xe)},Qw);return()=>clearInterval(T)},[n,i]),!t)return null;let b=T=>{let P=s>1?T/(s-1):0,M=Math.round(P*(hx-1))/(hx-1);return Vi(M)},N=Math.min(s,Math.floor(l/gx)),S=[];for(let T=0;T<N;T++){let P=b(T),M=S[S.length-1];M&&M.color===P?M.text+=lm:S.push({text:lm,color:P})}let A=lm.repeat(Math.max(0,s-N));return Ai.createElement(Yw,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1,columnGap:1},Ai.createElement(Ll,{color:y.secondary2},"\u25B6"),Ai.createElement(Ll,null,S.map((T,P)=>Ai.createElement(Ll,{key:P,color:T.color},T.text)),Ai.createElement(Ll,{color:y.secondary,dimColor:!0},A)))};var Ti=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=te(),o=t===I.COMMAND_LINE||t===I.PALETTE;return Dl.createElement(Zw,null,o?Dl.createElement(mx,{width:e,mode:t}):r==="replay"?Dl.createElement(yx,{width:e}):Dl.createElement(fx,{width:e,mode:t,availableHints:n}))};import{Box as Tr,Text as ns}from"ink";import vt,{useEffect as eM,useMemo as tM}from"react";import{ulid as vx}from"ulid";var Ol=vx(),nM=()=>[...new Set([...v().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(lu).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})),rM=e=>Re.text({id:Ol,parentNodeId:e,rank:"000000",name:"Help",isVirtual:!0,readonly:!0}),oM=(e,t,n)=>Re.text({id:vx(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,readonly:!0,isVirtual:!0}),Bl=[],bx=()=>{let e=Bl.filter(n=>n.id!==Ol).map(n=>n.id),t=Bl.filter(n=>n.id===Ol).map(n=>n.id);Bl=[];for(let n of[...e,...t])C.deleteNode(n)},sM=e=>{bx();let t=C.createNode(rM(v().rootNodeId));if(a(t)||!rr(t.value))return logger.error("Could not attach help nodes");Bl=[t.value,...e.map((n,r)=>oM(n,r,Ol)).map(C.createNode).filter(ye).map(({value:n})=>n).filter(rr)],U.navigate({contextNode:t.value,selectedIndex:0})},xx=({width:e,height:t})=>{let n=tM(()=>nM(),[]);eM(()=>(sM(n),()=>{bx()}),[n]);let r=v().selectedIndex;return vt.createElement(Tr,{flexDirection:"column",marginTop:3,borderColor:y.secondary,borderStyle:"round",width:e,height:t-2},vt.createElement(Tr,{paddingX:1,justifyContent:"center"},vt.createElement(ns,{color:y.accent},"Help"),vt.createElement(ns,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),vt.createElement(Tr,{paddingX:1,marginTop:1},vt.createElement(Tr,{width:20,justifyContent:"flex-end"},vt.createElement(ns,{color:y.secondary},"Key(s)")),vt.createElement(Tr,{flexGrow:1,width:40,paddingLeft:2},vt.createElement(ns,{color:y.secondary},"Action"))),vt.createElement(dt,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let l=i===r;return vt.createElement(Tr,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},vt.createElement(Tr,{width:20,justifyContent:"flex-end"},vt.createElement(ns,{color:y.accent},o)),vt.createElement(Tr,{flexGrow:1,width:40,paddingLeft:2},vt.createElement(ns,{color:l?y.primary:y.secondary2},s)))})))};import{Box as rs,Text as bt}from"ink";import Ae,{useEffect as iM,useState as cm}from"react";var Fl=({index:e,email:t,note:n,noteColor:r})=>Ae.createElement(rs,null,Ae.createElement(bt,{color:y.accent},e===void 0?" ":` ${e}.`),Ae.createElement(bt,null," ",t),n&&Ae.createElement(bt,{color:r??y.secondary2},` ${n}`)),Ix=({height:e})=>{let[t,n]=cm([]),[r,o]=cm([]),[s,i]=cm(null),{userName:l,gitEmail:d,gitName:m,userId:p}=V();return iM(()=>{let f=!0;return(async()=>{let h=ve(),x=ce(process.cwd());if(a(h)||a(x)||!p)return;let b=h.value.emailLinks,N=gn(b,p);n(N.map(P=>({email:P,others:vs(b,P).filter(M=>M!==p).map(M=>h.value.contributors[M]?.name??M)})));let S=ke(x.value),A=await Mn({repoRoot:x.value,stateBranch:a(S)?void 0:S.value,names:[l,m],links:b});if(!f)return;if(a(A)){i(A.message);return}let T=xr(A.value);So(T.map(P=>P.email)),o(T)})(),()=>{f=!1}},[p,l,m,d]),Ae.createElement(rs,{height:e-4,flexDirection:"column",paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},Ae.createElement(rs,null,Ae.createElement(bt,{color:y.accent,bold:!0},l??"Not configured"),Ae.createElement(bt,{color:y.secondary2}," on this board")),s&&Ae.createElement(bt,{color:y.red},s),Ae.createElement(rs,{flexDirection:"column"},Ae.createElement(bt,{color:y.secondary2},"CLAIMED"),t.length===0?Ae.createElement(Fl,{email:"Nothing claimed \u2014 your commits show the name git signed them with.",note:""}):t.map(f=>Ae.createElement(Fl,{key:f.email,email:f.email,note:f.others.length>0?`CONTESTED: also ${f.others.join(", ")}, resolves to nobody`:f.email===d?"your git identity here":void 0,noteColor:f.others.length>0?y.yellow:void 0}))),Ae.createElement(rs,{flexDirection:"column"},Ae.createElement(bt,{color:y.secondary2},"UNCLAIMED IN THIS HISTORY"),r.length===0?Ae.createElement(Fl,{email:"Nothing left to claim here."}):r.map(f=>Ae.createElement(Fl,{key:f.email,email:f.email,note:`${f.commits} commit${f.commits===1?"":"s"} as ${f.names.join(", ")||"unknown"}`}))),Ae.createElement(rs,{flexDirection:"column"},Ae.createElement(bt,{color:y.secondary2},Ae.createElement(bt,{color:y.accent},"[enter]")," writes a claim for the first into the command line, to confirm or change."),Ae.createElement(bt,{color:y.secondary2},Ae.createElement(bt,{color:y.accent},":config emails")," claims by address,",Ae.createElement(bt,{color:y.accent}," :config emails-unclaim "),"gives one back."),Ae.createElement(bt,{color:y.secondary2},Ae.createElement(bt,{color:y.accent},"[esc]")," to close")))};import aM from"chalk";import{Box as io,Text as tt}from"ink";import Te from"react";var lM=8,cM=()=>{let e=Un({exclude:process.cwd()});return a(e)?[]:e.value.slice(0,lM)},Ex=({width:e,height:t})=>{let n=cM();return Te.createElement(io,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},Te.createElement(tt,{color:y.accent,bold:!0},"Initialize project"),Te.createElement(tt,null,`This folder is not an ${aM.hex(y.accent)("epiq")} project yet.`),Te.createElement(tt,{color:y.primary},"To start tracking issues here, we need to initialize a new",Te.createElement(tt,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json "),"file in this repository."),Te.createElement(io,{marginTop:1,flexDirection:"column"},Te.createElement(io,null,Te.createElement(tt,{color:y.accent}," "),Te.createElement(tt,{color:y.primary},"Type "),Te.createElement(tt,{backgroundColor:y.secondary}," :init "))),Te.createElement(io,{marginTop:1},Te.createElement(tt,{color:y.secondary2},"This will create, commit and push "),Te.createElement(tt,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json ")),n.length>0&&Te.createElement(io,{marginTop:1,flexDirection:"column"},Te.createElement(tt,{color:y.accent,bold:!0},"Or open a recent project"),n.map((r,o)=>Te.createElement(io,{key:r.projectId},Te.createElement(tt,{color:y.accent},` ${o+1} `),Te.createElement(tt,{color:y.primary},Eo(r.root)),Te.createElement(tt,{color:y.secondary2},` ${r.root}`))),Te.createElement(io,{marginTop:1},Te.createElement(tt,{color:y.accent}," "),Te.createElement(tt,{color:y.primary},"Type "),Te.createElement(tt,{backgroundColor:y.secondary}," :open 1 "),Te.createElement(tt,{color:y.secondary2}," or "),Te.createElement(tt,{backgroundColor:y.secondary}," :open <path> "))))};import{Box as $l,Text as Ot}from"ink";import _e from"react";import{Box as _l,Text as Xn}from"ink";import Bt,{useEffect as dM,useState as Sx}from"react";var Rx=()=>{let[e,t]=Sx(null),[n,r]=Sx(null);return dM(()=>{let o=!0;return(async()=>{let i=ve(),l=ce(process.cwd());if(a(i)||a(l))return;let d=ke(l.value),{userName:m,gitName:p}=V(),f=await Mn({repoRoot:l.value,stateBranch:a(d)?void 0:d.value,names:[m,p],links:i.value.emailLinks});if(!o)return;if(a(f)){r(f.message);return}let g=xr(f.value);So(g.map(h=>h.email)),t(g)})(),()=>{o=!1}},[]),n?Bt.createElement(_l,{marginTop:1},Bt.createElement(Xn,{color:y.red},n)):e===null?null:e.length===0?Bt.createElement(_l,{marginTop:1},Bt.createElement(Xn,{color:y.secondary2},"No unclaimed addresses in this history \u2014 type",Bt.createElement(Xn,{color:y.accent}," :config emails none "),"to move on.")):Bt.createElement(_l,{flexDirection:"column",marginTop:1},e.map(o=>Bt.createElement(Xn,{key:o.email},Bt.createElement(Xn,{color:y.accent}," \xB7 "),Bt.createElement(Xn,null,o.email),Bt.createElement(Xn,{color:y.secondary2},` ${o.commits} commit${o.commits===1?"":"s"} as ${o.names.join(", ")||"unknown"}`))),Bt.createElement(_l,{marginTop:1},Bt.createElement(Xn,{color:y.secondary2},"Claim yours by address, or",Bt.createElement(Xn,{color:y.accent}," none "),"to skip.")))};var uM=({isDone:e,command:t,value:n,verb:r="Type",hint:o})=>_e.createElement($l,null,_e.createElement(Ot,{color:y.accent,dimColor:e},e?" \u2714 ":" "),_e.createElement(Ot,{dimColor:e},r," "),_e.createElement(Ot,{backgroundColor:y.secondary,dimColor:e}," "+t+" "),n!==void 0&&_e.createElement(_e.Fragment,null,_e.createElement(Ot,{dimColor:e}," "),_e.createElement(Ot,{color:y.secondary,dimColor:e},"<"+n+">")),o),mM=(e,t)=>e.length===0?void 0:$n(e.join(", "),Math.max(12,t-34)),pM=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function dm({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:l,isSetEmails:d,claimedEmails:m,emailSetupDeclined:p}=jn(),f=[{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."},{key:"emails",done:d,command:":config emails",value:p?"declined":mM(m,e),message:"Last one. Claim the git addresses whose commits are yours, so the board calls them by your name."}],g=f.findIndex(x=>!x.done),h=g===-1?void 0:f[g];return _e.createElement($l,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},_e.createElement(Ot,{color:y.accent,bold:!0},"Welcome! \u{1F539}"),_e.createElement(Ot,null,"Let's get you started - it's a breeze."),_e.createElement(Ot,{color:y.secondary2},"Remember - you can always search available commands by typing:",_e.createElement(Ot,{color:y.accent}," ? ")),h&&_e.createElement(Ot,{color:y.secondary2},h.message),_e.createElement($l,{flexDirection:"column"},f.map((x,b)=>{if(!(g===-1||b<=g))return null;let S=b===g,A=S&&g===0;return _e.createElement($l,{key:x.key,flexDirection:"column",marginBottom:1},_e.createElement(uM,{isDone:x.done,command:A?":config us":x.command,value:x.done?pM(x.value):void 0,verb:S&&!A?"Waiting:":"Type",hint:A?_e.createElement(Ot,{color:y.secondary2}," then ",_e.createElement(Ot,{color:y.accent},"tab")," to auto-complete ",_e.createElement(Ot,{backgroundColor:y.secondary},` ${x.command.split(" ").pop()} `)):void 0}),x.key==="emails"&&!x.done&&_e.createElement(Rx,null))})))}import Gl from"chalk";import{Box as Mi,Text as os}from"ink";import Je from"react";import{Box as Ul,Text as Cx}from"ink";import wr from"react";import fM from"chalk";var gM=e=>(C.getTag(e)?.name??"").length+3,hM=e=>{let t=C.getContributor(e);return(t?t.name:"").length+3},Nx=({width:e})=>{let{viewMode:t}=V(),n=te(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,l=i[o.id]?.[s],d=Nt(l?.id??o.id,"TICKET"),m=ye(d)?d.value:void 0,p=(m?.props.tags??[]).filter(M=>C.getTag(M)),f=m?.props.assignees??[],g=m?.parentNodeId?!pu(o.id,m.parentNodeId)&&t==="dense":!1,h=r.map((M,O)=>{let W=O===r.length-1,Y=be(M.id),xe=W?Y?.[s]?.title:void 0;return`${O?" / ":""}${M.title??""}${xe?` \u25B8 ${xe}`:""}`}).join(""),x=m?C.getCommentsByIssue(m.id):[],b=x.length?String(x.length).length+11:0,N=g?p.reduce((M,O)=>M+gM(O),0)+f.reduce((M,O)=>M+hM(O),0)+b:0,S=l?.id!=null&&!(t==="wide"&&_(l)),A=Math.max(0,e-N),T=h.substring(0,A)+(S?fM.hex(y.secondary2).dim(` ${H(l.id)}`):""),P=g?[...p.map(M=>wr.createElement(Ul,{key:`tag-${M}`,paddingLeft:1},wr.createElement(ko,{id:M}))),...f.map(M=>wr.createElement(Ul,{key:`assignee-${M}`,paddingLeft:1},wr.createElement(mr,{id:M}))),x.length?wr.createElement(Ul,{key:"comments",paddingLeft:1},wr.createElement(Cx,{color:y.accent},"[",x.length," comment",x.length===1?"":"s","]")):null]:[];return wr.createElement(Ul,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},wr.createElement(Cx,{color:y.secondary2},T),P)};import{Box as yM,Text as Ax}from"ink";import jl from"react";var vM=({filters:e})=>jl.createElement(yM,{columnGap:1},jl.createElement(Ax,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>jl.createElement(Ax,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Tx=jl.memo(vM);import{Box as bM,Text as Hl}from"ink";import wi from"react";function wx(){let{eventLog:e,unappliedEvents:t}=te(),n=e.at(-1)?.id,r=vo(n??""),o=ye(r)?_a(r.value):"INVALID DATE";return wi.createElement(bM,{paddingLeft:1},wi.createElement(Hl,{backgroundColor:y.accent,color:y.secondary}," Readonly "),wi.createElement(Hl,{color:y.accent}," "+t.length+" edits ago at "+o+"."),wi.createElement(Hl,{color:y.accent}," Resume with "),wi.createElement(Hl,{backgroundColor:y.accent,color:y.secondary}," ",":peek now"," "))}import{Box as xM,Text as um}from"ink";import Wl from"react";function Mx(){let{replay:e}=te();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return Wl.createElement(xM,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},Wl.createElement(um,{backgroundColor:y.accent,color:y.secondary}," \u25B6 REPLAY "),Wl.createElement(um,{color:y.secondary2},_a(new Date(r))),Wl.createElement(um,{color:y.accent},`${t}/${n} edits`))}import mm from"chalk";import{Box as IM,Text as Px}from"ink";import pm,{useEffect as EM,useState as SM}from"react";var RM=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],CM=150,Lx=12,NM=.36;function kx({syncStatus:e,autoSync:t}){let[n,r]=SM(0);EM(()=>{if(e.status!=="syncing"){r(0);return}let l=0,d=setInterval(()=>{l+=1;let m=(Math.sin(l*NM)+1)/2,p=Math.round(m*(Lx-1));r(f=>f===p?f:p)},CM);return()=>clearInterval(d)},[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:dp(RM,n/(Lx-1))??""}[e.status];return pm.createElement(IM,null,pm.createElement(Px,null,mm.hex(y.secondary2).dim(t?"Sync (auto): ":"Sync: ")),pm.createElement(Px,null,mm.hex(i)("\u25CF")+mm.hex(y.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import _x from"chalk";import{Text as $x}from"ink";import Ux,{useEffect as MM,useState as PM}from"react";import fm from"chalk";var AM="https://registry.npmjs.org/epiq/latest",gm=null,Dx=0,TM=1e3*60*60*24,Bx=e=>e.replace(/^v/,""),wM=(e,t)=>{let n=Bx(e).split(".").map(Number),r=Bx(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},Ox=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(gm&&Date.now()-Dx<TM)return gm;try{let t=await fetch(AM);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?wM(r,e)>0:!1};return gm=o,Dx=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},Fx=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?fm.hex(y.accent).dim(s):fm.hex(y.secondary).dim(s)).join(fm.hex(y.secondary2).dim("."))};function jx(){let[e,t]=PM({current:Pn,latest:null,updateAvailable:!1});return MM(()=>{let n=!0;return Ox(Pn).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?Ux.createElement($x,{dimColor:!0,color:y.secondary2},Pn+" "):Ux.createElement($x,null,_x.hex(y.secondary2).dim(Pn),_x.hex(y.accent).dim(" \u2197 "),Fx(Pn,e.latest))}function Pi({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=te(),{userName:i,preferredEditor:l,autoSync:d}=V(),m=64,p=process.stdout.columns-m-8,f=t||n==="replay",g=s?_n(s.currentLabel,Math.max(0,p)):"";return Je.createElement(Mi,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?Je.createElement(Mi,{paddingLeft:1},Je.createElement(os,{color:y.secondary2},g)):f?Je.createElement(os,null," "):o===I.PALETTE?Je.createElement(Mi,null,Je.createElement(os,{color:y.accent},"Command Palette"),Je.createElement(os,{dimColor:!0,color:y.secondary2}," ","- search, select and press enter")):Je.createElement(Mi,{paddingLeft:1},e.length>0?Je.createElement(Tx,{filters:e}):Je.createElement(Nx,{width:p})),n==="live"?Je.createElement(Mi,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},Je.createElement(kx,{autoSync:!!d,syncStatus:r}),Je.createElement(os,null,Gl.hex(y.secondary2).dim("Mode: ")+Gl.hex(y.secondary2).dim(o.padEnd(8," "))," "),Je.createElement(Hx,{icon:"@",value:i}),Je.createElement(Hx,{icon:"\u276F",value:l}),Je.createElement(jx,null)):"",n==="peek"?Je.createElement(wx,null):"",n==="replay"?Je.createElement(Mx,null):"")}function Hx({icon:e,value:t}){return Je.createElement(os,null,Gl.dim(e)+Gl.hex(y.accent)(` ${t??"-"} `))}import{Box as LM,Text as kM}from"ink";import Li from"react";import{Box as Vl,Text as hm}from"ink";import Mr from"react";function ym(){let e=te(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?ae(t?.id):[];return Mr.createElement(Vl,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:y.secondary,width:s},Mr.createElement(Vl,{padding:1,paddingTop:0,paddingBottom:0},Mr.createElement(hm,null,"Select a board:")),Mr.createElement(Vl,{padding:1,flexDirection:"column"},i.map((l,d)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===d,f=ae(l.id).flatMap(({id:g})=>be(g)).length;return Mr.createElement(Vl,{key:l.id??d},Mr.createElement(hm,{color:m?y.accent:y.secondary2},Mr.createElement(St,{isSelected:m})),Mr.createElement(hm,{color:m?y.accent:y.secondary2},l.title," (",f," issues)",l.readonly?" \u{1F512}":""))})))}var DM=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:l}=te(),d=n.find(({context:g})=>g==="BOARD"),f=s-1-3;return Li.createElement(LM,{flexDirection:"row"},e.context==="WORKSPACE"?Li.createElement(ym,null):d?Li.createElement(Ja,{height:f,width:i,swimlanes:(l[d.id]??[]).filter(g=>g!==void 0&&hn(g)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Li.createElement(kM,null))},Wx=Li.memo(DM);import{useEffect as BM}from"react";var OM=e=>{BM(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=V();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:l,mode:d}=v();d==="default"&&!l&&La(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},Gx=({autoSync:e})=>(OM(e),null);function vm({width:e,height:t}){let n=te(),{autoSync:r,viewMode:o}=op(),s=n.filters;if(n.mode===I.HELP)return Pe.createElement(Jn,{flexDirection:"column"},Pe.createElement(xx,{width:e,height:t}));if(n.mode===I.IDENTITY)return Pe.createElement(Jn,{flexDirection:"column"},Pe.createElement(Ix,{width:e,height:t}));if(n.mode===I.PALETTE)return Pe.createElement(Jn,{flexDirection:"column"},Pe.createElement(Pi,{filters:s}),Pe.createElement(nx,{width:e,height:t-2}),Pe.createElement(Ti,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=jn(),l=!i,d=i&&!n.hasProjectDefinition;if(l)return Pe.createElement(Jn,{flexDirection:"column"},Pe.createElement(Jn,{flexDirection:"column"},Pe.createElement(Pi,{hideBreadCrumb:!0,filters:s}),Pe.createElement(dm,{height:t,width:e})),Pe.createElement(Ti,{width:e,mode:n.mode,availableHints:[]}));if(d)return Pe.createElement(Jn,{flexDirection:"column"},Pe.createElement(Jn,{flexDirection:"column"},Pe.createElement(Pi,{hideBreadCrumb:!0,filters:s}),Pe.createElement(Ex,{height:t,width:e})),Pe.createElement(Ti,{width:e,mode:n.mode,availableHints:[]}));let m=ht(n.breadCrumb??[],"BOARD");if(ye(m)){let p=m.value.id,f=ae(p).length,g=3,h=Math.floor(e/g),x=Math.floor(e/Math.max(f,1));e=Math.min(x,h)*Math.max(f,g)}return Pe.createElement(Jn,{flexDirection:"column"},Pe.createElement(Gx,{autoSync:r}),Pe.createElement(Jn,{flexDirection:"column"},Pe.createElement(Pi,{filters:s}),Pe.createElement(Wx,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),Pe.createElement(Ti,{width:e,mode:n.mode,availableHints:n.availableHints}))}import FM from"readline";var zl,Kl,kn,_M=new Set([E.MoveCursorLeft,E.EraseInputWord,E.MoveCursorLeftOfWord,E.MoveCursorRight,E.MoveCursorRightOfWord,E.NavToPreviousContainer,E.NavToNextContainer,E.NavPreviousItem,E.NavNextItem,E.NavPreviousItemJump,E.NavNextItemJump,E.SetViewDense,E.SetViewWide,E.Confirm,E.Exit,E.Yank,E.InitCommandLine,E.InitCommandPalette,E.ExitCommandLine,E.CaptureInput,E.EraseInput,E.EraseInputWord,E.HideHelp,E.ViewHelp,E.SetViewDense,E.SetViewWide,E.GetLastCommandFromHistory,E.GetNextCommandFromHistory,E.AutoCompleteCommand]),$M=new Set([E.NavPreviousItem,E.NavNextItem,E.NavPreviousItemJump,E.NavNextItemJump,E.NavToPreviousContainer,E.NavToNextContainer,E.Confirm,E.Exit,E.InitCommandPalette,E.InitMove,E.MoveNextItem,E.MovePreviousItem,E.MoveNextItemJump,E.MovePreviousItemJump,E.MoveToNextContainer,E.MoveToPreviousContainer,E.Delete,E.AddItem,E.EditTitle,E.EditDescription,E.ConfirmMove,E.Edit,E.ViewHelp,E.Yank]),Vx=async e=>{if(e.ctrl&&e.name==="c")return U.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=v(),s=Sf(e,n);if(!s||r&&!_M.has(s)||o==="replay"&&n===I.DEFAULT&&$M.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(l){logger.error(l)}},UM=()=>async function(t,n){n.name!=="escape"&&(kn&&(clearTimeout(kn),kn=void 0),await Vx(n))},jM=()=>async function(t){if(t.length===1&&t[0]===27){kn&&clearTimeout(kn),kn=setTimeout(()=>{Vx({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),kn=void 0},25);return}kn&&(clearTimeout(kn),kn=void 0)};function zx(){zl&&process.stdin.removeListener("keypress",zl),Kl&&process.stdin.removeListener("data",Kl),zl=UM(),Kl=jM(),FM.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Kl),process.stdin.on("keypress",zl)}async function Kx(){try{let e=co({});if(a(e))return rn(0,e.message);let t=gt();ye(t)&&$e(t.value);let n=ce(process.cwd());$e({gitEmail:await vl(process.cwd()),gitName:await Cr(process.cwd())});let r=ye(n)?await tl(n.value):ky();if(a(r))return r;let o=bm();return a(o)?rn(6,o.message):(zx(),ye(n)&&nl(n.value),u("Booted Epiq",void 0))}catch(e){return rn(0,Mo(e))}}hy();var VM=`${un.bold("Epiq CLI")}
|
|
105
105
|
|
|
106
|
-
${
|
|
107
|
-
${
|
|
106
|
+
${un.dim("Boot in directory:")}
|
|
107
|
+
${un.cyan("$ epiq")}
|
|
108
108
|
|
|
109
|
-
${
|
|
110
|
-
${
|
|
109
|
+
${un.dim("Launch GUI:")}
|
|
110
|
+
${un.cyan("$ epiq gui")}
|
|
111
111
|
|
|
112
|
-
${
|
|
113
|
-
${
|
|
114
|
-
`,
|
|
115
|
-
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await
|
|
116
|
-
${e.message}`)),process.exitCode=1)}export{
|
|
112
|
+
${un.dim("Act as somebody other than the configured user:")}
|
|
113
|
+
${un.cyan("$ epiq --as claude")}
|
|
114
|
+
`,xm=WM(VM,{importMeta:import.meta,version:Pn,flags:{init:{type:"boolean",default:!1},as:{type:"string"}}}),ql=xm.input[0];ql&&ql!=="gui"&&(console.error(un.red(`Unknown command: ${ql}`)),process.exit(1));if(xm.flags.as!==void 0){let e=Zl(xm.flags.as,"--as");a(e)&&(console.error(un.red(e.message)),process.exit(1))}var qx=process.stdout.columns||120,Yx=process.stdout.rows||20,Yl=null,zM=e=>{try{return Yl?(Yl.rerender(e),u("Rerendered app",void 0)):(Yl=HM(e),u("Rendered app",void 0))}catch(t){return c(`Unable to render app: ${Mo(t)}`)}},bm=()=>zM(GM.createElement(vm,{width:qx,height:Yx}));process.stdout.on("resize",()=>{if(qx=process.stdout.columns||120,Yx=process.stdout.rows||20,!Yl)return;let e=bm();a(e)&&logger.info(`[boot:resize] ${e.message}`)});if(ql==="gui"){let e=await Qb({repoRoot:process.cwd()});a(e)&&(console.error(un.red(`Failed to start Epiq GUI:
|
|
115
|
+
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await Kx();a(e)&&(logger.info(e.message),console.error(un.red(`Failed to boot Epiq:
|
|
116
|
+
${e.message}`)),process.exitCode=1)}export{bm as renderApp};
|