epiq 1.10.0 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gui/main.js +113 -113
- package/dist/index.js +100 -100
- package/dist/mcp.js +114 -86
- package/package.json +1 -1
- package/readme.md +18 -143
package/dist/mcp.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var gI=Object.defineProperty;var g=(e,t)=>()=>(e&&(t=e(e=0)),t);var ss=(e,t)=>{for(var n in t)gI(e,n,{get:t[n],enumerable:!0})};var bm={};ss(bm,{failed:()=>a,isFail:()=>l,isSuccess:()=>_t,resultStatuses:()=>Tn,succeeded:()=>d});var Tn,a,d,l,_t,N=g(()=>{"use strict";Tn={Success:"success",Fail:"fail"},a=e=>({status:Tn.Fail,message:e,value:null}),d=(e,t)=>({status:Tn.Success,message:e,value:t}),l=e=>e.status==="fail",_t=e=>e.status==="success"});var Em={};ss(Em,{ACTOR_ID_ENV:()=>is,ACTOR_NAME_ENV:()=>Ft,applyActorNameArgument:()=>Ml,deriveActorId:()=>Im,isValidUserId:()=>Ai,isValidUserName:()=>as,resolveEnvActor:()=>Tl});import hI from"node:crypto";var Ft,is,xm,vI,wl,Ai,as,ro,Im,Tl,Ml,xr=g(()=>{"use strict";N();Ft="EPIQ_USER_NAME",is="EPIQ_USER_ID",xm="0123456789ABCDEFGHJKMNPQRSTVWXYZ",vI=26,wl=80,Ai=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),as=e=>e.trim().length>0&&e.length<=wl,ro=e=>e.trim().toLowerCase(),Im=e=>{let t=hI.createHash("sha256").update(`epiq:actor:${ro(e)}`).digest(),n="";for(let r=0;r<vI;r++)n+=xm[(t[r]??0)%xm.length];return n},Tl=(e,t=process.env)=>{let n=(t[Ft]??"").trim(),r=(t[is]??"").trim();return n?as(n)?!r&&e.userId&&e.userName&&ro(e.userName)===ro(n)?d("Actor override names the configured user",{userId:e.userId,userName:e.userName}):r&&!Ai(r)?a(`${is} must be 26 characters of Crockford base32`):r&&e.userId&&r===e.userId?a(`${is} is the configured user's own id; using it under a different name would rename them on the board`):d("Resolved actor from environment",{userId:r||Im(n),userName:r?n:ro(n)}):a(`${Ft} must be 1-${wl} characters of text`):r?a(`${is} is set without ${Ft}`):d("No actor override",null)},Ml=(e,t,n=process.env)=>{let r=e.trim();if(!as(r))return a(`${t} must be 1-${wl} characters of text`);let o=(n[Ft]??"").trim();return o&&ro(o)!==ro(r)?a(`${t} names ${r}, but ${Ft} names ${o}`):(o||(n[Ft]=r),d("Applied actor name argument",o||r))}});var kl,Sm=g(()=>{"use strict";kl="1.12.0"});var Rm={};ss(Rm,{parseMcpArgs:()=>bI});var yI,bI,Nm=g(()=>{"use strict";Sm();yI=`epiq-mcp ${kl}
|
|
3
3
|
|
|
4
4
|
Usage: epiq-mcp [name]
|
|
5
5
|
|
|
@@ -9,104 +9,132 @@ Usage: epiq-mcp [name]
|
|
|
9
9
|
Options:
|
|
10
10
|
-v, --version print the version
|
|
11
11
|
-h, --help print this help
|
|
12
|
-
`,
|
|
13
|
-
`}:t==="--help"||t==="-h"?{kind:"print",text:
|
|
14
|
-
`);if(n[n.length-1]===""&&n.pop(),t<=
|
|
12
|
+
`,bI=e=>{if(e.length>1)return{kind:"error",message:`Expected at most one name argument, got ${e.length}`};let t=e[0];return t===void 0?{kind:"none"}:t==="--version"||t==="-v"?{kind:"print",text:`${kl}
|
|
13
|
+
`}:t==="--help"||t==="-h"?{kind:"print",text:yI}:t.startsWith("-")?{kind:"error",message:`Unknown option ${t}; expected a name, e.g. epiq-mcp claude/peter`}:{kind:"name",name:t}}});import{decodeTime as Cm}from"ulid";var wi,ls,it,cs,Ll,Ir,at=g(()=>{"use strict";N();wi=1440*60*1e3,ls=(e,t=Date.now())=>e>t+wi?t:e,it=e=>ls(Cm(e)),cs=e=>{let t=Date.now()+wi,n=e.find(o=>o!==null&&o<=t)??null;if(n===null)return[...e];let r=null;return e.map(o=>{if(o===null)return null;let s=o<=t?o:r??n;return r=s,s})},Ll=e=>{try{return d("Decoded date",new Date(it(e)))}catch(t){return a("Decoding failed + "+t.message)}},Ir=e=>{if(!e?.id)return null;try{return Cm(e.id)}catch{return null}}});var Qe,w,Ye=g(()=>{"use strict";Qe={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"},w={accent:Qe.cyan,accent2:Qe.magenta,primary:Qe.white,secondary:Qe.grayDark,secondary2:Qe.grayLight,gray:Qe.gray,green:Qe.green,yellow:Qe.yellow,red:Qe.red}});var k,Ti,Pl=g(()=>{"use strict";Ye();k={red:Qe.red,yellow:Qe.yellow,green:Qe.green,blue:Qe.blue,magenta:Qe.magenta,cyan:Qe.cyan},Ti={urgent:k.red,critical:k.red,important:k.red,blocker:k.red,asap:k.red,immediate:k.red,fail:k.red,failure:k.red,broken:k.red,bug:k.red,error:k.red,incident:k.red,outage:k.red,production:k.red,crash:k.red,security:k.red,warning:k.yellow,warn:k.yellow,risky:k.yellow,risk:k.yellow,attention:k.yellow,pending:k.yellow,review:k.yellow,"needs-review":k.yellow,qa:k.yellow,testing:k.yellow,test:k.yellow,validate:k.yellow,verification:k.yellow,staging:k.yellow,check:k.yellow,"follow-up":k.yellow,followup:k.yellow,waiting:k.yellow,blocked:k.yellow,hold:k.yellow,done:k.green,complete:k.green,completed:k.green,success:k.green,ok:k.green,stable:k.green,resolved:k.green,fixed:k.green,closed:k.green,merged:k.green,released:k.green,deployed:k.green,approved:k.green,verified:k.green,working:k.green,healthy:k.green,pass:k.green,passing:k.green,info:k.blue,information:k.blue,note:k.blue,docs:k.blue,documentation:k.blue,doc:k.blue,guide:k.blue,help:k.blue,explanation:k.blue,detail:k.blue,details:k.blue,context:k.blue,design:k.blue,discussion:k.blue,proposal:k.blue,idea:k.blue,feature:k.magenta,enhancement:k.magenta,improvement:k.magenta,refactor:k.magenta,refactoring:k.magenta,cleanup:k.magenta,optimize:k.magenta,optimization:k.magenta,perf:k.magenta,performance:k.magenta,upgrade:k.magenta,migration:k.magenta,modernize:k.magenta,debt:k.magenta,todo:k.cyan,next:k.cyan,planned:k.cyan,plan:k.cyan,future:k.cyan,backlog:k.cyan,investigate:k.cyan,explore:k.cyan,prototype:k.cyan}});import Am from"chalk";var Ol,wm,Dl,Tm,xI,II,Mm,EI,SI,_l,Ze,km,Lm,Mi,RI,NI,ki,fn=g(()=>{"use strict";Pl();Ol={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},wm=(e,t,n)=>Math.max(t,Math.min(n,e)),Dl=(e,t,n)=>e+(t-e)*n,Tm=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},xI=e=>e.toLowerCase().trim(),II=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,c=s*(1-Math.abs(i%2-1)),u=0,p=0,m=0;i>=0&&i<1?(u=s,p=c):i>=1&&i<2?(u=c,p=s):i>=2&&i<3?(p=s,m=c):i>=3&&i<4?(p=c,m=s):i>=4&&i<5?(u=c,m=s):(u=s,m=c);let f=o-s/2;return[Math.round((u+f)*255),Math.round((p+f)*255),Math.round((m+f)*255)]},Mm=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,EI=(e,t,n)=>{let r=wm(n,0,1);return[Math.round(Dl(e[0],t[0],r)),Math.round(Dl(e[1],t[1],r)),Math.round(Dl(e[2],t[2],r))]},SI=(e,t,n)=>EI(e,t,n),_l=e=>{let t=Tm(e)%360,n=II(t,Ol.stringColor.saturation,Ol.stringColor.lightness);return Mm(n)},Ze=(e,t=Ti)=>{let n=xI(e??"");return n&&t[n]?t[n]:_l(n)},km=e=>{let t=Ol.gradient.stops,n=wm(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,s=Math.min(Math.floor(o),r-1),i=o-s;return SI(t[s],t[s+1],i)},Lm=e=>Mm(km(e)),Mi=e=>Tm(e.toLowerCase().trim())/4294967295,RI=e=>{let t=Mi(e);return km(t)},NI=e=>{let[t,n,r]=RI(e);return{normal:o=>Am.bgRgb(t,n,r).black(o),cursor:o=>Am.bgRgb(t,n,r).white.bold(o)}},ki=e=>NI(e).normal(` ${e} `)});var CI,ds,ht,Mn=g(()=>{"use strict";fn();CI="Unknown",ds=(e,t)=>t?.length?t:e?.length?e:CI,ht=(e,t)=>{let n=ds(e,t);return{id:e?.length?e:n,name:n,color:Ze(n)}}});var us,At,Pm,en=g(()=>{"use strict";N();us="removed",At=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?d("Found node",n):a("Unable to find node in breadcrumb")},Pm=["png","jpg","gif","webp"]});var Ge,Vn,ms,Fl,Bl,Kn,Dm,Li,wt=g(()=>{"use strict";Ge=e=>e.trim().toLowerCase(),Vn=e=>{let t=Ge(e);return t.length>0&&t.length<=254&&/^[^\s@]+@[^\s@]+$/.test(t)},ms=(e,t)=>`${Ge(e)} ${t}`,Fl=e=>!e.tombstoned,Bl=(e,t)=>{let n=Ge(t),r=new Set;for(let o of Object.values(e))Fl(o)&&o.email===n&&r.add(o.contributor);return[...r]},Kn=(e,t)=>{let n=new Set;for(let r of Object.values(e))Fl(r)&&r.contributor===t&&n.add(r.email);return[...n]},Dm=e=>{let t=new Map;for(let r of Object.values(e)){if(!Fl(r))continue;let o=t.get(r.email)??new Set;o.add(r.contributor),t.set(r.email,o)}let n=new Map;for(let[r,o]of t){let[s]=[...o];o.size===1&&s&&n.set(r,s)}return n},Li=(e,t)=>e===t.authorId||e===t.contributor});function $l(e){return e.context===re.WORKSPACE}function U(e){return e.context===re.TICKET}function Om(e){return e.context===re.TEXT}function et(e){return e.context===re.FIELD}function ps(e){return e.context===re.FIELD_LIST}var re,Er,Sr,fs,ce=g(()=>{"use strict";re={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};Er=e=>e.context===re.SWIMLANE,Sr=e=>e.context===re.BOARD,fs=e=>e.context===re.COMMENT});var x,Pe=g(()=>{"use strict";x={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette",IDENTITY:"identity"}});var _m=g(()=>{"use strict";Yn()});import Fm from"string-width";function Pi(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Rr,AI,jl,wI,Nr,Se,vt=g(()=>{"use strict";Rr=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",AI=/\u001B\[[0-9;]*m/,jl="\x1B[0m",wI=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),Nr=(e,t)=>{if(t<=0)return"";if(Fm(e)<=t)return e;if(t<=3)return"...".slice(0,t);let r=t-3,o="",s=0,i=!1;for(let c of e.split(/(\u001B\[[0-9;]*m)/))if(c!==""){if(AI.test(c)){o+=c,i=c!==jl&&c!=="\x1B[m";continue}for(let u of wI(c)){let p=Fm(u);if(s+p>r)return`${o}...${i?jl:""}`;o+=u,s+=p}}return`${o}...${i?jl:""}`},Se=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var Bm,$m,jm=g(()=>{"use strict";Bm=e=>{let t=new Map;for(let n of e){let r=n.toLowerCase();for(let o=1;o<=n.length;o++){let s=r.slice(0,o),i=t.get(s);i?i.push(n):t.set(s,[n])}}return t},$m=(e,t)=>t?e.get(t)??[]:[]});var Um,TI,Hm,Wm=g(()=>{"use strict";vt();jm();Um=new WeakMap,TI=e=>{let t=Um.get(e);return t||(t=Bm(e),Um.set(e,t)),t},Hm=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return $m(TI(e),r).filter(s=>Pi(r,s.toLowerCase())>=n)}});var MI,Gm,qm,zm=g(()=>{"use strict";vt();Wm();MI={hint:"",hints:[],overlap:0,remainder:""},Gm=({inputToMatch:e,lastWord:t,isLastWordCompleted:n,inputString:r},o,s=[])=>{if(n||e===""){let[c]=s;return s.length===1&&c&&!r.trim()?qm("",[c]):MI}let i=Hm({wordList:o,inputToMatch:e,overlapThreshold:1});return qm(t,i)},qm=(e,t)=>{let n=t[0]??"",r=Pi(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,m=(c&&i?o:n)+(c&&i?":":" "),f=m.slice(r);return{hint:m,hints:t,overlap:r,remainder:f}}});var oo,Di,Cr=g(()=>{"use strict";oo=e=>{let t=typeof e=="number"?e:Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<3e3||t>864e5?null:t},Di=e=>e==null||!Number.isFinite(e)?1e4:Math.min(864e5,Math.max(1,e))});import kI from"node:os";import LI from"node:path";var tn,kn,Oi=g(()=>{"use strict";tn=".epiq-global",kn=()=>process.env.EPIQ_GLOBAL_DIR??LI.join(kI.homedir(),tn)});var Ul,Vm=g(()=>{"use strict";N();Ul=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let i=r(...s);if(!n.has(i)){let c=e(...s).then(u=>(l(u)&&n.delete(i),u));n.set(i,c)}return n.get(i)});return o.clear=()=>n.clear(),o}});import nn from"fs";import zl from"path";import PI from"util";function FI(e){if(!nn.existsSync(e))return;let t=nn.statSync(e).size,n=_I(e,Vl).split(`
|
|
14
|
+
`);if(n[n.length-1]===""&&n.pop(),t<=Vl&&n.length<=Km)return;let r=n.slice(-Km).join(`
|
|
15
15
|
`)+`
|
|
16
|
-
`;
|
|
17
|
-
`;try{
|
|
18
|
-
`);return i===-1?"":s.slice(i+1)}finally{
|
|
19
|
-
`);u(n?{stdout:i,stderr:f,exitCode:124}:
|
|
20
|
-
`)))}),o.on("close",f=>{let h=f??1;if(n){u({stdout:i,stderr:c,exitCode:h});return}if(h!==0){u(
|
|
21
|
-
`)));return}u(d("Git command succeeded",{stdout:i,stderr:c,exitCode:h}))})}),W=({args:e,cwd:t})=>
|
|
22
|
-
${s}`:""}`));return}let m=Buffer.concat(o),f=new Map,h=0;for(let b of e){let
|
|
16
|
+
`;nn.writeFileSync(e,r,"utf8")}function ql(e,t,n=!1){let r=OI();if(!r)return;let o=BI(PI.format(...t)),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
17
|
+
`;try{nn.mkdirSync(zl.dirname(r),{recursive:!0}),nn.appendFileSync(r,c,"utf8"),Wl++,(Wl>=DI||nn.statSync(r).size>Vl)&&(Wl=0,FI(r))}catch{}}var Km,Vl,Hl,DI,Wl,Ym,OI,_I,BI,Gl,ie,Bt=g(()=>{"use strict";N();Q();Km=500,Vl=4*1024*1024,Hl=16*1024,DI=50,Wl=0,Ym=()=>process.env.EPIQ_MCP==="true",OI=()=>{let e=process.cwd(),t=_i(e);return l(t)?Ym()?zl.join(kn(),"epiq-mcp.log"):void 0:zl.join(t.value,lt,"log","epiq.log")},_I=(e,t)=>{let n=nn.statSync(e).size;if(n<=t)return nn.readFileSync(e,"utf8");let r=nn.openSync(e,"r");try{let o=Buffer.alloc(t);nn.readSync(r,o,0,t,n-t);let s=o.toString("utf8"),i=s.indexOf(`
|
|
18
|
+
`);return i===-1?"":s.slice(i+1)}finally{nn.closeSync(r)}};BI=e=>{if(e.length<=Hl)return e;let t=e.length-Hl;return`${e.slice(0,Hl)} \u2026 [${t} more chars]`};Gl=()=>Ym()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",ie={info(...e){let t=Gl();(t==="info"||t==="debug")&&ql("[Info]",e,!1)},debug(...e){Gl()==="debug"&&ql("[Debug]",e,!0)},error(...e){let t=Gl();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;ql("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=ie});var Re,Fi=g(()=>{"use strict";ze();Re={stage:({cwd:e,pathspec:t,ignoreRemoval:n=!1})=>W({args:["add",...n?["--ignore-removal"]:[],...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1,pathspec:r})=>W({args:["commit","--no-verify",...n?["--allow-empty"]:[],"-m",t,...r?.length?["--",...r]:[]],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>W({args:["fetch",t,`+refs/heads/${n}:refs/remotes/${t}/${n}`],cwd:e}),rebaseOnto:({cwd:e,ref:t})=>W({args:["-c","rebase.autoStash=true","rebase",t],cwd:e}),checkout:({cwd:e,branch:t})=>W({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 W({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>W({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>W({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>W({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>W({args:["worktree","prune"],cwd:e})}});var tt,Tt,gn=g(()=>{"use strict";rn();N();Q();tt=e=>{let t=Ne(e);if(l(t))return a("Unable to resolve epiq project root");let n=Mt(t.value);return l(n)?a("Unable to read project.json"):d("Resolved state branch",n.value.stateBranch)},Tt="origin"});import{spawn as Jm}from"node:child_process";import kt from"node:fs";import yt from"node:path";var Kl,$I,jI,UI,HI,Qm,Zm,ep,W,Me,Yl,io,Bi,Xl,tp,Ln,gs,$i,so,np,Jl,ji,rp,op,sp,WI,qI,GI,zI,ip,ap,Ql,Xm,hs,VI,vs,lp,cp,dp,up,ze=g(()=>{"use strict";N();Fi();gn();Kl=1e4,$I=12e4,jI=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),UI=e=>{let t=e.find((n,r)=>!n.startsWith("-")&&e[r-1]!=="-c");return t&&jI.has(t)?$I:Kl},HI=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(yt.delimiter))if(t)for(let n of e){let r=yt.join(t,n);try{if(!kt.statSync(r).isFile())continue;return kt.accessSync(r,kt.constants.X_OK),r}catch{continue}}return"git"},Qm=HI(),Zm={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},ep=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!kt.existsSync(t)){let f=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:f,exitCode:1});return}r(a(f));return}let o=Jm(Qm,e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Zm}),s=!1,i="",c="",u=f=>{s||(s=!0,clearTimeout(m),r(f))},p=UI(e),m=setTimeout(()=>{o.kill("SIGTERM");let f=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${p}ms`].join(`
|
|
19
|
+
`);u(n?{stdout:i,stderr:f,exitCode:124}:a(f))},p);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",f=>{i+=f}),o.stderr.on("data",f=>{c+=f}),o.on("error",f=>{if(n){u({stdout:i,stderr:f.message,exitCode:1});return}u(a([`git ${e.join(" ")}`,`cwd=${t}`,f.message].join(`
|
|
20
|
+
`)))}),o.on("close",f=>{let h=f??1;if(n){u({stdout:i,stderr:c,exitCode:h});return}if(h!==0){u(a([`git ${e.join(" ")}`,c.trim()||i.trim()||"Git command failed"].filter(Boolean).join(`
|
|
21
|
+
`)));return}u(d("Git command succeeded",{stdout:i,stderr:c,exitCode:h}))})}),W=({args:e,cwd:t})=>ep({args:e,cwd:t,allowFail:!1}),Me=({args:e,cwd:t})=>ep({args:e,cwd:t,allowFail:!0}),Yl=(e,t)=>new Promise(n=>{if(e.length===0){n(d("No blobs to read",new Map));return}let r=Jm(Qm,["cat-file","--batch"],{cwd:t,stdio:["pipe","pipe","pipe"],env:Zm}),o=[],s="",i=!1,c=p=>{i||(i=!0,clearTimeout(u),n(p))},u=setTimeout(()=>{r.kill("SIGTERM"),c(a(`git cat-file --batch timed out after ${Kl}ms`))},Kl);r.stdout.on("data",p=>o.push(p)),r.stderr.setEncoding("utf8"),r.stderr.on("data",p=>{s+=p}),r.on("error",p=>c(a(p.message))),r.on("close",p=>{if(p!==0){c(a(`git cat-file --batch exited ${p}${s?`
|
|
22
|
+
${s}`:""}`));return}let m=Buffer.concat(o),f=new Map,h=0;for(let b of e){let I=m.indexOf(10,h);if(I===-1){c(a(`git cat-file --batch output ended before a header for ${b}`));return}let C=m.toString("utf8",h,I);h=I+1;let T=/^[0-9a-f]{4,64} \S+ (\d+)$/.exec(C);if(!T||!T[1]){c(a(`Unexpected git cat-file --batch header: "${C}"`));return}let S=Number(T[1]);f.set(b,m.toString("utf8",h,h+S)),h+=S+1}c(d("Read blobs",f))}),r.stdin.write(e.join(`
|
|
23
23
|
`)+`
|
|
24
|
-
`),r.stdin.end()}),
|
|
25
|
-
${r.message}`);let o=await W({args:["rev-parse","HEAD"],cwd:e});return
|
|
26
|
-
${o.message}`):d("Created commit and resolved SHA",o.value.stdout.trim())},
|
|
27
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(
|
|
28
|
-
${t.stderr.trim()}`):d("Aborted stale rebase",!0)},
|
|
29
|
-
${o.message}`);let s=await
|
|
30
|
-
${s.message}`);let i=await
|
|
31
|
-
`+r.message);let o=
|
|
32
|
-
`+o.message):d("Ensured epiq storage",n)},
|
|
33
|
-
`,
|
|
34
|
-
`,
|
|
24
|
+
`),r.stdin.end()}),io=async({cwd:e,message:t,pathspec:n})=>{let r=await Re.commit({cwd:e,message:t,pathspec:n});if(l(r))return a(`Failed to create commit
|
|
25
|
+
${r.message}`);let o=await W({args:["rev-parse","HEAD"],cwd:e});return l(o)?a(`Commit created, but failed to read HEAD SHA
|
|
26
|
+
${o.message}`):d("Created commit and resolved SHA",o.value.stdout.trim())},Bi=async e=>{let t=await W({cwd:e,args:["rev-parse","--git-dir"]});if(l(t))return a(t.message);let n=t.value.stdout.trim();return d("Resolved git dir",yt.isAbsolute(n)?n:yt.resolve(e,n))},Xl=async e=>{let t=await Bi(e);if(l(t))return a(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(r))if(kt.existsSync(yt.join(n,s)))return d("Checked for in-progress Git operation",i);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,i]of Object.entries(o))if(kt.existsSync(yt.join(n,s)))return d("Checked for in-progress Git operation",i);return d("Checked for in-progress Git operation",null)},tp=async e=>{let t=await Xl(e);return l(t)?a(t.message):d("Checked for in-progress Git operation",t.value!==null)},Ln=async({repoRoot:e})=>{let n=(await Me({args:["remote","get-url",Tt],cwd:e})).exitCode===0;return d(`Checked remote ${n}`,n)},gs=async({repoRoot:e,branch:t})=>{let n=await Me({args:["ls-remote","--heads",Tt,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${Tt}/${t}`):d("Checked remote branch",n.stdout.trim().length>0)},$i=async({repoRoot:e,branch:t})=>{let n=await Me({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?d("Local branch exists",!0):n.exitCode===1?d("Local branch missing",!1):a(n.stderr.trim()||`Unable to inspect branch ${t}`)},so=e=>{try{return kt.realpathSync.native(e)}catch{return yt.resolve(e)}},np=async({repoRoot:e,worktreeRoot:t})=>{let n=await W({args:["worktree","list","--porcelain"],cwd:e});if(l(n))return a(n.message);let r=so(t),o=n.value.stdout.split(`
|
|
27
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(so).includes(r);return d("Checked worktree registration",o)},Jl=async e=>{let t=await Me({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return d("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},ji=async e=>{let t=await W({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return l(t)?a(t.message):d("Resolved current branch",t.value.stdout.trim())},rp=async e=>{let t=await W({args:["rev-parse","--short","HEAD"],cwd:e});return l(t)?a(t.message):d("Resolved short HEAD sha",t.value.stdout.trim())},op=e=>e.includes("fetch first")||e.includes("non-fast-forward"),sp=async e=>{let t=await Me({cwd:e,args:["rev-parse","--absolute-git-dir"]});if(t.exitCode!==0)return!1;let n=t.stdout.trim();return n?kt.existsSync(yt.join(n,"rebase-merge"))||kt.existsSync(yt.join(n,"rebase-apply")):!1},WI=3,qI=120,GI=e=>new Promise(t=>setTimeout(t,e)),zI=async(e,t)=>{let n=await Re.rebaseOnto({cwd:e,ref:t});for(let r=1;r<WI;r+=1){if(!l(n)||await sp(e))return n;await GI(qI),n=await Re.rebaseOnto({cwd:e,ref:t})}return n},ip=async(e,{preserve:t=[]}={})=>{let n=await Bi(e);if(l(n))return a(n.message);let r=n.value,o=[];for(let s of kt.readdirSync(r))if(s.endsWith(".lock")&&!t.includes(s))try{kt.rmSync(yt.join(r,s),{force:!0}),o.push(s)}catch{}return d("Cleared stale git lock files",o)},ap=async(e,t)=>{let n=await Me({cwd:e,args:["rev-parse","--git-common-dir"]});if(n.exitCode!==0)return a(`Unable to resolve the common git directory at ${e}`);let r=yt.resolve(e,n.stdout.trim()),o=yt.join(r,"refs","heads"),s=yt.resolve(o,`${t}.lock`);if(!s.startsWith(`${o}${yt.sep}`))return a(`Refusing to clear a ref lock outside ${o}`);if(!kt.existsSync(s))return d("No ref lock to clear",!1);try{kt.rmSync(s,{force:!0})}catch{return d("Ref lock could not be cleared",!1)}return d("Cleared a stale ref lock",!0)},Ql=async e=>{if(!await sp(e))return d("No rebase to abort",!1);let t=await Me({cwd:e,args:["rebase","--abort"]});return t.exitCode!==0?a(`Failed to abort the rebase in progress at ${e}
|
|
28
|
+
${t.stderr.trim()}`):d("Aborted stale rebase",!0)},Xm=async e=>{let t=await Me({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},hs=e=>/could not resolve host/i.test(e)||/connection refused|connection timed out|operation timed out/i.test(e)||/network is unreachable|no route to host/i.test(e)||/failed to connect to/i.test(e),VI=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),vs=async({cwd:e,branch:t})=>{let n=await Ql(e);if(l(n))return a(n.message);let r=await Xm(e),o=await Re.fetch({cwd:e,remote:Tt,branch:t});if(l(o))return VI(o.message)?d("Remote branch missing, skipped pull",!1):a(`Failed to fetch ${t}
|
|
29
|
+
${o.message}`);let s=await zI(e,`${Tt}/${t}`);if(l(s))return a(`Failed during rebase
|
|
30
|
+
${s.message}`);let i=await Xm(e),c=r!==null&&i!==null&&r!==i;return d(c?"Pulled with rebase":"Already up to date",c)},lp=async e=>{let t=await Me({args:["rev-list","--count","@{u}..HEAD"],cwd:e});return t.exitCode!==0?d("No upstream to compare against",!1):d("Compared against upstream",Number(t.stdout.trim())>0)},cp=async e=>{let t=await Me({args:["status","--porcelain","--untracked-files=all"],cwd:e});return t.exitCode!==0?a(t.stderr.trim()||"Unable to inspect the worktree for changes"):d("Inspected worktree for changes",t.stdout.trim().length>0)},dp=async(e,t)=>{let n=await Me({args:["diff","--cached","--quiet",...t?.length?["--",...t]:[]],cwd:e});return n.exitCode===0?d("No staged changes",!1):n.exitCode===1?d("Has staged changes",!0):a(n.stderr.trim()||"Unable to inspect staged changes")},up=async e=>{let t=await ji(e);return l(t)?a(t.message):d("Checked detached HEAD state",t.value==="HEAD")}});import Xn from"node:fs";import bt from"node:path";var fp,gp,hp,vp,Ar,be,KI,mp,ys,bs,yp,YI,XI,Zl,ec,pp,bp,xp,Lt,bM,nt=g(()=>{"use strict";rn();N();Oi();Q();Vm();Bt();ze();fp="4b825dc642cb6eb9a060e54bf8d69288fbee4904",gp=e=>bt.join(lt,Pn,e),hp=()=>bt.join(lt,tc),vp=kn,Ar=()=>bt.join(vp(),"worktrees"),be=({repoRoot:e})=>{let t=hn(e);return l(t)?a(t.message):d("Resolved state branch root",bt.join(Ar(),t.value))},KI=e=>bt.join(e,lt),mp=e=>bt.join(KI(e),Pn),ys=e=>{try{return Xn.mkdirSync(e,{recursive:!0}),d("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},bs=()=>{let e=vp(),t=Ar(),n=!Xn.existsSync(e)||!Xn.existsSync(t),r=ys(e);if(l(r))return a(`Ensure epiq home failed.
|
|
31
|
+
`+r.message);let o=ys(t);return l(o)?a(`Ensure worktrees dir failed.
|
|
32
|
+
`+o.message):d("Ensured epiq storage",n)},yp=e=>{Xn.existsSync(e)&&(ie.debug("[sync] remove path",e),Xn.rmSync(e,{recursive:!0,force:!0}))},YI=`*.jsonl merge=union
|
|
33
|
+
`,XI=`*~pending*.jsonl
|
|
34
|
+
`,Zl=()=>bt.join(lt,Pn,".gitattributes"),ec=()=>bt.join(lt,Pn,".gitignore"),pp=(e,t)=>{try{Xn.readFileSync(e,"utf8")!==t&&Xn.writeFileSync(e,t)}catch{Xn.writeFileSync(e,t)}},bp=(e,t)=>{for(let n of[mp(e),mp(t)]){let r=ys(n);if(l(r))return a(r.message)}return pp(bt.join(t,Zl()),YI),pp(bt.join(t,ec()),XI),d("Ensured state branch",void 0)},xp=async e=>{let t=await W({args:["ls-tree","--name-only","HEAD"],cwd:e});if(l(t))return a(`ensure state branch is storage only failed
|
|
35
35
|
`+t.message);let r=t.value.stdout.trim().split(`
|
|
36
|
-
`).filter(Boolean).filter(i=>i!==
|
|
37
|
-
${o.message}`);let s=await
|
|
38
|
-
`,"utf8"),d("Created project.json",null)}catch(o){return
|
|
39
|
-
`,"utf8")}catch(n){return l(`Unable to write ${Hi}: ${n instanceof Error?n.message:String(n)}`)}return d("Recorded recent project",e)},Wi=({exclude:e}={})=>{let t=Sp();if(a(t))return t;let n=e===void 0?null:bp(e);return d("Listed recent projects",t.value.filter(r=>n===null||bp(r.root)!==n).filter(Rp).sort(Ep))},Rs=({root:e,now:t=Date.now()})=>{let n=Es.resolve(e),r=fn(n);if(a(r))return l(r.message);let o=r.value,s=Sp(),i=a(s)?[]:s.value,c=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(u=>u.projectId!==o&&u.root!==n)].filter(Rp).sort(Ep).slice(0,ZI);return nE(c)}});import{useSyncExternalStore as Bk}from"react";var qi,rE,oE,de,ut,Ue=g(()=>{"use strict";qi={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,gitEmail:null,gitName:null,declinedEmailBoards:[],viewMode:null},rE=new Set,oE=()=>{for(let e of rE)e()},de=()=>qi,ut=e=>(qi={...qi,...e},oE(),qi)});var ec,Np,Cp,tc=g(()=>{"use strict";ec=null,Np=e=>{ec=e},Cp=e=>ec?ec(e):[]});var wp,Ap,co,Ss=g(()=>{"use strict";wp=[],Ap=e=>{wp=e},co=()=>wp});var Ns,nc,Tp,kp,rc,Mp,Lp,Pp,wr=g(()=>{"use strict";wt();N();Zt();Ue();tc();Ss();ee();Ns=()=>{let e=de(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1,o=Tp(),s=o.length>0?null:nc(),i=s!==null&&(e.declinedEmailBoards??[]).includes(s),c=o.length>0||i||s===null;return{isSetupDone:n&&t&&r&&c,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r,isSetEmails:c,claimedEmails:o,emailSetupDeclined:i}},nc=()=>{let e=Ce(process.cwd());if(a(e))return null;let t=fn(e.value);return a(t)?null:t.value||null},Tp=()=>{let{userId:e}=de();return e?Cp(e):[]},kp=()=>Tp().length>0,rc=()=>{let e=Ce(process.cwd());if(a(e))return!1;let t=Tt(e.value);return Dt(t)},Mp=e=>e===!0?"on":e===!1?"off":null,Lp=e=>e==="on"?!0:e==="off"?!1:null,Pp=()=>{let e=Ns();if(!e.isSetUserName)return"config username ";if(!e.isSetPreferredEditor)return"config editor ";if(!e.isSetAutoSync)return"config autoSync ";if(!rc())return"init";if(!e.isSetEmails){let{gitEmail:t}=de(),n=co()[0]??t;return n&&zn(n)?`config emails ${n}`:"config emails "}return null}});var sE,we,Gi,tn=g(()=>{"use strict";sE=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[we,Gi]=sE});var iE,aE,hn,vn,zi,Vi,uo=g(()=>{"use strict";me();N();pe();D();iE=e=>e.props.tags??[],aE=e=>e.props.assignees??[],hn=e=>iE(e).map(t=>C.getTag(t)).filter(t=>!!t),vn=e=>aE(e).map(t=>C.getContributor(t)).filter(t=>!!t),zi=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!U(n)?l("Invalid untag target"):d("Retrieved tags from ticket in breadcrumb",hn(n))},Vi=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!U(n)?l("Invalid unassign target"):d("Retrieved assignees from ticket in breadcrumb",vn(n))}});var I,Ar=g(()=>{"use strict";I={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",NONE:""}});var lE,cE,dE,uE,mE,Tr,Dp,Ki,Yi,Op,pE,oc,Cs=g(()=>{"use strict";lE=/^(\d+)(h|d|w|mo|y)$/,cE=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,dE=({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},uE=(e,t=new Date)=>{let n=e.match(lE);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(o){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},mE=e=>{let t=e.match(cE);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),u=Number(r),p=Number(o),m=s?Number(s):0,f=i?Number(i):0;return dE({year:c,month:u,day:p,hour:m,minute:f})?new Date(c,u-1,p,m,f):null},Tr=e=>{let t=e.trim().toLowerCase();return uE(t)??mE(t)},Dp=/^(\d+)(s|m)?$/,Ki=e=>{let t=e.trim().toLowerCase().match(Dp);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Yi=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Dp.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Op=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,pE=[{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}],oc=(e=pE)=>{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 fE,ye,Mt,He,gE,hE,ic,ac,Bp,kr,Xi,sc,_p,vE,yE,ws,Fp,bE,xE,lc,IE,We,Pn=g(()=>{"use strict";Sr();lo();N();wr();tn();me();pe();D();kl();uo();Ar();Cs();fE=["BOARD","TICKET","SWIMLANE","COMMENT"],ye={EDITOR:"editor",VIEW:"view",USERNAME:"username",EMAILS:"emails",EMAILS_UNCLAIM:"emails-unclaim",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},Mt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},He={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},gE=[ye.EDITOR,ye.VIEW,ye.USERNAME,ye.EMAILS,ye.EMAILS_UNCLAIM,ye.AUTOSYNC,ye.SYNC_DEBOUNCE_MS,ye.ATTACHMENT_MAX_KB,ye.LOG_LEVEL],hE=(e=v().selectedNode?.context)=>{switch(e){case"TICKET":return[Mt.TITLE,Mt.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Mt.TITLE];case"COMMENT":return[Mt.COMMENT];default:return[]}},ic=[String(3e3),"5000","15000","30000","60000"],ac=["250","500","1000"],Bp=["10s","20s","30s","45s"],kr=[I.EXIT,I.SYNC,I.HELP,I.EXPORT,I.CONFIG,I.YANK],Xi=[I.NEW,I.EDIT,I.DELETE,I.MOVE],sc=[I.TAG,I.UNTAG,I.ASSIGN,I.UNASSIGN,I.CLOSE_ISSUE,I.RE_OPEN_ISSUE,I.EDIT,I.COMMENT],_p=[I.FILTER,I.PEEK,I.REPLAY],vE={WORKSPACE:[...kr,...Xi],BOARD:[..._p,...kr,...Xi],SWIMLANE:[..._p,...kr,...Xi],TICKET:[...kr,...Xi,...sc],FIELD:[...kr,...sc],FIELD_LIST:[...kr,...sc],TEXT:[...kr],COMMENT:[I.EDIT,I.DELETE,I.YANK]},yE=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],ws=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&U(n)),Fp=e=>e.parentNodeId===we,bE=({selectedNode:e,breadCrumb:t})=>{let n=hE(e?.context);return ws({breadCrumb:t,selectedNode:e})?n.includes(Mt.DESCRIPTION)?n:[...n,Mt.DESCRIPTION]:n},xE=({selectedNode:e,breadCrumb:t})=>{let n=ws({breadCrumb:t,selectedNode:e});return n?[He.REF,He.TITLE,...n.props?.description?.trim()?[He.DESCRIPTION]:[],...hn(n).length>0?[He.TAGS]:[],...vn(n).length>0?[He.ASSIGNEES]:[]]:e?[He.REF,He.TITLE]:[]},lc=()=>{let e=Wi({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},IE=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Ns();if(!r)return[I.HELP,I.CONFIG];if(!rc())return[I.HELP,I.INIT,I.OPEN];if(t)return[I.HELP,I.PEEK,I.REPLAY,I.EXPORT,I.CONFIG,I.YANK];let o=e?.context,s=o&&fE.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?vE[u]:[]))],c=ws({breadCrumb:n,selectedNode:e});return i.filter(u=>u===I.MOVE?!1:u===I.YANK?!!(c??e):u===I.EDIT?s||!!c:u===I.DELETE?s:u===I.UNTAG?!!(c&&hn(c).length>0):u===I.UNASSIGN?!!(c&&vn(c).length>0):u===I.RE_OPEN_ISSUE?!!(c&&Fp(c)):u===I.CLOSE_ISSUE?!!(c&&!Fp(c)):!0)},We=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let s=t.context??"WORKSPACE";return{[I.NONE]:IE({breadCrumb:o,readOnly:r,selectedNode:n}),[I.EXIT]:["confirm"],[I.EXPORT]:[],[I.SYNC]:[],[I.INIT]:[],[I.OPEN]:e===I.OPEN?lc():[],[I.HELP]:[],[I.PEEK]:[...oc(),"now","prev","next"],[I.REPLAY]:[...oc()],[I.EDIT]:bE({selectedNode:n,breadCrumb:o}),[I.YANK]:xE({selectedNode:n,breadCrumb:o}),[I.COMMENT]:[],[I.DELETE]:["confirm"],[I.RE_OPEN_ISSUE]:["confirm"],[I.CLOSE_ISSUE]:["confirm"],[I.MOVE]:["start","confirm","next","previous","jump-next","jump-previous","to-next","to-previous","cancel"],[I.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[I.TAG]:[...new Set([...Object.keys(wi),...C.getExistingTags()])],[I.UNTAG]:[...zi()?.value?.map(({name:c})=>c)??[]],[I.UNASSIGN]:[...Vi()?.value?.map(({name:c})=>c)??[]],[I.ASSIGN]:C.getExistingAssignees(),[I.NEW]:yE(s),[I.CONFIG]:[...gE]}[e]??[]}});var $p,jp=g(()=>{"use strict";$p=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{accessSync as EE,copyFileSync as RE,existsSync as Ji,mkdirSync as Up,readdirSync as Hp,readFileSync as SE,renameSync as NE,rmSync as CE,statSync as Wp,unlinkSync as wE,writeFileSync as AE}from"node:fs";import mo from"node:path";var cc,Qe,Qi=g(()=>{"use strict";cc=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Qe={writeToFile:(e,t)=>{try{let n=mo.dirname(e);Ji(n)||Up(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);AE(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return SE(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Qe.readFile(e);return t===null?null:JSON.parse(t)}catch(t){return logger.error(`Failed to read JSON at ${e}:`,t),null}},dirExists:e=>{try{return Ji(e)&&Wp(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await EE(e),!0}catch{return!1}},mkDir:e=>Up(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=mo.parse(t);for(;;){let r=mo.join(t,e);try{if(Ji(r)&&Wp(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=mo.dirname(t)}return null},readFirstJSON(e){try{if(!Qe.dirExists(e))return null;let t=Hp(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=mo.join(e,t);return Qe.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Qe.dirExists(e)?Hp(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{wE(e)}catch(t){(!cc(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{CE(e,{recursive:!0,force:!0})}catch(t){(!cc(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(mo.dirname(t)),!n?.overwrite&&Ji(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{NE(e,t)}catch(r){if(cc(r)&&r.code==="EXDEV"){RE(e,t),this.rmFile(e);return}throw r}}}});import TE from"node:path";import{z as nn}from"zod";var kE,Gp,ME,zp,dc,uc,LE,yn,Vp,xt,Xn,bn=g(()=>{"use strict";yr();Sr();ee();N();Qi();kE={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},Gp=nn.object({logLevel:nn.enum(["info","error","debug"]),preferredEditor:nn.string().optional(),userName:nn.string().optional(),userId:nn.string().optional(),autoSync:nn.boolean().nullable().optional(),autoSyncDebounceMs:nn.number().optional(),attachmentMaxKb:nn.number().optional(),viewMode:nn.enum(["dense","wide"]).optional(),declinedEmailBoards:nn.array(nn.string()).optional()}).partial(),ME="config.json",zp=kn,dc=()=>TE.join(zp(),ME),uc=()=>{try{return Qe.mkDir(zp()),d(`Ensured ~/${Jt} exists`,null)}catch{return l(`Unable to create ~/${Jt}`)}},LE=e=>{let t;try{t=JSON.parse(e)}catch{return l(`Invalid ~/${Jt}/config.json JSON`)}let n=Gp.safeParse(t??{});return n.success?d("Parsed config",n.data):l(`Invalid ~/${Jt}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},yn=()=>{let e=uc();if(a(e))return l(e.message);let t=dc(),n=Qe.readFile(t);return n==null||n.trim()===""?d("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):LE(n)},Vp=e=>{let t=uc();if(a(t))return l(t.message);let n=Gp.safeParse(e);if(!n.success)return l(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=dc();try{return Qe.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
40
|
-
`),d("Config written",null)}catch{return l(`Unable to write ~/${Jt}/config.json`)}},xt=e=>{let t=yn();if(a(t))return l("Failed to read existing config");let n={...t.value,...e};return Vp(n)},Xn=()=>{let e=dc(),t=uc();if(a(t))return l(`Unable to create ~/${Jt}`);if(!(Qe.readFile(e)!==null)){let S=Vp(kE);if(a(S))throw new Error(`Unable to create ~/${Jt}/config.json`)}let r=yn();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,declinedEmailBoards:c,autoSync:u,autoSyncDebounceMs:p,attachmentMaxKb:m,logLevel:f,viewMode:h}=r.value,b=Cl({userId:i,userName:s});if(a(b))return l(b.message);let E=b.value??{userId:i,userName:s};return!E.userName||!E.userId?l(`User name or ID not configured in ~/${Jt}/config.json`):(process.env.EPIQ_LOG_LEVEL=f,d("successfully loaded settings",{gitEmail:null,gitName:null,declinedEmailBoards:c??[],logLevel:f??"debug",preferredEditor:o??"",userName:E.userName,userId:E.userId,autoSync:u??!1,autoSyncIntervalMs:p??1e4,attachmentMaxKb:m??null,viewMode:h??"dense"}))}});var Kp,Yp,mc,Xp=g(()=>{"use strict";Kp="/media/",Yp=e=>`${Kp}${e}`,mc=(e,t)=>`})`});import PE from"node:crypto";import pc from"node:fs";import DE from"node:path";var Dn,po,OE,_E,FE,Jp,fo=g(()=>{"use strict";Xt();N();ee();Xp();Dn=500,po=(e,t)=>`${e}.${t}`,OE=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?d("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?d("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")))?d("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"))?d("Sniffed image type","webp"):l(`Unsupported image format. Allowed: ${km.join(", ")}`),_E=e=>PE.createHash("sha256").update(e).digest("hex"),FE=(e,t=Dn)=>{if(e.length===0)return l("Attachment is empty");if(e.length>t*1024)return l(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=OE(e);return a(n)?n:d("Validated attachment data",{hash:_E(e),ext:n.value,bytes:e.length})},Jp=(e,t,n=Dn)=>{let r=FE(t,n);if(a(r))return r;let o=$i(e),s=DE.join(o,po(r.value.hash,r.value.ext));try{pc.existsSync(s)||(pc.mkdirSync(o,{recursive:!0}),pc.writeFileSync(s,t))}catch(i){return l(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return d("Wrote attachment blob",r.value)}});import BE from"zod";var As,Ts,Qp,fc=g(()=>{"use strict";bn();fo();N();ge();Ue();As=50,Ts=5e3,Qp=()=>{let e=fe().commandMeta.inputString,t=BE.coerce.number().int().min(As).max(Ts).safeParse(e);if(!t.success)return l(`Attachment size cap must be ${As}-${Ts} KB (default ${Dn})`);let n=xt({attachmentMaxKb:t.data});return a(n)?n:(ut({attachmentMaxKb:t.data}),d(`Attachment size cap set to ${t.data} KB`,null))}});var ot,On=g(()=>{"use strict";ot=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null});import{createHash as $E}from"node:crypto";var jE,UE,Zp,Te,Jn=g(()=>{"use strict";jE="0123456789ABCDEFGHJKMNPQRSTVWXYZ",UE=e=>{let t=$E("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+=jE[Number(n>>s&31n)]}return r},Zp=new Map,Te=(e,t)=>{let n=`${e}:virtual:${t}`,r=Zp.get(n);if(r!==void 0)return r;let o=UE(n);return Zp.set(n,o),o}});import ef from"chalk";var Re,_e,Fe,tf=g(()=>{"use strict";un();Je();Re=e=>ef.dim(e),_e=e=>ef.hex(T.primary)(e),Fe=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let m=[...t.filter(Boolean).filter(f=>f.startsWith(i))].sort((f,h)=>Ai(f)-Ai(h)).slice(0,r).map(f=>Ti(f)).join(" ");return m?`${Re(e)}${m}${Re(n)}`:""}});var Qn,Zi=g(()=>{"use strict";Qn={None:"none",Invalid:"invalid",Valid:"valid"}});import of from"chalk";var HE,nf,xe,WE,ae,K,ho,rf,ea,gc,qE,go,GE,zE,VE,KE,YE,sf,af=g(()=>{"use strict";Sr();wr();jp();lt();Xt();N();pe();Ue();fc();fo();wt();D();un();On();uo();Jn();tf();Ss();Ar();Zi();Pn();Cs();HE=["BOARD","TICKET","SWIMLANE"],nf=()=>{let e=v().selectedNode;if(!e?.context)return K({message:Re("Missing target context")});if(HE.includes(e.context))return ae();if(e.parentNodeId){let t=v().nodes[e.parentNodeId];if(t?.id===Te(t?.parentNodeId??"","comments"))return ae()}return K({message:Re("Command not available in this context")})},xe="<ENTER> to confirm",WE=()=>{let{userId:e}=de(),t=ke();return!e||a(t)?[]:Vn(t.value.emailLinks,e)},ae=(e="",t=[],n=!0)=>({message:n?Re(e):e,validity:Qn.Valid,completionWordList:t}),K=({message:e,completionWordList:t=[]})=>({validity:Qn.Invalid,message:e,completionWordList:t}),ho=e=>e.length===0,rf=(e,t)=>{let n=Ct(v().breadCrumb,"BOARD");if(a(n))return K({message:_e("Command is not applicable in this context")});let r=Tl(n.value.id);return a(r)?K({message:_e(`Unable to ${t}: board id is not a valid ULID`)}):Op({date:e,horizonDate:r.value})?null:K({message:_e(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},ea=e=>` ${of.hex("#000").bgHex(tt(e))(` ${e} `)} `,gc=({modifier:e})=>{let t="confirm";return e===t?ae(xe):K({message:ho(e)?Re("if you are certain, enter ")+Ti(t):"",completionWordList:[t]})},qE=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?K({message:Re(n)}):ae():K({message:ho(r)?t:"",completionWordList:[...e]}),go=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>ho(n)&&ho(r)?K({message:e,completionWordList:[]}):ae(t??xe),GE=({modifier:e,inputString:t})=>{let n=lc();return!ho(e)||!ho(t)?ae(xe):K({message:n.length?Re("number from the list, or a path"):Re("path to an epiq project"),completionWordList:n})},zE=({modifier:e,inputString:t})=>{let n=We(I.CONFIG);if(!n.includes(e))return K({message:Fe({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ye.EDITOR:{let r=[...$p];return t.trim()?r.includes(t.trim())?ae(xe):K({message:Fe({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):K({message:Fe({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ye.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?ae(xe):K({message:Fe({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ye.USERNAME:{let r=de().gitName,o=r?[r]:[],s=t.trim(),i=o.filter(p=>p.startsWith(s)),u=i.length===1&&i[0]===s?"":Fe({prefix:"name: ",wordList:o,inputString:s,minLengthForHints:0});return s?u?ae(`${u} ${Re(xe)}`,o,!1):ae(xe,o):K({message:u||_e("Enter a user name. Saved in ")+of.bgBlack("~/.epiq-global/config.json"),completionWordList:o})}case ye.EMAILS:{let r=de().gitEmail,o=co(),s=o.length>0||!r?o:[r],i=[...s,"none"],c=t.trim(),u=(E,S)=>K({message:Fe({prefix:E,wordList:i,noOfHints:3,inputString:S,minLengthForHints:0}),completionWordList:i});if(!c)return ae(`${xe} to see your addresses, or name one`,i);let p=c.split(/[,\s]+/).filter(Boolean),m=p[p.length-1]??"",f=E=>E==="none"||s.includes(E.toLowerCase()),h=E=>i.some(S=>S.startsWith(E.toLowerCase())),b=p.filter(E=>!f(E)&&!h(E));return b.length>0?K({message:_e(`no address here matches ${b.join(", ")} \u2014 pick one from the list, or its number`),completionWordList:i}):f(m)?ae(xe):u("",m)}case ye.EMAILS_UNCLAIM:{let r=WE(),o=t.trim();return r.length===0?K({message:_e("you have not claimed any addresses"),completionWordList:[]}):o&&r.includes(o.toLowerCase())?ae(xe):K({message:Fe({prefix:"give an address back ",wordList:r,noOfHints:3,inputString:o,minLengthForHints:0}),completionWordList:r})}case ye.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?ae(xe):K({message:Fe({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ye.AUTOSYNC:{let r=["on","off"],o=de().autoSync;if(!r.includes(t.trim())){let s=Mp(o);return K({message:Fe({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return ae(xe)}case ye.ATTACHMENT_MAX_KB:{let r=de().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<As||o>Ts){let s=Fe({prefix:" examples: ",wordList:ac,minLengthForHints:0,inputString:t});return K({message:_e(`provide a size cap in KB (${As}-${Ts}). current: ${r??Dn} KB.`)+s,completionWordList:ac})}return ae(xe)}case ye.SYNC_DEBOUNCE_MS:{let r=de().autoSyncIntervalMs,o=ro(t);if(!t.trim()||o===null){let s=Fe({prefix:" examples: ",wordList:ic,minLengthForHints:0,inputString:t});return K({message:_e(`provide a duration between ${3e3}ms and ${864e5}ms. current duration: ${r}ms.`)+s,completionWordList:ic})}return ae(xe)}default:return K({message:_e("Unknown config option"),completionWordList:n})}},VE=({modifier:e,inputString:t})=>{let n=We(I.EDIT);if(!n.length)return K({message:_e("Command not available in this context")});if(!n.includes(e)){let r=Fe({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return K({message:r||_e("Unknown edit option"),completionWordList:n})}switch(e){case Mt.COMMENT:return t.trim()?ae(xe):K({message:Re("write a comment...")});case Mt.TITLE:return ae(xe);case Mt.DESCRIPTION:{let{preferredEditor:r}=de();return r?ae(Re("<ENTER> to edit in ")+r):K({message:"No editor selected"})}default:return K({message:_e("Unknown edit option"),completionWordList:n})}},KE=({modifier:e})=>{let t=We(I.YANK);return t.length?t.includes(e)?ae(xe+Re(" and copy to clipboard")):K({message:Fe({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):K({message:_e("Nothing selected to copy from")})},YE={[I.EXPORT]:()=>ae(xe+Re(", and create export markdown file")),[I.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return ae(xe);let n={message:Re("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Tr(r);if(!r||!o)return K(n);let s=rf(o,"peek");return s||ae(xe)},[I.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Yi(e.modifier,e.inputString),r={message:Re("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Tr(t);if(!t||!o)return K(r);let s=rf(o,"replay");return s||(n&&Ki(n)===null?K({message:_e("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):ae("<ENTER> to replay board history",n?Bp:[]))},[I.EXIT]:()=>ae(xe+Re(" and exit the application")),[I.INIT]:()=>ae(xe),[I.OPEN]:GE,[I.PALETTE]:()=>ae(xe),[I.FILTER]:e=>{if(e.modifier==="clear")return ae(xe);let t=s=>We(I.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return K({message:Fe({wordList:We(I.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:We(I.FILTER)});let n=Object.values(v().tags).map(s=>s.name),r=Object.values(v().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?K({message:Fe({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):ae():K({message:Fe({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[I.NONE]:e=>{let t=We(I.NONE);return K({message:Fe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[I.NEW]:e=>qE({list:We(I.NEW),hint:Fe({wordList:We(I.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[I.HELP]:()=>ae(xe),[I.EDIT]:VE,[I.COMMENT]:e=>{let t=go({hint:Re(`write a comment (max ${4e3} char)...`),onOk:Re(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===Qn.Invalid?t:e.inputString.length>4e3?ae(_e("max input exceeded")):t},[I.CONFIG]:zE,[I.YANK]:KE,[I.DELETE]:e=>{let t=nf();return t.validity==="invalid"?t:gc(e)},[I.CLOSE_ISSUE]:e=>gc(e),[I.RE_OPEN_ISSUE]:e=>gc(e),[I.MOVE]:e=>{let t=nf();return t.validity==="invalid"?t:go({hint:Fe({prefix:"hey hacker! These commands are blocked for you... ",wordList:We(I.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[I.TAG]:e=>{let n=C.getExistingTags().slice(0,10).map(ea).join("");return go({hint:n.length?Re("create tag or reuse:")+n+Re(""):Re("create tag ...")})(e)},[I.UNTAG]:e=>{let t=zi();if(a(t))return K({message:_e("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(ea).slice(0,10);return n.length?go({hint:Re(" ... ")+n.join("")})(e):K({message:_e("Issue has no tags"),completionWordList:[]})},[I.ASSIGN]:e=>{let t=C.getExistingAssignees().map(ea).slice(0,10);return go({hint:Re("assignees... ")+t.join("")})(e)},[I.UNASSIGN]:e=>{let t=Vi();if(a(t))return K({message:_e("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(ea).slice(0,10);return n.length?go({hint:Re("remove assignee... ")+n.join("")})(e):K({message:_e("Issue has no assignees"),completionWordList:[]})},[I.SYNC]:()=>ae(xe)},sf=Object.fromEntries(Object.entries(YE).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]))});var ta,lf=g(()=>{"use strict";ta=["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 XE,JE,QE,ZE,eR,cf,df,uf,mf=g(()=>{"use strict";N();D();lf();XE=3,JE=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"]),QE=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},ZE=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=XE&&!JE.has(t)&&!/^\d+$/.test(t)),eR=e=>{let t=new Map;for(let s of QE(e))for(let i of ZE(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),r=new Set(n),o=ta.filter(s=>!r.has(s));return[...n,...o]},cf=ta,df=-1,uf=()=>{let e=ke();if(a(e))return ta;let t=e.value,n=t.eventLog.length;return n!==df&&(cf=eR(t),df=n),cf}});var pf,ff,hc=g(()=>{"use strict";Wm();Pn();Ar();af();mf();D();Oe();pf=e=>Object.values(I).includes(e),ff=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:u}=sf[n].validate(n,r,s),p=n!==I.PEEK&&n!==I.REPLAY,m=o==="command"||o==="modifier"?We(n):p?uf():[],{mode:f}=v(),h=f===x.COMMAND_LINE?i??"":"",b=[...u,...m];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:h,autoCompletion:t?Hm(e,b,u):{hint:"",hints:[],remainder:"",overlap:0}}}});var gf,tR,nR,rR,hf=g(()=>{"use strict";hc();Pn();gf=e=>{let t=e.trimStart(),n=nR(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=rR(e),c=pf(r)?r:null,u=c!==null,p=r!=="",m=c?We(c)??[]:[],f=c&&m.includes(o)?o:"",h="word";n.length===0||n.length===1&&!s?h="command":(n.length===1&&s||n.length===2&&!s)&&(h="modifier");let b=s?"":i,E=tR(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:p,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:h,inputToMatch:b,inputString:E}},tR=(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},nR=e=>e.trim()?e.trim().split(/\s+/):[],rR=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as iP}from"react";var vo,vc,Ms,yo,oR,vf,Ft,Ls,yc,bc,yf,bf,na,xf,ne,If,Ef,Rf,Sf,Nf,fe,ra,ge=g(()=>{"use strict";hc();hf();N();Zi();vo=e=>e===vc||e===":",vc=" ",Ms=40,yo={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Qn.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},oR=new Set,vf=()=>{for(let e of oR)e()},Ft=e=>{let n=e(yo),r=gf(n.value),o=n.cursorPosition===n.value.length;yo={...n,commandMeta:ff(r,o)},vf()},Ls=({message:e,status:t})=>{let n=structuredClone(yo);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,yo=n,vf(),d(e,null)},yc=e=>{Ft(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},bc=e=>{Ft(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&vo(n[o-1]);)o--;for(;o>0&&!vo(n[o-1]);)o--}else{for(;o<n.length&&!vo(n[o]);)o++;for(;o<n.length&&vo(n[o]);)o++}return{...t,cursorPosition:o}})},yf=()=>{Ft(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},bf=()=>{Ft(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&vo(t[r-1]);)r--;for(;r>0&&!vo(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},na=e=>{Ft(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},xf=()=>{Ft(e=>({...e,commandIsPending:!0}))},ne=e=>{Ft(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},If=({addToHistory:e=!0,line:t})=>{Ft(n=>{let r=t??n.value;return{...n,commandHistory:e&&r.trim()?[r,...n.commandHistory].slice(0,Ms):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}})},Ef=e=>{Ft(t=>({...t,commandHistory:e.slice(0,Ms),commandHistoryIndex:-1}))},Rf=()=>{Ft(e=>e.commandHistoryIndex===-1?e:{...e,commandHistoryIndex:-1})},Sf=()=>{Ft(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Nf=()=>{Ft(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},fe=()=>yo,ra=()=>{let[e,...t]=yo.value.split(vc);return t.join(vc).trim()}});var P,hP,Kn=g(()=>{"use strict";Oe();Pm();D();ge();Ue();P={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavPreviousItemJump:"navPreviousItemJump",NavNextItemJump:"navNextItemJump",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MovePreviousItemJump:"movePreviousItemJump",MoveNextItemJump:"moveNextItemJump",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",OpenInEditor:"openInEditor",MarkDiffLine:"markDiffLine",CommentOnDiffLine:"commentOnDiffLine",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"},hP={[P.NavPreviousItem]:P.NavPreviousItemJump,[P.NavNextItem]:P.NavNextItemJump,[P.MovePreviousItem]:P.MovePreviousItemJump,[P.MoveNextItem]:P.MoveNextItemJump}});function Cf(e){return!e||!iR.test(e)?l(`Invalid hex rank: ${e}`):d("Converted rank to bigint",BigInt("0x"+e))}function Lt(e,t=Ps){if(e<0n)return l("Negative rank not allowed");let n=e.toString(16);return d("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function pt(e,t){if(!e&&!t)return Lt(rn/2n,Ps);let n=e?Cf(e):d("Resolved lower bound",0n);if(a(n))return n;let r=t?Cf(t):d("Resolved upper bound",rn);if(a(r))return r;let o=n.value,s=r.value;if(s<=o)return l("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?l("No rank space available between neighbors"):Lt(i,Ps)}function wf(e){if(e<=0)return d("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=rn*BigInt(r+1)/(t+1n),s=Lt(o,Ps);if(a(s))return s;n.push(s.value)}return d("Resolved evenly spaced ranks",n)}var Ps,sR,rn,iR,bo=g(()=>{"use strict";N();Ps=24n,sR=Ps*4n,rn=(1n<<sR)-1n,iR=/^[0-9a-f]+$/});var O,Af,Bt=g(()=>{"use strict";O=({userId:e})=>({userId:e}),Af=e=>({action:e.action,payload:e.payload})});var xc,wP,$t=g(()=>{"use strict";Bt();xc=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","tombstone.tag","restore.tag","create.contributor","rename.contributor","tombstone.contributor","restore.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","move.node","edit.description","add.issue.comment","edit.issue.comment","delete.issue.comment","add.issue.attachment","delete.issue.attachment","close.issue","reopen.issue","lock.node","rebalance.children","link.contributor.user","link.contributor.email","unlink.contributor.email"],wP=new Set(xc)});import{ulid as aR}from"ulid";var Ic,Tf=g(()=>{"use strict";N();jt();bo();$t();Ic=(e,t)=>{let n=Me(e),r=wf(n.length);if(a(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],c=r.value[s];if(!i||!c)return l("Unable to assign rebalance rank");o[i.id]=c}return d("Created rebalance event",{id:aR(),action:"rebalance.children",payload:{parent:e,ranks:o},...O(t)})}});import{z as Lr}from"zod";var kf,Mf,lR,UP,cR,dR,Lf,uR,mR,Ec,Pf,Rc,Ds=g(()=>{"use strict";N();kf=1,Mf=Lr.tuple([Lr.string().min(1),Lr.string().min(1).nullable()]),lR=Lr.looseObject({v:Lr.literal(kf),id:Mf}),UP=Lr.looseObject({v:Lr.number().int().positive(),id:Mf}),cR=e=>Object.prototype.hasOwnProperty.call(e,"__proto__"),dR=e=>{let t={};for(let n of Object.keys(e))n!=="__proto__"&&(t[n]=e[n]);return t},Lf=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return l("Invalid persisted event envelope: expected an object");let{v:t,id:n}=e;if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return l("Invalid persisted event envelope: v");if(!Array.isArray(n)||n.length!==2)return l("Invalid persisted event envelope: id");let[r,o]=n;return typeof r!="string"||r.length===0?l("Invalid persisted event envelope: id.0"):o!==null&&(typeof o!="string"||o.length===0)?l("Invalid persisted event envelope: id.1"):d("Parsed persisted event envelope",cR(e)?dR(e):e)},uR=[1],mR=new Set(uR),Ec=e=>mR.has(e),Pf=e=>{let t=lR.safeParse(e);return t.success?d("Parsed persisted event",t.data):l(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Rc=(e,t)=>{let n={[e.action]:e.payload,v:kf,id:t};return Pf(n)}});import Sc from"node:fs";import pR from"node:path";var Os,Nc,Cc,Pr,Df,wc,Zn,Of,_f,Ff,xo=g(()=>{"use strict";ee();Os=e=>e?.code==="ENOENT",Nc=3,Cc=e=>Sc.readdirSync(e).filter(t=>t.endsWith(".jsonl")).sort(),Pr=e=>{let t=bt(e);for(let n=1;;n++){if(!Sc.existsSync(t))return"none";let r=[],o=!1;for(let s of Cc(t))try{let{size:i,mtimeMs:c}=Sc.statSync(pR.join(t,s));r.push(`${s}:${i}:${c}`)}catch(i){if(!Os(i))throw i;if(n<Nc){o=!0;break}}if(!o)return r.join("|")}},Df=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),wc=(e,t,n)=>{let r=Df(t),o=Pr(e),s=Df(o);for(let[i,c]of s)if(i!==n&&r.get(i)!==c)return null;for(let i of r.keys())if(i!==n&&!s.has(i))return null;return o},Zn=null,Of=e=>Zn&&Zn.root===e?Zn.signature:null,_f=(e,t)=>{Zn={root:e,signature:t}},Ff=(e,t)=>{if(!Zn||Zn.root!==e)return;let n=wc(e,Zn.signature,t);Zn=n===null?null:{root:e,signature:n}}});import Be from"node:fs";import Dr from"node:path";import{ulid as fR}from"ulid";var sa,Ac,$f,jf,ia,gR,Tc,Or,_s,Uf,hR,vR,Hf,yR,Wf,bR,qf,xR,oa,Bf,aa,_r=g(()=>{"use strict";N();ee();sa="~pending",Ac=/~pending(-[0-9a-z]+)*$/i,$f=/-f(\d+)$/,jf=e=>{let t=e.indexOf(".");return t===-1?`${e}${sa}`:e.slice(0,t)+sa+e.slice(t)},ia=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},gR=e=>{let[t,n]=ia(e);return Ac.test(t)?t.replace(Ac,"")+n:null},Tc=e=>e.replace(Ac,""),Or=e=>e.endsWith(".jsonl")&&gR(e)!==null,_s=e=>Tc(ia(e)[0]),Uf=e=>{let[t]=ia(e),n=$f.exec(t);return n&&Or(e)?Number(n[1]):null},hR=e=>jf(e).replace(sa,`${sa}-${fR().toLowerCase()}`),vR=(e,t)=>{let[n,r]=ia(e);return`${n.replace($f,"")}-f${t}${r}`},Hf=(e,t)=>Dr.join(bt(e),jf(t)),yR=(e,t)=>Math.max(0,Be.statSync(e).size-(Uf(t)??0)),Wf=e=>{let t=bt(e);try{return Be.existsSync(t)?Be.readdirSync(t).filter(Or).some(n=>yR(Dr.join(t,n),n)>0):!1}catch{return!0}},bR=3,qf=(e,t)=>{for(let n=1;;n++){let r=Be.openSync(e,"a"),o;try{Be.writeSync(r,t),o=Be.fstatSync(r).ino}finally{Be.closeSync(r)}let s;try{s=Be.statSync(e).ino}catch{s=null}if(s===o||n>=bR)return}},xR=e=>{let t;try{t=Be.openSync(e,"r")}catch{return!0}try{let{size:n}=Be.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return Be.readSync(t,r,0,1,n-1),r[0]===10}finally{Be.closeSync(t)}},oa=10,Bf=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(oa)+1;if(r===0)return{bytes:0,lines:0};let o=t.subarray(0,r);if(o.toString("utf8").trim().length===0)return{bytes:r,lines:0};Be.appendFileSync(e,Buffer.concat([Buffer.from(xR(e)?"":`
|
|
41
|
-
`),o,Buffer.from(o[o.length-1]===
|
|
42
|
-
`)]));let s=0;for(let i of o)i===
|
|
43
|
-
`).entries()){let h=f.trim();if(!h)continue;let b;try{b=JSON.parse(h)}catch{p(m+1,"invalid JSON");continue}let
|
|
44
|
-
`),i&&(i.current=h);let S=Oc.basename(m);return e.advanceEdgeRef(s,S,h),Ff(s,S),d("Event persisted",{path:m,entry:E.value})}catch(u){let p=u instanceof Error?u.message:"Unknown persist error";return l(`Failed to persist event: ${p}`)}}return{mintEventId:n,persist:r}}});var ig,ag=g(()=>{"use strict";N();ig=(e,t,n)=>{function r(s,i,c){let u=n.mintEventId(i,c);if(a(u))return l(u.message);let p={...s,id:u.value[0]},m=t.materialize(p);if(m.status!==An.Success)return m;let f=n.persist({event:p,rootDir:i,edge:c,id:u.value});return a(f)?f:m}function o(s,i){if(s.length===0||!s[0])return l("No events provided");let c=e.write.readOnlyReason();if(c)return l(c);let u=e.replay.batch(()=>{let p={},m=e.write.beforeWrite(s[0],b=>r(b,i,p));if(a(m))return l(m.message);let f=s.map(b=>r(b,i,p)),h=f.filter(a);return h.length>0?l("Materialize and persist failed: "+h.map(b=>b.message).join(", ")):d("Materialization succeeded",f.map(b=>b.value))});return a(u)?l(u.message):u.value??l("Materialize and persist produced nothing")}return{materializeAndPersist:r,materializeAndPersistAll:o}}});var lg,cg=g(()=>{"use strict";Dc();ma();pa();ag();lg=e=>{let t=Zf(e),n=Qf(e),r=sg(n),o=ig(e,t,r);return{...t,...n,...r,...o}}});import{z as re}from"zod";var Y,on,or,fa,_c,$R,dg,ug=g(()=>{"use strict";N();Y=re.string().min(1),on=re.string(),or=re.string(),fa=re.looseObject({id:Y}),_c=re.looseObject({id:Y,name:on,parent:Y,rank:or}),$R={"init.workspace":re.looseObject({id:Y,name:on,rank:or}),"add.workspace":re.looseObject({id:Y,name:on,rank:or}),"add.board":_c,"add.swimlane":_c,"add.issue":_c,"add.field":re.looseObject({id:Y,name:on,parent:Y,rank:or}),"edit.title":re.looseObject({id:Y,name:on}),"delete.node":fa,"lock.node":fa,"move.node":re.looseObject({id:Y,parent:Y,rank:or}),"edit.description":re.looseObject({id:Y,md:re.string()}),"close.issue":re.looseObject({id:Y,parent:Y,rank:or}),"reopen.issue":re.looseObject({id:Y,parent:Y,rank:or}),"create.tag":re.looseObject({id:Y,name:on}),"tombstone.tag":fa,"restore.tag":re.looseObject({id:Y,name:on}),"create.contributor":re.looseObject({id:Y,name:on}),"rename.contributor":re.looseObject({id:Y,name:on}),"tombstone.contributor":fa,"restore.contributor":re.looseObject({id:Y,name:on}),"link.contributor.user":re.looseObject({contributor:Y}),"link.contributor.email":re.looseObject({contributor:Y,email:Y}),"unlink.contributor.email":re.looseObject({contributor:Y,email:Y}),"add.issue.assignee":re.looseObject({id:Y,assignee:Y}),"remove.issue.assignee":re.looseObject({id:Y,assignee:Y}),"add.issue.tag":re.looseObject({id:Y,tag:Y}),"remove.issue.tag":re.looseObject({id:Y,tag:Y}),"add.issue.comment":re.looseObject({id:Y,issue:Y,md:re.string()}),"edit.issue.comment":re.looseObject({id:Y,issue:Y,md:re.string()}),"delete.issue.comment":re.looseObject({id:Y,issue:Y}),"add.issue.attachment":re.looseObject({id:Y,issue:Y,hash:re.string().min(1),ext:re.string().min(1),name:on,bytes:re.number()}),"delete.issue.attachment":re.looseObject({id:Y,issue:Y}),"rebalance.children":re.looseObject({parent:Y,ranks:re.record(re.string(),or)})},dg=(e,t)=>{let r=$R[e].safeParse(t);return r.success?d("Payload is readable",void 0):l(`${e}: ${r.error.issues.map(o=>`${o.path.join(".")||"payload"} ${o.message}`).join(", ")}`)}});import{ulid as jR}from"ulid";var mg,pg=g(()=>{"use strict";N();pe();Ue();mg=(e,t)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return d("Contributor write already in flight",void 0);let{userId:n,userName:r}=de();if(!r||n!==e.userId)return d("Not this actor own write",void 0);let o=C.getContributor(e.userId),s={id:jR(),action:o?"rename.contributor":"create.contributor",payload:{id:e.userId,name:r},userId:e.userId};if(o&&(o.tombstoned||o.name===r))return d("Contributor name is current",void 0);let i=t(s);return a(i)?l(i.message):d("Contributor name recorded",void 0)}});var Ae,Eo=g(()=>{"use strict";Ae={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",DIFF:"Diff",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var V,$s,ft=g(()=>{"use strict";V=e=>e.slice(-7).toUpperCase(),$s=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?V(e).includes(n):!0}});var $e,sr=g(()=>{"use strict";me();ft();$e={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:ie.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:V(e)},context:ie.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:ie.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:ie.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:ie.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:V(e)},context:ie.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0,disabled:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:i?{disabled:!0}:{},context:ie.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:ie.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})}});var js,fg,gg=g(()=>{"use strict";me();N();Eo();wt();pe();sr();D();ma();tn();js=(e,t,n)=>C.getNode(e)?B(`a node with id ${e} already exists`,n):t===e?B("a node cannot be its own parent",n):null,fg={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=$e.workspace(t,n,r),s=Us(o);if(a(s))return ua(s.message,e);let i=C.createNode(o);return a(i)?B(i.message??"Failed to initialize workspace",e):_l(i.value)?d("Workspace initialized",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=js(t,void 0,e);if(o)return o;let s=C.createNode($e.workspace(t,n,r));return a(s)?B(s.message??"Failed to add workspace",e):_l(s.value)?d("Added workspace",{action:e.action,result:s.value}):l("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=js(t,r,e);if(s)return s;let i=C.createNode($e.board(t,n,r,o));return a(i)?B(i.message??"Unable to create board",e):Ir(i.value)?d("Added board",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=js(t,r,e);if(s)return s;let i=C.createNode($e.swimlane(t,n,r,o));return a(i)?B(i.message??"Unable to create swimlane",e):xr(i.value)?d("Added swimlane",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=js(t,r,e);if(s)return s;let i=C.createNode($e.ticket(t,n,r,o));return a(i)?B(i.message??"Unable to create issue",e):U(i.value)?d("Added issue",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=js(t,r,e);if(i)return i;let c=C.createNode($e.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(Ae.DESCRIPTION)?"vertical":"horizontal"}));return a(c)?B(c.message??`Unable to create field: ${n}`,e):nt(c.value)?d("Added field",{action:e.action,result:c.value}):l("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!C.getNode(t))return B(`Unable to locate node with id ${t}`,e);let o=C.renameNode(t,n);return a(o)?B(o.message??"Unable to edit title",e):d("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=C.tombstoneNode(t);return a(n)?B(n.message??"Unable to delete node",e):d("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=C.createTag({id:t,name:n});return a(r)?B(r.message??"Unable to create tag",e):d("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=C.tombstoneTag(t);return a(n)?B(n.message??"Unable to delete tag",e):d("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=C.restoreTag(t,n);return a(r)?B(r.message??"Unable to restore tag",e):d("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=C.createContributor({id:t,name:n});return a(r)?B(r.message??"Unable to create contributor",e):d("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=C.renameContributor(t,n);return a(r)?B(r.message??"Unable to rename contributor",e):d("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=C.tombstoneContributor(t);return a(n)?B(n.message??"Unable to remove contributor",e):d("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,r=C.restoreContributor(t,n);return a(r)?B(r.message??"Unable to restore contributor",e):d("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=C.tag(t,n);return a(r)?B(r.message??"Unable to tag issue",e):d("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=C.untag(t,n);return a(r)?B(r.message??"Unable to untag issue",e):d("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=C.assign(t,n);return a(r)?B(r.message??"Unable to assign issue",e):d("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=C.unassign(t,n);return a(r)?B(r.message??"Unable to unassign issue",e):d("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=C.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?B(o.message??"Failed to move node",e):d("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=C.editValue(t,n);return a(r)?B(r.message??"Unable to edit description",e):d("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=C.getNode(t);if(!o)return B("Unable to locate issue",e);if(!U(o))return B("Can only close issues",e);let s=C.getNode(we);if(!s)return B("Unable to locate target swimlane",e);if(n!==s.id)return B("Close target must be closed swimlane",e);let i=C.moveNodeToRank({id:t,parentId:n,rank:r});return a(i)?B(i.message??"Unable to close issue",e):d("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=C.getNode(t);if(!o)return B("Unable to locate issue",e);if(!U(o))return B("Can only reopen issues",e);let s=C.getNode(we);if(!s)return B("Unable to locate closed swimlane",e);if(n===s.id)return B("Cannot reopen issue into closed swimlane",e);if(!C.getNode(n))return B("Reopen parent no longer exists",e);let c=C.moveNodeToRank({id:t,parentId:n,rank:r});return a(c)?B(c.message??"Unable to reopen issue",e):d("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=C.lockNode(t);return a(n)?B(n.message??"Unable to lock node",e):d("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let s=C.getNode(r);if(!s)return B(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return B(`Node ${r} is not child of ${t}`,e);let i=C.updateNode({...s,rank:o});if(a(i))return B(i.message??"Unable to rebalance child",e)}return d("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=C.createComment({id:t,issue:n,authorId:r,md:o,deleted:!1});return a(s)?B(s.message??"Unable to add comment",e):d("Comment added",{action:e.action,result:{id:t,issue:n,author:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=e.payload,o=C.getComment(t);if(!o)return B("Unable to locate comment",e);if(o.issue!==n)return B("Comment does not belong to issue",e);let s=C.editComment(t,r);return a(s)?B(s.message??"Unable to edit comment",e):d("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=C.getComment(t);if(!r)return B("Unable to locate comment",e);if(r.issue!==n)return B("Comment does not belong to issue",e);let o=C.deleteComment(t);return a(o)?B(o.message??"Unable to delete comment",e):d("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:r,ext:o,name:s,bytes:i}=e.payload,c=C.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return a(c)?B(c.message??"Unable to add attachment",e):d("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=C.getAttachment(t);if(!r)return B("Unable to locate attachment",e);if(r.issue!==n)return B("Attachment does not belong to issue",e);let o=C.deleteAttachment(t);return a(o)?B(o.message??"Unable to delete attachment",e):d("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.email":e=>{let{contributor:t,email:n}=e.payload;if(!zn(n))return B(`not an email address: ${n}`,e);let r=C.linkContributorEmail({email:n,contributor:t,authorId:e.userId});return a(r)?B(r.message??"Unable to link email",e):d("Email linked to contributor",{action:e.action,result:r.value})},"unlink.contributor.email":e=>{let{contributor:t,email:n}=e.payload,r=C.unlinkContributorEmail(n,t,e.userId);return a(r)?B(r.message??"Unable to unlink email",e):d("Email unlinked from contributor",{action:e.action,result:r.value})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=C.linkUserId({contributorId:t,userId:e.userId});return a(n)?B(n.message??"Unable to link contributor",e):d("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}}});var hg,vg,UR,HR,Fc,WR,_n,qR,yg,Bc=g(()=>{"use strict";me();N();pe();D();$c();hg=e=>{let t=C.getNode(e);if(!t||!U(t)||t.isDeleted)return null;let n=ha(t);return a(n)?n:null},vg=e=>{if(!va())return null;for(let t of e){let n=hg(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=hg(r);if(o)return o}return null},UR=(e,t)=>{let n=C.getNode(e);n&&C.updateNode({...n,log:[...n.log??[],t]})},HR=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},Fc=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 HR(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":case"link.contributor.email":case"unlink.contributor.email":default:return[]}},WR=e=>{Pe(t=>({...t,eventLog:[...t.eventLog,e]}))},_n=null,qR=e=>{for(let[t,n]of e.nodeLog){let r=C.getNode(t);r&&C.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&Pe(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),vg([...e.virtualNodeIds])},yg={isInitialized:()=>Ut(),batch:e=>ga(e),afterApply(e,{batched:t,bypassLogging:n}){let r=[...new Set(Fc(e))];if(t){_n??={appLog:[],nodeLog:new Map,virtualNodeIds:new Set};for(let o of r){if(!n){let s=_n.nodeLog.get(o);s?s.push(e):_n.nodeLog.set(o,[e])}if(va()){_n.virtualNodeIds.add(o);let s=v().nodes[o]?.parentNodeId;s&&_n.virtualNodeIds.add(s)}}return n||_n.appLog.push(e),null}return n||(r.forEach(o=>UR(o,e)),WR(e)),vg(r)},flush(){if(!_n)return null;let e=_n;return _n=null,qR(e)}}});var he,bg=g(()=>{"use strict";N();Ue();yr();he=()=>{let{userName:e,userId:t}=de();return e?t?Ni(t)?ss(e)?d("Successfully resolved actor ID",{userId:t,userName:e}):l("Invalid user name in config"):l("Invalid user ID in config"):l("User ID not configured"):l("User name not configured")}});var GR,zR,Hs,Fn,V0,K0,sn,xg,Fr,Br,jc,Y0,X0,J0,Q0,Uc,Z0,Ig,eO,_,$=g(()=>{"use strict";Ds();cg();ug();D();pg();$t();gg();Bc();bg();Ds();Dc();ma();pa();GR={genesis:"init.workspace",actions:xc,readPayload:dg,apply:fg,replay:yg,write:{readOnlyReason:()=>{let e=v();return e.readOnly?e.readOnlyReason??"Cannot change the board while time travelling":null},beforeWrite:mg}},zR=lg(GR),{materialize:Hs,materializeAll:Fn,fromPersistedEvent:V0,decodeReconstructedEvents:K0,loadMergedEventsWithUnreadable:sn,loadEventActors:xg,loadActorNames:Fr,loadMergedEvents:Br,loadMergedEventsBefore:jc,getEdgeRef:Y0,advanceEdgeRef:X0,clearEdgeCache:J0,getSortedEvents:Q0,loadEffectiveEventTimes:Uc,mintEventId:Z0,persist:Ig,materializeAndPersist:eO,materializeAndPersistAll:_}=zR});var $r,Hc,Eg=g(()=>{"use strict";ft();$r=e=>e.trim().toLocaleLowerCase(),Hc=(e,t)=>$r(e).includes($r(t))});var VR,KR,Rg,Sg,YR,XR,Ng,Cg=g(()=>{"use strict";D();ft();Eg();VR=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},KR=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},Rg=null,Sg=new Map,YR=()=>{let e=v().eventLog??[];if(e===Rg)return Sg;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 Rg=e,Sg=t,t},XR=e=>{let{contributors:t}=v(),n=YR().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},Ng=(e,t)=>{let n=$r(t.value);if(!n)return!0;switch(t.target){case"title":return Hc(e.title??"",n);case"description":return Hc(e.props.description??"",n);case"tag":return VR(e).map($r).some(o=>o.includes(n));case"assignee":return KR(e).map($r).some(o=>o.includes(n));case"actor":return XR(e).map($r).some(o=>o.includes(n));case"ref":return $s(e.id,t.value);default:return!0}}});var Wc,JR,wg,Ag,Tg,qc=g(()=>{"use strict";me();Cg();Wc=(e,t)=>e.rank<t.rank?-1:e.rank>t.rank?1:0,JR=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,wg=(e,t)=>Object.values(e).filter(n=>JR(n,t)).sort(Wc),Ag=(e,t)=>{let n={};for(let r of Object.values(e)){if(U(r)&&t.length>0&&!t.every(s=>Ng(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(Wc);return n},Tg=(e,t)=>{let n={};for(let r of Object.values(e)){if(!r.parentNodeId||r.isDeleted||!t.has(r.parentNodeId))continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(Wc);return n}});var kg,ya,Me,Mg,Lg,xn,Bn,jt=g(()=>{"use strict";Tf();$();N();D();qc();bo();kg=e=>ya(Me(e),{at:"end"}),ya=(e,t={at:"end"})=>{let n=o=>a(o)?d("Rank space exhausted",{rank:"",needsRebalance:!0}):d("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(pt(void 0,void 0));let r=()=>n(pt(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(pt(void 0,o.rank)):l("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(pt(o.rank,void 0)):l("Unable to resolve last sibling")}case"before":{let o=Mg(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o>0?e[o-1]:void 0;return n(pt(i?.rank,s.rank))}case"after":{let o=Mg(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o<e.length-1?e[o+1]:void 0;return n(pt(s.rank,i?.rank))}}},Me=e=>{let t=v();if(!Pg()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return wg(t.nodes,e)},Mg=(e,t)=>e.findIndex(n=>n.id===t),Lg=(e,t,n={at:"end"})=>ya(Me(t).filter(r=>r.id!==e),n),xn=(e,t,n,r,o)=>{let s=Lg(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return d("Resolved rank",s.value.rank);let i=Ic(e,r);if(a(i))return i;let c=_([i.value],o);if(a(c))return c;let u=Lg(t,e,n);return a(u)?u:u.value.needsRebalance?l("Rank rebalance failed to create space"):d("Resolved rank after rebalance",u.value.rank)},Bn=(e,t,n)=>{let r=kg(e);if(a(r))return r;if(!r.value.needsRebalance)return d("Resolved rank",r.value.rank);let o=Ic(e,t);if(a(o))return o;let s=_([o.value],n);if(a(s))return s;let i=kg(e);return a(i)?i:i.value.needsRebalance?l("Rank rebalance failed to create space"):d("Resolved rank after rebalance",i.value.rank)}});var Ws,H,Dg,Og,_g,It=g(()=>{"use strict";D();Ws=5,H={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=be(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||H.navigate({contextNode:o,selectedIndex:be(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=be(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;H.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Dg(1),navigateToPreviousItem:()=>Dg(-1),jumpToNextItem:()=>Og(Ws),jumpToPreviousItem:()=>Og(-Ws),navigateToNextContainer:()=>_g(1),navigateToPreviousContainer:()=>_g(-1),navigate:({contextNode:e,selectedIndex:t})=>{A({contextNodeId:e.id,selectedIndex:t})}},Dg=e=>{let{selectedIndex:t,contextNode:n}=v(),r=be(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;H.navigate({selectedIndex:s,contextNode:n})},Og=e=>{let{selectedIndex:t,contextNode:n}=v(),r=be(n.id).length;if(r===0)return;let o=Math.max(0,t),s=Math.min(Math.max(o+e,0),r-1);H.navigate({selectedIndex:s,contextNode:n})},_g=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=be(o.id),i=s.findIndex(h=>h.id===t.id);if(i<0)return;let c=s.at(i+e)??s.at(0);if(!c)return;let u=be(c.id),p=Math.max(0,u.length-1),m=Math.min(Math.max(0,r),p),f=u.length?m:-1;H.navigate({contextNode:c,selectedIndex:f})}});var Bg,$g,QR,ba,jg,Fg,ZR,Ug,Hg=g(()=>{"use strict";me();N();jt();D();It();Bg=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),$g=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},QR=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&&nt(t)&&t.childRenderAxis==="vertical"},ba=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=Me(r.id);return H.navigate({contextNode:r,selectedIndex:Bg(t,o.length)}),!0},jg=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return ba(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=Me(o.id).findIndex(c=>c.id===n.id);return i>=0?(H.navigate({contextNode:o,selectedIndex:i}),!0):jg(o.id)},Fg=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),jg(n))return!0;n=t[n]?.parentNodeId}return!1},ZR=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},Ug=e=>{let{nodes:t,rootNodeId:n}=v();if(QR(e.contextNodeId)&&ba(e.contextNodeId,e.selectedIndex))return d("Restored navigation inside text container",null);if(ZR(e.selectedNodeId)&&e.selectedNodeId&&Fg(e.selectedNodeId))return d("Restored navigation to selected node or ancestor",null);if(ba(e.contextNodeId,e.selectedIndex))return d("Restored navigation to previous container",null);if(e.parentNodeId&&ba(e.parentNodeId,e.selectedIndex))return d("Restored navigation to previous parent",null);if(Fg(e.contextNodeId))return d("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return l("Unable to restore navigation");let o=Me(r.id);return H.navigate({contextNode:r,selectedIndex:Bg(e.selectedIndex,o.length)}),d("Restored navigation to root",null)}});import{monotonicFactory as eS,ulid as In}from"ulid";function tS(){let e=ke();if(a(e))return l("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return l("No workspace found in event log");let[r]=be(n.id),[o]=r?be(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return d("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?d("Resolved boot nav target",{contextNode:r,selectedIndex:0}):d("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function nS(){let e=tS();return a(e)?e:H.navigate(e.value)}function Wg({userId:e,userName:t}){let n=qs(),r=qs(),o=qs(),s=qs(),i=qs(),c=pt(void 0,void 0);if(a(c))return c;let u=pt(void 0,void 0);if(a(u))return u;let p=pt(u.value,void 0);if(a(p))return p;let m=pt(void 0,void 0);if(a(m))return m;let f=pt(m.value,void 0);if(a(f))return f;let h=pt(f.value,void 0);if(a(h))return h;let b=pt(void 0,void 0);return a(b)?b:d("Created default events",[{id:In(),userId:e,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:In(),userId:e,action:"create.contributor",payload:{id:e,name:t}},{id:In(),userId:e,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:In(),userId:e,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:m.value}},{id:In(),userId:e,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:In(),userId:e,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:h.value}},{id:In(),userId:e,action:"add.board",payload:{id:Gi,name:"Closed",parent:n,rank:p.value}},{id:In(),userId:e,action:"add.swimlane",payload:{id:we,name:"Closed",parent:Gi,rank:b.value}},{id:In(),userId:e,action:"lock.node",payload:{id:Gi}},{id:In(),userId:e,action:"lock.node",payload:{id:we}}])}function En(e,t=[]){if(rS())return d("Skipped boot while checked out at a historical point",null);if(!e.length){let s=$e.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=Us(s);return a(i)?i:(A({hasProjectDefinition:!1,mode:x.DEFAULT}),d("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return l("Initialized Epiq project has no workspace init event");let n=Fn(e),{fatal:r,skipped:o}=tr(n);return r.length>0?l(`Materializing failed:
|
|
36
|
+
`).filter(Boolean).filter(i=>i!==lt);if(r.length===0)return d("State branch is storage-only",!1);let o=await W({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(l(o))return a(`Failed to clean storage branch
|
|
37
|
+
${o.message}`);let s=await io({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:r});return l(s)?a(s.message):d("Cleaned storage branch",!0)},Lt=Ul(async(e=process.cwd())=>{let t=await W({args:["rev-parse","--show-toplevel"],cwd:e});return l(t)?a("Not inside a Git repository"):d("Resolved repo root",t.value.stdout.trim())},e=>bt.resolve(e)),bM=Ul(async e=>{let t=await W({args:["rev-parse","--git-dir"],cwd:e});if(l(t))return a(t.message);let n=t.value.stdout.trim(),r=bt.isAbsolute(n)?n:bt.join(e,n);return d("Resolved git dir",r)},e=>bt.resolve(e))});import xs from"node:fs";import vn from"node:path";var CM,lt,Pn,tc,JI,wr,ao,xt,Ui,Ip,QI,Is,_i,ZI,Ne,Ep,xe,Q=g(()=>{"use strict";N();nt();Oi();CM=process.env.IS_LOCAL==="true",lt=".epiq",Pn="events",tc="media",JI="project.json",wr=e=>vn.join(e,lt),ao=e=>vn.join(wr(e),JI),xt=e=>vn.join(wr(e),Pn),Ui=e=>vn.join(wr(e),tc),Ip=e=>vn.join(e,lt),QI=e=>{let t=vn.join(e,lt);return xs.existsSync(t)&&xs.statSync(t).isDirectory()},Is=e=>{let t=ao(e);return xs.existsSync(t)&&xs.statSync(t).isFile()},_i=e=>{let t=vn.resolve(e);for(;;){if(QI(t))return d("Resolved closest .epiq root",t);let n=vn.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},ZI="No .epiq/project.json found in any parent",Ne=e=>{let t=vn.resolve(e);for(;;){if(Is(t))return d("Resolved closest epiq project root",t);let n=vn.dirname(t);if(n===t)return a(ZI);t=n}},Ep=e=>{let t=xt(e);try{return xs.mkdirSync(t,{recursive:!0}),d("Resolved events dir",t)}catch(n){return a(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},xe=async()=>{let e=await Lt(process.cwd());if(l(e))return e;let t=be({repoRoot:e.value});return l(t)?t:d("Resolved persist root",t.value)}});import Es from"node:fs";import{ulid as eE}from"ulid";import{z as Hi}from"zod";var tE,nE,Wi,Mt,hn,nc,rn=g(()=>{"use strict";N();Q();tE="__epiq_state__",nE=Hi.object({projectId:Hi.string().min(1),stateBranch:Hi.string().min(1),createdAt:Hi.iso.datetime()}),Wi=()=>({projectId:eE(),stateBranch:tE,createdAt:new Date().toISOString()}),Mt=e=>{let t=ao(e);if(!Es.existsSync(t))return a("Missing .epiq/project.json");try{let n=Es.readFileSync(t,"utf8"),r=JSON.parse(n),o=nE.safeParse(r);return o.success?d("Read project.json",o.data):a(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return a(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},hn=e=>{let t=Mt(e);return l(t)?a(t.message):d("Read projectId",t.value.projectId)},nc=({repoRoot:e,fileContents:t})=>{let n=wr(e),r=ao(e);try{if(Es.mkdirSync(n,{recursive:!0}),Es.existsSync(r)){let o=Mt(e);return l(o)?a(o.message):d("Project already initialized",null)}return Es.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
38
|
+
`,"utf8"),d("Created project.json",null)}catch(o){return a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}}});import Ss from"node:fs";import Rs from"node:path";import{z as lo}from"zod";var qi,rE,oE,sE,Rp,Np,Sp,Cp,Ap,wp,iE,Gi,Ns,co=g(()=>{"use strict";N();rn();Oi();Q();qi="recent-projects.json",rE=20,oE=lo.object({projectId:lo.string().min(1),root:lo.string().min(1),lastOpenedAt:lo.number().finite()}),sE=lo.object({projects:lo.array(oE)}),Rp=()=>Rs.join(kn(),qi),Np=e=>Rs.basename(e)||e,Sp=e=>{let t=Rs.resolve(e);try{return Ss.realpathSync(t)}catch{return t}},Cp=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Ap=e=>{if(!Is(e.root))return!1;let t=hn(e.root);return!l(t)&&t.value===e.projectId},wp=()=>{let e=Rp();if(!Ss.existsSync(e))return d("No recent projects recorded",[]);let t;try{t=JSON.parse(Ss.readFileSync(e,"utf8"))}catch(r){return a(`Invalid ${qi}: ${r instanceof Error?r.message:String(r)}`)}let n=sE.safeParse(t);return n.success?d("Read recent projects",n.data.projects):a(`Invalid ${qi} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},iE=e=>{let t=Rp();try{Ss.mkdirSync(Rs.dirname(t),{recursive:!0}),Ss.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
39
|
+
`,"utf8")}catch(n){return a(`Unable to write ${qi}: ${n instanceof Error?n.message:String(n)}`)}return d("Recorded recent project",e)},Gi=({exclude:e}={})=>{let t=wp();if(l(t))return t;let n=e===void 0?null:Sp(e);return d("Listed recent projects",t.value.filter(r=>n===null||Sp(r.root)!==n).filter(Ap).sort(Cp))},Ns=({root:e,now:t=Date.now()})=>{let n=Rs.resolve(e),r=hn(n);if(l(r))return a(r.message);let o=r.value,s=wp(),i=l(s)?[]:s.value,c=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(u=>u.projectId!==o&&u.root!==n)].filter(Ap).sort(Cp).slice(0,rE);return iE(c)}});import{useSyncExternalStore as zM}from"react";var zi,aE,lE,ae,ct,$e=g(()=>{"use strict";zi={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,gitEmail:null,gitName:null,declinedEmailBoards:[],viewMode:null},aE=new Set,lE=()=>{for(let e of aE)e()},ae=()=>zi,ct=e=>(zi={...zi,...e},lE(),zi)});var rc,Tp,Mp,oc=g(()=>{"use strict";rc=null,Tp=e=>{rc=e},Mp=e=>rc?rc(e):[]});var kp,Lp,uo,Cs=g(()=>{"use strict";kp=[],Lp=e=>{kp=e},uo=()=>kp});var As,sc,Pp,Dp,ic,Op,_p,Fp,Tr=g(()=>{"use strict";wt();N();rn();$e();oc();Cs();Q();As=()=>{let e=ae(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1,o=Pp(),s=o.length>0?null:sc(),i=s!==null&&(e.declinedEmailBoards??[]).includes(s),c=o.length>0||i||s===null;return{isSetupDone:n&&t&&r&&c,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r,isSetEmails:c,claimedEmails:o,emailSetupDeclined:i}},sc=()=>{let e=Ne(process.cwd());if(l(e))return null;let t=hn(e.value);return l(t)?null:t.value||null},Pp=()=>{let{userId:e}=ae();return e?Mp(e):[]},Dp=()=>Pp().length>0,ic=()=>{let e=Ne(process.cwd());if(l(e))return!1;let t=Mt(e.value);return _t(t)},Op=e=>e===!0?"on":e===!1?"off":null,_p=e=>e==="on"?!0:e==="off"?!1:null,Fp=()=>{let e=As();if(!e.isSetUserName)return"config username ";if(!e.isSetPreferredEditor)return"config editor ";if(!e.isSetAutoSync)return"config autoSync ";if(!ic())return"init";if(!e.isSetEmails){let{gitEmail:t}=ae(),n=uo()[0]??t;return n&&Vn(n)?`config emails ${n}`:"config emails "}return null}});var cE,Ce,Vi,on=g(()=>{"use strict";cE=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[Ce,Vi]=cE});var dE,uE,yn,bn,Ki,Yi,mo=g(()=>{"use strict";ce();N();de();D();dE=e=>e.props.tags??[],uE=e=>e.props.assignees??[],yn=e=>dE(e).map(t=>R.getTag(t)).filter(t=>!!t),bn=e=>uE(e).map(t=>R.getContributor(t)).filter(t=>!!t),Ki=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!U(n)?a("Invalid untag target"):d("Retrieved tags from ticket in breadcrumb",yn(n))},Yi=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!U(n)?a("Invalid unassign target"):d("Retrieved assignees from ticket in breadcrumb",bn(n))}});var E,Mr=g(()=>{"use strict";E={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",NONE:""}});var mE,pE,fE,gE,hE,kr,Bp,Xi,Ji,$p,vE,ac,ws=g(()=>{"use strict";mE=/^(\d+)(h|d|w|mo|y)$/,pE=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,fE=({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},gE=(e,t=new Date)=>{let n=e.match(mE);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(o){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},hE=e=>{let t=e.match(pE);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),u=Number(r),p=Number(o),m=s?Number(s):0,f=i?Number(i):0;return fE({year:c,month:u,day:p,hour:m,minute:f})?new Date(c,u-1,p,m,f):null},kr=e=>{let t=e.trim().toLowerCase();return gE(t)??hE(t)},Bp=/^(\d+)(s|m)?$/,Xi=e=>{let t=e.trim().toLowerCase().match(Bp);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Ji=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Bp.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},$p=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,vE=[{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}],ac=(e=vE)=>{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 yE,he,Pt,je,bE,xE,cc,dc,Hp,Lr,Qi,lc,jp,IE,EE,Ts,Up,SE,RE,uc,NE,Ue,Dn=g(()=>{"use strict";Cr();co();N();Tr();on();ce();de();D();Pl();mo();Mr();ws();yE=["BOARD","TICKET","SWIMLANE","COMMENT"],he={EDITOR:"editor",VIEW:"view",USERNAME:"username",EMAILS:"emails",EMAILS_UNCLAIM:"emails-unclaim",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},Pt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},je={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},bE=[he.EDITOR,he.VIEW,he.USERNAME,he.EMAILS,he.EMAILS_UNCLAIM,he.AUTOSYNC,he.SYNC_DEBOUNCE_MS,he.ATTACHMENT_MAX_KB,he.LOG_LEVEL],xE=(e=v().selectedNode?.context)=>{switch(e){case"TICKET":return[Pt.TITLE,Pt.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Pt.TITLE];case"COMMENT":return[Pt.COMMENT];default:return[]}},cc=[String(3e3),"5000","15000","30000","60000"],dc=["250","500","1000"],Hp=["10s","20s","30s","45s"],Lr=[E.EXIT,E.SYNC,E.HELP,E.EXPORT,E.CONFIG,E.YANK],Qi=[E.NEW,E.EDIT,E.DELETE,E.MOVE],lc=[E.TAG,E.UNTAG,E.ASSIGN,E.UNASSIGN,E.CLOSE_ISSUE,E.RE_OPEN_ISSUE,E.EDIT,E.COMMENT],jp=[E.FILTER,E.PEEK,E.REPLAY],IE={WORKSPACE:[...Lr,...Qi],BOARD:[...jp,...Lr,...Qi],SWIMLANE:[...jp,...Lr,...Qi],TICKET:[...Lr,...Qi,...lc],FIELD:[...Lr,...lc],FIELD_LIST:[...Lr,...lc],TEXT:[...Lr],COMMENT:[E.EDIT,E.DELETE,E.YANK]},EE=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Ts=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&U(n)),Up=e=>e.parentNodeId===Ce,SE=({selectedNode:e,breadCrumb:t})=>{let n=xE(e?.context);return Ts({breadCrumb:t,selectedNode:e})?n.includes(Pt.DESCRIPTION)?n:[...n,Pt.DESCRIPTION]:n},RE=({selectedNode:e,breadCrumb:t})=>{let n=Ts({breadCrumb:t,selectedNode:e});return n?[je.REF,je.TITLE,...n.props?.description?.trim()?[je.DESCRIPTION]:[],...yn(n).length>0?[je.TAGS]:[],...bn(n).length>0?[je.ASSIGNEES]:[]]:e?[je.REF,je.TITLE]:[]},uc=()=>{let e=Gi({exclude:process.cwd()});return l(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},NE=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=As();if(!r)return[E.HELP,E.CONFIG];if(!ic())return[E.HELP,E.INIT,E.OPEN];if(t)return[E.HELP,E.PEEK,E.REPLAY,E.EXPORT,E.CONFIG,E.YANK];let o=e?.context,s=o&&yE.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?IE[u]:[]))],c=Ts({breadCrumb:n,selectedNode:e});return i.filter(u=>u===E.MOVE?!1:u===E.YANK?!!(c??e):u===E.EDIT?s||!!c:u===E.DELETE?s:u===E.UNTAG?!!(c&&yn(c).length>0):u===E.UNASSIGN?!!(c&&bn(c).length>0):u===E.RE_OPEN_ISSUE?!!(c&&Up(c)):u===E.CLOSE_ISSUE?!!(c&&!Up(c)):!0)},Ue=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let s=t.context??"WORKSPACE";return{[E.NONE]:NE({breadCrumb:o,readOnly:r,selectedNode:n}),[E.EXIT]:["confirm"],[E.EXPORT]:[],[E.SYNC]:[],[E.INIT]:[],[E.OPEN]:e===E.OPEN?uc():[],[E.HELP]:[],[E.PEEK]:[...ac(),"now","prev","next"],[E.REPLAY]:[...ac()],[E.EDIT]:SE({selectedNode:n,breadCrumb:o}),[E.YANK]:RE({selectedNode:n,breadCrumb:o}),[E.COMMENT]:[],[E.DELETE]:["confirm"],[E.RE_OPEN_ISSUE]:["confirm"],[E.CLOSE_ISSUE]:["confirm"],[E.MOVE]:["start","confirm","next","previous","jump-next","jump-previous","to-next","to-previous","cancel"],[E.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[E.TAG]:[...new Set([...Object.keys(Ti),...R.getExistingTags()])],[E.UNTAG]:[...Ki()?.value?.map(({name:c})=>c)??[]],[E.UNASSIGN]:[...Yi()?.value?.map(({name:c})=>c)??[]],[E.ASSIGN]:R.getExistingAssignees(),[E.NEW]:EE(s),[E.CONFIG]:[...bE]}[e]??[]}});var Wp,qp=g(()=>{"use strict";Wp=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{accessSync as CE,copyFileSync as AE,existsSync as Zi,mkdirSync as Gp,readdirSync as zp,readFileSync as wE,renameSync as TE,rmSync as ME,statSync as Vp,unlinkSync as kE,writeFileSync as LE}from"node:fs";import po from"node:path";var mc,Xe,ea=g(()=>{"use strict";mc=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Xe={writeToFile:(e,t)=>{try{let n=po.dirname(e);Zi(n)||Gp(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);LE(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return wE(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Xe.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 Zi(e)&&Vp(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await CE(e),!0}catch{return!1}},mkDir:e=>Gp(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=po.parse(t);for(;;){let r=po.join(t,e);try{if(Zi(r)&&Vp(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=po.dirname(t)}return null},readFirstJSON(e){try{if(!Xe.dirExists(e))return null;let t=zp(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=po.join(e,t);return Xe.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Xe.dirExists(e)?zp(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{kE(e)}catch(t){(!mc(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{ME(e,{recursive:!0,force:!0})}catch(t){(!mc(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(po.dirname(t)),!n?.overwrite&&Zi(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{TE(e,t)}catch(r){if(mc(r)&&r.code==="EXDEV"){AE(e,t),this.rmFile(e);return}throw r}}}});import PE from"node:path";import{z as sn}from"zod";var DE,Yp,OE,Xp,pc,fc,_E,xn,Jp,It,Jn,In=g(()=>{"use strict";xr();Cr();Q();N();ea();DE={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},Yp=sn.object({logLevel:sn.enum(["info","error","debug"]),preferredEditor:sn.string().optional(),userName:sn.string().optional(),userId:sn.string().optional(),autoSync:sn.boolean().nullable().optional(),autoSyncDebounceMs:sn.number().optional(),attachmentMaxKb:sn.number().optional(),viewMode:sn.enum(["dense","wide"]).optional(),declinedEmailBoards:sn.array(sn.string()).optional()}).partial(),OE="config.json",Xp=kn,pc=()=>PE.join(Xp(),OE),fc=()=>{try{return Xe.mkDir(Xp()),d(`Ensured ~/${tn} exists`,null)}catch{return a(`Unable to create ~/${tn}`)}},_E=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${tn}/config.json JSON`)}let n=Yp.safeParse(t??{});return n.success?d("Parsed config",n.data):a(`Invalid ~/${tn}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},xn=()=>{let e=fc();if(l(e))return a(e.message);let t=pc(),n=Xe.readFile(t);return n==null||n.trim()===""?d("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):_E(n)},Jp=e=>{let t=fc();if(l(t))return a(t.message);let n=Yp.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=pc();try{return Xe.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
40
|
+
`),d("Config written",null)}catch{return a(`Unable to write ~/${tn}/config.json`)}},It=e=>{let t=xn();if(l(t))return a("Failed to read existing config");let n={...t.value,...e};return Jp(n)},Jn=()=>{let e=pc(),t=fc();if(l(t))return a(`Unable to create ~/${tn}`);if(!(Xe.readFile(e)!==null)){let C=Jp(DE);if(l(C))throw new Error(`Unable to create ~/${tn}/config.json`)}let r=xn();if(l(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,declinedEmailBoards:c,autoSync:u,autoSyncDebounceMs:p,attachmentMaxKb:m,logLevel:f,viewMode:h}=r.value,b=Tl({userId:i,userName:s});if(l(b))return a(b.message);let I=b.value??{userId:i,userName:s};return!I.userName||!I.userId?a(`User name or ID not configured in ~/${tn}/config.json`):(process.env.EPIQ_LOG_LEVEL=f,d("successfully loaded settings",{gitEmail:null,gitName:null,declinedEmailBoards:c??[],logLevel:f??"debug",preferredEditor:o??"",userName:I.userName,userId:I.userId,autoSync:u??!1,autoSyncIntervalMs:p??1e4,attachmentMaxKb:m??null,viewMode:h??"dense"}))}});var Qp,Zp,gc,ef=g(()=>{"use strict";Qp="/media/",Zp=e=>`${Qp}${e}`,gc=(e,t)=>`})`});import FE from"node:crypto";import hc from"node:fs";import BE from"node:path";var On,fo,$E,jE,UE,tf,go=g(()=>{"use strict";en();N();Q();ef();On=500,fo=(e,t)=>`${e}.${t}`,$E=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?d("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?d("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")))?d("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"))?d("Sniffed image type","webp"):a(`Unsupported image format. Allowed: ${Pm.join(", ")}`),jE=e=>FE.createHash("sha256").update(e).digest("hex"),UE=(e,t=On)=>{if(e.length===0)return a("Attachment is empty");if(e.length>t*1024)return a(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=$E(e);return l(n)?n:d("Validated attachment data",{hash:jE(e),ext:n.value,bytes:e.length})},tf=(e,t,n=On)=>{let r=UE(t,n);if(l(r))return r;let o=Ui(e),s=BE.join(o,fo(r.value.hash,r.value.ext));try{hc.existsSync(s)||(hc.mkdirSync(o,{recursive:!0}),hc.writeFileSync(s,t))}catch(i){return a(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return d("Wrote attachment blob",r.value)}});import HE from"zod";var Ms,ks,nf,vc=g(()=>{"use strict";In();go();N();pe();$e();Ms=50,ks=5e3,nf=()=>{let e=me().commandMeta.inputString,t=HE.coerce.number().int().min(Ms).max(ks).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${Ms}-${ks} KB (default ${On})`);let n=It({attachmentMaxKb:t.data});return l(n)?n:(ct({attachmentMaxKb:t.data}),d(`Attachment size cap set to ${t.data} KB`,null))}});var rt,_n=g(()=>{"use strict";rt=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null});import{createHash as WE}from"node:crypto";var qE,GE,rf,we,Qn=g(()=>{"use strict";qE="0123456789ABCDEFGHJKMNPQRSTVWXYZ",GE=e=>{let t=WE("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+=qE[Number(n>>s&31n)]}return r},rf=new Map,we=(e,t)=>{let n=`${e}:virtual:${t}`,r=rf.get(n);if(r!==void 0)return r;let o=GE(n);return rf.set(n,o),o}});import of from"chalk";var Ie,De,Oe,sf=g(()=>{"use strict";fn();Ye();Ie=e=>of.dim(e),De=e=>of.hex(w.primary)(e),Oe=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let m=[...t.filter(Boolean).filter(f=>f.startsWith(i))].sort((f,h)=>Mi(f)-Mi(h)).slice(0,r).map(f=>ki(f)).join(" ");return m?`${Ie(e)}${m}${Ie(n)}`:""}});var Zn,ta=g(()=>{"use strict";Zn={None:"none",Invalid:"invalid",Valid:"valid"}});import cf from"chalk";var zE,af,ye,VE,oe,K,vo,lf,na,yc,KE,ho,YE,XE,JE,QE,ZE,df,uf=g(()=>{"use strict";Cr();Tr();qp();at();en();N();de();$e();vc();go();wt();D();fn();_n();mo();Qn();sf();Cs();Mr();ta();Dn();ws();zE=["BOARD","TICKET","SWIMLANE"],af=()=>{let e=v().selectedNode;if(!e?.context)return K({message:Ie("Missing target context")});if(zE.includes(e.context))return oe();if(e.parentNodeId){let t=v().nodes[e.parentNodeId];if(t?.id===we(t?.parentNodeId??"","comments"))return oe()}return K({message:Ie("Command not available in this context")})},ye="<ENTER> to confirm",VE=()=>{let{userId:e}=ae(),t=Ee();return!e||l(t)?[]:Kn(t.value.emailLinks,e)},oe=(e="",t=[],n=!0)=>({message:n?Ie(e):e,validity:Zn.Valid,completionWordList:t}),K=({message:e,completionWordList:t=[]})=>({validity:Zn.Invalid,message:e,completionWordList:t}),vo=e=>e.length===0,lf=(e,t)=>{let n=At(v().breadCrumb,"BOARD");if(l(n))return K({message:De("Command is not applicable in this context")});let r=Ll(n.value.id);return l(r)?K({message:De(`Unable to ${t}: board id is not a valid ULID`)}):$p({date:e,horizonDate:r.value})?null:K({message:De(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},na=e=>` ${cf.hex("#000").bgHex(Ze(e))(` ${e} `)} `,yc=({modifier:e})=>{let t="confirm";return e===t?oe(ye):K({message:vo(e)?Ie("if you are certain, enter ")+ki(t):"",completionWordList:[t]})},KE=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?K({message:Ie(n)}):oe():K({message:vo(r)?t:"",completionWordList:[...e]}),ho=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>vo(n)&&vo(r)?K({message:e,completionWordList:[]}):oe(t??ye),YE=({modifier:e,inputString:t})=>{let n=uc();return!vo(e)||!vo(t)?oe(ye):K({message:n.length?Ie("number from the list, or a path"):Ie("path to an epiq project"),completionWordList:n})},XE=({modifier:e,inputString:t})=>{let n=Ue(E.CONFIG);if(!n.includes(e))return K({message:Oe({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case he.EDITOR:{let r=[...Wp];return t.trim()?r.includes(t.trim())?oe(ye):K({message:Oe({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):K({message:Oe({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case he.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?oe(ye):K({message:Oe({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case he.USERNAME:{let r=ae().gitName,o=r?[r]:[],s=t.trim(),i=o.filter(p=>p.startsWith(s)),u=i.length===1&&i[0]===s?"":Oe({prefix:"name: ",wordList:o,inputString:s,minLengthForHints:0});return s?u?oe(`${u} ${Ie(ye)}`,o,!1):oe(ye,o):K({message:u||De("Enter a user name. Saved in ")+cf.bgBlack("~/.epiq-global/config.json"),completionWordList:o})}case he.EMAILS:{let r=ae().gitEmail,o=uo(),s=o.length>0||!r?o:[r],i=[...s,"none"],c=t.trim(),u=(I,C)=>K({message:Oe({prefix:I,wordList:i,noOfHints:3,inputString:C,minLengthForHints:0}),completionWordList:i});if(!c)return oe(`${ye} to see your addresses, or name one`,i);let p=c.split(/[,\s]+/).filter(Boolean),m=p[p.length-1]??"",f=I=>I==="none"||s.includes(I.toLowerCase()),h=I=>i.some(C=>C.startsWith(I.toLowerCase())),b=p.filter(I=>!f(I)&&!h(I));return b.length>0?K({message:De(`no address here matches ${b.join(", ")} \u2014 pick one from the list, or its number`),completionWordList:i}):f(m)?oe(ye):u("",m)}case he.EMAILS_UNCLAIM:{let r=VE(),o=t.trim();return r.length===0?K({message:De("you have not claimed any addresses"),completionWordList:[]}):o&&r.includes(o.toLowerCase())?oe(ye):K({message:Oe({prefix:"give an address back ",wordList:r,noOfHints:3,inputString:o,minLengthForHints:0}),completionWordList:r})}case he.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?oe(ye):K({message:Oe({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case he.AUTOSYNC:{let r=["on","off"],o=ae().autoSync;if(!r.includes(t.trim())){let s=Op(o);return K({message:Oe({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return oe(ye)}case he.ATTACHMENT_MAX_KB:{let r=ae().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<Ms||o>ks){let s=Oe({prefix:" examples: ",wordList:dc,minLengthForHints:0,inputString:t});return K({message:De(`provide a size cap in KB (${Ms}-${ks}). current: ${r??On} KB.`)+s,completionWordList:dc})}return oe(ye)}case he.SYNC_DEBOUNCE_MS:{let r=ae().autoSyncIntervalMs,o=oo(t);if(!t.trim()||o===null){let s=Oe({prefix:" examples: ",wordList:cc,minLengthForHints:0,inputString:t});return K({message:De(`provide a duration between ${3e3}ms and ${864e5}ms. current duration: ${r}ms.`)+s,completionWordList:cc})}return oe(ye)}default:return K({message:De("Unknown config option"),completionWordList:n})}},JE=({modifier:e,inputString:t})=>{let n=Ue(E.EDIT);if(!n.length)return K({message:De("Command not available in this context")});if(!n.includes(e)){let r=Oe({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return K({message:r||De("Unknown edit option"),completionWordList:n})}switch(e){case Pt.COMMENT:return t.trim()?oe(ye):K({message:Ie("write a comment...")});case Pt.TITLE:return oe(ye);case Pt.DESCRIPTION:{let{preferredEditor:r}=ae();return r?oe(Ie("<ENTER> to edit in ")+r):K({message:"No editor selected"})}default:return K({message:De("Unknown edit option"),completionWordList:n})}},QE=({modifier:e})=>{let t=Ue(E.YANK);return t.length?t.includes(e)?oe(ye+Ie(" and copy to clipboard")):K({message:Oe({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):K({message:De("Nothing selected to copy from")})},ZE={[E.EXPORT]:()=>oe(ye+Ie(", and create export markdown file")),[E.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return oe(ye);let n={message:Ie("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=kr(r);if(!r||!o)return K(n);let s=lf(o,"peek");return s||oe(ye)},[E.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Ji(e.modifier,e.inputString),r={message:Ie("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=kr(t);if(!t||!o)return K(r);let s=lf(o,"replay");return s||(n&&Xi(n)===null?K({message:De("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):oe("<ENTER> to replay board history",n?Hp:[]))},[E.EXIT]:()=>oe(ye+Ie(" and exit the application")),[E.INIT]:()=>oe(ye),[E.OPEN]:YE,[E.PALETTE]:()=>oe(ye),[E.FILTER]:e=>{if(e.modifier==="clear")return oe(ye);let t=s=>Ue(E.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return K({message:Oe({wordList:Ue(E.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Ue(E.FILTER)});let n=Object.values(v().tags).map(s=>s.name),r=Object.values(v().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?K({message:Oe({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):oe():K({message:Oe({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[E.NONE]:e=>{let t=Ue(E.NONE);return K({message:Oe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[E.NEW]:e=>KE({list:Ue(E.NEW),hint:Oe({wordList:Ue(E.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[E.HELP]:()=>oe(ye),[E.EDIT]:JE,[E.COMMENT]:e=>{let t=ho({hint:Ie(`write a comment (max ${4e3} char)...`),onOk:Ie(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===Zn.Invalid?t:e.inputString.length>4e3?oe(De("max input exceeded")):t},[E.CONFIG]:XE,[E.YANK]:QE,[E.DELETE]:e=>{let t=af();return t.validity==="invalid"?t:yc(e)},[E.CLOSE_ISSUE]:e=>yc(e),[E.RE_OPEN_ISSUE]:e=>yc(e),[E.MOVE]:e=>{let t=af();return t.validity==="invalid"?t:ho({hint:Oe({prefix:"hey hacker! These commands are blocked for you... ",wordList:Ue(E.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[E.TAG]:e=>{let n=R.getExistingTags().slice(0,10).map(na).join("");return ho({hint:n.length?Ie("create tag or reuse:")+n+Ie(""):Ie("create tag ...")})(e)},[E.UNTAG]:e=>{let t=Ki();if(l(t))return K({message:De("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(na).slice(0,10);return n.length?ho({hint:Ie(" ... ")+n.join("")})(e):K({message:De("Issue has no tags"),completionWordList:[]})},[E.ASSIGN]:e=>{let t=R.getExistingAssignees().map(na).slice(0,10);return ho({hint:Ie("assignees... ")+t.join("")})(e)},[E.UNASSIGN]:e=>{let t=Yi();if(l(t))return K({message:De("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(na).slice(0,10);return n.length?ho({hint:Ie("remove assignee... ")+n.join("")})(e):K({message:De("Issue has no assignees"),completionWordList:[]})},[E.SYNC]:()=>oe(ye)},df=Object.fromEntries(Object.entries(ZE).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]))});var ra,mf=g(()=>{"use strict";ra=["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 eS,tS,nS,rS,oS,pf,ff,gf,hf=g(()=>{"use strict";N();D();mf();eS=3,tS=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"]),nS=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},rS=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=eS&&!tS.has(t)&&!/^\d+$/.test(t)),oS=e=>{let t=new Map;for(let s of nS(e))for(let i of rS(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),r=new Set(n),o=ra.filter(s=>!r.has(s));return[...n,...o]},pf=ra,ff=-1,gf=()=>{let e=Ee();if(l(e))return ra;let t=e.value,n=t.eventLog.length;return n!==ff&&(pf=oS(t),ff=n),pf}});var vf,yf,bc=g(()=>{"use strict";zm();Dn();Mr();uf();hf();D();Pe();vf=e=>Object.values(E).includes(e),yf=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:u}=df[n].validate(n,r,s),p=n!==E.PEEK&&n!==E.REPLAY,m=o==="command"||o==="modifier"?Ue(n):p?gf():[],{mode:f}=v(),h=f===x.COMMAND_LINE?i??"":"",b=[...u,...m];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:h,autoCompletion:t?Gm(e,b,u):{hint:"",hints:[],remainder:"",overlap:0}}}});var bf,sS,iS,aS,xf=g(()=>{"use strict";bc();Dn();bf=e=>{let t=e.trimStart(),n=iS(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=aS(e),c=vf(r)?r:null,u=c!==null,p=r!=="",m=c?Ue(c)??[]:[],f=c&&m.includes(o)?o:"",h="word";n.length===0||n.length===1&&!s?h="command":(n.length===1&&s||n.length===2&&!s)&&(h="modifier");let b=s?"":i,I=sS(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:p,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:h,inputToMatch:b,inputString:I}},sS=(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},iS=e=>e.trim()?e.trim().split(/\s+/):[],aS=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as fP}from"react";var yo,xc,Ps,bo,lS,If,$t,Ds,Ic,Ec,Ef,Sf,oa,Rf,Z,Nf,Cf,Af,wf,Tf,me,sa,pe=g(()=>{"use strict";bc();xf();N();ta();yo=e=>e===xc||e===":",xc=" ",Ps=40,bo={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Zn.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},lS=new Set,If=()=>{for(let e of lS)e()},$t=e=>{let n=e(bo),r=bf(n.value),o=n.cursorPosition===n.value.length;bo={...n,commandMeta:yf(r,o)},If()},Ds=({message:e,status:t})=>{let n=structuredClone(bo);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,bo=n,If(),d(e,null)},Ic=e=>{$t(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Ec=e=>{$t(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&yo(n[o-1]);)o--;for(;o>0&&!yo(n[o-1]);)o--}else{for(;o<n.length&&!yo(n[o]);)o++;for(;o<n.length&&yo(n[o]);)o++}return{...t,cursorPosition:o}})},Ef=()=>{$t(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},Sf=()=>{$t(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&yo(t[r-1]);)r--;for(;r>0&&!yo(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},oa=e=>{$t(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},Rf=()=>{$t(e=>({...e,commandIsPending:!0}))},Z=e=>{$t(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Nf=({addToHistory:e=!0,line:t})=>{$t(n=>{let r=t??n.value;return{...n,commandHistory:e&&r.trim()?[r,...n.commandHistory].slice(0,Ps):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}})},Cf=e=>{$t(t=>({...t,commandHistory:e.slice(0,Ps),commandHistoryIndex:-1}))},Af=()=>{$t(e=>e.commandHistoryIndex===-1?e:{...e,commandHistoryIndex:-1})},wf=()=>{$t(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Tf=()=>{$t(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},me=()=>bo,sa=()=>{let[e,...t]=bo.value.split(xc);return t.join(xc).trim()}});var P,RP,Yn=g(()=>{"use strict";Pe();_m();D();pe();$e();P={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavPreviousItemJump:"navPreviousItemJump",NavNextItemJump:"navNextItemJump",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MovePreviousItemJump:"movePreviousItemJump",MoveNextItemJump:"moveNextItemJump",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",OpenInEditor:"openInEditor",MarkDiffLine:"markDiffLine",CommentOnDiffLine:"commentOnDiffLine",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"},RP={[P.NavPreviousItem]:P.NavPreviousItemJump,[P.NavNextItem]:P.NavNextItemJump,[P.MovePreviousItem]:P.MovePreviousItemJump,[P.MoveNextItem]:P.MoveNextItemJump}});function Mf(e){return!e||!dS.test(e)?a(`Invalid hex rank: ${e}`):d("Converted rank to bigint",BigInt("0x"+e))}function Dt(e,t=Os){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return d("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function ut(e,t){if(!e&&!t)return Dt(an/2n,Os);let n=e?Mf(e):d("Resolved lower bound",0n);if(l(n))return n;let r=t?Mf(t):d("Resolved upper bound",an);if(l(r))return r;let o=n.value,s=r.value;if(s<=o)return a("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):Dt(i,Os)}function kf(e){if(e<=0)return d("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=an*BigInt(r+1)/(t+1n),s=Dt(o,Os);if(l(s))return s;n.push(s.value)}return d("Resolved evenly spaced ranks",n)}var Os,cS,an,dS,xo=g(()=>{"use strict";N();Os=24n,cS=Os*4n,an=(1n<<cS)-1n,dS=/^[0-9a-f]+$/});var O,Lf,jt=g(()=>{"use strict";O=({userId:e})=>({userId:e}),Lf=e=>({action:e.action,payload:e.payload})});var Sc,OP,Ut=g(()=>{"use strict";jt();Sc=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","tombstone.tag","restore.tag","create.contributor","rename.contributor","tombstone.contributor","restore.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","move.node","edit.description","add.issue.comment","edit.issue.comment","delete.issue.comment","add.issue.attachment","delete.issue.attachment","close.issue","reopen.issue","lock.node","rebalance.children","link.contributor.user","link.contributor.email","unlink.contributor.email"],OP=new Set(Sc)});import{ulid as uS}from"ulid";var Rc,Pf=g(()=>{"use strict";N();Ht();xo();Ut();Rc=(e,t)=>{let n=Te(e),r=kf(n.length);if(l(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],c=r.value[s];if(!i||!c)return a("Unable to assign rebalance rank");o[i.id]=c}return d("Created rebalance event",{id:uS(),action:"rebalance.children",payload:{parent:e,ranks:o},...O(t)})}});import{z as Dr}from"zod";var Df,Of,mS,YP,pS,fS,_f,gS,hS,Nc,Ff,Cc,_s=g(()=>{"use strict";N();Df=1,Of=Dr.tuple([Dr.string().min(1),Dr.string().min(1).nullable()]),mS=Dr.looseObject({v:Dr.literal(Df),id:Of}),YP=Dr.looseObject({v:Dr.number().int().positive(),id:Of}),pS=e=>Object.prototype.hasOwnProperty.call(e,"__proto__"),fS=e=>{let t={};for(let n of Object.keys(e))n!=="__proto__"&&(t[n]=e[n]);return t},_f=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return a("Invalid persisted event envelope: expected an object");let{v:t,id:n}=e;if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return a("Invalid persisted event envelope: v");if(!Array.isArray(n)||n.length!==2)return a("Invalid persisted event envelope: id");let[r,o]=n;return typeof r!="string"||r.length===0?a("Invalid persisted event envelope: id.0"):o!==null&&(typeof o!="string"||o.length===0)?a("Invalid persisted event envelope: id.1"):d("Parsed persisted event envelope",pS(e)?fS(e):e)},gS=[1],hS=new Set(gS),Nc=e=>hS.has(e),Ff=e=>{let t=mS.safeParse(e);return t.success?d("Parsed persisted event",t.data):a(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Cc=(e,t)=>{let n={[e.action]:e.payload,v:Df,id:t};return Ff(n)}});import Ac from"node:fs";import vS from"node:path";var Fs,wc,Tc,Wt,Bf,Mc,er,$f,Io,jf,tr=g(()=>{"use strict";Q();Fs=e=>e?.code==="ENOENT",wc=3,Tc=e=>Ac.readdirSync(e).filter(t=>t.endsWith(".jsonl")).sort(),Wt=e=>{let t=xt(e);for(let n=1;;n++){if(!Ac.existsSync(t))return"none";let r=[],o=!1;for(let s of Tc(t))try{let{size:i,mtimeMs:c}=Ac.statSync(vS.join(t,s));r.push(`${s}:${i}:${c}`)}catch(i){if(!Fs(i))throw i;if(n<wc){o=!0;break}}if(!o)return r.join("|")}},Bf=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),Mc=(e,t,n)=>{let r=Bf(t),o=Wt(e),s=Bf(o);for(let[i,c]of s)if(i!==n&&r.get(i)!==c)return null;for(let i of r.keys())if(i!==n&&!s.has(i))return null;return o},er=null,$f=e=>er&&er.root===e?er.signature:null,Io=(e,t)=>{er={root:e,signature:t}},jf=(e,t)=>{if(!er||er.root!==e)return;let n=Mc(e,er.signature,t);er=n===null?null:{root:e,signature:n}}});import _e from"node:fs";import Or from"node:path";import{ulid as yS}from"ulid";var aa,kc,Hf,Wf,la,bS,Lc,_r,Bs,qf,xS,IS,Gf,ES,zf,SS,Vf,RS,ia,Uf,ca,Fr=g(()=>{"use strict";N();Q();aa="~pending",kc=/~pending(-[0-9a-z]+)*$/i,Hf=/-f(\d+)$/,Wf=e=>{let t=e.indexOf(".");return t===-1?`${e}${aa}`:e.slice(0,t)+aa+e.slice(t)},la=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},bS=e=>{let[t,n]=la(e);return kc.test(t)?t.replace(kc,"")+n:null},Lc=e=>e.replace(kc,""),_r=e=>e.endsWith(".jsonl")&&bS(e)!==null,Bs=e=>Lc(la(e)[0]),qf=e=>{let[t]=la(e),n=Hf.exec(t);return n&&_r(e)?Number(n[1]):null},xS=e=>Wf(e).replace(aa,`${aa}-${yS().toLowerCase()}`),IS=(e,t)=>{let[n,r]=la(e);return`${n.replace(Hf,"")}-f${t}${r}`},Gf=(e,t)=>Or.join(xt(e),Wf(t)),ES=(e,t)=>Math.max(0,_e.statSync(e).size-(qf(t)??0)),zf=e=>{let t=xt(e);try{return _e.existsSync(t)?_e.readdirSync(t).filter(_r).some(n=>ES(Or.join(t,n),n)>0):!1}catch{return!0}},SS=3,Vf=(e,t)=>{for(let n=1;;n++){let r=_e.openSync(e,"a"),o;try{_e.writeSync(r,t),o=_e.fstatSync(r).ino}finally{_e.closeSync(r)}let s;try{s=_e.statSync(e).ino}catch{s=null}if(s===o||n>=SS)return}},RS=e=>{let t;try{t=_e.openSync(e,"r")}catch{return!0}try{let{size:n}=_e.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return _e.readSync(t,r,0,1,n-1),r[0]===10}finally{_e.closeSync(t)}},ia=10,Uf=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(ia)+1;if(r===0)return{bytes:0,lines:0};let o=t.subarray(0,r);if(o.toString("utf8").trim().length===0)return{bytes:r,lines:0};_e.appendFileSync(e,Buffer.concat([Buffer.from(RS(e)?"":`
|
|
41
|
+
`),o,Buffer.from(o[o.length-1]===ia?"":`
|
|
42
|
+
`)]));let s=0;for(let i of o)i===ia&&s++;return o[o.length-1]!==ia&&s++,{bytes:r,lines:s}},ca=(e,t)=>{let n=xt(e);if(!_e.existsSync(n))return d("No events directory",0);try{let r=Bs(t),o=_e.readdirSync(n).filter(c=>_r(c)&&Bs(c)===r),s=Or.join(n,t),i=0;for(let c of o){let u=qf(c);if(u!==null){let h=Or.join(n,c),b=_e.readFileSync(h).subarray(u);i+=Uf(s,b,!0).lines,_e.rmSync(h,{force:!0});continue}let p=/~pending-/i.test(c)?c:xS(t),m=Or.join(n,p);p!==c&&_e.renameSync(Or.join(n,c),m);let f=Uf(s,_e.readFileSync(m));i+=f.lines,_e.renameSync(m,Or.join(n,IS(p,f.bytes)))}return d("Folded pending logs",i)}catch(r){return a(`Unable to fold pending event logs in ${n}: ${r instanceof Error?r.message:String(r)}`)}}});import js from"node:fs";import ua from"node:path";import{decodeTime as NS}from"ulid";import{z as Pc}from"zod";var ma,CS,Jf,da,AS,wS,Qf,TS,MS,nr,kS,LS,$s,Dc,PS,DS,OS,Kf,_S,Zf,Yf,Oc,Xf,_c,eg,tg,Fc=g(()=>{"use strict";Bt();N();Q();at();_s();tr();Fr();ma="unknown",CS=Pc.object({userId:Pc.string().min(1).default(ma),userName:Pc.string().min(1).default(ma)}),Jf=new Set(["id","v","userId","userName"]),da=e=>{let t=Object.entries(e).filter(([o])=>!Jf.has(o));if(t.length!==1)return null;let n=t[0]?.[1];if(typeof n!="object"||n===null)return null;let r=n.id;return typeof r=="string"&&r.length>0?r:null},AS=/^[0-9a-hjkmnp-tv-z]{26}$/i,wS=e=>AS.test(e)?e.toUpperCase():e,Qf=e=>{let t=ua.basename(e,".jsonl"),n=t.indexOf("."),r=Lc(n===-1?t:t.slice(0,n)),o=n===-1?void 0:t.slice(n+1),s=CS.safeParse({userId:wS(r),userName:o});return s.success?d("Parsed event file actor",s.data):a(`Invalid event file name ${ua.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},TS=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?a(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?a("Invalid persisted event: action key is missing or invalid"):d("Resolved persisted action",t[0])},MS=(e,t)=>t in e,nr=new Map,kS=3e5,LS=512,$s=0,Dc=e=>e.entries.length+e.quarantined.length,PS=(e,t,n,r)=>{let o=nr.get(e);o&&($s-=Dc(o));let s={stamp:t,entries:n,quarantined:r};nr.delete(e),nr.set(e,s),$s+=Dc(s);for(let[i,c]of nr){if($s<=kS&&nr.size<=LS)break;i!==e&&(nr.delete(i),$s-=Dc(c))}},DS=()=>{nr.clear(),$s=0},OS=2n,Kf=1000000n,_S=e=>{try{let{size:t,mtimeNs:n}=js.statSync(e,{bigint:!0});return{value:`${t}:${n}`,settled:BigInt(Date.now())*Kf-n>OS*Kf}}catch{return null}},Zf=(e,t)=>{let n=Qf(e);if(l(n))return a(n.message);let r=_S(e),o=r?nr.get(e):void 0;if(r&&o&&o.stamp===r.value){if(t)for(let m of o.quarantined)t.push(m);return d("Parsed persisted events file",[...o.entries])}let s;try{s=js.readFileSync(e,"utf8")}catch(m){if(Fs(m))return d("Event file missing",null);throw m}let i=[],c=ua.basename(e),u=[],p=(m,f)=>{u.push({eventId:null,reason:"corrupt-line",detail:`${c}:${m} (${f})`,targetNodeId:null})};for(let[m,f]of s.split(`
|
|
43
|
+
`).entries()){let h=f.trim();if(!h)continue;let b;try{b=JSON.parse(h)}catch{p(m+1,"invalid JSON");continue}let I=_f(b);if(l(I)){p(m+1,I.message);continue}i.push({...I.value,userId:n.value.userId,userName:n.value.userName})}if(t)for(let m of u)t.push(m);return r?.settled&&PS(e,r.value,i,u),d("Parsed persisted events file",[...i])},Yf=(e,t)=>e<t?-1:e>t?1:0,Oc=(e,t)=>{let n=Yf(e.id[0],t.id[0]);return n!==0?n:Yf(JSON.stringify(e),JSON.stringify(t))},Xf=(e,t)=>{let n=new Map,r=new Map;for(let m of e){let f=m.id[0],h=m.id[1]??null;n.set(f,m);let b=r.get(h)??[];b.push(m),r.set(h,b)}for(let m of r.values())m.sort(Oc);let o=[],s=new Set,i=m=>{let f=[m];for(;f.length>0;){let h=f.pop(),b=h.id[0];if(s.has(b))continue;o.push(h),s.add(b);let I=r.get(b)??[];for(let C=I.length-1;C>=0;C--)f.push(I[C])}},c=(r.get(null)??[]).filter(m=>{let f=Object.keys(m).filter(h=>!Jf.has(h));return f.length===1&&f[0]===t});for(let m of c)i(m);let u=e.filter(m=>{let f=m.id[0],h=m.id[1]??null;return s.has(f)?!1:h===null||!n.has(h)}).sort(Oc);for(let m of u)i(m);let p=e.filter(m=>!s.has(m.id[0])).sort(Oc);for(let m of p)i(m);return o},_c=e=>cs(e.map(t=>{try{return NS(t.id[0])}catch{return null}})),eg=(e,t)=>{let n=new Set,r=[],o=[],s=_c(e);for(let i=0;i<e.length;i++){let c=e[i],u=c.id[0],p=c.id[1],m=s[i]??null;!(m!==null&&m<t)||p&&n.has(p)?(n.add(u),o.push(c)):r.push(c)}return{appliedEvents:r,unappliedEvents:o}},tg=e=>{let t=new Set(e.actions),n=S=>t.has(S),r=S=>{let{userId:M,userName:L,...F}=S,j=TS(F);if(l(j))return a(j.message);let z=j.value,X=S.id?.[0];return X?MS(F,z)?d("Decoded persisted event",{id:X,action:z,payload:F[z],userId:M}):a(`Persisted event is missing payload for action: ${z}`):a("Persisted event is missing id")},o=(S,M)=>{let L=[],F=new Map,j=new Map;for(let z of S){if(!Nc(z.v)){j.set(z.v,(j.get(z.v)??0)+1),M?.push({eventId:z.id[0],reason:"unsupported-schema-version",detail:`v${z.v}`,targetNodeId:da(z)});continue}let X=r(z);if(l(X)){M?.push({eventId:z.id[0],reason:"invalid-payload",detail:X.message,targetNodeId:da(z)});continue}let ne=X.value.action;if(!n(ne)){F.set(ne,(F.get(ne)??0)+1),M?.push({eventId:z.id[0],reason:"unknown-action",detail:ne,targetNodeId:da(z)});continue}let qe=e.readPayload(ne,X.value.payload);if(l(qe)){M?.push({eventId:z.id[0],reason:"invalid-payload",detail:qe.message,targetNodeId:da(z)});continue}L.push(X.value)}if(F.size>0){let z=[...F.entries()].map(([X,ne])=>`${X} (x${ne})`).join(", ");ie.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${z}. Upgrade to apply them.`)}if(j.size>0){let z=[...j.entries()].map(([X,ne])=>`v${X} (x${ne})`).join(", ");ie.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${z}. Upgrade to apply them.`)}return d("Decoded reconstructed events",L)},s=null;function i(S,M){let L=xt(S),F=Wt(S);if(!js.existsSync(L))return d("No events found",[]);let j=[],z=[];for(let ne=1;;ne++){j=[],z=[];let qe=!1;for(let q of Tc(L)){let se=Zf(ua.join(L,q),z);if(l(se))return a(se.message);if(se.value===null){if(ne<wc){qe=!0;break}continue}for(let gt of se.value)j.push(gt)}if(!qe)break}if(M)for(let ne of z)M.push(ne);let X=Xf(j,e.genesis);return s={root:S,signature:F,edge:X.at(-1)?.id?.[0]??null},d("All events loaded",X)}function c(S){let M=[],L=i(S,M);if(l(L))return a(L.message);let F=o(L.value,M);return l(F)?a(F.message):d("Loaded merged events",{events:F.value,unreadable:M})}function u(S){let M=i(S);return l(M)?a(M.message):d("Loaded event actors",M.value.map(({userId:L,userName:F})=>({userId:L,userName:F})))}function p(S){let M=new Map,L=xt(S),F;try{if(!js.existsSync(L))return M;F=js.readdirSync(L)}catch{return M}let j=new Set;for(let X of F){if(!X.endsWith(".jsonl"))continue;let ne=Qf(X);if(l(ne))continue;let{userId:qe,userName:q}=ne.value;if(!qe||!q||q===ma)continue;let se=M.get(qe);se!==void 0&&se!==q&&j.add(qe),M.set(qe,q)}if(j.size===0)return M;let z=u(S);if(l(z))return M;for(let{userId:X,userName:ne}of z.value)j.has(X)&&(!ne||ne===ma||M.set(X,ne));return M}function m(S){let M=c(S);return l(M)?a(M.message):d("Loaded merged events",M.value.events)}function f(S,M){let L=i(S);if(l(L))return a(L.message);let{appliedEvents:F,unappliedEvents:j}=eg(L.value,M),z=o(F);if(l(z))return a(z.message);let X=o(j);return l(X)?a(X.message):d("Loaded merged events before time",{appliedEvents:z.value,unappliedEvents:X.value})}function h(S=process.cwd()){let M=Wt(S);if(s&&s.root===S&&s.signature===M)return d("Loaded edge reference, unchanged",s.edge);let L=i(S);return l(L)?a(L.message):d("Loaded edge reference",L.value.at(-1)?.id?.[0]??null)}function b(S,M,L){if(!s||s.root!==S)return;let F=Mc(S,s.signature,M);s=F===null?null:{root:S,signature:F,edge:L}}function I(){s=null,DS()}let C=S=>Xf(S,e.genesis);function T(S){let M=i(S);if(l(M))return a(M.message);let L=_c(M.value);return d("Loaded effective event times",new Map(M.value.map((F,j)=>[F.id[0],L[j]??null])))}return{fromPersistedEvent:r,decodeReconstructedEvents:o,loadMergedEventsWithUnreadable:c,loadEventActors:u,loadActorNames:p,loadMergedEvents:m,loadMergedEventsBefore:f,getEdgeRef:h,advanceEdgeRef:b,clearEdgeCache:I,getSortedEvents:C,loadEffectiveEventTimes:T}}});var pa,B,Eo,rr,or,FS,ng,fa=g(()=>{"use strict";Bt();N();pa=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),B=(e,t)=>({...pa(e,t),convergence:!0}),Eo=e=>l(e)&&e.convergence===!0,rr=e=>{let t=e.filter(l);return{fatal:t.filter(n=>!Eo(n)),skipped:t.filter(Eo)}},or=e=>{e.length!==0&&ie.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},FS=e=>e.userId?.length?null:pa("Invalid user ID format",e),ng=e=>{let t=null;function n(o,s=!1){let i=e.apply[o.action];if(!i)return a(`Unknown event action "${o.action}", likely created by a newer epiq version. Evt id: ${o.id}`);if(!e.replay.isInitialized()&&o.action!==e.genesis)return B(`${o.action} arrived before the state was initialized`,o);if(o.action===e.genesis&&t){if(t.genesisApplied)return B("the state is already initialized",o);t.genesisApplied=!0}let c;try{c=i(o)}catch(m){return B(`threw while materializing (${m instanceof Error?m.message:String(m)})`,o)}if(l(c))return c;let u=FS(o);if(u)return u;let p=e.replay.afterApply(o,{batched:t!==null,bypassLogging:s});return p||c}return{materialize:n,materializeAll:o=>{let s=e.replay.batch(()=>{let i=t===null;i&&(t={genesisApplied:!1});let c=!1;try{let u=o.map(p=>n(p));if(i){c=!0;let p=e.replay.flush();if(p)return o.map(()=>p)}return u}finally{i&&(t=null,c||e.replay.flush())}});return l(s)?o.map(()=>a(s.message)):s.value}}}});var rg,og=g(()=>{"use strict";rg=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown"});import sg from"node:fs";import Bc from"node:path";import{decodeTime as BS,monotonicFactory as $S}from"ulid";var jS,US,HS,sr,ig,ag,lg,ga=g(()=>{"use strict";Bt();N();Q();og();at();_s();jt();tr();Fr();jS=0xffffffffffff,US=wi,HS=e=>{let t=Date.now(),n;try{n=BS(e)}catch{return t}return n>=jS?t:n>t+US?(ie.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)},sr=({userId:e})=>`${rg(e)}.jsonl`,ig=(e,t)=>{let n;try{if(!sg.existsSync(e))return[t];n=sg.readdirSync(e)}catch{return[t]}let r=Bs(t);return[...n.filter(s=>!s.endsWith(".jsonl")||s===t||_r(s)?!1:Bs(s)===r).sort(),t]},ag=(e,{userId:t})=>{let n=sr({userId:t});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(n))return a(`Invalid event log file name: ${n}`);let o=Bc.join(xt(e),n);return d("Successfully resolved event log path",o)},lg=e=>{let t=$S();function n(o,s){let i;if(s&&s.current!==void 0)i=s.current;else{let u=e.getEdgeRef(o);if(l(u))return a(u.message);i=u.value}let c=i?t(HS(i)):t();return d("Minted event id",[c,i])}function r({event:o,rootDir:s,edge:i,id:c}){try{let u=Ep(s);if(l(u))return u;let p=ag(s,{userId:o.userId});if(l(p))return p;let m=Gf(s,Bc.basename(p.value)),f=c?d("Minted event id",c):n(s,i);if(l(f))return a(f.message);let[h,b]=f.value,I=Cc(Lf(o),[h,b]);if(l(I))return a(I.message);Vf(m,`${JSON.stringify(I.value)}
|
|
44
|
+
`),i&&(i.current=h);let C=Bc.basename(m);return e.advanceEdgeRef(s,C,h),jf(s,C),d("Event persisted",{path:m,entry:I.value})}catch(u){let p=u instanceof Error?u.message:"Unknown persist error";return a(`Failed to persist event: ${p}`)}}return{mintEventId:n,persist:r}}});var cg,dg=g(()=>{"use strict";N();cg=(e,t,n)=>{function r(s,i,c){let u=n.mintEventId(i,c);if(l(u))return a(u.message);let p={...s,id:u.value[0]},m=t.materialize(p);if(m.status!==Tn.Success)return m;let f=n.persist({event:p,rootDir:i,edge:c,id:u.value});return l(f)?f:m}function o(s,i){if(s.length===0||!s[0])return a("No events provided");let c=e.write.readOnlyReason();if(c)return a(c);let u=e.replay.batch(()=>{let p={},m=e.write.beforeWrite(s[0],b=>r(b,i,p));if(l(m))return a(m.message);let f=s.map(b=>r(b,i,p)),h=f.filter(l);return h.length>0?a("Materialize and persist failed: "+h.map(b=>b.message).join(", ")):d("Materialization succeeded",f.map(b=>b.value))});return l(u)?a(u.message):u.value??a("Materialize and persist produced nothing")}return{materializeAndPersist:r,materializeAndPersistAll:o}}});var ug,mg=g(()=>{"use strict";Fc();fa();ga();dg();ug=e=>{let t=ng(e),n=tg(e),r=lg(n),o=cg(e,t,r);return{...t,...n,...r,...o}}});import{z as ee}from"zod";var Y,ln,ir,ha,$c,WS,pg,fg=g(()=>{"use strict";N();Y=ee.string().min(1),ln=ee.string(),ir=ee.string(),ha=ee.looseObject({id:Y}),$c=ee.looseObject({id:Y,name:ln,parent:Y,rank:ir}),WS={"init.workspace":ee.looseObject({id:Y,name:ln,rank:ir}),"add.workspace":ee.looseObject({id:Y,name:ln,rank:ir}),"add.board":$c,"add.swimlane":$c,"add.issue":$c,"add.field":ee.looseObject({id:Y,name:ln,parent:Y,rank:ir}),"edit.title":ee.looseObject({id:Y,name:ln}),"delete.node":ha,"lock.node":ha,"move.node":ee.looseObject({id:Y,parent:Y,rank:ir}),"edit.description":ee.looseObject({id:Y,md:ee.string()}),"close.issue":ee.looseObject({id:Y,parent:Y,rank:ir}),"reopen.issue":ee.looseObject({id:Y,parent:Y,rank:ir}),"create.tag":ee.looseObject({id:Y,name:ln}),"tombstone.tag":ha,"restore.tag":ee.looseObject({id:Y,name:ln}),"create.contributor":ee.looseObject({id:Y,name:ln}),"rename.contributor":ee.looseObject({id:Y,name:ln}),"tombstone.contributor":ha,"restore.contributor":ee.looseObject({id:Y,name:ln}),"link.contributor.user":ee.looseObject({contributor:Y}),"link.contributor.email":ee.looseObject({contributor:Y,email:Y}),"unlink.contributor.email":ee.looseObject({contributor:Y,email:Y}),"add.issue.assignee":ee.looseObject({id:Y,assignee:Y}),"remove.issue.assignee":ee.looseObject({id:Y,assignee:Y}),"add.issue.tag":ee.looseObject({id:Y,tag:Y}),"remove.issue.tag":ee.looseObject({id:Y,tag:Y}),"add.issue.comment":ee.looseObject({id:Y,issue:Y,md:ee.string()}),"edit.issue.comment":ee.looseObject({id:Y,issue:Y,md:ee.string()}),"delete.issue.comment":ee.looseObject({id:Y,issue:Y}),"add.issue.attachment":ee.looseObject({id:Y,issue:Y,hash:ee.string().min(1),ext:ee.string().min(1),name:ln,bytes:ee.number()}),"delete.issue.attachment":ee.looseObject({id:Y,issue:Y}),"rebalance.children":ee.looseObject({parent:Y,ranks:ee.record(ee.string(),ir)})},pg=(e,t)=>{let r=WS[e].safeParse(t);return r.success?d("Payload is readable",void 0):a(`${e}: ${r.error.issues.map(o=>`${o.path.join(".")||"payload"} ${o.message}`).join(", ")}`)}});import{ulid as qS}from"ulid";var gg,hg=g(()=>{"use strict";N();de();$e();gg=(e,t)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return d("Contributor write already in flight",void 0);let{userId:n,userName:r}=ae();if(!r||n!==e.userId)return d("Not this actor own write",void 0);let o=R.getContributor(e.userId),s={id:qS(),action:o?"rename.contributor":"create.contributor",payload:{id:e.userId,name:r},userId:e.userId};if(o&&(o.tombstoned||o.name===r))return d("Contributor name is current",void 0);let i=t(s);return l(i)?a(i.message):d("Contributor name recorded",void 0)}});var Ae,So=g(()=>{"use strict";Ae={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",DIFF:"Diff",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var V,Us,mt=g(()=>{"use strict";V=e=>e.slice(-7).toUpperCase(),Us=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?V(e).includes(n):!0}});var Fe,ar=g(()=>{"use strict";ce();mt();Fe={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:re.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:V(e)},context:re.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:re.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:re.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:re.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:V(e)},context:re.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0,disabled:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:i?{disabled:!0}:{},context:re.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:re.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})}});var Hs,vg,yg=g(()=>{"use strict";ce();N();So();wt();de();ar();D();fa();on();Hs=(e,t,n)=>R.getNode(e)?B(`a node with id ${e} already exists`,n):t===e?B("a node cannot be its own parent",n):null,vg={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Fe.workspace(t,n,r),s=Ws(o);if(l(s))return pa(s.message,e);let i=R.createNode(o);return l(i)?B(i.message??"Failed to initialize workspace",e):$l(i.value)?d("Workspace initialized",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Hs(t,void 0,e);if(o)return o;let s=R.createNode(Fe.workspace(t,n,r));return l(s)?B(s.message??"Failed to add workspace",e):$l(s.value)?d("Added workspace",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Hs(t,r,e);if(s)return s;let i=R.createNode(Fe.board(t,n,r,o));return l(i)?B(i.message??"Unable to create board",e):Sr(i.value)?d("Added board",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Hs(t,r,e);if(s)return s;let i=R.createNode(Fe.swimlane(t,n,r,o));return l(i)?B(i.message??"Unable to create swimlane",e):Er(i.value)?d("Added swimlane",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Hs(t,r,e);if(s)return s;let i=R.createNode(Fe.ticket(t,n,r,o));return l(i)?B(i.message??"Unable to create issue",e):U(i.value)?d("Added issue",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=Hs(t,r,e);if(i)return i;let c=R.createNode(Fe.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(Ae.DESCRIPTION)?"vertical":"horizontal"}));return l(c)?B(c.message??`Unable to create field: ${n}`,e):et(c.value)?d("Added field",{action:e.action,result:c.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!R.getNode(t))return B(`Unable to locate node with id ${t}`,e);let o=R.renameNode(t,n);return l(o)?B(o.message??"Unable to edit title",e):d("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=R.tombstoneNode(t);return l(n)?B(n.message??"Unable to delete node",e):d("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=R.createTag({id:t,name:n});return l(r)?B(r.message??"Unable to create tag",e):d("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=R.tombstoneTag(t);return l(n)?B(n.message??"Unable to delete tag",e):d("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=R.restoreTag(t,n);return l(r)?B(r.message??"Unable to restore tag",e):d("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=R.createContributor({id:t,name:n});return l(r)?B(r.message??"Unable to create contributor",e):d("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=R.renameContributor(t,n);return l(r)?B(r.message??"Unable to rename contributor",e):d("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=R.tombstoneContributor(t);return l(n)?B(n.message??"Unable to remove contributor",e):d("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,r=R.restoreContributor(t,n);return l(r)?B(r.message??"Unable to restore contributor",e):d("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=R.tag(t,n);return l(r)?B(r.message??"Unable to tag issue",e):d("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=R.untag(t,n);return l(r)?B(r.message??"Unable to untag issue",e):d("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=R.assign(t,n);return l(r)?B(r.message??"Unable to assign issue",e):d("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=R.unassign(t,n);return l(r)?B(r.message??"Unable to unassign issue",e):d("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=R.moveNodeToRank({id:t,parentId:n,rank:r});return l(o)?B(o.message??"Failed to move node",e):d("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=R.editValue(t,n);return l(r)?B(r.message??"Unable to edit description",e):d("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=R.getNode(t);if(!o)return B("Unable to locate issue",e);if(!U(o))return B("Can only close issues",e);let s=R.getNode(Ce);if(!s)return B("Unable to locate target swimlane",e);if(n!==s.id)return B("Close target must be closed swimlane",e);let i=R.moveNodeToRank({id:t,parentId:n,rank:r});return l(i)?B(i.message??"Unable to close issue",e):d("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=R.getNode(t);if(!o)return B("Unable to locate issue",e);if(!U(o))return B("Can only reopen issues",e);let s=R.getNode(Ce);if(!s)return B("Unable to locate closed swimlane",e);if(n===s.id)return B("Cannot reopen issue into closed swimlane",e);if(!R.getNode(n))return B("Reopen parent no longer exists",e);let c=R.moveNodeToRank({id:t,parentId:n,rank:r});return l(c)?B(c.message??"Unable to reopen issue",e):d("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=R.lockNode(t);return l(n)?B(n.message??"Unable to lock node",e):d("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let s=R.getNode(r);if(!s)return B(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return B(`Node ${r} is not child of ${t}`,e);let i=R.updateNode({...s,rank:o});if(l(i))return B(i.message??"Unable to rebalance child",e)}return d("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=R.createComment({id:t,issue:n,authorId:r,md:o,deleted:!1});return l(s)?B(s.message??"Unable to add comment",e):d("Comment added",{action:e.action,result:{id:t,issue:n,author:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=e.payload,o=R.getComment(t);if(!o)return B("Unable to locate comment",e);if(o.issue!==n)return B("Comment does not belong to issue",e);let s=R.editComment(t,r);return l(s)?B(s.message??"Unable to edit comment",e):d("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=R.getComment(t);if(!r)return B("Unable to locate comment",e);if(r.issue!==n)return B("Comment does not belong to issue",e);let o=R.deleteComment(t);return l(o)?B(o.message??"Unable to delete comment",e):d("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:r,ext:o,name:s,bytes:i}=e.payload,c=R.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return l(c)?B(c.message??"Unable to add attachment",e):d("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=R.getAttachment(t);if(!r)return B("Unable to locate attachment",e);if(r.issue!==n)return B("Attachment does not belong to issue",e);let o=R.deleteAttachment(t);return l(o)?B(o.message??"Unable to delete attachment",e):d("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.email":e=>{let{contributor:t,email:n}=e.payload;if(!Vn(n))return B(`not an email address: ${n}`,e);let r=R.linkContributorEmail({email:n,contributor:t,authorId:e.userId});return l(r)?B(r.message??"Unable to link email",e):d("Email linked to contributor",{action:e.action,result:r.value})},"unlink.contributor.email":e=>{let{contributor:t,email:n}=e.payload,r=R.unlinkContributorEmail(n,t,e.userId);return l(r)?B(r.message??"Unable to unlink email",e):d("Email unlinked from contributor",{action:e.action,result:r.value})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=R.linkUserId({contributorId:t,userId:e.userId});return l(n)?B(n.message??"Unable to link contributor",e):d("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}}});var bg,xg,GS,zS,jc,VS,Fn,KS,Ig,Uc=g(()=>{"use strict";ce();N();de();D();Hc();bg=e=>{let t=R.getNode(e);if(!t||!U(t)||t.isDeleted)return null;let n=ya(t);return l(n)?n:null},xg=e=>{if(!ba())return null;for(let t of e){let n=bg(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=bg(r);if(o)return o}return null},GS=(e,t)=>{let n=R.getNode(e);n&&R.updateNode({...n,log:[...n.log??[],t]})},zS=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},jc=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 zS(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":case"link.contributor.email":case"unlink.contributor.email":default:return[]}},VS=e=>{ke(t=>({...t,eventLog:[...t.eventLog,e]}))},Fn=null,KS=e=>{for(let[t,n]of e.nodeLog){let r=R.getNode(t);r&&R.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&ke(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),xg([...e.virtualNodeIds])},Ig={isInitialized:()=>qt(),batch:e=>va(e),afterApply(e,{batched:t,bypassLogging:n}){let r=[...new Set(jc(e))];if(t){Fn??={appLog:[],nodeLog:new Map,virtualNodeIds:new Set};for(let o of r){if(!n){let s=Fn.nodeLog.get(o);s?s.push(e):Fn.nodeLog.set(o,[e])}if(ba()){Fn.virtualNodeIds.add(o);let s=v().nodes[o]?.parentNodeId;s&&Fn.virtualNodeIds.add(s)}}return n||Fn.appLog.push(e),null}return n||(r.forEach(o=>GS(o,e)),VS(e)),xg(r)},flush(){if(!Fn)return null;let e=Fn;return Fn=null,KS(e)}}});var fe,Eg=g(()=>{"use strict";N();$e();xr();fe=()=>{let{userName:e,userId:t}=ae();return e?t?Ai(t)?as(e)?d("Successfully resolved actor ID",{userId:t,userName:e}):a("Invalid user name in config"):a("Invalid user ID in config"):a("User ID not configured"):a("User name not configured")}});var YS,XS,qs,Bn,tO,nO,cn,Sg,Br,$r,Wc,rO,oO,sO,iO,qc,aO,Rg,lO,_,$=g(()=>{"use strict";_s();mg();fg();D();hg();Ut();yg();Uc();Eg();_s();Fc();fa();ga();YS={genesis:"init.workspace",actions:Sc,readPayload:pg,apply:vg,replay:Ig,write:{readOnlyReason:()=>{let e=v();return e.readOnly?e.readOnlyReason??"Cannot change the board while time travelling":null},beforeWrite:gg}},XS=ug(YS),{materialize:qs,materializeAll:Bn,fromPersistedEvent:tO,decodeReconstructedEvents:nO,loadMergedEventsWithUnreadable:cn,loadEventActors:Sg,loadActorNames:Br,loadMergedEvents:$r,loadMergedEventsBefore:Wc,getEdgeRef:rO,advanceEdgeRef:oO,clearEdgeCache:sO,getSortedEvents:iO,loadEffectiveEventTimes:qc,mintEventId:aO,persist:Rg,materializeAndPersist:lO,materializeAndPersistAll:_}=XS});var jr,Gc,Ng=g(()=>{"use strict";mt();jr=e=>e.trim().toLocaleLowerCase(),Gc=(e,t)=>jr(e).includes(jr(t))});var JS,QS,Cg,Ag,ZS,eR,wg,Tg=g(()=>{"use strict";D();mt();Ng();JS=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},QS=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},Cg=null,Ag=new Map,ZS=()=>{let e=v().eventLog??[];if(e===Cg)return Ag;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 Cg=e,Ag=t,t},eR=e=>{let{contributors:t}=v(),n=ZS().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},wg=(e,t)=>{let n=jr(t.value);if(!n)return!0;switch(t.target){case"title":return Gc(e.title??"",n);case"description":return Gc(e.props.description??"",n);case"tag":return JS(e).map(jr).some(o=>o.includes(n));case"assignee":return QS(e).map(jr).some(o=>o.includes(n));case"actor":return eR(e).map(jr).some(o=>o.includes(n));case"ref":return Us(e.id,t.value);default:return!0}}});var zc,tR,Mg,kg,Lg,Vc=g(()=>{"use strict";ce();Tg();zc=(e,t)=>e.rank<t.rank?-1:e.rank>t.rank?1:0,tR=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,Mg=(e,t)=>Object.values(e).filter(n=>tR(n,t)).sort(zc),kg=(e,t)=>{let n={};for(let r of Object.values(e)){if(U(r)&&t.length>0&&!t.every(s=>wg(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(zc);return n},Lg=(e,t)=>{let n={};for(let r of Object.values(e)){if(!r.parentNodeId||r.isDeleted||!t.has(r.parentNodeId))continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(zc);return n}});var Pg,xa,Te,Dg,Og,En,$n,Ht=g(()=>{"use strict";Pf();$();N();D();Vc();xo();Pg=e=>xa(Te(e),{at:"end"}),xa=(e,t={at:"end"})=>{let n=o=>l(o)?d("Rank space exhausted",{rank:"",needsRebalance:!0}):d("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(ut(void 0,void 0));let r=()=>n(ut(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(ut(void 0,o.rank)):a("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(ut(o.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let o=Dg(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o>0?e[o-1]:void 0;return n(ut(i?.rank,s.rank))}case"after":{let o=Dg(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o<e.length-1?e[o+1]:void 0;return n(ut(s.rank,i?.rank))}}},Te=e=>{let t=v();if(!_g()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return Mg(t.nodes,e)},Dg=(e,t)=>e.findIndex(n=>n.id===t),Og=(e,t,n={at:"end"})=>xa(Te(t).filter(r=>r.id!==e),n),En=(e,t,n,r,o)=>{let s=Og(t,e,n);if(l(s))return s;if(!s.value.needsRebalance)return d("Resolved rank",s.value.rank);let i=Rc(e,r);if(l(i))return i;let c=_([i.value],o);if(l(c))return c;let u=Og(t,e,n);return l(u)?u:u.value.needsRebalance?a("Rank rebalance failed to create space"):d("Resolved rank after rebalance",u.value.rank)},$n=(e,t,n)=>{let r=Pg(e);if(l(r))return r;if(!r.value.needsRebalance)return d("Resolved rank",r.value.rank);let o=Rc(e,t);if(l(o))return o;let s=_([o.value],n);if(l(s))return s;let i=Pg(e);return l(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):d("Resolved rank after rebalance",i.value.rank)}});var Gs,H,Fg,Bg,$g,Et=g(()=>{"use strict";D();Gs=5,H={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=ve(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||H.navigate({contextNode:o,selectedIndex:ve(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=ve(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;H.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Fg(1),navigateToPreviousItem:()=>Fg(-1),jumpToNextItem:()=>Bg(Gs),jumpToPreviousItem:()=>Bg(-Gs),navigateToNextContainer:()=>$g(1),navigateToPreviousContainer:()=>$g(-1),navigate:({contextNode:e,selectedIndex:t})=>{A({contextNodeId:e.id,selectedIndex:t})}},Fg=e=>{let{selectedIndex:t,contextNode:n}=v(),r=ve(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;H.navigate({selectedIndex:s,contextNode:n})},Bg=e=>{let{selectedIndex:t,contextNode:n}=v(),r=ve(n.id).length;if(r===0)return;let o=Math.max(0,t),s=Math.min(Math.max(o+e,0),r-1);H.navigate({selectedIndex:s,contextNode:n})},$g=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=ve(o.id),i=s.findIndex(h=>h.id===t.id);if(i<0)return;let c=s.at(i+e)??s.at(0);if(!c)return;let u=ve(c.id),p=Math.max(0,u.length-1),m=Math.min(Math.max(0,r),p),f=u.length?m:-1;H.navigate({contextNode:c,selectedIndex:f})}});var Ug,Hg,nR,Ia,Wg,jg,rR,qg,Gg=g(()=>{"use strict";ce();N();Ht();D();Et();Ug=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Hg=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},nR=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&&et(t)&&t.childRenderAxis==="vertical"},Ia=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=Te(r.id);return H.navigate({contextNode:r,selectedIndex:Ug(t,o.length)}),!0},Wg=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Ia(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=Te(o.id).findIndex(c=>c.id===n.id);return i>=0?(H.navigate({contextNode:o,selectedIndex:i}),!0):Wg(o.id)},jg=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Wg(n))return!0;n=t[n]?.parentNodeId}return!1},rR=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},qg=e=>{let{nodes:t,rootNodeId:n}=v();if(nR(e.contextNodeId)&&Ia(e.contextNodeId,e.selectedIndex))return d("Restored navigation inside text container",null);if(rR(e.selectedNodeId)&&e.selectedNodeId&&jg(e.selectedNodeId))return d("Restored navigation to selected node or ancestor",null);if(Ia(e.contextNodeId,e.selectedIndex))return d("Restored navigation to previous container",null);if(e.parentNodeId&&Ia(e.parentNodeId,e.selectedIndex))return d("Restored navigation to previous parent",null);if(jg(e.contextNodeId))return d("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return a("Unable to restore navigation");let o=Te(r.id);return H.navigate({contextNode:r,selectedIndex:Ug(e.selectedIndex,o.length)}),d("Restored navigation to root",null)}});import{monotonicFactory as oR,ulid as Sn}from"ulid";function sR(){let e=Ee();if(l(e))return a("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return a("No workspace found in event log");let[r]=ve(n.id),[o]=r?ve(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return d("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?d("Resolved boot nav target",{contextNode:r,selectedIndex:0}):d("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function iR(){let e=sR();return l(e)?e:H.navigate(e.value)}function zg({userId:e,userName:t}){let n=zs(),r=zs(),o=zs(),s=zs(),i=zs(),c=ut(void 0,void 0);if(l(c))return c;let u=ut(void 0,void 0);if(l(u))return u;let p=ut(u.value,void 0);if(l(p))return p;let m=ut(void 0,void 0);if(l(m))return m;let f=ut(m.value,void 0);if(l(f))return f;let h=ut(f.value,void 0);if(l(h))return h;let b=ut(void 0,void 0);return l(b)?b:d("Created default events",[{id:Sn(),userId:e,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:Sn(),userId:e,action:"create.contributor",payload:{id:e,name:t}},{id:Sn(),userId:e,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Sn(),userId:e,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:m.value}},{id:Sn(),userId:e,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Sn(),userId:e,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:h.value}},{id:Sn(),userId:e,action:"add.board",payload:{id:Vi,name:"Closed",parent:n,rank:p.value}},{id:Sn(),userId:e,action:"add.swimlane",payload:{id:Ce,name:"Closed",parent:Vi,rank:b.value}},{id:Sn(),userId:e,action:"lock.node",payload:{id:Vi}},{id:Sn(),userId:e,action:"lock.node",payload:{id:Ce}}])}function Rn(e,t=[]){if(aR())return d("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Fe.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=Ws(s);return l(i)?i:(A({hasProjectDefinition:!1,mode:x.DEFAULT}),d("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return a("Initialized Epiq project has no workspace init event");let n=Bn(e),{fatal:r,skipped:o}=rr(n);return r.length>0?a(`Materializing failed:
|
|
45
45
|
${r.map(s=>s.message).join(`
|
|
46
|
-
`)}`):(
|
|
47
|
-
`,"utf8"),d("Wrote the state branch identity",void 0)}catch(n){return
|
|
48
|
-
`),
|
|
49
|
-
`).filter(t=>t.trim().length>0),
|
|
50
|
-
`);
|
|
46
|
+
`)}`):(or(o),iR(),A({hasProjectDefinition:!0}),lR(t),d("State booted successfully",null))}var zs,aR,lR,Ur=g(()=>{"use strict";Bt();Et();Pe();N();ar();D();xo();$();on();zs=oR();aR=()=>{let e=Ee();if(l(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},lR=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(", ");ie.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(", ");ie.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 cR}from"ws";var dR,Vg,Kg=g(()=>{"use strict";dR=new Set,Vg=e=>{let t=JSON.stringify(e);for(let n of dR)n.readyState===cR.OPEN&&n.send(t)}});var Ea,Ro,Hr,Kc,Sa,Be,Vs=g(()=>{"use strict";Kg();N();D();Ea=e=>{qt()&&(A({syncStatus:e}),Vg({type:"sync-status",payload:e}))},Ro=(e="Syncing...")=>{Ea({status:"syncing",msg:e})},Hr=(e="Synced")=>{Ea({status:"synced",msg:e})},Kc=e=>{Ea({status:"failed",msg:e})},Sa=e=>{Ea({status:"offline",msg:e})},Be=e=>(Kc(e),a(e))});var No,Yg,ge,Ra=g(()=>{"use strict";N();No=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),Yg=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}},ge=(e,t)=>(l(t)&&logger.info(`[${e}]:failed`,t.message),t)});import Na from"node:fs";import Xg from"node:path";var ot,Jg,uR,Yc,mR,Qg,Xc=g(()=>{"use strict";gn();ze();N();Q();rn();ot=".epiq/project.json",Jg=e=>Xg.join(e,ot),uR=e=>{if(!Na.existsSync(Jg(e)))return d("State branch carries no identity yet",null);let t=Mt(e);return l(t)?a(`On the state branch: ${t.message}`):d("Read the state branch identity",t.value)},Yc=(e,t)=>{try{let n=Jg(e);return Na.mkdirSync(Xg.dirname(n),{recursive:!0}),Na.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
47
|
+
`,"utf8"),d("Wrote the state branch identity",void 0)}catch(n){return a(n instanceof Error?`Failed to write the state branch identity: ${n.message}`:"Failed to write the state branch identity")}},mR=({checkout:e,branch:t,stateBranch:n})=>[`This checkout's ${ot} names project ${e.projectId}`,`(created ${e.createdAt}), but the state branch ${n}`,`belongs to project ${t.projectId} (created ${t.createdAt}).`,"","The branch holds the board, so its id is the one that counts. Point the","checkout at it and commit the change:","",` git show ${n}:${ot} > ${ot}`,"","A second id is minted when init runs in a checkout that has no","project file while the state branch already exists; nothing on the","board is lost by it, but every checkout has to agree on one."].join(`
|
|
48
|
+
`),Qg=({repoRoot:e,stateBranchRoot:t,stateBranch:n})=>{if(!Na.existsSync(ao(e)))return d("No project file to compare","no-checkout-file");let r=Mt(e);if(l(r))return a(r.message);let o=uR(t);if(l(o))return a(o.message);if(o.value===null){let s=Yc(t,r.value);return l(s)?a(s.message):d("Stamped the state branch with this project","stamped")}return o.value.projectId!==r.value.projectId?a(mR({checkout:r.value,branch:o.value,stateBranch:n})):d("The checkout and the state branch agree","matched")}});import Nn from"node:fs";import Ks from"node:path";var Co,Zg,eh,th,pR,nh,fR,gR,rh,Jc=g(()=>{"use strict";ze();N();Fr();tr();Q();Co=e=>e.split(`
|
|
49
|
+
`).filter(t=>t.trim().length>0),Zg=e=>{let t=Ks.join(e,lt,Pn);try{if(!Nn.existsSync(t))return d("No events directory",[]);let n=Nn.readdirSync(t).filter(r=>r.endsWith(".jsonl")).filter(r=>Co(Nn.readFileSync(Ks.join(t,r),"utf8")).length>0);return d("Looked for stranded event logs",n)}catch(n){return a(`Unable to check ${t} for event logs before deleting it: ${n instanceof Error?n.message:String(n)}`)}},eh=e=>Ks.join(e,lt,Pn),th=e=>{let t=eh(e),n=new Map;try{if(!Nn.existsSync(t))return n;for(let r of Nn.readdirSync(t))if(r.endsWith(".jsonl")&&!_r(r))try{n.set(r,Co(Nn.readFileSync(Ks.join(t,r),"utf8")))}catch(o){if(!Fs(o))throw o}}catch{return n}return n},pR=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},nh=(e,t)=>{if(t.size===0)return[];let n=eh(e),r=[];for(let[o,s]of t){if(s.length===0)continue;let i=Ks.join(n,o);try{let c=Nn.existsSync(i)?Nn.readFileSync(i,"utf8"):null,u=new Set(c===null?[]:Co(c)),p=s.filter(f=>!u.has(f)).filter(pR);if(p.length===0)continue;Nn.mkdirSync(n,{recursive:!0});let m=c!==null&&c.length>0&&!c.endsWith(`
|
|
50
|
+
`);Nn.appendFileSync(i,`${m?`
|
|
51
51
|
`:""}${p.join(`
|
|
52
52
|
`)}
|
|
53
|
-
`,"utf8"),r.push(`${o} (${p.length})`)}catch{continue}}return r},
|
|
54
|
-
`),
|
|
55
|
-
`));
|
|
56
|
-
${n.message}`);let r=n.value.stdout.trim(),o=await W({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return
|
|
57
|
-
${o.message}`):d("Created state branch",!0)},
|
|
58
|
-
`+n.message);if(n.value)return d("Local state branch already exists",!1);let r=await
|
|
59
|
-
`+r.message);let o=r.value,s=o?await
|
|
60
|
-
`+s.message);let i=s.value;if(o&&i){let c=await
|
|
61
|
-
${c.message}`)}if(i){let c=await W({args:["branch","--track",t,`${
|
|
62
|
-
${c.message}`):d("Created local state branch from remote",!0)}return
|
|
63
|
-
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return d("Found worktree for branch",o)}return d("No worktree found for branch",null)},
|
|
64
|
-
`+r.message);if(
|
|
65
|
-
`));
|
|
66
|
-
${o.message}`):d("Created state branch worktree",!0)},
|
|
67
|
-
`));if(s&&s!==o){let u=await
|
|
68
|
-
`));
|
|
69
|
-
${p.message}`)}if(s
|
|
70
|
-
${u.message}`)}let i=await
|
|
71
|
-
${u.message}`)}return
|
|
72
|
-
${o.message}`):d("Checked out state branch",!0)},
|
|
73
|
-
${c.message}`);let u=await
|
|
74
|
-
${u.message}`):d("Configured state branch upstream",!0)},
|
|
75
|
-
${s.message}`):d("Staged state branch event file",n)},
|
|
76
|
-
${r.message}`):d("Staged state branch media files",t)},
|
|
77
|
-
${n.message}`):d("Staged event log config",t)},
|
|
78
|
-
`+r.message):
|
|
79
|
-
${s.message}`);let i=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return d(i?"Pushed state branch":"Remote already up to date",i)},ih=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=dt(e);if(a(o))return o;let s=o.value,i=[vs(),await Vs({repoRoot:e,stateBranchName:s}),await ir({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await yS({stateBranchRoot:t,stateBranchName:s}),await hp(t),n?await bS({stateBranchRoot:t,repoRoot:e}):d("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(a(c))return l(c.message);r=r||!!c.value}return d(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)}});import Co from"node:fs";import Jc from"node:os";import xS from"node:path";var Qc,ah,IS,ES,RS,ch,Xc,lh,SS,Xs,Zc=g(()=>{"use strict";N();Ke();_t();Qc="epiq-sync.lock",ah=600*1e3,IS=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}},ES=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},RS=e=>e?e.hostname!==Jc.hostname()||ES(e.pid)?Date.now()-e.startedAt>ah?"stale":null:"dead":"stale",ch=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,Xc=e=>{try{return IS(Co.readFileSync(e,"utf8"))}catch{return null}},lh=(e,t)=>{let n={pid:process.pid,hostname:Jc.hostname(),startedAt:Date.now(),operation:t},r=`${e}.${process.pid}.pending.lock`;try{return Co.writeFileSync(r,JSON.stringify(n)),Co.linkSync(r,e),!0}catch{return!1}finally{try{Co.rmSync(r,{force:!0})}catch{}}},SS=async({worktreeRoot:e,operation:t})=>{let n=await _i(e);if(a(n))return l(n.message);let r=xS.join(n.value,Qc),o=()=>{try{let u=Xc(r);u&&u.pid===process.pid&&Co.rmSync(r)}catch{}};if(lh(r,t))return d("Acquired sync lock",{acquired:!0,claim:"clean",release:o});let s=Xc(r),i=RS(s);if(i===null)return d("Sync lock is held",{acquired:!1,heldBy:s});ce.info(`Breaking an abandoned sync lock: ${s?ch(s):"unreadable lock file"}`);try{Co.rmSync(r,{force:!0})}catch{}if(lh(r,t))return d("Acquired sync lock after breaking a stale one",{acquired:!0,claim:i,release:o});let c=Xc(r);return d("Sync lock taken by another process",{acquired:!1,heldBy:c??{pid:-1,hostname:Jc.hostname(),startedAt:Date.now(),operation:"unknown"}})},Xs=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await SS({worktreeRoot:e,operation:t});if(a(r))return l(r.message);if(!r.value.acquired)return ce.info(`Skipping ${t}: the state worktree is held by ${ch(r.value.heldBy)}`),d("State worktree is held by another process",null);let{claim:o,release:s}=r.value;try{return d("Ran under the sync lock",await n(o))}finally{s()}}});import uh from"node:fs";var NS,CS,ed,dh,Na,Ca,wa=g(()=>{"use strict";N();Gs();pa();ee();Ea();mn();rt();Ke();Ys();Kc();_r();Zc();NS=async({claim:e,cwd:t,ensureUpstream:n})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:t,ensureUpstream:n});let r=ve("getRepoRootDir",await kt(t));if(a(r))return l(r.message);let o=r.value;logger.debug("[sync] repo root",o);let s=ve("getStateBranchRoot",Ie({repoRoot:o}));if(a(s))return l(s.message);let i=s.value;if(logger.debug("[sync] state branch root",i),e!=="stale"&&uh.existsSync(i)){let m=await rp(i,{preserve:[Qc]});if(a(m))return l(m.message);m.value.length>0&&logger.info("[sync] cleared git lock files left by a dead process",{removed:m.value,stateBranchRoot:i});let f=ve("abortRebaseIfPresent(stateBranchRoot)",await Yl(i));if(a(f))return l(f.message)}logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:i,ensureUpstream:n});let c=ve("bootstrapStateBranchStorage",await ih({repoRoot:o,stateBranchRoot:i,ensureUpstream:n}));if(a(c))return l(c.message);logger.debug("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:i}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:i});let u=ve("getInProgressGitOperation(stateBranchRoot)",await Vl(i));if(a(u))return l(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value!==null)return logger.info("[sync] state branch git operation in progress",{claim:e}),l(`Cannot sync while there is a ${u.value} in the state branch at ${i}`);logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:i});let p=ve("ensureStateBranchLayout",gp(o,i));return a(p)?l(p.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:i,bootstrapped:c.value}),d("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:i,bootstrapped:c.value}))},CS=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=[];for(let p of rg(bt(t),n)){let m=ve("stageStateBranchOwnEventFile",await Sa({stateBranchRoot:t,eventFileName:p}));if(a(m))return l(m.message);r.push(m.value)}let o=ve("stageStateBranchMediaFiles",await rh({stateBranchRoot:t}));if(a(o))return l(o.message);let s=ve("stageStateBranchEventConfig",await oh({stateBranchRoot:t}));if(a(s))return l(s.message);let i=[...r,o.value,...s.value].filter(p=>p!==null);if(i.length===0)return d("Nothing to stage",{createdCommit:!1});let c=ve("hasStagedChanges(after stage)",await ip(t,i));if(a(c))return l(c.message);if(logger.debug("[sync] state branch change check after stage result",{changed:c.value}),!c.value)return logger.info("[sync] no own event file changes to commit"),d("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let u=ve("createStateBranchSyncCommit",await sh({repoRoot:e,stateBranchRoot:t,pathspec:i}));return a(u)?l(u.message):(logger.debug("[sync] created sync commit",u.value),d("Committed own event file",{createdCommit:!0,commitSha:u.value}))},ed=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return Ia(n),d(n,{...e,pulled:!1,pushed:!1,offline:!0})},dh=async({cwd:e=process.cwd(),ownEventFileName:t},n)=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),l("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}),l("Own event file must end with .jsonl");Ro();let r=ve("ensureSyncReady",await NS({claim:n,cwd:e,ensureUpstream:!0}));if(a(r))return je(r.message);let{repoRoot:o,stateBranchRoot:s,bootstrapped:i}=r.value,c=ve("isDetachedHead(stateBranchRoot)",await ap(s));if(a(c))return je(c.message);if(logger.debug("[sync] detached state branch check result",{detached:c.value}),c.value)return je("Cannot run :sync while the state branch is in detached HEAD state");let u=!1,p,m=!1,f=!1,h=ve("getStateBranch",dt(o));if(a(h))return je(h.message);let b=h.value;logger.debug("[sync] resolved state branch",{stateBranch:b,stateBranchRoot:s});let E=ve("flushPendingLogs",aa(s,t));a(E)&&logger.error(`[sync] ${E.message}`);let S=ve("commitOwnEventFileToStateBranch",await CS({repoRoot:o,stateBranchRoot:s,ownEventFileName:t}));if(a(S))return je(S.message);u=S.value.createdCommit,p=S.value.commitSha;let w=ve("hasRemote",await Mn({repoRoot:s}));if(a(w))return je(w.message);if(!w.value)return ed({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i},"no remote");let R=ve("pullBranchRebaseIfPresent",await gs({cwd:s,branch:b}));if(a(R))return fs(R.message)?ed({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i}):je(R.message);m=R.value;let k=ve("isAheadOfUpstream",await op(s));if(a(k))return je(k.message);if(u||i||k.value){logger.info("[sync] pushing state branch",{createdCommit:u,bootstrapped:i,stateBranchRoot:s});let M=ve("pushStateBranch",await Ks({stateBranchRoot:s,repoRoot:o}));if(a(M)&&tp(M.message)){let F=ve("pullBranchRebaseIfPresent(retry)",await gs({cwd:s,branch:b}));if(a(F))return je(F.message);m=m||F.value,M=ve("pushStateBranch(retry)",await Ks({stateBranchRoot:s,repoRoot:o}))}if(a(M))return fs(M.message)?ed({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i}):je(M.message);f=M.value}if(u){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:s});let M=ve("git rev-parse HEAD",await W({args:["rev-parse","HEAD"],cwd:s}));if(a(M))return je(M.message);p=M.value.stdout.trim(),logger.debug("[sync] final sync commit sha",p)}return Ur(f?"Synced and pushed":m||u?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),d("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,pulled:m,pushed:f,bootstrapped:i,offline:!1})},Na=async(e,t)=>{let n=Qg(e);try{return await t()}finally{let r=Zg(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},Ca=async e=>{let t=e.cwd??process.cwd(),n=await kt(t);if(a(n))return je(n.message);let r=Ie({repoRoot:n.value});if(a(r))return je(r.message);let o=r.value;if(!uh.existsSync(o))return dh(e,"clean");let s=await Xs({worktreeRoot:o,operation:"sync",fn:i=>Na(o,()=>dh(e,i))});return a(s)?je(s.message):s.value===null?d("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 Sn,Aa,wS,td,mh,Ta=g(()=>{"use strict";Hg();jr();$();$();Oe();N();D();Gs();Ea();wa();Sn=null,Aa=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Sn,currentStatus:v().syncStatus?.status,currentMessage:v().syncStatus?.msg}),Sn)return logger.debug("[sync] syncAndReloadState joining existing promise"),Sn;logger.debug("[sync] syncAndReloadState creating promise"),Sn=wS();try{let e=await Sn;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:v().syncStatus?.status,statusMessageAfterResolve:v().syncStatus?.msg}),a(e)&&v().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),A({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}),Sn||l(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:v().syncStatus?.status,statusMessageBeforeClear:v().syncStatus?.msg}),Sn=null}},wS=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:v().mode,syncStatus:v().syncStatus});let e=mh();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:v().mode,message:e.message,syncStatus:v().syncStatus}),e;if(Sn)return Sn;logger.debug("[sync] syncAndReloadState:start");let t=ve("resolveActorId",he());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),l("Unable to resolve event log path");A({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:v().syncStatus});let n=rr(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=ve("syncEpiqWithRemote",await Ca({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),A({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:v().syncStatus}),je(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value,i=td(o);return a(i)?i:(A({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:v().syncStatus}),d("Synced",!0))},td=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=ve("loadMergedEvents",sn(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(t),message:(a(t),t.message),count:a(t)?void 0:t.value.events.length}),a(t))return A({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:v().syncStatus}),l(`Unable to load events. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=mh();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:v().mode,message:n.message,syncStatus:v().syncStatus}),n;let r=$g(),o=v().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:r,selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id,selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual}),!v().selectedNode?.isVirtual&&!v().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:t.value.events.length});let i=ve("bootStateFromEventLog",En(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(i),message:(a(i),i.message)}),a(i))return A({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:v().syncStatus}),l(`Unable to boot synced state. ${i.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),A({filters:o}),logger.debug("[sync] restoreNavigationAnchor:start");let s=ve("restoreNavigationAnchor",Ug(r));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(s),message:a(s)?s.message:"Navigation restored",selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id}),a(s)?(A({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:v().syncStatus}),s):d("Reloaded state from event log",null)},mh=()=>v().mode===x.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:v().mode,syncStatus:v().syncStatus}),A({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),l("Will not re-materialize if not in default mode, to not lose edit data"))});var ph,nd,rd,Js,od,AS,fh,TS,gh,hh=g(()=>{"use strict";Sr();N();Ue();D();Ta();ph=0,rd=!1,Js=!1,od=()=>{if(rd)return!0;let e=ke();return a(e)?!1:e.value.syncStatus.status==="syncing"},AS=()=>{let e=Li(de().autoSyncIntervalMs),t=Date.now()-ph;return Math.max(0,e-t)},fh=()=>{nd||(nd=setTimeout(async()=>{if(nd=void 0,!!Ut()){if(od()){Js=!0;return}Js=!1,await TS()}},AS()))},TS=async()=>{if(v().readOnly||v().timeMode==="peek"||v().timeMode==="replay")return l("Cannot auto-sync while peeking");if(!Ut())return l("Cannot auto-sync before state is initialized");if(od())return Js=!0,l("Sync already in progress");rd=!0,ph=Date.now(),A({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Aa()}finally{rd=!1,Js&&fh()}},gh=()=>{Ut()&&(Js=!0,!od()&&fh())}});var vh,G,sd=g(()=>{"use strict";D();Ar();vh=e=>{let{context:t}=v().contextNode;if(!t)return G.None;switch(e){case I.EXIT:return G.Exit;case I.EXPORT:return G.Export;case I.INIT:return G.Init;case I.OPEN:return G.OpenProject;case I.DELETE:return G.Delete;case I.EDIT:return G.Edit;case I.COMMENT:return G.Comment;case I.HELP:return G.ViewHelp;case I.RE_OPEN_ISSUE:return G.ReopenIssue;case I.CLOSE_ISSUE:return G.CloseIssue;case I.TAG:return G.TagTicket;case I.UNTAG:return G.UntagTicket;case I.ASSIGN:return G.AssignUserToTicket;case I.UNASSIGN:return G.UnassignUserFromTicket;case I.NEW:return G.NewItem;case I.FILTER:return G.Filter;case I.MOVE:return G.Move;case I.PEEK:return G.Peek;case I.REPLAY:return G.Replay;case I.CONFIG:return G.Config;case I.YANK:return G.Yank;case I.SYNC:return G.Sync;default:return G.None}},G={Exit:"exit",Init:"init",OpenProject:"open-project",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export"}});import{Text as yh}from"ink";import bh,{useEffect as xh,useState as kS}from"react";var Ih,Ht,wo=g(()=>{"use strict";D();Je();Ih={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "],identity:["\u276F "]},Ht=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Ye(),r=Ih[n]??Ih.default,[o,s]=kS(0);if(xh(()=>{s(0)},[r]),xh(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return bh.createElement(yh,null,t);let i=r[o]??r[0]??t;return bh.createElement(yh,{color:T.accent,dimColor:o===1},i)}});import{Box as id,Text as MS}from"ink";import ka from"react";var LS,Wt,Hr=g(()=>{"use strict";Je();LS=(e,t,n,r)=>{let o=u=>Math.max(1,e[u]??1),s=n,i=n+1,c=o(n);for(;i<t&&c+o(i)<=r;)c+=o(i),i++;for(;s>0&&c+o(s-1)<=r;)s--,c+=o(s);return{start:s,end:i}},Wt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),c=Math.max(1,Math.ceil(r)),u=Math.max(0,Math.min(n,e.length-1)),p=Math.max(1,Math.floor(i/c)),m=Math.max(0,e.length-p),{start:f,end:h}=o?LS(o,e.length,u,i):s?{start:Math.min(m,Math.max(0,u-p+1)),end:Math.min(m,Math.max(0,u-p+1))+p}:{start:Math.min(m,Math.floor(u/p)*p),end:Math.min(m,Math.floor(u/p)*p)+p},b=Math.max(1,h-f),E=e.slice(f,h),S=e.length>b,w=i,R=S?Math.max(1,Math.floor(b/e.length*w)):w,k=Math.max(0,w-R),M=Math.max(1,e.length-b),F=S?Math.floor(f/M*k):0;return ka.createElement(id,{flexDirection:"row",height:i,width:"100%"},ka.createElement(id,{flexDirection:"column",flexGrow:1,height:i},E),ka.createElement(id,{flexDirection:"column",width:1,height:w},Array.from({length:w}).map((j,z)=>ka.createElement(MS,{key:z,color:S&&z>=F&&z<F+R?T.accent:T.secondary},S?"\u2502":" "))))}});var Eh,ad,PS,Ma,ld=g(()=>{"use strict";D();PS=()=>{let{eventLog:e=[]}=v();if(ad&&Eh===e)return ad;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Eh=e,ad=t,t},Ma=e=>PS().has(e)});import{Text as DS}from"ink";import OS from"react";var Ao,La=g(()=>{"use strict";un();pe();ld();vt();Ao=({id:e,isSelected:t,maxWidth:n})=>{let r=C.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:Er(o,n);return OS.createElement(DS,{underline:t,color:tt(o)},"@"+s,Ma(e)?"":"\u2197")}});import{Text as _S}from"ink";import FS from"react";var Pa,cd=g(()=>{"use strict";pe();Je();un();vt();Pa=({id:e,isSelected:t,maxWidth:n})=>{let r=C.getTag(e);if(!r)return;let o=n===void 0?r.name:Er(r.name,n);return FS.createElement(_S,{underline:t,backgroundColor:tt(r.name),color:T.secondary}," "+o+" ")}});import{useEffect as BS,useState as $S}from"react";var jS,Rh,Da,Qs,US,HS,To,Oa=g(()=>{"use strict";un();jS=80,Rh=1400,Da=new Set,Qs=null,US=e=>(Da.add(e),Qs||(Qs=setInterval(()=>{for(let t of Da)t()},jS)),()=>{Da.delete(e),Da.size===0&&Qs&&(clearInterval(Qs),Qs=null)}),HS=()=>{let e=Date.now()%Rh/Rh;return e<.5?e*2:(1-e)*2},To=e=>{let[,t]=$S(0);return BS(()=>{if(e)return US(()=>t(n=>n+1))},[e]),Tm(HS())}});import{Box as ko,Text as Mo}from"ink";import Et from"react";var WS,Sh,qS,GS,Nh,Ch=g(()=>{"use strict";pe();Je();vt();ld();ft();uo();La();cd();Oa();WS=(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),Er(e.slice(o).trim(),n)]},Sh=3,qS=2,GS=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let i=e.length-o-1,c=i>0?String(i).length+1:0;if(r+s.width+c>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},Nh=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=To(r),s=e-4,i=s-7-1,[c,u]=WS(Se(t.title),i,s),p=u?null:Er(Se(t.props.description),s)||null,m=hn(t),f=vn(t).map(R=>({...R,name:R.name})),h=Math.max(1,s-Sh),b=C.getCommentsByIssue(t.id),E=b.length?String(b.length).length+2+1:0,{shown:S,hidden:w}=GS([...m.map(R=>({id:R.id,isTag:!0,width:Math.min(R.name.length,h)+Sh})),...f.map(R=>({id:R.id,isTag:!1,width:Math.min(R.name.length,h)+qS+(Ma(R.id)?0:1)}))],s-E);return Et.createElement(ko,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?T.accent:T.secondary,justifyContent:"space-between"},Et.createElement(ko,{paddingLeft:1,paddingRight:1,flexDirection:"column"},Et.createElement(ko,{justifyContent:"space-between"},Et.createElement(Mo,{color:T.primary},c),Et.createElement(Mo,{color:T.secondary2,dimColor:!0},V(t.id))),u&&Et.createElement(Mo,{color:T.primary},u),p&&Et.createElement(Mo,{color:T.secondary2,dimColor:!0},p)),Et.createElement(ko,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},Et.createElement(ko,{flexDirection:"row"},S.map(R=>Et.createElement(ko,{paddingRight:1,key:R.id},R.isTag?Et.createElement(Pa,{id:R.id,maxWidth:h}):Et.createElement(Ao,{id:R.id,maxWidth:h}))),w>0&&Et.createElement(Mo,{color:T.secondary2,dimColor:!0},"+",w)),b.length>0&&Et.createElement(Mo,{color:T.accent},"[",b.length,"]")))}});import{Box as Wr,Text as Zs}from"ink";import Pt from"react";var zS,wh,Ah=g(()=>{"use strict";Oe();pe();Je();un();wo();Oa();zS=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,wh=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let c=To(s),u=(r.props.tags??[]).map(j=>C.getTag(j)).filter(j=>!!j),p=(r.props.assignees??[]).map(j=>C.getContributor(j)).map(j=>j&&{...j,name:j.name}).filter(j=>!!j),m=1,f=u.length*(1+m),h=p.length*(2+m),b=u.map(j=>Pt.createElement(Wr,{key:j.id,paddingRight:m},Pt.createElement(Zs,{color:tt(j.name)},"\u25A0"))),E=p.map(j=>Pt.createElement(Wr,{key:j.id,paddingRight:m},Pt.createElement(Zs,{color:Pl(j.name)},"@"+j.name.at(0)))),S=s?c:o?T.accent:i===x.MOVE?T.secondary:T.primary,w=C.getCommentsByIssue(r.id),R=w.length?String(w.length).length+2+m:0,k=w.length?Pt.createElement(Wr,{paddingRight:m},Pt.createElement(Zs,{color:T.accent},"[",w.length,"]")):null,M=f+h+R,F=Math.max(1,n-t-M-(M>0?1:0));return Pt.createElement(Wr,{justifyContent:"space-between"},Pt.createElement(Wr,null,Pt.createElement(Wr,{width:t},o?Pt.createElement(Ht,{isSelected:!0}):Pt.createElement(Zs,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),Pt.createElement(Zs,{wrap:"truncate",color:S},zS(r.title,F))),Pt.createElement(Wr,null,b,E,k))}});import VS from"chalk";import{Box as dd,Text as KS}from"ink";import Nn from"react";var YS,Th,kh=g(()=>{"use strict";me();D();Je();wo();Hr();Ch();Ah();Oa();YS=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:p}=Ye(),m=u[e.id]??[],f=p?new Set(p.flashNodeIds):null,h=f?.has(e.id)??!1,b=To(h),E=`${e.title} ${VS.hex(T.secondary2).dim("("+m.length+")")}`,S=3,w=o?1:5,R=s&&i===-1,k=n-3-(o?1:0)-(R?2:0),M=Math.max(2,String(m.length).length+1),F=r-S-1,j=Nn.createElement(dd,{borderStyle:"round",borderColor:T.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},Nn.createElement(Ht,{isSelected:t}),Nn.createElement(KS,{bold:!0,color:h?b:t?T.accent:T.primary},E," ",e.readonly?"\u{1F512}":"")),z=(J,se)=>{let ze=s&&i===se;if(!U(J))return null;let q=f?.has(J.id)??!1;return o?Nn.createElement(wh,{key:J.id,index:se,labelWidth:M,width:k,ticket:J,isSelected:ze,isFlashing:q,mode:c}):Nn.createElement(Nh,{key:J.id,width:k,ticket:J,isSelected:ze,isFlashing:q})};return Nn.createElement(dd,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?T.accent:T.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},j,Nn.createElement(dd,null,m.length>0&&Nn.createElement(Wt,{selectedIndex:i,height:F,itemHeight:w},m.map(z)),R&&Nn.createElement(Ht,{isSelected:!0})))},Th=Nn.memo(YS)});var Mh,Lh,Ph,_a=g(()=>{"use strict";sr();Mh=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},Lh=(e,t,n)=>$e.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0}),Ph=e=>e.action==="add.issue.comment"});var ar,ei=g(()=>{"use strict";ar=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 Po,Text as Un}from"ink";import it,{useEffect as XS,useMemo as JS,useRef as QS}from"react";import{decodeTime as Dh}from"ulid";function _h({ticket:e,width:t,height:n}){let r=JS(()=>eN(e),[e]),o=QS([]);XS(()=>(Oh(o.current),o.current=nN(e,r),()=>{Oh(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Ye(),c=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?it.createElement(Po,{flexDirection:"column",width:t,height:n,padding:1},it.createElement(Un,{color:T.primary},"No attachments yet."),it.createElement(Po,{paddingTop:1},it.createElement(Un,{color:T.primary},"Attach images from the browser GUI"),it.createElement(Un,{color:T.accent}," epiq gui "),it.createElement(Un,{color:T.primary},"by dropping or pasting them."))):it.createElement(Po,{flexDirection:"column",width:t,height:n},it.createElement(Po,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:T.secondary,borderStyle:"single",paddingBottom:1},it.createElement(Un,{color:T.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),it.createElement(Wt,{height:c,itemHeight:2,selectedIndex:s},r.map((p,m)=>{let f=m===s,h=p.name.length>u?p.name.slice(0,u-1)+"\u2026":p.name;return it.createElement(Po,{key:p.id,flexDirection:"row",paddingX:1,paddingBottom:1},it.createElement(Un,{color:T.accent},f?"\u276F ":" "),it.createElement(Po,{paddingLeft:1},it.createElement(Un,{color:T.secondary2},`#${m+1} `),it.createElement(Un,{color:f?T.accent:T.primary},h),it.createElement(Un,{color:T.secondary2}," "+rN(p.bytes)+" "+ar(at(p.id)))))})))}var ZS,eN,Oh,tN,nN,rN,Fh=g(()=>{"use strict";It();lt();ei();me();N();pe();sr();D();Je();Jn();Hr();ZS=e=>Te(e,"attachments"),eN=e=>C.getAttachmentsByIssue(e.id).sort((t,n)=>Dh(t.id)-Dh(n.id)),Oh=e=>{for(let t of e)C.deleteNode(t.id)},tN=(e,t,n)=>$e.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),nN=(e,t)=>{let n=C.getNode(ZS(e.id));if(!n||!nt(n))return[];let r=t.map((o,s)=>tN(o,s,n.id)).map(o=>C.createNode(o)).filter(Dt).map(({value:o})=>o).filter(nt);return t.length>0&&v().selectedIndex<0&&H.navigate({contextNode:n,selectedIndex:0}),r},rN=e=>`${Math.max(1,Math.round(e/1024))} KB`});var $h,ud,oN,Bh,ti,jh,Uh,sN,Hh,Wh,md,iN,qh,Fa=g(()=>{"use strict";$h=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,ud=e=>e.replace($h,""),oN=e=>`<!-- epiq-diff-comment:${JSON.stringify(e).replaceAll(">","\\u003e")} -->`,Bh=e=>e==="additions"||e==="deletions",ti=e=>{let t=$h.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"||!Bh(r.side)||!Bh(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r},jh=/```\n([\s\S]*?)\n?```\s*$/,Uh=e=>jh.exec(e)?.[1]??null,sN=/`[^`\n]+`[^\n]*\n?$/,Hh=e=>ud(e).replace(jh,"").replace(sN,"").trim(),Wh=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})`},md=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${Wh(e)}`,iN=e=>{let t=e.split(`
|
|
53
|
+
`,"utf8"),r.push(`${o} (${p.length})`)}catch{continue}}return r},fR=(e,t)=>{let n=new Set(Co(t));return Co(e).filter(r=>!n.has(r))},gR=(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(`
|
|
54
|
+
`),rh=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let r=await Me({args:["show",`HEAD:${t}`],cwd:e});if(r.exitCode!==0)return d("No committed log to compare against",void 0);let o=fR(r.stdout,n);return o.length>0?a(gR(t,o,Co(r.stdout).length)):d("Event log only grew",void 0)}});import jn from"node:fs";import Un from"node:path";var hR,sh,oh,vR,Qc,Ys,yR,bR,lr,xR,IR,ER,SR,Ca,ih,ah,lh,Xs,ch,Js=g(()=>{"use strict";Fr();N();Xc();Bt();Fi();gn();Jc();nt();ze();hR="[epiq:init-repo]",sh=async e=>{let t=await Me({args:["rev-parse","--verify","--quiet","HEAD"],cwd:e});if(t.exitCode===0)return d("Initial commit already exists",!1);if(!(t.exitCode===1&&t.stdout.trim()===""&&t.stderr.trim()===""))return a(["Could not determine whether the repository has any commits, so nothing was written.",`git rev-parse exited ${t.exitCode}`,t.stderr.trim()].filter(Boolean).join(`
|
|
55
|
+
`));ie.info("Creating initial commit");let r=await W({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(l(r))return a(r.message);let o=await W({args:["commit-tree",r.value.stdout.trim(),"-m",hR],cwd:e});if(l(o))return a(o.message);let s=await W({args:["update-ref","HEAD",o.value.stdout.trim()],cwd:e});return l(s)?a(s.message):d("Created initial commit",!0)},oh=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",vR=async e=>{let t=await ji(e);if(l(t))return a(t.message);let n=await rp(e);return l(n)?a(n.message):d("Built sync commit message",`[sync|branch:${oh(t.value)}:sha:${oh(n.value)}]`)},Qc=async({repoRoot:e,stateBranchName:t})=>{ie.info(`Creating ${t}`);let n=await W({args:["commit-tree",fp,"-m","[epiq:init-state-branch]"],cwd:e});if(l(n))return a(`Failed to create state branch commit
|
|
56
|
+
${n.message}`);let r=n.value.stdout.trim(),o=await W({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return l(o)?a(`Failed to create ${t}
|
|
57
|
+
${o.message}`):d("Created state branch",!0)},Ys=async({repoRoot:e,stateBranchName:t})=>{let n=await $i({repoRoot:e,branch:t});if(l(n))return a(`Ensure local state branch failed
|
|
58
|
+
`+n.message);if(n.value)return d("Local state branch already exists",!1);let r=await Ln({repoRoot:e});if(l(r))return a(`Ensure local state branch failed
|
|
59
|
+
`+r.message);let o=r.value,s=o?await gs({repoRoot:e,branch:t}):d("No remote, no remote state branch",!1);if(l(s))return a(`Ensure local state branch failed
|
|
60
|
+
`+s.message);let i=s.value;if(o&&i){let c=await Re.fetch({cwd:e,remote:Tt,branch:t});if(l(c))return a(`Failed to fetch ${t} from remote
|
|
61
|
+
${c.message}`)}if(i){let c=await W({args:["branch","--track",t,`${Tt}/${t}`],cwd:e});return l(c)?a(`Failed to create local ${t} from remote
|
|
62
|
+
${c.message}`):d("Created local state branch from remote",!0)}return Qc({repoRoot:e,stateBranchName:t})},yR=async({repoRoot:e,branch:t})=>{let n=await W({args:["worktree","list","--porcelain"],cwd:e});if(l(n))return a(n.message);let r=n.value.stdout.split(`
|
|
63
|
+
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return d("Found worktree for branch",o)}return d("No worktree found for branch",null)},bR=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=ys(Un.dirname(t));if(l(r))return a(`Failed to create state branch worktree
|
|
64
|
+
`+r.message);if(jn.existsSync(t)&&!jn.existsSync(Un.join(t,".git"))){let s=Zg(t);if(l(s))return a(s.message);if(s.value.length>0)return a([`Refusing to delete ${t}.`,"","It is not a usable worktree \u2014 it has no .git \u2014 but it still holds",`${s.value.length} event log(s) with content:`,...s.value.map(i=>` ${i}`),"","Deleting it would destroy them, and with no .git here there is no","committed copy to recover from. Move the directory aside and","salvage the logs before letting epiq recreate the worktree."].join(`
|
|
65
|
+
`));ie.info("Removing broken state branch worktree path"),yp(t)}ie.info("Creating state branch worktree");let o=await Re.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return l(o)?a(`Failed to create state branch worktree
|
|
66
|
+
${o.message}`):d("Created state branch worktree",!0)},lr=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await IR({repoRoot:e,stateBranchRoot:t,stateBranchName:n});if(l(r))return r;let o=Qg({repoRoot:e,stateBranchRoot:t,stateBranch:n});return l(o)?a(o.message):(o.value==="stamped"&&ie.info("Stamped the state branch with this project\u2019s identity"),r)},xR=(e,t)=>{let n=so(Ar());return Un.dirname(e)===n&&Un.dirname(t)===n},IR=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await yR({repoRoot:e,branch:n});if(l(r))return a(r.message);let o=so(t),s=r.value?so(r.value):null;if(s&&s===o&&jn.existsSync(s))return d("State branch already checked out in expected worktree",!1);if(s&&s!==o&&xR(s,o))return a([`The state branch ${n} is checked out under project ${Un.basename(s)}, but this checkout names project ${Un.basename(o)}.`,"","Two ids for one branch means a checkout minted a second identity for","a board that already existed. Nothing on the board is lost by it, but",`every checkout has to agree on one: compare ${ot} here`,`with \`git show ${n}:${ot}\`, and keep the branch's.`].join(`
|
|
67
|
+
`));if(s&&s!==o){let u=await cp(s);if(l(u))return a(u.message);if(u.value||zf(s))return a([`Refusing to move the state branch worktree away from ${s}.`,"","It holds changes that are not committed yet, which for this","branch means events no sync has published. Removing it would","destroy them outright \u2014 there is no stash or reflog to recover","a deleted worktree from.","",`This worktree is expected at ${o}, so something else is`,"using a different EPIQ_GLOBAL_DIR against the same repository.","Sync from that location first, or point both at the same one."].join(`
|
|
68
|
+
`));ie.info("Moving state branch worktree to expected location");let p=await Re.worktreeRemove({cwd:e,worktreeRoot:s});if(l(p))return a(`Failed to remove existing state branch worktree
|
|
69
|
+
${p.message}`)}if(s&&!jn.existsSync(s)){ie.info("Pruning stale state branch worktree");let u=await Re.worktreePrune({cwd:e});if(l(u))return a(`Failed to prune stale worktrees
|
|
70
|
+
${u.message}`)}let i=await np({repoRoot:e,worktreeRoot:t});if(l(i))return a(i.message);let c=jn.existsSync(t);if(i.value&&c)return d("State branch worktree already exists",!1);if(i.value&&!c){ie.info("Pruning missing registered state branch worktree");let u=await Re.worktreePrune({cwd:e});if(l(u))return a(`Failed to prune stale worktrees
|
|
71
|
+
${u.message}`)}return bR({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},ER=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await ji(e);if(l(n))return a(n.message);if(n.value===t)return d("State branch already checked out",!1);(await Me({cwd:e,args:["rebase","--abort"]})).exitCode===0&&ie.info("Aborted stale state branch rebase");let o=await Re.checkout({cwd:e,branch:t});return l(o)?a(`Failed to checkout ${t}
|
|
72
|
+
${o.message}`):d("Checked out state branch",!0)},SR=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Jl(t);if(l(n))return a(n.message);if(n.value)return d("State branch upstream already configured",!1);let r=await Ln({repoRoot:t});if(l(r))return a(r.message);if(!r.value)return d("No remote available for state branch upstream",!1);let o=tt(e);if(l(o))return o;let s=o.value,i=await gs({repoRoot:t,branch:s});if(l(i))return a(i.message);if(!i.value)return d("Remote state branch missing; upstream will be configured on first push",!1);ie.info(`Configuring ${s} upstream`);let c=await Re.fetch({cwd:t,remote:Tt,branch:s});if(l(c))return a(`Failed to fetch ${s}
|
|
73
|
+
${c.message}`);let u=await Re.setUpstream({cwd:t,branch:s,upstream:`${Tt}/${s}`});return l(u)?a(`Failed to set state branch upstream
|
|
74
|
+
${u.message}`):d("Configured state branch upstream",!0)},Ca=async({stateBranchRoot:e,eventFileName:t})=>{let n=gp(t),r=Un.join(e,n);if(!jn.existsSync(r))return d("No event file to stage",null);let o=await rh({stateBranchRoot:e,relativePath:n,workingContent:jn.readFileSync(r,"utf8")});if(l(o))return a(o.message);let s=await Re.stage({cwd:e,pathspec:[n]});return l(s)?a(`Failed to stage state branch event file
|
|
75
|
+
${s.message}`):d("Staged state branch event file",n)},ih=async({stateBranchRoot:e})=>{let t=hp(),n=Un.join(e,t);if(!jn.existsSync(n))return d("No media directory to stage",null);let r=await Re.stage({cwd:e,pathspec:[t],ignoreRemoval:!0});return l(r)?a(`Failed to stage state branch media files
|
|
76
|
+
${r.message}`):d("Staged state branch media files",t)},ah=async({stateBranchRoot:e})=>{let t=[Zl(),ec(),ot].filter(r=>jn.existsSync(Un.join(e,r)));if(t.length===0)return d("No event log config to stage",[]);let n=await Re.stage({cwd:e,pathspec:t});return l(n)?a(`Failed to stage event log config
|
|
77
|
+
${n.message}`):d("Staged event log config",t)},lh=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let r=await vR(e);return l(r)?a(`Create state branch sync commit failed
|
|
78
|
+
`+r.message):io({cwd:t,message:r.value,pathspec:n})},Xs=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Jl(t);if(l(n))return a(n.message);let r=tt(e);if(l(r))return r;let o=r.value,s=n.value?await Re.push({cwd:t}):await Re.push({cwd:t,remote:Tt,branch:o,setUpstream:!0});if(l(s))return a(`Failed during state branch push
|
|
79
|
+
${s.message}`);let i=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return d(i?"Pushed state branch":"Remote already up to date",i)},ch=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=tt(e);if(l(o))return o;let s=o.value,i=[bs(),await Ys({repoRoot:e,stateBranchName:s}),await lr({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await ER({stateBranchRoot:t,stateBranchName:s}),await xp(t),n?await SR({stateBranchRoot:t,repoRoot:e}):d("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(l(c))return a(c.message);r=r||!!c.value}return d(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)}});import Ao from"node:fs";import ed from"node:os";import RR from"node:path";var td,dh,NR,CR,AR,mh,Zc,uh,wR,Qs,nd=g(()=>{"use strict";N();ze();Bt();td="epiq-sync.lock",dh=600*1e3,NR=e=>{try{let t=JSON.parse(e);return typeof t.pid!="number"||typeof t.hostname!="string"||typeof t.startedAt!="number"||typeof t.operation!="string"?null:t}catch{return null}},CR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},AR=e=>e?e.hostname!==ed.hostname()||CR(e.pid)?Date.now()-e.startedAt>dh?"stale":null:"dead":"stale",mh=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,Zc=e=>{try{return NR(Ao.readFileSync(e,"utf8"))}catch{return null}},uh=(e,t)=>{let n={pid:process.pid,hostname:ed.hostname(),startedAt:Date.now(),operation:t},r=`${e}.${process.pid}.pending.lock`;try{return Ao.writeFileSync(r,JSON.stringify(n)),Ao.linkSync(r,e),!0}catch{return!1}finally{try{Ao.rmSync(r,{force:!0})}catch{}}},wR=async({worktreeRoot:e,operation:t})=>{let n=await Bi(e);if(l(n))return a(n.message);let r=RR.join(n.value,td),o=()=>{try{let u=Zc(r);u&&u.pid===process.pid&&Ao.rmSync(r)}catch{}};if(uh(r,t))return d("Acquired sync lock",{acquired:!0,claim:"clean",release:o});let s=Zc(r),i=AR(s);if(i===null)return d("Sync lock is held",{acquired:!1,heldBy:s});ie.info(`Breaking an abandoned sync lock: ${s?mh(s):"unreadable lock file"}`);try{Ao.rmSync(r,{force:!0})}catch{}if(uh(r,t))return d("Acquired sync lock after breaking a stale one",{acquired:!0,claim:i,release:o});let c=Zc(r);return d("Sync lock taken by another process",{acquired:!1,heldBy:c??{pid:-1,hostname:ed.hostname(),startedAt:Date.now(),operation:"unknown"}})},Qs=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await wR({worktreeRoot:e,operation:t});if(l(r))return a(r.message);if(!r.value.acquired)return ie.info(`Skipping ${t}: the state worktree is held by ${mh(r.value.heldBy)}`),d("State worktree is held by another process",null);let{claim:o,release:s}=r.value;try{return d("Ran under the sync lock",await n(o))}finally{s()}}});import fh from"node:fs";var TR,MR,rd,ph,Aa,wa,Ta=g(()=>{"use strict";N();Vs();ga();Q();Ra();gn();nt();ze();Js();Jc();Fr();nd();TR=async({claim:e,cwd:t,ensureUpstream:n})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:t,ensureUpstream:n});let r=ge("getRepoRootDir",await Lt(t));if(l(r))return a(r.message);let o=r.value;logger.debug("[sync] repo root",o);let s=ge("getStateBranchRoot",be({repoRoot:o}));if(l(s))return a(s.message);let i=s.value;if(logger.debug("[sync] state branch root",i),e!=="stale"&&fh.existsSync(i)){let m=await ip(i,{preserve:[td]});if(l(m))return a(m.message);m.value.length>0&&logger.info("[sync] cleared git lock files left by a dead process",{removed:m.value,stateBranchRoot:i});let f=tt(o);if(l(f))return a(f.message);let h=await ap(i,f.value);if(l(h))return a(h.message);h.value&&logger.info("[sync] cleared a ref lock left by a dead process",{branch:f.value,stateBranchRoot:i});let b=ge("abortRebaseIfPresent(stateBranchRoot)",await Ql(i));if(l(b))return a(b.message)}logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:i,ensureUpstream:n});let c=ge("bootstrapStateBranchStorage",await ch({repoRoot:o,stateBranchRoot:i,ensureUpstream:n}));if(l(c))return a(c.message);logger.debug("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:i}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:i});let u=ge("getInProgressGitOperation(stateBranchRoot)",await Xl(i));if(l(u))return a(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value!==null)return logger.info("[sync] state branch git operation in progress",{claim:e}),a(`Cannot sync while there is a ${u.value} in the state branch at ${i}`);logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:i});let p=ge("ensureStateBranchLayout",bp(o,i));return l(p)?a(p.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:i,bootstrapped:c.value}),d("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:i,bootstrapped:c.value}))},MR=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=[];for(let p of ig(xt(t),n)){let m=ge("stageStateBranchOwnEventFile",await Ca({stateBranchRoot:t,eventFileName:p}));if(l(m))return a(m.message);r.push(m.value)}let o=ge("stageStateBranchMediaFiles",await ih({stateBranchRoot:t}));if(l(o))return a(o.message);let s=ge("stageStateBranchEventConfig",await ah({stateBranchRoot:t}));if(l(s))return a(s.message);let i=[...r,o.value,...s.value].filter(p=>p!==null);if(i.length===0)return d("Nothing to stage",{createdCommit:!1});let c=ge("hasStagedChanges(after stage)",await dp(t,i));if(l(c))return a(c.message);if(logger.debug("[sync] state branch change check after stage result",{changed:c.value}),!c.value)return logger.info("[sync] no own event file changes to commit"),d("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let u=ge("createStateBranchSyncCommit",await lh({repoRoot:e,stateBranchRoot:t,pathspec:i}));return l(u)?a(u.message):(logger.debug("[sync] created sync commit",u.value),d("Committed own event file",{createdCommit:!0,commitSha:u.value}))},rd=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return Sa(n),d(n,{...e,pulled:!1,pushed:!1,offline:!0})},ph=async({cwd:e=process.cwd(),ownEventFileName:t},n)=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),a("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),a("Own event file must end with .jsonl");Ro();let r=ge("ensureSyncReady",await TR({claim:n,cwd:e,ensureUpstream:!0}));if(l(r))return Be(r.message);let{repoRoot:o,stateBranchRoot:s,bootstrapped:i}=r.value,c=ge("isDetachedHead(stateBranchRoot)",await up(s));if(l(c))return Be(c.message);if(logger.debug("[sync] detached state branch check result",{detached:c.value}),c.value)return Be("Cannot run :sync while the state branch is in detached HEAD state");let u=!1,p,m=!1,f=!1,h=ge("getStateBranch",tt(o));if(l(h))return Be(h.message);let b=h.value;logger.debug("[sync] resolved state branch",{stateBranch:b,stateBranchRoot:s});let I=ge("flushPendingLogs",ca(s,t));l(I)&&logger.error(`[sync] ${I.message}`);let C=ge("commitOwnEventFileToStateBranch",await MR({repoRoot:o,stateBranchRoot:s,ownEventFileName:t}));if(l(C))return Be(C.message);u=C.value.createdCommit,p=C.value.commitSha;let T=ge("hasRemote",await Ln({repoRoot:s}));if(l(T))return Be(T.message);if(!T.value)return rd({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i},"no remote");let S=ge("pullBranchRebaseIfPresent",await vs({cwd:s,branch:b}));if(l(S))return hs(S.message)?rd({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i}):Be(S.message);m=S.value;let M=ge("isAheadOfUpstream",await lp(s));if(l(M))return Be(M.message);if(u||i||M.value){logger.info("[sync] pushing state branch",{createdCommit:u,bootstrapped:i,stateBranchRoot:s});let L=ge("pushStateBranch",await Xs({stateBranchRoot:s,repoRoot:o}));if(l(L)&&op(L.message)){let F=ge("pullBranchRebaseIfPresent(retry)",await vs({cwd:s,branch:b}));if(l(F))return Be(F.message);m=m||F.value,L=ge("pushStateBranch(retry)",await Xs({stateBranchRoot:s,repoRoot:o}))}if(l(L))return hs(L.message)?rd({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i}):Be(L.message);f=L.value}if(u){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:s});let L=ge("git rev-parse HEAD",await W({args:["rev-parse","HEAD"],cwd:s}));if(l(L))return Be(L.message);p=L.value.stdout.trim(),logger.debug("[sync] final sync commit sha",p)}return Hr(f?"Synced and pushed":m||u?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),d("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,pulled:m,pushed:f,bootstrapped:i,offline:!1})},Aa=async(e,t)=>{let n=th(e);try{return await t()}finally{let r=nh(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},wa=async e=>{let t=e.cwd??process.cwd(),n=await Lt(t);if(l(n))return Be(n.message);let r=be({repoRoot:n.value});if(l(r))return Be(r.message);let o=r.value;if(!fh.existsSync(o))return ph(e,"clean");let s=await Qs({worktreeRoot:o,operation:"sync",fn:i=>Aa(o,()=>ph(e,i))});return l(s)?Be(s.message):s.value===null?d("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 wo,Ma,kR,LR,od,gh,ka=g(()=>{"use strict";Gg();Ur();$();$();tr();Pe();N();D();Vs();Ra();Ta();wo=null,Ma=async()=>(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!wo,currentStatus:v().syncStatus?.status,currentMessage:v().syncStatus?.msg}),wo?(logger.debug("[sync] syncAndReloadState joining existing promise"),wo):(logger.debug("[sync] syncAndReloadState creating promise"),wo=kR().finally(()=>{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:v().syncStatus?.status,statusMessageBeforeClear:v().syncStatus?.msg}),wo=null}),wo)),kR=async()=>{let e;try{e=await LR(),logger.debug("[sync] syncAndReloadState promise resolved",{success:!l(e),message:e.message,statusAfterResolve:v().syncStatus?.status,statusMessageAfterResolve:v().syncStatus?.msg})}catch(n){let r=n instanceof Error?n.message:String(n);logger.error("[sync] syncAndReloadState promise threw",{message:r,error:n}),e=a(r)}let t=Ee();return l(e)&&!l(t)&&t.value.syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),A({syncStatus:{msg:e.message,status:"failed"}})),e},LR=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:v().mode,syncStatus:v().syncStatus});let e=gh();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:v().mode,message:e.message,syncStatus:v().syncStatus}),e;logger.debug("[sync] syncAndReloadState:start");let t=ge("resolveActorId",fe());if(l(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:l(t)?t.message:"Missing actor id"}),a("Unable to resolve event log path");A({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:v().syncStatus});let n=sr(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=ge("syncEpiqWithRemote",await wa({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!l(r),message:(l(r),r.message)}),l(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),A({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:v().syncStatus}),Be(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value,i=od(o);return l(i)?i:(A({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:v().syncStatus}),d("Synced",!0))},od=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=Wt(e),n=ge("loadMergedEvents",cn(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!l(n),message:(l(n),n.message),count:l(n)?void 0:n.value.events.length}),l(n))return A({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:v().syncStatus}),a(`Unable to load events. ${n.message}`);logger.debug("[sync] loaded merged events after sync",{count:n.value.events.length});let r=gh();if(r)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:v().mode,message:r.message,syncStatus:v().syncStatus}),r;let o=Hg(),s=v().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:o,selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id,selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual}),!v().selectedNode?.isVirtual&&!v().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:n.value.events.length});let c=Ee(),u=!l(c)&&c.value.timeMode==="live",p=ge("bootStateFromEventLog",Rn(n.value.events,n.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!l(p),message:(l(p),p.message)}),l(p))return A({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:v().syncStatus}),a(`Unable to boot synced state. ${p.message}`);u&&Io(e,t)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),A({filters:s}),logger.debug("[sync] restoreNavigationAnchor:start");let i=ge("restoreNavigationAnchor",qg(o));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!l(i),message:l(i)?i.message:"Navigation restored",selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id}),l(i)?(A({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:v().syncStatus}),i):d("Reloaded state from event log",null)},gh=()=>v().mode===x.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:v().mode,syncStatus:v().syncStatus}),A({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"))});var hh,sd,id,Zs,ad,PR,vh,DR,yh,bh=g(()=>{"use strict";Cr();N();$e();D();ka();hh=0,id=!1,Zs=!1,ad=()=>{if(id)return!0;let e=Ee();return l(e)?!1:e.value.syncStatus.status==="syncing"},PR=()=>{let e=Di(ae().autoSyncIntervalMs),t=Date.now()-hh;return Math.max(0,e-t)},vh=()=>{sd||(sd=setTimeout(async()=>{if(sd=void 0,!!qt()){if(ad()){Zs=!0;return}Zs=!1,await DR()}},PR()))},DR=async()=>{if(v().readOnly||v().timeMode==="peek"||v().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!qt())return a("Cannot auto-sync before state is initialized");if(ad())return Zs=!0,a("Sync already in progress");id=!0,hh=Date.now(),A({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Ma()}finally{id=!1,Zs&&vh()}},yh=()=>{qt()&&(Zs=!0,!ad()&&vh())}});var xh,G,ld=g(()=>{"use strict";D();Mr();xh=e=>{let{context:t}=v().contextNode;if(!t)return G.None;switch(e){case E.EXIT:return G.Exit;case E.EXPORT:return G.Export;case E.INIT:return G.Init;case E.OPEN:return G.OpenProject;case E.DELETE:return G.Delete;case E.EDIT:return G.Edit;case E.COMMENT:return G.Comment;case E.HELP:return G.ViewHelp;case E.RE_OPEN_ISSUE:return G.ReopenIssue;case E.CLOSE_ISSUE:return G.CloseIssue;case E.TAG:return G.TagTicket;case E.UNTAG:return G.UntagTicket;case E.ASSIGN:return G.AssignUserToTicket;case E.UNASSIGN:return G.UnassignUserFromTicket;case E.NEW:return G.NewItem;case E.FILTER:return G.Filter;case E.MOVE:return G.Move;case E.PEEK:return G.Peek;case E.REPLAY:return G.Replay;case E.CONFIG:return G.Config;case E.YANK:return G.Yank;case E.SYNC:return G.Sync;default:return G.None}},G={Exit:"exit",Init:"init",OpenProject:"open-project",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export"}});import{Text as Ih}from"ink";import Eh,{useEffect as Sh,useState as OR}from"react";var Rh,Gt,To=g(()=>{"use strict";D();Ye();Rh={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "],identity:["\u276F "]},Gt=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Ve(),r=Rh[n]??Rh.default,[o,s]=OR(0);if(Sh(()=>{s(0)},[r]),Sh(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return Eh.createElement(Ih,null,t);let i=r[o]??r[0]??t;return Eh.createElement(Ih,{color:w.accent,dimColor:o===1},i)}});import{Box as cd,Text as _R}from"ink";import La from"react";var FR,zt,Wr=g(()=>{"use strict";Ye();FR=(e,t,n,r)=>{let o=u=>Math.max(1,e[u]??1),s=n,i=n+1,c=o(n);for(;i<t&&c+o(i)<=r;)c+=o(i),i++;for(;s>0&&c+o(s-1)<=r;)s--,c+=o(s);return{start:s,end:i}},zt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),c=Math.max(1,Math.ceil(r)),u=Math.max(0,Math.min(n,e.length-1)),p=Math.max(1,Math.floor(i/c)),m=Math.max(0,e.length-p),{start:f,end:h}=o?FR(o,e.length,u,i):s?{start:Math.min(m,Math.max(0,u-p+1)),end:Math.min(m,Math.max(0,u-p+1))+p}:{start:Math.min(m,Math.floor(u/p)*p),end:Math.min(m,Math.floor(u/p)*p)+p},b=Math.max(1,h-f),I=e.slice(f,h),C=e.length>b,T=i,S=C?Math.max(1,Math.floor(b/e.length*T)):T,M=Math.max(0,T-S),L=Math.max(1,e.length-b),F=C?Math.floor(f/L*M):0;return La.createElement(cd,{flexDirection:"row",height:i,width:"100%"},La.createElement(cd,{flexDirection:"column",flexGrow:1,height:i},I),La.createElement(cd,{flexDirection:"column",width:1,height:T},Array.from({length:T}).map((j,z)=>La.createElement(_R,{key:z,color:C&&z>=F&&z<F+S?w.accent:w.secondary},C?"\u2502":" "))))}});var Nh,dd,BR,Pa,ud=g(()=>{"use strict";D();BR=()=>{let{eventLog:e=[]}=v();if(dd&&Nh===e)return dd;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Nh=e,dd=t,t},Pa=e=>BR().has(e)});import{Text as $R}from"ink";import jR from"react";var Mo,Da=g(()=>{"use strict";fn();de();ud();vt();Mo=({id:e,isSelected:t,maxWidth:n})=>{let r=R.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:Rr(o,n);return jR.createElement($R,{underline:t,color:Ze(o)},"@"+s,Pa(e)?"":"\u2197")}});import{Text as UR}from"ink";import HR from"react";var Oa,md=g(()=>{"use strict";de();Ye();fn();vt();Oa=({id:e,isSelected:t,maxWidth:n})=>{let r=R.getTag(e);if(!r)return;let o=n===void 0?r.name:Rr(r.name,n);return HR.createElement(UR,{underline:t,backgroundColor:Ze(r.name),color:w.secondary}," "+o+" ")}});import{useEffect as WR,useState as qR}from"react";var GR,Ch,_a,ei,zR,VR,ko,Fa=g(()=>{"use strict";fn();GR=80,Ch=1400,_a=new Set,ei=null,zR=e=>(_a.add(e),ei||(ei=setInterval(()=>{for(let t of _a)t()},GR)),()=>{_a.delete(e),_a.size===0&&ei&&(clearInterval(ei),ei=null)}),VR=()=>{let e=Date.now()%Ch/Ch;return e<.5?e*2:(1-e)*2},ko=e=>{let[,t]=qR(0);return WR(()=>{if(e)return zR(()=>t(n=>n+1))},[e]),Lm(VR())}});import{Box as Lo,Text as Po}from"ink";import St from"react";var KR,Ah,YR,XR,wh,Th=g(()=>{"use strict";de();Ye();vt();ud();mt();mo();Da();md();Fa();KR=(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),Rr(e.slice(o).trim(),n)]},Ah=3,YR=2,XR=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let i=e.length-o-1,c=i>0?String(i).length+1:0;if(r+s.width+c>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},wh=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=ko(r),s=e-4,i=s-7-1,[c,u]=KR(Se(t.title),i,s),p=u?null:Rr(Se(t.props.description),s)||null,m=yn(t),f=bn(t).map(S=>({...S,name:S.name})),h=Math.max(1,s-Ah),b=R.getCommentsByIssue(t.id),I=b.length?String(b.length).length+2+1:0,{shown:C,hidden:T}=XR([...m.map(S=>({id:S.id,isTag:!0,width:Math.min(S.name.length,h)+Ah})),...f.map(S=>({id:S.id,isTag:!1,width:Math.min(S.name.length,h)+YR+(Pa(S.id)?0:1)}))],s-I);return St.createElement(Lo,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?w.accent:w.secondary,justifyContent:"space-between"},St.createElement(Lo,{paddingLeft:1,paddingRight:1,flexDirection:"column"},St.createElement(Lo,{justifyContent:"space-between"},St.createElement(Po,{color:w.primary},c),St.createElement(Po,{color:w.secondary2,dimColor:!0},V(t.id))),u&&St.createElement(Po,{color:w.primary},u),p&&St.createElement(Po,{color:w.secondary2,dimColor:!0},p)),St.createElement(Lo,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},St.createElement(Lo,{flexDirection:"row"},C.map(S=>St.createElement(Lo,{paddingRight:1,key:S.id},S.isTag?St.createElement(Oa,{id:S.id,maxWidth:h}):St.createElement(Mo,{id:S.id,maxWidth:h}))),T>0&&St.createElement(Po,{color:w.secondary2,dimColor:!0},"+",T)),b.length>0&&St.createElement(Po,{color:w.accent},"[",b.length,"]")))}});import{Box as qr,Text as ti}from"ink";import Ot from"react";var JR,Mh,kh=g(()=>{"use strict";Pe();de();Ye();fn();To();Fa();JR=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,Mh=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let c=ko(s),u=(r.props.tags??[]).map(j=>R.getTag(j)).filter(j=>!!j),p=(r.props.assignees??[]).map(j=>R.getContributor(j)).map(j=>j&&{...j,name:j.name}).filter(j=>!!j),m=1,f=u.length*(1+m),h=p.length*(2+m),b=u.map(j=>Ot.createElement(qr,{key:j.id,paddingRight:m},Ot.createElement(ti,{color:Ze(j.name)},"\u25A0"))),I=p.map(j=>Ot.createElement(qr,{key:j.id,paddingRight:m},Ot.createElement(ti,{color:_l(j.name)},"@"+j.name.at(0)))),C=s?c:o?w.accent:i===x.MOVE?w.secondary:w.primary,T=R.getCommentsByIssue(r.id),S=T.length?String(T.length).length+2+m:0,M=T.length?Ot.createElement(qr,{paddingRight:m},Ot.createElement(ti,{color:w.accent},"[",T.length,"]")):null,L=f+h+S,F=Math.max(1,n-t-L-(L>0?1:0));return Ot.createElement(qr,{justifyContent:"space-between"},Ot.createElement(qr,null,Ot.createElement(qr,{width:t},o?Ot.createElement(Gt,{isSelected:!0}):Ot.createElement(ti,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),Ot.createElement(ti,{wrap:"truncate",color:C},JR(r.title,F))),Ot.createElement(qr,null,b,I,M))}});import QR from"chalk";import{Box as pd,Text as ZR}from"ink";import Cn from"react";var eN,Lh,Ph=g(()=>{"use strict";ce();D();Ye();To();Wr();Th();kh();Fa();eN=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:p}=Ve(),m=u[e.id]??[],f=p?new Set(p.flashNodeIds):null,h=f?.has(e.id)??!1,b=ko(h),I=`${e.title} ${QR.hex(w.secondary2).dim("("+m.length+")")}`,C=3,T=o?1:5,S=s&&i===-1,M=n-3-(o?1:0)-(S?2:0),L=Math.max(2,String(m.length).length+1),F=r-C-1,j=Cn.createElement(pd,{borderStyle:"round",borderColor:w.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},Cn.createElement(Gt,{isSelected:t}),Cn.createElement(ZR,{bold:!0,color:h?b:t?w.accent:w.primary},I," ",e.readonly?"\u{1F512}":"")),z=(X,ne)=>{let qe=s&&i===ne;if(!U(X))return null;let q=f?.has(X.id)??!1;return o?Cn.createElement(Mh,{key:X.id,index:ne,labelWidth:L,width:M,ticket:X,isSelected:qe,isFlashing:q,mode:c}):Cn.createElement(wh,{key:X.id,width:M,ticket:X,isSelected:qe,isFlashing:q})};return Cn.createElement(pd,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?w.accent:w.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},j,Cn.createElement(pd,null,m.length>0&&Cn.createElement(zt,{selectedIndex:i,height:F,itemHeight:T},m.map(z)),S&&Cn.createElement(Gt,{isSelected:!0})))},Lh=Cn.memo(eN)});var Dh,Oh,_h,Ba=g(()=>{"use strict";ar();Dh=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},Oh=(e,t,n)=>Fe.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0}),_h=e=>e.action==="add.issue.comment"});var cr,ni=g(()=>{"use strict";cr=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"}});import{Box as Oo,Text as Hn}from"ink";import st,{useEffect as tN,useMemo as nN,useRef as rN}from"react";import{decodeTime as Fh}from"ulid";function $h({ticket:e,width:t,height:n}){let r=nN(()=>sN(e),[e]),o=rN([]);tN(()=>(Bh(o.current),o.current=aN(e,r),()=>{Bh(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Ve(),c=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?st.createElement(Oo,{flexDirection:"column",width:t,height:n,padding:1},st.createElement(Hn,{color:w.primary},"No attachments yet."),st.createElement(Oo,{paddingTop:1},st.createElement(Hn,{color:w.primary},"Attach images from the browser GUI"),st.createElement(Hn,{color:w.accent}," epiq gui "),st.createElement(Hn,{color:w.primary},"by dropping or pasting them."))):st.createElement(Oo,{flexDirection:"column",width:t,height:n},st.createElement(Oo,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:w.secondary,borderStyle:"single",paddingBottom:1},st.createElement(Hn,{color:w.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),st.createElement(zt,{height:c,itemHeight:2,selectedIndex:s},r.map((p,m)=>{let f=m===s,h=p.name.length>u?p.name.slice(0,u-1)+"\u2026":p.name;return st.createElement(Oo,{key:p.id,flexDirection:"row",paddingX:1,paddingBottom:1},st.createElement(Hn,{color:w.accent},f?"\u276F ":" "),st.createElement(Oo,{paddingLeft:1},st.createElement(Hn,{color:w.secondary2},`#${m+1} `),st.createElement(Hn,{color:f?w.accent:w.primary},h),st.createElement(Hn,{color:w.secondary2}," "+lN(p.bytes)+" "+cr(it(p.id)))))})))}var oN,sN,Bh,iN,aN,lN,jh=g(()=>{"use strict";Et();at();ni();ce();N();de();ar();D();Ye();Qn();Wr();oN=e=>we(e,"attachments"),sN=e=>R.getAttachmentsByIssue(e.id).sort((t,n)=>Fh(t.id)-Fh(n.id)),Bh=e=>{for(let t of e)R.deleteNode(t.id)},iN=(e,t,n)=>Fe.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),aN=(e,t)=>{let n=R.getNode(oN(e.id));if(!n||!et(n))return[];let r=t.map((o,s)=>iN(o,s,n.id)).map(o=>R.createNode(o)).filter(_t).map(({value:o})=>o).filter(et);return t.length>0&&v().selectedIndex<0&&H.navigate({contextNode:n,selectedIndex:0}),r},lN=e=>`${Math.max(1,Math.round(e/1024))} KB`});var Hh,fd,cN,Uh,ri,Wh,qh,dN,Gh,zh,gd,uN,Vh,$a=g(()=>{"use strict";Hh=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,fd=e=>e.replace(Hh,""),cN=e=>`<!-- epiq-diff-comment:${JSON.stringify(e).replaceAll(">","\\u003e")} -->`,Uh=e=>e==="additions"||e==="deletions",ri=e=>{let t=Hh.exec(e);if(!t?.[1])return null;let n;try{n=JSON.parse(t[1])}catch{return null}let r=n;return typeof r?.filePath!="string"||typeof r.start!="number"||typeof r.end!="number"||typeof r.note!="string"||!Uh(r.side)||!Uh(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r},Wh=/```\n([\s\S]*?)\n?```\s*$/,qh=e=>Wh.exec(e)?.[1]??null,dN=/`[^`\n]+`[^\n]*\n?$/,Gh=e=>fd(e).replace(Wh,"").replace(dN,"").trim(),zh=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})`},gd=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${zh(e)}`,uN=e=>{let t=e.split(`
|
|
80
80
|
`),n=t.filter(r=>r.trim()!=="").reduce((r,o)=>{let s=/^[ \t]*/.exec(o)?.[0].length??0;return r===null?s:Math.min(r,s)},null);return n?t.map(r=>r.slice(n)).join(`
|
|
81
|
-
`):e},
|
|
82
|
-
`)}});var
|
|
83
|
-
`),t);let o=
|
|
84
|
-
`).map(
|
|
85
|
-
`),t),{kind:"blank"}]:[],{kind:"caption",text:
|
|
86
|
-
`),[p,m,f,h,...b]=(c??"").split(
|
|
87
|
-
`;else if(o==="t")n+=" ";else if(o==='"'||o==="\\")n+=o;else if(o&&/[0-7]/.test(o)){let s=t.slice(r,r+3);n+=String.fromCharCode(parseInt(s,8)),r+=2}else o!==void 0&&(n+=o)}try{return decodeURIComponent(escape(n))}catch{return n}},
|
|
88
|
-
`)){if(i.startsWith("diff --git ")){n=s();let m=i.slice(11),f=m.lastIndexOf(" b/");f!==-1&&(n.path=
|
|
89
|
-
`)}}}});import{spawn as
|
|
90
|
-
`).map(o=>o.trim()).filter(Boolean);return r.length===0?l("No changed files found for this commit"):d("Listed changed files",r)},HN=async(e,t,n)=>{let r=await UN(e,t);if(a(r))return l(r.message);let o=r.value;if(o.length>$N)return l(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=si("commit-diffs",t);if(a(s))return l(s.message);let i=s.value,c=await Promise.all(o.map(async(h,b)=>{let[E,S]=await Promise.all([vv(e,`${t}~1`,h),vv(e,t,h)]),w=qa.basename(h),R=qa.join(i,String(b),"before",w),k=qa.join(i,String(b),"after",w);return Td(R)||(Qe.writeToFile(R,E),await kd(R,292)),Td(k)||(Qe.writeToFile(k,S),await kd(k,292)),{beforePath:R,afterPath:k}})),[u,...p]=c;if(!u)return l("No changed files found for this commit");let m=await Cd(n,u.beforePath,u.afterPath,"new");if(a(m)||p.length===0)return m;await new Promise(h=>setTimeout(h,jN));let f=await Promise.all(p.map(({beforePath:h,afterPath:b})=>Cd(n,h,b,"reuse")));for(let h of f)a(h)&&logger.error(`Failed to open an additional diff tab for ${t}: ${h.message}`);return m},Md=async e=>{if(!oi(e.sha))return l("Invalid commit sha");let t=dr(e.repoRoot);if(a(t))return l(t.message);let n=t.value,r=Wa()[0];if(r&&Nd(r)){let o=await HN(n,e.sha,r);if(!a(o))return o;logger.error(`Side-by-side diff failed for ${e.sha}, falling back to unified diff: ${o.message}`)}return BN(n,e.sha)}});var ii=g(()=>{"use strict";Do();vd();sv();Ha();yv()});var Ga,Bo,Ld=g(()=>{"use strict";N();sr();D();bo();pe();Ga=(e,t,n)=>{let r=[],o=ga(()=>{for(let s=0;s<t;s++){let i=Lt(BigInt(s+1));if(!Dt(i))continue;let c=C.createNode($e.text({id:n(s),name:`Line ${s+1}`,parentNodeId:e,rank:i.value,readonly:!0,isVirtual:!0}));Dt(c)&&r.push(c.value)}});return a(o)&&logger.error(`Line nodes: ${o.message}`),r},Bo=e=>{C.deleteNodes(e.map(t=>t.id))}});import{useSyncExternalStore as WN}from"react";var Va,za,Pd,bv,Dd,Ka,xv,Gr,Od,Iv,ur,Ya=g(()=>{"use strict";D();Va=null,za=null,Pd=new Set,bv=()=>{for(let e of Pd)e()},Dd=e=>{Va=e,bv()},Ka=()=>Va,xv={mark:null},Gr=e=>{za=e,xv={mark:e},bv()},Od=e=>za&&za.sha===e?za.row:null,Iv=()=>WN(e=>(Pd.add(e),()=>{Pd.delete(e)}),()=>xv),ur=()=>{let{contextNode:e}=v();return Va&&Va.sha===e.id?e.id:null}});var Ev=g(()=>{"use strict"});import{Box as an,Text as Hn}from"ink";import De,{useEffect as _d,useMemo as Rv,useRef as GN,useState as zN}from"react";import VN from"string-width";function Cv({ticket:e,sha:t,subject:n,width:r,height:o}){let[s,i]=zN({state:"loading"});_d(()=>{let M=!0;return i({state:"loading"}),yd({sha:t}).then(F=>{M&&i(a(F)?{state:"failed",message:F.message}:{state:"loaded",rows:Id(xd(F.value))})}),()=>{M=!1}},[t]);let c=s.state==="loaded"?s.rows:null,u=c!==null&&c.length>4e3,p=GN([]);_d(()=>(Bo(p.current),p.current=c&&!u?Ga(t,c.length,M=>Fd(t,M)):[],()=>{Bo(p.current),p.current=[]}),[t,c,u]),_d(()=>(Dd(c?{sha:t,rows:c}:null),Gr(null),()=>{Dd(null),Gr(null)}),[t,c]);let{selectedIndex:m}=Ye(),{mark:f}=Iv(),h=Rv(()=>c?Ed(c,C.getCommentsByIssue(e.id),t):new Set,[c,t,e]),b=f&&f.sha===t?f.row:null,E=M=>b!==null&&M>=Math.min(b,m)&&M<=Math.max(b,m),S=Rv(()=>c?Math.max(5,c.reduce((M,F)=>Math.max(M,Nv(F).length),0)+2):5,[c]),w=Math.max(1,o-4),R=Math.max(8,r-S-6);if(s.state!=="loaded")return De.createElement(an,{flexDirection:"column",width:r,height:o,padding:1},De.createElement(Hn,{color:T.primary},s.state==="loading"?"Reading the diff\u2026":`Could not read the diff: ${s.message}`));let k=M=>De.createElement(an,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:T.secondary,borderStyle:"single",paddingBottom:1},De.createElement(Hn,{color:T.secondary2,wrap:"truncate-end"},Rr(`${t.slice(0,7)} ${n} \u2014 ${M}`,Math.max(8,r-6))));return s.rows.length===0?De.createElement(an,{flexDirection:"column",width:r,height:o},k("no changes"),De.createElement(an,{paddingX:1},De.createElement(Hn,{color:T.primary},"This commit changed no files."))):u?De.createElement(an,{flexDirection:"column",width:r,height:o},k("too large to draw here"),De.createElement(an,{paddingX:1,flexDirection:"column"},De.createElement(Hn,{color:T.primary},`${s.rows.length.toLocaleString()} lines of diff.`),De.createElement(Hn,{color:T.secondary2},"Press o to open it in your editor."))):De.createElement(an,{flexDirection:"column",width:r,height:o},k(b===null?"enter to comment on a line, s to start a range, o editor, q back":"move to the other end, then enter to comment \u2014 s clears the mark"),De.createElement(Wt,{scrollByOne:!0,height:w,selectedIndex:m,itemHeight:1},s.rows.map((M,F)=>{let j=F===m,z=KN(M.kind);if(M.kind==="file")return De.createElement(an,{key:Fd(t,F),paddingX:1},De.createElement(Hn,{backgroundColor:T.secondary,color:j?T.accent:z,bold:!0,wrap:"truncate-end"},Sv(` ${Rr(ri(M.text),R)}`,R+S+1)));let J=E(F),se=`${YN(M.kind)}${Rr(ri(M.text),R)}`;return De.createElement(an,{key:Fd(t,F),paddingX:1},De.createElement(an,{flexShrink:0},De.createElement(Hn,{color:j||J?T.accent:T.secondary2,dimColor:!j&&!J,wrap:"truncate-end"},`${j?"\u276F":"\xA0"}${J?"\u258C":"\xA0"}${Nv(M).padStart(S-2,"\xA0")}`)),De.createElement(an,{flexShrink:0},De.createElement(Hn,{color:T.yellow,wrap:"truncate-end"},h.has(F)?"\u2502":"\xA0")),De.createElement(Hn,{color:j?T.accent:z,backgroundColor:j||J?T.secondary:void 0,wrap:"truncate-end"},j||J?Sv(se,R+1):se))})))}var Fd,KN,Sv,YN,Nv,wv=g(()=>{"use strict";ii();pe();N();Ld();Ya();D();Je();Ev();Ba();vt();Hr();Fd=(e,t)=>`${e}::patch::${t}`,KN=e=>{switch(e){case"added":return T.green;case"removed":return T.red;case"hunk":return T.accent;case"file":return T.primary;default:return T.secondary2}},Sv=(e,t)=>{let n=VN(e);return n>=t?e:e+"\xA0".repeat(t-n)},YN=e=>e==="added"?"+":e==="removed"?"-":" ",Nv=e=>e.kind==="file"||e.kind==="hunk"||e.kind==="note"||e.newLine===void 0?"":String(e.newLine)});import{Box as zr,Text as Cn}from"ink";import Ge,{useEffect as Av,useRef as XN,useState as JN}from"react";function kv({ticket:e,width:t,height:n}){let[r,o]=JN({state:"loading"}),s=V(e.id);Av(()=>{let E=!0;return o({state:"loading"}),Fo({ref:s}).then(S=>{E&&o(a(S)?{state:"failed",message:S.message}:{state:"loaded",commits:S.value})}),()=>{E=!1}},[s]);let i=XN([]),c=r.state==="loaded"?r.commits:null;Av(()=>(Tv(i.current),i.current=c?eC(e,c):[],()=>{Tv(i.current),i.current=[]}),[e,c]);let{selectedIndex:u,contextNode:p}=Ye(),m=c?.find(E=>E.sha===p.id)??null,h=Math.max(1,n-4),b=Math.max(12,t-34);return r.state!=="loaded"?Ge.createElement(zr,{flexDirection:"column",width:t,height:n,padding:1},Ge.createElement(Cn,{color:T.primary},r.state==="loading"?"Reading commits\u2026":`Could not read commits: ${r.message}`)):m?Ge.createElement(Cv,{ticket:e,sha:m.sha,subject:m.subject,width:t,height:n}):r.commits.length===0?Ge.createElement(zr,{flexDirection:"column",width:t,height:n,padding:1},Ge.createElement(Cn,{color:T.primary},"No commits reference this ticket."),Ge.createElement(zr,{paddingTop:1},Ge.createElement(Cn,{color:T.primary},"Commits are matched by the"),Ge.createElement(Cn,{color:T.accent},` ${s} `),Ge.createElement(Cn,{color:T.primary},"prefix on their subject line."))):Ge.createElement(zr,{flexDirection:"column",width:t,height:n},Ge.createElement(zr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:T.secondary,borderStyle:"single",paddingBottom:1},Ge.createElement(Cn,{color:T.secondary2},`Diff (${r.commits.length}) \u2014 enter to read, o to open in your editor `)),Ge.createElement(Wt,{height:h,itemHeight:2,selectedIndex:u},r.commits.map((E,S)=>{let w=S===u,R=E.subject.length>b?E.subject.slice(0,b-1)+"\u2026":E.subject;return Ge.createElement(zr,{key:E.sha,flexDirection:"row",paddingX:1,paddingBottom:1},Ge.createElement(Cn,{color:T.accent},w?"\u276F ":" "),Ge.createElement(zr,{paddingLeft:1},Ge.createElement(Cn,{color:T.secondary2},`${E.sha.slice(0,7)} `),Ge.createElement(Cn,{color:w?T.accent:T.primary},R),Ge.createElement(Cn,{color:T.secondary2},` ${tC(E)} ${ar(E.time)}`)))})))}var QN,Tv,ZN,eC,tC,Mv=g(()=>{"use strict";It();ii();me();N();pe();sr();D();Je();ei();ft();Jn();wv();Hr();QN=e=>Te(e,"diff"),Tv=e=>{for(let t of e)C.deleteNode(t.id)},ZN=(e,t,n)=>$e.field({id:e.sha,name:e.subject,parentNodeId:n,rank:String(t).padStart(6,"0"),childRenderAxis:"vertical",isVirtual:!0}),eC=(e,t)=>{let n=C.getNode(QN(e.id));if(!n||!nt(n))return[];let r=t.map((o,s)=>ZN(o,s,n.id)).map(o=>C.createNode(o)).filter(Dt).map(({value:o})=>o).filter(nt);return t.length>0&&v().selectedIndex<0&&v().contextNode.id===n.id&&H.navigate({contextNode:n,selectedIndex:0}),r},tC=e=>`+${e.insertions} -${e.deletions}`});import{Box as Xa,Text as nC}from"ink";import Wn from"react";var Lv,Pv=g(()=>{"use strict";me();pe();Eo();D();Je();La();wo();cd();Lv=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Ye(),{title:o}=t,s=t.parentNodeId?C.getNode(t.parentNodeId):void 0,i=s&&U(s)?o===Ae.ASSIGNEES?s.props.assignees??[]:o===Ae.TAGS?(s.props.tags??[]).filter(c=>C.getTag(c)):[]:[];return Wn.createElement(Xa,{alignItems:"center",paddingTop:1},Wn.createElement(Xa,{minWidth:12},Wn.createElement(Ht,{isSelected:n}),Wn.createElement(nC,{color:n?T.accent:T.secondary2},o,":")),Wn.createElement(Xa,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let p=r.id===t.id&&u===e;return Wn.createElement(Xa,{key:`${o}-${c}`,paddingRight:2,minHeight:1},Wn.createElement(Ht,{isSelected:p}),o===Ae.ASSIGNEES?Wn.createElement(Ao,{isSelected:p,id:c}):o===Ae.TAGS?Wn.createElement(Pa,{isSelected:p,id:c}):null)})))}});var Bd,Dv,$d,jd=g(()=>{"use strict";Bd=e=>Math.max(5,String(Math.max(e,1)).length+3),Dv=(e,t)=>Math.max(0,e-6-Bd(t)),$d=(e,t=0,n=0)=>Math.max(1,e-5-2*t-(n>0?1+n:0))});import{Box as $o,Text as Ud}from"ink";import Gt,{useEffect as rC,useMemo as Hd,useRef as oC}from"react";var sC,Ov,Wd,_v=g(()=>{"use strict";Ld();D();Je();vt();jd();wo();Hr();gd();Ba();sC="\u2029",Ov=(e,t)=>`${e}::inline-line::${t}`,Wd=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=Ye(),u=Hd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),p=Hd(()=>u.join("\0"),[u]),m=oC([]);rC(()=>(Bo(m.current),m.current=Ga(e,u.length,S=>Ov(e,S)),()=>{Bo(m.current),m.current=[]}),[e,p]);let f=Bd(u.length),h=Dv(s,u.length),E=Hd(()=>pd(u).map(S=>{if(S.kind==="code"||S.kind==="caption")return{...S,text:Rr(S.text,h)};if(S.kind==="text"||S.kind==="heading"){let w=S.spans.map(R=>R.code?`\`${R.text}\``:R.text).join("");return{...S,spans:ni(Rr(w,h))}}return S}),[u,h]).map((S,w)=>{let R=c.id===e&&i===w;return Gt.createElement($o,{key:Ov(e,w)},Gt.createElement($o,{flexShrink:0},Gt.createElement(Ud,{color:R?T.primary:T.secondary2,dimColor:!R},`${w+1} `.padStart(f,"\xA0"))),S.kind==="blank"?Gt.createElement(Ud,{backgroundColor:R?"gray":void 0},sC):Gt.createElement($o,null,Gt.createElement(fd,{line:S,width:S.kind==="code"?h:0,wrap:"truncate-end"})))});return Gt.createElement($o,{flexDirection:"column",paddingTop:1},Gt.createElement($o,null,Gt.createElement(Ht,{isSelected:o}),Gt.createElement(Ud,{color:o?T.accent:T.secondary2},t)),Gt.createElement($o,{flexDirection:"row",borderStyle:"round",borderColor:T.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},Gt.createElement(Wt,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},E)))}});import{Box as jo,Text as iC}from"ink";import Rt,{useMemo as Uo}from"react";var aC,lC,cC,dC,uC,Fv,Bv=g(()=>{"use strict";me();pe();D();Je();_a();Jn();Fh();tv();wo();Mv();Pv();_v();jd();aC=e=>Te(e,"description"),lC=e=>Te(e,"comments"),cC=e=>Te(e,"history"),dC=e=>Te(e,"diff"),uC=e=>Te(e,"attachments"),Fv=({ticket:e,height:t})=>{let n=Uo(()=>Mh(e),[e]),{selectedIndex:r,contextNode:o}=Ye(),s=process.stdout.columns||120,i=Uo(()=>aC(e.id),[e.id]),c=Uo(()=>lC(e.id),[e.id]),u=Uo(()=>cC(e.id),[e.id]),p=Uo(()=>dC(e.id),[e.id]),m=Uo(()=>uC(e.id),[e.id]),f=C.getAttachmentsByIssue(e.id).length,h=o.id===e.id,b=o.id===c||o.parentNodeId===c,E=o.id===u||o.parentNodeId===u,S=o.id===m||o.parentNodeId===m,w=o.id===p||o.parentNodeId===p,R=be(e.id);if(b){let le=t-3;return Rt.createElement(jo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Rt.createElement(ev,{ticket:e,width:s,height:le}))}if(S){let le=t-3;return Rt.createElement(jo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Rt.createElement(_h,{ticket:e,width:s,height:le}))}if(w){let le=t-3;return Rt.createElement(jo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Rt.createElement(kv,{ticket:e,width:s,height:le}))}if(E){let q=C.getNode(u),le=q&&nt(q)?q.props.value??"":"",gt=$d(t);return Rt.createElement(jo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},q?Rt.createElement(Wd,{id:q.id,label:"Event log",text:le,selected:!1,maxWidth:s,rows:gt}):null)}let k=[u,p,c,m],M=q=>k.includes(q),F=R.reduce((q,le)=>us(le)?q+1:q,0),j=R.reduce((q,le)=>M(le.id)?q+1:q,0),z=R.findIndex(q=>M(q.id)),J=$d(t,F,j),se=(q,le,gt,ns)=>Rt.createElement(jo,{key:q.id,paddingTop:le===z?1:0},Rt.createElement(Ht,{isSelected:gt}),Rt.createElement(iC,{backgroundColor:T.secondary,color:gt?T.accent:T.primary},ns)),ze=(q,le,gt)=>q.id===i?Rt.createElement(Wd,{key:q.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:le,maxWidth:s,rows:J}):us(q)?Rt.createElement(Lv,{key:q.id,parent:q,selected:le,selectedIndex:r}):q.id===c?se(q,gt,le,` Comments (${n}) \u203A\u203A `):q.id===m?se(q,gt,le,` Attachments (${f}) \u203A\u203A `):q.id===u?se(q,gt,le," History \u203A\u203A "):q.id===p?se(q,gt,le," Diff \u203A\u203A "):null;return Rt.createElement(jo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R.map((q,le)=>ze(q,h&&r===le,le)))}});import{Box as mC}from"ink";import Ja from"react";var pC,$v,jv=g(()=>{"use strict";me();kh();Bv();pC=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let u=t.context,p=u===ie.TICKET||u===ie.FIELD_LIST||u===ie.FIELD,m=u===ie.BOARD||u===ie.SWIMLANE,f=u===ie.TICKET?t:r.find(w=>w.context===ie.TICKET),h=Math.floor(c/3),b=Math.floor(c/Math.max(e.length,1)),E=Math.min(b,h),S=s==="dense";return Ja.createElement(mC,{flexDirection:"row",height:i},m&&e.map((w,R)=>{let k=t.id===w.id,M=k?n:-1,F=t.context===ie.BOARD&&n===R;return Ja.createElement(Th,{key:w.id,height:i,width:E,swimlane:w,isSelected:F,isDense:S,isFocused:k,listSelectedIndex:M,mode:o})}),p&&f&&Ja.createElement(Fv,{height:i,ticket:f}))},$v=Ja.memo(pC)});import Uv from"node:fs";import fC from"node:path";import gC from"react";import{render as hC}from"ink";import{Writable as vC}from"node:stream";var ai,yC,bC,xC,IC,Hv,Wv=g(()=>{"use strict";jv();me();N();D();ee();Ue();ai=e=>String(e).padStart(2,"0"),yC=e=>{let t=e.getUTCFullYear(),n=ai(e.getUTCMonth()+1),r=ai(e.getUTCDate()),o=ai(e.getUTCHours()),s=ai(e.getUTCMinutes()),i=ai(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},bC=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",xC=async(e,{width:t,height:n})=>{let r="",o=new vC({write(i,c,u){let p=IC(i.toString()).trimEnd();p.trim().length>0&&p.includes("\u256D")&&(r=p),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=hC(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},IC=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Hv=async()=>{let{viewMode:e}=de(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=v(),i=r.find(R=>R.context==="BOARD");if(!i)return l("No board found to export");let c=120,u=40,p=await xC(gC.createElement($v,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(R=>R!==void 0&&xr(R)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:u});if(!p)return l("Failed to render board export");let m=Di(process.cwd());if(a(m))return l("Unable to export, epiq root not found");let f=new Date,h=yC(f),b=`board_${bC(i.title)}_${h}.md`,E=vp(m.value);Uv.mkdirSync(E,{recursive:!0});let S=fC.join(E,b),w=`# Board - ${i.title}
|
|
81
|
+
`):e},Vh=({snippet:e,...t})=>{let n=t.note.trim();return[...n?[n,""]:[],cN({...t,note:n}),`\`${t.filePath}\` ${zh(t)}`,"```",uN(e),"```"].join(`
|
|
82
|
+
`)}});var mN,oi,pN,fN,gN,hN,si,hd,Yh,Kh,Xh,ja=g(()=>{"use strict";$a();mN=(e,t)=>{let n=Math.max(1,Math.floor(t)),r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[""];let o=[],s="";for(let i of r){let c=i;for(;c.length>n;)s&&(o.push(s),s=""),o.push(c.slice(0,n)),c=c.slice(n);s?s.length+1+c.length<=n?s=`${s} ${c}`:(o.push(s),s=c):s=c}return s&&o.push(s),o},oi=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)},pN=/!\[([^\]]*)\]\([^)]*\)/g,fN=e=>e.replace(pN,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),gN=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),hN=4,si=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(hN)),hd=e=>{let t=!1;return e.map(si).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=ri(n);if(r)return{kind:"caption",text:gd(r)};let o=fN(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:oi(s[1]??"")}:{kind:"text",spans:oi(o)}})},Yh=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Kh=(e,t)=>{let n=[];for(let r of hd(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 Yh(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of mN(gN(r.spans),t))n.push({kind:r.kind,spans:oi(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},Xh=(e,t)=>{let n=ri(e),r=n?qh(e):null;if(!n||r===null)return Kh(fd(e).split(`
|
|
83
|
+
`),t);let o=Gh(e),s=r.split(`
|
|
84
|
+
`).map(si),i=n.side===n.endSide?n.start:void 0,c=i===void 0?0:String(i+s.length-1).length+3;return[...o?[...Kh(o.split(`
|
|
85
|
+
`),t),{kind:"blank"}]:[],{kind:"caption",text:gd(n)},...s.flatMap((u,p)=>Yh(u,Math.max(1,t-c)).map((m,f)=>({kind:"code",text:m,number:i===void 0||f>0?void 0:i+p})))]}});import{Box as Jh,Text as Gr}from"ink";import Vt from"react";var Qh,vd,Zh,yd=g(()=>{"use strict";Ye();Qh=({spans:e,bold:t,wrap:n})=>Vt.createElement(Gr,{color:w.primary,bold:t,wrap:n},e.map((r,o)=>r.code?Vt.createElement(Gr,{key:o,color:w.yellow},r.text):Vt.createElement(Gr,{key:o},r.text))),vd=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return Vt.createElement(Gr,null," ");case"fence":return Vt.createElement(Gr,{color:w.secondary2},"```");case"caption":return Vt.createElement(Gr,{color:w.accent,wrap:r},e.text);case"heading":return Vt.createElement(Qh,{spans:e.spans,bold:!0,wrap:r});case"text":return Vt.createElement(Qh,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return Vt.createElement(Gr,{backgroundColor:w.secondary,color:w.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},Zh=({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 Vt.createElement(Jh,{flexDirection:"column"},e.map((o,s)=>Vt.createElement(Jh,{key:s},Vt.createElement(vd,{line:o,width:t,gutter:r}))))}});import{Box as dr,Text as ur}from"ink";import He,{useEffect as vN,useMemo as ev,useRef as yN}from"react";import{decodeTime as tv}from"ulid";function rv({ticket:e,width:t,height:n}){let r=ev(()=>IN(e),[e]),o=yN([]);vN(()=>(nv(o.current),o.current=EN(e,r),()=>{nv(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Ve(),c=Math.max(1,n-4),u=Math.max(20,t-8),p=ev(()=>r.map(f=>{let h=Xh(f.md,u);return h.length>0?h:[{kind:"blank"}]}),[r,u]),m=p.map(f=>f.length+bN);return r.length===0?He.createElement(dr,{flexDirection:"column",width:t,height:n,padding:1},He.createElement(ur,{color:w.primary},"No comments yet."),He.createElement(dr,{paddingTop:1},He.createElement(ur,{color:w.primary},"Use"),He.createElement(ur,{color:w.accent}," :comment "),He.createElement(ur,{color:w.primary},"to add the first one."))):He.createElement(dr,{flexDirection:"column",width:t,height:n},He.createElement(dr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:w.secondary,borderStyle:"single",paddingBottom:1},He.createElement(ur,{color:w.secondary2},"Comments (",r.length,") ")),He.createElement(zt,{height:c,itemHeights:m,selectedIndex:s},r.map((f,h)=>{let b=h===s;return He.createElement(dr,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:w.secondary,borderStyle:"single"},He.createElement(dr,{flexDirection:"row",paddingBottom:1},He.createElement(ur,{color:w.accent},b?"\u276F ":" "),He.createElement(dr,{paddingLeft:1},He.createElement(ur,{color:w.secondary2},`#${h+1} `),He.createElement(Mo,{id:f.authorId}),He.createElement(ur,{color:w.secondary2}," "+cr(it(f.id))))),He.createElement(dr,{paddingLeft:3,paddingBottom:1},He.createElement(Zh,{lines:p[h]??[],width:u})))})))}var bN,xN,IN,nv,EN,ov=g(()=>{"use strict";Et();at();ni();ce();N();de();D();Ye();Qn();Da();Wr();Ba();ja();yd();bN=4,xN=e=>we(e,"comments"),IN=e=>R.getCommentsByIssue(e.id).sort((t,n)=>tv(t.id)-tv(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,md:t.md})),nv=e=>{for(let t of e)R.deleteNode(t.id)},EN=(e,t)=>{let n=R.getNode(xN(e.id));if(!n||!et(n))return[];let r=t.map((o,s)=>Oh(o,s,n.id)).map(R.createNode).filter(_t).map(({value:o})=>o).filter(fs);return t.length>0&&v().selectedIndex<0&&H.navigate({contextNode:n,selectedIndex:0}),r}});var mr,ii,_o=g(()=>{"use strict";N();Q();mr=e=>{let t=Ne(e??process.cwd());return l(t)?a(t.message):d("Resolved Epiq repo root",t.value)},ii=e=>/^[0-9a-f]{7,40}$/i.test(e)});var SN,Ua,bd=g(()=>{"use strict";SN="EPIQ_CACHE_MS",Ua=e=>{let t=process.env[SN];if(t===void 0||t.trim()==="")return e;let n=Number(t);return Number.isFinite(n)&&n>=0?n:e}});var Fo,sv,iv,Bo,RN,av,$o,xd=g(()=>{"use strict";ze();N();rn();bd();mt();_o();Fo="",sv="",iv=5e3,Bo=null,RN=(e,t,n)=>(t===void 0||e>=Math.floor(t/1e3)*1e3)&&(n===void 0||e<=n),av=async(e={})=>{let t=mr(e.repoRoot);if(l(t))return a(t.message);let n=Mt(t.value);if(l(n))return a(n.message);let r=e.start===void 0&&e.end===void 0;if(r&&Bo&&Bo.repoRoot===t.value&&Bo.stateBranch===n.value.stateBranch&&Date.now()-Bo.fetchedAt<Ua(iv))return d("Computed commit timeline",Bo.result);let o=await W({cwd:t.value,args:["log","--branches","--not",n.value.stateBranch,...e.start!==void 0?[`--since=@${Math.floor(e.start/1e3)}`]:[],...e.end!==void 0?[`--until=@${Math.floor(e.end/1e3)}`]:[],"--shortstat",`--format=${sv}%H${Fo}%at${Fo}%an${Fo}%ae${Fo}%s`]});if(l(o))return a(o.message);let s=o.value.stdout.split(sv).filter(i=>i.trim().length>0).map(i=>{let[c,...u]=i.split(`
|
|
86
|
+
`),[p,m,f,h,...b]=(c??"").split(Fo);if(!p||!m)return null;let I=u.join(" "),C=Number(/(\d+) insertion/.exec(I)?.[1]??0),T=Number(/(\d+) deletion/.exec(I)?.[1]??0);return{sha:p,time:Number(m)*1e3,author:f??"unknown",authorEmail:h??"",subject:b.join(Fo),linesChanged:C+T,insertions:C,deletions:T}}).filter(i=>i!==null).filter(i=>RN(i.time,e.start,e.end));return r&&(Bo={repoRoot:t.value,stateBranch:n.value.stateBranch,fetchedAt:Date.now(),result:s}),d("Computed commit timeline",s)},$o=async e=>{let t=e.ref.trim();if(!t)return a("ref must not be empty");if(t.length!==7)return a(`"${t}" is ${t.length} characters; a ref is ${7}. Read it off the issue rather than slicing the id by hand.`);let n=await av({repoRoot:e.repoRoot});if(l(n))return a(n.message);let r=`${t.toUpperCase()} `,o=c=>c.subject.toUpperCase().startsWith(r),s=n.value,i=[];for(let[c,u]of s.entries()){if(!o(u))continue;let p=s[c+1];i.push({...u,precedingSha:p&&o(p)?p.sha:null})}return d("Matched commits by ref",i)}});var Id,lv=g(()=>{"use strict";ze();N();_o();xd();Id=async e=>{if(!ii(e.sha))return a("Invalid commit sha");let t=mr(e.repoRoot);if(l(t))return a(t.message);let n=await W({cwd:t.value,args:["show","--no-ext-diff","--no-color","--patch","--find-renames","--format=",e.sha]});return l(n)?a(n.message):d("Read commit patch",n.value.stdout)}});var NN,Ha,cv,Sd,Ed,Rd,Wa,Nd,dv,CN,uv,mv,pv,Cd,qa=g(()=>{"use strict";$a();NN=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/,Ha=e=>{if(!e.startsWith('"')||!e.endsWith('"'))return e;let t=e.slice(1,-1),n="";for(let r=0;r<t.length;r++){if(t[r]!=="\\"){n+=t[r];continue}let o=t[++r];if(o==="n")n+=`
|
|
87
|
+
`;else if(o==="t")n+=" ";else if(o==='"'||o==="\\")n+=o;else if(o&&/[0-7]/.test(o)){let s=t.slice(r,r+3);n+=String.fromCharCode(parseInt(s,8)),r+=2}else o!==void 0&&(n+=o)}try{return decodeURIComponent(escape(n))}catch{return n}},cv=e=>{let t=Ha(e.trim());return t==="/dev/null"?null:t.replace(/^[ab]\//,"")},Sd=e=>{let t=[],n=null,r=0,o=0,s=()=>{let i={path:"",oldPath:null,binary:!1,added:0,removed:0,lines:[]};return t.push(i),i};for(let i of e.split(`
|
|
88
|
+
`)){if(i.startsWith("diff --git ")){n=s();let m=i.slice(11),f=m.lastIndexOf(" b/");f!==-1&&(n.path=Ha(m.slice(f+1)).replace(/^b\//,""));continue}if(!n){if(!i.trim())continue;n=s()}let c=n,u=c.lines.length===0;if(u&&i.startsWith("--- ")){let m=cv(i.slice(4));m&&(c.oldPath=m);continue}if(u&&i.startsWith("+++ ")){let m=cv(i.slice(4));m&&(c.path=m);continue}if(u&&i.startsWith("rename from ")){c.oldPath=Ha(i.slice(12));continue}if(u&&i.startsWith("rename to ")){c.path=Ha(i.slice(10));continue}if(u&&(i.startsWith("Binary files ")||i.startsWith("GIT binary patch"))){c.binary=!0,c.lines.push({kind:"note",text:"Binary file"});continue}let p=NN.exec(i);if(p){r=Number(p[1]),o=Number(p[3]),c.lines.push({kind:"hunk",text:i});continue}if(!u){if(i.startsWith("\\")){c.lines.push({kind:"note",text:i.slice(1).trim()});continue}if(i.startsWith("+")){c.added++,c.lines.push({kind:"added",text:i.slice(1),newLine:o++});continue}if(i.startsWith("-")){c.removed++,c.lines.push({kind:"removed",text:i.slice(1),oldLine:r++});continue}if(i.startsWith(" ")){c.lines.push({kind:"context",text:i.slice(1),oldLine:r++,newLine:o++});continue}i===""&&c.lines.push({kind:"context",text:"",oldLine:r++,newLine:o++})}}for(let i of t)!i.path&&i.oldPath&&(i.path=i.oldPath);return t.filter(i=>i.path!=="")},Ed=e=>e.oldPath&&e.oldPath!==e.path?e.oldPath:null,Rd=e=>e.flatMap(t=>[{kind:"file",text:`${Ed(t)?`${Ed(t)} \u2192 `:""}${t.path}`,file:t},...t.lines]),Wa=e=>{let t="",n=-1;return e.map(r=>(r.kind==="file"&&(t=r.file.path),r.kind==="hunk"&&n++,{file:t,hunk:n}))},Nd=(e,t,n)=>{let r=t.map(i=>ri(i.md)).filter(i=>i!==null&&i.sha===n&&i.side==="additions");if(r.length===0)return new Set;let o=Wa(e),s=new Set;return e.forEach((i,c)=>{let u=i.newLine;if(u===void 0)return;let p=o[c]?.file;r.some(m=>m.filePath===p&&m.start<=u&&u<=m.end)&&s.add(c)}),s},dv=(e,t)=>e===t?`line:${e}`:`lines:${e}-${t}`,CN=/^lines?:(\d+)(?:-(\d+))?(?:\s+|$)/,uv=e=>{let t=CN.exec(e);if(!t)return null;let n=Number(t[1]),r=t[2]===void 0?n:Number(t[2]);return{start:Math.min(n,r),end:Math.max(n,r),note:e.slice(t[0].length)}},mv=(e,t)=>Wa(e)[t]?.file??null,pv=(e,t,n,r)=>{let o=Wa(e),s=u=>e.findIndex((p,m)=>o[m]?.file===t&&(p.kind==="added"||p.kind==="context")&&p.newLine===u),i=s(n),c=s(r);return i===-1||c===-1?{ok:!1,reason:`${t} has no line ${i===-1?n:r} on the new side`}:Cd(e,i,c)},Cd=(e,t,n)=>{let[r,o]=t<=n?[t,n]:[n,t],s=e[r],i=e[o];if(!s||!i)return{ok:!1,reason:"That line is not in the diff"};let c=h=>(h.kind==="added"||h.kind==="context")&&h.newLine!==void 0;if(!c(s)||!c(i))return{ok:!1,reason:"Comments anchor to the new side: pick an added or unchanged line"};let u=Wa(e),p=u[r],m=u[o];if(p.file!==m.file)return{ok:!1,reason:"A comment covers one file at a time"};if(p.hunk!==m.hunk)return{ok:!1,reason:"A comment covers one hunk at a time"};let f=e.slice(r,o+1).filter(c);return{ok:!0,value:{filePath:p.file,start:f[0].newLine,end:f[f.length-1].newLine,snippet:f.map(h=>h.text).join(`
|
|
89
|
+
`)}}}});import{spawn as AN,spawnSync as wN}from"node:child_process";import TN from"node:os";import fv from"node:path";import{ulid as MN}from"ulid";function Ad(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 kN(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Ga(){let{preferredEditor:e}=ae(),t=[e?kN(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function wd(e){let[t=""]=Ad(e);return/(^|\/)code(-insiders)?$/.test(t)}function gv(e,t){let[n="",...r]=Ad(e);return{command:n,args:[...r,...t]}}function hv(e,t){return gv(e,wd(e)?["--wait",t]:[t])}function LN(e,t,n,r="new"){return gv(e,[r==="new"?"--new-window":"--reuse-window","--diff",t,n])}function vv(e){let t=fv.join(TN.tmpdir(),"epiq");Xe.mkDir(t);let n=fv.join(t,MN());Xe.writeToFile(n,e??"");let r=Ga();for(let o of r){let{command:s,args:i}=hv(o,n);if(!s)continue;let c=wN(s,i,{stdio:"inherit"});if(!c.error&&c.status===0){let u=Xe.readFile(n);if(u==null)return a("Unable to read edited file");let p=u.replace(/\r?\n$/,"");return d("Successfully edited",p)}}return a("Unable to open editor")}function DN(e){let[t=""]=Ad(e),n=t.split("/").pop()??t;return PN.has(n)}function yv({command:e,args:t},n){return new Promise(r=>{if(!e){r(a(`"${n}" is not a usable editor command`));return}let o=AN(e,t,{stdio:"ignore",detached:!0}),s=!1,i=u=>{s||(s=!0,clearTimeout(c),r(u))};o.on("error",u=>i(a(u.message))),o.on("exit",u=>{i(u===0?d("Opened editor",!0):a(`"${n}" exited with code ${u}`))});let c=setTimeout(()=>{o.unref(),i(d("Opened editor",!0))},ON)})}function _N(e,t){return DN(e)?Promise.resolve(a(`"${e}" is a terminal editor and can't open from the GUI (no terminal attached). Set preferredEditor to a GUI editor (e.g. "code"), or open the file yourself: ${t}`)):yv(hv(e,t),e)}function Td(e,t,n,r="new"){return yv(LN(e,t,n,r),e)}async function bv(e){let t=Ga();if(t.length===0)return a("No editor configured (preferredEditor, VISUAL, or EDITOR)");let n=a("Unable to open editor");for(let r of t){let o=await _N(r,e);if(!l(o))return o;n=o,logger.error(`Failed to open editor "${r}" for ${e}: ${o.message}`)}return n}var PN,ON,Md=g(()=>{"use strict";N();$e();ea();PN=new Set(["vim","vi","nvim","nano","pico","ed"]);ON=600});import{chmodSync as FN,existsSync as BN,lstatSync as $N,mkdirSync as jN}from"node:fs";import UN from"node:os";import HN from"node:path";var ai,kd=g(()=>{"use strict";N();ai=(...e)=>{let t=HN.join(UN.tmpdir(),"epiq",...e);try{return BN(t)&&$N(t).isSymbolicLink()?a(`Refusing to write through a symlink at ${t}`):(jN(t,{recursive:!0,mode:448}),FN(t,448),d("Prepared private temp dir",t))}catch(n){return a(`Unable to prepare ${t}: ${n instanceof Error?n.message:String(n)}`)}}});import{existsSync as Ld}from"node:fs";import{chmod as Pd}from"node:fs/promises";import za from"node:path";var WN,qN,GN,xv,zN,VN,Dd,Iv=g(()=>{"use strict";ze();Md();N();ea();kd();_o();WN=async(e,t)=>{let n=await W({cwd:e,args:["show",t]});if(l(n))return a(n.message);let r=ai("commit-diffs");if(l(r))return a(r.message);let o=za.join(r.value,`${t}.diff`);return Ld(o)||(Xe.writeToFile(o,n.value.stdout),await Pd(o,292)),bv(o)},qN=12,GN=800,xv=async(e,t,n)=>{let r=await W({cwd:e,args:["show",`${t}:${n}`]});return l(r)?"":r.value.stdout},zN=async(e,t)=>{let n=await W({cwd:e,args:["diff","--name-only",`${t}~1`,t]});if(l(n))return a(n.message);let r=n.value.stdout.split(`
|
|
90
|
+
`).map(o=>o.trim()).filter(Boolean);return r.length===0?a("No changed files found for this commit"):d("Listed changed files",r)},VN=async(e,t,n)=>{let r=await zN(e,t);if(l(r))return a(r.message);let o=r.value;if(o.length>qN)return a(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=ai("commit-diffs",t);if(l(s))return a(s.message);let i=s.value,c=await Promise.all(o.map(async(h,b)=>{let[I,C]=await Promise.all([xv(e,`${t}~1`,h),xv(e,t,h)]),T=za.basename(h),S=za.join(i,String(b),"before",T),M=za.join(i,String(b),"after",T);return Ld(S)||(Xe.writeToFile(S,I),await Pd(S,292)),Ld(M)||(Xe.writeToFile(M,C),await Pd(M,292)),{beforePath:S,afterPath:M}})),[u,...p]=c;if(!u)return a("No changed files found for this commit");let m=await Td(n,u.beforePath,u.afterPath,"new");if(l(m)||p.length===0)return m;await new Promise(h=>setTimeout(h,GN));let f=await Promise.all(p.map(({beforePath:h,afterPath:b})=>Td(n,h,b,"reuse")));for(let h of f)l(h)&&logger.error(`Failed to open an additional diff tab for ${t}: ${h.message}`);return m},Dd=async e=>{if(!ii(e.sha))return a("Invalid commit sha");let t=mr(e.repoRoot);if(l(t))return a(t.message);let n=t.value,r=Ga()[0];if(r&&wd(r)){let o=await VN(n,e.sha,r);if(!l(o))return o;logger.error(`Side-by-side diff failed for ${e.sha}, falling back to unified diff: ${o.message}`)}return WN(n,e.sha)}});var li=g(()=>{"use strict";_o();xd();lv();qa();Iv()});var Va,jo,Od=g(()=>{"use strict";N();ar();D();xo();de();Va=(e,t,n)=>{let r=[],o=va(()=>{for(let s=0;s<t;s++){let i=Dt(BigInt(s+1));if(!_t(i))continue;let c=R.createNode(Fe.text({id:n(s),name:`Line ${s+1}`,parentNodeId:e,rank:i.value,readonly:!0,isVirtual:!0}));_t(c)&&r.push(c.value)}});return l(o)&&logger.error(`Line nodes: ${o.message}`),r},jo=e=>{R.deleteNodes(e.map(t=>t.id))}});import{useSyncExternalStore as KN}from"react";var Ya,Ka,_d,Ev,Fd,Xa,Sv,zr,Bd,Rv,pr,Ja=g(()=>{"use strict";D();Ya=null,Ka=null,_d=new Set,Ev=()=>{for(let e of _d)e()},Fd=e=>{Ya=e,Ev()},Xa=()=>Ya,Sv={mark:null},zr=e=>{Ka=e,Sv={mark:e},Ev()},Bd=e=>Ka&&Ka.sha===e?Ka.row:null,Rv=()=>KN(e=>(_d.add(e),()=>{_d.delete(e)}),()=>Sv),pr=()=>{let{contextNode:e}=v();return Ya&&Ya.sha===e.id?e.id:null}});var Nv=g(()=>{"use strict"});import{Box as dn,Text as Wn}from"ink";import Le,{useEffect as $d,useMemo as Cv,useRef as XN,useState as JN}from"react";import QN from"string-width";function Tv({ticket:e,sha:t,subject:n,width:r,height:o}){let[s,i]=JN({state:"loading"});$d(()=>{let L=!0;return i({state:"loading"}),Id({sha:t}).then(F=>{L&&i(l(F)?{state:"failed",message:F.message}:{state:"loaded",rows:Rd(Sd(F.value))})}),()=>{L=!1}},[t]);let c=s.state==="loaded"?s.rows:null,u=c!==null&&c.length>4e3,p=XN([]);$d(()=>(jo(p.current),p.current=c&&!u?Va(t,c.length,L=>jd(t,L)):[],()=>{jo(p.current),p.current=[]}),[t,c,u]),$d(()=>(Fd(c?{sha:t,rows:c}:null),zr(null),()=>{Fd(null),zr(null)}),[t,c]);let{selectedIndex:m}=Ve(),{mark:f}=Rv(),h=Cv(()=>c?Nd(c,R.getCommentsByIssue(e.id),t):new Set,[c,t,e]),b=f&&f.sha===t?f.row:null,I=L=>b!==null&&L>=Math.min(b,m)&&L<=Math.max(b,m),C=Cv(()=>c?Math.max(5,c.reduce((L,F)=>Math.max(L,wv(F).length),0)+2):5,[c]),T=Math.max(1,o-4),S=Math.max(8,r-C-6);if(s.state!=="loaded")return Le.createElement(dn,{flexDirection:"column",width:r,height:o,padding:1},Le.createElement(Wn,{color:w.primary},s.state==="loading"?"Reading the diff\u2026":`Could not read the diff: ${s.message}`));let M=L=>Le.createElement(dn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:w.secondary,borderStyle:"single",paddingBottom:1},Le.createElement(Wn,{color:w.secondary2,wrap:"truncate-end"},Nr(`${t.slice(0,7)} ${n} \u2014 ${L}`,Math.max(8,r-6))));return s.rows.length===0?Le.createElement(dn,{flexDirection:"column",width:r,height:o},M("no changes"),Le.createElement(dn,{paddingX:1},Le.createElement(Wn,{color:w.primary},"This commit changed no files."))):u?Le.createElement(dn,{flexDirection:"column",width:r,height:o},M("too large to draw here"),Le.createElement(dn,{paddingX:1,flexDirection:"column"},Le.createElement(Wn,{color:w.primary},`${s.rows.length.toLocaleString()} lines of diff.`),Le.createElement(Wn,{color:w.secondary2},"Press o to open it in your editor."))):Le.createElement(dn,{flexDirection:"column",width:r,height:o},M(b===null?"enter to comment on a line, s to start a range, o editor, q back":"move to the other end, then enter to comment \u2014 s clears the mark"),Le.createElement(zt,{scrollByOne:!0,height:T,selectedIndex:m,itemHeight:1},s.rows.map((L,F)=>{let j=F===m,z=ZN(L.kind);if(L.kind==="file")return Le.createElement(dn,{key:jd(t,F),paddingX:1},Le.createElement(Wn,{backgroundColor:w.secondary,color:j?w.accent:z,bold:!0,wrap:"truncate-end"},Av(` ${Nr(si(L.text),S)}`,S+C+1)));let X=I(F),ne=`${eC(L.kind)}${Nr(si(L.text),S)}`;return Le.createElement(dn,{key:jd(t,F),paddingX:1},Le.createElement(dn,{flexShrink:0},Le.createElement(Wn,{color:j||X?w.accent:w.secondary2,dimColor:!j&&!X,wrap:"truncate-end"},`${j?"\u276F":"\xA0"}${X?"\u258C":"\xA0"}${wv(L).padStart(C-2,"\xA0")}`)),Le.createElement(dn,{flexShrink:0},Le.createElement(Wn,{color:w.yellow,wrap:"truncate-end"},h.has(F)?"\u2502":"\xA0")),Le.createElement(Wn,{color:j?w.accent:z,backgroundColor:j||X?w.secondary:void 0,wrap:"truncate-end"},j||X?Av(ne,S+1):ne))})))}var jd,ZN,Av,eC,wv,Mv=g(()=>{"use strict";li();de();N();Od();Ja();D();Ye();Nv();ja();vt();Wr();jd=(e,t)=>`${e}::patch::${t}`,ZN=e=>{switch(e){case"added":return w.green;case"removed":return w.red;case"hunk":return w.accent;case"file":return w.primary;default:return w.secondary2}},Av=(e,t)=>{let n=QN(e);return n>=t?e:e+"\xA0".repeat(t-n)},eC=e=>e==="added"?"+":e==="removed"?"-":" ",wv=e=>e.kind==="file"||e.kind==="hunk"||e.kind==="note"||e.newLine===void 0?"":String(e.newLine)});import{Box as Vr,Text as An}from"ink";import We,{useEffect as kv,useRef as tC,useState as nC}from"react";function Pv({ticket:e,width:t,height:n}){let[r,o]=nC({state:"loading"}),s=V(e.id);kv(()=>{let I=!0;return o({state:"loading"}),$o({ref:s}).then(C=>{I&&o(l(C)?{state:"failed",message:C.message}:{state:"loaded",commits:C.value})}),()=>{I=!1}},[s]);let i=tC([]),c=r.state==="loaded"?r.commits:null;kv(()=>(Lv(i.current),i.current=c?sC(e,c):[],()=>{Lv(i.current),i.current=[]}),[e,c]);let{selectedIndex:u,contextNode:p}=Ve(),m=c?.find(I=>I.sha===p.id)??null,h=Math.max(1,n-4),b=Math.max(12,t-34);return r.state!=="loaded"?We.createElement(Vr,{flexDirection:"column",width:t,height:n,padding:1},We.createElement(An,{color:w.primary},r.state==="loading"?"Reading commits\u2026":`Could not read commits: ${r.message}`)):m?We.createElement(Tv,{ticket:e,sha:m.sha,subject:m.subject,width:t,height:n}):r.commits.length===0?We.createElement(Vr,{flexDirection:"column",width:t,height:n,padding:1},We.createElement(An,{color:w.primary},"No commits reference this ticket."),We.createElement(Vr,{paddingTop:1},We.createElement(An,{color:w.primary},"Commits are matched by the"),We.createElement(An,{color:w.accent},` ${s} `),We.createElement(An,{color:w.primary},"prefix on their subject line."))):We.createElement(Vr,{flexDirection:"column",width:t,height:n},We.createElement(Vr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:w.secondary,borderStyle:"single",paddingBottom:1},We.createElement(An,{color:w.secondary2},`Diff (${r.commits.length}) \u2014 enter to read, o to open in your editor `)),We.createElement(zt,{height:h,itemHeight:2,selectedIndex:u},r.commits.map((I,C)=>{let T=C===u,S=I.subject.length>b?I.subject.slice(0,b-1)+"\u2026":I.subject;return We.createElement(Vr,{key:I.sha,flexDirection:"row",paddingX:1,paddingBottom:1},We.createElement(An,{color:w.accent},T?"\u276F ":" "),We.createElement(Vr,{paddingLeft:1},We.createElement(An,{color:w.secondary2},`${I.sha.slice(0,7)} `),We.createElement(An,{color:T?w.accent:w.primary},S),We.createElement(An,{color:w.secondary2},` ${iC(I)} ${cr(I.time)}`)))})))}var rC,Lv,oC,sC,iC,Dv=g(()=>{"use strict";Et();li();ce();N();de();ar();D();Ye();ni();mt();Qn();Mv();Wr();rC=e=>we(e,"diff"),Lv=e=>{for(let t of e)R.deleteNode(t.id)},oC=(e,t,n)=>Fe.field({id:e.sha,name:e.subject,parentNodeId:n,rank:String(t).padStart(6,"0"),childRenderAxis:"vertical",isVirtual:!0}),sC=(e,t)=>{let n=R.getNode(rC(e.id));if(!n||!et(n))return[];let r=t.map((o,s)=>oC(o,s,n.id)).map(o=>R.createNode(o)).filter(_t).map(({value:o})=>o).filter(et);return t.length>0&&v().selectedIndex<0&&v().contextNode.id===n.id&&H.navigate({contextNode:n,selectedIndex:0}),r},iC=e=>`+${e.insertions} -${e.deletions}`});import{Box as Qa,Text as aC}from"ink";import qn from"react";var Ov,_v=g(()=>{"use strict";ce();de();So();D();Ye();Da();To();md();Ov=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Ve(),{title:o}=t,s=t.parentNodeId?R.getNode(t.parentNodeId):void 0,i=s&&U(s)?o===Ae.ASSIGNEES?s.props.assignees??[]:o===Ae.TAGS?(s.props.tags??[]).filter(c=>R.getTag(c)):[]:[];return qn.createElement(Qa,{alignItems:"center",paddingTop:1},qn.createElement(Qa,{minWidth:12},qn.createElement(Gt,{isSelected:n}),qn.createElement(aC,{color:n?w.accent:w.secondary2},o,":")),qn.createElement(Qa,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let p=r.id===t.id&&u===e;return qn.createElement(Qa,{key:`${o}-${c}`,paddingRight:2,minHeight:1},qn.createElement(Gt,{isSelected:p}),o===Ae.ASSIGNEES?qn.createElement(Mo,{isSelected:p,id:c}):o===Ae.TAGS?qn.createElement(Oa,{isSelected:p,id:c}):null)})))}});var Ud,Fv,Hd,Wd=g(()=>{"use strict";Ud=e=>Math.max(5,String(Math.max(e,1)).length+3),Fv=(e,t)=>Math.max(0,e-6-Ud(t)),Hd=(e,t=0,n=0)=>Math.max(1,e-5-2*t-(n>0?1+n:0))});import{Box as Uo,Text as qd}from"ink";import Kt,{useEffect as lC,useMemo as Gd,useRef as cC}from"react";var dC,Bv,zd,$v=g(()=>{"use strict";Od();D();Ye();vt();Wd();To();Wr();yd();ja();dC="\u2029",Bv=(e,t)=>`${e}::inline-line::${t}`,zd=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=Ve(),u=Gd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),p=Gd(()=>u.join("\0"),[u]),m=cC([]);lC(()=>(jo(m.current),m.current=Va(e,u.length,C=>Bv(e,C)),()=>{jo(m.current),m.current=[]}),[e,p]);let f=Ud(u.length),h=Fv(s,u.length),I=Gd(()=>hd(u).map(C=>{if(C.kind==="code"||C.kind==="caption")return{...C,text:Nr(C.text,h)};if(C.kind==="text"||C.kind==="heading"){let T=C.spans.map(S=>S.code?`\`${S.text}\``:S.text).join("");return{...C,spans:oi(Nr(T,h))}}return C}),[u,h]).map((C,T)=>{let S=c.id===e&&i===T;return Kt.createElement(Uo,{key:Bv(e,T)},Kt.createElement(Uo,{flexShrink:0},Kt.createElement(qd,{color:S?w.primary:w.secondary2,dimColor:!S},`${T+1} `.padStart(f,"\xA0"))),C.kind==="blank"?Kt.createElement(qd,{backgroundColor:S?"gray":void 0},dC):Kt.createElement(Uo,null,Kt.createElement(vd,{line:C,width:C.kind==="code"?h:0,wrap:"truncate-end"})))});return Kt.createElement(Uo,{flexDirection:"column",paddingTop:1},Kt.createElement(Uo,null,Kt.createElement(Gt,{isSelected:o}),Kt.createElement(qd,{color:o?w.accent:w.secondary2},t)),Kt.createElement(Uo,{flexDirection:"row",borderStyle:"round",borderColor:w.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},Kt.createElement(zt,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},I)))}});import{Box as Ho,Text as uC}from"ink";import Rt,{useMemo as Wo}from"react";var mC,pC,fC,gC,hC,jv,Uv=g(()=>{"use strict";ce();de();D();Ye();Ba();Qn();jh();ov();To();Dv();_v();$v();Wd();mC=e=>we(e,"description"),pC=e=>we(e,"comments"),fC=e=>we(e,"history"),gC=e=>we(e,"diff"),hC=e=>we(e,"attachments"),jv=({ticket:e,height:t})=>{let n=Wo(()=>Dh(e),[e]),{selectedIndex:r,contextNode:o}=Ve(),s=process.stdout.columns||120,i=Wo(()=>mC(e.id),[e.id]),c=Wo(()=>pC(e.id),[e.id]),u=Wo(()=>fC(e.id),[e.id]),p=Wo(()=>gC(e.id),[e.id]),m=Wo(()=>hC(e.id),[e.id]),f=R.getAttachmentsByIssue(e.id).length,h=o.id===e.id,b=o.id===c||o.parentNodeId===c,I=o.id===u||o.parentNodeId===u,C=o.id===m||o.parentNodeId===m,T=o.id===p||o.parentNodeId===p,S=ve(e.id);if(b){let se=t-3;return Rt.createElement(Ho,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Rt.createElement(rv,{ticket:e,width:s,height:se}))}if(C){let se=t-3;return Rt.createElement(Ho,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Rt.createElement($h,{ticket:e,width:s,height:se}))}if(T){let se=t-3;return Rt.createElement(Ho,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Rt.createElement(Pv,{ticket:e,width:s,height:se}))}if(I){let q=R.getNode(u),se=q&&et(q)?q.props.value??"":"",gt=Hd(t);return Rt.createElement(Ho,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},q?Rt.createElement(zd,{id:q.id,label:"Event log",text:se,selected:!1,maxWidth:s,rows:gt}):null)}let M=[u,p,c,m],L=q=>M.includes(q),F=S.reduce((q,se)=>ps(se)?q+1:q,0),j=S.reduce((q,se)=>L(se.id)?q+1:q,0),z=S.findIndex(q=>L(q.id)),X=Hd(t,F,j),ne=(q,se,gt,os)=>Rt.createElement(Ho,{key:q.id,paddingTop:se===z?1:0},Rt.createElement(Gt,{isSelected:gt}),Rt.createElement(uC,{backgroundColor:w.secondary,color:gt?w.accent:w.primary},os)),qe=(q,se,gt)=>q.id===i?Rt.createElement(zd,{key:q.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:se,maxWidth:s,rows:X}):ps(q)?Rt.createElement(Ov,{key:q.id,parent:q,selected:se,selectedIndex:r}):q.id===c?ne(q,gt,se,` Comments (${n}) \u203A\u203A `):q.id===m?ne(q,gt,se,` Attachments (${f}) \u203A\u203A `):q.id===u?ne(q,gt,se," History \u203A\u203A "):q.id===p?ne(q,gt,se," Diff \u203A\u203A "):null;return Rt.createElement(Ho,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},S.map((q,se)=>qe(q,h&&r===se,se)))}});import{Box as vC}from"ink";import Za from"react";var yC,Hv,Wv=g(()=>{"use strict";ce();Ph();Uv();yC=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let u=t.context,p=u===re.TICKET||u===re.FIELD_LIST||u===re.FIELD,m=u===re.BOARD||u===re.SWIMLANE,f=u===re.TICKET?t:r.find(T=>T.context===re.TICKET),h=Math.floor(c/3),b=Math.floor(c/Math.max(e.length,1)),I=Math.min(b,h),C=s==="dense";return Za.createElement(vC,{flexDirection:"row",height:i},m&&e.map((T,S)=>{let M=t.id===T.id,L=M?n:-1,F=t.context===re.BOARD&&n===S;return Za.createElement(Lh,{key:T.id,height:i,width:I,swimlane:T,isSelected:F,isDense:C,isFocused:M,listSelectedIndex:L,mode:o})}),p&&f&&Za.createElement(jv,{height:i,ticket:f}))},Hv=Za.memo(yC)});import qv from"node:fs";import bC from"node:path";import xC from"react";import{render as IC}from"ink";import{Writable as EC}from"node:stream";var ci,SC,RC,NC,CC,Gv,zv=g(()=>{"use strict";Wv();ce();N();D();Q();$e();ci=e=>String(e).padStart(2,"0"),SC=e=>{let t=e.getUTCFullYear(),n=ci(e.getUTCMonth()+1),r=ci(e.getUTCDate()),o=ci(e.getUTCHours()),s=ci(e.getUTCMinutes()),i=ci(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},RC=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",NC=async(e,{width:t,height:n})=>{let r="",o=new EC({write(i,c,u){let p=CC(i.toString()).trimEnd();p.trim().length>0&&p.includes("\u256D")&&(r=p),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=IC(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},CC=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Gv=async()=>{let{viewMode:e}=ae(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=v(),i=r.find(S=>S.context==="BOARD");if(!i)return a("No board found to export");let c=120,u=40,p=await NC(xC.createElement(Hv,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(S=>S!==void 0&&Er(S)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:u});if(!p)return a("Failed to render board export");let m=_i(process.cwd());if(l(m))return a("Unable to export, epiq root not found");let f=new Date,h=SC(f),b=`board_${RC(i.title)}_${h}.md`,I=Ip(m.value);qv.mkdirSync(I,{recursive:!0});let C=bC.join(I,b),T=`# Board - ${i.title}
|
|
91
91
|
Date: ${f.toISOString()}
|
|
92
92
|
|
|
93
93
|
\`\`\`text
|
|
94
94
|
${p}
|
|
95
95
|
\`\`\`
|
|
96
|
-
`;return
|
|
96
|
+
`;return qv.writeFileSync(C,T,"utf8"),d("Exported board layout",C)}});import{useSyncExternalStore as z1}from"react";var Vd,AC,wC,qo,TC,fr,el=g(()=>{"use strict";N();AC=new Set,wC=()=>{for(let e of AC)e()},qo=()=>{if(!Vd)throw new Error("Ui state not initialized. Call initUiState() first.");return Vd},TC=e=>{let t=qo();return Vd=e(t),wC(),d("UX state updated",null)},fr=e=>TC(t=>({...t,...e}))});import{ulid as Kd}from"ulid";var Vv,MC,kC,Kv=g(()=>{"use strict";Md();$();$();en();ce();N();So();de();D();Q();Dn();jt();Vv=async e=>{let{contextNode:t,selectedIndex:n}=v(),r=ve(t.id)[n];if(e.modifier===Pt.DESCRIPTION)return kC();if(r&&fs(r))return MC(e);if(e.modifier===Pt.TITLE){let o=fe();if(l(o))return a("Unable to resolve user ID");let s=r;if(!s)return a("Missing node");if(s.readonly)return a("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return a("Provide a title");let c=await xe();return l(c)?c:_([{id:Kd(),action:"edit.title",payload:{id:s.id,name:i},...O(o.value)}],c.value)}return a("Unknown edit command")},MC=async e=>{let t=fe();if(l(t))return a("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=v(),o=ve(n.id)[r];if(!o||!fs(o))return a("Select a comment first");if(o.readonly)return a("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return a("Unable to resolve comment issue");let i=v().nodes[s];if(!i||!U(i))return a("Unable to resolve comment issue");if(i.readonly)return a("Cannot edit readonly issue");let c=o.id.split(":").at(0)??"",u=R.getComment(c);if(!u||u.deleted)return a("Unable to resolve comment");if(u.issue!==i.id)return a("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return a("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let p=e.inputString.trim();if(!p)return a("Provide a comment");let m=await xe();if(l(m))return m;let f=m.value;return _([{id:Kd(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:p},...O(t.value)}],f)},kC=async()=>{let e=fe();if(l(e))return a("Unable to resolve user ID");let t=await xe();if(l(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=v(),s=At([...r,o],"TICKET");if(l(s))return a("Edit target must be an issue");let i=s.value;if(!U(i))return a("Edit target must be an issue");if(i.readonly)return a("Cannot edit readonly issue");let c=ve(i.id).find(f=>f.title===Ae.DESCRIPTION);if(!c)return a("No target found");if(c.readonly)return a("Cannot edit readonly field");let u=i.props.description??"";if(typeof u!="string")return a("Selected field is not editable text");let p=vv(u);if(l(p))return a("Failed to edit field");let m=p.value;return m===u?d("No changes made",null):_([{id:Kd(),action:"edit.description",payload:{id:i.id,md:m},...O(e.value)}],n)}});import Yd from"node:fs";import LC from"node:path";var Yv,Xv=g(()=>{"use strict";N();Bt();Yv=async e=>{let t=LC.join(e,".gitignore"),n=Yd.existsSync(t)?Yd.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
97
97
|
`).map(u=>u.trim()),s=r.filter(u=>!o.some(p=>p===u||p===u.replace(/\/$/,"")||p==="/"+u||p==="/"+u.replace(/\/$/,"")));if(s.length===0)return d("Local epiq paths already ignored",!1);let c=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
98
98
|
`);return n=n.trimEnd()+`
|
|
99
99
|
|
|
100
100
|
${c}
|
|
101
|
-
`,
|
|
102
|
-
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},
|
|
103
|
-
`));let o;try{o=JSON.parse(r.value.stdout)}catch(
|
|
104
|
-
`));let u=
|
|
105
|
-
`,"utf8"),ui.renameSync(m,s)}catch(f){try{ui.rmSync(m,{force:!0})}catch{}return l(`Unable to write ${mi}: ${f instanceof Error?f.message:String(f)}`)}return d("Stored command history",null)}});var HC,cy,WC,dy,qC,uy,my=g(()=>{"use strict";mn();rt();Ke();Ys();Ta();Zc();wa();Zd();lo();jr();$();N();Zt();ge();D();Gs();ee();Ea();HC=e=>e.some(t=>t.action==="init.workspace"),cy=async(e,t)=>{let n=dt(e);return a(n)?l(n.message):gs({cwd:t,branch:n.value})},WC=e=>{let t=Ce(process.cwd());if(a(t))return!1;let n=Ie({repoRoot:t.value});return!a(n)&&n.value===e},dy=async e=>{let t=Ie({repoRoot:e});if(a(t))return So(3,t.message);let n=t.value,r=await ir({repoRoot:e,stateBranchRoot:n,stateBranchName:Ui().stateBranch});if(a(r))return So(3,r.message);let o=sn(n);if(a(o))return So(3,o.message);if(!HC(o.value.events)){let m=await Xs({worktreeRoot:n,operation:"boot pull",fn:()=>Na(n,()=>cy(e,n))});if(a(m)?logger.info(3,m.message):m.value===null?logger.info(3,"Another process holds the state worktree, skipped pull"):a(m.value)&&logger.info(3,m.value.message),o=sn(n),a(o))return So(3,o.message)}let{events:s,unreadable:i}=o.value,c=En(s,i);if(a(c))return So(4,c.message);A({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let u=Rs({root:e});a(u)&&logger.info(u.message);let p=ay({root:e});return a(p)&&logger.info(p.message),Ef(a(p)?[]:p.value),d("Loaded project",void 0)},qC=async e=>{let t=Ie({repoRoot:e});if(a(t))return l(t.message);let n=t.value,r=await Mn({repoRoot:n});if(a(r))return l(r.message);if(!r.value)return d("No remote to pull",void 0);let o=await Xs({worktreeRoot:n,operation:"boot pull",fn:()=>Na(n,()=>(Ro("Pulling"),cy(e,n)))});if(a(o))return je(o.message);if(o.value===null)return d("Another process holds the state worktree",void 0);let s=o.value;if(a(s))return fs(s.message)?(Ia("Offline"),d("Offline",void 0)):je(s.message);if(!s.value)return Ur("Already synced"),d("Already synced",void 0);if(!WC(n))return d("Project changed during the pull",void 0);let i=td(n);return a(i)?i:(Ur("Pulled"),d("Pulled and reloaded",void 0))},uy=e=>{qC(e).then(t=>{a(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${zg(t)}`)})}});import GC from"node:os";import py from"node:path";var zC,VC,fy,gy=g(()=>{"use strict";my();lo();N();ge();D();ee();zC=e=>e==="~"||e.startsWith("~/")?py.join(GC.homedir(),e.slice(1)):e,VC=(e,t)=>{let n=e.trim();if(!n)return l("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?d("Resolved recent project",o.root):l(`No recent project #${n}`)}let r=Ce(py.resolve(zC(n)));return a(r)?l(`No epiq project at ${n}`):d("Resolved project path",r.value)},fy=async()=>{let e=ra();if(ne(""),v().hasProjectDefinition)return l("Already in a project; run epiq from another directory");let t=Wi({exclude:process.cwd()}),n=a(t)?[]:t.value,r=VC(e,n);if(a(r))return l(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(c){return l(`Unable to enter ${o}: ${c instanceof Error?c.message:String(c)}`)}let i=await dy(o);return a(i)?(process.chdir(s),l(i.message)):(uy(o),d(`Opened ${Ip(o)}`,null))}});var nl,eu=g(()=>{"use strict";It();$();$();N();D();nl=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=v(),s=jc(n,t);if(a(s))return l(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=qn();if(a(u))return u;let p=Fn(i),{fatal:m,skipped:f}=tr(p);if(m.length>0)return qn(),A(o),l(m.map(b=>b.message).join(", "));nr(f);let h=v().nodes[e];return h?(H.navigate({contextNode:h,selectedIndex:r}),d("",{unappliedEvents:c})):(qn(),A(o),l("Board did not exist at that date"))}});var hy,vy=g(()=>{"use strict";hy=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 KC,YC,XC,rl,ol,Kr,yy,by,tu=g(()=>{"use strict";lt();pi();$();Bc();Oe();N();vy();D();KC=20,YC=16,XC=150,rl=null,ol=null,Kr=()=>{rl!==null&&(clearInterval(rl),rl=null),ol!==null&&(clearTimeout(ol),ol=null)},yy=()=>{Kr(),A({mode:x.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},by=({events:e,startTime:t,durationMs:n})=>{Kr();let r=e.length,o=as(e.map(f=>br(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=hy(o),c=Math.max(1,Math.round(n*KC/1e3)),u=Math.max(Math.round(n/c),YC),p=0,m=0;A({mode:x.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),rl=setInterval(()=>{p++;let f=p/c,h=[],b,E;for(;m<r&&i[m]<=f;){let w=e[m],R=Hs(w);if(a(R)){if(Io(R)){m++;continue}yy();return}h.push(...Fc(w)),b=w,E=o[m],m++}if(m>=r||p>=c){for(;m<r;m++){let R=Hs(e[m]);if(a(R)&&!Io(R))break}let w=v().replay;A({unappliedEvents:[],replay:w&&{...w,progress:1,appliedCount:r}}),Kr(),ol=setTimeout(yy,XC);return}let S=v().replay;A({unappliedEvents:e.slice(m),replay:{progress:Math.min(1,f),appliedCount:m,totalCount:r,startTime:t,endTime:s,currentTime:b?E??S?.currentTime??t:S?.currentTime??t,currentLabel:b?nu(b):S?.currentLabel??"",flashNodeIds:b?[...new Set(h)]:S?.flashNodeIds??[]}})},u)}});var xy,Iy=g(()=>{"use strict";rt();lt();$();$();Oe();Xt();N();ge();D();Cs();eu();tu();xy=async()=>{let e=Ct(v().breadCrumb,"BOARD");if(a(e))return e;let t=await kt(process.cwd());if(a(t))return l("Unable to locate repo root");let n=Ie({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=fe().commandMeta;if(Kr(),r==="now"){let c=Br(n.value);if(a(c))return l(c.message);let u=qn();if(a(u))return u;let p=Fn(c.value),{fatal:m,skipped:f}=tr(p);return m.length>0?l(m.map(h=>h.message).join(", ")):(nr(f),A({mode:x.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),d("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let c=Uc(n.value);if(a(c))return c;let u=r==="prev"?v().eventLog.at(-1):v().unappliedEvents.at(0),p=u===void 0?null:br(u),m=(u===void 0?null:c.value.get(u.id)??null)??(p===null?null:is(p));if(m===null)return l(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?m:m+1}else{let c=Tr(r||o.trim());if(!c)return l("Invalid peek date");s=c.getTime()}let i=nl({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(i)?i:(A({mode:x.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),d("Peeking",!0))}});var Ey,Ry=g(()=>{"use strict";rt();Xt();N();ge();D();Cs();eu();tu();Ey=async()=>{let e=Ct(v().breadCrumb,"BOARD");if(a(e))return e;let t=await kt(process.cwd());if(a(t))return l("Unable to locate repo root");let n=Ie({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=fe().commandMeta,{dateInput:s,durationInput:i}=Yi(r,o);if(Kr(),v().syncStatus.status==="syncing")return l("Cannot replay while syncing, try again in a moment");let c=Tr(s);if(!c)return l("Invalid replay date");let u=i?Ki(i):15e3;if(u===null)return l("Invalid replay duration (try e.g. 30s or 2m)");let p=c.getTime(),m=v(),f=nl({boardId:e.value.id,targetTime:p,stateBranchRoot:n.value,selectedIndex:-1});if(a(f))return f;let{unappliedEvents:h}=f.value;return h.length===0?(qn(),A(m),d("Nothing to replay from that point",!0)):(by({events:h,startTime:p,durationMs:u}),d("Replaying board history",!0))}});import{spawn as QC}from"node:child_process";var ZC,Sy,Ny=g(()=>{"use strict";N();ZC=()=>{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"]}}},Sy=async e=>new Promise(t=>{let{command:n,args:r}=ZC();try{let o=QC(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(l(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?d("Copied to clipboard",null):l(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(l(`Clipboard tool not available (${n})`))}})});var fi,Cy,wy=g(()=>{"use strict";N();D();Ny();ft();uo();Pn();fi=async(e,t)=>{if(!e.trim())return l(`Nothing to copy: ${t} is empty`);let n=await Sy(e);return a(n)?n:d(`Copied ${t} to clipboard`,null)},Cy=async e=>{let{breadCrumb:t,selectedNode:n}=v(),r=ws({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return l("Nothing selected to copy from");switch(e.modifier){case He.REF:return fi(V(o.id),"ref");case He.TITLE:return fi(o.title,"title");case He.DESCRIPTION:return r?fi(r.props?.description??"","description"):l("No issue in scope");case He.TAGS:{if(!r)return l("No issue in scope");let s=hn(r).map(({name:i})=>i);return fi(s.join(", "),"tags")}case He.ASSIGNEES:{if(!r)return l("No issue in scope");let s=vn(r).map(({name:i})=>i);return fi(s.join(", "),"assignees")}default:return l("Yank one of: ref, title, description, tags, assignees")}}});var Ay,Ty=g(()=>{"use strict";Ta();Oe();N();ge();D();Ay=async()=>{ne(""),A({mode:x.DEFAULT});let e=ke();if(a(e))return l(e.message);if(e.value.syncStatus.status==="syncing")return l("Sync already in progress");A({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Aa();return a(t)?(A({syncStatus:{msg:t.message,status:"failed"}}),t):(A({mode:x.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as ky}from"ulid";var My,Ly=g(()=>{"use strict";$();$();me();N();D();_a();ee();$t();My=async()=>{let e=he();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=be(t.id)[n];if(!r)return l("Unable to resolve child to delete");let o=await Ee();if(a(o))return o;if(r.context==="COMMENT"){let s=r.id,i=U(t)?t.id:t.parentNodeId;if(!i)return l("Unable to resolve comment issue");let c=v().nodes[i];if(!c||!U(c))return l("Unable to resolve comment issue");let u=c.log?.filter(Ph).find(p=>p.payload.id===s);return u?u.payload.author!==e.value.userId?l("You can only delete your own comments"):_([{id:ky(),action:"delete.issue.comment",payload:{id:s,issue:i},...O(e.value)}],o.value):l("Unable to resolve comment")}return _([{id:ky(),action:"delete.node",payload:{id:r.id},...O(e.value)}],o.value)}});import{ulid as ew}from"ulid";var Py,Dy=g(()=>{"use strict";$();$();tn();me();N();jt();D();ee();Bt();Py=async()=>{let e=he();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=be(t.id)[n];if(!r)return l("Unable to close issue, no target found");if(!U(r))return l("Cannot close in this context");let o=v().nodes[we];if(!o)return l("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return l("Issue is already closed");let s=await Ee();if(a(s))return s;let i=s.value,c=xn(o.id,r.id,{at:"end"},e.value,i);if(a(c))return c;let u=_([{id:ew(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...O(e.value)}],i);return a(u)?u:d("Issue closed",null)}});var sl,ru=g(()=>{"use strict";sl=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{ulid as tw}from"ulid";var Oy,_y=g(()=>{"use strict";$();$();ru();tn();me();N();pe();jt();D();ee();Bt();Oy=async()=>{let e=he();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=be(t.id)[n];if(!r)return l("Unable to reopen issue, no target found");let o=r.context==="TICKET"?d("Resolved ticket",r):zt(r.id,"TICKET");if(a(o))return l("Cannot reopen in this context");let s=o.value,i=v().nodes[we];if(!i)return l("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return l("Issue is not closed");if(!U(s))return l("Target node is not issue");let c=sl(s);if(!c)return l("Unable to resolve previous parent from issue history");if(c===i.id)return l("Previous parent resolves to closed swimlane");let u=v().nodes[c];if(!u)return l("Previous parent no longer exists");let p=await Ee();if(a(p))return p;let m=p.value,f=xn(u.id,s.id,{at:"end"},e.value,m);if(a(f))return f;let h=_([{id:tw(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...O(e.value)}],m);return a(h)?h:d("Issue reopened",null)}});import{ulid as nw}from"ulid";var Fy,By=g(()=>{"use strict";$();$();N();ge();D();ee();Bt();Fy=async()=>{let e=he();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=be(t.id)[n];if(!r)return l("Missing node");if(r.readonly)return l("Cannot rename readonly node");let o=ra();if(!o)return l("Provide a title");let s=await Ee();return a(s)?s:_([{id:nw(),action:"edit.title",payload:{id:r.id,name:o},...O(e.value)}],s.value)}});import{ulid as rw}from"ulid";var $y,jy=g(()=>{"use strict";pe();$();$();me();N();ge();D();ee();Bt();$y=async()=>{let e=he();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=fe().commandMeta,r=(t||n).trim();if(!r)return l("Provide a tag");let o=C.findTagByName(r);if(!o)return l(`Tag "${r}" does not exist`);let{selectedNode:s}=v();if(!s)return l("Invalid untag target");let i=zt(s.id,"TICKET");if(a(i))return l("Unable to untag issue in this context");let c=i.value;if(!U(c))return l("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return l("Issue is not tagged with that tag");let p=await Ee();return a(p)?p:_([{id:rw(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...O(e.value)}],p.value)}});import{ulid as ou}from"ulid";var Uy,Hy=g(()=>{"use strict";pe();$();$();me();N();ge();D();ee();Bt();Uy=async()=>{let e=he();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=fe().commandMeta,r=(t||n).trim();if(!r)return l("Provide a tag");let{selectedNode:o}=v();if(!o)return l("Invalid tag target");let s=zt(o.id,"TICKET");if(a(s))return l("Unable to tag issue in this context");let i=s.value;if(!U(i))return l("Target node is not issue");let c=await Ee();if(a(c))return c;let u=C.findTagByName(r),p=u?.id??ou();return(i.props.tags??[]).includes(p)?l("Already tagged with that tag"):_([...u?[]:[{id:ou(),action:"create.tag",payload:{id:p,name:r},...O(e.value)}],{id:ou(),action:"add.issue.tag",payload:{id:i.id,tag:p},...O(e.value)}],c.value)}});var gi,Wy,il=g(()=>{"use strict";wt();Tn();gi=({events:e,registry:t,logFileNames:n})=>{let r=new Map(n),o=new Set;for(let s of e)s.userId&&(r.has(s.userId)||r.set(s.userId,""),o.add(s.userId));for(let s of Object.values(t))r.set(s.id,s.name);return[...r.entries()].map(([s,i])=>({id:s,name:i,isExternal:!o.has(s)}))},Wy=({authorName:e,authorEmail:t,owners:n,registry:r})=>{let o=Ve(t),s=n.get(o),i=s?r[s]:void 0;return s?{...ht(s,i?.name),resolved:!0}:{...ht(o||e,e),resolved:!1}}});var al,su=g(()=>{"use strict";$();il();D();al=e=>{let{eventLog:t=[],contributors:n}=v();return gi({events:t,registry:n,logFileNames:Fr(e)})}});import{ulid as iu}from"ulid";var qy,Gy=g(()=>{"use strict";$();$();me();N();pe();ge();D();su();ee();Bt();qy=async()=>{let e=he();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=fe().commandMeta,r=(t||n).trim();if(!r)return l("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return l("Provide an assignee");let{selectedIndex:i,contextNode:c}=v(),u=be(c.id)[i];if(!u)return l("Invalid assign target");let p=zt(u.id,"TICKET");if(a(p))return l("Unable to assign issue in this context");let m=p.value;if(!U(m))return l("Target node is not issue");let f=await Ee();if(a(f))return f;let h=al(f.value),b=!o&&s.toLowerCase()==="me",E,S;if(b)E=e.value.userId,S=h.find(k=>k.id===E)?.name??e.value.userName;else{let k=h.filter(F=>F.name===s);if(k.length>1)return l(`"${s}" matches ${k.length} contributors (${k.map(F=>F.id).join(", ")}). Assign from the GUI to choose by id.`);let M=k[0];if(!M&&!o)return l(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);E=M?.id??iu(),S=M?.name??s}if((m.props.assignees??[]).includes(E))return l("Assignee already assigned");let R=!!v().contributors[E];return _([...R?[]:[{id:iu(),action:"create.contributor",payload:{id:E,name:S},...O(e.value)}],{id:iu(),action:"add.issue.assignee",payload:{id:m.id,assignee:E},...O(e.value)}],f.value)}});import{ulid as ow}from"ulid";var zy,Vy=g(()=>{"use strict";$();$();me();N();pe();ge();D();su();ee();Bt();zy=async()=>{let e=he();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=fe().commandMeta,r=(t||n).trim();if(!r)return l("Provide an assignee to remove");let{selectedNode:o}=v();if(!o)return l("Invalid unassign target");let s=zt(o.id,"TICKET");if(a(s))return l("Unable to unassign in this context");let i=s.value;if(!U(i))return l("Target node is not issue");let c=i.props.assignees??[],u=r.toLowerCase()==="me",p=await Ee();if(a(p))return p;let m=u?c.filter(h=>h===e.value.userId):al(p.value).filter(h=>h.name===r&&c.includes(h.id)).map(h=>h.id);if(m.length>1)return l(`"${r}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let f=m[0];return f?_([{id:ow(),action:"remove.issue.assignee",payload:{id:i.id,assignee:f},...O(e.value)}],p.value):l(u?"Issue is not assigned to you":`Issue is not assigned to "${r}"`)}});import{ulid as Ky}from"ulid";var sw,Yy,Xy=g(()=>{"use strict";$();$();Xt();me();N();pe();D();On();ee();Bt();Ha();Ya();Fa();sw=e=>{let t=e.trim(),n=ur(),r=n?lv(t):null;if(!n||!r)return{ok:!0,md:t,anchored:!1};let o=Ka();if(!o||o.sha!==n)return{ok:!1,reason:"No diff is open"};let s=cv(o.rows,Math.max(0,v().selectedIndex));if(!s)return{ok:!1,reason:"That line is not in a file"};let i=dv(o.rows,s,r.start,r.end);return i.ok?{ok:!0,anchored:!0,md:qh({filePath:i.value.filePath,start:i.value.start,end:i.value.end,side:"additions",endSide:"additions",note:r.note,sha:n,snippet:i.value.snippet})}:{ok:!1,reason:i.reason}},Yy=async e=>{let t=sw(e.inputString);if(!t.ok)return l(t.reason);let{md:n,anchored:r}=t;if(!n)return l("Provide a comment");if(n.length>4e3)return l(r?`The note and the ${n.length} characters of quoted lines exceed ${4e3}; comment on fewer lines`:`Cannot exceed ${4e3} characters`);let o=he();if(a(o))return l("Unable to resolve user ID");let{breadCrumb:s,selectedNode:i}=v(),c=Ct([...s,i],"TICKET");if(a(c))return l("Edit target must be an issue");let u=c.value;if(!u)return l("Invalid comment target");let p=u.context==="TICKET"?d("Resolved ticket",u):zt(u.id,"TICKET");if(a(p))return l("Unable to comment on issue in this context");let m=p.value;if(!U(m))return l("Target node is not issue");let f=await Ee();if(a(f))return f;let h=await _([{id:Ky(),action:"add.issue.comment",payload:{id:Ky(),issue:m.id,author:o.value.userId,md:n},...O(o.value)}],f.value);return r&&!a(h)&&Gr(null),h}});var Jy,iw,Qy,ll,au=g(()=>{"use strict";Sr();N();Ue();bn();Jy=e=>e.userName?.trim()?e.preferredEditor?.trim()?null:"no editor configured":"no username configured",iw=e=>{let t=Xn();return a(t)?Jy({userName:e.userName,preferredEditor:e.preferredEditor})??t.message:Jy(t.value)},Qy=()=>{let e=yn();return a(e)?l(e.message):d("Read auto sync settings",{enabled:e.value.autoSync===!0,intervalMs:Li(e.value.autoSyncDebounceMs),blockedReason:iw(e.value)})},ll=e=>{let t=e.intervalMs===void 0?void 0:ro(e.intervalMs);if(e.intervalMs!==void 0&&t===null)return l(`Auto sync interval must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=Qy();if(a(n))return n;let r=xt({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncDebounceMs:t}});if(a(r))return l(r.message);ut({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncIntervalMs:t}});let o=Qy();return a(o)?d("Changed auto sync settings",{...n.value,...e.enabled===void 0?{}:{enabled:e.enabled},...t==null?{}:{intervalMs:t}}):o}});var Zy,eb=g(()=>{"use strict";Sr();au();N();ge();Zy=()=>{let e=fe().commandMeta.inputString,t=ro(e);if(t===null)return l(`Auto sync duration must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=ll({intervalMs:t});return a(n)?n:d(`Auto sync interval set to ${t}ms`,null)}});var tb,nb=g(()=>{"use strict";wr();au();N();ge();tb=()=>{let e=fe().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return l("Invalid response");let t=Lp(e),n=ll({enabled:t===!0});return a(n)?n:d(`Auto sync set to "${e}"`,null)}});var lu,rb,ob,aw,lw,hi,cl,dl=g(()=>{"use strict";Ke();wt();N();hd();lu=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=2),rb="",ob=new Map,aw=15e3,lw=async(e,t)=>{let n=`${e} ${t??""}`,r=ob.get(n);if(r&&Date.now()-r.at<$a(aw))return d("Cached author scan",r.authors);let o=await Le({cwd:e,args:["log","--branches",...t?["--not",t]:[],`--format=%an${rb}%ae`]});if(o.exitCode!==0)return l(`Could not read this repository's history: ${(o.stderr??"").trim()||`git exited ${o.exitCode}`}`);let s=new Map;for(let i of(o.stdout??"").split(`
|
|
106
|
-
`)){let c=i.lastIndexOf(rb);if(c===-1)continue;let u=i.slice(0,c),p=Ve(i.slice(c+1));if(!zn(p))continue;let m=s.get(p)??{names:new Set,commits:0};u&&m.names.add(u),m.commits+=1,s.set(p,m)}return ob.set(n,{at:Date.now(),authors:s}),d("Scanned repository authors",s)},hi=async({repoRoot:e,stateBranch:t,names:n,links:r})=>{let o=await lw(e,t);if(a(o))return l(o.message);let s=o.value,i=new Map;for(let u of Object.values(r)){if(u.tombstoned)continue;let p=i.get(u.email)??new Set;p.add(u.contributor),i.set(u.email,p)}let c=new Set(n.flatMap(u=>lu(u??"")));return d("Found candidates",[...s.entries()].map(([u,p])=>({email:u,names:[...p.names],commits:p.commits,looksLikeYours:[...p.names].some(m=>lu(m).some(f=>c.has(f)))||lu(u.split("@")[0]??"").some(m=>c.has(m)),claimedBy:[...i.get(u)??[]]})).sort((u,p)=>u.looksLikeYours===p.looksLikeYours?p.commits-u.commits:Number(p.looksLikeYours)-Number(u.looksLikeYours)))},cl=e=>e.filter(t=>t.claimedBy.length===0)});import{ulid as cw}from"ulid";var sb,ib,ab=g(()=>{"use strict";$();mn();rt();wt();N();Oe();dl();ge();Ss();Ue();D();bn();wr();ee();sb=()=>{let e=nc();if(!e)return d("Nothing here to decline",null);let t=yn(),n=a(t)?[]:t.value.declinedEmailBoards??[],r=[...new Set([...n,e])],o=xt({declinedEmailBoards:r});return a(o)?l(o.message):(ut({declinedEmailBoards:[...new Set([...de().declinedEmailBoards??[],e])]}),d("Declined",null))},ib=async()=>{let e=fe().commandMeta.inputString.trim();if(e==="none"){let w=sb();return a(w)?w:d("Left unlinked. Your commits will show the name git signed them with. Run :config emails again to change that.",null)}let{userId:t,userName:n,gitName:r}=de();if(!t)return l("Set a username first with :config username");let o=ke();if(a(o))return l("Board is not loaded");let s=Ce(process.cwd());if(a(s))return l(s.message);let i=dt(s.value),c=await hi({repoRoot:s.value,stateBranch:a(i)?void 0:i.value,names:[n,r],links:o.value.emailLinks});if(a(c))return c;let p=cl(c.value);if(Ap(p.map(w=>w.email)),p.length===0){if(!kp()){let w=sb();if(a(w))return w}return d("No unclaimed addresses in this history.",null)}if(!e)return A({mode:x.IDENTITY}),d("Opened identity",null);let m=e.split(/[,\s]+/).filter(Boolean),f=[],h=[];for(let w of m){let R=p.find(k=>k.email===Ve(w));if(!R){h.push(w);continue}f.includes(R)||f.push(R)}if(h.length>0)return l(`Not on the list: ${h.join(", ")}. Pick one of ${p.map(w=>w.email).join(", ")}.`);let b=Ie({repoRoot:s.value});if(a(b))return b;let E=f.map(w=>({id:cw(),action:"link.contributor.email",payload:{contributor:t,email:w.email},userId:t})),S=_(E,b.value);return a(S)?l(S.message):d(`Claimed ${f.map(w=>w.email).join(", ")}. Every commit by ${f.length===1?"that address":"those addresses"} is now yours.`,null)}});import{ulid as dw}from"ulid";var lb,cb=g(()=>{"use strict";$();rt();wt();N();ge();Ue();D();ee();lb=()=>{let e=fe().commandMeta.inputString.trim(),{userId:t}=de();if(!t)return l("Set a username first with :config username");let n=ke();if(a(n))return l("Board is not loaded");let r=Vn(n.value.emailLinks,t);if(r.length===0)return l("You have not claimed any addresses.");if(!e)return l(`Which one? ${r.join(", ")}.`);let o=r.find(u=>u===Ve(e));if(!o)return l(`You have not claimed ${e}. Yours: ${r.join(", ")}.`);let s=Ce(process.cwd());if(a(s))return s;let i=Ie({repoRoot:s.value});if(a(i))return i;let c=_([{id:dw(),action:"unlink.contributor.email",payload:{contributor:t,email:o},userId:t}],i.value);return a(c)?l(c.message):d(`Unclaimed ${o}`,null)}});var db,ub=g(()=>{"use strict";bn();N();ge();Ue();db=()=>{let e=fe().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return l("Invalid response");let n=xt({logLevel:e});return a(n)?n:(ut({logLevel:e}),d(`Auto sync set to "${e}"`,null))}});import{ulid as uw}from"ulid";var mb,pb=g(()=>{"use strict";yr();bn();N();Ue();Pn();eb();fc();nb();ab();cb();ub();mb=e=>{let t=e.inputString.trim();switch(e.modifier){case ye.USERNAME:{if(process.env[Ot])return l(`Cannot change the configured user while ${Ot} names this process`);let n=yn();if(a(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,c=r||uw();if(!i||!c)return l("Unable to resolve user name or id");let u=xt({userName:i,userId:c,preferredEditor:o??""});return a(u)?u:(ut({userName:i,userId:c}),d(`Username set to "${i}"`,null))}case ye.EDITOR:{if(!t)return l("No editor provided");let n=xt({preferredEditor:t});return a(n)?n:(ut({preferredEditor:t}),d(`Editor configuration set to "${t}"`,null))}case ye.VIEW:{if(t!=="wide"&&t!=="dense")return l("Invalid view mode");let n=xt({viewMode:t});return a(n)?n:(ut({viewMode:t}),d(`View set to "${t}"`,null))}case ye.EMAILS:return ib();case ye.EMAILS_UNCLAIM:return lb();case ye.AUTOSYNC:return tb();case ye.LOG_LEVEL:return db();case ye.SYNC_DEBOUNCE_MS:return Zy();case ye.ATTACHMENT_MAX_KB:return Qp();default:return l("Unknown config command")}}});var cu,fb=g(()=>{"use strict";wr();Oe();ge();D();cu=()=>{let e=Pp(),t=v().mode;if(!(t!==x.COMMAND_LINE&&t!==x.DEFAULT)){if(!e){A({mode:x.DEFAULT});return}A({mode:x.COMMAND_LINE}),ne(e)}}});var gb,hb=g(()=>{"use strict";Wv();It();Oe();N();ge();D();Qa();Ar();sd();Pn();Gv();Yv();ny();oy();gy();Iy();Ry();wy();Ty();Ly();Dy();_y();By();jy();Hy();Gy();Vy();Xy();pb();fb();gb=[{systemOnly:!0,intent:G.Move,description:"Internal move-state command",mode:x.COMMAND_LINE,action:ty},{intent:G.Delete,description:"Delete the currently selected node",mode:x.COMMAND_LINE,action:My,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:x.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=fe().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>We(I.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return l("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return Pe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:x.DEFAULT})),d("Filter updated",null)}},{intent:G.ViewHelp,description:"Open the help screen",mode:x.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return mr({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),A({mode:x.HELP}),d("Viewing help",null)}},{intent:G.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:x.COMMAND_LINE,action:Py,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:x.COMMAND_LINE,action:Oy,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.Init,description:"Initialize Epiq in the current git repository",mode:x.COMMAND_LINE,action:Kv,onSuccess:cu},{intent:G.OpenProject,description:"Open a recently used epiq project, by number or path",mode:x.COMMAND_LINE,action:fy,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.NewItem,description:"Create a new board, swimlane, or issue",mode:x.COMMAND_LINE,action:ry,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.Rename,description:"Rename the currently selected node",mode:x.COMMAND_LINE,action:Fy,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.UntagTicket,description:"Remove a tag from the selected issue",mode:x.COMMAND_LINE,action:$y,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.TagTicket,description:"Add or create a tag on the selected issue",mode:x.COMMAND_LINE,action:Uy,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.AssignUserToTicket,description:"Assign a user to the selected issue",mode:x.COMMAND_LINE,action:qy,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:x.COMMAND_LINE,action:zy,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.Comment,description:"Add a comment to the selected issue",mode:x.COMMAND_LINE,action:async(e,t)=>Yy(t),onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.Sync,description:"Pull, commit, and push Epiq state",mode:x.COMMAND_LINE,action:Ay},{intent:G.Peek,description:"View board state at another point in time",mode:x.COMMAND_LINE,action:xy},{intent:G.Replay,description:"Replay board history forward from a point in time",mode:x.COMMAND_LINE,action:Ey},{intent:G.Export,description:"Export the current board layout to markdown",mode:x.COMMAND_LINE,action:async()=>{let e=await Hv();return a(e)?e:(A({mode:x.DEFAULT}),d("Export successful",!0))}},{intent:G.Exit,description:"Exit the application",mode:x.COMMAND_LINE,action:async()=>(H.exit(),d("Exit successful",!0))},{intent:G.Edit,description:"Edit title or description",mode:x.COMMAND_LINE,action:async(e,t)=>qv(t),onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:x.COMMAND_LINE,action:async(e,t)=>Cy(t),onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:x.COMMAND_LINE,action:(e,t)=>mb(t),onSuccess:cu}]});var mw,Vt,du=g(()=>{"use strict";hh();Zi();sd();hb();Zd();N();ge();Ue();D();mw=new Set(["peek","replay","filter","view-help","yank"]),Vt=async({isForceExecutedBySystem:e=!1}={})=>{let{value:t,commandMeta:{command:n,validity:r,modifier:o,inputString:s}}=fe();if(!n)return l("No command to confirm");if(!e&&r===Qn.Invalid)return l("Invalid command");let i=vh(n);xf();let{readOnly:c}=v();if(c&&!mw.has(i))return Ls({status:An.Fail,message:"Command not available in readonly state",value:null});let u=gb.filter(f=>e||f.systemOnly!==!0).find(f=>f.intent===i);if(!u)return Ls({status:An.Fail,message:"Command not found",value:null});let p;try{p=await u.action(u,{command:n,inputString:s,modifier:o})}catch(f){return Ls({status:An.Fail,message:f instanceof Error?f.message:"Command failed",value:null})}if(a(p))return Ls(p);let m=!e;if(If({addToHistory:m,line:t}),m){let f=ly({commands:fe().commandHistory});a(f)&&logger.info(f.message)}return u.onSuccess?.(),de().autoSync&&gh(),p}});var ul,ml,vb,yb=g(()=>{"use strict";N();Oe();D();Kn();du();Jd();ge();ul=[{intent:P.Exit,mode:x.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(A({mode:x.COMMAND_LINE}),ne("move cancel"),Vt({isForceExecutedBySystem:!0}))},{intent:P.InitMove,mode:x.DEFAULT,description:"[m] move",action:()=>(A({mode:x.COMMAND_LINE}),ne("move start"),Vt({isForceExecutedBySystem:!0}))},{intent:P.ConfirmMove,mode:x.MOVE,description:"[m] confirm move",action:()=>(A({mode:x.COMMAND_LINE}),ne("move confirm"),Vt({isForceExecutedBySystem:!0}))}],ml=[{intent:P.MovePreviousItem,mode:x.MOVE,action:()=>ln()?(A({mode:x.COMMAND_LINE}),ne("move previous"),Vt({isForceExecutedBySystem:!0})):l("No pending move")},{intent:P.MoveNextItem,mode:x.MOVE,description:"[arrows/hjkl] move (shift x5)",action:()=>ln()?(A({mode:x.COMMAND_LINE}),ne("move next"),Vt({isForceExecutedBySystem:!0})):l("No pending move")},{intent:P.MovePreviousItemJump,mode:x.MOVE,action:()=>ln()?(A({mode:x.COMMAND_LINE}),ne("move jump-previous"),Vt({isForceExecutedBySystem:!0})):l("No pending move")},{intent:P.MoveNextItemJump,mode:x.MOVE,action:()=>ln()?(A({mode:x.COMMAND_LINE}),ne("move jump-next"),Vt({isForceExecutedBySystem:!0})):l("No pending move")}],vb=[{intent:P.MoveToNextContainer,mode:x.MOVE,action:()=>ln()?(A({mode:x.COMMAND_LINE}),ne("move to-next"),Vt({isForceExecutedBySystem:!0})):l("No pending move")},{intent:P.MoveToPreviousContainer,mode:x.MOVE,action:()=>ln()?(A({mode:x.COMMAND_LINE}),ne("move to-previous"),Vt({isForceExecutedBySystem:!0})):l("No pending move")}]});var bb,xb=g(()=>{"use strict";me();yb();bb={[ie.WORKSPACE]:[...ul,...ml],[ie.BOARD]:[...ul,...ml],[ie.SWIMLANE]:[...ul,...ml,...vb],[ie.TICKET]:[],[ie.FIELD]:[],[ie.FIELD_LIST]:[],[ie.TEXT]:[],[ie.COMMENT]:[]}});import{spawn as pw}from"node:child_process";function Ib(e){let t=process.platform,o=pw(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 Eb=g(()=>{"use strict"});import fw from"node:fs";import gw from"node:path";var Rb,Sb=g(()=>{"use strict";rt();fo();N();ee();Eb();Rb=e=>{let t=Ce(process.cwd());if(a(t))return l("Unable to resolve project root");let n=Ie({repoRoot:t.value});if(a(n))return l(n.message);let r=po(e.hash,e.ext),o=gw.join($i(n.value),r);return fw.existsSync(o)?(Ib(o),d(`Opened ${e.name}`,null)):l("Attachment file not found \u2014 run :sync to fetch it")}});var Nb,Cb,wb=g(()=>{"use strict";Oe();N();ge();D();Qa();Kn();It();Nb=()=>{ne("");let{pendingNavTarget:e}=Ho();A({mode:x.DEFAULT}),e&&H.navigate(e),mr({pendingNavTarget:void 0})},Cb=[{intent:P.ExitCommandLine,mode:x.HELP,action:()=>(Nb(),d("Exiting help",null))},{intent:P.Exit,mode:x.HELP,action:()=>(Nb(),d("Closed help",null))},{intent:P.NavPreviousItem,mode:x.HELP,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(H.navigateToPreviousItem(),d("Navigating to previous help item",null))},{intent:P.NavNextItem,mode:x.HELP,action:()=>(H.navigateToNextItem(),d("Navigating to next help item",null))},{intent:P.NavPreviousItemJump,mode:x.HELP,action:()=>(H.jumpToPreviousItem(),d("Jumping to previous help item",null))},{intent:P.NavNextItemJump,mode:x.HELP,action:()=>(H.jumpToNextItem(),d("Jumping to next help item",null))},{intent:P.NavToPreviousContainer,mode:x.HELP,action:()=>(H.navigateToPreviousContainer(),d("Navigating to previous help container",null))},{intent:P.NavToNextContainer,mode:x.HELP,action:()=>(H.navigateToNextContainer(),d("Navigating to next help container",null))}]});var Ab,Tb,kb=g(()=>{"use strict";Oe();N();ge();Ss();D();Kn();Ab=()=>{ne(""),A({mode:x.DEFAULT})},Tb=[{intent:P.Confirm,mode:x.IDENTITY,description:"[enter] claim the first",action:()=>{let[e]=co();return e?(A({mode:x.COMMAND_LINE}),ne(`config emails ${e}`),d("Proposed claim",null)):d("Nothing left to claim",null)}},{intent:P.ExitCommandLine,mode:x.IDENTITY,action:()=>(Ab(),d("Closed identity",null))},{intent:P.Exit,mode:x.IDENTITY,description:"[esc] close",action:()=>(Ab(),d("Closed identity",null))}]});var hw,Mb,Lb,Pb=g(()=>{"use strict";Oe();me();N();ge();D();Qa();Kn();It();hw=e=>{A({mode:x.COMMAND_LINE});let{pendingNavTarget:t}=Ho();t&&H.navigate(t),mr({pendingNavTarget:void 0}),ne(`${e} `)},Mb=()=>{ne("");let{pendingNavTarget:e}=Ho();e&&H.navigate(e),mr({pendingNavTarget:void 0}),A({mode:x.DEFAULT})},Lb=[{intent:P.InitCommandPalette,mode:x.DEFAULT,description:"[?] command palette",action:()=>{ne("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return mr({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),A({mode:x.PALETTE}),d("Opening command palette",null)}},{intent:P.Confirm,mode:x.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!Lm(e))return l("Command only applicable on text nodes");if(e.props.disabled)return l("Command is not available in this context");let t=e.title;return t?(hw(t),d("Selected command",t)):d("No command selected",null)}},{intent:P.ExitCommandLine,mode:x.PALETTE,action:()=>(Mb(),d("Exiting palette",null))},{intent:P.Exit,mode:x.PALETTE,action:()=>(Mb(),d("Closed command palette",null))},{intent:P.NavPreviousItem,mode:x.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(H.navigateToPreviousItem(),d("Navigating to previous item",null))},{intent:P.NavNextItem,mode:x.PALETTE,action:()=>(H.navigateToNextItem(),d("Navigating to next item",null))},{intent:P.NavToPreviousContainer,mode:x.PALETTE,action:()=>(H.navigateToPreviousContainer(),d("Navigating to previous container",null))},{intent:P.NavToNextContainer,mode:x.PALETTE,action:()=>(H.navigateToNextContainer(),d("Navigating to next container",null))}]});var Db,Ob,_b=g(()=>{"use strict";Ar();Pn();ii();Ha();Oe();N();Ya();Eo();pe();jt();ge();D();Sb();Kn();Jn();wb();kb();Pb();It();Db=()=>{let e=ur();if(!e)return d("Nothing to comment on here",null);let t=Ka();if(!t||t.sha!==e)return l("The diff is still loading");let{selectedIndex:n}=v(),r=Math.max(0,n),o=Rd(t.rows,Od(e)??r,r);return o.ok?(A({mode:x.COMMAND_LINE}),ne(`${I.COMMENT} ${av(o.value.start,o.value.end)} `),d("Commenting on a diff line",null)):l(o.reason)},Ob=[{intent:P.InitCommandLine,mode:x.DEFAULT,description:"[:] write command",action:()=>(A({mode:x.COMMAND_LINE}),ne(""),d("Entering command line mode",null))},...Cb,...Tb,...Lb,{intent:P.AddItem,mode:x.DEFAULT,description:"[n] new...",action:()=>(A({mode:x.COMMAND_LINE}),ne(`${I.NEW} `),d("Adding new item",null))},{intent:P.Delete,mode:x.DEFAULT,description:"[d] delete",action:()=>(A({mode:x.COMMAND_LINE}),ne(`${I.DELETE} `),d("Deleting item",null))},{intent:P.Confirm,mode:x.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!Me(e?.id??"")?.length){let r=e?C.getAttachment(e.id):void 0;if(r)return Rb(r);if(ur())return Db();if(e?.title===Ae.DESCRIPTION)return A({mode:x.COMMAND_LINE}),ne(`${I.EDIT} description `),d("Propose command",!0);if(e?.title===Ae.ASSIGNEES)return A({mode:x.COMMAND_LINE}),ne(`${I.ASSIGN} `),d("Propose command",!0);if(e?.title===Ae.TAGS)return A({mode:x.COMMAND_LINE}),ne(`${I.TAG} `),d("Propose command",!0);if(t.title===Ae.DESCRIPTION&&e?.context==="TEXT")return A({mode:x.COMMAND_LINE}),ne(`${I.EDIT} description `),d("Propose command",!0)}return H.enterChildNode(),d("Entering context",null)}},{intent:P.OpenInEditor,mode:x.DEFAULT,action:()=>{let{selectedNode:e,contextNode:t}=v(),n=t.parentNodeId,o=!!n&&t.id===Te(n,"diff")?e?.id:ur()??void 0;return o?Md({sha:o}):d("Nothing here opens in an editor",null)}},{intent:P.MarkDiffLine,mode:x.DEFAULT,action:()=>{let e=ur();if(!e)return d("Nothing to mark here",null);let{selectedIndex:t}=v(),n=Od(e);return Gr(n===t?null:{sha:e,row:Math.max(0,t)}),d("Marked diff line",null)}},{intent:P.CommentOnDiffLine,mode:x.DEFAULT,action:()=>ur()?Db():d("Nothing to comment on here",null)},{intent:P.Yank,mode:x.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=v(),t=e?.title===Ae.DESCRIPTION?He.DESCRIPTION:e?.title===Ae.TAGS?He.TAGS:e?.title===Ae.ASSIGNEES?He.ASSIGNEES:He.REF,r=We(I.YANK).includes(t)?t:He.REF;return A({mode:x.COMMAND_LINE}),ne(`${I.YANK} ${r}`),d("Propose command",!0)}},{intent:P.EditTitle,mode:x.DEFAULT,description:"[r] rename title",action:()=>(A({mode:x.COMMAND_LINE}),ne(`${I.EDIT} title ${v().selectedNode?.title}`),d("Exiting context",null))},{intent:P.EditDescription,mode:x.DEFAULT,description:"[e] edit desc",action:()=>(A({mode:x.COMMAND_LINE}),ne(`${I.EDIT} description `),d("Exiting context",null))},{intent:P.Exit,mode:x.DEFAULT,description:"[q] exit context",action:()=>(H.enterParentNode(),d("Exiting context",null))},{intent:P.NavPreviousItem,mode:x.DEFAULT,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(H.navigateToPreviousItem(),d("Navigating to previous item",null))},{intent:P.NavNextItem,mode:x.DEFAULT,action:()=>(H.navigateToNextItem(),d("Navigating to next item",null))},{intent:P.NavPreviousItemJump,mode:x.DEFAULT,action:()=>(H.jumpToPreviousItem(),d("Jumping to previous item",null))},{intent:P.NavNextItemJump,mode:x.DEFAULT,action:()=>(H.jumpToNextItem(),d("Jumping to next item",null))},{intent:P.NavToPreviousContainer,mode:x.DEFAULT,action:()=>(H.navigateToPreviousContainer(),d("Navigating to previous container",null))},{intent:P.NavToNextContainer,mode:x.DEFAULT,action:()=>(H.navigateToNextContainer(),d("Navigating to next container",null))}]});var vw,yw,Fb,Bb=g(()=>{"use strict";ge();vw=500,yw=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Fb=e=>{let t=yw(e);t&&na(n=>(n+t).slice(0,vw))}});var bw,xw,Iw,$b,jb=g(()=>{"use strict";Bb();Oe();N();ge();D();Kn();du();bw=[x.COMMAND_LINE,x.PALETTE],xw=e=>e==="edit title "?v().selectedNode?.title??"":"",Iw=e=>[{intent:P.MoveCursorLeft,mode:e,action:()=>(yc(-1),d("Moving cursor left",null))},{intent:P.MoveCursorRight,mode:e,action:()=>(yc(1),d("Moving cursor right",null))},{intent:P.MoveCursorLeftOfWord,mode:e,action:()=>(bc("left"),d("Moving cursor left of word",null))},{intent:P.MoveCursorRightOfWord,mode:e,action:()=>(bc("right"),d("Moving cursor right of word",null))},{intent:P.AutoCompleteCommand,mode:e,action:()=>(na((t,{remainder:n})=>{let r=n?t+n:t;return r+xw(r)}),d("Auto-completing command",null))},{intent:P.CaptureInput,mode:e,action:(t,{sequence:n})=>(Fb(n??""),d("Capturing input",null))},{intent:P.EraseInput,mode:e,action:()=>(yf(),d("Erasing input",null))},{intent:P.EraseInputWord,mode:e,action:()=>(bf(),d("Erasing input word",null))}],$b=[{intent:P.Confirm,mode:x.COMMAND_LINE,action:()=>(Vt(),d("Executing command",null))},{intent:P.ViewHelp,mode:x.DEFAULT,action:()=>(A({mode:x.HELP}),d("Viewing help",null))},...bw.flatMap(Iw),{intent:P.ExitCommandLine,mode:x.COMMAND_LINE,action:()=>(Rf(),A({mode:x.DEFAULT}),d("Exiting command line",null))},{intent:P.GetLastCommandFromHistory,mode:x.COMMAND_LINE,action:()=>(Sf(),d("Getting last command from history",null))},{intent:P.GetNextCommandFromHistory,mode:x.COMMAND_LINE,action:()=>(Nf(),d("Getting next command from history",null))}]});var Ew,Ub,Hb,Wb=g(()=>{"use strict";Ew=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},Ub=({keys:e})=>e.length===1?0:1,Hb=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(Ew).filter(r=>r!==null).sort((r,o)=>Ub(r)-Ub(o))}});function qb(e,t,n){let r=t[e];if(!r)return l("buildBreadCrumb(): current node not found");let o=[],s=new Set,i=r;for(;i&&!s.has(i.id)&&(o.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let c=o[o.length-1];return!c||c.id!==n?l("buildBreadCrumb(): node is not connected to root"):(o.reverse(),d("Breadcrumb built",o))}var Gb=g(()=>{"use strict";N()});var zb,Vb=g(()=>{"use strict";zb=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 Rw}from"react";function fu(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return l("derive(): contextNodeId is missing");if(!r)return l("derive(): rootNode is missing");if(!o[r])return l("derive(): unable to find root node");let c=o[t];if(!c)return l("Unable to derive state, contextNode not found");let u=qb(t,o,r);if(a(u))return logger.error(u.message),u;let p=u.value,{context:m}=c,f=[...Ob,...bb[m]??[],...$b],h=Hb(f,n),b=zb(f),E=Nw(o,s),S=E[t]?.[e.selectedIndex]??null;return d("Derived successfully",{...e,contextNode:c,breadCrumb:p,availableHints:h,availableActions:f,actionIndex:b,selectedNode:S,renderedChildrenIndex:E})}function Us(e){uu=e;let t=Ce(process.cwd()),n=!1;if(!a(t)){let s=Tt(t.value);if(a(s))return l(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},emailLinks:{},mode:x.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=fu(r);return a(o)?o:(St=o.value,pu(),d("State initialized",null))}function Pe(e){let t=v(),n=e(t);if(Yr)return n.nodes!==t.nodes&&(pr=null),vi=n,St={...t,...n},d("State updated",null);let r=fu(n);return a(r)?l(r.message??"Unable to update state"):(St=r.value,pu(),d("State updated",null))}function ga(e){if(Yr)return d("Joined batch",e());Yr=!0,vi=null,pr=new Set;let t=()=>{let n=vi;if(Yr=!1,vi=null,n===null)return null;let r=fu(n);return a(r)?l(r.message??"Unable to update state"):(St=r.value,pu(),d("State updated",null))};try{let n=e(),r=t();return r&&a(r)?l(r.message):d("State updated",n)}finally{Yr&&t()}}function Xr(e,t,n){if(!Yr)return Pe(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=v(),o=r[e]??{};if(e==="nodes"){let i=o[t],c=n;i?.parentNodeId&&pr?.add(i.parentNodeId),c.parentNodeId&&pr?.add(c.parentNodeId)}o[t]=n;let s={...r,[e]:o};return vi=s,St={...r,...s},d("State updated",null)}var St,uu,mu,pu,Sw,v,ke,Yr,vi,Pg,A,Ye,pr,Kb,Nw,be,qn,Ut,D=g(()=>{"use strict";xb();_b();jb();Wb();Zt();Oe();N();ee();qc();Gb();Vb();wt();tc();mu=new Set,pu=()=>{for(let e of mu)e()},Sw=e=>(mu.add(e),()=>mu.delete(e));v=()=>{if(!St)throw new Error("State not initialized. Call initWorkspaceState() first.");return St},ke=()=>St?d("Retrieved state",St):l("State not initialized. Call initWorkspaceState() first.");Np(e=>St?Vn(St.emailLinks,e):[]);Yr=!1,vi=null;Pg=()=>Yr,A=e=>Pe(t=>({...t,...e}));Ye=()=>Rw(Sw,v,v),pr=null,Kb=null,Nw=(e,t)=>{let n=St?.renderedChildrenIndex,r=n!==void 0&&pr!==null&&e===Kb&&t.length===0&&St?.filters.length===0,o;if(r){o={...n};let s=Tg(e,pr);for(let i of pr){let c=s[i];c?o[i]=c:delete o[i]}}else o=Ag(e,t);return Kb=e,pr=new Set,o},be=e=>v()?.renderedChildrenIndex[e]??[],qn=()=>uu?Us(uu):l("Cannot reset state: no initial workspace found"),Ut=()=>St!==void 0});var zt,Cw,fr,C,pe=g(()=>{"use strict";Xt();wt();me();N();D();jt();zt=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return l("Node not found");if(r.context===t)return d("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 d("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return l(`No ancestor found for context: ${t}`)},Cw=(e,t)=>{let{nodes:n}=v(),r=new Set,o=n[e];for(;o?.parentNodeId&&!r.has(o.id);){if(o.parentNodeId===t)return!0;r.add(o.id),o=n[o.parentNodeId]}return!1},fr=(e,t)=>e?e.readonly?l({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:l("Node not found"),C={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return l("Contributor not found");if(n.userId&&n.userId!==t)return l("Contributor is already linked to another user");let r={...n,userId:t},o=Pe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?l("Unable to link contributor to user"):d("Linked contributor to user",r)},deleteNode(e){C.deleteNodes([e])},deleteNodes(e){e.length!==0&&Pe(t=>{let n={...t.nodes};for(let r of e)delete n[r];return{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return l("Unable to create comment, missing issue");if(!U(t))return l("Can only comment on issues");let n=Xr("comments",e.id,{...e,deleted:!1});return a(n)?l("Unable to create comment"):d("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return l("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return l("Unable to edit comment, missing issue");if(!U(r))return l("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=Xr("comments",e,o);return a(s)?l("Unable to edit comment"):d("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return l("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=Xr("comments",e,n);return a(r)?l("Unable to delete comment"):d("Deleted comment",n)},getComment(e){return v().comments?.[e]},getCommentsByIssue(e){return Object.values(v().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(v().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return l("Unable to create attachment, missing issue");if(!U(t))return l("Can only attach to issues");let n=Pe(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?l("Unable to create attachment"):d("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return l("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=Pe(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return a(r)?l("Unable to delete attachment"):d("Deleted attachment",n)},getAttachment(e){return v().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(v().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(v().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return l("Edit target node not found");let o=fr(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),d("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return l("Rename target node not found");let r=fr(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),d("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return Me(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),s=this.getNode(t);if(!o)return l("Node not found");if(!s)return l("Target parent not found");if(r===e)return l("Cannot move root node");if(e===t)return l("Cannot move node into itself");let i=fr(o,"move");if(i)return i;if(Cw(t,e))return l("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),d("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return l("Node not found");if(r===e)return l("Cannot delete root node");let s=fr(o,"delete");if(s)return s;let i=new Set,c=p=>{let m=t[p];if(!(!m||i.has(p))){i.add(p);for(let f of Me(m.id))c(f.id)}};c(e);let u={...structuredClone(t)};for(let p of i){if(!u[p])return l("Unable to locate node to delete");u[p]={...u[p],isDeleted:!0}}return n?(A({nodes:u}),d("Successfully tomb stoned",o)):l("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return l("Contributor not found");let n={...t,name:cs,tombstoned:!0},r=Pe(o=>({...o,contributors:{...o.contributors,[e]:n}}));return a(r)?l("Unable to remove contributor"):d("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return l("Contributor not found");if(n.tombstoned)return l("Cannot rename a removed contributor");let r={...n,name:t},o=Pe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?l("Unable to rename contributor"):d("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return l("Contributor not found");let r={...n,name:t,tombstoned:!1},o=Pe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?l("Unable to restore contributor"):d("Restored contributor",r)},linkContributorEmail({email:e,contributor:t,authorId:n}){if(!this.getContributor(t))return l("Unable to link email, missing contributor");let r={email:Ve(e),contributor:t,authorId:n},o=ds(r.email,t),s=v().emailLinks[o];if(s&&!s.tombstoned)return d("Email already linked",s);let i=Pe(c=>({...c,emailLinks:{...c.emailLinks,[o]:r}}));return a(i)?l("Unable to link email"):d("Linked email to contributor",r)},unlinkContributorEmail(e,t,n){let r=ds(e,t),o=v().emailLinks[r];if(!o)return l("Unable to unlink, no such link");if(o.tombstoned)return d("Email already unlinked",o);if(!ki(n,o))return l("Only the author of a link or the contributor it names may remove it");let s={...o,tombstoned:!0},i=Pe(c=>({...c,emailLinks:{...c.emailLinks,[r]:s}}));return a(i)?l("Unable to unlink email"):d("Unlinked email from contributor",s)},getEmailLinks(){return v().emailLinks},createContributor(e){let t=Pe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?l("Unable to create contributor"):d("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return l("Unable to assign contributor, missing contributor");if(!r)return l("Unable to assign contributor, missing target");let o=fr(r,"edit");if(o)return o;if(!U(r))return l("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return l("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),d("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return l("Unable to unassign, missing contributor");if(!r)return l("Unable to unassign, missing target");let o=fr(r,"edit");if(o)return o;if(!U(r))return l("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return d("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),d("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return l("Unable to add tag, missing tag");if(!r)return l("Unable to add tag, missing target");let o=fr(r,"edit");if(o)return o;if(!U(r))return l("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return l("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),d("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),r=this.getNode(e);if(!n)return l("Unable to remove tag, missing tag");if(!r)return l("Unable to remove tag, missing target");let o=fr(r,"edit");if(o)return o;if(!U(r))return l("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return d("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),d("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return l("Tag not found");let n={...t,tombstoned:!0},r=Pe(o=>({...o,tags:{...o.tags,[e]:n}}));return a(r)?l("Unable to delete tag"):d("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return l("Tag not found");let r={...n,name:t,tombstoned:!1},o=Pe(s=>({...s,tags:{...s.tags,[e]:r}}));return a(o)?l("Unable to restore tag"):d("Restored tag",r)},createTag(e){let t=Pe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?l("Could not create tag"):d("Tag created",e)},createNode(e){let t=Xr("nodes",e.id,e);return a(t)?l("Unable to create node"):d("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return l("Failed to locate node");let n={...t,readonly:!0},r=Xr("nodes",e,n);return a(r)?l(r.message):d("Locked node",n)},updateNode(e){let t=Xr("nodes",e.id,e);return a(t)?t:d("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){let t=v().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return v().tags[e]},getTags(){return Object.values(v().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return v().nodes[e]},getSiblings(e){return Me(e)}}});import gr from"chalk";import Yb from"string-width";var ww,Aw,gu,Tw,kw,Xb,Jb,Mw,Lw,Pw,Dw,Ow,_w,nu,Qb,pi=g(()=>{"use strict";lt();N();Tn();pe();D();un();ei();ww=(e,t)=>e+" ".repeat(Math.max(0,t-Yb(e))),Aw=(e,t)=>" ".repeat(Math.max(0,t-Yb(e)))+e,gu=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed contributor","link.contributor.user":"Linked contributor","link.contributor.email":"Claimed","unlink.contributor.email":"Unclaimed","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),Tw=(e,t)=>t?e<t?"up":e>t?"down":null:null,kw=(e,t)=>{let n=C.getNode(e.payload.parent),r=n?gr.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=Tw(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Xb=e=>`${Math.max(1,Math.round(e/1024))} KB`,Jb=e=>C.getAttachment(e)?.name??"",Mw=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?gr.bgHex(tt(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?gr.bgHex(tt(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=v().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?gr.hex(tt(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?gr.hex(tt(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"add.issue.attachment":return`"${e.payload.name}" ${gr.dim(`(${Xb(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Jb(e.payload.id);return t?`"${t}"`:""}default:return""}},Lw=e=>{let t=ar(at(e));return gr.gray(Aw(t,8))},Pw=12,Dw=e=>ww(`${e}`,Pw),Ow=e=>{let t=ke();return a(t)?e:ls(e,t.value.contributors[e]?.name)},_w=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=v().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"move.node":{let t=C.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Xb(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Jb(e.payload.id);return t?`"${t}"`:""}default:return""}},nu=e=>[gu(e.action),_w(e)].filter(Boolean).join(" "),Qb=(e,t)=>{let n=Lw(e.id),r=Dw(Ow(e.userId)),o=gr.dim("\u203A"),s=e.action==="move.node"?kw(e,t):[gu(e.action),Mw(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`}});var ex={};rs(ex,{areVirtualNodesEnabled:()=>va,createOrUpdateVirtualField:()=>qo,createOrUpdateVirtualFieldList:()=>hu,materializeTicketVirtualNodes:()=>ha,materializeVirtualNodes:()=>Vw,setVirtualNodesEnabled:()=>zw});var Fw,Bw,$w,jw,Uw,Hw,Ww,qo,hu,pl,qw,ha,Gw,Zb,zw,va,Vw,$c=g(()=>{"use strict";pi();me();N();Eo();pe();sr();D();bo();Jn();Fw=e=>Te(e,"comments"),Bw=e=>Te(e,"description"),$w=e=>Te(e,"assignees"),jw=e=>Te(e,"tags"),Uw=e=>Te(e,"history"),Hw=e=>Te(e,"diff"),Ww=e=>Te(e,"attachments"),qo=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=C.getNode(e);if(!c){let m=C.createNode({...$e.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return a(m)?m:d("Virtual field created",void 0)}if(!nt(c))return l(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==i))return d("Virtual field unchanged",void 0);let p=C.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return a(p)?p:d("Virtual field updated",void 0)},hu=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=C.getNode(e);if(!i){let p=C.createNode({...$e.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return a(p)?p:d("Virtual field list created",void 0)}if(!us(i))return l(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return d("Virtual field list unchanged",void 0);let u=C.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(u)?u:d("Virtual field list updated",void 0)},pl=null,qw=()=>{if(pl)return d("Virtual field ranks",pl);let e=Lt(rn/4n),t=Lt(rn/2n),n=Lt(rn*3n/4n),r=Lt(rn*7n/8n),o=Lt(rn*15n/16n),s=Lt(rn*13n/16n),i=Lt(rn*27n/32n);return a(e)?e:a(t)?t:a(n)?n:a(r)?r:a(o)?o:a(s)?s:a(i)?i:(pl={description:e.value,assignees:t.value,tags:n.value,comments:r.value,attachments:o.value,log:s.value,diff:i.value},d("Virtual field ranks",pl))},ha=e=>{let t=qw();if(a(t))return t;let n=t.value,r=qo({id:Bw(e.id),name:Ae.DESCRIPTION,parentNodeId:e.id,rank:n.description,value:e.props.description??"",childRenderAxis:"vertical"});if(a(r))return r;let o=hu({id:$w(e.id),name:Ae.ASSIGNEES,parentNodeId:e.id,rank:n.assignees,readonly:!0});if(a(o))return o;let s=hu({id:jw(e.id),name:Ae.TAGS,parentNodeId:e.id,rank:n.tags,readonly:!0});if(a(s))return s;let i=qo({id:Fw(e.id),name:Ae.COMMENTS,parentNodeId:e.id,rank:n.comments,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(i))return i;let c=qo({id:Ww(e.id),name:Ae.ATTACHMENTS,parentNodeId:e.id,rank:n.attachments,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(c))return c;let u=qo({id:Uw(e.id),name:Ae.HISTORY,parentNodeId:e.id,rank:n.log,value:Gw(e),readonly:!0,childRenderAxis:"vertical"});if(a(u))return u;let p=qo({id:Hw(e.id),name:Ae.DIFF,parentNodeId:e.id,rank:n.diff,value:"",readonly:!0,childRenderAxis:"vertical"});return a(p)?p:d("Ticket virtual nodes materialized",void 0)},Gw=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=>Qb(r,n.get(r.action)??[])).join(`
|
|
107
|
-
`)},
|
|
108
|
-
`)){let i=s.indexOf(" ");if(i===-1)continue;let c=s.slice(0,i),u=s.slice(i+1);c==="user.name"&&(r=u.trim()||null),c==="user.email"&&(o=Ve(u)||null)}return sx.set(e,{name:r,email:o,readAt:Date.now()}),{name:r,email:o}},ax=async e=>(await ix(e)).email,Qr=async e=>(await ix(e)).name});import Zw from"node:fs";var Zr,hl,Z,te,X,cn=g(()=>{"use strict";rt();Ke();mn();Ys();bi();bn();Ue();jr();xo();ee();$();N();D();_t();yi();Zr=e=>{let t=Ce(e??process.cwd());return a(t)?l(t.message):d("Resolved Epiq repo root",t.value)},hl=null,Z=async(e,t)=>{let n=Zr(e);if(a(n))return n;let r=Ie({repoRoot:n.value});if(a(r))return l(r.message);let o=dt(n.value);if(a(o))return l(o.message);if(!(hl!==null&&hl.repoRoot===n.value&&hl.stateBranchRoot===r.value&&Zw.existsSync(Cr(r.value)))){let f=await Vs({repoRoot:n.value,stateBranchName:o.value});if(a(f))return l(f.message);let h=await ir({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(a(h))return l(h.message);hl={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let f=await W({cwd:r.value,args:["pull","--ff-only"]});a(f)&&ce.info(3,f.message)}let i={repoRoot:n.value,stateBranchRoot:r.value},c=Xn();a(c)||ut(c.value),ut({gitEmail:await ax(n.value),gitName:await Qr(n.value)});let u=Pr(r.value);if(Of(r.value)===u&&Ut()&&Jr().mode==="live")return d("Booted Epiq state, unchanged",i);let p=sn(r.value);if(a(p))return l(p.message);let m=En(p.value.events,p.value.unreadable);return a(m)?l(m.message):(_f(r.value,u),d("Booted Epiq state",i))},te=()=>{let e=Xn();return a(e)?l(e.message):e.value.userId?e.value.userName?d("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):l("Unable to retrieve user name"):l("Unable to retrieve user id")},X=()=>{let e=ke();return a(e)?l(e.message):e}});var Go,lx,zo,yu=g(()=>{"use strict";lt();pe();Tn();uo();Go=e=>hn(e).map(t=>ht(t.id,t.name)),lx=e=>C.getCommentsByIssue(e).sort((t,n)=>t.id<n.id?-1:t.id>n.id?1:0).map(t=>({id:t.id,author:ls(t.authorId,C.getContributor(t.authorId)?.name),createdAt:at(t.id),body:t.md})),zo=e=>vn(e).map(({id:t,name:n})=>ht(t,n))});var Ze,hr,bu,eo=g(()=>{"use strict";me();N();cn();Ze=e=>{let t=X();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?l("Issue not found"):U(n)?n.readonly?l("Issue is readonly"):d("Found issue",n):l("Target must be an issue")},hr=e=>{let t=X();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?l("Swimlane not found"):xr(n)?n.readonly?l("Swimlane is readonly"):d("Found swimlane",n):l("Target must be a swimlane")},bu=e=>{let t=X();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?l("Board not found"):Ir(n)?n.readonly?l("Board is readonly"):d("Found board",n):l("Target must be a board")}});import eA from"node:fs";import tA from"node:path";import{ulid as cx}from"ulid";var nA,dx,xu,Iu=g(()=>{"use strict";bn();$();$t();N();vt();eo();fo();cn();nA=e=>{if(e.filePath)try{return d("Read attachment file",{data:eA.readFileSync(e.filePath),name:e.name??tA.basename(e.filePath)})}catch(t){return l(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?d("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):l("Provide either filePath or dataBase64")},dx=()=>{let e=Xn();return a(e)?Dn:e.value.attachmentMaxKb??Dn},xu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=Ze(e.issueId);if(a(o))return o;let s=nA(e);if(a(s))return s;let i=Jp(t.value.stateBranchRoot,s.value.data,dx());if(a(i))return i;let c=Se(s.value.name).trim()||"image",u=cx(),p={id:cx(),...O(n.value),action:"add.issue.attachment",payload:{id:u,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:c,bytes:i.value.bytes}},m=_([p],t.value.stateBranchRoot);if(a(m))return l(m.message);let f=po(i.value.hash,i.value.ext);return d("Added issue attachment",{id:u,issueId:e.issueId,fileName:f,bytes:i.value.bytes,markdown:mc(c,f)})}});var Eu,cJ,Ru,ux=g(()=>{"use strict";bn();lt();tn();me();N();pe();lo();Tn();un();vu();ft();vt();fo();_t();yi();cn();yu();Iu();wa();$();Gs();Eu=async(e={})=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=X();return a(n)?n:d("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})},cJ=365*24*60*60*1e3,Ru=async(e={})=>{Ro();let t=Zr(e.repoRoot);if(a(t))return l("Sync failed");let n=te();if(a(n))return n;let r=await Ca({cwd:t.value,ownEventFileName:rr(n.value)});return a(r)?(Gc(r.message),r):(Ur(),d("Synced",r.value))}});var xi,Vo,Ii,Su=g(()=>{"use strict";N();ft();xi=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?d("Resolved targets",t):l("Provide issueId or issueIds")},Vo=(e,t)=>{let n=t.done.length,r=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?d(r,t):l(`${r}: ${t.failed.map(o=>`${o.ref} ${o.reason}`).join("; ")}`)},Ii=(e,t)=>{let n={done:[],failed:[]};for(let r of e){let o=t(r);a(o)?n.failed.push({id:r,ref:V(r),reason:o.message}):n.done.push({id:r,ref:V(r)})}return n}});import{ulid as Kt}from"ulid";async function Cu(e){let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=X();if(a(n))return n;let r=n.value.nodes,o=e.query?.trim().toLowerCase(),s=Object.values(r).filter(U).filter(c=>!c.isDeleted).filter(c=>e.includeClosed||c.parentNodeId!==we).filter(c=>e.boardId?(c.parentNodeId?r[c.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(c=>!e.swimlaneId||c.parentNodeId===e.swimlaneId).filter(c=>!e.tag||Go(c).some(u=>mx(u.name,e.tag))).filter(c=>!e.assignee||zo(c).some(u=>mx(u.name,e.assignee))).filter(c=>!o||c.title.toLowerCase().includes(o)||(c.props.description??"").toLowerCase().includes(o)),i=c=>Se((c.parentNodeId?r[c.parentNodeId]?.title:void 0)??"");return e.brief?d("Listed issues",s.map(c=>({id:c.id,ref:V(c.id),title:Se(c.title),swimlane:i(c),tags:Go(c).map(u=>u.name),assignees:zo(c).map(u=>u.name)}))):d("Listed issues",s.map(c=>({id:c.id,ref:V(c.id),title:Se(c.title),description:c.props.description??"",createdAt:at(c.id),enteredLaneAt:fl(c.log??[],at(c.id)),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===we,readonly:!!c.readonly,tags:Go(c),assignees:zo(c)})))}async function Au(e){let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=xi(e);if(a(r))return r;let o=s=>rA(s,n.value,t.value.stateBranchRoot);return e.issueIds?Vo("Closed",Ii(r.value,o)):o(r.value[0])}async function ku(e){let t=Zr(e.repoRoot);if(a(t))return t;let n=te();if(a(n))return n;let r=Ie({repoRoot:t.value});if(a(r))return r;let o=sn(r.value);if(a(o))return o;let s=En(o.value.events,o.value.unreadable);if(a(s))return s;let i=xi(e);if(a(i))return i;let c=u=>oA(u,e,n.value,r.value);return e.issueIds?Vo("Moved",Ii(i.value,c)):c(i.value[0])}var Nu,mx,wu,rA,Tu,oA,Mu,Lu,px=g(()=>{"use strict";rt();Qd();lt();jr();$();$();$t();ru();tn();me();Tn();N();pe();jt();pi();On();vu();ft();vt();cn();yu();Su();eo();Nu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=X();if(a(n))return n;let r=e.idOrRef.trim();if(!r)return l("Provide an issue id or ref");let o=Object.values(n.value.nodes).filter(U).filter(u=>!u.isDeleted),s=o.find(u=>u.id===r),i=s?[s]:o.filter(u=>$s(u.id,r));if(i.length===0)return l(`No issue matches "${r}"`);if(i.length>1)return l(`"${r}" matches ${i.length} issues: ${i.map(u=>`${V(u.id)} (${Se(u.title)})`).join(", ")}. Use a full ref or id.`);let c=i[0];return d("Found issue",{id:c.id,ref:V(c.id),title:Se(c.title),description:c.props.description??"",createdAt:at(c.id),enteredLaneAt:fl(c.log??[],at(c.id)),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===we,readonly:!!c.readonly,tags:Go(c),assignees:zo(c),comments:lx(c.id)})},mx=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();wu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=Se(e.title);if(!o)return l("Issue title cannot be empty");let s=e.description??"",i=ot("Issue title",o,300)??ot("Issue description",s,2e4);if(i)return l(i);if((e.tagNames?.length??0)>20)return l(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return l(`Cannot set more than ${20} assignees at once`);let c=hr(e.parentId);if(a(c))return c;let u=Bn(e.parentId,n.value,t.value.stateBranchRoot);if(a(u))return u;let p=el({name:o,parent:e.parentId,user:n.value,rank:u.value});if(a(p))return p;let m=[...p.value],f=m.find(S=>S.action==="add.issue")?.payload.id;if(!f)return l("Unable to determine created issue id");s&&m.push({id:Kt(),...O(n.value),action:"edit.description",payload:{id:f,md:s}});let h=[];for(let S of e.tagNames??[]){let w=Se(S).trim();if(!w||h.some(F=>F.name===w))continue;let R=ot("Tag name",w,60);if(R)return l(R);let k=C.findTagByName(w),M=k?.id??Kt();k||m.push({id:Kt(),...O(n.value),action:"create.tag",payload:{id:M,name:w}}),m.push({id:Kt(),...O(n.value),action:"add.issue.tag",payload:{id:f,tag:M}}),h.push({id:M,name:w})}let b=[];for(let S of e.assigneeNames??[]){let w=Se(S).trim();if(!w||b.some(F=>F.name===w))continue;let R=ot("Assignee name",w,80);if(R)return l(R);let k=Object.values(r.value.contributors).find(F=>F.name===w),M=k?.id??Kt();k||m.push({id:Kt(),...O(n.value),action:"create.contributor",payload:{id:M,name:w}}),m.push({id:Kt(),...O(n.value),action:"add.issue.assignee",payload:{id:f,assignee:M}}),b.push({id:M,name:w})}let E=_(m,t.value.stateBranchRoot);return a(E)?l(E.message):d("Created issue",{id:f,ref:V(f),title:o,parentId:e.parentId,description:s,tags:h,assignees:b})},rA=(e,t,n)=>{let r=Ze(e);if(a(r))return r;let o=xn(we,e,{at:"end"},t,n);if(a(o))return o;let s={id:Kt(),...O(t),action:"close.issue",payload:{id:e,parent:we,rank:o.value}},i=_([s],n);return a(i)?l(i.message):d("Closed issue",{id:e,ref:V(e)})};Tu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o||o.isDeleted)return l("Issue not found");if(!U(o))return l("Target must be an issue");if(o.parentNodeId!==we)return l("Issue is not closed");let s=sl(o);if(!s)return l("Unable to resolve previous parent from issue history");if(s===we)return l("Previous parent resolves to closed swimlane");let i=hr(s);if(a(i))return i;let c=i.value,u=xn(c.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(u))return u;let p={id:Kt(),...O(n.value),action:"reopen.issue",payload:{id:o.id,parent:c.id,rank:u.value}},m=_([p],t.value.stateBranchRoot);return a(m)?l(m.message):d("Reopened issue",{id:o.id,ref:V(o.id),parentId:c.id})},oA=(e,t,n,r)=>{let o=Ze(e);if(a(o))return o;let s=hr(t.parentId);if(a(s))return s;let i=xn(t.parentId,e,t.position??{at:"end"},n,r);if(a(i))return i;let c={id:Kt(),...O(n),action:"move.node",payload:{id:e,parent:t.parentId,rank:i.value}},u=_([c],r);return a(u)?l(u.message):d("Moved issue",{id:e,ref:V(e),parentId:t.parentId})};Mu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=Ze(e.issueId);if(a(o))return o;let s=o.value,i=ot("Issue description",e.description,2e4);if(i)return l(i);let c=s.props.description??"";if(c===e.description)return d("No changes made",{id:e.issueId,ref:V(e.issueId),description:c});let u={id:Kt(),...O(n.value),action:"edit.description",payload:{id:e.issueId,md:e.description}},p=_([u],t.value.stateBranchRoot);return a(p)?l(p.message):d("Edited issue description",{id:e.issueId,ref:V(e.issueId),description:e.description})},Lu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=Ze(e.issueId);if(a(o))return o;let s=o.value,i=Se(e.title);if(!i.trim())return l("Issue title cannot be empty");let c=ot("Issue title",i,300);if(c)return l(c);if(s.title===i)return d("No changes made",{id:e.issueId,ref:V(e.issueId),title:i});let u={id:Kt(),...O(n.value),action:"edit.title",payload:{id:e.issueId,name:i}},p=_([u],t.value.stateBranchRoot);return a(p)?l(p.message):d("Edited issue title",{id:e.issueId,ref:V(e.issueId),title:i})}});import{ulid as vr}from"ulid";var Pu,Du,Ou,_u,Fu,Bu,$u,ju,fx=g(()=>{"use strict";rt();jr();$();$();$t();tn();me();N();jt();On();ft();vt();yi();cn();eo();Pu=async(e={})=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=X();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 d("Listed boards",r)},Du=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=r.value.nodes[r.value.rootNodeId];if(!o)return l("Workspace not found");if(Jr().mode!=="live")return l("Cannot add a board while time travelling");let s=Se(e.title);if(!s.trim())return l("Board title cannot be empty");let i=ot("Board title",s,300);if(i)return l(i);let c=Bn(o.id,n.value,t.value.stateBranchRoot);if(a(c))return c;let u=vr(),p={id:vr(),...O(n.value),action:"add.board",payload:{id:u,name:s,parent:o.id,rank:c.value}},m=_([p],t.value.stateBranchRoot);return a(m)?l(m.message):d("Created board",{id:u,ref:V(u),title:s})},Ou=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=r.value.nodes[e.boardId];if(!o||o.isDeleted)return l("Board not found");if(!Ir(o))return l("Edit target must be a board");if(o.readonly)return l("Cannot edit readonly board");if(Jr().mode!=="live")return l("Cannot rename a board while time travelling");let s=Se(e.title);if(!s.trim())return l("Board title cannot be empty");let i=ot("Board title",s,300);if(i)return l(i);if(o.title===s)return d("No changes made",{id:e.boardId,ref:V(e.boardId),title:s});let c={id:vr(),...O(n.value),action:"edit.title",payload:{id:e.boardId,name:s}},u=_([c],t.value.stateBranchRoot);return a(u)?l(u.message):d("Edited board title",{id:e.boardId,ref:V(e.boardId),title:s})},_u=async(e={})=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=X();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===we,readonly:!!o.readonly}));return d("Listed swimlanes",r)},Fu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=bu(e.boardId);if(a(o))return o;if(Jr().mode!=="live")return l("Cannot add a swimlane while time travelling");let s=Se(e.title);if(!s.trim())return l("Swimlane title cannot be empty");let i=ot("Swimlane title",s,300);if(i)return l(i);let c=Bn(e.boardId,n.value,t.value.stateBranchRoot);if(a(c))return c;let u=vr(),p={id:vr(),...O(n.value),action:"add.swimlane",payload:{id:u,name:s,parent:e.boardId,rank:c.value}},m=_([p],t.value.stateBranchRoot);return a(m)?l(m.message):d("Created swimlane",{id:u,ref:V(u),title:s,boardId:e.boardId})},Bu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=hr(e.swimlaneId);if(a(o))return o;let s=o.value,i=Se(e.title);if(!i.trim())return l("Swimlane title cannot be empty");let c=ot("Swimlane title",i,300);if(c)return l(c);if(s.title===i)return d("No changes made",{id:e.swimlaneId,ref:V(e.swimlaneId),title:i});let u={id:vr(),...O(n.value),action:"edit.title",payload:{id:e.swimlaneId,name:i}},p=_([u],t.value.stateBranchRoot);return a(p)?l(p.message):d("Edited swimlane title",{id:e.swimlaneId,ref:V(e.swimlaneId),title:i})},$u=async e=>{let t=Zr(e.repoRoot);if(a(t))return t;let n=te();if(a(n))return n;let r=Ie({repoRoot:t.value});if(a(r))return r;let o=sn(r.value);if(a(o))return o;let s=En(o.value.events,o.value.unreadable);if(a(s))return s;let i=hr(e.swimlaneId);if(a(i))return i;let c=bu(e.boardId);if(a(c))return c;let u=xn(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(a(u))return u;let p={id:vr(),...O(n.value),action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:u.value}},m=_([p],r.value);return a(m)?l(m.message):d("Moved swimlane",{id:e.swimlaneId,ref:V(e.swimlaneId),boardId:e.boardId})},ju=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=hr(e.swimlaneId);if(a(o))return o;let s={id:vr(),...O(n.value),action:"delete.node",payload:{id:e.swimlaneId}},i=_([s],t.value.stateBranchRoot);return a(i)?l(i.message):d("Deleted swimlane",{id:e.swimlaneId,ref:V(e.swimlaneId)})}});import{ulid as Xo}from"ulid";async function Uu(e){let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=xi(e);if(a(r))return r;let o=Se(e.tagName).trim();if(!o)return l("Tag name cannot be empty");let s=ot("Tag name",o,60);if(s)return l(s);let i=Ii(r.value,Ze);if(!e.issueIds&&i.failed[0])return l(i.failed[0].reason);if(i.done.length===0)return l(Vo("Tagged",i).message);let c=C.findTagByName(o),u=c?.id??Xo(),p=[...c?[]:[{id:Xo(),...O(n.value),action:"create.tag",payload:{id:u,name:o}}],...i.done.map(({id:b})=>({id:Xo(),...O(n.value),action:"add.issue.tag",payload:{id:b,tag:u}}))],m=_(p,t.value.stateBranchRoot);if(a(m))return l(m.message);let f={id:u,name:o};if(!e.issueIds)return d("Added issue tag",{...i.done[0],tag:f});let h=Vo("Tagged",i);return a(h)?h:d(h.message,{...h.value,tag:f})}var Hu,Wu,qu,gx=g(()=>{"use strict";$();$t();N();pe();On();ft();vt();cn();Su();eo();Hu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return l("Tag not found");if(o.tombstoned)return l("Tag is already deleted");let s=[{id:Xo(),...O(n.value),action:"tombstone.tag",payload:{id:e.tagId}}],i=_(s,t.value.stateBranchRoot);return a(i)?l(i.message):d("Deleted tag",{id:o.id,name:o.name})},Wu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return l("Tag not found");if(!o.tombstoned)return l("Tag is not deleted");if(C.findTagByName(o.name))return l(`Cannot restore: another tag is already named "${o.name}"`);let s=[{id:Xo(),...O(n.value),action:"restore.tag",payload:{id:e.tagId,name:o.name}}],i=_(s,t.value.stateBranchRoot);return a(i)?l(i.message):d("Restored tag",{id:o.id,name:o.name})},qu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=Ze(e.issueId);if(a(o))return o;if(!r.value.tags[e.tagId])return l("Tag not found");let s={id:Xo(),...O(n.value),action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=_([s],t.value.stateBranchRoot);return a(i)?l(i.message):d("Removed issue tag",{id:e.issueId,ref:V(e.issueId),tagId:e.tagId})}});import{ulid as Gn}from"ulid";var Gu,hx,zu,Vu,sA,Ku,Yu,Xu,vx=g(()=>{"use strict";N();Xt();yr();$();$();$t();il();Tn();gl();On();ft();vt();cn();eo();Gu=async e=>{let t=wl(e.name,"name");if(a(t))return l(t.message);let n=await Z(e.repoRoot,{pull:!1});if(a(n))return n;let r=te();if(a(r))return r;let o=X();if(a(o))return o;let s=r.value,i=!!o.value.contributors[s.userId];if(!i){let c=_([{id:Gn(),...O(s),action:"create.contributor",payload:{id:s.userId,name:s.userName}}],n.value.stateBranchRoot);if(a(c))return l(c.message)}return d(`Assumed ${s.userName}`,{...s,registered:!i})},hx=async(e,t)=>{let n=Fr(e).get(t);return n===void 0?void 0:{id:t,name:n}},zu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=Ze(e.issueId);if(a(o))return o;let s=e.self?n.value.userId:e.assigneeId;if(s){let S=r.value.contributors[s],w=S?void 0:await hx(t.value.stateBranchRoot,s);if(!S&&!w)return l("Unknown assignee id");let R=S??w,k=[...S?[]:[{id:Gn(),...O(n.value),action:"create.contributor",payload:{id:R.id,name:R.name}}],{id:Gn(),...O(n.value),action:"add.issue.assignee",payload:{id:e.issueId,assignee:R.id}}],M=_(k,t.value.stateBranchRoot);return a(M)?l(M.message):d("Added issue assignee",{id:e.issueId,ref:V(e.issueId),assignee:{id:R.id,name:R.name}})}let i=Se(e.assigneeName??"").trim();if(!i)return l("Provide assigneeId, self or assigneeName");let c=ot("Assignee name",i,80);if(c)return l(c);let u=gi({events:r.value.eventLog??[],registry:r.value.contributors,logFileNames:Fr(t.value.stateBranchRoot)}).filter(S=>S.name===i);if(u.length>1)return l(`"${i}" matches ${u.length} contributors (${u.map(({id:S})=>S).join(", ")}). Assign by assigneeId to choose.`);let p=u[0];if(!p&&!e.createUnlinked)return l(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let m=p?.id??Gn(),f=p?.name??i,b=[...!!r.value.contributors[m]?[]:[{id:Gn(),...O(n.value),action:"create.contributor",payload:{id:m,name:f}}],{id:Gn(),...O(n.value),action:"add.issue.assignee",payload:{id:e.issueId,assignee:m}}],E=_(b,t.value.stateBranchRoot);return a(E)?l(E.message):d("Added issue assignee",{id:e.issueId,ref:V(e.issueId),assignee:{id:m,name:f}})},Vu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;if(!r.value.contributors[e.contributorId])return l("Contributor not found");if(await hx(t.value.stateBranchRoot,e.contributorId))return l("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let i=[{id:Gn(),...O(n.value),action:"tombstone.contributor",payload:{id:e.contributorId}}],c=_(i,t.value.stateBranchRoot);return a(c)?l(c.message):d("Tombstoned contributor",{id:e.contributorId,name:cs})},sA=async(e,t)=>{let n=Br(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},Ku=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=r.value.contributors[e.contributorId];if(!o)return l("Contributor not found");if(!o.tombstoned)return l("Contributor is not tombstoned");let s=await sA(t.value.stateBranchRoot,e.contributorId);if(!s)return l("Cannot restore this contributor \u2014 no original name found in the event log");let i=[{id:Gn(),...O(n.value),action:"restore.contributor",payload:{id:e.contributorId,name:s}}],c=_(i,t.value.stateBranchRoot);return a(c)?l(c.message):d("Restored contributor",{id:e.contributorId,name:s})},Yu=async(e={})=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=Br(t.value.stateBranchRoot);if(a(o))return l(o.message);let s=e.boardId?nx(o.value,e.boardId):o.value,i=new Set,c=xg(t.value.stateBranchRoot);if(a(c))return l(c.message);for(let m of c.value)m.userId&&i.add(m.userId);let u=r.value.contributors,p=gi({events:s,registry:u,logFileNames:Fr(t.value.stateBranchRoot)}).map(({id:m,name:f,isExternal:h})=>({...ht(m,f),isSelf:m===n.value.userId,isExternal:h,isRemoved:u[m]?.tombstoned===!0,hasAuthoredAnywhere:i.has(m)}));return d("Listed board contributors",p)},Xu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=Ze(e.issueId);if(a(o))return o;if(!r.value.contributors[e.assigneeId])return l("Assignee not found");let s={id:Gn(),...O(n.value),action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=_([s],t.value.stateBranchRoot);return a(i)?l(i.message):d("Removed issue assignee",{id:e.issueId,ref:V(e.issueId),assigneeId:e.assigneeId})}});import{ulid as bl}from"ulid";var Ju,Qu,Zu,yx=g(()=>{"use strict";$();$t();N();On();cn();eo();Ju=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=Ze(e.issueId);if(a(o))return o;let s=e.body.trim();if(!s)return l("Comment cannot be empty");if(s.length>4e3)return l(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i=bl(),c={id:bl(),...O(n.value),action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},u=_([c],t.value.stateBranchRoot);return a(u)?l(u.message):d("Added issue comment",{id:i,issueId:e.issueId,body:s})},Qu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();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 l("Unable to resolve comment");if(o.payload.author!==n.value.userId)return l("You can only delete your own comments");let s=Ze(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return d("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:bl(),...O(n.value),action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=_([c],t.value.stateBranchRoot);return a(u)?l(u.message):d("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},Zu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();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 l("Unable to resolve comment");if(o.payload.author!==n.value.userId)return l("You can only edit your own comments");let s=Ze(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return l("Comment was deleted");let c=e.body.trim();if(!c)return l("Comment cannot be empty");if(c.length>4e3)return l(`Comment cannot exceed ${4e3} characters (got ${c.length})`);let u={id:bl(),...O(n.value),action:"edit.issue.comment",payload:{id:e.commentId,issue:o.payload.issue,md:c}},p=_([u],t.value.stateBranchRoot);return a(p)?l(p.message):d("Edited issue comment",{id:e.commentId,issueId:o.payload.issue,body:c})}});import{ulid as bx}from"ulid";var em,tm,nm,rm,om=g(()=>{"use strict";$();wt();Tn();N();mn();bi();dl();Ue();cn();em=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;if(!zn(e.email))return l(`Not an email address: ${e.email}`);let o=Ve(e.email),s=e.contributorId??n.value.userId;if(!r.value.contributors[s])return l(`Unknown contributor: ${s}`);let i=Ol(r.value.emailLinks,o);if(i.includes(s))return d(`${o} is already yours`,{contributor:s,email:o,contested:i.filter(u=>u!==s)});let c=_([{id:bx(),action:"link.contributor.email",payload:{contributor:s,email:o},userId:n.value.userId}],t.value.stateBranchRoot);return a(c)?l(c.message):d(i.length>0?`Claimed ${o}, but somebody else claims it too, so it now resolves to neither of you`:`Claimed ${o}`,{contributor:s,email:o,contested:i})},tm=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let o=Ve(e.email),s=e.contributorId??n.value.userId,i=r.value.emailLinks[ds(o,s)];if(!i||i.tombstoned)return l(`No such link: ${o} to ${s}`);if(!ki(n.value.userId,i))return l("Only whoever made a claim, or the contributor it names, may undo it");let c=_([{id:bx(),action:"unlink.contributor.email",payload:{contributor:s,email:o},userId:n.value.userId}],t.value.stateBranchRoot);return a(c)?l(c.message):d(`Unclaimed ${o}`,{contributor:s,email:o})},nm=async(e={})=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=X();if(a(n))return n;let{emailLinks:r,contributors:o}=n.value,s=new Map;for(let f of Object.values(r)){if(f.tombstoned)continue;let h=s.get(f.email)??new Set;h.add(f.contributor),s.set(f.email,h)}let i=[...s.entries()].map(([f,h])=>({email:f,contested:h.size>1,claimants:[...h].map(b=>ht(b,o[b]?.name))})).sort((f,h)=>f.email.localeCompare(h.email)),c=te(),u=a(c)?[]:Vn(r,c.value.userId),p=de().gitEmail,m=p?Ol(r,p).filter(f=>a(c)||f!==c.value.userId):[];return d("Listed contributor emails",{emails:i,mine:u,git:p?{email:p,linkedToMe:u.includes(p),heldByOthers:m.map(f=>ht(f,o[f]?.name))}:null})},rm=async(e={})=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=X();if(a(r))return r;let{userId:o,userName:s}=n.value,i=dt(t.value.repoRoot),c=await hi({repoRoot:t.value.repoRoot,stateBranch:a(i)?void 0:i.value,names:[s,await Qr(t.value.repoRoot)],links:r.value.emailLinks});if(a(c))return c;let u=cl(c.value),p=u.filter(m=>m.looksLikeYours);return d(u.length===0?"No unclaimed addresses in this history":`${u.length} unclaimed address(es) in this history, ${p.length>0?`${p.length} of which look like yours`:"none obviously yours"}. Show them to the user and link only the ones they confirm; each is a permanent event that replicates to every clone.`,{contributor:o,candidates:u,likely:p.length})}});var xx=g(()=>{"use strict";lt();N()});var Ix=g(()=>{"use strict";mn();bi();N();dl();xx();cn()});var Ex=g(()=>{"use strict";ux();px();fx();gx();vx();yx();Iu();om();Ix()});import{ulid as iA}from"ulid";var Rx,Sx,Nx,Cx=g(()=>{"use strict";yr();lo();bi();bn();N();Kd();_t();Rx=[{name:"userName",question:"the name they want to appear under on the board"},{name:"preferredEditor",question:'the command that opens a file for editing, e.g. "vim", "nano" or "code --wait"'},{name:"autoSync",question:"whether the TUI and GUI should sync with the git remote on their own (true or false)"}],Sx=e=>e.trim().toLowerCase(),Nx=async(e={})=>{let t=yn();if(a(t))return l(t.message);let n=t.value,r=e.userName?.trim(),o=(process.env[Ot]??"").trim();if(r&&o&&Sx(r)===Sx(o))return l(`userName "${r}" is this agent's own identity. Pass the user's name, the one they want the TUI and GUI to write as.`);let s={userName:r||void 0,preferredEditor:e.preferredEditor?.trim()||void 0,autoSync:e.autoSync},i={userName:n.userName?.trim()||void 0,preferredEditor:n.preferredEditor?.trim()||void 0,autoSync:typeof n.autoSync=="boolean"?n.autoSync:void 0};for(let w of Rx){let R=s[w.name],k=i[w.name];if(!(R===void 0||k===void 0||R===k))return l(`This machine is already set up with ${w.name} ${JSON.stringify(k)}; epiq_project_init does not change it. Call again without ${w.name}, or let the user change it in the TUI with :config.`)}let c={};if(s.userName&&!i.userName&&(c.userName=s.userName),s.preferredEditor&&!i.preferredEditor&&(c.preferredEditor=s.preferredEditor),s.autoSync!==void 0&&i.autoSync===void 0&&(c.autoSync=s.autoSync),(c.userName||i.userName)&&!n.userId&&(c.userId=iA()),Object.keys(c).length>0){let w=xt(c);if(a(w))return l(w.message)}let u={...n,...c},p=Rx.filter(w=>{let R=u[w.name];return typeof R=="boolean"?!1:!R?.trim()});if(p.length>0){let w=p.map(M=>`${M.name} (${M.question})`).join("; "),R=p.some(M=>M.name==="userName")?await Qr(e.repoRoot??process.cwd()):null,k=R?` This repository's git user.name is ${JSON.stringify(R)} \u2014 offer it as the default for userName, and use it only if the user agrees.`:"";return l(`Setup incomplete. Ask the user for: ${w}.${k} Then call epiq_project_init again with the answers; what was given so far is saved.`)}let m={userId:u.userId??"",userName:u.userName??""};if(!m.userId||!m.userName)return l("Missing Epiq user id");let f=await Za({cwd:e.repoRoot??process.cwd(),user:m});if(a(f))return f;let{defaultEvents:h,...b}=f.value,E=Rs({root:b.repoRoot});a(E)&&ce.info(E.message);let S=b.warnings.length===0?"Project initialized":`Project initialized, with warnings: ${b.warnings.join(" ")}`;return d(S,{...b,user:m})}});var wn,xl=g(()=>{"use strict";wn=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""})});var aA,wx,Ax=g(()=>{"use strict";xl();aA=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},wx=({commits:e,patch:t})=>{let n=e.map(i=>i.time),o=t.files.map(i=>({...wn(i),changed:i.addedCount+i.removed})).reduce((i,c)=>i===null||c.changed>i.changed?c:i,null),s=t.insertions+t.deletions;return{commits:e.length,authors:[...new Set(e.map(i=>i.author))].sort(),firstCommitAt:n.length?Math.min(...n):null,lastCommitAt:n.length?Math.max(...n):null,files:t.files.length,filesAdded:t.files.filter(i=>i.status==="added").length,filesModified:t.files.filter(i=>i.status==="modified").length,filesDeleted:t.files.filter(i=>i.status==="deleted").length,binaryFiles:t.files.filter(i=>i.binary).length,directories:new Set(t.files.map(i=>aA(i.path))).size,insertions:t.insertions,deletions:t.deletions,net:t.insertions-t.deletions,largestFile:o,concentration:o&&s>0?o.changed/s:0,selfChurn:t.selfChurn,truncated:t.truncated}}});var Xe,Yt,sm,Jo,lA,Q,Il,El,Tx,cA,kx,to,Ri,dA,uA,Qo,mA,pA,fA,dn,Mx,Lx,Px,gA,hA,Dx,Ox,Zo=g(()=>{"use strict";Xe={line:["//"],block:[["/*","*/"]]},Yt={line:["#"],block:[]},sm={line:["--"],block:[]},Jo={line:[],block:[["<!--","-->"]]},lA={line:[],block:[]},Q=(e,t)=>({name:e,comment:t}),Il=Q("TypeScript",Xe),El=Q("JavaScript",Xe),Tx={ts:Il,tsx:Il,mts:Il,cts:Il,js:El,jsx:El,mjs:El,cjs:El,py:Q("Python",{line:["#"],block:[['"""','"""']]}),rb:Q("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:Q("Go",Xe),rs:Q("Rust",Xe),java:Q("Java",Xe),kt:Q("Kotlin",Xe),swift:Q("Swift",Xe),c:Q("C",Xe),h:Q("C",Xe),cc:Q("C++",Xe),cpp:Q("C++",Xe),hpp:Q("C++",Xe),cs:Q("C#",Xe),php:Q("PHP",Xe),scala:Q("Scala",Xe),dart:Q("Dart",Xe),lua:Q("Lua",sm),hs:Q("Haskell",sm),sql:Q("SQL",sm),ex:Q("Elixir",Yt),exs:Q("Elixir",Yt),pl:Q("Perl",Yt),r:Q("R",Yt),jl:Q("Julia",Yt),sh:Q("Shell",Yt),bash:Q("Shell",Yt),zsh:Q("Shell",Yt),vue:Q("Vue",Jo),svelte:Q("Svelte",Jo),html:Q("HTML",Jo),xml:Q("XML",Jo),md:Q("Markdown",Jo),mdx:Q("Markdown",Jo),css:Q("CSS",{line:[],block:[["/*","*/"]]}),scss:Q("CSS",Xe),less:Q("CSS",Xe),yml:Q("YAML",Yt),yaml:Q("YAML",Yt),toml:Q("TOML",Yt),ini:Q("INI",Yt),json:Q("JSON",lA)},cA="Other",kx=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},to=e=>Tx[kx(e)]?.name??cA,Ri=e=>Tx[kx(e)]?.comment??null,dA=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],uA=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,Qo=e=>uA.test(e)||dA.some(t=>t.test(e)),mA=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,pA=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,fA=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,dn=e=>mA.test(e)||pA.test(e)||fA.test(e),Mx=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),Lx=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),Px=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),gA=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,hA=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,Dx=e=>gA.test(e),Ox=e=>hA.test(e)});var _x,vA,im,yA,Fx,am=g(()=>{"use strict";Zo();_x=/\b(TODO|FIXME|HACK|XXX)\b/,vA=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,im=(e,t)=>{let n=e.trim();return n===""?"blank":t&&(t.line.some(r=>n.startsWith(r))||t.block.some(([r])=>n.startsWith(r))||t.block.some(([r])=>r==="/*")&&(n.startsWith("*")||n.startsWith("*/")))?"comment":"code"},yA=(e,t)=>{let n=e.trim();for(let r of[...t.line,...t.block.flat(),"*"])if(n.startsWith(r)){n=n.slice(r.length).trim();break}return n},Fx=({patch:e,repoShareByLanguage:t})=>{let n=new Map,r=0,o=0,s=0,i=0,c=0,u=0;for(let m of e.files){if(m.binary||dn(m.path))continue;let f=Ri(m.path);if(!f||f.line.length===0&&f.block.length===0)continue;let h=to(m.path),b=n.get(h)??{comment:0,code:0};for(let{text:E}of m.added){let S=im(E,f);if(_x.test(E)&&i++,S==="blank"){s++;continue}if(S==="comment"){r++,b.comment++,f&&vA.test(yA(E,f))&&u++;continue}o++,b.code++}for(let{text:E}of m.removedLines)_x.test(E)&&c++;n.set(h,b)}let p=r+o;return{byLanguage:[...n.entries()].map(([m,f])=>({name:m,commentLines:f.comment,codeLines:f.code,share:f.comment+f.code===0?0:f.comment/(f.comment+f.code),repoShare:t?.get(m)??null})).sort((m,f)=>f.commentLines+f.codeLines-(m.commentLines+m.codeLines)),commentLines:r,codeLines:o,blankLines:s,share:p===0?0:r/p,todoLinesAdded:i,todoLinesRemoved:c,commentedOutCodeLines:u}}});var bA,Rl,lm,xA,IA,EA,Bx,$x=g(()=>{"use strict";Zo();xl();bA=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,Rl=6,lm=10,xA=e=>{let t=0;for(let n of e){if(n.trim()===""||n.startsWith(" "))continue;let r=n.length-n.trimStart().length;r>0&&(t===0||r<t)&&(t=r)}return Math.min(Math.max(t,2),8)},IA=(e,t)=>{let n=e.length-e.trimStart().length;if(n===0)return 0;let r=e.slice(0,n).split(" ").length-1;return r>0?r:Math.floor(n/t)},EA=e=>{if(e.length<Rl*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let r=0;r+Rl<=e.length;r++){let o=e.slice(r,r+Rl);if(o.some(c=>c.text.length<3))continue;let s=o.map(c=>c.text).join(`
|
|
109
|
-
`),i=t.get(s);if(i===void 0){t.set(s,{...o[0],at:r});continue}if(i.file!==o[0]?.file)for(let c=0;c<
|
|
110
|
-
`)){if(f.startsWith(
|
|
111
|
-
`)){let f=
|
|
112
|
-
`)){let R=im(w,b);R==="comment"&&S.comment++,R==="code"&&S.code++}u.set(E,S)}let p=new Map;for(let[m,f]of u){let h=f.comment+f.code;h>0&&p.set(m,f.comment/h)}return{languages:r,commentShareByLanguage:p}}});var Yx,Xx=g(()=>{"use strict";Zo();xl();Yx=({patch:e})=>{let t=0,n=0,r=[],o=[],s=0,i=0;for(let c of e.files)if(!(c.binary||dn(c.path))&&Qo(c.path)){t+=c.addedCount,n+=c.removed,c.status==="added"&&r.push(wn(c)),c.status==="deleted"&&o.push(wn(c));for(let{text:u}of c.added)Dx(u)&&s++,Ox(u)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:r,deletedTestFiles:o,skippedTestLinesAdded:s,focusedTestLinesAdded:i}}});var PA,Jx,Qx=g(()=>{"use strict";N();Ax();am();$x();Ux();zx();Kx();Xx();PA=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,Jx=async({repoRoot:e,ref:t,commits:n})=>{let r=await Gx({repoRoot:e,shas:n.map(c=>c.sha)});if(a(r))return l(r.message);let o=r.value,s=PA(n),i=s?await Vx({repoRoot:e,sha:s}):null;return d("Derived issue stats",{ref:t,shape:wx({commits:n,patch:o}),languages:jx({patch:o,languagesBefore:i?.languages??null}),tests:Yx({patch:o}),comments:Fx({patch:o,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:Bx({patch:o})})}});var Zx,eI=g(()=>{"use strict";il();N();wt();D();Zx=e=>{if(a(e))return e;let t=ke(),n=a(t)?{}:t.value.emailLinks,r=a(t)?{}:t.value.contributors,o=Mm(n),s=e.value.map(i=>({...i,authorIdentity:Wy({authorName:i.author,authorEmail:i.authorEmail,owners:o,registry:r})}));return d(e.message,s)}});var DA,Si,OA,tI,nI=g(()=>{"use strict";N();Qx();ft();ee();eI();ii();DA=32,Si=new Map,OA=(e,t)=>{if(Si.set(e,t),Si.size>DA){let n=Si.keys().next();n.done||Si.delete(n.value)}return t},tI=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return l("idOrRef must not be empty");let n=t.length>7?V(t):t.toUpperCase(),r=Ce(e.repoRoot??process.cwd());if(a(r))return l(r.message);let o=r.value,s=Zx(await Fo({repoRoot:o,ref:n}));if(a(s))return l(s.message);let i=s.value.map(m=>({sha:m.sha,time:m.time,author:m.authorIdentity?.resolved?m.authorIdentity.name:m.author,subject:m.subject})),c=[o,n,i.map(m=>`${m.sha}:${m.author}`).join(",")].join(" "),u=Si.get(c);if(u)return d("Derived issue stats",u);let p=await Jx({repoRoot:o,ref:n,commits:i});return a(p)?l(p.message):d("Derived issue stats",OA(c,p.value))}});var es,um,rI=g(()=>{"use strict";es=".claude/skills/epiq/SKILL.md",um="---\nname: epiq\ndescription: Workflow rules for working the epiq issue board \u2014 use the epiq MCP, sync on demand, scope tickets small, keep status/tags accurate, and communicate via comments.\n---\n\n# Epiq board workflow\n\n- **Never test against the real board.** Point any dev server, manual test or test run at a throwaway project, never at this repo's own. Deleting test tickets afterwards does not undo the events. Stop the dev server when you're done rather than leaving it autosyncing.\n- **Use the epiq MCP tools** (`epiq_*`) for all board operations \u2014 never the `epiq` CLI or hand-edited state files.\n- **Never edit the state branch directly.** Don't check it out, don't write to its worktree, don't touch the event log or any file under it by hand or by script \u2014 go through the MCP for every read and write. The event log is the system of record: an edit made outside it bypasses validation and ordering, and can corrupt history in ways no later fix can undo.\n- **Sync is on-demand only.** MCP reads/writes operate on local state and never pull/push automatically. Call `epiq_sync` explicitly when you need the latest remote state or want to publish local changes.\n- **Break work into small, scoped tickets.** One ticket per independent unit of work, not one giant ticket for a whole feature/epic. Small tickets move through the board cleanly and are easier to review.\n- **A small request tightly coupled to a ticket goes into that ticket, not a new one.** When the user asks for a tweak that only makes sense as part of work a ticket already covers \u2014 halving a limit it just introduced, moving a control it just added \u2014 do not file a fresh ticket for it. Record the new requirement as a comment on the original ticket and fold it into the description, move the ticket back to Ongoing if it had already reached Done, prefix the follow-up's commits with that ticket's ref, and add a further `Solution:` comment when it lands, so the ticket's own commit list tells the whole story. `QPPR7PE` is what this avoids: a one-line follow-up to `MBB6WY5` (halve the log cap it had just introduced) that now lives on a ticket of its own. The original does not have to be the ticket you took this session: any ticket open on the board and assigned to you counts. A new ticket is for work that stands on its own \u2014 that someone else could pick up cold, or that needs more than a line or two to describe.\n- **Keep the status column current as work progresses**\n- **Assign the ticket to yourself when you pick it up**, alongside moving it to Ongoing \u2014 so the board shows who is on what, not just what is in flight.\n- **A ticket you file for work you will do this session is assigned to you as you file it.** Filing it unassigned and picking it up a minute later leaves a window where the board shows nobody on it. Picking up a ticket assigned to somebody else is fine \u2014 but ask the user first: it may be mid-flight in another session, and the assignee is what says so.\n- **Take a name as soon as this skill loads, and say it.** Your board identity is `provider/human-name` \u2014 the model provider, a slash, then a short human first name: `claude/peter`, `codex/fred`. Announce it as your first line, exactly `Assuming claude/peter`, and work under it for the whole session so the log reads \"claude/peter did X\" rather than signing the user's name to your work. Before inventing one, call `epiq_contributor_list` and reuse an existing identity for your provider if there is one \u2014 a name is permanent once it has authored anything (`tombstoneContributor` refuses authors), and each new one adds a contributor and an event log file forever. Keep the name stable across sessions; never rename yourself mid-session.\n- **Make the name true with `epiq_actor_assume`, before your first board write.** Announcing alone changes nothing: the writes would still be signed with the user's name. The tool takes the identity for the rest of the session and registers it, so the board carries `claude/peter` rather than the sanitized `claude-peter` the log file name would give. It is idempotent, so re-announcing is free; if it refuses because the server was launched under a name, that name wins \u2014 work under the one it reports and say so. Never claim an attribution the tool did not confirm.\n- **Boot your own MCP instance, and never share one.** `epiq_actor_assume` binds the name to the server process it is called on, so two sessions on one server \u2014 or a session on the user's own instance \u2014 would sign every write with whichever name was assumed last, and the log would fold them into one contributor. Every session therefore needs a server process of its own before its first board call: the one Claude Code spawns for the session counts, and if that never connected (a `CONNECT_TIMEOUT` at boot), start one yourself \u2014 `npx -y -p epiq@latest epiq-mcp` speaks MCP JSON-RPC over stdio, so a small script holding that process and forwarding `tools/call` requests is enough \u2014 rather than waiting on the user or borrowing another session's. Assume the name on *that* process; a restart forgets it, so assume it again before the next write. Kill what you started when the session ends, including the `epiq-mcp` child, which outlives its parent.\n- **When other agents may be running, ask which name to take rather than picking one.** Nothing stops two live agents answering to one name \u2014 the log is a CRDT and takes concurrent writers happily, so they would converge into one indistinguishable identity rather than fail. Another session is likely whenever there is more than one `epiq-mcp` process, another worktree with recent changes, or the user says so; in that case list the existing names for your provider from `epiq_contributor_list` and ask the user which one is free, before `epiq_actor_assume` \u2014 a name once assumed binds the server process, and a second name is refused until it restarts. Ask with the names in the question, not \"which name?\": the user is choosing between identities they can see on the board.\n- **Name the terminal window after the identity.** Several sessions look alike; the name in the tab is how the user tells which window is `claude/peter`. The session cannot reach the terminal itself \u2014 the shell it runs has no tty \u2014 so put the request in the announcement line: `Assuming claude/peter \u2014 please /rename claude/peter so this window carries the name.`\n- **Prefix commits with the ticket ref. **Retrieve the ref programmatically, NEVER DERIVE IT.\\*\\* Read the `ref` field off the MCP response (`epiq_issue_list` and `epiq_board_list` include it on every entry). This is what link-by-reference feature matches on.\n- **Work in a worktree, and leave the root checkout alone.** Take one before the first edit (`EnterWorktree`, or `git worktree add .claude/worktrees/<ref>-<slug>` for a branch that already exists), and never check a feature branch out at the root: the root is where `main` belongs and where the user checks it out themselves, and a branch checked out anywhere is unavailable everywhere else. For the same reason `main` never goes *into* a worktree. Several sessions share this repository at once, so a shared checkout also means one session's `checkout` or `reset` quietly discarding another's work. A fresh worktree needs its own `npm install` before the hooks and suites will run there.\n- **Never work on main, and never merge into it locally. Every change reaches main through a pull request.** Branch before the first edit, push the branch, open the PR, let the gate run, then integrate it. A local merge into `main` looks like it worked and is invisible to everyone else: the work is on nobody's remote, no PR ran the gate over it, and it is one `git fetch origin +main:main` away from vanishing from the branch you are sitting on. That has already happened here \u2014 a tag-filter feature and a scrubber-URL feature lived only in one machine's local `main` for a day, and disappeared the moment somebody synced main with the remote. If you find yourself with commits on local `main`, move them onto a branch and open a PR before doing anything else.\n- **Always rebase onto the target, never merge into it.** Rebase the branch onto the target first, then integrate with a rebase merge \u2014 `gh pr merge --rebase`, never `--merge`. Main stays a flat sequence of ref-prefixed commits, which is what the commit\u2194ticket linking reads. A merge commit adds a subject carrying no ref and buries the branch's commits behind it.\n- **Squashing the branch down first is fine \u2014 one commit per ticket ref.** A branch's worth of fixups is history nobody needs on main, so collapsing it into a single commit (`git rebase -i`, or `gh pr merge --squash` with a ref-prefixed subject) is welcome, provided every commit that lands still opens with its ticket's ref. What the linking cannot survive is a squash *across* refs: fold two tickets' commits into one subject and one of them loses its commits for good. So a branch carrying two refs squashes to two commits, not one \u2014 and check the resulting subject before integrating, because `--squash` defaults to the PR title, which is only right if the title carries the ref.\n- **The git user is the sole author of every commit you write.** Commit under the repo's configured `user.name` / `user.email` and nothing else: no `Co-Authored-By:` line, no `Claude-Session:` line, no `\u{1F916} Generated with` footer, and never an `--author` override naming Claude or a tool. The commit body ends with the last line of prose. This holds for amends and rebases too \u2014 check `git log --format='%an <%ae>%n%b'` over the branch before pushing, because a trailer added by a default template survives a rebase and reaches main unnoticed. It does **not** license rewriting anyone else's authorship: commits by other contributors keep their author, and reassigning them would both misattribute their work and mean force-pushing main.\n- **Tag tickets properly.** Reuse existing tags where they fit (check current issues/tags first) instead of inventing near-duplicates.\n- **Read the ticket's comments before starting, not just its description.** The description is what was known when the ticket was written; comments carry later context \u2014 narrowed scope, a decision already taken, a dead end someone hit, a correction to the original diagnosis. Working from the description alone risks redoing settled work or implementing something that was already ruled out.\n- **Use comments to communicate deviations.** If the work diverges from what the ticket describes \u2014 scope changes, findings, blockers, test results \u2014 record it as a comment on the ticket, not just in chat.\n- When a ticket is done, **Document the outcome in a comment starting with `Solution:`.** Use that exact prefix as the comment's opening line, so `^Solution:` finds every resolved ticket on the board. Say what actually resolved it \u2014 the commit, the approach taken, and anything a reader would otherwise have to reverse-engineer from the diff; a bare commit hash is not a solution. Use the same prefix when a ticket is closed _without_ a code change, and say why.\n- **Attach a screenshot only when a picture carries what words cannot** \u2014 a layout that has to be seen, a rendering bug, a chart whose shape is the point. It is the special case, not a routine part of a `Solution:` comment: most outcomes are better described than photographed, and a screenshot of something a sentence already covers costs everyone the bytes below. When one does earn its place, use `epiq_issue_attachment_add` (it takes a file path) and paste the `markdown` it returns into the comment.\n- **Crop and compress it first.** `epiq_issue_attachment_add` stores the file exactly as it finds it \u2014 only the GUI compresses on upload \u2014 so a raw full-screen capture goes in at full size, up to the 500 KB cap. The blob lands in `.epiq/media/` on the state branch, replicates to every clone, and is never removed: deleting an attachment writes a tombstone and the bytes stay, so time travel can still resolve them. Crop to the region that makes the point, scale it down, and land well under the cap rather than against it. An oversized image is permanent, for everybody \u2014 the same reason the text limits exist.\n- **Be concise.** Titles, descriptions, and comments should be scannable, not essays.\n- If a ticket is blocked, **record the blocker in a comment** and move it to Blocked (or tag it blocked if there is no Blocked column).\n- If a you decide to take a new approach, make sure to document the fork in a new comment, and tag the ticket with a \"fork\" tag, **update the description** to reflect the new plan. Don't leave it as-is and expect readers to infer the change from comments.\n- **Park decisions that are the user's to make.** A design fork, a change with blast radius beyond its ticket, anything you'd want a second opinion on \u2014 file a ticket tagged `human-input-needed` naming the options and the trade-off, then carry on with whatever doesn't depend on the answer. Settling it alone in chat, while nobody is reading, is a decision the user never made.\n- **Findings from a code review get their own tickets**, tagged `from-review`, with the description saying which branch or PR the review covered \u2014 so the provenance survives even if the tag doesn't.\n"});import Sl from"node:fs";import oI from"node:path";var sI,iI=g(()=>{"use strict";rt();N();rI();sI=async(e={})=>{let t=await kt(e.repoRoot??process.cwd());if(a(t))return l(t.message);let n=oI.join(t.value,es);if(Sl.existsSync(n)){if(Sl.readFileSync(n,"utf8")===um)return d("Skill already installed and up to date",{path:n,written:!1});if(!e.force)return l(`${es} already exists and differs from the bundled skill. Pass force:true to overwrite it.`)}try{Sl.mkdirSync(oI.dirname(n),{recursive:!0}),Sl.writeFileSync(n,um,"utf8")}catch(r){return l(r instanceof Error?`Failed to write ${es}: ${r.message}`:`Failed to write ${es}`)}return d(`Installed skill at ${es}`,{path:n,written:!0})}});var lI={};rs(lI,{createMcpServer:()=>aI,resultJson:()=>mm,startMcpServer:()=>$A});import{McpServer as FA}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as BA}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as y}from"zod";var mm,oe,aI,$A,cI=g(()=>{"use strict";N();On();Ex();om();Cx();nI();iI();yi();mm=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),oe=e=>t=>ox(async()=>mm(await e(t))),aI=()=>{let e=new FA({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:y.object({repoRoot:y.string().optional()})},oe(Eu)),e.registerTool("epiq_issue_list",{description:"List Epiq issues. Narrow with boardId, swimlaneId, tag, assignee or query (matched against title and description), and pass brief to get id, ref, title, swimlane, tag names and assignee names only \u2014 descriptions are the bulk of a board. Read one ticket with epiq_issue_get.",inputSchema:y.object({repoRoot:y.string().optional(),includeClosed:y.boolean().optional(),boardId:y.string().optional(),swimlaneId:y.string().optional(),tag:y.string().optional(),assignee:y.string().optional(),query:y.string().optional(),brief:y.boolean().optional()})},oe(Cu)),e.registerTool("epiq_issue_get",{description:"Get one Epiq issue by its full id or its 7-character ref, with its comments in log order. Use this rather than listing the whole board when you already know which issue you want, and rather than epiq_state_get to read a thread.",inputSchema:y.object({idOrRef:y.string().min(1),repoRoot:y.string().optional()})},oe(Nu)),e.registerTool("epiq_issue_stats",{description:"Code stats for one issue, derived from the commits whose subject carries its ref: how big the change is, how it is spread, and how much of it the ticket spent rewriting its own work. Reads git only \u2014 it never touches the board \u2014 so it is safe to call while other work is in flight. No commits carrying the ref reads as a change of zero size, which is not the same as no work: a commit only links if its subject opens with the ref.",inputSchema:y.object({idOrRef:y.string().min(1),repoRoot:y.string().optional()})},async t=>mm(await tI(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:y.object({repoRoot:y.string().optional()})},oe(Pu)),e.registerTool("epiq_board_create",{description:"Create an Epiq board. It comes out without swimlanes; add them with epiq_swimlane_create. Refused while time travelling.",inputSchema:y.object({repoRoot:y.string().optional(),title:y.string().min(1).max(300)})},oe(Du)),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:y.object({repoRoot:y.string().optional(),boardId:y.string().optional()})},oe(_u)),e.registerTool("epiq_swimlane_create",{description:"Create an Epiq swimlane on a board",inputSchema:y.object({repoRoot:y.string().optional(),boardId:y.string().min(1),title:y.string().min(1).max(300)})},oe(Fu)),e.registerTool("epiq_swimlane_title_edit",{description:"Edit an Epiq swimlane title",inputSchema:y.object({repoRoot:y.string().optional(),swimlaneId:y.string().min(1),title:y.string().min(1).max(300)})},oe(Bu)),e.registerTool("epiq_board_title_edit",{description:"Edit an Epiq board title. Refused while time travelling.",inputSchema:y.object({repoRoot:y.string().optional(),boardId:y.string().min(1),title:y.string().min(1).max(300)})},oe(Ou)),e.registerTool("epiq_swimlane_move",{description:"Move/reorder an Epiq swimlane, optionally to another board",inputSchema:y.object({repoRoot:y.string().optional(),swimlaneId:y.string().min(1),boardId:y.string().min(1),position:y.discriminatedUnion("at",[y.object({at:y.literal("start")}),y.object({at:y.literal("end")}),y.object({at:y.literal("before"),sibling:y.string().min(1)}),y.object({at:y.literal("after"),sibling:y.string().min(1)})]).optional()})},oe($u)),e.registerTool("epiq_swimlane_delete",{description:"Delete (archive) an Epiq swimlane. This also archives every issue contained in it.",inputSchema:y.object({repoRoot:y.string().optional(),swimlaneId:y.string().min(1)})},oe(ju)),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue in a swimlane: parentId is the swimlane id (epiq_swimlane_list), never a board id. Optionally set description, tags, and assignees atomically in the same call instead of separate follow-up edits.",inputSchema:y.object({title:y.string().min(1).max(300),parentId:y.string().min(1),repoRoot:y.string().optional(),description:y.string().max(2e4).optional(),tagNames:y.array(y.string().max(60)).max(20).optional(),assigneeNames:y.array(y.string().max(80)).max(20).optional()})},oe(wu)),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),description:y.string().max(2e4),repoRoot:y.string().optional()})},oe(Mu)),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),title:y.string().min(1).max(300),repoRoot:y.string().optional()})},oe(Lu)),e.registerTool("epiq_issue_tag_add",{description:"Add a tag to an Epiq issue, or to many at once with issueIds, creating the tag if it does not exist",inputSchema:y.object({issueId:y.string().min(1).optional(),issueIds:y.array(y.string().min(1)).min(1).max(200).optional(),tagName:y.string().min(1).max(60),repoRoot:y.string().optional()})},oe(Uu)),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),tagId:y.string().min(1),repoRoot:y.string().optional()})},oe(qu)),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:y.object({boardId:y.string().min(1).optional(),repoRoot:y.string().optional()})},oe(Yu)),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:y.object({contributorId:y.string().min(1),repoRoot:y.string().optional()})},oe(Vu)),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:y.object({tagId:y.string().min(1),repoRoot:y.string().optional()})},oe(Hu)),e.registerTool("epiq_tag_restore",{description:"Put back a tag deleted with epiq_tag_remove, on every ticket that still carried it.",inputSchema:y.object({tagId:y.string().min(1),repoRoot:y.string().optional()})},oe(Wu)),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:y.object({contributorId:y.string().min(1),repoRoot:y.string().optional()})},oe(Ku)),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:y.object({issueId:y.string().min(1),assigneeId:y.string().min(1).optional(),self:y.boolean().optional(),assigneeName:y.string().min(1).max(80).optional(),createUnlinked:y.boolean().optional(),repoRoot:y.string().optional()})},oe(zu)),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),assigneeId:y.string().min(1),repoRoot:y.string().optional()})},oe(Xu)),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),body:y.string().min(1).max(4e3),repoRoot:y.string().optional()})},oe(Ju)),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:y.object({issueId:y.string().min(1),filePath:y.string().min(1),name:y.string().min(1).max(200).optional(),repoRoot:y.string().optional()})},oe(xu)),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:y.object({commentId:y.string().min(1),repoRoot:y.string().optional()})},oe(Qu)),e.registerTool("epiq_issue_comment_edit",{description:"Replace the body of one of your own comments on an Epiq issue",inputSchema:y.object({commentId:y.string().min(1),body:y.string().min(1).max(4e3),repoRoot:y.string().optional()})},oe(Zu)),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:y.object({issueId:y.string().min(1),repoRoot:y.string().optional()})},oe(Tu)),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue, or many at once with issueIds \u2014 one call, an outcome per ticket",inputSchema:y.object({issueId:y.string().min(1).optional(),issueIds:y.array(y.string().min(1)).min(1).max(200).optional(),repoRoot:y.string().optional()})},oe(Au)),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane (parentId is the swimlane id), or many at once with issueIds \u2014 one call, an outcome per ticket",inputSchema:y.object({issueId:y.string().min(1).optional(),issueIds:y.array(y.string().min(1)).min(1).max(200).optional(),parentId:y.string().min(1),position:y.discriminatedUnion("at",[y.object({at:y.literal("start")}),y.object({at:y.literal("end")}),y.object({at:y.literal("before"),sibling:y.string().min(1)}),y.object({at:y.literal("after"),sibling:y.string().min(1)})]).optional(),repoRoot:y.string().optional()})},oe(ku)),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:y.object({name:y.string().min(1).max(80),repoRoot:y.string().optional()})},oe(Gu)),e.registerTool("epiq_contributor_email_link",{description:"Bind a git author address to a contributor, so their commits and their board activity read as one person. Defaults to you; pass contributorId to link a colleague who does not use epiq, whose commits otherwise never resolve. The address the repository's git is configured with links itself on your first write, so this is for older addresses and for other people. An address two contributors claim resolves to neither, and the reply says so.",inputSchema:y.object({email:y.string().min(1).max(254),contributorId:y.string().min(1).optional(),repoRoot:y.string().optional()})},oe(em)),e.registerTool("epiq_contributor_email_unlink",{description:"Retract a link between a git address and a contributor. Allowed only to whoever wrote the link and to the contributor it names, so nobody can strip links that are neither theirs nor about them. Forward-only: the address stops resolving and the event stays in the log.",inputSchema:y.object({email:y.string().min(1).max(254),contributorId:y.string().min(1).optional(),repoRoot:y.string().optional()})},oe(tm)),e.registerTool("epiq_contributor_email_suggest",{description:"Addresses in this repository's history that look like yours and nobody has claimed, for the user to confirm. Run it once after this feature reaches a board with history: the address git is configured with links itself, but older ones do not, and until they are linked those commits show a raw git name. Show the list and link only what the user confirms \u2014 each link is permanent and replicates to every clone.",inputSchema:y.object({repoRoot:y.string().optional()})},oe(rm)),e.registerTool("epiq_contributor_email_list",{description:"Every git address the board has bound to a contributor, and who holds it. An address with more than one claimant is flagged contested and resolves to none of them, which is the state nothing else reports.",inputSchema:y.object({repoRoot:y.string().optional()})},oe(nm)),e.registerTool("epiq_project_init",{description:`Set up a new Epiq board in a git repository without the TUI. Runs in the repository at repoRoot (default: the current directory), which must have no uncommitted changes. The first time on a machine it also records the user's setup: ask the user for userName (how they want to appear on the board), preferredEditor (e.g. "vim" or "code --wait") and autoSync (whether the TUI and GUI sync with the remote on their own) and pass them here; called without them it fails naming what is still missing, keeping whatever was given. It fills in answers the machine lacks and refuses to change ones it has. Pass the user's name, never your own agent identity. Commits the state branch and .epiq/project.json and tries to push both; a push that fails is a warning, not an error. Afterwards the other tools work in that repository.`,inputSchema:y.object({repoRoot:y.string().optional(),userName:y.string().min(1).max(80).optional(),preferredEditor:y.string().min(1).max(200).optional(),autoSync:y.boolean().optional()})},oe(Nx)),e.registerTool("epiq_skill_install",{description:"Write the official Epiq workflow skill into the repository at .claude/skills/epiq/SKILL.md, so agents working there follow the same board rules. Run it after epiq_project_init, not before: the new file is an uncommitted change that init refuses. In a project that already has a board, run it any time. Refuses to overwrite a differing file unless force is true; an identical file is left alone.",inputSchema:y.object({repoRoot:y.string().optional(),force:y.boolean().optional()})},oe(sI)),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:y.object({repoRoot:y.string().optional()})},oe(Ru)),e},$A=async()=>{let e=aI(),t=new BA;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:jA}=await Promise.resolve().then(()=>(yr(),bm)),{isFail:UA}=await Promise.resolve().then(()=>(N(),hm)),{parseMcpArgs:HA}=await Promise.resolve().then(()=>(Em(),Im)),ts=HA(process.argv.slice(2));ts.kind==="error"&&(console.error(ts.message),process.exit(1));ts.kind==="print"&&(process.stdout.write(ts.text),process.exit(0));if(ts.kind==="name"){let e=jA(ts.name,"The name argument");UA(e)&&(console.error(e.message),process.exit(1))}var{setVirtualNodesEnabled:WA}=await Promise.resolve().then(()=>($c(),ex));WA(!1);var{startMcpServer:qA}=await Promise.resolve().then(()=>(cI(),lI));await qA();
|
|
101
|
+
`,Yd.writeFileSync(t,n,"utf8"),ie.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),d("Local epiq paths ignored",!0)}});import PC from"node:fs";import Xd from"node:path";var DC,le,tl,OC,_C,Jd=g(()=>{"use strict";Xv();Fi();nt();ze();Js();Ur();$();Fr();N();Q();rn();Xc();DC=async e=>{let t=await W({cwd:e,args:["status","--porcelain"]});return l(t)?t:d("Checked git diff",t.value.stdout.split(`
|
|
102
|
+
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},le=(e,t)=>a(`[${e}] ${t}`),tl=async({cwd:e,user:t})=>{let n=Wi(),r=await Lt(e);if(l(r))return le(1,r.message);let o=r.value,s=await tp(o);if(l(s))return le(2,s.message);if(s.value)return le(2,`Cannot initialize Epiq while a git operation is in progress: ${s.value}`);let i=await DC(o);if(l(i))return le(2.5,i.message);if(i.value.length>0)return le(3,`Cannot initialize Epiq with uncommitted changes (${i.value.join(", ")}). Commit or stash your changes first.`);if(Is(o))return le(4,"Epiq project already initialized");let{userId:c,userName:u}=t;if(!c||!u)return le(5,"Missing Epiq user id");let p=await sh(o);if(l(p))return le(6,p.message);let m=n.stateBranch,f=await $i({repoRoot:o,branch:m});if(l(f))return le(6,f.message);if(f.value)return le(6,`State branch already exists: ${m}`);let h=await OC({repoRoot:o,stateBranch:m});if(l(h))return le(6,h.message);if(h.value)return _C({repoRoot:o,stateBranch:m});let b=await Qc({repoRoot:o,stateBranchName:m});if(l(b))return le(6,b.message);let I=bs();if(l(I))return le(7,I.message);let C=Xd.join(Ar(),n.projectId),T=await lr({repoRoot:o,stateBranchRoot:C,stateBranchName:m});if(l(T))return le(8,T.message);let S=Xd.join(C,".epiq");PC.mkdirSync(S,{recursive:!0});let M=zg({userId:c,userName:u});if(l(M))return le(9,M.message);for(let fI of M.value){let ym=Rg({event:fI,rootDir:C});if(l(ym))return le(9,ym.message)}let L=sr({userId:c}),F=ca(C,L);if(l(F))return le(9,F.message);let j=Yc(C,n);if(l(j))return le(9,j.message);let z=await Ca({stateBranchRoot:C,eventFileName:L});if(l(z))return le(10,z.message);let X=await Re.stage({cwd:C,pathspec:[ot]});if(l(X))return le(10,X.message);let ne=await io({cwd:C,message:"[epiq:init]"});if(l(ne))return le(10,ne.message);let qe=await Yv(o);if(l(qe))return le(11,qe.message);let q=nc({repoRoot:o,fileContents:n});if(l(q))return le(12,q.message);let se=await Re.stage({cwd:o,pathspec:[".epiq/project.json",".gitignore"]});if(l(se))return le(13,se.message);let gt=await Re.commit({cwd:o,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(l(gt))return le(13,gt.message);let os=[],hm=await W({cwd:o,args:["push","-u","origin","HEAD"]});l(hm)&&os.push(`[init:14] ${hm.message}`);let vm=await Xs({repoRoot:o,stateBranchRoot:C});return l(vm)&&os.push(`[init:15] ${vm.message}`),d("Project initialized",{repoRoot:o,projectId:n.projectId,stateBranch:m,stateBranchRoot:C,defaultEvents:M.value,warnings:os})},OC=async({repoRoot:e,stateBranch:t})=>{let n=await Ln({repoRoot:e});if(l(n))return a(n.message);if(!n.value)return d("No remote",!1);let r=await gs({repoRoot:e,branch:t});return l(r)?a(`Could not ask origin whether ${t} exists: ${r.message}`):r},_C=async({repoRoot:e,stateBranch:t})=>{let n=await W({cwd:e,args:["fetch","origin",t]});if(l(n))return le(6,n.message);let r=await W({cwd:e,args:["show",`origin/${t}:${ot}`]});if(l(r))return le(6,[`This repository is already an epiq project: origin has the state branch ${t}.`,"Initialising again would mint a second id for the same board.","","The branch was written before branches carried their identity, so restore",`${ot} from a checkout that has it, for example:`,"",` git show origin/main:${ot} > ${ot}`,"","and commit it; every later boot then stamps the branch, and the next clone adopts it."].join(`
|
|
103
|
+
`));let o;try{o=JSON.parse(r.value.stdout)}catch(I){return le(6,`The identity on origin/${t} is not readable: ${I instanceof Error?I.message:String(I)}`)}let s=nc({repoRoot:e,fileContents:o});if(l(s))return le(12,s.message);let i=await Re.stage({cwd:e,pathspec:[ot]});if(l(i))return le(13,i.message);let c=await Re.commit({cwd:e,message:"[epiq:adopt-project]",pathspec:[ot]});if(l(c))return le(13,c.message);let u=bs();if(l(u))return le(7,u.message);let p=Xd.join(Ar(),o.projectId),m=await Ys({repoRoot:e,stateBranchName:t});if(l(m))return le(8,m.message);let f=await lr({repoRoot:e,stateBranchRoot:p,stateBranchName:t});if(l(f))return le(8,f.message);let h=[],b=await W({cwd:e,args:["push","-u","origin","HEAD"]});return l(b)&&h.push(`[init:14] ${b.message}`),d("Adopted the project origin already holds",{repoRoot:e,projectId:o.projectId,stateBranch:o.stateBranch,stateBranchRoot:p,defaultEvents:[],warnings:h})}});var di,Jv,Qv=g(()=>{"use strict";Et();Tr();$();N();Jd();pe();$e();D();di=(e,t)=>a(`[${e}] ${t}`),Jv=async()=>{Z("");let e=As();if(!e.isSetupDone||!e.userName)return di(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let t=ae(),n=t.userName,r=t.userId;if(!r||!n)return di(5,"Missing Epiq user id");let o=await tl({cwd:process.cwd(),user:{userId:r,userName:n}});if(l(o))return o;let s="Project initialized!";for(let h of o.value.warnings)s+=` Warn: ${h}`;let c=Bn(o.value.defaultEvents).filter(l);if(c.length>0)return di(16,c.map(h=>h.message).join(`
|
|
104
|
+
`));let u=Ee();if(l(u))return di(16,u.message);let{rootNodeId:p,nodes:m}=u.value,f=m[p];return f?(H.navigate({contextNode:f,selectedIndex:0}),A({hasProjectDefinition:!0}),d(s,null)):di(16,"Unable to resolve initialized root node")}});import{ulid as FC}from"ulid";function Zd(e){let t=ey();if(l(t))return t;let{contextNode:n,nodes:r}=v();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=Te(o.id),i=s.findIndex(({id:p})=>p===n.id);if(i<0)return a("Current node not found among siblings");let c=s[i+e];if(!c)return a("Missing sibling node");let u=ty({id:t.value.id,parentId:c.id,position:{at:"end"}});return l(u)?u:ny(u.value)}function mi(e,t=1){let n=ey();if(l(n))return n;let{contextNode:r,selectedIndex:o}=v(),s=Te(r.id),i=Math.min(Math.max(o+e*t,0),s.length-1),c=i===o?void 0:s[i];if(!c)return a("Missing sibling node");let u=ty({id:n.value.id,parentId:r.id,position:{at:e===1?"after":"before",sibling:c.id}});return l(u)?u:ny(u.value)}var Zv,un,ui,ey,Qd,ty,ny,eu=g(()=>{"use strict";$();$();N();Ht();D();Zv=null,un=()=>structuredClone(Zv),ui=e=>{Zv=e},ey=()=>{let{contextNode:e,selectedIndex:t}=v(),r=Te(e.id)[t];return r?d("Resolved selected child",r):a("Target node not found")},Qd=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Te(t).filter(o=>o.id!==e);return xa(r,n)},ty=({id:e,parentId:t,position:n={at:"end"}})=>{let r=fe();if(l(r))return a("Unable to resolve user ID");let o=Qd({parentId:t,id:e,position:n});return l(o)?o:d("Created pending move state",{id:FC(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},ny=e=>{ui(e);let t=qs(e,!0);return l(t)?t:d("Node moved successfully",t.value)}});import{ulid as BC}from"ulid";var ry,Go,oy,sy=g(()=>{"use strict";Et();eu();$();$();Ut();Pe();N();Ht();pe();D();Q();ry=()=>{let e=un();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=v().nodes[n];if(!r)return a("Move parent not found");let o=Te(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(H.navigate({contextNode:r,selectedIndex:o}),d("Synchronized navigation to moved node",null))},Go=(e,t="Moved preview")=>{if(l(e))return un()&&A({mode:x.MOVE}),e;let n=ry();return l(n)?n:(A({mode:x.MOVE}),d(t,null))},oy=async()=>{let e=fe();if(l(e))return a("Unable to resolve user ID");let{modifier:t}=me().commandMeta,{contextNode:n,selectedIndex:r}=v(),o=Te(n.id)[r];if(!o)return A({mode:x.DEFAULT}),a("No move target");if(t==="start"){if(o.readonly)return a("Target node is read-only");if(r===-1)return a("No item selected");if(!o.parentNodeId)return a("Target has no parent");let s=Te(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],u=s[i+1],p=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},m=Qd({parentId:o.parentNodeId,id:o.id,position:p});return l(m)?m:(ui({id:BC(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:m.value.rank},...O(e.value)}),A({mode:x.MOVE}),d("Move initialized",null))}if(t==="next")return Go(mi(1));if(t==="previous")return Go(mi(-1));if(t==="jump-next")return Go(mi(1,Gs));if(t==="jump-previous")return Go(mi(-1,Gs));if(t==="to-next")return Go(Zd(1));if(t==="to-previous")return Go(Zd(-1));if(t==="confirm"){let s=un();if(!s)return a("No pending move to confirm");let i=await xe();if(l(i))return i;let c=_([s],i.value);if(l(c))return c;let u=ry();return l(u)?u:(ui(null),A({mode:x.DEFAULT}),d("Moved item",null))}return t==="cancel"?(ui(null),A({mode:x.DEFAULT}),d("Cancelling move",null)):a("Invalid move modifier")}});import{monotonicFactory as $C,ulid as jC}from"ulid";var UC,nl,tu=g(()=>{"use strict";N();UC=$C(),nl=({name:e,parent:t,rank:n,user:{userId:r}})=>{let o=UC();return d("Created issue events",[{id:jC(),userId:r,action:"add.issue",payload:{id:o,parent:t,name:e,rank:n}}])}});import{ulid as rl}from"ulid";var iy,ay=g(()=>{"use strict";Et();tu();$();$();Ut();en();N();de();Ht();D();Q();iy=async(e,t)=>{let n=fe();if(l(n))return a("Unable to resolve user ID");let r=await xe();if(l(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=v(),u=p=>{let m=_([p],o);if(l(m))return m;let f=R.getNode(m.value[0].result.id);if(!f)return a("Created node not found");if(!f.parentNodeId)return m;let h=R.getNode(f.parentNodeId);return h?(H.navigate({contextNode:h,selectedIndex:R.getSiblings(f.parentNodeId).findIndex(({id:b})=>b===f.id)}),m):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:p}=v(),m=R.getNode(p);if(!m)return a("Workspace not found");let f=$n(m.id,n.value,o);return l(f)?f:u({id:rl(),action:"add.board",payload:{id:rl(),name:t.inputString,parent:m.id,rank:f.value},...O(n.value)})}if(t.modifier==="swimlane"){let p=At(s,"BOARD");if(l(p))return a("Unable to add swimlane in this context");let m=$n(p.value.id,n.value,o);return l(m)?m:u({id:rl(),action:"add.swimlane",payload:{id:rl(),name:t.inputString,parent:p.value.id,rank:m.value},...O(n.value)})}if(t.modifier==="issue"){let p=ve(i.id)[c],m=i.context==="SWIMLANE"?i:i.context==="BOARD"&&p?.context==="SWIMLANE"?p:(()=>{let M=At(s,"SWIMLANE");return l(M)?null:M.value})();if(!m)return a("Unable to add issue in this context");let f=$n(m.id,n.value,o);if(l(f))return f;let h=nl({name:t.inputString,parent:m.id,rank:f.value,user:n.value});if(l(h))return h;let b=h.value,I=_([...b],o);if(l(I))return I;if(!I.value[0])return a("Issue creation failed");let S=b.find(M=>M.action==="add.issue")?.payload.id;return S?(H.navigate({contextNode:m,selectedIndex:R.getSiblings(m.id).findIndex(({id:M})=>M===S)}),d("Issue created",null)):a("Unable to determine ticket id")}return d("Success",null)}});import pi from"node:fs";import HC from"node:path";import{z as Kr}from"zod";var fi,WC,qC,GC,ly,zC,cy,dy,uy,nu=g(()=>{"use strict";N();rn();pe();kd();Q();fi="command-history.json",WC=20,qC=Kr.object({projectId:Kr.string().min(1),commands:Kr.array(Kr.string()),lastUsedAt:Kr.number().finite()}),GC=Kr.object({projects:Kr.array(qC)}),ly=()=>{let e=ai();return l(e)?e:d("Resolved command history path",HC.join(e.value,fi))},zC=()=>{try{let e=Ne(process.cwd());return l(e)?null:e.value}catch{return null}},cy=e=>{if(!pi.existsSync(e))return d("No command history recorded",{state:"read",projects:[]});let t;try{t=pi.readFileSync(e,"utf8")}catch(o){return a(`Unable to read ${fi}: ${o instanceof Error?o.message:String(o)}`)}let n;try{n=JSON.parse(t)}catch(o){return d("Unparsable command history",{state:"corrupt",reason:`Invalid ${fi}: ${o instanceof Error?o.message:String(o)}`})}let r=GC.safeParse(n);return r.success?d("Read command history",{state:"read",projects:r.data.projects}):d("Command history in an unknown shape",{state:"corrupt",reason:`Invalid ${fi} shape: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`})},dy=({root:e})=>{let t=hn(e);if(l(t))return a(t.message);let n=ly();if(l(n))return n;let r=cy(n.value);if(l(r))return r;let o=r.value;if(o.state==="corrupt")return a(o.reason);let s=o.projects.find(i=>i.projectId===t.value);return d("Read command history",s?.commands.slice(0,Ps)??[])},uy=({commands:e,root:t=zC(),now:n=Date.now()})=>{if(t===null)return d("No project; command history not stored",null);let r=hn(t);if(l(r))return a(r.message);let o=ly();if(l(o))return o;let s=o.value,i=cy(s);if(l(i))return i;let c=i.value,u=c.state==="read"?c.projects:[],p=[{projectId:r.value,commands:e.slice(0,Ps),lastUsedAt:n},...u.filter(f=>f.projectId!==r.value)].sort((f,h)=>h.lastUsedAt-f.lastUsedAt).slice(0,WC),m=`${s}.${process.pid}.tmp`;try{pi.writeFileSync(m,JSON.stringify({projects:p},null,2)+`
|
|
105
|
+
`,"utf8"),pi.renameSync(m,s)}catch(f){try{pi.rmSync(m,{force:!0})}catch{}return a(`Unable to write ${fi}: ${f instanceof Error?f.message:String(f)}`)}return d("Stored command history",null)}});var VC,py,KC,my,fy,YC,XC,gy,hy=g(()=>{"use strict";gn();nt();ze();Js();ka();nd();Ta();nu();co();Ur();$();tr();N();rn();pe();D();Vs();Q();Ra();VC=e=>e.some(t=>t.action==="init.workspace"),py=async(e,t)=>{let n=tt(e);return l(n)?a(n.message):vs({cwd:t,branch:n.value})},KC=e=>{let t=Ne(process.cwd());if(l(t))return!1;let n=be({repoRoot:t.value});return!l(n)&&n.value===e},my=!1,fy=async e=>{my=!0;try{return await YC(e)}finally{my=!1}},YC=async e=>{let t=be({repoRoot:e});if(l(t))return No(3,t.message);let n=t.value,r=await lr({repoRoot:e,stateBranchRoot:n,stateBranchName:Wi().stateBranch});if(l(r))return No(3,r.message);let o=Wt(n),s=cn(n);if(l(s))return No(3,s.message);if(!VC(s.value.events)){let f=await Qs({worktreeRoot:n,operation:"boot pull",fn:()=>Aa(n,()=>py(e,n))});if(l(f)?logger.info(3,f.message):f.value===null?logger.info(3,"Another process holds the state worktree, skipped pull"):l(f.value)&&logger.info(3,f.value.message),o=Wt(n),s=cn(n),l(s))return No(3,s.message)}let{events:i,unreadable:c}=s.value,u=Rn(i,c);if(l(u))return No(4,u.message);Io(n,o),A({hasProjectDefinition:!0,hasInitializingEvents:!!i.length});let p=Ns({root:e});l(p)&&logger.info(p.message);let m=dy({root:e});return l(m)&&logger.info(m.message),Cf(l(m)?[]:m.value),d("Loaded project",void 0)},XC=async e=>{let t=be({repoRoot:e});if(l(t))return a(t.message);let n=t.value,r=await Ln({repoRoot:n});if(l(r))return a(r.message);if(!r.value)return d("No remote to pull",void 0);let o=await Qs({worktreeRoot:n,operation:"boot pull",fn:()=>Aa(n,()=>(Ro("Pulling"),py(e,n)))});if(l(o))return Be(o.message);if(o.value===null)return d("Another process holds the state worktree",void 0);let s=o.value;if(l(s))return hs(s.message)?(Sa("Offline"),d("Offline",void 0)):Be(s.message);if(!s.value)return Hr("Already synced"),d("Already synced",void 0);if(!KC(n))return d("Project changed during the pull",void 0);let i=od(n);return l(i)?i:(Hr("Pulled"),d("Pulled and reloaded",void 0))},gy=e=>{XC(e).then(t=>{l(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${Yg(t)}`)})}});import JC from"node:os";import vy from"node:path";var QC,ZC,yy,by=g(()=>{"use strict";hy();co();N();pe();D();Q();QC=e=>e==="~"||e.startsWith("~/")?vy.join(JC.homedir(),e.slice(1)):e,ZC=(e,t)=>{let n=e.trim();if(!n)return a("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?d("Resolved recent project",o.root):a(`No recent project #${n}`)}let r=Ne(vy.resolve(QC(n)));return l(r)?a(`No epiq project at ${n}`):d("Resolved project path",r.value)},yy=async()=>{let e=sa();if(Z(""),v().hasProjectDefinition)return a("Already in a project; run epiq from another directory");let t=Gi({exclude:process.cwd()}),n=l(t)?[]:t.value,r=ZC(e,n);if(l(r))return a(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(c){return a(`Unable to enter ${o}: ${c instanceof Error?c.message:String(c)}`)}let i=await fy(o);return l(i)?(process.chdir(s),a(i.message)):(gy(o),d(`Opened ${Np(o)}`,null))}});var ol,ru=g(()=>{"use strict";Et();$();$();N();D();ol=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=v(),s=Wc(n,t);if(l(s))return a(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=Gn();if(l(u))return u;let p=Bn(i),{fatal:m,skipped:f}=rr(p);if(m.length>0)return Gn(),A(o),a(m.map(b=>b.message).join(", "));or(f);let h=v().nodes[e];return h?(H.navigate({contextNode:h,selectedIndex:r}),d("",{unappliedEvents:c})):(Gn(),A(o),a("Board did not exist at that date"))}});var xy,Iy=g(()=>{"use strict";xy=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 eA,tA,nA,sl,il,Yr,Ey,Sy,ou=g(()=>{"use strict";at();gi();$();Uc();Pe();N();Iy();D();eA=20,tA=16,nA=150,sl=null,il=null,Yr=()=>{sl!==null&&(clearInterval(sl),sl=null),il!==null&&(clearTimeout(il),il=null)},Ey=()=>{Yr(),A({mode:x.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Sy=({events:e,startTime:t,durationMs:n})=>{Yr();let r=e.length,o=cs(e.map(f=>Ir(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=xy(o),c=Math.max(1,Math.round(n*eA/1e3)),u=Math.max(Math.round(n/c),tA),p=0,m=0;A({mode:x.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),sl=setInterval(()=>{p++;let f=p/c,h=[],b,I;for(;m<r&&i[m]<=f;){let T=e[m],S=qs(T);if(l(S)){if(Eo(S)){m++;continue}Ey();return}h.push(...jc(T)),b=T,I=o[m],m++}if(m>=r||p>=c){for(;m<r;m++){let S=qs(e[m]);if(l(S)&&!Eo(S))break}let T=v().replay;A({unappliedEvents:[],replay:T&&{...T,progress:1,appliedCount:r}}),Yr(),il=setTimeout(Ey,nA);return}let C=v().replay;A({unappliedEvents:e.slice(m),replay:{progress:Math.min(1,f),appliedCount:m,totalCount:r,startTime:t,endTime:s,currentTime:b?I??C?.currentTime??t:C?.currentTime??t,currentLabel:b?su(b):C?.currentLabel??"",flashNodeIds:b?[...new Set(h)]:C?.flashNodeIds??[]}})},u)}});var Ry,Ny=g(()=>{"use strict";nt();at();$();$();Pe();en();N();pe();D();ws();ru();ou();Ry=async()=>{let e=At(v().breadCrumb,"BOARD");if(l(e))return e;let t=await Lt(process.cwd());if(l(t))return a("Unable to locate repo root");let n=be({repoRoot:t.value});if(l(n))return n;let{modifier:r,inputString:o}=me().commandMeta;if(Yr(),r==="now"){let c=$r(n.value);if(l(c))return a(c.message);let u=Gn();if(l(u))return u;let p=Bn(c.value),{fatal:m,skipped:f}=rr(p);return m.length>0?a(m.map(h=>h.message).join(", ")):(or(f),A({mode:x.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),d("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let c=qc(n.value);if(l(c))return c;let u=r==="prev"?v().eventLog.at(-1):v().unappliedEvents.at(0),p=u===void 0?null:Ir(u),m=(u===void 0?null:c.value.get(u.id)??null)??(p===null?null:ls(p));if(m===null)return a(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?m:m+1}else{let c=kr(r||o.trim());if(!c)return a("Invalid peek date");s=c.getTime()}let i=ol({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return l(i)?i:(A({mode:x.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),d("Peeking",!0))}});var Cy,Ay=g(()=>{"use strict";nt();en();N();pe();D();ws();ru();ou();Cy=async()=>{let e=At(v().breadCrumb,"BOARD");if(l(e))return e;let t=await Lt(process.cwd());if(l(t))return a("Unable to locate repo root");let n=be({repoRoot:t.value});if(l(n))return n;let{modifier:r,inputString:o}=me().commandMeta,{dateInput:s,durationInput:i}=Ji(r,o);if(Yr(),v().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let c=kr(s);if(!c)return a("Invalid replay date");let u=i?Xi(i):15e3;if(u===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let p=c.getTime(),m=v(),f=ol({boardId:e.value.id,targetTime:p,stateBranchRoot:n.value,selectedIndex:-1});if(l(f))return f;let{unappliedEvents:h}=f.value;return h.length===0?(Gn(),A(m),d("Nothing to replay from that point",!0)):(Sy({events:h,startTime:p,durationMs:u}),d("Replaying board history",!0))}});import{spawn as oA}from"node:child_process";var sA,wy,Ty=g(()=>{"use strict";N();sA=()=>{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"]}}},wy=async e=>new Promise(t=>{let{command:n,args:r}=sA();try{let o=oA(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(a(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?d("Copied to clipboard",null):a(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(a(`Clipboard tool not available (${n})`))}})});var hi,My,ky=g(()=>{"use strict";N();D();Ty();mt();mo();Dn();hi=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await wy(e);return l(n)?n:d(`Copied ${t} to clipboard`,null)},My=async e=>{let{breadCrumb:t,selectedNode:n}=v(),r=Ts({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return a("Nothing selected to copy from");switch(e.modifier){case je.REF:return hi(V(o.id),"ref");case je.TITLE:return hi(o.title,"title");case je.DESCRIPTION:return r?hi(r.props?.description??"","description"):a("No issue in scope");case je.TAGS:{if(!r)return a("No issue in scope");let s=yn(r).map(({name:i})=>i);return hi(s.join(", "),"tags")}case je.ASSIGNEES:{if(!r)return a("No issue in scope");let s=bn(r).map(({name:i})=>i);return hi(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}}});var Ly,Py=g(()=>{"use strict";ka();Pe();N();pe();D();Ly=async()=>{Z(""),A({mode:x.DEFAULT});let e=Ee();if(l(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");A({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Ma();return l(t)?(A({syncStatus:{msg:t.message,status:"failed"}}),t):(A({mode:x.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as Dy}from"ulid";var Oy,_y=g(()=>{"use strict";$();$();ce();N();D();Ba();Q();Ut();Oy=async()=>{let e=fe();if(l(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=ve(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await xe();if(l(o))return o;if(r.context==="COMMENT"){let s=r.id,i=U(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=v().nodes[i];if(!c||!U(c))return a("Unable to resolve comment issue");let u=c.log?.filter(_h).find(p=>p.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):_([{id:Dy(),action:"delete.issue.comment",payload:{id:s,issue:i},...O(e.value)}],o.value):a("Unable to resolve comment")}return _([{id:Dy(),action:"delete.node",payload:{id:r.id},...O(e.value)}],o.value)}});import{ulid as iA}from"ulid";var Fy,By=g(()=>{"use strict";$();$();on();ce();N();Ht();D();Q();jt();Fy=async()=>{let e=fe();if(l(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=ve(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!U(r))return a("Cannot close in this context");let o=v().nodes[Ce];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await xe();if(l(s))return s;let i=s.value,c=En(o.id,r.id,{at:"end"},e.value,i);if(l(c))return c;let u=_([{id:iA(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...O(e.value)}],i);return l(u)?u:d("Issue closed",null)}});var al,iu=g(()=>{"use strict";al=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null}});import{ulid as aA}from"ulid";var $y,jy=g(()=>{"use strict";$();$();iu();on();ce();N();de();Ht();D();Q();jt();$y=async()=>{let e=fe();if(l(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=ve(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?d("Resolved ticket",r):Yt(r.id,"TICKET");if(l(o))return a("Cannot reopen in this context");let s=o.value,i=v().nodes[Ce];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!U(s))return a("Target node is not issue");let c=al(s);if(!c)return a("Unable to resolve previous parent from issue history");if(c===i.id)return a("Previous parent resolves to closed swimlane");let u=v().nodes[c];if(!u)return a("Previous parent no longer exists");let p=await xe();if(l(p))return p;let m=p.value,f=En(u.id,s.id,{at:"end"},e.value,m);if(l(f))return f;let h=_([{id:aA(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...O(e.value)}],m);return l(h)?h:d("Issue reopened",null)}});import{ulid as lA}from"ulid";var Uy,Hy=g(()=>{"use strict";$();$();N();pe();D();Q();jt();Uy=async()=>{let e=fe();if(l(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=ve(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=sa();if(!o)return a("Provide a title");let s=await xe();return l(s)?s:_([{id:lA(),action:"edit.title",payload:{id:r.id,name:o},...O(e.value)}],s.value)}});import{ulid as cA}from"ulid";var Wy,qy=g(()=>{"use strict";de();$();$();ce();N();pe();D();Q();jt();Wy=async()=>{let e=fe();if(l(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=me().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=R.findTagByName(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=v();if(!s)return a("Invalid untag target");let i=Yt(s.id,"TICKET");if(l(i))return a("Unable to untag issue in this context");let c=i.value;if(!U(c))return a("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let p=await xe();return l(p)?p:_([{id:cA(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...O(e.value)}],p.value)}});import{ulid as au}from"ulid";var Gy,zy=g(()=>{"use strict";de();$();$();ce();N();pe();D();Q();jt();Gy=async()=>{let e=fe();if(l(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=me().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=v();if(!o)return a("Invalid tag target");let s=Yt(o.id,"TICKET");if(l(s))return a("Unable to tag issue in this context");let i=s.value;if(!U(i))return a("Target node is not issue");let c=await xe();if(l(c))return c;let u=R.findTagByName(r),p=u?.id??au();return(i.props.tags??[]).includes(p)?a("Already tagged with that tag"):_([...u?[]:[{id:au(),action:"create.tag",payload:{id:p,name:r},...O(e.value)}],{id:au(),action:"add.issue.tag",payload:{id:i.id,tag:p},...O(e.value)}],c.value)}});var vi,Vy,ll=g(()=>{"use strict";wt();Mn();vi=({events:e,registry:t,logFileNames:n})=>{let r=new Map(n),o=new Set;for(let s of e)s.userId&&(r.has(s.userId)||r.set(s.userId,""),o.add(s.userId));for(let s of Object.values(t))r.set(s.id,s.name);return[...r.entries()].map(([s,i])=>({id:s,name:i,isExternal:!o.has(s)}))},Vy=({authorName:e,authorEmail:t,owners:n,registry:r})=>{let o=Ge(t),s=n.get(o),i=s?r[s]:void 0;return s?{...ht(s,i?.name),resolved:!0}:{...ht(o||e,e),resolved:!1}}});var cl,lu=g(()=>{"use strict";$();ll();D();cl=e=>{let{eventLog:t=[],contributors:n}=v();return vi({events:t,registry:n,logFileNames:Br(e)})}});import{ulid as cu}from"ulid";var Ky,Yy=g(()=>{"use strict";$();$();ce();N();de();pe();D();lu();Q();jt();Ky=async()=>{let e=fe();if(l(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=me().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return a("Provide an assignee");let{selectedIndex:i,contextNode:c}=v(),u=ve(c.id)[i];if(!u)return a("Invalid assign target");let p=Yt(u.id,"TICKET");if(l(p))return a("Unable to assign issue in this context");let m=p.value;if(!U(m))return a("Target node is not issue");let f=await xe();if(l(f))return f;let h=cl(f.value),b=!o&&s.toLowerCase()==="me",I,C;if(b)I=e.value.userId,C=h.find(M=>M.id===I)?.name??e.value.userName;else{let M=h.filter(F=>F.name===s);if(M.length>1)return a(`"${s}" matches ${M.length} contributors (${M.map(F=>F.id).join(", ")}). Assign from the GUI to choose by id.`);let L=M[0];if(!L&&!o)return a(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);I=L?.id??cu(),C=L?.name??s}if((m.props.assignees??[]).includes(I))return a("Assignee already assigned");let S=!!v().contributors[I];return _([...S?[]:[{id:cu(),action:"create.contributor",payload:{id:I,name:C},...O(e.value)}],{id:cu(),action:"add.issue.assignee",payload:{id:m.id,assignee:I},...O(e.value)}],f.value)}});import{ulid as dA}from"ulid";var Xy,Jy=g(()=>{"use strict";$();$();ce();N();de();pe();D();lu();Q();jt();Xy=async()=>{let e=fe();if(l(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=me().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let{selectedNode:o}=v();if(!o)return a("Invalid unassign target");let s=Yt(o.id,"TICKET");if(l(s))return a("Unable to unassign in this context");let i=s.value;if(!U(i))return a("Target node is not issue");let c=i.props.assignees??[],u=r.toLowerCase()==="me",p=await xe();if(l(p))return p;let m=u?c.filter(h=>h===e.value.userId):cl(p.value).filter(h=>h.name===r&&c.includes(h.id)).map(h=>h.id);if(m.length>1)return a(`"${r}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let f=m[0];return f?_([{id:dA(),action:"remove.issue.assignee",payload:{id:i.id,assignee:f},...O(e.value)}],p.value):a(u?"Issue is not assigned to you":`Issue is not assigned to "${r}"`)}});import{ulid as Qy}from"ulid";var uA,Zy,eb=g(()=>{"use strict";$();$();en();ce();N();de();D();_n();Q();jt();qa();Ja();$a();uA=e=>{let t=e.trim(),n=pr(),r=n?uv(t):null;if(!n||!r)return{ok:!0,md:t,anchored:!1};let o=Xa();if(!o||o.sha!==n)return{ok:!1,reason:"No diff is open"};let s=mv(o.rows,Math.max(0,v().selectedIndex));if(!s)return{ok:!1,reason:"That line is not in a file"};let i=pv(o.rows,s,r.start,r.end);return i.ok?{ok:!0,anchored:!0,md:Vh({filePath:i.value.filePath,start:i.value.start,end:i.value.end,side:"additions",endSide:"additions",note:r.note,sha:n,snippet:i.value.snippet})}:{ok:!1,reason:i.reason}},Zy=async e=>{let t=uA(e.inputString);if(!t.ok)return a(t.reason);let{md:n,anchored:r}=t;if(!n)return a("Provide a comment");if(n.length>4e3)return a(r?`The note and the ${n.length} characters of quoted lines exceed ${4e3}; comment on fewer lines`:`Cannot exceed ${4e3} characters`);let o=fe();if(l(o))return a("Unable to resolve user ID");let{breadCrumb:s,selectedNode:i}=v(),c=At([...s,i],"TICKET");if(l(c))return a("Edit target must be an issue");let u=c.value;if(!u)return a("Invalid comment target");let p=u.context==="TICKET"?d("Resolved ticket",u):Yt(u.id,"TICKET");if(l(p))return a("Unable to comment on issue in this context");let m=p.value;if(!U(m))return a("Target node is not issue");let f=await xe();if(l(f))return f;let h=await _([{id:Qy(),action:"add.issue.comment",payload:{id:Qy(),issue:m.id,author:o.value.userId,md:n},...O(o.value)}],f.value);return r&&!l(h)&&zr(null),h}});var tb,mA,nb,dl,du=g(()=>{"use strict";Cr();N();$e();In();tb=e=>e.userName?.trim()?e.preferredEditor?.trim()?null:"no editor configured":"no username configured",mA=e=>{let t=Jn();return l(t)?tb({userName:e.userName,preferredEditor:e.preferredEditor})??t.message:tb(t.value)},nb=()=>{let e=xn();return l(e)?a(e.message):d("Read auto sync settings",{enabled:e.value.autoSync===!0,intervalMs:Di(e.value.autoSyncDebounceMs),blockedReason:mA(e.value)})},dl=e=>{let t=e.intervalMs===void 0?void 0:oo(e.intervalMs);if(e.intervalMs!==void 0&&t===null)return a(`Auto sync interval must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=nb();if(l(n))return n;let r=It({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncDebounceMs:t}});if(l(r))return a(r.message);ct({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncIntervalMs:t}});let o=nb();return l(o)?d("Changed auto sync settings",{...n.value,...e.enabled===void 0?{}:{enabled:e.enabled},...t==null?{}:{intervalMs:t}}):o}});var rb,ob=g(()=>{"use strict";Cr();du();N();pe();rb=()=>{let e=me().commandMeta.inputString,t=oo(e);if(t===null)return a(`Auto sync duration must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=dl({intervalMs:t});return l(n)?n:d(`Auto sync interval set to ${t}ms`,null)}});var sb,ib=g(()=>{"use strict";Tr();du();N();pe();sb=()=>{let e=me().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=_p(e),n=dl({enabled:t===!0});return l(n)?n:d(`Auto sync set to "${e}"`,null)}});var uu,ab,lb,pA,fA,yi,ul,ml=g(()=>{"use strict";ze();wt();N();bd();uu=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=2),ab="",lb=new Map,pA=15e3,fA=async(e,t)=>{let n=`${e} ${t??""}`,r=lb.get(n);if(r&&Date.now()-r.at<Ua(pA))return d("Cached author scan",r.authors);let o=await Me({cwd:e,args:["log","--branches",...t?["--not",t]:[],`--format=%an${ab}%ae`]});if(o.exitCode!==0)return a(`Could not read this repository's history: ${(o.stderr??"").trim()||`git exited ${o.exitCode}`}`);let s=new Map;for(let i of(o.stdout??"").split(`
|
|
106
|
+
`)){let c=i.lastIndexOf(ab);if(c===-1)continue;let u=i.slice(0,c),p=Ge(i.slice(c+1));if(!Vn(p))continue;let m=s.get(p)??{names:new Set,commits:0};u&&m.names.add(u),m.commits+=1,s.set(p,m)}return lb.set(n,{at:Date.now(),authors:s}),d("Scanned repository authors",s)},yi=async({repoRoot:e,stateBranch:t,names:n,links:r})=>{let o=await fA(e,t);if(l(o))return a(o.message);let s=o.value,i=new Map;for(let u of Object.values(r)){if(u.tombstoned)continue;let p=i.get(u.email)??new Set;p.add(u.contributor),i.set(u.email,p)}let c=new Set(n.flatMap(u=>uu(u??"")));return d("Found candidates",[...s.entries()].map(([u,p])=>({email:u,names:[...p.names],commits:p.commits,looksLikeYours:[...p.names].some(m=>uu(m).some(f=>c.has(f)))||uu(u.split("@")[0]??"").some(m=>c.has(m)),claimedBy:[...i.get(u)??[]]})).sort((u,p)=>u.looksLikeYours===p.looksLikeYours?p.commits-u.commits:Number(p.looksLikeYours)-Number(u.looksLikeYours)))},ul=e=>e.filter(t=>t.claimedBy.length===0)});import{ulid as gA}from"ulid";var cb,db,ub=g(()=>{"use strict";$();gn();nt();wt();N();Pe();ml();pe();Cs();$e();D();In();Tr();Q();cb=()=>{let e=sc();if(!e)return d("Nothing here to decline",null);let t=xn(),n=l(t)?[]:t.value.declinedEmailBoards??[],r=[...new Set([...n,e])],o=It({declinedEmailBoards:r});return l(o)?a(o.message):(ct({declinedEmailBoards:[...new Set([...ae().declinedEmailBoards??[],e])]}),d("Declined",null))},db=async()=>{let e=me().commandMeta.inputString.trim();if(e==="none"){let T=cb();return l(T)?T:d("Left unlinked. Your commits will show the name git signed them with. Run :config emails again to change that.",null)}let{userId:t,userName:n,gitName:r}=ae();if(!t)return a("Set a username first with :config username");let o=Ee();if(l(o))return a("Board is not loaded");let s=Ne(process.cwd());if(l(s))return a(s.message);let i=tt(s.value),c=await yi({repoRoot:s.value,stateBranch:l(i)?void 0:i.value,names:[n,r],links:o.value.emailLinks});if(l(c))return c;let p=ul(c.value);if(Lp(p.map(T=>T.email)),p.length===0){if(!Dp()){let T=cb();if(l(T))return T}return d("No unclaimed addresses in this history.",null)}if(!e)return A({mode:x.IDENTITY}),d("Opened identity",null);let m=e.split(/[,\s]+/).filter(Boolean),f=[],h=[];for(let T of m){let S=p.find(M=>M.email===Ge(T));if(!S){h.push(T);continue}f.includes(S)||f.push(S)}if(h.length>0)return a(`Not on the list: ${h.join(", ")}. Pick one of ${p.map(T=>T.email).join(", ")}.`);let b=be({repoRoot:s.value});if(l(b))return b;let I=f.map(T=>({id:gA(),action:"link.contributor.email",payload:{contributor:t,email:T.email},userId:t})),C=_(I,b.value);return l(C)?a(C.message):d(`Claimed ${f.map(T=>T.email).join(", ")}. Every commit by ${f.length===1?"that address":"those addresses"} is now yours.`,null)}});import{ulid as hA}from"ulid";var mb,pb=g(()=>{"use strict";$();nt();wt();N();pe();$e();D();Q();mb=()=>{let e=me().commandMeta.inputString.trim(),{userId:t}=ae();if(!t)return a("Set a username first with :config username");let n=Ee();if(l(n))return a("Board is not loaded");let r=Kn(n.value.emailLinks,t);if(r.length===0)return a("You have not claimed any addresses.");if(!e)return a(`Which one? ${r.join(", ")}.`);let o=r.find(u=>u===Ge(e));if(!o)return a(`You have not claimed ${e}. Yours: ${r.join(", ")}.`);let s=Ne(process.cwd());if(l(s))return s;let i=be({repoRoot:s.value});if(l(i))return i;let c=_([{id:hA(),action:"unlink.contributor.email",payload:{contributor:t,email:o},userId:t}],i.value);return l(c)?a(c.message):d(`Unclaimed ${o}`,null)}});var fb,gb=g(()=>{"use strict";In();N();pe();$e();fb=()=>{let e=me().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=It({logLevel:e});return l(n)?n:(ct({logLevel:e}),d(`Auto sync set to "${e}"`,null))}});import{ulid as vA}from"ulid";var hb,vb=g(()=>{"use strict";xr();In();N();$e();Dn();ob();vc();ib();ub();pb();gb();hb=e=>{let t=e.inputString.trim();switch(e.modifier){case he.USERNAME:{if(process.env[Ft])return a(`Cannot change the configured user while ${Ft} names this process`);let n=xn();if(l(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,c=r||vA();if(!i||!c)return a("Unable to resolve user name or id");let u=It({userName:i,userId:c,preferredEditor:o??""});return l(u)?u:(ct({userName:i,userId:c}),d(`Username set to "${i}"`,null))}case he.EDITOR:{if(!t)return a("No editor provided");let n=It({preferredEditor:t});return l(n)?n:(ct({preferredEditor:t}),d(`Editor configuration set to "${t}"`,null))}case he.VIEW:{if(t!=="wide"&&t!=="dense")return a("Invalid view mode");let n=It({viewMode:t});return l(n)?n:(ct({viewMode:t}),d(`View set to "${t}"`,null))}case he.EMAILS:return db();case he.EMAILS_UNCLAIM:return mb();case he.AUTOSYNC:return sb();case he.LOG_LEVEL:return fb();case he.SYNC_DEBOUNCE_MS:return rb();case he.ATTACHMENT_MAX_KB:return nf();default:return a("Unknown config command")}}});var mu,yb=g(()=>{"use strict";Tr();Pe();pe();D();mu=()=>{let e=Fp(),t=v().mode;if(!(t!==x.COMMAND_LINE&&t!==x.DEFAULT)){if(!e){A({mode:x.DEFAULT});return}A({mode:x.COMMAND_LINE}),Z(e)}}});var bb,xb=g(()=>{"use strict";zv();Et();Pe();N();pe();D();el();Mr();ld();Dn();Kv();Qv();sy();ay();by();Ny();Ay();ky();Py();_y();By();jy();Hy();qy();zy();Yy();Jy();eb();vb();yb();bb=[{systemOnly:!0,intent:G.Move,description:"Internal move-state command",mode:x.COMMAND_LINE,action:oy},{intent:G.Delete,description:"Delete the currently selected node",mode:x.COMMAND_LINE,action:Oy,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:x.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=me().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>Ue(E.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return ke(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:x.DEFAULT})),d("Filter updated",null)}},{intent:G.ViewHelp,description:"Open the help screen",mode:x.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return fr({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),A({mode:x.HELP}),d("Viewing help",null)}},{intent:G.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:x.COMMAND_LINE,action:Fy,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:x.COMMAND_LINE,action:$y,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.Init,description:"Initialize Epiq in the current git repository",mode:x.COMMAND_LINE,action:Jv,onSuccess:mu},{intent:G.OpenProject,description:"Open a recently used epiq project, by number or path",mode:x.COMMAND_LINE,action:yy,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.NewItem,description:"Create a new board, swimlane, or issue",mode:x.COMMAND_LINE,action:iy,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.Rename,description:"Rename the currently selected node",mode:x.COMMAND_LINE,action:Uy,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.UntagTicket,description:"Remove a tag from the selected issue",mode:x.COMMAND_LINE,action:Wy,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.TagTicket,description:"Add or create a tag on the selected issue",mode:x.COMMAND_LINE,action:Gy,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.AssignUserToTicket,description:"Assign a user to the selected issue",mode:x.COMMAND_LINE,action:Ky,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:x.COMMAND_LINE,action:Xy,onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.Comment,description:"Add a comment to the selected issue",mode:x.COMMAND_LINE,action:async(e,t)=>Zy(t),onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.Sync,description:"Pull, commit, and push Epiq state",mode:x.COMMAND_LINE,action:Ly},{intent:G.Peek,description:"View board state at another point in time",mode:x.COMMAND_LINE,action:Ry},{intent:G.Replay,description:"Replay board history forward from a point in time",mode:x.COMMAND_LINE,action:Cy},{intent:G.Export,description:"Export the current board layout to markdown",mode:x.COMMAND_LINE,action:async()=>{let e=await Gv();return l(e)?e:(A({mode:x.DEFAULT}),d("Export successful",!0))}},{intent:G.Exit,description:"Exit the application",mode:x.COMMAND_LINE,action:async()=>(H.exit(),d("Exit successful",!0))},{intent:G.Edit,description:"Edit title or description",mode:x.COMMAND_LINE,action:async(e,t)=>Vv(t),onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:x.COMMAND_LINE,action:async(e,t)=>My(t),onSuccess:()=>A({mode:x.DEFAULT})},{intent:G.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:x.COMMAND_LINE,action:(e,t)=>hb(t),onSuccess:mu}]});var yA,Xt,pu=g(()=>{"use strict";bh();ta();ld();xb();nu();N();pe();$e();D();yA=new Set(["peek","replay","filter","view-help","yank"]),Xt=async({isForceExecutedBySystem:e=!1}={})=>{let{value:t,commandMeta:{command:n,validity:r,modifier:o,inputString:s}}=me();if(!n)return a("No command to confirm");if(!e&&r===Zn.Invalid)return a("Invalid command");let i=xh(n);Rf();let{readOnly:c}=v();if(c&&!yA.has(i))return Ds({status:Tn.Fail,message:"Command not available in readonly state",value:null});let u=bb.filter(f=>e||f.systemOnly!==!0).find(f=>f.intent===i);if(!u)return Ds({status:Tn.Fail,message:"Command not found",value:null});let p;try{p=await u.action(u,{command:n,inputString:s,modifier:o})}catch(f){return Ds({status:Tn.Fail,message:f instanceof Error?f.message:"Command failed",value:null})}if(l(p))return Ds(p);let m=!e;if(Nf({addToHistory:m,line:t}),m){let f=uy({commands:me().commandHistory});l(f)&&logger.info(f.message)}return u.onSuccess?.(),ae().autoSync&&yh(),p}});var pl,fl,Ib,Eb=g(()=>{"use strict";N();Pe();D();Yn();pu();eu();pe();pl=[{intent:P.Exit,mode:x.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(A({mode:x.COMMAND_LINE}),Z("move cancel"),Xt({isForceExecutedBySystem:!0}))},{intent:P.InitMove,mode:x.DEFAULT,description:"[m] move",action:()=>(A({mode:x.COMMAND_LINE}),Z("move start"),Xt({isForceExecutedBySystem:!0}))},{intent:P.ConfirmMove,mode:x.MOVE,description:"[m] confirm move",action:()=>(A({mode:x.COMMAND_LINE}),Z("move confirm"),Xt({isForceExecutedBySystem:!0}))}],fl=[{intent:P.MovePreviousItem,mode:x.MOVE,action:()=>un()?(A({mode:x.COMMAND_LINE}),Z("move previous"),Xt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:P.MoveNextItem,mode:x.MOVE,description:"[arrows/hjkl] move (shift x5)",action:()=>un()?(A({mode:x.COMMAND_LINE}),Z("move next"),Xt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:P.MovePreviousItemJump,mode:x.MOVE,action:()=>un()?(A({mode:x.COMMAND_LINE}),Z("move jump-previous"),Xt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:P.MoveNextItemJump,mode:x.MOVE,action:()=>un()?(A({mode:x.COMMAND_LINE}),Z("move jump-next"),Xt({isForceExecutedBySystem:!0})):a("No pending move")}],Ib=[{intent:P.MoveToNextContainer,mode:x.MOVE,action:()=>un()?(A({mode:x.COMMAND_LINE}),Z("move to-next"),Xt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:P.MoveToPreviousContainer,mode:x.MOVE,action:()=>un()?(A({mode:x.COMMAND_LINE}),Z("move to-previous"),Xt({isForceExecutedBySystem:!0})):a("No pending move")}]});var Sb,Rb=g(()=>{"use strict";ce();Eb();Sb={[re.WORKSPACE]:[...pl,...fl],[re.BOARD]:[...pl,...fl],[re.SWIMLANE]:[...pl,...fl,...Ib],[re.TICKET]:[],[re.FIELD]:[],[re.FIELD_LIST]:[],[re.TEXT]:[],[re.COMMENT]:[]}});import{spawn as bA}from"node:child_process";function Nb(e){let t=process.platform,o=bA(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 Cb=g(()=>{"use strict"});import xA from"node:fs";import IA from"node:path";var Ab,wb=g(()=>{"use strict";nt();go();N();Q();Cb();Ab=e=>{let t=Ne(process.cwd());if(l(t))return a("Unable to resolve project root");let n=be({repoRoot:t.value});if(l(n))return a(n.message);let r=fo(e.hash,e.ext),o=IA.join(Ui(n.value),r);return xA.existsSync(o)?(Nb(o),d(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")}});var Tb,Mb,kb=g(()=>{"use strict";Pe();N();pe();D();el();Yn();Et();Tb=()=>{Z("");let{pendingNavTarget:e}=qo();A({mode:x.DEFAULT}),e&&H.navigate(e),fr({pendingNavTarget:void 0})},Mb=[{intent:P.ExitCommandLine,mode:x.HELP,action:()=>(Tb(),d("Exiting help",null))},{intent:P.Exit,mode:x.HELP,action:()=>(Tb(),d("Closed help",null))},{intent:P.NavPreviousItem,mode:x.HELP,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(H.navigateToPreviousItem(),d("Navigating to previous help item",null))},{intent:P.NavNextItem,mode:x.HELP,action:()=>(H.navigateToNextItem(),d("Navigating to next help item",null))},{intent:P.NavPreviousItemJump,mode:x.HELP,action:()=>(H.jumpToPreviousItem(),d("Jumping to previous help item",null))},{intent:P.NavNextItemJump,mode:x.HELP,action:()=>(H.jumpToNextItem(),d("Jumping to next help item",null))},{intent:P.NavToPreviousContainer,mode:x.HELP,action:()=>(H.navigateToPreviousContainer(),d("Navigating to previous help container",null))},{intent:P.NavToNextContainer,mode:x.HELP,action:()=>(H.navigateToNextContainer(),d("Navigating to next help container",null))}]});var Lb,Pb,Db=g(()=>{"use strict";Pe();N();pe();Cs();D();Yn();Lb=()=>{Z(""),A({mode:x.DEFAULT})},Pb=[{intent:P.Confirm,mode:x.IDENTITY,description:"[enter] claim the first",action:()=>{let[e]=uo();return e?(A({mode:x.COMMAND_LINE}),Z(`config emails ${e}`),d("Proposed claim",null)):d("Nothing left to claim",null)}},{intent:P.ExitCommandLine,mode:x.IDENTITY,action:()=>(Lb(),d("Closed identity",null))},{intent:P.Exit,mode:x.IDENTITY,description:"[esc] close",action:()=>(Lb(),d("Closed identity",null))}]});var EA,Ob,_b,Fb=g(()=>{"use strict";Pe();ce();N();pe();D();el();Yn();Et();EA=e=>{A({mode:x.COMMAND_LINE});let{pendingNavTarget:t}=qo();t&&H.navigate(t),fr({pendingNavTarget:void 0}),Z(`${e} `)},Ob=()=>{Z("");let{pendingNavTarget:e}=qo();e&&H.navigate(e),fr({pendingNavTarget:void 0}),A({mode:x.DEFAULT})},_b=[{intent:P.InitCommandPalette,mode:x.DEFAULT,description:"[?] command palette",action:()=>{Z("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return fr({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),A({mode:x.PALETTE}),d("Opening command palette",null)}},{intent:P.Confirm,mode:x.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!Om(e))return a("Command only applicable on text nodes");if(e.props.disabled)return a("Command is not available in this context");let t=e.title;return t?(EA(t),d("Selected command",t)):d("No command selected",null)}},{intent:P.ExitCommandLine,mode:x.PALETTE,action:()=>(Ob(),d("Exiting palette",null))},{intent:P.Exit,mode:x.PALETTE,action:()=>(Ob(),d("Closed command palette",null))},{intent:P.NavPreviousItem,mode:x.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(H.navigateToPreviousItem(),d("Navigating to previous item",null))},{intent:P.NavNextItem,mode:x.PALETTE,action:()=>(H.navigateToNextItem(),d("Navigating to next item",null))},{intent:P.NavToPreviousContainer,mode:x.PALETTE,action:()=>(H.navigateToPreviousContainer(),d("Navigating to previous container",null))},{intent:P.NavToNextContainer,mode:x.PALETTE,action:()=>(H.navigateToNextContainer(),d("Navigating to next container",null))}]});var Bb,$b,jb=g(()=>{"use strict";Mr();Dn();li();qa();Pe();N();Ja();So();de();Ht();pe();D();wb();Yn();Qn();kb();Db();Fb();Et();Bb=()=>{let e=pr();if(!e)return d("Nothing to comment on here",null);let t=Xa();if(!t||t.sha!==e)return a("The diff is still loading");let{selectedIndex:n}=v(),r=Math.max(0,n),o=Cd(t.rows,Bd(e)??r,r);return o.ok?(A({mode:x.COMMAND_LINE}),Z(`${E.COMMENT} ${dv(o.value.start,o.value.end)} `),d("Commenting on a diff line",null)):a(o.reason)},$b=[{intent:P.InitCommandLine,mode:x.DEFAULT,description:"[:] write command",action:()=>(A({mode:x.COMMAND_LINE}),Z(""),d("Entering command line mode",null))},...Mb,...Pb,..._b,{intent:P.AddItem,mode:x.DEFAULT,description:"[n] new...",action:()=>(A({mode:x.COMMAND_LINE}),Z(`${E.NEW} `),d("Adding new item",null))},{intent:P.Delete,mode:x.DEFAULT,description:"[d] delete",action:()=>(A({mode:x.COMMAND_LINE}),Z(`${E.DELETE} `),d("Deleting item",null))},{intent:P.Confirm,mode:x.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!Te(e?.id??"")?.length){let r=e?R.getAttachment(e.id):void 0;if(r)return Ab(r);if(pr())return Bb();if(e?.title===Ae.DESCRIPTION)return A({mode:x.COMMAND_LINE}),Z(`${E.EDIT} description `),d("Propose command",!0);if(e?.title===Ae.ASSIGNEES)return A({mode:x.COMMAND_LINE}),Z(`${E.ASSIGN} `),d("Propose command",!0);if(e?.title===Ae.TAGS)return A({mode:x.COMMAND_LINE}),Z(`${E.TAG} `),d("Propose command",!0);if(t.title===Ae.DESCRIPTION&&e?.context==="TEXT")return A({mode:x.COMMAND_LINE}),Z(`${E.EDIT} description `),d("Propose command",!0)}return H.enterChildNode(),d("Entering context",null)}},{intent:P.OpenInEditor,mode:x.DEFAULT,action:()=>{let{selectedNode:e,contextNode:t}=v(),n=t.parentNodeId,o=!!n&&t.id===we(n,"diff")?e?.id:pr()??void 0;return o?Dd({sha:o}):d("Nothing here opens in an editor",null)}},{intent:P.MarkDiffLine,mode:x.DEFAULT,action:()=>{let e=pr();if(!e)return d("Nothing to mark here",null);let{selectedIndex:t}=v(),n=Bd(e);return zr(n===t?null:{sha:e,row:Math.max(0,t)}),d("Marked diff line",null)}},{intent:P.CommentOnDiffLine,mode:x.DEFAULT,action:()=>pr()?Bb():d("Nothing to comment on here",null)},{intent:P.Yank,mode:x.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=v(),t=e?.title===Ae.DESCRIPTION?je.DESCRIPTION:e?.title===Ae.TAGS?je.TAGS:e?.title===Ae.ASSIGNEES?je.ASSIGNEES:je.REF,r=Ue(E.YANK).includes(t)?t:je.REF;return A({mode:x.COMMAND_LINE}),Z(`${E.YANK} ${r}`),d("Propose command",!0)}},{intent:P.EditTitle,mode:x.DEFAULT,description:"[r] rename title",action:()=>(A({mode:x.COMMAND_LINE}),Z(`${E.EDIT} title ${v().selectedNode?.title}`),d("Exiting context",null))},{intent:P.EditDescription,mode:x.DEFAULT,description:"[e] edit desc",action:()=>(A({mode:x.COMMAND_LINE}),Z(`${E.EDIT} description `),d("Exiting context",null))},{intent:P.Exit,mode:x.DEFAULT,description:"[q] exit context",action:()=>(H.enterParentNode(),d("Exiting context",null))},{intent:P.NavPreviousItem,mode:x.DEFAULT,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(H.navigateToPreviousItem(),d("Navigating to previous item",null))},{intent:P.NavNextItem,mode:x.DEFAULT,action:()=>(H.navigateToNextItem(),d("Navigating to next item",null))},{intent:P.NavPreviousItemJump,mode:x.DEFAULT,action:()=>(H.jumpToPreviousItem(),d("Jumping to previous item",null))},{intent:P.NavNextItemJump,mode:x.DEFAULT,action:()=>(H.jumpToNextItem(),d("Jumping to next item",null))},{intent:P.NavToPreviousContainer,mode:x.DEFAULT,action:()=>(H.navigateToPreviousContainer(),d("Navigating to previous container",null))},{intent:P.NavToNextContainer,mode:x.DEFAULT,action:()=>(H.navigateToNextContainer(),d("Navigating to next container",null))}]});var SA,RA,Ub,Hb=g(()=>{"use strict";pe();SA=500,RA=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Ub=e=>{let t=RA(e);t&&oa(n=>(n+t).slice(0,SA))}});var NA,CA,AA,Wb,qb=g(()=>{"use strict";Hb();Pe();N();pe();D();Yn();pu();NA=[x.COMMAND_LINE,x.PALETTE],CA=e=>e==="edit title "?v().selectedNode?.title??"":"",AA=e=>[{intent:P.MoveCursorLeft,mode:e,action:()=>(Ic(-1),d("Moving cursor left",null))},{intent:P.MoveCursorRight,mode:e,action:()=>(Ic(1),d("Moving cursor right",null))},{intent:P.MoveCursorLeftOfWord,mode:e,action:()=>(Ec("left"),d("Moving cursor left of word",null))},{intent:P.MoveCursorRightOfWord,mode:e,action:()=>(Ec("right"),d("Moving cursor right of word",null))},{intent:P.AutoCompleteCommand,mode:e,action:()=>(oa((t,{remainder:n})=>{let r=n?t+n:t;return r+CA(r)}),d("Auto-completing command",null))},{intent:P.CaptureInput,mode:e,action:(t,{sequence:n})=>(Ub(n??""),d("Capturing input",null))},{intent:P.EraseInput,mode:e,action:()=>(Ef(),d("Erasing input",null))},{intent:P.EraseInputWord,mode:e,action:()=>(Sf(),d("Erasing input word",null))}],Wb=[{intent:P.Confirm,mode:x.COMMAND_LINE,action:()=>(Xt(),d("Executing command",null))},{intent:P.ViewHelp,mode:x.DEFAULT,action:()=>(A({mode:x.HELP}),d("Viewing help",null))},...NA.flatMap(AA),{intent:P.ExitCommandLine,mode:x.COMMAND_LINE,action:()=>(Af(),A({mode:x.DEFAULT}),d("Exiting command line",null))},{intent:P.GetLastCommandFromHistory,mode:x.COMMAND_LINE,action:()=>(wf(),d("Getting last command from history",null))},{intent:P.GetNextCommandFromHistory,mode:x.COMMAND_LINE,action:()=>(Tf(),d("Getting next command from history",null))}]});var wA,Gb,zb,Vb=g(()=>{"use strict";wA=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},Gb=({keys:e})=>e.length===1?0:1,zb=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(wA).filter(r=>r!==null).sort((r,o)=>Gb(r)-Gb(o))}});function Kb(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=new Set,i=r;for(;i&&!s.has(i.id)&&(o.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let c=o[o.length-1];return!c||c.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),d("Breadcrumb built",o))}var Yb=g(()=>{"use strict";N()});var Xb,Jb=g(()=>{"use strict";Xb=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 TA}from"react";function vu(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return a("derive(): contextNodeId is missing");if(!r)return a("derive(): rootNode is missing");if(!o[r])return a("derive(): unable to find root node");let c=o[t];if(!c)return a("Unable to derive state, contextNode not found");let u=Kb(t,o,r);if(l(u))return logger.error(u.message),u;let p=u.value,{context:m}=c,f=[...$b,...Sb[m]??[],...Wb],h=zb(f,n),b=Xb(f),I=kA(o,s),C=I[t]?.[e.selectedIndex]??null;return d("Derived successfully",{...e,contextNode:c,breadCrumb:p,availableHints:h,availableActions:f,actionIndex:b,selectedNode:C,renderedChildrenIndex:I})}function Ws(e){fu=e;let t=Ne(process.cwd()),n=!1;if(!l(t)){let s=Mt(t.value);if(l(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},emailLinks:{},mode:x.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=vu(r);return l(o)?o:(Nt=o.value,hu(),d("State initialized",null))}function ke(e){let t=v(),n=e(t);if(Xr)return n.nodes!==t.nodes&&(gr=null),bi=n,Nt={...t,...n},d("State updated",null);let r=vu(n);return l(r)?a(r.message??"Unable to update state"):(Nt=r.value,hu(),d("State updated",null))}function va(e){if(Xr)return d("Joined batch",e());Xr=!0,bi=null,gr=new Set;let t=()=>{let n=bi;if(Xr=!1,bi=null,n===null)return null;let r=vu(n);return l(r)?a(r.message??"Unable to update state"):(Nt=r.value,hu(),d("State updated",null))};try{let n=e(),r=t();return r&&l(r)?a(r.message):d("State updated",n)}finally{Xr&&t()}}function Jr(e,t,n){if(!Xr)return ke(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=v(),o=r[e]??{};if(e==="nodes"){let i=o[t],c=n;i?.parentNodeId&&gr?.add(i.parentNodeId),c.parentNodeId&&gr?.add(c.parentNodeId)}o[t]=n;let s={...r,[e]:o};return bi=s,Nt={...r,...s},d("State updated",null)}var Nt,fu,gu,hu,MA,v,Ee,Xr,bi,_g,A,Ve,gr,Qb,kA,ve,Gn,qt,D=g(()=>{"use strict";Rb();jb();qb();Vb();rn();Pe();N();Q();Vc();Yb();Jb();wt();oc();gu=new Set,hu=()=>{for(let e of gu)e()},MA=e=>(gu.add(e),()=>gu.delete(e));v=()=>{if(!Nt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Nt},Ee=()=>Nt?d("Retrieved state",Nt):a("State not initialized. Call initWorkspaceState() first.");Tp(e=>Nt?Kn(Nt.emailLinks,e):[]);Xr=!1,bi=null;_g=()=>Xr,A=e=>ke(t=>({...t,...e}));Ve=()=>TA(MA,v,v),gr=null,Qb=null,kA=(e,t)=>{let n=Nt?.renderedChildrenIndex,r=n!==void 0&&gr!==null&&e===Qb&&t.length===0&&Nt?.filters.length===0,o;if(r){o={...n};let s=Lg(e,gr);for(let i of gr){let c=s[i];c?o[i]=c:delete o[i]}}else o=kg(e,t);return Qb=e,gr=new Set,o},ve=e=>v()?.renderedChildrenIndex[e]??[],Gn=()=>fu?Ws(fu):a("Cannot reset state: no initial workspace found"),qt=()=>Nt!==void 0});var Yt,LA,hr,R,de=g(()=>{"use strict";en();wt();ce();N();D();Ht();Yt=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return d("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 d("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},LA=(e,t)=>{let{nodes:n}=v(),r=new Set,o=n[e];for(;o?.parentNodeId&&!r.has(o.id);){if(o.parentNodeId===t)return!0;r.add(o.id),o=n[o.parentNodeId]}return!1},hr=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:a("Node not found"),R={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.userId&&n.userId!==t)return a("Contributor is already linked to another user");let r={...n,userId:t},o=ke(s=>({...s,contributors:{...s.contributors,[e]:r}}));return l(o)?a("Unable to link contributor to user"):d("Linked contributor to user",r)},deleteNode(e){R.deleteNodes([e])},deleteNodes(e){e.length!==0&&ke(t=>{let n={...t.nodes};for(let r of e)delete n[r];return{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create comment, missing issue");if(!U(t))return a("Can only comment on issues");let n=Jr("comments",e.id,{...e,deleted:!1});return l(n)?a("Unable to create comment"):d("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return a("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return a("Unable to edit comment, missing issue");if(!U(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=Jr("comments",e,o);return l(s)?a("Unable to edit comment"):d("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return a("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=Jr("comments",e,n);return l(r)?a("Unable to delete comment"):d("Deleted comment",n)},getComment(e){return v().comments?.[e]},getCommentsByIssue(e){return Object.values(v().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(v().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create attachment, missing issue");if(!U(t))return a("Can only attach to issues");let n=ke(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return l(n)?a("Unable to create attachment"):d("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return a("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=ke(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return l(r)?a("Unable to delete attachment"):d("Deleted attachment",n)},getAttachment(e){return v().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(v().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(v().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return a("Edit target node not found");let o=hr(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),d("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return a("Rename target node not found");let r=hr(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),d("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return Te(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),s=this.getNode(t);if(!o)return a("Node not found");if(!s)return a("Target parent not found");if(r===e)return a("Cannot move root node");if(e===t)return a("Cannot move node into itself");let i=hr(o,"move");if(i)return i;if(LA(t,e))return a("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),d("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=hr(o,"delete");if(s)return s;let i=new Set,c=p=>{let m=t[p];if(!(!m||i.has(p))){i.add(p);for(let f of Te(m.id))c(f.id)}};c(e);let u={...structuredClone(t)};for(let p of i){if(!u[p])return a("Unable to locate node to delete");u[p]={...u[p],isDeleted:!0}}return n?(A({nodes:u}),d("Successfully tomb stoned",o)):a("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return a("Contributor not found");let n={...t,name:us,tombstoned:!0},r=ke(o=>({...o,contributors:{...o.contributors,[e]:n}}));return l(r)?a("Unable to remove contributor"):d("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.tombstoned)return a("Cannot rename a removed contributor");let r={...n,name:t},o=ke(s=>({...s,contributors:{...s.contributors,[e]:r}}));return l(o)?a("Unable to rename contributor"):d("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");let r={...n,name:t,tombstoned:!1},o=ke(s=>({...s,contributors:{...s.contributors,[e]:r}}));return l(o)?a("Unable to restore contributor"):d("Restored contributor",r)},linkContributorEmail({email:e,contributor:t,authorId:n}){if(!this.getContributor(t))return a("Unable to link email, missing contributor");let r={email:Ge(e),contributor:t,authorId:n},o=ms(r.email,t),s=v().emailLinks[o];if(s&&!s.tombstoned)return d("Email already linked",s);let i=ke(c=>({...c,emailLinks:{...c.emailLinks,[o]:r}}));return l(i)?a("Unable to link email"):d("Linked email to contributor",r)},unlinkContributorEmail(e,t,n){let r=ms(e,t),o=v().emailLinks[r];if(!o)return a("Unable to unlink, no such link");if(o.tombstoned)return d("Email already unlinked",o);if(!Li(n,o))return a("Only the author of a link or the contributor it names may remove it");let s={...o,tombstoned:!0},i=ke(c=>({...c,emailLinks:{...c.emailLinks,[r]:s}}));return l(i)?a("Unable to unlink email"):d("Unlinked email from contributor",s)},getEmailLinks(){return v().emailLinks},createContributor(e){let t=ke(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return l(t)?a("Unable to create contributor"):d("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to assign contributor, missing contributor");if(!r)return a("Unable to assign contributor, missing target");let o=hr(r,"edit");if(o)return o;if(!U(r))return a("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return a("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),d("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to unassign, missing contributor");if(!r)return a("Unable to unassign, missing target");let o=hr(r,"edit");if(o)return o;if(!U(r))return a("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return d("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),d("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to add tag, missing tag");if(!r)return a("Unable to add tag, missing target");let o=hr(r,"edit");if(o)return o;if(!U(r))return a("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return a("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),d("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),r=this.getNode(e);if(!n)return a("Unable to remove tag, missing tag");if(!r)return a("Unable to remove tag, missing target");let o=hr(r,"edit");if(o)return o;if(!U(r))return a("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return d("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),d("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return a("Tag not found");let n={...t,tombstoned:!0},r=ke(o=>({...o,tags:{...o.tags,[e]:n}}));return l(r)?a("Unable to delete tag"):d("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return a("Tag not found");let r={...n,name:t,tombstoned:!1},o=ke(s=>({...s,tags:{...s.tags,[e]:r}}));return l(o)?a("Unable to restore tag"):d("Restored tag",r)},createTag(e){let t=ke(n=>({...n,tags:{...n.tags,[e.id]:e}}));return l(t)?a("Could not create tag"):d("Tag created",e)},createNode(e){let t=Jr("nodes",e.id,e);return l(t)?a("Unable to create node"):d("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=Jr("nodes",e,n);return l(r)?a(r.message):d("Locked node",n)},updateNode(e){let t=Jr("nodes",e.id,e);return l(t)?t:d("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){let t=v().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return v().tags[e]},getTags(){return Object.values(v().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return v().nodes[e]},getSiblings(e){return Te(e)}}});import vr from"chalk";import Zb from"string-width";var PA,DA,yu,OA,_A,ex,tx,FA,BA,$A,jA,UA,HA,su,nx,gi=g(()=>{"use strict";at();N();Mn();de();D();fn();ni();PA=(e,t)=>e+" ".repeat(Math.max(0,t-Zb(e))),DA=(e,t)=>" ".repeat(Math.max(0,t-Zb(e)))+e,yu=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed contributor","link.contributor.user":"Linked contributor","link.contributor.email":"Claimed","unlink.contributor.email":"Unclaimed","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),OA=(e,t)=>t?e<t?"up":e>t?"down":null:null,_A=(e,t)=>{let n=R.getNode(e.payload.parent),r=n?vr.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=OA(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},ex=e=>`${Math.max(1,Math.round(e/1024))} KB`,tx=e=>R.getAttachment(e)?.name??"",FA=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?vr.bgHex(Ze(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?vr.bgHex(Ze(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=v().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?vr.hex(Ze(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?vr.hex(Ze(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"add.issue.attachment":return`"${e.payload.name}" ${vr.dim(`(${ex(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=tx(e.payload.id);return t?`"${t}"`:""}default:return""}},BA=e=>{let t=cr(it(e));return vr.gray(DA(t,8))},$A=12,jA=e=>PA(`${e}`,$A),UA=e=>{let t=Ee();return l(t)?e:ds(e,t.value.contributors[e]?.name)},HA=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=v().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"move.node":{let t=R.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${ex(e.payload.bytes)})`;case"delete.issue.attachment":{let t=tx(e.payload.id);return t?`"${t}"`:""}default:return""}},su=e=>[yu(e.action),HA(e)].filter(Boolean).join(" "),nx=(e,t)=>{let n=BA(e.id),r=jA(UA(e.userId)),o=vr.dim("\u203A"),s=e.action==="move.node"?_A(e,t):[yu(e.action),FA(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`}});var ox={};ss(ox,{areVirtualNodesEnabled:()=>ba,createOrUpdateVirtualField:()=>zo,createOrUpdateVirtualFieldList:()=>bu,materializeTicketVirtualNodes:()=>ya,materializeVirtualNodes:()=>ZA,setVirtualNodesEnabled:()=>QA});var WA,qA,GA,zA,VA,KA,YA,zo,bu,gl,XA,ya,JA,rx,QA,ba,ZA,Hc=g(()=>{"use strict";gi();ce();N();So();de();ar();D();xo();Qn();WA=e=>we(e,"comments"),qA=e=>we(e,"description"),GA=e=>we(e,"assignees"),zA=e=>we(e,"tags"),VA=e=>we(e,"history"),KA=e=>we(e,"diff"),YA=e=>we(e,"attachments"),zo=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=R.getNode(e);if(!c){let m=R.createNode({...Fe.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return l(m)?m:d("Virtual field created",void 0)}if(!et(c))return a(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==i))return d("Virtual field unchanged",void 0);let p=R.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return l(p)?p:d("Virtual field updated",void 0)},bu=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=R.getNode(e);if(!i){let p=R.createNode({...Fe.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return l(p)?p:d("Virtual field list created",void 0)}if(!ps(i))return a(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return d("Virtual field list unchanged",void 0);let u=R.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return l(u)?u:d("Virtual field list updated",void 0)},gl=null,XA=()=>{if(gl)return d("Virtual field ranks",gl);let e=Dt(an/4n),t=Dt(an/2n),n=Dt(an*3n/4n),r=Dt(an*7n/8n),o=Dt(an*15n/16n),s=Dt(an*13n/16n),i=Dt(an*27n/32n);return l(e)?e:l(t)?t:l(n)?n:l(r)?r:l(o)?o:l(s)?s:l(i)?i:(gl={description:e.value,assignees:t.value,tags:n.value,comments:r.value,attachments:o.value,log:s.value,diff:i.value},d("Virtual field ranks",gl))},ya=e=>{let t=XA();if(l(t))return t;let n=t.value,r=zo({id:qA(e.id),name:Ae.DESCRIPTION,parentNodeId:e.id,rank:n.description,value:e.props.description??"",childRenderAxis:"vertical"});if(l(r))return r;let o=bu({id:GA(e.id),name:Ae.ASSIGNEES,parentNodeId:e.id,rank:n.assignees,readonly:!0});if(l(o))return o;let s=bu({id:zA(e.id),name:Ae.TAGS,parentNodeId:e.id,rank:n.tags,readonly:!0});if(l(s))return s;let i=zo({id:WA(e.id),name:Ae.COMMENTS,parentNodeId:e.id,rank:n.comments,value:"",readonly:!1,childRenderAxis:"vertical"});if(l(i))return i;let c=zo({id:YA(e.id),name:Ae.ATTACHMENTS,parentNodeId:e.id,rank:n.attachments,value:"",readonly:!0,childRenderAxis:"vertical"});if(l(c))return c;let u=zo({id:VA(e.id),name:Ae.HISTORY,parentNodeId:e.id,rank:n.log,value:JA(e),readonly:!0,childRenderAxis:"vertical"});if(l(u))return u;let p=zo({id:KA(e.id),name:Ae.DIFF,parentNodeId:e.id,rank:n.diff,value:"",readonly:!0,childRenderAxis:"vertical"});return l(p)?p:d("Ticket virtual nodes materialized",void 0)},JA=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=>nx(r,n.get(r.action)??[])).join(`
|
|
107
|
+
`)},rx=!0,QA=e=>{rx=e},ba=()=>rx,ZA=()=>{let{nodes:e}=v();for(let t of Object.values(e)){if(!U(t))continue;let n=ya(t);if(l(n))return n}return d("Virtual nodes materialized",void 0)}});var ew,tw,hl,xu=g(()=>{"use strict";at();ew=e=>{switch(e.action){case"add.issue":case"move.node":case"close.issue":case"reopen.issue":return e.payload.parent;default:return null}},tw=(e,t)=>{let n=[];for(let r of e){let o=ew(r);if(o===null||o===n.at(-1)?.laneId)continue;let s=Ir(r);n.push({laneId:o,enteredAt:s===null?t:ls(s)})}return n},hl=(e,t)=>tw(e,t).at(-1)?.enteredAt??t});var sx=g(()=>{"use strict";en()});var nw,ix,vl=g(()=>{"use strict";at();$();tr();gi();N();sx();Mn();on();nw=e=>{let t=new Map,n=new Set,r=o=>{let s=new Set,i=o;for(;i&&!s.has(i);){if(n.has(i))return i;s.add(i),i=t.get(i)}return null};return e.map(o=>{let s=o.payload,i=s?.id;if(!i)return null;o.action==="add.board"&&n.add(i);let c=o.action==="close.issue"?r(i):null,u=s.parent??s.issue;return u&&t.set(i,u),c!==null?c:n.has(i)?i:r(i)})},ix=(e,t)=>{let n=nw(e);return e.filter((r,o)=>n[o]===t)}});var rw,ax,lx,Qr,xi=g(()=>{"use strict";nt();_o();vl();$();$();N();D();on();vl();rw=null,ax=Promise.resolve(),lx=e=>{let t=ax.then(e,e);return ax=t.then(()=>{},()=>{}),t},Qr=()=>{if(!qt())return{mode:"live",asOfTime:null};let{timeMode:e}=v();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:rw}}});var cx,ow,dx,ux,Zr,Ii=g(()=>{"use strict";ze();wt();cx=new Map,ow=3e4,dx=async e=>{let t=cx.get(e);if(t&&Date.now()-t.readAt<ow)return{name:t.name,email:t.email};let n=await Me({args:["config","--get-regexp","^user\\.(name|email)$"],cwd:e}),r=null,o=null;if(n.exitCode===0)for(let s of(n.stdout??"").split(`
|
|
108
|
+
`)){let i=s.indexOf(" ");if(i===-1)continue;let c=s.slice(0,i),u=s.slice(i+1);c==="user.name"&&(r=u.trim()||null),c==="user.email"&&(o=Ge(u)||null)}return cx.set(e,{name:r,email:o,readAt:Date.now()}),{name:r,email:o}},ux=async e=>(await dx(e)).email,Zr=async e=>(await dx(e)).name});import sw from"node:fs";var eo,yl,iw,Jt,pt,ft,ue,mn=g(()=>{"use strict";nt();ze();gn();Js();Ii();In();$e();Ur();tr();Q();$();N();D();Bt();xi();eo=e=>{let t=Ne(e??process.cwd());return l(t)?a(t.message):d("Resolved Epiq repo root",t.value)},yl=null,iw=async(e,t)=>{let n=eo(e);if(l(n))return n;let r=be({repoRoot:n.value});if(l(r))return a(r.message);let o=tt(n.value);if(l(o))return a(o.message);if(!(yl!==null&&yl.repoRoot===n.value&&yl.stateBranchRoot===r.value&&sw.existsSync(wr(r.value)))){let f=await Ys({repoRoot:n.value,stateBranchName:o.value});if(l(f))return a(f.message);let h=await lr({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(l(h))return a(h.message);yl={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let f=await W({cwd:r.value,args:["pull","--ff-only"]});l(f)&&ie.info(3,f.message)}let i={repoRoot:n.value,stateBranchRoot:r.value},c=Jn();l(c)||ct(c.value),ct({gitEmail:await ux(n.value),gitName:await Zr(n.value)});let u=Wt(r.value);if($f(r.value)===u&&qt()&&Qr().mode==="live")return d("Booted Epiq state, unchanged",i);let p=cn(r.value);if(l(p))return a(p.message);let m=Rn(p.value.events,p.value.unreadable);return l(m)?a(m.message):(Io(r.value,u),d("Booted Epiq state",i))},Jt=()=>{let e=Jn();return l(e)?a(e.message):e.value.userId?e.value.userName?d("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},pt=()=>{let e=Ee();return l(e)?a(e.message):e},ft=e=>iw(e,{pull:!1}),ue=async e=>{let t=await ft(e);if(l(t))return t;let n=Jt();if(l(n))return n;let r=pt();return l(r)?r:d("Booted",{boot:t.value,actor:n.value,state:r.value})}});var aw,bl,Vo,mx,Ko,Iu=g(()=>{"use strict";at();de();Mn();mo();aw=e=>{let t=R.getNode(e);if(!t)return[];let n=new Set;t.parentNodeId&&n.add(t.parentNodeId);for(let r of t.log??[]){let o=r.payload;o.id===e&&o.parent&&n.add(o.parent)}return[...n]},bl=e=>{let t=new Set;e.parentNodeId&&t.add(e.parentNodeId);for(let r of e.log??[]){let o=r.payload;o.id===e.id&&o.parent&&t.add(o.parent)}let n=new Set;for(let r of t)for(let o of aw(r))n.add(o);return[...n]},Vo=e=>yn(e).map(t=>ht(t.id,t.name)),mx=e=>R.getCommentsByIssue(e).sort((t,n)=>t.id<n.id?-1:t.id>n.id?1:0).map(t=>({id:t.id,author:ds(t.authorId,R.getContributor(t.authorId)?.name),createdAt:it(t.id),body:t.md})),Ko=e=>bn(e).map(({id:t,name:n})=>ht(t,n))});var Je,yr,Eu,to=g(()=>{"use strict";ce();N();mn();Je=e=>{let t=pt();if(l(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?a("Issue not found"):U(n)?n.readonly?a("Issue is readonly"):d("Found issue",n):a("Target must be an issue")},yr=e=>{let t=pt();if(l(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?a("Swimlane not found"):Er(n)?n.readonly?a("Swimlane is readonly"):d("Found swimlane",n):a("Target must be a swimlane")},Eu=e=>{let t=pt();if(l(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?a("Board not found"):Sr(n)?n.readonly?a("Board is readonly"):d("Found board",n):a("Target must be a board")}});import lw from"node:fs";import cw from"node:path";import{ulid as px}from"ulid";var dw,fx,Su,Ru=g(()=>{"use strict";In();$();Ut();N();vt();to();go();mn();dw=e=>{if(e.filePath)try{return d("Read attachment file",{data:lw.readFileSync(e.filePath),name:e.name??cw.basename(e.filePath)})}catch(t){return a(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?d("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):a("Provide either filePath or dataBase64")},fx=()=>{let e=Jn();return l(e)?On:e.value.attachmentMaxKb??On},Su=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=Je(e.issueId);if(l(n))return n;let r=dw(e);if(l(r))return r;let o=tf(t.value.boot.stateBranchRoot,r.value.data,fx());if(l(o))return o;let s=Se(r.value.name).trim()||"image",i=px(),c={id:px(),...O(t.value.actor),action:"add.issue.attachment",payload:{id:i,issue:e.issueId,author:t.value.actor.userId,hash:o.value.hash,ext:o.value.ext,name:s,bytes:o.value.bytes}},u=_([c],t.value.boot.stateBranchRoot);if(l(u))return a(u.message);let p=fo(o.value.hash,o.value.ext);return d("Added issue attachment",{id:i,issueId:e.issueId,fileName:p,bytes:o.value.bytes,markdown:gc(s,p)})}});var Nu,bJ,Cu,gx=g(()=>{"use strict";In();at();on();ce();N();de();co();Mn();fn();xu();mt();vt();go();Bt();xi();mn();Iu();Ru();Ta();$();Vs();Nu=async(e={})=>{let t=await ft(e.repoRoot);if(l(t))return t;let n=pt();return l(n)?n:d("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})},bJ=365*24*60*60*1e3,Cu=async(e={})=>{Ro();let t=eo(e.repoRoot);if(l(t))return a("Sync failed");let n=Jt();if(l(n))return n;let r=await wa({cwd:t.value,ownEventFileName:sr(n.value)});return l(r)?(Kc(r.message),r):(Hr(),d("Synced",r.value))}});var Ei,Yo,Si,Au=g(()=>{"use strict";N();mt();Ei=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?d("Resolved targets",t):a("Provide issueId or issueIds")},Yo=(e,t)=>{let n=t.done.length,r=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?d(r,t):a(`${r}: ${t.failed.map(o=>`${o.ref} ${o.reason}`).join("; ")}`)},Si=(e,t)=>{let n={done:[],failed:[]};for(let r of e){let o=t(r);l(o)?n.failed.push({id:r,ref:V(r),reason:o.message}):n.done.push({id:r,ref:V(r)})}return n}});import{ulid as Qt}from"ulid";async function Tu(e){let t=await ft(e.repoRoot);if(l(t))return t;let n=pt();if(l(n))return n;let r=n.value.nodes,o=e.query?.trim().toLowerCase(),s=Object.values(r).filter(U).filter(c=>!c.isDeleted).filter(c=>e.includeClosed||c.parentNodeId!==Ce).filter(c=>e.boardId?(c.parentNodeId?r[c.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(c=>!e.swimlaneId||c.parentNodeId===e.swimlaneId).filter(c=>!e.tag||Vo(c).some(u=>hx(u.name,e.tag))).filter(c=>!e.assignee||Ko(c).some(u=>hx(u.name,e.assignee))).filter(c=>!o||c.title.toLowerCase().includes(o)||(c.props.description??"").toLowerCase().includes(o)),i=c=>Se((c.parentNodeId?r[c.parentNodeId]?.title:void 0)??"");return e.brief?d("Listed issues",s.map(c=>({id:c.id,ref:V(c.id),title:Se(c.title),swimlane:i(c),tags:Vo(c).map(u=>u.name),assignees:Ko(c).map(u=>u.name)}))):d("Listed issues",s.map(c=>({id:c.id,ref:V(c.id),title:Se(c.title),description:c.props.description??"",createdAt:it(c.id),enteredLaneAt:hl(c.log??[],it(c.id)),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===Ce,boardIds:bl(c),readonly:!!c.readonly,tags:Vo(c),assignees:Ko(c)})))}async function ku(e){let t=await ft(e.repoRoot);if(l(t))return t;let n=Jt();if(l(n))return n;let r=Ei(e);if(l(r))return r;let o=s=>uw(s,n.value,t.value.stateBranchRoot);return e.issueIds?Yo("Closed",Si(r.value,o)):o(r.value[0])}async function Pu(e){let t=eo(e.repoRoot);if(l(t))return t;let n=Jt();if(l(n))return n;let r=be({repoRoot:t.value});if(l(r))return r;let o=cn(r.value);if(l(o))return o;let s=Rn(o.value.events,o.value.unreadable);if(l(s))return s;let i=Ei(e);if(l(i))return i;let c=u=>mw(u,e,n.value,r.value);return e.issueIds?Yo("Moved",Si(i.value,c)):c(i.value[0])}var wu,hx,Mu,uw,Lu,mw,Du,Ou,vx=g(()=>{"use strict";nt();tu();at();Ur();$();$();Ut();iu();on();ce();Mn();N();de();Ht();gi();_n();xu();mt();vt();mn();Iu();Au();to();wu=async e=>{let t=await ft(e.repoRoot);if(l(t))return t;let n=pt();if(l(n))return n;let r=e.idOrRef.trim();if(!r)return a("Provide an issue id or ref");let o=Object.values(n.value.nodes).filter(U).filter(u=>!u.isDeleted),s=o.find(u=>u.id===r),i=s?[s]:o.filter(u=>Us(u.id,r));if(i.length===0)return a(`No issue matches "${r}"`);if(i.length>1)return a(`"${r}" matches ${i.length} issues: ${i.map(u=>`${V(u.id)} (${Se(u.title)})`).join(", ")}. Use a full ref or id.`);let c=i[0];return d("Found issue",{id:c.id,ref:V(c.id),title:Se(c.title),description:c.props.description??"",createdAt:it(c.id),enteredLaneAt:hl(c.log??[],it(c.id)),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===Ce,boardIds:bl(c),readonly:!!c.readonly,tags:Vo(c),assignees:Ko(c),comments:mx(c.id)})},hx=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();Mu=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=Se(e.title);if(!n)return a("Issue title cannot be empty");let r=e.description??"",o=rt("Issue title",n,300)??rt("Issue description",r,2e4);if(o)return a(o);if((e.tagNames?.length??0)>20)return a(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return a(`Cannot set more than ${20} assignees at once`);let s=yr(e.parentId);if(l(s))return s;let i=$n(e.parentId,t.value.actor,t.value.boot.stateBranchRoot);if(l(i))return i;let c=nl({name:n,parent:e.parentId,user:t.value.actor,rank:i.value});if(l(c))return c;let u=[...c.value],p=u.find(b=>b.action==="add.issue")?.payload.id;if(!p)return a("Unable to determine created issue id");r&&u.push({id:Qt(),...O(t.value.actor),action:"edit.description",payload:{id:p,md:r}});let m=[];for(let b of e.tagNames??[]){let I=Se(b).trim();if(!I||m.some(M=>M.name===I))continue;let C=rt("Tag name",I,60);if(C)return a(C);let T=R.findTagByName(I),S=T?.id??Qt();T||u.push({id:Qt(),...O(t.value.actor),action:"create.tag",payload:{id:S,name:I}}),u.push({id:Qt(),...O(t.value.actor),action:"add.issue.tag",payload:{id:p,tag:S}}),m.push({id:S,name:I})}let f=[];for(let b of e.assigneeNames??[]){let I=Se(b).trim();if(!I||f.some(M=>M.name===I))continue;let C=rt("Assignee name",I,80);if(C)return a(C);let T=Object.values(t.value.state.contributors).find(M=>M.name===I),S=T?.id??Qt();T||u.push({id:Qt(),...O(t.value.actor),action:"create.contributor",payload:{id:S,name:I}}),u.push({id:Qt(),...O(t.value.actor),action:"add.issue.assignee",payload:{id:p,assignee:S}}),f.push({id:S,name:I})}let h=_(u,t.value.boot.stateBranchRoot);return l(h)?a(h.message):d("Created issue",{id:p,ref:V(p),title:n,parentId:e.parentId,description:r,tags:m,assignees:f})},uw=(e,t,n)=>{let r=Je(e);if(l(r))return r;let o=En(Ce,e,{at:"end"},t,n);if(l(o))return o;let s={id:Qt(),...O(t),action:"close.issue",payload:{id:e,parent:Ce,rank:o.value}},i=_([s],n);return l(i)?a(i.message):d("Closed issue",{id:e,ref:V(e)})};Lu=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=t.value.state.nodes[e.issueId];if(!n||n.isDeleted)return a("Issue not found");if(!U(n))return a("Target must be an issue");if(n.parentNodeId!==Ce)return a("Issue is not closed");let r=al(n);if(!r)return a("Unable to resolve previous parent from issue history");if(r===Ce)return a("Previous parent resolves to closed swimlane");let o=yr(r);if(l(o))return o;let s=o.value,i=En(s.id,n.id,{at:"end"},t.value.actor,t.value.boot.stateBranchRoot);if(l(i))return i;let c={id:Qt(),...O(t.value.actor),action:"reopen.issue",payload:{id:n.id,parent:s.id,rank:i.value}},u=_([c],t.value.boot.stateBranchRoot);return l(u)?a(u.message):d("Reopened issue",{id:n.id,ref:V(n.id),parentId:s.id})},mw=(e,t,n,r)=>{let o=Je(e);if(l(o))return o;let s=yr(t.parentId);if(l(s))return s;let i=En(t.parentId,e,t.position??{at:"end"},n,r);if(l(i))return i;let c={id:Qt(),...O(n),action:"move.node",payload:{id:e,parent:t.parentId,rank:i.value}},u=_([c],r);return l(u)?a(u.message):d("Moved issue",{id:e,ref:V(e),parentId:t.parentId})};Du=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=Je(e.issueId);if(l(n))return n;let r=n.value,o=rt("Issue description",e.description,2e4);if(o)return a(o);let s=r.props.description??"";if(s===e.description)return d("No changes made",{id:e.issueId,ref:V(e.issueId),description:s});let i={id:Qt(),...O(t.value.actor),action:"edit.description",payload:{id:e.issueId,md:e.description}},c=_([i],t.value.boot.stateBranchRoot);return l(c)?a(c.message):d("Edited issue description",{id:e.issueId,ref:V(e.issueId),description:e.description})},Ou=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=Je(e.issueId);if(l(n))return n;let r=n.value,o=Se(e.title);if(!o.trim())return a("Issue title cannot be empty");let s=rt("Issue title",o,300);if(s)return a(s);if(r.title===o)return d("No changes made",{id:e.issueId,ref:V(e.issueId),title:o});let i={id:Qt(),...O(t.value.actor),action:"edit.title",payload:{id:e.issueId,name:o}},c=_([i],t.value.boot.stateBranchRoot);return l(c)?a(c.message):d("Edited issue title",{id:e.issueId,ref:V(e.issueId),title:o})}});import{ulid as br}from"ulid";var _u,Fu,Bu,$u,ju,Uu,Hu,Wu,yx=g(()=>{"use strict";nt();Ur();$();$();Ut();on();ce();N();Ht();_n();mt();vt();xi();mn();to();_u=async(e={})=>{let t=await ft(e.repoRoot);if(l(t))return t;let n=pt();if(l(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 d("Listed boards",r)},Fu=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=t.value.state.nodes[t.value.state.rootNodeId];if(!n)return a("Workspace not found");if(Qr().mode!=="live")return a("Cannot add a board while time travelling");let r=Se(e.title);if(!r.trim())return a("Board title cannot be empty");let o=rt("Board title",r,300);if(o)return a(o);let s=$n(n.id,t.value.actor,t.value.boot.stateBranchRoot);if(l(s))return s;let i=br(),c={id:br(),...O(t.value.actor),action:"add.board",payload:{id:i,name:r,parent:n.id,rank:s.value}},u=_([c],t.value.boot.stateBranchRoot);return l(u)?a(u.message):d("Created board",{id:i,ref:V(i),title:r})},Bu=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=t.value.state.nodes[e.boardId];if(!n||n.isDeleted)return a("Board not found");if(!Sr(n))return a("Edit target must be a board");if(n.readonly)return a("Cannot edit readonly board");if(Qr().mode!=="live")return a("Cannot rename a board while time travelling");let r=Se(e.title);if(!r.trim())return a("Board title cannot be empty");let o=rt("Board title",r,300);if(o)return a(o);if(n.title===r)return d("No changes made",{id:e.boardId,ref:V(e.boardId),title:r});let s={id:br(),...O(t.value.actor),action:"edit.title",payload:{id:e.boardId,name:r}},i=_([s],t.value.boot.stateBranchRoot);return l(i)?a(i.message):d("Edited board title",{id:e.boardId,ref:V(e.boardId),title:r})},$u=async(e={})=>{let t=await ft(e.repoRoot);if(l(t))return t;let n=pt();if(l(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===Ce,readonly:!!o.readonly}));return d("Listed swimlanes",r)},ju=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=Eu(e.boardId);if(l(n))return n;if(Qr().mode!=="live")return a("Cannot add a swimlane while time travelling");let r=Se(e.title);if(!r.trim())return a("Swimlane title cannot be empty");let o=rt("Swimlane title",r,300);if(o)return a(o);let s=$n(e.boardId,t.value.actor,t.value.boot.stateBranchRoot);if(l(s))return s;let i=br(),c={id:br(),...O(t.value.actor),action:"add.swimlane",payload:{id:i,name:r,parent:e.boardId,rank:s.value}},u=_([c],t.value.boot.stateBranchRoot);return l(u)?a(u.message):d("Created swimlane",{id:i,ref:V(i),title:r,boardId:e.boardId})},Uu=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=yr(e.swimlaneId);if(l(n))return n;let r=n.value,o=Se(e.title);if(!o.trim())return a("Swimlane title cannot be empty");let s=rt("Swimlane title",o,300);if(s)return a(s);if(r.title===o)return d("No changes made",{id:e.swimlaneId,ref:V(e.swimlaneId),title:o});let i={id:br(),...O(t.value.actor),action:"edit.title",payload:{id:e.swimlaneId,name:o}},c=_([i],t.value.boot.stateBranchRoot);return l(c)?a(c.message):d("Edited swimlane title",{id:e.swimlaneId,ref:V(e.swimlaneId),title:o})},Hu=async e=>{let t=eo(e.repoRoot);if(l(t))return t;let n=Jt();if(l(n))return n;let r=be({repoRoot:t.value});if(l(r))return r;let o=cn(r.value);if(l(o))return o;let s=Rn(o.value.events,o.value.unreadable);if(l(s))return s;let i=yr(e.swimlaneId);if(l(i))return i;let c=Eu(e.boardId);if(l(c))return c;let u=En(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(l(u))return u;let p={id:br(),...O(n.value),action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:u.value}},m=_([p],r.value);return l(m)?a(m.message):d("Moved swimlane",{id:e.swimlaneId,ref:V(e.swimlaneId),boardId:e.boardId})},Wu=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=yr(e.swimlaneId);if(l(n))return n;let r={id:br(),...O(t.value.actor),action:"delete.node",payload:{id:e.swimlaneId}},o=_([r],t.value.boot.stateBranchRoot);return l(o)?a(o.message):d("Deleted swimlane",{id:e.swimlaneId,ref:V(e.swimlaneId)})}});import{ulid as Qo}from"ulid";async function qu(e){let t=await ft(e.repoRoot);if(l(t))return t;let n=Jt();if(l(n))return n;let r=Ei(e);if(l(r))return r;let o=Se(e.tagName).trim();if(!o)return a("Tag name cannot be empty");let s=rt("Tag name",o,60);if(s)return a(s);let i=Si(r.value,Je);if(!e.issueIds&&i.failed[0])return a(i.failed[0].reason);if(i.done.length===0)return a(Yo("Tagged",i).message);let c=R.findTagByName(o),u=c?.id??Qo(),p=[...c?[]:[{id:Qo(),...O(n.value),action:"create.tag",payload:{id:u,name:o}}],...i.done.map(({id:b})=>({id:Qo(),...O(n.value),action:"add.issue.tag",payload:{id:b,tag:u}}))],m=_(p,t.value.stateBranchRoot);if(l(m))return a(m.message);let f={id:u,name:o};if(!e.issueIds)return d("Added issue tag",{...i.done[0],tag:f});let h=Yo("Tagged",i);return l(h)?h:d(h.message,{...h.value,tag:f})}var Gu,zu,Vu,bx=g(()=>{"use strict";$();Ut();N();de();_n();mt();vt();mn();Au();to();Gu=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=t.value.state.tags[e.tagId];if(!n)return a("Tag not found");if(n.tombstoned)return a("Tag is already deleted");let r=[{id:Qo(),...O(t.value.actor),action:"tombstone.tag",payload:{id:e.tagId}}],o=_(r,t.value.boot.stateBranchRoot);return l(o)?a(o.message):d("Deleted tag",{id:n.id,name:n.name})},zu=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=t.value.state.tags[e.tagId];if(!n)return a("Tag not found");if(!n.tombstoned)return a("Tag is not deleted");if(R.findTagByName(n.name))return a(`Cannot restore: another tag is already named "${n.name}"`);let r=[{id:Qo(),...O(t.value.actor),action:"restore.tag",payload:{id:e.tagId,name:n.name}}],o=_(r,t.value.boot.stateBranchRoot);return l(o)?a(o.message):d("Restored tag",{id:n.id,name:n.name})},Vu=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=Je(e.issueId);if(l(n))return n;if(!t.value.state.tags[e.tagId])return a("Tag not found");let r={id:Qo(),...O(t.value.actor),action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},o=_([r],t.value.boot.stateBranchRoot);return l(o)?a(o.message):d("Removed issue tag",{id:e.issueId,ref:V(e.issueId),tagId:e.tagId})}});import{ulid as zn}from"ulid";var Ku,xx,Yu,Xu,pw,Ju,Qu,Zu,Ix=g(()=>{"use strict";N();en();xr();$();$();Ut();ll();Mn();vl();_n();mt();vt();mn();to();Ku=async e=>{let t=Ml(e.name,"name");if(l(t))return a(t.message);let n=await ue(e.repoRoot);if(l(n))return n;let r=n.value.actor,o=!!n.value.state.contributors[r.userId];if(!o){let s=_([{id:zn(),...O(r),action:"create.contributor",payload:{id:r.userId,name:r.userName}}],n.value.boot.stateBranchRoot);if(l(s))return a(s.message)}return d(`Assumed ${r.userName}`,{...r,registered:!o})},xx=async(e,t)=>{let n=Br(e).get(t);return n===void 0?void 0:{id:t,name:n}},Yu=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=Je(e.issueId);if(l(n))return n;let r=e.self?t.value.actor.userId:e.assigneeId;if(r){let b=t.value.state.contributors[r],I=b?void 0:await xx(t.value.boot.stateBranchRoot,r);if(!b&&!I)return a("Unknown assignee id");let C=b??I,T=[...b?[]:[{id:zn(),...O(t.value.actor),action:"create.contributor",payload:{id:C.id,name:C.name}}],{id:zn(),...O(t.value.actor),action:"add.issue.assignee",payload:{id:e.issueId,assignee:C.id}}],S=_(T,t.value.boot.stateBranchRoot);return l(S)?a(S.message):d("Added issue assignee",{id:e.issueId,ref:V(e.issueId),assignee:{id:C.id,name:C.name}})}let o=Se(e.assigneeName??"").trim();if(!o)return a("Provide assigneeId, self or assigneeName");let s=rt("Assignee name",o,80);if(s)return a(s);let i=vi({events:t.value.state.eventLog??[],registry:t.value.state.contributors,logFileNames:Br(t.value.boot.stateBranchRoot)}).filter(b=>b.name===o);if(i.length>1)return a(`"${o}" matches ${i.length} contributors (${i.map(({id:b})=>b).join(", ")}). Assign by assigneeId to choose.`);let c=i[0];if(!c&&!e.createUnlinked)return a(`No contributor named "${o}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let u=c?.id??zn(),p=c?.name??o,f=[...!!t.value.state.contributors[u]?[]:[{id:zn(),...O(t.value.actor),action:"create.contributor",payload:{id:u,name:p}}],{id:zn(),...O(t.value.actor),action:"add.issue.assignee",payload:{id:e.issueId,assignee:u}}],h=_(f,t.value.boot.stateBranchRoot);return l(h)?a(h.message):d("Added issue assignee",{id:e.issueId,ref:V(e.issueId),assignee:{id:u,name:p}})},Xu=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;if(!t.value.state.contributors[e.contributorId])return a("Contributor not found");if(await xx(t.value.boot.stateBranchRoot,e.contributorId))return a("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let o=[{id:zn(),...O(t.value.actor),action:"tombstone.contributor",payload:{id:e.contributorId}}],s=_(o,t.value.boot.stateBranchRoot);return l(s)?a(s.message):d("Tombstoned contributor",{id:e.contributorId,name:us})},pw=async(e,t)=>{let n=$r(e);if(l(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},Ju=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=t.value.state.contributors[e.contributorId];if(!n)return a("Contributor not found");if(!n.tombstoned)return a("Contributor is not tombstoned");let r=await pw(t.value.boot.stateBranchRoot,e.contributorId);if(!r)return a("Cannot restore this contributor \u2014 no original name found in the event log");let o=[{id:zn(),...O(t.value.actor),action:"restore.contributor",payload:{id:e.contributorId,name:r}}],s=_(o,t.value.boot.stateBranchRoot);return l(s)?a(s.message):d("Restored contributor",{id:e.contributorId,name:r})},Qu=async(e={})=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=$r(t.value.boot.stateBranchRoot);if(l(n))return a(n.message);let r=e.boardId?ix(n.value,e.boardId):n.value,o=new Set,s=Sg(t.value.boot.stateBranchRoot);if(l(s))return a(s.message);for(let u of s.value)u.userId&&o.add(u.userId);let i=t.value.state.contributors,c=vi({events:r,registry:i,logFileNames:Br(t.value.boot.stateBranchRoot)}).map(({id:u,name:p,isExternal:m})=>({...ht(u,p),isSelf:u===t.value.actor.userId,isExternal:m,isRemoved:i[u]?.tombstoned===!0,hasAuthoredAnywhere:o.has(u)}));return d("Listed board contributors",c)},Zu=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=Je(e.issueId);if(l(n))return n;if(!t.value.state.contributors[e.assigneeId])return a("Assignee not found");let r={id:zn(),...O(t.value.actor),action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},o=_([r],t.value.boot.stateBranchRoot);return l(o)?a(o.message):d("Removed issue assignee",{id:e.issueId,ref:V(e.issueId),assigneeId:e.assigneeId})}});import{ulid as El}from"ulid";var em,tm,nm,Ex=g(()=>{"use strict";$();Ut();N();_n();mn();to();em=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=Je(e.issueId);if(l(n))return n;let r=e.body.trim();if(!r)return a("Comment cannot be empty");if(r.length>4e3)return a(`Comment cannot exceed ${4e3} characters (got ${r.length})`);let o=El(),s={id:El(),...O(t.value.actor),action:"add.issue.comment",payload:{id:o,issue:e.issueId,md:r,author:t.value.actor.userId}},i=_([s],t.value.boot.stateBranchRoot);return l(i)?a(i.message):d("Added issue comment",{id:o,issueId:e.issueId,body:r})},tm=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=t.value.state.eventLog.find(c=>c.action==="add.issue.comment"&&c.payload.id===e.commentId);if(!n)return a("Unable to resolve comment");if(n.payload.author!==t.value.actor.userId)return a("You can only delete your own comments");let r=Je(n.payload.issue);if(l(r))return r;if(t.value.state.eventLog.some(c=>c.action==="delete.issue.comment"&&c.payload.id===e.commentId))return d("Comment already deleted",{id:e.commentId,issueId:n.payload.issue});let s={id:El(),...O(t.value.actor),action:"delete.issue.comment",payload:{id:e.commentId,issue:n.payload.issue}},i=_([s],t.value.boot.stateBranchRoot);return l(i)?a(i.message):d("Deleted issue comment",{id:e.commentId,issueId:n.payload.issue})},nm=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=t.value.state.eventLog.find(u=>u.action==="add.issue.comment"&&u.payload.id===e.commentId);if(!n)return a("Unable to resolve comment");if(n.payload.author!==t.value.actor.userId)return a("You can only edit your own comments");let r=Je(n.payload.issue);if(l(r))return r;if(t.value.state.eventLog.some(u=>u.action==="delete.issue.comment"&&u.payload.id===e.commentId))return a("Comment was deleted");let s=e.body.trim();if(!s)return a("Comment cannot be empty");if(s.length>4e3)return a(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i={id:El(),...O(t.value.actor),action:"edit.issue.comment",payload:{id:e.commentId,issue:n.payload.issue,md:s}},c=_([i],t.value.boot.stateBranchRoot);return l(c)?a(c.message):d("Edited issue comment",{id:e.commentId,issueId:n.payload.issue,body:s})}});import{ulid as Sx}from"ulid";var rm,om,sm,im,am=g(()=>{"use strict";$();wt();Mn();N();gn();Ii();ml();$e();mn();rm=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;if(!Vn(e.email))return a(`Not an email address: ${e.email}`);let n=Ge(e.email),r=e.contributorId??t.value.actor.userId;if(!t.value.state.contributors[r])return a(`Unknown contributor: ${r}`);let o=Bl(t.value.state.emailLinks,n);if(o.includes(r))return d(`${n} is already yours`,{contributor:r,email:n,contested:o.filter(i=>i!==r)});let s=_([{id:Sx(),action:"link.contributor.email",payload:{contributor:r,email:n},userId:t.value.actor.userId}],t.value.boot.stateBranchRoot);return l(s)?a(s.message):d(o.length>0?`Claimed ${n}, but somebody else claims it too, so it now resolves to neither of you`:`Claimed ${n}`,{contributor:r,email:n,contested:o})},om=async e=>{let t=await ue(e.repoRoot);if(l(t))return t;let n=Ge(e.email),r=e.contributorId??t.value.actor.userId,o=t.value.state.emailLinks[ms(n,r)];if(!o||o.tombstoned)return a(`No such link: ${n} to ${r}`);if(!Li(t.value.actor.userId,o))return a("Only whoever made a claim, or the contributor it names, may undo it");let s=_([{id:Sx(),action:"unlink.contributor.email",payload:{contributor:r,email:n},userId:t.value.actor.userId}],t.value.boot.stateBranchRoot);return l(s)?a(s.message):d(`Unclaimed ${n}`,{contributor:r,email:n})},sm=async(e={})=>{let t=await ft(e.repoRoot);if(l(t))return t;let n=pt();if(l(n))return n;let{emailLinks:r,contributors:o}=n.value,s=new Map;for(let f of Object.values(r)){if(f.tombstoned)continue;let h=s.get(f.email)??new Set;h.add(f.contributor),s.set(f.email,h)}let i=[...s.entries()].map(([f,h])=>({email:f,contested:h.size>1,claimants:[...h].map(b=>ht(b,o[b]?.name))})).sort((f,h)=>f.email.localeCompare(h.email)),c=Jt(),u=l(c)?[]:Kn(r,c.value.userId),p=ae().gitEmail,m=p?Bl(r,p).filter(f=>l(c)||f!==c.value.userId):[];return d("Listed contributor emails",{emails:i,mine:u,git:p?{email:p,linkedToMe:u.includes(p),heldByOthers:m.map(f=>ht(f,o[f]?.name))}:null})},im=async(e={})=>{let t=await ue(e.repoRoot);if(l(t))return t;let{userId:n,userName:r}=t.value.actor,o=tt(t.value.boot.repoRoot),s=await yi({repoRoot:t.value.boot.repoRoot,stateBranch:l(o)?void 0:o.value,names:[r,await Zr(t.value.boot.repoRoot)],links:t.value.state.emailLinks});if(l(s))return s;let i=ul(s.value),c=i.filter(u=>u.looksLikeYours);return d(i.length===0?"No unclaimed addresses in this history":`${i.length} unclaimed address(es) in this history, ${c.length>0?`${c.length} of which look like yours`:"none obviously yours"}. Show them to the user and link only the ones they confirm; each is a permanent event that replicates to every clone.`,{contributor:n,candidates:i,likely:c.length})}});var Rx=g(()=>{"use strict";at();N()});var Nx=g(()=>{"use strict";gn();Ii();N();ml();Rx();mn()});var Cx=g(()=>{"use strict";gx();vx();yx();bx();Ix();Ex();Ru();am();Nx()});import{ulid as fw}from"ulid";var Ax,wx,Tx,Mx=g(()=>{"use strict";xr();co();Ii();In();N();Jd();Bt();Ax=[{name:"userName",question:"the name they want to appear under on the board"},{name:"preferredEditor",question:'the command that opens a file for editing, e.g. "vim", "nano" or "code --wait"'},{name:"autoSync",question:"whether the TUI and GUI should sync with the git remote on their own (true or false)"}],wx=e=>e.trim().toLowerCase(),Tx=async(e={})=>{let t=xn();if(l(t))return a(t.message);let n=t.value,r=e.userName?.trim(),o=(process.env[Ft]??"").trim();if(r&&o&&wx(r)===wx(o))return a(`userName "${r}" is this agent's own identity. Pass the user's name, the one they want the TUI and GUI to write as.`);let s={userName:r||void 0,preferredEditor:e.preferredEditor?.trim()||void 0,autoSync:e.autoSync},i={userName:n.userName?.trim()||void 0,preferredEditor:n.preferredEditor?.trim()||void 0,autoSync:typeof n.autoSync=="boolean"?n.autoSync:void 0};for(let T of Ax){let S=s[T.name],M=i[T.name];if(!(S===void 0||M===void 0||S===M))return a(`This machine is already set up with ${T.name} ${JSON.stringify(M)}; epiq_project_init does not change it. Call again without ${T.name}, or let the user change it in the TUI with :config.`)}let c={};if(s.userName&&!i.userName&&(c.userName=s.userName),s.preferredEditor&&!i.preferredEditor&&(c.preferredEditor=s.preferredEditor),s.autoSync!==void 0&&i.autoSync===void 0&&(c.autoSync=s.autoSync),(c.userName||i.userName)&&!n.userId&&(c.userId=fw()),Object.keys(c).length>0){let T=It(c);if(l(T))return a(T.message)}let u={...n,...c},p=Ax.filter(T=>{let S=u[T.name];return typeof S=="boolean"?!1:!S?.trim()});if(p.length>0){let T=p.map(L=>`${L.name} (${L.question})`).join("; "),S=p.some(L=>L.name==="userName")?await Zr(e.repoRoot??process.cwd()):null,M=S?` This repository's git user.name is ${JSON.stringify(S)} \u2014 offer it as the default for userName, and use it only if the user agrees.`:"";return a(`Setup incomplete. Ask the user for: ${T}.${M} Then call epiq_project_init again with the answers; what was given so far is saved.`)}let m={userId:u.userId??"",userName:u.userName??""};if(!m.userId||!m.userName)return a("Missing Epiq user id");let f=await tl({cwd:e.repoRoot??process.cwd(),user:m});if(l(f))return f;let{defaultEvents:h,...b}=f.value,I=Ns({root:b.repoRoot});l(I)&&ie.info(I.message);let C=b.warnings.length===0?"Project initialized":`Project initialized, with warnings: ${b.warnings.join(" ")}`;return d(C,{...b,user:m})}});var wn,Sl=g(()=>{"use strict";wn=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""})});var gw,kx,Lx=g(()=>{"use strict";Sl();gw=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},kx=({commits:e,patch:t})=>{let n=e.map(i=>i.time),o=t.files.map(i=>({...wn(i),changed:i.addedCount+i.removed})).reduce((i,c)=>i===null||c.changed>i.changed?c:i,null),s=t.insertions+t.deletions;return{commits:e.length,authors:[...new Set(e.map(i=>i.author))].sort(),firstCommitAt:n.length?Math.min(...n):null,lastCommitAt:n.length?Math.max(...n):null,files:t.files.length,filesAdded:t.files.filter(i=>i.status==="added").length,filesModified:t.files.filter(i=>i.status==="modified").length,filesDeleted:t.files.filter(i=>i.status==="deleted").length,binaryFiles:t.files.filter(i=>i.binary).length,directories:new Set(t.files.map(i=>gw(i.path))).size,insertions:t.insertions,deletions:t.deletions,net:t.insertions-t.deletions,largestFile:o,concentration:o&&s>0?o.changed/s:0,selfChurn:t.selfChurn,truncated:t.truncated}}});var Ke,Zt,lm,Zo,hw,J,Rl,Nl,Px,vw,Dx,no,Ni,yw,bw,es,xw,Iw,Ew,pn,Ox,_x,Fx,Sw,Rw,Bx,$x,ts=g(()=>{"use strict";Ke={line:["//"],block:[["/*","*/"]]},Zt={line:["#"],block:[]},lm={line:["--"],block:[]},Zo={line:[],block:[["<!--","-->"]]},hw={line:[],block:[]},J=(e,t)=>({name:e,comment:t}),Rl=J("TypeScript",Ke),Nl=J("JavaScript",Ke),Px={ts:Rl,tsx:Rl,mts:Rl,cts:Rl,js:Nl,jsx:Nl,mjs:Nl,cjs:Nl,py:J("Python",{line:["#"],block:[['"""','"""']]}),rb:J("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:J("Go",Ke),rs:J("Rust",Ke),java:J("Java",Ke),kt:J("Kotlin",Ke),swift:J("Swift",Ke),c:J("C",Ke),h:J("C",Ke),cc:J("C++",Ke),cpp:J("C++",Ke),hpp:J("C++",Ke),cs:J("C#",Ke),php:J("PHP",Ke),scala:J("Scala",Ke),dart:J("Dart",Ke),lua:J("Lua",lm),hs:J("Haskell",lm),sql:J("SQL",lm),ex:J("Elixir",Zt),exs:J("Elixir",Zt),pl:J("Perl",Zt),r:J("R",Zt),jl:J("Julia",Zt),sh:J("Shell",Zt),bash:J("Shell",Zt),zsh:J("Shell",Zt),vue:J("Vue",Zo),svelte:J("Svelte",Zo),html:J("HTML",Zo),xml:J("XML",Zo),md:J("Markdown",Zo),mdx:J("Markdown",Zo),css:J("CSS",{line:[],block:[["/*","*/"]]}),scss:J("CSS",Ke),less:J("CSS",Ke),yml:J("YAML",Zt),yaml:J("YAML",Zt),toml:J("TOML",Zt),ini:J("INI",Zt),json:J("JSON",hw)},vw="Other",Dx=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},no=e=>Px[Dx(e)]?.name??vw,Ni=e=>Px[Dx(e)]?.comment??null,yw=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],bw=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,es=e=>bw.test(e)||yw.some(t=>t.test(e)),xw=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,Iw=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,Ew=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,pn=e=>xw.test(e)||Iw.test(e)||Ew.test(e),Ox=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),_x=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),Fx=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),Sw=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,Rw=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,Bx=e=>Sw.test(e),$x=e=>Rw.test(e)});var jx,Nw,cm,Cw,Ux,dm=g(()=>{"use strict";ts();jx=/\b(TODO|FIXME|HACK|XXX)\b/,Nw=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,cm=(e,t)=>{let n=e.trim();return n===""?"blank":t&&(t.line.some(r=>n.startsWith(r))||t.block.some(([r])=>n.startsWith(r))||t.block.some(([r])=>r==="/*")&&(n.startsWith("*")||n.startsWith("*/")))?"comment":"code"},Cw=(e,t)=>{let n=e.trim();for(let r of[...t.line,...t.block.flat(),"*"])if(n.startsWith(r)){n=n.slice(r.length).trim();break}return n},Ux=({patch:e,repoShareByLanguage:t})=>{let n=new Map,r=0,o=0,s=0,i=0,c=0,u=0;for(let m of e.files){if(m.binary||pn(m.path))continue;let f=Ni(m.path);if(!f||f.line.length===0&&f.block.length===0)continue;let h=no(m.path),b=n.get(h)??{comment:0,code:0};for(let{text:I}of m.added){let C=cm(I,f);if(jx.test(I)&&i++,C==="blank"){s++;continue}if(C==="comment"){r++,b.comment++,f&&Nw.test(Cw(I,f))&&u++;continue}o++,b.code++}for(let{text:I}of m.removedLines)jx.test(I)&&c++;n.set(h,b)}let p=r+o;return{byLanguage:[...n.entries()].map(([m,f])=>({name:m,commentLines:f.comment,codeLines:f.code,share:f.comment+f.code===0?0:f.comment/(f.comment+f.code),repoShare:t?.get(m)??null})).sort((m,f)=>f.commentLines+f.codeLines-(m.commentLines+m.codeLines)),commentLines:r,codeLines:o,blankLines:s,share:p===0?0:r/p,todoLinesAdded:i,todoLinesRemoved:c,commentedOutCodeLines:u}}});var Aw,Cl,um,ww,Tw,Mw,Hx,Wx=g(()=>{"use strict";ts();Sl();Aw=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,Cl=6,um=10,ww=e=>{let t=0;for(let n of e){if(n.trim()===""||n.startsWith(" "))continue;let r=n.length-n.trimStart().length;r>0&&(t===0||r<t)&&(t=r)}return Math.min(Math.max(t,2),8)},Tw=(e,t)=>{let n=e.length-e.trimStart().length;if(n===0)return 0;let r=e.slice(0,n).split(" ").length-1;return r>0?r:Math.floor(n/t)},Mw=e=>{if(e.length<Cl*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let r=0;r+Cl<=e.length;r++){let o=e.slice(r,r+Cl);if(o.some(c=>c.text.length<3))continue;let s=o.map(c=>c.text).join(`
|
|
109
|
+
`),i=t.get(s);if(i===void 0){t.set(s,{...o[0],at:r});continue}if(i.file!==o[0]?.file)for(let c=0;c<Cl;c++)n[i.at+c]=!0,n[r+c]=!0}return n.filter(Boolean).length},Hx=({patch:e})=>{let t=[],n=[],r=[],o=!1,s=0,i=0,c=null,u=[];for(let[p,m]of e.files.entries()){if(pn(m.path)&&t.push(wn(m)),Ox(m.path)&&n.push(wn(m)),_x(m.path)&&r.push(wn(m)),Fx(m.path)&&(o=!0),m.binary||pn(m.path))continue;let f=m.added.map(I=>I.text),h=ww(f),b=m.status!=="deleted";for(let I of f){Aw.test(I)&&s++;let C=Tw(I,h);C>i&&(i=C,c=wn(m)),b&&u.push({text:I.trim(),file:p})}u.push({text:" ",file:p})}return{generatedPaths:t.slice(0,um),dependencyManifests:n.slice(0,um),buildOrCiPaths:r.slice(0,um),docsTouched:o,debugPrintLinesAdded:s,maxIndentLevels:i,deepestFile:c,duplicatedLines:Mw(u)}}});var qx,Gx=g(()=>{"use strict";ts();qx=({patch:e,languagesBefore:t})=>{let n=new Map,r=0;for(let i of e.files){if(i.binary)continue;let c=i.addedCount+i.removed;if(pn(i.path)){r+=c;continue}let u=no(i.path),p=n.get(u)??{name:u,added:0,removed:0,addedInTests:0,share:0};p.added+=i.addedCount,p.removed+=i.removed,es(i.path)&&(p.addedInTests+=i.addedCount),n.set(u,p)}let o=[...n.values()].reduce((i,c)=>i+c.added+c.removed,0),s=[...n.values()].map(i=>({...i,share:o===0?0:(i.added+i.removed)/o})).sort((i,c)=>c.added+c.removed-(i.added+i.removed));return{languages:s,introduced:t===null?[]:s.filter(i=>!t.has(i.name)).map(i=>i.name),generatedLines:r}}});var kw,mm,Lw,zx,Pw,pm,Dw,Ow,Vx,Kx,_w,Fw,Bw,Yx,Xx=g(()=>{"use strict";ze();N();kw=200,mm=2e5,Lw=5e4,zx=25,Pw=64*1024*1024,pm="",Dw=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/,Ow=/^diff --git a\/(.+) b\/\1$/,Vx=(e,t)=>e==="/dev/null"?null:e.startsWith(t)?e.slice(2):e,Kx=(e,t)=>e===null?"added":t===null?"deleted":"modified",_w=()=>({byPath:new Map,insertions:0,deletions:0,selfChurn:0,retainedLines:0}),Fw=(e,t)=>{let n=e.byPath,r="",o=null,s=null,i=null,c=!1,u=0,p=(f,h)=>h==="modified"&&f==="added"?"added":h,m=(f,h)=>{let b=n.get(f);if(b)return b.entry.status=p(b.entry.status,h),b.entry.shas.includes(r)||b.entry.shas.push(r),b;let C={entry:{path:f,status:h,binary:!1,added:[],addedCount:0,removed:0,removedLines:[],shas:[r]},pendingByText:new Map};return n.set(f,C),C};for(let f of t.split(`
|
|
110
|
+
`)){if(f.startsWith(pm)){r=f.slice(pm.length).trim(),o=null,s=null,i=null,c=!1;continue}if(f.startsWith("diff --git ")){o=null,i=null,c=!0,s=Ow.exec(f)?.[1]??null;continue}if(c&&f.startsWith("Binary files ")&&s){let[,b=""]=/^Binary files (.*) differ$/.exec(f)??[],[I="",C=""]=b.split(" and ");o=m(s,Kx(I==="/dev/null"?null:I,C==="/dev/null"?null:C)),o.entry.binary=!0;continue}if(c&&f.startsWith("--- ")){i=Vx(f.slice(4),"a/");continue}if(c&&f.startsWith("+++ ")){let b=Vx(f.slice(4),"b/"),I=b??i??s;I&&(o=m(I,Kx(i,b)));continue}let h=Dw.exec(f);if(h){u=Number(h[1]),c=!1;continue}if(o){if(f.startsWith("+")){let b=f.slice(1);e.insertions++,o.entry.addedCount++,e.retainedLines<mm&&(o.entry.added.push({sha:r,line:u,text:b}),e.retainedLines++),o.pendingByText.size<Lw&&o.pendingByText.set(b,(o.pendingByText.get(b)??0)+1),u++;continue}if(f.startsWith("-")){let b=f.slice(1);e.deletions++,o.entry.removed++,e.retainedLines<mm&&(o.entry.removedLines.push({sha:r,line:0,text:b}),e.retainedLines++);let I=o.pendingByText.get(b)??0;I>0&&b.trim().length>2&&(e.selfChurn++,o.pendingByText.set(b,I-1))}}}},Bw=e=>({files:[...e.byPath.values()].map(t=>t.entry),insertions:e.insertions,deletions:e.deletions,selfChurn:e.selfChurn,retainedLines:e.retainedLines}),Yx=async({repoRoot:e,shas:t})=>{if(t.length===0)return d("No commits to scan",{files:[],insertions:0,deletions:0,selfChurn:0,scannedCommits:0,truncated:!1});let n=t.slice(0,kw).reverse(),r=_w(),o=0,s=0,i=!1;for(let u=0;u<n.length;u+=zx){let p=n.slice(u,u+zx),m=await W({cwd:e,args:["-c","core.quotePath=false","show","--unified=0","--no-renames","--no-color",`--format=${pm}%H`,...p]});if(l(m))return a(m.message);if(Fw(r,m.value.stdout),o+=m.value.stdout.length,s+=p.length,o>Pw){i=!0;break}}let c=Bw(r);return d("Scanned ticket patch",{files:c.files,insertions:c.insertions,deletions:c.deletions,selfChurn:c.selfChurn,scannedCommits:s,truncated:i||s<t.length||c.retainedLines>=mm})}});var $w,jw,Jx,Qx=g(()=>{"use strict";ze();N();dm();ts();$w=40,jw=/^\d{6} blob ([0-9a-f]{40})\t(.+)$/,Jx=async({repoRoot:e,sha:t})=>{let n=await Me({cwd:e,args:["-c","core.quotePath=false","ls-tree","-r",`${t}~1`]});if(n.exitCode!==0)return null;let r=new Set,o=new Map;for(let m of n.stdout.split(`
|
|
111
|
+
`)){let f=jw.exec(m);if(!f)continue;let[,h="",b=""]=f;if(pn(b))continue;let I=no(b);if(r.add(I),es(b)||!Ni(b))continue;let C=o.get(I)??[];C.length<$w&&(C.push({blob:h,path:b}),o.set(I,C))}let s=[...o.values()].flat(),i=await Yl(s.map(m=>m.blob),e);if(l(i))return{languages:r,commentShareByLanguage:new Map};let c=i.value,u=new Map;for(let{blob:m,path:f}of s){let h=c.get(m);if(h===void 0)continue;let b=Ni(f),I=no(f),C=u.get(I)??{comment:0,code:0};for(let T of h.split(`
|
|
112
|
+
`)){let S=cm(T,b);S==="comment"&&C.comment++,S==="code"&&C.code++}u.set(I,C)}let p=new Map;for(let[m,f]of u){let h=f.comment+f.code;h>0&&p.set(m,f.comment/h)}return{languages:r,commentShareByLanguage:p}}});var Zx,eI=g(()=>{"use strict";ts();Sl();Zx=({patch:e})=>{let t=0,n=0,r=[],o=[],s=0,i=0;for(let c of e.files)if(!(c.binary||pn(c.path))&&es(c.path)){t+=c.addedCount,n+=c.removed,c.status==="added"&&r.push(wn(c)),c.status==="deleted"&&o.push(wn(c));for(let{text:u}of c.added)Bx(u)&&s++,$x(u)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:r,deletedTestFiles:o,skippedTestLinesAdded:s,focusedTestLinesAdded:i}}});var Uw,tI,nI=g(()=>{"use strict";N();Lx();dm();Wx();Gx();Xx();Qx();eI();Uw=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,tI=async({repoRoot:e,ref:t,commits:n})=>{let r=await Yx({repoRoot:e,shas:n.map(c=>c.sha)});if(l(r))return a(r.message);let o=r.value,s=Uw(n),i=s?await Jx({repoRoot:e,sha:s}):null;return d("Derived issue stats",{ref:t,shape:kx({commits:n,patch:o}),languages:qx({patch:o,languagesBefore:i?.languages??null}),tests:Zx({patch:o}),comments:Ux({patch:o,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:Hx({patch:o})})}});var rI,oI=g(()=>{"use strict";ll();N();wt();D();rI=e=>{if(l(e))return e;let t=Ee(),n=l(t)?{}:t.value.emailLinks,r=l(t)?{}:t.value.contributors,o=Dm(n),s=e.value.map(i=>({...i,authorIdentity:Vy({authorName:i.author,authorEmail:i.authorEmail,owners:o,registry:r})}));return d(e.message,s)}});var Hw,Ci,Ww,sI,iI=g(()=>{"use strict";N();nI();mt();Q();oI();li();Hw=32,Ci=new Map,Ww=(e,t)=>{if(Ci.set(e,t),Ci.size>Hw){let n=Ci.keys().next();n.done||Ci.delete(n.value)}return t},sI=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return a("idOrRef must not be empty");let n=t.length>7?V(t):t.toUpperCase(),r=Ne(e.repoRoot??process.cwd());if(l(r))return a(r.message);let o=r.value,s=rI(await $o({repoRoot:o,ref:n}));if(l(s))return a(s.message);let i=s.value.map(m=>({sha:m.sha,time:m.time,author:m.authorIdentity?.resolved?m.authorIdentity.name:m.author,subject:m.subject})),c=[o,n,i.map(m=>`${m.sha}:${m.author}`).join(",")].join(" "),u=Ci.get(c);if(u)return d("Derived issue stats",u);let p=await tI({repoRoot:o,ref:n,commits:i});return l(p)?a(p.message):d("Derived issue stats",Ww(c,p.value))}});var ns,fm,aI=g(()=>{"use strict";ns=".claude/skills/epiq/SKILL.md",fm=`---
|
|
113
|
+
name: epiq
|
|
114
|
+
description: Workflow for working an epiq issue board through the epiq MCP \u2014 take an identity, sync on demand, keep tickets small and their status, tags and comments current.
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
# Epiq board workflow
|
|
118
|
+
|
|
119
|
+
- **Use the \`epiq_*\` MCP tools** for every board read and write \u2014 never the CLI, hand edits, or the state branch directly.
|
|
120
|
+
- Never edit the state branch directly. Don't check it out, don't write to its worktree, don't touch the event log or any file under it by hand or by script \u2014 go through the MCP for every read and write. The event log is the system of record: an edit made outside it bypasses validation and ordering, and can corrupt history in ways no later fix can undo.
|
|
121
|
+
- Keep the status column current as work progresses (move tickets along the board with correct status)
|
|
122
|
+
- **Sync is on demand:** call \`epiq_sync\` to pull or publish; nothing else does.
|
|
123
|
+
- **Take an identity before your first write:** \`provider/name\` (e.g. \`claude/peter\`), set with \`epiq_actor_assume\`. Reuse one from \`epiq_contributor_list\` \u2014 names are permanent. If other agents may be running, ask which name is free, rather than just picking one.
|
|
124
|
+
- Break work into small, reasonably scoped tickets.
|
|
125
|
+
- **One MCP server per session** \u2014 the name binds to the process; a restart forgets it. epiq_actor_assume binds the name to the server process it is called on, so two sessions on one server \u2014 or a session on the user's own instance \u2014 would sign every write with whichever name was assumed last, and the log would fold them into one contributor. Every session therefore needs a server process of its own.
|
|
126
|
+
- **Keep tickets small**; put a small follow-up on its existing ticket instead of a new one.
|
|
127
|
+
- **Read a ticket's comments before starting.**
|
|
128
|
+
- **Picking up a ticket:** assign yourself and move it to the in-progress lane. Ask before taking one assigned to someone else.
|
|
129
|
+
- **Keep status, tags and description current**; reuse existing tags.
|
|
130
|
+
- **Comment** on deviations, blockers, and the outcome when done.
|
|
131
|
+
- **Prompt user for closing tickets and big decisions**
|
|
132
|
+
- **Park decisions that are the user's to make.** A design fork, a change with blast radius beyond its ticket, anything you'd want a second opinion on - file a ticket tagged human-input-needed naming the options and the trade-offs, then carry on with whatever doesn't depend on the answer.
|
|
133
|
+
- **Link commits** by starting the subject with the ticket's \`ref\` from the MCP response \u2014 never derive the ref from the id.
|
|
134
|
+
- *If a you decide to take a new approach*, add a "fork" tag, and document the fork in a comment, also, update the description to reflect the new plan.
|
|
135
|
+
- **Attachments are permanent** in every clone (max 500 KB): only when a picture is needed, make sure images are cropped and compressed. An oversized image is permanent, for everybody \u2014 the same reason the text limits exist.
|
|
136
|
+
- **Be concise.** Titles, descriptions, and comments should be scannable, not essays.
|
|
137
|
+
- **When a ticket is done, Document the outcome in a comment starting with "Solution:"**. Use that exact prefix as the comment's opening line.
|
|
138
|
+
- **The git user is the sole author of every commit you write.** Commit under the repo's configured user.name / user.email and nothing else: no Co-Authored-By: line, no Claude-Session: line, no \u{1F916} Generated with footer, and never an --author override naming Claude or a tool.
|
|
139
|
+
- Always rebase onto the target, never merge into it. Rebase the branch onto the target first, then integrate with a rebase merge \u2014 gh pr merge --rebase, never --merge. Main stays a flat sequence of ref-prefixed commits, which is what the commit\u2194ticket linking reads. A merge commit adds a subject carrying no ref and buries the branch's commits behind it.
|
|
140
|
+
`});import Al from"node:fs";import lI from"node:path";var cI,dI=g(()=>{"use strict";nt();N();aI();cI=async(e={})=>{let t=await Lt(e.repoRoot??process.cwd());if(l(t))return a(t.message);let n=lI.join(t.value,ns);if(Al.existsSync(n)){if(Al.readFileSync(n,"utf8")===fm)return d("Skill already installed and up to date",{path:n,written:!1});if(!e.force)return a(`${ns} already exists and differs from the bundled skill. Pass force:true to overwrite it.`)}try{Al.mkdirSync(lI.dirname(n),{recursive:!0}),Al.writeFileSync(n,fm,"utf8")}catch(r){return a(r instanceof Error?`Failed to write ${ns}: ${r.message}`:`Failed to write ${ns}`)}return d(`Installed skill at ${ns}`,{path:n,written:!0})}});var mI={};ss(mI,{createMcpServer:()=>uI,resultJson:()=>gm,startMcpServer:()=>Vw});import{McpServer as Gw}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as zw}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as y}from"zod";var gm,te,uI,Vw,pI=g(()=>{"use strict";N();_n();Cx();am();Mx();iI();dI();xi();gm=e=>({isError:l(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),te=e=>t=>lx(async()=>gm(await e(t))),uI=()=>{let e=new Gw({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:y.object({repoRoot:y.string().optional()})},te(Nu)),e.registerTool("epiq_issue_list",{description:"List Epiq issues. Narrow with boardId, swimlaneId, tag, assignee or query (matched against title and description), and pass brief to get id, ref, title, swimlane, tag names and assignee names only \u2014 descriptions are the bulk of a board. Read one ticket with epiq_issue_get.",inputSchema:y.object({repoRoot:y.string().optional(),includeClosed:y.boolean().optional(),boardId:y.string().optional(),swimlaneId:y.string().optional(),tag:y.string().optional(),assignee:y.string().optional(),query:y.string().optional(),brief:y.boolean().optional()})},te(Tu)),e.registerTool("epiq_issue_get",{description:"Get one Epiq issue by its full id or its 7-character ref, with its comments in log order. Use this rather than listing the whole board when you already know which issue you want, and rather than epiq_state_get to read a thread.",inputSchema:y.object({idOrRef:y.string().min(1),repoRoot:y.string().optional()})},te(wu)),e.registerTool("epiq_issue_stats",{description:"Code stats for one issue, derived from the commits whose subject carries its ref: how big the change is, how it is spread, and how much of it the ticket spent rewriting its own work. Reads git only \u2014 it never touches the board \u2014 so it is safe to call while other work is in flight. No commits carrying the ref reads as a change of zero size, which is not the same as no work: a commit only links if its subject opens with the ref.",inputSchema:y.object({idOrRef:y.string().min(1),repoRoot:y.string().optional()})},async t=>gm(await sI(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:y.object({repoRoot:y.string().optional()})},te(_u)),e.registerTool("epiq_board_create",{description:"Create an Epiq board. It comes out without swimlanes; add them with epiq_swimlane_create. Refused while time travelling.",inputSchema:y.object({repoRoot:y.string().optional(),title:y.string().min(1).max(300)})},te(Fu)),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:y.object({repoRoot:y.string().optional(),boardId:y.string().optional()})},te($u)),e.registerTool("epiq_swimlane_create",{description:"Create an Epiq swimlane on a board",inputSchema:y.object({repoRoot:y.string().optional(),boardId:y.string().min(1),title:y.string().min(1).max(300)})},te(ju)),e.registerTool("epiq_swimlane_title_edit",{description:"Edit an Epiq swimlane title",inputSchema:y.object({repoRoot:y.string().optional(),swimlaneId:y.string().min(1),title:y.string().min(1).max(300)})},te(Uu)),e.registerTool("epiq_board_title_edit",{description:"Edit an Epiq board title. Refused while time travelling.",inputSchema:y.object({repoRoot:y.string().optional(),boardId:y.string().min(1),title:y.string().min(1).max(300)})},te(Bu)),e.registerTool("epiq_swimlane_move",{description:"Move/reorder an Epiq swimlane, optionally to another board",inputSchema:y.object({repoRoot:y.string().optional(),swimlaneId:y.string().min(1),boardId:y.string().min(1),position:y.discriminatedUnion("at",[y.object({at:y.literal("start")}),y.object({at:y.literal("end")}),y.object({at:y.literal("before"),sibling:y.string().min(1)}),y.object({at:y.literal("after"),sibling:y.string().min(1)})]).optional()})},te(Hu)),e.registerTool("epiq_swimlane_delete",{description:"Delete (archive) an Epiq swimlane. This also archives every issue contained in it.",inputSchema:y.object({repoRoot:y.string().optional(),swimlaneId:y.string().min(1)})},te(Wu)),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue in a swimlane: parentId is the swimlane id (epiq_swimlane_list), never a board id. Optionally set description, tags, and assignees atomically in the same call instead of separate follow-up edits.",inputSchema:y.object({title:y.string().min(1).max(300),parentId:y.string().min(1),repoRoot:y.string().optional(),description:y.string().max(2e4).optional(),tagNames:y.array(y.string().max(60)).max(20).optional(),assigneeNames:y.array(y.string().max(80)).max(20).optional()})},te(Mu)),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),description:y.string().max(2e4),repoRoot:y.string().optional()})},te(Du)),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),title:y.string().min(1).max(300),repoRoot:y.string().optional()})},te(Ou)),e.registerTool("epiq_issue_tag_add",{description:"Add a tag to an Epiq issue, or to many at once with issueIds, creating the tag if it does not exist",inputSchema:y.object({issueId:y.string().min(1).optional(),issueIds:y.array(y.string().min(1)).min(1).max(200).optional(),tagName:y.string().min(1).max(60),repoRoot:y.string().optional()})},te(qu)),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),tagId:y.string().min(1),repoRoot:y.string().optional()})},te(Vu)),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:y.object({boardId:y.string().min(1).optional(),repoRoot:y.string().optional()})},te(Qu)),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:y.object({contributorId:y.string().min(1),repoRoot:y.string().optional()})},te(Xu)),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:y.object({tagId:y.string().min(1),repoRoot:y.string().optional()})},te(Gu)),e.registerTool("epiq_tag_restore",{description:"Put back a tag deleted with epiq_tag_remove, on every ticket that still carried it.",inputSchema:y.object({tagId:y.string().min(1),repoRoot:y.string().optional()})},te(zu)),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:y.object({contributorId:y.string().min(1),repoRoot:y.string().optional()})},te(Ju)),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:y.object({issueId:y.string().min(1),assigneeId:y.string().min(1).optional(),self:y.boolean().optional(),assigneeName:y.string().min(1).max(80).optional(),createUnlinked:y.boolean().optional(),repoRoot:y.string().optional()})},te(Yu)),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),assigneeId:y.string().min(1),repoRoot:y.string().optional()})},te(Zu)),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),body:y.string().min(1).max(4e3),repoRoot:y.string().optional()})},te(em)),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:y.object({issueId:y.string().min(1),filePath:y.string().min(1),name:y.string().min(1).max(200).optional(),repoRoot:y.string().optional()})},te(Su)),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:y.object({commentId:y.string().min(1),repoRoot:y.string().optional()})},te(tm)),e.registerTool("epiq_issue_comment_edit",{description:"Replace the body of one of your own comments on an Epiq issue",inputSchema:y.object({commentId:y.string().min(1),body:y.string().min(1).max(4e3),repoRoot:y.string().optional()})},te(nm)),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:y.object({issueId:y.string().min(1),repoRoot:y.string().optional()})},te(Lu)),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue, or many at once with issueIds \u2014 one call, an outcome per ticket",inputSchema:y.object({issueId:y.string().min(1).optional(),issueIds:y.array(y.string().min(1)).min(1).max(200).optional(),repoRoot:y.string().optional()})},te(ku)),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane (parentId is the swimlane id), or many at once with issueIds \u2014 one call, an outcome per ticket",inputSchema:y.object({issueId:y.string().min(1).optional(),issueIds:y.array(y.string().min(1)).min(1).max(200).optional(),parentId:y.string().min(1),position:y.discriminatedUnion("at",[y.object({at:y.literal("start")}),y.object({at:y.literal("end")}),y.object({at:y.literal("before"),sibling:y.string().min(1)}),y.object({at:y.literal("after"),sibling:y.string().min(1)})]).optional(),repoRoot:y.string().optional()})},te(Pu)),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:y.object({name:y.string().min(1).max(80),repoRoot:y.string().optional()})},te(Ku)),e.registerTool("epiq_contributor_email_link",{description:"Bind a git author address to a contributor, so their commits and their board activity read as one person. Defaults to you; pass contributorId to link a colleague who does not use epiq, whose commits otherwise never resolve. The address the repository's git is configured with links itself on your first write, so this is for older addresses and for other people. An address two contributors claim resolves to neither, and the reply says so.",inputSchema:y.object({email:y.string().min(1).max(254),contributorId:y.string().min(1).optional(),repoRoot:y.string().optional()})},te(rm)),e.registerTool("epiq_contributor_email_unlink",{description:"Retract a link between a git address and a contributor. Allowed only to whoever wrote the link and to the contributor it names, so nobody can strip links that are neither theirs nor about them. Forward-only: the address stops resolving and the event stays in the log.",inputSchema:y.object({email:y.string().min(1).max(254),contributorId:y.string().min(1).optional(),repoRoot:y.string().optional()})},te(om)),e.registerTool("epiq_contributor_email_suggest",{description:"Addresses in this repository's history that look like yours and nobody has claimed, for the user to confirm. Run it once after this feature reaches a board with history: the address git is configured with links itself, but older ones do not, and until they are linked those commits show a raw git name. Show the list and link only what the user confirms \u2014 each link is permanent and replicates to every clone.",inputSchema:y.object({repoRoot:y.string().optional()})},te(im)),e.registerTool("epiq_contributor_email_list",{description:"Every git address the board has bound to a contributor, and who holds it. An address with more than one claimant is flagged contested and resolves to none of them, which is the state nothing else reports.",inputSchema:y.object({repoRoot:y.string().optional()})},te(sm)),e.registerTool("epiq_project_init",{description:`Set up a new Epiq board in a git repository without the TUI. Runs in the repository at repoRoot (default: the current directory), which must have no uncommitted changes. The first time on a machine it also records the user's setup: ask the user for userName (how they want to appear on the board), preferredEditor (e.g. "vim" or "code --wait") and autoSync (whether the TUI and GUI sync with the remote on their own) and pass them here; called without them it fails naming what is still missing, keeping whatever was given. It fills in answers the machine lacks and refuses to change ones it has. Pass the user's name, never your own agent identity. Commits the state branch and .epiq/project.json and tries to push both; a push that fails is a warning, not an error. Afterwards the other tools work in that repository.`,inputSchema:y.object({repoRoot:y.string().optional(),userName:y.string().min(1).max(80).optional(),preferredEditor:y.string().min(1).max(200).optional(),autoSync:y.boolean().optional()})},te(Tx)),e.registerTool("epiq_skill_install",{description:"Write the official Epiq workflow skill into the repository at .claude/skills/epiq/SKILL.md, so agents working there follow the same board rules. Run it after epiq_project_init, not before: the new file is an uncommitted change that init refuses. In a project that already has a board, run it any time. Refuses to overwrite a differing file unless force is true; an identical file is left alone.",inputSchema:y.object({repoRoot:y.string().optional(),force:y.boolean().optional()})},te(cI)),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:y.object({repoRoot:y.string().optional()})},te(Cu)),e},Vw=async()=>{let e=uI(),t=new zw;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:Kw}=await Promise.resolve().then(()=>(xr(),Em)),{isFail:Yw}=await Promise.resolve().then(()=>(N(),bm)),{parseMcpArgs:Xw}=await Promise.resolve().then(()=>(Nm(),Rm)),rs=Xw(process.argv.slice(2));rs.kind==="error"&&(console.error(rs.message),process.exit(1));rs.kind==="print"&&(process.stdout.write(rs.text),process.exit(0));if(rs.kind==="name"){let e=Kw(rs.name,"The name argument");Yw(e)&&(console.error(e.message),process.exit(1))}var{setVirtualNodesEnabled:Jw}=await Promise.resolve().then(()=>(Hc(),ox));Jw(!1);var{startMcpServer:Qw}=await Promise.resolve().then(()=>(pI(),mI));await Qw();
|