epiq 1.7.0 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/gui/main.js +2955 -1125
- package/dist/index.js +75 -70
- package/dist/mcp.js +58 -54
- package/package.json +2 -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(
|
|
2
|
+
var $g=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var To=(e,t)=>{for(var n in t)$g(e,n,{get:t[n],enumerable:!0})};var hd={};To(hd,{failed:()=>i,isFail:()=>a,isSuccess:()=>ht,resultStatuses:()=>Dt,succeeded:()=>c});var Dt,i,c,a,ht,C=y(()=>{"use strict";Dt={Success:"success",Fail:"fail"},i=e=>({status:Dt.Fail,message:e,value:null}),c=(e,t)=>({status:Dt.Success,message:e,value:t}),a=e=>e.status==="fail",ht=e=>e.status==="success"});var bd={};To(bd,{ACTOR_ID_ENV:()=>Rr,ACTOR_NAME_ENV:()=>vt,applyActorNameArgument:()=>ai,deriveActorId:()=>yd,isValidUserId:()=>wo,isValidUserName:()=>Sr,resolveEnvActor:()=>ii});import jg from"node:crypto";var vt,Rr,vd,Hg,si,wo,Sr,Jn,yd,ii,ai,Qn=y(()=>{"use strict";C();vt="EPIQ_USER_NAME",Rr="EPIQ_USER_ID",vd="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Hg=26,si=80,wo=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),Sr=e=>e.trim().length>0&&e.length<=si,Jn=e=>e.trim().toLowerCase(),yd=e=>{let t=jg.createHash("sha256").update(`epiq:actor:${Jn(e)}`).digest(),n="";for(let r=0;r<Hg;r++)n+=vd[(t[r]??0)%vd.length];return n},ii=(e,t=process.env)=>{let n=(t[vt]??"").trim(),r=(t[Rr]??"").trim();return n?Sr(n)?!r&&e.userId&&e.userName&&Jn(e.userName)===Jn(n)?c("Actor override names the configured user",{userId:e.userId,userName:e.userName}):r&&!wo(r)?i(`${Rr} must be 26 characters of Crockford base32`):r&&e.userId&&r===e.userId?i(`${Rr} 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||yd(n),userName:r?n:Jn(n)}):i(`${vt} must be 1-${si} characters of text`):r?i(`${Rr} is set without ${vt}`):c("No actor override",null)},ai=(e,t,n=process.env)=>{let r=e.trim();if(!Sr(r))return i(`${t} must be 1-${si} characters of text`);let o=(n[vt]??"").trim();return o&&Jn(o)!==Jn(r)?i(`${t} names ${r}, but ${vt} names ${o}`):(n[vt]=r,c("Applied actor name argument",r))}});import{decodeTime as xd}from"ulid";var Mo,di,yt,Nr,Id,Cr,dt=y(()=>{"use strict";C();Mo=1440*60*1e3,di=(e,t=Date.now())=>e>t+Mo?t:e,yt=e=>di(xd(e)),Nr=e=>{let t=Date.now()+Mo,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})},Id=e=>{try{return c("Decoded date",new Date(yt(e)))}catch(t){return i("Decoding failed + "+t.message)}},Cr=e=>{if(!e?.id)return null;try{return xd(e.id)}catch{return null}}});var ko,ze,Ed,bt=y(()=>{"use strict";C();ko="removed",ze=(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")},Ed=["png","jpg","gif","webp"]});function ci(e){return e.context===_.WORKSPACE}function P(e){return e.context===_.TICKET}function Rd(e){return e.context===_.TEXT}function Ye(e){return e.context===_.FIELD}function Ar(e){return e.context===_.FIELD_LIST}var _,bn,Lo,Tr,ge=y(()=>{"use strict";_={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};bn=e=>e.context===_.SWIMLANE,Lo=e=>e.context===_.BOARD,Tr=e=>e.context===_.COMMENT});var h,le=y(()=>{"use strict";h={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var Sd=y(()=>{"use strict";xn()});import Nd from"string-width";function Po(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var In,Wg,li,Gg,ui,Me,Jt=y(()=>{"use strict";In=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Wg=/\u001B\[[0-9;]*m/,li="\x1B[0m",Gg=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),ui=(e,t)=>{if(t<=0)return"";if(Nd(e)<=t)return e;if(t<=3)return"...".slice(0,t);let r=t-3,o="",s=0,d=!1;for(let l of e.split(/(\u001B\[[0-9;]*m)/))if(l!==""){if(Wg.test(l)){o+=l,d=l!==li&&l!=="\x1B[m";continue}for(let u of Gg(l)){let m=Nd(u);if(s+m>r)return`${o}...${d?li:""}`;o+=u,s+=m}}return`${o}...${d?li:""}`},Me=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var Cd,Ad,Td=y(()=>{"use strict";Cd=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},Ad=(e,t)=>t?e.get(t)??[]:[]});var wd,qg,Md,kd=y(()=>{"use strict";Jt();Td();wd=new WeakMap,qg=e=>{let t=wd.get(e);return t||(t=Cd(e),wd.set(e,t)),t},Md=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Ad(qg(e),r).filter(s=>Po(r,s)>=n)}});var Vg,Ld,Kg,Pd=y(()=>{"use strict";Jt();kd();Vg={hint:"",hints:[],overlap:0,remainder:""},Ld=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Vg;let o=Md({wordList:r,inputToMatch:e,overlapThreshold:1});return Kg(t,o)},Kg=(e,t)=>{let n=t[0]??"",r=Po(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),d=r<(o??"").length,l=!!s,p=(l&&d?o:n)+(l&&d?":":" "),g=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:g}}});import{useSyncExternalStore as oI}from"react";var Do,zg,Yg,ve,et,Be=y(()=>{"use strict";Do={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},zg=new Set,Yg=()=>{for(let e of zg)e()},ve=()=>Do,et=e=>(Do={...Do,...e},Yg(),Do)});function Dd(e){return!e||!Jg.test(e)?i(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function tt(e,t=wr){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 tt(xt/2n,wr);let n=e?Dd(e):c("Resolved lower bound",0n);if(a(n))return n;let r=t?Dd(t):c("Resolved upper bound",xt);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"):tt(d,wr)}function Fd(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=xt*BigInt(r+1)/(t+1n),s=tt(o,wr);if(a(s))return s;n.push(s.value)}return c("Resolved evenly spaced ranks",n)}var wr,Xg,xt,Jg,Zn=y(()=>{"use strict";C();wr=24n,Xg=wr*4n,xt=(1n<<Xg)-1n,Jg=/^[0-9a-f]+$/});import{ulid as Qg}from"ulid";var mi,Od=y(()=>{"use strict";C();It();Zn();mi=(e,t)=>{let n=ue(e),r=Fd(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:Qg(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})}});import Mr from"node:fs";import{ulid as Zg}from"ulid";import{z as Fo}from"zod";var ef,tf,Oo,Ft,kr,Bd,Ot=y(()=>{"use strict";C();re();ef="__epiq_state__",tf=Fo.object({projectId:Fo.string().min(1),stateBranch:Fo.string().min(1),createdAt:Fo.iso.datetime()}),Oo=()=>({projectId:Zg(),stateBranch:ef,createdAt:new Date().toISOString()}),Ft=e=>{let t=Bo(e);if(!Mr.existsSync(t))return i("Missing .epiq/project.json");try{let n=Mr.readFileSync(t,"utf8"),r=JSON.parse(n),o=tf.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")}},kr=e=>{let t=Ft(e);return a(t)?i(t.message):c("Read projectId",t.value.projectId)},Bd=({repoRoot:e,fileContents:t})=>{let n=En(e),r=Bo(e);try{if(Mr.mkdirSync(n,{recursive:!0}),Mr.existsSync(r)){let o=Ft(e);return a(o)?i(o.message):c("Project already initialized",null)}return Mr.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 nf from"node:os";import rf from"node:path";var ct,Rn,_o=y(()=>{"use strict";ct=".epiq-global",Rn=()=>process.env.EPIQ_GLOBAL_DIR??rf.join(nf.homedir(),ct)});var pi,_d=y(()=>{"use strict";C();pi=(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 he,Uo=y(()=>{"use strict";lt();he={stage:({cwd:e,pathspec:t,ignoreRemoval:n=!1})=>G({args:["add",...n?["--ignore-removal"]:[],...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1,pathspec:r})=>G({args:["commit","--no-verify",...n?["--allow-empty"]:[],"-m",t,...r?.length?["--",...r]:[]],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>G({args:["fetch",t,`+refs/heads/${n}:refs/remotes/${t}/${n}`],cwd:e}),rebaseOnto:({cwd:e,ref:t})=>G({args:["-c","rebase.autoStash=true","rebase",t],cwd:e}),checkout:({cwd:e,branch:t})=>G({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 G({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>G({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>G({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>G({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>G({args:["worktree","prune"],cwd:e})}});var Qt,nt,Lr=y(()=>{"use strict";Ot();C();re();Qt=e=>{let t=Xe(e);if(a(t))return i("Unable to resolve epiq project root");let n=Ft(t.value);return a(n)?i("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},nt="origin"});import{spawn as of}from"node:child_process";import Sn from"node:fs";import Nn from"node:path";var sf,af,df,cf,lf,uf,mf,$d,G,Ue,er,gi,pf,$o,fi,hi,jo,Pr,jd,vi,Ho,Hd,Wd,gf,Ud,yi,ff,bi,Gd,qd,Vd,Kd,lt=y(()=>{"use strict";C();Uo();Lr();sf=1e4,af=12e4,df=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),cf=e=>{let t=e.find((n,r)=>!n.startsWith("-")&&e[r-1]!=="-c");return t&&df.has(t)?af:sf},lf=()=>{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(!Sn.statSync(r).isFile())continue;return Sn.accessSync(r,Sn.constants.X_OK),r}catch{continue}}return"git"},uf=lf(),mf={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},$d=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Sn.existsSync(t)){let g=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:g,exitCode:1});return}r(i(g));return}let o=of(uf,e,{cwd:t,stdio:["ignore","pipe","pipe"],env:mf}),s=!1,d="",l="",u=g=>{s||(s=!0,clearTimeout(p),r(g))},m=cf(e),p=setTimeout(()=>{o.kill("SIGTERM");let g=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${m}ms`].join(`
|
|
4
|
+
`);u(n?{stdout:d,stderr:g,exitCode:124}:i(g))},m);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",g=>{d+=g}),o.stderr.on("data",g=>{l+=g}),o.on("error",g=>{if(n){u({stdout:d,stderr:g.message,exitCode:1});return}u(i([`git ${e.join(" ")}`,`cwd=${t}`,g.message].join(`
|
|
5
|
+
`)))}),o.on("close",g=>{let I=g??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}))})}),G=({args:e,cwd:t})=>$d({args:e,cwd:t,allowFail:!1}),Ue=({args:e,cwd:t})=>$d({args:e,cwd:t,allowFail:!0}),er=async({cwd:e,message:t,pathspec:n})=>{let r=await he.commit({cwd:e,message:t,pathspec:n});if(a(r))return i(`Failed to create commit
|
|
7
|
+
${r.message}`);let o=await G({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())},gi=async e=>{let t=await G({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))},pf=async e=>{let t=await gi(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(Sn.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(Sn.existsSync(Nn.join(n,s)))return c("Checked for in-progress Git operation",d);return c("Checked for in-progress Git operation",null)},$o=async e=>{let t=await pf(e);return a(t)?i(t.message):c("Checked for in-progress Git operation",t.value!==null)},fi=async({repoRoot:e})=>{let n=(await Ue({args:["remote","get-url",nt],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},hi=async({repoRoot:e,branch:t})=>{let n=await Ue({args:["ls-remote","--heads",nt,t],cwd:e});return n.exitCode!==0?i(n.stderr.trim()||`Unable to inspect remote branch ${nt}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},jo=async({repoRoot:e,branch:t})=>{let n=await Ue({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}`)},Pr=e=>{try{return Sn.realpathSync.native(e)}catch{return Nn.resolve(e)}},jd=async({repoRoot:e,worktreeRoot:t})=>{let n=await G({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let r=Pr(t),o=n.value.stdout.split(`
|
|
9
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Pr).includes(r);return c("Checked worktree registration",o)},vi=async e=>{let t=await Ue({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Ho=async e=>{let t=await G({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved current branch",t.value.stdout.trim())},Hd=async e=>{let t=await G({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},Wd=e=>e.includes("fetch first")||e.includes("non-fast-forward"),gf=async e=>(await Ue({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1),Ud=async e=>{let t=await Ue({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},yi=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),ff=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),bi=async({cwd:e,branch:t})=>{let n=await gf(e);if(a(n))return i(n.message);let r=await Ud(e),o=await he.fetch({cwd:e,remote:nt,branch:t});if(a(o))return ff(o.message)?c("Remote branch missing, skipped pull",!1):i(`Failed to fetch ${t}
|
|
10
10
|
${o.message}`);let s=await he.rebaseOnto({cwd:e,ref:`${nt}/${t}`});if(a(s))return i(`Failed during rebase
|
|
11
|
-
${s.message}`);let d=await
|
|
12
|
-
`+r.message);let o=
|
|
13
|
-
`+o.message):c("Ensured epiq storage",n)},
|
|
14
|
-
`,
|
|
11
|
+
${s.message}`);let d=await Ud(e),l=r!==null&&d!==null&&r!==d;return c(l?"Pulled with rebase":"Already up to date",l)},Gd=async e=>{let t=await Ue({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)},qd=async e=>{let t=await Ue({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)},Vd=async(e,t)=>{let n=await Ue({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")},Kd=async e=>{let t=await Ho(e);return a(t)?i(t.message):c("Checked detached HEAD state",t.value==="HEAD")}});import Zt from"node:fs";import rt from"node:path";var Yd,Xd,Jd,Qd,Wo,Se,hf,zd,Dr,Go,Zd,xi,Ii,ec,tc,ut,ZI,mt=y(()=>{"use strict";Ot();C();_o();re();_d();Et();lt();Yd="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Xd=e=>rt.join($e,en,e),Jd=()=>rt.join($e,Ei),Qd=Rn,Wo=()=>rt.join(Qd(),"worktrees"),Se=({repoRoot:e})=>{let t=kr(e);return a(t)?i(t.message):c("Resolved state branch root",rt.join(Wo(),t.value))},hf=e=>rt.join(e,$e),zd=e=>rt.join(hf(e),en),Dr=e=>{try{return Zt.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return i(t instanceof Error?t.message:String(t))}},Go=()=>{let e=Qd(),t=Wo(),n=!Zt.existsSync(e)||!Zt.existsSync(t),r=Dr(e);if(a(r))return i(`Ensure epiq home failed.
|
|
12
|
+
`+r.message);let o=Dr(t);return a(o)?i(`Ensure worktrees dir failed.
|
|
13
|
+
`+o.message):c("Ensured epiq storage",n)},Zd=e=>{Zt.existsSync(e)&&(X.debug("[sync] remove path",e),Zt.rmSync(e,{recursive:!0,force:!0}))},xi=`*.jsonl merge=union
|
|
14
|
+
`,Ii=()=>rt.join($e,en,".gitattributes"),ec=(e,t)=>{for(let r of[zd(e),zd(t)]){let o=Dr(r);if(a(o))return i(o.message)}let n=rt.join(t,Ii());try{Zt.readFileSync(n,"utf8")!==xi&&Zt.writeFileSync(n,xi)}catch{Zt.writeFileSync(n,xi)}return c("Ensured state branch",void 0)},tc=async e=>{let t=await G({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!==$e);if(r.length===0)return c("State branch is storage-only",!1);let o=await G({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(a(o))return i(`Failed to clean storage branch
|
|
17
|
+
${o.message}`);let s=await er({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:r});return a(s)?i(s.message):c("Cleaned storage branch",!0)},ut=pi(async(e=process.cwd())=>{let t=await G({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=>rt.resolve(e)),ZI=pi(async e=>{let t=await G({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return i(t.message);let n=t.value.stdout.trim(),r=rt.isAbsolute(n)?n:rt.join(e,n);return c("Resolved git dir",r)},e=>rt.resolve(e))});import Fr from"node:fs";import Rt from"node:path";var iE,$e,en,Ei,vf,En,Bo,Cn,qo,nc,yf,Or,Vo,bf,Xe,rc,St,re=y(()=>{"use strict";C();mt();_o();iE=process.env.IS_LOCAL==="true",$e=".epiq",en="events",Ei="media",vf="project.json",En=e=>Rt.join(e,$e),Bo=e=>Rt.join(En(e),vf),Cn=e=>Rt.join(En(e),en),qo=e=>Rt.join(En(e),Ei),nc=e=>Rt.join(e,$e),yf=e=>{let t=Rt.join(e,$e);return Fr.existsSync(t)&&Fr.statSync(t).isDirectory()},Or=e=>{let t=Bo(e);return Fr.existsSync(t)&&Fr.statSync(t).isFile()},Vo=e=>{let t=Rt.resolve(e);for(;;){if(yf(t))return c("Resolved closest .epiq root",t);let n=Rt.dirname(t);if(n===t)return i("No .epiq directory found in any parent");t=n}},bf="No .epiq/project.json found in any parent",Xe=e=>{let t=Rt.resolve(e);for(;;){if(Or(t))return c("Resolved closest epiq project root",t);let n=Rt.dirname(t);if(n===t)return i(bf);t=n}},rc=e=>{let t=Cn(e);try{return Fr.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")}},St=async()=>{let e=await ut(process.cwd());if(a(e))return e;let t=Se({repoRoot:e.value});return a(t)?t:c("Resolved persist root",t.value)}});import Br from"fs";import Ci from"path";import xf from"util";function Ef(){let e=ic();if(!e||!Br.existsSync(e))return;let n=Br.readFileSync(e,"utf8").split(`
|
|
18
|
+
`);if(n[n.length-1]===""&&n.pop(),n.length<=oc)return;let r=n.slice(-oc).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
|
|
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
|
+
`;Br.writeFileSync(e,r,"utf8")}function Si(e,t,n=!1){let r=ic();if(!r)return;let o=xf.format(...t),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
21
|
+
`;Br.mkdirSync(Ci.dirname(r),{recursive:!0}),Br.appendFileSync(r,l,"utf8"),Ri++,Ri>=If&&(Ri=0,Ef())}var oc,If,Ri,sc,ic,Ni,X,Et=y(()=>{"use strict";C();re();oc=1e3,If=50,Ri=0,sc=()=>process.env.EPIQ_MCP==="true",ic=()=>{let e=process.cwd(),t=Vo(e);return a(t)?sc()?Ci.join(process.cwd(),".epiq-mcp.log"):void 0:Ci.join(t.value,$e,"log","epiq.log")};Ni=()=>sc()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",X={info(...e){let t=Ni();(t==="info"||t==="debug")&&Si("[Info]",e,!1)},debug(...e){Ni()==="debug"&&Si("[Debug]",e,!0)},error(...e){let t=Ni();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;Si("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=X});var ie,tr=y(()=>{"use strict";ie={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var z,_r,tn=y(()=>{"use strict";z=e=>e.slice(-7).toUpperCase(),_r=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?z(e).includes(n):!0}});var Ne,An=y(()=>{"use strict";ge();tn();Ne={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:_.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:z(e)},context:_.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:_.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:_.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:_.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:z(e)},context:_.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:_.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:_.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:d})}});var Rf,ye,Ko,nr=y(()=>{"use strict";Rf=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ye,Ko]=Rf});function nn(e,t=!1){let n=Mf[e.action];if(!n)return i(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);if(!ot()&&e.action!=="init.workspace")return L(`${e.action} arrived before the workspace was initialized`,e);if(e.action==="init.workspace"&&je){if(je.genesisApplied)return L("the workspace is already initialized",e);je.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=wf(e,t);return o||r}var Ai,L,$r,Tn,wn,ac,dc,Sf,Nf,Ti,Cf,Af,je,Tf,wf,Ur,Mf,Bt,_t=y(()=>{"use strict";Et();ge();C();tr();me();An();k();wi();nr();Ai=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),L=(e,t)=>({...Ai(e,t),convergence:!0}),$r=e=>a(e)&&e.convergence===!0,Tn=e=>{let t=e.filter(a);return{fatal:t.filter(n=>!$r(n)),skipped:t.filter($r)}},wn=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("; ")}`)},ac=e=>{let t=x.getNode(e);if(!t||!P(t)||t.isDeleted)return null;let n=zo(t);return a(n)?n:null},dc=e=>{if(!Yo())return null;for(let t of e){let n=ac(t);if(n)return n;let r=f().nodes[t]?.parentNodeId;if(!r)continue;let o=ac(r);if(o)return o}return null},Sf=(e,t)=>{let n=x.getNode(e);n&&x.updateNode({...n,log:[...n.log??[],t]})},Nf=e=>{let t=[e],n=f().nodes[e]?.parentNodeId;return n&&t.push(n),t},Ti=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 Nf(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[]}},Cf=e=>{Ie(t=>({...t,eventLog:[...t.eventLog,e]}))},Af=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?Ai("Invalid user ID format",e):c("Valid user",null)},je=null,Tf=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]})),dc([...e.virtualNodeIds])},wf=(e,t)=>{let n=Af(e);if(a(n))return n;let r=[...new Set(Ti(e))];if(je){for(let s of r){if(!t){let d=je.nodeLog.get(s);d?d.push(e):je.nodeLog.set(s,[e])}if(Yo()){je.virtualNodeIds.add(s);let d=f().nodes[s]?.parentNodeId;d&&je.virtualNodeIds.add(d)}}return t||je.appLog.push(e),null}t||(r.forEach(s=>Sf(s,e)),Cf(e));let o=dc(r);return o||null},Ur=(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,Mf={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Ne.workspace(t,n,r),s=jr(o);if(a(s))return Ai(s.message,e);let d=x.createNode(o);return a(d)?L(d.message??"Failed to initialize workspace",e):ci(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=Ur(t,void 0,e);if(o)return o;let s=x.createNode(Ne.workspace(t,n,r));return a(s)?L(s.message??"Failed to add workspace",e):ci(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=Ur(t,r,e);if(s)return s;let d=x.createNode(Ne.board(t,n,r,o));return a(d)?L(d.message??"Unable to create board",e):Lo(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=Ur(t,r,e);if(s)return s;let d=x.createNode(Ne.swimlane(t,n,r,o));return a(d)?L(d.message??"Unable to create swimlane",e):bn(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=Ur(t,r,e);if(s)return s;let d=x.createNode(Ne.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=Ur(t,r,e);if(d)return d;let l=x.createNode(Ne.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(ie.DESCRIPTION)?"vertical":"horizontal"}));return a(l)?L(l.message??`Unable to create field: ${n}`,e):Ye(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(ye);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(ye);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}})}};Bt=e=>{let t=cc(()=>{let n=je===null;n&&(je={appLog:[],nodeLog:new Map,virtualNodeIds:new Set,genesisApplied:!1});try{let r=e.map(o=>nn(o));if(n&&je){let o=Tf(je);if(o)return e.map(()=>o)}return r}finally{n&&(je=null)}});return a(t)?e.map(()=>i(t.message)):t.value}});var Mi,lc=y(()=>{"use strict";Mi=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown"});import{existsSync as kf,readdirSync as Lf,statSync as Pf}from"node:fs";import Df from"node:path";var Mn,uc,ki,rn,mc,pc,gc,Hr=y(()=>{"use strict";re();Mn=e=>{let t=Cn(e);return kf(t)?Lf(t).filter(n=>n.endsWith(".jsonl")).sort().map(n=>{let{size:r,mtimeMs:o}=Pf(Df.join(t,n));return`${n}:${r}:${o}`}).join("|"):"none"},uc=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),ki=(e,t,n)=>{let r=uc(t),o=Mn(e),s=uc(o);for(let[d,l]of s)if(d!==n&&r.get(d)!==l)return null;for(let d of r.keys())if(d!==n&&!s.has(d))return null;return o},rn=null,mc=e=>rn&&rn.root===e?rn.signature:null,pc=(e,t)=>{rn={root:e,signature:t}},gc=(e,t)=>{if(!rn||rn.root!==e)return;let n=ki(e,rn.signature,t);rn=n===null?null:{root:e,signature:n}}});var Ff,Of,fc,hc,Li=y(()=>{"use strict";Ff=["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"],Of=new Set(Ff),fc=e=>Of.has(e),hc=e=>({action:e.action,payload:e.payload})});import{z as V}from"zod";var W,pt,on,Xo,Pi,Bf,vc,yc=y(()=>{"use strict";C();W=V.string().min(1),pt=V.string(),on=V.string(),Xo=V.looseObject({id:W}),Pi=V.looseObject({id:W,name:pt,parent:W,rank:on}),Bf={"init.workspace":V.looseObject({id:W,name:pt,rank:on}),"add.workspace":V.looseObject({id:W,name:pt,rank:on}),"add.board":Pi,"add.swimlane":Pi,"add.issue":Pi,"add.field":V.looseObject({id:W,name:pt,parent:W,rank:on}),"edit.title":V.looseObject({id:W,name:pt}),"delete.node":Xo,"lock.node":Xo,"move.node":V.looseObject({id:W,parent:W,rank:on}),"edit.description":V.looseObject({id:W,md:V.string()}),"close.issue":V.looseObject({id:W,parent:W,rank:on}),"reopen.issue":V.looseObject({id:W,parent:W,rank:on}),"create.tag":V.looseObject({id:W,name:pt}),"tombstone.tag":Xo,"restore.tag":V.looseObject({id:W,name:pt}),"create.contributor":V.looseObject({id:W,name:pt}),"rename.contributor":V.looseObject({id:W,name:pt}),"tombstone.contributor":Xo,"restore.contributor":V.looseObject({id:W,name:pt}),"link.contributor.user":V.looseObject({contributor:W}),"add.issue.assignee":V.looseObject({id:W,assignee:W}),"remove.issue.assignee":V.looseObject({id:W,assignee:W}),"add.issue.tag":V.looseObject({id:W,tag:W}),"remove.issue.tag":V.looseObject({id:W,tag:W}),"add.issue.comment":V.looseObject({id:W,issue:W,md:V.string()}),"edit.issue.comment":V.looseObject({id:W,issue:W,md:V.string()}),"delete.issue.comment":V.looseObject({id:W,issue:W}),"add.issue.attachment":V.looseObject({id:W,issue:W,hash:V.string().min(1),ext:V.string().min(1),name:pt,bytes:V.number()}),"delete.issue.attachment":V.looseObject({id:W,issue:W}),"rebalance.children":V.looseObject({parent:W,ranks:V.record(V.string(),on)})},vc=(e,t)=>{let r=Bf[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 Qo from"node:fs";import Zo from"node:path";import{decodeTime as _f}from"ulid";import{z as Di}from"zod";function Wr(e,t){let n=Cn(e),r=Mn(e);if(!Qo.existsSync(n))return c("No events found",[]);let o=Qo.readdirSync(n).filter(l=>l.endsWith(".jsonl")).map(l=>Zo.join(n,l)),s=[];for(let l of o){let u=Kf(l,t);if(a(u))return i(u.message);s.push(...u.value)}let d=Yf(s);return Ut={root:e,signature:r,edge:d.at(-1)?.id?.[0]??null},c("All events loaded",d)}function $t(e){let t=[],n=Wr(e,t);if(a(n))return i(n.message);let r=Oi(n.value,t);return a(r)?i(r.message):(zf=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 kn(e){let t=$t(e);return a(t)?i(t.message):c("Loaded merged events",t.value.events)}function _i(e,t){let n=Wr(e);if(a(n))return i(n.message);let{appliedEvents:r,unappliedEvents:o}=Xf(n.value,t),s=Oi(r);if(a(s))return i(s.message);let d=Oi(o);return a(d)?i(d.message):c("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function bc(e=process.cwd()){let t=Mn(e);if(Ut&&Ut.root===e&&Ut.signature===t)return c("Loaded edge reference, unchanged",Ut.edge);let n=Wr(e);return a(n)?i(n.message):c("Loaded edge reference",n.value.at(-1)?.id?.[0]??null)}function xc(e,t,n){if(!Ut||Ut.root!==e)return;let r=ki(e,Ut.signature,t);Ut=r===null?null:{root:e,signature:r,edge:n}}function Ui(e){let t=Wr(e);if(a(t))return i(t.message);let n=Ic(t.value);return c("Loaded effective event times",new Map(t.value.map((r,o)=>[r.id[0],n[o]??null])))}var Uf,Jo,$f,jf,Hf,Wf,Gf,qf,Vf,Oi,Kf,zf,Ut,Fi,Yf,Ic,Xf,jt=y(()=>{"use strict";Et();C();re();Hr();dt();Li();gt();yc();Uf=Di.object({userId:Di.string().min(1).default("unknown"),userName:Di.string().min(1).default("unknown")}),Jo=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},$f=/^[0-9a-hjkmnp-tv-z]{26}$/i,jf=e=>$f.test(e)?e.toUpperCase():e,Hf=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=Uf.safeParse({userId:jf(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(", ")}`)},Wf=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])},Gf=(e,t)=>t in e,qf=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Vf=e=>{let{userId:t,userName:n,...r}=e,o=Wf(r);if(a(o))return i(o.message);let s=o.value,d=e.id?.[0];return d?Gf(r,s)?c("Decoded persisted event",qf({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")},Oi=(e,t)=>{let n=[],r=new Map,o=new Map;for(let s of e){if(!Rc(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:Jo(s)});continue}let d=Vf(s);if(a(d)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:d.message,targetNodeId:Jo(s)});continue}let l=d.value.action;if(!fc(l)){r.set(l,(r.get(l)??0)+1),t?.push({eventId:s.id[0],reason:"unknown-action",detail:l,targetNodeId:Jo(s)});continue}let u=vc(l,d.value.payload);if(a(u)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:u.message,targetNodeId:Jo(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)},Kf=(e,t)=>{if(!Qo.existsSync(e))return c("Event file missing",[]);let n=Hf(e);if(a(n))return i(n.message);let r=Qo.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 g=Ec(p);if(a(g)){d(l+1,g.message);continue}o.push({...g.value,userId:n.value.userId,userName:n.value.userName})}return c("Parsed persisted events file",o)};zf=[];Ut=null;Fi=(e,t)=>{let n=e.id[0].localeCompare(t.id[0]);return n!==0?n:JSON.stringify(e).localeCompare(JSON.stringify(t))},Yf=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],g=m.id[1]??null;t.set(p,m);let I=n.get(g)??[];I.push(m),n.set(g,I)}for(let m of n.values())m.sort(Fi);let r=[],o=new Set,s=m=>{let p=[m];for(;p.length>0;){let g=p.pop(),I=g.id[0];if(o.has(I))continue;r.push(g),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(g=>g!=="id"&&g!=="v"&&g!=="userId"&&g!=="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],g=m.id[1]??null;return o.has(p)?!1:g===null||!t.has(g)}).sort(Fi);for(let m of l)s(m);let u=e.filter(m=>!o.has(m.id[0])).sort(Fi);for(let m of u)s(m);return r},Ic=e=>Nr(e.map(t=>{try{return _f(t.id[0])}catch{return null}}));Xf=(e,t)=>{let n=new Set,r=[],o=[],s=Ic(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 Jf from"node:fs";import Nc from"node:path";import{decodeTime as Qf,monotonicFactory as Zf}from"ulid";import{z as Ln}from"zod";function $i(e,t){let n;if(t&&t.current!==void 0)n=t.current;else{let o=bc(e);if(a(o))return i(o.message);n=o.value}let r=n?Sc(nh(n)):Sc();return c("Minted event id",[r,n])}function es({event:e,rootDir:t,edge:n,id:r}){try{let o=rc(t);if(a(o))return o;let s=dh(t,{userId:e.userId,userName:e.userName});if(a(s))return s;let d=r?c("Minted event id",r):$i(t,n);if(a(d))return i(d.message);let[l,u]=d.value,m=ch(hc(e),[l,u]);if(a(m))return i(m.message);Jf.appendFileSync(s.value,`${JSON.stringify(m.value)}
|
|
23
|
+
`,"utf8"),n&&(n.current=l);let p=Nc.basename(s.value);return xc(t,p,l),gc(t,p),c("Event persisted",{path:s.value,entry:m.value})}catch(o){let s=o instanceof Error?o.message:"Unknown persist error";return i(`Failed to persist event: ${s}`)}}var Cc,Sc,eh,th,nh,Ac,rh,oh,Ec,sh,ih,Rc,ah,fe,Pn,dh,ch,gt=y(()=>{"use strict";Et();Qn();C();Be();re();lc();dt();jt();Hr();Li();Cc=1,Sc=Zf(),eh=0xffffffffffff,th=Mo,nh=e=>{let t=Date.now(),n;try{n=Qf(e)}catch{return t}return n>=eh?t:n>t+th?(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)},Ac=Ln.tuple([Ln.string().min(1),Ln.string().min(1).nullable()]),rh=Ln.looseObject({v:Ln.literal(Cc),id:Ac}),oh=Ln.looseObject({v:Ln.number().int().positive(),id:Ac}),Ec=e=>{let t=oh.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(", ")}`)},sh=[1],ih=new Set(sh),Rc=e=>ih.has(e),ah=e=>{let t=rh.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}=ve();return e?t?wo(t)?Sr(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")},Pn=({userId:e,userName:t})=>`${Mi(e)}.${Mi(t)}.jsonl`,dh=(e,{userId:t,userName:n})=>{let r=Pn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return i(`Invalid event log file name: ${r}`);let s=Nc.join(Cn(e),r);return c("Successfully resolved event log path",s)},ch=(e,t)=>{let n={[e.action]:e.payload,v:Cc,id:t};return ah(n)}});import{ulid as lh}from"ulid";function Tc(e,t,n){let r=$i(t,n);if(a(r))return i(r.message);let o={...e,id:r.value[0]},s=nn(o);if(s.status!==Dt.Success)return s;let d=es({event:o,rootDir:t,edge:n,id:r.value});return a(d)?d:s}function B(e,t){if(e.length===0||!e[0])return i("No events provided");if(f().readOnly)return i(f().readOnlyReason??"Cannot change the board while time travelling");let n={},r=uh(e[0],t,n);if(a(r))return r;let o=e.map(d=>Tc(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 uh,Dn=y(()=>{"use strict";C();me();k();_t();gt();uh=(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:lh(),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=Tc(o,t,n);return a(s)?i(s.message):c("Contributor name recorded",void 0)}});var Fn,ji,wc=y(()=>{"use strict";tn();Fn=e=>e.trim().toLocaleLowerCase(),ji=(e,t)=>Fn(e).includes(Fn(t))});var mh,ph,Mc,kc,gh,fh,Lc,Pc=y(()=>{"use strict";k();tn();wc();mh=e=>{let{tags:t}=f();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},ph=e=>{let{contributors:t}=f();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},Mc=null,kc=new Map,gh=()=>{let e=f().eventLog??[];if(e===Mc)return kc;let t=new Map;for(let n of e){if(!n.userId)continue;let r=n.payload;for(let o of[r.id,r.issue]){if(typeof o!="string")continue;let s=t.get(o)??new Set;s.add(n.userId),t.set(o,s)}}return Mc=e,kc=t,t},fh=e=>{let{contributors:t}=f(),n=gh().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},Lc=(e,t)=>{let n=Fn(t.value);if(!n)return!0;switch(t.target){case"title":return ji(e.title??"",n);case"description":return ji(e.props.description??"",n);case"tag":return mh(e).map(Fn).some(o=>o.includes(n));case"assignee":return ph(e).map(Fn).some(o=>o.includes(n));case"actor":return fh(e).map(Fn).some(o=>o.includes(n));case"ref":return _r(e.id,t.value);default:return!0}}});var Dc,hh,Fc,Oc,Hi=y(()=>{"use strict";ge();Pc();Dc=(e,t)=>e.rank.localeCompare(t.rank),hh=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,Fc=(e,t)=>Object.values(e).filter(n=>hh(n,t)).sort(Dc),Oc=(e,t)=>{let n={};for(let r of Object.values(e)){if(P(r)&&t.length>0&&!t.every(s=>Lc(r,s))||!r.parentNodeId||r.isDeleted)continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(Dc);return n}});var Bc,ts,ue,_c,Uc,sn,On,It=y(()=>{"use strict";Od();Dn();C();k();Hi();Zn();Bc=e=>ts(ue(e),{at:"end"}),ts=(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=_c(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=_c(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))}}},ue=e=>{let t=f();if(!$c()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return Fc(t.nodes,e)},_c=(e,t)=>e.findIndex(n=>n.id===t),Uc=(e,t,n={at:"end"})=>ts(ue(t).filter(r=>r.id!==e),n),sn=(e,t,n,r,o)=>{let s=Uc(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return c("Resolved rank",s.value.rank);let d=mi(e,r);if(a(d))return d;let l=B([d.value],o);if(a(l))return l;let u=Uc(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)},On=(e,t,n)=>{let r=Bc(e);if(a(r))return r;if(!r.value.needsRebalance)return c("Resolved rank",r.value.rank);let o=mi(e,t);if(a(o))return o;let s=B([o.value],n);if(a(s))return s;let d=Bc(e);return a(d)?d:d.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",d.value.rank)}});var U,jc,Hc,Je=y(()=>{"use strict";k();U={exit(){process.exit(0)},enterChildNode(){let e=f(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=ae(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||U.navigate({contextNode:o,selectedIndex:ae(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=f();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;U.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>jc(1),navigateToPreviousItem:()=>jc(-1),navigateToNextContainer:()=>Hc(1),navigateToPreviousContainer:()=>Hc(-1),navigate:({contextNode:e,selectedIndex:t})=>{E({contextNodeId:e.id,selectedIndex:t})}},jc=e=>{let{selectedIndex:t,contextNode:n}=f(),r=ae(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;U.navigate({selectedIndex:s,contextNode:n})},Hc=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=f();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),g=u.length?p:-1;U.navigate({contextNode:l,selectedIndex:g})}});var Gc,qc,vh,ns,Vc,Wc,yh,Kc,zc=y(()=>{"use strict";ge();C();It();k();Je();Gc=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),qc=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=f();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},vh=e=>{let t=f().nodes[e];return!!t&&!t.isDeleted&&Ye(t)&&t.childRenderAxis==="vertical"},ns=(e,t)=>{let{nodes:n}=f(),r=n[e];if(!r||r.isDeleted)return!1;let o=ue(r.id);return U.navigate({contextNode:r,selectedIndex:Gc(t,o.length)}),!0},Vc=e=>{let{nodes:t}=f(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return ns(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let d=ue(o.id).findIndex(l=>l.id===n.id);return d>=0?(U.navigate({contextNode:o,selectedIndex:d}),!0):Vc(o.id)},Wc=e=>{let{nodes:t}=f(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Vc(n))return!0;n=t[n]?.parentNodeId}return!1},yh=e=>{if(!e)return!1;let t=f().nodes[e];return!!t&&!t.isDeleted},Kc=e=>{let{nodes:t,rootNodeId:n}=f();if(vh(e.contextNodeId)&&ns(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(yh(e.selectedNodeId)&&e.selectedNodeId&&Wc(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(ns(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&ns(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(Wc(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=ue(r.id);return U.navigate({contextNode:r,selectedIndex:Gc(e.selectedIndex,o.length)}),c("Restored navigation to root",null)}});import{monotonicFactory as bh,ulid as Nt}from"ulid";function xh(){let e=He();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 Ih(){let e=xh();return a(e)?e:U.navigate(e.value)}function Yc({userId:e,userName:t}){let n=Gr(),r=Gr(),o=Gr(),s=Gr(),d=Gr(),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 g=_e(p.value,void 0);if(a(g))return g;let I=_e(g.value,void 0);if(a(I))return I;let N=_e(void 0,void 0);return a(N)?N:c("Created default events",[{id:Nt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:Nt(),userId:e,userName:t,action:"create.contributor",payload:{id:e,name:t}},{id:Nt(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Nt(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Nt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:g.value}},{id:Nt(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:r,rank:I.value}},{id:Nt(),userId:e,userName:t,action:"add.board",payload:{id:Ko,name:"Closed",parent:n,rank:m.value}},{id:Nt(),userId:e,userName:t,action:"add.swimlane",payload:{id:ye,name:"Closed",parent:Ko,rank:N.value}},{id:Nt(),userId:e,userName:t,action:"lock.node",payload:{id:Ko}},{id:Nt(),userId:e,userName:t,action:"lock.node",payload:{id:ye}}])}function an(e,t=[]){if(Eh())return c("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Ne.workspace("temporary-uninitialized-workspace","Workspace","a0"),d=jr(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=Bt(e),{fatal:r,skipped:o}=Tn(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
|
-
|
|
25
|
+
`)}`):(wn(o),Ih(),E({hasProjectDefinition:!0}),Rh(t),c("State booted successfully",null))}var Gr,Eh,Rh,qr=y(()=>{"use strict";Et();Je();le();C();An();k();Zn();_t();nr();Gr=bh();Eh=()=>{let e=He();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},Rh=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 Sh}from"ws";var Nh,Xc,Jc=y(()=>{"use strict";Nh=new Set,Xc=e=>{let t=JSON.stringify(e);for(let n of Nh)n.readyState===Sh.OPEN&&n.send(t)}});var rs,os,ss,Wi,Qc,ke,is=y(()=>{"use strict";Jc();C();k();rs=e=>{ot()&&(E({syncStatus:e}),Xc({type:"sync-status",payload:e}))},os=(e="Syncing...")=>{rs({status:"syncing",msg:e})},ss=(e="Synced")=>{rs({status:"synced",msg:e})},Wi=e=>{rs({status:"failed",msg:e})},Qc=e=>{rs({status:"offline",msg:e})},ke=e=>(Wi(e),i(e))});var Vr,Z,as=y(()=>{"use strict";C();Vr=(e,t)=>(logger.error(`[boot:${e}] ${t}`),i(`[boot:${e}] ${t}`)),Z=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});import Ct from"node:fs";import Kr from"node:path";var rr,Zc,el,tl,Ch,nl,Ah,Th,rl,Gi=y(()=>{"use strict";lt();C();re();rr=e=>e.split(`
|
|
26
|
+
`).filter(t=>t.trim().length>0),Zc=e=>{let t=Kr.join(e,$e,en);try{if(!Ct.existsSync(t))return c("No events directory",[]);let n=Ct.readdirSync(t).filter(r=>r.endsWith(".jsonl")).filter(r=>rr(Ct.readFileSync(Kr.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)}`)}},el=e=>Kr.join(e,$e,en),tl=e=>{let t=el(e),n=new Map;try{if(!Ct.existsSync(t))return n;for(let r of Ct.readdirSync(t))r.endsWith(".jsonl")&&n.set(r,rr(Ct.readFileSync(Kr.join(t,r),"utf8")))}catch{return n}return n},Ch=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},nl=(e,t)=>{if(t.size===0)return[];let n=el(e),r=[];for(let[o,s]of t){if(s.length===0)continue;let d=Kr.join(n,o);try{let l=Ct.existsSync(d)?Ct.readFileSync(d,"utf8"):null,u=new Set(l===null?[]:rr(l)),m=s.filter(g=>!u.has(g)).filter(Ch);if(m.length===0)continue;Ct.mkdirSync(n,{recursive:!0});let p=l!==null&&l.length>0&&!l.endsWith(`
|
|
27
|
+
`);Ct.appendFileSync(d,`${p?`
|
|
28
|
+
`:""}${m.join(`
|
|
29
|
+
`)}
|
|
30
|
+
`,"utf8"),r.push(`${o} (${m.length})`)}catch{continue}}return r},Ah=(e,t)=>{let n=new Set(rr(t));return rr(e).filter(r=>!n.has(r))},Th=(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
|
+
`),rl=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let r=await Ue({args:["show",`HEAD:${t}`],cwd:e});if(r.exitCode!==0)return c("No committed log to compare against",void 0);let o=Ah(r.stdout,n);return o.length>0?i(Th(t,o,rr(r.stdout).length)):c("Event log only grew",void 0)}});import Ht from"node:fs";import zr from"node:path";var wh,sl,ol,Mh,qi,Vi,kh,Lh,Bn,Ph,Dh,ds,il,al,dl,Yr,cl,Xr=y(()=>{"use strict";C();Et();Uo();Lr();Gi();mt();lt();wh="[epiq:init-repo]",sl=async e=>{let t=await Ue({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 G({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(a(r))return i(r.message);let o=await G({args:["commit-tree",r.value.stdout.trim(),"-m",wh],cwd:e});if(a(o))return i(o.message);let s=await G({args:["update-ref","HEAD",o.value.stdout.trim()],cwd:e});return a(s)?i(s.message):c("Created initial commit",!0)},ol=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Mh=async e=>{let t=await Ho(e);if(a(t))return i(t.message);let n=await Hd(e);return a(n)?i(n.message):c("Built sync commit message",`[sync|branch:${ol(t.value)}:sha:${ol(n.value)}]`)},qi=async({repoRoot:e,stateBranchName:t})=>{X.info(`Creating ${t}`);let n=await G({args:["commit-tree",Yd,"-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 G({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)},Vi=async({repoRoot:e,stateBranchName:t})=>{let n=await jo({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 fi({repoRoot:e});if(a(r))return i(`Ensure local state branch failed
|
|
36
|
+
`+r.message);let o=r.value,s=o?await hi({repoRoot:e,branch:t}):c("No remote, no remote state branch",!1);if(a(s))return i(`Ensure local state branch failed
|
|
33
37
|
`+s.message);let d=s.value;if(o&&d){let l=await he.fetch({cwd:e,remote:nt,branch:t});if(a(l))return i(`Failed to fetch ${t} from remote
|
|
34
|
-
${l.message}`)}if(d){let l=await
|
|
35
|
-
${l.message}`):c("Created local state branch from remote",!0)}return
|
|
36
|
-
`),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)},
|
|
37
|
-
`+r.message);if(
|
|
38
|
-
`));
|
|
39
|
-
${o.message}`):c("Created state branch worktree",!0)},
|
|
40
|
-
`));
|
|
41
|
-
${m.message}`)}if(s&&!
|
|
42
|
-
${u.message}`)}let d=await
|
|
43
|
-
${u.message}`)}return
|
|
44
|
-
${o.message}`):c("Checked out state branch",!0)},
|
|
38
|
+
${l.message}`)}if(d){let l=await G({args:["branch","--track",t,`${nt}/${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 qi({repoRoot:e,stateBranchName:t})},kh=async({repoRoot:e,branch:t})=>{let n=await G({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)},Lh=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Dr(zr.dirname(t));if(a(r))return i(`Failed to create state branch worktree
|
|
41
|
+
`+r.message);if(Ht.existsSync(t)&&!Ht.existsSync(zr.join(t,".git"))){let s=Zc(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"),Zd(t)}X.info("Creating state branch worktree");let o=await he.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)},Bn=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await kh({repoRoot:e,branch:n});if(a(r))return i(r.message);let o=Pr(t),s=r.value?Pr(r.value):null;if(s&&s===o&&Ht.existsSync(s))return c("State branch already checked out in expected worktree",!1);if(s&&s!==o){let u=await qd(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 he.worktreeRemove({cwd:e,worktreeRoot:s});if(a(m))return i(`Failed to remove existing state branch worktree
|
|
45
|
+
${m.message}`)}if(s&&!Ht.existsSync(s)){X.info("Pruning stale state branch worktree");let u=await he.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
|
|
46
|
+
${u.message}`)}let d=await jd({repoRoot:e,worktreeRoot:t});if(a(d))return i(d.message);let l=Ht.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 he.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
|
|
47
|
+
${u.message}`)}return Lh({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Ph=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Ho(e);if(a(n))return i(n.message);if(n.value===t)return c("State branch already checked out",!1);(await Ue({cwd:e,args:["rebase","--abort"]})).exitCode===0&&X.info("Aborted stale state branch rebase");let o=await he.checkout({cwd:e,branch:t});return a(o)?i(`Failed to checkout ${t}
|
|
48
|
+
${o.message}`):c("Checked out state branch",!0)},Dh=async({repoRoot:e,stateBranchRoot:t})=>{let n=await vi(t);if(a(n))return i(n.message);if(n.value)return c("State branch upstream already configured",!1);let r=await fi({repoRoot:t});if(a(r))return i(r.message);if(!r.value)return c("No remote available for state branch upstream",!1);let o=Qt(e);if(a(o))return o;let s=o.value,d=await hi({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 he.fetch({cwd:t,remote:nt,branch:s});if(a(l))return i(`Failed to fetch ${s}
|
|
45
49
|
${l.message}`);let u=await he.setUpstream({cwd:t,branch:s,upstream:`${nt}/${s}`});return a(u)?i(`Failed to set state branch upstream
|
|
46
|
-
${u.message}`):c("Configured state branch upstream",!0)},
|
|
47
|
-
${s.message}`):c("Staged state branch event file",n)},
|
|
48
|
-
${r.message}`):c("Staged state branch media files",t)},
|
|
49
|
-
${n.message}`):c("Staged event log attributes",t)},
|
|
50
|
-
`+r.message):
|
|
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
|
-
`),t);let o=
|
|
55
|
-
`).map(
|
|
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}
|
|
57
|
-
Date: ${
|
|
50
|
+
${u.message}`):c("Configured state branch upstream",!0)},ds=async({stateBranchRoot:e,eventFileName:t})=>{let n=Xd(t),r=zr.join(e,n);if(!Ht.existsSync(r))return c("No event file to stage",null);let o=await rl({stateBranchRoot:e,relativePath:n,workingContent:Ht.readFileSync(r,"utf8")});if(a(o))return i(o.message);let s=await he.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)},il=async({stateBranchRoot:e})=>{let t=Jd(),n=zr.join(e,t);if(!Ht.existsSync(n))return c("No media directory to stage",null);let r=await he.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)},al=async({stateBranchRoot:e})=>{let t=Ii();if(!Ht.existsSync(zr.join(e,t)))return c("No event log attributes to stage",null);let n=await he.stage({cwd:e,pathspec:[t]});return a(n)?i(`Failed to stage event log attributes
|
|
53
|
+
${n.message}`):c("Staged event log attributes",t)},dl=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let r=await Mh(e);return a(r)?i(`Create state branch sync commit failed
|
|
54
|
+
`+r.message):er({cwd:t,message:r.value,pathspec:n})},Yr=async({repoRoot:e,stateBranchRoot:t})=>{let n=await vi(t);if(a(n))return i(n.message);let r=Qt(e);if(a(r))return r;let o=r.value,s=n.value?await he.push({cwd:t}):await he.push({cwd:t,remote:nt,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)},cl=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Qt(e);if(a(o))return o;let s=o.value,d=[Go(),await Vi({repoRoot:e,stateBranchName:s}),await Bn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Ph({stateBranchRoot:t,stateBranchName:s}),await tc(t),n?await Dh({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 cs from"node:fs";import zi from"node:os";import Fh from"node:path";var Oh,ll,Bh,_h,Uh,ml,Ki,ul,$h,pl,gl=y(()=>{"use strict";C();lt();Et();Oh="epiq-sync.lock",ll=600*1e3,Bh=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}},_h=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Uh=e=>e&&(e.hostname!==zi.hostname()||_h(e.pid))?Date.now()-e.startedAt>ll:!0,ml=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,Ki=e=>{try{return Bh(cs.readFileSync(e,"utf8"))}catch{return null}},ul=(e,t)=>{let n={pid:process.pid,hostname:zi.hostname(),startedAt:Date.now(),operation:t};try{return cs.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},$h=async({worktreeRoot:e,operation:t})=>{let n=await gi(e);if(a(n))return i(n.message);let r=Fh.join(n.value,Oh),o=()=>{try{let l=Ki(r);l&&l.pid===process.pid&&cs.rmSync(r)}catch{}};if(ul(r,t))return c("Acquired sync lock",{acquired:!0,release:o});let s=Ki(r);if(!Uh(s))return c("Sync lock is held",{acquired:!1,heldBy:s});X.info(`Breaking an abandoned sync lock: ${s?ml(s):"unreadable lock file"}`);try{cs.rmSync(r,{force:!0})}catch{}if(ul(r,t))return c("Acquired sync lock after breaking a stale one",{acquired:!0,release:o});let d=Ki(r);return c("Sync lock taken by another process",{acquired:!1,heldBy:d??{pid:-1,hostname:zi.hostname(),startedAt:Date.now(),operation:"unknown"}})},pl=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await $h({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 ${ml(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 jh from"node:fs";var Hh,Wh,fl,hl,Gh,ls,Yi=y(()=>{"use strict";C();is();as();Lr();mt();lt();Xr();Gi();gl();Hh=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",Se({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 cl({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 $o(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",ec(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}))},Wh=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 ds({stateBranchRoot:t,eventFileName:n}));if(a(r))return i(r.message);let o=Z("stageStateBranchMediaFiles",await il({stateBranchRoot:t}));if(a(o))return i(o.message);let s=Z("stageStateBranchEventAttributes",await al({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 Vd(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 dl({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}))},fl=e=>{let t=e.createdCommit?"Committed locally, offline":"Offline";return Qc(t),c(t,{...e,pulled:!1,pushed:!1,offline:!0})},hl=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");os();let n=Z("ensureSyncReady",await Hh({cwd:e,ensureUpstream:!0}));if(a(n))return ke(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,d=Z("isDetachedHead(stateBranchRoot)",await Kd(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,g=Z("getStateBranch",Qt(r));if(a(g))return ke(g.message);let I=g.value;logger.debug("[sync] resolved state branch",{stateBranch:I,stateBranchRoot:o});let N=Z("commitOwnEventFileToStateBranch",await Wh({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(a(N))return ke(N.message);l=N.value.createdCommit,u=N.value.commitSha;let A=Z("pullBranchRebaseIfPresent",await bi({cwd:o,branch:I}));if(a(A))return yi(A.message)?fl({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,bootstrapped:s}):ke(A.message);m=A.value;let w=Z("isAheadOfUpstream",await Gd(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=Z("pushStateBranch",await Yr({stateBranchRoot:o,repoRoot:r}));if(a(T)&&Wd(T.message)){let M=Z("pullBranchRebaseIfPresent(retry)",await bi({cwd:o,branch:I}));if(a(M))return ke(M.message);m=m||M.value,T=Z("pushStateBranch(retry)",await Yr({stateBranchRoot:o,repoRoot:r}))}if(a(T))return yi(T.message)?fl({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=Z("git rev-parse HEAD",await G({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 ss(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})},Gh=async(e,t)=>{let n=tl(e);try{return await t()}finally{let r=nl(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},ls=async e=>{let t=e.cwd??process.cwd(),n=await ut(t);if(a(n))return ke(n.message);let r=Se({repoRoot:n.value});if(a(r))return ke(r.message);let o=r.value;if(!jh.existsSync(o))return hl(e);let s=await pl({worktreeRoot:o,operation:"sync",fn:()=>Gh(o,()=>hl(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 At,us,qh,vl,Xi=y(()=>{"use strict";zc();qr();jt();gt();le();C();k();is();as();Yi();At=null,us=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!At,currentStatus:f().syncStatus?.status,currentMessage:f().syncStatus?.msg}),At)return logger.debug("[sync] syncAndReloadState joining existing promise"),At;logger.debug("[sync] syncAndReloadState creating promise"),At=qh();try{let e=await At;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:f().syncStatus?.status,statusMessageAfterResolve:f().syncStatus?.msg}),a(e)&&f().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}),At||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:f().syncStatus?.status,statusMessageBeforeClear:f().syncStatus?.msg}),At=null}},qh=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:f().mode,syncStatus:f().syncStatus});let e=vl();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:f().mode,message:e.message,syncStatus:f().syncStatus}),e;if(At)return At;logger.debug("[sync] syncAndReloadState:start");let t=Z("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:f().syncStatus});let n=Pn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=Z("syncEpiqWithRemote",await ls({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:f().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=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:f().syncStatus}),i(`Unable to load events. ${d.message}`);logger.debug("[sync] loaded merged events after sync",{count:d.value.events.length});let l=vl();if(l)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:f().mode,message:l.message,syncStatus:f().syncStatus}),l;let u=qc(),m=f().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:u,selectedNodeId:f().selectedNode?.id,contextNodeId:f().contextNode?.id,selectedNodeIsVirtual:f().selectedNode?.isVirtual,contextNodeIsVirtual:f().contextNode?.isVirtual}),!f().selectedNode?.isVirtual&&!f().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:d.value.events.length});let g=Z("bootStateFromEventLog",an(d.value.events,d.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(g),message:(a(g),g.message)}),a(g))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:f().syncStatus}),i(`Unable to boot synced state. ${g.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:f().selectedNode?.isVirtual,contextNodeIsVirtual:f().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),E({filters:m}),logger.debug("[sync] restoreNavigationAnchor:start");let p=Z("restoreNavigationAnchor",Kc(u));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(p),message:a(p)?p.message:"Navigation restored",selectedNodeId:f().selectedNode?.id,contextNodeId:f().contextNode?.id}),a(p)?(E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:f().syncStatus}),p):(E({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:f().syncStatus}),c("Synced",!0))},vl=()=>f().mode===h.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:f().mode,syncStatus:f().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 or,yl,bl,Ji,Qi,Jr,Zi,Vh,xl,Kh,Il,ms=y(()=>{"use strict";C();Be();k();Xi();or=3e3,yl=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<or?null:t},bl=0,Qi=!1,Jr=!1,Zi=()=>{if(Qi)return!0;let e=He();return a(e)?!1:e.value.syncStatus.status==="syncing"},Vh=()=>{let e=ve().autoSyncIntervalMs??1e4,t=Date.now()-bl;return Math.max(0,e-t)},xl=()=>{Ji||(Ji=setTimeout(async()=>{if(Ji=void 0,!!ot()){if(Zi()){Jr=!0;return}Jr=!1,await Kh()}},Vh()))},Kh=async()=>{if(f().readOnly||f().timeMode==="peek"||f().timeMode==="replay")return i("Cannot auto-sync while peeking");if(!ot())return i("Cannot auto-sync before state is initialized");if(Zi())return Jr=!0,i("Sync already in progress");Qi=!0,bl=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await us()}finally{Qi=!1,Jr&&xl()}},Il=()=>{ot()&&(Jr=!0,!Zi()&&xl())}});import Qr from"node:fs";import Zr from"node:path";import{z as sr}from"zod";var ps,zh,Yh,Xh,Rl,Sl,El,Nl,Cl,Al,Jh,gs,ea,eo=y(()=>{"use strict";C();Ot();_o();re();ps="recent-projects.json",zh=20,Yh=sr.object({projectId:sr.string().min(1),root:sr.string().min(1),lastOpenedAt:sr.number().finite()}),Xh=sr.object({projects:sr.array(Yh)}),Rl=()=>Zr.join(Rn(),ps),Sl=e=>Zr.basename(e)||e,El=e=>{let t=Zr.resolve(e);try{return Qr.realpathSync(t)}catch{return t}},Nl=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Cl=e=>{if(!Or(e.root))return!1;let t=kr(e.root);return!a(t)&&t.value===e.projectId},Al=()=>{let e=Rl();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 ${ps}: ${r instanceof Error?r.message:String(r)}`)}let n=Xh.safeParse(t);return n.success?c("Read recent projects",n.data.projects):i(`Invalid ${ps} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Jh=e=>{let t=Rl();try{Qr.mkdirSync(Zr.dirname(t),{recursive:!0}),Qr.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
56
|
+
`,"utf8")}catch(n){return i(`Unable to write ${ps}: ${n instanceof Error?n.message:String(n)}`)}return c("Recorded recent project",e)},gs=({exclude:e}={})=>{let t=Al();if(a(t))return t;let n=e===void 0?null:El(e);return c("Listed recent projects",t.value.filter(r=>n===null||El(r.root)!==n).filter(Cl).sort(Nl))},ea=({root:e,now:t=Date.now()})=>{let n=Zr.resolve(e),r=kr(n);if(a(r))return i(r.message);let o=r.value,s=Al(),d=a(s)?[]:s.value,l=[{projectId:o,root:n,lastOpenedAt:t},...d.filter(u=>u.projectId!==o&&u.root!==n)].filter(Cl).sort(Nl).slice(0,zh);return Jh(l)}});var fs,Tl,wl,Ml,to=y(()=>{"use strict";C();Ot();Be();re();fs=()=>{let e=ve(),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}},Tl=()=>{let e=Xe(process.cwd());if(a(e))return!1;let t=Ft(e.value);return ht(t)},wl=e=>e===!0?"on":e===!1?"off":null,Ml=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,ir,hs=y(()=>{"use strict";Pe();R={red:Le.red,yellow:Le.yellow,green:Le.green,blue:Le.blue,magenta:Le.magenta,cyan:Le.cyan},ir={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 Qh,Zh,dn,cn,vs,ys,no=y(()=>{"use strict";ge();C();me();k();Qh=e=>e.props.tags??[],Zh=e=>e.props.assignees??[],dn=e=>Qh(e).map(t=>x.getTag(t)).filter(t=>!!t),cn=e=>Zh(e).map(t=>x.getContributor(t)).filter(t=>!!t),vs=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!P(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",dn(n))},ys=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!P(n)?i("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",cn(n))}});var v,_n=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 ev,tv,nv,rv,ov,Un,kl,bs,xs,Ll,sv,ta,ro=y(()=>{"use strict";ev=/^(\d+)(h|d|w|mo|y)$/,tv=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,nv=({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},rv=(e,t=new Date)=>{let n=e.match(ev);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}},ov=e=>{let t=e.match(tv);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,g=d?Number(d):0;return nv({year:l,month:u,day:m,hour:p,minute:g})?new Date(l,u-1,m,p,g):null},Un=e=>{let t=e.trim().toLowerCase();return rv(t)??ov(t)},kl=/^(\d+)(s|m)?$/,bs=e=>{let t=e.trim().toLowerCase().match(kl);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},xs=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&kl.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Ll=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,sv=[{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}],ta=(e=sv)=>{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 iv,pe,Qe,Ee,av,dv,ra,oa,Fl,$n,Is,na,Pl,cv,lv,oo,Dl,uv,mv,sa,pv,be,ln=y(()=>{"use strict";ms();eo();C();to();nr();ge();me();k();hs();no();_n();ro();iv=["BOARD","TICKET","SWIMLANE","COMMENT"],pe={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},Qe={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Ee={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},av=[pe.EDITOR,pe.VIEW,pe.USERNAME,pe.AUTOSYNC,pe.SYNC_DEBOUNCE_MS,pe.ATTACHMENT_MAX_KB,pe.LOG_LEVEL],dv=(e=f().selectedNode?.context)=>{switch(e){case"TICKET":return[Qe.TITLE,Qe.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Qe.TITLE];case"COMMENT":return[Qe.COMMENT];default:return[]}},ra=[String(or),"5000","15000","30000","60000"],oa=["250","500","1000"],Fl=["10s","20s","30s","45s"],$n=[v.COFFEE,v.EXIT,v.SYNC,v.HELP,v.EXPORT,v.CONFIG,v.YANK],Is=[v.NEW,v.EDIT,v.DELETE,v.MOVE],na=[v.TAG,v.UNTAG,v.ASSIGN,v.UNASSIGN,v.CLOSE_ISSUE,v.RE_OPEN_ISSUE,v.EDIT,v.COMMENT],Pl=[v.FILTER,v.PEEK,v.REPLAY],cv={WORKSPACE:[...$n,...Is],BOARD:[...Pl,...$n,...Is],SWIMLANE:[...Pl,...$n,...Is],TICKET:[...$n,...Is,...na],FIELD:[...$n,...na],FIELD_LIST:[...$n,...na],TEXT:[...$n],COMMENT:[v.EDIT,v.DELETE,v.YANK]},lv=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],oo=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&P(n)),Dl=e=>e.parentNodeId===ye,uv=({selectedNode:e,breadCrumb:t})=>{let n=dv(e?.context);return oo({breadCrumb:t,selectedNode:e})?n.includes(Qe.DESCRIPTION)?n:[...n,Qe.DESCRIPTION]:n},mv=({selectedNode:e,breadCrumb:t})=>{let n=oo({breadCrumb:t,selectedNode:e});return n?[Ee.REF,Ee.TITLE,...n.props?.description?.trim()?[Ee.DESCRIPTION]:[],...dn(n).length>0?[Ee.TAGS]:[],...cn(n).length>0?[Ee.ASSIGNEES]:[]]:e?[Ee.REF,Ee.TITLE]:[]},sa=()=>{let e=gs({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},pv=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=fs();if(!r)return[v.HELP,v.CONFIG];if(!Tl())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&&iv.includes(o),d=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?cv[u]:[]))],l=oo({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&&dn(l).length>0):u===v.UNASSIGN?!!(l&&cn(l).length>0):u===v.RE_OPEN_ISSUE?!!(l&&Dl(l)):u===v.CLOSE_ISSUE?!!(l&&!Dl(l)):!0)},be=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=f())=>{let s=t.context??"WORKSPACE";return{[v.NONE]:pv({breadCrumb:o,readOnly:r,selectedNode:n}),[v.EXIT]:["confirm"],[v.EXPORT]:[],[v.SYNC]:[],[v.INIT]:[],[v.OPEN]:e===v.OPEN?sa():[],[v.HELP]:[],[v.PEEK]:[...ta(),"now","prev","next"],[v.REPLAY]:[...ta()],[v.EDIT]:uv({selectedNode:n,breadCrumb:o}),[v.YANK]:mv({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","actor","description","title","ref","clear"],[v.TAG]:[...new Set([...Object.keys(ir),...x.getExistingTags()])],[v.UNTAG]:[...vs()?.value?.map(({name:l})=>l)??[]],[v.UNASSIGN]:[...ys()?.value?.map(({name:l})=>l)??[]],[v.ASSIGN]:x.getExistingAssignees(),[v.NEW]:lv(s),[v.CONFIG]:[...av],[v.COFFEE]:["1","3","5","20","custom"]}[e]??[]}});var Ol,Bl=y(()=>{"use strict";Ol=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{accessSync as gv,copyFileSync as fv,existsSync as Es,mkdirSync as _l,readdirSync as Ul,readFileSync as hv,renameSync as vv,rmSync as yv,statSync as $l,unlinkSync as bv,writeFileSync as xv}from"node:fs";import ar from"node:path";var ia,We,Rs=y(()=>{"use strict";ia=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",We={writeToFile:(e,t)=>{try{let n=ar.dirname(e);Es(n)||_l(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);xv(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return hv(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=We.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 Es(e)&&$l(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await gv(e),!0}catch{return!1}},mkDir:e=>_l(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=ar.parse(t);for(;;){let r=ar.join(t,e);try{if(Es(r)&&$l(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=ar.dirname(t)}return null},readFirstJSON(e){try{if(!We.dirExists(e))return null;let t=Ul(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=ar.join(e,t);return We.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return We.dirExists(e)?Ul(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{bv(e)}catch(t){(!ia(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{yv(e,{recursive:!0,force:!0})}catch(t){(!ia(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(ar.dirname(t)),!n?.overwrite&&Es(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{vv(e,t)}catch(r){if(ia(r)&&r.code==="EXDEV"){fv(e,t),this.rmFile(e);return}throw r}}}});import Iv from"node:path";import{z as Wt}from"zod";var Ev,jl,Rv,Hl,aa,da,Sv,Ss,Wl,st,ca,jn=y(()=>{"use strict";Qn();re();C();Rs();Ev={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},jl=Wt.object({logLevel:Wt.enum(["info","error","debug"]),preferredEditor:Wt.string().optional(),userName:Wt.string().optional(),userId:Wt.string().optional(),autoSync:Wt.boolean().nullable().optional(),autoSyncDebounceMs:Wt.number().optional(),attachmentMaxKb:Wt.number().optional(),viewMode:Wt.enum(["dense","wide"]).optional()}).partial(),Rv="config.json",Hl=Rn,aa=()=>Iv.join(Hl(),Rv),da=()=>{try{return We.mkDir(Hl()),c(`Ensured ~/${ct} exists`,null)}catch{return i(`Unable to create ~/${ct}`)}},Sv=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${ct}/config.json JSON`)}let n=jl.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(", ")}`)},Ss=()=>{let e=da();if(a(e))return i(e.message);let t=aa(),n=We.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Sv(n)},Wl=e=>{let t=da();if(a(t))return i(t.message);let n=jl.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=aa();try{return We.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
57
|
+
`),c("Config written",null)}catch{return i(`Unable to write ~/${ct}/config.json`)}},st=e=>{let t=Ss();if(a(t))return i("Failed to read existing config");let n={...t.value,...e};return Wl(n)},ca=()=>{let e=aa(),t=da();if(a(t))return i(`Unable to create ~/${ct}`);if(!(We.readFile(e)!==null)){let A=Wl(Ev);if(a(A))throw new Error(`Unable to create ~/${ct}/config.json`)}let r=Ss();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:g}=r.value,I=ii({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:g??"dense"}))}});var Gl,ql,la,Vl=y(()=>{"use strict";Gl="/media/",ql=e=>`${Gl}${e}`,la=(e,t)=>`})`});import Nv from"node:crypto";import ua from"node:fs";import Cv from"node:path";var Gt,so,Av,Tv,wv,Kl,io=y(()=>{"use strict";bt();C();re();Vl();Gt=500,so=(e,t)=>`${e}.${t}`,Av=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: ${Ed.join(", ")}`),Tv=e=>Nv.createHash("sha256").update(e).digest("hex"),wv=(e,t=Gt)=>{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=Av(e);return a(n)?n:c("Validated attachment data",{hash:Tv(e),ext:n.value,bytes:e.length})},Kl=(e,t,n=Gt)=>{let r=wv(t,n);if(a(r))return r;let o=qo(e),s=Cv.join(o,so(r.value.hash,r.value.ext));try{ua.existsSync(s)||(ua.mkdirSync(o,{recursive:!0}),ua.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 Mv from"zod";var ao,co,zl,ma=y(()=>{"use strict";jn();io();le();C();xe();Be();k();ao=50,co=5e3,zl=()=>{let e=de().commandMeta.inputString,t=Mv.coerce.number().int().min(ao).max(co).safeParse(e);if(!t.success)return i(`Attachment size cap must be ${ao}-${co} KB (default ${Gt})`);let n=st({attachmentMaxKb:t.data});return a(n)?n:(et({attachmentMaxKb:t.data}),E({mode:h.DEFAULT}),c(`Attachment size cap set to ${t.data} KB`,null))}});import Yl from"chalk";var ga,Xl,pa,Jl,kv,Lv,Ql,Pv,Dv,lo,De,Zl,eu,Ns,Fv,Ov,Cs,Tt=y(()=>{"use strict";hs();ga={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Xl=(e,t,n)=>Math.max(t,Math.min(n,e)),pa=(e,t,n)=>e+(t-e)*n,Jl=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},kv=e=>e.toLowerCase().trim(),Lv=(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 g=o-s/2;return[Math.round((u+g)*255),Math.round((m+g)*255),Math.round((p+g)*255)]},Ql=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Pv=(e,t,n)=>{let r=Xl(n,0,1);return[Math.round(pa(e[0],t[0],r)),Math.round(pa(e[1],t[1],r)),Math.round(pa(e[2],t[2],r))]},Dv=(e,t,n)=>Pv(e,t,n),lo=e=>{let t=Jl(e)%360,n=Lv(t,ga.stringColor.saturation,ga.stringColor.lightness);return Ql(n)},De=(e,t=ir)=>{let n=kv(e??"");return n&&t[n]?t[n]:lo(n)},Zl=e=>{let t=ga.gradient.stops,n=Xl(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 Dv(t[s],t[s+1],d)},eu=e=>Ql(Zl(e)),Ns=e=>Jl(e.toLowerCase().trim())/4294967295,Fv=e=>{let t=Ns(e);return Zl(t)},Ov=e=>{let[t,n,r]=Fv(e);return{normal:o=>Yl.bgRgb(t,n,r).black(o),cursor:o=>Yl.bgRgb(t,n,r).white.bold(o)}},Cs=e=>Ov(e).normal(` ${e} `)});var ft,uo=y(()=>{"use strict";ft=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null});import{createHash as Bv}from"node:crypto";var _v,Uv,Ce,dr=y(()=>{"use strict";_v="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Uv=e=>{let t=Bv("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+=_v[Number(n>>s&31n)]}return r},Ce=(e,t)=>Uv(`${e}:virtual:${t}`)});import tu from"chalk";var te,Ae,Te,nu=y(()=>{"use strict";Tt();Pe();te=e=>tu.dim(e),Ae=e=>tu.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(g=>g.startsWith(d))].sort((g,I)=>Ns(g)-Ns(I)).slice(0,r).map(g=>Cs(g)).join(" ");return p?`${te(e)}${p}${te(n)}`:""}});var un,As=y(()=>{"use strict";un={None:"none",Invalid:"invalid",Valid:"valid"}});import su from"chalk";var $v,ru,ce,Y,j,cr,ou,Ts,fa,jv,Hn,Hv,Wv,Gv,qv,Vv,iu,au=y(()=>{"use strict";ms();to();Bl();dt();bt();C();me();Be();ma();io();k();Tt();uo();no();dr();nu();_n();As();ln();ro();$v=["BOARD","TICKET","SWIMLANE"],ru=()=>{let e=f().selectedNode;if(!e?.context)return j({message:te("Missing target context")});if($v.includes(e.context))return Y();if(e.parentNodeId){let t=f().nodes[e.parentNodeId];if(t?.id===Ce(t?.parentNodeId??"","comments"))return Y()}return j({message:te("Command not available in this context")})},ce="<ENTER> to confirm",Y=(e="",t=[])=>({message:te(e),validity:un.Valid,completionWordList:t}),j=({message:e,completionWordList:t=[]})=>({validity:un.Invalid,message:e,completionWordList:t}),cr=e=>e.length===0,ou=(e,t)=>{let n=ze(f().breadCrumb,"BOARD");if(a(n))return j({message:Ae("Command is not applicable in this context")});let r=Id(n.value.id);return a(r)?j({message:Ae(`Unable to ${t}: board id is not a valid ULID`)}):Ll({date:e,horizonDate:r.value})?null:j({message:Ae(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},Ts=e=>` ${su.hex("#000").bgHex(De(e))(` ${e} `)} `,fa=({modifier:e})=>{let t="confirm";return e===t?Y(ce):j({message:cr(e)?te("if you are certain, enter ")+Cs(t):"",completionWordList:[t]})},jv=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?j({message:te(n)}):Y():j({message:cr(r)?t:"",completionWordList:[...e]}),Hn=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>cr(n)&&cr(r)?j({message:e,completionWordList:[]}):Y(t??ce),Hv=({modifier:e,inputString:t})=>{let n=sa();return!cr(e)||!cr(t)?Y(ce):j({message:n.length?te("number from the list, or a path"):te("path to an epiq project"),completionWordList:n})},Wv=({modifier:e,inputString:t})=>{let n=be(v.CONFIG);if(!n.includes(e))return j({message:Te({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case pe.EDITOR:{let r=[...Ol];return t.trim()?r.includes(t.trim())?Y(ce):j({message:Te({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):j({message:Te({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case pe.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?Y(ce):j({message:Te({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case pe.USERNAME:return t.trim()?Y(ce):j({message:Ae("Enter a user name. Saved in ")+su.bgBlack("~/.epiq-global/config.json")});case pe.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?Y(ce):j({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=ve().autoSync;if(!r.includes(t.trim())){let s=wl(o);return j({message:Te({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return Y(ce)}case pe.ATTACHMENT_MAX_KB:{let r=ve().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<ao||o>co){let s=Te({prefix:" examples: ",wordList:oa,minLengthForHints:0,inputString:t});return j({message:Ae(`provide a size cap in KB (${ao}-${co}). current: ${r??Gt} KB.`)+s,completionWordList:oa})}return Y(ce)}case pe.SYNC_DEBOUNCE_MS:{let r=ve().autoSyncIntervalMs,o=yl(t);if(!t.trim()||o===null||o<or){let s=Te({prefix:" examples: ",wordList:ra,minLengthForHints:0,inputString:t});return j({message:Ae(`provide duration above ${or}ms. current duration: ${r}ms.`)+s,completionWordList:ra})}return Y(ce)}default:return j({message:Ae("Unknown config option"),completionWordList:n})}},Gv=({modifier:e,inputString:t})=>{let n=be(v.EDIT);if(!n.length)return j({message:Ae("Command not available in this context")});if(!n.includes(e)){let r=Te({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return j({message:r||Ae("Unknown edit option"),completionWordList:n})}switch(e){case Qe.COMMENT:return t.trim()?Y(ce):j({message:te("write a comment...")});case Qe.TITLE:return Y(ce);case Qe.DESCRIPTION:{let{preferredEditor:r}=ve();return r?Y(te("<ENTER> to edit in ")+r):j({message:"No editor selected"})}default:return j({message:Ae("Unknown edit option"),completionWordList:n})}},qv=({modifier:e})=>{let t=be(v.YANK);return t.length?t.includes(e)?Y(ce+te(" and copy to clipboard")):j({message:Te({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):j({message:Ae("Nothing selected to copy from")})},Vv={[v.EXPORT]:()=>Y(ce+te(", 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:te("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Un(r);if(!r||!o)return j(n);let s=ou(o,"peek");return s||Y(ce)},[v.REPLAY]:e=>{let{dateInput:t,durationInput:n}=xs(e.modifier,e.inputString),r={message:te("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Un(t);if(!t||!o)return j(r);let s=ou(o,"replay");return s||(n&&bs(n)===null?j({message:Ae("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):Y("<ENTER> to replay board history",n?Fl:[]))},[v.EXIT]:()=>Y(ce+te(" and exit the application")),[v.INIT]:()=>Y(ce),[v.OPEN]:Hv,[v.PALETTE]:()=>Y(ce),[v.FILTER]:e=>{if(e.modifier==="clear")return Y(ce);let t=s=>be(v.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return j({message:Te({wordList:be(v.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:be(v.FILTER)});let n=Object.values(f().tags).map(s=>s.name),r=Object.values(f().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?j({message:Te({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):Y():j({message:Te({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[v.NONE]:e=>{let t=be(v.NONE);return j({message:Te({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[v.NEW]:e=>jv({list:be(v.NEW),hint:Te({wordList:be(v.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[v.HELP]:()=>Y(ce),[v.EDIT]:Gv,[v.COMMENT]:e=>{let t=Hn({hint:te(`write a comment (max ${4e3} char)...`),onOk:te(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===un.Invalid?t:e.inputString.length>4e3?Y(Ae("max input exceeded")):t},[v.CONFIG]:Wv,[v.YANK]:qv,[v.DELETE]:e=>{let t=ru();return t.validity==="invalid"?t:fa(e)},[v.CLOSE_ISSUE]:e=>fa(e),[v.RE_OPEN_ISSUE]:e=>fa(e),[v.MOVE]:e=>{let t=ru();return t.validity==="invalid"?t:Hn({hint:Te({prefix:"hey hacker! These commands are blocked for you... ",wordList:be(v.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[v.TAG]:e=>{let n=x.getExistingTags().slice(0,10).map(Ts).join("");return Hn({hint:n.length?te("create tag or reuse:")+n+te(""):te("create tag ...")})(e)},[v.UNTAG]:e=>{let t=vs();if(a(t))return j({message:Ae("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Ts).slice(0,10);return n.length?Hn({hint:te(" ... ")+n.join("")})(e):j({message:Ae("Issue has no tags"),completionWordList:[]})},[v.ASSIGN]:e=>{let t=x.getExistingAssignees().map(Ts).slice(0,10);return Hn({hint:te("assignees... ")+t.join("")})(e)},[v.UNASSIGN]:e=>{let t=ys();if(a(t))return j({message:Ae("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Ts).slice(0,10);return n.length?Hn({hint:te("remove assignee... ")+n.join("")})(e):j({message:Ae("Issue has no assignees"),completionWordList:[]})},[v.SYNC]:()=>Y(ce),[v.COFFEE]:e=>{let{modifier:t}=e,n=be(v.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?j({message:te("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):Hn({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)}},iu=Object.fromEntries(Object.entries(Vv).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]))});var ws,du=y(()=>{"use strict";ws=["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 Kv,zv,Yv,Xv,Jv,cu,lu,uu,mu=y(()=>{"use strict";C();k();du();Kv=3,zv=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"]),Yv=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},Xv=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=Kv&&!zv.has(t)&&!/^\d+$/.test(t)),Jv=e=>{let t=new Map;for(let s of Yv(e))for(let d of Xv(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=ws.filter(s=>!r.has(s));return[...n,...o]},cu=ws,lu=-1,uu=()=>{let e=He();if(a(e))return ws;let t=e.value,n=t.eventLog.length;return n!==lu&&(cu=Jv(t),lu=n),cu}});var pu,gu,ha=y(()=>{"use strict";Pd();ln();_n();au();mu();k();le();pu=e=>Object.values(v).includes(e),gu=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:d,validity:l,completionWordList:u}=iu[n].validate(n,r,s),m=n!==v.PEEK&&n!==v.REPLAY,p=o==="command"||o==="modifier"?be(n):m?uu():[],{mode:g}=f(),I=g===h.COMMAND_LINE?d??"":"",N=[...u,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:I,autoCompletion:t?Ld(e,N):{hint:"",hints:[],remainder:"",overlap:0}}}});var fu,Qv,Zv,ey,hu=y(()=>{"use strict";ha();ln();fu=e=>{let t=e.trimStart(),n=Zv(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),d=ey(e),l=pu(r)?r:null,u=l!==null,m=r!=="",p=l?be(l)??[]:[],g=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=Qv(t,l,g);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:s,modifier:g,target:I,inputToMatch:N,inputString:A}},Qv=(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},Zv=e=>e.trim()?e.trim().split(/\s+/):[],ey=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as aT}from"react";var lr,va,ur,ty,vu,wt,mo,ya,ba,yu,bu,Ms,xu,K,Iu,Eu,Ru,de,ks,xe=y(()=>{"use strict";ha();hu();C();As();lr=e=>e===va||e===":",va=" ",ur={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:un.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},ty=new Set,vu=()=>{for(let e of ty)e()},wt=e=>{let n=e(ur),r=fu(n.value),o=n.cursorPosition===n.value.length;ur={...n,commandMeta:gu(r,o)},vu()},mo=({message:e,status:t})=>{let n=structuredClone(ur);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,ur=n,vu(),c(e,null)},ya=e=>{wt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},ba=e=>{wt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&lr(n[o-1]);)o--;for(;o>0&&!lr(n[o-1]);)o--}else{for(;o<n.length&&!lr(n[o]);)o++;for(;o<n.length&&lr(n[o]);)o++}return{...t,cursorPosition:o}})},yu=()=>{wt(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}})},bu=()=>{wt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&lr(t[r-1]);)r--;for(;r>0&&!lr(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Ms=e=>{wt(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}})},xu=()=>{wt(e=>({...e,commandIsPending:!0}))},K=e=>{wt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Iu=({addToHistory:e=!0})=>{wt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Eu=()=>{wt(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}})},Ru=()=>{wt(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=()=>ur,ks=()=>{let[e,...t]=ur.value.split(va);return t.join(va).trim()}});var D,xn=y(()=>{"use strict";le();Sd();k();xe();Be();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 Su,F,xa=y(()=>{"use strict";k();_n();Su=e=>{let{context:t}=f().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 Nu}from"ink";import Cu,{useEffect as Au,useState as ny}from"react";var Tu,qe,mr=y(()=>{"use strict";k();Pe();Tu={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},qe=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Ve(),r=Tu[n]??Tu.default,[o,s]=ny(0);if(Au(()=>{s(0)},[r]),Au(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return Cu.createElement(Nu,null,t);let d=r[o]??r[0]??t;return Cu.createElement(Nu,{color:S.accent,dimColor:o===1},d)}});import{Box as Ia,Text as ry}from"ink";import Ls from"react";var oy,mn,po=y(()=>{"use strict";Pe();oy=(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}},mn=({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:g,end:I}=o?oy(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-g),A=e.slice(g,I),w=e.length>N,T=d,M=w?Math.max(1,Math.floor(N/e.length*T)):T,$=Math.max(0,T-M),O=Math.max(1,e.length-N),H=w?Math.floor(g/O*$):0;return Ls.createElement(Ia,{flexDirection:"row",height:d,width:"100%"},Ls.createElement(Ia,{flexDirection:"column",flexGrow:1,height:d},A),Ls.createElement(Ia,{flexDirection:"column",width:1,height:T},Array.from({length:T}).map((Q,Xt)=>Ls.createElement(ry,{key:Xt,color:w&&Xt>=H&&Xt<H+M?S.accent:S.secondary},w?"\u2502":" "))))}});var wu,Ea,sy,Ps,Ra=y(()=>{"use strict";k();sy=()=>{let{eventLog:e=[]}=f();if(Ea&&wu===e)return Ea;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return wu=e,Ea=t,t},Ps=e=>sy().has(e)});import{Text as iy}from"ink";import ay from"react";var dy,cy,pr,Ds=y(()=>{"use strict";hs();Tt();me();Ra();Jt();dy=e=>e.toLowerCase().trim(),cy=(e,t=ir)=>{let n=dy(e);return t[n]?t[n]:lo(n)},pr=({id:e,isSelected:t,maxWidth:n})=>{let r=x.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:In(o,n);return ay.createElement(iy,{underline:t,color:cy(o)},"@"+s,Ps(e)?"":"\u2197")}});import{Text as ly}from"ink";import uy from"react";var Fs,Sa=y(()=>{"use strict";me();Pe();Tt();Jt();Fs=({id:e,isSelected:t,maxWidth:n})=>{let r=x.getTag(e);if(!r)return;let o=n===void 0?r.name:In(r.name,n);return uy.createElement(ly,{underline:t,backgroundColor:De(r.name),color:S.secondary}," "+o+" ")}});import{useEffect as my,useState as py}from"react";var gy,Mu,Os,go,fy,hy,gr,Bs=y(()=>{"use strict";Tt();gy=80,Mu=1400,Os=new Set,go=null,fy=e=>(Os.add(e),go||(go=setInterval(()=>{for(let t of Os)t()},gy)),()=>{Os.delete(e),Os.size===0&&go&&(clearInterval(go),go=null)}),hy=()=>{let e=Date.now()%Mu/Mu;return e<.5?e*2:(1-e)*2},gr=e=>{let[,t]=py(0);return my(()=>{if(e)return fy(()=>t(n=>n+1))},[e]),eu(hy())}});import{Box as fr,Text as hr}from"ink";import Ke from"react";var vy,ku,yy,by,Pu,Du=y(()=>{"use strict";me();Pe();Jt();Ra();tn();no();Ds();Sa();Bs();vy=(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),In(e.slice(o).trim(),n)]},ku=3,yy=2,by=(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}},Pu=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=gr(r),s=e-4,d=s-7-1,[l,u]=vy(Me(t.title),d,s),m=u?null:In(Me(t.props.description),s)||null,p=dn(t),g=cn(t).map(M=>({...M,name:M.name})),I=Math.max(1,s-ku),N=x.getCommentsByIssue(t.id),A=N.length?String(N.length).length+2+1:0,{shown:w,hidden:T}=by([...p.map(M=>({id:M.id,isTag:!0,width:Math.min(M.name.length,I)+ku})),...g.map(M=>({id:M.id,isTag:!1,width:Math.min(M.name.length,I)+yy+(Ps(M.id)?0:1)}))],s-A);return Ke.createElement(fr,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?S.accent:S.secondary,justifyContent:"space-between"},Ke.createElement(fr,{paddingLeft:1,paddingRight:1,flexDirection:"column"},Ke.createElement(fr,{justifyContent:"space-between"},Ke.createElement(hr,{color:S.primary},l),Ke.createElement(hr,{color:S.secondary2,dimColor:!0},z(t.id))),u&&Ke.createElement(hr,{color:S.primary},u),m&&Ke.createElement(hr,{color:S.secondary2,dimColor:!0},m)),Ke.createElement(fr,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},Ke.createElement(fr,{flexDirection:"row"},w.map(M=>Ke.createElement(fr,{paddingRight:1,key:M.id},M.isTag?Ke.createElement(Fs,{id:M.id,maxWidth:I}):Ke.createElement(pr,{id:M.id,maxWidth:I}))),T>0&&Ke.createElement(hr,{color:S.secondary2,dimColor:!0},"+",T)),N.length>0&&Ke.createElement(hr,{color:S.accent},"[",N.length,"]")))}});import{Box as Wn,Text as fo}from"ink";import Ze from"react";var xy,Fu,Ou=y(()=>{"use strict";le();me();Pe();Tt();mr();Bs();xy=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,Fu=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:d})=>{let l=gr(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,g=u.length*(1+p),I=m.length*(2+p),N=u.map(Q=>Ze.createElement(Wn,{key:Q.id,paddingRight:p},Ze.createElement(fo,{color:De(Q.name)},"\u25A0"))),A=m.map(Q=>Ze.createElement(Wn,{key:Q.id,paddingRight:p},Ze.createElement(fo,{color:lo(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,$=T.length?Ze.createElement(Wn,{paddingRight:p},Ze.createElement(fo,{color:S.accent},"[",T.length,"]")):null,O=g+I+M,H=Math.max(1,n-t-O-(O>0?1:0));return Ze.createElement(Wn,{justifyContent:"space-between"},Ze.createElement(Wn,null,Ze.createElement(Wn,{width:t},o?Ze.createElement(qe,{isSelected:!0}):Ze.createElement(fo,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),Ze.createElement(fo,{wrap:"truncate",color:w},xy(r.title,H))),Ze.createElement(Wn,null,N,A,$))}});import Iy from"chalk";import{Box as Na,Text as Ey}from"ink";import Mt from"react";var Ry,Bu,_u=y(()=>{"use strict";ge();k();Pe();mr();po();Du();Ou();Bs();Ry=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u,replay:m}=Ve(),p=u[e.id]??[],g=m?new Set(m.flashNodeIds):null,I=g?.has(e.id)??!1,N=gr(I),A=`${e.title} ${Iy.hex(S.secondary2).dim("("+p.length+")")}`,w=3,T=o?1:5,M=s&&d===-1,$=n-3-(o?1:0)-(M?2:0),O=Math.max(2,String(p.length).length+1),H=r-w-1,Q=Mt.createElement(Na,{borderStyle:"round",borderColor:S.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},Mt.createElement(qe,{isSelected:t}),Mt.createElement(Ey,{bold:!0,color:I?N:t?S.accent:S.primary},A," ",e.readonly?"\u{1F512}":"")),Xt=(Pt,Xn)=>{let Ir=s&&d===Xn;if(!P(Pt))return null;let Er=g?.has(Pt.id)??!1;return o?Mt.createElement(Fu,{key:Pt.id,index:Xn,labelWidth:O,width:$,ticket:Pt,isSelected:Ir,isFlashing:Er,mode:l}):Mt.createElement(Pu,{key:Pt.id,width:$,ticket:Pt,isSelected:Ir,isFlashing:Er})};return Mt.createElement(Na,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?S.accent:S.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},Q,Mt.createElement(Na,null,p.length>0&&Mt.createElement(mn,{selectedIndex:d,height:H,itemHeight:T},p.map(Xt)),M&&Mt.createElement(qe,{isSelected:!0})))},Bu=Mt.memo(Ry)});var Uu,$u,Ca=y(()=>{"use strict";An();Uu=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},$u=(e,t,n)=>Ne.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0})});var vr,_s=y(()=>{"use strict";vr=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 yr,Text as qt}from"ink";import Fe,{useEffect as Sy,useMemo as Ny,useRef as Cy}from"react";import{decodeTime as ju}from"ulid";function Wu({ticket:e,width:t,height:n}){let r=Ny(()=>Ty(e),[e]),o=Cy([]);Sy(()=>(Hu(o.current),o.current=My(e,r),()=>{Hu(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Ve(),l=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?Fe.createElement(yr,{flexDirection:"column",width:t,height:n,padding:1},Fe.createElement(qt,{color:S.primary},"No attachments yet."),Fe.createElement(yr,{paddingTop:1},Fe.createElement(qt,{color:S.primary},"Attach images from the browser GUI"),Fe.createElement(qt,{color:S.accent}," epiq gui "),Fe.createElement(qt,{color:S.primary},"by dropping or pasting them."))):Fe.createElement(yr,{flexDirection:"column",width:t,height:n},Fe.createElement(yr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:S.secondary,borderStyle:"single",paddingBottom:1},Fe.createElement(qt,{color:S.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),Fe.createElement(mn,{height:l,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let g=p===s,I=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return Fe.createElement(yr,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},Fe.createElement(qt,{color:S.accent},g?"\u276F ":" "),Fe.createElement(yr,{paddingLeft:1},Fe.createElement(qt,{color:S.secondary2},`#${p+1} `),Fe.createElement(qt,{color:g?S.accent:S.primary},I),Fe.createElement(qt,{color:S.secondary2}," "+ky(m.bytes)+" "+vr(yt(m.id)))))})))}var Ay,Ty,Hu,wy,My,ky,Gu=y(()=>{"use strict";Je();dt();_s();ge();C();me();An();k();Pe();dr();po();Ay=e=>Ce(e,"attachments"),Ty=e=>x.getAttachmentsByIssue(e.id).sort((t,n)=>ju(t.id)-ju(n.id)),Hu=e=>{for(let t of e)x.deleteNode(t.id)},wy=(e,t,n)=>Ne.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),My=(e,t)=>{let n=x.getNode(Ay(e.id));if(!n||!Ye(n))return[];let r=t.map((o,s)=>wy(o,s,n.id)).map(o=>x.createNode(o)).filter(ht).map(({value:o})=>o).filter(Ye);return t.length>0&&f().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),r},ky=e=>`${Math.max(1,Math.round(e/1024))} KB`});var Vu,Aa,qu,Ta,Ku,zu,Ly,Yu,Py,wa,Xu=y(()=>{"use strict";Vu=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,Aa=e=>e.replace(Vu,""),qu=e=>e==="additions"||e==="deletions",Ta=e=>{let t=Vu.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"||!qu(r.side)||!qu(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r},Ku=/```\n([\s\S]*?)\n?```\s*$/,zu=e=>Ku.exec(e)?.[1]??null,Ly=/`[^`\n]+`[^\n]*\n?$/,Yu=e=>Aa(e).replace(Ku,"").replace(Ly,"").trim(),Py=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})`},wa=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${Py(e)}`});var Dy,ho,Fy,Oy,By,_y,Qu,Ma,Zu,Ju,em,ka=y(()=>{"use strict";Xu();Dy=(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},ho=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)},Fy=/!\[([^\]]*)\]\([^)]*\)/g,Oy=e=>e.replace(Fy,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),By=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),_y=4,Qu=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(_y)),Ma=e=>{let t=!1;return e.map(Qu).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=Ta(n);if(r)return{kind:"caption",text:wa(r)};let o=Oy(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:ho(s[1]??"")}:{kind:"text",spans:ho(o)}})},Zu=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Ju=(e,t)=>{let n=[];for(let r of Ma(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 Zu(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of Dy(By(r.spans),t))n.push({kind:r.kind,spans:ho(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},em=(e,t)=>{let n=Ta(e),r=n?zu(e):null;if(!n||r===null)return Ju(Aa(e).split(`
|
|
58
|
+
`),t);let o=Yu(e),s=r.split(`
|
|
59
|
+
`).map(Qu),d=n.side===n.endSide?n.start:void 0,l=d===void 0?0:String(d+s.length-1).length+3;return[...o?[...Ju(o.split(`
|
|
60
|
+
`),t),{kind:"blank"}]:[],{kind:"caption",text:wa(n)},...s.flatMap((u,m)=>Zu(u,Math.max(1,t-l)).map((p,g)=>({kind:"code",text:p,number:d===void 0||g>0?void 0:d+m})))]}});import{Box as tm,Text as Gn}from"ink";import it from"react";var nm,La,rm,Pa=y(()=>{"use strict";Pe();nm=({spans:e,bold:t,wrap:n})=>it.createElement(Gn,{color:S.primary,bold:t,wrap:n},e.map((r,o)=>r.code?it.createElement(Gn,{key:o,color:S.yellow},r.text):it.createElement(Gn,{key:o},r.text))),La=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return it.createElement(Gn,null," ");case"fence":return it.createElement(Gn,{color:S.secondary2},"```");case"caption":return it.createElement(Gn,{color:S.accent,wrap:r},e.text);case"heading":return it.createElement(nm,{spans:e.spans,bold:!0,wrap:r});case"text":return it.createElement(nm,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return it.createElement(Gn,{backgroundColor:S.secondary,color:S.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},rm=({lines:e,width:t})=>{let n=e.flatMap(o=>o.kind==="code"&&o.number!==void 0?[o.number]:[]),r=n.length>0?String(Math.max(...n)).length+3:0;return it.createElement(tm,{flexDirection:"column"},e.map((o,s)=>it.createElement(tm,{key:s},it.createElement(La,{line:o,width:t,gutter:r}))))}});import{Box as pn,Text as gn}from"ink";import Re,{useEffect as Uy,useMemo as om,useRef as $y}from"react";import{decodeTime as sm}from"ulid";function am({ticket:e,width:t,height:n}){let r=om(()=>Wy(e),[e]),o=$y([]);Uy(()=>(im(o.current),o.current=Gy(e,r),()=>{im(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Ve(),l=Math.max(1,n-4),u=Math.max(20,t-8),m=om(()=>r.map(g=>{let I=em(g.md,u);return I.length>0?I:[{kind:"blank"}]}),[r,u]),p=m.map(g=>g.length+jy);return r.length===0?Re.createElement(pn,{flexDirection:"column",width:t,height:n,padding:1},Re.createElement(gn,{color:S.primary},"No comments yet."),Re.createElement(pn,{paddingTop:1},Re.createElement(gn,{color:S.primary},"Use"),Re.createElement(gn,{color:S.accent}," :comment "),Re.createElement(gn,{color:S.primary},"to add the first one."))):Re.createElement(pn,{flexDirection:"column",width:t,height:n},Re.createElement(pn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:S.secondary,borderStyle:"single",paddingBottom:1},Re.createElement(gn,{color:S.secondary2},"Comments (",r.length,") ")),Re.createElement(mn,{height:l,itemHeights:p,selectedIndex:s},r.map((g,I)=>{let N=I===s;return Re.createElement(pn,{key:g.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:S.secondary,borderStyle:"single"},Re.createElement(pn,{flexDirection:"row",paddingBottom:1},Re.createElement(gn,{color:S.accent},N?"\u276F ":" "),Re.createElement(pn,{paddingLeft:1},Re.createElement(gn,{color:S.secondary2},`#${I+1} `),Re.createElement(pr,{id:g.authorId}),Re.createElement(gn,{color:S.secondary2}," "+vr(yt(g.id))))),Re.createElement(pn,{paddingLeft:3,paddingBottom:1},Re.createElement(rm,{lines:m[I]??[],width:u})))})))}var jy,Hy,Wy,im,Gy,dm=y(()=>{"use strict";Je();dt();_s();ge();C();me();k();Pe();dr();Ds();po();Ca();ka();Pa();jy=4,Hy=e=>Ce(e,"comments"),Wy=e=>x.getCommentsByIssue(e.id).sort((t,n)=>sm(t.id)-sm(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),im=e=>{for(let t of e)x.deleteNode(t.id)},Gy=(e,t)=>{let n=x.getNode(Hy(e.id));if(!n||!Ye(n))return[];let r=t.map((o,s)=>$u(o,s,n.id)).map(x.createNode).filter(ht).map(({value:o})=>o).filter(Tr);return t.length>0&&f().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),r}});import{Box as Us,Text as qy}from"ink";import Vt from"react";var cm,lm=y(()=>{"use strict";ge();me();tr();k();Pe();Ds();mr();Sa();cm=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Ve(),{title:o}=t,s=t.parentNodeId?x.getNode(t.parentNodeId):void 0,d=s&&P(s)?o===ie.ASSIGNEES?s.props.assignees??[]:o===ie.TAGS?(s.props.tags??[]).filter(l=>x.getTag(l)):[]:[];return Vt.createElement(Us,{alignItems:"center",paddingTop:1},Vt.createElement(Us,{minWidth:12},Vt.createElement(qe,{isSelected:n}),Vt.createElement(qy,{color:n?S.accent:S.secondary2},o,":")),Vt.createElement(Us,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=r.id===t.id&&u===e;return Vt.createElement(Us,{key:`${o}-${l}`,paddingRight:2,minHeight:1},Vt.createElement(qe,{isSelected:m}),o===ie.ASSIGNEES?Vt.createElement(pr,{isSelected:m,id:l}):o===ie.TAGS?Vt.createElement(Fs,{isSelected:m,id:l}):null)})))}});var Da,um,Fa,Oa=y(()=>{"use strict";Da=e=>Math.max(5,String(Math.max(e,1)).length+3),um=(e,t)=>Math.max(0,e-6-Da(t)),Fa=(e,t=0)=>Math.max(1,e-5-2*t)});import{Box as br,Text as Ba}from"ink";import at,{useEffect as Vy,useMemo as _a}from"react";var Ky,mm,Ua,pm,zy,$a,gm=y(()=>{"use strict";me();C();An();k();Pe();Jt();Oa();mr();po();Pa();ka();Zn();Ky="\u2029",mm=(e,t)=>`${e}::inline-line::${t}`,Ua=new Map,pm=e=>{let t=Ua.get(e)??[];Ua.delete(e);for(let n of t)x.deleteNode(n)},zy=(e,t)=>{pm(e);let n=[];t.forEach((r,o)=>{let s=tt(BigInt(o+1));if(!ht(s))return;let d=x.createNode(Ne.text({id:mm(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));ht(d)&&n.push(d.value.id)}),Ua.set(e,n)},$a=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:d,contextNode:l}=Ve(),u=_a(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=_a(()=>u.join("\0"),[u]);Vy(()=>(zy(e,u),()=>{pm(e)}),[e,m]);let p=Da(u.length),g=um(s,u.length),N=_a(()=>Ma(u).map(A=>{if(A.kind==="code"||A.kind==="caption")return{...A,text:ui(A.text,g)};if(A.kind==="text"||A.kind==="heading"){let w=A.spans.map(T=>T.code?`\`${T.text}\``:T.text).join("");return{...A,spans:ho(ui(w,g))}}return A}),[u,g]).map((A,w)=>{let T=l.id===e&&d===w;return at.createElement(br,{key:mm(e,w)},at.createElement(br,{flexShrink:0},at.createElement(Ba,{color:T?S.primary:S.secondary2,dimColor:!T},`${w+1} `.padStart(p,"\xA0"))),A.kind==="blank"?at.createElement(Ba,{backgroundColor:T?"gray":void 0},Ky):at.createElement(br,null,at.createElement(La,{line:A,width:A.kind==="code"?g:0,wrap:"truncate-end"})))});return at.createElement(br,{flexDirection:"column",paddingTop:1},at.createElement(br,null,at.createElement(qe,{isSelected:o}),at.createElement(Ba,{color:o?S.accent:S.secondary2},t)),at.createElement(br,{flexDirection:"row",borderStyle:"round",borderColor:S.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},at.createElement(mn,{scrollByOne:!0,height:r,selectedIndex:d,itemHeight:1},N)))}});import{Box as qn,Text as ja}from"ink";import we,{useMemo as vo}from"react";var Yy,Xy,Jy,Qy,fm,hm=y(()=>{"use strict";ge();me();k();Pe();Ca();dr();Gu();dm();mr();lm();gm();Oa();Yy=e=>Ce(e,"description"),Xy=e=>Ce(e,"comments"),Jy=e=>Ce(e,"history"),Qy=e=>Ce(e,"attachments"),fm=({ticket:e,height:t})=>{let n=vo(()=>Uu(e),[e]),{selectedIndex:r,contextNode:o}=Ve(),s=process.stdout.columns||120,d=vo(()=>Yy(e.id),[e.id]),l=vo(()=>Xy(e.id),[e.id]),u=vo(()=>Jy(e.id),[e.id]),m=vo(()=>Qy(e.id),[e.id]),p=x.getAttachmentsByIssue(e.id).length,g=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 H=t-3;return we.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},we.createElement(am,{ticket:e,width:s,height:H}))}if(A){let H=t-3;return we.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},we.createElement(Wu,{ticket:e,width:s,height:H}))}if(N){let O=x.getNode(u),H=O&&Ye(O)?O.props.value??"":"",Q=Fa(t);return we.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},O?we.createElement($a,{id:O.id,label:"Event log",text:H,selected:!1,maxWidth:s,rows:Q}):null)}let T=w.reduce((O,H)=>Ar(H)||H.id===l||H.id===m||H.id===u?O+1:O,0),M=Fa(t,T),$=(O,H)=>O.id===d?we.createElement($a,{key:O.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:H,maxWidth:s,rows:M}):Ar(O)?we.createElement(cm,{key:O.id,parent:O,selected:H,selectedIndex:r}):O.id===l?we.createElement(qn,{key:O.id,paddingTop:1},we.createElement(qe,{isSelected:H}),we.createElement(ja,{backgroundColor:S.secondary,color:H?S.accent:S.primary},` Comments (${n}) \u203A\u203A `)):O.id===m?we.createElement(qn,{key:O.id,paddingTop:1},we.createElement(qe,{isSelected:H}),we.createElement(ja,{backgroundColor:S.secondary,color:H?S.accent:S.primary},` Attachments (${p}) \u203A\u203A `)):O.id===u?we.createElement(qn,{key:O.id,paddingTop:1},we.createElement(qe,{isSelected:H}),we.createElement(ja,{backgroundColor:S.secondary,color:H?S.accent:S.primary}," History \u203A\u203A ")):null;return we.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},w.map((O,H)=>$(O,g&&r===H)))}});import{Box as Zy}from"ink";import $s from"react";var eb,vm,ym=y(()=>{"use strict";ge();_u();hm();eb=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:d,width:l})=>{let u=t.context,m=u===_.TICKET||u===_.FIELD_LIST||u===_.FIELD,p=u===_.BOARD||u===_.SWIMLANE,g=u===_.TICKET?t:r.find(T=>T.context===_.TICKET),I=Math.floor(l/3),N=Math.floor(l/Math.max(e.length,1)),A=Math.min(N,I),w=s==="dense";return $s.createElement(Zy,{flexDirection:"row",height:d},p&&e.map((T,M)=>{let $=t.id===T.id,O=$?n:-1,H=t.context===_.BOARD&&n===M;return $s.createElement(Bu,{key:T.id,height:d,width:A,swimlane:T,isSelected:H,isDense:w,isFocused:$,listSelectedIndex:O,mode:o})}),m&&g&&$s.createElement(fm,{height:d,ticket:g}))},vm=$s.memo(eb)});import bm from"node:fs";import tb from"node:path";import nb from"react";import{render as rb}from"ink";import{Writable as ob}from"node:stream";var yo,sb,ib,ab,db,xm,Im=y(()=>{"use strict";ym();ge();C();k();re();Be();yo=e=>String(e).padStart(2,"0"),sb=e=>{let t=e.getUTCFullYear(),n=yo(e.getUTCMonth()+1),r=yo(e.getUTCDate()),o=yo(e.getUTCHours()),s=yo(e.getUTCMinutes()),d=yo(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${d}`},ib=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",ab=async(e,{width:t,height:n})=>{let r="",o=new ob({write(d,l,u){let m=db(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=rb(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),r},db=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),xm=async()=>{let{viewMode:e}=ve(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=f(),d=r.find(M=>M.context==="BOARD");if(!d)return i("No board found to export");let l=120,u=40,m=await ab(nb.createElement(vm,{height:u,width:l,swimlanes:(s[d.id]??[]).filter(M=>M!==void 0&&bn(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=Vo(process.cwd());if(a(p))return i("Unable to export, epiq root not found");let g=new Date,I=sb(g),N=`board_${ib(d.title)}_${I}.md`,A=nc(p.value);bm.mkdirSync(A,{recursive:!0});let w=tb.join(A,N),T=`# Board - ${d.title}
|
|
61
|
+
Date: ${g.toISOString()}
|
|
58
62
|
|
|
59
63
|
\`\`\`text
|
|
60
64
|
${m}
|
|
61
65
|
\`\`\`
|
|
62
|
-
`;return
|
|
66
|
+
`;return bm.writeFileSync(w,T,"utf8"),c("Exported board layout",w)}});var js,Ha=y(()=>{"use strict";js=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 Hk}from"react";var Wa,cb,lb,xr,ub,fn,Hs=y(()=>{"use strict";C();cb=new Set,lb=()=>{for(let e of cb)e()},xr=()=>{if(!Wa)throw new Error("Ui state not initialized. Call initUiState() first.");return Wa},ub=e=>{let t=xr();return Wa=e(t),lb(),c("UX state updated",null)},fn=e=>ub(t=>({...t,...e}))});import{spawn as mb}from"node:child_process";function bo(e){let t=process.platform,o=mb(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 Ga=y(()=>{"use strict"});import{spawn as Yk,spawnSync as pb}from"node:child_process";import gb from"node:os";import Em from"node:path";import{ulid as fb}from"ulid";function Rm(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 hb(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Sm(){let{preferredEditor:e}=ve(),t=[e?hb(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Nm(e){let[t=""]=Rm(e);return/(^|\/)code(-insiders)?$/.test(t)}function vb(e,t){let[n="",...r]=Rm(e);return{command:n,args:[...r,...t]}}function yb(e,t){return vb(e,Nm(e)?["--wait",t]:[t])}function Cm(e){let t=Em.join(gb.tmpdir(),"epiq");We.mkDir(t);let n=Em.join(t,fb());We.writeToFile(n,e??"");let r=Sm();for(let o of r){let{command:s,args:d}=yb(o,n);if(!s)continue;let l=pb(s,d,{stdio:"inherit"});if(!l.error&&l.status===0){let u=We.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 qa=y(()=>{"use strict";C();Be();Rs()});import{ulid as Va}from"ulid";var Am,bb,xb,Tm=y(()=>{"use strict";qa();Dn();gt();bt();ge();C();tr();me();k();re();ln();Am=async e=>{let{contextNode:t,selectedIndex:n}=f(),r=ae(t.id)[n];if(e.modifier===Qe.DESCRIPTION)return xb();if(r&&Tr(r))return bb(e);if(e.modifier===Qe.TITLE){let o=fe();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 St();return a(l)?l:B([{id:Va(),action:"edit.title",payload:{id:s.id,name:d},...o.value}],l.value)}return i("Unknown edit command")},bb=async e=>{let t=fe();if(a(t))return i("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=f(),o=ae(n.id)[r];if(!o||!Tr(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=f().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 St();if(a(p))return p;let g=p.value;return B([{id:Va(),action:"edit.issue.comment",payload:{id:u.id,issue:d.id,md:m},...t.value}],g)},xb=async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let t=await St();if(a(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=f(),s=ze([...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(g=>g.title===ie.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=Cm(u);if(a(m))return i("Failed to edit field");let p=m.value;return p===u?c("No changes made",null):B([{id:Va(),action:"edit.description",payload:{id:d.id,md:p},...e.value}],n)}});import Ka from"node:fs";import Ib from"node:path";var wm,Mm=y(()=>{"use strict";C();Et();wm=async e=>{let t=Ib.join(e,".gitignore"),n=Ka.existsSync(t)?Ka.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
|
+
`,Ka.writeFileSync(t,n,"utf8"),X.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)}});import Eb from"node:fs";import km from"node:path";var Rb,oe,Lm,Pm=y(()=>{"use strict";Mm();Uo();mt();lt();Xr();Je();to();qr();_t();gt();le();C();Ot();xe();Be();k();re();Rb=async e=>{let t=await G({cwd:e,args:["status","--porcelain"]});return a(t)?t:c("Checked git diff",t.value.stdout.trim().length>0)},oe=(e,t)=>i(`[${e}] ${t}`),Lm=async()=>{K("");let e=Oo(),t=await ut(process.cwd());if(a(t))return oe(1,t.message);let n=t.value,r=await $o(n);if(a(r))return oe(2,r.message);if(r.value)return oe(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await Rb(n);if(a(o))return oe(2.5,o.message);if(o.value)return oe(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(Or(n))return oe(4,"Epiq project already initialized");let s=fs();if(!s.isSetupDone||!s.userName)return oe(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let d=ve(),l=d.userName,u=d.userId;if(!u||!l)return oe(5,"Missing Epiq user id");let m=await sl(n);if(a(m))return oe(6,m.message);let p=e.stateBranch,g=await jo({repoRoot:n,branch:p});if(a(g))return oe(6,g.message);if(g.value)return oe(6,`State branch already exists: ${p}`);let I=await qi({repoRoot:n,stateBranchName:p});if(a(I))return oe(6,I.message);let N=Go();if(a(N))return oe(7,N.message);let A=km.join(Wo(),e.projectId),w=await Bn({repoRoot:n,stateBranchRoot:A,stateBranchName:p});if(a(w))return oe(8,w.message);let T=km.join(A,".epiq");Eb.mkdirSync(T,{recursive:!0});let M=Yc({userId:u,userName:l});if(a(M))return oe(9,M.message);for(let oi of M.value){let fd=es({event:oi,rootDir:A});if(a(fd))return oe(9,fd.message)}let $=await ds({stateBranchRoot:A,eventFileName:Pn({userId:u,userName:l})});if(a($))return oe(10,$.message);let O=await er({cwd:A,message:"[epiq:init]"});if(a(O))return oe(10,O.message);let H=await wm(n);if(a(H))return oe(11,H.message);let Q=Bd({repoRoot:n,fileContents:e});if(a(Q))return oe(12,Q.message);let Xt=await he.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(Xt))return oe(13,Xt.message);let Pt=await he.commit({cwd:n,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(a(Pt))return oe(13,Pt.message);let Xn="Project initialized!",Ir=await G({cwd:n,args:["push","-u","origin","HEAD"]});a(Ir)&&(Xn+=` Warn: [init:14] ${Ir.message}`);let Er=await Yr({repoRoot:n,stateBranchRoot:A});a(Er)&&(Xn+=` Warn: [init:15] ${Er.message}`);let pd=Bt(M.value).filter(a);if(pd.length>0)return oe(16,pd.map(oi=>oi.message).join(`
|
|
72
|
+
`));let ri=He();if(a(ri))return oe(16,ri.message);let{rootNodeId:_g,nodes:Ug}=ri.value,gd=Ug[_g];return gd?(U.navigate({contextNode:gd,selectedIndex:0}),E({hasProjectDefinition:!0,mode:h.DEFAULT}),c(Xn,null)):oe(16,"Unable to resolve initialized root node")}});import{ulid as Sb}from"ulid";function Ya(e){let t=Fm();if(a(t))return t;let{contextNode:n,nodes:r}=f();if(!n.parentNodeId)return i("Missing parent node id");let o=r[n.parentNodeId];if(!o)return i("Missing parent node");let s=ue(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=Om({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Bm(u.value)}function Xa(e){let t=Fm();if(a(t))return t;let{contextNode:n,selectedIndex:r}=f(),s=ue(n.id)[r+e];if(!s)return i("Missing sibling node");let d=Om({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:Bm(d.value)}var Dm,hn,xo,Fm,za,Om,Bm,Ja=y(()=>{"use strict";_t();gt();C();It();k();Dm=null,hn=()=>structuredClone(Dm),xo=e=>{Dm=e},Fm=()=>{let{contextNode:e,selectedIndex:t}=f(),r=ue(e.id)[t];return r?c("Resolved selected child",r):i("Target node not found")},za=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ue(t).filter(o=>o.id!==e);return ts(r,n)},Om=({id:e,parentId:t,position:n={at:"end"}})=>{let r=fe();if(a(r))return i("Unable to resolve user ID");let o=za({parentId:t,id:e,position:n});return a(o)?o:c("Created pending move state",{id:Sb(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Bm=e=>{xo(e);let t=nn(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as Nb}from"ulid";var _m,Ws,Um,$m=y(()=>{"use strict";Je();Ja();Dn();gt();le();C();It();xe();k();re();_m=()=>{let e=hn();if(!e)return i("No pending move state");let t=e.payload.id,n=e.payload.parent,r=f().nodes[n];if(!r)return i("Move parent not found");let o=ue(n).findIndex(s=>s.id===t);return o===-1?i("Moved node not found among rendered children"):(U.navigate({contextNode:r,selectedIndex:o}),c("Synchronized navigation to moved node",null))},Ws=(e,t="Moved preview")=>{if(a(e))return e;let n=_m();return a(n)?n:(E({mode:h.MOVE}),c(t,null))},Um=async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=de().commandMeta,{contextNode:n,selectedIndex:r}=f(),o=ue(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=ue(o.parentNodeId),d=s.findIndex(({id:g})=>g===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=za({parentId:o.parentNodeId,id:o.id,position:m});return a(p)?p:(xo({id:Nb(),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 Ws(Xa(1));if(t==="previous")return Ws(Xa(-1));if(t==="to-next")return Ws(Ya(1));if(t==="to-previous")return Ws(Ya(-1));if(t==="confirm"){let s=hn();if(!s)return i("No pending move to confirm");let d=await St();if(a(d))return d;let l=B([s],d.value);if(a(l))return l;let u=_m();return a(u)?u:(xo(null),E({mode:h.DEFAULT}),c("Moved item",null))}return t==="cancel"?(xo(null),E({mode:h.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as Cb,ulid as Ab}from"ulid";var Tb,Gs,Qa=y(()=>{"use strict";C();Tb=Cb(),Gs=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=Tb();return c("Created issue events",[{id:Ab(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as qs}from"ulid";var jm,Hm=y(()=>{"use strict";Je();Qa();Dn();gt();bt();C();me();It();k();re();jm=async(e,t)=>{let n=fe();if(a(n))return i("Unable to resolve user ID");let r=await St();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}=f(),u=m=>{let p=B([m],o);if(a(p))return p;let g=x.getNode(p.value[0].result.id);if(!g)return i("Created node not found");if(!g.parentNodeId)return p;let I=x.getNode(g.parentNodeId);return I?(U.navigate({contextNode:I,selectedIndex:x.getSiblings(g.parentNodeId).findIndex(({id:N})=>N===g.id)}),p):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=f(),p=x.getNode(m);if(!p)return i("Workspace not found");let g=On(p.id,n.value,o);return a(g)?g:u({id:qs(),action:"add.board",payload:{id:qs(),name:t.inputString,parent:p.id,rank:g.value},...n.value})}if(t.modifier==="swimlane"){let m=ze(s,"BOARD");if(a(m))return i("Unable to add swimlane in this context");let p=On(m.value.id,n.value,o);return a(p)?p:u({id:qs(),action:"add.swimlane",payload:{id:qs(),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 $=ze(s,"SWIMLANE");return a($)?null:$.value})();if(!p)return i("Unable to add issue in this context");let g=On(p.id,n.value,o);if(a(g))return g;let I=Gs({name:t.inputString,parent:p.id,rank:g.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($=>$.action==="add.issue")?.payload.id;return M?(U.navigate({contextNode:p,selectedIndex:x.getSiblings(p.id).findIndex(({id:$})=>$===M)}),c("Issue created",null)):i("Unable to determine ticket id")}return c("Success",null)}});var Wm,Gm=y(()=>{"use strict";mt();lt();Xr();eo();qr();jt();C();Ot();k();as();Wm=async e=>{let t=Se({repoRoot:e});if(a(t))return Vr(3,t.message);let n=await Bn({repoRoot:e,stateBranchRoot:t.value,stateBranchName:Oo().stateBranch});if(a(n))return Vr(3,n.message);let r=await G({cwd:t.value,args:["pull","--ff-only"]});a(r)&&logger.info(3,r.message);let o=$t(t.value);if(a(o))return Vr(3,o.message);let{events:s,unreadable:d}=o.value,l=an(s,d);if(a(l))return Vr(4,l.message);E({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let u=ea({root:e});return a(u)&&logger.info(u.message),c("Loaded project",void 0)}});import wb from"node:os";import qm from"node:path";var Mb,kb,Vm,Km=y(()=>{"use strict";Gm();eo();C();xe();k();re();Mb=e=>e==="~"||e.startsWith("~/")?qm.join(wb.homedir(),e.slice(1)):e,kb=(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(qm.resolve(Mb(n)));return a(r)?i(`No epiq project at ${n}`):c("Resolved project path",r.value)},Vm=async()=>{let e=ks();if(K(""),f().hasProjectDefinition)return i("Already in a project; run epiq from another directory");let t=gs({exclude:process.cwd()}),n=a(t)?[]:t.value,r=kb(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 Wm(o);return a(d)?(process.chdir(s),i(d.message)):c(`Opened ${Sl(o)}`,null)}});var Vs,Za=y(()=>{"use strict";Je();jt();_t();C();k();Vs=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=f(),s=_i(n,t);if(a(s))return i(s.message);let{appliedEvents:d,unappliedEvents:l}=s.value,u=Kt();if(a(u))return u;let m=Bt(d),{fatal:p,skipped:g}=Tn(m);if(p.length>0)return Kt(),E(o),i(p.map(N=>N.message).join(", "));wn(g);let I=f().nodes[e];return I?(U.navigate({contextNode:I,selectedIndex:r}),c("",{unappliedEvents:l})):(Kt(),E(o),i("Board did not exist at that date"))}});var zm,Ym=y(()=>{"use strict";zm=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)}});var Lb,Pb,Db,Ks,zs,Vn,Xm,Jm,ed=y(()=>{"use strict";dt();Io();_t();le();C();Ym();k();Lb=20,Pb=16,Db=150,Ks=null,zs=null,Vn=()=>{Ks!==null&&(clearInterval(Ks),Ks=null),zs!==null&&(clearTimeout(zs),zs=null)},Xm=()=>{Vn(),E({mode:h.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Jm=({events:e,startTime:t,durationMs:n})=>{Vn();let r=e.length,o=Nr(e.map(g=>Cr(g))).map(g=>g??t),s=o[r-1]??Date.now(),d=zm(o),l=Math.max(1,Math.round(n*Lb/1e3)),u=Math.max(Math.round(n/l),Pb),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:[]}}),Ks=setInterval(()=>{m++;let g=m/l,I=[],N,A;for(;p<r&&d[p]<=g;){let T=e[p],M=nn(T);if(a(M)){if($r(M)){p++;continue}Xm();return}I.push(...Ti(T)),N=T,A=o[p],p++}if(p>=r||m>=l){for(;p<r;p++){let M=nn(e[p]);if(a(M)&&!$r(M))break}let T=f().replay;E({unappliedEvents:[],replay:T&&{...T,progress:1,appliedCount:r}}),Vn(),zs=setTimeout(Xm,Db);return}let w=f().replay;E({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,g),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:N?A??w?.currentTime??t:w?.currentTime??t,currentLabel:N?td(N):w?.currentLabel??"",flashNodeIds:N?[...new Set(I)]:w?.flashNodeIds??[]}})},u)}});var Qm,Zm=y(()=>{"use strict";mt();dt();jt();_t();le();bt();C();xe();k();ro();Za();ed();Qm=async()=>{let e=ze(f().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=Se({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=de().commandMeta;if(Vn(),r==="now"){let l=kn(n.value);if(a(l))return i(l.message);let u=Kt();if(a(u))return u;let m=Bt(l.value),{fatal:p,skipped:g}=Tn(m);return p.length>0?i(p.map(I=>I.message).join(", ")):(wn(g),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=Ui(n.value);if(a(l))return l;let u=r==="prev"?f().eventLog.at(-1):f().unappliedEvents.at(0),m=u===void 0?null:Cr(u),p=(u===void 0?null:l.value.get(u.id)??null)??(m===null?null:di(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=Un(r||o.trim());if(!l)return i("Invalid peek date");s=l.getTime()}let d=Vs({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 ep,tp=y(()=>{"use strict";mt();bt();C();xe();k();ro();Za();ed();ep=async()=>{let e=ze(f().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=Se({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=de().commandMeta,{dateInput:s,durationInput:d}=xs(r,o);if(Vn(),f().syncStatus.status==="syncing")return i("Cannot replay while syncing, try again in a moment");let l=Un(s);if(!l)return i("Invalid replay date");let u=d?bs(d):15e3;if(u===null)return i("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=f(),g=Vs({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(g))return g;let{unappliedEvents:I}=g.value;return I.length===0?(Kt(),E(p),c("Nothing to replay from that point",!0)):(Jm({events:I,startTime:m,durationMs:u}),c("Replaying board history",!0))}});import Ob from"zod";var np,rp=y(()=>{"use strict";jn();le();C();xe();Be();k();np=()=>{let e=de().commandMeta.inputString,t=Ob.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=st({autoSyncDebounceMs:t.data});return a(n)?n:(et({autoSyncIntervalMs:t.data}),E({mode:h.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))}});var op,sp=y(()=>{"use strict";to();jn();le();C();xe();Be();k();op=()=>{let e=de().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=Ml(e),n=st({autoSync:t});return a(n)?n:(et({autoSync:t}),E({mode:h.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var ip,ap=y(()=>{"use strict";jn();le();C();xe();Be();k();ip=()=>{let e=de().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return i("Invalid response");let n=st({logLevel:e});return a(n)?n:(et({logLevel:e}),E({mode:h.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});import{spawn as Bb}from"node:child_process";var _b,dp,cp=y(()=>{"use strict";C();_b=()=>{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"]}}},dp=async e=>new Promise(t=>{let{command:n,args:r}=_b();try{let o=Bb(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 Eo,lp,up=y(()=>{"use strict";C();k();cp();tn();no();ln();Eo=async(e,t)=>{if(!e.trim())return i(`Nothing to copy: ${t} is empty`);let n=await dp(e);return a(n)?n:c(`Copied ${t} to clipboard`,null)},lp=async e=>{let{breadCrumb:t,selectedNode:n}=f(),r=oo({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return i("Nothing selected to copy from");switch(e.modifier){case Ee.REF:return Eo(z(o.id),"ref");case Ee.TITLE:return Eo(o.title,"title");case Ee.DESCRIPTION:return r?Eo(r.props?.description??"","description"):i("No issue in scope");case Ee.TAGS:{if(!r)return i("No issue in scope");let s=dn(r).map(({name:d})=>d);return Eo(s.join(", "),"tags")}case Ee.ASSIGNEES:{if(!r)return i("No issue in scope");let s=cn(r).map(({name:d})=>d);return Eo(s.join(", "),"assignees")}default:return i("Yank one of: ref, title, description, tags, assignees")}}});var mp,pp=y(()=>{"use strict";Xi();le();C();xe();k();mp=async()=>{K(""),E({mode:h.DEFAULT});let e=He();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 us();return a(t)?(E({syncStatus:{msg:t.message,status:"failed"}}),t):(E({mode:h.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as Oe}from"ulid";var Ub,gp,zt,fp,hp=y(()=>{"use strict";me();Im();Je();Qn();jn();Dn();gt();Ha();nr();le();bt();ge();C();me();It();xe();Be();k();Hs();re();Ga();_n();xa();ln();uo();Tm();Pm();$m();Hm();Km();Zm();tp();rp();ma();sp();ap();up();pp();Ub=e=>e.action==="add.issue.comment",gp=()=>{let{eventLog:e=[],contributors:t}=f(),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 St();return a(e)?e:c("Resolved persist root",e.value)},fp=[{systemOnly:!0,intent:F.Move,description:"Internal move-state command",mode:h.COMMAND_LINE,action:Um},{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}=f(),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=f().nodes[d];if(!l||!P(l))return i("Unable to resolve comment issue");let u=l.log?.filter(Ub).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):B([{id:Oe(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],o.value):i("Unable to resolve comment")}return B([{id:Oe(),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=>be(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}=f();return fn({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}=f(),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=f().nodes[ye];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=sn(o.id,r.id,{at:"end"},e.value,d);if(a(l))return l;let u=B([{id:Oe(),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}=f(),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):Kn(r.id,"TICKET");if(a(o))return i("Cannot reopen in this context");let s=o.value,d=f().nodes[ye];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=js(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=f().nodes[l];if(!u)return i("Previous parent no longer exists");let m=await zt();if(a(m))return m;let p=m.value,g=sn(u.id,s.id,{at:"end"},e.value,p);if(a(g))return g;let I=B([{id:Oe(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:g.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:Lm},{intent:F.OpenProject,description:"Open a recently used epiq project, by number or path",mode:h.COMMAND_LINE,action:Vm,onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.NewItem,description:"Create a new board, swimlane, or issue",mode:h.COMMAND_LINE,action:jm,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}=f(),r=ae(t.id)[n];if(!r)return i("Missing node");if(r.readonly)return i("Cannot rename readonly node");let o=ks();if(!o)return i("Provide a title");let s=await zt();return a(s)?s:B([{id:Oe(),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}=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}=f();if(!s)return i("Invalid untag target");let d=Kn(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:B([{id:Oe(),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}=de().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let{selectedNode:o}=f();if(!o)return i("Invalid tag target");let s=Kn(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??Oe();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):B([...u?[]:[{id:Oe(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:Oe(),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}=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}=f(),u=ae(l.id)[d];if(!u)return i("Invalid assign target");let m=Kn(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 g=await zt();if(a(g))return g;let I=gp(),N=!o&&s.toLowerCase()==="me",A,w;if(N)A=e.value.userId,w=I.find($=>$.id===A)?.name??e.value.userName;else{let $=I.filter(H=>H.name===s);if($.length>1)return i(`"${s}" matches ${$.length} contributors (${$.map(H=>H.id).join(", ")}). Assign from the GUI to choose by id.`);let O=$[0];if(!O&&!o)return i(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);A=O?.id??Oe(),w=O?.name??s}if((p.props.assignees??[]).includes(A))return i("Assignee already assigned");let M=!!f().contributors[A];return B([...M?[]:[{id:Oe(),action:"create.contributor",payload:{id:A,name:w},...e.value}],{id:Oe(),action:"add.issue.assignee",payload:{id:p.id,assignee:A},...e.value}],g.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}=de().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee to remove");let{selectedNode:o}=f();if(!o)return i("Invalid unassign target");let s=Kn(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):gp().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 g=await zt();return a(g)?g:B([{id:Oe(),action:"remove.issue.assignee",payload:{id:d.id,assignee:p},...e.value}],g.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}=f(),d=ze([...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):Kn(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:B([{id:Oe(),action:"add.issue.comment",payload:{id:Oe(),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:mp},{intent:F.Peek,description:"View board state at another point in time",mode:h.COMMAND_LINE,action:Qm},{intent:F.Replay,description:"Replay board history forward from a point in time",mode:h.COMMAND_LINE,action:ep},{intent:F.Export,description:"Export the current board layout to markdown",mode:h.COMMAND_LINE,action:async()=>{let e=await xm();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()=>(U.exit(),c("Exit successful",!0))},{intent:F.Edit,description:"Edit title or description",mode:h.COMMAND_LINE,action:async(e,t)=>Am(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)=>lp(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[vt])return i(`Cannot change the configured user while ${vt} names this process`);let r=Ss();if(a(r))return r;let{userId:o,preferredEditor:s,userName:d}=r.value,l=n||d,u=o||Oe();if(!l||!u)return i("Unable to resolve user name or id");let m=st({userName:l,userId:u,preferredEditor:s??""});return a(m)?m:(et({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=st({preferredEditor:n});return a(r)?r:(et({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=st({viewMode:n});return a(r)?r:(et({viewMode:n}),E({mode:h.DEFAULT}),c(`View set to "${n}"`,null))}case pe.AUTOSYNC:return op();case pe.LOG_LEVEL:return ip();case pe.SYNC_DEBOUNCE_MS:return np();case pe.ATTACHMENT_MAX_KB:return zl();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"?bo("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):bo(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),K(""),c("Thanks you!",null)}}]});var $b,kt,nd=y(()=>{"use strict";ms();As();xa();hp();C();xe();Be();k();$b=new Set(["peek","replay","filter","view-help","yank"]),kt=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===un.Invalid)return i("Invalid command");let s=Su(t);xu();let{readOnly:d}=f();if(d&&!$b.has(s))return mo({status:Dt.Fail,message:"Command not available in readonly state",value:null});let l=fp.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return mo({status:Dt.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return mo({status:Dt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?mo(u):(Iu({addToHistory:!e}),l.onSuccess?.(),ve().autoSync&&Il(),u)}});var Ys,Xs,vp,yp=y(()=>{"use strict";C();le();k();xn();nd();Ja();xe();Ys=[{intent:D.Exit,mode:h.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:h.COMMAND_LINE}),K("move cancel"),kt({isForceExecutedBySystem:!0}))},{intent:D.InitMove,mode:h.DEFAULT,description:"[m] move (init/confirm)",action:()=>(E({mode:h.COMMAND_LINE}),K("move start"),kt({isForceExecutedBySystem:!0}))},{intent:D.ConfirmMove,mode:h.MOVE,action:()=>(E({mode:h.COMMAND_LINE}),K("move confirm"),kt({isForceExecutedBySystem:!0}))}],Xs=[{intent:D.MovePreviousItem,mode:h.MOVE,action:()=>hn()?(E({mode:h.COMMAND_LINE}),K("move previous"),kt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:D.MoveNextItem,mode:h.MOVE,action:()=>hn()?(E({mode:h.COMMAND_LINE}),K("move next"),kt({isForceExecutedBySystem:!0})):i("No pending move")}],vp=[{intent:D.MoveToNextContainer,mode:h.MOVE,action:()=>hn()?(E({mode:h.COMMAND_LINE}),K("move to-next"),kt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:D.MoveToPreviousContainer,mode:h.MOVE,action:()=>hn()?(E({mode:h.COMMAND_LINE}),K("move to-previous"),kt({isForceExecutedBySystem:!0})):i("No pending move")}]});var bp,xp=y(()=>{"use strict";ge();yp();bp={[_.WORKSPACE]:[...Ys,...Xs],[_.BOARD]:[...Ys,...Xs],[_.SWIMLANE]:[...Ys,...Xs,...vp],[_.TICKET]:[],[_.FIELD]:[],[_.FIELD_LIST]:[],[_.TEXT]:[],[_.COMMENT]:[]}});import jb from"node:fs";import Hb from"node:path";var Ip,Ep=y(()=>{"use strict";mt();io();C();re();Ga();Ip=e=>{let t=Xe(process.cwd());if(a(t))return i("Unable to resolve project root");let n=Se({repoRoot:t.value});if(a(n))return i(n.message);let r=so(e.hash,e.ext),o=Hb.join(qo(n.value),r);return jb.existsSync(o)?(bo(o),c(`Opened ${e.name}`,null)):i("Attachment file not found \u2014 run :sync to fetch it")}});var Rp,Sp,Np=y(()=>{"use strict";le();C();xe();k();Hs();xn();Je();Rp=()=>{K("");let{pendingNavTarget:e}=xr();E({mode:h.DEFAULT}),e&&U.navigate(e),fn({pendingNavTarget:void 0})},Sp=[{intent:D.ExitCommandLine,mode:h.HELP,action:()=>(Rp(),c("Exiting help",null))},{intent:D.Exit,mode:h.HELP,action:()=>(Rp(),c("Closed help",null))},{intent:D.NavPreviousItem,mode:h.HELP,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:D.NavNextItem,mode:h.HELP,action:()=>(U.navigateToNextItem(),c("Navigating to next help item",null))},{intent:D.NavToPreviousContainer,mode:h.HELP,action:()=>(U.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:D.NavToNextContainer,mode:h.HELP,action:()=>(U.navigateToNextContainer(),c("Navigating to next help container",null))}]});var Wb,Cp,Ap,Tp=y(()=>{"use strict";le();ge();C();xe();k();Hs();xn();Je();Wb=e=>{E({mode:h.COMMAND_LINE});let{pendingNavTarget:t}=xr();t&&U.navigate(t),fn({pendingNavTarget:void 0}),K(`${e} `)},Cp=()=>{K("");let{pendingNavTarget:e}=xr();e&&U.navigate(e),fn({pendingNavTarget:void 0}),E({mode:h.DEFAULT})},Ap=[{intent:D.InitCommandPalette,mode:h.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{K("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=f();return fn({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}=f();if(!e||!Rd(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?(Wb(t),c("Selected command",t)):c("No command selected",null)}},{intent:D.ExitCommandLine,mode:h.PALETTE,action:()=>(Cp(),c("Exiting palette",null))},{intent:D.Exit,mode:h.PALETTE,action:()=>(Cp(),c("Closed command palette",null))},{intent:D.NavPreviousItem,mode:h.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:D.NavNextItem,mode:h.PALETTE,action:()=>(U.navigateToNextItem(),c("Navigating to next item",null))},{intent:D.NavToPreviousContainer,mode:h.PALETTE,action:()=>(U.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:D.NavToNextContainer,mode:h.PALETTE,action:()=>(U.navigateToNextContainer(),c("Navigating to next container",null))}]});var wp,Mp=y(()=>{"use strict";_n();ln();le();C();tr();me();It();xe();k();Ep();xn();Np();Tp();Je();wp=[...Sp,...Ap,{intent:D.AddItem,mode:h.DEFAULT,description:"[n] new...",action:()=>(E({mode:h.COMMAND_LINE}),K(`${v.NEW} `),c("Adding new item",null))},{intent:D.Delete,mode:h.DEFAULT,description:"[d] delete",action:()=>(E({mode:h.COMMAND_LINE}),K(`${v.DELETE} `),c("Deleting item",null))},{intent:D.InitCommandLine,mode:h.DEFAULT,description:"[:] focus command line",action:()=>(E({mode:h.COMMAND_LINE}),K(""),c("Entering command line mode",null))},{intent:D.Confirm,mode:h.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=f();if(!ue(e?.id??"")?.length){let r=e?x.getAttachment(e.id):void 0;if(r)return Ip(r);if(e?.title===ie.DESCRIPTION)return E({mode:h.COMMAND_LINE}),K(`${v.EDIT} description `),c("Propose command",!0);if(e?.title===ie.ASSIGNEES)return E({mode:h.COMMAND_LINE}),K(`${v.ASSIGN} `),c("Propose command",!0);if(e?.title===ie.TAGS)return E({mode:h.COMMAND_LINE}),K(`${v.TAG} `),c("Propose command",!0);if(t.title===ie.DESCRIPTION&&e?.context==="TEXT")return E({mode:h.COMMAND_LINE}),K(`${v.EDIT} description `),c("Propose command",!0)}return U.enterChildNode(),c("Entering context",null)}},{intent:D.Yank,mode:h.DEFAULT,description:"[y] yank to clipboard",action:()=>{let{selectedNode:e}=f(),t=e?.title===ie.DESCRIPTION?Ee.DESCRIPTION:e?.title===ie.TAGS?Ee.TAGS:e?.title===ie.ASSIGNEES?Ee.ASSIGNEES:Ee.REF,r=be(v.YANK).includes(t)?t:Ee.REF;return E({mode:h.COMMAND_LINE}),K(`${v.YANK} ${r}`),c("Propose command",!0)}},{intent:D.EditTitle,mode:h.DEFAULT,description:"[r] rename title",action:()=>(E({mode:h.COMMAND_LINE}),K(`${v.EDIT} title ${f().selectedNode?.title}`),c("Exiting context",null))},{intent:D.EditDescription,mode:h.DEFAULT,description:"[e] edit description",action:()=>(E({mode:h.COMMAND_LINE}),K(`${v.EDIT} description `),c("Exiting context",null))},{intent:D.Exit,mode:h.DEFAULT,description:"[q] exit context",action:()=>(U.enterParentNode(),c("Exiting context",null))},{intent:D.NavPreviousItem,mode:h.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:D.NavNextItem,mode:h.DEFAULT,action:()=>(U.navigateToNextItem(),c("Navigating to next item",null))},{intent:D.NavToPreviousContainer,mode:h.DEFAULT,action:()=>(U.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:D.NavToNextContainer,mode:h.DEFAULT,action:()=>(U.navigateToNextContainer(),c("Navigating to next container",null))}]});var Gb,qb,kp,Lp=y(()=>{"use strict";xe();Gb=500,qb=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),kp=e=>{let t=qb(e);t&&Ms(n=>(n+t).slice(0,Gb))}});var Vb,Kb,Pp,Dp=y(()=>{"use strict";Lp();le();C();xe();k();xn();nd();Vb=[h.COMMAND_LINE,h.PALETTE],Kb=e=>[{intent:D.MoveCursorLeft,mode:e,action:()=>(ya(-1),c("Moving cursor left",null))},{intent:D.MoveCursorRight,mode:e,action:()=>(ya(1),c("Moving cursor right",null))},{intent:D.MoveCursorLeftOfWord,mode:e,action:()=>(ba("left"),c("Moving cursor left of word",null))},{intent:D.MoveCursorRightOfWord,mode:e,action:()=>(ba("right"),c("Moving cursor right of word",null))},{intent:D.AutoCompleteCommand,mode:e,action:()=>(Ms((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=f().selectedNode?.title??""),r+o}),c("Auto-completing command",null))},{intent:D.CaptureInput,mode:e,action:(t,{sequence:n})=>(kp(n??""),c("Capturing input",null))},{intent:D.EraseInput,mode:e,action:()=>(yu(),c("Erasing input",null))},{intent:D.EraseInputWord,mode:e,action:()=>(bu(),c("Erasing input word",null))}],Pp=[{intent:D.Confirm,mode:h.COMMAND_LINE,action:()=>(kt(),c("Executing command",null))},{intent:D.ViewHelp,mode:h.DEFAULT,action:()=>(E({mode:h.HELP}),c("Viewing help",null))},...Vb.flatMap(Kb),{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:()=>(Eu(),c("Getting last command from history",null))},{intent:D.GetNextCommandFromHistory,mode:h.COMMAND_LINE,action:()=>(Ru(),c("Getting next command from history",null))}]});import Bp from"chalk";var Js,Fp,Op,rd,_p=y(()=>{"use strict";le();ge();Pe();Js=Bp.dim.hex(S.secondary2)(": for command line"),Fp="q to exit",Op=`${Bp.hex(S.accent)("m")} to confirm`,rd={[_.WORKSPACE]:[Js],[_.BOARD]:[Js],[_.BOARD+h.COMMAND_LINE]:[Js],[_.SWIMLANE]:[Js],[_.TICKET+h.HELP]:[Fp],[_.SWIMLANE+h.HELP]:[Fp],[_.TICKET]:[],[_.FIELD]:[],[_.SWIMLANE+h.MOVE]:[Op],[_.TICKET+h.MOVE]:[Op]}});function Up(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 $p=y(()=>{"use strict";C()});var jp,Hp=y(()=>{"use strict";jp=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 zb}from"react";function ad(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=Up(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,g=rd[p+n]??rd[p]??[],I=[...wp,...bp[p]??[],...Pp],N=jp(I),A=Xb(o,s),w=A[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:g,availableActions:I,actionIndex:N,selectedNode:w,renderedChildrenIndex:A})}function jr(e){od=e;let t=Xe(process.cwd()),n=!1;if(!a(t)){let s=Ft(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=ad(r);return a(o)?o:(Lt=o.value,id(),c("State initialized",null))}function Ie(e){let t=f(),n=e(t);if(zn)return Ro=n,Lt={...t,...n},c("State updated",null);let r=ad(n);return a(r)?i(r.message??"Unable to update state"):(Lt=r.value,id(),c("State updated",null))}function cc(e){if(zn)return c("Joined batch",e());zn=!0,Ro=null;let t=()=>{let n=Ro;if(zn=!1,Ro=null,n===null)return null;let r=ad(n);return a(r)?i(r.message??"Unable to update state"):(Lt=r.value,id(),c("State updated",null))};try{let n=e(),r=t();return r&&a(r)?i(r.message):c("State updated",n)}finally{zn&&t()}}function Yn(e,t,n){if(!zn)return Ie(d=>({...d,[e]:{...d[e]??{},[t]:n}}));let r=f(),o=r[e]??{};o[t]=n;let s={...r,[e]:o};return Ro=s,Lt={...r,...s},c("State updated",null)}var Lt,od,sd,id,Yb,f,He,zn,Ro,$c,E,Ve,Xb,ae,Kt,ot,k=y(()=>{"use strict";xp();Mp();Dp();_p();Ot();le();C();re();Hi();$p();Hp();sd=new Set,id=()=>{for(let e of sd)e()},Yb=e=>(sd.add(e),()=>sd.delete(e));f=()=>{if(!Lt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Lt},He=()=>Lt?c("Retrieved state",Lt):i("State not initialized. Call initWorkspaceState() first.");zn=!1,Ro=null;$c=()=>zn,E=e=>Ie(t=>({...t,...e}));Ve=()=>zb(Yb,f,f),Xb=Oc,ae=e=>f()?.renderedChildrenIndex[e]??[],Kt=()=>od?jr(od):i("Cannot reset state: no initial workspace found"),ot=()=>Lt!==void 0});var Kn,Jb,vn,x,me=y(()=>{"use strict";bt();ge();C();k();It();Kn=(e,t)=>{let{nodes:n}=f(),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}`)},Jb=(e,t)=>{let{nodes:n}=f(),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},vn=(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=Yn("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=Yn("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=Yn("comments",e,n);return a(r)?i("Unable to delete comment"):c("Deleted comment",n)},getComment(e){return f().comments?.[e]},getCommentsByIssue(e){return Object.values(f().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(f().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return 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 f().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(f().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(f().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=f(),r=n[e];if(!r)return i("Edit target node not found");let o=vn(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=vn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=f();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return ue(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=f(),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=vn(o,"move");if(d)return d;if(Jb(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}=f(),o=this.getNode(e);if(!o)return i("Node not found");if(r===e)return i("Cannot delete root node");let s=vn(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 g of ue(p.id))l(g.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:ko,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=vn(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=vn(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=vn(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=vn(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=Yn("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=Yn("nodes",e,n);return a(r)?i(r.message):c("Locked node",n)},updateNode(e){let t=Yn("nodes",e.id,e);return a(t)?t:c("Updated node",e)},getContributor(e){return f().contributors[e]},getTag(e){let t=f().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return f().tags[e]},getTags(){return Object.values(f().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return f().nodes[e]},getSiblings(e){return ue(e)}}});import yn from"chalk";import Wp from"string-width";var Qb,Zb,dd,ex,tx,Gp,qp,nx,rx,ox,sx,ix,td,Vp,Io=y(()=>{"use strict";dt();me();k();Tt();_s();Qb=(e,t)=>e+" ".repeat(Math.max(0,t-Wp(e))),Zb=(e,t)=>" ".repeat(Math.max(0,t-Wp(e)))+e,dd=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`),ex=(e,t)=>t?e<t?"up":e>t?"down":null:null,tx=(e,t)=>{let n=x.getNode(e.payload.parent),r=n?yn.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=ex(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Gp=e=>`${Math.max(1,Math.round(e/1024))} KB`,qp=e=>x.getAttachment(e)?.name??"",nx=e=>{switch(e.action){case"add.issue.tag":{let t=f().tags[e.payload.tag];return t?yn.bgHex(De(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?yn.bgHex(De(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=f().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?yn.hex(De(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?yn.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}" ${yn.dim(`(${Gp(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=qp(e.payload.id);return t?`"${t}"`:""}default:return""}},rx=e=>{let t=vr(yt(e));return yn.gray(Zb(t,8))},ox=12,sx=e=>Qb(`${e}`,ox),ix=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=f().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}" (${Gp(e.payload.bytes)})`;case"delete.issue.attachment":{let t=qp(e.payload.id);return t?`"${t}"`:""}default:return""}},td=e=>[dd(e.action),ix(e)].filter(Boolean).join(" "),Vp=(e,t)=>{let n=rx(e.id),r=sx(e.userName),o=yn.dim("\u203A"),s=e.action==="move.node"?tx(e,t):[dd(e.action),nx(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`}});var zp={};To(zp,{areVirtualNodesEnabled:()=>Yo,createOrUpdateVirtualField:()=>So,createOrUpdateVirtualFieldList:()=>cd,materializeTicketVirtualNodes:()=>zo,materializeVirtualNodes:()=>fx,setVirtualNodesEnabled:()=>gx});var ax,dx,cx,lx,ux,mx,So,cd,zo,px,Kp,gx,Yo,fx,wi=y(()=>{"use strict";Io();ge();C();tr();me();An();k();Zn();dr();ax=e=>Ce(e,"comments"),dx=e=>Ce(e,"description"),cx=e=>Ce(e,"assignees"),lx=e=>Ce(e,"tags"),ux=e=>Ce(e,"history"),mx=e=>Ce(e,"attachments"),So=({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({...Ne.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(!Ye(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)},cd=({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({...Ne.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(!Ar(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)},zo=e=>{let t=tt(xt/4n),n=tt(xt/2n),r=tt(xt*3n/4n),o=tt(xt*7n/8n),s=tt(xt*15n/16n),d=tt(xt*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=So({id:dx(e.id),name:ie.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(l))return l;let u=cd({id:cx(e.id),name:ie.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(u))return u;let m=cd({id:lx(e.id),name:ie.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(a(m))return m;let p=So({id:ax(e.id),name:ie.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(p))return p;let g=So({id:mx(e.id),name:ie.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(g))return g;let I=So({id:ux(e.id),name:ie.HISTORY,parentNodeId:e.id,rank:d.value,value:px(e),readonly:!0,childRenderAxis:"vertical"});return a(I)?I:c("Ticket virtual nodes materialized",void 0)},px=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=>Vp(r,n.get(r.action)??[])).join(`
|
|
73
|
+
`)},Kp=!0,gx=e=>{Kp=e},Yo=()=>Kp,fx=()=>{let{nodes:e}=f();for(let t of Object.values(e)){if(!P(t))continue;let n=zo(t);if(a(n))return n}return c("Virtual nodes materialized",void 0)}});var hx,Yp,ld=y(()=>{"use strict";dt();jt();Hr();Io();C();Tt();hx=e=>{let t=new Map,n=new Set,r=o=>{let s=new Set,d=o;for(;d&&!s.has(d);){if(n.has(d))return d;s.add(d),d=t.get(d)}return null};return e.map(o=>{let s=o.payload,d=s?.id;if(!d)return null;o.action==="add.board"&&n.add(d);let l=s.parent??s.issue;return l&&t.set(d,l),n.has(d)?d:r(d)})},Yp=(e,t)=>{let n=hx(e);return e.filter((r,o)=>n[o]===t)}});var vx,Xp,Jp,ud,md=y(()=>{"use strict";mt();lt();tn();qa();jt();_t();C();Ot();Rs();re();k();ld();vx=null,Xp=Promise.resolve(),Jp=e=>{let t=Xp.then(e,e);return Xp=t.then(()=>{},()=>{}),t},ud=()=>{if(!ot())return{mode:"live",asOfTime:null};let{timeMode:e}=f();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:vx}}});import Qp from"node:fs";import yx from"node:path";import{ulid as q}from"ulid";var bx,xx,ti,Qs,ee,se,ne,Zp,Ix,eg,tg,ng,rg,og,sg,ig,ag,dg,cg,lg,ug,mg,pg,gg,fg,tU,hg,vg,yg,bg,xg,Ig,Eg,Rg,Sg,Ng,Ex,Cg,Ag,Tg,wg,Mg,kg,Lg,Pg=y(()=>{"use strict";mt();lt();Lr();Xr();Yi();Qn();jn();Qa();dt();qr();Hr();re();jt();Dn();gt();ld();Ha();nr();ge();C();me();It();k();is();eo();re();bt();Io();Tt();uo();tn();Jt();io();Et();md();bx=e=>{if(e.filePath)try{return c("Read attachment file",{data:Qp.readFileSync(e.filePath),name:e.name??yx.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")},xx=()=>{let e=ca();return a(e)?Gt:e.value.attachmentMaxKb??Gt},ti=e=>{let t=Xe(e??process.cwd());return a(t)?i(t.message):c("Resolved Epiq repo root",t.value)},Qs=null,ee=async(e,t)=>{let n=ti(e);if(a(n))return n;let r=Se({repoRoot:n.value});if(a(r))return i(r.message);let o=Qt(n.value);if(a(o))return i(o.message);if(!(Qs!==null&&Qs.repoRoot===n.value&&Qs.stateBranchRoot===r.value&&Qp.existsSync(En(r.value)))){let p=await Vi({repoRoot:n.value,stateBranchName:o.value});if(a(p))return i(p.message);let g=await Bn({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(a(g))return i(g.message);Qs={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let p=await G({cwd:r.value,args:["pull","--ff-only"]});a(p)&&X.info(3,p.message)}let d={repoRoot:n.value,stateBranchRoot:r.value},l=Mn(r.value);if(mc(r.value)===l&&ot()&&ud().mode==="live")return c("Booted Epiq state, unchanged",d);let u=$t(r.value);if(a(u))return i(u.message);let m=an(u.value.events,u.value.unreadable);return a(m)?i(m.message):(pc(r.value,l),c("Booted Epiq state",d))},se=()=>{let e=ca();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=He();return a(e)?i(e.message):e},Zp=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)})),Ix=()=>{let e=He(),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},eg=(e,t)=>{let n=new Map(e);for(let r of Object.values(t))n.set(r.id,r.name);return n},tg=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)})),ng=async(e={})=>{let t=await ee(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:z(o.id),title:o.title,parentId:o.parentNodeId,readonly:!!o.readonly}));return c("Listed boards",r)},rg=async(e={})=>{let t=await ee(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===ye,readonly:!!o.readonly}));return c("Listed swimlanes",r)},og=async e=>{let t=await ee(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(P).filter(u=>!u.isDeleted),s=o.find(u=>u.id===r),d=s?[s]:o.filter(u=>_r(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=>`${z(u.id)} (${Me(u.title)})`).join(", ")}. Use a full ref or id.`);let l=d[0];return c("Found issue",{id:l.id,ref:z(l.id),title:Me(l.title),description:l.props.description??"",createdAt:yt(l.id),parentNodeId:l.parentNodeId,isClosed:l.parentNodeId===ye,readonly:!!l.readonly,tags:Zp(l),assignees:tg(l)})},sg=async e=>{let t=await ee(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(P).filter(s=>!s.isDeleted).filter(s=>e.includeClosed||s.parentNodeId!==ye).filter(s=>e.boardId?(s.parentNodeId?r[s.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).map(s=>({id:s.id,ref:z(s.id),title:Me(s.title),description:s.props.description??"",createdAt:yt(s.id),parentNodeId:s.parentNodeId,isClosed:s.parentNodeId===ye,readonly:!!s.readonly,tags:Zp(s),assignees:tg(s)}));return c("Listed issues",o)},ig=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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=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=On(e.parentId,n.value,t.value.stateBranchRoot);if(a(l))return l;let u=Gs({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:q(),...n.value,action:"edit.description",payload:{id:p,md:s}});let g=[];for(let A of e.tagNames??[]){let w=Me(A).trim();if(!w||g.some(O=>O.name===w))continue;let T=ft("Tag name",w,60);if(T)return i(T);let M=x.findTagByName(w),$=M?.id??q();M||m.push({id:q(),...n.value,action:"create.tag",payload:{id:$,name:w}}),m.push({id:q(),...n.value,action:"add.issue.tag",payload:{id:p,tag:$}}),g.push({id:$,name:w})}let I=[];for(let A of e.assigneeNames??[]){let w=Me(A).trim();if(!w||I.some(O=>O.name===w))continue;let T=ft("Assignee name",w,80);if(T)return i(T);let M=Object.values(r.value.contributors).find(O=>O.name===w),$=M?.id??q();M||m.push({id:q(),...n.value,action:"create.contributor",payload:{id:$,name:w}}),m.push({id:q(),...n.value,action:"add.issue.assignee",payload:{id:p,assignee:$}}),I.push({id:$,name:w})}let N=B(m,t.value.stateBranchRoot);return a(N)?i(N.message):c("Created issue",{id:p,ref:z(p),title:o,parentId:e.parentId,description:s,tags:g,assignees:I})},ag=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=sn(ye,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(r))return r;let o={id:q(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ye,rank:r.value}},s=B([o],t.value.stateBranchRoot);return a(s)?i(s.message):c("Closed issue",{id:e.issueId,ref:z(e.issueId)})},dg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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(!P(o))return i("Target node is not issue");if(o.parentNodeId!==ye)return i("Issue is not closed");let s=js(o);if(!s)return i("Unable to resolve previous parent from issue history");if(s===ye)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=sn(d.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(l))return l;let u={id:q(),...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:z(o.id),parentId:d.id})},cg=async e=>{let t=ti(e.repoRoot);if(a(t))return t;let n=se();if(a(n))return n;let r=Se({repoRoot:t.value});if(a(r))return r;let o=$t(r.value);if(a(o))return o;let s=an(o.value.events,o.value.unreadable);if(a(s))return s;let d=sn(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(a(d))return d;let l={id:q(),...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:z(e.issueId),parentId:e.parentId})},lg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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(!Lo(o))return i("Target parent must be a board");if(o.readonly)return i("Cannot add a swimlane to a readonly board");if(ud().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=ft("Swimlane title",s,300);if(d)return i(d);let l=On(e.boardId,n.value,t.value.stateBranchRoot);if(a(l))return l;let u=q(),m={id:q(),...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:z(u),title:s,boardId:e.boardId})},ug=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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(!bn(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=ft("Swimlane title",s,300);if(d)return i(d);if(o.title===s)return c("No changes made",{id:e.swimlaneId,ref:z(e.swimlaneId),title:s});let l={id:q(),...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:z(e.swimlaneId),title:s})},mg=async e=>{let t=ti(e.repoRoot);if(a(t))return t;let n=se();if(a(n))return n;let r=Se({repoRoot:t.value});if(a(r))return r;let o=$t(r.value);if(a(o))return o;let s=an(o.value.events,o.value.unreadable);if(a(s))return s;let d=sn(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(a(d))return d;let l={id:q(),...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:z(e.swimlaneId),boardId:e.boardId})},pg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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(!bn(o))return i("Delete target must be a swimlane");let s={id:q(),...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:z(e.swimlaneId)})},gg=async(e={})=>{os();let t=ti(e.repoRoot);if(a(t))return i("Sync failed");let n=se();if(a(n))return n;let r=await ls({cwd:t.value,ownEventFileName:Pn(n.value)});return a(r)?(Wi(r.message),r):(ss(),c("Synced",r.value))},fg=async(e={})=>{let t=await ee(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})},tU=365*24*60*60*1e3,hg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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(!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:z(e.issueId),description:d});let l={id:q(),...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:z(e.issueId),description:e.description})},vg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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(!P(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=ft("Issue title",s,300);if(d)return i(d);if(o.title===s)return c("No changes made",{id:e.issueId,ref:z(e.issueId),title:s});let l={id:q(),...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:z(e.issueId),title:s})},yg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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(!P(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=ft("Tag name",s,60);if(d)return i(d);let l=x.findTagByName(s),u=l?.id??q(),m=[...l?[]:[{id:q(),...n.value,action:"create.tag",payload:{id:u,name:s}}],{id:q(),...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:z(e.issueId),tag:{id:u,name:s}})},bg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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:q(),...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})},xg=async e=>{let t=ai(e.name,"name");if(a(t))return i(t.message);let n=await ee(e.repoRoot,{pull:!1});if(a(n))return n;let r=se();if(a(r))return r;let o=ne();if(a(o))return o;let s=r.value,d=!!o.value.contributors[s.userId];if(!d){let l=B([{id:q(),...s,action:"create.contributor",payload:{id:s.userId,name:s.userName}}],n.value.stateBranchRoot);if(a(l))return i(l.message)}return c(`Assumed ${s.userName}`,{...s,registered:!d})},Ig=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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:q(),...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})},Eg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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(!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:q(),...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:z(e.issueId),tagId:e.tagId})},Rg=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}},Sg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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(!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 Rg(t.value.stateBranchRoot,s);if(!T&&!M)return i("Unknown assignee id");let $=T??M,O=[...T?[]:[{id:q(),...n.value,action:"create.contributor",payload:{id:$.id,name:$.name}}],{id:q(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:$.id}}],H=B(O,t.value.stateBranchRoot);return a(H)?i(H.message):c("Added issue assignee",{id:e.issueId,ref:z(e.issueId),assignee:{id:$.id,name:$.name}})}let d=Me(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=[...eg(Ix(),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[g=q(),I=d]=p??[],A=[...!!r.value.contributors[g]?[]:[{id:q(),...n.value,action:"create.contributor",payload:{id:g,name:I}}],{id:q(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:g}}],w=B(A,t.value.stateBranchRoot);return a(w)?i(w.message):c("Added issue assignee",{id:e.issueId,ref:z(e.issueId),assignee:{id:g,name:I}})},Ng=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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 Rg(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:q(),...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:ko})},Ex=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},Cg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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 Ex(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:q(),...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})},Ag=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=kn(t.value.stateBranchRoot);if(a(o))return i(o.message);let s=e.boardId?Yp(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=[...eg(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)},Tg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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(!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:q(),...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:z(e.issueId),assigneeId:e.assigneeId})},wg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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(!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=q(),l={id:q(),...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})},Mg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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(!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:q(),...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})},kg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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(!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:q(),...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})},Lg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();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(!P(o))return i("Attachment target must be an issue");if(o.readonly)return i("Cannot attach to readonly issue");let s=bx(e);if(a(s))return s;let d=Kl(t.value.stateBranchRoot,s.value.data,xx());if(a(d))return d;let l=Me(s.value.name).trim()||"image",u=q(),m={id:q(),...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 g=so(d.value.hash,d.value.ext);return c("Added issue attachment",{id:u,issueId:e.issueId,fileName:g,bytes:d.value.bytes,markdown:la(l,g)})}});var Og={};To(Og,{createMcpServer:()=>Fg,resultJson:()=>Dg,startMcpServer:()=>Cx});import{McpServer as Sx}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Nx}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as b}from"zod";var Dg,J,Fg,Cx,Bg=y(()=>{"use strict";C();uo();Pg();md();Dg=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),J=e=>t=>Jp(async()=>Dg(await e(t))),Fg=()=>{let e=new Sx({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(fg)),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(sg)),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(og)),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:b.object({repoRoot:b.string().optional()})},J(ng)),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:b.object({repoRoot:b.string().optional(),boardId:b.string().optional()})},J(rg)),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(lg)),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(ug)),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(mg)),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(pg)),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(ig)),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(hg)),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(vg)),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(yg)),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(Eg)),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(Ag)),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(Ng)),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(bg)),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(Ig)),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(Cg)),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(Sg)),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(Tg)),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(wg)),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(Lg)),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(Mg)),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(kg)),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(dg)),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),repoRoot:b.string().optional()})},J(ag)),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(cg)),e.registerTool("epiq_actor_assume",{description:'Take a board identity for the rest of this session, so your writes are attributed to you rather than to the user. Pass the name you announced \u2014 the model provider, a slash, then a short human first name, e.g. "claude/peter". Takes effect on the very next write; no relaunch. A name the server was launched with wins, and re-assuming the same name is harmless. Reuse an existing agent identity (epiq_contributor_list) before inventing one: a name is permanent once it has authored anything.',inputSchema:b.object({name:b.string().min(1).max(80),repoRoot:b.string().optional()})},J(xg)),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(gg)),e},Cx=async()=>{let e=Fg(),t=new Nx;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:Ax}=await Promise.resolve().then(()=>(Qn(),bd)),{isFail:Tx}=await Promise.resolve().then(()=>(C(),hd)),ni=process.argv.slice(2);ni.length>1&&(console.error(`Expected at most one name argument, got ${ni.length}`),process.exit(1));if(ni[0]!==void 0){let e=Ax(ni[0],"The name argument");Tx(e)&&(console.error(e.message),process.exit(1))}var{setVirtualNodesEnabled:wx}=await Promise.resolve().then(()=>(wi(),zp));wx(!1);var{startMcpServer:Mx}=await Promise.resolve().then(()=>(Bg(),Og));await Mx();
|