epiq 0.3.5 → 0.3.6

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/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{render as Ic}from"ink";import Sc from"meow";import Tc from"react";import vc from"chalk";import{Box as fe,Text as _e}from"ink";import O from"react";import at from"chalk";import{monotonicFactory as yd,ulid as Te}from"ulid";import{useSyncExternalStore as pd}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function ye(e){return e.context==="TICKET"}var Ur=e=>e.context==="SWIMLANE";var p={INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",RENAME:"rename",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",SET_DESCRIPTION:"edit",SET_EDITOR:"config:editor",SET_VIEW:"config:view",SET_USERNAME:"config:username",SYNC:"sync",NONE:""},Ne={None:"none",Invalid:"invalid",Valid:"valid"},xe={None:"none",Success:"success",Fail:"fail"},s=e=>({result:xe.Fail,message:e,data:null}),u=(e,t)=>({result:xe.Success,message:e,data:t}),Wr=()=>({result:xe.None,message:"No result",data:null}),c=e=>e.result==="fail",Fe=e=>e.result==="success";var f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function Pt(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Dt=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Dn=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var Hr=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),i=t.get(o);i?i.push(n):t.set(o,[n])}return t},$r=(e,t)=>t?e.get(t)??[]:[];var _r=new WeakMap,us=e=>{let t=_r.get(e);return t||(t=Hr(e),_r.set(e,t)),t};var Kr=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return $r(us(e),r).filter(i=>Pt(r,i)>=n)};var Vr=({inputToMatch:e,lastWord:t},n)=>{if(t.endsWith(" "))return{hint:"",hints:[],overlap:0,remainder:""};let r=Kr({wordList:n,inputToMatch:e,overlapThreshold:1});return ms(t,r)},ms=(e,t)=>{let n=t[0]??"",r=Pt(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),a=r<(o??"").length,d=!!i,g=(d&&a?o:n)+(d&&a?":":" "),y=g.slice(r);return{hint:g,hints:t,overlap:r,remainder:y}};var jr=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var qe=24n,ps=qe*4n,Ft=(1n<<ps)-1n,gs=/^[0-9a-f]+$/;function zr(e){if(!e||!gs.test(e))throw new Error(`Invalid hex rank: ${e}`);return BigInt("0x"+e)}function kt(e,t=qe){if(e<0n)throw new Error("Negative rank not allowed");return e.toString(16).padStart(Number(t),"0")}function mt(e,t){if(!e&&!t)return kt(Ft/2n,qe);let n=e?zr(e):0n,r=t?zr(t):Ft;if(r<=n)return kt(Ft/2n,qe);let o=(n+r)/2n;return o===n||o===r?"":kt(o,qe)}function me(){return kt(Ft/2n,qe)}var ne={workspace:(e,t)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r=!1)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:(e,t,n,r={},o="horizontal")=>({id:e,title:t,rank:me(),isDeleted:!1,props:r,context:P.FIELD,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[]}),ticket:(e,t,n)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,props:r={},readonly:o=!0})=>({id:e,title:t,rank:me(),isDeleted:!1,props:r,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[]})};var W=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Gr=(e,t)=>e.findIndex(n=>n.id===t),Fn=(e,t={at:"end"})=>{if(e.length===0)return u("Resolved rank",me());switch(t.at){case"start":{let n=e[0];return n?u("Resolved rank",mt(void 0,n.rank)):s("Unable to resolve first sibling")}case"end":{let n=e[e.length-1];return n?u("Resolved rank",mt(n.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let n=Gr(e,t.sibling);if(n<0)return s("Sibling not found");let r=n>0?e[n-1]:void 0,o=e[n];return o?u("Resolved rank",mt(r?.rank,o.rank)):s("Sibling not found")}case"after":{let n=Gr(e,t.sibling);if(n<0)return s("Sibling not found");let r=e[n],o=n<e.length-1?e[n+1]:void 0;return r?u("Resolved rank",mt(r.rank,o?.rank)):s("Sibling not found")}}};var ke=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return s("Node not found");if(r.context===t)return u("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return u("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return s(`No ancestor found for context: ${t}`)},On=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},kn=(e,t)=>e?e.readonly?s({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:s("Node not found"),C={deleteNode(e){de(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return s("Edit target node not found");let o=kn(r,"edit");if(o)return o;let i={...r,props:{...r.props,value:t}};return C.updateNode(i),u("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return s("Rename target node not found");let r=kn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),u("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return W(e).find(n=>n.title===t)},moveNode({id:e,parentId:t,position:n={at:"end"}}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let a=kn(o,"move");if(a)return a;if(On(t,e))return s("Cannot move node into its own descendant");let d=W(t).filter(g=>g.id!==e),l=Fn(d,n);if(c(l))return l;let m={...o,parentNodeId:t,rank:l.data};return this.updateNode(m),u("Moved node successfully",m)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,a=l=>{let m=t[l];if(!(!m||i.has(l))){i.add(l);for(let g of W(m.id))a(g.id)}};a(e);let d={...structuredClone(t)};for(let l of i){if(!d[l])return s("Unable to locate node to delete");d[l]={...d[l],isDeleted:!0}}return n?(A({nodes:d}),u("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=de(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return c(t)?s("Unable to create contributor"):u("Created contributor",e)},assign(e,t,n){let r=C.getContributor(t),o=C.getNode(e);if(!o||!r)return s("Unable assign contributor to issue");let i=this.getFieldByTitle(o.id,"Assignees");if(!i)return s("Unable to locate assignees field");if(W(i.id).some(l=>l.props?.value===t))return s("Contributor already assigned");let d=this.createNodeAtPosition(ne.field(n,r.name,i.id,{value:t}));return c(d)?d:u("Assigned contributor",d.data)},createTag(e){let t=de(n=>({...n,tags:{...n.tags,[e.id]:e}}));return c(t)?s("Could not create tag"):u("Tag created",e)},tag(e,t,n){let r=C.getTag(t),o=C.getNode(e);if(!r)return s("Unable to add tag, missing tag");if(!o)return s("Unable to add tag, missing target");let i=this.getFieldByTitle(o.id,"Tags");if(!i)return s("Unable to locate tags field");if(W(i.id).some(l=>l.props?.value===t))return s("Tag already assigned");let d=this.createNodeAtPosition(ne.field(n,r.name,i.id,{value:t}));return c(d)?d:u("Tag added",d.data)},untag(e,t){let n=C.getTag(t),r=C.getNode(e);if(!n)return s("Unable to remove tag, missing tag");if(!r)return s("Unable to remove tag, missing target");let o=this.getFieldByTitle(r.id,"Tags");if(!o)return s("Unable to locate tags field");let i=W(o.id).find(d=>d.props?.value===t);if(!i)return u("Issue is not tagged with that tag",null);let a={...i,isDeleted:!0};return this.updateNode(a),u("Tag removed",a)},unassign(e,t){let n=C.getContributor(t),r=C.getNode(e);if(!n)return s("Unable to unassign, missing contributor");if(!r)return s("Unable to unassign, missing target");let o=this.getFieldByTitle(r.id,"Assignees");if(!o)return s("Unable to locate assignees field");let i=W(o.id).find(d=>d.props?.value===t);if(!i)return u("Issue is not assigned to that contributor",null);let a={...i,isDeleted:!0};return this.updateNode(a),u("Assignee removed",a)},createNodeAtPosition(e,t={at:"end"}){if(!e.parentNodeId){let i={...e,rank:me()};return this.createNode(i),u("Created node",i)}let n=W(e.parentNodeId),r=Fn(n,t);if(c(r))return r;let o={...e,rank:r.data};return this.createNode(o),u("Created node",o)},createNode(e){let t=de(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return c(t)?s("Unable to create node"):u("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let n={...t,readonly:!0},r=de(o=>({...o,nodes:{...o.nodes,[e]:n}}));return c(r)?s(r.message):u("Locked node",n)},updateNode(e){let t=de(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return c(t)?t:u("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings:e=>Object.values(v().nodes).filter(t=>!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank))};var Ot={autoSync:!1,preferredEditor:null,userName:null,userId:null},pe=()=>Ot,Ye=e=>(Ot={...Ot,...e},Ot);var Bt=()=>{let e=pe(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},qr=()=>!Ke();var q={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#2a2f45",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},E={accent:q.cyan,accent2:q.magenta,primary:q.white,secondary:q.grayDark,secondary2:q.grayLight,gray:q.gray,green:q.green,yellow:q.yellow,red:q.red};var h={red:q.red,yellow:q.yellow,green:q.green,blue:q.blue,magenta:q.magenta,cyan:q.cyan},Je={urgent:h.red,critical:h.red,important:h.red,blocker:h.red,asap:h.red,immediate:h.red,fail:h.red,failure:h.red,broken:h.red,bug:h.red,error:h.red,incident:h.red,outage:h.red,production:h.red,crash:h.red,security:h.red,warning:h.yellow,warn:h.yellow,risky:h.yellow,risk:h.yellow,attention:h.yellow,pending:h.yellow,review:h.yellow,"needs-review":h.yellow,qa:h.yellow,testing:h.yellow,test:h.yellow,validate:h.yellow,verification:h.yellow,staging:h.yellow,check:h.yellow,"follow-up":h.yellow,followup:h.yellow,waiting:h.yellow,blocked:h.yellow,hold:h.yellow,done:h.green,complete:h.green,completed:h.green,success:h.green,ok:h.green,stable:h.green,resolved:h.green,fixed:h.green,closed:h.green,merged:h.green,released:h.green,deployed:h.green,approved:h.green,verified:h.green,working:h.green,healthy:h.green,pass:h.green,passing:h.green,info:h.blue,information:h.blue,note:h.blue,docs:h.blue,documentation:h.blue,doc:h.blue,guide:h.blue,help:h.blue,explanation:h.blue,detail:h.blue,details:h.blue,context:h.blue,design:h.blue,discussion:h.blue,proposal:h.blue,idea:h.blue,feature:h.magenta,enhancement:h.magenta,improvement:h.magenta,refactor:h.magenta,refactoring:h.magenta,cleanup:h.magenta,optimize:h.magenta,optimization:h.magenta,perf:h.magenta,performance:h.magenta,upgrade:h.magenta,migration:h.magenta,modernize:h.magenta,debt:h.magenta,todo:h.cyan,next:h.cyan,planned:h.cyan,plan:h.cyan,future:h.cyan,backlog:h.cyan,investigate:h.cyan,explore:h.cyan,prototype:h.cyan};var Yr=(e,t)=>{let r=M(e.id).find(o=>o.title===t);return r?M(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},Bn=e=>Yr(e,"Tags").map(t=>C.getTag(t)).filter(t=>!!t),Ut=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ye(n)?s("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",Bn(n)??[])},Wt=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ye(n)?s("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",Un(n)??[])},Un=e=>Yr(e,"Assignees").map(t=>C.getContributor(t)).filter(t=>!!t);var fs=/^(\d+)(h|d|w|mo|y)$/,ys=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,xs=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let i=new Date(e,t-1,n,r,o);return i.getFullYear()===e&&i.getMonth()===t-1&&i.getDate()===n&&i.getHours()===r&&i.getMinutes()===o},vs=(e,t=new Date)=>{let n=e.match(fs);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let a=new Date(t);switch(o){case"h":return a.setHours(a.getHours()-i),a;case"d":return a.setDate(a.getDate()-i),a;case"w":return a.setDate(a.getDate()-i*7),a;case"mo":return a.setMonth(a.getMonth()-i),a;case"y":return a.setFullYear(a.getFullYear()-i),a;default:return null}},hs=e=>{let t=e.match(ys);if(!t)return null;let[,n,r,o,i,a]=t,d=Number(n),l=Number(r),m=Number(o),g=i?Number(i):0,y=a?Number(a):0;return xs({year:d,month:l,day:m,hour:g,minute:y})?new Date(d,l-1,m,g,y):null},Ht=e=>{let t=e.trim().toLowerCase();return vs(t)??hs(t)},Jr=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Es=[{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}],Xr=(e=Es)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let i=r;i<=o;i++)t.push(`${i}${n}`);return t};var Cs=["BOARD","TICKET","SWIMLANE"],z=e=>{let{currentNode:t,readOnly:n,selectedNode:r}=v(),o=Bt().isSetup,i=t.context,a=r?.context,d=[p.SYNC,p.HELP,p.SET_VIEW,p.SET_EDITOR,p.SET_USERNAME],l=[p.NEW,p.RENAME,p.DELETE],m=[p.TAG,p.UNTAG,p.ASSIGN,p.UNASSIGN,p.CLOSE_ISSUE,p.RE_OPEN_ISSUE,p.SET_DESCRIPTION],g=[p.FILTER,p.PEEK],y={WORKSPACE:[...d,...l],BOARD:[...g,...d,...l],SWIMLANE:[...g,...d,...l],TICKET:[...d,...l,...m],FIELD:[...d,...m],FIELD_LIST:[...d,...m],TEXT:[...d]},N=a&&Cs.includes(a),b=[...y[i||"WORKSPACE"]].filter(T=>[p.RENAME,p.DELETE,p.MOVE].includes(T)?N:!0),I={[p.PEEK]:[...Xr(),"now","prev","next"],[p.SYNC]:[],[p.INIT]:[],[p.SET_USERNAME]:[],[p.SET_DESCRIPTION]:["confirm"],[p.DELETE]:["confirm"],[p.RE_OPEN_ISSUE]:["confirm"],[p.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[p.CLOSE_ISSUE]:["confirm"],[p.FILTER]:["tag","assignee","description","title","clear"],[p.SET_VIEW]:["dense","wide"],[p.SET_EDITOR]:[...jr,"vim"],[p.TAG]:[...new Set([...Object.keys(Je),...C.getExistingTags()])],[p.UNTAG]:[...Ut()?.data?.map(({name:T})=>T)??[]],[p.UNASSIGN]:[...Wt()?.data?.map(({name:T})=>T)??[]],[p.ASSIGN]:C.getExistingAssignees(),[p.HELP]:[],[p.RENAME]:[],[p.NEW]:i==="TICKET"||i==="FIELD"||i==="FIELD_LIST"?["issue","swimlane","board"]:i==="SWIMLANE"?["issue","swimlane","board"]:i==="BOARD"?["issue","swimlane","board"]:["board"],[p.NONE]:b};return o?qr()?n&&(I={[p.NONE]:[p.HELP,p.PEEK],[p.HELP]:I[p.HELP],[p.PEEK]:I[p.PEEK]}):I={[p.NONE]:[p.HELP,p.INIT],[p.HELP]:I[p.HELP],[p.INIT]:I[p.INIT]}:I={[p.NONE]:[p.HELP,p.SET_EDITOR,p.SET_USERNAME],[p.HELP]:I[p.HELP],[p.SET_EDITOR]:I[p.SET_EDITOR],[p.SET_USERNAME]:I[p.SET_USERNAME]},I[e]??[]};import Qe from"chalk";import{decodeTime as Qr}from"ulid";var Zr=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 i=Math.floor(t/o);if(i>=1)return`${i}${r} ago`}return"just now"},eo=e=>{let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},$t=e=>{try{return u("Decoded date",new Date(Qr(e)))}catch(t){return s("Decoding failed + "+t.message)}},Wn=e=>{if(!e?.id)return null;try{return Qr(e.id)}catch{return null}};var be=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?u("Found node",n):s("Unable to find node in breadcrumb")};import Xe from"chalk";var $n={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Ns=(e,t,n)=>Math.max(t,Math.min(n,e)),Hn=(e,t,n)=>e+(t-e)*n,to=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},bs=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,a=e/60,d=i*(1-Math.abs(a%2-1)),l=0,m=0,g=0;a>=0&&a<1?(l=i,m=d):a>=1&&a<2?(l=d,m=i):a>=2&&a<3?(m=i,g=d):a>=3&&a<4?(m=d,g=i):a>=4&&a<5?(l=d,g=i):(l=i,g=d);let y=o-i/2;return[Math.round((l+y)*255),Math.round((m+y)*255),Math.round((g+y)*255)]},Is=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Ss=(e,t,n)=>[Math.round(Hn(e[0],t[0],n)),Math.round(Hn(e[1],t[1],n)),Math.round(Hn(e[2],t[2],n))],pt=e=>{let n=to(e)%360,r=bs(n,$n.stringColor.saturation,$n.stringColor.lightness);return Is(r)},Ts=e=>{let t=$n.gradient.stops,n=Ns(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,i=Math.min(Math.floor(o),r-1),a=o-i;return Ss(t[i],t[i+1],a)},_t=e=>to(e.toLowerCase().trim())/4294967295,no=e=>{let t=_t(e);return Ts(t)},As=e=>{let[t,n,r]=no(e);return{normal:o=>Xe.bgRgb(t,n,r).black(o),cursor:o=>Xe.bgRgb(t,n,r).white.bold(o)}},_n=e=>{let[t,n,r]=no(e);return{fg:o=>Xe.rgb(t,n,r)(o),fgCursor:o=>Xe.rgb(t,n,r).inverse(o),bg:o=>Xe.bgRgb(t,n,r).black(o),bgCursor:o=>Xe.bgRgb(t,n,r).white.bold(o)}},Kn=e=>As(e).normal(` ${e} `),Y=(e,t=Je)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:pt(r)};var ws=["BOARD","TICKET","SWIMLANE"],Vn=()=>{let e=v().selectedNode;return e?.context?ws.includes(e?.context)?V():H({message:"Command not available in this context"}):H({message:"Missing target context"})},ce="<ENTER> to confirm",V=(e="",t=[])=>({message:e,validity:Ne.Valid,completionWordList:t}),H=({message:e,completionWordList:t=[]})=>({validity:Ne.Invalid,message:e,completionWordList:t}),ft=e=>e.length===0,Oe=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let l=[...t.filter(Boolean).filter(g=>g.startsWith(o.trim()))].sort((g,y)=>_t(g)-_t(y)).slice(0,r).map(Kn),m=l.length>i?l.join(" "):"";return m?`${e}${m}${n}`:""},jn=({modifier:e})=>{let t="confirm";return e===t?V(ce):H({message:ft(e)?`if you are certain, enter ${Kn(t)}`:"",completionWordList:[t]})},Rs=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?V(ce):H({message:ft(n)?t:""}),Ms=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?H({message:n}):V():H({message:ft(r)?t:""}),gt=({hint:e})=>({modifier:t,inputString:n})=>ft(t)&&ft(n)?H({message:e,completionWordList:[]}):V(ce),Ls={[p.PEEK]:e=>{let t=e.modifier;if(t==="now")return V(ce);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return V(ce);let r=Ht(t);if(!t||!r)return H(n);let o=be(v().breadCrumb,"BOARD");if(c(o))return H({message:"Command is not applicable in this context"});let i=$t(o.data.id);return c(i)?H({message:"Unable to peek: board id is not a valid ULID"}):Jr({date:r,horizonDate:i.data})?V(ce):H({message:Qe.red(`nothing to peek before ${i.data.toISOString().slice(0,16).replace("T"," ")}`)})},[p.INIT]:()=>V(ce),[p.FILTER]:e=>{if(e.modifier==="clear")return V();let t=a=>z(p.FILTER).includes(a);if(!e.modifier||!t(e.modifier??""))return H({message:Oe({wordList:z(p.FILTER),inputString:e.inputString}),completionWordList:z(p.FILTER)});let r=Object.values(v().tags).map(a=>a.name),o=Object.values(v().contributors).map(a=>a.name),i=e.modifier==="tag"?r:e.modifier==="assignee"?o:[];return e.inputString?i.length&&!i.includes(e.inputString.trim()??"")?H({message:Oe({prefix:`existing ${e.modifier}s... `,wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i}):V():H({message:Oe({prefix:"one of... ",wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i})},[p.NONE]:e=>{let t=z(p.NONE),n=/^[A-Za-z_]+:/g,r=e.inputString.match(n);return r&&r.length?t=[...t.filter(o=>o.trim().match(n))]:t=[...new Set(t.flatMap(o=>o.match(n)?.join("").replace(":","")??o))],e.command?V():H({message:Oe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[p.NEW]:e=>Ms({list:z(p.NEW),hint:Oe({wordList:z(p.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[p.SET_DESCRIPTION]:()=>V(ce),[p.HELP]:()=>V(ce),[p.RENAME]:()=>{let e=Vn();return e.validity==="invalid"?e:V(ce)},[p.DELETE]:e=>{let t=Vn();return t.validity==="invalid"?t:jn(e)},[p.CLOSE_ISSUE]:e=>jn(e),[p.RE_OPEN_ISSUE]:e=>jn(e),[p.MOVE]:e=>{let t=Vn();return t.validity==="invalid"?t:gt({hint:Oe({prefix:"hey hacker! These commands are blocked for you... ",wordList:z(p.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[p.TAG]:e=>{let t=C.getExistingTags().map(n=>` ${Qe.bgHex(Y(n))(" "+n+" ")} `).slice(0,10);return gt({hint:"tag name like... "+t.join("")})(e)},[p.UNTAG]:e=>{let t=Ut();if(c(t))return H({message:"Invalid untag target",completionWordList:[]});let n=t.data.map(({name:r})=>r).map(r=>` ${Qe.bgHex(Y(r))(" "+r+" ")} `).slice(0,10);return n.length?gt({hint:" ... "+n.join("")})(e):H({message:"Issue has not tags",completionWordList:[]})},[p.ASSIGN]:e=>{let t=C.getExistingAssignees().map(n=>` ${Qe.bgHex(Y(n))(" "+n+" ")} `).slice(0,10);return gt({hint:"assign to... "+t.join("")})(e)},[p.UNASSIGN]:e=>{let t=Wt();if(c(t))return H({message:"Invalid unassign target",completionWordList:[]});let n=t.data.map(({name:r})=>r).map(r=>` ${Qe.bgHex(Y(r))(" "+r+" ")} `).slice(0,10);return n.length?gt({hint:"remove assignee... "+n.join("")})(e):H({message:"Issue has no assignees",completionWordList:[]})},[p.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=z(p.SET_EDITOR);return e.modifier?V(ce):H({message:Oe({wordList:t,inputString:e.inputString})})},[p.SET_USERNAME]:e=>e.inputString?V():H({message:`Enter a username. Saved in ${Qe.bgBlack("~/.epiq/")}`}),[p.SET_VIEW]:e=>Rs({list:z(p.SET_VIEW),hint:Oe({wordList:z(p.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[p.SYNC]:()=>V(ce)},ro=Object.fromEntries(Object.entries(Ls).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var oo=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"];var L={Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",SetView:"set-view",SetEditor:"set-editor",SetUserName:"set-user-name",SetAutoSync:"set-auto-sync",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",Sync:"sync"};var io=e=>Object.values(p).includes(e),so=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:d,completionWordList:l}=ro[n].validate(n,r,i),m=o==="command"?Object.values(p):n&&e.target==="modifier"?z(n):oo;return{validity:d,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?Vr(e,[...l,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var ao=e=>{let t=e.trimStart(),n=Ds(t),r=(n[0]??"").trimStart().trimEnd(),o=(n[1]??"").trimStart().trimEnd(),i=Fs(e),a=io(r)?r:null,d=a!==null,l=r!=="",m=e.endsWith(" "),g=a?z(a)??[]:[],y=a&&g.includes(o)?o:"",N="word";n.length<=1?N="command":n.length===2&&(N="modifier");let b=Ps(t,a,y);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:l,command:a,isCommandKeyword:d,isLastWordCompleted:m,modifier:y,target:N,inputToMatch:i,inputString:b}},Ps=(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},Ds=e=>e?e.split(/\s+/):[],Fs=e=>e.trimEnd().split(/\s+/).at(-1)??"";var co=" ",J={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Ne.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},zn=new Set,lo=()=>{for(let e of zn)e()},uo=e=>(zn.add(e),()=>zn.delete(e)),Ie=e=>{let n=e(J),r=ao(n.value),o=n.cursorPosition===n.value.length;J={...n,commandMeta:so(r,o)},lo()},yt=({message:e,result:t})=>{let n=structuredClone(J);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,J=n,lo(),u(e,null)},Gn=e=>{Ie(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},qn=e=>{Ie(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&n[o-1]===" ";)o--;for(;o>0&&n[o-1]!==" ";)o--}else{for(;o<n.length&&n[o]!==" ";)o++;for(;o<n.length&&n[o]===" ";)o++}return{...t,cursorPosition:o}})},mo=()=>{Ie(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}})},po=()=>{Ie(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&t[r-1]===" ";)r--;for(;r>0&&t[r-1]!==" ";)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},j=e=>{Ie(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),i=e(r,t.commandMeta.autoCompletion),a=i+o,d=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:d,commandIsPending:!1}})},go=()=>{Ie(e=>({...e,commandIsPending:!0}))},fo=({addToHistory:e=!0})=>{Ie(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),ks()},yo=()=>{Ie(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}})},xo=()=>{Ie(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ks=()=>j(()=>""),re=()=>J,Kt=()=>{let[e,...t]=J.value.split(co);return t.join(co).trim()};var Os=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Bs=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",Us=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",vo=(e,t)=>{if(Bs(e,e.sequence))return x.MoveCursorLeftOfWord;if(Us(e,e.sequence))return x.MoveCursorRightOfWord;if(Os(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.GetLastCommandFromHistory;case"down":return x.GetNextCommandFromHistory;case"left":return x.MoveCursorLeft;case"right":return x.MoveCursorRight;case"return":return x.Confirm;case"backspace":return t?x.EraseInput:x.ExitCommandLine;case"escape":return x.ExitCommandLine;default:return x.CaptureInput}};var x={Sync:"sync",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",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",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function Ws(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function Hs(e,t,n){let r=v().currentNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function ho(e,t){let n=re();if(e.sequence===":"&&n.value==="")return x.InitCommandLine;if(t===f.MOVE)switch(e.name){case"m":case"return":return x.ConfirmMove}if(t===f.COMMAND_LINE)return vo(e,n.value);let r=Ws(e);if(r){let o=t===f.MOVE?{prevItem:x.MovePreviousItem,nextItem:x.MoveNextItem,prevContainer:x.MoveToPreviousContainer,nextContainer:x.MoveToNextContainer}:{prevItem:x.NavPreviousItem,nextItem:x.NavNextItem,prevContainer:x.NavToPreviousContainer,nextContainer:x.NavToNextContainer};return Hs(v().currentNode.childRenderAxis,r,o)}if(e.ctrl&&e.name==="c")return x.Exit;switch(e.name){case"e":return x.Edit;case"n":return x.AddItem;case"m":return x.InitMove;case"d":return x.Delete;case"return":return x.Confirm;case"space":return x.Confirm;case"v":return v().viewMode==="wide"?x.SetViewDense:x.SetViewWide;case"q":case"escape":return x.Exit;case"s":return x.Sync;default:return null}}var Eo=e=>{let{context:t}=v()?.currentNode;if(!t)return L.None;switch(e){case p.INIT:return L.Init;case p.DELETE:return L.Delete;case p.SET_DESCRIPTION:return L.Edit;case p.HELP:return L.ViewHelp;case p.RE_OPEN_ISSUE:return L.ReopenIssue;case p.CLOSE_ISSUE:return L.CloseIssue;case p.TAG:return L.TagTicket;case p.UNTAG:return L.UntagTicket;case p.ASSIGN:return L.AssignUserToTicket;case p.UNASSIGN:return L.UnassignUserFromTicket;case p.RENAME:return L.Rename;case p.NEW:return L.NewItem;case p.FILTER:return L.Filter;case p.MOVE:return L.Move;case p.PEEK:return L.Peek;case p.SET_USERNAME:return L.SetUserName;case p.SET_EDITOR:return L.SetEditor;case p.SET_VIEW:return L.SetView;case p.SYNC:return L.Sync;default:return L.None}};import{ulid as $}from"ulid";import{spawnSync as qs}from"node:child_process";import Ys from"node:os";import Io from"node:path";import{ulid as Js}from"ulid";import{accessSync as $s,copyFileSync as _s,existsSync as Vt,mkdirSync as Co,readdirSync as No,readFileSync as Ks,renameSync as Vs,rmSync as js,statSync as bo,unlinkSync as zs,writeFileSync as Gs}from"node:fs";import Ze from"node:path";var le={writeToFile:(e,t)=>{try{let n=Ze.dirname(e);Vt(n)||Co(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Gs(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Ks(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=le.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 Vt(e)&&bo(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await $s(e),!0}catch{return!1}},mkDir:e=>Co(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Ze.parse(t);for(;;){let r=Ze.join(t,e);try{if(Vt(r)&&bo(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Ze.dirname(t)}return null},readFirstJSON(e){try{if(!le.dirExists(e))return null;let t=No(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Ze.join(e,t);return le.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return le.dirExists(e)?No(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{zs(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{js(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Ze.dirname(t)),!n?.overwrite&&Vt(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Vs(e,t)}catch(r){if(r?.code==="EXDEV"){_s(e,t),this.rmFile(e);return}throw r}}};function Xs(){let{preferredEditor:e}=pe(),t=[e,process.env.VISUAL,process.env.EDITOR,"vim","nano"].filter(n=>!!n?.trim());return[...new Set(t)]}function Qs(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function So(e){let t=Io.join(Ys.tmpdir(),"epiq");le.mkDir(t);let n=Io.join(t,Js());le.writeToFile(n,e??"");let r=Xs();for(let o of r){let i=Qs(o,n),a=qs(i,{stdio:"inherit",shell:!0});if(!a.error&&a.status===0){let d=le.readFile(n);if(d==null)return s("Unable to read edited file");let l=d.replace(/\r?\n$/,"");return u("Successfully edited",l)}}return s("Unable to open editor")}import{monotonicFactory as Zs,ulid as jt}from"ulid";var zt=Zs(),To=({name:e,parent:t,user:{userId:n,userName:r}})=>{let o=zt(),i=zt(),a=zt(),d=zt();return[{id:jt(),userId:n,userName:r,action:"add.issue",payload:{id:o,parent:t,name:e}},{id:jt(),userId:n,userName:r,action:"add.field",payload:{id:i,parent:o,name:"Description",val:""}},{id:jt(),userId:n,userName:r,action:"add.field",payload:{id:a,parent:o,name:"Assignees"}},{id:jt(),userId:n,userName:r,action:"add.field",payload:{id:d,parent:o,name:"Tags"}}]};import Xt from"node:fs";import Qt from"node:path";import{z as Xn}from"zod";var Gt=process.env.IS_LOCAL==="true",Se=()=>".epiq";import qt from"node:fs";import Be from"node:path";import{decodeTime as ea,monotonicFactory as ta}from"ulid";import{z as xt}from"zod";import na from"node:os";var Ao=e=>({action:e.action,payload:e.payload});var ra=Be.join(na.homedir(),".epiq"),oa=e=>Be.resolve(e)===ra,ia=e=>{let t=Be.join(e,Se());return qt.existsSync(t)&&qt.statSync(t).isDirectory()&&!oa(e)},Ro=1,wo=ta(),sa="events",aa=xt.tuple([xt.string().min(1),xt.string().min(1).nullable()]),da=xt.looseObject({v:xt.literal(Ro),id:aa}),Yn=e=>{let t=da.safeParse(e);return t.success?u("Parsed persisted event",t.data):s(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Yt=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",X=()=>{let{userName:e,userId:t}=pe();return e?t?e.trim()?u("Successfully resolved actor ID",{userId:Yt(t),userName:Yt(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},et=(e=process.cwd())=>{let t=Be.resolve(e);for(;;){if(ia(t))return t;let n=Be.dirname(t);if(n===t)return Be.resolve(e);t=n}},Mo=(e=process.cwd())=>Be.join(et(e),Se(),sa),Jn=({userId:e,userName:t})=>`${Yt(e)}.${Yt(t)}.jsonl`,ca=(e=process.cwd(),{userId:t,userName:n})=>{let r=Jn({userId:t,userName:n});return/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r)?u("Successfully resolved event log path",Be.join(Mo(e),r)):s(`Invalid event log file name: ${r}`)},la=(e,t)=>{let n={[e.action]:e.payload,v:Ro,id:t};return Yn(n)};function Jt({event:e,rootDir:t=process.cwd()}){try{let n=et(t),r=Mo(n),o=ca(n,{userId:e.userId,userName:e.userName});if(c(o))return o;qt.mkdirSync(r,{recursive:!0});let i=Lo(n);if(c(i))return s(i.message);let a;if(i.data){let l=ea(i.data),m=Math.max(Date.now(),l+1);a=wo(m)}else a=wo();let d=la(Ao(e),[a,i.data]);return c(d)?s(d.message):(qt.appendFileSync(o.data,`${JSON.stringify(d.data)}
2
+ import{render as Ic}from"ink";import Sc from"meow";import Tc from"react";import vc from"chalk";import{Box as fe,Text as _e}from"ink";import O from"react";import at from"chalk";import{monotonicFactory as yd,ulid as Te}from"ulid";import{useSyncExternalStore as pd}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function ye(e){return e.context==="TICKET"}var Ur=e=>e.context==="SWIMLANE";var p={INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",RENAME:"rename",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",SET_DESCRIPTION:"edit",SET_EDITOR:"config:editor",SET_VIEW:"config:view",SET_USERNAME:"config:username",SYNC:"sync",NONE:""},Ne={None:"none",Invalid:"invalid",Valid:"valid"},xe={None:"none",Success:"success",Fail:"fail"},s=e=>({result:xe.Fail,message:e,data:null}),u=(e,t)=>({result:xe.Success,message:e,data:t}),Wr=()=>({result:xe.None,message:"No result",data:null}),c=e=>e.result==="fail",Fe=e=>e.result==="success";var f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function Pt(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Dt=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Dn=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var Hr=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),i=t.get(o);i?i.push(n):t.set(o,[n])}return t},$r=(e,t)=>t?e.get(t)??[]:[];var _r=new WeakMap,us=e=>{let t=_r.get(e);return t||(t=Hr(e),_r.set(e,t)),t};var Kr=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return $r(us(e),r).filter(i=>Pt(r,i)>=n)};var Vr=({inputToMatch:e,lastWord:t},n)=>{if(t.endsWith(" "))return{hint:"",hints:[],overlap:0,remainder:""};let r=Kr({wordList:n,inputToMatch:e,overlapThreshold:1});return ms(t,r)},ms=(e,t)=>{let n=t[0]??"",r=Pt(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),a=r<(o??"").length,d=!!i,g=(d&&a?o:n)+(d&&a?":":" "),y=g.slice(r);return{hint:g,hints:t,overlap:r,remainder:y}};var jr=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var qe=24n,ps=qe*4n,Ft=(1n<<ps)-1n,gs=/^[0-9a-f]+$/;function zr(e){if(!e||!gs.test(e))throw new Error(`Invalid hex rank: ${e}`);return BigInt("0x"+e)}function kt(e,t=qe){if(e<0n)throw new Error("Negative rank not allowed");return e.toString(16).padStart(Number(t),"0")}function mt(e,t){if(!e&&!t)return kt(Ft/2n,qe);let n=e?zr(e):0n,r=t?zr(t):Ft;if(r<=n)return kt(Ft/2n,qe);let o=(n+r)/2n;return o===n||o===r?"":kt(o,qe)}function me(){return kt(Ft/2n,qe)}var ne={workspace:(e,t)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r=!1)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:(e,t,n,r={},o="horizontal")=>({id:e,title:t,rank:me(),isDeleted:!1,props:r,context:P.FIELD,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[]}),ticket:(e,t,n)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,props:r={},readonly:o=!0})=>({id:e,title:t,rank:me(),isDeleted:!1,props:r,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[]})};var W=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Gr=(e,t)=>e.findIndex(n=>n.id===t),Fn=(e,t={at:"end"})=>{if(e.length===0)return u("Resolved rank",me());switch(t.at){case"start":{let n=e[0];return n?u("Resolved rank",mt(void 0,n.rank)):s("Unable to resolve first sibling")}case"end":{let n=e[e.length-1];return n?u("Resolved rank",mt(n.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let n=Gr(e,t.sibling);if(n<0)return s("Sibling not found");let r=n>0?e[n-1]:void 0,o=e[n];return o?u("Resolved rank",mt(r?.rank,o.rank)):s("Sibling not found")}case"after":{let n=Gr(e,t.sibling);if(n<0)return s("Sibling not found");let r=e[n],o=n<e.length-1?e[n+1]:void 0;return r?u("Resolved rank",mt(r.rank,o?.rank)):s("Sibling not found")}}};var ke=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return s("Node not found");if(r.context===t)return u("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return u("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return s(`No ancestor found for context: ${t}`)},On=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},kn=(e,t)=>e?e.readonly?s({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:s("Node not found"),C={deleteNode(e){de(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return s("Edit target node not found");let o=kn(r,"edit");if(o)return o;let i={...r,props:{...r.props,value:t}};return C.updateNode(i),u("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return s("Rename target node not found");let r=kn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),u("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return W(e).find(n=>n.title===t)},moveNode({id:e,parentId:t,position:n={at:"end"}}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let a=kn(o,"move");if(a)return a;if(On(t,e))return s("Cannot move node into its own descendant");let d=W(t).filter(g=>g.id!==e),l=Fn(d,n);if(c(l))return l;let m={...o,parentNodeId:t,rank:l.data};return this.updateNode(m),u("Moved node successfully",m)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,a=l=>{let m=t[l];if(!(!m||i.has(l))){i.add(l);for(let g of W(m.id))a(g.id)}};a(e);let d={...structuredClone(t)};for(let l of i){if(!d[l])return s("Unable to locate node to delete");d[l]={...d[l],isDeleted:!0}}return n?(A({nodes:d}),u("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=de(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return c(t)?s("Unable to create contributor"):u("Created contributor",e)},assign(e,t,n){let r=C.getContributor(t),o=C.getNode(e);if(!o||!r)return s("Unable assign contributor to issue");let i=this.getFieldByTitle(o.id,"Assignees");if(!i)return s("Unable to locate assignees field");if(W(i.id).some(l=>l.props?.value===t))return s("Contributor already assigned");let d=this.createNodeAtPosition(ne.field(n,r.name,i.id,{value:t}));return c(d)?d:u("Assigned contributor",d.data)},createTag(e){let t=de(n=>({...n,tags:{...n.tags,[e.id]:e}}));return c(t)?s("Could not create tag"):u("Tag created",e)},tag(e,t,n){let r=C.getTag(t),o=C.getNode(e);if(!r)return s("Unable to add tag, missing tag");if(!o)return s("Unable to add tag, missing target");let i=this.getFieldByTitle(o.id,"Tags");if(!i)return s("Unable to locate tags field");if(W(i.id).some(l=>l.props?.value===t))return s("Tag already assigned");let d=this.createNodeAtPosition(ne.field(n,r.name,i.id,{value:t}));return c(d)?d:u("Tag added",d.data)},untag(e,t){let n=C.getTag(t),r=C.getNode(e);if(!n)return s("Unable to remove tag, missing tag");if(!r)return s("Unable to remove tag, missing target");let o=this.getFieldByTitle(r.id,"Tags");if(!o)return s("Unable to locate tags field");let i=W(o.id).find(d=>d.props?.value===t);if(!i)return u("Issue is not tagged with that tag",null);let a={...i,isDeleted:!0};return this.updateNode(a),u("Tag removed",a)},unassign(e,t){let n=C.getContributor(t),r=C.getNode(e);if(!n)return s("Unable to unassign, missing contributor");if(!r)return s("Unable to unassign, missing target");let o=this.getFieldByTitle(r.id,"Assignees");if(!o)return s("Unable to locate assignees field");let i=W(o.id).find(d=>d.props?.value===t);if(!i)return u("Issue is not assigned to that contributor",null);let a={...i,isDeleted:!0};return this.updateNode(a),u("Assignee removed",a)},createNodeAtPosition(e,t={at:"end"}){if(!e.parentNodeId){let i={...e,rank:me()};return this.createNode(i),u("Created node",i)}let n=W(e.parentNodeId),r=Fn(n,t);if(c(r))return r;let o={...e,rank:r.data};return this.createNode(o),u("Created node",o)},createNode(e){let t=de(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return c(t)?s("Unable to create node"):u("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let n={...t,readonly:!0},r=de(o=>({...o,nodes:{...o.nodes,[e]:n}}));return c(r)?s(r.message):u("Locked node",n)},updateNode(e){let t=de(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return c(t)?t:u("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings:e=>Object.values(v().nodes).filter(t=>!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank))};var Ot={autoSync:!1,preferredEditor:null,userName:null,userId:null},pe=()=>Ot,Ye=e=>(Ot={...Ot,...e},Ot);var Bt=()=>{let e=pe(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},qr=()=>!Ke();var q={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#2a2f45",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},E={accent:q.cyan,accent2:q.magenta,primary:q.white,secondary:q.grayDark,secondary2:q.grayLight,gray:q.gray,green:q.green,yellow:q.yellow,red:q.red};var h={red:q.red,yellow:q.yellow,green:q.green,blue:q.blue,magenta:q.magenta,cyan:q.cyan},Je={urgent:h.red,critical:h.red,important:h.red,blocker:h.red,asap:h.red,immediate:h.red,fail:h.red,failure:h.red,broken:h.red,bug:h.red,error:h.red,incident:h.red,outage:h.red,production:h.red,crash:h.red,security:h.red,warning:h.yellow,warn:h.yellow,risky:h.yellow,risk:h.yellow,attention:h.yellow,pending:h.yellow,review:h.yellow,"needs-review":h.yellow,qa:h.yellow,testing:h.yellow,test:h.yellow,validate:h.yellow,verification:h.yellow,staging:h.yellow,check:h.yellow,"follow-up":h.yellow,followup:h.yellow,waiting:h.yellow,blocked:h.yellow,hold:h.yellow,done:h.green,complete:h.green,completed:h.green,success:h.green,ok:h.green,stable:h.green,resolved:h.green,fixed:h.green,closed:h.green,merged:h.green,released:h.green,deployed:h.green,approved:h.green,verified:h.green,working:h.green,healthy:h.green,pass:h.green,passing:h.green,info:h.blue,information:h.blue,note:h.blue,docs:h.blue,documentation:h.blue,doc:h.blue,guide:h.blue,help:h.blue,explanation:h.blue,detail:h.blue,details:h.blue,context:h.blue,design:h.blue,discussion:h.blue,proposal:h.blue,idea:h.blue,feature:h.magenta,enhancement:h.magenta,improvement:h.magenta,refactor:h.magenta,refactoring:h.magenta,cleanup:h.magenta,optimize:h.magenta,optimization:h.magenta,perf:h.magenta,performance:h.magenta,upgrade:h.magenta,migration:h.magenta,modernize:h.magenta,debt:h.magenta,todo:h.cyan,next:h.cyan,planned:h.cyan,plan:h.cyan,future:h.cyan,backlog:h.cyan,investigate:h.cyan,explore:h.cyan,prototype:h.cyan};var Yr=(e,t)=>{let r=M(e.id).find(o=>o.title===t);return r?M(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},Bn=e=>Yr(e,"Tags").map(t=>C.getTag(t)).filter(t=>!!t),Ut=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ye(n)?s("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",Bn(n)??[])},Wt=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ye(n)?s("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",Un(n)??[])},Un=e=>Yr(e,"Assignees").map(t=>C.getContributor(t)).filter(t=>!!t);var fs=/^(\d+)(h|d|w|mo|y)$/,ys=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,xs=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let i=new Date(e,t-1,n,r,o);return i.getFullYear()===e&&i.getMonth()===t-1&&i.getDate()===n&&i.getHours()===r&&i.getMinutes()===o},vs=(e,t=new Date)=>{let n=e.match(fs);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let a=new Date(t);switch(o){case"h":return a.setHours(a.getHours()-i),a;case"d":return a.setDate(a.getDate()-i),a;case"w":return a.setDate(a.getDate()-i*7),a;case"mo":return a.setMonth(a.getMonth()-i),a;case"y":return a.setFullYear(a.getFullYear()-i),a;default:return null}},hs=e=>{let t=e.match(ys);if(!t)return null;let[,n,r,o,i,a]=t,d=Number(n),l=Number(r),m=Number(o),g=i?Number(i):0,y=a?Number(a):0;return xs({year:d,month:l,day:m,hour:g,minute:y})?new Date(d,l-1,m,g,y):null},Ht=e=>{let t=e.trim().toLowerCase();return vs(t)??hs(t)},Jr=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Es=[{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}],Xr=(e=Es)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let i=r;i<=o;i++)t.push(`${i}${n}`);return t};var Cs=["BOARD","TICKET","SWIMLANE"],z=e=>{let{currentNode:t,readOnly:n,selectedNode:r}=v(),o=Bt().isSetup,i=t.context,a=r?.context,d=[p.SYNC,p.HELP,p.SET_VIEW,p.SET_EDITOR,p.SET_USERNAME],l=[p.NEW,p.RENAME,p.DELETE],m=[p.TAG,p.UNTAG,p.ASSIGN,p.UNASSIGN,p.CLOSE_ISSUE,p.RE_OPEN_ISSUE,p.SET_DESCRIPTION],g=[p.FILTER,p.PEEK],y={WORKSPACE:[...d,...l],BOARD:[...g,...d,...l],SWIMLANE:[...g,...d,...l],TICKET:[...d,...l,...m],FIELD:[...d,...m],FIELD_LIST:[...d,...m],TEXT:[...d]},N=a&&Cs.includes(a),b=[...y[i||"WORKSPACE"]].filter(T=>[p.RENAME,p.DELETE,p.MOVE].includes(T)?N:!0),I={[p.PEEK]:[...Xr(),"now","prev","next"],[p.SYNC]:[],[p.INIT]:[],[p.SET_USERNAME]:[],[p.SET_DESCRIPTION]:["confirm"],[p.DELETE]:["confirm"],[p.RE_OPEN_ISSUE]:["confirm"],[p.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[p.CLOSE_ISSUE]:["confirm"],[p.FILTER]:["tag","assignee","description","title","clear"],[p.SET_VIEW]:["dense","wide"],[p.SET_EDITOR]:[...jr,"vim"],[p.TAG]:[...new Set([...Object.keys(Je),...C.getExistingTags()])],[p.UNTAG]:[...Ut()?.data?.map(({name:T})=>T)??[]],[p.UNASSIGN]:[...Wt()?.data?.map(({name:T})=>T)??[]],[p.ASSIGN]:C.getExistingAssignees(),[p.HELP]:[],[p.RENAME]:[],[p.NEW]:i==="TICKET"||i==="FIELD"||i==="FIELD_LIST"?["issue","swimlane","board"]:i==="SWIMLANE"?["issue","swimlane","board"]:i==="BOARD"?["issue","swimlane","board"]:["board"],[p.NONE]:b};return o?qr()?n&&(I={[p.NONE]:[p.HELP,p.PEEK],[p.HELP]:I[p.HELP],[p.PEEK]:I[p.PEEK]}):I={[p.NONE]:[p.HELP,p.INIT],[p.HELP]:I[p.HELP],[p.INIT]:I[p.INIT]}:I={[p.NONE]:[p.HELP,p.SET_EDITOR,p.SET_USERNAME],[p.HELP]:I[p.HELP],[p.SET_EDITOR]:I[p.SET_EDITOR],[p.SET_USERNAME]:I[p.SET_USERNAME]},I[e]??[]};import Qe from"chalk";import{decodeTime as Qr}from"ulid";var Zr=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 i=Math.floor(t/o);if(i>=1)return`${i}${r} ago`}return"just now"},eo=e=>{let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},$t=e=>{try{return u("Decoded date",new Date(Qr(e)))}catch(t){return s("Decoding failed + "+t.message)}},Wn=e=>{if(!e?.id)return null;try{return Qr(e.id)}catch{return null}};var be=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?u("Found node",n):s("Unable to find node in breadcrumb")};import Xe from"chalk";var $n={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Ns=(e,t,n)=>Math.max(t,Math.min(n,e)),Hn=(e,t,n)=>e+(t-e)*n,to=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},bs=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,a=e/60,d=i*(1-Math.abs(a%2-1)),l=0,m=0,g=0;a>=0&&a<1?(l=i,m=d):a>=1&&a<2?(l=d,m=i):a>=2&&a<3?(m=i,g=d):a>=3&&a<4?(m=d,g=i):a>=4&&a<5?(l=d,g=i):(l=i,g=d);let y=o-i/2;return[Math.round((l+y)*255),Math.round((m+y)*255),Math.round((g+y)*255)]},Is=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Ss=(e,t,n)=>[Math.round(Hn(e[0],t[0],n)),Math.round(Hn(e[1],t[1],n)),Math.round(Hn(e[2],t[2],n))],pt=e=>{let n=to(e)%360,r=bs(n,$n.stringColor.saturation,$n.stringColor.lightness);return Is(r)},Ts=e=>{let t=$n.gradient.stops,n=Ns(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,i=Math.min(Math.floor(o),r-1),a=o-i;return Ss(t[i],t[i+1],a)},_t=e=>to(e.toLowerCase().trim())/4294967295,no=e=>{let t=_t(e);return Ts(t)},As=e=>{let[t,n,r]=no(e);return{normal:o=>Xe.bgRgb(t,n,r).black(o),cursor:o=>Xe.bgRgb(t,n,r).white.bold(o)}},_n=e=>{let[t,n,r]=no(e);return{fg:o=>Xe.rgb(t,n,r)(o),fgCursor:o=>Xe.rgb(t,n,r).inverse(o),bg:o=>Xe.bgRgb(t,n,r).black(o),bgCursor:o=>Xe.bgRgb(t,n,r).white.bold(o)}},Kn=e=>As(e).normal(` ${e} `),Y=(e,t=Je)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:pt(r)};var ws=["BOARD","TICKET","SWIMLANE"],Vn=()=>{let e=v().selectedNode;return e?.context?ws.includes(e?.context)?V():H({message:"Command not available in this context"}):H({message:"Missing target context"})},ce="<ENTER> to confirm",V=(e="",t=[])=>({message:e,validity:Ne.Valid,completionWordList:t}),H=({message:e,completionWordList:t=[]})=>({validity:Ne.Invalid,message:e,completionWordList:t}),ft=e=>e.length===0,Oe=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let l=[...t.filter(Boolean).filter(g=>g.startsWith(o.trim()))].sort((g,y)=>_t(g)-_t(y)).slice(0,r).map(Kn),m=l.length>i?l.join(" "):"";return m?`${e}${m}${n}`:""},jn=({modifier:e})=>{let t="confirm";return e===t?V(ce):H({message:ft(e)?`if you are certain, enter ${Kn(t)}`:"",completionWordList:[t]})},Rs=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?V(ce):H({message:ft(n)?t:""}),Ms=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?H({message:n}):V():H({message:ft(r)?t:""}),gt=({hint:e})=>({modifier:t,inputString:n})=>ft(t)&&ft(n)?H({message:e,completionWordList:[]}):V(ce),Ls={[p.PEEK]:e=>{let t=e.modifier;if(t==="now")return V(ce);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return V(ce);let r=Ht(t);if(!t||!r)return H(n);let o=be(v().breadCrumb,"BOARD");if(c(o))return H({message:"Command is not applicable in this context"});let i=$t(o.data.id);return c(i)?H({message:"Unable to peek: board id is not a valid ULID"}):Jr({date:r,horizonDate:i.data})?V(ce):H({message:Qe.red(`nothing to peek before ${i.data.toISOString().slice(0,16).replace("T"," ")}`)})},[p.INIT]:()=>V(ce),[p.FILTER]:e=>{if(e.modifier==="clear")return V();let t=a=>z(p.FILTER).includes(a);if(!e.modifier||!t(e.modifier??""))return H({message:Oe({wordList:z(p.FILTER),inputString:e.inputString}),completionWordList:z(p.FILTER)});let r=Object.values(v().tags).map(a=>a.name),o=Object.values(v().contributors).map(a=>a.name),i=e.modifier==="tag"?r:e.modifier==="assignee"?o:[];return e.inputString?i.length&&!i.includes(e.inputString.trim()??"")?H({message:Oe({prefix:`existing ${e.modifier}s... `,wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i}):V():H({message:Oe({prefix:"one of... ",wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i})},[p.NONE]:e=>{let t=z(p.NONE),n=/^[A-Za-z_]+:/g,r=e.inputString.match(n);return r&&r.length?t=[...t.filter(o=>o.trim().match(n))]:t=[...new Set(t.flatMap(o=>o.match(n)?.join("").replace(":","")??o))],e.command?V():H({message:Oe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[p.NEW]:e=>Ms({list:z(p.NEW),hint:Oe({wordList:z(p.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[p.SET_DESCRIPTION]:()=>V(ce),[p.HELP]:()=>V(ce),[p.RENAME]:()=>{let e=Vn();return e.validity==="invalid"?e:V(ce)},[p.DELETE]:e=>{let t=Vn();return t.validity==="invalid"?t:jn(e)},[p.CLOSE_ISSUE]:e=>jn(e),[p.RE_OPEN_ISSUE]:e=>jn(e),[p.MOVE]:e=>{let t=Vn();return t.validity==="invalid"?t:gt({hint:Oe({prefix:"hey hacker! These commands are blocked for you... ",wordList:z(p.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[p.TAG]:e=>{let t=C.getExistingTags().map(n=>` ${Qe.bgHex(Y(n))(" "+n+" ")} `).slice(0,10);return gt({hint:"tag name like... "+t.join("")})(e)},[p.UNTAG]:e=>{let t=Ut();if(c(t))return H({message:"Invalid untag target",completionWordList:[]});let n=t.data.map(({name:r})=>r).map(r=>` ${Qe.bgHex(Y(r))(" "+r+" ")} `).slice(0,10);return n.length?gt({hint:" ... "+n.join("")})(e):H({message:"Issue has not tags",completionWordList:[]})},[p.ASSIGN]:e=>{let t=C.getExistingAssignees().map(n=>` ${Qe.bgHex(Y(n))(" "+n+" ")} `).slice(0,10);return gt({hint:"assign to... "+t.join("")})(e)},[p.UNASSIGN]:e=>{let t=Wt();if(c(t))return H({message:"Invalid unassign target",completionWordList:[]});let n=t.data.map(({name:r})=>r).map(r=>` ${Qe.bgHex(Y(r))(" "+r+" ")} `).slice(0,10);return n.length?gt({hint:"remove assignee... "+n.join("")})(e):H({message:"Issue has no assignees",completionWordList:[]})},[p.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=z(p.SET_EDITOR);return e.modifier?V(ce):H({message:Oe({wordList:t,inputString:e.inputString})})},[p.SET_USERNAME]:e=>e.inputString?V():H({message:`Enter a username. Saved in ${Qe.bgBlack("~/.epiq/")}`}),[p.SET_VIEW]:e=>Rs({list:z(p.SET_VIEW),hint:Oe({wordList:z(p.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[p.SYNC]:()=>V(ce)},ro=Object.fromEntries(Object.entries(Ls).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var oo=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"];var L={Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",SetView:"set-view",SetEditor:"set-editor",SetUserName:"set-user-name",SetAutoSync:"set-auto-sync",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",Sync:"sync"};var io=e=>Object.values(p).includes(e),so=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:d,completionWordList:l}=ro[n].validate(n,r,i),m=o==="command"?Object.values(p):n&&e.target==="modifier"?z(n):oo;return{validity:d,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?Vr(e,[...l,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var ao=e=>{let t=e.trimStart(),n=Ds(t),r=(n[0]??"").trimStart().trimEnd(),o=(n[1]??"").trimStart().trimEnd(),i=Fs(e),a=io(r)?r:null,d=a!==null,l=r!=="",m=e.endsWith(" "),g=a?z(a)??[]:[],y=a&&g.includes(o)?o:"",N="word";n.length<=1?N="command":n.length===2&&(N="modifier");let b=Ps(t,a,y);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:l,command:a,isCommandKeyword:d,isLastWordCompleted:m,modifier:y,target:N,inputToMatch:i,inputString:b}},Ps=(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},Ds=e=>e?e.split(/\s+/):[],Fs=e=>e.trimEnd().split(/\s+/).at(-1)??"";var co=" ",J={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Ne.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},zn=new Set,lo=()=>{for(let e of zn)e()},uo=e=>(zn.add(e),()=>zn.delete(e)),Ie=e=>{let n=e(J),r=ao(n.value),o=n.cursorPosition===n.value.length;J={...n,commandMeta:so(r,o)},lo()},yt=({message:e,result:t})=>{let n=structuredClone(J);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,J=n,lo(),u(e,null)},Gn=e=>{Ie(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},qn=e=>{Ie(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&n[o-1]===" ";)o--;for(;o>0&&n[o-1]!==" ";)o--}else{for(;o<n.length&&n[o]!==" ";)o++;for(;o<n.length&&n[o]===" ";)o++}return{...t,cursorPosition:o}})},mo=()=>{Ie(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}})},po=()=>{Ie(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&t[r-1]===" ";)r--;for(;r>0&&t[r-1]!==" ";)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},j=e=>{Ie(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),i=e(r,t.commandMeta.autoCompletion),a=i+o,d=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:d,commandIsPending:!1}})},go=()=>{Ie(e=>({...e,commandIsPending:!0}))},fo=({addToHistory:e=!0})=>{Ie(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),ks()},yo=()=>{Ie(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}})},xo=()=>{Ie(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ks=()=>j(()=>""),re=()=>J,Kt=()=>{let[e,...t]=J.value.split(co);return t.join(co).trim()};var Os=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Bs=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",Us=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",vo=(e,t)=>{if(Bs(e,e.sequence))return x.MoveCursorLeftOfWord;if(Us(e,e.sequence))return x.MoveCursorRightOfWord;if(Os(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.GetLastCommandFromHistory;case"down":return x.GetNextCommandFromHistory;case"left":return x.MoveCursorLeft;case"right":return x.MoveCursorRight;case"return":return x.Confirm;case"backspace":return t?x.EraseInput:x.ExitCommandLine;case"escape":return x.ExitCommandLine;default:return x.CaptureInput}};var x={Sync:"sync",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",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",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function Ws(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function Hs(e,t,n){let r=v().currentNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function ho(e,t){let n=re();if(e.sequence===":"&&n.value==="")return x.InitCommandLine;if(t===f.MOVE)switch(e.name){case"m":case"return":return x.ConfirmMove}if(t===f.COMMAND_LINE)return vo(e,n.value);let r=Ws(e);if(r){let o=t===f.MOVE?{prevItem:x.MovePreviousItem,nextItem:x.MoveNextItem,prevContainer:x.MoveToPreviousContainer,nextContainer:x.MoveToNextContainer}:{prevItem:x.NavPreviousItem,nextItem:x.NavNextItem,prevContainer:x.NavToPreviousContainer,nextContainer:x.NavToNextContainer};return Hs(v().currentNode.childRenderAxis,r,o)}if(e.ctrl&&e.name==="c")return x.Exit;switch(e.name){case"e":return x.Edit;case"n":return x.AddItem;case"m":return x.InitMove;case"d":return x.Delete;case"return":return x.Confirm;case"space":return x.Confirm;case"v":return v().viewMode==="wide"?x.SetViewDense:x.SetViewWide;case"q":case"escape":return x.Exit;case"s":return x.Sync;default:return null}}var Eo=e=>{let{context:t}=v()?.currentNode;if(!t)return L.None;switch(e){case p.INIT:return L.Init;case p.DELETE:return L.Delete;case p.SET_DESCRIPTION:return L.Edit;case p.HELP:return L.ViewHelp;case p.RE_OPEN_ISSUE:return L.ReopenIssue;case p.CLOSE_ISSUE:return L.CloseIssue;case p.TAG:return L.TagTicket;case p.UNTAG:return L.UntagTicket;case p.ASSIGN:return L.AssignUserToTicket;case p.UNASSIGN:return L.UnassignUserFromTicket;case p.RENAME:return L.Rename;case p.NEW:return L.NewItem;case p.FILTER:return L.Filter;case p.MOVE:return L.Move;case p.PEEK:return L.Peek;case p.SET_USERNAME:return L.SetUserName;case p.SET_EDITOR:return L.SetEditor;case p.SET_VIEW:return L.SetView;case p.SYNC:return L.Sync;default:return L.None}};import{ulid as $}from"ulid";import{spawnSync as qs}from"node:child_process";import Ys from"node:os";import Io from"node:path";import{ulid as Js}from"ulid";import{accessSync as $s,copyFileSync as _s,existsSync as Vt,mkdirSync as Co,readdirSync as No,readFileSync as Ks,renameSync as Vs,rmSync as js,statSync as bo,unlinkSync as zs,writeFileSync as Gs}from"node:fs";import Ze from"node:path";var le={writeToFile:(e,t)=>{try{let n=Ze.dirname(e);Vt(n)||Co(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Gs(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Ks(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=le.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 Vt(e)&&bo(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await $s(e),!0}catch{return!1}},mkDir:e=>Co(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Ze.parse(t);for(;;){let r=Ze.join(t,e);try{if(Vt(r)&&bo(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Ze.dirname(t)}return null},readFirstJSON(e){try{if(!le.dirExists(e))return null;let t=No(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Ze.join(e,t);return le.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return le.dirExists(e)?No(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{zs(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{js(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Ze.dirname(t)),!n?.overwrite&&Vt(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Vs(e,t)}catch(r){if(r?.code==="EXDEV"){_s(e,t),this.rmFile(e);return}throw r}}};function Xs(){let{preferredEditor:e}=pe(),t=[e,process.env.VISUAL,process.env.EDITOR,"vim","nano"].filter(n=>!!n?.trim());return[...new Set(t)]}function Qs(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function So(e){let t=Io.join(Ys.tmpdir(),"epiq");le.mkDir(t);let n=Io.join(t,Js());le.writeToFile(n,e??"");let r=Xs();for(let o of r){let i=Qs(o,n),a=qs(i,{stdio:"inherit",shell:!0});if(!a.error&&a.status===0){let d=le.readFile(n);if(d==null)return s("Unable to read edited file");let l=d.replace(/\r?\n$/,"");return u("Successfully edited",l)}}return s("Unable to open editor")}import{monotonicFactory as Zs,ulid as jt}from"ulid";var zt=Zs(),To=({name:e,parent:t,user:{userId:n,userName:r}})=>{let o=zt(),i=zt(),a=zt(),d=zt();return[{id:jt(),userId:n,userName:r,action:"add.issue",payload:{id:o,parent:t,name:e}},{id:jt(),userId:n,userName:r,action:"add.field",payload:{id:i,parent:o,name:"Description",val:""}},{id:jt(),userId:n,userName:r,action:"add.field",payload:{id:a,parent:o,name:"Assignees"}},{id:jt(),userId:n,userName:r,action:"add.field",payload:{id:d,parent:o,name:"Tags"}}]};import Xt from"node:fs";import Qt from"node:path";import{z as Xn}from"zod";var Gt=process.env.IS_LOCAL==="true",Se=()=>".epiq";import qt from"node:fs";import ea from"node:os";import Be from"node:path";import{decodeTime as ta,monotonicFactory as na}from"ulid";import{z as xt}from"zod";var Ao=e=>({action:e.action,payload:e.payload});var ra=Be.resolve(ea.homedir(),".epiq"),Ro=1,wo=na(),oa="events",ia=xt.tuple([xt.string().min(1),xt.string().min(1).nullable()]),sa=xt.looseObject({v:xt.literal(Ro),id:ia}),Yn=e=>{let t=sa.safeParse(e);return t.success?u("Parsed persisted event",t.data):s(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Yt=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",X=()=>{let{userName:e,userId:t}=pe();return e?t?e.trim()?u("Successfully resolved actor ID",{userId:Yt(t),userName:Yt(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},aa=e=>Be.resolve(e)===ra,da=e=>{let t=Be.join(e,Se());return!aa(t)&&qt.existsSync(t)&&qt.statSync(t).isDirectory()},et=e=>{let t=Be.resolve(e);for(;;){if(da(t))return t;let n=Be.dirname(t);if(n===t)return Be.resolve(e);t=n}},Mo=e=>Be.join(et(e),Se(),oa),Jn=({userId:e,userName:t})=>`${Yt(e)}.${Yt(t)}.jsonl`,ca=(e,{userId:t,userName:n})=>{let r=Jn({userId:t,userName:n});return/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r)?u("Successfully resolved event log path",Be.join(Mo(e),r)):s(`Invalid event log file name: ${r}`)},la=(e,t)=>{let n={[e.action]:e.payload,v:Ro,id:t};return Yn(n)};function Jt({event:e,rootDir:t=process.cwd()}){try{let n=et(t),r=Mo(n),o=ca(n,{userId:e.userId,userName:e.userName});if(c(o))return o;qt.mkdirSync(r,{recursive:!0});let i=Lo(n);if(c(i))return s(i.message);let a=i.data?wo(Math.max(Date.now(),ta(i.data)+1)):wo(),d=la(Ao(e),[a,i.data]);return c(d)?s(d.message):(qt.appendFileSync(o.data,`${JSON.stringify(d.data)}
3
3
  `,"utf8"),u("Event persisted",{path:o.data,entry:d.data}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return s(`Failed to persist event: ${r}`)}}import{decodeTime as ua}from"ulid";var ma=Se(),pa="events",ga=Xn.object({userId:Xn.string().min(1).default("unknown"),userName:Xn.string().min(1).default("unknown")}),fa=(e=process.cwd())=>Qt.join(et(e),ma,pa),ya=e=>{let[t,n]=Qt.basename(e,".jsonl").split("."),r=ga.safeParse({userId:t,userName:n});return r.success?u("Parsed event file actor",r.data):s(`Invalid event file name ${Qt.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},xa=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?s(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?s("Invalid persisted event: action key is missing or invalid"):u("Resolved persisted action",t[0])},va=(e,t)=>t in e,ha=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Ea=e=>{let{userId:t,userName:n,...r}=e,o=xa(r);if(c(o))return s(o.message);let i=o.data,a=e.id?.[0];return a?va(r,i)?u("Decoded persisted event",ha({id:a,action:i,payload:r[i],userId:t,userName:n})):s(`Persisted event is missing payload for action: ${i}`):s("Persisted event is missing id")},Zt=e=>{if(!Xt.existsSync(e))return u("Event file missing",[]);let t=ya(e);if(c(t))return s(t.message);let n=Xt.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
4
4
  `)){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{return s(`Failed to parse event JSON from ${e}: ${i}`)}let d=Yn(a);if(c(d))return s(`${d.message} in ${e}: ${i}`);r.push({...d.data,userId:t.data.userId,userName:t.data.userName})}return u("Parsed persisted events file",r)};function Po(e=process.cwd()){let t=fa(e);if(!Xt.existsSync(t))return s("No events found");let n=Xt.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Qt.join(t,o)),r=[];for(let o of n){let i=Zt(o);if(c(i))return s(i.message);r.push(...i.data)}return u("All events loaded",Ca(r))}function vt(e=process.cwd()){let t=Po(e);if(c(t))return s(t.message);let n=[];for(let r of t.data){let o=Ea(r);if(c(o))return s(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);n.push(o.data)}return u("Loaded merged events",n)}function Lo(e=process.cwd()){let t=Po(e);return c(t)?s(t.message):u("Loaded edge reference",t.data.at(-1)?.id?.[0]??null)}var Ca=e=>{let t=new Map(e.map(d=>[d.id[0],d])),n=new Map;for(let d of e){let l=d.id[1],m=n.get(l)??[];m.push(d),n.set(l,m)}for(let d of n.values())d.sort((l,m)=>{let[g]=l.id,[y]=m.id;return g.localeCompare(y)});let r=[],o=new Set,i=d=>{let l=n.get(d)??[];for(let m of l){let[g]=m.id;o.has(g)||(o.add(g),r.push(m),i(g))}};i(null);let a=[...e].filter(d=>{let[l]=d.id;return!o.has(l)}).sort((d,l)=>{let[m,g]=d.id,[y,N]=l.id,b=g===null||t.has(g),I=N===null||t.has(N);if(b&&!I)return-1;if(!b&&I)return 1;let T=(g??"").localeCompare(N??"");return T!==0?T:m.localeCompare(y)});return[...r,...a]},Do=(e,t)=>{let n=e.findIndex(r=>{try{return ua(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var Fo=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)return r.payload.parent}return null};var Na=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[tt,en]=Na;var D=(e,t)=>s(`${t.split(".").join(" ")+" failed, "+e.toLowerCase()}`),ba={"init.workspace":({action:e,payload:t})=>{let{id:n,name:r}=t,o=ne.workspace(n,r);Qn(o);let i=C.createNodeAtPosition(o);return c(i)?D(i.message??"Failed to initialize workspace",e):u("Workspace initialized",{action:e,result:i.data})},"add.workspace":({action:e,payload:t})=>{let{id:n,name:r}=t,o=ne.workspace(n,r),i=C.createNodeAtPosition(o);return c(i)?D(i.message??"Failed to add workspace",e):u("Added workspace",{action:e,result:i.data})},"add.board":({action:e,payload:t})=>{let{id:n,name:r,parent:o}=t,i=C.createNodeAtPosition(ne.board(n,r,o));return c(i)?D(i.message??"Unable to create board",e):u("Added board",{action:e,result:i.data})},"add.swimlane":({action:e,payload:t})=>{let{id:n,name:r,parent:o}=t,i=C.createNodeAtPosition(ne.swimlane(n,r,o));return c(i)?D(i.message??"Unable to create swimlane",e):u("Added swimlane",{action:e,result:i.data})},"add.issue":({action:e,payload:t})=>{let{id:n,name:r,parent:o}=t,i=C.createNodeAtPosition(ne.ticket(n,r,o));return c(i)?D(i.message??"Unable to create issue",e):u("Added issue",{action:e,result:i.data})},"add.field":({action:e,payload:t})=>{let{id:n,name:r,parent:o,val:i}=t,a=C.createNodeAtPosition(ne.field(n,r,o,{value:i},r.includes("Description")?"vertical":"horizontal"));return c(a)?D(a.message??`Unable to create field: ${r}`,e):u("Added field",{action:e,result:a.data})},"edit.title":({action:e,payload:t})=>{let{id:n,name:r}=t;if(!C.getNode(n))return D("Unable to locate node",e);let i=C.renameNode(n,r);return c(i)?D(i.message??"Unable to edit title",e):u("Edited title",{action:e,result:i.data})},"delete.node":({action:e,payload:t})=>{let{id:n}=t,r=C.tombstoneNode(n);return c(r)?D(r.message??"Unable to delete node",e):u("Deleted node",{action:e,result:r.data})},"create.tag":({action:e,payload:t})=>{let{id:n,name:r}=t,o=C.createTag({id:n,name:r});return c(o)?D(o.message??"Unable to create tag",e):u("Tag added",{action:e,result:o.data})},"create.contributor":({action:e,payload:t})=>{let{id:n,name:r}=t,o=C.createContributor({id:n,name:r});return c(o)?D(o.message??"Unable to create contributor",e):u("Contributor created",{action:e,result:o.data})},"tag.issue":({action:e,payload:t})=>{let{id:n,target:r,tagId:o}=t,i=C.tag(r,o,n);return c(i)?D(i.message??"Unable to tag issue",e):u("Issue tagged",{action:e,result:i.data})},"untag.issue":({action:e,payload:t})=>{let{target:n,tagId:r}=t,o=C.untag(n,r);return c(o)?D(o.message??"Unable to untag ",e):u("Issue untagged",{action:e,result:o.data})},"assign.issue":({action:e,payload:t})=>{let{id:n,contributor:r,target:o}=t,i=C.assign(o,r,n);return c(i)?D(i.message??"Unable to assign issue",e):u("Assigned successfully",{action:e,result:i.data})},"unassign.issue":({action:e,payload:t})=>{let{target:n,contributor:r}=t,o=C.unassign(n,r);return c(o)?D(o.message??"Unable to unassign issue",e):u("Issue unassigned",{action:e,result:o.data})},"move.node":({action:e,payload:t})=>{let{id:n,parent:r,pos:o}=t,i=C.moveNode({id:n,parentId:r,position:o});return c(i)?D(i.message??"Failed to move node",e):u("Moved node",{action:e,result:i.data})},"edit.description":({action:e,payload:t})=>{let{id:n,md:r}=t,o=C.editValue(n,r);return c(o)?D(o.message??"Unable to edit description",e):u("Set node value",{action:e,result:o.data})},"close.issue":({action:e,payload:t})=>{let{id:n}=t,r=C.getNode(n);if(!r)return D("Unable to locate issue",e);if(!ye(r))return D("Can only close issues",e);let o=C.getNode(tt);if(!o)return D("Unable to locate target swimlane",e);if(o.id===r.parentNodeId)return D("Cannot close closed issue",e);let a=C.moveNode({id:n,parentId:o.id});return c(a)?D(a.message??"Unable to close issue",e):u("Issue closed",{action:e,result:a.data})},"reopen.issue":({action:e,payload:t})=>{let{id:n}=t,r=C.getNode(n);if(!r)return D("Unable to locate issue",e);if(!ye(r))return D("Can only reopen issues",e);let o=C.getNode(tt);if(!o)return D("Unable to locate closed swimlane",e);if(!(r.parentNodeId===o.id))return D("Issue is not closed",e);let a=Fo(r);if(!a)return D("Unable to resolve previous parent from issue history",e);if(a===o.id)return D("Previous parent resolves to closed swimlane",e);if(!C.getNode(a))return D("Previous parent no longer exists",e);let l=C.moveNode({id:n,parentId:a});return c(l)?D(l.message??"Unable to reopen issue",e):u("Issue reopened",{action:e,result:l.data})},"lock.node":({action:e,payload:t})=>{let{id:n}=t,r=C.lockNode(n);return c(r)?D(r.message??"Unable to lock node",e):u("Node locked",{action:e,result:r.data})}},Ia=(e,t)=>{let n=C.getNode(e);n&&C.updateNode({...n,log:[...n.log??[],t]})},Sa=e=>{switch(e.action){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"delete.node":case"move.node":case"close.issue":case"reopen.issue":return[e.payload.id];case"edit.description":let t=[e.payload.id],n=v().nodes[e.payload.id]?.parentNodeId;return n&&t.push(n),t;case"tag.issue":case"untag.issue":case"assign.issue":case"unassign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function nt(e,t=!1){let n=ba[e.action](e);if(c(n))return n;t||([...new Set(Sa(e))].forEach(a=>Ia(a,e)),de(a=>({...a,eventLog:[...a.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?D("Invalid user ID format",e.action):(C.createContributor({name:o,id:r}),n)}var Ve=e=>e.map(t=>nt(t));function Q(e){let t=nt(e);if(t.result!==xe.Success)return t;let n=Jt({event:e});return c(n)?n:t}function ko(e){return e.map(t=>Q(t))}import bt from"node:fs";import{spawn as wa}from"node:child_process";import er from"node:fs";import rt from"node:path";var ht=(e,t)=>{let n=new Map,r=t??((...i)=>JSON.stringify(i)),o=((...i)=>{let a=r(...i);if(!n.has(a)){let d=e(...i).then(l=>(c(l)&&n.delete(a),l));n.set(a,d)}return n.get(a)});return o.clear=()=>n.clear(),o};import Et from"fs";import Bo from"path";import Ta from"util";var Oo=1e3,Uo=(e=process.cwd())=>Bo.join(et(e),Se(),"log","epiq.log");function Aa(e=process.cwd()){if(!Gt)return;let t=Uo(e);if(!Et.existsSync(t))return;let r=Et.readFileSync(t,"utf8").split(`
5
5
  `);if(r[r.length-1]===""&&r.pop(),r.length<=Oo)return;let o=r.slice(-Oo).join(`
package/dist/mcp.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import{McpServer as ws}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Ts}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as A}from"zod";var m={INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",RENAME:"rename",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",SET_DESCRIPTION:"edit",SET_EDITOR:"config:editor",SET_VIEW:"config:view",SET_USERNAME:"config:username",SYNC:"sync",NONE:""},re={None:"none",Invalid:"invalid",Valid:"valid"},ee={None:"none",Success:"success",Fail:"fail"},i=e=>({result:ee.Fail,message:e,data:null}),c=(e,t)=>({result:ee.Success,message:e,data:t}),fn=()=>({result:ee.None,message:"No result",data:null}),a=e=>e.result==="fail";import{ulid as so}from"ulid";import{monotonicFactory as yo,ulid as Xe}from"ulid";var Qe=yo(),Ze=({name:e,parent:t,user:{userId:n,userName:r}})=>{let o=Qe(),s=Qe(),d=Qe(),l=Qe();return[{id:Xe(),userId:n,userName:r,action:"add.issue",payload:{id:o,parent:t,name:e}},{id:Xe(),userId:n,userName:r,action:"add.field",payload:{id:s,parent:o,name:"Description",val:""}},{id:Xe(),userId:n,userName:r,action:"add.field",payload:{id:d,parent:o,name:"Assignees"}},{id:Xe(),userId:n,userName:r,action:"add.field",payload:{id:l,parent:o,name:"Tags"}}]};import Pe from"chalk";import{monotonicFactory as bs,ulid as de}from"ulid";import{useSyncExternalStore as vm}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function z(e){return e.context==="TICKET"}var p={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function et(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var tt=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var vn=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},yn=(e,t)=>t?e.get(t)??[]:[];var En=new WeakMap,Eo=e=>{let t=En.get(e);return t||(t=vn(e),En.set(e,t)),t};var Nn=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return yn(Eo(e),r).filter(s=>et(r,s)>=n)};var In=({inputToMatch:e,lastWord:t},n)=>{if(t.endsWith(" "))return{hint:"",hints:[],overlap:0,remainder:""};let r=Nn({wordList:n,inputToMatch:e,overlapThreshold:1});return No(t,r)},No=(e,t)=>{let n=t[0]??"",r=et(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),d=r<(o??"").length,l=!!s,v=(l&&d?o:n)+(l&&d?":":" "),N=v.slice(r);return{hint:v,hints:t,overlap:r,remainder:N}};var xn=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var xe=24n,Io=xe*4n,nt=(1n<<Io)-1n,xo=/^[0-9a-f]+$/;function bn(e){if(!e||!xo.test(e))throw new Error(`Invalid hex rank: ${e}`);return BigInt("0x"+e)}function rt(e,t=xe){if(e<0n)throw new Error("Negative rank not allowed");return e.toString(16).padStart(Number(t),"0")}function ke(e,t){if(!e&&!t)return rt(nt/2n,xe);let n=e?bn(e):0n,r=t?bn(t):nt;if(r<=n)return rt(nt/2n,xe);let o=(n+r)/2n;return o===n||o===r?"":rt(o,xe)}function Q(){return rt(nt/2n,xe)}var te={workspace:(e,t)=>({id:e,title:t,rank:Q(),isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r=!1)=>({id:e,title:t,rank:Q(),isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n)=>({id:e,title:t,rank:Q(),isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:(e,t,n,r={},o="horizontal")=>({id:e,title:t,rank:Q(),isDeleted:!1,props:r,context:P.FIELD,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[]}),ticket:(e,t,n)=>({id:e,title:t,rank:Q(),isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,props:r={},readonly:o=!0})=>({id:e,title:t,rank:Q(),isDeleted:!1,props:r,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[]})};var H=e=>Object.values(y().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Cn=(e,t)=>e.findIndex(n=>n.id===t),Ut=(e,t={at:"end"})=>{if(e.length===0)return c("Resolved rank",Q());switch(t.at){case"start":{let n=e[0];return n?c("Resolved rank",ke(void 0,n.rank)):i("Unable to resolve first sibling")}case"end":{let n=e[e.length-1];return n?c("Resolved rank",ke(n.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let n=Cn(e,t.sibling);if(n<0)return i("Sibling not found");let r=n>0?e[n-1]:void 0,o=e[n];return o?c("Resolved rank",ke(r?.rank,o.rank)):i("Sibling not found")}case"after":{let n=Cn(e,t.sibling);if(n<0)return i("Sibling not found");let r=e[n],o=n<e.length-1?e[n+1]:void 0;return r?c("Resolved rank",ke(r.rank,o?.rank)):i("Sibling not found")}}};var be=(e,t)=>{let{nodes:n}=y(),r=n[e];if(!r)return i("Node not found");if(r.context===t)return c("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return c("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return i(`No ancestor found for context: ${t}`)},bo=(e,t)=>{let{nodes:n}=y(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},_t=(e,t)=>e?e.readonly?i({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:i("Node not found"),E={deleteNode(e){q(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=y(),r=n[e];if(!r)return i("Edit target node not found");let o=_t(r,"edit");if(o)return o;let s={...r,props:{...r.props,value:t}};return E.updateNode(s),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return i("Rename target node not found");let r=_t(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=y();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=y();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return H(e).find(n=>n.title===t)},moveNode({id:e,parentId:t,position:n={at:"end"}}){let{rootNodeId:r}=y(),o=this.getNode(e),s=this.getNode(t);if(!o)return i("Node not found");if(!s)return i("Target parent not found");if(r===e)return i("Cannot move root node");if(e===t)return i("Cannot move node into itself");let d=_t(o,"move");if(d)return d;if(bo(t,e))return i("Cannot move node into its own descendant");let l=H(t).filter(v=>v.id!==e),u=Ut(l,n);if(a(u))return u;let g={...o,parentNodeId:t,rank:u.data};return this.updateNode(g),c("Moved node successfully",g)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=y(),o=this.getNode(e);if(!o)return i("Node not found");if(r===e)return i("Cannot delete root node");let s=new Set,d=u=>{let g=t[u];if(!(!g||s.has(u))){s.add(u);for(let v of H(g.id))d(v.id)}};d(e);let l={...structuredClone(t)};for(let u of s){if(!l[u])return i("Unable to locate node to delete");l[u]={...l[u],isDeleted:!0}}return n?(I({nodes:l}),c("Successfully tomb stoned",o)):i("Unable to delete undefined")},createContributor(e){let t=q(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?i("Unable to create contributor"):c("Created contributor",e)},assign(e,t,n){let r=E.getContributor(t),o=E.getNode(e);if(!o||!r)return i("Unable assign contributor to issue");let s=this.getFieldByTitle(o.id,"Assignees");if(!s)return i("Unable to locate assignees field");if(H(s.id).some(u=>u.props?.value===t))return i("Contributor already assigned");let l=this.createNodeAtPosition(te.field(n,r.name,s.id,{value:t}));return a(l)?l:c("Assigned contributor",l.data)},createTag(e){let t=q(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?i("Could not create tag"):c("Tag created",e)},tag(e,t,n){let r=E.getTag(t),o=E.getNode(e);if(!r)return i("Unable to add tag, missing tag");if(!o)return i("Unable to add tag, missing target");let s=this.getFieldByTitle(o.id,"Tags");if(!s)return i("Unable to locate tags field");if(H(s.id).some(u=>u.props?.value===t))return i("Tag already assigned");let l=this.createNodeAtPosition(te.field(n,r.name,s.id,{value:t}));return a(l)?l:c("Tag added",l.data)},untag(e,t){let n=E.getTag(t),r=E.getNode(e);if(!n)return i("Unable to remove tag, missing tag");if(!r)return i("Unable to remove tag, missing target");let o=this.getFieldByTitle(r.id,"Tags");if(!o)return i("Unable to locate tags field");let s=H(o.id).find(l=>l.props?.value===t);if(!s)return c("Issue is not tagged with that tag",null);let d={...s,isDeleted:!0};return this.updateNode(d),c("Tag removed",d)},unassign(e,t){let n=E.getContributor(t),r=E.getNode(e);if(!n)return i("Unable to unassign, missing contributor");if(!r)return i("Unable to unassign, missing target");let o=this.getFieldByTitle(r.id,"Assignees");if(!o)return i("Unable to locate assignees field");let s=H(o.id).find(l=>l.props?.value===t);if(!s)return c("Issue is not assigned to that contributor",null);let d={...s,isDeleted:!0};return this.updateNode(d),c("Assignee removed",d)},createNodeAtPosition(e,t={at:"end"}){if(!e.parentNodeId){let s={...e,rank:Q()};return this.createNode(s),c("Created node",s)}let n=H(e.parentNodeId),r=Ut(n,t);if(a(r))return r;let o={...e,rank:r.data};return this.createNode(o),c("Created node",o)},createNode(e){let t=q(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?i("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return i("Failed to locate node");let n={...t,readonly:!0},r=q(o=>({...o,nodes:{...o.nodes,[e]:n}}));return a(r)?i(r.message):c("Locked node",n)},updateNode(e){let t=q(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?t:c("Updated node",e)},getContributor(e){return y().contributors[e]},getTag(e){return y().tags[e]},getNode(e){return y().nodes[e]},getSiblings:e=>Object.values(y().nodes).filter(t=>!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank))};var ot={autoSync:!1,preferredEditor:null,userName:null,userId:null},oe=()=>ot,it=e=>(ot={...ot,...e},ot);var hn=()=>{let e=oe(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},Rn=()=>!Oe();var B={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#2a2f45",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},Sn={accent:B.cyan,accent2:B.magenta,primary:B.white,secondary:B.grayDark,secondary2:B.grayLight,gray:B.gray,green:B.green,yellow:B.yellow,red:B.red};var f={red:B.red,yellow:B.yellow,green:B.green,blue:B.blue,magenta:B.magenta,cyan:B.cyan},st={urgent:f.red,critical:f.red,important:f.red,blocker:f.red,asap:f.red,immediate:f.red,fail:f.red,failure:f.red,broken:f.red,bug:f.red,error:f.red,incident:f.red,outage:f.red,production:f.red,crash:f.red,security:f.red,warning:f.yellow,warn:f.yellow,risky:f.yellow,risk:f.yellow,attention:f.yellow,pending:f.yellow,review:f.yellow,"needs-review":f.yellow,qa:f.yellow,testing:f.yellow,test:f.yellow,validate:f.yellow,verification:f.yellow,staging:f.yellow,check:f.yellow,"follow-up":f.yellow,followup:f.yellow,waiting:f.yellow,blocked:f.yellow,hold:f.yellow,done:f.green,complete:f.green,completed:f.green,success:f.green,ok:f.green,stable:f.green,resolved:f.green,fixed:f.green,closed:f.green,merged:f.green,released:f.green,deployed:f.green,approved:f.green,verified:f.green,working:f.green,healthy:f.green,pass:f.green,passing:f.green,info:f.blue,information:f.blue,note:f.blue,docs:f.blue,documentation:f.blue,doc:f.blue,guide:f.blue,help:f.blue,explanation:f.blue,detail:f.blue,details:f.blue,context:f.blue,design:f.blue,discussion:f.blue,proposal:f.blue,idea:f.blue,feature:f.magenta,enhancement:f.magenta,improvement:f.magenta,refactor:f.magenta,refactoring:f.magenta,cleanup:f.magenta,optimize:f.magenta,optimization:f.magenta,perf:f.magenta,performance:f.magenta,upgrade:f.magenta,migration:f.magenta,modernize:f.magenta,debt:f.magenta,todo:f.cyan,next:f.cyan,planned:f.cyan,plan:f.cyan,future:f.cyan,backlog:f.cyan,investigate:f.cyan,explore:f.cyan,prototype:f.cyan};var An=(e,t)=>{let r=R(e.id).find(o=>o.title===t);return r?R(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},Co=e=>An(e,"Tags").map(t=>E.getTag(t)).filter(t=>!!t),at=()=>{let{breadCrumb:e,selectedNode:t}=y(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!z(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Co(n)??[])},dt=()=>{let{breadCrumb:e,selectedNode:t}=y(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!z(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",ho(n)??[])},ho=e=>An(e,"Assignees").map(t=>E.getContributor(t)).filter(t=>!!t);var wn=(e,t)=>{let r=R(e.id).find(o=>o.title===t);return r&&typeof r.props?.value=="string"?tt(r.props.value):""};var Ro=/^(\d+)(h|d|w|mo|y)$/,So=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Ao=({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},wo=(e,t=new Date)=>{let n=e.match(Ro);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let d=new Date(t);switch(o){case"h":return d.setHours(d.getHours()-s),d;case"d":return d.setDate(d.getDate()-s),d;case"w":return d.setDate(d.getDate()-s*7),d;case"mo":return d.setMonth(d.getMonth()-s),d;case"y":return d.setFullYear(d.getFullYear()-s),d;default:return null}},To=e=>{let t=e.match(So);if(!t)return null;let[,n,r,o,s,d]=t,l=Number(n),u=Number(r),g=Number(o),v=s?Number(s):0,N=d?Number(d):0;return Ao({year:l,month:u,day:g,hour:v,minute:N})?new Date(l,u-1,g,v,N):null},ct=e=>{let t=e.trim().toLowerCase();return wo(t)??To(t)},Tn=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Mo=[{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}],Mn=(e=Mo)=>{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 Lo=["BOARD","TICKET","SWIMLANE"],_=e=>{let{currentNode:t,readOnly:n,selectedNode:r}=y(),o=hn().isSetup,s=t.context,d=r?.context,l=[m.SYNC,m.HELP,m.SET_VIEW,m.SET_EDITOR,m.SET_USERNAME],u=[m.NEW,m.RENAME,m.DELETE],g=[m.TAG,m.UNTAG,m.ASSIGN,m.UNASSIGN,m.CLOSE_ISSUE,m.RE_OPEN_ISSUE,m.SET_DESCRIPTION],v=[m.FILTER,m.PEEK],N={WORKSPACE:[...l,...u],BOARD:[...v,...l,...u],SWIMLANE:[...v,...l,...u],TICKET:[...l,...u,...g],FIELD:[...l,...g],FIELD_LIST:[...l,...g],TEXT:[...l]},C=d&&Lo.includes(d),S=[...N[s||"WORKSPACE"]].filter(j=>[m.RENAME,m.DELETE,m.MOVE].includes(j)?C:!0),M={[m.PEEK]:[...Mn(),"now","prev","next"],[m.SYNC]:[],[m.INIT]:[],[m.SET_USERNAME]:[],[m.SET_DESCRIPTION]:["confirm"],[m.DELETE]:["confirm"],[m.RE_OPEN_ISSUE]:["confirm"],[m.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[m.CLOSE_ISSUE]:["confirm"],[m.FILTER]:["tag","assignee","description","title","clear"],[m.SET_VIEW]:["dense","wide"],[m.SET_EDITOR]:[...xn,"vim"],[m.TAG]:[...new Set([...Object.keys(st),...E.getExistingTags()])],[m.UNTAG]:[...at()?.data?.map(({name:j})=>j)??[]],[m.UNASSIGN]:[...dt()?.data?.map(({name:j})=>j)??[]],[m.ASSIGN]:E.getExistingAssignees(),[m.HELP]:[],[m.RENAME]:[],[m.NEW]:s==="TICKET"||s==="FIELD"||s==="FIELD_LIST"?["issue","swimlane","board"]:s==="SWIMLANE"?["issue","swimlane","board"]:s==="BOARD"?["issue","swimlane","board"]:["board"],[m.NONE]:S};return o?Rn()?n&&(M={[m.NONE]:[m.HELP,m.PEEK],[m.HELP]:M[m.HELP],[m.PEEK]:M[m.PEEK]}):M={[m.NONE]:[m.HELP,m.INIT],[m.HELP]:M[m.HELP],[m.INIT]:M[m.INIT]}:M={[m.NONE]:[m.HELP,m.SET_EDITOR,m.SET_USERNAME],[m.HELP]:M[m.HELP],[m.SET_EDITOR]:M[m.SET_EDITOR],[m.SET_USERNAME]:M[m.SET_USERNAME]},M[e]??[]};import Ce from"chalk";import{decodeTime as Ln}from"ulid";var Pn=e=>{try{return c("Decoded date",new Date(Ln(e)))}catch(t){return i("Decoding failed + "+t.message)}},Bt=e=>{if(!e?.id)return null;try{return Ln(e.id)}catch{return null}};var ye=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?c("Found node",n):i("Unable to find node in breadcrumb")};import Dn from"chalk";var $t={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Po=(e,t,n)=>Math.max(t,Math.min(n,e)),Wt=(e,t,n)=>e+(t-e)*n,Fn=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Do=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,d=e/60,l=s*(1-Math.abs(d%2-1)),u=0,g=0,v=0;d>=0&&d<1?(u=s,g=l):d>=1&&d<2?(u=l,g=s):d>=2&&d<3?(g=s,v=l):d>=3&&d<4?(g=l,v=s):d>=4&&d<5?(u=l,v=s):(u=s,v=l);let N=o-s/2;return[Math.round((u+N)*255),Math.round((g+N)*255),Math.round((v+N)*255)]},Fo=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,ko=(e,t,n)=>[Math.round(Wt(e[0],t[0],n)),Math.round(Wt(e[1],t[1],n)),Math.round(Wt(e[2],t[2],n))],Oo=e=>{let n=Fn(e)%360,r=Do(n,$t.stringColor.saturation,$t.stringColor.lightness);return Fo(r)},Uo=e=>{let t=$t.gradient.stops,n=Po(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,s=Math.min(Math.floor(o),r-1),d=o-s;return ko(t[s],t[s+1],d)},lt=e=>Fn(e.toLowerCase().trim())/4294967295,_o=e=>{let t=lt(e);return Uo(t)},Bo=e=>{let[t,n,r]=_o(e);return{normal:o=>Dn.bgRgb(t,n,r).black(o),cursor:o=>Dn.bgRgb(t,n,r).white.bold(o)}};var Ht=e=>Bo(e).normal(` ${e} `),Ue=(e,t=st)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:Oo(r)};var Wo=["BOARD","TICKET","SWIMLANE"],Kt=()=>{let e=y().selectedNode;return e?.context?Wo.includes(e?.context)?k():D({message:"Command not available in this context"}):D({message:"Missing target context"})},G="<ENTER> to confirm",k=(e="",t=[])=>({message:e,validity:re.Valid,completionWordList:t}),D=({message:e,completionWordList:t=[]})=>({validity:re.Invalid,message:e,completionWordList:t}),Be=e=>e.length===0,me=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let u=[...t.filter(Boolean).filter(v=>v.startsWith(o.trim()))].sort((v,N)=>lt(v)-lt(N)).slice(0,r).map(Ht),g=u.length>s?u.join(" "):"";return g?`${e}${g}${n}`:""},Vt=({modifier:e})=>{let t="confirm";return e===t?k(G):D({message:Be(e)?`if you are certain, enter ${Ht(t)}`:"",completionWordList:[t]})},$o=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?k(G):D({message:Be(n)?t:""}),Ho=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?D({message:n}):k():D({message:Be(r)?t:""}),_e=({hint:e})=>({modifier:t,inputString:n})=>Be(t)&&Be(n)?D({message:e,completionWordList:[]}):k(G),Ko={[m.PEEK]:e=>{let t=e.modifier;if(t==="now")return k(G);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return k(G);let r=ct(t);if(!t||!r)return D(n);let o=ye(y().breadCrumb,"BOARD");if(a(o))return D({message:"Command is not applicable in this context"});let s=Pn(o.data.id);return a(s)?D({message:"Unable to peek: board id is not a valid ULID"}):Tn({date:r,horizonDate:s.data})?k(G):D({message:Ce.red(`nothing to peek before ${s.data.toISOString().slice(0,16).replace("T"," ")}`)})},[m.INIT]:()=>k(G),[m.FILTER]:e=>{if(e.modifier==="clear")return k();let t=d=>_(m.FILTER).includes(d);if(!e.modifier||!t(e.modifier??""))return D({message:me({wordList:_(m.FILTER),inputString:e.inputString}),completionWordList:_(m.FILTER)});let r=Object.values(y().tags).map(d=>d.name),o=Object.values(y().contributors).map(d=>d.name),s=e.modifier==="tag"?r:e.modifier==="assignee"?o:[];return e.inputString?s.length&&!s.includes(e.inputString.trim()??"")?D({message:me({prefix:`existing ${e.modifier}s... `,wordList:s,noOfHints:10,inputString:e.inputString}),completionWordList:s}):k():D({message:me({prefix:"one of... ",wordList:s,noOfHints:10,inputString:e.inputString}),completionWordList:s})},[m.NONE]:e=>{let t=_(m.NONE),n=/^[A-Za-z_]+:/g,r=e.inputString.match(n);return r&&r.length?t=[...t.filter(o=>o.trim().match(n))]:t=[...new Set(t.flatMap(o=>o.match(n)?.join("").replace(":","")??o))],e.command?k():D({message:me({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[m.NEW]:e=>Ho({list:_(m.NEW),hint:me({wordList:_(m.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[m.SET_DESCRIPTION]:()=>k(G),[m.HELP]:()=>k(G),[m.RENAME]:()=>{let e=Kt();return e.validity==="invalid"?e:k(G)},[m.DELETE]:e=>{let t=Kt();return t.validity==="invalid"?t:Vt(e)},[m.CLOSE_ISSUE]:e=>Vt(e),[m.RE_OPEN_ISSUE]:e=>Vt(e),[m.MOVE]:e=>{let t=Kt();return t.validity==="invalid"?t:_e({hint:me({prefix:"hey hacker! These commands are blocked for you... ",wordList:_(m.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[m.TAG]:e=>{let t=E.getExistingTags().map(n=>` ${Ce.bgHex(Ue(n))(" "+n+" ")} `).slice(0,10);return _e({hint:"tag name like... "+t.join("")})(e)},[m.UNTAG]:e=>{let t=at();if(a(t))return D({message:"Invalid untag target",completionWordList:[]});let n=t.data.map(({name:r})=>r).map(r=>` ${Ce.bgHex(Ue(r))(" "+r+" ")} `).slice(0,10);return n.length?_e({hint:" ... "+n.join("")})(e):D({message:"Issue has not tags",completionWordList:[]})},[m.ASSIGN]:e=>{let t=E.getExistingAssignees().map(n=>` ${Ce.bgHex(Ue(n))(" "+n+" ")} `).slice(0,10);return _e({hint:"assign to... "+t.join("")})(e)},[m.UNASSIGN]:e=>{let t=dt();if(a(t))return D({message:"Invalid unassign target",completionWordList:[]});let n=t.data.map(({name:r})=>r).map(r=>` ${Ce.bgHex(Ue(r))(" "+r+" ")} `).slice(0,10);return n.length?_e({hint:"remove assignee... "+n.join("")})(e):D({message:"Issue has no assignees",completionWordList:[]})},[m.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=_(m.SET_EDITOR);return e.modifier?k(G):D({message:me({wordList:t,inputString:e.inputString})})},[m.SET_USERNAME]:e=>e.inputString?k():D({message:`Enter a username. Saved in ${Ce.bgBlack("~/.epiq/")}`}),[m.SET_VIEW]:e=>$o({list:_(m.SET_VIEW),hint:me({wordList:_(m.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[m.SYNC]:()=>k(G)},kn=Object.fromEntries(Object.entries(Ko).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var On=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"];var b={Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",SetView:"set-view",SetEditor:"set-editor",SetUserName:"set-user-name",SetAutoSync:"set-auto-sync",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",Sync:"sync"};var Un=e=>Object.values(m).includes(e),_n=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:d,validity:l,completionWordList:u}=kn[n].validate(n,r,s),g=o==="command"?Object.values(m):n&&e.target==="modifier"?_(n):On;return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:d??"",autoCompletion:t?In(e,[...u,...g]):{hint:"",hints:[],remainder:"",overlap:0}}};var Bn=e=>{let t=e.trimStart(),n=jo(t),r=(n[0]??"").trimStart().trimEnd(),o=(n[1]??"").trimStart().trimEnd(),s=zo(e),d=Un(r)?r:null,l=d!==null,u=r!=="",g=e.endsWith(" "),v=d?_(d)??[]:[],N=d&&v.includes(o)?o:"",C="word";n.length<=1?C="command":n.length===2&&(C="modifier");let S=Vo(t,d,N);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:s,hasCommand:u,command:d,isCommandKeyword:l,isLastWordCompleted:g,modifier:N,target:C,inputToMatch:s,inputString:S}},Vo=(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},jo=e=>e?e.split(/\s+/):[],zo=e=>e.trimEnd().split(/\s+/).at(-1)??"";var Wn=" ",he={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:re.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},qo=new Set,$n=()=>{for(let e of qo)e()};var ie=e=>{let n=e(he),r=Bn(n.value),o=n.cursorPosition===n.value.length;he={...n,commandMeta:_n(r,o)},$n()},We=({message:e,result:t})=>{let n=structuredClone(he);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,he=n,$n(),c(e,null)},jt=e=>{ie(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},zt=e=>{ie(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&n[o-1]===" ";)o--;for(;o>0&&n[o-1]!==" ";)o--}else{for(;o<n.length&&n[o]!==" ";)o++;for(;o<n.length&&n[o]===" ";)o++}return{...t,cursorPosition:o}})},Hn=()=>{ie(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}})},Kn=()=>{ie(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&t[r-1]===" ";)r--;for(;r>0&&t[r-1]!==" ";)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},O=e=>{ie(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),d=s+o,l=Math.max(0,Math.min(s.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},Vn=()=>{ie(e=>({...e,commandIsPending:!0}))},jn=({addToHistory:e=!0})=>{ie(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),Go()},zn=()=>{ie(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}})},qn=()=>{ie(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Go=()=>O(()=>""),J=()=>he,ut=()=>{let[e,...t]=he.value.split(Wn);return t.join(Wn).trim()};var h={Sync:"sync",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",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",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};var Gn=e=>{let{context:t}=y()?.currentNode;if(!t)return b.None;switch(e){case m.INIT:return b.Init;case m.DELETE:return b.Delete;case m.SET_DESCRIPTION:return b.Edit;case m.HELP:return b.ViewHelp;case m.RE_OPEN_ISSUE:return b.ReopenIssue;case m.CLOSE_ISSUE:return b.CloseIssue;case m.TAG:return b.TagTicket;case m.UNTAG:return b.UntagTicket;case m.ASSIGN:return b.AssignUserToTicket;case m.UNASSIGN:return b.UnassignUserFromTicket;case m.RENAME:return b.Rename;case m.NEW:return b.NewItem;case m.FILTER:return b.Filter;case m.MOVE:return b.Move;case m.PEEK:return b.Peek;case m.SET_USERNAME:return b.SetUserName;case m.SET_EDITOR:return b.SetEditor;case m.SET_VIEW:return b.SetView;case m.SYNC:return b.Sync;default:return b.None}};import{ulid as F}from"ulid";import{spawnSync as ni}from"node:child_process";import ri from"node:os";import Qn from"node:path";import{ulid as oi}from"ulid";import{accessSync as Jo,copyFileSync as Yo,existsSync as mt,mkdirSync as Jn,readdirSync as Yn,readFileSync as Xo,renameSync as Qo,rmSync as Zo,statSync as Xn,unlinkSync as ei,writeFileSync as ti}from"node:fs";import Re from"node:path";var Y={writeToFile:(e,t)=>{try{let n=Re.dirname(e);mt(n)||Jn(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);ti(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Xo(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Y.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 mt(e)&&Xn(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Jo(e),!0}catch{return!1}},mkDir:e=>Jn(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Re.parse(t);for(;;){let r=Re.join(t,e);try{if(mt(r)&&Xn(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Re.dirname(t)}return null},readFirstJSON(e){try{if(!Y.dirExists(e))return null;let t=Yn(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Re.join(e,t);return Y.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Y.dirExists(e)?Yn(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{ei(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Zo(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Re.dirname(t)),!n?.overwrite&&mt(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Qo(e,t)}catch(r){if(r?.code==="EXDEV"){Yo(e,t),this.rmFile(e);return}throw r}}};function ii(){let{preferredEditor:e}=oe(),t=[e,process.env.VISUAL,process.env.EDITOR,"vim","nano"].filter(n=>!!n?.trim());return[...new Set(t)]}function si(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function Zn(e){let t=Qn.join(ri.tmpdir(),"epiq");Y.mkDir(t);let n=Qn.join(t,oi());Y.writeToFile(n,e??"");let r=ii();for(let o of r){let s=si(o,n),d=ni(s,{stdio:"inherit",shell:!0});if(!d.error&&d.status===0){let l=Y.readFile(n);if(l==null)return i("Unable to read edited file");let u=l.replace(/\r?\n$/,"");return c("Successfully edited",u)}}return i("Unable to open editor")}import yt from"node:fs";import Et from"node:path";import{z as Gt}from"zod";var pt=process.env.IS_LOCAL==="true",se=()=>".epiq";import gt from"node:fs";import pe from"node:path";import{decodeTime as ai,monotonicFactory as di}from"ulid";import{z as $e}from"zod";import ci from"node:os";var er=e=>({action:e.action,payload:e.payload});var li=pe.join(ci.homedir(),".epiq"),ui=e=>pe.resolve(e)===li,mi=e=>{let t=pe.join(e,se());return gt.existsSync(t)&&gt.statSync(t).isDirectory()&&!ui(e)},nr=1,tr=di(),pi="events",gi=$e.tuple([$e.string().min(1),$e.string().min(1).nullable()]),fi=$e.looseObject({v:$e.literal(nr),id:gi}),qt=e=>{let t=fi.safeParse(e);return t.success?c("Parsed persisted event",t.data):i(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},ft=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",W=()=>{let{userName:e,userId:t}=oe();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:ft(t),userName:ft(e)}):i("Unable to resolve actor ID from settings or OS user info"):i("User ID not configured"):i("User name not configured")},ae=(e=process.cwd())=>{let t=pe.resolve(e);for(;;){if(mi(t))return t;let n=pe.dirname(t);if(n===t)return pe.resolve(e);t=n}},rr=(e=process.cwd())=>pe.join(ae(e),se(),pi),He=({userId:e,userName:t})=>`${ft(e)}.${ft(t)}.jsonl`,vi=(e=process.cwd(),{userId:t,userName:n})=>{let r=He({userId:t,userName:n});return/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r)?c("Successfully resolved event log path",pe.join(rr(e),r)):i(`Invalid event log file name: ${r}`)},yi=(e,t)=>{let n={[e.action]:e.payload,v:nr,id:t};return qt(n)};function vt({event:e,rootDir:t=process.cwd()}){try{let n=ae(t),r=rr(n),o=vi(n,{userId:e.userId,userName:e.userName});if(a(o))return o;gt.mkdirSync(r,{recursive:!0});let s=or(n);if(a(s))return i(s.message);let d;if(s.data){let u=ai(s.data),g=Math.max(Date.now(),u+1);d=tr(g)}else d=tr();let l=yi(er(e),[d,s.data]);return a(l)?i(l.message):(gt.appendFileSync(o.data,`${JSON.stringify(l.data)}
2
+ import{McpServer as ws}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Ts}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as A}from"zod";var m={INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",RENAME:"rename",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",SET_DESCRIPTION:"edit",SET_EDITOR:"config:editor",SET_VIEW:"config:view",SET_USERNAME:"config:username",SYNC:"sync",NONE:""},re={None:"none",Invalid:"invalid",Valid:"valid"},ee={None:"none",Success:"success",Fail:"fail"},i=e=>({result:ee.Fail,message:e,data:null}),c=(e,t)=>({result:ee.Success,message:e,data:t}),fn=()=>({result:ee.None,message:"No result",data:null}),a=e=>e.result==="fail";import{ulid as so}from"ulid";import{monotonicFactory as yo,ulid as Xe}from"ulid";var Qe=yo(),Ze=({name:e,parent:t,user:{userId:n,userName:r}})=>{let o=Qe(),s=Qe(),d=Qe(),l=Qe();return[{id:Xe(),userId:n,userName:r,action:"add.issue",payload:{id:o,parent:t,name:e}},{id:Xe(),userId:n,userName:r,action:"add.field",payload:{id:s,parent:o,name:"Description",val:""}},{id:Xe(),userId:n,userName:r,action:"add.field",payload:{id:d,parent:o,name:"Assignees"}},{id:Xe(),userId:n,userName:r,action:"add.field",payload:{id:l,parent:o,name:"Tags"}}]};import Pe from"chalk";import{monotonicFactory as bs,ulid as de}from"ulid";import{useSyncExternalStore as vm}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function z(e){return e.context==="TICKET"}var p={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function et(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var tt=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var vn=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},yn=(e,t)=>t?e.get(t)??[]:[];var En=new WeakMap,Eo=e=>{let t=En.get(e);return t||(t=vn(e),En.set(e,t)),t};var Nn=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return yn(Eo(e),r).filter(s=>et(r,s)>=n)};var In=({inputToMatch:e,lastWord:t},n)=>{if(t.endsWith(" "))return{hint:"",hints:[],overlap:0,remainder:""};let r=Nn({wordList:n,inputToMatch:e,overlapThreshold:1});return No(t,r)},No=(e,t)=>{let n=t[0]??"",r=et(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),d=r<(o??"").length,l=!!s,f=(l&&d?o:n)+(l&&d?":":" "),N=f.slice(r);return{hint:f,hints:t,overlap:r,remainder:N}};var xn=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var xe=24n,Io=xe*4n,nt=(1n<<Io)-1n,xo=/^[0-9a-f]+$/;function bn(e){if(!e||!xo.test(e))throw new Error(`Invalid hex rank: ${e}`);return BigInt("0x"+e)}function rt(e,t=xe){if(e<0n)throw new Error("Negative rank not allowed");return e.toString(16).padStart(Number(t),"0")}function ke(e,t){if(!e&&!t)return rt(nt/2n,xe);let n=e?bn(e):0n,r=t?bn(t):nt;if(r<=n)return rt(nt/2n,xe);let o=(n+r)/2n;return o===n||o===r?"":rt(o,xe)}function Q(){return rt(nt/2n,xe)}var te={workspace:(e,t)=>({id:e,title:t,rank:Q(),isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r=!1)=>({id:e,title:t,rank:Q(),isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n)=>({id:e,title:t,rank:Q(),isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:(e,t,n,r={},o="horizontal")=>({id:e,title:t,rank:Q(),isDeleted:!1,props:r,context:P.FIELD,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[]}),ticket:(e,t,n)=>({id:e,title:t,rank:Q(),isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,props:r={},readonly:o=!0})=>({id:e,title:t,rank:Q(),isDeleted:!1,props:r,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[]})};var H=e=>Object.values(y().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Cn=(e,t)=>e.findIndex(n=>n.id===t),Ut=(e,t={at:"end"})=>{if(e.length===0)return c("Resolved rank",Q());switch(t.at){case"start":{let n=e[0];return n?c("Resolved rank",ke(void 0,n.rank)):i("Unable to resolve first sibling")}case"end":{let n=e[e.length-1];return n?c("Resolved rank",ke(n.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let n=Cn(e,t.sibling);if(n<0)return i("Sibling not found");let r=n>0?e[n-1]:void 0,o=e[n];return o?c("Resolved rank",ke(r?.rank,o.rank)):i("Sibling not found")}case"after":{let n=Cn(e,t.sibling);if(n<0)return i("Sibling not found");let r=e[n],o=n<e.length-1?e[n+1]:void 0;return r?c("Resolved rank",ke(r.rank,o?.rank)):i("Sibling not found")}}};var be=(e,t)=>{let{nodes:n}=y(),r=n[e];if(!r)return i("Node not found");if(r.context===t)return c("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return c("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return i(`No ancestor found for context: ${t}`)},bo=(e,t)=>{let{nodes:n}=y(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},_t=(e,t)=>e?e.readonly?i({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:i("Node not found"),E={deleteNode(e){q(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=y(),r=n[e];if(!r)return i("Edit target node not found");let o=_t(r,"edit");if(o)return o;let s={...r,props:{...r.props,value:t}};return E.updateNode(s),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return i("Rename target node not found");let r=_t(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=y();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=y();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return H(e).find(n=>n.title===t)},moveNode({id:e,parentId:t,position:n={at:"end"}}){let{rootNodeId:r}=y(),o=this.getNode(e),s=this.getNode(t);if(!o)return i("Node not found");if(!s)return i("Target parent not found");if(r===e)return i("Cannot move root node");if(e===t)return i("Cannot move node into itself");let d=_t(o,"move");if(d)return d;if(bo(t,e))return i("Cannot move node into its own descendant");let l=H(t).filter(f=>f.id!==e),u=Ut(l,n);if(a(u))return u;let v={...o,parentNodeId:t,rank:u.data};return this.updateNode(v),c("Moved node successfully",v)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=y(),o=this.getNode(e);if(!o)return i("Node not found");if(r===e)return i("Cannot delete root node");let s=new Set,d=u=>{let v=t[u];if(!(!v||s.has(u))){s.add(u);for(let f of H(v.id))d(f.id)}};d(e);let l={...structuredClone(t)};for(let u of s){if(!l[u])return i("Unable to locate node to delete");l[u]={...l[u],isDeleted:!0}}return n?(I({nodes:l}),c("Successfully tomb stoned",o)):i("Unable to delete undefined")},createContributor(e){let t=q(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?i("Unable to create contributor"):c("Created contributor",e)},assign(e,t,n){let r=E.getContributor(t),o=E.getNode(e);if(!o||!r)return i("Unable assign contributor to issue");let s=this.getFieldByTitle(o.id,"Assignees");if(!s)return i("Unable to locate assignees field");if(H(s.id).some(u=>u.props?.value===t))return i("Contributor already assigned");let l=this.createNodeAtPosition(te.field(n,r.name,s.id,{value:t}));return a(l)?l:c("Assigned contributor",l.data)},createTag(e){let t=q(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?i("Could not create tag"):c("Tag created",e)},tag(e,t,n){let r=E.getTag(t),o=E.getNode(e);if(!r)return i("Unable to add tag, missing tag");if(!o)return i("Unable to add tag, missing target");let s=this.getFieldByTitle(o.id,"Tags");if(!s)return i("Unable to locate tags field");if(H(s.id).some(u=>u.props?.value===t))return i("Tag already assigned");let l=this.createNodeAtPosition(te.field(n,r.name,s.id,{value:t}));return a(l)?l:c("Tag added",l.data)},untag(e,t){let n=E.getTag(t),r=E.getNode(e);if(!n)return i("Unable to remove tag, missing tag");if(!r)return i("Unable to remove tag, missing target");let o=this.getFieldByTitle(r.id,"Tags");if(!o)return i("Unable to locate tags field");let s=H(o.id).find(l=>l.props?.value===t);if(!s)return c("Issue is not tagged with that tag",null);let d={...s,isDeleted:!0};return this.updateNode(d),c("Tag removed",d)},unassign(e,t){let n=E.getContributor(t),r=E.getNode(e);if(!n)return i("Unable to unassign, missing contributor");if(!r)return i("Unable to unassign, missing target");let o=this.getFieldByTitle(r.id,"Assignees");if(!o)return i("Unable to locate assignees field");let s=H(o.id).find(l=>l.props?.value===t);if(!s)return c("Issue is not assigned to that contributor",null);let d={...s,isDeleted:!0};return this.updateNode(d),c("Assignee removed",d)},createNodeAtPosition(e,t={at:"end"}){if(!e.parentNodeId){let s={...e,rank:Q()};return this.createNode(s),c("Created node",s)}let n=H(e.parentNodeId),r=Ut(n,t);if(a(r))return r;let o={...e,rank:r.data};return this.createNode(o),c("Created node",o)},createNode(e){let t=q(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?i("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return i("Failed to locate node");let n={...t,readonly:!0},r=q(o=>({...o,nodes:{...o.nodes,[e]:n}}));return a(r)?i(r.message):c("Locked node",n)},updateNode(e){let t=q(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?t:c("Updated node",e)},getContributor(e){return y().contributors[e]},getTag(e){return y().tags[e]},getNode(e){return y().nodes[e]},getSiblings:e=>Object.values(y().nodes).filter(t=>!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank))};var ot={autoSync:!1,preferredEditor:null,userName:null,userId:null},oe=()=>ot,it=e=>(ot={...ot,...e},ot);var hn=()=>{let e=oe(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},Rn=()=>!Oe();var B={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#2a2f45",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},Sn={accent:B.cyan,accent2:B.magenta,primary:B.white,secondary:B.grayDark,secondary2:B.grayLight,gray:B.gray,green:B.green,yellow:B.yellow,red:B.red};var g={red:B.red,yellow:B.yellow,green:B.green,blue:B.blue,magenta:B.magenta,cyan:B.cyan},st={urgent:g.red,critical:g.red,important:g.red,blocker:g.red,asap:g.red,immediate:g.red,fail:g.red,failure:g.red,broken:g.red,bug:g.red,error:g.red,incident:g.red,outage:g.red,production:g.red,crash:g.red,security:g.red,warning:g.yellow,warn:g.yellow,risky:g.yellow,risk:g.yellow,attention:g.yellow,pending:g.yellow,review:g.yellow,"needs-review":g.yellow,qa:g.yellow,testing:g.yellow,test:g.yellow,validate:g.yellow,verification:g.yellow,staging:g.yellow,check:g.yellow,"follow-up":g.yellow,followup:g.yellow,waiting:g.yellow,blocked:g.yellow,hold:g.yellow,done:g.green,complete:g.green,completed:g.green,success:g.green,ok:g.green,stable:g.green,resolved:g.green,fixed:g.green,closed:g.green,merged:g.green,released:g.green,deployed:g.green,approved:g.green,verified:g.green,working:g.green,healthy:g.green,pass:g.green,passing:g.green,info:g.blue,information:g.blue,note:g.blue,docs:g.blue,documentation:g.blue,doc:g.blue,guide:g.blue,help:g.blue,explanation:g.blue,detail:g.blue,details:g.blue,context:g.blue,design:g.blue,discussion:g.blue,proposal:g.blue,idea:g.blue,feature:g.magenta,enhancement:g.magenta,improvement:g.magenta,refactor:g.magenta,refactoring:g.magenta,cleanup:g.magenta,optimize:g.magenta,optimization:g.magenta,perf:g.magenta,performance:g.magenta,upgrade:g.magenta,migration:g.magenta,modernize:g.magenta,debt:g.magenta,todo:g.cyan,next:g.cyan,planned:g.cyan,plan:g.cyan,future:g.cyan,backlog:g.cyan,investigate:g.cyan,explore:g.cyan,prototype:g.cyan};var An=(e,t)=>{let r=R(e.id).find(o=>o.title===t);return r?R(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},Co=e=>An(e,"Tags").map(t=>E.getTag(t)).filter(t=>!!t),at=()=>{let{breadCrumb:e,selectedNode:t}=y(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!z(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Co(n)??[])},dt=()=>{let{breadCrumb:e,selectedNode:t}=y(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!z(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",ho(n)??[])},ho=e=>An(e,"Assignees").map(t=>E.getContributor(t)).filter(t=>!!t);var wn=(e,t)=>{let r=R(e.id).find(o=>o.title===t);return r&&typeof r.props?.value=="string"?tt(r.props.value):""};var Ro=/^(\d+)(h|d|w|mo|y)$/,So=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Ao=({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},wo=(e,t=new Date)=>{let n=e.match(Ro);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let d=new Date(t);switch(o){case"h":return d.setHours(d.getHours()-s),d;case"d":return d.setDate(d.getDate()-s),d;case"w":return d.setDate(d.getDate()-s*7),d;case"mo":return d.setMonth(d.getMonth()-s),d;case"y":return d.setFullYear(d.getFullYear()-s),d;default:return null}},To=e=>{let t=e.match(So);if(!t)return null;let[,n,r,o,s,d]=t,l=Number(n),u=Number(r),v=Number(o),f=s?Number(s):0,N=d?Number(d):0;return Ao({year:l,month:u,day:v,hour:f,minute:N})?new Date(l,u-1,v,f,N):null},ct=e=>{let t=e.trim().toLowerCase();return wo(t)??To(t)},Tn=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Mo=[{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}],Mn=(e=Mo)=>{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 Lo=["BOARD","TICKET","SWIMLANE"],_=e=>{let{currentNode:t,readOnly:n,selectedNode:r}=y(),o=hn().isSetup,s=t.context,d=r?.context,l=[m.SYNC,m.HELP,m.SET_VIEW,m.SET_EDITOR,m.SET_USERNAME],u=[m.NEW,m.RENAME,m.DELETE],v=[m.TAG,m.UNTAG,m.ASSIGN,m.UNASSIGN,m.CLOSE_ISSUE,m.RE_OPEN_ISSUE,m.SET_DESCRIPTION],f=[m.FILTER,m.PEEK],N={WORKSPACE:[...l,...u],BOARD:[...f,...l,...u],SWIMLANE:[...f,...l,...u],TICKET:[...l,...u,...v],FIELD:[...l,...v],FIELD_LIST:[...l,...v],TEXT:[...l]},C=d&&Lo.includes(d),S=[...N[s||"WORKSPACE"]].filter(j=>[m.RENAME,m.DELETE,m.MOVE].includes(j)?C:!0),M={[m.PEEK]:[...Mn(),"now","prev","next"],[m.SYNC]:[],[m.INIT]:[],[m.SET_USERNAME]:[],[m.SET_DESCRIPTION]:["confirm"],[m.DELETE]:["confirm"],[m.RE_OPEN_ISSUE]:["confirm"],[m.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[m.CLOSE_ISSUE]:["confirm"],[m.FILTER]:["tag","assignee","description","title","clear"],[m.SET_VIEW]:["dense","wide"],[m.SET_EDITOR]:[...xn,"vim"],[m.TAG]:[...new Set([...Object.keys(st),...E.getExistingTags()])],[m.UNTAG]:[...at()?.data?.map(({name:j})=>j)??[]],[m.UNASSIGN]:[...dt()?.data?.map(({name:j})=>j)??[]],[m.ASSIGN]:E.getExistingAssignees(),[m.HELP]:[],[m.RENAME]:[],[m.NEW]:s==="TICKET"||s==="FIELD"||s==="FIELD_LIST"?["issue","swimlane","board"]:s==="SWIMLANE"?["issue","swimlane","board"]:s==="BOARD"?["issue","swimlane","board"]:["board"],[m.NONE]:S};return o?Rn()?n&&(M={[m.NONE]:[m.HELP,m.PEEK],[m.HELP]:M[m.HELP],[m.PEEK]:M[m.PEEK]}):M={[m.NONE]:[m.HELP,m.INIT],[m.HELP]:M[m.HELP],[m.INIT]:M[m.INIT]}:M={[m.NONE]:[m.HELP,m.SET_EDITOR,m.SET_USERNAME],[m.HELP]:M[m.HELP],[m.SET_EDITOR]:M[m.SET_EDITOR],[m.SET_USERNAME]:M[m.SET_USERNAME]},M[e]??[]};import Ce from"chalk";import{decodeTime as Ln}from"ulid";var Pn=e=>{try{return c("Decoded date",new Date(Ln(e)))}catch(t){return i("Decoding failed + "+t.message)}},Bt=e=>{if(!e?.id)return null;try{return Ln(e.id)}catch{return null}};var ye=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?c("Found node",n):i("Unable to find node in breadcrumb")};import Dn from"chalk";var $t={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Po=(e,t,n)=>Math.max(t,Math.min(n,e)),Wt=(e,t,n)=>e+(t-e)*n,Fn=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Do=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,d=e/60,l=s*(1-Math.abs(d%2-1)),u=0,v=0,f=0;d>=0&&d<1?(u=s,v=l):d>=1&&d<2?(u=l,v=s):d>=2&&d<3?(v=s,f=l):d>=3&&d<4?(v=l,f=s):d>=4&&d<5?(u=l,f=s):(u=s,f=l);let N=o-s/2;return[Math.round((u+N)*255),Math.round((v+N)*255),Math.round((f+N)*255)]},Fo=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,ko=(e,t,n)=>[Math.round(Wt(e[0],t[0],n)),Math.round(Wt(e[1],t[1],n)),Math.round(Wt(e[2],t[2],n))],Oo=e=>{let n=Fn(e)%360,r=Do(n,$t.stringColor.saturation,$t.stringColor.lightness);return Fo(r)},Uo=e=>{let t=$t.gradient.stops,n=Po(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,s=Math.min(Math.floor(o),r-1),d=o-s;return ko(t[s],t[s+1],d)},lt=e=>Fn(e.toLowerCase().trim())/4294967295,_o=e=>{let t=lt(e);return Uo(t)},Bo=e=>{let[t,n,r]=_o(e);return{normal:o=>Dn.bgRgb(t,n,r).black(o),cursor:o=>Dn.bgRgb(t,n,r).white.bold(o)}};var Ht=e=>Bo(e).normal(` ${e} `),Ue=(e,t=st)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:Oo(r)};var Wo=["BOARD","TICKET","SWIMLANE"],Kt=()=>{let e=y().selectedNode;return e?.context?Wo.includes(e?.context)?k():D({message:"Command not available in this context"}):D({message:"Missing target context"})},G="<ENTER> to confirm",k=(e="",t=[])=>({message:e,validity:re.Valid,completionWordList:t}),D=({message:e,completionWordList:t=[]})=>({validity:re.Invalid,message:e,completionWordList:t}),Be=e=>e.length===0,me=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let u=[...t.filter(Boolean).filter(f=>f.startsWith(o.trim()))].sort((f,N)=>lt(f)-lt(N)).slice(0,r).map(Ht),v=u.length>s?u.join(" "):"";return v?`${e}${v}${n}`:""},Vt=({modifier:e})=>{let t="confirm";return e===t?k(G):D({message:Be(e)?`if you are certain, enter ${Ht(t)}`:"",completionWordList:[t]})},$o=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?k(G):D({message:Be(n)?t:""}),Ho=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?D({message:n}):k():D({message:Be(r)?t:""}),_e=({hint:e})=>({modifier:t,inputString:n})=>Be(t)&&Be(n)?D({message:e,completionWordList:[]}):k(G),Ko={[m.PEEK]:e=>{let t=e.modifier;if(t==="now")return k(G);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return k(G);let r=ct(t);if(!t||!r)return D(n);let o=ye(y().breadCrumb,"BOARD");if(a(o))return D({message:"Command is not applicable in this context"});let s=Pn(o.data.id);return a(s)?D({message:"Unable to peek: board id is not a valid ULID"}):Tn({date:r,horizonDate:s.data})?k(G):D({message:Ce.red(`nothing to peek before ${s.data.toISOString().slice(0,16).replace("T"," ")}`)})},[m.INIT]:()=>k(G),[m.FILTER]:e=>{if(e.modifier==="clear")return k();let t=d=>_(m.FILTER).includes(d);if(!e.modifier||!t(e.modifier??""))return D({message:me({wordList:_(m.FILTER),inputString:e.inputString}),completionWordList:_(m.FILTER)});let r=Object.values(y().tags).map(d=>d.name),o=Object.values(y().contributors).map(d=>d.name),s=e.modifier==="tag"?r:e.modifier==="assignee"?o:[];return e.inputString?s.length&&!s.includes(e.inputString.trim()??"")?D({message:me({prefix:`existing ${e.modifier}s... `,wordList:s,noOfHints:10,inputString:e.inputString}),completionWordList:s}):k():D({message:me({prefix:"one of... ",wordList:s,noOfHints:10,inputString:e.inputString}),completionWordList:s})},[m.NONE]:e=>{let t=_(m.NONE),n=/^[A-Za-z_]+:/g,r=e.inputString.match(n);return r&&r.length?t=[...t.filter(o=>o.trim().match(n))]:t=[...new Set(t.flatMap(o=>o.match(n)?.join("").replace(":","")??o))],e.command?k():D({message:me({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[m.NEW]:e=>Ho({list:_(m.NEW),hint:me({wordList:_(m.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[m.SET_DESCRIPTION]:()=>k(G),[m.HELP]:()=>k(G),[m.RENAME]:()=>{let e=Kt();return e.validity==="invalid"?e:k(G)},[m.DELETE]:e=>{let t=Kt();return t.validity==="invalid"?t:Vt(e)},[m.CLOSE_ISSUE]:e=>Vt(e),[m.RE_OPEN_ISSUE]:e=>Vt(e),[m.MOVE]:e=>{let t=Kt();return t.validity==="invalid"?t:_e({hint:me({prefix:"hey hacker! These commands are blocked for you... ",wordList:_(m.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[m.TAG]:e=>{let t=E.getExistingTags().map(n=>` ${Ce.bgHex(Ue(n))(" "+n+" ")} `).slice(0,10);return _e({hint:"tag name like... "+t.join("")})(e)},[m.UNTAG]:e=>{let t=at();if(a(t))return D({message:"Invalid untag target",completionWordList:[]});let n=t.data.map(({name:r})=>r).map(r=>` ${Ce.bgHex(Ue(r))(" "+r+" ")} `).slice(0,10);return n.length?_e({hint:" ... "+n.join("")})(e):D({message:"Issue has not tags",completionWordList:[]})},[m.ASSIGN]:e=>{let t=E.getExistingAssignees().map(n=>` ${Ce.bgHex(Ue(n))(" "+n+" ")} `).slice(0,10);return _e({hint:"assign to... "+t.join("")})(e)},[m.UNASSIGN]:e=>{let t=dt();if(a(t))return D({message:"Invalid unassign target",completionWordList:[]});let n=t.data.map(({name:r})=>r).map(r=>` ${Ce.bgHex(Ue(r))(" "+r+" ")} `).slice(0,10);return n.length?_e({hint:"remove assignee... "+n.join("")})(e):D({message:"Issue has no assignees",completionWordList:[]})},[m.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=_(m.SET_EDITOR);return e.modifier?k(G):D({message:me({wordList:t,inputString:e.inputString})})},[m.SET_USERNAME]:e=>e.inputString?k():D({message:`Enter a username. Saved in ${Ce.bgBlack("~/.epiq/")}`}),[m.SET_VIEW]:e=>$o({list:_(m.SET_VIEW),hint:me({wordList:_(m.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[m.SYNC]:()=>k(G)},kn=Object.fromEntries(Object.entries(Ko).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var On=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"];var b={Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",SetView:"set-view",SetEditor:"set-editor",SetUserName:"set-user-name",SetAutoSync:"set-auto-sync",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",Sync:"sync"};var Un=e=>Object.values(m).includes(e),_n=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:d,validity:l,completionWordList:u}=kn[n].validate(n,r,s),v=o==="command"?Object.values(m):n&&e.target==="modifier"?_(n):On;return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:d??"",autoCompletion:t?In(e,[...u,...v]):{hint:"",hints:[],remainder:"",overlap:0}}};var Bn=e=>{let t=e.trimStart(),n=jo(t),r=(n[0]??"").trimStart().trimEnd(),o=(n[1]??"").trimStart().trimEnd(),s=zo(e),d=Un(r)?r:null,l=d!==null,u=r!=="",v=e.endsWith(" "),f=d?_(d)??[]:[],N=d&&f.includes(o)?o:"",C="word";n.length<=1?C="command":n.length===2&&(C="modifier");let S=Vo(t,d,N);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:s,hasCommand:u,command:d,isCommandKeyword:l,isLastWordCompleted:v,modifier:N,target:C,inputToMatch:s,inputString:S}},Vo=(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},jo=e=>e?e.split(/\s+/):[],zo=e=>e.trimEnd().split(/\s+/).at(-1)??"";var Wn=" ",he={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:re.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},qo=new Set,$n=()=>{for(let e of qo)e()};var ie=e=>{let n=e(he),r=Bn(n.value),o=n.cursorPosition===n.value.length;he={...n,commandMeta:_n(r,o)},$n()},We=({message:e,result:t})=>{let n=structuredClone(he);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,he=n,$n(),c(e,null)},jt=e=>{ie(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},zt=e=>{ie(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&n[o-1]===" ";)o--;for(;o>0&&n[o-1]!==" ";)o--}else{for(;o<n.length&&n[o]!==" ";)o++;for(;o<n.length&&n[o]===" ";)o++}return{...t,cursorPosition:o}})},Hn=()=>{ie(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}})},Kn=()=>{ie(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&t[r-1]===" ";)r--;for(;r>0&&t[r-1]!==" ";)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},O=e=>{ie(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),d=s+o,l=Math.max(0,Math.min(s.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},Vn=()=>{ie(e=>({...e,commandIsPending:!0}))},jn=({addToHistory:e=!0})=>{ie(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),Go()},zn=()=>{ie(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}})},qn=()=>{ie(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Go=()=>O(()=>""),J=()=>he,ut=()=>{let[e,...t]=he.value.split(Wn);return t.join(Wn).trim()};var h={Sync:"sync",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",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",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};var Gn=e=>{let{context:t}=y()?.currentNode;if(!t)return b.None;switch(e){case m.INIT:return b.Init;case m.DELETE:return b.Delete;case m.SET_DESCRIPTION:return b.Edit;case m.HELP:return b.ViewHelp;case m.RE_OPEN_ISSUE:return b.ReopenIssue;case m.CLOSE_ISSUE:return b.CloseIssue;case m.TAG:return b.TagTicket;case m.UNTAG:return b.UntagTicket;case m.ASSIGN:return b.AssignUserToTicket;case m.UNASSIGN:return b.UnassignUserFromTicket;case m.RENAME:return b.Rename;case m.NEW:return b.NewItem;case m.FILTER:return b.Filter;case m.MOVE:return b.Move;case m.PEEK:return b.Peek;case m.SET_USERNAME:return b.SetUserName;case m.SET_EDITOR:return b.SetEditor;case m.SET_VIEW:return b.SetView;case m.SYNC:return b.Sync;default:return b.None}};import{ulid as F}from"ulid";import{spawnSync as ni}from"node:child_process";import ri from"node:os";import Qn from"node:path";import{ulid as oi}from"ulid";import{accessSync as Jo,copyFileSync as Yo,existsSync as mt,mkdirSync as Jn,readdirSync as Yn,readFileSync as Xo,renameSync as Qo,rmSync as Zo,statSync as Xn,unlinkSync as ei,writeFileSync as ti}from"node:fs";import Re from"node:path";var Y={writeToFile:(e,t)=>{try{let n=Re.dirname(e);mt(n)||Jn(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);ti(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Xo(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Y.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 mt(e)&&Xn(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Jo(e),!0}catch{return!1}},mkDir:e=>Jn(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Re.parse(t);for(;;){let r=Re.join(t,e);try{if(mt(r)&&Xn(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Re.dirname(t)}return null},readFirstJSON(e){try{if(!Y.dirExists(e))return null;let t=Yn(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Re.join(e,t);return Y.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Y.dirExists(e)?Yn(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{ei(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Zo(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Re.dirname(t)),!n?.overwrite&&mt(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Qo(e,t)}catch(r){if(r?.code==="EXDEV"){Yo(e,t),this.rmFile(e);return}throw r}}};function ii(){let{preferredEditor:e}=oe(),t=[e,process.env.VISUAL,process.env.EDITOR,"vim","nano"].filter(n=>!!n?.trim());return[...new Set(t)]}function si(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function Zn(e){let t=Qn.join(ri.tmpdir(),"epiq");Y.mkDir(t);let n=Qn.join(t,oi());Y.writeToFile(n,e??"");let r=ii();for(let o of r){let s=si(o,n),d=ni(s,{stdio:"inherit",shell:!0});if(!d.error&&d.status===0){let l=Y.readFile(n);if(l==null)return i("Unable to read edited file");let u=l.replace(/\r?\n$/,"");return c("Successfully edited",u)}}return i("Unable to open editor")}import yt from"node:fs";import Et from"node:path";import{z as Gt}from"zod";var pt=process.env.IS_LOCAL==="true",se=()=>".epiq";import gt from"node:fs";import ai from"node:os";import pe from"node:path";import{decodeTime as di,monotonicFactory as ci}from"ulid";import{z as $e}from"zod";var er=e=>({action:e.action,payload:e.payload});var li=pe.resolve(ai.homedir(),".epiq"),nr=1,tr=ci(),ui="events",mi=$e.tuple([$e.string().min(1),$e.string().min(1).nullable()]),pi=$e.looseObject({v:$e.literal(nr),id:mi}),qt=e=>{let t=pi.safeParse(e);return t.success?c("Parsed persisted event",t.data):i(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},ft=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",W=()=>{let{userName:e,userId:t}=oe();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:ft(t),userName:ft(e)}):i("Unable to resolve actor ID from settings or OS user info"):i("User ID not configured"):i("User name not configured")},gi=e=>pe.resolve(e)===li,fi=e=>{let t=pe.join(e,se());return!gi(t)&&gt.existsSync(t)&&gt.statSync(t).isDirectory()},ae=e=>{let t=pe.resolve(e);for(;;){if(fi(t))return t;let n=pe.dirname(t);if(n===t)return pe.resolve(e);t=n}},rr=e=>pe.join(ae(e),se(),ui),He=({userId:e,userName:t})=>`${ft(e)}.${ft(t)}.jsonl`,vi=(e,{userId:t,userName:n})=>{let r=He({userId:t,userName:n});return/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r)?c("Successfully resolved event log path",pe.join(rr(e),r)):i(`Invalid event log file name: ${r}`)},yi=(e,t)=>{let n={[e.action]:e.payload,v:nr,id:t};return qt(n)};function vt({event:e,rootDir:t=process.cwd()}){try{let n=ae(t),r=rr(n),o=vi(n,{userId:e.userId,userName:e.userName});if(a(o))return o;gt.mkdirSync(r,{recursive:!0});let s=or(n);if(a(s))return i(s.message);let d=s.data?tr(Math.max(Date.now(),di(s.data)+1)):tr(),l=yi(er(e),[d,s.data]);return a(l)?i(l.message):(gt.appendFileSync(o.data,`${JSON.stringify(l.data)}
3
3
  `,"utf8"),c("Event persisted",{path:o.data,entry:l.data}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return i(`Failed to persist event: ${r}`)}}import{decodeTime as Ei}from"ulid";var Ni=se(),Ii="events",xi=Gt.object({userId:Gt.string().min(1).default("unknown"),userName:Gt.string().min(1).default("unknown")}),bi=(e=process.cwd())=>Et.join(ae(e),Ni,Ii),Ci=e=>{let[t,n]=Et.basename(e,".jsonl").split("."),r=xi.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):i(`Invalid event file name ${Et.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},hi=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?i(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?i("Invalid persisted event: action key is missing or invalid"):c("Resolved persisted action",t[0])},Ri=(e,t)=>t in e,Si=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Ai=e=>{let{userId:t,userName:n,...r}=e,o=hi(r);if(a(o))return i(o.message);let s=o.data,d=e.id?.[0];return d?Ri(r,s)?c("Decoded persisted event",Si({id:d,action:s,payload:r[s],userId:t,userName:n})):i(`Persisted event is missing payload for action: ${s}`):i("Persisted event is missing id")},Nt=e=>{if(!yt.existsSync(e))return c("Event file missing",[]);let t=Ci(e);if(a(t))return i(t.message);let n=yt.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
4
- `)){let s=o.trim();if(!s)continue;let d;try{d=JSON.parse(s)}catch{return i(`Failed to parse event JSON from ${e}: ${s}`)}let l=qt(d);if(a(l))return i(`${l.message} in ${e}: ${s}`);r.push({...l.data,userId:t.data.userId,userName:t.data.userName})}return c("Parsed persisted events file",r)};function ir(e=process.cwd()){let t=bi(e);if(!yt.existsSync(t))return i("No events found");let n=yt.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Et.join(t,o)),r=[];for(let o of n){let s=Nt(o);if(a(s))return i(s.message);r.push(...s.data)}return c("All events loaded",wi(r))}function Ke(e=process.cwd()){let t=ir(e);if(a(t))return i(t.message);let n=[];for(let r of t.data){let o=Ai(r);if(a(o))return i(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);n.push(o.data)}return c("Loaded merged events",n)}function or(e=process.cwd()){let t=ir(e);return a(t)?i(t.message):c("Loaded edge reference",t.data.at(-1)?.id?.[0]??null)}var wi=e=>{let t=new Map(e.map(l=>[l.id[0],l])),n=new Map;for(let l of e){let u=l.id[1],g=n.get(u)??[];g.push(l),n.set(u,g)}for(let l of n.values())l.sort((u,g)=>{let[v]=u.id,[N]=g.id;return v.localeCompare(N)});let r=[],o=new Set,s=l=>{let u=n.get(l)??[];for(let g of u){let[v]=g.id;o.has(v)||(o.add(v),r.push(g),s(v))}};s(null);let d=[...e].filter(l=>{let[u]=l.id;return!o.has(u)}).sort((l,u)=>{let[g,v]=l.id,[N,C]=u.id,S=v===null||t.has(v),M=C===null||t.has(C);if(S&&!M)return-1;if(!S&&M)return 1;let j=(v??"").localeCompare(C??"");return j!==0?j:g.localeCompare(N)});return[...r,...d]},sr=(e,t)=>{let n=e.findIndex(r=>{try{return Ei(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var ar=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)return r.payload.parent}return null};var Ti=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[Z,It]=Ti;var w=(e,t)=>i(`${t.split(".").join(" ")+" failed, "+e.toLowerCase()}`),Mi={"init.workspace":({action:e,payload:t})=>{let{id:n,name:r}=t,o=te.workspace(n,r);Jt(o);let s=E.createNodeAtPosition(o);return a(s)?w(s.message??"Failed to initialize workspace",e):c("Workspace initialized",{action:e,result:s.data})},"add.workspace":({action:e,payload:t})=>{let{id:n,name:r}=t,o=te.workspace(n,r),s=E.createNodeAtPosition(o);return a(s)?w(s.message??"Failed to add workspace",e):c("Added workspace",{action:e,result:s.data})},"add.board":({action:e,payload:t})=>{let{id:n,name:r,parent:o}=t,s=E.createNodeAtPosition(te.board(n,r,o));return a(s)?w(s.message??"Unable to create board",e):c("Added board",{action:e,result:s.data})},"add.swimlane":({action:e,payload:t})=>{let{id:n,name:r,parent:o}=t,s=E.createNodeAtPosition(te.swimlane(n,r,o));return a(s)?w(s.message??"Unable to create swimlane",e):c("Added swimlane",{action:e,result:s.data})},"add.issue":({action:e,payload:t})=>{let{id:n,name:r,parent:o}=t,s=E.createNodeAtPosition(te.ticket(n,r,o));return a(s)?w(s.message??"Unable to create issue",e):c("Added issue",{action:e,result:s.data})},"add.field":({action:e,payload:t})=>{let{id:n,name:r,parent:o,val:s}=t,d=E.createNodeAtPosition(te.field(n,r,o,{value:s},r.includes("Description")?"vertical":"horizontal"));return a(d)?w(d.message??`Unable to create field: ${r}`,e):c("Added field",{action:e,result:d.data})},"edit.title":({action:e,payload:t})=>{let{id:n,name:r}=t;if(!E.getNode(n))return w("Unable to locate node",e);let s=E.renameNode(n,r);return a(s)?w(s.message??"Unable to edit title",e):c("Edited title",{action:e,result:s.data})},"delete.node":({action:e,payload:t})=>{let{id:n}=t,r=E.tombstoneNode(n);return a(r)?w(r.message??"Unable to delete node",e):c("Deleted node",{action:e,result:r.data})},"create.tag":({action:e,payload:t})=>{let{id:n,name:r}=t,o=E.createTag({id:n,name:r});return a(o)?w(o.message??"Unable to create tag",e):c("Tag added",{action:e,result:o.data})},"create.contributor":({action:e,payload:t})=>{let{id:n,name:r}=t,o=E.createContributor({id:n,name:r});return a(o)?w(o.message??"Unable to create contributor",e):c("Contributor created",{action:e,result:o.data})},"tag.issue":({action:e,payload:t})=>{let{id:n,target:r,tagId:o}=t,s=E.tag(r,o,n);return a(s)?w(s.message??"Unable to tag issue",e):c("Issue tagged",{action:e,result:s.data})},"untag.issue":({action:e,payload:t})=>{let{target:n,tagId:r}=t,o=E.untag(n,r);return a(o)?w(o.message??"Unable to untag ",e):c("Issue untagged",{action:e,result:o.data})},"assign.issue":({action:e,payload:t})=>{let{id:n,contributor:r,target:o}=t,s=E.assign(o,r,n);return a(s)?w(s.message??"Unable to assign issue",e):c("Assigned successfully",{action:e,result:s.data})},"unassign.issue":({action:e,payload:t})=>{let{target:n,contributor:r}=t,o=E.unassign(n,r);return a(o)?w(o.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e,result:o.data})},"move.node":({action:e,payload:t})=>{let{id:n,parent:r,pos:o}=t,s=E.moveNode({id:n,parentId:r,position:o});return a(s)?w(s.message??"Failed to move node",e):c("Moved node",{action:e,result:s.data})},"edit.description":({action:e,payload:t})=>{let{id:n,md:r}=t,o=E.editValue(n,r);return a(o)?w(o.message??"Unable to edit description",e):c("Set node value",{action:e,result:o.data})},"close.issue":({action:e,payload:t})=>{let{id:n}=t,r=E.getNode(n);if(!r)return w("Unable to locate issue",e);if(!z(r))return w("Can only close issues",e);let o=E.getNode(Z);if(!o)return w("Unable to locate target swimlane",e);if(o.id===r.parentNodeId)return w("Cannot close closed issue",e);let d=E.moveNode({id:n,parentId:o.id});return a(d)?w(d.message??"Unable to close issue",e):c("Issue closed",{action:e,result:d.data})},"reopen.issue":({action:e,payload:t})=>{let{id:n}=t,r=E.getNode(n);if(!r)return w("Unable to locate issue",e);if(!z(r))return w("Can only reopen issues",e);let o=E.getNode(Z);if(!o)return w("Unable to locate closed swimlane",e);if(!(r.parentNodeId===o.id))return w("Issue is not closed",e);let d=ar(r);if(!d)return w("Unable to resolve previous parent from issue history",e);if(d===o.id)return w("Previous parent resolves to closed swimlane",e);if(!E.getNode(d))return w("Previous parent no longer exists",e);let u=E.moveNode({id:n,parentId:d});return a(u)?w(u.message??"Unable to reopen issue",e):c("Issue reopened",{action:e,result:u.data})},"lock.node":({action:e,payload:t})=>{let{id:n}=t,r=E.lockNode(n);return a(r)?w(r.message??"Unable to lock node",e):c("Node locked",{action:e,result:r.data})}},Li=(e,t)=>{let n=E.getNode(e);n&&E.updateNode({...n,log:[...n.log??[],t]})},Pi=e=>{switch(e.action){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"delete.node":case"move.node":case"close.issue":case"reopen.issue":return[e.payload.id];case"edit.description":let t=[e.payload.id],n=y().nodes[e.payload.id]?.parentNodeId;return n&&t.push(n),t;case"tag.issue":case"untag.issue":case"assign.issue":case"unassign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function Se(e,t=!1){let n=Mi[e.action](e);if(a(n))return n;t||([...new Set(Pi(e))].forEach(d=>Li(d,e)),q(d=>({...d,eventLog:[...d.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?w("Invalid user ID format",e.action):(E.createContributor({name:o,id:r}),n)}var Ee=e=>e.map(t=>Se(t));function $(e){let t=Se(e);if(t.result!==ee.Success)return t;let n=vt({event:e});return a(n)?n:t}function Ae(e){return e.map(t=>$(t))}import qe from"node:fs";import{spawn as ki}from"node:child_process";import Xt from"node:fs";import we from"node:path";var Ve=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let d=r(...s);if(!n.has(d)){let l=e(...s).then(u=>(a(u)&&n.delete(d),u));n.set(d,l)}return n.get(d)});return o.clear=()=>n.clear(),o};import je from"fs";import cr from"path";import Di from"util";var dr=1e3,lr=(e=process.cwd())=>cr.join(ae(e),se(),"log","epiq.log");function Fi(e=process.cwd()){if(!pt)return;let t=lr(e);if(!je.existsSync(t))return;let r=je.readFileSync(t,"utf8").split(`
4
+ `)){let s=o.trim();if(!s)continue;let d;try{d=JSON.parse(s)}catch{return i(`Failed to parse event JSON from ${e}: ${s}`)}let l=qt(d);if(a(l))return i(`${l.message} in ${e}: ${s}`);r.push({...l.data,userId:t.data.userId,userName:t.data.userName})}return c("Parsed persisted events file",r)};function ir(e=process.cwd()){let t=bi(e);if(!yt.existsSync(t))return i("No events found");let n=yt.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Et.join(t,o)),r=[];for(let o of n){let s=Nt(o);if(a(s))return i(s.message);r.push(...s.data)}return c("All events loaded",wi(r))}function Ke(e=process.cwd()){let t=ir(e);if(a(t))return i(t.message);let n=[];for(let r of t.data){let o=Ai(r);if(a(o))return i(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);n.push(o.data)}return c("Loaded merged events",n)}function or(e=process.cwd()){let t=ir(e);return a(t)?i(t.message):c("Loaded edge reference",t.data.at(-1)?.id?.[0]??null)}var wi=e=>{let t=new Map(e.map(l=>[l.id[0],l])),n=new Map;for(let l of e){let u=l.id[1],v=n.get(u)??[];v.push(l),n.set(u,v)}for(let l of n.values())l.sort((u,v)=>{let[f]=u.id,[N]=v.id;return f.localeCompare(N)});let r=[],o=new Set,s=l=>{let u=n.get(l)??[];for(let v of u){let[f]=v.id;o.has(f)||(o.add(f),r.push(v),s(f))}};s(null);let d=[...e].filter(l=>{let[u]=l.id;return!o.has(u)}).sort((l,u)=>{let[v,f]=l.id,[N,C]=u.id,S=f===null||t.has(f),M=C===null||t.has(C);if(S&&!M)return-1;if(!S&&M)return 1;let j=(f??"").localeCompare(C??"");return j!==0?j:v.localeCompare(N)});return[...r,...d]},sr=(e,t)=>{let n=e.findIndex(r=>{try{return Ei(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var ar=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)return r.payload.parent}return null};var Ti=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[Z,It]=Ti;var w=(e,t)=>i(`${t.split(".").join(" ")+" failed, "+e.toLowerCase()}`),Mi={"init.workspace":({action:e,payload:t})=>{let{id:n,name:r}=t,o=te.workspace(n,r);Jt(o);let s=E.createNodeAtPosition(o);return a(s)?w(s.message??"Failed to initialize workspace",e):c("Workspace initialized",{action:e,result:s.data})},"add.workspace":({action:e,payload:t})=>{let{id:n,name:r}=t,o=te.workspace(n,r),s=E.createNodeAtPosition(o);return a(s)?w(s.message??"Failed to add workspace",e):c("Added workspace",{action:e,result:s.data})},"add.board":({action:e,payload:t})=>{let{id:n,name:r,parent:o}=t,s=E.createNodeAtPosition(te.board(n,r,o));return a(s)?w(s.message??"Unable to create board",e):c("Added board",{action:e,result:s.data})},"add.swimlane":({action:e,payload:t})=>{let{id:n,name:r,parent:o}=t,s=E.createNodeAtPosition(te.swimlane(n,r,o));return a(s)?w(s.message??"Unable to create swimlane",e):c("Added swimlane",{action:e,result:s.data})},"add.issue":({action:e,payload:t})=>{let{id:n,name:r,parent:o}=t,s=E.createNodeAtPosition(te.ticket(n,r,o));return a(s)?w(s.message??"Unable to create issue",e):c("Added issue",{action:e,result:s.data})},"add.field":({action:e,payload:t})=>{let{id:n,name:r,parent:o,val:s}=t,d=E.createNodeAtPosition(te.field(n,r,o,{value:s},r.includes("Description")?"vertical":"horizontal"));return a(d)?w(d.message??`Unable to create field: ${r}`,e):c("Added field",{action:e,result:d.data})},"edit.title":({action:e,payload:t})=>{let{id:n,name:r}=t;if(!E.getNode(n))return w("Unable to locate node",e);let s=E.renameNode(n,r);return a(s)?w(s.message??"Unable to edit title",e):c("Edited title",{action:e,result:s.data})},"delete.node":({action:e,payload:t})=>{let{id:n}=t,r=E.tombstoneNode(n);return a(r)?w(r.message??"Unable to delete node",e):c("Deleted node",{action:e,result:r.data})},"create.tag":({action:e,payload:t})=>{let{id:n,name:r}=t,o=E.createTag({id:n,name:r});return a(o)?w(o.message??"Unable to create tag",e):c("Tag added",{action:e,result:o.data})},"create.contributor":({action:e,payload:t})=>{let{id:n,name:r}=t,o=E.createContributor({id:n,name:r});return a(o)?w(o.message??"Unable to create contributor",e):c("Contributor created",{action:e,result:o.data})},"tag.issue":({action:e,payload:t})=>{let{id:n,target:r,tagId:o}=t,s=E.tag(r,o,n);return a(s)?w(s.message??"Unable to tag issue",e):c("Issue tagged",{action:e,result:s.data})},"untag.issue":({action:e,payload:t})=>{let{target:n,tagId:r}=t,o=E.untag(n,r);return a(o)?w(o.message??"Unable to untag ",e):c("Issue untagged",{action:e,result:o.data})},"assign.issue":({action:e,payload:t})=>{let{id:n,contributor:r,target:o}=t,s=E.assign(o,r,n);return a(s)?w(s.message??"Unable to assign issue",e):c("Assigned successfully",{action:e,result:s.data})},"unassign.issue":({action:e,payload:t})=>{let{target:n,contributor:r}=t,o=E.unassign(n,r);return a(o)?w(o.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e,result:o.data})},"move.node":({action:e,payload:t})=>{let{id:n,parent:r,pos:o}=t,s=E.moveNode({id:n,parentId:r,position:o});return a(s)?w(s.message??"Failed to move node",e):c("Moved node",{action:e,result:s.data})},"edit.description":({action:e,payload:t})=>{let{id:n,md:r}=t,o=E.editValue(n,r);return a(o)?w(o.message??"Unable to edit description",e):c("Set node value",{action:e,result:o.data})},"close.issue":({action:e,payload:t})=>{let{id:n}=t,r=E.getNode(n);if(!r)return w("Unable to locate issue",e);if(!z(r))return w("Can only close issues",e);let o=E.getNode(Z);if(!o)return w("Unable to locate target swimlane",e);if(o.id===r.parentNodeId)return w("Cannot close closed issue",e);let d=E.moveNode({id:n,parentId:o.id});return a(d)?w(d.message??"Unable to close issue",e):c("Issue closed",{action:e,result:d.data})},"reopen.issue":({action:e,payload:t})=>{let{id:n}=t,r=E.getNode(n);if(!r)return w("Unable to locate issue",e);if(!z(r))return w("Can only reopen issues",e);let o=E.getNode(Z);if(!o)return w("Unable to locate closed swimlane",e);if(!(r.parentNodeId===o.id))return w("Issue is not closed",e);let d=ar(r);if(!d)return w("Unable to resolve previous parent from issue history",e);if(d===o.id)return w("Previous parent resolves to closed swimlane",e);if(!E.getNode(d))return w("Previous parent no longer exists",e);let u=E.moveNode({id:n,parentId:d});return a(u)?w(u.message??"Unable to reopen issue",e):c("Issue reopened",{action:e,result:u.data})},"lock.node":({action:e,payload:t})=>{let{id:n}=t,r=E.lockNode(n);return a(r)?w(r.message??"Unable to lock node",e):c("Node locked",{action:e,result:r.data})}},Li=(e,t)=>{let n=E.getNode(e);n&&E.updateNode({...n,log:[...n.log??[],t]})},Pi=e=>{switch(e.action){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"delete.node":case"move.node":case"close.issue":case"reopen.issue":return[e.payload.id];case"edit.description":let t=[e.payload.id],n=y().nodes[e.payload.id]?.parentNodeId;return n&&t.push(n),t;case"tag.issue":case"untag.issue":case"assign.issue":case"unassign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function Se(e,t=!1){let n=Mi[e.action](e);if(a(n))return n;t||([...new Set(Pi(e))].forEach(d=>Li(d,e)),q(d=>({...d,eventLog:[...d.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?w("Invalid user ID format",e.action):(E.createContributor({name:o,id:r}),n)}var Ee=e=>e.map(t=>Se(t));function $(e){let t=Se(e);if(t.result!==ee.Success)return t;let n=vt({event:e});return a(n)?n:t}function Ae(e){return e.map(t=>$(t))}import qe from"node:fs";import{spawn as ki}from"node:child_process";import Xt from"node:fs";import we from"node:path";var Ve=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let d=r(...s);if(!n.has(d)){let l=e(...s).then(u=>(a(u)&&n.delete(d),u));n.set(d,l)}return n.get(d)});return o.clear=()=>n.clear(),o};import je from"fs";import cr from"path";import Di from"util";var dr=1e3,lr=(e=process.cwd())=>cr.join(ae(e),se(),"log","epiq.log");function Fi(e=process.cwd()){if(!pt)return;let t=lr(e);if(!je.existsSync(t))return;let r=je.readFileSync(t,"utf8").split(`
5
5
  `);if(r[r.length-1]===""&&r.pop(),r.length<=dr)return;let o=r.slice(-dr).join(`
6
6
  `)+`
7
7
  `;je.writeFileSync(t,o,"utf8")}function Yt(e,t,n=!1,r=process.cwd()){if(!pt)return;let o=lr(r),s=Di.format(...t),d=new Date,u=`[${n?d.toISOString().slice(11,19):d.toISOString()}] ${e} ${s}
8
- `;je.mkdirSync(cr.dirname(o),{recursive:!0}),je.appendFileSync(o,u,"utf8"),Fi(r)}var x={info(...e){Yt("[Info]",e,!1)},debug(...e){Yt("->",e,!0)},error(...e){Yt("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=x;var ur=15e3,Oi={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},pr=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Xt.existsSync(t)){let v=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:v,exitCode:1});return}r(i(v));return}let o=ki("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Oi}),s=!1,d="",l="",u=v=>{s||(s=!0,clearTimeout(g),r(v))},g=setTimeout(()=>{o.kill("SIGTERM");let v=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${ur}ms`].join(`
9
- `);u(n?{stdout:d,stderr:v,exitCode:124}:i(v))},ur);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",v=>{d+=v}),o.stderr.on("data",v=>{l+=v}),o.on("error",v=>{if(n){u({stdout:d,stderr:v.message,exitCode:1});return}u(i([`git ${e.join(" ")}`,`cwd=${t}`,v.message].join(`
10
- `)))}),o.on("close",v=>{let N=v??1;if(n){u({stdout:d,stderr:l,exitCode:N});return}if(N!==0){u(i([`git ${e.join(" ")}`,l.trim()||d.trim()||"Git command failed"].filter(Boolean).join(`
8
+ `;je.mkdirSync(cr.dirname(o),{recursive:!0}),je.appendFileSync(o,u,"utf8"),Fi(r)}var x={info(...e){Yt("[Info]",e,!1)},debug(...e){Yt("->",e,!0)},error(...e){Yt("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=x;var ur=15e3,Oi={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},pr=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Xt.existsSync(t)){let f=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:f,exitCode:1});return}r(i(f));return}let o=ki("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Oi}),s=!1,d="",l="",u=f=>{s||(s=!0,clearTimeout(v),r(f))},v=setTimeout(()=>{o.kill("SIGTERM");let f=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${ur}ms`].join(`
9
+ `);u(n?{stdout:d,stderr:f,exitCode:124}:i(f))},ur);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",f=>{d+=f}),o.stderr.on("data",f=>{l+=f}),o.on("error",f=>{if(n){u({stdout:d,stderr:f.message,exitCode:1});return}u(i([`git ${e.join(" ")}`,`cwd=${t}`,f.message].join(`
10
+ `)))}),o.on("close",f=>{let N=f??1;if(n){u({stdout:d,stderr:l,exitCode:N});return}if(N!==0){u(i([`git ${e.join(" ")}`,l.trim()||d.trim()||"Git command failed"].filter(Boolean).join(`
11
11
  `)));return}u(c("Git command succeeded",{stdout:d,stderr:l,exitCode:N}))})}),T=({args:e,cwd:t})=>pr({args:e,cwd:t,allowFail:!1}),Ne=({args:e,cwd:t})=>pr({args:e,cwd:t,allowFail:!0}),gr=Ve(async(e=process.cwd())=>{let t=await T({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?i("Not inside a Git repository"):c("Resolved repo root",t.data.stdout.trim())},e=>we.resolve(e)),Ui=Ve(async e=>{let t=await T({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return i(t.message);let n=t.data.stdout.trim(),r=we.isAbsolute(n)?n:we.join(e,n);return c("Resolved git dir",r)},e=>we.resolve(e)),Qt=async({cwd:e,message:t})=>{let n=await T({args:["commit","-m",t],cwd:e});if(a(n))return i(`Failed to create commit
12
12
  ${n.message}`);let r=await T({args:["rev-parse","HEAD"],cwd:e});return a(r)?i(`Commit created, but failed to read HEAD SHA
13
13
  ${r.message}`):c("Created commit and resolved SHA",r.data.stdout.trim())},Zt=async e=>{let t=await Ui(e);if(a(t))return i(t.message);let n=t.data,o=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","REBASE_HEAD","rebase-merge","rebase-apply"].filter(s=>Xt.existsSync(we.join(n,s)));return c("Checked for in-progress Git operation",o.length>0)},xt=async({repoRoot:e,remote:t})=>{let n=await Ne({args:["remote","get-url",t],cwd:e});return c("Checked remote",n.exitCode===0)},bt=async({repoRoot:e,remote:t,branch:n})=>{let r=await Ne({args:["ls-remote","--heads",t,n],cwd:e});return r.exitCode!==0?i(r.stderr.trim()||`Unable to inspect remote branch ${t}/${n}`):c("Checked remote branch",r.stdout.trim().length>0)},fr=async({repoRoot:e,branch:t})=>{let n=await Ne({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?c("Local branch exists",!0):n.exitCode===1?c("Local branch missing",!1):i(n.stderr.trim()||`Unable to inspect branch ${t}`)},mr=e=>{try{return Xt.realpathSync.native(e)}catch{return we.resolve(e)}},vr=async({repoRoot:e,worktreeRoot:t})=>{let n=await T({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let r=mr(t),o=n.data.stdout.split(`
@@ -16,7 +16,7 @@ ${o.message}`);x.debug("[git] pull start",{cwd:e,remote:t,branch:n});let s=await
16
16
  ${s.message}`):c("Pulled with rebase",!0)},Nr=async e=>{let t=await T({args:["status","--porcelain"],cwd:e});return a(t)?i(t.message):c("Checked remote worktree changes",t.data.stdout.trim().length>0)},Ir=async e=>{let t=await Ct(e);return a(t)?i(t.message):c("Checked detached HEAD state",t.data==="HEAD")};import{createHash as Ki}from"node:crypto";import ne from"node:fs";import Vi from"node:os";import V from"node:path";import ht from"node:fs";import _i from"node:path";import{decodeTime as Bi}from"ulid";var nn=e=>{let[t,n]=e.id;return`${t}:${n??""}`},xr=e=>{let[t]=e.id;return Bi(t)},Wi=e=>{let{userId:t,userName:n,...r}=e;return r},$i=e=>e.length===0?"":e.map(t=>JSON.stringify(Wi(t))).join(`
17
17
  `)+`
18
18
  `,Hi=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(nn(r),r);return[...n.values()].sort((r,o)=>{let s=xr(r)-xr(o);return s!==0?s:nn(r).localeCompare(nn(o))})},Rt=({sourceFile:e,targetFile:t})=>{let n=Nt(e);if(a(n))return i(n.message);let r=Nt(t);if(a(r))return i(r.message);let o=Hi(r.data,n.data),s=$i(o);return(ht.existsSync(t)?ht.readFileSync(t,"utf8"):"")===s?c("Event file already merged",!1):(ht.mkdirSync(_i.dirname(t),{recursive:!0}),ht.writeFileSync(t,s,"utf8"),c("Merged event file",!0))};var L="epiq/events",K="origin",rn=se(),Cr="events",ji="4b825dc642cb6eb9a060e54bf8d69288fbee4904",zi=e=>V.join(rn,Cr,e),qi=e=>Ki("sha1").update(V.resolve(e)).digest("hex").slice(0,12),hr=()=>V.join(Vi.homedir(),".epiq"),Rr=()=>V.join(hr(),"worktrees"),Sr=e=>V.join(Rr(),qi(e)),Gi=e=>V.join(e,rn),Te=e=>V.join(Gi(e),Cr),ze=({root:e,fileName:t})=>V.join(Te(e),t),St=e=>(x.debug("[sync] ensure dir",e),ne.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)),Ji=()=>{x.debug("[sync] ensure epiq storage");let e=St(hr());if(a(e))return i(e.message);let t=St(Rr());return a(t)?i(t.message):c("Ensured epiq storage",void 0)},Yi=e=>{ne.existsSync(e)&&(x.debug("[sync] remove path",e),ne.rmSync(e,{recursive:!0,force:!0}))},Xi=e=>{let t=Te(e);if(!ne.existsSync(t))return x.debug("[sync] events dir missing",t),c("Events dir missing",[]);let n=ne.readdirSync(t,{withFileTypes:!0}).filter(r=>r.isFile()).map(r=>r.name).filter(r=>r.endsWith(".jsonl")).sort();return x.debug("[sync] listed event files",{eventsDir:t,count:n.length}),c("Listed event files",n)},Qi=async e=>{x.debug("[sync] inspect local HEAD",e);let t=await Ne({args:["rev-parse","--verify","HEAD"],cwd:e});return t.exitCode===0?c("Repo has HEAD",!0):t.exitCode===1?c("Repo has no HEAD",!1):i(t.stderr.trim()||"Unable to inspect HEAD")},Zi=Ve(async e=>{x.debug("[sync] inspect remote history",{repoRoot:e,remote:K});let t=await xt({repoRoot:e,remote:K});if(a(t))return i(t.message);if(!t.data)return c("No remote configured",!1);let n=await Ne({args:["ls-remote","--heads",K],cwd:e});if(n.exitCode!==0)return i(n.stderr.trim()||"Unable to inspect remote heads");let r=n.stdout.trim().length>0;return x.debug("[sync] remote history",r),c("Checked remote history",r)},e=>V.resolve(e)),Ar=async e=>{x.debug("[sync] ensure initial commit");let t=await Qi(e);if(a(t))return i(t.message);if(t.data)return x.debug("[sync] local HEAD exists"),c("Repo already initialized",!1);let n=await Zi(e);if(a(n))return i(n.message);if(n.data)return x.debug("[sync] skip local init commit due to remote history"),c("Skipped local init commit because remote history exists",!1);x.debug("[sync] create empty init commit");let r=await T({args:["commit","--allow-empty","-m","[epiq:init]"],cwd:e});return a(r)?i(`Failed to create initial commit
19
- ${r.message}`):c("Created initial commit",!0)},wr=({repoRoot:e,worktreeRoot:t})=>{let n=Xi(t);if(a(n))return i(n.message);let r=Te(t),o=Te(e),s=!1;for(let d of n.data){let l=V.join(r,d),u=V.join(o,d);x.debug("[sync] hydrate event file",{from:l,to:u});let g=Rt({sourceFile:l,targetFile:u});if(a(g))return i(g.message);s=s||g.data}return x.debug("[sync] hydrate changed",s),c("Hydrated event files from remote worktree",s)},br=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",es=async e=>{let t=await Ct(e);if(a(t))return i(t.message);let n=await yr(e);if(a(n))return i(n.message);let r=`[epiq:sync:${br(t.data)}:${br(n.data)}]`;return x.debug("[sync] commit message",r),c("Built sync commit message",r)},ts=async e=>{x.debug("[sync] create empty storage branch",L);let t=await T({args:["commit-tree",ji,"-m","[epiq:init-storage-branch]"],cwd:e});if(a(t))return i(`Failed to create storage branch commit
19
+ ${r.message}`):c("Created initial commit",!0)},wr=({repoRoot:e,worktreeRoot:t})=>{let n=Xi(t);if(a(n))return i(n.message);let r=Te(t),o=Te(e),s=!1;for(let d of n.data){let l=V.join(r,d),u=V.join(o,d);x.debug("[sync] hydrate event file",{from:l,to:u});let v=Rt({sourceFile:l,targetFile:u});if(a(v))return i(v.message);s=s||v.data}return x.debug("[sync] hydrate changed",s),c("Hydrated event files from remote worktree",s)},br=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",es=async e=>{let t=await Ct(e);if(a(t))return i(t.message);let n=await yr(e);if(a(n))return i(n.message);let r=`[epiq:sync:${br(t.data)}:${br(n.data)}]`;return x.debug("[sync] commit message",r),c("Built sync commit message",r)},ts=async e=>{x.debug("[sync] create empty storage branch",L);let t=await T({args:["commit-tree",ji,"-m","[epiq:init-storage-branch]"],cwd:e});if(a(t))return i(`Failed to create storage branch commit
20
20
  ${t.message}`);let n=t.data.stdout.trim(),r=await T({args:["update-ref",`refs/heads/${L}`,n],cwd:e});return a(r)?i(`Failed to create ${L}
21
21
  ${r.message}`):c("Created empty storage branch",!0)},ns=async({repoRoot:e})=>{x.debug("[sync] ensure local remote branch",L);let t=await fr({repoRoot:e,branch:L});if(a(t))return i(t.message);if(t.data)return x.debug("[sync] local remote branch exists"),c("Local remote branch already exists",!1);let n=await xt({repoRoot:e,remote:K});if(a(n))return i(n.message);if(n.data){let r=await bt({repoRoot:e,remote:K,branch:L});if(a(r))return i(r.message);if(r.data){x.debug("[sync] fetch remote branch before local track");let o=await T({args:["fetch",K,L],cwd:e});if(a(o))return i(`Failed to fetch ${L} from remote
22
22
  ${o.message}`);x.debug("[sync] create local tracking branch",L);let s=await T({args:["branch","--track",L,`${K}/${L}`],cwd:e});return a(s)?i(`Failed to create local ${L} from remote
@@ -32,8 +32,8 @@ ${o.message}`);let s=await Qt({cwd:e,message:"[epiq:repair-storage-branch]"});re
32
32
  ${o.message}`);x.debug("[sync] set upstream to remote branch");let s=await T({args:["branch","--set-upstream-to",`${K}/${L}`,L],cwd:e});return a(s)?i(`Failed to set remote upstream
33
33
  ${s.message}`):c("Configured remote upstream",!0)},Tr=async({worktreeRoot:e,ownEventFileName:t})=>{x.debug("[sync] stage own event file in remote worktree",t);let n=await T({args:["add",zi(t)],cwd:e});return a(n)?i(`Failed to stage remote own event file
34
34
  ${n.message}`):c("Staged remote own event file",void 0)},Mr=async({repoRoot:e,worktreeRoot:t})=>{let n=await es(e);return a(n)?i(n.message):(x.debug("[sync] create remote sync commit"),Qt({cwd:t,message:n.data}))},on=async e=>{x.debug("[sync] push remote worktree");let t=await en(e);if(a(t))return i(t.message);let n=await T({args:t.data?["push"]:["push","-u",K,L],cwd:e});return x.debug("[sync] push result",n),a(n)?i(`Failed during remote push
35
- ${n.message}`):c("Pushed remote",!0)},Lr=async({repoRoot:e,worktreeRoot:t,ensureUpstream:n})=>{x.debug("[sync] bootstrap remote storage",{repoRoot:e,worktreeRoot:t,ensureUpstream:n});let r=!1,o=[Ji(),await ns({repoRoot:e}),await is({repoRoot:e,worktreeRoot:t}),await ss(t),await as(t),n?await ds(t):c("Skipped remote upstream bootstrap",!1)];for(let s of o){if(a(s))return i(s.message);r=r||!!s.data}return x.debug("[sync] bootstrap changed",r),c(n?"Bootstrapped remote storage":"Bootstrapped remote storage (readonly)",r)},Pr=(e,t)=>{for(let n of[Te(e),Te(t)]){let r=St(n);if(a(r))return i(r.message)}return c("Ensured remote layout",void 0)};var cs=({repoRoot:e,worktreeRoot:t,ownEventFileName:n})=>{let r=ze({root:e,fileName:n}),o=ze({root:t,fileName:n});return qe.existsSync(r)?(logger.debug("[sync] merge own event file to remote",{ownEventFileName:n,localFile:r,remoteFile:o}),Rt({sourceFile:r,targetFile:o})):(logger.debug("[sync] local own event file missing",r),c("Local own event file missing, nothing to merge",!1))},Dr=async({repoRoot:e,worktreeRoot:t,ownEventFileName:n})=>{let r=cs({repoRoot:e,worktreeRoot:t,ownEventFileName:n});if(a(r))return i(r.message);let o=await Nr(t);if(a(o))return i(o.message);if(!r.data&&!o.data)return c("Own event file already up to date in remote worktree",{createdCommit:!1});let s=await Tr({worktreeRoot:t,ownEventFileName:n});if(a(s))return i(s.message);let d=await Mr({repoRoot:e,worktreeRoot:t});return a(d)?i(d.message):c("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:d.data})},Fr=({repoRoot:e,worktreeRoot:t,ownEventFileName:n})=>{let r=ze({root:e,fileName:n}),o=ze({root:t,fileName:n});logger.debug("[sync] own event file sizes",{local:qe.existsSync(r)?qe.statSync(r).size:0,remote:qe.existsSync(o)?qe.statSync(o).size:0})},At=async({cwd:e=process.cwd(),ownEventFileName:t})=>{logger.debug("[sync] start write sync",{cwd:e,ownEventFileName:t});let n=await gr(e);if(a(n))return i(n.message);let r=n.data,o=Sr(r);logger.debug("[sync] resolved roots",{repoRoot:r,worktreeRoot:o});let s=await Ir(r);if(a(s))return i(s.message);if(s.data)return i("Cannot run :sync while the repository is in detached HEAD state");if(t.includes("/")||t.includes("\\"))return i("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return i("Own event file must end with .jsonl");let d=await Zt(r);if(a(d))return i(d.message);if(d.data)return i("Cannot run :sync while a merge, rebase, cherry-pick, or revert is in progress in the current repo");let l=await Ar(r);if(a(l))return i(l.message);logger.debug("[sync] ensure initial commit changed",l.data);let u=await Lr({repoRoot:r,worktreeRoot:o,ensureUpstream:!0});if(a(u))return i(u.message);let g=await Zt(o);if(a(g))return i(g.message);if(g.data)return i("Cannot run :sync while a merge, rebase, cherry-pick, or revert is in progress in the remote worktree");let v=Pr(r,o);if(a(v))return i(v.message);let N=!1,C,S=!1,M=!1,j=!1;logger.debug("[sync] pull remote branch before local copy");let kt=await tn({cwd:o,remote:K,branch:L});if(a(kt))return i(kt.message);S=kt.data,logger.debug("[sync] pulled remote",S);let Ot=wr({repoRoot:r,worktreeRoot:o});if(a(Ot))return i(Ot.message);j=Ot.data,logger.debug("[sync] hydrated from remote",j);let De=await Dr({repoRoot:r,worktreeRoot:o,ownEventFileName:t});if(a(De))return i(De.message);if(N=De.data.createdCommit,C=De.data.commitSha,Fr({repoRoot:r,worktreeRoot:o,ownEventFileName:t}),logger.debug("[sync] sync own file result",De.data),N||u.data){let ve=await on(o),Ye=ve;if(a(ve)&&Er(ve.message)){let gn=await tn({cwd:o,remote:K,branch:L});if(a(gn))return i(gn.message);let Fe=await Dr({repoRoot:r,worktreeRoot:o,ownEventFileName:t});if(a(Fe))return i(Fe.message);Fe.data.createdCommit&&(N=!0,C=Fe.data.commitSha),Fr({repoRoot:r,worktreeRoot:o,ownEventFileName:t}),logger.debug("[sync] retry sync own file result",Fe.data),Ye=await on(o)}if(a(Ye))return i(Ye.message);M=Ye.data,logger.debug("[sync] pushed remote",M)}else logger.debug("[sync] no commit created, skipped push");if(N){let ve=await T({args:["rev-parse","HEAD"],cwd:o});if(a(ve))return i(ve.message);C=ve.data.stdout.trim()}return c("Synced event logs with remote",{repoRoot:r,worktreeRoot:o,createdCommit:N,commitSha:C,pulled:S,pushed:M,hydrated:j,bootstrapped:u.data})};import{ulid as kr}from"ulid";var Me=null,ge=()=>structuredClone(Me),Le=e=>Me=e,Or=()=>{let{currentNode:e,selectedIndex:t}=y(),r=R(e.id)[t];return r?c("Resolved selected child",r):i("Target node not found")};function sn(e){let t=Or();if(a(t))return t;let{currentNode:n,nodes:r}=y();if(!n.parentNodeId)return i("Missing parent node id");let o=r[n.parentNodeId];if(!o)return i("Missing parent node");let s=H(o.id),d=s.findIndex(({id:C})=>C===n.id);if(d<0)return i("Current node not found among siblings");let l=s[d+e];if(!l)return i("Missing sibling node");let u=W();if(a(u))return i("Unable to resolve user ID");let{userId:g,userName:v}=u.data;if(Le({id:kr(),userId:g,userName:v,action:"move.node",payload:{id:t.data.id,parent:l.id,pos:{at:"end"}}}),!Me)return i("Could not materialize move state");let N=Se(Me,!0);return a(N)?N:c("Node moved successfully",N.data)}function an(e){let t=Or();if(a(t))return t;let{currentNode:n,selectedIndex:r}=y(),s=H(n.id)[r+e];if(!s)return i("Missing sibling node");let d=W();if(a(d))return i("Unable to resolve user ID");let{userId:l,userName:u}=d.data;if(Le({id:kr(),userId:l,userName:u,action:"move.node",payload:{id:t.data.id,parent:n.id,pos:{at:e===1?"after":"before",sibling:s.id}}}),!Me)return i("Could not materialize move state");let g=Se(Me,!0);return a(g)?g:c("Node moved successfully",g.data)}import ls from"node:os";import Ur from"node:path";import{z as Ge}from"zod";var us={userId:"",userName:"",preferredEditor:"",autoSync:!1},_r=Ge.object({preferredEditor:Ge.string().optional(),userName:Ge.string().optional(),userId:Ge.string().optional(),autoSync:Ge.boolean().optional()}).strict(),ms=".epiq",ps="config.json",Br=()=>Ur.join(ls.homedir(),ms),dn=()=>Ur.join(Br(),ps),cn=()=>{try{return Y.mkDir(Br()),c("Ensured ~/.epiq exists",null)}catch{return i("Unable to create ~/.epiq")}},gs=e=>{let t;try{t=JSON.parse(e)}catch{return i("Invalid ~/.epiq/config.json JSON")}let n=_r.safeParse(t??{});return n.success?c("Parsed config",n.data):i(`Invalid ~/.epiq/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Wr=()=>{let e=cn();if(a(e))return i(e.message);let t=dn(),n=Y.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{autoSync:!1,preferredEditor:"",userId:"",userName:""}):gs(n)},$r=e=>{let t=cn();if(a(t))return i(t.message);let n=_r.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=dn();try{return Y.writeToFile(r,JSON.stringify(n.data,null,2)+`
36
- `),c("Config written",null)}catch{return i("Unable to write ~/.epiq/config.json")}},wt=e=>{let t=Wr();if(a(t))return i("Failed to read existing config");let n={...t.data,...e};return $r(n)},Hr=()=>{let e=dn(),t=cn();if(a(t))return i("Unable to create ~/.epiq");if(!(Y.readFile(e)!==null)){let u=$r(us);if(a(u))throw new Error("Unable to create ~/.epiq/config.json")}let r=Wr();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:d,autoSync:l}=r.data;return!s||!d?i("User name or ID not configured in ~/.epiq/config.json"):c("successfully loaded settings",{preferredEditor:o??"",userName:s,userId:d,autoSync:l??!1})};var Kr=e=>Object.values(y().tags).find(t=>t.name===e),Vr=e=>Object.values(y().contributors).find(t=>t.name===e),jr=[{systemOnly:!0,intent:b.Move,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=J().commandMeta,n=()=>{let l=ge();if(!l)return i("No pending move state");let u=l.payload.id;if(!y().nodes[u])return i("Moved node not found");let v=l.payload.parent,N=y().nodes[v];if(!N)return i("Move parent not found");let C=R(v).findIndex(S=>S.id===u);return C===-1?i("Moved node not found among rendered children"):(U.navigate({currentNode:N,selectedIndex:C}),c("Synchronized navigation to moved node",null))},r=l=>{if(a(l))return i(l.message);let u=n();return a(u)?i(u.message):c("Updated move preview",null)},{currentNode:o,selectedIndex:s}=y(),d=R(o.id)[s];if(!d)return I({mode:p.DEFAULT}),i("No move target");if(t==="start"){if(d.readonly)return i("Target node is read-only");if(s===-1)return i("No item selected");if(!d.parentNodeId)return i("Target has no parent");let l=R(d.parentNodeId),u=l.findIndex(({id:S})=>S===d.id);if(u===-1)return i("Target not found among siblings");let g=l[u-1],v=l[u+1],N=v!=null?{at:"before",sibling:v.id}:g!=null?{at:"after",sibling:g.id}:{at:"start"};Le({id:F(),action:"move.node",payload:{id:d.id,parent:d.parentNodeId,pos:N},...e.data}),I({mode:p.MOVE});let C=n();return a(C)?i(C.message):c("Move initialized",null)}if(t==="next")return I({mode:p.MOVE}),r(an(1));if(t==="previous")return I({mode:p.MOVE}),r(an(-1));if(t==="to-next")return I({mode:p.MOVE}),r(sn(1));if(t==="to-previous")return I({mode:p.MOVE}),r(sn(-1));if(t==="confirm"){I({mode:p.DEFAULT});let l=ge();if(!l)return i("No pending move to confirm");let u=$(l);if(a(u))return u;let g=n();return a(g)?i(g.message):(Le(null),c("Moved item",null))}return t==="cancel"?(Le(null),I({mode:p.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}},{intent:b.Delete,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=y(),r=R(t.id)[n];return r?$({id:F(),action:"delete.node",payload:{id:r.id},...e.data}):i("Unable to resolve child to delete")},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.Edit,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let t=ye(y().breadCrumb,"TICKET");if(a(t))return i("Edit target must be an issue");let n=t.data;if(n.readonly)return i("Cannot edit readonly field");let{currentNode:r,selectedIndex:o}=y();if(!R(n.id)[o])return i("No selected field");let d=R(r.id)[o];if(!d)return i("No selected field");if(d.readonly)return i("Cannot edit readonly field");let l=d.props.value;if(typeof l!="string")return i("Selected field is not editable text");let u=Zn(l);if(a(u))return i("Failed to edit field");let g=u.data;return g===l?c("No changes made",null):d.title==="Description"?$({id:F(),action:"edit.description",payload:{id:d.id,md:g},...e.data}):d.title==="Title"?$({id:F(),action:"edit.title",payload:{id:d.id,name:g},...e.data}):i(`Editing not supported for "${d.title}"`)},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.Filter,mode:p.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=J().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(l=>_(m.FILTER).map(u=>u.split(n)[0]).includes(l))(r))return i("Invalid filter modifier");let d={target:r,operator:"=",value:t.trim()};return q(l=>({...l,filters:e==="clear"?[]:[...l.filters,d],mode:p.DEFAULT})),c("Viewing help",null)}},{intent:b.ViewHelp,mode:p.COMMAND_LINE,action:()=>(I({mode:p.HELP}),c("Viewing help",null))},{intent:b.CloseIssue,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=y(),r=R(t.id)[n];if(!r)return i("Unable to close issue, no target found");if(!r.parentNodeId)return i("No target parent found");if(!z(r))return i("Cannot close in this context");let o=$({id:F(),action:"close.issue",payload:{id:r.id,parent:r.parentNodeId},...e.data});return a(o)?o:c("Viewing help",null)}},{intent:b.ReopenIssue,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=y(),r=R(t.id)[n];if(!r)return i("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):be(r.id,"TICKET");if(a(o))return i("Cannot reopen in this context");let s=o.data,d=$({id:F(),action:"reopen.issue",payload:{id:s.id},...e.data});return a(d)?d:c("Issue reopened",null)},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.SetUserName,mode:p.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:n}=oe(),r=ut()?.trim();if(!r)return i("No username provided");let o=r??n,s=e??F();if(!o||!s)return i("Unable to resolve user name or id");let d=wt({userName:o,userId:s,preferredEditor:t??""});return a(d)?d:(it({userName:o,userId:s}),I({mode:p.DEFAULT}),c(`Username set to "${r}"`,null))}},{intent:b.Init,mode:p.COMMAND_LINE,action:()=>{let e=un();if(a(e))return e;let{rootNodeId:t,nodes:n}=y();return U.navigate({currentNode:n[t],selectedIndex:0}),I({mode:p.DEFAULT}),c("Project initialized",null)}},{intent:b.SetEditor,mode:p.COMMAND_LINE,action:()=>{let e=ut()?.trim();if(!e)return i("No editor provided");let t=wt({preferredEditor:e});return a(t)?t:(it({preferredEditor:e}),I({mode:p.DEFAULT}),c(`Editor configuration set to "${e}"`,null))}},{intent:b.SetAutoSync,mode:p.COMMAND_LINE,action:()=>{let e=J().commandMeta.modifier;if(e!=="true"&&e!=="false")return i("Invalid response");let t=e.toLowerCase()==="true",n=wt({autoSync:t});return a(n)?n:(it({autoSync:t}),I({mode:p.DEFAULT}),c(`Auto synchronization set to "${t}"`,null))}},{intent:b.NewItem,mode:p.COMMAND_LINE,action:(e,t)=>{let n=W();if(a(n))return i("Unable to resolve user ID");if(!t.inputString)return i(`provide a name for your ${t.modifier}`);let{breadCrumb:r,currentNode:o,selectedIndex:s}=y(),d=l=>{let u=$(l);if(a(u))return u;let g=E.getNode(u.data.result.id);if(!g)return i("Created node not found");if(!g.parentNodeId)return u;let v=E.getNode(g.parentNodeId);return v?(U.navigate({currentNode:v,selectedIndex:E.getSiblings(g.parentNodeId).findIndex(({id:N})=>N===g.id)}),u):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:l}=y(),u=E.getNode(l);return u?d({id:F(),action:"add.board",payload:{id:F(),name:t.inputString,parent:u.id},...n.data}):i("Workspace not found")}if(t.modifier==="swimlane"){let l=ye(r,"BOARD");return a(l)?i("Unable to add swimlane in this context"):d({id:F(),action:"add.swimlane",payload:{id:F(),name:t.inputString,parent:l.data.id},...n.data})}if(t.modifier==="issue"){let l=R(o.id)[s],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&l?.context==="SWIMLANE"?l:(()=>{let S=ye(r,"SWIMLANE");return a(S)?null:S.data})();if(!u)return i("Unable to add issue in this context");let g=Ze({name:t.inputString,parent:u.id,user:n.data}),v=Ae(g);if(v.some(S=>a(S)))return i("Issue create failed: "+v.filter(a).map(S=>S.message).filter(Boolean).join(", "));let N=v[0];if(!N||a(N))return i("Issue creation failed");let C=g[0]?.payload.id;return C?(U.navigate({currentNode:u,selectedIndex:E.getSiblings(u.id).findIndex(({id:S})=>S===C)}),c("Issue created",null)):i("Unable to determine ticket id")}return fn()},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.SetView,mode:p.COMMAND_LINE,action:()=>{let{commandMeta:e}=J();return e.validity===re.Invalid?i("Invalid command "+ee):(q(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),c("View set",null))},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.Rename,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=y(),r=R(t.id)[n];if(!r)return i("Missing node");if(r.readonly)return i("Cannot rename readonly node");let o=ut();return o?$({id:F(),action:"edit.title",payload:{id:r.id,name:o},...e.data}):i("Provide a new name")},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.UntagTicket,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=J().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let o=Kr(r);if(!o)return i(`Tag "${r}" does not exist`);let{selectedNode:s}=y();if(!s)return i("Invalid untag target");let d=be(s.id,"TICKET");if(a(d))return i("Unable to untag issue in this context");let l=d.data,u=E.getFieldByTitle(l.id,"Tags");if(!u)return i("Unable to locate tags field");let g=R(u.id).find(v=>v.props?.value===o.id);return g?$({id:F(),action:"untag.issue",payload:{id:g.id,target:l.id,tagId:o.id},...e.data}):i("Issue is not tagged with that tag")},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.TagTicket,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=J().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let{selectedIndex:o,currentNode:s}=y(),d=R(s.id)[o];if(!d)return i("Invalid tag target");let l=be(d.id,"TICKET");if(a(l))return i("Unable to tag issue in this context");let u=l.data,g=Kr(r),v;if(g)v=g.id;else{let S=F(),M=$({id:F(),action:"create.tag",payload:{id:S,name:r},userId:e.data.userId,userName:e.data.userName});if(a(M))return M;v=M.data.result.id}let N=E.getFieldByTitle(u.id,"Tags");return N?R(N.id).some(S=>S.props?.value===v)?i("Already tagged with that tag"):$({id:F(),action:"tag.issue",payload:{id:F(),target:u.id,tagId:v},...e.data}):i("Unable to locate tags field")},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.AssignUserToTicket,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=J().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee");let{selectedIndex:o,currentNode:s}=y(),d=R(s.id)[o];if(!d)return i("Invalid assign target");let l=be(d.id,"TICKET");if(a(l))return i("Unable to assign issue in this context");let u=l.data,g=Vr(r),v;if(g)v=g.id;else{let S=F(),M=$({id:F(),action:"create.contributor",payload:{id:S,name:r},userId:e.data.userId,userName:e.data.userName});if(a(M))return M;v=M.data.result.id}let N=E.getFieldByTitle(u.id,"Assignees");return N?R(N.id).some(S=>S.props?.value===v)?i("Assignee already assigned"):$({id:F(),action:"assign.issue",payload:{id:F(),target:u.id,contributor:v},...e.data}):i("Unable to locate assignees field")},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.UnassignUserFromTicket,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=J().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee to remove");let o=Vr(r);if(!o)return i(`Assignee "${r}" does not exist`);let{selectedNode:s}=y();if(!s)return i("Invalid unassign target");let d=be(s.id,"TICKET");if(a(d))return i("Unable to unassign in this context");let l=d.data,u=E.getFieldByTitle(l.id,"Assignees");if(!u)return i("Unable to locate assignees field");let g=R(u.id).find(v=>v.props?.value===o.id);return g?$({id:F(),action:"unassign.issue",payload:{id:g.id,target:l.id,contributor:o.id},...e.data}):i(`Issue is not assigned to "${r}"`)},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.Sync,mode:p.COMMAND_LINE,action:async()=>{O(()=>""),I({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:e,userName:t}=oe();if(!e)return i("Unable to resolve userId");if(!t)return i("Unable to resolve userName");let n=Oe()?un():c("No pending default events",null);if(a(n))return i(`Unable to persist default events. ${n.message}`);let r=W();if(a(r)||!r.data)return i("Unable to resolve event log path");let o=He(r.data);logger.debug("[sync-command] pending defaults",Oe());let s=await At({ownEventFileName:o});if(a(s))return I({syncStatus:{msg:s.message,status:"outOfSync"}}),i(`Unable to sync state. ${s.message}`);I({syncStatus:{msg:"Synced",status:"synced"},mode:p.DEFAULT});let d=Ke();return a(d)?i("Unable to load events"):(Ee(d.data),c("Synced",!0))}},{intent:b.Peek,mode:p.COMMAND_LINE,action:async()=>{let e=ye(y().breadCrumb,"BOARD");if(a(e))return e;let t=Ke();if(a(t))return i(t.message);let n=t.data,{modifier:r}=J().commandMeta,o;if(r==="now"){let N=ln();if(a(N))return N;let C=Ee(n);return C.some(a)?i(C.map(S=>S.message).join(", ")):(I({mode:p.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}if(r==="prev"){let N=y().eventLog.at(-2),C=Bt(N);if(C===null)return i("No previous event to peek");o=C}else if(r==="next"){let N=y().unappliedEvents.at(0),C=Bt(N);if(C===null)return i("No next event to peek");o=C}else{let N=ct(r);if(!N)return i("Invalid peek date");o=N.getTime()}let s=e.data.id,{appliedEvents:d,unappliedEvents:l}=sr(n,o),u=ln();if(a(u))return u;let g=Ee(d);if(g.some(a))return i(g.map(N=>N.message).join(", "));let v=y().nodes[s];return v?(U.navigate({currentNode:v,selectedIndex:0}),I({mode:p.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:l}),c("Peeking ",!0)):i("Board did not exist at peek date")}}];var fs=new Set(["peek","filter","view-help"]),X=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=J();if(!t)return i("No command to confirm");if(!e&&n===re.Invalid)return i("Invalid command");let s=Gn(t);if(Vn(),y().readOnly&&!fs.has(s))return We({result:ee.Fail,message:"Command not available in readonly state",data:null});let d=jr.filter(u=>e||u.systemOnly!==!0).find(u=>u.intent===s);if(!d)return We({result:ee.Fail,message:"Command not found",data:null});let l=await d.action(d,{command:t,inputString:o,modifier:r});return a(l)?We(l):(jn({addToHistory:!e}),d.onSuccess?.(),We(l))};var Tt=[{intent:h.Exit,mode:p.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(I({mode:p.COMMAND_LINE}),O(()=>"move cancel"),X({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:p.DEFAULT,description:"[m] move init/confirm",action:()=>(I({mode:p.COMMAND_LINE}),O(()=>"move start"),X({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:p.MOVE,action:()=>(I({mode:p.COMMAND_LINE}),O(()=>"move confirm"),X({isForceExecutedBySystem:!0}))}],Mt=[{intent:h.MovePreviousItem,mode:p.MOVE,action:()=>ge()?(I({mode:p.COMMAND_LINE}),O(()=>"move previous"),X({isForceExecutedBySystem:!0})):i("No pending move")},{intent:h.MoveNextItem,mode:p.MOVE,action:()=>ge()?(I({mode:p.COMMAND_LINE}),O(()=>"move next"),X({isForceExecutedBySystem:!0})):i("No pending move")}],zr=[{intent:h.MoveToNextContainer,mode:p.MOVE,action:()=>ge()?(I({mode:p.COMMAND_LINE}),O(()=>"move to-next"),X({isForceExecutedBySystem:!0})):i("No pending move")},{intent:h.MoveToPreviousContainer,mode:p.MOVE,action:()=>ge()?(I({mode:p.COMMAND_LINE}),O(()=>"move to-previous"),X({isForceExecutedBySystem:!0})):i("No pending move")}];var qr={[P.WORKSPACE]:[...Tt,...Mt],[P.BOARD]:[...Tt,...Mt],[P.SWIMLANE]:[...Tt,...Mt,...zr],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var Gr=[{intent:h.AddItem,mode:p.DEFAULT,description:"[n] new...",action:()=>(I({mode:p.COMMAND_LINE}),O(()=>`${m.NEW} `),c("Adding new item",null))},{intent:h.Delete,mode:p.DEFAULT,description:"[d] delete",action:()=>(I({mode:p.COMMAND_LINE}),O(()=>`${m.DELETE} `),c("Deleting item",null))},{intent:h.InitCommandLine,mode:p.DEFAULT,description:"[:] focus command line",action:()=>(I({mode:p.COMMAND_LINE}),O(()=>""),c("Entering command line mode",null))},{intent:h.Confirm,mode:p.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(U.enterChildNode(),c("Entering context",null))},{intent:h.Exit,mode:p.DEFAULT,description:"[q] exit context",action:()=>(U.enterParentNode(),c("Exiting context",null))},{intent:h.NavPreviousItem,mode:p.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:h.NavNextItem,mode:p.DEFAULT,action:()=>(U.navigateToNextItem(),c("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:p.DEFAULT,action:()=>(U.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:p.DEFAULT,action:()=>(U.navigateToNextContainer(),c("Navigating to next container",null))},{intent:h.Edit,mode:p.DEFAULT,action:()=>(I({mode:p.COMMAND_LINE}),O(()=>"edit"),X(),c("Fired command",!0))},{intent:h.SetViewDense,mode:p.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(I({viewMode:"dense"}),c("View set",null))},{intent:h.SetViewWide,mode:p.DEFAULT,action:()=>(I({viewMode:"wide"}),c("View set",null))}];var Jr=[{intent:h.ViewHelp,mode:p.DEFAULT,action:()=>(I({mode:p.HELP}),c("Viewing help",null))},{intent:h.Exit,mode:p.HELP,action:()=>(I({mode:p.DEFAULT}),c("Exiting help",null))},{intent:h.Confirm,mode:p.COMMAND_LINE,action:()=>(X(),c("Executing command",null))},{intent:h.MoveCursorLeft,mode:p.COMMAND_LINE,action:()=>(jt(-1),c("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:p.COMMAND_LINE,action:()=>(jt(1),c("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:p.COMMAND_LINE,action:()=>(zt("left"),c("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:p.COMMAND_LINE,action:()=>(zt("right"),c("Moving cursor right of word",null))},{intent:h.ExitCommandLine,mode:p.COMMAND_LINE,action:()=>(I({mode:p.DEFAULT}),c("Exiting command line",null))},{intent:h.AutoCompleteCommand,mode:p.COMMAND_LINE,action:()=>(O((e,{remainder:t})=>t?e+t:e),c("Auto-completing command",null))},{intent:h.CaptureInput,mode:p.COMMAND_LINE,action:(e,{sequence:t})=>(O(n=>n+t),c("Capturing input",null))},{intent:h.EraseInput,mode:p.COMMAND_LINE,action:()=>(Hn(),c("Erasing input",null))},{intent:h.EraseInputWord,mode:p.COMMAND_LINE,action:()=>(Kn(),c("Erasing input word",null))},{intent:h.GetLastCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(zn(),c("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(qn(),c("Getting next command from history",null))}];import vs from"chalk";var Lt=": for command line",Yr="q to exit",Xr=`${vs.hex(Sn.accent)("m")} to confirm`,mn={[P.WORKSPACE]:[Lt],[P.BOARD]:[Lt],[P.BOARD+p.COMMAND_LINE]:[Lt],[P.SWIMLANE]:[Lt],[P.TICKET+p.HELP]:[Yr],[P.SWIMLANE+p.HELP]:[Yr],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+p.MOVE]:[Xr],[P.TICKET+p.MOVE]:[Xr]};var Pt=e=>e.trim().toLocaleLowerCase(),ys=(e,t)=>{let n=E.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},Es=e=>{let{tags:t}=y(),n=E.getFieldByTitle(e,"Tags");return n?H(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},Ns=e=>{let{contributors:t}=y(),n=E.getFieldByTitle(e,"Assignees");return n?H(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},Qr=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return Pt(e.title??"").includes(n);case"description":return Pt(ys(e.id,"Description")).includes(n);case"tag":return Es(e.id).map(Pt).some(l=>l.includes(n));case"assignee":return Ns(e.id).map(Pt).some(l=>l.includes(n));default:return!0}};function Zr(e,t,n){let r=t[e];if(!r)return i("buildBreadCrumb(): current node not found");let o=[],s=r;for(;s&&(o.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let d=o[o.length-1];return!d||d.id!==n?i("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var eo=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var Dt,pn,Is=new Set,to=()=>{for(let e of Is)e()};function no(e){let{currentNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return i("derive(): currentNodeId is missing");if(!r)return i("derive(): rootNode is missing");if(!o[r])return i("derive(): unable to find root node");let l=o[t];if(!l)return logger.error("Unable to derive state, currentNode not found"),i("Unable to derive state, currentNode not found");let u=Zr(t,o,r);if(a(u))return logger.error(u.message),u;let g=u.data,{context:v}=l,N=mn[v+n]??mn[v]??[],C=[...Gr,...qr[v]??[],...Jr],S=eo(C),M=xs(o,s),j=M[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,currentNode:l,breadCrumb:g,availableHints:N,availableActions:C,actionIndex:S,selectedNode:j,renderedChildrenIndex:M})}var y=()=>(Dt||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),Dt);function Jt(e){pn=e;let t={readOnly:!1,filters:[],tags:{},contributors:{},viewMode:"dense",mode:p.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live"},n=no(t);return a(n)?n:(Dt=n.data,to(),c("State initialized",null))}function q(e){let t=y(),n=e(t),r=no(n);return a(r)?i(r.message??"Unable to update state"):(Dt=r.data,to(),c("State updated",null))}var I=e=>q(t=>({...t,...e}));var xs=(e,t)=>{let n={};for(let r of Object.values(e))z(r)&&t.length>0&&!t.every(o=>Qr(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,s)=>{let d=e[o.id],l=e[s.id];return!d||!l?0:d.rank.localeCompare(l.rank)});return n},R=e=>y()?.renderedChildrenIndex[e]??[],ln=()=>pn?Jt(pn):i("Cannot reset state: no initial workspace found");var U={exit(){process.exit(0)},enterChildNode(){let e=y(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=R(t.id)[n];!r||t.context==="FIELD"||U.navigate({currentNode:r,selectedIndex:R(r.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=y();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=R(n.id),o=r.findIndex(({id:d})=>d===e.id),s=r.length===0?-1:o>=0?o:0;U.navigate({currentNode:n,selectedIndex:s})},navigateToNextItem:()=>ro(1),navigateToPreviousItem:()=>ro(-1),navigateToNextContainer:()=>oo(1),navigateToPreviousContainer:()=>oo(-1),navigate:({currentNode:e=y().currentNode,selectedIndex:t})=>{I({currentNodeId:e.id,selectedIndex:t})}},ro=e=>{let t=y(),n=R(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;U.navigate({selectedIndex:o})},oo=e=>{let{currentNode:t,nodes:n,selectedIndex:r}=y();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let s=R(o.id),d=s.findIndex(C=>C.id===t.id);if(d<0)return;let l=s.at(d+e)??s.at(0);if(!l)return;let u=R(l.id),g=Math.max(0,u.length-1),v=Math.min(Math.max(0,r),g),N=u.length?v:-1;U.navigate({currentNode:l,selectedIndex:N})};var ce="system",le="ACTOR",Je=bs(),ue=null;function Cs(){let e=Object.values(y().nodes).find(r=>r.context==="WORKSPACE");if(!e)throw new Error("No workspace found in event log");let[t]=R(e.id),[n]=t?R(t.id):[];if(logger.debug("Boot navigation target:",{workspace:e?.id,firstBoard:t?.id,firstSwimlane:n?.id}),n){let r=y().renderedChildrenIndex?.[n.id]??[];return{currentNode:n,selectedIndex:r.length>0?0:-1}}else return t?{currentNode:t,selectedIndex:0}:e?{currentNode:e,selectedIndex:0}:{currentNode:y().nodes[y().rootNodeId],selectedIndex:0}}function hs(){let e=Cs();U.navigate(e)}function Rs(){let e=Je(),t=Je(),n=Je(),r=Je(),o=Je();return[{id:de(),userId:ce,userName:le,action:"init.workspace",payload:{id:e,name:"Workspace"}},{id:de(),userId:ce,userName:le,action:"add.board",payload:{id:t,name:"Default",parent:e}},{id:de(),userId:ce,userName:le,action:"add.swimlane",payload:{id:n,name:"Todo",parent:t}},{id:de(),userId:ce,userName:le,action:"add.swimlane",payload:{id:r,name:"In progress",parent:t}},{id:de(),userId:ce,userName:le,action:"add.swimlane",payload:{id:o,name:"Done",parent:t}},{id:de(),userId:ce,userName:le,action:"add.board",payload:{id:It,name:"Closed",parent:e}},{id:de(),userId:ce,userName:le,action:"add.swimlane",payload:{id:Z,name:"Closed",parent:It}},{id:de(),userId:ce,userName:le,action:"lock.node",payload:{id:It}},{id:de(),userId:ce,userName:le,action:"lock.node",payload:{id:Z}}]}function Oe(){return ue!==null}function un(){if(!ue||ue.length===0)return ue=null,c("No pending default events to persist",null);let e=ue.map(t=>vt({event:t})).filter(a);return e.length>0?i([Pe.bold.red("Persisting default events failed"),"",...e.map((t,n)=>`${Pe.dim.gray(`${n+1}.`)} ${Pe.dim(t.message)}`),`
35
+ ${n.message}`):c("Pushed remote",!0)},Lr=async({repoRoot:e,worktreeRoot:t,ensureUpstream:n})=>{x.debug("[sync] bootstrap remote storage",{repoRoot:e,worktreeRoot:t,ensureUpstream:n});let r=!1,o=[Ji(),await ns({repoRoot:e}),await is({repoRoot:e,worktreeRoot:t}),await ss(t),await as(t),n?await ds(t):c("Skipped remote upstream bootstrap",!1)];for(let s of o){if(a(s))return i(s.message);r=r||!!s.data}return x.debug("[sync] bootstrap changed",r),c(n?"Bootstrapped remote storage":"Bootstrapped remote storage (readonly)",r)},Pr=(e,t)=>{for(let n of[Te(e),Te(t)]){let r=St(n);if(a(r))return i(r.message)}return c("Ensured remote layout",void 0)};var cs=({repoRoot:e,worktreeRoot:t,ownEventFileName:n})=>{let r=ze({root:e,fileName:n}),o=ze({root:t,fileName:n});return qe.existsSync(r)?(logger.debug("[sync] merge own event file to remote",{ownEventFileName:n,localFile:r,remoteFile:o}),Rt({sourceFile:r,targetFile:o})):(logger.debug("[sync] local own event file missing",r),c("Local own event file missing, nothing to merge",!1))},Dr=async({repoRoot:e,worktreeRoot:t,ownEventFileName:n})=>{let r=cs({repoRoot:e,worktreeRoot:t,ownEventFileName:n});if(a(r))return i(r.message);let o=await Nr(t);if(a(o))return i(o.message);if(!r.data&&!o.data)return c("Own event file already up to date in remote worktree",{createdCommit:!1});let s=await Tr({worktreeRoot:t,ownEventFileName:n});if(a(s))return i(s.message);let d=await Mr({repoRoot:e,worktreeRoot:t});return a(d)?i(d.message):c("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:d.data})},Fr=({repoRoot:e,worktreeRoot:t,ownEventFileName:n})=>{let r=ze({root:e,fileName:n}),o=ze({root:t,fileName:n});logger.debug("[sync] own event file sizes",{local:qe.existsSync(r)?qe.statSync(r).size:0,remote:qe.existsSync(o)?qe.statSync(o).size:0})},At=async({cwd:e=process.cwd(),ownEventFileName:t})=>{logger.debug("[sync] start write sync",{cwd:e,ownEventFileName:t});let n=await gr(e);if(a(n))return i(n.message);let r=n.data,o=Sr(r);logger.debug("[sync] resolved roots",{repoRoot:r,worktreeRoot:o});let s=await Ir(r);if(a(s))return i(s.message);if(s.data)return i("Cannot run :sync while the repository is in detached HEAD state");if(t.includes("/")||t.includes("\\"))return i("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return i("Own event file must end with .jsonl");let d=await Zt(r);if(a(d))return i(d.message);if(d.data)return i("Cannot run :sync while a merge, rebase, cherry-pick, or revert is in progress in the current repo");let l=await Ar(r);if(a(l))return i(l.message);logger.debug("[sync] ensure initial commit changed",l.data);let u=await Lr({repoRoot:r,worktreeRoot:o,ensureUpstream:!0});if(a(u))return i(u.message);let v=await Zt(o);if(a(v))return i(v.message);if(v.data)return i("Cannot run :sync while a merge, rebase, cherry-pick, or revert is in progress in the remote worktree");let f=Pr(r,o);if(a(f))return i(f.message);let N=!1,C,S=!1,M=!1,j=!1;logger.debug("[sync] pull remote branch before local copy");let kt=await tn({cwd:o,remote:K,branch:L});if(a(kt))return i(kt.message);S=kt.data,logger.debug("[sync] pulled remote",S);let Ot=wr({repoRoot:r,worktreeRoot:o});if(a(Ot))return i(Ot.message);j=Ot.data,logger.debug("[sync] hydrated from remote",j);let De=await Dr({repoRoot:r,worktreeRoot:o,ownEventFileName:t});if(a(De))return i(De.message);if(N=De.data.createdCommit,C=De.data.commitSha,Fr({repoRoot:r,worktreeRoot:o,ownEventFileName:t}),logger.debug("[sync] sync own file result",De.data),N||u.data){let ve=await on(o),Ye=ve;if(a(ve)&&Er(ve.message)){let gn=await tn({cwd:o,remote:K,branch:L});if(a(gn))return i(gn.message);let Fe=await Dr({repoRoot:r,worktreeRoot:o,ownEventFileName:t});if(a(Fe))return i(Fe.message);Fe.data.createdCommit&&(N=!0,C=Fe.data.commitSha),Fr({repoRoot:r,worktreeRoot:o,ownEventFileName:t}),logger.debug("[sync] retry sync own file result",Fe.data),Ye=await on(o)}if(a(Ye))return i(Ye.message);M=Ye.data,logger.debug("[sync] pushed remote",M)}else logger.debug("[sync] no commit created, skipped push");if(N){let ve=await T({args:["rev-parse","HEAD"],cwd:o});if(a(ve))return i(ve.message);C=ve.data.stdout.trim()}return c("Synced event logs with remote",{repoRoot:r,worktreeRoot:o,createdCommit:N,commitSha:C,pulled:S,pushed:M,hydrated:j,bootstrapped:u.data})};import{ulid as kr}from"ulid";var Me=null,ge=()=>structuredClone(Me),Le=e=>Me=e,Or=()=>{let{currentNode:e,selectedIndex:t}=y(),r=R(e.id)[t];return r?c("Resolved selected child",r):i("Target node not found")};function sn(e){let t=Or();if(a(t))return t;let{currentNode:n,nodes:r}=y();if(!n.parentNodeId)return i("Missing parent node id");let o=r[n.parentNodeId];if(!o)return i("Missing parent node");let s=H(o.id),d=s.findIndex(({id:C})=>C===n.id);if(d<0)return i("Current node not found among siblings");let l=s[d+e];if(!l)return i("Missing sibling node");let u=W();if(a(u))return i("Unable to resolve user ID");let{userId:v,userName:f}=u.data;if(Le({id:kr(),userId:v,userName:f,action:"move.node",payload:{id:t.data.id,parent:l.id,pos:{at:"end"}}}),!Me)return i("Could not materialize move state");let N=Se(Me,!0);return a(N)?N:c("Node moved successfully",N.data)}function an(e){let t=Or();if(a(t))return t;let{currentNode:n,selectedIndex:r}=y(),s=H(n.id)[r+e];if(!s)return i("Missing sibling node");let d=W();if(a(d))return i("Unable to resolve user ID");let{userId:l,userName:u}=d.data;if(Le({id:kr(),userId:l,userName:u,action:"move.node",payload:{id:t.data.id,parent:n.id,pos:{at:e===1?"after":"before",sibling:s.id}}}),!Me)return i("Could not materialize move state");let v=Se(Me,!0);return a(v)?v:c("Node moved successfully",v.data)}import ls from"node:os";import Ur from"node:path";import{z as Ge}from"zod";var us={userId:"",userName:"",preferredEditor:"",autoSync:!1},_r=Ge.object({preferredEditor:Ge.string().optional(),userName:Ge.string().optional(),userId:Ge.string().optional(),autoSync:Ge.boolean().optional()}).strict(),ms=".epiq",ps="config.json",Br=()=>Ur.join(ls.homedir(),ms),dn=()=>Ur.join(Br(),ps),cn=()=>{try{return Y.mkDir(Br()),c("Ensured ~/.epiq exists",null)}catch{return i("Unable to create ~/.epiq")}},gs=e=>{let t;try{t=JSON.parse(e)}catch{return i("Invalid ~/.epiq/config.json JSON")}let n=_r.safeParse(t??{});return n.success?c("Parsed config",n.data):i(`Invalid ~/.epiq/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Wr=()=>{let e=cn();if(a(e))return i(e.message);let t=dn(),n=Y.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{autoSync:!1,preferredEditor:"",userId:"",userName:""}):gs(n)},$r=e=>{let t=cn();if(a(t))return i(t.message);let n=_r.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=dn();try{return Y.writeToFile(r,JSON.stringify(n.data,null,2)+`
36
+ `),c("Config written",null)}catch{return i("Unable to write ~/.epiq/config.json")}},wt=e=>{let t=Wr();if(a(t))return i("Failed to read existing config");let n={...t.data,...e};return $r(n)},Hr=()=>{let e=dn(),t=cn();if(a(t))return i("Unable to create ~/.epiq");if(!(Y.readFile(e)!==null)){let u=$r(us);if(a(u))throw new Error("Unable to create ~/.epiq/config.json")}let r=Wr();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:d,autoSync:l}=r.data;return!s||!d?i("User name or ID not configured in ~/.epiq/config.json"):c("successfully loaded settings",{preferredEditor:o??"",userName:s,userId:d,autoSync:l??!1})};var Kr=e=>Object.values(y().tags).find(t=>t.name===e),Vr=e=>Object.values(y().contributors).find(t=>t.name===e),jr=[{systemOnly:!0,intent:b.Move,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=J().commandMeta,n=()=>{let l=ge();if(!l)return i("No pending move state");let u=l.payload.id;if(!y().nodes[u])return i("Moved node not found");let f=l.payload.parent,N=y().nodes[f];if(!N)return i("Move parent not found");let C=R(f).findIndex(S=>S.id===u);return C===-1?i("Moved node not found among rendered children"):(U.navigate({currentNode:N,selectedIndex:C}),c("Synchronized navigation to moved node",null))},r=l=>{if(a(l))return i(l.message);let u=n();return a(u)?i(u.message):c("Updated move preview",null)},{currentNode:o,selectedIndex:s}=y(),d=R(o.id)[s];if(!d)return I({mode:p.DEFAULT}),i("No move target");if(t==="start"){if(d.readonly)return i("Target node is read-only");if(s===-1)return i("No item selected");if(!d.parentNodeId)return i("Target has no parent");let l=R(d.parentNodeId),u=l.findIndex(({id:S})=>S===d.id);if(u===-1)return i("Target not found among siblings");let v=l[u-1],f=l[u+1],N=f!=null?{at:"before",sibling:f.id}:v!=null?{at:"after",sibling:v.id}:{at:"start"};Le({id:F(),action:"move.node",payload:{id:d.id,parent:d.parentNodeId,pos:N},...e.data}),I({mode:p.MOVE});let C=n();return a(C)?i(C.message):c("Move initialized",null)}if(t==="next")return I({mode:p.MOVE}),r(an(1));if(t==="previous")return I({mode:p.MOVE}),r(an(-1));if(t==="to-next")return I({mode:p.MOVE}),r(sn(1));if(t==="to-previous")return I({mode:p.MOVE}),r(sn(-1));if(t==="confirm"){I({mode:p.DEFAULT});let l=ge();if(!l)return i("No pending move to confirm");let u=$(l);if(a(u))return u;let v=n();return a(v)?i(v.message):(Le(null),c("Moved item",null))}return t==="cancel"?(Le(null),I({mode:p.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}},{intent:b.Delete,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=y(),r=R(t.id)[n];return r?$({id:F(),action:"delete.node",payload:{id:r.id},...e.data}):i("Unable to resolve child to delete")},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.Edit,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let t=ye(y().breadCrumb,"TICKET");if(a(t))return i("Edit target must be an issue");let n=t.data;if(n.readonly)return i("Cannot edit readonly field");let{currentNode:r,selectedIndex:o}=y();if(!R(n.id)[o])return i("No selected field");let d=R(r.id)[o];if(!d)return i("No selected field");if(d.readonly)return i("Cannot edit readonly field");let l=d.props.value;if(typeof l!="string")return i("Selected field is not editable text");let u=Zn(l);if(a(u))return i("Failed to edit field");let v=u.data;return v===l?c("No changes made",null):d.title==="Description"?$({id:F(),action:"edit.description",payload:{id:d.id,md:v},...e.data}):d.title==="Title"?$({id:F(),action:"edit.title",payload:{id:d.id,name:v},...e.data}):i(`Editing not supported for "${d.title}"`)},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.Filter,mode:p.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=J().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(l=>_(m.FILTER).map(u=>u.split(n)[0]).includes(l))(r))return i("Invalid filter modifier");let d={target:r,operator:"=",value:t.trim()};return q(l=>({...l,filters:e==="clear"?[]:[...l.filters,d],mode:p.DEFAULT})),c("Viewing help",null)}},{intent:b.ViewHelp,mode:p.COMMAND_LINE,action:()=>(I({mode:p.HELP}),c("Viewing help",null))},{intent:b.CloseIssue,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=y(),r=R(t.id)[n];if(!r)return i("Unable to close issue, no target found");if(!r.parentNodeId)return i("No target parent found");if(!z(r))return i("Cannot close in this context");let o=$({id:F(),action:"close.issue",payload:{id:r.id,parent:r.parentNodeId},...e.data});return a(o)?o:c("Viewing help",null)}},{intent:b.ReopenIssue,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=y(),r=R(t.id)[n];if(!r)return i("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):be(r.id,"TICKET");if(a(o))return i("Cannot reopen in this context");let s=o.data,d=$({id:F(),action:"reopen.issue",payload:{id:s.id},...e.data});return a(d)?d:c("Issue reopened",null)},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.SetUserName,mode:p.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:n}=oe(),r=ut()?.trim();if(!r)return i("No username provided");let o=r??n,s=e??F();if(!o||!s)return i("Unable to resolve user name or id");let d=wt({userName:o,userId:s,preferredEditor:t??""});return a(d)?d:(it({userName:o,userId:s}),I({mode:p.DEFAULT}),c(`Username set to "${r}"`,null))}},{intent:b.Init,mode:p.COMMAND_LINE,action:()=>{let e=un();if(a(e))return e;let{rootNodeId:t,nodes:n}=y();return U.navigate({currentNode:n[t],selectedIndex:0}),I({mode:p.DEFAULT}),c("Project initialized",null)}},{intent:b.SetEditor,mode:p.COMMAND_LINE,action:()=>{let e=ut()?.trim();if(!e)return i("No editor provided");let t=wt({preferredEditor:e});return a(t)?t:(it({preferredEditor:e}),I({mode:p.DEFAULT}),c(`Editor configuration set to "${e}"`,null))}},{intent:b.SetAutoSync,mode:p.COMMAND_LINE,action:()=>{let e=J().commandMeta.modifier;if(e!=="true"&&e!=="false")return i("Invalid response");let t=e.toLowerCase()==="true",n=wt({autoSync:t});return a(n)?n:(it({autoSync:t}),I({mode:p.DEFAULT}),c(`Auto synchronization set to "${t}"`,null))}},{intent:b.NewItem,mode:p.COMMAND_LINE,action:(e,t)=>{let n=W();if(a(n))return i("Unable to resolve user ID");if(!t.inputString)return i(`provide a name for your ${t.modifier}`);let{breadCrumb:r,currentNode:o,selectedIndex:s}=y(),d=l=>{let u=$(l);if(a(u))return u;let v=E.getNode(u.data.result.id);if(!v)return i("Created node not found");if(!v.parentNodeId)return u;let f=E.getNode(v.parentNodeId);return f?(U.navigate({currentNode:f,selectedIndex:E.getSiblings(v.parentNodeId).findIndex(({id:N})=>N===v.id)}),u):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:l}=y(),u=E.getNode(l);return u?d({id:F(),action:"add.board",payload:{id:F(),name:t.inputString,parent:u.id},...n.data}):i("Workspace not found")}if(t.modifier==="swimlane"){let l=ye(r,"BOARD");return a(l)?i("Unable to add swimlane in this context"):d({id:F(),action:"add.swimlane",payload:{id:F(),name:t.inputString,parent:l.data.id},...n.data})}if(t.modifier==="issue"){let l=R(o.id)[s],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&l?.context==="SWIMLANE"?l:(()=>{let S=ye(r,"SWIMLANE");return a(S)?null:S.data})();if(!u)return i("Unable to add issue in this context");let v=Ze({name:t.inputString,parent:u.id,user:n.data}),f=Ae(v);if(f.some(S=>a(S)))return i("Issue create failed: "+f.filter(a).map(S=>S.message).filter(Boolean).join(", "));let N=f[0];if(!N||a(N))return i("Issue creation failed");let C=v[0]?.payload.id;return C?(U.navigate({currentNode:u,selectedIndex:E.getSiblings(u.id).findIndex(({id:S})=>S===C)}),c("Issue created",null)):i("Unable to determine ticket id")}return fn()},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.SetView,mode:p.COMMAND_LINE,action:()=>{let{commandMeta:e}=J();return e.validity===re.Invalid?i("Invalid command "+ee):(q(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),c("View set",null))},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.Rename,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=y(),r=R(t.id)[n];if(!r)return i("Missing node");if(r.readonly)return i("Cannot rename readonly node");let o=ut();return o?$({id:F(),action:"edit.title",payload:{id:r.id,name:o},...e.data}):i("Provide a new name")},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.UntagTicket,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=J().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let o=Kr(r);if(!o)return i(`Tag "${r}" does not exist`);let{selectedNode:s}=y();if(!s)return i("Invalid untag target");let d=be(s.id,"TICKET");if(a(d))return i("Unable to untag issue in this context");let l=d.data,u=E.getFieldByTitle(l.id,"Tags");if(!u)return i("Unable to locate tags field");let v=R(u.id).find(f=>f.props?.value===o.id);return v?$({id:F(),action:"untag.issue",payload:{id:v.id,target:l.id,tagId:o.id},...e.data}):i("Issue is not tagged with that tag")},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.TagTicket,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=J().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let{selectedIndex:o,currentNode:s}=y(),d=R(s.id)[o];if(!d)return i("Invalid tag target");let l=be(d.id,"TICKET");if(a(l))return i("Unable to tag issue in this context");let u=l.data,v=Kr(r),f;if(v)f=v.id;else{let S=F(),M=$({id:F(),action:"create.tag",payload:{id:S,name:r},userId:e.data.userId,userName:e.data.userName});if(a(M))return M;f=M.data.result.id}let N=E.getFieldByTitle(u.id,"Tags");return N?R(N.id).some(S=>S.props?.value===f)?i("Already tagged with that tag"):$({id:F(),action:"tag.issue",payload:{id:F(),target:u.id,tagId:f},...e.data}):i("Unable to locate tags field")},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.AssignUserToTicket,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=J().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee");let{selectedIndex:o,currentNode:s}=y(),d=R(s.id)[o];if(!d)return i("Invalid assign target");let l=be(d.id,"TICKET");if(a(l))return i("Unable to assign issue in this context");let u=l.data,v=Vr(r),f;if(v)f=v.id;else{let S=F(),M=$({id:F(),action:"create.contributor",payload:{id:S,name:r},userId:e.data.userId,userName:e.data.userName});if(a(M))return M;f=M.data.result.id}let N=E.getFieldByTitle(u.id,"Assignees");return N?R(N.id).some(S=>S.props?.value===f)?i("Assignee already assigned"):$({id:F(),action:"assign.issue",payload:{id:F(),target:u.id,contributor:f},...e.data}):i("Unable to locate assignees field")},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.UnassignUserFromTicket,mode:p.COMMAND_LINE,action:()=>{let e=W();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=J().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee to remove");let o=Vr(r);if(!o)return i(`Assignee "${r}" does not exist`);let{selectedNode:s}=y();if(!s)return i("Invalid unassign target");let d=be(s.id,"TICKET");if(a(d))return i("Unable to unassign in this context");let l=d.data,u=E.getFieldByTitle(l.id,"Assignees");if(!u)return i("Unable to locate assignees field");let v=R(u.id).find(f=>f.props?.value===o.id);return v?$({id:F(),action:"unassign.issue",payload:{id:v.id,target:l.id,contributor:o.id},...e.data}):i(`Issue is not assigned to "${r}"`)},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.Sync,mode:p.COMMAND_LINE,action:async()=>{O(()=>""),I({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:e,userName:t}=oe();if(!e)return i("Unable to resolve userId");if(!t)return i("Unable to resolve userName");let n=Oe()?un():c("No pending default events",null);if(a(n))return i(`Unable to persist default events. ${n.message}`);let r=W();if(a(r)||!r.data)return i("Unable to resolve event log path");let o=He(r.data);logger.debug("[sync-command] pending defaults",Oe());let s=await At({ownEventFileName:o});if(a(s))return I({syncStatus:{msg:s.message,status:"outOfSync"}}),i(`Unable to sync state. ${s.message}`);I({syncStatus:{msg:"Synced",status:"synced"},mode:p.DEFAULT});let d=Ke();return a(d)?i("Unable to load events"):(Ee(d.data),c("Synced",!0))}},{intent:b.Peek,mode:p.COMMAND_LINE,action:async()=>{let e=ye(y().breadCrumb,"BOARD");if(a(e))return e;let t=Ke();if(a(t))return i(t.message);let n=t.data,{modifier:r}=J().commandMeta,o;if(r==="now"){let N=ln();if(a(N))return N;let C=Ee(n);return C.some(a)?i(C.map(S=>S.message).join(", ")):(I({mode:p.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}if(r==="prev"){let N=y().eventLog.at(-2),C=Bt(N);if(C===null)return i("No previous event to peek");o=C}else if(r==="next"){let N=y().unappliedEvents.at(0),C=Bt(N);if(C===null)return i("No next event to peek");o=C}else{let N=ct(r);if(!N)return i("Invalid peek date");o=N.getTime()}let s=e.data.id,{appliedEvents:d,unappliedEvents:l}=sr(n,o),u=ln();if(a(u))return u;let v=Ee(d);if(v.some(a))return i(v.map(N=>N.message).join(", "));let f=y().nodes[s];return f?(U.navigate({currentNode:f,selectedIndex:0}),I({mode:p.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:l}),c("Peeking ",!0)):i("Board did not exist at peek date")}}];var fs=new Set(["peek","filter","view-help"]),X=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=J();if(!t)return i("No command to confirm");if(!e&&n===re.Invalid)return i("Invalid command");let s=Gn(t);if(Vn(),y().readOnly&&!fs.has(s))return We({result:ee.Fail,message:"Command not available in readonly state",data:null});let d=jr.filter(u=>e||u.systemOnly!==!0).find(u=>u.intent===s);if(!d)return We({result:ee.Fail,message:"Command not found",data:null});let l=await d.action(d,{command:t,inputString:o,modifier:r});return a(l)?We(l):(jn({addToHistory:!e}),d.onSuccess?.(),We(l))};var Tt=[{intent:h.Exit,mode:p.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(I({mode:p.COMMAND_LINE}),O(()=>"move cancel"),X({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:p.DEFAULT,description:"[m] move init/confirm",action:()=>(I({mode:p.COMMAND_LINE}),O(()=>"move start"),X({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:p.MOVE,action:()=>(I({mode:p.COMMAND_LINE}),O(()=>"move confirm"),X({isForceExecutedBySystem:!0}))}],Mt=[{intent:h.MovePreviousItem,mode:p.MOVE,action:()=>ge()?(I({mode:p.COMMAND_LINE}),O(()=>"move previous"),X({isForceExecutedBySystem:!0})):i("No pending move")},{intent:h.MoveNextItem,mode:p.MOVE,action:()=>ge()?(I({mode:p.COMMAND_LINE}),O(()=>"move next"),X({isForceExecutedBySystem:!0})):i("No pending move")}],zr=[{intent:h.MoveToNextContainer,mode:p.MOVE,action:()=>ge()?(I({mode:p.COMMAND_LINE}),O(()=>"move to-next"),X({isForceExecutedBySystem:!0})):i("No pending move")},{intent:h.MoveToPreviousContainer,mode:p.MOVE,action:()=>ge()?(I({mode:p.COMMAND_LINE}),O(()=>"move to-previous"),X({isForceExecutedBySystem:!0})):i("No pending move")}];var qr={[P.WORKSPACE]:[...Tt,...Mt],[P.BOARD]:[...Tt,...Mt],[P.SWIMLANE]:[...Tt,...Mt,...zr],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var Gr=[{intent:h.AddItem,mode:p.DEFAULT,description:"[n] new...",action:()=>(I({mode:p.COMMAND_LINE}),O(()=>`${m.NEW} `),c("Adding new item",null))},{intent:h.Delete,mode:p.DEFAULT,description:"[d] delete",action:()=>(I({mode:p.COMMAND_LINE}),O(()=>`${m.DELETE} `),c("Deleting item",null))},{intent:h.InitCommandLine,mode:p.DEFAULT,description:"[:] focus command line",action:()=>(I({mode:p.COMMAND_LINE}),O(()=>""),c("Entering command line mode",null))},{intent:h.Confirm,mode:p.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(U.enterChildNode(),c("Entering context",null))},{intent:h.Exit,mode:p.DEFAULT,description:"[q] exit context",action:()=>(U.enterParentNode(),c("Exiting context",null))},{intent:h.NavPreviousItem,mode:p.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:h.NavNextItem,mode:p.DEFAULT,action:()=>(U.navigateToNextItem(),c("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:p.DEFAULT,action:()=>(U.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:p.DEFAULT,action:()=>(U.navigateToNextContainer(),c("Navigating to next container",null))},{intent:h.Edit,mode:p.DEFAULT,action:()=>(I({mode:p.COMMAND_LINE}),O(()=>"edit"),X(),c("Fired command",!0))},{intent:h.SetViewDense,mode:p.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(I({viewMode:"dense"}),c("View set",null))},{intent:h.SetViewWide,mode:p.DEFAULT,action:()=>(I({viewMode:"wide"}),c("View set",null))}];var Jr=[{intent:h.ViewHelp,mode:p.DEFAULT,action:()=>(I({mode:p.HELP}),c("Viewing help",null))},{intent:h.Exit,mode:p.HELP,action:()=>(I({mode:p.DEFAULT}),c("Exiting help",null))},{intent:h.Confirm,mode:p.COMMAND_LINE,action:()=>(X(),c("Executing command",null))},{intent:h.MoveCursorLeft,mode:p.COMMAND_LINE,action:()=>(jt(-1),c("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:p.COMMAND_LINE,action:()=>(jt(1),c("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:p.COMMAND_LINE,action:()=>(zt("left"),c("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:p.COMMAND_LINE,action:()=>(zt("right"),c("Moving cursor right of word",null))},{intent:h.ExitCommandLine,mode:p.COMMAND_LINE,action:()=>(I({mode:p.DEFAULT}),c("Exiting command line",null))},{intent:h.AutoCompleteCommand,mode:p.COMMAND_LINE,action:()=>(O((e,{remainder:t})=>t?e+t:e),c("Auto-completing command",null))},{intent:h.CaptureInput,mode:p.COMMAND_LINE,action:(e,{sequence:t})=>(O(n=>n+t),c("Capturing input",null))},{intent:h.EraseInput,mode:p.COMMAND_LINE,action:()=>(Hn(),c("Erasing input",null))},{intent:h.EraseInputWord,mode:p.COMMAND_LINE,action:()=>(Kn(),c("Erasing input word",null))},{intent:h.GetLastCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(zn(),c("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(qn(),c("Getting next command from history",null))}];import vs from"chalk";var Lt=": for command line",Yr="q to exit",Xr=`${vs.hex(Sn.accent)("m")} to confirm`,mn={[P.WORKSPACE]:[Lt],[P.BOARD]:[Lt],[P.BOARD+p.COMMAND_LINE]:[Lt],[P.SWIMLANE]:[Lt],[P.TICKET+p.HELP]:[Yr],[P.SWIMLANE+p.HELP]:[Yr],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+p.MOVE]:[Xr],[P.TICKET+p.MOVE]:[Xr]};var Pt=e=>e.trim().toLocaleLowerCase(),ys=(e,t)=>{let n=E.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},Es=e=>{let{tags:t}=y(),n=E.getFieldByTitle(e,"Tags");return n?H(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},Ns=e=>{let{contributors:t}=y(),n=E.getFieldByTitle(e,"Assignees");return n?H(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},Qr=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return Pt(e.title??"").includes(n);case"description":return Pt(ys(e.id,"Description")).includes(n);case"tag":return Es(e.id).map(Pt).some(l=>l.includes(n));case"assignee":return Ns(e.id).map(Pt).some(l=>l.includes(n));default:return!0}};function Zr(e,t,n){let r=t[e];if(!r)return i("buildBreadCrumb(): current node not found");let o=[],s=r;for(;s&&(o.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let d=o[o.length-1];return!d||d.id!==n?i("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var eo=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var Dt,pn,Is=new Set,to=()=>{for(let e of Is)e()};function no(e){let{currentNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return i("derive(): currentNodeId is missing");if(!r)return i("derive(): rootNode is missing");if(!o[r])return i("derive(): unable to find root node");let l=o[t];if(!l)return logger.error("Unable to derive state, currentNode not found"),i("Unable to derive state, currentNode not found");let u=Zr(t,o,r);if(a(u))return logger.error(u.message),u;let v=u.data,{context:f}=l,N=mn[f+n]??mn[f]??[],C=[...Gr,...qr[f]??[],...Jr],S=eo(C),M=xs(o,s),j=M[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,currentNode:l,breadCrumb:v,availableHints:N,availableActions:C,actionIndex:S,selectedNode:j,renderedChildrenIndex:M})}var y=()=>(Dt||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),Dt);function Jt(e){pn=e;let t={readOnly:!1,filters:[],tags:{},contributors:{},viewMode:"dense",mode:p.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live"},n=no(t);return a(n)?n:(Dt=n.data,to(),c("State initialized",null))}function q(e){let t=y(),n=e(t),r=no(n);return a(r)?i(r.message??"Unable to update state"):(Dt=r.data,to(),c("State updated",null))}var I=e=>q(t=>({...t,...e}));var xs=(e,t)=>{let n={};for(let r of Object.values(e))z(r)&&t.length>0&&!t.every(o=>Qr(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,s)=>{let d=e[o.id],l=e[s.id];return!d||!l?0:d.rank.localeCompare(l.rank)});return n},R=e=>y()?.renderedChildrenIndex[e]??[],ln=()=>pn?Jt(pn):i("Cannot reset state: no initial workspace found");var U={exit(){process.exit(0)},enterChildNode(){let e=y(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=R(t.id)[n];!r||t.context==="FIELD"||U.navigate({currentNode:r,selectedIndex:R(r.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=y();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=R(n.id),o=r.findIndex(({id:d})=>d===e.id),s=r.length===0?-1:o>=0?o:0;U.navigate({currentNode:n,selectedIndex:s})},navigateToNextItem:()=>ro(1),navigateToPreviousItem:()=>ro(-1),navigateToNextContainer:()=>oo(1),navigateToPreviousContainer:()=>oo(-1),navigate:({currentNode:e=y().currentNode,selectedIndex:t})=>{I({currentNodeId:e.id,selectedIndex:t})}},ro=e=>{let t=y(),n=R(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;U.navigate({selectedIndex:o})},oo=e=>{let{currentNode:t,nodes:n,selectedIndex:r}=y();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let s=R(o.id),d=s.findIndex(C=>C.id===t.id);if(d<0)return;let l=s.at(d+e)??s.at(0);if(!l)return;let u=R(l.id),v=Math.max(0,u.length-1),f=Math.min(Math.max(0,r),v),N=u.length?f:-1;U.navigate({currentNode:l,selectedIndex:N})};var ce="system",le="ACTOR",Je=bs(),ue=null;function Cs(){let e=Object.values(y().nodes).find(r=>r.context==="WORKSPACE");if(!e)throw new Error("No workspace found in event log");let[t]=R(e.id),[n]=t?R(t.id):[];if(logger.debug("Boot navigation target:",{workspace:e?.id,firstBoard:t?.id,firstSwimlane:n?.id}),n){let r=y().renderedChildrenIndex?.[n.id]??[];return{currentNode:n,selectedIndex:r.length>0?0:-1}}else return t?{currentNode:t,selectedIndex:0}:e?{currentNode:e,selectedIndex:0}:{currentNode:y().nodes[y().rootNodeId],selectedIndex:0}}function hs(){let e=Cs();U.navigate(e)}function Rs(){let e=Je(),t=Je(),n=Je(),r=Je(),o=Je();return[{id:de(),userId:ce,userName:le,action:"init.workspace",payload:{id:e,name:"Workspace"}},{id:de(),userId:ce,userName:le,action:"add.board",payload:{id:t,name:"Default",parent:e}},{id:de(),userId:ce,userName:le,action:"add.swimlane",payload:{id:n,name:"Todo",parent:t}},{id:de(),userId:ce,userName:le,action:"add.swimlane",payload:{id:r,name:"In progress",parent:t}},{id:de(),userId:ce,userName:le,action:"add.swimlane",payload:{id:o,name:"Done",parent:t}},{id:de(),userId:ce,userName:le,action:"add.board",payload:{id:It,name:"Closed",parent:e}},{id:de(),userId:ce,userName:le,action:"add.swimlane",payload:{id:Z,name:"Closed",parent:It}},{id:de(),userId:ce,userName:le,action:"lock.node",payload:{id:It}},{id:de(),userId:ce,userName:le,action:"lock.node",payload:{id:Z}}]}function Oe(){return ue!==null}function un(){if(!ue||ue.length===0)return ue=null,c("No pending default events to persist",null);let e=ue.map(t=>vt({event:t})).filter(a);return e.length>0?i([Pe.bold.red("Persisting default events failed"),"",...e.map((t,n)=>`${Pe.dim.gray(`${n+1}.`)} ${Pe.dim(t.message)}`),`
37
37
  `].join(`
38
38
  `)):(ue=null,c("Persisted pending default events",null))}function io(e){let t;e.some(r=>r.action==="init.workspace")?(ue=null,t=Ee(e)):(ue=Rs(),t=Ee([...ue]));let n=t.filter(a);return n.length>0?i([Pe.bold.red("Materializing failed"),"",...n.map((r,o)=>`${Pe.dim.gray(`${o+1}.`)} ${Pe.dim(r.message)}`),`
39
39
  `].join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "epiq",
3
- "version": "0.3.5",
3
+ "version": "0.3.6",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "EPIQ - CLI based issue tracker",