epiq 1.7.0 → 1.7.2
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/LICENSE +21 -0
- package/dist/gui/main.js +252 -168
- package/dist/index.js +75 -71
- package/dist/mcp.js +60 -56
- package/package.json +1 -1
package/dist/mcp.js
CHANGED
|
@@ -1,69 +1,73 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`,"utf8"),c("Created project.json",null)}catch(o){return i(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}}});import
|
|
4
|
-
`);u(n?{stdout:d,stderr:
|
|
5
|
-
`)))}),o.on("close",
|
|
6
|
-
`)));return}u(c("Git command succeeded",{stdout:d,stderr:l,exitCode:
|
|
7
|
-
${r.message}`);let o=await
|
|
8
|
-
${o.message}`):c("Created commit and resolved SHA",o.value.stdout.trim())},
|
|
9
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(
|
|
10
|
-
${o.message}`);let s=await
|
|
11
|
-
${s.message}`);let d=await
|
|
12
|
-
`+r.message);let o=
|
|
13
|
-
`+o.message):c("Ensured epiq storage",n)},
|
|
14
|
-
`,
|
|
2
|
+
var ag=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var Eo=(e,t)=>{for(var n in t)ag(e,n,{get:t[n],enumerable:!0})};var Za={};Eo(Za,{failed:()=>i,isFail:()=>a,isSuccess:()=>vt,resultStatuses:()=>Ft,succeeded:()=>c});var Ft,i,c,a,vt,C=y(()=>{"use strict";Ft={Success:"success",Fail:"fail"},i=e=>({status:Ft.Fail,message:e,value:null}),c=(e,t)=>({status:Ft.Success,message:e,value:t}),a=e=>e.status==="fail",vt=e=>e.status==="success"});var nd={};Eo(nd,{ACTOR_ID_ENV:()=>gr,ACTOR_NAME_ENV:()=>yt,applyActorNameArgument:()=>lg,deriveActorId:()=>td,isValidUserId:()=>Ro,isValidUserName:()=>fr,resolveEnvActor:()=>ti});import dg from"node:crypto";var yt,gr,ed,cg,ei,Ro,fr,Wn,td,ti,lg,hr=y(()=>{"use strict";C();yt="EPIQ_USER_NAME",gr="EPIQ_USER_ID",ed="0123456789ABCDEFGHJKMNPQRSTVWXYZ",cg=26,ei=80,Ro=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),fr=e=>e.trim().length>0&&e.length<=ei,Wn=e=>e.trim().toLowerCase(),td=e=>{let t=dg.createHash("sha256").update(`epiq:actor:${Wn(e)}`).digest(),n="";for(let r=0;r<cg;r++)n+=ed[(t[r]??0)%ed.length];return n},ti=(e,t=process.env)=>{let n=(t[yt]??"").trim(),r=(t[gr]??"").trim();return n?fr(n)?!r&&e.userId&&e.userName&&Wn(e.userName)===Wn(n)?c("Actor override names the configured user",{userId:e.userId,userName:e.userName}):r&&!Ro(r)?i(`${gr} must be 26 characters of Crockford base32`):r&&e.userId&&r===e.userId?i(`${gr} is the configured user's own id; using it under a different name would rename them on the board`):c("Resolved actor from environment",{userId:r||td(n),userName:r?n:Wn(n)}):i(`${yt} must be 1-${ei} characters of text`):r?i(`${gr} is set without ${yt}`):c("No actor override",null)},lg=(e,t,n=process.env)=>{let r=e.trim();if(!fr(r))return i(`${t} must be 1-${ei} characters of text`);let o=(n[yt]??"").trim();return o&&Wn(o)!==Wn(r)?i(`${t} names ${r}, but ${yt} names ${o}`):(n[yt]=r,c("Applied actor name argument",r))}});import{decodeTime as rd}from"ulid";var No,ni,bt,vr,od,yr,dt=y(()=>{"use strict";C();No=1440*60*1e3,ni=(e,t=Date.now())=>e>t+No?t:e,bt=e=>ni(rd(e)),vr=e=>{let t=Date.now()+No,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})},od=e=>{try{return c("Decoded date",new Date(bt(e)))}catch(t){return i("Decoding failed + "+t.message)}},yr=e=>{if(!e?.id)return null;try{return rd(e.id)}catch{return null}}});var So,Xe,sd,xt=y(()=>{"use strict";C();So="removed",Xe=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?c("Found node",n):i("Unable to find node in breadcrumb")},sd=["png","jpg","gif","webp"]});function ri(e){return e.context===B.WORKSPACE}function P(e){return e.context===B.TICKET}function id(e){return e.context===B.TEXT}function Je(e){return e.context===B.FIELD}function br(e){return e.context===B.FIELD_LIST}var B,xn,Co,xr,he=y(()=>{"use strict";B={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};xn=e=>e.context===B.SWIMLANE,Co=e=>e.context===B.BOARD,xr=e=>e.context===B.COMMENT});var h,ue=y(()=>{"use strict";h={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var ad=y(()=>{"use strict";In()});function Ao(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var It,Le,Xt=y(()=>{"use strict";It=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Le=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var dd,cd,ld=y(()=>{"use strict";dd=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},cd=(e,t)=>t?e.get(t)??[]:[]});var ud,ug,md,pd=y(()=>{"use strict";Xt();ld();ud=new WeakMap,ug=e=>{let t=ud.get(e);return t||(t=dd(e),ud.set(e,t)),t},md=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return cd(ug(e),r).filter(s=>Ao(r,s)>=n)}});var mg,gd,pg,fd=y(()=>{"use strict";Xt();pd();mg={hint:"",hints:[],overlap:0,remainder:""},gd=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return mg;let o=md({wordList:r,inputToMatch:e,overlapThreshold:1});return pg(t,o)},pg=(e,t)=>{let n=t[0]??"",r=Ao(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),d=r<(o??"").length,l=!!s,p=(l&&d?o:n)+(l&&d?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}}});import{useSyncExternalStore as yx}from"react";var To,gg,fg,xe,nt,Ue=y(()=>{"use strict";To={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},gg=new Set,fg=()=>{for(let e of gg)e()},xe=()=>To,nt=e=>(To={...To,...e},fg(),To)});function hd(e){return!e||!vg.test(e)?i(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function rt(e,t=Ir){if(e<0n)return i("Negative rank not allowed");let n=e.toString(16);return c("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function $e(e,t){if(!e&&!t)return rt(Et/2n,Ir);let n=e?hd(e):c("Resolved lower bound",0n);if(a(n))return n;let r=t?hd(t):c("Resolved upper bound",Et);if(a(r))return r;let o=n.value,s=r.value;if(s<=o)return i("Neighbouring ranks leave no space between them");let d=(o+s)/2n;return d===o||d===s?i("No rank space available between neighbors"):rt(d,Ir)}function vd(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Et*BigInt(r+1)/(t+1n),s=rt(o,Ir);if(a(s))return s;n.push(s.value)}return c("Resolved evenly spaced ranks",n)}var Ir,hg,Et,vg,Gn=y(()=>{"use strict";C();Ir=24n,hg=Ir*4n,Et=(1n<<hg)-1n,vg=/^[0-9a-f]+$/});import{ulid as yg}from"ulid";var oi,yd=y(()=>{"use strict";C();Rt();Gn();oi=(e,t)=>{let n=me(e),r=vd(n.length);if(a(r))return r;let o={};for(let s=0;s<n.length;s++){let d=n[s],l=r.value[s];if(!d||!l)return i("Unable to assign rebalance rank");o[d.id]=l}return c("Created rebalance event",{id:yg(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})}});import Er from"node:fs";import{ulid as bg}from"ulid";import{z as wo}from"zod";var xg,Ig,Mo,Ot,Rr,bd,Bt=y(()=>{"use strict";C();pe();xg="__epiq_state__",Ig=wo.object({projectId:wo.string().min(1),stateBranch:wo.string().min(1),createdAt:wo.iso.datetime()}),Mo=()=>({projectId:bg(),stateBranch:xg,createdAt:new Date().toISOString()}),Ot=e=>{let t=ko(e);if(!Er.existsSync(t))return i("Missing .epiq/project.json");try{let n=Er.readFileSync(t,"utf8"),r=JSON.parse(n),o=Ig.safeParse(r);return o.success?c("Read project.json",o.data):i(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return i(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},Rr=e=>{let t=Ot(e);return a(t)?i(t.message):c("Read projectId",t.value.projectId)},bd=({repoRoot:e,fileContents:t})=>{let n=Nr(e),r=ko(e);try{if(Er.mkdirSync(n,{recursive:!0}),Er.existsSync(r)){let o=Ot(e);return a(o)?i(o.message):c("Project already initialized",null)}return Er.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,"utf8"),c("Created project.json",null)}catch(o){return i(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}}});import Eg from"node:os";import Rg from"node:path";var ct,En,Lo=y(()=>{"use strict";ct=".epiq-global",En=()=>process.env.EPIQ_GLOBAL_DIR??Rg.join(Eg.homedir(),ct)});var si,xd=y(()=>{"use strict";C();si=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let d=r(...s);if(!n.has(d)){let l=e(...s).then(u=>(a(u)&&n.delete(d),u));n.set(d,l)}return n.get(d)});return o.clear=()=>n.clear(),o}});var ye,Po=y(()=>{"use strict";lt();ye={stage:({cwd:e,pathspec:t,ignoreRemoval:n=!1})=>H({args:["add",...n?["--ignore-removal"]:[],...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1,pathspec:r})=>H({args:["commit","--no-verify",...n?["--allow-empty"]:[],"-m",t,...r?.length?["--",...r]:[]],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>H({args:["fetch",t,`+refs/heads/${n}:refs/remotes/${t}/${n}`],cwd:e}),rebaseOnto:({cwd:e,ref:t})=>H({args:["-c","rebase.autoStash=true","rebase",t],cwd:e}),checkout:({cwd:e,branch:t})=>H({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 H({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>H({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>H({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>H({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>H({args:["worktree","prune"],cwd:e})}});var Jt,ot,Sr=y(()=>{"use strict";Bt();C();pe();Jt=e=>{let t=Qe(e);if(a(t))return i("Unable to resolve epiq project root");let n=Ot(t.value);return a(n)?i("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},ot="origin"});import{spawn as Ng}from"node:child_process";import Rn from"node:fs";import Nn from"node:path";var Sg,Cg,Ag,Tg,wg,Mg,kg,Ed,H,je,qn,ii,Lg,Do,ai,di,Fo,Cr,Rd,ci,Oo,Nd,Sd,Pg,Id,li,Dg,ui,Cd,Ad,Td,wd,lt=y(()=>{"use strict";C();Po();Sr();Sg=1e4,Cg=12e4,Ag=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),Tg=e=>{let t=e.find((n,r)=>!n.startsWith("-")&&e[r-1]!=="-c");return t&&Ag.has(t)?Cg:Sg},wg=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(Nn.delimiter))if(t)for(let n of e){let r=Nn.join(t,n);try{if(!Rn.statSync(r).isFile())continue;return Rn.accessSync(r,Rn.constants.X_OK),r}catch{continue}}return"git"},Mg=wg(),kg={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Ed=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Rn.existsSync(t)){let f=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:f,exitCode:1});return}r(i(f));return}let o=Ng(Mg,e,{cwd:t,stdio:["ignore","pipe","pipe"],env:kg}),s=!1,d="",l="",u=f=>{s||(s=!0,clearTimeout(p),r(f))},m=Tg(e),p=setTimeout(()=>{o.kill("SIGTERM");let f=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${m}ms`].join(`
|
|
4
|
+
`);u(n?{stdout:d,stderr:f,exitCode:124}:i(f))},m);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",f=>{d+=f}),o.stderr.on("data",f=>{l+=f}),o.on("error",f=>{if(n){u({stdout:d,stderr:f.message,exitCode:1});return}u(i([`git ${e.join(" ")}`,`cwd=${t}`,f.message].join(`
|
|
5
|
+
`)))}),o.on("close",f=>{let I=f??1;if(n){u({stdout:d,stderr:l,exitCode:I});return}if(I!==0){u(i([`git ${e.join(" ")}`,l.trim()||d.trim()||"Git command failed"].filter(Boolean).join(`
|
|
6
|
+
`)));return}u(c("Git command succeeded",{stdout:d,stderr:l,exitCode:I}))})}),H=({args:e,cwd:t})=>Ed({args:e,cwd:t,allowFail:!1}),je=({args:e,cwd:t})=>Ed({args:e,cwd:t,allowFail:!0}),qn=async({cwd:e,message:t,pathspec:n})=>{let r=await ye.commit({cwd:e,message:t,pathspec:n});if(a(r))return i(`Failed to create commit
|
|
7
|
+
${r.message}`);let o=await H({args:["rev-parse","HEAD"],cwd:e});return a(o)?i(`Commit created, but failed to read HEAD SHA
|
|
8
|
+
${o.message}`):c("Created commit and resolved SHA",o.value.stdout.trim())},ii=async e=>{let t=await H({cwd:e,args:["rev-parse","--git-dir"]});if(a(t))return i(t.message);let n=t.value.stdout.trim();return c("Resolved git dir",Nn.isAbsolute(n)?n:Nn.resolve(e,n))},Lg=async e=>{let t=await ii(e);if(a(t))return i(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,d]of Object.entries(r))if(Rn.existsSync(Nn.join(n,s)))return c("Checked for in-progress Git operation",d);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,d]of Object.entries(o))if(Rn.existsSync(Nn.join(n,s)))return c("Checked for in-progress Git operation",d);return c("Checked for in-progress Git operation",null)},Do=async e=>{let t=await Lg(e);return a(t)?i(t.message):c("Checked for in-progress Git operation",t.value!==null)},ai=async({repoRoot:e})=>{let n=(await je({args:["remote","get-url",ot],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},di=async({repoRoot:e,branch:t})=>{let n=await je({args:["ls-remote","--heads",ot,t],cwd:e});return n.exitCode!==0?i(n.stderr.trim()||`Unable to inspect remote branch ${ot}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},Fo=async({repoRoot:e,branch:t})=>{let n=await je({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?c("Local branch exists",!0):n.exitCode===1?c("Local branch missing",!1):i(n.stderr.trim()||`Unable to inspect branch ${t}`)},Cr=e=>{try{return Rn.realpathSync.native(e)}catch{return Nn.resolve(e)}},Rd=async({repoRoot:e,worktreeRoot:t})=>{let n=await H({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let r=Cr(t),o=n.value.stdout.split(`
|
|
9
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Cr).includes(r);return c("Checked worktree registration",o)},ci=async e=>{let t=await je({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Oo=async e=>{let t=await H({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved current branch",t.value.stdout.trim())},Nd=async e=>{let t=await H({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},Sd=e=>e.includes("fetch first")||e.includes("non-fast-forward"),Pg=async e=>(await je({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1),Id=async e=>{let t=await je({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},li=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),Dg=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),ui=async({cwd:e,branch:t})=>{let n=await Pg(e);if(a(n))return i(n.message);let r=await Id(e),o=await ye.fetch({cwd:e,remote:ot,branch:t});if(a(o))return Dg(o.message)?c("Remote branch missing, skipped pull",!1):i(`Failed to fetch ${t}
|
|
10
|
+
${o.message}`);let s=await ye.rebaseOnto({cwd:e,ref:`${ot}/${t}`});if(a(s))return i(`Failed during rebase
|
|
11
|
+
${s.message}`);let d=await Id(e),l=r!==null&&d!==null&&r!==d;return c(l?"Pulled with rebase":"Already up to date",l)},Cd=async e=>{let t=await je({args:["rev-list","--count","@{u}..HEAD"],cwd:e});return t.exitCode!==0?c("No upstream to compare against",!1):c("Compared against upstream",Number(t.stdout.trim())>0)},Ad=async e=>{let t=await je({args:["status","--porcelain","--untracked-files=all"],cwd:e});return t.exitCode!==0?i(t.stderr.trim()||"Unable to inspect the worktree for changes"):c("Inspected worktree for changes",t.stdout.trim().length>0)},Td=async(e,t)=>{let n=await je({args:["diff","--cached","--quiet",...t?.length?["--",...t]:[]],cwd:e});return n.exitCode===0?c("No staged changes",!1):n.exitCode===1?c("Has staged changes",!0):i(n.stderr.trim()||"Unable to inspect staged changes")},wd=async e=>{let t=await Oo(e);return a(t)?i(t.message):c("Checked detached HEAD state",t.value==="HEAD")}});import Qt from"node:fs";import st from"node:path";var kd,Ld,Pd,Dd,Bo,Ce,Fg,Md,Ar,_o,Fd,mi,pi,Od,Bd,ut,pI,mt=y(()=>{"use strict";Bt();C();Lo();pe();xd();Nt();lt();kd="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Ld=e=>st.join(He,Zt,e),Pd=()=>st.join(He,gi),Dd=En,Bo=()=>st.join(Dd(),"worktrees"),Ce=({repoRoot:e})=>{let t=Rr(e);return a(t)?i(t.message):c("Resolved state branch root",st.join(Bo(),t.value))},Fg=e=>st.join(e,He),Md=e=>st.join(Fg(e),Zt),Ar=e=>{try{return Qt.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return i(t instanceof Error?t.message:String(t))}},_o=()=>{let e=Dd(),t=Bo(),n=!Qt.existsSync(e)||!Qt.existsSync(t),r=Ar(e);if(a(r))return i(`Ensure epiq home failed.
|
|
12
|
+
`+r.message);let o=Ar(t);return a(o)?i(`Ensure worktrees dir failed.
|
|
13
|
+
`+o.message):c("Ensured epiq storage",n)},Fd=e=>{Qt.existsSync(e)&&(X.debug("[sync] remove path",e),Qt.rmSync(e,{recursive:!0,force:!0}))},mi=`*.jsonl merge=union
|
|
14
|
+
`,pi=()=>st.join(He,Zt,".gitattributes"),Od=(e,t)=>{for(let r of[Md(e),Md(t)]){let o=Ar(r);if(a(o))return i(o.message)}let n=st.join(t,pi());try{Qt.readFileSync(n,"utf8")!==mi&&Qt.writeFileSync(n,mi)}catch{Qt.writeFileSync(n,mi)}return c("Ensured state branch",void 0)},Bd=async e=>{let t=await H({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return i(`ensure state branch is storage only failed
|
|
15
15
|
`+t.message);let r=t.value.stdout.trim().split(`
|
|
16
|
-
`).filter(Boolean).filter(d=>d!==
|
|
17
|
-
${o.message}`);let s=await
|
|
18
|
-
`);if(n[n.length-1]===""&&n.pop(),n.length
|
|
16
|
+
`).filter(Boolean).filter(d=>d!==He);if(r.length===0)return c("State branch is storage-only",!1);let o=await H({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(a(o))return i(`Failed to clean storage branch
|
|
17
|
+
${o.message}`);let s=await qn({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:r});return a(s)?i(s.message):c("Cleaned storage branch",!0)},ut=si(async(e=process.cwd())=>{let t=await H({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?i("Not inside a Git repository"):c("Resolved repo root",t.value.stdout.trim())},e=>st.resolve(e)),pI=si(async e=>{let t=await H({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return i(t.message);let n=t.value.stdout.trim(),r=st.isAbsolute(n)?n:st.join(e,n);return c("Resolved git dir",r)},e=>st.resolve(e))});import Tr from"node:fs";import St from"node:path";var xI,He,Zt,gi,Og,Nr,ko,wr,Uo,_d,Bg,Mr,$o,_g,Qe,Ud,Ct,pe=y(()=>{"use strict";C();mt();Lo();xI=process.env.IS_LOCAL==="true",He=".epiq",Zt="events",gi="media",Og="project.json",Nr=e=>St.join(e,He),ko=e=>St.join(Nr(e),Og),wr=e=>St.join(Nr(e),Zt),Uo=e=>St.join(Nr(e),gi),_d=e=>St.join(e,He),Bg=e=>{let t=St.join(e,He);return Tr.existsSync(t)&&Tr.statSync(t).isDirectory()},Mr=e=>{let t=ko(e);return Tr.existsSync(t)&&Tr.statSync(t).isFile()},$o=e=>{let t=St.resolve(e);for(;;){if(Bg(t))return c("Resolved closest .epiq root",t);let n=St.dirname(t);if(n===t)return i("No .epiq directory found in any parent");t=n}},_g="No .epiq/project.json found in any parent",Qe=e=>{let t=St.resolve(e);for(;;){if(Mr(t))return c("Resolved closest epiq project root",t);let n=St.dirname(t);if(n===t)return i(_g);t=n}},Ud=e=>{let t=wr(e);try{return Tr.mkdirSync(t,{recursive:!0}),c("Resolved events dir",t)}catch(n){return i(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},Ct=async()=>{let e=await ut(process.cwd());if(a(e))return e;let t=Ce({repoRoot:e.value});return a(t)?t:c("Resolved persist root",t.value)}});import kr from"fs";import yi from"path";import Ug from"util";function jg(){let e=Hd();if(!e||!kr.existsSync(e))return;let n=kr.readFileSync(e,"utf8").split(`
|
|
18
|
+
`);if(n[n.length-1]===""&&n.pop(),n.length<=$d)return;let r=n.slice(-$d).join(`
|
|
19
19
|
`)+`
|
|
20
|
-
`;
|
|
21
|
-
`;Sr.mkdirSync(ci.dirname(r),{recursive:!0}),Sr.appendFileSync(r,l,"utf8"),ii++,ii>=Sg&&(ii=0,Cg())}var Ld,Sg,ii,Pd,Dd,di,z,It=y(()=>{"use strict";C();ue();Ld=1e3,Sg=50,ii=0,Pd=()=>process.env.EPIQ_MCP==="true",Dd=()=>{let e=process.cwd(),t=Lo(e);return a(t)?Pd()?ci.join(process.cwd(),".epiq-mcp.log"):void 0:ci.join(t.value,Je,"log","epiq.log")};di=()=>Pd()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",z={info(...e){let t=di();(t==="info"||t==="debug")&&ai("[Info]",e,!1)},debug(...e){di()==="debug"&&ai("[Debug]",e,!0)},error(...e){let t=di();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;ai("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=z});var re,Hn=y(()=>{"use strict";re={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var V,Cr,Yt=y(()=>{"use strict";V=e=>e.slice(-7).toUpperCase(),Cr=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?V(e).includes(n):!0}});var Se,xn=y(()=>{"use strict";ge();Yt();Se={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:O.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:V(e)},context:O.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:O.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:d=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:O.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:d}),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:O.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:V(e)},context:O.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:O.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:d=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:O.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:d})}});var Ag,be,Po,Wn=y(()=>{"use strict";Ag=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[be,Po]=Ag});function Xt(e,t=!1){let n=Dg[e.action];if(!n)return i(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);if(!Nt()&&e.action!=="init.workspace")return D(`${e.action} arrived before the workspace was initialized`,e);if(e.action==="init.workspace"&&$e){if($e.genesisApplied)return D("the workspace is already initialized",e);$e.genesisApplied=!0}let r=n(e);if(a(r))return r;let o=Pg(e,t);return o||r}var li,D,Ar,In,En,Fd,Bd,Tg,wg,ui,Mg,kg,$e,Lg,Pg,Dg,Dt,Ft=y(()=>{"use strict";It();ge();C();Hn();me();xn();k();mi();Wn();li=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),D=(e,t)=>({...li(e,t),convergence:!0}),Ar=e=>a(e)&&e.convergence===!0,In=e=>{let t=e.filter(a);return{fatal:t.filter(n=>!Ar(n)),skipped:t.filter(Ar)}},En=e=>{e.length!==0&&z.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},Fd=e=>{let t=x.getNode(e);if(!t||!L(t)||t.isDeleted)return null;let n=Do(t);return a(n)?n:null},Bd=e=>{if(!Fo())return null;for(let t of e){let n=Fd(t);if(n)return n;let r=g().nodes[t]?.parentNodeId;if(!r)continue;let o=Fd(r);if(o)return o}return null},Tg=(e,t)=>{let n=x.getNode(e);n&&x.updateNode({...n,log:[...n.log??[],t]})},wg=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},ui=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 wg(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":default:return[]}},Mg=e=>{oe(t=>({...t,eventLog:[...t.eventLog,e]}))},kg=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?li("Invalid user ID format",e):c("Valid user",null)},$e=null,Lg=e=>{for(let[t,n]of e.nodeLog){let r=x.getNode(t);r&&x.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&oe(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),Bd([...e.virtualNodeIds])},Pg=(e,t)=>{let n=kg(e);if(a(n))return n;let r=[...new Set(ui(e))];if($e){for(let s of r){if(!t){let d=$e.nodeLog.get(s);d?d.push(e):$e.nodeLog.set(s,[e])}if(Fo()){$e.virtualNodeIds.add(s);let d=g().nodes[s]?.parentNodeId;d&&$e.virtualNodeIds.add(d)}}return t||$e.appLog.push(e),null}t||(r.forEach(s=>Tg(s,e)),Mg(e));let o=Bd(r);return o||null},Dg={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Se.workspace(t,n,r),s=Tr(o);if(a(s))return li(s.message,e);let d=x.createNode(o);return a(d)?D(d.message??"Failed to initialize workspace",e):zs(d.value)?c("Workspace initialized",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=x.createNode(Se.workspace(t,n,r));return a(o)?D(o.message??"Failed to add workspace",e):zs(o.value)?c("Added workspace",{action:e.action,result:o.value}):i("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=x.createNode(Se.board(t,n,r,o));return a(s)?D(s.message??"Unable to create board",e):yo(s.value)?c("Added board",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=x.createNode(Se.swimlane(t,n,r,o));return a(s)?D(s.message??"Unable to create swimlane",e):gn(s.value)?c("Added swimlane",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=x.createNode(Se.ticket(t,n,r,o));return a(s)?D(s.message??"Unable to create issue",e):L(s.value)?c("Added issue",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,d=x.createNode(Se.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(re.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?D(d.message??`Unable to create field: ${n}`,e):ze(d.value)?c("Added field",{action:e.action,result:d.value}):i("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!x.getNode(t))return D(`Unable to locate node with id ${t}`,e);let o=x.renameNode(t,n);return a(o)?D(o.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=x.tombstoneNode(t);return a(n)?D(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=x.createTag({id:t,name:n});return a(r)?D(r.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=x.tombstoneTag(t);return a(n)?D(n.message??"Unable to delete tag",e):c("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=x.restoreTag(t,n);return a(r)?D(r.message??"Unable to restore tag",e):c("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=x.createContributor({id:t,name:n});return a(r)?D(r.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=x.renameContributor(t,n);return a(r)?D(r.message??"Unable to rename contributor",e):c("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=x.tombstoneContributor(t);return a(n)?D(n.message??"Unable to remove contributor",e):c("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,r=x.restoreContributor(t,n);return a(r)?D(r.message??"Unable to restore contributor",e):c("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=x.tag(t,n);return a(r)?D(r.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=x.untag(t,n);return a(r)?D(r.message??"Unable to untag issue",e):c("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=x.assign(t,n);return a(r)?D(r.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=x.unassign(t,n);return a(r)?D(r.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=x.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?D(o.message??"Failed to move node",e):c("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=x.editValue(t,n);return a(r)?D(r.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=x.getNode(t);if(!o)return D("Unable to locate issue",e);if(!L(o))return D("Can only close issues",e);let s=x.getNode(be);if(!s)return D("Unable to locate target swimlane",e);if(n!==s.id)return D("Close target must be closed swimlane",e);let d=x.moveNodeToRank({id:t,parentId:n,rank:r});return a(d)?D(d.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=x.getNode(t);if(!o)return D("Unable to locate issue",e);if(!L(o))return D("Can only reopen issues",e);let s=x.getNode(be);if(!s)return D("Unable to locate closed swimlane",e);if(n===s.id)return D("Cannot reopen issue into closed swimlane",e);if(!x.getNode(n))return D("Reopen parent no longer exists",e);let l=x.moveNodeToRank({id:t,parentId:n,rank:r});return a(l)?D(l.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=x.lockNode(t);return a(n)?D(n.message??"Unable to lock node",e):c("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=x.getNode(r);if(!s)return D(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return D(`Node ${r} is not child of ${t}`,e);let d=x.updateNode({...s,rank:o});if(a(d))return D(d.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=x.createComment({id:t,issue:n,authorId:r,authorName:x.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return a(s)?D(s.message??"Unable to add comment",e):c("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=x.getComment(t);if(!o)return D("Unable to locate comment",e);if(o.issue!==n)return D("Comment does not belong to issue",e);let s=x.editComment(t,r);return a(s)?D(s.message??"Unable to edit comment",e):c("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=x.getComment(t);if(!r)return D("Unable to locate comment",e);if(r.issue!==n)return D("Comment does not belong to issue",e);let o=x.deleteComment(t);return a(o)?D(o.message??"Unable to delete comment",e):c("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:d}=e.payload,l=x.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:d,deleted:!1});return a(l)?D(l.message??"Unable to add attachment",e):c("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=x.getAttachment(t);if(!r)return D("Unable to locate attachment",e);if(r.issue!==n)return D("Attachment does not belong to issue",e);let o=x.deleteAttachment(t);return a(o)?D(o.message??"Unable to delete attachment",e):c("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=x.linkUserId({contributorId:t,userId:e.userId});return a(n)?D(n.message??"Unable to link contributor",e):c("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};Dt=e=>{let t=Od(()=>{let n=$e===null;n&&($e={appLog:[],nodeLog:new Map,virtualNodeIds:new Set,genesisApplied:!1});try{let r=e.map(o=>Xt(o));if(n&&$e){let o=Lg($e);if(o)return e.map(()=>o)}return r}finally{n&&($e=null)}});return a(t)?e.map(()=>i(t.message)):t.value}});var pi,_d=y(()=>{"use strict";pi=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown"});var Fg,Bg,Ud,$d,gi=y(()=>{"use strict";Fg=["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"],Bg=new Set(Fg),Ud=e=>Bg.has(e),$d=e=>({action:e.action,payload:e.payload})});import Bo from"node:fs";import Oo from"node:path";import{decodeTime as Og}from"ulid";import{z as fi}from"zod";function wr(e,t){let n=Rr(e);if(!Bo.existsSync(n))return c("No events found",[]);let r=Bo.readdirSync(n).filter(s=>s.endsWith(".jsonl")).map(s=>Oo.join(n,s)),o=[];for(let s of r){let d=Vg(s,t);if(a(d))return i(d.message);o.push(...d.value)}return c("All events loaded",zg(o))}function Bt(e){let t=[],n=wr(e,t);if(a(n))return i(n.message);let r=yi(n.value,t);return a(r)?i(r.message):(Kg=t,c("Loaded merged events",{events:r.value,unreadable:t}))}function bi(e){let t=wr(e);return a(t)?i(t.message):c("Loaded event actors",t.value.map(({userId:n,userName:r})=>({userId:n,userName:r})))}function Gn(e){let t=Bt(e);return a(t)?i(t.message):c("Loaded merged events",t.value.events)}function xi(e,t){let n=wr(e);if(a(n))return i(n.message);let{appliedEvents:r,unappliedEvents:o}=Yg(n.value,t),s=yi(r);if(a(s))return i(s.message);let d=yi(o);return a(d)?i(d.message):c("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function jd(e=process.cwd()){let t=wr(e);return a(t)?i(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}function Ii(e){let t=wr(e);if(a(t))return i(t.message);let n=Hd(t.value);return c("Loaded effective event times",new Map(t.value.map((r,o)=>[r.id[0],n[o]??null])))}var _g,hi,Ug,$g,jg,Hg,Wg,Gg,qg,yi,Vg,Kg,vi,zg,Hd,Yg,Jt=y(()=>{"use strict";It();C();ue();it();gi();mt();_g=fi.object({userId:fi.string().min(1).default("unknown"),userName:fi.string().min(1).default("unknown")}),hi=e=>{let t=Object.entries(e).filter(([o])=>o!=="id"&&o!=="v"&&o!=="userId"&&o!=="userName");if(t.length!==1)return null;let n=t[0]?.[1];if(typeof n!="object"||n===null)return null;let r=n.id;return typeof r=="string"&&r.length>0?r:null},Ug=/^[0-9a-hjkmnp-tv-z]{26}$/i,$g=e=>Ug.test(e)?e.toUpperCase():e,jg=e=>{let t=Oo.basename(e,".jsonl"),n=t.indexOf("."),r=n===-1?t:t.slice(0,n),o=n===-1?void 0:t.slice(n+1),s=_g.safeParse({userId:$g(r),userName:o});return s.success?c("Parsed event file actor",s.data):i(`Invalid event file name ${Oo.basename(e)}: ${s.error.issues.map(d=>d.path.join(".")||d.message).join(", ")}`)},Hg=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?i(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?i("Invalid persisted event: action key is missing or invalid"):c("Resolved persisted action",t[0])},Wg=(e,t)=>t in e,Gg=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),qg=e=>{let{userId:t,userName:n,...r}=e,o=Hg(r);if(a(o))return i(o.message);let s=o.value,d=e.id?.[0];return d?Wg(r,s)?c("Decoded persisted event",Gg({id:d,action:s,payload:r[s],userId:t,userName:n})):i(`Persisted event is missing payload for action: ${s}`):i("Persisted event is missing id")},yi=(e,t)=>{let n=[],r=new Map,o=new Map;for(let s of e){if(!Gd(s.v)){o.set(s.v,(o.get(s.v)??0)+1),t?.push({eventId:s.id[0],reason:"unsupported-schema-version",detail:`v${s.v}`,targetNodeId:hi(s)});continue}let d=qg(s);if(a(d)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:d.message,targetNodeId:hi(s)});continue}let l=d.value.action;if(!Ud(l)){r.set(l,(r.get(l)??0)+1),t?.push({eventId:s.id[0],reason:"unknown-action",detail:l,targetNodeId:hi(s)});continue}n.push(d.value)}if(r.size>0){let s=[...r.entries()].map(([d,l])=>`${d} (x${l})`).join(", ");z.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${s}. Upgrade to apply them.`)}if(o.size>0){let s=[...o.entries()].map(([d,l])=>`v${d} (x${l})`).join(", ");z.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${s}. Upgrade to apply them.`)}return c("Decoded reconstructed events",n)},Vg=(e,t)=>{if(!Bo.existsSync(e))return c("Event file missing",[]);let n=jg(e);if(a(n))return i(n.message);let r=Bo.readFileSync(e,"utf8"),o=[],s=Oo.basename(e),d=(l,u)=>{t?.push({eventId:null,reason:"corrupt-line",detail:`${s}:${l} (${u})`,targetNodeId:null})};for(let[l,u]of r.split(`
|
|
22
|
-
`).entries()){let m=u.trim();if(!m)continue;let p;try{p=JSON.parse(m)}catch{d(l+1,"invalid JSON");continue}let f=
|
|
23
|
-
`,"utf8"),n&&(n.current=d),c("Event persisted",{path:o.value,entry:l.value}))}catch(r){let o=r instanceof Error?r.message:"Unknown persist error";return i(`Failed to persist event: ${o}`)}}var Vd,qd,ef,tf,nf,Kd,rf,of,Wd,sf,af,Gd,df,fe,Nn,cf,lf,mt=y(()=>{"use strict";It();ur();C();Oe();ue();_d();it();Jt();gi();Vd=1,qd=Zg(),ef=0xffffffffffff,tf=ho,nf=e=>{let t=Date.now(),n;try{n=Qg(e)}catch{return t}return n>=ef?t:n>t+tf?(z.error("[persist] edge id is too far in the future; seeding from the wall clock instead",{edgeRef:e,edgeTime:n,now:t}),t):Math.max(t,n+1)},Kd=Rn.tuple([Rn.string().min(1),Rn.string().min(1).nullable()]),rf=Rn.looseObject({v:Rn.literal(Vd),id:Kd}),of=Rn.looseObject({v:Rn.number().int().positive(),id:Kd}),Wd=e=>{let t=of.safeParse(e);return t.success?c("Parsed persisted event envelope",t.data):i(`Invalid persisted event envelope: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},sf=[1],af=new Set(sf),Gd=e=>af.has(e),df=e=>{let t=rf.safeParse(e);return t.success?c("Parsed persisted event",t.data):i(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},fe=()=>{let{userName:e,userId:t}=ye();return e?t?fo(t)?lr(e)?c("Successfully resolved actor ID",{userId:t,userName:e}):i("Invalid user name in config"):i("Invalid user ID in config"):i("User ID not configured"):i("User name not configured")},Nn=({userId:e,userName:t})=>`${pi(e)}.${pi(t)}.jsonl`,cf=(e,{userId:t,userName:n})=>{let r=Nn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return i(`Invalid event log file name: ${r}`);let s=Jg.join(Rr(e),r);return c("Successfully resolved event log path",s)},lf=(e,t)=>{let n={[e.action]:e.payload,v:Vd,id:t};return df(n)}});import{ulid as uf}from"ulid";function zd(e,t,n){let r=Xt(e);if(r.status!==kt.Success)return r;let o=_o({event:e,rootDir:t,edge:n});return a(o)?o:r}function B(e,t){if(e.length===0||!e[0])return i("No events provided");if(g().readOnly)return i(g().readOnlyReason??"Cannot change the board while time travelling");let n={},r=mf(e[0],t,n);if(a(r))return r;let o=e.map(d=>zd(d,t,n)),s=o.filter(a);return s.length>0?i("Materialize and persist failed: "+s.map(d=>d.message).join(", ")):c("Materialization succeeded",o.map(d=>d.value))}var mf,Sn=y(()=>{"use strict";C();me();k();Ft();mt();mf=(e,t,n)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return c("Contributor write already in flight",void 0);let r=x.getContributor(e.userId),o={id:uf(),action:r?"rename.contributor":"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName};if(r&&(r.tombstoned||r.name===e.userName))return c("Contributor name is current",void 0);let s=zd(o,t,n);return a(s)?i(s.message):c("Contributor name recorded",void 0)}});var Yd,Uo,le,Xd,Jd,Qt,Cn,xt=y(()=>{"use strict";cd();Sn();C();k();$n();Yd=e=>Uo(le(e),{at:"end"}),Uo=(e,t={at:"end"})=>{let n=o=>a(o)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(_e(void 0,void 0));let r=()=>n(_e(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(_e(void 0,o.rank)):i("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(_e(o.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let o=Xd(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let d=o>0?e[o-1]:void 0;return n(_e(d?.rank,s.rank))}case"after":{let o=Xd(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let d=o<e.length-1?e[o+1]:void 0;return n(_e(s.rank,d?.rank))}}},le=e=>Object.values(g().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Xd=(e,t)=>e.findIndex(n=>n.id===t),Jd=(e,t,n={at:"end"})=>Uo(le(t).filter(r=>r.id!==e),n),Qt=(e,t,n,r,o)=>{let s=Jd(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return c("Resolved rank",s.value.rank);let d=Ys(e,r);if(a(d))return d;let l=B([d.value],o);if(a(l))return l;let u=Jd(t,e,n);return a(u)?u:u.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",u.value.rank)},Cn=(e,t,n)=>{let r=Yd(e);if(a(r))return r;if(!r.value.needsRebalance)return c("Resolved rank",r.value.rank);let o=Ys(e,t);if(a(o))return o;let s=B([o.value],n);if(a(s))return s;let d=Yd(e);return a(d)?d:d.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",d.value.rank)}});var _,Qd,Zd,Qe=y(()=>{"use strict";k();_={exit(){process.exit(0)},enterChildNode(){let e=g(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=se(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||_.navigate({contextNode:o,selectedIndex:se(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=g();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=se(n.id),o=r.findIndex(({id:d})=>d===e.id),s=r.length===0?-1:o>=0?o:0;_.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Qd(1),navigateToPreviousItem:()=>Qd(-1),navigateToNextContainer:()=>Zd(1),navigateToPreviousContainer:()=>Zd(-1),navigate:({contextNode:e,selectedIndex:t})=>{E({contextNodeId:e.id,selectedIndex:t})}},Qd=e=>{let{selectedIndex:t,contextNode:n}=g(),r=se(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;_.navigate({selectedIndex:s,contextNode:n})},Zd=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=g();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=se(o.id),d=s.findIndex(I=>I.id===t.id);if(d<0)return;let l=s.at(d+e)??s.at(0);if(!l)return;let u=se(l.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),f=u.length?p:-1;_.navigate({contextNode:l,selectedIndex:f})}});var tc,nc,pf,$o,rc,ec,gf,oc,sc=y(()=>{"use strict";ge();C();xt();k();Qe();tc=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),nc=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},pf=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&ze(t)&&t.childRenderAxis==="vertical"},$o=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r||r.isDeleted)return!1;let o=le(r.id);return _.navigate({contextNode:r,selectedIndex:tc(t,o.length)}),!0},rc=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return $o(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let d=le(o.id).findIndex(l=>l.id===n.id);return d>=0?(_.navigate({contextNode:o,selectedIndex:d}),!0):rc(o.id)},ec=e=>{let{nodes:t}=g(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),rc(n))return!0;n=t[n]?.parentNodeId}return!1},gf=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},oc=e=>{let{nodes:t,rootNodeId:n}=g();if(pf(e.contextNodeId)&&$o(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(gf(e.selectedNodeId)&&e.selectedNodeId&&ec(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if($o(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&$o(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(ec(e.contextNodeId))return c("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return i("Unable to restore navigation");let o=le(r.id);return _.navigate({contextNode:r,selectedIndex:tc(e.selectedIndex,o.length)}),c("Restored navigation to root",null)}});import{monotonicFactory as ff,ulid as St}from"ulid";function hf(){let e=je();if(a(e))return i("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return i("No workspace found in event log");let[r]=se(n.id),[o]=r?se(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return c("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?c("Resolved boot nav target",{contextNode:r,selectedIndex:0}):c("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function vf(){let e=hf();return a(e)?e:_.navigate(e.value)}function ic({userId:e,userName:t}){let n=Mr(),r=Mr(),o=Mr(),s=Mr(),d=Mr(),l=_e(void 0,void 0);if(a(l))return l;let u=_e(void 0,void 0);if(a(u))return u;let m=_e(u.value,void 0);if(a(m))return m;let p=_e(void 0,void 0);if(a(p))return p;let f=_e(p.value,void 0);if(a(f))return f;let I=_e(f.value,void 0);if(a(I))return I;let N=_e(void 0,void 0);return a(N)?N:c("Created default events",[{id:St(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:St(),userId:e,userName:t,action:"create.contributor",payload:{id:e,name:t}},{id:St(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:St(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:St(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:St(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:r,rank:I.value}},{id:St(),userId:e,userName:t,action:"add.board",payload:{id:Po,name:"Closed",parent:n,rank:m.value}},{id:St(),userId:e,userName:t,action:"add.swimlane",payload:{id:be,name:"Closed",parent:Po,rank:N.value}},{id:St(),userId:e,userName:t,action:"lock.node",payload:{id:Po}},{id:St(),userId:e,userName:t,action:"lock.node",payload:{id:be}}])}function Zt(e,t=[]){if(yf())return c("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Se.workspace("temporary-uninitialized-workspace","Workspace","a0"),d=Tr(s);return a(d)?d:(E({hasProjectDefinition:!1,mode:h.DEFAULT}),c("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return i("Initialized Epiq project has no workspace init event");let n=Dt(e),{fatal:r,skipped:o}=In(n);return r.length>0?i(`Materializing failed:
|
|
20
|
+
`;kr.writeFileSync(e,r,"utf8")}function hi(e,t,n=!1){let r=Hd();if(!r)return;let o=Ug.format(...t),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
21
|
+
`;kr.mkdirSync(yi.dirname(r),{recursive:!0}),kr.appendFileSync(r,l,"utf8"),fi++,fi>=$g&&(fi=0,jg())}var $d,$g,fi,jd,Hd,vi,X,Nt=y(()=>{"use strict";C();pe();$d=1e3,$g=50,fi=0,jd=()=>process.env.EPIQ_MCP==="true",Hd=()=>{let e=process.cwd(),t=$o(e);return a(t)?jd()?yi.join(process.cwd(),".epiq-mcp.log"):void 0:yi.join(t.value,He,"log","epiq.log")};vi=()=>jd()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",X={info(...e){let t=vi();(t==="info"||t==="debug")&&hi("[Info]",e,!1)},debug(...e){vi()==="debug"&&hi("[Debug]",e,!0)},error(...e){let t=vi();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;hi("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=X});var se,Vn=y(()=>{"use strict";se={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var K,Lr,en=y(()=>{"use strict";K=e=>e.slice(-7).toUpperCase(),Lr=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?K(e).includes(n):!0}});var Ae,Sn=y(()=>{"use strict";he();en();Ae={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:B.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:K(e)},context:B.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:B.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:d=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:B.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:d}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:B.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:K(e)},context:B.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:B.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:d=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:B.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:d})}});var Hg,Ie,jo,zn=y(()=>{"use strict";Hg=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[Ie,jo]=Hg});function tn(e,t=!1){let n=Yg[e.action];if(!n)return i(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);if(!At()&&e.action!=="init.workspace")return L(`${e.action} arrived before the workspace was initialized`,e);if(e.action==="init.workspace"&&We){if(We.genesisApplied)return L("the workspace is already initialized",e);We.genesisApplied=!0}let r;try{r=n(e)}catch(s){return L(`threw while materializing (${s instanceof Error?s.message:String(s)})`,e)}if(a(r))return r;let o=Kg(e,t);return o||r}var bi,L,Dr,Cn,An,Wd,Gd,Wg,Gg,xi,qg,Vg,We,zg,Kg,Pr,Yg,_t,Ut=y(()=>{"use strict";Nt();he();C();Vn();ge();Sn();k();Ii();zn();bi=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),L=(e,t)=>({...bi(e,t),convergence:!0}),Dr=e=>a(e)&&e.convergence===!0,Cn=e=>{let t=e.filter(a);return{fatal:t.filter(n=>!Dr(n)),skipped:t.filter(Dr)}},An=e=>{e.length!==0&&X.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},Wd=e=>{let t=x.getNode(e);if(!t||!P(t)||t.isDeleted)return null;let n=Ho(t);return a(n)?n:null},Gd=e=>{if(!Wo())return null;for(let t of e){let n=Wd(t);if(n)return n;let r=g().nodes[t]?.parentNodeId;if(!r)continue;let o=Wd(r);if(o)return o}return null},Wg=(e,t)=>{let n=x.getNode(e);n&&x.updateNode({...n,log:[...n.log??[],t]})},Gg=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},xi=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 Gg(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":default:return[]}},qg=e=>{ie(t=>({...t,eventLog:[...t.eventLog,e]}))},Vg=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?bi("Invalid user ID format",e):c("Valid user",null)},We=null,zg=e=>{for(let[t,n]of e.nodeLog){let r=x.getNode(t);r&&x.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&ie(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),Gd([...e.virtualNodeIds])},Kg=(e,t)=>{let n=Vg(e);if(a(n))return n;let r=[...new Set(xi(e))];if(We){for(let s of r){if(!t){let d=We.nodeLog.get(s);d?d.push(e):We.nodeLog.set(s,[e])}if(Wo()){We.virtualNodeIds.add(s);let d=g().nodes[s]?.parentNodeId;d&&We.virtualNodeIds.add(d)}}return t||We.appLog.push(e),null}t||(r.forEach(s=>Wg(s,e)),qg(e));let o=Gd(r);return o||null},Pr=(e,t,n)=>x.getNode(e)?L(`a node with id ${e} already exists`,n):t===e?L("a node cannot be its own parent",n):null,Yg={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Ae.workspace(t,n,r),s=Fr(o);if(a(s))return bi(s.message,e);let d=x.createNode(o);return a(d)?L(d.message??"Failed to initialize workspace",e):ri(d.value)?c("Workspace initialized",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Pr(t,void 0,e);if(o)return o;let s=x.createNode(Ae.workspace(t,n,r));return a(s)?L(s.message??"Failed to add workspace",e):ri(s.value)?c("Added workspace",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Pr(t,r,e);if(s)return s;let d=x.createNode(Ae.board(t,n,r,o));return a(d)?L(d.message??"Unable to create board",e):Co(d.value)?c("Added board",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Pr(t,r,e);if(s)return s;let d=x.createNode(Ae.swimlane(t,n,r,o));return a(d)?L(d.message??"Unable to create swimlane",e):xn(d.value)?c("Added swimlane",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Pr(t,r,e);if(s)return s;let d=x.createNode(Ae.ticket(t,n,r,o));return a(d)?L(d.message??"Unable to create issue",e):P(d.value)?c("Added issue",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,d=Pr(t,r,e);if(d)return d;let l=x.createNode(Ae.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(se.DESCRIPTION)?"vertical":"horizontal"}));return a(l)?L(l.message??`Unable to create field: ${n}`,e):Je(l.value)?c("Added field",{action:e.action,result:l.value}):i("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!x.getNode(t))return L(`Unable to locate node with id ${t}`,e);let o=x.renameNode(t,n);return a(o)?L(o.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=x.tombstoneNode(t);return a(n)?L(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=x.createTag({id:t,name:n});return a(r)?L(r.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=x.tombstoneTag(t);return a(n)?L(n.message??"Unable to delete tag",e):c("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=x.restoreTag(t,n);return a(r)?L(r.message??"Unable to restore tag",e):c("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=x.createContributor({id:t,name:n});return a(r)?L(r.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=x.renameContributor(t,n);return a(r)?L(r.message??"Unable to rename contributor",e):c("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=x.tombstoneContributor(t);return a(n)?L(n.message??"Unable to remove contributor",e):c("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,r=x.restoreContributor(t,n);return a(r)?L(r.message??"Unable to restore contributor",e):c("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=x.tag(t,n);return a(r)?L(r.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=x.untag(t,n);return a(r)?L(r.message??"Unable to untag issue",e):c("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=x.assign(t,n);return a(r)?L(r.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=x.unassign(t,n);return a(r)?L(r.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=x.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?L(o.message??"Failed to move node",e):c("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=x.editValue(t,n);return a(r)?L(r.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=x.getNode(t);if(!o)return L("Unable to locate issue",e);if(!P(o))return L("Can only close issues",e);let s=x.getNode(Ie);if(!s)return L("Unable to locate target swimlane",e);if(n!==s.id)return L("Close target must be closed swimlane",e);let d=x.moveNodeToRank({id:t,parentId:n,rank:r});return a(d)?L(d.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=x.getNode(t);if(!o)return L("Unable to locate issue",e);if(!P(o))return L("Can only reopen issues",e);let s=x.getNode(Ie);if(!s)return L("Unable to locate closed swimlane",e);if(n===s.id)return L("Cannot reopen issue into closed swimlane",e);if(!x.getNode(n))return L("Reopen parent no longer exists",e);let l=x.moveNodeToRank({id:t,parentId:n,rank:r});return a(l)?L(l.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=x.lockNode(t);return a(n)?L(n.message??"Unable to lock node",e):c("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=x.getNode(r);if(!s)return L(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return L(`Node ${r} is not child of ${t}`,e);let d=x.updateNode({...s,rank:o});if(a(d))return L(d.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=x.createComment({id:t,issue:n,authorId:r,authorName:x.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return a(s)?L(s.message??"Unable to add comment",e):c("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=x.getComment(t);if(!o)return L("Unable to locate comment",e);if(o.issue!==n)return L("Comment does not belong to issue",e);let s=x.editComment(t,r);return a(s)?L(s.message??"Unable to edit comment",e):c("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=x.getComment(t);if(!r)return L("Unable to locate comment",e);if(r.issue!==n)return L("Comment does not belong to issue",e);let o=x.deleteComment(t);return a(o)?L(o.message??"Unable to delete comment",e):c("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:d}=e.payload,l=x.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:d,deleted:!1});return a(l)?L(l.message??"Unable to add attachment",e):c("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=x.getAttachment(t);if(!r)return L("Unable to locate attachment",e);if(r.issue!==n)return L("Attachment does not belong to issue",e);let o=x.deleteAttachment(t);return a(o)?L(o.message??"Unable to delete attachment",e):c("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=x.linkUserId({contributorId:t,userId:e.userId});return a(n)?L(n.message??"Unable to link contributor",e):c("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};_t=e=>{let t=qd(()=>{let n=We===null;n&&(We={appLog:[],nodeLog:new Map,virtualNodeIds:new Set,genesisApplied:!1});try{let r=e.map(o=>tn(o));if(n&&We){let o=zg(We);if(o)return e.map(()=>o)}return r}finally{n&&(We=null)}});return a(t)?e.map(()=>i(t.message)):t.value}});var Ei,Vd=y(()=>{"use strict";Ei=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown"});var Xg,Jg,zd,Kd,Ri=y(()=>{"use strict";Xg=["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"],Jg=new Set(Xg),zd=e=>Jg.has(e),Kd=e=>({action:e.action,payload:e.payload})});import{z as W}from"zod";var j,pt,nn,Go,Ni,Qg,Yd,Xd=y(()=>{"use strict";C();j=W.string().min(1),pt=W.string(),nn=W.string(),Go=W.looseObject({id:j}),Ni=W.looseObject({id:j,name:pt,parent:j,rank:nn}),Qg={"init.workspace":W.looseObject({id:j,name:pt,rank:nn}),"add.workspace":W.looseObject({id:j,name:pt,rank:nn}),"add.board":Ni,"add.swimlane":Ni,"add.issue":Ni,"add.field":W.looseObject({id:j,name:pt,parent:j,rank:nn}),"edit.title":W.looseObject({id:j,name:pt}),"delete.node":Go,"lock.node":Go,"move.node":W.looseObject({id:j,parent:j,rank:nn}),"edit.description":W.looseObject({id:j,md:W.string()}),"close.issue":W.looseObject({id:j,parent:j,rank:nn}),"reopen.issue":W.looseObject({id:j,parent:j,rank:nn}),"create.tag":W.looseObject({id:j,name:pt}),"tombstone.tag":Go,"restore.tag":W.looseObject({id:j,name:pt}),"create.contributor":W.looseObject({id:j,name:pt}),"rename.contributor":W.looseObject({id:j,name:pt}),"tombstone.contributor":Go,"restore.contributor":W.looseObject({id:j,name:pt}),"link.contributor.user":W.looseObject({contributor:j}),"add.issue.assignee":W.looseObject({id:j,assignee:j}),"remove.issue.assignee":W.looseObject({id:j,assignee:j}),"add.issue.tag":W.looseObject({id:j,tag:j}),"remove.issue.tag":W.looseObject({id:j,tag:j}),"add.issue.comment":W.looseObject({id:j,issue:j,md:W.string()}),"edit.issue.comment":W.looseObject({id:j,issue:j,md:W.string()}),"delete.issue.comment":W.looseObject({id:j,issue:j}),"add.issue.attachment":W.looseObject({id:j,issue:j,hash:W.string().min(1),ext:W.string().min(1),name:pt,bytes:W.number()}),"delete.issue.attachment":W.looseObject({id:j,issue:j}),"rebalance.children":W.looseObject({parent:j,ranks:W.record(W.string(),nn)})},Yd=(e,t)=>{let r=Qg[e].safeParse(t);return r.success?c("Payload is readable",void 0):i(`${e}: ${r.error.issues.map(o=>`${o.path.join(".")||"payload"} ${o.message}`).join(", ")}`)}});import Vo from"node:fs";import zo from"node:path";import{decodeTime as Zg}from"ulid";import{z as Si}from"zod";function Or(e,t){let n=wr(e);if(!Vo.existsSync(n))return c("No events found",[]);let r=Vo.readdirSync(n).filter(s=>s.endsWith(".jsonl")).map(s=>zo.join(n,s)),o=[];for(let s of r){let d=cf(s,t);if(a(d))return i(d.message);o.push(...d.value)}return c("All events loaded",uf(o))}function $t(e){let t=[],n=Or(e,t);if(a(n))return i(n.message);let r=Ai(n.value,t);return a(r)?i(r.message):(lf=t,c("Loaded merged events",{events:r.value,unreadable:t}))}function Ti(e){let t=Or(e);return a(t)?i(t.message):c("Loaded event actors",t.value.map(({userId:n,userName:r})=>({userId:n,userName:r})))}function Kn(e){let t=$t(e);return a(t)?i(t.message):c("Loaded merged events",t.value.events)}function wi(e,t){let n=Or(e);if(a(n))return i(n.message);let{appliedEvents:r,unappliedEvents:o}=mf(n.value,t),s=Ai(r);if(a(s))return i(s.message);let d=Ai(o);return a(d)?i(d.message):c("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function Jd(e=process.cwd()){let t=Or(e);return a(t)?i(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}function Mi(e){let t=Or(e);if(a(t))return i(t.message);let n=Qd(t.value);return c("Loaded effective event times",new Map(t.value.map((r,o)=>[r.id[0],n[o]??null])))}var ef,qo,tf,nf,rf,of,sf,af,df,Ai,cf,lf,Ci,uf,Qd,mf,rn=y(()=>{"use strict";Nt();C();pe();dt();Ri();gt();Xd();ef=Si.object({userId:Si.string().min(1).default("unknown"),userName:Si.string().min(1).default("unknown")}),qo=e=>{let t=Object.entries(e).filter(([o])=>o!=="id"&&o!=="v"&&o!=="userId"&&o!=="userName");if(t.length!==1)return null;let n=t[0]?.[1];if(typeof n!="object"||n===null)return null;let r=n.id;return typeof r=="string"&&r.length>0?r:null},tf=/^[0-9a-hjkmnp-tv-z]{26}$/i,nf=e=>tf.test(e)?e.toUpperCase():e,rf=e=>{let t=zo.basename(e,".jsonl"),n=t.indexOf("."),r=n===-1?t:t.slice(0,n),o=n===-1?void 0:t.slice(n+1),s=ef.safeParse({userId:nf(r),userName:o});return s.success?c("Parsed event file actor",s.data):i(`Invalid event file name ${zo.basename(e)}: ${s.error.issues.map(d=>d.path.join(".")||d.message).join(", ")}`)},of=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?i(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?i("Invalid persisted event: action key is missing or invalid"):c("Resolved persisted action",t[0])},sf=(e,t)=>t in e,af=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),df=e=>{let{userId:t,userName:n,...r}=e,o=of(r);if(a(o))return i(o.message);let s=o.value,d=e.id?.[0];return d?sf(r,s)?c("Decoded persisted event",af({id:d,action:s,payload:r[s],userId:t,userName:n})):i(`Persisted event is missing payload for action: ${s}`):i("Persisted event is missing id")},Ai=(e,t)=>{let n=[],r=new Map,o=new Map;for(let s of e){if(!ec(s.v)){o.set(s.v,(o.get(s.v)??0)+1),t?.push({eventId:s.id[0],reason:"unsupported-schema-version",detail:`v${s.v}`,targetNodeId:qo(s)});continue}let d=df(s);if(a(d)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:d.message,targetNodeId:qo(s)});continue}let l=d.value.action;if(!zd(l)){r.set(l,(r.get(l)??0)+1),t?.push({eventId:s.id[0],reason:"unknown-action",detail:l,targetNodeId:qo(s)});continue}let u=Yd(l,d.value.payload);if(a(u)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:u.message,targetNodeId:qo(s)});continue}n.push(d.value)}if(r.size>0){let s=[...r.entries()].map(([d,l])=>`${d} (x${l})`).join(", ");X.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${s}. Upgrade to apply them.`)}if(o.size>0){let s=[...o.entries()].map(([d,l])=>`v${d} (x${l})`).join(", ");X.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${s}. Upgrade to apply them.`)}return c("Decoded reconstructed events",n)},cf=(e,t)=>{if(!Vo.existsSync(e))return c("Event file missing",[]);let n=rf(e);if(a(n))return i(n.message);let r=Vo.readFileSync(e,"utf8"),o=[],s=zo.basename(e),d=(l,u)=>{t?.push({eventId:null,reason:"corrupt-line",detail:`${s}:${l} (${u})`,targetNodeId:null})};for(let[l,u]of r.split(`
|
|
22
|
+
`).entries()){let m=u.trim();if(!m)continue;let p;try{p=JSON.parse(m)}catch{d(l+1,"invalid JSON");continue}let f=Zd(p);if(a(f)){d(l+1,f.message);continue}o.push({...f.value,userId:n.value.userId,userName:n.value.userName})}return c("Parsed persisted events file",o)};lf=[];Ci=(e,t)=>{let n=e.id[0].localeCompare(t.id[0]);return n!==0?n:JSON.stringify(e).localeCompare(JSON.stringify(t))},uf=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],f=m.id[1]??null;t.set(p,m);let I=n.get(f)??[];I.push(m),n.set(f,I)}for(let m of n.values())m.sort(Ci);let r=[],o=new Set,s=m=>{let p=[m];for(;p.length>0;){let f=p.pop(),I=f.id[0];if(o.has(I))continue;r.push(f),o.add(I);let N=n.get(I)??[];for(let A=N.length-1;A>=0;A--)p.push(N[A])}},d=(n.get(null)??[]).filter(m=>{let p=Object.keys(m).filter(f=>f!=="id"&&f!=="v"&&f!=="userId"&&f!=="userName");return p.length===1&&p[0]==="init.workspace"});for(let m of d)s(m);let l=e.filter(m=>{let p=m.id[0],f=m.id[1]??null;return o.has(p)?!1:f===null||!t.has(f)}).sort(Ci);for(let m of l)s(m);let u=e.filter(m=>!o.has(m.id[0])).sort(Ci);for(let m of u)s(m);return r},Qd=e=>vr(e.map(t=>{try{return Zg(t.id[0])}catch{return null}}));mf=(e,t)=>{let n=new Set,r=[],o=[],s=Qd(e);for(let d=0;d<e.length;d++){let l=e[d],u=l.id[0],m=l.id[1],p=s[d]??null;!(p!==null&&p<t)||m&&n.has(m)?(n.add(u),o.push(l)):r.push(l)}return{appliedEvents:r,unappliedEvents:o}}});import pf from"node:fs";import gf from"node:path";import{decodeTime as ff,monotonicFactory as hf}from"ulid";import{z as Tn}from"zod";function Ko({event:e,rootDir:t,edge:n}){try{let r=Ud(t);if(a(r))return r;let o=Sf(t,{userId:e.userId,userName:e.userName});if(a(o))return o;let s;if(n&&n.current!==void 0)s=n.current;else{let u=Jd(t);if(a(u))return i(u.message);s=u.value}let d=s?tc(bf(s)):tc(),l=Cf(Kd(e),[d,s]);return a(l)?i(l.message):(pf.appendFileSync(o.value,`${JSON.stringify(l.value)}
|
|
23
|
+
`,"utf8"),n&&(n.current=d),c("Event persisted",{path:o.value,entry:l.value}))}catch(r){let o=r instanceof Error?r.message:"Unknown persist error";return i(`Failed to persist event: ${o}`)}}var nc,tc,vf,yf,bf,rc,xf,If,Zd,Ef,Rf,ec,Nf,ve,wn,Sf,Cf,gt=y(()=>{"use strict";Nt();hr();C();Ue();pe();Vd();dt();rn();Ri();nc=1,tc=hf(),vf=0xffffffffffff,yf=No,bf=e=>{let t=Date.now(),n;try{n=ff(e)}catch{return t}return n>=vf?t:n>t+yf?(X.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)},rc=Tn.tuple([Tn.string().min(1),Tn.string().min(1).nullable()]),xf=Tn.looseObject({v:Tn.literal(nc),id:rc}),If=Tn.looseObject({v:Tn.number().int().positive(),id:rc}),Zd=e=>{let t=If.safeParse(e);return t.success?c("Parsed persisted event envelope",t.data):i(`Invalid persisted event envelope: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Ef=[1],Rf=new Set(Ef),ec=e=>Rf.has(e),Nf=e=>{let t=xf.safeParse(e);return t.success?c("Parsed persisted event",t.data):i(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},ve=()=>{let{userName:e,userId:t}=xe();return e?t?Ro(t)?fr(e)?c("Successfully resolved actor ID",{userId:t,userName:e}):i("Invalid user name in config"):i("Invalid user ID in config"):i("User ID not configured"):i("User name not configured")},wn=({userId:e,userName:t})=>`${Ei(e)}.${Ei(t)}.jsonl`,Sf=(e,{userId:t,userName:n})=>{let r=wn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return i(`Invalid event log file name: ${r}`);let s=gf.join(wr(e),r);return c("Successfully resolved event log path",s)},Cf=(e,t)=>{let n={[e.action]:e.payload,v:nc,id:t};return Nf(n)}});import{ulid as Af}from"ulid";function oc(e,t,n){let r=tn(e);if(r.status!==Ft.Success)return r;let o=Ko({event:e,rootDir:t,edge:n});return a(o)?o:r}function O(e,t){if(e.length===0||!e[0])return i("No events provided");if(g().readOnly)return i(g().readOnlyReason??"Cannot change the board while time travelling");let n={},r=Tf(e[0],t,n);if(a(r))return r;let o=e.map(d=>oc(d,t,n)),s=o.filter(a);return s.length>0?i("Materialize and persist failed: "+s.map(d=>d.message).join(", ")):c("Materialization succeeded",o.map(d=>d.value))}var Tf,Mn=y(()=>{"use strict";C();ge();k();Ut();gt();Tf=(e,t,n)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return c("Contributor write already in flight",void 0);let r=x.getContributor(e.userId),o={id:Af(),action:r?"rename.contributor":"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName};if(r&&(r.tombstoned||r.name===e.userName))return c("Contributor name is current",void 0);let s=oc(o,t,n);return a(s)?i(s.message):c("Contributor name recorded",void 0)}});var sc,Yo,me,ic,ac,on,kn,Rt=y(()=>{"use strict";yd();Mn();C();k();Gn();sc=e=>Yo(me(e),{at:"end"}),Yo=(e,t={at:"end"})=>{let n=o=>a(o)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n($e(void 0,void 0));let r=()=>n($e(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n($e(void 0,o.rank)):i("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n($e(o.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let o=ic(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let d=o>0?e[o-1]:void 0;return n($e(d?.rank,s.rank))}case"after":{let o=ic(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let d=o<e.length-1?e[o+1]:void 0;return n($e(s.rank,d?.rank))}}},me=e=>Object.values(g().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),ic=(e,t)=>e.findIndex(n=>n.id===t),ac=(e,t,n={at:"end"})=>Yo(me(t).filter(r=>r.id!==e),n),on=(e,t,n,r,o)=>{let s=ac(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return c("Resolved rank",s.value.rank);let d=oi(e,r);if(a(d))return d;let l=O([d.value],o);if(a(l))return l;let u=ac(t,e,n);return a(u)?u:u.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",u.value.rank)},kn=(e,t,n)=>{let r=sc(e);if(a(r))return r;if(!r.value.needsRebalance)return c("Resolved rank",r.value.rank);let o=oi(e,t);if(a(o))return o;let s=O([o.value],n);if(a(s))return s;let d=sc(e);return a(d)?d:d.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",d.value.rank)}});var _,dc,cc,Ze=y(()=>{"use strict";k();_={exit(){process.exit(0)},enterChildNode(){let e=g(),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"||_.navigate({contextNode:o,selectedIndex:ae(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=g();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:d})=>d===e.id),s=r.length===0?-1:o>=0?o:0;_.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>dc(1),navigateToPreviousItem:()=>dc(-1),navigateToNextContainer:()=>cc(1),navigateToPreviousContainer:()=>cc(-1),navigate:({contextNode:e,selectedIndex:t})=>{E({contextNodeId:e.id,selectedIndex:t})}},dc=e=>{let{selectedIndex:t,contextNode:n}=g(),r=ae(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;_.navigate({selectedIndex:s,contextNode:n})},cc=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=g();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),d=s.findIndex(I=>I.id===t.id);if(d<0)return;let l=s.at(d+e)??s.at(0);if(!l)return;let u=ae(l.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),f=u.length?p:-1;_.navigate({contextNode:l,selectedIndex:f})}});var uc,mc,wf,Xo,pc,lc,Mf,gc,fc=y(()=>{"use strict";he();C();Rt();k();Ze();uc=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),mc=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},wf=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&Je(t)&&t.childRenderAxis==="vertical"},Xo=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r||r.isDeleted)return!1;let o=me(r.id);return _.navigate({contextNode:r,selectedIndex:uc(t,o.length)}),!0},pc=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Xo(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let d=me(o.id).findIndex(l=>l.id===n.id);return d>=0?(_.navigate({contextNode:o,selectedIndex:d}),!0):pc(o.id)},lc=e=>{let{nodes:t}=g(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),pc(n))return!0;n=t[n]?.parentNodeId}return!1},Mf=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},gc=e=>{let{nodes:t,rootNodeId:n}=g();if(wf(e.contextNodeId)&&Xo(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(Mf(e.selectedNodeId)&&e.selectedNodeId&&lc(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(Xo(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&Xo(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(lc(e.contextNodeId))return c("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return i("Unable to restore navigation");let o=me(r.id);return _.navigate({contextNode:r,selectedIndex:uc(e.selectedIndex,o.length)}),c("Restored navigation to root",null)}});import{monotonicFactory as kf,ulid as Tt}from"ulid";function Lf(){let e=Ge();if(a(e))return i("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return i("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 c("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?c("Resolved boot nav target",{contextNode:r,selectedIndex:0}):c("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function Pf(){let e=Lf();return a(e)?e:_.navigate(e.value)}function hc({userId:e,userName:t}){let n=Br(),r=Br(),o=Br(),s=Br(),d=Br(),l=$e(void 0,void 0);if(a(l))return l;let u=$e(void 0,void 0);if(a(u))return u;let m=$e(u.value,void 0);if(a(m))return m;let p=$e(void 0,void 0);if(a(p))return p;let f=$e(p.value,void 0);if(a(f))return f;let I=$e(f.value,void 0);if(a(I))return I;let N=$e(void 0,void 0);return a(N)?N:c("Created default events",[{id:Tt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:Tt(),userId:e,userName:t,action:"create.contributor",payload:{id:e,name:t}},{id:Tt(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Tt(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Tt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Tt(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:r,rank:I.value}},{id:Tt(),userId:e,userName:t,action:"add.board",payload:{id:jo,name:"Closed",parent:n,rank:m.value}},{id:Tt(),userId:e,userName:t,action:"add.swimlane",payload:{id:Ie,name:"Closed",parent:jo,rank:N.value}},{id:Tt(),userId:e,userName:t,action:"lock.node",payload:{id:jo}},{id:Tt(),userId:e,userName:t,action:"lock.node",payload:{id:Ie}}])}function sn(e,t=[]){if(Df())return c("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Ae.workspace("temporary-uninitialized-workspace","Workspace","a0"),d=Fr(s);return a(d)?d:(E({hasProjectDefinition:!1,mode:h.DEFAULT}),c("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return i("Initialized Epiq project has no workspace init event");let n=_t(e),{fatal:r,skipped:o}=Cn(n);return r.length>0?i(`Materializing failed:
|
|
24
24
|
${r.map(s=>s.message).join(`
|
|
25
|
-
`)}`):(
|
|
26
|
-
`).filter(t=>t.trim().length>0),
|
|
27
|
-
`)
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
${
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
${
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
`+
|
|
38
|
-
`)
|
|
39
|
-
${
|
|
40
|
-
`))
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
${
|
|
44
|
-
|
|
45
|
-
${
|
|
46
|
-
${u.message}`)
|
|
47
|
-
${
|
|
48
|
-
${
|
|
49
|
-
${
|
|
50
|
-
|
|
51
|
-
${s.message}`);let d=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return c(d?"Pushed state branch":"Remote already up to date",d)},bc=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Kt(e);if(a(o))return o;let s=o.value,d=[Mo(),await Si({repoRoot:e,stateBranchName:s}),await An({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Tf({stateBranchRoot:t,stateBranchName:s}),await wd(t),n?await wf({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of d){if(a(l))return i(l.message);r=r||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)}});import zo from"node:fs";import Ai from"node:os";import Mf from"node:path";var kf,xc,Lf,Pf,Df,Ec,Ci,Ic,Ff,Rc,Nc=y(()=>{"use strict";C();ct();It();kf="epiq-sync.lock",xc=600*1e3,Lf=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}},Pf=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Df=e=>e&&(e.hostname!==Ai.hostname()||Pf(e.pid))?Date.now()-e.startedAt>xc:!0,Ec=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,Ci=e=>{try{return Lf(zo.readFileSync(e,"utf8"))}catch{return null}},Ic=(e,t)=>{let n={pid:process.pid,hostname:Ai.hostname(),startedAt:Date.now(),operation:t};try{return zo.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},Ff=async({worktreeRoot:e,operation:t})=>{let n=await Js(e);if(a(n))return i(n.message);let r=Mf.join(n.value,kf),o=()=>{try{let l=Ci(r);l&&l.pid===process.pid&&zo.rmSync(r)}catch{}};if(Ic(r,t))return c("Acquired sync lock",{acquired:!0,release:o});let s=Ci(r);if(!Df(s))return c("Sync lock is held",{acquired:!1,heldBy:s});z.info(`Breaking an abandoned sync lock: ${s?Ec(s):"unreadable lock file"}`);try{zo.rmSync(r,{force:!0})}catch{}if(Ic(r,t))return c("Acquired sync lock after breaking a stale one",{acquired:!0,release:o});let d=Ci(r);return c("Sync lock taken by another process",{acquired:!1,heldBy:d??{pid:-1,hostname:Ai.hostname(),startedAt:Date.now(),operation:"unknown"}})},Rc=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await Ff({worktreeRoot:e,operation:t});if(a(r))return i(r.message);if(!r.value.acquired)return z.info(`Skipping ${t}: the state worktree is held by ${Ec(r.value.heldBy)}`),c("State worktree is held by another process",null);let{release:o}=r.value;try{return c("Ran under the sync lock",await n())}finally{o()}}});import Bf from"node:fs";var Of,_f,Sc,Cc,Yo,Ti=y(()=>{"use strict";C();Go();qo();br();ut();ct();Fr();Nc();Of=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=J("getRepoRootDir",await lt(e));if(a(n))return i(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=J("getStateBranchRoot",Ne({repoRoot:r}));if(a(o))return i(o.message);let s=o.value;logger.debug("[sync] state branch root",s),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let d=J("bootstrapStateBranchStorage",await bc({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(a(d))return i(d.message);logger.debug("[sync] bootstrap result",{bootstrapped:d.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let l=J("hasInProgressGitOperation(stateBranchRoot)",await Co(s));if(a(l))return i(l.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:l.value}),l.value)return logger.info("[sync] state branch git operation in progress"),i("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let u=J("ensureStateBranchLayout",Td(r,s));return a(u)?i(u.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:d.value}),c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:d.value}))},_f=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=J("stageStateBranchOwnEventFile",await Ko({stateBranchRoot:t,eventFileName:n}));if(a(r))return i(r.message);let o=J("stageStateBranchMediaFiles",await hc({stateBranchRoot:t}));if(a(o))return i(o.message);let s=J("stageStateBranchEventAttributes",await vc({stateBranchRoot:t}));if(a(s))return i(s.message);let d=[r.value,o.value,s.value].filter(m=>m!==null);if(d.length===0)return c("Nothing to stage",{createdCommit:!1});let l=J("hasStagedChanges(after stage)",await xd(t,d));if(a(l))return i(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"),c("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let u=J("createStateBranchSyncCommit",await yc({repoRoot:e,stateBranchRoot:t,pathspec:d}));return a(u)?i(u.message):(logger.debug("[sync] created sync commit",u.value),c("Committed own event file",{createdCommit:!0,commitSha:u.value}))},Sc=e=>{let t=e.createdCommit?"Committed locally, offline":"Offline";return cc(t),c(t,{...e,pulled:!1,pushed:!1,offline:!0})},Cc=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),i("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}),i("Own event file must end with .jsonl");Ho();let n=J("ensureSyncReady",await Of({cwd:e,ensureUpstream:!0}));if(a(n))return ke(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,d=J("isDetachedHead(stateBranchRoot)",await Id(o));if(a(d))return ke(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return ke("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,p=!1,f=J("getStateBranch",Kt(r));if(a(f))return ke(f.message);let I=f.value;logger.debug("[sync] resolved state branch",{stateBranch:I,stateBranchRoot:o});let N=J("commitOwnEventFileToStateBranch",await _f({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(a(N))return ke(N.message);l=N.value.createdCommit,u=N.value.commitSha;let A=J("pullBranchRebaseIfPresent",await ni({cwd:o,branch:I}));if(a(A))return ti(A.message)?Sc({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,bootstrapped:s}):ke(A.message);m=A.value;let w=J("isAheadOfUpstream",await yd(o));if(a(w))return ke(w.message);if(l||s||w.value){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:s,stateBranchRoot:o});let T=J("pushStateBranch",await Dr({stateBranchRoot:o,repoRoot:r}));if(a(T)&&vd(T.message)){let M=J("pullBranchRebaseIfPresent(retry)",await ni({cwd:o,branch:I}));if(a(M))return ke(M.message);m=m||M.value,T=J("pushStateBranch(retry)",await Dr({stateBranchRoot:o,repoRoot:r}))}if(a(T))return ti(T.message)?Sc({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,bootstrapped:s}):ke(T.message);p=T.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let T=J("git rev-parse HEAD",await j({args:["rev-parse","HEAD"],cwd:o}));if(a(T))return ke(T.message);u=T.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Wo(p?"Synced and pushed":m||l?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),c("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,pulled:m,pushed:p,bootstrapped:s,offline:!1})},Yo=async e=>{let t=e.cwd??process.cwd(),n=await lt(t);if(a(n))return ke(n.message);let r=Ne({repoRoot:n.value});if(a(r))return ke(r.message);let o=r.value;if(!Bf.existsSync(o))return Cc(e);let s=await Rc({worktreeRoot:o,operation:"sync",fn:()=>Cc(e)});return a(s)?ke(s.message):s.value===null?c("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 Ct,Xo,Uf,Ac,wi=y(()=>{"use strict";sc();kr();Jt();mt();ce();C();k();Go();qo();Ti();Ct=null,Xo=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Ct,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),Ct)return logger.debug("[sync] syncAndReloadState joining existing promise"),Ct;logger.debug("[sync] syncAndReloadState creating promise"),Ct=Uf();try{let e=await Ct;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:g().syncStatus?.status,statusMessageAfterResolve:g().syncStatus?.msg}),a(e)&&g().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),E({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}),Ct||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),Ct=null}},Uf=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=Ac();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(Ct)return Ct;logger.debug("[sync] syncAndReloadState:start");let t=J("resolveActorId",fe());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),i("Unable to resolve event log path");E({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:g().syncStatus});let n=Nn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=J("syncEpiqWithRemote",await Yo({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),E({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),ke(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let d=J("loadMergedEvents",Bt(o));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(d),message:(a(d),d.message),count:a(d)?void 0:d.value.events.length}),a(d))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:g().syncStatus}),i(`Unable to load events. ${d.message}`);logger.debug("[sync] loaded merged events after sync",{count:d.value.events.length});let l=Ac();if(l)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:l.message,syncStatus:g().syncStatus}),l;let u=nc(),m=g().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:u,selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id,selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual}),!g().selectedNode?.isVirtual&&!g().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:d.value.events.length});let f=J("bootStateFromEventLog",Zt(d.value.events,d.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(f),message:(a(f),f.message)}),a(f))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:g().syncStatus}),i(`Unable to boot synced state. ${f.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),E({filters:m}),logger.debug("[sync] restoreNavigationAnchor:start");let p=J("restoreNavigationAnchor",oc(u));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(p),message:a(p)?p.message:"Navigation restored",selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id}),a(p)?(E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),p):(E({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),c("Synced",!0))},Ac=()=>g().mode===h.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),E({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),i("Will not re-materialize if not in default mode, to not lose edit data"))});var qn,Tc,wc,Mi,ki,Br,Li,$f,Mc,jf,kc,Jo=y(()=>{"use strict";C();Oe();k();wi();qn=3e3,Tc=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<qn?null:t},wc=0,ki=!1,Br=!1,Li=()=>{if(ki)return!0;let e=je();return a(e)?!1:e.value.syncStatus.status==="syncing"},$f=()=>{let e=ye().autoSyncIntervalMs??1e4,t=Date.now()-wc;return Math.max(0,e-t)},Mc=()=>{Mi||(Mi=setTimeout(async()=>{if(Mi=void 0,!!Nt()){if(Li()){Br=!0;return}Br=!1,await jf()}},$f()))},jf=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return i("Cannot auto-sync while peeking");if(!Nt())return i("Cannot auto-sync before state is initialized");if(Li())return Br=!0,i("Sync already in progress");ki=!0,wc=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Xo()}finally{ki=!1,Br&&Mc()}},kc=()=>{Nt()&&(Br=!0,!Li()&&Mc())}});import Or from"node:fs";import _r from"node:path";import{z as Vn}from"zod";var Qo,Hf,Wf,Gf,Pc,Dc,Lc,Fc,Bc,Oc,qf,Zo,Pi,Ur=y(()=>{"use strict";C();Pt();No();ue();Qo="recent-projects.json",Hf=20,Wf=Vn.object({projectId:Vn.string().min(1),root:Vn.string().min(1),lastOpenedAt:Vn.number().finite()}),Gf=Vn.object({projects:Vn.array(Wf)}),Pc=()=>_r.join(hn(),Qo),Dc=e=>_r.basename(e)||e,Lc=e=>{let t=_r.resolve(e);try{return Or.realpathSync(t)}catch{return t}},Fc=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Bc=e=>{if(!Nr(e.root))return!1;let t=vr(e.root);return!a(t)&&t.value===e.projectId},Oc=()=>{let e=Pc();if(!Or.existsSync(e))return c("No recent projects recorded",[]);let t;try{t=JSON.parse(Or.readFileSync(e,"utf8"))}catch(r){return i(`Invalid ${Qo}: ${r instanceof Error?r.message:String(r)}`)}let n=Gf.safeParse(t);return n.success?c("Read recent projects",n.data.projects):i(`Invalid ${Qo} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},qf=e=>{let t=Pc();try{Or.mkdirSync(_r.dirname(t),{recursive:!0}),Or.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
52
|
-
`,"utf8")}catch(n){return i(`Unable to write ${Qo}: ${n instanceof Error?n.message:String(n)}`)}return c("Recorded recent project",e)},Zo=({exclude:e}={})=>{let t=Oc();if(a(t))return t;let n=e===void 0?null:Lc(e);return c("Listed recent projects",t.value.filter(r=>n===null||Lc(r.root)!==n).filter(Bc).sort(Fc))},Pi=({root:e,now:t=Date.now()})=>{let n=_r.resolve(e),r=vr(n);if(a(r))return i(r.message);let o=r.value,s=Oc(),d=a(s)?[]:s.value,l=[{projectId:o,root:n,lastOpenedAt:t},...d.filter(u=>u.projectId!==o&&u.root!==n)].filter(Bc).sort(Fc).slice(0,Hf);return qf(l)}});var es,_c,Uc,$c,$r=y(()=>{"use strict";C();Pt();Oe();ue();es=()=>{let e=ye(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},_c=()=>{let e=Xe(process.cwd());if(a(e))return!1;let t=Lt(e.value);return ft(t)},Uc=e=>e===!0?"on":e===!1?"off":null,$c=e=>e==="on"?!0:e==="off"?!1:null});var Le,S,Pe=y(()=>{"use strict";Le={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"},S={accent:Le.cyan,accent2:Le.magenta,primary:Le.white,secondary:Le.grayDark,secondary2:Le.grayLight,gray:Le.gray,green:Le.green,yellow:Le.yellow,red:Le.red}});var R,Kn,ts=y(()=>{"use strict";Pe();R={red:Le.red,yellow:Le.yellow,green:Le.green,blue:Le.blue,magenta:Le.magenta,cyan:Le.cyan},Kn={urgent:R.red,critical:R.red,important:R.red,blocker:R.red,asap:R.red,immediate:R.red,fail:R.red,failure:R.red,broken:R.red,bug:R.red,error:R.red,incident:R.red,outage:R.red,production:R.red,crash:R.red,security:R.red,warning:R.yellow,warn:R.yellow,risky:R.yellow,risk:R.yellow,attention:R.yellow,pending:R.yellow,review:R.yellow,"needs-review":R.yellow,qa:R.yellow,testing:R.yellow,test:R.yellow,validate:R.yellow,verification:R.yellow,staging:R.yellow,check:R.yellow,"follow-up":R.yellow,followup:R.yellow,waiting:R.yellow,blocked:R.yellow,hold:R.yellow,done:R.green,complete:R.green,completed:R.green,success:R.green,ok:R.green,stable:R.green,resolved:R.green,fixed:R.green,closed:R.green,merged:R.green,released:R.green,deployed:R.green,approved:R.green,verified:R.green,working:R.green,healthy:R.green,pass:R.green,passing:R.green,info:R.blue,information:R.blue,note:R.blue,docs:R.blue,documentation:R.blue,doc:R.blue,guide:R.blue,help:R.blue,explanation:R.blue,detail:R.blue,details:R.blue,context:R.blue,design:R.blue,discussion:R.blue,proposal:R.blue,idea:R.blue,feature:R.magenta,enhancement:R.magenta,improvement:R.magenta,refactor:R.magenta,refactoring:R.magenta,cleanup:R.magenta,optimize:R.magenta,optimization:R.magenta,perf:R.magenta,performance:R.magenta,upgrade:R.magenta,migration:R.magenta,modernize:R.magenta,debt:R.magenta,todo:R.cyan,next:R.cyan,planned:R.cyan,plan:R.cyan,future:R.cyan,backlog:R.cyan,investigate:R.cyan,explore:R.cyan,prototype:R.cyan}});var Vf,Kf,en,tn,ns,rs,jr=y(()=>{"use strict";ge();C();me();k();Vf=e=>e.props.tags??[],Kf=e=>e.props.assignees??[],en=e=>Vf(e).map(t=>x.getTag(t)).filter(t=>!!t),tn=e=>Kf(e).map(t=>x.getContributor(t)).filter(t=>!!t),ns=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!L(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",en(n))},rs=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!L(n)?i("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",tn(n))}});var v,Tn=y(()=>{"use strict";v={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",COFFEE:"coffee",NONE:""}});var zf,Yf,Xf,Jf,Qf,wn,jc,os,ss,Hc,Zf,Di,Hr=y(()=>{"use strict";zf=/^(\d+)(h|d|w|mo|y)$/,Yf=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Xf=({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},Jf=(e,t=new Date)=>{let n=e.match(zf);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let d=new Date(t);switch(o){case"h":return d.setHours(d.getHours()-s),d;case"d":return d.setDate(d.getDate()-s),d;case"w":return d.setDate(d.getDate()-s*7),d;case"mo":return d.setMonth(d.getMonth()-s),d;case"y":return d.setFullYear(d.getFullYear()-s),d;default:return null}},Qf=e=>{let t=e.match(Yf);if(!t)return null;let[,n,r,o,s,d]=t,l=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,f=d?Number(d):0;return Xf({year:l,month:u,day:m,hour:p,minute:f})?new Date(l,u-1,m,p,f):null},wn=e=>{let t=e.trim().toLowerCase();return Jf(t)??Qf(t)},jc=/^(\d+)(s|m)?$/,os=e=>{let t=e.trim().toLowerCase().match(jc);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},ss=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&jc.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Hc=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Zf=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],Di=(e=Zf)=>{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 eh,pe,Ze,Ee,th,nh,Bi,Oi,qc,Mn,is,Fi,Wc,rh,oh,Wr,Gc,sh,ih,_i,ah,xe,nn=y(()=>{"use strict";Jo();Ur();C();$r();Wn();ge();me();k();ts();jr();Tn();Hr();eh=["BOARD","TICKET","SWIMLANE","COMMENT"],pe={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},Ze={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Ee={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},th=[pe.EDITOR,pe.VIEW,pe.USERNAME,pe.AUTOSYNC,pe.SYNC_DEBOUNCE_MS,pe.ATTACHMENT_MAX_KB,pe.LOG_LEVEL],nh=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[Ze.TITLE,Ze.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Ze.TITLE];case"COMMENT":return[Ze.COMMENT];default:return[]}},Bi=[String(qn),"5000","15000","30000","60000"],Oi=["250","500","1000"],qc=["10s","20s","30s","45s"],Mn=[v.COFFEE,v.EXIT,v.SYNC,v.HELP,v.EXPORT,v.CONFIG,v.YANK],is=[v.NEW,v.EDIT,v.DELETE,v.MOVE],Fi=[v.TAG,v.UNTAG,v.ASSIGN,v.UNASSIGN,v.CLOSE_ISSUE,v.RE_OPEN_ISSUE,v.EDIT,v.COMMENT],Wc=[v.FILTER,v.PEEK,v.REPLAY],rh={WORKSPACE:[...Mn,...is],BOARD:[...Wc,...Mn,...is],SWIMLANE:[...Wc,...Mn,...is],TICKET:[...Mn,...is,...Fi],FIELD:[...Mn,...Fi],FIELD_LIST:[...Mn,...Fi],TEXT:[...Mn],COMMENT:[v.EDIT,v.DELETE,v.YANK]},oh=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Wr=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&L(n)),Gc=e=>e.parentNodeId===be,sh=({selectedNode:e,breadCrumb:t})=>{let n=nh(e?.context);return Wr({breadCrumb:t,selectedNode:e})?n.includes(Ze.DESCRIPTION)?n:[...n,Ze.DESCRIPTION]:n},ih=({selectedNode:e,breadCrumb:t})=>{let n=Wr({breadCrumb:t,selectedNode:e});return n?[Ee.REF,Ee.TITLE,...n.props?.description?.trim()?[Ee.DESCRIPTION]:[],...en(n).length>0?[Ee.TAGS]:[],...tn(n).length>0?[Ee.ASSIGNEES]:[]]:e?[Ee.REF,Ee.TITLE]:[]},_i=()=>{let e=Zo({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},ah=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=es();if(!r)return[v.HELP,v.CONFIG];if(!_c())return[v.HELP,v.INIT,v.OPEN];if(t)return[v.HELP,v.PEEK,v.REPLAY,v.EXPORT,v.CONFIG,v.YANK];let o=e?.context,s=o&&eh.includes(o),d=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?rh[u]:[]))],l=Wr({breadCrumb:n,selectedNode:e});return d.filter(u=>u===v.MOVE?!1:u===v.YANK?!!(l??e):u===v.EDIT?s||!!l:u===v.DELETE?s:u===v.UNTAG?!!(l&&en(l).length>0):u===v.UNASSIGN?!!(l&&tn(l).length>0):u===v.RE_OPEN_ISSUE?!!(l&&Gc(l)):u===v.CLOSE_ISSUE?!!(l&&!Gc(l)):!0)},xe=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=g())=>{let s=t.context??"WORKSPACE";return{[v.NONE]:ah({breadCrumb:o,readOnly:r,selectedNode:n}),[v.EXIT]:["confirm"],[v.EXPORT]:[],[v.SYNC]:[],[v.INIT]:[],[v.OPEN]:e===v.OPEN?_i():[],[v.HELP]:[],[v.PEEK]:[...Di(),"now","prev","next"],[v.REPLAY]:[...Di()],[v.EDIT]:sh({selectedNode:n,breadCrumb:o}),[v.YANK]:ih({selectedNode:n,breadCrumb:o}),[v.COMMENT]:[],[v.DELETE]:["confirm"],[v.RE_OPEN_ISSUE]:["confirm"],[v.CLOSE_ISSUE]:["confirm"],[v.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[v.FILTER]:["tag","assignee","description","title","ref","clear"],[v.TAG]:[...new Set([...Object.keys(Kn),...x.getExistingTags()])],[v.UNTAG]:[...ns()?.value?.map(({name:l})=>l)??[]],[v.UNASSIGN]:[...rs()?.value?.map(({name:l})=>l)??[]],[v.ASSIGN]:x.getExistingAssignees(),[v.NEW]:oh(s),[v.CONFIG]:[...th],[v.COFFEE]:["1","3","5","20","custom"]}[e]??[]}});var Vc,Kc=y(()=>{"use strict";Vc=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{accessSync as dh,copyFileSync as ch,existsSync as as,mkdirSync as zc,readdirSync as Yc,readFileSync as lh,renameSync as uh,rmSync as mh,statSync as Xc,unlinkSync as ph,writeFileSync as gh}from"node:fs";import zn from"node:path";var Ui,He,ds=y(()=>{"use strict";Ui=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",He={writeToFile:(e,t)=>{try{let n=zn.dirname(e);as(n)||zc(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);gh(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return lh(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=He.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 as(e)&&Xc(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await dh(e),!0}catch{return!1}},mkDir:e=>zc(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=zn.parse(t);for(;;){let r=zn.join(t,e);try{if(as(r)&&Xc(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=zn.dirname(t)}return null},readFirstJSON(e){try{if(!He.dirExists(e))return null;let t=Yc(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=zn.join(e,t);return He.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return He.dirExists(e)?Yc(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{ph(e)}catch(t){(!Ui(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{mh(e,{recursive:!0,force:!0})}catch(t){(!Ui(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(zn.dirname(t)),!n?.overwrite&&as(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{uh(e,t)}catch(r){if(Ui(r)&&r.code==="EXDEV"){ch(e,t),this.rmFile(e);return}throw r}}}});import fh from"node:path";import{z as _t}from"zod";var hh,Jc,vh,Qc,$i,ji,yh,cs,Zc,ot,Hi,kn=y(()=>{"use strict";ur();ue();C();ds();hh={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},Jc=_t.object({logLevel:_t.enum(["info","error","debug"]),preferredEditor:_t.string().optional(),userName:_t.string().optional(),userId:_t.string().optional(),autoSync:_t.boolean().nullable().optional(),autoSyncDebounceMs:_t.number().optional(),attachmentMaxKb:_t.number().optional(),viewMode:_t.enum(["dense","wide"]).optional()}).partial(),vh="config.json",Qc=hn,$i=()=>fh.join(Qc(),vh),ji=()=>{try{return He.mkDir(Qc()),c(`Ensured ~/${dt} exists`,null)}catch{return i(`Unable to create ~/${dt}`)}},yh=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${dt}/config.json JSON`)}let n=Jc.safeParse(t??{});return n.success?c("Parsed config",n.data):i(`Invalid ~/${dt}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},cs=()=>{let e=ji();if(a(e))return i(e.message);let t=$i(),n=He.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):yh(n)},Zc=e=>{let t=ji();if(a(t))return i(t.message);let n=Jc.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=$i();try{return He.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
53
|
-
`),c("Config written",null)}catch{return i(`Unable to write ~/${dt}/config.json`)}},ot=e=>{let t=cs();if(a(t))return i("Failed to read existing config");let n={...t.value,...e};return Zc(n)},Hi=()=>{let e=$i(),t=ji();if(a(t))return i(`Unable to create ~/${dt}`);if(!(He.readFile(e)!==null)){let A=Zc(hh);if(a(A))throw new Error(`Unable to create ~/${dt}/config.json`)}let r=cs();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:d,autoSync:l,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:f}=r.value,I=Vs({userId:d,userName:s});if(a(I))return i(I.message);let N=I.value??{userId:d,userName:s};return!N.userName||!N.userId?i(`User name or ID not configured in ~/${dt}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,c("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:N.userName,userId:N.userId,autoSync:l??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))}});var el,tl,Wi,nl=y(()=>{"use strict";el="/media/",tl=e=>`${el}${e}`,Wi=(e,t)=>`})`});import bh from"node:crypto";import Gi from"node:fs";import xh from"node:path";var Ut,Gr,Ih,Eh,Rh,rl,qr=y(()=>{"use strict";yt();C();ue();nl();Ut=500,Gr=(e,t)=>`${e}.${t}`,Ih=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?c("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?c("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")))?c("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"))?c("Sniffed image type","webp"):i(`Unsupported image format. Allowed: ${Xa.join(", ")}`),Eh=e=>bh.createHash("sha256").update(e).digest("hex"),Rh=(e,t=Ut)=>{if(e.length===0)return i("Attachment is empty");if(e.length>t*1024)return i(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=Ih(e);return a(n)?n:c("Validated attachment data",{hash:Eh(e),ext:n.value,bytes:e.length})},rl=(e,t,n=Ut)=>{let r=Rh(t,n);if(a(r))return r;let o=ko(e),s=xh.join(o,Gr(r.value.hash,r.value.ext));try{Gi.existsSync(s)||(Gi.mkdirSync(o,{recursive:!0}),Gi.writeFileSync(s,t))}catch(d){return i(`Unable to write attachment blob: ${d instanceof Error?d.message:String(d)}`)}return c("Wrote attachment blob",r.value)}});import Nh from"zod";var Vr,Kr,ol,qi=y(()=>{"use strict";kn();qr();ce();C();Ie();Oe();k();Vr=50,Kr=5e3,ol=()=>{let e=ie().commandMeta.inputString,t=Nh.coerce.number().int().min(Vr).max(Kr).safeParse(e);if(!t.success)return i(`Attachment size cap must be ${Vr}-${Kr} KB (default ${Ut})`);let n=ot({attachmentMaxKb:t.data});return a(n)?n:(tt({attachmentMaxKb:t.data}),E({mode:h.DEFAULT}),c(`Attachment size cap set to ${t.data} KB`,null))}});import sl from"chalk";var Ki,il,Vi,al,Sh,Ch,dl,Ah,Th,zr,De,cl,ll,ls,wh,Mh,us,At=y(()=>{"use strict";ts();Ki={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},il=(e,t,n)=>Math.max(t,Math.min(n,e)),Vi=(e,t,n)=>e+(t-e)*n,al=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Sh=e=>e.toLowerCase().trim(),Ch=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,d=e/60,l=s*(1-Math.abs(d%2-1)),u=0,m=0,p=0;d>=0&&d<1?(u=s,m=l):d>=1&&d<2?(u=l,m=s):d>=2&&d<3?(m=s,p=l):d>=3&&d<4?(m=l,p=s):d>=4&&d<5?(u=l,p=s):(u=s,p=l);let f=o-s/2;return[Math.round((u+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},dl=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Ah=(e,t,n)=>{let r=il(n,0,1);return[Math.round(Vi(e[0],t[0],r)),Math.round(Vi(e[1],t[1],r)),Math.round(Vi(e[2],t[2],r))]},Th=(e,t,n)=>Ah(e,t,n),zr=e=>{let t=al(e)%360,n=Ch(t,Ki.stringColor.saturation,Ki.stringColor.lightness);return dl(n)},De=(e,t=Kn)=>{let n=Sh(e);return n&&t[n]?t[n]:zr(n)},cl=e=>{let t=Ki.gradient.stops,n=il(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),d=o-s;return Th(t[s],t[s+1],d)},ll=e=>dl(cl(e)),ls=e=>al(e.toLowerCase().trim())/4294967295,wh=e=>{let t=ls(e);return cl(t)},Mh=e=>{let[t,n,r]=wh(e);return{normal:o=>sl.bgRgb(t,n,r).black(o),cursor:o=>sl.bgRgb(t,n,r).white.bold(o)}},us=e=>Mh(e).normal(` ${e} `)});var pt,Yr=y(()=>{"use strict";pt=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null});import{createHash as kh}from"node:crypto";var Lh,Ph,Ce,Yn=y(()=>{"use strict";Lh="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ph=e=>{let t=kh("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+=Lh[Number(n>>s&31n)]}return r},Ce=(e,t)=>Ph(`${e}:virtual:${t}`)});import ul from"chalk";var Q,Ae,Te,ml=y(()=>{"use strict";At();Pe();Q=e=>ul.dim(e),Ae=e=>ul.hex(S.primary)(e),Te=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let d=o.trim();if(d.length<s)return"";let p=[...t.filter(Boolean).filter(f=>f.startsWith(d))].sort((f,I)=>ls(f)-ls(I)).slice(0,r).map(f=>us(f)).join(" ");return p?`${Q(e)}${p}${Q(n)}`:""}});var rn,ms=y(()=>{"use strict";rn={None:"none",Invalid:"invalid",Valid:"valid"}});import fl from"chalk";var Dh,pl,ae,K,$,Xn,gl,ps,zi,Fh,Ln,Bh,Oh,_h,Uh,$h,hl,vl=y(()=>{"use strict";Jo();$r();Kc();it();yt();C();me();Oe();qi();qr();k();At();Yr();jr();Yn();ml();Tn();ms();nn();Hr();Dh=["BOARD","TICKET","SWIMLANE"],pl=()=>{let e=g().selectedNode;if(!e?.context)return $({message:Q("Missing target context")});if(Dh.includes(e.context))return K();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===Ce(t?.parentNodeId??"","comments"))return K()}return $({message:Q("Command not available in this context")})},ae="<ENTER> to confirm",K=(e="",t=[])=>({message:Q(e),validity:rn.Valid,completionWordList:t}),$=({message:e,completionWordList:t=[]})=>({validity:rn.Invalid,message:e,completionWordList:t}),Xn=e=>e.length===0,gl=(e,t)=>{let n=Ke(g().breadCrumb,"BOARD");if(a(n))return $({message:Ae("Command is not applicable in this context")});let r=Ya(n.value.id);return a(r)?$({message:Ae(`Unable to ${t}: board id is not a valid ULID`)}):Hc({date:e,horizonDate:r.value})?null:$({message:Ae(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},ps=e=>` ${fl.hex("#000").bgHex(De(e))(` ${e} `)} `,zi=({modifier:e})=>{let t="confirm";return e===t?K(ae):$({message:Xn(e)?Q("if you are certain, enter ")+us(t):"",completionWordList:[t]})},Fh=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?$({message:Q(n)}):K():$({message:Xn(r)?t:"",completionWordList:[...e]}),Ln=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>Xn(n)&&Xn(r)?$({message:e,completionWordList:[]}):K(t??ae),Bh=({modifier:e,inputString:t})=>{let n=_i();return!Xn(e)||!Xn(t)?K(ae):$({message:n.length?Q("number from the list, or a path"):Q("path to an epiq project"),completionWordList:n})},Oh=({modifier:e,inputString:t})=>{let n=xe(v.CONFIG);if(!n.includes(e))return $({message:Te({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case pe.EDITOR:{let r=[...Vc];return t.trim()?r.includes(t.trim())?K(ae):$({message:Te({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):$({message:Te({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case pe.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?K(ae):$({message:Te({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case pe.USERNAME:return t.trim()?K(ae):$({message:Ae("Enter a user name. Saved in ")+fl.bgBlack("~/.epiq-global/config.json")});case pe.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?K(ae):$({message:Te({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case pe.AUTOSYNC:{let r=["on","off"],o=ye().autoSync;if(!r.includes(t.trim())){let s=Uc(o);return $({message:Te({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return K(ae)}case pe.ATTACHMENT_MAX_KB:{let r=ye().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<Vr||o>Kr){let s=Te({prefix:" examples: ",wordList:Oi,minLengthForHints:0,inputString:t});return $({message:Ae(`provide a size cap in KB (${Vr}-${Kr}). current: ${r??Ut} KB.`)+s,completionWordList:Oi})}return K(ae)}case pe.SYNC_DEBOUNCE_MS:{let r=ye().autoSyncIntervalMs,o=Tc(t);if(!t.trim()||o===null||o<qn){let s=Te({prefix:" examples: ",wordList:Bi,minLengthForHints:0,inputString:t});return $({message:Ae(`provide duration above ${qn}ms. current duration: ${r}ms.`)+s,completionWordList:Bi})}return K(ae)}default:return $({message:Ae("Unknown config option"),completionWordList:n})}},_h=({modifier:e,inputString:t})=>{let n=xe(v.EDIT);if(!n.length)return $({message:Ae("Command not available in this context")});if(!n.includes(e)){let r=Te({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return $({message:r||Ae("Unknown edit option"),completionWordList:n})}switch(e){case Ze.COMMENT:return t.trim()?K(ae):$({message:Q("write a comment...")});case Ze.TITLE:return K(ae);case Ze.DESCRIPTION:{let{preferredEditor:r}=ye();return r?K(Q("<ENTER> to edit in ")+r):$({message:"No editor selected"})}default:return $({message:Ae("Unknown edit option"),completionWordList:n})}},Uh=({modifier:e})=>{let t=xe(v.YANK);return t.length?t.includes(e)?K(ae+Q(" and copy to clipboard")):$({message:Te({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):$({message:Ae("Nothing selected to copy from")})},$h={[v.EXPORT]:()=>K(ae+Q(", and create export markdown file")),[v.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return K(ae);let n={message:Q("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=wn(r);if(!r||!o)return $(n);let s=gl(o,"peek");return s||K(ae)},[v.REPLAY]:e=>{let{dateInput:t,durationInput:n}=ss(e.modifier,e.inputString),r={message:Q("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=wn(t);if(!t||!o)return $(r);let s=gl(o,"replay");return s||(n&&os(n)===null?$({message:Ae("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):K("<ENTER> to replay board history",n?qc:[]))},[v.EXIT]:()=>K(ae+Q(" and exit the application")),[v.INIT]:()=>K(ae),[v.OPEN]:Bh,[v.PALETTE]:()=>K(ae),[v.FILTER]:e=>{if(e.modifier==="clear")return K(ae);let t=s=>xe(v.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return $({message:Te({wordList:xe(v.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:xe(v.FILTER)});let n=Object.values(g().tags).map(s=>s.name),r=Object.values(g().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?$({message:Te({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):K():$({message:Te({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[v.NONE]:e=>{let t=xe(v.NONE);return $({message:Te({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[v.NEW]:e=>Fh({list:xe(v.NEW),hint:Te({wordList:xe(v.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[v.HELP]:()=>K(ae),[v.EDIT]:_h,[v.COMMENT]:e=>{let t=Ln({hint:Q(`write a comment (max ${4e3} char)...`),onOk:Q(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===rn.Invalid?t:e.inputString.length>4e3?K(Ae("max input exceeded")):t},[v.CONFIG]:Oh,[v.YANK]:Uh,[v.DELETE]:e=>{let t=pl();return t.validity==="invalid"?t:zi(e)},[v.CLOSE_ISSUE]:e=>zi(e),[v.RE_OPEN_ISSUE]:e=>zi(e),[v.MOVE]:e=>{let t=pl();return t.validity==="invalid"?t:Ln({hint:Te({prefix:"hey hacker! These commands are blocked for you... ",wordList:xe(v.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[v.TAG]:e=>{let n=x.getExistingTags().slice(0,10).map(ps).join("");return Ln({hint:n.length?Q("create tag or reuse:")+n+Q(""):Q("create tag ...")})(e)},[v.UNTAG]:e=>{let t=ns();if(a(t))return $({message:Ae("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(ps).slice(0,10);return n.length?Ln({hint:Q(" ... ")+n.join("")})(e):$({message:Ae("Issue has no tags"),completionWordList:[]})},[v.ASSIGN]:e=>{let t=x.getExistingAssignees().map(ps).slice(0,10);return Ln({hint:Q("assignees... ")+t.join("")})(e)},[v.UNASSIGN]:e=>{let t=rs();if(a(t))return $({message:Ae("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(ps).slice(0,10);return n.length?Ln({hint:Q("remove assignee... ")+n.join("")})(e):$({message:Ae("Issue has no assignees"),completionWordList:[]})},[v.SYNC]:()=>K(ae),[v.COFFEE]:e=>{let{modifier:t}=e,n=xe(v.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?$({message:Q("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):Ln({hint:Te({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},hl=Object.fromEntries(Object.entries($h).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]))});var gs,yl=y(()=>{"use strict";gs=["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 jh,Hh,Wh,Gh,qh,bl,xl,Il,El=y(()=>{"use strict";C();k();yl();jh=3,Hh=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"]),Wh=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},Gh=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=jh&&!Hh.has(t)&&!/^\d+$/.test(t)),qh=e=>{let t=new Map;for(let s of Wh(e))for(let d of Gh(s))t.set(d,(t.get(d)??0)+1);let n=[...t.entries()].sort((s,d)=>d[1]-s[1]||s[0].localeCompare(d[0])).map(([s])=>s),r=new Set(n),o=gs.filter(s=>!r.has(s));return[...n,...o]},bl=gs,xl=-1,Il=()=>{let e=je();if(a(e))return gs;let t=e.value,n=t.eventLog.length;return n!==xl&&(bl=qh(t),xl=n),bl}});var Rl,Nl,Yi=y(()=>{"use strict";id();nn();Tn();vl();El();k();ce();Rl=e=>Object.values(v).includes(e),Nl=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:d,validity:l,completionWordList:u}=hl[n].validate(n,r,s),m=n!==v.PEEK&&n!==v.REPLAY,p=o==="command"||o==="modifier"?xe(n):m?Il():[],{mode:f}=g(),I=f===h.COMMAND_LINE?d??"":"",N=[...u,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:I,autoCompletion:t?sd(e,N):{hint:"",hints:[],remainder:"",overlap:0}}}});var Sl,Vh,Kh,zh,Cl=y(()=>{"use strict";Yi();nn();Sl=e=>{let t=e.trimStart(),n=Kh(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),d=zh(e),l=Rl(r)?r:null,u=l!==null,m=r!=="",p=l?xe(l)??[]:[],f=l&&p.includes(o)?o:"",I="word";n.length===0||n.length===1&&!s?I="command":(n.length===1&&s||n.length===2&&!s)&&(I="modifier");let N=s?"":d,A=Vh(t,l,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:I,inputToMatch:N,inputString:A}},Vh=(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},Kh=e=>e.trim()?e.trim().split(/\s+/):[],zh=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as FC}from"react";var Jn,Xi,Qn,Yh,Al,Tt,Xr,Ji,Qi,Tl,wl,fs,Ml,G,kl,Ll,Pl,ie,hs,Ie=y(()=>{"use strict";Yi();Cl();C();ms();Jn=e=>e===Xi||e===":",Xi=" ",Qn={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:rn.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Yh=new Set,Al=()=>{for(let e of Yh)e()},Tt=e=>{let n=e(Qn),r=Sl(n.value),o=n.cursorPosition===n.value.length;Qn={...n,commandMeta:Nl(r,o)},Al()},Xr=({message:e,status:t})=>{let n=structuredClone(Qn);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Qn=n,Al(),c(e,null)},Ji=e=>{Tt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Qi=e=>{Tt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Jn(n[o-1]);)o--;for(;o>0&&!Jn(n[o-1]);)o--}else{for(;o<n.length&&!Jn(n[o]);)o++;for(;o<n.length&&Jn(n[o]);)o++}return{...t,cursorPosition:o}})},Tl=()=>{Tt(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},wl=()=>{Tt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Jn(t[r-1]);)r--;for(;r>0&&!Jn(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},fs=e=>{Tt(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),d=s+o,l=Math.max(0,Math.min(s.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},Ml=()=>{Tt(e=>({...e,commandIsPending:!0}))},G=e=>{Tt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},kl=({addToHistory:e=!0})=>{Tt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Ll=()=>{Tt(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Pl=()=>{Tt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ie=()=>Qn,hs=()=>{let[e,...t]=Qn.value.split(Xi);return t.join(Xi).trim()}});var P,fn=y(()=>{"use strict";ce();Qa();k();Ie();Oe();P={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"}});var Dl,F,Zi=y(()=>{"use strict";k();Tn();Dl=e=>{let{context:t}=g().contextNode;if(!t)return F.None;switch(e){case v.EXIT:return F.Exit;case v.EXPORT:return F.Export;case v.COFFEE:return F.Coffee;case v.INIT:return F.Init;case v.OPEN:return F.OpenProject;case v.DELETE:return F.Delete;case v.EDIT:return F.Edit;case v.COMMENT:return F.Comment;case v.HELP:return F.ViewHelp;case v.RE_OPEN_ISSUE:return F.ReopenIssue;case v.CLOSE_ISSUE:return F.CloseIssue;case v.TAG:return F.TagTicket;case v.UNTAG:return F.UntagTicket;case v.ASSIGN:return F.AssignUserToTicket;case v.UNASSIGN:return F.UnassignUserFromTicket;case v.NEW:return F.NewItem;case v.FILTER:return F.Filter;case v.MOVE:return F.Move;case v.PEEK:return F.Peek;case v.REPLAY:return F.Replay;case v.CONFIG:return F.Config;case v.YANK:return F.Yank;case v.SYNC:return F.Sync;default:return F.None}},F={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",Coffee:"coffee"}});import{Text as Fl}from"ink";import Bl,{useEffect as Ol,useState as Xh}from"react";var _l,Ge,Zn=y(()=>{"use strict";k();Pe();_l={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ge=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=qe(),r=_l[n]??_l.default,[o,s]=Xh(0);if(Ol(()=>{s(0)},[r]),Ol(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return Bl.createElement(Fl,null,t);let d=r[o]??r[0]??t;return Bl.createElement(Fl,{color:S.accent,dimColor:o===1},d)}});import{Box as ea,Text as Jh}from"ink";import vs from"react";var Qh,on,Jr=y(()=>{"use strict";Pe();Qh=(e,t,n,r)=>{let o=u=>Math.max(1,e[u]??1),s=n,d=n+1,l=o(n);for(;d<t&&l+o(d)<=r;)l+=o(d),d++;for(;s>0&&l+o(s-1)<=r;)s--,l+=o(s);return{start:s,end:d}},on=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let d=Math.max(1,Math.floor(t)),l=Math.max(1,Math.ceil(r)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(1,Math.floor(d/l)),p=Math.max(0,e.length-m),{start:f,end:I}=o?Qh(o,e.length,u,d):s?{start:Math.min(p,Math.max(0,u-m+1)),end:Math.min(p,Math.max(0,u-m+1))+m}:{start:Math.min(p,Math.floor(u/m)*m),end:Math.min(p,Math.floor(u/m)*m)+m},N=Math.max(1,I-f),A=e.slice(f,I),w=e.length>N,T=d,M=w?Math.max(1,Math.floor(N/e.length*T)):T,U=Math.max(0,T-M),ee=Math.max(1,e.length-N),ve=w?Math.floor(f/ee*U):0;return vs.createElement(ea,{flexDirection:"row",height:d,width:"100%"},vs.createElement(ea,{flexDirection:"column",flexGrow:1,height:d},A),vs.createElement(ea,{flexDirection:"column",width:1,height:T},Array.from({length:T}).map((X,W)=>vs.createElement(Jh,{key:W,color:w&&W>=ve&&W<ve+M?S.accent:S.secondary},w?"\u2502":" "))))}});var Ul,ta,Zh,ys,na=y(()=>{"use strict";k();Zh=()=>{let{eventLog:e=[]}=g();if(ta&&Ul===e)return ta;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Ul=e,ta=t,t},ys=e=>Zh().has(e)});import{Text as ev}from"ink";import tv from"react";var nv,rv,er,bs=y(()=>{"use strict";ts();At();me();na();Vt();nv=e=>e.toLowerCase().trim(),rv=(e,t=Kn)=>{let n=nv(e);return t[n]?t[n]:zr(n)},er=({id:e,isSelected:t,maxWidth:n})=>{let r=x.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:bt(o,n);return tv.createElement(ev,{underline:t,color:rv(o)},"@"+s,ys(e)?"":"\u2197")}});import{Text as ov}from"ink";import sv from"react";var xs,ra=y(()=>{"use strict";me();Pe();At();Vt();xs=({id:e,isSelected:t,maxWidth:n})=>{let r=x.getTag(e);if(!r)return;let o=n===void 0?r.name:bt(r.name,n);return sv.createElement(ov,{underline:t,backgroundColor:De(r.name),color:S.secondary}," "+o+" ")}});import{useEffect as iv,useState as av}from"react";var dv,$l,Is,Qr,cv,lv,tr,Es=y(()=>{"use strict";At();dv=80,$l=1400,Is=new Set,Qr=null,cv=e=>(Is.add(e),Qr||(Qr=setInterval(()=>{for(let t of Is)t()},dv)),()=>{Is.delete(e),Is.size===0&&Qr&&(clearInterval(Qr),Qr=null)}),lv=()=>{let e=Date.now()%$l/$l;return e<.5?e*2:(1-e)*2},tr=e=>{let[,t]=av(0);return iv(()=>{if(e)return cv(()=>t(n=>n+1))},[e]),ll(lv())}});import{Box as nr,Text as rr}from"ink";import Ve from"react";var uv,jl,mv,pv,Wl,Gl=y(()=>{"use strict";me();Pe();Vt();na();Yt();jr();bs();ra();Es();uv=(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),bt(e.slice(o).trim(),n)]},jl=3,mv=2,pv=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let d=e.length-o-1,l=d>0?String(d).length+1:0;if(r+s.width+l>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},Wl=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=tr(r),s=e-4,d=s-7-1,[l,u]=uv(Me(t.title),d,s),m=u?null:bt(Me(t.props.description),s)||null,p=en(t),f=tn(t).map(M=>({...M,name:M.name})),I=Math.max(1,s-jl),N=x.getCommentsByIssue(t.id),A=N.length?String(N.length).length+2+1:0,{shown:w,hidden:T}=pv([...p.map(M=>({id:M.id,isTag:!0,width:Math.min(M.name.length,I)+jl})),...f.map(M=>({id:M.id,isTag:!1,width:Math.min(M.name.length,I)+mv+(ys(M.id)?0:1)}))],s-A);return Ve.createElement(nr,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?S.accent:S.secondary,justifyContent:"space-between"},Ve.createElement(nr,{paddingLeft:1,paddingRight:1,flexDirection:"column"},Ve.createElement(nr,{justifyContent:"space-between"},Ve.createElement(rr,{color:S.primary},l),Ve.createElement(rr,{color:S.secondary2,dimColor:!0},V(t.id))),u&&Ve.createElement(rr,{color:S.primary},u),m&&Ve.createElement(rr,{color:S.secondary2,dimColor:!0},m)),Ve.createElement(nr,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},Ve.createElement(nr,{flexDirection:"row"},w.map(M=>Ve.createElement(nr,{paddingRight:1,key:M.id},M.isTag?Ve.createElement(xs,{id:M.id,maxWidth:I}):Ve.createElement(er,{id:M.id,maxWidth:I}))),T>0&&Ve.createElement(rr,{color:S.secondary2,dimColor:!0},"+",T)),N.length>0&&Ve.createElement(rr,{color:S.accent},"[",N.length,"]")))}});import{Box as Pn,Text as Zr}from"ink";import et from"react";var gv,ql,Vl=y(()=>{"use strict";ce();me();Pe();At();Zn();Es();gv=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,ql=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:d})=>{let l=tr(s),u=(r.props.tags??[]).map(X=>x.getTag(X)).filter(X=>!!X),m=(r.props.assignees??[]).map(X=>x.getContributor(X)).map(X=>X&&{...X,name:X.name}).filter(X=>!!X),p=1,f=u.length*(1+p),I=m.length*(2+p),N=u.map(X=>et.createElement(Pn,{key:X.id,paddingRight:p},et.createElement(Zr,{color:De(X.name)},"\u25A0"))),A=m.map(X=>et.createElement(Pn,{key:X.id,paddingRight:p},et.createElement(Zr,{color:zr(X.name)},"@"+X.name.at(0)))),w=s?l:o?S.accent:d===h.MOVE?S.secondary:S.primary,T=x.getCommentsByIssue(r.id),M=T.length?String(T.length).length+2+p:0,U=T.length?et.createElement(Pn,{paddingRight:p},et.createElement(Zr,{color:S.accent},"[",T.length,"]")):null,ee=f+I+M,ve=Math.max(1,n-t-ee-(ee>0?1:0));return et.createElement(Pn,{justifyContent:"space-between"},et.createElement(Pn,null,et.createElement(Pn,{width:t},o?et.createElement(Ge,{isSelected:!0}):et.createElement(Zr,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),et.createElement(Zr,{wrap:"truncate",color:w},gv(r.title,ve))),et.createElement(Pn,null,N,A,U))}});import fv from"chalk";import{Box as oa,Text as hv}from"ink";import wt from"react";var vv,Kl,zl=y(()=>{"use strict";ge();k();Pe();Zn();Jr();Gl();Vl();Es();vv=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u,replay:m}=qe(),p=u[e.id]??[],f=m?new Set(m.flashNodeIds):null,I=f?.has(e.id)??!1,N=tr(I),A=`${e.title} ${fv.hex(S.secondary2).dim("("+p.length+")")}`,w=3,T=o?1:5,M=s&&d===-1,U=n-3-(o?1:0)-(M?2:0),ee=Math.max(2,String(p.length).length+1),ve=r-w-1,X=wt.createElement(oa,{borderStyle:"round",borderColor:S.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},wt.createElement(Ge,{isSelected:t}),wt.createElement(hv,{bold:!0,color:I?N:t?S.accent:S.primary},A," ",e.readonly?"\u{1F512}":"")),W=(q,mn)=>{let pn=s&&d===mn;if(!L(q))return null;let dr=f?.has(q.id)??!1;return o?wt.createElement(ql,{key:q.id,index:mn,labelWidth:ee,width:U,ticket:q,isSelected:pn,isFlashing:dr,mode:l}):wt.createElement(Wl,{key:q.id,width:U,ticket:q,isSelected:pn,isFlashing:dr})};return wt.createElement(oa,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?S.accent:S.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},X,wt.createElement(oa,null,p.length>0&&wt.createElement(on,{selectedIndex:d,height:ve,itemHeight:T},p.map(W)),M&&wt.createElement(Ge,{isSelected:!0})))},Kl=wt.memo(vv)});var Yl,Xl,sa=y(()=>{"use strict";xn();Yl=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},Xl=(e,t,n)=>Se.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0})});var or,Rs=y(()=>{"use strict";or=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"}});import{Box as sr,Text as $t}from"ink";import Fe,{useEffect as yv,useMemo as bv,useRef as xv}from"react";import{decodeTime as Jl}from"ulid";function Zl({ticket:e,width:t,height:n}){let r=bv(()=>Ev(e),[e]),o=xv([]);yv(()=>(Ql(o.current),o.current=Nv(e,r),()=>{Ql(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=qe(),l=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?Fe.createElement(sr,{flexDirection:"column",width:t,height:n,padding:1},Fe.createElement($t,{color:S.primary},"No attachments yet."),Fe.createElement(sr,{paddingTop:1},Fe.createElement($t,{color:S.primary},"Attach images from the browser GUI"),Fe.createElement($t,{color:S.accent}," epiq gui "),Fe.createElement($t,{color:S.primary},"by dropping or pasting them."))):Fe.createElement(sr,{flexDirection:"column",width:t,height:n},Fe.createElement(sr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:S.secondary,borderStyle:"single",paddingBottom:1},Fe.createElement($t,{color:S.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),Fe.createElement(on,{height:l,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,I=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return Fe.createElement(sr,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},Fe.createElement($t,{color:S.accent},f?"\u276F ":" "),Fe.createElement(sr,{paddingLeft:1},Fe.createElement($t,{color:S.secondary2},`#${p+1} `),Fe.createElement($t,{color:f?S.accent:S.primary},I),Fe.createElement($t,{color:S.secondary2}," "+Sv(m.bytes)+" "+or(vt(m.id)))))})))}var Iv,Ev,Ql,Rv,Nv,Sv,eu=y(()=>{"use strict";Qe();it();Rs();ge();C();me();xn();k();Pe();Yn();Jr();Iv=e=>Ce(e,"attachments"),Ev=e=>x.getAttachmentsByIssue(e.id).sort((t,n)=>Jl(t.id)-Jl(n.id)),Ql=e=>{for(let t of e)x.deleteNode(t.id)},Rv=(e,t,n)=>Se.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),Nv=(e,t)=>{let n=x.getNode(Iv(e.id));if(!n||!ze(n))return[];let r=t.map((o,s)=>Rv(o,s,n.id)).map(o=>x.createNode(o)).filter(ft).map(({value:o})=>o).filter(ze);return t.length>0&&g().selectedIndex<0&&_.navigate({contextNode:n,selectedIndex:0}),r},Sv=e=>`${Math.max(1,Math.round(e/1024))} KB`});var nu,ia,tu,aa,ru,ou,Cv,su,Av,da,iu=y(()=>{"use strict";nu=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,ia=e=>e.replace(nu,""),tu=e=>e==="additions"||e==="deletions",aa=e=>{let t=nu.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"||!tu(r.side)||!tu(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r},ru=/```\n([\s\S]*?)\n?```\s*$/,ou=e=>ru.exec(e)?.[1]??null,Cv=/`[^`\n]+`[^\n]*\n?$/,su=e=>ia(e).replace(ru,"").replace(Cv,"").trim(),Av=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})`},da=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${Av(e)}`});var Tv,eo,wv,Mv,kv,Lv,du,ca,cu,au,lu,la=y(()=>{"use strict";iu();Tv=(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 d of r){let l=d;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},eo=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)},wv=/!\[([^\]]*)\]\([^)]*\)/g,Mv=e=>e.replace(wv,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),kv=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),Lv=4,du=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(Lv)),ca=e=>{let t=!1;return e.map(du).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=aa(n);if(r)return{kind:"caption",text:da(r)};let o=Mv(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:eo(s[1]??"")}:{kind:"text",spans:eo(o)}})},cu=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],au=(e,t)=>{let n=[];for(let r of ca(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 cu(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of Tv(kv(r.spans),t))n.push({kind:r.kind,spans:eo(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},lu=(e,t)=>{let n=aa(e),r=n?ou(e):null;if(!n||r===null)return au(ia(e).split(`
|
|
54
|
-
|
|
55
|
-
`).map(du),d=n.side===n.endSide?n.start:void 0,l=d===void 0?0:String(d+s.length-1).length+3;return[...o?[...au(o.split(`
|
|
56
|
-
`),t),{kind:"blank"}]:[],{kind:"caption",text:da(n)},...s.flatMap((u,m)=>cu(u,Math.max(1,t-l)).map((p,f)=>({kind:"code",text:p,number:d===void 0||f>0?void 0:d+m})))]}});import{Box as uu,Text as Dn}from"ink";import st from"react";var mu,ua,pu,ma=y(()=>{"use strict";Pe();mu=({spans:e,bold:t})=>st.createElement(Dn,{color:S.primary,bold:t},e.map((n,r)=>n.code?st.createElement(Dn,{key:r,color:S.yellow},n.text):st.createElement(Dn,{key:r},n.text))),ua=({line:e,width:t,gutter:n=0})=>{switch(e.kind){case"blank":return st.createElement(Dn,null," ");case"fence":return st.createElement(Dn,{color:S.secondary2},"```");case"caption":return st.createElement(Dn,{color:S.accent},e.text);case"heading":return st.createElement(mu,{spans:e.spans,bold:!0});case"text":return st.createElement(mu,{spans:e.spans});case"code":{let r=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return st.createElement(Dn,{backgroundColor:S.secondary,color:S.primary},r,e.text.padEnd(Math.max(0,t-r.length)))}}},pu=({lines:e,width:t})=>{let n=e.flatMap(o=>o.kind==="code"&&o.number!==void 0?[o.number]:[]),r=n.length>0?String(Math.max(...n)).length+3:0;return st.createElement(uu,{flexDirection:"column"},e.map((o,s)=>st.createElement(uu,{key:s},st.createElement(ua,{line:o,width:t,gutter:r}))))}});import{Box as sn,Text as an}from"ink";import Re,{useEffect as Pv,useMemo as gu,useRef as Dv}from"react";import{decodeTime as fu}from"ulid";function vu({ticket:e,width:t,height:n}){let r=gu(()=>Ov(e),[e]),o=Dv([]);Pv(()=>(hu(o.current),o.current=_v(e,r),()=>{hu(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=qe(),l=Math.max(1,n-4),u=Math.max(20,t-8),m=gu(()=>r.map(f=>{let I=lu(f.md,u);return I.length>0?I:[{kind:"blank"}]}),[r,u]),p=m.map(f=>f.length+Fv);return r.length===0?Re.createElement(sn,{flexDirection:"column",width:t,height:n,padding:1},Re.createElement(an,{color:S.primary},"No comments yet."),Re.createElement(sn,{paddingTop:1},Re.createElement(an,{color:S.primary},"Use"),Re.createElement(an,{color:S.accent}," :comment "),Re.createElement(an,{color:S.primary},"to add the first one."))):Re.createElement(sn,{flexDirection:"column",width:t,height:n},Re.createElement(sn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:S.secondary,borderStyle:"single",paddingBottom:1},Re.createElement(an,{color:S.secondary2},"Comments (",r.length,") ")),Re.createElement(on,{height:l,itemHeights:p,selectedIndex:s},r.map((f,I)=>{let N=I===s;return Re.createElement(sn,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:S.secondary,borderStyle:"single"},Re.createElement(sn,{flexDirection:"row",paddingBottom:1},Re.createElement(an,{color:S.accent},N?"\u276F ":" "),Re.createElement(sn,{paddingLeft:1},Re.createElement(an,{color:S.secondary2},`#${I+1} `),Re.createElement(er,{id:f.authorId}),Re.createElement(an,{color:S.secondary2}," "+or(vt(f.id))))),Re.createElement(sn,{paddingLeft:3,paddingBottom:1},Re.createElement(pu,{lines:m[I]??[],width:u})))})))}var Fv,Bv,Ov,hu,_v,yu=y(()=>{"use strict";Qe();it();Rs();ge();C();me();k();Pe();Yn();bs();Jr();sa();la();ma();Fv=4,Bv=e=>Ce(e,"comments"),Ov=e=>x.getCommentsByIssue(e.id).sort((t,n)=>fu(t.id)-fu(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),hu=e=>{for(let t of e)x.deleteNode(t.id)},_v=(e,t)=>{let n=x.getNode(Bv(e.id));if(!n||!ze(n))return[];let r=t.map((o,s)=>Xl(o,s,n.id)).map(x.createNode).filter(ft).map(({value:o})=>o).filter(fr);return t.length>0&&g().selectedIndex<0&&_.navigate({contextNode:n,selectedIndex:0}),r}});import{Box as Ns,Text as Uv}from"ink";import jt from"react";var bu,xu=y(()=>{"use strict";ge();me();Hn();k();Pe();bs();Zn();ra();bu=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=qe(),{title:o}=t,s=t.parentNodeId?x.getNode(t.parentNodeId):void 0,d=s&&L(s)?o===re.ASSIGNEES?s.props.assignees??[]:o===re.TAGS?(s.props.tags??[]).filter(l=>x.getTag(l)):[]:[];return jt.createElement(Ns,{alignItems:"center",paddingTop:1},jt.createElement(Ns,{minWidth:12},jt.createElement(Ge,{isSelected:n}),jt.createElement(Uv,{color:n?S.accent:S.secondary2},o,":")),jt.createElement(Ns,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=r.id===t.id&&u===e;return jt.createElement(Ns,{key:`${o}-${l}`,paddingRight:2,minHeight:1},jt.createElement(Ge,{isSelected:m}),o===re.ASSIGNEES?jt.createElement(er,{isSelected:m,id:l}):o===re.TAGS?jt.createElement(xs,{isSelected:m,id:l}):null)})))}});import{Box as to,Text as pa}from"ink";import gt,{useEffect as $v,useMemo as ga}from"react";var jv,Iu,fa,Eu,Hv,ha,Ru=y(()=>{"use strict";me();C();xn();k();Pe();Vt();Zn();Jr();ma();la();$n();jv="\u2029",Iu=(e,t)=>`${e}::inline-line::${t}`,fa=new Map,Eu=e=>{let t=fa.get(e)??[];fa.delete(e);for(let n of t)x.deleteNode(n)},Hv=(e,t)=>{Eu(e);let n=[];t.forEach((r,o)=>{let s=Ye(BigInt(o+1));if(!ft(s))return;let d=x.createNode(Se.text({id:Iu(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));ft(d)&&n.push(d.value.id)}),fa.set(e,n)},ha=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:d,contextNode:l}=qe(),u=ga(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=ga(()=>u.join("\0"),[u]);$v(()=>(Hv(e,u),()=>{Eu(e)}),[e,m]);let p=s-10,I=ga(()=>ca(u).map(N=>{if(N.kind==="code")return{...N,text:bt(N.text,p)};if(N.kind==="text"||N.kind==="heading"){let A=N.spans.map(w=>w.code?`\`${w.text}\``:w.text).join("");return{...N,spans:eo(bt(A,p))}}return N}),[u,p]).map((N,A)=>{let w=l.id===e&&d===A;return gt.createElement(to,{key:Iu(e,A)},gt.createElement(pa,{color:w?S.primary:S.secondary2,dimColor:!w},`${A+1} `.padStart(5,"\xA0")),N.kind==="blank"?gt.createElement(pa,{backgroundColor:w?"gray":void 0},jv):gt.createElement(to,null,gt.createElement(ua,{line:N,width:N.kind==="code"?p:0})))});return gt.createElement(to,{flexDirection:"column",paddingTop:1},gt.createElement(to,null,gt.createElement(Ge,{isSelected:o}),gt.createElement(pa,{color:o?S.accent:S.secondary2},t)),gt.createElement(to,{flexDirection:"row",borderStyle:"round",borderColor:S.secondary,paddingLeft:1,marginLeft:1},gt.createElement(on,{scrollByOne:!0,height:r-3,selectedIndex:d,itemHeight:1},I)))}});import{Box as Fn,Text as va}from"ink";import we,{useMemo as no}from"react";var Wv,Gv,qv,Vv,Nu,Su=y(()=>{"use strict";ge();me();k();Pe();sa();Yn();eu();yu();Zn();xu();Ru();Wv=e=>Ce(e,"description"),Gv=e=>Ce(e,"comments"),qv=e=>Ce(e,"history"),Vv=e=>Ce(e,"attachments"),Nu=({ticket:e,height:t})=>{let n=no(()=>Yl(e),[e]),{selectedIndex:r,contextNode:o}=qe(),s=process.stdout.columns||120,d=no(()=>Wv(e.id),[e.id]),l=no(()=>Gv(e.id),[e.id]),u=no(()=>qv(e.id),[e.id]),m=no(()=>Vv(e.id),[e.id]),p=x.getAttachmentsByIssue(e.id).length,f=o.id===e.id,I=o.id===l||o.parentNodeId===l,N=o.id===u||o.parentNodeId===u,A=o.id===m||o.parentNodeId===m,w=se(e.id);if(I){let q=t-3;return we.createElement(Fn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},we.createElement(vu,{ticket:e,width:s,height:q}))}if(A){let q=t-3;return we.createElement(Fn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},we.createElement(Zl,{ticket:e,width:s,height:q}))}if(N){let W=x.getNode(u),q=W&&ze(W)?W.props.value??"":"",pn=t-3;return we.createElement(Fn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},W?we.createElement(ha,{id:W.id,label:"Event log",text:q,selected:!1,maxWidth:s,height:pn}):null)}let T=w.reduce((W,q)=>gr(q)||q.id===l||q.id===m||q.id===u?W+1:W,0),M=2,U=3,ee=T,ve=t-U-ee-M,X=(W,q)=>W.id===d?we.createElement(ha,{key:W.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:q,maxWidth:s,height:ve}):gr(W)?we.createElement(bu,{key:W.id,parent:W,selected:q,selectedIndex:r}):W.id===l?we.createElement(Fn,{key:W.id,paddingTop:1},we.createElement(Ge,{isSelected:q}),we.createElement(va,{backgroundColor:S.secondary,color:q?S.accent:S.primary},` Comments (${n}) \u203A\u203A `)):W.id===m?we.createElement(Fn,{key:W.id,paddingTop:1},we.createElement(Ge,{isSelected:q}),we.createElement(va,{backgroundColor:S.secondary,color:q?S.accent:S.primary},` Attachments (${p}) \u203A\u203A `)):W.id===u?we.createElement(Fn,{key:W.id,paddingTop:1},we.createElement(Ge,{isSelected:q}),we.createElement(va,{backgroundColor:S.secondary,color:q?S.accent:S.primary}," History \u203A\u203A ")):null;return we.createElement(Fn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},w.map((W,q)=>X(W,f&&r===q)))}});import{Box as Kv}from"ink";import Ss from"react";var zv,Cu,Au=y(()=>{"use strict";ge();zl();Su();zv=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:d,width:l})=>{let u=t.context,m=u===O.TICKET||u===O.FIELD_LIST||u===O.FIELD,p=u===O.BOARD||u===O.SWIMLANE,f=u===O.TICKET?t:r.find(T=>T.context===O.TICKET),I=Math.floor(l/3),N=Math.floor(l/Math.max(e.length,1)),A=Math.min(N,I),w=s==="dense";return Ss.createElement(Kv,{flexDirection:"row",height:d},p&&e.map((T,M)=>{let U=t.id===T.id,ee=U?n:-1,ve=t.context===O.BOARD&&n===M;return Ss.createElement(Kl,{key:T.id,height:d,width:A,swimlane:T,isSelected:ve,isDense:w,isFocused:U,listSelectedIndex:ee,mode:o})}),m&&f&&Ss.createElement(Nu,{height:d,ticket:f}))},Cu=Ss.memo(zv)});import Tu from"node:fs";import Yv from"node:path";import Xv from"react";import{render as Jv}from"ink";import{Writable as Qv}from"node:stream";var ro,Zv,ey,ty,ny,wu,Mu=y(()=>{"use strict";Au();ge();C();k();ue();Oe();ro=e=>String(e).padStart(2,"0"),Zv=e=>{let t=e.getUTCFullYear(),n=ro(e.getUTCMonth()+1),r=ro(e.getUTCDate()),o=ro(e.getUTCHours()),s=ro(e.getUTCMinutes()),d=ro(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${d}`},ey=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",ty=async(e,{width:t,height:n})=>{let r="",o=new Qv({write(d,l,u){let m=ny(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=Jv(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),r},ny=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),wu=async()=>{let{viewMode:e}=ye(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=g(),d=r.find(M=>M.context==="BOARD");if(!d)return i("No board found to export");let l=120,u=40,m=await ty(Xv.createElement(Cu,{height:u,width:l,swimlanes:(s[d.id]??[]).filter(M=>M!==void 0&&gn(M)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:u});if(!m)return i("Failed to render board export");let p=Lo(process.cwd());if(a(p))return i("Unable to export, epiq root not found");let f=new Date,I=Zv(f),N=`board_${ey(d.title)}_${I}.md`,A=Md(p.value);Tu.mkdirSync(A,{recursive:!0});let w=Yv.join(A,N),T=`# Board - ${d.title}
|
|
25
|
+
`)}`):(An(o),Pf(),E({hasProjectDefinition:!0}),Ff(t),c("State booted successfully",null))}var Br,Df,Ff,_r=y(()=>{"use strict";Nt();Ze();ue();C();Sn();k();Gn();Ut();zn();Br=kf();Df=()=>{let e=Ge();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},Ff=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(", ");X.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(", ");X.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}}});import{WebSocket as Of}from"ws";var Bf,vc,yc=y(()=>{"use strict";Bf=new Set,vc=e=>{let t=JSON.stringify(e);for(let n of Bf)n.readyState===Of.OPEN&&n.send(t)}});var Jo,Qo,Zo,ki,bc,Pe,es=y(()=>{"use strict";yc();C();k();Jo=e=>{At()&&(E({syncStatus:e}),vc({type:"sync-status",payload:e}))},Qo=(e="Syncing...")=>{Jo({status:"syncing",msg:e})},Zo=(e="Synced")=>{Jo({status:"synced",msg:e})},ki=e=>{Jo({status:"failed",msg:e})},bc=e=>{Jo({status:"offline",msg:e})},Pe=e=>(ki(e),i(e))});var Ur,Z,ts=y(()=>{"use strict";C();Ur=(e,t)=>(logger.error(`[boot:${e}] ${t}`),i(`[boot:${e}] ${t}`)),Z=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});import wt from"node:fs";import $r from"node:path";var Yn,xc,Ic,Ec,_f,Rc,Uf,$f,Nc,Li=y(()=>{"use strict";lt();C();pe();Yn=e=>e.split(`
|
|
26
|
+
`).filter(t=>t.trim().length>0),xc=e=>{let t=$r.join(e,He,Zt);try{if(!wt.existsSync(t))return c("No events directory",[]);let n=wt.readdirSync(t).filter(r=>r.endsWith(".jsonl")).filter(r=>Yn(wt.readFileSync($r.join(t,r),"utf8")).length>0);return c("Looked for stranded event logs",n)}catch(n){return i(`Unable to check ${t} for event logs before deleting it: ${n instanceof Error?n.message:String(n)}`)}},Ic=e=>$r.join(e,He,Zt),Ec=e=>{let t=Ic(e),n=new Map;try{if(!wt.existsSync(t))return n;for(let r of wt.readdirSync(t))r.endsWith(".jsonl")&&n.set(r,Yn(wt.readFileSync($r.join(t,r),"utf8")))}catch{return n}return n},_f=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},Rc=(e,t)=>{if(t.size===0)return[];let n=Ic(e),r=[];for(let[o,s]of t){if(s.length===0)continue;let d=$r.join(n,o);try{let l=wt.existsSync(d)?wt.readFileSync(d,"utf8"):null,u=new Set(l===null?[]:Yn(l)),m=s.filter(f=>!u.has(f)).filter(_f);if(m.length===0)continue;wt.mkdirSync(n,{recursive:!0});let p=l!==null&&l.length>0&&!l.endsWith(`
|
|
27
|
+
`);wt.appendFileSync(d,`${p?`
|
|
28
|
+
`:""}${m.join(`
|
|
29
|
+
`)}
|
|
30
|
+
`,"utf8"),r.push(`${o} (${m.length})`)}catch{continue}}return r},Uf=(e,t)=>{let n=new Set(Yn(t));return Yn(e).filter(r=>!n.has(r))},$f=(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(`
|
|
31
|
+
`),Nc=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let r=await je({args:["show",`HEAD:${t}`],cwd:e});if(r.exitCode!==0)return c("No committed log to compare against",void 0);let o=Uf(r.stdout,n);return o.length>0?i($f(t,o,Yn(r.stdout).length)):c("Event log only grew",void 0)}});import jt from"node:fs";import jr from"node:path";var jf,Cc,Sc,Hf,Pi,Di,Wf,Gf,Ln,qf,Vf,ns,Ac,Tc,wc,Hr,Mc,Wr=y(()=>{"use strict";C();Nt();Po();Sr();Li();mt();lt();jf="[epiq:init-repo]",Cc=async e=>{let t=await je({args:["rev-parse","--verify","--quiet","HEAD"],cwd:e});if(t.exitCode===0)return c("Initial commit already exists",!1);if(!(t.exitCode===1&&t.stdout.trim()===""&&t.stderr.trim()===""))return i(["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(`
|
|
32
|
+
`));X.info("Creating initial commit");let r=await H({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(a(r))return i(r.message);let o=await H({args:["commit-tree",r.value.stdout.trim(),"-m",jf],cwd:e});if(a(o))return i(o.message);let s=await H({args:["update-ref","HEAD",o.value.stdout.trim()],cwd:e});return a(s)?i(s.message):c("Created initial commit",!0)},Sc=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Hf=async e=>{let t=await Oo(e);if(a(t))return i(t.message);let n=await Nd(e);return a(n)?i(n.message):c("Built sync commit message",`[sync|branch:${Sc(t.value)}:sha:${Sc(n.value)}]`)},Pi=async({repoRoot:e,stateBranchName:t})=>{X.info(`Creating ${t}`);let n=await H({args:["commit-tree",kd,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return i(`Failed to create state branch commit
|
|
33
|
+
${n.message}`);let r=n.value.stdout.trim(),o=await H({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return a(o)?i(`Failed to create ${t}
|
|
34
|
+
${o.message}`):c("Created state branch",!0)},Di=async({repoRoot:e,stateBranchName:t})=>{let n=await Fo({repoRoot:e,branch:t});if(a(n))return i(`Ensure local state branch failed
|
|
35
|
+
`+n.message);if(n.value)return c("Local state branch already exists",!1);let r=await ai({repoRoot:e});if(a(r))return i(`Ensure local state branch failed
|
|
36
|
+
`+r.message);let o=r.value,s=o?await di({repoRoot:e,branch:t}):c("No remote, no remote state branch",!1);if(a(s))return i(`Ensure local state branch failed
|
|
37
|
+
`+s.message);let d=s.value;if(o&&d){let l=await ye.fetch({cwd:e,remote:ot,branch:t});if(a(l))return i(`Failed to fetch ${t} from remote
|
|
38
|
+
${l.message}`)}if(d){let l=await H({args:["branch","--track",t,`${ot}/${t}`],cwd:e});return a(l)?i(`Failed to create local ${t} from remote
|
|
39
|
+
${l.message}`):c("Created local state branch from remote",!0)}return Pi({repoRoot:e,stateBranchName:t})},Wf=async({repoRoot:e,branch:t})=>{let n=await H({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let r=n.value.stdout.split(`
|
|
40
|
+
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return c("Found worktree for branch",o)}return c("No worktree found for branch",null)},Gf=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Ar(jr.dirname(t));if(a(r))return i(`Failed to create state branch worktree
|
|
41
|
+
`+r.message);if(jt.existsSync(t)&&!jt.existsSync(jr.join(t,".git"))){let s=xc(t);if(a(s))return i(s.message);if(s.value.length>0)return i([`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(d=>` ${d}`),"","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(`
|
|
42
|
+
`));X.info("Removing broken state branch worktree path"),Fd(t)}X.info("Creating state branch worktree");let o=await ye.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(o)?i(`Failed to create state branch worktree
|
|
43
|
+
${o.message}`):c("Created state branch worktree",!0)},Ln=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await Wf({repoRoot:e,branch:n});if(a(r))return i(r.message);let o=Cr(t),s=r.value?Cr(r.value):null;if(s&&s===o&&jt.existsSync(s))return c("State branch already checked out in expected worktree",!1);if(s&&s!==o){let u=await Ad(s);if(a(u))return i(u.message);if(u.value)return i([`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(`
|
|
44
|
+
`));X.info("Moving state branch worktree to expected location");let m=await ye.worktreeRemove({cwd:e,worktreeRoot:s});if(a(m))return i(`Failed to remove existing state branch worktree
|
|
45
|
+
${m.message}`)}if(s&&!jt.existsSync(s)){X.info("Pruning stale state branch worktree");let u=await ye.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
|
|
46
|
+
${u.message}`)}let d=await Rd({repoRoot:e,worktreeRoot:t});if(a(d))return i(d.message);let l=jt.existsSync(t);if(d.value&&l)return c("State branch worktree already exists",!1);if(d.value&&!l){X.info("Pruning missing registered state branch worktree");let u=await ye.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
|
|
47
|
+
${u.message}`)}return Gf({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},qf=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Oo(e);if(a(n))return i(n.message);if(n.value===t)return c("State branch already checked out",!1);(await je({cwd:e,args:["rebase","--abort"]})).exitCode===0&&X.info("Aborted stale state branch rebase");let o=await ye.checkout({cwd:e,branch:t});return a(o)?i(`Failed to checkout ${t}
|
|
48
|
+
${o.message}`):c("Checked out state branch",!0)},Vf=async({repoRoot:e,stateBranchRoot:t})=>{let n=await ci(t);if(a(n))return i(n.message);if(n.value)return c("State branch upstream already configured",!1);let r=await ai({repoRoot:t});if(a(r))return i(r.message);if(!r.value)return c("No remote available for state branch upstream",!1);let o=Jt(e);if(a(o))return o;let s=o.value,d=await di({repoRoot:t,branch:s});if(a(d))return i(d.message);if(!d.value)return c("Remote state branch missing; upstream will be configured on first push",!1);X.info(`Configuring ${s} upstream`);let l=await ye.fetch({cwd:t,remote:ot,branch:s});if(a(l))return i(`Failed to fetch ${s}
|
|
49
|
+
${l.message}`);let u=await ye.setUpstream({cwd:t,branch:s,upstream:`${ot}/${s}`});return a(u)?i(`Failed to set state branch upstream
|
|
50
|
+
${u.message}`):c("Configured state branch upstream",!0)},ns=async({stateBranchRoot:e,eventFileName:t})=>{let n=Ld(t),r=jr.join(e,n);if(!jt.existsSync(r))return c("No event file to stage",null);let o=await Nc({stateBranchRoot:e,relativePath:n,workingContent:jt.readFileSync(r,"utf8")});if(a(o))return i(o.message);let s=await ye.stage({cwd:e,pathspec:[n]});return a(s)?i(`Failed to stage state branch event file
|
|
51
|
+
${s.message}`):c("Staged state branch event file",n)},Ac=async({stateBranchRoot:e})=>{let t=Pd(),n=jr.join(e,t);if(!jt.existsSync(n))return c("No media directory to stage",null);let r=await ye.stage({cwd:e,pathspec:[t],ignoreRemoval:!0});return a(r)?i(`Failed to stage state branch media files
|
|
52
|
+
${r.message}`):c("Staged state branch media files",t)},Tc=async({stateBranchRoot:e})=>{let t=pi();if(!jt.existsSync(jr.join(e,t)))return c("No event log attributes to stage",null);let n=await ye.stage({cwd:e,pathspec:[t]});return a(n)?i(`Failed to stage event log attributes
|
|
53
|
+
${n.message}`):c("Staged event log attributes",t)},wc=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let r=await Hf(e);return a(r)?i(`Create state branch sync commit failed
|
|
54
|
+
`+r.message):qn({cwd:t,message:r.value,pathspec:n})},Hr=async({repoRoot:e,stateBranchRoot:t})=>{let n=await ci(t);if(a(n))return i(n.message);let r=Jt(e);if(a(r))return r;let o=r.value,s=n.value?await ye.push({cwd:t}):await ye.push({cwd:t,remote:ot,branch:o,setUpstream:!0});if(a(s))return i(`Failed during state branch push
|
|
55
|
+
${s.message}`);let d=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return c(d?"Pushed state branch":"Remote already up to date",d)},Mc=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Jt(e);if(a(o))return o;let s=o.value,d=[_o(),await Di({repoRoot:e,stateBranchName:s}),await Ln({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await qf({stateBranchRoot:t,stateBranchName:s}),await Bd(t),n?await Vf({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of d){if(a(l))return i(l.message);r=r||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)}});import rs from"node:fs";import Oi from"node:os";import zf from"node:path";var Kf,kc,Yf,Xf,Jf,Pc,Fi,Lc,Qf,Dc,Fc=y(()=>{"use strict";C();lt();Nt();Kf="epiq-sync.lock",kc=600*1e3,Yf=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}},Xf=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Jf=e=>e&&(e.hostname!==Oi.hostname()||Xf(e.pid))?Date.now()-e.startedAt>kc:!0,Pc=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,Fi=e=>{try{return Yf(rs.readFileSync(e,"utf8"))}catch{return null}},Lc=(e,t)=>{let n={pid:process.pid,hostname:Oi.hostname(),startedAt:Date.now(),operation:t};try{return rs.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},Qf=async({worktreeRoot:e,operation:t})=>{let n=await ii(e);if(a(n))return i(n.message);let r=zf.join(n.value,Kf),o=()=>{try{let l=Fi(r);l&&l.pid===process.pid&&rs.rmSync(r)}catch{}};if(Lc(r,t))return c("Acquired sync lock",{acquired:!0,release:o});let s=Fi(r);if(!Jf(s))return c("Sync lock is held",{acquired:!1,heldBy:s});X.info(`Breaking an abandoned sync lock: ${s?Pc(s):"unreadable lock file"}`);try{rs.rmSync(r,{force:!0})}catch{}if(Lc(r,t))return c("Acquired sync lock after breaking a stale one",{acquired:!0,release:o});let d=Fi(r);return c("Sync lock taken by another process",{acquired:!1,heldBy:d??{pid:-1,hostname:Oi.hostname(),startedAt:Date.now(),operation:"unknown"}})},Dc=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await Qf({worktreeRoot:e,operation:t});if(a(r))return i(r.message);if(!r.value.acquired)return X.info(`Skipping ${t}: the state worktree is held by ${Pc(r.value.heldBy)}`),c("State worktree is held by another process",null);let{release:o}=r.value;try{return c("Ran under the sync lock",await n())}finally{o()}}});import Zf from"node:fs";var eh,th,Oc,Bc,nh,os,Bi=y(()=>{"use strict";C();es();ts();Sr();mt();lt();Wr();Li();Fc();eh=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=Z("getRepoRootDir",await ut(e));if(a(n))return i(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=Z("getStateBranchRoot",Ce({repoRoot:r}));if(a(o))return i(o.message);let s=o.value;logger.debug("[sync] state branch root",s),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let d=Z("bootstrapStateBranchStorage",await Mc({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(a(d))return i(d.message);logger.debug("[sync] bootstrap result",{bootstrapped:d.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let l=Z("hasInProgressGitOperation(stateBranchRoot)",await Do(s));if(a(l))return i(l.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:l.value}),l.value)return logger.info("[sync] state branch git operation in progress"),i("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let u=Z("ensureStateBranchLayout",Od(r,s));return a(u)?i(u.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:d.value}),c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:d.value}))},th=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=Z("stageStateBranchOwnEventFile",await ns({stateBranchRoot:t,eventFileName:n}));if(a(r))return i(r.message);let o=Z("stageStateBranchMediaFiles",await Ac({stateBranchRoot:t}));if(a(o))return i(o.message);let s=Z("stageStateBranchEventAttributes",await Tc({stateBranchRoot:t}));if(a(s))return i(s.message);let d=[r.value,o.value,s.value].filter(m=>m!==null);if(d.length===0)return c("Nothing to stage",{createdCommit:!1});let l=Z("hasStagedChanges(after stage)",await Td(t,d));if(a(l))return i(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"),c("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let u=Z("createStateBranchSyncCommit",await wc({repoRoot:e,stateBranchRoot:t,pathspec:d}));return a(u)?i(u.message):(logger.debug("[sync] created sync commit",u.value),c("Committed own event file",{createdCommit:!0,commitSha:u.value}))},Oc=e=>{let t=e.createdCommit?"Committed locally, offline":"Offline";return bc(t),c(t,{...e,pulled:!1,pushed:!1,offline:!0})},Bc=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),i("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}),i("Own event file must end with .jsonl");Qo();let n=Z("ensureSyncReady",await eh({cwd:e,ensureUpstream:!0}));if(a(n))return Pe(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,d=Z("isDetachedHead(stateBranchRoot)",await wd(o));if(a(d))return Pe(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return Pe("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,p=!1,f=Z("getStateBranch",Jt(r));if(a(f))return Pe(f.message);let I=f.value;logger.debug("[sync] resolved state branch",{stateBranch:I,stateBranchRoot:o});let N=Z("commitOwnEventFileToStateBranch",await th({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(a(N))return Pe(N.message);l=N.value.createdCommit,u=N.value.commitSha;let A=Z("pullBranchRebaseIfPresent",await ui({cwd:o,branch:I}));if(a(A))return li(A.message)?Oc({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,bootstrapped:s}):Pe(A.message);m=A.value;let w=Z("isAheadOfUpstream",await Cd(o));if(a(w))return Pe(w.message);if(l||s||w.value){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:s,stateBranchRoot:o});let T=Z("pushStateBranch",await Hr({stateBranchRoot:o,repoRoot:r}));if(a(T)&&Sd(T.message)){let M=Z("pullBranchRebaseIfPresent(retry)",await ui({cwd:o,branch:I}));if(a(M))return Pe(M.message);m=m||M.value,T=Z("pushStateBranch(retry)",await Hr({stateBranchRoot:o,repoRoot:r}))}if(a(T))return li(T.message)?Oc({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,bootstrapped:s}):Pe(T.message);p=T.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let T=Z("git rev-parse HEAD",await H({args:["rev-parse","HEAD"],cwd:o}));if(a(T))return Pe(T.message);u=T.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Zo(p?"Synced and pushed":m||l?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),c("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,pulled:m,pushed:p,bootstrapped:s,offline:!1})},nh=async(e,t)=>{let n=Ec(e);try{return await t()}finally{let r=Rc(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},os=async e=>{let t=e.cwd??process.cwd(),n=await ut(t);if(a(n))return Pe(n.message);let r=Ce({repoRoot:n.value});if(a(r))return Pe(r.message);let o=r.value;if(!Zf.existsSync(o))return Bc(e);let s=await Dc({worktreeRoot:o,operation:"sync",fn:()=>nh(o,()=>Bc(e))});return a(s)?Pe(s.message):s.value===null?c("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 Mt,ss,rh,_c,_i=y(()=>{"use strict";fc();_r();rn();gt();ue();C();k();es();ts();Bi();Mt=null,ss=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Mt,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),Mt)return logger.debug("[sync] syncAndReloadState joining existing promise"),Mt;logger.debug("[sync] syncAndReloadState creating promise"),Mt=rh();try{let e=await Mt;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:g().syncStatus?.status,statusMessageAfterResolve:g().syncStatus?.msg}),a(e)&&g().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),E({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}),Mt||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),Mt=null}},rh=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=_c();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(Mt)return Mt;logger.debug("[sync] syncAndReloadState:start");let t=Z("resolveActorId",ve());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),i("Unable to resolve event log path");E({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:g().syncStatus});let n=wn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=Z("syncEpiqWithRemote",await os({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),E({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),Pe(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let d=Z("loadMergedEvents",$t(o));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(d),message:(a(d),d.message),count:a(d)?void 0:d.value.events.length}),a(d))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:g().syncStatus}),i(`Unable to load events. ${d.message}`);logger.debug("[sync] loaded merged events after sync",{count:d.value.events.length});let l=_c();if(l)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:l.message,syncStatus:g().syncStatus}),l;let u=mc(),m=g().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:u,selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id,selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual}),!g().selectedNode?.isVirtual&&!g().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:d.value.events.length});let f=Z("bootStateFromEventLog",sn(d.value.events,d.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(f),message:(a(f),f.message)}),a(f))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:g().syncStatus}),i(`Unable to boot synced state. ${f.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),E({filters:m}),logger.debug("[sync] restoreNavigationAnchor:start");let p=Z("restoreNavigationAnchor",gc(u));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(p),message:a(p)?p.message:"Navigation restored",selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id}),a(p)?(E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),p):(E({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),c("Synced",!0))},_c=()=>g().mode===h.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),E({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),i("Will not re-materialize if not in default mode, to not lose edit data"))});var Xn,Uc,$c,Ui,$i,Gr,ji,oh,jc,sh,Hc,is=y(()=>{"use strict";C();Ue();k();_i();Xn=3e3,Uc=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Xn?null:t},$c=0,$i=!1,Gr=!1,ji=()=>{if($i)return!0;let e=Ge();return a(e)?!1:e.value.syncStatus.status==="syncing"},oh=()=>{let e=xe().autoSyncIntervalMs??1e4,t=Date.now()-$c;return Math.max(0,e-t)},jc=()=>{Ui||(Ui=setTimeout(async()=>{if(Ui=void 0,!!At()){if(ji()){Gr=!0;return}Gr=!1,await sh()}},oh()))},sh=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return i("Cannot auto-sync while peeking");if(!At())return i("Cannot auto-sync before state is initialized");if(ji())return Gr=!0,i("Sync already in progress");$i=!0,$c=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await ss()}finally{$i=!1,Gr&&jc()}},Hc=()=>{At()&&(Gr=!0,!ji()&&jc())}});import qr from"node:fs";import Vr from"node:path";import{z as Jn}from"zod";var as,ih,ah,dh,Gc,qc,Wc,Vc,zc,Kc,ch,ds,Hi,zr=y(()=>{"use strict";C();Bt();Lo();pe();as="recent-projects.json",ih=20,ah=Jn.object({projectId:Jn.string().min(1),root:Jn.string().min(1),lastOpenedAt:Jn.number().finite()}),dh=Jn.object({projects:Jn.array(ah)}),Gc=()=>Vr.join(En(),as),qc=e=>Vr.basename(e)||e,Wc=e=>{let t=Vr.resolve(e);try{return qr.realpathSync(t)}catch{return t}},Vc=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,zc=e=>{if(!Mr(e.root))return!1;let t=Rr(e.root);return!a(t)&&t.value===e.projectId},Kc=()=>{let e=Gc();if(!qr.existsSync(e))return c("No recent projects recorded",[]);let t;try{t=JSON.parse(qr.readFileSync(e,"utf8"))}catch(r){return i(`Invalid ${as}: ${r instanceof Error?r.message:String(r)}`)}let n=dh.safeParse(t);return n.success?c("Read recent projects",n.data.projects):i(`Invalid ${as} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},ch=e=>{let t=Gc();try{qr.mkdirSync(Vr.dirname(t),{recursive:!0}),qr.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
56
|
+
`,"utf8")}catch(n){return i(`Unable to write ${as}: ${n instanceof Error?n.message:String(n)}`)}return c("Recorded recent project",e)},ds=({exclude:e}={})=>{let t=Kc();if(a(t))return t;let n=e===void 0?null:Wc(e);return c("Listed recent projects",t.value.filter(r=>n===null||Wc(r.root)!==n).filter(zc).sort(Vc))},Hi=({root:e,now:t=Date.now()})=>{let n=Vr.resolve(e),r=Rr(n);if(a(r))return i(r.message);let o=r.value,s=Kc(),d=a(s)?[]:s.value,l=[{projectId:o,root:n,lastOpenedAt:t},...d.filter(u=>u.projectId!==o&&u.root!==n)].filter(zc).sort(Vc).slice(0,ih);return ch(l)}});var cs,Yc,Xc,Jc,Kr=y(()=>{"use strict";C();Bt();Ue();pe();cs=()=>{let e=xe(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},Yc=()=>{let e=Qe(process.cwd());if(a(e))return!1;let t=Ot(e.value);return vt(t)},Xc=e=>e===!0?"on":e===!1?"off":null,Jc=e=>e==="on"?!0:e==="off"?!1:null});var De,S,Fe=y(()=>{"use strict";De={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"},S={accent:De.cyan,accent2:De.magenta,primary:De.white,secondary:De.grayDark,secondary2:De.grayLight,gray:De.gray,green:De.green,yellow:De.yellow,red:De.red}});var R,Qn,ls=y(()=>{"use strict";Fe();R={red:De.red,yellow:De.yellow,green:De.green,blue:De.blue,magenta:De.magenta,cyan:De.cyan},Qn={urgent:R.red,critical:R.red,important:R.red,blocker:R.red,asap:R.red,immediate:R.red,fail:R.red,failure:R.red,broken:R.red,bug:R.red,error:R.red,incident:R.red,outage:R.red,production:R.red,crash:R.red,security:R.red,warning:R.yellow,warn:R.yellow,risky:R.yellow,risk:R.yellow,attention:R.yellow,pending:R.yellow,review:R.yellow,"needs-review":R.yellow,qa:R.yellow,testing:R.yellow,test:R.yellow,validate:R.yellow,verification:R.yellow,staging:R.yellow,check:R.yellow,"follow-up":R.yellow,followup:R.yellow,waiting:R.yellow,blocked:R.yellow,hold:R.yellow,done:R.green,complete:R.green,completed:R.green,success:R.green,ok:R.green,stable:R.green,resolved:R.green,fixed:R.green,closed:R.green,merged:R.green,released:R.green,deployed:R.green,approved:R.green,verified:R.green,working:R.green,healthy:R.green,pass:R.green,passing:R.green,info:R.blue,information:R.blue,note:R.blue,docs:R.blue,documentation:R.blue,doc:R.blue,guide:R.blue,help:R.blue,explanation:R.blue,detail:R.blue,details:R.blue,context:R.blue,design:R.blue,discussion:R.blue,proposal:R.blue,idea:R.blue,feature:R.magenta,enhancement:R.magenta,improvement:R.magenta,refactor:R.magenta,refactoring:R.magenta,cleanup:R.magenta,optimize:R.magenta,optimization:R.magenta,perf:R.magenta,performance:R.magenta,upgrade:R.magenta,migration:R.magenta,modernize:R.magenta,debt:R.magenta,todo:R.cyan,next:R.cyan,planned:R.cyan,plan:R.cyan,future:R.cyan,backlog:R.cyan,investigate:R.cyan,explore:R.cyan,prototype:R.cyan}});var lh,uh,an,dn,us,ms,Yr=y(()=>{"use strict";he();C();ge();k();lh=e=>e.props.tags??[],uh=e=>e.props.assignees??[],an=e=>lh(e).map(t=>x.getTag(t)).filter(t=>!!t),dn=e=>uh(e).map(t=>x.getContributor(t)).filter(t=>!!t),us=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!P(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",an(n))},ms=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!P(n)?i("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",dn(n))}});var v,Pn=y(()=>{"use strict";v={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",COFFEE:"coffee",NONE:""}});var mh,ph,gh,fh,hh,Dn,Qc,ps,gs,Zc,vh,Wi,Xr=y(()=>{"use strict";mh=/^(\d+)(h|d|w|mo|y)$/,ph=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,gh=({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},fh=(e,t=new Date)=>{let n=e.match(mh);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let d=new Date(t);switch(o){case"h":return d.setHours(d.getHours()-s),d;case"d":return d.setDate(d.getDate()-s),d;case"w":return d.setDate(d.getDate()-s*7),d;case"mo":return d.setMonth(d.getMonth()-s),d;case"y":return d.setFullYear(d.getFullYear()-s),d;default:return null}},hh=e=>{let t=e.match(ph);if(!t)return null;let[,n,r,o,s,d]=t,l=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,f=d?Number(d):0;return gh({year:l,month:u,day:m,hour:p,minute:f})?new Date(l,u-1,m,p,f):null},Dn=e=>{let t=e.trim().toLowerCase();return fh(t)??hh(t)},Qc=/^(\d+)(s|m)?$/,ps=e=>{let t=e.trim().toLowerCase().match(Qc);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},gs=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Qc.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Zc=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,vh=[{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}],Wi=(e=vh)=>{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 yh,fe,et,Ne,bh,xh,qi,Vi,nl,Fn,fs,Gi,el,Ih,Eh,Jr,tl,Rh,Nh,zi,Sh,Ee,cn=y(()=>{"use strict";is();zr();C();Kr();zn();he();ge();k();ls();Yr();Pn();Xr();yh=["BOARD","TICKET","SWIMLANE","COMMENT"],fe={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},et={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Ne={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},bh=[fe.EDITOR,fe.VIEW,fe.USERNAME,fe.AUTOSYNC,fe.SYNC_DEBOUNCE_MS,fe.ATTACHMENT_MAX_KB,fe.LOG_LEVEL],xh=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[et.TITLE,et.DESCRIPTION];case"BOARD":case"SWIMLANE":return[et.TITLE];case"COMMENT":return[et.COMMENT];default:return[]}},qi=[String(Xn),"5000","15000","30000","60000"],Vi=["250","500","1000"],nl=["10s","20s","30s","45s"],Fn=[v.COFFEE,v.EXIT,v.SYNC,v.HELP,v.EXPORT,v.CONFIG,v.YANK],fs=[v.NEW,v.EDIT,v.DELETE,v.MOVE],Gi=[v.TAG,v.UNTAG,v.ASSIGN,v.UNASSIGN,v.CLOSE_ISSUE,v.RE_OPEN_ISSUE,v.EDIT,v.COMMENT],el=[v.FILTER,v.PEEK,v.REPLAY],Ih={WORKSPACE:[...Fn,...fs],BOARD:[...el,...Fn,...fs],SWIMLANE:[...el,...Fn,...fs],TICKET:[...Fn,...fs,...Gi],FIELD:[...Fn,...Gi],FIELD_LIST:[...Fn,...Gi],TEXT:[...Fn],COMMENT:[v.EDIT,v.DELETE,v.YANK]},Eh=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Jr=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&P(n)),tl=e=>e.parentNodeId===Ie,Rh=({selectedNode:e,breadCrumb:t})=>{let n=xh(e?.context);return Jr({breadCrumb:t,selectedNode:e})?n.includes(et.DESCRIPTION)?n:[...n,et.DESCRIPTION]:n},Nh=({selectedNode:e,breadCrumb:t})=>{let n=Jr({breadCrumb:t,selectedNode:e});return n?[Ne.REF,Ne.TITLE,...n.props?.description?.trim()?[Ne.DESCRIPTION]:[],...an(n).length>0?[Ne.TAGS]:[],...dn(n).length>0?[Ne.ASSIGNEES]:[]]:e?[Ne.REF,Ne.TITLE]:[]},zi=()=>{let e=ds({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},Sh=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=cs();if(!r)return[v.HELP,v.CONFIG];if(!Yc())return[v.HELP,v.INIT,v.OPEN];if(t)return[v.HELP,v.PEEK,v.REPLAY,v.EXPORT,v.CONFIG,v.YANK];let o=e?.context,s=o&&yh.includes(o),d=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?Ih[u]:[]))],l=Jr({breadCrumb:n,selectedNode:e});return d.filter(u=>u===v.MOVE?!1:u===v.YANK?!!(l??e):u===v.EDIT?s||!!l:u===v.DELETE?s:u===v.UNTAG?!!(l&&an(l).length>0):u===v.UNASSIGN?!!(l&&dn(l).length>0):u===v.RE_OPEN_ISSUE?!!(l&&tl(l)):u===v.CLOSE_ISSUE?!!(l&&!tl(l)):!0)},Ee=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=g())=>{let s=t.context??"WORKSPACE";return{[v.NONE]:Sh({breadCrumb:o,readOnly:r,selectedNode:n}),[v.EXIT]:["confirm"],[v.EXPORT]:[],[v.SYNC]:[],[v.INIT]:[],[v.OPEN]:e===v.OPEN?zi():[],[v.HELP]:[],[v.PEEK]:[...Wi(),"now","prev","next"],[v.REPLAY]:[...Wi()],[v.EDIT]:Rh({selectedNode:n,breadCrumb:o}),[v.YANK]:Nh({selectedNode:n,breadCrumb:o}),[v.COMMENT]:[],[v.DELETE]:["confirm"],[v.RE_OPEN_ISSUE]:["confirm"],[v.CLOSE_ISSUE]:["confirm"],[v.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[v.FILTER]:["tag","assignee","description","title","ref","clear"],[v.TAG]:[...new Set([...Object.keys(Qn),...x.getExistingTags()])],[v.UNTAG]:[...us()?.value?.map(({name:l})=>l)??[]],[v.UNASSIGN]:[...ms()?.value?.map(({name:l})=>l)??[]],[v.ASSIGN]:x.getExistingAssignees(),[v.NEW]:Eh(s),[v.CONFIG]:[...bh],[v.COFFEE]:["1","3","5","20","custom"]}[e]??[]}});var rl,ol=y(()=>{"use strict";rl=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{accessSync as Ch,copyFileSync as Ah,existsSync as hs,mkdirSync as sl,readdirSync as il,readFileSync as Th,renameSync as wh,rmSync as Mh,statSync as al,unlinkSync as kh,writeFileSync as Lh}from"node:fs";import Zn from"node:path";var Ki,qe,vs=y(()=>{"use strict";Ki=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",qe={writeToFile:(e,t)=>{try{let n=Zn.dirname(e);hs(n)||sl(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Lh(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Th(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=qe.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 hs(e)&&al(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Ch(e),!0}catch{return!1}},mkDir:e=>sl(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Zn.parse(t);for(;;){let r=Zn.join(t,e);try{if(hs(r)&&al(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Zn.dirname(t)}return null},readFirstJSON(e){try{if(!qe.dirExists(e))return null;let t=il(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Zn.join(e,t);return qe.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return qe.dirExists(e)?il(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{kh(e)}catch(t){(!Ki(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Mh(e,{recursive:!0,force:!0})}catch(t){(!Ki(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Zn.dirname(t)),!n?.overwrite&&hs(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{wh(e,t)}catch(r){if(Ki(r)&&r.code==="EXDEV"){Ah(e,t),this.rmFile(e);return}throw r}}}});import Ph from"node:path";import{z as Ht}from"zod";var Dh,dl,Fh,cl,Yi,Xi,Oh,ys,ll,it,Ji,On=y(()=>{"use strict";hr();pe();C();vs();Dh={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},dl=Ht.object({logLevel:Ht.enum(["info","error","debug"]),preferredEditor:Ht.string().optional(),userName:Ht.string().optional(),userId:Ht.string().optional(),autoSync:Ht.boolean().nullable().optional(),autoSyncDebounceMs:Ht.number().optional(),attachmentMaxKb:Ht.number().optional(),viewMode:Ht.enum(["dense","wide"]).optional()}).partial(),Fh="config.json",cl=En,Yi=()=>Ph.join(cl(),Fh),Xi=()=>{try{return qe.mkDir(cl()),c(`Ensured ~/${ct} exists`,null)}catch{return i(`Unable to create ~/${ct}`)}},Oh=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${ct}/config.json JSON`)}let n=dl.safeParse(t??{});return n.success?c("Parsed config",n.data):i(`Invalid ~/${ct}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},ys=()=>{let e=Xi();if(a(e))return i(e.message);let t=Yi(),n=qe.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Oh(n)},ll=e=>{let t=Xi();if(a(t))return i(t.message);let n=dl.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Yi();try{return qe.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
57
|
+
`),c("Config written",null)}catch{return i(`Unable to write ~/${ct}/config.json`)}},it=e=>{let t=ys();if(a(t))return i("Failed to read existing config");let n={...t.value,...e};return ll(n)},Ji=()=>{let e=Yi(),t=Xi();if(a(t))return i(`Unable to create ~/${ct}`);if(!(qe.readFile(e)!==null)){let A=ll(Dh);if(a(A))throw new Error(`Unable to create ~/${ct}/config.json`)}let r=ys();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:d,autoSync:l,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:f}=r.value,I=ti({userId:d,userName:s});if(a(I))return i(I.message);let N=I.value??{userId:d,userName:s};return!N.userName||!N.userId?i(`User name or ID not configured in ~/${ct}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,c("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:N.userName,userId:N.userId,autoSync:l??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))}});var ul,ml,Qi,pl=y(()=>{"use strict";ul="/media/",ml=e=>`${ul}${e}`,Qi=(e,t)=>`})`});import Bh from"node:crypto";import Zi from"node:fs";import _h from"node:path";var Wt,Qr,Uh,$h,jh,gl,Zr=y(()=>{"use strict";xt();C();pe();pl();Wt=500,Qr=(e,t)=>`${e}.${t}`,Uh=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?c("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?c("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")))?c("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"))?c("Sniffed image type","webp"):i(`Unsupported image format. Allowed: ${sd.join(", ")}`),$h=e=>Bh.createHash("sha256").update(e).digest("hex"),jh=(e,t=Wt)=>{if(e.length===0)return i("Attachment is empty");if(e.length>t*1024)return i(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=Uh(e);return a(n)?n:c("Validated attachment data",{hash:$h(e),ext:n.value,bytes:e.length})},gl=(e,t,n=Wt)=>{let r=jh(t,n);if(a(r))return r;let o=Uo(e),s=_h.join(o,Qr(r.value.hash,r.value.ext));try{Zi.existsSync(s)||(Zi.mkdirSync(o,{recursive:!0}),Zi.writeFileSync(s,t))}catch(d){return i(`Unable to write attachment blob: ${d instanceof Error?d.message:String(d)}`)}return c("Wrote attachment blob",r.value)}});import Hh from"zod";var eo,to,fl,ea=y(()=>{"use strict";On();Zr();ue();C();Re();Ue();k();eo=50,to=5e3,fl=()=>{let e=de().commandMeta.inputString,t=Hh.coerce.number().int().min(eo).max(to).safeParse(e);if(!t.success)return i(`Attachment size cap must be ${eo}-${to} KB (default ${Wt})`);let n=it({attachmentMaxKb:t.data});return a(n)?n:(nt({attachmentMaxKb:t.data}),E({mode:h.DEFAULT}),c(`Attachment size cap set to ${t.data} KB`,null))}});import hl from"chalk";var na,vl,ta,yl,Wh,Gh,bl,qh,Vh,no,Oe,xl,Il,bs,zh,Kh,xs,kt=y(()=>{"use strict";ls();na={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},vl=(e,t,n)=>Math.max(t,Math.min(n,e)),ta=(e,t,n)=>e+(t-e)*n,yl=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Wh=e=>e.toLowerCase().trim(),Gh=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,d=e/60,l=s*(1-Math.abs(d%2-1)),u=0,m=0,p=0;d>=0&&d<1?(u=s,m=l):d>=1&&d<2?(u=l,m=s):d>=2&&d<3?(m=s,p=l):d>=3&&d<4?(m=l,p=s):d>=4&&d<5?(u=l,p=s):(u=s,p=l);let f=o-s/2;return[Math.round((u+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},bl=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,qh=(e,t,n)=>{let r=vl(n,0,1);return[Math.round(ta(e[0],t[0],r)),Math.round(ta(e[1],t[1],r)),Math.round(ta(e[2],t[2],r))]},Vh=(e,t,n)=>qh(e,t,n),no=e=>{let t=yl(e)%360,n=Gh(t,na.stringColor.saturation,na.stringColor.lightness);return bl(n)},Oe=(e,t=Qn)=>{let n=Wh(e);return n&&t[n]?t[n]:no(n)},xl=e=>{let t=na.gradient.stops,n=vl(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),d=o-s;return Vh(t[s],t[s+1],d)},Il=e=>bl(xl(e)),bs=e=>yl(e.toLowerCase().trim())/4294967295,zh=e=>{let t=bs(e);return xl(t)},Kh=e=>{let[t,n,r]=zh(e);return{normal:o=>hl.bgRgb(t,n,r).black(o),cursor:o=>hl.bgRgb(t,n,r).white.bold(o)}},xs=e=>Kh(e).normal(` ${e} `)});var ft,ro=y(()=>{"use strict";ft=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null});import{createHash as Yh}from"node:crypto";var Xh,Jh,Te,er=y(()=>{"use strict";Xh="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Jh=e=>{let t=Yh("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+=Xh[Number(n>>s&31n)]}return r},Te=(e,t)=>Jh(`${e}:virtual:${t}`)});import El from"chalk";var ee,we,Me,Rl=y(()=>{"use strict";kt();Fe();ee=e=>El.dim(e),we=e=>El.hex(S.primary)(e),Me=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let d=o.trim();if(d.length<s)return"";let p=[...t.filter(Boolean).filter(f=>f.startsWith(d))].sort((f,I)=>bs(f)-bs(I)).slice(0,r).map(f=>xs(f)).join(" ");return p?`${ee(e)}${p}${ee(n)}`:""}});var ln,Is=y(()=>{"use strict";ln={None:"none",Invalid:"invalid",Valid:"valid"}});import Cl from"chalk";var Qh,Nl,ce,Y,$,tr,Sl,Es,ra,Zh,Bn,ev,tv,nv,rv,ov,Al,Tl=y(()=>{"use strict";is();Kr();ol();dt();xt();C();ge();Ue();ea();Zr();k();kt();ro();Yr();er();Rl();Pn();Is();cn();Xr();Qh=["BOARD","TICKET","SWIMLANE"],Nl=()=>{let e=g().selectedNode;if(!e?.context)return $({message:ee("Missing target context")});if(Qh.includes(e.context))return Y();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===Te(t?.parentNodeId??"","comments"))return Y()}return $({message:ee("Command not available in this context")})},ce="<ENTER> to confirm",Y=(e="",t=[])=>({message:ee(e),validity:ln.Valid,completionWordList:t}),$=({message:e,completionWordList:t=[]})=>({validity:ln.Invalid,message:e,completionWordList:t}),tr=e=>e.length===0,Sl=(e,t)=>{let n=Xe(g().breadCrumb,"BOARD");if(a(n))return $({message:we("Command is not applicable in this context")});let r=od(n.value.id);return a(r)?$({message:we(`Unable to ${t}: board id is not a valid ULID`)}):Zc({date:e,horizonDate:r.value})?null:$({message:we(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},Es=e=>` ${Cl.hex("#000").bgHex(Oe(e))(` ${e} `)} `,ra=({modifier:e})=>{let t="confirm";return e===t?Y(ce):$({message:tr(e)?ee("if you are certain, enter ")+xs(t):"",completionWordList:[t]})},Zh=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?$({message:ee(n)}):Y():$({message:tr(r)?t:"",completionWordList:[...e]}),Bn=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>tr(n)&&tr(r)?$({message:e,completionWordList:[]}):Y(t??ce),ev=({modifier:e,inputString:t})=>{let n=zi();return!tr(e)||!tr(t)?Y(ce):$({message:n.length?ee("number from the list, or a path"):ee("path to an epiq project"),completionWordList:n})},tv=({modifier:e,inputString:t})=>{let n=Ee(v.CONFIG);if(!n.includes(e))return $({message:Me({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case fe.EDITOR:{let r=[...rl];return t.trim()?r.includes(t.trim())?Y(ce):$({message:Me({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):$({message:Me({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case fe.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?Y(ce):$({message:Me({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case fe.USERNAME:return t.trim()?Y(ce):$({message:we("Enter a user name. Saved in ")+Cl.bgBlack("~/.epiq-global/config.json")});case fe.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?Y(ce):$({message:Me({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case fe.AUTOSYNC:{let r=["on","off"],o=xe().autoSync;if(!r.includes(t.trim())){let s=Xc(o);return $({message:Me({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return Y(ce)}case fe.ATTACHMENT_MAX_KB:{let r=xe().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<eo||o>to){let s=Me({prefix:" examples: ",wordList:Vi,minLengthForHints:0,inputString:t});return $({message:we(`provide a size cap in KB (${eo}-${to}). current: ${r??Wt} KB.`)+s,completionWordList:Vi})}return Y(ce)}case fe.SYNC_DEBOUNCE_MS:{let r=xe().autoSyncIntervalMs,o=Uc(t);if(!t.trim()||o===null||o<Xn){let s=Me({prefix:" examples: ",wordList:qi,minLengthForHints:0,inputString:t});return $({message:we(`provide duration above ${Xn}ms. current duration: ${r}ms.`)+s,completionWordList:qi})}return Y(ce)}default:return $({message:we("Unknown config option"),completionWordList:n})}},nv=({modifier:e,inputString:t})=>{let n=Ee(v.EDIT);if(!n.length)return $({message:we("Command not available in this context")});if(!n.includes(e)){let r=Me({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return $({message:r||we("Unknown edit option"),completionWordList:n})}switch(e){case et.COMMENT:return t.trim()?Y(ce):$({message:ee("write a comment...")});case et.TITLE:return Y(ce);case et.DESCRIPTION:{let{preferredEditor:r}=xe();return r?Y(ee("<ENTER> to edit in ")+r):$({message:"No editor selected"})}default:return $({message:we("Unknown edit option"),completionWordList:n})}},rv=({modifier:e})=>{let t=Ee(v.YANK);return t.length?t.includes(e)?Y(ce+ee(" and copy to clipboard")):$({message:Me({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):$({message:we("Nothing selected to copy from")})},ov={[v.EXPORT]:()=>Y(ce+ee(", and create export markdown file")),[v.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return Y(ce);let n={message:ee("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Dn(r);if(!r||!o)return $(n);let s=Sl(o,"peek");return s||Y(ce)},[v.REPLAY]:e=>{let{dateInput:t,durationInput:n}=gs(e.modifier,e.inputString),r={message:ee("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Dn(t);if(!t||!o)return $(r);let s=Sl(o,"replay");return s||(n&&ps(n)===null?$({message:we("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):Y("<ENTER> to replay board history",n?nl:[]))},[v.EXIT]:()=>Y(ce+ee(" and exit the application")),[v.INIT]:()=>Y(ce),[v.OPEN]:ev,[v.PALETTE]:()=>Y(ce),[v.FILTER]:e=>{if(e.modifier==="clear")return Y(ce);let t=s=>Ee(v.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return $({message:Me({wordList:Ee(v.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Ee(v.FILTER)});let n=Object.values(g().tags).map(s=>s.name),r=Object.values(g().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?$({message:Me({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):Y():$({message:Me({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[v.NONE]:e=>{let t=Ee(v.NONE);return $({message:Me({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[v.NEW]:e=>Zh({list:Ee(v.NEW),hint:Me({wordList:Ee(v.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[v.HELP]:()=>Y(ce),[v.EDIT]:nv,[v.COMMENT]:e=>{let t=Bn({hint:ee(`write a comment (max ${4e3} char)...`),onOk:ee(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===ln.Invalid?t:e.inputString.length>4e3?Y(we("max input exceeded")):t},[v.CONFIG]:tv,[v.YANK]:rv,[v.DELETE]:e=>{let t=Nl();return t.validity==="invalid"?t:ra(e)},[v.CLOSE_ISSUE]:e=>ra(e),[v.RE_OPEN_ISSUE]:e=>ra(e),[v.MOVE]:e=>{let t=Nl();return t.validity==="invalid"?t:Bn({hint:Me({prefix:"hey hacker! These commands are blocked for you... ",wordList:Ee(v.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[v.TAG]:e=>{let n=x.getExistingTags().slice(0,10).map(Es).join("");return Bn({hint:n.length?ee("create tag or reuse:")+n+ee(""):ee("create tag ...")})(e)},[v.UNTAG]:e=>{let t=us();if(a(t))return $({message:we("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Es).slice(0,10);return n.length?Bn({hint:ee(" ... ")+n.join("")})(e):$({message:we("Issue has no tags"),completionWordList:[]})},[v.ASSIGN]:e=>{let t=x.getExistingAssignees().map(Es).slice(0,10);return Bn({hint:ee("assignees... ")+t.join("")})(e)},[v.UNASSIGN]:e=>{let t=ms();if(a(t))return $({message:we("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Es).slice(0,10);return n.length?Bn({hint:ee("remove assignee... ")+n.join("")})(e):$({message:we("Issue has no assignees"),completionWordList:[]})},[v.SYNC]:()=>Y(ce),[v.COFFEE]:e=>{let{modifier:t}=e,n=Ee(v.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?$({message:ee("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):Bn({hint:Me({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},Al=Object.fromEntries(Object.entries(ov).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]))});var Rs,wl=y(()=>{"use strict";Rs=["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 sv,iv,av,dv,cv,Ml,kl,Ll,Pl=y(()=>{"use strict";C();k();wl();sv=3,iv=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"]),av=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},dv=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=sv&&!iv.has(t)&&!/^\d+$/.test(t)),cv=e=>{let t=new Map;for(let s of av(e))for(let d of dv(s))t.set(d,(t.get(d)??0)+1);let n=[...t.entries()].sort((s,d)=>d[1]-s[1]||s[0].localeCompare(d[0])).map(([s])=>s),r=new Set(n),o=Rs.filter(s=>!r.has(s));return[...n,...o]},Ml=Rs,kl=-1,Ll=()=>{let e=Ge();if(a(e))return Rs;let t=e.value,n=t.eventLog.length;return n!==kl&&(Ml=cv(t),kl=n),Ml}});var Dl,Fl,oa=y(()=>{"use strict";fd();cn();Pn();Tl();Pl();k();ue();Dl=e=>Object.values(v).includes(e),Fl=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:d,validity:l,completionWordList:u}=Al[n].validate(n,r,s),m=n!==v.PEEK&&n!==v.REPLAY,p=o==="command"||o==="modifier"?Ee(n):m?Ll():[],{mode:f}=g(),I=f===h.COMMAND_LINE?d??"":"",N=[...u,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:I,autoCompletion:t?gd(e,N):{hint:"",hints:[],remainder:"",overlap:0}}}});var Ol,lv,uv,mv,Bl=y(()=>{"use strict";oa();cn();Ol=e=>{let t=e.trimStart(),n=uv(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),d=mv(e),l=Dl(r)?r:null,u=l!==null,m=r!=="",p=l?Ee(l)??[]:[],f=l&&p.includes(o)?o:"",I="word";n.length===0||n.length===1&&!s?I="command":(n.length===1&&s||n.length===2&&!s)&&(I="modifier");let N=s?"":d,A=lv(t,l,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:I,inputToMatch:N,inputString:A}},lv=(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},uv=e=>e.trim()?e.trim().split(/\s+/):[],mv=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as sA}from"react";var nr,sa,rr,pv,_l,Lt,oo,ia,aa,Ul,$l,Ns,jl,V,Hl,Wl,Gl,de,Ss,Re=y(()=>{"use strict";oa();Bl();C();Is();nr=e=>e===sa||e===":",sa=" ",rr={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:ln.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},pv=new Set,_l=()=>{for(let e of pv)e()},Lt=e=>{let n=e(rr),r=Ol(n.value),o=n.cursorPosition===n.value.length;rr={...n,commandMeta:Fl(r,o)},_l()},oo=({message:e,status:t})=>{let n=structuredClone(rr);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,rr=n,_l(),c(e,null)},ia=e=>{Lt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},aa=e=>{Lt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&nr(n[o-1]);)o--;for(;o>0&&!nr(n[o-1]);)o--}else{for(;o<n.length&&!nr(n[o]);)o++;for(;o<n.length&&nr(n[o]);)o++}return{...t,cursorPosition:o}})},Ul=()=>{Lt(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}})},$l=()=>{Lt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&nr(t[r-1]);)r--;for(;r>0&&!nr(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Ns=e=>{Lt(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),d=s+o,l=Math.max(0,Math.min(s.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},jl=()=>{Lt(e=>({...e,commandIsPending:!0}))},V=e=>{Lt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Hl=({addToHistory:e=!0})=>{Lt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Wl=()=>{Lt(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}})},Gl=()=>{Lt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},de=()=>rr,Ss=()=>{let[e,...t]=rr.value.split(sa);return t.join(sa).trim()}});var D,In=y(()=>{"use strict";ue();ad();k();Re();Ue();D={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"}});var ql,F,da=y(()=>{"use strict";k();Pn();ql=e=>{let{context:t}=g().contextNode;if(!t)return F.None;switch(e){case v.EXIT:return F.Exit;case v.EXPORT:return F.Export;case v.COFFEE:return F.Coffee;case v.INIT:return F.Init;case v.OPEN:return F.OpenProject;case v.DELETE:return F.Delete;case v.EDIT:return F.Edit;case v.COMMENT:return F.Comment;case v.HELP:return F.ViewHelp;case v.RE_OPEN_ISSUE:return F.ReopenIssue;case v.CLOSE_ISSUE:return F.CloseIssue;case v.TAG:return F.TagTicket;case v.UNTAG:return F.UntagTicket;case v.ASSIGN:return F.AssignUserToTicket;case v.UNASSIGN:return F.UnassignUserFromTicket;case v.NEW:return F.NewItem;case v.FILTER:return F.Filter;case v.MOVE:return F.Move;case v.PEEK:return F.Peek;case v.REPLAY:return F.Replay;case v.CONFIG:return F.Config;case v.YANK:return F.Yank;case v.SYNC:return F.Sync;default:return F.None}},F={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",Coffee:"coffee"}});import{Text as Vl}from"ink";import zl,{useEffect as Kl,useState as gv}from"react";var Yl,ze,or=y(()=>{"use strict";k();Fe();Yl={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},ze=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Ke(),r=Yl[n]??Yl.default,[o,s]=gv(0);if(Kl(()=>{s(0)},[r]),Kl(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return zl.createElement(Vl,null,t);let d=r[o]??r[0]??t;return zl.createElement(Vl,{color:S.accent,dimColor:o===1},d)}});import{Box as ca,Text as fv}from"ink";import Cs from"react";var hv,un,so=y(()=>{"use strict";Fe();hv=(e,t,n,r)=>{let o=u=>Math.max(1,e[u]??1),s=n,d=n+1,l=o(n);for(;d<t&&l+o(d)<=r;)l+=o(d),d++;for(;s>0&&l+o(s-1)<=r;)s--,l+=o(s);return{start:s,end:d}},un=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let d=Math.max(1,Math.floor(t)),l=Math.max(1,Math.ceil(r)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(1,Math.floor(d/l)),p=Math.max(0,e.length-m),{start:f,end:I}=o?hv(o,e.length,u,d):s?{start:Math.min(p,Math.max(0,u-m+1)),end:Math.min(p,Math.max(0,u-m+1))+m}:{start:Math.min(p,Math.floor(u/m)*m),end:Math.min(p,Math.floor(u/m)*m)+m},N=Math.max(1,I-f),A=e.slice(f,I),w=e.length>N,T=d,M=w?Math.max(1,Math.floor(N/e.length*T)):T,U=Math.max(0,T-M),ne=Math.max(1,e.length-N),be=w?Math.floor(f/ne*U):0;return Cs.createElement(ca,{flexDirection:"row",height:d,width:"100%"},Cs.createElement(ca,{flexDirection:"column",flexGrow:1,height:d},A),Cs.createElement(ca,{flexDirection:"column",width:1,height:T},Array.from({length:T}).map((Q,q)=>Cs.createElement(fv,{key:q,color:w&&q>=be&&q<be+M?S.accent:S.secondary},w?"\u2502":" "))))}});var Xl,la,vv,As,ua=y(()=>{"use strict";k();vv=()=>{let{eventLog:e=[]}=g();if(la&&Xl===e)return la;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Xl=e,la=t,t},As=e=>vv().has(e)});import{Text as yv}from"ink";import bv from"react";var xv,Iv,sr,Ts=y(()=>{"use strict";ls();kt();ge();ua();Xt();xv=e=>e.toLowerCase().trim(),Iv=(e,t=Qn)=>{let n=xv(e);return t[n]?t[n]:no(n)},sr=({id:e,isSelected:t,maxWidth:n})=>{let r=x.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:It(o,n);return bv.createElement(yv,{underline:t,color:Iv(o)},"@"+s,As(e)?"":"\u2197")}});import{Text as Ev}from"ink";import Rv from"react";var ws,ma=y(()=>{"use strict";ge();Fe();kt();Xt();ws=({id:e,isSelected:t,maxWidth:n})=>{let r=x.getTag(e);if(!r)return;let o=n===void 0?r.name:It(r.name,n);return Rv.createElement(Ev,{underline:t,backgroundColor:Oe(r.name),color:S.secondary}," "+o+" ")}});import{useEffect as Nv,useState as Sv}from"react";var Cv,Jl,Ms,io,Av,Tv,ir,ks=y(()=>{"use strict";kt();Cv=80,Jl=1400,Ms=new Set,io=null,Av=e=>(Ms.add(e),io||(io=setInterval(()=>{for(let t of Ms)t()},Cv)),()=>{Ms.delete(e),Ms.size===0&&io&&(clearInterval(io),io=null)}),Tv=()=>{let e=Date.now()%Jl/Jl;return e<.5?e*2:(1-e)*2},ir=e=>{let[,t]=Sv(0);return Nv(()=>{if(e)return Av(()=>t(n=>n+1))},[e]),Il(Tv())}});import{Box as ar,Text as dr}from"ink";import Ye from"react";var wv,Ql,Mv,kv,eu,tu=y(()=>{"use strict";ge();Fe();Xt();ua();en();Yr();Ts();ma();ks();wv=(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),It(e.slice(o).trim(),n)]},Ql=3,Mv=2,kv=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let d=e.length-o-1,l=d>0?String(d).length+1:0;if(r+s.width+l>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},eu=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=ir(r),s=e-4,d=s-7-1,[l,u]=wv(Le(t.title),d,s),m=u?null:It(Le(t.props.description),s)||null,p=an(t),f=dn(t).map(M=>({...M,name:M.name})),I=Math.max(1,s-Ql),N=x.getCommentsByIssue(t.id),A=N.length?String(N.length).length+2+1:0,{shown:w,hidden:T}=kv([...p.map(M=>({id:M.id,isTag:!0,width:Math.min(M.name.length,I)+Ql})),...f.map(M=>({id:M.id,isTag:!1,width:Math.min(M.name.length,I)+Mv+(As(M.id)?0:1)}))],s-A);return Ye.createElement(ar,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?S.accent:S.secondary,justifyContent:"space-between"},Ye.createElement(ar,{paddingLeft:1,paddingRight:1,flexDirection:"column"},Ye.createElement(ar,{justifyContent:"space-between"},Ye.createElement(dr,{color:S.primary},l),Ye.createElement(dr,{color:S.secondary2,dimColor:!0},K(t.id))),u&&Ye.createElement(dr,{color:S.primary},u),m&&Ye.createElement(dr,{color:S.secondary2,dimColor:!0},m)),Ye.createElement(ar,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},Ye.createElement(ar,{flexDirection:"row"},w.map(M=>Ye.createElement(ar,{paddingRight:1,key:M.id},M.isTag?Ye.createElement(ws,{id:M.id,maxWidth:I}):Ye.createElement(sr,{id:M.id,maxWidth:I}))),T>0&&Ye.createElement(dr,{color:S.secondary2,dimColor:!0},"+",T)),N.length>0&&Ye.createElement(dr,{color:S.accent},"[",N.length,"]")))}});import{Box as _n,Text as ao}from"ink";import tt from"react";var Lv,nu,ru=y(()=>{"use strict";ue();ge();Fe();kt();or();ks();Lv=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,nu=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:d})=>{let l=ir(s),u=(r.props.tags??[]).map(Q=>x.getTag(Q)).filter(Q=>!!Q),m=(r.props.assignees??[]).map(Q=>x.getContributor(Q)).map(Q=>Q&&{...Q,name:Q.name}).filter(Q=>!!Q),p=1,f=u.length*(1+p),I=m.length*(2+p),N=u.map(Q=>tt.createElement(_n,{key:Q.id,paddingRight:p},tt.createElement(ao,{color:Oe(Q.name)},"\u25A0"))),A=m.map(Q=>tt.createElement(_n,{key:Q.id,paddingRight:p},tt.createElement(ao,{color:no(Q.name)},"@"+Q.name.at(0)))),w=s?l:o?S.accent:d===h.MOVE?S.secondary:S.primary,T=x.getCommentsByIssue(r.id),M=T.length?String(T.length).length+2+p:0,U=T.length?tt.createElement(_n,{paddingRight:p},tt.createElement(ao,{color:S.accent},"[",T.length,"]")):null,ne=f+I+M,be=Math.max(1,n-t-ne-(ne>0?1:0));return tt.createElement(_n,{justifyContent:"space-between"},tt.createElement(_n,null,tt.createElement(_n,{width:t},o?tt.createElement(ze,{isSelected:!0}):tt.createElement(ao,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),tt.createElement(ao,{wrap:"truncate",color:w},Lv(r.title,be))),tt.createElement(_n,null,N,A,U))}});import Pv from"chalk";import{Box as pa,Text as Dv}from"ink";import Pt from"react";var Fv,ou,su=y(()=>{"use strict";he();k();Fe();or();so();tu();ru();ks();Fv=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u,replay:m}=Ke(),p=u[e.id]??[],f=m?new Set(m.flashNodeIds):null,I=f?.has(e.id)??!1,N=ir(I),A=`${e.title} ${Pv.hex(S.secondary2).dim("("+p.length+")")}`,w=3,T=o?1:5,M=s&&d===-1,U=n-3-(o?1:0)-(M?2:0),ne=Math.max(2,String(p.length).length+1),be=r-w-1,Q=Pt.createElement(pa,{borderStyle:"round",borderColor:S.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},Pt.createElement(ze,{isSelected:t}),Pt.createElement(Dv,{bold:!0,color:I?N:t?S.accent:S.primary},A," ",e.readonly?"\u{1F512}":"")),q=(z,yn)=>{let bn=s&&d===yn;if(!P(z))return null;let pr=f?.has(z.id)??!1;return o?Pt.createElement(nu,{key:z.id,index:yn,labelWidth:ne,width:U,ticket:z,isSelected:bn,isFlashing:pr,mode:l}):Pt.createElement(eu,{key:z.id,width:U,ticket:z,isSelected:bn,isFlashing:pr})};return Pt.createElement(pa,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?S.accent:S.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},Q,Pt.createElement(pa,null,p.length>0&&Pt.createElement(un,{selectedIndex:d,height:be,itemHeight:T},p.map(q)),M&&Pt.createElement(ze,{isSelected:!0})))},ou=Pt.memo(Fv)});var iu,au,ga=y(()=>{"use strict";Sn();iu=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},au=(e,t,n)=>Ae.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0})});var cr,Ls=y(()=>{"use strict";cr=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"}});import{Box as lr,Text as Gt}from"ink";import Be,{useEffect as Ov,useMemo as Bv,useRef as _v}from"react";import{decodeTime as du}from"ulid";function lu({ticket:e,width:t,height:n}){let r=Bv(()=>$v(e),[e]),o=_v([]);Ov(()=>(cu(o.current),o.current=Hv(e,r),()=>{cu(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Ke(),l=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?Be.createElement(lr,{flexDirection:"column",width:t,height:n,padding:1},Be.createElement(Gt,{color:S.primary},"No attachments yet."),Be.createElement(lr,{paddingTop:1},Be.createElement(Gt,{color:S.primary},"Attach images from the browser GUI"),Be.createElement(Gt,{color:S.accent}," epiq gui "),Be.createElement(Gt,{color:S.primary},"by dropping or pasting them."))):Be.createElement(lr,{flexDirection:"column",width:t,height:n},Be.createElement(lr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:S.secondary,borderStyle:"single",paddingBottom:1},Be.createElement(Gt,{color:S.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),Be.createElement(un,{height:l,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,I=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return Be.createElement(lr,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},Be.createElement(Gt,{color:S.accent},f?"\u276F ":" "),Be.createElement(lr,{paddingLeft:1},Be.createElement(Gt,{color:S.secondary2},`#${p+1} `),Be.createElement(Gt,{color:f?S.accent:S.primary},I),Be.createElement(Gt,{color:S.secondary2}," "+Wv(m.bytes)+" "+cr(bt(m.id)))))})))}var Uv,$v,cu,jv,Hv,Wv,uu=y(()=>{"use strict";Ze();dt();Ls();he();C();ge();Sn();k();Fe();er();so();Uv=e=>Te(e,"attachments"),$v=e=>x.getAttachmentsByIssue(e.id).sort((t,n)=>du(t.id)-du(n.id)),cu=e=>{for(let t of e)x.deleteNode(t.id)},jv=(e,t,n)=>Ae.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),Hv=(e,t)=>{let n=x.getNode(Uv(e.id));if(!n||!Je(n))return[];let r=t.map((o,s)=>jv(o,s,n.id)).map(o=>x.createNode(o)).filter(vt).map(({value:o})=>o).filter(Je);return t.length>0&&g().selectedIndex<0&&_.navigate({contextNode:n,selectedIndex:0}),r},Wv=e=>`${Math.max(1,Math.round(e/1024))} KB`});var pu,fa,mu,ha,gu,fu,Gv,hu,qv,va,vu=y(()=>{"use strict";pu=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,fa=e=>e.replace(pu,""),mu=e=>e==="additions"||e==="deletions",ha=e=>{let t=pu.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"||!mu(r.side)||!mu(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r},gu=/```\n([\s\S]*?)\n?```\s*$/,fu=e=>gu.exec(e)?.[1]??null,Gv=/`[^`\n]+`[^\n]*\n?$/,hu=e=>fa(e).replace(gu,"").replace(Gv,"").trim(),qv=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})`},va=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${qv(e)}`});var Vv,co,zv,Kv,Yv,Xv,bu,ya,xu,yu,Iu,ba=y(()=>{"use strict";vu();Vv=(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 d of r){let l=d;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},co=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)},zv=/!\[([^\]]*)\]\([^)]*\)/g,Kv=e=>e.replace(zv,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),Yv=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),Xv=4,bu=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(Xv)),ya=e=>{let t=!1;return e.map(bu).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=ha(n);if(r)return{kind:"caption",text:va(r)};let o=Kv(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:co(s[1]??"")}:{kind:"text",spans:co(o)}})},xu=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],yu=(e,t)=>{let n=[];for(let r of ya(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 xu(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of Vv(Yv(r.spans),t))n.push({kind:r.kind,spans:co(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},Iu=(e,t)=>{let n=ha(e),r=n?fu(e):null;if(!n||r===null)return yu(fa(e).split(`
|
|
58
|
+
`),t);let o=hu(e),s=r.split(`
|
|
59
|
+
`).map(bu),d=n.side===n.endSide?n.start:void 0,l=d===void 0?0:String(d+s.length-1).length+3;return[...o?[...yu(o.split(`
|
|
60
|
+
`),t),{kind:"blank"}]:[],{kind:"caption",text:va(n)},...s.flatMap((u,m)=>xu(u,Math.max(1,t-l)).map((p,f)=>({kind:"code",text:p,number:d===void 0||f>0?void 0:d+m})))]}});import{Box as Eu,Text as Un}from"ink";import at from"react";var Ru,xa,Nu,Ia=y(()=>{"use strict";Fe();Ru=({spans:e,bold:t})=>at.createElement(Un,{color:S.primary,bold:t},e.map((n,r)=>n.code?at.createElement(Un,{key:r,color:S.yellow},n.text):at.createElement(Un,{key:r},n.text))),xa=({line:e,width:t,gutter:n=0})=>{switch(e.kind){case"blank":return at.createElement(Un,null," ");case"fence":return at.createElement(Un,{color:S.secondary2},"```");case"caption":return at.createElement(Un,{color:S.accent},e.text);case"heading":return at.createElement(Ru,{spans:e.spans,bold:!0});case"text":return at.createElement(Ru,{spans:e.spans});case"code":{let r=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return at.createElement(Un,{backgroundColor:S.secondary,color:S.primary},r,e.text.padEnd(Math.max(0,t-r.length)))}}},Nu=({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 at.createElement(Eu,{flexDirection:"column"},e.map((o,s)=>at.createElement(Eu,{key:s},at.createElement(xa,{line:o,width:t,gutter:r}))))}});import{Box as mn,Text as pn}from"ink";import Se,{useEffect as Jv,useMemo as Su,useRef as Qv}from"react";import{decodeTime as Cu}from"ulid";function Tu({ticket:e,width:t,height:n}){let r=Su(()=>ty(e),[e]),o=Qv([]);Jv(()=>(Au(o.current),o.current=ny(e,r),()=>{Au(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Ke(),l=Math.max(1,n-4),u=Math.max(20,t-8),m=Su(()=>r.map(f=>{let I=Iu(f.md,u);return I.length>0?I:[{kind:"blank"}]}),[r,u]),p=m.map(f=>f.length+Zv);return r.length===0?Se.createElement(mn,{flexDirection:"column",width:t,height:n,padding:1},Se.createElement(pn,{color:S.primary},"No comments yet."),Se.createElement(mn,{paddingTop:1},Se.createElement(pn,{color:S.primary},"Use"),Se.createElement(pn,{color:S.accent}," :comment "),Se.createElement(pn,{color:S.primary},"to add the first one."))):Se.createElement(mn,{flexDirection:"column",width:t,height:n},Se.createElement(mn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:S.secondary,borderStyle:"single",paddingBottom:1},Se.createElement(pn,{color:S.secondary2},"Comments (",r.length,") ")),Se.createElement(un,{height:l,itemHeights:p,selectedIndex:s},r.map((f,I)=>{let N=I===s;return Se.createElement(mn,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:S.secondary,borderStyle:"single"},Se.createElement(mn,{flexDirection:"row",paddingBottom:1},Se.createElement(pn,{color:S.accent},N?"\u276F ":" "),Se.createElement(mn,{paddingLeft:1},Se.createElement(pn,{color:S.secondary2},`#${I+1} `),Se.createElement(sr,{id:f.authorId}),Se.createElement(pn,{color:S.secondary2}," "+cr(bt(f.id))))),Se.createElement(mn,{paddingLeft:3,paddingBottom:1},Se.createElement(Nu,{lines:m[I]??[],width:u})))})))}var Zv,ey,ty,Au,ny,wu=y(()=>{"use strict";Ze();dt();Ls();he();C();ge();k();Fe();er();Ts();so();ga();ba();Ia();Zv=4,ey=e=>Te(e,"comments"),ty=e=>x.getCommentsByIssue(e.id).sort((t,n)=>Cu(t.id)-Cu(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),Au=e=>{for(let t of e)x.deleteNode(t.id)},ny=(e,t)=>{let n=x.getNode(ey(e.id));if(!n||!Je(n))return[];let r=t.map((o,s)=>au(o,s,n.id)).map(x.createNode).filter(vt).map(({value:o})=>o).filter(xr);return t.length>0&&g().selectedIndex<0&&_.navigate({contextNode:n,selectedIndex:0}),r}});import{Box as Ps,Text as ry}from"ink";import qt from"react";var Mu,ku=y(()=>{"use strict";he();ge();Vn();k();Fe();Ts();or();ma();Mu=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Ke(),{title:o}=t,s=t.parentNodeId?x.getNode(t.parentNodeId):void 0,d=s&&P(s)?o===se.ASSIGNEES?s.props.assignees??[]:o===se.TAGS?(s.props.tags??[]).filter(l=>x.getTag(l)):[]:[];return qt.createElement(Ps,{alignItems:"center",paddingTop:1},qt.createElement(Ps,{minWidth:12},qt.createElement(ze,{isSelected:n}),qt.createElement(ry,{color:n?S.accent:S.secondary2},o,":")),qt.createElement(Ps,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=r.id===t.id&&u===e;return qt.createElement(Ps,{key:`${o}-${l}`,paddingRight:2,minHeight:1},qt.createElement(ze,{isSelected:m}),o===se.ASSIGNEES?qt.createElement(sr,{isSelected:m,id:l}):o===se.TAGS?qt.createElement(ws,{isSelected:m,id:l}):null)})))}});import{Box as lo,Text as Ea}from"ink";import ht,{useEffect as oy,useMemo as Ra}from"react";var sy,Lu,Na,Pu,iy,Sa,Du=y(()=>{"use strict";ge();C();Sn();k();Fe();Xt();or();so();Ia();ba();Gn();sy="\u2029",Lu=(e,t)=>`${e}::inline-line::${t}`,Na=new Map,Pu=e=>{let t=Na.get(e)??[];Na.delete(e);for(let n of t)x.deleteNode(n)},iy=(e,t)=>{Pu(e);let n=[];t.forEach((r,o)=>{let s=rt(BigInt(o+1));if(!vt(s))return;let d=x.createNode(Ae.text({id:Lu(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));vt(d)&&n.push(d.value.id)}),Na.set(e,n)},Sa=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:d,contextNode:l}=Ke(),u=Ra(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Ra(()=>u.join("\0"),[u]);oy(()=>(iy(e,u),()=>{Pu(e)}),[e,m]);let p=s-10,I=Ra(()=>ya(u).map(N=>{if(N.kind==="code")return{...N,text:It(N.text,p)};if(N.kind==="text"||N.kind==="heading"){let A=N.spans.map(w=>w.code?`\`${w.text}\``:w.text).join("");return{...N,spans:co(It(A,p))}}return N}),[u,p]).map((N,A)=>{let w=l.id===e&&d===A;return ht.createElement(lo,{key:Lu(e,A)},ht.createElement(Ea,{color:w?S.primary:S.secondary2,dimColor:!w},`${A+1} `.padStart(5,"\xA0")),N.kind==="blank"?ht.createElement(Ea,{backgroundColor:w?"gray":void 0},sy):ht.createElement(lo,null,ht.createElement(xa,{line:N,width:N.kind==="code"?p:0})))});return ht.createElement(lo,{flexDirection:"column",paddingTop:1},ht.createElement(lo,null,ht.createElement(ze,{isSelected:o}),ht.createElement(Ea,{color:o?S.accent:S.secondary2},t)),ht.createElement(lo,{flexDirection:"row",borderStyle:"round",borderColor:S.secondary,paddingLeft:1,marginLeft:1},ht.createElement(un,{scrollByOne:!0,height:r-3,selectedIndex:d,itemHeight:1},I)))}});import{Box as $n,Text as Ca}from"ink";import ke,{useMemo as uo}from"react";var ay,dy,cy,ly,Fu,Ou=y(()=>{"use strict";he();ge();k();Fe();ga();er();uu();wu();or();ku();Du();ay=e=>Te(e,"description"),dy=e=>Te(e,"comments"),cy=e=>Te(e,"history"),ly=e=>Te(e,"attachments"),Fu=({ticket:e,height:t})=>{let n=uo(()=>iu(e),[e]),{selectedIndex:r,contextNode:o}=Ke(),s=process.stdout.columns||120,d=uo(()=>ay(e.id),[e.id]),l=uo(()=>dy(e.id),[e.id]),u=uo(()=>cy(e.id),[e.id]),m=uo(()=>ly(e.id),[e.id]),p=x.getAttachmentsByIssue(e.id).length,f=o.id===e.id,I=o.id===l||o.parentNodeId===l,N=o.id===u||o.parentNodeId===u,A=o.id===m||o.parentNodeId===m,w=ae(e.id);if(I){let z=t-3;return ke.createElement($n,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},ke.createElement(Tu,{ticket:e,width:s,height:z}))}if(A){let z=t-3;return ke.createElement($n,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},ke.createElement(lu,{ticket:e,width:s,height:z}))}if(N){let q=x.getNode(u),z=q&&Je(q)?q.props.value??"":"",bn=t-3;return ke.createElement($n,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},q?ke.createElement(Sa,{id:q.id,label:"Event log",text:z,selected:!1,maxWidth:s,height:bn}):null)}let T=w.reduce((q,z)=>br(z)||z.id===l||z.id===m||z.id===u?q+1:q,0),M=2,U=3,ne=T,be=t-U-ne-M,Q=(q,z)=>q.id===d?ke.createElement(Sa,{key:q.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:z,maxWidth:s,height:be}):br(q)?ke.createElement(Mu,{key:q.id,parent:q,selected:z,selectedIndex:r}):q.id===l?ke.createElement($n,{key:q.id,paddingTop:1},ke.createElement(ze,{isSelected:z}),ke.createElement(Ca,{backgroundColor:S.secondary,color:z?S.accent:S.primary},` Comments (${n}) \u203A\u203A `)):q.id===m?ke.createElement($n,{key:q.id,paddingTop:1},ke.createElement(ze,{isSelected:z}),ke.createElement(Ca,{backgroundColor:S.secondary,color:z?S.accent:S.primary},` Attachments (${p}) \u203A\u203A `)):q.id===u?ke.createElement($n,{key:q.id,paddingTop:1},ke.createElement(ze,{isSelected:z}),ke.createElement(Ca,{backgroundColor:S.secondary,color:z?S.accent:S.primary}," History \u203A\u203A ")):null;return ke.createElement($n,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},w.map((q,z)=>Q(q,f&&r===z)))}});import{Box as uy}from"ink";import Ds from"react";var my,Bu,_u=y(()=>{"use strict";he();su();Ou();my=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:d,width:l})=>{let u=t.context,m=u===B.TICKET||u===B.FIELD_LIST||u===B.FIELD,p=u===B.BOARD||u===B.SWIMLANE,f=u===B.TICKET?t:r.find(T=>T.context===B.TICKET),I=Math.floor(l/3),N=Math.floor(l/Math.max(e.length,1)),A=Math.min(N,I),w=s==="dense";return Ds.createElement(uy,{flexDirection:"row",height:d},p&&e.map((T,M)=>{let U=t.id===T.id,ne=U?n:-1,be=t.context===B.BOARD&&n===M;return Ds.createElement(ou,{key:T.id,height:d,width:A,swimlane:T,isSelected:be,isDense:w,isFocused:U,listSelectedIndex:ne,mode:o})}),m&&f&&Ds.createElement(Fu,{height:d,ticket:f}))},Bu=Ds.memo(my)});import Uu from"node:fs";import py from"node:path";import gy from"react";import{render as fy}from"ink";import{Writable as hy}from"node:stream";var mo,vy,yy,by,xy,$u,ju=y(()=>{"use strict";_u();he();C();k();pe();Ue();mo=e=>String(e).padStart(2,"0"),vy=e=>{let t=e.getUTCFullYear(),n=mo(e.getUTCMonth()+1),r=mo(e.getUTCDate()),o=mo(e.getUTCHours()),s=mo(e.getUTCMinutes()),d=mo(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${d}`},yy=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",by=async(e,{width:t,height:n})=>{let r="",o=new hy({write(d,l,u){let m=xy(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=fy(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),r},xy=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),$u=async()=>{let{viewMode:e}=xe(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=g(),d=r.find(M=>M.context==="BOARD");if(!d)return i("No board found to export");let l=120,u=40,m=await by(gy.createElement(Bu,{height:u,width:l,swimlanes:(s[d.id]??[]).filter(M=>M!==void 0&&xn(M)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:u});if(!m)return i("Failed to render board export");let p=$o(process.cwd());if(a(p))return i("Unable to export, epiq root not found");let f=new Date,I=vy(f),N=`board_${yy(d.title)}_${I}.md`,A=_d(p.value);Uu.mkdirSync(A,{recursive:!0});let w=py.join(A,N),T=`# Board - ${d.title}
|
|
57
61
|
Date: ${f.toISOString()}
|
|
58
62
|
|
|
59
63
|
\`\`\`text
|
|
60
64
|
${m}
|
|
61
65
|
\`\`\`
|
|
62
|
-
`;return
|
|
66
|
+
`;return Uu.writeFileSync(w,T,"utf8"),c("Exported board layout",w)}});var Fs,Aa=y(()=>{"use strict";Fs=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null}});import{useSyncExternalStore as OM}from"react";var Ta,Iy,Ey,ur,Ry,gn,Os=y(()=>{"use strict";C();Iy=new Set,Ey=()=>{for(let e of Iy)e()},ur=()=>{if(!Ta)throw new Error("Ui state not initialized. Call initUiState() first.");return Ta},Ry=e=>{let t=ur();return Ta=e(t),Ey(),c("UX state updated",null)},gn=e=>Ry(t=>({...t,...e}))});import{spawn as Ny}from"node:child_process";function po(e){let t=process.platform,o=Ny(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 wa=y(()=>{"use strict"});import{spawn as WM,spawnSync as Sy}from"node:child_process";import Cy from"node:os";import Hu from"node:path";import{ulid as Ay}from"ulid";function Wu(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 Ty(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Gu(){let{preferredEditor:e}=xe(),t=[e?Ty(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function qu(e){let[t=""]=Wu(e);return/(^|\/)code(-insiders)?$/.test(t)}function wy(e,t){let[n="",...r]=Wu(e);return{command:n,args:[...r,...t]}}function My(e,t){return wy(e,qu(e)?["--wait",t]:[t])}function Vu(e){let t=Hu.join(Cy.tmpdir(),"epiq");qe.mkDir(t);let n=Hu.join(t,Ay());qe.writeToFile(n,e??"");let r=Gu();for(let o of r){let{command:s,args:d}=My(o,n);if(!s)continue;let l=Sy(s,d,{stdio:"inherit"});if(!l.error&&l.status===0){let u=qe.readFile(n);if(u==null)return i("Unable to read edited file");let m=u.replace(/\r?\n$/,"");return c("Successfully edited",m)}}return i("Unable to open editor")}var Ma=y(()=>{"use strict";C();Ue();vs()});import{ulid as ka}from"ulid";var zu,ky,Ly,Ku=y(()=>{"use strict";Ma();Mn();gt();xt();he();C();Vn();ge();k();pe();cn();zu=async e=>{let{contextNode:t,selectedIndex:n}=g(),r=ae(t.id)[n];if(e.modifier===et.DESCRIPTION)return Ly();if(r&&xr(r))return ky(e);if(e.modifier===et.TITLE){let o=ve();if(a(o))return i("Unable to resolve user ID");let s=r;if(!s)return i("Missing node");if(s.readonly)return i("Cannot rename readonly node");let d=e.inputString.trim();if(!d)return i("Provide a title");let l=await Ct();return a(l)?l:O([{id:ka(),action:"edit.title",payload:{id:s.id,name:d},...o.value}],l.value)}return i("Unknown edit command")},ky=async e=>{let t=ve();if(a(t))return i("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=g(),o=ae(n.id)[r];if(!o||!xr(o))return i("Select a comment first");if(o.readonly)return i("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return i("Unable to resolve comment issue");let d=g().nodes[s];if(!d||!P(d))return i("Unable to resolve comment issue");if(d.readonly)return i("Cannot edit readonly issue");let l=o.id.split(":").at(0)??"",u=x.getComment(l);if(!u||u.deleted)return i("Unable to resolve comment");if(u.issue!==d.id)return i("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return i("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return i("Provide a comment");let p=await Ct();if(a(p))return p;let f=p.value;return O([{id:ka(),action:"edit.issue.comment",payload:{id:u.id,issue:d.id,md:m},...t.value}],f)},Ly=async()=>{let e=ve();if(a(e))return i("Unable to resolve user ID");let t=await Ct();if(a(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=g(),s=Xe([...r,o],"TICKET");if(a(s))return i("Edit target must be an issue");let d=s.value;if(!P(d))return i("Edit target must be an issue");if(d.readonly)return i("Cannot edit readonly issue");let l=ae(d.id).find(f=>f.title===se.DESCRIPTION);if(!l)return i("No target found");if(l.readonly)return i("Cannot edit readonly field");let u=d.props.description??"";if(typeof u!="string")return i("Selected field is not editable text");let m=Vu(u);if(a(m))return i("Failed to edit field");let p=m.value;return p===u?c("No changes made",null):O([{id:ka(),action:"edit.description",payload:{id:d.id,md:p},...e.value}],n)}});import La from"node:fs";import Py from"node:path";var Yu,Xu=y(()=>{"use strict";C();Nt();Yu=async e=>{let t=Py.join(e,".gitignore"),n=La.existsSync(t)?La.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
63
67
|
`).map(u=>u.trim()),s=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(s.length===0)return c("Local epiq paths already ignored",!1);let l=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
64
68
|
`);return n=n.trimEnd()+`
|
|
65
69
|
|
|
66
70
|
${l}
|
|
67
|
-
`,
|
|
68
|
-
`));let Ws=je();if(a(Ws))return te(16,Ws.message);let{rootNodeId:zp,nodes:Yp}=Ws.value,Ha=Yp[zp];return Ha?(_.navigate({contextNode:Ha,selectedIndex:0}),E({hasProjectDefinition:!0,mode:h.DEFAULT}),c(mn,null)):te(16,"Unable to resolve initialized root node")}});import{ulid as yy}from"ulid";function Sa(e){let t=Gu();if(a(t))return t;let{contextNode:n,nodes:r}=g();if(!n.parentNodeId)return i("Missing parent node id");let o=r[n.parentNodeId];if(!o)return i("Missing parent node");let s=le(o.id),d=s.findIndex(({id:m})=>m===n.id);if(d<0)return i("Current node not found among siblings");let l=s[d+e];if(!l)return i("Missing sibling node");let u=qu({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Vu(u.value)}function Ca(e){let t=Gu();if(a(t))return t;let{contextNode:n,selectedIndex:r}=g(),s=le(n.id)[r+e];if(!s)return i("Missing sibling node");let d=qu({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:Vu(d.value)}var Wu,cn,so,Gu,Na,qu,Vu,Aa=y(()=>{"use strict";Ft();mt();C();xt();k();Wu=null,cn=()=>structuredClone(Wu),so=e=>{Wu=e},Gu=()=>{let{contextNode:e,selectedIndex:t}=g(),r=le(e.id)[t];return r?c("Resolved selected child",r):i("Target node not found")},Na=({id:e,parentId:t,position:n={at:"end"}})=>{let r=le(t).filter(o=>o.id!==e);return Uo(r,n)},qu=({id:e,parentId:t,position:n={at:"end"}})=>{let r=fe();if(a(r))return i("Unable to resolve user ID");let o=Na({parentId:t,id:e,position:n});return a(o)?o:c("Created pending move state",{id:yy(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Vu=e=>{so(e);let t=Xt(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as by}from"ulid";var Ku,Ts,zu,Yu=y(()=>{"use strict";Qe();Aa();Sn();mt();ce();C();xt();Ie();k();ue();Ku=()=>{let e=cn();if(!e)return i("No pending move state");let t=e.payload.id,n=e.payload.parent,r=g().nodes[n];if(!r)return i("Move parent not found");let o=le(n).findIndex(s=>s.id===t);return o===-1?i("Moved node not found among rendered children"):(_.navigate({contextNode:r,selectedIndex:o}),c("Synchronized navigation to moved node",null))},Ts=(e,t="Moved preview")=>{if(a(e))return e;let n=Ku();return a(n)?n:(E({mode:h.MOVE}),c(t,null))},zu=async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=ie().commandMeta,{contextNode:n,selectedIndex:r}=g(),o=le(n.id)[r];if(!o)return E({mode:h.DEFAULT}),i("No move target");if(t==="start"){if(o.readonly)return i("Target node is read-only");if(r===-1)return i("No item selected");if(!o.parentNodeId)return i("Target has no parent");let s=le(o.parentNodeId),d=s.findIndex(({id:f})=>f===o.id);if(d===-1)return i("Target not found among siblings");let l=s[d-1],u=s[d+1],m=u!=null?{at:"before",sibling:u.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},p=Na({parentId:o.parentNodeId,id:o.id,position:m});return a(p)?p:(so({id:by(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),E({mode:h.MOVE}),c("Move initialized",null))}if(t==="next")return Ts(Ca(1));if(t==="previous")return Ts(Ca(-1));if(t==="to-next")return Ts(Sa(1));if(t==="to-previous")return Ts(Sa(-1));if(t==="confirm"){let s=cn();if(!s)return i("No pending move to confirm");let d=await Rt();if(a(d))return d;let l=B([s],d.value);if(a(l))return l;let u=Ku();return a(u)?u:(so(null),E({mode:h.DEFAULT}),c("Moved item",null))}return t==="cancel"?(so(null),E({mode:h.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as xy,ulid as Iy}from"ulid";var Ey,ws,Ta=y(()=>{"use strict";C();Ey=xy(),ws=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=Ey();return c("Created issue events",[{id:Iy(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as Ms}from"ulid";var Xu,Ju=y(()=>{"use strict";Qe();Ta();Sn();mt();yt();C();me();xt();k();ue();Xu=async(e,t)=>{let n=fe();if(a(n))return i("Unable to resolve user ID");let r=await Rt();if(a(r))return r;let o=r.value;if(!t.inputString)return i(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:d,selectedIndex:l}=g(),u=m=>{let p=B([m],o);if(a(p))return p;let f=x.getNode(p.value[0].result.id);if(!f)return i("Created node not found");if(!f.parentNodeId)return p;let I=x.getNode(f.parentNodeId);return I?(_.navigate({contextNode:I,selectedIndex:x.getSiblings(f.parentNodeId).findIndex(({id:N})=>N===f.id)}),p):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=x.getNode(m);if(!p)return i("Workspace not found");let f=Cn(p.id,n.value,o);return a(f)?f:u({id:Ms(),action:"add.board",payload:{id:Ms(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=Ke(s,"BOARD");if(a(m))return i("Unable to add swimlane in this context");let p=Cn(m.value.id,n.value,o);return a(p)?p:u({id:Ms(),action:"add.swimlane",payload:{id:Ms(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=se(d.id)[l],p=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let U=Ke(s,"SWIMLANE");return a(U)?null:U.value})();if(!p)return i("Unable to add issue in this context");let f=Cn(p.id,n.value,o);if(a(f))return f;let I=ws({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(a(I))return I;let N=I.value,A=B([...N],o);if(a(A))return A;if(!A.value[0])return i("Issue creation failed");let M=N.find(U=>U.action==="add.issue")?.payload.id;return M?(_.navigate({contextNode:p,selectedIndex:x.getSiblings(p.id).findIndex(({id:U})=>U===M)}),c("Issue created",null)):i("Unable to determine ticket id")}return c("Success",null)}});var Qu,Zu=y(()=>{"use strict";ut();ct();Fr();Ur();kr();Jt();C();Pt();k();qo();Qu=async e=>{let t=Ne({repoRoot:e});if(a(t))return Lr(3,t.message);let n=await An({repoRoot:e,stateBranchRoot:t.value,stateBranchName:Eo().stateBranch});if(a(n))return Lr(3,n.message);let r=await j({cwd:t.value,args:["pull","--ff-only"]});a(r)&&logger.info(3,r.message);let o=Bt(t.value);if(a(o))return Lr(3,o.message);let{events:s,unreadable:d}=o.value,l=Zt(s,d);if(a(l))return Lr(4,l.message);E({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let u=Pi({root:e});return a(u)&&logger.info(u.message),c("Loaded project",void 0)}});import Ry from"node:os";import em from"node:path";var Ny,Sy,tm,nm=y(()=>{"use strict";Zu();Ur();C();Ie();k();ue();Ny=e=>e==="~"||e.startsWith("~/")?em.join(Ry.homedir(),e.slice(1)):e,Sy=(e,t)=>{let n=e.trim();if(!n)return i("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?c("Resolved recent project",o.root):i(`No recent project #${n}`)}let r=Xe(em.resolve(Ny(n)));return a(r)?i(`No epiq project at ${n}`):c("Resolved project path",r.value)},tm=async()=>{let e=hs();if(G(""),g().hasProjectDefinition)return i("Already in a project; run epiq from another directory");let t=Zo({exclude:process.cwd()}),n=a(t)?[]:t.value,r=Sy(e,n);if(a(r))return i(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(l){return i(`Unable to enter ${o}: ${l instanceof Error?l.message:String(l)}`)}let d=await Qu(o);return a(d)?(process.chdir(s),i(d.message)):c(`Opened ${Dc(o)}`,null)}});var ks,wa=y(()=>{"use strict";Qe();Jt();Ft();C();k();ks=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=g(),s=xi(n,t);if(a(s))return i(s.message);let{appliedEvents:d,unappliedEvents:l}=s.value,u=Ht();if(a(u))return u;let m=Dt(d),{fatal:p,skipped:f}=In(m);if(p.length>0)return Ht(),E(o),i(p.map(N=>N.message).join(", "));En(f);let I=g().nodes[e];return I?(_.navigate({contextNode:I,selectedIndex:r}),c("",{unappliedEvents:l})):(Ht(),E(o),i("Board did not exist at that date"))}});var Cy,Ay,Ty,Ls,Ps,Bn,rm,wy,om,Ma=y(()=>{"use strict";it();io();Ft();ce();C();k();Cy=20,Ay=16,Ty=150,Ls=null,Ps=null,Bn=()=>{Ls!==null&&(clearInterval(Ls),Ls=null),Ps!==null&&(clearTimeout(Ps),Ps=null)},rm=()=>{Bn(),E({mode:h.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},wy=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)},om=({events:e,startTime:t,durationMs:n})=>{Bn();let r=e.length,o=mr(e.map(f=>pr(f))).map(f=>f??t),s=o[r-1]??Date.now(),d=wy(o),l=Math.max(1,Math.round(n*Cy/1e3)),u=Math.max(Math.round(n/l),Ay),m=0,p=0;E({mode:h.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Ls=setInterval(()=>{m++;let f=m/l,I=[],N,A;for(;p<r&&d[p]<=f;){let T=e[p],M=Xt(T);if(a(M)){if(Ar(M)){p++;continue}rm();return}I.push(...ui(T)),N=T,A=o[p],p++}if(p>=r||m>=l){for(;p<r;p++){let M=Xt(e[p]);if(a(M)&&!Ar(M))break}let T=g().replay;E({unappliedEvents:[],replay:T&&{...T,progress:1,appliedCount:r}}),Bn(),Ps=setTimeout(rm,Ty);return}let w=g().replay;E({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:N?A??w?.currentTime??t:w?.currentTime??t,currentLabel:N?ka(N):w?.currentLabel??"",flashNodeIds:N?[...new Set(I)]:w?.flashNodeIds??[]}})},u)}});var sm,im=y(()=>{"use strict";ut();it();Jt();Ft();ce();yt();C();Ie();k();Hr();wa();Ma();sm=async()=>{let e=Ke(g().breadCrumb,"BOARD");if(a(e))return e;let t=await lt(process.cwd());if(a(t))return i("Unable to locate repo root");let n=Ne({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=ie().commandMeta;if(Bn(),r==="now"){let l=Gn(n.value);if(a(l))return i(l.message);let u=Ht();if(a(u))return u;let m=Dt(l.value),{fatal:p,skipped:f}=In(m);return p.length>0?i(p.map(I=>I.message).join(", ")):(En(f),E({mode:h.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),c("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let l=Ii(n.value);if(a(l))return l;let u=r==="prev"?g().eventLog.at(-1):g().unappliedEvents.at(0),m=u===void 0?null:pr(u),p=(u===void 0?null:l.value.get(u.id)??null)??(m===null?null:Ks(m));if(p===null)return i(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?p:p+1}else{let l=wn(r||o.trim());if(!l)return i("Invalid peek date");s=l.getTime()}let d=ks({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(d)?d:(E({mode:h.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:d.value.unappliedEvents,replay:null}),c("Peeking",!0))}});var am,dm=y(()=>{"use strict";ut();yt();C();Ie();k();Hr();wa();Ma();am=async()=>{let e=Ke(g().breadCrumb,"BOARD");if(a(e))return e;let t=await lt(process.cwd());if(a(t))return i("Unable to locate repo root");let n=Ne({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=ie().commandMeta,{dateInput:s,durationInput:d}=ss(r,o);if(Bn(),g().syncStatus.status==="syncing")return i("Cannot replay while syncing, try again in a moment");let l=wn(s);if(!l)return i("Invalid replay date");let u=d?os(d):15e3;if(u===null)return i("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=g(),f=ks({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(f))return f;let{unappliedEvents:I}=f.value;return I.length===0?(Ht(),E(p),c("Nothing to replay from that point",!0)):(om({events:I,startTime:m,durationMs:u}),c("Replaying board history",!0))}});import ky from"zod";var cm,lm=y(()=>{"use strict";kn();ce();C();Ie();Oe();k();cm=()=>{let e=ie().commandMeta.inputString,t=ky.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return i("Auto sync duration must be a number of at least 3000 ms");let n=ot({autoSyncDebounceMs:t.data});return a(n)?n:(tt({autoSyncIntervalMs:t.data}),E({mode:h.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))}});var um,mm=y(()=>{"use strict";$r();kn();ce();C();Ie();Oe();k();um=()=>{let e=ie().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=$c(e),n=ot({autoSync:t});return a(n)?n:(tt({autoSync:t}),E({mode:h.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var pm,gm=y(()=>{"use strict";kn();ce();C();Ie();Oe();k();pm=()=>{let e=ie().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return i("Invalid response");let n=ot({logLevel:e});return a(n)?n:(tt({logLevel:e}),E({mode:h.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});import{spawn as Ly}from"node:child_process";var Py,fm,hm=y(()=>{"use strict";C();Py=()=>{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"]}}},fm=async e=>new Promise(t=>{let{command:n,args:r}=Py();try{let o=Ly(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(i(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?c("Copied to clipboard",null):i(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(i(`Clipboard tool not available (${n})`))}})});var ao,vm,ym=y(()=>{"use strict";C();k();hm();Yt();jr();nn();ao=async(e,t)=>{if(!e.trim())return i(`Nothing to copy: ${t} is empty`);let n=await fm(e);return a(n)?n:c(`Copied ${t} to clipboard`,null)},vm=async e=>{let{breadCrumb:t,selectedNode:n}=g(),r=Wr({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return i("Nothing selected to copy from");switch(e.modifier){case Ee.REF:return ao(V(o.id),"ref");case Ee.TITLE:return ao(o.title,"title");case Ee.DESCRIPTION:return r?ao(r.props?.description??"","description"):i("No issue in scope");case Ee.TAGS:{if(!r)return i("No issue in scope");let s=en(r).map(({name:d})=>d);return ao(s.join(", "),"tags")}case Ee.ASSIGNEES:{if(!r)return i("No issue in scope");let s=tn(r).map(({name:d})=>d);return ao(s.join(", "),"assignees")}default:return i("Yank one of: ref, title, description, tags, assignees")}}});var bm,xm=y(()=>{"use strict";wi();ce();C();Ie();k();bm=async()=>{G(""),E({mode:h.DEFAULT});let e=je();if(a(e))return i(e.message);if(e.value.syncStatus.status==="syncing")return i("Sync already in progress");E({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Xo();return a(t)?(E({syncStatus:{msg:t.message,status:"failed"}}),t):(E({mode:h.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as Be}from"ulid";var Dy,Im,Wt,Em,Rm=y(()=>{"use strict";me();Mu();Qe();ur();kn();Sn();mt();ya();Wn();ce();yt();ge();C();me();xt();Ie();Oe();k();As();ue();xa();Tn();Zi();nn();Yr();Ou();Hu();Yu();Ju();nm();im();dm();lm();qi();mm();gm();ym();xm();Dy=e=>e.action==="add.issue.comment",Im=()=>{let{eventLog:e=[],contributors:t}=g(),n=new Map,r=new Set;for(let o of e)o.userId&&(n.set(o.userId,o.userName??""),r.add(o.userId));for(let o of Object.values(t))n.set(o.id,o.name);return[...n.entries()].map(([o,s])=>({id:o,name:s,isExternal:!r.has(o)}))},Wt=async()=>{let e=await Rt();return a(e)?e:c("Resolved persist root",e.value)},Em=[{systemOnly:!0,intent:F.Move,description:"Internal move-state command",mode:h.COMMAND_LINE,action:zu},{intent:F.Delete,description:"Delete the currently selected node",mode:h.COMMAND_LINE,action:async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=se(t.id)[n];if(!r)return i("Unable to resolve child to delete");let o=await Wt();if(a(o))return o;if(r.context==="COMMENT"){let s=r.id,d=L(t)?t.id:t.parentNodeId;if(!d)return i("Unable to resolve comment issue");let l=g().nodes[d];if(!l||!L(l))return i("Unable to resolve comment issue");let u=l.log?.filter(Dy).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):B([{id:Be(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],o.value):i("Unable to resolve comment")}return B([{id:Be(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:h.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ie().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(d=>xe(v.FILTER).map(l=>l.split(n)[0]).includes(d))(r))return i("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return oe(d=>({...d,filters:e==="clear"?[]:[...d.filters,s],mode:h.DEFAULT})),c("Filter updated",null)}},{intent:F.ViewHelp,description:"Open the help screen",mode:h.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return dn({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),E({mode:h.HELP}),c("Viewing help",null)}},{intent:F.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:h.COMMAND_LINE,action:async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=se(t.id)[n];if(!r)return i("Unable to close issue, no target found");if(!L(r))return i("Cannot close in this context");let o=g().nodes[be];if(!o)return i("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return i("Issue is already closed");let s=await Wt();if(a(s))return s;let d=s.value,l=Qt(o.id,r.id,{at:"end"},e.value,d);if(a(l))return l;let u=B([{id:Be(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...e.value}],d);return a(u)?u:c("Issue closed",null)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:h.COMMAND_LINE,action:async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=se(t.id)[n];if(!r)return i("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):On(r.id,"TICKET");if(a(o))return i("Cannot reopen in this context");let s=o.value,d=g().nodes[be];if(!d)return i("Unable to locate closed swimlane");if(s.parentNodeId!==d.id)return i("Issue is not closed");if(!L(s))return i("Target node is not issue");let l=Cs(s);if(!l)return i("Unable to resolve previous parent from issue history");if(l===d.id)return i("Previous parent resolves to closed swimlane");let u=g().nodes[l];if(!u)return i("Previous parent no longer exists");let m=await Wt();if(a(m))return m;let p=m.value,f=Qt(u.id,s.id,{at:"end"},e.value,p);if(a(f))return f;let I=B([{id:Be(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...e.value}],p);return a(I)?I:c("Issue reopened",null)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Init,description:"Initialize Epiq in the current git repository",mode:h.COMMAND_LINE,action:ju},{intent:F.OpenProject,description:"Open a recently used epiq project, by number or path",mode:h.COMMAND_LINE,action:tm,onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.NewItem,description:"Create a new board, swimlane, or issue",mode:h.COMMAND_LINE,action:Xu,onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Rename,description:"Rename the currently selected node",mode:h.COMMAND_LINE,action:async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=se(t.id)[n];if(!r)return i("Missing node");if(r.readonly)return i("Cannot rename readonly node");let o=hs();if(!o)return i("Provide a title");let s=await Wt();return a(s)?s:B([{id:Be(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.UntagTicket,description:"Remove a tag from the selected issue",mode:h.COMMAND_LINE,action:async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=ie().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let o=x.findTagByName(r);if(!o)return i(`Tag "${r}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid untag target");let d=On(s.id,"TICKET");if(a(d))return i("Unable to untag issue in this context");let l=d.value;if(!L(l))return i("Target node is not issue");if(!(l.props.tags??[]).includes(o.id))return i("Issue is not tagged with that tag");let m=await Wt();return a(m)?m:B([{id:Be(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.TagTicket,description:"Add or create a tag on the selected issue",mode:h.COMMAND_LINE,action:async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=ie().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let{selectedNode:o}=g();if(!o)return i("Invalid tag target");let s=On(o.id,"TICKET");if(a(s))return i("Unable to tag issue in this context");let d=s.value;if(!L(d))return i("Target node is not issue");let l=await Wt();if(a(l))return l;let u=x.findTagByName(r),m=u?.id??Be();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):B([...u?[]:[{id:Be(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:Be(),action:"add.issue.tag",payload:{id:d.id,tag:m},...e.value}],l.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.AssignUserToTicket,description:"Assign a user to the selected issue",mode:h.COMMAND_LINE,action:async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=ie().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return i("Provide an assignee");let{selectedIndex:d,contextNode:l}=g(),u=se(l.id)[d];if(!u)return i("Invalid assign target");let m=On(u.id,"TICKET");if(a(m))return i("Unable to assign issue in this context");let p=m.value;if(!L(p))return i("Target node is not issue");let f=await Wt();if(a(f))return f;let I=Im(),N=!o&&s.toLowerCase()==="me",A,w;if(N)A=e.value.userId,w=I.find(U=>U.id===A)?.name??e.value.userName;else{let U=I.filter(ve=>ve.name===s);if(U.length>1)return i(`"${s}" matches ${U.length} contributors (${U.map(ve=>ve.id).join(", ")}). Assign from the GUI to choose by id.`);let ee=U[0];if(!ee&&!o)return i(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);A=ee?.id??Be(),w=ee?.name??s}if((p.props.assignees??[]).includes(A))return i("Assignee already assigned");let M=!!g().contributors[A];return B([...M?[]:[{id:Be(),action:"create.contributor",payload:{id:A,name:w},...e.value}],{id:Be(),action:"add.issue.assignee",payload:{id:p.id,assignee:A},...e.value}],f.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:h.COMMAND_LINE,action:async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=ie().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee to remove");let{selectedNode:o}=g();if(!o)return i("Invalid unassign target");let s=On(o.id,"TICKET");if(a(s))return i("Unable to unassign in this context");let d=s.value;if(!L(d))return i("Target node is not issue");let l=d.props.assignees??[],u=r.toLowerCase()==="me",m=u?l.filter(I=>I===e.value.userId):Im().filter(I=>I.name===r&&l.includes(I.id)).map(I=>I.id);if(m.length>1)return i(`"${r}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return i(u?"Issue is not assigned to you":`Issue is not assigned to "${r}"`);let f=await Wt();return a(f)?f:B([{id:Be(),action:"remove.issue.assignee",payload:{id:d.id,assignee:p},...e.value}],f.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Comment,description:"Add a comment to the selected issue",mode:h.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return i("Provide a comment");if(n.length>4e3)return i(`Cannot exceed ${4e3} characters`);let r=fe();if(a(r))return i("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=g(),d=Ke([...o,s],"TICKET");if(a(d))return i("Edit target must be an issue");let l=d.value;if(!l)return i("Invalid comment target");let u=l.context==="TICKET"?c("Resolved ticket",l):On(l.id,"TICKET");if(a(u))return i("Unable to comment on issue in this context");let m=u.value;if(!L(m))return i("Target node is not issue");let p=await Wt();return a(p)?p:B([{id:Be(),action:"add.issue.comment",payload:{id:Be(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Sync,description:"Pull, commit, and push Epiq state",mode:h.COMMAND_LINE,action:bm},{intent:F.Peek,description:"View board state at another point in time",mode:h.COMMAND_LINE,action:sm},{intent:F.Replay,description:"Replay board history forward from a point in time",mode:h.COMMAND_LINE,action:am},{intent:F.Export,description:"Export the current board layout to markdown",mode:h.COMMAND_LINE,action:async()=>{let e=await wu();return a(e)?e:(E({mode:h.DEFAULT}),c("Export successful",!0))}},{intent:F.Exit,description:"Exit the application",mode:h.COMMAND_LINE,action:async()=>(_.exit(),c("Exit successful",!0))},{intent:F.Edit,description:"Edit title or description",mode:h.COMMAND_LINE,action:async(e,t)=>Bu(t),onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:h.COMMAND_LINE,action:async(e,t)=>vm(t),onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:h.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case pe.USERNAME:{if(process.env[ht])return i(`Cannot change the configured user while ${ht} names this process`);let r=cs();if(a(r))return r;let{userId:o,preferredEditor:s,userName:d}=r.value,l=n||d,u=o||Be();if(!l||!u)return i("Unable to resolve user name or id");let m=ot({userName:l,userId:u,preferredEditor:s??""});return a(m)?m:(tt({userName:l,userId:u}),E({mode:h.DEFAULT}),c(`Username set to "${l}"`,null))}case pe.EDITOR:{if(!n)return i("No editor provided");let r=ot({preferredEditor:n});return a(r)?r:(tt({preferredEditor:n}),E({mode:h.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case pe.VIEW:{if(n!=="wide"&&n!=="dense")return i("Invalid view mode");let r=ot({viewMode:n});return a(r)?r:(tt({viewMode:n}),E({mode:h.DEFAULT}),c(`View set to "${n}"`,null))}case pe.AUTOSYNC:return um();case pe.LOG_LEVEL:return pm();case pe.SYNC_DEBOUNCE_MS:return cm();case pe.ATTACHMENT_MAX_KB:return ol();default:return i("Unknown config command")}}},{intent:F.Coffee,description:"Sponsor the development of Epiq!",mode:h.COMMAND_LINE,action:()=>{let e=ie().commandMeta.modifier;return e==="custom"?oo("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):oo(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),G(""),c("Thanks you!",null)}}]});var Fy,Mt,La=y(()=>{"use strict";Jo();ms();Zi();Rm();C();Ie();Oe();k();Fy=new Set(["peek","replay","filter","view-help","yank"]),Mt=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ie();if(!t)return i("No command to confirm");if(!e&&n===rn.Invalid)return i("Invalid command");let s=Dl(t);Ml();let{readOnly:d}=g();if(d&&!Fy.has(s))return Xr({status:kt.Fail,message:"Command not available in readonly state",value:null});let l=Em.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return Xr({status:kt.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return Xr({status:kt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?Xr(u):(kl({addToHistory:!e}),l.onSuccess?.(),ye().autoSync&&kc(),u)}});var Ds,Fs,Nm,Sm=y(()=>{"use strict";C();ce();k();fn();La();Aa();Ie();Ds=[{intent:P.Exit,mode:h.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:h.COMMAND_LINE}),G("move cancel"),Mt({isForceExecutedBySystem:!0}))},{intent:P.InitMove,mode:h.DEFAULT,description:"[m] move (init/confirm)",action:()=>(E({mode:h.COMMAND_LINE}),G("move start"),Mt({isForceExecutedBySystem:!0}))},{intent:P.ConfirmMove,mode:h.MOVE,action:()=>(E({mode:h.COMMAND_LINE}),G("move confirm"),Mt({isForceExecutedBySystem:!0}))}],Fs=[{intent:P.MovePreviousItem,mode:h.MOVE,action:()=>cn()?(E({mode:h.COMMAND_LINE}),G("move previous"),Mt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:P.MoveNextItem,mode:h.MOVE,action:()=>cn()?(E({mode:h.COMMAND_LINE}),G("move next"),Mt({isForceExecutedBySystem:!0})):i("No pending move")}],Nm=[{intent:P.MoveToNextContainer,mode:h.MOVE,action:()=>cn()?(E({mode:h.COMMAND_LINE}),G("move to-next"),Mt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:P.MoveToPreviousContainer,mode:h.MOVE,action:()=>cn()?(E({mode:h.COMMAND_LINE}),G("move to-previous"),Mt({isForceExecutedBySystem:!0})):i("No pending move")}]});var Cm,Am=y(()=>{"use strict";ge();Sm();Cm={[O.WORKSPACE]:[...Ds,...Fs],[O.BOARD]:[...Ds,...Fs],[O.SWIMLANE]:[...Ds,...Fs,...Nm],[O.TICKET]:[],[O.FIELD]:[],[O.FIELD_LIST]:[],[O.TEXT]:[],[O.COMMENT]:[]}});import By from"node:fs";import Oy from"node:path";var Tm,wm=y(()=>{"use strict";ut();qr();C();ue();xa();Tm=e=>{let t=Xe(process.cwd());if(a(t))return i("Unable to resolve project root");let n=Ne({repoRoot:t.value});if(a(n))return i(n.message);let r=Gr(e.hash,e.ext),o=Oy.join(ko(n.value),r);return By.existsSync(o)?(oo(o),c(`Opened ${e.name}`,null)):i("Attachment file not found \u2014 run :sync to fetch it")}});var Mm,km,Lm=y(()=>{"use strict";ce();C();Ie();k();As();fn();Qe();Mm=()=>{G("");let{pendingNavTarget:e}=ir();E({mode:h.DEFAULT}),e&&_.navigate(e),dn({pendingNavTarget:void 0})},km=[{intent:P.ExitCommandLine,mode:h.HELP,action:()=>(Mm(),c("Exiting help",null))},{intent:P.Exit,mode:h.HELP,action:()=>(Mm(),c("Closed help",null))},{intent:P.NavPreviousItem,mode:h.HELP,description:"[arrows/hjkl] navigate",action:()=>(_.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:P.NavNextItem,mode:h.HELP,action:()=>(_.navigateToNextItem(),c("Navigating to next help item",null))},{intent:P.NavToPreviousContainer,mode:h.HELP,action:()=>(_.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:P.NavToNextContainer,mode:h.HELP,action:()=>(_.navigateToNextContainer(),c("Navigating to next help container",null))}]});var _y,Pm,Dm,Fm=y(()=>{"use strict";ce();ge();C();Ie();k();As();fn();Qe();_y=e=>{E({mode:h.COMMAND_LINE});let{pendingNavTarget:t}=ir();t&&_.navigate(t),dn({pendingNavTarget:void 0}),G(`${e} `)},Pm=()=>{G("");let{pendingNavTarget:e}=ir();e&&_.navigate(e),dn({pendingNavTarget:void 0}),E({mode:h.DEFAULT})},Dm=[{intent:P.InitCommandPalette,mode:h.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{G("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return dn({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),E({mode:h.PALETTE}),c("Opening command palette",null)}},{intent:P.Confirm,mode:h.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!Ja(e))return i("Command only applicable on text nodes");if(e.props.disabled)return i("Command is not available in this context");let t=e.title;return t?(_y(t),c("Selected command",t)):c("No command selected",null)}},{intent:P.ExitCommandLine,mode:h.PALETTE,action:()=>(Pm(),c("Exiting palette",null))},{intent:P.Exit,mode:h.PALETTE,action:()=>(Pm(),c("Closed command palette",null))},{intent:P.NavPreviousItem,mode:h.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(_.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:P.NavNextItem,mode:h.PALETTE,action:()=>(_.navigateToNextItem(),c("Navigating to next item",null))},{intent:P.NavToPreviousContainer,mode:h.PALETTE,action:()=>(_.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:P.NavToNextContainer,mode:h.PALETTE,action:()=>(_.navigateToNextContainer(),c("Navigating to next container",null))}]});var Bm,Om=y(()=>{"use strict";Tn();nn();ce();C();Hn();me();xt();Ie();k();wm();fn();Lm();Fm();Qe();Bm=[...km,...Dm,{intent:P.AddItem,mode:h.DEFAULT,description:"[n] new...",action:()=>(E({mode:h.COMMAND_LINE}),G(`${v.NEW} `),c("Adding new item",null))},{intent:P.Delete,mode:h.DEFAULT,description:"[d] delete",action:()=>(E({mode:h.COMMAND_LINE}),G(`${v.DELETE} `),c("Deleting item",null))},{intent:P.InitCommandLine,mode:h.DEFAULT,description:"[:] focus command line",action:()=>(E({mode:h.COMMAND_LINE}),G(""),c("Entering command line mode",null))},{intent:P.Confirm,mode:h.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!le(e?.id??"")?.length){let r=e?x.getAttachment(e.id):void 0;if(r)return Tm(r);if(e?.title===re.DESCRIPTION)return E({mode:h.COMMAND_LINE}),G(`${v.EDIT} description `),c("Propose command",!0);if(e?.title===re.ASSIGNEES)return E({mode:h.COMMAND_LINE}),G(`${v.ASSIGN} `),c("Propose command",!0);if(e?.title===re.TAGS)return E({mode:h.COMMAND_LINE}),G(`${v.TAG} `),c("Propose command",!0);if(t.title===re.DESCRIPTION&&e?.context==="TEXT")return E({mode:h.COMMAND_LINE}),G(`${v.EDIT} description `),c("Propose command",!0)}return _.enterChildNode(),c("Entering context",null)}},{intent:P.Yank,mode:h.DEFAULT,description:"[y] yank to clipboard",action:()=>{let{selectedNode:e}=g(),t=e?.title===re.DESCRIPTION?Ee.DESCRIPTION:e?.title===re.TAGS?Ee.TAGS:e?.title===re.ASSIGNEES?Ee.ASSIGNEES:Ee.REF,r=xe(v.YANK).includes(t)?t:Ee.REF;return E({mode:h.COMMAND_LINE}),G(`${v.YANK} ${r}`),c("Propose command",!0)}},{intent:P.EditTitle,mode:h.DEFAULT,description:"[r] rename title",action:()=>(E({mode:h.COMMAND_LINE}),G(`${v.EDIT} title ${g().selectedNode?.title}`),c("Exiting context",null))},{intent:P.EditDescription,mode:h.DEFAULT,description:"[e] edit description",action:()=>(E({mode:h.COMMAND_LINE}),G(`${v.EDIT} description `),c("Exiting context",null))},{intent:P.Exit,mode:h.DEFAULT,description:"[q] exit context",action:()=>(_.enterParentNode(),c("Exiting context",null))},{intent:P.NavPreviousItem,mode:h.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(_.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:P.NavNextItem,mode:h.DEFAULT,action:()=>(_.navigateToNextItem(),c("Navigating to next item",null))},{intent:P.NavToPreviousContainer,mode:h.DEFAULT,action:()=>(_.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:P.NavToNextContainer,mode:h.DEFAULT,action:()=>(_.navigateToNextContainer(),c("Navigating to next container",null))}]});var Uy,$y,_m,Um=y(()=>{"use strict";Ie();Uy=500,$y=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),_m=e=>{let t=$y(e);t&&fs(n=>(n+t).slice(0,Uy))}});var jy,Hy,$m,jm=y(()=>{"use strict";Um();ce();C();Ie();k();fn();La();jy=[h.COMMAND_LINE,h.PALETTE],Hy=e=>[{intent:P.MoveCursorLeft,mode:e,action:()=>(Ji(-1),c("Moving cursor left",null))},{intent:P.MoveCursorRight,mode:e,action:()=>(Ji(1),c("Moving cursor right",null))},{intent:P.MoveCursorLeftOfWord,mode:e,action:()=>(Qi("left"),c("Moving cursor left of word",null))},{intent:P.MoveCursorRightOfWord,mode:e,action:()=>(Qi("right"),c("Moving cursor right of word",null))},{intent:P.AutoCompleteCommand,mode:e,action:()=>(fs((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=g().selectedNode?.title??""),r+o}),c("Auto-completing command",null))},{intent:P.CaptureInput,mode:e,action:(t,{sequence:n})=>(_m(n??""),c("Capturing input",null))},{intent:P.EraseInput,mode:e,action:()=>(Tl(),c("Erasing input",null))},{intent:P.EraseInputWord,mode:e,action:()=>(wl(),c("Erasing input word",null))}],$m=[{intent:P.Confirm,mode:h.COMMAND_LINE,action:()=>(Mt(),c("Executing command",null))},{intent:P.ViewHelp,mode:h.DEFAULT,action:()=>(E({mode:h.HELP}),c("Viewing help",null))},...jy.flatMap(Hy),{intent:P.ExitCommandLine,mode:h.COMMAND_LINE,action:()=>(E({mode:h.DEFAULT}),c("Exiting command line",null))},{intent:P.GetLastCommandFromHistory,mode:h.COMMAND_LINE,action:()=>(Ll(),c("Getting last command from history",null))},{intent:P.GetNextCommandFromHistory,mode:h.COMMAND_LINE,action:()=>(Pl(),c("Getting next command from history",null))}]});import Gm from"chalk";var Bs,Hm,Wm,Pa,qm=y(()=>{"use strict";ce();ge();Pe();Bs=Gm.dim.hex(S.secondary2)(": for command line"),Hm="q to exit",Wm=`${Gm.hex(S.accent)("m")} to confirm`,Pa={[O.WORKSPACE]:[Bs],[O.BOARD]:[Bs],[O.BOARD+h.COMMAND_LINE]:[Bs],[O.SWIMLANE]:[Bs],[O.TICKET+h.HELP]:[Hm],[O.SWIMLANE+h.HELP]:[Hm],[O.TICKET]:[],[O.FIELD]:[],[O.SWIMLANE+h.MOVE]:[Wm],[O.TICKET+h.MOVE]:[Wm]}});var ar,Da,Vm=y(()=>{"use strict";Yt();ar=e=>e.trim().toLocaleLowerCase(),Da=(e,t)=>ar(e).includes(ar(t))});var Wy,Gy,Km,zm=y(()=>{"use strict";k();Yt();Vm();Wy=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},Gy=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},Km=(e,t)=>{let n=ar(t.value);if(!n)return!0;switch(t.target){case"title":return Da(e.title??"",n);case"description":return Da(e.props.description??"",n);case"tag":return Wy(e).map(ar).some(o=>o.includes(n));case"assignee":return Gy(e).map(ar).some(o=>o.includes(n));case"ref":return Cr(e.id,t.value);default:return!0}}});function Ym(e,t,n){let r=t[e];if(!r)return i("buildBreadCrumb(): current node not found");let o=[],s=r;for(;s&&(o.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let d=o[o.length-1];return!d||d.id!==n?i("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var Xm=y(()=>{"use strict";C()});var Jm,Qm=y(()=>{"use strict";Jm=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t}});import{useSyncExternalStore as qy}from"react";function _a(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return i("derive(): contextNodeId is missing");if(!r)return i("derive(): rootNode is missing");if(!o[r])return i("derive(): unable to find root node");let l=o[t];if(!l)return i("Unable to derive state, contextNode not found");let u=Ym(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,f=Pa[p+n]??Pa[p]??[],I=[...Bm,...Cm[p]??[],...$m],N=Jm(I),A=Ky(o,s),w=A[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:f,availableActions:I,actionIndex:N,selectedNode:w,renderedChildrenIndex:A})}function Tr(e){Fa=e;let t=Xe(process.cwd()),n=!1;if(!a(t)){let s=Lt(t.value);if(a(s))return i(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:h.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{},attachments:{}},o=_a(r);return a(o)?o:(Gt=o.value,Oa(),c("State initialized",null))}function oe(e){let t=g(),n=e(t);if(co)return Os=n,Gt={...t,...n},c("State updated",null);let r=_a(n);return a(r)?i(r.message??"Unable to update state"):(Gt=r.value,Oa(),c("State updated",null))}function Od(e){if(co)return c("Joined batch",e());co=!0,Os=null;let t=()=>{let n=Os;if(co=!1,Os=null,n===null)return null;let r=_a(n);return a(r)?i(r.message??"Unable to update state"):(Gt=r.value,Oa(),c("State updated",null))};try{let n=e(),r=t();return r&&a(r)?i(r.message):c("State updated",n)}finally{co&&t()}}var Gt,Fa,Ba,Oa,Vy,g,je,co,Os,E,qe,Ky,se,Ht,Nt,k=y(()=>{"use strict";Am();Om();jm();qm();Pt();ce();ge();C();ue();zm();Xm();Qm();Ba=new Set,Oa=()=>{for(let e of Ba)e()},Vy=e=>(Ba.add(e),()=>Ba.delete(e));g=()=>{if(!Gt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Gt},je=()=>Gt?c("Retrieved state",Gt):i("State not initialized. Call initWorkspaceState() first.");co=!1,Os=null;E=e=>oe(t=>({...t,...e})),qe=()=>qy(Vy,g,g),Ky=(e,t)=>{let n={};for(let r of Object.values(e))L(r)&&t.length>0&&!t.every(o=>Km(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,s)=>{let d=e[o.id],l=e[s.id];return!d||!l?0:d.rank.localeCompare(l.rank)});return n},se=e=>g()?.renderedChildrenIndex[e]??[],Ht=()=>Fa?Tr(Fa):i("Cannot reset state: no initial workspace found"),Nt=()=>Gt!==void 0});var On,zy,ln,x,me=y(()=>{"use strict";yt();ge();C();k();xt();On=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r)return i("Node not found");if(r.context===t)return c("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return c("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return i(`No ancestor found for context: ${t}`)},zy=(e,t)=>{let{nodes:n}=g(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},ln=(e,t)=>e?e.readonly?i({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:i("Node not found"),x={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return i("Contributor not found");if(n.userId&&n.userId!==t)return i("Contributor is already linked to another user");let r={...n,userId:t},o=oe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?i("Unable to link contributor to user"):c("Linked contributor to user",r)},deleteNode(e){oe(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create comment, missing issue");if(!L(t))return i("Can only comment on issues");let n=oe(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?i("Unable to create comment"):c("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return i("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return i("Unable to edit comment, missing issue");if(!L(r))return i("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=oe(d=>({...d,comments:{...d.comments??{},[e]:o}}));return a(s)?i("Unable to edit comment"):c("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return i("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=oe(o=>({...o,comments:{...o.comments??{},[e]:n}}));return a(r)?i("Unable to delete comment"):c("Deleted comment",n)},getComment(e){return g().comments?.[e]},getCommentsByIssue(e){return Object.values(g().comments??{}).filter(t=>t.issue===e&&!t.deleted)},createAttachment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create attachment, missing issue");if(!L(t))return i("Can only attach to issues");let n=oe(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?i("Unable to create attachment"):c("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return i("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=oe(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return a(r)?i("Unable to delete attachment"):c("Deleted attachment",n)},getAttachment(e){return g().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(g().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=g(),r=n[e];if(!r)return i("Edit target node not found");let o=ln(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return i("Rename target node not found");let r=ln(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=g();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return le(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=g(),o=this.getNode(e),s=this.getNode(t);if(!o)return i("Node not found");if(!s)return i("Target parent not found");if(r===e)return i("Cannot move root node");if(e===t)return i("Cannot move node into itself");let d=ln(o,"move");if(d)return d;if(zy(t,e))return i("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=g(),o=this.getNode(e);if(!o)return i("Node not found");if(r===e)return i("Cannot delete root node");let s=ln(o,"delete");if(s)return s;let d=new Set,l=m=>{let p=t[m];if(!(!p||d.has(m))){d.add(m);for(let f of le(p.id))l(f.id)}};l(e);let u={...structuredClone(t)};for(let m of d){if(!u[m])return i("Unable to locate node to delete");u[m]={...u[m],isDeleted:!0}}return n?(E({nodes:u}),c("Successfully tomb stoned",o)):i("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return i("Contributor not found");let n={...t,name:vo,tombstoned:!0},r=oe(o=>({...o,contributors:{...o.contributors,[e]:n}}));return a(r)?i("Unable to remove contributor"):c("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return i("Contributor not found");if(n.tombstoned)return i("Cannot rename a removed contributor");let r={...n,name:t},o=oe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?i("Unable to rename contributor"):c("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return i("Contributor not found");let r={...n,name:t,tombstoned:!1},o=oe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?i("Unable to restore contributor"):c("Restored contributor",r)},createContributor(e){let t=oe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?i("Unable to create contributor"):c("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return i("Unable to assign contributor, missing contributor");if(!r)return i("Unable to assign contributor, missing target");let o=ln(r,"edit");if(o)return o;if(!L(r))return i("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return i("Contributor already assigned");let d={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(d),c("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return i("Unable to unassign, missing contributor");if(!r)return i("Unable to unassign, missing target");let o=ln(r,"edit");if(o)return o;if(!L(r))return i("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return c("Issue is not assigned to that contributor",{assignee:t});let d={...r,props:{...r.props,assignees:s.filter(l=>l!==t)}};return this.updateNode(d),c("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return i("Unable to add tag, missing tag");if(!r)return i("Unable to add tag, missing target");let o=ln(r,"edit");if(o)return o;if(!L(r))return i("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return i("Tag already assigned");let d={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(d),c("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),r=this.getNode(e);if(!n)return i("Unable to remove tag, missing tag");if(!r)return i("Unable to remove tag, missing target");let o=ln(r,"edit");if(o)return o;if(!L(r))return i("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return c("Issue is not tagged with that tag",{tag:t});let d={...r,props:{...r.props,tags:s.filter(l=>l!==t)}};return this.updateNode(d),c("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return i("Tag not found");let n={...t,tombstoned:!0},r=oe(o=>({...o,tags:{...o.tags,[e]:n}}));return a(r)?i("Unable to delete tag"):c("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return i("Tag not found");let r={...n,name:t,tombstoned:!1},o=oe(s=>({...s,tags:{...s.tags,[e]:r}}));return a(o)?i("Unable to restore tag"):c("Restored tag",r)},createTag(e){let t=oe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?i("Could not create tag"):c("Tag created",e)},createNode(e){let t=oe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?i("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return i("Failed to locate node");let n={...t,readonly:!0},r=oe(o=>({...o,nodes:{...o.nodes,[e]:n}}));return a(r)?i(r.message):c("Locked node",n)},updateNode(e){let t=oe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?t:c("Updated node",e)},getContributor(e){return g().contributors[e]},getTag(e){let t=g().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return g().tags[e]},getTags(){return Object.values(g().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return g().nodes[e]},getSiblings(e){return le(e)}}});import un from"chalk";import Zm from"string-width";var Yy,Xy,Ua,Jy,Qy,ep,tp,Zy,eb,tb,nb,rb,ka,np,io=y(()=>{"use strict";it();me();k();At();Rs();Yy=(e,t)=>e+" ".repeat(Math.max(0,t-Zm(e))),Xy=(e,t)=>" ".repeat(Math.max(0,t-Zm(e)))+e,Ua=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed contributor","link.contributor.user":"Linked contributor","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),Jy=(e,t)=>t?e<t?"up":e>t?"down":null:null,Qy=(e,t)=>{let n=x.getNode(e.payload.parent),r=n?un.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=Jy(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},ep=e=>`${Math.max(1,Math.round(e/1024))} KB`,tp=e=>x.getAttachment(e)?.name??"",Zy=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?un.bgHex(De(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?un.bgHex(De(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=g().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?un.hex(De(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?un.hex(De(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${un.dim(`(${ep(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=tp(e.payload.id);return t?`"${t}"`:""}default:return""}},eb=e=>{let t=or(vt(e));return un.gray(Xy(t,8))},tb=12,nb=e=>Yy(`${e}`,tb),rb=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=g().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=x.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${ep(e.payload.bytes)})`;case"delete.issue.attachment":{let t=tp(e.payload.id);return t?`"${t}"`:""}default:return""}},ka=e=>[Ua(e.action),rb(e)].filter(Boolean).join(" "),np=(e,t)=>{let n=eb(e.id),r=nb(e.userName),o=un.dim("\u203A"),s=e.action==="move.node"?Qy(e,t):[Ua(e.action),Zy(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`}});var op={};go(op,{areVirtualNodesEnabled:()=>Fo,createOrUpdateVirtualField:()=>lo,createOrUpdateVirtualFieldList:()=>$a,materializeTicketVirtualNodes:()=>Do,materializeVirtualNodes:()=>mb,setVirtualNodesEnabled:()=>ub});var ob,sb,ib,ab,db,cb,lo,$a,Do,lb,rp,ub,Fo,mb,mi=y(()=>{"use strict";io();ge();C();Hn();me();xn();k();$n();Yn();ob=e=>Ce(e,"comments"),sb=e=>Ce(e,"description"),ib=e=>Ce(e,"assignees"),ab=e=>Ce(e,"tags"),db=e=>Ce(e,"history"),cb=e=>Ce(e,"attachments"),lo=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:d="horizontal"})=>{let l=x.getNode(e);if(!l){let p=x.createNode({...Se.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:d});return a(p)?p:c("Virtual field created",void 0)}if(!ze(l))return i(`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!==d))return c("Virtual field unchanged",void 0);let m=x.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:s,childRenderAxis:d});return a(m)?m:c("Virtual field updated",void 0)},$a=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let d=x.getNode(e);if(!d){let m=x.createNode({...Se.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return a(m)?m:c("Virtual field list created",void 0)}if(!gr(d))return i(`Existing virtual node ${e} is not a field list`);if(!(d.title!==t||d.parentNodeId!==n||d.rank!==r||d.readonly!==o||d.childRenderAxis!==s))return c("Virtual field list unchanged",void 0);let u=x.updateNode({...d,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(u)?u:c("Virtual field list updated",void 0)},Do=e=>{let t=Ye(at/4n),n=Ye(at/2n),r=Ye(at*3n/4n),o=Ye(at*7n/8n),s=Ye(at*15n/16n),d=Ye(at*13n/16n);if(a(t))return t;if(a(n))return n;if(a(r))return r;if(a(o))return o;if(a(s))return s;if(a(d))return d;let l=lo({id:sb(e.id),name:re.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(l))return l;let u=$a({id:ib(e.id),name:re.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(u))return u;let m=$a({id:ab(e.id),name:re.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(a(m))return m;let p=lo({id:ob(e.id),name:re.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(p))return p;let f=lo({id:cb(e.id),name:re.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(f))return f;let I=lo({id:db(e.id),name:re.HISTORY,parentNodeId:e.id,rank:d.value,value:lb(e),readonly:!0,childRenderAxis:"vertical"});return a(I)?I:c("Ticket virtual nodes materialized",void 0)},lb=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=>np(r,n.get(r.action)??[])).join(`
|
|
69
|
-
`)},rp=!0,ub=e=>{rp=e},Fo=()=>rp,mb=()=>{let{nodes:e}=g();for(let t of Object.values(e)){if(!L(t))continue;let n=Do(t);if(a(n))return n}return c("Virtual nodes materialized",void 0)}});var sp=y(()=>{"use strict"});var pb,ip,ap,dp,cp,_s=y(()=>{"use strict";ut();ct();Yt();Ia();it();io();At();Jt();Ft();sp();C();Pt();ds();ue();k();pb=null,ip=Promise.resolve(),ap=e=>{let t=ip.then(e,e);return ip=t.then(()=>{},()=>{}),t},dp=()=>{if(!Nt())return{mode:"live",asOfTime:null};let{timeMode:e}=g();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:pb}},cp=(e,t)=>{let n=new Map,r=new Set,o=d=>{let l=new Set,u=d;for(;u&&!l.has(u);){if(r.has(u))return u;l.add(u),u=n.get(u)}return null},s=[];for(let d of e){let l=d.payload,u=l?.id;if(!u)continue;d.action==="add.board"&&r.add(u);let m=l.parent??l.issue;m&&n.set(u,m),(u===t||o(u)===t)&&s.push(d)}return s}});import gb from"node:fs";import fb from"node:path";import{ulid as H}from"ulid";var hb,vb,js,Z,de,ne,lp,yb,up,mp,pp,gp,fp,hp,vp,yp,bp,xp,Ip,Ep,Rp,Np,Sp,Cp,Ap,Tp,wp,Mp,kp,Lp,Pp,Dp,Fp,bb,Bp,Op,_p,Up,$p,jp,Hp,Wp=y(()=>{"use strict";ut();ct();br();Fr();Ti();kn();Ta();it();kr();Jt();Sn();mt();_s();ya();Wn();ge();C();me();xt();k();Go();Ur();ue();yt();io();At();Yr();Yt();Vt();qr();It();_s();hb=e=>{if(e.filePath)try{return c("Read attachment file",{data:gb.readFileSync(e.filePath),name:e.name??fb.basename(e.filePath)})}catch(t){return i(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?c("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):i("Provide either filePath or dataBase64")},vb=()=>{let e=Hi();return a(e)?Ut:e.value.attachmentMaxKb??Ut},js=e=>{let t=Xe(e??process.cwd());return a(t)?i(t.message):c("Resolved Epiq repo root",t.value)},Z=async(e,t)=>{let n=js(e);if(a(n))return n;let r=Ne({repoRoot:n.value});if(a(r))return i(r.message);let o=Kt(n.value);if(a(o))return i(o.message);let s=await Si({repoRoot:n.value,stateBranchName:o.value});if(a(s))return i(s.message);let d=await An({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(a(d))return i(d.message);if(t?.pull??!1){let m=await j({cwd:r.value,args:["pull","--ff-only"]});a(m)&&z.info(3,m.message)}let l=Bt(r.value);if(a(l))return i(l.message);let u=Zt(l.value.events,l.value.unreadable);return a(u)?i(u.message):c("Booted Epiq state",{repoRoot:n.value,stateBranchRoot:r.value})},de=()=>{let e=Hi();return a(e)?i(e.message):e.value.userId?e.value.userName?c("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):i("Unable to retrieve user name"):i("Unable to retrieve user id")},ne=()=>{let e=je();return a(e)?i(e.message):e},lp=e=>(e.props.tags??[]).map(t=>x.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:De(t.name)})),yb=()=>{let e=je(),t=a(e)?[]:e.value.eventLog??[],n=new Map;for(let r of t)r.userId&&r.userName&&n.set(r.userId,r.userName);return n},up=(e,t)=>{let n=new Map(e);for(let r of Object.values(t))n.set(r.id,r.name);return n},mp=e=>(e.props.assignees??[]).map(t=>x.getContributor(t)).filter(t=>t!=null).map(({id:t,name:n})=>({id:t,name:n,color:De(n)})),pp=async(e={})=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=ne();if(a(n))return n;let r=Object.values(n.value.nodes).filter(o=>o.context==="BOARD"&&!o.isDeleted).map(o=>({id:o.id,ref:V(o.id),title:o.title,parentId:o.parentNodeId,readonly:!!o.readonly}));return c("Listed boards",r)},gp=async(e={})=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=ne();if(a(n))return n;let r=Object.values(n.value.nodes).filter(o=>o.context==="SWIMLANE"&&!o.isDeleted).filter(o=>!e.boardId||o.parentNodeId===e.boardId).map(o=>({id:o.id,title:o.title,boardId:o.parentNodeId,isClosed:o.id===be,readonly:!!o.readonly}));return c("Listed swimlanes",r)},fp=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=ne();if(a(n))return n;let r=e.idOrRef.trim();if(!r)return i("Provide an issue id or ref");let o=Object.values(n.value.nodes).filter(L).filter(u=>!u.isDeleted),s=o.find(u=>u.id===r),d=s?[s]:o.filter(u=>Cr(u.id,r));if(d.length===0)return i(`No issue matches "${r}"`);if(d.length>1)return i(`"${r}" matches ${d.length} issues: ${d.map(u=>`${V(u.id)} (${Me(u.title)})`).join(", ")}. Use a full ref or id.`);let l=d[0];return c("Found issue",{id:l.id,ref:V(l.id),title:Me(l.title),description:l.props.description??"",createdAt:vt(l.id),parentNodeId:l.parentNodeId,isClosed:l.parentNodeId===be,readonly:!!l.readonly,tags:lp(l),assignees:mp(l)})},hp=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=ne();if(a(n))return n;let r=n.value.nodes,o=Object.values(r).filter(L).filter(s=>!s.isDeleted).filter(s=>e.includeClosed||s.parentNodeId!==be).filter(s=>e.boardId?(s.parentNodeId?r[s.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).map(s=>({id:s.id,ref:V(s.id),title:Me(s.title),description:s.props.description??"",createdAt:vt(s.id),parentNodeId:s.parentNodeId,isClosed:s.parentNodeId===be,readonly:!!s.readonly,tags:lp(s),assignees:mp(s)}));return c("Listed issues",o)},vp=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=Me(e.title);if(!o)return i("Issue title cannot be empty");let s=e.description??"",d=pt("Issue title",o,300)??pt("Issue description",s,2e4);if(d)return i(d);if((e.tagNames?.length??0)>20)return i(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return i(`Cannot set more than ${20} assignees at once`);let l=Cn(e.parentId,n.value,t.value.stateBranchRoot);if(a(l))return l;let u=ws({name:o,parent:e.parentId,user:n.value,rank:l.value});if(a(u))return u;let m=[...u.value],p=m.find(A=>A.action==="add.issue")?.payload.id;if(!p)return i("Unable to determine created issue id");s&&m.push({id:H(),...n.value,action:"edit.description",payload:{id:p,md:s}});let f=[];for(let A of e.tagNames??[]){let w=Me(A).trim();if(!w||f.some(ee=>ee.name===w))continue;let T=pt("Tag name",w,60);if(T)return i(T);let M=x.findTagByName(w),U=M?.id??H();M||m.push({id:H(),...n.value,action:"create.tag",payload:{id:U,name:w}}),m.push({id:H(),...n.value,action:"add.issue.tag",payload:{id:p,tag:U}}),f.push({id:U,name:w})}let I=[];for(let A of e.assigneeNames??[]){let w=Me(A).trim();if(!w||I.some(ee=>ee.name===w))continue;let T=pt("Assignee name",w,80);if(T)return i(T);let M=Object.values(r.value.contributors).find(ee=>ee.name===w),U=M?.id??H();M||m.push({id:H(),...n.value,action:"create.contributor",payload:{id:U,name:w}}),m.push({id:H(),...n.value,action:"add.issue.assignee",payload:{id:p,assignee:U}}),I.push({id:U,name:w})}let N=B(m,t.value.stateBranchRoot);return a(N)?i(N.message):c("Created issue",{id:p,ref:V(p),title:o,parentId:e.parentId,description:s,tags:f,assignees:I})},yp=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=Qt(be,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(r))return r;let o={id:H(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:be,rank:r.value}},s=B([o],t.value.stateBranchRoot);return a(s)?i(s.message):c("Closed issue",{id:e.issueId,ref:V(e.issueId)})},bp=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!L(o))return i("Target node is not issue");if(o.parentNodeId!==be)return i("Issue is not closed");let s=Cs(o);if(!s)return i("Unable to resolve previous parent from issue history");if(s===be)return i("Previous parent resolves to closed swimlane");let d=r.value.nodes[s];if(!d)return i("Previous parent no longer exists");let l=Qt(d.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(l))return l;let u={id:H(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:d.id,rank:l.value}},m=B([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Reopened issue",{id:o.id,ref:V(o.id),parentId:d.id})},xp=async e=>{let t=js(e.repoRoot);if(a(t))return t;let n=de();if(a(n))return n;let r=Ne({repoRoot:t.value});if(a(r))return r;let o=Bt(r.value);if(a(o))return o;let s=Zt(o.value.events,o.value.unreadable);if(a(s))return s;let d=Qt(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(a(d))return d;let l={id:H(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:d.value}},u=B([l],r.value);return a(u)?i(u.message):c("Moved issue",{id:e.issueId,ref:V(e.issueId),parentId:e.parentId})},Ip=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.boardId];if(!o)return i("Board not found");if(!yo(o))return i("Target parent must be a board");if(o.readonly)return i("Cannot add a swimlane to a readonly board");if(dp().mode!=="live")return i("Cannot add a swimlane while time travelling");let s=Me(e.title);if(!s.trim())return i("Swimlane title cannot be empty");let d=pt("Swimlane title",s,300);if(d)return i(d);let l=Cn(e.boardId,n.value,t.value.stateBranchRoot);if(a(l))return l;let u=H(),m={id:H(),...n.value,action:"add.swimlane",payload:{id:u,name:s,parent:e.boardId,rank:l.value}},p=B([m],t.value.stateBranchRoot);return a(p)?i(p.message):c("Created swimlane",{id:u,ref:V(u),title:s,boardId:e.boardId})},Ep=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.swimlaneId];if(!o)return i("Swimlane not found");if(!gn(o))return i("Edit target must be a swimlane");if(o.readonly)return i("Cannot edit readonly swimlane");let s=Me(e.title);if(!s.trim())return i("Swimlane title cannot be empty");let d=pt("Swimlane title",s,300);if(d)return i(d);if(o.title===s)return c("No changes made",{id:e.swimlaneId,ref:V(e.swimlaneId),title:s});let l={id:H(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:s}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Edited swimlane title",{id:e.swimlaneId,ref:V(e.swimlaneId),title:s})},Rp=async e=>{let t=js(e.repoRoot);if(a(t))return t;let n=de();if(a(n))return n;let r=Ne({repoRoot:t.value});if(a(r))return r;let o=Bt(r.value);if(a(o))return o;let s=Zt(o.value.events,o.value.unreadable);if(a(s))return s;let d=Qt(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(a(d))return d;let l={id:H(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:d.value}},u=B([l],r.value);return a(u)?i(u.message):c("Moved swimlane",{id:e.swimlaneId,ref:V(e.swimlaneId),boardId:e.boardId})},Np=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.swimlaneId];if(!o)return i("Swimlane not found");if(!gn(o))return i("Delete target must be a swimlane");let s={id:H(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},d=B([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Deleted swimlane",{id:e.swimlaneId,ref:V(e.swimlaneId)})},Sp=async(e={})=>{Ho();let t=js(e.repoRoot);if(a(t))return i("Sync failed");let n=de();if(a(n))return n;let r=await Yo({cwd:t.value,ownEventFileName:Nn(n.value)});return a(r)?(Ei(r.message),r):(Wo(),c("Synced",r.value))},Cp=async(e={})=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=ne();return a(n)?n:c("Retrieved Epiq state",{root:t.value.repoRoot,stateBranchRoot:t.value.stateBranchRoot,nodes:n.value.nodes,rootNodeId:n.value.rootNodeId,contextNode:n.value.contextNode,selectedIndex:n.value.selectedIndex,eventLog:n.value.eventLog})},Ap=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!L(o))return i("Edit target must be an issue");if(o.readonly)return i("Cannot edit readonly issue");let s=pt("Issue description",e.description,2e4);if(s)return i(s);let d=o.props.description??"";if(d===e.description)return c("No changes made",{id:e.issueId,ref:V(e.issueId),description:d});let l={id:H(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Edited issue description",{id:e.issueId,ref:V(e.issueId),description:e.description})},Tp=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!L(o))return i("Edit target must be an issue");if(o.readonly)return i("Cannot edit readonly issue");let s=Me(e.title);if(!s.trim())return i("Issue title cannot be empty");let d=pt("Issue title",s,300);if(d)return i(d);if(o.title===s)return c("No changes made",{id:e.issueId,ref:V(e.issueId),title:s});let l={id:H(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Edited issue title",{id:e.issueId,ref:V(e.issueId),title:s})},wp=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!L(o))return i("Tag target must be an issue");if(o.readonly)return i("Cannot tag readonly issue");let s=Me(e.tagName).trim();if(!s)return i("Tag name cannot be empty");let d=pt("Tag name",s,60);if(d)return i(d);let l=x.findTagByName(s),u=l?.id??H(),m=[...l?[]:[{id:H(),...n.value,action:"create.tag",payload:{id:u,name:s}}],{id:H(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:u}}],p=B(m,t.value.stateBranchRoot);return a(p)?i(p.message):c("Added issue tag",{id:e.issueId,ref:V(e.issueId),tag:{id:u,name:s}})},Mp=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return i("Tag not found");if(o.tombstoned)return i("Tag is already deleted");let s=[{id:H(),...n.value,action:"tombstone.tag",payload:{id:e.tagId}}],d=B(s,t.value.stateBranchRoot);return a(d)?i(d.message):c("Deleted tag",{id:o.id,name:o.name})},kp=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return i("Tag not found");if(!o.tombstoned)return i("Tag is not deleted");if(x.findTagByName(o.name))return i(`Cannot restore: another tag is already named "${o.name}"`);let s=[{id:H(),...n.value,action:"restore.tag",payload:{id:e.tagId,name:o.name}}],d=B(s,t.value.stateBranchRoot);return a(d)?i(d.message):c("Restored tag",{id:o.id,name:o.name})},Lp=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!L(o))return i("Untag target must be an issue");if(o.readonly)return i("Cannot untag readonly issue");if(!r.value.tags[e.tagId])return i("Tag not found");let s={id:H(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},d=B([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue tag",{id:e.issueId,ref:V(e.issueId),tagId:e.tagId})},Pp=async(e,t)=>{let n=bi(e);if(a(n))return;let r;for(let o of n.value)o.userId===t&&(r=o.userName??r);return r===void 0?void 0:{id:t,name:r}},Dp=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!L(o))return i("Assign target must be an issue");if(o.readonly)return i("Cannot assign readonly issue");let s=e.self?n.value.userId:e.assigneeId;if(s){let T=r.value.contributors[s],M=T?void 0:await Pp(t.value.stateBranchRoot,s);if(!T&&!M)return i("Unknown assignee id");let U=T??M,ee=[...T?[]:[{id:H(),...n.value,action:"create.contributor",payload:{id:U.id,name:U.name}}],{id:H(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:U.id}}],ve=B(ee,t.value.stateBranchRoot);return a(ve)?i(ve.message):c("Added issue assignee",{id:e.issueId,ref:V(e.issueId),assignee:{id:U.id,name:U.name}})}let d=Me(e.assigneeName??"").trim();if(!d)return i("Provide assigneeId, self or assigneeName");let l=pt("Assignee name",d,80);if(l)return i(l);let m=[...up(yb(),r.value.contributors).entries()].filter(([,T])=>T===d);if(m.length>1)return i(`"${d}" matches ${m.length} contributors (${m.map(([T])=>T).join(", ")}). Assign by assigneeId to choose.`);let p=m[0];if(!p&&!e.createUnlinked)return i(`No contributor named "${d}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[f=H(),I=d]=p??[],A=[...!!r.value.contributors[f]?[]:[{id:H(),...n.value,action:"create.contributor",payload:{id:f,name:I}}],{id:H(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:f}}],w=B(A,t.value.stateBranchRoot);return a(w)?i(w.message):c("Added issue assignee",{id:e.issueId,ref:V(e.issueId),assignee:{id:f,name:I}})},Fp=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;if(!r.value.contributors[e.contributorId])return i("Contributor not found");if(await Pp(t.value.stateBranchRoot,e.contributorId))return i("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let d=[{id:H(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],l=B(d,t.value.stateBranchRoot);return a(l)?i(l.message):c("Tombstoned contributor",{id:e.contributorId,name:vo})},bb=async(e,t)=>{let n=Gn(e);if(a(n))return;let r;for(let o of n.value){if(o.action!=="create.contributor")continue;let s=o.payload;s.id===t&&s.name&&(r=s.name)}return r},Bp=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.contributors[e.contributorId];if(!o)return i("Contributor not found");if(!o.tombstoned)return i("Contributor is not tombstoned");let s=await bb(t.value.stateBranchRoot,e.contributorId);if(!s)return i("Cannot restore this contributor \u2014 no original name found in the event log");let d=[{id:H(),...n.value,action:"restore.contributor",payload:{id:e.contributorId,name:s}}],l=B(d,t.value.stateBranchRoot);return a(l)?i(l.message):c("Restored contributor",{id:e.contributorId,name:s})},Op=async(e={})=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=Gn(t.value.stateBranchRoot);if(a(o))return i(o.message);let s=e.boardId?cp(o.value,e.boardId):o.value,d=new Map,l=new Set,u=new Set,m=bi(t.value.stateBranchRoot);if(a(m))return i(m.message);for(let N of m.value)N.userId&&u.add(N.userId);for(let N of s)N.userId&&(d.set(N.userId,N.userName??""),l.add(N.userId));let p=r.value.contributors,I=[...up(d,p).entries()].map(([N,A])=>({id:N,name:A,color:De(A),isSelf:N===n.value.userId,isExternal:!l.has(N),isRemoved:p[N]?.tombstoned===!0,hasAuthoredAnywhere:u.has(N)}));return c("Listed board contributors",I)},_p=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!L(o))return i("Unassign target must be an issue");if(o.readonly)return i("Cannot unassign readonly issue");if(!r.value.contributors[e.assigneeId])return i("Assignee not found");let s={id:H(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},d=B([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue assignee",{id:e.issueId,ref:V(e.issueId),assigneeId:e.assigneeId})},Up=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!L(o))return i("Comment target must be an issue");if(o.readonly)return i("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return i("Comment cannot be empty");if(s.length>4e3)return i(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let d=H(),l={id:H(),...n.value,action:"add.issue.comment",payload:{id:d,issue:e.issueId,md:s,author:n.value.userId}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Added issue comment",{id:d,issueId:e.issueId,body:s})},$p=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();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 i("Unable to resolve comment");if(o.payload.author!==n.value.userId)return i("You can only delete your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return i("Issue not found");if(!L(s))return i("Comment target must be an issue");if(s.readonly)return i("Cannot delete comment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return c("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let l={id:H(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},jp=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();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 i("Unable to resolve comment");if(o.payload.author!==n.value.userId)return i("You can only edit your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return i("Issue not found");if(!L(s))return i("Comment target must be an issue");if(s.readonly)return i("Cannot edit comment on readonly issue");if(r.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return i("Comment was deleted");let l=e.body.trim();if(!l)return i("Comment cannot be empty");if(l.length>4e3)return i(`Comment cannot exceed ${4e3} characters (got ${l.length})`);let u={id:H(),...n.value,action:"edit.issue.comment",payload:{id:e.commentId,issue:o.payload.issue,md:l}},m=B([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Edited issue comment",{id:e.commentId,issueId:o.payload.issue,body:l})},Hp=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=de();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!L(o))return i("Attachment target must be an issue");if(o.readonly)return i("Cannot attach to readonly issue");let s=hb(e);if(a(s))return s;let d=rl(t.value.stateBranchRoot,s.value.data,vb());if(a(d))return d;let l=Me(s.value.name).trim()||"image",u=H(),m={id:H(),...n.value,action:"add.issue.attachment",payload:{id:u,issue:e.issueId,author:n.value.userId,hash:d.value.hash,ext:d.value.ext,name:l,bytes:d.value.bytes}},p=B([m],t.value.stateBranchRoot);if(a(p))return i(p.message);let f=Gr(d.value.hash,d.value.ext);return c("Added issue attachment",{id:u,issueId:e.issueId,fileName:f,bytes:d.value.bytes,markdown:Wi(l,f)})}});var Vp={};go(Vp,{createMcpServer:()=>qp,resultJson:()=>Gp,startMcpServer:()=>Rb});import{McpServer as Ib}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Eb}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as b}from"zod";var Gp,Y,qp,Rb,Kp=y(()=>{"use strict";C();Yr();Wp();_s();Gp=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Y=e=>t=>ap(async()=>Gp(await e(t))),qp=()=>{let e=new Ib({name:"epiq",version:"0.2.30"});return e.registerTool("epiq_state_get",{description:"Get the full current Epiq state, including nodes and event log",inputSchema:b.object({repoRoot:b.string().optional()})},Y(Cp)),e.registerTool("epiq_issue_list",{description:"List Epiq issues. Pass boardId to scope results to a single board and reduce response size.",inputSchema:b.object({repoRoot:b.string().optional(),includeClosed:b.boolean().optional(),boardId:b.string().optional()})},Y(hp)),e.registerTool("epiq_issue_get",{description:"Get one Epiq issue by its full id or its 7-character ref. Use this rather than listing the whole board when you already know which issue you want.",inputSchema:b.object({idOrRef:b.string().min(1),repoRoot:b.string().optional()})},Y(fp)),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:b.object({repoRoot:b.string().optional()})},Y(pp)),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:b.object({repoRoot:b.string().optional(),boardId:b.string().optional()})},Y(gp)),e.registerTool("epiq_swimlane_create",{description:"Create an Epiq swimlane on a board",inputSchema:b.object({repoRoot:b.string().optional(),boardId:b.string().min(1),title:b.string().min(1).max(300)})},Y(Ip)),e.registerTool("epiq_swimlane_title_edit",{description:"Edit an Epiq swimlane title",inputSchema:b.object({repoRoot:b.string().optional(),swimlaneId:b.string().min(1),title:b.string().min(1).max(300)})},Y(Ep)),e.registerTool("epiq_swimlane_move",{description:"Move/reorder an Epiq swimlane, optionally to another board",inputSchema:b.object({repoRoot:b.string().optional(),swimlaneId:b.string().min(1),boardId:b.string().min(1),position:b.discriminatedUnion("at",[b.object({at:b.literal("start")}),b.object({at:b.literal("end")}),b.object({at:b.literal("before"),sibling:b.string().min(1)}),b.object({at:b.literal("after"),sibling:b.string().min(1)})]).optional()})},Y(Rp)),e.registerTool("epiq_swimlane_delete",{description:"Delete (archive) an Epiq swimlane. This also archives every issue contained in it.",inputSchema:b.object({repoRoot:b.string().optional(),swimlaneId:b.string().min(1)})},Y(Np)),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue. Optionally set description, tags, and assignees atomically in the same call instead of separate follow-up edits.",inputSchema:b.object({title:b.string().min(1).max(300),parentId:b.string().min(1),repoRoot:b.string().optional(),description:b.string().max(2e4).optional(),tagNames:b.array(b.string().max(60)).max(20).optional(),assigneeNames:b.array(b.string().max(80)).max(20).optional()})},Y(vp)),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),description:b.string().max(2e4),repoRoot:b.string().optional()})},Y(Ap)),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),title:b.string().min(1).max(300),repoRoot:b.string().optional()})},Y(Tp)),e.registerTool("epiq_issue_tag_add",{description:"Add a tag to an Epiq issue, creating the tag if it does not exist",inputSchema:b.object({issueId:b.string().min(1),tagName:b.string().min(1).max(60),repoRoot:b.string().optional()})},Y(wp)),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),tagId:b.string().min(1),repoRoot:b.string().optional()})},Y(Lp)),e.registerTool("epiq_contributor_list",{description:"List people who can be assigned: everyone who has authored an event (optionally scoped to one board) unioned with the contributor registry. Use these ids with epiq_issue_assignee_add rather than assigning by name.",inputSchema:b.object({boardId:b.string().min(1).optional(),repoRoot:b.string().optional()})},Y(Op)),e.registerTool("epiq_contributor_remove",{description:"Remove an external contributor from the assignee suggestion lists. Their id and every reference to it survive, so existing assignments stay intact and the event log is untouched. Refused for anyone who has authored events, since their name is in the log regardless.",inputSchema:b.object({contributorId:b.string().min(1),repoRoot:b.string().optional()})},Y(Fp)),e.registerTool("epiq_tag_remove",{description:"Delete a tag from the whole workspace. It disappears from every ticket, picker and filter, but its id and history stay in the event log, and the name is free for a new tag.",inputSchema:b.object({tagId:b.string().min(1),repoRoot:b.string().optional()})},Y(Mp)),e.registerTool("epiq_tag_restore",{description:"Put back a tag deleted with epiq_tag_remove, on every ticket that still carried it.",inputSchema:b.object({tagId:b.string().min(1),repoRoot:b.string().optional()})},Y(kp)),e.registerTool("epiq_contributor_restore",{description:"Put a contributor removed with epiq_contributor_remove back into the suggestion lists, under the name they were created with.",inputSchema:b.object({contributorId:b.string().min(1),repoRoot:b.string().optional()})},Y(Bp)),e.registerTool("epiq_issue_assignee_add",{description:"Assign a contributor to an Epiq issue. Pass self:true to assign yourself. Prefer assigneeId otherwise, which assigns a known contributor (from the registry or the event log) and fails if the id is unknown. assigneeName matches an existing contributor by name; to create somebody new from a name you must also pass createUnlinked, which adds them as an external (non-contributor) assignee.",inputSchema:b.object({issueId:b.string().min(1),assigneeId:b.string().min(1).optional(),self:b.boolean().optional(),assigneeName:b.string().min(1).max(80).optional(),createUnlinked:b.boolean().optional(),repoRoot:b.string().optional()})},Y(Dp)),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),assigneeId:b.string().min(1),repoRoot:b.string().optional()})},Y(_p)),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),body:b.string().min(1).max(4e3),repoRoot:b.string().optional()})},Y(Up)),e.registerTool("epiq_issue_attachment_add",{description:"Attach an image file to an Epiq issue. Returns `markdown` \u2014 paste it into a comment or description body to render the image inline.",inputSchema:b.object({issueId:b.string().min(1),filePath:b.string().min(1),name:b.string().min(1).max(200).optional(),repoRoot:b.string().optional()})},Y(Hp)),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:b.object({commentId:b.string().min(1),repoRoot:b.string().optional()})},Y($p)),e.registerTool("epiq_issue_comment_edit",{description:"Replace the body of one of your own comments on an Epiq issue",inputSchema:b.object({commentId:b.string().min(1),body:b.string().min(1).max(4e3),repoRoot:b.string().optional()})},Y(jp)),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:b.object({issueId:b.string().min(1),repoRoot:b.string().optional()})},Y(bp)),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),repoRoot:b.string().optional()})},Y(yp)),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:b.object({issueId:b.string().min(1),parentId:b.string().min(1),position:b.discriminatedUnion("at",[b.object({at:b.literal("start")}),b.object({at:b.literal("end")}),b.object({at:b.literal("before"),sibling:b.string().min(1)}),b.object({at:b.literal("after"),sibling:b.string().min(1)})]).optional(),repoRoot:b.string().optional()})},Y(xp)),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote (pull remote changes and push local ones). Other Epiq MCP tools only read and write local state and never sync automatically \u2014 call this on demand when you need to see or publish the latest remote changes.",inputSchema:b.object({repoRoot:b.string().optional()})},Y(Sp)),e},Rb=async()=>{let e=qp(),t=new Eb;await e.connect(t)}});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;var{applyActorNameArgument:Nb}=await Promise.resolve().then(()=>(ur(),Ka)),{isFail:Sb}=await Promise.resolve().then(()=>(C(),Ga)),Hs=process.argv.slice(2);Hs.length>1&&(console.error(`Expected at most one name argument, got ${Hs.length}`),process.exit(1));if(Hs[0]!==void 0){let e=Nb(Hs[0],"The name argument");Sb(e)&&(console.error(e.message),process.exit(1))}var{setVirtualNodesEnabled:Cb}=await Promise.resolve().then(()=>(mi(),op));Cb(!1);var{startMcpServer:Ab}=await Promise.resolve().then(()=>(Kp(),Vp));await Ab();
|
|
71
|
+
`,La.writeFileSync(t,n,"utf8"),X.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)}});import Dy from"node:fs";import Ju from"node:path";var Fy,re,Qu,Zu=y(()=>{"use strict";Xu();Po();mt();lt();Wr();Ze();Kr();_r();Ut();gt();ue();C();Bt();Re();Ue();k();pe();Fy=async e=>{let t=await H({cwd:e,args:["status","--porcelain"]});return a(t)?t:c("Checked git diff",t.value.stdout.trim().length>0)},re=(e,t)=>i(`[${e}] ${t}`),Qu=async()=>{V("");let e=Mo(),t=await ut(process.cwd());if(a(t))return re(1,t.message);let n=t.value,r=await Do(n);if(a(r))return re(2,r.message);if(r.value)return re(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await Fy(n);if(a(o))return re(2.5,o.message);if(o.value)return re(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(Mr(n))return re(4,"Epiq project already initialized");let s=cs();if(!s.isSetupDone||!s.userName)return re(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let d=xe(),l=d.userName,u=d.userId;if(!u||!l)return re(5,"Missing Epiq user id");let m=await Cc(n);if(a(m))return re(6,m.message);let p=e.stateBranch,f=await Fo({repoRoot:n,branch:p});if(a(f))return re(6,f.message);if(f.value)return re(6,`State branch already exists: ${p}`);let I=await Pi({repoRoot:n,stateBranchName:p});if(a(I))return re(6,I.message);let N=_o();if(a(N))return re(7,N.message);let A=Ju.join(Bo(),e.projectId),w=await Ln({repoRoot:n,stateBranchRoot:A,stateBranchName:p});if(a(w))return re(8,w.message);let T=Ju.join(A,".epiq");Dy.mkdirSync(T,{recursive:!0});let M=hc({userId:u,userName:l});if(a(M))return re(9,M.message);for(let Zs of M.value){let Qa=Ko({event:Zs,rootDir:A});if(a(Qa))return re(9,Qa.message)}let U=await ns({stateBranchRoot:A,eventFileName:wn({userId:u,userName:l})});if(a(U))return re(10,U.message);let ne=await qn({cwd:A,message:"[epiq:init]"});if(a(ne))return re(10,ne.message);let be=await Yu(n);if(a(be))return re(11,be.message);let Q=bd({repoRoot:n,fileContents:e});if(a(Q))return re(12,Q.message);let q=await ye.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(q))return re(13,q.message);let z=await ye.commit({cwd:n,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(a(z))return re(13,z.message);let yn="Project initialized!",bn=await H({cwd:n,args:["push","-u","origin","HEAD"]});a(bn)&&(yn+=` Warn: [init:14] ${bn.message}`);let pr=await Hr({repoRoot:n,stateBranchRoot:A});a(pr)&&(yn+=` Warn: [init:15] ${pr.message}`);let Xa=_t(M.value).filter(a);if(Xa.length>0)return re(16,Xa.map(Zs=>Zs.message).join(`
|
|
72
|
+
`));let Qs=Ge();if(a(Qs))return re(16,Qs.message);let{rootNodeId:sg,nodes:ig}=Qs.value,Ja=ig[sg];return Ja?(_.navigate({contextNode:Ja,selectedIndex:0}),E({hasProjectDefinition:!0,mode:h.DEFAULT}),c(yn,null)):re(16,"Unable to resolve initialized root node")}});import{ulid as Oy}from"ulid";function Da(e){let t=tm();if(a(t))return t;let{contextNode:n,nodes:r}=g();if(!n.parentNodeId)return i("Missing parent node id");let o=r[n.parentNodeId];if(!o)return i("Missing parent node");let s=me(o.id),d=s.findIndex(({id:m})=>m===n.id);if(d<0)return i("Current node not found among siblings");let l=s[d+e];if(!l)return i("Missing sibling node");let u=nm({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:rm(u.value)}function Fa(e){let t=tm();if(a(t))return t;let{contextNode:n,selectedIndex:r}=g(),s=me(n.id)[r+e];if(!s)return i("Missing sibling node");let d=nm({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:rm(d.value)}var em,fn,go,tm,Pa,nm,rm,Oa=y(()=>{"use strict";Ut();gt();C();Rt();k();em=null,fn=()=>structuredClone(em),go=e=>{em=e},tm=()=>{let{contextNode:e,selectedIndex:t}=g(),r=me(e.id)[t];return r?c("Resolved selected child",r):i("Target node not found")},Pa=({id:e,parentId:t,position:n={at:"end"}})=>{let r=me(t).filter(o=>o.id!==e);return Yo(r,n)},nm=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ve();if(a(r))return i("Unable to resolve user ID");let o=Pa({parentId:t,id:e,position:n});return a(o)?o:c("Created pending move state",{id:Oy(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},rm=e=>{go(e);let t=tn(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as By}from"ulid";var om,Bs,sm,im=y(()=>{"use strict";Ze();Oa();Mn();gt();ue();C();Rt();Re();k();pe();om=()=>{let e=fn();if(!e)return i("No pending move state");let t=e.payload.id,n=e.payload.parent,r=g().nodes[n];if(!r)return i("Move parent not found");let o=me(n).findIndex(s=>s.id===t);return o===-1?i("Moved node not found among rendered children"):(_.navigate({contextNode:r,selectedIndex:o}),c("Synchronized navigation to moved node",null))},Bs=(e,t="Moved preview")=>{if(a(e))return e;let n=om();return a(n)?n:(E({mode:h.MOVE}),c(t,null))},sm=async()=>{let e=ve();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=de().commandMeta,{contextNode:n,selectedIndex:r}=g(),o=me(n.id)[r];if(!o)return E({mode:h.DEFAULT}),i("No move target");if(t==="start"){if(o.readonly)return i("Target node is read-only");if(r===-1)return i("No item selected");if(!o.parentNodeId)return i("Target has no parent");let s=me(o.parentNodeId),d=s.findIndex(({id:f})=>f===o.id);if(d===-1)return i("Target not found among siblings");let l=s[d-1],u=s[d+1],m=u!=null?{at:"before",sibling:u.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},p=Pa({parentId:o.parentNodeId,id:o.id,position:m});return a(p)?p:(go({id:By(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),E({mode:h.MOVE}),c("Move initialized",null))}if(t==="next")return Bs(Fa(1));if(t==="previous")return Bs(Fa(-1));if(t==="to-next")return Bs(Da(1));if(t==="to-previous")return Bs(Da(-1));if(t==="confirm"){let s=fn();if(!s)return i("No pending move to confirm");let d=await Ct();if(a(d))return d;let l=O([s],d.value);if(a(l))return l;let u=om();return a(u)?u:(go(null),E({mode:h.DEFAULT}),c("Moved item",null))}return t==="cancel"?(go(null),E({mode:h.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as _y,ulid as Uy}from"ulid";var $y,_s,Ba=y(()=>{"use strict";C();$y=_y(),_s=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=$y();return c("Created issue events",[{id:Uy(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as Us}from"ulid";var am,dm=y(()=>{"use strict";Ze();Ba();Mn();gt();xt();C();ge();Rt();k();pe();am=async(e,t)=>{let n=ve();if(a(n))return i("Unable to resolve user ID");let r=await Ct();if(a(r))return r;let o=r.value;if(!t.inputString)return i(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:d,selectedIndex:l}=g(),u=m=>{let p=O([m],o);if(a(p))return p;let f=x.getNode(p.value[0].result.id);if(!f)return i("Created node not found");if(!f.parentNodeId)return p;let I=x.getNode(f.parentNodeId);return I?(_.navigate({contextNode:I,selectedIndex:x.getSiblings(f.parentNodeId).findIndex(({id:N})=>N===f.id)}),p):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=x.getNode(m);if(!p)return i("Workspace not found");let f=kn(p.id,n.value,o);return a(f)?f:u({id:Us(),action:"add.board",payload:{id:Us(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=Xe(s,"BOARD");if(a(m))return i("Unable to add swimlane in this context");let p=kn(m.value.id,n.value,o);return a(p)?p:u({id:Us(),action:"add.swimlane",payload:{id:Us(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=ae(d.id)[l],p=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let U=Xe(s,"SWIMLANE");return a(U)?null:U.value})();if(!p)return i("Unable to add issue in this context");let f=kn(p.id,n.value,o);if(a(f))return f;let I=_s({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(a(I))return I;let N=I.value,A=O([...N],o);if(a(A))return A;if(!A.value[0])return i("Issue creation failed");let M=N.find(U=>U.action==="add.issue")?.payload.id;return M?(_.navigate({contextNode:p,selectedIndex:x.getSiblings(p.id).findIndex(({id:U})=>U===M)}),c("Issue created",null)):i("Unable to determine ticket id")}return c("Success",null)}});var cm,lm=y(()=>{"use strict";mt();lt();Wr();zr();_r();rn();C();Bt();k();ts();cm=async e=>{let t=Ce({repoRoot:e});if(a(t))return Ur(3,t.message);let n=await Ln({repoRoot:e,stateBranchRoot:t.value,stateBranchName:Mo().stateBranch});if(a(n))return Ur(3,n.message);let r=await H({cwd:t.value,args:["pull","--ff-only"]});a(r)&&logger.info(3,r.message);let o=$t(t.value);if(a(o))return Ur(3,o.message);let{events:s,unreadable:d}=o.value,l=sn(s,d);if(a(l))return Ur(4,l.message);E({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let u=Hi({root:e});return a(u)&&logger.info(u.message),c("Loaded project",void 0)}});import jy from"node:os";import um from"node:path";var Hy,Wy,mm,pm=y(()=>{"use strict";lm();zr();C();Re();k();pe();Hy=e=>e==="~"||e.startsWith("~/")?um.join(jy.homedir(),e.slice(1)):e,Wy=(e,t)=>{let n=e.trim();if(!n)return i("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?c("Resolved recent project",o.root):i(`No recent project #${n}`)}let r=Qe(um.resolve(Hy(n)));return a(r)?i(`No epiq project at ${n}`):c("Resolved project path",r.value)},mm=async()=>{let e=Ss();if(V(""),g().hasProjectDefinition)return i("Already in a project; run epiq from another directory");let t=ds({exclude:process.cwd()}),n=a(t)?[]:t.value,r=Wy(e,n);if(a(r))return i(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(l){return i(`Unable to enter ${o}: ${l instanceof Error?l.message:String(l)}`)}let d=await cm(o);return a(d)?(process.chdir(s),i(d.message)):c(`Opened ${qc(o)}`,null)}});var $s,_a=y(()=>{"use strict";Ze();rn();Ut();C();k();$s=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=g(),s=wi(n,t);if(a(s))return i(s.message);let{appliedEvents:d,unappliedEvents:l}=s.value,u=Vt();if(a(u))return u;let m=_t(d),{fatal:p,skipped:f}=Cn(m);if(p.length>0)return Vt(),E(o),i(p.map(N=>N.message).join(", "));An(f);let I=g().nodes[e];return I?(_.navigate({contextNode:I,selectedIndex:r}),c("",{unappliedEvents:l})):(Vt(),E(o),i("Board did not exist at that date"))}});var Gy,qy,Vy,js,Hs,jn,gm,zy,fm,Ua=y(()=>{"use strict";dt();fo();Ut();ue();C();k();Gy=20,qy=16,Vy=150,js=null,Hs=null,jn=()=>{js!==null&&(clearInterval(js),js=null),Hs!==null&&(clearTimeout(Hs),Hs=null)},gm=()=>{jn(),E({mode:h.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},zy=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)},fm=({events:e,startTime:t,durationMs:n})=>{jn();let r=e.length,o=vr(e.map(f=>yr(f))).map(f=>f??t),s=o[r-1]??Date.now(),d=zy(o),l=Math.max(1,Math.round(n*Gy/1e3)),u=Math.max(Math.round(n/l),qy),m=0,p=0;E({mode:h.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),js=setInterval(()=>{m++;let f=m/l,I=[],N,A;for(;p<r&&d[p]<=f;){let T=e[p],M=tn(T);if(a(M)){if(Dr(M)){p++;continue}gm();return}I.push(...xi(T)),N=T,A=o[p],p++}if(p>=r||m>=l){for(;p<r;p++){let M=tn(e[p]);if(a(M)&&!Dr(M))break}let T=g().replay;E({unappliedEvents:[],replay:T&&{...T,progress:1,appliedCount:r}}),jn(),Hs=setTimeout(gm,Vy);return}let w=g().replay;E({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:N?A??w?.currentTime??t:w?.currentTime??t,currentLabel:N?$a(N):w?.currentLabel??"",flashNodeIds:N?[...new Set(I)]:w?.flashNodeIds??[]}})},u)}});var hm,vm=y(()=>{"use strict";mt();dt();rn();Ut();ue();xt();C();Re();k();Xr();_a();Ua();hm=async()=>{let e=Xe(g().breadCrumb,"BOARD");if(a(e))return e;let t=await ut(process.cwd());if(a(t))return i("Unable to locate repo root");let n=Ce({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=de().commandMeta;if(jn(),r==="now"){let l=Kn(n.value);if(a(l))return i(l.message);let u=Vt();if(a(u))return u;let m=_t(l.value),{fatal:p,skipped:f}=Cn(m);return p.length>0?i(p.map(I=>I.message).join(", ")):(An(f),E({mode:h.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),c("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let l=Mi(n.value);if(a(l))return l;let u=r==="prev"?g().eventLog.at(-1):g().unappliedEvents.at(0),m=u===void 0?null:yr(u),p=(u===void 0?null:l.value.get(u.id)??null)??(m===null?null:ni(m));if(p===null)return i(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?p:p+1}else{let l=Dn(r||o.trim());if(!l)return i("Invalid peek date");s=l.getTime()}let d=$s({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(d)?d:(E({mode:h.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:d.value.unappliedEvents,replay:null}),c("Peeking",!0))}});var ym,bm=y(()=>{"use strict";mt();xt();C();Re();k();Xr();_a();Ua();ym=async()=>{let e=Xe(g().breadCrumb,"BOARD");if(a(e))return e;let t=await ut(process.cwd());if(a(t))return i("Unable to locate repo root");let n=Ce({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=de().commandMeta,{dateInput:s,durationInput:d}=gs(r,o);if(jn(),g().syncStatus.status==="syncing")return i("Cannot replay while syncing, try again in a moment");let l=Dn(s);if(!l)return i("Invalid replay date");let u=d?ps(d):15e3;if(u===null)return i("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=g(),f=$s({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(f))return f;let{unappliedEvents:I}=f.value;return I.length===0?(Vt(),E(p),c("Nothing to replay from that point",!0)):(fm({events:I,startTime:m,durationMs:u}),c("Replaying board history",!0))}});import Yy from"zod";var xm,Im=y(()=>{"use strict";On();ue();C();Re();Ue();k();xm=()=>{let e=de().commandMeta.inputString,t=Yy.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return i("Auto sync duration must be a number of at least 3000 ms");let n=it({autoSyncDebounceMs:t.data});return a(n)?n:(nt({autoSyncIntervalMs:t.data}),E({mode:h.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))}});var Em,Rm=y(()=>{"use strict";Kr();On();ue();C();Re();Ue();k();Em=()=>{let e=de().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=Jc(e),n=it({autoSync:t});return a(n)?n:(nt({autoSync:t}),E({mode:h.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var Nm,Sm=y(()=>{"use strict";On();ue();C();Re();Ue();k();Nm=()=>{let e=de().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return i("Invalid response");let n=it({logLevel:e});return a(n)?n:(nt({logLevel:e}),E({mode:h.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});import{spawn as Xy}from"node:child_process";var Jy,Cm,Am=y(()=>{"use strict";C();Jy=()=>{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"]}}},Cm=async e=>new Promise(t=>{let{command:n,args:r}=Jy();try{let o=Xy(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(i(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?c("Copied to clipboard",null):i(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(i(`Clipboard tool not available (${n})`))}})});var ho,Tm,wm=y(()=>{"use strict";C();k();Am();en();Yr();cn();ho=async(e,t)=>{if(!e.trim())return i(`Nothing to copy: ${t} is empty`);let n=await Cm(e);return a(n)?n:c(`Copied ${t} to clipboard`,null)},Tm=async e=>{let{breadCrumb:t,selectedNode:n}=g(),r=Jr({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return i("Nothing selected to copy from");switch(e.modifier){case Ne.REF:return ho(K(o.id),"ref");case Ne.TITLE:return ho(o.title,"title");case Ne.DESCRIPTION:return r?ho(r.props?.description??"","description"):i("No issue in scope");case Ne.TAGS:{if(!r)return i("No issue in scope");let s=an(r).map(({name:d})=>d);return ho(s.join(", "),"tags")}case Ne.ASSIGNEES:{if(!r)return i("No issue in scope");let s=dn(r).map(({name:d})=>d);return ho(s.join(", "),"assignees")}default:return i("Yank one of: ref, title, description, tags, assignees")}}});var Mm,km=y(()=>{"use strict";_i();ue();C();Re();k();Mm=async()=>{V(""),E({mode:h.DEFAULT});let e=Ge();if(a(e))return i(e.message);if(e.value.syncStatus.status==="syncing")return i("Sync already in progress");E({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await ss();return a(t)?(E({syncStatus:{msg:t.message,status:"failed"}}),t):(E({mode:h.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as _e}from"ulid";var Qy,Lm,zt,Pm,Dm=y(()=>{"use strict";ge();ju();Ze();hr();On();Mn();gt();Aa();zn();ue();xt();he();C();ge();Rt();Re();Ue();k();Os();pe();wa();Pn();da();cn();ro();Ku();Zu();im();dm();pm();vm();bm();Im();ea();Rm();Sm();wm();km();Qy=e=>e.action==="add.issue.comment",Lm=()=>{let{eventLog:e=[],contributors:t}=g(),n=new Map,r=new Set;for(let o of e)o.userId&&(n.set(o.userId,o.userName??""),r.add(o.userId));for(let o of Object.values(t))n.set(o.id,o.name);return[...n.entries()].map(([o,s])=>({id:o,name:s,isExternal:!r.has(o)}))},zt=async()=>{let e=await Ct();return a(e)?e:c("Resolved persist root",e.value)},Pm=[{systemOnly:!0,intent:F.Move,description:"Internal move-state command",mode:h.COMMAND_LINE,action:sm},{intent:F.Delete,description:"Delete the currently selected node",mode:h.COMMAND_LINE,action:async()=>{let e=ve();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=ae(t.id)[n];if(!r)return i("Unable to resolve child to delete");let o=await zt();if(a(o))return o;if(r.context==="COMMENT"){let s=r.id,d=P(t)?t.id:t.parentNodeId;if(!d)return i("Unable to resolve comment issue");let l=g().nodes[d];if(!l||!P(l))return i("Unable to resolve comment issue");let u=l.log?.filter(Qy).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):O([{id:_e(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],o.value):i("Unable to resolve comment")}return O([{id:_e(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:h.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=de().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(d=>Ee(v.FILTER).map(l=>l.split(n)[0]).includes(d))(r))return i("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return ie(d=>({...d,filters:e==="clear"?[]:[...d.filters,s],mode:h.DEFAULT})),c("Filter updated",null)}},{intent:F.ViewHelp,description:"Open the help screen",mode:h.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return gn({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),E({mode:h.HELP}),c("Viewing help",null)}},{intent:F.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:h.COMMAND_LINE,action:async()=>{let e=ve();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=ae(t.id)[n];if(!r)return i("Unable to close issue, no target found");if(!P(r))return i("Cannot close in this context");let o=g().nodes[Ie];if(!o)return i("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return i("Issue is already closed");let s=await zt();if(a(s))return s;let d=s.value,l=on(o.id,r.id,{at:"end"},e.value,d);if(a(l))return l;let u=O([{id:_e(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...e.value}],d);return a(u)?u:c("Issue closed",null)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:h.COMMAND_LINE,action:async()=>{let e=ve();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=ae(t.id)[n];if(!r)return i("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):Hn(r.id,"TICKET");if(a(o))return i("Cannot reopen in this context");let s=o.value,d=g().nodes[Ie];if(!d)return i("Unable to locate closed swimlane");if(s.parentNodeId!==d.id)return i("Issue is not closed");if(!P(s))return i("Target node is not issue");let l=Fs(s);if(!l)return i("Unable to resolve previous parent from issue history");if(l===d.id)return i("Previous parent resolves to closed swimlane");let u=g().nodes[l];if(!u)return i("Previous parent no longer exists");let m=await zt();if(a(m))return m;let p=m.value,f=on(u.id,s.id,{at:"end"},e.value,p);if(a(f))return f;let I=O([{id:_e(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...e.value}],p);return a(I)?I:c("Issue reopened",null)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Init,description:"Initialize Epiq in the current git repository",mode:h.COMMAND_LINE,action:Qu},{intent:F.OpenProject,description:"Open a recently used epiq project, by number or path",mode:h.COMMAND_LINE,action:mm,onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.NewItem,description:"Create a new board, swimlane, or issue",mode:h.COMMAND_LINE,action:am,onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Rename,description:"Rename the currently selected node",mode:h.COMMAND_LINE,action:async()=>{let e=ve();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=ae(t.id)[n];if(!r)return i("Missing node");if(r.readonly)return i("Cannot rename readonly node");let o=Ss();if(!o)return i("Provide a title");let s=await zt();return a(s)?s:O([{id:_e(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.UntagTicket,description:"Remove a tag from the selected issue",mode:h.COMMAND_LINE,action:async()=>{let e=ve();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=de().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let o=x.findTagByName(r);if(!o)return i(`Tag "${r}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid untag target");let d=Hn(s.id,"TICKET");if(a(d))return i("Unable to untag issue in this context");let l=d.value;if(!P(l))return i("Target node is not issue");if(!(l.props.tags??[]).includes(o.id))return i("Issue is not tagged with that tag");let m=await zt();return a(m)?m:O([{id:_e(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.TagTicket,description:"Add or create a tag on the selected issue",mode:h.COMMAND_LINE,action:async()=>{let e=ve();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=de().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let{selectedNode:o}=g();if(!o)return i("Invalid tag target");let s=Hn(o.id,"TICKET");if(a(s))return i("Unable to tag issue in this context");let d=s.value;if(!P(d))return i("Target node is not issue");let l=await zt();if(a(l))return l;let u=x.findTagByName(r),m=u?.id??_e();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):O([...u?[]:[{id:_e(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:_e(),action:"add.issue.tag",payload:{id:d.id,tag:m},...e.value}],l.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.AssignUserToTicket,description:"Assign a user to the selected issue",mode:h.COMMAND_LINE,action:async()=>{let e=ve();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=de().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return i("Provide an assignee");let{selectedIndex:d,contextNode:l}=g(),u=ae(l.id)[d];if(!u)return i("Invalid assign target");let m=Hn(u.id,"TICKET");if(a(m))return i("Unable to assign issue in this context");let p=m.value;if(!P(p))return i("Target node is not issue");let f=await zt();if(a(f))return f;let I=Lm(),N=!o&&s.toLowerCase()==="me",A,w;if(N)A=e.value.userId,w=I.find(U=>U.id===A)?.name??e.value.userName;else{let U=I.filter(be=>be.name===s);if(U.length>1)return i(`"${s}" matches ${U.length} contributors (${U.map(be=>be.id).join(", ")}). Assign from the GUI to choose by id.`);let ne=U[0];if(!ne&&!o)return i(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);A=ne?.id??_e(),w=ne?.name??s}if((p.props.assignees??[]).includes(A))return i("Assignee already assigned");let M=!!g().contributors[A];return O([...M?[]:[{id:_e(),action:"create.contributor",payload:{id:A,name:w},...e.value}],{id:_e(),action:"add.issue.assignee",payload:{id:p.id,assignee:A},...e.value}],f.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:h.COMMAND_LINE,action:async()=>{let e=ve();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=de().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee to remove");let{selectedNode:o}=g();if(!o)return i("Invalid unassign target");let s=Hn(o.id,"TICKET");if(a(s))return i("Unable to unassign in this context");let d=s.value;if(!P(d))return i("Target node is not issue");let l=d.props.assignees??[],u=r.toLowerCase()==="me",m=u?l.filter(I=>I===e.value.userId):Lm().filter(I=>I.name===r&&l.includes(I.id)).map(I=>I.id);if(m.length>1)return i(`"${r}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return i(u?"Issue is not assigned to you":`Issue is not assigned to "${r}"`);let f=await zt();return a(f)?f:O([{id:_e(),action:"remove.issue.assignee",payload:{id:d.id,assignee:p},...e.value}],f.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Comment,description:"Add a comment to the selected issue",mode:h.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return i("Provide a comment");if(n.length>4e3)return i(`Cannot exceed ${4e3} characters`);let r=ve();if(a(r))return i("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=g(),d=Xe([...o,s],"TICKET");if(a(d))return i("Edit target must be an issue");let l=d.value;if(!l)return i("Invalid comment target");let u=l.context==="TICKET"?c("Resolved ticket",l):Hn(l.id,"TICKET");if(a(u))return i("Unable to comment on issue in this context");let m=u.value;if(!P(m))return i("Target node is not issue");let p=await zt();return a(p)?p:O([{id:_e(),action:"add.issue.comment",payload:{id:_e(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Sync,description:"Pull, commit, and push Epiq state",mode:h.COMMAND_LINE,action:Mm},{intent:F.Peek,description:"View board state at another point in time",mode:h.COMMAND_LINE,action:hm},{intent:F.Replay,description:"Replay board history forward from a point in time",mode:h.COMMAND_LINE,action:ym},{intent:F.Export,description:"Export the current board layout to markdown",mode:h.COMMAND_LINE,action:async()=>{let e=await $u();return a(e)?e:(E({mode:h.DEFAULT}),c("Export successful",!0))}},{intent:F.Exit,description:"Exit the application",mode:h.COMMAND_LINE,action:async()=>(_.exit(),c("Exit successful",!0))},{intent:F.Edit,description:"Edit title or description",mode:h.COMMAND_LINE,action:async(e,t)=>zu(t),onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:h.COMMAND_LINE,action:async(e,t)=>Tm(t),onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:h.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case fe.USERNAME:{if(process.env[yt])return i(`Cannot change the configured user while ${yt} names this process`);let r=ys();if(a(r))return r;let{userId:o,preferredEditor:s,userName:d}=r.value,l=n||d,u=o||_e();if(!l||!u)return i("Unable to resolve user name or id");let m=it({userName:l,userId:u,preferredEditor:s??""});return a(m)?m:(nt({userName:l,userId:u}),E({mode:h.DEFAULT}),c(`Username set to "${l}"`,null))}case fe.EDITOR:{if(!n)return i("No editor provided");let r=it({preferredEditor:n});return a(r)?r:(nt({preferredEditor:n}),E({mode:h.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case fe.VIEW:{if(n!=="wide"&&n!=="dense")return i("Invalid view mode");let r=it({viewMode:n});return a(r)?r:(nt({viewMode:n}),E({mode:h.DEFAULT}),c(`View set to "${n}"`,null))}case fe.AUTOSYNC:return Em();case fe.LOG_LEVEL:return Nm();case fe.SYNC_DEBOUNCE_MS:return xm();case fe.ATTACHMENT_MAX_KB:return fl();default:return i("Unknown config command")}}},{intent:F.Coffee,description:"Sponsor the development of Epiq!",mode:h.COMMAND_LINE,action:()=>{let e=de().commandMeta.modifier;return e==="custom"?po("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):po(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),V(""),c("Thanks you!",null)}}]});var Zy,Dt,ja=y(()=>{"use strict";is();Is();da();Dm();C();Re();Ue();k();Zy=new Set(["peek","replay","filter","view-help","yank"]),Dt=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=de();if(!t)return i("No command to confirm");if(!e&&n===ln.Invalid)return i("Invalid command");let s=ql(t);jl();let{readOnly:d}=g();if(d&&!Zy.has(s))return oo({status:Ft.Fail,message:"Command not available in readonly state",value:null});let l=Pm.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return oo({status:Ft.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return oo({status:Ft.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?oo(u):(Hl({addToHistory:!e}),l.onSuccess?.(),xe().autoSync&&Hc(),u)}});var Ws,Gs,Fm,Om=y(()=>{"use strict";C();ue();k();In();ja();Oa();Re();Ws=[{intent:D.Exit,mode:h.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:h.COMMAND_LINE}),V("move cancel"),Dt({isForceExecutedBySystem:!0}))},{intent:D.InitMove,mode:h.DEFAULT,description:"[m] move (init/confirm)",action:()=>(E({mode:h.COMMAND_LINE}),V("move start"),Dt({isForceExecutedBySystem:!0}))},{intent:D.ConfirmMove,mode:h.MOVE,action:()=>(E({mode:h.COMMAND_LINE}),V("move confirm"),Dt({isForceExecutedBySystem:!0}))}],Gs=[{intent:D.MovePreviousItem,mode:h.MOVE,action:()=>fn()?(E({mode:h.COMMAND_LINE}),V("move previous"),Dt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:D.MoveNextItem,mode:h.MOVE,action:()=>fn()?(E({mode:h.COMMAND_LINE}),V("move next"),Dt({isForceExecutedBySystem:!0})):i("No pending move")}],Fm=[{intent:D.MoveToNextContainer,mode:h.MOVE,action:()=>fn()?(E({mode:h.COMMAND_LINE}),V("move to-next"),Dt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:D.MoveToPreviousContainer,mode:h.MOVE,action:()=>fn()?(E({mode:h.COMMAND_LINE}),V("move to-previous"),Dt({isForceExecutedBySystem:!0})):i("No pending move")}]});var Bm,_m=y(()=>{"use strict";he();Om();Bm={[B.WORKSPACE]:[...Ws,...Gs],[B.BOARD]:[...Ws,...Gs],[B.SWIMLANE]:[...Ws,...Gs,...Fm],[B.TICKET]:[],[B.FIELD]:[],[B.FIELD_LIST]:[],[B.TEXT]:[],[B.COMMENT]:[]}});import eb from"node:fs";import tb from"node:path";var Um,$m=y(()=>{"use strict";mt();Zr();C();pe();wa();Um=e=>{let t=Qe(process.cwd());if(a(t))return i("Unable to resolve project root");let n=Ce({repoRoot:t.value});if(a(n))return i(n.message);let r=Qr(e.hash,e.ext),o=tb.join(Uo(n.value),r);return eb.existsSync(o)?(po(o),c(`Opened ${e.name}`,null)):i("Attachment file not found \u2014 run :sync to fetch it")}});var jm,Hm,Wm=y(()=>{"use strict";ue();C();Re();k();Os();In();Ze();jm=()=>{V("");let{pendingNavTarget:e}=ur();E({mode:h.DEFAULT}),e&&_.navigate(e),gn({pendingNavTarget:void 0})},Hm=[{intent:D.ExitCommandLine,mode:h.HELP,action:()=>(jm(),c("Exiting help",null))},{intent:D.Exit,mode:h.HELP,action:()=>(jm(),c("Closed help",null))},{intent:D.NavPreviousItem,mode:h.HELP,description:"[arrows/hjkl] navigate",action:()=>(_.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:D.NavNextItem,mode:h.HELP,action:()=>(_.navigateToNextItem(),c("Navigating to next help item",null))},{intent:D.NavToPreviousContainer,mode:h.HELP,action:()=>(_.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:D.NavToNextContainer,mode:h.HELP,action:()=>(_.navigateToNextContainer(),c("Navigating to next help container",null))}]});var nb,Gm,qm,Vm=y(()=>{"use strict";ue();he();C();Re();k();Os();In();Ze();nb=e=>{E({mode:h.COMMAND_LINE});let{pendingNavTarget:t}=ur();t&&_.navigate(t),gn({pendingNavTarget:void 0}),V(`${e} `)},Gm=()=>{V("");let{pendingNavTarget:e}=ur();e&&_.navigate(e),gn({pendingNavTarget:void 0}),E({mode:h.DEFAULT})},qm=[{intent:D.InitCommandPalette,mode:h.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{V("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return gn({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),E({mode:h.PALETTE}),c("Opening command palette",null)}},{intent:D.Confirm,mode:h.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!id(e))return i("Command only applicable on text nodes");if(e.props.disabled)return i("Command is not available in this context");let t=e.title;return t?(nb(t),c("Selected command",t)):c("No command selected",null)}},{intent:D.ExitCommandLine,mode:h.PALETTE,action:()=>(Gm(),c("Exiting palette",null))},{intent:D.Exit,mode:h.PALETTE,action:()=>(Gm(),c("Closed command palette",null))},{intent:D.NavPreviousItem,mode:h.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(_.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:D.NavNextItem,mode:h.PALETTE,action:()=>(_.navigateToNextItem(),c("Navigating to next item",null))},{intent:D.NavToPreviousContainer,mode:h.PALETTE,action:()=>(_.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:D.NavToNextContainer,mode:h.PALETTE,action:()=>(_.navigateToNextContainer(),c("Navigating to next container",null))}]});var zm,Km=y(()=>{"use strict";Pn();cn();ue();C();Vn();ge();Rt();Re();k();$m();In();Wm();Vm();Ze();zm=[...Hm,...qm,{intent:D.AddItem,mode:h.DEFAULT,description:"[n] new...",action:()=>(E({mode:h.COMMAND_LINE}),V(`${v.NEW} `),c("Adding new item",null))},{intent:D.Delete,mode:h.DEFAULT,description:"[d] delete",action:()=>(E({mode:h.COMMAND_LINE}),V(`${v.DELETE} `),c("Deleting item",null))},{intent:D.InitCommandLine,mode:h.DEFAULT,description:"[:] focus command line",action:()=>(E({mode:h.COMMAND_LINE}),V(""),c("Entering command line mode",null))},{intent:D.Confirm,mode:h.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!me(e?.id??"")?.length){let r=e?x.getAttachment(e.id):void 0;if(r)return Um(r);if(e?.title===se.DESCRIPTION)return E({mode:h.COMMAND_LINE}),V(`${v.EDIT} description `),c("Propose command",!0);if(e?.title===se.ASSIGNEES)return E({mode:h.COMMAND_LINE}),V(`${v.ASSIGN} `),c("Propose command",!0);if(e?.title===se.TAGS)return E({mode:h.COMMAND_LINE}),V(`${v.TAG} `),c("Propose command",!0);if(t.title===se.DESCRIPTION&&e?.context==="TEXT")return E({mode:h.COMMAND_LINE}),V(`${v.EDIT} description `),c("Propose command",!0)}return _.enterChildNode(),c("Entering context",null)}},{intent:D.Yank,mode:h.DEFAULT,description:"[y] yank to clipboard",action:()=>{let{selectedNode:e}=g(),t=e?.title===se.DESCRIPTION?Ne.DESCRIPTION:e?.title===se.TAGS?Ne.TAGS:e?.title===se.ASSIGNEES?Ne.ASSIGNEES:Ne.REF,r=Ee(v.YANK).includes(t)?t:Ne.REF;return E({mode:h.COMMAND_LINE}),V(`${v.YANK} ${r}`),c("Propose command",!0)}},{intent:D.EditTitle,mode:h.DEFAULT,description:"[r] rename title",action:()=>(E({mode:h.COMMAND_LINE}),V(`${v.EDIT} title ${g().selectedNode?.title}`),c("Exiting context",null))},{intent:D.EditDescription,mode:h.DEFAULT,description:"[e] edit description",action:()=>(E({mode:h.COMMAND_LINE}),V(`${v.EDIT} description `),c("Exiting context",null))},{intent:D.Exit,mode:h.DEFAULT,description:"[q] exit context",action:()=>(_.enterParentNode(),c("Exiting context",null))},{intent:D.NavPreviousItem,mode:h.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(_.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:D.NavNextItem,mode:h.DEFAULT,action:()=>(_.navigateToNextItem(),c("Navigating to next item",null))},{intent:D.NavToPreviousContainer,mode:h.DEFAULT,action:()=>(_.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:D.NavToNextContainer,mode:h.DEFAULT,action:()=>(_.navigateToNextContainer(),c("Navigating to next container",null))}]});var rb,ob,Ym,Xm=y(()=>{"use strict";Re();rb=500,ob=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Ym=e=>{let t=ob(e);t&&Ns(n=>(n+t).slice(0,rb))}});var sb,ib,Jm,Qm=y(()=>{"use strict";Xm();ue();C();Re();k();In();ja();sb=[h.COMMAND_LINE,h.PALETTE],ib=e=>[{intent:D.MoveCursorLeft,mode:e,action:()=>(ia(-1),c("Moving cursor left",null))},{intent:D.MoveCursorRight,mode:e,action:()=>(ia(1),c("Moving cursor right",null))},{intent:D.MoveCursorLeftOfWord,mode:e,action:()=>(aa("left"),c("Moving cursor left of word",null))},{intent:D.MoveCursorRightOfWord,mode:e,action:()=>(aa("right"),c("Moving cursor right of word",null))},{intent:D.AutoCompleteCommand,mode:e,action:()=>(Ns((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=g().selectedNode?.title??""),r+o}),c("Auto-completing command",null))},{intent:D.CaptureInput,mode:e,action:(t,{sequence:n})=>(Ym(n??""),c("Capturing input",null))},{intent:D.EraseInput,mode:e,action:()=>(Ul(),c("Erasing input",null))},{intent:D.EraseInputWord,mode:e,action:()=>($l(),c("Erasing input word",null))}],Jm=[{intent:D.Confirm,mode:h.COMMAND_LINE,action:()=>(Dt(),c("Executing command",null))},{intent:D.ViewHelp,mode:h.DEFAULT,action:()=>(E({mode:h.HELP}),c("Viewing help",null))},...sb.flatMap(ib),{intent:D.ExitCommandLine,mode:h.COMMAND_LINE,action:()=>(E({mode:h.DEFAULT}),c("Exiting command line",null))},{intent:D.GetLastCommandFromHistory,mode:h.COMMAND_LINE,action:()=>(Wl(),c("Getting last command from history",null))},{intent:D.GetNextCommandFromHistory,mode:h.COMMAND_LINE,action:()=>(Gl(),c("Getting next command from history",null))}]});import tp from"chalk";var qs,Zm,ep,Ha,np=y(()=>{"use strict";ue();he();Fe();qs=tp.dim.hex(S.secondary2)(": for command line"),Zm="q to exit",ep=`${tp.hex(S.accent)("m")} to confirm`,Ha={[B.WORKSPACE]:[qs],[B.BOARD]:[qs],[B.BOARD+h.COMMAND_LINE]:[qs],[B.SWIMLANE]:[qs],[B.TICKET+h.HELP]:[Zm],[B.SWIMLANE+h.HELP]:[Zm],[B.TICKET]:[],[B.FIELD]:[],[B.SWIMLANE+h.MOVE]:[ep],[B.TICKET+h.MOVE]:[ep]}});var mr,Wa,rp=y(()=>{"use strict";en();mr=e=>e.trim().toLocaleLowerCase(),Wa=(e,t)=>mr(e).includes(mr(t))});var ab,db,op,sp=y(()=>{"use strict";k();en();rp();ab=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},db=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},op=(e,t)=>{let n=mr(t.value);if(!n)return!0;switch(t.target){case"title":return Wa(e.title??"",n);case"description":return Wa(e.props.description??"",n);case"tag":return ab(e).map(mr).some(o=>o.includes(n));case"assignee":return db(e).map(mr).some(o=>o.includes(n));case"ref":return Lr(e.id,t.value);default:return!0}}});function ip(e,t,n){let r=t[e];if(!r)return i("buildBreadCrumb(): current node not found");let o=[],s=new Set,d=r;for(;d&&!s.has(d.id)&&(o.push(d),s.add(d.id),!(d.id===n||!d.parentNodeId));)d=t[d.parentNodeId];let l=o[o.length-1];return!l||l.id!==n?i("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var ap=y(()=>{"use strict";C()});var dp,cp=y(()=>{"use strict";dp=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t}});import{useSyncExternalStore as cb}from"react";function za(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return i("derive(): contextNodeId is missing");if(!r)return i("derive(): rootNode is missing");if(!o[r])return i("derive(): unable to find root node");let l=o[t];if(!l)return i("Unable to derive state, contextNode not found");let u=ip(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,f=Ha[p+n]??Ha[p]??[],I=[...zm,...Bm[p]??[],...Jm],N=dp(I),A=ub(o,s),w=A[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:f,availableActions:I,actionIndex:N,selectedNode:w,renderedChildrenIndex:A})}function Fr(e){Ga=e;let t=Qe(process.cwd()),n=!1;if(!a(t)){let s=Ot(t.value);if(a(s))return i(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:h.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{},attachments:{}},o=za(r);return a(o)?o:(Kt=o.value,Va(),c("State initialized",null))}function ie(e){let t=g(),n=e(t);if(vo)return Vs=n,Kt={...t,...n},c("State updated",null);let r=za(n);return a(r)?i(r.message??"Unable to update state"):(Kt=r.value,Va(),c("State updated",null))}function qd(e){if(vo)return c("Joined batch",e());vo=!0,Vs=null;let t=()=>{let n=Vs;if(vo=!1,Vs=null,n===null)return null;let r=za(n);return a(r)?i(r.message??"Unable to update state"):(Kt=r.value,Va(),c("State updated",null))};try{let n=e(),r=t();return r&&a(r)?i(r.message):c("State updated",n)}finally{vo&&t()}}var Kt,Ga,qa,Va,lb,g,Ge,vo,Vs,E,Ke,ub,ae,Vt,At,k=y(()=>{"use strict";_m();Km();Qm();np();Bt();ue();he();C();pe();sp();ap();cp();qa=new Set,Va=()=>{for(let e of qa)e()},lb=e=>(qa.add(e),()=>qa.delete(e));g=()=>{if(!Kt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Kt},Ge=()=>Kt?c("Retrieved state",Kt):i("State not initialized. Call initWorkspaceState() first.");vo=!1,Vs=null;E=e=>ie(t=>({...t,...e})),Ke=()=>cb(lb,g,g),ub=(e,t)=>{let n={};for(let r of Object.values(e))P(r)&&t.length>0&&!t.every(o=>op(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,s)=>{let d=e[o.id],l=e[s.id];return!d||!l?0:d.rank.localeCompare(l.rank)});return n},ae=e=>g()?.renderedChildrenIndex[e]??[],Vt=()=>Ga?Fr(Ga):i("Cannot reset state: no initial workspace found"),At=()=>Kt!==void 0});var Hn,mb,hn,x,ge=y(()=>{"use strict";xt();he();C();k();Rt();Hn=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r)return i("Node not found");if(r.context===t)return c("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 c("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return i(`No ancestor found for context: ${t}`)},mb=(e,t)=>{let{nodes:n}=g(),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},hn=(e,t)=>e?e.readonly?i({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:i("Node not found"),x={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return i("Contributor not found");if(n.userId&&n.userId!==t)return i("Contributor is already linked to another user");let r={...n,userId:t},o=ie(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?i("Unable to link contributor to user"):c("Linked contributor to user",r)},deleteNode(e){ie(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create comment, missing issue");if(!P(t))return i("Can only comment on issues");let n=ie(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?i("Unable to create comment"):c("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return i("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return i("Unable to edit comment, missing issue");if(!P(r))return i("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=ie(d=>({...d,comments:{...d.comments??{},[e]:o}}));return a(s)?i("Unable to edit comment"):c("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return i("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=ie(o=>({...o,comments:{...o.comments??{},[e]:n}}));return a(r)?i("Unable to delete comment"):c("Deleted comment",n)},getComment(e){return g().comments?.[e]},getCommentsByIssue(e){return Object.values(g().comments??{}).filter(t=>t.issue===e&&!t.deleted)},createAttachment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create attachment, missing issue");if(!P(t))return i("Can only attach to issues");let n=ie(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?i("Unable to create attachment"):c("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return i("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=ie(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return a(r)?i("Unable to delete attachment"):c("Deleted attachment",n)},getAttachment(e){return g().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(g().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=g(),r=n[e];if(!r)return i("Edit target node not found");let o=hn(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return i("Rename target node not found");let r=hn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=g();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return me(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=g(),o=this.getNode(e),s=this.getNode(t);if(!o)return i("Node not found");if(!s)return i("Target parent not found");if(r===e)return i("Cannot move root node");if(e===t)return i("Cannot move node into itself");let d=hn(o,"move");if(d)return d;if(mb(t,e))return i("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=g(),o=this.getNode(e);if(!o)return i("Node not found");if(r===e)return i("Cannot delete root node");let s=hn(o,"delete");if(s)return s;let d=new Set,l=m=>{let p=t[m];if(!(!p||d.has(m))){d.add(m);for(let f of me(p.id))l(f.id)}};l(e);let u={...structuredClone(t)};for(let m of d){if(!u[m])return i("Unable to locate node to delete");u[m]={...u[m],isDeleted:!0}}return n?(E({nodes:u}),c("Successfully tomb stoned",o)):i("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return i("Contributor not found");let n={...t,name:So,tombstoned:!0},r=ie(o=>({...o,contributors:{...o.contributors,[e]:n}}));return a(r)?i("Unable to remove contributor"):c("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return i("Contributor not found");if(n.tombstoned)return i("Cannot rename a removed contributor");let r={...n,name:t},o=ie(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?i("Unable to rename contributor"):c("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return i("Contributor not found");let r={...n,name:t,tombstoned:!1},o=ie(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?i("Unable to restore contributor"):c("Restored contributor",r)},createContributor(e){let t=ie(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?i("Unable to create contributor"):c("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return i("Unable to assign contributor, missing contributor");if(!r)return i("Unable to assign contributor, missing target");let o=hn(r,"edit");if(o)return o;if(!P(r))return i("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return i("Contributor already assigned");let d={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(d),c("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return i("Unable to unassign, missing contributor");if(!r)return i("Unable to unassign, missing target");let o=hn(r,"edit");if(o)return o;if(!P(r))return i("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return c("Issue is not assigned to that contributor",{assignee:t});let d={...r,props:{...r.props,assignees:s.filter(l=>l!==t)}};return this.updateNode(d),c("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return i("Unable to add tag, missing tag");if(!r)return i("Unable to add tag, missing target");let o=hn(r,"edit");if(o)return o;if(!P(r))return i("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return i("Tag already assigned");let d={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(d),c("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),r=this.getNode(e);if(!n)return i("Unable to remove tag, missing tag");if(!r)return i("Unable to remove tag, missing target");let o=hn(r,"edit");if(o)return o;if(!P(r))return i("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return c("Issue is not tagged with that tag",{tag:t});let d={...r,props:{...r.props,tags:s.filter(l=>l!==t)}};return this.updateNode(d),c("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return i("Tag not found");let n={...t,tombstoned:!0},r=ie(o=>({...o,tags:{...o.tags,[e]:n}}));return a(r)?i("Unable to delete tag"):c("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return i("Tag not found");let r={...n,name:t,tombstoned:!1},o=ie(s=>({...s,tags:{...s.tags,[e]:r}}));return a(o)?i("Unable to restore tag"):c("Restored tag",r)},createTag(e){let t=ie(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?i("Could not create tag"):c("Tag created",e)},createNode(e){let t=ie(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?i("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return i("Failed to locate node");let n={...t,readonly:!0},r=ie(o=>({...o,nodes:{...o.nodes,[e]:n}}));return a(r)?i(r.message):c("Locked node",n)},updateNode(e){let t=ie(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?t:c("Updated node",e)},getContributor(e){return g().contributors[e]},getTag(e){let t=g().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return g().tags[e]},getTags(){return Object.values(g().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return g().nodes[e]},getSiblings(e){return me(e)}}});import vn from"chalk";import lp from"string-width";var pb,gb,Ka,fb,hb,up,mp,vb,yb,bb,xb,Ib,$a,pp,fo=y(()=>{"use strict";dt();ge();k();kt();Ls();pb=(e,t)=>e+" ".repeat(Math.max(0,t-lp(e))),gb=(e,t)=>" ".repeat(Math.max(0,t-lp(e)))+e,Ka=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed contributor","link.contributor.user":"Linked contributor","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),fb=(e,t)=>t?e<t?"up":e>t?"down":null:null,hb=(e,t)=>{let n=x.getNode(e.payload.parent),r=n?vn.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=fb(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},up=e=>`${Math.max(1,Math.round(e/1024))} KB`,mp=e=>x.getAttachment(e)?.name??"",vb=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?vn.bgHex(Oe(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?vn.bgHex(Oe(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=g().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?vn.hex(Oe(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?vn.hex(Oe(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${vn.dim(`(${up(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=mp(e.payload.id);return t?`"${t}"`:""}default:return""}},yb=e=>{let t=cr(bt(e));return vn.gray(gb(t,8))},bb=12,xb=e=>pb(`${e}`,bb),Ib=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=g().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=x.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${up(e.payload.bytes)})`;case"delete.issue.attachment":{let t=mp(e.payload.id);return t?`"${t}"`:""}default:return""}},$a=e=>[Ka(e.action),Ib(e)].filter(Boolean).join(" "),pp=(e,t)=>{let n=yb(e.id),r=xb(e.userName),o=vn.dim("\u203A"),s=e.action==="move.node"?hb(e,t):[Ka(e.action),vb(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`}});var fp={};Eo(fp,{areVirtualNodesEnabled:()=>Wo,createOrUpdateVirtualField:()=>yo,createOrUpdateVirtualFieldList:()=>Ya,materializeTicketVirtualNodes:()=>Ho,materializeVirtualNodes:()=>Mb,setVirtualNodesEnabled:()=>wb});var Eb,Rb,Nb,Sb,Cb,Ab,yo,Ya,Ho,Tb,gp,wb,Wo,Mb,Ii=y(()=>{"use strict";fo();he();C();Vn();ge();Sn();k();Gn();er();Eb=e=>Te(e,"comments"),Rb=e=>Te(e,"description"),Nb=e=>Te(e,"assignees"),Sb=e=>Te(e,"tags"),Cb=e=>Te(e,"history"),Ab=e=>Te(e,"attachments"),yo=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:d="horizontal"})=>{let l=x.getNode(e);if(!l){let p=x.createNode({...Ae.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:d});return a(p)?p:c("Virtual field created",void 0)}if(!Je(l))return i(`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!==d))return c("Virtual field unchanged",void 0);let m=x.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:s,childRenderAxis:d});return a(m)?m:c("Virtual field updated",void 0)},Ya=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let d=x.getNode(e);if(!d){let m=x.createNode({...Ae.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return a(m)?m:c("Virtual field list created",void 0)}if(!br(d))return i(`Existing virtual node ${e} is not a field list`);if(!(d.title!==t||d.parentNodeId!==n||d.rank!==r||d.readonly!==o||d.childRenderAxis!==s))return c("Virtual field list unchanged",void 0);let u=x.updateNode({...d,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(u)?u:c("Virtual field list updated",void 0)},Ho=e=>{let t=rt(Et/4n),n=rt(Et/2n),r=rt(Et*3n/4n),o=rt(Et*7n/8n),s=rt(Et*15n/16n),d=rt(Et*13n/16n);if(a(t))return t;if(a(n))return n;if(a(r))return r;if(a(o))return o;if(a(s))return s;if(a(d))return d;let l=yo({id:Rb(e.id),name:se.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(l))return l;let u=Ya({id:Nb(e.id),name:se.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(u))return u;let m=Ya({id:Sb(e.id),name:se.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(a(m))return m;let p=yo({id:Eb(e.id),name:se.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(p))return p;let f=yo({id:Ab(e.id),name:se.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(f))return f;let I=yo({id:Cb(e.id),name:se.HISTORY,parentNodeId:e.id,rank:d.value,value:Tb(e),readonly:!0,childRenderAxis:"vertical"});return a(I)?I:c("Ticket virtual nodes materialized",void 0)},Tb=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=>pp(r,n.get(r.action)??[])).join(`
|
|
73
|
+
`)},gp=!0,wb=e=>{gp=e},Wo=()=>gp,Mb=()=>{let{nodes:e}=g();for(let t of Object.values(e)){if(!P(t))continue;let n=Ho(t);if(a(n))return n}return c("Virtual nodes materialized",void 0)}});var hp=y(()=>{"use strict"});var kb,vp,yp,bp,xp,zs=y(()=>{"use strict";mt();lt();en();Ma();dt();fo();kt();rn();Ut();hp();C();Bt();vs();pe();k();kb=null,vp=Promise.resolve(),yp=e=>{let t=vp.then(e,e);return vp=t.then(()=>{},()=>{}),t},bp=()=>{if(!At())return{mode:"live",asOfTime:null};let{timeMode:e}=g();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:kb}},xp=(e,t)=>{let n=new Map,r=new Set,o=d=>{let l=new Set,u=d;for(;u&&!l.has(u);){if(r.has(u))return u;l.add(u),u=n.get(u)}return null},s=[];for(let d of e){let l=d.payload,u=l?.id;if(!u)continue;d.action==="add.board"&&r.add(u);let m=l.parent??l.issue;m&&n.set(u,m),(u===t||o(u)===t)&&s.push(d)}return s}});import Lb from"node:fs";import Pb from"node:path";import{ulid as G}from"ulid";var Db,Fb,Xs,te,le,oe,Ip,Ob,Ep,Rp,Np,Sp,Cp,Ap,Tp,wp,Mp,kp,Lp,Pp,Dp,Fp,Op,Bp,_p,Up,$p,jp,Hp,Wp,Gp,qp,Vp,Bb,zp,Kp,Yp,Xp,Jp,Qp,Zp,eg=y(()=>{"use strict";mt();lt();Sr();Wr();Bi();On();Ba();dt();_r();rn();Mn();gt();zs();Aa();zn();he();C();ge();Rt();k();es();zr();pe();xt();fo();kt();ro();en();Xt();Zr();Nt();zs();Db=e=>{if(e.filePath)try{return c("Read attachment file",{data:Lb.readFileSync(e.filePath),name:e.name??Pb.basename(e.filePath)})}catch(t){return i(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?c("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):i("Provide either filePath or dataBase64")},Fb=()=>{let e=Ji();return a(e)?Wt:e.value.attachmentMaxKb??Wt},Xs=e=>{let t=Qe(e??process.cwd());return a(t)?i(t.message):c("Resolved Epiq repo root",t.value)},te=async(e,t)=>{let n=Xs(e);if(a(n))return n;let r=Ce({repoRoot:n.value});if(a(r))return i(r.message);let o=Jt(n.value);if(a(o))return i(o.message);let s=await Di({repoRoot:n.value,stateBranchName:o.value});if(a(s))return i(s.message);let d=await Ln({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(a(d))return i(d.message);if(t?.pull??!1){let m=await H({cwd:r.value,args:["pull","--ff-only"]});a(m)&&X.info(3,m.message)}let l=$t(r.value);if(a(l))return i(l.message);let u=sn(l.value.events,l.value.unreadable);return a(u)?i(u.message):c("Booted Epiq state",{repoRoot:n.value,stateBranchRoot:r.value})},le=()=>{let e=Ji();return a(e)?i(e.message):e.value.userId?e.value.userName?c("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):i("Unable to retrieve user name"):i("Unable to retrieve user id")},oe=()=>{let e=Ge();return a(e)?i(e.message):e},Ip=e=>(e.props.tags??[]).map(t=>x.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Oe(t.name)})),Ob=()=>{let e=Ge(),t=a(e)?[]:e.value.eventLog??[],n=new Map;for(let r of t)r.userId&&r.userName&&n.set(r.userId,r.userName);return n},Ep=(e,t)=>{let n=new Map(e);for(let r of Object.values(t))n.set(r.id,r.name);return n},Rp=e=>(e.props.assignees??[]).map(t=>x.getContributor(t)).filter(t=>t!=null).map(({id:t,name:n})=>({id:t,name:n,color:Oe(n)})),Np=async(e={})=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let r=Object.values(n.value.nodes).filter(o=>o.context==="BOARD"&&!o.isDeleted).map(o=>({id:o.id,ref:K(o.id),title:o.title,parentId:o.parentNodeId,readonly:!!o.readonly}));return c("Listed boards",r)},Sp=async(e={})=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let r=Object.values(n.value.nodes).filter(o=>o.context==="SWIMLANE"&&!o.isDeleted).filter(o=>!e.boardId||o.parentNodeId===e.boardId).map(o=>({id:o.id,title:o.title,boardId:o.parentNodeId,isClosed:o.id===Ie,readonly:!!o.readonly}));return c("Listed swimlanes",r)},Cp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let r=e.idOrRef.trim();if(!r)return i("Provide an issue id or ref");let o=Object.values(n.value.nodes).filter(P).filter(u=>!u.isDeleted),s=o.find(u=>u.id===r),d=s?[s]:o.filter(u=>Lr(u.id,r));if(d.length===0)return i(`No issue matches "${r}"`);if(d.length>1)return i(`"${r}" matches ${d.length} issues: ${d.map(u=>`${K(u.id)} (${Le(u.title)})`).join(", ")}. Use a full ref or id.`);let l=d[0];return c("Found issue",{id:l.id,ref:K(l.id),title:Le(l.title),description:l.props.description??"",createdAt:bt(l.id),parentNodeId:l.parentNodeId,isClosed:l.parentNodeId===Ie,readonly:!!l.readonly,tags:Ip(l),assignees:Rp(l)})},Ap=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let r=n.value.nodes,o=Object.values(r).filter(P).filter(s=>!s.isDeleted).filter(s=>e.includeClosed||s.parentNodeId!==Ie).filter(s=>e.boardId?(s.parentNodeId?r[s.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).map(s=>({id:s.id,ref:K(s.id),title:Le(s.title),description:s.props.description??"",createdAt:bt(s.id),parentNodeId:s.parentNodeId,isClosed:s.parentNodeId===Ie,readonly:!!s.readonly,tags:Ip(s),assignees:Rp(s)}));return c("Listed issues",o)},Tp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=Le(e.title);if(!o)return i("Issue title cannot be empty");let s=e.description??"",d=ft("Issue title",o,300)??ft("Issue description",s,2e4);if(d)return i(d);if((e.tagNames?.length??0)>20)return i(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return i(`Cannot set more than ${20} assignees at once`);let l=kn(e.parentId,n.value,t.value.stateBranchRoot);if(a(l))return l;let u=_s({name:o,parent:e.parentId,user:n.value,rank:l.value});if(a(u))return u;let m=[...u.value],p=m.find(A=>A.action==="add.issue")?.payload.id;if(!p)return i("Unable to determine created issue id");s&&m.push({id:G(),...n.value,action:"edit.description",payload:{id:p,md:s}});let f=[];for(let A of e.tagNames??[]){let w=Le(A).trim();if(!w||f.some(ne=>ne.name===w))continue;let T=ft("Tag name",w,60);if(T)return i(T);let M=x.findTagByName(w),U=M?.id??G();M||m.push({id:G(),...n.value,action:"create.tag",payload:{id:U,name:w}}),m.push({id:G(),...n.value,action:"add.issue.tag",payload:{id:p,tag:U}}),f.push({id:U,name:w})}let I=[];for(let A of e.assigneeNames??[]){let w=Le(A).trim();if(!w||I.some(ne=>ne.name===w))continue;let T=ft("Assignee name",w,80);if(T)return i(T);let M=Object.values(r.value.contributors).find(ne=>ne.name===w),U=M?.id??G();M||m.push({id:G(),...n.value,action:"create.contributor",payload:{id:U,name:w}}),m.push({id:G(),...n.value,action:"add.issue.assignee",payload:{id:p,assignee:U}}),I.push({id:U,name:w})}let N=O(m,t.value.stateBranchRoot);return a(N)?i(N.message):c("Created issue",{id:p,ref:K(p),title:o,parentId:e.parentId,description:s,tags:f,assignees:I})},wp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=on(Ie,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(r))return r;let o={id:G(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:Ie,rank:r.value}},s=O([o],t.value.stateBranchRoot);return a(s)?i(s.message):c("Closed issue",{id:e.issueId,ref:K(e.issueId)})},Mp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Target node is not issue");if(o.parentNodeId!==Ie)return i("Issue is not closed");let s=Fs(o);if(!s)return i("Unable to resolve previous parent from issue history");if(s===Ie)return i("Previous parent resolves to closed swimlane");let d=r.value.nodes[s];if(!d)return i("Previous parent no longer exists");let l=on(d.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(l))return l;let u={id:G(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:d.id,rank:l.value}},m=O([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Reopened issue",{id:o.id,ref:K(o.id),parentId:d.id})},kp=async e=>{let t=Xs(e.repoRoot);if(a(t))return t;let n=le();if(a(n))return n;let r=Ce({repoRoot:t.value});if(a(r))return r;let o=$t(r.value);if(a(o))return o;let s=sn(o.value.events,o.value.unreadable);if(a(s))return s;let d=on(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(a(d))return d;let l={id:G(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:d.value}},u=O([l],r.value);return a(u)?i(u.message):c("Moved issue",{id:e.issueId,ref:K(e.issueId),parentId:e.parentId})},Lp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=r.value.nodes[e.boardId];if(!o)return i("Board not found");if(!Co(o))return i("Target parent must be a board");if(o.readonly)return i("Cannot add a swimlane to a readonly board");if(bp().mode!=="live")return i("Cannot add a swimlane while time travelling");let s=Le(e.title);if(!s.trim())return i("Swimlane title cannot be empty");let d=ft("Swimlane title",s,300);if(d)return i(d);let l=kn(e.boardId,n.value,t.value.stateBranchRoot);if(a(l))return l;let u=G(),m={id:G(),...n.value,action:"add.swimlane",payload:{id:u,name:s,parent:e.boardId,rank:l.value}},p=O([m],t.value.stateBranchRoot);return a(p)?i(p.message):c("Created swimlane",{id:u,ref:K(u),title:s,boardId:e.boardId})},Pp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=r.value.nodes[e.swimlaneId];if(!o)return i("Swimlane not found");if(!xn(o))return i("Edit target must be a swimlane");if(o.readonly)return i("Cannot edit readonly swimlane");let s=Le(e.title);if(!s.trim())return i("Swimlane title cannot be empty");let d=ft("Swimlane title",s,300);if(d)return i(d);if(o.title===s)return c("No changes made",{id:e.swimlaneId,ref:K(e.swimlaneId),title:s});let l={id:G(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:s}},u=O([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Edited swimlane title",{id:e.swimlaneId,ref:K(e.swimlaneId),title:s})},Dp=async e=>{let t=Xs(e.repoRoot);if(a(t))return t;let n=le();if(a(n))return n;let r=Ce({repoRoot:t.value});if(a(r))return r;let o=$t(r.value);if(a(o))return o;let s=sn(o.value.events,o.value.unreadable);if(a(s))return s;let d=on(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(a(d))return d;let l={id:G(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:d.value}},u=O([l],r.value);return a(u)?i(u.message):c("Moved swimlane",{id:e.swimlaneId,ref:K(e.swimlaneId),boardId:e.boardId})},Fp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=r.value.nodes[e.swimlaneId];if(!o)return i("Swimlane not found");if(!xn(o))return i("Delete target must be a swimlane");let s={id:G(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},d=O([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Deleted swimlane",{id:e.swimlaneId,ref:K(e.swimlaneId)})},Op=async(e={})=>{Qo();let t=Xs(e.repoRoot);if(a(t))return i("Sync failed");let n=le();if(a(n))return n;let r=await os({cwd:t.value,ownEventFileName:wn(n.value)});return a(r)?(ki(r.message),r):(Zo(),c("Synced",r.value))},Bp=async(e={})=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();return a(n)?n:c("Retrieved Epiq state",{root:t.value.repoRoot,stateBranchRoot:t.value.stateBranchRoot,nodes:n.value.nodes,rootNodeId:n.value.rootNodeId,contextNode:n.value.contextNode,selectedIndex:n.value.selectedIndex,eventLog:n.value.eventLog})},_p=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Edit target must be an issue");if(o.readonly)return i("Cannot edit readonly issue");let s=ft("Issue description",e.description,2e4);if(s)return i(s);let d=o.props.description??"";if(d===e.description)return c("No changes made",{id:e.issueId,ref:K(e.issueId),description:d});let l={id:G(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},u=O([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Edited issue description",{id:e.issueId,ref:K(e.issueId),description:e.description})},Up=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Edit target must be an issue");if(o.readonly)return i("Cannot edit readonly issue");let s=Le(e.title);if(!s.trim())return i("Issue title cannot be empty");let d=ft("Issue title",s,300);if(d)return i(d);if(o.title===s)return c("No changes made",{id:e.issueId,ref:K(e.issueId),title:s});let l={id:G(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},u=O([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Edited issue title",{id:e.issueId,ref:K(e.issueId),title:s})},$p=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Tag target must be an issue");if(o.readonly)return i("Cannot tag readonly issue");let s=Le(e.tagName).trim();if(!s)return i("Tag name cannot be empty");let d=ft("Tag name",s,60);if(d)return i(d);let l=x.findTagByName(s),u=l?.id??G(),m=[...l?[]:[{id:G(),...n.value,action:"create.tag",payload:{id:u,name:s}}],{id:G(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:u}}],p=O(m,t.value.stateBranchRoot);return a(p)?i(p.message):c("Added issue tag",{id:e.issueId,ref:K(e.issueId),tag:{id:u,name:s}})},jp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return i("Tag not found");if(o.tombstoned)return i("Tag is already deleted");let s=[{id:G(),...n.value,action:"tombstone.tag",payload:{id:e.tagId}}],d=O(s,t.value.stateBranchRoot);return a(d)?i(d.message):c("Deleted tag",{id:o.id,name:o.name})},Hp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return i("Tag not found");if(!o.tombstoned)return i("Tag is not deleted");if(x.findTagByName(o.name))return i(`Cannot restore: another tag is already named "${o.name}"`);let s=[{id:G(),...n.value,action:"restore.tag",payload:{id:e.tagId,name:o.name}}],d=O(s,t.value.stateBranchRoot);return a(d)?i(d.message):c("Restored tag",{id:o.id,name:o.name})},Wp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Untag target must be an issue");if(o.readonly)return i("Cannot untag readonly issue");if(!r.value.tags[e.tagId])return i("Tag not found");let s={id:G(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},d=O([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue tag",{id:e.issueId,ref:K(e.issueId),tagId:e.tagId})},Gp=async(e,t)=>{let n=Ti(e);if(a(n))return;let r;for(let o of n.value)o.userId===t&&(r=o.userName??r);return r===void 0?void 0:{id:t,name:r}},qp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Assign target must be an issue");if(o.readonly)return i("Cannot assign readonly issue");let s=e.self?n.value.userId:e.assigneeId;if(s){let T=r.value.contributors[s],M=T?void 0:await Gp(t.value.stateBranchRoot,s);if(!T&&!M)return i("Unknown assignee id");let U=T??M,ne=[...T?[]:[{id:G(),...n.value,action:"create.contributor",payload:{id:U.id,name:U.name}}],{id:G(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:U.id}}],be=O(ne,t.value.stateBranchRoot);return a(be)?i(be.message):c("Added issue assignee",{id:e.issueId,ref:K(e.issueId),assignee:{id:U.id,name:U.name}})}let d=Le(e.assigneeName??"").trim();if(!d)return i("Provide assigneeId, self or assigneeName");let l=ft("Assignee name",d,80);if(l)return i(l);let m=[...Ep(Ob(),r.value.contributors).entries()].filter(([,T])=>T===d);if(m.length>1)return i(`"${d}" matches ${m.length} contributors (${m.map(([T])=>T).join(", ")}). Assign by assigneeId to choose.`);let p=m[0];if(!p&&!e.createUnlinked)return i(`No contributor named "${d}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[f=G(),I=d]=p??[],A=[...!!r.value.contributors[f]?[]:[{id:G(),...n.value,action:"create.contributor",payload:{id:f,name:I}}],{id:G(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:f}}],w=O(A,t.value.stateBranchRoot);return a(w)?i(w.message):c("Added issue assignee",{id:e.issueId,ref:K(e.issueId),assignee:{id:f,name:I}})},Vp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;if(!r.value.contributors[e.contributorId])return i("Contributor not found");if(await Gp(t.value.stateBranchRoot,e.contributorId))return i("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let d=[{id:G(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],l=O(d,t.value.stateBranchRoot);return a(l)?i(l.message):c("Tombstoned contributor",{id:e.contributorId,name:So})},Bb=async(e,t)=>{let n=Kn(e);if(a(n))return;let r;for(let o of n.value){if(o.action!=="create.contributor")continue;let s=o.payload;s.id===t&&s.name&&(r=s.name)}return r},zp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=r.value.contributors[e.contributorId];if(!o)return i("Contributor not found");if(!o.tombstoned)return i("Contributor is not tombstoned");let s=await Bb(t.value.stateBranchRoot,e.contributorId);if(!s)return i("Cannot restore this contributor \u2014 no original name found in the event log");let d=[{id:G(),...n.value,action:"restore.contributor",payload:{id:e.contributorId,name:s}}],l=O(d,t.value.stateBranchRoot);return a(l)?i(l.message):c("Restored contributor",{id:e.contributorId,name:s})},Kp=async(e={})=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=Kn(t.value.stateBranchRoot);if(a(o))return i(o.message);let s=e.boardId?xp(o.value,e.boardId):o.value,d=new Map,l=new Set,u=new Set,m=Ti(t.value.stateBranchRoot);if(a(m))return i(m.message);for(let N of m.value)N.userId&&u.add(N.userId);for(let N of s)N.userId&&(d.set(N.userId,N.userName??""),l.add(N.userId));let p=r.value.contributors,I=[...Ep(d,p).entries()].map(([N,A])=>({id:N,name:A,color:Oe(A),isSelf:N===n.value.userId,isExternal:!l.has(N),isRemoved:p[N]?.tombstoned===!0,hasAuthoredAnywhere:u.has(N)}));return c("Listed board contributors",I)},Yp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Unassign target must be an issue");if(o.readonly)return i("Cannot unassign readonly issue");if(!r.value.contributors[e.assigneeId])return i("Assignee not found");let s={id:G(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},d=O([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue assignee",{id:e.issueId,ref:K(e.issueId),assigneeId:e.assigneeId})},Xp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Comment target must be an issue");if(o.readonly)return i("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return i("Comment cannot be empty");if(s.length>4e3)return i(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let d=G(),l={id:G(),...n.value,action:"add.issue.comment",payload:{id:d,issue:e.issueId,md:s,author:n.value.userId}},u=O([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Added issue comment",{id:d,issueId:e.issueId,body:s})},Jp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();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 i("Unable to resolve comment");if(o.payload.author!==n.value.userId)return i("You can only delete your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return i("Issue not found");if(!P(s))return i("Comment target must be an issue");if(s.readonly)return i("Cannot delete comment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return c("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let l={id:G(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=O([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},Qp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();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 i("Unable to resolve comment");if(o.payload.author!==n.value.userId)return i("You can only edit your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return i("Issue not found");if(!P(s))return i("Comment target must be an issue");if(s.readonly)return i("Cannot edit comment on readonly issue");if(r.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return i("Comment was deleted");let l=e.body.trim();if(!l)return i("Comment cannot be empty");if(l.length>4e3)return i(`Comment cannot exceed ${4e3} characters (got ${l.length})`);let u={id:G(),...n.value,action:"edit.issue.comment",payload:{id:e.commentId,issue:o.payload.issue,md:l}},m=O([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Edited issue comment",{id:e.commentId,issueId:o.payload.issue,body:l})},Zp=async e=>{let t=await te(e.repoRoot,{pull:!1});if(a(t))return t;let n=le();if(a(n))return n;let r=oe();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Attachment target must be an issue");if(o.readonly)return i("Cannot attach to readonly issue");let s=Db(e);if(a(s))return s;let d=gl(t.value.stateBranchRoot,s.value.data,Fb());if(a(d))return d;let l=Le(s.value.name).trim()||"image",u=G(),m={id:G(),...n.value,action:"add.issue.attachment",payload:{id:u,issue:e.issueId,author:n.value.userId,hash:d.value.hash,ext:d.value.ext,name:l,bytes:d.value.bytes}},p=O([m],t.value.stateBranchRoot);if(a(p))return i(p.message);let f=Qr(d.value.hash,d.value.ext);return c("Added issue attachment",{id:u,issueId:e.issueId,fileName:f,bytes:d.value.bytes,markdown:Qi(l,f)})}});var rg={};Eo(rg,{createMcpServer:()=>ng,resultJson:()=>tg,startMcpServer:()=>jb});import{McpServer as Ub}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as $b}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as b}from"zod";var tg,J,ng,jb,og=y(()=>{"use strict";C();ro();eg();zs();tg=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),J=e=>t=>yp(async()=>tg(await e(t))),ng=()=>{let e=new Ub({name:"epiq",version:"0.2.30"});return e.registerTool("epiq_state_get",{description:"Get the full current Epiq state, including nodes and event log",inputSchema:b.object({repoRoot:b.string().optional()})},J(Bp)),e.registerTool("epiq_issue_list",{description:"List Epiq issues. Pass boardId to scope results to a single board and reduce response size.",inputSchema:b.object({repoRoot:b.string().optional(),includeClosed:b.boolean().optional(),boardId:b.string().optional()})},J(Ap)),e.registerTool("epiq_issue_get",{description:"Get one Epiq issue by its full id or its 7-character ref. Use this rather than listing the whole board when you already know which issue you want.",inputSchema:b.object({idOrRef:b.string().min(1),repoRoot:b.string().optional()})},J(Cp)),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:b.object({repoRoot:b.string().optional()})},J(Np)),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:b.object({repoRoot:b.string().optional(),boardId:b.string().optional()})},J(Sp)),e.registerTool("epiq_swimlane_create",{description:"Create an Epiq swimlane on a board",inputSchema:b.object({repoRoot:b.string().optional(),boardId:b.string().min(1),title:b.string().min(1).max(300)})},J(Lp)),e.registerTool("epiq_swimlane_title_edit",{description:"Edit an Epiq swimlane title",inputSchema:b.object({repoRoot:b.string().optional(),swimlaneId:b.string().min(1),title:b.string().min(1).max(300)})},J(Pp)),e.registerTool("epiq_swimlane_move",{description:"Move/reorder an Epiq swimlane, optionally to another board",inputSchema:b.object({repoRoot:b.string().optional(),swimlaneId:b.string().min(1),boardId:b.string().min(1),position:b.discriminatedUnion("at",[b.object({at:b.literal("start")}),b.object({at:b.literal("end")}),b.object({at:b.literal("before"),sibling:b.string().min(1)}),b.object({at:b.literal("after"),sibling:b.string().min(1)})]).optional()})},J(Dp)),e.registerTool("epiq_swimlane_delete",{description:"Delete (archive) an Epiq swimlane. This also archives every issue contained in it.",inputSchema:b.object({repoRoot:b.string().optional(),swimlaneId:b.string().min(1)})},J(Fp)),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue. Optionally set description, tags, and assignees atomically in the same call instead of separate follow-up edits.",inputSchema:b.object({title:b.string().min(1).max(300),parentId:b.string().min(1),repoRoot:b.string().optional(),description:b.string().max(2e4).optional(),tagNames:b.array(b.string().max(60)).max(20).optional(),assigneeNames:b.array(b.string().max(80)).max(20).optional()})},J(Tp)),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),description:b.string().max(2e4),repoRoot:b.string().optional()})},J(_p)),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),title:b.string().min(1).max(300),repoRoot:b.string().optional()})},J(Up)),e.registerTool("epiq_issue_tag_add",{description:"Add a tag to an Epiq issue, creating the tag if it does not exist",inputSchema:b.object({issueId:b.string().min(1),tagName:b.string().min(1).max(60),repoRoot:b.string().optional()})},J($p)),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),tagId:b.string().min(1),repoRoot:b.string().optional()})},J(Wp)),e.registerTool("epiq_contributor_list",{description:"List people who can be assigned: everyone who has authored an event (optionally scoped to one board) unioned with the contributor registry. Use these ids with epiq_issue_assignee_add rather than assigning by name.",inputSchema:b.object({boardId:b.string().min(1).optional(),repoRoot:b.string().optional()})},J(Kp)),e.registerTool("epiq_contributor_remove",{description:"Remove an external contributor from the assignee suggestion lists. Their id and every reference to it survive, so existing assignments stay intact and the event log is untouched. Refused for anyone who has authored events, since their name is in the log regardless.",inputSchema:b.object({contributorId:b.string().min(1),repoRoot:b.string().optional()})},J(Vp)),e.registerTool("epiq_tag_remove",{description:"Delete a tag from the whole workspace. It disappears from every ticket, picker and filter, but its id and history stay in the event log, and the name is free for a new tag.",inputSchema:b.object({tagId:b.string().min(1),repoRoot:b.string().optional()})},J(jp)),e.registerTool("epiq_tag_restore",{description:"Put back a tag deleted with epiq_tag_remove, on every ticket that still carried it.",inputSchema:b.object({tagId:b.string().min(1),repoRoot:b.string().optional()})},J(Hp)),e.registerTool("epiq_contributor_restore",{description:"Put a contributor removed with epiq_contributor_remove back into the suggestion lists, under the name they were created with.",inputSchema:b.object({contributorId:b.string().min(1),repoRoot:b.string().optional()})},J(zp)),e.registerTool("epiq_issue_assignee_add",{description:"Assign a contributor to an Epiq issue. Pass self:true to assign yourself. Prefer assigneeId otherwise, which assigns a known contributor (from the registry or the event log) and fails if the id is unknown. assigneeName matches an existing contributor by name; to create somebody new from a name you must also pass createUnlinked, which adds them as an external (non-contributor) assignee.",inputSchema:b.object({issueId:b.string().min(1),assigneeId:b.string().min(1).optional(),self:b.boolean().optional(),assigneeName:b.string().min(1).max(80).optional(),createUnlinked:b.boolean().optional(),repoRoot:b.string().optional()})},J(qp)),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),assigneeId:b.string().min(1),repoRoot:b.string().optional()})},J(Yp)),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),body:b.string().min(1).max(4e3),repoRoot:b.string().optional()})},J(Xp)),e.registerTool("epiq_issue_attachment_add",{description:"Attach an image file to an Epiq issue. Returns `markdown` \u2014 paste it into a comment or description body to render the image inline.",inputSchema:b.object({issueId:b.string().min(1),filePath:b.string().min(1),name:b.string().min(1).max(200).optional(),repoRoot:b.string().optional()})},J(Zp)),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:b.object({commentId:b.string().min(1),repoRoot:b.string().optional()})},J(Jp)),e.registerTool("epiq_issue_comment_edit",{description:"Replace the body of one of your own comments on an Epiq issue",inputSchema:b.object({commentId:b.string().min(1),body:b.string().min(1).max(4e3),repoRoot:b.string().optional()})},J(Qp)),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:b.object({issueId:b.string().min(1),repoRoot:b.string().optional()})},J(Mp)),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),repoRoot:b.string().optional()})},J(wp)),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:b.object({issueId:b.string().min(1),parentId:b.string().min(1),position:b.discriminatedUnion("at",[b.object({at:b.literal("start")}),b.object({at:b.literal("end")}),b.object({at:b.literal("before"),sibling:b.string().min(1)}),b.object({at:b.literal("after"),sibling:b.string().min(1)})]).optional(),repoRoot:b.string().optional()})},J(kp)),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote (pull remote changes and push local ones). Other Epiq MCP tools only read and write local state and never sync automatically \u2014 call this on demand when you need to see or publish the latest remote changes.",inputSchema:b.object({repoRoot:b.string().optional()})},J(Op)),e},jb=async()=>{let e=ng(),t=new $b;await e.connect(t)}});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;var{applyActorNameArgument:Hb}=await Promise.resolve().then(()=>(hr(),nd)),{isFail:Wb}=await Promise.resolve().then(()=>(C(),Za)),Js=process.argv.slice(2);Js.length>1&&(console.error(`Expected at most one name argument, got ${Js.length}`),process.exit(1));if(Js[0]!==void 0){let e=Hb(Js[0],"The name argument");Wb(e)&&(console.error(e.message),process.exit(1))}var{setVirtualNodesEnabled:Gb}=await Promise.resolve().then(()=>(Ii(),fp));Gb(!1);var{startMcpServer:qb}=await Promise.resolve().then(()=>(og(),rg));await qb();
|