epiq 1.8.6 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gui/main.js +3412 -2046
- package/dist/index.js +101 -91
- package/dist/mcp.js +92 -82
- package/package.json +5 -3
- package/readme.md +2 -1
package/dist/mcp.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Ux=Object.defineProperty;var g=(e,t)=>()=>(e&&(t=e(e=0)),t);var Zr=(e,t)=>{for(var n in t)Ux(e,n,{get:t[n],enumerable:!0})};var nm={};Zr(nm,{failed:()=>l,isFail:()=>a,isSuccess:()=>Dt,resultStatuses:()=>Sn,succeeded:()=>d});var Sn,l,d,a,Dt,w=g(()=>{"use strict";Sn={Success:"success",Fail:"fail"},l=e=>({status:Sn.Fail,message:e,value:null}),d=(e,t)=>({status:Sn.Success,message:e,value:t}),a=e=>e.status==="fail",Dt=e=>e.status==="success"});var sm={};Zr(sm,{ACTOR_ID_ENV:()=>es,ACTOR_NAME_ENV:()=>Ot,applyActorNameArgument:()=>vl,deriveActorId:()=>rm,isValidUserId:()=>gi,isValidUserName:()=>ts,resolveEnvActor:()=>hl});import Hx from"node:crypto";var Ot,es,om,Wx,gl,gi,ts,Qo,rm,hl,vl,vo=g(()=>{"use strict";w();Ot="EPIQ_USER_NAME",es="EPIQ_USER_ID",om="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Wx=26,gl=80,gi=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),ts=e=>e.trim().length>0&&e.length<=gl,Qo=e=>e.trim().toLowerCase(),rm=e=>{let t=Hx.createHash("sha256").update(`epiq:actor:${Qo(e)}`).digest(),n="";for(let o=0;o<Wx;o++)n+=om[(t[o]??0)%om.length];return n},hl=(e,t=process.env)=>{let n=(t[Ot]??"").trim(),o=(t[es]??"").trim();return n?ts(n)?!o&&e.userId&&e.userName&&Qo(e.userName)===Qo(n)?d("Actor override names the configured user",{userId:e.userId,userName:e.userName}):o&&!gi(o)?l(`${es} must be 26 characters of Crockford base32`):o&&e.userId&&o===e.userId?l(`${es} 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:o||rm(n),userName:o?n:Qo(n)}):l(`${Ot} must be 1-${gl} characters of text`):o?l(`${es} is set without ${Ot}`):d("No actor override",null)},vl=(e,t,n=process.env)=>{let o=e.trim();if(!ts(o))return l(`${t} must be 1-${gl} characters of text`);let r=(n[Ot]??"").trim();return r&&Qo(r)!==Qo(o)?l(`${t} names ${o}, but ${Ot} names ${r}`):(r||(n[Ot]=o),d("Applied actor name argument",r||o))}});var yl,im=g(()=>{"use strict";yl="1.9.0"});var am={};Zr(am,{parseMcpArgs:()=>Gx});var qx,Gx,lm=g(()=>{"use strict";im();qx=`epiq-mcp ${yl}
|
|
3
3
|
|
|
4
4
|
Usage: epiq-mcp [name]
|
|
5
5
|
|
|
@@ -9,94 +9,104 @@ Usage: epiq-mcp [name]
|
|
|
9
9
|
Options:
|
|
10
10
|
-v, --version print the version
|
|
11
11
|
-h, --help print this help
|
|
12
|
-
`,
|
|
13
|
-
`}:t==="--help"||t==="-h"?{kind:"print",text:Xv}:t.startsWith("-")?{kind:"error",message:`Unknown option ${t}; expected a name, e.g. epiq-mcp claude/peter`}:{kind:"name",name:t}}});import{decodeTime as Ml}from"ulid";var As,No,Ge,Co,Pl,Vn,Je=h(()=>{"use strict";S();As=1440*60*1e3,No=(e,t=Date.now())=>e>t+As?t:e,Ge=e=>No(Ml(e)),Co=e=>{let t=Date.now()+As,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})},Pl=e=>{try{return l("Decoded date",new Date(Ge(e)))}catch(t){return d("Decoding failed + "+t.message)}},Vn=e=>{if(!e?.id)return null;try{return Ml(e.id)}catch{return null}}});var Ts,lt,Ll,$t=h(()=>{"use strict";S();Ts="removed",lt=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?l("Found node",n):d("Unable to find node in breadcrumb")},Ll=["png","jpg","gif","webp"]});function pa(e){return e.context===Y.WORKSPACE}function F(e){return e.context===Y.TICKET}function Dl(e){return e.context===Y.TEXT}function ut(e){return e.context===Y.FIELD}function wo(e){return e.context===Y.FIELD_LIST}var Y,Kn,Yn,Ao,ee=h(()=>{"use strict";Y={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};Kn=e=>e.context===Y.SWIMLANE,Yn=e=>e.context===Y.BOARD,Ao=e=>e.context===Y.COMMENT});var b,ve=h(()=>{"use strict";b={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var _l=h(()=>{"use strict";Xn()});import Fl from"string-width";function ks(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Jn,Qv,fa,Zv,ga,le,mt=h(()=>{"use strict";Jn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Qv=/\u001B\[[0-9;]*m/,fa="\x1B[0m",Zv=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),ga=(e,t)=>{if(t<=0)return"";if(Fl(e)<=t)return e;if(t<=3)return"...".slice(0,t);let r=t-3,o="",s=0,i=!1;for(let c of e.split(/(\u001B\[[0-9;]*m)/))if(c!==""){if(Qv.test(c)){o+=c,i=c!==fa&&c!=="\x1B[m";continue}for(let u of Zv(c)){let m=Fl(u);if(s+m>r)return`${o}...${i?fa:""}`;o+=u,s+=m}}return`${o}...${i?fa:""}`},le=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var Bl,Ol,Ul=h(()=>{"use strict";Bl=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},Ol=(e,t)=>t?e.get(t)??[]:[]});var jl,ey,$l,Wl=h(()=>{"use strict";mt();Ul();jl=new WeakMap,ey=e=>{let t=jl.get(e);return t||(t=Bl(e),jl.set(e,t)),t},$l=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Ol(ey(e),r).filter(s=>ks(r,s)>=n)}});var ty,Hl,ny,ql=h(()=>{"use strict";mt();Wl();ty={hint:"",hints:[],overlap:0,remainder:""},Hl=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return ty;let o=$l({wordList:r,inputToMatch:e,overlapThreshold:1});return ny(t,o)},ny=(e,t)=>{let n=t[0]??"",r=ks(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,p=(c&&i?o:n)+(c&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}}});import{useSyncExternalStore as bN}from"react";var Ms,ry,oy,xe,xt,ze=h(()=>{"use strict";Ms={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},ry=new Set,oy=()=>{for(let e of ry)e()},xe=()=>Ms,xt=e=>(Ms={...Ms,...e},oy(),Ms)});function Gl(e){return!e||!iy.test(e)?d(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function Et(e,t=To){if(e<0n)return d("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Ve(e,t){if(!e&&!t)return Et(Wt/2n,To);let n=e?Gl(e):l("Resolved lower bound",0n);if(a(n))return n;let r=t?Gl(t):l("Resolved upper bound",Wt);if(a(r))return r;let o=n.value,s=r.value;if(s<=o)return d("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?d("No rank space available between neighbors"):Et(i,To)}function zl(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Wt*BigInt(r+1)/(t+1n),s=Et(o,To);if(a(s))return s;n.push(s.value)}return l("Resolved evenly spaced ranks",n)}var To,sy,Wt,iy,wr=h(()=>{"use strict";S();To=24n,sy=To*4n,Wt=(1n<<sy)-1n,iy=/^[0-9a-f]+$/});import{ulid as ay}from"ulid";var ha,Vl=h(()=>{"use strict";S();Rt();wr();ha=(e,t)=>{let n=ye(e),r=zl(n.length);if(a(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],c=r.value[s];if(!i||!c)return d("Unable to assign rebalance rank");o[i.id]=c}return l("Created rebalance event",{id:ay(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})}});import ko from"node:fs";import{ulid as dy}from"ulid";import{z as Ps}from"zod";var cy,ly,Ls,pt,Mo,va,Ht=h(()=>{"use strict";S();ie();cy="__epiq_state__",ly=Ps.object({projectId:Ps.string().min(1),stateBranch:Ps.string().min(1),createdAt:Ps.iso.datetime()}),Ls=()=>({projectId:dy(),stateBranch:cy,createdAt:new Date().toISOString()}),pt=e=>{let t=Ar(e);if(!ko.existsSync(t))return d("Missing .epiq/project.json");try{let n=ko.readFileSync(t,"utf8"),r=JSON.parse(n),o=ly.safeParse(r);return o.success?l("Read project.json",o.data):d(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return d(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},Mo=e=>{let t=pt(e);return a(t)?d(t.message):l("Read projectId",t.value.projectId)},va=({repoRoot:e,fileContents:t})=>{let n=Qn(e),r=Ar(e);try{if(ko.mkdirSync(n,{recursive:!0}),ko.existsSync(r)){let o=pt(e);return a(o)?d(o.message):l("Project already initialized",null)}return ko.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
14
|
-
`,"utf8"),
|
|
15
|
-
`);u(n?{stdout:i,stderr:f,exitCode:124}:
|
|
16
|
-
`)))}),
|
|
17
|
-
`)));return}u(
|
|
18
|
-
${s}`:""}`));return}let
|
|
12
|
+
`,Gx=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:`${yl}
|
|
13
|
+
`}:t==="--help"||t==="-h"?{kind:"print",text:qx}:t.startsWith("-")?{kind:"error",message:`Unknown option ${t}; expected a name, e.g. epiq-mcp claude/peter`}:{kind:"name",name:t}}});import{decodeTime as cm}from"ulid";var hi,ns,ct,os,dm,yo,ft=g(()=>{"use strict";w();hi=1440*60*1e3,ns=(e,t=Date.now())=>e>t+hi?t:e,ct=e=>ns(cm(e)),os=e=>{let t=Date.now()+hi,n=e.find(r=>r!==null&&r<=t)??null;if(n===null)return[...e];let o=null;return e.map(r=>{if(r===null)return null;let s=r<=t?r:o??n;return o=s,s})},dm=e=>{try{return d("Decoded date",new Date(ct(e)))}catch(t){return l("Decoding failed + "+t.message)}},yo=e=>{if(!e?.id)return null;try{return cm(e.id)}catch{return null}}});var tt,k,Je=g(()=>{"use strict";tt={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"},k={accent:tt.cyan,accent2:tt.magenta,primary:tt.white,secondary:tt.grayDark,secondary2:tt.grayLight,gray:tt.gray,green:tt.green,yellow:tt.yellow,red:tt.red}});var M,vi,bl=g(()=>{"use strict";Je();M={red:tt.red,yellow:tt.yellow,green:tt.green,blue:tt.blue,magenta:tt.magenta,cyan:tt.cyan},vi={urgent:M.red,critical:M.red,important:M.red,blocker:M.red,asap:M.red,immediate:M.red,fail:M.red,failure:M.red,broken:M.red,bug:M.red,error:M.red,incident:M.red,outage:M.red,production:M.red,crash:M.red,security:M.red,warning:M.yellow,warn:M.yellow,risky:M.yellow,risk:M.yellow,attention:M.yellow,pending:M.yellow,review:M.yellow,"needs-review":M.yellow,qa:M.yellow,testing:M.yellow,test:M.yellow,validate:M.yellow,verification:M.yellow,staging:M.yellow,check:M.yellow,"follow-up":M.yellow,followup:M.yellow,waiting:M.yellow,blocked:M.yellow,hold:M.yellow,done:M.green,complete:M.green,completed:M.green,success:M.green,ok:M.green,stable:M.green,resolved:M.green,fixed:M.green,closed:M.green,merged:M.green,released:M.green,deployed:M.green,approved:M.green,verified:M.green,working:M.green,healthy:M.green,pass:M.green,passing:M.green,info:M.blue,information:M.blue,note:M.blue,docs:M.blue,documentation:M.blue,doc:M.blue,guide:M.blue,help:M.blue,explanation:M.blue,detail:M.blue,details:M.blue,context:M.blue,design:M.blue,discussion:M.blue,proposal:M.blue,idea:M.blue,feature:M.magenta,enhancement:M.magenta,improvement:M.magenta,refactor:M.magenta,refactoring:M.magenta,cleanup:M.magenta,optimize:M.magenta,optimization:M.magenta,perf:M.magenta,performance:M.magenta,upgrade:M.magenta,migration:M.magenta,modernize:M.magenta,debt:M.magenta,todo:M.cyan,next:M.cyan,planned:M.cyan,plan:M.cyan,future:M.cyan,backlog:M.cyan,investigate:M.cyan,explore:M.cyan,prototype:M.cyan}});import um from"chalk";var Il,mm,xl,pm,zx,Vx,fm,Kx,Yx,El,nt,gm,hm,yi,Xx,Jx,bi,dn=g(()=>{"use strict";bl();Il={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},mm=(e,t,n)=>Math.max(t,Math.min(n,e)),xl=(e,t,n)=>e+(t-e)*n,pm=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},zx=e=>e.toLowerCase().trim(),Vx=(e,t,n)=>{let o=t/100,r=n/100,s=(1-Math.abs(2*r-1))*o,i=e/60,c=s*(1-Math.abs(i%2-1)),u=0,p=0,m=0;i>=0&&i<1?(u=s,p=c):i>=1&&i<2?(u=c,p=s):i>=2&&i<3?(p=s,m=c):i>=3&&i<4?(p=c,m=s):i>=4&&i<5?(u=c,m=s):(u=s,m=c);let f=r-s/2;return[Math.round((u+f)*255),Math.round((p+f)*255),Math.round((m+f)*255)]},fm=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Kx=(e,t,n)=>{let o=mm(n,0,1);return[Math.round(xl(e[0],t[0],o)),Math.round(xl(e[1],t[1],o)),Math.round(xl(e[2],t[2],o))]},Yx=(e,t,n)=>Kx(e,t,n),El=e=>{let t=pm(e)%360,n=Vx(t,Il.stringColor.saturation,Il.stringColor.lightness);return fm(n)},nt=(e,t=vi)=>{let n=zx(e??"");return n&&t[n]?t[n]:El(n)},gm=e=>{let t=Il.gradient.stops,n=mm(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let o=t.length-1,r=n*o,s=Math.min(Math.floor(r),o-1),i=r-s;return Yx(t[s],t[s+1],i)},hm=e=>fm(gm(e)),yi=e=>pm(e.toLowerCase().trim())/4294967295,Xx=e=>{let t=yi(e);return gm(t)},Jx=e=>{let[t,n,o]=Xx(e);return{normal:r=>um.bgRgb(t,n,o).black(r),cursor:r=>um.bgRgb(t,n,o).white.bold(r)}},bi=e=>Jx(e).normal(` ${e} `)});var Qx,rs,gt,Nn=g(()=>{"use strict";dn();Qx="Unknown",rs=(e,t)=>t?.length?t:e?.length?e:Qx,gt=(e,t)=>{let n=rs(e,t);return{id:e?.length?e:n,name:n,color:nt(n)}}});var ss,Nt,vm,Yt=g(()=>{"use strict";w();ss="removed",Nt=(e,t)=>{let n=e.find(o=>o.context===t);return n!==void 0?d("Found node",n):l("Unable to find node in breadcrumb")},vm=["png","jpg","gif","webp"]});var Ve,Gn,is,Rl,Sl,zn,ym,xi,wt=g(()=>{"use strict";Ve=e=>e.trim().toLowerCase(),Gn=e=>{let t=Ve(e);return t.length>0&&t.length<=254&&/^[^\s@]+@[^\s@]+$/.test(t)},is=(e,t)=>`${Ve(e)} ${t}`,Rl=e=>!e.tombstoned,Sl=(e,t)=>{let n=Ve(t),o=new Set;for(let r of Object.values(e))Rl(r)&&r.email===n&&o.add(r.contributor);return[...o]},zn=(e,t)=>{let n=new Set;for(let o of Object.values(e))Rl(o)&&o.contributor===t&&n.add(o.email);return[...n]},ym=e=>{let t=new Map;for(let o of Object.values(e)){if(!Rl(o))continue;let r=t.get(o.email)??new Set;r.add(o.contributor),t.set(o.email,r)}let n=new Map;for(let[o,r]of t){let[s]=[...r];r.size===1&&s&&n.set(o,s)}return n},xi=(e,t)=>e===t.authorId||e===t.contributor});function Nl(e){return e.context===se.WORKSPACE}function U(e){return e.context===se.TICKET}function bm(e){return e.context===se.TEXT}function ot(e){return e.context===se.FIELD}function as(e){return e.context===se.FIELD_LIST}var se,bo,xo,ls,me=g(()=>{"use strict";se={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};bo=e=>e.context===se.SWIMLANE,xo=e=>e.context===se.BOARD,ls=e=>e.context===se.COMMENT});var b,Oe=g(()=>{"use strict";b={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette",IDENTITY:"identity"}});var xm=g(()=>{"use strict";Vn()});import Im from"string-width";function Ii(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}var Io,Zx,wl,eI,Eo,Se,ht=g(()=>{"use strict";Io=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Zx=/\u001B\[[0-9;]*m/,wl="\x1B[0m",eI=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),Eo=(e,t)=>{if(t<=0)return"";if(Im(e)<=t)return e;if(t<=3)return"...".slice(0,t);let o=t-3,r="",s=0,i=!1;for(let c of e.split(/(\u001B\[[0-9;]*m)/))if(c!==""){if(Zx.test(c)){r+=c,i=c!==wl&&c!=="\x1B[m";continue}for(let u of eI(c)){let p=Im(u);if(s+p>o)return`${r}...${i?wl:""}`;r+=u,s+=p}}return`${r}...${i?wl:""}`},Se=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var Em,Rm,Sm=g(()=>{"use strict";Em=e=>{let t=new Map;for(let n of e){let o=n.toLowerCase();for(let r=1;r<=n.length;r++){let s=o.slice(0,r),i=t.get(s);i?i.push(n):t.set(s,[n])}}return t},Rm=(e,t)=>t?e.get(t)??[]:[]});var Nm,tI,wm,Cm=g(()=>{"use strict";ht();Sm();Nm=new WeakMap,tI=e=>{let t=Nm.get(e);return t||(t=Em(e),Nm.set(e,t)),t},wm=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let o=t.toLowerCase();return Rm(tI(e),o).filter(s=>Ii(o,s.toLowerCase())>=n)}});var nI,Tm,Am,km=g(()=>{"use strict";ht();Cm();nI={hint:"",hints:[],overlap:0,remainder:""},Tm=({inputToMatch:e,lastWord:t,isLastWordCompleted:n,inputString:o},r,s=[])=>{if(n||e===""){let[c]=s;return s.length===1&&c&&!o.trim()?Am("",[c]):nI}let i=wm({wordList:r,inputToMatch:e,overlapThreshold:1});return Am(t,i)},Am=(e,t)=>{let n=t[0]??"",o=Ii(e.toLowerCase(),n.toLowerCase()),[r,s]=n.split(":"),i=o<(r??"").length,c=!!s,m=(c&&i?r:n)+(c&&i?":":" "),f=m.slice(o);return{hint:m,hints:t,overlap:o,remainder:f}}});import{useSyncExternalStore as QA}from"react";var Ei,oI,rI,le,Qe,Fe=g(()=>{"use strict";Ei={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,gitEmail:null,gitName:null,declinedEmailBoards:[],viewMode:null},oI=new Set,rI=()=>{for(let e of oI)e()},le=()=>Ei,Qe=e=>(Ei={...Ei,...e},rI(),Ei)});function Mm(e){return!e||!iI.test(e)?l(`Invalid hex rank: ${e}`):d("Converted rank to bigint",BigInt("0x"+e))}function Ct(e,t=cs){if(e<0n)return l("Negative rank not allowed");let n=e.toString(16);return d("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function dt(e,t){if(!e&&!t)return Ct(Xt/2n,cs);let n=e?Mm(e):d("Resolved lower bound",0n);if(a(n))return n;let o=t?Mm(t):d("Resolved upper bound",Xt);if(a(o))return o;let r=n.value,s=o.value;if(s<=r)return l("Neighbouring ranks leave no space between them");let i=(r+s)/2n;return i===r||i===s?l("No rank space available between neighbors"):Ct(i,cs)}function Lm(e){if(e<=0)return d("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let o=0;o<e;o++){let r=Xt*BigInt(o+1)/(t+1n),s=Ct(r,cs);if(a(s))return s;n.push(s.value)}return d("Resolved evenly spaced ranks",n)}var cs,sI,Xt,iI,Zo=g(()=>{"use strict";w();cs=24n,sI=cs*4n,Xt=(1n<<sI)-1n,iI=/^[0-9a-f]+$/});var D,Pm,Ft=g(()=>{"use strict";D=({userId:e})=>({userId:e}),Pm=e=>({action:e.action,payload:e.payload})});var Cl,cT,_t=g(()=>{"use strict";Ft();Cl=["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"],cT=new Set(Cl)});import{ulid as aI}from"ulid";var Al,Dm=g(()=>{"use strict";w();Bt();Zo();_t();Al=(e,t)=>{let n=ke(e),o=Lm(n.length);if(a(o))return o;let r={};for(let s=0;s<n.length;s++){let i=n[s],c=o.value[s];if(!i||!c)return l("Unable to assign rebalance rank");r[i.id]=c}return d("Created rebalance event",{id:aI(),action:"rebalance.children",payload:{parent:e,ranks:r},...D(t)})}});import{z as Ro}from"zod";var Om,Fm,lI,cI,_m,dI,uI,Tl,Bm,kl,ds=g(()=>{"use strict";w();Om=1,Fm=Ro.tuple([Ro.string().min(1),Ro.string().min(1).nullable()]),lI=Ro.looseObject({v:Ro.literal(Om),id:Fm}),cI=Ro.looseObject({v:Ro.number().int().positive(),id:Fm}),_m=e=>{let t=cI.safeParse(e);return t.success?d("Parsed persisted event envelope",t.data):l(`Invalid persisted event envelope: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},dI=[1],uI=new Set(dI),Tl=e=>uI.has(e),Bm=e=>{let t=lI.safeParse(e);return t.success?d("Parsed persisted event",t.data):l(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},kl=(e,t)=>{let n={[e.action]:e.payload,v:Om,id:t};return Bm(n)}});import us from"node:fs";import{ulid as mI}from"ulid";import{z as Ri}from"zod";var pI,fI,Si,At,un,Ml,Jt=g(()=>{"use strict";w();ee();pI="__epiq_state__",fI=Ri.object({projectId:Ri.string().min(1),stateBranch:Ri.string().min(1),createdAt:Ri.iso.datetime()}),Si=()=>({projectId:mI(),stateBranch:pI,createdAt:new Date().toISOString()}),At=e=>{let t=er(e);if(!us.existsSync(t))return l("Missing .epiq/project.json");try{let n=us.readFileSync(t,"utf8"),o=JSON.parse(n),r=fI.safeParse(o);return r.success?d("Read project.json",r.data):l(`Invalid .epiq/project.json: ${r.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return l(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},un=e=>{let t=At(e);return a(t)?l(t.message):d("Read projectId",t.value.projectId)},Ml=({repoRoot:e,fileContents:t})=>{let n=So(e),o=er(e);try{if(us.mkdirSync(n,{recursive:!0}),us.existsSync(o)){let r=At(e);return a(r)?l(r.message):d("Project already initialized",null)}return us.writeFileSync(o,JSON.stringify(t,null,2)+`
|
|
14
|
+
`,"utf8"),d("Created project.json",null)}catch(r){return l(r instanceof Error?`Failed to initialize project: ${r.message}`:"Failed to initialize project")}}});import gI from"node:os";import hI from"node:path";var Qt,wn,Ni=g(()=>{"use strict";Qt=".epiq-global",wn=()=>process.env.EPIQ_GLOBAL_DIR??hI.join(gI.homedir(),Qt)});var Ll,$m=g(()=>{"use strict";w();Ll=(e,t)=>{let n=new Map,o=t??((...s)=>JSON.stringify(s)),r=((...s)=>{let i=o(...s);if(!n.has(i)){let c=e(...s).then(u=>(a(u)&&n.delete(i),u));n.set(i,c)}return n.get(i)});return r.clear=()=>n.clear(),r}});var Ne,wi=g(()=>{"use strict";Ke();Ne={stage:({cwd:e,pathspec:t,ignoreRemoval:n=!1})=>W({args:["add",...n?["--ignore-removal"]:[],...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1,pathspec:o})=>W({args:["commit","--no-verify",...n?["--allow-empty"]:[],"-m",t,...o?.length?["--",...o]:[]],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>W({args:["fetch",t,`+refs/heads/${n}:refs/remotes/${t}/${n}`],cwd:e}),rebaseOnto:({cwd:e,ref:t})=>W({args:["-c","rebase.autoStash=true","rebase",t],cwd:e}),checkout:({cwd:e,branch:t})=>W({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:o=!1})=>{let r=t&&n?["push","--no-verify",...o?["-u"]:[],t,n]:["push","--no-verify"];return W({args:r,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>W({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>W({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>W({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>W({args:["worktree","prune"],cwd:e})}});var vt,Tt,Cn=g(()=>{"use strict";Jt();w();ee();vt=e=>{let t=we(e);if(a(t))return l("Unable to resolve epiq project root");let n=At(t.value);return a(n)?l("Unable to read project.json"):d("Resolved state branch",n.value.stateBranch)},Tt="origin"});import{spawn as Um}from"node:child_process";import An from"node:fs";import Tn from"node:path";var Pl,vI,yI,bI,xI,Hm,Wm,qm,W,Le,Dl,nr,Ol,II,Ci,kn,ms,Ai,tr,Gm,Fl,Ti,zm,Vm,Km,EI,RI,SI,NI,wI,jm,ps,CI,fs,Ym,Xm,Jm,Qm,Ke=g(()=>{"use strict";w();wi();Cn();Pl=1e4,vI=12e4,yI=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),bI=e=>{let t=e.find((n,o)=>!n.startsWith("-")&&e[o-1]!=="-c");return t&&yI.has(t)?vI:Pl},xI=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(Tn.delimiter))if(t)for(let n of e){let o=Tn.join(t,n);try{if(!An.statSync(o).isFile())continue;return An.accessSync(o,An.constants.X_OK),o}catch{continue}}return"git"},Hm=xI(),Wm={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},qm=({args:e,cwd:t,allowFail:n})=>new Promise(o=>{if(!An.existsSync(t)){let f=`Git cwd does not exist: ${t}`;if(n){o({stdout:"",stderr:f,exitCode:1});return}o(l(f));return}let r=Um(Hm,e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Wm}),s=!1,i="",c="",u=f=>{s||(s=!0,clearTimeout(m),o(f))},p=bI(e),m=setTimeout(()=>{r.kill("SIGTERM");let f=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${p}ms`].join(`
|
|
15
|
+
`);u(n?{stdout:i,stderr:f,exitCode:124}:l(f))},p);r.stdout.setEncoding("utf8"),r.stderr.setEncoding("utf8"),r.stdout.on("data",f=>{i+=f}),r.stderr.on("data",f=>{c+=f}),r.on("error",f=>{if(n){u({stdout:i,stderr:f.message,exitCode:1});return}u(l([`git ${e.join(" ")}`,`cwd=${t}`,f.message].join(`
|
|
16
|
+
`)))}),r.on("close",f=>{let h=f??1;if(n){u({stdout:i,stderr:c,exitCode:h});return}if(h!==0){u(l([`git ${e.join(" ")}`,c.trim()||i.trim()||"Git command failed"].filter(Boolean).join(`
|
|
17
|
+
`)));return}u(d("Git command succeeded",{stdout:i,stderr:c,exitCode:h}))})}),W=({args:e,cwd:t})=>qm({args:e,cwd:t,allowFail:!1}),Le=({args:e,cwd:t})=>qm({args:e,cwd:t,allowFail:!0}),Dl=(e,t)=>new Promise(n=>{if(e.length===0){n(d("No blobs to read",new Map));return}let o=Um(Hm,["cat-file","--batch"],{cwd:t,stdio:["pipe","pipe","pipe"],env:Wm}),r=[],s="",i=!1,c=p=>{i||(i=!0,clearTimeout(u),n(p))},u=setTimeout(()=>{o.kill("SIGTERM"),c(l(`git cat-file --batch timed out after ${Pl}ms`))},Pl);o.stdout.on("data",p=>r.push(p)),o.stderr.setEncoding("utf8"),o.stderr.on("data",p=>{s+=p}),o.on("error",p=>c(l(p.message))),o.on("close",p=>{if(p!==0){c(l(`git cat-file --batch exited ${p}${s?`
|
|
18
|
+
${s}`:""}`));return}let m=Buffer.concat(r),f=new Map,h=0;for(let x of e){let E=m.indexOf(10,h);if(E===-1){c(l(`git cat-file --batch output ended before a header for ${x}`));return}let S=m.toString("utf8",h,E);h=E+1;let C=/^[0-9a-f]{4,64} \S+ (\d+)$/.exec(S);if(!C||!C[1]){c(l(`Unexpected git cat-file --batch header: "${S}"`));return}let R=Number(C[1]);f.set(x,m.toString("utf8",h,h+R)),h+=R+1}c(d("Read blobs",f))}),o.stdin.write(e.join(`
|
|
19
19
|
`)+`
|
|
20
|
-
`),
|
|
21
|
-
${
|
|
22
|
-
${
|
|
23
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(
|
|
24
|
-
${t.stderr.trim()}`):
|
|
25
|
-
${
|
|
26
|
-
${s.message}`);let i=await
|
|
27
|
-
`+
|
|
28
|
-
`+
|
|
29
|
-
`,
|
|
30
|
-
`,
|
|
31
|
-
`+t.message);let
|
|
32
|
-
`).filter(Boolean).filter(i=>i!==
|
|
33
|
-
${
|
|
34
|
-
`);if(n[n.length-1]===""&&n.pop(),t<=
|
|
20
|
+
`),o.stdin.end()}),nr=async({cwd:e,message:t,pathspec:n})=>{let o=await Ne.commit({cwd:e,message:t,pathspec:n});if(a(o))return l(`Failed to create commit
|
|
21
|
+
${o.message}`);let r=await W({args:["rev-parse","HEAD"],cwd:e});return a(r)?l(`Commit created, but failed to read HEAD SHA
|
|
22
|
+
${r.message}`):d("Created commit and resolved SHA",r.value.stdout.trim())},Ol=async e=>{let t=await W({cwd:e,args:["rev-parse","--git-dir"]});if(a(t))return l(t.message);let n=t.value.stdout.trim();return d("Resolved git dir",Tn.isAbsolute(n)?n:Tn.resolve(e,n))},II=async e=>{let t=await Ol(e);if(a(t))return l(t.message);let n=t.value,o={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(o))if(An.existsSync(Tn.join(n,s)))return d("Checked for in-progress Git operation",i);let r={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,i]of Object.entries(r))if(An.existsSync(Tn.join(n,s)))return d("Checked for in-progress Git operation",i);return d("Checked for in-progress Git operation",null)},Ci=async e=>{let t=await II(e);return a(t)?l(t.message):d("Checked for in-progress Git operation",t.value!==null)},kn=async({repoRoot:e})=>{let n=(await Le({args:["remote","get-url",Tt],cwd:e})).exitCode===0;return d(`Checked remote ${n}`,n)},ms=async({repoRoot:e,branch:t})=>{let n=await Le({args:["ls-remote","--heads",Tt,t],cwd:e});return n.exitCode!==0?l(n.stderr.trim()||`Unable to inspect remote branch ${Tt}/${t}`):d("Checked remote branch",n.stdout.trim().length>0)},Ai=async({repoRoot:e,branch:t})=>{let n=await Le({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):l(n.stderr.trim()||`Unable to inspect branch ${t}`)},tr=e=>{try{return An.realpathSync.native(e)}catch{return Tn.resolve(e)}},Gm=async({repoRoot:e,worktreeRoot:t})=>{let n=await W({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return l(n.message);let o=tr(t),r=n.value.stdout.split(`
|
|
23
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(tr).includes(o);return d("Checked worktree registration",r)},Fl=async e=>{let t=await Le({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return d("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Ti=async e=>{let t=await W({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?l(t.message):d("Resolved current branch",t.value.stdout.trim())},zm=async e=>{let t=await W({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?l(t.message):d("Resolved short HEAD sha",t.value.stdout.trim())},Vm=e=>e.includes("fetch first")||e.includes("non-fast-forward"),Km=async e=>{let t=await Le({cwd:e,args:["rev-parse","--absolute-git-dir"]});if(t.exitCode!==0)return!1;let n=t.stdout.trim();return n?An.existsSync(Tn.join(n,"rebase-merge"))||An.existsSync(Tn.join(n,"rebase-apply")):!1},EI=3,RI=120,SI=e=>new Promise(t=>setTimeout(t,e)),NI=async(e,t)=>{let n=await Ne.rebaseOnto({cwd:e,ref:t});for(let o=1;o<EI;o+=1){if(!a(n)||await Km(e))return n;await SI(RI),n=await Ne.rebaseOnto({cwd:e,ref:t})}return n},wI=async e=>{if(!await Km(e))return d("No rebase to abort",!1);let t=await Le({cwd:e,args:["rebase","--abort"]});return t.exitCode!==0?l(`Failed to abort the rebase in progress at ${e}
|
|
24
|
+
${t.stderr.trim()}`):d("Aborted stale rebase",!0)},jm=async e=>{let t=await Le({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},ps=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),CI=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),fs=async({cwd:e,branch:t})=>{let n=await wI(e);if(a(n))return l(n.message);let o=await jm(e),r=await Ne.fetch({cwd:e,remote:Tt,branch:t});if(a(r))return CI(r.message)?d("Remote branch missing, skipped pull",!1):l(`Failed to fetch ${t}
|
|
25
|
+
${r.message}`);let s=await NI(e,`${Tt}/${t}`);if(a(s))return l(`Failed during rebase
|
|
26
|
+
${s.message}`);let i=await jm(e),c=o!==null&&i!==null&&o!==i;return d(c?"Pulled with rebase":"Already up to date",c)},Ym=async e=>{let t=await Le({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)},Xm=async e=>{let t=await Le({args:["status","--porcelain","--untracked-files=all"],cwd:e});return t.exitCode!==0?l(t.stderr.trim()||"Unable to inspect the worktree for changes"):d("Inspected worktree for changes",t.stdout.trim().length>0)},Jm=async(e,t)=>{let n=await Le({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):l(n.stderr.trim()||"Unable to inspect staged changes")},Qm=async e=>{let t=await Ti(e);return a(t)?l(t.message):d("Checked detached HEAD state",t.value==="HEAD")}});import Kn from"node:fs";import yt from"node:path";var tp,np,op,rp,No,Ie,AI,Zm,gs,hs,sp,TI,kI,_l,Bl,ep,ip,ap,kt,lk,rt=g(()=>{"use strict";Jt();w();Ni();ee();$m();$t();Ke();tp="4b825dc642cb6eb9a060e54bf8d69288fbee4904",np=e=>yt.join(ut,Mn,e),op=()=>yt.join(ut,$l),rp=wn,No=()=>yt.join(rp(),"worktrees"),Ie=({repoRoot:e})=>{let t=un(e);return a(t)?l(t.message):d("Resolved state branch root",yt.join(No(),t.value))},AI=e=>yt.join(e,ut),Zm=e=>yt.join(AI(e),Mn),gs=e=>{try{return Kn.mkdirSync(e,{recursive:!0}),d("Ensured directory",void 0)}catch(t){return l(t instanceof Error?t.message:String(t))}},hs=()=>{let e=rp(),t=No(),n=!Kn.existsSync(e)||!Kn.existsSync(t),o=gs(e);if(a(o))return l(`Ensure epiq home failed.
|
|
27
|
+
`+o.message);let r=gs(t);return a(r)?l(`Ensure worktrees dir failed.
|
|
28
|
+
`+r.message):d("Ensured epiq storage",n)},sp=e=>{Kn.existsSync(e)&&(ce.debug("[sync] remove path",e),Kn.rmSync(e,{recursive:!0,force:!0}))},TI=`*.jsonl merge=union
|
|
29
|
+
`,kI=`*~pending*.jsonl
|
|
30
|
+
`,_l=()=>yt.join(ut,Mn,".gitattributes"),Bl=()=>yt.join(ut,Mn,".gitignore"),ep=(e,t)=>{try{Kn.readFileSync(e,"utf8")!==t&&Kn.writeFileSync(e,t)}catch{Kn.writeFileSync(e,t)}},ip=(e,t)=>{for(let n of[Zm(e),Zm(t)]){let o=gs(n);if(a(o))return l(o.message)}return ep(yt.join(t,_l()),TI),ep(yt.join(t,Bl()),kI),d("Ensured state branch",void 0)},ap=async e=>{let t=await W({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return l(`ensure state branch is storage only failed
|
|
31
|
+
`+t.message);let o=t.value.stdout.trim().split(`
|
|
32
|
+
`).filter(Boolean).filter(i=>i!==ut);if(o.length===0)return d("State branch is storage-only",!1);let r=await W({args:["rm","-r","--ignore-unmatch","--",...o],cwd:e});if(a(r))return l(`Failed to clean storage branch
|
|
33
|
+
${r.message}`);let s=await nr({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:o});return a(s)?l(s.message):d("Cleaned storage branch",!0)},kt=Ll(async(e=process.cwd())=>{let t=await W({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?l("Not inside a Git repository"):d("Resolved repo root",t.value.stdout.trim())},e=>yt.resolve(e)),lk=Ll(async e=>{let t=await W({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return l(t.message);let n=t.value.stdout.trim(),o=yt.isAbsolute(n)?n:yt.join(e,n);return d("Resolved git dir",o)},e=>yt.resolve(e))});import vs from"node:fs";import mn from"node:path";var gk,ut,Mn,$l,MI,So,er,bt,ki,lp,LI,ys,Mi,PI,we,cp,Ee,ee=g(()=>{"use strict";w();rt();Ni();gk=process.env.IS_LOCAL==="true",ut=".epiq",Mn="events",$l="media",MI="project.json",So=e=>mn.join(e,ut),er=e=>mn.join(So(e),MI),bt=e=>mn.join(So(e),Mn),ki=e=>mn.join(So(e),$l),lp=e=>mn.join(e,ut),LI=e=>{let t=mn.join(e,ut);return vs.existsSync(t)&&vs.statSync(t).isDirectory()},ys=e=>{let t=er(e);return vs.existsSync(t)&&vs.statSync(t).isFile()},Mi=e=>{let t=mn.resolve(e);for(;;){if(LI(t))return d("Resolved closest .epiq root",t);let n=mn.dirname(t);if(n===t)return l("No .epiq directory found in any parent");t=n}},PI="No .epiq/project.json found in any parent",we=e=>{let t=mn.resolve(e);for(;;){if(ys(t))return d("Resolved closest epiq project root",t);let n=mn.dirname(t);if(n===t)return l(PI);t=n}},cp=e=>{let t=bt(e);try{return vs.mkdirSync(t,{recursive:!0}),d("Resolved events dir",t)}catch(n){return l(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},Ee=async()=>{let e=await kt(process.cwd());if(a(e))return e;let t=Ie({repoRoot:e.value});return a(t)?t:d("Resolved persist root",t.value)}});import Zt from"fs";import ql from"path";import DI from"util";function BI(e){if(!Zt.existsSync(e))return;let t=Zt.statSync(e).size,n=_I(e,Gl).split(`
|
|
34
|
+
`);if(n[n.length-1]===""&&n.pop(),t<=Gl&&n.length<=dp)return;let o=n.slice(-dp).join(`
|
|
35
35
|
`)+`
|
|
36
|
-
`;
|
|
37
|
-
`;try{
|
|
38
|
-
`);return i===-1?"":s.slice(i+1)}finally{Ft.closeSync(r)}};_y=e=>{if(e.length<=Ca)return e;let t=e.length-Ca;return`${e.slice(0,Ca)} \u2026 [${t} more chars]`};Ta=()=>Iu()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",X={info(...e){let t=Ta();(t==="info"||t==="debug")&&Aa("[Info]",e,!1)},debug(...e){Ta()==="debug"&&Aa("[Debug]",e,!0)},error(...e){let t=Ta();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;Aa("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=X});var ge,Mr=h(()=>{"use strict";ge={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var j,Uo,tt=h(()=>{"use strict";j=e=>e.slice(-7).toUpperCase(),Uo=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?j(e).includes(n):!0}});var Pe,tr=h(()=>{"use strict";ee();tt();Pe={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:Y.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:j(e)},context:Y.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:Y.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:Y.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:Y.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:j(e)},context:Y.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:Y.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:Y.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})}});var Fy,me,$s,Bt=h(()=>{"use strict";Fy=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[me,$s]=Fy});function Tn(e,t=!1){let n=Hy[e.action];if(!n)return d(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);if(!Nt()&&e.action!=="init.workspace")return _(`${e.action} arrived before the workspace was initialized`,e);if(e.action==="init.workspace"&&nt){if(nt.genesisApplied)return _("the workspace is already initialized",e);nt.genesisApplied=!0}let r;try{r=n(e)}catch(s){return _(`threw while materializing (${s instanceof Error?s.message:String(s)})`,e)}if(a(r))return r;let o=Wy(e,t);return o||r}var Pa,_,$o,nr,rr,xu,Eu,By,Oy,La,Uy,jy,nt,$y,Wy,jo,Hy,mn,pn=h(()=>{"use strict";St();ee();S();Mr();re();tr();M();Da();Bt();Pa=(e,t)=>d(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),_=(e,t)=>({...Pa(e,t),convergence:!0}),$o=e=>a(e)&&e.convergence===!0,nr=e=>{let t=e.filter(a);return{fatal:t.filter(n=>!$o(n)),skipped:t.filter($o)}},rr=e=>{e.length!==0&&X.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},xu=e=>{let t=E.getNode(e);if(!t||!F(t)||t.isDeleted)return null;let n=Hs(t);return a(n)?n:null},Eu=e=>{if(!qs())return null;for(let t of e){let n=xu(t);if(n)return n;let r=g().nodes[t]?.parentNodeId;if(!r)continue;let o=xu(r);if(o)return o}return null},By=(e,t)=>{let n=E.getNode(e);n&&E.updateNode({...n,log:[...n.log??[],t]})},Oy=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},La=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 Oy(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":default:return[]}},Uy=e=>{Ne(t=>({...t,eventLog:[...t.eventLog,e]}))},jy=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?Pa("Invalid user ID format",e):l("Valid user",null)},nt=null,$y=e=>{for(let[t,n]of e.nodeLog){let r=E.getNode(t);r&&E.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&Ne(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),Eu([...e.virtualNodeIds])},Wy=(e,t)=>{let n=jy(e);if(a(n))return n;let r=[...new Set(La(e))];if(nt){for(let s of r){if(!t){let i=nt.nodeLog.get(s);i?i.push(e):nt.nodeLog.set(s,[e])}if(qs()){nt.virtualNodeIds.add(s);let i=g().nodes[s]?.parentNodeId;i&&nt.virtualNodeIds.add(i)}}return t||nt.appLog.push(e),null}t||(r.forEach(s=>By(s,e)),Uy(e));let o=Eu(r);return o||null},jo=(e,t,n)=>E.getNode(e)?_(`a node with id ${e} already exists`,n):t===e?_("a node cannot be its own parent",n):null,Hy={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Pe.workspace(t,n,r),s=Wo(o);if(a(s))return Pa(s.message,e);let i=E.createNode(o);return a(i)?_(i.message??"Failed to initialize workspace",e):pa(i.value)?l("Workspace initialized",{action:e.action,result:i.value}):d("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=jo(t,void 0,e);if(o)return o;let s=E.createNode(Pe.workspace(t,n,r));return a(s)?_(s.message??"Failed to add workspace",e):pa(s.value)?l("Added workspace",{action:e.action,result:s.value}):d("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=jo(t,r,e);if(s)return s;let i=E.createNode(Pe.board(t,n,r,o));return a(i)?_(i.message??"Unable to create board",e):Yn(i.value)?l("Added board",{action:e.action,result:i.value}):d("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=jo(t,r,e);if(s)return s;let i=E.createNode(Pe.swimlane(t,n,r,o));return a(i)?_(i.message??"Unable to create swimlane",e):Kn(i.value)?l("Added swimlane",{action:e.action,result:i.value}):d("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=jo(t,r,e);if(s)return s;let i=E.createNode(Pe.ticket(t,n,r,o));return a(i)?_(i.message??"Unable to create issue",e):F(i.value)?l("Added issue",{action:e.action,result:i.value}):d("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=jo(t,r,e);if(i)return i;let c=E.createNode(Pe.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(ge.DESCRIPTION)?"vertical":"horizontal"}));return a(c)?_(c.message??`Unable to create field: ${n}`,e):ut(c.value)?l("Added field",{action:e.action,result:c.value}):d("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!E.getNode(t))return _(`Unable to locate node with id ${t}`,e);let o=E.renameNode(t,n);return a(o)?_(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=E.tombstoneNode(t);return a(n)?_(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=E.createTag({id:t,name:n});return a(r)?_(r.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=E.tombstoneTag(t);return a(n)?_(n.message??"Unable to delete tag",e):l("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=E.restoreTag(t,n);return a(r)?_(r.message??"Unable to restore tag",e):l("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=E.createContributor({id:t,name:n});return a(r)?_(r.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=E.renameContributor(t,n);return a(r)?_(r.message??"Unable to rename contributor",e):l("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=E.tombstoneContributor(t);return a(n)?_(n.message??"Unable to remove contributor",e):l("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,r=E.restoreContributor(t,n);return a(r)?_(r.message??"Unable to restore contributor",e):l("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=E.tag(t,n);return a(r)?_(r.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=E.untag(t,n);return a(r)?_(r.message??"Unable to untag issue",e):l("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=E.assign(t,n);return a(r)?_(r.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=E.unassign(t,n);return a(r)?_(r.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=E.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?_(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=E.editValue(t,n);return a(r)?_(r.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=E.getNode(t);if(!o)return _("Unable to locate issue",e);if(!F(o))return _("Can only close issues",e);let s=E.getNode(me);if(!s)return _("Unable to locate target swimlane",e);if(n!==s.id)return _("Close target must be closed swimlane",e);let i=E.moveNodeToRank({id:t,parentId:n,rank:r});return a(i)?_(i.message??"Unable to close issue",e):l("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=E.getNode(t);if(!o)return _("Unable to locate issue",e);if(!F(o))return _("Can only reopen issues",e);let s=E.getNode(me);if(!s)return _("Unable to locate closed swimlane",e);if(n===s.id)return _("Cannot reopen issue into closed swimlane",e);if(!E.getNode(n))return _("Reopen parent no longer exists",e);let c=E.moveNodeToRank({id:t,parentId:n,rank:r});return a(c)?_(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=E.lockNode(t);return a(n)?_(n.message??"Unable to lock node",e):l("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=E.getNode(r);if(!s)return _(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return _(`Node ${r} is not child of ${t}`,e);let i=E.updateNode({...s,rank:o});if(a(i))return _(i.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=E.createComment({id:t,issue:n,authorId:r,authorName:E.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return a(s)?_(s.message??"Unable to add comment",e):l("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=E.getComment(t);if(!o)return _("Unable to locate comment",e);if(o.issue!==n)return _("Comment does not belong to issue",e);let s=E.editComment(t,r);return a(s)?_(s.message??"Unable to edit comment",e):l("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=E.getComment(t);if(!r)return _("Unable to locate comment",e);if(r.issue!==n)return _("Comment does not belong to issue",e);let o=E.deleteComment(t);return a(o)?_(o.message??"Unable to delete comment",e):l("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:r,ext:o,name:s,bytes:i}=e.payload,c=E.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return a(c)?_(c.message??"Unable to add attachment",e):l("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=E.getAttachment(t);if(!r)return _("Unable to locate attachment",e);if(r.issue!==n)return _("Attachment does not belong to issue",e);let o=E.deleteAttachment(t);return a(o)?_(o.message??"Unable to delete attachment",e):l("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=E.linkUserId({contributorId:t,userId:e.userId});return a(n)?_(n.message??"Unable to link contributor",e):l("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};mn=e=>{let t=Ws(()=>{let n=nt===null;n&&(nt={appLog:[],nodeLog:new Map,virtualNodeIds:new Set,genesisApplied:!1});try{let r=e.map(o=>Tn(o));if(n&&nt){let o=$y(nt);if(o)return e.map(()=>o)}return r}finally{n&&(nt=null)}});return a(t)?e.map(()=>d(t.message)):t.value}});var _a,Ru=h(()=>{"use strict";_a=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown"});import Ee from"node:fs";import or from"node:path";import{ulid as qy}from"ulid";var zs,Fa,Nu,Cu,Ba,wu,Au,Vs,Tu,Gy,zy,ku,Vy,Mu,Ky,Pu,Yy,Gs,Su,Ks,sr=h(()=>{"use strict";S();ie();zs="~pending",Fa=/~pending(-[0-9a-z]+)*$/i,Nu=/-f(\d+)$/,Cu=e=>{let t=e.indexOf(".");return t===-1?`${e}${zs}`:e.slice(0,t)+zs+e.slice(t)},Ba=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},wu=e=>{let[t,n]=Ba(e);return Fa.test(t)?t.replace(Fa,"")+n:null},Au=e=>e.replace(Fa,""),Vs=e=>e.endsWith(".jsonl")&&wu(e)!==null,Tu=e=>{let[t]=Ba(e),n=Nu.exec(t);return n&&Vs(e)?Number(n[1]):null},Gy=e=>Cu(e).replace(zs,`${zs}-${qy().toLowerCase()}`),zy=(e,t)=>{let[n,r]=Ba(e);return`${n.replace(Nu,"")}-f${t}${r}`},ku=(e,t)=>or.join(_t(e),Cu(t)),Vy=(e,t)=>Math.max(0,Ee.statSync(e).size-(Tu(t)??0)),Mu=e=>{let t=_t(e);try{return Ee.existsSync(t)?Ee.readdirSync(t).filter(Vs).some(n=>Vy(or.join(t,n),n)>0):!1}catch{return!0}},Ky=3,Pu=(e,t)=>{for(let n=1;;n++){let r=Ee.openSync(e,"a"),o;try{Ee.writeSync(r,t),o=Ee.fstatSync(r).ino}finally{Ee.closeSync(r)}let s;try{s=Ee.statSync(e).ino}catch{s=null}if(s===o||n>=Ky)return}},Yy=e=>{let t;try{t=Ee.openSync(e,"r")}catch{return!0}try{let{size:n}=Ee.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return Ee.readSync(t,r,0,1,n-1),r[0]===10}finally{Ee.closeSync(t)}},Gs=10,Su=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(Gs)+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};Ee.appendFileSync(e,Buffer.concat([Buffer.from(Yy(e)?"":`
|
|
39
|
-
`),
|
|
40
|
-
`)]));let s=0;for(let i of
|
|
41
|
-
`).entries()){let
|
|
42
|
-
`),n&&(n.current=u);let f=Xa.basename(i.value);return qu(t,f,u),Fu(t,f),l("Event persisted",{path:i.value,entry:p.value})}catch(o){let s=o instanceof Error?o.message:"Unknown persist error";return d(`Failed to persist event: ${s}`)}}var Yu,Ku,fb,gb,hb,Xu,vb,yb,zu,bb,Ib,Vu,xb,oe,cr,Eb,Rb,Ce=h(()=>{"use strict";St();zn();S();ze();ie();Ru();Je();sr();wt();Pr();Wa();Yu=1,Ku=pb(),fb=0xffffffffffff,gb=As,hb=e=>{let t=Date.now(),n;try{n=mb(e)}catch{return t}return n>=fb?t:n>t+gb?(X.error("[persist] edge id is too far in the future; seeding from the wall clock instead",{edgeRef:e,edgeTime:n,now:t}),t):Math.max(t,n+1)},Xu=dr.tuple([dr.string().min(1),dr.string().min(1).nullable()]),vb=dr.looseObject({v:dr.literal(Yu),id:Xu}),yb=dr.looseObject({v:dr.number().int().positive(),id:Xu}),zu=e=>{let t=yb.safeParse(e);return t.success?l("Parsed persisted event envelope",t.data):d(`Invalid persisted event envelope: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},bb=[1],Ib=new Set(bb),Vu=e=>Ib.has(e),xb=e=>{let t=vb.safeParse(e);return t.success?l("Parsed persisted event",t.data):d(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},oe=()=>{let{userName:e,userId:t}=xe();return e?t?ws(t)?So(e)?l("Successfully resolved actor ID",{userId:t,userName:e}):d("Invalid user name in config"):d("Invalid user ID in config"):d("User ID not configured"):d("User name not configured")},cr=({userId:e,userName:t})=>`${_a(e)}.${_a(t)}.jsonl`,Eb=(e,{userId:t,userName:n})=>{let r=cr({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return d(`Invalid event log file name: ${r}`);let s=Xa.join(_t(e),r);return l("Successfully resolved event log path",s)},Rb=(e,t)=>{let n={[e.action]:e.payload,v:Yu,id:t};return xb(n)}});import{ulid as Sb}from"ulid";function Ju(e,t,n){let r=Ja(t,n);if(a(r))return d(r.message);let o={...e,id:r.value[0]},s=Tn(o);if(s.status!==sn.Success)return s;let i=Qs({event:o,rootDir:t,edge:n,id:r.value});return a(i)?i:s}function P(e,t){if(e.length===0||!e[0])return d("No events provided");if(g().readOnly)return d(g().readOnlyReason??"Cannot change the board while time travelling");let n=Ws(()=>{let r={},o=Nb(e[0],t,r);if(a(o))return d(o.message);let s=e.map(c=>Ju(c,t,r)),i=s.filter(a);return i.length>0?d("Materialize and persist failed: "+i.map(c=>c.message).join(", ")):l("Materialization succeeded",s.map(c=>c.value))});return a(n)?d(n.message):n.value??d("Materialize and persist produced nothing")}var Nb,Re=h(()=>{"use strict";S();re();M();pn();Ce();Nb=(e,t,n)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return l("Contributor write already in flight",void 0);let r=E.getContributor(e.userId),o={id:Sb(),action:r?"rename.contributor":"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName};if(r&&(r.tombstoned||r.name===e.userName))return l("Contributor name is current",void 0);let s=Ju(o,t,n);return a(s)?d(s.message):l("Contributor name recorded",void 0)}});var lr,Qa,Qu=h(()=>{"use strict";tt();lr=e=>e.trim().toLocaleLowerCase(),Qa=(e,t)=>lr(e).includes(lr(t))});var Cb,wb,Zu,em,Ab,Tb,tm,nm=h(()=>{"use strict";M();tt();Qu();Cb=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},wb=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},Zu=null,em=new Map,Ab=()=>{let e=g().eventLog??[];if(e===Zu)return em;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 Zu=e,em=t,t},Tb=e=>{let{contributors:t}=g(),n=Ab().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},tm=(e,t)=>{let n=lr(t.value);if(!n)return!0;switch(t.target){case"title":return Qa(e.title??"",n);case"description":return Qa(e.props.description??"",n);case"tag":return Cb(e).map(lr).some(o=>o.includes(n));case"assignee":return wb(e).map(lr).some(o=>o.includes(n));case"actor":return Tb(e).map(lr).some(o=>o.includes(n));case"ref":return Uo(e.id,t.value);default:return!0}}});var Za,kb,rm,om,sm,ed=h(()=>{"use strict";ee();nm();Za=(e,t)=>e.rank<t.rank?-1:e.rank>t.rank?1:0,kb=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,rm=(e,t)=>Object.values(e).filter(n=>kb(n,t)).sort(Za),om=(e,t)=>{let n={};for(let r of Object.values(e)){if(F(r)&&t.length>0&&!t.every(s=>tm(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(Za);return n},sm=(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(Za);return n}});var im,Zs,ye,am,dm,Vt,gn,Rt=h(()=>{"use strict";Vl();Re();S();M();ed();wr();im=e=>Zs(ye(e),{at:"end"}),Zs=(e,t={at:"end"})=>{let n=o=>a(o)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(Ve(void 0,void 0));let r=()=>n(Ve(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(Ve(void 0,o.rank)):d("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(Ve(o.rank,void 0)):d("Unable to resolve last sibling")}case"before":{let o=am(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(Ve(i?.rank,s.rank))}case"after":{let o=am(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(Ve(s.rank,i?.rank))}}},ye=e=>{let t=g();if(!cm()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return rm(t.nodes,e)},am=(e,t)=>e.findIndex(n=>n.id===t),dm=(e,t,n={at:"end"})=>Zs(ye(t).filter(r=>r.id!==e),n),Vt=(e,t,n,r,o)=>{let s=dm(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return l("Resolved rank",s.value.rank);let i=ha(e,r);if(a(i))return i;let c=P([i.value],o);if(a(c))return c;let u=dm(t,e,n);return a(u)?u:u.value.needsRebalance?d("Rank rebalance failed to create space"):l("Resolved rank after rebalance",u.value.rank)},gn=(e,t,n)=>{let r=im(e);if(a(r))return r;if(!r.value.needsRebalance)return l("Resolved rank",r.value.rank);let o=ha(e,t);if(a(o))return o;let s=P([o.value],n);if(a(s))return s;let i=im(e);return a(i)?i:i.value.needsRebalance?d("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)}});var $,lm,um,ht=h(()=>{"use strict";M();$={exit(){process.exit(0)},enterChildNode(){let e=g(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=ae(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||$.navigate({contextNode:o,selectedIndex:ae(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=g();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=ae(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;$.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>lm(1),navigateToPreviousItem:()=>lm(-1),navigateToNextContainer:()=>um(1),navigateToPreviousContainer:()=>um(-1),navigate:({contextNode:e,selectedIndex:t})=>{N({contextNodeId:e.id,selectedIndex:t})}},lm=e=>{let{selectedIndex:t,contextNode:n}=g(),r=ae(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;$.navigate({selectedIndex:s,contextNode:n})},um=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=g();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=ae(o.id),i=s.findIndex(y=>y.id===t.id);if(i<0)return;let c=s.at(i+e)??s.at(0);if(!c)return;let u=ae(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),f=u.length?p:-1;$.navigate({contextNode:c,selectedIndex:f})}});var pm,fm,Mb,ei,gm,mm,Pb,hm,vm=h(()=>{"use strict";ee();S();Rt();M();ht();pm=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),fm=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},Mb=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&ut(t)&&t.childRenderAxis==="vertical"},ei=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r||r.isDeleted)return!1;let o=ye(r.id);return $.navigate({contextNode:r,selectedIndex:pm(t,o.length)}),!0},gm=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return ei(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=ye(o.id).findIndex(c=>c.id===n.id);return i>=0?($.navigate({contextNode:o,selectedIndex:i}),!0):gm(o.id)},mm=e=>{let{nodes:t}=g(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),gm(n))return!0;n=t[n]?.parentNodeId}return!1},Pb=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},hm=e=>{let{nodes:t,rootNodeId:n}=g();if(Mb(e.contextNodeId)&&ei(e.contextNodeId,e.selectedIndex))return l("Restored navigation inside text container",null);if(Pb(e.selectedNodeId)&&e.selectedNodeId&&mm(e.selectedNodeId))return l("Restored navigation to selected node or ancestor",null);if(ei(e.contextNodeId,e.selectedIndex))return l("Restored navigation to previous container",null);if(e.parentNodeId&&ei(e.parentNodeId,e.selectedIndex))return l("Restored navigation to previous parent",null);if(mm(e.contextNodeId))return l("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return d("Unable to restore navigation");let o=ye(r.id);return $.navigate({contextNode:r,selectedIndex:pm(e.selectedIndex,o.length)}),l("Restored navigation to root",null)}});import{monotonicFactory as Lb,ulid as Kt}from"ulid";function Db(){let e=Ye();if(a(e))return d("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return d("No workspace found in event log");let[r]=ae(n.id),[o]=r?ae(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return l("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?l("Resolved boot nav target",{contextNode:r,selectedIndex:0}):l("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function _b(){let e=Db();return a(e)?e:$.navigate(e.value)}function ym({userId:e,userName:t}){let n=Go(),r=Go(),o=Go(),s=Go(),i=Go(),c=Ve(void 0,void 0);if(a(c))return c;let u=Ve(void 0,void 0);if(a(u))return u;let m=Ve(u.value,void 0);if(a(m))return m;let p=Ve(void 0,void 0);if(a(p))return p;let f=Ve(p.value,void 0);if(a(f))return f;let y=Ve(f.value,void 0);if(a(y))return y;let x=Ve(void 0,void 0);return a(x)?x:l("Created default events",[{id:Kt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:Kt(),userId:e,userName:t,action:"create.contributor",payload:{id:e,name:t}},{id:Kt(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Kt(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Kt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Kt(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:y.value}},{id:Kt(),userId:e,userName:t,action:"add.board",payload:{id:$s,name:"Closed",parent:n,rank:m.value}},{id:Kt(),userId:e,userName:t,action:"add.swimlane",payload:{id:me,name:"Closed",parent:$s,rank:x.value}},{id:Kt(),userId:e,userName:t,action:"lock.node",payload:{id:$s}},{id:Kt(),userId:e,userName:t,action:"lock.node",payload:{id:me}}])}function Yt(e,t=[]){if(Fb())return l("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Pe.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=Wo(s);return a(i)?i:(N({hasProjectDefinition:!1,mode:b.DEFAULT}),l("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return d("Initialized Epiq project has no workspace init event");let n=mn(e),{fatal:r,skipped:o}=nr(n);return r.length>0?d(`Materializing failed:
|
|
43
|
-
${
|
|
44
|
-
`)}`):(
|
|
45
|
-
`,"utf8"),
|
|
46
|
-
`),
|
|
47
|
-
`).filter(t=>t.trim().length>0),
|
|
48
|
-
`);
|
|
49
|
-
`:""}${
|
|
36
|
+
`;Zt.writeFileSync(e,o,"utf8")}function Hl(e,t,n=!1){let o=FI();if(!o)return;let r=$I(DI.format(...t)),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${r}
|
|
37
|
+
`;try{Zt.mkdirSync(ql.dirname(o),{recursive:!0}),Zt.appendFileSync(o,c,"utf8"),Ul++,(Ul>=OI||Zt.statSync(o).size>Gl)&&(Ul=0,BI(o))}catch{}}var dp,Gl,jl,OI,Ul,up,FI,_I,$I,Wl,ce,$t=g(()=>{"use strict";w();ee();dp=500,Gl=4*1024*1024,jl=16*1024,OI=50,Ul=0,up=()=>process.env.EPIQ_MCP==="true",FI=()=>{let e=process.cwd(),t=Mi(e);return a(t)?up()?ql.join(wn(),"epiq-mcp.log"):void 0:ql.join(t.value,ut,"log","epiq.log")},_I=(e,t)=>{let n=Zt.statSync(e).size;if(n<=t)return Zt.readFileSync(e,"utf8");let o=Zt.openSync(e,"r");try{let r=Buffer.alloc(t);Zt.readSync(o,r,0,t,n-t);let s=r.toString("utf8"),i=s.indexOf(`
|
|
38
|
+
`);return i===-1?"":s.slice(i+1)}finally{Zt.closeSync(o)}};$I=e=>{if(e.length<=jl)return e;let t=e.length-jl;return`${e.slice(0,jl)} \u2026 [${t} more chars]`};Wl=()=>up()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",ce={info(...e){let t=Wl();(t==="info"||t==="debug")&&Hl("[Info]",e,!1)},debug(...e){Wl()==="debug"&&Hl("[Debug]",e,!0)},error(...e){let t=Wl();if(t==="error"||t==="info"||t==="debug"){let o=e.some(r=>r instanceof Error)?void 0:new Error().stack;Hl("[Error]",[...e,o].filter(Boolean),!1)}}};globalThis.logger=ce});import zl from"node:fs";import jI from"node:path";var bs,Vl,Kl,wo,mp,Yl,Yn,pp,fp,gp,or=g(()=>{"use strict";ee();bs=e=>e?.code==="ENOENT",Vl=3,Kl=e=>zl.readdirSync(e).filter(t=>t.endsWith(".jsonl")).sort(),wo=e=>{let t=bt(e);for(let n=1;;n++){if(!zl.existsSync(t))return"none";let o=[],r=!1;for(let s of Kl(t))try{let{size:i,mtimeMs:c}=zl.statSync(jI.join(t,s));o.push(`${s}:${i}:${c}`)}catch(i){if(!bs(i))throw i;if(n<Vl){r=!0;break}}if(!r)return o.join("|")}},mp=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),Yl=(e,t,n)=>{let o=mp(t),r=wo(e),s=mp(r);for(let[i,c]of s)if(i!==n&&o.get(i)!==c)return null;for(let i of o.keys())if(i!==n&&!s.has(i))return null;return r},Yn=null,pp=e=>Yn&&Yn.root===e?Yn.signature:null,fp=(e,t)=>{Yn={root:e,signature:t}},gp=(e,t)=>{if(!Yn||Yn.root!==e)return;let n=Yl(e,Yn.signature,t);Yn=n===null?null:{root:e,signature:n}}});import _e from"node:fs";import Co from"node:path";import{ulid as UI}from"ulid";var Pi,Xl,vp,yp,Di,HI,Jl,Ao,xs,bp,WI,qI,xp,GI,Ip,zI,Ep,VI,Li,hp,Oi,To=g(()=>{"use strict";w();ee();Pi="~pending",Xl=/~pending(-[0-9a-z]+)*$/i,vp=/-f(\d+)$/,yp=e=>{let t=e.indexOf(".");return t===-1?`${e}${Pi}`:e.slice(0,t)+Pi+e.slice(t)},Di=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},HI=e=>{let[t,n]=Di(e);return Xl.test(t)?t.replace(Xl,"")+n:null},Jl=e=>e.replace(Xl,""),Ao=e=>e.endsWith(".jsonl")&&HI(e)!==null,xs=e=>Jl(Di(e)[0]),bp=e=>{let[t]=Di(e),n=vp.exec(t);return n&&Ao(e)?Number(n[1]):null},WI=e=>yp(e).replace(Pi,`${Pi}-${UI().toLowerCase()}`),qI=(e,t)=>{let[n,o]=Di(e);return`${n.replace(vp,"")}-f${t}${o}`},xp=(e,t)=>Co.join(bt(e),yp(t)),GI=(e,t)=>Math.max(0,_e.statSync(e).size-(bp(t)??0)),Ip=e=>{let t=bt(e);try{return _e.existsSync(t)?_e.readdirSync(t).filter(Ao).some(n=>GI(Co.join(t,n),n)>0):!1}catch{return!0}},zI=3,Ep=(e,t)=>{for(let n=1;;n++){let o=_e.openSync(e,"a"),r;try{_e.writeSync(o,t),r=_e.fstatSync(o).ino}finally{_e.closeSync(o)}let s;try{s=_e.statSync(e).ino}catch{s=null}if(s===r||n>=zI)return}},VI=e=>{let t;try{t=_e.openSync(e,"r")}catch{return!0}try{let{size:n}=_e.fstatSync(t);if(n===0)return!0;let o=Buffer.alloc(1);return _e.readSync(t,o,0,1,n-1),o[0]===10}finally{_e.closeSync(t)}},Li=10,hp=(e,t,n=!1)=>{let o=n?t.length:t.lastIndexOf(Li)+1;if(o===0)return{bytes:0,lines:0};let r=t.subarray(0,o);if(r.toString("utf8").trim().length===0)return{bytes:o,lines:0};_e.appendFileSync(e,Buffer.concat([Buffer.from(VI(e)?"":`
|
|
39
|
+
`),r,Buffer.from(r[r.length-1]===Li?"":`
|
|
40
|
+
`)]));let s=0;for(let i of r)i===Li&&s++;return r[r.length-1]!==Li&&s++,{bytes:o,lines:s}},Oi=(e,t)=>{let n=bt(e);if(!_e.existsSync(n))return d("No events directory",0);try{let o=xs(t),r=_e.readdirSync(n).filter(c=>Ao(c)&&xs(c)===o),s=Co.join(n,t),i=0;for(let c of r){let u=bp(c);if(u!==null){let h=Co.join(n,c),x=_e.readFileSync(h).subarray(u);i+=hp(s,x,!0).lines,_e.rmSync(h,{force:!0});continue}let p=/~pending-/i.test(c)?c:WI(t),m=Co.join(n,p);p!==c&&_e.renameSync(Co.join(n,c),m);let f=hp(s,_e.readFileSync(m));i+=f.lines,_e.renameSync(m,Co.join(n,qI(p,f.bytes)))}return d("Folded pending logs",i)}catch(o){return l(`Unable to fold pending event logs in ${n}: ${o instanceof Error?o.message:String(o)}`)}}});import _i from"node:fs";import Bi from"node:path";import{decodeTime as KI}from"ulid";import{z as Ql}from"zod";var $i,YI,Np,Fi,XI,JI,wp,QI,ZI,Cp,Rp,Zl,Sp,ec,Ap,Tp,tc=g(()=>{"use strict";$t();w();ee();ft();ds();or();To();$i="unknown",YI=Ql.object({userId:Ql.string().min(1).default($i),userName:Ql.string().min(1).default($i)}),Np=new Set(["id","v","userId","userName"]),Fi=e=>{let t=Object.entries(e).filter(([r])=>!Np.has(r));if(t.length!==1)return null;let n=t[0]?.[1];if(typeof n!="object"||n===null)return null;let o=n.id;return typeof o=="string"&&o.length>0?o:null},XI=/^[0-9a-hjkmnp-tv-z]{26}$/i,JI=e=>XI.test(e)?e.toUpperCase():e,wp=e=>{let t=Bi.basename(e,".jsonl"),n=t.indexOf("."),o=Jl(n===-1?t:t.slice(0,n)),r=n===-1?void 0:t.slice(n+1),s=YI.safeParse({userId:JI(o),userName:r});return s.success?d("Parsed event file actor",s.data):l(`Invalid event file name ${Bi.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},QI=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?l(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?l("Invalid persisted event: action key is missing or invalid"):d("Resolved persisted action",t[0])},ZI=(e,t)=>t in e,Cp=(e,t)=>{let n=wp(e);if(a(n))return l(n.message);let o;try{o=_i.readFileSync(e,"utf8")}catch(c){if(bs(c))return d("Event file missing",null);throw c}let r=[],s=Bi.basename(e),i=(c,u)=>{t?.push({eventId:null,reason:"corrupt-line",detail:`${s}:${c} (${u})`,targetNodeId:null})};for(let[c,u]of o.split(`
|
|
41
|
+
`).entries()){let p=u.trim();if(!p)continue;let m;try{m=JSON.parse(p)}catch{i(c+1,"invalid JSON");continue}let f=_m(m);if(a(f)){i(c+1,f.message);continue}r.push({...f.value,userId:n.value.userId,userName:n.value.userName})}return d("Parsed persisted events file",r)},Rp=(e,t)=>e<t?-1:e>t?1:0,Zl=(e,t)=>{let n=Rp(e.id[0],t.id[0]);return n!==0?n:Rp(JSON.stringify(e),JSON.stringify(t))},Sp=(e,t)=>{let n=new Map,o=new Map;for(let m of e){let f=m.id[0],h=m.id[1]??null;n.set(f,m);let x=o.get(h)??[];x.push(m),o.set(h,x)}for(let m of o.values())m.sort(Zl);let r=[],s=new Set,i=m=>{let f=[m];for(;f.length>0;){let h=f.pop(),x=h.id[0];if(s.has(x))continue;r.push(h),s.add(x);let E=o.get(x)??[];for(let S=E.length-1;S>=0;S--)f.push(E[S])}},c=(o.get(null)??[]).filter(m=>{let f=Object.keys(m).filter(h=>!Np.has(h));return f.length===1&&f[0]===t});for(let m of c)i(m);let u=e.filter(m=>{let f=m.id[0],h=m.id[1]??null;return s.has(f)?!1:h===null||!n.has(h)}).sort(Zl);for(let m of u)i(m);let p=e.filter(m=>!s.has(m.id[0])).sort(Zl);for(let m of p)i(m);return r},ec=e=>os(e.map(t=>{try{return KI(t.id[0])}catch{return null}})),Ap=(e,t)=>{let n=new Set,o=[],r=[],s=ec(e);for(let i=0;i<e.length;i++){let c=e[i],u=c.id[0],p=c.id[1],m=s[i]??null;!(m!==null&&m<t)||p&&n.has(p)?(n.add(u),r.push(c)):o.push(c)}return{appliedEvents:o,unappliedEvents:r}},Tp=e=>{let t=new Set(e.actions),n=R=>t.has(R),o=R=>{let{userId:A,userName:L,..._}=R,j=QI(_);if(a(j))return l(j.message);let z=j.value,X=R.id?.[0];return X?ZI(_,z)?d("Decoded persisted event",{id:X,action:z,payload:_[z],userId:A}):l(`Persisted event is missing payload for action: ${z}`):l("Persisted event is missing id")},r=(R,A)=>{let L=[],_=new Map,j=new Map;for(let z of R){if(!Tl(z.v)){j.set(z.v,(j.get(z.v)??0)+1),A?.push({eventId:z.id[0],reason:"unsupported-schema-version",detail:`v${z.v}`,targetNodeId:Fi(z)});continue}let X=o(z);if(a(X)){A?.push({eventId:z.id[0],reason:"invalid-payload",detail:X.message,targetNodeId:Fi(z)});continue}let ue=X.value.action;if(!n(ue)){_.set(ue,(_.get(ue)??0)+1),A?.push({eventId:z.id[0],reason:"unknown-action",detail:ue,targetNodeId:Fi(z)});continue}let ze=e.readPayload(ue,X.value.payload);if(a(ze)){A?.push({eventId:z.id[0],reason:"invalid-payload",detail:ze.message,targetNodeId:Fi(z)});continue}L.push(X.value)}if(_.size>0){let z=[..._.entries()].map(([X,ue])=>`${X} (x${ue})`).join(", ");ce.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${z}. Upgrade to apply them.`)}if(j.size>0){let z=[...j.entries()].map(([X,ue])=>`v${X} (x${ue})`).join(", ");ce.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${z}. Upgrade to apply them.`)}return d("Decoded reconstructed events",L)},s=null;function i(R,A){let L=bt(R),_=wo(R);if(!_i.existsSync(L))return d("No events found",[]);let j=[],z=[];for(let ue=1;;ue++){j=[],z=[];let ze=!1;for(let q of Kl(L)){let ae=Cp(Bi.join(L,q),z);if(a(ae))return l(ae.message);if(ae.value===null){if(ue<Vl){ze=!0;break}continue}j.push(...ae.value)}if(!ze)break}A?.push(...z);let X=Sp(j,e.genesis);return s={root:R,signature:_,edge:X.at(-1)?.id?.[0]??null},d("All events loaded",X)}function c(R){let A=[],L=i(R,A);if(a(L))return l(L.message);let _=r(L.value,A);return a(_)?l(_.message):d("Loaded merged events",{events:_.value,unreadable:A})}function u(R){let A=i(R);return a(A)?l(A.message):d("Loaded event actors",A.value.map(({userId:L,userName:_})=>({userId:L,userName:_})))}function p(R){let A=new Map,L=bt(R),_;try{if(!_i.existsSync(L))return A;_=_i.readdirSync(L)}catch{return A}let j=new Set;for(let X of _){if(!X.endsWith(".jsonl"))continue;let ue=wp(X);if(a(ue))continue;let{userId:ze,userName:q}=ue.value;if(!ze||!q||q===$i)continue;let ae=A.get(ze);ae!==void 0&&ae!==q&&j.add(ze),A.set(ze,q)}if(j.size===0)return A;let z=u(R);if(a(z))return A;for(let{userId:X,userName:ue}of z.value)j.has(X)&&(!ue||ue===$i||A.set(X,ue));return A}function m(R){let A=c(R);return a(A)?l(A.message):d("Loaded merged events",A.value.events)}function f(R,A){let L=i(R);if(a(L))return l(L.message);let{appliedEvents:_,unappliedEvents:j}=Ap(L.value,A),z=r(_);if(a(z))return l(z.message);let X=r(j);return a(X)?l(X.message):d("Loaded merged events before time",{appliedEvents:z.value,unappliedEvents:X.value})}function h(R=process.cwd()){let A=wo(R);if(s&&s.root===R&&s.signature===A)return d("Loaded edge reference, unchanged",s.edge);let L=i(R);return a(L)?l(L.message):d("Loaded edge reference",L.value.at(-1)?.id?.[0]??null)}function x(R,A,L){if(!s||s.root!==R)return;let _=Yl(R,s.signature,A);s=_===null?null:{root:R,signature:_,edge:L}}function E(){s=null}let S=R=>Sp(R,e.genesis);function C(R){let A=i(R);if(a(A))return l(A.message);let L=ec(A.value);return d("Loaded effective event times",new Map(A.value.map((_,j)=>[_.id[0],L[j]??null])))}return{fromPersistedEvent:o,decodeReconstructedEvents:r,loadMergedEventsWithUnreadable:c,loadEventActors:u,loadActorNames:p,loadMergedEvents:m,loadMergedEventsBefore:f,getEdgeRef:h,advanceEdgeRef:x,clearEdgeCache:E,getSortedEvents:S,loadEffectiveEventTimes:C}}});var ji,B,rr,Xn,Jn,eE,kp,Ui=g(()=>{"use strict";$t();w();ji=(e,t)=>l(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),B=(e,t)=>({...ji(e,t),convergence:!0}),rr=e=>a(e)&&e.convergence===!0,Xn=e=>{let t=e.filter(a);return{fatal:t.filter(n=>!rr(n)),skipped:t.filter(rr)}},Jn=e=>{e.length!==0&&ce.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},eE=e=>e.userId?.length?null:ji("Invalid user ID format",e),kp=e=>{let t=null;function n(r,s=!1){let i=e.apply[r.action];if(!i)return l(`Unknown event action "${r.action}", likely created by a newer epiq version. Evt id: ${r.id}`);if(!e.replay.isInitialized()&&r.action!==e.genesis)return B(`${r.action} arrived before the state was initialized`,r);if(r.action===e.genesis&&t){if(t.genesisApplied)return B("the state is already initialized",r);t.genesisApplied=!0}let c;try{c=i(r)}catch(m){return B(`threw while materializing (${m instanceof Error?m.message:String(m)})`,r)}if(a(c))return c;let u=eE(r);if(u)return u;let p=e.replay.afterApply(r,{batched:t!==null,bypassLogging:s});return p||c}return{materialize:n,materializeAll:r=>{let s=e.replay.batch(()=>{let i=t===null;i&&(t={genesisApplied:!1});let c=!1;try{let u=r.map(p=>n(p));if(i){c=!0;let p=e.replay.flush();if(p)return r.map(()=>p)}return u}finally{i&&(t=null,c||e.replay.flush())}});return a(s)?r.map(()=>l(s.message)):s.value}}}});var Mp,Lp=g(()=>{"use strict";Mp=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown"});import Pp from"node:fs";import nc from"node:path";import{decodeTime as tE,monotonicFactory as nE}from"ulid";var oE,rE,sE,Qn,Dp,Op,Fp,Hi=g(()=>{"use strict";$t();w();ee();Lp();ft();ds();Ft();or();To();oE=0xffffffffffff,rE=hi,sE=e=>{let t=Date.now(),n;try{n=tE(e)}catch{return t}return n>=oE?t:n>t+rE?(ce.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)},Qn=({userId:e})=>`${Mp(e)}.jsonl`,Dp=(e,t)=>{let n;try{if(!Pp.existsSync(e))return[t];n=Pp.readdirSync(e)}catch{return[t]}let o=xs(t);return[...n.filter(s=>!s.endsWith(".jsonl")||s===t||Ao(s)?!1:xs(s)===o).sort(),t]},Op=(e,{userId:t})=>{let n=Qn({userId:t});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(n))return l(`Invalid event log file name: ${n}`);let r=nc.join(bt(e),n);return d("Successfully resolved event log path",r)},Fp=e=>{let t=nE();function n(r,s){let i;if(s&&s.current!==void 0)i=s.current;else{let u=e.getEdgeRef(r);if(a(u))return l(u.message);i=u.value}let c=i?t(sE(i)):t();return d("Minted event id",[c,i])}function o({event:r,rootDir:s,edge:i,id:c}){try{let u=cp(s);if(a(u))return u;let p=Op(s,{userId:r.userId});if(a(p))return p;let m=xp(s,nc.basename(p.value)),f=c?d("Minted event id",c):n(s,i);if(a(f))return l(f.message);let[h,x]=f.value,E=kl(Pm(r),[h,x]);if(a(E))return l(E.message);Ep(m,`${JSON.stringify(E.value)}
|
|
42
|
+
`),i&&(i.current=h);let S=nc.basename(m);return e.advanceEdgeRef(s,S,h),gp(s,S),d("Event persisted",{path:m,entry:E.value})}catch(u){let p=u instanceof Error?u.message:"Unknown persist error";return l(`Failed to persist event: ${p}`)}}return{mintEventId:n,persist:o}}});var _p,Bp=g(()=>{"use strict";w();_p=(e,t,n)=>{function o(s,i,c){let u=n.mintEventId(i,c);if(a(u))return l(u.message);let p={...s,id:u.value[0]},m=t.materialize(p);if(m.status!==Sn.Success)return m;let f=n.persist({event:p,rootDir:i,edge:c,id:u.value});return a(f)?f:m}function r(s,i){if(s.length===0||!s[0])return l("No events provided");let c=e.write.readOnlyReason();if(c)return l(c);let u=e.replay.batch(()=>{let p={},m=e.write.beforeWrite(s[0],x=>o(x,i,p));if(a(m))return l(m.message);let f=s.map(x=>o(x,i,p)),h=f.filter(a);return h.length>0?l("Materialize and persist failed: "+h.map(x=>x.message).join(", ")):d("Materialization succeeded",f.map(x=>x.value))});return a(u)?l(u.message):u.value??l("Materialize and persist produced nothing")}return{materializeAndPersist:o,materializeAndPersistAll:r}}});var $p,jp=g(()=>{"use strict";tc();Ui();Hi();Bp();$p=e=>{let t=kp(e),n=Tp(e),o=Fp(n),r=_p(e,t,o);return{...t,...n,...o,...r}}});import{z as te}from"zod";var K,en,Zn,Wi,oc,iE,Up,Hp=g(()=>{"use strict";w();K=te.string().min(1),en=te.string(),Zn=te.string(),Wi=te.looseObject({id:K}),oc=te.looseObject({id:K,name:en,parent:K,rank:Zn}),iE={"init.workspace":te.looseObject({id:K,name:en,rank:Zn}),"add.workspace":te.looseObject({id:K,name:en,rank:Zn}),"add.board":oc,"add.swimlane":oc,"add.issue":oc,"add.field":te.looseObject({id:K,name:en,parent:K,rank:Zn}),"edit.title":te.looseObject({id:K,name:en}),"delete.node":Wi,"lock.node":Wi,"move.node":te.looseObject({id:K,parent:K,rank:Zn}),"edit.description":te.looseObject({id:K,md:te.string()}),"close.issue":te.looseObject({id:K,parent:K,rank:Zn}),"reopen.issue":te.looseObject({id:K,parent:K,rank:Zn}),"create.tag":te.looseObject({id:K,name:en}),"tombstone.tag":Wi,"restore.tag":te.looseObject({id:K,name:en}),"create.contributor":te.looseObject({id:K,name:en}),"rename.contributor":te.looseObject({id:K,name:en}),"tombstone.contributor":Wi,"restore.contributor":te.looseObject({id:K,name:en}),"link.contributor.user":te.looseObject({contributor:K}),"link.contributor.email":te.looseObject({contributor:K,email:K}),"unlink.contributor.email":te.looseObject({contributor:K,email:K}),"add.issue.assignee":te.looseObject({id:K,assignee:K}),"remove.issue.assignee":te.looseObject({id:K,assignee:K}),"add.issue.tag":te.looseObject({id:K,tag:K}),"remove.issue.tag":te.looseObject({id:K,tag:K}),"add.issue.comment":te.looseObject({id:K,issue:K,md:te.string()}),"edit.issue.comment":te.looseObject({id:K,issue:K,md:te.string()}),"delete.issue.comment":te.looseObject({id:K,issue:K}),"add.issue.attachment":te.looseObject({id:K,issue:K,hash:te.string().min(1),ext:te.string().min(1),name:en,bytes:te.number()}),"delete.issue.attachment":te.looseObject({id:K,issue:K}),"rebalance.children":te.looseObject({parent:K,ranks:te.record(te.string(),Zn)})},Up=(e,t)=>{let o=iE[e].safeParse(t);return o.success?d("Payload is readable",void 0):l(`${e}: ${o.error.issues.map(r=>`${r.path.join(".")||"payload"} ${r.message}`).join(", ")}`)}});import{ulid as aE}from"ulid";var Wp,qp=g(()=>{"use strict";w();pe();Fe();Wp=(e,t)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return d("Contributor write already in flight",void 0);let{userId:n,userName:o}=le();if(!o||n!==e.userId)return d("Not this actor own write",void 0);let r=N.getContributor(e.userId),s={id:aE(),action:r?"rename.contributor":"create.contributor",payload:{id:e.userId,name:o},userId:e.userId};if(r&&(r.tombstoned||r.name===o))return d("Contributor name is current",void 0);let i=t(s);return a(i)?l(i.message):d("Contributor name recorded",void 0)}});var Ce,sr=g(()=>{"use strict";Ce={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",DIFF:"Diff",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var V,Is,mt=g(()=>{"use strict";V=e=>e.slice(-7).toUpperCase(),Is=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?V(e).includes(n):!0}});var Be,eo=g(()=>{"use strict";me();mt();Be={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:se.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,o,r=!1)=>({id:e,title:t,rank:o,isDeleted:!1,props:{ref:V(e)},context:se.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:se.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:o,props:r={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:se.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:o,childRenderAxis:r="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:se.FIELD_LIST,childRenderAxis:r,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{ref:V(e)},context:se.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!0,isVirtual:s=!0,disabled:i=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:i?{disabled:!0}:{},context:se.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:r,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:o,props:r={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:se.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})}});var lE,Ae,qi,tn=g(()=>{"use strict";lE=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[Ae,qi]=lE});var Es,Gp,zp=g(()=>{"use strict";me();w();sr();wt();pe();eo();O();Ui();tn();Es=(e,t,n)=>N.getNode(e)?B(`a node with id ${e} already exists`,n):t===e?B("a node cannot be its own parent",n):null,Gp={"init.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=Be.workspace(t,n,o),s=Rs(r);if(a(s))return ji(s.message,e);let i=N.createNode(r);return a(i)?B(i.message??"Failed to initialize workspace",e):Nl(i.value)?d("Workspace initialized",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=Es(t,void 0,e);if(r)return r;let s=N.createNode(Be.workspace(t,n,o));return a(s)?B(s.message??"Failed to add workspace",e):Nl(s.value)?d("Added workspace",{action:e.action,result:s.value}):l("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=Es(t,o,e);if(s)return s;let i=N.createNode(Be.board(t,n,o,r));return a(i)?B(i.message??"Unable to create board",e):xo(i.value)?d("Added board",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=Es(t,o,e);if(s)return s;let i=N.createNode(Be.swimlane(t,n,o,r));return a(i)?B(i.message??"Unable to create swimlane",e):bo(i.value)?d("Added swimlane",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=Es(t,o,e);if(s)return s;let i=N.createNode(Be.ticket(t,n,o,r));return a(i)?B(i.message??"Unable to create issue",e):U(i.value)?d("Added issue",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:o,val:r,rank:s}=e.payload,i=Es(t,o,e);if(i)return i;let c=N.createNode(Be.field({id:t,name:n,parentNodeId:o,rank:s,props:{value:r},childRenderAxis:n.includes(Ce.DESCRIPTION)?"vertical":"horizontal"}));return a(c)?B(c.message??`Unable to create field: ${n}`,e):ot(c.value)?d("Added field",{action:e.action,result:c.value}):l("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!N.getNode(t))return B(`Unable to locate node with id ${t}`,e);let r=N.renameNode(t,n);return a(r)?B(r.message??"Unable to edit title",e):d("Edited title",{action:e.action,result:r.value})},"delete.node":e=>{let{id:t}=e.payload,n=N.tombstoneNode(t);return a(n)?B(n.message??"Unable to delete node",e):d("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,o=N.createTag({id:t,name:n});return a(o)?B(o.message??"Unable to create tag",e):d("Tag added",{action:e.action,result:o.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=N.tombstoneTag(t);return a(n)?B(n.message??"Unable to delete tag",e):d("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,o=N.restoreTag(t,n);return a(o)?B(o.message??"Unable to restore tag",e):d("Tag restored",{action:e.action,result:o.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,o=N.createContributor({id:t,name:n});return a(o)?B(o.message??"Unable to create contributor",e):d("Contributor created",{action:e.action,result:o.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,o=N.renameContributor(t,n);return a(o)?B(o.message??"Unable to rename contributor",e):d("Contributor renamed",{action:e.action,result:o.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=N.tombstoneContributor(t);return a(n)?B(n.message??"Unable to remove contributor",e):d("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,o=N.restoreContributor(t,n);return a(o)?B(o.message??"Unable to restore contributor",e):d("Contributor restored",{action:e.action,result:o.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,o=N.tag(t,n);return a(o)?B(o.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,o=N.untag(t,n);return a(o)?B(o.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,o=N.assign(t,n);return a(o)?B(o.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,o=N.unassign(t,n);return a(o)?B(o.message??"Unable to unassign issue",e):d("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:o}=e.payload,r=N.moveNodeToRank({id:t,parentId:n,rank:o});return a(r)?B(r.message??"Failed to move node",e):d("Moved node",{action:e.action,result:r.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,o=N.editValue(t,n);return a(o)?B(o.message??"Unable to edit description",e):d("Set node value",{action:e.action,result:o.value})},"close.issue":e=>{let{id:t,parent:n,rank:o}=e.payload,r=N.getNode(t);if(!r)return B("Unable to locate issue",e);if(!U(r))return B("Can only close issues",e);let s=N.getNode(Ae);if(!s)return B("Unable to locate target swimlane",e);if(n!==s.id)return B("Close target must be closed swimlane",e);let i=N.moveNodeToRank({id:t,parentId:n,rank:o});return a(i)?B(i.message??"Unable to close issue",e):d("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:o}=e.payload,r=N.getNode(t);if(!r)return B("Unable to locate issue",e);if(!U(r))return B("Can only reopen issues",e);let s=N.getNode(Ae);if(!s)return B("Unable to locate closed swimlane",e);if(n===s.id)return B("Cannot reopen issue into closed swimlane",e);if(!N.getNode(n))return B("Reopen parent no longer exists",e);let c=N.moveNodeToRank({id:t,parentId:n,rank:o});return a(c)?B(c.message??"Unable to reopen issue",e):d("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=N.lockNode(t);return a(n)?B(n.message??"Unable to lock node",e):d("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[o,r]of Object.entries(n)){let s=N.getNode(o);if(!s)return B(`Unable to locate node ${o}`,e);if(s.parentNodeId!==t)return B(`Node ${o} is not child of ${t}`,e);let i=N.updateNode({...s,rank:r});if(a(i))return B(i.message??"Unable to rebalance child",e)}return d("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:o,md:r}=e.payload,s=N.createComment({id:t,issue:n,authorId:o,md:r,deleted:!1});return a(s)?B(s.message??"Unable to add comment",e):d("Comment added",{action:e.action,result:{id:t,issue:n,author:o,md:r}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:o}=e.payload,r=N.getComment(t);if(!r)return B("Unable to locate comment",e);if(r.issue!==n)return B("Comment does not belong to issue",e);let s=N.editComment(t,o);return a(s)?B(s.message??"Unable to edit comment",e):d("Comment edited",{action:e.action,result:{id:t,issue:n,md:o}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,o=N.getComment(t);if(!o)return B("Unable to locate comment",e);if(o.issue!==n)return B("Comment does not belong to issue",e);let r=N.deleteComment(t);return a(r)?B(r.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:o,ext:r,name:s,bytes:i}=e.payload,c=N.createAttachment({id:t,issue:n,hash:o,ext:r,name:s,bytes:i,deleted:!1});return a(c)?B(c.message??"Unable to add attachment",e):d("Attachment added",{action:e.action,result:{id:t,issue:n,hash:o}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,o=N.getAttachment(t);if(!o)return B("Unable to locate attachment",e);if(o.issue!==n)return B("Attachment does not belong to issue",e);let r=N.deleteAttachment(t);return a(r)?B(r.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(!Gn(n))return B(`not an email address: ${n}`,e);let o=N.linkContributorEmail({email:n,contributor:t,authorId:e.userId});return a(o)?B(o.message??"Unable to link email",e):d("Email linked to contributor",{action:e.action,result:o.value})},"unlink.contributor.email":e=>{let{contributor:t,email:n}=e.payload,o=N.unlinkContributorEmail(n,t,e.userId);return a(o)?B(o.message??"Unable to unlink email",e):d("Email unlinked from contributor",{action:e.action,result:o.value})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=N.linkUserId({contributorId:t,userId:e.userId});return a(n)?B(n.message??"Unable to link contributor",e):d("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}}});var Vp,Kp,cE,dE,rc,uE,Ln,mE,Yp,sc=g(()=>{"use strict";me();w();pe();O();ic();Vp=e=>{let t=N.getNode(e);if(!t||!U(t)||t.isDeleted)return null;let n=zi(t);return a(n)?n:null},Kp=e=>{if(!Vi())return null;for(let t of e){let n=Vp(t);if(n)return n;let o=v().nodes[t]?.parentNodeId;if(!o)continue;let r=Vp(o);if(r)return r}return null},cE=(e,t)=>{let n=N.getNode(e);n&&N.updateNode({...n,log:[...n.log??[],t]})},dE=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},rc=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 dE(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":case"link.contributor.email":case"unlink.contributor.email":default:return[]}},uE=e=>{Pe(t=>({...t,eventLog:[...t.eventLog,e]}))},Ln=null,mE=e=>{for(let[t,n]of e.nodeLog){let o=N.getNode(t);o&&N.updateNode({...o,log:[...o.log??[],...n]})}return e.appLog.length>0&&Pe(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),Kp([...e.virtualNodeIds])},Yp={isInitialized:()=>jt(),batch:e=>Gi(e),afterApply(e,{batched:t,bypassLogging:n}){let o=[...new Set(rc(e))];if(t){Ln??={appLog:[],nodeLog:new Map,virtualNodeIds:new Set};for(let r of o){if(!n){let s=Ln.nodeLog.get(r);s?s.push(e):Ln.nodeLog.set(r,[e])}if(Vi()){Ln.virtualNodeIds.add(r);let s=v().nodes[r]?.parentNodeId;s&&Ln.virtualNodeIds.add(s)}}return n||Ln.appLog.push(e),null}return n||(o.forEach(r=>cE(r,e)),uE(e)),Kp(o)},flush(){if(!Ln)return null;let e=Ln;return Ln=null,mE(e)}}});var ge,Xp=g(()=>{"use strict";w();Fe();vo();ge=()=>{let{userName:e,userId:t}=le();return e?t?gi(t)?ts(e)?d("Successfully resolved actor ID",{userId:t,userName:e}):l("Invalid user name in config"):l("Invalid user ID in config"):l("User ID not configured"):l("User name not configured")}});var pE,fE,Ss,Pn,TL,kL,nn,Jp,ko,Mo,ac,ML,LL,PL,DL,lc,OL,Qp,FL,F,$=g(()=>{"use strict";ds();jp();Hp();O();qp();_t();zp();sc();Xp();ds();tc();Ui();Hi();pE={genesis:"init.workspace",actions:Cl,readPayload:Up,apply:Gp,replay:Yp,write:{readOnlyReason:()=>{let e=v();return e.readOnly?e.readOnlyReason??"Cannot change the board while time travelling":null},beforeWrite:Wp}},fE=$p(pE),{materialize:Ss,materializeAll:Pn,fromPersistedEvent:TL,decodeReconstructedEvents:kL,loadMergedEventsWithUnreadable:nn,loadEventActors:Jp,loadActorNames:ko,loadMergedEvents:Mo,loadMergedEventsBefore:ac,getEdgeRef:ML,advanceEdgeRef:LL,clearEdgeCache:PL,getSortedEvents:DL,loadEffectiveEventTimes:lc,mintEventId:OL,persist:Qp,materializeAndPersist:FL,materializeAndPersistAll:F}=fE});var Lo,cc,Zp=g(()=>{"use strict";mt();Lo=e=>e.trim().toLocaleLowerCase(),cc=(e,t)=>Lo(e).includes(Lo(t))});var gE,hE,ef,tf,vE,yE,nf,of=g(()=>{"use strict";O();mt();Zp();gE=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},hE=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>{let o=t[n];return o?o.name:void 0}).filter(n=>!!n)},ef=null,tf=new Map,vE=()=>{let e=v().eventLog??[];if(e===ef)return tf;let t=new Map;for(let n of e){if(!n.userId)continue;let o=n.payload;for(let r of[o.id,o.issue]){if(typeof r!="string")continue;let s=t.get(r)??new Set;s.add(n.userId),t.set(r,s)}}return ef=e,tf=t,t},yE=e=>{let{contributors:t}=v(),n=vE().get(e.id);return n?[...n].map(o=>t[o]?.name).filter(o=>!!o):[]},nf=(e,t)=>{let n=Lo(t.value);if(!n)return!0;switch(t.target){case"title":return cc(e.title??"",n);case"description":return cc(e.props.description??"",n);case"tag":return gE(e).map(Lo).some(r=>r.includes(n));case"assignee":return hE(e).map(Lo).some(r=>r.includes(n));case"actor":return yE(e).map(Lo).some(r=>r.includes(n));case"ref":return Is(e.id,t.value);default:return!0}}});var dc,bE,rf,sf,af,uc=g(()=>{"use strict";me();of();dc=(e,t)=>e.rank<t.rank?-1:e.rank>t.rank?1:0,bE=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,rf=(e,t)=>Object.values(e).filter(n=>bE(n,t)).sort(dc),sf=(e,t)=>{let n={};for(let o of Object.values(e)){if(U(o)&&t.length>0&&!t.every(s=>nf(o,s))||!o.parentNodeId||o.isDeleted)continue;let r=n[o.parentNodeId];r?r.push(o):n[o.parentNodeId]=[o]}for(let o of Object.keys(n))n[o].sort(dc);return n},af=(e,t)=>{let n={};for(let o of Object.values(e)){if(!o.parentNodeId||o.isDeleted||!t.has(o.parentNodeId))continue;let r=n[o.parentNodeId];r?r.push(o):n[o.parentNodeId]=[o]}for(let o of Object.keys(n))n[o].sort(dc);return n}});var lf,Ki,ke,cf,df,pn,Dn,Bt=g(()=>{"use strict";Dm();$();w();O();uc();Zo();lf=e=>Ki(ke(e),{at:"end"}),Ki=(e,t={at:"end"})=>{let n=r=>a(r)?d("Rank space exhausted",{rank:"",needsRebalance:!0}):d("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(dt(void 0,void 0));let o=()=>n(dt(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let r=e[0];return r?n(dt(void 0,r.rank)):l("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(dt(r.rank,void 0)):l("Unable to resolve last sibling")}case"before":{let r=cf(e,t.sibling),s=r<0?void 0:e[r];if(!s)return o();let i=r>0?e[r-1]:void 0;return n(dt(i?.rank,s.rank))}case"after":{let r=cf(e,t.sibling),s=r<0?void 0:e[r];if(!s)return o();let i=r<e.length-1?e[r+1]:void 0;return n(dt(s.rank,i?.rank))}}},ke=e=>{let t=v();if(!uf()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return rf(t.nodes,e)},cf=(e,t)=>e.findIndex(n=>n.id===t),df=(e,t,n={at:"end"})=>Ki(ke(t).filter(o=>o.id!==e),n),pn=(e,t,n,o,r)=>{let s=df(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return d("Resolved rank",s.value.rank);let i=Al(e,o);if(a(i))return i;let c=F([i.value],r);if(a(c))return c;let u=df(t,e,n);return a(u)?u:u.value.needsRebalance?l("Rank rebalance failed to create space"):d("Resolved rank after rebalance",u.value.rank)},Dn=(e,t,n)=>{let o=lf(e);if(a(o))return o;if(!o.value.needsRebalance)return d("Resolved rank",o.value.rank);let r=Al(e,t);if(a(r))return r;let s=F([r.value],n);if(a(s))return s;let i=lf(e);return a(i)?i:i.value.needsRebalance?l("Rank rebalance failed to create space"):d("Resolved rank after rebalance",i.value.rank)}});var Ns,H,mf,pf,ff,xt=g(()=>{"use strict";O();Ns=5,H={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.contextNode,n=Math.max(0,e.selectedIndex),o=ve(t.id),r=o[n];r&&(t.context==="FIELD"&&o.length===0||r.context==="COMMENT"||r.context==="TEXT"||H.navigate({contextNode:r,selectedIndex:ve(r.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let o=ve(n.id),r=o.findIndex(({id:i})=>i===e.id),s=o.length===0?-1:r>=0?r:0;H.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>mf(1),navigateToPreviousItem:()=>mf(-1),jumpToNextItem:()=>pf(Ns),jumpToPreviousItem:()=>pf(-Ns),navigateToNextContainer:()=>ff(1),navigateToPreviousContainer:()=>ff(-1),navigate:({contextNode:e,selectedIndex:t})=>{T({contextNodeId:e.id,selectedIndex:t})}},mf=e=>{let{selectedIndex:t,contextNode:n}=v(),o=ve(n.id).length;if(o===0)return;let s=(Math.max(0,t)+e+o)%o;H.navigate({selectedIndex:s,contextNode:n})},pf=e=>{let{selectedIndex:t,contextNode:n}=v(),o=ve(n.id).length;if(o===0)return;let r=Math.max(0,t),s=Math.min(Math.max(r+e,0),o-1);H.navigate({selectedIndex:s,contextNode:n})},ff=e=>{let{contextNode:t,nodes:n,selectedIndex:o}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let r=n[t.parentNodeId];if(!r)return;let s=ve(r.id),i=s.findIndex(h=>h.id===t.id);if(i<0)return;let c=s.at(i+e)??s.at(0);if(!c)return;let u=ve(c.id),p=Math.max(0,u.length-1),m=Math.min(Math.max(0,o),p),f=u.length?m:-1;H.navigate({contextNode:c,selectedIndex:f})}});var hf,vf,xE,Yi,yf,gf,IE,bf,xf=g(()=>{"use strict";me();w();Bt();O();xt();hf=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),vf=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},xE=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&&ot(t)&&t.childRenderAxis==="vertical"},Yi=(e,t)=>{let{nodes:n}=v(),o=n[e];if(!o||o.isDeleted)return!1;let r=ke(o.id);return H.navigate({contextNode:o,selectedIndex:hf(t,r.length)}),!0},yf=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let o=n.parentNodeId;if(!o)return Yi(n.id,0);let r=t[o];if(!r||r.isDeleted)return!1;let i=ke(r.id).findIndex(c=>c.id===n.id);return i>=0?(H.navigate({contextNode:r,selectedIndex:i}),!0):yf(r.id)},gf=e=>{let{nodes:t}=v(),n=e,o=new Set;for(;n&&!o.has(n);){if(o.add(n),yf(n))return!0;n=t[n]?.parentNodeId}return!1},IE=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},bf=e=>{let{nodes:t,rootNodeId:n}=v();if(xE(e.contextNodeId)&&Yi(e.contextNodeId,e.selectedIndex))return d("Restored navigation inside text container",null);if(IE(e.selectedNodeId)&&e.selectedNodeId&&gf(e.selectedNodeId))return d("Restored navigation to selected node or ancestor",null);if(Yi(e.contextNodeId,e.selectedIndex))return d("Restored navigation to previous container",null);if(e.parentNodeId&&Yi(e.parentNodeId,e.selectedIndex))return d("Restored navigation to previous parent",null);if(gf(e.contextNodeId))return d("Restored navigation to previous container or ancestor",null);let o=t[n];if(!o||o.isDeleted)return l("Unable to restore navigation");let r=ke(o.id);return H.navigate({contextNode:o,selectedIndex:hf(e.selectedIndex,r.length)}),d("Restored navigation to root",null)}});import{monotonicFactory as EE,ulid as fn}from"ulid";function RE(){let e=Me();if(a(e))return l("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return l("No workspace found in event log");let[o]=ve(n.id),[r]=o?ve(o.id):[];if(r){let s=t.renderedChildrenIndex?.[r.id]??[];return d("Resolved boot nav target",{contextNode:r,selectedIndex:s.length>0?0:-1})}else return o?d("Resolved boot nav target",{contextNode:o,selectedIndex:0}):d("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function SE(){let e=RE();return a(e)?e:H.navigate(e.value)}function If({userId:e,userName:t}){let n=ws(),o=ws(),r=ws(),s=ws(),i=ws(),c=dt(void 0,void 0);if(a(c))return c;let u=dt(void 0,void 0);if(a(u))return u;let p=dt(u.value,void 0);if(a(p))return p;let m=dt(void 0,void 0);if(a(m))return m;let f=dt(m.value,void 0);if(a(f))return f;let h=dt(f.value,void 0);if(a(h))return h;let x=dt(void 0,void 0);return a(x)?x:d("Created default events",[{id:fn(),userId:e,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:fn(),userId:e,action:"create.contributor",payload:{id:e,name:t}},{id:fn(),userId:e,action:"add.board",payload:{id:o,name:"Default",parent:n,rank:u.value}},{id:fn(),userId:e,action:"add.swimlane",payload:{id:r,name:"Todo",parent:o,rank:m.value}},{id:fn(),userId:e,action:"add.swimlane",payload:{id:s,name:"In progress",parent:o,rank:f.value}},{id:fn(),userId:e,action:"add.swimlane",payload:{id:i,name:"Done",parent:o,rank:h.value}},{id:fn(),userId:e,action:"add.board",payload:{id:qi,name:"Closed",parent:n,rank:p.value}},{id:fn(),userId:e,action:"add.swimlane",payload:{id:Ae,name:"Closed",parent:qi,rank:x.value}},{id:fn(),userId:e,action:"lock.node",payload:{id:qi}},{id:fn(),userId:e,action:"lock.node",payload:{id:Ae}}])}function gn(e,t=[]){if(NE())return d("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Be.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=Rs(s);return a(i)?i:(T({hasProjectDefinition:!1,mode:b.DEFAULT}),d("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return l("Initialized Epiq project has no workspace init event");let n=Pn(e),{fatal:o,skipped:r}=Xn(n);return o.length>0?l(`Materializing failed:
|
|
43
|
+
${o.map(s=>s.message).join(`
|
|
44
|
+
`)}`):(Jn(r),SE(),T({hasProjectDefinition:!0}),wE(t),d("State booted successfully",null))}var ws,NE,wE,Po=g(()=>{"use strict";$t();xt();Oe();w();eo();O();Zo();$();tn();ws=EE();NE=()=>{let e=Me();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},wE=e=>{if(e.length===0)return;let t=e.filter(o=>o.reason==="corrupt-line"||o.reason==="invalid-payload"),n=e.filter(o=>o.reason==="unsupported-schema-version"||o.reason==="unknown-action");if(n.length>0){let o=[...new Set(n.map(r=>r.detail))].join(", ");ce.info(`This build cannot read ${n.length} event(s) in the log (${o}). They are skipped, so anything they changed may be out of date until you upgrade.`)}if(t.length>0){let o=[...new Set(t.map(r=>r.detail))].join(", ");ce.info(`Skipped ${t.length} corrupt line(s) in the event log (${o}). The rest of the board loaded normally; those events are unrecoverable.`)}}});import{WebSocket as CE}from"ws";var AE,Ef,Rf=g(()=>{"use strict";AE=new Set,Ef=e=>{let t=JSON.stringify(e);for(let n of AE)n.readyState===CE.OPEN&&n.send(t)}});var Xi,ir,Do,mc,Ji,$e,Cs=g(()=>{"use strict";Rf();w();O();Xi=e=>{jt()&&(T({syncStatus:e}),Ef({type:"sync-status",payload:e}))},ir=(e="Syncing...")=>{Xi({status:"syncing",msg:e})},Do=(e="Synced")=>{Xi({status:"synced",msg:e})},mc=e=>{Xi({status:"failed",msg:e})},Ji=e=>{Xi({status:"offline",msg:e})},$e=e=>(mc(e),l(e))});var ar,Sf,ye,Qi=g(()=>{"use strict";w();ar=(e,t)=>(logger.error(`[boot:${e}] ${t}`),l(`[boot:${e}] ${t}`)),Sf=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)}},ye=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});import Zi from"node:fs";import Nf from"node:path";var st,wf,TE,pc,kE,Cf,fc=g(()=>{"use strict";Cn();Ke();w();ee();Jt();st=".epiq/project.json",wf=e=>Nf.join(e,st),TE=e=>{if(!Zi.existsSync(wf(e)))return d("State branch carries no identity yet",null);let t=At(e);return a(t)?l(`On the state branch: ${t.message}`):d("Read the state branch identity",t.value)},pc=(e,t)=>{try{let n=wf(e);return Zi.mkdirSync(Nf.dirname(n),{recursive:!0}),Zi.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
45
|
+
`,"utf8"),d("Wrote the state branch identity",void 0)}catch(n){return l(n instanceof Error?`Failed to write the state branch identity: ${n.message}`:"Failed to write the state branch identity")}},kE=({checkout:e,branch:t,stateBranch:n})=>[`This checkout's ${st} 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}:${st} > ${st}`,"","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(`
|
|
46
|
+
`),Cf=({repoRoot:e,stateBranchRoot:t,stateBranch:n})=>{if(!Zi.existsSync(er(e)))return d("No project file to compare","no-checkout-file");let o=At(e);if(a(o))return l(o.message);let r=TE(t);if(a(r))return l(r.message);if(r.value===null){let s=pc(t,o.value);return a(s)?l(s.message):d("Stamped the state branch with this project","stamped")}return r.value.projectId!==o.value.projectId?l(kE({checkout:o.value,branch:r.value,stateBranch:n})):d("The checkout and the state branch agree","matched")}});import hn from"node:fs";import As from"node:path";var lr,Af,Tf,kf,ME,Mf,LE,PE,Lf,gc=g(()=>{"use strict";Ke();w();To();or();ee();lr=e=>e.split(`
|
|
47
|
+
`).filter(t=>t.trim().length>0),Af=e=>{let t=As.join(e,ut,Mn);try{if(!hn.existsSync(t))return d("No events directory",[]);let n=hn.readdirSync(t).filter(o=>o.endsWith(".jsonl")).filter(o=>lr(hn.readFileSync(As.join(t,o),"utf8")).length>0);return d("Looked for stranded event logs",n)}catch(n){return l(`Unable to check ${t} for event logs before deleting it: ${n instanceof Error?n.message:String(n)}`)}},Tf=e=>As.join(e,ut,Mn),kf=e=>{let t=Tf(e),n=new Map;try{if(!hn.existsSync(t))return n;for(let o of hn.readdirSync(t))if(o.endsWith(".jsonl")&&!Ao(o))try{n.set(o,lr(hn.readFileSync(As.join(t,o),"utf8")))}catch(r){if(!bs(r))throw r}}catch{return n}return n},ME=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},Mf=(e,t)=>{if(t.size===0)return[];let n=Tf(e),o=[];for(let[r,s]of t){if(s.length===0)continue;let i=As.join(n,r);try{let c=hn.existsSync(i)?hn.readFileSync(i,"utf8"):null,u=new Set(c===null?[]:lr(c)),p=s.filter(f=>!u.has(f)).filter(ME);if(p.length===0)continue;hn.mkdirSync(n,{recursive:!0});let m=c!==null&&c.length>0&&!c.endsWith(`
|
|
48
|
+
`);hn.appendFileSync(i,`${m?`
|
|
49
|
+
`:""}${p.join(`
|
|
50
50
|
`)}
|
|
51
|
-
`,"utf8"),
|
|
52
|
-
`),
|
|
53
|
-
`));
|
|
54
|
-
${n.message}`);let
|
|
55
|
-
${
|
|
56
|
-
`+n.message);if(n.value)return
|
|
57
|
-
`+
|
|
58
|
-
`+s.message);let i=s.value;if(
|
|
59
|
-
${c.message}`)}if(i){let c=await W({args:["branch","--track",t,`${
|
|
60
|
-
${c.message}`):
|
|
61
|
-
`),
|
|
62
|
-
`+
|
|
63
|
-
`));
|
|
64
|
-
${
|
|
65
|
-
`));if(s&&s!==
|
|
66
|
-
`));
|
|
67
|
-
${
|
|
68
|
-
${u.message}`)}let i=await
|
|
69
|
-
${u.message}`)}return
|
|
70
|
-
${
|
|
71
|
-
${c.message}`);let u=await
|
|
72
|
-
${u.message}`):
|
|
73
|
-
${s.message}`):
|
|
74
|
-
${
|
|
75
|
-
${n.message}`):
|
|
76
|
-
`+
|
|
77
|
-
${s.message}`);let i=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return l(i?"Pushed state branch":"Remote already up to date",i)},_m=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=qt(e);if(a(o))return o;let s=o.value,i=[Fo(),await Ko({repoRoot:e,stateBranchName:s}),await Pn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Jb({stateBranchRoot:t,stateBranchName:s}),await hu(t),n?await Qb({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(a(c))return d(c.message);r=r||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)}});import ii from"node:fs";import ad from"node:os";import Zb from"node:path";var eI,Fm,tI,nI,rI,Om,id,Bm,oI,ai,dd=h(()=>{"use strict";S();Qe();St();eI="epiq-sync.lock",Fm=600*1e3,tI=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}},nI=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},rI=e=>e&&(e.hostname!==ad.hostname()||nI(e.pid))?Date.now()-e.startedAt>Fm:!0,Om=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,id=e=>{try{return tI(ii.readFileSync(e,"utf8"))}catch{return null}},Bm=(e,t)=>{let n={pid:process.pid,hostname:ad.hostname(),startedAt:Date.now(),operation:t};try{return ii.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},oI=async({worktreeRoot:e,operation:t})=>{let n=await xa(e);if(a(n))return d(n.message);let r=Zb.join(n.value,eI),o=()=>{try{let c=id(r);c&&c.pid===process.pid&&ii.rmSync(r)}catch{}};if(Bm(r,t))return l("Acquired sync lock",{acquired:!0,release:o});let s=id(r);if(!rI(s))return l("Sync lock is held",{acquired:!1,heldBy:s});X.info(`Breaking an abandoned sync lock: ${s?Om(s):"unreadable lock file"}`);try{ii.rmSync(r,{force:!0})}catch{}if(Bm(r,t))return l("Acquired sync lock after breaking a stale one",{acquired:!0,release:o});let i=id(r);return l("Sync lock taken by another process",{acquired:!1,heldBy:i??{pid:-1,hostname:ad.hostname(),startedAt:Date.now(),operation:"unknown"}})},ai=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await oI({worktreeRoot:e,operation:t});if(a(r))return d(r.message);if(!r.value.acquired)return X.info(`Skipping ${t}: the state worktree is held by ${Om(r.value.heldBy)}`),l("State worktree is held by another process",null);let{release:o}=r.value;try{return l("Ran under the sync lock",await n())}finally{o()}}});import sI from"node:fs";var iI,aI,cd,Um,ld,di,ci=h(()=>{"use strict";S();zo();ri();Zn();et();Qe();Xo();od();sr();dd();iI=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=se("getRepoRootDir",await gt(e));if(a(n))return d(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=se("getStateBranchRoot",Ie({repoRoot:r}));if(a(o))return d(o.message);let s=o.value;logger.debug("[sync] state branch root",s),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let i=se("bootstrapStateBranchStorage",await _m({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(a(i))return d(i.message);logger.debug("[sync] bootstrap result",{bootstrapped:i.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let c=se("hasInProgressGitOperation(stateBranchRoot)",await Fs(s));if(a(c))return d(c.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:c.value}),c.value)return logger.info("[sync] state branch git operation in progress"),d("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let u=se("ensureStateBranchLayout",gu(r,s));return a(u)?d(u.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:i.value}),l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:i.value}))},aI=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=se("stageStateBranchOwnEventFile",await si({stateBranchRoot:t,eventFileName:n}));if(a(r))return d(r.message);let o=se("stageStateBranchMediaFiles",await Pm({stateBranchRoot:t}));if(a(o))return d(o.message);let s=se("stageStateBranchEventConfig",await Lm({stateBranchRoot:t}));if(a(s))return d(s.message);let i=[r.value,o.value,...s.value].filter(m=>m!==null);if(i.length===0)return l("Nothing to stage",{createdCommit:!1});let c=se("hasStagedChanges(after stage)",await iu(t,i));if(a(c))return d(c.message);if(logger.debug("[sync] state branch change check after stage result",{changed:c.value}),!c.value)return logger.info("[sync] no own event file changes to commit"),l("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let u=se("createStateBranchSyncCommit",await Dm({repoRoot:e,stateBranchRoot:t,pathspec:i}));return a(u)?d(u.message):(logger.debug("[sync] created sync commit",u.value),l("Committed own event file",{createdCommit:!0,commitSha:u.value}))},cd=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return ni(n),l(n,{...e,pulled:!1,pushed:!1,offline:!0})},Um=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),d("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}),d("Own event file must end with .jsonl");Lr();let n=se("ensureSyncReady",await iI({cwd:e,ensureUpstream:!0}));if(a(n))return Se(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=se("isDetachedHead(stateBranchRoot)",await au(o));if(a(i))return Se(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return Se("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,f=se("getStateBranch",qt(r));if(a(f))return Se(f.message);let y=f.value;logger.debug("[sync] resolved state branch",{stateBranch:y,stateBranchRoot:o});let x=se("flushPendingLogs",Ks(o,t));a(x)&&logger.error(`[sync] ${x.message}`);let R=se("commitOwnEventFileToStateBranch",await aI({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(a(R))return Se(R.message);c=R.value.createdCommit,u=R.value.commitSha;let A=se("hasRemote",await ln({repoRoot:o}));if(a(A))return Se(A.message);if(!A.value)return cd({repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,bootstrapped:s},"no remote");let w=se("pullBranchRebaseIfPresent",await Do({cwd:o,branch:y}));if(a(w))return Lo(w.message)?cd({repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,bootstrapped:s}):Se(w.message);m=w.value;let k=se("isAheadOfUpstream",await ou(o));if(a(k))return Se(k.message);if(c||s||k.value){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:o});let L=se("pushStateBranch",await Yo({stateBranchRoot:o,repoRoot:r}));if(a(L)&&nu(L.message)){let D=se("pullBranchRebaseIfPresent(retry)",await Do({cwd:o,branch:y}));if(a(D))return Se(D.message);m=m||D.value,L=se("pushStateBranch(retry)",await Yo({stateBranchRoot:o,repoRoot:r}))}if(a(L))return Lo(L.message)?cd({repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,bootstrapped:s}):Se(L.message);p=L.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let L=se("git rev-parse HEAD",await W({args:["rev-parse","HEAD"],cwd:o}));if(a(L))return Se(L.message);u=L.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return mr(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:s,offline:!1})},ld=async(e,t)=>{let n=wm(e);try{return await t()}finally{let r=Am(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},di=async e=>{let t=e.cwd??process.cwd(),n=await gt(t);if(a(n))return Se(n.message);let r=Ie({repoRoot:n.value});if(a(r))return Se(r.message);let o=r.value;if(!sI.existsSync(o))return Um(e);let s=await ai({worktreeRoot:o,operation:"sync",fn:()=>ld(o,()=>Um(e))});return a(s)?Se(s.message):s.value===null?l("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 Jt,li,dI,ud,jm,ui=h(()=>{"use strict";vm();ur();wt();Ce();ve();S();M();zo();ri();ci();Jt=null,li=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Jt,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),Jt)return logger.debug("[sync] syncAndReloadState joining existing promise"),Jt;logger.debug("[sync] syncAndReloadState creating promise"),Jt=dI();try{let e=await Jt;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:g().syncStatus?.status,statusMessageAfterResolve:g().syncStatus?.msg}),a(e)&&g().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),N({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),Jt||d(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),Jt=null}},dI=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=jm();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(Jt)return Jt;logger.debug("[sync] syncAndReloadState:start");let t=se("resolveActorId",oe());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),d("Unable to resolve event log path");N({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:g().syncStatus});let n=cr(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=se("syncEpiqWithRemote",await di({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(r),message:(a(r),r.message)}),a(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),N({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),Se(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value,i=ud(o);return a(i)?i:(N({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),l("Synced",!0))},ud=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=se("loadMergedEvents",Ct(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(t),message:(a(t),t.message),count:a(t)?void 0:t.value.events.length}),a(t))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:g().syncStatus}),d(`Unable to load events. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=jm();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:n.message,syncStatus:g().syncStatus}),n;let r=fm(),o=g().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:r,selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id,selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual}),!g().selectedNode?.isVirtual&&!g().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:t.value.events.length});let i=se("bootStateFromEventLog",Yt(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(i),message:(a(i),i.message)}),a(i))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:g().syncStatus}),d(`Unable to boot synced state. ${i.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),N({filters:o}),logger.debug("[sync] restoreNavigationAnchor:start");let s=se("restoreNavigationAnchor",hm(r));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(s),message:a(s)?s.message:"Navigation restored",selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id}),a(s)?(N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),s):l("Reloaded state from event log",null)},jm=()=>g().mode===b.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),N({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),d("Will not re-materialize if not in default mode, to not lose edit data"))});var Fr,$m,Wm,md,pd,Jo,fd,cI,Hm,lI,qm,mi=h(()=>{"use strict";S();ze();M();ui();Fr=3e3,$m=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Fr?null:t},Wm=0,pd=!1,Jo=!1,fd=()=>{if(pd)return!0;let e=Ye();return a(e)?!1:e.value.syncStatus.status==="syncing"},cI=()=>{let e=xe().autoSyncIntervalMs??1e4,t=Date.now()-Wm;return Math.max(0,e-t)},Hm=()=>{md||(md=setTimeout(async()=>{if(md=void 0,!!Nt()){if(fd()){Jo=!0;return}Jo=!1,await lI()}},cI()))},lI=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return d("Cannot auto-sync while peeking");if(!Nt())return d("Cannot auto-sync before state is initialized");if(fd())return Jo=!0,d("Sync already in progress");pd=!0,Wm=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await li()}finally{pd=!1,Jo&&Hm()}},qm=()=>{Nt()&&(Jo=!0,!fd()&&Hm())}});import Qo from"node:fs";import Zo from"node:path";import{z as Br}from"zod";var pi,uI,mI,pI,zm,Vm,Gm,Km,Ym,Xm,fI,fi,es,Or=h(()=>{"use strict";S();Ht();Ds();ie();pi="recent-projects.json",uI=20,mI=Br.object({projectId:Br.string().min(1),root:Br.string().min(1),lastOpenedAt:Br.number().finite()}),pI=Br.object({projects:Br.array(mI)}),zm=()=>Zo.join(an(),pi),Vm=e=>Zo.basename(e)||e,Gm=e=>{let t=Zo.resolve(e);try{return Qo.realpathSync(t)}catch{return t}},Km=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Ym=e=>{if(!Oo(e.root))return!1;let t=Mo(e.root);return!a(t)&&t.value===e.projectId},Xm=()=>{let e=zm();if(!Qo.existsSync(e))return l("No recent projects recorded",[]);let t;try{t=JSON.parse(Qo.readFileSync(e,"utf8"))}catch(r){return d(`Invalid ${pi}: ${r instanceof Error?r.message:String(r)}`)}let n=pI.safeParse(t);return n.success?l("Read recent projects",n.data.projects):d(`Invalid ${pi} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},fI=e=>{let t=zm();try{Qo.mkdirSync(Zo.dirname(t),{recursive:!0}),Qo.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
78
|
-
`,"utf8")}catch(n){return d(`Unable to write ${pi}: ${n instanceof Error?n.message:String(n)}`)}return l("Recorded recent project",e)},fi=({exclude:e}={})=>{let t=Xm();if(a(t))return t;let n=e===void 0?null:Gm(e);return l("Listed recent projects",t.value.filter(r=>n===null||Gm(r.root)!==n).filter(Ym).sort(Km))},es=({root:e,now:t=Date.now()})=>{let n=Zo.resolve(e),r=Mo(n);if(a(r))return d(r.message);let o=r.value,s=Xm(),i=a(s)?[]:s.value,c=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(u=>u.projectId!==o&&u.root!==n)].filter(Ym).sort(Km).slice(0,uI);return fI(c)}});var gi,Jm,Qm,Zm,ts=h(()=>{"use strict";S();Ht();ze();ie();gi=()=>{let e=xe(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},Jm=()=>{let e=Me(process.cwd());if(a(e))return!1;let t=pt(e.value);return jt(t)},Qm=e=>e===!0?"on":e===!1?"off":null,Zm=e=>e==="on"?!0:e==="off"?!1:null});var We,T,Xe=h(()=>{"use strict";We={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"},T={accent:We.cyan,accent2:We.magenta,primary:We.white,secondary:We.grayDark,secondary2:We.grayLight,gray:We.gray,green:We.green,yellow:We.yellow,red:We.red}});var C,Ur,hi=h(()=>{"use strict";Xe();C={red:We.red,yellow:We.yellow,green:We.green,blue:We.blue,magenta:We.magenta,cyan:We.cyan},Ur={urgent:C.red,critical:C.red,important:C.red,blocker:C.red,asap:C.red,immediate:C.red,fail:C.red,failure:C.red,broken:C.red,bug:C.red,error:C.red,incident:C.red,outage:C.red,production:C.red,crash:C.red,security:C.red,warning:C.yellow,warn:C.yellow,risky:C.yellow,risk:C.yellow,attention:C.yellow,pending:C.yellow,review:C.yellow,"needs-review":C.yellow,qa:C.yellow,testing:C.yellow,test:C.yellow,validate:C.yellow,verification:C.yellow,staging:C.yellow,check:C.yellow,"follow-up":C.yellow,followup:C.yellow,waiting:C.yellow,blocked:C.yellow,hold:C.yellow,done:C.green,complete:C.green,completed:C.green,success:C.green,ok:C.green,stable:C.green,resolved:C.green,fixed:C.green,closed:C.green,merged:C.green,released:C.green,deployed:C.green,approved:C.green,verified:C.green,working:C.green,healthy:C.green,pass:C.green,passing:C.green,info:C.blue,information:C.blue,note:C.blue,docs:C.blue,documentation:C.blue,doc:C.blue,guide:C.blue,help:C.blue,explanation:C.blue,detail:C.blue,details:C.blue,context:C.blue,design:C.blue,discussion:C.blue,proposal:C.blue,idea:C.blue,feature:C.magenta,enhancement:C.magenta,improvement:C.magenta,refactor:C.magenta,refactoring:C.magenta,cleanup:C.magenta,optimize:C.magenta,optimization:C.magenta,perf:C.magenta,performance:C.magenta,upgrade:C.magenta,migration:C.magenta,modernize:C.magenta,debt:C.magenta,todo:C.cyan,next:C.cyan,planned:C.cyan,plan:C.cyan,future:C.cyan,backlog:C.cyan,investigate:C.cyan,explore:C.cyan,prototype:C.cyan}});var gI,hI,Ln,Dn,vi,yi,ns=h(()=>{"use strict";ee();S();re();M();gI=e=>e.props.tags??[],hI=e=>e.props.assignees??[],Ln=e=>gI(e).map(t=>E.getTag(t)).filter(t=>!!t),Dn=e=>hI(e).map(t=>E.getContributor(t)).filter(t=>!!t),vi=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!F(n)?d("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Ln(n))},yi=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!F(n)?d("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",Dn(n))}});var I,pr=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 vI,yI,bI,II,xI,fr,ep,bi,Ii,tp,EI,gd,rs=h(()=>{"use strict";vI=/^(\d+)(h|d|w|mo|y)$/,yI=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,bI=({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},II=(e,t=new Date)=>{let n=e.match(vI);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}},xI=e=>{let t=e.match(yI);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return bI({year:c,month:u,day:m,hour:p,minute:f})?new Date(c,u-1,m,p,f):null},fr=e=>{let t=e.trim().toLowerCase();return II(t)??xI(t)},ep=/^(\d+)(s|m)?$/,bi=e=>{let t=e.trim().toLowerCase().match(ep);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Ii=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&ep.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},tp=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,EI=[{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}],gd=(e=EI)=>{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 RI,be,vt,we,SI,NI,vd,yd,op,gr,xi,hd,np,CI,wI,os,rp,AI,TI,bd,kI,Ae,yn=h(()=>{"use strict";mi();Or();S();ts();Bt();ee();re();M();hi();ns();pr();rs();RI=["BOARD","TICKET","SWIMLANE","COMMENT"],be={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},vt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},we={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},SI=[be.EDITOR,be.VIEW,be.USERNAME,be.AUTOSYNC,be.SYNC_DEBOUNCE_MS,be.ATTACHMENT_MAX_KB,be.LOG_LEVEL],NI=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[vt.TITLE,vt.DESCRIPTION];case"BOARD":case"SWIMLANE":return[vt.TITLE];case"COMMENT":return[vt.COMMENT];default:return[]}},vd=[String(Fr),"5000","15000","30000","60000"],yd=["250","500","1000"],op=["10s","20s","30s","45s"],gr=[I.EXIT,I.SYNC,I.HELP,I.EXPORT,I.CONFIG,I.YANK],xi=[I.NEW,I.EDIT,I.DELETE,I.MOVE],hd=[I.TAG,I.UNTAG,I.ASSIGN,I.UNASSIGN,I.CLOSE_ISSUE,I.RE_OPEN_ISSUE,I.EDIT,I.COMMENT],np=[I.FILTER,I.PEEK,I.REPLAY],CI={WORKSPACE:[...gr,...xi],BOARD:[...np,...gr,...xi],SWIMLANE:[...np,...gr,...xi],TICKET:[...gr,...xi,...hd],FIELD:[...gr,...hd],FIELD_LIST:[...gr,...hd],TEXT:[...gr],COMMENT:[I.EDIT,I.DELETE,I.YANK]},wI=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],os=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&F(n)),rp=e=>e.parentNodeId===me,AI=({selectedNode:e,breadCrumb:t})=>{let n=NI(e?.context);return os({breadCrumb:t,selectedNode:e})?n.includes(vt.DESCRIPTION)?n:[...n,vt.DESCRIPTION]:n},TI=({selectedNode:e,breadCrumb:t})=>{let n=os({breadCrumb:t,selectedNode:e});return n?[we.REF,we.TITLE,...n.props?.description?.trim()?[we.DESCRIPTION]:[],...Ln(n).length>0?[we.TAGS]:[],...Dn(n).length>0?[we.ASSIGNEES]:[]]:e?[we.REF,we.TITLE]:[]},bd=()=>{let e=fi({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},kI=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=gi();if(!r)return[I.HELP,I.CONFIG];if(!Jm())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&&RI.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?CI[u]:[]))],c=os({breadCrumb:n,selectedNode:e});return i.filter(u=>u===I.MOVE?!1:u===I.YANK?!!(c??e):u===I.EDIT?s||!!c:u===I.DELETE?s:u===I.UNTAG?!!(c&&Ln(c).length>0):u===I.UNASSIGN?!!(c&&Dn(c).length>0):u===I.RE_OPEN_ISSUE?!!(c&&rp(c)):u===I.CLOSE_ISSUE?!!(c&&!rp(c)):!0)},Ae=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=g())=>{let s=t.context??"WORKSPACE";return{[I.NONE]:kI({breadCrumb:o,readOnly:r,selectedNode:n}),[I.EXIT]:["confirm"],[I.EXPORT]:[],[I.SYNC]:[],[I.INIT]:[],[I.OPEN]:e===I.OPEN?bd():[],[I.HELP]:[],[I.PEEK]:[...gd(),"now","prev","next"],[I.REPLAY]:[...gd()],[I.EDIT]:AI({selectedNode:n,breadCrumb:o}),[I.YANK]:TI({selectedNode:n,breadCrumb:o}),[I.COMMENT]:[],[I.DELETE]:["confirm"],[I.RE_OPEN_ISSUE]:["confirm"],[I.CLOSE_ISSUE]:["confirm"],[I.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[I.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[I.TAG]:[...new Set([...Object.keys(Ur),...E.getExistingTags()])],[I.UNTAG]:[...vi()?.value?.map(({name:c})=>c)??[]],[I.UNASSIGN]:[...yi()?.value?.map(({name:c})=>c)??[]],[I.ASSIGN]:E.getExistingAssignees(),[I.NEW]:wI(s),[I.CONFIG]:[...SI]}[e]??[]}});var sp,ip=h(()=>{"use strict";sp=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{accessSync as MI,copyFileSync as PI,existsSync as Ei,mkdirSync as ap,readdirSync as dp,readFileSync as LI,renameSync as DI,rmSync as _I,statSync as cp,unlinkSync as FI,writeFileSync as BI}from"node:fs";import jr from"node:path";var Id,rt,Ri=h(()=>{"use strict";Id=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",rt={writeToFile:(e,t)=>{try{let n=jr.dirname(e);Ei(n)||ap(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);BI(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return LI(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=rt.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 Ei(e)&&cp(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await MI(e),!0}catch{return!1}},mkDir:e=>ap(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=jr.parse(t);for(;;){let r=jr.join(t,e);try{if(Ei(r)&&cp(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=jr.dirname(t)}return null},readFirstJSON(e){try{if(!rt.dirExists(e))return null;let t=dp(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=jr.join(e,t);return rt.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return rt.dirExists(e)?dp(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{FI(e)}catch(t){(!Id(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{_I(e,{recursive:!0,force:!0})}catch(t){(!Id(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(jr.dirname(t)),!n?.overwrite&&Ei(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{DI(e,t)}catch(r){if(Id(r)&&r.code==="EXDEV"){PI(e,t),this.rmFile(e);return}throw r}}}});import OI from"node:path";import{z as bn}from"zod";var UI,lp,jI,up,xd,Ed,$I,$r,mp,ot,ss,Qt=h(()=>{"use strict";zn();ie();S();Ri();UI={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},lp=bn.object({logLevel:bn.enum(["info","error","debug"]),preferredEditor:bn.string().optional(),userName:bn.string().optional(),userId:bn.string().optional(),autoSync:bn.boolean().nullable().optional(),autoSyncDebounceMs:bn.number().optional(),attachmentMaxKb:bn.number().optional(),viewMode:bn.enum(["dense","wide"]).optional()}).partial(),jI="config.json",up=an,xd=()=>OI.join(up(),jI),Ed=()=>{try{return rt.mkDir(up()),l(`Ensured ~/${Dt} exists`,null)}catch{return d(`Unable to create ~/${Dt}`)}},$I=e=>{let t;try{t=JSON.parse(e)}catch{return d(`Invalid ~/${Dt}/config.json JSON`)}let n=lp.safeParse(t??{});return n.success?l("Parsed config",n.data):d(`Invalid ~/${Dt}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},$r=()=>{let e=Ed();if(a(e))return d(e.message);let t=xd(),n=rt.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):$I(n)},mp=e=>{let t=Ed();if(a(t))return d(t.message);let n=lp.safeParse(e);if(!n.success)return d(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=xd();try{return rt.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
79
|
-
`),l("Config written",null)}catch{return d(`Unable to write ~/${Dt}/config.json`)}},ot=e=>{let t=$r();if(a(t))return d("Failed to read existing config");let n={...t.value,...e};return mp(n)},ss=()=>{let e=xd(),t=Ed();if(a(t))return d(`Unable to create ~/${Dt}`);if(!(rt.readFile(e)!==null)){let R=mp(UI);if(a(R))throw new Error(`Unable to create ~/${Dt}/config.json`)}let r=$r();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:c,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:f}=r.value,y=la({userId:i,userName:s});if(a(y))return d(y.message);let x=y.value??{userId:i,userName:s};return!x.userName||!x.userId?d(`User name or ID not configured in ~/${Dt}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,l("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:x.userName,userId:x.userId,autoSync:c??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))}});var pp,fp,Rd,gp=h(()=>{"use strict";pp="/media/",fp=e=>`${pp}${e}`,Rd=(e,t)=>`})`});import WI from"node:crypto";import Sd from"node:fs";import HI from"node:path";var In,Wr,qI,GI,zI,hp,Hr=h(()=>{"use strict";$t();S();ie();gp();In=500,Wr=(e,t)=>`${e}.${t}`,qI=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?l("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?l("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")))?l("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"))?l("Sniffed image type","webp"):d(`Unsupported image format. Allowed: ${Ll.join(", ")}`),GI=e=>WI.createHash("sha256").update(e).digest("hex"),zI=(e,t=In)=>{if(e.length===0)return d("Attachment is empty");if(e.length>t*1024)return d(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=qI(e);return a(n)?n:l("Validated attachment data",{hash:GI(e),ext:n.value,bytes:e.length})},hp=(e,t,n=In)=>{let r=zI(t,n);if(a(r))return r;let o=Us(e),s=HI.join(o,Wr(r.value.hash,r.value.ext));try{Sd.existsSync(s)||(Sd.mkdirSync(o,{recursive:!0}),Sd.writeFileSync(s,t))}catch(i){return d(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return l("Wrote attachment blob",r.value)}});import VI from"zod";var is,as,vp,Nd=h(()=>{"use strict";Qt();Hr();ve();S();pe();ze();M();is=50,as=5e3,vp=()=>{let e=ce().commandMeta.inputString,t=VI.coerce.number().int().min(is).max(as).safeParse(e);if(!t.success)return d(`Attachment size cap must be ${is}-${as} KB (default ${In})`);let n=ot({attachmentMaxKb:t.data});return a(n)?n:(xt({attachmentMaxKb:t.data}),N({mode:b.DEFAULT}),l(`Attachment size cap set to ${t.data} KB`,null))}});import yp from"chalk";var wd,bp,Cd,Ip,KI,YI,xp,XI,JI,ds,Te,Ep,Rp,Si,QI,ZI,Ni,yt=h(()=>{"use strict";hi();wd={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},bp=(e,t,n)=>Math.max(t,Math.min(n,e)),Cd=(e,t,n)=>e+(t-e)*n,Ip=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},KI=e=>e.toLowerCase().trim(),YI=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,c=s*(1-Math.abs(i%2-1)),u=0,m=0,p=0;i>=0&&i<1?(u=s,m=c):i>=1&&i<2?(u=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<5?(u=c,p=s):(u=s,p=c);let f=o-s/2;return[Math.round((u+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},xp=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,XI=(e,t,n)=>{let r=bp(n,0,1);return[Math.round(Cd(e[0],t[0],r)),Math.round(Cd(e[1],t[1],r)),Math.round(Cd(e[2],t[2],r))]},JI=(e,t,n)=>XI(e,t,n),ds=e=>{let t=Ip(e)%360,n=YI(t,wd.stringColor.saturation,wd.stringColor.lightness);return xp(n)},Te=(e,t=Ur)=>{let n=KI(e??"");return n&&t[n]?t[n]:ds(n)},Ep=e=>{let t=wd.gradient.stops,n=bp(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 JI(t[s],t[s+1],i)},Rp=e=>xp(Ep(e)),Si=e=>Ip(e.toLowerCase().trim())/4294967295,QI=e=>{let t=Si(e);return Ep(t)},ZI=e=>{let[t,n,r]=QI(e);return{normal:o=>yp.bgRgb(t,n,r).black(o),cursor:o=>yp.bgRgb(t,n,r).white.bold(o)}},Ni=e=>ZI(e).normal(` ${e} `)});var He,xn=h(()=>{"use strict";He=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null});import{createHash as ex}from"node:crypto";var tx,nx,Le,qr=h(()=>{"use strict";tx="0123456789ABCDEFGHJKMNPQRSTVWXYZ",nx=e=>{let t=ex("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+=tx[Number(n>>s&31n)]}return r},Le=(e,t)=>nx(`${e}:virtual:${t}`)});import Sp from"chalk";var fe,De,Ue,Np=h(()=>{"use strict";yt();Xe();fe=e=>Sp.dim(e),De=e=>Sp.hex(T.primary)(e),Ue=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(f=>f.startsWith(i))].sort((f,y)=>Si(f)-Si(y)).slice(0,r).map(f=>Ni(f)).join(" ");return p?`${fe(e)}${p}${fe(n)}`:""}});var _n,Ci=h(()=>{"use strict";_n={None:"none",Invalid:"invalid",Valid:"valid"}});import Ap from"chalk";var rx,Cp,he,te,G,zr,wp,wi,Ad,ox,Gr,sx,ix,ax,dx,cx,Tp,kp=h(()=>{"use strict";mi();ts();ip();Je();$t();S();re();ze();Nd();Hr();M();yt();xn();ns();qr();Np();pr();Ci();yn();rs();rx=["BOARD","TICKET","SWIMLANE"],Cp=()=>{let e=g().selectedNode;if(!e?.context)return G({message:fe("Missing target context")});if(rx.includes(e.context))return te();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===Le(t?.parentNodeId??"","comments"))return te()}return G({message:fe("Command not available in this context")})},he="<ENTER> to confirm",te=(e="",t=[])=>({message:fe(e),validity:_n.Valid,completionWordList:t}),G=({message:e,completionWordList:t=[]})=>({validity:_n.Invalid,message:e,completionWordList:t}),zr=e=>e.length===0,wp=(e,t)=>{let n=lt(g().breadCrumb,"BOARD");if(a(n))return G({message:De("Command is not applicable in this context")});let r=Pl(n.value.id);return a(r)?G({message:De(`Unable to ${t}: board id is not a valid ULID`)}):tp({date:e,horizonDate:r.value})?null:G({message:De(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},wi=e=>` ${Ap.hex("#000").bgHex(Te(e))(` ${e} `)} `,Ad=({modifier:e})=>{let t="confirm";return e===t?te(he):G({message:zr(e)?fe("if you are certain, enter ")+Ni(t):"",completionWordList:[t]})},ox=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?G({message:fe(n)}):te():G({message:zr(r)?t:"",completionWordList:[...e]}),Gr=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>zr(n)&&zr(r)?G({message:e,completionWordList:[]}):te(t??he),sx=({modifier:e,inputString:t})=>{let n=bd();return!zr(e)||!zr(t)?te(he):G({message:n.length?fe("number from the list, or a path"):fe("path to an epiq project"),completionWordList:n})},ix=({modifier:e,inputString:t})=>{let n=Ae(I.CONFIG);if(!n.includes(e))return G({message:Ue({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case be.EDITOR:{let r=[...sp];return t.trim()?r.includes(t.trim())?te(he):G({message:Ue({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):G({message:Ue({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case be.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?te(he):G({message:Ue({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case be.USERNAME:return t.trim()?te(he):G({message:De("Enter a user name. Saved in ")+Ap.bgBlack("~/.epiq-global/config.json")});case be.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?te(he):G({message:Ue({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case be.AUTOSYNC:{let r=["on","off"],o=xe().autoSync;if(!r.includes(t.trim())){let s=Qm(o);return G({message:Ue({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return te(he)}case be.ATTACHMENT_MAX_KB:{let r=xe().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<is||o>as){let s=Ue({prefix:" examples: ",wordList:yd,minLengthForHints:0,inputString:t});return G({message:De(`provide a size cap in KB (${is}-${as}). current: ${r??In} KB.`)+s,completionWordList:yd})}return te(he)}case be.SYNC_DEBOUNCE_MS:{let r=xe().autoSyncIntervalMs,o=$m(t);if(!t.trim()||o===null||o<Fr){let s=Ue({prefix:" examples: ",wordList:vd,minLengthForHints:0,inputString:t});return G({message:De(`provide duration above ${Fr}ms. current duration: ${r}ms.`)+s,completionWordList:vd})}return te(he)}default:return G({message:De("Unknown config option"),completionWordList:n})}},ax=({modifier:e,inputString:t})=>{let n=Ae(I.EDIT);if(!n.length)return G({message:De("Command not available in this context")});if(!n.includes(e)){let r=Ue({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return G({message:r||De("Unknown edit option"),completionWordList:n})}switch(e){case vt.COMMENT:return t.trim()?te(he):G({message:fe("write a comment...")});case vt.TITLE:return te(he);case vt.DESCRIPTION:{let{preferredEditor:r}=xe();return r?te(fe("<ENTER> to edit in ")+r):G({message:"No editor selected"})}default:return G({message:De("Unknown edit option"),completionWordList:n})}},dx=({modifier:e})=>{let t=Ae(I.YANK);return t.length?t.includes(e)?te(he+fe(" and copy to clipboard")):G({message:Ue({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):G({message:De("Nothing selected to copy from")})},cx={[I.EXPORT]:()=>te(he+fe(", and create export markdown file")),[I.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return te(he);let n={message:fe("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=fr(r);if(!r||!o)return G(n);let s=wp(o,"peek");return s||te(he)},[I.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Ii(e.modifier,e.inputString),r={message:fe("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=fr(t);if(!t||!o)return G(r);let s=wp(o,"replay");return s||(n&&bi(n)===null?G({message:De("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):te("<ENTER> to replay board history",n?op:[]))},[I.EXIT]:()=>te(he+fe(" and exit the application")),[I.INIT]:()=>te(he),[I.OPEN]:sx,[I.PALETTE]:()=>te(he),[I.FILTER]:e=>{if(e.modifier==="clear")return te(he);let t=s=>Ae(I.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return G({message:Ue({wordList:Ae(I.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Ae(I.FILTER)});let n=Object.values(g().tags).map(s=>s.name),r=Object.values(g().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?G({message:Ue({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):te():G({message:Ue({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[I.NONE]:e=>{let t=Ae(I.NONE);return G({message:Ue({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[I.NEW]:e=>ox({list:Ae(I.NEW),hint:Ue({wordList:Ae(I.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[I.HELP]:()=>te(he),[I.EDIT]:ax,[I.COMMENT]:e=>{let t=Gr({hint:fe(`write a comment (max ${4e3} char)...`),onOk:fe(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===_n.Invalid?t:e.inputString.length>4e3?te(De("max input exceeded")):t},[I.CONFIG]:ix,[I.YANK]:dx,[I.DELETE]:e=>{let t=Cp();return t.validity==="invalid"?t:Ad(e)},[I.CLOSE_ISSUE]:e=>Ad(e),[I.RE_OPEN_ISSUE]:e=>Ad(e),[I.MOVE]:e=>{let t=Cp();return t.validity==="invalid"?t:Gr({hint:Ue({prefix:"hey hacker! These commands are blocked for you... ",wordList:Ae(I.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[I.TAG]:e=>{let n=E.getExistingTags().slice(0,10).map(wi).join("");return Gr({hint:n.length?fe("create tag or reuse:")+n+fe(""):fe("create tag ...")})(e)},[I.UNTAG]:e=>{let t=vi();if(a(t))return G({message:De("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(wi).slice(0,10);return n.length?Gr({hint:fe(" ... ")+n.join("")})(e):G({message:De("Issue has no tags"),completionWordList:[]})},[I.ASSIGN]:e=>{let t=E.getExistingAssignees().map(wi).slice(0,10);return Gr({hint:fe("assignees... ")+t.join("")})(e)},[I.UNASSIGN]:e=>{let t=yi();if(a(t))return G({message:De("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(wi).slice(0,10);return n.length?Gr({hint:fe("remove assignee... ")+n.join("")})(e):G({message:De("Issue has no assignees"),completionWordList:[]})},[I.SYNC]:()=>te(he)},Tp=Object.fromEntries(Object.entries(cx).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]))});var Ai,Mp=h(()=>{"use strict";Ai=["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 lx,ux,mx,px,fx,Pp,Lp,Dp,_p=h(()=>{"use strict";S();M();Mp();lx=3,ux=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"]),mx=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},px=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=lx&&!ux.has(t)&&!/^\d+$/.test(t)),fx=e=>{let t=new Map;for(let s of mx(e))for(let i of px(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=Ai.filter(s=>!r.has(s));return[...n,...o]},Pp=Ai,Lp=-1,Dp=()=>{let e=Ye();if(a(e))return Ai;let t=e.value,n=t.eventLog.length;return n!==Lp&&(Pp=fx(t),Lp=n),Pp}});var Fp,Bp,Td=h(()=>{"use strict";ql();yn();pr();kp();_p();M();ve();Fp=e=>Object.values(I).includes(e),Bp=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:u}=Tp[n].validate(n,r,s),m=n!==I.PEEK&&n!==I.REPLAY,p=o==="command"||o==="modifier"?Ae(n):m?Dp():[],{mode:f}=g(),y=f===b.COMMAND_LINE?i??"":"",x=[...u,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:y,autoCompletion:t?Hl(e,x):{hint:"",hints:[],remainder:"",overlap:0}}}});var Op,gx,hx,vx,Up=h(()=>{"use strict";Td();yn();Op=e=>{let t=e.trimStart(),n=hx(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=vx(e),c=Fp(r)?r:null,u=c!==null,m=r!=="",p=c?Ae(c)??[]:[],f=c&&p.includes(o)?o:"",y="word";n.length===0||n.length===1&&!s?y="command":(n.length===1&&s||n.length===2&&!s)&&(y="modifier");let x=s?"":i,R=gx(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:y,inputToMatch:x,inputString:R}},gx=(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},hx=e=>e.trim()?e.trim().split(/\s+/):[],vx=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as GP}from"react";var Vr,kd,Kr,yx,jp,Zt,cs,Md,Pd,$p,Wp,Ti,Hp,ne,qp,Gp,zp,ce,ki,pe=h(()=>{"use strict";Td();Up();S();Ci();Vr=e=>e===kd||e===":",kd=" ",Kr={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:_n.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},yx=new Set,jp=()=>{for(let e of yx)e()},Zt=e=>{let n=e(Kr),r=Op(n.value),o=n.cursorPosition===n.value.length;Kr={...n,commandMeta:Bp(r,o)},jp()},cs=({message:e,status:t})=>{let n=structuredClone(Kr);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Kr=n,jp(),l(e,null)},Md=e=>{Zt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Pd=e=>{Zt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Vr(n[o-1]);)o--;for(;o>0&&!Vr(n[o-1]);)o--}else{for(;o<n.length&&!Vr(n[o]);)o++;for(;o<n.length&&Vr(n[o]);)o++}return{...t,cursorPosition:o}})},$p=()=>{Zt(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}})},Wp=()=>{Zt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Vr(t[r-1]);)r--;for(;r>0&&!Vr(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Ti=e=>{Zt(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},Hp=()=>{Zt(e=>({...e,commandIsPending:!0}))},ne=e=>{Zt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},qp=({addToHistory:e=!0})=>{Zt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Gp=()=>{Zt(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}})},zp=()=>{Zt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ce=()=>Kr,ki=()=>{let[e,...t]=Kr.value.split(kd);return t.join(kd).trim()}});var B,Xn=h(()=>{"use strict";ve();_l();M();pe();ze();B={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"}});var Vp,O,Ld=h(()=>{"use strict";M();pr();Vp=e=>{let{context:t}=g().contextNode;if(!t)return O.None;switch(e){case I.EXIT:return O.Exit;case I.EXPORT:return O.Export;case I.INIT:return O.Init;case I.OPEN:return O.OpenProject;case I.DELETE:return O.Delete;case I.EDIT:return O.Edit;case I.COMMENT:return O.Comment;case I.HELP:return O.ViewHelp;case I.RE_OPEN_ISSUE:return O.ReopenIssue;case I.CLOSE_ISSUE:return O.CloseIssue;case I.TAG:return O.TagTicket;case I.UNTAG:return O.UntagTicket;case I.ASSIGN:return O.AssignUserToTicket;case I.UNASSIGN:return O.UnassignUserFromTicket;case I.NEW:return O.NewItem;case I.FILTER:return O.Filter;case I.MOVE:return O.Move;case I.PEEK:return O.Peek;case I.REPLAY:return O.Replay;case I.CONFIG:return O.Config;case I.YANK:return O.Yank;case I.SYNC:return O.Sync;default:return O.None}},O={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 Kp}from"ink";import Yp,{useEffect as Xp,useState as bx}from"react";var Jp,it,Yr=h(()=>{"use strict";M();Xe();Jp={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},it=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=at(),r=Jp[n]??Jp.default,[o,s]=bx(0);if(Xp(()=>{s(0)},[r]),Xp(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return Yp.createElement(Kp,null,t);let i=r[o]??r[0]??t;return Yp.createElement(Kp,{color:T.accent,dimColor:o===1},i)}});import{Box as Dd,Text as Ix}from"ink";import Mi from"react";var xx,Fn,ls=h(()=>{"use strict";Xe();xx=(e,t,n,r)=>{let o=u=>Math.max(1,e[u]??1),s=n,i=n+1,c=o(n);for(;i<t&&c+o(i)<=r;)c+=o(i),i++;for(;s>0&&c+o(s-1)<=r;)s--,c+=o(s);return{start:s,end:i}},Fn=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),c=Math.max(1,Math.ceil(r)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(1,Math.floor(i/c)),p=Math.max(0,e.length-m),{start:f,end:y}=o?xx(o,e.length,u,i):s?{start:Math.min(p,Math.max(0,u-m+1)),end:Math.min(p,Math.max(0,u-m+1))+m}:{start:Math.min(p,Math.floor(u/m)*m),end:Math.min(p,Math.floor(u/m)*m)+m},x=Math.max(1,y-f),R=e.slice(f,y),A=e.length>x,w=i,k=A?Math.max(1,Math.floor(x/e.length*w)):w,L=Math.max(0,w-k),D=Math.max(1,e.length-x),U=A?Math.floor(f/D*L):0;return Mi.createElement(Dd,{flexDirection:"row",height:i,width:"100%"},Mi.createElement(Dd,{flexDirection:"column",flexGrow:1,height:i},R),Mi.createElement(Dd,{flexDirection:"column",width:1,height:w},Array.from({length:w}).map((de,wn)=>Mi.createElement(Ix,{key:wn,color:A&&wn>=U&&wn<U+k?T.accent:T.secondary},A?"\u2502":" "))))}});var Qp,_d,Ex,Pi,Fd=h(()=>{"use strict";M();Ex=()=>{let{eventLog:e=[]}=g();if(_d&&Qp===e)return _d;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Qp=e,_d=t,t},Pi=e=>Ex().has(e)});import{Text as Rx}from"ink";import Sx from"react";var Nx,Cx,Xr,Li=h(()=>{"use strict";hi();yt();re();Fd();mt();Nx=e=>e.toLowerCase().trim(),Cx=(e,t=Ur)=>{let n=Nx(e);return t[n]?t[n]:ds(n)},Xr=({id:e,isSelected:t,maxWidth:n})=>{let r=E.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:Jn(o,n);return Sx.createElement(Rx,{underline:t,color:Cx(o)},"@"+s,Pi(e)?"":"\u2197")}});import{Text as wx}from"ink";import Ax from"react";var Di,Bd=h(()=>{"use strict";re();Xe();yt();mt();Di=({id:e,isSelected:t,maxWidth:n})=>{let r=E.getTag(e);if(!r)return;let o=n===void 0?r.name:Jn(r.name,n);return Ax.createElement(wx,{underline:t,backgroundColor:Te(r.name),color:T.secondary}," "+o+" ")}});import{useEffect as Tx,useState as kx}from"react";var Mx,Zp,_i,us,Px,Lx,Jr,Fi=h(()=>{"use strict";yt();Mx=80,Zp=1400,_i=new Set,us=null,Px=e=>(_i.add(e),us||(us=setInterval(()=>{for(let t of _i)t()},Mx)),()=>{_i.delete(e),_i.size===0&&us&&(clearInterval(us),us=null)}),Lx=()=>{let e=Date.now()%Zp/Zp;return e<.5?e*2:(1-e)*2},Jr=e=>{let[,t]=kx(0);return Tx(()=>{if(e)return Px(()=>t(n=>n+1))},[e]),Rp(Lx())}});import{Box as Qr,Text as Zr}from"ink";import dt from"react";var Dx,ef,_x,Fx,tf,nf=h(()=>{"use strict";re();Xe();mt();Fd();tt();ns();Li();Bd();Fi();Dx=(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),Jn(e.slice(o).trim(),n)]},ef=3,_x=2,Fx=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let i=e.length-o-1,c=i>0?String(i).length+1:0;if(r+s.width+c>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},tf=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Jr(r),s=e-4,i=s-7-1,[c,u]=Dx(le(t.title),i,s),m=u?null:Jn(le(t.props.description),s)||null,p=Ln(t),f=Dn(t).map(k=>({...k,name:k.name})),y=Math.max(1,s-ef),x=E.getCommentsByIssue(t.id),R=x.length?String(x.length).length+2+1:0,{shown:A,hidden:w}=Fx([...p.map(k=>({id:k.id,isTag:!0,width:Math.min(k.name.length,y)+ef})),...f.map(k=>({id:k.id,isTag:!1,width:Math.min(k.name.length,y)+_x+(Pi(k.id)?0:1)}))],s-R);return dt.createElement(Qr,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?T.accent:T.secondary,justifyContent:"space-between"},dt.createElement(Qr,{paddingLeft:1,paddingRight:1,flexDirection:"column"},dt.createElement(Qr,{justifyContent:"space-between"},dt.createElement(Zr,{color:T.primary},c),dt.createElement(Zr,{color:T.secondary2,dimColor:!0},j(t.id))),u&&dt.createElement(Zr,{color:T.primary},u),m&&dt.createElement(Zr,{color:T.secondary2,dimColor:!0},m)),dt.createElement(Qr,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},dt.createElement(Qr,{flexDirection:"row"},A.map(k=>dt.createElement(Qr,{paddingRight:1,key:k.id},k.isTag?dt.createElement(Di,{id:k.id,maxWidth:y}):dt.createElement(Xr,{id:k.id,maxWidth:y}))),w>0&&dt.createElement(Zr,{color:T.secondary2,dimColor:!0},"+",w)),x.length>0&&dt.createElement(Zr,{color:T.accent},"[",x.length,"]")))}});import{Box as hr,Text as ms}from"ink";import bt from"react";var Bx,rf,of=h(()=>{"use strict";ve();re();Xe();yt();Yr();Fi();Bx=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,rf=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let c=Jr(s),u=(r.props.tags??[]).map(de=>E.getTag(de)).filter(de=>!!de),m=(r.props.assignees??[]).map(de=>E.getContributor(de)).map(de=>de&&{...de,name:de.name}).filter(de=>!!de),p=1,f=u.length*(1+p),y=m.length*(2+p),x=u.map(de=>bt.createElement(hr,{key:de.id,paddingRight:p},bt.createElement(ms,{color:Te(de.name)},"\u25A0"))),R=m.map(de=>bt.createElement(hr,{key:de.id,paddingRight:p},bt.createElement(ms,{color:ds(de.name)},"@"+de.name.at(0)))),A=s?c:o?T.accent:i===b.MOVE?T.secondary:T.primary,w=E.getCommentsByIssue(r.id),k=w.length?String(w.length).length+2+p:0,L=w.length?bt.createElement(hr,{paddingRight:p},bt.createElement(ms,{color:T.accent},"[",w.length,"]")):null,D=f+y+k,U=Math.max(1,n-t-D-(D>0?1:0));return bt.createElement(hr,{justifyContent:"space-between"},bt.createElement(hr,null,bt.createElement(hr,{width:t},o?bt.createElement(it,{isSelected:!0}):bt.createElement(ms,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),bt.createElement(ms,{wrap:"truncate",color:A},Bx(r.title,U))),bt.createElement(hr,null,x,R,L))}});import Ox from"chalk";import{Box as Od,Text as Ux}from"ink";import en from"react";var jx,sf,af=h(()=>{"use strict";ee();M();Xe();Yr();ls();nf();of();Fi();jx=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:m}=at(),p=u[e.id]??[],f=m?new Set(m.flashNodeIds):null,y=f?.has(e.id)??!1,x=Jr(y),R=`${e.title} ${Ox.hex(T.secondary2).dim("("+p.length+")")}`,A=3,w=o?1:5,k=s&&i===-1,L=n-3-(o?1:0)-(k?2:0),D=Math.max(2,String(p.length).length+1),U=r-A-1,de=en.createElement(Od,{borderStyle:"round",borderColor:T.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},en.createElement(it,{isSelected:t}),en.createElement(Ux,{bold:!0,color:y?x:t?T.accent:T.primary},R," ",e.readonly?"\u{1F512}":"")),wn=(on,bo)=>{let Io=s&&i===bo;if(!F(on))return null;let xo=f?.has(on.id)??!1;return o?en.createElement(rf,{key:on.id,index:bo,labelWidth:D,width:L,ticket:on,isSelected:Io,isFlashing:xo,mode:c}):en.createElement(tf,{key:on.id,width:L,ticket:on,isSelected:Io,isFlashing:xo})};return en.createElement(Od,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?T.accent:T.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},de,en.createElement(Od,null,p.length>0&&en.createElement(Fn,{selectedIndex:i,height:U,itemHeight:w},p.map(wn)),k&&en.createElement(it,{isSelected:!0})))},sf=en.memo(jx)});var df,cf,Ud=h(()=>{"use strict";tr();df=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},cf=(e,t,n)=>Pe.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0})});var to,Bi=h(()=>{"use strict";to=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 no,Text as En}from"ink";import qe,{useEffect as $x,useMemo as Wx,useRef as Hx}from"react";import{decodeTime as lf}from"ulid";function mf({ticket:e,width:t,height:n}){let r=Wx(()=>Gx(e),[e]),o=Hx([]);$x(()=>(uf(o.current),o.current=Vx(e,r),()=>{uf(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=at(),c=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?qe.createElement(no,{flexDirection:"column",width:t,height:n,padding:1},qe.createElement(En,{color:T.primary},"No attachments yet."),qe.createElement(no,{paddingTop:1},qe.createElement(En,{color:T.primary},"Attach images from the browser GUI"),qe.createElement(En,{color:T.accent}," epiq gui "),qe.createElement(En,{color:T.primary},"by dropping or pasting them."))):qe.createElement(no,{flexDirection:"column",width:t,height:n},qe.createElement(no,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:T.secondary,borderStyle:"single",paddingBottom:1},qe.createElement(En,{color:T.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),qe.createElement(Fn,{height:c,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,y=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return qe.createElement(no,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},qe.createElement(En,{color:T.accent},f?"\u276F ":" "),qe.createElement(no,{paddingLeft:1},qe.createElement(En,{color:T.secondary2},`#${p+1} `),qe.createElement(En,{color:f?T.accent:T.primary},y),qe.createElement(En,{color:T.secondary2}," "+Kx(m.bytes)+" "+to(Ge(m.id)))))})))}var qx,Gx,uf,zx,Vx,Kx,pf=h(()=>{"use strict";ht();Je();Bi();ee();S();re();tr();M();Xe();qr();ls();qx=e=>Le(e,"attachments"),Gx=e=>E.getAttachmentsByIssue(e.id).sort((t,n)=>lf(t.id)-lf(n.id)),uf=e=>{for(let t of e)E.deleteNode(t.id)},zx=(e,t,n)=>Pe.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),Vx=(e,t)=>{let n=E.getNode(qx(e.id));if(!n||!ut(n))return[];let r=t.map((o,s)=>zx(o,s,n.id)).map(o=>E.createNode(o)).filter(jt).map(({value:o})=>o).filter(ut);return t.length>0&&g().selectedIndex<0&&$.navigate({contextNode:n,selectedIndex:0}),r},Kx=e=>`${Math.max(1,Math.round(e/1024))} KB`});var gf,jd,ff,$d,hf,vf,Yx,yf,Xx,Wd,bf=h(()=>{"use strict";gf=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,jd=e=>e.replace(gf,""),ff=e=>e==="additions"||e==="deletions",$d=e=>{let t=gf.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"||!ff(r.side)||!ff(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r},hf=/```\n([\s\S]*?)\n?```\s*$/,vf=e=>hf.exec(e)?.[1]??null,Yx=/`[^`\n]+`[^\n]*\n?$/,yf=e=>jd(e).replace(hf,"").replace(Yx,"").trim(),Xx=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})`},Wd=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${Xx(e)}`});var Jx,ps,Qx,Zx,eE,tE,xf,Hd,Ef,If,Rf,qd=h(()=>{"use strict";bf();Jx=(e,t)=>{let n=Math.max(1,Math.floor(t)),r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[""];let o=[],s="";for(let i of r){let c=i;for(;c.length>n;)s&&(o.push(s),s=""),o.push(c.slice(0,n)),c=c.slice(n);s?s.length+1+c.length<=n?s=`${s} ${c}`:(o.push(s),s=c):s=c}return s&&o.push(s),o},ps=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)},Qx=/!\[([^\]]*)\]\([^)]*\)/g,Zx=e=>e.replace(Qx,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),eE=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),tE=4,xf=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(tE)),Hd=e=>{let t=!1;return e.map(xf).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=$d(n);if(r)return{kind:"caption",text:Wd(r)};let o=Zx(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:ps(s[1]??"")}:{kind:"text",spans:ps(o)}})},Ef=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],If=(e,t)=>{let n=[];for(let r of Hd(e))if(r.kind!=="fence"){if(r.kind==="blank"){n.length>0&&n[n.length-1]?.kind!=="blank"&&n.push(r);continue}if(r.kind==="code"){for(let o of Ef(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of Jx(eE(r.spans),t))n.push({kind:r.kind,spans:ps(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},Rf=(e,t)=>{let n=$d(e),r=n?vf(e):null;if(!n||r===null)return If(jd(e).split(`
|
|
80
|
-
`),t)
|
|
81
|
-
`)
|
|
82
|
-
`),t),{kind:"blank"}]:[],{kind:"caption",text:Wd(n)},...s.flatMap((u,m)=>Ef(u,Math.max(1,t-c)).map((p,f)=>({kind:"code",text:p,number:i===void 0||f>0?void 0:i+m})))]}});import{Box as Sf,Text as vr}from"ink";import At from"react";var Nf,Gd,Cf,zd=h(()=>{"use strict";Xe();Nf=({spans:e,bold:t,wrap:n})=>At.createElement(vr,{color:T.primary,bold:t,wrap:n},e.map((r,o)=>r.code?At.createElement(vr,{key:o,color:T.yellow},r.text):At.createElement(vr,{key:o},r.text))),Gd=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return At.createElement(vr,null," ");case"fence":return At.createElement(vr,{color:T.secondary2},"```");case"caption":return At.createElement(vr,{color:T.accent,wrap:r},e.text);case"heading":return At.createElement(Nf,{spans:e.spans,bold:!0,wrap:r});case"text":return At.createElement(Nf,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return At.createElement(vr,{backgroundColor:T.secondary,color:T.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},Cf=({lines:e,width:t})=>{let n=e.flatMap(o=>o.kind==="code"&&o.number!==void 0?[o.number]:[]),r=n.length>0?String(Math.max(...n)).length+3:0;return At.createElement(Sf,{flexDirection:"column"},e.map((o,s)=>At.createElement(Sf,{key:s},At.createElement(Gd,{line:o,width:t,gutter:r}))))}});import{Box as Bn,Text as On}from"ink";import ke,{useEffect as nE,useMemo as wf,useRef as rE}from"react";import{decodeTime as Af}from"ulid";function kf({ticket:e,width:t,height:n}){let r=wf(()=>iE(e),[e]),o=rE([]);nE(()=>(Tf(o.current),o.current=aE(e,r),()=>{Tf(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=at(),c=Math.max(1,n-4),u=Math.max(20,t-8),m=wf(()=>r.map(f=>{let y=Rf(f.md,u);return y.length>0?y:[{kind:"blank"}]}),[r,u]),p=m.map(f=>f.length+oE);return r.length===0?ke.createElement(Bn,{flexDirection:"column",width:t,height:n,padding:1},ke.createElement(On,{color:T.primary},"No comments yet."),ke.createElement(Bn,{paddingTop:1},ke.createElement(On,{color:T.primary},"Use"),ke.createElement(On,{color:T.accent}," :comment "),ke.createElement(On,{color:T.primary},"to add the first one."))):ke.createElement(Bn,{flexDirection:"column",width:t,height:n},ke.createElement(Bn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:T.secondary,borderStyle:"single",paddingBottom:1},ke.createElement(On,{color:T.secondary2},"Comments (",r.length,") ")),ke.createElement(Fn,{height:c,itemHeights:p,selectedIndex:s},r.map((f,y)=>{let x=y===s;return ke.createElement(Bn,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:T.secondary,borderStyle:"single"},ke.createElement(Bn,{flexDirection:"row",paddingBottom:1},ke.createElement(On,{color:T.accent},x?"\u276F ":" "),ke.createElement(Bn,{paddingLeft:1},ke.createElement(On,{color:T.secondary2},`#${y+1} `),ke.createElement(Xr,{id:f.authorId}),ke.createElement(On,{color:T.secondary2}," "+to(Ge(f.id))))),ke.createElement(Bn,{paddingLeft:3,paddingBottom:1},ke.createElement(Cf,{lines:m[y]??[],width:u})))})))}var oE,sE,iE,Tf,aE,Mf=h(()=>{"use strict";ht();Je();Bi();ee();S();re();M();Xe();qr();Li();ls();Ud();qd();zd();oE=4,sE=e=>Le(e,"comments"),iE=e=>E.getCommentsByIssue(e.id).sort((t,n)=>Af(t.id)-Af(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),Tf=e=>{for(let t of e)E.deleteNode(t.id)},aE=(e,t)=>{let n=E.getNode(sE(e.id));if(!n||!ut(n))return[];let r=t.map((o,s)=>cf(o,s,n.id)).map(E.createNode).filter(jt).map(({value:o})=>o).filter(Ao);return t.length>0&&g().selectedIndex<0&&$.navigate({contextNode:n,selectedIndex:0}),r}});import{Box as Oi,Text as dE}from"ink";import Rn from"react";var Pf,Lf=h(()=>{"use strict";ee();re();Mr();M();Xe();Li();Yr();Bd();Pf=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=at(),{title:o}=t,s=t.parentNodeId?E.getNode(t.parentNodeId):void 0,i=s&&F(s)?o===ge.ASSIGNEES?s.props.assignees??[]:o===ge.TAGS?(s.props.tags??[]).filter(c=>E.getTag(c)):[]:[];return Rn.createElement(Oi,{alignItems:"center",paddingTop:1},Rn.createElement(Oi,{minWidth:12},Rn.createElement(it,{isSelected:n}),Rn.createElement(dE,{color:n?T.accent:T.secondary2},o,":")),Rn.createElement(Oi,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let m=r.id===t.id&&u===e;return Rn.createElement(Oi,{key:`${o}-${c}`,paddingRight:2,minHeight:1},Rn.createElement(it,{isSelected:m}),o===ge.ASSIGNEES?Rn.createElement(Xr,{isSelected:m,id:c}):o===ge.TAGS?Rn.createElement(Di,{isSelected:m,id:c}):null)})))}});var Vd,Df,Kd,Yd=h(()=>{"use strict";Vd=e=>Math.max(5,String(Math.max(e,1)).length+3),Df=(e,t)=>Math.max(0,e-6-Vd(t)),Kd=(e,t=0)=>Math.max(1,e-5-2*t)});import{Box as ro,Text as Xd}from"ink";import Tt,{useEffect as cE,useMemo as Jd}from"react";var lE,_f,Qd,Ff,uE,Zd,Bf=h(()=>{"use strict";re();S();tr();M();Xe();mt();Yd();Yr();ls();zd();qd();wr();lE="\u2029",_f=(e,t)=>`${e}::inline-line::${t}`,Qd=new Map,Ff=e=>{let t=Qd.get(e)??[];Qd.delete(e);for(let n of t)E.deleteNode(n)},uE=(e,t)=>{Ff(e);let n=[];t.forEach((r,o)=>{let s=Et(BigInt(o+1));if(!jt(s))return;let i=E.createNode(Pe.text({id:_f(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));jt(i)&&n.push(i.value.id)}),Qd.set(e,n)},Zd=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=at(),u=Jd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Jd(()=>u.join("\0"),[u]);cE(()=>(uE(e,u),()=>{Ff(e)}),[e,m]);let p=Vd(u.length),f=Df(s,u.length),x=Jd(()=>Hd(u).map(R=>{if(R.kind==="code"||R.kind==="caption")return{...R,text:ga(R.text,f)};if(R.kind==="text"||R.kind==="heading"){let A=R.spans.map(w=>w.code?`\`${w.text}\``:w.text).join("");return{...R,spans:ps(ga(A,f))}}return R}),[u,f]).map((R,A)=>{let w=c.id===e&&i===A;return Tt.createElement(ro,{key:_f(e,A)},Tt.createElement(ro,{flexShrink:0},Tt.createElement(Xd,{color:w?T.primary:T.secondary2,dimColor:!w},`${A+1} `.padStart(p,"\xA0"))),R.kind==="blank"?Tt.createElement(Xd,{backgroundColor:w?"gray":void 0},lE):Tt.createElement(ro,null,Tt.createElement(Gd,{line:R,width:R.kind==="code"?f:0,wrap:"truncate-end"})))});return Tt.createElement(ro,{flexDirection:"column",paddingTop:1},Tt.createElement(ro,null,Tt.createElement(it,{isSelected:o}),Tt.createElement(Xd,{color:o?T.accent:T.secondary2},t)),Tt.createElement(ro,{flexDirection:"row",borderStyle:"round",borderColor:T.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},Tt.createElement(Fn,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},x)))}});import{Box as yr,Text as ec}from"ink";import _e,{useMemo as fs}from"react";var mE,pE,fE,gE,Of,Uf=h(()=>{"use strict";ee();re();M();Xe();Ud();qr();pf();Mf();Yr();Lf();Bf();Yd();mE=e=>Le(e,"description"),pE=e=>Le(e,"comments"),fE=e=>Le(e,"history"),gE=e=>Le(e,"attachments"),Of=({ticket:e,height:t})=>{let n=fs(()=>df(e),[e]),{selectedIndex:r,contextNode:o}=at(),s=process.stdout.columns||120,i=fs(()=>mE(e.id),[e.id]),c=fs(()=>pE(e.id),[e.id]),u=fs(()=>fE(e.id),[e.id]),m=fs(()=>gE(e.id),[e.id]),p=E.getAttachmentsByIssue(e.id).length,f=o.id===e.id,y=o.id===c||o.parentNodeId===c,x=o.id===u||o.parentNodeId===u,R=o.id===m||o.parentNodeId===m,A=ae(e.id);if(y){let U=t-3;return _e.createElement(yr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},_e.createElement(kf,{ticket:e,width:s,height:U}))}if(R){let U=t-3;return _e.createElement(yr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},_e.createElement(mf,{ticket:e,width:s,height:U}))}if(x){let D=E.getNode(u),U=D&&ut(D)?D.props.value??"":"",de=Kd(t);return _e.createElement(yr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},D?_e.createElement(Zd,{id:D.id,label:"Event log",text:U,selected:!1,maxWidth:s,rows:de}):null)}let w=A.reduce((D,U)=>wo(U)||U.id===c||U.id===m||U.id===u?D+1:D,0),k=Kd(t,w),L=(D,U)=>D.id===i?_e.createElement(Zd,{key:D.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:U,maxWidth:s,rows:k}):wo(D)?_e.createElement(Pf,{key:D.id,parent:D,selected:U,selectedIndex:r}):D.id===c?_e.createElement(yr,{key:D.id,paddingTop:1},_e.createElement(it,{isSelected:U}),_e.createElement(ec,{backgroundColor:T.secondary,color:U?T.accent:T.primary},` Comments (${n}) \u203A\u203A `)):D.id===m?_e.createElement(yr,{key:D.id,paddingTop:1},_e.createElement(it,{isSelected:U}),_e.createElement(ec,{backgroundColor:T.secondary,color:U?T.accent:T.primary},` Attachments (${p}) \u203A\u203A `)):D.id===u?_e.createElement(yr,{key:D.id,paddingTop:1},_e.createElement(it,{isSelected:U}),_e.createElement(ec,{backgroundColor:T.secondary,color:U?T.accent:T.primary}," History \u203A\u203A ")):null;return _e.createElement(yr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},A.map((D,U)=>L(D,f&&r===U)))}});import{Box as hE}from"ink";import Ui from"react";var vE,jf,$f=h(()=>{"use strict";ee();af();Uf();vE=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let u=t.context,m=u===Y.TICKET||u===Y.FIELD_LIST||u===Y.FIELD,p=u===Y.BOARD||u===Y.SWIMLANE,f=u===Y.TICKET?t:r.find(w=>w.context===Y.TICKET),y=Math.floor(c/3),x=Math.floor(c/Math.max(e.length,1)),R=Math.min(x,y),A=s==="dense";return Ui.createElement(hE,{flexDirection:"row",height:i},p&&e.map((w,k)=>{let L=t.id===w.id,D=L?n:-1,U=t.context===Y.BOARD&&n===k;return Ui.createElement(sf,{key:w.id,height:i,width:R,swimlane:w,isSelected:U,isDense:A,isFocused:L,listSelectedIndex:D,mode:o})}),m&&f&&Ui.createElement(Of,{height:i,ticket:f}))},jf=Ui.memo(vE)});import Wf from"node:fs";import yE from"node:path";import bE from"react";import{render as IE}from"ink";import{Writable as xE}from"node:stream";var gs,EE,RE,SE,NE,Hf,qf=h(()=>{"use strict";$f();ee();S();M();ie();ze();gs=e=>String(e).padStart(2,"0"),EE=e=>{let t=e.getUTCFullYear(),n=gs(e.getUTCMonth()+1),r=gs(e.getUTCDate()),o=gs(e.getUTCHours()),s=gs(e.getUTCMinutes()),i=gs(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},RE=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",SE=async(e,{width:t,height:n})=>{let r="",o=new xE({write(i,c,u){let m=NE(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=IE(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},NE=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Hf=async()=>{let{viewMode:e}=xe(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=g(),i=r.find(k=>k.context==="BOARD");if(!i)return d("No board found to export");let c=120,u=40,m=await SE(bE.createElement(jf,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(k=>k!==void 0&&Kn(k)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:u});if(!m)return d("Failed to render board export");let p=js(process.cwd());if(a(p))return d("Unable to export, epiq root not found");let f=new Date,y=EE(f),x=`board_${RE(i.title)}_${y}.md`,R=vu(p.value);Wf.mkdirSync(R,{recursive:!0});let A=yE.join(R,x),w=`# Board - ${i.title}
|
|
51
|
+
`,"utf8"),o.push(`${r} (${p.length})`)}catch{continue}}return o},LE=(e,t)=>{let n=new Set(lr(t));return lr(e).filter(o=>!n.has(o))},PE=(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(`
|
|
52
|
+
`),Lf=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let o=await Le({args:["show",`HEAD:${t}`],cwd:e});if(o.exitCode!==0)return d("No committed log to compare against",void 0);let r=LE(o.stdout,n);return r.length>0?l(PE(t,r,lr(o.stdout).length)):d("Event log only grew",void 0)}});import On from"node:fs";import Fn from"node:path";var DE,Df,Pf,OE,hc,Ts,FE,_E,to,BE,$E,jE,UE,ea,Of,Ff,_f,ks,Bf,Ms=g(()=>{"use strict";To();w();fc();$t();wi();Cn();gc();rt();Ke();DE="[epiq:init-repo]",Df=async e=>{let t=await Le({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 l(["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(`
|
|
53
|
+
`));ce.info("Creating initial commit");let o=await W({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(a(o))return l(o.message);let r=await W({args:["commit-tree",o.value.stdout.trim(),"-m",DE],cwd:e});if(a(r))return l(r.message);let s=await W({args:["update-ref","HEAD",r.value.stdout.trim()],cwd:e});return a(s)?l(s.message):d("Created initial commit",!0)},Pf=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",OE=async e=>{let t=await Ti(e);if(a(t))return l(t.message);let n=await zm(e);return a(n)?l(n.message):d("Built sync commit message",`[sync|branch:${Pf(t.value)}:sha:${Pf(n.value)}]`)},hc=async({repoRoot:e,stateBranchName:t})=>{ce.info(`Creating ${t}`);let n=await W({args:["commit-tree",tp,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return l(`Failed to create state branch commit
|
|
54
|
+
${n.message}`);let o=n.value.stdout.trim(),r=await W({args:["update-ref",`refs/heads/${t}`,o],cwd:e});return a(r)?l(`Failed to create ${t}
|
|
55
|
+
${r.message}`):d("Created state branch",!0)},Ts=async({repoRoot:e,stateBranchName:t})=>{let n=await Ai({repoRoot:e,branch:t});if(a(n))return l(`Ensure local state branch failed
|
|
56
|
+
`+n.message);if(n.value)return d("Local state branch already exists",!1);let o=await kn({repoRoot:e});if(a(o))return l(`Ensure local state branch failed
|
|
57
|
+
`+o.message);let r=o.value,s=r?await ms({repoRoot:e,branch:t}):d("No remote, no remote state branch",!1);if(a(s))return l(`Ensure local state branch failed
|
|
58
|
+
`+s.message);let i=s.value;if(r&&i){let c=await Ne.fetch({cwd:e,remote:Tt,branch:t});if(a(c))return l(`Failed to fetch ${t} from remote
|
|
59
|
+
${c.message}`)}if(i){let c=await W({args:["branch","--track",t,`${Tt}/${t}`],cwd:e});return a(c)?l(`Failed to create local ${t} from remote
|
|
60
|
+
${c.message}`):d("Created local state branch from remote",!0)}return hc({repoRoot:e,stateBranchName:t})},FE=async({repoRoot:e,branch:t})=>{let n=await W({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return l(n.message);let o=n.value.stdout.split(`
|
|
61
|
+
`),r=null;for(let s of o){if(s.startsWith("worktree ")){r=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&r)return d("Found worktree for branch",r)}return d("No worktree found for branch",null)},_E=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=gs(Fn.dirname(t));if(a(o))return l(`Failed to create state branch worktree
|
|
62
|
+
`+o.message);if(On.existsSync(t)&&!On.existsSync(Fn.join(t,".git"))){let s=Af(t);if(a(s))return l(s.message);if(s.value.length>0)return l([`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(`
|
|
63
|
+
`));ce.info("Removing broken state branch worktree path"),sp(t)}ce.info("Creating state branch worktree");let r=await Ne.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(r)?l(`Failed to create state branch worktree
|
|
64
|
+
${r.message}`):d("Created state branch worktree",!0)},to=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=await $E({repoRoot:e,stateBranchRoot:t,stateBranchName:n});if(a(o))return o;let r=Cf({repoRoot:e,stateBranchRoot:t,stateBranch:n});return a(r)?l(r.message):(r.value==="stamped"&&ce.info("Stamped the state branch with this project\u2019s identity"),o)},BE=(e,t)=>{let n=tr(No());return Fn.dirname(e)===n&&Fn.dirname(t)===n},$E=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=await FE({repoRoot:e,branch:n});if(a(o))return l(o.message);let r=tr(t),s=o.value?tr(o.value):null;if(s&&s===r&&On.existsSync(s))return d("State branch already checked out in expected worktree",!1);if(s&&s!==r&&BE(s,r))return l([`The state branch ${n} is checked out under project ${Fn.basename(s)}, but this checkout names project ${Fn.basename(r)}.`,"","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 ${st} here`,`with \`git show ${n}:${st}\`, and keep the branch's.`].join(`
|
|
65
|
+
`));if(s&&s!==r){let u=await Xm(s);if(a(u))return l(u.message);if(u.value||Ip(s))return l([`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 ${r}, 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(`
|
|
66
|
+
`));ce.info("Moving state branch worktree to expected location");let p=await Ne.worktreeRemove({cwd:e,worktreeRoot:s});if(a(p))return l(`Failed to remove existing state branch worktree
|
|
67
|
+
${p.message}`)}if(s&&!On.existsSync(s)){ce.info("Pruning stale state branch worktree");let u=await Ne.worktreePrune({cwd:e});if(a(u))return l(`Failed to prune stale worktrees
|
|
68
|
+
${u.message}`)}let i=await Gm({repoRoot:e,worktreeRoot:t});if(a(i))return l(i.message);let c=On.existsSync(t);if(i.value&&c)return d("State branch worktree already exists",!1);if(i.value&&!c){ce.info("Pruning missing registered state branch worktree");let u=await Ne.worktreePrune({cwd:e});if(a(u))return l(`Failed to prune stale worktrees
|
|
69
|
+
${u.message}`)}return _E({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},jE=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Ti(e);if(a(n))return l(n.message);if(n.value===t)return d("State branch already checked out",!1);(await Le({cwd:e,args:["rebase","--abort"]})).exitCode===0&&ce.info("Aborted stale state branch rebase");let r=await Ne.checkout({cwd:e,branch:t});return a(r)?l(`Failed to checkout ${t}
|
|
70
|
+
${r.message}`):d("Checked out state branch",!0)},UE=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Fl(t);if(a(n))return l(n.message);if(n.value)return d("State branch upstream already configured",!1);let o=await kn({repoRoot:t});if(a(o))return l(o.message);if(!o.value)return d("No remote available for state branch upstream",!1);let r=vt(e);if(a(r))return r;let s=r.value,i=await ms({repoRoot:t,branch:s});if(a(i))return l(i.message);if(!i.value)return d("Remote state branch missing; upstream will be configured on first push",!1);ce.info(`Configuring ${s} upstream`);let c=await Ne.fetch({cwd:t,remote:Tt,branch:s});if(a(c))return l(`Failed to fetch ${s}
|
|
71
|
+
${c.message}`);let u=await Ne.setUpstream({cwd:t,branch:s,upstream:`${Tt}/${s}`});return a(u)?l(`Failed to set state branch upstream
|
|
72
|
+
${u.message}`):d("Configured state branch upstream",!0)},ea=async({stateBranchRoot:e,eventFileName:t})=>{let n=np(t),o=Fn.join(e,n);if(!On.existsSync(o))return d("No event file to stage",null);let r=await Lf({stateBranchRoot:e,relativePath:n,workingContent:On.readFileSync(o,"utf8")});if(a(r))return l(r.message);let s=await Ne.stage({cwd:e,pathspec:[n]});return a(s)?l(`Failed to stage state branch event file
|
|
73
|
+
${s.message}`):d("Staged state branch event file",n)},Of=async({stateBranchRoot:e})=>{let t=op(),n=Fn.join(e,t);if(!On.existsSync(n))return d("No media directory to stage",null);let o=await Ne.stage({cwd:e,pathspec:[t],ignoreRemoval:!0});return a(o)?l(`Failed to stage state branch media files
|
|
74
|
+
${o.message}`):d("Staged state branch media files",t)},Ff=async({stateBranchRoot:e})=>{let t=[_l(),Bl(),st].filter(o=>On.existsSync(Fn.join(e,o)));if(t.length===0)return d("No event log config to stage",[]);let n=await Ne.stage({cwd:e,pathspec:t});return a(n)?l(`Failed to stage event log config
|
|
75
|
+
${n.message}`):d("Staged event log config",t)},_f=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let o=await OE(e);return a(o)?l(`Create state branch sync commit failed
|
|
76
|
+
`+o.message):nr({cwd:t,message:o.value,pathspec:n})},ks=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Fl(t);if(a(n))return l(n.message);let o=vt(e);if(a(o))return o;let r=o.value,s=n.value?await Ne.push({cwd:t}):await Ne.push({cwd:t,remote:Tt,branch:r,setUpstream:!0});if(a(s))return l(`Failed during state branch push
|
|
77
|
+
${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)},Bf=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let o=!1,r=vt(e);if(a(r))return r;let s=r.value,i=[hs(),await Ts({repoRoot:e,stateBranchName:s}),await to({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await jE({stateBranchRoot:t,stateBranchName:s}),await ap(t),n?await UE({stateBranchRoot:t,repoRoot:e}):d("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(a(c))return l(c.message);o=o||!!c.value}return d(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",o)}});import ta from"node:fs";import yc from"node:os";import HE from"node:path";var WE,$f,qE,GE,zE,Uf,vc,jf,VE,na,bc=g(()=>{"use strict";w();Ke();$t();WE="epiq-sync.lock",$f=600*1e3,qE=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}},GE=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},zE=e=>e&&(e.hostname!==yc.hostname()||GE(e.pid))?Date.now()-e.startedAt>$f:!0,Uf=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,vc=e=>{try{return qE(ta.readFileSync(e,"utf8"))}catch{return null}},jf=(e,t)=>{let n={pid:process.pid,hostname:yc.hostname(),startedAt:Date.now(),operation:t};try{return ta.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},VE=async({worktreeRoot:e,operation:t})=>{let n=await Ol(e);if(a(n))return l(n.message);let o=HE.join(n.value,WE),r=()=>{try{let c=vc(o);c&&c.pid===process.pid&&ta.rmSync(o)}catch{}};if(jf(o,t))return d("Acquired sync lock",{acquired:!0,release:r});let s=vc(o);if(!zE(s))return d("Sync lock is held",{acquired:!1,heldBy:s});ce.info(`Breaking an abandoned sync lock: ${s?Uf(s):"unreadable lock file"}`);try{ta.rmSync(o,{force:!0})}catch{}if(jf(o,t))return d("Acquired sync lock after breaking a stale one",{acquired:!0,release:r});let i=vc(o);return d("Sync lock taken by another process",{acquired:!1,heldBy:i??{pid:-1,hostname:yc.hostname(),startedAt:Date.now(),operation:"unknown"}})},na=async({worktreeRoot:e,operation:t,fn:n})=>{let o=await VE({worktreeRoot:e,operation:t});if(a(o))return l(o.message);if(!o.value.acquired)return ce.info(`Skipping ${t}: the state worktree is held by ${Uf(o.value.heldBy)}`),d("State worktree is held by another process",null);let{release:r}=o.value;try{return d("Ran under the sync lock",await n())}finally{r()}}});import KE from"node:fs";var YE,XE,xc,Hf,Ic,oa,ra=g(()=>{"use strict";w();Cs();Hi();ee();Qi();Cn();rt();Ke();Ms();gc();To();bc();YE=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=ye("getRepoRootDir",await kt(e));if(a(n))return l(n.message);let o=n.value;logger.debug("[sync] repo root",o);let r=ye("getStateBranchRoot",Ie({repoRoot:o}));if(a(r))return l(r.message);let s=r.value;logger.debug("[sync] state branch root",s),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:s,ensureUpstream:t});let i=ye("bootstrapStateBranchStorage",await Bf({repoRoot:o,stateBranchRoot:s,ensureUpstream:t}));if(a(i))return l(i.message);logger.debug("[sync] bootstrap result",{bootstrapped:i.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let c=ye("hasInProgressGitOperation(stateBranchRoot)",await Ci(s));if(a(c))return l(c.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:c.value}),c.value)return logger.info("[sync] state branch git operation in progress"),l("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:s});let u=ye("ensureStateBranchLayout",ip(o,s));return a(u)?l(u.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:s,bootstrapped:i.value}),d("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:s,bootstrapped:i.value}))},XE=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 o=[];for(let p of Dp(bt(t),n)){let m=ye("stageStateBranchOwnEventFile",await ea({stateBranchRoot:t,eventFileName:p}));if(a(m))return l(m.message);o.push(m.value)}let r=ye("stageStateBranchMediaFiles",await Of({stateBranchRoot:t}));if(a(r))return l(r.message);let s=ye("stageStateBranchEventConfig",await Ff({stateBranchRoot:t}));if(a(s))return l(s.message);let i=[...o,r.value,...s.value].filter(p=>p!==null);if(i.length===0)return d("Nothing to stage",{createdCommit:!1});let c=ye("hasStagedChanges(after stage)",await Jm(t,i));if(a(c))return l(c.message);if(logger.debug("[sync] state branch change check after stage result",{changed:c.value}),!c.value)return logger.info("[sync] no own event file changes to commit"),d("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let u=ye("createStateBranchSyncCommit",await _f({repoRoot:e,stateBranchRoot:t,pathspec:i}));return a(u)?l(u.message):(logger.debug("[sync] created sync commit",u.value),d("Committed own event file",{createdCommit:!0,commitSha:u.value}))},xc=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return Ji(n),d(n,{...e,pulled:!1,pushed:!1,offline:!0})},Hf=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),l("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),l("Own event file must end with .jsonl");ir();let n=ye("ensureSyncReady",await YE({cwd:e,ensureUpstream:!0}));if(a(n))return $e(n.message);let{repoRoot:o,stateBranchRoot:r,bootstrapped:s}=n.value,i=ye("isDetachedHead(stateBranchRoot)",await Qm(r));if(a(i))return $e(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return $e("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,p=!1,m=!1,f=ye("getStateBranch",vt(o));if(a(f))return $e(f.message);let h=f.value;logger.debug("[sync] resolved state branch",{stateBranch:h,stateBranchRoot:r});let x=ye("flushPendingLogs",Oi(r,t));a(x)&&logger.error(`[sync] ${x.message}`);let E=ye("commitOwnEventFileToStateBranch",await XE({repoRoot:o,stateBranchRoot:r,ownEventFileName:t}));if(a(E))return $e(E.message);c=E.value.createdCommit,u=E.value.commitSha;let S=ye("hasRemote",await kn({repoRoot:r}));if(a(S))return $e(S.message);if(!S.value)return xc({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s},"no remote");let C=ye("pullBranchRebaseIfPresent",await fs({cwd:r,branch:h}));if(a(C))return ps(C.message)?xc({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s}):$e(C.message);p=C.value;let R=ye("isAheadOfUpstream",await Ym(r));if(a(R))return $e(R.message);if(c||s||R.value){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:r});let A=ye("pushStateBranch",await ks({stateBranchRoot:r,repoRoot:o}));if(a(A)&&Vm(A.message)){let L=ye("pullBranchRebaseIfPresent(retry)",await fs({cwd:r,branch:h}));if(a(L))return $e(L.message);p=p||L.value,A=ye("pushStateBranch(retry)",await ks({stateBranchRoot:r,repoRoot:o}))}if(a(A))return ps(A.message)?xc({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s}):$e(A.message);m=A.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:r});let A=ye("git rev-parse HEAD",await W({args:["rev-parse","HEAD"],cwd:r}));if(a(A))return $e(A.message);u=A.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Do(m?"Synced and pushed":p||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),d("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,pulled:p,pushed:m,bootstrapped:s,offline:!1})},Ic=async(e,t)=>{let n=kf(e);try{return await t()}finally{let o=Mf(e,n);o.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${o.join(", ")}`)}},oa=async e=>{let t=e.cwd??process.cwd(),n=await kt(t);if(a(n))return $e(n.message);let o=Ie({repoRoot:n.value});if(a(o))return $e(o.message);let r=o.value;if(!KE.existsSync(r))return Hf(e);let s=await na({worktreeRoot:r,operation:"sync",fn:()=>Ic(r,()=>Hf(e))});return a(s)?$e(s.message):s.value===null?d("Another process is syncing this board",{repoRoot:n.value,stateBranchRoot:r,createdCommit:!1,pulled:!1,pushed:!1,bootstrapped:!1,offline:!1,skipped:!0}):s.value}});var vn,sa,JE,Ec,Wf,ia=g(()=>{"use strict";xf();Po();$();$();Oe();w();O();Cs();Qi();ra();vn=null,sa=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!vn,currentStatus:v().syncStatus?.status,currentMessage:v().syncStatus?.msg}),vn)return logger.debug("[sync] syncAndReloadState joining existing promise"),vn;logger.debug("[sync] syncAndReloadState creating promise"),vn=JE();try{let e=await vn;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:v().syncStatus?.status,statusMessageAfterResolve:v().syncStatus?.msg}),a(e)&&v().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),T({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),vn||l(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:v().syncStatus?.status,statusMessageBeforeClear:v().syncStatus?.msg}),vn=null}},JE=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:v().mode,syncStatus:v().syncStatus});let e=Wf();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:v().mode,message:e.message,syncStatus:v().syncStatus}),e;if(vn)return vn;logger.debug("[sync] syncAndReloadState:start");let t=ye("resolveActorId",ge());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),l("Unable to resolve event log path");T({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:v().syncStatus});let n=Qn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let o=ye("syncEpiqWithRemote",await oa({ownEventFileName:n}));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:v().syncStatus}),$e(`Unable to sync state. ${o.message}`);let{stateBranchRoot:r,offline:s}=o.value,i=Ec(r);return a(i)?i:(T({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:v().syncStatus}),d("Synced",!0))},Ec=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=ye("loadMergedEvents",nn(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(t),message:(a(t),t.message),count:a(t)?void 0:t.value.events.length}),a(t))return T({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:v().syncStatus}),l(`Unable to load events. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=Wf();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:v().mode,message:n.message,syncStatus:v().syncStatus}),n;let o=vf(),r=v().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:o,selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id,selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual}),!v().selectedNode?.isVirtual&&!v().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:t.value.events.length});let i=ye("bootStateFromEventLog",gn(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(i),message:(a(i),i.message)}),a(i))return T({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:v().syncStatus}),l(`Unable to boot synced state. ${i.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),T({filters:r}),logger.debug("[sync] restoreNavigationAnchor:start");let s=ye("restoreNavigationAnchor",bf(o));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(s),message:a(s)?s.message:"Navigation restored",selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id}),a(s)?(T({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:v().syncStatus}),s):d("Reloaded state from event log",null)},Wf=()=>v().mode===b.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:v().mode,syncStatus:v().syncStatus}),T({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),l("Will not re-materialize if not in default mode, to not lose edit data"))});var cr,qf,Gf,Rc,Sc,Ls,Nc,QE,zf,ZE,Vf,aa=g(()=>{"use strict";w();Fe();O();ia();cr=3e3,qf=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<cr?null:t},Gf=0,Sc=!1,Ls=!1,Nc=()=>{if(Sc)return!0;let e=Me();return a(e)?!1:e.value.syncStatus.status==="syncing"},QE=()=>{let e=le().autoSyncIntervalMs??1e4,t=Date.now()-Gf;return Math.max(0,e-t)},zf=()=>{Rc||(Rc=setTimeout(async()=>{if(Rc=void 0,!!jt()){if(Nc()){Ls=!0;return}Ls=!1,await ZE()}},QE()))},ZE=async()=>{if(v().readOnly||v().timeMode==="peek"||v().timeMode==="replay")return l("Cannot auto-sync while peeking");if(!jt())return l("Cannot auto-sync before state is initialized");if(Nc())return Ls=!0,l("Sync already in progress");Sc=!0,Gf=Date.now(),T({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await sa()}finally{Sc=!1,Ls&&zf()}},Vf=()=>{jt()&&(Ls=!0,!Nc()&&zf())}});import Ps from"node:fs";import Ds from"node:path";import{z as dr}from"zod";var la,eR,tR,nR,Yf,Xf,Kf,Jf,Qf,Zf,oR,ca,Os,ur=g(()=>{"use strict";w();Jt();Ni();ee();la="recent-projects.json",eR=20,tR=dr.object({projectId:dr.string().min(1),root:dr.string().min(1),lastOpenedAt:dr.number().finite()}),nR=dr.object({projects:dr.array(tR)}),Yf=()=>Ds.join(wn(),la),Xf=e=>Ds.basename(e)||e,Kf=e=>{let t=Ds.resolve(e);try{return Ps.realpathSync(t)}catch{return t}},Jf=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Qf=e=>{if(!ys(e.root))return!1;let t=un(e.root);return!a(t)&&t.value===e.projectId},Zf=()=>{let e=Yf();if(!Ps.existsSync(e))return d("No recent projects recorded",[]);let t;try{t=JSON.parse(Ps.readFileSync(e,"utf8"))}catch(o){return l(`Invalid ${la}: ${o instanceof Error?o.message:String(o)}`)}let n=nR.safeParse(t);return n.success?d("Read recent projects",n.data.projects):l(`Invalid ${la} shape: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},oR=e=>{let t=Yf();try{Ps.mkdirSync(Ds.dirname(t),{recursive:!0}),Ps.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
78
|
+
`,"utf8")}catch(n){return l(`Unable to write ${la}: ${n instanceof Error?n.message:String(n)}`)}return d("Recorded recent project",e)},ca=({exclude:e}={})=>{let t=Zf();if(a(t))return t;let n=e===void 0?null:Kf(e);return d("Listed recent projects",t.value.filter(o=>n===null||Kf(o.root)!==n).filter(Qf).sort(Jf))},Os=({root:e,now:t=Date.now()})=>{let n=Ds.resolve(e),o=un(n);if(a(o))return l(o.message);let r=o.value,s=Zf(),i=a(s)?[]:s.value,c=[{projectId:r,root:n,lastOpenedAt:t},...i.filter(u=>u.projectId!==r&&u.root!==n)].filter(Qf).sort(Jf).slice(0,eR);return oR(c)}});var wc,eg,tg,Cc=g(()=>{"use strict";wc=null,eg=e=>{wc=e},tg=e=>wc?wc(e):[]});var ng,og,mr,Fs=g(()=>{"use strict";ng=[],og=e=>{ng=e},mr=()=>ng});var _s,Ac,rg,sg,Tc,ig,ag,lg,Oo=g(()=>{"use strict";wt();w();Jt();Fe();Cc();Fs();ee();_s=()=>{let e=le(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),o=e.autoSync===!0||e.autoSync===!1,r=rg(),s=r.length>0?null:Ac(),i=s!==null&&(e.declinedEmailBoards??[]).includes(s),c=r.length>0||i||s===null;return{isSetupDone:n&&t&&o&&c,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:o,isSetEmails:c,claimedEmails:r,emailSetupDeclined:i}},Ac=()=>{let e=we(process.cwd());if(a(e))return null;let t=un(e.value);return a(t)?null:t.value||null},rg=()=>{let{userId:e}=le();return e?tg(e):[]},sg=()=>rg().length>0,Tc=()=>{let e=we(process.cwd());if(a(e))return!1;let t=At(e.value);return Dt(t)},ig=e=>e===!0?"on":e===!1?"off":null,ag=e=>e==="on"?!0:e==="off"?!1:null,lg=()=>{let e=_s();if(!e.isSetUserName)return"config username ";if(!e.isSetPreferredEditor)return"config editor ";if(!e.isSetAutoSync)return"config autoSync ";if(!Tc())return"init";if(!e.isSetEmails){let{gitEmail:t}=le(),n=mr()[0]??t;return n&&Gn(n)?`config emails ${n}`:"config emails "}return null}});var rR,sR,yn,bn,da,ua,pr=g(()=>{"use strict";me();w();pe();O();rR=e=>e.props.tags??[],sR=e=>e.props.assignees??[],yn=e=>rR(e).map(t=>N.getTag(t)).filter(t=>!!t),bn=e=>sR(e).map(t=>N.getContributor(t)).filter(t=>!!t),da=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!U(n)?l("Invalid untag target"):d("Retrieved tags from ticket in breadcrumb",yn(n))},ua=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!U(n)?l("Invalid unassign target"):d("Retrieved assignees from ticket in breadcrumb",bn(n))}});var I,Fo=g(()=>{"use strict";I={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",NONE:""}});var iR,aR,lR,cR,dR,_o,cg,ma,pa,dg,uR,kc,Bs=g(()=>{"use strict";iR=/^(\d+)(h|d|w|mo|y)$/,aR=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,lR=({year:e,month:t,day:n,hour:o=0,minute:r=0})=>{let s=new Date(e,t-1,n,o,r);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===o&&s.getMinutes()===r},cR=(e,t=new Date)=>{let n=e.match(iR);if(!n)return null;let[,o,r]=n,s=Number(o);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(r){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}},dR=e=>{let t=e.match(aR);if(!t)return null;let[,n,o,r,s,i]=t,c=Number(n),u=Number(o),p=Number(r),m=s?Number(s):0,f=i?Number(i):0;return lR({year:c,month:u,day:p,hour:m,minute:f})?new Date(c,u-1,p,m,f):null},_o=e=>{let t=e.trim().toLowerCase();return cR(t)??dR(t)},cg=/^(\d+)(s|m)?$/,ma=e=>{let t=e.trim().toLowerCase().match(cg);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},pa=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),o=n.length>0&&cg.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:o}},dg=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,uR=[{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}],kc=(e=uR)=>{let t=[];for(let{unit:n,from:o,to:r}of e)for(let s=o;s<=r;s++)t.push(`${s}${n}`);return t}});var mR,be,Mt,He,pR,fR,Lc,Pc,pg,Bo,fa,Mc,ug,gR,hR,$s,mg,vR,yR,Dc,bR,We,_n=g(()=>{"use strict";aa();ur();w();Oo();tn();me();pe();O();bl();pr();Fo();Bs();mR=["BOARD","TICKET","SWIMLANE","COMMENT"],be={EDITOR:"editor",VIEW:"view",USERNAME:"username",EMAILS:"emails",EMAILS_UNCLAIM:"emails-unclaim",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},Mt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},He={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},pR=[be.EDITOR,be.VIEW,be.USERNAME,be.EMAILS,be.EMAILS_UNCLAIM,be.AUTOSYNC,be.SYNC_DEBOUNCE_MS,be.ATTACHMENT_MAX_KB,be.LOG_LEVEL],fR=(e=v().selectedNode?.context)=>{switch(e){case"TICKET":return[Mt.TITLE,Mt.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Mt.TITLE];case"COMMENT":return[Mt.COMMENT];default:return[]}},Lc=[String(cr),"5000","15000","30000","60000"],Pc=["250","500","1000"],pg=["10s","20s","30s","45s"],Bo=[I.EXIT,I.SYNC,I.HELP,I.EXPORT,I.CONFIG,I.YANK],fa=[I.NEW,I.EDIT,I.DELETE,I.MOVE],Mc=[I.TAG,I.UNTAG,I.ASSIGN,I.UNASSIGN,I.CLOSE_ISSUE,I.RE_OPEN_ISSUE,I.EDIT,I.COMMENT],ug=[I.FILTER,I.PEEK,I.REPLAY],gR={WORKSPACE:[...Bo,...fa],BOARD:[...ug,...Bo,...fa],SWIMLANE:[...ug,...Bo,...fa],TICKET:[...Bo,...fa,...Mc],FIELD:[...Bo,...Mc],FIELD_LIST:[...Bo,...Mc],TEXT:[...Bo],COMMENT:[I.EDIT,I.DELETE,I.YANK]},hR=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],$s=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&U(n)),mg=e=>e.parentNodeId===Ae,vR=({selectedNode:e,breadCrumb:t})=>{let n=fR(e?.context);return $s({breadCrumb:t,selectedNode:e})?n.includes(Mt.DESCRIPTION)?n:[...n,Mt.DESCRIPTION]:n},yR=({selectedNode:e,breadCrumb:t})=>{let n=$s({breadCrumb:t,selectedNode:e});return n?[He.REF,He.TITLE,...n.props?.description?.trim()?[He.DESCRIPTION]:[],...yn(n).length>0?[He.TAGS]:[],...bn(n).length>0?[He.ASSIGNEES]:[]]:e?[He.REF,He.TITLE]:[]},Dc=()=>{let e=ca({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},bR=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:o}=_s();if(!o)return[I.HELP,I.CONFIG];if(!Tc())return[I.HELP,I.INIT,I.OPEN];if(t)return[I.HELP,I.PEEK,I.REPLAY,I.EXPORT,I.CONFIG,I.YANK];let r=e?.context,s=r&&mR.includes(r),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?gR[u]:[]))],c=$s({breadCrumb:n,selectedNode:e});return i.filter(u=>u===I.MOVE?!1:u===I.YANK?!!(c??e):u===I.EDIT?s||!!c:u===I.DELETE?s:u===I.UNTAG?!!(c&&yn(c).length>0):u===I.UNASSIGN?!!(c&&bn(c).length>0):u===I.RE_OPEN_ISSUE?!!(c&&mg(c)):u===I.CLOSE_ISSUE?!!(c&&!mg(c)):!0)},We=(e,{contextNode:t,selectedNode:n,readOnly:o,breadCrumb:r}=v())=>{let s=t.context??"WORKSPACE";return{[I.NONE]:bR({breadCrumb:r,readOnly:o,selectedNode:n}),[I.EXIT]:["confirm"],[I.EXPORT]:[],[I.SYNC]:[],[I.INIT]:[],[I.OPEN]:e===I.OPEN?Dc():[],[I.HELP]:[],[I.PEEK]:[...kc(),"now","prev","next"],[I.REPLAY]:[...kc()],[I.EDIT]:vR({selectedNode:n,breadCrumb:r}),[I.YANK]:yR({selectedNode:n,breadCrumb:r}),[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(vi),...N.getExistingTags()])],[I.UNTAG]:[...da()?.value?.map(({name:c})=>c)??[]],[I.UNASSIGN]:[...ua()?.value?.map(({name:c})=>c)??[]],[I.ASSIGN]:N.getExistingAssignees(),[I.NEW]:hR(s),[I.CONFIG]:[...pR]}[e]??[]}});var fg,gg=g(()=>{"use strict";fg=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{accessSync as xR,copyFileSync as IR,existsSync as ga,mkdirSync as hg,readdirSync as vg,readFileSync as ER,renameSync as RR,rmSync as SR,statSync as yg,unlinkSync as NR,writeFileSync as wR}from"node:fs";import fr from"node:path";var Oc,Ze,ha=g(()=>{"use strict";Oc=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Ze={writeToFile:(e,t)=>{try{let n=fr.dirname(e);ga(n)||hg(n,{recursive:!0});let o=typeof t=="string"?t:JSON.stringify(t,null,2);wR(e,o,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return ER(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Ze.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 ga(e)&&yg(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await xR(e),!0}catch{return!1}},mkDir:e=>hg(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=fr.parse(t);for(;;){let o=fr.join(t,e);try{if(ga(o)&&yg(o).isDirectory())return o}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=fr.dirname(t)}return null},readFirstJSON(e){try{if(!Ze.dirExists(e))return null;let t=vg(e).filter(o=>o.endsWith(".json")).sort()[0];if(!t)return null;let n=fr.join(e,t);return Ze.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Ze.dirExists(e)?vg(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{NR(e)}catch(t){(!Oc(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{SR(e,{recursive:!0,force:!0})}catch(t){(!Oc(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(fr.dirname(t)),!n?.overwrite&&ga(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{RR(e,t)}catch(o){if(Oc(o)&&o.code==="EXDEV"){IR(e,t),this.rmFile(e);return}throw o}}}});import CR from"node:path";import{z as on}from"zod";var AR,bg,TR,xg,Fc,_c,kR,no,Ig,it,gr,rn=g(()=>{"use strict";vo();ee();w();ha();AR={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},bg=on.object({logLevel:on.enum(["info","error","debug"]),preferredEditor:on.string().optional(),userName:on.string().optional(),userId:on.string().optional(),autoSync:on.boolean().nullable().optional(),autoSyncDebounceMs:on.number().optional(),attachmentMaxKb:on.number().optional(),viewMode:on.enum(["dense","wide"]).optional(),declinedEmailBoards:on.array(on.string()).optional()}).partial(),TR="config.json",xg=wn,Fc=()=>CR.join(xg(),TR),_c=()=>{try{return Ze.mkDir(xg()),d(`Ensured ~/${Qt} exists`,null)}catch{return l(`Unable to create ~/${Qt}`)}},kR=e=>{let t;try{t=JSON.parse(e)}catch{return l(`Invalid ~/${Qt}/config.json JSON`)}let n=bg.safeParse(t??{});return n.success?d("Parsed config",n.data):l(`Invalid ~/${Qt}/config.json shape: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},no=()=>{let e=_c();if(a(e))return l(e.message);let t=Fc(),n=Ze.readFile(t);return n==null||n.trim()===""?d("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):kR(n)},Ig=e=>{let t=_c();if(a(t))return l(t.message);let n=bg.safeParse(e);if(!n.success)return l(`Invalid config: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`);let o=Fc();try{return Ze.writeToFile(o,JSON.stringify(n.data,null,2)+`
|
|
79
|
+
`),d("Config written",null)}catch{return l(`Unable to write ~/${Qt}/config.json`)}},it=e=>{let t=no();if(a(t))return l("Failed to read existing config");let n={...t.value,...e};return Ig(n)},gr=()=>{let e=Fc(),t=_c();if(a(t))return l(`Unable to create ~/${Qt}`);if(!(Ze.readFile(e)!==null)){let S=Ig(AR);if(a(S))throw new Error(`Unable to create ~/${Qt}/config.json`)}let o=no();if(a(o))throw new Error(o.message||"Unable to load settings");let{preferredEditor:r,userName:s,userId:i,declinedEmailBoards:c,autoSync:u,autoSyncDebounceMs:p,attachmentMaxKb:m,logLevel:f,viewMode:h}=o.value,x=hl({userId:i,userName:s});if(a(x))return l(x.message);let E=x.value??{userId:i,userName:s};return!E.userName||!E.userId?l(`User name or ID not configured in ~/${Qt}/config.json`):(process.env.EPIQ_LOG_LEVEL=f,d("successfully loaded settings",{gitEmail:null,gitName:null,declinedEmailBoards:c??[],logLevel:f??"debug",preferredEditor:r??"",userName:E.userName,userId:E.userId,autoSync:u??!1,autoSyncIntervalMs:p??1e4,attachmentMaxKb:m??null,viewMode:h??"dense"}))}});var Eg,Rg,Bc,Sg=g(()=>{"use strict";Eg="/media/",Rg=e=>`${Eg}${e}`,Bc=(e,t)=>`})`});import MR from"node:crypto";import $c from"node:fs";import LR from"node:path";var Bn,hr,PR,DR,OR,Ng,vr=g(()=>{"use strict";Yt();w();ee();Sg();Bn=500,hr=(e,t)=>`${e}.${t}`,PR=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?d("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?d("Sniffed image type","jpg"):e.length>=6&&(e.subarray(0,6).equals(Buffer.from("GIF87a","ascii"))||e.subarray(0,6).equals(Buffer.from("GIF89a","ascii")))?d("Sniffed image type","gif"):e.length>=12&&e.subarray(0,4).equals(Buffer.from("RIFF","ascii"))&&e.subarray(8,12).equals(Buffer.from("WEBP","ascii"))?d("Sniffed image type","webp"):l(`Unsupported image format. Allowed: ${vm.join(", ")}`),DR=e=>MR.createHash("sha256").update(e).digest("hex"),OR=(e,t=Bn)=>{if(e.length===0)return l("Attachment is empty");if(e.length>t*1024)return l(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=PR(e);return a(n)?n:d("Validated attachment data",{hash:DR(e),ext:n.value,bytes:e.length})},Ng=(e,t,n=Bn)=>{let o=OR(t,n);if(a(o))return o;let r=ki(e),s=LR.join(r,hr(o.value.hash,o.value.ext));try{$c.existsSync(s)||($c.mkdirSync(r,{recursive:!0}),$c.writeFileSync(s,t))}catch(i){return l(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return d("Wrote attachment blob",o.value)}});import FR from"zod";var js,Us,wg,jc=g(()=>{"use strict";rn();vr();w();he();Fe();js=50,Us=5e3,wg=()=>{let e=fe().commandMeta.inputString,t=FR.coerce.number().int().min(js).max(Us).safeParse(e);if(!t.success)return l(`Attachment size cap must be ${js}-${Us} KB (default ${Bn})`);let n=it({attachmentMaxKb:t.data});return a(n)?n:(Qe({attachmentMaxKb:t.data}),d(`Attachment size cap set to ${t.data} KB`,null))}});var at,$n=g(()=>{"use strict";at=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null});import{createHash as _R}from"node:crypto";var BR,$R,Te,oo=g(()=>{"use strict";BR="0123456789ABCDEFGHJKMNPQRSTVWXYZ",$R=e=>{let t=_R("sha256").update(e).digest(),n=0n;for(let r=0;r<16;r++)n=n<<8n|BigInt(t[r]);let o="";for(let r=0;r<26;r++){let s=BigInt((25-r)*5);o+=BR[Number(n>>s&31n)]}return o},Te=(e,t)=>$R(`${e}:virtual:${t}`)});import Cg from"chalk";var Re,je,Ue,Ag=g(()=>{"use strict";dn();Je();Re=e=>Cg.dim(e),je=e=>Cg.hex(k.primary)(e),Ue=({prefix:e="",wordList:t,postfix:n="",noOfHints:o=100,inputString:r,minLengthForHints:s=1})=>{let i=r.trim();if(i.length<s)return"";let m=[...t.filter(Boolean).filter(f=>f.startsWith(i))].sort((f,h)=>yi(f)-yi(h)).slice(0,o).map(f=>bi(f)).join(" ");return m?`${Re(e)}${m}${Re(n)}`:""}});var ro,va=g(()=>{"use strict";ro={None:"none",Invalid:"invalid",Valid:"valid"}});import Mg from"chalk";var jR,Tg,xe,UR,ie,Y,br,kg,ya,Uc,HR,yr,WR,qR,GR,zR,VR,Lg,Pg=g(()=>{"use strict";aa();Oo();gg();ft();Yt();w();pe();Fe();jc();vr();wt();O();dn();$n();pr();oo();Ag();Fs();Fo();va();_n();Bs();jR=["BOARD","TICKET","SWIMLANE"],Tg=()=>{let e=v().selectedNode;if(!e?.context)return Y({message:Re("Missing target context")});if(jR.includes(e.context))return ie();if(e.parentNodeId){let t=v().nodes[e.parentNodeId];if(t?.id===Te(t?.parentNodeId??"","comments"))return ie()}return Y({message:Re("Command not available in this context")})},xe="<ENTER> to confirm",UR=()=>{let{userId:e}=le(),t=Me();return!e||a(t)?[]:zn(t.value.emailLinks,e)},ie=(e="",t=[],n=!0)=>({message:n?Re(e):e,validity:ro.Valid,completionWordList:t}),Y=({message:e,completionWordList:t=[]})=>({validity:ro.Invalid,message:e,completionWordList:t}),br=e=>e.length===0,kg=(e,t)=>{let n=Nt(v().breadCrumb,"BOARD");if(a(n))return Y({message:je("Command is not applicable in this context")});let o=dm(n.value.id);return a(o)?Y({message:je(`Unable to ${t}: board id is not a valid ULID`)}):dg({date:e,horizonDate:o.value})?null:Y({message:je(`nothing to ${t} before ${o.value.toISOString().slice(0,16).replace("T"," ")}`)})},ya=e=>` ${Mg.hex("#000").bgHex(nt(e))(` ${e} `)} `,Uc=({modifier:e})=>{let t="confirm";return e===t?ie(xe):Y({message:br(e)?Re("if you are certain, enter ")+bi(t):"",completionWordList:[t]})},HR=({list:e,hint:t,onValue:n})=>({modifier:o,inputString:r})=>e.includes(o)?r.trim().length<1?Y({message:Re(n)}):ie():Y({message:br(o)?t:"",completionWordList:[...e]}),yr=({hint:e,onOk:t})=>({modifier:n,inputString:o})=>br(n)&&br(o)?Y({message:e,completionWordList:[]}):ie(t??xe),WR=({modifier:e,inputString:t})=>{let n=Dc();return!br(e)||!br(t)?ie(xe):Y({message:n.length?Re("number from the list, or a path"):Re("path to an epiq project"),completionWordList:n})},qR=({modifier:e,inputString:t})=>{let n=We(I.CONFIG);if(!n.includes(e))return Y({message:Ue({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case be.EDITOR:{let o=[...fg];return t.trim()?o.includes(t.trim())?ie(xe):Y({message:Ue({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o}):Y({message:Ue({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case be.VIEW:{let o=["dense","wide"];return o.includes(t.trim())?ie(xe):Y({message:Ue({prefix:"view... ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case be.USERNAME:{let o=le().gitName,r=o?[o]:[],s=t.trim(),i=r.filter(p=>p.startsWith(s)),u=i.length===1&&i[0]===s?"":Ue({prefix:"name: ",wordList:r,inputString:s,minLengthForHints:0});return s?u?ie(`${u} ${Re(xe)}`,r,!1):ie(xe,r):Y({message:u||je("Enter a user name. Saved in ")+Mg.bgBlack("~/.epiq-global/config.json"),completionWordList:r})}case be.EMAILS:{let o=le().gitEmail,r=mr(),s=r.length>0||!o?r:[o],i=[...s,"none"],c=t.trim(),u=(E,S)=>Y({message:Ue({prefix:E,wordList:i,noOfHints:3,inputString:S,minLengthForHints:0}),completionWordList:i});if(!c)return ie(`${xe} to see your addresses, or name one`,i);let p=c.split(/[,\s]+/).filter(Boolean),m=p[p.length-1]??"",f=E=>E==="none"||s.includes(E.toLowerCase()),h=E=>i.some(S=>S.startsWith(E.toLowerCase())),x=p.filter(E=>!f(E)&&!h(E));return x.length>0?Y({message:je(`no address here matches ${x.join(", ")} \u2014 pick one from the list, or its number`),completionWordList:i}):f(m)?ie(xe):u("",m)}case be.EMAILS_UNCLAIM:{let o=UR(),r=t.trim();return o.length===0?Y({message:je("you have not claimed any addresses"),completionWordList:[]}):r&&o.includes(r.toLowerCase())?ie(xe):Y({message:Ue({prefix:"give an address back ",wordList:o,noOfHints:3,inputString:r,minLengthForHints:0}),completionWordList:o})}case be.LOG_LEVEL:{let o=["debug","error","info"],r=t.trim();return o.includes(r)?ie(xe):Y({message:Ue({prefix:"one of: ",wordList:[...o],inputString:r,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...o]})}case be.AUTOSYNC:{let o=["on","off"],r=le().autoSync;if(!o.includes(t.trim())){let s=ig(r);return Y({message:Ue({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:o,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:o})}return ie(xe)}case be.ATTACHMENT_MAX_KB:{let o=le().attachmentMaxKb,r=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(r)||r<js||r>Us){let s=Ue({prefix:" examples: ",wordList:Pc,minLengthForHints:0,inputString:t});return Y({message:je(`provide a size cap in KB (${js}-${Us}). current: ${o??Bn} KB.`)+s,completionWordList:Pc})}return ie(xe)}case be.SYNC_DEBOUNCE_MS:{let o=le().autoSyncIntervalMs,r=qf(t);if(!t.trim()||r===null||r<cr){let s=Ue({prefix:" examples: ",wordList:Lc,minLengthForHints:0,inputString:t});return Y({message:je(`provide duration above ${cr}ms. current duration: ${o}ms.`)+s,completionWordList:Lc})}return ie(xe)}default:return Y({message:je("Unknown config option"),completionWordList:n})}},GR=({modifier:e,inputString:t})=>{let n=We(I.EDIT);if(!n.length)return Y({message:je("Command not available in this context")});if(!n.includes(e)){let o=Ue({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return Y({message:o||je("Unknown edit option"),completionWordList:n})}switch(e){case Mt.COMMENT:return t.trim()?ie(xe):Y({message:Re("write a comment...")});case Mt.TITLE:return ie(xe);case Mt.DESCRIPTION:{let{preferredEditor:o}=le();return o?ie(Re("<ENTER> to edit in ")+o):Y({message:"No editor selected"})}default:return Y({message:je("Unknown edit option"),completionWordList:n})}},zR=({modifier:e})=>{let t=We(I.YANK);return t.length?t.includes(e)?ie(xe+Re(" and copy to clipboard")):Y({message:Ue({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):Y({message:je("Nothing selected to copy from")})},VR={[I.EXPORT]:()=>ie(xe+Re(", and create export markdown file")),[I.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return ie(xe);let n={message:Re("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},o=t||e.inputString.trim(),r=_o(o);if(!o||!r)return Y(n);let s=kg(r,"peek");return s||ie(xe)},[I.REPLAY]:e=>{let{dateInput:t,durationInput:n}=pa(e.modifier,e.inputString),o={message:Re("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},r=_o(t);if(!t||!r)return Y(o);let s=kg(r,"replay");return s||(n&&ma(n)===null?Y({message:je("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):ie("<ENTER> to replay board history",n?pg:[]))},[I.EXIT]:()=>ie(xe+Re(" and exit the application")),[I.INIT]:()=>ie(xe),[I.OPEN]:WR,[I.PALETTE]:()=>ie(xe),[I.FILTER]:e=>{if(e.modifier==="clear")return ie(xe);let t=s=>We(I.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return Y({message:Ue({wordList:We(I.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:We(I.FILTER)});let n=Object.values(v().tags).map(s=>s.name),o=Object.values(v().contributors).map(s=>s.name),r=e.modifier==="tag"?n:e.modifier==="assignee"?o:[];return e.inputString?r.length&&!r.includes(e.inputString.trim())?Y({message:Ue({prefix:`existing ${e.modifier}s... `,wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r}):ie():Y({message:Ue({prefix:"one of... ",wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r})},[I.NONE]:e=>{let t=We(I.NONE);return Y({message:Ue({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[I.NEW]:e=>HR({list:We(I.NEW),hint:Ue({wordList:We(I.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[I.HELP]:()=>ie(xe),[I.EDIT]:GR,[I.COMMENT]:e=>{let t=yr({hint:Re(`write a comment (max ${4e3} char)...`),onOk:Re(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===ro.Invalid?t:e.inputString.length>4e3?ie(je("max input exceeded")):t},[I.CONFIG]:qR,[I.YANK]:zR,[I.DELETE]:e=>{let t=Tg();return t.validity==="invalid"?t:Uc(e)},[I.CLOSE_ISSUE]:e=>Uc(e),[I.RE_OPEN_ISSUE]:e=>Uc(e),[I.MOVE]:e=>{let t=Tg();return t.validity==="invalid"?t:yr({hint:Ue({prefix:"hey hacker! These commands are blocked for you... ",wordList:We(I.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[I.TAG]:e=>{let n=N.getExistingTags().slice(0,10).map(ya).join("");return yr({hint:n.length?Re("create tag or reuse:")+n+Re(""):Re("create tag ...")})(e)},[I.UNTAG]:e=>{let t=da();if(a(t))return Y({message:je("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(ya).slice(0,10);return n.length?yr({hint:Re(" ... ")+n.join("")})(e):Y({message:je("Issue has no tags"),completionWordList:[]})},[I.ASSIGN]:e=>{let t=N.getExistingAssignees().map(ya).slice(0,10);return yr({hint:Re("assignees... ")+t.join("")})(e)},[I.UNASSIGN]:e=>{let t=ua();if(a(t))return Y({message:je("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(ya).slice(0,10);return n.length?yr({hint:Re("remove assignee... ")+n.join("")})(e):Y({message:je("Issue has no assignees"),completionWordList:[]})},[I.SYNC]:()=>ie(xe)},Lg=Object.fromEntries(Object.entries(VR).map(([e,t])=>[e,{validate:(n,o,r)=>t({modifier:o,command:n,inputString:r})}]))});var ba,Dg=g(()=>{"use strict";ba=["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 KR,YR,XR,JR,QR,Og,Fg,_g,Bg=g(()=>{"use strict";w();O();Dg();KR=3,YR=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"]),XR=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let o=n.props;typeof o.description=="string"&&t.push(o.description),typeof o.value=="string"&&t.push(o.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},JR=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=KR&&!YR.has(t)&&!/^\d+$/.test(t)),QR=e=>{let t=new Map;for(let s of XR(e))for(let i of JR(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),o=new Set(n),r=ba.filter(s=>!o.has(s));return[...n,...r]},Og=ba,Fg=-1,_g=()=>{let e=Me();if(a(e))return ba;let t=e.value,n=t.eventLog.length;return n!==Fg&&(Og=QR(t),Fg=n),Og}});var $g,jg,Hc=g(()=>{"use strict";km();_n();Fo();Pg();Bg();O();Oe();$g=e=>Object.values(I).includes(e),jg=(e,t)=>{let n=e.command??"",{modifier:o,target:r,inputString:s}=e,{message:i,validity:c,completionWordList:u}=Lg[n].validate(n,o,s),p=n!==I.PEEK&&n!==I.REPLAY,m=r==="command"||r==="modifier"?We(n):p?_g():[],{mode:f}=v(),h=f===b.COMMAND_LINE?i??"":"",x=[...u,...m];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:h,autoCompletion:t?Tm(e,x,u):{hint:"",hints:[],remainder:"",overlap:0}}}});var Ug,ZR,eS,tS,Hg=g(()=>{"use strict";Hc();_n();Ug=e=>{let t=e.trimStart(),n=eS(t),o=n[0]??"",r=n[1]??"",s=/\s$/.test(e),i=tS(e),c=$g(o)?o:null,u=c!==null,p=o!=="",m=c?We(c)??[]:[],f=c&&m.includes(r)?r:"",h="word";n.length===0||n.length===1&&!s?h="command":(n.length===1&&s||n.length===2&&!s)&&(h="modifier");let x=s?"":i,E=ZR(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:o,lastWord:i,hasCommand:p,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:h,inputToMatch:x,inputString:E}},ZR=(e,t,n)=>{let o=e;return t&&o.startsWith(t)&&(o=o.slice(t.length)),o=o.replace(/^\s+/,""),n&&o.startsWith(n)&&(o=o.slice(n.length),o=o.replace(/^\s+/,"")),o},eS=e=>e.trim()?e.trim().split(/\s+/):[],tS=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as AF}from"react";var xr,Wc,Hs,Ir,nS,Wg,sn,Ws,qc,Gc,qg,Gg,xa,zg,ne,Vg,Kg,Yg,Xg,fe,Ia,he=g(()=>{"use strict";Hc();Hg();w();va();xr=e=>e===Wc||e===":",Wc=" ",Hs=40,Ir={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:ro.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},nS=new Set,Wg=()=>{for(let e of nS)e()},sn=e=>{let n=e(Ir),o=Ug(n.value),r=n.cursorPosition===n.value.length;Ir={...n,commandMeta:jg(o,r)},Wg()},Ws=({message:e,status:t})=>{let n=structuredClone(Ir);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Ir=n,Wg(),d(e,null)},qc=e=>{sn(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Gc=e=>{sn(t=>{let{value:n,cursorPosition:o}=t,r=o;if(e==="left"){for(;r>0&&xr(n[r-1]);)r--;for(;r>0&&!xr(n[r-1]);)r--}else{for(;r<n.length&&!xr(n[r]);)r++;for(;r<n.length&&xr(n[r]);)r++}return{...t,cursorPosition:r}})},qg=()=>{sn(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}})},Gg=()=>{sn(e=>{let{value:t,cursorPosition:n}=e,o=n;for(;o>0&&xr(t[o-1]);)o--;for(;o>0&&!xr(t[o-1]);)o--;let r=t.slice(n);return{...e,value:t.slice(0,o)+r,cursorPosition:o,commandIsPending:!1}})},xa=e=>{sn(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),o=t.value.slice(0,n),r=t.value.slice(n),s=e(o,t.commandMeta.autoCompletion),i=s+r,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},zg=()=>{sn(e=>({...e,commandIsPending:!0}))},ne=e=>{sn(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Vg=({addToHistory:e=!0,line:t})=>{sn(n=>{let o=t??n.value;return{...n,commandHistory:e&&o.trim()?[o,...n.commandHistory].slice(0,Hs):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}})},Kg=e=>{sn(t=>({...t,commandHistory:e.slice(0,Hs),commandHistoryIndex:-1}))},Yg=()=>{sn(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}})},Xg=()=>{sn(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},fe=()=>Ir,Ia=()=>{let[e,...t]=Ir.value.split(Wc);return t.join(Wc).trim()}});var P,BF,Vn=g(()=>{"use strict";Oe();xm();O();he();Fe();P={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavPreviousItemJump:"navPreviousItemJump",NavNextItemJump:"navNextItemJump",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MovePreviousItemJump:"movePreviousItemJump",MoveNextItemJump:"moveNextItemJump",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",OpenInEditor:"openInEditor",MarkDiffLine:"markDiffLine",CommentOnDiffLine:"commentOnDiffLine",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"},BF={[P.NavPreviousItem]:P.NavPreviousItemJump,[P.NavNextItem]:P.NavNextItemJump,[P.MovePreviousItem]:P.MovePreviousItemJump,[P.MoveNextItem]:P.MoveNextItemJump}});var Jg,G,zc=g(()=>{"use strict";O();Fo();Jg=e=>{let{context:t}=v().contextNode;if(!t)return G.None;switch(e){case I.EXIT:return G.Exit;case I.EXPORT:return G.Export;case I.INIT:return G.Init;case I.OPEN:return G.OpenProject;case I.DELETE:return G.Delete;case I.EDIT:return G.Edit;case I.COMMENT:return G.Comment;case I.HELP:return G.ViewHelp;case I.RE_OPEN_ISSUE:return G.ReopenIssue;case I.CLOSE_ISSUE:return G.CloseIssue;case I.TAG:return G.TagTicket;case I.UNTAG:return G.UntagTicket;case I.ASSIGN:return G.AssignUserToTicket;case I.UNASSIGN:return G.UnassignUserFromTicket;case I.NEW:return G.NewItem;case I.FILTER:return G.Filter;case I.MOVE:return G.Move;case I.PEEK:return G.Peek;case I.REPLAY:return G.Replay;case I.CONFIG:return G.Config;case I.YANK:return G.Yank;case I.SYNC:return G.Sync;default:return G.None}},G={Exit:"exit",Init:"init",OpenProject:"open-project",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export"}});import{Text as Qg}from"ink";import Zg,{useEffect as eh,useState as oS}from"react";var th,Ut,Er=g(()=>{"use strict";O();Je();th={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "],identity:["\u276F "]},Ut=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Ye(),o=th[n]??th.default,[r,s]=oS(0);if(eh(()=>{s(0)},[o]),eh(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%o.length)},500);return()=>clearInterval(c)},[e,o]),!e)return Zg.createElement(Qg,null,t);let i=o[r]??o[0]??t;return Zg.createElement(Qg,{color:k.accent,dimColor:r===1},i)}});import{Box as Vc,Text as rS}from"ink";import Ea from"react";var sS,Ht,$o=g(()=>{"use strict";Je();sS=(e,t,n,o)=>{let r=u=>Math.max(1,e[u]??1),s=n,i=n+1,c=r(n);for(;i<t&&c+r(i)<=o;)c+=r(i),i++;for(;s>0&&c+r(s-1)<=o;)s--,c+=r(s);return{start:s,end:i}},Ht=({children:e=[],height:t,selectedIndex:n,itemHeight:o=1,itemHeights:r,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),c=Math.max(1,Math.ceil(o)),u=Math.max(0,Math.min(n,e.length-1)),p=Math.max(1,Math.floor(i/c)),m=Math.max(0,e.length-p),{start:f,end:h}=r?sS(r,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},x=Math.max(1,h-f),E=e.slice(f,h),S=e.length>x,C=i,R=S?Math.max(1,Math.floor(x/e.length*C)):C,A=Math.max(0,C-R),L=Math.max(1,e.length-x),_=S?Math.floor(f/L*A):0;return Ea.createElement(Vc,{flexDirection:"row",height:i,width:"100%"},Ea.createElement(Vc,{flexDirection:"column",flexGrow:1,height:i},E),Ea.createElement(Vc,{flexDirection:"column",width:1,height:C},Array.from({length:C}).map((j,z)=>Ea.createElement(rS,{key:z,color:S&&z>=_&&z<_+R?k.accent:k.secondary},S?"\u2502":" "))))}});var nh,Kc,iS,Ra,Yc=g(()=>{"use strict";O();iS=()=>{let{eventLog:e=[]}=v();if(Kc&&nh===e)return Kc;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return nh=e,Kc=t,t},Ra=e=>iS().has(e)});import{Text as aS}from"ink";import lS from"react";var Rr,Sa=g(()=>{"use strict";dn();pe();Yc();ht();Rr=({id:e,isSelected:t,maxWidth:n})=>{let o=N.getContributor(e);if(!o)return;let r=o.name,s=n===void 0?r:Io(r,n);return lS.createElement(aS,{underline:t,color:nt(r)},"@"+s,Ra(e)?"":"\u2197")}});import{Text as cS}from"ink";import dS from"react";var Na,Xc=g(()=>{"use strict";pe();Je();dn();ht();Na=({id:e,isSelected:t,maxWidth:n})=>{let o=N.getTag(e);if(!o)return;let r=n===void 0?o.name:Io(o.name,n);return dS.createElement(cS,{underline:t,backgroundColor:nt(o.name),color:k.secondary}," "+r+" ")}});import{useEffect as uS,useState as mS}from"react";var pS,oh,wa,qs,fS,gS,Sr,Ca=g(()=>{"use strict";dn();pS=80,oh=1400,wa=new Set,qs=null,fS=e=>(wa.add(e),qs||(qs=setInterval(()=>{for(let t of wa)t()},pS)),()=>{wa.delete(e),wa.size===0&&qs&&(clearInterval(qs),qs=null)}),gS=()=>{let e=Date.now()%oh/oh;return e<.5?e*2:(1-e)*2},Sr=e=>{let[,t]=mS(0);return uS(()=>{if(e)return fS(()=>t(n=>n+1))},[e]),hm(gS())}});import{Box as Nr,Text as wr}from"ink";import It from"react";var hS,rh,vS,yS,sh,ih=g(()=>{"use strict";pe();Je();ht();Yc();mt();pr();Sa();Xc();Ca();hS=(e,t,n)=>{if(e.length<=t)return[e,null];let o=e.lastIndexOf(" ",t),r=o>0?o:t;return[e.slice(0,r),Io(e.slice(r).trim(),n)]},rh=3,vS=2,yS=(e,t)=>{let n=[],o=0;for(let[r,s]of e.entries()){let i=e.length-r-1,c=i>0?String(i).length+1:0;if(o+s.width+c>t)break;o+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},sh=({width:e,ticket:t,isSelected:n,isFlashing:o=!1})=>{let r=Sr(o),s=e-4,i=s-7-1,[c,u]=hS(Se(t.title),i,s),p=u?null:Io(Se(t.props.description),s)||null,m=yn(t),f=bn(t).map(R=>({...R,name:R.name})),h=Math.max(1,s-rh),x=N.getCommentsByIssue(t.id),E=x.length?String(x.length).length+2+1:0,{shown:S,hidden:C}=yS([...m.map(R=>({id:R.id,isTag:!0,width:Math.min(R.name.length,h)+rh})),...f.map(R=>({id:R.id,isTag:!1,width:Math.min(R.name.length,h)+vS+(Ra(R.id)?0:1)}))],s-E);return It.createElement(Nr,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:o?r:n?k.accent:k.secondary,justifyContent:"space-between"},It.createElement(Nr,{paddingLeft:1,paddingRight:1,flexDirection:"column"},It.createElement(Nr,{justifyContent:"space-between"},It.createElement(wr,{color:k.primary},c),It.createElement(wr,{color:k.secondary2,dimColor:!0},V(t.id))),u&&It.createElement(wr,{color:k.primary},u),p&&It.createElement(wr,{color:k.secondary2,dimColor:!0},p)),It.createElement(Nr,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},It.createElement(Nr,{flexDirection:"row"},S.map(R=>It.createElement(Nr,{paddingRight:1,key:R.id},R.isTag?It.createElement(Na,{id:R.id,maxWidth:h}):It.createElement(Rr,{id:R.id,maxWidth:h}))),C>0&&It.createElement(wr,{color:k.secondary2,dimColor:!0},"+",C)),x.length>0&&It.createElement(wr,{color:k.accent},"[",x.length,"]")))}});import{Box as jo,Text as Gs}from"ink";import Lt from"react";var bS,ah,lh=g(()=>{"use strict";Oe();pe();Je();dn();Er();Ca();bS=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,ah=({index:e,labelWidth:t,width:n,ticket:o,isSelected:r,isFlashing:s=!1,mode:i})=>{let c=Sr(s),u=(o.props.tags??[]).map(j=>N.getTag(j)).filter(j=>!!j),p=(o.props.assignees??[]).map(j=>N.getContributor(j)).map(j=>j&&{...j,name:j.name}).filter(j=>!!j),m=1,f=u.length*(1+m),h=p.length*(2+m),x=u.map(j=>Lt.createElement(jo,{key:j.id,paddingRight:m},Lt.createElement(Gs,{color:nt(j.name)},"\u25A0"))),E=p.map(j=>Lt.createElement(jo,{key:j.id,paddingRight:m},Lt.createElement(Gs,{color:El(j.name)},"@"+j.name.at(0)))),S=s?c:r?k.accent:i===b.MOVE?k.secondary:k.primary,C=N.getCommentsByIssue(o.id),R=C.length?String(C.length).length+2+m:0,A=C.length?Lt.createElement(jo,{paddingRight:m},Lt.createElement(Gs,{color:k.accent},"[",C.length,"]")):null,L=f+h+R,_=Math.max(1,n-t-L-(L>0?1:0));return Lt.createElement(jo,{justifyContent:"space-between"},Lt.createElement(jo,null,Lt.createElement(jo,{width:t},r?Lt.createElement(Ut,{isSelected:!0}):Lt.createElement(Gs,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),Lt.createElement(Gs,{wrap:"truncate",color:S},bS(o.title,_))),Lt.createElement(jo,null,x,E,A))}});import xS from"chalk";import{Box as Jc,Text as IS}from"ink";import xn from"react";var ES,ch,dh=g(()=>{"use strict";me();O();Je();Er();$o();ih();lh();Ca();ES=({swimlane:e,isSelected:t,width:n,height:o,isDense:r,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:p}=Ye(),m=u[e.id]??[],f=p?new Set(p.flashNodeIds):null,h=f?.has(e.id)??!1,x=Sr(h),E=`${e.title} ${xS.hex(k.secondary2).dim("("+m.length+")")}`,S=3,C=r?1:5,R=s&&i===-1,A=n-3-(r?1:0)-(R?2:0),L=Math.max(2,String(m.length).length+1),_=o-S-1,j=xn.createElement(Jc,{borderStyle:"round",borderColor:k.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:r?1:0},xn.createElement(Ut,{isSelected:t}),xn.createElement(IS,{bold:!0,color:h?x:t?k.accent:k.primary},E," ",e.readonly?"\u{1F512}":"")),z=(X,ue)=>{let ze=s&&i===ue;if(!U(X))return null;let q=f?.has(X.id)??!1;return r?xn.createElement(ah,{key:X.id,index:ue,labelWidth:L,width:A,ticket:X,isSelected:ze,isFlashing:q,mode:c}):xn.createElement(sh,{key:X.id,width:A,ticket:X,isSelected:ze,isFlashing:q})};return xn.createElement(Jc,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?k.accent:k.secondary,paddingRight:0,paddingLeft:r?1:0,height:o},j,xn.createElement(Jc,null,m.length>0&&xn.createElement(Ht,{selectedIndex:i,height:_,itemHeight:C},m.map(z)),R&&xn.createElement(Ut,{isSelected:!0})))},ch=xn.memo(ES)});var uh,mh,ph,Aa=g(()=>{"use strict";eo();uh=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},mh=(e,t,n)=>Be.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0}),ph=e=>e.action==="add.issue.comment"});var so,zs=g(()=>{"use strict";so=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:o,ms:r}of n){let s=Math.floor(t/r);if(s>=1)return`${s}${o} ago`}return"just now"}});import{Box as Ar,Text as jn}from"ink";import lt,{useEffect as RS,useMemo as SS,useRef as NS}from"react";import{decodeTime as fh}from"ulid";function hh({ticket:e,width:t,height:n}){let o=SS(()=>CS(e),[e]),r=NS([]);RS(()=>(gh(r.current),r.current=TS(e,o),()=>{gh(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=Ye(),c=Math.max(1,n-4),u=Math.max(12,t-32);return o.length===0?lt.createElement(Ar,{flexDirection:"column",width:t,height:n,padding:1},lt.createElement(jn,{color:k.primary},"No attachments yet."),lt.createElement(Ar,{paddingTop:1},lt.createElement(jn,{color:k.primary},"Attach images from the browser GUI"),lt.createElement(jn,{color:k.accent}," epiq gui "),lt.createElement(jn,{color:k.primary},"by dropping or pasting them."))):lt.createElement(Ar,{flexDirection:"column",width:t,height:n},lt.createElement(Ar,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:k.secondary,borderStyle:"single",paddingBottom:1},lt.createElement(jn,{color:k.secondary2},"Attachments (",o.length,") \u2014 enter to open"," ")),lt.createElement(Ht,{height:c,itemHeight:2,selectedIndex:s},o.map((p,m)=>{let f=m===s,h=p.name.length>u?p.name.slice(0,u-1)+"\u2026":p.name;return lt.createElement(Ar,{key:p.id,flexDirection:"row",paddingX:1,paddingBottom:1},lt.createElement(jn,{color:k.accent},f?"\u276F ":" "),lt.createElement(Ar,{paddingLeft:1},lt.createElement(jn,{color:k.secondary2},`#${m+1} `),lt.createElement(jn,{color:f?k.accent:k.primary},h),lt.createElement(jn,{color:k.secondary2}," "+kS(p.bytes)+" "+so(ct(p.id)))))})))}var wS,CS,gh,AS,TS,kS,vh=g(()=>{"use strict";xt();ft();zs();me();w();pe();eo();O();Je();oo();$o();wS=e=>Te(e,"attachments"),CS=e=>N.getAttachmentsByIssue(e.id).sort((t,n)=>fh(t.id)-fh(n.id)),gh=e=>{for(let t of e)N.deleteNode(t.id)},AS=(e,t,n)=>Be.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),TS=(e,t)=>{let n=N.getNode(wS(e.id));if(!n||!ot(n))return[];let o=t.map((r,s)=>AS(r,s,n.id)).map(r=>N.createNode(r)).filter(Dt).map(({value:r})=>r).filter(ot);return t.length>0&&v().selectedIndex<0&&H.navigate({contextNode:n,selectedIndex:0}),o},kS=e=>`${Math.max(1,Math.round(e/1024))} KB`});var bh,Qc,MS,yh,Vs,xh,Ih,LS,Eh,Rh,Zc,PS,Sh,Ta=g(()=>{"use strict";bh=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,Qc=e=>e.replace(bh,""),MS=e=>`<!-- epiq-diff-comment:${JSON.stringify(e).replaceAll(">","\\u003e")} -->`,yh=e=>e==="additions"||e==="deletions",Vs=e=>{let t=bh.exec(e);if(!t?.[1])return null;let n;try{n=JSON.parse(t[1])}catch{return null}let o=n;return typeof o?.filePath!="string"||typeof o.start!="number"||typeof o.end!="number"||typeof o.note!="string"||!yh(o.side)||!yh(o.endSide)||o.sha!==void 0&&typeof o.sha!="string"||o.issueRef!==void 0&&typeof o.issueRef!="string"?null:o},xh=/```\n([\s\S]*?)\n?```\s*$/,Ih=e=>xh.exec(e)?.[1]??null,LS=/`[^`\n]+`[^\n]*\n?$/,Eh=e=>Qc(e).replace(xh,"").replace(LS,"").trim(),Rh=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})`},Zc=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${Rh(e)}`,PS=e=>{let t=e.split(`
|
|
80
|
+
`),n=t.filter(o=>o.trim()!=="").reduce((o,r)=>{let s=/^[ \t]*/.exec(r)?.[0].length??0;return o===null?s:Math.min(o,s)},null);return n?t.map(o=>o.slice(n)).join(`
|
|
81
|
+
`):e},Sh=({snippet:e,...t})=>{let n=t.note.trim();return[...n?[n,""]:[],MS({...t,note:n}),`\`${t.filePath}\` ${Rh(t)}`,"```",PS(e),"```"].join(`
|
|
82
|
+
`)}});var DS,Ks,OS,FS,_S,BS,Ys,ed,wh,Nh,Ch,ka=g(()=>{"use strict";Ta();DS=(e,t)=>{let n=Math.max(1,Math.floor(t)),o=e.split(/\s+/).filter(Boolean);if(o.length===0)return[""];let r=[],s="";for(let i of o){let c=i;for(;c.length>n;)s&&(r.push(s),s=""),r.push(c.slice(0,n)),c=c.slice(n);s?s.length+1+c.length<=n?s=`${s} ${c}`:(r.push(s),s=c):s=c}return s&&r.push(s),r},Ks=e=>{let t=e.split("`");return t.length%2===0?[{text:e}]:t.map((n,o)=>o%2===1?{text:n,code:!0}:{text:n}).filter(n=>n.text.length>0)},OS=/!\[([^\]]*)\]\([^)]*\)/g,FS=e=>e.replace(OS,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),_S=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),BS=4,Ys=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(BS)),ed=e=>{let t=!1;return e.map(Ys).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let o=Vs(n);if(o)return{kind:"caption",text:Zc(o)};let r=FS(n);if(r.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(r);return s?{kind:"heading",spans:Ks(s[1]??"")}:{kind:"text",spans:Ks(r)}})},wh=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Nh=(e,t)=>{let n=[];for(let o of ed(e))if(o.kind!=="fence"){if(o.kind==="blank"){n.length>0&&n[n.length-1]?.kind!=="blank"&&n.push(o);continue}if(o.kind==="code"){for(let r of wh(o.text,t))n.push({kind:"code",text:r});continue}if(o.kind==="caption"){n.push(o);continue}for(let r of DS(_S(o.spans),t))n.push({kind:o.kind,spans:Ks(r)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},Ch=(e,t)=>{let n=Vs(e),o=n?Ih(e):null;if(!n||o===null)return Nh(Qc(e).split(`
|
|
83
|
+
`),t);let r=Eh(e),s=o.split(`
|
|
84
|
+
`).map(Ys),i=n.side===n.endSide?n.start:void 0,c=i===void 0?0:String(i+s.length-1).length+3;return[...r?[...Nh(r.split(`
|
|
85
|
+
`),t),{kind:"blank"}]:[],{kind:"caption",text:Zc(n)},...s.flatMap((u,p)=>wh(u,Math.max(1,t-c)).map((m,f)=>({kind:"code",text:m,number:i===void 0||f>0?void 0:i+p})))]}});import{Box as Ah,Text as Uo}from"ink";import Wt from"react";var Th,td,kh,nd=g(()=>{"use strict";Je();Th=({spans:e,bold:t,wrap:n})=>Wt.createElement(Uo,{color:k.primary,bold:t,wrap:n},e.map((o,r)=>o.code?Wt.createElement(Uo,{key:r,color:k.yellow},o.text):Wt.createElement(Uo,{key:r},o.text))),td=({line:e,width:t,gutter:n=0,wrap:o})=>{switch(e.kind){case"blank":return Wt.createElement(Uo,null," ");case"fence":return Wt.createElement(Uo,{color:k.secondary2},"```");case"caption":return Wt.createElement(Uo,{color:k.accent,wrap:o},e.text);case"heading":return Wt.createElement(Th,{spans:e.spans,bold:!0,wrap:o});case"text":return Wt.createElement(Th,{spans:e.spans,wrap:o});case"code":{let r=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return Wt.createElement(Uo,{backgroundColor:k.secondary,color:k.primary,wrap:o},r,e.text.padEnd(Math.max(0,t-r.length)))}}},kh=({lines:e,width:t})=>{let n=e.flatMap(r=>r.kind==="code"&&r.number!==void 0?[r.number]:[]),o=n.length>0?String(Math.max(...n)).length+3:0;return Wt.createElement(Ah,{flexDirection:"column"},e.map((r,s)=>Wt.createElement(Ah,{key:s},Wt.createElement(td,{line:r,width:t,gutter:o}))))}});import{Box as io,Text as ao}from"ink";import qe,{useEffect as $S,useMemo as Mh,useRef as jS}from"react";import{decodeTime as Lh}from"ulid";function Dh({ticket:e,width:t,height:n}){let o=Mh(()=>WS(e),[e]),r=jS([]);$S(()=>(Ph(r.current),r.current=qS(e,o),()=>{Ph(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=Ye(),c=Math.max(1,n-4),u=Math.max(20,t-8),p=Mh(()=>o.map(f=>{let h=Ch(f.md,u);return h.length>0?h:[{kind:"blank"}]}),[o,u]),m=p.map(f=>f.length+US);return o.length===0?qe.createElement(io,{flexDirection:"column",width:t,height:n,padding:1},qe.createElement(ao,{color:k.primary},"No comments yet."),qe.createElement(io,{paddingTop:1},qe.createElement(ao,{color:k.primary},"Use"),qe.createElement(ao,{color:k.accent}," :comment "),qe.createElement(ao,{color:k.primary},"to add the first one."))):qe.createElement(io,{flexDirection:"column",width:t,height:n},qe.createElement(io,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:k.secondary,borderStyle:"single",paddingBottom:1},qe.createElement(ao,{color:k.secondary2},"Comments (",o.length,") ")),qe.createElement(Ht,{height:c,itemHeights:m,selectedIndex:s},o.map((f,h)=>{let x=h===s;return qe.createElement(io,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:k.secondary,borderStyle:"single"},qe.createElement(io,{flexDirection:"row",paddingBottom:1},qe.createElement(ao,{color:k.accent},x?"\u276F ":" "),qe.createElement(io,{paddingLeft:1},qe.createElement(ao,{color:k.secondary2},`#${h+1} `),qe.createElement(Rr,{id:f.authorId}),qe.createElement(ao,{color:k.secondary2}," "+so(ct(f.id))))),qe.createElement(io,{paddingLeft:3,paddingBottom:1},qe.createElement(kh,{lines:p[h]??[],width:u})))})))}var US,HS,WS,Ph,qS,Oh=g(()=>{"use strict";xt();ft();zs();me();w();pe();O();Je();oo();Sa();$o();Aa();ka();nd();US=4,HS=e=>Te(e,"comments"),WS=e=>N.getCommentsByIssue(e.id).sort((t,n)=>Lh(t.id)-Lh(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,md:t.md})),Ph=e=>{for(let t of e)N.deleteNode(t.id)},qS=(e,t)=>{let n=N.getNode(HS(e.id));if(!n||!ot(n))return[];let o=t.map((r,s)=>mh(r,s,n.id)).map(N.createNode).filter(Dt).map(({value:r})=>r).filter(ls);return t.length>0&&v().selectedIndex<0&&H.navigate({contextNode:n,selectedIndex:0}),o}});var lo,Xs,Tr=g(()=>{"use strict";w();ee();lo=e=>{let t=we(e??process.cwd());return a(t)?l(t.message):d("Resolved Epiq repo root",t.value)},Xs=e=>/^[0-9a-f]{7,40}$/i.test(e)});var kr,Fh,_h,Mr,Bh,Lr,od=g(()=>{"use strict";Ke();w();Jt();mt();Tr();kr="",Fh="",_h=5e3,Mr=null,Bh=async(e={})=>{let t=lo(e.repoRoot);if(a(t))return l(t.message);let n=At(t.value);if(a(n))return l(n.message);let o=e.start===void 0&&e.end===void 0;if(o&&Mr&&Mr.repoRoot===t.value&&Mr.stateBranch===n.value.stateBranch&&Date.now()-Mr.fetchedAt<_h)return d("Computed commit timeline",Mr.result);let r=await W({cwd:t.value,args:["log","--branches","--not",n.value.stateBranch,...e.start!==void 0?[`--since=@${Math.floor(e.start/1e3)}`]:[],...e.end!==void 0?[`--until=@${Math.floor(e.end/1e3)}`]:[],"--shortstat",`--format=${Fh}%H${kr}%at${kr}%an${kr}%ae${kr}%s`]});if(a(r))return l(r.message);let s=r.value.stdout.split(Fh).filter(i=>i.trim().length>0).map(i=>{let[c,...u]=i.split(`
|
|
86
|
+
`),[p,m,f,h,...x]=(c??"").split(kr);if(!p||!m)return null;let E=u.join(" "),S=Number(/(\d+) insertion/.exec(E)?.[1]??0),C=Number(/(\d+) deletion/.exec(E)?.[1]??0);return{sha:p,time:Number(m)*1e3,author:f??"unknown",authorEmail:h??"",subject:x.join(kr),linesChanged:S+C,insertions:S,deletions:C}}).filter(i=>i!==null).filter(i=>(e.start===void 0||i.time>=e.start)&&(e.end===void 0||i.time<=e.end));return o&&(Mr={repoRoot:t.value,stateBranch:n.value.stateBranch,fetchedAt:Date.now(),result:s}),d("Computed commit timeline",s)},Lr=async e=>{let t=e.ref.trim();if(!t)return l("ref must not be empty");if(t.length!==7)return l(`"${t}" is ${t.length} characters; a ref is ${7}. Read it off the issue rather than slicing the id by hand.`);let n=await Bh({repoRoot:e.repoRoot});if(a(n))return l(n.message);let o=`${t.toUpperCase()} `,r=c=>c.subject.toUpperCase().startsWith(o),s=n.value,i=[];for(let[c,u]of s.entries()){if(!r(u))continue;let p=s[c+1];i.push({...u,precedingSha:p&&r(p)?p.sha:null})}return d("Matched commits by ref",i)}});var rd,$h=g(()=>{"use strict";Ke();w();Tr();od();rd=async e=>{if(!Xs(e.sha))return l("Invalid commit sha");let t=lo(e.repoRoot);if(a(t))return l(t.message);let n=await W({cwd:t.value,args:["show","--no-ext-diff","--no-color","--patch","--find-renames","--format=",e.sha]});return a(n)?l(n.message):d("Read commit patch",n.value.stdout)}});var GS,Ma,jh,id,sd,ad,La,ld,Uh,zS,Hh,Wh,qh,cd,Pa=g(()=>{"use strict";Ta();GS=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/,Ma=e=>{if(!e.startsWith('"')||!e.endsWith('"'))return e;let t=e.slice(1,-1),n="";for(let o=0;o<t.length;o++){if(t[o]!=="\\"){n+=t[o];continue}let r=t[++o];if(r==="n")n+=`
|
|
87
|
+
`;else if(r==="t")n+=" ";else if(r==='"'||r==="\\")n+=r;else if(r&&/[0-7]/.test(r)){let s=t.slice(o,o+3);n+=String.fromCharCode(parseInt(s,8)),o+=2}else r!==void 0&&(n+=r)}try{return decodeURIComponent(escape(n))}catch{return n}},jh=e=>{let t=Ma(e.trim());return t==="/dev/null"?null:t.replace(/^[ab]\//,"")},id=e=>{let t=[],n=null,o=0,r=0,s=()=>{let i={path:"",oldPath:null,binary:!1,added:0,removed:0,lines:[]};return t.push(i),i};for(let i of e.split(`
|
|
88
|
+
`)){if(i.startsWith("diff --git ")){n=s();let m=i.slice(11),f=m.lastIndexOf(" b/");f!==-1&&(n.path=Ma(m.slice(f+1)).replace(/^b\//,""));continue}if(!n){if(!i.trim())continue;n=s()}let c=n,u=c.lines.length===0;if(u&&i.startsWith("--- ")){let m=jh(i.slice(4));m&&(c.oldPath=m);continue}if(u&&i.startsWith("+++ ")){let m=jh(i.slice(4));m&&(c.path=m);continue}if(u&&i.startsWith("rename from ")){c.oldPath=Ma(i.slice(12));continue}if(u&&i.startsWith("rename to ")){c.path=Ma(i.slice(10));continue}if(u&&(i.startsWith("Binary files ")||i.startsWith("GIT binary patch"))){c.binary=!0,c.lines.push({kind:"note",text:"Binary file"});continue}let p=GS.exec(i);if(p){o=Number(p[1]),r=Number(p[3]),c.lines.push({kind:"hunk",text:i});continue}if(!u){if(i.startsWith("\\")){c.lines.push({kind:"note",text:i.slice(1).trim()});continue}if(i.startsWith("+")){c.added++,c.lines.push({kind:"added",text:i.slice(1),newLine:r++});continue}if(i.startsWith("-")){c.removed++,c.lines.push({kind:"removed",text:i.slice(1),oldLine:o++});continue}if(i.startsWith(" ")){c.lines.push({kind:"context",text:i.slice(1),oldLine:o++,newLine:r++});continue}i===""&&c.lines.push({kind:"context",text:"",oldLine:o++,newLine:r++})}}for(let i of t)!i.path&&i.oldPath&&(i.path=i.oldPath);return t.filter(i=>i.path!=="")},sd=e=>e.oldPath&&e.oldPath!==e.path?e.oldPath:null,ad=e=>e.flatMap(t=>[{kind:"file",text:`${sd(t)?`${sd(t)} \u2192 `:""}${t.path}`,file:t},...t.lines]),La=e=>{let t="",n=-1;return e.map(o=>(o.kind==="file"&&(t=o.file.path),o.kind==="hunk"&&n++,{file:t,hunk:n}))},ld=(e,t,n)=>{let o=t.map(i=>Vs(i.md)).filter(i=>i!==null&&i.sha===n&&i.side==="additions");if(o.length===0)return new Set;let r=La(e),s=new Set;return e.forEach((i,c)=>{let u=i.newLine;if(u===void 0)return;let p=r[c]?.file;o.some(m=>m.filePath===p&&m.start<=u&&u<=m.end)&&s.add(c)}),s},Uh=(e,t)=>e===t?`line:${e}`:`lines:${e}-${t}`,zS=/^lines?:(\d+)(?:-(\d+))?(?:\s+|$)/,Hh=e=>{let t=zS.exec(e);if(!t)return null;let n=Number(t[1]),o=t[2]===void 0?n:Number(t[2]);return{start:Math.min(n,o),end:Math.max(n,o),note:e.slice(t[0].length)}},Wh=(e,t)=>La(e)[t]?.file??null,qh=(e,t,n,o)=>{let r=La(e),s=u=>e.findIndex((p,m)=>r[m]?.file===t&&(p.kind==="added"||p.kind==="context")&&p.newLine===u),i=s(n),c=s(o);return i===-1||c===-1?{ok:!1,reason:`${t} has no line ${i===-1?n:o} on the new side`}:cd(e,i,c)},cd=(e,t,n)=>{let[o,r]=t<=n?[t,n]:[n,t],s=e[o],i=e[r];if(!s||!i)return{ok:!1,reason:"That line is not in the diff"};let c=h=>(h.kind==="added"||h.kind==="context")&&h.newLine!==void 0;if(!c(s)||!c(i))return{ok:!1,reason:"Comments anchor to the new side: pick an added or unchanged line"};let u=La(e),p=u[o],m=u[r];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(o,r+1).filter(c);return{ok:!0,value:{filePath:p.file,start:f[0].newLine,end:f[f.length-1].newLine,snippet:f.map(h=>h.text).join(`
|
|
89
|
+
`)}}}});import{spawn as VS,spawnSync as KS}from"node:child_process";import YS from"node:os";import Gh from"node:path";import{ulid as XS}from"ulid";function dd(e){let t=[],n="",o=!1,r=null;for(let s of e.trim()){if(r){s===r?r=null:n+=s;continue}if(s==='"'||s==="'"){r=s,o=!0;continue}if(/\s/.test(s)){o&&t.push(n),n="",o=!1;continue}n+=s,o=!0}return o&&t.push(n),t}function JS(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Da(){let{preferredEditor:e}=le(),t=[e?JS(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function ud(e){let[t=""]=dd(e);return/(^|\/)code(-insiders)?$/.test(t)}function zh(e,t){let[n="",...o]=dd(e);return{command:n,args:[...o,...t]}}function Vh(e,t){return zh(e,ud(e)?["--wait",t]:[t])}function QS(e,t,n,o="new"){return zh(e,[o==="new"?"--new-window":"--reuse-window","--diff",t,n])}function Kh(e){let t=Gh.join(YS.tmpdir(),"epiq");Ze.mkDir(t);let n=Gh.join(t,XS());Ze.writeToFile(n,e??"");let o=Da();for(let r of o){let{command:s,args:i}=Vh(r,n);if(!s)continue;let c=KS(s,i,{stdio:"inherit"});if(!c.error&&c.status===0){let u=Ze.readFile(n);if(u==null)return l("Unable to read edited file");let p=u.replace(/\r?\n$/,"");return d("Successfully edited",p)}}return l("Unable to open editor")}function eN(e){let[t=""]=dd(e),n=t.split("/").pop()??t;return ZS.has(n)}function Yh({command:e,args:t},n){return new Promise(o=>{if(!e){o(l(`"${n}" is not a usable editor command`));return}let r=VS(e,t,{stdio:"ignore",detached:!0}),s=!1,i=u=>{s||(s=!0,clearTimeout(c),o(u))};r.on("error",u=>i(l(u.message))),r.on("exit",u=>{i(u===0?d("Opened editor",!0):l(`"${n}" exited with code ${u}`))});let c=setTimeout(()=>{r.unref(),i(d("Opened editor",!0))},tN)})}function nN(e,t){return eN(e)?Promise.resolve(l(`"${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}`)):Yh(Vh(e,t),e)}function md(e,t,n,o="new"){return Yh(QS(e,t,n,o),e)}async function Xh(e){let t=Da();if(t.length===0)return l("No editor configured (preferredEditor, VISUAL, or EDITOR)");let n=l("Unable to open editor");for(let o of t){let r=await nN(o,e);if(!a(r))return r;n=r,logger.error(`Failed to open editor "${o}" for ${e}: ${r.message}`)}return n}var ZS,tN,pd=g(()=>{"use strict";w();Fe();ha();ZS=new Set(["vim","vi","nvim","nano","pico","ed"]);tN=600});import{chmodSync as oN,existsSync as rN,lstatSync as sN,mkdirSync as iN}from"node:fs";import aN from"node:os";import lN from"node:path";var Js,fd=g(()=>{"use strict";w();Js=(...e)=>{let t=lN.join(aN.tmpdir(),"epiq",...e);try{return rN(t)&&sN(t).isSymbolicLink()?l(`Refusing to write through a symlink at ${t}`):(iN(t,{recursive:!0,mode:448}),oN(t,448),d("Prepared private temp dir",t))}catch(n){return l(`Unable to prepare ${t}: ${n instanceof Error?n.message:String(n)}`)}}});import{existsSync as gd}from"node:fs";import{chmod as hd}from"node:fs/promises";import Oa from"node:path";var cN,dN,uN,Jh,mN,pN,vd,Qh=g(()=>{"use strict";Ke();pd();w();ha();fd();Tr();cN=async(e,t)=>{let n=await W({cwd:e,args:["show",t]});if(a(n))return l(n.message);let o=Js("commit-diffs");if(a(o))return l(o.message);let r=Oa.join(o.value,`${t}.diff`);return gd(r)||(Ze.writeToFile(r,n.value.stdout),await hd(r,292)),Xh(r)},dN=12,uN=800,Jh=async(e,t,n)=>{let o=await W({cwd:e,args:["show",`${t}:${n}`]});return a(o)?"":o.value.stdout},mN=async(e,t)=>{let n=await W({cwd:e,args:["diff","--name-only",`${t}~1`,t]});if(a(n))return l(n.message);let o=n.value.stdout.split(`
|
|
90
|
+
`).map(r=>r.trim()).filter(Boolean);return o.length===0?l("No changed files found for this commit"):d("Listed changed files",o)},pN=async(e,t,n)=>{let o=await mN(e,t);if(a(o))return l(o.message);let r=o.value;if(r.length>dN)return l(`Commit touches ${r.length} files \u2014 too many for a side-by-side view`);let s=Js("commit-diffs",t);if(a(s))return l(s.message);let i=s.value,c=await Promise.all(r.map(async(h,x)=>{let[E,S]=await Promise.all([Jh(e,`${t}~1`,h),Jh(e,t,h)]),C=Oa.basename(h),R=Oa.join(i,String(x),"before",C),A=Oa.join(i,String(x),"after",C);return gd(R)||(Ze.writeToFile(R,E),await hd(R,292)),gd(A)||(Ze.writeToFile(A,S),await hd(A,292)),{beforePath:R,afterPath:A}})),[u,...p]=c;if(!u)return l("No changed files found for this commit");let m=await md(n,u.beforePath,u.afterPath,"new");if(a(m)||p.length===0)return m;await new Promise(h=>setTimeout(h,uN));let f=await Promise.all(p.map(({beforePath:h,afterPath:x})=>md(n,h,x,"reuse")));for(let h of f)a(h)&&logger.error(`Failed to open an additional diff tab for ${t}: ${h.message}`);return m},vd=async e=>{if(!Xs(e.sha))return l("Invalid commit sha");let t=lo(e.repoRoot);if(a(t))return l(t.message);let n=t.value,o=Da()[0];if(o&&ud(o)){let r=await pN(n,e.sha,o);if(!a(r))return r;logger.error(`Side-by-side diff failed for ${e.sha}, falling back to unified diff: ${r.message}`)}return cN(n,e.sha)}});var Qs=g(()=>{"use strict";Tr();od();$h();Pa();Qh()});var Fa,Pr,yd=g(()=>{"use strict";w();eo();O();Zo();pe();Fa=(e,t,n)=>{let o=[],r=Gi(()=>{for(let s=0;s<t;s++){let i=Ct(BigInt(s+1));if(!Dt(i))continue;let c=N.createNode(Be.text({id:n(s),name:`Line ${s+1}`,parentNodeId:e,rank:i.value,readonly:!0,isVirtual:!0}));Dt(c)&&o.push(c.value)}});return a(r)&&logger.error(`Line nodes: ${r.message}`),o},Pr=e=>{N.deleteNodes(e.map(t=>t.id))}});import{useSyncExternalStore as fN}from"react";var Ba,_a,bd,Zh,xd,$a,ev,Ho,Id,tv,co,ja=g(()=>{"use strict";O();Ba=null,_a=null,bd=new Set,Zh=()=>{for(let e of bd)e()},xd=e=>{Ba=e,Zh()},$a=()=>Ba,ev={mark:null},Ho=e=>{_a=e,ev={mark:e},Zh()},Id=e=>_a&&_a.sha===e?_a.row:null,tv=()=>fN(e=>(bd.add(e),()=>{bd.delete(e)}),()=>ev),co=()=>{let{contextNode:e}=v();return Ba&&Ba.sha===e.id?e.id:null}});var nv=g(()=>{"use strict"});import{Box as an,Text as Un}from"ink";import De,{useEffect as Ed,useMemo as ov,useRef as hN,useState as vN}from"react";import yN from"string-width";function iv({ticket:e,sha:t,subject:n,width:o,height:r}){let[s,i]=vN({state:"loading"});Ed(()=>{let L=!0;return i({state:"loading"}),rd({sha:t}).then(_=>{L&&i(a(_)?{state:"failed",message:_.message}:{state:"loaded",rows:ad(id(_.value))})}),()=>{L=!1}},[t]);let c=s.state==="loaded"?s.rows:null,u=c!==null&&c.length>4e3,p=hN([]);Ed(()=>(Pr(p.current),p.current=c&&!u?Fa(t,c.length,L=>Rd(t,L)):[],()=>{Pr(p.current),p.current=[]}),[t,c,u]),Ed(()=>(xd(c?{sha:t,rows:c}:null),Ho(null),()=>{xd(null),Ho(null)}),[t,c]);let{selectedIndex:m}=Ye(),{mark:f}=tv(),h=ov(()=>c?ld(c,N.getCommentsByIssue(e.id),t):new Set,[c,t,e]),x=f&&f.sha===t?f.row:null,E=L=>x!==null&&L>=Math.min(x,m)&&L<=Math.max(x,m),S=ov(()=>c?Math.max(5,c.reduce((L,_)=>Math.max(L,sv(_).length),0)+2):5,[c]),C=Math.max(1,r-4),R=Math.max(8,o-S-6);if(s.state!=="loaded")return De.createElement(an,{flexDirection:"column",width:o,height:r,padding:1},De.createElement(Un,{color:k.primary},s.state==="loading"?"Reading the diff\u2026":`Could not read the diff: ${s.message}`));let A=L=>De.createElement(an,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:k.secondary,borderStyle:"single",paddingBottom:1},De.createElement(Un,{color:k.secondary2,wrap:"truncate-end"},Eo(`${t.slice(0,7)} ${n} \u2014 ${L}`,Math.max(8,o-6))));return s.rows.length===0?De.createElement(an,{flexDirection:"column",width:o,height:r},A("no changes"),De.createElement(an,{paddingX:1},De.createElement(Un,{color:k.primary},"This commit changed no files."))):u?De.createElement(an,{flexDirection:"column",width:o,height:r},A("too large to draw here"),De.createElement(an,{paddingX:1,flexDirection:"column"},De.createElement(Un,{color:k.primary},`${s.rows.length.toLocaleString()} lines of diff.`),De.createElement(Un,{color:k.secondary2},"Press o to open it in your editor."))):De.createElement(an,{flexDirection:"column",width:o,height:r},A(x===null?"enter to comment on a line, s to start a range, o editor, q back":"move to the other end, then enter to comment \u2014 s clears the mark"),De.createElement(Ht,{scrollByOne:!0,height:C,selectedIndex:m,itemHeight:1},s.rows.map((L,_)=>{let j=_===m,z=bN(L.kind);if(L.kind==="file")return De.createElement(an,{key:Rd(t,_),paddingX:1},De.createElement(Un,{backgroundColor:k.secondary,color:j?k.accent:z,bold:!0,wrap:"truncate-end"},rv(` ${Eo(Ys(L.text),R)}`,R+S+1)));let X=E(_),ue=`${xN(L.kind)}${Eo(Ys(L.text),R)}`;return De.createElement(an,{key:Rd(t,_),paddingX:1},De.createElement(an,{flexShrink:0},De.createElement(Un,{color:j||X?k.accent:k.secondary2,dimColor:!j&&!X,wrap:"truncate-end"},`${j?"\u276F":"\xA0"}${X?"\u258C":"\xA0"}${sv(L).padStart(S-2,"\xA0")}`)),De.createElement(an,{flexShrink:0},De.createElement(Un,{color:k.yellow,wrap:"truncate-end"},h.has(_)?"\u2502":"\xA0")),De.createElement(Un,{color:j?k.accent:z,backgroundColor:j||X?k.secondary:void 0,wrap:"truncate-end"},j||X?rv(ue,R+1):ue))})))}var Rd,bN,rv,xN,sv,av=g(()=>{"use strict";Qs();pe();w();yd();ja();O();Je();nv();ka();ht();$o();Rd=(e,t)=>`${e}::patch::${t}`,bN=e=>{switch(e){case"added":return k.green;case"removed":return k.red;case"hunk":return k.accent;case"file":return k.primary;default:return k.secondary2}},rv=(e,t)=>{let n=yN(e);return n>=t?e:e+"\xA0".repeat(t-n)},xN=e=>e==="added"?"+":e==="removed"?"-":" ",sv=e=>e.kind==="file"||e.kind==="hunk"||e.kind==="note"||e.newLine===void 0?"":String(e.newLine)});import{Box as Wo,Text as In}from"ink";import Ge,{useEffect as lv,useRef as IN,useState as EN}from"react";function dv({ticket:e,width:t,height:n}){let[o,r]=EN({state:"loading"}),s=V(e.id);lv(()=>{let E=!0;return r({state:"loading"}),Lr({ref:s}).then(S=>{E&&r(a(S)?{state:"failed",message:S.message}:{state:"loaded",commits:S.value})}),()=>{E=!1}},[s]);let i=IN([]),c=o.state==="loaded"?o.commits:null;lv(()=>(cv(i.current),i.current=c?NN(e,c):[],()=>{cv(i.current),i.current=[]}),[e,c]);let{selectedIndex:u,contextNode:p}=Ye(),m=c?.find(E=>E.sha===p.id)??null,h=Math.max(1,n-4),x=Math.max(12,t-34);return o.state!=="loaded"?Ge.createElement(Wo,{flexDirection:"column",width:t,height:n,padding:1},Ge.createElement(In,{color:k.primary},o.state==="loading"?"Reading commits\u2026":`Could not read commits: ${o.message}`)):m?Ge.createElement(iv,{ticket:e,sha:m.sha,subject:m.subject,width:t,height:n}):o.commits.length===0?Ge.createElement(Wo,{flexDirection:"column",width:t,height:n,padding:1},Ge.createElement(In,{color:k.primary},"No commits reference this ticket."),Ge.createElement(Wo,{paddingTop:1},Ge.createElement(In,{color:k.primary},"Commits are matched by the"),Ge.createElement(In,{color:k.accent},` ${s} `),Ge.createElement(In,{color:k.primary},"prefix on their subject line."))):Ge.createElement(Wo,{flexDirection:"column",width:t,height:n},Ge.createElement(Wo,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:k.secondary,borderStyle:"single",paddingBottom:1},Ge.createElement(In,{color:k.secondary2},`Diff (${o.commits.length}) \u2014 enter to read, o to open in your editor `)),Ge.createElement(Ht,{height:h,itemHeight:2,selectedIndex:u},o.commits.map((E,S)=>{let C=S===u,R=E.subject.length>x?E.subject.slice(0,x-1)+"\u2026":E.subject;return Ge.createElement(Wo,{key:E.sha,flexDirection:"row",paddingX:1,paddingBottom:1},Ge.createElement(In,{color:k.accent},C?"\u276F ":" "),Ge.createElement(Wo,{paddingLeft:1},Ge.createElement(In,{color:k.secondary2},`${E.sha.slice(0,7)} `),Ge.createElement(In,{color:C?k.accent:k.primary},R),Ge.createElement(In,{color:k.secondary2},` ${wN(E)} ${so(E.time)}`)))})))}var RN,cv,SN,NN,wN,uv=g(()=>{"use strict";xt();Qs();me();w();pe();eo();O();Je();zs();mt();oo();av();$o();RN=e=>Te(e,"diff"),cv=e=>{for(let t of e)N.deleteNode(t.id)},SN=(e,t,n)=>Be.field({id:e.sha,name:e.subject,parentNodeId:n,rank:String(t).padStart(6,"0"),childRenderAxis:"vertical",isVirtual:!0}),NN=(e,t)=>{let n=N.getNode(RN(e.id));if(!n||!ot(n))return[];let o=t.map((r,s)=>SN(r,s,n.id)).map(r=>N.createNode(r)).filter(Dt).map(({value:r})=>r).filter(ot);return t.length>0&&v().selectedIndex<0&&v().contextNode.id===n.id&&H.navigate({contextNode:n,selectedIndex:0}),o},wN=e=>`+${e.insertions} -${e.deletions}`});import{Box as Ua,Text as CN}from"ink";import Hn from"react";var mv,pv=g(()=>{"use strict";me();pe();sr();O();Je();Sa();Er();Xc();mv=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:o}=Ye(),{title:r}=t,s=t.parentNodeId?N.getNode(t.parentNodeId):void 0,i=s&&U(s)?r===Ce.ASSIGNEES?s.props.assignees??[]:r===Ce.TAGS?(s.props.tags??[]).filter(c=>N.getTag(c)):[]:[];return Hn.createElement(Ua,{alignItems:"center",paddingTop:1},Hn.createElement(Ua,{minWidth:12},Hn.createElement(Ut,{isSelected:n}),Hn.createElement(CN,{color:n?k.accent:k.secondary2},r,":")),Hn.createElement(Ua,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let p=o.id===t.id&&u===e;return Hn.createElement(Ua,{key:`${r}-${c}`,paddingRight:2,minHeight:1},Hn.createElement(Ut,{isSelected:p}),r===Ce.ASSIGNEES?Hn.createElement(Rr,{isSelected:p,id:c}):r===Ce.TAGS?Hn.createElement(Na,{isSelected:p,id:c}):null)})))}});var Sd,fv,Nd,wd=g(()=>{"use strict";Sd=e=>Math.max(5,String(Math.max(e,1)).length+3),fv=(e,t)=>Math.max(0,e-6-Sd(t)),Nd=(e,t=0,n=0)=>Math.max(1,e-5-2*t-(n>0?1+n:0))});import{Box as Dr,Text as Cd}from"ink";import qt,{useEffect as AN,useMemo as Ad,useRef as TN}from"react";var kN,gv,Td,hv=g(()=>{"use strict";yd();O();Je();ht();wd();Er();$o();nd();ka();kN="\u2029",gv=(e,t)=>`${e}::inline-line::${t}`,Td=({id:e,label:t,text:n,rows:o,selected:r,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=Ye(),u=Ad(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),p=Ad(()=>u.join("\0"),[u]),m=TN([]);AN(()=>(Pr(m.current),m.current=Fa(e,u.length,S=>gv(e,S)),()=>{Pr(m.current),m.current=[]}),[e,p]);let f=Sd(u.length),h=fv(s,u.length),E=Ad(()=>ed(u).map(S=>{if(S.kind==="code"||S.kind==="caption")return{...S,text:Eo(S.text,h)};if(S.kind==="text"||S.kind==="heading"){let C=S.spans.map(R=>R.code?`\`${R.text}\``:R.text).join("");return{...S,spans:Ks(Eo(C,h))}}return S}),[u,h]).map((S,C)=>{let R=c.id===e&&i===C;return qt.createElement(Dr,{key:gv(e,C)},qt.createElement(Dr,{flexShrink:0},qt.createElement(Cd,{color:R?k.primary:k.secondary2,dimColor:!R},`${C+1} `.padStart(f,"\xA0"))),S.kind==="blank"?qt.createElement(Cd,{backgroundColor:R?"gray":void 0},kN):qt.createElement(Dr,null,qt.createElement(td,{line:S,width:S.kind==="code"?h:0,wrap:"truncate-end"})))});return qt.createElement(Dr,{flexDirection:"column",paddingTop:1},qt.createElement(Dr,null,qt.createElement(Ut,{isSelected:r}),qt.createElement(Cd,{color:r?k.accent:k.secondary2},t)),qt.createElement(Dr,{flexDirection:"row",borderStyle:"round",borderColor:k.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},qt.createElement(Ht,{scrollByOne:!0,height:o,selectedIndex:i,itemHeight:1},E)))}});import{Box as Or,Text as MN}from"ink";import Et,{useMemo as Fr}from"react";var LN,PN,DN,ON,FN,vv,yv=g(()=>{"use strict";me();pe();O();Je();Aa();oo();vh();Oh();Er();uv();pv();hv();wd();LN=e=>Te(e,"description"),PN=e=>Te(e,"comments"),DN=e=>Te(e,"history"),ON=e=>Te(e,"diff"),FN=e=>Te(e,"attachments"),vv=({ticket:e,height:t})=>{let n=Fr(()=>uh(e),[e]),{selectedIndex:o,contextNode:r}=Ye(),s=process.stdout.columns||120,i=Fr(()=>LN(e.id),[e.id]),c=Fr(()=>PN(e.id),[e.id]),u=Fr(()=>DN(e.id),[e.id]),p=Fr(()=>ON(e.id),[e.id]),m=Fr(()=>FN(e.id),[e.id]),f=N.getAttachmentsByIssue(e.id).length,h=r.id===e.id,x=r.id===c||r.parentNodeId===c,E=r.id===u||r.parentNodeId===u,S=r.id===m||r.parentNodeId===m,C=r.id===p||r.parentNodeId===p,R=ve(e.id);if(x){let ae=t-3;return Et.createElement(Or,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Et.createElement(Dh,{ticket:e,width:s,height:ae}))}if(S){let ae=t-3;return Et.createElement(Or,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Et.createElement(hh,{ticket:e,width:s,height:ae}))}if(C){let ae=t-3;return Et.createElement(Or,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Et.createElement(dv,{ticket:e,width:s,height:ae}))}if(E){let q=N.getNode(u),ae=q&&ot(q)?q.props.value??"":"",Pt=Nd(t);return Et.createElement(Or,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},q?Et.createElement(Td,{id:q.id,label:"Event log",text:ae,selected:!1,maxWidth:s,rows:Pt}):null)}let A=[u,p,c,m],L=q=>A.includes(q),_=R.reduce((q,ae)=>as(ae)?q+1:q,0),j=R.reduce((q,ae)=>L(ae.id)?q+1:q,0),z=R.findIndex(q=>L(q.id)),X=Nd(t,_,j),ue=(q,ae,Pt,Qr)=>Et.createElement(Or,{key:q.id,paddingTop:ae===z?1:0},Et.createElement(Ut,{isSelected:Pt}),Et.createElement(MN,{backgroundColor:k.secondary,color:Pt?k.accent:k.primary},Qr)),ze=(q,ae,Pt)=>q.id===i?Et.createElement(Td,{key:q.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:ae,maxWidth:s,rows:X}):as(q)?Et.createElement(mv,{key:q.id,parent:q,selected:ae,selectedIndex:o}):q.id===c?ue(q,Pt,ae,` Comments (${n}) \u203A\u203A `):q.id===m?ue(q,Pt,ae,` Attachments (${f}) \u203A\u203A `):q.id===u?ue(q,Pt,ae," History \u203A\u203A "):q.id===p?ue(q,Pt,ae," Diff \u203A\u203A "):null;return Et.createElement(Or,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R.map((q,ae)=>ze(q,h&&o===ae,ae)))}});import{Box as _N}from"ink";import Ha from"react";var BN,bv,xv=g(()=>{"use strict";me();dh();yv();BN=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,viewMode:s,height:i,width:c})=>{let u=t.context,p=u===se.TICKET||u===se.FIELD_LIST||u===se.FIELD,m=u===se.BOARD||u===se.SWIMLANE,f=u===se.TICKET?t:o.find(C=>C.context===se.TICKET),h=Math.floor(c/3),x=Math.floor(c/Math.max(e.length,1)),E=Math.min(x,h),S=s==="dense";return Ha.createElement(_N,{flexDirection:"row",height:i},m&&e.map((C,R)=>{let A=t.id===C.id,L=A?n:-1,_=t.context===se.BOARD&&n===R;return Ha.createElement(ch,{key:C.id,height:i,width:E,swimlane:C,isSelected:_,isDense:S,isFocused:A,listSelectedIndex:L,mode:r})}),p&&f&&Ha.createElement(vv,{height:i,ticket:f}))},bv=Ha.memo(BN)});import Iv from"node:fs";import $N from"node:path";import jN from"react";import{render as UN}from"ink";import{Writable as HN}from"node:stream";var Zs,WN,qN,GN,zN,Ev,Rv=g(()=>{"use strict";xv();me();w();O();ee();Fe();Zs=e=>String(e).padStart(2,"0"),WN=e=>{let t=e.getUTCFullYear(),n=Zs(e.getUTCMonth()+1),o=Zs(e.getUTCDate()),r=Zs(e.getUTCHours()),s=Zs(e.getUTCMinutes()),i=Zs(e.getUTCSeconds());return`${t}-${n}-${o}_${r}-${s}-${i}`},qN=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",GN=async(e,{width:t,height:n})=>{let o="",r=new HN({write(i,c,u){let p=zN(i.toString()).trimEnd();p.trim().length>0&&p.includes("\u256D")&&(o=p),u()}});r.columns=t,r.rows=n,r.isTTY=!0;let s=UN(e,{stdout:r,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),o},zN=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Ev=async()=>{let{viewMode:e}=le(),{contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,renderedChildrenIndex:s}=v(),i=o.find(R=>R.context==="BOARD");if(!i)return l("No board found to export");let c=120,u=40,p=await GN(jN.createElement(bv,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(R=>R!==void 0&&bo(R)),contextNode:t,selectedIndex:n,breadCrumb:o,viewMode:e??"dense",mode:r}),{width:c,height:u});if(!p)return l("Failed to render board export");let m=Mi(process.cwd());if(a(m))return l("Unable to export, epiq root not found");let f=new Date,h=WN(f),x=`board_${qN(i.title)}_${h}.md`,E=lp(m.value);Iv.mkdirSync(E,{recursive:!0});let S=$N.join(E,x),C=`# Board - ${i.title}
|
|
83
91
|
Date: ${f.toISOString()}
|
|
84
92
|
|
|
85
93
|
\`\`\`text
|
|
86
|
-
${
|
|
94
|
+
${p}
|
|
87
95
|
\`\`\`
|
|
88
|
-
`;return
|
|
89
|
-
`).map(u=>u.trim()),s=
|
|
96
|
+
`;return Iv.writeFileSync(S,C,"utf8"),d("Exported board layout",S)}});import{useSyncExternalStore as e1}from"react";var kd,VN,KN,_r,YN,uo,Wa=g(()=>{"use strict";w();VN=new Set,KN=()=>{for(let e of VN)e()},_r=()=>{if(!kd)throw new Error("Ui state not initialized. Call initUiState() first.");return kd},YN=e=>{let t=_r();return kd=e(t),KN(),d("UX state updated",null)},uo=e=>YN(t=>({...t,...e}))});import{ulid as Md}from"ulid";var Sv,XN,JN,Nv=g(()=>{"use strict";pd();$();$();Yt();me();w();sr();pe();O();ee();_n();Ft();Sv=async e=>{let{contextNode:t,selectedIndex:n}=v(),o=ve(t.id)[n];if(e.modifier===Mt.DESCRIPTION)return JN();if(o&&ls(o))return XN(e);if(e.modifier===Mt.TITLE){let r=ge();if(a(r))return l("Unable to resolve user ID");let s=o;if(!s)return l("Missing node");if(s.readonly)return l("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return l("Provide a title");let c=await Ee();return a(c)?c:F([{id:Md(),action:"edit.title",payload:{id:s.id,name:i},...D(r.value)}],c.value)}return l("Unknown edit command")},XN=async e=>{let t=ge();if(a(t))return l("Unable to resolve user ID");let{contextNode:n,selectedIndex:o}=v(),r=ve(n.id)[o];if(!r||!ls(r))return l("Select a comment first");if(r.readonly)return l("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return l("Unable to resolve comment issue");let i=v().nodes[s];if(!i||!U(i))return l("Unable to resolve comment issue");if(i.readonly)return l("Cannot edit readonly issue");let c=r.id.split(":").at(0)??"",u=N.getComment(c);if(!u||u.deleted)return l("Unable to resolve comment");if(u.issue!==i.id)return l("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return l("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let p=e.inputString.trim();if(!p)return l("Provide a comment");let m=await Ee();if(a(m))return m;let f=m.value;return F([{id:Md(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:p},...D(t.value)}],f)},JN=async()=>{let e=ge();if(a(e))return l("Unable to resolve user ID");let t=await Ee();if(a(t))return t;let n=t.value,{breadCrumb:o,selectedNode:r}=v(),s=Nt([...o,r],"TICKET");if(a(s))return l("Edit target must be an issue");let i=s.value;if(!U(i))return l("Edit target must be an issue");if(i.readonly)return l("Cannot edit readonly issue");let c=ve(i.id).find(f=>f.title===Ce.DESCRIPTION);if(!c)return l("No target found");if(c.readonly)return l("Cannot edit readonly field");let u=i.props.description??"";if(typeof u!="string")return l("Selected field is not editable text");let p=Kh(u);if(a(p))return l("Failed to edit field");let m=p.value;return m===u?d("No changes made",null):F([{id:Md(),action:"edit.description",payload:{id:i.id,md:m},...D(e.value)}],n)}});import Ld from"node:fs";import QN from"node:path";var wv,Cv=g(()=>{"use strict";w();$t();wv=async e=>{let t=QN.join(e,".gitignore"),n=Ld.existsSync(t)?Ld.readFileSync(t,"utf8"):"",o=[".epiq/events/",".epiq/log/"],r=n.split(`
|
|
97
|
+
`).map(u=>u.trim()),s=o.filter(u=>!r.some(p=>p===u||p===u.replace(/\/$/,"")||p==="/"+u||p==="/"+u.replace(/\/$/,"")));if(s.length===0)return d("Local epiq paths already ignored",!1);let c=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
90
98
|
`);return n=n.trimEnd()+`
|
|
91
99
|
|
|
92
100
|
${c}
|
|
93
|
-
`,
|
|
94
|
-
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},
|
|
95
|
-
`));let
|
|
96
|
-
`));let u=Ye();if(a(u))return hs(16,u.message);let{rootNodeId:m,nodes:p}=u.value,f=p[m];return f?($.navigate({contextNode:f,selectedIndex:0}),N({hasProjectDefinition:!0,mode:b.DEFAULT}),l(s,null)):hs(16,"Unable to resolve initialized root node")}});import{ulid as WE}from"ulid";function dc(e){let t=rg();if(a(t))return t;let{contextNode:n,nodes:r}=g();if(!n.parentNodeId)return d("Missing parent node id");let o=r[n.parentNodeId];if(!o)return d("Missing parent node");let s=ye(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return d("Current node not found among siblings");let c=s[i+e];if(!c)return d("Missing sibling node");let u=og({id:t.value.id,parentId:c.id,position:{at:"end"}});return a(u)?u:sg(u.value)}function cc(e){let t=rg();if(a(t))return t;let{contextNode:n,selectedIndex:r}=g(),s=ye(n.id)[r+e];if(!s)return d("Missing sibling node");let i=og({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(i)?i:sg(i.value)}var ng,jn,vs,rg,ac,og,sg,lc=h(()=>{"use strict";pn();Ce();S();Rt();M();ng=null,jn=()=>structuredClone(ng),vs=e=>{ng=e},rg=()=>{let{contextNode:e,selectedIndex:t}=g(),r=ye(e.id)[t];return r?l("Resolved selected child",r):d("Target node not found")},ac=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ye(t).filter(o=>o.id!==e);return Zs(r,n)},og=({id:e,parentId:t,position:n={at:"end"}})=>{let r=oe();if(a(r))return d("Unable to resolve user ID");let o=ac({parentId:t,id:e,position:n});return a(o)?o:l("Created pending move state",{id:WE(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},sg=e=>{vs(e);let t=Tn(e,!0);return a(t)?t:l("Node moved successfully",t.value)}});import{ulid as HE}from"ulid";var ig,Wi,ag,dg=h(()=>{"use strict";ht();lc();Re();Ce();ve();S();Rt();pe();M();ie();ig=()=>{let e=jn();if(!e)return d("No pending move state");let t=e.payload.id,n=e.payload.parent,r=g().nodes[n];if(!r)return d("Move parent not found");let o=ye(n).findIndex(s=>s.id===t);return o===-1?d("Moved node not found among rendered children"):($.navigate({contextNode:r,selectedIndex:o}),l("Synchronized navigation to moved node",null))},Wi=(e,t="Moved preview")=>{if(a(e))return e;let n=ig();return a(n)?n:(N({mode:b.MOVE}),l(t,null))},ag=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{modifier:t}=ce().commandMeta,{contextNode:n,selectedIndex:r}=g(),o=ye(n.id)[r];if(!o)return N({mode:b.DEFAULT}),d("No move target");if(t==="start"){if(o.readonly)return d("Target node is read-only");if(r===-1)return d("No item selected");if(!o.parentNodeId)return d("Target has no parent");let s=ye(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return d("Target not found among siblings");let c=s[i-1],u=s[i+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=ac({parentId:o.parentNodeId,id:o.id,position:m});return a(p)?p:(vs({id:HE(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),N({mode:b.MOVE}),l("Move initialized",null))}if(t==="next")return Wi(cc(1));if(t==="previous")return Wi(cc(-1));if(t==="to-next")return Wi(dc(1));if(t==="to-previous")return Wi(dc(-1));if(t==="confirm"){let s=jn();if(!s)return d("No pending move to confirm");let i=await zt();if(a(i))return i;let c=P([s],i.value);if(a(c))return c;let u=ig();return a(u)?u:(vs(null),N({mode:b.DEFAULT}),l("Moved item",null))}return t==="cancel"?(vs(null),N({mode:b.DEFAULT}),l("Cancelling move",null)):d("Invalid move modifier")}});import{monotonicFactory as qE,ulid as GE}from"ulid";var zE,Hi,uc=h(()=>{"use strict";S();zE=qE(),Hi=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=zE();return l("Created issue events",[{id:GE(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as qi}from"ulid";var cg,lg=h(()=>{"use strict";ht();uc();Re();Ce();$t();S();re();Rt();M();ie();cg=async(e,t)=>{let n=oe();if(a(n))return d("Unable to resolve user ID");let r=await zt();if(a(r))return r;let o=r.value;if(!t.inputString)return d(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=g(),u=m=>{let p=P([m],o);if(a(p))return p;let f=E.getNode(p.value[0].result.id);if(!f)return d("Created node not found");if(!f.parentNodeId)return p;let y=E.getNode(f.parentNodeId);return y?($.navigate({contextNode:y,selectedIndex:E.getSiblings(f.parentNodeId).findIndex(({id:x})=>x===f.id)}),p):d("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=E.getNode(m);if(!p)return d("Workspace not found");let f=gn(p.id,n.value,o);return a(f)?f:u({id:qi(),action:"add.board",payload:{id:qi(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=lt(s,"BOARD");if(a(m))return d("Unable to add swimlane in this context");let p=gn(m.value.id,n.value,o);return a(p)?p:u({id:qi(),action:"add.swimlane",payload:{id:qi(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=ae(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let L=lt(s,"SWIMLANE");return a(L)?null:L.value})();if(!p)return d("Unable to add issue in this context");let f=gn(p.id,n.value,o);if(a(f))return f;let y=Hi({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(a(y))return y;let x=y.value,R=P([...x],o);if(a(R))return R;if(!R.value[0])return d("Issue creation failed");let k=x.find(L=>L.action==="add.issue")?.payload.id;return k?($.navigate({contextNode:p,selectedIndex:E.getSiblings(p.id).findIndex(({id:L})=>L===k)}),l("Issue created",null)):d("Unable to determine ticket id")}return l("Success",null)}});var VE,ug,KE,mg,YE,pg,fg=h(()=>{"use strict";Zn();et();Qe();Xo();ui();dd();ci();Or();ur();wt();S();Ht();M();zo();ie();ri();VE=e=>e.some(t=>t.action==="init.workspace"),ug=async(e,t)=>{let n=qt(e);return a(n)?d(n.message):Do({cwd:t,branch:n.value})},KE=e=>{let t=Me(process.cwd());if(a(t))return!1;let n=Ie({repoRoot:t.value});return!a(n)&&n.value===e},mg=async e=>{let t=Ie({repoRoot:e});if(a(t))return Dr(3,t.message);let n=t.value,r=await Pn({repoRoot:e,stateBranchRoot:n,stateBranchName:Ls().stateBranch});if(a(r))return Dr(3,r.message);let o=Ct(n);if(a(o))return Dr(3,o.message);if(!VE(o.value.events)){let m=await ug(e,n);if(a(m)&&logger.info(3,m.message),o=Ct(n),a(o))return Dr(3,o.message)}let{events:s,unreadable:i}=o.value,c=Yt(s,i);if(a(c))return Dr(4,c.message);N({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let u=es({root:e});return a(u)&&logger.info(u.message),l("Loaded project",void 0)},YE=async e=>{let t=Ie({repoRoot:e});if(a(t))return d(t.message);let n=t.value,r=await ln({repoRoot:n});if(a(r))return d(r.message);if(!r.value)return l("No remote to pull",void 0);let o=await ai({worktreeRoot:n,operation:"boot pull",fn:()=>ld(n,()=>(Lr("Pulling"),ug(e,n)))});if(a(o))return Se(o.message);if(o.value===null)return l("Another process holds the state worktree",void 0);let s=o.value;if(a(s))return Lo(s.message)?(ni("Offline"),l("Offline",void 0)):Se(s.message);if(!s.value)return mr("Already synced"),l("Already synced",void 0);if(!KE(n))return l("Project changed during the pull",void 0);let i=ud(n);return a(i)?i:(mr("Pulled"),l("Pulled and reloaded",void 0))},pg=e=>{YE(e).then(t=>{a(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${xm(t)}`)})}});import XE from"node:os";import gg from"node:path";var JE,QE,hg,vg=h(()=>{"use strict";fg();Or();S();pe();M();ie();JE=e=>e==="~"||e.startsWith("~/")?gg.join(XE.homedir(),e.slice(1)):e,QE=(e,t)=>{let n=e.trim();if(!n)return d("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?l("Resolved recent project",o.root):d(`No recent project #${n}`)}let r=Me(gg.resolve(JE(n)));return a(r)?d(`No epiq project at ${n}`):l("Resolved project path",r.value)},hg=async()=>{let e=ki();if(ne(""),g().hasProjectDefinition)return d("Already in a project; run epiq from another directory");let t=fi({exclude:process.cwd()}),n=a(t)?[]:t.value,r=QE(e,n);if(a(r))return d(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(c){return d(`Unable to enter ${o}: ${c instanceof Error?c.message:String(c)}`)}let i=await mg(o);return a(i)?(process.chdir(s),d(i.message)):(pg(o),l(`Opened ${Vm(o)}`,null))}});var Gi,mc=h(()=>{"use strict";ht();wt();pn();S();M();Gi=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=g(),s=Ka(n,t);if(a(s))return d(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=Sn();if(a(u))return u;let m=mn(i),{fatal:p,skipped:f}=nr(m);if(p.length>0)return Sn(),N(o),d(p.map(x=>x.message).join(", "));rr(f);let y=g().nodes[e];return y?($.navigate({contextNode:y,selectedIndex:r}),l("",{unappliedEvents:c})):(Sn(),N(o),d("Board did not exist at that date"))}});var yg,bg=h(()=>{"use strict";yg=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 ZE,eR,tR,zi,Vi,br,Ig,xg,pc=h(()=>{"use strict";Je();ys();pn();ve();S();bg();M();ZE=20,eR=16,tR=150,zi=null,Vi=null,br=()=>{zi!==null&&(clearInterval(zi),zi=null),Vi!==null&&(clearTimeout(Vi),Vi=null)},Ig=()=>{br(),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},xg=({events:e,startTime:t,durationMs:n})=>{br();let r=e.length,o=Co(e.map(f=>Vn(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=yg(o),c=Math.max(1,Math.round(n*ZE/1e3)),u=Math.max(Math.round(n/c),eR),m=0,p=0;N({mode:b.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),zi=setInterval(()=>{m++;let f=m/c,y=[],x,R;for(;p<r&&i[p]<=f;){let w=e[p],k=Tn(w);if(a(k)){if($o(k)){p++;continue}Ig();return}y.push(...La(w)),x=w,R=o[p],p++}if(p>=r||m>=c){for(;p<r;p++){let k=Tn(e[p]);if(a(k)&&!$o(k))break}let w=g().replay;N({unappliedEvents:[],replay:w&&{...w,progress:1,appliedCount:r}}),br(),Vi=setTimeout(Ig,tR);return}let A=g().replay;N({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:x?R??A?.currentTime??t:A?.currentTime??t,currentLabel:x?fc(x):A?.currentLabel??"",flashNodeIds:x?[...new Set(y)]:A?.flashNodeIds??[]}})},u)}});var Eg,Rg=h(()=>{"use strict";et();Je();wt();pn();ve();$t();S();pe();M();rs();mc();pc();Eg=async()=>{let e=lt(g().breadCrumb,"BOARD");if(a(e))return e;let t=await gt(process.cwd());if(a(t))return d("Unable to locate repo root");let n=Ie({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=ce().commandMeta;if(br(),r==="now"){let c=ar(n.value);if(a(c))return d(c.message);let u=Sn();if(a(u))return u;let m=mn(c.value),{fatal:p,skipped:f}=nr(m);return p.length>0?d(p.map(y=>y.message).join(", ")):(rr(f),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),l("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let c=Ya(n.value);if(a(c))return c;let u=r==="prev"?g().eventLog.at(-1):g().unappliedEvents.at(0),m=u===void 0?null:Vn(u),p=(u===void 0?null:c.value.get(u.id)??null)??(m===null?null:No(m));if(p===null)return d(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?p:p+1}else{let c=fr(r||o.trim());if(!c)return d("Invalid peek date");s=c.getTime()}let i=Gi({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(i)?i:(N({mode:b.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),l("Peeking",!0))}});var Sg,Ng=h(()=>{"use strict";et();$t();S();pe();M();rs();mc();pc();Sg=async()=>{let e=lt(g().breadCrumb,"BOARD");if(a(e))return e;let t=await gt(process.cwd());if(a(t))return d("Unable to locate repo root");let n=Ie({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=ce().commandMeta,{dateInput:s,durationInput:i}=Ii(r,o);if(br(),g().syncStatus.status==="syncing")return d("Cannot replay while syncing, try again in a moment");let c=fr(s);if(!c)return d("Invalid replay date");let u=i?bi(i):15e3;if(u===null)return d("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=g(),f=Gi({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(f))return f;let{unappliedEvents:y}=f.value;return y.length===0?(Sn(),N(p),l("Nothing to replay from that point",!0)):(xg({events:y,startTime:m,durationMs:u}),l("Replaying board history",!0))}});import{spawn as rR}from"node:child_process";var oR,Cg,wg=h(()=>{"use strict";S();oR=()=>{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"]}}},Cg=async e=>new Promise(t=>{let{command:n,args:r}=oR();try{let o=rR(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(d(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?l("Copied to clipboard",null):d(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(d(`Clipboard tool not available (${n})`))}})});var bs,Ag,Tg=h(()=>{"use strict";S();M();wg();tt();ns();yn();bs=async(e,t)=>{if(!e.trim())return d(`Nothing to copy: ${t} is empty`);let n=await Cg(e);return a(n)?n:l(`Copied ${t} to clipboard`,null)},Ag=async e=>{let{breadCrumb:t,selectedNode:n}=g(),r=os({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return d("Nothing selected to copy from");switch(e.modifier){case we.REF:return bs(j(o.id),"ref");case we.TITLE:return bs(o.title,"title");case we.DESCRIPTION:return r?bs(r.props?.description??"","description"):d("No issue in scope");case we.TAGS:{if(!r)return d("No issue in scope");let s=Ln(r).map(({name:i})=>i);return bs(s.join(", "),"tags")}case we.ASSIGNEES:{if(!r)return d("No issue in scope");let s=Dn(r).map(({name:i})=>i);return bs(s.join(", "),"assignees")}default:return d("Yank one of: ref, title, description, tags, assignees")}}});var kg,Mg=h(()=>{"use strict";ui();ve();S();pe();M();kg=async()=>{ne(""),N({mode:b.DEFAULT});let e=Ye();if(a(e))return d(e.message);if(e.value.syncStatus.status==="syncing")return d("Sync already in progress");N({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await li();return a(t)?(N({syncStatus:{msg:t.message,status:"failed"}}),t):(N({mode:b.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});var Fe,tn=h(()=>{"use strict";S();ie();Fe=async()=>{let e=await zt();return a(e)?e:l("Resolved persist root",e.value)}});import{ulid as Pg}from"ulid";var sR,Lg,Dg=h(()=>{"use strict";Re();Ce();ee();S();M();tn();sR=e=>e.action==="add.issue.comment",Lg=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=ae(t.id)[n];if(!r)return d("Unable to resolve child to delete");let o=await Fe();if(a(o))return o;if(r.context==="COMMENT"){let s=r.id,i=F(t)?t.id:t.parentNodeId;if(!i)return d("Unable to resolve comment issue");let c=g().nodes[i];if(!c||!F(c))return d("Unable to resolve comment issue");let u=c.log?.filter(sR).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?d("You can only delete your own comments"):P([{id:Pg(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):d("Unable to resolve comment")}return P([{id:Pg(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)}});import{ulid as iR}from"ulid";var _g,Fg=h(()=>{"use strict";Re();Ce();Bt();ee();S();Rt();M();tn();_g=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=ae(t.id)[n];if(!r)return d("Unable to close issue, no target found");if(!F(r))return d("Cannot close in this context");let o=g().nodes[me];if(!o)return d("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return d("Issue is already closed");let s=await Fe();if(a(s))return s;let i=s.value,c=Vt(o.id,r.id,{at:"end"},e.value,i);if(a(c))return c;let u=P([{id:iR(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value}],i);return a(u)?u:l("Issue closed",null)}});var Ki,gc=h(()=>{"use strict";Ki=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 aR}from"ulid";var Bg,Og=h(()=>{"use strict";Re();Ce();gc();Bt();ee();S();re();Rt();M();tn();Bg=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=ae(t.id)[n];if(!r)return d("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):kt(r.id,"TICKET");if(a(o))return d("Cannot reopen in this context");let s=o.value,i=g().nodes[me];if(!i)return d("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return d("Issue is not closed");if(!F(s))return d("Target node is not issue");let c=Ki(s);if(!c)return d("Unable to resolve previous parent from issue history");if(c===i.id)return d("Previous parent resolves to closed swimlane");let u=g().nodes[c];if(!u)return d("Previous parent no longer exists");let m=await Fe();if(a(m))return m;let p=m.value,f=Vt(u.id,s.id,{at:"end"},e.value,p);if(a(f))return f;let y=P([{id:aR(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...e.value}],p);return a(y)?y:l("Issue reopened",null)}});import{ulid as dR}from"ulid";var Ug,jg=h(()=>{"use strict";Re();Ce();S();pe();M();tn();Ug=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),r=ae(t.id)[n];if(!r)return d("Missing node");if(r.readonly)return d("Cannot rename readonly node");let o=ki();if(!o)return d("Provide a title");let s=await Fe();return a(s)?s:P([{id:dR(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)}});import{ulid as cR}from"ulid";var $g,Wg=h(()=>{"use strict";re();Re();Ce();ee();S();pe();M();tn();$g=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{modifier:t,inputString:n}=ce().commandMeta,r=(t||n).trim();if(!r)return d("Provide a tag");let o=E.findTagByName(r);if(!o)return d(`Tag "${r}" does not exist`);let{selectedNode:s}=g();if(!s)return d("Invalid untag target");let i=kt(s.id,"TICKET");if(a(i))return d("Unable to untag issue in this context");let c=i.value;if(!F(c))return d("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return d("Issue is not tagged with that tag");let m=await Fe();return a(m)?m:P([{id:cR(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}],m.value)}});import{ulid as hc}from"ulid";var Hg,qg=h(()=>{"use strict";re();Re();Ce();ee();S();pe();M();tn();Hg=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{modifier:t,inputString:n}=ce().commandMeta,r=(t||n).trim();if(!r)return d("Provide a tag");let{selectedNode:o}=g();if(!o)return d("Invalid tag target");let s=kt(o.id,"TICKET");if(a(s))return d("Unable to tag issue in this context");let i=s.value;if(!F(i))return d("Target node is not issue");let c=await Fe();if(a(c))return c;let u=E.findTagByName(r),m=u?.id??hc();return(i.props.tags??[]).includes(m)?d("Already tagged with that tag"):P([...u?[]:[{id:hc(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:hc(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)}});var Yi,vc=h(()=>{"use strict";M();Yi=()=>{let{eventLog:e=[],contributors:t}=g(),n=new Map,r=new Set;for(let o of e)o.userId&&(n.set(o.userId,o.userName??""),r.add(o.userId));for(let o of Object.values(t))n.set(o.id,o.name);return[...n.entries()].map(([o,s])=>({id:o,name:s,isExternal:!r.has(o)}))}});import{ulid as yc}from"ulid";var Gg,zg=h(()=>{"use strict";Re();Ce();ee();S();re();pe();M();vc();tn();Gg=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{modifier:t,inputString:n}=ce().commandMeta,r=(t||n).trim();if(!r)return d("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return d("Provide an assignee");let{selectedIndex:i,contextNode:c}=g(),u=ae(c.id)[i];if(!u)return d("Invalid assign target");let m=kt(u.id,"TICKET");if(a(m))return d("Unable to assign issue in this context");let p=m.value;if(!F(p))return d("Target node is not issue");let f=await Fe();if(a(f))return f;let y=Yi(),x=!o&&s.toLowerCase()==="me",R,A;if(x)R=e.value.userId,A=y.find(L=>L.id===R)?.name??e.value.userName;else{let L=y.filter(U=>U.name===s);if(L.length>1)return d(`"${s}" matches ${L.length} contributors (${L.map(U=>U.id).join(", ")}). Assign from the GUI to choose by id.`);let D=L[0];if(!D&&!o)return d(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);R=D?.id??yc(),A=D?.name??s}if((p.props.assignees??[]).includes(R))return d("Assignee already assigned");let k=!!g().contributors[R];return P([...k?[]:[{id:yc(),action:"create.contributor",payload:{id:R,name:A},...e.value}],{id:yc(),action:"add.issue.assignee",payload:{id:p.id,assignee:R},...e.value}],f.value)}});import{ulid as lR}from"ulid";var Vg,Kg=h(()=>{"use strict";Re();Ce();ee();S();re();pe();M();vc();tn();Vg=async()=>{let e=oe();if(a(e))return d("Unable to resolve user ID");let{modifier:t,inputString:n}=ce().commandMeta,r=(t||n).trim();if(!r)return d("Provide an assignee to remove");let{selectedNode:o}=g();if(!o)return d("Invalid unassign target");let s=kt(o.id,"TICKET");if(a(s))return d("Unable to unassign in this context");let i=s.value;if(!F(i))return d("Target node is not issue");let c=i.props.assignees??[],u=r.toLowerCase()==="me",m=u?c.filter(y=>y===e.value.userId):Yi().filter(y=>y.name===r&&c.includes(y.id)).map(y=>y.id);if(m.length>1)return d(`"${r}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return d(u?"Issue is not assigned to you":`Issue is not assigned to "${r}"`);let f=await Fe();return a(f)?f:P([{id:lR(),action:"remove.issue.assignee",payload:{id:i.id,assignee:p},...e.value}],f.value)}});import{ulid as Yg}from"ulid";var Xg,Jg=h(()=>{"use strict";Re();Ce();$t();ee();S();re();M();xn();tn();Xg=async e=>{let t=e.inputString.trim();if(!t)return d("Provide a comment");if(t.length>4e3)return d(`Cannot exceed ${4e3} characters`);let n=oe();if(a(n))return d("Unable to resolve user ID");let{breadCrumb:r,selectedNode:o}=g(),s=lt([...r,o],"TICKET");if(a(s))return d("Edit target must be an issue");let i=s.value;if(!i)return d("Invalid comment target");let c=i.context==="TICKET"?l("Resolved ticket",i):kt(i.id,"TICKET");if(a(c))return d("Unable to comment on issue in this context");let u=c.value;if(!F(u))return d("Target node is not issue");let m=await Fe();return a(m)?m:P([{id:Yg(),action:"add.issue.comment",payload:{id:Yg(),issue:u.id,author:n.value.userId,md:t},...n.value}],m.value)}});import uR from"zod";var Qg,Zg=h(()=>{"use strict";Qt();ve();S();pe();ze();M();Qg=()=>{let e=ce().commandMeta.inputString,t=uR.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return d("Auto sync duration must be a number of at least 3000 ms");let n=ot({autoSyncDebounceMs:t.data});return a(n)?n:(xt({autoSyncIntervalMs:t.data}),N({mode:b.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))}});var eh,th=h(()=>{"use strict";ts();Qt();ve();S();pe();ze();M();eh=()=>{let e=ce().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return d("Invalid response");let t=Zm(e),n=ot({autoSync:t});return a(n)?n:(xt({autoSync:t}),N({mode:b.DEFAULT}),l(`Auto sync set to "${e}"`,null))}});var nh,rh=h(()=>{"use strict";Qt();ve();S();pe();ze();M();nh=()=>{let e=ce().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return d("Invalid response");let n=ot({logLevel:e});return a(n)?n:(xt({logLevel:e}),N({mode:b.DEFAULT}),l(`Auto sync set to "${e}"`,null))}});import{ulid as mR}from"ulid";var oh,sh=h(()=>{"use strict";zn();Qt();ve();S();ze();M();yn();Zg();Nd();th();rh();oh=e=>{let t=e.inputString.trim();switch(e.modifier){case be.USERNAME:{if(process.env[It])return d(`Cannot change the configured user while ${It} names this process`);let n=$r();if(a(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,c=r||mR();if(!i||!c)return d("Unable to resolve user name or id");let u=ot({userName:i,userId:c,preferredEditor:o??""});return a(u)?u:(xt({userName:i,userId:c}),N({mode:b.DEFAULT}),l(`Username set to "${i}"`,null))}case be.EDITOR:{if(!t)return d("No editor provided");let n=ot({preferredEditor:t});return a(n)?n:(xt({preferredEditor:t}),N({mode:b.DEFAULT}),l(`Editor configuration set to "${t}"`,null))}case be.VIEW:{if(t!=="wide"&&t!=="dense")return d("Invalid view mode");let n=ot({viewMode:t});return a(n)?n:(xt({viewMode:t}),N({mode:b.DEFAULT}),l(`View set to "${t}"`,null))}case be.AUTOSYNC:return eh();case be.LOG_LEVEL:return nh();case be.SYNC_DEBOUNCE_MS:return Qg();case be.ATTACHMENT_MAX_KB:return vp();default:return d("Unknown config command")}}});var ih,ah=h(()=>{"use strict";qf();ht();ve();S();pe();M();ji();pr();Ld();yn();Jf();tg();dg();lg();vg();Rg();Ng();Tg();Mg();Dg();Fg();Og();jg();Wg();qg();zg();Kg();Jg();sh();ih=[{systemOnly:!0,intent:O.Move,description:"Internal move-state command",mode:b.COMMAND_LINE,action:ag},{intent:O.Delete,description:"Delete the currently selected node",mode:b.COMMAND_LINE,action:Lg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:b.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ce().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>Ae(I.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return d("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return Ne(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:b.DEFAULT})),l("Filter updated",null)}},{intent:O.ViewHelp,description:"Open the help screen",mode:b.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return Un({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),N({mode:b.HELP}),l("Viewing help",null)}},{intent:O.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:b.COMMAND_LINE,action:_g,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:b.COMMAND_LINE,action:Bg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.Init,description:"Initialize Epiq in the current git repository",mode:b.COMMAND_LINE,action:eg},{intent:O.OpenProject,description:"Open a recently used epiq project, by number or path",mode:b.COMMAND_LINE,action:hg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.NewItem,description:"Create a new board, swimlane, or issue",mode:b.COMMAND_LINE,action:cg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.Rename,description:"Rename the currently selected node",mode:b.COMMAND_LINE,action:Ug,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.UntagTicket,description:"Remove a tag from the selected issue",mode:b.COMMAND_LINE,action:$g,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.TagTicket,description:"Add or create a tag on the selected issue",mode:b.COMMAND_LINE,action:Hg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.AssignUserToTicket,description:"Assign a user to the selected issue",mode:b.COMMAND_LINE,action:Gg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:b.COMMAND_LINE,action:Vg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.Comment,description:"Add a comment to the selected issue",mode:b.COMMAND_LINE,action:async(e,t)=>Xg(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.Sync,description:"Pull, commit, and push Epiq state",mode:b.COMMAND_LINE,action:kg},{intent:O.Peek,description:"View board state at another point in time",mode:b.COMMAND_LINE,action:Eg},{intent:O.Replay,description:"Replay board history forward from a point in time",mode:b.COMMAND_LINE,action:Sg},{intent:O.Export,description:"Export the current board layout to markdown",mode:b.COMMAND_LINE,action:async()=>{let e=await Hf();return a(e)?e:(N({mode:b.DEFAULT}),l("Export successful",!0))}},{intent:O.Exit,description:"Exit the application",mode:b.COMMAND_LINE,action:async()=>($.exit(),l("Exit successful",!0))},{intent:O.Edit,description:"Edit title or description",mode:b.COMMAND_LINE,action:async(e,t)=>Xf(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:b.COMMAND_LINE,action:async(e,t)=>Ag(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:O.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:b.COMMAND_LINE,action:(e,t)=>oh(t)}]});var pR,nn,bc=h(()=>{"use strict";mi();Ci();Ld();ah();S();pe();ze();M();pR=new Set(["peek","replay","filter","view-help","yank"]),nn=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ce();if(!t)return d("No command to confirm");if(!e&&n===_n.Invalid)return d("Invalid command");let s=Vp(t);Hp();let{readOnly:i}=g();if(i&&!pR.has(s))return cs({status:sn.Fail,message:"Command not available in readonly state",value:null});let c=ih.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return cs({status:sn.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return cs({status:sn.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?cs(u):(qp({addToHistory:!e}),c.onSuccess?.(),xe().autoSync&&qm(),u)}});var Xi,Ji,dh,ch=h(()=>{"use strict";S();ve();M();Xn();bc();lc();pe();Xi=[{intent:B.Exit,mode:b.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(N({mode:b.COMMAND_LINE}),ne("move cancel"),nn({isForceExecutedBySystem:!0}))},{intent:B.InitMove,mode:b.DEFAULT,description:"[m] move",action:()=>(N({mode:b.COMMAND_LINE}),ne("move start"),nn({isForceExecutedBySystem:!0}))},{intent:B.ConfirmMove,mode:b.MOVE,description:"[m] confirm move",action:()=>(N({mode:b.COMMAND_LINE}),ne("move confirm"),nn({isForceExecutedBySystem:!0}))}],Ji=[{intent:B.MovePreviousItem,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),ne("move previous"),nn({isForceExecutedBySystem:!0})):d("No pending move")},{intent:B.MoveNextItem,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),ne("move next"),nn({isForceExecutedBySystem:!0})):d("No pending move")}],dh=[{intent:B.MoveToNextContainer,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),ne("move to-next"),nn({isForceExecutedBySystem:!0})):d("No pending move")},{intent:B.MoveToPreviousContainer,mode:b.MOVE,action:()=>jn()?(N({mode:b.COMMAND_LINE}),ne("move to-previous"),nn({isForceExecutedBySystem:!0})):d("No pending move")}]});var lh,uh=h(()=>{"use strict";ee();ch();lh={[Y.WORKSPACE]:[...Xi,...Ji],[Y.BOARD]:[...Xi,...Ji],[Y.SWIMLANE]:[...Xi,...Ji,...dh],[Y.TICKET]:[],[Y.FIELD]:[],[Y.FIELD_LIST]:[],[Y.TEXT]:[],[Y.COMMENT]:[]}});import{spawn as fR}from"node:child_process";function mh(e){let t=process.platform,o=fR(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 ph=h(()=>{"use strict"});import gR from"node:fs";import hR from"node:path";var fh,gh=h(()=>{"use strict";et();Hr();S();ie();ph();fh=e=>{let t=Me(process.cwd());if(a(t))return d("Unable to resolve project root");let n=Ie({repoRoot:t.value});if(a(n))return d(n.message);let r=Wr(e.hash,e.ext),o=hR.join(Us(n.value),r);return gR.existsSync(o)?(mh(o),l(`Opened ${e.name}`,null)):d("Attachment file not found \u2014 run :sync to fetch it")}});var hh,vh,yh=h(()=>{"use strict";ve();S();pe();M();ji();Xn();ht();hh=()=>{ne("");let{pendingNavTarget:e}=oo();N({mode:b.DEFAULT}),e&&$.navigate(e),Un({pendingNavTarget:void 0})},vh=[{intent:B.ExitCommandLine,mode:b.HELP,action:()=>(hh(),l("Exiting help",null))},{intent:B.Exit,mode:b.HELP,action:()=>(hh(),l("Closed help",null))},{intent:B.NavPreviousItem,mode:b.HELP,description:"[arrows/hjkl] navigate",action:()=>($.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:B.NavNextItem,mode:b.HELP,action:()=>($.navigateToNextItem(),l("Navigating to next help item",null))},{intent:B.NavToPreviousContainer,mode:b.HELP,action:()=>($.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:B.NavToNextContainer,mode:b.HELP,action:()=>($.navigateToNextContainer(),l("Navigating to next help container",null))}]});var vR,bh,Ih,xh=h(()=>{"use strict";ve();ee();S();pe();M();ji();Xn();ht();vR=e=>{N({mode:b.COMMAND_LINE});let{pendingNavTarget:t}=oo();t&&$.navigate(t),Un({pendingNavTarget:void 0}),ne(`${e} `)},bh=()=>{ne("");let{pendingNavTarget:e}=oo();e&&$.navigate(e),Un({pendingNavTarget:void 0}),N({mode:b.DEFAULT})},Ih=[{intent:B.InitCommandPalette,mode:b.DEFAULT,description:"[?] command palette",action:()=>{ne("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=g();return Un({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),N({mode:b.PALETTE}),l("Opening command palette",null)}},{intent:B.Confirm,mode:b.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!Dl(e))return d("Command only applicable on text nodes");if(e.props.disabled)return d("Command is not available in this context");let t=e.title;return t?(vR(t),l("Selected command",t)):l("No command selected",null)}},{intent:B.ExitCommandLine,mode:b.PALETTE,action:()=>(bh(),l("Exiting palette",null))},{intent:B.Exit,mode:b.PALETTE,action:()=>(bh(),l("Closed command palette",null))},{intent:B.NavPreviousItem,mode:b.PALETTE,description:"[arrows/hjkl] navigate",action:()=>($.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:B.NavNextItem,mode:b.PALETTE,action:()=>($.navigateToNextItem(),l("Navigating to next item",null))},{intent:B.NavToPreviousContainer,mode:b.PALETTE,action:()=>($.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:B.NavToNextContainer,mode:b.PALETTE,action:()=>($.navigateToNextContainer(),l("Navigating to next container",null))}]});var Eh,Rh=h(()=>{"use strict";pr();yn();ve();S();Mr();re();Rt();pe();M();gh();Xn();yh();xh();ht();Eh=[{intent:B.InitCommandLine,mode:b.DEFAULT,description:"[:] write command",action:()=>(N({mode:b.COMMAND_LINE}),ne(""),l("Entering command line mode",null))},...vh,...Ih,{intent:B.AddItem,mode:b.DEFAULT,description:"[n] new...",action:()=>(N({mode:b.COMMAND_LINE}),ne(`${I.NEW} `),l("Adding new item",null))},{intent:B.Delete,mode:b.DEFAULT,description:"[d] delete",action:()=>(N({mode:b.COMMAND_LINE}),ne(`${I.DELETE} `),l("Deleting item",null))},{intent:B.Confirm,mode:b.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!ye(e?.id??"")?.length){let r=e?E.getAttachment(e.id):void 0;if(r)return fh(r);if(e?.title===ge.DESCRIPTION)return N({mode:b.COMMAND_LINE}),ne(`${I.EDIT} description `),l("Propose command",!0);if(e?.title===ge.ASSIGNEES)return N({mode:b.COMMAND_LINE}),ne(`${I.ASSIGN} `),l("Propose command",!0);if(e?.title===ge.TAGS)return N({mode:b.COMMAND_LINE}),ne(`${I.TAG} `),l("Propose command",!0);if(t.title===ge.DESCRIPTION&&e?.context==="TEXT")return N({mode:b.COMMAND_LINE}),ne(`${I.EDIT} description `),l("Propose command",!0)}return $.enterChildNode(),l("Entering context",null)}},{intent:B.Yank,mode:b.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=g(),t=e?.title===ge.DESCRIPTION?we.DESCRIPTION:e?.title===ge.TAGS?we.TAGS:e?.title===ge.ASSIGNEES?we.ASSIGNEES:we.REF,r=Ae(I.YANK).includes(t)?t:we.REF;return N({mode:b.COMMAND_LINE}),ne(`${I.YANK} ${r}`),l("Propose command",!0)}},{intent:B.EditTitle,mode:b.DEFAULT,description:"[r] rename title",action:()=>(N({mode:b.COMMAND_LINE}),ne(`${I.EDIT} title ${g().selectedNode?.title}`),l("Exiting context",null))},{intent:B.EditDescription,mode:b.DEFAULT,description:"[e] edit desc",action:()=>(N({mode:b.COMMAND_LINE}),ne(`${I.EDIT} description `),l("Exiting context",null))},{intent:B.Exit,mode:b.DEFAULT,description:"[q] exit context",action:()=>($.enterParentNode(),l("Exiting context",null))},{intent:B.NavPreviousItem,mode:b.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>($.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:B.NavNextItem,mode:b.DEFAULT,action:()=>($.navigateToNextItem(),l("Navigating to next item",null))},{intent:B.NavToPreviousContainer,mode:b.DEFAULT,action:()=>($.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:B.NavToNextContainer,mode:b.DEFAULT,action:()=>($.navigateToNextContainer(),l("Navigating to next container",null))}]});var yR,bR,Sh,Nh=h(()=>{"use strict";pe();yR=500,bR=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Sh=e=>{let t=bR(e);t&&Ti(n=>(n+t).slice(0,yR))}});var IR,xR,Ch,wh=h(()=>{"use strict";Nh();ve();S();pe();M();Xn();bc();IR=[b.COMMAND_LINE,b.PALETTE],xR=e=>[{intent:B.MoveCursorLeft,mode:e,action:()=>(Md(-1),l("Moving cursor left",null))},{intent:B.MoveCursorRight,mode:e,action:()=>(Md(1),l("Moving cursor right",null))},{intent:B.MoveCursorLeftOfWord,mode:e,action:()=>(Pd("left"),l("Moving cursor left of word",null))},{intent:B.MoveCursorRightOfWord,mode:e,action:()=>(Pd("right"),l("Moving cursor right of word",null))},{intent:B.AutoCompleteCommand,mode:e,action:()=>(Ti((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=g().selectedNode?.title??""),r+o}),l("Auto-completing command",null))},{intent:B.CaptureInput,mode:e,action:(t,{sequence:n})=>(Sh(n??""),l("Capturing input",null))},{intent:B.EraseInput,mode:e,action:()=>($p(),l("Erasing input",null))},{intent:B.EraseInputWord,mode:e,action:()=>(Wp(),l("Erasing input word",null))}],Ch=[{intent:B.Confirm,mode:b.COMMAND_LINE,action:()=>(nn(),l("Executing command",null))},{intent:B.ViewHelp,mode:b.DEFAULT,action:()=>(N({mode:b.HELP}),l("Viewing help",null))},...IR.flatMap(xR),{intent:B.ExitCommandLine,mode:b.COMMAND_LINE,action:()=>(N({mode:b.DEFAULT}),l("Exiting command line",null))},{intent:B.GetLastCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Gp(),l("Getting last command from history",null))},{intent:B.GetNextCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(zp(),l("Getting next command from history",null))}]});var ER,Ah,Th,kh=h(()=>{"use strict";ER=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},Ah=({keys:e})=>e.length===1?0:1,Th=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(ER).filter(r=>r!==null).sort((r,o)=>Ah(r)-Ah(o))}});function Mh(e,t,n){let r=t[e];if(!r)return d("buildBreadCrumb(): current node not found");let o=[],s=new Set,i=r;for(;i&&!s.has(i.id)&&(o.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let c=o[o.length-1];return!c||c.id!==n?d("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var Ph=h(()=>{"use strict";S()});var Lh,Dh=h(()=>{"use strict";Lh=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 RR}from"react";function Rc(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return d("derive(): contextNodeId is missing");if(!r)return d("derive(): rootNode is missing");if(!o[r])return d("derive(): unable to find root node");let c=o[t];if(!c)return d("Unable to derive state, contextNode not found");let u=Mh(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,f=[...Eh,...lh[p]??[],...Ch],y=Th(f,n),x=Lh(f),R=NR(o,s),A=R[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:y,availableActions:f,actionIndex:x,selectedNode:A,renderedChildrenIndex:R})}function Wo(e){Ic=e;let t=Me(process.cwd()),n=!1;if(!a(t)){let s=pt(t.value);if(a(s))return d(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:b.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=Rc(r);return a(o)?o:(Mt=o.value,Ec(),l("State initialized",null))}function Ne(e){let t=g(),n=e(t);if(Ir)return n.nodes!==t.nodes&&($n=null),Is=n,Mt={...t,...n},l("State updated",null);let r=Rc(n);return a(r)?d(r.message??"Unable to update state"):(Mt=r.value,Ec(),l("State updated",null))}function Ws(e){if(Ir)return l("Joined batch",e());Ir=!0,Is=null,$n=new Set;let t=()=>{let n=Is;if(Ir=!1,Is=null,n===null)return null;let r=Rc(n);return a(r)?d(r.message??"Unable to update state"):(Mt=r.value,Ec(),l("State updated",null))};try{let n=e(),r=t();return r&&a(r)?d(r.message):l("State updated",n)}finally{Ir&&t()}}function xr(e,t,n){if(!Ir)return Ne(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=g(),o=r[e]??{};if(e==="nodes"){let i=o[t],c=n;i?.parentNodeId&&$n?.add(i.parentNodeId),c.parentNodeId&&$n?.add(c.parentNodeId)}o[t]=n;let s={...r,[e]:o};return Is=s,Mt={...r,...s},l("State updated",null)}var Mt,Ic,xc,Ec,SR,g,Ye,Ir,Is,cm,N,at,$n,_h,NR,ae,Sn,Nt,M=h(()=>{"use strict";uh();Rh();wh();kh();Ht();ve();S();ie();ed();Ph();Dh();xc=new Set,Ec=()=>{for(let e of xc)e()},SR=e=>(xc.add(e),()=>xc.delete(e));g=()=>{if(!Mt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Mt},Ye=()=>Mt?l("Retrieved state",Mt):d("State not initialized. Call initWorkspaceState() first.");Ir=!1,Is=null;cm=()=>Ir,N=e=>Ne(t=>({...t,...e}));at=()=>RR(SR,g,g),$n=null,_h=null,NR=(e,t)=>{let n=Mt?.renderedChildrenIndex,r=n!==void 0&&$n!==null&&e===_h&&t.length===0&&Mt?.filters.length===0,o;if(r){o={...n};let s=sm(e,$n);for(let i of $n){let c=s[i];c?o[i]=c:delete o[i]}}else o=om(e,t);return _h=e,$n=new Set,o},ae=e=>g()?.renderedChildrenIndex[e]??[],Sn=()=>Ic?Wo(Ic):d("Cannot reset state: no initial workspace found"),Nt=()=>Mt!==void 0});var kt,CR,Wn,E,re=h(()=>{"use strict";$t();ee();S();M();Rt();kt=(e,t)=>{let{nodes:n}=g(),r=n[e];if(!r)return d("Node not found");if(r.context===t)return l("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 l("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return d(`No ancestor found for context: ${t}`)},CR=(e,t)=>{let{nodes:n}=g(),r=new Set,o=n[e];for(;o?.parentNodeId&&!r.has(o.id);){if(o.parentNodeId===t)return!0;r.add(o.id),o=n[o.parentNodeId]}return!1},Wn=(e,t)=>e?e.readonly?d({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:d("Node not found"),E={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return d("Contributor not found");if(n.userId&&n.userId!==t)return d("Contributor is already linked to another user");let r={...n,userId:t},o=Ne(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?d("Unable to link contributor to user"):l("Linked contributor to user",r)},deleteNode(e){Ne(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return d("Unable to create comment, missing issue");if(!F(t))return d("Can only comment on issues");let n=xr("comments",e.id,{...e,deleted:!1});return a(n)?d("Unable to create comment"):l("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return d("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return d("Unable to edit comment, missing issue");if(!F(r))return d("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=xr("comments",e,o);return a(s)?d("Unable to edit comment"):l("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return d("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=xr("comments",e,n);return a(r)?d("Unable to delete comment"):l("Deleted comment",n)},getComment(e){return g().comments?.[e]},getCommentsByIssue(e){return Object.values(g().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(g().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 d("Unable to create attachment, missing issue");if(!F(t))return d("Can only attach to issues");let n=Ne(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?d("Unable to create attachment"):l("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return d("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=Ne(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return a(r)?d("Unable to delete attachment"):l("Deleted attachment",n)},getAttachment(e){return g().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(g().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(g().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}=g(),r=n[e];if(!r)return d("Edit target node not found");let o=Wn(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return d("Rename target node not found");let r=Wn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=g();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return ye(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=g(),o=this.getNode(e),s=this.getNode(t);if(!o)return d("Node not found");if(!s)return d("Target parent not found");if(r===e)return d("Cannot move root node");if(e===t)return d("Cannot move node into itself");let i=Wn(o,"move");if(i)return i;if(CR(t,e))return d("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=g(),o=this.getNode(e);if(!o)return d("Node not found");if(r===e)return d("Cannot delete root node");let s=Wn(o,"delete");if(s)return s;let i=new Set,c=m=>{let p=t[m];if(!(!p||i.has(m))){i.add(m);for(let f of ye(p.id))c(f.id)}};c(e);let u={...structuredClone(t)};for(let m of i){if(!u[m])return d("Unable to locate node to delete");u[m]={...u[m],isDeleted:!0}}return n?(N({nodes:u}),l("Successfully tomb stoned",o)):d("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return d("Contributor not found");let n={...t,name:Ts,tombstoned:!0},r=Ne(o=>({...o,contributors:{...o.contributors,[e]:n}}));return a(r)?d("Unable to remove contributor"):l("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return d("Contributor not found");if(n.tombstoned)return d("Cannot rename a removed contributor");let r={...n,name:t},o=Ne(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?d("Unable to rename contributor"):l("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return d("Contributor not found");let r={...n,name:t,tombstoned:!1},o=Ne(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?d("Unable to restore contributor"):l("Restored contributor",r)},createContributor(e){let t=Ne(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?d("Unable to create contributor"):l("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return d("Unable to assign contributor, missing contributor");if(!r)return d("Unable to assign contributor, missing target");let o=Wn(r,"edit");if(o)return o;if(!F(r))return d("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return d("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),l("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return d("Unable to unassign, missing contributor");if(!r)return d("Unable to unassign, missing target");let o=Wn(r,"edit");if(o)return o;if(!F(r))return d("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return l("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),l("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return d("Unable to add tag, missing tag");if(!r)return d("Unable to add tag, missing target");let o=Wn(r,"edit");if(o)return o;if(!F(r))return d("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return d("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),l("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),r=this.getNode(e);if(!n)return d("Unable to remove tag, missing tag");if(!r)return d("Unable to remove tag, missing target");let o=Wn(r,"edit");if(o)return o;if(!F(r))return d("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return l("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),l("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return d("Tag not found");let n={...t,tombstoned:!0},r=Ne(o=>({...o,tags:{...o.tags,[e]:n}}));return a(r)?d("Unable to delete tag"):l("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return d("Tag not found");let r={...n,name:t,tombstoned:!1},o=Ne(s=>({...s,tags:{...s.tags,[e]:r}}));return a(o)?d("Unable to restore tag"):l("Restored tag",r)},createTag(e){let t=Ne(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?d("Could not create tag"):l("Tag created",e)},createNode(e){let t=xr("nodes",e.id,e);return a(t)?d("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return d("Failed to locate node");let n={...t,readonly:!0},r=xr("nodes",e,n);return a(r)?d(r.message):l("Locked node",n)},updateNode(e){let t=xr("nodes",e.id,e);return a(t)?t:l("Updated node",e)},getContributor(e){return g().contributors[e]},getTag(e){let t=g().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return g().tags[e]},getTags(){return Object.values(g().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return g().nodes[e]},getSiblings(e){return ye(e)}}});import Hn from"chalk";import Fh from"string-width";var wR,AR,Sc,TR,kR,Bh,Oh,MR,PR,LR,DR,_R,fc,Uh,ys=h(()=>{"use strict";Je();re();M();yt();Bi();wR=(e,t)=>e+" ".repeat(Math.max(0,t-Fh(e))),AR=(e,t)=>" ".repeat(Math.max(0,t-Fh(e)))+e,Sc=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed contributor","link.contributor.user":"Linked contributor","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),TR=(e,t)=>t?e<t?"up":e>t?"down":null:null,kR=(e,t)=>{let n=E.getNode(e.payload.parent),r=n?Hn.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=TR(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Bh=e=>`${Math.max(1,Math.round(e/1024))} KB`,Oh=e=>E.getAttachment(e)?.name??"",MR=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Hn.bgHex(Te(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Hn.bgHex(Te(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=g().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Hn.hex(Te(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Hn.hex(Te(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Hn.dim(`(${Bh(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Oh(e.payload.id);return t?`"${t}"`:""}default:return""}},PR=e=>{let t=to(Ge(e));return Hn.gray(AR(t,8))},LR=12,DR=e=>wR(`${e}`,LR),_R=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=g().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=E.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Bh(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Oh(e.payload.id);return t?`"${t}"`:""}default:return""}},fc=e=>[Sc(e.action),_R(e)].filter(Boolean).join(" "),Uh=(e,t)=>{let n=PR(e.id),r=DR(e.userName),o=Hn.dim("\u203A"),s=e.action==="move.node"?kR(e,t):[Sc(e.action),MR(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`}});var $h={};Eo($h,{areVirtualNodesEnabled:()=>qs,createOrUpdateVirtualField:()=>xs,createOrUpdateVirtualFieldList:()=>Nc,materializeTicketVirtualNodes:()=>Hs,materializeVirtualNodes:()=>qR,setVirtualNodesEnabled:()=>HR});var FR,BR,OR,UR,jR,$R,xs,Nc,Hs,WR,jh,HR,qs,qR,Da=h(()=>{"use strict";ys();ee();S();Mr();re();tr();M();wr();qr();FR=e=>Le(e,"comments"),BR=e=>Le(e,"description"),OR=e=>Le(e,"assignees"),UR=e=>Le(e,"tags"),jR=e=>Le(e,"history"),$R=e=>Le(e,"attachments"),xs=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=E.getNode(e);if(!c){let p=E.createNode({...Pe.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return a(p)?p:l("Virtual field created",void 0)}if(!ut(c))return d(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==i))return l("Virtual field unchanged",void 0);let m=E.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return a(m)?m:l("Virtual field updated",void 0)},Nc=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=E.getNode(e);if(!i){let m=E.createNode({...Pe.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return a(m)?m:l("Virtual field list created",void 0)}if(!wo(i))return d(`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 l("Virtual field list unchanged",void 0);let u=E.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(u)?u:l("Virtual field list updated",void 0)},Hs=e=>{let t=Et(Wt/4n),n=Et(Wt/2n),r=Et(Wt*3n/4n),o=Et(Wt*7n/8n),s=Et(Wt*15n/16n),i=Et(Wt*13n/16n);if(a(t))return t;if(a(n))return n;if(a(r))return r;if(a(o))return o;if(a(s))return s;if(a(i))return i;let c=xs({id:BR(e.id),name:ge.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(c))return c;let u=Nc({id:OR(e.id),name:ge.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(u))return u;let m=Nc({id:UR(e.id),name:ge.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(a(m))return m;let p=xs({id:FR(e.id),name:ge.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(p))return p;let f=xs({id:$R(e.id),name:ge.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(f))return f;let y=xs({id:jR(e.id),name:ge.HISTORY,parentNodeId:e.id,rank:i.value,value:WR(e),readonly:!0,childRenderAxis:"vertical"});return a(y)?y:l("Ticket virtual nodes materialized",void 0)},WR=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=>Uh(r,n.get(r.action)??[])).join(`
|
|
97
|
-
`)},jh=!0,HR=e=>{jh=e},qs=()=>jh,qR=()=>{let{nodes:e}=g();for(let t of Object.values(e)){if(!F(t))continue;let n=Hs(t);if(a(n))return n}return l("Virtual nodes materialized",void 0)}});var GR,zR,Qi,Cc=h(()=>{"use strict";Je();GR=e=>{switch(e.action){case"add.issue":case"move.node":case"close.issue":case"reopen.issue":return e.payload.parent;default:return null}},zR=(e,t)=>{let n=[];for(let r of e){let o=GR(r);if(o===null||o===n.at(-1)?.laneId)continue;let s=Vn(r);n.push({laneId:o,enteredAt:s===null?t:No(s)})}return n},Qi=(e,t)=>zR(e,t).at(-1)?.enteredAt??t});var Wh=h(()=>{"use strict";S()});var VR,Hh,wc=h(()=>{"use strict";Je();wt();Pr();ys();S();yt();Bt();VR=e=>{let t=new Map,n=new Set,r=o=>{let s=new Set,i=o;for(;i&&!s.has(i);){if(n.has(i))return i;s.add(i),i=t.get(i)}return null};return e.map(o=>{let s=o.payload,i=s?.id;if(!i)return null;o.action==="add.board"&&n.add(i);let c=o.action==="close.issue"?r(i):null,u=s.parent??s.issue;return u&&t.set(i,u),c!==null?c:n.has(i)?i:r(i)})},Hh=(e,t)=>{let n=VR(e);return e.filter((r,o)=>n[o]===t)}});var KR,qh,zh,YR,Er,Es,Gh,XR,so,JR,Vh,io=h(()=>{"use strict";et();Qe();tt();nc();wt();pn();S();Ht();Ri();Wh();ie();M();Bt();wc();KR=null,qh=Promise.resolve(),zh=e=>{let t=qh.then(e,e);return qh=t.then(()=>{},()=>{}),t},YR=e=>{let t=Me(e??process.cwd());return a(t)?d(t.message):l("Resolved Epiq repo root",t.value)},Er=()=>{if(!Nt())return{mode:"live",asOfTime:null};let{timeMode:e}=g();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:KR}},Es="",Gh="",XR=5e3,so=null,JR=async(e={})=>{let t=YR(e.repoRoot);if(a(t))return d(t.message);let n=pt(t.value);if(a(n))return d(n.message);let r=e.start===void 0&&e.end===void 0;if(r&&so&&so.repoRoot===t.value&&so.stateBranch===n.value.stateBranch&&Date.now()-so.fetchedAt<XR)return l("Computed commit timeline",so.result);let o=await W({cwd:t.value,args:["log","--branches","--not",n.value.stateBranch,...e.start!==void 0?[`--since=@${Math.floor(e.start/1e3)}`]:[],...e.end!==void 0?[`--until=@${Math.floor(e.end/1e3)}`]:[],"--shortstat",`--format=${Gh}%H${Es}%at${Es}%an${Es}%s`]});if(a(o))return d(o.message);let s=o.value.stdout.split(Gh).filter(i=>i.trim().length>0).map(i=>{let[c,...u]=i.split(`
|
|
98
|
-
`),[m,p,f,...y]=(c??"").split(Es);if(!m||!p)return null;let x=u.join(" "),R=Number(/(\d+) insertion/.exec(x)?.[1]??0),A=Number(/(\d+) deletion/.exec(x)?.[1]??0);return{sha:m,time:Number(p)*1e3,author:f??"unknown",subject:y.join(Es),linesChanged:R+A,insertions:R,deletions:A}}).filter(i=>i!==null).filter(i=>(e.start===void 0||i.time>=e.start)&&(e.end===void 0||i.time<=e.end));return r&&(so={repoRoot:t.value,stateBranch:n.value.stateBranch,fetchedAt:Date.now(),result:s}),l("Computed commit timeline",s)},Vh=async e=>{let t=e.ref.trim();if(!t)return d("ref must not be empty");if(t.length!==7)return d(`"${t}" is ${t.length} characters; a ref is ${7}. Read it off the issue rather than slicing the id by hand.`);let n=await JR({repoRoot:e.repoRoot});if(a(n))return d(n.message);let r=`${t.toUpperCase()} `,o=c=>c.subject.toUpperCase().startsWith(r),s=n.value,i=[];for(let[c,u]of s.entries()){if(!o(u))continue;let m=s[c+1];i.push({...u,precedingSha:m&&o(m)?m.sha:null})}return l("Matched commits by ref",i)}});import QR from"node:fs";var Rr,Zi,K,Q,z,Nn=h(()=>{"use strict";et();Qe();Zn();Xo();Qt();ur();Pr();ie();wt();S();M();St();io();Rr=e=>{let t=Me(e??process.cwd());return a(t)?d(t.message):l("Resolved Epiq repo root",t.value)},Zi=null,K=async(e,t)=>{let n=Rr(e);if(a(n))return n;let r=Ie({repoRoot:n.value});if(a(r))return d(r.message);let o=qt(n.value);if(a(o))return d(o.message);if(!(Zi!==null&&Zi.repoRoot===n.value&&Zi.stateBranchRoot===r.value&&QR.existsSync(Qn(r.value)))){let p=await Ko({repoRoot:n.value,stateBranchName:o.value});if(a(p))return d(p.message);let f=await Pn({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(a(f))return d(f.message);Zi={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let p=await W({cwd:r.value,args:["pull","--ff-only"]});a(p)&&X.info(3,p.message)}let i={repoRoot:n.value,stateBranchRoot:r.value},c=ir(r.value);if(Du(r.value)===c&&Nt()&&Er().mode==="live")return l("Booted Epiq state, unchanged",i);let u=Ct(r.value);if(a(u))return d(u.message);let m=Yt(u.value.events,u.value.unreadable);return a(m)?d(m.message):(_u(r.value,c),l("Booted Epiq state",i))},Q=()=>{let e=ss();return a(e)?d(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):d("Unable to retrieve user name"):d("Unable to retrieve user id")},z=()=>{let e=Ye();return a(e)?d(e.message):e}});var ao,Kh,co,Ac=h(()=>{"use strict";Je();re();yt();ao=e=>(e.props.tags??[]).map(t=>E.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Te(t.name)})),Kh=e=>E.getCommentsByIssue(e).sort((t,n)=>t.id<n.id?-1:t.id>n.id?1:0).map(t=>({id:t.id,author:E.getContributor(t.authorId)?.name??t.authorName??"Unknown",createdAt:Ge(t.id),body:t.md})),co=e=>(e.props.assignees??[]).map(t=>E.getContributor(t)).filter(t=>t!=null).map(({id:t,name:n})=>({id:t,name:n,color:Te(n)}))});var je,qn,Tc,Sr=h(()=>{"use strict";ee();S();Nn();je=e=>{let t=z();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?d("Issue not found"):F(n)?n.readonly?d("Issue is readonly"):l("Found issue",n):d("Target must be an issue")},qn=e=>{let t=z();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?d("Swimlane not found"):Kn(n)?n.readonly?d("Swimlane is readonly"):l("Found swimlane",n):d("Target must be a swimlane")},Tc=e=>{let t=z();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?d("Board not found"):Yn(n)?n.readonly?d("Board is readonly"):l("Found board",n):d("Target must be a board")}});import ZR from"node:fs";import eS from"node:path";import{ulid as Yh}from"ulid";var tS,Xh,kc,Mc=h(()=>{"use strict";Qt();Re();S();mt();Sr();Hr();Nn();tS=e=>{if(e.filePath)try{return l("Read attachment file",{data:ZR.readFileSync(e.filePath),name:e.name??eS.basename(e.filePath)})}catch(t){return d(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?l("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):d("Provide either filePath or dataBase64")},Xh=()=>{let e=ss();return a(e)?In:e.value.attachmentMaxKb??In},kc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=je(e.issueId);if(a(o))return o;let s=tS(e);if(a(s))return s;let i=hp(t.value.stateBranchRoot,s.value.data,Xh());if(a(i))return i;let c=le(s.value.name).trim()||"image",u=Yh(),m={id:Yh(),...n.value,action:"add.issue.attachment",payload:{id:u,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:c,bytes:i.value.bytes}},p=P([m],t.value.stateBranchRoot);if(a(p))return d(p.message);let f=Wr(i.value.hash,i.value.ext);return l("Added issue attachment",{id:u,issueId:e.issueId,fileName:f,bytes:i.value.bytes,markdown:Rd(c,f)})}});var Pc,vG,Lc,Jh=h(()=>{"use strict";Qt();Je();Bt();ee();S();re();Or();yt();Cc();tt();mt();Hr();St();io();Nn();Ac();Mc();ci();Ce();zo();Pc=async(e={})=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=z();return a(n)?n:l("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})},vG=365*24*60*60*1e3,Lc=async(e={})=>{Lr();let t=Rr(e.repoRoot);if(a(t))return d("Sync failed");let n=Q();if(a(n))return n;let r=await di({cwd:t.value,ownEventFileName:cr(n.value)});return a(r)?(td(r.message),r):(mr(),l("Synced",r.value))}});var Rs,lo,Dc,_c=h(()=>{"use strict";S();tt();Rs=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?l("Resolved targets",t):d("Provide issueId or issueIds")},lo=(e,t)=>{let n=t.done.length,r=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?l(r,t):d(`${r}: ${t.failed.map(o=>`${o.ref} ${o.reason}`).join("; ")}`)},Dc=(e,t)=>{let n={done:[],failed:[]};for(let r of e){let o=t(r);a(o)?n.failed.push({id:r,ref:j(r),reason:o.message}):n.done.push({id:r,ref:j(r)})}return n}});import{ulid as Pt}from"ulid";async function Bc(e){let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=z();if(a(n))return n;let r=n.value.nodes,o=e.query?.trim().toLowerCase(),s=Object.values(r).filter(F).filter(c=>!c.isDeleted).filter(c=>e.includeClosed||c.parentNodeId!==me).filter(c=>e.boardId?(c.parentNodeId?r[c.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(c=>!e.swimlaneId||c.parentNodeId===e.swimlaneId).filter(c=>!e.tag||ao(c).some(u=>Qh(u.name,e.tag))).filter(c=>!e.assignee||co(c).some(u=>Qh(u.name,e.assignee))).filter(c=>!o||c.title.toLowerCase().includes(o)||(c.props.description??"").toLowerCase().includes(o)),i=c=>le((c.parentNodeId?r[c.parentNodeId]?.title:void 0)??"");return e.brief?l("Listed issues",s.map(c=>({id:c.id,ref:j(c.id),title:le(c.title),swimlane:i(c),tags:ao(c).map(u=>u.name),assignees:co(c).map(u=>u.name)}))):l("Listed issues",s.map(c=>({id:c.id,ref:j(c.id),title:le(c.title),description:c.props.description??"",createdAt:Ge(c.id),enteredLaneAt:Qi(c.log??[],Ge(c.id)),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===me,readonly:!!c.readonly,tags:ao(c),assignees:co(c)})))}async function Uc(e){let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=Rs(e);if(a(r))return r;let o=s=>nS(s,n.value,t.value.stateBranchRoot);return e.issueIds?lo("Closed",Dc(r.value,o)):o(r.value[0])}async function $c(e){let t=Rr(e.repoRoot);if(a(t))return t;let n=Q();if(a(n))return n;let r=Ie({repoRoot:t.value});if(a(r))return r;let o=Ct(r.value);if(a(o))return o;let s=Yt(o.value.events,o.value.unreadable);if(a(s))return s;let i=Rs(e);if(a(i))return i;let c=u=>rS(u,e,n.value,r.value);return e.issueIds?lo("Moved",Dc(i.value,c)):c(i.value[0])}var Fc,Qh,Oc,nS,jc,rS,Wc,Hc,Zh=h(()=>{"use strict";et();uc();Je();ur();wt();Re();gc();Bt();ee();S();re();Rt();ys();yt();xn();Cc();tt();mt();Nn();Ac();_c();Sr();Fc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=z();if(a(n))return n;let r=e.idOrRef.trim();if(!r)return d("Provide an issue id or ref");let o=Object.values(n.value.nodes).filter(F).filter(u=>!u.isDeleted),s=o.find(u=>u.id===r),i=s?[s]:o.filter(u=>Uo(u.id,r));if(i.length===0)return d(`No issue matches "${r}"`);if(i.length>1)return d(`"${r}" matches ${i.length} issues: ${i.map(u=>`${j(u.id)} (${le(u.title)})`).join(", ")}. Use a full ref or id.`);let c=i[0];return l("Found issue",{id:c.id,ref:j(c.id),title:le(c.title),description:c.props.description??"",createdAt:Ge(c.id),enteredLaneAt:Qi(c.log??[],Ge(c.id)),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===me,readonly:!!c.readonly,tags:ao(c),assignees:co(c),comments:Kh(c.id)})},Qh=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();Oc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=le(e.title);if(!o)return d("Issue title cannot be empty");let s=e.description??"",i=He("Issue title",o,300)??He("Issue description",s,2e4);if(i)return d(i);if((e.tagNames?.length??0)>20)return d(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return d(`Cannot set more than ${20} assignees at once`);let c=qn(e.parentId);if(a(c))return c;let u=gn(e.parentId,n.value,t.value.stateBranchRoot);if(a(u))return u;let m=Hi({name:o,parent:e.parentId,user:n.value,rank:u.value});if(a(m))return m;let p=[...m.value],f=p.find(A=>A.action==="add.issue")?.payload.id;if(!f)return d("Unable to determine created issue id");s&&p.push({id:Pt(),...n.value,action:"edit.description",payload:{id:f,md:s}});let y=[];for(let A of e.tagNames??[]){let w=le(A).trim();if(!w||y.some(U=>U.name===w))continue;let k=He("Tag name",w,60);if(k)return d(k);let L=E.findTagByName(w),D=L?.id??Pt();L||p.push({id:Pt(),...n.value,action:"create.tag",payload:{id:D,name:w}}),p.push({id:Pt(),...n.value,action:"add.issue.tag",payload:{id:f,tag:D}}),y.push({id:D,name:w})}let x=[];for(let A of e.assigneeNames??[]){let w=le(A).trim();if(!w||x.some(U=>U.name===w))continue;let k=He("Assignee name",w,80);if(k)return d(k);let L=Object.values(r.value.contributors).find(U=>U.name===w),D=L?.id??Pt();L||p.push({id:Pt(),...n.value,action:"create.contributor",payload:{id:D,name:w}}),p.push({id:Pt(),...n.value,action:"add.issue.assignee",payload:{id:f,assignee:D}}),x.push({id:D,name:w})}let R=P(p,t.value.stateBranchRoot);return a(R)?d(R.message):l("Created issue",{id:f,ref:j(f),title:o,parentId:e.parentId,description:s,tags:y,assignees:x})},nS=(e,t,n)=>{let r=je(e);if(a(r))return r;let o=Vt(me,e,{at:"end"},t,n);if(a(o))return o;let s={id:Pt(),...t,action:"close.issue",payload:{id:e,parent:me,rank:o.value}},i=P([s],n);return a(i)?d(i.message):l("Closed issue",{id:e,ref:j(e)})};jc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o||o.isDeleted)return d("Issue not found");if(!F(o))return d("Target must be an issue");if(o.parentNodeId!==me)return d("Issue is not closed");let s=Ki(o);if(!s)return d("Unable to resolve previous parent from issue history");if(s===me)return d("Previous parent resolves to closed swimlane");let i=qn(s);if(a(i))return i;let c=i.value,u=Vt(c.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(u))return u;let m={id:Pt(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:c.id,rank:u.value}},p=P([m],t.value.stateBranchRoot);return a(p)?d(p.message):l("Reopened issue",{id:o.id,ref:j(o.id),parentId:c.id})},rS=(e,t,n,r)=>{let o=je(e);if(a(o))return o;let s=qn(t.parentId);if(a(s))return s;let i=Vt(t.parentId,e,t.position??{at:"end"},n,r);if(a(i))return i;let c={id:Pt(),...n,action:"move.node",payload:{id:e,parent:t.parentId,rank:i.value}},u=P([c],r);return a(u)?d(u.message):l("Moved issue",{id:e,ref:j(e),parentId:t.parentId})};Wc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=je(e.issueId);if(a(o))return o;let s=o.value,i=He("Issue description",e.description,2e4);if(i)return d(i);let c=s.props.description??"";if(c===e.description)return l("No changes made",{id:e.issueId,ref:j(e.issueId),description:c});let u={id:Pt(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},m=P([u],t.value.stateBranchRoot);return a(m)?d(m.message):l("Edited issue description",{id:e.issueId,ref:j(e.issueId),description:e.description})},Hc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=je(e.issueId);if(a(o))return o;let s=o.value,i=le(e.title);if(!i.trim())return d("Issue title cannot be empty");let c=He("Issue title",i,300);if(c)return d(c);if(s.title===i)return l("No changes made",{id:e.issueId,ref:j(e.issueId),title:i});let u={id:Pt(),...n.value,action:"edit.title",payload:{id:e.issueId,name:i}},m=P([u],t.value.stateBranchRoot);return a(m)?d(m.message):l("Edited issue title",{id:e.issueId,ref:j(e.issueId),title:i})}});import{ulid as Gn}from"ulid";var qc,Gc,zc,Vc,Kc,Yc,Xc,Jc,ev=h(()=>{"use strict";et();ur();wt();Re();Bt();ee();S();Rt();xn();tt();mt();io();Nn();Sr();qc=async(e={})=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=z();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:j(o.id),title:o.title,parentId:o.parentNodeId,readonly:!!o.readonly}));return l("Listed boards",r)},Gc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=r.value.nodes[r.value.rootNodeId];if(!o)return d("Workspace not found");if(Er().mode!=="live")return d("Cannot add a board while time travelling");let s=le(e.title);if(!s.trim())return d("Board title cannot be empty");let i=He("Board title",s,300);if(i)return d(i);let c=gn(o.id,n.value,t.value.stateBranchRoot);if(a(c))return c;let u=Gn(),m={id:Gn(),...n.value,action:"add.board",payload:{id:u,name:s,parent:o.id,rank:c.value}},p=P([m],t.value.stateBranchRoot);return a(p)?d(p.message):l("Created board",{id:u,ref:j(u),title:s})},zc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=r.value.nodes[e.boardId];if(!o||o.isDeleted)return d("Board not found");if(!Yn(o))return d("Edit target must be a board");if(o.readonly)return d("Cannot edit readonly board");if(Er().mode!=="live")return d("Cannot rename a board while time travelling");let s=le(e.title);if(!s.trim())return d("Board title cannot be empty");let i=He("Board title",s,300);if(i)return d(i);if(o.title===s)return l("No changes made",{id:e.boardId,ref:j(e.boardId),title:s});let c={id:Gn(),...n.value,action:"edit.title",payload:{id:e.boardId,name:s}},u=P([c],t.value.stateBranchRoot);return a(u)?d(u.message):l("Edited board title",{id:e.boardId,ref:j(e.boardId),title:s})},Vc=async(e={})=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=z();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===me,readonly:!!o.readonly}));return l("Listed swimlanes",r)},Kc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=Tc(e.boardId);if(a(o))return o;if(Er().mode!=="live")return d("Cannot add a swimlane while time travelling");let s=le(e.title);if(!s.trim())return d("Swimlane title cannot be empty");let i=He("Swimlane title",s,300);if(i)return d(i);let c=gn(e.boardId,n.value,t.value.stateBranchRoot);if(a(c))return c;let u=Gn(),m={id:Gn(),...n.value,action:"add.swimlane",payload:{id:u,name:s,parent:e.boardId,rank:c.value}},p=P([m],t.value.stateBranchRoot);return a(p)?d(p.message):l("Created swimlane",{id:u,ref:j(u),title:s,boardId:e.boardId})},Yc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=qn(e.swimlaneId);if(a(o))return o;let s=o.value,i=le(e.title);if(!i.trim())return d("Swimlane title cannot be empty");let c=He("Swimlane title",i,300);if(c)return d(c);if(s.title===i)return l("No changes made",{id:e.swimlaneId,ref:j(e.swimlaneId),title:i});let u={id:Gn(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:i}},m=P([u],t.value.stateBranchRoot);return a(m)?d(m.message):l("Edited swimlane title",{id:e.swimlaneId,ref:j(e.swimlaneId),title:i})},Xc=async e=>{let t=Rr(e.repoRoot);if(a(t))return t;let n=Q();if(a(n))return n;let r=Ie({repoRoot:t.value});if(a(r))return r;let o=Ct(r.value);if(a(o))return o;let s=Yt(o.value.events,o.value.unreadable);if(a(s))return s;let i=qn(e.swimlaneId);if(a(i))return i;let c=Tc(e.boardId);if(a(c))return c;let u=Vt(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(a(u))return u;let m={id:Gn(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:u.value}},p=P([m],r.value);return a(p)?d(p.message):l("Moved swimlane",{id:e.swimlaneId,ref:j(e.swimlaneId),boardId:e.boardId})},Jc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=qn(e.swimlaneId);if(a(o))return o;let s={id:Gn(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},i=P([s],t.value.stateBranchRoot);return a(i)?d(i.message):l("Deleted swimlane",{id:e.swimlaneId,ref:j(e.swimlaneId)})}});import{ulid as po}from"ulid";async function Qc(e){let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=Rs(e);if(a(r))return r;let o=le(e.tagName).trim();if(!o)return d("Tag name cannot be empty");let s=He("Tag name",o,60);if(s)return d(s);let i={done:[],failed:[]};for(let x of r.value){let R=je(x);a(R)?i.failed.push({id:x,ref:j(x),reason:R.message}):i.done.push({id:x,ref:j(x)})}if(!e.issueIds&&i.failed[0])return d(i.failed[0].reason);if(i.done.length===0)return d(lo("Tagged",i).message);let c=E.findTagByName(o),u=c?.id??po(),m=[...c?[]:[{id:po(),...n.value,action:"create.tag",payload:{id:u,name:o}}],...i.done.map(({id:x})=>({id:po(),...n.value,action:"add.issue.tag",payload:{id:x,tag:u}}))],p=P(m,t.value.stateBranchRoot);if(a(p))return d(p.message);let f={id:u,name:o};if(!e.issueIds)return l("Added issue tag",{...i.done[0],tag:f});let y=lo("Tagged",i);return a(y)?y:l(y.message,{...y.value,tag:f})}var Zc,el,tl,tv=h(()=>{"use strict";Re();S();re();xn();tt();mt();Nn();_c();Sr();Zc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return d("Tag not found");if(o.tombstoned)return d("Tag is already deleted");let s=[{id:po(),...n.value,action:"tombstone.tag",payload:{id:e.tagId}}],i=P(s,t.value.stateBranchRoot);return a(i)?d(i.message):l("Deleted tag",{id:o.id,name:o.name})},el=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return d("Tag not found");if(!o.tombstoned)return d("Tag is not deleted");if(E.findTagByName(o.name))return d(`Cannot restore: another tag is already named "${o.name}"`);let s=[{id:po(),...n.value,action:"restore.tag",payload:{id:e.tagId,name:o.name}}],i=P(s,t.value.stateBranchRoot);return a(i)?d(i.message):l("Restored tag",{id:o.id,name:o.name})},tl=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=je(e.issueId);if(a(o))return o;if(!r.value.tags[e.tagId])return d("Tag not found");let s={id:po(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=P([s],t.value.stateBranchRoot);return a(i)?d(i.message):l("Removed issue tag",{id:e.issueId,ref:j(e.issueId),tagId:e.tagId})}});import{ulid as Cn}from"ulid";var oS,nv,nl,rv,rl,ol,sS,sl,il,al,ov=h(()=>{"use strict";S();M();$t();zn();wt();Re();wc();yt();xn();tt();mt();Nn();Sr();oS=()=>{let e=Ye(),t=a(e)?[]:e.value.eventLog??[],n=new Map;for(let r of t)r.userId&&r.userName&&n.set(r.userId,r.userName);return n},nv=(e,t)=>{let n=new Map(e);for(let r of Object.values(t))n.set(r.id,r.name);return n},nl=async e=>{let t=ua(e.name,"name");if(a(t))return d(t.message);let n=await K(e.repoRoot,{pull:!1});if(a(n))return n;let r=Q();if(a(r))return r;let o=z();if(a(o))return o;let s=r.value,i=!!o.value.contributors[s.userId];if(!i){let c=P([{id:Cn(),...s,action:"create.contributor",payload:{id:s.userId,name:s.userName}}],n.value.stateBranchRoot);if(a(c))return d(c.message)}return l(`Assumed ${s.userName}`,{...s,registered:!i})},rv=async(e,t)=>{let n=Va(e);if(a(n))return;let r;for(let o of n.value)o.userId===t&&(r=o.userName??r);return r===void 0?void 0:{id:t,name:r}},rl=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=je(e.issueId);if(a(o))return o;let s=e.self?n.value.userId:e.assigneeId;if(s){let w=r.value.contributors[s],k=w?void 0:await rv(t.value.stateBranchRoot,s);if(!w&&!k)return d("Unknown assignee id");let L=w??k,D=[...w?[]:[{id:Cn(),...n.value,action:"create.contributor",payload:{id:L.id,name:L.name}}],{id:Cn(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:L.id}}],U=P(D,t.value.stateBranchRoot);return a(U)?d(U.message):l("Added issue assignee",{id:e.issueId,ref:j(e.issueId),assignee:{id:L.id,name:L.name}})}let i=le(e.assigneeName??"").trim();if(!i)return d("Provide assigneeId, self or assigneeName");let c=He("Assignee name",i,80);if(c)return d(c);let m=[...nv(oS(),r.value.contributors).entries()].filter(([,w])=>w===i);if(m.length>1)return d(`"${i}" matches ${m.length} contributors (${m.map(([w])=>w).join(", ")}). Assign by assigneeId to choose.`);let p=m[0];if(!p&&!e.createUnlinked)return d(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[f=Cn(),y=i]=p??[],R=[...!!r.value.contributors[f]?[]:[{id:Cn(),...n.value,action:"create.contributor",payload:{id:f,name:y}}],{id:Cn(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:f}}],A=P(R,t.value.stateBranchRoot);return a(A)?d(A.message):l("Added issue assignee",{id:e.issueId,ref:j(e.issueId),assignee:{id:f,name:y}})},ol=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;if(!r.value.contributors[e.contributorId])return d("Contributor not found");if(await rv(t.value.stateBranchRoot,e.contributorId))return d("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let i=[{id:Cn(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],c=P(i,t.value.stateBranchRoot);return a(c)?d(c.message):l("Tombstoned contributor",{id:e.contributorId,name:Ts})},sS=async(e,t)=>{let n=ar(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},sl=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=r.value.contributors[e.contributorId];if(!o)return d("Contributor not found");if(!o.tombstoned)return d("Contributor is not tombstoned");let s=await sS(t.value.stateBranchRoot,e.contributorId);if(!s)return d("Cannot restore this contributor \u2014 no original name found in the event log");let i=[{id:Cn(),...n.value,action:"restore.contributor",payload:{id:e.contributorId,name:s}}],c=P(i,t.value.stateBranchRoot);return a(c)?d(c.message):l("Restored contributor",{id:e.contributorId,name:s})},il=async(e={})=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=ar(t.value.stateBranchRoot);if(a(o))return d(o.message);let s=e.boardId?Hh(o.value,e.boardId):o.value,i=new Map,c=new Set,u=new Set,m=Va(t.value.stateBranchRoot);if(a(m))return d(m.message);for(let x of m.value)x.userId&&u.add(x.userId);for(let x of s)x.userId&&(i.set(x.userId,x.userName??""),c.add(x.userId));let p=r.value.contributors,y=[...nv(i,p).entries()].map(([x,R])=>({id:x,name:R,color:Te(R),isSelf:x===n.value.userId,isExternal:!c.has(x),isRemoved:p[x]?.tombstoned===!0,hasAuthoredAnywhere:u.has(x)}));return l("Listed board contributors",y)},al=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=je(e.issueId);if(a(o))return o;if(!r.value.contributors[e.assigneeId])return d("Assignee not found");let s={id:Cn(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=P([s],t.value.stateBranchRoot);return a(i)?d(i.message):l("Removed issue assignee",{id:e.issueId,ref:j(e.issueId),assigneeId:e.assigneeId})}});import{ulid as na}from"ulid";var dl,cl,ll,sv=h(()=>{"use strict";Re();S();xn();Nn();Sr();dl=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=je(e.issueId);if(a(o))return o;let s=e.body.trim();if(!s)return d("Comment cannot be empty");if(s.length>4e3)return d(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i=na(),c={id:na(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},u=P([c],t.value.stateBranchRoot);return a(u)?d(u.message):l("Added issue comment",{id:i,issueId:e.issueId,body:s})},cl=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return d("Unable to resolve comment");if(o.payload.author!==n.value.userId)return d("You can only delete your own comments");let s=je(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return l("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:na(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=P([c],t.value.stateBranchRoot);return a(u)?d(u.message):l("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},ll=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Q();if(a(n))return n;let r=z();if(a(r))return r;let o=r.value.eventLog.find(p=>p.action==="add.issue.comment"&&p.payload.id===e.commentId);if(!o)return d("Unable to resolve comment");if(o.payload.author!==n.value.userId)return d("You can only edit your own comments");let s=je(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return d("Comment was deleted");let c=e.body.trim();if(!c)return d("Comment cannot be empty");if(c.length>4e3)return d(`Comment cannot exceed ${4e3} characters (got ${c.length})`);let u={id:na(),...n.value,action:"edit.issue.comment",payload:{id:e.commentId,issue:o.payload.issue,md:c}},m=P([u],t.value.stateBranchRoot);return a(m)?d(m.message):l("Edited issue comment",{id:e.commentId,issueId:o.payload.issue,body:c})}});var iv=h(()=>{"use strict";Jh();Zh();ev();tv();ov();sv();Mc()});import{ulid as iS}from"ulid";var av,dv,cv,lv=h(()=>{"use strict";zn();Or();Qt();S();ic();St();av=[{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)"}],dv=e=>e.trim().toLowerCase(),cv=async(e={})=>{let t=$r();if(a(t))return d(t.message);let n=t.value,r=e.userName?.trim(),o=(process.env[It]??"").trim();if(r&&o&&dv(r)===dv(o))return d(`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 av){let k=s[w.name],L=i[w.name];if(!(k===void 0||L===void 0||k===L))return d(`This machine is already set up with ${w.name} ${JSON.stringify(L)}; epiq_project_init does not change it. Call again without ${w.name}, or let the user change it in the TUI with :config.`)}let c={};if(s.userName&&!i.userName&&(c.userName=s.userName),s.preferredEditor&&!i.preferredEditor&&(c.preferredEditor=s.preferredEditor),s.autoSync!==void 0&&i.autoSync===void 0&&(c.autoSync=s.autoSync),(c.userName||i.userName)&&!n.userId&&(c.userId=iS()),Object.keys(c).length>0){let w=ot(c);if(a(w))return d(w.message)}let u={...n,...c},m=av.filter(w=>{let k=u[w.name];return typeof k=="boolean"?!1:!k?.trim()});if(m.length>0){let w=m.map(k=>`${k.name} (${k.question})`).join("; ");return d(`Setup incomplete. Ask the user for: ${w}. Then call epiq_project_init again with the answers; what was given so far is saved.`)}let p={userId:u.userId??"",userName:u.userName??""};if(!p.userId||!p.userName)return d("Missing Epiq user id");let f=await $i({cwd:e.repoRoot??process.cwd(),user:p});if(a(f))return f;let{defaultEvents:y,...x}=f.value,R=es({root:x.repoRoot});a(R)&&X.info(R.message);let A=x.warnings.length===0?"Project initialized":`Project initialized, with warnings: ${x.warnings.join(" ")}`;return l(A,{...x,user:p})}});var rn,ra=h(()=>{"use strict";rn=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""})});var aS,uv,mv=h(()=>{"use strict";ra();aS=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},uv=({commits:e,patch:t})=>{let n=e.map(i=>i.time),o=t.files.map(i=>({...rn(i),changed:i.addedCount+i.removed})).reduce((i,c)=>i===null||c.changed>i.changed?c:i,null),s=t.insertions+t.deletions;return{commits:e.length,authors:[...new Set(e.map(i=>i.author))].sort(),firstCommitAt:n.length?Math.min(...n):null,lastCommitAt:n.length?Math.max(...n):null,files:t.files.length,filesAdded:t.files.filter(i=>i.status==="added").length,filesModified:t.files.filter(i=>i.status==="modified").length,filesDeleted:t.files.filter(i=>i.status==="deleted").length,binaryFiles:t.files.filter(i=>i.binary).length,directories:new Set(t.files.map(i=>aS(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 Be,Lt,ul,fo,dS,H,oa,sa,pv,cS,fv,Nr,Ns,lS,uS,go,mS,pS,fS,Ut,gv,hv,vv,gS,hS,yv,bv,ho=h(()=>{"use strict";Be={line:["//"],block:[["/*","*/"]]},Lt={line:["#"],block:[]},ul={line:["--"],block:[]},fo={line:[],block:[["<!--","-->"]]},dS={line:[],block:[]},H=(e,t)=>({name:e,comment:t}),oa=H("TypeScript",Be),sa=H("JavaScript",Be),pv={ts:oa,tsx:oa,mts:oa,cts:oa,js:sa,jsx:sa,mjs:sa,cjs:sa,py:H("Python",{line:["#"],block:[['"""','"""']]}),rb:H("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:H("Go",Be),rs:H("Rust",Be),java:H("Java",Be),kt:H("Kotlin",Be),swift:H("Swift",Be),c:H("C",Be),h:H("C",Be),cc:H("C++",Be),cpp:H("C++",Be),hpp:H("C++",Be),cs:H("C#",Be),php:H("PHP",Be),scala:H("Scala",Be),dart:H("Dart",Be),lua:H("Lua",ul),hs:H("Haskell",ul),sql:H("SQL",ul),ex:H("Elixir",Lt),exs:H("Elixir",Lt),pl:H("Perl",Lt),r:H("R",Lt),jl:H("Julia",Lt),sh:H("Shell",Lt),bash:H("Shell",Lt),zsh:H("Shell",Lt),vue:H("Vue",fo),svelte:H("Svelte",fo),html:H("HTML",fo),xml:H("XML",fo),md:H("Markdown",fo),mdx:H("Markdown",fo),css:H("CSS",{line:[],block:[["/*","*/"]]}),scss:H("CSS",Be),less:H("CSS",Be),yml:H("YAML",Lt),yaml:H("YAML",Lt),toml:H("TOML",Lt),ini:H("INI",Lt),json:H("JSON",dS)},cS="Other",fv=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},Nr=e=>pv[fv(e)]?.name??cS,Ns=e=>pv[fv(e)]?.comment??null,lS=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],uS=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,go=e=>uS.test(e)||lS.some(t=>t.test(e)),mS=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,pS=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,fS=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,Ut=e=>mS.test(e)||pS.test(e)||fS.test(e),gv=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),hv=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),vv=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),gS=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,hS=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,yv=e=>gS.test(e),bv=e=>hS.test(e)});var Iv,vS,ml,yS,xv,pl=h(()=>{"use strict";ho();Iv=/\b(TODO|FIXME|HACK|XXX)\b/,vS=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,ml=(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"},yS=(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},xv=({patch:e,repoShareByLanguage:t})=>{let n=new Map,r=0,o=0,s=0,i=0,c=0,u=0;for(let p of e.files){if(p.binary||Ut(p.path))continue;let f=Ns(p.path);if(!f||f.line.length===0&&f.block.length===0)continue;let y=Nr(p.path),x=n.get(y)??{comment:0,code:0};for(let{text:R}of p.added){let A=ml(R,f);if(Iv.test(R)&&i++,A==="blank"){s++;continue}if(A==="comment"){r++,x.comment++,f&&vS.test(yS(R,f))&&u++;continue}o++,x.code++}for(let{text:R}of p.removedLines)Iv.test(R)&&c++;n.set(y,x)}let m=r+o;return{byLanguage:[...n.entries()].map(([p,f])=>({name:p,commentLines:f.comment,codeLines:f.code,share:f.comment+f.code===0?0:f.comment/(f.comment+f.code),repoShare:t?.get(p)??null})).sort((p,f)=>f.commentLines+f.codeLines-(p.commentLines+p.codeLines)),commentLines:r,codeLines:o,blankLines:s,share:m===0?0:r/m,todoLinesAdded:i,todoLinesRemoved:c,commentedOutCodeLines:u}}});var bS,ia,fl,IS,xS,ES,Ev,Rv=h(()=>{"use strict";ho();ra();bS=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,ia=6,fl=10,IS=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)},xS=(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)},ES=e=>{if(e.length<ia*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let r=0;r+ia<=e.length;r++){let o=e.slice(r,r+ia);if(o.some(c=>c.text.length<3))continue;let s=o.map(c=>c.text).join(`
|
|
99
|
-
`),
|
|
100
|
-
`)){if(f.startsWith(hl)){r=f.slice(hl.length).trim(),o=null,s=null,i=null,c=!1;continue}if(f.startsWith("diff --git ")){o=null,i=null,c=!0,s=wS.exec(f)?.[1]??null;continue}if(c&&f.startsWith("Binary files ")&&s){let[,x=""]=/^Binary files (.*) differ$/.exec(f)??[],[R="",A=""]=x.split(" and ");o=p(s,Av(R==="/dev/null"?null:R,A==="/dev/null"?null:A)),o.entry.binary=!0;continue}if(c&&f.startsWith("--- ")){i=wv(f.slice(4),"a/");continue}if(c&&f.startsWith("+++ ")){let x=wv(f.slice(4),"b/"),R=x??i??s;R&&(o=p(R,Av(i,x)));continue}let y=CS.exec(f);if(y){u=Number(y[1]),c=!1;continue}if(o){if(f.startsWith("+")){let x=f.slice(1);e.insertions++,o.entry.addedCount++,e.retainedLines<gl&&(o.entry.added.push({sha:r,line:u,text:x}),e.retainedLines++),o.pendingByText.size<SS&&o.pendingByText.set(x,(o.pendingByText.get(x)??0)+1),u++;continue}if(f.startsWith("-")){let x=f.slice(1);e.deletions++,o.entry.removed++,e.retainedLines<gl&&(o.entry.removedLines.push({sha:r,line:0,text:x}),e.retainedLines++);let R=o.pendingByText.get(x)??0;R>0&&x.trim().length>2&&(e.selfChurn++,o.pendingByText.set(x,R-1))}}}},kS=e=>({files:[...e.byPath.values()].map(t=>t.entry),insertions:e.insertions,deletions:e.deletions,selfChurn:e.selfChurn,retainedLines:e.retainedLines}),Tv=async({repoRoot:e,shas:t})=>{if(t.length===0)return l("No commits to scan",{files:[],insertions:0,deletions:0,selfChurn:0,scannedCommits:0,truncated:!1});let n=t.slice(0,RS).reverse(),r=AS(),o=0,s=0,i=!1;for(let u=0;u<n.length;u+=Cv){let m=n.slice(u,u+Cv),p=await W({cwd:e,args:["-c","core.quotePath=false","show","--unified=0","--no-renames","--no-color",`--format=${hl}%H`,...m]});if(a(p))return d(p.message);if(TS(r,p.value.stdout),o+=p.value.stdout.length,s+=m.length,o>NS){i=!0;break}}let c=kS(r);return l("Scanned ticket patch",{files:c.files,insertions:c.insertions,deletions:c.deletions,selfChurn:c.selfChurn,scannedCommits:s,truncated:i||s<t.length||c.retainedLines>=gl})}});var MS,PS,Mv,Pv=h(()=>{"use strict";Qe();S();pl();ho();MS=40,PS=/^\d{6} blob ([0-9a-f]{40})\t(.+)$/,Mv=async({repoRoot:e,sha:t})=>{let n=await Oe({cwd:e,args:["-c","core.quotePath=false","ls-tree","-r",`${t}~1`]});if(n.exitCode!==0)return null;let r=new Set,o=new Map;for(let p of n.stdout.split(`
|
|
101
|
-
`)){let
|
|
102
|
-
`)){let k=ml(w,x);k==="comment"&&A.comment++,k==="code"&&A.code++}u.set(R,A)}let m=new Map;for(let[p,f]of u){let y=f.comment+f.code;y>0&&m.set(p,f.comment/y)}return{languages:r,commentShareByLanguage:m}}});var Lv,Dv=h(()=>{"use strict";ho();ra();Lv=({patch:e})=>{let t=0,n=0,r=[],o=[],s=0,i=0;for(let c of e.files)if(!(c.binary||Ut(c.path))&&go(c.path)){t+=c.addedCount,n+=c.removed,c.status==="added"&&r.push(rn(c)),c.status==="deleted"&&o.push(rn(c));for(let{text:u}of c.added)yv(u)&&s++,bv(u)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:r,deletedTestFiles:o,skippedTestLinesAdded:s,focusedTestLinesAdded:i}}});var LS,_v,Fv=h(()=>{"use strict";S();mv();pl();Rv();Nv();kv();Pv();Dv();LS=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,_v=async({repoRoot:e,ref:t,commits:n})=>{let r=await Tv({repoRoot:e,shas:n.map(c=>c.sha)});if(a(r))return d(r.message);let o=r.value,s=LS(n),i=s?await Mv({repoRoot:e,sha:s}):null;return l("Derived issue stats",{ref:t,shape:uv({commits:n,patch:o}),languages:Sv({patch:o,languagesBefore:i?.languages??null}),tests:Lv({patch:o}),comments:xv({patch:o,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:Ev({patch:o})})}});var DS,Cs,_S,Bv,Ov=h(()=>{"use strict";S();Fv();tt();ie();io();DS=32,Cs=new Map,_S=(e,t)=>{if(Cs.set(e,t),Cs.size>DS){let n=Cs.keys().next();n.done||Cs.delete(n.value)}return t},Bv=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return d("idOrRef must not be empty");let n=t.length>7?j(t):t.toUpperCase(),r=Me(e.repoRoot??process.cwd());if(a(r))return d(r.message);let o=r.value,s=await Vh({repoRoot:o,ref:n});if(a(s))return d(s.message);let i=s.value.map(p=>({sha:p.sha,time:p.time,author:p.author,subject:p.subject})),c=[o,n,i.map(p=>p.sha).join(",")].join(" "),u=Cs.get(c);if(u)return l("Derived issue stats",u);let m=await _v({repoRoot:o,ref:n,commits:i});return a(m)?d(m.message):l("Derived issue stats",_S(c,m.value))}});var vo,vl,Uv=h(()=>{"use strict";vo=".claude/skills/epiq/SKILL.md",vl="---\nname: epiq\ndescription: Workflow rules for working the epiq issue board \u2014 use the epiq MCP, sync on demand, scope tickets small, keep status/tags accurate, and communicate via comments.\n---\n\n# Epiq board workflow\n\n- **Never test against the real board.** Point any dev server, manual test or test run at a throwaway project, never at this repo's own. Deleting test tickets afterwards does not undo the events. Stop the dev server when you're done rather than leaving it autosyncing.\n- **Use the epiq MCP tools** (`epiq_*`) for all board operations \u2014 never the `epiq` CLI or hand-edited state files.\n- **Never edit the state branch directly.** Don't check it out, don't write to its worktree, don't touch the event log or any file under it by hand or by script \u2014 go through the MCP for every read and write. The event log is the system of record: an edit made outside it bypasses validation and ordering, and can corrupt history in ways no later fix can undo.\n- **Sync is on-demand only.** MCP reads/writes operate on local state and never pull/push automatically. Call `epiq_sync` explicitly when you need the latest remote state or want to publish local changes.\n- **Break work into small, scoped tickets.** One ticket per independent unit of work, not one giant ticket for a whole feature/epic. Small tickets move through the board cleanly and are easier to review.\n- **A small request tightly coupled to a ticket goes into that ticket, not a new one.** When the user asks for a tweak that only makes sense as part of work a ticket already covers \u2014 halving a limit it just introduced, moving a control it just added \u2014 do not file a fresh ticket for it. Record the new requirement as a comment on the original ticket and fold it into the description, move the ticket back to Ongoing if it had already reached Done, prefix the follow-up's commits with that ticket's ref, and add a further `Solution:` comment when it lands, so the ticket's own commit list tells the whole story. `QPPR7PE` is what this avoids: a one-line follow-up to `MBB6WY5` (halve the log cap it had just introduced) that now lives on a ticket of its own. The original does not have to be the ticket you took this session: any ticket open on the board and assigned to you counts. A new ticket is for work that stands on its own \u2014 that someone else could pick up cold, or that needs more than a line or two to describe.\n- **Keep the status column current as work progresses**\n- **Assign the ticket to yourself when you pick it up**, alongside moving it to Ongoing \u2014 so the board shows who is on what, not just what is in flight.\n- **A ticket you file for work you will do this session is assigned to you as you file it.** Filing it unassigned and picking it up a minute later leaves a window where the board shows nobody on it. Picking up a ticket assigned to somebody else is fine \u2014 but ask the user first: it may be mid-flight in another session, and the assignee is what says so.\n- **Take a name as soon as this skill loads, and say it.** Your board identity is `provider/human-name` \u2014 the model provider, a slash, then a short human first name: `claude/peter`, `codex/fred`. Announce it as your first line, exactly `Assuming claude/peter`, and work under it for the whole session so the log reads \"claude/peter did X\" rather than signing the user's name to your work. Before inventing one, call `epiq_contributor_list` and reuse an existing identity for your provider if there is one \u2014 a name is permanent once it has authored anything (`tombstoneContributor` refuses authors), and each new one adds a contributor and an event log file forever. Keep the name stable across sessions; never rename yourself mid-session.\n- **Make the name true with `epiq_actor_assume`, before your first board write.** Announcing alone changes nothing: the writes would still be signed with the user's name. The tool takes the identity for the rest of the session and registers it, so the board carries `claude/peter` rather than the sanitized `claude-peter` the log file name would give. It is idempotent, so re-announcing is free; if it refuses because the server was launched under a name, that name wins \u2014 work under the one it reports and say so. Never claim an attribution the tool did not confirm.\n- **Boot your own MCP instance, and never share one.** `epiq_actor_assume` binds the name to the server process it is called on, so two sessions on one server \u2014 or a session on the user's own instance \u2014 would sign every write with whichever name was assumed last, and the log would fold them into one contributor. Every session therefore needs a server process of its own before its first board call: the one Claude Code spawns for the session counts, and if that never connected (a `CONNECT_TIMEOUT` at boot), start one yourself \u2014 `npx -y -p epiq@latest epiq-mcp` speaks MCP JSON-RPC over stdio, so a small script holding that process and forwarding `tools/call` requests is enough \u2014 rather than waiting on the user or borrowing another session's. Assume the name on *that* process; a restart forgets it, so assume it again before the next write. Kill what you started when the session ends, including the `epiq-mcp` child, which outlives its parent.\n- **When other agents may be running, ask which name to take rather than picking one.** Nothing stops two live agents answering to one name \u2014 the log is a CRDT and takes concurrent writers happily, so they would converge into one indistinguishable identity rather than fail. Another session is likely whenever there is more than one `epiq-mcp` process, another worktree with recent changes, or the user says so; in that case list the existing names for your provider from `epiq_contributor_list` and ask the user which one is free, before `epiq_actor_assume` \u2014 a name once assumed binds the server process, and a second name is refused until it restarts. Ask with the names in the question, not \"which name?\": the user is choosing between identities they can see on the board.\n- **Name the terminal window after the identity.** Several sessions look alike; the name in the tab is how the user tells which window is `claude/peter`. The session cannot reach the terminal itself \u2014 the shell it runs has no tty \u2014 so put the request in the announcement line: `Assuming claude/peter \u2014 please /rename claude/peter so this window carries the name.`\n- **Prefix commits with the ticket ref. **Retrieve the ref programmatically, NEVER DERIVE IT.\\*\\* Read the `ref` field off the MCP response (`epiq_issue_list` and `epiq_board_list` include it on every entry). This is what link-by-reference feature matches on.\n- **Work in a worktree, and leave the root checkout alone.** Take one before the first edit (`EnterWorktree`, or `git worktree add .claude/worktrees/<ref>-<slug>` for a branch that already exists), and never check a feature branch out at the root: the root is where `main` belongs and where the user checks it out themselves, and a branch checked out anywhere is unavailable everywhere else. For the same reason `main` never goes *into* a worktree. Several sessions share this repository at once, so a shared checkout also means one session's `checkout` or `reset` quietly discarding another's work. A fresh worktree needs its own `npm install` before the hooks and suites will run there.\n- **Never work on main, and never merge into it locally. Every change reaches main through a pull request.** Branch before the first edit, push the branch, open the PR, let the gate run, then integrate it. A local merge into `main` looks like it worked and is invisible to everyone else: the work is on nobody's remote, no PR ran the gate over it, and it is one `git fetch origin +main:main` away from vanishing from the branch you are sitting on. That has already happened here \u2014 a tag-filter feature and a scrubber-URL feature lived only in one machine's local `main` for a day, and disappeared the moment somebody synced main with the remote. If you find yourself with commits on local `main`, move them onto a branch and open a PR before doing anything else.\n- **Always rebase onto the target, never merge into it.** Rebase the branch onto the target first, then integrate with a rebase merge \u2014 `gh pr merge --rebase`, never `--merge`. Main stays a flat sequence of ref-prefixed commits, which is what the commit\u2194ticket linking reads. A merge commit adds a subject carrying no ref and buries the branch's commits behind it.\n- **Squashing the branch down first is fine \u2014 one commit per ticket ref.** A branch's worth of fixups is history nobody needs on main, so collapsing it into a single commit (`git rebase -i`, or `gh pr merge --squash` with a ref-prefixed subject) is welcome, provided every commit that lands still opens with its ticket's ref. What the linking cannot survive is a squash *across* refs: fold two tickets' commits into one subject and one of them loses its commits for good. So a branch carrying two refs squashes to two commits, not one \u2014 and check the resulting subject before integrating, because `--squash` defaults to the PR title, which is only right if the title carries the ref.\n- **The git user is the sole author of every commit you write.** Commit under the repo's configured `user.name` / `user.email` and nothing else: no `Co-Authored-By:` line, no `Claude-Session:` line, no `\u{1F916} Generated with` footer, and never an `--author` override naming Claude or a tool. The commit body ends with the last line of prose. This holds for amends and rebases too \u2014 check `git log --format='%an <%ae>%n%b'` over the branch before pushing, because a trailer added by a default template survives a rebase and reaches main unnoticed. It does **not** license rewriting anyone else's authorship: commits by other contributors keep their author, and reassigning them would both misattribute their work and mean force-pushing main.\n- **Tag tickets properly.** Reuse existing tags where they fit (check current issues/tags first) instead of inventing near-duplicates.\n- **Read the ticket's comments before starting, not just its description.** The description is what was known when the ticket was written; comments carry later context \u2014 narrowed scope, a decision already taken, a dead end someone hit, a correction to the original diagnosis. Working from the description alone risks redoing settled work or implementing something that was already ruled out.\n- **Use comments to communicate deviations.** If the work diverges from what the ticket describes \u2014 scope changes, findings, blockers, test results \u2014 record it as a comment on the ticket, not just in chat.\n- When a ticket is done, **Document the outcome in a comment starting with `Solution:`.** Use that exact prefix as the comment's opening line, so `^Solution:` finds every resolved ticket on the board. Say what actually resolved it \u2014 the commit, the approach taken, and anything a reader would otherwise have to reverse-engineer from the diff; a bare commit hash is not a solution. Use the same prefix when a ticket is closed _without_ a code change, and say why.\n- **Attach a screenshot only when a picture carries what words cannot** \u2014 a layout that has to be seen, a rendering bug, a chart whose shape is the point. It is the special case, not a routine part of a `Solution:` comment: most outcomes are better described than photographed, and a screenshot of something a sentence already covers costs everyone the bytes below. When one does earn its place, use `epiq_issue_attachment_add` (it takes a file path) and paste the `markdown` it returns into the comment.\n- **Crop and compress it first.** `epiq_issue_attachment_add` stores the file exactly as it finds it \u2014 only the GUI compresses on upload \u2014 so a raw full-screen capture goes in at full size, up to the 500 KB cap. The blob lands in `.epiq/media/` on the state branch, replicates to every clone, and is never removed: deleting an attachment writes a tombstone and the bytes stay, so time travel can still resolve them. Crop to the region that makes the point, scale it down, and land well under the cap rather than against it. An oversized image is permanent, for everybody \u2014 the same reason the text limits exist.\n- **Be concise.** Titles, descriptions, and comments should be scannable, not essays.\n- If a ticket is blocked, **record the blocker in a comment** and move it to Blocked (or tag it blocked if there is no Blocked column).\n- If a you decide to take a new approach, make sure to document the fork in a new comment, and tag the ticket with a \"fork\" tag, **update the description** to reflect the new plan. Don't leave it as-is and expect readers to infer the change from comments.\n- **Park decisions that are the user's to make.** A design fork, a change with blast radius beyond its ticket, anything you'd want a second opinion on \u2014 file a ticket tagged `human-input-needed` naming the options and the trade-off, then carry on with whatever doesn't depend on the answer. Settling it alone in chat, while nobody is reading, is a decision the user never made.\n- **Findings from a code review get their own tickets**, tagged `from-review`, with the description saying which branch or PR the review covered \u2014 so the provenance survives even if the tag doesn't.\n"});import aa from"node:fs";import jv from"node:path";var $v,Wv=h(()=>{"use strict";et();S();Uv();$v=async(e={})=>{let t=await gt(e.repoRoot??process.cwd());if(a(t))return d(t.message);let n=jv.join(t.value,vo);if(aa.existsSync(n)){if(aa.readFileSync(n,"utf8")===vl)return l("Skill already installed and up to date",{path:n,written:!1});if(!e.force)return d(`${vo} already exists and differs from the bundled skill. Pass force:true to overwrite it.`)}try{aa.mkdirSync(jv.dirname(n),{recursive:!0}),aa.writeFileSync(n,vl,"utf8")}catch(r){return d(r instanceof Error?`Failed to write ${vo}: ${r.message}`:`Failed to write ${vo}`)}return l(`Installed skill at ${vo}`,{path:n,written:!0})}});var qv={};Eo(qv,{createMcpServer:()=>Hv,resultJson:()=>yl,startMcpServer:()=>US});import{McpServer as BS}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as OS}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as v}from"zod";var yl,Z,Hv,US,Gv=h(()=>{"use strict";S();xn();iv();lv();Ov();Wv();io();yl=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Z=e=>t=>zh(async()=>yl(await e(t))),Hv=()=>{let e=new BS({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()})},Z(Pc)),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()})},Z(Bc)),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()})},Z(Fc)),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=>yl(await Bv(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:v.object({repoRoot:v.string().optional()})},Z(qc)),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)})},Z(Gc)),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:v.object({repoRoot:v.string().optional(),boardId:v.string().optional()})},Z(Vc)),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)})},Z(Kc)),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)})},Z(Yc)),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)})},Z(zc)),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()})},Z(Xc)),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)})},Z(Jc)),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()})},Z(Oc)),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()})},Z(Wc)),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()})},Z(Hc)),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()})},Z(Qc)),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()})},Z(tl)),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()})},Z(il)),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()})},Z(ol)),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()})},Z(Zc)),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()})},Z(el)),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()})},Z(sl)),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()})},Z(rl)),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()})},Z(al)),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()})},Z(dl)),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()})},Z(kc)),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()})},Z(cl)),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()})},Z(ll)),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()})},Z(jc)),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()})},Z(Uc)),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()})},Z($c)),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()})},Z(nl)),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()})},Z(cv)),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()})},Z($v)),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote (pull remote changes and push local ones). Other Epiq MCP tools only read and write local state and never sync automatically \u2014 call this on demand when you need to see or publish the latest remote changes.",inputSchema:v.object({repoRoot:v.string().optional()})},Z(Lc)),e},US=async()=>{let e=Hv(),t=new OS;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:jS}=await Promise.resolve().then(()=>(zn(),wl)),{isFail:$S}=await Promise.resolve().then(()=>(S(),Sl)),{parseMcpArgs:WS}=await Promise.resolve().then(()=>(kl(),Tl)),yo=WS(process.argv.slice(2));yo.kind==="error"&&(console.error(yo.message),process.exit(1));yo.kind==="print"&&(process.stdout.write(yo.text),process.exit(0));if(yo.kind==="name"){let e=jS(yo.name,"The name argument");$S(e)&&(console.error(e.message),process.exit(1))}var{setVirtualNodesEnabled:HS}=await Promise.resolve().then(()=>(Da(),$h));HS(!1);var{startMcpServer:qS}=await Promise.resolve().then(()=>(Gv(),qv));await qS();
|
|
101
|
+
`,Ld.writeFileSync(t,n,"utf8"),ce.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),d("Local epiq paths ignored",!0)}});import ZN from"node:fs";import Pd from"node:path";var ew,de,qa,tw,nw,Dd=g(()=>{"use strict";Cv();wi();rt();Ke();Ms();Po();$();To();w();ee();Jt();fc();ew=async e=>{let t=await W({cwd:e,args:["status","--porcelain"]});return a(t)?t:d("Checked git diff",t.value.stdout.split(`
|
|
102
|
+
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},de=(e,t)=>l(`[${e}] ${t}`),qa=async({cwd:e,user:t})=>{let n=Si(),o=await kt(e);if(a(o))return de(1,o.message);let r=o.value,s=await Ci(r);if(a(s))return de(2,s.message);if(s.value)return de(2,`Cannot initialize Epiq while a git operation is in progress: ${s.value}`);let i=await ew(r);if(a(i))return de(2.5,i.message);if(i.value.length>0)return de(3,`Cannot initialize Epiq with uncommitted changes (${i.value.join(", ")}). Commit or stash your changes first.`);if(ys(r))return de(4,"Epiq project already initialized");let{userId:c,userName:u}=t;if(!c||!u)return de(5,"Missing Epiq user id");let p=await Df(r);if(a(p))return de(6,p.message);let m=n.stateBranch,f=await Ai({repoRoot:r,branch:m});if(a(f))return de(6,f.message);if(f.value)return de(6,`State branch already exists: ${m}`);let h=await tw({repoRoot:r,stateBranch:m});if(a(h))return de(6,h.message);if(h.value)return nw({repoRoot:r,stateBranch:m});let x=await hc({repoRoot:r,stateBranchName:m});if(a(x))return de(6,x.message);let E=hs();if(a(E))return de(7,E.message);let S=Pd.join(No(),n.projectId),C=await to({repoRoot:r,stateBranchRoot:S,stateBranchName:m});if(a(C))return de(8,C.message);let R=Pd.join(S,".epiq");ZN.mkdirSync(R,{recursive:!0});let A=If({userId:c,userName:u});if(a(A))return de(9,A.message);for(let jx of A.value){let tm=Qp({event:jx,rootDir:S});if(a(tm))return de(9,tm.message)}let L=Qn({userId:c}),_=Oi(S,L);if(a(_))return de(9,_.message);let j=pc(S,n);if(a(j))return de(9,j.message);let z=await ea({stateBranchRoot:S,eventFileName:L});if(a(z))return de(10,z.message);let X=await Ne.stage({cwd:S,pathspec:[st]});if(a(X))return de(10,X.message);let ue=await nr({cwd:S,message:"[epiq:init]"});if(a(ue))return de(10,ue.message);let ze=await wv(r);if(a(ze))return de(11,ze.message);let q=Ml({repoRoot:r,fileContents:n});if(a(q))return de(12,q.message);let ae=await Ne.stage({cwd:r,pathspec:[".epiq/project.json",".gitignore"]});if(a(ae))return de(13,ae.message);let Pt=await Ne.commit({cwd:r,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(a(Pt))return de(13,Pt.message);let Qr=[],Zu=await W({cwd:r,args:["push","-u","origin","HEAD"]});a(Zu)&&Qr.push(`[init:14] ${Zu.message}`);let em=await ks({repoRoot:r,stateBranchRoot:S});return a(em)&&Qr.push(`[init:15] ${em.message}`),d("Project initialized",{repoRoot:r,projectId:n.projectId,stateBranch:m,stateBranchRoot:S,defaultEvents:A.value,warnings:Qr})},tw=async({repoRoot:e,stateBranch:t})=>{let n=await kn({repoRoot:e});if(a(n))return l(n.message);if(!n.value)return d("No remote",!1);let o=await ms({repoRoot:e,branch:t});return a(o)?l(`Could not ask origin whether ${t} exists: ${o.message}`):o},nw=async({repoRoot:e,stateBranch:t})=>{let n=await W({cwd:e,args:["fetch","origin",t]});if(a(n))return de(6,n.message);let o=await W({cwd:e,args:["show",`origin/${t}:${st}`]});if(a(o))return de(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",`${st} from a checkout that has it, for example:`,"",` git show origin/main:${st} > ${st}`,"","and commit it; every later boot then stamps the branch, and the next clone adopts it."].join(`
|
|
103
|
+
`));let r;try{r=JSON.parse(o.value.stdout)}catch(E){return de(6,`The identity on origin/${t} is not readable: ${E instanceof Error?E.message:String(E)}`)}let s=Ml({repoRoot:e,fileContents:r});if(a(s))return de(12,s.message);let i=await Ne.stage({cwd:e,pathspec:[st]});if(a(i))return de(13,i.message);let c=await Ne.commit({cwd:e,message:"[epiq:adopt-project]",pathspec:[st]});if(a(c))return de(13,c.message);let u=hs();if(a(u))return de(7,u.message);let p=Pd.join(No(),r.projectId),m=await Ts({repoRoot:e,stateBranchName:t});if(a(m))return de(8,m.message);let f=await to({repoRoot:e,stateBranchRoot:p,stateBranchName:t});if(a(f))return de(8,f.message);let h=[],x=await W({cwd:e,args:["push","-u","origin","HEAD"]});return a(x)&&h.push(`[init:14] ${x.message}`),d("Adopted the project origin already holds",{repoRoot:e,projectId:r.projectId,stateBranch:r.stateBranch,stateBranchRoot:p,defaultEvents:[],warnings:h})}});var ei,Av,Tv=g(()=>{"use strict";xt();Oo();$();w();Dd();he();Fe();O();ei=(e,t)=>l(`[${e}] ${t}`),Av=async()=>{ne("");let e=_s();if(!e.isSetupDone||!e.userName)return ei(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let t=le(),n=t.userName,o=t.userId;if(!o||!n)return ei(5,"Missing Epiq user id");let r=await qa({cwd:process.cwd(),user:{userId:o,userName:n}});if(a(r))return r;let s="Project initialized!";for(let h of r.value.warnings)s+=` Warn: ${h}`;let c=Pn(r.value.defaultEvents).filter(a);if(c.length>0)return ei(16,c.map(h=>h.message).join(`
|
|
104
|
+
`));let u=Me();if(a(u))return ei(16,u.message);let{rootNodeId:p,nodes:m}=u.value,f=m[p];return f?(H.navigate({contextNode:f,selectedIndex:0}),T({hasProjectDefinition:!0}),d(s,null)):ei(16,"Unable to resolve initialized root node")}});import{ulid as ow}from"ulid";function Fd(e){let t=Mv();if(a(t))return t;let{contextNode:n,nodes:o}=v();if(!n.parentNodeId)return l("Missing parent node id");let r=o[n.parentNodeId];if(!r)return l("Missing parent node");let s=ke(r.id),i=s.findIndex(({id:p})=>p===n.id);if(i<0)return l("Current node not found among siblings");let c=s[i+e];if(!c)return l("Missing sibling node");let u=Lv({id:t.value.id,parentId:c.id,position:{at:"end"}});return a(u)?u:Pv(u.value)}function ni(e,t=1){let n=Mv();if(a(n))return n;let{contextNode:o,selectedIndex:r}=v(),s=ke(o.id),i=Math.min(Math.max(r+e*t,0),s.length-1),c=i===r?void 0:s[i];if(!c)return l("Missing sibling node");let u=Lv({id:n.value.id,parentId:o.id,position:{at:e===1?"after":"before",sibling:c.id}});return a(u)?u:Pv(u.value)}var kv,ln,ti,Mv,Od,Lv,Pv,_d=g(()=>{"use strict";$();$();w();Bt();O();kv=null,ln=()=>structuredClone(kv),ti=e=>{kv=e},Mv=()=>{let{contextNode:e,selectedIndex:t}=v(),o=ke(e.id)[t];return o?d("Resolved selected child",o):l("Target node not found")},Od=({id:e,parentId:t,position:n={at:"end"}})=>{let o=ke(t).filter(r=>r.id!==e);return Ki(o,n)},Lv=({id:e,parentId:t,position:n={at:"end"}})=>{let o=ge();if(a(o))return l("Unable to resolve user ID");let r=Od({parentId:t,id:e,position:n});return a(r)?r:d("Created pending move state",{id:ow(),...o.value,action:"move.node",payload:{id:e,parent:t,rank:r.value.rank}})},Pv=e=>{ti(e);let t=Ss(e,!0);return a(t)?t:d("Node moved successfully",t.value)}});import{ulid as rw}from"ulid";var Dv,Br,Ov,Fv=g(()=>{"use strict";xt();_d();$();$();_t();Oe();w();Bt();he();O();ee();Dv=()=>{let e=ln();if(!e)return l("No pending move state");let t=e.payload.id,n=e.payload.parent,o=v().nodes[n];if(!o)return l("Move parent not found");let r=ke(n).findIndex(s=>s.id===t);return r===-1?l("Moved node not found among rendered children"):(H.navigate({contextNode:o,selectedIndex:r}),d("Synchronized navigation to moved node",null))},Br=(e,t="Moved preview")=>{if(a(e))return ln()&&T({mode:b.MOVE}),e;let n=Dv();return a(n)?n:(T({mode:b.MOVE}),d(t,null))},Ov=async()=>{let e=ge();if(a(e))return l("Unable to resolve user ID");let{modifier:t}=fe().commandMeta,{contextNode:n,selectedIndex:o}=v(),r=ke(n.id)[o];if(!r)return T({mode:b.DEFAULT}),l("No move target");if(t==="start"){if(r.readonly)return l("Target node is read-only");if(o===-1)return l("No item selected");if(!r.parentNodeId)return l("Target has no parent");let s=ke(r.parentNodeId),i=s.findIndex(({id:f})=>f===r.id);if(i===-1)return l("Target not found among siblings");let c=s[i-1],u=s[i+1],p=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},m=Od({parentId:r.parentNodeId,id:r.id,position:p});return a(m)?m:(ti({id:rw(),action:"move.node",payload:{id:r.id,parent:r.parentNodeId,rank:m.value.rank},...D(e.value)}),T({mode:b.MOVE}),d("Move initialized",null))}if(t==="next")return Br(ni(1));if(t==="previous")return Br(ni(-1));if(t==="jump-next")return Br(ni(1,Ns));if(t==="jump-previous")return Br(ni(-1,Ns));if(t==="to-next")return Br(Fd(1));if(t==="to-previous")return Br(Fd(-1));if(t==="confirm"){let s=ln();if(!s)return l("No pending move to confirm");let i=await Ee();if(a(i))return i;let c=F([s],i.value);if(a(c))return c;let u=Dv();return a(u)?u:(ti(null),T({mode:b.DEFAULT}),d("Moved item",null))}return t==="cancel"?(ti(null),T({mode:b.DEFAULT}),d("Cancelling move",null)):l("Invalid move modifier")}});import{monotonicFactory as sw,ulid as iw}from"ulid";var aw,Ga,Bd=g(()=>{"use strict";w();aw=sw(),Ga=({name:e,parent:t,rank:n,user:{userId:o}})=>{let r=aw();return d("Created issue events",[{id:iw(),userId:o,action:"add.issue",payload:{id:r,parent:t,name:e,rank:n}}])}});import{ulid as za}from"ulid";var _v,Bv=g(()=>{"use strict";xt();Bd();$();$();_t();Yt();w();pe();Bt();O();ee();_v=async(e,t)=>{let n=ge();if(a(n))return l("Unable to resolve user ID");let o=await Ee();if(a(o))return o;let r=o.value;if(!t.inputString)return l(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=v(),u=p=>{let m=F([p],r);if(a(m))return m;let f=N.getNode(m.value[0].result.id);if(!f)return l("Created node not found");if(!f.parentNodeId)return m;let h=N.getNode(f.parentNodeId);return h?(H.navigate({contextNode:h,selectedIndex:N.getSiblings(f.parentNodeId).findIndex(({id:x})=>x===f.id)}),m):l("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:p}=v(),m=N.getNode(p);if(!m)return l("Workspace not found");let f=Dn(m.id,n.value,r);return a(f)?f:u({id:za(),action:"add.board",payload:{id:za(),name:t.inputString,parent:m.id,rank:f.value},...D(n.value)})}if(t.modifier==="swimlane"){let p=Nt(s,"BOARD");if(a(p))return l("Unable to add swimlane in this context");let m=Dn(p.value.id,n.value,r);return a(m)?m:u({id:za(),action:"add.swimlane",payload:{id:za(),name:t.inputString,parent:p.value.id,rank:m.value},...D(n.value)})}if(t.modifier==="issue"){let p=ve(i.id)[c],m=i.context==="SWIMLANE"?i:i.context==="BOARD"&&p?.context==="SWIMLANE"?p:(()=>{let A=Nt(s,"SWIMLANE");return a(A)?null:A.value})();if(!m)return l("Unable to add issue in this context");let f=Dn(m.id,n.value,r);if(a(f))return f;let h=Ga({name:t.inputString,parent:m.id,rank:f.value,user:n.value});if(a(h))return h;let x=h.value,E=F([...x],r);if(a(E))return E;if(!E.value[0])return l("Issue creation failed");let R=x.find(A=>A.action==="add.issue")?.payload.id;return R?(H.navigate({contextNode:m,selectedIndex:N.getSiblings(m.id).findIndex(({id:A})=>A===R)}),d("Issue created",null)):l("Unable to determine ticket id")}return d("Success",null)}});import oi from"node:fs";import lw from"node:path";import{z as qo}from"zod";var ri,cw,dw,uw,$v,mw,jv,Uv,Hv,$d=g(()=>{"use strict";w();Jt();he();fd();ee();ri="command-history.json",cw=20,dw=qo.object({projectId:qo.string().min(1),commands:qo.array(qo.string()),lastUsedAt:qo.number().finite()}),uw=qo.object({projects:qo.array(dw)}),$v=()=>{let e=Js();return a(e)?e:d("Resolved command history path",lw.join(e.value,ri))},mw=()=>{try{let e=we(process.cwd());return a(e)?null:e.value}catch{return null}},jv=e=>{if(!oi.existsSync(e))return d("No command history recorded",{state:"read",projects:[]});let t;try{t=oi.readFileSync(e,"utf8")}catch(r){return l(`Unable to read ${ri}: ${r instanceof Error?r.message:String(r)}`)}let n;try{n=JSON.parse(t)}catch(r){return d("Unparsable command history",{state:"corrupt",reason:`Invalid ${ri}: ${r instanceof Error?r.message:String(r)}`})}let o=uw.safeParse(n);return o.success?d("Read command history",{state:"read",projects:o.data.projects}):d("Command history in an unknown shape",{state:"corrupt",reason:`Invalid ${ri} shape: ${o.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`})},Uv=({root:e})=>{let t=un(e);if(a(t))return l(t.message);let n=$v();if(a(n))return n;let o=jv(n.value);if(a(o))return o;let r=o.value;if(r.state==="corrupt")return l(r.reason);let s=r.projects.find(i=>i.projectId===t.value);return d("Read command history",s?.commands.slice(0,Hs)??[])},Hv=({commands:e,root:t=mw(),now:n=Date.now()})=>{if(t===null)return d("No project; command history not stored",null);let o=un(t);if(a(o))return l(o.message);let r=$v();if(a(r))return r;let s=r.value,i=jv(s);if(a(i))return i;let c=i.value,u=c.state==="read"?c.projects:[],p=[{projectId:o.value,commands:e.slice(0,Hs),lastUsedAt:n},...u.filter(f=>f.projectId!==o.value)].sort((f,h)=>h.lastUsedAt-f.lastUsedAt).slice(0,cw),m=`${s}.${process.pid}.tmp`;try{oi.writeFileSync(m,JSON.stringify({projects:p},null,2)+`
|
|
105
|
+
`,"utf8"),oi.renameSync(m,s)}catch(f){try{oi.rmSync(m,{force:!0})}catch{}return l(`Unable to write ${ri}: ${f instanceof Error?f.message:String(f)}`)}return d("Stored command history",null)}});var pw,Wv,fw,qv,gw,Gv,zv=g(()=>{"use strict";Cn();rt();Ke();Ms();ia();bc();ra();$d();ur();Po();$();w();Jt();he();O();Cs();ee();Qi();pw=e=>e.some(t=>t.action==="init.workspace"),Wv=async(e,t)=>{let n=vt(e);return a(n)?l(n.message):fs({cwd:t,branch:n.value})},fw=e=>{let t=we(process.cwd());if(a(t))return!1;let n=Ie({repoRoot:t.value});return!a(n)&&n.value===e},qv=async e=>{let t=Ie({repoRoot:e});if(a(t))return ar(3,t.message);let n=t.value,o=await to({repoRoot:e,stateBranchRoot:n,stateBranchName:Si().stateBranch});if(a(o))return ar(3,o.message);let r=nn(n);if(a(r))return ar(3,r.message);if(!pw(r.value.events)){let m=await Wv(e,n);if(a(m)&&logger.info(3,m.message),r=nn(n),a(r))return ar(3,r.message)}let{events:s,unreadable:i}=r.value,c=gn(s,i);if(a(c))return ar(4,c.message);T({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let u=Os({root:e});a(u)&&logger.info(u.message);let p=Uv({root:e});return a(p)&&logger.info(p.message),Kg(a(p)?[]:p.value),d("Loaded project",void 0)},gw=async e=>{let t=Ie({repoRoot:e});if(a(t))return l(t.message);let n=t.value,o=await kn({repoRoot:n});if(a(o))return l(o.message);if(!o.value)return d("No remote to pull",void 0);let r=await na({worktreeRoot:n,operation:"boot pull",fn:()=>Ic(n,()=>(ir("Pulling"),Wv(e,n)))});if(a(r))return $e(r.message);if(r.value===null)return d("Another process holds the state worktree",void 0);let s=r.value;if(a(s))return ps(s.message)?(Ji("Offline"),d("Offline",void 0)):$e(s.message);if(!s.value)return Do("Already synced"),d("Already synced",void 0);if(!fw(n))return d("Project changed during the pull",void 0);let i=Ec(n);return a(i)?i:(Do("Pulled"),d("Pulled and reloaded",void 0))},Gv=e=>{gw(e).then(t=>{a(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${Sf(t)}`)})}});import hw from"node:os";import Vv from"node:path";var vw,yw,Kv,Yv=g(()=>{"use strict";zv();ur();w();he();O();ee();vw=e=>e==="~"||e.startsWith("~/")?Vv.join(hw.homedir(),e.slice(1)):e,yw=(e,t)=>{let n=e.trim();if(!n)return l("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let r=t[Number(n)-1];return r?d("Resolved recent project",r.root):l(`No recent project #${n}`)}let o=we(Vv.resolve(vw(n)));return a(o)?l(`No epiq project at ${n}`):d("Resolved project path",o.value)},Kv=async()=>{let e=Ia();if(ne(""),v().hasProjectDefinition)return l("Already in a project; run epiq from another directory");let t=ca({exclude:process.cwd()}),n=a(t)?[]:t.value,o=yw(e,n);if(a(o))return l(o.message);let r=o.value,s=process.cwd();try{process.chdir(r)}catch(c){return l(`Unable to enter ${r}: ${c instanceof Error?c.message:String(c)}`)}let i=await qv(r);return a(i)?(process.chdir(s),l(i.message)):(Gv(r),d(`Opened ${Xf(r)}`,null))}});var Va,jd=g(()=>{"use strict";xt();$();$();w();O();Va=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:o})=>{let r=v(),s=ac(n,t);if(a(s))return l(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=Wn();if(a(u))return u;let p=Pn(i),{fatal:m,skipped:f}=Xn(p);if(m.length>0)return Wn(),T(r),l(m.map(x=>x.message).join(", "));Jn(f);let h=v().nodes[e];return h?(H.navigate({contextNode:h,selectedIndex:o}),d("",{unappliedEvents:c})):(Wn(),T(r),l("Board did not exist at that date"))}});var Xv,Jv=g(()=>{"use strict";Xv=e=>{let t=[],n=0;for(let r=0;r<e.length;r++){let s=r===0?0:Math.max(0,e[r]-e[r-1]);n+=Math.sqrt(s),t[r]=n}let o=n;return t.map((r,s)=>o>0?r/o:(s+1)/e.length)}});var bw,xw,Iw,Ka,Ya,Go,Qv,Zv,Ud=g(()=>{"use strict";ft();si();$();sc();Oe();w();Jv();O();bw=20,xw=16,Iw=150,Ka=null,Ya=null,Go=()=>{Ka!==null&&(clearInterval(Ka),Ka=null),Ya!==null&&(clearTimeout(Ya),Ya=null)},Qv=()=>{Go(),T({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Zv=({events:e,startTime:t,durationMs:n})=>{Go();let o=e.length,r=os(e.map(f=>yo(f))).map(f=>f??t),s=r[o-1]??Date.now(),i=Xv(r),c=Math.max(1,Math.round(n*bw/1e3)),u=Math.max(Math.round(n/c),xw),p=0,m=0;T({mode:b.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:o,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Ka=setInterval(()=>{p++;let f=p/c,h=[],x,E;for(;m<o&&i[m]<=f;){let C=e[m],R=Ss(C);if(a(R)){if(rr(R)){m++;continue}Qv();return}h.push(...rc(C)),x=C,E=r[m],m++}if(m>=o||p>=c){for(;m<o;m++){let R=Ss(e[m]);if(a(R)&&!rr(R))break}let C=v().replay;T({unappliedEvents:[],replay:C&&{...C,progress:1,appliedCount:o}}),Go(),Ya=setTimeout(Qv,Iw);return}let S=v().replay;T({unappliedEvents:e.slice(m),replay:{progress:Math.min(1,f),appliedCount:m,totalCount:o,startTime:t,endTime:s,currentTime:x?E??S?.currentTime??t:S?.currentTime??t,currentLabel:x?Hd(x):S?.currentLabel??"",flashNodeIds:x?[...new Set(h)]:S?.flashNodeIds??[]}})},u)}});var ey,ty=g(()=>{"use strict";rt();ft();$();$();Oe();Yt();w();he();O();Bs();jd();Ud();ey=async()=>{let e=Nt(v().breadCrumb,"BOARD");if(a(e))return e;let t=await kt(process.cwd());if(a(t))return l("Unable to locate repo root");let n=Ie({repoRoot:t.value});if(a(n))return n;let{modifier:o,inputString:r}=fe().commandMeta;if(Go(),o==="now"){let c=Mo(n.value);if(a(c))return l(c.message);let u=Wn();if(a(u))return u;let p=Pn(c.value),{fatal:m,skipped:f}=Xn(p);return m.length>0?l(m.map(h=>h.message).join(", ")):(Jn(f),T({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),d("Peeking now",!0))}let s;if(o==="prev"||o==="next"){let c=lc(n.value);if(a(c))return c;let u=o==="prev"?v().eventLog.at(-1):v().unappliedEvents.at(0),p=u===void 0?null:yo(u),m=(u===void 0?null:c.value.get(u.id)??null)??(p===null?null:ns(p));if(m===null)return l(o==="prev"?"No previous event to peek":"No next event to peek");s=o==="prev"?m:m+1}else{let c=_o(o||r.trim());if(!c)return l("Invalid peek date");s=c.getTime()}let i=Va({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(i)?i:(T({mode:b.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),d("Peeking",!0))}});var ny,oy=g(()=>{"use strict";rt();Yt();w();he();O();Bs();jd();Ud();ny=async()=>{let e=Nt(v().breadCrumb,"BOARD");if(a(e))return e;let t=await kt(process.cwd());if(a(t))return l("Unable to locate repo root");let n=Ie({repoRoot:t.value});if(a(n))return n;let{modifier:o,inputString:r}=fe().commandMeta,{dateInput:s,durationInput:i}=pa(o,r);if(Go(),v().syncStatus.status==="syncing")return l("Cannot replay while syncing, try again in a moment");let c=_o(s);if(!c)return l("Invalid replay date");let u=i?ma(i):15e3;if(u===null)return l("Invalid replay duration (try e.g. 30s or 2m)");let p=c.getTime(),m=v(),f=Va({boardId:e.value.id,targetTime:p,stateBranchRoot:n.value,selectedIndex:-1});if(a(f))return f;let{unappliedEvents:h}=f.value;return h.length===0?(Wn(),T(m),d("Nothing to replay from that point",!0)):(Zv({events:h,startTime:p,durationMs:u}),d("Replaying board history",!0))}});import{spawn as Rw}from"node:child_process";var Sw,ry,sy=g(()=>{"use strict";w();Sw=()=>{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"]}}},ry=async e=>new Promise(t=>{let{command:n,args:o}=Sw();try{let r=Rw(n,o,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>t(l(`Clipboard tool not available (${n})`))),r.on("close",s=>t(s===0?d("Copied to clipboard",null):l(`Clipboard tool failed (${n})`))),r.stdin.on("error",()=>{}),r.stdin.write(e),r.stdin.end()}catch{t(l(`Clipboard tool not available (${n})`))}})});var ii,iy,ay=g(()=>{"use strict";w();O();sy();mt();pr();_n();ii=async(e,t)=>{if(!e.trim())return l(`Nothing to copy: ${t} is empty`);let n=await ry(e);return a(n)?n:d(`Copied ${t} to clipboard`,null)},iy=async e=>{let{breadCrumb:t,selectedNode:n}=v(),o=$s({breadCrumb:t,selectedNode:n}),r=o??n;if(!r)return l("Nothing selected to copy from");switch(e.modifier){case He.REF:return ii(V(r.id),"ref");case He.TITLE:return ii(r.title,"title");case He.DESCRIPTION:return o?ii(o.props?.description??"","description"):l("No issue in scope");case He.TAGS:{if(!o)return l("No issue in scope");let s=yn(o).map(({name:i})=>i);return ii(s.join(", "),"tags")}case He.ASSIGNEES:{if(!o)return l("No issue in scope");let s=bn(o).map(({name:i})=>i);return ii(s.join(", "),"assignees")}default:return l("Yank one of: ref, title, description, tags, assignees")}}});var ly,cy=g(()=>{"use strict";ia();Oe();w();he();O();ly=async()=>{ne(""),T({mode:b.DEFAULT});let e=Me();if(a(e))return l(e.message);if(e.value.syncStatus.status==="syncing")return l("Sync already in progress");T({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await sa();return a(t)?(T({syncStatus:{msg:t.message,status:"failed"}}),t):(T({mode:b.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as dy}from"ulid";var uy,my=g(()=>{"use strict";$();$();me();w();O();Aa();ee();_t();uy=async()=>{let e=ge();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),o=ve(t.id)[n];if(!o)return l("Unable to resolve child to delete");let r=await Ee();if(a(r))return r;if(o.context==="COMMENT"){let s=o.id,i=U(t)?t.id:t.parentNodeId;if(!i)return l("Unable to resolve comment issue");let c=v().nodes[i];if(!c||!U(c))return l("Unable to resolve comment issue");let u=c.log?.filter(ph).find(p=>p.payload.id===s);return u?u.payload.author!==e.value.userId?l("You can only delete your own comments"):F([{id:dy(),action:"delete.issue.comment",payload:{id:s,issue:i},...D(e.value)}],r.value):l("Unable to resolve comment")}return F([{id:dy(),action:"delete.node",payload:{id:o.id},...D(e.value)}],r.value)}});import{ulid as Nw}from"ulid";var py,fy=g(()=>{"use strict";$();$();tn();me();w();Bt();O();ee();Ft();py=async()=>{let e=ge();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),o=ve(t.id)[n];if(!o)return l("Unable to close issue, no target found");if(!U(o))return l("Cannot close in this context");let r=v().nodes[Ae];if(!r)return l("Unable to locate closed swimlane");if(o.parentNodeId===r.id)return l("Issue is already closed");let s=await Ee();if(a(s))return s;let i=s.value,c=pn(r.id,o.id,{at:"end"},e.value,i);if(a(c))return c;let u=F([{id:Nw(),action:"close.issue",payload:{id:o.id,parent:r.id,rank:c.value},...D(e.value)}],i);return a(u)?u:d("Issue closed",null)}});var Xa,Wd=g(()=>{"use strict";Xa=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let o=t[n];if(o&&o.action==="close.issue"&&o.payload.id===e.id){for(let r=n-1;r>=0;r--){let s=t[r];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 ww}from"ulid";var gy,hy=g(()=>{"use strict";$();$();Wd();tn();me();w();pe();Bt();O();ee();Ft();gy=async()=>{let e=ge();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),o=ve(t.id)[n];if(!o)return l("Unable to reopen issue, no target found");let r=o.context==="TICKET"?d("Resolved ticket",o):Gt(o.id,"TICKET");if(a(r))return l("Cannot reopen in this context");let s=r.value,i=v().nodes[Ae];if(!i)return l("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return l("Issue is not closed");if(!U(s))return l("Target node is not issue");let c=Xa(s);if(!c)return l("Unable to resolve previous parent from issue history");if(c===i.id)return l("Previous parent resolves to closed swimlane");let u=v().nodes[c];if(!u)return l("Previous parent no longer exists");let p=await Ee();if(a(p))return p;let m=p.value,f=pn(u.id,s.id,{at:"end"},e.value,m);if(a(f))return f;let h=F([{id:ww(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...D(e.value)}],m);return a(h)?h:d("Issue reopened",null)}});import{ulid as Cw}from"ulid";var vy,yy=g(()=>{"use strict";$();$();w();he();O();ee();Ft();vy=async()=>{let e=ge();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),o=ve(t.id)[n];if(!o)return l("Missing node");if(o.readonly)return l("Cannot rename readonly node");let r=Ia();if(!r)return l("Provide a title");let s=await Ee();return a(s)?s:F([{id:Cw(),action:"edit.title",payload:{id:o.id,name:r},...D(e.value)}],s.value)}});import{ulid as Aw}from"ulid";var by,xy=g(()=>{"use strict";pe();$();$();me();w();he();O();ee();Ft();by=async()=>{let e=ge();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=fe().commandMeta,o=(t||n).trim();if(!o)return l("Provide a tag");let r=N.findTagByName(o);if(!r)return l(`Tag "${o}" does not exist`);let{selectedNode:s}=v();if(!s)return l("Invalid untag target");let i=Gt(s.id,"TICKET");if(a(i))return l("Unable to untag issue in this context");let c=i.value;if(!U(c))return l("Target node is not issue");if(!(c.props.tags??[]).includes(r.id))return l("Issue is not tagged with that tag");let p=await Ee();return a(p)?p:F([{id:Aw(),action:"remove.issue.tag",payload:{id:c.id,tag:r.id},...D(e.value)}],p.value)}});import{ulid as qd}from"ulid";var Iy,Ey=g(()=>{"use strict";pe();$();$();me();w();he();O();ee();Ft();Iy=async()=>{let e=ge();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=fe().commandMeta,o=(t||n).trim();if(!o)return l("Provide a tag");let{selectedNode:r}=v();if(!r)return l("Invalid tag target");let s=Gt(r.id,"TICKET");if(a(s))return l("Unable to tag issue in this context");let i=s.value;if(!U(i))return l("Target node is not issue");let c=await Ee();if(a(c))return c;let u=N.findTagByName(o),p=u?.id??qd();return(i.props.tags??[]).includes(p)?l("Already tagged with that tag"):F([...u?[]:[{id:qd(),action:"create.tag",payload:{id:p,name:o},...D(e.value)}],{id:qd(),action:"add.issue.tag",payload:{id:i.id,tag:p},...D(e.value)}],c.value)}});var ai,Ry,Ja=g(()=>{"use strict";wt();Nn();ai=({events:e,registry:t,logFileNames:n})=>{let o=new Map(n),r=new Set;for(let s of e)s.userId&&(o.has(s.userId)||o.set(s.userId,""),r.add(s.userId));for(let s of Object.values(t))o.set(s.id,s.name);return[...o.entries()].map(([s,i])=>({id:s,name:i,isExternal:!r.has(s)}))},Ry=({authorName:e,authorEmail:t,owners:n,registry:o})=>{let r=Ve(t),s=n.get(r),i=s?o[s]:void 0;return s?{...gt(s,i?.name),resolved:!0}:{...gt(r||e,e),resolved:!1}}});var Qa,Gd=g(()=>{"use strict";$();Ja();O();Qa=e=>{let{eventLog:t=[],contributors:n}=v();return ai({events:t,registry:n,logFileNames:ko(e)})}});import{ulid as zd}from"ulid";var Sy,Ny=g(()=>{"use strict";$();$();me();w();pe();he();O();Gd();ee();Ft();Sy=async()=>{let e=ge();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=fe().commandMeta,o=(t||n).trim();if(!o)return l("Provide an assignee");let r=o.startsWith("!"),s=(r?o.slice(1):o).trim();if(!s)return l("Provide an assignee");let{selectedIndex:i,contextNode:c}=v(),u=ve(c.id)[i];if(!u)return l("Invalid assign target");let p=Gt(u.id,"TICKET");if(a(p))return l("Unable to assign issue in this context");let m=p.value;if(!U(m))return l("Target node is not issue");let f=await Ee();if(a(f))return f;let h=Qa(f.value),x=!r&&s.toLowerCase()==="me",E,S;if(x)E=e.value.userId,S=h.find(A=>A.id===E)?.name??e.value.userName;else{let A=h.filter(_=>_.name===s);if(A.length>1)return l(`"${s}" matches ${A.length} contributors (${A.map(_=>_.id).join(", ")}). Assign from the GUI to choose by id.`);let L=A[0];if(!L&&!r)return l(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);E=L?.id??zd(),S=L?.name??s}if((m.props.assignees??[]).includes(E))return l("Assignee already assigned");let R=!!v().contributors[E];return F([...R?[]:[{id:zd(),action:"create.contributor",payload:{id:E,name:S},...D(e.value)}],{id:zd(),action:"add.issue.assignee",payload:{id:m.id,assignee:E},...D(e.value)}],f.value)}});import{ulid as Tw}from"ulid";var wy,Cy=g(()=>{"use strict";$();$();me();w();pe();he();O();Gd();ee();Ft();wy=async()=>{let e=ge();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=fe().commandMeta,o=(t||n).trim();if(!o)return l("Provide an assignee to remove");let{selectedNode:r}=v();if(!r)return l("Invalid unassign target");let s=Gt(r.id,"TICKET");if(a(s))return l("Unable to unassign in this context");let i=s.value;if(!U(i))return l("Target node is not issue");let c=i.props.assignees??[],u=o.toLowerCase()==="me",p=await Ee();if(a(p))return p;let m=u?c.filter(h=>h===e.value.userId):Qa(p.value).filter(h=>h.name===o&&c.includes(h.id)).map(h=>h.id);if(m.length>1)return l(`"${o}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let f=m[0];return f?F([{id:Tw(),action:"remove.issue.assignee",payload:{id:i.id,assignee:f},...D(e.value)}],p.value):l(u?"Issue is not assigned to you":`Issue is not assigned to "${o}"`)}});import{ulid as Ay}from"ulid";var kw,Ty,ky=g(()=>{"use strict";$();$();Yt();me();w();pe();O();$n();ee();Ft();Pa();ja();Ta();kw=e=>{let t=e.trim(),n=co(),o=n?Hh(t):null;if(!n||!o)return{ok:!0,md:t,anchored:!1};let r=$a();if(!r||r.sha!==n)return{ok:!1,reason:"No diff is open"};let s=Wh(r.rows,Math.max(0,v().selectedIndex));if(!s)return{ok:!1,reason:"That line is not in a file"};let i=qh(r.rows,s,o.start,o.end);return i.ok?{ok:!0,anchored:!0,md:Sh({filePath:i.value.filePath,start:i.value.start,end:i.value.end,side:"additions",endSide:"additions",note:o.note,sha:n,snippet:i.value.snippet})}:{ok:!1,reason:i.reason}},Ty=async e=>{let t=kw(e.inputString);if(!t.ok)return l(t.reason);let{md:n,anchored:o}=t;if(!n)return l("Provide a comment");if(n.length>4e3)return l(o?`The note and the ${n.length} characters of quoted lines exceed ${4e3}; comment on fewer lines`:`Cannot exceed ${4e3} characters`);let r=ge();if(a(r))return l("Unable to resolve user ID");let{breadCrumb:s,selectedNode:i}=v(),c=Nt([...s,i],"TICKET");if(a(c))return l("Edit target must be an issue");let u=c.value;if(!u)return l("Invalid comment target");let p=u.context==="TICKET"?d("Resolved ticket",u):Gt(u.id,"TICKET");if(a(p))return l("Unable to comment on issue in this context");let m=p.value;if(!U(m))return l("Target node is not issue");let f=await Ee();if(a(f))return f;let h=await F([{id:Ay(),action:"add.issue.comment",payload:{id:Ay(),issue:m.id,author:r.value.userId,md:n},...D(r.value)}],f.value);return o&&!a(h)&&Ho(null),h}});import Mw from"zod";var My,Ly=g(()=>{"use strict";rn();w();he();Fe();My=()=>{let e=fe().commandMeta.inputString,t=Mw.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return l("Auto sync duration must be a number of at least 3000 ms");let n=it({autoSyncDebounceMs:t.data});return a(n)?n:(Qe({autoSyncIntervalMs:t.data}),d(`Auto sync interval set to ${t.data}ms`,null))}});var Py,Dy=g(()=>{"use strict";Oo();rn();w();he();Fe();Py=()=>{let e=fe().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return l("Invalid response");let t=ag(e),n=it({autoSync:t});return a(n)?n:(Qe({autoSync:t}),d(`Auto sync set to "${e}"`,null))}});var Vd,Oy,Fy,Lw,Pw,Za,el,Kd=g(()=>{"use strict";Ke();wt();w();Vd=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=2),Oy="",Fy=new Map,Lw=15e3,Pw=async(e,t)=>{let n=`${e} ${t??""}`,o=Fy.get(n);if(o&&Date.now()-o.at<Lw)return d("Cached author scan",o.authors);let r=await Le({cwd:e,args:["log","--branches",...t?["--not",t]:[],`--format=%an${Oy}%ae`]});if(r.exitCode!==0)return l(`Could not read this repository's history: ${(r.stderr??"").trim()||`git exited ${r.exitCode}`}`);let s=new Map;for(let i of(r.stdout??"").split(`
|
|
106
|
+
`)){let c=i.lastIndexOf(Oy);if(c===-1)continue;let u=i.slice(0,c),p=Ve(i.slice(c+1));if(!Gn(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 Fy.set(n,{at:Date.now(),authors:s}),d("Scanned repository authors",s)},Za=async({repoRoot:e,stateBranch:t,names:n,links:o})=>{let r=await Pw(e,t);if(a(r))return l(r.message);let s=r.value,i=new Map;for(let u of Object.values(o)){if(u.tombstoned)continue;let p=i.get(u.email)??new Set;p.add(u.contributor),i.set(u.email,p)}let c=new Set(n.flatMap(u=>Vd(u??"")));return d("Found candidates",[...s.entries()].map(([u,p])=>({email:u,names:[...p.names],commits:p.commits,looksLikeYours:[...p.names].some(m=>Vd(m).some(f=>c.has(f)))||Vd(u.split("@")[0]??"").some(m=>c.has(m)),claimedBy:[...i.get(u)??[]]})).sort((u,p)=>u.looksLikeYours===p.looksLikeYours?p.commits-u.commits:Number(p.looksLikeYours)-Number(u.looksLikeYours)))},el=e=>e.filter(t=>t.claimedBy.length===0)});import{ulid as Dw}from"ulid";var _y,By,$y=g(()=>{"use strict";$();Cn();rt();wt();w();Oe();Kd();he();Fs();Fe();O();rn();Oo();ee();_y=()=>{let e=Ac();if(!e)return d("Nothing here to decline",null);let t=no(),n=a(t)?[]:t.value.declinedEmailBoards??[],o=[...new Set([...n,e])],r=it({declinedEmailBoards:o});return a(r)?l(r.message):(Qe({declinedEmailBoards:[...new Set([...le().declinedEmailBoards??[],e])]}),d("Declined",null))},By=async()=>{let e=fe().commandMeta.inputString.trim();if(e==="none"){let C=_y();return a(C)?C: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:o}=le();if(!t)return l("Set a username first with :config username");let r=Me();if(a(r))return l("Board is not loaded");let s=we(process.cwd());if(a(s))return l(s.message);let i=vt(s.value),c=await Za({repoRoot:s.value,stateBranch:a(i)?void 0:i.value,names:[n,o],links:r.value.emailLinks});if(a(c))return c;let p=el(c.value);if(og(p.map(C=>C.email)),p.length===0){if(!sg()){let C=_y();if(a(C))return C}return d("No unclaimed addresses in this history.",null)}if(!e)return T({mode:b.IDENTITY}),d("Opened identity",null);let m=e.split(/[,\s]+/).filter(Boolean),f=[],h=[];for(let C of m){let R=p.find(A=>A.email===Ve(C));if(!R){h.push(C);continue}f.includes(R)||f.push(R)}if(h.length>0)return l(`Not on the list: ${h.join(", ")}. Pick one of ${p.map(C=>C.email).join(", ")}.`);let x=Ie({repoRoot:s.value});if(a(x))return x;let E=f.map(C=>({id:Dw(),action:"link.contributor.email",payload:{contributor:t,email:C.email},userId:t})),S=F(E,x.value);return a(S)?l(S.message):d(`Claimed ${f.map(C=>C.email).join(", ")}. Every commit by ${f.length===1?"that address":"those addresses"} is now yours.`,null)}});import{ulid as Ow}from"ulid";var jy,Uy=g(()=>{"use strict";$();rt();wt();w();he();Fe();O();ee();jy=()=>{let e=fe().commandMeta.inputString.trim(),{userId:t}=le();if(!t)return l("Set a username first with :config username");let n=Me();if(a(n))return l("Board is not loaded");let o=zn(n.value.emailLinks,t);if(o.length===0)return l("You have not claimed any addresses.");if(!e)return l(`Which one? ${o.join(", ")}.`);let r=o.find(u=>u===Ve(e));if(!r)return l(`You have not claimed ${e}. Yours: ${o.join(", ")}.`);let s=we(process.cwd());if(a(s))return s;let i=Ie({repoRoot:s.value});if(a(i))return i;let c=F([{id:Ow(),action:"unlink.contributor.email",payload:{contributor:t,email:r},userId:t}],i.value);return a(c)?l(c.message):d(`Unclaimed ${r}`,null)}});var Hy,Wy=g(()=>{"use strict";rn();w();he();Fe();Hy=()=>{let e=fe().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return l("Invalid response");let n=it({logLevel:e});return a(n)?n:(Qe({logLevel:e}),d(`Auto sync set to "${e}"`,null))}});import{ulid as Fw}from"ulid";var qy,Gy=g(()=>{"use strict";vo();rn();w();Fe();_n();Ly();jc();Dy();$y();Uy();Wy();qy=e=>{let t=e.inputString.trim();switch(e.modifier){case be.USERNAME:{if(process.env[Ot])return l(`Cannot change the configured user while ${Ot} names this process`);let n=no();if(a(n))return n;let{userId:o,preferredEditor:r,userName:s}=n.value,i=t||s,c=o||Fw();if(!i||!c)return l("Unable to resolve user name or id");let u=it({userName:i,userId:c,preferredEditor:r??""});return a(u)?u:(Qe({userName:i,userId:c}),d(`Username set to "${i}"`,null))}case be.EDITOR:{if(!t)return l("No editor provided");let n=it({preferredEditor:t});return a(n)?n:(Qe({preferredEditor:t}),d(`Editor configuration set to "${t}"`,null))}case be.VIEW:{if(t!=="wide"&&t!=="dense")return l("Invalid view mode");let n=it({viewMode:t});return a(n)?n:(Qe({viewMode:t}),d(`View set to "${t}"`,null))}case be.EMAILS:return By();case be.EMAILS_UNCLAIM:return jy();case be.AUTOSYNC:return Py();case be.LOG_LEVEL:return Hy();case be.SYNC_DEBOUNCE_MS:return My();case be.ATTACHMENT_MAX_KB:return wg();default:return l("Unknown config command")}}});var Yd,zy=g(()=>{"use strict";Oo();Oe();he();O();Yd=()=>{let e=lg(),t=v().mode;if(!(t!==b.COMMAND_LINE&&t!==b.DEFAULT)){if(!e){T({mode:b.DEFAULT});return}T({mode:b.COMMAND_LINE}),ne(e)}}});var Vy,Ky=g(()=>{"use strict";Rv();xt();Oe();w();he();O();Wa();Fo();zc();_n();Nv();Tv();Fv();Bv();Yv();ty();oy();ay();cy();my();fy();hy();yy();xy();Ey();Ny();Cy();ky();Gy();zy();Vy=[{systemOnly:!0,intent:G.Move,description:"Internal move-state command",mode:b.COMMAND_LINE,action:Ov},{intent:G.Delete,description:"Delete the currently selected node",mode:b.COMMAND_LINE,action:uy,onSuccess:()=>T({mode:b.DEFAULT})},{intent:G.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:b.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=fe().commandMeta,n=/(!=|=)/,[o]=e.split(n);if(!o||!(i=>We(I.FILTER).map(c=>c.split(n)[0]).includes(i))(o))return l("Invalid filter modifier");let s={target:o,operator:"=",value:t.trim()};return Pe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:b.DEFAULT})),d("Filter updated",null)}},{intent:G.ViewHelp,description:"Open the help screen",mode:b.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=v();return uo({pendingNavTarget:{contextNode:e,breadCrumb:o,selectedIndex:t,selectedNode:n}}),T({mode:b.HELP}),d("Viewing help",null)}},{intent:G.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:b.COMMAND_LINE,action:py,onSuccess:()=>T({mode:b.DEFAULT})},{intent:G.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:b.COMMAND_LINE,action:gy,onSuccess:()=>T({mode:b.DEFAULT})},{intent:G.Init,description:"Initialize Epiq in the current git repository",mode:b.COMMAND_LINE,action:Av,onSuccess:Yd},{intent:G.OpenProject,description:"Open a recently used epiq project, by number or path",mode:b.COMMAND_LINE,action:Kv,onSuccess:()=>T({mode:b.DEFAULT})},{intent:G.NewItem,description:"Create a new board, swimlane, or issue",mode:b.COMMAND_LINE,action:_v,onSuccess:()=>T({mode:b.DEFAULT})},{intent:G.Rename,description:"Rename the currently selected node",mode:b.COMMAND_LINE,action:vy,onSuccess:()=>T({mode:b.DEFAULT})},{intent:G.UntagTicket,description:"Remove a tag from the selected issue",mode:b.COMMAND_LINE,action:by,onSuccess:()=>T({mode:b.DEFAULT})},{intent:G.TagTicket,description:"Add or create a tag on the selected issue",mode:b.COMMAND_LINE,action:Iy,onSuccess:()=>T({mode:b.DEFAULT})},{intent:G.AssignUserToTicket,description:"Assign a user to the selected issue",mode:b.COMMAND_LINE,action:Sy,onSuccess:()=>T({mode:b.DEFAULT})},{intent:G.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:b.COMMAND_LINE,action:wy,onSuccess:()=>T({mode:b.DEFAULT})},{intent:G.Comment,description:"Add a comment to the selected issue",mode:b.COMMAND_LINE,action:async(e,t)=>Ty(t),onSuccess:()=>T({mode:b.DEFAULT})},{intent:G.Sync,description:"Pull, commit, and push Epiq state",mode:b.COMMAND_LINE,action:ly},{intent:G.Peek,description:"View board state at another point in time",mode:b.COMMAND_LINE,action:ey},{intent:G.Replay,description:"Replay board history forward from a point in time",mode:b.COMMAND_LINE,action:ny},{intent:G.Export,description:"Export the current board layout to markdown",mode:b.COMMAND_LINE,action:async()=>{let e=await Ev();return a(e)?e:(T({mode:b.DEFAULT}),d("Export successful",!0))}},{intent:G.Exit,description:"Exit the application",mode:b.COMMAND_LINE,action:async()=>(H.exit(),d("Exit successful",!0))},{intent:G.Edit,description:"Edit title or description",mode:b.COMMAND_LINE,action:async(e,t)=>Sv(t),onSuccess:()=>T({mode:b.DEFAULT})},{intent:G.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:b.COMMAND_LINE,action:async(e,t)=>iy(t),onSuccess:()=>T({mode:b.DEFAULT})},{intent:G.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:b.COMMAND_LINE,action:(e,t)=>qy(t),onSuccess:Yd}]});var _w,zt,Xd=g(()=>{"use strict";aa();va();zc();Ky();$d();w();he();Fe();O();_w=new Set(["peek","replay","filter","view-help","yank"]),zt=async({isForceExecutedBySystem:e=!1}={})=>{let{value:t,commandMeta:{command:n,validity:o,modifier:r,inputString:s}}=fe();if(!n)return l("No command to confirm");if(!e&&o===ro.Invalid)return l("Invalid command");let i=Jg(n);zg();let{readOnly:c}=v();if(c&&!_w.has(i))return Ws({status:Sn.Fail,message:"Command not available in readonly state",value:null});let u=Vy.filter(f=>e||f.systemOnly!==!0).find(f=>f.intent===i);if(!u)return Ws({status:Sn.Fail,message:"Command not found",value:null});let p;try{p=await u.action(u,{command:n,inputString:s,modifier:r})}catch(f){return Ws({status:Sn.Fail,message:f instanceof Error?f.message:"Command failed",value:null})}if(a(p))return Ws(p);let m=!e;if(Vg({addToHistory:m,line:t}),m){let f=Hv({commands:fe().commandHistory});a(f)&&logger.info(f.message)}return u.onSuccess?.(),le().autoSync&&Vf(),p}});var tl,nl,Yy,Xy=g(()=>{"use strict";w();Oe();O();Vn();Xd();_d();he();tl=[{intent:P.Exit,mode:b.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(T({mode:b.COMMAND_LINE}),ne("move cancel"),zt({isForceExecutedBySystem:!0}))},{intent:P.InitMove,mode:b.DEFAULT,description:"[m] move",action:()=>(T({mode:b.COMMAND_LINE}),ne("move start"),zt({isForceExecutedBySystem:!0}))},{intent:P.ConfirmMove,mode:b.MOVE,description:"[m] confirm move",action:()=>(T({mode:b.COMMAND_LINE}),ne("move confirm"),zt({isForceExecutedBySystem:!0}))}],nl=[{intent:P.MovePreviousItem,mode:b.MOVE,action:()=>ln()?(T({mode:b.COMMAND_LINE}),ne("move previous"),zt({isForceExecutedBySystem:!0})):l("No pending move")},{intent:P.MoveNextItem,mode:b.MOVE,description:"[arrows/hjkl] move (shift x5)",action:()=>ln()?(T({mode:b.COMMAND_LINE}),ne("move next"),zt({isForceExecutedBySystem:!0})):l("No pending move")},{intent:P.MovePreviousItemJump,mode:b.MOVE,action:()=>ln()?(T({mode:b.COMMAND_LINE}),ne("move jump-previous"),zt({isForceExecutedBySystem:!0})):l("No pending move")},{intent:P.MoveNextItemJump,mode:b.MOVE,action:()=>ln()?(T({mode:b.COMMAND_LINE}),ne("move jump-next"),zt({isForceExecutedBySystem:!0})):l("No pending move")}],Yy=[{intent:P.MoveToNextContainer,mode:b.MOVE,action:()=>ln()?(T({mode:b.COMMAND_LINE}),ne("move to-next"),zt({isForceExecutedBySystem:!0})):l("No pending move")},{intent:P.MoveToPreviousContainer,mode:b.MOVE,action:()=>ln()?(T({mode:b.COMMAND_LINE}),ne("move to-previous"),zt({isForceExecutedBySystem:!0})):l("No pending move")}]});var Jy,Qy=g(()=>{"use strict";me();Xy();Jy={[se.WORKSPACE]:[...tl,...nl],[se.BOARD]:[...tl,...nl],[se.SWIMLANE]:[...tl,...nl,...Yy],[se.TICKET]:[],[se.FIELD]:[],[se.FIELD_LIST]:[],[se.TEXT]:[],[se.COMMENT]:[]}});import{spawn as Bw}from"node:child_process";function Zy(e){let t=process.platform,r=Bw(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return r.unref(),r.on("error",()=>{}),!0}var eb=g(()=>{"use strict"});import $w from"node:fs";import jw from"node:path";var tb,nb=g(()=>{"use strict";rt();vr();w();ee();eb();tb=e=>{let t=we(process.cwd());if(a(t))return l("Unable to resolve project root");let n=Ie({repoRoot:t.value});if(a(n))return l(n.message);let o=hr(e.hash,e.ext),r=jw.join(ki(n.value),o);return $w.existsSync(r)?(Zy(r),d(`Opened ${e.name}`,null)):l("Attachment file not found \u2014 run :sync to fetch it")}});var ob,rb,sb=g(()=>{"use strict";Oe();w();he();O();Wa();Vn();xt();ob=()=>{ne("");let{pendingNavTarget:e}=_r();T({mode:b.DEFAULT}),e&&H.navigate(e),uo({pendingNavTarget:void 0})},rb=[{intent:P.ExitCommandLine,mode:b.HELP,action:()=>(ob(),d("Exiting help",null))},{intent:P.Exit,mode:b.HELP,action:()=>(ob(),d("Closed help",null))},{intent:P.NavPreviousItem,mode:b.HELP,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(H.navigateToPreviousItem(),d("Navigating to previous help item",null))},{intent:P.NavNextItem,mode:b.HELP,action:()=>(H.navigateToNextItem(),d("Navigating to next help item",null))},{intent:P.NavPreviousItemJump,mode:b.HELP,action:()=>(H.jumpToPreviousItem(),d("Jumping to previous help item",null))},{intent:P.NavNextItemJump,mode:b.HELP,action:()=>(H.jumpToNextItem(),d("Jumping to next help item",null))},{intent:P.NavToPreviousContainer,mode:b.HELP,action:()=>(H.navigateToPreviousContainer(),d("Navigating to previous help container",null))},{intent:P.NavToNextContainer,mode:b.HELP,action:()=>(H.navigateToNextContainer(),d("Navigating to next help container",null))}]});var ib,ab,lb=g(()=>{"use strict";Oe();w();he();Fs();O();Vn();ib=()=>{ne(""),T({mode:b.DEFAULT})},ab=[{intent:P.Confirm,mode:b.IDENTITY,description:"[enter] claim the first",action:()=>{let[e]=mr();return e?(T({mode:b.COMMAND_LINE}),ne(`config emails ${e}`),d("Proposed claim",null)):d("Nothing left to claim",null)}},{intent:P.ExitCommandLine,mode:b.IDENTITY,action:()=>(ib(),d("Closed identity",null))},{intent:P.Exit,mode:b.IDENTITY,description:"[esc] close",action:()=>(ib(),d("Closed identity",null))}]});var Uw,cb,db,ub=g(()=>{"use strict";Oe();me();w();he();O();Wa();Vn();xt();Uw=e=>{T({mode:b.COMMAND_LINE});let{pendingNavTarget:t}=_r();t&&H.navigate(t),uo({pendingNavTarget:void 0}),ne(`${e} `)},cb=()=>{ne("");let{pendingNavTarget:e}=_r();e&&H.navigate(e),uo({pendingNavTarget:void 0}),T({mode:b.DEFAULT})},db=[{intent:P.InitCommandPalette,mode:b.DEFAULT,description:"[?] command palette",action:()=>{ne("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=v();return uo({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}}),T({mode:b.PALETTE}),d("Opening command palette",null)}},{intent:P.Confirm,mode:b.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!bm(e))return l("Command only applicable on text nodes");if(e.props.disabled)return l("Command is not available in this context");let t=e.title;return t?(Uw(t),d("Selected command",t)):d("No command selected",null)}},{intent:P.ExitCommandLine,mode:b.PALETTE,action:()=>(cb(),d("Exiting palette",null))},{intent:P.Exit,mode:b.PALETTE,action:()=>(cb(),d("Closed command palette",null))},{intent:P.NavPreviousItem,mode:b.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(H.navigateToPreviousItem(),d("Navigating to previous item",null))},{intent:P.NavNextItem,mode:b.PALETTE,action:()=>(H.navigateToNextItem(),d("Navigating to next item",null))},{intent:P.NavToPreviousContainer,mode:b.PALETTE,action:()=>(H.navigateToPreviousContainer(),d("Navigating to previous container",null))},{intent:P.NavToNextContainer,mode:b.PALETTE,action:()=>(H.navigateToNextContainer(),d("Navigating to next container",null))}]});var mb,pb,fb=g(()=>{"use strict";Fo();_n();Qs();Pa();Oe();w();ja();sr();pe();Bt();he();O();nb();Vn();oo();sb();lb();ub();xt();mb=()=>{let e=co();if(!e)return d("Nothing to comment on here",null);let t=$a();if(!t||t.sha!==e)return l("The diff is still loading");let{selectedIndex:n}=v(),o=Math.max(0,n),r=cd(t.rows,Id(e)??o,o);return r.ok?(T({mode:b.COMMAND_LINE}),ne(`${I.COMMENT} ${Uh(r.value.start,r.value.end)} `),d("Commenting on a diff line",null)):l(r.reason)},pb=[{intent:P.InitCommandLine,mode:b.DEFAULT,description:"[:] write command",action:()=>(T({mode:b.COMMAND_LINE}),ne(""),d("Entering command line mode",null))},...rb,...ab,...db,{intent:P.AddItem,mode:b.DEFAULT,description:"[n] new...",action:()=>(T({mode:b.COMMAND_LINE}),ne(`${I.NEW} `),d("Adding new item",null))},{intent:P.Delete,mode:b.DEFAULT,description:"[d] delete",action:()=>(T({mode:b.COMMAND_LINE}),ne(`${I.DELETE} `),d("Deleting item",null))},{intent:P.Confirm,mode:b.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!ke(e?.id??"")?.length){let o=e?N.getAttachment(e.id):void 0;if(o)return tb(o);if(co())return mb();if(e?.title===Ce.DESCRIPTION)return T({mode:b.COMMAND_LINE}),ne(`${I.EDIT} description `),d("Propose command",!0);if(e?.title===Ce.ASSIGNEES)return T({mode:b.COMMAND_LINE}),ne(`${I.ASSIGN} `),d("Propose command",!0);if(e?.title===Ce.TAGS)return T({mode:b.COMMAND_LINE}),ne(`${I.TAG} `),d("Propose command",!0);if(t.title===Ce.DESCRIPTION&&e?.context==="TEXT")return T({mode:b.COMMAND_LINE}),ne(`${I.EDIT} description `),d("Propose command",!0)}return H.enterChildNode(),d("Entering context",null)}},{intent:P.OpenInEditor,mode:b.DEFAULT,action:()=>{let{selectedNode:e,contextNode:t}=v(),n=t.parentNodeId,r=!!n&&t.id===Te(n,"diff")?e?.id:co()??void 0;return r?vd({sha:r}):d("Nothing here opens in an editor",null)}},{intent:P.MarkDiffLine,mode:b.DEFAULT,action:()=>{let e=co();if(!e)return d("Nothing to mark here",null);let{selectedIndex:t}=v(),n=Id(e);return Ho(n===t?null:{sha:e,row:Math.max(0,t)}),d("Marked diff line",null)}},{intent:P.CommentOnDiffLine,mode:b.DEFAULT,action:()=>co()?mb():d("Nothing to comment on here",null)},{intent:P.Yank,mode:b.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=v(),t=e?.title===Ce.DESCRIPTION?He.DESCRIPTION:e?.title===Ce.TAGS?He.TAGS:e?.title===Ce.ASSIGNEES?He.ASSIGNEES:He.REF,o=We(I.YANK).includes(t)?t:He.REF;return T({mode:b.COMMAND_LINE}),ne(`${I.YANK} ${o}`),d("Propose command",!0)}},{intent:P.EditTitle,mode:b.DEFAULT,description:"[r] rename title",action:()=>(T({mode:b.COMMAND_LINE}),ne(`${I.EDIT} title ${v().selectedNode?.title}`),d("Exiting context",null))},{intent:P.EditDescription,mode:b.DEFAULT,description:"[e] edit desc",action:()=>(T({mode:b.COMMAND_LINE}),ne(`${I.EDIT} description `),d("Exiting context",null))},{intent:P.Exit,mode:b.DEFAULT,description:"[q] exit context",action:()=>(H.enterParentNode(),d("Exiting context",null))},{intent:P.NavPreviousItem,mode:b.DEFAULT,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(H.navigateToPreviousItem(),d("Navigating to previous item",null))},{intent:P.NavNextItem,mode:b.DEFAULT,action:()=>(H.navigateToNextItem(),d("Navigating to next item",null))},{intent:P.NavPreviousItemJump,mode:b.DEFAULT,action:()=>(H.jumpToPreviousItem(),d("Jumping to previous item",null))},{intent:P.NavNextItemJump,mode:b.DEFAULT,action:()=>(H.jumpToNextItem(),d("Jumping to next item",null))},{intent:P.NavToPreviousContainer,mode:b.DEFAULT,action:()=>(H.navigateToPreviousContainer(),d("Navigating to previous container",null))},{intent:P.NavToNextContainer,mode:b.DEFAULT,action:()=>(H.navigateToNextContainer(),d("Navigating to next container",null))}]});var Hw,Ww,gb,hb=g(()=>{"use strict";he();Hw=500,Ww=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),gb=e=>{let t=Ww(e);t&&xa(n=>(n+t).slice(0,Hw))}});var qw,Gw,zw,vb,yb=g(()=>{"use strict";hb();Oe();w();he();O();Vn();Xd();qw=[b.COMMAND_LINE,b.PALETTE],Gw=e=>e==="edit title "?v().selectedNode?.title??"":"",zw=e=>[{intent:P.MoveCursorLeft,mode:e,action:()=>(qc(-1),d("Moving cursor left",null))},{intent:P.MoveCursorRight,mode:e,action:()=>(qc(1),d("Moving cursor right",null))},{intent:P.MoveCursorLeftOfWord,mode:e,action:()=>(Gc("left"),d("Moving cursor left of word",null))},{intent:P.MoveCursorRightOfWord,mode:e,action:()=>(Gc("right"),d("Moving cursor right of word",null))},{intent:P.AutoCompleteCommand,mode:e,action:()=>(xa((t,{remainder:n})=>{let o=n?t+n:t;return o+Gw(o)}),d("Auto-completing command",null))},{intent:P.CaptureInput,mode:e,action:(t,{sequence:n})=>(gb(n??""),d("Capturing input",null))},{intent:P.EraseInput,mode:e,action:()=>(qg(),d("Erasing input",null))},{intent:P.EraseInputWord,mode:e,action:()=>(Gg(),d("Erasing input word",null))}],vb=[{intent:P.Confirm,mode:b.COMMAND_LINE,action:()=>(zt(),d("Executing command",null))},{intent:P.ViewHelp,mode:b.DEFAULT,action:()=>(T({mode:b.HELP}),d("Viewing help",null))},...qw.flatMap(zw),{intent:P.ExitCommandLine,mode:b.COMMAND_LINE,action:()=>(T({mode:b.DEFAULT}),d("Exiting command line",null))},{intent:P.GetLastCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Yg(),d("Getting last command from history",null))},{intent:P.GetNextCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Xg(),d("Getting next command from history",null))}]});var Vw,bb,xb,Ib=g(()=>{"use strict";Vw=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},bb=({keys:e})=>e.length===1?0:1,xb=(e,t)=>{let n=new Set;for(let o of e)o.mode!==t||!o.description||n.add(o.description);return[...n].map(Vw).filter(o=>o!==null).sort((o,r)=>bb(o)-bb(r))}});function Eb(e,t,n){let o=t[e];if(!o)return l("buildBreadCrumb(): current node not found");let r=[],s=new Set,i=o;for(;i&&!s.has(i.id)&&(r.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let c=r[r.length-1];return!c||c.id!==n?l("buildBreadCrumb(): node is not connected to root"):(r.reverse(),d("Breadcrumb built",r))}var Rb=g(()=>{"use strict";w()});var Sb,Nb=g(()=>{"use strict";Sb=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 Kw}from"react";function eu(e){let{contextNodeId:t,mode:n,rootNodeId:o,nodes:r,filters:s}=e;if(!t)return l("derive(): contextNodeId is missing");if(!o)return l("derive(): rootNode is missing");if(!r[o])return l("derive(): unable to find root node");let c=r[t];if(!c)return l("Unable to derive state, contextNode not found");let u=Eb(t,r,o);if(a(u))return logger.error(u.message),u;let p=u.value,{context:m}=c,f=[...pb,...Jy[m]??[],...vb],h=xb(f,n),x=Sb(f),E=Xw(r,s),S=E[t]?.[e.selectedIndex]??null;return d("Derived successfully",{...e,contextNode:c,breadCrumb:p,availableHints:h,availableActions:f,actionIndex:x,selectedNode:S,renderedChildrenIndex:E})}function Rs(e){Jd=e;let t=we(process.cwd()),n=!1;if(!a(t)){let s=At(t.value);if(a(s))return l(s.message);n=!0}let o={readOnly:!1,filters:[],tags:{},contributors:{},emailLinks:{},mode:b.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:{}},r=eu(o);return a(r)?r:(Rt=r.value,Zd(),d("State initialized",null))}function Pe(e){let t=v(),n=e(t);if(zo)return n.nodes!==t.nodes&&(mo=null),li=n,Rt={...t,...n},d("State updated",null);let o=eu(n);return a(o)?l(o.message??"Unable to update state"):(Rt=o.value,Zd(),d("State updated",null))}function Gi(e){if(zo)return d("Joined batch",e());zo=!0,li=null,mo=new Set;let t=()=>{let n=li;if(zo=!1,li=null,n===null)return null;let o=eu(n);return a(o)?l(o.message??"Unable to update state"):(Rt=o.value,Zd(),d("State updated",null))};try{let n=e(),o=t();return o&&a(o)?l(o.message):d("State updated",n)}finally{zo&&t()}}function Vo(e,t,n){if(!zo)return Pe(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let o=v(),r=o[e]??{};if(e==="nodes"){let i=r[t],c=n;i?.parentNodeId&&mo?.add(i.parentNodeId),c.parentNodeId&&mo?.add(c.parentNodeId)}r[t]=n;let s={...o,[e]:r};return li=s,Rt={...o,...s},d("State updated",null)}var Rt,Jd,Qd,Zd,Yw,v,Me,zo,li,uf,T,Ye,mo,wb,Xw,ve,Wn,jt,O=g(()=>{"use strict";Qy();fb();yb();Ib();Jt();Oe();w();ee();uc();Rb();Nb();wt();Cc();Qd=new Set,Zd=()=>{for(let e of Qd)e()},Yw=e=>(Qd.add(e),()=>Qd.delete(e));v=()=>{if(!Rt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Rt},Me=()=>Rt?d("Retrieved state",Rt):l("State not initialized. Call initWorkspaceState() first.");eg(e=>Rt?zn(Rt.emailLinks,e):[]);zo=!1,li=null;uf=()=>zo,T=e=>Pe(t=>({...t,...e}));Ye=()=>Kw(Yw,v,v),mo=null,wb=null,Xw=(e,t)=>{let n=Rt?.renderedChildrenIndex,o=n!==void 0&&mo!==null&&e===wb&&t.length===0&&Rt?.filters.length===0,r;if(o){r={...n};let s=af(e,mo);for(let i of mo){let c=s[i];c?r[i]=c:delete r[i]}}else r=sf(e,t);return wb=e,mo=new Set,r},ve=e=>v()?.renderedChildrenIndex[e]??[],Wn=()=>Jd?Rs(Jd):l("Cannot reset state: no initial workspace found"),jt=()=>Rt!==void 0});var Gt,Jw,po,N,pe=g(()=>{"use strict";Yt();wt();me();w();O();Bt();Gt=(e,t)=>{let{nodes:n}=v(),o=n[e];if(!o)return l("Node not found");if(o.context===t)return d("Resolved ancestor node",o);let r=new Set([o.id]),s=o.parentNodeId?n[o.parentNodeId]:void 0;for(;s&&!r.has(s.id);){if(s.context===t)return d("Resolved ancestor node",s);r.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return l(`No ancestor found for context: ${t}`)},Jw=(e,t)=>{let{nodes:n}=v(),o=new Set,r=n[e];for(;r?.parentNodeId&&!o.has(r.id);){if(r.parentNodeId===t)return!0;o.add(r.id),r=n[r.parentNodeId]}return!1},po=(e,t)=>e?e.readonly?l({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:l("Node not found"),N={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return l("Contributor not found");if(n.userId&&n.userId!==t)return l("Contributor is already linked to another user");let o={...n,userId:t},r=Pe(s=>({...s,contributors:{...s.contributors,[e]:o}}));return a(r)?l("Unable to link contributor to user"):d("Linked contributor to user",o)},deleteNode(e){N.deleteNodes([e])},deleteNodes(e){e.length!==0&&Pe(t=>{let n={...t.nodes};for(let o of e)delete n[o];return{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return l("Unable to create comment, missing issue");if(!U(t))return l("Can only comment on issues");let n=Vo("comments",e.id,{...e,deleted:!1});return a(n)?l("Unable to create comment"):d("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return l("Unable to edit comment, missing comment");let o=this.getNode(n.issue);if(!o)return l("Unable to edit comment, missing issue");if(!U(o))return l("Can only edit issue comments");let r={...n,md:t,deleted:!1},s=Vo("comments",e,r);return a(s)?l("Unable to edit comment"):d("Edited comment",r)},deleteComment(e){let t=this.getComment(e);if(!t)return l("Unable to delete comment, missing comment");let n={...t,deleted:!0},o=Vo("comments",e,n);return a(o)?l("Unable to delete comment"):d("Deleted comment",n)},getComment(e){return v().comments?.[e]},getCommentsByIssue(e){return Object.values(v().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(v().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return l("Unable to create attachment, missing issue");if(!U(t))return l("Can only attach to issues");let n=Pe(o=>({...o,attachments:{...o.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?l("Unable to create attachment"):d("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return l("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},o=Pe(r=>({...r,attachments:{...r.attachments??{},[e]:n}}));return a(o)?l("Unable to delete attachment"):d("Deleted attachment",n)},getAttachment(e){return v().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(v().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(v().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=v(),o=n[e];if(!o)return l("Edit target node not found");let r=po(o,"edit");if(r)return r;let s={...o,props:{...o.props,description:t}};return this.updateNode(s),d("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return l("Rename target node not found");let o=po(n,"rename");if(o)return o;let r={...n,title:t};return this.updateNode(r),d("Renamed node",r)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return ke(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:o}=v(),r=this.getNode(e),s=this.getNode(t);if(!r)return l("Node not found");if(!s)return l("Target parent not found");if(o===e)return l("Cannot move root node");if(e===t)return l("Cannot move node into itself");let i=po(r,"move");if(i)return i;if(Jw(t,e))return l("Cannot move node into its own descendant");let c={...r,parentNodeId:t,rank:n};return this.updateNode(c),d("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:o}=v(),r=this.getNode(e);if(!r)return l("Node not found");if(o===e)return l("Cannot delete root node");let s=po(r,"delete");if(s)return s;let i=new Set,c=p=>{let m=t[p];if(!(!m||i.has(p))){i.add(p);for(let f of ke(m.id))c(f.id)}};c(e);let u={...structuredClone(t)};for(let p of i){if(!u[p])return l("Unable to locate node to delete");u[p]={...u[p],isDeleted:!0}}return n?(T({nodes:u}),d("Successfully tomb stoned",r)):l("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return l("Contributor not found");let n={...t,name:ss,tombstoned:!0},o=Pe(r=>({...r,contributors:{...r.contributors,[e]:n}}));return a(o)?l("Unable to remove contributor"):d("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return l("Contributor not found");if(n.tombstoned)return l("Cannot rename a removed contributor");let o={...n,name:t},r=Pe(s=>({...s,contributors:{...s.contributors,[e]:o}}));return a(r)?l("Unable to rename contributor"):d("Renamed contributor",o)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return l("Contributor not found");let o={...n,name:t,tombstoned:!1},r=Pe(s=>({...s,contributors:{...s.contributors,[e]:o}}));return a(r)?l("Unable to restore contributor"):d("Restored contributor",o)},linkContributorEmail({email:e,contributor:t,authorId:n}){if(!this.getContributor(t))return l("Unable to link email, missing contributor");let o={email:Ve(e),contributor:t,authorId:n},r=is(o.email,t),s=v().emailLinks[r];if(s&&!s.tombstoned)return d("Email already linked",s);let i=Pe(c=>({...c,emailLinks:{...c.emailLinks,[r]:o}}));return a(i)?l("Unable to link email"):d("Linked email to contributor",o)},unlinkContributorEmail(e,t,n){let o=is(e,t),r=v().emailLinks[o];if(!r)return l("Unable to unlink, no such link");if(r.tombstoned)return d("Email already unlinked",r);if(!xi(n,r))return l("Only the author of a link or the contributor it names may remove it");let s={...r,tombstoned:!0},i=Pe(c=>({...c,emailLinks:{...c.emailLinks,[o]:s}}));return a(i)?l("Unable to unlink email"):d("Unlinked email from contributor",s)},getEmailLinks(){return v().emailLinks},createContributor(e){let t=Pe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?l("Unable to create contributor"):d("Created contributor",e)},assign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return l("Unable to assign contributor, missing contributor");if(!o)return l("Unable to assign contributor, missing target");let r=po(o,"edit");if(r)return r;if(!U(o))return l("Target is not an issue");let s=o.props.assignees??[];if(s.includes(t))return l("Contributor already assigned");let i={...o,props:{...o.props,assignees:[...s,t]}};return this.updateNode(i),d("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return l("Unable to unassign, missing contributor");if(!o)return l("Unable to unassign, missing target");let r=po(o,"edit");if(r)return r;if(!U(o))return l("Target is not an issue");let s=o.props.assignees??[];if(!s.includes(t))return d("Issue is not assigned to that contributor",{assignee:t});let i={...o,props:{...o.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),d("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),o=this.getNode(e);if(!n)return l("Unable to add tag, missing tag");if(!o)return l("Unable to add tag, missing target");let r=po(o,"edit");if(r)return r;if(!U(o))return l("Target is not an issue");let s=o.props.tags??[];if(s.includes(t))return l("Tag already assigned");let i={...o,props:{...o.props,tags:[...s,t]}};return this.updateNode(i),d("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),o=this.getNode(e);if(!n)return l("Unable to remove tag, missing tag");if(!o)return l("Unable to remove tag, missing target");let r=po(o,"edit");if(r)return r;if(!U(o))return l("Target is not an issue");let s=o.props.tags??[];if(!s.includes(t))return d("Issue is not tagged with that tag",{tag:t});let i={...o,props:{...o.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),d("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return l("Tag not found");let n={...t,tombstoned:!0},o=Pe(r=>({...r,tags:{...r.tags,[e]:n}}));return a(o)?l("Unable to delete tag"):d("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return l("Tag not found");let o={...n,name:t,tombstoned:!1},r=Pe(s=>({...s,tags:{...s.tags,[e]:o}}));return a(r)?l("Unable to restore tag"):d("Restored tag",o)},createTag(e){let t=Pe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?l("Could not create tag"):d("Tag created",e)},createNode(e){let t=Vo("nodes",e.id,e);return a(t)?l("Unable to create node"):d("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return l("Failed to locate node");let n={...t,readonly:!0},o=Vo("nodes",e,n);return a(o)?l(o.message):d("Locked node",n)},updateNode(e){let t=Vo("nodes",e.id,e);return a(t)?t:d("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){let t=v().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return v().tags[e]},getTags(){return Object.values(v().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return v().nodes[e]},getSiblings(e){return ke(e)}}});import fo from"chalk";import Cb from"string-width";var Qw,Zw,tu,eC,tC,Ab,Tb,nC,oC,rC,sC,iC,aC,Hd,kb,si=g(()=>{"use strict";ft();w();Nn();pe();O();dn();zs();Qw=(e,t)=>e+" ".repeat(Math.max(0,t-Cb(e))),Zw=(e,t)=>" ".repeat(Math.max(0,t-Cb(e)))+e,tu=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed contributor","link.contributor.user":"Linked contributor","link.contributor.email":"Claimed","unlink.contributor.email":"Unclaimed","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),eC=(e,t)=>t?e<t?"up":e>t?"down":null:null,tC=(e,t)=>{let n=N.getNode(e.payload.parent),o=n?fo.dim.bgBlack(` ${n.title} `):"unknown",r=t.at(-1);if(r&&"parent"in r&&"rank"in r&&r.parent===e.payload.parent){let s=eC(e.payload.rank,r.rank);if(s)return`Moved ${s} in ${o}`}return`Moved issue to ${o}`},Ab=e=>`${Math.max(1,Math.round(e/1024))} KB`,Tb=e=>N.getAttachment(e)?.name??"",nC=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?fo.bgHex(nt(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?fo.bgHex(nt(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=v().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?fo.hex(nt(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?fo.hex(nt(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"add.issue.attachment":return`"${e.payload.name}" ${fo.dim(`(${Ab(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Tb(e.payload.id);return t?`"${t}"`:""}default:return""}},oC=e=>{let t=so(ct(e));return fo.gray(Zw(t,8))},rC=12,sC=e=>Qw(`${e}`,rC),iC=e=>{let t=Me();return a(t)?e:rs(e,t.value.contributors[e]?.name)},aC=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=v().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"move.node":{let t=N.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Ab(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Tb(e.payload.id);return t?`"${t}"`:""}default:return""}},Hd=e=>[tu(e.action),aC(e)].filter(Boolean).join(" "),kb=(e,t)=>{let n=oC(e.id),o=sC(iC(e.userId)),r=fo.dim("\u203A"),s=e.action==="move.node"?tC(e,t):[tu(e.action),nC(e)].filter(Boolean).join(" ");return`${o} ${n} ${r} ${s}`}});var Lb={};Zr(Lb,{areVirtualNodesEnabled:()=>Vi,createOrUpdateVirtualField:()=>$r,createOrUpdateVirtualFieldList:()=>nu,materializeTicketVirtualNodes:()=>zi,materializeVirtualNodes:()=>vC,setVirtualNodesEnabled:()=>hC});var lC,cC,dC,uC,mC,pC,fC,$r,nu,zi,gC,Mb,hC,Vi,vC,ic=g(()=>{"use strict";si();me();w();sr();pe();eo();O();Zo();oo();lC=e=>Te(e,"comments"),cC=e=>Te(e,"description"),dC=e=>Te(e,"assignees"),uC=e=>Te(e,"tags"),mC=e=>Te(e,"history"),pC=e=>Te(e,"diff"),fC=e=>Te(e,"attachments"),$r=({id:e,name:t,parentNodeId:n,rank:o,value:r,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=N.getNode(e);if(!c){let m=N.createNode({...Be.field({id:e,name:t,parentNodeId:n,rank:o,props:{value:r},isVirtual:!0}),readonly:s,childRenderAxis:i});return a(m)?m:d("Virtual field created",void 0)}if(!ot(c))return l(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==o||c.props.value!==r||c.readonly!==s||c.childRenderAxis!==i))return d("Virtual field unchanged",void 0);let p=N.updateNode({...c,title:t,parentNodeId:n,rank:o,props:{...c.props,value:r},readonly:s,childRenderAxis:i});return a(p)?p:d("Virtual field updated",void 0)},nu=({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!1,childRenderAxis:s="horizontal"})=>{let i=N.getNode(e);if(!i){let p=N.createNode({...Be.fieldList({id:e,name:t,parentNodeId:n,rank:o,isVirtual:!0}),readonly:r,childRenderAxis:s});return a(p)?p:d("Virtual field list created",void 0)}if(!as(i))return l(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==o||i.readonly!==r||i.childRenderAxis!==s))return d("Virtual field list unchanged",void 0);let u=N.updateNode({...i,title:t,parentNodeId:n,rank:o,readonly:r,childRenderAxis:s});return a(u)?u:d("Virtual field list updated",void 0)},zi=e=>{let t=Ct(Xt/4n),n=Ct(Xt/2n),o=Ct(Xt*3n/4n),r=Ct(Xt*7n/8n),s=Ct(Xt*15n/16n),i=Ct(Xt*13n/16n),c=Ct(Xt*27n/32n);if(a(t))return t;if(a(n))return n;if(a(o))return o;if(a(r))return r;if(a(s))return s;if(a(i))return i;if(a(c))return c;let u=$r({id:cC(e.id),name:Ce.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(u))return u;let p=nu({id:dC(e.id),name:Ce.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(p))return p;let m=nu({id:uC(e.id),name:Ce.TAGS,parentNodeId:e.id,rank:o.value,readonly:!0});if(a(m))return m;let f=$r({id:lC(e.id),name:Ce.COMMENTS,parentNodeId:e.id,rank:r.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(f))return f;let h=$r({id:fC(e.id),name:Ce.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(h))return h;let x=$r({id:mC(e.id),name:Ce.HISTORY,parentNodeId:e.id,rank:i.value,value:gC(e),readonly:!0,childRenderAxis:"vertical"});if(a(x))return x;let E=$r({id:pC(e.id),name:Ce.DIFF,parentNodeId:e.id,rank:c.value,value:"",readonly:!0,childRenderAxis:"vertical"});return a(E)?E:d("Ticket virtual nodes materialized",void 0)},gC=e=>{let t=[...e.log].reverse(),n=new Map;for(let o of t){let r=n.get(o.action)??[];r.push(o.payload),n.set(o.action,r)}return t.map(o=>kb(o,n.get(o.action)??[])).join(`
|
|
107
|
+
`)},Mb=!0,hC=e=>{Mb=e},Vi=()=>Mb,vC=()=>{let{nodes:e}=v();for(let t of Object.values(e)){if(!U(t))continue;let n=zi(t);if(a(n))return n}return d("Virtual nodes materialized",void 0)}});var yC,bC,ol,ou=g(()=>{"use strict";ft();yC=e=>{switch(e.action){case"add.issue":case"move.node":case"close.issue":case"reopen.issue":return e.payload.parent;default:return null}},bC=(e,t)=>{let n=[];for(let o of e){let r=yC(o);if(r===null||r===n.at(-1)?.laneId)continue;let s=yo(o);n.push({laneId:r,enteredAt:s===null?t:ns(s)})}return n},ol=(e,t)=>bC(e,t).at(-1)?.enteredAt??t});var Pb=g(()=>{"use strict";Yt()});var xC,Db,rl=g(()=>{"use strict";ft();$();or();si();w();Pb();Nn();tn();xC=e=>{let t=new Map,n=new Set,o=r=>{let s=new Set,i=r;for(;i&&!s.has(i);){if(n.has(i))return i;s.add(i),i=t.get(i)}return null};return e.map(r=>{let s=r.payload,i=s?.id;if(!i)return null;r.action==="add.board"&&n.add(i);let c=r.action==="close.issue"?o(i):null,u=s.parent??s.issue;return u&&t.set(i,u),c!==null?c:n.has(i)?i:o(i)})},Db=(e,t)=>{let n=xC(e);return e.filter((o,r)=>n[r]===t)}});var IC,Ob,Fb,Ko,ci=g(()=>{"use strict";rt();Tr();rl();$();$();w();O();tn();rl();IC=null,Ob=Promise.resolve(),Fb=e=>{let t=Ob.then(e,e);return Ob=t.then(()=>{},()=>{}),t},Ko=()=>{if(!jt())return{mode:"live",asOfTime:null};let{timeMode:e}=v();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:IC}}});var _b,EC,Bb,$b,jr,sl=g(()=>{"use strict";Ke();wt();_b=new Map,EC=3e4,Bb=async e=>{let t=_b.get(e);if(t&&Date.now()-t.readAt<EC)return{name:t.name,email:t.email};let n=await Le({args:["config","--get-regexp","^user\\.(name|email)$"],cwd:e}),o=null,r=null;if(n.exitCode===0)for(let s of(n.stdout??"").split(`
|
|
108
|
+
`)){let i=s.indexOf(" ");if(i===-1)continue;let c=s.slice(0,i),u=s.slice(i+1);c==="user.name"&&(o=u.trim()||null),c==="user.email"&&(r=Ve(u)||null)}return _b.set(e,{name:o,email:r,readAt:Date.now()}),{name:o,email:r}},$b=async e=>(await Bb(e)).email,jr=async e=>(await Bb(e)).name});import RC from"node:fs";var Yo,il,Z,oe,J,En=g(()=>{"use strict";rt();Ke();Cn();Ms();sl();rn();Fe();Po();or();ee();$();w();O();$t();ci();Yo=e=>{let t=we(e??process.cwd());return a(t)?l(t.message):d("Resolved Epiq repo root",t.value)},il=null,Z=async(e,t)=>{let n=Yo(e);if(a(n))return n;let o=Ie({repoRoot:n.value});if(a(o))return l(o.message);let r=vt(n.value);if(a(r))return l(r.message);if(!(il!==null&&il.repoRoot===n.value&&il.stateBranchRoot===o.value&&RC.existsSync(So(o.value)))){let f=await Ts({repoRoot:n.value,stateBranchName:r.value});if(a(f))return l(f.message);let h=await to({repoRoot:n.value,stateBranchRoot:o.value,stateBranchName:r.value});if(a(h))return l(h.message);il={repoRoot:n.value,stateBranchRoot:o.value}}if(t?.pull??!1){let f=await W({cwd:o.value,args:["pull","--ff-only"]});a(f)&&ce.info(3,f.message)}let i={repoRoot:n.value,stateBranchRoot:o.value},c=gr();a(c)||Qe(c.value),Qe({gitEmail:await $b(n.value),gitName:await jr(n.value)});let u=wo(o.value);if(pp(o.value)===u&&jt()&&Ko().mode==="live")return d("Booted Epiq state, unchanged",i);let p=nn(o.value);if(a(p))return l(p.message);let m=gn(p.value.events,p.value.unreadable);return a(m)?l(m.message):(fp(o.value,u),d("Booted Epiq state",i))},oe=()=>{let e=gr();return a(e)?l(e.message):e.value.userId?e.value.userName?d("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):l("Unable to retrieve user name"):l("Unable to retrieve user id")},J=()=>{let e=Me();return a(e)?l(e.message):e}});var Ur,jb,Hr,ru=g(()=>{"use strict";ft();pe();Nn();pr();Ur=e=>yn(e).map(t=>gt(t.id,t.name)),jb=e=>N.getCommentsByIssue(e).sort((t,n)=>t.id<n.id?-1:t.id>n.id?1:0).map(t=>({id:t.id,author:rs(t.authorId,N.getContributor(t.authorId)?.name),createdAt:ct(t.id),body:t.md})),Hr=e=>bn(e).map(({id:t,name:n})=>gt(t,n))});var et,go,su,Xo=g(()=>{"use strict";me();w();En();et=e=>{let t=J();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?l("Issue not found"):U(n)?n.readonly?l("Issue is readonly"):d("Found issue",n):l("Target must be an issue")},go=e=>{let t=J();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?l("Swimlane not found"):bo(n)?n.readonly?l("Swimlane is readonly"):d("Found swimlane",n):l("Target must be a swimlane")},su=e=>{let t=J();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?l("Board not found"):xo(n)?n.readonly?l("Board is readonly"):d("Found board",n):l("Target must be a board")}});import SC from"node:fs";import NC from"node:path";import{ulid as Ub}from"ulid";var wC,Hb,iu,au=g(()=>{"use strict";rn();$();_t();w();ht();Xo();vr();En();wC=e=>{if(e.filePath)try{return d("Read attachment file",{data:SC.readFileSync(e.filePath),name:e.name??NC.basename(e.filePath)})}catch(t){return l(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?d("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):l("Provide either filePath or dataBase64")},Hb=()=>{let e=gr();return a(e)?Bn:e.value.attachmentMaxKb??Bn},iu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=et(e.issueId);if(a(r))return r;let s=wC(e);if(a(s))return s;let i=Ng(t.value.stateBranchRoot,s.value.data,Hb());if(a(i))return i;let c=Se(s.value.name).trim()||"image",u=Ub(),p={id:Ub(),...D(n.value),action:"add.issue.attachment",payload:{id:u,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:c,bytes:i.value.bytes}},m=F([p],t.value.stateBranchRoot);if(a(m))return l(m.message);let f=hr(i.value.hash,i.value.ext);return d("Added issue attachment",{id:u,issueId:e.issueId,fileName:f,bytes:i.value.bytes,markdown:Bc(c,f)})}});var lu,x6,cu,Wb=g(()=>{"use strict";rn();ft();tn();me();w();pe();ur();Nn();dn();ou();mt();ht();vr();$t();ci();En();ru();au();ra();$();Cs();lu=async(e={})=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();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})},x6=365*24*60*60*1e3,cu=async(e={})=>{ir();let t=Yo(e.repoRoot);if(a(t))return l("Sync failed");let n=oe();if(a(n))return n;let o=await oa({cwd:t.value,ownEventFileName:Qn(n.value)});return a(o)?(mc(o.message),o):(Do(),d("Synced",o.value))}});var di,Wr,ui,du=g(()=>{"use strict";w();mt();di=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?d("Resolved targets",t):l("Provide issueId or issueIds")},Wr=(e,t)=>{let n=t.done.length,o=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?d(o,t):l(`${o}: ${t.failed.map(r=>`${r.ref} ${r.reason}`).join("; ")}`)},ui=(e,t)=>{let n={done:[],failed:[]};for(let o of e){let r=t(o);a(r)?n.failed.push({id:o,ref:V(o),reason:r.message}):n.done.push({id:o,ref:V(o)})}return n}});import{ulid as Vt}from"ulid";async function mu(e){let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=n.value.nodes,r=e.query?.trim().toLowerCase(),s=Object.values(o).filter(U).filter(c=>!c.isDeleted).filter(c=>e.includeClosed||c.parentNodeId!==Ae).filter(c=>e.boardId?(c.parentNodeId?o[c.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(c=>!e.swimlaneId||c.parentNodeId===e.swimlaneId).filter(c=>!e.tag||Ur(c).some(u=>qb(u.name,e.tag))).filter(c=>!e.assignee||Hr(c).some(u=>qb(u.name,e.assignee))).filter(c=>!r||c.title.toLowerCase().includes(r)||(c.props.description??"").toLowerCase().includes(r)),i=c=>Se((c.parentNodeId?o[c.parentNodeId]?.title:void 0)??"");return e.brief?d("Listed issues",s.map(c=>({id:c.id,ref:V(c.id),title:Se(c.title),swimlane:i(c),tags:Ur(c).map(u=>u.name),assignees:Hr(c).map(u=>u.name)}))):d("Listed issues",s.map(c=>({id:c.id,ref:V(c.id),title:Se(c.title),description:c.props.description??"",createdAt:ct(c.id),enteredLaneAt:ol(c.log??[],ct(c.id)),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===Ae,readonly:!!c.readonly,tags:Ur(c),assignees:Hr(c)})))}async function fu(e){let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=di(e);if(a(o))return o;let r=s=>CC(s,n.value,t.value.stateBranchRoot);return e.issueIds?Wr("Closed",ui(o.value,r)):r(o.value[0])}async function hu(e){let t=Yo(e.repoRoot);if(a(t))return t;let n=oe();if(a(n))return n;let o=Ie({repoRoot:t.value});if(a(o))return o;let r=nn(o.value);if(a(r))return r;let s=gn(r.value.events,r.value.unreadable);if(a(s))return s;let i=di(e);if(a(i))return i;let c=u=>AC(u,e,n.value,o.value);return e.issueIds?Wr("Moved",ui(i.value,c)):c(i.value[0])}var uu,qb,pu,CC,gu,AC,vu,yu,Gb=g(()=>{"use strict";rt();Bd();ft();Po();$();$();_t();Wd();tn();me();Nn();w();pe();Bt();si();$n();ou();mt();ht();En();ru();du();Xo();uu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=e.idOrRef.trim();if(!o)return l("Provide an issue id or ref");let r=Object.values(n.value.nodes).filter(U).filter(u=>!u.isDeleted),s=r.find(u=>u.id===o),i=s?[s]:r.filter(u=>Is(u.id,o));if(i.length===0)return l(`No issue matches "${o}"`);if(i.length>1)return l(`"${o}" matches ${i.length} issues: ${i.map(u=>`${V(u.id)} (${Se(u.title)})`).join(", ")}. Use a full ref or id.`);let c=i[0];return d("Found issue",{id:c.id,ref:V(c.id),title:Se(c.title),description:c.props.description??"",createdAt:ct(c.id),enteredLaneAt:ol(c.log??[],ct(c.id)),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===Ae,readonly:!!c.readonly,tags:Ur(c),assignees:Hr(c),comments:jb(c.id)})},qb=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();pu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=Se(e.title);if(!r)return l("Issue title cannot be empty");let s=e.description??"",i=at("Issue title",r,300)??at("Issue description",s,2e4);if(i)return l(i);if((e.tagNames?.length??0)>20)return l(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return l(`Cannot set more than ${20} assignees at once`);let c=go(e.parentId);if(a(c))return c;let u=Dn(e.parentId,n.value,t.value.stateBranchRoot);if(a(u))return u;let p=Ga({name:r,parent:e.parentId,user:n.value,rank:u.value});if(a(p))return p;let m=[...p.value],f=m.find(S=>S.action==="add.issue")?.payload.id;if(!f)return l("Unable to determine created issue id");s&&m.push({id:Vt(),...D(n.value),action:"edit.description",payload:{id:f,md:s}});let h=[];for(let S of e.tagNames??[]){let C=Se(S).trim();if(!C||h.some(_=>_.name===C))continue;let R=at("Tag name",C,60);if(R)return l(R);let A=N.findTagByName(C),L=A?.id??Vt();A||m.push({id:Vt(),...D(n.value),action:"create.tag",payload:{id:L,name:C}}),m.push({id:Vt(),...D(n.value),action:"add.issue.tag",payload:{id:f,tag:L}}),h.push({id:L,name:C})}let x=[];for(let S of e.assigneeNames??[]){let C=Se(S).trim();if(!C||x.some(_=>_.name===C))continue;let R=at("Assignee name",C,80);if(R)return l(R);let A=Object.values(o.value.contributors).find(_=>_.name===C),L=A?.id??Vt();A||m.push({id:Vt(),...D(n.value),action:"create.contributor",payload:{id:L,name:C}}),m.push({id:Vt(),...D(n.value),action:"add.issue.assignee",payload:{id:f,assignee:L}}),x.push({id:L,name:C})}let E=F(m,t.value.stateBranchRoot);return a(E)?l(E.message):d("Created issue",{id:f,ref:V(f),title:r,parentId:e.parentId,description:s,tags:h,assignees:x})},CC=(e,t,n)=>{let o=et(e);if(a(o))return o;let r=pn(Ae,e,{at:"end"},t,n);if(a(r))return r;let s={id:Vt(),...D(t),action:"close.issue",payload:{id:e,parent:Ae,rank:r.value}},i=F([s],n);return a(i)?l(i.message):d("Closed issue",{id:e,ref:V(e)})};gu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r||r.isDeleted)return l("Issue not found");if(!U(r))return l("Target must be an issue");if(r.parentNodeId!==Ae)return l("Issue is not closed");let s=Xa(r);if(!s)return l("Unable to resolve previous parent from issue history");if(s===Ae)return l("Previous parent resolves to closed swimlane");let i=go(s);if(a(i))return i;let c=i.value,u=pn(c.id,r.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(u))return u;let p={id:Vt(),...D(n.value),action:"reopen.issue",payload:{id:r.id,parent:c.id,rank:u.value}},m=F([p],t.value.stateBranchRoot);return a(m)?l(m.message):d("Reopened issue",{id:r.id,ref:V(r.id),parentId:c.id})},AC=(e,t,n,o)=>{let r=et(e);if(a(r))return r;let s=go(t.parentId);if(a(s))return s;let i=pn(t.parentId,e,t.position??{at:"end"},n,o);if(a(i))return i;let c={id:Vt(),...D(n),action:"move.node",payload:{id:e,parent:t.parentId,rank:i.value}},u=F([c],o);return a(u)?l(u.message):d("Moved issue",{id:e,ref:V(e),parentId:t.parentId})};vu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=et(e.issueId);if(a(r))return r;let s=r.value,i=at("Issue description",e.description,2e4);if(i)return l(i);let c=s.props.description??"";if(c===e.description)return d("No changes made",{id:e.issueId,ref:V(e.issueId),description:c});let u={id:Vt(),...D(n.value),action:"edit.description",payload:{id:e.issueId,md:e.description}},p=F([u],t.value.stateBranchRoot);return a(p)?l(p.message):d("Edited issue description",{id:e.issueId,ref:V(e.issueId),description:e.description})},yu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=et(e.issueId);if(a(r))return r;let s=r.value,i=Se(e.title);if(!i.trim())return l("Issue title cannot be empty");let c=at("Issue title",i,300);if(c)return l(c);if(s.title===i)return d("No changes made",{id:e.issueId,ref:V(e.issueId),title:i});let u={id:Vt(),...D(n.value),action:"edit.title",payload:{id:e.issueId,name:i}},p=F([u],t.value.stateBranchRoot);return a(p)?l(p.message):d("Edited issue title",{id:e.issueId,ref:V(e.issueId),title:i})}});import{ulid as ho}from"ulid";var bu,xu,Iu,Eu,Ru,Su,Nu,wu,zb=g(()=>{"use strict";rt();Po();$();$();_t();tn();me();w();Bt();$n();mt();ht();ci();En();Xo();bu=async(e={})=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="BOARD"&&!r.isDeleted).map(r=>({id:r.id,ref:V(r.id),title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return d("Listed boards",o)},xu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=o.value.nodes[o.value.rootNodeId];if(!r)return l("Workspace not found");if(Ko().mode!=="live")return l("Cannot add a board while time travelling");let s=Se(e.title);if(!s.trim())return l("Board title cannot be empty");let i=at("Board title",s,300);if(i)return l(i);let c=Dn(r.id,n.value,t.value.stateBranchRoot);if(a(c))return c;let u=ho(),p={id:ho(),...D(n.value),action:"add.board",payload:{id:u,name:s,parent:r.id,rank:c.value}},m=F([p],t.value.stateBranchRoot);return a(m)?l(m.message):d("Created board",{id:u,ref:V(u),title:s})},Iu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=o.value.nodes[e.boardId];if(!r||r.isDeleted)return l("Board not found");if(!xo(r))return l("Edit target must be a board");if(r.readonly)return l("Cannot edit readonly board");if(Ko().mode!=="live")return l("Cannot rename a board while time travelling");let s=Se(e.title);if(!s.trim())return l("Board title cannot be empty");let i=at("Board title",s,300);if(i)return l(i);if(r.title===s)return d("No changes made",{id:e.boardId,ref:V(e.boardId),title:s});let c={id:ho(),...D(n.value),action:"edit.title",payload:{id:e.boardId,name:s}},u=F([c],t.value.stateBranchRoot);return a(u)?l(u.message):d("Edited board title",{id:e.boardId,ref:V(e.boardId),title:s})},Eu=async(e={})=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="SWIMLANE"&&!r.isDeleted).filter(r=>!e.boardId||r.parentNodeId===e.boardId).map(r=>({id:r.id,title:r.title,boardId:r.parentNodeId,isClosed:r.id===Ae,readonly:!!r.readonly}));return d("Listed swimlanes",o)},Ru=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=su(e.boardId);if(a(r))return r;if(Ko().mode!=="live")return l("Cannot add a swimlane while time travelling");let s=Se(e.title);if(!s.trim())return l("Swimlane title cannot be empty");let i=at("Swimlane title",s,300);if(i)return l(i);let c=Dn(e.boardId,n.value,t.value.stateBranchRoot);if(a(c))return c;let u=ho(),p={id:ho(),...D(n.value),action:"add.swimlane",payload:{id:u,name:s,parent:e.boardId,rank:c.value}},m=F([p],t.value.stateBranchRoot);return a(m)?l(m.message):d("Created swimlane",{id:u,ref:V(u),title:s,boardId:e.boardId})},Su=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=go(e.swimlaneId);if(a(r))return r;let s=r.value,i=Se(e.title);if(!i.trim())return l("Swimlane title cannot be empty");let c=at("Swimlane title",i,300);if(c)return l(c);if(s.title===i)return d("No changes made",{id:e.swimlaneId,ref:V(e.swimlaneId),title:i});let u={id:ho(),...D(n.value),action:"edit.title",payload:{id:e.swimlaneId,name:i}},p=F([u],t.value.stateBranchRoot);return a(p)?l(p.message):d("Edited swimlane title",{id:e.swimlaneId,ref:V(e.swimlaneId),title:i})},Nu=async e=>{let t=Yo(e.repoRoot);if(a(t))return t;let n=oe();if(a(n))return n;let o=Ie({repoRoot:t.value});if(a(o))return o;let r=nn(o.value);if(a(r))return r;let s=gn(r.value.events,r.value.unreadable);if(a(s))return s;let i=go(e.swimlaneId);if(a(i))return i;let c=su(e.boardId);if(a(c))return c;let u=pn(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,o.value);if(a(u))return u;let p={id:ho(),...D(n.value),action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:u.value}},m=F([p],o.value);return a(m)?l(m.message):d("Moved swimlane",{id:e.swimlaneId,ref:V(e.swimlaneId),boardId:e.boardId})},wu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=go(e.swimlaneId);if(a(r))return r;let s={id:ho(),...D(n.value),action:"delete.node",payload:{id:e.swimlaneId}},i=F([s],t.value.stateBranchRoot);return a(i)?l(i.message):d("Deleted swimlane",{id:e.swimlaneId,ref:V(e.swimlaneId)})}});import{ulid as zr}from"ulid";async function Cu(e){let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=di(e);if(a(o))return o;let r=Se(e.tagName).trim();if(!r)return l("Tag name cannot be empty");let s=at("Tag name",r,60);if(s)return l(s);let i=ui(o.value,et);if(!e.issueIds&&i.failed[0])return l(i.failed[0].reason);if(i.done.length===0)return l(Wr("Tagged",i).message);let c=N.findTagByName(r),u=c?.id??zr(),p=[...c?[]:[{id:zr(),...D(n.value),action:"create.tag",payload:{id:u,name:r}}],...i.done.map(({id:x})=>({id:zr(),...D(n.value),action:"add.issue.tag",payload:{id:x,tag:u}}))],m=F(p,t.value.stateBranchRoot);if(a(m))return l(m.message);let f={id:u,name:r};if(!e.issueIds)return d("Added issue tag",{...i.done[0],tag:f});let h=Wr("Tagged",i);return a(h)?h:d(h.message,{...h.value,tag:f})}var Au,Tu,ku,Vb=g(()=>{"use strict";$();_t();w();pe();$n();mt();ht();En();du();Xo();Au=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=o.value.tags[e.tagId];if(!r)return l("Tag not found");if(r.tombstoned)return l("Tag is already deleted");let s=[{id:zr(),...D(n.value),action:"tombstone.tag",payload:{id:e.tagId}}],i=F(s,t.value.stateBranchRoot);return a(i)?l(i.message):d("Deleted tag",{id:r.id,name:r.name})},Tu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=o.value.tags[e.tagId];if(!r)return l("Tag not found");if(!r.tombstoned)return l("Tag is not deleted");if(N.findTagByName(r.name))return l(`Cannot restore: another tag is already named "${r.name}"`);let s=[{id:zr(),...D(n.value),action:"restore.tag",payload:{id:e.tagId,name:r.name}}],i=F(s,t.value.stateBranchRoot);return a(i)?l(i.message):d("Restored tag",{id:r.id,name:r.name})},ku=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=et(e.issueId);if(a(r))return r;if(!o.value.tags[e.tagId])return l("Tag not found");let s={id:zr(),...D(n.value),action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=F([s],t.value.stateBranchRoot);return a(i)?l(i.message):d("Removed issue tag",{id:e.issueId,ref:V(e.issueId),tagId:e.tagId})}});import{ulid as qn}from"ulid";var Mu,Kb,Lu,Pu,TC,Du,Ou,Fu,Yb=g(()=>{"use strict";w();Yt();vo();$();$();_t();Ja();Nn();rl();$n();mt();ht();En();Xo();Mu=async e=>{let t=vl(e.name,"name");if(a(t))return l(t.message);let n=await Z(e.repoRoot,{pull:!1});if(a(n))return n;let o=oe();if(a(o))return o;let r=J();if(a(r))return r;let s=o.value,i=!!r.value.contributors[s.userId];if(!i){let c=F([{id:qn(),...D(s),action:"create.contributor",payload:{id:s.userId,name:s.userName}}],n.value.stateBranchRoot);if(a(c))return l(c.message)}return d(`Assumed ${s.userName}`,{...s,registered:!i})},Kb=async(e,t)=>{let n=ko(e).get(t);return n===void 0?void 0:{id:t,name:n}},Lu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=et(e.issueId);if(a(r))return r;let s=e.self?n.value.userId:e.assigneeId;if(s){let S=o.value.contributors[s],C=S?void 0:await Kb(t.value.stateBranchRoot,s);if(!S&&!C)return l("Unknown assignee id");let R=S??C,A=[...S?[]:[{id:qn(),...D(n.value),action:"create.contributor",payload:{id:R.id,name:R.name}}],{id:qn(),...D(n.value),action:"add.issue.assignee",payload:{id:e.issueId,assignee:R.id}}],L=F(A,t.value.stateBranchRoot);return a(L)?l(L.message):d("Added issue assignee",{id:e.issueId,ref:V(e.issueId),assignee:{id:R.id,name:R.name}})}let i=Se(e.assigneeName??"").trim();if(!i)return l("Provide assigneeId, self or assigneeName");let c=at("Assignee name",i,80);if(c)return l(c);let u=ai({events:o.value.eventLog??[],registry:o.value.contributors,logFileNames:ko(t.value.stateBranchRoot)}).filter(S=>S.name===i);if(u.length>1)return l(`"${i}" matches ${u.length} contributors (${u.map(({id:S})=>S).join(", ")}). Assign by assigneeId to choose.`);let p=u[0];if(!p&&!e.createUnlinked)return l(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let m=p?.id??qn(),f=p?.name??i,x=[...!!o.value.contributors[m]?[]:[{id:qn(),...D(n.value),action:"create.contributor",payload:{id:m,name:f}}],{id:qn(),...D(n.value),action:"add.issue.assignee",payload:{id:e.issueId,assignee:m}}],E=F(x,t.value.stateBranchRoot);return a(E)?l(E.message):d("Added issue assignee",{id:e.issueId,ref:V(e.issueId),assignee:{id:m,name:f}})},Pu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;if(!o.value.contributors[e.contributorId])return l("Contributor not found");if(await Kb(t.value.stateBranchRoot,e.contributorId))return l("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let i=[{id:qn(),...D(n.value),action:"tombstone.contributor",payload:{id:e.contributorId}}],c=F(i,t.value.stateBranchRoot);return a(c)?l(c.message):d("Tombstoned contributor",{id:e.contributorId,name:ss})},TC=async(e,t)=>{let n=Mo(e);if(a(n))return;let o;for(let r of n.value){if(r.action!=="create.contributor")continue;let s=r.payload;s.id===t&&s.name&&(o=s.name)}return o},Du=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=o.value.contributors[e.contributorId];if(!r)return l("Contributor not found");if(!r.tombstoned)return l("Contributor is not tombstoned");let s=await TC(t.value.stateBranchRoot,e.contributorId);if(!s)return l("Cannot restore this contributor \u2014 no original name found in the event log");let i=[{id:qn(),...D(n.value),action:"restore.contributor",payload:{id:e.contributorId,name:s}}],c=F(i,t.value.stateBranchRoot);return a(c)?l(c.message):d("Restored contributor",{id:e.contributorId,name:s})},Ou=async(e={})=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=Mo(t.value.stateBranchRoot);if(a(r))return l(r.message);let s=e.boardId?Db(r.value,e.boardId):r.value,i=new Set,c=Jp(t.value.stateBranchRoot);if(a(c))return l(c.message);for(let m of c.value)m.userId&&i.add(m.userId);let u=o.value.contributors,p=ai({events:s,registry:u,logFileNames:ko(t.value.stateBranchRoot)}).map(({id:m,name:f,isExternal:h})=>({...gt(m,f),isSelf:m===n.value.userId,isExternal:h,isRemoved:u[m]?.tombstoned===!0,hasAuthoredAnywhere:i.has(m)}));return d("Listed board contributors",p)},Fu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=et(e.issueId);if(a(r))return r;if(!o.value.contributors[e.assigneeId])return l("Assignee not found");let s={id:qn(),...D(n.value),action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=F([s],t.value.stateBranchRoot);return a(i)?l(i.message):d("Removed issue assignee",{id:e.issueId,ref:V(e.issueId),assigneeId:e.assigneeId})}});import{ulid as cl}from"ulid";var _u,Bu,$u,Xb=g(()=>{"use strict";$();_t();w();$n();En();Xo();_u=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=et(e.issueId);if(a(r))return r;let s=e.body.trim();if(!s)return l("Comment cannot be empty");if(s.length>4e3)return l(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i=cl(),c={id:cl(),...D(n.value),action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},u=F([c],t.value.stateBranchRoot);return a(u)?l(u.message):d("Added issue comment",{id:i,issueId:e.issueId,body:s})},Bu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=o.value.eventLog.find(p=>p.action==="add.issue.comment"&&p.payload.id===e.commentId);if(!r)return l("Unable to resolve comment");if(r.payload.author!==n.value.userId)return l("You can only delete your own comments");let s=et(r.payload.issue);if(a(s))return s;if(o.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return d("Comment already deleted",{id:e.commentId,issueId:r.payload.issue});let c={id:cl(),...D(n.value),action:"delete.issue.comment",payload:{id:e.commentId,issue:r.payload.issue}},u=F([c],t.value.stateBranchRoot);return a(u)?l(u.message):d("Deleted issue comment",{id:e.commentId,issueId:r.payload.issue})},$u=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=o.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!r)return l("Unable to resolve comment");if(r.payload.author!==n.value.userId)return l("You can only edit your own comments");let s=et(r.payload.issue);if(a(s))return s;if(o.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return l("Comment was deleted");let c=e.body.trim();if(!c)return l("Comment cannot be empty");if(c.length>4e3)return l(`Comment cannot exceed ${4e3} characters (got ${c.length})`);let u={id:cl(),...D(n.value),action:"edit.issue.comment",payload:{id:e.commentId,issue:r.payload.issue,md:c}},p=F([u],t.value.stateBranchRoot);return a(p)?l(p.message):d("Edited issue comment",{id:e.commentId,issueId:r.payload.issue,body:c})}});import{ulid as Jb}from"ulid";var ju,Uu,Hu,Wu,qu=g(()=>{"use strict";$();wt();Nn();w();Cn();sl();Kd();Fe();En();ju=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;if(!Gn(e.email))return l(`Not an email address: ${e.email}`);let r=Ve(e.email),s=e.contributorId??n.value.userId;if(!o.value.contributors[s])return l(`Unknown contributor: ${s}`);let i=Sl(o.value.emailLinks,r);if(i.includes(s))return d(`${r} is already yours`,{contributor:s,email:r,contested:i.filter(u=>u!==s)});let c=F([{id:Jb(),action:"link.contributor.email",payload:{contributor:s,email:r},userId:n.value.userId}],t.value.stateBranchRoot);return a(c)?l(c.message):d(i.length>0?`Claimed ${r}, but somebody else claims it too, so it now resolves to neither of you`:`Claimed ${r}`,{contributor:s,email:r,contested:i})},Uu=async e=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let r=Ve(e.email),s=e.contributorId??n.value.userId,i=o.value.emailLinks[is(r,s)];if(!i||i.tombstoned)return l(`No such link: ${r} to ${s}`);if(!xi(n.value.userId,i))return l("Only whoever made a claim, or the contributor it names, may undo it");let c=F([{id:Jb(),action:"unlink.contributor.email",payload:{contributor:s,email:r},userId:n.value.userId}],t.value.stateBranchRoot);return a(c)?l(c.message):d(`Unclaimed ${r}`,{contributor:s,email:r})},Hu=async(e={})=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let{emailLinks:o,contributors:r}=n.value,s=new Map;for(let f of Object.values(o)){if(f.tombstoned)continue;let h=s.get(f.email)??new Set;h.add(f.contributor),s.set(f.email,h)}let i=[...s.entries()].map(([f,h])=>({email:f,contested:h.size>1,claimants:[...h].map(x=>gt(x,r[x]?.name))})).sort((f,h)=>f.email.localeCompare(h.email)),c=oe(),u=a(c)?[]:zn(o,c.value.userId),p=le().gitEmail,m=p?Sl(o,p).filter(f=>a(c)||f!==c.value.userId):[];return d("Listed contributor emails",{emails:i,mine:u,git:p?{email:p,linkedToMe:u.includes(p),heldByOthers:m.map(f=>gt(f,r[f]?.name))}:null})},Wu=async(e={})=>{let t=await Z(e.repoRoot,{pull:!1});if(a(t))return t;let n=oe();if(a(n))return n;let o=J();if(a(o))return o;let{userId:r,userName:s}=n.value,i=vt(t.value.repoRoot),c=await Za({repoRoot:t.value.repoRoot,stateBranch:a(i)?void 0:i.value,names:[s,await jr(t.value.repoRoot)],links:o.value.emailLinks});if(a(c))return c;let u=el(c.value),p=u.filter(m=>m.looksLikeYours);return d(u.length===0?"No unclaimed addresses in this history":`${u.length} unclaimed address(es) in this history, ${p.length>0?`${p.length} of which look like yours`:"none obviously yours"}. Show them to the user and link only the ones they confirm; each is a permanent event that replicates to every clone.`,{contributor:r,candidates:u,likely:p.length})}});var Qb=g(()=>{"use strict";Wb();Gb();zb();Vb();Yb();Xb();au();qu()});import{ulid as kC}from"ulid";var Zb,ex,tx,nx=g(()=>{"use strict";vo();ur();sl();rn();w();Dd();$t();Zb=[{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)"}],ex=e=>e.trim().toLowerCase(),tx=async(e={})=>{let t=no();if(a(t))return l(t.message);let n=t.value,o=e.userName?.trim(),r=(process.env[Ot]??"").trim();if(o&&r&&ex(o)===ex(r))return l(`userName "${o}" 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:o||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 C of Zb){let R=s[C.name],A=i[C.name];if(!(R===void 0||A===void 0||R===A))return l(`This machine is already set up with ${C.name} ${JSON.stringify(A)}; epiq_project_init does not change it. Call again without ${C.name}, or let the user change it in the TUI with :config.`)}let c={};if(s.userName&&!i.userName&&(c.userName=s.userName),s.preferredEditor&&!i.preferredEditor&&(c.preferredEditor=s.preferredEditor),s.autoSync!==void 0&&i.autoSync===void 0&&(c.autoSync=s.autoSync),(c.userName||i.userName)&&!n.userId&&(c.userId=kC()),Object.keys(c).length>0){let C=it(c);if(a(C))return l(C.message)}let u={...n,...c},p=Zb.filter(C=>{let R=u[C.name];return typeof R=="boolean"?!1:!R?.trim()});if(p.length>0){let C=p.map(L=>`${L.name} (${L.question})`).join("; "),R=p.some(L=>L.name==="userName")?await jr(e.repoRoot??process.cwd()):null,A=R?` This repository's git user.name is ${JSON.stringify(R)} \u2014 offer it as the default for userName, and use it only if the user agrees.`:"";return l(`Setup incomplete. Ask the user for: ${C}.${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 l("Missing Epiq user id");let f=await qa({cwd:e.repoRoot??process.cwd(),user:m});if(a(f))return f;let{defaultEvents:h,...x}=f.value,E=Os({root:x.repoRoot});a(E)&&ce.info(E.message);let S=x.warnings.length===0?"Project initialized":`Project initialized, with warnings: ${x.warnings.join(" ")}`;return d(S,{...x,user:m})}});var Rn,dl=g(()=>{"use strict";Rn=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""})});var MC,ox,rx=g(()=>{"use strict";dl();MC=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},ox=({commits:e,patch:t})=>{let n=e.map(i=>i.time),r=t.files.map(i=>({...Rn(i),changed:i.addedCount+i.removed})).reduce((i,c)=>i===null||c.changed>i.changed?c:i,null),s=t.insertions+t.deletions;return{commits:e.length,authors:[...new Set(e.map(i=>i.author))].sort(),firstCommitAt:n.length?Math.min(...n):null,lastCommitAt:n.length?Math.max(...n):null,files:t.files.length,filesAdded:t.files.filter(i=>i.status==="added").length,filesModified:t.files.filter(i=>i.status==="modified").length,filesDeleted:t.files.filter(i=>i.status==="deleted").length,binaryFiles:t.files.filter(i=>i.binary).length,directories:new Set(t.files.map(i=>MC(i.path))).size,insertions:t.insertions,deletions:t.deletions,net:t.insertions-t.deletions,largestFile:r,concentration:r&&s>0?r.changed/s:0,selfChurn:t.selfChurn,truncated:t.truncated}}});var Xe,Kt,Gu,Vr,LC,Q,ul,ml,sx,PC,ix,Jo,pi,DC,OC,Kr,FC,_C,BC,cn,ax,lx,cx,$C,jC,dx,ux,Yr=g(()=>{"use strict";Xe={line:["//"],block:[["/*","*/"]]},Kt={line:["#"],block:[]},Gu={line:["--"],block:[]},Vr={line:[],block:[["<!--","-->"]]},LC={line:[],block:[]},Q=(e,t)=>({name:e,comment:t}),ul=Q("TypeScript",Xe),ml=Q("JavaScript",Xe),sx={ts:ul,tsx:ul,mts:ul,cts:ul,js:ml,jsx:ml,mjs:ml,cjs:ml,py:Q("Python",{line:["#"],block:[['"""','"""']]}),rb:Q("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:Q("Go",Xe),rs:Q("Rust",Xe),java:Q("Java",Xe),kt:Q("Kotlin",Xe),swift:Q("Swift",Xe),c:Q("C",Xe),h:Q("C",Xe),cc:Q("C++",Xe),cpp:Q("C++",Xe),hpp:Q("C++",Xe),cs:Q("C#",Xe),php:Q("PHP",Xe),scala:Q("Scala",Xe),dart:Q("Dart",Xe),lua:Q("Lua",Gu),hs:Q("Haskell",Gu),sql:Q("SQL",Gu),ex:Q("Elixir",Kt),exs:Q("Elixir",Kt),pl:Q("Perl",Kt),r:Q("R",Kt),jl:Q("Julia",Kt),sh:Q("Shell",Kt),bash:Q("Shell",Kt),zsh:Q("Shell",Kt),vue:Q("Vue",Vr),svelte:Q("Svelte",Vr),html:Q("HTML",Vr),xml:Q("XML",Vr),md:Q("Markdown",Vr),mdx:Q("Markdown",Vr),css:Q("CSS",{line:[],block:[["/*","*/"]]}),scss:Q("CSS",Xe),less:Q("CSS",Xe),yml:Q("YAML",Kt),yaml:Q("YAML",Kt),toml:Q("TOML",Kt),ini:Q("INI",Kt),json:Q("JSON",LC)},PC="Other",ix=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},Jo=e=>sx[ix(e)]?.name??PC,pi=e=>sx[ix(e)]?.comment??null,DC=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],OC=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,Kr=e=>OC.test(e)||DC.some(t=>t.test(e)),FC=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,_C=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,BC=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,cn=e=>FC.test(e)||_C.test(e)||BC.test(e),ax=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),lx=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),cx=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),$C=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,jC=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,dx=e=>$C.test(e),ux=e=>jC.test(e)});var mx,UC,zu,HC,px,Vu=g(()=>{"use strict";Yr();mx=/\b(TODO|FIXME|HACK|XXX)\b/,UC=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,zu=(e,t)=>{let n=e.trim();return n===""?"blank":t&&(t.line.some(o=>n.startsWith(o))||t.block.some(([o])=>n.startsWith(o))||t.block.some(([o])=>o==="/*")&&(n.startsWith("*")||n.startsWith("*/")))?"comment":"code"},HC=(e,t)=>{let n=e.trim();for(let o of[...t.line,...t.block.flat(),"*"])if(n.startsWith(o)){n=n.slice(o.length).trim();break}return n},px=({patch:e,repoShareByLanguage:t})=>{let n=new Map,o=0,r=0,s=0,i=0,c=0,u=0;for(let m of e.files){if(m.binary||cn(m.path))continue;let f=pi(m.path);if(!f||f.line.length===0&&f.block.length===0)continue;let h=Jo(m.path),x=n.get(h)??{comment:0,code:0};for(let{text:E}of m.added){let S=zu(E,f);if(mx.test(E)&&i++,S==="blank"){s++;continue}if(S==="comment"){o++,x.comment++,f&&UC.test(HC(E,f))&&u++;continue}r++,x.code++}for(let{text:E}of m.removedLines)mx.test(E)&&c++;n.set(h,x)}let p=o+r;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:o,codeLines:r,blankLines:s,share:p===0?0:o/p,todoLinesAdded:i,todoLinesRemoved:c,commentedOutCodeLines:u}}});var WC,pl,Ku,qC,GC,zC,fx,gx=g(()=>{"use strict";Yr();dl();WC=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,pl=6,Ku=10,qC=e=>{let t=0;for(let n of e){if(n.trim()===""||n.startsWith(" "))continue;let o=n.length-n.trimStart().length;o>0&&(t===0||o<t)&&(t=o)}return Math.min(Math.max(t,2),8)},GC=(e,t)=>{let n=e.length-e.trimStart().length;if(n===0)return 0;let o=e.slice(0,n).split(" ").length-1;return o>0?o:Math.floor(n/t)},zC=e=>{if(e.length<pl*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let o=0;o+pl<=e.length;o++){let r=e.slice(o,o+pl);if(r.some(c=>c.text.length<3))continue;let s=r.map(c=>c.text).join(`
|
|
109
|
+
`),i=t.get(s);if(i===void 0){t.set(s,{...r[0],at:o});continue}if(i.file!==r[0]?.file)for(let c=0;c<pl;c++)n[i.at+c]=!0,n[o+c]=!0}return n.filter(Boolean).length},fx=({patch:e})=>{let t=[],n=[],o=[],r=!1,s=0,i=0,c=null,u=[];for(let[p,m]of e.files.entries()){if(cn(m.path)&&t.push(Rn(m)),ax(m.path)&&n.push(Rn(m)),lx(m.path)&&o.push(Rn(m)),cx(m.path)&&(r=!0),m.binary||cn(m.path))continue;let f=m.added.map(E=>E.text),h=qC(f),x=m.status!=="deleted";for(let E of f){WC.test(E)&&s++;let S=GC(E,h);S>i&&(i=S,c=Rn(m)),x&&u.push({text:E.trim(),file:p})}u.push({text:" ",file:p})}return{generatedPaths:t.slice(0,Ku),dependencyManifests:n.slice(0,Ku),buildOrCiPaths:o.slice(0,Ku),docsTouched:r,debugPrintLinesAdded:s,maxIndentLevels:i,deepestFile:c,duplicatedLines:zC(u)}}});var hx,vx=g(()=>{"use strict";Yr();hx=({patch:e,languagesBefore:t})=>{let n=new Map,o=0;for(let i of e.files){if(i.binary)continue;let c=i.addedCount+i.removed;if(cn(i.path)){o+=c;continue}let u=Jo(i.path),p=n.get(u)??{name:u,added:0,removed:0,addedInTests:0,share:0};p.added+=i.addedCount,p.removed+=i.removed,Kr(i.path)&&(p.addedInTests+=i.addedCount),n.set(u,p)}let r=[...n.values()].reduce((i,c)=>i+c.added+c.removed,0),s=[...n.values()].map(i=>({...i,share:r===0?0:(i.added+i.removed)/r})).sort((i,c)=>c.added+c.removed-(i.added+i.removed));return{languages:s,introduced:t===null?[]:s.filter(i=>!t.has(i.name)).map(i=>i.name),generatedLines:o}}});var VC,Yu,KC,yx,YC,Xu,XC,JC,bx,xx,QC,ZC,eA,Ix,Ex=g(()=>{"use strict";Ke();w();VC=200,Yu=2e5,KC=5e4,yx=25,YC=64*1024*1024,Xu="",XC=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/,JC=/^diff --git a\/(.+) b\/\1$/,bx=(e,t)=>e==="/dev/null"?null:e.startsWith(t)?e.slice(2):e,xx=(e,t)=>e===null?"added":t===null?"deleted":"modified",QC=()=>({byPath:new Map,insertions:0,deletions:0,selfChurn:0,retainedLines:0}),ZC=(e,t)=>{let n=e.byPath,o="",r=null,s=null,i=null,c=!1,u=0,p=(f,h)=>h==="modified"&&f==="added"?"added":h,m=(f,h)=>{let x=n.get(f);if(x)return x.entry.status=p(x.entry.status,h),x.entry.shas.includes(o)||x.entry.shas.push(o),x;let S={entry:{path:f,status:h,binary:!1,added:[],addedCount:0,removed:0,removedLines:[],shas:[o]},pendingByText:new Map};return n.set(f,S),S};for(let f of t.split(`
|
|
110
|
+
`)){if(f.startsWith(Xu)){o=f.slice(Xu.length).trim(),r=null,s=null,i=null,c=!1;continue}if(f.startsWith("diff --git ")){r=null,i=null,c=!0,s=JC.exec(f)?.[1]??null;continue}if(c&&f.startsWith("Binary files ")&&s){let[,x=""]=/^Binary files (.*) differ$/.exec(f)??[],[E="",S=""]=x.split(" and ");r=m(s,xx(E==="/dev/null"?null:E,S==="/dev/null"?null:S)),r.entry.binary=!0;continue}if(c&&f.startsWith("--- ")){i=bx(f.slice(4),"a/");continue}if(c&&f.startsWith("+++ ")){let x=bx(f.slice(4),"b/"),E=x??i??s;E&&(r=m(E,xx(i,x)));continue}let h=XC.exec(f);if(h){u=Number(h[1]),c=!1;continue}if(r){if(f.startsWith("+")){let x=f.slice(1);e.insertions++,r.entry.addedCount++,e.retainedLines<Yu&&(r.entry.added.push({sha:o,line:u,text:x}),e.retainedLines++),r.pendingByText.size<KC&&r.pendingByText.set(x,(r.pendingByText.get(x)??0)+1),u++;continue}if(f.startsWith("-")){let x=f.slice(1);e.deletions++,r.entry.removed++,e.retainedLines<Yu&&(r.entry.removedLines.push({sha:o,line:0,text:x}),e.retainedLines++);let E=r.pendingByText.get(x)??0;E>0&&x.trim().length>2&&(e.selfChurn++,r.pendingByText.set(x,E-1))}}}},eA=e=>({files:[...e.byPath.values()].map(t=>t.entry),insertions:e.insertions,deletions:e.deletions,selfChurn:e.selfChurn,retainedLines:e.retainedLines}),Ix=async({repoRoot:e,shas:t})=>{if(t.length===0)return d("No commits to scan",{files:[],insertions:0,deletions:0,selfChurn:0,scannedCommits:0,truncated:!1});let n=t.slice(0,VC).reverse(),o=QC(),r=0,s=0,i=!1;for(let u=0;u<n.length;u+=yx){let p=n.slice(u,u+yx),m=await W({cwd:e,args:["-c","core.quotePath=false","show","--unified=0","--no-renames","--no-color",`--format=${Xu}%H`,...p]});if(a(m))return l(m.message);if(ZC(o,m.value.stdout),r+=m.value.stdout.length,s+=p.length,r>YC){i=!0;break}}let c=eA(o);return d("Scanned ticket patch",{files:c.files,insertions:c.insertions,deletions:c.deletions,selfChurn:c.selfChurn,scannedCommits:s,truncated:i||s<t.length||c.retainedLines>=Yu})}});var tA,nA,Rx,Sx=g(()=>{"use strict";Ke();w();Vu();Yr();tA=40,nA=/^\d{6} blob ([0-9a-f]{40})\t(.+)$/,Rx=async({repoRoot:e,sha:t})=>{let n=await Le({cwd:e,args:["-c","core.quotePath=false","ls-tree","-r",`${t}~1`]});if(n.exitCode!==0)return null;let o=new Set,r=new Map;for(let m of n.stdout.split(`
|
|
111
|
+
`)){let f=nA.exec(m);if(!f)continue;let[,h="",x=""]=f;if(cn(x))continue;let E=Jo(x);if(o.add(E),Kr(x)||!pi(x))continue;let S=r.get(E)??[];S.length<tA&&(S.push({blob:h,path:x}),r.set(E,S))}let s=[...r.values()].flat(),i=await Dl(s.map(m=>m.blob),e);if(a(i))return{languages:o,commentShareByLanguage:new Map};let c=i.value,u=new Map;for(let{blob:m,path:f}of s){let h=c.get(m);if(h===void 0)continue;let x=pi(f),E=Jo(f),S=u.get(E)??{comment:0,code:0};for(let C of h.split(`
|
|
112
|
+
`)){let R=zu(C,x);R==="comment"&&S.comment++,R==="code"&&S.code++}u.set(E,S)}let p=new Map;for(let[m,f]of u){let h=f.comment+f.code;h>0&&p.set(m,f.comment/h)}return{languages:o,commentShareByLanguage:p}}});var Nx,wx=g(()=>{"use strict";Yr();dl();Nx=({patch:e})=>{let t=0,n=0,o=[],r=[],s=0,i=0;for(let c of e.files)if(!(c.binary||cn(c.path))&&Kr(c.path)){t+=c.addedCount,n+=c.removed,c.status==="added"&&o.push(Rn(c)),c.status==="deleted"&&r.push(Rn(c));for(let{text:u}of c.added)dx(u)&&s++,ux(u)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:o,deletedTestFiles:r,skippedTestLinesAdded:s,focusedTestLinesAdded:i}}});var oA,Cx,Ax=g(()=>{"use strict";w();rx();Vu();gx();vx();Ex();Sx();wx();oA=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,Cx=async({repoRoot:e,ref:t,commits:n})=>{let o=await Ix({repoRoot:e,shas:n.map(c=>c.sha)});if(a(o))return l(o.message);let r=o.value,s=oA(n),i=s?await Rx({repoRoot:e,sha:s}):null;return d("Derived issue stats",{ref:t,shape:ox({commits:n,patch:r}),languages:hx({patch:r,languagesBefore:i?.languages??null}),tests:Nx({patch:r}),comments:px({patch:r,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:fx({patch:r})})}});var Tx,kx=g(()=>{"use strict";Ja();w();wt();O();Tx=e=>{if(a(e))return e;let t=Me(),n=a(t)?{}:t.value.emailLinks,o=a(t)?{}:t.value.contributors,r=ym(n),s=e.value.map(i=>({...i,authorIdentity:Ry({authorName:i.author,authorEmail:i.authorEmail,owners:r,registry:o})}));return d(e.message,s)}});var rA,fi,sA,Mx,Lx=g(()=>{"use strict";w();Ax();mt();ee();kx();Qs();rA=32,fi=new Map,sA=(e,t)=>{if(fi.set(e,t),fi.size>rA){let n=fi.keys().next();n.done||fi.delete(n.value)}return t},Mx=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return l("idOrRef must not be empty");let n=t.length>7?V(t):t.toUpperCase(),o=we(e.repoRoot??process.cwd());if(a(o))return l(o.message);let r=o.value,s=Tx(await Lr({repoRoot:r,ref:n}));if(a(s))return l(s.message);let i=s.value.map(m=>({sha:m.sha,time:m.time,author:m.authorIdentity?.resolved?m.authorIdentity.name:m.author,subject:m.subject})),c=[r,n,i.map(m=>`${m.sha}:${m.author}`).join(",")].join(" "),u=fi.get(c);if(u)return d("Derived issue stats",u);let p=await Cx({repoRoot:r,ref:n,commits:i});return a(p)?l(p.message):d("Derived issue stats",sA(c,p.value))}});var Xr,Ju,Px=g(()=>{"use strict";Xr=".claude/skills/epiq/SKILL.md",Ju="---\nname: epiq\ndescription: Workflow rules for working the epiq issue board \u2014 use the epiq MCP, sync on demand, scope tickets small, keep status/tags accurate, and communicate via comments.\n---\n\n# Epiq board workflow\n\n- **Never test against the real board.** Point any dev server, manual test or test run at a throwaway project, never at this repo's own. Deleting test tickets afterwards does not undo the events. Stop the dev server when you're done rather than leaving it autosyncing.\n- **Use the epiq MCP tools** (`epiq_*`) for all board operations \u2014 never the `epiq` CLI or hand-edited state files.\n- **Never edit the state branch directly.** Don't check it out, don't write to its worktree, don't touch the event log or any file under it by hand or by script \u2014 go through the MCP for every read and write. The event log is the system of record: an edit made outside it bypasses validation and ordering, and can corrupt history in ways no later fix can undo.\n- **Sync is on-demand only.** MCP reads/writes operate on local state and never pull/push automatically. Call `epiq_sync` explicitly when you need the latest remote state or want to publish local changes.\n- **Break work into small, scoped tickets.** One ticket per independent unit of work, not one giant ticket for a whole feature/epic. Small tickets move through the board cleanly and are easier to review.\n- **A small request tightly coupled to a ticket goes into that ticket, not a new one.** When the user asks for a tweak that only makes sense as part of work a ticket already covers \u2014 halving a limit it just introduced, moving a control it just added \u2014 do not file a fresh ticket for it. Record the new requirement as a comment on the original ticket and fold it into the description, move the ticket back to Ongoing if it had already reached Done, prefix the follow-up's commits with that ticket's ref, and add a further `Solution:` comment when it lands, so the ticket's own commit list tells the whole story. `QPPR7PE` is what this avoids: a one-line follow-up to `MBB6WY5` (halve the log cap it had just introduced) that now lives on a ticket of its own. The original does not have to be the ticket you took this session: any ticket open on the board and assigned to you counts. A new ticket is for work that stands on its own \u2014 that someone else could pick up cold, or that needs more than a line or two to describe.\n- **Keep the status column current as work progresses**\n- **Assign the ticket to yourself when you pick it up**, alongside moving it to Ongoing \u2014 so the board shows who is on what, not just what is in flight.\n- **A ticket you file for work you will do this session is assigned to you as you file it.** Filing it unassigned and picking it up a minute later leaves a window where the board shows nobody on it. Picking up a ticket assigned to somebody else is fine \u2014 but ask the user first: it may be mid-flight in another session, and the assignee is what says so.\n- **Take a name as soon as this skill loads, and say it.** Your board identity is `provider/human-name` \u2014 the model provider, a slash, then a short human first name: `claude/peter`, `codex/fred`. Announce it as your first line, exactly `Assuming claude/peter`, and work under it for the whole session so the log reads \"claude/peter did X\" rather than signing the user's name to your work. Before inventing one, call `epiq_contributor_list` and reuse an existing identity for your provider if there is one \u2014 a name is permanent once it has authored anything (`tombstoneContributor` refuses authors), and each new one adds a contributor and an event log file forever. Keep the name stable across sessions; never rename yourself mid-session.\n- **Make the name true with `epiq_actor_assume`, before your first board write.** Announcing alone changes nothing: the writes would still be signed with the user's name. The tool takes the identity for the rest of the session and registers it, so the board carries `claude/peter` rather than the sanitized `claude-peter` the log file name would give. It is idempotent, so re-announcing is free; if it refuses because the server was launched under a name, that name wins \u2014 work under the one it reports and say so. Never claim an attribution the tool did not confirm.\n- **Boot your own MCP instance, and never share one.** `epiq_actor_assume` binds the name to the server process it is called on, so two sessions on one server \u2014 or a session on the user's own instance \u2014 would sign every write with whichever name was assumed last, and the log would fold them into one contributor. Every session therefore needs a server process of its own before its first board call: the one Claude Code spawns for the session counts, and if that never connected (a `CONNECT_TIMEOUT` at boot), start one yourself \u2014 `npx -y -p epiq@latest epiq-mcp` speaks MCP JSON-RPC over stdio, so a small script holding that process and forwarding `tools/call` requests is enough \u2014 rather than waiting on the user or borrowing another session's. Assume the name on *that* process; a restart forgets it, so assume it again before the next write. Kill what you started when the session ends, including the `epiq-mcp` child, which outlives its parent.\n- **When other agents may be running, ask which name to take rather than picking one.** Nothing stops two live agents answering to one name \u2014 the log is a CRDT and takes concurrent writers happily, so they would converge into one indistinguishable identity rather than fail. Another session is likely whenever there is more than one `epiq-mcp` process, another worktree with recent changes, or the user says so; in that case list the existing names for your provider from `epiq_contributor_list` and ask the user which one is free, before `epiq_actor_assume` \u2014 a name once assumed binds the server process, and a second name is refused until it restarts. Ask with the names in the question, not \"which name?\": the user is choosing between identities they can see on the board.\n- **Name the terminal window after the identity.** Several sessions look alike; the name in the tab is how the user tells which window is `claude/peter`. The session cannot reach the terminal itself \u2014 the shell it runs has no tty \u2014 so put the request in the announcement line: `Assuming claude/peter \u2014 please /rename claude/peter so this window carries the name.`\n- **Prefix commits with the ticket ref. **Retrieve the ref programmatically, NEVER DERIVE IT.\\*\\* Read the `ref` field off the MCP response (`epiq_issue_list` and `epiq_board_list` include it on every entry). This is what link-by-reference feature matches on.\n- **Work in a worktree, and leave the root checkout alone.** Take one before the first edit (`EnterWorktree`, or `git worktree add .claude/worktrees/<ref>-<slug>` for a branch that already exists), and never check a feature branch out at the root: the root is where `main` belongs and where the user checks it out themselves, and a branch checked out anywhere is unavailable everywhere else. For the same reason `main` never goes *into* a worktree. Several sessions share this repository at once, so a shared checkout also means one session's `checkout` or `reset` quietly discarding another's work. A fresh worktree needs its own `npm install` before the hooks and suites will run there.\n- **Never work on main, and never merge into it locally. Every change reaches main through a pull request.** Branch before the first edit, push the branch, open the PR, let the gate run, then integrate it. A local merge into `main` looks like it worked and is invisible to everyone else: the work is on nobody's remote, no PR ran the gate over it, and it is one `git fetch origin +main:main` away from vanishing from the branch you are sitting on. That has already happened here \u2014 a tag-filter feature and a scrubber-URL feature lived only in one machine's local `main` for a day, and disappeared the moment somebody synced main with the remote. If you find yourself with commits on local `main`, move them onto a branch and open a PR before doing anything else.\n- **Always rebase onto the target, never merge into it.** Rebase the branch onto the target first, then integrate with a rebase merge \u2014 `gh pr merge --rebase`, never `--merge`. Main stays a flat sequence of ref-prefixed commits, which is what the commit\u2194ticket linking reads. A merge commit adds a subject carrying no ref and buries the branch's commits behind it.\n- **Squashing the branch down first is fine \u2014 one commit per ticket ref.** A branch's worth of fixups is history nobody needs on main, so collapsing it into a single commit (`git rebase -i`, or `gh pr merge --squash` with a ref-prefixed subject) is welcome, provided every commit that lands still opens with its ticket's ref. What the linking cannot survive is a squash *across* refs: fold two tickets' commits into one subject and one of them loses its commits for good. So a branch carrying two refs squashes to two commits, not one \u2014 and check the resulting subject before integrating, because `--squash` defaults to the PR title, which is only right if the title carries the ref.\n- **The git user is the sole author of every commit you write.** Commit under the repo's configured `user.name` / `user.email` and nothing else: no `Co-Authored-By:` line, no `Claude-Session:` line, no `\u{1F916} Generated with` footer, and never an `--author` override naming Claude or a tool. The commit body ends with the last line of prose. This holds for amends and rebases too \u2014 check `git log --format='%an <%ae>%n%b'` over the branch before pushing, because a trailer added by a default template survives a rebase and reaches main unnoticed. It does **not** license rewriting anyone else's authorship: commits by other contributors keep their author, and reassigning them would both misattribute their work and mean force-pushing main.\n- **Tag tickets properly.** Reuse existing tags where they fit (check current issues/tags first) instead of inventing near-duplicates.\n- **Read the ticket's comments before starting, not just its description.** The description is what was known when the ticket was written; comments carry later context \u2014 narrowed scope, a decision already taken, a dead end someone hit, a correction to the original diagnosis. Working from the description alone risks redoing settled work or implementing something that was already ruled out.\n- **Use comments to communicate deviations.** If the work diverges from what the ticket describes \u2014 scope changes, findings, blockers, test results \u2014 record it as a comment on the ticket, not just in chat.\n- When a ticket is done, **Document the outcome in a comment starting with `Solution:`.** Use that exact prefix as the comment's opening line, so `^Solution:` finds every resolved ticket on the board. Say what actually resolved it \u2014 the commit, the approach taken, and anything a reader would otherwise have to reverse-engineer from the diff; a bare commit hash is not a solution. Use the same prefix when a ticket is closed _without_ a code change, and say why.\n- **Attach a screenshot only when a picture carries what words cannot** \u2014 a layout that has to be seen, a rendering bug, a chart whose shape is the point. It is the special case, not a routine part of a `Solution:` comment: most outcomes are better described than photographed, and a screenshot of something a sentence already covers costs everyone the bytes below. When one does earn its place, use `epiq_issue_attachment_add` (it takes a file path) and paste the `markdown` it returns into the comment.\n- **Crop and compress it first.** `epiq_issue_attachment_add` stores the file exactly as it finds it \u2014 only the GUI compresses on upload \u2014 so a raw full-screen capture goes in at full size, up to the 500 KB cap. The blob lands in `.epiq/media/` on the state branch, replicates to every clone, and is never removed: deleting an attachment writes a tombstone and the bytes stay, so time travel can still resolve them. Crop to the region that makes the point, scale it down, and land well under the cap rather than against it. An oversized image is permanent, for everybody \u2014 the same reason the text limits exist.\n- **Be concise.** Titles, descriptions, and comments should be scannable, not essays.\n- If a ticket is blocked, **record the blocker in a comment** and move it to Blocked (or tag it blocked if there is no Blocked column).\n- If a you decide to take a new approach, make sure to document the fork in a new comment, and tag the ticket with a \"fork\" tag, **update the description** to reflect the new plan. Don't leave it as-is and expect readers to infer the change from comments.\n- **Park decisions that are the user's to make.** A design fork, a change with blast radius beyond its ticket, anything you'd want a second opinion on \u2014 file a ticket tagged `human-input-needed` naming the options and the trade-off, then carry on with whatever doesn't depend on the answer. Settling it alone in chat, while nobody is reading, is a decision the user never made.\n- **Findings from a code review get their own tickets**, tagged `from-review`, with the description saying which branch or PR the review covered \u2014 so the provenance survives even if the tag doesn't.\n"});import fl from"node:fs";import Dx from"node:path";var Ox,Fx=g(()=>{"use strict";rt();w();Px();Ox=async(e={})=>{let t=await kt(e.repoRoot??process.cwd());if(a(t))return l(t.message);let n=Dx.join(t.value,Xr);if(fl.existsSync(n)){if(fl.readFileSync(n,"utf8")===Ju)return d("Skill already installed and up to date",{path:n,written:!1});if(!e.force)return l(`${Xr} already exists and differs from the bundled skill. Pass force:true to overwrite it.`)}try{fl.mkdirSync(Dx.dirname(n),{recursive:!0}),fl.writeFileSync(n,Ju,"utf8")}catch(o){return l(o instanceof Error?`Failed to write ${Xr}: ${o.message}`:`Failed to write ${Xr}`)}return d(`Installed skill at ${Xr}`,{path:n,written:!0})}});var Bx={};Zr(Bx,{createMcpServer:()=>_x,resultJson:()=>Qu,startMcpServer:()=>cA});import{McpServer as aA}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as lA}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as y}from"zod";var Qu,re,_x,cA,$x=g(()=>{"use strict";w();$n();Qb();qu();nx();Lx();Fx();ci();Qu=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),re=e=>t=>Fb(async()=>Qu(await e(t))),_x=()=>{let e=new aA({name:"epiq",version:"0.2.30"});return e.registerTool("epiq_state_get",{description:"Get the full current Epiq state, including nodes and event log",inputSchema:y.object({repoRoot:y.string().optional()})},re(lu)),e.registerTool("epiq_issue_list",{description:"List Epiq issues. Narrow with boardId, swimlaneId, tag, assignee or query (matched against title and description), and pass brief to get id, ref, title, swimlane, tag names and assignee names only \u2014 descriptions are the bulk of a board. Read one ticket with epiq_issue_get.",inputSchema:y.object({repoRoot:y.string().optional(),includeClosed:y.boolean().optional(),boardId:y.string().optional(),swimlaneId:y.string().optional(),tag:y.string().optional(),assignee:y.string().optional(),query:y.string().optional(),brief:y.boolean().optional()})},re(mu)),e.registerTool("epiq_issue_get",{description:"Get one Epiq issue by its full id or its 7-character ref, with its comments in log order. Use this rather than listing the whole board when you already know which issue you want, and rather than epiq_state_get to read a thread.",inputSchema:y.object({idOrRef:y.string().min(1),repoRoot:y.string().optional()})},re(uu)),e.registerTool("epiq_issue_stats",{description:"Code stats for one issue, derived from the commits whose subject carries its ref: how big the change is, how it is spread, and how much of it the ticket spent rewriting its own work. Reads git only \u2014 it never touches the board \u2014 so it is safe to call while other work is in flight. No commits carrying the ref reads as a change of zero size, which is not the same as no work: a commit only links if its subject opens with the ref.",inputSchema:y.object({idOrRef:y.string().min(1),repoRoot:y.string().optional()})},async t=>Qu(await Mx(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:y.object({repoRoot:y.string().optional()})},re(bu)),e.registerTool("epiq_board_create",{description:"Create an Epiq board. It comes out without swimlanes; add them with epiq_swimlane_create. Refused while time travelling.",inputSchema:y.object({repoRoot:y.string().optional(),title:y.string().min(1).max(300)})},re(xu)),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:y.object({repoRoot:y.string().optional(),boardId:y.string().optional()})},re(Eu)),e.registerTool("epiq_swimlane_create",{description:"Create an Epiq swimlane on a board",inputSchema:y.object({repoRoot:y.string().optional(),boardId:y.string().min(1),title:y.string().min(1).max(300)})},re(Ru)),e.registerTool("epiq_swimlane_title_edit",{description:"Edit an Epiq swimlane title",inputSchema:y.object({repoRoot:y.string().optional(),swimlaneId:y.string().min(1),title:y.string().min(1).max(300)})},re(Su)),e.registerTool("epiq_board_title_edit",{description:"Edit an Epiq board title. Refused while time travelling.",inputSchema:y.object({repoRoot:y.string().optional(),boardId:y.string().min(1),title:y.string().min(1).max(300)})},re(Iu)),e.registerTool("epiq_swimlane_move",{description:"Move/reorder an Epiq swimlane, optionally to another board",inputSchema:y.object({repoRoot:y.string().optional(),swimlaneId:y.string().min(1),boardId:y.string().min(1),position:y.discriminatedUnion("at",[y.object({at:y.literal("start")}),y.object({at:y.literal("end")}),y.object({at:y.literal("before"),sibling:y.string().min(1)}),y.object({at:y.literal("after"),sibling:y.string().min(1)})]).optional()})},re(Nu)),e.registerTool("epiq_swimlane_delete",{description:"Delete (archive) an Epiq swimlane. This also archives every issue contained in it.",inputSchema:y.object({repoRoot:y.string().optional(),swimlaneId:y.string().min(1)})},re(wu)),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue in a swimlane: parentId is the swimlane id (epiq_swimlane_list), never a board id. Optionally set description, tags, and assignees atomically in the same call instead of separate follow-up edits.",inputSchema:y.object({title:y.string().min(1).max(300),parentId:y.string().min(1),repoRoot:y.string().optional(),description:y.string().max(2e4).optional(),tagNames:y.array(y.string().max(60)).max(20).optional(),assigneeNames:y.array(y.string().max(80)).max(20).optional()})},re(pu)),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),description:y.string().max(2e4),repoRoot:y.string().optional()})},re(vu)),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),title:y.string().min(1).max(300),repoRoot:y.string().optional()})},re(yu)),e.registerTool("epiq_issue_tag_add",{description:"Add a tag to an Epiq issue, or to many at once with issueIds, creating the tag if it does not exist",inputSchema:y.object({issueId:y.string().min(1).optional(),issueIds:y.array(y.string().min(1)).min(1).max(200).optional(),tagName:y.string().min(1).max(60),repoRoot:y.string().optional()})},re(Cu)),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),tagId:y.string().min(1),repoRoot:y.string().optional()})},re(ku)),e.registerTool("epiq_contributor_list",{description:"List people who can be assigned: everyone who has authored an event (optionally scoped to one board) unioned with the contributor registry. Use these ids with epiq_issue_assignee_add rather than assigning by name.",inputSchema:y.object({boardId:y.string().min(1).optional(),repoRoot:y.string().optional()})},re(Ou)),e.registerTool("epiq_contributor_remove",{description:"Remove an external contributor from the assignee suggestion lists. Their id and every reference to it survive, so existing assignments stay intact and the event log is untouched. Refused for anyone who has authored events, since their name is in the log regardless.",inputSchema:y.object({contributorId:y.string().min(1),repoRoot:y.string().optional()})},re(Pu)),e.registerTool("epiq_tag_remove",{description:"Delete a tag from the whole workspace. It disappears from every ticket, picker and filter, but its id and history stay in the event log, and the name is free for a new tag.",inputSchema:y.object({tagId:y.string().min(1),repoRoot:y.string().optional()})},re(Au)),e.registerTool("epiq_tag_restore",{description:"Put back a tag deleted with epiq_tag_remove, on every ticket that still carried it.",inputSchema:y.object({tagId:y.string().min(1),repoRoot:y.string().optional()})},re(Tu)),e.registerTool("epiq_contributor_restore",{description:"Put a contributor removed with epiq_contributor_remove back into the suggestion lists, under the name they were created with.",inputSchema:y.object({contributorId:y.string().min(1),repoRoot:y.string().optional()})},re(Du)),e.registerTool("epiq_issue_assignee_add",{description:"Assign a contributor to an Epiq issue. Pass self:true to assign yourself. Prefer assigneeId otherwise, which assigns a known contributor (from the registry or the event log) and fails if the id is unknown. assigneeName matches an existing contributor by name; to create somebody new from a name you must also pass createUnlinked, which adds them as an external (non-contributor) assignee.",inputSchema:y.object({issueId:y.string().min(1),assigneeId:y.string().min(1).optional(),self:y.boolean().optional(),assigneeName:y.string().min(1).max(80).optional(),createUnlinked:y.boolean().optional(),repoRoot:y.string().optional()})},re(Lu)),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),assigneeId:y.string().min(1),repoRoot:y.string().optional()})},re(Fu)),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),body:y.string().min(1).max(4e3),repoRoot:y.string().optional()})},re(_u)),e.registerTool("epiq_issue_attachment_add",{description:"Attach an image file to an Epiq issue. Returns `markdown` \u2014 paste it into a comment or description body to render the image inline.",inputSchema:y.object({issueId:y.string().min(1),filePath:y.string().min(1),name:y.string().min(1).max(200).optional(),repoRoot:y.string().optional()})},re(iu)),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:y.object({commentId:y.string().min(1),repoRoot:y.string().optional()})},re(Bu)),e.registerTool("epiq_issue_comment_edit",{description:"Replace the body of one of your own comments on an Epiq issue",inputSchema:y.object({commentId:y.string().min(1),body:y.string().min(1).max(4e3),repoRoot:y.string().optional()})},re($u)),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:y.object({issueId:y.string().min(1),repoRoot:y.string().optional()})},re(gu)),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue, or many at once with issueIds \u2014 one call, an outcome per ticket",inputSchema:y.object({issueId:y.string().min(1).optional(),issueIds:y.array(y.string().min(1)).min(1).max(200).optional(),repoRoot:y.string().optional()})},re(fu)),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane (parentId is the swimlane id), or many at once with issueIds \u2014 one call, an outcome per ticket",inputSchema:y.object({issueId:y.string().min(1).optional(),issueIds:y.array(y.string().min(1)).min(1).max(200).optional(),parentId:y.string().min(1),position:y.discriminatedUnion("at",[y.object({at:y.literal("start")}),y.object({at:y.literal("end")}),y.object({at:y.literal("before"),sibling:y.string().min(1)}),y.object({at:y.literal("after"),sibling:y.string().min(1)})]).optional(),repoRoot:y.string().optional()})},re(hu)),e.registerTool("epiq_actor_assume",{description:'Take a board identity for the rest of this session, so your writes are attributed to you rather than to the user. Pass the name you announced \u2014 the model provider, a slash, then a short human first name, e.g. "claude/peter". Takes effect on the very next write; no relaunch. A name the server was launched with wins, and re-assuming the same name is harmless. Reuse an existing agent identity (epiq_contributor_list) before inventing one: a name is permanent once it has authored anything.',inputSchema:y.object({name:y.string().min(1).max(80),repoRoot:y.string().optional()})},re(Mu)),e.registerTool("epiq_contributor_email_link",{description:"Bind a git author address to a contributor, so their commits and their board activity read as one person. Defaults to you; pass contributorId to link a colleague who does not use epiq, whose commits otherwise never resolve. The address the repository's git is configured with links itself on your first write, so this is for older addresses and for other people. An address two contributors claim resolves to neither, and the reply says so.",inputSchema:y.object({email:y.string().min(1).max(254),contributorId:y.string().min(1).optional(),repoRoot:y.string().optional()})},re(ju)),e.registerTool("epiq_contributor_email_unlink",{description:"Retract a link between a git address and a contributor. Allowed only to whoever wrote the link and to the contributor it names, so nobody can strip links that are neither theirs nor about them. Forward-only: the address stops resolving and the event stays in the log.",inputSchema:y.object({email:y.string().min(1).max(254),contributorId:y.string().min(1).optional(),repoRoot:y.string().optional()})},re(Uu)),e.registerTool("epiq_contributor_email_suggest",{description:"Addresses in this repository's history that look like yours and nobody has claimed, for the user to confirm. Run it once after this feature reaches a board with history: the address git is configured with links itself, but older ones do not, and until they are linked those commits show a raw git name. Show the list and link only what the user confirms \u2014 each link is permanent and replicates to every clone.",inputSchema:y.object({repoRoot:y.string().optional()})},re(Wu)),e.registerTool("epiq_contributor_email_list",{description:"Every git address the board has bound to a contributor, and who holds it. An address with more than one claimant is flagged contested and resolves to none of them, which is the state nothing else reports.",inputSchema:y.object({repoRoot:y.string().optional()})},re(Hu)),e.registerTool("epiq_project_init",{description:`Set up a new Epiq board in a git repository without the TUI. Runs in the repository at repoRoot (default: the current directory), which must have no uncommitted changes. The first time on a machine it also records the user's setup: ask the user for userName (how they want to appear on the board), preferredEditor (e.g. "vim" or "code --wait") and autoSync (whether the TUI and GUI sync with the remote on their own) and pass them here; called without them it fails naming what is still missing, keeping whatever was given. It fills in answers the machine lacks and refuses to change ones it has. Pass the user's name, never your own agent identity. Commits the state branch and .epiq/project.json and tries to push both; a push that fails is a warning, not an error. Afterwards the other tools work in that repository.`,inputSchema:y.object({repoRoot:y.string().optional(),userName:y.string().min(1).max(80).optional(),preferredEditor:y.string().min(1).max(200).optional(),autoSync:y.boolean().optional()})},re(tx)),e.registerTool("epiq_skill_install",{description:"Write the official Epiq workflow skill into the repository at .claude/skills/epiq/SKILL.md, so agents working there follow the same board rules. Run it after epiq_project_init, not before: the new file is an uncommitted change that init refuses. In a project that already has a board, run it any time. Refuses to overwrite a differing file unless force is true; an identical file is left alone.",inputSchema:y.object({repoRoot:y.string().optional(),force:y.boolean().optional()})},re(Ox)),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote (pull remote changes and push local ones). Other Epiq MCP tools only read and write local state and never sync automatically \u2014 call this on demand when you need to see or publish the latest remote changes.",inputSchema:y.object({repoRoot:y.string().optional()})},re(cu)),e},cA=async()=>{let e=_x(),t=new lA;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:dA}=await Promise.resolve().then(()=>(vo(),sm)),{isFail:uA}=await Promise.resolve().then(()=>(w(),nm)),{parseMcpArgs:mA}=await Promise.resolve().then(()=>(lm(),am)),Jr=mA(process.argv.slice(2));Jr.kind==="error"&&(console.error(Jr.message),process.exit(1));Jr.kind==="print"&&(process.stdout.write(Jr.text),process.exit(0));if(Jr.kind==="name"){let e=dA(Jr.name,"The name argument");uA(e)&&(console.error(e.message),process.exit(1))}var{setVirtualNodesEnabled:pA}=await Promise.resolve().then(()=>(ic(),Lb));pA(!1);var{startMcpServer:fA}=await Promise.resolve().then(()=>($x(),Bx));await fA();
|