epiq 0.3.8 → 0.3.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -1,39 +1,65 @@
1
1
  #!/usr/bin/env node
2
- import{McpServer as Ss}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as As}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 Is,ulid as de}from"ulid";import{useSyncExternalStore as fm}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
- `,"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],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
- `);if(r[r.length-1]===""&&r.pop(),r.length<=dr)return;let o=r.slice(-dr).join(`
2
+ import{McpServer as gd}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as fd}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as L}from"zod";var pe={None:"none",Success:"success",Fail:"fail"},i=e=>({status:pe.Fail,message:e,value:null}),c=(e,t)=>({status:pe.Success,message:e,value:t}),l=e=>e.status==="fail",Zn=e=>e.status==="success";import{ulid as Ii}from"ulid";import{monotonicFactory as Pi,ulid as ft}from"ulid";var vt=Pi(),yt=({name:e,parent:t,user:{userId:n,userName:r}})=>{let o=vt(),s=vt(),a=vt(),d=vt();return[{id:ft(),userId:n,userName:r,action:"add.issue",payload:{id:o,parent:t,name:e}},{id:ft(),userId:n,userName:r,action:"add.field",payload:{id:s,parent:o,name:"Description",val:""}},{id:ft(),userId:n,userName:r,action:"add.field",payload:{id:a,parent:o,name:"Assignees"}},{id:ft(),userId:n,userName:r,action:"add.field",payload:{id:d,parent:o,name:"Tags"}}]};import Xe from"chalk";import{monotonicFactory as dd,ulid as Ee}from"ulid";import{useSyncExternalStore as id}from"react";var M={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function X(e){return e.context==="TICKET"}var Qn=e=>e.context==="SWIMLANE";var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function xt(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Nt=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Oe=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var er=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},tr=(e,t)=>t?e.get(t)??[]:[];var nr=new WeakMap,Li=e=>{let t=nr.get(e);return t||(t=er(e),nr.set(e,t)),t};var rr=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return tr(Li(e),r).filter(s=>xt(r,s)>=n)};var Di={hint:"",hints:[],overlap:0,remainder:""},or=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Di;let o=rr({wordList:r,inputToMatch:e,overlapThreshold:1});return Fi(t,o)},Fi=(e,t)=>{let n=t[0]??"",r=xt(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),a=r<(o??"").length,d=!!s,f=(d&&a?o:n)+(d&&a?":":" "),N=f.slice(r);return{hint:f,hints:t,overlap:r,remainder:N}};var ir=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var Ue=24n,ki=Ue*4n,Et=(1n<<ki)-1n,Oi=/^[0-9a-f]+$/;function sr(e){if(!e||!Oi.test(e))throw new Error(`Invalid hex rank: ${e}`);return BigInt("0x"+e)}function It(e,t=Ue){if(e<0n)throw new Error("Negative rank not allowed");return e.toString(16).padStart(Number(t),"0")}function Je(e,t){if(!e&&!t)return It(Et/2n,Ue);let n=e?sr(e):0n,r=t?sr(t):Et;if(r<=n)return It(Et/2n,Ue);let o=(n+r)/2n;return o===n||o===r?"":It(o,Ue)}function de(){return It(Et/2n,Ue)}var Y={workspace:(e,t)=>({id:e,title:t,rank:de(),isDeleted:!1,props:{},context:M.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r=!1)=>({id:e,title:t,rank:de(),isDeleted:!1,props:{},context:M.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n)=>({id:e,title:t,rank:de(),isDeleted:!1,props:{},context:M.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:(e,t,n,r={},o="horizontal")=>({id:e,title:t,rank:de(),isDeleted:!1,props:r,context:M.FIELD,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[]}),ticket:(e,t,n)=>({id:e,title:t,rank:de(),isDeleted:!1,props:{},context:M.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:de(),isDeleted:!1,props:r,context:M.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[]})};var G=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),ar=(e,t)=>e.findIndex(n=>n.id===t),rn=(e,t={at:"end"})=>{if(e.length===0)return c("Resolved rank",de());switch(t.at){case"start":{let n=e[0];return n?c("Resolved rank",Je(void 0,n.rank)):i("Unable to resolve first sibling")}case"end":{let n=e[e.length-1];return n?c("Resolved rank",Je(n.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let n=ar(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",Je(r?.rank,o.rank)):i("Sibling not found")}case"after":{let n=ar(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",Je(r.rank,o?.rank)):i("Sibling not found")}}};var Be=(e,t)=>{let{nodes:n}=v(),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}`)},Ui=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},on=(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"),x={deleteNode(e){Z(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 i("Edit target node not found");let o=on(r,"edit");if(o)return o;let s={...r,props:{...r.props,value:t}};return x.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=on(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("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 G(e).find(n=>n.title===t)},moveNode({id:e,parentId:t,position:n={at:"end"}}){let{rootNodeId:r}=v(),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 a=on(o,"move");if(a)return a;if(Ui(t,e))return i("Cannot move node into its own descendant");let d=G(t).filter(f=>f.id!==e),u=rn(d,n);if(l(u))return u;let m={...o,parentNodeId:t,rank:u.value};return this.updateNode(m),c("Moved node successfully",m)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return i("Node not found");if(r===e)return i("Cannot delete root node");let s=new Set,a=u=>{let m=t[u];if(!(!m||s.has(u))){s.add(u);for(let f of G(m.id))a(f.id)}};a(e);let d={...structuredClone(t)};for(let u of s){if(!d[u])return i("Unable to locate node to delete");d[u]={...d[u],isDeleted:!0}}return n?(h({nodes:d}),c("Successfully tomb stoned",o)):i("Unable to delete undefined")},createContributor(e){let t=Z(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return l(t)?i("Unable to create contributor"):c("Created contributor",e)},assign(e,t,n){let r=x.getContributor(t),o=x.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(G(s.id).some(u=>u.props?.value===t))return i("Contributor already assigned");let d=this.createNodeAtPosition(Y.field(n,r.name,s.id,{value:t}));return l(d)?d:c("Assigned contributor",d.value)},createTag(e){let t=Z(n=>({...n,tags:{...n.tags,[e.id]:e}}));return l(t)?i("Could not create tag"):c("Tag created",e)},tag(e,t,n){let r=x.getTag(t),o=x.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(G(s.id).some(u=>u.props?.value===t))return i("Tag already assigned");let d=this.createNodeAtPosition(Y.field(n,r.name,s.id,{value:t}));return l(d)?d:c("Tag added",d.value)},untag(e,t){let n=x.getTag(t),r=x.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=G(o.id).find(d=>d.props?.value===t);if(!s)return c("Issue is not tagged with that tag",null);let a={...s,isDeleted:!0};return this.updateNode(a),c("Tag removed",a)},unassign(e,t){let n=x.getContributor(t),r=x.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=G(o.id).find(d=>d.props?.value===t);if(!s)return c("Issue is not assigned to that contributor",null);let a={...s,isDeleted:!0};return this.updateNode(a),c("Assignee removed",a)},createNodeAtPosition(e,t={at:"end"}){if(!e.parentNodeId){let s={...e,rank:de()};return this.createNode(s),c("Created node",s)}let n=G(e.parentNodeId),r=rn(n,t);if(l(r))return r;let o={...e,rank:r.value};return this.createNode(o),c("Created node",o)},createNode(e){let t=Z(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return l(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=Z(o=>({...o,nodes:{...o.nodes,[e]:n}}));return l(r)?i(r.message):c("Locked node",n)},updateNode(e){let t=Z(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return l(t)?t:c("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 ht={autoSync:!1,preferredEditor:null,userName:null,userId:null},ge=()=>ht,Ct=e=>(ht={...ht,...e},ht);var dr=()=>{let e=ge(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},lr=()=>!Ze();var K={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"},w={accent:K.cyan,accent2:K.magenta,primary:K.white,secondary:K.grayDark,secondary2:K.grayLight,gray:K.gray,green:K.green,yellow:K.yellow,red:K.red};var y={red:K.red,yellow:K.yellow,green:K.green,blue:K.blue,magenta:K.magenta,cyan:K.cyan},_e={urgent:y.red,critical:y.red,important:y.red,blocker:y.red,asap:y.red,immediate:y.red,fail:y.red,failure:y.red,broken:y.red,bug:y.red,error:y.red,incident:y.red,outage:y.red,production:y.red,crash:y.red,security:y.red,warning:y.yellow,warn:y.yellow,risky:y.yellow,risk:y.yellow,attention:y.yellow,pending:y.yellow,review:y.yellow,"needs-review":y.yellow,qa:y.yellow,testing:y.yellow,test:y.yellow,validate:y.yellow,verification:y.yellow,staging:y.yellow,check:y.yellow,"follow-up":y.yellow,followup:y.yellow,waiting:y.yellow,blocked:y.yellow,hold:y.yellow,done:y.green,complete:y.green,completed:y.green,success:y.green,ok:y.green,stable:y.green,resolved:y.green,fixed:y.green,closed:y.green,merged:y.green,released:y.green,deployed:y.green,approved:y.green,verified:y.green,working:y.green,healthy:y.green,pass:y.green,passing:y.green,info:y.blue,information:y.blue,note:y.blue,docs:y.blue,documentation:y.blue,doc:y.blue,guide:y.blue,help:y.blue,explanation:y.blue,detail:y.blue,details:y.blue,context:y.blue,design:y.blue,discussion:y.blue,proposal:y.blue,idea:y.blue,feature:y.magenta,enhancement:y.magenta,improvement:y.magenta,refactor:y.magenta,refactoring:y.magenta,cleanup:y.magenta,optimize:y.magenta,optimization:y.magenta,perf:y.magenta,performance:y.magenta,upgrade:y.magenta,migration:y.magenta,modernize:y.magenta,debt:y.magenta,todo:y.cyan,next:y.cyan,planned:y.cyan,plan:y.cyan,future:y.cyan,backlog:y.cyan,investigate:y.cyan,explore:y.cyan,prototype:y.cyan};var cr=(e,t)=>{let r=b(e.id).find(o=>o.title===t);return r?b(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},sn=e=>cr(e,"Tags").map(t=>x.getTag(t)).filter(t=>!!t),bt=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!X(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",sn(n)??[])},St=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!X(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",an(n)??[])},an=e=>cr(e,"Assignees").map(t=>x.getContributor(t)).filter(t=>!!t);var ur=(e,t)=>{let r=b(e.id).find(o=>o.title===t);return r&&typeof r.props?.value=="string"?Oe(r.props.value):""};var p={EXIT:"exit",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",EXPORT:"export",NONE:""};var Bi=/^(\d+)(h|d|w|mo|y)$/,_i=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,$i=({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},Wi=(e,t=new Date)=>{let n=e.match(Bi);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let a=new Date(t);switch(o){case"h":return a.setHours(a.getHours()-s),a;case"d":return a.setDate(a.getDate()-s),a;case"w":return a.setDate(a.getDate()-s*7),a;case"mo":return a.setMonth(a.getMonth()-s),a;case"y":return a.setFullYear(a.getFullYear()-s),a;default:return null}},Hi=e=>{let t=e.match(_i);if(!t)return null;let[,n,r,o,s,a]=t,d=Number(n),u=Number(r),m=Number(o),f=s?Number(s):0,N=a?Number(a):0;return $i({year:d,month:u,day:m,hour:f,minute:N})?new Date(d,u-1,m,f,N):null},Rt=e=>{let t=e.trim().toLowerCase();return Wi(t)??Hi(t)},mr=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Ki=[{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}],pr=(e=Ki)=>{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 Vi=["BOARD","TICKET","SWIMLANE"],Me=[p.SYNC,p.HELP,p.EXPORT,p.SET_VIEW,p.SET_EDITOR,p.SET_USERNAME],At=[p.NEW,p.RENAME,p.DELETE,p.MOVE],dn=[p.TAG,p.UNTAG,p.ASSIGN,p.UNASSIGN,p.CLOSE_ISSUE,p.RE_OPEN_ISSUE,p.SET_DESCRIPTION],gr=[p.FILTER,p.PEEK],ji={WORKSPACE:[...Me,...At],BOARD:[...gr,...Me,...At],SWIMLANE:[...gr,...Me,...At],TICKET:[...Me,...At,...dn],FIELD:[...Me,...dn],FIELD_LIST:[...Me,...dn],TEXT:[...Me]},zi=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Gi=()=>{let{currentNode:e,selectedNode:t,readOnly:n}=v();if(!dr().isSetup)return[p.HELP,p.SET_EDITOR,p.SET_USERNAME];if(!lr())return[p.HELP,p.INIT];if(n)return[p.HELP,p.PEEK,p.EXPORT,p.SET_VIEW];let o=e.context??"WORKSPACE",s=t?.context,a=s&&Vi.includes(s);return ji[o].filter(d=>d===p.RENAME||d===p.DELETE||d===p.MOVE?a:!0)},W=e=>{let{currentNode:t}=v(),n=t.context??"WORKSPACE";return{[p.NONE]:Gi(),[p.EXIT]:["confirm"],[p.EXPORT]:[],[p.SYNC]:[],[p.INIT]:[],[p.HELP]:[],[p.PEEK]:[...pr(),"now","prev","next"],[p.SET_USERNAME]:[],[p.SET_DESCRIPTION]:["confirm"],[p.DELETE]:["confirm"],[p.RE_OPEN_ISSUE]:["confirm"],[p.CLOSE_ISSUE]:["confirm"],[p.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[p.FILTER]:["tag","assignee","description","title","clear"],[p.SET_VIEW]:["dense","wide"],[p.SET_EDITOR]:[...ir],[p.TAG]:[...new Set([...Object.keys(_e),...x.getExistingTags()])],[p.UNTAG]:[...bt()?.value?.map(({name:o})=>o)??[]],[p.UNASSIGN]:[...St()?.value?.map(({name:o})=>o)??[]],[p.ASSIGN]:x.getExistingAssignees(),[p.RENAME]:[],[p.NEW]:zi(n)}[e]??[]};import $e from"chalk";import{decodeTime as fr}from"ulid";var vr=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"};var yr=e=>{try{return c("Decoded date",new Date(fr(e)))}catch(t){return i("Decoding failed + "+t.message)}},ln=e=>{if(!e?.id)return null;try{return fr(e.id)}catch{return null}};var Pe=(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 xr from"chalk";var un={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},qi=(e,t,n)=>Math.max(t,Math.min(n,e)),cn=(e,t,n)=>e+(t-e)*n,Nr=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Xi=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,a=e/60,d=s*(1-Math.abs(a%2-1)),u=0,m=0,f=0;a>=0&&a<1?(u=s,m=d):a>=1&&a<2?(u=d,m=s):a>=2&&a<3?(m=s,f=d):a>=3&&a<4?(m=d,f=s):a>=4&&a<5?(u=d,f=s):(u=s,f=d);let N=o-s/2;return[Math.round((u+N)*255),Math.round((m+N)*255),Math.round((f+N)*255)]},Yi=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Ji=(e,t,n)=>[Math.round(cn(e[0],t[0],n)),Math.round(cn(e[1],t[1],n)),Math.round(cn(e[2],t[2],n))],Qe=e=>{let n=Nr(e)%360,r=Xi(n,un.stringColor.saturation,un.stringColor.lightness);return Yi(r)},Zi=e=>{let t=un.gradient.stops,n=qi(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),a=o-s;return Ji(t[s],t[s+1],a)},Tt=e=>Nr(e.toLowerCase().trim())/4294967295,Qi=e=>{let t=Tt(e);return Zi(t)},es=e=>{let[t,n,r]=Qi(e);return{normal:o=>xr.bgRgb(t,n,r).black(o),cursor:o=>xr.bgRgb(t,n,r).white.bold(o)}};var mn=e=>es(e).normal(` ${e} `),J=(e,t=_e)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:Qe(r)};var fe={None:"none",Invalid:"invalid",Valid:"valid"};var ts=["BOARD","TICKET","SWIMLANE"],pn=()=>{let e=v().selectedNode;return e?.context?ts.includes(e?.context)?_():U({message:"Command not available in this context"}):U({message:"Missing target context"})},q="<ENTER> to confirm",_=(e="",t=[])=>({message:e,validity:fe.Valid,completionWordList:t}),U=({message:e,completionWordList:t=[]})=>({validity:fe.Invalid,message:e,completionWordList:t}),tt=e=>e.length===0,be=({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)=>Tt(f)-Tt(N)).slice(0,r).map(mn),m=u.length>s?u.join(" "):"";return m?`${e}${m}${n}`:""},gn=({modifier:e})=>{let t="confirm";return e===t?_(q):U({message:tt(e)?`if you are certain, enter ${mn(t)}`:"",completionWordList:[t]})},ns=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?_(q):U({message:tt(n)?t:""}),rs=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?U({message:n}):_():U({message:tt(r)?t:""}),et=({hint:e})=>({modifier:t,inputString:n})=>tt(t)&&tt(n)?U({message:e,completionWordList:[]}):_(q),os={[p.EXPORT]:()=>_(q+", and create export markdown file"),[p.PEEK]:e=>{let t=e.modifier;if(t==="now")return _(q);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 _(q);let r=Rt(t);if(!t||!r)return U(n);let o=Pe(v().breadCrumb,"BOARD");if(l(o))return U({message:"Command is not applicable in this context"});let s=yr(o.value.id);return l(s)?U({message:"Unable to peek: board id is not a valid ULID"}):mr({date:r,horizonDate:s.value})?_(q):U({message:$e.red(`nothing to peek before ${s.value.toISOString().slice(0,16).replace("T"," ")}`)})},[p.EXIT]:()=>_(q+" and exit the application"),[p.INIT]:()=>_(q),[p.FILTER]:e=>{if(e.modifier==="clear")return _();let t=a=>W(p.FILTER).includes(a);if(!e.modifier||!t(e.modifier??""))return U({message:be({wordList:W(p.FILTER),inputString:e.inputString}),completionWordList:W(p.FILTER)});let r=Object.values(v().tags).map(a=>a.name),o=Object.values(v().contributors).map(a=>a.name),s=e.modifier==="tag"?r:e.modifier==="assignee"?o:[];return e.inputString?s.length&&!s.includes(e.inputString.trim()??"")?U({message:be({prefix:`existing ${e.modifier}s... `,wordList:s,noOfHints:10,inputString:e.inputString}),completionWordList:s}):_():U({message:be({prefix:"one of... ",wordList:s,noOfHints:10,inputString:e.inputString}),completionWordList:s})},[p.NONE]:e=>{let t=W(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?_():U({message:be({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[p.NEW]:e=>rs({list:W(p.NEW),hint:be({wordList:W(p.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[p.SET_DESCRIPTION]:()=>_(q),[p.HELP]:()=>_(q),[p.RENAME]:()=>{let e=pn();return e.validity==="invalid"?e:_(q)},[p.DELETE]:e=>{let t=pn();return t.validity==="invalid"?t:gn(e)},[p.CLOSE_ISSUE]:e=>gn(e),[p.RE_OPEN_ISSUE]:e=>gn(e),[p.MOVE]:e=>{let t=pn();return t.validity==="invalid"?t:et({hint:be({prefix:"hey hacker! These commands are blocked for you... ",wordList:W(p.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[p.TAG]:e=>{let t=x.getExistingTags().map(n=>` ${$e.bgHex(J(n))(" "+n+" ")} `).slice(0,10);return et({hint:"tag name like... "+t.join("")})(e)},[p.UNTAG]:e=>{let t=bt();if(l(t))return U({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${$e.bgHex(J(r))(" "+r+" ")} `).slice(0,10);return n.length?et({hint:" ... "+n.join("")})(e):U({message:"Issue has not tags",completionWordList:[]})},[p.ASSIGN]:e=>{let t=x.getExistingAssignees().map(n=>` ${$e.bgHex(J(n))(" "+n+" ")} `).slice(0,10);return et({hint:"assign to... "+t.join("")})(e)},[p.UNASSIGN]:e=>{let t=St();if(l(t))return U({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${$e.bgHex(J(r))(" "+r+" ")} `).slice(0,10);return n.length?et({hint:"remove assignee... "+n.join("")})(e):U({message:"Issue has no assignees",completionWordList:[]})},[p.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=W(p.SET_EDITOR);return e.modifier?_(q):U({message:be({wordList:t,inputString:e.inputString})})},[p.SET_USERNAME]:e=>e.inputString?_():U({message:`Enter a username. Saved in ${$e.bgBlack("~/.epiq-global/")}`}),[p.SET_VIEW]:e=>ns({list:W(p.SET_VIEW),hint:be({wordList:W(p.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[p.SYNC]:()=>_(q)},Er=Object.fromEntries(Object.entries(os).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Ir=["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 S={Exit:"exit",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",Export:"export"};var hr=e=>Object.values(p).includes(e),Cr=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:a,validity:d,completionWordList:u}=Er[n].validate(n,r,s),m=o==="command"?Object.values(p):n&&e.target==="modifier"?W(n):Ir;return{validity:d,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?or(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var br=e=>{let t=e.trimStart(),n=ss(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),a=as(e),d=hr(r)?r:null,u=d!==null,m=r!=="",f=d?W(d)??[]:[],N=d&&f.includes(o)?o:"",E="word";n.length===0||n.length===1&&!s?E="command":(n.length===1&&s||n.length===2&&!s)&&(E="modifier");let I=s?"":a,R=is(t,d,N);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:a,hasCommand:m,command:d,isCommandKeyword:u,isLastWordCompleted:s,modifier:N,target:E,inputToMatch:I,inputString:R}},is=(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},ss=e=>e.trim()?e.trim().split(/\s+/):[],as=e=>e.trimEnd().split(/\s+/).at(-1)??"";var Sr=" ",We={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:fe.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},ds=new Set,Rr=()=>{for(let e of ds)e()};var ve=e=>{let n=e(We),r=br(n.value),o=n.cursorPosition===n.value.length;We={...n,commandMeta:Cr(r,o)},Rr()},nt=({message:e,status:t})=>{let n=structuredClone(We);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,We=n,Rr(),c(e,null)},fn=e=>{ve(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},vn=e=>{ve(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}})},Ar=()=>{ve(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}})},Tr=()=>{ve(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}})},$=e=>{ve(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),a=s+o,d=Math.max(0,Math.min(s.length,a.length));return{...t,value:a,cursorPosition:d,commandIsPending:!1}})},wr=()=>{ve(e=>({...e,commandIsPending:!0}))},Mr=({addToHistory:e=!0})=>{ve(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),ls()},Pr=()=>{ve(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}})},Lr=()=>{ve(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ls=()=>$(()=>""),Q=()=>We,wt=()=>{let[e,...t]=We.value.split(Sr);return t.join(Sr).trim()};var T={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 Dr=e=>{let{context:t}=v()?.currentNode;if(!t)return S.None;switch(e){case p.EXIT:return S.Exit;case p.EXPORT:return S.Export;case p.INIT:return S.Init;case p.DELETE:return S.Delete;case p.SET_DESCRIPTION:return S.Edit;case p.HELP:return S.ViewHelp;case p.RE_OPEN_ISSUE:return S.ReopenIssue;case p.CLOSE_ISSUE:return S.CloseIssue;case p.TAG:return S.TagTicket;case p.UNTAG:return S.UntagTicket;case p.ASSIGN:return S.AssignUserToTicket;case p.UNASSIGN:return S.UnassignUserFromTicket;case p.RENAME:return S.Rename;case p.NEW:return S.NewItem;case p.FILTER:return S.Filter;case p.MOVE:return S.Move;case p.PEEK:return S.Peek;case p.SET_USERNAME:return S.SetUserName;case p.SET_EDITOR:return S.SetEditor;case p.SET_VIEW:return S.SetView;case p.SYNC:return S.Sync;default:return S.None}};import{ulid as B}from"ulid";import{spawnSync as ys}from"node:child_process";import xs from"node:os";import Ur from"node:path";import{ulid as Ns}from"ulid";import{accessSync as cs,copyFileSync as us,existsSync as Mt,mkdirSync as Fr,readdirSync as kr,readFileSync as ms,renameSync as ps,rmSync as gs,statSync as Or,unlinkSync as fs,writeFileSync as vs}from"node:fs";import He from"node:path";var ee={writeToFile:(e,t)=>{try{let n=He.dirname(e);Mt(n)||Fr(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);vs(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return ms(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=ee.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)&&Or(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await cs(e),!0}catch{return!1}},mkDir:e=>Fr(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=He.parse(t);for(;;){let r=He.join(t,e);try{if(Mt(r)&&Or(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=He.dirname(t)}return null},readFirstJSON(e){try{if(!ee.dirExists(e))return null;let t=kr(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=He.join(e,t);return ee.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return ee.dirExists(e)?kr(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{fs(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{gs(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(He.dirname(t)),!n?.overwrite&&Mt(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{ps(e,t)}catch(r){if(r?.code==="EXDEV"){us(e,t),this.rmFile(e);return}throw r}}};function Es(){let{preferredEditor:e}=ge(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Is(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function Br(e){let t=Ur.join(xs.tmpdir(),"epiq");ee.mkDir(t);let n=Ur.join(t,Ns());ee.writeToFile(n,e??"");let r=Es();for(let o of r){let s=Is(o,n),a=ys(s,{stdio:"inherit",shell:!0});if(!a.error&&a.status===0){let d=ee.readFile(n);if(d==null)return i("Unable to read edited file");let u=d.replace(/\r?\n$/,"");return c("Successfully edited",u)}}return i("Unable to open editor")}import Ft from"node:fs";import In from"node:path";import{decodeTime as Ds}from"ulid";import{z as En}from"zod";import Ss from"node:fs";import Rs from"node:path";import{decodeTime as As,monotonicFactory as Ts}from"ulid";import{z as ot}from"zod";import yn from"node:fs";import Ke from"node:path";var xn=process.env.IS_LOCAL==="true",Se=".epiq",ne=".epiq-global",Pt="events",hs="epiq",_r=e=>Ke.join(e,hs),Cs=e=>Ke.join(e,Se),rt=e=>Ke.join(Cs(e),Pt),bs=e=>{let t=Ke.join(e,Se);return yn.existsSync(t)&&yn.statSync(t).isDirectory()},re=e=>{let t=Ke.resolve(e);for(;;){if(bs(t))return c("Resolved closest .epiq root",t);let n=Ke.dirname(t);if(n===t)return i("No .epiq directory found in any parent");t=n}},$r=e=>{let t=rt(e);try{return yn.mkdirSync(t,{recursive:!0}),c("Resolved events dir",t)}catch(n){return i(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}};var Wr=e=>({action:e.action,payload:e.payload});var Kr=1,Hr=Ts(),ws=ot.tuple([ot.string().min(1),ot.string().min(1).nullable()]),Ms=ot.looseObject({v:ot.literal(Kr),id:ws}),Nn=e=>{let t=Ms.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(", ")}`)},Lt=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",V=()=>{let{userName:e,userId:t}=ge();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:Lt(t),userName:Lt(e)}):i("Unable to resolve actor ID from settings or OS user info"):i("User ID not configured"):i("User name not configured")},it=({userId:e,userName:t})=>`${Lt(e)}.${Lt(t)}.jsonl`,Ps=(e,{userId:t,userName:n})=>{let r=it({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return i(`Invalid event log file name: ${r}`);let s=Rs.join(rt(e),r);return c("Successfully resolved event log path",s)},Ls=(e,t)=>{let n={[e.action]:e.payload,v:Kr,id:t};return Nn(n)};function Dt({event:e,rootDir:t=process.cwd()}){try{let n=re(t);if(l(n))return n;let r=$r(n.value);if(l(r))return r;let o=Ps(n.value,{userId:e.userId,userName:e.userName});if(l(o))return o;let s=Vr(n.value);if(l(s))return i(s.message);let a=s.value?Hr(Math.max(Date.now(),As(s.value)+1)):Hr(),d=Ls(Wr(e),[a,s.value]);return l(d)?i(d.message):(Ss.appendFileSync(o.value,`${JSON.stringify(d.value)}
3
+ `,"utf8"),c("Event persisted",{path:o.value,entry:d.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return i(`Failed to persist event: ${r}`)}}var Fs=En.object({userId:En.string().min(1).default("unknown"),userName:En.string().min(1).default("unknown")}),ks=e=>{let[t,n]=In.basename(e,".jsonl").split("."),r=Fs.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):i(`Invalid event file name ${In.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Os=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])},Us=(e,t)=>t in e,Bs=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),_s=e=>{let{userId:t,userName:n,...r}=e,o=Os(r);if(l(o))return i(o.message);let s=o.value,a=e.id?.[0];return a?Us(r,s)?c("Decoded persisted event",Bs({id:a,action:s,payload:r[s],userId:t,userName:n})):i(`Persisted event is missing payload for action: ${s}`):i("Persisted event is missing id")},kt=e=>{if(!Ft.existsSync(e))return c("Event file missing",[]);let t=ks(e);if(l(t))return i(t.message);let n=Ft.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
4
+ `)){let s=o.trim();if(!s)continue;let a;try{a=JSON.parse(s)}catch{return i(`Failed to parse event JSON from ${e}: ${s}`)}let d=Nn(a);if(l(d))return i(`${d.message} in ${e}: ${s}`);r.push({...d.value,userId:t.value.userId,userName:t.value.userName})}return c("Parsed persisted events file",r)};function jr(e){let t=rt(e);if(!Ft.existsSync(t))return i("No events found");let n=Ft.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>In.join(t,o)),r=[];for(let o of n){let s=kt(o);if(l(s))return i(s.message);r.push(...s.value)}return c("All events loaded",$s(r))}function st(e){let t=jr(e);if(l(t))return i(t.message);let n=[];for(let r of t.value){let o=_s(r);if(l(o))return i(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);n.push(o.value)}return c("Loaded merged events",n)}function Vr(e=process.cwd()){let t=jr(e);return l(t)?i(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var $s=e=>{let t=new Map;for(let d of e){let u=d.id[1]??null,m=t.get(u)??[];m.push(d),t.set(u,m)}for(let d of t.values())d.sort((u,m)=>u.id[0].localeCompare(m.id[0]));let n=[],r=new Set;a(t.get(null)??[]);let o=!0;for(;o;){o=!1;for(let d=0;d<n.length;d++){let u=n[d];if(!u)continue;let m=(t.get(u.id[0])??[]).filter(f=>!r.has(f.id[0]));if(m.length!==0){n.splice(d+1,0,...m);for(let f of m)r.add(f.id[0]);o=!0,d+=m.length}}}let s=e.filter(d=>!r.has(d.id[0])).sort((d,u)=>d.id[0].localeCompare(u.id[0]));return n.push(...s),n;function a(d){for(let u of d)r.has(u.id[0])||(n.push(u),r.add(u.id[0]))}},zr=(e,t)=>{let n=e.findIndex(r=>{try{return Ds(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var Gr=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 Ws=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[le,Ot]=Ws;var D=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Hs={"init.workspace":e=>{let{id:t,name:n}=e.payload,r=Y.workspace(t,n);hn(r);let o=x.createNodeAtPosition(r);return l(o)?D(o.message??"Failed to initialize workspace",e):c("Workspace initialized",{action:e.action,result:o.value})},"add.workspace":e=>{let{id:t,name:n}=e.payload,r=Y.workspace(t,n),o=x.createNodeAtPosition(r);return l(o)?D(o.message??"Failed to add workspace",e):c("Added workspace",{action:e.action,result:o.value})},"add.board":e=>{let{id:t,name:n,parent:r}=e.payload,o=x.createNodeAtPosition(Y.board(t,n,r));return l(o)?D(o.message??"Unable to create board",e):c("Added board",{action:e.action,result:o.value})},"add.swimlane":e=>{let{id:t,name:n,parent:r}=e.payload,o=x.createNodeAtPosition(Y.swimlane(t,n,r));return l(o)?D(o.message??"Unable to create swimlane",e):c("Added swimlane",{action:e.action,result:o.value})},"add.issue":e=>{let{id:t,name:n,parent:r}=e.payload,o=x.createNodeAtPosition(Y.ticket(t,n,r));return l(o)?D(o.message??"Unable to create issue",e):c("Added issue",{action:e.action,result:o.value})},"add.field":e=>{let{id:t,name:n,parent:r,val:o}=e.payload,s=x.createNodeAtPosition(Y.field(t,n,r,{value:o},n.includes("Description")?"vertical":"horizontal"));return l(s)?D(s.message??`Unable to create field: ${n}`,e):c("Added field",{action:e.action,result:s.value})},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!x.getNode(t))return D(`Unable to locate node with id ${t}`,e);let o=x.renameNode(t,n);return l(o)?D(o.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=x.tombstoneNode(t);return l(n)?D(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=x.createTag({id:t,name:n});return l(r)?D(r.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=x.createContributor({id:t,name:n});return l(r)?D(r.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:r.value})},"tag.issue":e=>{let{id:t,target:n,tagId:r}=e.payload,o=x.tag(n,r,t);return l(o)?D(o.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:o.value})},"untag.issue":e=>{let{target:t,tagId:n}=e.payload,r=x.untag(t,n);return l(r)?D(r.message??"Unable to untag ",e):c("Issue untagged",{action:e.action,result:r.value})},"assign.issue":e=>{let{id:t,contributor:n,target:r}=e.payload,o=x.assign(r,n,t);return l(o)?D(o.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:o.value})},"unassign.issue":e=>{let{target:t,contributor:n}=e.payload,r=x.unassign(t,n);return l(r)?D(r.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:r.value})},"move.node":e=>{let{id:t,parent:n,pos:r}=e.payload,o=x.moveNode({id:t,parentId:n,position:r});return l(o)?D(o.message??"Failed to move node",e):c("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=x.editValue(t,n);return l(r)?D(r.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t}=e.payload,n=x.getNode(t);if(!n)return D("Unable to locate issue",e);if(!X(n))return D("Can only close issues",e);let r=x.getNode(le);if(!r)return D("Unable to locate target swimlane",e);if(r.id===n.parentNodeId)return D("Cannot close closed issue",e);let s=x.moveNode({id:t,parentId:r.id});return l(s)?D(s.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:s.value})},"reopen.issue":e=>{let{id:t}=e.payload,n=x.getNode(t);if(!n)return D("Unable to locate issue",e);if(!X(n))return D("Can only reopen issues",e);let r=x.getNode(le);if(!r)return D("Unable to locate closed swimlane",e);if(!(n.parentNodeId===r.id))return D("Issue is not closed",e);let s=Gr(n);if(!s)return D("Unable to resolve previous parent from issue history",e);if(s===r.id)return D("Previous parent resolves to closed swimlane",e);if(!x.getNode(s))return D("Previous parent no longer exists",e);let d=x.moveNode({id:t,parentId:s});return l(d)?D(d.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:d.value})},"lock.node":e=>{let{id:t}=e.payload,n=x.lockNode(t);return l(n)?D(n.message??"Unable to lock node",e):c("Node locked",{action:e.action,result:n.value})}},Ks=(e,t)=>{let n=x.getNode(e);n&&x.updateNode({...n,log:[...n.log??[],t]})},Vs=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 Ve(e,t=!1){let n=Hs[e.action](e);if(l(n))return n;t||([...new Set(Vs(e))].forEach(a=>Ks(a,e)),Z(a=>({...a,eventLog:[...a.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?D("Invalid user ID format",e):(x.createContributor({name:o,id:r}),n)}var Le=e=>e.map(t=>Ve(t));function j(e){let t=Ve(e);if(t.status!==pe.Success)return t;let n=Dt({event:e});return l(n)?n:t}function je(e){return e.map(t=>j(t))}import ca from"node:fs";import{createHash as Xs}from"node:crypto";import dt from"node:fs";import Ys from"node:os";import ie from"node:path";var Cn=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let a=r(...s);if(!n.has(a)){let d=e(...s).then(u=>(l(u)&&n.delete(a),u));n.set(a,d)}return n.get(a)});return o.clear=()=>n.clear(),o};import at from"fs";import Xr from"path";import js from"util";var qr=1e3,Yr=()=>{let e=process.cwd(),t=re(e);if(!l(t))return Xr.join(t.value,Se,"log","epiq.log")};function zs(){if(!xn)return;let e=Yr();if(e===void 0||!at.existsSync(e))return;let n=at.readFileSync(e,"utf8").split(`
5
+ `);if(n[n.length-1]===""&&n.pop(),n.length<=qr)return;let r=n.slice(-qr).join(`
6
6
  `)+`
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 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
- `)));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
- ${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
- ${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(`
14
- `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(mr).includes(r);return c("Checked worktree registration",o)},en=async e=>{let t=await Ne({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Ct=async e=>{let t=await T({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved current branch",t.data.stdout.trim())},yr=async e=>{let t=await T({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved short HEAD sha",t.data.stdout.trim())},Er=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),tn=async({cwd:e,remote:t,branch:n})=>{let r=await bt({repoRoot:e,remote:t,branch:n});if(a(r))return i(r.message);if(!r.data)return c("Remote branch missing, skipped pull",!1);x.debug("[git] fetch start",{cwd:e,remote:t,branch:n});let o=await T({args:["fetch",t,n],cwd:e});if(x.debug("[git] fetch done",o),a(o))return i(`Failed to fetch ${n}
15
- ${o.message}`);x.debug("[git] pull start",{cwd:e,remote:t,branch:n});let s=await T({args:["pull","--rebase",t,n],cwd:e});return x.debug("[git] pull done",s),a(s)?i(`Failed during pull --rebase
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(`
7
+ `;at.writeFileSync(e,r,"utf8")}function bn(e,t,n=!1){if(!xn)return;let r=Yr();if(!r)return;let o=js.format(...t),s=new Date,d=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
8
+ `;at.mkdirSync(Xr.dirname(r),{recursive:!0}),at.appendFileSync(r,d,"utf8"),zs()}var te={info(...e){bn("[Info]",e,!1)},debug(...e){bn("->",e,!0)},error(...e){bn("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=te;import{spawn as Gs}from"node:child_process";import Sn from"node:fs";import Qr from"node:path";var O="epiq/events",oe="origin";var H={stage:({cwd:e,pathspec:t})=>F({args:["add",t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>F({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>F({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>F({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>F({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push",...r?["-u"]:[],t,n]:["push"];return F({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>F({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>F({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>F({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>F({args:["worktree","prune"],cwd:e})};var Jr=15e3,qs={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},eo=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Sn.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=Gs("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:qs}),s=!1,a="",d="",u=f=>{s||(s=!0,clearTimeout(m),r(f))},m=setTimeout(()=>{o.kill("SIGTERM");let f=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${Jr}ms`].join(`
9
+ `);u(n?{stdout:a,stderr:f,exitCode:124}:i(f))},Jr);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",f=>{a+=f}),o.stderr.on("data",f=>{d+=f}),o.on("error",f=>{if(n){u({stdout:a,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:a,stderr:d,exitCode:N});return}if(N!==0){u(i([`git ${e.join(" ")}`,d.trim()||a.trim()||"Git command failed"].filter(Boolean).join(`
11
+ `)));return}u(c("Git command succeeded",{stdout:a,stderr:d,exitCode:N}))})}),F=({args:e,cwd:t})=>eo({args:e,cwd:t,allowFail:!1}),ze=({args:e,cwd:t})=>eo({args:e,cwd:t,allowFail:!0}),Ut=async({cwd:e,message:t})=>{let n=await H.commit({cwd:e,message:t});if(l(n))return i(`Failed to create commit
12
+ ${n.message}`);let r=await F({args:["rev-parse","HEAD"],cwd:e});return l(r)?i(`Commit created, but failed to read HEAD SHA
13
+ ${r.message}`):c("Created commit and resolved SHA",r.value.stdout.trim())},Rn=async e=>{let t=await ao(e);if(l(t))return i(t.message);let n=t.value,o=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","REBASE_HEAD","rebase-merge","rebase-apply"].filter(s=>Sn.existsSync(Qr.join(n,s)));return c("Checked for in-progress Git operation",o.length>0)},An=async({repoRoot:e})=>{let n=(await ze({args:["remote","get-url",oe],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},Bt=async({repoRoot:e,branch:t})=>{let n=await ze({args:["ls-remote","--heads",oe,t],cwd:e});return n.exitCode!==0?i(n.stderr.trim()||`Unable to inspect remote branch ${oe}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},to=async({repoRoot:e,branch:t})=>{let n=await ze({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}`)},Zr=e=>{try{return Sn.realpathSync.native(e)}catch{return Qr.resolve(e)}},no=async({repoRoot:e,worktreeRoot:t})=>{let n=await F({args:["worktree","list","--porcelain"],cwd:e});if(l(n))return i(n.message);let r=Zr(t),o=n.value.stdout.split(`
14
+ `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Zr).includes(r);return c("Checked worktree registration",o)},Tn=async e=>{let t=await ze({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},_t=async e=>{let t=await F({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return l(t)?i(t.message):c("Resolved current branch",t.value.stdout.trim())},ro=async e=>{let t=await F({args:["rev-parse","--short","HEAD"],cwd:e});return l(t)?i(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},oo=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),wn=async({cwd:e,branch:t})=>{let n=await Bt({repoRoot:e,branch:t});if(l(n))return i(n.message);if(!n.value)return c("Remote branch missing, skipped pull",!1);let r=await H.fetch({cwd:e,remote:oe,branch:t});if(l(r))return i(`Failed to fetch ${t}
15
+ ${r.message}`);let o=await H.pullRebase({cwd:e,remote:oe,branch:t});return l(o)?i(`Failed during pull --rebase
16
+ ${o.message}`):c("Pulled with rebase",!0)},io=async e=>{let t=await F({args:["status","--porcelain"],cwd:e});return l(t)?i(t.message):c("Checked state branch changes",t.value.stdout.trim().length>0)},so=async e=>{let t=await _t(e);return l(t)?i(t.message):c("Checked detached HEAD state",t.value==="HEAD")};var lo="4b825dc642cb6eb9a060e54bf8d69288fbee4904",co=e=>ie.join(Se,Pt,e),Js=e=>Xs("sha1").update(ie.resolve(e)).digest("hex").slice(0,12),uo=()=>ie.join(Ys.homedir(),ne),mo=()=>ie.join(uo(),"worktrees"),po=e=>ie.join(mo(),Js(e)),Zs=e=>ie.join(e,Se),De=e=>ie.join(Zs(e),Pt),Mn=({root:e,fileName:t})=>ie.join(De(e),t),lt=e=>{try{return dt.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return i(t instanceof Error?t.message:String(t))}},go=()=>{let e=lt(uo());if(l(e))return i(`Ensure epiq home failed.
17
+ `+e.message);let t=lt(mo());return l(t)?i(`Ensure worktrees dir failed.
18
+ `+t.message):c("Ensured epiq storage",!0)},fo=e=>{dt.existsSync(e)&&(te.debug("[sync] remove path",e),dt.rmSync(e,{recursive:!0,force:!0}))},vo=e=>{let t=De(e);if(!dt.existsSync(t))return c("Events dir missing",[]);let n=dt.readdirSync(t,{withFileTypes:!0}).filter(r=>r.isFile()).map(r=>r.name).filter(r=>r.endsWith(".jsonl")).sort();return c("Listed event files",n)},yo=(e,t)=>{for(let n of[De(e),De(t)]){let r=lt(n);if(l(r))return i(r.message)}return c("Ensured state branch",void 0)},xo=async e=>{let t=await F({args:["ls-tree","--name-only","HEAD"],cwd:e});if(l(t))return i(`ensure state branch is storage only failed
19
+ `+t.message);let r=t.value.stdout.trim().split(`
20
+ `).filter(Boolean).filter(a=>a!==Se);if(r.length===0)return c("State branch is storage-only",!1);let o=await F({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(l(o))return i(`Failed to clean storage branch
21
+ ${o.message}`);let s=await Ut({cwd:e,message:"[epiq:repair-storage-branch]"});return l(s)?i(s.message):c("Cleaned storage branch",!0)},No=Cn(async(e=process.cwd())=>{let t=await F({args:["rev-parse","--show-toplevel"],cwd:e});return l(t)?i("Not inside a Git repository"):c("Resolved repo root",t.value.stdout.trim())},e=>ie.resolve(e)),ao=Cn(async e=>{let t=await F({args:["rev-parse","--git-dir"],cwd:e});if(l(t))return i(t.message);let n=t.value.stdout.trim(),r=ie.isAbsolute(n)?n:ie.join(e,n);return c("Resolved git dir",r)},e=>ie.resolve(e));import Re from"node:fs";import ct from"node:path";var ho=async e=>{let t=ct.join(e,".gitignore"),n=Re.existsSync(t)?Re.readFileSync(t,"utf8"):"",r=".epiq";return n.split(`
22
+ `).some(d=>{let u=d.trim();return u===r||u===r+"/"})?c(`${r} already ignored`,!1):(n=n.trimEnd()+`
23
+
24
+ # [epiq]: hydrated state is never to be committed
25
+ ${r}
26
+ `,Re.writeFileSync(t,n+`
27
+ `,"utf8"),te.info(`Added ${r} to .gitignore (epiq local cache)`),c(`${r} ignored`,!0))},Co=async e=>{if((await ze({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);te.info("Creating initial commit");let n=await H.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return l(n)?i(n.message):c("Created initial commit",!0)},Eo=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Qs=async e=>{let t=await _t(e);if(l(t))return i(t.message);let n=await ro(e);if(l(n))return i(n.message);let r=`[epiq:sync:${Eo(t.value)}:${Eo(n.value)}]`;return c("Built sync commit message",r)},Io=async e=>{te.info(`Creating ${O}`);let t=await F({args:["commit-tree",lo,"-m","[epiq:init-state-branch]"],cwd:e});if(l(t))return i(`Failed to create state branch commit
28
+ ${t.message}`);let n=t.value.stdout.trim(),r=await F({args:["update-ref",`refs/heads/${O}`,n],cwd:e});return l(r)?i(`Failed to create ${O}
29
+ ${r.message}`):c("Created state branch",!0)},ea=async({repoRoot:e})=>{let t=await to({repoRoot:e,branch:O});if(l(t))return i(`Ensure local state branch failed
30
+ `+t.message);if(t.value)return c("Local state branch already exists",!1);let n=await An({repoRoot:e});if(l(n))return i(`Ensure local state branch failed
31
+ `+n.message);if(!n.value)return Io(e);let r=await Bt({repoRoot:e,branch:O});if(l(r))return i(`Ensure local state branch failed
32
+ `+r.message);if(!r.value)return Io(e);let o=await H.fetch({cwd:e,remote:oe,branch:O});if(l(o))return i(`Failed to fetch ${O} from remote
33
+ ${o.message}`);let s=await F({args:["branch","--track",O,`${oe}/${O}`],cwd:e});return l(s)?i(`Failed to create local ${O} from remote
34
+ ${s.message}`):c("Created local state branch from remote",!0)},ta=async({repoRoot:e,branch:t})=>{let n=await F({args:["worktree","list","--porcelain"],cwd:e});if(l(n))return i(n.message);let r=n.value.stdout.split(`
35
+ `),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return c("Found worktree for branch",o)}return c("No worktree found for branch",null)},na=async({repoRoot:e,stateBranchRoot:t})=>{let n=lt(ct.dirname(t));if(l(n))return i(`Failed to create state branch worktree
36
+ `+n.message);Re.existsSync(t)&&!Re.existsSync(ct.join(t,".git"))&&(te.info("Removing broken state branch worktree path"),fo(t)),te.info("Creating state branch worktree");let r=await H.worktreeAdd({cwd:e,worktreeRoot:t,branch:O});return l(r)?i(`Failed to create state branch worktree
37
+ ${r.message}`):c("Created state branch worktree",!0)},ra=async({repoRoot:e,stateBranchRoot:t})=>{let n=await ta({repoRoot:e,branch:O});if(l(n))return i(n.message);let r=ct.resolve(t),o=n.value?ct.resolve(n.value):null;if(o&&o===r&&Re.existsSync(o))return c("State branch already checked out in expected worktree",!1);if(o&&o!==r){te.info("Moving state branch worktree to expected location");let d=await H.worktreeRemove({cwd:e,worktreeRoot:o});if(l(d))return i(`Failed to remove existing state branch worktree
38
+ ${d.message}`)}if(o&&!Re.existsSync(o)){te.info("Pruning stale state branch worktree");let d=await H.worktreePrune({cwd:e});if(l(d))return i(`Failed to prune stale worktrees
39
+ ${d.message}`)}let s=await no({repoRoot:e,worktreeRoot:t});if(l(s))return i(s.message);let a=Re.existsSync(t);if(s.value&&a)return c("State branch worktree already exists",!1);if(s.value&&!a){te.info("Pruning missing registered state branch worktree");let d=await H.worktreePrune({cwd:e});if(l(d))return i(`Failed to prune stale worktrees
40
+ ${d.message}`)}return na({repoRoot:e,stateBranchRoot:t})},oa=async e=>{let t=await _t(e);if(l(t))return i(t.message);if(t.value===O)return c("State branch already checked out",!1);let n=await H.checkout({cwd:e,branch:O});return l(n)?i(`Failed to checkout ${O}
41
+ ${n.message}`):c("Checked out state branch",!0)},ia=async e=>{let t=await Tn(e);if(l(t))return i(t.message);if(t.value)return c("State branch upstream already configured",!1);let n=await An({repoRoot:e});if(l(n))return i(n.message);if(!n.value)return c("No remote available for state branch upstream",!1);let r=await Bt({repoRoot:e,branch:O});if(l(r))return i(r.message);if(!r.value)return c("Remote state branch missing; upstream will be configured on first push",!1);te.info(`Configuring ${O} upstream`);let o=await H.fetch({cwd:e,remote:oe,branch:O});if(l(o))return i(`Failed to fetch ${O}
42
+ ${o.message}`);let s=await H.setUpstream({cwd:e,branch:O,upstream:`${oe}/${O}`});return l(s)?i(`Failed to set state branch upstream
43
+ ${s.message}`):c("Configured state branch upstream",!0)},bo=async({stateBranchRoot:e,ownEventFileName:t})=>{let n=await H.stage({cwd:e,pathspec:co(t)});return l(n)?i(`Failed to stage state branch own event file
44
+ ${n.message}`):c("Staged state branch own event file",void 0)},So=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Qs(e);return l(n)?i(`Create state branch sync commit failed
45
+ `+n.message):Ut({cwd:t,message:n.value})},Pn=async e=>{let t=await Tn(e);if(l(t))return i(t.message);let n=t.value?await H.push({cwd:e}):await H.push({cwd:e,remote:oe,branch:O,setUpstream:!0});return l(n)?i(`Failed during state branch push
46
+ ${n.message}`):c("Pushed state branch",!0)},Ro=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=[go(),await ea({repoRoot:e}),await ra({repoRoot:e,stateBranchRoot:t}),await oa(t),await xo(t),n?await ia(t):c("Skipped state branch upstream bootstrap",!1)];for(let s of o){if(l(s))return i(s.message);r=r||!!s.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage (readonly)",r)};import $t from"node:fs";import Dn from"node:path";import{decodeTime as sa}from"ulid";var Ln=e=>{let[t,n]=e.id;return`${t}:${n??""}`},Ao=e=>{let[t]=e.id;return sa(t)},aa=e=>{let{userId:t,userName:n,...r}=e;return r},da=e=>e.length===0?"":e.map(t=>JSON.stringify(aa(t))).join(`
17
47
  `)+`
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)};var Il=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));var Ar=async e=>{if((await Ne({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);let n=await T({args:["commit","--allow-empty","-m","Initial commit"],cwd:e});return a(n)?i(n.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",Qi=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)},Zi=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
- ${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}
20
- ${r.message}`):c("Created empty storage branch",!0)},es=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
21
- ${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
22
- ${s.message}`):c("Created local remote branch from remote",!0)}}return Zi(e)},ts=async({repoRoot:e,branch:t})=>{let n=await T({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let r=n.data.stdout.split(`
23
- `),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return c("Found worktree for branch",o)}return c("No worktree found for branch",null)},ns=async({repoRoot:e,worktreeRoot:t})=>{x.debug("[sync] create remote worktree",t);let n=St(V.dirname(t));if(a(n))return i(n.message);ne.existsSync(t)&&!ne.existsSync(V.join(t,".git"))&&(x.debug("[sync] remove broken remote worktree path",t),Yi(t));let r=await T({args:["worktree","add",t,L],cwd:e});return a(r)?i(`Failed to create remote worktree
24
- ${r.message}`):c("Created remote worktree",!0)},rs=async({repoRoot:e,worktreeRoot:t})=>{x.debug("[sync] ensure remote worktree",t);let n=await ts({repoRoot:e,branch:L});if(a(n))return i(n.message);let r=n.data,o=V.resolve(t),s=r?V.resolve(r):null;if(s&&s===o&&ne.existsSync(s))return x.debug("[sync] reuse existing remote branch worktree",{expected:o,actual:s}),c("Remote branch already checked out in expected worktree",!1);if(s&&s!==o){x.debug("[sync] remove old remote branch worktree",{expected:o,actual:s});let u=await T({args:["worktree","remove","--force",s],cwd:e});if(a(u))return i(`Failed to remove existing remote worktree
25
- ${u.message}`)}if(s&&!ne.existsSync(s)){x.debug("[sync] prune stale branch worktree registration",{existingBranchWorktree:s});let u=await T({args:["worktree","prune"],cwd:e});if(a(u))return i(`Failed to prune stale worktrees
26
- ${u.message}`)}let d=await vr({repoRoot:e,worktreeRoot:t});if(a(d))return i(d.message);let l=ne.existsSync(t);if(d.data&&l)return x.debug("[sync] remote worktree exists"),c("Remote worktree already exists",!1);if(d.data&&!l){x.debug("[sync] prune stale remote worktree registration");let u=await T({args:["worktree","prune"],cwd:e});if(a(u))return i(`Failed to prune stale worktrees
27
- ${u.message}`)}return ns({repoRoot:e,worktreeRoot:t})},os=async e=>{let t=await Ct(e);if(a(t))return i(t.message);if(t.data===L)return x.debug("[sync] remote branch already checked out"),c("Remote branch already checked out",!1);x.debug("[sync] checkout remote branch",L);let n=await T({args:["checkout",L],cwd:e});return a(n)?i(`Failed to checkout ${L}
28
- ${n.message}`):c("Checked out remote branch",!0)},is=async e=>{let t=await T({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return i(t.message);let r=t.data.stdout.trim().split(`
29
- `).filter(Boolean).filter(d=>d!==rn);if(r.length===0)return c("Remote branch is storage-only",!1);x.debug("[sync] remove app files from storage branch",r);let o=await T({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(a(o))return i(`Failed to clean storage branch
30
- ${o.message}`);let s=await Qt({cwd:e,message:"[epiq:repair-storage-branch]"});return a(s)?i(s.message):c("Cleaned storage branch",!0)},ss=async e=>{x.debug("[sync] ensure remote upstream",L);let t=await en(e);if(a(t))return i(t.message);if(t.data)return x.debug("[sync] remote upstream already configured"),c("Remote upstream already configured",!1);let n=await xt({repoRoot:e,remote:K});if(a(n))return i(n.message);if(!n.data)return x.debug("[sync] no remote configured for upstream"),c("No remote available for upstream",!1);let r=await bt({repoRoot:e,remote:K,branch:L});if(a(r))return i(r.message);if(!r.data)return x.debug("[sync] remote branch missing; upstream will be configured on first push"),c("Deferred upstream until first push",!1);x.debug("[sync] fetch remote branch before upstream set");let o=await T({args:["fetch",K,L],cwd:e});if(a(o))return i(`Failed to fetch ${L}
31
- ${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
32
- ${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
33
- ${n.message}`):c("Staged remote own event file",void 0)},Mr=async({repoRoot:e,worktreeRoot:t})=>{let n=await Qi(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
34
- ${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 es({repoRoot:e}),await rs({repoRoot:e,worktreeRoot:t}),await os(t),await is(t),n?await ss(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 as=({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=as({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 Ar(r);if(a(s))return i(`Failed to ensure initial commit: ${s.message}`);logger.debug("[sync] ensure initial commit changed",s.data);let d=await Ir(r);if(a(d))return i(d.message);if(d.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 l=await Zt(r);if(a(l))return i(l.message);if(l.data)return i("Cannot run :sync while a merge, rebase, cherry-pick, or revert is in progress in the current repo");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 ds from"node:os";import Ur from"node:path";import{z as Ge}from"zod";var cs={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(),ls=".epiq",us="config.json",Br=()=>Ur.join(ds.homedir(),ls),dn=()=>Ur.join(Br(),us),cn=()=>{try{return Y.mkDir(Br()),c("Ensured ~/.epiq exists",null)}catch{return i("Unable to create ~/.epiq")}},ms=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:""}):ms(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)+`
35
- `),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(cs);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 ps=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&&!ps.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 gs from"chalk";var Lt=": for command line",Yr="q to exit",Xr=`${gs.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(),fs=(e,t)=>{let n=E.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},vs=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):[]},ys=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(fs(e.id,"Description")).includes(n);case"tag":return vs(e.id).map(Pt).some(l=>l.includes(n));case"assignee":return ys(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,Es=new Set,to=()=>{for(let e of Es)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=Ns(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 Ns=(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=Is(),ue=null;function xs(){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 bs(){let e=xs();U.navigate(e)}function Cs(){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)}`),`
48
+ `,la=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(Ln(r),r);return[...n.values()].sort((r,o)=>{let s=Ao(r)-Ao(o);return s!==0?s:Ln(r).localeCompare(Ln(o))})},Fn=({sourceFile:e,targetFile:t})=>{let n=kt(e);if(l(n))return i(n.message);let r=kt(t);if(l(r))return i(r.message);let o=la(r.value,n.value),s=da(o);return($t.existsSync(t)?$t.readFileSync(t,"utf8"):"")===s?c("Event file already merged",!1):($t.mkdirSync(Dn.dirname(t),{recursive:!0}),$t.writeFileSync(t,s,"utf8"),c("Merged event file",!0))},To=({repoRoot:e,stateBranchRoot:t})=>{let n=vo(t);if(l(n))return i(n.message);let r=De(t),o=De(e),s=!1;for(let a of n.value){let d=Dn.join(r,a),u=Dn.join(o,a),m=Fn({sourceFile:d,targetFile:u});if(l(m))return i(m.message);s=s||m.value}return c("Hydrated event files from state branch",s)};var ua=({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=Mn({root:e,fileName:n}),o=Mn({root:t,fileName:n});return ca.existsSync(r)?Fn({sourceFile:r,targetFile:o}):c("Local own event file missing, nothing to merge",!1)},ma=async({cwd:e,ensureUpstream:t})=>{let n=await No(e);if(l(n))return i(n.message);let r=n.value,o=po(r),s=await ho(r);if(l(s))return i("Sync aborted. Unable to gitignore hydrated events");let a=await Rn(r);if(l(a))return i(a.message);if(a.value)return i("Cannot sync while a git operation is in progress in the current repo");let d=await Co(r);if(l(d))return i(d.message);let u=await Ro({repoRoot:r,stateBranchRoot:o,ensureUpstream:t});if(l(u))return i(u.message);let m=await Rn(o);if(l(m))return i(m.message);if(m.value)return i("Cannot sync while a git operation is in progress in the state branch");let f=yo(r,o);return l(f)?i(f.message):c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:o,bootstrapped:u.value})},wo=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=ua({repoRoot:e,stateBranchRoot:t,ownEventFileName:n});if(l(r))return i(r.message);let o=await io(t);if(l(o))return i(o.message);if(!r.value&&!o.value)return c("Own event file already up to date in state branch",{createdCommit:!1});let s=await bo({stateBranchRoot:t,ownEventFileName:n});if(l(s))return i(s.message);let a=await So({repoRoot:e,stateBranchRoot:t});return l(a)?i(a.message):c("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:a.value})},Wt=async({cwd:e=process.cwd(),ownEventFileName:t})=>{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 n=await ma({cwd:e,ensureUpstream:!0});if(l(n))return n;let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,a=await so(r);if(l(a))return i(a.message);if(a.value)return i("Cannot run :sync while the repository is in detached HEAD state");let d=!1,u,m=!1,f=!1,N=!1,E=await wn({cwd:o,branch:O});if(l(E))return i(E.message);m=E.value;let I=To({repoRoot:r,stateBranchRoot:o});if(l(I))return i(I.message);N=I.value;let R=await wo({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(l(R))return i(R.message);if(d=R.value.createdCommit,u=R.value.commitSha,d||s){let A=await Pn(o),C=A;if(l(A)&&oo(A.message)){let P=await wn({cwd:o,branch:O});if(l(P))return i(P.message);let z=await wo({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(l(z))return i(z.message);z.value.createdCommit&&(d=!0,u=z.value.commitSha),C=await Pn(o)}if(l(C))return i(C.message);f=C.value,logger.debug("[sync] pushed to state branch",f)}else logger.debug("[sync] no commit created, skipped push");if(d){let A=await F({args:["rev-parse","HEAD"],cwd:o});if(l(A))return i(A.message);u=A.value.stdout.trim()}return c("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:d,commitSha:u,pulled:m,pushed:f,hydrated:N,bootstrapped:s})};import{ulid as Mo}from"ulid";var Ge=null,Ae=()=>structuredClone(Ge),qe=e=>Ge=e,Po=()=>{let{currentNode:e,selectedIndex:t}=v(),r=b(e.id)[t];return r?c("Resolved selected child",r):i("Target node not found")};function kn(e){let t=Po();if(l(t))return t;let{currentNode:n,nodes:r}=v();if(!n.parentNodeId)return i("Missing parent node id");let o=r[n.parentNodeId];if(!o)return i("Missing parent node");let s=G(o.id),a=s.findIndex(({id:E})=>E===n.id);if(a<0)return i("Current node not found among siblings");let d=s[a+e];if(!d)return i("Missing sibling node");let u=V();if(l(u))return i("Unable to resolve user ID");let{userId:m,userName:f}=u.value;if(qe({id:Mo(),userId:m,userName:f,action:"move.node",payload:{id:t.value.id,parent:d.id,pos:{at:"end"}}}),!Ge)return i("Could not materialize move state");let N=Ve(Ge,!0);return l(N)?N:c("Node moved successfully",N.value)}function On(e){let t=Po();if(l(t))return t;let{currentNode:n,selectedIndex:r}=v(),s=G(n.id)[r+e];if(!s)return i("Missing sibling node");let a=V();if(l(a))return i("Unable to resolve user ID");let{userId:d,userName:u}=a.value;if(qe({id:Mo(),userId:d,userName:u,action:"move.node",payload:{id:t.value.id,parent:n.id,pos:{at:e===1?"after":"before",sibling:s.id}}}),!Ge)return i("Could not materialize move state");let m=Ve(Ge,!0);return l(m)?m:c("Node moved successfully",m.value)}import pa from"node:os";import Lo from"node:path";import{z as ut}from"zod";var ga={userId:"",userName:"",preferredEditor:"",autoSync:!1},Do=ut.object({preferredEditor:ut.string().optional(),userName:ut.string().optional(),userId:ut.string().optional(),autoSync:ut.boolean().optional()}).strict(),fa="config.json",Fo=()=>Lo.join(pa.homedir(),ne),Un=()=>Lo.join(Fo(),fa),Bn=()=>{try{return ee.mkDir(Fo()),c(`Ensured ~/${ne} exists`,null)}catch{return i(`Unable to create ~/${ne}`)}},va=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${ne}/config.json JSON`)}let n=Do.safeParse(t??{});return n.success?c("Parsed config",n.data):i(`Invalid ~/${ne}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},ko=()=>{let e=Bn();if(l(e))return i(e.message);let t=Un(),n=ee.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{autoSync:!1,preferredEditor:"",userId:"",userName:""}):va(n)},Oo=e=>{let t=Bn();if(l(t))return i(t.message);let n=Do.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Un();try{return ee.writeToFile(r,JSON.stringify(n.data,null,2)+`
49
+ `),c("Config written",null)}catch{return i(`Unable to write ~/${ne}/config.json`)}},Ht=e=>{let t=ko();if(l(t))return i("Failed to read existing config");let n={...t.value,...e};return Oo(n)},Uo=()=>{let e=Un(),t=Bn();if(l(t))return i(`Unable to create ~/${ne}`);if(!(ee.readFile(e)!==null)){let u=Oo(ga);if(l(u))throw new Error(`Unable to create ~/${ne}/config.json`)}let r=ko();if(l(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:a,autoSync:d}=r.value;return!s||!a?i(`User name or ID not configured in ~/${ne}/config.json`):c("successfully loaded settings",{preferredEditor:o??"",userName:s,userId:a,autoSync:d??!1})};var _o=()=>{let{currentNode:e,selectedIndex:t}=v(),n=b(e.id)[t];return{currentNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:n?.parentNodeId??null,selectedIndex:t}},Bo=(e,t)=>Math.max(0,Math.min(e,Math.max(0,t-1))),$o=e=>{let{nodes:t}=v(),n=t[e.currentNodeId];if(n&&!n.isDeleted&&e.selectedNodeId){let s=b(n.id).findIndex(a=>a.id===e.selectedNodeId);if(s>=0)return k.navigate({currentNode:n,selectedIndex:s}),c("Restored navigation",null)}if(e.selectedNodeId){let o=t[e.selectedNodeId];if(o&&!o.isDeleted&&o.parentNodeId){let s=t[o.parentNodeId];if(s&&!s.isDeleted){let a=b(s.id).findIndex(d=>d.id===o.id);if(a>=0)return k.navigate({currentNode:s,selectedIndex:a}),c("Restored navigation to moved node",null)}}}if(n&&!n.isDeleted){let o=b(n.id);return k.navigate({currentNode:n,selectedIndex:Bo(e.selectedIndex,o.length)}),c("Restored navigation to previous container",null)}if(e.parentNodeId){let o=t[e.parentNodeId];if(o&&!o.isDeleted){let s=b(o.id);return k.navigate({currentNode:o,selectedIndex:Bo(e.selectedIndex,s.length)}),c("Restored navigation to parent",null)}}let r=t[v().rootNodeId];return!r||r.isDeleted?i("Unable to restore navigation"):(k.navigate({currentNode:r,selectedIndex:0}),c("Restored navigation to root",null))};import ti from"node:fs";import Va from"node:path";import ja from"react";import{Box as Ha}from"ink";import Yt from"react";import{Box as Wn,Text as Ta}from"ink";import me from"react";import{Text as Wo}from"ink";import Ho,{useEffect as Ko,useState as ya}from"react";var Vo={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},se=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=ue(),r=Vo[n]??Vo.default,[o,s]=ya(0);if(Ko(()=>{s(0)},[r]),Ko(()=>{if(!e)return;let d=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(d)},[e,r]),!e)return Ho.createElement(Wo,null,t);let a=r[o]??r[0]??t;return Ho.createElement(Wo,{color:w.accent,dimColor:o===1},a)};import{Box as _n,Text as xa}from"ink";import Kt from"react";var Vt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),a=Math.max(1,Math.ceil(r)),d=Math.max(1,Math.floor(s/a)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-d),f=o?Math.min(m,Math.max(0,u-d+1)):Math.min(m,Math.floor(u/d)*d),N=f+d,E=e.slice(f,N),I=e.length>d,R=s,A=I?Math.max(1,Math.floor(d/e.length*R)):R,C=Math.max(0,R-A),P=Math.max(1,e.length-d),z=I?Math.floor(f/P*C):0;return Kt.createElement(_n,{flexDirection:"row",height:s,width:"100%"},Kt.createElement(_n,{flexDirection:"column",flexGrow:1,height:s},E),Kt.createElement(_n,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((Jn,Ye)=>Kt.createElement(xa,{key:Ye,color:I&&Ye>=z&&Ye<z+A?w.accent:w.secondary},I?"\u2502":" "))))};import{Box as Gt,Text as Sa}from"ink";import Fe from"react";import{Text as Na}from"ink";import Ea from"react";var Ia=e=>e.toLowerCase().trim(),ha=(e,t=_e)=>{let n=Ia(e);return t[n]?t[n]:Qe(n)},jt=({id:e,isSelected:t})=>{let n=x.getContributor(e);if(n)return Ea.createElement(Na,{underline:t,color:ha(n.name)},"@"+n.name)};import{Text as Ca}from"ink";import ba from"react";var zt=({id:e,isSelected:t})=>{let n=x.getTag(e);if(n)return ba.createElement(Ca,{underline:t,backgroundColor:J(n.name),color:w.primary}," "+n.name+" ")};var jo=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=Nt(Oe(t.title),r),s=sn(t),a=an(t);return Fe.createElement(Gt,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?w.accent:w.secondary,justifyContent:"space-between"},Fe.createElement(Gt,{borderBottom:!0},Fe.createElement(Gt,{paddingLeft:1,flexDirection:"column"},Fe.createElement(Sa,{color:w.primary},o))),Fe.createElement(Gt,{flexDirection:"row",paddingLeft:1},s.map(d=>Fe.createElement(zt,{key:d.id,id:d.id})),a.map(d=>Fe.createElement(jt,{key:d.id,id:d.id}))))};import Ra from"chalk";import{Box as mt,Text as $n}from"ink";import ye from"react";var Aa=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,zo=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let s=b(t.id),a=A=>{let C=s.find(P=>P.title===A);return C?b(C.id).map(P=>typeof P.props?.value=="string"?P.props.value:"").filter(P=>!!P):[]},d=a("Tags").map(A=>x.getTag(A)).filter(A=>!!A),u=a("Assignees").map(A=>x.getContributor(A)).filter(A=>!!A),m=1,f=d.length*(1+m),N=u.length*(2+m),E=d.map(A=>ye.createElement(mt,{key:A.id,paddingRight:m},ye.createElement($n,{color:J(A.name)},"\u25A0"))),I=u.map(A=>ye.createElement(mt,{key:A.id,paddingRight:m},ye.createElement($n,{color:Qe(A.name)},"@"+A.name.at(0)))),R=n?w.accent:o===g.MOVE?w.secondary:w.primary;return ye.createElement(mt,{borderBottom:!0,justifyContent:"space-between"},ye.createElement(mt,null,ye.createElement(se,{isSelected:n,placeholder:Ra.dim.gray(r+1+" ")}),ye.createElement($n,{wrap:"truncate",color:R},Aa(t.title,e-f-N-14))),ye.createElement(mt,null,E,I))};var wa=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:a,mode:d})=>{let{renderedChildrenIndex:u}=ue(),m=u[e.id]??[],f=`${e.title} (${m.length})`,N=3,E=o?1:4,I=r-N-(o?2:1),R=me.createElement(Wn,{borderStyle:"round",borderColor:w.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},me.createElement(se,{isSelected:t}),me.createElement(Ta,{bold:!0,color:t?w.accent:w.primary},f," ",e.readonly?"\u{1F512}":"")),A=(C,P)=>{let z=s&&a===P;return o?me.createElement(zo,{key:C.id,index:P,width:n,ticket:C,isSelected:z,mode:d}):me.createElement(jo,{key:C.id,width:n,ticket:C,isSelected:z})};return me.createElement(Wn,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?w.accent:w.secondary,paddingRight:1,paddingLeft:1,height:r},R,me.createElement(Wn,{padding:o?1:0},m.length>0&&me.createElement(Vt,{selectedIndex:a,height:I,itemHeight:E},m.map(A)),me.createElement(se,{isSelected:s&&a===-1})))},Go=me.memo(wa);import{Box as Vn,Text as $a}from"ink";import Te,{useEffect as jn,useMemo as Jo}from"react";import ce from"chalk";import qo from"string-width";import{decodeTime as Ma}from"ulid";var Pa=(e,t)=>e+" ".repeat(Math.max(0,t-qo(e))),La=(e,t)=>" ".repeat(Math.max(0,t-qo(e)))+e,Da=e=>(()=>{let n={"add.issue":"Created with title","assign.issue":"Assigned to","unassign.issue":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","tag.issue":"Tagged with","untag.issue":"Removed tag","lock.node":"Locked node","move.node":"Moved issue"};return(o=>n[o]??(o.endsWith("e")?`${o}d`:`${o}ed`))(e)})(),Fa=e=>{switch(e.action){case"move.node":{let t=x.getNode(e.payload.parent),n=t?ce.dim.bgBlack(` ${t.title} `):"unknown",r=e.payload.pos;if(!r)return`to ${n}`;switch(r.at){case"start":return`to ${n} ${ce.dim("(to top of list)")}`;case"end":return`to ${n} ${ce.dim("(to bottom of list)")}`;case"before":return`to ${n} ${ce.dim("(up in list)")}`;case"after":return`to ${n} ${ce.dim("(down in list)")}`}}case"tag.issue":{let t=v().tags[e.payload.tagId];return t?ce.bgHex(J(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=v().tags[e.payload.tagId];return t?ce.bgHex(J(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=v().contributors[e.payload.contributor];return t?ce.hex(J(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=v().contributors[e.payload.contributor];return t?ce.hex(J(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;default:return""}},ka=e=>{let t=vr(Ma(e));return ce.gray(La(t,8))},Oa=12,Ua=e=>Pa(`${e}`,Oa),Xo=e=>{let t=ka(e.id),n=Ua(e.userName),r=Da(e.action),o=Fa(e),s=ce.dim("\u203A"),a=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${s} ${a}`};import{Box as qt,Text as Ba}from"ink";import xe from"react";var Yo=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=ue(),{title:o}=t,s=b(t.id).map(a=>{let d=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return x.getContributor(d)?.id;if(o==="Tags")return x.getTag(d)?.id}).filter(a=>!!a);return xe.createElement(qt,{alignItems:"center",paddingTop:1},xe.createElement(qt,{minWidth:12},xe.createElement(se,{isSelected:n}),xe.createElement(Ba,{color:n?w.accent:w.secondary2},o,":")),xe.createElement(qt,{flexDirection:"row",marginLeft:1,paddingRight:1},s.map((a,d)=>{let u=r.id===t.id&&d===e;return xe.createElement(qt,{key:`${o}-${a}`,paddingRight:2,minHeight:1},xe.createElement(se,{isSelected:u}),o==="Assignees"?xe.createElement(jt,{isSelected:u,id:a}):o==="Tags"?xe.createElement(zt,{isSelected:u,id:a}):null)})))};import{Box as Xt,Text as Hn}from"ink";import Ne,{useEffect as _a}from"react";var Kn=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:a,currentNode:d}=ue(),u=E=>String(E).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];_a(()=>{let E=[];return m.forEach((I,R)=>{let A=Y.text({id:`${R}`,name:`Line ${R+1}`,parentNodeId:e,props:{value:I},readonly:!0}),C=x.createNodeAtPosition(A);Zn(C)&&E.push(C.value.id)}),()=>E.forEach(x.deleteNode)},[e,n]);let f="\u2029",N=m.map((E,I)=>{let R=d.id===e&&a===I;return Ne.createElement(Xt,{key:`${e}-${I}`},Ne.createElement(Hn,{color:R?w.primary:w.secondary2,dimColor:!R},`${I+1} `.padStart(5,"\xA0")),Ne.createElement(Hn,{backgroundColor:R?"gray":""},u(E.length?Nt(E,s-10):f)))});return Ne.createElement(Xt,{flexDirection:"column",paddingTop:1},Ne.createElement(Xt,null,Ne.createElement(se,{isSelected:o}),Ne.createElement(Hn,{color:o?w.accent:w.secondary2},t)),Ne.createElement(Xt,{flexDirection:"row",borderStyle:"round",borderColor:w.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Ne.createElement(Vt,{scrollByOne:!0,children:N,height:r-2,selectedIndex:a,itemHeight:1})))};var Wa=e=>`${e}::log`,Zo=e=>e==="Assignees"||e==="Tags",Qo=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=ue(),o=process.stdout.columns||120,s=Jo(()=>Wa(e.id),[e.id]),a=Jo(()=>[...e.log].reverse().map(Xo).join(`
50
+ `),[e.log]);jn(()=>{if(x.getNode(s))return;let P={...Y.field(s,"Log",e.id,{value:a}),readonly:!0,childRenderAxis:"vertical"};return x.createNodeAtPosition(P),()=>{x.deleteNode(s)}},[s,e.id,a]),jn(()=>{let C=x.getNode(s);C&&C.props.value!==a&&x.updateNode({...C,props:{...C.props,value:a},childRenderAxis:"vertical",readonly:!0})},[s,a]);let d=r.id===e.id,u=r.id===s||r.parentNodeId===s;jn(()=>{u&&(n>=0||k.navigate({selectedIndex:0}))},[u,n]);let m=b(e.id);if(u){let C=x.getNode(s),z=t-3;return Te.createElement(Vn,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},C?Te.createElement(Kn,{id:C.id,label:"Event log",text:C.props.value??"",selected:!1,maxWidth:o,height:z}):null)}let f=m.reduce((C,P)=>Zo(P.title)||P.id===s?C+1:C,0),N=2,E=f*1,R=t-3-E-N,A=(C,P)=>Zo(C.title)?Te.createElement(Yo,{key:C.id,parent:C,selected:P,selectedIndex:n}):C.id===s?Te.createElement(Vn,{key:C.id,paddingTop:1},Te.createElement(se,{isSelected:P}),Te.createElement($a,{backgroundColor:w.secondary,color:P?w.accent:w.primary}," History \u203A\u203A ")):C.title==="Description"?Te.createElement(Kn,{label:"Description (press e to edit)",key:C.id,id:C.id,text:C.props.value??"",selected:P,maxWidth:o,height:R}):null;return Te.createElement(Vn,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((C,P)=>A(C,d&&n===P)))};var Ka=({swimlanes:e,currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:a,width:d})=>{let u=t.context,m=u===M.TICKET||u===M.FIELD_LIST||u===M.FIELD,f=u===M.BOARD||u===M.SWIMLANE,N=u===M.TICKET?t:r.find(C=>C.context===M.TICKET),E=Math.floor(d/3),I=Math.floor(d/Math.max(e.length,1)),R=Math.min(I,E),A=s==="dense";return Yt.createElement(Ha,{flexDirection:"row",height:a},f&&e.map((C,P)=>{let z=t.id===C.id,Jn=z?n:-1,Ye=t.context===M.BOARD&&n===P;return Yt.createElement(Go,{key:C.id,height:a,width:R,swimlane:C,isSelected:Ye,isDense:A,isFocused:z,listSelectedIndex:Jn,mode:o})}),m&&N&&Yt.createElement(Qo,{height:a,ticket:N}))},ei=Yt.memo(Ka);import{render as za}from"ink";import{Writable as Ga}from"node:stream";var pt=e=>String(e).padStart(2,"0"),qa=e=>{let t=e.getUTCFullYear(),n=pt(e.getUTCMonth()+1),r=pt(e.getUTCDate()),o=pt(e.getUTCHours()),s=pt(e.getUTCMinutes()),a=pt(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${a}`},Xa=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Ya=async(e,{width:t,height:n})=>{let r="",o=new Ga({write(a,d,u){let m=Ja(a.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=za(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(a=>setTimeout(a,0)),s.unmount(),r},Ja=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),ni=async()=>{let{currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:r,mode:o,renderedChildrenIndex:s}=v(),a=n.find(P=>P.context==="BOARD");if(!a)return i("No board found to export");let d=120,u=40,m=await Ya(ja.createElement(ei,{height:u,width:d,swimlanes:(s[a.id]??[]).filter(P=>P!==void 0&&Qn(P)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:r,mode:o}),{width:d,height:u});if(!m)return i("Failed to render board export");let f=re(process.cwd());if(l(f))return i("Unable to export, epiq root not found");let N=new Date,E=qa(N),I=`board_${Xa(a.title)}_${E}.md`,R=_r(f.value);ti.mkdirSync(R,{recursive:!0});let A=Va.join(R,I),C=`# Board - ${a.title}
51
+ Date: ${N.toISOString()}
52
+
53
+ \`\`\`text
54
+ ${m}
55
+ \`\`\`
56
+ `;return ti.writeFileSync(A,C,"utf8"),c("Exported board layout",A)};var ri=e=>Object.values(v().tags).find(t=>t.name===e),oi=e=>Object.values(v().contributors).find(t=>t.name===e),ii=[{systemOnly:!0,intent:S.Move,mode:g.COMMAND_LINE,action:()=>{let e=V();if(l(e))return i("Unable to resolve user ID");let{modifier:t}=Q().commandMeta,n=()=>{let d=Ae();if(!d)return i("No pending move state");let u=d.payload.id;if(!v().nodes[u])return i("Moved node not found");let f=d.payload.parent,N=v().nodes[f];if(!N)return i("Move parent not found");let E=b(f).findIndex(I=>I.id===u);return E===-1?i("Moved node not found among rendered children"):(k.navigate({currentNode:N,selectedIndex:E}),c("Synchronized navigation to moved node",null))},r=d=>{if(l(d))return i(d.message);let u=n();return l(u)?i(u.message):c("Updated move preview",null)},{currentNode:o,selectedIndex:s}=v(),a=b(o.id)[s];if(!a)return h({mode:g.DEFAULT}),i("No move target");if(t==="start"){if(a.readonly)return i("Target node is read-only");if(s===-1)return i("No item selected");if(!a.parentNodeId)return i("Target has no parent");let d=b(a.parentNodeId),u=d.findIndex(({id:I})=>I===a.id);if(u===-1)return i("Target not found among siblings");let m=d[u-1],f=d[u+1],N=f!=null?{at:"before",sibling:f.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"};qe({id:B(),action:"move.node",payload:{id:a.id,parent:a.parentNodeId,pos:N},...e.value}),h({mode:g.MOVE});let E=n();return l(E)?i(E.message):c("Move initialized",null)}if(t==="next")return h({mode:g.MOVE}),r(On(1));if(t==="previous")return h({mode:g.MOVE}),r(On(-1));if(t==="to-next")return h({mode:g.MOVE}),r(kn(1));if(t==="to-previous")return h({mode:g.MOVE}),r(kn(-1));if(t==="confirm"){h({mode:g.DEFAULT});let d=Ae();if(!d)return i("No pending move to confirm");let u=j(d);if(l(u))return u;let m=n();return l(m)?i(m.message):(qe(null),c("Moved item",null))}return t==="cancel"?(qe(null),h({mode:g.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}},{intent:S.Delete,mode:g.COMMAND_LINE,action:()=>{let e=V();if(l(e))return i("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=b(t.id)[n];return r?j({id:B(),action:"delete.node",payload:{id:r.id},...e.value}):i("Unable to resolve child to delete")},onSuccess:()=>h({mode:g.DEFAULT})},{intent:S.Edit,mode:g.COMMAND_LINE,action:()=>{let e=V();if(l(e))return i("Unable to resolve user ID");let t=Pe(v().breadCrumb,"TICKET");if(l(t))return i("Edit target must be an issue");let n=t.value;if(n.readonly)return i("Cannot edit readonly field");let{currentNode:r,selectedIndex:o}=v();if(!b(n.id)[o])return i("No selected field");let a=b(r.id)[o];if(!a)return i("No selected field");if(a.readonly)return i("Cannot edit readonly field");let d=a.props.value;if(typeof d!="string")return i("Selected field is not editable text");let u=Br(d);if(l(u))return i("Failed to edit field");let m=u.value;return m===d?c("No changes made",null):a.title==="Description"?j({id:B(),action:"edit.description",payload:{id:a.id,md:m},...e.value}):a.title==="Title"?j({id:B(),action:"edit.title",payload:{id:a.id,name:m},...e.value}):i(`Editing not supported for "${a.title}"`)},onSuccess:()=>h({mode:g.DEFAULT})},{intent:S.Filter,mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=Q().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(d=>W(p.FILTER).map(u=>u.split(n)[0]).includes(d))(r))return i("Invalid filter modifier");let a={target:r,operator:"=",value:t.trim()};return Z(d=>({...d,filters:e==="clear"?[]:[...d.filters,a],mode:g.DEFAULT})),c("Viewing help",null)}},{intent:S.ViewHelp,mode:g.COMMAND_LINE,action:()=>(h({mode:g.HELP}),c("Viewing help",null))},{intent:S.CloseIssue,mode:g.COMMAND_LINE,action:()=>{let e=V();if(l(e))return i("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=b(t.id)[n];if(!r)return i("Unable to close issue, no target found");if(!r.parentNodeId)return i("No target parent found");if(!X(r))return i("Cannot close in this context");let o=j({id:B(),action:"close.issue",payload:{id:r.id,parent:r.parentNodeId},...e.value});return l(o)?o:c("Viewing help",null)}},{intent:S.ReopenIssue,mode:g.COMMAND_LINE,action:()=>{let e=V();if(l(e))return i("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=b(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(l(o))return i("Cannot reopen in this context");let s=o.value,a=j({id:B(),action:"reopen.issue",payload:{id:s.id},...e.value});return l(a)?a:c("Issue reopened",null)},onSuccess:()=>h({mode:g.DEFAULT})},{intent:S.SetUserName,mode:g.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:n}=ge(),r=wt()?.trim();if(!r)return i("No username provided");let o=r??n,s=e??B();if(!o||!s)return i("Unable to resolve user name or id");let a=Ht({userName:o,userId:s,preferredEditor:t??""});return l(a)?a:(Ct({userName:o,userId:s}),h({mode:g.DEFAULT}),c(`Username set to "${r}"`,null))}},{intent:S.Init,mode:g.COMMAND_LINE,action:()=>{let e=Gn();if(l(e))return e;let{rootNodeId:t,nodes:n}=v();return k.navigate({currentNode:n[t],selectedIndex:0}),h({mode:g.DEFAULT}),c("Project initialized",null)}},{intent:S.SetEditor,mode:g.COMMAND_LINE,action:()=>{let e=wt()?.trim();if(!e)return i("No editor provided");let t=Ht({preferredEditor:e});return l(t)?t:(Ct({preferredEditor:e}),h({mode:g.DEFAULT}),c(`Editor configuration set to "${e}"`,null))}},{intent:S.SetAutoSync,mode:g.COMMAND_LINE,action:()=>{let e=Q().commandMeta.modifier;if(e!=="true"&&e!=="false")return i("Invalid response");let t=e.toLowerCase()==="true",n=Ht({autoSync:t});return l(n)?n:(Ct({autoSync:t}),h({mode:g.DEFAULT}),c(`Auto synchronization set to "${t}"`,null))}},{intent:S.NewItem,mode:g.COMMAND_LINE,action:(e,t)=>{let n=V();if(l(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}=v(),a=d=>{let u=j(d);if(l(u))return u;let m=x.getNode(u.value.result.id);if(!m)return i("Created node not found");if(!m.parentNodeId)return u;let f=x.getNode(m.parentNodeId);return f?(k.navigate({currentNode:f,selectedIndex:x.getSiblings(m.parentNodeId).findIndex(({id:N})=>N===m.id)}),u):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:d}=v(),u=x.getNode(d);return u?a({id:B(),action:"add.board",payload:{id:B(),name:t.inputString,parent:u.id},...n.value}):i("Workspace not found")}if(t.modifier==="swimlane"){let d=Pe(r,"BOARD");return l(d)?i("Unable to add swimlane in this context"):a({id:B(),action:"add.swimlane",payload:{id:B(),name:t.inputString,parent:d.value.id},...n.value})}if(t.modifier==="issue"){let d=b(o.id)[s],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&d?.context==="SWIMLANE"?d:(()=>{let I=Pe(r,"SWIMLANE");return l(I)?null:I.value})();if(!u)return i("Unable to add issue in this context");let m=yt({name:t.inputString,parent:u.id,user:n.value}),f=je(m);if(f.some(I=>l(I)))return i("Issue create failed: "+f.filter(l).map(I=>I.message).filter(Boolean).join(", "));let N=f[0];if(!N||l(N))return i("Issue creation failed");let E=m[0]?.payload.id;return E?(k.navigate({currentNode:u,selectedIndex:x.getSiblings(u.id).findIndex(({id:I})=>I===E)}),c("Issue created",null)):i("Unable to determine ticket id")}return c("Success",null)},onSuccess:()=>h({mode:g.DEFAULT})},{intent:S.SetView,mode:g.COMMAND_LINE,action:()=>{let{commandMeta:e}=Q();return e.validity===fe.Invalid?i("Invalid command "+pe):(Z(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),c("View set",null))},onSuccess:()=>h({mode:g.DEFAULT})},{intent:S.Rename,mode:g.COMMAND_LINE,action:()=>{let e=V();if(l(e))return i("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=b(t.id)[n];if(!r)return i("Missing node");if(r.readonly)return i("Cannot rename readonly node");let o=wt();return o?j({id:B(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):i("Provide a new name")},onSuccess:()=>h({mode:g.DEFAULT})},{intent:S.UntagTicket,mode:g.COMMAND_LINE,action:()=>{let e=V();if(l(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let o=ri(r);if(!o)return i(`Tag "${r}" does not exist`);let{selectedNode:s}=v();if(!s)return i("Invalid untag target");let a=Be(s.id,"TICKET");if(l(a))return i("Unable to untag issue in this context");let d=a.value,u=x.getFieldByTitle(d.id,"Tags");if(!u)return i("Unable to locate tags field");let m=b(u.id).find(f=>f.props?.value===o.id);return m?j({id:B(),action:"untag.issue",payload:{id:m.id,target:d.id,tagId:o.id},...e.value}):i("Issue is not tagged with that tag")},onSuccess:()=>h({mode:g.DEFAULT})},{intent:S.TagTicket,mode:g.COMMAND_LINE,action:()=>{let e=V();if(l(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let{selectedIndex:o,currentNode:s}=v(),a=b(s.id)[o];if(!a)return i("Invalid tag target");let d=Be(a.id,"TICKET");if(l(d))return i("Unable to tag issue in this context");let u=d.value,m=ri(r),f;if(m)f=m.id;else{let I=B(),R=j({id:B(),action:"create.tag",payload:{id:I,name:r},userId:e.value.userId,userName:e.value.userName});if(l(R))return R;f=R.value.result.id}let N=x.getFieldByTitle(u.id,"Tags");return N?b(N.id).some(I=>I.props?.value===f)?i("Already tagged with that tag"):j({id:B(),action:"tag.issue",payload:{id:B(),target:u.id,tagId:f},...e.value}):i("Unable to locate tags field")},onSuccess:()=>h({mode:g.DEFAULT})},{intent:S.AssignUserToTicket,mode:g.COMMAND_LINE,action:()=>{let e=V();if(l(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee");let{selectedIndex:o,currentNode:s}=v(),a=b(s.id)[o];if(!a)return i("Invalid assign target");let d=Be(a.id,"TICKET");if(l(d))return i("Unable to assign issue in this context");let u=d.value,m=oi(r),f;if(m)f=m.id;else{let I=B(),R=j({id:B(),action:"create.contributor",payload:{id:I,name:r},userId:e.value.userId,userName:e.value.userName});if(l(R))return R;f=R.value.result.id}let N=x.getFieldByTitle(u.id,"Assignees");return N?b(N.id).some(I=>I.props?.value===f)?i("Assignee already assigned"):j({id:B(),action:"assign.issue",payload:{id:B(),target:u.id,contributor:f},...e.value}):i("Unable to locate assignees field")},onSuccess:()=>h({mode:g.DEFAULT})},{intent:S.UnassignUserFromTicket,mode:g.COMMAND_LINE,action:()=>{let e=V();if(l(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee to remove");let o=oi(r);if(!o)return i(`Assignee "${r}" does not exist`);let{selectedNode:s}=v();if(!s)return i("Invalid unassign target");let a=Be(s.id,"TICKET");if(l(a))return i("Unable to unassign in this context");let d=a.value,u=x.getFieldByTitle(d.id,"Assignees");if(!u)return i("Unable to locate assignees field");let m=b(u.id).find(f=>f.props?.value===o.id);return m?j({id:B(),action:"unassign.issue",payload:{id:m.id,target:d.id,contributor:o.id},...e.value}):i(`Issue is not assigned to "${r}"`)},onSuccess:()=>h({mode:g.DEFAULT})},{intent:S.Sync,mode:g.COMMAND_LINE,action:async()=>{let e=_o();$(()=>""),h({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:n}=ge();if(!t)return i("Unable to resolve userId");if(!n)return i("Unable to resolve userName");let r=Ze()?Gn():c("No pending default events",null);if(l(r))return i(`Unable to persist default events. ${r.message}`);let o=V();if(l(o)||!o.value)return i("Unable to resolve event log path");let s=it(o.value);logger.debug("[sync-command] pending defaults",Ze());let a=await Wt({ownEventFileName:s});if(l(a))return h({syncStatus:{msg:a.message,status:"outOfSync"}}),i(`Unable to sync state. ${a.message}`);h({syncStatus:{msg:"Synced",status:"synced"},mode:g.DEFAULT});let d=re(process.cwd());if(l(d))throw new Error(d.message);let u=st(d.value);if(l(u))return i("Unable to load events");Le(u.value);let m=$o(e);return l(m)?m:c("Synced",!0)}},{intent:S.Peek,mode:g.COMMAND_LINE,action:async()=>{let e=Pe(v().breadCrumb,"BOARD");if(l(e))return e;let t=re(process.cwd());if(l(t))throw new Error(t.message);let n=st(t.value);if(l(n))return i(n.message);let r=n.value,{modifier:o}=Q().commandMeta,s;if(o==="now"){let E=zn();if(l(E))return E;let I=Le(r);return I.some(l)?i(I.map(R=>R.message).join(", ")):(h({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}if(o==="prev"){let E=v().eventLog.at(-2),I=ln(E);if(I===null)return i("No previous event to peek");s=I}else if(o==="next"){let E=v().unappliedEvents.at(0),I=ln(E);if(I===null)return i("No next event to peek");s=I}else{let E=Rt(o);if(!E)return i("Invalid peek date");s=E.getTime()}let a=e.value.id,{appliedEvents:d,unappliedEvents:u}=zr(r,s),m=zn();if(l(m))return m;let f=Le(d);if(f.some(l))return i(f.map(E=>E.message).join(", "));let N=v().nodes[a];return N?(k.navigate({currentNode:N,selectedIndex:0}),h({mode:g.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),c("Peeking ",!0)):i("Board did not exist at peek date")}},{intent:S.Export,mode:g.COMMAND_LINE,action:async()=>{let e=await ni();return l(e)?e:(h({mode:g.DEFAULT}),c("Export successful",!0))}},{intent:S.Exit,mode:g.COMMAND_LINE,action:async()=>(k.exit(),c("Exit successful",!0))}];var Za=new Set(["peek","filter","view-help"]),ae=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=Q();if(!t)return i("No command to confirm");if(!e&&n===fe.Invalid)return i("Invalid command");let s=Dr(t);if(wr(),v().readOnly&&!Za.has(s))return nt({status:pe.Fail,message:"Command not available in readonly state",value:null});let a=ii.filter(u=>e||u.systemOnly!==!0).find(u=>u.intent===s);if(!a)return nt({status:pe.Fail,message:"Command not found",value:null});let d=await a.action(a,{command:t,inputString:o,modifier:r});return l(d)?nt(d):(Mr({addToHistory:!e}),a.onSuccess?.(),nt(d))};var Jt=[{intent:T.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(h({mode:g.COMMAND_LINE}),$(()=>"move cancel"),ae({isForceExecutedBySystem:!0}))},{intent:T.InitMove,mode:g.DEFAULT,description:"[m] move init/confirm",action:()=>(h({mode:g.COMMAND_LINE}),$(()=>"move start"),ae({isForceExecutedBySystem:!0}))},{intent:T.ConfirmMove,mode:g.MOVE,action:()=>(h({mode:g.COMMAND_LINE}),$(()=>"move confirm"),ae({isForceExecutedBySystem:!0}))}],Zt=[{intent:T.MovePreviousItem,mode:g.MOVE,action:()=>Ae()?(h({mode:g.COMMAND_LINE}),$(()=>"move previous"),ae({isForceExecutedBySystem:!0})):i("No pending move")},{intent:T.MoveNextItem,mode:g.MOVE,action:()=>Ae()?(h({mode:g.COMMAND_LINE}),$(()=>"move next"),ae({isForceExecutedBySystem:!0})):i("No pending move")}],si=[{intent:T.MoveToNextContainer,mode:g.MOVE,action:()=>Ae()?(h({mode:g.COMMAND_LINE}),$(()=>"move to-next"),ae({isForceExecutedBySystem:!0})):i("No pending move")},{intent:T.MoveToPreviousContainer,mode:g.MOVE,action:()=>Ae()?(h({mode:g.COMMAND_LINE}),$(()=>"move to-previous"),ae({isForceExecutedBySystem:!0})):i("No pending move")}];var ai={[M.WORKSPACE]:[...Jt,...Zt],[M.BOARD]:[...Jt,...Zt],[M.SWIMLANE]:[...Jt,...Zt,...si],[M.TICKET]:[],[M.FIELD]:[],[M.FIELD_LIST]:[],[M.TEXT]:[]};var di=[{intent:T.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(h({mode:g.COMMAND_LINE}),$(()=>`${p.NEW} `),c("Adding new item",null))},{intent:T.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(h({mode:g.COMMAND_LINE}),$(()=>`${p.DELETE} `),c("Deleting item",null))},{intent:T.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(h({mode:g.COMMAND_LINE}),$(()=>""),c("Entering command line mode",null))},{intent:T.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(k.enterChildNode(),c("Entering context",null))},{intent:T.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(k.enterParentNode(),c("Exiting context",null))},{intent:T.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(k.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:T.NavNextItem,mode:g.DEFAULT,action:()=>(k.navigateToNextItem(),c("Navigating to next item",null))},{intent:T.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(k.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:T.NavToNextContainer,mode:g.DEFAULT,action:()=>(k.navigateToNextContainer(),c("Navigating to next container",null))},{intent:T.Edit,mode:g.DEFAULT,action:()=>(h({mode:g.COMMAND_LINE}),$(()=>"edit"),ae(),c("Fired command",!0))},{intent:T.SetViewDense,mode:g.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(h({viewMode:"dense"}),c("View set",null))},{intent:T.SetViewWide,mode:g.DEFAULT,action:()=>(h({viewMode:"wide"}),c("View set",null))}];var Qa=500,ed=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),li=e=>{let t=ed(e);t&&$(n=>(n+t).slice(0,Qa))};var ci=[{intent:T.ViewHelp,mode:g.DEFAULT,action:()=>(h({mode:g.HELP}),c("Viewing help",null))},{intent:T.Exit,mode:g.HELP,action:()=>(h({mode:g.DEFAULT}),c("Exiting help",null))},{intent:T.Confirm,mode:g.COMMAND_LINE,action:()=>(ae(),c("Executing command",null))},{intent:T.MoveCursorLeft,mode:g.COMMAND_LINE,action:()=>(fn(-1),c("Moving cursor left",null))},{intent:T.MoveCursorRight,mode:g.COMMAND_LINE,action:()=>(fn(1),c("Moving cursor right",null))},{intent:T.MoveCursorLeftOfWord,mode:g.COMMAND_LINE,action:()=>(vn("left"),c("Moving cursor left of word",null))},{intent:T.MoveCursorRightOfWord,mode:g.COMMAND_LINE,action:()=>(vn("right"),c("Moving cursor right of word",null))},{intent:T.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(h({mode:g.DEFAULT}),c("Exiting command line",null))},{intent:T.AutoCompleteCommand,mode:g.COMMAND_LINE,action:()=>($((e,{remainder:t})=>t?e+t:e),c("Auto-completing command",null))},{intent:T.CaptureInput,mode:g.COMMAND_LINE,action:(e,{sequence:t})=>(li(t??""),c("Capturing input",null))},{intent:T.EraseInput,mode:g.COMMAND_LINE,action:()=>(Ar(),c("Erasing input",null))},{intent:T.EraseInputWord,mode:g.COMMAND_LINE,action:()=>(Tr(),c("Erasing input word",null))},{intent:T.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(Pr(),c("Getting last command from history",null))},{intent:T.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(Lr(),c("Getting next command from history",null))}];import td from"chalk";var Qt=": for command line",ui="q to exit",mi=`${td.hex(w.accent)("m")} to confirm`,qn={[M.WORKSPACE]:[Qt],[M.BOARD]:[Qt],[M.BOARD+g.COMMAND_LINE]:[Qt],[M.SWIMLANE]:[Qt],[M.TICKET+g.HELP]:[ui],[M.SWIMLANE+g.HELP]:[ui],[M.TICKET]:[],[M.FIELD]:[],[M.SWIMLANE+g.MOVE]:[mi],[M.TICKET+g.MOVE]:[mi]};var en=e=>e.trim().toLocaleLowerCase(),nd=(e,t)=>{let n=x.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},rd=e=>{let{tags:t}=v(),n=x.getFieldByTitle(e,"Tags");return n?G(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},od=e=>{let{contributors:t}=v(),n=x.getFieldByTitle(e,"Assignees");return n?G(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},pi=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return en(e.title??"").includes(n);case"description":return en(nd(e.id,"Description")).includes(n);case"tag":return rd(e.id).map(en).some(d=>d.includes(n));case"assignee":return od(e.id).map(en).some(d=>d.includes(n));default:return!0}};function gi(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 a=o[o.length-1];return!a||a.id!==n?i("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var fi=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 tn,Xn,Yn=new Set,vi=()=>{for(let e of Yn)e()},sd=e=>(Yn.add(e),()=>Yn.delete(e));function yi(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 d=o[t];if(!d)return i("Unable to derive state, currentNode not found");let u=gi(t,o,r);if(l(u))return logger.error(u.message),u;let m=u.value,{context:f}=d,N=qn[f+n]??qn[f]??[],E=[...di,...ai[f]??[],...ci],I=fi(E),R=ad(o,s),A=R[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,currentNode:d,breadCrumb:m,availableHints:N,availableActions:E,actionIndex:I,selectedNode:A,renderedChildrenIndex:R})}var v=()=>(tn||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),tn);function hn(e){Xn=e;let t={readOnly:!1,filters:[],tags:{},contributors:{},viewMode:"dense",mode:g.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live"},n=yi(t);return l(n)?n:(tn=n.value,vi(),c("State initialized",null))}function Z(e){let t=v(),n=e(t),r=yi(n);return l(r)?i(r.message??"Unable to update state"):(tn=r.value,vi(),c("State updated",null))}var h=e=>Z(t=>({...t,...e}));var ue=()=>id(sd,v,v),ad=(e,t)=>{let n={};for(let r of Object.values(e))X(r)&&t.length>0&&!t.every(o=>pi(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 a=e[o.id],d=e[s.id];return!a||!d?0:a.rank.localeCompare(d.rank)});return n},b=e=>v()?.renderedChildrenIndex[e]??[],zn=()=>Xn?hn(Xn):i("Cannot reset state: no initial workspace found");var k={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=b(t.id)[n];!r||t.context==="FIELD"||k.navigate({currentNode:r,selectedIndex:b(r.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=b(n.id),o=r.findIndex(({id:a})=>a===e.id),s=r.length===0?-1:o>=0?o:0;k.navigate({currentNode:n,selectedIndex:s})},navigateToNextItem:()=>xi(1),navigateToPreviousItem:()=>xi(-1),navigateToNextContainer:()=>Ni(1),navigateToPreviousContainer:()=>Ni(-1),navigate:({currentNode:e=v().currentNode,selectedIndex:t})=>{h({currentNodeId:e.id,selectedIndex:t})}},xi=e=>{let t=v(),n=b(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;k.navigate({selectedIndex:o})},Ni=e=>{let{currentNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let s=b(o.id),a=s.findIndex(E=>E.id===t.id);if(a<0)return;let d=s.at(a+e)??s.at(0);if(!d)return;let u=b(d.id),m=Math.max(0,u.length-1),f=Math.min(Math.max(0,r),m),N=u.length?f:-1;k.navigate({currentNode:d,selectedIndex:N})};var Ie="system",he="ACTOR",gt=dd(),Ce=null;function ld(){let e=Object.values(v().nodes).find(r=>r.context==="WORKSPACE");if(!e)throw new Error("No workspace found in event log");let[t]=b(e.id),[n]=t?b(t.id):[];if(logger.debug("Boot navigation target:",{workspace:e?.id,firstBoard:t?.id,firstSwimlane:n?.id}),n){let r=v().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:v().nodes[v().rootNodeId],selectedIndex:0}}function cd(){let e=ld();k.navigate(e)}function ud(){let e=gt(),t=gt(),n=gt(),r=gt(),o=gt();return[{id:Ee(),userId:Ie,userName:he,action:"init.workspace",payload:{id:e,name:"Workspace"}},{id:Ee(),userId:Ie,userName:he,action:"add.board",payload:{id:t,name:"Default",parent:e}},{id:Ee(),userId:Ie,userName:he,action:"add.swimlane",payload:{id:n,name:"Todo",parent:t}},{id:Ee(),userId:Ie,userName:he,action:"add.swimlane",payload:{id:r,name:"In progress",parent:t}},{id:Ee(),userId:Ie,userName:he,action:"add.swimlane",payload:{id:o,name:"Done",parent:t}},{id:Ee(),userId:Ie,userName:he,action:"add.board",payload:{id:Ot,name:"Closed",parent:e}},{id:Ee(),userId:Ie,userName:he,action:"add.swimlane",payload:{id:le,name:"Closed",parent:Ot}},{id:Ee(),userId:Ie,userName:he,action:"lock.node",payload:{id:Ot}},{id:Ee(),userId:Ie,userName:he,action:"lock.node",payload:{id:le}}]}function Ze(){return Ce!==null}function Gn(){if(!Ce||Ce.length===0)return Ce=null,c("No pending default events to persist",null);let e=Ce.map(t=>Dt({event:t})).filter(l);return e.length>0?i([Xe.bold.red("Persisting default events failed"),"",...e.map((t,n)=>`${Xe.dim.gray(`${n+1}.`)} ${Xe.dim(t.message)}`),`
36
57
  `].join(`
37
- `)):(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=Cs(),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)}`),`
58
+ `)):(Ce=null,c("Persisted pending default events",null))}function Ei(e){let t;e.some(r=>r.action==="init.workspace")?(Ce=null,t=Le(e)):(Ce=ud(),t=Le([...Ce]));let n=t.filter(l);return n.length>0?i([Xe.bold.red("Materializing failed"),"",...n.map((r,o)=>`${Xe.dim.gray(`${o+1}.`)} ${Xe.dim(r.message)}`),`
38
59
  `].join(`
39
- `)):(bs(),c("State booted successfully",null))}var Ie=e=>{let t=ae(e??process.cwd()),n=Ke(t);if(a(n))return i(n.message);let r=io(n.data);return a(r)?i(r.message):c("Booted Epiq state",{root:t})},Ft=()=>{let e=Hr();return a(e)?i(e.message):e.data.userId?e.data.userName?c("Resolved actor",{userId:e.data.userId,userName:e.data.userName}):i("Unable to retrieve user name"):i("Unable to retrieve user id")},ao=(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):[]},hs=e=>ao(e,"Tags").map(t=>E.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),Rs=e=>ao(e,"Assignees").map(t=>E.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),co=(e={})=>{let t=Ie(e.repoRoot);if(a(t))return t;let n=Object.values(y().nodes).filter(r=>r.context==="BOARD").map(r=>({id:r.id,title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return c("Listed boards",n)},lo=(e={})=>{let t=Ie(e.repoRoot);if(a(t))return t;let n=Object.values(y().nodes).filter(r=>r.context==="SWIMLANE").filter(r=>!e.boardId||r.parentNodeId===e.boardId).map(r=>({id:r.id,title:r.title,boardId:r.parentNodeId,isClosed:r.id===Z,readonly:!!r.readonly}));return c("Listed swimlanes",n)},uo=e=>{let t=Ie(e.repoRoot);if(a(t))return t;let n=Object.values(y().nodes).filter(z).filter(r=>e.includeClosed||r.parentNodeId!==Z).map(r=>({id:r.id,title:tt(r.title),description:wn(r,"Description"),parentId:r.parentNodeId,isClosed:r.parentNodeId===Z,readonly:!!r.readonly,tags:hs(r),assignees:Rs(r)}));return c("Listed issues",n)},mo=e=>{let t=Ie(e.repoRoot);if(a(t))return t;let n=Ft();if(a(n))return n;let r=E.getNode(e.parentId);if(!r)return i(`Unable to locate parent swimlane: ${e.parentId}`);if(r.context!=="SWIMLANE")return i(`Parent must be a swimlane, got: ${r.context}`);let o=Ze({name:e.title,parent:e.parentId,user:n.data}),d=Ae(o).find(a);if(d)return i(d.message);let l=o.find(u=>u.action==="add.issue")?.payload.id;return l?c("Created issue",{id:l,title:e.title,parentId:e.parentId}):i("Unable to determine created issue id")},po=e=>{let t=Ie(e.repoRoot);if(a(t))return t;let n=Ft();if(a(n))return n;let r=E.getNode(e.issueId);if(!r)return i(`Unable to locate issue: ${e.issueId}`);if(!r.parentNodeId)return i(`Unable to locate issue parent for: ${e.issueId}`);if(!z(r))return i("Can only close issues");if(r.parentNodeId===Z)return i("Issue is already closed");let o={id:so(),userId:n.data.userId,userName:n.data.userName,action:"close.issue",payload:{id:e.issueId,parent:r.parentNodeId}},d=Ae([o]).find(a);return d?i(d.message):c("Closed issue",{id:e.issueId,closed:!0})},go=(e={})=>{let t=Ie(e.repoRoot);return a(t)?t:c("Retrieved Epiq state",{root:t.data.root,nodes:y().nodes,rootNodeId:y().rootNodeId,currentNode:y().currentNode,selectedIndex:y().selectedIndex,eventLog:y().eventLog})},fo=e=>{let t=Ie(e.repoRoot);if(a(t))return t;let n=Ft();if(a(n))return n;let r=E.getNode(e.issueId);if(!r)return i(`Unable to locate issue: ${e.issueId}`);if(!z(r))return i("Can only move issues");let o=E.getNode(e.parentId);if(!o)return i(`Unable to locate target swimlane: ${e.parentId}`);if(o.context!=="SWIMLANE")return i(`Target parent must be a swimlane, got: ${o.context}`);if(o.readonly)return i("Cannot move issue to readonly swimlane");let s={id:so(),userId:n.data.userId,userName:n.data.userName,action:"move.node",payload:{id:e.issueId,parent:e.parentId,...e.position==null?{}:{pos:e.position}}},l=Ae([s]).find(a);return l?i(l.message):c("Moved issue",{id:e.issueId,parentId:e.parentId,position:e.position??{at:"end"}})},vo=async(e={})=>{let t=ae(e.repoRoot??process.cwd()),n=Ft();if(a(n))return n;let r=await At({cwd:t,ownEventFileName:He({userId:n.data.userId,userName:n.data.userName})});return a(r)?r:c("Synced Epiq state",r.data)};var fe=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),ws=()=>{let e=new Ss({name:"epiq",version:"0.2.30"});return e.registerTool("epiq_state_get",{description:"Get the full current Epiq state, including nodes and event log",inputSchema:A.object({repoRoot:A.string().optional()})},async t=>fe(await go(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:A.object({repoRoot:A.string().optional(),includeClosed:A.boolean().optional()})},async t=>fe(await uo(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:A.object({repoRoot:A.string().optional()})},async t=>fe(await co(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:A.object({repoRoot:A.string().optional(),boardId:A.string().optional()})},async t=>fe(await lo(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue",inputSchema:A.object({title:A.string().min(1),parentId:A.string().min(1),repoRoot:A.string().optional()})},async t=>fe(await mo(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:A.object({issueId:A.string().min(1),repoRoot:A.string().optional()})},async t=>fe(await po(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:A.object({issueId:A.string().min(1),parentId:A.string().min(1),position:A.discriminatedUnion("at",[A.object({at:A.literal("start")}),A.object({at:A.literal("end")}),A.object({at:A.literal("before"),sibling:A.string().min(1)}),A.object({at:A.literal("after"),sibling:A.string().min(1)})]).optional(),repoRoot:A.string().optional()})},async t=>fe(await fo(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:A.object({repoRoot:A.string().optional()})},async t=>fe(await vo(t))),e},Ts=async()=>{let e=ws(),t=new As;await e.connect(t)};await Ts();export{ws as createMcpServer,fe as resultJson,Ts as startMcpServer};
60
+
61
+ See complete log:
62
+
63
+ `)+e.map(r=>JSON.stringify(r)).join(`
64
+ `)):(cd(),c("State booted successfully",null))}var ke=e=>{let t=re(e??process.cwd());if(l(t))return t;let n=st(t.value);if(l(n))return i(n.message);let r=Ei(n.value);return l(r)?i(r.message):c("Booted Epiq state",{root:t.value})},nn=()=>{let e=Uo();return l(e)?i(e.message):e.value.userId?e.value.userName?c("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):i("Unable to retrieve user name"):i("Unable to retrieve user id")},hi=(e,t)=>{let r=b(e.id).find(o=>o.title===t);return r?b(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},md=e=>hi(e,"Tags").map(t=>x.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),pd=e=>hi(e,"Assignees").map(t=>x.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),Ci=(e={})=>{let t=ke(e.repoRoot);if(l(t))return t;let n=Object.values(v().nodes).filter(r=>r.context==="BOARD").map(r=>({id:r.id,title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return c("Listed boards",n)},bi=(e={})=>{let t=ke(e.repoRoot);if(l(t))return t;let n=Object.values(v().nodes).filter(r=>r.context==="SWIMLANE").filter(r=>!e.boardId||r.parentNodeId===e.boardId).map(r=>({id:r.id,title:r.title,boardId:r.parentNodeId,isClosed:r.id===le,readonly:!!r.readonly}));return c("Listed swimlanes",n)},Si=e=>{let t=ke(e.repoRoot);if(l(t))return t;let n=Object.values(v().nodes).filter(X).filter(r=>e.includeClosed||r.parentNodeId!==le).map(r=>({id:r.id,title:Oe(r.title),description:ur(r,"Description"),parentId:r.parentNodeId,isClosed:r.parentNodeId===le,readonly:!!r.readonly,tags:md(r),assignees:pd(r)}));return c("Listed issues",n)},Ri=e=>{let t=ke(e.repoRoot);if(l(t))return t;let n=nn();if(l(n))return n;let r=x.getNode(e.parentId);if(!r)return i(`Unable to locate parent swimlane: ${e.parentId}`);if(r.context!=="SWIMLANE")return i(`Parent must be a swimlane, got: ${r.context}`);let o=yt({name:e.title,parent:e.parentId,user:n.value}),a=je(o).find(l);if(a)return i(a.message);let d=o.find(u=>u.action==="add.issue")?.payload.id;return d?c("Created issue",{id:d,title:e.title,parentId:e.parentId}):i("Unable to determine created issue id")},Ai=e=>{let t=ke(e.repoRoot);if(l(t))return t;let n=nn();if(l(n))return n;let r=x.getNode(e.issueId);if(!r)return i(`Unable to locate issue: ${e.issueId}`);if(!r.parentNodeId)return i(`Unable to locate issue parent for: ${e.issueId}`);if(!X(r))return i("Can only close issues");if(r.parentNodeId===le)return i("Issue is already closed");let o={id:Ii(),userId:n.value.userId,userName:n.value.userName,action:"close.issue",payload:{id:e.issueId,parent:r.parentNodeId}},a=je([o]).find(l);return a?i(a.message):c("Closed issue",{id:e.issueId,closed:!0})},Ti=(e={})=>{let t=ke(e.repoRoot);return l(t)?t:c("Retrieved Epiq state",{root:t.value.root,nodes:v().nodes,rootNodeId:v().rootNodeId,currentNode:v().currentNode,selectedIndex:v().selectedIndex,eventLog:v().eventLog})},wi=e=>{let t=ke(e.repoRoot);if(l(t))return t;let n=nn();if(l(n))return n;let r=x.getNode(e.issueId);if(!r)return i(`Unable to locate issue: ${e.issueId}`);if(!X(r))return i("Can only move issues");let o=x.getNode(e.parentId);if(!o)return i(`Unable to locate target swimlane: ${e.parentId}`);if(o.context!=="SWIMLANE")return i(`Target parent must be a swimlane, got: ${o.context}`);if(o.readonly)return i("Cannot move issue to readonly swimlane");let s={id:Ii(),userId:n.value.userId,userName:n.value.userName,action:"move.node",payload:{id:e.issueId,parent:e.parentId,...e.position==null?{}:{pos:e.position}}},d=je([s]).find(l);return d?i(d.message):c("Moved issue",{id:e.issueId,parentId:e.parentId,position:e.position??{at:"end"}})},Mi=async(e={})=>{let t=re(e.repoRoot??process.cwd());if(l(t))return i(`Sync failed
65
+ `+t);let n=nn();if(l(n))return n;let r=await Wt({cwd:t.value,ownEventFileName:it({userId:n.value.userId,userName:n.value.userName})});return l(r)?r:c("Synced Epiq state",r.value)};var we=e=>({isError:l(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),vd=()=>{let e=new gd({name:"epiq",version:"0.2.30"});return e.registerTool("epiq_state_get",{description:"Get the full current Epiq state, including nodes and event log",inputSchema:L.object({repoRoot:L.string().optional()})},async t=>we(await Ti(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:L.object({repoRoot:L.string().optional(),includeClosed:L.boolean().optional()})},async t=>we(await Si(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:L.object({repoRoot:L.string().optional()})},async t=>we(await Ci(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:L.object({repoRoot:L.string().optional(),boardId:L.string().optional()})},async t=>we(await bi(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue",inputSchema:L.object({title:L.string().min(1),parentId:L.string().min(1),repoRoot:L.string().optional()})},async t=>we(await Ri(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:L.object({issueId:L.string().min(1),repoRoot:L.string().optional()})},async t=>we(await Ai(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:L.object({issueId:L.string().min(1),parentId:L.string().min(1),position:L.discriminatedUnion("at",[L.object({at:L.literal("start")}),L.object({at:L.literal("end")}),L.object({at:L.literal("before"),sibling:L.string().min(1)}),L.object({at:L.literal("after"),sibling:L.string().min(1)})]).optional(),repoRoot:L.string().optional()})},async t=>we(await wi(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:L.object({repoRoot:L.string().optional()})},async t=>we(await Mi(t))),e},yd=async()=>{let e=vd(),t=new fd;await e.connect(t)};await yd();export{vd as createMcpServer,we as resultJson,yd as startMcpServer};