epiq 1.13.0 → 1.13.1

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/mcp.js CHANGED
@@ -1,150 +1,2 @@
1
1
  #!/usr/bin/env node
2
- var jI=Object.defineProperty;var h=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ds=(e,t)=>{for(var n in t)jI(e,n,{get:t[n],enumerable:!0})};var bf={};Ds(bf,{failed:()=>c,isFail:()=>a,isSuccess:()=>Vt,resultStatuses:()=>Un,succeeded:()=>d});var Un,c,d,a,Vt,C=h(()=>{"use strict";Un={Success:"success",Fail:"fail"},c=e=>({status:Un.Fail,message:e,value:null}),d=(e,t)=>({status:Un.Success,message:e,value:t}),a=e=>e.status==="fail",Vt=e=>e.status==="success"});var xf={};Ds(xf,{ACTOR_ID_ENV:()=>Fs,ACTOR_NAME_ENV:()=>Kt,applyActorNameArgument:()=>Hl,deriveActorId:()=>Rf,isValidUserId:()=>Ra,isValidUserName:()=>Bs,resolveEnvActor:()=>Ul});import UI from"node:crypto";var Kt,Fs,vf,HI,jl,Ra,Bs,Mo,Rf,Ul,Hl,$r=h(()=>{"use strict";C();Kt="EPIQ_USER_NAME",Fs="EPIQ_USER_ID",vf="0123456789ABCDEFGHJKMNPQRSTVWXYZ",HI=26,jl=80,Ra=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),Bs=e=>e.trim().length>0&&e.length<=jl,Mo=e=>e.trim().toLowerCase(),Rf=e=>{let t=UI.createHash("sha256").update(`epiq:actor:${Mo(e)}`).digest(),n="";for(let r=0;r<HI;r++)n+=vf[(t[r]??0)%vf.length];return n},Ul=(e,t=process.env)=>{let n=(t[Kt]??"").trim(),r=(t[Fs]??"").trim();return n?Bs(n)?!r&&e.userId&&e.userName&&Mo(e.userName)===Mo(n)?d("Actor override names the configured user",{userId:e.userId,userName:e.userName}):r&&!Ra(r)?c(`${Fs} must be 26 characters of Crockford base32`):r&&e.userId&&r===e.userId?c(`${Fs} 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||Rf(n),userName:r?n:Mo(n)}):c(`${Kt} must be 1-${jl} characters of text`):r?c(`${Fs} is set without ${Kt}`):d("No actor override",null)},Hl=(e,t,n=process.env)=>{let r=e.trim();if(!Bs(r))return c(`${t} must be 1-${jl} characters of text`);let o=(n[Kt]??"").trim();return o&&Mo(o)!==Mo(r)?c(`${t} names ${r}, but ${Kt} names ${o}`):(o||(n[Kt]=r),d("Applied actor name argument",o||r))}});var Wl,Ef=h(()=>{"use strict";Wl="1.13.0"});var Sf={};Ds(Sf,{parseMcpArgs:()=>GI});var WI,GI,If=h(()=>{"use strict";Ef();WI=`epiq-mcp ${Wl}
3
-
4
- Usage: epiq-mcp [name]
5
-
6
- name the board identity this server writes under, e.g. claude/peter
7
- (equivalent to setting EPIQ_USER_NAME)
8
-
9
- Options:
10
- -v, --version print the version
11
- -h, --help print this help
12
- `,GI=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:`${Wl}
13
- `}:t==="--help"||t==="-h"?{kind:"print",text:WI}:t.startsWith("-")?{kind:"error",message:`Unknown option ${t}; expected a name, e.g. epiq-mcp claude/peter`}:{kind:"name",name:t}}});var qI,zI,VI,Gl,Cf,xa,$s,KI,dr,ko=h(()=>{"use strict";qI=new Set(["https:","http:","ssh:","git:","file:"]),zI=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*:[^:]+$/,VI=/^[\x21-\x7e]+$/,Gl=2048,Cf="Use https://, ssh://, git:// or user@host:path.",xa=()=>globalThis.process?.env?.EPIQ_ALLOW_LOCAL_REPOS==="1",$s=(e,t=xa())=>{if(e.length>Gl)return"is too long";if(!VI.test(e))return"holds spaces or characters git would not";if(e.startsWith("-"))return"would be read as an option";if(/[\\#?]/.test(e))return"holds a character a clone URL has no use for";if(e.replace(/\[[^\]]*\]/g,"").includes("::"))return"names a remote helper";if(zI.test(e))return null;let n;try{n=new URL(e)}catch{return"is not a remote URL"}return/%/.test(KI(e))?"percent-encodes its host":qI.has(n.protocol)?n.password?"carries a password \u2014 use a credential helper":n.username&&n.protocol!=="ssh:"?"names a user before the host \u2014 leave it to a credential helper":n.protocol==="file:"?t?n.hostname?"names a host in a file:// URL":e.startsWith("file:///")?null:"is not a file:/// URL":"is a path on this machine, which nobody else can fetch":n.hostname?n.hostname.startsWith("-")||n.username.startsWith("-")?"would be read as an option":null:"names no host":"uses a transport epiq does not clone over"},KI=e=>{let t=e.indexOf("//");if(t===-1)return"";let n=e.slice(t+2),r=n.indexOf("/");return r===-1?n:n.slice(0,r)},dr=(e,t=xa())=>$s(e,t)===null});import{createHash as YI}from"node:crypto";var zl,Vl,Kl,Hn,XI,JI,wf,jr,QI,Ur,ZI,eC,tC,Nf,Wn,Gn,js,Af,ql,Yl,Tf,Mf,kf,Ea,Hr=h(()=>{"use strict";C();ko();zl=()=>({entries:{},seq:0}),Vl="default",Kl="board",Hn=20,XI=/^\d{4}-\d{2}-\d{2}$/,JI=/^[a-z0-9][a-z0-9._-]{0,23}$/,wf=/-[0-9a-f]{12}$/,jr=e=>e==="board"||e==="all"||QI(e),QI=e=>{if(!XI.test(e)||e<"1970-01-01")return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e},Ur=e=>JI.test(e)&&!wf.test(e),ZI=/^([^@/]+@)([^:/]+)(:.*)$/,eC=/^([a-z][a-z0-9+.-]*:\/\/)([^/]*)(.*)$/i,tC=e=>{let t=ZI.exec(e);if(t)return`${t[1]}${t[2].toLowerCase()}${t[3]}`;let n=eC.exec(e);if(!n)return e;let r=n[2],o=r.lastIndexOf("@")+1;return`${n[1].toLowerCase()}${r.slice(0,o)}${r.slice(o).toLowerCase()}${n[3]}`},Nf=e=>tC(e.trim().replace(/\/+$/,"").replace(/\.git$/i,"")),Wn=e=>(Nf(e).toLowerCase().split(/[/:]/).filter(Boolean).pop()??"").replace(/[^a-z0-9._-]/g,"-").slice(0,24).replace(/^[.-]+/,"")||"repo",Gn=e=>`${Wn(e)}-${YI("sha1").update(Nf(e)).digest("hex").slice(0,12)}`,js=e=>e.replace(wf,""),Af=e=>{let t={},{branches:n,since:r,label:o}=e;return(n==="default"||n==="all")&&(t.branches=n),typeof r=="string"&&jr(r)&&(t.since=r),typeof o=="string"&&(o===""||Ur(o))&&(t.label=o),t},ql=(e,t)=>{let n={...e,...t.branches?{branches:t.branches}:{},...t.since?{since:t.since}:{}};return t.label===""?delete n.label:t.label&&(n.label=t.label),n},Yl=(e,t)=>{let n=t.payload&&typeof t.payload=="object"?t.payload:{},r=Af(n);if(t.action==="connect.repo"){let l=typeof n.url=="string"?n.url.trim():"";if(l==="")return c("no URL");let u=Gn(l),p=Object.hasOwn(e.entries,u)?e.entries[u]:void 0,m=p?.live===!0?ql(p,r):ql({id:u,url:l,branches:Vl,since:Kl,live:!0,seq:e.seq+1},r);return p?.live||e.seq++,e.entries[u]=m,d("Connected repo",m)}let o=typeof n.repo=="string"?n.repo:"",s=Object.hasOwn(e.entries,o)?e.entries[o]:void 0;if(!s?.live)return c("no such connected repo");if(t.action==="disconnect.repo"){let l={...s,live:!1};return e.entries[o]=l,d("Disconnected repo",l)}if(Object.keys(r).length===0)return c("nothing this build reads to change");let i=ql(s,r);return e.entries[o]=i,d("Edited repo",i)},Tf=e=>e==="connect.repo"||e==="edit.repo"||e==="disconnect.repo",Mf=e=>{let t=zl();for(let n of e)Tf(n.action)&&Yl(t,{action:n.action,payload:n.payload});return t},kf=e=>{let t=Object.values(e.entries),n=t.filter(s=>s.live&&dr(s.url)).sort((s,i)=>s.seq-i.seq),r=new Set,o=n.map(s=>{let i=[s.label,Wn(s.url)].find(l=>l!==void 0&&!r.has(l))??s.id;return r.add(i),{id:s.id,url:s.url,branches:s.branches,since:s.since,label:i}});return{live:o.slice(0,Hn),overLimit:o.slice(Hn),disconnected:t.filter(s=>!s.live).map(s=>s.id)}},Ea=e=>{let t=e.payload&&typeof e.payload=="object"?e.payload:{},n=typeof t.label=="string"&&t.label!==""?t.label:null;if(e.action==="connect.repo")return typeof t.url=="string"?n??Wn(t.url):"";let r=typeof t.repo=="string"?js(t.repo):"";if(e.action!=="edit.repo")return r;let o=Af(t),s=[o.label!==void 0?o.label===""?"label cleared":`label ${o.label}`:null,o.branches?`${o.branches} branches`:null,o.since?`since ${o.since}`:null].filter(Boolean);return s.length>0?`${r} (${s.join(", ")})`:r}});import{decodeTime as Lf}from"ulid";var Sa,Us,gt,Hs,Xl,Wr,ht=h(()=>{"use strict";C();Sa=1440*60*1e3,Us=(e,t=Date.now())=>e>t+Sa?t:e,gt=e=>Us(Lf(e)),Hs=e=>{let t=Date.now()+Sa,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})},Xl=e=>{try{return d("Decoded date",new Date(gt(e)))}catch(t){return c("Decoding failed + "+t.message)}},Wr=e=>{if(!e?.id)return null;try{return Lf(e.id)}catch{return null}}});var st,M,et=h(()=>{"use strict";st={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},M={accent:st.cyan,accent2:st.magenta,primary:st.white,secondary:st.grayDark,secondary2:st.grayLight,gray:st.gray,green:st.green,yellow:st.yellow,red:st.red}});var k,Ia,Jl=h(()=>{"use strict";et();k={red:st.red,yellow:st.yellow,green:st.green,blue:st.blue,magenta:st.magenta,cyan:st.cyan},Ia={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 Pf from"chalk";var Zl,Of,Ql,_f,nC,rC,Df,oC,sC,ed,it,Ff,Bf,Ca,iC,aC,wa,Cn=h(()=>{"use strict";Jl();Zl={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Of=(e,t,n)=>Math.max(t,Math.min(n,e)),Ql=(e,t,n)=>e+(t-e)*n,_f=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},nC=e=>e.toLowerCase().trim(),rC=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,l=s*(1-Math.abs(i%2-1)),u=0,p=0,m=0;i>=0&&i<1?(u=s,p=l):i>=1&&i<2?(u=l,p=s):i>=2&&i<3?(p=s,m=l):i>=3&&i<4?(p=l,m=s):i>=4&&i<5?(u=l,m=s):(u=s,m=l);let f=o-s/2;return[Math.round((u+f)*255),Math.round((p+f)*255),Math.round((m+f)*255)]},Df=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,oC=(e,t,n)=>{let r=Of(n,0,1);return[Math.round(Ql(e[0],t[0],r)),Math.round(Ql(e[1],t[1],r)),Math.round(Ql(e[2],t[2],r))]},sC=(e,t,n)=>oC(e,t,n),ed=e=>{let t=_f(e)%360,n=rC(t,Zl.stringColor.saturation,Zl.stringColor.lightness);return Df(n)},it=(e,t=Ia)=>{let n=nC(e??"");return n&&t[n]?t[n]:ed(n)},Ff=e=>{let t=Zl.gradient.stops,n=Of(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 sC(t[s],t[s+1],i)},Bf=e=>Df(Ff(e)),Ca=e=>_f(e.toLowerCase().trim())/4294967295,iC=e=>{let t=Ca(e);return Ff(t)},aC=e=>{let[t,n,r]=iC(e);return{normal:o=>Pf.bgRgb(t,n,r).black(o),cursor:o=>Pf.bgRgb(t,n,r).white.bold(o)}},wa=e=>aC(e).normal(` ${e} `)});var cC,Ws,Ct,qn=h(()=>{"use strict";Cn();cC="Unknown",Ws=(e,t)=>t?.length?t:e?.length?e:cC,Ct=(e,t)=>{let n=Ws(e,t);return{id:e?.length?e:n,name:n,color:it(n)}}});var Gs,Ft,$f,fn=h(()=>{"use strict";C();Gs="removed",Ft=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?d("Found node",n):c("Unable to find node in breadcrumb")},$f=["png","jpg","gif","webp"]});var Xe,ur,qs,td,nd,mr,jf,Na,Bt=h(()=>{"use strict";Xe=e=>e.trim().toLowerCase(),ur=e=>{let t=Xe(e);return t.length>0&&t.length<=254&&/^[^\s@]+@[^\s@]+$/.test(t)},qs=(e,t)=>`${Xe(e)} ${t}`,td=e=>!e.tombstoned,nd=(e,t)=>{let n=Xe(t),r=new Set;for(let o of Object.values(e))td(o)&&o.email===n&&r.add(o.contributor);return[...r]},mr=(e,t)=>{let n=new Set;for(let r of Object.values(e))td(r)&&r.contributor===t&&n.add(r.email);return[...n]},jf=e=>{let t=new Map;for(let r of Object.values(e)){if(!td(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},Na=(e,t)=>e===t.authorId||e===t.contributor});function rd(e){return e.context===me.WORKSPACE}function W(e){return e.context===me.TICKET}function Uf(e){return e.context===me.TEXT}function at(e){return e.context===me.FIELD}function zs(e){return e.context===me.FIELD_LIST}var me,Gr,qr,Vs,pe=h(()=>{"use strict";me={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};Gr=e=>e.context===me.SWIMLANE,qr=e=>e.context===me.BOARD,Vs=e=>e.context===me.COMMENT});var x,$e=h(()=>{"use strict";x={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette",IDENTITY:"identity"}});var Hf=h(()=>{"use strict";pr()});import Wf from"string-width";function Aa(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var zr,lC,od,dC,Vr,ye,ct=h(()=>{"use strict";zr=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",lC=/\u001B\[[0-9;]*m/,od="\x1B[0m",dC=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),Vr=(e,t)=>{if(t<=0)return"";if(Wf(e)<=t)return e;if(t<=3)return"...".slice(0,t);let r=t-3,o="",s=0,i=!1;for(let l of e.split(/(\u001B\[[0-9;]*m)/))if(l!==""){if(lC.test(l)){o+=l,i=l!==od&&l!=="\x1B[m";continue}for(let u of dC(l)){let p=Wf(u);if(s+p>r)return`${o}...${i?od:""}`;o+=u,s+=p}}return`${o}...${i?od:""}`},ye=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var Gf,qf,zf=h(()=>{"use strict";Gf=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},qf=(e,t)=>t?e.get(t)??[]:[]});var Vf,uC,Kf,Yf=h(()=>{"use strict";ct();zf();Vf=new WeakMap,uC=e=>{let t=Vf.get(e);return t||(t=Gf(e),Vf.set(e,t)),t},Kf=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return qf(uC(e),r).filter(s=>Aa(r,s.toLowerCase())>=n)}});var mC,Jf,Xf,Qf=h(()=>{"use strict";ct();Yf();mC={hint:"",hints:[],overlap:0,remainder:""},Jf=({inputToMatch:e,lastWord:t,isLastWordCompleted:n,inputString:r},o,s=[])=>{if(n||e===""){let[l]=s;return s.length===1&&l&&!r.trim()?Xf("",[l]):mC}let i=Kf({wordList:o,inputToMatch:e,overlapThreshold:1});return Xf(t,i)},Xf=(e,t)=>{let n=t[0]??"",r=Aa(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,l=!!s,m=(l&&i?o:n)+(l&&i?":":" "),f=m.slice(r);return{hint:m,hints:t,overlap:r,remainder:f}}});var Lo,Ta,Kr=h(()=>{"use strict";Lo=e=>{let t=typeof e=="number"?e:Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<3e3||t>864e5?null:t},Ta=e=>e==null||!Number.isFinite(e)?1e4:Math.min(864e5,Math.max(1,e))});import pC from"node:os";import fC from"node:path";var gn,wt,Po=h(()=>{"use strict";gn=".epiq-global",wt=()=>process.env.EPIQ_GLOBAL_DIR??fC.join(pC.homedir(),gn)});var sd,Zf=h(()=>{"use strict";C();sd=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let i=r(...s);if(!n.has(i)){let l=e(...s).then(u=>(a(u)&&n.delete(i),u));n.set(i,l)}return n.get(i)});return o.clear=()=>n.clear(),o}});import hn from"fs";import dd from"path";import gC from"util";function vC(e){if(!hn.existsSync(e))return;let t=hn.statSync(e).size,n=bC(e,ud).split(`
14
- `);if(n[n.length-1]===""&&n.pop(),t<=ud&&n.length<=eg)return;let r=n.slice(-eg).join(`
15
- `)+`
16
- `;hn.writeFileSync(e,r,"utf8")}function cd(e,t,n=!1){let r=yC();if(!r)return;let o=RC(gC.format(...t)),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
17
- `;try{hn.mkdirSync(dd.dirname(r),{recursive:!0}),hn.appendFileSync(r,l,"utf8"),ad++,(ad>=hC||hn.statSync(r).size>ud)&&(ad=0,vC(r))}catch{}}var eg,ud,id,hC,ad,tg,yC,bC,RC,ld,z,yt=h(()=>{"use strict";C();oe();eg=500,ud=4*1024*1024,id=16*1024,hC=50,ad=0,tg=()=>process.env.EPIQ_MCP==="true",yC=()=>{let e=process.cwd(),t=Ma(e);return a(t)?tg()?dd.join(wt(),"epiq-mcp.log"):void 0:dd.join(t.value,bt,"log","epiq.log")},bC=(e,t)=>{let n=hn.statSync(e).size;if(n<=t)return hn.readFileSync(e,"utf8");let r=hn.openSync(e,"r");try{let o=Buffer.alloc(t);hn.readSync(r,o,0,t,n-t);let s=o.toString("utf8"),i=s.indexOf(`
18
- `);return i===-1?"":s.slice(i+1)}finally{hn.closeSync(r)}};RC=e=>{if(e.length<=id)return e;let t=e.length-id;return`${e.slice(0,id)} \u2026 [${t} more chars]`};ld=()=>tg()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",z={info(...e){let t=ld();(t==="info"||t==="debug")&&cd("[Info]",e,!1)},debug(...e){ld()==="debug"&&cd("[Debug]",e,!0)},error(...e){let t=ld();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;cd("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=z});var Ne,ka=h(()=>{"use strict";De();Ne={stage:({cwd:e,pathspec:t,ignoreRemoval:n=!1})=>G({args:["add",...n?["--ignore-removal"]:[],...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1,pathspec:r})=>G({args:["commit","--no-verify",...n?["--allow-empty"]:[],"-m",t,...r?.length?["--",...r]:[]],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>G({args:["fetch",t,`+refs/heads/${n}:refs/remotes/${t}/${n}`],cwd:e}),rebaseOnto:({cwd:e,ref:t})=>G({args:["-c","rebase.autoStash=true","rebase",t],cwd:e}),checkout:({cwd:e,branch:t})=>G({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push","--no-verify",...r?["-u"]:[],t,n]:["push","--no-verify"];return G({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>G({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>G({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>G({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>G({args:["worktree","prune"],cwd:e})}});var lt,$t,wn=h(()=>{"use strict";Yt();C();oe();lt=e=>{let t=Ae(e);if(a(t))return c("Unable to resolve epiq project root");let n=vt(t.value);return a(n)?c("Unable to read project.json"):d("Resolved state branch",n.value.stateBranch)},$t="origin"});import{spawn as sg}from"node:child_process";import Nt from"node:fs";import je from"node:path";var ig,Pa,ag,cg,pd,xC,fd,lg,EC,SC,IC,CC,dg,wC,NC,gd,AC,TC,ug,MC,mg,kC,ng,hd,LC,pg,La,rg,fg,gg,md,PC,hg,yg,OC,bg,vg,Rg,G,Pe,yd,_o,Oa,bd,xg,zn,Ks,_a,Oo,Eg,vd,Da,Sg,Ig,Cg,_C,DC,FC,BC,wg,Ng,Rd,og,Ys,$C,Xs,Ag,Tg,Mg,kg,De=h(()=>{"use strict";C();Po();ka();wn();ig="Output past",Pa=e=>e.includes(ig),ag="Git command timed out",cg=e=>e.includes(ag),pd=1e4,xC=12e4,fd=256*1024*1024,lg=64*1024,EC=8*1024*1024,SC=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),IC=e=>{let t=ug(e);return t&&SC.has(t)?xC:pd},CC=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(je.delimiter))if(t)for(let n of e){let r=je.join(t,n);try{if(!Nt.statSync(r).isFile())continue;return Nt.accessSync(r,Nt.constants.X_OK),r}catch{continue}}return"git"},dg=CC(),wC=["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE"],NC=e=>Object.fromEntries(Object.entries(e).filter(([t])=>!wC.includes(t))),gd={...NC(process.env),GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},AC=["-c","diff.noprefix=false","-c","diff.mnemonicPrefix=false","-c","diff.srcPrefix=a/","-c","diff.dstPrefix=b/","-c","log.showSignature=false"],TC=new Set(["log","show","diff"]),ug=e=>e.find((t,n)=>!t.startsWith("-")&&e[n-1]!=="-c"),MC=e=>TC.has(ug(e)??"")?AC:[],mg=()=>["attr.tree=refs/epiq/no-attributes",`core.hooksPath=${je.join(wt(),"repos",".no-hooks")}`,"protocol.ext.allow=never","protocol.fd.allow=never","protocol.file.allow=always","submodule.recurse=false","fetch.recurseSubmodules=false","credential.interactive=never","core.longpaths=true","gc.auto=0","maintenance.auto=false","fetch.unpackLimit=1","fetch.writeCommitGraph=false","core.logAllRefUpdates=false"].flatMap(e=>["-c",e]),kC=/^[\w-]+[\\/][a-z0-9._-]+-[0-9a-f]{12}\.git(\.\d+(-\d+)?(\.[0-9a-f-]{36})?\.pending)?$/,ng=e=>{try{return Nt.realpathSync(e)}catch{return je.resolve(e)}},hd=e=>{let t=je.join(wt(),"repos");return[[je.resolve(t),je.resolve(e)],[ng(t),ng(e)]].some(([n,r])=>kC.test(je.relative(n,r)))},LC=e=>hd(e)?["--git-dir=.",...mg()]:[],pg={...Object.fromEntries(Object.entries(gd).filter(([e])=>e!=="GIT_ALLOW_PROTOCOL")),LC_ALL:"C",LANGUAGE:"",GIT_PROTOCOL_FROM_USER:"0"},La=new Set,rg=!1,fg=process.platform!=="win32",gg=(e,t)=>{try{if(fg&&e.pid){process.kill(-e.pid,t);return}}catch{}e.kill(t)},md=(e="SIGTERM")=>{for(let t of La)gg(t,e)},PC=["SIGTERM","SIGINT","SIGHUP"],hg=!1,yg=()=>hg,OC=2e3,bg=()=>{if(rg)return;rg=!0,process.once("exit",()=>md());let e=new Map;for(let t of PC)e.set(t,()=>{hg=!0;let n=()=>{for(let[s,i]of e)process.off(s,i);process.kill(process.pid,t)};md();let r=Date.now()+OC,o=()=>{if(La.size===0)return n();if(Date.now()>=r)return md("SIGKILL"),n();setTimeout(o,20)};o()});for(let[t,n]of e)process.once(t,n)},vg=e=>{La.add(e),e.once("close",()=>La.delete(e))},Rg=({args:e,cwd:t,allowFail:n,timeoutMs:r,maxOutput:o=fd,forClone:s=!1,keepPartial:i=!1,abort:l})=>new Promise(u=>{let p=hd(t),m=p||s,f=[...MC(e),...p?["--git-dir=."]:[],...m?mg():[],...e];if(!Nt.existsSync(t)){let $=`Git cwd does not exist: ${t}`;if(n){u({stdout:"",stderr:$,exitCode:1});return}u(c($));return}m&&bg();let g=sg(dg,f,{cwd:t,stdio:["ignore","pipe","pipe"],env:m?pg:gd,detached:m&&fg});m&&vg(g);let b=$=>m?gg(g,$):g.kill($),E=!1,R="",w="",S=$=>{E||(E=!0,clearTimeout(q),u($))},A=r??IC(f),L=!1,P=()=>[`git ${f.join(" ")}`,`cwd=${t}`,`${ag} after ${A}ms`].join(`
19
- `),B=()=>S(n?{stdout:R,stderr:P(),exitCode:124}:c(P())),q=setTimeout(()=>{L=!0,b("SIGTERM"),setTimeout(()=>b("SIGKILL"),3e3).unref(),setTimeout(B,6e3).unref()},A),Q=null,te=()=>{let $=[`git ${f.join(" ")}`,Q].join(`
20
- `);S(n?{stdout:R,stderr:$,exitCode:1}:c($))},we=()=>{Q=String(l?.reason??"stopped"),b("SIGTERM"),setTimeout(()=>b("SIGKILL"),3e3).unref(),setTimeout(te,6e3).unref()};l?.aborted?we():l?.addEventListener("abort",we,{once:!0}),g.stdout.setEncoding("utf8"),g.stderr.setEncoding("utf8"),g.stdout.on("data",$=>{if(R+=$,R.length>o){if(b("SIGTERM"),i&&!n){let Ze=R.slice(0,o);S(d("Git output cut",{stdout:Ze.slice(0,Ze.lastIndexOf(`
21
- `)+1),stderr:w,exitCode:0,truncated:!0}));return}let ne=`git ${f.join(" ")}
22
- ${ig} ${o} characters; stopped`;S(n?{stdout:"",stderr:ne,exitCode:1}:c(ne))}}),g.stderr.on("data",$=>{w.length<lg&&(w+=$)}),g.on("error",$=>{if(n){S({stdout:R,stderr:$.message,exitCode:1});return}S(c([`git ${f.join(" ")}`,`cwd=${t}`,$.message].join(`
23
- `)))}),g.on("close",$=>{if(l?.removeEventListener("abort",we),L)return B();if(Q!==null)return te();let ne=$??1;if(n){S({stdout:R,stderr:w,exitCode:ne});return}if(ne!==0){S(c([`git ${f.join(" ")}`,w.trim()||R.trim()||"Git command failed"].filter(Boolean).join(`
24
- `)));return}S(d("Git command succeeded",{stdout:R,stderr:w,exitCode:ne}))})}),G=({args:e,cwd:t,timeoutMs:n,maxOutput:r,forClone:o,keepPartial:s,abort:i})=>Rg({args:e,cwd:t,allowFail:!1,timeoutMs:n,maxOutput:r,forClone:o,keepPartial:s,abort:i}),Pe=({args:e,cwd:t})=>Rg({args:e,cwd:t,allowFail:!0}),yd=(e,t)=>new Promise(n=>{if(e.length===0){n(d("No blobs to read",new Map));return}let r=hd(t);r&&bg();let o=sg(dg,[...LC(t),"cat-file","--batch"],{cwd:t,stdio:["pipe","pipe","pipe"],env:r?pg:gd});r&&vg(o);let s=[],i="",l=!1,u=f=>{l||(l=!0,clearTimeout(p),n(f))},p=setTimeout(()=>{o.kill("SIGTERM"),u(c(`git cat-file --batch timed out after ${pd}ms`))},pd),m=0;o.stdout.on("data",f=>{if(m+=f.length,m>fd){o.kill("SIGTERM"),u(c(`git cat-file --batch: past ${fd} bytes; stopped`));return}s.push(f)}),o.stderr.setEncoding("utf8"),o.stderr.on("data",f=>{i.length<lg&&(i+=f)}),o.on("error",f=>u(c(f.message))),o.on("close",f=>{if(f!==0){u(c(`git cat-file --batch exited ${f}${i?`
25
- ${i}`:""}`));return}let g=Buffer.concat(s),b=new Map,E=0;for(let R of e){let w=g.indexOf(10,E);if(w===-1){u(c(`git cat-file --batch output ended before a header for ${R}`));return}let S=g.toString("utf8",E,w);E=w+1;let A=/^[0-9a-f]{4,64} \S+ (\d+)$/.exec(S);if(!A||!A[1]){u(c(`Unexpected git cat-file --batch header: "${S}"`));return}let L=Number(A[1]);L<=EC&&b.set(R,g.toString("utf8",E,E+L)),E+=L+1}u(d("Read blobs",b))}),o.stdin.write(e.join(`
26
- `)+`
27
- `),o.stdin.end()}),_o=async({cwd:e,message:t,pathspec:n})=>{let r=await Ne.commit({cwd:e,message:t,pathspec:n});if(a(r))return c(`Failed to create commit
28
- ${r.message}`);let o=await G({args:["rev-parse","HEAD"],cwd:e});return a(o)?c(`Commit created, but failed to read HEAD SHA
29
- ${o.message}`):d("Created commit and resolved SHA",o.value.stdout.trim())},Oa=async e=>{let t=await G({cwd:e,args:["rev-parse","--git-dir"]});if(a(t))return c(t.message);let n=t.value.stdout.trim();return d("Resolved git dir",je.isAbsolute(n)?n:je.resolve(e,n))},bd=async e=>{let t=await Oa(e);if(a(t))return c(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(r))if(Nt.existsSync(je.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(Nt.existsSync(je.join(n,s)))return d("Checked for in-progress Git operation",i);return d("Checked for in-progress Git operation",null)},xg=async e=>{let t=await bd(e);return a(t)?c(t.message):d("Checked for in-progress Git operation",t.value!==null)},zn=async({repoRoot:e})=>{let n=(await Pe({args:["remote","get-url",$t],cwd:e})).exitCode===0;return d(`Checked remote ${n}`,n)},Ks=async({repoRoot:e,branch:t})=>{let n=await Pe({args:["ls-remote","--heads",$t,t],cwd:e});return n.exitCode!==0?c(n.stderr.trim()||`Unable to inspect remote branch ${$t}/${t}`):d("Checked remote branch",n.stdout.trim().length>0)},_a=async({repoRoot:e,branch:t})=>{let n=await Pe({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):c(n.stderr.trim()||`Unable to inspect branch ${t}`)},Oo=e=>{try{return Nt.realpathSync.native(e)}catch{return je.resolve(e)}},Eg=async({repoRoot:e,worktreeRoot:t})=>{let n=await G({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return c(n.message);let r=Oo(t),o=n.value.stdout.split(`
30
- `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Oo).includes(r);return d("Checked worktree registration",o)},vd=async e=>{let t=await Pe({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return d("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Da=async e=>{let t=await G({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?c(t.message):d("Resolved current branch",t.value.stdout.trim())},Sg=async e=>{let t=await G({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?c(t.message):d("Resolved short HEAD sha",t.value.stdout.trim())},Ig=e=>e.includes("fetch first")||e.includes("non-fast-forward"),Cg=async e=>{let t=await Pe({cwd:e,args:["rev-parse","--absolute-git-dir"]});if(t.exitCode!==0)return!1;let n=t.stdout.trim();return n?Nt.existsSync(je.join(n,"rebase-merge"))||Nt.existsSync(je.join(n,"rebase-apply")):!1},_C=3,DC=120,FC=e=>new Promise(t=>setTimeout(t,e)),BC=async(e,t)=>{let n=await Ne.rebaseOnto({cwd:e,ref:t});for(let r=1;r<_C;r+=1){if(!a(n)||await Cg(e))return n;await FC(DC),n=await Ne.rebaseOnto({cwd:e,ref:t})}return n},wg=async(e,{preserve:t=[]}={})=>{let n=await Oa(e);if(a(n))return c(n.message);let r=n.value,o=[];for(let s of Nt.readdirSync(r))if(s.endsWith(".lock")&&!t.includes(s))try{Nt.rmSync(je.join(r,s),{force:!0}),o.push(s)}catch{}return d("Cleared stale git lock files",o)},Ng=async(e,t)=>{let n=await Pe({cwd:e,args:["rev-parse","--git-common-dir"]});if(n.exitCode!==0)return c(`Unable to resolve the common git directory at ${e}`);let r=je.resolve(e,n.stdout.trim()),o=je.join(r,"refs","heads"),s=je.resolve(o,`${t}.lock`);if(!s.startsWith(`${o}${je.sep}`))return c(`Refusing to clear a ref lock outside ${o}`);if(!Nt.existsSync(s))return d("No ref lock to clear",!1);try{Nt.rmSync(s,{force:!0})}catch{return d("Ref lock could not be cleared",!1)}return d("Cleared a stale ref lock",!0)},Rd=async e=>{if(!await Cg(e))return d("No rebase to abort",!1);let t=await Pe({cwd:e,args:["rebase","--abort"]});return t.exitCode!==0?c(`Failed to abort the rebase in progress at ${e}
31
- ${t.stderr.trim()}`):d("Aborted stale rebase",!0)},og=async e=>{let t=await Pe({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},Ys=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),$C=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),Xs=async({cwd:e,branch:t})=>{let n=await Rd(e);if(a(n))return c(n.message);let r=await og(e),o=await Ne.fetch({cwd:e,remote:$t,branch:t});if(a(o))return $C(o.message)?d("Remote branch missing, skipped pull",!1):c(`Failed to fetch ${t}
32
- ${o.message}`);let s=await BC(e,`${$t}/${t}`);if(a(s))return c(`Failed during rebase
33
- ${s.message}`);let i=await og(e),l=r!==null&&i!==null&&r!==i;return d(l?"Pulled with rebase":"Already up to date",l)},Ag=async e=>{let t=await Pe({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)},Tg=async e=>{let t=await Pe({args:["status","--porcelain","--untracked-files=all"],cwd:e});return t.exitCode!==0?c(t.stderr.trim()||"Unable to inspect the worktree for changes"):d("Inspected worktree for changes",t.stdout.trim().length>0)},Mg=async(e,t)=>{let n=await Pe({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):c(n.stderr.trim()||"Unable to inspect staged changes")},kg=async e=>{let t=await Da(e);return a(t)?c(t.message):d("Checked detached HEAD state",t.value==="HEAD")}});import fr from"node:fs";import At from"node:path";var Og,_g,Dg,Fg,Yr,xe,jC,Lg,Js,Qs,Bg,UC,HC,xd,Ed,Pg,$g,jg,jt,TO,tt=h(()=>{"use strict";Yt();C();Po();oe();Zf();yt();De();Og="4b825dc642cb6eb9a060e54bf8d69288fbee4904",_g=e=>At.join(bt,Vn,e),Dg=()=>At.join(bt,Sd),Fg=wt,Yr=()=>At.join(Fg(),"worktrees"),xe=({repoRoot:e})=>{let t=Nn(e);return a(t)?c(t.message):d("Resolved state branch root",At.join(Yr(),t.value))},jC=e=>At.join(e,bt),Lg=e=>At.join(jC(e),Vn),Js=e=>{try{return fr.mkdirSync(e,{recursive:!0}),d("Ensured directory",void 0)}catch(t){return c(t instanceof Error?t.message:String(t))}},Qs=()=>{let e=Fg(),t=Yr(),n=!fr.existsSync(e)||!fr.existsSync(t),r=Js(e);if(a(r))return c(`Ensure epiq home failed.
34
- `+r.message);let o=Js(t);return a(o)?c(`Ensure worktrees dir failed.
35
- `+o.message):d("Ensured epiq storage",n)},Bg=e=>{fr.existsSync(e)&&(z.debug("[sync] remove path",e),fr.rmSync(e,{recursive:!0,force:!0}))},UC=`*.jsonl merge=union
36
- `,HC=`*~pending*.jsonl
37
- `,xd=()=>At.join(bt,Vn,".gitattributes"),Ed=()=>At.join(bt,Vn,".gitignore"),Pg=(e,t)=>{try{fr.readFileSync(e,"utf8")!==t&&fr.writeFileSync(e,t)}catch{fr.writeFileSync(e,t)}},$g=(e,t)=>{for(let n of[Lg(e),Lg(t)]){let r=Js(n);if(a(r))return c(r.message)}return Pg(At.join(t,xd()),UC),Pg(At.join(t,Ed()),HC),d("Ensured state branch",void 0)},jg=async e=>{let t=await G({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return c(`ensure state branch is storage only failed
38
- `+t.message);let r=t.value.stdout.trim().split(`
39
- `).filter(Boolean).filter(i=>i!==bt);if(r.length===0)return d("State branch is storage-only",!1);let o=await G({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(a(o))return c(`Failed to clean storage branch
40
- ${o.message}`);let s=await _o({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:r});return a(s)?c(s.message):d("Cleaned storage branch",!0)},jt=sd(async(e=process.cwd())=>{let t=await G({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?c("Not inside a Git repository"):d("Resolved repo root",t.value.stdout.trim())},e=>At.resolve(e)),TO=sd(async e=>{let t=await G({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return c(t.message);let n=t.value.stdout.trim(),r=At.isAbsolute(n)?n:At.join(e,n);return d("Resolved git dir",r)},e=>At.resolve(e))});import Zs from"node:fs";import An from"node:path";var DO,bt,Vn,Sd,WC,Xr,Do,Tt,Fa,Ug,GC,ei,Ma,qC,Ae,Hg,Ie,oe=h(()=>{"use strict";C();tt();Po();DO=process.env.IS_LOCAL==="true",bt=".epiq",Vn="events",Sd="media",WC="project.json",Xr=e=>An.join(e,bt),Do=e=>An.join(Xr(e),WC),Tt=e=>An.join(Xr(e),Vn),Fa=e=>An.join(Xr(e),Sd),Ug=e=>An.join(e,bt),GC=e=>{let t=An.join(e,bt);return Zs.existsSync(t)&&Zs.statSync(t).isDirectory()},ei=e=>{let t=Do(e);return Zs.existsSync(t)&&Zs.statSync(t).isFile()},Ma=e=>{let t=An.resolve(e);for(;;){if(GC(t))return d("Resolved closest .epiq root",t);let n=An.dirname(t);if(n===t)return c("No .epiq directory found in any parent");t=n}},qC="No .epiq/project.json found in any parent",Ae=e=>{let t=An.resolve(e);for(;;){if(ei(t))return d("Resolved closest epiq project root",t);let n=An.dirname(t);if(n===t)return c(qC);t=n}},Hg=e=>{let t=Tt(e);try{return Zs.mkdirSync(t,{recursive:!0}),d("Resolved events dir",t)}catch(n){return c(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},Ie=async()=>{let e=await jt(process.cwd());if(a(e))return e;let t=xe({repoRoot:e.value});return a(t)?t:d("Resolved persist root",t.value)}});import ti from"node:fs";import{ulid as zC}from"ulid";import{z as Ba}from"zod";var Id,VC,$a,vt,Nn,Cd,Yt=h(()=>{"use strict";C();oe();Id="__epiq_state__",VC=Ba.object({projectId:Ba.string().min(1),stateBranch:Ba.string().min(1),createdAt:Ba.iso.datetime()}),$a=()=>({projectId:zC(),stateBranch:Id,createdAt:new Date().toISOString()}),vt=e=>{let t=Do(e);if(!ti.existsSync(t))return c("Missing .epiq/project.json");try{let n=ti.readFileSync(t,"utf8"),r=JSON.parse(n),o=VC.safeParse(r);return o.success?d("Read project.json",o.data):c(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return c(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},Nn=e=>{let t=vt(e);return a(t)?c(t.message):d("Read projectId",t.value.projectId)},Cd=({repoRoot:e,fileContents:t})=>{let n=Xr(e),r=Do(e);try{if(ti.mkdirSync(n,{recursive:!0}),ti.existsSync(r)){let o=vt(e);return a(o)?c(o.message):d("Project already initialized",null)}return ti.writeFileSync(r,JSON.stringify(t,null,2)+`
41
- `,"utf8"),d("Created project.json",null)}catch(o){return c(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}}});import ni from"node:fs";import ri from"node:path";import{z as Fo}from"zod";var ja,KC,YC,XC,Gg,qg,Wg,zg,Vg,Kg,JC,Ua,oi,Bo=h(()=>{"use strict";C();Yt();Po();oe();ja="recent-projects.json",KC=20,YC=Fo.object({projectId:Fo.string().min(1),root:Fo.string().min(1),lastOpenedAt:Fo.number().finite()}),XC=Fo.object({projects:Fo.array(YC)}),Gg=()=>ri.join(wt(),ja),qg=e=>ri.basename(e)||e,Wg=e=>{let t=ri.resolve(e);try{return ni.realpathSync(t)}catch{return t}},zg=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Vg=e=>{if(!ei(e.root))return!1;let t=Nn(e.root);return!a(t)&&t.value===e.projectId},Kg=()=>{let e=Gg();if(!ni.existsSync(e))return d("No recent projects recorded",[]);let t;try{t=JSON.parse(ni.readFileSync(e,"utf8"))}catch(r){return c(`Invalid ${ja}: ${r instanceof Error?r.message:String(r)}`)}let n=XC.safeParse(t);return n.success?d("Read recent projects",n.data.projects):c(`Invalid ${ja} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},JC=e=>{let t=Gg();try{ni.mkdirSync(ri.dirname(t),{recursive:!0}),ni.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
42
- `,"utf8")}catch(n){return c(`Unable to write ${ja}: ${n instanceof Error?n.message:String(n)}`)}return d("Recorded recent project",e)},Ua=({exclude:e}={})=>{let t=Kg();if(a(t))return t;let n=e===void 0?null:Wg(e);return d("Listed recent projects",t.value.filter(r=>n===null||Wg(r.root)!==n).filter(Vg).sort(zg))},oi=({root:e,now:t=Date.now()})=>{let n=ri.resolve(e),r=Nn(n);if(a(r))return c(r.message);let o=r.value,s=Kg(),i=a(s)?[]:s.value,l=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(u=>u.projectId!==o&&u.root!==n)].filter(Vg).sort(zg).slice(0,KC);return JC(l)}});import{useSyncExternalStore as n_}from"react";var Ha,QC,ZC,ce,Rt,Ue=h(()=>{"use strict";Ha={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,gitEmail:null,gitName:null,declinedEmailBoards:[],viewMode:null},QC=new Set,ZC=()=>{for(let e of QC)e()},ce=()=>Ha,Rt=e=>(Ha={...Ha,...e},ZC(),Ha)});var wd,Yg,Xg,Nd=h(()=>{"use strict";wd=null,Yg=e=>{wd=e},Xg=e=>wd?wd(e):[]});var Jg,Qg,$o,si=h(()=>{"use strict";Jg=[],Qg=e=>{Jg=e},$o=()=>Jg});var ii,Ad,Zg,eh,Td,th,nh,rh,Jr=h(()=>{"use strict";Bt();C();Yt();Ue();Nd();si();oe();ii=()=>{let e=ce(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1,o=Zg(),s=o.length>0?null:Ad(),i=s!==null&&(e.declinedEmailBoards??[]).includes(s),l=o.length>0||i||s===null;return{isSetupDone:n&&t&&r&&l,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r,isSetEmails:l,claimedEmails:o,emailSetupDeclined:i}},Ad=()=>{let e=Ae(process.cwd());if(a(e))return null;let t=Nn(e.value);return a(t)?null:t.value||null},Zg=()=>{let{userId:e}=ce();return e?Xg(e):[]},eh=()=>Zg().length>0,Td=()=>{let e=Ae(process.cwd());if(a(e))return!1;let t=vt(e.value);return Vt(t)},th=e=>e===!0?"on":e===!1?"off":null,nh=e=>e==="on"?!0:e==="off"?!1:null,rh=()=>{let e=ii();if(!e.isSetUserName)return"config username ";if(!e.isSetPreferredEditor)return"config editor ";if(!e.isSetAutoSync)return"config autoSync ";if(!Td())return"init";if(!e.isSetEmails){let{gitEmail:t}=ce(),n=$o()[0]??t;return n&&ur(n)?`config emails ${n}`:"config emails "}return null}});var ew,Te,Wa,yn=h(()=>{"use strict";ew=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[Te,Wa]=ew});var tw,nw,Tn,Mn,Ga,qa,jo=h(()=>{"use strict";pe();C();ge();O();tw=e=>e.props.tags??[],nw=e=>e.props.assignees??[],Tn=e=>tw(e).map(t=>N.getTag(t)).filter(t=>!!t),Mn=e=>nw(e).map(t=>N.getContributor(t)).filter(t=>!!t),Ga=()=>{let{breadCrumb:e,selectedNode:t}=y(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!W(n)?c("Invalid untag target"):d("Retrieved tags from ticket in breadcrumb",Tn(n))},qa=()=>{let{breadCrumb:e,selectedNode:t}=y(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!W(n)?c("Invalid unassign target"):d("Retrieved assignees from ticket in breadcrumb",Mn(n))}});var I,Qr=h(()=>{"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 rw,ow,sw,iw,aw,Zr,oh,za,Va,sh,cw,Md,ai=h(()=>{"use strict";rw=/^(\d+)(h|d|w|mo|y)$/,ow=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,sw=({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},iw=(e,t=new Date)=>{let n=e.match(rw);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}},aw=e=>{let t=e.match(ow);if(!t)return null;let[,n,r,o,s,i]=t,l=Number(n),u=Number(r),p=Number(o),m=s?Number(s):0,f=i?Number(i):0;return sw({year:l,month:u,day:p,hour:m,minute:f})?new Date(l,u-1,p,m,f):null},Zr=e=>{let t=e.trim().toLowerCase();return iw(t)??aw(t)},oh=/^(\d+)(s|m)?$/,za=e=>{let t=e.trim().toLowerCase().match(oh);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Va=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&oh.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},sh=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,cw=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],Md=(e=cw)=>{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 lw,ie,Ut,Ve,dw,uw,Ld,Pd,Od,ch,eo,Ka,kd,ih,mw,pw,ci,ah,fw,gw,_d,hw,Ke,Kn=h(()=>{"use strict";Kr();Bo();C();Jr();yn();pe();ge();O();Jl();jo();Qr();ai();lw=["BOARD","TICKET","SWIMLANE","COMMENT"],ie={EDITOR:"editor",VIEW:"view",USERNAME:"username",EMAILS:"emails",EMAILS_UNCLAIM:"emails-unclaim",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",REPO_CLONE_MAX_MB:"repoCloneMaxMb",LOG_LEVEL:"logLevel",REPO_CONNECT:"repoConnect",REPO_DISCONNECT:"repoDisconnect"},Ut={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Ve={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},dw=[ie.EDITOR,ie.VIEW,ie.USERNAME,ie.EMAILS,ie.EMAILS_UNCLAIM,ie.AUTOSYNC,ie.SYNC_DEBOUNCE_MS,ie.ATTACHMENT_MAX_KB,ie.LOG_LEVEL,ie.REPO_CONNECT,ie.REPO_DISCONNECT,ie.REPO_CLONE_MAX_MB],uw=(e=y().selectedNode?.context)=>{switch(e){case"TICKET":return[Ut.TITLE,Ut.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Ut.TITLE];case"COMMENT":return[Ut.COMMENT];default:return[]}},Ld=[String(3e3),"5000","15000","30000","60000"],Pd=["250","500","1000"],Od=["512","2048","8192"],ch=["10s","20s","30s","45s"],eo=[I.EXIT,I.SYNC,I.HELP,I.EXPORT,I.CONFIG,I.YANK],Ka=[I.NEW,I.EDIT,I.DELETE,I.MOVE],kd=[I.TAG,I.UNTAG,I.ASSIGN,I.UNASSIGN,I.CLOSE_ISSUE,I.RE_OPEN_ISSUE,I.EDIT,I.COMMENT],ih=[I.FILTER,I.PEEK,I.REPLAY],mw={WORKSPACE:[...eo,...Ka],BOARD:[...ih,...eo,...Ka],SWIMLANE:[...ih,...eo,...Ka],TICKET:[...eo,...Ka,...kd],FIELD:[...eo,...kd],FIELD_LIST:[...eo,...kd],TEXT:[...eo],COMMENT:[I.EDIT,I.DELETE,I.YANK]},pw=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],ci=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&W(n)),ah=e=>e.parentNodeId===Te,fw=({selectedNode:e,breadCrumb:t})=>{let n=uw(e?.context);return ci({breadCrumb:t,selectedNode:e})?n.includes(Ut.DESCRIPTION)?n:[...n,Ut.DESCRIPTION]:n},gw=({selectedNode:e,breadCrumb:t})=>{let n=ci({breadCrumb:t,selectedNode:e});return n?[Ve.REF,Ve.TITLE,...n.props?.description?.trim()?[Ve.DESCRIPTION]:[],...Tn(n).length>0?[Ve.TAGS]:[],...Mn(n).length>0?[Ve.ASSIGNEES]:[]]:e?[Ve.REF,Ve.TITLE]:[]},_d=()=>{let e=Ua({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},hw=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=ii();if(!r)return[I.HELP,I.CONFIG];if(!Td())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&&lw.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?mw[u]:[]))],l=ci({breadCrumb:n,selectedNode:e});return i.filter(u=>u===I.MOVE?!1:u===I.YANK?!!(l??e):u===I.EDIT?s||!!l:u===I.DELETE?s:u===I.UNTAG?!!(l&&Tn(l).length>0):u===I.UNASSIGN?!!(l&&Mn(l).length>0):u===I.RE_OPEN_ISSUE?!!(l&&ah(l)):u===I.CLOSE_ISSUE?!!(l&&!ah(l)):!0)},Ke=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=y())=>{let s=t.context??"WORKSPACE";return{[I.NONE]:hw({breadCrumb:o,readOnly:r,selectedNode:n}),[I.EXIT]:["confirm"],[I.EXPORT]:[],[I.SYNC]:[],[I.INIT]:[],[I.OPEN]:e===I.OPEN?_d():[],[I.HELP]:[],[I.PEEK]:[...Md(),"now","prev","next"],[I.REPLAY]:[...Md()],[I.EDIT]:fw({selectedNode:n,breadCrumb:o}),[I.YANK]:gw({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(Ia),...N.getExistingTags()])],[I.UNTAG]:[...Ga()?.value?.map(({name:l})=>l)??[]],[I.UNASSIGN]:[...qa()?.value?.map(({name:l})=>l)??[]],[I.ASSIGN]:N.getExistingAssignees(),[I.NEW]:pw(s),[I.CONFIG]:[...dw]}[e]??[]}});var lh,dh=h(()=>{"use strict";lh=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{accessSync as yw,copyFileSync as bw,existsSync as Ya,mkdirSync as uh,readdirSync as mh,readFileSync as vw,renameSync as Rw,rmSync as xw,statSync as ph,unlinkSync as Ew,writeFileSync as Sw}from"node:fs";import Uo from"node:path";var Dd,nt,Xa=h(()=>{"use strict";Dd=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",nt={writeToFile:(e,t)=>{try{let n=Uo.dirname(e);Ya(n)||uh(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Sw(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return vw(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=nt.readFile(e);return t===null?null:JSON.parse(t)}catch(t){return logger.error(`Failed to read JSON at ${e}:`,t),null}},dirExists:e=>{try{return Ya(e)&&ph(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await yw(e),!0}catch{return!1}},mkDir:e=>uh(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Uo.parse(t);for(;;){let r=Uo.join(t,e);try{if(Ya(r)&&ph(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Uo.dirname(t)}return null},readFirstJSON(e){try{if(!nt.dirExists(e))return null;let t=mh(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Uo.join(e,t);return nt.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return nt.dirExists(e)?mh(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Ew(e)}catch(t){(!Dd(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{xw(e,{recursive:!0,force:!0})}catch(t){(!Dd(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Uo.dirname(t)),!n?.overwrite&&Ya(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Rw(e,t)}catch(r){if(Dd(r)&&r.code==="EXDEV"){bw(e,t),this.rmFile(e);return}throw r}}}});import Iw from"node:path";import{z as Xt}from"zod";var Cw,gh,ww,hh,Fd,Bd,Nw,Jt,yh,dt,gr,Qt=h(()=>{"use strict";$r();Kr();oe();C();Xa();Cw={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},gh=Xt.object({logLevel:Xt.enum(["info","error","debug"]),preferredEditor:Xt.string().optional(),userName:Xt.string().optional(),userId:Xt.string().optional(),autoSync:Xt.boolean().nullable().optional(),autoSyncDebounceMs:Xt.number().optional(),attachmentMaxKb:Xt.number().optional(),repoCloneMaxMb:Xt.number().optional(),viewMode:Xt.enum(["dense","wide"]).optional(),declinedEmailBoards:Xt.array(Xt.string()).optional()}).partial(),ww="config.json",hh=wt,Fd=()=>Iw.join(hh(),ww),Bd=()=>{try{return nt.mkDir(hh()),d(`Ensured ~/${gn} exists`,null)}catch{return c(`Unable to create ~/${gn}`)}},Nw=e=>{let t;try{t=JSON.parse(e)}catch{return c(`Invalid ~/${gn}/config.json JSON`)}let n=gh.safeParse(t??{});return n.success?d("Parsed config",n.data):c(`Invalid ~/${gn}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Jt=()=>{let e=Bd();if(a(e))return c(e.message);let t=Fd(),n=nt.readFile(t);return n==null||n.trim()===""?d("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Nw(n)},yh=e=>{let t=Bd();if(a(t))return c(t.message);let n=gh.safeParse(e);if(!n.success)return c(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Fd();try{return nt.writeToFile(r,JSON.stringify(n.data,null,2)+`
43
- `),d("Config written",null)}catch{return c(`Unable to write ~/${gn}/config.json`)}},dt=e=>{let t=Jt();if(a(t))return c("Failed to read existing config");let n={...t.value,...e};return yh(n)},gr=()=>{let e=Fd(),t=Bd();if(a(t))return c(`Unable to create ~/${gn}`);if(!(nt.readFile(e)!==null)){let R=yh(Cw);if(a(R))throw new Error(`Unable to create ~/${gn}/config.json`)}let r=Jt();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,declinedEmailBoards:l,autoSync:u,autoSyncDebounceMs:p,attachmentMaxKb:m,logLevel:f,viewMode:g}=r.value,b=Ul({userId:i,userName:s});if(a(b))return c(b.message);let E=b.value??{userId:i,userName:s};return!E.userName||!E.userId?c(`User name or ID not configured in ~/${gn}/config.json`):(process.env.EPIQ_LOG_LEVEL=f,d("successfully loaded settings",{gitEmail:null,gitName:null,declinedEmailBoards:l??[],logLevel:f??"debug",preferredEditor:o??"",userName:E.userName,userId:E.userId,autoSync:u??!1,autoSyncIntervalMs:p??1e4,attachmentMaxKb:m??null,viewMode:g??"dense"}))}});var bh,vh,$d,Rh=h(()=>{"use strict";bh="/media/",vh=e=>`${bh}${e}`,$d=(e,t)=>`![${e}](${vh(t)})`});import Aw from"node:crypto";import jd from"node:fs";import Tw from"node:path";var Yn,Ho,Mw,kw,Lw,xh,Wo=h(()=>{"use strict";fn();C();oe();Rh();Yn=500,Ho=(e,t)=>`${e}.${t}`,Mw=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"):c(`Unsupported image format. Allowed: ${$f.join(", ")}`),kw=e=>Aw.createHash("sha256").update(e).digest("hex"),Lw=(e,t=Yn)=>{if(e.length===0)return c("Attachment is empty");if(e.length>t*1024)return c(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=Mw(e);return a(n)?n:d("Validated attachment data",{hash:kw(e),ext:n.value,bytes:e.length})},xh=(e,t,n=Yn)=>{let r=Lw(t,n);if(a(r))return r;let o=Fa(e),s=Tw.join(o,Ho(r.value.hash,r.value.ext));try{jd.existsSync(s)||(jd.mkdirSync(o,{recursive:!0}),jd.writeFileSync(s,t))}catch(i){return c(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return d("Wrote attachment blob",r.value)}});import Pw from"zod";var li,di,Eh,Ud=h(()=>{"use strict";Qt();Wo();C();he();Ue();li=50,di=5e3,Eh=()=>{let e=le().commandMeta.inputString,t=Pw.coerce.number().int().min(li).max(di).safeParse(e);if(!t.success)return c(`Attachment size cap must be ${li}-${di} KB (default ${Yn})`);let n=dt({attachmentMaxKb:t.data});return a(n)?n:(Rt({attachmentMaxKb:t.data}),d(`Attachment size cap set to ${t.data} KB`,null))}});import Sh from"node:fs";import Ow from"node:path";var Hd,Go,qo,Wd,zo,hr,ui,Ja=h(()=>{"use strict";Qt();C();Hd=2048,Go=1,qo=1048576,Wd=e=>Number.isInteger(e)&&e>=Go&&e<=qo,zo=()=>{let e=Jt(),t=a(e)?void 0:e.value.repoCloneMaxMb;return t!==void 0&&Wd(t)?t:Hd},hr=e=>{let t=0,n=r=>{let o;try{o=Sh.readdirSync(r,{withFileTypes:!0})}catch{return}for(let s of o){let i=Ow.join(r,s.name);if(s.isDirectory()){n(i);continue}try{t+=Sh.lstatSync(i).size}catch{}}};return n(e),t},ui=e=>`Its clone would pass this machine's ${e} MB cap for a connected repo: narrow its history, or raise repoCloneMaxMb`});var Mt,mi,Vo=h(()=>{"use strict";C();oe();Mt=e=>{let t=Ae(e??process.cwd());return a(t)?c(t.message):d("Resolved Epiq repo root",t.value)},mi=e=>/^[0-9a-f]{7,40}$/i.test(e)});import Gd from"node:fs";import _w from"node:path";var pi,qd,zd,kt,Ih,Vd,Xn,Qa,Ko,Ch,wh,kn=h(()=>{"use strict";oe();pi=e=>e?.code==="ENOENT",qd=3,zd=e=>Gd.readdirSync(e).filter(t=>t.endsWith(".jsonl")).sort(),kt=e=>{let t=Tt(e);for(let n=1;;n++){if(!Gd.existsSync(t))return"none";let r=[],o=!1;for(let s of zd(t))try{let{size:i,mtimeMs:l}=Gd.statSync(_w.join(t,s));r.push(`${s}:${i}:${l}`)}catch(i){if(!pi(i))throw i;if(n<qd){o=!0;break}}if(!o)return r.join("|")}},Ih=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),Vd=(e,t,n,r)=>{let o=Ih(t),s=kt(e),i=Ih(s),l=u=>u===void 0?0:Number(u.slice(0,u.indexOf(":")));if(l(i.get(n))!==l(o.get(n))+r)return null;for(let[u,p]of i)if(u!==n&&o.get(u)!==p)return null;for(let u of o.keys())if(u!==n&&!i.has(u))return null;return s},Xn=null,Qa=e=>Xn&&Xn.root===e?Xn.signature:null,Ko=(e,t)=>{Xn={root:e,signature:t}},Ch=(e,t,n)=>{if(!Xn||Xn.root!==e)return;let r=Vd(e,Xn.signature,t,n);Xn=r===null?null:{root:e,signature:r}},wh=()=>{Xn=null}});import{z as no}from"zod";var Nh,Ah,Dw,OD,Fw,Bw,Th,$w,jw,Kd,Mh,Yd,fi=h(()=>{"use strict";C();Nh=1,Ah=no.tuple([no.string().min(1),no.string().min(1).nullable()]),Dw=no.looseObject({v:no.literal(Nh),id:Ah}),OD=no.looseObject({v:no.number().int().positive(),id:Ah}),Fw=e=>Object.prototype.hasOwnProperty.call(e,"__proto__"),Bw=e=>{let t={};for(let n of Object.keys(e))n!=="__proto__"&&(t[n]=e[n]);return t},Th=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return c("Invalid persisted event envelope: expected an object");let{v:t,id:n}=e;if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return c("Invalid persisted event envelope: v");if(!Array.isArray(n)||n.length!==2)return c("Invalid persisted event envelope: id");let[r,o]=n;return typeof r!="string"||r.length===0?c("Invalid persisted event envelope: id.0"):o!==null&&(typeof o!="string"||o.length===0)?c("Invalid persisted event envelope: id.1"):d("Parsed persisted event envelope",Fw(e)?Bw(e):e)},$w=[1],jw=new Set($w),Kd=e=>jw.has(e),Mh=e=>{let t=Dw.safeParse(e);return t.success?d("Parsed persisted event",t.data):c(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Yd=(e,t)=>{let n={[e.action]:e.payload,v:Nh,id:t};return Mh(n)}});import He from"node:fs";import ro from"node:path";import{ulid as Uw}from"ulid";var ec,Xd,Lh,Ph,tc,Hw,Jd,oo,gi,Oh,Ww,Gw,_h,qw,Dh,zw,Fh,Vw,Za,kh,nc,so=h(()=>{"use strict";C();oe();ec="~pending",Xd=/~pending(-[0-9a-z]+)*$/i,Lh=/-f(\d+)$/,Ph=e=>{let t=e.indexOf(".");return t===-1?`${e}${ec}`:e.slice(0,t)+ec+e.slice(t)},tc=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},Hw=e=>{let[t,n]=tc(e);return Xd.test(t)?t.replace(Xd,"")+n:null},Jd=e=>e.replace(Xd,""),oo=e=>e.endsWith(".jsonl")&&Hw(e)!==null,gi=e=>Jd(tc(e)[0]),Oh=e=>{let[t]=tc(e),n=Lh.exec(t);return n&&oo(e)?Number(n[1]):null},Ww=e=>Ph(e).replace(ec,`${ec}-${Uw().toLowerCase()}`),Gw=(e,t)=>{let[n,r]=tc(e);return`${n.replace(Lh,"")}-f${t}${r}`},_h=(e,t)=>ro.join(Tt(e),Ph(t)),qw=(e,t)=>Math.max(0,He.statSync(e).size-(Oh(t)??0)),Dh=e=>{let t=Tt(e);try{return He.existsSync(t)?He.readdirSync(t).filter(oo).some(n=>qw(ro.join(t,n),n)>0):!1}catch{return!0}},zw=3,Fh=(e,t)=>{for(let n=1;;n++){let r=He.openSync(e,"a"),o;try{He.writeSync(r,t),o=He.fstatSync(r).ino}finally{He.closeSync(r)}let s;try{s=He.statSync(e).ino}catch{s=null}if(s===o||n>=zw)return}},Vw=e=>{let t;try{t=He.openSync(e,"r")}catch{return!0}try{let{size:n}=He.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return He.readSync(t,r,0,1,n-1),r[0]===10}finally{He.closeSync(t)}},Za=10,kh=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(Za)+1;if(r===0)return{bytes:0,lines:0};let o=t.subarray(0,r);if(o.toString("utf8").trim().length===0)return{bytes:r,lines:0};He.appendFileSync(e,Buffer.concat([Buffer.from(Vw(e)?"":`
44
- `),o,Buffer.from(o[o.length-1]===Za?"":`
45
- `)]));let s=0;for(let i of o)i===Za&&s++;return o[o.length-1]!==Za&&s++,{bytes:r,lines:s}},nc=(e,t)=>{let n=Tt(e);if(!He.existsSync(n))return d("No events directory",0);try{let r=gi(t),o=He.readdirSync(n).filter(l=>oo(l)&&gi(l)===r),s=ro.join(n,t),i=0;for(let l of o){let u=Oh(l);if(u!==null){let g=ro.join(n,l),b=He.readFileSync(g).subarray(u);i+=kh(s,b,!0).lines,He.rmSync(g,{force:!0});continue}let p=/~pending-/i.test(l)?l:Ww(t),m=ro.join(n,p);p!==l&&He.renameSync(ro.join(n,l),m);let f=kh(s,He.readFileSync(m));i+=f.lines,He.renameSync(m,ro.join(n,Gw(p,f.bytes)))}return d("Folded pending logs",i)}catch(r){return c(`Unable to fold pending event logs in ${n}: ${r instanceof Error?r.message:String(r)}`)}}});import yi from"node:fs";import oc from"node:path";import{decodeTime as Kw}from"ulid";import{z as Qd}from"zod";var sc,Yw,Uh,rc,Xw,Jw,Hh,Qw,Zw,yr,eN,tN,hi,Zd,nN,rN,oN,Bh,sN,Wh,$h,eu,jh,tu,Gh,qh,nu=h(()=>{"use strict";yt();C();oe();ht();fi();kn();so();sc="unknown",Yw=Qd.object({userId:Qd.string().min(1).default(sc),userName:Qd.string().min(1).default(sc)}),Uh=new Set(["id","v","userId","userName"]),rc=e=>{let t=Object.entries(e).filter(([o])=>!Uh.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},Xw=/^[0-9a-hjkmnp-tv-z]{26}$/i,Jw=e=>Xw.test(e)?e.toUpperCase():e,Hh=e=>{let t=oc.basename(e,".jsonl"),n=t.indexOf("."),r=Jd(n===-1?t:t.slice(0,n)),o=n===-1?void 0:t.slice(n+1),s=Yw.safeParse({userId:Jw(r),userName:o});return s.success?d("Parsed event file actor",s.data):c(`Invalid event file name ${oc.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},Qw=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?c(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?c("Invalid persisted event: action key is missing or invalid"):d("Resolved persisted action",t[0])},Zw=(e,t)=>t in e,yr=new Map,eN=3e5,tN=512,hi=0,Zd=e=>e.entries.length+e.quarantined.length,nN=(e,t,n,r)=>{let o=yr.get(e);o&&(hi-=Zd(o));let s={stamp:t,entries:n,quarantined:r};yr.delete(e),yr.set(e,s),hi+=Zd(s);for(let[i,l]of yr){if(hi<=eN&&yr.size<=tN)break;i!==e&&(yr.delete(i),hi-=Zd(l))}},rN=()=>{yr.clear(),hi=0},oN=2n,Bh=1000000n,sN=e=>{try{let{size:t,mtimeNs:n}=yi.statSync(e,{bigint:!0});return{value:`${t}:${n}`,settled:BigInt(Date.now())*Bh-n>oN*Bh}}catch{return null}},Wh=(e,t)=>{let n=Hh(e);if(a(n))return c(n.message);let r=sN(e),o=r?yr.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=yi.readFileSync(e,"utf8")}catch(m){if(pi(m))return d("Event file missing",null);throw m}let i=[],l=oc.basename(e),u=[],p=(m,f)=>{u.push({eventId:null,reason:"corrupt-line",detail:`${l}:${m} (${f})`,targetNodeId:null})};for(let[m,f]of s.split(`
46
- `).entries()){let g=f.trim();if(!g)continue;let b;try{b=JSON.parse(g)}catch{p(m+1,"invalid JSON");continue}let E=Th(b);if(a(E)){p(m+1,E.message);continue}i.push({...E.value,userId:n.value.userId,userName:n.value.userName})}if(t)for(let m of u)t.push(m);return r?.settled&&nN(e,r.value,i,u),d("Parsed persisted events file",[...i])},$h=(e,t)=>e<t?-1:e>t?1:0,eu=(e,t)=>{let n=$h(e.id[0],t.id[0]);return n!==0?n:$h(JSON.stringify(e),JSON.stringify(t))},jh=(e,t)=>{let n=new Map,r=new Map;for(let m of e){let f=m.id[0],g=m.id[1]??null;n.set(f,m);let b=r.get(g)??[];b.push(m),r.set(g,b)}for(let m of r.values())m.sort(eu);let o=[],s=new Set,i=m=>{let f=[m];for(;f.length>0;){let g=f.pop(),b=g.id[0];if(s.has(b))continue;o.push(g),s.add(b);let E=r.get(b)??[];for(let R=E.length-1;R>=0;R--)f.push(E[R])}},l=(r.get(null)??[]).filter(m=>{let f=Object.keys(m).filter(g=>!Uh.has(g));return f.length===1&&f[0]===t});for(let m of l)i(m);let u=e.filter(m=>{let f=m.id[0],g=m.id[1]??null;return s.has(f)?!1:g===null||!n.has(g)}).sort(eu);for(let m of u)i(m);let p=e.filter(m=>!s.has(m.id[0])).sort(eu);for(let m of p)i(m);return o},tu=e=>Hs(e.map(t=>{try{return Kw(t.id[0])}catch{return null}})),Gh=(e,t)=>{let n=new Set,r=[],o=[],s=tu(e);for(let i=0;i<e.length;i++){let l=e[i],u=l.id[0],p=l.id[1],m=s[i]??null;!(m!==null&&m<t)||p&&n.has(p)?(n.add(u),o.push(l)):r.push(l)}return{appliedEvents:r,unappliedEvents:o}},qh=e=>{let t=new Set(e.actions),n=S=>t.has(S),r=S=>{let{userId:A,userName:L,...P}=S,B=Qw(P);if(a(B))return c(B.message);let q=B.value,Q=S.id?.[0];return Q?Zw(P,q)?d("Decoded persisted event",{id:Q,action:q,payload:P[q],userId:A}):c(`Persisted event is missing payload for action: ${q}`):c("Persisted event is missing id")},o=(S,A)=>{let L=[],P=new Map,B=new Map;for(let q of S){if(!Kd(q.v)){B.set(q.v,(B.get(q.v)??0)+1),A?.push({eventId:q.id[0],reason:"unsupported-schema-version",detail:`v${q.v}`,targetNodeId:rc(q)});continue}let Q=r(q);if(a(Q)){A?.push({eventId:q.id[0],reason:"invalid-payload",detail:Q.message,targetNodeId:rc(q)});continue}let te=Q.value.action;if(!n(te)){P.set(te,(P.get(te)??0)+1),A?.push({eventId:q.id[0],reason:"unknown-action",detail:te,targetNodeId:rc(q)});continue}let we=e.readPayload(te,Q.value.payload);if(a(we)){A?.push({eventId:q.id[0],reason:"invalid-payload",detail:we.message,targetNodeId:rc(q)});continue}L.push(Q.value)}if(P.size>0){let q=[...P.entries()].map(([Q,te])=>`${Q} (x${te})`).join(", ");z.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${q}. Upgrade to apply them.`)}if(B.size>0){let q=[...B.entries()].map(([Q,te])=>`v${Q} (x${te})`).join(", ");z.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${q}. Upgrade to apply them.`)}return d("Decoded reconstructed events",L)},s=null;function i(S,A){let L=Tt(S),P=kt(S);if(!yi.existsSync(L))return d("No events found",[]);let B=[],q=[];for(let te=1;;te++){B=[],q=[];let we=!1;for(let $ of zd(L)){let ne=Wh(oc.join(L,$),q);if(a(ne))return c(ne.message);if(ne.value===null){if(te<qd){we=!0;break}continue}for(let Ze of ne.value)B.push(Ze)}if(!we)break}if(A)for(let te of q)A.push(te);let Q=jh(B,e.genesis);return s={root:S,signature:P,edge:Q.at(-1)?.id?.[0]??null},d("All events loaded",Q)}function l(S){let A=[],L=i(S,A);if(a(L))return c(L.message);let P=o(L.value,A);return a(P)?c(P.message):d("Loaded merged events",{events:P.value,unreadable:A})}function u(S){let A=i(S);return a(A)?c(A.message):d("Loaded event actors",A.value.map(({userId:L,userName:P})=>({userId:L,userName:P})))}function p(S){let A=new Map,L=Tt(S),P;try{if(!yi.existsSync(L))return A;P=yi.readdirSync(L)}catch{return A}let B=new Set;for(let Q of P){if(!Q.endsWith(".jsonl"))continue;let te=Hh(Q);if(a(te))continue;let{userId:we,userName:$}=te.value;if(!we||!$||$===sc)continue;let ne=A.get(we);ne!==void 0&&ne!==$&&B.add(we),A.set(we,$)}if(B.size===0)return A;let q=u(S);if(a(q))return A;for(let{userId:Q,userName:te}of q.value)B.has(Q)&&(!te||te===sc||A.set(Q,te));return A}function m(S){let A=l(S);return a(A)?c(A.message):d("Loaded merged events",A.value.events)}function f(S,A){let L=i(S);if(a(L))return c(L.message);let{appliedEvents:P,unappliedEvents:B}=Gh(L.value,A),q=o(P);if(a(q))return c(q.message);let Q=o(B);return a(Q)?c(Q.message):d("Loaded merged events before time",{appliedEvents:q.value,unappliedEvents:Q.value})}function g(S=process.cwd()){let A=kt(S);if(s&&s.root===S&&s.signature===A)return d("Loaded edge reference, unchanged",s.edge);let L=i(S);return a(L)?c(L.message):d("Loaded edge reference",L.value.at(-1)?.id?.[0]??null)}function b(S,A,L,P){if(!s||s.root!==S)return;let B=Vd(S,s.signature,A,P);s=B===null?null:{root:S,signature:B,edge:L}}function E(){s=null,rN()}let R=S=>jh(S,e.genesis);function w(S){let A=i(S);if(a(A))return c(A.message);let L=tu(A.value);return d("Loaded effective event times",new Map(A.value.map((P,B)=>[P.id[0],L[B]??null])))}return{fromPersistedEvent:r,decodeReconstructedEvents:o,loadMergedEventsWithUnreadable:l,loadEventActors:u,loadActorNames:p,loadMergedEvents:m,loadMergedEventsBefore:f,getEdgeRef:g,advanceEdgeRef:b,clearEdgeCache:E,getSortedEvents:R,loadEffectiveEventTimes:w}}});var ic,U,Yo,br,vr,iN,zh,ac=h(()=>{"use strict";yt();C();ic=(e,t)=>c(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),U=(e,t)=>({...ic(e,t),convergence:!0}),Yo=e=>a(e)&&e.convergence===!0,br=e=>{let t=e.filter(a);return{fatal:t.filter(n=>!Yo(n)),skipped:t.filter(Yo)}},vr=e=>{e.length!==0&&z.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},iN=e=>e.userId?.length?null:ic("Invalid user ID format",e),zh=e=>{let t=null;function n(o,s=!1){let i=e.apply[o.action];if(!i)return c(`Unknown event action "${o.action}", likely created by a newer epiq version. Evt id: ${o.id}`);if(!e.replay.isInitialized()&&o.action!==e.genesis)return U(`${o.action} arrived before the state was initialized`,o);if(o.action===e.genesis&&t){if(t.genesisApplied)return U("the state is already initialized",o);t.genesisApplied=!0}let l;try{l=i(o)}catch(m){return U(`threw while materializing (${m instanceof Error?m.message:String(m)})`,o)}if(a(l))return l;let u=iN(o);if(u)return u;let p=e.replay.afterApply(o,{batched:t!==null,bypassLogging:s});return p||l}return{materialize:n,materializeAll:o=>{let s=e.replay.batch(()=>{let i=t===null;i&&(t={genesisApplied:!1});let l=!1;try{let u=o.map(p=>n(p));if(i){l=!0;let p=e.replay.flush();if(p)return o.map(()=>p)}return u}finally{i&&(t=null,l||e.replay.flush())}});return a(s)?o.map(()=>c(s.message)):s.value}}}});var Vh,Kh=h(()=>{"use strict";Vh=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown"});var D,Yh,Zt=h(()=>{"use strict";D=({userId:e})=>({userId:e}),Yh=e=>({action:e.action,payload:e.payload})});import Xh from"node:fs";import ru from"node:path";import{decodeTime as aN,monotonicFactory as cN}from"ulid";var lN,dN,uN,Rr,Jh,Qh,Zh,cc=h(()=>{"use strict";yt();C();oe();Kh();ht();fi();Zt();kn();so();lN=0xffffffffffff,dN=Sa,uN=e=>{let t=Date.now(),n;try{n=aN(e)}catch{return t}return n>=lN?t:n>t+dN?(z.error("[persist] edge id is too far in the future; seeding from the wall clock instead",{edgeRef:e,edgeTime:n,now:t}),t):Math.max(t,n+1)},Rr=({userId:e})=>`${Vh(e)}.jsonl`,Jh=(e,t)=>{let n;try{if(!Xh.existsSync(e))return[t];n=Xh.readdirSync(e)}catch{return[t]}let r=gi(t);return[...n.filter(s=>!s.endsWith(".jsonl")||s===t||oo(s)?!1:gi(s)===r).sort(),t]},Qh=(e,{userId:t})=>{let n=Rr({userId:t});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(n))return c(`Invalid event log file name: ${n}`);let o=ru.join(Tt(e),n);return d("Successfully resolved event log path",o)},Zh=e=>{let t=cN();function n(o,s){let i;if(s&&s.current!==void 0)i=s.current;else{let u=e.getEdgeRef(o);if(a(u))return c(u.message);i=u.value}let l=i?t(uN(i)):t();return d("Minted event id",[l,i])}function r({event:o,rootDir:s,edge:i,id:l}){try{let u=Hg(s);if(a(u))return u;let p=Qh(s,{userId:o.userId});if(a(p))return p;let m=_h(s,ru.basename(p.value)),f=l?d("Minted event id",l):n(s,i);if(a(f))return c(f.message);let[g,b]=f.value,E=Yd(Yh(o),[g,b]);if(a(E))return c(E.message);let R=`${JSON.stringify(E.value)}
47
- `;Fh(m,R),i&&(i.current=g);let w=ru.basename(m);return e.advanceEdgeRef(s,w,g,Buffer.byteLength(R)),Ch(s,w,Buffer.byteLength(R)),d("Event persisted",{path:m,entry:E.value})}catch(u){let p=u instanceof Error?u.message:"Unknown persist error";return c(`Failed to persist event: ${p}`)}}return{mintEventId:n,persist:r}}});var ey,ty=h(()=>{"use strict";C();kn();ey=(e,t,n)=>{function r(s,i,l){let u=n.mintEventId(i,l);if(a(u))return c(u.message);let p={...s,id:u.value[0]},m=t.materialize(p);if(m.status!==Un.Success)return m;let f=n.persist({event:p,rootDir:i,edge:l,id:u.value});return a(f)?(wh(),f):m}function o(s,i){if(s.length===0||!s[0])return c("No events provided");let l=e.write.readOnlyReason();if(l)return c(l);let u=e.replay.batch(()=>{let p={},m=e.write.beforeWrite(s[0],b=>r(b,i,p));if(a(m))return c(m.message);let f=s.map(b=>r(b,i,p)),g=f.filter(a);return g.length>0?c("Materialize and persist failed: "+g.map(b=>b.message).join(", ")):d("Materialization succeeded",f.map(b=>b.value))});return a(u)?c(u.message):u.value??c("Materialize and persist produced nothing")}return{materializeAndPersist:r,materializeAndPersistAll:o}}});var ny,ry=h(()=>{"use strict";nu();ac();cc();ty();ny=e=>{let t=zh(e),n=qh(e),r=Zh(n),o=ey(e,t,r);return{...t,...n,...r,...o}}});import{z as Z}from"zod";var J,bn,xr,lc,ou,mN,oy,sy=h(()=>{"use strict";C();J=Z.string().min(1),bn=Z.string(),xr=Z.string(),lc=Z.looseObject({id:J}),ou=Z.looseObject({id:J,name:bn,parent:J,rank:xr}),mN={"init.workspace":Z.looseObject({id:J,name:bn,rank:xr}),"add.workspace":Z.looseObject({id:J,name:bn,rank:xr}),"add.board":ou,"add.swimlane":ou,"add.issue":ou,"add.field":Z.looseObject({id:J,name:bn,parent:J,rank:xr}),"edit.title":Z.looseObject({id:J,name:bn}),"delete.node":lc,"lock.node":lc,"move.node":Z.looseObject({id:J,parent:J,rank:xr}),"edit.description":Z.looseObject({id:J,md:Z.string()}),"close.issue":Z.looseObject({id:J,parent:J,rank:xr}),"reopen.issue":Z.looseObject({id:J,parent:J,rank:xr}),"create.tag":Z.looseObject({id:J,name:bn}),"tombstone.tag":lc,"restore.tag":Z.looseObject({id:J,name:bn}),"create.contributor":Z.looseObject({id:J,name:bn}),"rename.contributor":Z.looseObject({id:J,name:bn}),"tombstone.contributor":lc,"restore.contributor":Z.looseObject({id:J,name:bn}),"link.contributor.user":Z.looseObject({contributor:J}),"link.contributor.email":Z.looseObject({contributor:J,email:J}),"unlink.contributor.email":Z.looseObject({contributor:J,email:J}),"connect.repo":Z.looseObject({url:Z.string()}),"edit.repo":Z.looseObject({repo:J}),"disconnect.repo":Z.looseObject({repo:J}),"add.issue.assignee":Z.looseObject({id:J,assignee:J}),"remove.issue.assignee":Z.looseObject({id:J,assignee:J}),"add.issue.tag":Z.looseObject({id:J,tag:J}),"remove.issue.tag":Z.looseObject({id:J,tag:J}),"add.issue.comment":Z.looseObject({id:J,issue:J,md:Z.string()}),"edit.issue.comment":Z.looseObject({id:J,issue:J,md:Z.string()}),"delete.issue.comment":Z.looseObject({id:J,issue:J}),"add.issue.attachment":Z.looseObject({id:J,issue:J,hash:Z.string().min(1),ext:Z.string().min(1),name:bn,bytes:Z.number()}),"delete.issue.attachment":Z.looseObject({id:J,issue:J}),"rebalance.children":Z.looseObject({parent:J,ranks:Z.record(Z.string(),xr)})},oy=(e,t)=>{let r=mN[e].safeParse(t);return r.success?d("Payload is readable",void 0):c(`${e}: ${r.error.issues.map(o=>`${o.path.join(".")||"payload"} ${o.message}`).join(", ")}`)}});import{ulid as pN}from"ulid";var iy,ay=h(()=>{"use strict";C();ge();Ue();iy=(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}=ce();if(!r||n!==e.userId)return d("Not this actor own write",void 0);let o=N.getContributor(e.userId),s={id:pN(),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)?c(i.message):d("Contributor name recorded",void 0)}});var su,ZF,en=h(()=>{"use strict";Zt();su=["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","connect.repo","edit.repo","disconnect.repo"],ZF=new Set(su)});var Me,Xo=h(()=>{"use strict";Me={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",DIFF:"Diff",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var Y,bi,rt=h(()=>{"use strict";Y=e=>e.slice(-7).toUpperCase(),bi=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?Y(e).includes(n):!0}});var We,Er=h(()=>{"use strict";pe();rt();We={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:me.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:Y(e)},context:me.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:me.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:me.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:me.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:Y(e)},context:me.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:me.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:me.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})}});var vi,iu,cy,ly=h(()=>{"use strict";pe();C();Xo();Bt();ge();Er();O();ac();yn();Hr();vi=(e,t,n)=>N.getNode(e)?U(`a node with id ${e} already exists`,n):t===e?U("a node cannot be its own parent",n):null,iu=e=>{let t=y().repos,n=Yl(t,e);if(a(n))return{skip:U(n.message,e)};let r=Oe(o=>({...o,repos:t}));return a(r)?{skip:U("Unable to update repos",e)}:{message:n.message,entry:n.value}},cy={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=We.workspace(t,n,r),s=Ri(o);if(a(s))return ic(s.message,e);let i=N.createNode(o);return a(i)?U(i.message??"Failed to initialize workspace",e):rd(i.value)?d("Workspace initialized",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=vi(t,void 0,e);if(o)return o;let s=N.createNode(We.workspace(t,n,r));return a(s)?U(s.message??"Failed to add workspace",e):rd(s.value)?d("Added workspace",{action:e.action,result:s.value}):c("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=vi(t,r,e);if(s)return s;let i=N.createNode(We.board(t,n,r,o));return a(i)?U(i.message??"Unable to create board",e):qr(i.value)?d("Added board",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=vi(t,r,e);if(s)return s;let i=N.createNode(We.swimlane(t,n,r,o));return a(i)?U(i.message??"Unable to create swimlane",e):Gr(i.value)?d("Added swimlane",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=vi(t,r,e);if(s)return s;let i=N.createNode(We.ticket(t,n,r,o));return a(i)?U(i.message??"Unable to create issue",e):W(i.value)?d("Added issue",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=vi(t,r,e);if(i)return i;let l=N.createNode(We.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(Me.DESCRIPTION)?"vertical":"horizontal"}));return a(l)?U(l.message??`Unable to create field: ${n}`,e):at(l.value)?d("Added field",{action:e.action,result:l.value}):c("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!N.getNode(t))return U(`Unable to locate node with id ${t}`,e);let o=N.renameNode(t,n);return a(o)?U(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=N.tombstoneNode(t);return a(n)?U(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=N.createTag({id:t,name:n});return a(r)?U(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=N.tombstoneTag(t);return a(n)?U(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=N.restoreTag(t,n);return a(r)?U(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=N.createContributor({id:t,name:n});return a(r)?U(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=N.renameContributor(t,n);return a(r)?U(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=N.tombstoneContributor(t);return a(n)?U(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=N.restoreContributor(t,n);return a(r)?U(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=N.tag(t,n);return a(r)?U(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=N.untag(t,n);return a(r)?U(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=N.assign(t,n);return a(r)?U(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=N.unassign(t,n);return a(r)?U(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=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?U(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=N.editValue(t,n);return a(r)?U(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=N.getNode(t);if(!o)return U("Unable to locate issue",e);if(!W(o))return U("Can only close issues",e);let s=N.getNode(Te);if(!s)return U("Unable to locate target swimlane",e);if(n!==s.id)return U("Close target must be closed swimlane",e);let i=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(i)?U(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=N.getNode(t);if(!o)return U("Unable to locate issue",e);if(!W(o))return U("Can only reopen issues",e);let s=N.getNode(Te);if(!s)return U("Unable to locate closed swimlane",e);if(n===s.id)return U("Cannot reopen issue into closed swimlane",e);if(!N.getNode(n))return U("Reopen parent no longer exists",e);let l=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(l)?U(l.message??"Unable to reopen issue",e):d("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=N.lockNode(t);return a(n)?U(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=N.getNode(r);if(!s)return U(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return U(`Node ${r} is not child of ${t}`,e);let i=N.updateNode({...s,rank:o});if(a(i))return U(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=N.createComment({id:t,issue:n,authorId:r,md:o,deleted:!1});return a(s)?U(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=N.getComment(t);if(!o)return U("Unable to locate comment",e);if(o.issue!==n)return U("Comment does not belong to issue",e);let s=N.editComment(t,r);return a(s)?U(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=N.getComment(t);if(!r)return U("Unable to locate comment",e);if(r.issue!==n)return U("Comment does not belong to issue",e);let o=N.deleteComment(t);return a(o)?U(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,l=N.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return a(l)?U(l.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=N.getAttachment(t);if(!r)return U("Unable to locate attachment",e);if(r.issue!==n)return U("Attachment does not belong to issue",e);let o=N.deleteAttachment(t);return a(o)?U(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(!ur(n))return U(`not an email address: ${n}`,e);let r=N.linkContributorEmail({email:n,contributor:t,authorId:e.userId});return a(r)?U(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=N.unlinkContributorEmail(n,t,e.userId);return a(r)?U(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=N.linkUserId({contributorId:t,userId:e.userId});return a(n)?U(n.message??"Unable to link contributor",e):d("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})},"connect.repo":e=>{let t=iu(e);return"skip"in t?t.skip:d(t.message,{action:e.action,result:t.entry})},"edit.repo":e=>{let t=iu(e);return"skip"in t?t.skip:d(t.message,{action:e.action,result:t.entry})},"disconnect.repo":e=>{let t=iu(e);return"skip"in t?t.skip:d(t.message,{action:e.action,result:t.entry})}}});var dy,uy,fN,gN,au,hN,Jn,yN,my,cu=h(()=>{"use strict";pe();C();ge();O();lu();dy=e=>{let t=N.getNode(e);if(!t||!W(t)||t.isDeleted)return null;let n=uc(t);return a(n)?n:null},uy=e=>{if(!mc())return null;for(let t of e){let n=dy(t);if(n)return n;let r=y().nodes[t]?.parentNodeId;if(!r)continue;let o=dy(r);if(o)return o}return null},fN=(e,t)=>{let n=N.getNode(e);n&&N.updateNode({...n,log:[...n.log??[],t]})},gN=e=>{let t=[e],n=y().nodes[e]?.parentNodeId;return n&&t.push(n),t},au=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 gN(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":case"connect.repo":case"edit.repo":case"disconnect.repo":default:return[]}},hN=e=>{Oe(t=>({...t,eventLog:[...t.eventLog,e]}))},Jn=null,yN=e=>{for(let[t,n]of e.nodeLog){let r=N.getNode(t);r&&N.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&Oe(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),uy([...e.virtualNodeIds])},my={isInitialized:()=>ut(),batch:e=>dc(e),afterApply(e,{batched:t,bypassLogging:n}){let r=[...new Set(au(e))];if(t){Jn??={appLog:[],nodeLog:new Map,virtualNodeIds:new Set};for(let o of r){if(!n){let s=Jn.nodeLog.get(o);s?s.push(e):Jn.nodeLog.set(o,[e])}if(mc()){Jn.virtualNodeIds.add(o);let s=y().nodes[o]?.parentNodeId;s&&Jn.virtualNodeIds.add(s)}}return n||Jn.appLog.push(e),null}return n||(r.forEach(o=>fN(o,e)),hN(e)),uy(r)},flush(){if(!Jn)return null;let e=Jn;return Jn=null,yN(e)}}});var be,py=h(()=>{"use strict";C();Ue();$r();be=()=>{let{userName:e,userId:t}=ce();return e?t?Ra(t)?Bs(e)?d("Successfully resolved actor ID",{userId:t,userName:e}):c("Invalid user name in config"):c("Invalid user ID in config"):c("User ID not configured"):c("User name not configured")}});var bN,vN,xi,Qn,VB,KB,vn,fy,io,Zn,du,YB,XB,JB,QB,uu,ZB,gy,e$,F,H=h(()=>{"use strict";fi();ry();sy();O();ay();en();ly();cu();py();fi();nu();ac();cc();bN={genesis:"init.workspace",actions:su,readPayload:oy,apply:cy,replay:my,write:{readOnlyReason:()=>{let e=y();return e.readOnly?e.readOnlyReason??"Cannot change the board while time travelling":null},beforeWrite:iy}},vN=ny(bN),{materialize:xi,materializeAll:Qn,fromPersistedEvent:VB,decodeReconstructedEvents:KB,loadMergedEventsWithUnreadable:vn,loadEventActors:fy,loadActorNames:io,loadMergedEvents:Zn,loadMergedEventsBefore:du,getEdgeRef:YB,advanceEdgeRef:XB,clearEdgeCache:JB,getSortedEvents:QB,loadEffectiveEventTimes:uu,mintEventId:ZB,persist:gy,materializeAndPersist:e$,materializeAndPersistAll:F}=vN});import{createHash as RN}from"node:crypto";import hy from"node:path";import xN from"node:fs";import{ulid as EN}from"ulid";var mu,pc,SN,Ei,IN,Ht,fc,yy,pu,Si,fu,gu,gc,hu,yu,by,Ln,Jo,hc,vy,Sr,er,Qo=h(()=>{"use strict";tt();kn();H();Hr();C();Yt();O();Po();ko();ko();Hr();mu="Unchanged",pc="Renamed ",SN={live:[],overLimit:[],disconnected:[]},Ei=null,IN=(e,t)=>{if(!ut())return null;let n=y();return n.timeMode==="live"&&n.replay===null&&Qa(e)===t?n.repos:null},Ht=e=>{try{let t=xe({repoRoot:e});if(a(t))return c(t.message);let n=t.value,r=kt(n);if(r==="none")return d("No log yet",SN);if(Ei&&Ei.root===n&&Ei.signature===r)return d("Read connected repos",Ei.repos);let o=IN(n,r);if(!o){let i=Zn(n);if(a(i))return c(i.message);o=Mf(i.value)}let s=kf(o);return Ei={root:n,signature:r,repos:s},d("Read connected repos",s)}catch(t){return c(`Could not read the connected repos: ${t instanceof Error?t.message:String(t)}`)}},fc=e=>{let t=Ht(e);return a(t)?c(t.message):d("Read other repos",t.value.live)},yy=(e,t)=>{let n=fc(e);return!a(n)&&n.value.some(r=>r.id===t)},pu=e=>{let t=e.url.trim(),n=$s(t);if(n)return c(`That URL ${n}. ${Cf}`);if(e.since!==void 0&&!jr(e.since))return c(`"${e.since}" is not a history window: use board, all or YYYY-MM-DD.`);let r=e.label?.trim();if(r&&!Ur(r))return c(`"${r}" is not a label: up to 24 of a-z, 0-9, dot, dash or underscore, opening on a letter or digit.`);let o=Ht(e.repoRoot);if(a(o))return c(o.message);let s=[...o.value.live,...o.value.overLimit],i=Gn(t),l=s.find(g=>g.id===i),u=r===void 0?void 0:r===Wn(l?.url??t)?"":r;if(u&&s.some(g=>g.id!==i&&g.label===u))return c(`Another repo is already called ${u}`);let p={...e.branches?{branches:e.branches}:{},...e.since?{since:e.since}:{},...u!==void 0?{label:u}:{}};if(!l){let g={id:i,url:t,branches:e.branches??Vl,since:e.since??Kl,label:u||Wn(t)};return d("Plan",{kind:"connect",repo:g,event:{url:t,...e.branches?{branches:e.branches}:{},...e.since?{since:e.since}:{},...u?{label:u}:{}}})}let m={...l,branches:e.branches??l.branches,since:e.since??l.since,label:u===void 0?l.label:u||Wn(l.url)};if(m.branches===l.branches&&m.since===l.since&&m.label===l.label)return d("Plan",{kind:"unchanged",repo:l});let f=m.branches===l.branches&&m.since===l.since;return d("Plan",{kind:"edit",repo:m,event:{repo:i,...p},message:`${f?pc:"Updated "}${m.label}`})},Si=e=>{let t=xe({repoRoot:e.repoRoot});if(a(t))return c(t.message);let n=F([{id:EN(),userId:e.actorId,...e.event}],t.value);return a(n)?c(n.message):d("Wrote repo event",null)},fu=e=>{let t=Ht(e);return new Map(a(t)?[]:[...t.value.live,...t.value.overLimit].map(n=>[n.id,n.label]))},gu=e=>e.map(t=>e.filter(n=>n.label===t.label).length===1?t.label:t.id),gc=(e,t)=>{let n=t.trim(),r=e.filter(s=>s.label===n);if(r.length>1)return c(`Several repos are called ${n} \u2014 name one by its id or URL`);let o=r[0]??e.find(s=>s.id===n||dr(n)&&s.id===Gn(n));return o?d("Found",o):c(`No repo "${n}" is connected`)},hu=(e,t)=>{let n=Ht(e);return a(n)?c(n.message):gc([...n.value.live,...n.value.overLimit],t)},yu=e=>hy.join(wt(),"repos",/^[\w-]+$/.test(e)?e:RN("sha1").update(e).digest("hex")),by=/^[a-z0-9._-]+-[0-9a-f]{12}\.git$/,Ln=(e,t)=>hy.join(yu(e),`${t}.git`),Jo=e=>`${e}.json`,hc=/^(?!-)[A-Za-z0-9._/-]{1,100}$/,vy=e=>{try{let t=JSON.parse(xN.readFileSync(Jo(e),"utf8"));return typeof t.stateBranch=="string"&&hc.test(t.stateBranch)?t.stateBranch:null}catch{return null}},Sr=(e,t)=>e==="all"?null:e==="board"?t.slice(0,10):e,er=e=>{let t=vt(e);return a(t)?c(t.message):d("Read project",{projectId:t.value.projectId,createdAt:t.value.createdAt})}});var Ry,xy=h(()=>{"use strict";rt();Ry=(e,t)=>{let n=(e.trim().split(/\s+/)[0]??"").toUpperCase();return n&&t.has(n)?n:null}});import{execFileSync as CN}from"node:child_process";import{randomUUID as Iy}from"node:crypto";import Wt from"node:fs";import Ci from"node:os";import wN from"node:path";var bu,NN,Cy,wy,Ny,AN,Ay,Ty,TN,Ey,MN,yc,kN,LN,PN,My,Ii,ON,_N,wi,Sy,Ni,bc=h(()=>{"use strict";C();De();yt();bu="epiq-sync.lock",NN=600*1e3,Cy=Date.now()-process.uptime()*1e3,wy=()=>Math.round(Cy),Ny=5e3,AN=5e3,Ay=e=>{try{if(process.platform==="linux"){let s=Wt.readFileSync(`/proc/${e}/stat`,"utf8"),i=s.slice(s.lastIndexOf(")")+2).split(" "),l=Number(i[19]),u=/^btime (\d+)$/m.exec(Wt.readFileSync("/proc/stat","utf8"))?.[1];return u&&Number.isFinite(l)?Number(u)*1e3+l*10:null}if(process.platform==="win32")return null;let t=Ey.get(e);if(t&&Date.now()-t.at<TN)return t.value;let n=CN("ps",["-o","lstart=","-p",String(e)],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"],env:{...process.env,LC_ALL:"C"}}).trim(),r=Date.parse(n),o=Number.isNaN(r)?null:r;return Ey.set(e,{at:Date.now(),value:o}),o}catch{return null}},Ty=(e,t)=>{let n=Ay(e);return n!==null&&n>t+Ny},TN=5e3,Ey=new Map,MN=e=>{let t=Date.now()-Ci.uptime()*1e3;if(e.startedAt<t)return!1;if(Date.now()-e.startedAt<AN||e.processStartedAt===void 0)return!0;let n=Ay(e.pid);return n===null||Math.abs(n-e.processStartedAt)<=Ny},yc=new Map,kN=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}},LN=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},PN=(e,t=NN,n=!1)=>e?e.hostname!==Ci.hostname()?Date.now()-e.startedAt>t?"stale":null:!LN(e.pid)||n&&!MN(e)?"dead":Date.now()-e.startedAt>t?"stale":null:"stale",My=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,Ii=e=>{try{return kN(Wt.readFileSync(e,"utf8"))}catch{return null}},ON=(e,t)=>{let n={pid:process.pid,hostname:Ci.hostname(),startedAt:Date.now(),operation:t,token:Iy(),processStartedAt:Cy},r=`${e}.${process.pid}.pending.lock`;try{return Wt.writeFileSync(r,JSON.stringify(n)),Wt.linkSync(r,e),n}catch{return null}finally{try{Wt.rmSync(r,{force:!0})}catch{}}},_N=async({worktreeRoot:e,operation:t})=>{let n=await Oa(e);return a(n)?c(n.message):d("Tried the sync lock",wi({lockPath:wN.join(n.value,bu),operation:t}))},wi=({lockPath:e,operation:t,staleAfterMs:n,checkProcess:r=!1})=>{let o=null,s=()=>{try{let u=Ii(e);u&&Sy(u,o)&&Wt.rmSync(e)}catch{}finally{yc.get(e)===o?.token&&yc.delete(e)}},i=u=>(o=ON(e,t),o?(yc.set(e,o.token),{acquired:!0,claim:u,release:s}):null);for(let u=0;u<5;u++){let p=i("clean");if(p)return p;let m=Ii(e);if(m===null&&(!Wt.existsSync(e)||(m=Ii(e),m!==null)||!Wt.existsSync(e)))continue;let g=m!==null&&m.pid===process.pid&&m.hostname===Ci.hostname()&&yc.get(e)!==m.token?"dead":PN(m,n,r);if(g===null)return{acquired:!1,heldBy:m};z.info(`Breaking an abandoned sync lock: ${m?My(m):"unreadable lock file"}`);let b=`${e}.${process.pid}.${Iy()}.broken.lock`;try{Wt.renameSync(e,b)}catch{continue}if(!Sy(Ii(b),m)){try{Wt.linkSync(b,e)}catch{}Wt.rmSync(b,{force:!0});continue}Wt.rmSync(b,{force:!0});let E=i(g);if(E)return E}return{acquired:!1,heldBy:Ii(e)??{pid:-1,hostname:Ci.hostname(),startedAt:Date.now(),operation:"unknown"}}},Sy=(e,t)=>e===null||t===null?e===t:e.pid===t.pid&&e.hostname===t.hostname&&e.startedAt===t.startedAt&&e.token===t.token,Ni=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await _N({worktreeRoot:e,operation:t});if(a(r))return c(r.message);if(!r.value.acquired)return z.info(`Skipping ${t}: the state worktree is held by ${My(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()}}});var DN,vc,vu=h(()=>{"use strict";DN="EPIQ_CACHE_MS",vc=e=>{let t=process.env[DN];if(t===void 0||t.trim()==="")return e;let n=Number(t);return Number.isFinite(n)&&n>=0?n:e}});import ky from"node:fs";import FN from"node:path";var Ly,Ru,xu,Py,BN,co,Rc,$N,xc,lo=h(()=>{"use strict";De();C();Yt();Vo();Qo();Ly=new Set,Ru=new Map,xu=(e,t)=>{t?Ru.set(e,t):Ru.delete(e)},Py=e=>Ru.get(e)??null,BN=e=>{try{return new Set(ky.readFileSync(FN.join(e,"shallow"),"utf8").split(`
48
- `).map(t=>t.trim()).filter(Boolean))}catch{return Ly}},co=async e=>{let t=Mt(e);if(a(t))return c(t.message);let n=t.value,r=vt(n);if(a(r))return c(r.message);let o={cwd:n,revisions:["--branches","--not",r.value.stateBranch],exclude:Ly},s=fc(n);if(a(s))return d("Listed sources",[o]);let i=s.value.flatMap(l=>{let u=Ln(r.value.projectId,l.id);if(!ky.existsSync(u))return[];let p=Sr(l.since,r.value.createdAt),m=new Set([r.value.stateBranch,Id,vy(u)].filter(f=>f!==null));return[{repo:l.id,cwd:u,revisions:[...[...m].map(f=>`--exclude=${f}`),"--branches"],exclude:BN(u),...p?{notBefore:Date.parse(`${p}T00:00:00Z`)}:{}}]});return d("Listed sources",[o,...i])},Rc=e=>t=>e.find(n=>(n.repo??"")===(t??""))?.cwd,$N=async(e,t)=>!a(await G({cwd:e,args:["cat-file","-e",`${t}^{commit}`]})),xc=async e=>{let t=await co(e.repoRoot);if(a(t))return c(t.message);let n=t.value;if(e.repo){let r=n.find(o=>o.repo===e.repo);return r?d("Resolved repo",r.cwd):c(`No clone of repo "${e.repo}" here yet \u2014 sync to fetch it`)}if(n.length===1)return d("Resolved repo",n[0].cwd);for(let r of n)if(await $N(r.cwd,e.sha))return d("Resolved repo",r.cwd);return d("Resolved repo",n[0].cwd)}});import{randomBytes as jN}from"node:crypto";import UN from"node:fs";var HN,WN,Oy,GN,qN,Ec,zN,VN,KN,Ir,YN,Eu,XN,JN,_y,QN,Dy,Ai,Ti=h(()=>{"use strict";De();yt();C();vu();rt();ct();lo();HN="",WN="",Oy=5e3,GN=12e4,qN=32*1024*1024,Ec=new Map,zN=e=>{try{return UN.statSync(`${e}.json`).mtimeMs}catch{return null}},VN=e=>{let t=e.repo?jN(8).toString("hex"):"";return{field:`${HN}${t}`,record:`${WN}${t}`}},KN=/^[0-9a-f]{40}([0-9a-f]{24})?$/,Ir=()=>{Ec.clear()},YN=(e,t,n)=>(t===void 0||e>=Math.floor(t/1e3)*1e3)&&(n===void 0||e<=n),Eu=e=>ye(e).replace(/[\u0080-\u009f\u202a-\u202e\u2066-\u2069]/g,""),XN=async(e,t)=>{let n=t.start===void 0&&t.end===void 0,r=[e.cwd,e.revisions.join(" "),e.notBefore??"",e.exclude.size].join("\0"),o=n?Ec.get(r):void 0,s=e.repo?zN(e.cwd):null;if(o&&(e.repo?o.version===s:Date.now()-o.fetchedAt<vc(Oy)))return o.result;let i=VN(e),l=await G({cwd:e.cwd,...e.repo?{timeoutMs:GN,maxOutput:qN}:{},args:["log",...e.revisions,...t.start!==void 0?[`--since=@${Math.floor(t.start/1e3)}`]:[],...t.end!==void 0?[`--until=@${Math.floor(t.end/1e3)}`]:[],"--shortstat",`--format=${i.record}%H${i.field}%at${e.notBefore?`${i.field}%ct`:""}${i.field}%an${i.field}%ae${i.field}%s`]});if(a(l))return e.repo&&n&&!cg(l.message)&&Ec.set(r,{fetchedAt:Date.now(),version:s,result:c(l.message)}),c(l.message);let u=l.value.stdout.split(i.record).filter(p=>p.trim().length>0).map(p=>{let[m,...f]=p.split(`
49
- `),g=(m??"").split(i.field),[b,E]=g;if(e.repo&&!KN.test(b??""))return null;let R=e.notBefore?g[2]:void 0,[w,S,...A]=g.slice(e.notBefore?3:2);if(!b||!E||e.exclude.has(b)||e.notBefore&&Number(R)*1e3<e.notBefore)return null;let L=f.join(" "),P=Number(/(\d+) insertion/.exec(L)?.[1]??0),B=Number(/(\d+) deletion/.exec(L)?.[1]??0);return{sha:b,...e.repo?{repo:e.repo}:{},time:Number(E)*1e3,author:Eu(w)||"unknown",authorEmail:Eu(S),subject:Eu(A.join(i.field)),linesChanged:P+B,insertions:P,deletions:B}}).filter(p=>p!==null).filter(p=>YN(p.time,t.start,t.end));return n&&Ec.set(r,{fetchedAt:Date.now(),version:s,result:d("Computed commit timeline",u)}),d("Computed commit timeline",u)},JN=async(e,t)=>{let n=await co(e);if(a(n))return c(n.message);let r=n.value,o=[];for(let i of r)o.push(await XN(i,t));let s=[];for(let[i,l]of o.entries()){let u=r[i].repo;if(a(l)){if(!u)return c(l.message);z.info(`[repos] could not read a clone: ${l.message}`),xu(u,Pa(l.message)?"its history is too long to read; narrow its window":"its history could not be read");continue}u&&xu(u,null),s.push(l.value)}return d("Read every source",s)},_y=e=>{if(e.length<=1)return e;let t=new Set;return e.map(n=>{let r=n.filter(o=>!t.has(o.sha));for(let o of r)t.add(o.sha);return r})},QN=e=>{let t=e.filter(n=>n.length>0);return t.length<=1?t[0]??[]:t.flat().sort((n,r)=>r.time-n.time)},Dy=async e=>{let t=e.ref.trim();if(!t)return c("ref must not be empty");if(t.length!==7)return c(`"${t}" is ${t.length} characters; a ref is ${7}. Read it off the issue rather than slicing the id by hand.`);let n=await JN(e.repoRoot,{});if(a(n))return c(n.message);let r=`${t.toUpperCase()} `,o=s=>s.subject.toUpperCase().startsWith(r);return d("Matched commits by ref",n.value.map(s=>{let i=[];for(let[l,u]of s.entries()){if(!o(u))continue;let p=s[l+1];i.push({...u,precedingSha:p&&o(p)?p.sha:null})}return i}))},Ai=async e=>{let t=await Dy(e);return a(t)?c(t.message):d("Matched commits by ref",QN(_y(t.value)))}});import{randomUUID as Pi}from"node:crypto";import j from"node:fs";import se from"node:path";var Sc,On,Fy,wu,Cu,Gy,Oi,Ge,ZN,eA,Li,Mi,Nu,tA,qy,By,nA,rA,zy,oA,Vy,sA,Ky,Au,iA,aA,Yy,Xy,Jy,cA,Qy,$y,lA,Zy,eb,tb,nb,dA,uA,mA,pA,fA,jy,Su,uo,Uy,gA,rb,Ic,Gt,Tu,Mu,ob,ki,sb,hA,Hy,ib,yA,bA,vA,RA,ab,xA,cb,EA,lb,Pn,db,_i,ku,ub,SA,IA,CA,Wy,Zo,Iu,wA,Di,Cc=h(()=>{"use strict";De();bc();yt();C();Ti();lo();Ja();Qo();Sc=1800*1e3,On=e=>`${e}.removed`,Fy=e=>{try{j.writeFileSync(On(e),"",{flag:"wx"})}catch(t){if(t.code!=="EEXIST")throw t;if(Ic(On(e)))throw new Error("The removal mark is a link, which epiq will not use")}},wu=()=>`${process.pid}-${wy()}`,Cu=e=>{try{let t=JSON.parse(j.readFileSync(Jo(e),"utf8"));return{fetchedAt:typeof t.fetchedAt=="number"?t.fetchedAt:null,attemptedAt:typeof t.attemptedAt=="number"?t.attemptedAt:null,error:typeof t.error=="string"?t.error:null,branches:t.branches==="all"||t.branches==="default"?t.branches:null,since:typeof t.since=="string"?t.since:null,restartedAt:typeof t.restartedAt=="number"?t.restartedAt:null,restartTriedAt:typeof t.restartTriedAt=="number"?t.restartTriedAt:null,restarts:typeof t.restarts=="number"&&t.restarts>=0?t.restarts:0,bytes:typeof t.bytes=="number"&&t.bytes>=0?t.bytes:null,stateBranch:typeof t.stateBranch=="string"&&hc.test(t.stateBranch)?t.stateBranch:null}}catch{return null}},Gy=(e,t)=>{try{let n=`${Jo(e)}.${wu()}.${Pi()}.tmp`;j.writeFileSync(n,JSON.stringify(t)+`
50
- `,{flag:"wx"}),j.renameSync(n,Jo(e))}catch(n){z.info(`[repos] could not record fetch status: ${String(n)}`)}},Oi=e=>{let t=er(e);if(a(t))return c(t.message);let n=Ht(e);if(a(n))return c(n.message);let r=(o,s)=>{let i=Ln(t.value.projectId,o.id),l=Cu(i),u=j.existsSync(i);return{...o,cloned:u,overLimit:s,bytes:u?l?.bytes??null:null,fetchedAt:l?.fetchedAt??null,error:l?.error??Py(o.id)}};return d("Listed repos",[...n.value.live.map(o=>r(o,!1)),...n.value.overLimit.map(o=>r(o,!0))])},Ge=e=>G({...e,forClone:!0}),ZN=(e,t)=>Ge({cwd:e,args:t,timeoutMs:Sc}),eA=1e3,Li=async(e,t,n,{undo:r}={})=>{let o=zo(),s=o*1024*1024,i=new AbortController,l=setInterval(()=>{hr(n)>s&&i.abort(ui(o))},eA),u;try{u=await Ge({cwd:e,args:t,timeoutMs:Sc,abort:i.signal})}finally{clearInterval(l)}return i.signal.aborted||!a(u)&&hr(n)>s?(zy(n),r&&(rA(n,r),tb(n)),c(ui(o))):u},Mi=e=>{try{return j.readFileSync(e)}catch{return null}},Nu=e=>{try{return j.readdirSync(e)}catch{return[]}},tA=e=>{let t=new Map,n=r=>{let o=se.join(e,r);for(let s of j.readdirSync(o,{withFileTypes:!0})){let i=se.join(r,s.name);s.isDirectory()?n(i):t.set(i,j.readFileSync(se.join(e,i)))}};return j.existsSync(se.join(e,"refs"))&&n("refs"),{refs:t,packedRefs:Mi(se.join(e,"packed-refs")),head:Mi(se.join(e,"HEAD")),config:Mi(se.join(e,"config")),shallow:Mi(se.join(e,"shallow")),packs:new Set(Nu(se.join(e,"objects","pack")))}},qy="epiq-restore-",By=(e,t,n)=>{let r=se.join(e,`${qy}${Pi()}.tmp`);j.writeFileSync(r,n,{flag:"wx"}),j.mkdirSync(se.dirname(se.join(e,t)),{recursive:!0}),j.renameSync(r,se.join(e,t))},nA=e=>{let t=[],n=r=>{for(let o of j.readdirSync(se.join(e,r),{withFileTypes:!0})){let s=se.join(r,o.name);o.isDirectory()?n(s):t.push(s)}};return j.existsSync(se.join(e,"refs"))&&n("refs"),t},rA=(e,t)=>{for(let[r,o]of t.refs)By(e,r,o);for(let r of nA(e))t.refs.has(r)||j.rmSync(se.join(e,r),{force:!0});for(let[r,o]of[["packed-refs",t.packedRefs],["HEAD",t.head],["config",t.config],["shallow",t.shallow]])o?By(e,r,o):j.rmSync(se.join(e,r),{force:!0});let n=se.join(e,"objects","pack");for(let r of Nu(n))t.packs.has(r)||j.rmSync(se.join(n,r));uo.delete(e)},zy=e=>{let t=se.join(e,"objects");for(let[n,r]of[[se.join(t,"pack"),"tmp_"],[se.join(t,"pack"),".tmp-"],[t,"incoming-"],[e,qy]])try{for(let o of j.readdirSync(n))o.startsWith(r)&&j.rmSync(se.join(n,o),{recursive:!0,force:!0})}catch{}},oA=/could not read from remote repository|the remote end hung up unexpectedly|early EOF|fetch-pack: invalid index-pack output/i,Vy=e=>{let t=e.split(`
51
- `).map(s=>s.replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g,"").trim()).filter(s=>s&&!s.startsWith("git ")),n=t.filter(s=>/^(fatal|error):/i.test(s));return(n.filter(s=>!oA.test(s))[0]??n[n.length-1]??t[t.length-1]??e).replace(/^(fatal|error):\s*/i,"").slice(0,300)},sA=64*1024,Ky=async e=>{let t="HEAD:.epiq/project.json",n=await Ge({cwd:e,args:["cat-file","-s",t]});if(a(n)||!(Number(n.value.stdout.trim())<=sA))return null;let r=await Ge({cwd:e,args:["cat-file","blob",t]});if(a(r))return null;try{let{stateBranch:o}=JSON.parse(r.value.stdout);return typeof o=="string"&&hc.test(o)?o:null}catch{return null}},Au=async e=>{let t=await Ge({cwd:e,args:["symbolic-ref","--short","HEAD"]});return a(t)?null:t.value.stdout.trim()||null},iA=async(e,t)=>{if(t==="all")return d("All branches","+refs/heads/*:refs/heads/*");let n=await Au(e);return n?d("Default branch",`+refs/heads/${n}:refs/heads/${n}`):c("Could not tell which branch is the default")},aA=async e=>{let t=await Au(e);if(!t)return;let n=await Ge({cwd:e,args:["for-each-ref","--format=%(refname)","refs/heads/"]});if(!a(n))for(let r of n.value.stdout.split(`
52
- `).filter(Boolean))r!==`refs/heads/${t}`&&await Ge({cwd:e,args:["update-ref","-d",r]})},Yy=async e=>{let t=await Ge({cwd:e,args:["for-each-ref","--count=1","--format=x","refs/heads/"]});return!a(t)&&t.value.stdout.trim()!==""},Xy=e=>`--shallow-since=@${Math.floor(Date.parse(`${e}T00:00:00Z`)/1e3)}`,Jy=async(e,t)=>{if(!await Yy(e))return d("Empty",null);let n=await Li(e,["fetch","--no-tags","--deepen=1","origin"],e,{undo:t});return a(n)?c(n.message):d("Deepened",null)},cA=/no commits selected for shallow requests|error processing shallow info/i,Qy=async(e,t,n)=>{let r=se.dirname(e);j.mkdirSync(r,{recursive:!0}),j.rmSync(e,{recursive:!0,force:!0});let o=u=>["clone","--bare","--no-tags",t.branches==="default"?"--single-branch":"--no-single-branch",...u,"--",t.url,e],s=await Li(r,o(n?[Xy(n)]:[]),e),i=n!==null;if(a(s)&&n&&cA.test(s.message)&&(j.rmSync(e,{recursive:!0,force:!0}),s=await Li(r,o(["--depth=1"]),e),i=!1),a(s))return j.rmSync(e,{recursive:!0,force:!0}),c(s.message);let l=await iA(e,t.branches);if(a(l))return j.rmSync(e,{recursive:!0,force:!0}),c(l.message);if(await Ge({cwd:e,args:["config","remote.origin.fetch",l.value]}),i){let u=await Jy(e);if(a(u))return j.rmSync(e,{recursive:!0,force:!0}),c(u.message)}return d("Built clone",null)},$y=async(e,t,n,{replace:r=!1}={})=>{let o=`${e}.${wu()}.pending`,s=await Qy(o,t,n);if(a(s))return s;if(r&&j.existsSync(e)){let i=`${e}.${Pi()}.deleting`;j.renameSync(e,i),j.renameSync(o,e);try{j.rmSync(i,{recursive:!0,force:!0})}catch(l){z.info(`[repos] could not clear an old clone: ${Gt(l)}`)}return d("Cloned anew",null)}return j.existsSync(e)?(j.rmSync(o,{recursive:!0,force:!0}),d("Cloned elsewhere",null)):Ic(e)?(j.rmSync(o,{recursive:!0,force:!0}),c("The clone path is a link, which epiq will not use")):(j.renameSync(o,e),d("Cloned",null))},lA=async(e,t)=>!/[*:]/.test(t)&&!a(await Ge({cwd:e,args:["check-ref-format",`refs/heads/${t}`]})),Zy=async e=>{let t=await ZN(e,["ls-remote","--symref","origin","HEAD"]);if(a(t))return null;let n=/^ref: refs\/heads\/(\S+)\tHEAD$/m.exec(t.value.stdout)?.[1],r=/^[0-9a-f]{40,64}\tHEAD$/m.test(t.value.stdout);return n&&r&&await lA(e,n)?n:null},eb=async(e,t)=>{let n=t??await Zy(e);if(!n)return c("Could not tell which branch the remote now defaults to");let r=await Ge({cwd:e,args:["symbolic-ref","HEAD",`refs/heads/${n}`]});if(a(r))return c(r.message);let o=await Ge({cwd:e,args:["config","remote.origin.fetch",`+refs/heads/${n}:refs/heads/${n}`]});return a(o)?c(o.message):d("Followed",null)},tb=e=>{let t=(n,r)=>{for(let o of j.readdirSync(n,{withFileTypes:!0})){let s=se.join(n,o.name);o.isFile()&&o.name.endsWith(".lock")?j.rmSync(s,{force:!0}):o.isDirectory()&&r>0&&t(s,r-1)}};try{for(let r of j.readdirSync(e))r.endsWith(".lock")&&j.rmSync(se.join(e,r),{force:!0});let n=se.join(e,"refs");j.existsSync(n)&&t(n,16)}catch(n){z.info(`[repos] could not clear stale locks: ${String(n)}`)}},nb=e=>j.existsSync(se.join(e,"shallow")),dA=20,uA=async e=>{if(Nu(se.join(e,"objects","pack")).filter(r=>r.endsWith(".pack")).length<=dA)return;let n=await Ge({cwd:e,args:["repack","--geometric=2","-d","-q"],timeoutMs:Sc});a(n)&&z.info(`[repos] repack: ${n.message}`)},mA=async e=>{let t=await Ge({cwd:e,args:["config","--get","remote.origin.fetch"]});return a(t)?null:t.value.stdout.trim()||null},pA=e=>`+refs/heads/${e}:refs/heads/${e}`,fA=async(e,t)=>{let n=await mA(e);if(t==="all"){let s="+refs/heads/*:refs/heads/*";if(n===s)return d("Tracking",null);let i=await Ge({cwd:e,args:["config","remote.origin.fetch",s]});return a(i)?c(i.message):d("Tracking",null)}let r=await Au(e),o=await Zy(e)??r;return o?r===o&&n===pA(o)?d("Tracking",null):eb(e,o):c("Could not tell which branch is the default")},jy=async(e,t,n,r)=>{let o=zo();if(hr(e)>o*1024*1024)return c(ui(o));let s=tA(e),i=await fA(e,t.branches);if(a(i))return c(i.message);let l=n===null?nb(e)?["--unshallow"]:[]:r?.since&&n<r.since?[Xy(n)]:[],u=["fetch","--prune","--no-tags",...l,"origin"],p=await Li(e,u,e,{undo:s});if(a(p)&&t.branches==="default"&&/couldn't find remote ref/i.test(p.message)){let m=await eb(e);if(a(m))return c(m.message);p=await Li(e,u,e,{undo:s})}if(a(p))return c(p.message);if(l[0]?.startsWith("--shallow-since")){let m=await Jy(e,s);if(a(m))return c(m.message)}return t.branches==="default"&&await aA(e),await uA(e),d("Fetched",null)},Su=async e=>{if(!j.existsSync(e))return"";let t=await Ge({cwd:e,args:["for-each-ref","--format=%(objectname) %(refname)"]}),n=nb(e)?j.readFileSync(se.join(e,"shallow"),"utf8"):"";return`${a(t)?"":t.value.stdout}
53
- ${n}`},uo=new Map,Uy=(e,t)=>{let n=uo.get(e);return uo.set(e,t),n!==void 0&&n!==t},gA=async(e,t)=>{let n=await Ge({cwd:e,args:["config","--get","remote.origin.url"]});return a(n)?"unknown":Gn(n.value.stdout.trim())===t.id?"this":"other"},rb=e=>{let t=se.join(e,".gitignore");try{if(j.lstatSync(t,{throwIfNoEntry:!1}))return;j.writeFileSync(t,`*
54
- `,{flag:"wx"})}catch(n){z.info(`[repos] could not write ${t}: ${Gt(n)}`)}},Ic=e=>{try{return j.lstatSync(e).isSymbolicLink()}catch{return!1}},Gt=e=>e instanceof Error?e.message:String(e),Tu=".lock",Mu=Sc*4,ob=async(e,t,n)=>{let r=Date.now()+n;for(;;){let o=wi({lockPath:`${e}${Tu}`,operation:t,staleAfterMs:Mu,checkProcess:!0});if(o.acquired||Date.now()>=r)return o;await new Promise(s=>setTimeout(s,250))}},ki=e=>{let t=`${e}.${Pi()}.deleting`;try{j.renameSync(e,t)}catch(n){if(n.code!=="ENOENT")throw n}j.rmSync(t,{recursive:!0,force:!0}),j.rmSync(Jo(e),{force:!0}),j.rmSync(On(e),{force:!0}),uo.delete(e)},sb=5e3,hA=async e=>{let t=await Ge({cwd:e,args:["config","--get","remote.origin.url"]});if(a(t)||!t.value.stdout.trim())return!1;let n=Mi(se.join(e,"shallow"));return n&&!/^(?:[0-9a-f]{40}(?:[0-9a-f]{24})?\n)*$/.test(n.toString("utf8"))?!1:await Yy(e)?!a(await Ge({cwd:e,args:["rev-list","--max-count=1","--branches"]})):!0},Hy=[0,6e4,10*6e4,60*6e4],ib=e=>{if(!e?.restartTriedAt||Date.now()<e.restartTriedAt)return!0;let t=Hy[Math.min(e.restarts,Hy.length-1)];return Date.now()-e.restartTriedAt>=t},yA=360*60*1e3,bA=e=>{let t=e?.restartTriedAt??e?.restartedAt;return ib(e)&&(!t||Date.now()<t||Date.now()-t>=yA)},vA=6e4,RA=async(e,t,n)=>{let r=zo();return hr(e)>r*1024*1024?"past the cap":n.endsWith(ui(r))?null:await ab(e,t)?"remote answers":null},ab=async(e,t)=>!a(await Ge({cwd:se.dirname(e),args:["ls-remote","--",t.url,"HEAD"],timeoutMs:vA})),xA=async(e,t,n,r,o)=>{let s=(m,f,g=!1)=>({id:r.id,label:r.label,ok:m,changed:g,message:f}),i=Ln(t,r.id),l=Sr(r.since,n);try{j.mkdirSync(se.dirname(i),{recursive:!0}),rb(se.dirname(i))}catch(m){return s(!1,Gt(m))}let u=Cu(i);if(u?.attemptedAt&&(u.error!==null||u.branches===r.branches&&u.since===l)&&Date.now()>=u.attemptedAt&&Date.now()-u.attemptedAt<o&&!j.existsSync(On(i))){let m=j.existsSync(i)&&Uy(i,await Su(i));return u.error?s(!1,u.error,m):s(!0,"Fetched recently",m)}if(Ic(i))return s(!1,"The clone path is a link, which epiq will not use");let p=await ob(i,`fetch ${r.label}`,o===0?sb:0);if(!p.acquired)return{...s(!0,"Being fetched by another process"),skipped:!0};try{let m=j.existsSync(On(i));m&&ki(i);let f=j.existsSync(i);f&&await gA(i,r)==="other"&&(ki(i),f=!1);let g=f?Cu(i):null;if(f&&!uo.has(i)&&uo.set(i,await Su(i)),f&&(tb(i),zy(i)),!f&&m&&!yy(e,r.id))return s(!0,"Removed before it was cloned");let E=f&&!await hA(i)&&ib(g),R=E&&await ab(i,r),w=f?E?c(R?"Its clone will not open":"Its clone will not open, and its remote does not answer"):await jy(i,r,l,g):await $y(i,r,l);if(f&&!R&&a(w)&&bA(g)){let P=await RA(i,r,w.message);P==="remote answers"&&(w=await jy(i,r,l,g)),R=P!==null&&a(w)}R&&(z.info(`[repos] ${r.label}: starting its clone over`),w=await $y(i,r,l,{replace:!0}),uo.delete(i));let S=R&&!(a(w)&&yg()),A=a(w)?Vy(w.message):"Fetched",L=a(w)?g?.stateBranch??null:await Ky(i);return Gy(i,{fetchedAt:a(w)?g?.fetchedAt??null:Date.now(),attemptedAt:Date.now(),error:a(w)?A:null,branches:a(w)?g?.branches??r.branches:r.branches,since:a(w)?g?.since??l:l,stateBranch:L,restartedAt:R&&!a(w)?Date.now():g?.restartedAt??null,restartTriedAt:S?Date.now():g?.restartTriedAt??null,restarts:S?(g?.restarts??0)+1:a(w)?g?.restarts??0:0,bytes:a(w)?g?.bytes??null:hr(i)}),a(w)?(z.info(`[repos] ${r.label}: ${w.message}`),s(!1,A)):s(!0,A,Uy(i,await Su(i))||!f||R)}catch(m){return z.info(`[repos] ${r.label}: ${Gt(m)}`),s(!1,Gt(m))}finally{try{j.existsSync(On(i))&&ki(i)}catch(m){z.info(`[repos] ${r.label}: could not delete the clone: ${Gt(m)}`)}p.release(),cb(i)}},cb=e=>{if(!j.existsSync(On(e)))return;let t=wi({lockPath:`${e}${Tu}`,operation:"remove",staleAfterMs:Mu,checkProcess:!0});if(t.acquired)try{j.existsSync(On(e))&&ki(e)}catch(n){z.info(`[repos] could not delete a clone: ${Gt(n)}`)}finally{t.release()}},EA=e=>{let t=yu(e);if(j.existsSync(t))for(let n of j.readdirSync(t)){let r=/^.+\.git(?:\.json)?\.(\d+)(?:-(\d+))?(?:\.[0-9a-f-]{36})?\.(?:pending|tmp)$/.exec(n);if(r&&!IA(Number(r[1]),r[2]===void 0?null:Number(r[2]))||/\.git\.[0-9a-f-]{36}\.deleting$/.test(n))try{j.rmSync(se.join(t,n),{recursive:!0,force:!0})}catch(o){z.info(`[repos] could not sweep ${n}: ${Gt(o)}`)}}},lb=async(e,t)=>{let n=er(e);if(a(n))return c(n.message);let r=Ln(n.value.projectId,t.id),o=`${r}.${wu()}.${Pi()}.pending`;try{j.mkdirSync(se.dirname(r),{recursive:!0}),rb(se.dirname(r));let s=await Qy(o,t,Sr(t.since,n.value.createdAt));return a(s)?c(Vy(s.message)):d("Staged",{stagePath:o,bytes:hr(o)})}catch(s){return Pn(o),c(Gt(s))}},Pn=e=>{try{j.rmSync(e,{recursive:!0,force:!0})}catch(t){z.info(`[repos] could not clear a stage: ${Gt(t)}`)}},db=async(e,t,n)=>{let r=er(e);if(a(r))return Pn(n);let{projectId:o,createdAt:s}=r.value,i=Ln(o,t.id),l=await ob(i,`connect ${t.label}`,sb);if(!l.acquired)return Pn(n);try{if(j.rmSync(On(i),{force:!0}),j.existsSync(i)||Ic(i))return Pn(n);j.renameSync(n,i),Gy(i,{fetchedAt:Date.now(),attemptedAt:Date.now(),error:null,branches:t.branches,since:Sr(t.since,s),stateBranch:await Ky(i),restartedAt:null,restartTriedAt:null,restarts:0,bytes:hr(i)}),Ir()}catch(u){z.info(`[repos] could not place ${t.label}: ${Gt(u)}`),Pn(n)}finally{l.release()}},_i=e=>{let t=hu(e.repoRoot,e.repo);if(a(t))return t;let n=Si({repoRoot:e.repoRoot,actorId:e.actorId,event:{action:"disconnect.repo",payload:{repo:t.value.id}}});if(a(n))return c(n.message);let r=ku({repoRoot:e.repoRoot,repoId:t.value.id});Ir();let o=er(e.repoRoot);!a(r)&&!a(o)&&ub(o.value.projectId,t.value.id);let s=`Disconnected ${t.value.label}`;return a(r)?d(`${s}, but its clone stays: ${r.message}`,t.value):d(s,t.value)},ku=e=>{let t=er(e.repoRoot);if(a(t))return c(t.message);if(!by.test(`${e.repoId}.git`))return c("Not a clone epiq made");let n=Ln(t.value.projectId,e.repoId);try{j.mkdirSync(se.dirname(n),{recursive:!0})}catch(o){return c(`Could not remove the clone: ${Gt(o)}`)}let r=wi({lockPath:`${n}${Tu}`,operation:"remove",staleAfterMs:Mu,checkProcess:!0});try{return r.acquired?(ki(n),Fy(n),d("Removed clone",null)):(Fy(n),cb(n),d("Removed once its fetch ends",null))}catch(o){return c(`Could not remove the clone: ${String(o)}`)}finally{r.acquired&&r.release()}},ub=(e,t)=>{let n=Ln(e,t);j.existsSync(n)||j.rmSync(On(n),{force:!0})},SA=(e,t,n)=>{for(let r of n){if(!j.existsSync(Ln(t,r)))continue;let o=ku({repoRoot:e,repoId:r});if(a(o)){z.info(`[repos] could not clear ${r}: ${o.message}`);continue}Ir(),ub(t,r)}},IA=(e,t)=>CA(e)&&(t===null||!Ty(e,t)),CA=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Wy=4,Zo=e=>{let t=e.minIntervalMs??0,n=Iu.get(e.repoRoot);if(n)return n.minIntervalMs<=t?n.result:n.result.then(()=>Zo(e));let r=wA(e.repoRoot,t).catch(o=>c(Gt(o))).finally(()=>{Iu.delete(e.repoRoot)});return Iu.set(e.repoRoot,{result:r,minIntervalMs:t}),r},Iu=new Map,wA=async(e,t)=>{let n=er(e);if(a(n))return c(n.message);let r=Ht(e);if(a(r))return c(r.message);let{projectId:o,createdAt:s}=n.value,i=r.value.live;try{EA(o)}catch(u){z.info(`[repos] sweep failed: ${String(u)}`)}if(SA(e,o,r.value.disconnected),i.length===0)return d("No other repos",[]);let l=[];for(let u=0;u<i.length;u+=Wy)l.push(...await Promise.all(i.slice(u,u+Wy).map(p=>xA(e,o,s,p,t))));return l.some(u=>u.changed)&&Ir(),d("Fetched other repos",l)},Di=e=>{let t=e.filter(o=>!o.ok),n=e.filter(o=>o.skipped),r=[t.length>0&&`could not fetch ${t.map(o=>`${o.label} (${o.message.slice(0,80)})`).join(", ")}`,n.length>0&&`another process is fetching ${n.map(o=>o.label).join(", ")}`].filter(Boolean);return r.length>0?r.join("; "):null}});var Pu,es,mb,Ou,NA,AA,pb,fb,Lu,TA,MA,wc,Fi,gb=h(()=>{"use strict";De();C();pe();O();xy();rt();Cc();Qo();Ti();Pu=900*1e3,es=new Map,mb=0,Ou=new Map,NA=e=>{let t=(Ou.get(e)??0)+1;return Ou.set(e,t),t},AA=(e,t)=>JSON.stringify([e,t.id,t.branches,t.since]),pb=e=>{let t=es.get(e);t&&(clearTimeout(t.timer),es.delete(e),Pn(t.stagePath))},fb=e=>{if(e.startsWith("file:"))return"this machine";let t=/^[^@/]+@([^:/]+):/.exec(e);if(t?.[1])return t[1];try{return new URL(e).host||e}catch{return e}},Lu=async(e,t)=>{let n=await G({cwd:e,args:t,forClone:!0,keepPartial:!0});return a(n)?null:n.value.stdout},TA=async(e,t,n)=>{let r=(await Lu(e,["symbolic-ref","--short","HEAD"]))?.trim().replace(/^refs\/heads\//,""),o=await Lu(e,["log","-1","--format=%s%x00%an%x00%cI","HEAD"]),[s,i,l]=(o??"").trim().split("\0"),p=(await Lu(e,["log","--branches","--max-count=100000",...t?[`--since=@${Math.floor(Date.parse(`${t}T00:00:00Z`)/1e3)}`]:[],"--format=%s"])??"").split(`
55
- `).filter(Boolean);return{defaultBranch:r||null,latest:s!==void 0&&s!==""&&i&&l?{subject:s,author:i,date:l}:null,commits:p.length,ticketCommits:p.filter(m=>Ry(m,n)).length}},MA=()=>{if(!ut())return{knownRefs:new Set,contributors:0};let e=y();return{knownRefs:new Set(Object.values(e.nodes).filter(t=>W(t)).map(t=>Y(t.id))),contributors:Object.values(e.contributors).filter(t=>!t.tombstoned).length}},wc=e=>{let t=Oi(e);return a(t)?0:t.value.reduce((n,r)=>n+(r.bytes??0),0)},Fi=async e=>{let t=pu(e);if(a(t))return c(t.message);let n=t.value;if(n.kind!=="connect"&&e.mode==="preview")return c(`${n.repo.label} is already connected`);if(n.kind==="unchanged")return d(mu,{kind:"unchanged",repo:n.repo});if(n.kind==="edit"){let R=Si({repoRoot:e.repoRoot,actorId:e.actorId,event:{action:"edit.repo",payload:n.event}});return a(R)?c(R.message):(n.message.startsWith(pc)||Ir(),d(n.message,{kind:"updated",repo:n.repo}))}let r=AA(e.repoRoot,n.repo),o=es.get(n.repo.id);if(e.mode==="confirm"&&o?.key!==r)return c("Nothing is staged for this connect here, or it was staged with other options: preview it again");if(e.mode==="confirm"&&o){clearTimeout(o.timer),es.delete(n.repo.id);let R=Si({repoRoot:e.repoRoot,actorId:e.actorId,event:{action:"connect.repo",payload:n.event}});if(a(R))return Pn(o.stagePath),c(R.message);await db(e.repoRoot,n.repo,o.stagePath);let w=Ht(e.repoRoot),S=!a(w)&&w.value.overLimit.some(A=>A.id===n.repo.id);return d(S?`Connected ${n.repo.label}, but the board already reads ${Hn} repos: it is not fetched until one ahead of it is disconnected`:`Connected ${n.repo.label}`,{kind:"connected",repo:n.repo})}for(let R of[...es.keys()])pb(R);let s=NA(n.repo.id),i=++mb,l=()=>Ou.get(n.repo.id)!==s||mb!==i,u=er(e.repoRoot);if(a(u))return c(u.message);let p=await lb(e.repoRoot,n.repo);if(a(p))return c(`Could not clone it: ${p.message}`);if(l())return Pn(p.value.stagePath),c("Cancelled");let m=MA(),f=await TA(p.value.stagePath,Sr(n.repo.since,u.value.createdAt),m.knownRefs),g=Ht(e.repoRoot),b={repo:n.repo,host:fb(n.repo.url),...f,bytes:p.value.bytes,contributors:m.contributors,claimedBytes:wc(e.repoRoot),overLimit:!a(g)&&g.value.live.length>=Hn,expiresAt:Date.now()+Pu};if(l())return Pn(p.value.stagePath),c("Cancelled");let E=setTimeout(()=>pb(n.repo.id),Pu);return E.unref(),es.set(n.repo.id,{stagePath:p.value.stagePath,key:r,preview:b,timer:E}),d("Preview: nothing is connected until you confirm",{kind:"preview",preview:b})}});var hb=h(()=>{"use strict";De();Qo()});var kA,_u,yb=h(()=>{"use strict";De();yt();C();Vo();lo();Ti();kA=8*1024*1024,_u=async e=>{if(!mi(e.sha))return c("Invalid commit sha");let t=await xc(e);if(a(t))return c(t.message);let n=await G({cwd:t.value,maxOutput:kA,args:["show","--no-ext-diff","--no-color","--patch","--find-renames","--format=",e.sha]});return a(n)?c(Pa(n.message)?"This commit is too large to show here; open it in your editor":n.message):d("Read commit patch",n.value.stdout)}});var vb,Du,LA,bb,Bi,Rb,xb,PA,Eb,Sb,Fu,OA,Ib,Nc=h(()=>{"use strict";vb=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,Du=e=>e.replace(vb,""),LA=e=>`<!-- epiq-diff-comment:${JSON.stringify(e).replaceAll(">","\\u003e")} -->`,bb=e=>e==="additions"||e==="deletions",Bi=e=>{let t=vb.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"||!bb(r.side)||!bb(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r},Rb=/```\n([\s\S]*?)\n?```\s*$/,xb=e=>Rb.exec(e)?.[1]??null,PA=/`[^`\n]+`[^\n]*\n?$/,Eb=e=>Du(e).replace(Rb,"").replace(PA,"").trim(),Sb=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})`},Fu=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${Sb(e)}`,OA=e=>{let t=e.split(`
56
- `),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(`
57
- `):e},Ib=({snippet:e,...t})=>{let n=t.note.trim();return[...n?[n,""]:[],LA({...t,note:n}),`\`${t.filePath}\` ${Sb(t)}`,"```",OA(e),"```"].join(`
58
- `)}});var _A,Ac,Cb,$u,Bu,ju,Tc,Uu,wb,DA,Nb,Ab,Tb,Hu,Mc=h(()=>{"use strict";Nc();_A=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/,Ac=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+=`
59
- `;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}},Cb=e=>{let t=Ac(e.trim());return t==="/dev/null"?null:t.replace(/^[ab]\//,"")},$u=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(`
60
- `)){if(i.startsWith("diff --git ")){n=s();let m=i.slice(11),f=m.lastIndexOf(" b/");f!==-1&&(n.path=Ac(m.slice(f+1)).replace(/^b\//,""));continue}if(!n){if(!i.trim())continue;n=s()}let l=n,u=l.lines.length===0;if(u&&i.startsWith("--- ")){let m=Cb(i.slice(4));m&&(l.oldPath=m);continue}if(u&&i.startsWith("+++ ")){let m=Cb(i.slice(4));m&&(l.path=m);continue}if(u&&i.startsWith("rename from ")){l.oldPath=Ac(i.slice(12));continue}if(u&&i.startsWith("rename to ")){l.path=Ac(i.slice(10));continue}if(u&&(i.startsWith("Binary files ")||i.startsWith("GIT binary patch"))){l.binary=!0,l.lines.push({kind:"note",text:"Binary file"});continue}let p=_A.exec(i);if(p){r=Number(p[1]),o=Number(p[3]),l.lines.push({kind:"hunk",text:i});continue}if(!u){if(i.startsWith("\\")){l.lines.push({kind:"note",text:i.slice(1).trim()});continue}if(i.startsWith("+")){l.added++,l.lines.push({kind:"added",text:i.slice(1),newLine:o++});continue}if(i.startsWith("-")){l.removed++,l.lines.push({kind:"removed",text:i.slice(1),oldLine:r++});continue}if(i.startsWith(" ")){l.lines.push({kind:"context",text:i.slice(1),oldLine:r++,newLine:o++});continue}i===""&&l.lines.push({kind:"context",text:"",oldLine:r++,newLine:o++})}}for(let i of t)!i.path&&i.oldPath&&(i.path=i.oldPath);return t.filter(i=>i.path!=="")},Bu=e=>e.oldPath&&e.oldPath!==e.path?e.oldPath:null,ju=e=>e.flatMap(t=>[{kind:"file",text:`${Bu(t)?`${Bu(t)} \u2192 `:""}${t.path}`,file:t},...t.lines]),Tc=e=>{let t="",n=-1;return e.map(r=>(r.kind==="file"&&(t=r.file.path),r.kind==="hunk"&&n++,{file:t,hunk:n}))},Uu=(e,t,n)=>{let r=t.map(i=>Bi(i.md)).filter(i=>i!==null&&i.sha===n&&i.side==="additions");if(r.length===0)return new Set;let o=Tc(e),s=new Set;return e.forEach((i,l)=>{let u=i.newLine;if(u===void 0)return;let p=o[l]?.file;r.some(m=>m.filePath===p&&m.start<=u&&u<=m.end)&&s.add(l)}),s},wb=(e,t)=>e===t?`line:${e}`:`lines:${e}-${t}`,DA=/^lines?:(\d+)(?:-(\d+))?(?:\s+|$)/,Nb=e=>{let t=DA.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)}},Ab=(e,t)=>Tc(e)[t]?.file??null,Tb=(e,t,n,r)=>{let o=Tc(e),s=u=>e.findIndex((p,m)=>o[m]?.file===t&&(p.kind==="added"||p.kind==="context")&&p.newLine===u),i=s(n),l=s(r);return i===-1||l===-1?{ok:!1,reason:`${t} has no line ${i===-1?n:r} on the new side`}:Hu(e,i,l)},Hu=(e,t,n)=>{let[r,o]=t<=n?[t,n]:[n,t],s=e[r],i=e[o];if(!s||!i)return{ok:!1,reason:"That line is not in the diff"};let l=g=>(g.kind==="added"||g.kind==="context")&&g.newLine!==void 0;if(!l(s)||!l(i))return{ok:!1,reason:"Comments anchor to the new side: pick an added or unchanged line"};let u=Tc(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(l);return{ok:!0,value:{filePath:p.file,start:f[0].newLine,end:f[f.length-1].newLine,snippet:f.map(g=>g.text).join(`
61
- `)}}}});import{spawn as FA,spawnSync as BA}from"node:child_process";import $A from"node:os";import Mb from"node:path";import{ulid as jA}from"ulid";function Wu(e){let t=[],n="",r=!1,o=null;for(let s of e.trim()){if(o){s===o?o=null:n+=s;continue}if(s==='"'||s==="'"){o=s,r=!0;continue}if(/\s/.test(s)){r&&t.push(n),n="",r=!1;continue}n+=s,r=!0}return r&&t.push(n),t}function UA(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function kc(){let{preferredEditor:e}=ce(),t=[e?UA(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Gu(e){let[t=""]=Wu(e);return/(^|\/)code(-insiders)?$/.test(t)}function kb(e,t){let[n="",...r]=Wu(e);return{command:n,args:[...r,...t]}}function Lb(e,t){return kb(e,Gu(e)?["--wait",t]:[t])}function HA(e,t,n,r="new"){return kb(e,[r==="new"?"--new-window":"--reuse-window","--diff",t,n])}function Pb(e){let t=Mb.join($A.tmpdir(),"epiq");nt.mkDir(t);let n=Mb.join(t,jA());nt.writeToFile(n,e??"");let r=kc();for(let o of r){let{command:s,args:i}=Lb(o,n);if(!s)continue;let l=BA(s,i,{stdio:"inherit"});if(!l.error&&l.status===0){let u=nt.readFile(n);if(u==null)return c("Unable to read edited file");let p=u.replace(/\r?\n$/,"");return d("Successfully edited",p)}}return c("Unable to open editor")}function GA(e){let[t=""]=Wu(e),n=t.split("/").pop()??t;return WA.has(n)}function Ob({command:e,args:t},n){return new Promise(r=>{if(!e){r(c(`"${n}" is not a usable editor command`));return}let o=FA(e,t,{stdio:"ignore",detached:!0}),s=!1,i=u=>{s||(s=!0,clearTimeout(l),r(u))};o.on("error",u=>i(c(u.message))),o.on("exit",u=>{i(u===0?d("Opened editor",!0):c(`"${n}" exited with code ${u}`))});let l=setTimeout(()=>{o.unref(),i(d("Opened editor",!0))},qA)})}function zA(e,t){return GA(e)?Promise.resolve(c(`"${e}" is a terminal editor and can't open from the GUI (no terminal attached). Set preferredEditor to a GUI editor (e.g. "code"), or open the file yourself: ${t}`)):Ob(Lb(e,t),e)}function qu(e,t,n,r="new"){return Ob(HA(e,t,n,r),e)}async function _b(e){let t=kc();if(t.length===0)return c("No editor configured (preferredEditor, VISUAL, or EDITOR)");let n=c("Unable to open editor");for(let r of t){let o=await zA(r,e);if(!a(o))return o;n=o,logger.error(`Failed to open editor "${r}" for ${e}: ${o.message}`)}return n}var WA,qA,zu=h(()=>{"use strict";C();Ue();Xa();WA=new Set(["vim","vi","nvim","nano","pico","ed"]);qA=600});import{chmodSync as VA,existsSync as KA,lstatSync as YA,mkdirSync as XA}from"node:fs";import JA from"node:os";import QA from"node:path";var $i,Vu=h(()=>{"use strict";C();$i=(...e)=>{let t=QA.join(JA.tmpdir(),"epiq",...e);try{return KA(t)&&YA(t).isSymbolicLink()?c(`Refusing to write through a symlink at ${t}`):(XA(t,{recursive:!0,mode:448}),VA(t,448),d("Prepared private temp dir",t))}catch(n){return c(`Unable to prepare ${t}: ${n instanceof Error?n.message:String(n)}`)}}});import{existsSync as Ku}from"node:fs";import{chmod as Yu}from"node:fs/promises";import Lc from"node:path";var ZA,eT,tT,Db,nT,rT,Xu,Fb=h(()=>{"use strict";De();zu();C();Xa();Vu();Vo();lo();ZA=async(e,t)=>{let n=await G({cwd:e,args:["show","--no-ext-diff",t]});if(a(n))return c(n.message);let r=$i("commit-diffs");if(a(r))return c(r.message);let o=Lc.join(r.value,`${t}.diff`);return Ku(o)||(nt.writeToFile(o,n.value.stdout),await Yu(o,292)),_b(o)},eT=12,tT=800,Db=async(e,t,n)=>{let r=await G({cwd:e,args:["show",`${t}:${n}`]});return a(r)?"":r.value.stdout},nT=async(e,t)=>{let n=await G({cwd:e,args:["diff","--name-only",`${t}~1`,t]});if(a(n))return c(n.message);let r=n.value.stdout.split(`
62
- `).map(o=>o.trim()).filter(Boolean);return r.length===0?c("No changed files found for this commit"):d("Listed changed files",r)},rT=async(e,t,n)=>{let r=await nT(e,t);if(a(r))return c(r.message);let o=r.value;if(o.length>eT)return c(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=$i("commit-diffs",t);if(a(s))return c(s.message);let i=s.value,l=await Promise.all(o.map(async(g,b)=>{let[E,R]=await Promise.all([Db(e,`${t}~1`,g),Db(e,t,g)]),w=Lc.basename(g),S=Lc.join(i,String(b),"before",w),A=Lc.join(i,String(b),"after",w);return Ku(S)||(nt.writeToFile(S,E),await Yu(S,292)),Ku(A)||(nt.writeToFile(A,R),await Yu(A,292)),{beforePath:S,afterPath:A}})),[u,...p]=l;if(!u)return c("No changed files found for this commit");let m=await qu(n,u.beforePath,u.afterPath,"new");if(a(m)||p.length===0)return m;await new Promise(g=>setTimeout(g,tT));let f=await Promise.all(p.map(({beforePath:g,afterPath:b})=>qu(n,g,b,"reuse")));for(let g of f)a(g)&&logger.error(`Failed to open an additional diff tab for ${t}: ${g.message}`);return m},Xu=async e=>{if(!mi(e.sha))return c("Invalid commit sha");let t=await xc(e);if(a(t))return c(t.message);let n=t.value,r=kc()[0];if(r&&Gu(r)){let o=await rT(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 ZA(n,e.sha)}});var Cr=h(()=>{"use strict";Vo();Qo();gb();hb();Cc();lo();Ti();yb();Mc();Fb()});var Bb,$b=h(()=>{"use strict";Bb=e=>{if(e<1024)return`${e} B`;let t=["KB","MB","GB","TB"],n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${n>=10?Math.round(n):n.toFixed(1)} ${t[r]}`}});var Ju,Qu,jb,sT,ts,iT,Ub,Hb,Wb,Zu=h(()=>{"use strict";Cr();C();he();Ue();$b();ct();Ju=["branches=default","branches=all","since=board","since=all","since=YYYY-MM-DD","label=<name>","confirm"],Qu=e=>{let[t="",...n]=e.trim().split(/\s+/).filter(Boolean);if(!t)return c("a remote URL to read commits from");if(!dr(t))return c("https://, ssh://, git://, file:/// or user@host:path");let r={url:t},o=new Set;for(let s of n){let i=s.indexOf("="),l=i===-1?s:s.slice(0,i),u=i===-1?"":s.slice(i+1);if(o.has(l))return c(`one ${l}=, not two`);if(o.add(l),s==="confirm")r.confirm=!0;else if(l==="branches"&&(u==="default"||u==="all"))r.branches=u;else if(l==="since"&&jr(u))r.since=u;else if(l==="label"&&(u===""||Ur(u)))r.label=u;else return c(`${Ju.join(", ")}; not "${s}"`)}return d("Parsed",r)},jb=()=>{let e=Mt();if(a(e))return[];let t=Ht(e.value);return a(t)?[]:[...t.value.live,...t.value.overLimit]},sT=e=>{let t=e.latest?`latest "${ye(e.latest.subject).slice(0,60)}" by ${ye(e.latest.author).slice(0,40)}`:"no commits",n=e.ticketCommits===0?"none linked, wrong repo?":`${e.ticketCommits} linked`;return[`${e.repo.label} from ${e.host}`,e.defaultBranch?ye(e.defaultBranch).slice(0,60):"no default branch",t,`${e.commits} commits, ${n}`,Bb(e.bytes),e.overLimit?"over the limit: not downloaded until another repo is disconnected":e.contributors>1?`all ${e.contributors} contributors download it on next sync`:"everyone downloads it on next sync"].join(" \xB7 ")},ts=null,iT=e=>`${e.trim()} confirm`,Ub=e=>ts&&ts.line===e.trim()?ts.summary:null,Hb=async()=>{let e=le().commandMeta.inputString,t=Qu(e);if(a(t))return c(`Expected ${t.message}`);let{userId:n}=ce();if(!n)return c("Set a username first with :config username");let r=Mt();if(a(r))return r;let o=await Fi({repoRoot:r.value,actorId:n,url:t.value.url,branches:t.value.branches,since:t.value.since,label:t.value.label,mode:t.value.confirm?"confirm":"auto"});if(a(o))return c(o.message);if(o.value.kind==="preview"){let s=iT(e);return ts={line:s,summary:sT(o.value.preview)},d(ts.summary,{followUp:`config repoConnect ${s}`})}return t.value.confirm&&(ts=null),d(o.value.kind==="connected"?`${o.message} \u2014 it syncs with the board; :sync fetches it`:o.message,null)},Wb=()=>{let{userId:e}=ce();if(!e)return c("Set a username first with :config username");let t=Mt();if(a(t))return t;let n=_i({repoRoot:t.value,actorId:e,repo:le().commandMeta.inputString});return a(n)?c(n.message):d(`${n.message} \u2014 it syncs with the board`,null)}});var mt,tr=h(()=>{"use strict";mt=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null});import{createHash as aT}from"node:crypto";var cT,lT,Gb,ke,wr=h(()=>{"use strict";cT="0123456789ABCDEFGHJKMNPQRSTVWXYZ",lT=e=>{let t=aT("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+=cT[Number(n>>s&31n)]}return r},Gb=new Map,ke=(e,t)=>{let n=`${e}:virtual:${t}`,r=Gb.get(n);if(r!==void 0)return r;let o=lT(n);return Gb.set(n,o),o}});import qb from"chalk";var Se,Le,Fe,zb=h(()=>{"use strict";Cn();et();Se=e=>qb.dim(e),Le=e=>qb.hex(M.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,g)=>Ca(f)-Ca(g)).slice(0,r).map(f=>wa(f)).join(" ");return m?`${Se(e)}${m}${Se(n)}`:""}});var Nr,Pc=h(()=>{"use strict";Nr={None:"none",Invalid:"invalid",Valid:"valid"}});import Yb from"chalk";var dT,Vb,ve,uT,ae,K,rs,Kb,Oc,em,mT,ns,pT,fT,gT,hT,yT,Xb,Jb=h(()=>{"use strict";Kr();Jr();dh();ht();fn();C();ge();Ue();Ud();Wo();Ja();Cr();Zu();Bt();O();Cn();tr();jo();wr();zb();si();Qr();Pc();Kn();ai();dT=["BOARD","TICKET","SWIMLANE"],Vb=()=>{let e=y().selectedNode;if(!e?.context)return K({message:Se("Missing target context")});if(dT.includes(e.context))return ae();if(e.parentNodeId){let t=y().nodes[e.parentNodeId];if(t?.id===ke(t?.parentNodeId??"","comments"))return ae()}return K({message:Se("Command not available in this context")})},ve="<ENTER> to confirm",uT=()=>{let{userId:e}=ce(),t=Ce();return!e||a(t)?[]:mr(t.value.emailLinks,e)},ae=(e="",t=[],n=!0)=>({message:n?Se(e):e,validity:Nr.Valid,completionWordList:t}),K=({message:e,completionWordList:t=[]})=>({validity:Nr.Invalid,message:e,completionWordList:t}),rs=e=>e.length===0,Kb=(e,t)=>{let n=Ft(y().breadCrumb,"BOARD");if(a(n))return K({message:Le("Command is not applicable in this context")});let r=Xl(n.value.id);return a(r)?K({message:Le(`Unable to ${t}: board id is not a valid ULID`)}):sh({date:e,horizonDate:r.value})?null:K({message:Le(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},Oc=e=>` ${Yb.hex("#000").bgHex(it(e))(` ${e} `)} `,em=({modifier:e})=>{let t="confirm";return e===t?ae(ve):K({message:rs(e)?Se("if you are certain, enter ")+wa(t):"",completionWordList:[t]})},mT=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?K({message:Se(n)}):ae():K({message:rs(r)?t:"",completionWordList:[...e]}),ns=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>rs(n)&&rs(r)?K({message:e,completionWordList:[]}):ae(t??ve),pT=({modifier:e,inputString:t})=>{let n=_d();return!rs(e)||!rs(t)?ae(ve):K({message:n.length?Se("number from the list, or a path"):Se("path to an epiq project"),completionWordList:n})},fT=({modifier:e,inputString:t})=>{let n=Ke(I.CONFIG);if(!n.includes(e))return K({message:Fe({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ie.EDITOR:{let r=[...lh];return t.trim()?r.includes(t.trim())?ae(ve):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 ie.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?ae(ve):K({message:Fe({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ie.USERNAME:{let r=ce().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} ${Se(ve)}`,o,!1):ae(ve,o):K({message:u||Le("Enter a user name. Saved in ")+Yb.bgBlack("~/.epiq-global/config.json"),completionWordList:o})}case ie.EMAILS:{let r=ce().gitEmail,o=$o(),s=o.length>0||!r?o:[r],i=[...s,"none"],l=t.trim(),u=(E,R)=>K({message:Fe({prefix:E,wordList:i,noOfHints:3,inputString:R,minLengthForHints:0}),completionWordList:i});if(!l)return ae(`${ve} to see your addresses, or name one`,i);let p=l.split(/[,\s]+/).filter(Boolean),m=p[p.length-1]??"",f=E=>E==="none"||s.includes(E.toLowerCase()),g=E=>i.some(R=>R.startsWith(E.toLowerCase())),b=p.filter(E=>!f(E)&&!g(E));return b.length>0?K({message:Le(`no address here matches ${b.join(", ")} \u2014 pick one from the list, or its number`),completionWordList:i}):f(m)?ae(ve):u("",m)}case ie.EMAILS_UNCLAIM:{let r=uT(),o=t.trim();return r.length===0?K({message:Le("you have not claimed any addresses"),completionWordList:[]}):o&&r.includes(o.toLowerCase())?ae(ve):K({message:Fe({prefix:"give an address back ",wordList:r,noOfHints:3,inputString:o,minLengthForHints:0}),completionWordList:r})}case ie.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?ae(ve):K({message:Fe({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ie.AUTOSYNC:{let r=["on","off"],o=ce().autoSync;if(!r.includes(t.trim())){let s=th(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(ve)}case ie.ATTACHMENT_MAX_KB:{let r=ce().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<li||o>di){let s=Fe({prefix:" examples: ",wordList:Pd,minLengthForHints:0,inputString:t});return K({message:Le(`provide a size cap in KB (${li}-${di}). current: ${r??Yn} KB.`)+s,completionWordList:Pd})}return ae(ve)}case ie.REPO_CLONE_MAX_MB:{let r=t.trim();if(!/^\d+$/.test(r)||!Wd(Number(r))){let o=Fe({prefix:" examples: ",wordList:Od,minLengthForHints:0,inputString:t});return K({message:Le(`provide a connected repo's clone cap in MB (${Go}-${qo}). current: ${zo()} MB.`)+o,completionWordList:Od})}return ae(ve)}case ie.REPO_CONNECT:{let r=Qu(t);if(a(r))return K({message:Le(r.message),completionWordList:[]});let o=r.value.confirm?Ub(t):null;return r.value.confirm&&!o?K({message:Le("preview it first: run the line without confirm"),completionWordList:[]}):ae(`${o??Se(Ju.join(" "))} ${ve}`,[],!1)}case ie.REPO_DISCONNECT:{let r=jb(),o=gu(r),s=t.trim();return o.length===0?K({message:Le("no other repos are connected"),completionWordList:[]}):s&&!a(gc(r,s))?ae(ve):K({message:Fe({prefix:"stop reading ",wordList:o,noOfHints:3,inputString:s,minLengthForHints:0}),completionWordList:o})}case ie.SYNC_DEBOUNCE_MS:{let r=ce().autoSyncIntervalMs,o=Lo(t);if(!t.trim()||o===null){let s=Fe({prefix:" examples: ",wordList:Ld,minLengthForHints:0,inputString:t});return K({message:Le(`provide a duration between ${3e3}ms and ${864e5}ms. current duration: ${r}ms.`)+s,completionWordList:Ld})}return ae(ve)}default:return K({message:Le("Unknown config option"),completionWordList:n})}},gT=({modifier:e,inputString:t})=>{let n=Ke(I.EDIT);if(!n.length)return K({message:Le("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||Le("Unknown edit option"),completionWordList:n})}switch(e){case Ut.COMMENT:return t.trim()?ae(ve):K({message:Se("write a comment...")});case Ut.TITLE:return ae(ve);case Ut.DESCRIPTION:{let{preferredEditor:r}=ce();return r?ae(Se("<ENTER> to edit in ")+r):K({message:"No editor selected"})}default:return K({message:Le("Unknown edit option"),completionWordList:n})}},hT=({modifier:e})=>{let t=Ke(I.YANK);return t.length?t.includes(e)?ae(ve+Se(" and copy to clipboard")):K({message:Fe({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):K({message:Le("Nothing selected to copy from")})},yT={[I.EXPORT]:()=>ae(ve+Se(", and create export markdown file")),[I.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return ae(ve);let n={message:Se("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Zr(r);if(!r||!o)return K(n);let s=Kb(o,"peek");return s||ae(ve)},[I.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Va(e.modifier,e.inputString),r={message:Se("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Zr(t);if(!t||!o)return K(r);let s=Kb(o,"replay");return s||(n&&za(n)===null?K({message:Le("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):ae("<ENTER> to replay board history",n?ch:[]))},[I.EXIT]:()=>ae(ve+Se(" and exit the application")),[I.INIT]:()=>ae(ve),[I.OPEN]:pT,[I.PALETTE]:()=>ae(ve),[I.FILTER]:e=>{if(e.modifier==="clear")return ae(ve);let t=s=>Ke(I.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return K({message:Fe({wordList:Ke(I.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Ke(I.FILTER)});let n=Object.values(y().tags).map(s=>s.name),r=Object.values(y().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=Ke(I.NONE);return K({message:Fe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[I.NEW]:e=>mT({list:Ke(I.NEW),hint:Fe({wordList:Ke(I.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[I.HELP]:()=>ae(ve),[I.EDIT]:gT,[I.COMMENT]:e=>{let t=ns({hint:Se(`write a comment (max ${4e3} char)...`),onOk:Se(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===Nr.Invalid?t:e.inputString.length>4e3?ae(Le("max input exceeded")):t},[I.CONFIG]:fT,[I.YANK]:hT,[I.DELETE]:e=>{let t=Vb();return t.validity==="invalid"?t:em(e)},[I.CLOSE_ISSUE]:e=>em(e),[I.RE_OPEN_ISSUE]:e=>em(e),[I.MOVE]:e=>{let t=Vb();return t.validity==="invalid"?t:ns({hint:Fe({prefix:"hey hacker! These commands are blocked for you... ",wordList:Ke(I.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[I.TAG]:e=>{let n=N.getExistingTags().slice(0,10).map(Oc).join("");return ns({hint:n.length?Se("create tag or reuse:")+n+Se(""):Se("create tag ...")})(e)},[I.UNTAG]:e=>{let t=Ga();if(a(t))return K({message:Le("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Oc).slice(0,10);return n.length?ns({hint:Se(" ... ")+n.join("")})(e):K({message:Le("Issue has no tags"),completionWordList:[]})},[I.ASSIGN]:e=>{let t=N.getExistingAssignees().map(Oc).slice(0,10);return ns({hint:Se("assignees... ")+t.join("")})(e)},[I.UNASSIGN]:e=>{let t=qa();if(a(t))return K({message:Le("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Oc).slice(0,10);return n.length?ns({hint:Se("remove assignee... ")+n.join("")})(e):K({message:Le("Issue has no assignees"),completionWordList:[]})},[I.SYNC]:()=>ae(ve)},Xb=Object.fromEntries(Object.entries(yT).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]))});var _c,Qb=h(()=>{"use strict";_c=["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 bT,vT,RT,xT,ET,Zb,ev,tv,nv=h(()=>{"use strict";C();O();Qb();bT=3,vT=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"]),RT=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},xT=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=bT&&!vT.has(t)&&!/^\d+$/.test(t)),ET=e=>{let t=new Map;for(let s of RT(e))for(let i of xT(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=_c.filter(s=>!r.has(s));return[...n,...o]},Zb=_c,ev=-1,tv=()=>{let e=Ce();if(a(e))return _c;let t=e.value,n=t.eventLog.length;return n!==ev&&(Zb=ET(t),ev=n),Zb}});var rv,ov,tm=h(()=>{"use strict";Qf();Kn();Qr();Jb();nv();O();$e();rv=e=>Object.values(I).includes(e),ov=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:l,completionWordList:u}=Xb[n].validate(n,r,s),p=n!==I.PEEK&&n!==I.REPLAY,m=o==="command"||o==="modifier"?Ke(n):p?tv():[],{mode:f}=y(),g=f===x.COMMAND_LINE?i??"":"",b=[...u,...m];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?Jf(e,b,u):{hint:"",hints:[],remainder:"",overlap:0}}}});var sv,ST,IT,CT,iv=h(()=>{"use strict";tm();Kn();sv=e=>{let t=e.trimStart(),n=IT(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=CT(e),l=rv(r)?r:null,u=l!==null,p=r!=="",m=l?Ke(l)??[]:[],f=l&&m.includes(o)?o:"",g="word";n.length===0||n.length===1&&!s?g="command":(n.length===1&&s||n.length===2&&!s)&&(g="modifier");let b=s?"":i,E=ST(t,l,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:p,command:l,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:b,inputString:E}},ST=(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},IT=e=>e.trim()?e.trim().split(/\s+/):[],CT=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as sH}from"react";var os,nm,Ui,ss,wT,av,tn,Hi,rm,om,cv,lv,Dc,dv,re,uv,mv,pv,fv,gv,le,Fc,he=h(()=>{"use strict";tm();iv();C();Pc();os=e=>e===nm||e===":",nm=" ",Ui=40,ss={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Nr.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},wT=new Set,av=()=>{for(let e of wT)e()},tn=e=>{let n=e(ss),r=sv(n.value),o=n.cursorPosition===n.value.length;ss={...n,commandMeta:ov(r,o)},av()},Hi=({message:e,status:t})=>{let n=structuredClone(ss);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,ss=n,av(),d(e,null)},rm=e=>{tn(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},om=e=>{tn(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&os(n[o-1]);)o--;for(;o>0&&!os(n[o-1]);)o--}else{for(;o<n.length&&!os(n[o]);)o++;for(;o<n.length&&os(n[o]);)o++}return{...t,cursorPosition:o}})},cv=()=>{tn(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}})},lv=()=>{tn(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&os(t[r-1]);)r--;for(;r>0&&!os(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Dc=e=>{tn(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,l=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:l,commandIsPending:!1}})},dv=()=>{tn(e=>({...e,commandIsPending:!0}))},re=e=>{tn(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},uv=({addToHistory:e=!0,line:t})=>{tn(n=>{let r=t??n.value;return{...n,commandHistory:e&&r.trim()?[r,...n.commandHistory].slice(0,Ui):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}})},mv=e=>{tn(t=>({...t,commandHistory:e.slice(0,Ui),commandHistoryIndex:-1}))},pv=()=>{tn(e=>e.commandHistoryIndex===-1?e:{...e,commandHistoryIndex:-1})},fv=()=>{tn(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}})},gv=()=>{tn(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},le=()=>ss,Fc=()=>{let[e,...t]=ss.value.split(nm);return t.join(nm).trim()}});var _,gH,pr=h(()=>{"use strict";$e();Hf();O();he();Ue();_={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"},gH={[_.NavPreviousItem]:_.NavPreviousItemJump,[_.NavNextItem]:_.NavNextItemJump,[_.MovePreviousItem]:_.MovePreviousItemJump,[_.MoveNextItem]:_.MoveNextItemJump}});function hv(e){return!e||!AT.test(e)?c(`Invalid hex rank: ${e}`):d("Converted rank to bigint",BigInt("0x"+e))}function qt(e,t=Wi){if(e<0n)return c("Negative rank not allowed");let n=e.toString(16);return d("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Et(e,t){if(!e&&!t)return qt(Rn/2n,Wi);let n=e?hv(e):d("Resolved lower bound",0n);if(a(n))return n;let r=t?hv(t):d("Resolved upper bound",Rn);if(a(r))return r;let o=n.value,s=r.value;if(s<=o)return c("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?c("No rank space available between neighbors"):qt(i,Wi)}function yv(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=qt(o,Wi);if(a(s))return s;n.push(s.value)}return d("Resolved evenly spaced ranks",n)}var Wi,NT,Rn,AT,is=h(()=>{"use strict";C();Wi=24n,NT=Wi*4n,Rn=(1n<<NT)-1n,AT=/^[0-9a-f]+$/});import{ulid as TT}from"ulid";var sm,bv=h(()=>{"use strict";C();nn();is();en();sm=(e,t)=>{let n=_e(e),r=yv(n.length);if(a(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],l=r.value[s];if(!i||!l)return c("Unable to assign rebalance rank");o[i.id]=l}return d("Created rebalance event",{id:TT(),action:"rebalance.children",payload:{parent:e,ranks:o},...D(t)})}});var mo,im,vv=h(()=>{"use strict";rt();mo=e=>e.trim().toLocaleLowerCase(),im=(e,t)=>mo(e).includes(mo(t))});var MT,kT,Rv,xv,LT,PT,Ev,Sv=h(()=>{"use strict";O();rt();vv();MT=e=>{let{tags:t}=y();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},kT=e=>{let{contributors:t}=y();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},Rv=null,xv=new Map,LT=()=>{let e=y().eventLog??[];if(e===Rv)return xv;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 Rv=e,xv=t,t},PT=e=>{let{contributors:t}=y(),n=LT().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},Ev=(e,t)=>{let n=mo(t.value);if(!n)return!0;switch(t.target){case"title":return im(e.title??"",n);case"description":return im(e.props.description??"",n);case"tag":return MT(e).map(mo).some(o=>o.includes(n));case"assignee":return kT(e).map(mo).some(o=>o.includes(n));case"actor":return PT(e).map(mo).some(o=>o.includes(n));case"ref":return bi(e.id,t.value);default:return!0}}});var am,OT,Iv,Cv,wv,cm=h(()=>{"use strict";pe();Sv();am=(e,t)=>e.rank<t.rank?-1:e.rank>t.rank?1:0,OT=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,Iv=(e,t)=>Object.values(e).filter(n=>OT(n,t)).sort(am),Cv=(e,t)=>{let n={};for(let r of Object.values(e)){if(W(r)&&t.length>0&&!t.every(s=>Ev(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(am);return n},wv=(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(am);return n}});var Nv,Bc,_e,Av,Tv,_n,nr,nn=h(()=>{"use strict";bv();H();C();O();cm();is();Nv=e=>Bc(_e(e),{at:"end"}),Bc=(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(Et(void 0,void 0));let r=()=>n(Et(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(Et(void 0,o.rank)):c("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(Et(o.rank,void 0)):c("Unable to resolve last sibling")}case"before":{let o=Av(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(Et(i?.rank,s.rank))}case"after":{let o=Av(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(Et(s.rank,i?.rank))}}},_e=e=>{let t=y();if(!Mv()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return Iv(t.nodes,e)},Av=(e,t)=>e.findIndex(n=>n.id===t),Tv=(e,t,n={at:"end"})=>Bc(_e(t).filter(r=>r.id!==e),n),_n=(e,t,n,r,o)=>{let s=Tv(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return d("Resolved rank",s.value.rank);let i=sm(e,r);if(a(i))return i;let l=F([i.value],o);if(a(l))return l;let u=Tv(t,e,n);return a(u)?u:u.value.needsRebalance?c("Rank rebalance failed to create space"):d("Resolved rank after rebalance",u.value.rank)},nr=(e,t,n)=>{let r=Nv(e);if(a(r))return r;if(!r.value.needsRebalance)return d("Resolved rank",r.value.rank);let o=sm(e,t);if(a(o))return o;let s=F([o.value],n);if(a(s))return s;let i=Nv(e);return a(i)?i:i.value.needsRebalance?c("Rank rebalance failed to create space"):d("Resolved rank after rebalance",i.value.rank)}});var Gi,V,kv,Lv,Pv,Lt=h(()=>{"use strict";O();Gi=5,V={exit(){process.exit(0)},enterChildNode(){let e=y(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=Ee(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||V.navigate({contextNode:o,selectedIndex:Ee(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=y();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=Ee(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;V.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>kv(1),navigateToPreviousItem:()=>kv(-1),jumpToNextItem:()=>Lv(Gi),jumpToPreviousItem:()=>Lv(-Gi),navigateToNextContainer:()=>Pv(1),navigateToPreviousContainer:()=>Pv(-1),navigate:({contextNode:e,selectedIndex:t})=>{T({contextNodeId:e.id,selectedIndex:t})}},kv=e=>{let{selectedIndex:t,contextNode:n}=y(),r=Ee(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;V.navigate({selectedIndex:s,contextNode:n})},Lv=e=>{let{selectedIndex:t,contextNode:n}=y(),r=Ee(n.id).length;if(r===0)return;let o=Math.max(0,t),s=Math.min(Math.max(o+e,0),r-1);V.navigate({selectedIndex:s,contextNode:n})},Pv=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=y();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=Ee(o.id),i=s.findIndex(g=>g.id===t.id);if(i<0)return;let l=s.at(i+e)??s.at(0);if(!l)return;let u=Ee(l.id),p=Math.max(0,u.length-1),m=Math.min(Math.max(0,r),p),f=u.length?m:-1;V.navigate({contextNode:l,selectedIndex:f})}});var _v,Dv,_T,$c,Fv,Ov,DT,Bv,$v=h(()=>{"use strict";pe();C();nn();O();Lt();_v=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Dv=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=y();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},_T=e=>{let t=y().nodes[e];return!!t&&!t.isDeleted&&at(t)&&t.childRenderAxis==="vertical"},$c=(e,t)=>{let{nodes:n}=y(),r=n[e];if(!r||r.isDeleted)return!1;let o=_e(r.id);return V.navigate({contextNode:r,selectedIndex:_v(t,o.length)}),!0},Fv=e=>{let{nodes:t}=y(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return $c(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=_e(o.id).findIndex(l=>l.id===n.id);return i>=0?(V.navigate({contextNode:o,selectedIndex:i}),!0):Fv(o.id)},Ov=e=>{let{nodes:t}=y(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Fv(n))return!0;n=t[n]?.parentNodeId}return!1},DT=e=>{if(!e)return!1;let t=y().nodes[e];return!!t&&!t.isDeleted},Bv=e=>{let{nodes:t,rootNodeId:n}=y();if(_T(e.contextNodeId)&&$c(e.contextNodeId,e.selectedIndex))return d("Restored navigation inside text container",null);if(DT(e.selectedNodeId)&&e.selectedNodeId&&Ov(e.selectedNodeId))return d("Restored navigation to selected node or ancestor",null);if($c(e.contextNodeId,e.selectedIndex))return d("Restored navigation to previous container",null);if(e.parentNodeId&&$c(e.parentNodeId,e.selectedIndex))return d("Restored navigation to previous parent",null);if(Ov(e.contextNodeId))return d("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return c("Unable to restore navigation");let o=_e(r.id);return V.navigate({contextNode:r,selectedIndex:_v(e.selectedIndex,o.length)}),d("Restored navigation to root",null)}});import{monotonicFactory as FT,ulid as Dn}from"ulid";function BT(){let e=Ce();if(a(e))return c("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return c("No workspace found in event log");let[r]=Ee(n.id),[o]=r?Ee(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 $T(){let e=BT();return a(e)?e:V.navigate(e.value)}function jv({userId:e,userName:t}){let n=qi(),r=qi(),o=qi(),s=qi(),i=qi(),l=Et(void 0,void 0);if(a(l))return l;let u=Et(void 0,void 0);if(a(u))return u;let p=Et(u.value,void 0);if(a(p))return p;let m=Et(void 0,void 0);if(a(m))return m;let f=Et(m.value,void 0);if(a(f))return f;let g=Et(f.value,void 0);if(a(g))return g;let b=Et(void 0,void 0);return a(b)?b:d("Created default events",[{id:Dn(),userId:e,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:Dn(),userId:e,action:"create.contributor",payload:{id:e,name:t}},{id:Dn(),userId:e,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Dn(),userId:e,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:m.value}},{id:Dn(),userId:e,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Dn(),userId:e,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:g.value}},{id:Dn(),userId:e,action:"add.board",payload:{id:Wa,name:"Closed",parent:n,rank:p.value}},{id:Dn(),userId:e,action:"add.swimlane",payload:{id:Te,name:"Closed",parent:Wa,rank:b.value}},{id:Dn(),userId:e,action:"lock.node",payload:{id:Wa}},{id:Dn(),userId:e,action:"lock.node",payload:{id:Te}}])}function Fn(e,t=[]){if(jT())return d("Skipped boot while checked out at a historical point",null);if(!e.length){let s=We.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=Ri(s);return a(i)?i:(T({hasProjectDefinition:!1,mode:x.DEFAULT}),d("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return c("Initialized Epiq project has no workspace init event");let n=Qn(e),{fatal:r,skipped:o}=br(n);return r.length>0?c(`Materializing failed:
63
- ${r.map(s=>s.message).join(`
64
- `)}`):(vr(o),$T(),T({hasProjectDefinition:!0}),UT(t),d("State booted successfully",null))}var qi,jT,UT,po=h(()=>{"use strict";yt();Lt();$e();C();Er();O();is();H();yn();qi=FT();jT=()=>{let e=Ce();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},UT=e=>{if(e.length===0)return;let t=e.filter(r=>r.reason==="corrupt-line"||r.reason==="invalid-payload"),n=e.filter(r=>r.reason==="unsupported-schema-version"||r.reason==="unknown-action");if(n.length>0){let r=[...new Set(n.map(o=>o.detail))].join(", ");z.info(`This build cannot read ${n.length} event(s) in the log (${r}). They are skipped, so anything they changed may be out of date until you upgrade.`)}if(t.length>0){let r=[...new Set(t.map(o=>o.detail))].join(", ");z.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}}});import{WebSocket as HT}from"ws";var WT,Uv,Hv=h(()=>{"use strict";WT=new Set,Uv=e=>{let t=JSON.stringify(e);for(let n of WT)n.readyState===HT.OPEN&&n.send(t)}});var jc,as,fo,lm,Uc,qe,zi=h(()=>{"use strict";Hv();C();O();jc=e=>{ut()&&(T({syncStatus:e}),Uv({type:"sync-status",payload:e}))},as=(e="Syncing...")=>{jc({status:"syncing",msg:e})},fo=(e="Synced")=>{jc({status:"synced",msg:e})},lm=e=>{jc({status:"failed",msg:e})},Uc=e=>{jc({status:"offline",msg:e})},qe=e=>(lm(e),c(e))});var cs,Wv,Re,Hc=h(()=>{"use strict";C();cs=(e,t)=>(logger.error(`[boot:${e}] ${t}`),c(`[boot:${e}] ${t}`)),Wv=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)}},Re=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});import Wc from"node:fs";import Gv from"node:path";var pt,qv,GT,dm,qT,zv,um=h(()=>{"use strict";wn();De();C();oe();Yt();pt=".epiq/project.json",qv=e=>Gv.join(e,pt),GT=e=>{if(!Wc.existsSync(qv(e)))return d("State branch carries no identity yet",null);let t=vt(e);return a(t)?c(`On the state branch: ${t.message}`):d("Read the state branch identity",t.value)},dm=(e,t)=>{try{let n=qv(e);return Wc.mkdirSync(Gv.dirname(n),{recursive:!0}),Wc.writeFileSync(n,JSON.stringify(t,null,2)+`
65
- `,"utf8"),d("Wrote the state branch identity",void 0)}catch(n){return c(n instanceof Error?`Failed to write the state branch identity: ${n.message}`:"Failed to write the state branch identity")}},qT=({checkout:e,branch:t,stateBranch:n})=>[`This checkout's ${pt} 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}:${pt} > ${pt}`,"","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(`
66
- `),zv=({repoRoot:e,stateBranchRoot:t,stateBranch:n})=>{if(!Wc.existsSync(Do(e)))return d("No project file to compare","no-checkout-file");let r=vt(e);if(a(r))return c(r.message);let o=GT(t);if(a(o))return c(o.message);if(o.value===null){let s=dm(t,r.value);return a(s)?c(s.message):d("Stamped the state branch with this project","stamped")}return o.value.projectId!==r.value.projectId?c(qT({checkout:r.value,branch:o.value,stateBranch:n})):d("The checkout and the state branch agree","matched")}});import Bn from"node:fs";import Vi from"node:path";var ls,Vv,Kv,Yv,zT,Xv,VT,KT,Jv,mm=h(()=>{"use strict";De();C();so();kn();oe();ls=e=>e.split(`
67
- `).filter(t=>t.trim().length>0),Vv=e=>{let t=Vi.join(e,bt,Vn);try{if(!Bn.existsSync(t))return d("No events directory",[]);let n=Bn.readdirSync(t).filter(r=>r.endsWith(".jsonl")).filter(r=>ls(Bn.readFileSync(Vi.join(t,r),"utf8")).length>0);return d("Looked for stranded event logs",n)}catch(n){return c(`Unable to check ${t} for event logs before deleting it: ${n instanceof Error?n.message:String(n)}`)}},Kv=e=>Vi.join(e,bt,Vn),Yv=e=>{let t=Kv(e),n=new Map;try{if(!Bn.existsSync(t))return n;for(let r of Bn.readdirSync(t))if(r.endsWith(".jsonl")&&!oo(r))try{n.set(r,ls(Bn.readFileSync(Vi.join(t,r),"utf8")))}catch(o){if(!pi(o))throw o}}catch{return n}return n},zT=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},Xv=(e,t)=>{if(t.size===0)return[];let n=Kv(e),r=[];for(let[o,s]of t){if(s.length===0)continue;let i=Vi.join(n,o);try{let l=Bn.existsSync(i)?Bn.readFileSync(i,"utf8"):null,u=new Set(l===null?[]:ls(l)),p=s.filter(f=>!u.has(f)).filter(zT);if(p.length===0)continue;Bn.mkdirSync(n,{recursive:!0});let m=l!==null&&l.length>0&&!l.endsWith(`
68
- `);Bn.appendFileSync(i,`${m?`
69
- `:""}${p.join(`
70
- `)}
71
- `,"utf8"),r.push(`${o} (${p.length})`)}catch{continue}}return r},VT=(e,t)=>{let n=new Set(ls(t));return ls(e).filter(r=>!n.has(r))},KT=(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(`
72
- `),Jv=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let r=await Pe({args:["show",`HEAD:${t}`],cwd:e});if(r.exitCode!==0)return d("No committed log to compare against",void 0);let o=VT(r.stdout,n);return o.length>0?c(KT(t,o,ls(r.stdout).length)):d("Event log only grew",void 0)}});import rr from"node:fs";import or from"node:path";var YT,Zv,Qv,XT,pm,Ki,JT,QT,Ar,ZT,eM,tM,nM,Gc,eR,tR,nR,Yi,rR,Xi=h(()=>{"use strict";so();C();um();yt();ka();wn();mm();tt();De();YT="[epiq:init-repo]",Zv=async e=>{let t=await Pe({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 c(["Could not determine whether the repository has any commits, so nothing was written.",`git rev-parse exited ${t.exitCode}`,t.stderr.trim()].filter(Boolean).join(`
73
- `));z.info("Creating initial commit");let r=await G({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(a(r))return c(r.message);let o=await G({args:["commit-tree",r.value.stdout.trim(),"-m",YT],cwd:e});if(a(o))return c(o.message);let s=await G({args:["update-ref","HEAD",o.value.stdout.trim()],cwd:e});return a(s)?c(s.message):d("Created initial commit",!0)},Qv=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",XT=async e=>{let t=await Da(e);if(a(t))return c(t.message);let n=await Sg(e);return a(n)?c(n.message):d("Built sync commit message",`[sync|branch:${Qv(t.value)}:sha:${Qv(n.value)}]`)},pm=async({repoRoot:e,stateBranchName:t})=>{z.info(`Creating ${t}`);let n=await G({args:["commit-tree",Og,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return c(`Failed to create state branch commit
74
- ${n.message}`);let r=n.value.stdout.trim(),o=await G({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return a(o)?c(`Failed to create ${t}
75
- ${o.message}`):d("Created state branch",!0)},Ki=async({repoRoot:e,stateBranchName:t})=>{let n=await _a({repoRoot:e,branch:t});if(a(n))return c(`Ensure local state branch failed
76
- `+n.message);if(n.value)return d("Local state branch already exists",!1);let r=await zn({repoRoot:e});if(a(r))return c(`Ensure local state branch failed
77
- `+r.message);let o=r.value,s=o?await Ks({repoRoot:e,branch:t}):d("No remote, no remote state branch",!1);if(a(s))return c(`Ensure local state branch failed
78
- `+s.message);let i=s.value;if(o&&i){let l=await Ne.fetch({cwd:e,remote:$t,branch:t});if(a(l))return c(`Failed to fetch ${t} from remote
79
- ${l.message}`)}if(i){let l=await G({args:["branch","--track",t,`${$t}/${t}`],cwd:e});return a(l)?c(`Failed to create local ${t} from remote
80
- ${l.message}`):d("Created local state branch from remote",!0)}return pm({repoRoot:e,stateBranchName:t})},JT=async({repoRoot:e,branch:t})=>{let n=await G({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return c(n.message);let r=n.value.stdout.split(`
81
- `),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)},QT=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Js(or.dirname(t));if(a(r))return c(`Failed to create state branch worktree
82
- `+r.message);if(rr.existsSync(t)&&!rr.existsSync(or.join(t,".git"))){let s=Vv(t);if(a(s))return c(s.message);if(s.value.length>0)return c([`Refusing to delete ${t}.`,"","It is not a usable worktree \u2014 it has no .git \u2014 but it still holds",`${s.value.length} event log(s) with content:`,...s.value.map(i=>` ${i}`),"","Deleting it would destroy them, and with no .git here there is no","committed copy to recover from. Move the directory aside and","salvage the logs before letting epiq recreate the worktree."].join(`
83
- `));z.info("Removing broken state branch worktree path"),Bg(t)}z.info("Creating state branch worktree");let o=await Ne.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(o)?c(`Failed to create state branch worktree
84
- ${o.message}`):d("Created state branch worktree",!0)},Ar=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await eM({repoRoot:e,stateBranchRoot:t,stateBranchName:n});if(a(r))return r;let o=zv({repoRoot:e,stateBranchRoot:t,stateBranch:n});return a(o)?c(o.message):(o.value==="stamped"&&z.info("Stamped the state branch with this project\u2019s identity"),r)},ZT=(e,t)=>{let n=Oo(Yr());return or.dirname(e)===n&&or.dirname(t)===n},eM=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await JT({repoRoot:e,branch:n});if(a(r))return c(r.message);let o=Oo(t),s=r.value?Oo(r.value):null;if(s&&s===o&&rr.existsSync(s))return d("State branch already checked out in expected worktree",!1);if(s&&s!==o&&ZT(s,o))return c([`The state branch ${n} is checked out under project ${or.basename(s)}, but this checkout names project ${or.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 ${pt} here`,`with \`git show ${n}:${pt}\`, and keep the branch's.`].join(`
85
- `));if(s&&s!==o){let u=await Tg(s);if(a(u))return c(u.message);if(u.value||Dh(s))return c([`Refusing to move the state branch worktree away from ${s}.`,"","It holds changes that are not committed yet, which for this","branch means events no sync has published. Removing it would","destroy them outright \u2014 there is no stash or reflog to recover","a deleted worktree from.","",`This worktree is expected at ${o}, so something else is`,"using a different EPIQ_GLOBAL_DIR against the same repository.","Sync from that location first, or point both at the same one."].join(`
86
- `));z.info("Moving state branch worktree to expected location");let p=await Ne.worktreeRemove({cwd:e,worktreeRoot:s});if(a(p))return c(`Failed to remove existing state branch worktree
87
- ${p.message}`)}if(s&&!rr.existsSync(s)){z.info("Pruning stale state branch worktree");let u=await Ne.worktreePrune({cwd:e});if(a(u))return c(`Failed to prune stale worktrees
88
- ${u.message}`)}let i=await Eg({repoRoot:e,worktreeRoot:t});if(a(i))return c(i.message);let l=rr.existsSync(t);if(i.value&&l)return d("State branch worktree already exists",!1);if(i.value&&!l){z.info("Pruning missing registered state branch worktree");let u=await Ne.worktreePrune({cwd:e});if(a(u))return c(`Failed to prune stale worktrees
89
- ${u.message}`)}return QT({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},tM=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Da(e);if(a(n))return c(n.message);if(n.value===t)return d("State branch already checked out",!1);(await Pe({cwd:e,args:["rebase","--abort"]})).exitCode===0&&z.info("Aborted stale state branch rebase");let o=await Ne.checkout({cwd:e,branch:t});return a(o)?c(`Failed to checkout ${t}
90
- ${o.message}`):d("Checked out state branch",!0)},nM=async({repoRoot:e,stateBranchRoot:t})=>{let n=await vd(t);if(a(n))return c(n.message);if(n.value)return d("State branch upstream already configured",!1);let r=await zn({repoRoot:t});if(a(r))return c(r.message);if(!r.value)return d("No remote available for state branch upstream",!1);let o=lt(e);if(a(o))return o;let s=o.value,i=await Ks({repoRoot:t,branch:s});if(a(i))return c(i.message);if(!i.value)return d("Remote state branch missing; upstream will be configured on first push",!1);z.info(`Configuring ${s} upstream`);let l=await Ne.fetch({cwd:t,remote:$t,branch:s});if(a(l))return c(`Failed to fetch ${s}
91
- ${l.message}`);let u=await Ne.setUpstream({cwd:t,branch:s,upstream:`${$t}/${s}`});return a(u)?c(`Failed to set state branch upstream
92
- ${u.message}`):d("Configured state branch upstream",!0)},Gc=async({stateBranchRoot:e,eventFileName:t})=>{let n=_g(t),r=or.join(e,n);if(!rr.existsSync(r))return d("No event file to stage",null);let o=await Jv({stateBranchRoot:e,relativePath:n,workingContent:rr.readFileSync(r,"utf8")});if(a(o))return c(o.message);let s=await Ne.stage({cwd:e,pathspec:[n]});return a(s)?c(`Failed to stage state branch event file
93
- ${s.message}`):d("Staged state branch event file",n)},eR=async({stateBranchRoot:e})=>{let t=Dg(),n=or.join(e,t);if(!rr.existsSync(n))return d("No media directory to stage",null);let r=await Ne.stage({cwd:e,pathspec:[t],ignoreRemoval:!0});return a(r)?c(`Failed to stage state branch media files
94
- ${r.message}`):d("Staged state branch media files",t)},tR=async({stateBranchRoot:e})=>{let t=[xd(),Ed(),pt].filter(r=>rr.existsSync(or.join(e,r)));if(t.length===0)return d("No event log config to stage",[]);let n=await Ne.stage({cwd:e,pathspec:t});return a(n)?c(`Failed to stage event log config
95
- ${n.message}`):d("Staged event log config",t)},nR=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let r=await XT(e);return a(r)?c(`Create state branch sync commit failed
96
- `+r.message):_o({cwd:t,message:r.value,pathspec:n})},Yi=async({repoRoot:e,stateBranchRoot:t})=>{let n=await vd(t);if(a(n))return c(n.message);let r=lt(e);if(a(r))return r;let o=r.value,s=n.value?await Ne.push({cwd:t}):await Ne.push({cwd:t,remote:$t,branch:o,setUpstream:!0});if(a(s))return c(`Failed during state branch push
97
- ${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)},rR=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=lt(e);if(a(o))return o;let s=o.value,i=[Qs(),await Ki({repoRoot:e,stateBranchName:s}),await Ar({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await tM({stateBranchRoot:t,stateBranchName:s}),await jg(t),n?await nM({stateBranchRoot:t,repoRoot:e}):d("Skipped state branch upstream bootstrap",!1)];for(let l of i){if(a(l))return c(l.message);r=r||!!l.value}return d(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)}});import sR from"node:fs";var rM,oM,fm,oR,qc,zc,Vc=h(()=>{"use strict";C();zi();cc();oe();Hc();wn();tt();De();Xi();mm();so();bc();rM=async({claim:e,cwd:t,ensureUpstream:n})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:t,ensureUpstream:n});let r=Re("getRepoRootDir",await jt(t));if(a(r))return c(r.message);let o=r.value;logger.debug("[sync] repo root",o);let s=Re("getStateBranchRoot",xe({repoRoot:o}));if(a(s))return c(s.message);let i=s.value;if(logger.debug("[sync] state branch root",i),e!=="stale"&&sR.existsSync(i)){let m=await wg(i,{preserve:[bu]});if(a(m))return c(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=lt(o);if(a(f))return c(f.message);let g=await Ng(i,f.value);if(a(g))return c(g.message);g.value&&logger.info("[sync] cleared a ref lock left by a dead process",{branch:f.value,stateBranchRoot:i});let b=Re("abortRebaseIfPresent(stateBranchRoot)",await Rd(i));if(a(b))return c(b.message)}logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:i,ensureUpstream:n});let l=Re("bootstrapStateBranchStorage",await rR({repoRoot:o,stateBranchRoot:i,ensureUpstream:n}));if(a(l))return c(l.message);logger.debug("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:i}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:i});let u=Re("getInProgressGitOperation(stateBranchRoot)",await bd(i));if(a(u))return c(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}),c(`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=Re("ensureStateBranchLayout",$g(o,i));return a(p)?c(p.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:i,bootstrapped:l.value}),d("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:i,bootstrapped:l.value}))},oM=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 Jh(Tt(t),n)){let m=Re("stageStateBranchOwnEventFile",await Gc({stateBranchRoot:t,eventFileName:p}));if(a(m))return c(m.message);r.push(m.value)}let o=Re("stageStateBranchMediaFiles",await eR({stateBranchRoot:t}));if(a(o))return c(o.message);let s=Re("stageStateBranchEventConfig",await tR({stateBranchRoot:t}));if(a(s))return c(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 l=Re("hasStagedChanges(after stage)",await Mg(t,i));if(a(l))return c(l.message);if(logger.debug("[sync] state branch change check after stage result",{changed:l.value}),!l.value)return logger.info("[sync] no own event file changes to commit"),d("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let u=Re("createStateBranchSyncCommit",await nR({repoRoot:e,stateBranchRoot:t,pathspec:i}));return a(u)?c(u.message):(logger.debug("[sync] created sync commit",u.value),d("Committed own event file",{createdCommit:!0,commitSha:u.value}))},fm=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return Uc(n),d(n,{...e,pulled:!1,pushed:!1,offline:!0})},oR=async({cwd:e=process.cwd(),ownEventFileName:t},n)=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),c("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),c("Own event file must end with .jsonl");as();let r=Re("ensureSyncReady",await rM({claim:n,cwd:e,ensureUpstream:!0}));if(a(r))return qe(r.message);let{repoRoot:o,stateBranchRoot:s,bootstrapped:i}=r.value,l=Re("isDetachedHead(stateBranchRoot)",await kg(s));if(a(l))return qe(l.message);if(logger.debug("[sync] detached state branch check result",{detached:l.value}),l.value)return qe("Cannot run :sync while the state branch is in detached HEAD state");let u=!1,p,m=!1,f=!1,g=Re("getStateBranch",lt(o));if(a(g))return qe(g.message);let b=g.value;logger.debug("[sync] resolved state branch",{stateBranch:b,stateBranchRoot:s});let E=Re("flushPendingLogs",nc(s,t));a(E)&&logger.error(`[sync] ${E.message}`);let R=Re("commitOwnEventFileToStateBranch",await oM({repoRoot:o,stateBranchRoot:s,ownEventFileName:t}));if(a(R))return qe(R.message);u=R.value.createdCommit,p=R.value.commitSha;let w=Re("hasRemote",await zn({repoRoot:s}));if(a(w))return qe(w.message);if(!w.value)return fm({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i},"no remote");let S=Re("pullBranchRebaseIfPresent",await Xs({cwd:s,branch:b}));if(a(S))return Ys(S.message)?fm({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i}):qe(S.message);m=S.value;let A=Re("isAheadOfUpstream",await Ag(s));if(a(A))return qe(A.message);if(u||i||A.value){logger.info("[sync] pushing state branch",{createdCommit:u,bootstrapped:i,stateBranchRoot:s});let L=Re("pushStateBranch",await Yi({stateBranchRoot:s,repoRoot:o}));if(a(L)&&Ig(L.message)){let P=Re("pullBranchRebaseIfPresent(retry)",await Xs({cwd:s,branch:b}));if(a(P))return qe(P.message);m=m||P.value,L=Re("pushStateBranch(retry)",await Yi({stateBranchRoot:s,repoRoot:o}))}if(a(L))return Ys(L.message)?fm({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:p,bootstrapped:i}):qe(L.message);f=L.value}if(u){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:s});let L=Re("git rev-parse HEAD",await G({args:["rev-parse","HEAD"],cwd:s}));if(a(L))return qe(L.message);p=L.value.stdout.trim(),logger.debug("[sync] final sync commit sha",p)}return fo(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})},qc=async(e,t)=>{let n=Yv(e);try{return await t()}finally{let r=Xv(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},zc=async e=>{let t=e.cwd??process.cwd(),n=await jt(t);if(a(n))return qe(n.message);let r=xe({repoRoot:n.value});if(a(r))return qe(r.message);let o=r.value;if(!sR.existsSync(o))return oR(e,"clean");let s=await Ni({worktreeRoot:o,operation:"sync",fn:i=>qc(o,()=>oR(e,i))});return a(s)?qe(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 ds,Kc,sM,iM,aM,gm,iR,Yc=h(()=>{"use strict";$v();po();Cc();H();H();kn();$e();C();O();zi();Hc();Vc();ds=null,Kc=async({reposMinIntervalMs:e=0}={})=>(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!ds,currentStatus:y().syncStatus?.status,currentMessage:y().syncStatus?.msg}),ds?(logger.debug("[sync] syncAndReloadState joining existing promise"),ds):(logger.debug("[sync] syncAndReloadState creating promise"),ds=sM(e).finally(()=>{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:y().syncStatus?.status,statusMessageBeforeClear:y().syncStatus?.msg}),ds=null}),ds)),sM=async e=>{let t;try{t=await iM(e),logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(t),message:t.message,statusAfterResolve:y().syncStatus?.status,statusMessageAfterResolve:y().syncStatus?.msg})}catch(r){let o=r instanceof Error?r.message:String(r);logger.error("[sync] syncAndReloadState promise threw",{message:o,error:r}),t=c(o)}let n=Ce();return a(t)&&!a(n)&&n.value.syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),T({syncStatus:{msg:t.message,status:"failed"}})),t},iM=async e=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:y().mode,syncStatus:y().syncStatus});let t=iR();if(t)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:y().mode,message:t.message,syncStatus:y().syncStatus}),t;logger.debug("[sync] syncAndReloadState:start");let n=Re("resolveActorId",be());if(a(n)||!n.value)return logger.info("[sync] unable to resolve actor id",{message:a(n)?n.message:"Missing actor id"}),c("Unable to resolve event log path");T({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:y().syncStatus});let r=Rr(n.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:r}),logger.debug("[sync] syncEpiqWithRemote:start");let o=Re("syncEpiqWithRemote",await zc({ownEventFileName:r}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(o),message:(a(o),o.message)}),a(o))return logger.error("[sync] syncAndReloadState:sync failed",o.message),T({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:y().syncStatus}),qe(`Unable to sync state. ${o.message}`);let{stateBranchRoot:s,offline:i,repoRoot:l}=o.value,u=gm(s);return a(u)?u:(T({hasProjectDefinition:!0,syncStatus:i?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:y().syncStatus}),aM(l,e),d("Synced",!0))},aM=async(e,t)=>{let n=await Zo({repoRoot:e,minIntervalMs:t}),r=a(n)?null:Di(n.value),o=y().syncStatus;r&&o?.status==="synced"&&T({syncStatus:{msg:`Synced \xB7 ${r}`,status:"synced"}})},gm=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=kt(e),n=Re("loadMergedEvents",vn(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(n),message:(a(n),n.message),count:a(n)?void 0:n.value.events.length}),a(n))return T({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:y().syncStatus}),c(`Unable to load events. ${n.message}`);logger.debug("[sync] loaded merged events after sync",{count:n.value.events.length});let r=iR();if(r)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:y().mode,message:r.message,syncStatus:y().syncStatus}),r;let o=Dv(),s=y().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:o,selectedNodeId:y().selectedNode?.id,contextNodeId:y().contextNode?.id,selectedNodeIsVirtual:y().selectedNode?.isVirtual,contextNodeIsVirtual:y().contextNode?.isVirtual}),!y().selectedNode?.isVirtual&&!y().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:n.value.events.length});let l=Ce(),u=!a(l)&&l.value.timeMode==="live",p=Re("bootStateFromEventLog",Fn(n.value.events,n.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(p),message:(a(p),p.message)}),a(p))return T({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:y().syncStatus}),c(`Unable to boot synced state. ${p.message}`);u&&Ko(e,t)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:y().selectedNode?.isVirtual,contextNodeIsVirtual:y().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),T({filters:s}),logger.debug("[sync] restoreNavigationAnchor:start");let i=Re("restoreNavigationAnchor",Bv(o));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(i),message:a(i)?i.message:"Navigation restored",selectedNodeId:y().selectedNode?.id,contextNodeId:y().contextNode?.id}),a(i)?(T({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:y().syncStatus}),i):d("Reloaded state from event log",null)},iR=()=>y().mode===x.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:y().mode,syncStatus:y().syncStatus}),T({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),c("Will not re-materialize if not in default mode, to not lose edit data"))});var aR,hm,ym,Ji,bm,cM,cR,lM,lR,dR=h(()=>{"use strict";Kr();C();Ue();O();Yc();aR=0,ym=!1,Ji=!1,bm=()=>{if(ym)return!0;let e=Ce();return a(e)?!1:e.value.syncStatus.status==="syncing"},cM=()=>{let e=Ta(ce().autoSyncIntervalMs),t=Date.now()-aR;return Math.max(0,e-t)},cR=()=>{hm||(hm=setTimeout(async()=>{if(hm=void 0,!!ut()){if(bm()){Ji=!0;return}Ji=!1,await lM()}},cM()))},lM=async()=>{if(y().readOnly||y().timeMode==="peek"||y().timeMode==="replay")return c("Cannot auto-sync while peeking");if(!ut())return c("Cannot auto-sync before state is initialized");if(bm())return Ji=!0,c("Sync already in progress");ym=!0,aR=Date.now(),T({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Kc({reposMinIntervalMs:6e4})}finally{ym=!1,Ji&&cR()}},lR=()=>{ut()&&(Ji=!0,!bm()&&cR())}});var uR,X,vm=h(()=>{"use strict";O();Qr();uR=e=>{let{context:t}=y().contextNode;if(!t)return X.None;switch(e){case I.EXIT:return X.Exit;case I.EXPORT:return X.Export;case I.INIT:return X.Init;case I.OPEN:return X.OpenProject;case I.DELETE:return X.Delete;case I.EDIT:return X.Edit;case I.COMMENT:return X.Comment;case I.HELP:return X.ViewHelp;case I.RE_OPEN_ISSUE:return X.ReopenIssue;case I.CLOSE_ISSUE:return X.CloseIssue;case I.TAG:return X.TagTicket;case I.UNTAG:return X.UntagTicket;case I.ASSIGN:return X.AssignUserToTicket;case I.UNASSIGN:return X.UnassignUserFromTicket;case I.NEW:return X.NewItem;case I.FILTER:return X.Filter;case I.MOVE:return X.Move;case I.PEEK:return X.Peek;case I.REPLAY:return X.Replay;case I.CONFIG:return X.Config;case I.YANK:return X.Yank;case I.SYNC:return X.Sync;default:return X.None}},X={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 mR}from"ink";import pR,{useEffect as fR,useState as dM}from"react";var gR,rn,us=h(()=>{"use strict";O();et();gR={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "],identity:["\u276F "]},rn=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Je(),r=gR[n]??gR.default,[o,s]=dM(0);if(fR(()=>{s(0)},[r]),fR(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return pR.createElement(mR,null,t);let i=r[o]??r[0]??t;return pR.createElement(mR,{color:M.accent,dimColor:o===1},i)}});import{Box as Rm,Text as uM}from"ink";import Xc from"react";var mM,on,go=h(()=>{"use strict";et();mM=(e,t,n,r)=>{let o=u=>Math.max(1,e[u]??1),s=n,i=n+1,l=o(n);for(;i<t&&l+o(i)<=r;)l+=o(i),i++;for(;s>0&&l+o(s-1)<=r;)s--,l+=o(s);return{start:s,end:i}},on=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),l=Math.max(1,Math.ceil(r)),u=Math.max(0,Math.min(n,e.length-1)),p=Math.max(1,Math.floor(i/l)),m=Math.max(0,e.length-p),{start:f,end:g}=o?mM(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,g-f),E=e.slice(f,g),R=e.length>b,w=i,S=R?Math.max(1,Math.floor(b/e.length*w)):w,A=Math.max(0,w-S),L=Math.max(1,e.length-b),P=R?Math.floor(f/L*A):0;return Xc.createElement(Rm,{flexDirection:"row",height:i,width:"100%"},Xc.createElement(Rm,{flexDirection:"column",flexGrow:1,height:i},E),Xc.createElement(Rm,{flexDirection:"column",width:1,height:w},Array.from({length:w}).map((B,q)=>Xc.createElement(uM,{key:q,color:R&&q>=P&&q<P+S?M.accent:M.secondary},R?"\u2502":" "))))}});var hR,xm,pM,Jc,Em=h(()=>{"use strict";O();pM=()=>{let{eventLog:e=[]}=y();if(xm&&hR===e)return xm;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return hR=e,xm=t,t},Jc=e=>pM().has(e)});import{Text as fM}from"ink";import gM from"react";var ms,Qc=h(()=>{"use strict";Cn();ge();Em();ct();ms=({id:e,isSelected:t,maxWidth:n})=>{let r=N.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:zr(o,n);return gM.createElement(fM,{underline:t,color:it(o)},"@"+s,Jc(e)?"":"\u2197")}});import{Text as hM}from"ink";import yM from"react";var Zc,Sm=h(()=>{"use strict";ge();et();Cn();ct();Zc=({id:e,isSelected:t,maxWidth:n})=>{let r=N.getTag(e);if(!r)return;let o=n===void 0?r.name:zr(r.name,n);return yM.createElement(hM,{underline:t,backgroundColor:it(r.name),color:M.secondary}," "+o+" ")}});import{useEffect as bM,useState as vM}from"react";var RM,yR,el,Qi,xM,EM,ps,tl=h(()=>{"use strict";Cn();RM=80,yR=1400,el=new Set,Qi=null,xM=e=>(el.add(e),Qi||(Qi=setInterval(()=>{for(let t of el)t()},RM)),()=>{el.delete(e),el.size===0&&Qi&&(clearInterval(Qi),Qi=null)}),EM=()=>{let e=Date.now()%yR/yR;return e<.5?e*2:(1-e)*2},ps=e=>{let[,t]=vM(0);return bM(()=>{if(e)return xM(()=>t(n=>n+1))},[e]),Bf(EM())}});import{Box as fs,Text as gs}from"ink";import Pt from"react";var SM,bR,IM,CM,vR,RR=h(()=>{"use strict";ge();et();ct();Em();rt();jo();Qc();Sm();tl();SM=(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),zr(e.slice(o).trim(),n)]},bR=3,IM=2,CM=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let i=e.length-o-1,l=i>0?String(i).length+1:0;if(r+s.width+l>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},vR=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=ps(r),s=e-4,i=s-7-1,[l,u]=SM(ye(t.title),i,s),p=u?null:zr(ye(t.props.description),s)||null,m=Tn(t),f=Mn(t).map(S=>({...S,name:S.name})),g=Math.max(1,s-bR),b=N.getCommentsByIssue(t.id),E=b.length?String(b.length).length+2+1:0,{shown:R,hidden:w}=CM([...m.map(S=>({id:S.id,isTag:!0,width:Math.min(S.name.length,g)+bR})),...f.map(S=>({id:S.id,isTag:!1,width:Math.min(S.name.length,g)+IM+(Jc(S.id)?0:1)}))],s-E);return Pt.createElement(fs,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?M.accent:M.secondary,justifyContent:"space-between"},Pt.createElement(fs,{paddingLeft:1,paddingRight:1,flexDirection:"column"},Pt.createElement(fs,{justifyContent:"space-between"},Pt.createElement(gs,{color:M.primary},l),Pt.createElement(gs,{color:M.secondary2,dimColor:!0},Y(t.id))),u&&Pt.createElement(gs,{color:M.primary},u),p&&Pt.createElement(gs,{color:M.secondary2,dimColor:!0},p)),Pt.createElement(fs,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},Pt.createElement(fs,{flexDirection:"row"},R.map(S=>Pt.createElement(fs,{paddingRight:1,key:S.id},S.isTag?Pt.createElement(Zc,{id:S.id,maxWidth:g}):Pt.createElement(ms,{id:S.id,maxWidth:g}))),w>0&&Pt.createElement(gs,{color:M.secondary2,dimColor:!0},"+",w)),b.length>0&&Pt.createElement(gs,{color:M.accent},"[",b.length,"]")))}});import{Box as ho,Text as Zi}from"ink";import zt from"react";var wM,xR,ER=h(()=>{"use strict";$e();ge();et();Cn();us();tl();wM=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,xR=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let l=ps(s),u=(r.props.tags??[]).map(B=>N.getTag(B)).filter(B=>!!B),p=(r.props.assignees??[]).map(B=>N.getContributor(B)).map(B=>B&&{...B,name:B.name}).filter(B=>!!B),m=1,f=u.length*(1+m),g=p.length*(2+m),b=u.map(B=>zt.createElement(ho,{key:B.id,paddingRight:m},zt.createElement(Zi,{color:it(B.name)},"\u25A0"))),E=p.map(B=>zt.createElement(ho,{key:B.id,paddingRight:m},zt.createElement(Zi,{color:ed(B.name)},"@"+B.name.at(0)))),R=s?l:o?M.accent:i===x.MOVE?M.secondary:M.primary,w=N.getCommentsByIssue(r.id),S=w.length?String(w.length).length+2+m:0,A=w.length?zt.createElement(ho,{paddingRight:m},zt.createElement(Zi,{color:M.accent},"[",w.length,"]")):null,L=f+g+S,P=Math.max(1,n-t-L-(L>0?1:0));return zt.createElement(ho,{justifyContent:"space-between"},zt.createElement(ho,null,zt.createElement(ho,{width:t},o?zt.createElement(rn,{isSelected:!0}):zt.createElement(Zi,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),zt.createElement(Zi,{wrap:"truncate",color:R},wM(r.title,P))),zt.createElement(ho,null,b,E,A))}});import NM from"chalk";import{Box as Im,Text as AM}from"ink";import $n from"react";var TM,SR,IR=h(()=>{"use strict";pe();O();et();us();go();RR();ER();tl();TM=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:l})=>{let{renderedChildrenIndex:u,replay:p}=Je(),m=u[e.id]??[],f=p?new Set(p.flashNodeIds):null,g=f?.has(e.id)??!1,b=ps(g),E=`${e.title} ${NM.hex(M.secondary2).dim("("+m.length+")")}`,R=3,w=o?1:5,S=s&&i===-1,A=n-3-(o?1:0)-(S?2:0),L=Math.max(2,String(m.length).length+1),P=r-R-1,B=$n.createElement(Im,{borderStyle:"round",borderColor:M.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},$n.createElement(rn,{isSelected:t}),$n.createElement(AM,{bold:!0,color:g?b:t?M.accent:M.primary},E," ",e.readonly?"\u{1F512}":"")),q=(Q,te)=>{let we=s&&i===te;if(!W(Q))return null;let $=f?.has(Q.id)??!1;return o?$n.createElement(xR,{key:Q.id,index:te,labelWidth:L,width:A,ticket:Q,isSelected:we,isFlashing:$,mode:l}):$n.createElement(vR,{key:Q.id,width:A,ticket:Q,isSelected:we,isFlashing:$})};return $n.createElement(Im,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?M.accent:M.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},B,$n.createElement(Im,null,m.length>0&&$n.createElement(on,{selectedIndex:i,height:P,itemHeight:w},m.map(q)),S&&$n.createElement(rn,{isSelected:!0})))},SR=$n.memo(TM)});var CR,wR,NR,nl=h(()=>{"use strict";Er();CR=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},wR=(e,t,n)=>We.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0}),NR=e=>e.action==="add.issue.comment"});var Tr,ea=h(()=>{"use strict";Tr=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 hs,Text as sr}from"ink";import ft,{useEffect as MM,useMemo as kM,useRef as LM}from"react";import{decodeTime as AR}from"ulid";function MR({ticket:e,width:t,height:n}){let r=kM(()=>OM(e),[e]),o=LM([]);MM(()=>(TR(o.current),o.current=DM(e,r),()=>{TR(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Je(),l=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?ft.createElement(hs,{flexDirection:"column",width:t,height:n,padding:1},ft.createElement(sr,{color:M.primary},"No attachments yet."),ft.createElement(hs,{paddingTop:1},ft.createElement(sr,{color:M.primary},"Attach images from the browser GUI"),ft.createElement(sr,{color:M.accent}," epiq gui "),ft.createElement(sr,{color:M.primary},"by dropping or pasting them."))):ft.createElement(hs,{flexDirection:"column",width:t,height:n},ft.createElement(hs,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:M.secondary,borderStyle:"single",paddingBottom:1},ft.createElement(sr,{color:M.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),ft.createElement(on,{height:l,itemHeight:2,selectedIndex:s},r.map((p,m)=>{let f=m===s,g=p.name.length>u?p.name.slice(0,u-1)+"\u2026":p.name;return ft.createElement(hs,{key:p.id,flexDirection:"row",paddingX:1,paddingBottom:1},ft.createElement(sr,{color:M.accent},f?"\u276F ":" "),ft.createElement(hs,{paddingLeft:1},ft.createElement(sr,{color:M.secondary2},`#${m+1} `),ft.createElement(sr,{color:f?M.accent:M.primary},g),ft.createElement(sr,{color:M.secondary2}," "+FM(p.bytes)+" "+Tr(gt(p.id)))))})))}var PM,OM,TR,_M,DM,FM,kR=h(()=>{"use strict";Lt();ht();ea();pe();C();ge();Er();O();et();wr();go();PM=e=>ke(e,"attachments"),OM=e=>N.getAttachmentsByIssue(e.id).sort((t,n)=>AR(t.id)-AR(n.id)),TR=e=>{for(let t of e)N.deleteNode(t.id)},_M=(e,t,n)=>We.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),DM=(e,t)=>{let n=N.getNode(PM(e.id));if(!n||!at(n))return[];let r=t.map((o,s)=>_M(o,s,n.id)).map(o=>N.createNode(o)).filter(Vt).map(({value:o})=>o).filter(at);return t.length>0&&y().selectedIndex<0&&V.navigate({contextNode:n,selectedIndex:0}),r},FM=e=>`${Math.max(1,Math.round(e/1024))} KB`});var BM,ta,$M,jM,UM,HM,rl,Cm,PR,LR,OR,ol=h(()=>{"use strict";Nc();BM=(e,t)=>{let n=Math.max(1,Math.floor(t)),r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[""];let o=[],s="";for(let i of r){let l=i;for(;l.length>n;)s&&(o.push(s),s=""),o.push(l.slice(0,n)),l=l.slice(n);s?s.length+1+l.length<=n?s=`${s} ${l}`:(o.push(s),s=l):s=l}return s&&o.push(s),o},ta=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)},$M=/!\[([^\]]*)\]\([^)]*\)/g,jM=e=>e.replace($M,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),UM=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),HM=4,rl=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(HM)),Cm=e=>{let t=!1;return e.map(rl).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=Bi(n);if(r)return{kind:"caption",text:Fu(r)};let o=jM(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:ta(s[1]??"")}:{kind:"text",spans:ta(o)}})},PR=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],LR=(e,t)=>{let n=[];for(let r of Cm(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 PR(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of BM(UM(r.spans),t))n.push({kind:r.kind,spans:ta(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},OR=(e,t)=>{let n=Bi(e),r=n?xb(e):null;if(!n||r===null)return LR(Du(e).split(`
98
- `),t);let o=Eb(e),s=r.split(`
99
- `).map(rl),i=n.side===n.endSide?n.start:void 0,l=i===void 0?0:String(i+s.length-1).length+3;return[...o?[...LR(o.split(`
100
- `),t),{kind:"blank"}]:[],{kind:"caption",text:Fu(n)},...s.flatMap((u,p)=>PR(u,Math.max(1,t-l)).map((m,f)=>({kind:"code",text:m,number:i===void 0||f>0?void 0:i+p})))]}});import{Box as _R,Text as yo}from"ink";import sn from"react";var DR,wm,FR,Nm=h(()=>{"use strict";et();DR=({spans:e,bold:t,wrap:n})=>sn.createElement(yo,{color:M.primary,bold:t,wrap:n},e.map((r,o)=>r.code?sn.createElement(yo,{key:o,color:M.yellow},r.text):sn.createElement(yo,{key:o},r.text))),wm=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return sn.createElement(yo,null," ");case"fence":return sn.createElement(yo,{color:M.secondary2},"```");case"caption":return sn.createElement(yo,{color:M.accent,wrap:r},e.text);case"heading":return sn.createElement(DR,{spans:e.spans,bold:!0,wrap:r});case"text":return sn.createElement(DR,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return sn.createElement(yo,{backgroundColor:M.secondary,color:M.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},FR=({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 sn.createElement(_R,{flexDirection:"column"},e.map((o,s)=>sn.createElement(_R,{key:s},sn.createElement(wm,{line:o,width:t,gutter:r}))))}});import{Box as Mr,Text as kr}from"ink";import Ye,{useEffect as WM,useMemo as BR,useRef as GM}from"react";import{decodeTime as $R}from"ulid";function UR({ticket:e,width:t,height:n}){let r=BR(()=>VM(e),[e]),o=GM([]);WM(()=>(jR(o.current),o.current=KM(e,r),()=>{jR(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Je(),l=Math.max(1,n-4),u=Math.max(20,t-8),p=BR(()=>r.map(f=>{let g=OR(f.md,u);return g.length>0?g:[{kind:"blank"}]}),[r,u]),m=p.map(f=>f.length+qM);return r.length===0?Ye.createElement(Mr,{flexDirection:"column",width:t,height:n,padding:1},Ye.createElement(kr,{color:M.primary},"No comments yet."),Ye.createElement(Mr,{paddingTop:1},Ye.createElement(kr,{color:M.primary},"Use"),Ye.createElement(kr,{color:M.accent}," :comment "),Ye.createElement(kr,{color:M.primary},"to add the first one."))):Ye.createElement(Mr,{flexDirection:"column",width:t,height:n},Ye.createElement(Mr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:M.secondary,borderStyle:"single",paddingBottom:1},Ye.createElement(kr,{color:M.secondary2},"Comments (",r.length,") ")),Ye.createElement(on,{height:l,itemHeights:m,selectedIndex:s},r.map((f,g)=>{let b=g===s;return Ye.createElement(Mr,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:M.secondary,borderStyle:"single"},Ye.createElement(Mr,{flexDirection:"row",paddingBottom:1},Ye.createElement(kr,{color:M.accent},b?"\u276F ":" "),Ye.createElement(Mr,{paddingLeft:1},Ye.createElement(kr,{color:M.secondary2},`#${g+1} `),Ye.createElement(ms,{id:f.authorId}),Ye.createElement(kr,{color:M.secondary2}," "+Tr(gt(f.id))))),Ye.createElement(Mr,{paddingLeft:3,paddingBottom:1},Ye.createElement(FR,{lines:p[g]??[],width:u})))})))}var qM,zM,VM,jR,KM,HR=h(()=>{"use strict";Lt();ht();ea();pe();C();ge();O();et();wr();Qc();go();nl();ol();Nm();qM=4,zM=e=>ke(e,"comments"),VM=e=>N.getCommentsByIssue(e.id).sort((t,n)=>$R(t.id)-$R(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,md:t.md})),jR=e=>{for(let t of e)N.deleteNode(t.id)},KM=(e,t)=>{let n=N.getNode(zM(e.id));if(!n||!at(n))return[];let r=t.map((o,s)=>wR(o,s,n.id)).map(N.createNode).filter(Vt).map(({value:o})=>o).filter(Vs);return t.length>0&&y().selectedIndex<0&&V.navigate({contextNode:n,selectedIndex:0}),r}});var sl,ys,Am=h(()=>{"use strict";C();Er();O();is();ge();sl=(e,t,n)=>{let r=[],o=dc(()=>{for(let s=0;s<t;s++){let i=qt(BigInt(s+1));if(!Vt(i))continue;let l=N.createNode(We.text({id:n(s),name:`Line ${s+1}`,parentNodeId:e,rank:i.value,readonly:!0,isVirtual:!0}));Vt(l)&&r.push(l.value)}});return a(o)&&logger.error(`Line nodes: ${o.message}`),r},ys=e=>{N.deleteNodes(e.map(t=>t.id))}});import{useSyncExternalStore as YM}from"react";var al,il,Tm,WR,Mm,cl,GR,bo,km,qR,Lr,ll=h(()=>{"use strict";O();al=null,il=null,Tm=new Set,WR=()=>{for(let e of Tm)e()},Mm=e=>{al=e,WR()},cl=()=>al,GR={mark:null},bo=e=>{il=e,GR={mark:e},WR()},km=e=>il&&il.sha===e?il.row:null,qR=()=>YM(e=>(Tm.add(e),()=>{Tm.delete(e)}),()=>GR),Lr=()=>{let{contextNode:e}=y();return al&&al.sha===e.id?e.id:null}});var zR=h(()=>{"use strict"});import{Box as xn,Text as ir}from"ink";import Be,{useEffect as Lm,useMemo as VR,useRef as JM,useState as QM}from"react";import ZM from"string-width";function JR({ticket:e,sha:t,repo:n,subject:r,width:o,height:s}){let[i,l]=QM({state:"loading"});Lm(()=>{let P=!0;return l({state:"loading"}),_u({sha:t,repo:n}).then(B=>{P&&l(a(B)?{state:"failed",message:B.message}:{state:"loaded",rows:ju($u(B.value))})}),()=>{P=!1}},[t,n]);let u=i.state==="loaded"?i.rows:null,p=u!==null&&u.length>4e3,m=JM([]);Lm(()=>(ys(m.current),m.current=u&&!p?sl(t,u.length,P=>Pm(t,P)):[],()=>{ys(m.current),m.current=[]}),[t,u,p]),Lm(()=>(Mm(u?{sha:t,rows:u}:null),bo(null),()=>{Mm(null),bo(null)}),[t,u]);let{selectedIndex:f}=Je(),{mark:g}=qR(),b=VR(()=>u?Uu(u,N.getCommentsByIssue(e.id),t):new Set,[u,t,e]),E=g&&g.sha===t?g.row:null,R=P=>E!==null&&P>=Math.min(E,f)&&P<=Math.max(E,f),w=VR(()=>u?Math.max(5,u.reduce((P,B)=>Math.max(P,XR(B).length),0)+2):5,[u]),S=Math.max(1,s-4),A=Math.max(8,o-w-6);if(i.state!=="loaded")return Be.createElement(xn,{flexDirection:"column",width:o,height:s,padding:1},Be.createElement(ir,{color:M.primary},i.state==="loading"?"Reading the diff\u2026":`Could not read the diff: ${i.message}`));let L=P=>Be.createElement(xn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:M.secondary,borderStyle:"single",paddingBottom:1},Be.createElement(ir,{color:M.secondary2,wrap:"truncate-end"},Vr(`${t.slice(0,7)} ${r} \u2014 ${P}`,Math.max(8,o-6))));return i.rows.length===0?Be.createElement(xn,{flexDirection:"column",width:o,height:s},L("no changes"),Be.createElement(xn,{paddingX:1},Be.createElement(ir,{color:M.primary},"This commit changed no files."))):p?Be.createElement(xn,{flexDirection:"column",width:o,height:s},L("too large to draw here"),Be.createElement(xn,{paddingX:1,flexDirection:"column"},Be.createElement(ir,{color:M.primary},`${i.rows.length.toLocaleString()} lines of diff.`),Be.createElement(ir,{color:M.secondary2},"Press o to open it in your editor."))):Be.createElement(xn,{flexDirection:"column",width:o,height:s},L(E===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"),Be.createElement(on,{scrollByOne:!0,height:S,selectedIndex:f,itemHeight:1},i.rows.map((P,B)=>{let q=B===f,Q=ek(P.kind);if(P.kind==="file")return Be.createElement(xn,{key:Pm(t,B),paddingX:1},Be.createElement(ir,{backgroundColor:M.secondary,color:q?M.accent:Q,bold:!0,wrap:"truncate-end"},YR(` ${Vr(KR(P.text),A)}`,A+w+1)));let te=R(B),we=`${tk(P.kind)}${Vr(KR(P.text),A)}`;return Be.createElement(xn,{key:Pm(t,B),paddingX:1},Be.createElement(xn,{flexShrink:0},Be.createElement(ir,{color:q||te?M.accent:M.secondary2,dimColor:!q&&!te,wrap:"truncate-end"},`${q?"\u276F":"\xA0"}${te?"\u258C":"\xA0"}${XR(P).padStart(w-2,"\xA0")}`)),Be.createElement(xn,{flexShrink:0},Be.createElement(ir,{color:M.yellow,wrap:"truncate-end"},b.has(B)?"\u2502":"\xA0")),Be.createElement(ir,{color:q?M.accent:Q,backgroundColor:q||te?M.secondary:void 0,wrap:"truncate-end"},q||te?YR(we,A+1):we))})))}var Pm,KR,ek,YR,tk,XR,QR=h(()=>{"use strict";Cr();ge();C();Am();ll();O();et();zR();ol();ct();go();Pm=(e,t)=>`${e}::patch::${t}`,KR=e=>rl(e).replace(/[\x00-\x1f\x7f-\x9f]/g,"\uFFFD"),ek=e=>{switch(e){case"added":return M.green;case"removed":return M.red;case"hunk":return M.accent;case"file":return M.primary;default:return M.secondary2}},YR=(e,t)=>{let n=ZM(e);return n>=t?e:e+"\xA0".repeat(t-n)},tk=e=>e==="added"?"+":e==="removed"?"-":" ",XR=e=>e.kind==="file"||e.kind==="hunk"||e.kind==="note"||e.newLine===void 0?"":String(e.newLine)});import{Box as vo,Text as En}from"ink";import ze,{useEffect as ZR,useRef as nk,useState as rk}from"react";function tx({ticket:e,width:t,height:n}){let[r,o]=rk({state:"loading"}),s=Y(e.id);ZR(()=>{let R=!0;return o({state:"loading"}),Ai({ref:s}).then(w=>{if(!R)return;let S=Mt();o(a(w)?{state:"failed",message:w.message}:{state:"loaded",commits:w.value,labels:a(S)?new Map:fu(S.value)})}),()=>{R=!1}},[s]);let i=nk([]),l=r.state==="loaded"?r.commits:null,u=r.state==="loaded"?r.labels:null;ZR(()=>(ex(i.current),i.current=l?ik(e,l):[],()=>{ex(i.current),i.current=[]}),[e,l]);let{selectedIndex:p,contextNode:m}=Je(),f=l?.find(R=>R.sha===m.id)??null,b=Math.max(1,n-4),E=Math.max(12,t-34);return r.state!=="loaded"?ze.createElement(vo,{flexDirection:"column",width:t,height:n,padding:1},ze.createElement(En,{color:M.primary},r.state==="loading"?"Reading commits\u2026":`Could not read commits: ${r.message}`)):f?ze.createElement(JR,{ticket:e,sha:f.sha,repo:f.repo,subject:f.subject,width:t,height:n}):r.commits.length===0?ze.createElement(vo,{flexDirection:"column",width:t,height:n,padding:1},ze.createElement(En,{color:M.primary},"No commits reference this ticket."),ze.createElement(vo,{paddingTop:1},ze.createElement(En,{color:M.primary},"Commits are matched by the"),ze.createElement(En,{color:M.accent},` ${s} `),ze.createElement(En,{color:M.primary},"prefix on their subject line."))):ze.createElement(vo,{flexDirection:"column",width:t,height:n},ze.createElement(vo,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:M.secondary,borderStyle:"single",paddingBottom:1},ze.createElement(En,{color:M.secondary2},`Diff (${r.commits.length}) \u2014 enter to read, o to open in your editor `)),ze.createElement(on,{height:b,itemHeight:2,selectedIndex:p},r.commits.map((R,w)=>{let S=w===p,A=R.subject.length>E?R.subject.slice(0,E-1)+"\u2026":R.subject;return ze.createElement(vo,{key:R.sha,flexDirection:"row",paddingX:1,paddingBottom:1},ze.createElement(En,{color:M.accent},S?"\u276F ":" "),ze.createElement(vo,{paddingLeft:1},ze.createElement(En,{color:M.secondary2},`${R.sha.slice(0,7)} `),R.repo&&ze.createElement(En,{color:M.secondary2},`[${u?.get(R.repo)??js(R.repo)}] `),ze.createElement(En,{color:S?M.accent:M.primary},A),ze.createElement(En,{color:M.secondary2},` ${ak(R)} ${Tr(R.time)}`)))})))}var ok,ex,sk,ik,ak,nx=h(()=>{"use strict";Lt();Cr();pe();C();ge();Er();O();et();ea();rt();wr();QR();go();ok=e=>ke(e,"diff"),ex=e=>{for(let t of e)N.deleteNode(t.id)},sk=(e,t,n)=>We.field({id:e.sha,name:e.subject,parentNodeId:n,rank:String(t).padStart(6,"0"),childRenderAxis:"vertical",isVirtual:!0}),ik=(e,t)=>{let n=N.getNode(ok(e.id));if(!n||!at(n))return[];let r=t.map((o,s)=>sk(o,s,n.id)).map(o=>N.createNode(o)).filter(Vt).map(({value:o})=>o).filter(at);return t.length>0&&y().selectedIndex<0&&y().contextNode.id===n.id&&V.navigate({contextNode:n,selectedIndex:0}),r},ak=e=>`+${e.insertions} -${e.deletions}`});import{Box as dl,Text as ck}from"ink";import ar from"react";var rx,ox=h(()=>{"use strict";pe();ge();Xo();O();et();Qc();us();Sm();rx=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Je(),{title:o}=t,s=t.parentNodeId?N.getNode(t.parentNodeId):void 0,i=s&&W(s)?o===Me.ASSIGNEES?s.props.assignees??[]:o===Me.TAGS?(s.props.tags??[]).filter(l=>N.getTag(l)):[]:[];return ar.createElement(dl,{alignItems:"center",paddingTop:1},ar.createElement(dl,{minWidth:12},ar.createElement(rn,{isSelected:n}),ar.createElement(ck,{color:n?M.accent:M.secondary2},o,":")),ar.createElement(dl,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((l,u)=>{let p=r.id===t.id&&u===e;return ar.createElement(dl,{key:`${o}-${l}`,paddingRight:2,minHeight:1},ar.createElement(rn,{isSelected:p}),o===Me.ASSIGNEES?ar.createElement(ms,{isSelected:p,id:l}):o===Me.TAGS?ar.createElement(Zc,{isSelected:p,id:l}):null)})))}});var Om,sx,_m,Dm=h(()=>{"use strict";Om=e=>Math.max(5,String(Math.max(e,1)).length+3),sx=(e,t)=>Math.max(0,e-6-Om(t)),_m=(e,t=0,n=0)=>Math.max(1,e-5-2*t-(n>0?1+n:0))});import{Box as bs,Text as Fm}from"ink";import an,{useEffect as lk,useMemo as Bm,useRef as dk}from"react";var uk,ix,$m,ax=h(()=>{"use strict";Am();O();et();ct();Dm();us();go();Nm();ol();uk="\u2029",ix=(e,t)=>`${e}::inline-line::${t}`,$m=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:l}=Je(),u=Bm(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),p=Bm(()=>u.join("\0"),[u]),m=dk([]);lk(()=>(ys(m.current),m.current=sl(e,u.length,R=>ix(e,R)),()=>{ys(m.current),m.current=[]}),[e,p]);let f=Om(u.length),g=sx(s,u.length),E=Bm(()=>Cm(u).map(R=>{if(R.kind==="code"||R.kind==="caption")return{...R,text:Vr(R.text,g)};if(R.kind==="text"||R.kind==="heading"){let w=R.spans.map(S=>S.code?`\`${S.text}\``:S.text).join("");return{...R,spans:ta(Vr(w,g))}}return R}),[u,g]).map((R,w)=>{let S=l.id===e&&i===w;return an.createElement(bs,{key:ix(e,w)},an.createElement(bs,{flexShrink:0},an.createElement(Fm,{color:S?M.primary:M.secondary2,dimColor:!S},`${w+1} `.padStart(f,"\xA0"))),R.kind==="blank"?an.createElement(Fm,{backgroundColor:S?"gray":void 0},uk):an.createElement(bs,null,an.createElement(wm,{line:R,width:R.kind==="code"?g:0,wrap:"truncate-end"})))});return an.createElement(bs,{flexDirection:"column",paddingTop:1},an.createElement(bs,null,an.createElement(rn,{isSelected:o}),an.createElement(Fm,{color:o?M.accent:M.secondary2},t)),an.createElement(bs,{flexDirection:"row",borderStyle:"round",borderColor:M.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},an.createElement(on,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},E)))}});import{Box as vs,Text as mk}from"ink";import Ot,{useMemo as Rs}from"react";var pk,fk,gk,hk,yk,cx,lx=h(()=>{"use strict";pe();ge();O();et();nl();wr();kR();HR();us();nx();ox();ax();Dm();pk=e=>ke(e,"description"),fk=e=>ke(e,"comments"),gk=e=>ke(e,"history"),hk=e=>ke(e,"diff"),yk=e=>ke(e,"attachments"),cx=({ticket:e,height:t})=>{let n=Rs(()=>CR(e),[e]),{selectedIndex:r,contextNode:o}=Je(),s=process.stdout.columns||120,i=Rs(()=>pk(e.id),[e.id]),l=Rs(()=>fk(e.id),[e.id]),u=Rs(()=>gk(e.id),[e.id]),p=Rs(()=>hk(e.id),[e.id]),m=Rs(()=>yk(e.id),[e.id]),f=N.getAttachmentsByIssue(e.id).length,g=o.id===e.id,b=o.id===l||o.parentNodeId===l,E=o.id===u||o.parentNodeId===u,R=o.id===m||o.parentNodeId===m,w=o.id===p||o.parentNodeId===p,S=Ee(e.id);if(b){let ne=t-3;return Ot.createElement(vs,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ot.createElement(UR,{ticket:e,width:s,height:ne}))}if(R){let ne=t-3;return Ot.createElement(vs,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ot.createElement(MR,{ticket:e,width:s,height:ne}))}if(w){let ne=t-3;return Ot.createElement(vs,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ot.createElement(tx,{ticket:e,width:s,height:ne}))}if(E){let $=N.getNode(u),ne=$&&at($)?$.props.value??"":"",Ze=_m(t);return Ot.createElement(vs,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},$?Ot.createElement($m,{id:$.id,label:"Event log",text:ne,selected:!1,maxWidth:s,rows:Ze}):null)}let A=[u,p,l,m],L=$=>A.includes($),P=S.reduce(($,ne)=>zs(ne)?$+1:$,0),B=S.reduce(($,ne)=>L(ne.id)?$+1:$,0),q=S.findIndex($=>L($.id)),Q=_m(t,P,B),te=($,ne,Ze,_s)=>Ot.createElement(vs,{key:$.id,paddingTop:ne===q?1:0},Ot.createElement(rn,{isSelected:Ze}),Ot.createElement(mk,{backgroundColor:M.secondary,color:Ze?M.accent:M.primary},_s)),we=($,ne,Ze)=>$.id===i?Ot.createElement($m,{key:$.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:ne,maxWidth:s,rows:Q}):zs($)?Ot.createElement(rx,{key:$.id,parent:$,selected:ne,selectedIndex:r}):$.id===l?te($,Ze,ne,` Comments (${n}) \u203A\u203A `):$.id===m?te($,Ze,ne,` Attachments (${f}) \u203A\u203A `):$.id===u?te($,Ze,ne," History \u203A\u203A "):$.id===p?te($,Ze,ne," Diff \u203A\u203A "):null;return Ot.createElement(vs,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},S.map(($,ne)=>we($,g&&r===ne,ne)))}});import{Box as bk}from"ink";import ul from"react";var vk,dx,ux=h(()=>{"use strict";pe();IR();lx();vk=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:l})=>{let u=t.context,p=u===me.TICKET||u===me.FIELD_LIST||u===me.FIELD,m=u===me.BOARD||u===me.SWIMLANE,f=u===me.TICKET?t:r.find(w=>w.context===me.TICKET),g=Math.floor(l/3),b=Math.floor(l/Math.max(e.length,1)),E=Math.min(b,g),R=s==="dense";return ul.createElement(bk,{flexDirection:"row",height:i},m&&e.map((w,S)=>{let A=t.id===w.id,L=A?n:-1,P=t.context===me.BOARD&&n===S;return ul.createElement(SR,{key:w.id,height:i,width:E,swimlane:w,isSelected:P,isDense:R,isFocused:A,listSelectedIndex:L,mode:o})}),p&&f&&ul.createElement(cx,{height:i,ticket:f}))},dx=ul.memo(vk)});import mx from"node:fs";import Rk from"node:path";import xk from"react";import{render as Ek}from"ink";import{Writable as Sk}from"node:stream";var na,Ik,Ck,wk,Nk,px,fx=h(()=>{"use strict";ux();pe();C();O();oe();Ue();na=e=>String(e).padStart(2,"0"),Ik=e=>{let t=e.getUTCFullYear(),n=na(e.getUTCMonth()+1),r=na(e.getUTCDate()),o=na(e.getUTCHours()),s=na(e.getUTCMinutes()),i=na(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},Ck=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",wk=async(e,{width:t,height:n})=>{let r="",o=new Sk({write(i,l,u){let p=Nk(i.toString()).trimEnd();p.trim().length>0&&p.includes("\u256D")&&(r=p),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=Ek(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},Nk=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),px=async()=>{let{viewMode:e}=ce(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=y(),i=r.find(S=>S.context==="BOARD");if(!i)return c("No board found to export");let l=120,u=40,p=await wk(xk.createElement(dx,{height:u,width:l,swimlanes:(s[i.id]??[]).filter(S=>S!==void 0&&Gr(S)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:u});if(!p)return c("Failed to render board export");let m=Ma(process.cwd());if(a(m))return c("Unable to export, epiq root not found");let f=new Date,g=Ik(f),b=`board_${Ck(i.title)}_${g}.md`,E=Ug(m.value);mx.mkdirSync(E,{recursive:!0});let R=Rk.join(E,b),w=`# Board - ${i.title}
101
- Date: ${f.toISOString()}
102
-
103
- \`\`\`text
104
- ${p}
105
- \`\`\`
106
- `;return mx.writeFileSync(R,w,"utf8"),d("Exported board layout",R)}});import{useSyncExternalStore as GV}from"react";var jm,Ak,Tk,xs,Mk,Pr,ml=h(()=>{"use strict";C();Ak=new Set,Tk=()=>{for(let e of Ak)e()},xs=()=>{if(!jm)throw new Error("Ui state not initialized. Call initUiState() first.");return jm},Mk=e=>{let t=xs();return jm=e(t),Tk(),d("UX state updated",null)},Pr=e=>Mk(t=>({...t,...e}))});import{ulid as Um}from"ulid";var gx,kk,Lk,hx=h(()=>{"use strict";zu();H();H();fn();pe();C();Xo();ge();O();oe();Kn();Zt();gx=async e=>{let{contextNode:t,selectedIndex:n}=y(),r=Ee(t.id)[n];if(e.modifier===Ut.DESCRIPTION)return Lk();if(r&&Vs(r))return kk(e);if(e.modifier===Ut.TITLE){let o=be();if(a(o))return c("Unable to resolve user ID");let s=r;if(!s)return c("Missing node");if(s.readonly)return c("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return c("Provide a title");let l=await Ie();return a(l)?l:F([{id:Um(),action:"edit.title",payload:{id:s.id,name:i},...D(o.value)}],l.value)}return c("Unknown edit command")},kk=async e=>{let t=be();if(a(t))return c("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=y(),o=Ee(n.id)[r];if(!o||!Vs(o))return c("Select a comment first");if(o.readonly)return c("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return c("Unable to resolve comment issue");let i=y().nodes[s];if(!i||!W(i))return c("Unable to resolve comment issue");if(i.readonly)return c("Cannot edit readonly issue");let l=o.id.split(":").at(0)??"",u=N.getComment(l);if(!u||u.deleted)return c("Unable to resolve comment");if(u.issue!==i.id)return c("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return c("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let p=e.inputString.trim();if(!p)return c("Provide a comment");let m=await Ie();if(a(m))return m;let f=m.value;return F([{id:Um(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:p},...D(t.value)}],f)},Lk=async()=>{let e=be();if(a(e))return c("Unable to resolve user ID");let t=await Ie();if(a(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=y(),s=Ft([...r,o],"TICKET");if(a(s))return c("Edit target must be an issue");let i=s.value;if(!W(i))return c("Edit target must be an issue");if(i.readonly)return c("Cannot edit readonly issue");let l=Ee(i.id).find(f=>f.title===Me.DESCRIPTION);if(!l)return c("No target found");if(l.readonly)return c("Cannot edit readonly field");let u=i.props.description??"";if(typeof u!="string")return c("Selected field is not editable text");let p=Pb(u);if(a(p))return c("Failed to edit field");let m=p.value;return m===u?d("No changes made",null):F([{id:Um(),action:"edit.description",payload:{id:i.id,md:m},...D(e.value)}],n)}});import Hm from"node:fs";import Pk from"node:path";var yx,bx=h(()=>{"use strict";C();yt();yx=async e=>{let t=Pk.join(e,".gitignore"),n=Hm.existsSync(t)?Hm.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
107
- `).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 l=["# [epiq]: local hydrated state is never committed",...s].join(`
108
- `);return n=n.trimEnd()+`
109
-
110
- ${l}
111
- `,Hm.writeFileSync(t,n,"utf8"),z.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),d("Local epiq paths ignored",!0)}});import Ok from"node:fs";import Wm from"node:path";var _k,fe,pl,Dk,Fk,Gm=h(()=>{"use strict";bx();ka();tt();De();Xi();po();H();so();C();oe();Yt();um();_k=async e=>{let t=await G({cwd:e,args:["status","--porcelain"]});return a(t)?t:d("Checked git diff",t.value.stdout.split(`
112
- `).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},fe=(e,t)=>c(`[${e}] ${t}`),pl=async({cwd:e,user:t})=>{let n=$a(),r=await jt(e);if(a(r))return fe(1,r.message);let o=r.value,s=await xg(o);if(a(s))return fe(2,s.message);if(s.value)return fe(2,`Cannot initialize Epiq while a git operation is in progress: ${s.value}`);let i=await _k(o);if(a(i))return fe(2.5,i.message);if(i.value.length>0)return fe(3,`Cannot initialize Epiq with uncommitted changes (${i.value.join(", ")}). Commit or stash your changes first.`);if(ei(o))return fe(4,"Epiq project already initialized");let{userId:l,userName:u}=t;if(!l||!u)return fe(5,"Missing Epiq user id");let p=await Zv(o);if(a(p))return fe(6,p.message);let m=n.stateBranch,f=await _a({repoRoot:o,branch:m});if(a(f))return fe(6,f.message);if(f.value)return fe(6,`State branch already exists: ${m}`);let g=await Dk({repoRoot:o,stateBranch:m});if(a(g))return fe(6,g.message);if(g.value)return Fk({repoRoot:o,stateBranch:m});let b=await pm({repoRoot:o,stateBranchName:m});if(a(b))return fe(6,b.message);let E=Qs();if(a(E))return fe(7,E.message);let R=Wm.join(Yr(),n.projectId),w=await Ar({repoRoot:o,stateBranchRoot:R,stateBranchName:m});if(a(w))return fe(8,w.message);let S=Wm.join(R,".epiq");Ok.mkdirSync(S,{recursive:!0});let A=jv({userId:l,userName:u});if(a(A))return fe(9,A.message);for(let $I of A.value){let yf=gy({event:$I,rootDir:R});if(a(yf))return fe(9,yf.message)}let L=Rr({userId:l}),P=nc(R,L);if(a(P))return fe(9,P.message);let B=dm(R,n);if(a(B))return fe(9,B.message);let q=await Gc({stateBranchRoot:R,eventFileName:L});if(a(q))return fe(10,q.message);let Q=await Ne.stage({cwd:R,pathspec:[pt]});if(a(Q))return fe(10,Q.message);let te=await _o({cwd:R,message:"[epiq:init]"});if(a(te))return fe(10,te.message);let we=await yx(o);if(a(we))return fe(11,we.message);let $=Cd({repoRoot:o,fileContents:n});if(a($))return fe(12,$.message);let ne=await Ne.stage({cwd:o,pathspec:[".epiq/project.json",".gitignore"]});if(a(ne))return fe(13,ne.message);let Ze=await Ne.commit({cwd:o,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(a(Ze))return fe(13,Ze.message);let _s=[],gf=await G({cwd:o,args:["push","-u","origin","HEAD"]});a(gf)&&_s.push(`[init:14] ${gf.message}`);let hf=await Yi({repoRoot:o,stateBranchRoot:R});return a(hf)&&_s.push(`[init:15] ${hf.message}`),d("Project initialized",{repoRoot:o,projectId:n.projectId,stateBranch:m,stateBranchRoot:R,defaultEvents:A.value,warnings:_s})},Dk=async({repoRoot:e,stateBranch:t})=>{let n=await zn({repoRoot:e});if(a(n))return c(n.message);if(!n.value)return d("No remote",!1);let r=await Ks({repoRoot:e,branch:t});return a(r)?c(`Could not ask origin whether ${t} exists: ${r.message}`):r},Fk=async({repoRoot:e,stateBranch:t})=>{let n=await G({cwd:e,args:["fetch","origin",t]});if(a(n))return fe(6,n.message);let r=await G({cwd:e,args:["show",`origin/${t}:${pt}`]});if(a(r))return fe(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",`${pt} from a checkout that has it, for example:`,"",` git show origin/main:${pt} > ${pt}`,"","and commit it; every later boot then stamps the branch, and the next clone adopts it."].join(`
113
- `));let o;try{o=JSON.parse(r.value.stdout)}catch(E){return fe(6,`The identity on origin/${t} is not readable: ${E instanceof Error?E.message:String(E)}`)}let s=Cd({repoRoot:e,fileContents:o});if(a(s))return fe(12,s.message);let i=await Ne.stage({cwd:e,pathspec:[pt]});if(a(i))return fe(13,i.message);let l=await Ne.commit({cwd:e,message:"[epiq:adopt-project]",pathspec:[pt]});if(a(l))return fe(13,l.message);let u=Qs();if(a(u))return fe(7,u.message);let p=Wm.join(Yr(),o.projectId),m=await Ki({repoRoot:e,stateBranchName:t});if(a(m))return fe(8,m.message);let f=await Ar({repoRoot:e,stateBranchRoot:p,stateBranchName:t});if(a(f))return fe(8,f.message);let g=[],b=await G({cwd:e,args:["push","-u","origin","HEAD"]});return a(b)&&g.push(`[init:14] ${b.message}`),d("Adopted the project origin already holds",{repoRoot:e,projectId:o.projectId,stateBranch:o.stateBranch,stateBranchRoot:p,defaultEvents:[],warnings:g})}});var ra,vx,Rx=h(()=>{"use strict";Lt();Jr();H();C();Gm();he();Ue();O();ra=(e,t)=>c(`[${e}] ${t}`),vx=async()=>{re("");let e=ii();if(!e.isSetupDone||!e.userName)return ra(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let t=ce(),n=t.userName,r=t.userId;if(!r||!n)return ra(5,"Missing Epiq user id");let o=await pl({cwd:process.cwd(),user:{userId:r,userName:n}});if(a(o))return o;let s="Project initialized!";for(let g of o.value.warnings)s+=` Warn: ${g}`;let l=Qn(o.value.defaultEvents).filter(a);if(l.length>0)return ra(16,l.map(g=>g.message).join(`
114
- `));let u=Ce();if(a(u))return ra(16,u.message);let{rootNodeId:p,nodes:m}=u.value,f=m[p];return f?(V.navigate({contextNode:f,selectedIndex:0}),T({hasProjectDefinition:!0}),d(s,null)):ra(16,"Unable to resolve initialized root node")}});import{ulid as Bk}from"ulid";function zm(e){let t=Ex();if(a(t))return t;let{contextNode:n,nodes:r}=y();if(!n.parentNodeId)return c("Missing parent node id");let o=r[n.parentNodeId];if(!o)return c("Missing parent node");let s=_e(o.id),i=s.findIndex(({id:p})=>p===n.id);if(i<0)return c("Current node not found among siblings");let l=s[i+e];if(!l)return c("Missing sibling node");let u=Sx({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Ix(u.value)}function sa(e,t=1){let n=Ex();if(a(n))return n;let{contextNode:r,selectedIndex:o}=y(),s=_e(r.id),i=Math.min(Math.max(o+e*t,0),s.length-1),l=i===o?void 0:s[i];if(!l)return c("Missing sibling node");let u=Sx({id:n.value.id,parentId:r.id,position:{at:e===1?"after":"before",sibling:l.id}});return a(u)?u:Ix(u.value)}var xx,Sn,oa,Ex,qm,Sx,Ix,Vm=h(()=>{"use strict";H();H();C();nn();O();xx=null,Sn=()=>structuredClone(xx),oa=e=>{xx=e},Ex=()=>{let{contextNode:e,selectedIndex:t}=y(),r=_e(e.id)[t];return r?d("Resolved selected child",r):c("Target node not found")},qm=({id:e,parentId:t,position:n={at:"end"}})=>{let r=_e(t).filter(o=>o.id!==e);return Bc(r,n)},Sx=({id:e,parentId:t,position:n={at:"end"}})=>{let r=be();if(a(r))return c("Unable to resolve user ID");let o=qm({parentId:t,id:e,position:n});return a(o)?o:d("Created pending move state",{id:Bk(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Ix=e=>{oa(e);let t=xi(e,!0);return a(t)?t:d("Node moved successfully",t.value)}});import{ulid as $k}from"ulid";var Cx,Es,wx,Nx=h(()=>{"use strict";Lt();Vm();H();H();en();$e();C();nn();he();O();oe();Cx=()=>{let e=Sn();if(!e)return c("No pending move state");let t=e.payload.id,n=e.payload.parent,r=y().nodes[n];if(!r)return c("Move parent not found");let o=_e(n).findIndex(s=>s.id===t);return o===-1?c("Moved node not found among rendered children"):(V.navigate({contextNode:r,selectedIndex:o}),d("Synchronized navigation to moved node",null))},Es=(e,t="Moved preview")=>{if(a(e))return Sn()&&T({mode:x.MOVE}),e;let n=Cx();return a(n)?n:(T({mode:x.MOVE}),d(t,null))},wx=async()=>{let e=be();if(a(e))return c("Unable to resolve user ID");let{modifier:t}=le().commandMeta,{contextNode:n,selectedIndex:r}=y(),o=_e(n.id)[r];if(!o)return T({mode:x.DEFAULT}),c("No move target");if(t==="start"){if(o.readonly)return c("Target node is read-only");if(r===-1)return c("No item selected");if(!o.parentNodeId)return c("Target has no parent");let s=_e(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return c("Target not found among siblings");let l=s[i-1],u=s[i+1],p=u!=null?{at:"before",sibling:u.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},m=qm({parentId:o.parentNodeId,id:o.id,position:p});return a(m)?m:(oa({id:$k(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:m.value.rank},...D(e.value)}),T({mode:x.MOVE}),d("Move initialized",null))}if(t==="next")return Es(sa(1));if(t==="previous")return Es(sa(-1));if(t==="jump-next")return Es(sa(1,Gi));if(t==="jump-previous")return Es(sa(-1,Gi));if(t==="to-next")return Es(zm(1));if(t==="to-previous")return Es(zm(-1));if(t==="confirm"){let s=Sn();if(!s)return c("No pending move to confirm");let i=await Ie();if(a(i))return i;let l=F([s],i.value);if(a(l))return l;let u=Cx();return a(u)?u:(oa(null),T({mode:x.DEFAULT}),d("Moved item",null))}return t==="cancel"?(oa(null),T({mode:x.DEFAULT}),d("Cancelling move",null)):c("Invalid move modifier")}});import{monotonicFactory as jk,ulid as Uk}from"ulid";var Hk,fl,Km=h(()=>{"use strict";C();Hk=jk(),fl=({name:e,parent:t,rank:n,user:{userId:r}})=>{let o=Hk();return d("Created issue events",[{id:Uk(),userId:r,action:"add.issue",payload:{id:o,parent:t,name:e,rank:n}}])}});import{ulid as gl}from"ulid";var Ax,Tx=h(()=>{"use strict";Lt();Km();H();H();en();fn();C();ge();nn();O();oe();Ax=async(e,t)=>{let n=be();if(a(n))return c("Unable to resolve user ID");let r=await Ie();if(a(r))return r;let o=r.value;if(!t.inputString)return c(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:l}=y(),u=p=>{let m=F([p],o);if(a(m))return m;let f=N.getNode(m.value[0].result.id);if(!f)return c("Created node not found");if(!f.parentNodeId)return m;let g=N.getNode(f.parentNodeId);return g?(V.navigate({contextNode:g,selectedIndex:N.getSiblings(f.parentNodeId).findIndex(({id:b})=>b===f.id)}),m):c("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:p}=y(),m=N.getNode(p);if(!m)return c("Workspace not found");let f=nr(m.id,n.value,o);return a(f)?f:u({id:gl(),action:"add.board",payload:{id:gl(),name:t.inputString,parent:m.id,rank:f.value},...D(n.value)})}if(t.modifier==="swimlane"){let p=Ft(s,"BOARD");if(a(p))return c("Unable to add swimlane in this context");let m=nr(p.value.id,n.value,o);return a(m)?m:u({id:gl(),action:"add.swimlane",payload:{id:gl(),name:t.inputString,parent:p.value.id,rank:m.value},...D(n.value)})}if(t.modifier==="issue"){let p=Ee(i.id)[l],m=i.context==="SWIMLANE"?i:i.context==="BOARD"&&p?.context==="SWIMLANE"?p:(()=>{let A=Ft(s,"SWIMLANE");return a(A)?null:A.value})();if(!m)return c("Unable to add issue in this context");let f=nr(m.id,n.value,o);if(a(f))return f;let g=fl({name:t.inputString,parent:m.id,rank:f.value,user:n.value});if(a(g))return g;let b=g.value,E=F([...b],o);if(a(E))return E;if(!E.value[0])return c("Issue creation failed");let S=b.find(A=>A.action==="add.issue")?.payload.id;return S?(V.navigate({contextNode:m,selectedIndex:N.getSiblings(m.id).findIndex(({id:A})=>A===S)}),d("Issue created",null)):c("Unable to determine ticket id")}return d("Success",null)}});import ia from"node:fs";import Wk from"node:path";import{z as Ro}from"zod";var aa,Gk,qk,zk,Mx,Vk,kx,Lx,Px,Ym=h(()=>{"use strict";C();Yt();he();Vu();oe();aa="command-history.json",Gk=20,qk=Ro.object({projectId:Ro.string().min(1),commands:Ro.array(Ro.string()),lastUsedAt:Ro.number().finite()}),zk=Ro.object({projects:Ro.array(qk)}),Mx=()=>{let e=$i();return a(e)?e:d("Resolved command history path",Wk.join(e.value,aa))},Vk=()=>{try{let e=Ae(process.cwd());return a(e)?null:e.value}catch{return null}},kx=e=>{if(!ia.existsSync(e))return d("No command history recorded",{state:"read",projects:[]});let t;try{t=ia.readFileSync(e,"utf8")}catch(o){return c(`Unable to read ${aa}: ${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 ${aa}: ${o instanceof Error?o.message:String(o)}`})}let r=zk.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 ${aa} shape: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`})},Lx=({root:e})=>{let t=Nn(e);if(a(t))return c(t.message);let n=Mx();if(a(n))return n;let r=kx(n.value);if(a(r))return r;let o=r.value;if(o.state==="corrupt")return c(o.reason);let s=o.projects.find(i=>i.projectId===t.value);return d("Read command history",s?.commands.slice(0,Ui)??[])},Px=({commands:e,root:t=Vk(),now:n=Date.now()})=>{if(t===null)return d("No project; command history not stored",null);let r=Nn(t);if(a(r))return c(r.message);let o=Mx();if(a(o))return o;let s=o.value,i=kx(s);if(a(i))return i;let l=i.value,u=l.state==="read"?l.projects:[],p=[{projectId:r.value,commands:e.slice(0,Ui),lastUsedAt:n},...u.filter(f=>f.projectId!==r.value)].sort((f,g)=>g.lastUsedAt-f.lastUsedAt).slice(0,Gk),m=`${s}.${process.pid}.tmp`;try{ia.writeFileSync(m,JSON.stringify({projects:p},null,2)+`
115
- `,"utf8"),ia.renameSync(m,s)}catch(f){try{ia.rmSync(m,{force:!0})}catch{}return c(`Unable to write ${aa}: ${f instanceof Error?f.message:String(f)}`)}return d("Stored command history",null)}});var Kk,_x,Yk,Ox,Dx,Xk,Jk,Fx,Bx=h(()=>{"use strict";wn();tt();De();Xi();Yc();bc();Vc();Ym();Bo();po();H();kn();C();Yt();he();O();zi();oe();Hc();Kk=e=>e.some(t=>t.action==="init.workspace"),_x=async(e,t)=>{let n=lt(e);return a(n)?c(n.message):Xs({cwd:t,branch:n.value})},Yk=e=>{let t=Ae(process.cwd());if(a(t))return!1;let n=xe({repoRoot:t.value});return!a(n)&&n.value===e},Ox=!1,Dx=async e=>{Ox=!0;try{return await Xk(e)}finally{Ox=!1}},Xk=async e=>{let t=xe({repoRoot:e});if(a(t))return cs(3,t.message);let n=t.value,r=await Ar({repoRoot:e,stateBranchRoot:n,stateBranchName:$a().stateBranch});if(a(r))return cs(3,r.message);let o=kt(n),s=vn(n);if(a(s))return cs(3,s.message);if(!Kk(s.value.events)){let f=await Ni({worktreeRoot:n,operation:"boot pull",fn:()=>qc(n,()=>_x(e,n))});if(a(f)?logger.info(3,f.message):f.value===null?logger.info(3,"Another process holds the state worktree, skipped pull"):a(f.value)&&logger.info(3,f.value.message),o=kt(n),s=vn(n),a(s))return cs(3,s.message)}let{events:i,unreadable:l}=s.value,u=Fn(i,l);if(a(u))return cs(4,u.message);Ko(n,o),T({hasProjectDefinition:!0,hasInitializingEvents:!!i.length});let p=oi({root:e});a(p)&&logger.info(p.message);let m=Lx({root:e});return a(m)&&logger.info(m.message),mv(a(m)?[]:m.value),d("Loaded project",void 0)},Jk=async e=>{let t=xe({repoRoot:e});if(a(t))return c(t.message);let n=t.value,r=await zn({repoRoot:n});if(a(r))return c(r.message);if(!r.value)return d("No remote to pull",void 0);let o=await Ni({worktreeRoot:n,operation:"boot pull",fn:()=>qc(n,()=>(as("Pulling"),_x(e,n)))});if(a(o))return qe(o.message);if(o.value===null)return d("Another process holds the state worktree",void 0);let s=o.value;if(a(s))return Ys(s.message)?(Uc("Offline"),d("Offline",void 0)):qe(s.message);if(!s.value)return fo("Already synced"),d("Already synced",void 0);if(!Yk(n))return d("Project changed during the pull",void 0);let i=gm(n);return a(i)?i:(fo("Pulled"),d("Pulled and reloaded",void 0))},Fx=e=>{Jk(e).then(t=>{a(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${Wv(t)}`)})}});import Qk from"node:os";import $x from"node:path";var Zk,eL,jx,Ux=h(()=>{"use strict";Bx();Bo();C();he();O();oe();Zk=e=>e==="~"||e.startsWith("~/")?$x.join(Qk.homedir(),e.slice(1)):e,eL=(e,t)=>{let n=e.trim();if(!n)return c("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?d("Resolved recent project",o.root):c(`No recent project #${n}`)}let r=Ae($x.resolve(Zk(n)));return a(r)?c(`No epiq project at ${n}`):d("Resolved project path",r.value)},jx=async()=>{let e=Fc();if(re(""),y().hasProjectDefinition)return c("Already in a project; run epiq from another directory");let t=Ua({exclude:process.cwd()}),n=a(t)?[]:t.value,r=eL(e,n);if(a(r))return c(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(l){return c(`Unable to enter ${o}: ${l instanceof Error?l.message:String(l)}`)}let i=await Dx(o);return a(i)?(process.chdir(s),c(i.message)):(Fx(o),d(`Opened ${qg(o)}`,null))}});var hl,Xm=h(()=>{"use strict";Lt();H();H();C();O();hl=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=y(),s=du(n,t);if(a(s))return c(s.message);let{appliedEvents:i,unappliedEvents:l}=s.value,u=cr();if(a(u))return u;let p=Qn(i),{fatal:m,skipped:f}=br(p);if(m.length>0)return cr(),T(o),c(m.map(b=>b.message).join(", "));vr(f);let g=y().nodes[e];return g?(V.navigate({contextNode:g,selectedIndex:r}),d("",{unappliedEvents:l})):(cr(),T(o),c("Board did not exist at that date"))}});var Hx,Wx=h(()=>{"use strict";Hx=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 tL,nL,rL,yl,bl,xo,Gx,qx,Jm=h(()=>{"use strict";ht();ca();H();cu();$e();C();Wx();O();tL=20,nL=16,rL=150,yl=null,bl=null,xo=()=>{yl!==null&&(clearInterval(yl),yl=null),bl!==null&&(clearTimeout(bl),bl=null)},Gx=()=>{xo(),T({mode:x.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},qx=({events:e,startTime:t,durationMs:n})=>{xo();let r=e.length,o=Hs(e.map(f=>Wr(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=Hx(o),l=Math.max(1,Math.round(n*tL/1e3)),u=Math.max(Math.round(n/l),nL),p=0,m=0;T({mode:x.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),yl=setInterval(()=>{p++;let f=p/l,g=[],b,E;for(;m<r&&i[m]<=f;){let w=e[m],S=xi(w);if(a(S)){if(Yo(S)){m++;continue}Gx();return}g.push(...au(w)),b=w,E=o[m],m++}if(m>=r||p>=l){for(;m<r;m++){let S=xi(e[m]);if(a(S)&&!Yo(S))break}let w=y().replay;T({unappliedEvents:[],replay:w&&{...w,progress:1,appliedCount:r}}),xo(),bl=setTimeout(Gx,rL);return}let R=y().replay;T({unappliedEvents:e.slice(m),replay:{progress:Math.min(1,f),appliedCount:m,totalCount:r,startTime:t,endTime:s,currentTime:b?E??R?.currentTime??t:R?.currentTime??t,currentLabel:b?Qm(b):R?.currentLabel??"",flashNodeIds:b?[...new Set(g)]:R?.flashNodeIds??[]}})},u)}});var zx,Vx=h(()=>{"use strict";tt();ht();H();H();$e();fn();C();he();O();ai();Xm();Jm();zx=async()=>{let e=Ft(y().breadCrumb,"BOARD");if(a(e))return e;let t=await jt(process.cwd());if(a(t))return c("Unable to locate repo root");let n=xe({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=le().commandMeta;if(xo(),r==="now"){let l=Zn(n.value);if(a(l))return c(l.message);let u=cr();if(a(u))return u;let p=Qn(l.value),{fatal:m,skipped:f}=br(p);return m.length>0?c(m.map(g=>g.message).join(", ")):(vr(f),T({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 l=uu(n.value);if(a(l))return l;let u=r==="prev"?y().eventLog.at(-1):y().unappliedEvents.at(0),p=u===void 0?null:Wr(u),m=(u===void 0?null:l.value.get(u.id)??null)??(p===null?null:Us(p));if(m===null)return c(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?m:m+1}else{let l=Zr(r||o.trim());if(!l)return c("Invalid peek date");s=l.getTime()}let i=hl({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(i)?i:(T({mode:x.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),d("Peeking",!0))}});var Kx,Yx=h(()=>{"use strict";tt();fn();C();he();O();ai();Xm();Jm();Kx=async()=>{let e=Ft(y().breadCrumb,"BOARD");if(a(e))return e;let t=await jt(process.cwd());if(a(t))return c("Unable to locate repo root");let n=xe({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=le().commandMeta,{dateInput:s,durationInput:i}=Va(r,o);if(xo(),y().syncStatus.status==="syncing")return c("Cannot replay while syncing, try again in a moment");let l=Zr(s);if(!l)return c("Invalid replay date");let u=i?za(i):15e3;if(u===null)return c("Invalid replay duration (try e.g. 30s or 2m)");let p=l.getTime(),m=y(),f=hl({boardId:e.value.id,targetTime:p,stateBranchRoot:n.value,selectedIndex:-1});if(a(f))return f;let{unappliedEvents:g}=f.value;return g.length===0?(cr(),T(m),d("Nothing to replay from that point",!0)):(qx({events:g,startTime:p,durationMs:u}),d("Replaying board history",!0))}});import{spawn as sL}from"node:child_process";var iL,Xx,Jx=h(()=>{"use strict";C();iL=()=>{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"]}}},Xx=async e=>new Promise(t=>{let{command:n,args:r}=iL();try{let o=sL(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(c(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?d("Copied to clipboard",null):c(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(c(`Clipboard tool not available (${n})`))}})});var la,Qx,Zx=h(()=>{"use strict";C();O();Jx();rt();jo();Kn();la=async(e,t)=>{if(!e.trim())return c(`Nothing to copy: ${t} is empty`);let n=await Xx(e);return a(n)?n:d(`Copied ${t} to clipboard`,null)},Qx=async e=>{let{breadCrumb:t,selectedNode:n}=y(),r=ci({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return c("Nothing selected to copy from");switch(e.modifier){case Ve.REF:return la(Y(o.id),"ref");case Ve.TITLE:return la(o.title,"title");case Ve.DESCRIPTION:return r?la(r.props?.description??"","description"):c("No issue in scope");case Ve.TAGS:{if(!r)return c("No issue in scope");let s=Tn(r).map(({name:i})=>i);return la(s.join(", "),"tags")}case Ve.ASSIGNEES:{if(!r)return c("No issue in scope");let s=Mn(r).map(({name:i})=>i);return la(s.join(", "),"assignees")}default:return c("Yank one of: ref, title, description, tags, assignees")}}});var eE,tE=h(()=>{"use strict";Yc();$e();C();he();O();eE=async()=>{re(""),T({mode:x.DEFAULT});let e=Ce();if(a(e))return c(e.message);if(e.value.syncStatus.status==="syncing")return c("Sync already in progress");T({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Kc();return a(t)?(T({syncStatus:{msg:t.message,status:"failed"}}),t):(T({mode:x.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as nE}from"ulid";var rE,oE=h(()=>{"use strict";H();H();pe();C();O();nl();oe();en();rE=async()=>{let e=be();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=y(),r=Ee(t.id)[n];if(!r)return c("Unable to resolve child to delete");let o=await Ie();if(a(o))return o;if(r.context==="COMMENT"){let s=r.id,i=W(t)?t.id:t.parentNodeId;if(!i)return c("Unable to resolve comment issue");let l=y().nodes[i];if(!l||!W(l))return c("Unable to resolve comment issue");let u=l.log?.filter(NR).find(p=>p.payload.id===s);return u?u.payload.author!==e.value.userId?c("You can only delete your own comments"):F([{id:nE(),action:"delete.issue.comment",payload:{id:s,issue:i},...D(e.value)}],o.value):c("Unable to resolve comment")}return F([{id:nE(),action:"delete.node",payload:{id:r.id},...D(e.value)}],o.value)}});import{ulid as aL}from"ulid";var sE,iE=h(()=>{"use strict";H();H();yn();pe();C();nn();O();oe();Zt();sE=async()=>{let e=be();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=y(),r=Ee(t.id)[n];if(!r)return c("Unable to close issue, no target found");if(!W(r))return c("Cannot close in this context");let o=y().nodes[Te];if(!o)return c("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return c("Issue is already closed");let s=await Ie();if(a(s))return s;let i=s.value,l=_n(o.id,r.id,{at:"end"},e.value,i);if(a(l))return l;let u=F([{id:aL(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...D(e.value)}],i);return a(u)?u:d("Issue closed",null)}});var vl,Zm=h(()=>{"use strict";vl=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 cL}from"ulid";var aE,cE=h(()=>{"use strict";H();H();Zm();yn();pe();C();ge();nn();O();oe();Zt();aE=async()=>{let e=be();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=y(),r=Ee(t.id)[n];if(!r)return c("Unable to reopen issue, no target found");let o=r.context==="TICKET"?d("Resolved ticket",r):cn(r.id,"TICKET");if(a(o))return c("Cannot reopen in this context");let s=o.value,i=y().nodes[Te];if(!i)return c("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return c("Issue is not closed");if(!W(s))return c("Target node is not issue");let l=vl(s);if(!l)return c("Unable to resolve previous parent from issue history");if(l===i.id)return c("Previous parent resolves to closed swimlane");let u=y().nodes[l];if(!u)return c("Previous parent no longer exists");let p=await Ie();if(a(p))return p;let m=p.value,f=_n(u.id,s.id,{at:"end"},e.value,m);if(a(f))return f;let g=F([{id:cL(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...D(e.value)}],m);return a(g)?g:d("Issue reopened",null)}});import{ulid as lL}from"ulid";var lE,dE=h(()=>{"use strict";H();H();C();he();O();oe();Zt();lE=async()=>{let e=be();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=y(),r=Ee(t.id)[n];if(!r)return c("Missing node");if(r.readonly)return c("Cannot rename readonly node");let o=Fc();if(!o)return c("Provide a title");let s=await Ie();return a(s)?s:F([{id:lL(),action:"edit.title",payload:{id:r.id,name:o},...D(e.value)}],s.value)}});import{ulid as dL}from"ulid";var uE,mE=h(()=>{"use strict";ge();H();H();pe();C();he();O();oe();Zt();uE=async()=>{let e=be();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=le().commandMeta,r=(t||n).trim();if(!r)return c("Provide a tag");let o=N.findTagByName(r);if(!o)return c(`Tag "${r}" does not exist`);let{selectedNode:s}=y();if(!s)return c("Invalid untag target");let i=cn(s.id,"TICKET");if(a(i))return c("Unable to untag issue in this context");let l=i.value;if(!W(l))return c("Target node is not issue");if(!(l.props.tags??[]).includes(o.id))return c("Issue is not tagged with that tag");let p=await Ie();return a(p)?p:F([{id:dL(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...D(e.value)}],p.value)}});import{ulid as ep}from"ulid";var pE,fE=h(()=>{"use strict";ge();H();H();pe();C();he();O();oe();Zt();pE=async()=>{let e=be();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=le().commandMeta,r=(t||n).trim();if(!r)return c("Provide a tag");let{selectedNode:o}=y();if(!o)return c("Invalid tag target");let s=cn(o.id,"TICKET");if(a(s))return c("Unable to tag issue in this context");let i=s.value;if(!W(i))return c("Target node is not issue");let l=await Ie();if(a(l))return l;let u=N.findTagByName(r),p=u?.id??ep();return(i.props.tags??[]).includes(p)?c("Already tagged with that tag"):F([...u?[]:[{id:ep(),action:"create.tag",payload:{id:p,name:r},...D(e.value)}],{id:ep(),action:"add.issue.tag",payload:{id:i.id,tag:p},...D(e.value)}],l.value)}});var da,gE,Rl=h(()=>{"use strict";Bt();qn();da=({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)}))},gE=({authorName:e,authorEmail:t,owners:n,registry:r})=>{let o=Xe(t),s=n.get(o),i=s?r[s]:void 0;return s?{...Ct(s,i?.name),resolved:!0}:{...Ct(o||e,e),resolved:!1}}});var xl,tp=h(()=>{"use strict";H();Rl();O();xl=e=>{let{eventLog:t=[],contributors:n}=y();return da({events:t,registry:n,logFileNames:io(e)})}});import{ulid as np}from"ulid";var hE,yE=h(()=>{"use strict";H();H();pe();C();ge();he();O();tp();oe();Zt();hE=async()=>{let e=be();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=le().commandMeta,r=(t||n).trim();if(!r)return c("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return c("Provide an assignee");let{selectedIndex:i,contextNode:l}=y(),u=Ee(l.id)[i];if(!u)return c("Invalid assign target");let p=cn(u.id,"TICKET");if(a(p))return c("Unable to assign issue in this context");let m=p.value;if(!W(m))return c("Target node is not issue");let f=await Ie();if(a(f))return f;let g=xl(f.value),b=!o&&s.toLowerCase()==="me",E,R;if(b)E=e.value.userId,R=g.find(A=>A.id===E)?.name??e.value.userName;else{let A=g.filter(P=>P.name===s);if(A.length>1)return c(`"${s}" matches ${A.length} contributors (${A.map(P=>P.id).join(", ")}). Assign from the GUI to choose by id.`);let L=A[0];if(!L&&!o)return c(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);E=L?.id??np(),R=L?.name??s}if((m.props.assignees??[]).includes(E))return c("Assignee already assigned");let S=!!y().contributors[E];return F([...S?[]:[{id:np(),action:"create.contributor",payload:{id:E,name:R},...D(e.value)}],{id:np(),action:"add.issue.assignee",payload:{id:m.id,assignee:E},...D(e.value)}],f.value)}});import{ulid as uL}from"ulid";var bE,vE=h(()=>{"use strict";H();H();pe();C();ge();he();O();tp();oe();Zt();bE=async()=>{let e=be();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=le().commandMeta,r=(t||n).trim();if(!r)return c("Provide an assignee to remove");let{selectedNode:o}=y();if(!o)return c("Invalid unassign target");let s=cn(o.id,"TICKET");if(a(s))return c("Unable to unassign in this context");let i=s.value;if(!W(i))return c("Target node is not issue");let l=i.props.assignees??[],u=r.toLowerCase()==="me",p=await Ie();if(a(p))return p;let m=u?l.filter(g=>g===e.value.userId):xl(p.value).filter(g=>g.name===r&&l.includes(g.id)).map(g=>g.id);if(m.length>1)return c(`"${r}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let f=m[0];return f?F([{id:uL(),action:"remove.issue.assignee",payload:{id:i.id,assignee:f},...D(e.value)}],p.value):c(u?"Issue is not assigned to you":`Issue is not assigned to "${r}"`)}});import{ulid as RE}from"ulid";var mL,xE,EE=h(()=>{"use strict";H();H();fn();pe();C();ge();O();tr();oe();Zt();Mc();ll();Nc();mL=e=>{let t=e.trim(),n=Lr(),r=n?Nb(t):null;if(!n||!r)return{ok:!0,md:t,anchored:!1};let o=cl();if(!o||o.sha!==n)return{ok:!1,reason:"No diff is open"};let s=Ab(o.rows,Math.max(0,y().selectedIndex));if(!s)return{ok:!1,reason:"That line is not in a file"};let i=Tb(o.rows,s,r.start,r.end);return i.ok?{ok:!0,anchored:!0,md:Ib({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}},xE=async e=>{let t=mL(e.inputString);if(!t.ok)return c(t.reason);let{md:n,anchored:r}=t;if(!n)return c("Provide a comment");if(n.length>4e3)return c(r?`The note and the ${n.length} characters of quoted lines exceed ${4e3}; comment on fewer lines`:`Cannot exceed ${4e3} characters`);let o=be();if(a(o))return c("Unable to resolve user ID");let{breadCrumb:s,selectedNode:i}=y(),l=Ft([...s,i],"TICKET");if(a(l))return c("Edit target must be an issue");let u=l.value;if(!u)return c("Invalid comment target");let p=u.context==="TICKET"?d("Resolved ticket",u):cn(u.id,"TICKET");if(a(p))return c("Unable to comment on issue in this context");let m=p.value;if(!W(m))return c("Target node is not issue");let f=await Ie();if(a(f))return f;let g=await F([{id:RE(),action:"add.issue.comment",payload:{id:RE(),issue:m.id,author:o.value.userId,md:n},...D(o.value)}],f.value);return r&&!a(g)&&bo(null),g}});var SE,pL,IE,El,rp=h(()=>{"use strict";Kr();C();Ue();Qt();SE=e=>e.userName?.trim()?e.preferredEditor?.trim()?null:"no editor configured":"no username configured",pL=e=>{let t=gr();return a(t)?SE({userName:e.userName,preferredEditor:e.preferredEditor})??t.message:SE(t.value)},IE=()=>{let e=Jt();return a(e)?c(e.message):d("Read auto sync settings",{enabled:e.value.autoSync===!0,intervalMs:Ta(e.value.autoSyncDebounceMs),blockedReason:pL(e.value)})},El=e=>{let t=e.intervalMs===void 0?void 0:Lo(e.intervalMs);if(e.intervalMs!==void 0&&t===null)return c(`Auto sync interval must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=IE();if(a(n))return n;let r=dt({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncDebounceMs:t}});if(a(r))return c(r.message);Rt({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncIntervalMs:t}});let o=IE();return a(o)?d("Changed auto sync settings",{...n.value,...e.enabled===void 0?{}:{enabled:e.enabled},...t==null?{}:{intervalMs:t}}):o}});var CE,wE=h(()=>{"use strict";Kr();rp();C();he();CE=()=>{let e=le().commandMeta.inputString,t=Lo(e);if(t===null)return c(`Auto sync duration must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=El({intervalMs:t});return a(n)?n:d(`Auto sync interval set to ${t}ms`,null)}});import fL from"zod";var NE,AE=h(()=>{"use strict";Ja();Qt();C();he();NE=()=>{let e=fL.coerce.number().int().min(Go).max(qo).safeParse(le().commandMeta.inputString);if(!e.success)return c(`A connected repo's clone cap must be ${Go}-${qo} MB (default ${Hd})`);let t=dt({repoCloneMaxMb:e.data});return a(t)?t:d(`Connected repo clone cap set to ${e.data} MB`,null)}});var TE,ME=h(()=>{"use strict";Jr();rp();C();he();TE=()=>{let e=le().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return c("Invalid response");let t=nh(e),n=El({enabled:t===!0});return a(n)?n:d(`Auto sync set to "${e}"`,null)}});var op,kE,LE,gL,hL,ua,Sl,Il=h(()=>{"use strict";De();Bt();C();vu();op=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=2),kE="",LE=new Map,gL=15e3,hL=async(e,t)=>{let n=`${e} ${t??""}`,r=LE.get(n);if(r&&Date.now()-r.at<vc(gL))return d("Cached author scan",r.authors);let o=await Pe({cwd:e,args:["log","--branches",...t?["--not",t]:[],`--format=%an${kE}%ae`]});if(o.exitCode!==0)return c(`Could not read this repository's history: ${(o.stderr??"").trim()||`git exited ${o.exitCode}`}`);let s=new Map;for(let i of(o.stdout??"").split(`
116
- `)){let l=i.lastIndexOf(kE);if(l===-1)continue;let u=i.slice(0,l),p=Xe(i.slice(l+1));if(!ur(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 LE.set(n,{at:Date.now(),authors:s}),d("Scanned repository authors",s)},ua=async({repoRoot:e,stateBranch:t,names:n,links:r})=>{let o=await hL(e,t);if(a(o))return c(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 l=new Set(n.flatMap(u=>op(u??"")));return d("Found candidates",[...s.entries()].map(([u,p])=>({email:u,names:[...p.names],commits:p.commits,looksLikeYours:[...p.names].some(m=>op(m).some(f=>l.has(f)))||op(u.split("@")[0]??"").some(m=>l.has(m)),claimedBy:[...i.get(u)??[]]})).sort((u,p)=>u.looksLikeYours===p.looksLikeYours?p.commits-u.commits:Number(p.looksLikeYours)-Number(u.looksLikeYours)))},Sl=e=>e.filter(t=>t.claimedBy.length===0)});import{ulid as yL}from"ulid";var PE,OE,_E=h(()=>{"use strict";H();wn();tt();Bt();C();$e();Il();he();si();Ue();O();Qt();Jr();oe();PE=()=>{let e=Ad();if(!e)return d("Nothing here to decline",null);let t=Jt(),n=a(t)?[]:t.value.declinedEmailBoards??[],r=[...new Set([...n,e])],o=dt({declinedEmailBoards:r});return a(o)?c(o.message):(Rt({declinedEmailBoards:[...new Set([...ce().declinedEmailBoards??[],e])]}),d("Declined",null))},OE=async()=>{let e=le().commandMeta.inputString.trim();if(e==="none"){let w=PE();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}=ce();if(!t)return c("Set a username first with :config username");let o=Ce();if(a(o))return c("Board is not loaded");let s=Ae(process.cwd());if(a(s))return c(s.message);let i=lt(s.value),l=await ua({repoRoot:s.value,stateBranch:a(i)?void 0:i.value,names:[n,r],links:o.value.emailLinks});if(a(l))return l;let p=Sl(l.value);if(Qg(p.map(w=>w.email)),p.length===0){if(!eh()){let w=PE();if(a(w))return w}return d("No unclaimed addresses in this history.",null)}if(!e)return T({mode:x.IDENTITY}),d("Opened identity",null);let m=e.split(/[,\s]+/).filter(Boolean),f=[],g=[];for(let w of m){let S=p.find(A=>A.email===Xe(w));if(!S){g.push(w);continue}f.includes(S)||f.push(S)}if(g.length>0)return c(`Not on the list: ${g.join(", ")}. Pick one of ${p.map(w=>w.email).join(", ")}.`);let b=xe({repoRoot:s.value});if(a(b))return b;let E=f.map(w=>({id:yL(),action:"link.contributor.email",payload:{contributor:t,email:w.email},userId:t})),R=F(E,b.value);return a(R)?c(R.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 bL}from"ulid";var DE,FE=h(()=>{"use strict";H();tt();Bt();C();he();Ue();O();oe();DE=()=>{let e=le().commandMeta.inputString.trim(),{userId:t}=ce();if(!t)return c("Set a username first with :config username");let n=Ce();if(a(n))return c("Board is not loaded");let r=mr(n.value.emailLinks,t);if(r.length===0)return c("You have not claimed any addresses.");if(!e)return c(`Which one? ${r.join(", ")}.`);let o=r.find(u=>u===Xe(e));if(!o)return c(`You have not claimed ${e}. Yours: ${r.join(", ")}.`);let s=Ae(process.cwd());if(a(s))return s;let i=xe({repoRoot:s.value});if(a(i))return i;let l=F([{id:bL(),action:"unlink.contributor.email",payload:{contributor:t,email:o},userId:t}],i.value);return a(l)?c(l.message):d(`Unclaimed ${o}`,null)}});var BE,$E=h(()=>{"use strict";Qt();C();he();Ue();BE=()=>{let e=le().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return c("Invalid response");let n=dt({logLevel:e});return a(n)?n:(Rt({logLevel:e}),d(`Auto sync set to "${e}"`,null))}});import{ulid as vL}from"ulid";var jE,UE=h(()=>{"use strict";$r();Qt();C();Ue();Kn();wE();Ud();AE();ME();_E();FE();$E();Zu();jE=e=>{let t=e.inputString.trim();switch(e.modifier){case ie.USERNAME:{if(process.env[Kt])return c(`Cannot change the configured user while ${Kt} names this process`);let n=Jt();if(a(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,l=r||vL();if(!i||!l)return c("Unable to resolve user name or id");let u=dt({userName:i,userId:l,preferredEditor:o??""});return a(u)?u:(Rt({userName:i,userId:l}),d(`Username set to "${i}"`,null))}case ie.EDITOR:{if(!t)return c("No editor provided");let n=dt({preferredEditor:t});return a(n)?n:(Rt({preferredEditor:t}),d(`Editor configuration set to "${t}"`,null))}case ie.VIEW:{if(t!=="wide"&&t!=="dense")return c("Invalid view mode");let n=dt({viewMode:t});return a(n)?n:(Rt({viewMode:t}),d(`View set to "${t}"`,null))}case ie.EMAILS:return OE();case ie.EMAILS_UNCLAIM:return DE();case ie.AUTOSYNC:return TE();case ie.LOG_LEVEL:return BE();case ie.SYNC_DEBOUNCE_MS:return CE();case ie.ATTACHMENT_MAX_KB:return Eh();case ie.REPO_CLONE_MAX_MB:return NE();case ie.REPO_CONNECT:return Hb();case ie.REPO_DISCONNECT:return Wb();default:return c("Unknown config command")}}});var sp,HE=h(()=>{"use strict";Jr();$e();he();O();sp=()=>{let e=rh(),t=y().mode;if(!(t!==x.COMMAND_LINE&&t!==x.DEFAULT)){if(!e){T({mode:x.DEFAULT});return}T({mode:x.COMMAND_LINE}),re(e)}}});var WE,GE=h(()=>{"use strict";fx();Lt();$e();C();he();O();ml();Qr();vm();Kn();hx();Rx();Nx();Tx();Ux();Vx();Yx();Zx();tE();oE();iE();cE();dE();mE();fE();yE();vE();EE();UE();HE();WE=[{systemOnly:!0,intent:X.Move,description:"Internal move-state command",mode:x.COMMAND_LINE,action:wx},{intent:X.Delete,description:"Delete the currently selected node",mode:x.COMMAND_LINE,action:rE,onSuccess:()=>T({mode:x.DEFAULT})},{intent:X.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:x.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=le().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>Ke(I.FILTER).map(l=>l.split(n)[0]).includes(i))(r))return c("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return Oe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:x.DEFAULT})),d("Filter updated",null)}},{intent:X.ViewHelp,description:"Open the help screen",mode:x.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=y();return Pr({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),T({mode:x.HELP}),d("Viewing help",null)}},{intent:X.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:x.COMMAND_LINE,action:sE,onSuccess:()=>T({mode:x.DEFAULT})},{intent:X.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:x.COMMAND_LINE,action:aE,onSuccess:()=>T({mode:x.DEFAULT})},{intent:X.Init,description:"Initialize Epiq in the current git repository",mode:x.COMMAND_LINE,action:vx,onSuccess:sp},{intent:X.OpenProject,description:"Open a recently used epiq project, by number or path",mode:x.COMMAND_LINE,action:jx,onSuccess:()=>T({mode:x.DEFAULT})},{intent:X.NewItem,description:"Create a new board, swimlane, or issue",mode:x.COMMAND_LINE,action:Ax,onSuccess:()=>T({mode:x.DEFAULT})},{intent:X.Rename,description:"Rename the currently selected node",mode:x.COMMAND_LINE,action:lE,onSuccess:()=>T({mode:x.DEFAULT})},{intent:X.UntagTicket,description:"Remove a tag from the selected issue",mode:x.COMMAND_LINE,action:uE,onSuccess:()=>T({mode:x.DEFAULT})},{intent:X.TagTicket,description:"Add or create a tag on the selected issue",mode:x.COMMAND_LINE,action:pE,onSuccess:()=>T({mode:x.DEFAULT})},{intent:X.AssignUserToTicket,description:"Assign a user to the selected issue",mode:x.COMMAND_LINE,action:hE,onSuccess:()=>T({mode:x.DEFAULT})},{intent:X.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:x.COMMAND_LINE,action:bE,onSuccess:()=>T({mode:x.DEFAULT})},{intent:X.Comment,description:"Add a comment to the selected issue",mode:x.COMMAND_LINE,action:async(e,t)=>xE(t),onSuccess:()=>T({mode:x.DEFAULT})},{intent:X.Sync,description:"Pull, commit, and push Epiq state",mode:x.COMMAND_LINE,action:eE},{intent:X.Peek,description:"View board state at another point in time",mode:x.COMMAND_LINE,action:zx},{intent:X.Replay,description:"Replay board history forward from a point in time",mode:x.COMMAND_LINE,action:Kx},{intent:X.Export,description:"Export the current board layout to markdown",mode:x.COMMAND_LINE,action:async()=>{let e=await px();return a(e)?e:(T({mode:x.DEFAULT}),d("Export successful",!0))}},{intent:X.Exit,description:"Exit the application",mode:x.COMMAND_LINE,action:async()=>(V.exit(),d("Exit successful",!0))},{intent:X.Edit,description:"Edit title or description",mode:x.COMMAND_LINE,action:async(e,t)=>gx(t),onSuccess:()=>T({mode:x.DEFAULT})},{intent:X.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:x.COMMAND_LINE,action:async(e,t)=>Qx(t),onSuccess:()=>T({mode:x.DEFAULT})},{intent:X.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:x.COMMAND_LINE,action:(e,t)=>jE(t),onSuccess:sp}]});var RL,xL,ln,ip=h(()=>{"use strict";dR();Pc();vm();GE();Ym();C();he();Ue();O();RL=e=>{let t=e.value;return t&&typeof t=="object"&&typeof t.followUp=="string"?t.followUp:null},xL=new Set(["peek","replay","filter","view-help","yank"]),ln=async({isForceExecutedBySystem:e=!1}={})=>{let{value:t,commandMeta:{command:n,validity:r,modifier:o,inputString:s}}=le();if(!n)return c("No command to confirm");if(!e&&r===Nr.Invalid)return c("Invalid command");let i=uR(n);dv();let{readOnly:l}=y();if(l&&!xL.has(i))return Hi({status:Un.Fail,message:"Command not available in readonly state",value:null});let u=WE.filter(g=>e||g.systemOnly!==!0).find(g=>g.intent===i);if(!u)return Hi({status:Un.Fail,message:"Command not found",value:null});let p;try{p=await u.action(u,{command:n,inputString:s,modifier:o})}catch(g){return Hi({status:Un.Fail,message:g instanceof Error?g.message:"Command failed",value:null})}if(a(p))return Hi(p);let m=!e;if(uv({addToHistory:m,line:t}),m){let g=Px({commands:le().commandHistory});a(g)&&logger.info(g.message)}let f=RL(p);return f!==null?(re(f),p):(u.onSuccess?.(),ce().autoSync&&lR(),p)}});var Cl,wl,qE,zE=h(()=>{"use strict";C();$e();O();pr();ip();Vm();he();Cl=[{intent:_.Exit,mode:x.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(T({mode:x.COMMAND_LINE}),re("move cancel"),ln({isForceExecutedBySystem:!0}))},{intent:_.InitMove,mode:x.DEFAULT,description:"[m] move",action:()=>(T({mode:x.COMMAND_LINE}),re("move start"),ln({isForceExecutedBySystem:!0}))},{intent:_.ConfirmMove,mode:x.MOVE,description:"[m] confirm move",action:()=>(T({mode:x.COMMAND_LINE}),re("move confirm"),ln({isForceExecutedBySystem:!0}))}],wl=[{intent:_.MovePreviousItem,mode:x.MOVE,action:()=>Sn()?(T({mode:x.COMMAND_LINE}),re("move previous"),ln({isForceExecutedBySystem:!0})):c("No pending move")},{intent:_.MoveNextItem,mode:x.MOVE,description:"[arrows/hjkl] move (shift x5)",action:()=>Sn()?(T({mode:x.COMMAND_LINE}),re("move next"),ln({isForceExecutedBySystem:!0})):c("No pending move")},{intent:_.MovePreviousItemJump,mode:x.MOVE,action:()=>Sn()?(T({mode:x.COMMAND_LINE}),re("move jump-previous"),ln({isForceExecutedBySystem:!0})):c("No pending move")},{intent:_.MoveNextItemJump,mode:x.MOVE,action:()=>Sn()?(T({mode:x.COMMAND_LINE}),re("move jump-next"),ln({isForceExecutedBySystem:!0})):c("No pending move")}],qE=[{intent:_.MoveToNextContainer,mode:x.MOVE,action:()=>Sn()?(T({mode:x.COMMAND_LINE}),re("move to-next"),ln({isForceExecutedBySystem:!0})):c("No pending move")},{intent:_.MoveToPreviousContainer,mode:x.MOVE,action:()=>Sn()?(T({mode:x.COMMAND_LINE}),re("move to-previous"),ln({isForceExecutedBySystem:!0})):c("No pending move")}]});var VE,KE=h(()=>{"use strict";pe();zE();VE={[me.WORKSPACE]:[...Cl,...wl],[me.BOARD]:[...Cl,...wl],[me.SWIMLANE]:[...Cl,...wl,...qE],[me.TICKET]:[],[me.FIELD]:[],[me.FIELD_LIST]:[],[me.TEXT]:[],[me.COMMENT]:[]}});import{spawn as EL}from"node:child_process";function YE(e){let t=process.platform,o=EL(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 XE=h(()=>{"use strict"});import SL from"node:fs";import IL from"node:path";var JE,QE=h(()=>{"use strict";tt();Wo();C();oe();XE();JE=e=>{let t=Ae(process.cwd());if(a(t))return c("Unable to resolve project root");let n=xe({repoRoot:t.value});if(a(n))return c(n.message);let r=Ho(e.hash,e.ext),o=IL.join(Fa(n.value),r);return SL.existsSync(o)?(YE(o),d(`Opened ${e.name}`,null)):c("Attachment file not found \u2014 run :sync to fetch it")}});var ZE,eS,tS=h(()=>{"use strict";$e();C();he();O();ml();pr();Lt();ZE=()=>{re("");let{pendingNavTarget:e}=xs();T({mode:x.DEFAULT}),e&&V.navigate(e),Pr({pendingNavTarget:void 0})},eS=[{intent:_.ExitCommandLine,mode:x.HELP,action:()=>(ZE(),d("Exiting help",null))},{intent:_.Exit,mode:x.HELP,action:()=>(ZE(),d("Closed help",null))},{intent:_.NavPreviousItem,mode:x.HELP,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(V.navigateToPreviousItem(),d("Navigating to previous help item",null))},{intent:_.NavNextItem,mode:x.HELP,action:()=>(V.navigateToNextItem(),d("Navigating to next help item",null))},{intent:_.NavPreviousItemJump,mode:x.HELP,action:()=>(V.jumpToPreviousItem(),d("Jumping to previous help item",null))},{intent:_.NavNextItemJump,mode:x.HELP,action:()=>(V.jumpToNextItem(),d("Jumping to next help item",null))},{intent:_.NavToPreviousContainer,mode:x.HELP,action:()=>(V.navigateToPreviousContainer(),d("Navigating to previous help container",null))},{intent:_.NavToNextContainer,mode:x.HELP,action:()=>(V.navigateToNextContainer(),d("Navigating to next help container",null))}]});var nS,rS,oS=h(()=>{"use strict";$e();C();he();si();O();pr();nS=()=>{re(""),T({mode:x.DEFAULT})},rS=[{intent:_.Confirm,mode:x.IDENTITY,description:"[enter] claim the first",action:()=>{let[e]=$o();return e?(T({mode:x.COMMAND_LINE}),re(`config emails ${e}`),d("Proposed claim",null)):d("Nothing left to claim",null)}},{intent:_.ExitCommandLine,mode:x.IDENTITY,action:()=>(nS(),d("Closed identity",null))},{intent:_.Exit,mode:x.IDENTITY,description:"[esc] close",action:()=>(nS(),d("Closed identity",null))}]});var CL,sS,iS,aS=h(()=>{"use strict";$e();pe();C();he();O();ml();pr();Lt();CL=e=>{T({mode:x.COMMAND_LINE});let{pendingNavTarget:t}=xs();t&&V.navigate(t),Pr({pendingNavTarget:void 0}),re(`${e} `)},sS=()=>{re("");let{pendingNavTarget:e}=xs();e&&V.navigate(e),Pr({pendingNavTarget:void 0}),T({mode:x.DEFAULT})},iS=[{intent:_.InitCommandPalette,mode:x.DEFAULT,description:"[?] command palette",action:()=>{re("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=y();return Pr({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),T({mode:x.PALETTE}),d("Opening command palette",null)}},{intent:_.Confirm,mode:x.PALETTE,action:()=>{let{selectedNode:e}=y();if(!e||!Uf(e))return c("Command only applicable on text nodes");if(e.props.disabled)return c("Command is not available in this context");let t=e.title;return t?(CL(t),d("Selected command",t)):d("No command selected",null)}},{intent:_.ExitCommandLine,mode:x.PALETTE,action:()=>(sS(),d("Exiting palette",null))},{intent:_.Exit,mode:x.PALETTE,action:()=>(sS(),d("Closed command palette",null))},{intent:_.NavPreviousItem,mode:x.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(V.navigateToPreviousItem(),d("Navigating to previous item",null))},{intent:_.NavNextItem,mode:x.PALETTE,action:()=>(V.navigateToNextItem(),d("Navigating to next item",null))},{intent:_.NavToPreviousContainer,mode:x.PALETTE,action:()=>(V.navigateToPreviousContainer(),d("Navigating to previous container",null))},{intent:_.NavToNextContainer,mode:x.PALETTE,action:()=>(V.navigateToNextContainer(),d("Navigating to next container",null))}]});var cS,lS,dS=h(()=>{"use strict";Qr();Kn();Cr();Mc();$e();C();ll();Xo();ge();nn();he();O();QE();pr();wr();tS();oS();aS();Lt();cS=()=>{let e=Lr();if(!e)return d("Nothing to comment on here",null);let t=cl();if(!t||t.sha!==e)return c("The diff is still loading");let{selectedIndex:n}=y(),r=Math.max(0,n),o=Hu(t.rows,km(e)??r,r);return o.ok?(T({mode:x.COMMAND_LINE}),re(`${I.COMMENT} ${wb(o.value.start,o.value.end)} `),d("Commenting on a diff line",null)):c(o.reason)},lS=[{intent:_.InitCommandLine,mode:x.DEFAULT,description:"[:] write command",action:()=>(T({mode:x.COMMAND_LINE}),re(""),d("Entering command line mode",null))},...eS,...rS,...iS,{intent:_.AddItem,mode:x.DEFAULT,description:"[n] new...",action:()=>(T({mode:x.COMMAND_LINE}),re(`${I.NEW} `),d("Adding new item",null))},{intent:_.Delete,mode:x.DEFAULT,description:"[d] delete",action:()=>(T({mode:x.COMMAND_LINE}),re(`${I.DELETE} `),d("Deleting item",null))},{intent:_.Confirm,mode:x.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=y();if(!_e(e?.id??"")?.length){let r=e?N.getAttachment(e.id):void 0;if(r)return JE(r);if(Lr())return cS();if(e?.title===Me.DESCRIPTION)return T({mode:x.COMMAND_LINE}),re(`${I.EDIT} description `),d("Propose command",!0);if(e?.title===Me.ASSIGNEES)return T({mode:x.COMMAND_LINE}),re(`${I.ASSIGN} `),d("Propose command",!0);if(e?.title===Me.TAGS)return T({mode:x.COMMAND_LINE}),re(`${I.TAG} `),d("Propose command",!0);if(t.title===Me.DESCRIPTION&&e?.context==="TEXT")return T({mode:x.COMMAND_LINE}),re(`${I.EDIT} description `),d("Propose command",!0)}return V.enterChildNode(),d("Entering context",null)}},{intent:_.OpenInEditor,mode:x.DEFAULT,action:()=>{let{selectedNode:e,contextNode:t}=y(),n=t.parentNodeId,o=!!n&&t.id===ke(n,"diff")?e?.id:Lr()??void 0;return o?Xu({sha:o}):d("Nothing here opens in an editor",null)}},{intent:_.MarkDiffLine,mode:x.DEFAULT,action:()=>{let e=Lr();if(!e)return d("Nothing to mark here",null);let{selectedIndex:t}=y(),n=km(e);return bo(n===t?null:{sha:e,row:Math.max(0,t)}),d("Marked diff line",null)}},{intent:_.CommentOnDiffLine,mode:x.DEFAULT,action:()=>Lr()?cS():d("Nothing to comment on here",null)},{intent:_.Yank,mode:x.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=y(),t=e?.title===Me.DESCRIPTION?Ve.DESCRIPTION:e?.title===Me.TAGS?Ve.TAGS:e?.title===Me.ASSIGNEES?Ve.ASSIGNEES:Ve.REF,r=Ke(I.YANK).includes(t)?t:Ve.REF;return T({mode:x.COMMAND_LINE}),re(`${I.YANK} ${r}`),d("Propose command",!0)}},{intent:_.EditTitle,mode:x.DEFAULT,description:"[r] rename title",action:()=>(T({mode:x.COMMAND_LINE}),re(`${I.EDIT} title ${y().selectedNode?.title}`),d("Exiting context",null))},{intent:_.EditDescription,mode:x.DEFAULT,description:"[e] edit desc",action:()=>(T({mode:x.COMMAND_LINE}),re(`${I.EDIT} description `),d("Exiting context",null))},{intent:_.Exit,mode:x.DEFAULT,description:"[q] exit context",action:()=>(V.enterParentNode(),d("Exiting context",null))},{intent:_.NavPreviousItem,mode:x.DEFAULT,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(V.navigateToPreviousItem(),d("Navigating to previous item",null))},{intent:_.NavNextItem,mode:x.DEFAULT,action:()=>(V.navigateToNextItem(),d("Navigating to next item",null))},{intent:_.NavPreviousItemJump,mode:x.DEFAULT,action:()=>(V.jumpToPreviousItem(),d("Jumping to previous item",null))},{intent:_.NavNextItemJump,mode:x.DEFAULT,action:()=>(V.jumpToNextItem(),d("Jumping to next item",null))},{intent:_.NavToPreviousContainer,mode:x.DEFAULT,action:()=>(V.navigateToPreviousContainer(),d("Navigating to previous container",null))},{intent:_.NavToNextContainer,mode:x.DEFAULT,action:()=>(V.navigateToNextContainer(),d("Navigating to next container",null))}]});var wL,NL,uS,mS=h(()=>{"use strict";he();wL=500,NL=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),uS=e=>{let t=NL(e);t&&Dc(n=>(n+t).slice(0,wL))}});var AL,TL,ML,pS,fS=h(()=>{"use strict";mS();$e();C();he();O();pr();ip();AL=[x.COMMAND_LINE,x.PALETTE],TL=e=>e==="edit title "?y().selectedNode?.title??"":"",ML=e=>[{intent:_.MoveCursorLeft,mode:e,action:()=>(rm(-1),d("Moving cursor left",null))},{intent:_.MoveCursorRight,mode:e,action:()=>(rm(1),d("Moving cursor right",null))},{intent:_.MoveCursorLeftOfWord,mode:e,action:()=>(om("left"),d("Moving cursor left of word",null))},{intent:_.MoveCursorRightOfWord,mode:e,action:()=>(om("right"),d("Moving cursor right of word",null))},{intent:_.AutoCompleteCommand,mode:e,action:()=>(Dc((t,{remainder:n})=>{let r=n?t+n:t;return r+TL(r)}),d("Auto-completing command",null))},{intent:_.CaptureInput,mode:e,action:(t,{sequence:n})=>(uS(n??""),d("Capturing input",null))},{intent:_.EraseInput,mode:e,action:()=>(cv(),d("Erasing input",null))},{intent:_.EraseInputWord,mode:e,action:()=>(lv(),d("Erasing input word",null))}],pS=[{intent:_.Confirm,mode:x.COMMAND_LINE,action:()=>(ln(),d("Executing command",null))},{intent:_.ViewHelp,mode:x.DEFAULT,action:()=>(T({mode:x.HELP}),d("Viewing help",null))},...AL.flatMap(ML),{intent:_.ExitCommandLine,mode:x.COMMAND_LINE,action:()=>(pv(),T({mode:x.DEFAULT}),d("Exiting command line",null))},{intent:_.GetLastCommandFromHistory,mode:x.COMMAND_LINE,action:()=>(fv(),d("Getting last command from history",null))},{intent:_.GetNextCommandFromHistory,mode:x.COMMAND_LINE,action:()=>(gv(),d("Getting next command from history",null))}]});var kL,gS,hS,yS=h(()=>{"use strict";kL=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},gS=({keys:e})=>e.length===1?0:1,hS=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(kL).filter(r=>r!==null).sort((r,o)=>gS(r)-gS(o))}});function bS(e,t,n){let r=t[e];if(!r)return c("buildBreadCrumb(): current node not found");let o=[],s=new Set,i=r;for(;i&&!s.has(i.id)&&(o.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let l=o[o.length-1];return!l||l.id!==n?c("buildBreadCrumb(): node is not connected to root"):(o.reverse(),d("Breadcrumb built",o))}var vS=h(()=>{"use strict";C()});var RS,xS=h(()=>{"use strict";RS=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 LL}from"react";function dp(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return c("derive(): contextNodeId is missing");if(!r)return c("derive(): rootNode is missing");if(!o[r])return c("derive(): unable to find root node");let l=o[t];if(!l)return c("Unable to derive state, contextNode not found");let u=bS(t,o,r);if(a(u))return logger.error(u.message),u;let p=u.value,{context:m}=l,f=[...lS,...VE[m]??[],...pS],g=hS(f,n),b=RS(f),E=OL(o,s),R=E[t]?.[e.selectedIndex]??null;return d("Derived successfully",{...e,contextNode:l,breadCrumb:p,availableHints:g,availableActions:f,actionIndex:b,selectedNode:R,renderedChildrenIndex:E})}function Ri(e){ap=e;let t=Ae(process.cwd()),n=!1;if(!a(t)){let s=vt(t.value);if(a(s))return c(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},emailLinks:{},repos:zl(),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=dp(r);return a(o)?o:(_t=o.value,lp(),d("State initialized",null))}function Oe(e){let t=y(),n=e(t);if(Eo)return n.nodes!==t.nodes&&(Or=null),ma=n,_t={...t,...n},d("State updated",null);let r=dp(n);return a(r)?c(r.message??"Unable to update state"):(_t=r.value,lp(),d("State updated",null))}function dc(e){if(Eo)return d("Joined batch",e());Eo=!0,ma=null,Or=new Set;let t=()=>{let n=ma;if(Eo=!1,ma=null,n===null)return null;let r=dp(n);return a(r)?c(r.message??"Unable to update state"):(_t=r.value,lp(),d("State updated",null))};try{let n=e(),r=t();return r&&a(r)?c(r.message):d("State updated",n)}finally{Eo&&t()}}function So(e,t,n){if(!Eo)return Oe(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=y(),o=r[e]??{};if(e==="nodes"){let i=o[t],l=n;i?.parentNodeId&&Or?.add(i.parentNodeId),l.parentNodeId&&Or?.add(l.parentNodeId)}o[t]=n;let s={...r,[e]:o};return ma=s,_t={...r,...s},d("State updated",null)}var _t,ap,cp,lp,PL,y,Ce,Eo,ma,Mv,T,Je,Or,ES,OL,Ee,cr,ut,O=h(()=>{"use strict";Hr();KE();dS();fS();yS();Yt();$e();C();oe();cm();vS();xS();Bt();Nd();cp=new Set,lp=()=>{for(let e of cp)e()},PL=e=>(cp.add(e),()=>cp.delete(e));y=()=>{if(!_t)throw new Error("State not initialized. Call initWorkspaceState() first.");return _t},Ce=()=>_t?d("Retrieved state",_t):c("State not initialized. Call initWorkspaceState() first.");Yg(e=>_t?mr(_t.emailLinks,e):[]);Eo=!1,ma=null;Mv=()=>Eo,T=e=>Oe(t=>({...t,...e}));Je=()=>LL(PL,y,y),Or=null,ES=null,OL=(e,t)=>{let n=_t?.renderedChildrenIndex,r=n!==void 0&&Or!==null&&e===ES&&t.length===0&&_t?.filters.length===0,o;if(r){o={...n};let s=wv(e,Or);for(let i of Or){let l=s[i];l?o[i]=l:delete o[i]}}else o=Cv(e,t);return ES=e,Or=new Set,o},Ee=e=>y()?.renderedChildrenIndex[e]??[],cr=()=>ap?Ri(ap):c("Cannot reset state: no initial workspace found"),ut=()=>_t!==void 0});var cn,_L,_r,N,ge=h(()=>{"use strict";fn();Bt();pe();C();O();nn();cn=(e,t)=>{let{nodes:n}=y(),r=n[e];if(!r)return c("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 c(`No ancestor found for context: ${t}`)},_L=(e,t)=>{let{nodes:n}=y(),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},_r=(e,t)=>e?e.readonly?c({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:c("Node not found"),N={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return c("Contributor not found");if(n.userId&&n.userId!==t)return c("Contributor is already linked to another user");let r={...n,userId:t},o=Oe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?c("Unable to link contributor to user"):d("Linked contributor to user",r)},deleteNode(e){N.deleteNodes([e])},deleteNodes(e){e.length!==0&&Oe(t=>{let n={...t.nodes};for(let r of e)delete n[r];return{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return c("Unable to create comment, missing issue");if(!W(t))return c("Can only comment on issues");let n=So("comments",e.id,{...e,deleted:!1});return a(n)?c("Unable to create comment"):d("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return c("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return c("Unable to edit comment, missing issue");if(!W(r))return c("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=So("comments",e,o);return a(s)?c("Unable to edit comment"):d("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return c("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=So("comments",e,n);return a(r)?c("Unable to delete comment"):d("Deleted comment",n)},getComment(e){return y().comments?.[e]},getCommentsByIssue(e){return Object.values(y().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(y().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return c("Unable to create attachment, missing issue");if(!W(t))return c("Can only attach to issues");let n=Oe(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?c("Unable to create attachment"):d("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return c("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=Oe(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return a(r)?c("Unable to delete attachment"):d("Deleted attachment",n)},getAttachment(e){return y().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(y().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(y().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}=y(),r=n[e];if(!r)return c("Edit target node not found");let o=_r(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 c("Rename target node not found");let r=_r(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),d("Renamed node",o)},getExistingTags(){let{tags:e}=y();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=y();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return _e(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=y(),o=this.getNode(e),s=this.getNode(t);if(!o)return c("Node not found");if(!s)return c("Target parent not found");if(r===e)return c("Cannot move root node");if(e===t)return c("Cannot move node into itself");let i=_r(o,"move");if(i)return i;if(_L(t,e))return c("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),d("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=y(),o=this.getNode(e);if(!o)return c("Node not found");if(r===e)return c("Cannot delete root node");let s=_r(o,"delete");if(s)return s;let i=new Set,l=p=>{let m=t[p];if(!(!m||i.has(p))){i.add(p);for(let f of _e(m.id))l(f.id)}};l(e);let u={...structuredClone(t)};for(let p of i){if(!u[p])return c("Unable to locate node to delete");u[p]={...u[p],isDeleted:!0}}return n?(T({nodes:u}),d("Successfully tomb stoned",o)):c("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return c("Contributor not found");let n={...t,name:Gs,tombstoned:!0},r=Oe(o=>({...o,contributors:{...o.contributors,[e]:n}}));return a(r)?c("Unable to remove contributor"):d("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return c("Contributor not found");if(n.tombstoned)return c("Cannot rename a removed contributor");let r={...n,name:t},o=Oe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?c("Unable to rename contributor"):d("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return c("Contributor not found");let r={...n,name:t,tombstoned:!1},o=Oe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?c("Unable to restore contributor"):d("Restored contributor",r)},linkContributorEmail({email:e,contributor:t,authorId:n}){if(!this.getContributor(t))return c("Unable to link email, missing contributor");let r={email:Xe(e),contributor:t,authorId:n},o=qs(r.email,t),s=y().emailLinks[o];if(s&&!s.tombstoned)return d("Email already linked",s);let i=Oe(l=>({...l,emailLinks:{...l.emailLinks,[o]:r}}));return a(i)?c("Unable to link email"):d("Linked email to contributor",r)},unlinkContributorEmail(e,t,n){let r=qs(e,t),o=y().emailLinks[r];if(!o)return c("Unable to unlink, no such link");if(o.tombstoned)return d("Email already unlinked",o);if(!Na(n,o))return c("Only the author of a link or the contributor it names may remove it");let s={...o,tombstoned:!0},i=Oe(l=>({...l,emailLinks:{...l.emailLinks,[r]:s}}));return a(i)?c("Unable to unlink email"):d("Unlinked email from contributor",s)},getEmailLinks(){return y().emailLinks},createContributor(e){let t=Oe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?c("Unable to create contributor"):d("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return c("Unable to assign contributor, missing contributor");if(!r)return c("Unable to assign contributor, missing target");let o=_r(r,"edit");if(o)return o;if(!W(r))return c("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return c("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),d("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return c("Unable to unassign, missing contributor");if(!r)return c("Unable to unassign, missing target");let o=_r(r,"edit");if(o)return o;if(!W(r))return c("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(l=>l!==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 c("Unable to add tag, missing tag");if(!r)return c("Unable to add tag, missing target");let o=_r(r,"edit");if(o)return o;if(!W(r))return c("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return c("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),d("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),r=this.getNode(e);if(!n)return c("Unable to remove tag, missing tag");if(!r)return c("Unable to remove tag, missing target");let o=_r(r,"edit");if(o)return o;if(!W(r))return c("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(l=>l!==t)}};return this.updateNode(i),d("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return c("Tag not found");let n={...t,tombstoned:!0},r=Oe(o=>({...o,tags:{...o.tags,[e]:n}}));return a(r)?c("Unable to delete tag"):d("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return c("Tag not found");let r={...n,name:t,tombstoned:!1},o=Oe(s=>({...s,tags:{...s.tags,[e]:r}}));return a(o)?c("Unable to restore tag"):d("Restored tag",r)},createTag(e){let t=Oe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?c("Could not create tag"):d("Tag created",e)},createNode(e){let t=So("nodes",e.id,e);return a(t)?c("Unable to create node"):d("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return c("Failed to locate node");let n={...t,readonly:!0},r=So("nodes",e,n);return a(r)?c(r.message):d("Locked node",n)},updateNode(e){let t=So("nodes",e.id,e);return a(t)?t:d("Updated node",e)},getContributor(e){return y().contributors[e]},getTag(e){let t=y().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return y().tags[e]},getTags(){return Object.values(y().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return y().nodes[e]},getSiblings(e){return _e(e)}}});import Dr from"chalk";import SS from"string-width";var DL,FL,up,BL,$L,IS,CS,jL,UL,HL,WL,GL,qL,Qm,wS,ca=h(()=>{"use strict";Hr();ht();C();qn();ge();O();Cn();ea();DL=(e,t)=>e+" ".repeat(Math.max(0,t-SS(e))),FL=(e,t)=>" ".repeat(Math.max(0,t-SS(e)))+e,up=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","connect.repo":"Connected repo","edit.repo":"Edited repo","disconnect.repo":"Disconnected repo","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),BL=(e,t)=>t?e<t?"up":e>t?"down":null:null,$L=(e,t)=>{let n=N.getNode(e.payload.parent),r=n?Dr.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=BL(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},IS=e=>`${Math.max(1,Math.round(e/1024))} KB`,CS=e=>N.getAttachment(e)?.name??"",jL=e=>{switch(e.action){case"add.issue.tag":{let t=y().tags[e.payload.tag];return t?Dr.bgHex(it(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=y().tags[e.payload.tag];return t?Dr.bgHex(it(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=y().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=y().contributors[e.payload.assignee];return t?Dr.hex(it(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=y().contributors[e.payload.assignee];return t?Dr.hex(it(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"connect.repo":case"edit.repo":case"disconnect.repo":return Ea(e);case"add.issue.attachment":return`"${e.payload.name}" ${Dr.dim(`(${IS(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=CS(e.payload.id);return t?`"${t}"`:""}default:return""}},UL=e=>{let t=Tr(gt(e));return Dr.gray(FL(t,8))},HL=12,WL=e=>DL(`${e}`,HL),GL=e=>{let t=Ce();return a(t)?e:Ws(e,t.value.contributors[e]?.name)},qL=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=y().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=y().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=y().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"connect.repo":case"edit.repo":case"disconnect.repo":return Ea(e);case"move.node":{let t=N.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${IS(e.payload.bytes)})`;case"delete.issue.attachment":{let t=CS(e.payload.id);return t?`"${t}"`:""}default:return""}},Qm=e=>[up(e.action),qL(e)].filter(Boolean).join(" "),wS=(e,t)=>{let n=UL(e.id),r=WL(GL(e.userId)),o=Dr.dim("\u203A"),s=e.action==="move.node"?$L(e,t):[up(e.action),jL(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`}});var AS={};Ds(AS,{areVirtualNodesEnabled:()=>mc,createOrUpdateVirtualField:()=>Ss,createOrUpdateVirtualFieldList:()=>mp,materializeTicketVirtualNodes:()=>uc,materializeVirtualNodes:()=>nP,setVirtualNodesEnabled:()=>tP});var zL,VL,KL,YL,XL,JL,QL,Ss,mp,Nl,ZL,uc,eP,NS,tP,mc,nP,lu=h(()=>{"use strict";ca();pe();C();Xo();ge();Er();O();is();wr();zL=e=>ke(e,"comments"),VL=e=>ke(e,"description"),KL=e=>ke(e,"assignees"),YL=e=>ke(e,"tags"),XL=e=>ke(e,"history"),JL=e=>ke(e,"diff"),QL=e=>ke(e,"attachments"),Ss=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let l=N.getNode(e);if(!l){let m=N.createNode({...We.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(!at(l))return c(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==r||l.props.value!==o||l.readonly!==s||l.childRenderAxis!==i))return d("Virtual field unchanged",void 0);let p=N.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:s,childRenderAxis:i});return a(p)?p:d("Virtual field updated",void 0)},mp=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=N.getNode(e);if(!i){let p=N.createNode({...We.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(!zs(i))return c(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return d("Virtual field list unchanged",void 0);let u=N.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(u)?u:d("Virtual field list updated",void 0)},Nl=null,ZL=()=>{if(Nl)return d("Virtual field ranks",Nl);let e=qt(Rn/4n),t=qt(Rn/2n),n=qt(Rn*3n/4n),r=qt(Rn*7n/8n),o=qt(Rn*15n/16n),s=qt(Rn*13n/16n),i=qt(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:(Nl={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",Nl))},uc=e=>{let t=ZL();if(a(t))return t;let n=t.value,r=Ss({id:VL(e.id),name:Me.DESCRIPTION,parentNodeId:e.id,rank:n.description,value:e.props.description??"",childRenderAxis:"vertical"});if(a(r))return r;let o=mp({id:KL(e.id),name:Me.ASSIGNEES,parentNodeId:e.id,rank:n.assignees,readonly:!0});if(a(o))return o;let s=mp({id:YL(e.id),name:Me.TAGS,parentNodeId:e.id,rank:n.tags,readonly:!0});if(a(s))return s;let i=Ss({id:zL(e.id),name:Me.COMMENTS,parentNodeId:e.id,rank:n.comments,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(i))return i;let l=Ss({id:QL(e.id),name:Me.ATTACHMENTS,parentNodeId:e.id,rank:n.attachments,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(l))return l;let u=Ss({id:XL(e.id),name:Me.HISTORY,parentNodeId:e.id,rank:n.log,value:eP(e),readonly:!0,childRenderAxis:"vertical"});if(a(u))return u;let p=Ss({id:JL(e.id),name:Me.DIFF,parentNodeId:e.id,rank:n.diff,value:"",readonly:!0,childRenderAxis:"vertical"});return a(p)?p:d("Ticket virtual nodes materialized",void 0)},eP=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=>wS(r,n.get(r.action)??[])).join(`
117
- `)},NS=!0,tP=e=>{NS=e},mc=()=>NS,nP=()=>{let{nodes:e}=y();for(let t of Object.values(e)){if(!W(t))continue;let n=uc(t);if(a(n))return n}return d("Virtual nodes materialized",void 0)}});var rP,oP,Al,pp=h(()=>{"use strict";ht();rP=e=>{switch(e.action){case"add.issue":case"move.node":case"close.issue":case"reopen.issue":return e.payload.parent;default:return null}},oP=(e,t)=>{let n=[];for(let r of e){let o=rP(r);if(o===null||o===n.at(-1)?.laneId)continue;let s=Wr(r);n.push({laneId:o,enteredAt:s===null?t:Us(s)})}return n},Al=(e,t)=>oP(e,t).at(-1)?.enteredAt??t});var TS=h(()=>{"use strict";fn()});var sP,MS,Tl=h(()=>{"use strict";ht();H();kn();ca();Hr();C();TS();qn();yn();sP=e=>{let t=new Map,n=new Set,r=o=>{let s=new Set,i=o;for(;i&&!s.has(i);){if(n.has(i))return i;s.add(i),i=t.get(i)}return null};return e.map(o=>{let s=o.payload,i=s?.id;if(!i)return null;o.action==="add.board"&&n.add(i);let l=o.action==="close.issue"?r(i):null,u=s.parent??s.issue;return u&&t.set(i,u),l!==null?l:n.has(i)?i:r(i)})},MS=(e,t)=>{let n=sP(e);return e.filter((r,o)=>n[o]===t)}});var iP,kS,fp,Io,pa=h(()=>{"use strict";tt();Vo();Tl();H();H();C();O();yn();Tl();iP=null,kS=Promise.resolve(),fp=e=>{let t=kS.then(e,e);return kS=t.then(()=>{},()=>{}),t},Io=()=>{if(!ut())return{mode:"live",asOfTime:null};let{timeMode:e}=y();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:iP}}});var LS,aP,PS,OS,Co,fa=h(()=>{"use strict";De();Bt();LS=new Map,aP=3e4,PS=async e=>{let t=LS.get(e);if(t&&Date.now()-t.readAt<aP)return{name:t.name,email:t.email};let n=await Pe({args:["config","--get-regexp","^user\\.(name|email)$"],cwd:e}),r=null,o=null;if(n.exitCode===0)for(let s of(n.stdout??"").split(`
118
- `)){let i=s.indexOf(" ");if(i===-1)continue;let l=s.slice(0,i),u=s.slice(i+1);l==="user.name"&&(r=u.trim()||null),l==="user.email"&&(o=Xe(u)||null)}return LS.set(e,{name:r,email:o,readAt:Date.now()}),{name:r,email:o}},OS=async e=>(await PS(e)).email,Co=async e=>(await PS(e)).name});import cP from"node:fs";var wo,Ml,lP,dn,St,It,ue,un=h(()=>{"use strict";tt();De();wn();Xi();fa();Qt();Ue();po();kn();oe();H();C();O();yt();pa();wo=e=>{let t=Ae(e??process.cwd());return a(t)?c(t.message):d("Resolved Epiq repo root",t.value)},Ml=null,lP=async(e,t)=>{let n=wo(e);if(a(n))return n;let r=xe({repoRoot:n.value});if(a(r))return c(r.message);let o=lt(n.value);if(a(o))return c(o.message);if(!(Ml!==null&&Ml.repoRoot===n.value&&Ml.stateBranchRoot===r.value&&cP.existsSync(Xr(r.value)))){let f=await Ki({repoRoot:n.value,stateBranchName:o.value});if(a(f))return c(f.message);let g=await Ar({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(a(g))return c(g.message);Ml={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let f=await G({cwd:r.value,args:["pull","--ff-only"]});a(f)&&z.info(3,f.message)}let i={repoRoot:n.value,stateBranchRoot:r.value},l=gr();a(l)||Rt(l.value),Rt({gitEmail:await OS(n.value),gitName:await Co(n.value)});let u=kt(r.value);if(Qa(r.value)===u&&ut()&&Io().mode==="live")return d("Booted Epiq state, unchanged",i);let p=vn(r.value);if(a(p))return c(p.message);let m=Fn(p.value.events,p.value.unreadable);return a(m)?c(m.message):(Ko(r.value,u),d("Booted Epiq state",i))},dn=()=>{let e=gr();return a(e)?c(e.message):e.value.userId?e.value.userName?d("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):c("Unable to retrieve user name"):c("Unable to retrieve user id")},St=()=>{let e=Ce();return a(e)?c(e.message):e},It=e=>lP(e,{pull:!1}),ue=async e=>{let t=await It(e);if(a(t))return t;let n=dn();if(a(n))return n;let r=St();return a(r)?r:d("Booted",{boot:t.value,actor:n.value,state:r.value})}});var dP,kl,Is,_S,Cs,gp=h(()=>{"use strict";ht();ge();qn();jo();dP=e=>{let t=N.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]},kl=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 dP(r))n.add(o);return[...n]},Is=e=>Tn(e).map(t=>Ct(t.id,t.name)),_S=e=>N.getCommentsByIssue(e).sort((t,n)=>t.id<n.id?-1:t.id>n.id?1:0).map(t=>({id:t.id,author:Ws(t.authorId,N.getContributor(t.authorId)?.name),createdAt:gt(t.id),body:t.md})),Cs=e=>Mn(e).map(({id:t,name:n})=>Ct(t,n))});var ot,Fr,hp,No=h(()=>{"use strict";pe();C();un();ot=e=>{let t=St();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?c("Issue not found"):W(n)?n.readonly?c("Issue is readonly"):d("Found issue",n):c("Target must be an issue")},Fr=e=>{let t=St();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?c("Swimlane not found"):Gr(n)?n.readonly?c("Swimlane is readonly"):d("Found swimlane",n):c("Target must be a swimlane")},hp=e=>{let t=St();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?c("Board not found"):qr(n)?n.readonly?c("Board is readonly"):d("Found board",n):c("Target must be a board")}});import uP from"node:fs";import mP from"node:path";import{ulid as DS}from"ulid";var pP,FS,yp,bp=h(()=>{"use strict";Qt();H();en();C();ct();No();Wo();un();pP=e=>{if(e.filePath)try{return d("Read attachment file",{data:uP.readFileSync(e.filePath),name:e.name??mP.basename(e.filePath)})}catch(t){return c(`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"}):c("Provide either filePath or dataBase64")},FS=()=>{let e=gr();return a(e)?Yn:e.value.attachmentMaxKb??Yn},yp=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=ot(e.issueId);if(a(n))return n;let r=pP(e);if(a(r))return r;let o=xh(t.value.boot.stateBranchRoot,r.value.data,FS());if(a(o))return o;let s=ye(r.value.name).trim()||"image",i=DS(),l={id:DS(),...D(t.value.actor),action:"add.issue.attachment",payload:{id:i,issue:e.issueId,author:t.value.actor.userId,hash:o.value.hash,ext:o.value.ext,name:s,bytes:o.value.bytes}},u=F([l],t.value.boot.stateBranchRoot);if(a(u))return c(u.message);let p=Ho(o.value.hash,o.value.ext);return d("Added issue attachment",{id:i,issueId:e.issueId,fileName:p,bytes:o.value.bytes,markdown:$d(s,p)})}});var vp,AZ,Rp,BS=h(()=>{"use strict";Qt();ht();yn();pe();C();ge();Bo();qn();Cn();pp();rt();ct();Wo();yt();pa();un();gp();bp();Vc();H();zi();vp=async(e={})=>{let t=await It(e.repoRoot);if(a(t))return t;let n=St();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})},AZ=365*24*60*60*1e3,Rp=async(e={})=>{as();let t=wo(e.repoRoot);if(a(t))return c("Sync failed");let n=dn();if(a(n))return n;let r=await zc({cwd:t.value,ownEventFileName:Rr(n.value)});return a(r)?(lm(r.message),r):(fo(),d("Synced",r.value))}});var ga,ws,ha,xp=h(()=>{"use strict";C();rt();ga=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?d("Resolved targets",t):c("Provide issueId or issueIds")},ws=(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):c(`${r}: ${t.failed.map(o=>`${o.ref} ${o.reason}`).join("; ")}`)},ha=(e,t)=>{let n={done:[],failed:[]};for(let r of e){let o=t(r);a(o)?n.failed.push({id:r,ref:Y(r),reason:o.message}):n.done.push({id:r,ref:Y(r)})}return n}});import{ulid as mn}from"ulid";async function Sp(e){let t=await It(e.repoRoot);if(a(t))return t;let n=St();if(a(n))return n;let r=n.value.nodes,o=e.query?.trim().toLowerCase(),s=Object.values(r).filter(W).filter(l=>!l.isDeleted).filter(l=>e.includeClosed||l.parentNodeId!==Te).filter(l=>e.boardId?(l.parentNodeId?r[l.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(l=>!e.swimlaneId||l.parentNodeId===e.swimlaneId).filter(l=>!e.tag||Is(l).some(u=>$S(u.name,e.tag))).filter(l=>!e.assignee||Cs(l).some(u=>$S(u.name,e.assignee))).filter(l=>!o||l.title.toLowerCase().includes(o)||(l.props.description??"").toLowerCase().includes(o)),i=l=>ye((l.parentNodeId?r[l.parentNodeId]?.title:void 0)??"");return e.brief?d("Listed issues",s.map(l=>({id:l.id,ref:Y(l.id),title:ye(l.title),swimlane:i(l),tags:Is(l).map(u=>u.name),assignees:Cs(l).map(u=>u.name)}))):d("Listed issues",s.map(l=>({id:l.id,ref:Y(l.id),title:ye(l.title),description:l.props.description??"",createdAt:gt(l.id),enteredLaneAt:Al(l.log??[],gt(l.id)),parentNodeId:l.parentNodeId,isClosed:l.parentNodeId===Te,boardIds:kl(l),readonly:!!l.readonly,tags:Is(l),assignees:Cs(l)})))}async function Cp(e){let t=await It(e.repoRoot);if(a(t))return t;let n=dn();if(a(n))return n;let r=ga(e);if(a(r))return r;let o=s=>fP(s,n.value,t.value.stateBranchRoot);return e.issueIds?ws("Closed",ha(r.value,o)):o(r.value[0])}async function Np(e){let t=wo(e.repoRoot);if(a(t))return t;let n=dn();if(a(n))return n;let r=xe({repoRoot:t.value});if(a(r))return r;let o=vn(r.value);if(a(o))return o;let s=Fn(o.value.events,o.value.unreadable);if(a(s))return s;let i=ga(e);if(a(i))return i;let l=u=>gP(u,e,n.value,r.value);return e.issueIds?ws("Moved",ha(i.value,l)):l(i.value[0])}var Ep,$S,Ip,fP,wp,gP,Ap,Tp,jS=h(()=>{"use strict";tt();Km();ht();po();H();H();en();Zm();yn();pe();qn();C();ge();nn();ca();tr();pp();rt();ct();un();gp();xp();No();Ep=async e=>{let t=await It(e.repoRoot);if(a(t))return t;let n=St();if(a(n))return n;let r=e.idOrRef.trim();if(!r)return c("Provide an issue id or ref");let o=Object.values(n.value.nodes).filter(W).filter(u=>!u.isDeleted),s=o.find(u=>u.id===r),i=s?[s]:o.filter(u=>bi(u.id,r));if(i.length===0)return c(`No issue matches "${r}"`);if(i.length>1)return c(`"${r}" matches ${i.length} issues: ${i.map(u=>`${Y(u.id)} (${ye(u.title)})`).join(", ")}. Use a full ref or id.`);let l=i[0];return d("Found issue",{id:l.id,ref:Y(l.id),title:ye(l.title),description:l.props.description??"",createdAt:gt(l.id),enteredLaneAt:Al(l.log??[],gt(l.id)),parentNodeId:l.parentNodeId,isClosed:l.parentNodeId===Te,boardIds:kl(l),readonly:!!l.readonly,tags:Is(l),assignees:Cs(l),comments:_S(l.id)})},$S=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();Ip=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=ye(e.title);if(!n)return c("Issue title cannot be empty");let r=e.description??"",o=mt("Issue title",n,300)??mt("Issue description",r,2e4);if(o)return c(o);if((e.tagNames?.length??0)>20)return c(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return c(`Cannot set more than ${20} assignees at once`);let s=Fr(e.parentId);if(a(s))return s;let i=nr(e.parentId,t.value.actor,t.value.boot.stateBranchRoot);if(a(i))return i;let l=fl({name:n,parent:e.parentId,user:t.value.actor,rank:i.value});if(a(l))return l;let u=[...l.value],p=u.find(b=>b.action==="add.issue")?.payload.id;if(!p)return c("Unable to determine created issue id");r&&u.push({id:mn(),...D(t.value.actor),action:"edit.description",payload:{id:p,md:r}});let m=[];for(let b of e.tagNames??[]){let E=ye(b).trim();if(!E||m.some(A=>A.name===E))continue;let R=mt("Tag name",E,60);if(R)return c(R);let w=N.findTagByName(E),S=w?.id??mn();w||u.push({id:mn(),...D(t.value.actor),action:"create.tag",payload:{id:S,name:E}}),u.push({id:mn(),...D(t.value.actor),action:"add.issue.tag",payload:{id:p,tag:S}}),m.push({id:S,name:E})}let f=[];for(let b of e.assigneeNames??[]){let E=ye(b).trim();if(!E||f.some(A=>A.name===E))continue;let R=mt("Assignee name",E,80);if(R)return c(R);let w=Object.values(t.value.state.contributors).find(A=>A.name===E),S=w?.id??mn();w||u.push({id:mn(),...D(t.value.actor),action:"create.contributor",payload:{id:S,name:E}}),u.push({id:mn(),...D(t.value.actor),action:"add.issue.assignee",payload:{id:p,assignee:S}}),f.push({id:S,name:E})}let g=F(u,t.value.boot.stateBranchRoot);return a(g)?c(g.message):d("Created issue",{id:p,ref:Y(p),title:n,parentId:e.parentId,description:r,tags:m,assignees:f})},fP=(e,t,n)=>{let r=ot(e);if(a(r))return r;let o=_n(Te,e,{at:"end"},t,n);if(a(o))return o;let s={id:mn(),...D(t),action:"close.issue",payload:{id:e,parent:Te,rank:o.value}},i=F([s],n);return a(i)?c(i.message):d("Closed issue",{id:e,ref:Y(e)})};wp=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=t.value.state.nodes[e.issueId];if(!n||n.isDeleted)return c("Issue not found");if(!W(n))return c("Target must be an issue");if(n.parentNodeId!==Te)return c("Issue is not closed");let r=vl(n);if(!r)return c("Unable to resolve previous parent from issue history");if(r===Te)return c("Previous parent resolves to closed swimlane");let o=Fr(r);if(a(o))return o;let s=o.value,i=_n(s.id,n.id,{at:"end"},t.value.actor,t.value.boot.stateBranchRoot);if(a(i))return i;let l={id:mn(),...D(t.value.actor),action:"reopen.issue",payload:{id:n.id,parent:s.id,rank:i.value}},u=F([l],t.value.boot.stateBranchRoot);return a(u)?c(u.message):d("Reopened issue",{id:n.id,ref:Y(n.id),parentId:s.id})},gP=(e,t,n,r)=>{let o=ot(e);if(a(o))return o;let s=Fr(t.parentId);if(a(s))return s;let i=_n(t.parentId,e,t.position??{at:"end"},n,r);if(a(i))return i;let l={id:mn(),...D(n),action:"move.node",payload:{id:e,parent:t.parentId,rank:i.value}},u=F([l],r);return a(u)?c(u.message):d("Moved issue",{id:e,ref:Y(e),parentId:t.parentId})};Ap=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=ot(e.issueId);if(a(n))return n;let r=n.value,o=mt("Issue description",e.description,2e4);if(o)return c(o);let s=r.props.description??"";if(s===e.description)return d("No changes made",{id:e.issueId,ref:Y(e.issueId),description:s});let i={id:mn(),...D(t.value.actor),action:"edit.description",payload:{id:e.issueId,md:e.description}},l=F([i],t.value.boot.stateBranchRoot);return a(l)?c(l.message):d("Edited issue description",{id:e.issueId,ref:Y(e.issueId),description:e.description})},Tp=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=ot(e.issueId);if(a(n))return n;let r=n.value,o=ye(e.title);if(!o.trim())return c("Issue title cannot be empty");let s=mt("Issue title",o,300);if(s)return c(s);if(r.title===o)return d("No changes made",{id:e.issueId,ref:Y(e.issueId),title:o});let i={id:mn(),...D(t.value.actor),action:"edit.title",payload:{id:e.issueId,name:o}},l=F([i],t.value.boot.stateBranchRoot);return a(l)?c(l.message):d("Edited issue title",{id:e.issueId,ref:Y(e.issueId),title:o})}});import{ulid as Br}from"ulid";var Mp,kp,Lp,Pp,Op,_p,Dp,Fp,US=h(()=>{"use strict";tt();po();H();H();en();yn();pe();C();nn();tr();rt();ct();pa();un();No();Mp=async(e={})=>{let t=await It(e.repoRoot);if(a(t))return t;let n=St();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:Y(o.id),title:o.title,parentId:o.parentNodeId,readonly:!!o.readonly}));return d("Listed boards",r)},kp=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=t.value.state.nodes[t.value.state.rootNodeId];if(!n)return c("Workspace not found");if(Io().mode!=="live")return c("Cannot add a board while time travelling");let r=ye(e.title);if(!r.trim())return c("Board title cannot be empty");let o=mt("Board title",r,300);if(o)return c(o);let s=nr(n.id,t.value.actor,t.value.boot.stateBranchRoot);if(a(s))return s;let i=Br(),l={id:Br(),...D(t.value.actor),action:"add.board",payload:{id:i,name:r,parent:n.id,rank:s.value}},u=F([l],t.value.boot.stateBranchRoot);return a(u)?c(u.message):d("Created board",{id:i,ref:Y(i),title:r})},Lp=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=t.value.state.nodes[e.boardId];if(!n||n.isDeleted)return c("Board not found");if(!qr(n))return c("Edit target must be a board");if(n.readonly)return c("Cannot edit readonly board");if(Io().mode!=="live")return c("Cannot rename a board while time travelling");let r=ye(e.title);if(!r.trim())return c("Board title cannot be empty");let o=mt("Board title",r,300);if(o)return c(o);if(n.title===r)return d("No changes made",{id:e.boardId,ref:Y(e.boardId),title:r});let s={id:Br(),...D(t.value.actor),action:"edit.title",payload:{id:e.boardId,name:r}},i=F([s],t.value.boot.stateBranchRoot);return a(i)?c(i.message):d("Edited board title",{id:e.boardId,ref:Y(e.boardId),title:r})},Pp=async(e={})=>{let t=await It(e.repoRoot);if(a(t))return t;let n=St();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===Te,readonly:!!o.readonly}));return d("Listed swimlanes",r)},Op=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=hp(e.boardId);if(a(n))return n;if(Io().mode!=="live")return c("Cannot add a swimlane while time travelling");let r=ye(e.title);if(!r.trim())return c("Swimlane title cannot be empty");let o=mt("Swimlane title",r,300);if(o)return c(o);let s=nr(e.boardId,t.value.actor,t.value.boot.stateBranchRoot);if(a(s))return s;let i=Br(),l={id:Br(),...D(t.value.actor),action:"add.swimlane",payload:{id:i,name:r,parent:e.boardId,rank:s.value}},u=F([l],t.value.boot.stateBranchRoot);return a(u)?c(u.message):d("Created swimlane",{id:i,ref:Y(i),title:r,boardId:e.boardId})},_p=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=Fr(e.swimlaneId);if(a(n))return n;let r=n.value,o=ye(e.title);if(!o.trim())return c("Swimlane title cannot be empty");let s=mt("Swimlane title",o,300);if(s)return c(s);if(r.title===o)return d("No changes made",{id:e.swimlaneId,ref:Y(e.swimlaneId),title:o});let i={id:Br(),...D(t.value.actor),action:"edit.title",payload:{id:e.swimlaneId,name:o}},l=F([i],t.value.boot.stateBranchRoot);return a(l)?c(l.message):d("Edited swimlane title",{id:e.swimlaneId,ref:Y(e.swimlaneId),title:o})},Dp=async e=>{let t=wo(e.repoRoot);if(a(t))return t;let n=dn();if(a(n))return n;let r=xe({repoRoot:t.value});if(a(r))return r;let o=vn(r.value);if(a(o))return o;let s=Fn(o.value.events,o.value.unreadable);if(a(s))return s;let i=Fr(e.swimlaneId);if(a(i))return i;let l=hp(e.boardId);if(a(l))return l;let u=_n(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(a(u))return u;let p={id:Br(),...D(n.value),action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:u.value}},m=F([p],r.value);return a(m)?c(m.message):d("Moved swimlane",{id:e.swimlaneId,ref:Y(e.swimlaneId),boardId:e.boardId})},Fp=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=Fr(e.swimlaneId);if(a(n))return n;let r={id:Br(),...D(t.value.actor),action:"delete.node",payload:{id:e.swimlaneId}},o=F([r],t.value.boot.stateBranchRoot);return a(o)?c(o.message):d("Deleted swimlane",{id:e.swimlaneId,ref:Y(e.swimlaneId)})}});import{ulid as Ts}from"ulid";async function Bp(e){let t=await It(e.repoRoot);if(a(t))return t;let n=dn();if(a(n))return n;let r=ga(e);if(a(r))return r;let o=ye(e.tagName).trim();if(!o)return c("Tag name cannot be empty");let s=mt("Tag name",o,60);if(s)return c(s);let i=ha(r.value,ot);if(!e.issueIds&&i.failed[0])return c(i.failed[0].reason);if(i.done.length===0)return c(ws("Tagged",i).message);let l=N.findTagByName(o),u=l?.id??Ts(),p=[...l?[]:[{id:Ts(),...D(n.value),action:"create.tag",payload:{id:u,name:o}}],...i.done.map(({id:b})=>({id:Ts(),...D(n.value),action:"add.issue.tag",payload:{id:b,tag:u}}))],m=F(p,t.value.stateBranchRoot);if(a(m))return c(m.message);let f={id:u,name:o};if(!e.issueIds)return d("Added issue tag",{...i.done[0],tag:f});let g=ws("Tagged",i);return a(g)?g:d(g.message,{...g.value,tag:f})}var $p,jp,Up,HS=h(()=>{"use strict";H();en();C();ge();tr();rt();ct();un();xp();No();$p=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=t.value.state.tags[e.tagId];if(!n)return c("Tag not found");if(n.tombstoned)return c("Tag is already deleted");let r=[{id:Ts(),...D(t.value.actor),action:"tombstone.tag",payload:{id:e.tagId}}],o=F(r,t.value.boot.stateBranchRoot);return a(o)?c(o.message):d("Deleted tag",{id:n.id,name:n.name})},jp=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=t.value.state.tags[e.tagId];if(!n)return c("Tag not found");if(!n.tombstoned)return c("Tag is not deleted");if(N.findTagByName(n.name))return c(`Cannot restore: another tag is already named "${n.name}"`);let r=[{id:Ts(),...D(t.value.actor),action:"restore.tag",payload:{id:e.tagId,name:n.name}}],o=F(r,t.value.boot.stateBranchRoot);return a(o)?c(o.message):d("Restored tag",{id:n.id,name:n.name})},Up=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=ot(e.issueId);if(a(n))return n;if(!t.value.state.tags[e.tagId])return c("Tag not found");let r={id:Ts(),...D(t.value.actor),action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},o=F([r],t.value.boot.stateBranchRoot);return a(o)?c(o.message):d("Removed issue tag",{id:e.issueId,ref:Y(e.issueId),tagId:e.tagId})}});import{ulid as lr}from"ulid";var Hp,WS,Wp,Gp,hP,qp,zp,Vp,GS=h(()=>{"use strict";C();fn();$r();H();H();en();Rl();qn();Tl();tr();rt();ct();un();No();Hp=async e=>{let t=Hl(e.name,"name");if(a(t))return c(t.message);let n=await ue(e.repoRoot);if(a(n))return n;let r=n.value.actor,o=!!n.value.state.contributors[r.userId];if(!o){let s=F([{id:lr(),...D(r),action:"create.contributor",payload:{id:r.userId,name:r.userName}}],n.value.boot.stateBranchRoot);if(a(s))return c(s.message)}return d(`Assumed ${r.userName}`,{...r,registered:!o})},WS=async(e,t)=>{let n=io(e).get(t);return n===void 0?void 0:{id:t,name:n}},Wp=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=ot(e.issueId);if(a(n))return n;let r=e.self?t.value.actor.userId:e.assigneeId;if(r){let b=t.value.state.contributors[r],E=b?void 0:await WS(t.value.boot.stateBranchRoot,r);if(!b&&!E)return c("Unknown assignee id");let R=b??E,w=[...b?[]:[{id:lr(),...D(t.value.actor),action:"create.contributor",payload:{id:R.id,name:R.name}}],{id:lr(),...D(t.value.actor),action:"add.issue.assignee",payload:{id:e.issueId,assignee:R.id}}],S=F(w,t.value.boot.stateBranchRoot);return a(S)?c(S.message):d("Added issue assignee",{id:e.issueId,ref:Y(e.issueId),assignee:{id:R.id,name:R.name}})}let o=ye(e.assigneeName??"").trim();if(!o)return c("Provide assigneeId, self or assigneeName");let s=mt("Assignee name",o,80);if(s)return c(s);let i=da({events:t.value.state.eventLog??[],registry:t.value.state.contributors,logFileNames:io(t.value.boot.stateBranchRoot)}).filter(b=>b.name===o);if(i.length>1)return c(`"${o}" matches ${i.length} contributors (${i.map(({id:b})=>b).join(", ")}). Assign by assigneeId to choose.`);let l=i[0];if(!l&&!e.createUnlinked)return c(`No contributor named "${o}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let u=l?.id??lr(),p=l?.name??o,f=[...!!t.value.state.contributors[u]?[]:[{id:lr(),...D(t.value.actor),action:"create.contributor",payload:{id:u,name:p}}],{id:lr(),...D(t.value.actor),action:"add.issue.assignee",payload:{id:e.issueId,assignee:u}}],g=F(f,t.value.boot.stateBranchRoot);return a(g)?c(g.message):d("Added issue assignee",{id:e.issueId,ref:Y(e.issueId),assignee:{id:u,name:p}})},Gp=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;if(!t.value.state.contributors[e.contributorId])return c("Contributor not found");if(await WS(t.value.boot.stateBranchRoot,e.contributorId))return c("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let o=[{id:lr(),...D(t.value.actor),action:"tombstone.contributor",payload:{id:e.contributorId}}],s=F(o,t.value.boot.stateBranchRoot);return a(s)?c(s.message):d("Tombstoned contributor",{id:e.contributorId,name:Gs})},hP=async(e,t)=>{let n=Zn(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},qp=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=t.value.state.contributors[e.contributorId];if(!n)return c("Contributor not found");if(!n.tombstoned)return c("Contributor is not tombstoned");let r=await hP(t.value.boot.stateBranchRoot,e.contributorId);if(!r)return c("Cannot restore this contributor \u2014 no original name found in the event log");let o=[{id:lr(),...D(t.value.actor),action:"restore.contributor",payload:{id:e.contributorId,name:r}}],s=F(o,t.value.boot.stateBranchRoot);return a(s)?c(s.message):d("Restored contributor",{id:e.contributorId,name:r})},zp=async(e={})=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=Zn(t.value.boot.stateBranchRoot);if(a(n))return c(n.message);let r=e.boardId?MS(n.value,e.boardId):n.value,o=new Set,s=fy(t.value.boot.stateBranchRoot);if(a(s))return c(s.message);for(let u of s.value)u.userId&&o.add(u.userId);let i=t.value.state.contributors,l=da({events:r,registry:i,logFileNames:io(t.value.boot.stateBranchRoot)}).map(({id:u,name:p,isExternal:m})=>({...Ct(u,p),isSelf:u===t.value.actor.userId,isExternal:m,isRemoved:i[u]?.tombstoned===!0,hasAuthoredAnywhere:o.has(u)}));return d("Listed board contributors",l)},Vp=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=ot(e.issueId);if(a(n))return n;if(!t.value.state.contributors[e.assigneeId])return c("Assignee not found");let r={id:lr(),...D(t.value.actor),action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},o=F([r],t.value.boot.stateBranchRoot);return a(o)?c(o.message):d("Removed issue assignee",{id:e.issueId,ref:Y(e.issueId),assigneeId:e.assigneeId})}});import{ulid as Ol}from"ulid";var Kp,Yp,Xp,qS=h(()=>{"use strict";H();en();C();tr();un();No();Kp=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=ot(e.issueId);if(a(n))return n;let r=e.body.trim();if(!r)return c("Comment cannot be empty");if(r.length>4e3)return c(`Comment cannot exceed ${4e3} characters (got ${r.length})`);let o=Ol(),s={id:Ol(),...D(t.value.actor),action:"add.issue.comment",payload:{id:o,issue:e.issueId,md:r,author:t.value.actor.userId}},i=F([s],t.value.boot.stateBranchRoot);return a(i)?c(i.message):d("Added issue comment",{id:o,issueId:e.issueId,body:r})},Yp=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=t.value.state.eventLog.find(l=>l.action==="add.issue.comment"&&l.payload.id===e.commentId);if(!n)return c("Unable to resolve comment");if(n.payload.author!==t.value.actor.userId)return c("You can only delete your own comments");let r=ot(n.payload.issue);if(a(r))return r;if(t.value.state.eventLog.some(l=>l.action==="delete.issue.comment"&&l.payload.id===e.commentId))return d("Comment already deleted",{id:e.commentId,issueId:n.payload.issue});let s={id:Ol(),...D(t.value.actor),action:"delete.issue.comment",payload:{id:e.commentId,issue:n.payload.issue}},i=F([s],t.value.boot.stateBranchRoot);return a(i)?c(i.message):d("Deleted issue comment",{id:e.commentId,issueId:n.payload.issue})},Xp=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=t.value.state.eventLog.find(u=>u.action==="add.issue.comment"&&u.payload.id===e.commentId);if(!n)return c("Unable to resolve comment");if(n.payload.author!==t.value.actor.userId)return c("You can only edit your own comments");let r=ot(n.payload.issue);if(a(r))return r;if(t.value.state.eventLog.some(u=>u.action==="delete.issue.comment"&&u.payload.id===e.commentId))return c("Comment was deleted");let s=e.body.trim();if(!s)return c("Comment cannot be empty");if(s.length>4e3)return c(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i={id:Ol(),...D(t.value.actor),action:"edit.issue.comment",payload:{id:e.commentId,issue:n.payload.issue,md:s}},l=F([i],t.value.boot.stateBranchRoot);return a(l)?c(l.message):d("Edited issue comment",{id:e.commentId,issueId:n.payload.issue,body:s})}});import{ulid as zS}from"ulid";var Jp,Qp,Zp,ef,tf=h(()=>{"use strict";H();Bt();qn();C();wn();fa();Il();Ue();un();Jp=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;if(!ur(e.email))return c(`Not an email address: ${e.email}`);let n=Xe(e.email),r=e.contributorId??t.value.actor.userId;if(!t.value.state.contributors[r])return c(`Unknown contributor: ${r}`);let o=nd(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=F([{id:zS(),action:"link.contributor.email",payload:{contributor:r,email:n},userId:t.value.actor.userId}],t.value.boot.stateBranchRoot);return a(s)?c(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})},Qp=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let n=Xe(e.email),r=e.contributorId??t.value.actor.userId,o=t.value.state.emailLinks[qs(n,r)];if(!o||o.tombstoned)return c(`No such link: ${n} to ${r}`);if(!Na(t.value.actor.userId,o))return c("Only whoever made a claim, or the contributor it names, may undo it");let s=F([{id:zS(),action:"unlink.contributor.email",payload:{contributor:r,email:n},userId:t.value.actor.userId}],t.value.boot.stateBranchRoot);return a(s)?c(s.message):d(`Unclaimed ${n}`,{contributor:r,email:n})},Zp=async(e={})=>{let t=await It(e.repoRoot);if(a(t))return t;let n=St();if(a(n))return n;let{emailLinks:r,contributors:o}=n.value,s=new Map;for(let f of Object.values(r)){if(f.tombstoned)continue;let g=s.get(f.email)??new Set;g.add(f.contributor),s.set(f.email,g)}let i=[...s.entries()].map(([f,g])=>({email:f,contested:g.size>1,claimants:[...g].map(b=>Ct(b,o[b]?.name))})).sort((f,g)=>f.email.localeCompare(g.email)),l=dn(),u=a(l)?[]:mr(r,l.value.userId),p=ce().gitEmail,m=p?nd(r,p).filter(f=>a(l)||f!==l.value.userId):[];return d("Listed contributor emails",{emails:i,mine:u,git:p?{email:p,linkedToMe:u.includes(p),heldByOthers:m.map(f=>Ct(f,o[f]?.name))}:null})},ef=async(e={})=>{let t=await ue(e.repoRoot);if(a(t))return t;let{userId:n,userName:r}=t.value.actor,o=lt(t.value.boot.repoRoot),s=await ua({repoRoot:t.value.boot.repoRoot,stateBranch:a(o)?void 0:o.value,names:[r,await Co(t.value.boot.repoRoot)],links:t.value.state.emailLinks});if(a(s))return s;let i=Sl(s.value),l=i.filter(u=>u.looksLikeYours);return d(i.length===0?"No unclaimed addresses in this history":`${i.length} unclaimed address(es) in this history, ${l.length>0?`${l.length} of which look like yours`:"none obviously yours"}. Show them to the user and link only the ones they confirm; each is a permanent event that replicates to every clone.`,{contributor:n,candidates:i,likely:l.length})}});var VS=h(()=>{"use strict";ht();C()});var KS=h(()=>{"use strict";wn();fa();C();Il();VS();un()});var nf,rf,of,sf,af,YS,XS=h(()=>{"use strict";Cr();C();ko();un();nf=e=>{let t=Oi(e);return a(t)?c(t.message):d("Listed repos",{repos:t.value,claimedBytes:wc(e),limit:Hn,allowLocal:xa()})},rf=async(e={})=>{let t=Mt(e.repoRoot);return a(t)?c(t.message):nf(t.value)},of=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let{repoRoot:n}=t.value.boot,r=await Fi({repoRoot:n,actorId:t.value.actor.userId,url:e.url,branches:e.branches,since:e.since,label:e.label,mode:e.previewOnly?"preview":e.confirm?"confirm":"auto"});if(a(r))return c(r.message);let o=nf(n);return a(o)?c(o.message):d(r.message,{...o.value,...r.value.kind==="preview"?{preview:r.value.preview}:{}})},sf=async e=>{let t=await ue(e.repoRoot);if(a(t))return t;let{repoRoot:n}=t.value.boot,r=_i({repoRoot:n,actorId:t.value.actor.userId,repo:e.repo});if(a(r))return c(r.message);let o=nf(n);return a(o)?c(o.message):d(r.message,o.value)},af=async(e,t={},n=2e4)=>{if(a(e))return e;let r,o=await Promise.race([YS(t),new Promise(s=>{r=setTimeout(()=>s(null),n)})]);return clearTimeout(r),o===null?d(`${e.message} \xB7 still fetching other repos; epiq_repo_list shows how they stand`,e.value):a(o)||o.value.length===0?e:d([e.message,Di(o.value)].filter(Boolean).join(" \xB7 "),{...e.value,repos:o.value})},YS=async(e={})=>{let t=Mt(e.repoRoot);return a(t)?c(t.message):Zo({repoRoot:t.value,minIntervalMs:e.minIntervalMs})}});var JS=h(()=>{"use strict";BS();jS();US();HS();GS();qS();bp();tf();KS();XS()});import{ulid as yP}from"ulid";var QS,ZS,eI,tI=h(()=>{"use strict";$r();Bo();fa();Qt();C();Gm();yt();QS=[{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)"}],ZS=e=>e.trim().toLowerCase(),eI=async(e={})=>{let t=Jt();if(a(t))return c(t.message);let n=t.value,r=e.userName?.trim(),o=(process.env[Kt]??"").trim();if(r&&o&&ZS(r)===ZS(o))return c(`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 QS){let S=s[w.name],A=i[w.name];if(!(S===void 0||A===void 0||S===A))return c(`This machine is already set up with ${w.name} ${JSON.stringify(A)}; epiq_project_init does not change it. Call again without ${w.name}, or let the user change it in the TUI with :config.`)}let l={};if(s.userName&&!i.userName&&(l.userName=s.userName),s.preferredEditor&&!i.preferredEditor&&(l.preferredEditor=s.preferredEditor),s.autoSync!==void 0&&i.autoSync===void 0&&(l.autoSync=s.autoSync),(l.userName||i.userName)&&!n.userId&&(l.userId=yP()),Object.keys(l).length>0){let w=dt(l);if(a(w))return c(w.message)}let u={...n,...l},p=QS.filter(w=>{let S=u[w.name];return typeof S=="boolean"?!1:!S?.trim()});if(p.length>0){let w=p.map(L=>`${L.name} (${L.question})`).join("; "),S=p.some(L=>L.name==="userName")?await Co(e.repoRoot??process.cwd()):null,A=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 c(`Setup incomplete. Ask the user for: ${w}.${A} 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 c("Missing Epiq user id");let f=await pl({cwd:e.repoRoot??process.cwd(),user:m});if(a(f))return f;let{defaultEvents:g,...b}=f.value,E=oi({root:b.repoRoot});a(E)&&z.info(E.message);let R=b.warnings.length===0?"Project initialized":`Project initialized, with warnings: ${b.warnings.join(" ")}`;return d(R,{...b,user:m})}});var jn,_l=h(()=>{"use strict";jn=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""})});var bP,nI,rI=h(()=>{"use strict";_l();bP=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},nI=({commits:e,patch:t})=>{let n=e.map(i=>i.time),o=t.files.map(i=>({...jn(i),changed:i.addedCount+i.removed})).reduce((i,l)=>i===null||l.changed>i.changed?l:i,null),s=t.insertions+t.deletions;return{commits:e.length,authors:[...new Set(e.map(i=>i.author))].sort(),firstCommitAt:n.length?Math.min(...n):null,lastCommitAt:n.length?Math.max(...n):null,files:t.files.length,filesAdded:t.files.filter(i=>i.status==="added").length,filesModified:t.files.filter(i=>i.status==="modified").length,filesDeleted:t.files.filter(i=>i.status==="deleted").length,binaryFiles:t.files.filter(i=>i.binary).length,directories:new Set(t.files.map(i=>bP(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 Qe,pn,cf,Ms,vP,ee,Dl,Fl,oI,RP,sI,Ao,ba,xP,EP,ks,SP,IP,CP,In,iI,aI,cI,wP,NP,lI,dI,Ls=h(()=>{"use strict";Qe={line:["//"],block:[["/*","*/"]]},pn={line:["#"],block:[]},cf={line:["--"],block:[]},Ms={line:[],block:[["<!--","-->"]]},vP={line:[],block:[]},ee=(e,t)=>({name:e,comment:t}),Dl=ee("TypeScript",Qe),Fl=ee("JavaScript",Qe),oI={ts:Dl,tsx:Dl,mts:Dl,cts:Dl,js:Fl,jsx:Fl,mjs:Fl,cjs:Fl,py:ee("Python",{line:["#"],block:[['"""','"""']]}),rb:ee("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:ee("Go",Qe),rs:ee("Rust",Qe),java:ee("Java",Qe),kt:ee("Kotlin",Qe),swift:ee("Swift",Qe),c:ee("C",Qe),h:ee("C",Qe),cc:ee("C++",Qe),cpp:ee("C++",Qe),hpp:ee("C++",Qe),cs:ee("C#",Qe),php:ee("PHP",Qe),scala:ee("Scala",Qe),dart:ee("Dart",Qe),lua:ee("Lua",cf),hs:ee("Haskell",cf),sql:ee("SQL",cf),ex:ee("Elixir",pn),exs:ee("Elixir",pn),pl:ee("Perl",pn),r:ee("R",pn),jl:ee("Julia",pn),sh:ee("Shell",pn),bash:ee("Shell",pn),zsh:ee("Shell",pn),vue:ee("Vue",Ms),svelte:ee("Svelte",Ms),html:ee("HTML",Ms),xml:ee("XML",Ms),md:ee("Markdown",Ms),mdx:ee("Markdown",Ms),css:ee("CSS",{line:[],block:[["/*","*/"]]}),scss:ee("CSS",Qe),less:ee("CSS",Qe),yml:ee("YAML",pn),yaml:ee("YAML",pn),toml:ee("TOML",pn),ini:ee("INI",pn),json:ee("JSON",vP)},RP="Other",sI=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},Ao=e=>oI[sI(e)]?.name??RP,ba=e=>oI[sI(e)]?.comment??null,xP=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],EP=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,ks=e=>EP.test(e)||xP.some(t=>t.test(e)),SP=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,IP=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,CP=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,In=e=>SP.test(e)||IP.test(e)||CP.test(e),iI=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),aI=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),cI=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),wP=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,NP=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,lI=e=>wP.test(e),dI=e=>NP.test(e)});var uI,AP,lf,TP,mI,df=h(()=>{"use strict";Ls();uI=/\b(TODO|FIXME|HACK|XXX)\b/,AP=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,lf=(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"},TP=(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},mI=({patch:e,repoShareByLanguage:t})=>{let n=new Map,r=0,o=0,s=0,i=0,l=0,u=0;for(let m of e.files){if(m.binary||In(m.path))continue;let f=ba(m.path);if(!f||f.line.length===0&&f.block.length===0)continue;let g=Ao(m.path),b=n.get(g)??{comment:0,code:0};for(let{text:E}of m.added){let R=lf(E,f);if(uI.test(E)&&i++,R==="blank"){s++;continue}if(R==="comment"){r++,b.comment++,f&&AP.test(TP(E,f))&&u++;continue}o++,b.code++}for(let{text:E}of m.removedLines)uI.test(E)&&l++;n.set(g,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:l,commentedOutCodeLines:u}}});var MP,Bl,uf,kP,LP,PP,pI,fI=h(()=>{"use strict";Ls();_l();MP=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,Bl=6,uf=10,kP=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)},LP=(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)},PP=e=>{if(e.length<Bl*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let r=0;r+Bl<=e.length;r++){let o=e.slice(r,r+Bl);if(o.some(l=>l.text.length<3))continue;let s=o.map(l=>l.text).join(`
119
- `),i=t.get(s);if(i===void 0){t.set(s,{...o[0],at:r});continue}if(i.file!==o[0]?.file)for(let l=0;l<Bl;l++)n[i.at+l]=!0,n[r+l]=!0}return n.filter(Boolean).length},pI=({patch:e})=>{let t=[],n=[],r=[],o=!1,s=0,i=0,l=null,u=[];for(let[p,m]of e.files.entries()){if(In(m.path)&&t.push(jn(m)),iI(m.path)&&n.push(jn(m)),aI(m.path)&&r.push(jn(m)),cI(m.path)&&(o=!0),m.binary||In(m.path))continue;let f=m.added.map(E=>E.text),g=kP(f),b=m.status!=="deleted";for(let E of f){MP.test(E)&&s++;let R=LP(E,g);R>i&&(i=R,l=jn(m)),b&&u.push({text:E.trim(),file:p})}u.push({text:" ",file:p})}return{generatedPaths:t.slice(0,uf),dependencyManifests:n.slice(0,uf),buildOrCiPaths:r.slice(0,uf),docsTouched:o,debugPrintLinesAdded:s,maxIndentLevels:i,deepestFile:l,duplicatedLines:PP(u)}}});var gI,hI=h(()=>{"use strict";Ls();gI=({patch:e,languagesBefore:t})=>{let n=new Map,r=0;for(let i of e.files){if(i.binary)continue;let l=i.addedCount+i.removed;if(In(i.path)){r+=l;continue}let u=Ao(i.path),p=n.get(u)??{name:u,added:0,removed:0,addedInTests:0,share:0};p.added+=i.addedCount,p.removed+=i.removed,ks(i.path)&&(p.addedInTests+=i.addedCount),n.set(u,p)}let o=[...n.values()].reduce((i,l)=>i+l.added+l.removed,0),s=[...n.values()].map(i=>({...i,share:o===0?0:(i.added+i.removed)/o})).sort((i,l)=>l.added+l.removed-(i.added+i.removed));return{languages:s,introduced:t===null?[]:s.filter(i=>!t.has(i.name)).map(i=>i.name),generatedLines:r}}});var OP,mf,_P,DP,yI,pf,FP,BP,bI,vI,$P,jP,UP,RI,xI=h(()=>{"use strict";De();C();OP=200,mf=2e5,_P=5e4,DP=25,yI=64*1024*1024,pf="",FP=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/,BP=/^diff --git a\/(.+) b\/\1$/,bI=(e,t)=>e==="/dev/null"?null:e.startsWith(t)?e.slice(2):e,vI=(e,t)=>e===null?"added":t===null?"deleted":"modified",$P=()=>({byPath:new Map,insertions:0,deletions:0,selfChurn:0,retainedLines:0}),jP=(e,t)=>{let n=e.byPath,r="",o=null,s=null,i=null,l=!1,u=0,p=(f,g)=>g==="modified"&&f==="added"?"added":g,m=(f,g)=>{let b=n.get(f);if(b)return b.entry.status=p(b.entry.status,g),b.entry.shas.includes(r)||b.entry.shas.push(r),b;let R={entry:{path:f,status:g,binary:!1,added:[],addedCount:0,removed:0,removedLines:[],shas:[r]},pendingByText:new Map};return n.set(f,R),R};for(let f of t.split(`
120
- `)){if(f.startsWith(pf)){r=f.slice(pf.length).trim(),o=null,s=null,i=null,l=!1;continue}if(f.startsWith("diff --git ")){o=null,i=null,l=!0,s=BP.exec(f)?.[1]??null;continue}if(l&&f.startsWith("Binary files ")&&s){let[,b=""]=/^Binary files (.*) differ$/.exec(f)??[],[E="",R=""]=b.split(" and ");o=m(s,vI(E==="/dev/null"?null:E,R==="/dev/null"?null:R)),o.entry.binary=!0;continue}if(l&&f.startsWith("--- ")){i=bI(f.slice(4),"a/");continue}if(l&&f.startsWith("+++ ")){let b=bI(f.slice(4),"b/"),E=b??i??s;E&&(o=m(E,vI(i,b)));continue}let g=FP.exec(f);if(g){u=Number(g[1]),l=!1;continue}if(o){if(f.startsWith("+")){let b=f.slice(1);e.insertions++,o.entry.addedCount++,e.retainedLines<mf&&(o.entry.added.push({sha:r,line:u,text:b}),e.retainedLines++),o.pendingByText.size<_P&&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<mf&&(o.entry.removedLines.push({sha:r,line:0,text:b}),e.retainedLines++);let E=o.pendingByText.get(b)??0;E>0&&b.trim().length>2&&(e.selfChurn++,o.pendingByText.set(b,E-1))}}}},UP=e=>({files:[...e.byPath.values()].map(t=>t.entry),insertions:e.insertions,deletions:e.deletions,selfChurn:e.selfChurn,retainedLines:e.retainedLines}),RI=async({repoRoot:e,shas:t,cwdOf:n=()=>e})=>{if(t.length===0)return d("No commits to scan",{files:[],insertions:0,deletions:0,selfChurn:0,scannedCommits:0,truncated:!1});let r=t.slice(0,OP).reverse(),o=$P(),s=0,i=0,l=!1,u=[];for(let m of r){let f=n(m),g=u[u.length-1];g&&g.cwd===f&&g.shas.length<DP?g.shas.push(m):u.push({cwd:f,shas:[m]})}for(let{cwd:m,shas:f}of u){let g=await G({cwd:m,maxOutput:Math.max(1,yI-s),keepPartial:!0,args:["-c","core.quotePath=false","show","--unified=0","--no-renames","--no-color",`--format=${pf}%H`,...f]});if(a(g)){if(m!==e)continue;return c(g.message)}if(jP(o,g.value.stdout),s+=g.value.stdout.length,i+=f.length,g.value.truncated||s>yI){l=!0;break}}let p=UP(o);return d("Scanned ticket patch",{files:p.files,insertions:p.insertions,deletions:p.deletions,selfChurn:p.selfChurn,scannedCommits:i,truncated:l||i<t.length||p.retainedLines>=mf})}});var HP,WP,EI,SI=h(()=>{"use strict";De();C();df();Ls();HP=40,WP=/^\d{6} blob ([0-9a-f]{40})\t(.+)$/,EI=async({repoRoot:e,sha:t})=>{let n=await Pe({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(`
121
- `)){let f=WP.exec(m);if(!f)continue;let[,g="",b=""]=f;if(In(b))continue;let E=Ao(b);if(r.add(E),ks(b)||!ba(b))continue;let R=o.get(E)??[];R.length<HP&&(R.push({blob:g,path:b}),o.set(E,R))}let s=[...o.values()].flat(),i=await yd(s.map(m=>m.blob),e);if(a(i))return{languages:r,commentShareByLanguage:new Map};let l=i.value,u=new Map;for(let{blob:m,path:f}of s){let g=l.get(m);if(g===void 0)continue;let b=ba(f),E=Ao(f),R=u.get(E)??{comment:0,code:0};for(let w of g.split(`
122
- `)){let S=lf(w,b);S==="comment"&&R.comment++,S==="code"&&R.code++}u.set(E,R)}let p=new Map;for(let[m,f]of u){let g=f.comment+f.code;g>0&&p.set(m,f.comment/g)}return{languages:r,commentShareByLanguage:p}}});var II,CI=h(()=>{"use strict";Ls();_l();II=({patch:e})=>{let t=0,n=0,r=[],o=[],s=0,i=0;for(let l of e.files)if(!(l.binary||In(l.path))&&ks(l.path)){t+=l.addedCount,n+=l.removed,l.status==="added"&&r.push(jn(l)),l.status==="deleted"&&o.push(jn(l));for(let{text:u}of l.added)lI(u)&&s++,dI(u)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:r,deletedTestFiles:o,skippedTestLinesAdded:s,focusedTestLinesAdded:i}}});var GP,wI,NI=h(()=>{"use strict";lo();C();rI();df();fI();hI();xI();SI();CI();GP=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null),wI=async({repoRoot:e,ref:t,commits:n})=>{let r=await co(e);if(a(r))return c(r.message);let o=Rc(r.value),s=new Map(n.map(f=>[f.sha,f.repo])),i=f=>o(s.get(f))??e,l=await RI({repoRoot:e,shas:n.map(f=>f.sha),cwdOf:i});if(a(l))return c(l.message);let u=l.value,p=GP(n),m=p?await EI({repoRoot:i(p.sha),sha:p.sha}):null;return d("Derived issue stats",{ref:t,shape:nI({commits:n,patch:u}),languages:gI({patch:u,languagesBefore:m?.languages??null}),tests:II({patch:u}),comments:mI({patch:u,repoShareByLanguage:m?.commentShareByLanguage??null}),flags:pI({patch:u})})}});var AI,TI=h(()=>{"use strict";Rl();C();Bt();O();AI=e=>{if(a(e))return e;let t=Ce(),n=a(t)?{}:t.value.emailLinks,r=a(t)?{}:t.value.contributors,o=jf(n),s=e.value.map(i=>({...i,authorIdentity:gE({authorName:i.author,authorEmail:i.authorEmail,owners:o,registry:r})}));return d(e.message,s)}});var qP,va,zP,MI,kI=h(()=>{"use strict";C();NI();rt();oe();TI();Cr();qP=32,va=new Map,zP=(e,t)=>{if(va.set(e,t),va.size>qP){let n=va.keys().next();n.done||va.delete(n.value)}return t},MI=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return c("idOrRef must not be empty");let n=t.length>7?Y(t):t.toUpperCase(),r=Ae(e.repoRoot??process.cwd());if(a(r))return c(r.message);let o=r.value,s=AI(await Ai({repoRoot:o,ref:n}));if(a(s))return c(s.message);let i=s.value.map(m=>({sha:m.sha,...m.repo?{repo:m.repo}:{},time:m.time,author:m.authorIdentity?.resolved?m.authorIdentity.name:m.author,subject:m.subject})),l=[o,n,i.map(m=>`${m.sha}:${m.author}`).join(",")].join(" "),u=va.get(l);if(u)return d("Derived issue stats",u);let p=await wI({repoRoot:o,ref:n,commits:i});return a(p)?c(p.message):d("Derived issue stats",zP(l,p.value))}});var Ps,ff,LI=h(()=>{"use strict";Ps=".claude/skills/epiq/SKILL.md",ff=`---
123
- name: epiq
124
- 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.
125
- ---
126
-
127
- # Epiq board workflow
128
-
129
- - **Use the \`epiq_*\` MCP tools** for every board read and write \u2014 never the CLI, hand edits, or the state branch directly.
130
- - 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.
131
- - Keep the status column current as work progresses (move tickets along the board with correct status)
132
- - **Sync is on demand:** call \`epiq_sync\` to pull or publish; nothing else does.
133
- - **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.
134
- - Break work into small, reasonably scoped tickets.
135
- - **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.
136
- - **Keep tickets small**; put a small follow-up on its existing ticket instead of a new one.
137
- - **Read a ticket's comments before starting.**
138
- - **Picking up a ticket:** assign yourself and move it to the in-progress lane. Ask before taking one assigned to someone else.
139
- - **Keep status, tags and description current**; reuse existing tags.
140
- - **Comment** on deviations, blockers, and the outcome when done.
141
- - **Prompt user for closing tickets and big decisions**
142
- - **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.
143
- - **Link commits** by starting the subject with the ticket's \`ref\` from the MCP response \u2014 never derive the ref from the id.
144
- - *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.
145
- - **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.
146
- - **Be concise.** Titles, descriptions, and comments should be scannable, not essays.
147
- - **When a ticket is done, Document the outcome in a comment starting with "Solution:"**. Use that exact prefix as the comment's opening line.
148
- - **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.
149
- - 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.
150
- `});import $l from"node:fs";import PI from"node:path";var OI,_I=h(()=>{"use strict";tt();C();LI();OI=async(e={})=>{let t=await jt(e.repoRoot??process.cwd());if(a(t))return c(t.message);let n=PI.join(t.value,Ps);if($l.existsSync(n)){if($l.readFileSync(n,"utf8")===ff)return d("Skill already installed and up to date",{path:n,written:!1});if(!e.force)return c(`${Ps} already exists and differs from the bundled skill. Pass force:true to overwrite it.`)}try{$l.mkdirSync(PI.dirname(n),{recursive:!0}),$l.writeFileSync(n,ff,"utf8")}catch(r){return c(r instanceof Error?`Failed to write ${Ps}: ${r.message}`:`Failed to write ${Ps}`)}return d(`Installed skill at ${Ps}`,{path:n,written:!0})}});var FI={};Ds(FI,{createMcpServer:()=>DI,resultJson:()=>To,startMcpServer:()=>XP});import{McpServer as KP}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as YP}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as v}from"zod";var To,de,DI,XP,BI=h(()=>{"use strict";ko();C();tr();JS();tf();tI();kI();_I();pa();To=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),de=e=>t=>fp(async()=>To(await e(t))),DI=()=>{let e=new KP({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:v.object({repoRoot:v.string().optional()})},de(vp)),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:v.object({repoRoot:v.string().optional(),includeClosed:v.boolean().optional(),boardId:v.string().optional(),swimlaneId:v.string().optional(),tag:v.string().optional(),assignee:v.string().optional(),query:v.string().optional(),brief:v.boolean().optional()})},de(Sp)),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:v.object({idOrRef:v.string().min(1),repoRoot:v.string().optional()})},de(Ep)),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:v.object({idOrRef:v.string().min(1),repoRoot:v.string().optional()})},async t=>To(await MI(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:v.object({repoRoot:v.string().optional()})},de(Mp)),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:v.object({repoRoot:v.string().optional(),title:v.string().min(1).max(300)})},de(kp)),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:v.object({repoRoot:v.string().optional(),boardId:v.string().optional()})},de(Pp)),e.registerTool("epiq_swimlane_create",{description:"Create an Epiq swimlane on a board",inputSchema:v.object({repoRoot:v.string().optional(),boardId:v.string().min(1),title:v.string().min(1).max(300)})},de(Op)),e.registerTool("epiq_swimlane_title_edit",{description:"Edit an Epiq swimlane title",inputSchema:v.object({repoRoot:v.string().optional(),swimlaneId:v.string().min(1),title:v.string().min(1).max(300)})},de(_p)),e.registerTool("epiq_board_title_edit",{description:"Edit an Epiq board title. Refused while time travelling.",inputSchema:v.object({repoRoot:v.string().optional(),boardId:v.string().min(1),title:v.string().min(1).max(300)})},de(Lp)),e.registerTool("epiq_swimlane_move",{description:"Move/reorder an Epiq swimlane, optionally to another board",inputSchema:v.object({repoRoot:v.string().optional(),swimlaneId:v.string().min(1),boardId:v.string().min(1),position:v.discriminatedUnion("at",[v.object({at:v.literal("start")}),v.object({at:v.literal("end")}),v.object({at:v.literal("before"),sibling:v.string().min(1)}),v.object({at:v.literal("after"),sibling:v.string().min(1)})]).optional()})},de(Dp)),e.registerTool("epiq_swimlane_delete",{description:"Delete (archive) an Epiq swimlane. This also archives every issue contained in it.",inputSchema:v.object({repoRoot:v.string().optional(),swimlaneId:v.string().min(1)})},de(Fp)),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:v.object({title:v.string().min(1).max(300),parentId:v.string().min(1),repoRoot:v.string().optional(),description:v.string().max(2e4).optional(),tagNames:v.array(v.string().max(60)).max(20).optional(),assigneeNames:v.array(v.string().max(80)).max(20).optional()})},de(Ip)),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),description:v.string().max(2e4),repoRoot:v.string().optional()})},de(Ap)),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),title:v.string().min(1).max(300),repoRoot:v.string().optional()})},de(Tp)),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:v.object({issueId:v.string().min(1).optional(),issueIds:v.array(v.string().min(1)).min(1).max(200).optional(),tagName:v.string().min(1).max(60),repoRoot:v.string().optional()})},de(Bp)),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),tagId:v.string().min(1),repoRoot:v.string().optional()})},de(Up)),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:v.object({boardId:v.string().min(1).optional(),repoRoot:v.string().optional()})},de(zp)),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:v.object({contributorId:v.string().min(1),repoRoot:v.string().optional()})},de(Gp)),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:v.object({tagId:v.string().min(1),repoRoot:v.string().optional()})},de($p)),e.registerTool("epiq_tag_restore",{description:"Put back a tag deleted with epiq_tag_remove, on every ticket that still carried it.",inputSchema:v.object({tagId:v.string().min(1),repoRoot:v.string().optional()})},de(jp)),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:v.object({contributorId:v.string().min(1),repoRoot:v.string().optional()})},de(qp)),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:v.object({issueId:v.string().min(1),assigneeId:v.string().min(1).optional(),self:v.boolean().optional(),assigneeName:v.string().min(1).max(80).optional(),createUnlinked:v.boolean().optional(),repoRoot:v.string().optional()})},de(Wp)),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),assigneeId:v.string().min(1),repoRoot:v.string().optional()})},de(Vp)),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),body:v.string().min(1).max(4e3),repoRoot:v.string().optional()})},de(Kp)),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:v.object({issueId:v.string().min(1),filePath:v.string().min(1),name:v.string().min(1).max(200).optional(),repoRoot:v.string().optional()})},de(yp)),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:v.object({commentId:v.string().min(1),repoRoot:v.string().optional()})},de(Yp)),e.registerTool("epiq_issue_comment_edit",{description:"Replace the body of one of your own comments on an Epiq issue",inputSchema:v.object({commentId:v.string().min(1),body:v.string().min(1).max(4e3),repoRoot:v.string().optional()})},de(Xp)),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:v.object({issueId:v.string().min(1),repoRoot:v.string().optional()})},de(wp)),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue, or many at once with issueIds \u2014 one call, an outcome per ticket",inputSchema:v.object({issueId:v.string().min(1).optional(),issueIds:v.array(v.string().min(1)).min(1).max(200).optional(),repoRoot:v.string().optional()})},de(Cp)),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:v.object({issueId:v.string().min(1).optional(),issueIds:v.array(v.string().min(1)).min(1).max(200).optional(),parentId:v.string().min(1),position:v.discriminatedUnion("at",[v.object({at:v.literal("start")}),v.object({at:v.literal("end")}),v.object({at:v.literal("before"),sibling:v.string().min(1)}),v.object({at:v.literal("after"),sibling:v.string().min(1)})]).optional(),repoRoot:v.string().optional()})},de(Np)),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:v.object({name:v.string().min(1).max(80),repoRoot:v.string().optional()})},de(Hp)),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:v.object({email:v.string().min(1).max(254),contributorId:v.string().min(1).optional(),repoRoot:v.string().optional()})},de(Jp)),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:v.object({email:v.string().min(1).max(254),contributorId:v.string().min(1).optional(),repoRoot:v.string().optional()})},de(Qp)),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:v.object({repoRoot:v.string().optional()})},de(ef)),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:v.object({repoRoot:v.string().optional()})},de(Zp)),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:v.object({repoRoot:v.string().optional(),userName:v.string().min(1).max(80).optional(),preferredEditor:v.string().min(1).max(200).optional(),autoSync:v.boolean().optional()})},de(eI)),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:v.object({repoRoot:v.string().optional(),force:v.boolean().optional()})},de(OI)),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote (pull remote changes and push local ones), then fetch the repos connected with epiq_repo_connect. 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:v.object({repoRoot:v.string().optional()})},async t=>To(await af(await fp(()=>Rp(t)),t))),e.registerTool("epiq_repo_list",{description:"List the repos connected to the board, whose commits count as its own: each with this machine's clone status, size on disk and last fetch error, whether it is past the board's limit and so not fetched, and what all of them take on this machine.",inputSchema:v.object({repoRoot:v.string().optional()})},async t=>To(await rf(t))),e.registerTool("epiq_repo_connect",{description:"Connect another repo to the board by URL (https://, ssh://, git:// or user@host:path; never a local path, which nobody else could fetch), so commits there prefixed with a ticket's ref link to it; or change a connected repo's options. Connecting is a two-step, board-wide action: every contributor's epiq downloads the repo on their next sync. The first call clones it into a staging area and returns a preview (size, host, default branch, latest commit, how many commits name this board's tickets \u2014 none suggests the wrong repo) and writes nothing. Show the preview to the user; only once they agree, call again with confirm: true and the same options. Option changes to an already connected repo apply at once. branches: default (the default branch only) or all. since: how much history to clone \u2014 board (since the board was created, the default), all, or YYYY-MM-DD. label: what the repo is called on the board \u2014 its URL's basename unless set; empty goes back to the basename. Cloning uses your git credentials: ssh-agent or a credential helper must already work, since a passphrase prompt cannot be answered.",inputSchema:v.object({repoRoot:v.string().optional(),url:v.string().min(1).max(Gl),branches:v.enum(["default","all"]).optional(),since:v.string().max(20).optional(),label:v.string().max(24).optional(),confirm:v.boolean().optional()})},async t=>To(await of(t))),e.registerTool("epiq_repo_disconnect",{description:"Disconnect a repo by its label (when no other repo shares it), id or URL, and delete this machine's clone of it.",inputSchema:v.object({repoRoot:v.string().optional(),repo:v.string().min(1).max(2e3)})},async t=>To(await sf(t))),e},XP=async()=>{let e=DI(),t=new YP;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:JP}=await Promise.resolve().then(()=>($r(),xf)),{isFail:QP}=await Promise.resolve().then(()=>(C(),bf)),{parseMcpArgs:ZP}=await Promise.resolve().then(()=>(If(),Sf)),Os=ZP(process.argv.slice(2));Os.kind==="error"&&(console.error(Os.message),process.exit(1));Os.kind==="print"&&(process.stdout.write(Os.text),process.exit(0));if(Os.kind==="name"){let e=JP(Os.name,"The name argument");QP(e)&&(console.error(e.message),process.exit(1))}var{setVirtualNodesEnabled:e0}=await Promise.resolve().then(()=>(lu(),AS));e0(!1);var{startMcpServer:t0}=await Promise.resolve().then(()=>(BI(),FI));await t0();
2
+ process.env.EPIQ_MCP="true";process.env.NODE_ENV||="production";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;var{applyActorNameArgument:r}=await import("./actor-env-F6R6NBSD.js"),{isFail:s}=await import("./result-types-RM3ASLV3.js"),{parseMcpArgs:t}=await import("./args-Y5YFYS72.js"),e=t(process.argv.slice(2));e.kind==="error"&&(console.error(e.message),process.exit(1));e.kind==="print"&&(process.stdout.write(e.text),process.exit(0));if(e.kind==="name"){let o=r(e.name,"The name argument");s(o)&&(console.error(o.message),process.exit(1))}var{setVirtualNodesEnabled:n}=await import("./virtual-nodes-COSSGT2L.js");n(!1);var{startMcpServer:a}=await import("./server-2COW5M6S.js");await a();