epiq 0.2.29 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,46 +1,46 @@
1
1
  #!/usr/bin/env node
2
- import{render as ac}from"ink";import dc from"meow";import Gi from"react";import Jd from"chalk";import{Box as me,Text as Oe}from"ink";import k from"react";import st from"chalk";import{monotonicFactory as qa,ulid as Ee}from"ulid";import{useSyncExternalStore as Va}from"react";var L={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function We(e){return e.context==="TICKET"}var Mn=e=>e.context==="SWIMLANE";var f={INIT:"init",HELP:"help",NEW:"new",TAG:"tag",FILTER:"filter",MOVE:"move",ASSIGN:"assign",DELETE:"delete",RENAME:"rename",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",SET_DESCRIPTION:"edit",SET_EDITOR:"set:editor",SET_VIEW:"set:view",SET_USERNAME:"set:username",SYNC:"sync",NONE:""},ve={None:"none",Invalid:"invalid",Valid:"valid"},he={None:"none",Success:"success",Fail:"fail"},s=e=>({result:he.Fail,message:e,data:null}),c=(e,t)=>({result:he.Success,message:e,data:t}),Rn=()=>({result:he.None,message:"No result",data:null}),d=e=>e.result==="fail",ze=e=>e.result==="success";var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function Tt(e,t){let r=Math.min(e.length,t.length),n=0;for(;n<r&&e[n]===t[n];)n++;return n}var Mt=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Ln=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var Pn=e=>{let t=new Map;for(let r of e)for(let n=1;n<=r.length;n++){let o=r.slice(0,n),i=t.get(o);i?i.push(r):t.set(o,[r])}return t},Dn=(e,t)=>t?e.get(t)??[]:[];var Fn=new WeakMap,Zi=e=>{let t=Fn.get(e);return t||(t=Pn(e),Fn.set(e,t)),t};var kn=({wordList:e,inputToMatch:t,overlapThreshold:r=1})=>{let n=t.toLowerCase();return Dn(Zi(e),n).filter(i=>Tt(n,i)>=r)};var Bn=({inputToMatch:e,lastWord:t},r)=>{if(t.endsWith(" "))return{hint:"",hints:[],overlap:0,remainder:""};let n=kn({wordList:r,inputToMatch:e,overlapThreshold:1});return es(t,n)},es=(e,t)=>{let r=t[0]??"",n=Tt(e.toLowerCase(),r.toLowerCase()),o=r?r+" ":"",i=o.slice(n);return{hint:o,hints:t,overlap:n,remainder:i}};var On=["vi","vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var qe=24n,ts=qe*4n,Rt=(1n<<ts)-1n,rs=/^[0-9a-f]+$/;function Un(e){if(!e||!rs.test(e))throw new Error(`Invalid hex rank: ${e}`);return BigInt("0x"+e)}function Lt(e,t=qe){if(e<0n)throw new Error("Negative rank not allowed");return e.toString(16).padStart(Number(t),"0")}function mt(e,t){if(!e&&!t)return Lt(Rt/2n,qe);let r=e?Un(e):0n,n=t?Un(t):Rt;if(n<=r)return Lt(Rt/2n,qe);let o=(r+n)/2n;return o===r||o===n?"":Lt(o,qe)}function ae(){return Lt(Rt/2n,qe)}var X={workspace:(e,t)=>({id:e,title:t,rank:ae(),isDeleted:!1,props:{},context:L.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,r,n=!1)=>({id:e,title:t,rank:ae(),isDeleted:!1,props:{},context:L.BOARD,childRenderAxis:"horizontal",parentNodeId:r,readonly:n,log:[]}),swimlane:(e,t,r)=>({id:e,title:t,rank:ae(),isDeleted:!1,props:{},context:L.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:r,readonly:!1,log:[]}),field:(e,t,r,n={},o="horizontal")=>({id:e,title:t,rank:ae(),isDeleted:!1,props:n,context:L.FIELD,childRenderAxis:o,parentNodeId:r,readonly:!1,log:[]}),ticket:(e,t,r)=>({id:e,title:t,rank:ae(),isDeleted:!1,props:{},context:L.TICKET,childRenderAxis:"vertical",parentNodeId:r,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:r,props:n={},readonly:o=!0})=>({id:e,title:t,rank:ae(),isDeleted:!1,props:n,context:L.TEXT,childRenderAxis:"vertical",parentNodeId:r,readonly:o,log:[]})};var W=e=>Object.values(C().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,r)=>t.rank.localeCompare(r.rank)),Wn=(e,t)=>e.findIndex(r=>r.id===t),Sr=(e,t={at:"end"})=>{if(e.length===0)return c("Resolved rank",ae());switch(t.at){case"start":{let r=e[0];return r?c("Resolved rank",mt(void 0,r.rank)):s("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?c("Resolved rank",mt(r.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let r=Wn(e,t.sibling);if(r<0)return s("Sibling not found");let n=r>0?e[r-1]:void 0,o=e[r];return o?c("Resolved rank",mt(n?.rank,o.rank)):s("Sibling not found")}case"after":{let r=Wn(e,t.sibling);if(r<0)return s("Sibling not found");let n=e[r],o=r<e.length-1?e[r+1]:void 0;return n?c("Resolved rank",mt(n.rank,o?.rank)):s("Sibling not found")}}};var Ge=(e,t)=>{let{nodes:r}=C(),n=r[e];if(!n)return s("Node not found");if(n.context===t)return c("Resolved ancestor node",n);let o=n.parentNodeId?r[n.parentNodeId]:void 0;for(;o;){if(o.context===t)return c("Resolved ancestor node",o);o=o.parentNodeId?r[o.parentNodeId]:void 0}return s(`No ancestor found for context: ${t}`)},wr=(e,t)=>{let{nodes:r}=C(),n=r[e];for(;n?.parentNodeId;){if(n.parentNodeId===t)return!0;n=r[n.parentNodeId]}return!1},Ar=(e,t)=>e?e.readonly?s({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:s("Node not found"),E={deleteNode(e){de(t=>{let r={...t.nodes};return delete r[e],{...t,nodes:r}})},editValue(e,t){let{nodes:r}=C(),n=r[e];if(!n)return s("Edit target node not found");let o=Ar(n,"edit");if(o)return o;let i={...n,props:{...n.props,value:t}};return E.updateNode(i),c("Issue description updated",{md:t})},renameNode(e,t){let r=this.getNode(e);if(!r)return s("Rename target node not found");let n=Ar(r,"rename");if(n)return n;let o={...r,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=C();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=C();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return W(e).find(r=>r.title===t)},moveNode({id:e,parentId:t,position:r={at:"end"}}){let{rootNodeId:n}=C(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(n===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let a=Ar(o,"move");if(a)return a;if(wr(t,e))return s("Cannot move node into its own descendant");let l=W(t).filter(p=>p.id!==e),m=Sr(l,r);if(d(m))return m;let u={...o,parentNodeId:t,rank:m.data};return this.updateNode(u),c("Moved node successfully",u)},tombstoneNode(e){let{nodes:t,currentNodeId:r,rootNodeId:n}=C(),o=this.getNode(e);if(!o)return s("Node not found");if(n===e)return s("Cannot delete root node");let i=new Set,a=m=>{let u=t[m];if(!(!u||i.has(m))){i.add(m);for(let p of W(u.id))a(p.id)}};a(e);let l={...structuredClone(t)};for(let m of i){if(!l[m])return s("Unable to locate node to delete");l[m]={...l[m],isDeleted:!0}}return r?(w({nodes:l}),c("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=de(r=>({...r,contributors:{...r.contributors,[e.id]:e}}));return d(t)?s("Unable to create contributor"):c("Created contributor",e)},assign(e,t,r){let n=E.getContributor(t),o=E.getNode(e);if(!o||!n)return s("Unable assign contributor to issue");let i=this.getFieldByTitle(o.id,"Assignees");if(!i)return s("Unable to locate assignees field");if(W(i.id).some(m=>m.props?.value===t))return s("Contributor already assigned");let l=this.createNodeAtPosition(X.field(r,n.name,i.id,{value:t}));return d(l)?l:c("Assigned contributor",l.data)},createTag(e){let t=de(r=>({...r,tags:{...r.tags,[e.id]:e}}));return d(t)?s("Could not create tag"):c("Tag created",e)},tag(e,t,r){let n=E.getTag(t),o=E.getNode(e);if(!n)return s("Unable to add tag, missing tag");if(!o)return s("Unable to add tag, missing target");let i=this.getFieldByTitle(o.id,"Tags");if(!i)return s("Unable to locate tags field");if(W(i.id).some(m=>m.props?.value===t))return s("Tag already assigned");let l=this.createNodeAtPosition(X.field(r,n.name,i.id,{value:t}));return d(l)?l:c("Tag added",l.data)},createNodeAtPosition(e,t={at:"end"}){if(!e.parentNodeId){let i={...e,rank:ae()};return this.createNode(i),c("Created node",i)}let r=W(e.parentNodeId),n=Sr(r,t);if(d(n))return n;let o={...e,rank:n.data};return this.createNode(o),c("Created node",o)},createNode(e){let t=de(r=>({...r,nodes:{...r.nodes,[e.id]:e}}));return d(t)?s("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let r={...t,readonly:!0},n=de(o=>({...o,nodes:{...o.nodes,[e]:r}}));return d(n)?s(n.message):c("Locked node",r)},updateNode(e){let t=de(r=>({...r,nodes:{...r.nodes,[e.id]:e}}));return d(t)?t:c("Updated node",e)},getContributor(e){return C().contributors[e]},getTag(e){return C().tags[e]},getNode(e){return C().nodes[e]},getSiblings:e=>Object.values(C().nodes).filter(t=>!t.isDeleted&&t.parentNodeId===e).sort((t,r)=>t.rank.localeCompare(r.rank))};var Pt={preferredEditor:null,userName:null,userId:null},ce=()=>Pt,ut=e=>(Pt={...Pt,...e},Pt);var Dt=()=>{let e=ce(),t=!!e.userName?.trim(),r=!!e.preferredEditor?.trim();return{isSetup:r&&t,hasPreferredEditor:r,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},Hn=()=>!He();var j={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"},h={accent:j.cyan,accent2:j.magenta,primary:j.white,secondary:j.grayDark,secondary2:j.grayLight,gray:j.gray,green:j.green,yellow:j.yellow,red:j.red};var x={red:j.red,yellow:j.yellow,green:j.green,blue:j.blue,magenta:j.magenta,cyan:j.cyan},Je={urgent:x.red,critical:x.red,important:x.red,blocker:x.red,asap:x.red,immediate:x.red,fail:x.red,failure:x.red,broken:x.red,bug:x.red,error:x.red,incident:x.red,outage:x.red,production:x.red,crash:x.red,security:x.red,warning:x.yellow,warn:x.yellow,risky:x.yellow,risk:x.yellow,attention:x.yellow,pending:x.yellow,review:x.yellow,"needs-review":x.yellow,qa:x.yellow,testing:x.yellow,test:x.yellow,validate:x.yellow,verification:x.yellow,staging:x.yellow,check:x.yellow,"follow-up":x.yellow,followup:x.yellow,waiting:x.yellow,blocked:x.yellow,hold:x.yellow,done:x.green,complete:x.green,completed:x.green,success:x.green,ok:x.green,stable:x.green,resolved:x.green,fixed:x.green,closed:x.green,merged:x.green,released:x.green,deployed:x.green,approved:x.green,verified:x.green,working:x.green,healthy:x.green,pass:x.green,passing:x.green,info:x.blue,information:x.blue,note:x.blue,docs:x.blue,documentation:x.blue,doc:x.blue,guide:x.blue,help:x.blue,explanation:x.blue,detail:x.blue,details:x.blue,context:x.blue,design:x.blue,discussion:x.blue,proposal:x.blue,idea:x.blue,feature:x.magenta,enhancement:x.magenta,improvement:x.magenta,refactor:x.magenta,refactoring:x.magenta,cleanup:x.magenta,optimize:x.magenta,optimization:x.magenta,perf:x.magenta,performance:x.magenta,upgrade:x.magenta,migration:x.magenta,modernize:x.magenta,debt:x.magenta,todo:x.cyan,next:x.cyan,planned:x.cyan,plan:x.cyan,future:x.cyan,backlog:x.cyan,investigate:x.cyan,explore:x.cyan,prototype:x.cyan};var K=e=>{let{currentNode:t}=C(),r=Dt().isSetup,n=t.context,o=[f.SYNC,f.HELP,f.SET_VIEW,f.SET_EDITOR,f.SET_USERNAME],i=[f.NEW,f.RENAME,f.DELETE],a=[f.TAG,f.ASSIGN,f.CLOSE_ISSUE,f.RE_OPEN_ISSUE,f.SET_DESCRIPTION],m=[...{WORKSPACE:[...o,...i],BOARD:[f.FILTER,...o,...i],SWIMLANE:[f.FILTER,...o,...i],TICKET:[...o,...i,...a],FIELD:[...o,...a],FIELD_LIST:[...o,...a],TEXT:[...o]}[n||"WORKSPACE"]],u={[f.SYNC]:[],[f.INIT]:[],[f.SET_USERNAME]:[],[f.SET_DESCRIPTION]:["confirm"],[f.DELETE]:["confirm"],[f.RE_OPEN_ISSUE]:["confirm"],[f.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[f.CLOSE_ISSUE]:["confirm"],[f.FILTER]:["tag","assignee","description","title","clear"],[f.SET_VIEW]:["dense","wide"],[f.SET_EDITOR]:[...On,"vim"],[f.TAG]:[...new Set([...Object.keys(Je),...E.getExistingTags()])],[f.ASSIGN]:E.getExistingAssignees(),[f.HELP]:[],[f.RENAME]:[],[f.NEW]:n==="TICKET"||n==="FIELD"||n==="FIELD_LIST"?["issue","swimlane","board"]:n==="SWIMLANE"?["issue","swimlane","board"]:n==="BOARD"?["issue","swimlane","board"]:["board"],[f.NONE]:m};return r?Hn()||(u={[f.NONE]:[f.HELP,f.INIT],[f.HELP]:u[f.HELP],[f.INIT]:u[f.INIT]}):u={[f.NONE]:[f.HELP,f.SET_EDITOR,f.SET_USERNAME],[f.HELP]:u[f.HELP],[f.SET_EDITOR]:u[f.SET_EDITOR],[f.SET_USERNAME]:u[f.SET_USERNAME]},u[e]??[]};import Pr from"chalk";import Xe from"chalk";var Mr={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ns=(e,t,r)=>Math.max(t,Math.min(r,e)),Tr=(e,t,r)=>e+(t-e)*r,$n=e=>{let t=0;for(let r=0;r<e.length;r++)t=t*31+e.charCodeAt(r)>>>0;return t},os=(e,t,r)=>{let n=t/100,o=r/100,i=(1-Math.abs(2*o-1))*n,a=e/60,l=i*(1-Math.abs(a%2-1)),m=0,u=0,p=0;a>=0&&a<1?(m=i,u=l):a>=1&&a<2?(m=l,u=i):a>=2&&a<3?(u=i,p=l):a>=3&&a<4?(u=l,p=i):a>=4&&a<5?(m=l,p=i):(m=i,p=l);let y=o-i/2;return[Math.round((m+y)*255),Math.round((u+y)*255),Math.round((p+y)*255)]},is=([e,t,r])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}`,ss=(e,t,r)=>[Math.round(Tr(e[0],t[0],r)),Math.round(Tr(e[1],t[1],r)),Math.round(Tr(e[2],t[2],r))],pt=e=>{let r=$n(e)%360,n=os(r,Mr.stringColor.saturation,Mr.stringColor.lightness);return is(n)},as=e=>{let t=Mr.gradient.stops,r=ns(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let n=t.length-1,o=r*n,i=Math.min(Math.floor(o),n-1),a=o-i;return ss(t[i],t[i+1],a)},Ft=e=>$n(e.toLowerCase().trim())/4294967295,_n=e=>{let t=Ft(e);return as(t)},ds=e=>{let[t,r,n]=_n(e);return{normal:o=>Xe.bgRgb(t,r,n).black(o),cursor:o=>Xe.bgRgb(t,r,n).white.bold(o)}},Rr=e=>{let[t,r,n]=_n(e);return{fg:o=>Xe.rgb(t,r,n)(o),fgCursor:o=>Xe.rgb(t,r,n).inverse(o),bg:o=>Xe.bgRgb(t,r,n).black(o),bgCursor:o=>Xe.bgRgb(t,r,n).white.bold(o)}},Lr=e=>ds(e).normal(` ${e} `),se=(e,t=Je)=>{let n=(o=>o.toLowerCase().trim())(e);return n&&t[n]?t[n]:pt(n)};var Ce="<ENTER> to confirm",Y=(e="",t=[])=>({message:e,validity:ve.Valid,completionWordList:t}),le=({message:e,completionWordList:t})=>({validity:ve.Invalid,message:e,completionWordList:t}),gt=e=>e.length===0,Le=({prefix:e="",wordList:t,postfix:r="",noOfHints:n=2,inputString:o,minLengthForHints:i=1})=>{let m=[...t.filter(Boolean).filter(p=>p.startsWith(o.trim()))].sort((p,y)=>Ft(p)-Ft(y)).slice(0,n).map(Lr),u=m.length>i?m.join(" "):"";return u?`${e}${u}${r}`:""},Dr=({modifier:e})=>{let t="confirm";return e===t?Y(Ce):le({message:gt(e)?`if you are certain, enter ${Lr(t)}`:"",completionWordList:[t]})},cs=({list:e,hint:t})=>({modifier:r})=>e.includes(r)?Y(Ce):le({message:gt(r)?t:"",completionWordList:[]}),ls=({list:e,hint:t,onValue:r})=>({modifier:n,inputString:o})=>e.includes(n)?o.trim().length<1?le({message:r,completionWordList:[]}):Y():le({message:gt(n)?t:"",completionWordList:[]}),Fr=({hint:e})=>({modifier:t,inputString:r})=>gt(t)&&gt(r)?le({message:e,completionWordList:[]}):Y(Ce),ms={[f.INIT]:()=>Y(Ce),[f.FILTER]:e=>{if(e.modifier==="clear")return Y();let t=a=>K(f.FILTER).includes(a);if(!e.modifier||!t(e.modifier??""))return le({message:Le({wordList:K(f.FILTER),noOfHints:100,inputString:e.inputString}),completionWordList:K(f.FILTER)});let n=Object.values(C().tags).map(a=>a.name),o=Object.values(C().contributors).map(a=>a.name),i=e.modifier==="tag"?n:e.modifier==="assignee"?o:[];return e.inputString?i.length&&!i.includes(e.inputString.trim()??"")?le({message:Le({prefix:`existing ${e.modifier}s... `,wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i}):Y():le({message:Le({prefix:"one of... ",wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i})},[f.NONE]:e=>e.command?Y():le({message:Le({prefix:"commands... ",wordList:K(f.NONE),noOfHints:100,inputString:e.inputString,minLengthForHints:0}),completionWordList:[]}),[f.NEW]:e=>ls({list:K(f.NEW),hint:Le({wordList:K(f.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[f.SET_DESCRIPTION]:()=>Y(Ce),[f.HELP]:()=>Y(Ce),[f.RENAME]:()=>Y(Ce),[f.DELETE]:e=>Dr(e),[f.CLOSE_ISSUE]:e=>Dr(e),[f.RE_OPEN_ISSUE]:e=>Dr(e),[f.MOVE]:e=>Fr({hint:Le({prefix:"hey hacker! These commands are blocked for you... ",wordList:K(f.MOVE),noOfHints:10,inputString:e.inputString})})(e),[f.TAG]:e=>{let t=E.getExistingTags().map(r=>` ${Pr.bgHex(se(r))(" "+r+" ")} `).slice(0,10);return Fr({hint:"tag name like... "+t.join("")})(e)},[f.ASSIGN]:e=>{let t=E.getExistingAssignees().map(r=>` ${Pr.bgHex(se(r))(" "+r+" ")} `).slice(0,10);return Fr({hint:"assign to... "+t.join("")})(e)},[f.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=K(f.SET_EDITOR);return e.modifier?Y(Ce):le({message:Le({wordList:t,noOfHints:100,inputString:e.inputString}),completionWordList:[]})},[f.SET_USERNAME]:e=>e.inputString?Y():le({message:`Enter a username. Saved in ${Pr.bgBlack("~/.epiq/")}`,completionWordList:[]}),[f.SET_VIEW]:e=>cs({list:K(f.SET_VIEW),hint:Le({wordList:K(f.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[f.SYNC]:()=>Y(Ce)},Kn=Object.fromEntries(Object.entries(ms).map(([e,t])=>[e,{validate:(r,n,o)=>t({modifier:n,command:r,inputString:o})}]));var Vn=["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 R={Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",SetView:"set-view",SetEditor:"set-editor",SetUserName:"set-user-name",NewItem:"add-new-item",TagTicket:"ticket-tag",AssignUserToTicket:"ticket-assign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Sync:"sync"};var jn=e=>Object.values(f).includes(e),zn=(e,t)=>{let r=e.command??"",{modifier:n,target:o,inputString:i}=e,{message:a,validity:l,completionWordList:m}=Kn[r].validate(r,n,i),u=o==="command"?Object.values(f):r&&e.target==="modifier"?K(r):Vn;return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?Bn(e,[...m,...u]):{hint:"",hints:[],remainder:"",overlap:0}}};var qn=e=>{let t=e.trimStart(),r=ps(t),n=(r[0]??"").trimStart().trimEnd(),o=(r[1]??"").trimStart().trimEnd(),i=gs(e),a=jn(n)?n:null,l=a!==null,m=n!=="",u=e.endsWith(" "),p=a?K(a)??[]:[],y=a&&p.includes(o)?o:"",v="word";r.length<=1?v="command":r.length===2&&(v="modifier");let I=us(t,a,y);return{raw:e,trimmedStart:t,words:r,firstWord:n,lastWord:i,hasCommand:m,command:a,isCommandKeyword:l,isLastWordCompleted:u,modifier:y,target:v,inputToMatch:i,inputString:I}},us=(e,t,r)=>{let n=e;return t&&n.startsWith(t)&&(n=n.slice(t.length)),n=n.replace(/^\s+/,""),r&&n.startsWith(r)&&(n=n.slice(r.length),n=n.replace(/^\s+/,"")),n},ps=e=>e?e.split(/\s+/):[],gs=e=>e.trimEnd().split(/\s+/).at(-1)??"";var Gn=" ",z={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:ve.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},kr=new Set,Jn=()=>{for(let e of kr)e()},Xn=e=>(kr.add(e),()=>kr.delete(e)),Ne=e=>{let r=e(z),n=qn(r.value),o=r.cursorPosition===r.value.length;z={...r,commandMeta:zn(n,o)},Jn()},kt=({message:e,result:t})=>{let r=structuredClone(z);return r.commandMeta={...r.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},r.commandIsPending=!0,z=r,Jn(),c(e,null)},Br=e=>{Ne(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Or=e=>{Ne(t=>{let{value:r,cursorPosition:n}=t,o=n;if(e==="left"){for(;o>0&&r[o-1]===" ";)o--;for(;o>0&&r[o-1]!==" ";)o--}else{for(;o<r.length&&r[o]!==" ";)o++;for(;o<r.length&&r[o]===" ";)o++}return{...t,cursorPosition:o}})},Yn=()=>{Ne(e=>{let t=e.value.slice(e.cursorPosition),r=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,r)+t,cursorPosition:r,commandIsPending:!1}})},Qn=()=>{Ne(e=>{let{value:t,cursorPosition:r}=e,n=r;for(;n>0&&t[n-1]===" ";)n--;for(;n>0&&t[n-1]!==" ";)n--;let o=t.slice(r);return{...e,value:t.slice(0,n)+o,cursorPosition:n,commandIsPending:!1}})},H=e=>{Ne(t=>{let r=Math.max(0,Math.min(t.cursorPosition,t.value.length)),n=t.value.slice(0,r),o=t.value.slice(r),i=e(n,t.commandMeta.autoCompletion),a=i+o,l=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:l,commandIsPending:!1}})},Zn=()=>{Ne(e=>({...e,commandIsPending:!0}))},eo=({addToHistory:e=!0})=>{Ne(r=>({...r,commandHistory:e?[r.value,...r.commandHistory].slice(0,40):r.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),fs()},to=()=>{Ne(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),r=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:r,cursorPosition:r.length}})},ro=()=>{Ne(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),r=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:r,cursorPosition:r.length}})},fs=()=>H(()=>""),ue=()=>z,Bt=()=>{let[e,...t]=z.value.split(Gn);return t.join(Gn).trim()};var ys=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",xs=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",vs=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",no=(e,t)=>{if(xs(e,e.sequence))return"MoveCursorLeftOfWord";if(vs(e,e.sequence))return"MoveCursorRightOfWord";if(ys(e,e.sequence))return"EraseInputWord";switch(e.name){case"tab":return"autoCompleteCommand";case"up":return"getLastCommandFromHistory";case"down":return"getNextCommandFromHistory";case"left":return"MoveCursorLeft";case"right":return"MoveCursorRight";case"return":return"confirm";case"backspace":return t?"eraseInput":"exitCommandLine";case"escape":return"exitCommandLine";default:return"captureInput"}};function hs(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function Cs(e,t,r){let n=C().currentNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?r.prevItem:n?r.prevContainer:null;case"down":return e==="vertical"?r.nextItem:n?r.nextContainer:null;case"left":return e==="horizontal"?r.prevItem:n?r.prevContainer:null;case"right":return e==="horizontal"?r.nextItem:n?r.nextContainer:null}}function oo(e,t){let r=ue();if(e.sequence===":"&&r.value==="")return"initCommandLine";if(t===g.MOVE)switch(e.name){case"m":case"return":return"confirmMove"}if(t===g.COMMAND_LINE)return no(e,r.value);let n=hs(e);if(n){let o=t===g.MOVE?{prevItem:"movePreviousItem",nextItem:"moveNextItem",prevContainer:"moveToPreviousContainer",nextContainer:"moveToNextContainer"}:{prevItem:"navPreviousItem",nextItem:"navNextItem",prevContainer:"navToPreviousContainer",nextContainer:"navToNextContainer"};return Cs(C().currentNode.childRenderAxis,n,o)}if(e.ctrl&&e.name==="c")return"exit";switch(e.name){case"e":return"edit";case"n":return"addItem";case"m":return"initMove";case"d":return"Delete";case"return":return"confirm";case"space":return"confirm";case"v":return C().viewMode==="wide"?"SetViewDense":"SetViewWide";case"q":case"escape":return"exit";case"s":return"sync";default:return null}}var io=e=>{let{context:t}=C()?.currentNode;if(!t)return R.None;switch(e){case f.INIT:return R.Init;case f.DELETE:return R.Delete;case f.SET_DESCRIPTION:return R.Edit;case f.HELP:return R.ViewHelp;case f.RE_OPEN_ISSUE:return R.ReopenIssue;case f.CLOSE_ISSUE:return R.CloseIssue;case f.TAG:return R.TagTicket;case f.ASSIGN:return R.AssignUserToTicket;case f.RENAME:return R.Rename;case f.NEW:return R.NewItem;case f.FILTER:return R.Filter;case f.MOVE:return R.Move;case f.SET_USERNAME:return R.SetUserName;case f.SET_EDITOR:return R.SetEditor;case f.SET_VIEW:return R.SetView;case f.SYNC:return R.Sync;default:return R.None}};import sn from"fs";import{ulid as $}from"ulid";import{spawnSync as Ts}from"node:child_process";import Ms from"node:os";import lo from"node:path";import{ulid as Rs}from"ulid";import{accessSync as Ns,copyFileSync as Es,existsSync as Ot,mkdirSync as so,readdirSync as ao,readFileSync as bs,renameSync as Is,rmSync as Ss,statSync as co,unlinkSync as As,writeFileSync as ws}from"node:fs";import Ye from"node:path";var oe={writeToFile:(e,t)=>{try{let r=Ye.dirname(e);Ot(r)||so(r,{recursive:!0});let n=typeof t=="string"?t:JSON.stringify(t,null,2);ws(e,n,"utf-8")}catch(r){logger.error(`Failed to write file at ${e}:`,r)}},readFile:e=>{try{return bs(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=oe.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 Ot(e)&&co(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Ns(e),!0}catch{return!1}},mkDir:e=>so(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:r}=Ye.parse(t);for(;;){let n=Ye.join(t,e);try{if(Ot(n)&&co(n).isDirectory())return n}catch{logger.error(`Unable to locate folder ${e}`)}if(t===r)break;t=Ye.dirname(t)}return null},readFirstJSON(e){try{if(!oe.dirExists(e))return null;let t=ao(e).filter(n=>n.endsWith(".json")).sort()[0];if(!t)return null;let r=Ye.join(e,t);return oe.readFileJSON(r)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return oe.dirExists(e)?ao(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{As(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Ss(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,r){if(this.mkDir(Ye.dirname(t)),!r?.overwrite&&Ot(t))throw new Error(`moveFile: destination exists: ${t}`);r?.overwrite&&this.rmFile(t);try{Is(e,t)}catch(n){if(n?.code==="EXDEV"){Es(e,t),this.rmFile(e);return}throw n}}};function Ls(){let{preferredEditor:e}=ce(),t=[e,process.env.VISUAL,process.env.EDITOR,"vim","vi","nano"].filter(r=>!!r?.trim());return[...new Set(t)]}function Ps(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function mo(e){let t=lo.join(Ms.tmpdir(),"epiq");oe.mkDir(t);let r=lo.join(t,Rs());oe.writeToFile(r,e??"");let n=Ls();for(let o of n){let i=Ps(o,r),a=Ts(i,{stdio:"inherit",shell:!0});if(!a.error&&a.status===0){let l=oe.readFile(r);if(l==null)return s("Unable to read edited file");let m=l.replace(/\r?\n$/,"");return c("Successfully edited",m)}}return s("Unable to open editor")}import{monotonicFactory as Ds,ulid as Ut}from"ulid";var Wt=Ds(),uo=({name:e,parent:t,userId:r,userName:n})=>{let o=Wt(),i=Wt(),a=Wt(),l=Wt();return[{id:Ut(),userId:r,userName:n,action:"add.issue",payload:{id:o,parent:t,name:e}},{id:Ut(),userId:r,userName:n,action:"add.field",payload:{id:i,parent:o,name:"Description",val:""}},{id:Ut(),userId:r,userName:n,action:"add.field",payload:{id:a,parent:o,name:"Assignees"}},{id:Ut(),userId:r,userName:n,action:"add.field",payload:{id:l,parent:o,name:"Tags"}}]};var po=e=>{let t=e.log??[];for(let r=t.length-1;r>=0;r--){let n=t[r];if(n&&n.action==="close.issue"&&n.payload.id===e.id)return n.payload.parent}return null};var Fs=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[Qe,Ht]=Fs;var P=(e,t)=>s(`${t.split(".").join(" ")+" failed, "+e.toLowerCase()}`),ks={"init.workspace":({action:e,payload:t})=>{let{id:r,name:n}=t,o=X.workspace(r,n);go(o);let i=E.createNodeAtPosition(o);return d(i)?P(i.message??"Failed to initialize workspace",e):c("Workspace initialized",{action:e,result:i.data})},"add.workspace":({action:e,payload:t})=>{let{id:r,name:n}=t,o=X.workspace(r,n),i=E.createNodeAtPosition(o);return d(i)?P(i.message??"Failed to add workspace",e):c("Added workspace",{action:e,result:i.data})},"add.board":({action:e,payload:t})=>{let{id:r,name:n,parent:o}=t,i=E.createNodeAtPosition(X.board(r,n,o));return d(i)?P(i.message??"Unable to create board",e):c("Added board",{action:e,result:i.data})},"add.swimlane":({action:e,payload:t})=>{let{id:r,name:n,parent:o}=t,i=E.createNodeAtPosition(X.swimlane(r,n,o));return d(i)?P(i.message??"Unable to create swimlane",e):c("Added swimlane",{action:e,result:i.data})},"add.issue":({action:e,payload:t})=>{let{id:r,name:n,parent:o}=t,i=E.createNodeAtPosition(X.ticket(r,n,o));return d(i)?P(i.message??"Unable to create issue",e):c("Added issue",{action:e,result:i.data})},"add.field":({action:e,payload:t})=>{let{id:r,name:n,parent:o,val:i}=t,a=E.createNodeAtPosition(X.field(r,n,o,{value:i},n.includes("Description")?"vertical":"horizontal"));return d(a)?P(a.message??`Unable to create field: ${n}`,e):c("Added field",{action:e,result:a.data})},"edit.title":({action:e,payload:t})=>{let{id:r,name:n}=t;if(!E.getNode(r))return P("Unable to locate node",e);let i=E.renameNode(r,n);return d(i)?P(i.message??"Unable to edit title",e):c("Edited title",{action:e,result:i.data})},"delete.node":({action:e,payload:t})=>{let{id:r}=t,n=E.tombstoneNode(r);return d(n)?P(n.message??"Unable to delete node",e):c("Deleted node",{action:e,result:n.data})},"create.tag":({action:e,payload:t})=>{let{id:r,name:n}=t,o=E.createTag({id:r,name:n});return d(o)?P(o.message??"Unable to create tag",e):c("Tag added",{action:e,result:o.data})},"create.contributor":({action:e,payload:t})=>{let{id:r,name:n}=t,o=E.createContributor({id:r,name:n});return d(o)?P(o.message??"Unable to create contributor",e):c("Contributor created",{action:e,result:o.data})},"tag.issue":({action:e,payload:t})=>{let{id:r,target:n,tagId:o}=t,i=E.tag(n,o,r);return d(i)?P(i.message??"Unable to tag issue",e):c("Issue tagged",{action:e,result:i.data})},"assign.issue":({action:e,payload:t})=>{let{id:r,contributor:n,target:o}=t,i=E.assign(o,n,r);return d(i)?P(i.message??"Unable to assign issue",e):c("Assigned successfully",{action:e,result:i.data})},"move.node":({action:e,payload:t})=>{let{id:r,parent:n,pos:o}=t,i=E.moveNode({id:r,parentId:n,position:o});return d(i)?P(i.message??"Failed to move node",e):c("Moved node",{action:e,result:i.data})},"edit.description":({action:e,payload:t})=>{let{id:r,md:n}=t,o=E.editValue(r,n);return d(o)?P(o.message??"Unable to edit description",e):c("Set node value",{action:e,result:o.data})},"close.issue":({action:e,payload:t})=>{let{id:r}=t,n=E.getNode(r);if(!n)return P("Unable to locate issue",e);if(!We(n))return P("Can only close issues",e);let o=E.getNode(Qe);if(!o)return P("Unable to locate target swimlane",e);if(o.id===n.parentNodeId)return P("Cannot close closed issue",e);let a=E.moveNode({id:r,parentId:o.id});return d(a)?P(a.message??"Unable to close issue",e):c("Issue closed",{action:e,result:a.data})},"reopen.issue":({action:e,payload:t})=>{let{id:r}=t,n=E.getNode(r);if(!n)return P("Unable to locate issue",e);if(!We(n))return P("Can only reopen issues",e);let o=E.getNode(Qe);if(!o)return P("Unable to locate closed swimlane",e);if(!(n.parentNodeId===o.id))return P("Issue is not closed",e);let a=po(n);if(!a)return P("Unable to resolve previous parent from issue history",e);if(a===o.id)return P("Previous parent resolves to closed swimlane",e);if(!E.getNode(a))return P("Previous parent no longer exists",e);let m=E.moveNode({id:r,parentId:a});return d(m)?P(m.message??"Unable to reopen issue",e):c("Issue reopened",{action:e,result:m.data})},"lock.node":({action:e,payload:t})=>{let{id:r}=t,n=E.lockNode(r);return d(n)?P(n.message??"Unable to lock node",e):c("Node locked",{action:e,result:n.data})}},Bs=(e,t)=>{let r=E.getNode(e);r&&E.updateNode({...r,log:[...r.log??[],t]})},Os=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],r=C().nodes[e.payload.id]?.parentNodeId;return r&&t.push(r),t;case"tag.issue":case"assign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function Ze(e,t=!1){let r=ks[e.action],n=r(e);if(d(n))return n;if(!t){let a=[...new Set(Os(e))];for(let l of a)Bs(l,e)}let o=e.userId,i=e.userName;return!o?.length||!i?.length?P("Invalid user ID format",e.action):(E.createContributor({name:i,id:o}),n)}var ft=e=>e.map(t=>Ze(t));import zt from"node:fs";import $e from"node:path";import{decodeTime as Gs,monotonicFactory as Js}from"ulid";import{z as yt}from"zod";var $t=process.env.IS_LOCAL==="true",pe=()=>".epiq";import _t from"node:fs";import Kt from"node:path";import{z as Wr}from"zod";var Us=pe(),Ws="events",Hs=Wr.object({userId:Wr.string().min(1).default("unknown"),userName:Wr.string().min(1).default("unknown")}),$s=(e=process.cwd())=>Kt.join(et(e),Us,Ws),_s=e=>{let[t,r]=Kt.basename(e,".jsonl").split("."),n=Hs.safeParse({userId:t,userName:r});return n.success?c("Parsed event file actor",n.data):s(`Invalid event file name ${Kt.basename(e)}: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Ks=e=>{let t=Object.keys(e).filter(r=>r!=="id"&&r!=="v");return t.length!==1?s(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?s("Invalid persisted event: action key is missing or invalid"):c("Resolved persisted action",t[0])},Vs=(e,t)=>t in e,js=({id:e,action:t,payload:r,userId:n,userName:o})=>({id:e,action:t,payload:r,userId:n,userName:o}),zs=e=>{let{userId:t,userName:r,...n}=e,o=Ks(n);if(d(o))return s(o.message);let i=o.data,a=e.id?.[0];return a?Vs(n,i)?c("Decoded persisted event",js({id:a,action:i,payload:n[i],userId:t,userName:r})):s(`Persisted event is missing payload for action: ${i}`):s("Persisted event is missing id")},Vt=e=>{if(!_t.existsSync(e))return c("Event file missing",[]);let t=_s(e);if(d(t))return s(t.message);let r=_t.readFileSync(e,"utf8"),n=[];for(let o of r.split(`
3
- `)){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{return s(`Failed to parse event JSON from ${e}: ${i}`)}let l=Hr(a);if(d(l))return s(`${l.message} in ${e}: ${i}`);n.push({...l.data,userId:t.data.userId,userName:t.data.userName})}return c("Parsed persisted events file",n)};function fo(e=process.cwd()){let t=$s(e);if(!_t.existsSync(t))return s("No events found");let r=_t.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Kt.join(t,o)),n=[];for(let o of r){let i=Vt(o);if(d(i))return s(i.message);n.push(...i.data)}return c("All events loaded",qs(n))}function jt(e=process.cwd()){let t=fo(e);if(d(t))return s(t.message);let r=[];for(let n of t.data){let o=zs(n);if(d(o))return s(`Failed to decode event ${n.id?.[0]??"<unknown>"}: ${o.message}`);r.push(o.data)}return c("Loaded merged events",r)}function yo(e=process.cwd()){let t=fo(e);return d(t)?s(t.message):c("Loaded edge reference",t.data.at(-1)?.id?.[0]??null)}var qs=e=>{let t=new Map(e.map(l=>[l.id[0],l])),r=new Map;for(let l of e){let m=l.id[1],u=r.get(m)??[];u.push(l),r.set(m,u)}for(let l of r.values())l.sort((m,u)=>{let[p]=m.id,[y]=u.id;return p.localeCompare(y)});let n=[],o=new Set,i=l=>{let m=r.get(l)??[];for(let u of m){let[p]=u.id;o.has(p)||(o.add(p),n.push(u),i(p))}};i(null);let a=[...e].filter(l=>{let[m]=l.id;return!o.has(m)}).sort((l,m)=>{let[u,p]=l.id,[y,v]=m.id,I=p===null||t.has(p),S=v===null||t.has(v);if(I&&!S)return-1;if(!I&&S)return 1;let N=(p??"").localeCompare(v??"");return N!==0?N:u.localeCompare(y)});return[...n,...a]};var xo=e=>({action:e.action,payload:e.payload});var Co=1,vo=Js(),Xs="events",Ys=yt.tuple([yt.string().min(1),yt.string().min(1).nullable()]),Qs=yt.looseObject({v:yt.literal(Co),id:Ys}),Hr=e=>{let t=Qs.safeParse(e);return t.success?c("Parsed persisted event",t.data):s(`Invalid persisted event: ${t.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},ho=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",Q=()=>{let{userName:e,userId:t}=ce();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:ho(t),userName:ho(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},Zs=e=>zt.existsSync($e.join(e,pe()))&&zt.statSync($e.join(e,pe())).isDirectory(),et=(e=process.cwd())=>{let t=$e.resolve(e);for(;;){if(Zs(t))return t;let r=$e.dirname(t);if(r===t)return $e.resolve(e);t=r}},No=(e=process.cwd())=>$e.join(et(e),pe(),Xs),qt=()=>{let e=Q();return d(e)||!e.data?s("Unable to resolve event log path"):c("Succeeded",`${e.data.userId}.${e.data.userName}.jsonl`)},ea=(e=process.cwd())=>{let t=qt();if(d(t))return s("Unable to resolve file name");let r=t.data;return/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r)?c("Successfully resolved event log path",$e.join(No(e),r)):s(`Invalid event log file name: ${r}`)},ta=(e,t)=>{let r={[e.action]:e.payload,v:Co,id:t};return Hr(r)};function Eo(e,t=process.cwd()){try{let r=et(t),n=No(r),o=ea(r);if(d(o))return o;zt.mkdirSync(n,{recursive:!0});let i=yo(r);if(d(i))return s(i.message);let a;if(i.data){let m=Gs(i.data),u=Math.max(Date.now(),m+1);a=vo(u)}else a=vo();let l=ta(xo(e),[a,i.data]);return d(l)?s(l.message):(zt.appendFileSync(o.data,`${JSON.stringify(l.data)}
4
- `,"utf8"),c("Event persisted",{path:o.data,entry:l.data}))}catch(r){let n=r instanceof Error?r.message:"Unknown persist error";return s(`Failed to persist event: ${n}`)}}function Z(e){let t=Ze(e);if(t.result!==he.Success)return t;let r=Eo(e);return d(r)?r:t}function Gt(e){return e.map(t=>Z(t))}import{ulid as bo}from"ulid";var tt=null,Pe=()=>structuredClone(tt),rt=e=>tt=e,Io=()=>{let{currentNode:e,selectedIndex:t}=C(),n=M(e.id)[t];return n?c("Resolved selected child",n):s("Target node not found")};function $r(e){let t=Io();if(d(t))return t;let{currentNode:r,nodes:n}=C();if(!r.parentNodeId)return s("Missing parent node id");let o=n[r.parentNodeId];if(!o)return s("Missing parent node");let i=W(o.id),a=i.findIndex(({id:v})=>v===r.id);if(a<0)return s("Current node not found among siblings");let l=i[a+e];if(!l)return s("Missing sibling node");let m=Q();if(d(m))return s("Unable to resolve user ID");let{userId:u,userName:p}=m.data;if(rt({id:bo(),userId:u,userName:p,action:"move.node",payload:{id:t.data.id,parent:l.id,pos:{at:"end"}}}),!tt)return s("Could not materialize move state");let y=Ze(tt,!0);return d(y)?y:c("Node moved successfully",y.data)}function _r(e){let t=Io();if(d(t))return t;let{currentNode:r,selectedIndex:n}=C(),i=W(r.id)[n+e];if(!i)return s("Missing sibling node");let a=Q();if(d(a))return s("Unable to resolve user ID");let{userId:l,userName:m}=a.data;if(rt({id:bo(),userId:l,userName:m,action:"move.node",payload:{id:t.data.id,parent:r.id,pos:{at:e===1?"after":"before",sibling:i.id}}}),!tt)return s("Could not materialize move state");let u=Ze(tt,!0);return d(u)?u:c("Node moved successfully",u.data)}import ra from"node:os";import So from"node:path";import{z as Jt}from"zod";var na={userId:"",userName:"",preferredEditor:""},Ao=Jt.object({preferredEditor:Jt.string().optional(),userName:Jt.string().optional(),userId:Jt.string().optional()}).strict(),oa=".epiq",ia="config.json",wo=()=>So.join(ra.homedir(),oa),Kr=()=>So.join(wo(),ia),Vr=()=>{try{return oe.mkDir(wo()),c("Ensured ~/.epiq exists",null)}catch{return s("Unable to create ~/.epiq")}},sa=e=>{let t;try{t=JSON.parse(e)}catch{return s("Invalid ~/.epiq/config.json JSON")}let r=Ao.safeParse(t??{});return r.success?c("Parsed config",r.data):s(`Invalid ~/.epiq/config.json shape: ${r.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},To=()=>{let e=Vr();if(d(e))return s(e.message);let t=Kr(),r=oe.readFile(t);return r==null||r.trim()===""?c("No config found, using empty config",{}):sa(r)},Mo=e=>{let t=Vr();if(d(t))return s(t.message);let r=Ao.safeParse(e);if(!r.success)return s(`Invalid config: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let n=Kr();try{return oe.writeToFile(n,JSON.stringify(r.data,null,2)+`
5
- `),c("Config written",null)}catch{return s("Unable to write ~/.epiq/config.json")}},jr=e=>{let t=To();if(d(t))return s("Failed to read existing config");let r={...t.data,...e};return Mo(r)},Ro=()=>{let e=Kr(),t=Vr();if(d(t))throw new Error("Unable to create ~/.epiq");if(!(oe.readFile(e)!==null)){let l=Mo(na);if(d(l))throw new Error("Unable to create ~/.epiq/config.json")}let n=To();if(d(n))throw new Error(n.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:a}=n.data;return!i||!a?s("User name or ID not configured in ~/.epiq/config.json"):ut({preferredEditor:o,userName:i,userId:a})};var nt=(e,t)=>{let r=e.find(n=>n.context===t);return r!==void 0?c("Found node",r):s("Unable to find node in breadcrumb")};import Ct from"node:fs";import{spawn as ca}from"node:child_process";import qr from"node:fs";import ot from"node:path";var xt=(e,t)=>{let r=new Map,n=t??((...i)=>JSON.stringify(i)),o=((...i)=>{let a=n(...i);if(!r.has(a)){let l=e(...i).then(m=>(d(m)&&r.delete(a),m));r.set(a,l)}return r.get(a)});return o.clear=()=>r.clear(),o};import vt from"fs";import Po from"path";import aa from"util";var Lo=1e3,Do=(e=process.cwd())=>Po.join(et(e),pe(),"log","epiq.log");function da(e=process.cwd()){if(!$t)return;let t=Do(e);if(!vt.existsSync(t))return;let n=vt.readFileSync(t,"utf8").split(`
6
- `);if(n[n.length-1]===""&&n.pop(),n.length<=Lo)return;let o=n.slice(-Lo).join(`
2
+ import{render as Pc}from"ink";import Dc from"meow";import ds from"react";import hc from"chalk";import{Box as fe,Text as He}from"ink";import O from"react";import dt from"chalk";import{monotonicFactory as xd,ulid as Se}from"ulid";import{useSyncExternalStore as gd}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function $e(e){return e.context==="TICKET"}var Ur=e=>e.context==="SWIMLANE";var g={INIT:"init",HELP:"help",NEW:"new",TAG:"tag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",DELETE:"delete",RENAME:"rename",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",SET_DESCRIPTION:"edit",SET_EDITOR:"set:editor",SET_VIEW:"set:view",SET_USERNAME:"set:username",SYNC:"sync",NONE:""},Ne={None:"none",Invalid:"invalid",Valid:"valid"},ye={None:"none",Success:"success",Fail:"fail"},s=e=>({result:ye.Fail,message:e,data:null}),m=(e,t)=>({result:ye.Success,message:e,data:t}),Wr=()=>({result:ye.None,message:"No result",data:null}),c=e=>e.result==="fail",Fe=e=>e.result==="success";var f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function Pt(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Dt=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Pn=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var Hr=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),i=t.get(o);i?i.push(n):t.set(o,[n])}return t},_r=(e,t)=>t?e.get(t)??[]:[];var $r=new WeakMap,ps=e=>{let t=$r.get(e);return t||(t=Hr(e),$r.set(e,t)),t};var Kr=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return _r(ps(e),r).filter(i=>Pt(r,i)>=n)};var Vr=({inputToMatch:e,lastWord:t},n)=>{if(t.endsWith(" "))return{hint:"",hints:[],overlap:0,remainder:""};let r=Kr({wordList:n,inputToMatch:e,overlapThreshold:1});return gs(t,r)},gs=(e,t)=>{let n=t[0]??"",r=Pt(e.toLowerCase(),n.toLowerCase()),o=n?n+" ":"",i=o.slice(r);return{hint:o,hints:t,overlap:r,remainder:i}};var jr=["vi","vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var Je=24n,fs=Je*4n,Ft=(1n<<fs)-1n,ys=/^[0-9a-f]+$/;function zr(e){if(!e||!ys.test(e))throw new Error(`Invalid hex rank: ${e}`);return BigInt("0x"+e)}function kt(e,t=Je){if(e<0n)throw new Error("Negative rank not allowed");return e.toString(16).padStart(Number(t),"0")}function pt(e,t){if(!e&&!t)return kt(Ft/2n,Je);let n=e?zr(e):0n,r=t?zr(t):Ft;if(r<=n)return kt(Ft/2n,Je);let o=(n+r)/2n;return o===n||o===r?"":kt(o,Je)}function ue(){return kt(Ft/2n,Je)}var ee={workspace:(e,t)=>({id:e,title:t,rank:ue(),isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r=!1)=>({id:e,title:t,rank:ue(),isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n)=>({id:e,title:t,rank:ue(),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:ue(),isDeleted:!1,props:r,context:P.FIELD,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[]}),ticket:(e,t,n)=>({id:e,title:t,rank:ue(),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:ue(),isDeleted:!1,props:r,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[]})};var _=e=>Object.values(h().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Gr=(e,t)=>e.findIndex(n=>n.id===t),Dn=(e,t={at:"end"})=>{if(e.length===0)return m("Resolved rank",ue());switch(t.at){case"start":{let n=e[0];return n?m("Resolved rank",pt(void 0,n.rank)):s("Unable to resolve first sibling")}case"end":{let n=e[e.length-1];return n?m("Resolved rank",pt(n.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let n=Gr(e,t.sibling);if(n<0)return s("Sibling not found");let r=n>0?e[n-1]:void 0,o=e[n];return o?m("Resolved rank",pt(r?.rank,o.rank)):s("Sibling not found")}case"after":{let n=Gr(e,t.sibling);if(n<0)return s("Sibling not found");let r=e[n],o=n<e.length-1?e[n+1]:void 0;return r?m("Resolved rank",pt(r.rank,o?.rank)):s("Sibling not found")}}};var Xe=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r)return s("Node not found");if(r.context===t)return m("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return m("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return s(`No ancestor found for context: ${t}`)},kn=(e,t)=>{let{nodes:n}=h(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Fn=(e,t)=>e?e.readonly?s({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:s("Node not found"),N={deleteNode(e){ae(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=h(),r=n[e];if(!r)return s("Edit target node not found");let o=Fn(r,"edit");if(o)return o;let i={...r,props:{...r.props,value:t}};return N.updateNode(i),m("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return s("Rename target node not found");let r=Fn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),m("Renamed node",o)},getExistingTags(){let{tags:e}=h();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=h();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return _(e).find(n=>n.title===t)},moveNode({id:e,parentId:t,position:n={at:"end"}}){let{rootNodeId:r}=h(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let a=Fn(o,"move");if(a)return a;if(kn(t,e))return s("Cannot move node into its own descendant");let d=_(t).filter(p=>p.id!==e),l=Dn(d,n);if(c(l))return l;let u={...o,parentNodeId:t,rank:l.data};return this.updateNode(u),m("Moved node successfully",u)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=h(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,a=l=>{let u=t[l];if(!(!u||i.has(l))){i.add(l);for(let p of _(u.id))a(p.id)}};a(e);let d={...structuredClone(t)};for(let l of i){if(!d[l])return s("Unable to locate node to delete");d[l]={...d[l],isDeleted:!0}}return n?(w({nodes:d}),m("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=ae(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return c(t)?s("Unable to create contributor"):m("Created contributor",e)},assign(e,t,n){let r=N.getContributor(t),o=N.getNode(e);if(!o||!r)return s("Unable assign contributor to issue");let i=this.getFieldByTitle(o.id,"Assignees");if(!i)return s("Unable to locate assignees field");if(_(i.id).some(l=>l.props?.value===t))return s("Contributor already assigned");let d=this.createNodeAtPosition(ee.field(n,r.name,i.id,{value:t}));return c(d)?d:m("Assigned contributor",d.data)},createTag(e){let t=ae(n=>({...n,tags:{...n.tags,[e.id]:e}}));return c(t)?s("Could not create tag"):m("Tag created",e)},tag(e,t,n){let r=N.getTag(t),o=N.getNode(e);if(!r)return s("Unable to add tag, missing tag");if(!o)return s("Unable to add tag, missing target");let i=this.getFieldByTitle(o.id,"Tags");if(!i)return s("Unable to locate tags field");if(_(i.id).some(l=>l.props?.value===t))return s("Tag already assigned");let d=this.createNodeAtPosition(ee.field(n,r.name,i.id,{value:t}));return c(d)?d:m("Tag added",d.data)},createNodeAtPosition(e,t={at:"end"}){if(!e.parentNodeId){let i={...e,rank:ue()};return this.createNode(i),m("Created node",i)}let n=_(e.parentNodeId),r=Dn(n,t);if(c(r))return r;let o={...e,rank:r.data};return this.createNode(o),m("Created node",o)},createNode(e){let t=ae(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return c(t)?s("Unable to create node"):m("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let n={...t,readonly:!0},r=ae(o=>({...o,nodes:{...o.nodes,[e]:n}}));return c(r)?s(r.message):m("Locked node",n)},updateNode(e){let t=ae(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return c(t)?t:m("Updated node",e)},getContributor(e){return h().contributors[e]},getTag(e){return h().tags[e]},getNode(e){return h().nodes[e]},getSiblings:e=>Object.values(h().nodes).filter(t=>!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank))};var Ot={preferredEditor:null,userName:null,userId:null},pe=()=>Ot,gt=e=>(Ot={...Ot,...e},Ot);var Bt=()=>{let e=pe(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},qr=()=>!Ke();var q={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#2a2f45",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},E={accent:q.cyan,accent2:q.magenta,primary:q.white,secondary:q.grayDark,secondary2:q.grayLight,gray:q.gray,green:q.green,yellow:q.yellow,red:q.red};var v={red:q.red,yellow:q.yellow,green:q.green,blue:q.blue,magenta:q.magenta,cyan:q.cyan},Qe={urgent:v.red,critical:v.red,important:v.red,blocker:v.red,asap:v.red,immediate:v.red,fail:v.red,failure:v.red,broken:v.red,bug:v.red,error:v.red,incident:v.red,outage:v.red,production:v.red,crash:v.red,security:v.red,warning:v.yellow,warn:v.yellow,risky:v.yellow,risk:v.yellow,attention:v.yellow,pending:v.yellow,review:v.yellow,"needs-review":v.yellow,qa:v.yellow,testing:v.yellow,test:v.yellow,validate:v.yellow,verification:v.yellow,staging:v.yellow,check:v.yellow,"follow-up":v.yellow,followup:v.yellow,waiting:v.yellow,blocked:v.yellow,hold:v.yellow,done:v.green,complete:v.green,completed:v.green,success:v.green,ok:v.green,stable:v.green,resolved:v.green,fixed:v.green,closed:v.green,merged:v.green,released:v.green,deployed:v.green,approved:v.green,verified:v.green,working:v.green,healthy:v.green,pass:v.green,passing:v.green,info:v.blue,information:v.blue,note:v.blue,docs:v.blue,documentation:v.blue,doc:v.blue,guide:v.blue,help:v.blue,explanation:v.blue,detail:v.blue,details:v.blue,context:v.blue,design:v.blue,discussion:v.blue,proposal:v.blue,idea:v.blue,feature:v.magenta,enhancement:v.magenta,improvement:v.magenta,refactor:v.magenta,refactoring:v.magenta,cleanup:v.magenta,optimize:v.magenta,optimization:v.magenta,perf:v.magenta,performance:v.magenta,upgrade:v.magenta,migration:v.magenta,modernize:v.magenta,debt:v.magenta,todo:v.cyan,next:v.cyan,planned:v.cyan,plan:v.cyan,future:v.cyan,backlog:v.cyan,investigate:v.cyan,explore:v.cyan,prototype:v.cyan};var xs=/^(\d+)(h|d|w|mo|y)$/,vs=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,hs=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let i=new Date(e,t-1,n,r,o);return i.getFullYear()===e&&i.getMonth()===t-1&&i.getDate()===n&&i.getHours()===r&&i.getMinutes()===o},Es=(e,t=new Date)=>{let n=e.match(xs);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let a=new Date(t);switch(o){case"h":return a.setHours(a.getHours()-i),a;case"d":return a.setDate(a.getDate()-i),a;case"w":return a.setDate(a.getDate()-i*7),a;case"mo":return a.setMonth(a.getMonth()-i),a;case"y":return a.setFullYear(a.getFullYear()-i),a;default:return null}},Cs=e=>{let t=e.match(vs);if(!t)return null;let[,n,r,o,i,a]=t,d=Number(n),l=Number(r),u=Number(o),p=i?Number(i):0,y=a?Number(a):0;return hs({year:d,month:l,day:u,hour:p,minute:y})?new Date(d,l-1,u,p,y):null},Ut=e=>{let t=e.trim().toLowerCase();return Es(t)??Cs(t)},Yr=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Ns=[{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}],Jr=(e=Ns)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let i=r;i<=o;i++)t.push(`${i}${n}`);return t};var bs=["BOARD","TICKET","SWIMLANE"],z=e=>{let{currentNode:t,readOnly:n,selectedNode:r}=h(),o=Bt().isSetup,i=t.context,a=r?.context,d=[g.SYNC,g.HELP,g.SET_VIEW,g.SET_EDITOR,g.SET_USERNAME],l=[g.NEW,g.RENAME,g.DELETE],u=[g.TAG,g.ASSIGN,g.CLOSE_ISSUE,g.RE_OPEN_ISSUE,g.SET_DESCRIPTION],p=[g.FILTER,g.PEEK],y={WORKSPACE:[...d,...l],BOARD:[...p,...d,...l],SWIMLANE:[...p,...d,...l],TICKET:[...d,...l,...u],FIELD:[...d,...u],FIELD_LIST:[...d,...u],TEXT:[...d]},C=a&&bs.includes(a),b=[...y[i||"WORKSPACE"]].filter(A=>[g.RENAME,g.DELETE,g.MOVE].includes(A)?C:!0),I={[g.PEEK]:[...Jr(),"now","prev","next"],[g.SYNC]:[],[g.INIT]:[],[g.SET_USERNAME]:[],[g.SET_DESCRIPTION]:["confirm"],[g.DELETE]:["confirm"],[g.RE_OPEN_ISSUE]:["confirm"],[g.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[g.CLOSE_ISSUE]:["confirm"],[g.FILTER]:["tag","assignee","description","title","clear"],[g.SET_VIEW]:["dense","wide"],[g.SET_EDITOR]:[...jr,"vim"],[g.TAG]:[...new Set([...Object.keys(Qe),...N.getExistingTags()])],[g.ASSIGN]:N.getExistingAssignees(),[g.HELP]:[],[g.RENAME]:[],[g.NEW]:i==="TICKET"||i==="FIELD"||i==="FIELD_LIST"?["issue","swimlane","board"]:i==="SWIMLANE"?["issue","swimlane","board"]:i==="BOARD"?["issue","swimlane","board"]:["board"],[g.NONE]:b};return o?qr()?n&&(I={[g.NONE]:[g.HELP,g.PEEK],[g.HELP]:I[g.HELP],[g.PEEK]:I[g.PEEK]}):I={[g.NONE]:[g.HELP,g.INIT],[g.HELP]:I[g.HELP],[g.INIT]:I[g.INIT]}:I={[g.NONE]:[g.HELP,g.SET_EDITOR,g.SET_USERNAME],[g.HELP]:I[g.HELP],[g.SET_EDITOR]:I[g.SET_EDITOR],[g.SET_USERNAME]:I[g.SET_USERNAME]},I[e]??[]};import _t from"chalk";import{decodeTime as Xr}from"ulid";var Qr=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let i=Math.floor(t/o);if(i>=1)return`${i}${r} ago`}return"just now"},Zr=e=>{let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},Wt=e=>{try{return m("Decoded date",new Date(Xr(e)))}catch(t){return s("Decoding failed + "+t.message)}},On=e=>{if(!e?.id)return null;try{return Xr(e.id)}catch{return null}};var be=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?m("Found node",n):s("Unable to find node in breadcrumb")};import Ze from"chalk";var Un={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Is=(e,t,n)=>Math.max(t,Math.min(n,e)),Bn=(e,t,n)=>e+(t-e)*n,eo=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Ss=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,a=e/60,d=i*(1-Math.abs(a%2-1)),l=0,u=0,p=0;a>=0&&a<1?(l=i,u=d):a>=1&&a<2?(l=d,u=i):a>=2&&a<3?(u=i,p=d):a>=3&&a<4?(u=d,p=i):a>=4&&a<5?(l=d,p=i):(l=i,p=d);let y=o-i/2;return[Math.round((l+y)*255),Math.round((u+y)*255),Math.round((p+y)*255)]},As=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Ts=(e,t,n)=>[Math.round(Bn(e[0],t[0],n)),Math.round(Bn(e[1],t[1],n)),Math.round(Bn(e[2],t[2],n))],ft=e=>{let n=eo(e)%360,r=Ss(n,Un.stringColor.saturation,Un.stringColor.lightness);return As(r)},ws=e=>{let t=Un.gradient.stops,n=Is(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,i=Math.min(Math.floor(o),r-1),a=o-i;return Ts(t[i],t[i+1],a)},Ht=e=>eo(e.toLowerCase().trim())/4294967295,to=e=>{let t=Ht(e);return ws(t)},Ms=e=>{let[t,n,r]=to(e);return{normal:o=>Ze.bgRgb(t,n,r).black(o),cursor:o=>Ze.bgRgb(t,n,r).white.bold(o)}},Wn=e=>{let[t,n,r]=to(e);return{fg:o=>Ze.rgb(t,n,r)(o),fgCursor:o=>Ze.rgb(t,n,r).inverse(o),bg:o=>Ze.bgRgb(t,n,r).black(o),bgCursor:o=>Ze.bgRgb(t,n,r).white.bold(o)}},Hn=e=>Ms(e).normal(` ${e} `),me=(e,t=Qe)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:ft(r)};var Rs=["BOARD","TICKET","SWIMLANE"],_n=()=>{let e=h().selectedNode;return e?.context?Rs.includes(e?.context)?V():j({message:"Command not available in this context",completionWordList:[]}):j({message:"Missing target context",completionWordList:[]})},de="<ENTER> to confirm",V=(e="",t=[])=>({message:e,validity:Ne.Valid,completionWordList:t}),j=({message:e,completionWordList:t})=>({validity:Ne.Invalid,message:e,completionWordList:t}),yt=e=>e.length===0,ke=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let l=[...t.filter(Boolean).filter(p=>p.startsWith(o.trim()))].sort((p,y)=>Ht(p)-Ht(y)).slice(0,r).map(Hn),u=l.length>i?l.join(" "):"";return u?`${e}${u}${n}`:""},$n=({modifier:e})=>{let t="confirm";return e===t?V(de):j({message:yt(e)?`if you are certain, enter ${Hn(t)}`:"",completionWordList:[t]})},Ls=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?V(de):j({message:yt(n)?t:"",completionWordList:[]}),Ps=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?j({message:n,completionWordList:[]}):V():j({message:yt(r)?t:"",completionWordList:[]}),Kn=({hint:e})=>({modifier:t,inputString:n})=>yt(t)&&yt(n)?j({message:e,completionWordList:[]}):V(de),Ds={[g.PEEK]:e=>{let t=e.modifier;if(t==="now")return V(de);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD",completionWordList:[]};if(t==="prev"||t==="next")return V(de);let r=Ut(t);if(!t||!r)return j(n);let o=be(h().breadCrumb,"BOARD");if(c(o))return j({message:"Command is not applicable in this context",completionWordList:[]});let i=Wt(o.data.id);return c(i)?j({message:"Unable to peek: board id is not a valid ULID",completionWordList:[]}):Yr({date:r,horizonDate:i.data})?V(de):j({message:_t.red(`nothing to peek before ${i.data.toISOString().slice(0,16).replace("T"," ")}`),completionWordList:[]})},[g.INIT]:()=>V(de),[g.FILTER]:e=>{if(e.modifier==="clear")return V();let t=a=>z(g.FILTER).includes(a);if(!e.modifier||!t(e.modifier??""))return j({message:ke({wordList:z(g.FILTER),inputString:e.inputString}),completionWordList:z(g.FILTER)});let r=Object.values(h().tags).map(a=>a.name),o=Object.values(h().contributors).map(a=>a.name),i=e.modifier==="tag"?r:e.modifier==="assignee"?o:[];return e.inputString?i.length&&!i.includes(e.inputString.trim()??"")?j({message:ke({prefix:`existing ${e.modifier}s... `,wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i}):V():j({message:ke({prefix:"one of... ",wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i})},[g.NONE]:e=>e.command?V():j({message:ke({prefix:"commands... ",wordList:z(g.NONE),inputString:e.inputString,minLengthForHints:0}),completionWordList:[]}),[g.NEW]:e=>Ps({list:z(g.NEW),hint:ke({wordList:z(g.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[g.SET_DESCRIPTION]:()=>V(de),[g.HELP]:()=>V(de),[g.RENAME]:()=>{let e=_n();return e.validity==="invalid"?e:V(de)},[g.DELETE]:e=>{let t=_n();return t.validity==="invalid"?t:$n(e)},[g.CLOSE_ISSUE]:e=>$n(e),[g.RE_OPEN_ISSUE]:e=>$n(e),[g.MOVE]:e=>{let t=_n();return t.validity==="invalid"?t:Kn({hint:ke({prefix:"hey hacker! These commands are blocked for you... ",wordList:z(g.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[g.TAG]:e=>{let t=N.getExistingTags().map(n=>` ${_t.bgHex(me(n))(" "+n+" ")} `).slice(0,10);return Kn({hint:"tag name like... "+t.join("")})(e)},[g.ASSIGN]:e=>{let t=N.getExistingAssignees().map(n=>` ${_t.bgHex(me(n))(" "+n+" ")} `).slice(0,10);return Kn({hint:"assign to... "+t.join("")})(e)},[g.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=z(g.SET_EDITOR);return e.modifier?V(de):j({message:ke({wordList:t,inputString:e.inputString}),completionWordList:[]})},[g.SET_USERNAME]:e=>e.inputString?V():j({message:`Enter a username. Saved in ${_t.bgBlack("~/.epiq/")}`,completionWordList:[]}),[g.SET_VIEW]:e=>Ls({list:z(g.SET_VIEW),hint:ke({wordList:z(g.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[g.SYNC]:()=>V(de)},no=Object.fromEntries(Object.entries(Ds).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var ro=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"];var L={Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",SetView:"set-view",SetEditor:"set-editor",SetUserName:"set-user-name",NewItem:"add-new-item",TagTicket:"ticket-tag",AssignUserToTicket:"ticket-assign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Sync:"sync"};var oo=e=>Object.values(g).includes(e),io=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:d,completionWordList:l}=no[n].validate(n,r,i),u=o==="command"?Object.values(g):n&&e.target==="modifier"?z(n):ro;return{validity:d,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?Vr(e,[...l,...u]):{hint:"",hints:[],remainder:"",overlap:0}}};var so=e=>{let t=e.trimStart(),n=ks(t),r=(n[0]??"").trimStart().trimEnd(),o=(n[1]??"").trimStart().trimEnd(),i=Os(e),a=oo(r)?r:null,d=a!==null,l=r!=="",u=e.endsWith(" "),p=a?z(a)??[]:[],y=a&&p.includes(o)?o:"",C="word";n.length<=1?C="command":n.length===2&&(C="modifier");let b=Fs(t,a,y);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:l,command:a,isCommandKeyword:d,isLastWordCompleted:u,modifier:y,target:C,inputToMatch:i,inputString:b}},Fs=(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},ks=e=>e?e.split(/\s+/):[],Os=e=>e.trimEnd().split(/\s+/).at(-1)??"";var ao=" ",Y={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Ne.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Vn=new Set,co=()=>{for(let e of Vn)e()},lo=e=>(Vn.add(e),()=>Vn.delete(e)),Ie=e=>{let n=e(Y),r=so(n.value),o=n.cursorPosition===n.value.length;Y={...n,commandMeta:io(r,o)},co()},xt=({message:e,result:t})=>{let n=structuredClone(Y);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Y=n,co(),m(e,null)},jn=e=>{Ie(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},zn=e=>{Ie(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&n[o-1]===" ";)o--;for(;o>0&&n[o-1]!==" ";)o--}else{for(;o<n.length&&n[o]!==" ";)o++;for(;o<n.length&&n[o]===" ";)o++}return{...t,cursorPosition:o}})},mo=()=>{Ie(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},uo=()=>{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}})},$=e=>{Ie(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),i=e(r,t.commandMeta.autoCompletion),a=i+o,d=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:d,commandIsPending:!1}})},po=()=>{Ie(e=>({...e,commandIsPending:!0}))},go=({addToHistory:e=!0})=>{Ie(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),Bs()},fo=()=>{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}})},yo=()=>{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}})},Bs=()=>$(()=>""),ge=()=>Y,$t=()=>{let[e,...t]=Y.value.split(ao);return t.join(ao).trim()};var Us=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Ws=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",Hs=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",xo=(e,t)=>{if(Ws(e,e.sequence))return x.MoveCursorLeftOfWord;if(Hs(e,e.sequence))return x.MoveCursorRightOfWord;if(Us(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.GetLastCommandFromHistory;case"down":return x.GetNextCommandFromHistory;case"left":return x.MoveCursorLeft;case"right":return x.MoveCursorRight;case"return":return x.Confirm;case"backspace":return t?x.EraseInput:x.ExitCommandLine;case"escape":return x.ExitCommandLine;default:return x.CaptureInput}};var x={Sync:"sync",NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function _s(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function $s(e,t,n){let r=h().currentNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function vo(e,t){let n=ge();if(e.sequence===":"&&n.value==="")return x.InitCommandLine;if(t===f.MOVE)switch(e.name){case"m":case"return":return x.ConfirmMove}if(t===f.COMMAND_LINE)return xo(e,n.value);let r=_s(e);if(r){let o=t===f.MOVE?{prevItem:x.MovePreviousItem,nextItem:x.MoveNextItem,prevContainer:x.MoveToPreviousContainer,nextContainer:x.MoveToNextContainer}:{prevItem:x.NavPreviousItem,nextItem:x.NavNextItem,prevContainer:x.NavToPreviousContainer,nextContainer:x.NavToNextContainer};return $s(h().currentNode.childRenderAxis,r,o)}if(e.ctrl&&e.name==="c")return x.Exit;switch(e.name){case"e":return x.Edit;case"n":return x.AddItem;case"m":return x.InitMove;case"d":return x.Delete;case"return":return x.Confirm;case"space":return x.Confirm;case"v":return h().viewMode==="wide"?x.SetViewDense:x.SetViewWide;case"q":case"escape":return x.Exit;case"s":return x.Sync;default:return null}}var ho=e=>{let{context:t}=h()?.currentNode;if(!t)return L.None;switch(e){case g.INIT:return L.Init;case g.DELETE:return L.Delete;case g.SET_DESCRIPTION:return L.Edit;case g.HELP:return L.ViewHelp;case g.RE_OPEN_ISSUE:return L.ReopenIssue;case g.CLOSE_ISSUE:return L.CloseIssue;case g.TAG:return L.TagTicket;case g.ASSIGN:return L.AssignUserToTicket;case g.RENAME:return L.Rename;case g.NEW:return L.NewItem;case g.FILTER:return L.Filter;case g.MOVE:return L.Move;case g.PEEK:return L.Peek;case g.SET_USERNAME:return L.SetUserName;case g.SET_EDITOR:return L.SetEditor;case g.SET_VIEW:return L.SetView;case g.SYNC:return L.Sync;default:return L.None}};import{ulid as K}from"ulid";import{spawnSync as Js}from"node:child_process";import Xs from"node:os";import bo from"node:path";import{ulid as Qs}from"ulid";import{accessSync as Ks,copyFileSync as Vs,existsSync as Kt,mkdirSync as Eo,readdirSync as Co,readFileSync as js,renameSync as zs,rmSync as Gs,statSync as No,unlinkSync as qs,writeFileSync as Ys}from"node:fs";import et from"node:path";var ce={writeToFile:(e,t)=>{try{let n=et.dirname(e);Kt(n)||Eo(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Ys(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return js(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=ce.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 Kt(e)&&No(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Ks(e),!0}catch{return!1}},mkDir:e=>Eo(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=et.parse(t);for(;;){let r=et.join(t,e);try{if(Kt(r)&&No(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=et.dirname(t)}return null},readFirstJSON(e){try{if(!ce.dirExists(e))return null;let t=Co(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=et.join(e,t);return ce.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return ce.dirExists(e)?Co(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{qs(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(et.dirname(t)),!n?.overwrite&&Kt(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{zs(e,t)}catch(r){if(r?.code==="EXDEV"){Vs(e,t),this.rmFile(e);return}throw r}}};function Zs(){let{preferredEditor:e}=pe(),t=[e,process.env.VISUAL,process.env.EDITOR,"vim","vi","nano"].filter(n=>!!n?.trim());return[...new Set(t)]}function ea(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function Io(e){let t=bo.join(Xs.tmpdir(),"epiq");ce.mkDir(t);let n=bo.join(t,Qs());ce.writeToFile(n,e??"");let r=Zs();for(let o of r){let i=ea(o,n),a=Js(i,{stdio:"inherit",shell:!0});if(!a.error&&a.status===0){let d=ce.readFile(n);if(d==null)return s("Unable to read edited file");let l=d.replace(/\r?\n$/,"");return m("Successfully edited",l)}}return s("Unable to open editor")}import{monotonicFactory as ta,ulid as Vt}from"ulid";var jt=ta(),So=({name:e,parent:t,user:{userId:n,userName:r}})=>{let o=jt(),i=jt(),a=jt(),d=jt();return[{id:Vt(),userId:n,userName:r,action:"add.issue",payload:{id:o,parent:t,name:e}},{id:Vt(),userId:n,userName:r,action:"add.field",payload:{id:i,parent:o,name:"Description",val:""}},{id:Vt(),userId:n,userName:r,action:"add.field",payload:{id:a,parent:o,name:"Assignees"}},{id:Vt(),userId:n,userName:r,action:"add.field",payload:{id:d,parent:o,name:"Tags"}}]};import Jt from"node:fs";import Xt from"node:path";import{z as Yn}from"zod";var zt=process.env.IS_LOCAL==="true",xe=()=>".epiq";import Gt from"node:fs";import Ve from"node:path";import{decodeTime as na,monotonicFactory as ra}from"ulid";import{z as vt}from"zod";var Ao=e=>({action:e.action,payload:e.payload});var wo=1,To=ra(),oa="events",ia=vt.tuple([vt.string().min(1),vt.string().min(1).nullable()]),sa=vt.looseObject({v:vt.literal(wo),id:ia}),Gn=e=>{let t=sa.safeParse(e);return t.success?m("Parsed persisted event",t.data):s(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},qt=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",te=()=>{let{userName:e,userId:t}=pe();return e?t?e.trim()?m("Successfully resolved actor ID",{userId:qt(t),userName:qt(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},aa=e=>Gt.existsSync(Ve.join(e,xe()))&&Gt.statSync(Ve.join(e,xe())).isDirectory(),tt=(e=process.cwd())=>{let t=Ve.resolve(e);for(;;){if(aa(t))return t;let n=Ve.dirname(t);if(n===t)return Ve.resolve(e);t=n}},Mo=(e=process.cwd())=>Ve.join(tt(e),xe(),oa),qn=({userId:e,userName:t})=>`${qt(e)}.${qt(t)}.jsonl`,da=(e=process.cwd(),{userId:t,userName:n})=>{let r=qn({userId:t,userName:n});return/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r)?m("Successfully resolved event log path",Ve.join(Mo(e),r)):s(`Invalid event log file name: ${r}`)},ca=(e,t)=>{let n={[e.action]:e.payload,v:wo,id:t};return Gn(n)};function Yt({event:e,rootDir:t=process.cwd()}){try{let n=tt(t),r=Mo(n),o=da(n,{userId:e.userId,userName:e.userName});if(c(o))return o;Gt.mkdirSync(r,{recursive:!0});let i=Ro(n);if(c(i))return s(i.message);let a;if(i.data){let l=na(i.data),u=Math.max(Date.now(),l+1);a=To(u)}else a=To();let d=ca(Ao(e),[a,i.data]);return c(d)?s(d.message):(Gt.appendFileSync(o.data,`${JSON.stringify(d.data)}
3
+ `,"utf8"),m("Event persisted",{path:o.data,entry:d.data}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return s(`Failed to persist event: ${r}`)}}import{decodeTime as la}from"ulid";var ma=xe(),ua="events",pa=Yn.object({userId:Yn.string().min(1).default("unknown"),userName:Yn.string().min(1).default("unknown")}),ga=(e=process.cwd())=>Xt.join(tt(e),ma,ua),fa=e=>{let[t,n]=Xt.basename(e,".jsonl").split("."),r=pa.safeParse({userId:t,userName:n});return r.success?m("Parsed event file actor",r.data):s(`Invalid event file name ${Xt.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},ya=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?s(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?s("Invalid persisted event: action key is missing or invalid"):m("Resolved persisted action",t[0])},xa=(e,t)=>t in e,va=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),ha=e=>{let{userId:t,userName:n,...r}=e,o=ya(r);if(c(o))return s(o.message);let i=o.data,a=e.id?.[0];return a?xa(r,i)?m("Decoded persisted event",va({id:a,action:i,payload:r[i],userId:t,userName:n})):s(`Persisted event is missing payload for action: ${i}`):s("Persisted event is missing id")},Qt=e=>{if(!Jt.existsSync(e))return m("Event file missing",[]);let t=fa(e);if(c(t))return s(t.message);let n=Jt.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
4
+ `)){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{return s(`Failed to parse event JSON from ${e}: ${i}`)}let d=Gn(a);if(c(d))return s(`${d.message} in ${e}: ${i}`);r.push({...d.data,userId:t.data.userId,userName:t.data.userName})}return m("Parsed persisted events file",r)};function Lo(e=process.cwd()){let t=ga(e);if(!Jt.existsSync(t))return s("No events found");let n=Jt.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Xt.join(t,o)),r=[];for(let o of n){let i=Qt(o);if(c(i))return s(i.message);r.push(...i.data)}return m("All events loaded",Ea(r))}function ht(e=process.cwd()){let t=Lo(e);if(c(t))return s(t.message);let n=[];for(let r of t.data){let o=ha(r);if(c(o))return s(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);n.push(o.data)}return m("Loaded merged events",n)}function Ro(e=process.cwd()){let t=Lo(e);return c(t)?s(t.message):m("Loaded edge reference",t.data.at(-1)?.id?.[0]??null)}var Ea=e=>{let t=new Map(e.map(d=>[d.id[0],d])),n=new Map;for(let d of e){let l=d.id[1],u=n.get(l)??[];u.push(d),n.set(l,u)}for(let d of n.values())d.sort((l,u)=>{let[p]=l.id,[y]=u.id;return p.localeCompare(y)});let r=[],o=new Set,i=d=>{let l=n.get(d)??[];for(let u of l){let[p]=u.id;o.has(p)||(o.add(p),r.push(u),i(p))}};i(null);let a=[...e].filter(d=>{let[l]=d.id;return!o.has(l)}).sort((d,l)=>{let[u,p]=d.id,[y,C]=l.id,b=p===null||t.has(p),I=C===null||t.has(C);if(b&&!I)return-1;if(!b&&I)return 1;let A=(p??"").localeCompare(C??"");return A!==0?A:u.localeCompare(y)});return[...r,...a]},Po=(e,t)=>{let n=e.findIndex(r=>{try{return la(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var Do=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 Ca=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[nt,Zt]=Ca;var D=(e,t)=>s(`${t.split(".").join(" ")+" failed, "+e.toLowerCase()}`),Na={"init.workspace":({action:e,payload:t})=>{let{id:n,name:r}=t,o=ee.workspace(n,r);Jn(o);let i=N.createNodeAtPosition(o);return c(i)?D(i.message??"Failed to initialize workspace",e):m("Workspace initialized",{action:e,result:i.data})},"add.workspace":({action:e,payload:t})=>{let{id:n,name:r}=t,o=ee.workspace(n,r),i=N.createNodeAtPosition(o);return c(i)?D(i.message??"Failed to add workspace",e):m("Added workspace",{action:e,result:i.data})},"add.board":({action:e,payload:t})=>{let{id:n,name:r,parent:o}=t,i=N.createNodeAtPosition(ee.board(n,r,o));return c(i)?D(i.message??"Unable to create board",e):m("Added board",{action:e,result:i.data})},"add.swimlane":({action:e,payload:t})=>{let{id:n,name:r,parent:o}=t,i=N.createNodeAtPosition(ee.swimlane(n,r,o));return c(i)?D(i.message??"Unable to create swimlane",e):m("Added swimlane",{action:e,result:i.data})},"add.issue":({action:e,payload:t})=>{let{id:n,name:r,parent:o}=t,i=N.createNodeAtPosition(ee.ticket(n,r,o));return c(i)?D(i.message??"Unable to create issue",e):m("Added issue",{action:e,result:i.data})},"add.field":({action:e,payload:t})=>{let{id:n,name:r,parent:o,val:i}=t,a=N.createNodeAtPosition(ee.field(n,r,o,{value:i},r.includes("Description")?"vertical":"horizontal"));return c(a)?D(a.message??`Unable to create field: ${r}`,e):m("Added field",{action:e,result:a.data})},"edit.title":({action:e,payload:t})=>{let{id:n,name:r}=t;if(!N.getNode(n))return D("Unable to locate node",e);let i=N.renameNode(n,r);return c(i)?D(i.message??"Unable to edit title",e):m("Edited title",{action:e,result:i.data})},"delete.node":({action:e,payload:t})=>{let{id:n}=t,r=N.tombstoneNode(n);return c(r)?D(r.message??"Unable to delete node",e):m("Deleted node",{action:e,result:r.data})},"create.tag":({action:e,payload:t})=>{let{id:n,name:r}=t,o=N.createTag({id:n,name:r});return c(o)?D(o.message??"Unable to create tag",e):m("Tag added",{action:e,result:o.data})},"create.contributor":({action:e,payload:t})=>{let{id:n,name:r}=t,o=N.createContributor({id:n,name:r});return c(o)?D(o.message??"Unable to create contributor",e):m("Contributor created",{action:e,result:o.data})},"tag.issue":({action:e,payload:t})=>{let{id:n,target:r,tagId:o}=t,i=N.tag(r,o,n);return c(i)?D(i.message??"Unable to tag issue",e):m("Issue tagged",{action:e,result:i.data})},"assign.issue":({action:e,payload:t})=>{let{id:n,contributor:r,target:o}=t,i=N.assign(o,r,n);return c(i)?D(i.message??"Unable to assign issue",e):m("Assigned successfully",{action:e,result:i.data})},"move.node":({action:e,payload:t})=>{let{id:n,parent:r,pos:o}=t,i=N.moveNode({id:n,parentId:r,position:o});return c(i)?D(i.message??"Failed to move node",e):m("Moved node",{action:e,result:i.data})},"edit.description":({action:e,payload:t})=>{let{id:n,md:r}=t,o=N.editValue(n,r);return c(o)?D(o.message??"Unable to edit description",e):m("Set node value",{action:e,result:o.data})},"close.issue":({action:e,payload:t})=>{let{id:n}=t,r=N.getNode(n);if(!r)return D("Unable to locate issue",e);if(!$e(r))return D("Can only close issues",e);let o=N.getNode(nt);if(!o)return D("Unable to locate target swimlane",e);if(o.id===r.parentNodeId)return D("Cannot close closed issue",e);let a=N.moveNode({id:n,parentId:o.id});return c(a)?D(a.message??"Unable to close issue",e):m("Issue closed",{action:e,result:a.data})},"reopen.issue":({action:e,payload:t})=>{let{id:n}=t,r=N.getNode(n);if(!r)return D("Unable to locate issue",e);if(!$e(r))return D("Can only reopen issues",e);let o=N.getNode(nt);if(!o)return D("Unable to locate closed swimlane",e);if(!(r.parentNodeId===o.id))return D("Issue is not closed",e);let a=Do(r);if(!a)return D("Unable to resolve previous parent from issue history",e);if(a===o.id)return D("Previous parent resolves to closed swimlane",e);if(!N.getNode(a))return D("Previous parent no longer exists",e);let l=N.moveNode({id:n,parentId:a});return c(l)?D(l.message??"Unable to reopen issue",e):m("Issue reopened",{action:e,result:l.data})},"lock.node":({action:e,payload:t})=>{let{id:n}=t,r=N.lockNode(n);return c(r)?D(r.message??"Unable to lock node",e):m("Node locked",{action:e,result:r.data})}},ba=(e,t)=>{let n=N.getNode(e);n&&N.updateNode({...n,log:[...n.log??[],t]})},Ia=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=h().nodes[e.payload.id]?.parentNodeId;return n&&t.push(n),t;case"tag.issue":case"assign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function rt(e,t=!1){let n=Na[e.action](e);if(c(n))return n;t||([...new Set(Ia(e))].forEach(a=>ba(a,e)),ae(a=>({...a,eventLog:[...a.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?D("Invalid user ID format",e.action):(N.createContributor({name:o,id:r}),n)}var je=e=>e.map(t=>rt(t));function ne(e){let t=rt(e);if(t.result!==ye.Success)return t;let n=Yt({event:e});return c(n)?n:t}function Fo(e){return e.map(t=>ne(t))}import It from"node:fs";import{spawn as Ta}from"node:child_process";import Qn from"node:fs";import ot from"node:path";var Et=(e,t)=>{let n=new Map,r=t??((...i)=>JSON.stringify(i)),o=((...i)=>{let a=r(...i);if(!n.has(a)){let d=e(...i).then(l=>(c(l)&&n.delete(a),l));n.set(a,d)}return n.get(a)});return o.clear=()=>n.clear(),o};import Ct from"fs";import Oo from"path";import Sa from"util";var ko=1e3,Bo=(e=process.cwd())=>Oo.join(tt(e),xe(),"log","epiq.log");function Aa(e=process.cwd()){if(!zt)return;let t=Bo(e);if(!Ct.existsSync(t))return;let r=Ct.readFileSync(t,"utf8").split(`
5
+ `);if(r[r.length-1]===""&&r.pop(),r.length<=ko)return;let o=r.slice(-ko).join(`
7
6
  `)+`
8
- `;vt.writeFileSync(t,o,"utf8")}function zr(e,t,r=!1,n=process.cwd()){if(!$t)return;let o=Do(n),i=aa.format(...t),a=new Date,m=`[${r?a.toISOString().slice(11,19):a.toISOString()}] ${e} ${i}
9
- `;vt.mkdirSync(Po.dirname(o),{recursive:!0}),vt.appendFileSync(o,m,"utf8"),da(n)}var A={info(...e){zr("[Info]",e,!1)},debug(...e){zr("->",e,!0)},error(...e){zr("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=A;var Fo=15e3,la={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Bo=({args:e,cwd:t,allowFail:r})=>new Promise(n=>{if(!qr.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(r){n({stdout:"",stderr:p,exitCode:1});return}n(s(p));return}let o=ca("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:la}),i=!1,a="",l="",m=p=>{i||(i=!0,clearTimeout(u),n(p))},u=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${Fo}ms`].join(`
10
- `);m(r?{stdout:a,stderr:p,exitCode:124}:s(p))},Fo);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{a+=p}),o.stderr.on("data",p=>{l+=p}),o.on("error",p=>{if(r){m({stdout:a,stderr:p.message,exitCode:1});return}m(s([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
11
- `)))}),o.on("close",p=>{let y=p??1;if(r){m({stdout:a,stderr:l,exitCode:y});return}if(y!==0){m(s([`git ${e.join(" ")}`,l.trim()||a.trim()||"Git command failed"].filter(Boolean).join(`
12
- `)));return}m(c("Git command succeeded",{stdout:a,stderr:l,exitCode:y}))})}),D=({args:e,cwd:t})=>Bo({args:e,cwd:t,allowFail:!1}),_e=({args:e,cwd:t})=>Bo({args:e,cwd:t,allowFail:!0}),Gr=xt(async(e=process.cwd())=>{let t=await D({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?s("Not inside a Git repository"):c("Resolved repo root",t.data.stdout.trim())},e=>ot.resolve(e)),ma=xt(async e=>{let t=await D({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return s(t.message);let r=t.data.stdout.trim(),n=ot.isAbsolute(r)?r:ot.join(e,r);return c("Resolved git dir",n)},e=>ot.resolve(e)),Jr=async({cwd:e,message:t})=>{let r=await D({args:["commit","-m",t],cwd:e});if(d(r))return s(`Failed to create commit
13
- ${r.message}`);let n=await D({args:["rev-parse","HEAD"],cwd:e});return d(n)?s(`Commit created, but failed to read HEAD SHA
14
- ${n.message}`):c("Created commit and resolved SHA",n.data.stdout.trim())},ht=async e=>{let t=await ma(e);if(d(t))return s(t.message);let r=t.data,o=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","REBASE_HEAD","rebase-merge","rebase-apply"].filter(i=>qr.existsSync(ot.join(r,i)));return c("Checked for in-progress Git operation",o.length>0)},Xt=async({repoRoot:e,remote:t})=>{let r=await _e({args:["remote","get-url",t],cwd:e});return c("Checked remote",r.exitCode===0)},Yt=async({repoRoot:e,remote:t,branch:r})=>{let n=await _e({args:["ls-remote","--heads",t,r],cwd:e});return n.exitCode!==0?s(n.stderr.trim()||`Unable to inspect remote branch ${t}/${r}`):c("Checked remote branch",n.stdout.trim().length>0)},Oo=async({repoRoot:e,branch:t})=>{let r=await _e({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return r.exitCode===0?c("Local branch exists",!0):r.exitCode===1?c("Local branch missing",!1):s(r.stderr.trim()||`Unable to inspect branch ${t}`)},ko=e=>{try{return qr.realpathSync.native(e)}catch{return ot.resolve(e)}},Uo=async({repoRoot:e,worktreeRoot:t})=>{let r=await D({args:["worktree","list","--porcelain"],cwd:e});if(d(r))return s(r.message);let n=ko(t),o=r.data.stdout.split(`
15
- `).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(ko).includes(n);return c("Checked worktree registration",o)},Xr=async e=>{let t=await _e({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Qt=async e=>{let t=await D({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?s(t.message):c("Resolved current branch",t.data.stdout.trim())},Wo=async e=>{let t=await D({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?s(t.message):c("Resolved short HEAD sha",t.data.stdout.trim())},Ho=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Zt=async({cwd:e,remote:t,branch:r})=>{let n=await Yt({repoRoot:e,remote:t,branch:r});if(d(n))return s(n.message);if(!n.data)return c("Remote branch missing, skipped pull",!1);A.debug("[git] fetch start",{cwd:e,remote:t,branch:r});let o=await D({args:["fetch",t,r],cwd:e});if(A.debug("[git] fetch done",o),d(o))return s(`Failed to fetch ${r}
16
- ${o.message}`);A.debug("[git] pull start",{cwd:e,remote:t,branch:r});let i=await D({args:["pull","--rebase",t,r],cwd:e});return A.debug("[git] pull done",i),d(i)?s(`Failed during pull --rebase
17
- ${i.message}`):c("Pulled with rebase",!0)},$o=async e=>{let t=await D({args:["status","--porcelain"],cwd:e});return d(t)?s(t.message):c("Checked remote worktree changes",t.data.stdout.trim().length>0)},_o=async e=>{let t=await Qt(e);return d(t)?s(t.message):c("Checked detached HEAD state",t.data==="HEAD")};import{createHash as xa}from"node:crypto";import ge from"node:fs";import va from"node:os";import G from"node:path";import er from"node:fs";import ua from"node:path";import{decodeTime as pa}from"ulid";var Yr=e=>{let[t,r]=e.id;return`${t}:${r??""}`},Ko=e=>{let[t]=e.id;return pa(t)},ga=e=>{let{userId:t,userName:r,...n}=e;return n},fa=e=>e.length===0?"":e.map(t=>JSON.stringify(ga(t))).join(`
7
+ `;Ct.writeFileSync(t,o,"utf8")}function Xn(e,t,n=!1,r=process.cwd()){if(!zt)return;let o=Bo(r),i=Sa.format(...t),a=new Date,l=`[${n?a.toISOString().slice(11,19):a.toISOString()}] ${e} ${i}
8
+ `;Ct.mkdirSync(Oo.dirname(o),{recursive:!0}),Ct.appendFileSync(o,l,"utf8"),Aa(r)}var T={info(...e){Xn("[Info]",e,!1)},debug(...e){Xn("->",e,!0)},error(...e){Xn("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=T;var Uo=15e3,wa={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Ho=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Qn.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:p,exitCode:1});return}r(s(p));return}let o=Ta("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:wa}),i=!1,a="",d="",l=p=>{i||(i=!0,clearTimeout(u),r(p))},u=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${Uo}ms`].join(`
9
+ `);l(n?{stdout:a,stderr:p,exitCode:124}:s(p))},Uo);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{a+=p}),o.stderr.on("data",p=>{d+=p}),o.on("error",p=>{if(n){l({stdout:a,stderr:p.message,exitCode:1});return}l(s([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
10
+ `)))}),o.on("close",p=>{let y=p??1;if(n){l({stdout:a,stderr:d,exitCode:y});return}if(y!==0){l(s([`git ${e.join(" ")}`,d.trim()||a.trim()||"Git command failed"].filter(Boolean).join(`
11
+ `)));return}l(m("Git command succeeded",{stdout:a,stderr:d,exitCode:y}))})}),F=({args:e,cwd:t})=>Ho({args:e,cwd:t,allowFail:!1}),ze=({args:e,cwd:t})=>Ho({args:e,cwd:t,allowFail:!0}),Zn=Et(async(e=process.cwd())=>{let t=await F({args:["rev-parse","--show-toplevel"],cwd:e});return c(t)?s("Not inside a Git repository"):m("Resolved repo root",t.data.stdout.trim())},e=>ot.resolve(e)),Ma=Et(async e=>{let t=await F({args:["rev-parse","--git-dir"],cwd:e});if(c(t))return s(t.message);let n=t.data.stdout.trim(),r=ot.isAbsolute(n)?n:ot.join(e,n);return m("Resolved git dir",r)},e=>ot.resolve(e)),er=async({cwd:e,message:t})=>{let n=await F({args:["commit","-m",t],cwd:e});if(c(n))return s(`Failed to create commit
12
+ ${n.message}`);let r=await F({args:["rev-parse","HEAD"],cwd:e});return c(r)?s(`Commit created, but failed to read HEAD SHA
13
+ ${r.message}`):m("Created commit and resolved SHA",r.data.stdout.trim())},Nt=async e=>{let t=await Ma(e);if(c(t))return s(t.message);let n=t.data,o=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","REBASE_HEAD","rebase-merge","rebase-apply"].filter(i=>Qn.existsSync(ot.join(n,i)));return m("Checked for in-progress Git operation",o.length>0)},en=async({repoRoot:e,remote:t})=>{let n=await ze({args:["remote","get-url",t],cwd:e});return m("Checked remote",n.exitCode===0)},tn=async({repoRoot:e,remote:t,branch:n})=>{let r=await ze({args:["ls-remote","--heads",t,n],cwd:e});return r.exitCode!==0?s(r.stderr.trim()||`Unable to inspect remote branch ${t}/${n}`):m("Checked remote branch",r.stdout.trim().length>0)},_o=async({repoRoot:e,branch:t})=>{let n=await ze({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?m("Local branch exists",!0):n.exitCode===1?m("Local branch missing",!1):s(n.stderr.trim()||`Unable to inspect branch ${t}`)},Wo=e=>{try{return Qn.realpathSync.native(e)}catch{return ot.resolve(e)}},$o=async({repoRoot:e,worktreeRoot:t})=>{let n=await F({args:["worktree","list","--porcelain"],cwd:e});if(c(n))return s(n.message);let r=Wo(t),o=n.data.stdout.split(`
14
+ `).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(Wo).includes(r);return m("Checked worktree registration",o)},tr=async e=>{let t=await ze({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return m("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},nn=async e=>{let t=await F({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return c(t)?s(t.message):m("Resolved current branch",t.data.stdout.trim())},Ko=async e=>{let t=await F({args:["rev-parse","--short","HEAD"],cwd:e});return c(t)?s(t.message):m("Resolved short HEAD sha",t.data.stdout.trim())},Vo=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),rn=async({cwd:e,remote:t,branch:n})=>{let r=await tn({repoRoot:e,remote:t,branch:n});if(c(r))return s(r.message);if(!r.data)return m("Remote branch missing, skipped pull",!1);T.debug("[git] fetch start",{cwd:e,remote:t,branch:n});let o=await F({args:["fetch",t,n],cwd:e});if(T.debug("[git] fetch done",o),c(o))return s(`Failed to fetch ${n}
15
+ ${o.message}`);T.debug("[git] pull start",{cwd:e,remote:t,branch:n});let i=await F({args:["pull","--rebase",t,n],cwd:e});return T.debug("[git] pull done",i),c(i)?s(`Failed during pull --rebase
16
+ ${i.message}`):m("Pulled with rebase",!0)},jo=async e=>{let t=await F({args:["status","--porcelain"],cwd:e});return c(t)?s(t.message):m("Checked remote worktree changes",t.data.stdout.trim().length>0)},zo=async e=>{let t=await nn(e);return c(t)?s(t.message):m("Checked detached HEAD state",t.data==="HEAD")};import{createHash as ka}from"node:crypto";import ve from"node:fs";import Oa from"node:os";import X from"node:path";import on from"node:fs";import Ra from"node:path";import{decodeTime as La}from"ulid";var nr=e=>{let[t,n]=e.id;return`${t}:${n??""}`},Go=e=>{let[t]=e.id;return La(t)},Pa=e=>{let{userId:t,userName:n,...r}=e;return r},Da=e=>e.length===0?"":e.map(t=>JSON.stringify(Pa(t))).join(`
18
17
  `)+`
19
- `,ya=(e,t)=>{let r=new Map;for(let n of[...t,...e])r.set(Yr(n),n);return[...r.values()].sort((n,o)=>{let i=Ko(n)-Ko(o);return i!==0?i:Yr(n).localeCompare(Yr(o))})},tr=({sourceFile:e,targetFile:t})=>{let r=Vt(e);if(d(r))return s(r.message);let n=Vt(t);if(d(n))return s(n.message);let o=ya(n.data,r.data),i=fa(o);return(er.existsSync(t)?er.readFileSync(t,"utf8"):"")===i?c("Event file already merged",!1):(er.mkdirSync(ua.dirname(t),{recursive:!0}),er.writeFileSync(t,i,"utf8"),c("Merged event file",!0))};var F="epiq/events",q="origin",Qr=pe(),jo="events",ha="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Ca=e=>G.join(Qr,jo,e),Na=e=>xa("sha1").update(G.resolve(e)).digest("hex").slice(0,12),zo=()=>G.join(va.homedir(),".epiq"),qo=()=>G.join(zo(),"worktrees"),Zr=e=>G.join(qo(),Na(e)),Ea=e=>G.join(e,Qr),it=e=>G.join(Ea(e),jo),Ke=({root:e,fileName:t})=>G.join(it(e),t),rr=e=>(A.debug("[sync] ensure dir",e),ge.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)),ba=()=>{A.debug("[sync] ensure epiq storage");let e=rr(zo());if(d(e))return s(e.message);let t=rr(qo());return d(t)?s(t.message):c("Ensured epiq storage",void 0)},Ia=e=>{ge.existsSync(e)&&(A.debug("[sync] remove path",e),ge.rmSync(e,{recursive:!0,force:!0}))},Sa=e=>{let t=it(e);if(!ge.existsSync(t))return A.debug("[sync] events dir missing",t),c("Events dir missing",[]);let r=ge.readdirSync(t,{withFileTypes:!0}).filter(n=>n.isFile()).map(n=>n.name).filter(n=>n.endsWith(".jsonl")).sort();return A.debug("[sync] listed event files",{eventsDir:t,count:r.length}),c("Listed event files",r)},Aa=async e=>{A.debug("[sync] inspect local HEAD",e);let t=await _e({args:["rev-parse","--verify","HEAD"],cwd:e});return t.exitCode===0?c("Repo has HEAD",!0):t.exitCode===1?c("Repo has no HEAD",!1):s(t.stderr.trim()||"Unable to inspect HEAD")},wa=xt(async e=>{A.debug("[sync] inspect remote history",{repoRoot:e,remote:q});let t=await Xt({repoRoot:e,remote:q});if(d(t))return s(t.message);if(!t.data)return c("No remote configured",!1);let r=await _e({args:["ls-remote","--heads",q],cwd:e});if(r.exitCode!==0)return s(r.stderr.trim()||"Unable to inspect remote heads");let n=r.stdout.trim().length>0;return A.debug("[sync] remote history",n),c("Checked remote history",n)},e=>G.resolve(e)),en=async e=>{A.debug("[sync] ensure initial commit");let t=await Aa(e);if(d(t))return s(t.message);if(t.data)return A.debug("[sync] local HEAD exists"),c("Repo already initialized",!1);let r=await wa(e);if(d(r))return s(r.message);if(r.data)return A.debug("[sync] skip local init commit due to remote history"),c("Skipped local init commit because remote history exists",!1);A.debug("[sync] create empty init commit");let n=await D({args:["commit","--allow-empty","-m","[epiq:init]"],cwd:e});return d(n)?s(`Failed to create initial commit
20
- ${n.message}`):c("Created initial commit",!0)},tn=({repoRoot:e,worktreeRoot:t})=>{let r=Sa(t);if(d(r))return s(r.message);let n=it(t),o=it(e),i=!1;for(let a of r.data){let l=G.join(n,a),m=G.join(o,a);A.debug("[sync] hydrate event file",{from:l,to:m});let u=tr({sourceFile:l,targetFile:m});if(d(u))return s(u.message);i=i||u.data}return A.debug("[sync] hydrate changed",i),c("Hydrated event files from remote worktree",i)},Vo=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Ta=async e=>{let t=await Qt(e);if(d(t))return s(t.message);let r=await Wo(e);if(d(r))return s(r.message);let n=`[epiq:sync:${Vo(t.data)}:${Vo(r.data)}]`;return A.debug("[sync] commit message",n),c("Built sync commit message",n)},Ma=async e=>{A.debug("[sync] create empty storage branch",F);let t=await D({args:["commit-tree",ha,"-m","[epiq:init-storage-branch]"],cwd:e});if(d(t))return s(`Failed to create storage branch commit
21
- ${t.message}`);let r=t.data.stdout.trim(),n=await D({args:["update-ref",`refs/heads/${F}`,r],cwd:e});return d(n)?s(`Failed to create ${F}
22
- ${n.message}`):c("Created empty storage branch",!0)},Ra=async({repoRoot:e})=>{A.debug("[sync] ensure local remote branch",F);let t=await Oo({repoRoot:e,branch:F});if(d(t))return s(t.message);if(t.data)return A.debug("[sync] local remote branch exists"),c("Local remote branch already exists",!1);let r=await Xt({repoRoot:e,remote:q});if(d(r))return s(r.message);if(r.data){let n=await Yt({repoRoot:e,remote:q,branch:F});if(d(n))return s(n.message);if(n.data){A.debug("[sync] fetch remote branch before local track");let o=await D({args:["fetch",q,F],cwd:e});if(d(o))return s(`Failed to fetch ${F} from remote
23
- ${o.message}`);A.debug("[sync] create local tracking branch",F);let i=await D({args:["branch","--track",F,`${q}/${F}`],cwd:e});return d(i)?s(`Failed to create local ${F} from remote
24
- ${i.message}`):c("Created local remote branch from remote",!0)}}return Ma(e)},La=async({repoRoot:e,branch:t})=>{let r=await D({args:["worktree","list","--porcelain"],cwd:e});if(d(r))return s(r.message);let n=r.data.stdout.split(`
25
- `),o=null;for(let i of n){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return c("Found worktree for branch",o)}return c("No worktree found for branch",null)},Pa=async({repoRoot:e,worktreeRoot:t})=>{A.debug("[sync] create remote worktree",t);let r=rr(G.dirname(t));if(d(r))return s(r.message);ge.existsSync(t)&&!ge.existsSync(G.join(t,".git"))&&(A.debug("[sync] remove broken remote worktree path",t),Ia(t));let n=await D({args:["worktree","add",t,F],cwd:e});return d(n)?s(`Failed to create remote worktree
26
- ${n.message}`):c("Created remote worktree",!0)},Da=async({repoRoot:e,worktreeRoot:t})=>{A.debug("[sync] ensure remote worktree",t);let r=await La({repoRoot:e,branch:F});if(d(r))return s(r.message);let n=r.data,o=G.resolve(t),i=n?G.resolve(n):null;if(i&&i===o&&ge.existsSync(i))return A.debug("[sync] reuse existing remote branch worktree",{expected:o,actual:i}),c("Remote branch already checked out in expected worktree",!1);if(i&&i!==o){A.debug("[sync] remove old remote branch worktree",{expected:o,actual:i});let m=await D({args:["worktree","remove","--force",i],cwd:e});if(d(m))return s(`Failed to remove existing remote worktree
27
- ${m.message}`)}if(i&&!ge.existsSync(i)){A.debug("[sync] prune stale branch worktree registration",{existingBranchWorktree:i});let m=await D({args:["worktree","prune"],cwd:e});if(d(m))return s(`Failed to prune stale worktrees
28
- ${m.message}`)}let a=await Uo({repoRoot:e,worktreeRoot:t});if(d(a))return s(a.message);let l=ge.existsSync(t);if(a.data&&l)return A.debug("[sync] remote worktree exists"),c("Remote worktree already exists",!1);if(a.data&&!l){A.debug("[sync] prune stale remote worktree registration");let m=await D({args:["worktree","prune"],cwd:e});if(d(m))return s(`Failed to prune stale worktrees
29
- ${m.message}`)}return Pa({repoRoot:e,worktreeRoot:t})},Fa=async e=>{let t=await Qt(e);if(d(t))return s(t.message);if(t.data===F)return A.debug("[sync] remote branch already checked out"),c("Remote branch already checked out",!1);A.debug("[sync] checkout remote branch",F);let r=await D({args:["checkout",F],cwd:e});return d(r)?s(`Failed to checkout ${F}
30
- ${r.message}`):c("Checked out remote branch",!0)},ka=async e=>{let t=await D({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return s(t.message);let n=t.data.stdout.trim().split(`
31
- `).filter(Boolean).filter(a=>a!==Qr);if(n.length===0)return c("Remote branch is storage-only",!1);A.debug("[sync] remove app files from storage branch",n);let o=await D({args:["rm","-r","--ignore-unmatch","--",...n],cwd:e});if(d(o))return s(`Failed to clean storage branch
32
- ${o.message}`);let i=await Jr({cwd:e,message:"[epiq:repair-storage-branch]"});return d(i)?s(i.message):c("Cleaned storage branch",!0)},Ba=async e=>{A.debug("[sync] ensure remote upstream",F);let t=await Xr(e);if(d(t))return s(t.message);if(t.data)return A.debug("[sync] remote upstream already configured"),c("Remote upstream already configured",!1);let r=await Xt({repoRoot:e,remote:q});if(d(r))return s(r.message);if(!r.data)return A.debug("[sync] no remote configured for upstream"),c("No remote available for upstream",!1);let n=await Yt({repoRoot:e,remote:q,branch:F});if(d(n))return s(n.message);if(!n.data)return A.debug("[sync] remote branch missing; upstream will be configured on first push"),c("Deferred upstream until first push",!1);A.debug("[sync] fetch remote branch before upstream set");let o=await D({args:["fetch",q,F],cwd:e});if(d(o))return s(`Failed to fetch ${F}
33
- ${o.message}`);A.debug("[sync] set upstream to remote branch");let i=await D({args:["branch","--set-upstream-to",`${q}/${F}`,F],cwd:e});return d(i)?s(`Failed to set remote upstream
34
- ${i.message}`):c("Configured remote upstream",!0)},Go=async({worktreeRoot:e,ownEventFileName:t})=>{A.debug("[sync] stage own event file in remote worktree",t);let r=await D({args:["add",Ca(t)],cwd:e});return d(r)?s(`Failed to stage remote own event file
35
- ${r.message}`):c("Staged remote own event file",void 0)},Jo=async({repoRoot:e,worktreeRoot:t})=>{let r=await Ta(e);return d(r)?s(r.message):(A.debug("[sync] create remote sync commit"),Jr({cwd:t,message:r.data}))},rn=async e=>{A.debug("[sync] push remote worktree");let t=await Xr(e);if(d(t))return s(t.message);let r=await D({args:t.data?["push"]:["push","-u",q,F],cwd:e});return A.debug("[sync] push result",r),d(r)?s(`Failed during remote push
36
- ${r.message}`):c("Pushed remote",!0)},nn=async({repoRoot:e,worktreeRoot:t,ensureUpstream:r})=>{A.debug("[sync] bootstrap remote storage",{repoRoot:e,worktreeRoot:t,ensureUpstream:r});let n=!1,o=[ba(),await Ra({repoRoot:e}),await Da({repoRoot:e,worktreeRoot:t}),await Fa(t),await ka(t),r?await Ba(t):c("Skipped remote upstream bootstrap",!1)];for(let i of o){if(d(i))return s(i.message);n=n||!!i.data}return A.debug("[sync] bootstrap changed",n),c(r?"Bootstrapped remote storage":"Bootstrapped remote storage (readonly)",n)},on=(e,t)=>{for(let r of[it(e),it(t)]){let n=rr(r);if(d(n))return s(n.message)}return c("Ensured remote layout",void 0)};var Qo=async(e=process.cwd())=>{logger.debug("[sync] start readonly sync",{cwd:e});let t=await Gr(e);if(d(t))return s(t.message);let r=t.data,n=Zr(r);logger.debug("[sync] resolved readonly roots",{repoRoot:r,worktreeRoot:n});let o=await ht(r);if(d(o))return s(o.message);if(o.data)return s("Cannot sync while a git operation is in progress in the current repo");let i=await en(r);if(d(i))return s(i.message);logger.debug("[sync] readonly ensure initial commit changed",i.data);let a=await nn({repoRoot:r,worktreeRoot:n,ensureUpstream:!1});if(d(a))return s(a.message);let l=await ht(n);if(d(l))return s(l.message);if(l.data)return s("Cannot sync while a git operation is in progress in the remote worktree");let m=on(r,n);if(d(m))return s(m.message);logger.debug("[sync] readonly pull remote branch");let u=await Zt({cwd:n,remote:q,branch:F});if(d(u))return s(u.message);logger.debug("[sync] readonly pulled remote",u.data);let p=tn({repoRoot:r,worktreeRoot:n});return d(p)?s(p.message):(logger.debug("[sync] readonly hydrated from remote",p.data),c("Synced from remote",{repoRoot:r,worktreeRoot:n}))},Oa=({repoRoot:e,worktreeRoot:t,ownEventFileName:r})=>{let n=Ke({root:e,fileName:r}),o=Ke({root:t,fileName:r});return Ct.existsSync(n)?(logger.debug("[sync] merge own event file to remote",{ownEventFileName:r,localFile:n,remoteFile:o}),tr({sourceFile:n,targetFile:o})):(logger.debug("[sync] local own event file missing",n),c("Local own event file missing, nothing to merge",!1))},Xo=async({repoRoot:e,worktreeRoot:t,ownEventFileName:r})=>{let n=Oa({repoRoot:e,worktreeRoot:t,ownEventFileName:r});if(d(n))return s(n.message);let o=await $o(t);if(d(o))return s(o.message);if(!n.data&&!o.data)return c("Own event file already up to date in remote worktree",{createdCommit:!1});let i=await Go({worktreeRoot:t,ownEventFileName:r});if(d(i))return s(i.message);let a=await Jo({repoRoot:e,worktreeRoot:t});return d(a)?s(a.message):c("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:a.data})},Yo=({repoRoot:e,worktreeRoot:t,ownEventFileName:r})=>{let n=Ke({root:e,fileName:r}),o=Ke({root:t,fileName:r});logger.debug("[sync] own event file sizes",{local:Ct.existsSync(n)?Ct.statSync(n).size:0,remote:Ct.existsSync(o)?Ct.statSync(o).size:0})},Zo=async({cwd:e=process.cwd(),ownEventFileName:t})=>{logger.debug("[sync] start write sync",{cwd:e,ownEventFileName:t});let r=await Gr(e);if(d(r))return s(r.message);let n=r.data,o=Zr(n);logger.debug("[sync] resolved roots",{repoRoot:n,worktreeRoot:o});let i=await _o(n);if(d(i))return s(i.message);if(i.data)return s("Cannot run :sync while the repository is in detached HEAD state");if(t.includes("/")||t.includes("\\"))return s("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return s("Own event file must end with .jsonl");let a=await ht(n);if(d(a))return s(a.message);if(a.data)return s("Cannot run :sync while a merge, rebase, cherry-pick, or revert is in progress in the current repo");let l=await en(n);if(d(l))return s(l.message);logger.debug("[sync] ensure initial commit changed",l.data);let m=await nn({repoRoot:n,worktreeRoot:o,ensureUpstream:!0});if(d(m))return s(m.message);let u=await ht(o);if(d(u))return s(u.message);if(u.data)return s("Cannot run :sync while a merge, rebase, cherry-pick, or revert is in progress in the remote worktree");let p=on(n,o);if(d(p))return s(p.message);let y=!1,v,I=!1,S=!1,N=!1;logger.debug("[sync] pull remote branch before local copy");let b=await Zt({cwd:o,remote:q,branch:F});if(d(b))return s(b.message);I=b.data,logger.debug("[sync] pulled remote",I);let T=tn({repoRoot:n,worktreeRoot:o});if(d(T))return s(T.message);N=T.data,logger.debug("[sync] hydrated from remote",N);let B=await Xo({repoRoot:n,worktreeRoot:o,ownEventFileName:t});if(d(B))return s(B.message);if(y=B.data.createdCommit,v=B.data.commitSha,Yo({repoRoot:n,worktreeRoot:o,ownEventFileName:t}),logger.debug("[sync] sync own file result",B.data),y||m.data){let V=await rn(o),te=V;if(d(V)&&Ho(V.message)){let wt=await Zt({cwd:o,remote:q,branch:F});if(d(wt))return s(wt.message);let Re=await Xo({repoRoot:n,worktreeRoot:o,ownEventFileName:t});if(d(Re))return s(Re.message);Re.data.createdCommit&&(y=!0,v=Re.data.commitSha),Yo({repoRoot:n,worktreeRoot:o,ownEventFileName:t}),logger.debug("[sync] retry sync own file result",Re.data),te=await rn(o)}if(d(te))return s(te.message);S=te.data,logger.debug("[sync] pushed remote",S)}else logger.debug("[sync] no commit created, skipped push");if(y){let V=await D({args:["rev-parse","HEAD"],cwd:o});if(d(V))return s(V.message);v=V.data.stdout.trim()}return c("Synced event logs with remote",{repoRoot:n,worktreeRoot:o,createdCommit:y,commitSha:v,pulled:I,pushed:S,hydrated:N,bootstrapped:m.data})};var Ua=e=>Object.values(C().tags).find(t=>t.name===e),Wa=e=>Object.values(C().contributors).find(t=>t.name===e),ei=[{systemOnly:!0,intent:R.Move,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{userId:t,userName:r}=e.data,{modifier:n}=ue().commandMeta,o=()=>{let u=Pe();if(!u)return s("No pending move state");let p=u.payload.id;if(!C().nodes[p])return s("Moved node not found");let v=u.payload.parent,I=C().nodes[v];if(!I)return s("Move parent not found");let S=M(v).findIndex(N=>N.id===p);return S===-1?s("Moved node not found among rendered children"):(O.navigate({currentNode:I,selectedIndex:S}),c("Synchronized navigation to moved node",null))},i=u=>{if(d(u))return s(u.message);let p=o();return d(p)?s(p.message):c("Updated move preview",null)},{currentNode:a,selectedIndex:l}=C(),m=M(a.id)[l];if(!m)return w({mode:g.DEFAULT}),s("No move target");if(n==="start"){if(m.readonly)return s("Target node is read-only");if(l===-1)return s("No item selected");if(!m.parentNodeId)return s("Target has no parent");let u=M(m.parentNodeId),p=u.findIndex(({id:N})=>N===m.id);if(p===-1)return s("Target not found among siblings");let y=u[p-1],v=u[p+1],I=v!=null?{at:"before",sibling:v.id}:y!=null?{at:"after",sibling:y.id}:{at:"start"};rt({id:$(),userId:t,userName:r,action:"move.node",payload:{id:m.id,parent:m.parentNodeId,pos:I}}),w({mode:g.MOVE});let S=o();return d(S)?s(S.message):c("Move initialized",null)}if(n==="next")return w({mode:g.MOVE}),i(_r(1));if(n==="previous")return w({mode:g.MOVE}),i(_r(-1));if(n==="to-next")return w({mode:g.MOVE}),i($r(1));if(n==="to-previous")return w({mode:g.MOVE}),i($r(-1));if(n==="confirm"){w({mode:g.DEFAULT});let u=Pe();if(!u)return s("No pending move to confirm");let p=Z(u);if(d(p))return p;let y=o();return d(y)?s(y.message):(rt(null),c("Moved item",null))}return n==="cancel"?(rt(null),w({mode:g.DEFAULT}),c("Cancelling move",null)):s("Invalid move modifier")}},{intent:R.Delete,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{userId:t,userName:r}=e.data,{currentNode:n,selectedIndex:o}=C(),i=M(n.id)[o];return i?Z({id:$(),userId:t,userName:r,action:"delete.node",payload:{id:i.id}}):s("Unable to resolve child to delete")},onSuccess:()=>w({mode:g.DEFAULT})},{intent:R.Edit,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{userId:t,userName:r}=e.data,n=nt(C().breadCrumb,"TICKET");if(d(n))return s("Edit target must be an issue");let o=n.data;if(o.readonly)return s("Cannot edit readonly field");let{currentNode:i,selectedIndex:a}=C();if(!M(o.id)[a])return s("No selected field");let m=M(i.id)[a];if(!m)return s("No selected field");if(m.readonly)return s("Cannot edit readonly field");let u=m.props.value;if(typeof u!="string")return s("Selected field is not editable text");let p=mo(u);if(d(p))return s("Failed to edit field");let y=p.data;return y===u?c("No changes made",null):m.title==="Description"?Z({id:$(),userId:t,userName:r,action:"edit.description",payload:{id:m.id,md:y}}):m.title==="Title"?Z({id:$(),userId:t,userName:r,action:"edit.title",payload:{id:m.id,name:y}}):s(`Editing not supported for "${m.title}"`)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:R.Filter,mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ue().commandMeta,r=/(!=|=)/,[n,o]=e.split(r);if(!n||!(l=>K(f.FILTER).map(m=>m.split(r)[0]).includes(l))(n))return s("Invalid filter modifier");let a={target:n,operator:"=",value:t.trim()};return de(l=>({...l,filters:e==="clear"?[]:[...l.filters,a],mode:g.DEFAULT})),c("Viewing help",null)}},{intent:R.ViewHelp,mode:g.COMMAND_LINE,action:()=>(w({mode:g.HELP}),c("Viewing help",null))},{intent:R.CloseIssue,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{userId:t,userName:r}=e.data,{currentNode:n,selectedIndex:o}=C(),i=M(n.id)[o];if(!i)return s("Unable to close issue, no target found");if(!i.parentNodeId)return s("No target parent found");if(!We(i))return s("Cannot close in this context");let a=Z({id:$(),userId:t,userName:r,action:"close.issue",payload:{id:i.id,parent:i.parentNodeId}});return d(a)?a:c("Viewing help",null)}},{intent:R.ReopenIssue,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{userId:t,userName:r}=e.data,{currentNode:n,selectedIndex:o}=C(),i=M(n.id)[o];if(!i)return s("Unable to reopen issue, no target found");let a=i.context==="TICKET"?c("Resolved ticket",i):Ge(i.id,"TICKET");if(d(a))return s("Cannot reopen in this context");let l=a.data,m=Z({id:$(),userId:t,userName:r,action:"reopen.issue",payload:{id:l.id}});return d(m)?m:c("Issue reopened",null)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:R.SetUserName,mode:g.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:r}=ce(),n=Bt()?.trim();if(!n)return s("No username provided");let o=n??r,i=e??$();if(!o||!i)return s("Unable to resolve user name or id");let a=jr({userName:o,userId:i,preferredEditor:t??""});return d(a)?a:(ut({userName:o,userId:i}),w({mode:g.DEFAULT}),c(`Username set to "${n}"`,null))}},{intent:R.Init,mode:g.COMMAND_LINE,action:()=>{let e=an();if(d(e))return e;let{rootNodeId:t,nodes:r}=C();return O.navigate({currentNode:r[t],selectedIndex:0}),c("Project initialized",null)}},{intent:R.SetEditor,mode:g.COMMAND_LINE,action:()=>{let e=Bt()?.trim();if(!e)return s("No editor provided");let t=jr({preferredEditor:e});return d(t)?t:(ut({preferredEditor:e}),w({mode:g.DEFAULT}),c(`Editor configuration set to "${e}"`,null))}},{intent:R.NewItem,mode:g.COMMAND_LINE,action:(e,t)=>{let r=Q();if(d(r))return s("Unable to resolve user ID");let{userId:n,userName:o}=r.data;if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:i,currentNode:a,selectedIndex:l}=C(),m=u=>{let p=Z(u);if(d(p))return p;let y=E.getNode(p.data.result.id);if(!y)return s("Created node not found");if(!y.parentNodeId)return p;let v=E.getNode(y.parentNodeId);return v?(O.navigate({currentNode:v,selectedIndex:E.getSiblings(y.parentNodeId).findIndex(({id:I})=>I===y.id)}),p):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:u}=C(),p=E.getNode(u);return p?m({id:$(),userId:n,userName:o,action:"add.board",payload:{id:$(),name:t.inputString,parent:p.id}}):s("Workspace not found")}if(t.modifier==="swimlane"){let u=nt(i,"BOARD");return d(u)?s("Unable to add swimlane in this context"):m({id:$(),userId:n,userName:o,action:"add.swimlane",payload:{id:$(),name:t.inputString,parent:u.data.id}})}if(t.modifier==="issue"){let u=M(a.id)[l],p=a.context==="SWIMLANE"?a:a.context==="BOARD"&&u?.context==="SWIMLANE"?u:(()=>{let N=nt(i,"SWIMLANE");return d(N)?null:N.data})();if(!p)return s("Unable to add issue in this context");let y=uo({userId:n,userName:o,name:t.inputString,parent:p.id}),v=Gt(y);if(v.some(N=>d(N)))return s("Issue create failed: "+v.filter(d).map(N=>N.message).filter(Boolean).join(", "));let I=v[0];if(!I||d(I))return s("Issue creation failed");let S=y[0]?.payload.id;return S?(O.navigate({currentNode:p,selectedIndex:E.getSiblings(p.id).findIndex(({id:N})=>N===S)}),c("Issue created",null)):s("Unable to determine ticket id")}return Rn()},onSuccess:()=>w({mode:g.DEFAULT})},{intent:R.SetView,mode:g.COMMAND_LINE,action:()=>{let{commandMeta:e}=ue();return e.validity===ve.Invalid?s("Invalid command "+he):(de(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),c("View set",null))},onSuccess:()=>w({mode:g.DEFAULT})},{intent:R.Rename,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{userId:t,userName:r}=e.data,{currentNode:n,selectedIndex:o}=C(),i=M(n.id)[o];if(!i)return s("Missing node");if(i.readonly)return s("Cannot rename readonly node");let a=Bt();return a?Z({id:$(),userId:t,userName:r,action:"edit.title",payload:{id:i.id,name:a}}):s("Provide a new name")},onSuccess:()=>w({mode:g.DEFAULT})},{intent:R.TagTicket,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{userId:t,userName:r}=e.data,{modifier:n,inputString:o}=ue().commandMeta,i=(n||o).trim();if(!i)return s("Provide a tag");let{selectedIndex:a,currentNode:l}=C(),m=M(l.id)[a];if(!m)return s("Invalid tag target");let u=Ge(m.id,"TICKET");if(d(u))return s("Unable to tag issue in this context");let p=u.data,y=Ua(i),v;if(y)v=y.id;else{let N=$(),b=Z({id:$(),userId:t,userName:r,action:"create.tag",payload:{id:N,name:i}});if(d(b))return b;v=b.data.result.id}let I=E.getFieldByTitle(p.id,"Tags");return I?M(I.id).some(N=>N.props?.value===v)?s("Already tagged with that tag"):Z({id:$(),userId:t,userName:r,action:"tag.issue",payload:{id:$(),target:p.id,tagId:v}}):s("Unable to locate tags field")},onSuccess:()=>w({mode:g.DEFAULT})},{intent:R.AssignUserToTicket,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{userId:t,userName:r}=e.data,{modifier:n,inputString:o}=ue().commandMeta,i=(n||o).trim();if(!i)return s("Provide an assignee");let{selectedIndex:a,currentNode:l}=C(),m=M(l.id)[a];if(!m)return s("Invalid assign target");let u=Ge(m.id,"TICKET");if(d(u))return s("Unable to assign issue in this context");let p=u.data,y=Wa(i),v;if(y)v=y.id;else{let N=$(),b=Z({id:$(),userId:t,userName:r,action:"create.contributor",payload:{id:N,name:i}});if(d(b))return b;v=b.data.result.id}let I=E.getFieldByTitle(p.id,"Assignees");return I?M(I.id).some(N=>N.props?.value===v)?s("Assignee already assigned"):Z({id:$(),userId:t,userName:r,action:"assign.issue",payload:{id:$(),target:p.id,contributor:v}}):s("Unable to locate assignees field")},onSuccess:()=>w({mode:g.DEFAULT})},{intent:R.Sync,mode:g.COMMAND_LINE,action:async()=>{H(()=>""),w({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:e,userName:t}=ce();if(!e)return s("Unable to resolve userId");if(!t)return s("Unable to resolve userName");let r=He()?an():c("No pending default events",null);if(d(r))return s(`Unable to persist default events. ${r.message}`);let n=qt();if(d(n))return s("Unable to resolve log file name");logger.debug("[sync-command] pending defaults",He());let o=qt();logger.debug("[sync-command] persist file name",o);let i=d(o)?null:Ke({root:process.cwd(),fileName:o.data});logger.debug("[sync-command] local event file before sync",{localFile:i,exists:i?sn.existsSync(i):!1,size:i&&sn.existsSync(i)?sn.statSync(i).size:0});let a=await Zo({ownEventFileName:n.data});if(d(a))return w({syncStatus:{msg:a.message,status:"outOfSync"}}),s(`Unable to sync state. ${a.message}`);w({syncStatus:{msg:"Synced",status:"synced"},mode:g.DEFAULT});let l=jt();return d(l)?s("Unable to load events"):(ft(l.data),c("Synced",!0))}}];var ie=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:r,modifier:n,inputString:o}}=ue();if(!t)return s("No command to confirm");if(!e&&r===ve.Invalid)return s("Invalid command");let i=io(t);Zn();let a=ei.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===i);if(!a)return kt({result:he.Fail,message:"Command not found",data:null});let l=await a.action(a,{command:t,inputString:o,modifier:n});return d(l)?kt(l):(eo({addToHistory:!e}),a.onSuccess?.(),kt(l))};var nr=[{intent:"exit",mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(w({mode:g.COMMAND_LINE}),H(()=>"move cancel"),ie({isForceExecutedBySystem:!0}))},{intent:"initMove",mode:g.DEFAULT,description:"[m] move init/confirm",action:()=>(w({mode:g.COMMAND_LINE}),H(()=>"move start"),ie({isForceExecutedBySystem:!0}))},{intent:"confirmMove",mode:g.MOVE,action:()=>(w({mode:g.COMMAND_LINE}),H(()=>"move confirm"),ie({isForceExecutedBySystem:!0}))}],or=[{intent:"movePreviousItem",mode:g.MOVE,action:()=>Pe()?(w({mode:g.COMMAND_LINE}),H(()=>"move previous"),ie({isForceExecutedBySystem:!0})):s("No pending move")},{intent:"moveNextItem",mode:g.MOVE,action:()=>Pe()?(w({mode:g.COMMAND_LINE}),H(()=>"move next"),ie({isForceExecutedBySystem:!0})):s("No pending move")}],ti=[{intent:"moveToNextContainer",mode:g.MOVE,action:()=>Pe()?(w({mode:g.COMMAND_LINE}),H(()=>"move to-next"),ie({isForceExecutedBySystem:!0})):s("No pending move")},{intent:"moveToPreviousContainer",mode:g.MOVE,action:()=>Pe()?(w({mode:g.COMMAND_LINE}),H(()=>"move to-previous"),ie({isForceExecutedBySystem:!0})):s("No pending move")}];var ri={[L.WORKSPACE]:[...nr,...or],[L.BOARD]:[...nr,...or],[L.SWIMLANE]:[...nr,...or,...ti],[L.TICKET]:[],[L.FIELD]:[],[L.FIELD_LIST]:[],[L.TEXT]:[]};var ni=[{intent:"addItem",mode:g.DEFAULT,description:"[n] new...",action:()=>(w({mode:g.COMMAND_LINE}),H(()=>`${f.NEW} `),c("Adding new item",null))},{intent:"Delete",mode:g.DEFAULT,description:"[d] delete",action:()=>(w({mode:g.COMMAND_LINE}),H(()=>`${f.DELETE} `),c("Deleting item",null))},{intent:"initCommandLine",mode:g.DEFAULT,description:"[:] focus command line",action:()=>(w({mode:g.COMMAND_LINE}),H(()=>""),c("Entering command line mode",null))},{intent:"confirm",mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(O.enterChildNode(),c("Entering context",null))},{intent:"exit",mode:g.DEFAULT,description:"[q] exit context",action:()=>(logger.debug("Executing exit action"),O.enterParentNode(),c("Exiting context",null))},{intent:"navPreviousItem",mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(O.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:"navNextItem",mode:g.DEFAULT,action:()=>(O.navigateToNextItem(),c("Navigating to next item",null))},{intent:"navToPreviousContainer",mode:g.DEFAULT,action:()=>(O.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:"navToNextContainer",mode:g.DEFAULT,action:()=>(O.navigateToNextContainer(),c("Navigating to next container",null))},{intent:"edit",mode:g.DEFAULT,action:()=>(w({mode:g.COMMAND_LINE}),H(()=>"edit"),ie(),c("Fired command",!0))},{intent:"SetViewDense",mode:g.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(w({viewMode:"dense"}),c("View set",null))},{intent:"SetViewWide",mode:g.DEFAULT,action:()=>(w({viewMode:"wide"}),c("View set",null))},{intent:"sync",mode:g.DEFAULT,description:"[s] sync epiq with remote state branch",action:()=>(w({mode:g.COMMAND_LINE}),H(()=>"sync"),ie({isForceExecutedBySystem:!0}),c("Synced",!0))}];var oi=[{intent:"viewHelp",mode:g.DEFAULT,action:()=>(w({mode:g.HELP}),c("Viewing help",null))},{intent:"exit",mode:g.HELP,action:()=>(w({mode:g.DEFAULT}),c("Exiting help",null))},{intent:"confirm",mode:g.COMMAND_LINE,action:()=>(ie(),c("Executing command",null))},{intent:"MoveCursorLeft",mode:g.COMMAND_LINE,action:()=>(Br(-1),c("Moving cursor left",null))},{intent:"MoveCursorRight",mode:g.COMMAND_LINE,action:()=>(Br(1),c("Moving cursor right",null))},{intent:"MoveCursorLeftOfWord",mode:g.COMMAND_LINE,action:()=>(Or("left"),c("Moving cursor left of word",null))},{intent:"MoveCursorRightOfWord",mode:g.COMMAND_LINE,action:()=>(Or("right"),c("Moving cursor right of word",null))},{intent:"exitCommandLine",mode:g.COMMAND_LINE,action:()=>(w({mode:g.DEFAULT}),c("Exiting command line",null))},{intent:"autoCompleteCommand",mode:g.COMMAND_LINE,action:()=>(H((e,{remainder:t})=>t?e+t:e),c("Auto-completing command",null))},{intent:"captureInput",mode:g.COMMAND_LINE,action:(e,{sequence:t})=>(H(r=>r+t),c("Capturing input",null))},{intent:"eraseInput",mode:g.COMMAND_LINE,action:()=>(Yn(),c("Erasing input",null))},{intent:"EraseInputWord",mode:g.COMMAND_LINE,action:()=>(Qn(),c("Erasing input word",null))},{intent:"getLastCommandFromHistory",mode:g.COMMAND_LINE,action:()=>(to(),c("Getting last command from history",null))},{intent:"getNextCommandFromHistory",mode:g.COMMAND_LINE,action:()=>(ro(),c("Getting next command from history",null))}];import Ha from"chalk";var ir=": for command line",ii="q to exit",si=`${Ha.hex(h.accent)("m")} to confirm`,dn={[L.WORKSPACE]:[ir],[L.BOARD]:[ir],[L.BOARD+g.COMMAND_LINE]:[ir],[L.SWIMLANE]:[ir],[L.TICKET+g.HELP]:[ii],[L.SWIMLANE+g.HELP]:[ii],[L.TICKET]:[],[L.FIELD]:[],[L.SWIMLANE+g.MOVE]:[si],[L.TICKET+g.MOVE]:[si]};var sr=e=>e.trim().toLocaleLowerCase(),$a=(e,t)=>{let r=E.getFieldByTitle(e,t);if(!r)return"";let n=r.props?.value;return typeof n=="string"?n:""},_a=e=>{let{tags:t}=C(),r=E.getFieldByTitle(e,"Tags");return r?W(r.id).map(n=>{let o=n.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(n=>!!n):[]},Ka=e=>{let{contributors:t}=C(),r=E.getFieldByTitle(e,"Assignees");return r?W(r.id).map(n=>{let o=n.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(n=>!!n):[]},ai=(e,t)=>{let r=t.value;if(!r)return!0;switch(t.target){case"title":return sr(e.title??"").includes(r);case"description":return sr($a(e.id,"Description")).includes(r);case"tag":return _a(e.id).map(sr).some(l=>l.includes(r));case"assignee":return Ka(e.id).map(sr).some(l=>l.includes(r));default:return!0}};function di(e,t,r){let n=t[e];if(!n)return s("buildBreadCrumb(): current node not found");let o=[],i=n;for(;i&&(o.push(i),!(i.id===r||!i.parentNodeId));)i=t[i.parentNodeId];let a=o[o.length-1];return!a||a.id!==r?s("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var ci=e=>{let t={};for(let r of e)r.intent&&(t[r.mode]||(t[r.mode]={}),t[r.mode][r.intent]=r);return t};var ar,cn=new Set,li=()=>{for(let e of cn)e()},ja=e=>(cn.add(e),()=>cn.delete(e));function mi(e){let{currentNodeId:t,mode:r,rootNodeId:n,nodes:o,filters:i}=e;if(!t)return s("derive(): currentNodeId is missing");if(!n)return s("derive(): rootNode is missing");if(!o[n])return s("derive(): unable to find root node");let l=o[t];if(!l)return logger.error("Unable to derive state, currentNode not found"),s("Unable to derive state, currentNode not found");let m=di(t,o,n);if(d(m))return logger.error(m.message),m;let u=m.data,{context:p}=l,y=dn[p+r]??dn[p]??[],v=[...ni,...ri[p]??[],...oi],I=ci(v),S=za(o,i),N=S[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,currentNode:l,breadCrumb:u,availableHints:y,availableActions:v,actionIndex:I,selectedNode:N,renderedChildrenIndex:S})}var C=()=>(ar||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),ar);function go(e){let t={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:""}},r=mi(t);return d(r)?r:(ar=r.data,li(),c("State initialized",null))}function de(e){let t=C(),r=e(t),n=mi(r);return d(n)?s(n.message??"Unable to update state"):(ar=n.data,li(),c("State updated",null))}var w=e=>de(t=>({...t,...e}));var _=()=>Va(ja,C,C),za=(e,t)=>{let r={};for(let n of Object.values(e))We(n)&&t.length>0&&!t.every(o=>ai(n,o))||!n.parentNodeId||n.isDeleted||((!n.parentNodeId||!r[n.parentNodeId])&&(r[n.parentNodeId]=[]),r[n.parentNodeId].push(n));for(let n of Object.keys(r))r[n].sort((o,i)=>{let a=e[o.id],l=e[i.id];return!a||!l?0:a.rank.localeCompare(l.rank)});return r},M=e=>C().renderedChildrenIndex[e]??[];var O={exit(){process.exit(0)},enterChildNode(){let e=C(),t=e.currentNode,r=Math.max(0,e.selectedIndex),n=M(t.id)[r];!n||t.context==="FIELD"||O.navigate({currentNode:n,selectedIndex:M(n.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=C();if(!e.parentNodeId){logger.info("Missing parent node id");return}let r=t[e.parentNodeId];if(!r){logger.error("Parent not found");return}let n=M(r.id),o=n.findIndex(({id:a})=>a===e.id),i=n.length===0?-1:o>=0?o:0;O.navigate({currentNode:r,selectedIndex:i})},navigateToNextItem:()=>ui(1),navigateToPreviousItem:()=>ui(-1),navigateToNextContainer:()=>pi(1),navigateToPreviousContainer:()=>pi(-1),navigate:({currentNode:e=C().currentNode,selectedIndex:t})=>{w({currentNodeId:e.id,selectedIndex:t})}},ui=e=>{let t=C(),r=M(t.currentNode.id).length;if(r===0)return;let o=(Math.max(0,t.selectedIndex)+e+r)%r;O.navigate({selectedIndex:o})},pi=e=>{let{currentNode:t,nodes:r,selectedIndex:n}=C();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=r[t.parentNodeId];if(!t||!o)return;let i=M(o.id),a=i.findIndex(v=>v.id===t.id);if(a<0)return;let l=i.at(a+e)??i.at(0);if(!l)return;let m=M(l.id),u=Math.max(0,m.length-1),p=Math.min(Math.max(0,n),u),y=m.length?p:-1;O.navigate({currentNode:l,selectedIndex:y})};var be="system",Ie="ACTOR",Nt=qa(),De=null;function Ga(){let e=Object.values(C().nodes).find(n=>n.context==="WORKSPACE");if(!e)throw new Error("No workspace found in event log");let[t]=M(e.id),[r]=t?M(t.id):[];if(logger.debug("Boot navigation target:",{workspace:e?.id,firstBoard:t?.id,firstSwimlane:r?.id}),r){let n=C().renderedChildrenIndex?.[r.id]??[];return{currentNode:r,selectedIndex:n.length>0?0:-1}}else return t?{currentNode:t,selectedIndex:0}:e?{currentNode:e,selectedIndex:0}:{currentNode:C().nodes[C().rootNodeId],selectedIndex:0}}function Ja(){let e=Ga();O.navigate(e)}function Xa(){let e=Nt(),t=Nt(),r=Nt(),n=Nt(),o=Nt();return[{id:Ee(),userId:be,userName:Ie,action:"init.workspace",payload:{id:e,name:"Workspace"}},{id:Ee(),userId:be,userName:Ie,action:"add.board",payload:{id:t,name:"Default",parent:e}},{id:Ee(),userId:be,userName:Ie,action:"add.swimlane",payload:{id:r,name:"Todo",parent:t}},{id:Ee(),userId:be,userName:Ie,action:"add.swimlane",payload:{id:n,name:"Review",parent:t}},{id:Ee(),userId:be,userName:Ie,action:"add.swimlane",payload:{id:o,name:"Done",parent:t}},{id:Ee(),userId:be,userName:Ie,action:"add.board",payload:{id:Ht,name:"Closed",parent:e}},{id:Ee(),userId:be,userName:Ie,action:"add.swimlane",payload:{id:Qe,name:"Closed",parent:Ht}},{id:Ee(),userId:be,userName:Ie,action:"lock.node",payload:{id:Ht}},{id:Ee(),userId:be,userName:Ie,action:"lock.node",payload:{id:Qe}}]}function He(){return De!==null}function an(){if(!De||De.length===0)return c("No pending default events to persist",null);let t=Gt(De).filter(d);return t.length>0?s([st.bold.red("Materializing failed"),"",...t.map((r,n)=>`${st.dim.gray(`${n+1}.`)} ${st.dim(r.message)}`),`
18
+ `,Fa=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(nr(r),r);return[...n.values()].sort((r,o)=>{let i=Go(r)-Go(o);return i!==0?i:nr(r).localeCompare(nr(o))})},sn=({sourceFile:e,targetFile:t})=>{let n=Qt(e);if(c(n))return s(n.message);let r=Qt(t);if(c(r))return s(r.message);let o=Fa(r.data,n.data),i=Da(o);return(on.existsSync(t)?on.readFileSync(t,"utf8"):"")===i?m("Event file already merged",!1):(on.mkdirSync(Ra.dirname(t),{recursive:!0}),on.writeFileSync(t,i,"utf8"),m("Merged event file",!0))};var k="epiq/events",J="origin",rr=xe(),Yo="events",Ba="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Ua=e=>X.join(rr,Yo,e),Wa=e=>ka("sha1").update(X.resolve(e)).digest("hex").slice(0,12),Jo=()=>X.join(Oa.homedir(),".epiq"),Xo=()=>X.join(Jo(),"worktrees"),or=e=>X.join(Xo(),Wa(e)),Ha=e=>X.join(e,rr),it=e=>X.join(Ha(e),Yo),bt=({root:e,fileName:t})=>X.join(it(e),t),an=e=>(T.debug("[sync] ensure dir",e),ve.mkdirSync(e,{recursive:!0}),m("Ensured directory",void 0)),_a=()=>{T.debug("[sync] ensure epiq storage");let e=an(Jo());if(c(e))return s(e.message);let t=an(Xo());return c(t)?s(t.message):m("Ensured epiq storage",void 0)},$a=e=>{ve.existsSync(e)&&(T.debug("[sync] remove path",e),ve.rmSync(e,{recursive:!0,force:!0}))},Ka=e=>{let t=it(e);if(!ve.existsSync(t))return T.debug("[sync] events dir missing",t),m("Events dir missing",[]);let n=ve.readdirSync(t,{withFileTypes:!0}).filter(r=>r.isFile()).map(r=>r.name).filter(r=>r.endsWith(".jsonl")).sort();return T.debug("[sync] listed event files",{eventsDir:t,count:n.length}),m("Listed event files",n)},Va=async e=>{T.debug("[sync] inspect local HEAD",e);let t=await ze({args:["rev-parse","--verify","HEAD"],cwd:e});return t.exitCode===0?m("Repo has HEAD",!0):t.exitCode===1?m("Repo has no HEAD",!1):s(t.stderr.trim()||"Unable to inspect HEAD")},ja=Et(async e=>{T.debug("[sync] inspect remote history",{repoRoot:e,remote:J});let t=await en({repoRoot:e,remote:J});if(c(t))return s(t.message);if(!t.data)return m("No remote configured",!1);let n=await ze({args:["ls-remote","--heads",J],cwd:e});if(n.exitCode!==0)return s(n.stderr.trim()||"Unable to inspect remote heads");let r=n.stdout.trim().length>0;return T.debug("[sync] remote history",r),m("Checked remote history",r)},e=>X.resolve(e)),ir=async e=>{T.debug("[sync] ensure initial commit");let t=await Va(e);if(c(t))return s(t.message);if(t.data)return T.debug("[sync] local HEAD exists"),m("Repo already initialized",!1);let n=await ja(e);if(c(n))return s(n.message);if(n.data)return T.debug("[sync] skip local init commit due to remote history"),m("Skipped local init commit because remote history exists",!1);T.debug("[sync] create empty init commit");let r=await F({args:["commit","--allow-empty","-m","[epiq:init]"],cwd:e});return c(r)?s(`Failed to create initial commit
19
+ ${r.message}`):m("Created initial commit",!0)},sr=({repoRoot:e,worktreeRoot:t})=>{let n=Ka(t);if(c(n))return s(n.message);let r=it(t),o=it(e),i=!1;for(let a of n.data){let d=X.join(r,a),l=X.join(o,a);T.debug("[sync] hydrate event file",{from:d,to:l});let u=sn({sourceFile:d,targetFile:l});if(c(u))return s(u.message);i=i||u.data}return T.debug("[sync] hydrate changed",i),m("Hydrated event files from remote worktree",i)},qo=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",za=async e=>{let t=await nn(e);if(c(t))return s(t.message);let n=await Ko(e);if(c(n))return s(n.message);let r=`[epiq:sync:${qo(t.data)}:${qo(n.data)}]`;return T.debug("[sync] commit message",r),m("Built sync commit message",r)},Ga=async e=>{T.debug("[sync] create empty storage branch",k);let t=await F({args:["commit-tree",Ba,"-m","[epiq:init-storage-branch]"],cwd:e});if(c(t))return s(`Failed to create storage branch commit
20
+ ${t.message}`);let n=t.data.stdout.trim(),r=await F({args:["update-ref",`refs/heads/${k}`,n],cwd:e});return c(r)?s(`Failed to create ${k}
21
+ ${r.message}`):m("Created empty storage branch",!0)},qa=async({repoRoot:e})=>{T.debug("[sync] ensure local remote branch",k);let t=await _o({repoRoot:e,branch:k});if(c(t))return s(t.message);if(t.data)return T.debug("[sync] local remote branch exists"),m("Local remote branch already exists",!1);let n=await en({repoRoot:e,remote:J});if(c(n))return s(n.message);if(n.data){let r=await tn({repoRoot:e,remote:J,branch:k});if(c(r))return s(r.message);if(r.data){T.debug("[sync] fetch remote branch before local track");let o=await F({args:["fetch",J,k],cwd:e});if(c(o))return s(`Failed to fetch ${k} from remote
22
+ ${o.message}`);T.debug("[sync] create local tracking branch",k);let i=await F({args:["branch","--track",k,`${J}/${k}`],cwd:e});return c(i)?s(`Failed to create local ${k} from remote
23
+ ${i.message}`):m("Created local remote branch from remote",!0)}}return Ga(e)},Ya=async({repoRoot:e,branch:t})=>{let n=await F({args:["worktree","list","--porcelain"],cwd:e});if(c(n))return s(n.message);let r=n.data.stdout.split(`
24
+ `),o=null;for(let i of r){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return m("Found worktree for branch",o)}return m("No worktree found for branch",null)},Ja=async({repoRoot:e,worktreeRoot:t})=>{T.debug("[sync] create remote worktree",t);let n=an(X.dirname(t));if(c(n))return s(n.message);ve.existsSync(t)&&!ve.existsSync(X.join(t,".git"))&&(T.debug("[sync] remove broken remote worktree path",t),$a(t));let r=await F({args:["worktree","add",t,k],cwd:e});return c(r)?s(`Failed to create remote worktree
25
+ ${r.message}`):m("Created remote worktree",!0)},Xa=async({repoRoot:e,worktreeRoot:t})=>{T.debug("[sync] ensure remote worktree",t);let n=await Ya({repoRoot:e,branch:k});if(c(n))return s(n.message);let r=n.data,o=X.resolve(t),i=r?X.resolve(r):null;if(i&&i===o&&ve.existsSync(i))return T.debug("[sync] reuse existing remote branch worktree",{expected:o,actual:i}),m("Remote branch already checked out in expected worktree",!1);if(i&&i!==o){T.debug("[sync] remove old remote branch worktree",{expected:o,actual:i});let l=await F({args:["worktree","remove","--force",i],cwd:e});if(c(l))return s(`Failed to remove existing remote worktree
26
+ ${l.message}`)}if(i&&!ve.existsSync(i)){T.debug("[sync] prune stale branch worktree registration",{existingBranchWorktree:i});let l=await F({args:["worktree","prune"],cwd:e});if(c(l))return s(`Failed to prune stale worktrees
27
+ ${l.message}`)}let a=await $o({repoRoot:e,worktreeRoot:t});if(c(a))return s(a.message);let d=ve.existsSync(t);if(a.data&&d)return T.debug("[sync] remote worktree exists"),m("Remote worktree already exists",!1);if(a.data&&!d){T.debug("[sync] prune stale remote worktree registration");let l=await F({args:["worktree","prune"],cwd:e});if(c(l))return s(`Failed to prune stale worktrees
28
+ ${l.message}`)}return Ja({repoRoot:e,worktreeRoot:t})},Qa=async e=>{let t=await nn(e);if(c(t))return s(t.message);if(t.data===k)return T.debug("[sync] remote branch already checked out"),m("Remote branch already checked out",!1);T.debug("[sync] checkout remote branch",k);let n=await F({args:["checkout",k],cwd:e});return c(n)?s(`Failed to checkout ${k}
29
+ ${n.message}`):m("Checked out remote branch",!0)},Za=async e=>{let t=await F({args:["ls-tree","--name-only","HEAD"],cwd:e});if(c(t))return s(t.message);let r=t.data.stdout.trim().split(`
30
+ `).filter(Boolean).filter(a=>a!==rr);if(r.length===0)return m("Remote branch is storage-only",!1);T.debug("[sync] remove app files from storage branch",r);let o=await F({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(c(o))return s(`Failed to clean storage branch
31
+ ${o.message}`);let i=await er({cwd:e,message:"[epiq:repair-storage-branch]"});return c(i)?s(i.message):m("Cleaned storage branch",!0)},ed=async e=>{T.debug("[sync] ensure remote upstream",k);let t=await tr(e);if(c(t))return s(t.message);if(t.data)return T.debug("[sync] remote upstream already configured"),m("Remote upstream already configured",!1);let n=await en({repoRoot:e,remote:J});if(c(n))return s(n.message);if(!n.data)return T.debug("[sync] no remote configured for upstream"),m("No remote available for upstream",!1);let r=await tn({repoRoot:e,remote:J,branch:k});if(c(r))return s(r.message);if(!r.data)return T.debug("[sync] remote branch missing; upstream will be configured on first push"),m("Deferred upstream until first push",!1);T.debug("[sync] fetch remote branch before upstream set");let o=await F({args:["fetch",J,k],cwd:e});if(c(o))return s(`Failed to fetch ${k}
32
+ ${o.message}`);T.debug("[sync] set upstream to remote branch");let i=await F({args:["branch","--set-upstream-to",`${J}/${k}`,k],cwd:e});return c(i)?s(`Failed to set remote upstream
33
+ ${i.message}`):m("Configured remote upstream",!0)},Qo=async({worktreeRoot:e,ownEventFileName:t})=>{T.debug("[sync] stage own event file in remote worktree",t);let n=await F({args:["add",Ua(t)],cwd:e});return c(n)?s(`Failed to stage remote own event file
34
+ ${n.message}`):m("Staged remote own event file",void 0)},Zo=async({repoRoot:e,worktreeRoot:t})=>{let n=await za(e);return c(n)?s(n.message):(T.debug("[sync] create remote sync commit"),er({cwd:t,message:n.data}))},ar=async e=>{T.debug("[sync] push remote worktree");let t=await tr(e);if(c(t))return s(t.message);let n=await F({args:t.data?["push"]:["push","-u",J,k],cwd:e});return T.debug("[sync] push result",n),c(n)?s(`Failed during remote push
35
+ ${n.message}`):m("Pushed remote",!0)},dr=async({repoRoot:e,worktreeRoot:t,ensureUpstream:n})=>{T.debug("[sync] bootstrap remote storage",{repoRoot:e,worktreeRoot:t,ensureUpstream:n});let r=!1,o=[_a(),await qa({repoRoot:e}),await Xa({repoRoot:e,worktreeRoot:t}),await Qa(t),await Za(t),n?await ed(t):m("Skipped remote upstream bootstrap",!1)];for(let i of o){if(c(i))return s(i.message);r=r||!!i.data}return T.debug("[sync] bootstrap changed",r),m(n?"Bootstrapped remote storage":"Bootstrapped remote storage (readonly)",r)},cr=(e,t)=>{for(let n of[it(e),it(t)]){let r=an(n);if(c(r))return s(r.message)}return m("Ensured remote layout",void 0)};var ni=async(e=process.cwd())=>{logger.debug("[sync] start readonly sync",{cwd:e});let t=await Zn(e);if(c(t))return s(t.message);let n=t.data,r=or(n);logger.debug("[sync] resolved readonly roots",{repoRoot:n,worktreeRoot:r});let o=await Nt(n);if(c(o))return s(o.message);if(o.data)return s("Cannot sync while a git operation is in progress in the current repo");let i=await ir(n);if(c(i))return s(i.message);logger.debug("[sync] readonly ensure initial commit changed",i.data);let a=await dr({repoRoot:n,worktreeRoot:r,ensureUpstream:!1});if(c(a))return s(a.message);let d=await Nt(r);if(c(d))return s(d.message);if(d.data)return s("Cannot sync while a git operation is in progress in the remote worktree");let l=cr(n,r);if(c(l))return s(l.message);logger.debug("[sync] readonly pull remote branch");let u=await rn({cwd:r,remote:J,branch:k});if(c(u))return s(u.message);logger.debug("[sync] readonly pulled remote",u.data);let p=sr({repoRoot:n,worktreeRoot:r});return c(p)?s(p.message):(logger.debug("[sync] readonly hydrated from remote",p.data),m("Synced from remote",{repoRoot:n,worktreeRoot:r}))},td=({repoRoot:e,worktreeRoot:t,ownEventFileName:n})=>{let r=bt({root:e,fileName:n}),o=bt({root:t,fileName:n});return It.existsSync(r)?(logger.debug("[sync] merge own event file to remote",{ownEventFileName:n,localFile:r,remoteFile:o}),sn({sourceFile:r,targetFile:o})):(logger.debug("[sync] local own event file missing",r),m("Local own event file missing, nothing to merge",!1))},ei=async({repoRoot:e,worktreeRoot:t,ownEventFileName:n})=>{let r=td({repoRoot:e,worktreeRoot:t,ownEventFileName:n});if(c(r))return s(r.message);let o=await jo(t);if(c(o))return s(o.message);if(!r.data&&!o.data)return m("Own event file already up to date in remote worktree",{createdCommit:!1});let i=await Qo({worktreeRoot:t,ownEventFileName:n});if(c(i))return s(i.message);let a=await Zo({repoRoot:e,worktreeRoot:t});return c(a)?s(a.message):m("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:a.data})},ti=({repoRoot:e,worktreeRoot:t,ownEventFileName:n})=>{let r=bt({root:e,fileName:n}),o=bt({root:t,fileName:n});logger.debug("[sync] own event file sizes",{local:It.existsSync(r)?It.statSync(r).size:0,remote:It.existsSync(o)?It.statSync(o).size:0})},ri=async({cwd:e=process.cwd(),ownEventFileName:t})=>{logger.debug("[sync] start write sync",{cwd:e,ownEventFileName:t});let n=await Zn(e);if(c(n))return s(n.message);let r=n.data,o=or(r);logger.debug("[sync] resolved roots",{repoRoot:r,worktreeRoot:o});let i=await zo(r);if(c(i))return s(i.message);if(i.data)return s("Cannot run :sync while the repository is in detached HEAD state");if(t.includes("/")||t.includes("\\"))return s("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return s("Own event file must end with .jsonl");let a=await Nt(r);if(c(a))return s(a.message);if(a.data)return s("Cannot run :sync while a merge, rebase, cherry-pick, or revert is in progress in the current repo");let d=await ir(r);if(c(d))return s(d.message);logger.debug("[sync] ensure initial commit changed",d.data);let l=await dr({repoRoot:r,worktreeRoot:o,ensureUpstream:!0});if(c(l))return s(l.message);let u=await Nt(o);if(c(u))return s(u.message);if(u.data)return s("Cannot run :sync while a merge, rebase, cherry-pick, or revert is in progress in the remote worktree");let p=cr(r,o);if(c(p))return s(p.message);let y=!1,C,b=!1,I=!1,A=!1;logger.debug("[sync] pull remote branch before local copy");let S=await rn({cwd:o,remote:J,branch:k});if(c(S))return s(S.message);b=S.data,logger.debug("[sync] pulled remote",b);let M=sr({repoRoot:r,worktreeRoot:o});if(c(M))return s(M.message);A=M.data,logger.debug("[sync] hydrated from remote",A);let B=await ei({repoRoot:r,worktreeRoot:o,ownEventFileName:t});if(c(B))return s(B.message);if(y=B.data.createdCommit,C=B.data.commitSha,ti({repoRoot:r,worktreeRoot:o,ownEventFileName:t}),logger.debug("[sync] sync own file result",B.data),y||l.data){let G=await ar(o),oe=G;if(c(G)&&Vo(G.message)){let Lt=await rn({cwd:o,remote:J,branch:k});if(c(Lt))return s(Lt.message);let De=await ei({repoRoot:r,worktreeRoot:o,ownEventFileName:t});if(c(De))return s(De.message);De.data.createdCommit&&(y=!0,C=De.data.commitSha),ti({repoRoot:r,worktreeRoot:o,ownEventFileName:t}),logger.debug("[sync] retry sync own file result",De.data),oe=await ar(o)}if(c(oe))return s(oe.message);I=oe.data,logger.debug("[sync] pushed remote",I)}else logger.debug("[sync] no commit created, skipped push");if(y){let G=await F({args:["rev-parse","HEAD"],cwd:o});if(c(G))return s(G.message);C=G.data.stdout.trim()}return m("Synced event logs with remote",{repoRoot:r,worktreeRoot:o,createdCommit:y,commitSha:C,pulled:b,pushed:I,hydrated:A,bootstrapped:l.data})};import{ulid as oi}from"ulid";var st=null,Oe=()=>structuredClone(st),at=e=>st=e,ii=()=>{let{currentNode:e,selectedIndex:t}=h(),r=R(e.id)[t];return r?m("Resolved selected child",r):s("Target node not found")};function lr(e){let t=ii();if(c(t))return t;let{currentNode:n,nodes:r}=h();if(!n.parentNodeId)return s("Missing parent node id");let o=r[n.parentNodeId];if(!o)return s("Missing parent node");let i=_(o.id),a=i.findIndex(({id:C})=>C===n.id);if(a<0)return s("Current node not found among siblings");let d=i[a+e];if(!d)return s("Missing sibling node");let l=te();if(c(l))return s("Unable to resolve user ID");let{userId:u,userName:p}=l.data;if(at({id:oi(),userId:u,userName:p,action:"move.node",payload:{id:t.data.id,parent:d.id,pos:{at:"end"}}}),!st)return s("Could not materialize move state");let y=rt(st,!0);return c(y)?y:m("Node moved successfully",y.data)}function mr(e){let t=ii();if(c(t))return t;let{currentNode:n,selectedIndex:r}=h(),i=_(n.id)[r+e];if(!i)return s("Missing sibling node");let a=te();if(c(a))return s("Unable to resolve user ID");let{userId:d,userName:l}=a.data;if(at({id:oi(),userId:d,userName:l,action:"move.node",payload:{id:t.data.id,parent:n.id,pos:{at:e===1?"after":"before",sibling:i.id}}}),!st)return s("Could not materialize move state");let u=rt(st,!0);return c(u)?u:m("Node moved successfully",u.data)}import nd from"node:os";import si from"node:path";import{z as dn}from"zod";var rd={userId:"",userName:"",preferredEditor:""},ai=dn.object({preferredEditor:dn.string().optional(),userName:dn.string().optional(),userId:dn.string().optional()}).strict(),od=".epiq",id="config.json",di=()=>si.join(nd.homedir(),od),ur=()=>si.join(di(),id),pr=()=>{try{return ce.mkDir(di()),m("Ensured ~/.epiq exists",null)}catch{return s("Unable to create ~/.epiq")}},sd=e=>{let t;try{t=JSON.parse(e)}catch{return s("Invalid ~/.epiq/config.json JSON")}let n=ai.safeParse(t??{});return n.success?m("Parsed config",n.data):s(`Invalid ~/.epiq/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},ci=()=>{let e=pr();if(c(e))return s(e.message);let t=ur(),n=ce.readFile(t);return n==null||n.trim()===""?m("No config found, using empty config",{}):sd(n)},li=e=>{let t=pr();if(c(t))return s(t.message);let n=ai.safeParse(e);if(!n.success)return s(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=ur();try{return ce.writeToFile(r,JSON.stringify(n.data,null,2)+`
36
+ `),m("Config written",null)}catch{return s("Unable to write ~/.epiq/config.json")}},gr=e=>{let t=ci();if(c(t))return s("Failed to read existing config");let n={...t.data,...e};return li(n)},mi=()=>{let e=ur(),t=pr();if(c(t))return s("Unable to create ~/.epiq");if(!(ce.readFile(e)!==null)){let d=li(rd);if(c(d))throw new Error("Unable to create ~/.epiq/config.json")}let r=ci();if(c(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:a}=r.data;return!i||!a?s("User name or ID not configured in ~/.epiq/config.json"):m("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:a})};var ad=e=>Object.values(h().tags).find(t=>t.name===e),dd=e=>Object.values(h().contributors).find(t=>t.name===e),ui=[{systemOnly:!0,intent:L.Move,mode:f.COMMAND_LINE,action:()=>{let e=te();if(c(e))return s("Unable to resolve user ID");let{modifier:t}=ge().commandMeta,n=()=>{let d=Oe();if(!d)return s("No pending move state");let l=d.payload.id;if(!h().nodes[l])return s("Moved node not found");let p=d.payload.parent,y=h().nodes[p];if(!y)return s("Move parent not found");let C=R(p).findIndex(b=>b.id===l);return C===-1?s("Moved node not found among rendered children"):(U.navigate({currentNode:y,selectedIndex:C}),m("Synchronized navigation to moved node",null))},r=d=>{if(c(d))return s(d.message);let l=n();return c(l)?s(l.message):m("Updated move preview",null)},{currentNode:o,selectedIndex:i}=h(),a=R(o.id)[i];if(!a)return w({mode:f.DEFAULT}),s("No move target");if(t==="start"){if(a.readonly)return s("Target node is read-only");if(i===-1)return s("No item selected");if(!a.parentNodeId)return s("Target has no parent");let d=R(a.parentNodeId),l=d.findIndex(({id:b})=>b===a.id);if(l===-1)return s("Target not found among siblings");let u=d[l-1],p=d[l+1],y=p!=null?{at:"before",sibling:p.id}:u!=null?{at:"after",sibling:u.id}:{at:"start"};at({id:K(),action:"move.node",payload:{id:a.id,parent:a.parentNodeId,pos:y},...e.data}),w({mode:f.MOVE});let C=n();return c(C)?s(C.message):m("Move initialized",null)}if(t==="next")return w({mode:f.MOVE}),r(mr(1));if(t==="previous")return w({mode:f.MOVE}),r(mr(-1));if(t==="to-next")return w({mode:f.MOVE}),r(lr(1));if(t==="to-previous")return w({mode:f.MOVE}),r(lr(-1));if(t==="confirm"){w({mode:f.DEFAULT});let d=Oe();if(!d)return s("No pending move to confirm");let l=ne(d);if(c(l))return l;let u=n();return c(u)?s(u.message):(at(null),m("Moved item",null))}return t==="cancel"?(at(null),w({mode:f.DEFAULT}),m("Cancelling move",null)):s("Invalid move modifier")}},{intent:L.Delete,mode:f.COMMAND_LINE,action:()=>{let e=te();if(c(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=h(),r=R(t.id)[n];return r?ne({id:K(),action:"delete.node",payload:{id:r.id},...e.data}):s("Unable to resolve child to delete")},onSuccess:()=>w({mode:f.DEFAULT})},{intent:L.Edit,mode:f.COMMAND_LINE,action:()=>{let e=te();if(c(e))return s("Unable to resolve user ID");let t=be(h().breadCrumb,"TICKET");if(c(t))return s("Edit target must be an issue");let n=t.data;if(n.readonly)return s("Cannot edit readonly field");let{currentNode:r,selectedIndex:o}=h();if(!R(n.id)[o])return s("No selected field");let a=R(r.id)[o];if(!a)return s("No selected field");if(a.readonly)return s("Cannot edit readonly field");let d=a.props.value;if(typeof d!="string")return s("Selected field is not editable text");let l=Io(d);if(c(l))return s("Failed to edit field");let u=l.data;return u===d?m("No changes made",null):a.title==="Description"?ne({id:K(),action:"edit.description",payload:{id:a.id,md:u},...e.data}):a.title==="Title"?ne({id:K(),action:"edit.title",payload:{id:a.id,name:u},...e.data}):s(`Editing not supported for "${a.title}"`)},onSuccess:()=>w({mode:f.DEFAULT})},{intent:L.Filter,mode:f.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ge().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(d=>z(g.FILTER).map(l=>l.split(n)[0]).includes(d))(r))return s("Invalid filter modifier");let a={target:r,operator:"=",value:t.trim()};return ae(d=>({...d,filters:e==="clear"?[]:[...d.filters,a],mode:f.DEFAULT})),m("Viewing help",null)}},{intent:L.ViewHelp,mode:f.COMMAND_LINE,action:()=>(w({mode:f.HELP}),m("Viewing help",null))},{intent:L.CloseIssue,mode:f.COMMAND_LINE,action:()=>{let e=te();if(c(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=h(),r=R(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!r.parentNodeId)return s("No target parent found");if(!$e(r))return s("Cannot close in this context");let o=ne({id:K(),action:"close.issue",payload:{id:r.id,parent:r.parentNodeId},...e.data});return c(o)?o:m("Viewing help",null)}},{intent:L.ReopenIssue,mode:f.COMMAND_LINE,action:()=>{let e=te();if(c(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=h(),r=R(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?m("Resolved ticket",r):Xe(r.id,"TICKET");if(c(o))return s("Cannot reopen in this context");let i=o.data,a=ne({id:K(),action:"reopen.issue",payload:{id:i.id},...e.data});return c(a)?a:m("Issue reopened",null)},onSuccess:()=>w({mode:f.DEFAULT})},{intent:L.SetUserName,mode:f.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:n}=pe(),r=$t()?.trim();if(!r)return s("No username provided");let o=r??n,i=e??K();if(!o||!i)return s("Unable to resolve user name or id");let a=gr({userName:o,userId:i,preferredEditor:t??""});return c(a)?a:(gt({userName:o,userId:i}),w({mode:f.DEFAULT}),m(`Username set to "${r}"`,null))}},{intent:L.Init,mode:f.COMMAND_LINE,action:()=>{let e=yr();if(c(e))return e;let{rootNodeId:t,nodes:n}=h();return U.navigate({currentNode:n[t],selectedIndex:0}),m("Project initialized",null)}},{intent:L.SetEditor,mode:f.COMMAND_LINE,action:()=>{let e=$t()?.trim();if(!e)return s("No editor provided");let t=gr({preferredEditor:e});return c(t)?t:(gt({preferredEditor:e}),w({mode:f.DEFAULT}),m(`Editor configuration set to "${e}"`,null))}},{intent:L.NewItem,mode:f.COMMAND_LINE,action:(e,t)=>{let n=te();if(c(n))return s("Unable to resolve user ID");if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:r,currentNode:o,selectedIndex:i}=h(),a=d=>{let l=ne(d);if(c(l))return l;let u=N.getNode(l.data.result.id);if(!u)return s("Created node not found");if(!u.parentNodeId)return l;let p=N.getNode(u.parentNodeId);return p?(U.navigate({currentNode:p,selectedIndex:N.getSiblings(u.parentNodeId).findIndex(({id:y})=>y===u.id)}),l):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:d}=h(),l=N.getNode(d);return l?a({id:K(),action:"add.board",payload:{id:K(),name:t.inputString,parent:l.id},...n.data}):s("Workspace not found")}if(t.modifier==="swimlane"){let d=be(r,"BOARD");return c(d)?s("Unable to add swimlane in this context"):a({id:K(),action:"add.swimlane",payload:{id:K(),name:t.inputString,parent:d.data.id},...n.data})}if(t.modifier==="issue"){let d=R(o.id)[i],l=o.context==="SWIMLANE"?o:o.context==="BOARD"&&d?.context==="SWIMLANE"?d:(()=>{let b=be(r,"SWIMLANE");return c(b)?null:b.data})();if(!l)return s("Unable to add issue in this context");let u=So({name:t.inputString,parent:l.id,user:n.data}),p=Fo(u);if(p.some(b=>c(b)))return s("Issue create failed: "+p.filter(c).map(b=>b.message).filter(Boolean).join(", "));let y=p[0];if(!y||c(y))return s("Issue creation failed");let C=u[0]?.payload.id;return C?(U.navigate({currentNode:l,selectedIndex:N.getSiblings(l.id).findIndex(({id:b})=>b===C)}),m("Issue created",null)):s("Unable to determine ticket id")}return Wr()},onSuccess:()=>w({mode:f.DEFAULT})},{intent:L.SetView,mode:f.COMMAND_LINE,action:()=>{let{commandMeta:e}=ge();return e.validity===Ne.Invalid?s("Invalid command "+ye):(ae(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),m("View set",null))},onSuccess:()=>w({mode:f.DEFAULT})},{intent:L.Rename,mode:f.COMMAND_LINE,action:()=>{let e=te();if(c(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=h(),r=R(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=$t();return o?ne({id:K(),action:"edit.title",payload:{id:r.id,name:o},...e.data}):s("Provide a new name")},onSuccess:()=>w({mode:f.DEFAULT})},{intent:L.TagTicket,mode:f.COMMAND_LINE,action:()=>{let e=te();if(c(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ge().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=h(),a=R(i.id)[o];if(!a)return s("Invalid tag target");let d=Xe(a.id,"TICKET");if(c(d))return s("Unable to tag issue in this context");let l=d.data,u=ad(r),p;if(u)p=u.id;else{let b=K(),I=ne({id:K(),action:"create.tag",payload:{id:b,name:r},userId:e.data.userId,userName:e.data.userName});if(c(I))return I;p=I.data.result.id}let y=N.getFieldByTitle(l.id,"Tags");return y?R(y.id).some(b=>b.props?.value===p)?s("Already tagged with that tag"):ne({id:K(),action:"tag.issue",payload:{id:K(),target:l.id,tagId:p},...e.data}):s("Unable to locate tags field")},onSuccess:()=>w({mode:f.DEFAULT})},{intent:L.AssignUserToTicket,mode:f.COMMAND_LINE,action:()=>{let e=te();if(c(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ge().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=h(),a=R(i.id)[o];if(!a)return s("Invalid assign target");let d=Xe(a.id,"TICKET");if(c(d))return s("Unable to assign issue in this context");let l=d.data,u=dd(r),p;if(u)p=u.id;else{let b=K(),I=ne({id:K(),action:"create.contributor",payload:{id:b,name:r},userId:e.data.userId,userName:e.data.userName});if(c(I))return I;p=I.data.result.id}let y=N.getFieldByTitle(l.id,"Assignees");return y?R(y.id).some(b=>b.props?.value===p)?s("Assignee already assigned"):ne({id:K(),action:"assign.issue",payload:{id:K(),target:l.id,contributor:p},...e.data}):s("Unable to locate assignees field")},onSuccess:()=>w({mode:f.DEFAULT})},{intent:L.Sync,mode:f.COMMAND_LINE,action:async()=>{$(()=>""),w({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:e,userName:t}=pe();if(!e)return s("Unable to resolve userId");if(!t)return s("Unable to resolve userName");let n=Ke()?yr():m("No pending default events",null);if(c(n))return s(`Unable to persist default events. ${n.message}`);let r=te();if(c(r)||!r.data)return s("Unable to resolve event log path");let o=qn(r.data);logger.debug("[sync-command] pending defaults",Ke());let i=await ri({ownEventFileName:o});if(c(i))return w({syncStatus:{msg:i.message,status:"outOfSync"}}),s(`Unable to sync state. ${i.message}`);w({syncStatus:{msg:"Synced",status:"synced"},mode:f.DEFAULT});let a=ht();return c(a)?s("Unable to load events"):(je(a.data),m("Synced",!0))}},{intent:L.Peek,mode:f.COMMAND_LINE,action:async()=>{let e=be(h().breadCrumb,"BOARD");if(c(e))return e;let t=ht();if(c(t))return s(t.message);let n=t.data,{modifier:r}=ge().commandMeta,o;if(r==="now"){let y=fr();if(c(y))return y;let C=je(n);return C.some(c)?s(C.map(b=>b.message).join(", ")):(w({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),m("Peeking now",!0))}if(r==="prev"){let y=h().eventLog.at(-2),C=On(y);if(C===null)return s("No previous event to peek");o=C}else if(r==="next"){let y=h().unappliedEvents.at(0),C=On(y);if(C===null)return s("No next event to peek");o=C}else{let y=Ut(r);if(!y)return s("Invalid peek date");o=y.getTime()}let i=e.data.id,{appliedEvents:a,unappliedEvents:d}=Po(n,o),l=fr();if(c(l))return l;let u=je(a);if(u.some(c))return s(u.map(y=>y.message).join(", "));let p=h().nodes[i];return p?(U.navigate({currentNode:p,selectedIndex:0}),w({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:d}),m("Peeking ",!0)):s("Board did not exist at peek date")}}];var cd=new Set(["peek","filter","view-help"]),le=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ge();if(!t)return s("No command to confirm");if(!e&&n===Ne.Invalid)return s("Invalid command");let i=ho(t);if(po(),h().readOnly&&!cd.has(i))return xt({result:ye.Fail,message:"Command not available in readonly state",data:null});let a=ui.filter(l=>e||l.systemOnly!==!0).find(l=>l.intent===i);if(!a)return xt({result:ye.Fail,message:"Command not found",data:null});let d=await a.action(a,{command:t,inputString:o,modifier:r});return c(d)?xt(d):(go({addToHistory:!e}),a.onSuccess?.(),xt(d))};var cn=[{intent:x.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(w({mode:f.COMMAND_LINE}),$(()=>"move cancel"),le({isForceExecutedBySystem:!0}))},{intent:x.InitMove,mode:f.DEFAULT,description:"[m] move init/confirm",action:()=>(w({mode:f.COMMAND_LINE}),$(()=>"move start"),le({isForceExecutedBySystem:!0}))},{intent:x.ConfirmMove,mode:f.MOVE,action:()=>(w({mode:f.COMMAND_LINE}),$(()=>"move confirm"),le({isForceExecutedBySystem:!0}))}],ln=[{intent:x.MovePreviousItem,mode:f.MOVE,action:()=>Oe()?(w({mode:f.COMMAND_LINE}),$(()=>"move previous"),le({isForceExecutedBySystem:!0})):s("No pending move")},{intent:x.MoveNextItem,mode:f.MOVE,action:()=>Oe()?(w({mode:f.COMMAND_LINE}),$(()=>"move next"),le({isForceExecutedBySystem:!0})):s("No pending move")}],pi=[{intent:x.MoveToNextContainer,mode:f.MOVE,action:()=>Oe()?(w({mode:f.COMMAND_LINE}),$(()=>"move to-next"),le({isForceExecutedBySystem:!0})):s("No pending move")},{intent:x.MoveToPreviousContainer,mode:f.MOVE,action:()=>Oe()?(w({mode:f.COMMAND_LINE}),$(()=>"move to-previous"),le({isForceExecutedBySystem:!0})):s("No pending move")}];var gi={[P.WORKSPACE]:[...cn,...ln],[P.BOARD]:[...cn,...ln],[P.SWIMLANE]:[...cn,...ln,...pi],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var fi=[{intent:x.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(w({mode:f.COMMAND_LINE}),$(()=>`${g.NEW} `),m("Adding new item",null))},{intent:x.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(w({mode:f.COMMAND_LINE}),$(()=>`${g.DELETE} `),m("Deleting item",null))},{intent:x.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(w({mode:f.COMMAND_LINE}),$(()=>""),m("Entering command line mode",null))},{intent:x.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(U.enterChildNode(),m("Entering context",null))},{intent:x.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(U.enterParentNode(),m("Exiting context",null))},{intent:x.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),m("Navigating to previous item",null))},{intent:x.NavNextItem,mode:f.DEFAULT,action:()=>(U.navigateToNextItem(),m("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(U.navigateToPreviousContainer(),m("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:f.DEFAULT,action:()=>(U.navigateToNextContainer(),m("Navigating to next container",null))},{intent:x.Edit,mode:f.DEFAULT,action:()=>(w({mode:f.COMMAND_LINE}),$(()=>"edit"),le(),m("Fired command",!0))},{intent:x.SetViewDense,mode:f.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(w({viewMode:"dense"}),m("View set",null))},{intent:x.SetViewWide,mode:f.DEFAULT,action:()=>(w({viewMode:"wide"}),m("View set",null))},{intent:x.Sync,mode:f.DEFAULT,description:"[s] sync epiq with remote state branch",action:()=>(w({mode:f.COMMAND_LINE}),$(()=>"sync"),le({isForceExecutedBySystem:!0}),m("Synced",!0))}];var yi=[{intent:x.ViewHelp,mode:f.DEFAULT,action:()=>(w({mode:f.HELP}),m("Viewing help",null))},{intent:x.Exit,mode:f.HELP,action:()=>(w({mode:f.DEFAULT}),m("Exiting help",null))},{intent:x.Confirm,mode:f.COMMAND_LINE,action:()=>(le(),m("Executing command",null))},{intent:x.MoveCursorLeft,mode:f.COMMAND_LINE,action:()=>(jn(-1),m("Moving cursor left",null))},{intent:x.MoveCursorRight,mode:f.COMMAND_LINE,action:()=>(jn(1),m("Moving cursor right",null))},{intent:x.MoveCursorLeftOfWord,mode:f.COMMAND_LINE,action:()=>(zn("left"),m("Moving cursor left of word",null))},{intent:x.MoveCursorRightOfWord,mode:f.COMMAND_LINE,action:()=>(zn("right"),m("Moving cursor right of word",null))},{intent:x.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(w({mode:f.DEFAULT}),m("Exiting command line",null))},{intent:x.AutoCompleteCommand,mode:f.COMMAND_LINE,action:()=>($((e,{remainder:t})=>t?e+t:e),m("Auto-completing command",null))},{intent:x.CaptureInput,mode:f.COMMAND_LINE,action:(e,{sequence:t})=>($(n=>n+t),m("Capturing input",null))},{intent:x.EraseInput,mode:f.COMMAND_LINE,action:()=>(mo(),m("Erasing input",null))},{intent:x.EraseInputWord,mode:f.COMMAND_LINE,action:()=>(uo(),m("Erasing input word",null))},{intent:x.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(fo(),m("Getting last command from history",null))},{intent:x.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(yo(),m("Getting next command from history",null))}];import ld from"chalk";var mn=": for command line",xi="q to exit",vi=`${ld.hex(E.accent)("m")} to confirm`,xr={[P.WORKSPACE]:[mn],[P.BOARD]:[mn],[P.BOARD+f.COMMAND_LINE]:[mn],[P.SWIMLANE]:[mn],[P.TICKET+f.HELP]:[xi],[P.SWIMLANE+f.HELP]:[xi],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+f.MOVE]:[vi],[P.TICKET+f.MOVE]:[vi]};var un=e=>e.trim().toLocaleLowerCase(),md=(e,t)=>{let n=N.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},ud=e=>{let{tags:t}=h(),n=N.getFieldByTitle(e,"Tags");return n?_(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},pd=e=>{let{contributors:t}=h(),n=N.getFieldByTitle(e,"Assignees");return n?_(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},hi=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return un(e.title??"").includes(n);case"description":return un(md(e.id,"Description")).includes(n);case"tag":return ud(e.id).map(un).some(d=>d.includes(n));case"assignee":return pd(e.id).map(un).some(d=>d.includes(n));default:return!0}};function Ei(e,t,n){let r=t[e];if(!r)return s("buildBreadCrumb(): current node not found");let o=[],i=r;for(;i&&(o.push(i),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let a=o[o.length-1];return!a||a.id!==n?s("buildBreadCrumb(): node is not connected to root"):(o.reverse(),m("Breadcrumb built",o))}var Ci=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 pn,vr,hr=new Set,Ni=()=>{for(let e of hr)e()},fd=e=>(hr.add(e),()=>hr.delete(e));function bi(e){let{currentNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return s("derive(): currentNodeId is missing");if(!r)return s("derive(): rootNode is missing");if(!o[r])return s("derive(): unable to find root node");let d=o[t];if(!d)return logger.error("Unable to derive state, currentNode not found"),s("Unable to derive state, currentNode not found");let l=Ei(t,o,r);if(c(l))return logger.error(l.message),l;let u=l.data,{context:p}=d,y=xr[p+n]??xr[p]??[],C=[...fi,...gi[p]??[],...yi],b=Ci(C),I=yd(o,i),A=I[t]?.[e.selectedIndex]??null;return m("Derived successfully",{...e,currentNode:d,breadCrumb:u,availableHints:y,availableActions:C,actionIndex:b,selectedNode:A,renderedChildrenIndex:I})}var h=()=>(pn||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),pn);function Jn(e){vr=e;let t={readOnly:!1,filters:[],tags:{},contributors:{},viewMode:"dense",mode:f.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live"},n=bi(t);return c(n)?n:(pn=n.data,Ni(),m("State initialized",null))}function ae(e){let t=h(),n=e(t),r=bi(n);return c(r)?s(r.message??"Unable to update state"):(pn=r.data,Ni(),m("State updated",null))}var w=e=>ae(t=>({...t,...e}));var W=()=>gd(fd,h,h),yd=(e,t)=>{let n={};for(let r of Object.values(e))$e(r)&&t.length>0&&!t.every(o=>hi(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,i)=>{let a=e[o.id],d=e[i.id];return!a||!d?0:a.rank.localeCompare(d.rank)});return n},R=e=>h()?.renderedChildrenIndex[e]??[],fr=()=>vr?Jn(vr):s("Cannot reset state: no initial workspace found");var U={exit(){process.exit(0)},enterChildNode(){let e=h(),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}=h();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:a})=>a===e.id),i=r.length===0?-1:o>=0?o:0;U.navigate({currentNode:n,selectedIndex:i})},navigateToNextItem:()=>Ii(1),navigateToPreviousItem:()=>Ii(-1),navigateToNextContainer:()=>Si(1),navigateToPreviousContainer:()=>Si(-1),navigate:({currentNode:e=h().currentNode,selectedIndex:t})=>{w({currentNodeId:e.id,selectedIndex:t})}},Ii=e=>{let t=h(),n=R(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;U.navigate({selectedIndex:o})},Si=e=>{let{currentNode:t,nodes:n,selectedIndex:r}=h();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let i=R(o.id),a=i.findIndex(C=>C.id===t.id);if(a<0)return;let d=i.at(a+e)??i.at(0);if(!d)return;let l=R(d.id),u=Math.max(0,l.length-1),p=Math.min(Math.max(0,r),u),y=l.length?p:-1;U.navigate({currentNode:d,selectedIndex:y})};var Ae="system",Te="ACTOR",St=xd(),we=null;function vd(){let e=Object.values(h().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=h().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:h().nodes[h().rootNodeId],selectedIndex:0}}function hd(){let e=vd();U.navigate(e)}function Ed(){let e=St(),t=St(),n=St(),r=St(),o=St();return[{id:Se(),userId:Ae,userName:Te,action:"init.workspace",payload:{id:e,name:"Workspace"}},{id:Se(),userId:Ae,userName:Te,action:"add.board",payload:{id:t,name:"Default",parent:e}},{id:Se(),userId:Ae,userName:Te,action:"add.swimlane",payload:{id:n,name:"Todo",parent:t}},{id:Se(),userId:Ae,userName:Te,action:"add.swimlane",payload:{id:r,name:"Review",parent:t}},{id:Se(),userId:Ae,userName:Te,action:"add.swimlane",payload:{id:o,name:"Done",parent:t}},{id:Se(),userId:Ae,userName:Te,action:"add.board",payload:{id:Zt,name:"Closed",parent:e}},{id:Se(),userId:Ae,userName:Te,action:"add.swimlane",payload:{id:nt,name:"Closed",parent:Zt}},{id:Se(),userId:Ae,userName:Te,action:"lock.node",payload:{id:Zt}},{id:Se(),userId:Ae,userName:Te,action:"lock.node",payload:{id:nt}}]}function Ke(){return we!==null}function yr(){if(!we||we.length===0)return we=null,m("No pending default events to persist",null);let e=we.map(t=>Yt({event:t})).filter(c);return e.length>0?s([dt.bold.red("Persisting default events failed"),"",...e.map((t,n)=>`${dt.dim.gray(`${n+1}.`)} ${dt.dim(t.message)}`),`
37
37
  `].join(`
38
- `)):(De=null,c("Persisted pending default events",null))}function gi(e){let t;e.some(n=>n.action==="init.workspace")?(De=null,t=ft(e)):(De=Xa(),t=ft([...De]));let r=t.filter(d);return r.length>0?s([st.bold.red("Materializing failed"),"",...r.map((n,o)=>`${st.dim.gray(`${o+1}.`)} ${st.dim(n.message)}`),`
38
+ `)):(we=null,m("Persisted pending default events",null))}function Ai(e){let t;e.some(r=>r.action==="init.workspace")?(we=null,t=je(e)):(we=Ed(),t=je([...we]));let n=t.filter(c);return n.length>0?s([dt.bold.red("Materializing failed"),"",...n.map((r,o)=>`${dt.dim.gray(`${o+1}.`)} ${dt.dim(r.message)}`),`
39
39
  `].join(`
40
- `)):(Ja(),c("State booted successfully",null))}import{Box as gd}from"ink";import un from"react";import bt from"chalk";import{Box as ln,Text as fi}from"ink";import Et,{useEffect as Ya,useMemo as Qa,useState as Za}from"react";var yi=bt.gray,ed=bt.inverse,td=bt.inverse.gray,rd={hint:"",hints:[],overlap:0,remainder:""},vi=({value:e,command:t})=>{if(!t)return null;let r=e.trimStart(),o=e.length-r.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},nd=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let r=se(t);return{bg:n=>bt.bgHex(r).black(n),bgCursor:n=>bt.bgHex(r).inverse.black(n)}}return Rr(t)},od=({value:e,command:t,modifier:r})=>{if(!t||!r)return null;let n=vi({value:e,command:t});if(!n)return null;let i=e.slice(n.end).match(/^\s*/)?.[0].length??0,a=n.end+i;return e.slice(a,a+r.length)!==r?null:{start:a,end:a+r.length}},xi=()=>({value:z.value,cursorPosition:z.cursorPosition,commandIsPending:z.commandIsPending,autoCompletion:z.commandMeta.autoCompletion??rd,infoMessage:z.commandMeta.infoMessage,validationStatus:z.commandMeta.validity,command:z.commandMeta.command,inputString:z.commandMeta.inputString,modifier:z.commandMeta.modifier}),id=(e,t)=>e.value===t.value&&e.cursorPosition===t.cursorPosition&&e.commandIsPending===t.commandIsPending&&e.infoMessage===t.infoMessage&&e.autoCompletion.hint===t.autoCompletion.hint&&e.autoCompletion.overlap===t.autoCompletion.overlap&&e.autoCompletion.remainder===t.autoCompletion.remainder&&e.validationStatus===t.validationStatus&&e.command===t.command&&e.modifier===t.modifier&&e.inputString===t.inputString,hi=({width:e})=>{let[t,r]=Za(xi());Ya(()=>{let y=()=>{let I=xi();r(S=>id(S,I)?S:I)},v=Xn(y);return y(),()=>{v()}},[]);let{value:n,cursorPosition:o,infoMessage:i,commandIsPending:a,autoCompletion:l,command:m,modifier:u}=t,p=Qa(()=>{let y=Math.max(0,Math.min(o,n.length)),v=vi({value:n,command:m}),I=od({value:n,command:m,modifier:u}),S=m?Rr(m):null,N=nd({command:m,modifier:u}),b=(re,ne)=>{let br=v&&ne>=v.start&&ne<v.end,Ir=I&&ne>=I.start&&ne<I.end;return br&&S?S.fg(re):Ir&&N?N.bg(re):re},T=(re,ne)=>{let br=v&&ne>=v.start&&ne<v.end,Ir=I&&ne>=I.start&&ne<I.end;return br&&S?S.fgCursor(re):Ir&&N?N.bgCursor(re):ed(re)},B=n.slice(0,y),V=n[y]??" ",te=y<n.length?n.slice(y+1):"",wt=Array.from(B).map((re,ne)=>b(re,ne)).join(""),Re=T(V,y),Tn=Array.from(te).map((re,ne)=>b(re,y+1+ne)).join("");if(l.hint){let re=l.hint[l.overlap]??V;Re=td(re),Tn=yi(l.remainder.slice(1)+te)}return yi(":")+wt+Re+Tn},[n,o,l,m,u]);return Et.createElement(ln,{flexDirection:"column",justifyContent:"flex-start"},Et.createElement(ln,{flexDirection:"column",paddingX:1,borderColor:h.secondary,borderStyle:"round",width:e},Et.createElement(ln,null,Et.createElement(fi,null,p),i&&Et.createElement(fi,{wrap:"truncate",color:a?h.red:h.secondary2},` ${i} `))))};import Ci from"chalk";import{Box as sd,Text as mn}from"ink";import dr,{useEffect as ad,useState as dd}from"react";var cd=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Ni=e=>{let t=e.replace("#","");return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}},ld=({r:e,g:t,b:r})=>{let n=o=>Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0");return`#${n(e)}${n(t)}${n(r)}`},md=(e,t,r)=>{let n=Ni(e),o=Ni(t);return ld({r:n.r+(o.r-n.r)*r,g:n.g+(o.g-n.g)*r,b:n.b+(o.b-n.b)*r})},ud=(e,t)=>{if(e.length===1)return e[0];let r=t*(e.length-1),n=Math.floor(r),o=r-n,i=e[n],a=e[Math.min(n+1,e.length-1)];return md(i,a,o)},pd=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),Ei=({width:e,availableHints:t})=>{let{syncStatus:{status:r,msg:n}}=_(),[o,i]=dd(0);ad(()=>{if(r!=="syncing"){i(0);return}let b=setInterval(()=>{i(T=>T+1)},50);return()=>clearInterval(b)},[r]);let a=[],l=0;for(let b of t){let B=(a.length>0?" | ":"").length+b.length;if(l+B>e-4)break;a.push(b),l+=B}let m=r!="synced"?n??a.join(" | "):a.join(" | "),u=Math.max(0,e-2),p=r==="syncing"?ud(cd,(Math.sin(o*.12)+1)/2):h.secondary,y=Ci.hex(p??"fff"),v=Ci.hex(h.secondary2),I=y(`\u256D${"\u2500".repeat(u)}\u256E`),S=y(`\u2570${"\u2500".repeat(u)}\u256F`),N=`${y("\u2502")}${v(pd(` ${m} `,u))}${y("\u2502")}`;return dr.createElement(sd,{flexDirection:"column",width:e},dr.createElement(mn,null,I),dr.createElement(mn,null,N),dr.createElement(mn,null,S))};var cr=({width:e,mode:t,availableHints:r})=>{let n=_(),o=[],i=0;for(let a of r){let m=(o.length>0?" | ":"").length+a.length;if(i+m>e+2)break;o.push(a),i+=m}return un.createElement(gd,null,t===g.COMMAND_LINE&&n.syncStatus.status!=="syncing"?un.createElement(hi,{width:e}):un.createElement(Ei,{width:e,mode:t,availableHints:r}))};import{Box as at,Text as bi}from"ink";import Fe from"react";var Ii=({width:e})=>{let t=[...C().availableActions].map(r=>r.description).filter(r=>r!==void 0).map(r=>{let[n,o]=r.split("]"),i=n?.replace("[",""),a=o?.trim();return[i,a]}).filter(r=>r[0]!==void 0&&r[1]!==void 0).sort(([r],[n])=>r.length===1&&n.length!==1?-1:r.length!==1&&n.length===1?1:r.localeCompare(n,void 0,{sensitivity:"base"}));return t.unshift(["Key(s)","Action"]),Fe.createElement(at,{flexDirection:"column",marginTop:3,borderColor:h.secondary,borderStyle:"round",width:e,minHeight:19},Fe.createElement(at,{flexDirection:"column",width:e},C().mode===g.HELP?t.map(([r,n],o)=>Fe.createElement(at,{paddingLeft:1,key:o,flexDirection:"row"},Fe.createElement(at,{key:o,flexDirection:"row",paddingBottom:o?0:1},Fe.createElement(at,{width:20,justifyContent:"flex-end"},Fe.createElement(bi,{color:o?h.accent:h.secondary},r)),Fe.createElement(at,{flexGrow:1,width:40,paddingLeft:2},Fe.createElement(bi,{color:o?h.primary:h.secondary},n))))):null))};import Ti from"chalk";import{Box as gn,Text as Ri}from"ink";import Se from"react";import{Box as pn,Text as Nd}from"ink";import lt from"react";import{Text as fd}from"ink";import yd from"react";var xd=e=>e.toLowerCase().trim(),vd=(e,t=Je)=>{let r=xd(e);return t[r]?t[r]:pt(r)},dt=({id:e,isSelected:t})=>{let r=E.getContributor(e);if(r)return yd.createElement(fd,{underline:t,color:vd(r.name)},"@"+r.name)};import{Text as hd}from"ink";import Cd from"react";var ct=({id:e,isSelected:t})=>{let r=E.getTag(e);if(r)return Cd.createElement(hd,{underline:t,backgroundColor:se(r.name),color:h.primary}," "+r.name+" ")};var Ed=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",Si=({width:e})=>{let{breadCrumb:t,currentNode:r,selectedIndex:n,viewMode:o}=C(),i=W(r.id)[n],a=Ge(i?.id??r.id,"TICKET"),l=ze(a)?a.data:void 0,m=l?.id?W(l.id):[],u=N=>{let b=m.find(T=>T.title===N);return b?W(b.id).map(T=>typeof T.props?.value=="string"?T.props.value:"").filter(T=>!!T):[]},p=u("Tags"),y=u("Assignees"),v=l?.parentNodeId?!wr(r.id,l?.parentNodeId)&&o==="dense":!1,I=t.map((N,b)=>{let T=b===t.length-1,B=W(N.id),V=T?B?.[n]?.title:void 0;return`${b?" / ":""}${N.title??""}${V?` \u25B8 ${V}`:""}`}).join(""),S=Ed(I,e);return lt.createElement(pn,null,lt.createElement(Nd,{color:h.secondary2},S),v?p.map(N=>lt.createElement(pn,{key:N,paddingLeft:2},lt.createElement(ct,{id:N}))):null,v?y.map(N=>lt.createElement(pn,{key:N,paddingLeft:2},lt.createElement(dt,{id:N}))):null)};import{Box as bd,Text as Ai}from"ink";import lr from"react";var Id=({filters:e})=>lr.createElement(bd,{columnGap:1},lr.createElement(Ai,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:r,operator:n})=>lr.createElement(Ai,{backgroundColor:"black",color:"white"},` ${r}${n}"${t}" `))),wi=lr.memo(Id);function mr({filters:e,hideBreadCrumb:t=!1}){let{userName:r,preferredEditor:n}=ce(),o=40,i=process.stdout.columns-o-8;return Se.createElement(gn,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?Se.createElement(Ri,null," "):Se.createElement(gn,{paddingLeft:1},e.length>0?Se.createElement(wi,{filters:e}):Se.createElement(Si,{width:i})),Se.createElement(gn,{columnGap:1,paddingRight:2,"max-width":o,overflow:"hidden",justifyContent:"flex-end"},Se.createElement(Mi,{icon:"@",value:r}),Se.createElement(Mi,{icon:"\u276F",value:n})))}function Mi({icon:e,value:t}){return Se.createElement(Ri,null,Ti.dim(e)+Ti.hex(h.accent)(` ${t??"-"} `))}import{Box as zd,Text as qd}from"ink";import St from"react";import{Box as ur,Text as fn}from"ink";import ke from"react";import{Text as Li}from"ink";import Pi,{useEffect as Di,useState as Sd}from"react";var Fi={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},ee=({isSelected:e,placeholder:t=" "})=>{let{mode:r}=_(),n=Fi[r]??Fi.default,[o,i]=Sd(0);if(Di(()=>{i(0)},[n]),Di(()=>{if(!e)return;let l=setInterval(()=>{i(m=>(m+1)%n.length)},500);return()=>clearInterval(l)},[e,n]),!e)return Pi.createElement(Li,null,t);let a=n[o]??n[0]??t;return Pi.createElement(Li,{color:h.accent,dimColor:o===1},a)};function yn(){let e=_(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,a=t?.id?M(t?.id):[];return ke.createElement(ur,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:h.secondary,width:i},ke.createElement(ur,{padding:1,paddingTop:0,paddingBottom:0},ke.createElement(fn,null,"Select a board:")),ke.createElement(ur,{padding:1,flexDirection:"column"},a.map((l,m)=>{let u=e.currentNode.context==="WORKSPACE"&&e.selectedIndex===m,y=M(l.id).flatMap(({id:v})=>W(v)).length;return ke.createElement(ur,{key:l.id??m},ke.createElement(fn,{color:u?h.accent:h.secondary},ke.createElement(ee,{isSelected:u})),ke.createElement(fn,{color:u?h.accent:h.secondary},l.title," (",y," issues)",l.readonly?" \u{1F512}":""))})))}import{Box as Vd}from"ink";import vr from"react";import{Box as hn,Text as Rd}from"ink";import fe from"react";import{Box as xn,Text as Ad}from"ink";import pr from"react";var gr=({children:e=[],height:t,selectedIndex:r,itemHeight:n=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),a=Math.max(1,Math.ceil(n)),l=Math.max(1,Math.floor(i/a)),m=Math.max(0,Math.min(r,e.length-1)),u=Math.max(0,e.length-l),p=o?Math.min(u,Math.max(0,m-l+1)):Math.min(u,Math.floor(m/l)*l),y=p+l,v=e.slice(p,y),I=e.length>l,S=i,N=I?Math.max(1,Math.floor(l/e.length*S)):S,b=Math.max(0,S-N),T=Math.max(1,e.length-l),B=I?Math.floor(p/T*b):0;return pr.createElement(xn,{flexDirection:"row",height:i,width:"100%"},pr.createElement(xn,{flexDirection:"column",flexGrow:1,height:i},v),pr.createElement(xn,{flexDirection:"column",width:1,height:S},Array.from({length:S}).map((V,te)=>pr.createElement(Ad,{key:te,color:I&&te>=B&&te<B+N?h.accent:h.secondary},I?"\u2502":" "))))};import{Box as fr,Text as wd}from"ink";import Ve from"react";var ki=({width:e,ticket:t,isSelected:r})=>{let n=e-14,o=Mt(Ln(t.title),n),i=M(t.id),a=u=>{let p=i.find(y=>y.title===u);return p?M(p.id).map(y=>typeof y.props?.value=="string"?y.props.value:"").filter(y=>!!y):[]},l=a("Tags").map(u=>E.getTag(u)).filter(u=>!!u),m=a("Assignees").map(u=>E.getContributor(u)).filter(u=>!!u);return Ve.createElement(fr,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:r?h.accent:h.secondary,justifyContent:"space-between"},Ve.createElement(fr,{borderBottom:!0},Ve.createElement(fr,{paddingLeft:1,flexDirection:"column"},Ve.createElement(wd,{color:h.primary},o))),Ve.createElement(fr,{flexDirection:"row",paddingLeft:1},l.map(u=>Ve.createElement(ct,{key:u.id,id:u.id})),m.map(u=>Ve.createElement(dt,{key:u.id,id:u.id}))))};import Td from"chalk";import{Box as It,Text as vn}from"ink";import Ae from"react";var Md=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Bi=({width:e,ticket:t,isSelected:r,index:n,mode:o})=>{let i=M(t.id),a=N=>{let b=i.find(T=>T.title===N);return b?M(b.id).map(T=>typeof T.props?.value=="string"?T.props.value:"").filter(T=>!!T):[]},l=a("Tags").map(N=>E.getTag(N)).filter(N=>!!N),m=a("Assignees").map(N=>E.getContributor(N)).filter(N=>!!N),u=1,p=l.length*(1+u),y=m.length*(2+u),v=l.map(N=>Ae.createElement(It,{key:N.id,paddingRight:u},Ae.createElement(vn,{color:se(N.name)},"\u25A0"))),I=m.map(N=>Ae.createElement(It,{key:N.id,paddingRight:u},Ae.createElement(vn,{color:pt(N.name)},"@"+N.name.at(0)))),S=r?h.accent:o===g.MOVE?h.secondary:h.primary;return Ae.createElement(It,{borderBottom:!0,justifyContent:"space-between"},Ae.createElement(It,null,Ae.createElement(ee,{isSelected:r,placeholder:Td.dim.gray(n+1+" ")}),Ae.createElement(vn,{wrap:"truncate",color:S},Md(t.title,e-p-y-14))),Ae.createElement(It,null,v,I))};var Ld=({swimlane:e,isSelected:t,width:r,height:n,isDense:o,isFocused:i,listSelectedIndex:a,mode:l})=>{let{renderedChildrenIndex:m}=_(),u=m[e.id]??[],p=`${e.title} (${u.length})`,y=3,v=o?1:4,I=n-y-(o?2:1),S=fe.createElement(hn,{borderStyle:"round",borderColor:h.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},fe.createElement(ee,{isSelected:t}),fe.createElement(Rd,{bold:!0,color:t?h.accent:h.primary},p," ",e.readonly?"\u{1F512}":"")),N=(b,T)=>{let B=i&&a===T;return o?fe.createElement(Bi,{key:b.id,index:T,width:r,ticket:b,isSelected:B,mode:l}):fe.createElement(ki,{key:b.id,width:r,ticket:b,isSelected:B})};return fe.createElement(hn,{flexDirection:"column",width:r,borderStyle:"round",borderColor:t?h.accent:h.secondary,paddingRight:1,paddingLeft:1,height:n},S,fe.createElement(hn,{padding:o?1:0},u.length>0&&fe.createElement(gr,{selectedIndex:a,height:I,itemHeight:v},u.map(N)),fe.createElement(ee,{isSelected:i&&a===-1})))},Oi=fe.memo(Ld);import{Box as En,Text as _d}from"ink";import Be,{useEffect as bn,useMemo as _i}from"react";import we from"chalk";import Wi from"string-width";import{decodeTime as Pd}from"ulid";var Ui=e=>{let t=Date.now()-e,r=[{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:n,ms:o}of r){let i=Math.floor(t/o);if(i>=1)return`${i}${n} ago`}return"just now"};var Dd=(e,t)=>e+" ".repeat(Math.max(0,t-Wi(e))),Fd=(e,t)=>" ".repeat(Math.max(0,t-Wi(e)))+e,kd=e=>(()=>{let r={"add.issue":"Created with title","assign.issue":"Assigned to","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","tag.issue":"Tagged with","lock.node":"Locked node","move.node":"Moved issue"};return(o=>r[o]??(o.endsWith("e")?`${o}d`:`${o}ed`))(e)})(),Bd=e=>{switch(e.action){case"move.node":{let t=E.getNode(e.payload.parent),r=t?we.dim.bgBlack(` ${t.title} `):"unknown",n=e.payload.pos;if(!n)return`to ${r}`;switch(n.at){case"start":return`to ${r} ${we.dim("(to top of list)")}`;case"end":return`to ${r} ${we.dim("(to bottom of list)")}`;case"before":return`to ${r} ${we.dim("(up in list)")}`;case"after":return`to ${r} ${we.dim("(down in list)")}`}}case"tag.issue":{let t=C().tags[e.payload.tagId];return t?we.bgHex(se(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=C().contributors[e.payload.contributor];return t?we.hex(se(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""}},Od=e=>{let t=Ui(Pd(e));return we.gray(Fd(t,8))},Ud=12,Wd=e=>Dd(`${e}`,Ud),Hi=e=>{let t=Od(e.id),r=Wd(e.userName),n=kd(e.action),o=Bd(e),i=we.dim("\u203A"),a=[n,o].filter(Boolean).join(" ");return`${r} ${t} ${i} ${a}`};import{Box as yr,Text as Hd}from"ink";import Te from"react";var $i=({selectedIndex:e,parent:t,selected:r})=>{let{currentNode:n}=_(),{title:o}=t,i=M(t.id).map(a=>{let l=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return E.getContributor(l)?.id;if(o==="Tags")return E.getTag(l)?.id}).filter(a=>!!a);return Te.createElement(yr,{alignItems:"center",paddingTop:1},Te.createElement(yr,{minWidth:12},Te.createElement(ee,{isSelected:r}),Te.createElement(Hd,{color:r?h.accent:h.secondary2},o,":")),Te.createElement(yr,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,l)=>{let m=n.id===t.id&&l===e;return Te.createElement(yr,{key:`${o}-${a}`,paddingRight:2,minHeight:1},Te.createElement(ee,{isSelected:m}),o==="Assignees"?Te.createElement(dt,{isSelected:m,id:a}):o==="Tags"?Te.createElement(ct,{isSelected:m,id:a}):null)})))};import{Box as xr,Text as Cn}from"ink";import Me,{useEffect as $d}from"react";var Nn=({id:e,label:t,text:r,height:n,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:l}=_(),m=v=>String(v).replace(/\r?\n/g,""),u=typeof r=="string"?r.split(/\r?\n|\u2028|\u2029/):[];$d(()=>{let v=[];return u.forEach((I,S)=>{let N=X.text({id:`${S}`,name:`Line ${S+1}`,parentNodeId:e,props:{value:I},readonly:!0}),b=E.createNodeAtPosition(N);ze(b)&&v.push(b.data.id)}),()=>v.forEach(E.deleteNode)},[e,r]);let p="\u2029",y=u.map((v,I)=>{let S=l.id===e&&a===I;return Me.createElement(xr,{key:`${e}-${I}`},Me.createElement(Cn,{color:S?h.primary:h.secondary2,dimColor:!S},`${I+1} `.padStart(5,"\xA0")),Me.createElement(Cn,{backgroundColor:S?"gray":""},m(v.length?Mt(v,i-10):p)))});return Me.createElement(xr,{flexDirection:"column",paddingTop:1},Me.createElement(xr,null,Me.createElement(ee,{isSelected:o}),Me.createElement(Cn,{color:o?h.accent:h.secondary2},t)),Me.createElement(xr,{flexDirection:"row",borderStyle:"round",borderColor:h.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Me.createElement(gr,{scrollByOne:!0,children:y,height:n-2,selectedIndex:a,itemHeight:1})))};var Kd=e=>`${e}::log`,Ki=({ticket:e,height:t})=>{let{selectedIndex:r,currentNode:n}=_(),o=process.stdout.columns||120,i=_i(()=>Kd(e.id),[e.id]),a=_i(()=>[...e.log].reverse().map(Hi).join(`
41
- `),[e.log]);bn(()=>{if(E.getNode(i))return;let T={...X.field(i,"Log",e.id,{value:a}),readonly:!0,childRenderAxis:"vertical"};return E.createNodeAtPosition(T),()=>{E.deleteNode(i)}},[i,e.id]),bn(()=>{let b=E.getNode(i);b&&b.props.value!==a&&E.updateNode({...b,props:{...b.props,value:a},childRenderAxis:"vertical",readonly:!0})},[i,a]);let l=n.id===e.id,m=n.id===i||n.parentNodeId===i;bn(()=>{m&&(r>=0||O.navigate({selectedIndex:0}))},[m,r]);let u=M(e.id);if(m){let b=E.getNode(i),B=t-3;return Be.createElement(En,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},b?Be.createElement(Nn,{id:b.id,label:"Event log",text:b.props.value??"",selected:!1,maxWidth:o,height:B}):null)}let p=u.reduce((b,T)=>T.title==="Assignees"||T.title==="Tags"||T.id===i?++b:b,0),y=2,v=p*1,S=t-3-v-y,N=(b,T)=>b.title==="Assignees"||b.title==="Tags"?Be.createElement($i,{key:b.id,parent:b,selected:T,selectedIndex:r}):b.id===i?Be.createElement(En,{key:b.id,paddingTop:1},Be.createElement(ee,{isSelected:T}),Be.createElement(_d,{backgroundColor:h.secondary,color:T?h.accent:h.primary}," History \u203A\u203A ")):Be.createElement(Nn,{label:"Description (press e to edit)",key:b.id,id:b.id,text:b.props.value??"",selected:T,maxWidth:o,height:S});return Be.createElement(En,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},u.map((b,T)=>N(b,l&&r===T)))};var jd=({swimlanes:e,currentNode:t,selectedIndex:r,breadCrumb:n,mode:o,viewMode:i,height:a,width:l})=>{let m=t.context,u=m===L.TICKET||m===L.FIELD_LIST||m===L.FIELD,p=m===L.BOARD||m===L.SWIMLANE,y=m===L.TICKET?t:n.find(b=>b.context===L.TICKET),v=Math.floor(l/3),I=Math.floor(l/Math.max(e.length,1)),S=Math.min(I,v),N=i==="dense";return vr.createElement(Vd,{flexDirection:"row",height:a},p&&e.map((b,T)=>{let B=t.id===b.id,V=B?r:-1,te=t.context===L.BOARD&&r===T;return vr.createElement(Oi,{key:b.id,height:a,width:S,swimlane:b,isSelected:te,isDense:N,isFocused:B,listSelectedIndex:V,mode:o})}),u&&y&&vr.createElement(Ki,{height:a,ticket:y}))},Vi=vr.memo(jd);var Gd=({currentNode:e,selectedIndex:t,breadCrumb:r,mode:n,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:l}=_(),m=r.find(({context:v})=>v==="BOARD"),y=i-1-3;return St.createElement(zd,{flexDirection:"row"},e.context==="WORKSPACE"?St.createElement(yn,null):m?St.createElement(Vi,{height:y,width:a,swimlanes:(l[m.id]??[]).filter(v=>v!==void 0&&Mn(v)),currentNode:e,selectedIndex:t,breadCrumb:r,viewMode:o,mode:n}):St.createElement(qd,null))},ji=St.memo(Gd);import{Box as At,Text as ye}from"ink";import U from"react";var hr=({isDone:e,command:t,value:r})=>U.createElement(At,null,U.createElement(ye,{color:h.accent,dimColor:e},e?" \u2714 ":" "),U.createElement(ye,{dimColor:e},"Type "),U.createElement(ye,{backgroundColor:h.secondary,dimColor:e}," "+t+" "),r&&U.createElement(U.Fragment,null,U.createElement(ye,{dimColor:e}," "),U.createElement(ye,{color:h.secondary,dimColor:e},"<"+r+">")));function In({width:e,height:t,hasUserName:r,hasPreferredEditor:n,userName:o,preferredEditor:i}){let a=r&&n,l=r?n?null:":set:editor":":set:username";return U.createElement(At,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},U.createElement(ye,{color:h.accent,bold:!0},"Welcome! \u{1F539}"),U.createElement(ye,null,"Lets get you started - its a breeze."),U.createElement(ye,{color:h.secondary2},"And remember, you can always get help with"," ",U.createElement(ye,{color:h.accent},":help"),"."),!a&&U.createElement(ye,{color:h.secondary2},l===":set:username"?"First, choose your username.":"Nice. One more step."),U.createElement(At,{flexDirection:"column"},r&&U.createElement(At,{marginBottom:1},U.createElement(hr,{isDone:!0,command:":set:username",value:o})),!r&&U.createElement(hr,{isDone:!1,command:":set:username"}),r&&!n&&U.createElement(hr,{isDone:!1,command:":set:editor"}),a&&U.createElement(At,null,U.createElement(hr,{isDone:!0,command:":set:editor",value:i}))))}var Xd=({width:e,height:t})=>k.createElement(me,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},k.createElement(Oe,{color:h.accent,bold:!0},"Initialize project"),k.createElement(Oe,null,`This folder is not an ${Jd.hex(h.accent)("epiq")} project yet.`),k.createElement(Oe,{color:h.primary},"To start tracking issues here, we need to initialize a new"," ",k.createElement(Oe,{color:h.primary,backgroundColor:h.secondary}," .epiq/ ")," ","directory in this repository."),k.createElement(me,{marginTop:1,flexDirection:"column"},k.createElement(me,null,k.createElement(Oe,{color:h.accent}," "),k.createElement(Oe,{color:h.primary},"Type "),k.createElement(Oe,{backgroundColor:h.secondary}," :init "))),k.createElement(me,{marginTop:1},k.createElement(Oe,{color:h.secondary2},"(This will create the local epiq project files)")));function Sn({width:e,height:t}){let r=_(),n=r.filters;if(r.mode===g.HELP)return k.createElement(me,{flexDirection:"column"},k.createElement(Ii,{width:e}));let{isSetup:o,hasPreferredEditor:i,hasUserName:a,userName:l,preferredEditor:m}=Dt(),u=!o,p=o&&He();if(u)return k.createElement(me,{flexDirection:"column"},k.createElement(me,{flexDirection:"column"},k.createElement(mr,{hideBreadCrumb:!0,filters:n}),k.createElement(In,{height:t,width:e,hasUserName:a,hasPreferredEditor:i,userName:l??"",preferredEditor:m??""})),k.createElement(cr,{width:e,mode:r.mode,availableHints:r.availableHints}));if(p)return k.createElement(me,{flexDirection:"column"},k.createElement(me,{flexDirection:"column"},k.createElement(mr,{hideBreadCrumb:!0,filters:n}),k.createElement(Xd,{height:t,width:e})),k.createElement(cr,{width:e,mode:r.mode,availableHints:r.availableHints}));let y=nt(C().breadCrumb??[],"BOARD");if(ze(y)){let v=y.data.id,I=M(v).length,S=3,N=Math.floor(e/S),b=Math.floor(e/Math.max(I,1));e=Math.min(b,N)*Math.max(I,S)}return k.createElement(me,{flexDirection:"column"},k.createElement(me,{flexDirection:"column"},k.createElement(mr,{filters:n}),k.createElement(ji,{width:e,height:t,currentNode:r.currentNode,selectedIndex:r.selectedIndex,breadCrumb:r.breadCrumb,viewMode:r.viewMode,mode:r.mode})),k.createElement(cr,{width:e,mode:r.mode,availableHints:r.availableHints}))}import{Box as je,Text as Ue}from"ink";import J,{useEffect as Yd,useMemo as Qd,useState as Zd}from"react";var ec=["\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 ","\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551","\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551\u2584\u2584 \u2588\u2588\u2551","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D","\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2580\u2580\u255D "];function tc(e,t,r){return Math.min(r,Math.max(t,e))}function rc(e,t){return J.createElement(Ue,null,J.createElement(Ue,{color:t%2===0?"cyan":"blue",bold:!0},e.slice(0,14)),J.createElement(Ue,{color:t%2===0?"cyan":"blue",bold:!0},e.slice(14)))}function nc(e,t=28){if(e>=1)return"\u2588".repeat(t);let r=Math.floor(e*(t-1));return Array.from({length:t},(n,o)=>{let i=Math.abs(o-r);return i===0?"\u2588":i===1?"\u2593":i===2?"\u2592":i===3?"\u2591":o<r?"\u2500":"\xB7"}).join("")}function An({durationMs:e=3e3,slogan:t="Never leave the command line"}){let r=Math.max(1,e),[n,o]=Zd(0);Yd(()=>{let m=Date.now(),u=setInterval(()=>{let p=Date.now()-m;if(p>=r){o(r),clearInterval(u);return}o(p)},33);return()=>clearInterval(u)},[r]);let i=tc(n/r,0,1),a=Qd(()=>nc(i,28),[i]),l=`${Math.round(i*100)}%`;return J.createElement(je,{flexDirection:"column",alignItems:"center",justifyContent:"center",paddingX:4,paddingY:1},J.createElement(je,{flexDirection:"column",minWidth:42},J.createElement(je,{flexDirection:"column",marginBottom:1},ec.map((m,u)=>J.createElement(je,{key:u,justifyContent:"center"},rc(m,u)))),J.createElement(je,{justifyContent:"center",marginBottom:1},J.createElement(Ue,{color:"gray"},t)),J.createElement(je,{justifyContent:"center",marginBottom:1},J.createElement(Ue,{color:"cyan"},a.slice(0,10)),J.createElement(Ue,{color:"blue"},a.slice(10,18)),J.createElement(Ue,{color:"magenta"},a.slice(18))),J.createElement(je,{justifyContent:"center",marginBottom:1},J.createElement(Ue,{color:"gray"},l))))}import oc from"readline";var Cr,Nr,xe,zi=async e=>{if(e.ctrl&&e.name==="c")return O.exit();let{actionIndex:t,mode:r}=C(),n=oo(e,r);if(!n)return;let o=t[r]?.[n];if(o?.action)try{await o.action(o,e)}catch(i){logger.error(i)}},ic=()=>async function(t,r){r.name!=="escape"&&(xe&&(clearTimeout(xe),xe=void 0),await zi(r))},sc=()=>async function(t){if(t.length===1&&t[0]===27){xe&&clearTimeout(xe),xe=setTimeout(()=>{zi({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),xe=void 0},25);return}xe&&(clearTimeout(xe),xe=void 0)};function qi(){Cr&&process.stdin.removeListener("keypress",Cr),Nr&&process.stdin.removeListener("data",Nr),Cr=ic(),Nr=sc(),oc.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Nr),process.stdin.on("keypress",Cr)}import wn from"chalk";dc(`${wn.bold("Epiq CLI")}
40
+ `)):(hd(),m("State booted successfully",null))}import{Box as Ud}from"ink";import Nr from"react";import Tt from"chalk";import{Box as Er,Text as Ti}from"ink";import At,{useEffect as Cd,useMemo as Nd,useState as bd}from"react";var wi=Tt.gray,Id=Tt.inverse,Sd=Tt.inverse.gray,Ad={hint:"",hints:[],overlap:0,remainder:""},Ri=({value:e,command:t})=>{if(!t)return null;let n=e.trimStart(),o=e.length-n.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},Td=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=me(t);return{bg:r=>Tt.bgHex(n).black(r),bgCursor:r=>Tt.bgHex(n).inverse.black(r)}}return Wn(t)},wd=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Ri({value:e,command:t});if(!r)return null;let i=e.slice(r.end).match(/^\s*/)?.[0].length??0,a=r.end+i;return e.slice(a,a+n.length)!==n?null:{start:a,end:a+n.length}},Mi=()=>({value:Y.value,cursorPosition:Y.cursorPosition,commandIsPending:Y.commandIsPending,autoCompletion:Y.commandMeta.autoCompletion??Ad,infoMessage:Y.commandMeta.infoMessage,validationStatus:Y.commandMeta.validity,command:Y.commandMeta.command,inputString:Y.commandMeta.inputString,modifier:Y.commandMeta.modifier}),Md=(e,t)=>e.value===t.value&&e.cursorPosition===t.cursorPosition&&e.commandIsPending===t.commandIsPending&&e.infoMessage===t.infoMessage&&e.autoCompletion.hint===t.autoCompletion.hint&&e.autoCompletion.overlap===t.autoCompletion.overlap&&e.autoCompletion.remainder===t.autoCompletion.remainder&&e.validationStatus===t.validationStatus&&e.command===t.command&&e.modifier===t.modifier&&e.inputString===t.inputString,Li=({width:e})=>{let[t,n]=bd(Mi());Cd(()=>{let y=()=>{let b=Mi();n(I=>Md(I,b)?I:b)},C=lo(y);return y(),()=>{C()}},[]);let{value:r,cursorPosition:o,infoMessage:i,commandIsPending:a,autoCompletion:d,command:l,modifier:u}=t,p=Nd(()=>{let y=Math.max(0,Math.min(o,r.length)),C=Ri({value:r,command:l}),b=wd({value:r,command:l,modifier:u}),I=l?Wn(l):null,A=Td({command:l,modifier:u}),S=(ie,se)=>{let Rn=C&&se>=C.start&&se<C.end,Ln=b&&se>=b.start&&se<b.end;return Rn&&I?I.fg(ie):Ln&&A?A.bg(ie):ie},M=(ie,se)=>{let Rn=C&&se>=C.start&&se<C.end,Ln=b&&se>=b.start&&se<b.end;return Rn&&I?I.fgCursor(ie):Ln&&A?A.bgCursor(ie):Id(ie)},B=r.slice(0,y),G=r[y]??" ",oe=y<r.length?r.slice(y+1):"",Lt=Array.from(B).map((ie,se)=>S(ie,se)).join(""),De=M(G,y),Br=Array.from(oe).map((ie,se)=>S(ie,y+1+se)).join("");if(d.hint){let ie=d.hint[d.overlap]??G;De=Sd(ie),Br=wi(d.remainder.slice(1)+oe)}return wi(":")+Lt+De+Br},[r,o,d,l,u]);return At.createElement(Er,{flexDirection:"column",justifyContent:"flex-start"},At.createElement(Er,{flexDirection:"column",paddingX:1,borderColor:E.secondary,borderStyle:"round",width:e},At.createElement(Er,null,At.createElement(Ti,null,p),i&&At.createElement(Ti,{wrap:"truncate",color:a?E.red:E.secondary2},` ${i} `))))};import Pi from"chalk";import{Box as Rd,Text as Cr}from"ink";import gn,{useEffect as Ld,useState as Pd}from"react";var Dd=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Di=e=>{let t=e.replace("#","");return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}},Fd=({r:e,g:t,b:n})=>{let r=o=>Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0");return`#${r(e)}${r(t)}${r(n)}`},kd=(e,t,n)=>{let r=Di(e),o=Di(t);return Fd({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Od=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,i=e[r],a=e[Math.min(r+1,e.length-1)];return kd(i,a,o)},Bd=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),Fi=({width:e,availableHints:t})=>{let{syncStatus:{status:n,msg:r}}=W(),[o,i]=Pd(0);Ld(()=>{if(n!=="syncing"){i(0);return}let S=setInterval(()=>{i(M=>M+1)},50);return()=>clearInterval(S)},[n]);let a=[],d=0;for(let S of t){let B=(a.length>0?" | ":"").length+S.length;if(d+B>e-4)break;a.push(S),d+=B}let l=n!="synced"?r??a.join(" | "):a.join(" | "),u=Math.max(0,e-2),p=n==="syncing"?Od(Dd,(Math.sin(o*.12)+1)/2):E.secondary,y=Pi.hex(p??"fff"),C=Pi.hex(E.secondary2),b=y(`\u256D${"\u2500".repeat(u)}\u256E`),I=y(`\u2570${"\u2500".repeat(u)}\u256F`),A=`${y("\u2502")}${C(Bd(` ${l} `,u))}${y("\u2502")}`;return gn.createElement(Rd,{flexDirection:"column",width:e},gn.createElement(Cr,null,b),gn.createElement(Cr,null,A),gn.createElement(Cr,null,I))};var fn=({width:e,mode:t,availableHints:n})=>{let r=W(),o=[],i=0;for(let a of n){let l=(o.length>0?" | ":"").length+a.length;if(i+l>e+2)break;o.push(a),i+=l}return Nr.createElement(Ud,null,t===f.COMMAND_LINE&&r.syncStatus.status!=="syncing"?Nr.createElement(Li,{width:e}):Nr.createElement(Fi,{width:e,mode:t,availableHints:n}))};import{Box as ct,Text as ki}from"ink";import Be from"react";var Oi=({width:e})=>{let t=[...h().availableActions].map(n=>n.description).filter(n=>n!==void 0).map(n=>{let[r,o]=n.split("]"),i=r?.replace("[",""),a=o?.trim();return[i,a]}).filter(n=>n[0]!==void 0&&n[1]!==void 0).sort(([n],[r])=>n.length===1&&r.length!==1?-1:n.length!==1&&r.length===1?1:n.localeCompare(r,void 0,{sensitivity:"base"}));return t.unshift(["Key(s)","Action"]),Be.createElement(ct,{flexDirection:"column",marginTop:3,borderColor:E.secondary,borderStyle:"round",width:e,minHeight:19},Be.createElement(ct,{flexDirection:"column",width:e},h().mode===f.HELP?t.map(([n,r],o)=>Be.createElement(ct,{paddingLeft:1,key:o,flexDirection:"row"},Be.createElement(ct,{key:o,flexDirection:"row",paddingBottom:o?0:1},Be.createElement(ct,{width:20,justifyContent:"flex-end"},Be.createElement(ki,{color:o?E.accent:E.secondary},n)),Be.createElement(ct,{flexGrow:1,width:40,paddingLeft:2},Be.createElement(ki,{color:o?E.primary:E.secondary},r))))):null))};import Hi from"chalk";import{Box as xn,Text as Ge}from"ink";import Q from"react";import{Box as br,Text as jd}from"ink";import ut from"react";import{Text as Wd}from"ink";import Hd from"react";var _d=e=>e.toLowerCase().trim(),$d=(e,t=Qe)=>{let n=_d(e);return t[n]?t[n]:ft(n)},lt=({id:e,isSelected:t})=>{let n=N.getContributor(e);if(n)return Hd.createElement(Wd,{underline:t,color:$d(n.name)},"@"+n.name)};import{Text as Kd}from"ink";import Vd from"react";var mt=({id:e,isSelected:t})=>{let n=N.getTag(e);if(n)return Vd.createElement(Kd,{underline:t,backgroundColor:me(n.name),color:E.primary}," "+n.name+" ")};var zd=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",Bi=({width:e})=>{let{breadCrumb:t,currentNode:n,selectedIndex:r,viewMode:o}=h(),i=_(n.id)[r],a=Xe(i?.id??n.id,"TICKET"),d=Fe(a)?a.data:void 0,l=d?.id?_(d.id):[],u=A=>{let S=l.find(M=>M.title===A);return S?_(S.id).map(M=>typeof M.props?.value=="string"?M.props.value:"").filter(M=>!!M):[]},p=u("Tags"),y=u("Assignees"),C=d?.parentNodeId?!kn(n.id,d?.parentNodeId)&&o==="dense":!1,b=t.map((A,S)=>{let M=S===t.length-1,B=_(A.id),G=M?B?.[r]?.title:void 0;return`${S?" / ":""}${A.title??""}${G?` \u25B8 ${G}`:""}`}).join(""),I=zd(b,e);return ut.createElement(br,null,ut.createElement(jd,{color:E.secondary2},I),C?p.map(A=>ut.createElement(br,{key:A,paddingLeft:2},ut.createElement(mt,{id:A}))):null,C?y.map(A=>ut.createElement(br,{key:A,paddingLeft:2},ut.createElement(lt,{id:A}))):null)};import{Box as Gd,Text as Ui}from"ink";import yn from"react";var qd=({filters:e})=>yn.createElement(Gd,{columnGap:1},yn.createElement(Ui,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>yn.createElement(Ui,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Wi=yn.memo(qd);function vn({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o}=W(),{userName:i,preferredEditor:a}=pe(),d=40,l=process.stdout.columns-d-8,u=r.at(-1)?.id,p=Wt(u??""),y=Fe(p)?Zr(p.data):"INVALID DATE";return Q.createElement(xn,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?Q.createElement(Ge,null," "):Q.createElement(xn,{paddingLeft:1},e.length>0?Q.createElement(Wi,{filters:e}):Q.createElement(Bi,{width:l})),n==="live"?Q.createElement(xn,{columnGap:1,paddingRight:2,"max-width":d,overflow:"hidden",justifyContent:"flex-end"},Q.createElement(_i,{icon:"@",value:i}),Q.createElement(_i,{icon:"\u276F",value:a})):"",n==="peek"?Q.createElement(xn,{paddingLeft:1},Q.createElement(Ge,{backgroundColor:E.yellow}," Readonly "),Q.createElement(Ge,{color:E.yellow}," "+o.length+" edits ago at "),Q.createElement(Ge,{backgroundColor:E.yellow,color:E.accent}," "+y+" "),Q.createElement(Ge,{color:E.yellow},". Resume with "),Q.createElement(Ge,{backgroundColor:E.yellow}," :peek now ")):"")}function _i({icon:e,value:t}){return Q.createElement(Ge,null,Hi.dim(e)+Hi.hex(E.accent)(` ${t??"-"} `))}import{Box as yc,Text as xc}from"ink";import Mt from"react";import{Box as hn,Text as Ir}from"ink";import Ue from"react";import{Text as $i}from"ink";import Ki,{useEffect as Vi,useState as Yd}from"react";var ji={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},re=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=W(),r=ji[n]??ji.default,[o,i]=Yd(0);if(Vi(()=>{i(0)},[r]),Vi(()=>{if(!e)return;let d=setInterval(()=>{i(l=>(l+1)%r.length)},500);return()=>clearInterval(d)},[e,r]),!e)return Ki.createElement($i,null,t);let a=r[o]??r[0]??t;return Ki.createElement($i,{color:E.accent,dimColor:o===1},a)};function Sr(){let e=W(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,a=t?.id?R(t?.id):[];return Ue.createElement(hn,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:E.secondary,width:i},Ue.createElement(hn,{padding:1,paddingTop:0,paddingBottom:0},Ue.createElement(Ir,null,"Select a board:")),Ue.createElement(hn,{padding:1,flexDirection:"column"},a.map((d,l)=>{let u=e.currentNode.context==="WORKSPACE"&&e.selectedIndex===l,y=R(d.id).flatMap(({id:C})=>_(C)).length;return Ue.createElement(hn,{key:d.id??l},Ue.createElement(Ir,{color:u?E.accent:E.secondary},Ue.createElement(re,{isSelected:u})),Ue.createElement(Ir,{color:u?E.accent:E.secondary},d.title," (",y," issues)",d.readonly?" \u{1F512}":""))})))}import{Box as gc}from"ink";import Sn from"react";import{Box as wr,Text as ec}from"ink";import he from"react";import{Box as Ar,Text as Jd}from"ink";import En from"react";var Cn=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),a=Math.max(1,Math.ceil(r)),d=Math.max(1,Math.floor(i/a)),l=Math.max(0,Math.min(n,e.length-1)),u=Math.max(0,e.length-d),p=o?Math.min(u,Math.max(0,l-d+1)):Math.min(u,Math.floor(l/d)*d),y=p+d,C=e.slice(p,y),b=e.length>d,I=i,A=b?Math.max(1,Math.floor(d/e.length*I)):I,S=Math.max(0,I-A),M=Math.max(1,e.length-d),B=b?Math.floor(p/M*S):0;return En.createElement(Ar,{flexDirection:"row",height:i,width:"100%"},En.createElement(Ar,{flexDirection:"column",flexGrow:1,height:i},C),En.createElement(Ar,{flexDirection:"column",width:1,height:I},Array.from({length:I}).map((G,oe)=>En.createElement(Jd,{key:oe,color:b&&oe>=B&&oe<B+A?E.accent:E.secondary},b?"\u2502":" "))))};import{Box as Nn,Text as Xd}from"ink";import qe from"react";var zi=(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):[]},Gi=e=>zi(e,"Tags").map(t=>N.getTag(t)).filter(t=>!!t),qi=e=>zi(e,"Assignees").map(t=>N.getContributor(t)).filter(t=>!!t);var Yi=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=Dt(Pn(t.title),r),i=Gi(t),a=qi(t);return qe.createElement(Nn,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?E.accent:E.secondary,justifyContent:"space-between"},qe.createElement(Nn,{borderBottom:!0},qe.createElement(Nn,{paddingLeft:1,flexDirection:"column"},qe.createElement(Xd,{color:E.primary},o))),qe.createElement(Nn,{flexDirection:"row",paddingLeft:1},i.map(d=>qe.createElement(mt,{key:d.id,id:d.id})),a.map(d=>qe.createElement(lt,{key:d.id,id:d.id}))))};import Qd from"chalk";import{Box as wt,Text as Tr}from"ink";import Me from"react";var Zd=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Ji=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=R(t.id),a=A=>{let S=i.find(M=>M.title===A);return S?R(S.id).map(M=>typeof M.props?.value=="string"?M.props.value:"").filter(M=>!!M):[]},d=a("Tags").map(A=>N.getTag(A)).filter(A=>!!A),l=a("Assignees").map(A=>N.getContributor(A)).filter(A=>!!A),u=1,p=d.length*(1+u),y=l.length*(2+u),C=d.map(A=>Me.createElement(wt,{key:A.id,paddingRight:u},Me.createElement(Tr,{color:me(A.name)},"\u25A0"))),b=l.map(A=>Me.createElement(wt,{key:A.id,paddingRight:u},Me.createElement(Tr,{color:ft(A.name)},"@"+A.name.at(0)))),I=n?E.accent:o===f.MOVE?E.secondary:E.primary;return Me.createElement(wt,{borderBottom:!0,justifyContent:"space-between"},Me.createElement(wt,null,Me.createElement(re,{isSelected:n,placeholder:Qd.dim.gray(r+1+" ")}),Me.createElement(Tr,{wrap:"truncate",color:I},Zd(t.title,e-p-y-14))),Me.createElement(wt,null,C,b))};var tc=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:a,mode:d})=>{let{renderedChildrenIndex:l}=W(),u=l[e.id]??[],p=`${e.title} (${u.length})`,y=3,C=o?1:4,b=r-y-(o?2:1),I=he.createElement(wr,{borderStyle:"round",borderColor:E.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},he.createElement(re,{isSelected:t}),he.createElement(ec,{bold:!0,color:t?E.accent:E.primary},p," ",e.readonly?"\u{1F512}":"")),A=(S,M)=>{let B=i&&a===M;return o?he.createElement(Ji,{key:S.id,index:M,width:n,ticket:S,isSelected:B,mode:d}):he.createElement(Yi,{key:S.id,width:n,ticket:S,isSelected:B})};return he.createElement(wr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?E.accent:E.secondary,paddingRight:1,paddingLeft:1,height:r},I,he.createElement(wr,{padding:o?1:0},u.length>0&&he.createElement(Cn,{selectedIndex:a,height:b,itemHeight:C},u.map(A)),he.createElement(re,{isSelected:i&&a===-1})))},Xi=he.memo(tc);import{Box as Lr,Text as uc}from"ink";import We,{useEffect as Pr,useMemo as ts}from"react";import Re from"chalk";import Qi from"string-width";import{decodeTime as nc}from"ulid";var rc=(e,t)=>e+" ".repeat(Math.max(0,t-Qi(e))),oc=(e,t)=>" ".repeat(Math.max(0,t-Qi(e)))+e,ic=e=>(()=>{let n={"add.issue":"Created with title","assign.issue":"Assigned to","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","tag.issue":"Tagged with","lock.node":"Locked node","move.node":"Moved issue"};return(o=>n[o]??(o.endsWith("e")?`${o}d`:`${o}ed`))(e)})(),sc=e=>{switch(e.action){case"move.node":{let t=N.getNode(e.payload.parent),n=t?Re.dim.bgBlack(` ${t.title} `):"unknown",r=e.payload.pos;if(!r)return`to ${n}`;switch(r.at){case"start":return`to ${n} ${Re.dim("(to top of list)")}`;case"end":return`to ${n} ${Re.dim("(to bottom of list)")}`;case"before":return`to ${n} ${Re.dim("(up in list)")}`;case"after":return`to ${n} ${Re.dim("(down in list)")}`}}case"tag.issue":{let t=h().tags[e.payload.tagId];return t?Re.bgHex(me(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=h().contributors[e.payload.contributor];return t?Re.hex(me(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""}},ac=e=>{let t=Qr(nc(e));return Re.gray(oc(t,8))},dc=12,cc=e=>rc(`${e}`,dc),Zi=e=>{let t=ac(e.id),n=cc(e.userName),r=ic(e.action),o=sc(e),i=Re.dim("\u203A"),a=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${a}`};import{Box as bn,Text as lc}from"ink";import Le from"react";var es=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=W(),{title:o}=t,i=R(t.id).map(a=>{let d=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return N.getContributor(d)?.id;if(o==="Tags")return N.getTag(d)?.id}).filter(a=>!!a);return Le.createElement(bn,{alignItems:"center",paddingTop:1},Le.createElement(bn,{minWidth:12},Le.createElement(re,{isSelected:n}),Le.createElement(lc,{color:n?E.accent:E.secondary2},o,":")),Le.createElement(bn,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,d)=>{let l=r.id===t.id&&d===e;return Le.createElement(bn,{key:`${o}-${a}`,paddingRight:2,minHeight:1},Le.createElement(re,{isSelected:l}),o==="Assignees"?Le.createElement(lt,{isSelected:l,id:a}):o==="Tags"?Le.createElement(mt,{isSelected:l,id:a}):null)})))};import{Box as In,Text as Mr}from"ink";import Pe,{useEffect as mc}from"react";var Rr=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:d}=W(),l=C=>String(C).replace(/\r?\n/g,""),u=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];mc(()=>{let C=[];return u.forEach((b,I)=>{let A=ee.text({id:`${I}`,name:`Line ${I+1}`,parentNodeId:e,props:{value:b},readonly:!0}),S=N.createNodeAtPosition(A);Fe(S)&&C.push(S.data.id)}),()=>C.forEach(N.deleteNode)},[e,n]);let p="\u2029",y=u.map((C,b)=>{let I=d.id===e&&a===b;return Pe.createElement(In,{key:`${e}-${b}`},Pe.createElement(Mr,{color:I?E.primary:E.secondary2,dimColor:!I},`${b+1} `.padStart(5,"\xA0")),Pe.createElement(Mr,{backgroundColor:I?"gray":""},l(C.length?Dt(C,i-10):p)))});return Pe.createElement(In,{flexDirection:"column",paddingTop:1},Pe.createElement(In,null,Pe.createElement(re,{isSelected:o}),Pe.createElement(Mr,{color:o?E.accent:E.secondary2},t)),Pe.createElement(In,{flexDirection:"row",borderStyle:"round",borderColor:E.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Pe.createElement(Cn,{scrollByOne:!0,children:y,height:r-2,selectedIndex:a,itemHeight:1})))};var pc=e=>`${e}::log`,ns=e=>e==="Assignees"||e==="Tags",rs=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=W(),o=process.stdout.columns||120,i=ts(()=>pc(e.id),[e.id]),a=ts(()=>[...e.log].reverse().map(Zi).join(`
41
+ `),[e.log]);Pr(()=>{if(N.getNode(i))return;let M={...ee.field(i,"Log",e.id,{value:a}),readonly:!0,childRenderAxis:"vertical"};return N.createNodeAtPosition(M),()=>{N.deleteNode(i)}},[i,e.id,a]),Pr(()=>{let S=N.getNode(i);S&&S.props.value!==a&&N.updateNode({...S,props:{...S.props,value:a},childRenderAxis:"vertical",readonly:!0})},[i,a]);let d=r.id===e.id,l=r.id===i||r.parentNodeId===i;Pr(()=>{l&&(n>=0||U.navigate({selectedIndex:0}))},[l,n]);let u=R(e.id);if(l){let S=N.getNode(i),B=t-3;return We.createElement(Lr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},S?We.createElement(Rr,{id:S.id,label:"Event log",text:S.props.value??"",selected:!1,maxWidth:o,height:B}):null)}let p=u.reduce((S,M)=>ns(M.title)||M.id===i?S+1:S,0),y=2,C=p*1,I=t-3-C-y,A=(S,M)=>ns(S.title)?We.createElement(es,{key:S.id,parent:S,selected:M,selectedIndex:n}):S.id===i?We.createElement(Lr,{key:S.id,paddingTop:1},We.createElement(re,{isSelected:M}),We.createElement(uc,{backgroundColor:E.secondary,color:M?E.accent:E.primary}," History \u203A\u203A ")):S.title==="Description"?We.createElement(Rr,{label:"Description (press e to edit)",key:S.id,id:S.id,text:S.props.value??"",selected:M,maxWidth:o,height:I}):null;return We.createElement(Lr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},u.map((S,M)=>A(S,d&&n===M)))};var fc=({swimlanes:e,currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:a,width:d})=>{let l=t.context,u=l===P.TICKET||l===P.FIELD_LIST||l===P.FIELD,p=l===P.BOARD||l===P.SWIMLANE,y=l===P.TICKET?t:r.find(S=>S.context===P.TICKET),C=Math.floor(d/3),b=Math.floor(d/Math.max(e.length,1)),I=Math.min(b,C),A=i==="dense";return Sn.createElement(gc,{flexDirection:"row",height:a},p&&e.map((S,M)=>{let B=t.id===S.id,G=B?n:-1,oe=t.context===P.BOARD&&n===M;return Sn.createElement(Xi,{key:S.id,height:a,width:I,swimlane:S,isSelected:oe,isDense:A,isFocused:B,listSelectedIndex:G,mode:o})}),u&&y&&Sn.createElement(rs,{height:a,ticket:y}))},os=Sn.memo(fc);var vc=({currentNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:d}=W(),l=n.find(({context:C})=>C==="BOARD"),y=i-1-3;return Mt.createElement(yc,{flexDirection:"row"},e.context==="WORKSPACE"?Mt.createElement(Sr,null):l?Mt.createElement(os,{height:y,width:a,swimlanes:(d[l.id]??[]).filter(C=>C!==void 0&&Ur(C)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Mt.createElement(xc,null))},is=Mt.memo(vc);import{Box as Rt,Text as Ee}from"ink";import H from"react";var An=({isDone:e,command:t,value:n})=>H.createElement(Rt,null,H.createElement(Ee,{color:E.accent,dimColor:e},e?" \u2714 ":" "),H.createElement(Ee,{dimColor:e},"Type "),H.createElement(Ee,{backgroundColor:E.secondary,dimColor:e}," "+t+" "),n&&H.createElement(H.Fragment,null,H.createElement(Ee,{dimColor:e}," "),H.createElement(Ee,{color:E.secondary,dimColor:e},"<"+n+">")));function Dr({width:e,height:t,hasUserName:n,hasPreferredEditor:r,userName:o,preferredEditor:i}){let a=n&&r,d=n?r?null:":set:editor":":set:username";return H.createElement(Rt,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:E.secondary,rowGap:1},H.createElement(Ee,{color:E.accent,bold:!0},"Welcome! \u{1F539}"),H.createElement(Ee,null,"Lets get you started - its a breeze."),H.createElement(Ee,{color:E.secondary2},"And remember, you can always get help with"," ",H.createElement(Ee,{color:E.accent},":help"),"."),!a&&H.createElement(Ee,{color:E.secondary2},d===":set:username"?"First, choose your username.":"Nice. One more step."),H.createElement(Rt,{flexDirection:"column"},n&&H.createElement(Rt,{marginBottom:1},H.createElement(An,{isDone:!0,command:":set:username",value:o})),!n&&H.createElement(An,{isDone:!1,command:":set:username"}),n&&!r&&H.createElement(An,{isDone:!1,command:":set:editor"}),a&&H.createElement(Rt,null,H.createElement(An,{isDone:!0,command:":set:editor",value:i}))))}var Ec=({width:e,height:t})=>O.createElement(fe,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:E.secondary,rowGap:1},O.createElement(He,{color:E.accent,bold:!0},"Initialize project"),O.createElement(He,null,`This folder is not an ${hc.hex(E.accent)("epiq")} project yet.`),O.createElement(He,{color:E.primary},"To start tracking issues here, we need to initialize a new"," ",O.createElement(He,{color:E.primary,backgroundColor:E.secondary}," .epiq/ ")," ","directory in this repository."),O.createElement(fe,{marginTop:1,flexDirection:"column"},O.createElement(fe,null,O.createElement(He,{color:E.accent}," "),O.createElement(He,{color:E.primary},"Type "),O.createElement(He,{backgroundColor:E.secondary}," :init "))),O.createElement(fe,{marginTop:1},O.createElement(He,{color:E.secondary2},"(This will create the local epiq project files)")));function Fr({width:e,height:t}){let n=W(),r=n.filters;if(n.mode===f.HELP)return O.createElement(fe,{flexDirection:"column"},O.createElement(Oi,{width:e}));let{isSetup:o,hasPreferredEditor:i,hasUserName:a,userName:d,preferredEditor:l}=Bt(),u=!o,p=o&&Ke();if(u)return O.createElement(fe,{flexDirection:"column"},O.createElement(fe,{flexDirection:"column"},O.createElement(vn,{hideBreadCrumb:!0,filters:r}),O.createElement(Dr,{height:t,width:e,hasUserName:a,hasPreferredEditor:i,userName:d??"",preferredEditor:l??""})),O.createElement(fn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(p)return O.createElement(fe,{flexDirection:"column"},O.createElement(fe,{flexDirection:"column"},O.createElement(vn,{hideBreadCrumb:!0,filters:r}),O.createElement(Ec,{height:t,width:e})),O.createElement(fn,{width:e,mode:n.mode,availableHints:n.availableHints}));let y=be(h().breadCrumb??[],"BOARD");if(Fe(y)){let C=y.data.id,b=R(C).length,I=3,A=Math.floor(e/I),S=Math.floor(e/Math.max(b,1));e=Math.min(S,A)*Math.max(b,I)}return O.createElement(fe,{flexDirection:"column"},O.createElement(fe,{flexDirection:"column"},O.createElement(vn,{filters:r}),O.createElement(is,{width:e,height:t,currentNode:n.currentNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:n.viewMode,mode:n.mode})),O.createElement(fn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import{Box as Ye,Text as _e}from"ink";import Z,{useEffect as Cc,useMemo as Nc,useState as bc}from"react";var Ic=["\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 ","\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551","\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551\u2584\u2584 \u2588\u2588\u2551","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D","\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2580\u2580\u255D "];function Sc(e,t,n){return Math.min(n,Math.max(t,e))}function Ac(e,t){return Z.createElement(_e,null,Z.createElement(_e,{color:t%2===0?"cyan":"blue",bold:!0},e.slice(0,14)),Z.createElement(_e,{color:t%2===0?"cyan":"blue",bold:!0},e.slice(14)))}function Tc(e,t=28){if(e>=1)return"\u2588".repeat(t);let n=Math.floor(e*(t-1));return Array.from({length:t},(r,o)=>{let i=Math.abs(o-n);return i===0?"\u2588":i===1?"\u2593":i===2?"\u2592":i===3?"\u2591":o<n?"\u2500":"\xB7"}).join("")}function kr({durationMs:e=3e3,slogan:t="Never leave the command line"}){let n=Math.max(1,e),[r,o]=bc(0);Cc(()=>{let l=Date.now(),u=setInterval(()=>{let p=Date.now()-l;if(p>=n){o(n),clearInterval(u);return}o(p)},33);return()=>clearInterval(u)},[n]);let i=Sc(r/n,0,1),a=Nc(()=>Tc(i,28),[i]),d=`${Math.round(i*100)}%`;return Z.createElement(Ye,{flexDirection:"column",alignItems:"center",justifyContent:"center",paddingX:4,paddingY:1},Z.createElement(Ye,{flexDirection:"column",minWidth:42},Z.createElement(Ye,{flexDirection:"column",marginBottom:1},Ic.map((l,u)=>Z.createElement(Ye,{key:u,justifyContent:"center"},Ac(l,u)))),Z.createElement(Ye,{justifyContent:"center",marginBottom:1},Z.createElement(_e,{color:"gray"},t)),Z.createElement(Ye,{justifyContent:"center",marginBottom:1},Z.createElement(_e,{color:"cyan"},a.slice(0,10)),Z.createElement(_e,{color:"blue"},a.slice(10,18)),Z.createElement(_e,{color:"magenta"},a.slice(18))),Z.createElement(Ye,{justifyContent:"center",marginBottom:1},Z.createElement(_e,{color:"gray"},d))))}import wc from"readline";var Tn,wn,Ce,Mc=new Set([x.MoveCursorLeft,x.EraseInputWord,x.MoveCursorLeftOfWord,x.MoveCursorRight,x.MoveCursorRightOfWord,x.NavToPreviousContainer,x.NavToNextContainer,x.NavPreviousItem,x.NavNextItem,x.SetViewDense,x.SetViewWide,x.Confirm,x.Exit,x.InitCommandLine,x.ExitCommandLine,x.CaptureInput,x.EraseInput,x.EraseInputWord,x.HideHelp,x.ViewHelp,x.SetViewDense,x.SetViewWide,x.GetLastCommandFromHistory,x.GetNextCommandFromHistory,x.AutoCompleteCommand]),ss=async e=>{if(e.ctrl&&e.name==="c")return U.exit();let{actionIndex:t,mode:n,readOnly:r}=h(),o=vo(e,n);if(!o||r&&!Mc.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(a){logger.error(a)}},Rc=()=>async function(t,n){n.name!=="escape"&&(Ce&&(clearTimeout(Ce),Ce=void 0),await ss(n))},Lc=()=>async function(t){if(t.length===1&&t[0]===27){Ce&&clearTimeout(Ce),Ce=setTimeout(()=>{ss({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),Ce=void 0},25);return}Ce&&(clearTimeout(Ce),Ce=void 0)};function as(){Tn&&process.stdin.removeListener("keypress",Tn),wn&&process.stdin.removeListener("data",wn),Tn=Rc(),wn=Lc(),wc.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",wn),process.stdin.on("keypress",Tn)}import Or from"chalk";Dc(`${Or.bold("Epiq CLI")}
42
42
 
43
- ${wn.dim("Boot in directory:")}
44
- ${wn.cyan("$ epiq")}
43
+ ${Or.dim("Boot in directory:")}
44
+ ${Or.cyan("$ epiq")}
45
45
 
46
- `,{importMeta:import.meta,flags:{init:{type:"string"}}});var cc=2e3,lc=600,Ji=process.stdout.columns||120,Xi=process.stdout.rows||20,Er=null,mc=e=>new Promise(t=>setTimeout(t,e)),Yi=e=>{if(!Er){Er=ac(e);return}Er.rerender(e)},Qi=()=>{Yi(Gi.createElement(Sn,{width:Ji,height:Xi}))},uc=e=>{Yi(Gi.createElement(An,{durationMs:e}))},pc=()=>{let e=jt();if(d(e)){if(e.message.includes("No events found"))return logger.info("No events found, starting with empty state"),[];throw new Error(e.message)}return e.data},gc=e=>{let t=gi(e);if(d(t))throw new Error(`Failed to boot state: ${t.message}`)};async function fc(){Ro(),await Qo();let e=pc(),r=e.length===0?cc:lc;r>0&&uc(r);let n=Date.now();gc(e);let o=Date.now()-n,i=Math.max(0,r-o);i>0&&await mc(i),Qi(),qi()}process.stdout.on("resize",()=>{Ji=process.stdout.columns||120,Xi=process.stdout.rows||20,Er&&Qi()});(async()=>(console.clear(),await fc()))();
46
+ `,{importMeta:import.meta,flags:{init:{type:"string"}}});var Fc=2e3,kc=600,cs=process.stdout.columns||120,ls=process.stdout.rows||20,Mn=null,Oc=e=>new Promise(t=>setTimeout(t,e)),ms=e=>{if(!Mn){Mn=Pc(e);return}Mn.rerender(e)},us=()=>{ms(ds.createElement(Fr,{width:cs,height:ls}))},Bc=e=>{ms(ds.createElement(kr,{durationMs:e}))},Uc=()=>{let e=ht();if(c(e)){if(e.message.includes("No events found"))return logger.info("No events found, starting with empty state"),[];throw new Error(e.message)}return e.data},Wc=e=>{let t=Ai(e);if(c(t))throw new Error(`Failed to boot state: ${t.message}`)};async function Hc(){let e=mi();c(e)||gt(e.data),await ni();let t=Uc(),r=t.length===0?Fc:kc;r>0&&Bc(r);let o=Date.now();Wc(t);let i=Date.now()-o,a=Math.max(0,r-i);a>0&&await Oc(a),us(),as()}process.stdout.on("resize",()=>{cs=process.stdout.columns||120,ls=process.stdout.rows||20,Mn&&us()});(async()=>(console.clear(),await Hc()))();
package/dist/mcp.js ADDED
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ import{McpServer as xs}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Is}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as S}from"zod";var m={INIT:"init",HELP:"help",NEW:"new",TAG:"tag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",DELETE:"delete",RENAME:"rename",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",SET_DESCRIPTION:"edit",SET_EDITOR:"set:editor",SET_VIEW:"set:view",SET_USERNAME:"set:username",SYNC:"sync",NONE:""},oe={None:"none",Invalid:"invalid",Valid:"valid"},Z={None:"none",Success:"success",Fail:"fail"},i=e=>({result:Z.Fail,message:e,data:null}),c=(e,t)=>({result:Z.Success,message:e,data:t}),pn=()=>({result:Z.None,message:"No result",data:null}),a=e=>e.result==="fail";import{ulid as to}from"ulid";import Me from"chalk";import{monotonicFactory as gs,ulid as de}from"ulid";import{useSyncExternalStore as Xu}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function J(e){return e.context==="TICKET"}var p={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function ze(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var qe=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var gn=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},fn=(e,t)=>t?e.get(t)??[]:[];var vn=new WeakMap,mo=e=>{let t=vn.get(e);return t||(t=gn(e),vn.set(e,t)),t};var yn=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return fn(mo(e),r).filter(s=>ze(r,s)>=n)};var En=({inputToMatch:e,lastWord:t},n)=>{if(t.endsWith(" "))return{hint:"",hints:[],overlap:0,remainder:""};let r=yn({wordList:n,inputToMatch:e,overlapThreshold:1});return po(t,r)},po=(e,t)=>{let n=t[0]??"",r=ze(e.toLowerCase(),n.toLowerCase()),o=n?n+" ":"",s=o.slice(r);return{hint:o,hints:t,overlap:r,remainder:s}};var Nn=["vi","vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var Ie=24n,go=Ie*4n,Ge=(1n<<go)-1n,fo=/^[0-9a-f]+$/;function xn(e){if(!e||!fo.test(e))throw new Error(`Invalid hex rank: ${e}`);return BigInt("0x"+e)}function Je(e,t=Ie){if(e<0n)throw new Error("Negative rank not allowed");return e.toString(16).padStart(Number(t),"0")}function De(e,t){if(!e&&!t)return Je(Ge/2n,Ie);let n=e?xn(e):0n,r=t?xn(t):Ge;if(r<=n)return Je(Ge/2n,Ie);let o=(n+r)/2n;return o===n||o===r?"":Je(o,Ie)}function Y(){return Je(Ge/2n,Ie)}var ee={workspace:(e,t)=>({id:e,title:t,rank:Y(),isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r=!1)=>({id:e,title:t,rank:Y(),isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n)=>({id:e,title:t,rank:Y(),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:Y(),isDeleted:!1,props:r,context:P.FIELD,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[]}),ticket:(e,t,n)=>({id:e,title:t,rank:Y(),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:Y(),isDeleted:!1,props:r,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[]})};var V=e=>Object.values(y().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),In=(e,t)=>e.findIndex(n=>n.id===t),Lt=(e,t={at:"end"})=>{if(e.length===0)return c("Resolved rank",Y());switch(t.at){case"start":{let n=e[0];return n?c("Resolved rank",De(void 0,n.rank)):i("Unable to resolve first sibling")}case"end":{let n=e[e.length-1];return n?c("Resolved rank",De(n.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let n=In(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",De(r?.rank,o.rank)):i("Sibling not found")}case"after":{let n=In(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",De(r.rank,o?.rank)):i("Sibling not found")}}};var Ye=(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}`)},vo=(e,t)=>{let{nodes:n}=y(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Pt=(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"),N={deleteNode(e){j(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=Pt(r,"edit");if(o)return o;let s={...r,props:{...r.props,value:t}};return N.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=Pt(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 V(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=Pt(o,"move");if(d)return d;if(vo(t,e))return i("Cannot move node into its own descendant");let l=V(t).filter(v=>v.id!==e),u=Lt(l,n);if(a(u))return u;let f={...o,parentNodeId:t,rank:u.data};return this.updateNode(f),c("Moved node successfully",f)},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 f=t[u];if(!(!f||s.has(u))){s.add(u);for(let v of V(f.id))d(v.id)}};d(e);let l={...structuredClone(t)};for(let u of s){if(!l[u])return i("Unable to locate node to delete");l[u]={...l[u],isDeleted:!0}}return n?(I({nodes:l}),c("Successfully tomb stoned",o)):i("Unable to delete undefined")},createContributor(e){let t=j(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=N.getContributor(t),o=N.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(V(s.id).some(u=>u.props?.value===t))return i("Contributor already assigned");let l=this.createNodeAtPosition(ee.field(n,r.name,s.id,{value:t}));return a(l)?l:c("Assigned contributor",l.data)},createTag(e){let t=j(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=N.getTag(t),o=N.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(V(s.id).some(u=>u.props?.value===t))return i("Tag already assigned");let l=this.createNodeAtPosition(ee.field(n,r.name,s.id,{value:t}));return a(l)?l:c("Tag added",l.data)},createNodeAtPosition(e,t={at:"end"}){if(!e.parentNodeId){let s={...e,rank:Y()};return this.createNode(s),c("Created node",s)}let n=V(e.parentNodeId),r=Lt(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=j(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=j(o=>({...o,nodes:{...o.nodes,[e]:n}}));return a(r)?i(r.message):c("Locked node",n)},updateNode(e){let t=j(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 Xe={preferredEditor:null,userName:null,userId:null},ie=()=>Xe,Dt=e=>(Xe={...Xe,...e},Xe);var Cn=()=>{let e=ie(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},bn=()=>!Fe();var W={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"},hn={accent:W.cyan,accent2:W.magenta,primary:W.white,secondary:W.grayDark,secondary2:W.grayLight,gray:W.gray,green:W.green,yellow:W.yellow,red:W.red};var g={red:W.red,yellow:W.yellow,green:W.green,blue:W.blue,magenta:W.magenta,cyan:W.cyan},Qe={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 yo=/^(\d+)(h|d|w|mo|y)$/,Eo=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,No=({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},xo=(e,t=new Date)=>{let n=e.match(yo);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}},Io=e=>{let t=e.match(Eo);if(!t)return null;let[,n,r,o,s,d]=t,l=Number(n),u=Number(r),f=Number(o),v=s?Number(s):0,E=d?Number(d):0;return No({year:l,month:u,day:f,hour:v,minute:E})?new Date(l,u-1,f,v,E):null},Ze=e=>{let t=e.trim().toLowerCase();return xo(t)??Io(t)},Rn=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Co=[{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}],Sn=(e=Co)=>{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 bo=["BOARD","TICKET","SWIMLANE"],_=e=>{let{currentNode:t,readOnly:n,selectedNode:r}=y(),o=Cn().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],f=[m.TAG,m.ASSIGN,m.CLOSE_ISSUE,m.RE_OPEN_ISSUE,m.SET_DESCRIPTION],v=[m.FILTER,m.PEEK],E={WORKSPACE:[...l,...u],BOARD:[...v,...l,...u],SWIMLANE:[...v,...l,...u],TICKET:[...l,...u,...f],FIELD:[...l,...f],FIELD_LIST:[...l,...f],TEXT:[...l]},C=d&&bo.includes(d),R=[...E[s||"WORKSPACE"]].filter(Q=>[m.RENAME,m.DELETE,m.MOVE].includes(Q)?C:!0),M={[m.PEEK]:[...Sn(),"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]:[...Nn,"vim"],[m.TAG]:[...new Set([...Object.keys(Qe),...N.getExistingTags()])],[m.ASSIGN]:N.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]:R};return o?bn()?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 tt from"chalk";import{decodeTime as An}from"ulid";var wn=e=>{try{return c("Decoded date",new Date(An(e)))}catch(t){return i("Decoding failed + "+t.message)}},Ft=e=>{if(!e?.id)return null;try{return An(e.id)}catch{return null}};var ve=(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 Tn from"chalk";var Ot={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ho=(e,t,n)=>Math.max(t,Math.min(n,e)),kt=(e,t,n)=>e+(t-e)*n,Mn=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Ro=(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,f=0,v=0;d>=0&&d<1?(u=s,f=l):d>=1&&d<2?(u=l,f=s):d>=2&&d<3?(f=s,v=l):d>=3&&d<4?(f=l,v=s):d>=4&&d<5?(u=l,v=s):(u=s,v=l);let E=o-s/2;return[Math.round((u+E)*255),Math.round((f+E)*255),Math.round((v+E)*255)]},So=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Ao=(e,t,n)=>[Math.round(kt(e[0],t[0],n)),Math.round(kt(e[1],t[1],n)),Math.round(kt(e[2],t[2],n))],wo=e=>{let n=Mn(e)%360,r=Ro(n,Ot.stringColor.saturation,Ot.stringColor.lightness);return So(r)},To=e=>{let t=Ot.gradient.stops,n=ho(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 Ao(t[s],t[s+1],d)},et=e=>Mn(e.toLowerCase().trim())/4294967295,Mo=e=>{let t=et(e);return To(t)},Lo=e=>{let[t,n,r]=Mo(e);return{normal:o=>Tn.bgRgb(t,n,r).black(o),cursor:o=>Tn.bgRgb(t,n,r).white.bold(o)}};var Ut=e=>Lo(e).normal(` ${e} `),_t=(e,t=Qe)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:wo(r)};var Po=["BOARD","TICKET","SWIMLANE"],Wt=()=>{let e=y().selectedNode;return e?.context?Po.includes(e?.context)?k():U({message:"Command not available in this context",completionWordList:[]}):U({message:"Missing target context",completionWordList:[]})},z="<ENTER> to confirm",k=(e="",t=[])=>({message:e,validity:oe.Valid,completionWordList:t}),U=({message:e,completionWordList:t})=>({validity:oe.Invalid,message:e,completionWordList:t}),ke=e=>e.length===0,me=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let u=[...t.filter(Boolean).filter(v=>v.startsWith(o.trim()))].sort((v,E)=>et(v)-et(E)).slice(0,r).map(Ut),f=u.length>s?u.join(" "):"";return f?`${e}${f}${n}`:""},Bt=({modifier:e})=>{let t="confirm";return e===t?k(z):U({message:ke(e)?`if you are certain, enter ${Ut(t)}`:"",completionWordList:[t]})},Do=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?k(z):U({message:ke(n)?t:"",completionWordList:[]}),Fo=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?U({message:n,completionWordList:[]}):k():U({message:ke(r)?t:"",completionWordList:[]}),$t=({hint:e})=>({modifier:t,inputString:n})=>ke(t)&&ke(n)?U({message:e,completionWordList:[]}):k(z),ko={[m.PEEK]:e=>{let t=e.modifier;if(t==="now")return k(z);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD",completionWordList:[]};if(t==="prev"||t==="next")return k(z);let r=Ze(t);if(!t||!r)return U(n);let o=ve(y().breadCrumb,"BOARD");if(a(o))return U({message:"Command is not applicable in this context",completionWordList:[]});let s=wn(o.data.id);return a(s)?U({message:"Unable to peek: board id is not a valid ULID",completionWordList:[]}):Rn({date:r,horizonDate:s.data})?k(z):U({message:tt.red(`nothing to peek before ${s.data.toISOString().slice(0,16).replace("T"," ")}`),completionWordList:[]})},[m.INIT]:()=>k(z),[m.FILTER]:e=>{if(e.modifier==="clear")return k();let t=d=>_(m.FILTER).includes(d);if(!e.modifier||!t(e.modifier??""))return U({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()??"")?U({message:me({prefix:`existing ${e.modifier}s... `,wordList:s,noOfHints:10,inputString:e.inputString}),completionWordList:s}):k():U({message:me({prefix:"one of... ",wordList:s,noOfHints:10,inputString:e.inputString}),completionWordList:s})},[m.NONE]:e=>e.command?k():U({message:me({prefix:"commands... ",wordList:_(m.NONE),inputString:e.inputString,minLengthForHints:0}),completionWordList:[]}),[m.NEW]:e=>Fo({list:_(m.NEW),hint:me({wordList:_(m.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[m.SET_DESCRIPTION]:()=>k(z),[m.HELP]:()=>k(z),[m.RENAME]:()=>{let e=Wt();return e.validity==="invalid"?e:k(z)},[m.DELETE]:e=>{let t=Wt();return t.validity==="invalid"?t:Bt(e)},[m.CLOSE_ISSUE]:e=>Bt(e),[m.RE_OPEN_ISSUE]:e=>Bt(e),[m.MOVE]:e=>{let t=Wt();return t.validity==="invalid"?t:$t({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=N.getExistingTags().map(n=>` ${tt.bgHex(_t(n))(" "+n+" ")} `).slice(0,10);return $t({hint:"tag name like... "+t.join("")})(e)},[m.ASSIGN]:e=>{let t=N.getExistingAssignees().map(n=>` ${tt.bgHex(_t(n))(" "+n+" ")} `).slice(0,10);return $t({hint:"assign to... "+t.join("")})(e)},[m.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=_(m.SET_EDITOR);return e.modifier?k(z):U({message:me({wordList:t,inputString:e.inputString}),completionWordList:[]})},[m.SET_USERNAME]:e=>e.inputString?k():U({message:`Enter a username. Saved in ${tt.bgBlack("~/.epiq/")}`,completionWordList:[]}),[m.SET_VIEW]:e=>Do({list:_(m.SET_VIEW),hint:me({wordList:_(m.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[m.SYNC]:()=>k(z)},Ln=Object.fromEntries(Object.entries(ko).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Pn=["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",NewItem:"add-new-item",TagTicket:"ticket-tag",AssignUserToTicket:"ticket-assign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Sync:"sync"};var Dn=e=>Object.values(m).includes(e),Fn=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:d,validity:l,completionWordList:u}=Ln[n].validate(n,r,s),f=o==="command"?Object.values(m):n&&e.target==="modifier"?_(n):Pn;return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:d??"",autoCompletion:t?En(e,[...u,...f]):{hint:"",hints:[],remainder:"",overlap:0}}};var kn=e=>{let t=e.trimStart(),n=Uo(t),r=(n[0]??"").trimStart().trimEnd(),o=(n[1]??"").trimStart().trimEnd(),s=_o(e),d=Dn(r)?r:null,l=d!==null,u=r!=="",f=e.endsWith(" "),v=d?_(d)??[]:[],E=d&&v.includes(o)?o:"",C="word";n.length<=1?C="command":n.length===2&&(C="modifier");let R=Oo(t,d,E);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:s,hasCommand:u,command:d,isCommandKeyword:l,isLastWordCompleted:f,modifier:E,target:C,inputToMatch:s,inputString:R}},Oo=(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},Uo=e=>e?e.split(/\s+/):[],_o=e=>e.trimEnd().split(/\s+/).at(-1)??"";var On=" ",Ce={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:oe.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Wo=new Set,Un=()=>{for(let e of Wo)e()};var se=e=>{let n=e(Ce),r=kn(n.value),o=n.cursorPosition===n.value.length;Ce={...n,commandMeta:Fn(r,o)},Un()},Oe=({message:e,result:t})=>{let n=structuredClone(Ce);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Ce=n,Un(),c(e,null)},Ht=e=>{se(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Kt=e=>{se(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}})},_n=()=>{se(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}})},Wn=()=>{se(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}})},D=e=>{se(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}})},Bn=()=>{se(e=>({...e,commandIsPending:!0}))},$n=({addToHistory:e=!0})=>{se(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),Bo()},Hn=()=>{se(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}})},Kn=()=>{se(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Bo=()=>D(()=>""),te=()=>Ce,nt=()=>{let[e,...t]=Ce.value.split(On);return t.join(On).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 Vn=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.ASSIGN:return b.AssignUserToTicket;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 Go}from"node:child_process";import Jo from"node:os";import Gn from"node:path";import{ulid as Yo}from"ulid";import{accessSync as $o,copyFileSync as Ho,existsSync as rt,mkdirSync as jn,readdirSync as zn,readFileSync as Ko,renameSync as Vo,rmSync as jo,statSync as qn,unlinkSync as zo,writeFileSync as qo}from"node:fs";import be from"node:path";var q={writeToFile:(e,t)=>{try{let n=be.dirname(e);rt(n)||jn(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);qo(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Ko(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=q.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 rt(e)&&qn(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await $o(e),!0}catch{return!1}},mkDir:e=>jn(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=be.parse(t);for(;;){let r=be.join(t,e);try{if(rt(r)&&qn(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=be.dirname(t)}return null},readFirstJSON(e){try{if(!q.dirExists(e))return null;let t=zn(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=be.join(e,t);return q.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return q.dirExists(e)?zn(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{zo(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{jo(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(be.dirname(t)),!n?.overwrite&&rt(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Vo(e,t)}catch(r){if(r?.code==="EXDEV"){Ho(e,t),this.rmFile(e);return}throw r}}};function Xo(){let{preferredEditor:e}=ie(),t=[e,process.env.VISUAL,process.env.EDITOR,"vim","vi","nano"].filter(n=>!!n?.trim());return[...new Set(t)]}function Qo(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function Jn(e){let t=Gn.join(Jo.tmpdir(),"epiq");q.mkDir(t);let n=Gn.join(t,Yo());q.writeToFile(n,e??"");let r=Xo();for(let o of r){let s=Qo(o,n),d=Go(s,{stdio:"inherit",shell:!0});if(!d.error&&d.status===0){let l=q.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{monotonicFactory as Zo,ulid as ot}from"ulid";var it=Zo(),st=({name:e,parent:t,user:{userId:n,userName:r}})=>{let o=it(),s=it(),d=it(),l=it();return[{id:ot(),userId:n,userName:r,action:"add.issue",payload:{id:o,parent:t,name:e}},{id:ot(),userId:n,userName:r,action:"add.field",payload:{id:s,parent:o,name:"Description",val:""}},{id:ot(),userId:n,userName:r,action:"add.field",payload:{id:d,parent:o,name:"Assignees"}},{id:ot(),userId:n,userName:r,action:"add.field",payload:{id:l,parent:o,name:"Tags"}}]};import ut from"node:fs";import mt from"node:path";import{z as jt}from"zod";var at=process.env.IS_LOCAL==="true",ne=()=>".epiq";import dt from"node:fs";import ye from"node:path";import{decodeTime as ei,monotonicFactory as ti}from"ulid";import{z as Ue}from"zod";var Yn=e=>({action:e.action,payload:e.payload});var Qn=1,Xn=ti(),ni="events",ri=Ue.tuple([Ue.string().min(1),Ue.string().min(1).nullable()]),oi=Ue.looseObject({v:Ue.literal(Qn),id:ri}),Vt=e=>{let t=oi.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(", ")}`)},ct=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",H=()=>{let{userName:e,userId:t}=ie();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:ct(t),userName:ct(e)}):i("Unable to resolve actor ID from settings or OS user info"):i("User ID not configured"):i("User name not configured")},ii=e=>dt.existsSync(ye.join(e,ne()))&&dt.statSync(ye.join(e,ne())).isDirectory(),ae=(e=process.cwd())=>{let t=ye.resolve(e);for(;;){if(ii(t))return t;let n=ye.dirname(t);if(n===t)return ye.resolve(e);t=n}},Zn=(e=process.cwd())=>ye.join(ae(e),ne(),ni),_e=({userId:e,userName:t})=>`${ct(e)}.${ct(t)}.jsonl`,si=(e=process.cwd(),{userId:t,userName:n})=>{let r=_e({userId:t,userName:n});return/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r)?c("Successfully resolved event log path",ye.join(Zn(e),r)):i(`Invalid event log file name: ${r}`)},ai=(e,t)=>{let n={[e.action]:e.payload,v:Qn,id:t};return Vt(n)};function lt({event:e,rootDir:t=process.cwd()}){try{let n=ae(t),r=Zn(n),o=si(n,{userId:e.userId,userName:e.userName});if(a(o))return o;dt.mkdirSync(r,{recursive:!0});let s=er(n);if(a(s))return i(s.message);let d;if(s.data){let u=ei(s.data),f=Math.max(Date.now(),u+1);d=Xn(f)}else d=Xn();let l=ai(Yn(e),[d,s.data]);return a(l)?i(l.message):(dt.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 di}from"ulid";var ci=ne(),li="events",ui=jt.object({userId:jt.string().min(1).default("unknown"),userName:jt.string().min(1).default("unknown")}),mi=(e=process.cwd())=>mt.join(ae(e),ci,li),pi=e=>{let[t,n]=mt.basename(e,".jsonl").split("."),r=ui.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):i(`Invalid event file name ${mt.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},gi=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])},fi=(e,t)=>t in e,vi=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),yi=e=>{let{userId:t,userName:n,...r}=e,o=gi(r);if(a(o))return i(o.message);let s=o.data,d=e.id?.[0];return d?fi(r,s)?c("Decoded persisted event",vi({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")},pt=e=>{if(!ut.existsSync(e))return c("Event file missing",[]);let t=pi(e);if(a(t))return i(t.message);let n=ut.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=Vt(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 tr(e=process.cwd()){let t=mi(e);if(!ut.existsSync(t))return i("No events found");let n=ut.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>mt.join(t,o)),r=[];for(let o of n){let s=pt(o);if(a(s))return i(s.message);r.push(...s.data)}return c("All events loaded",Ei(r))}function We(e=process.cwd()){let t=tr(e);if(a(t))return i(t.message);let n=[];for(let r of t.data){let o=yi(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 er(e=process.cwd()){let t=tr(e);return a(t)?i(t.message):c("Loaded edge reference",t.data.at(-1)?.id?.[0]??null)}var Ei=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],f=n.get(u)??[];f.push(l),n.set(u,f)}for(let l of n.values())l.sort((u,f)=>{let[v]=u.id,[E]=f.id;return v.localeCompare(E)});let r=[],o=new Set,s=l=>{let u=n.get(l)??[];for(let f of u){let[v]=f.id;o.has(v)||(o.add(v),r.push(f),s(v))}};s(null);let d=[...e].filter(l=>{let[u]=l.id;return!o.has(u)}).sort((l,u)=>{let[f,v]=l.id,[E,C]=u.id,R=v===null||t.has(v),M=C===null||t.has(C);if(R&&!M)return-1;if(!R&&M)return 1;let Q=(v??"").localeCompare(C??"");return Q!==0?Q:f.localeCompare(E)});return[...r,...d]},nr=(e,t)=>{let n=e.findIndex(r=>{try{return di(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var rr=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 Ni=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[X,gt]=Ni;var w=(e,t)=>i(`${t.split(".").join(" ")+" failed, "+e.toLowerCase()}`),xi={"init.workspace":({action:e,payload:t})=>{let{id:n,name:r}=t,o=ee.workspace(n,r);zt(o);let s=N.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=ee.workspace(n,r),s=N.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=N.createNodeAtPosition(ee.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=N.createNodeAtPosition(ee.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=N.createNodeAtPosition(ee.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=N.createNodeAtPosition(ee.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(!N.getNode(n))return w("Unable to locate node",e);let s=N.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=N.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=N.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=N.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=N.tag(r,o,n);return a(s)?w(s.message??"Unable to tag issue",e):c("Issue tagged",{action:e,result:s.data})},"assign.issue":({action:e,payload:t})=>{let{id:n,contributor:r,target:o}=t,s=N.assign(o,r,n);return a(s)?w(s.message??"Unable to assign issue",e):c("Assigned successfully",{action:e,result:s.data})},"move.node":({action:e,payload:t})=>{let{id:n,parent:r,pos:o}=t,s=N.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=N.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=N.getNode(n);if(!r)return w("Unable to locate issue",e);if(!J(r))return w("Can only close issues",e);let o=N.getNode(X);if(!o)return w("Unable to locate target swimlane",e);if(o.id===r.parentNodeId)return w("Cannot close closed issue",e);let d=N.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=N.getNode(n);if(!r)return w("Unable to locate issue",e);if(!J(r))return w("Can only reopen issues",e);let o=N.getNode(X);if(!o)return w("Unable to locate closed swimlane",e);if(!(r.parentNodeId===o.id))return w("Issue is not closed",e);let d=rr(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(!N.getNode(d))return w("Previous parent no longer exists",e);let u=N.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=N.lockNode(n);return a(r)?w(r.message??"Unable to lock node",e):c("Node locked",{action:e,result:r.data})}},Ii=(e,t)=>{let n=N.getNode(e);n&&N.updateNode({...n,log:[...n.log??[],t]})},Ci=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"assign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function he(e,t=!1){let n=xi[e.action](e);if(a(n))return n;t||([...new Set(Ci(e))].forEach(d=>Ii(d,e)),j(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):(N.createContributor({name:o,id:r}),n)}var Ee=e=>e.map(t=>he(t));function K(e){let t=he(e);if(t.result!==Z.Success)return t;let n=lt({event:e});return a(n)?n:t}function Re(e){return e.map(t=>K(t))}import Ke from"node:fs";import{spawn as Ri}from"node:child_process";import Gt from"node:fs";import Se from"node:path";var Be=(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 $e from"fs";import ir from"path";import bi from"util";var or=1e3,sr=(e=process.cwd())=>ir.join(ae(e),ne(),"log","epiq.log");function hi(e=process.cwd()){if(!at)return;let t=sr(e);if(!$e.existsSync(t))return;let r=$e.readFileSync(t,"utf8").split(`
5
+ `);if(r[r.length-1]===""&&r.pop(),r.length<=or)return;let o=r.slice(-or).join(`
6
+ `)+`
7
+ `;$e.writeFileSync(t,o,"utf8")}function qt(e,t,n=!1,r=process.cwd()){if(!at)return;let o=sr(r),s=bi.format(...t),d=new Date,u=`[${n?d.toISOString().slice(11,19):d.toISOString()}] ${e} ${s}
8
+ `;$e.mkdirSync(ir.dirname(o),{recursive:!0}),$e.appendFileSync(o,u,"utf8"),hi(r)}var x={info(...e){qt("[Info]",e,!1)},debug(...e){qt("->",e,!0)},error(...e){qt("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=x;var ar=15e3,Si={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},cr=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Gt.existsSync(t)){let v=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:v,exitCode:1});return}r(i(v));return}let o=Ri("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Si}),s=!1,d="",l="",u=v=>{s||(s=!0,clearTimeout(f),r(v))},f=setTimeout(()=>{o.kill("SIGTERM");let v=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${ar}ms`].join(`
9
+ `);u(n?{stdout:d,stderr:v,exitCode:124}:i(v))},ar);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",v=>{d+=v}),o.stderr.on("data",v=>{l+=v}),o.on("error",v=>{if(n){u({stdout:d,stderr:v.message,exitCode:1});return}u(i([`git ${e.join(" ")}`,`cwd=${t}`,v.message].join(`
10
+ `)))}),o.on("close",v=>{let E=v??1;if(n){u({stdout:d,stderr:l,exitCode:E});return}if(E!==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:E}))})}),T=({args:e,cwd:t})=>cr({args:e,cwd:t,allowFail:!1}),Ne=({args:e,cwd:t})=>cr({args:e,cwd:t,allowFail:!0}),lr=Be(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=>Se.resolve(e)),Ai=Be(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=Se.isAbsolute(n)?n:Se.join(e,n);return c("Resolved git dir",r)},e=>Se.resolve(e)),Jt=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())},Yt=async e=>{let t=await Ai(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=>Gt.existsSync(Se.join(n,s)));return c("Checked for in-progress Git operation",o.length>0)},ft=async({repoRoot:e,remote:t})=>{let n=await Ne({args:["remote","get-url",t],cwd:e});return c("Checked remote",n.exitCode===0)},vt=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)},ur=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}`)},dr=e=>{try{return Gt.realpathSync.native(e)}catch{return Se.resolve(e)}},mr=async({repoRoot:e,worktreeRoot:t})=>{let n=await T({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let r=dr(t),o=n.data.stdout.split(`
14
+ `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(dr).includes(r);return c("Checked worktree registration",o)},Xt=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)},yt=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())},pr=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())},gr=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Qt=async({cwd:e,remote:t,branch:n})=>{let r=await vt({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)},fr=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)},vr=async e=>{let t=await yt(e);return a(t)?i(t.message):c("Checked detached HEAD state",t.data==="HEAD")};import{createHash as Di}from"node:crypto";import re from"node:fs";import Fi from"node:os";import $ from"node:path";import Et from"node:fs";import wi from"node:path";import{decodeTime as Ti}from"ulid";var Zt=e=>{let[t,n]=e.id;return`${t}:${n??""}`},yr=e=>{let[t]=e.id;return Ti(t)},Mi=e=>{let{userId:t,userName:n,...r}=e;return r},Li=e=>e.length===0?"":e.map(t=>JSON.stringify(Mi(t))).join(`
17
+ `)+`
18
+ `,Pi=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(Zt(r),r);return[...n.values()].sort((r,o)=>{let s=yr(r)-yr(o);return s!==0?s:Zt(r).localeCompare(Zt(o))})},Nt=({sourceFile:e,targetFile:t})=>{let n=pt(e);if(a(n))return i(n.message);let r=pt(t);if(a(r))return i(r.message);let o=Pi(r.data,n.data),s=Li(o);return(Et.existsSync(t)?Et.readFileSync(t,"utf8"):"")===s?c("Event file already merged",!1):(Et.mkdirSync(wi.dirname(t),{recursive:!0}),Et.writeFileSync(t,s,"utf8"),c("Merged event file",!0))};var L="epiq/events",B="origin",en=ne(),Nr="events",ki="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Oi=e=>$.join(en,Nr,e),Ui=e=>Di("sha1").update($.resolve(e)).digest("hex").slice(0,12),xr=()=>$.join(Fi.homedir(),".epiq"),Ir=()=>$.join(xr(),"worktrees"),Cr=e=>$.join(Ir(),Ui(e)),_i=e=>$.join(e,en),Ae=e=>$.join(_i(e),Nr),He=({root:e,fileName:t})=>$.join(Ae(e),t),xt=e=>(x.debug("[sync] ensure dir",e),re.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)),Wi=()=>{x.debug("[sync] ensure epiq storage");let e=xt(xr());if(a(e))return i(e.message);let t=xt(Ir());return a(t)?i(t.message):c("Ensured epiq storage",void 0)},Bi=e=>{re.existsSync(e)&&(x.debug("[sync] remove path",e),re.rmSync(e,{recursive:!0,force:!0}))},$i=e=>{let t=Ae(e);if(!re.existsSync(t))return x.debug("[sync] events dir missing",t),c("Events dir missing",[]);let n=re.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)},Hi=async e=>{x.debug("[sync] inspect local HEAD",e);let t=await Ne({args:["rev-parse","--verify","HEAD"],cwd:e});return t.exitCode===0?c("Repo has HEAD",!0):t.exitCode===1?c("Repo has no HEAD",!1):i(t.stderr.trim()||"Unable to inspect HEAD")},Ki=Be(async e=>{x.debug("[sync] inspect remote history",{repoRoot:e,remote:B});let t=await ft({repoRoot:e,remote:B});if(a(t))return i(t.message);if(!t.data)return c("No remote configured",!1);let n=await Ne({args:["ls-remote","--heads",B],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=>$.resolve(e)),br=async e=>{x.debug("[sync] ensure initial commit");let t=await Hi(e);if(a(t))return i(t.message);if(t.data)return x.debug("[sync] local HEAD exists"),c("Repo already initialized",!1);let n=await Ki(e);if(a(n))return i(n.message);if(n.data)return x.debug("[sync] skip local init commit due to remote history"),c("Skipped local init commit because remote history exists",!1);x.debug("[sync] create empty init commit");let r=await T({args:["commit","--allow-empty","-m","[epiq:init]"],cwd:e});return a(r)?i(`Failed to create initial commit
19
+ ${r.message}`):c("Created initial commit",!0)},hr=({repoRoot:e,worktreeRoot:t})=>{let n=$i(t);if(a(n))return i(n.message);let r=Ae(t),o=Ae(e),s=!1;for(let d of n.data){let l=$.join(r,d),u=$.join(o,d);x.debug("[sync] hydrate event file",{from:l,to:u});let f=Nt({sourceFile:l,targetFile:u});if(a(f))return i(f.message);s=s||f.data}return x.debug("[sync] hydrate changed",s),c("Hydrated event files from remote worktree",s)},Er=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Vi=async e=>{let t=await yt(e);if(a(t))return i(t.message);let n=await pr(e);if(a(n))return i(n.message);let r=`[epiq:sync:${Er(t.data)}:${Er(n.data)}]`;return x.debug("[sync] commit message",r),c("Built sync commit message",r)},ji=async e=>{x.debug("[sync] create empty storage branch",L);let t=await T({args:["commit-tree",ki,"-m","[epiq:init-storage-branch]"],cwd:e});if(a(t))return i(`Failed to create storage branch commit
20
+ ${t.message}`);let n=t.data.stdout.trim(),r=await T({args:["update-ref",`refs/heads/${L}`,n],cwd:e});return a(r)?i(`Failed to create ${L}
21
+ ${r.message}`):c("Created empty storage branch",!0)},zi=async({repoRoot:e})=>{x.debug("[sync] ensure local remote branch",L);let t=await ur({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 ft({repoRoot:e,remote:B});if(a(n))return i(n.message);if(n.data){let r=await vt({repoRoot:e,remote:B,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",B,L],cwd:e});if(a(o))return i(`Failed to fetch ${L} from remote
22
+ ${o.message}`);x.debug("[sync] create local tracking branch",L);let s=await T({args:["branch","--track",L,`${B}/${L}`],cwd:e});return a(s)?i(`Failed to create local ${L} from remote
23
+ ${s.message}`):c("Created local remote branch from remote",!0)}}return ji(e)},qi=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(`
24
+ `),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)},Gi=async({repoRoot:e,worktreeRoot:t})=>{x.debug("[sync] create remote worktree",t);let n=xt($.dirname(t));if(a(n))return i(n.message);re.existsSync(t)&&!re.existsSync($.join(t,".git"))&&(x.debug("[sync] remove broken remote worktree path",t),Bi(t));let r=await T({args:["worktree","add",t,L],cwd:e});return a(r)?i(`Failed to create remote worktree
25
+ ${r.message}`):c("Created remote worktree",!0)},Ji=async({repoRoot:e,worktreeRoot:t})=>{x.debug("[sync] ensure remote worktree",t);let n=await qi({repoRoot:e,branch:L});if(a(n))return i(n.message);let r=n.data,o=$.resolve(t),s=r?$.resolve(r):null;if(s&&s===o&&re.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
26
+ ${u.message}`)}if(s&&!re.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
27
+ ${u.message}`)}let d=await mr({repoRoot:e,worktreeRoot:t});if(a(d))return i(d.message);let l=re.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
28
+ ${u.message}`)}return Gi({repoRoot:e,worktreeRoot:t})},Yi=async e=>{let t=await yt(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}
29
+ ${n.message}`):c("Checked out remote branch",!0)},Xi=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(`
30
+ `).filter(Boolean).filter(d=>d!==en);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
31
+ ${o.message}`);let s=await Jt({cwd:e,message:"[epiq:repair-storage-branch]"});return a(s)?i(s.message):c("Cleaned storage branch",!0)},Qi=async e=>{x.debug("[sync] ensure remote upstream",L);let t=await Xt(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 ft({repoRoot:e,remote:B});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 vt({repoRoot:e,remote:B,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",B,L],cwd:e});if(a(o))return i(`Failed to fetch ${L}
32
+ ${o.message}`);x.debug("[sync] set upstream to remote branch");let s=await T({args:["branch","--set-upstream-to",`${B}/${L}`,L],cwd:e});return a(s)?i(`Failed to set remote upstream
33
+ ${s.message}`):c("Configured remote upstream",!0)},Rr=async({worktreeRoot:e,ownEventFileName:t})=>{x.debug("[sync] stage own event file in remote worktree",t);let n=await T({args:["add",Oi(t)],cwd:e});return a(n)?i(`Failed to stage remote own event file
34
+ ${n.message}`):c("Staged remote own event file",void 0)},Sr=async({repoRoot:e,worktreeRoot:t})=>{let n=await Vi(e);return a(n)?i(n.message):(x.debug("[sync] create remote sync commit"),Jt({cwd:t,message:n.data}))},tn=async e=>{x.debug("[sync] push remote worktree");let t=await Xt(e);if(a(t))return i(t.message);let n=await T({args:t.data?["push"]:["push","-u",B,L],cwd:e});return x.debug("[sync] push result",n),a(n)?i(`Failed during remote push
35
+ ${n.message}`):c("Pushed remote",!0)},Ar=async({repoRoot:e,worktreeRoot:t,ensureUpstream:n})=>{x.debug("[sync] bootstrap remote storage",{repoRoot:e,worktreeRoot:t,ensureUpstream:n});let r=!1,o=[Wi(),await zi({repoRoot:e}),await Ji({repoRoot:e,worktreeRoot:t}),await Yi(t),await Xi(t),n?await Qi(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)},wr=(e,t)=>{for(let n of[Ae(e),Ae(t)]){let r=xt(n);if(a(r))return i(r.message)}return c("Ensured remote layout",void 0)};var Zi=({repoRoot:e,worktreeRoot:t,ownEventFileName:n})=>{let r=He({root:e,fileName:n}),o=He({root:t,fileName:n});return Ke.existsSync(r)?(logger.debug("[sync] merge own event file to remote",{ownEventFileName:n,localFile:r,remoteFile:o}),Nt({sourceFile:r,targetFile:o})):(logger.debug("[sync] local own event file missing",r),c("Local own event file missing, nothing to merge",!1))},Tr=async({repoRoot:e,worktreeRoot:t,ownEventFileName:n})=>{let r=Zi({repoRoot:e,worktreeRoot:t,ownEventFileName:n});if(a(r))return i(r.message);let o=await fr(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 Rr({worktreeRoot:t,ownEventFileName:n});if(a(s))return i(s.message);let d=await Sr({repoRoot:e,worktreeRoot:t});return a(d)?i(d.message):c("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:d.data})},Mr=({repoRoot:e,worktreeRoot:t,ownEventFileName:n})=>{let r=He({root:e,fileName:n}),o=He({root:t,fileName:n});logger.debug("[sync] own event file sizes",{local:Ke.existsSync(r)?Ke.statSync(r).size:0,remote:Ke.existsSync(o)?Ke.statSync(o).size:0})},It=async({cwd:e=process.cwd(),ownEventFileName:t})=>{logger.debug("[sync] start write sync",{cwd:e,ownEventFileName:t});let n=await lr(e);if(a(n))return i(n.message);let r=n.data,o=Cr(r);logger.debug("[sync] resolved roots",{repoRoot:r,worktreeRoot:o});let s=await vr(r);if(a(s))return i(s.message);if(s.data)return i("Cannot run :sync while the repository is in detached HEAD state");if(t.includes("/")||t.includes("\\"))return i("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return i("Own event file must end with .jsonl");let d=await Yt(r);if(a(d))return i(d.message);if(d.data)return i("Cannot run :sync while a merge, rebase, cherry-pick, or revert is in progress in the current repo");let l=await br(r);if(a(l))return i(l.message);logger.debug("[sync] ensure initial commit changed",l.data);let u=await Ar({repoRoot:r,worktreeRoot:o,ensureUpstream:!0});if(a(u))return i(u.message);let f=await Yt(o);if(a(f))return i(f.message);if(f.data)return i("Cannot run :sync while a merge, rebase, cherry-pick, or revert is in progress in the remote worktree");let v=wr(r,o);if(a(v))return i(v.message);let E=!1,C,R=!1,M=!1,Q=!1;logger.debug("[sync] pull remote branch before local copy");let Tt=await Qt({cwd:o,remote:B,branch:L});if(a(Tt))return i(Tt.message);R=Tt.data,logger.debug("[sync] pulled remote",R);let Mt=hr({repoRoot:r,worktreeRoot:o});if(a(Mt))return i(Mt.message);Q=Mt.data,logger.debug("[sync] hydrated from remote",Q);let Le=await Tr({repoRoot:r,worktreeRoot:o,ownEventFileName:t});if(a(Le))return i(Le.message);if(E=Le.data.createdCommit,C=Le.data.commitSha,Mr({repoRoot:r,worktreeRoot:o,ownEventFileName:t}),logger.debug("[sync] sync own file result",Le.data),E||u.data){let fe=await tn(o),je=fe;if(a(fe)&&gr(fe.message)){let mn=await Qt({cwd:o,remote:B,branch:L});if(a(mn))return i(mn.message);let Pe=await Tr({repoRoot:r,worktreeRoot:o,ownEventFileName:t});if(a(Pe))return i(Pe.message);Pe.data.createdCommit&&(E=!0,C=Pe.data.commitSha),Mr({repoRoot:r,worktreeRoot:o,ownEventFileName:t}),logger.debug("[sync] retry sync own file result",Pe.data),je=await tn(o)}if(a(je))return i(je.message);M=je.data,logger.debug("[sync] pushed remote",M)}else logger.debug("[sync] no commit created, skipped push");if(E){let fe=await T({args:["rev-parse","HEAD"],cwd:o});if(a(fe))return i(fe.message);C=fe.data.stdout.trim()}return c("Synced event logs with remote",{repoRoot:r,worktreeRoot:o,createdCommit:E,commitSha:C,pulled:R,pushed:M,hydrated:Q,bootstrapped:u.data})};import{ulid as Lr}from"ulid";var we=null,pe=()=>structuredClone(we),Te=e=>we=e,Pr=()=>{let{currentNode:e,selectedIndex:t}=y(),r=A(e.id)[t];return r?c("Resolved selected child",r):i("Target node not found")};function nn(e){let t=Pr();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=V(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=H();if(a(u))return i("Unable to resolve user ID");let{userId:f,userName:v}=u.data;if(Te({id:Lr(),userId:f,userName:v,action:"move.node",payload:{id:t.data.id,parent:l.id,pos:{at:"end"}}}),!we)return i("Could not materialize move state");let E=he(we,!0);return a(E)?E:c("Node moved successfully",E.data)}function rn(e){let t=Pr();if(a(t))return t;let{currentNode:n,selectedIndex:r}=y(),s=V(n.id)[r+e];if(!s)return i("Missing sibling node");let d=H();if(a(d))return i("Unable to resolve user ID");let{userId:l,userName:u}=d.data;if(Te({id:Lr(),userId:l,userName:u,action:"move.node",payload:{id:t.data.id,parent:n.id,pos:{at:e===1?"after":"before",sibling:s.id}}}),!we)return i("Could not materialize move state");let f=he(we,!0);return a(f)?f:c("Node moved successfully",f.data)}import es from"node:os";import Dr from"node:path";import{z as Ct}from"zod";var ts={userId:"",userName:"",preferredEditor:""},Fr=Ct.object({preferredEditor:Ct.string().optional(),userName:Ct.string().optional(),userId:Ct.string().optional()}).strict(),ns=".epiq",rs="config.json",kr=()=>Dr.join(es.homedir(),ns),on=()=>Dr.join(kr(),rs),sn=()=>{try{return q.mkDir(kr()),c("Ensured ~/.epiq exists",null)}catch{return i("Unable to create ~/.epiq")}},os=e=>{let t;try{t=JSON.parse(e)}catch{return i("Invalid ~/.epiq/config.json JSON")}let n=Fr.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(", ")}`)},Or=()=>{let e=sn();if(a(e))return i(e.message);let t=on(),n=q.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{}):os(n)},Ur=e=>{let t=sn();if(a(t))return i(t.message);let n=Fr.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=on();try{return q.writeToFile(r,JSON.stringify(n.data,null,2)+`
36
+ `),c("Config written",null)}catch{return i("Unable to write ~/.epiq/config.json")}},an=e=>{let t=Or();if(a(t))return i("Failed to read existing config");let n={...t.data,...e};return Ur(n)},_r=()=>{let e=on(),t=sn();if(a(t))return i("Unable to create ~/.epiq");if(!(q.readFile(e)!==null)){let l=Ur(ts);if(a(l))throw new Error("Unable to create ~/.epiq/config.json")}let r=Or();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:d}=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})};var is=e=>Object.values(y().tags).find(t=>t.name===e),ss=e=>Object.values(y().contributors).find(t=>t.name===e),Wr=[{systemOnly:!0,intent:b.Move,mode:p.COMMAND_LINE,action:()=>{let e=H();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=te().commandMeta,n=()=>{let l=pe();if(!l)return i("No pending move state");let u=l.payload.id;if(!y().nodes[u])return i("Moved node not found");let v=l.payload.parent,E=y().nodes[v];if(!E)return i("Move parent not found");let C=A(v).findIndex(R=>R.id===u);return C===-1?i("Moved node not found among rendered children"):(O.navigate({currentNode:E,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=A(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=A(d.parentNodeId),u=l.findIndex(({id:R})=>R===d.id);if(u===-1)return i("Target not found among siblings");let f=l[u-1],v=l[u+1],E=v!=null?{at:"before",sibling:v.id}:f!=null?{at:"after",sibling:f.id}:{at:"start"};Te({id:F(),action:"move.node",payload:{id:d.id,parent:d.parentNodeId,pos:E},...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(rn(1));if(t==="previous")return I({mode:p.MOVE}),r(rn(-1));if(t==="to-next")return I({mode:p.MOVE}),r(nn(1));if(t==="to-previous")return I({mode:p.MOVE}),r(nn(-1));if(t==="confirm"){I({mode:p.DEFAULT});let l=pe();if(!l)return i("No pending move to confirm");let u=K(l);if(a(u))return u;let f=n();return a(f)?i(f.message):(Te(null),c("Moved item",null))}return t==="cancel"?(Te(null),I({mode:p.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}},{intent:b.Delete,mode:p.COMMAND_LINE,action:()=>{let e=H();if(a(e))return i("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=y(),r=A(t.id)[n];return r?K({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=H();if(a(e))return i("Unable to resolve user ID");let t=ve(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(!A(n.id)[o])return i("No selected field");let d=A(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=Jn(l);if(a(u))return i("Failed to edit field");let f=u.data;return f===l?c("No changes made",null):d.title==="Description"?K({id:F(),action:"edit.description",payload:{id:d.id,md:f},...e.data}):d.title==="Title"?K({id:F(),action:"edit.title",payload:{id:d.id,name:f},...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}=te().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 j(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=H();if(a(e))return i("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=y(),r=A(t.id)[n];if(!r)return i("Unable to close issue, no target found");if(!r.parentNodeId)return i("No target parent found");if(!J(r))return i("Cannot close in this context");let o=K({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=H();if(a(e))return i("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=y(),r=A(t.id)[n];if(!r)return i("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):Ye(r.id,"TICKET");if(a(o))return i("Cannot reopen in this context");let s=o.data,d=K({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}=ie(),r=nt()?.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=an({userName:o,userId:s,preferredEditor:t??""});return a(d)?d:(Dt({userName:o,userId:s}),I({mode:p.DEFAULT}),c(`Username set to "${r}"`,null))}},{intent:b.Init,mode:p.COMMAND_LINE,action:()=>{let e=cn();if(a(e))return e;let{rootNodeId:t,nodes:n}=y();return O.navigate({currentNode:n[t],selectedIndex:0}),c("Project initialized",null)}},{intent:b.SetEditor,mode:p.COMMAND_LINE,action:()=>{let e=nt()?.trim();if(!e)return i("No editor provided");let t=an({preferredEditor:e});return a(t)?t:(Dt({preferredEditor:e}),I({mode:p.DEFAULT}),c(`Editor configuration set to "${e}"`,null))}},{intent:b.NewItem,mode:p.COMMAND_LINE,action:(e,t)=>{let n=H();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=K(l);if(a(u))return u;let f=N.getNode(u.data.result.id);if(!f)return i("Created node not found");if(!f.parentNodeId)return u;let v=N.getNode(f.parentNodeId);return v?(O.navigate({currentNode:v,selectedIndex:N.getSiblings(f.parentNodeId).findIndex(({id:E})=>E===f.id)}),u):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:l}=y(),u=N.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=ve(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=A(o.id)[s],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&l?.context==="SWIMLANE"?l:(()=>{let R=ve(r,"SWIMLANE");return a(R)?null:R.data})();if(!u)return i("Unable to add issue in this context");let f=st({name:t.inputString,parent:u.id,user:n.data}),v=Re(f);if(v.some(R=>a(R)))return i("Issue create failed: "+v.filter(a).map(R=>R.message).filter(Boolean).join(", "));let E=v[0];if(!E||a(E))return i("Issue creation failed");let C=f[0]?.payload.id;return C?(O.navigate({currentNode:u,selectedIndex:N.getSiblings(u.id).findIndex(({id:R})=>R===C)}),c("Issue created",null)):i("Unable to determine ticket id")}return pn()},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.SetView,mode:p.COMMAND_LINE,action:()=>{let{commandMeta:e}=te();return e.validity===oe.Invalid?i("Invalid command "+Z):(j(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=H();if(a(e))return i("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=y(),r=A(t.id)[n];if(!r)return i("Missing node");if(r.readonly)return i("Cannot rename readonly node");let o=nt();return o?K({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.TagTicket,mode:p.COMMAND_LINE,action:()=>{let e=H();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=te().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let{selectedIndex:o,currentNode:s}=y(),d=A(s.id)[o];if(!d)return i("Invalid tag target");let l=Ye(d.id,"TICKET");if(a(l))return i("Unable to tag issue in this context");let u=l.data,f=is(r),v;if(f)v=f.id;else{let R=F(),M=K({id:F(),action:"create.tag",payload:{id:R,name:r},userId:e.data.userId,userName:e.data.userName});if(a(M))return M;v=M.data.result.id}let E=N.getFieldByTitle(u.id,"Tags");return E?A(E.id).some(R=>R.props?.value===v)?i("Already tagged with that tag"):K({id:F(),action:"tag.issue",payload:{id:F(),target:u.id,tagId:v},...e.data}):i("Unable to locate tags field")},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.AssignUserToTicket,mode:p.COMMAND_LINE,action:()=>{let e=H();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=te().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee");let{selectedIndex:o,currentNode:s}=y(),d=A(s.id)[o];if(!d)return i("Invalid assign target");let l=Ye(d.id,"TICKET");if(a(l))return i("Unable to assign issue in this context");let u=l.data,f=ss(r),v;if(f)v=f.id;else{let R=F(),M=K({id:F(),action:"create.contributor",payload:{id:R,name:r},userId:e.data.userId,userName:e.data.userName});if(a(M))return M;v=M.data.result.id}let E=N.getFieldByTitle(u.id,"Assignees");return E?A(E.id).some(R=>R.props?.value===v)?i("Assignee already assigned"):K({id:F(),action:"assign.issue",payload:{id:F(),target:u.id,contributor:v},...e.data}):i("Unable to locate assignees field")},onSuccess:()=>I({mode:p.DEFAULT})},{intent:b.Sync,mode:p.COMMAND_LINE,action:async()=>{D(()=>""),I({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:e,userName:t}=ie();if(!e)return i("Unable to resolve userId");if(!t)return i("Unable to resolve userName");let n=Fe()?cn():c("No pending default events",null);if(a(n))return i(`Unable to persist default events. ${n.message}`);let r=H();if(a(r)||!r.data)return i("Unable to resolve event log path");let o=_e(r.data);logger.debug("[sync-command] pending defaults",Fe());let s=await It({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=We();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=ve(y().breadCrumb,"BOARD");if(a(e))return e;let t=We();if(a(t))return i(t.message);let n=t.data,{modifier:r}=te().commandMeta,o;if(r==="now"){let E=dn();if(a(E))return E;let C=Ee(n);return C.some(a)?i(C.map(R=>R.message).join(", ")):(I({mode:p.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}if(r==="prev"){let E=y().eventLog.at(-2),C=Ft(E);if(C===null)return i("No previous event to peek");o=C}else if(r==="next"){let E=y().unappliedEvents.at(0),C=Ft(E);if(C===null)return i("No next event to peek");o=C}else{let E=Ze(r);if(!E)return i("Invalid peek date");o=E.getTime()}let s=e.data.id,{appliedEvents:d,unappliedEvents:l}=nr(n,o),u=dn();if(a(u))return u;let f=Ee(d);if(f.some(a))return i(f.map(E=>E.message).join(", "));let v=y().nodes[s];return v?(O.navigate({currentNode:v,selectedIndex:0}),I({mode:p.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:l}),c("Peeking ",!0)):i("Board did not exist at peek date")}}];var as=new Set(["peek","filter","view-help"]),G=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=te();if(!t)return i("No command to confirm");if(!e&&n===oe.Invalid)return i("Invalid command");let s=Vn(t);if(Bn(),y().readOnly&&!as.has(s))return Oe({result:Z.Fail,message:"Command not available in readonly state",data:null});let d=Wr.filter(u=>e||u.systemOnly!==!0).find(u=>u.intent===s);if(!d)return Oe({result:Z.Fail,message:"Command not found",data:null});let l=await d.action(d,{command:t,inputString:o,modifier:r});return a(l)?Oe(l):($n({addToHistory:!e}),d.onSuccess?.(),Oe(l))};var bt=[{intent:h.Exit,mode:p.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(I({mode:p.COMMAND_LINE}),D(()=>"move cancel"),G({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:p.DEFAULT,description:"[m] move init/confirm",action:()=>(I({mode:p.COMMAND_LINE}),D(()=>"move start"),G({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:p.MOVE,action:()=>(I({mode:p.COMMAND_LINE}),D(()=>"move confirm"),G({isForceExecutedBySystem:!0}))}],ht=[{intent:h.MovePreviousItem,mode:p.MOVE,action:()=>pe()?(I({mode:p.COMMAND_LINE}),D(()=>"move previous"),G({isForceExecutedBySystem:!0})):i("No pending move")},{intent:h.MoveNextItem,mode:p.MOVE,action:()=>pe()?(I({mode:p.COMMAND_LINE}),D(()=>"move next"),G({isForceExecutedBySystem:!0})):i("No pending move")}],Br=[{intent:h.MoveToNextContainer,mode:p.MOVE,action:()=>pe()?(I({mode:p.COMMAND_LINE}),D(()=>"move to-next"),G({isForceExecutedBySystem:!0})):i("No pending move")},{intent:h.MoveToPreviousContainer,mode:p.MOVE,action:()=>pe()?(I({mode:p.COMMAND_LINE}),D(()=>"move to-previous"),G({isForceExecutedBySystem:!0})):i("No pending move")}];var $r={[P.WORKSPACE]:[...bt,...ht],[P.BOARD]:[...bt,...ht],[P.SWIMLANE]:[...bt,...ht,...Br],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var Hr=[{intent:h.AddItem,mode:p.DEFAULT,description:"[n] new...",action:()=>(I({mode:p.COMMAND_LINE}),D(()=>`${m.NEW} `),c("Adding new item",null))},{intent:h.Delete,mode:p.DEFAULT,description:"[d] delete",action:()=>(I({mode:p.COMMAND_LINE}),D(()=>`${m.DELETE} `),c("Deleting item",null))},{intent:h.InitCommandLine,mode:p.DEFAULT,description:"[:] focus command line",action:()=>(I({mode:p.COMMAND_LINE}),D(()=>""),c("Entering command line mode",null))},{intent:h.Confirm,mode:p.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(O.enterChildNode(),c("Entering context",null))},{intent:h.Exit,mode:p.DEFAULT,description:"[q] exit context",action:()=>(O.enterParentNode(),c("Exiting context",null))},{intent:h.NavPreviousItem,mode:p.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(O.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:h.NavNextItem,mode:p.DEFAULT,action:()=>(O.navigateToNextItem(),c("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:p.DEFAULT,action:()=>(O.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:p.DEFAULT,action:()=>(O.navigateToNextContainer(),c("Navigating to next container",null))},{intent:h.Edit,mode:p.DEFAULT,action:()=>(I({mode:p.COMMAND_LINE}),D(()=>"edit"),G(),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))},{intent:h.Sync,mode:p.DEFAULT,description:"[s] sync epiq with remote state branch",action:()=>(I({mode:p.COMMAND_LINE}),D(()=>"sync"),G({isForceExecutedBySystem:!0}),c("Synced",!0))}];var Kr=[{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:()=>(G(),c("Executing command",null))},{intent:h.MoveCursorLeft,mode:p.COMMAND_LINE,action:()=>(Ht(-1),c("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:p.COMMAND_LINE,action:()=>(Ht(1),c("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:p.COMMAND_LINE,action:()=>(Kt("left"),c("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:p.COMMAND_LINE,action:()=>(Kt("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:()=>(D((e,{remainder:t})=>t?e+t:e),c("Auto-completing command",null))},{intent:h.CaptureInput,mode:p.COMMAND_LINE,action:(e,{sequence:t})=>(D(n=>n+t),c("Capturing input",null))},{intent:h.EraseInput,mode:p.COMMAND_LINE,action:()=>(_n(),c("Erasing input",null))},{intent:h.EraseInputWord,mode:p.COMMAND_LINE,action:()=>(Wn(),c("Erasing input word",null))},{intent:h.GetLastCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(Hn(),c("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(Kn(),c("Getting next command from history",null))}];import ds from"chalk";var Rt=": for command line",Vr="q to exit",jr=`${ds.hex(hn.accent)("m")} to confirm`,ln={[P.WORKSPACE]:[Rt],[P.BOARD]:[Rt],[P.BOARD+p.COMMAND_LINE]:[Rt],[P.SWIMLANE]:[Rt],[P.TICKET+p.HELP]:[Vr],[P.SWIMLANE+p.HELP]:[Vr],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+p.MOVE]:[jr],[P.TICKET+p.MOVE]:[jr]};var St=e=>e.trim().toLocaleLowerCase(),cs=(e,t)=>{let n=N.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},ls=e=>{let{tags:t}=y(),n=N.getFieldByTitle(e,"Tags");return n?V(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},us=e=>{let{contributors:t}=y(),n=N.getFieldByTitle(e,"Assignees");return n?V(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},zr=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return St(e.title??"").includes(n);case"description":return St(cs(e.id,"Description")).includes(n);case"tag":return ls(e.id).map(St).some(l=>l.includes(n));case"assignee":return us(e.id).map(St).some(l=>l.includes(n));default:return!0}};function qr(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 Gr=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 At,un,ms=new Set,Jr=()=>{for(let e of ms)e()};function Yr(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=qr(t,o,r);if(a(u))return logger.error(u.message),u;let f=u.data,{context:v}=l,E=ln[v+n]??ln[v]??[],C=[...Hr,...$r[v]??[],...Kr],R=Gr(C),M=ps(o,s),Q=M[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,currentNode:l,breadCrumb:f,availableHints:E,availableActions:C,actionIndex:R,selectedNode:Q,renderedChildrenIndex:M})}var y=()=>(At||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),At);function zt(e){un=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=Yr(t);return a(n)?n:(At=n.data,Jr(),c("State initialized",null))}function j(e){let t=y(),n=e(t),r=Yr(n);return a(r)?i(r.message??"Unable to update state"):(At=r.data,Jr(),c("State updated",null))}var I=e=>j(t=>({...t,...e}));var ps=(e,t)=>{let n={};for(let r of Object.values(e))J(r)&&t.length>0&&!t.every(o=>zr(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},A=e=>y()?.renderedChildrenIndex[e]??[],dn=()=>un?zt(un):i("Cannot reset state: no initial workspace found");var O={exit(){process.exit(0)},enterChildNode(){let e=y(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=A(t.id)[n];!r||t.context==="FIELD"||O.navigate({currentNode:r,selectedIndex:A(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=A(n.id),o=r.findIndex(({id:d})=>d===e.id),s=r.length===0?-1:o>=0?o:0;O.navigate({currentNode:n,selectedIndex:s})},navigateToNextItem:()=>Xr(1),navigateToPreviousItem:()=>Xr(-1),navigateToNextContainer:()=>Qr(1),navigateToPreviousContainer:()=>Qr(-1),navigate:({currentNode:e=y().currentNode,selectedIndex:t})=>{I({currentNodeId:e.id,selectedIndex:t})}},Xr=e=>{let t=y(),n=A(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;O.navigate({selectedIndex:o})},Qr=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=A(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=A(l.id),f=Math.max(0,u.length-1),v=Math.min(Math.max(0,r),f),E=u.length?v:-1;O.navigate({currentNode:l,selectedIndex:E})};var ce="system",le="ACTOR",Ve=gs(),ue=null;function fs(){let e=Object.values(y().nodes).find(r=>r.context==="WORKSPACE");if(!e)throw new Error("No workspace found in event log");let[t]=A(e.id),[n]=t?A(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 vs(){let e=fs();O.navigate(e)}function ys(){let e=Ve(),t=Ve(),n=Ve(),r=Ve(),o=Ve();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:"Review",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:gt,name:"Closed",parent:e}},{id:de(),userId:ce,userName:le,action:"add.swimlane",payload:{id:X,name:"Closed",parent:gt}},{id:de(),userId:ce,userName:le,action:"lock.node",payload:{id:gt}},{id:de(),userId:ce,userName:le,action:"lock.node",payload:{id:X}}]}function Fe(){return ue!==null}function cn(){if(!ue||ue.length===0)return ue=null,c("No pending default events to persist",null);let e=ue.map(t=>lt({event:t})).filter(a);return e.length>0?i([Me.bold.red("Persisting default events failed"),"",...e.map((t,n)=>`${Me.dim.gray(`${n+1}.`)} ${Me.dim(t.message)}`),`
37
+ `].join(`
38
+ `)):(ue=null,c("Persisted pending default events",null))}function Zr(e){let t;e.some(r=>r.action==="init.workspace")?(ue=null,t=Ee(e)):(ue=ys(),t=Ee([...ue]));let n=t.filter(a);return n.length>0?i([Me.bold.red("Materializing failed"),"",...n.map((r,o)=>`${Me.dim.gray(`${o+1}.`)} ${Me.dim(r.message)}`),`
39
+ `].join(`
40
+ `)):(vs(),c("State booted successfully",null))}var eo=(e,t)=>{let r=A(e.id).find(o=>o.title===t);return r&&typeof r.props?.value=="string"?qe(r.props.value):""};var xe=e=>{let t=ae(e??process.cwd()),n=We(t);if(a(n))return i(n.message);let r=Zr(n.data);return a(r)?i(r.message):c("Booted Epiq state",{root:t})},wt=()=>{let e=_r();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")},no=(e,t)=>{let r=A(e.id).find(o=>o.title===t);return r?A(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},Es=e=>no(e,"Tags").map(t=>N.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),Ns=e=>no(e,"Assignees").map(t=>N.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),ro=(e={})=>{let t=xe(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)},oo=(e={})=>{let t=xe(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===X,readonly:!!r.readonly}));return c("Listed swimlanes",n)},io=e=>{let t=xe(e.repoRoot);if(a(t))return t;let n=Object.values(y().nodes).filter(J).filter(r=>e.includeClosed||r.parentNodeId!==X).map(r=>({id:r.id,title:qe(r.title),description:eo(r,"Description"),parentId:r.parentNodeId,isClosed:r.parentNodeId===X,readonly:!!r.readonly,tags:Es(r),assignees:Ns(r)}));return c("Listed issues",n)},so=e=>{let t=xe(e.repoRoot);if(a(t))return t;let n=wt();if(a(n))return n;let r=N.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=st({name:e.title,parent:e.parentId,user:n.data}),d=Re(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")},ao=e=>{let t=xe(e.repoRoot);if(a(t))return t;let n=wt();if(a(n))return n;let r=N.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(!J(r))return i("Can only close issues");if(r.parentNodeId===X)return i("Issue is already closed");let o={id:to(),userId:n.data.userId,userName:n.data.userName,action:"close.issue",payload:{id:e.issueId,parent:r.parentNodeId}},d=Re([o]).find(a);return d?i(d.message):c("Closed issue",{id:e.issueId,closed:!0})},co=(e={})=>{let t=xe(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})},lo=e=>{let t=xe(e.repoRoot);if(a(t))return t;let n=wt();if(a(n))return n;let r=N.getNode(e.issueId);if(!r)return i(`Unable to locate issue: ${e.issueId}`);if(!J(r))return i("Can only move issues");let o=N.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:to(),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=Re([s]).find(a);return l?i(l.message):c("Moved issue",{id:e.issueId,parentId:e.parentId,position:e.position??{at:"end"}})},uo=async(e={})=>{let t=ae(e.repoRoot??process.cwd()),n=wt();if(a(n))return n;let r=await It({cwd:t,ownEventFileName:_e({userId:n.data.userId,userName:n.data.userName})});return a(r)?r:c("Synced Epiq state",r.data)};var ge=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Cs=()=>{let e=new xs({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:S.object({repoRoot:S.string().optional()})},async t=>ge(await co(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:S.object({repoRoot:S.string().optional(),includeClosed:S.boolean().optional()})},async t=>ge(await io(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:S.object({repoRoot:S.string().optional()})},async t=>ge(await ro(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:S.object({repoRoot:S.string().optional(),boardId:S.string().optional()})},async t=>ge(await oo(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue",inputSchema:S.object({title:S.string().min(1),parentId:S.string().min(1),repoRoot:S.string().optional()})},async t=>ge(await so(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:S.object({issueId:S.string().min(1),repoRoot:S.string().optional()})},async t=>ge(await ao(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:S.object({issueId:S.string().min(1),parentId:S.string().min(1),position:S.discriminatedUnion("at",[S.object({at:S.literal("start")}),S.object({at:S.literal("end")}),S.object({at:S.literal("before"),sibling:S.string().min(1)}),S.object({at:S.literal("after"),sibling:S.string().min(1)})]).optional(),repoRoot:S.string().optional()})},async t=>ge(await lo(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:S.object({repoRoot:S.string().optional()})},async t=>ge(await uo(t))),e},bs=async()=>{let e=Cs(),t=new Is;await e.connect(t)};await bs();export{Cs as createMcpServer,ge as resultJson,bs as startMcpServer};
package/package.json CHANGED
@@ -1,18 +1,35 @@
1
1
  {
2
2
  "name": "epiq",
3
- "version": "0.2.29",
3
+ "version": "0.3.0",
4
4
  "license": "UNLICENSED",
5
5
  "type": "module",
6
6
  "description": "EPIQ - CLI based issue tracker",
7
+ "keywords": [
8
+ "issue-tracker",
9
+ "task-manager",
10
+ "productivity",
11
+ "project-management",
12
+ "kanban",
13
+ "terminal",
14
+ "git",
15
+ "tui",
16
+ "commandline",
17
+ "offline-first",
18
+ "git-based",
19
+ "local-first",
20
+ "developer-tools",
21
+ "vim-inspired"
22
+ ],
7
23
  "bin": {
8
- "epiq": "dist/cli.js"
24
+ "epiq": "dist/cli.js",
25
+ "epiq-mcp": "dist/mcp.js"
9
26
  },
10
27
  "engines": {
11
28
  "node": ">=18"
12
29
  },
13
30
  "scripts": {
14
31
  "build": "tsc --noEmit",
15
- "build:npm": "rm -rf ./dist && esbuild source/cli.tsx --bundle --packages=external --platform=node --format=esm --target=node18 --minify --outfile=dist/cli.js --banner:js='#!/usr/bin/env node'",
32
+ "build:npm": "rm -rf ./dist && esbuild source/cli.tsx --bundle --packages=external --platform=node --format=esm --target=node18 --minify --outfile=dist/cli.js --banner:js='#!/usr/bin/env node' && esbuild source/mcp/server.ts --bundle --packages=external --platform=node --format=esm --target=node18 --minify --outfile=dist/mcp.js --banner:js='#!/usr/bin/env node'",
16
33
  "build:sea:bundle": "rm -rf ./dist && esbuild source/cli.tsx --bundle --platform=node --format=cjs --target=node18 --minify --outfile=dist/sea.cjs",
17
34
  "build:sea": "node --build-sea sea-config.json",
18
35
  "build:publish": "pnpm build:npm",
@@ -25,12 +42,15 @@
25
42
  "pack:check": "rm -f epiq-*.tgz && npm pack && FILE=$(ls -t epiq-*.tgz | head -n 1) && echo \"$FILE\" && tar -tf \"$FILE\"",
26
43
  "publish:dry": "rm -f epiq-*.tgz && npm pack && FILE=$(ls -t epiq-*.tgz | head -n 1) && npm publish --dry-run \"$FILE\"",
27
44
  "publish:tarball": "FILE=$(ls -t epiq-*.tgz | head -n 1) && echo \"Publishing $FILE\" && npm publish \"$FILE\"",
28
- "release": "pnpm test && pnpm pack:check && pnpm publish:tarball"
45
+ "release": "pnpm test && pnpm pack:check && pnpm publish:tarball",
46
+ "start:mcp": "IS_LOCAL=true tsx source/mcp/server.ts",
47
+ "inspect:mcp": "pnpm dlx @modelcontextprotocol/inspector"
29
48
  },
30
49
  "files": [
31
50
  "dist"
32
51
  ],
33
52
  "dependencies": {
53
+ "@modelcontextprotocol/sdk": "^1.29.0",
34
54
  "ink": "^6.8.0",
35
55
  "meow": "^14.1.0",
36
56
  "react": "^19.2.4",
package/readme.md CHANGED
@@ -1,9 +1,10 @@
1
- > ⓘ First stable release scheduled for end of April
1
+ > ⓘ First stable release scheduled for end of April 2026
2
2
 
3
3
  # Epiq
4
4
 
5
- **CLI-native issue tracker** — powered by Git.
6
- Manage all your projects directly via the command line, edit in your favorite editor.
5
+ Issue tracking is a part of the development lifecycle, but it often becomes a painful context switching exercise with poor ergonomics. `Epiq` provides issue tracking as a portable, integrated part of the development environment, with access to all the powerful tooling developers are used to. Epiq is a **CLI-native issue tracker** — powered by Git in which you can manage all your projects directly via the command line in a visual kanban board and edit content in your favorite, personalized editor.
6
+
7
+ With great attention to user ergonomics, epiq intends to make project management painless and friction free again, and has developer satisfaction as its primary target.
7
8
 
8
9
  ```
9
10
  '███████╗██████╗ ██╗ ██████╗ '
@@ -24,10 +25,10 @@ Epiq renders your issue board directly in the terminal using ASCII and stores it
24
25
  ## Features
25
26
 
26
27
  - Issue tracking — track work in tickets with name, description, tags, assignees, history log, etc.
28
+ - Ergonomics — fast keyboard-driven ux, command line with history, syntax highlighting etc.
29
+ - Time travel — inspect your app 1h, 1 week or 1 year ago
27
30
  - Filtering — query issues by description, tags, assignees, etc.
28
- - Ergonomics — fast keyboard-driven navigation
29
31
  - Autocompletion — minimize typing, stay in flow
30
- - Command system — built with ergonomics and automation in mind
31
32
  - Multi-user — real-time synchronization of board
32
33
  - Traceable event log — state is a full history of every change ever made
33
34
 
@@ -38,7 +39,7 @@ Most issue trackers live outside your workflow. Epiq brings issue tracking into
38
39
  These design choices result in a system that is:
39
40
 
40
41
  - **Zero setup** — no account registration required
41
- - **Repo-native** — your issues live where your code lives
42
+ - **Repo-native** — your issues can live where your code lives
42
43
  - **Offline-friendly** — works anywhere, with eventual consistency as a promise
43
44
  - **Speed** — local first, and eventual consistency makes epiq edits instant
44
45
  - **Portable** — run on your local machine, on a remote Linux server or your grandma’s connected toaster
@@ -47,6 +48,26 @@ These design choices result in a system that is:
47
48
 
48
49
  ---
49
50
 
51
+ ## MCP & Agent Compatibility
52
+
53
+ Epiq provides a MCP (Model Context Protocol) server for agents to interact with, making it easy to plug into modern agent frameworks.
54
+
55
+ To register Epiq with MCP-compatible clients (e.g. Claude Desktop), add it as a server using the `epiq-mcp` binary. Example configuration:
56
+
57
+ ```json
58
+ {
59
+ "mcpServers": {
60
+ "epiq": {
61
+ "command": "epiq-mcp"
62
+ }
63
+ }
64
+ }
65
+ ```
66
+
67
+ Once registered, agents can interact with your local Epiq instance through the MCP.
68
+
69
+ ---
70
+
50
71
  ### Example workflow:
51
72
 
52
73
  An issue lifecycle as epiq commands:
@@ -129,22 +150,22 @@ Clear all filters with `:filter clear`
129
150
 
130
151
  - You can reopen a task by visiting the `Closed` board, selecting an issue and typing command `:reopen`. This will restore the issue to its last previous location.
131
152
 
153
+ ### Reuse command
154
+
155
+ - Pro tip: just like in any terminal - if you need to do repeating tasks over and over again, you can just put yourself in the command mode, and then press arrow up, in order to access the last executed command. This helps a lot when you create tasks with similar names, or add the same tag to many tickets and so on.
156
+
132
157
  ---
133
158
 
134
159
  ## How epiq is synchronized
135
160
 
136
- Epiq uses Git in the background to synchronize state between clients. You do not need to do any manual git commands to make it work. Running `:sync` pulls and pushes changes between your local state and the remote.
161
+ Epiq uses Git in the background to synchronize state between clients. No manual git commands are required to make it work. Running `:sync` pulls and pushes changes between your local state and the remote state.
137
162
 
138
163
  - Your issue data is stored in a dedicated branch managed automatically by epiq
139
- - A local `.epiq/` folder is created in your project as a cache
140
-
141
- The `.epiq/` folder:
164
+ - A local `.epiq/` folder is created in your project as a local cache
142
165
 
143
- - Is non-authoritative and used for caching and local tracking
144
- - Can be committed if you want your board state versioned alongside your code
145
- - Is optional — epiq works whether you commit it or not
166
+ The `.epiq/` folder is non-authoritative and used for caching and local tracking. It can optionally be committed if you want your board state versioned alongside your code.
146
167
 
147
- > The system is designed to avoid merge conflicts.
168
+ > The system is designed to assure robustness and uses a number of techniques and design patterns to avoid merge conflicts.
148
169
 
149
170
  ---
150
171