epiq 0.4.7 → 0.4.8

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.
Files changed (3) hide show
  1. package/dist/index.js +50 -50
  2. package/dist/mcp.js +44 -44
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,69 +1,69 @@
1
1
  #!/usr/bin/env node
2
- import Jr from"chalk";import{render as bl}from"ink";import Il from"meow";import Sl from"react";import{Box as et}from"ink";import G from"react";import pt from"chalk";import{monotonicFactory as Hc,ulid as Le}from"ulid";import{useSyncExternalStore as _c}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function Hn(e){return e.context==="WORKSPACE"}function le(e){return e.context==="TICKET"}function eo(e){return e.context==="FIELD"}var tt=e=>e.context==="SWIMLANE",to=e=>e.context==="BOARD";var Ee={None:"none",Success:"success",Fail:"fail"},s=e=>({status:Ee.Fail,message:e,value:null}),l=(e,t)=>({status:Ee.Success,message:e,value:t}),c=e=>e.status==="fail",Ne=e=>e.status==="success";var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function jt(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Wt=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Kn=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var no=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},ro=(e,t)=>t?e.get(t)??[]:[];var oo=new WeakMap,aa=e=>{let t=oo.get(e);return t||(t=no(e),oo.set(e,t)),t};var io=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return ro(aa(e),r).filter(i=>jt(r,i)>=n)};var da={hint:"",hints:[],overlap:0,remainder:""},so=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return da;let o=io({wordList:r,inputToMatch:e,overlapThreshold:1});return ca(t,o)},ca=(e,t)=>{let n=t[0]??"",r=jt(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),a=r<(o??"").length,d=!!i,p=(d&&a?o:n)+(d&&a?":":" "),y=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:y}};var ao=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var te={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:(e,t,n,r,o={},i="horizontal")=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[]}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[]})};import{ulid as ma}from"ulid";var qe=24n,la=qe*4n,vt=(1n<<la)-1n,ua=/^[0-9a-f]+$/;function co(e){return!e||!ua.test(e)?s(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function Ce(e,t=qe){if(e<0n)return s("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function V(e,t){if(!e&&!t)return Ce(vt/2n,qe);let n=e?co(e):l("Resolved lower bound",0n);if(c(n))return n;let r=t?co(t):l("Resolved upper bound",vt);if(c(r))return r;let o=n.value,i=r.value;if(i<=o)return Ce(vt/2n,qe);let a=(o+i)/2n;return a===o||a===i?s("No rank space available between neighbors"):Ce(a,qe)}function lo(){return Ce(vt/2n,qe)}function uo(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=vt*BigInt(r+1)/(t+1n),i=Ce(o,qe);if(c(i))return i;n.push(i.value)}return l("Resolved evenly spaced ranks",n)}var Vn=(e,t)=>{let n=F(e),r=uo(n.length);if(c(r))return r;let o={};for(let i=0;i<n.length;i++){let a=n[i],d=r.value[i];if(!a||!d)return s("Unable to assign rebalance rank");o[a.id]=d}return l("Created rebalance event",{id:ma(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var pa=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[be,Ht]=pa;var k=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),ga={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=te.workspace(t,n,r);zn(o);let i=b.createNode(o);return c(i)?k(i.message??"Failed to initialize workspace",e):Hn(i.value)?l("Workspace initialized",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=te.workspace(t,n,r),i=b.createNode(o);return c(i)?k(i.message??"Failed to add workspace",e):Hn(i.value)?l("Added workspace",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=b.createNode(te.board(t,n,r,o));return c(i)?k(i.message??"Unable to create board",e):to(i.value)?l("Added board",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=b.createNode(te.swimlane(t,n,r,o));return c(i)?k(i.message??"Unable to create swimlane",e):tt(i.value)?l("Added swimlane",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=b.createNode(te.ticket(t,n,r,o));return c(i)?k(i.message??"Unable to create issue",e):le(i.value)?l("Added issue",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:i}=e.payload,a=b.createNode(te.field(t,n,r,i,{value:o},n.includes("Description")?"vertical":"horizontal"));return c(a)?k(a.message??`Unable to create field: ${n}`,e):eo(a.value)?l("Added field",{action:e.action,result:a.value}):s("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!b.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=b.renameNode(t,n);return c(o)?k(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=b.tombstoneNode(t);return c(n)?k(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=b.createTag({id:t,name:n});return c(r)?k(r.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=b.createContributor({id:t,name:n});return c(r)?k(r.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:r.value})},"tag.issue":e=>{let{id:t,target:n,tagId:r,rank:o}=e.payload,i=b.tag(n,r,t,o);return c(i)?k(i.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:i.value})},"untag.issue":e=>{let{target:t,tagId:n}=e.payload,r=b.untag(t,n);return c(r)?k(r.message??"Unable to untag ",e):l("Issue untagged",{action:e.action,result:r.value})},"assign.issue":e=>{let{id:t,contributor:n,target:r,rank:o}=e.payload,i=b.assign(r,n,t,o);return c(i)?k(i.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:i.value})},"unassign.issue":e=>{let{target:t,contributor:n}=e.payload,r=b.unassign(t,n);return c(r)?k(r.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:r.value})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.moveNodeToRank({id:t,parentId:n,rank:r});return c(o)?k(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=b.editValue(t,n);return c(r)?k(r.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return k("Unable to locate issue",e);if(!le(o))return k("Can only close issues",e);let i=b.getNode(be);if(!i)return k("Unable to locate target swimlane",e);if(n!==i.id)return k("Close target must be closed swimlane",e);let a=b.moveNodeToRank({id:t,parentId:n,rank:r});return c(a)?k(a.message??"Unable to close issue",e):l("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return k("Unable to locate issue",e);if(!le(o))return k("Can only reopen issues",e);let i=b.getNode(be);if(!i)return k("Unable to locate closed swimlane",e);if(n===i.id)return k("Cannot reopen issue into closed swimlane",e);if(!b.getNode(n))return k("Reopen parent no longer exists",e);let d=b.moveNodeToRank({id:t,parentId:n,rank:r});return c(d)?k(d.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=b.lockNode(t);return c(n)?k(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let i=b.getNode(r);if(!i)return k(`Unable to locate node ${r}`,e);if(i.parentNodeId!==t)return k(`Node ${r} is not child of ${t}`,e);let a=b.updateNode({...i,rank:o});if(c(a))return k(a.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})}},fa=(e,t)=>{let n=b.getNode(e);n&&b.updateNode({...n,log:[...n.log??[],t]})},va=e=>{switch(e.action){case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"delete.node":case"move.node":case"close.issue":case"reopen.issue":return[e.payload.id];case"edit.description":let t=[e.payload.id],n=v().nodes[e.payload.id]?.parentNodeId;return n&&t.push(n),t;case"tag.issue":case"untag.issue":case"assign.issue":case"unassign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function xt(e,t=!1){let n=ga[e.action](e);if(c(n))return n;t||([...new Set(va(e))].forEach(a=>fa(a,e)),de(a=>({...a,eventLog:[...a.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?k("Invalid user ID format",e):(b.createContributor({name:o,id:r}),n)}var Ge=e=>e.map(t=>xt(t));import Ta from"node:fs";import Ra from"node:path";import{decodeTime as Ma,monotonicFactory as Pa}from"ulid";import{z as Nt}from"zod";var Kt={autoSync:!1,preferredEditor:null,userName:null,userId:null},fe=()=>Kt,nt=e=>(Kt={...Kt,...e},Kt);import yt from"node:fs";import Ie from"node:path";var qn=process.env.IS_LOCAL==="true",Se=".epiq",ue=".epiq-global",Vt="events",xa="project.json",mo=e=>Ie.join(e,Se),zt=e=>Ie.join(e,Se),Ae=e=>Ie.join(zt(e),xa),ht=e=>Ie.join(zt(e),Vt),ya=e=>{let t=Ie.join(e,Se);return yt.existsSync(t)&&yt.statSync(t).isDirectory()},ha=e=>{let t=Ae(e);return yt.existsSync(t)&&yt.statSync(t).isFile()},we=e=>{let t=Ie.resolve(e);for(;;){if(ya(t))return l("Resolved closest .epiq root",t);let n=Ie.dirname(t);if(n===t)return s("No .epiq directory found in any parent");t=n}},qt=e=>{let t=Ie.resolve(e);for(;;){if(ha(t))return l("Resolved closest epiq project root",t);let n=Ie.dirname(t);if(n===t)return s("No .epiq/project.json found in any parent");t=n}},po=e=>{let t=ht(e);try{return yt.mkdirSync(t,{recursive:!0}),l("Resolved events dir",t)}catch(n){return s(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}};import Gt from"node:fs";import Yn from"node:path";import{decodeTime as Ea}from"ulid";import{z as Gn}from"zod";var Na=Gn.object({userId:Gn.string().min(1).default("unknown"),userName:Gn.string().min(1).default("unknown")}),Ca=e=>{let[t,n]=Yn.basename(e,".jsonl").split("."),r=Na.safeParse({userId:t,userName:n});return r.success?l("Parsed event file actor",r.data):s(`Invalid event file name ${Yn.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},ba=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"):l("Resolved persisted action",t[0])},Ia=(e,t)=>t in e,Sa=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Aa=e=>{let{userId:t,userName:n,...r}=e,o=ba(r);if(c(o))return s(o.message);let i=o.value,a=e.id?.[0];return a?Ia(r,i)?l("Decoded persisted event",Sa({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")},Yt=e=>{if(!Gt.existsSync(e))return l("Event file missing",[]);let t=Ca(e);if(c(t))return s(t.message);let n=Gt.readFileSync(e,"utf8"),r=[];for(let o of n.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 d=Xn(a);if(c(d))return s(`${d.message} in ${e}: ${i}`);r.push({...d.value,userId:t.value.userId,userName:t.value.userName})}return l("Parsed persisted events file",r)};function go(e){let t=ht(e);if(!Gt.existsSync(t))return s("No events found");let n=Gt.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Yn.join(t,o)),r=[];for(let o of n){let i=Yt(o);if(c(i))return s(i.message);r.push(...i.value)}return l("All events loaded",wa(r))}function Et(e){let t=go(e);if(c(t))return s(t.message);let n=[];for(let r of t.value){let o=Aa(r);if(c(o))return s(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);n.push(o.value)}return l("Loaded merged events",n)}function fo(e=process.cwd()){let t=go(e);return c(t)?s(t.message):l("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var wa=e=>{let t=new Map;for(let d of e){let u=d.id[1]??null,m=t.get(u)??[];m.push(d),t.set(u,m)}for(let d of t.values())d.sort((u,m)=>u.id[0].localeCompare(m.id[0]));let n=[],r=new Set;a(t.get(null)??[]);let o=!0;for(;o;){o=!1;for(let d=0;d<n.length;d++){let u=n[d];if(!u)continue;let m=(t.get(u.id[0])??[]).filter(p=>!r.has(p.id[0]));if(m.length!==0){n.splice(d+1,0,...m);for(let p of m)r.add(p.id[0]);o=!0,d+=m.length}}}let i=e.filter(d=>!r.has(d.id[0])).sort((d,u)=>d.id[0].localeCompare(u.id[0]));return n.push(...i),n;function a(d){for(let u of d)r.has(u.id[0])||(n.push(u),r.add(u.id[0]))}},vo=(e,t)=>{let n=e.findIndex(r=>{try{return Ea(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var xo=e=>({action:e.action,payload:e.payload});var ho=1,yo=Pa(),ka=Nt.tuple([Nt.string().min(1),Nt.string().min(1).nullable()]),Da=Nt.looseObject({v:Nt.literal(ho),id:ka}),Xn=e=>{let t=Da.safeParse(e);return t.success?l("Parsed persisted event",t.data):s(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Xt=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",Q=()=>{let{userName:e,userId:t}=fe();return e?t?e.trim()?l("Successfully resolved actor ID",{userId:Xt(t),userName:Xt(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},Jn=({userId:e,userName:t})=>`${Xt(e)}.${Xt(t)}.jsonl`,La=(e,{userId:t,userName:n})=>{let r=Jn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return s(`Invalid event log file name: ${r}`);let i=Ra.join(ht(e),r);return l("Successfully resolved event log path",i)},Fa=(e,t)=>{let n={[e.action]:e.payload,v:ho,id:t};return Xn(n)};function Jt({event:e,rootDir:t=process.cwd()}){try{let n=we(t);if(c(n))return n;let r=po(n.value);if(c(r))return r;let o=La(n.value,{userId:e.userId,userName:e.userName});if(c(o))return o;let i=fo(n.value);if(c(i))return s(i.message);let a=i.value?yo(Math.max(Date.now(),Ma(i.value)+1)):yo(),d=Fa(xo(e),[a,i.value]);return c(d)?s(d.message):(Ta.appendFileSync(o.value,`${JSON.stringify(d.value)}
4
- `,"utf8"),l("Event persisted",{path:o.value,entry:d.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return s(`Failed to persist event: ${r}`)}}function K(e){let t=xt(e);if(t.status!==Ee.Success)return t;let n=Jt({event:e});return c(n)?n:t}function Eo(e){return e.map(t=>K(t))}var No=e=>Zn(F(e),{at:"end"}),Zn=(e,t={at:"end"})=>{let n=r=>c(r)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(V(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(V(void 0,r.rank)):s("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(V(r.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let r=Co(e,t.sibling);if(r<0)return s("Sibling not found");let o=r>0?e[r-1]:void 0,i=e[r];return i?n(V(o?.rank,i.rank)):s("Sibling not found")}case"after":{let r=Co(e,t.sibling);if(r<0)return s("Sibling not found");let o=e[r],i=r<e.length-1?e[r+1]:void 0;return o?n(V(o.rank,i?.rank)):s("Sibling not found")}}},F=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Co=(e,t)=>e.findIndex(n=>n.id===t),bo=(e,t,n={at:"end"})=>Zn(F(t).filter(r=>r.id!==e),n),rt=(e,t,n,r)=>{let o=bo(t,e,n);if(c(o))return o;if(!o.value.needsRebalance)return l("Resolved rank",o.value.rank);let i=Vn(e,r);if(c(i))return i;let a=K(i.value);if(c(a))return a;let d=bo(t,e,n);return c(d)?d:d.value.needsRebalance?s("Rank rebalance failed to create space"):l("Resolved rank after rebalance",d.value.rank)},ot=(e,t)=>{let n=No(e);if(c(n))return n;if(!n.value.needsRebalance)return l("Resolved rank",n.value.rank);let r=Vn(e,t);if(c(r))return r;let o=K(r.value);if(c(o))return o;let i=No(e);return c(i)?i:i.value.needsRebalance?s("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)};var $e=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return s("Node not found");if(r.context===t)return l("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return l("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return s(`No ancestor found for context: ${t}`)},er=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Qn=(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"),b={deleteNode(e){de(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return s("Edit target node not found");let o=Qn(r,"edit");if(o)return o;let i={...r,props:{...r.props,value:t}};return this.updateNode(i),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return s("Rename target node not found");let r=Qn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return F(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let a=Qn(o,"move");if(a)return a;if(er(t,e))return s("Cannot move node into its own descendant");let d={...o,parentNodeId:t,rank:n};return this.updateNode(d),l("Moved node successfully",d)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,a=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let p of F(m.id))a(p.id)}};a(e);let d={...structuredClone(t)};for(let u of i){if(!d[u])return s("Unable to locate node to delete");d[u]={...d[u],isDeleted:!0}}return n?(w({nodes:d}),l("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=de(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return c(t)?s("Unable to create contributor"):l("Created contributor",e)},assign(e,t,n,r){let o=this.getContributor(t),i=this.getNode(e);if(!i||!o)return s("Unable assign contributor to issue");let a=this.getFieldByTitle(i.id,"Assignees");if(!a)return s("Unable to locate assignees field");if(F(a.id).some(p=>p.props?.value===t))return s("Contributor already assigned");let u=te.field(n,o.name,a.id,r,{value:t}),m=this.createNode(u);return c(m)?m:l("Assigned contributor",u)},createTag(e){let t=de(n=>({...n,tags:{...n.tags,[e.id]:e}}));return c(t)?s("Could not create tag"):l("Tag created",e)},tag(e,t,n,r){let o=this.getTag(t),i=this.getNode(e);if(!o)return s("Unable to add tag, missing tag");if(!i)return s("Unable to add tag, missing target");let a=this.getFieldByTitle(i.id,"Tags");if(!a)return s("Unable to locate tags field");if(F(a.id).some(p=>p.props?.value===t))return s("Tag already assigned");let u=te.field(n,o.name,a.id,r,{value:t}),m=this.createNode(u);return c(m)?m:l("Tag added",u)},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return s("Unable to remove tag, missing tag");if(!r)return s("Unable to remove tag, missing target");let o=this.getFieldByTitle(r.id,"Tags");if(!o)return s("Unable to locate tags field");let i=F(o.id).find(d=>d.props?.value===t);if(!i)return l("Issue is not tagged with that tag",null);let a={...i,isDeleted:!0};return this.updateNode(a),l("Tag removed",a)},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return s("Unable to unassign, missing contributor");if(!r)return s("Unable to unassign, missing target");let o=this.getFieldByTitle(r.id,"Assignees");if(!o)return s("Unable to locate assignees field");let i=F(o.id).find(d=>d.props?.value===t);if(!i)return l("Issue is not assigned to that contributor",null);let a={...i,isDeleted:!0};return this.updateNode(a),l("Assignee removed",a)},createNode(e){let t=de(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return c(t)?s("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let n={...t,readonly:!0},r=de(o=>({...o,nodes:{...o.nodes,[e]:n}}));return c(r)?s(r.message):l("Locked node",n)},updateNode(e){let t=de(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return c(t)?t:l("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return F(e)}};var Y={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:Y.cyan,accent2:Y.magenta,primary:Y.white,secondary:Y.grayDark,secondary2:Y.grayLight,gray:Y.gray,green:Y.green,yellow:Y.yellow,red:Y.red};var h={red:Y.red,yellow:Y.yellow,green:Y.green,blue:Y.blue,magenta:Y.magenta,cyan:Y.cyan},it={urgent:h.red,critical:h.red,important:h.red,blocker:h.red,asap:h.red,immediate:h.red,fail:h.red,failure:h.red,broken:h.red,bug:h.red,error:h.red,incident:h.red,outage:h.red,production:h.red,crash:h.red,security:h.red,warning:h.yellow,warn:h.yellow,risky:h.yellow,risk:h.yellow,attention:h.yellow,pending:h.yellow,review:h.yellow,"needs-review":h.yellow,qa:h.yellow,testing:h.yellow,test:h.yellow,validate:h.yellow,verification:h.yellow,staging:h.yellow,check:h.yellow,"follow-up":h.yellow,followup:h.yellow,waiting:h.yellow,blocked:h.yellow,hold:h.yellow,done:h.green,complete:h.green,completed:h.green,success:h.green,ok:h.green,stable:h.green,resolved:h.green,fixed:h.green,closed:h.green,merged:h.green,released:h.green,deployed:h.green,approved:h.green,verified:h.green,working:h.green,healthy:h.green,pass:h.green,passing:h.green,info:h.blue,information:h.blue,note:h.blue,docs:h.blue,documentation:h.blue,doc:h.blue,guide:h.blue,help:h.blue,explanation:h.blue,detail:h.blue,details:h.blue,context:h.blue,design:h.blue,discussion:h.blue,proposal:h.blue,idea:h.blue,feature:h.magenta,enhancement:h.magenta,improvement:h.magenta,refactor:h.magenta,refactoring:h.magenta,cleanup:h.magenta,optimize:h.magenta,optimization:h.magenta,perf:h.magenta,performance:h.magenta,upgrade:h.magenta,migration:h.magenta,modernize:h.magenta,debt:h.magenta,todo:h.cyan,next:h.cyan,planned:h.cyan,plan:h.cyan,future:h.cyan,backlog:h.cyan,investigate:h.cyan,explore:h.cyan,prototype:h.cyan};var Io=(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):[]},tr=e=>Io(e,"Tags").map(t=>b.getTag(t)).filter(t=>!!t),Zt=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!le(n)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",tr(n)??[])},Qt=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!le(n)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",nr(n)??[])},nr=e=>Io(e,"Assignees").map(t=>b.getContributor(t)).filter(t=>!!t);var f={EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",RENAME:"rename",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",SET_DESCRIPTION:"edit",SET_EDITOR:"config:editor",SET_VIEW:"config:view",SET_USERNAME:"config:username",SYNC:"sync",EXPORT:"export",NONE:""};var Ba=/^(\d+)(h|d|w|mo|y)$/,Oa=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Ua=({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},$a=(e,t=new Date)=>{let n=e.match(Ba);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}},_a=e=>{let t=e.match(Oa);if(!t)return null;let[,n,r,o,i,a]=t,d=Number(n),u=Number(r),m=Number(o),p=i?Number(i):0,y=a?Number(a):0;return Ua({year:d,month:u,day:m,hour:p,minute:y})?new Date(d,u-1,m,p,y):null},en=e=>{let t=e.trim().toLowerCase();return $a(t)??_a(t)},So=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,ja=[{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}],Ao=(e=ja)=>{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 Wa=["BOARD","TICKET","SWIMLANE"],Ye=[f.SYNC,f.HELP,f.EXPORT,f.SET_VIEW,f.SET_EDITOR,f.SET_USERNAME],tn=[f.NEW,f.RENAME,f.DELETE,f.MOVE],rr=[f.TAG,f.UNTAG,f.ASSIGN,f.UNASSIGN,f.CLOSE_ISSUE,f.RE_OPEN_ISSUE,f.SET_DESCRIPTION],wo=[f.FILTER,f.PEEK],Ha={WORKSPACE:[...Ye,...tn],BOARD:[...wo,...Ye,...tn],SWIMLANE:[...wo,...Ye,...tn],TICKET:[...Ye,...tn,...rr],FIELD:[...Ye,...rr],FIELD_LIST:[...Ye,...rr],TEXT:[...Ye]},Ka=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Va=()=>{let{currentNode:e,selectedNode:t,readOnly:n}=v();if(!nn().isSetup)return[f.HELP,f.SET_EDITOR,f.SET_USERNAME];if(!To())return[f.HELP,f.INIT];if(n)return[f.HELP,f.PEEK,f.EXPORT,f.SET_VIEW];let o=e.context??"WORKSPACE",i=t?.context,a=i&&Wa.includes(i);return Ha[o].filter(d=>d===f.RENAME||d===f.DELETE||d===f.MOVE?a:!0)},z=e=>{let{currentNode:t}=v(),n=t.context??"WORKSPACE";return{[f.NONE]:Va(),[f.EXIT]:["confirm"],[f.EXPORT]:[],[f.SYNC]:[],[f.INIT]:[],[f.HELP]:[],[f.PEEK]:[...Ao(),"now","prev","next"],[f.SET_USERNAME]:[],[f.SET_DESCRIPTION]:["confirm"],[f.DELETE]:["confirm"],[f.RE_OPEN_ISSUE]:["confirm"],[f.CLOSE_ISSUE]:["confirm"],[f.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[f.FILTER]:["tag","assignee","description","title","clear"],[f.SET_VIEW]:["dense","wide"],[f.SET_EDITOR]:[...ao],[f.TAG]:[...new Set([...Object.keys(it),...b.getExistingTags()])],[f.UNTAG]:[...Zt()?.value?.map(({name:o})=>o)??[]],[f.UNASSIGN]:[...Qt()?.value?.map(({name:o})=>o)??[]],[f.ASSIGN]:b.getExistingAssignees(),[f.RENAME]:[],[f.NEW]:Ka(n)}[e]??[]};import at from"chalk";import{decodeTime as Ro}from"ulid";var Mo=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"},Po=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())}`},rn=e=>{try{return l("Decoded date",new Date(Ro(e)))}catch(t){return s("Decoding failed + "+t.message)}},or=e=>{if(!e?.id)return null;try{return Ro(e.id)}catch{return null}};var Te=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?l("Found node",n):s("Unable to find node in breadcrumb")};import st from"chalk";var sr={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},za=(e,t,n)=>Math.max(t,Math.min(n,e)),ir=(e,t,n)=>e+(t-e)*n,ko=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},qa=(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)),u=0,m=0,p=0;a>=0&&a<1?(u=i,m=d):a>=1&&a<2?(u=d,m=i):a>=2&&a<3?(m=i,p=d):a>=3&&a<4?(m=d,p=i):a>=4&&a<5?(u=d,p=i):(u=i,p=d);let y=o-i/2;return[Math.round((u+y)*255),Math.round((m+y)*255),Math.round((p+y)*255)]},Ga=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Ya=(e,t,n)=>[Math.round(ir(e[0],t[0],n)),Math.round(ir(e[1],t[1],n)),Math.round(ir(e[2],t[2],n))],Ct=e=>{let n=ko(e)%360,r=qa(n,sr.stringColor.saturation,sr.stringColor.lightness);return Ga(r)},Xa=e=>{let t=sr.gradient.stops,n=za(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 Ya(t[i],t[i+1],a)},on=e=>ko(e.toLowerCase().trim())/4294967295,Do=e=>{let t=on(e);return Xa(t)},Ja=e=>{let[t,n,r]=Do(e);return{normal:o=>st.bgRgb(t,n,r).black(o),cursor:o=>st.bgRgb(t,n,r).white.bold(o)}},ar=e=>{let[t,n,r]=Do(e);return{fg:o=>st.rgb(t,n,r)(o),fgCursor:o=>st.rgb(t,n,r).inverse(o),bg:o=>st.bgRgb(t,n,r).black(o),bgCursor:o=>st.bgRgb(t,n,r).white.bold(o)}},dr=e=>Ja(e).normal(` ${e} `),X=(e,t=it)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:Ct(r)};var Re={None:"none",Invalid:"invalid",Valid:"valid"};var Za=["BOARD","TICKET","SWIMLANE"],cr=()=>{let e=v().selectedNode;return e?.context?Za.includes(e?.context)?j():U({message:"Command not available in this context"}):U({message:"Missing target context"})},ee="<ENTER> to confirm",j=(e="",t=[])=>({message:e,validity:Re.Valid,completionWordList:t}),U=({message:e,completionWordList:t=[]})=>({validity:Re.Invalid,message:e,completionWordList:t}),It=e=>e.length===0,_e=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let u=[...t.filter(Boolean).filter(p=>p.startsWith(o.trim()))].sort((p,y)=>on(p)-on(y)).slice(0,r).map(dr),m=u.length>i?u.join(" "):"";return m?`${e}${m}${n}`:""},lr=({modifier:e})=>{let t="confirm";return e===t?j(ee):U({message:It(e)?`if you are certain, enter ${dr(t)}`:"",completionWordList:[t]})},Qa=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?j(ee):U({message:It(n)?t:""}),ed=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?U({message:n}):j():U({message:It(r)?t:""}),bt=({hint:e})=>({modifier:t,inputString:n})=>It(t)&&It(n)?U({message:e,completionWordList:[]}):j(ee),td={[f.EXPORT]:()=>j(ee+", and create export markdown file"),[f.PEEK]:e=>{let t=e.modifier;if(t==="now")return j(ee);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return j(ee);let r=en(t);if(!t||!r)return U(n);let o=Te(v().breadCrumb,"BOARD");if(c(o))return U({message:"Command is not applicable in this context"});let i=rn(o.value.id);return c(i)?U({message:"Unable to peek: board id is not a valid ULID"}):So({date:r,horizonDate:i.value})?j(ee):U({message:at.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[f.EXIT]:()=>j(ee+" and exit the application"),[f.INIT]:()=>j(ee),[f.FILTER]:e=>{if(e.modifier==="clear")return j();let t=a=>z(f.FILTER).includes(a);if(!e.modifier||!t(e.modifier??""))return U({message:_e({wordList:z(f.FILTER),inputString:e.inputString}),completionWordList:z(f.FILTER)});let r=Object.values(v().tags).map(a=>a.name),o=Object.values(v().contributors).map(a=>a.name),i=e.modifier==="tag"?r:e.modifier==="assignee"?o:[];return e.inputString?i.length&&!i.includes(e.inputString.trim()??"")?U({message:_e({prefix:`existing ${e.modifier}s... `,wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i}):j():U({message:_e({prefix:"one of... ",wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i})},[f.NONE]:e=>{let t=z(f.NONE),n=/^[A-Za-z_]+:/g,r=e.inputString.match(n);return r&&r.length?t=[...t.filter(o=>o.trim().match(n))]:t=[...new Set(t.flatMap(o=>o.match(n)?.join("").replace(":","")??o))],e.command?j():U({message:_e({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[f.NEW]:e=>ed({list:z(f.NEW),hint:_e({wordList:z(f.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[f.SET_DESCRIPTION]:()=>j(ee),[f.HELP]:()=>j(ee),[f.RENAME]:()=>{let e=cr();return e.validity==="invalid"?e:j(ee)},[f.DELETE]:e=>{let t=cr();return t.validity==="invalid"?t:lr(e)},[f.CLOSE_ISSUE]:e=>lr(e),[f.RE_OPEN_ISSUE]:e=>lr(e),[f.MOVE]:e=>{let t=cr();return t.validity==="invalid"?t:bt({hint:_e({prefix:"hey hacker! These commands are blocked for you... ",wordList:z(f.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[f.TAG]:e=>{let t=b.getExistingTags().map(n=>` ${at.bgHex(X(n))(" "+n+" ")} `).slice(0,10);return bt({hint:"tag name like... "+t.join("")})(e)},[f.UNTAG]:e=>{let t=Zt();if(c(t))return U({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${at.bgHex(X(r))(" "+r+" ")} `).slice(0,10);return n.length?bt({hint:" ... "+n.join("")})(e):U({message:"Issue has not tags",completionWordList:[]})},[f.ASSIGN]:e=>{let t=b.getExistingAssignees().map(n=>` ${at.bgHex(X(n))(" "+n+" ")} `).slice(0,10);return bt({hint:"assign to... "+t.join("")})(e)},[f.UNASSIGN]:e=>{let t=Qt();if(c(t))return U({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${at.bgHex(X(r))(" "+r+" ")} `).slice(0,10);return n.length?bt({hint:"remove assignee... "+n.join("")})(e):U({message:"Issue has no assignees",completionWordList:[]})},[f.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=z(f.SET_EDITOR);return e.modifier?j(ee):U({message:_e({wordList:t,inputString:e.inputString})})},[f.SET_USERNAME]:e=>e.inputString?j():U({message:`Enter a username. Saved in ${at.bgBlack("~/.epiq-global/")}`}),[f.SET_VIEW]:e=>Qa({list:z(f.SET_VIEW),hint:_e({wordList:z(f.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[f.SYNC]:()=>j(ee)},Lo=Object.fromEntries(Object.entries(td).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Fo=["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 M={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",SetView:"set-view",SetEditor:"set-editor",SetUserName:"set-user-name",SetAutoSync:"set-auto-sync",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Sync:"sync",Export:"export"};var Bo=e=>Object.values(f).includes(e),Oo=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:d,completionWordList:u}=Lo[n].validate(n,r,i),m=o==="command"?Object.values(f):n&&e.target==="modifier"?z(n):Fo;return{validity:d,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?so(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var Uo=e=>{let t=e.trimStart(),n=rd(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),a=od(e),d=Bo(r)?r:null,u=d!==null,m=r!=="",p=d?z(d)??[]:[],y=d&&p.includes(o)?o:"",N="word";n.length===0||n.length===1&&!i?N="command":(n.length===1&&i||n.length===2&&!i)&&(N="modifier");let S=i?"":a,A=nd(t,d,y);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:a,hasCommand:m,command:d,isCommandKeyword:u,isLastWordCompleted:i,modifier:y,target:N,inputToMatch:S,inputString:A}},nd=(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},rd=e=>e.trim()?e.trim().split(/\s+/):[],od=e=>e.trimEnd().split(/\s+/).at(-1)??"";var $o=" ",J={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Re.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},ur=new Set,_o=()=>{for(let e of ur)e()},jo=e=>(ur.add(e),()=>ur.delete(e)),Me=e=>{let n=e(J),r=Uo(n.value),o=n.cursorPosition===n.value.length;J={...n,commandMeta:Oo(r,o)},_o()},St=({message:e,status:t})=>{let n=structuredClone(J);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,J=n,_o(),l(e,null)},mr=e=>{Me(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},pr=e=>{Me(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}})},Wo=()=>{Me(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}})},Ho=()=>{Me(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}})},H=e=>{Me(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}})},Ko=()=>{Me(e=>({...e,commandIsPending:!0}))},Vo=({addToHistory:e=!0})=>{Me(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),id()},zo=()=>{Me(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}})},qo=()=>{Me(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},id=()=>H(()=>""),ne=()=>J,sn=()=>{let[e,...t]=J.value.split($o);return t.join($o).trim()};var sd=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",ad=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",dd=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Go=(e,t)=>{if(ad(e,e.sequence))return x.MoveCursorLeftOfWord;if(dd(e,e.sequence))return x.MoveCursorRightOfWord;if(sd(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 cd(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 ld(e,t,n){let r=v().currentNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function Yo(e,t){let n=ne();if(e.sequence===":"&&n.value==="")return x.InitCommandLine;if(t===g.MOVE)switch(e.name){case"m":case"return":return x.ConfirmMove}if(t===g.COMMAND_LINE)return Go(e,n.value);let r=cd(e);if(r){let o=t===g.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 ld(v().currentNode.childRenderAxis,r,o)}if(e.ctrl&&e.name==="c")return x.Exit;switch(e.name){case"e":return x.Edit;case"n":return x.AddItem;case"m":return x.InitMove;case"d":return x.Delete;case"return":return x.Confirm;case"space":return x.Confirm;case"v":return v().viewMode==="wide"?x.SetViewDense:x.SetViewWide;case"q":case"escape":return x.Exit;case"s":return x.Sync;default:return null}}var Xo=e=>{let{context:t}=v()?.currentNode;if(!t)return M.None;switch(e){case f.EXIT:return M.Exit;case f.EXPORT:return M.Export;case f.INIT:return M.Init;case f.DELETE:return M.Delete;case f.SET_DESCRIPTION:return M.Edit;case f.HELP:return M.ViewHelp;case f.RE_OPEN_ISSUE:return M.ReopenIssue;case f.CLOSE_ISSUE:return M.CloseIssue;case f.TAG:return M.TagTicket;case f.UNTAG:return M.UntagTicket;case f.ASSIGN:return M.AssignUserToTicket;case f.UNASSIGN:return M.UnassignUserFromTicket;case f.RENAME:return M.Rename;case f.NEW:return M.NewItem;case f.FILTER:return M.Filter;case f.MOVE:return M.Move;case f.PEEK:return M.Peek;case f.SET_USERNAME:return M.SetUserName;case f.SET_EDITOR:return M.SetEditor;case f.SET_VIEW:return M.SetView;case f.SYNC:return M.Sync;default:return M.None}};import{ulid as _}from"ulid";import li from"node:fs";import Ud from"node:path";import $d from"react";import{Box as Bd}from"ink";import mn from"react";import{Box as vr,Text as Cd}from"ink";import xe from"react";import{Text as Jo}from"ink";import Zo,{useEffect as Qo,useState as ud}from"react";var ei={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},re=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=$(),r=ei[n]??ei.default,[o,i]=ud(0);if(Qo(()=>{i(0)},[r]),Qo(()=>{if(!e)return;let d=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(d)},[e,r]),!e)return Zo.createElement(Jo,null,t);let a=r[o]??r[0]??t;return Zo.createElement(Jo,{color:E.accent,dimColor:o===1},a)};import{Box as gr,Text as md}from"ink";import an from"react";var dn=({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)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-d),p=o?Math.min(m,Math.max(0,u-d+1)):Math.min(m,Math.floor(u/d)*d),y=p+d,N=e.slice(p,y),S=e.length>d,A=i,I=S?Math.max(1,Math.floor(d/e.length*A)):A,C=Math.max(0,A-I),T=Math.max(1,e.length-d),O=S?Math.floor(p/T*C):0;return an.createElement(gr,{flexDirection:"row",height:i,width:"100%"},an.createElement(gr,{flexDirection:"column",flexGrow:1,height:i},N),an.createElement(gr,{flexDirection:"column",width:1,height:A},Array.from({length:A}).map((ie,Ue)=>an.createElement(md,{key:Ue,color:S&&Ue>=O&&Ue<O+I?E.accent:E.secondary},S?"\u2502":" "))))};import{Box as cn,Text as hd}from"ink";import Xe from"react";import{Text as pd}from"ink";import gd from"react";var fd=e=>e.toLowerCase().trim(),vd=(e,t=it)=>{let n=fd(e);return t[n]?t[n]:Ct(n)},dt=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return gd.createElement(pd,{underline:t,color:vd(n.name)},"@"+n.name)};import{Text as xd}from"ink";import yd from"react";var ct=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return yd.createElement(xd,{underline:t,backgroundColor:X(n.name),color:E.primary}," "+n.name+" ")};var ti=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=Wt(Kn(t.title),r),i=tr(t),a=nr(t);return Xe.createElement(cn,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?E.accent:E.secondary,justifyContent:"space-between"},Xe.createElement(cn,{borderBottom:!0},Xe.createElement(cn,{paddingLeft:1,flexDirection:"column"},Xe.createElement(hd,{color:E.primary},o))),Xe.createElement(cn,{flexDirection:"row",paddingLeft:1},i.map(d=>Xe.createElement(ct,{key:d.id,id:d.id})),a.map(d=>Xe.createElement(dt,{key:d.id,id:d.id}))))};import Ed from"chalk";import{Box as At,Text as fr}from"ink";import Pe from"react";var Nd=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,ni=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=R(t.id),a=I=>{let C=i.find(T=>T.title===I);return C?R(C.id).map(T=>typeof T.props?.value=="string"?T.props.value:"").filter(T=>!!T):[]},d=a("Tags").map(I=>b.getTag(I)).filter(I=>!!I),u=a("Assignees").map(I=>b.getContributor(I)).filter(I=>!!I),m=1,p=d.length*(1+m),y=u.length*(2+m),N=d.map(I=>Pe.createElement(At,{key:I.id,paddingRight:m},Pe.createElement(fr,{color:X(I.name)},"\u25A0"))),S=u.map(I=>Pe.createElement(At,{key:I.id,paddingRight:m},Pe.createElement(fr,{color:Ct(I.name)},"@"+I.name.at(0)))),A=n?E.accent:o===g.MOVE?E.secondary:E.primary;return Pe.createElement(At,{borderBottom:!0,justifyContent:"space-between"},Pe.createElement(At,null,Pe.createElement(re,{isSelected:n,placeholder:Ed.dim.gray(r+1+" ")}),Pe.createElement(fr,{wrap:"truncate",color:A},Nd(t.title,e-p-y-14))),Pe.createElement(At,null,N,S))};var bd=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:a,mode:d})=>{let{renderedChildrenIndex:u}=$(),m=u[e.id]??[],p=`${e.title} (${m.length})`,y=3,N=o?1:4,S=r-y-(o?2:1),A=xe.createElement(vr,{borderStyle:"round",borderColor:E.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},xe.createElement(re,{isSelected:t}),xe.createElement(Cd,{bold:!0,color:t?E.accent:E.primary},p," ",e.readonly?"\u{1F512}":"")),I=(C,T)=>{let O=i&&a===T;return o?xe.createElement(ni,{key:C.id,index:T,width:n,ticket:C,isSelected:O,mode:d}):xe.createElement(ti,{key:C.id,width:n,ticket:C,isSelected:O})};return xe.createElement(vr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?E.accent:E.secondary,paddingRight:1,paddingLeft:1,height:r},A,xe.createElement(vr,{padding:o?1:0},m.length>0&&xe.createElement(dn,{selectedIndex:a,height:S,itemHeight:N},m.map(I)),xe.createElement(re,{isSelected:i&&a===-1})))},ri=xe.memo(bd);import{Box as hr,Text as Ld}from"ink";import je,{useEffect as Er,useMemo as ai}from"react";import Je from"chalk";import oi from"string-width";import{decodeTime as Id}from"ulid";var Sd=(e,t)=>e+" ".repeat(Math.max(0,t-oi(e))),Ad=(e,t)=>" ".repeat(Math.max(0,t-oi(e)))+e,wd=e=>(()=>{let n={"add.issue":"Created with title","assign.issue":"Assigned to","unassign.issue":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","tag.issue":"Tagged with","untag.issue":"Removed tag","lock.node":"Locked node","move.node":"Moved issue"};return(o=>n[o]??(o.endsWith("e")?`${o}d`:`${o}ed`))(e)})(),Td=e=>{switch(e.action){case"move.node":{let t=b.getNode(e.payload.parent);return`to ${t?Je.dim.bgBlack(` ${t.title} `):"unknown"} with rank ${e.payload.rank}`}case"tag.issue":{let t=v().tags[e.payload.tagId];return t?Je.bgHex(X(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=v().tags[e.payload.tagId];return t?Je.bgHex(X(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=v().contributors[e.payload.contributor];return t?Je.hex(X(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=v().contributors[e.payload.contributor];return t?Je.hex(X(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""}},Rd=e=>{let t=Mo(Id(e));return Je.gray(Ad(t,8))},Md=12,Pd=e=>Sd(`${e}`,Md),ii=e=>{let t=Rd(e.id),n=Pd(e.userName),r=wd(e.action),o=Td(e),i=Je.dim("\u203A"),a=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${a}`};import{Box as ln,Text as kd}from"ink";import ke from"react";var si=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=$(),{title:o}=t,i=R(t.id).map(a=>{let d=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return b.getContributor(d)?.id;if(o==="Tags")return b.getTag(d)?.id}).filter(a=>!!a);return ke.createElement(ln,{alignItems:"center",paddingTop:1},ke.createElement(ln,{minWidth:12},ke.createElement(re,{isSelected:n}),ke.createElement(kd,{color:n?E.accent:E.secondary2},o,":")),ke.createElement(ln,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,d)=>{let u=r.id===t.id&&d===e;return ke.createElement(ln,{key:`${o}-${a}`,paddingRight:2,minHeight:1},ke.createElement(re,{isSelected:u}),o==="Assignees"?ke.createElement(dt,{isSelected:u,id:a}):o==="Tags"?ke.createElement(ct,{isSelected:u,id:a}):null)})))};import{Box as un,Text as xr}from"ink";import De,{useEffect as Dd}from"react";var yr=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:d}=$(),u=N=>String(N).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];Dd(()=>{let N=[];return m.forEach((S,A)=>{let I=Ce(BigInt(A+1));if(!Ne(I))return;let C=te.text({id:`${e}-${A}`,name:`Line ${A+1}`,parentNodeId:e,rank:I.value,props:{value:S},readonly:!0}),T=b.createNode(C);Ne(T)&&N.push(T.value.id)}),()=>N.forEach(b.deleteNode)},[e,n]);let p="\u2029",y=m.map((N,S)=>{let A=d.id===e&&a===S;return De.createElement(un,{key:`${e}-${S}`},De.createElement(xr,{color:A?E.primary:E.secondary2,dimColor:!A},`${S+1} `.padStart(5,"\xA0")),De.createElement(xr,{backgroundColor:A?"gray":""},u(N.length?Wt(N,i-10):p)))});return De.createElement(un,{flexDirection:"column",paddingTop:1},De.createElement(un,null,De.createElement(re,{isSelected:o}),De.createElement(xr,{color:o?E.accent:E.secondary2},t)),De.createElement(un,{flexDirection:"row",borderStyle:"round",borderColor:E.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},De.createElement(dn,{scrollByOne:!0,children:y,height:r-2,selectedIndex:a,itemHeight:1})))};var Fd=e=>`${e}::log`,di=e=>e==="Assignees"||e==="Tags",ci=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=$(),o=process.stdout.columns||120,i=ai(()=>Fd(e.id),[e.id]),a=ai(()=>[...e.log].reverse().map(ii).join(`
5
- `),[e.log]);Er(()=>{if(b.getNode(i))return;let T=Ce(1n);if(c(T))return;let O={...te.field(i,"Log",e.id,T.value,{value:a}),readonly:!0,childRenderAxis:"vertical"};return b.createNode(O),()=>{b.deleteNode(i)}},[i,e.id,a]),Er(()=>{let C=b.getNode(i);C&&C.props.value!==a&&b.updateNode({...C,props:{...C.props,value:a},childRenderAxis:"vertical",readonly:!0})},[i,a]);let d=r.id===e.id,u=r.id===i||r.parentNodeId===i;Er(()=>{u&&(n>=0||D.navigate({selectedIndex:0}))},[u,n]);let m=R(e.id);if(u){let C=b.getNode(i),O=t-3;return je.createElement(hr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},C?je.createElement(yr,{id:C.id,label:"Event log",text:C.props.value??"",selected:!1,maxWidth:o,height:O}):null)}let p=m.reduce((C,T)=>di(T.title)||T.id===i?C+1:C,0),y=2,N=p*1,A=t-3-N-y,I=(C,T)=>di(C.title)?je.createElement(si,{key:C.id,parent:C,selected:T,selectedIndex:n}):C.id===i?je.createElement(hr,{key:C.id,paddingTop:1},je.createElement(re,{isSelected:T}),je.createElement(Ld,{backgroundColor:E.secondary,color:T?E.accent:E.primary}," History \u203A\u203A ")):C.title==="Description"?je.createElement(yr,{label:"Description (press e to edit)",key:C.id,id:C.id,text:C.props.value??"",selected:T,maxWidth:o,height:A}):null;return je.createElement(hr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((C,T)=>I(C,d&&n===T)))};var Od=({swimlanes:e,currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:a,width:d})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,p=u===P.BOARD||u===P.SWIMLANE,y=u===P.TICKET?t:r.find(C=>C.context===P.TICKET),N=Math.floor(d/3),S=Math.floor(d/Math.max(e.length,1)),A=Math.min(S,N),I=i==="dense";return mn.createElement(Bd,{flexDirection:"row",height:a},p&&e.map((C,T)=>{let O=t.id===C.id,ie=O?n:-1,Ue=t.context===P.BOARD&&n===T;return mn.createElement(ri,{key:C.id,height:a,width:A,swimlane:C,isSelected:Ue,isDense:I,isFocused:O,listSelectedIndex:ie,mode:o})}),m&&y&&mn.createElement(ci,{height:a,ticket:y}))},pn=mn.memo(Od);import{render as _d}from"ink";import{Writable as jd}from"node:stream";var wt=e=>String(e).padStart(2,"0"),Wd=e=>{let t=e.getUTCFullYear(),n=wt(e.getUTCMonth()+1),r=wt(e.getUTCDate()),o=wt(e.getUTCHours()),i=wt(e.getUTCMinutes()),a=wt(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${a}`},Hd=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Kd=async(e,{width:t,height:n})=>{let r="",o=new jd({write(a,d,u){let m=Vd(a.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=_d(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(a=>setTimeout(a,0)),i.unmount(),r},Vd=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),ui=async()=>{let{currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:r,mode:o,renderedChildrenIndex:i}=v(),a=n.find(T=>T.context==="BOARD");if(!a)return s("No board found to export");let d=120,u=40,m=await Kd($d.createElement(pn,{height:u,width:d,swimlanes:(i[a.id]??[]).filter(T=>T!==void 0&&tt(T)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:r,mode:o}),{width:d,height:u});if(!m)return s("Failed to render board export");let p=we(process.cwd());if(c(p))return s("Unable to export, epiq root not found");let y=new Date,N=Wd(y),S=`board_${Hd(a.title)}_${N}.md`,A=mo(p.value);li.mkdirSync(A,{recursive:!0});let I=Ud.join(A,S),C=`# Board - ${a.title}
2
+ import Xr from"chalk";import{render as Ec}from"ink";import Nc from"meow";import Cc from"react";import{Box as Ze}from"ink";import G from"react";import ut from"chalk";import{monotonicFactory as _l,ulid as ke}from"ulid";import{useSyncExternalStore as Bl}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function Hn(e){return e.context==="WORKSPACE"}function le(e){return e.context==="TICKET"}function Qr(e){return e.context==="FIELD"}var Qe=e=>e.context==="SWIMLANE",eo=e=>e.context==="BOARD";var he={None:"none",Success:"success",Fail:"fail"},s=e=>({status:he.Fail,message:e,value:null}),c=(e,t)=>({status:he.Success,message:e,value:t}),d=e=>e.status==="fail",Ee=e=>e.status==="success";var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function $t(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var _t=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",jn=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var to=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},no=(e,t)=>t?e.get(t)??[]:[];var ro=new WeakMap,oa=e=>{let t=ro.get(e);return t||(t=to(e),ro.set(e,t)),t};var oo=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return no(oa(e),r).filter(i=>$t(r,i)>=n)};var ia={hint:"",hints:[],overlap:0,remainder:""},io=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return ia;let o=oo({wordList:r,inputToMatch:e,overlapThreshold:1});return sa(t,o)},sa=(e,t)=>{let n=t[0]??"",r=$t(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),a=r<(o??"").length,l=!!i,p=(l&&a?o:n)+(l&&a?":":" "),y=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:y}};var so=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var te={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:(e,t,n,r,o={},i="horizontal")=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[]}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[]})};import{ulid as la}from"ulid";var ze=24n,aa=ze*4n,gt=(1n<<aa)-1n,da=/^[0-9a-f]+$/;function ao(e){return!e||!da.test(e)?s(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Ne(e,t=ze){if(e<0n)return s("Negative rank not allowed");let n=e.toString(16);return c("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function V(e,t){if(!e&&!t)return Ne(gt/2n,ze);let n=e?ao(e):c("Resolved lower bound",0n);if(d(n))return n;let r=t?ao(t):c("Resolved upper bound",gt);if(d(r))return r;let o=n.value,i=r.value;if(i<=o)return Ne(gt/2n,ze);let a=(o+i)/2n;return a===o||a===i?s("No rank space available between neighbors"):Ne(a,ze)}function lo(){return Ne(gt/2n,ze)}function co(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=gt*BigInt(r+1)/(t+1n),i=Ne(o,ze);if(d(i))return i;n.push(i.value)}return c("Resolved evenly spaced ranks",n)}var Kn=(e,t)=>{let n=F(e),r=co(n.length);if(d(r))return r;let o={};for(let i=0;i<n.length;i++){let a=n[i],l=r.value[i];if(!a||!l)return s("Unable to assign rebalance rank");o[a.id]=l}return c("Created rebalance event",{id:la(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var ca=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[Ce,Wt]=ca;var k=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),ua={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=te.workspace(t,n,r),i=Vn(o);if(d(i))return k(i.message,e);let a=b.createNode(o);return d(a)?k(a.message??"Failed to initialize workspace",e):Hn(a.value)?c("Workspace initialized",{action:e.action,result:a.value}):s("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=te.workspace(t,n,r),i=b.createNode(o);return d(i)?k(i.message??"Failed to add workspace",e):Hn(i.value)?c("Added workspace",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=b.createNode(te.board(t,n,r,o));return d(i)?k(i.message??"Unable to create board",e):eo(i.value)?c("Added board",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=b.createNode(te.swimlane(t,n,r,o));return d(i)?k(i.message??"Unable to create swimlane",e):Qe(i.value)?c("Added swimlane",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=b.createNode(te.ticket(t,n,r,o));return d(i)?k(i.message??"Unable to create issue",e):le(i.value)?c("Added issue",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:i}=e.payload,a=b.createNode(te.field(t,n,r,i,{value:o},n.includes("Description")?"vertical":"horizontal"));return d(a)?k(a.message??`Unable to create field: ${n}`,e):Qr(a.value)?c("Added field",{action:e.action,result:a.value}):s("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!b.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=b.renameNode(t,n);return d(o)?k(o.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=b.tombstoneNode(t);return d(n)?k(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=b.createTag({id:t,name:n});return d(r)?k(r.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=b.createContributor({id:t,name:n});return d(r)?k(r.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:r.value})},"tag.issue":e=>{let{id:t,target:n,tagId:r,rank:o}=e.payload,i=b.tag(n,r,t,o);return d(i)?k(i.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:i.value})},"untag.issue":e=>{let{target:t,tagId:n}=e.payload,r=b.untag(t,n);return d(r)?k(r.message??"Unable to untag ",e):c("Issue untagged",{action:e.action,result:r.value})},"assign.issue":e=>{let{id:t,contributor:n,target:r,rank:o}=e.payload,i=b.assign(r,n,t,o);return d(i)?k(i.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:i.value})},"unassign.issue":e=>{let{target:t,contributor:n}=e.payload,r=b.unassign(t,n);return d(r)?k(r.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:r.value})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?k(o.message??"Failed to move node",e):c("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=b.editValue(t,n);return d(r)?k(r.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return k("Unable to locate issue",e);if(!le(o))return k("Can only close issues",e);let i=b.getNode(Ce);if(!i)return k("Unable to locate target swimlane",e);if(n!==i.id)return k("Close target must be closed swimlane",e);let a=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(a)?k(a.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return k("Unable to locate issue",e);if(!le(o))return k("Can only reopen issues",e);let i=b.getNode(Ce);if(!i)return k("Unable to locate closed swimlane",e);if(n===i.id)return k("Cannot reopen issue into closed swimlane",e);if(!b.getNode(n))return k("Reopen parent no longer exists",e);let l=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(l)?k(l.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=b.lockNode(t);return d(n)?k(n.message??"Unable to lock node",e):c("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let i=b.getNode(r);if(!i)return k(`Unable to locate node ${r}`,e);if(i.parentNodeId!==t)return k(`Node ${r} is not child of ${t}`,e);let a=b.updateNode({...i,rank:o});if(d(a))return k(a.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})}},ma=(e,t)=>{let n=b.getNode(e);n&&b.updateNode({...n,log:[...n.log??[],t]})},pa=e=>{switch(e.action){case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"delete.node":case"move.node":case"close.issue":case"reopen.issue":return[e.payload.id];case"edit.description":let t=[e.payload.id],n=v().nodes[e.payload.id]?.parentNodeId;return n&&t.push(n),t;case"tag.issue":case"untag.issue":case"assign.issue":case"unassign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function ft(e,t=!1){let n=ua[e.action](e);if(d(n))return n;t||([...new Set(pa(e))].forEach(a=>ma(a,e)),ae(a=>({...a,eventLog:[...a.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?k("Invalid user ID format",e):(b.createContributor({name:o,id:r}),n)}var qe=e=>e.map(t=>ft(t));import Sa from"node:fs";import Aa from"node:path";import{decodeTime as wa,monotonicFactory as Ta}from"ulid";import{z as ht}from"zod";var Ht={autoSync:!1,preferredEditor:null,userName:null,userId:null},ge=()=>Ht,et=e=>(Ht={...Ht,...e},Ht);import vt from"node:fs";import be from"node:path";var zn=process.env.IS_LOCAL==="true",Ie=".epiq",ce=".epiq-global",jt="events",ga="project.json",uo=e=>be.join(e,Ie),Kt=e=>be.join(e,Ie),Vt=e=>be.join(Kt(e),ga),xt=e=>be.join(Kt(e),jt),fa=e=>{let t=be.join(e,Ie);return vt.existsSync(t)&&vt.statSync(t).isDirectory()},va=e=>{let t=Vt(e);return vt.existsSync(t)&&vt.statSync(t).isFile()},Se=e=>{let t=be.resolve(e);for(;;){if(fa(t))return c("Resolved closest .epiq root",t);let n=be.dirname(t);if(n===t)return s("No .epiq directory found in any parent");t=n}},zt=e=>{let t=be.resolve(e);for(;;){if(va(t))return c("Resolved closest epiq project root",t);let n=be.dirname(t);if(n===t)return s("No .epiq/project.json found in any parent");t=n}},mo=e=>{let t=xt(e);try{return vt.mkdirSync(t,{recursive:!0}),c("Resolved events dir",t)}catch(n){return s(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}};import qt from"node:fs";import Gn from"node:path";import{decodeTime as xa}from"ulid";import{z as qn}from"zod";var ya=qn.object({userId:qn.string().min(1).default("unknown"),userName:qn.string().min(1).default("unknown")}),ha=e=>{let[t,n]=Gn.basename(e,".jsonl").split("."),r=ya.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):s(`Invalid event file name ${Gn.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Ea=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"):c("Resolved persisted action",t[0])},Na=(e,t)=>t in e,Ca=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),ba=e=>{let{userId:t,userName:n,...r}=e,o=Ea(r);if(d(o))return s(o.message);let i=o.value,a=e.id?.[0];return a?Na(r,i)?c("Decoded persisted event",Ca({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")},Gt=e=>{if(!qt.existsSync(e))return c("Event file missing",[]);let t=ha(e);if(d(t))return s(t.message);let n=qt.readFileSync(e,"utf8"),r=[];for(let o of n.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=Yn(a);if(d(l))return s(`${l.message} in ${e}: ${i}`);r.push({...l.value,userId:t.value.userId,userName:t.value.userName})}return c("Parsed persisted events file",r)};function po(e){let t=xt(e);if(!qt.existsSync(t))return c("No events found",[]);let n=qt.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Gn.join(t,o)),r=[];for(let o of n){let i=Gt(o);if(d(i))return s(i.message);r.push(...i.value)}return c("All events loaded",Ia(r))}function yt(e){let t=po(e);if(d(t))return s(t.message);let n=[];for(let r of t.value){let o=ba(r);if(d(o))return s(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);n.push(o.value)}return c("Loaded merged events",n)}function go(e=process.cwd()){let t=po(e);return d(t)?s(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Ia=e=>{let t=new Map;for(let l of e){let u=l.id[1]??null,m=t.get(u)??[];m.push(l),t.set(u,m)}for(let l of t.values())l.sort((u,m)=>u.id[0].localeCompare(m.id[0]));let n=[],r=new Set;a(t.get(null)??[]);let o=!0;for(;o;){o=!1;for(let l=0;l<n.length;l++){let u=n[l];if(!u)continue;let m=(t.get(u.id[0])??[]).filter(p=>!r.has(p.id[0]));if(m.length!==0){n.splice(l+1,0,...m);for(let p of m)r.add(p.id[0]);o=!0,l+=m.length}}}let i=e.filter(l=>!r.has(l.id[0])).sort((l,u)=>l.id[0].localeCompare(u.id[0]));return n.push(...i),n;function a(l){for(let u of l)r.has(u.id[0])||(n.push(u),r.add(u.id[0]))}},fo=(e,t)=>{let n=e.findIndex(r=>{try{return xa(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var vo=e=>({action:e.action,payload:e.payload});var yo=1,xo=Ta(),Ra=ht.tuple([ht.string().min(1),ht.string().min(1).nullable()]),Ma=ht.looseObject({v:ht.literal(yo),id:Ra}),Yn=e=>{let t=Ma.safeParse(e);return t.success?c("Parsed persisted event",t.data):s(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Yt=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",Q=()=>{let{userName:e,userId:t}=ge();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:Yt(t),userName:Yt(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},Xn=({userId:e,userName:t})=>`${Yt(e)}.${Yt(t)}.jsonl`,Pa=(e,{userId:t,userName:n})=>{let r=Xn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return s(`Invalid event log file name: ${r}`);let i=Aa.join(xt(e),r);return c("Successfully resolved event log path",i)},ka=(e,t)=>{let n={[e.action]:e.payload,v:yo,id:t};return Yn(n)};function Xt({event:e,rootDir:t=process.cwd()}){try{let n=Se(t);if(d(n))return n;let r=mo(n.value);if(d(r))return r;let o=Pa(n.value,{userId:e.userId,userName:e.userName});if(d(o))return o;let i=go(n.value);if(d(i))return s(i.message);let a=i.value?xo(Math.max(Date.now(),wa(i.value)+1)):xo(),l=ka(vo(e),[a,i.value]);return d(l)?s(l.message):(Sa.appendFileSync(o.value,`${JSON.stringify(l.value)}
4
+ `,"utf8"),c("Event persisted",{path:o.value,entry:l.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return s(`Failed to persist event: ${r}`)}}function K(e){let t=ft(e);if(t.status!==he.Success)return t;let n=Xt({event:e});return d(n)?n:t}function ho(e){return e.map(t=>K(t))}var Eo=e=>Jn(F(e),{at:"end"}),Jn=(e,t={at:"end"})=>{let n=r=>d(r)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(V(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(V(void 0,r.rank)):s("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(V(r.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let r=No(e,t.sibling);if(r<0)return s("Sibling not found");let o=r>0?e[r-1]:void 0,i=e[r];return i?n(V(o?.rank,i.rank)):s("Sibling not found")}case"after":{let r=No(e,t.sibling);if(r<0)return s("Sibling not found");let o=e[r],i=r<e.length-1?e[r+1]:void 0;return o?n(V(o.rank,i?.rank)):s("Sibling not found")}}},F=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),No=(e,t)=>e.findIndex(n=>n.id===t),Co=(e,t,n={at:"end"})=>Jn(F(t).filter(r=>r.id!==e),n),tt=(e,t,n,r)=>{let o=Co(t,e,n);if(d(o))return o;if(!o.value.needsRebalance)return c("Resolved rank",o.value.rank);let i=Kn(e,r);if(d(i))return i;let a=K(i.value);if(d(a))return a;let l=Co(t,e,n);return d(l)?l:l.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",l.value.rank)},nt=(e,t)=>{let n=Eo(e);if(d(n))return n;if(!n.value.needsRebalance)return c("Resolved rank",n.value.rank);let r=Kn(e,t);if(d(r))return r;let o=K(r.value);if(d(o))return o;let i=Eo(e);return d(i)?i:i.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",i.value.rank)};var Ue=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return s("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 s(`No ancestor found for context: ${t}`)},Qn=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Zn=(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"),b={deleteNode(e){ae(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return s("Edit target node not found");let o=Zn(r,"edit");if(o)return o;let i={...r,props:{...r.props,value:t}};return this.updateNode(i),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return s("Rename target node not found");let r=Zn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return F(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let a=Zn(o,"move");if(a)return a;if(Qn(t,e))return s("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,a=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let p of F(m.id))a(p.id)}};a(e);let l={...structuredClone(t)};for(let u of i){if(!l[u])return s("Unable to locate node to delete");l[u]={...l[u],isDeleted:!0}}return n?(w({nodes:l}),c("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=ae(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?s("Unable to create contributor"):c("Created contributor",e)},assign(e,t,n,r){let o=this.getContributor(t),i=this.getNode(e);if(!i||!o)return s("Unable assign contributor to issue");let a=this.getFieldByTitle(i.id,"Assignees");if(!a)return s("Unable to locate assignees field");if(F(a.id).some(p=>p.props?.value===t))return s("Contributor already assigned");let u=te.field(n,o.name,a.id,r,{value:t}),m=this.createNode(u);return d(m)?m:c("Assigned contributor",u)},createTag(e){let t=ae(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?s("Could not create tag"):c("Tag created",e)},tag(e,t,n,r){let o=this.getTag(t),i=this.getNode(e);if(!o)return s("Unable to add tag, missing tag");if(!i)return s("Unable to add tag, missing target");let a=this.getFieldByTitle(i.id,"Tags");if(!a)return s("Unable to locate tags field");if(F(a.id).some(p=>p.props?.value===t))return s("Tag already assigned");let u=te.field(n,o.name,a.id,r,{value:t}),m=this.createNode(u);return d(m)?m:c("Tag added",u)},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return s("Unable to remove tag, missing tag");if(!r)return s("Unable to remove tag, missing target");let o=this.getFieldByTitle(r.id,"Tags");if(!o)return s("Unable to locate tags field");let i=F(o.id).find(l=>l.props?.value===t);if(!i)return c("Issue is not tagged with that tag",null);let a={...i,isDeleted:!0};return this.updateNode(a),c("Tag removed",a)},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return s("Unable to unassign, missing contributor");if(!r)return s("Unable to unassign, missing target");let o=this.getFieldByTitle(r.id,"Assignees");if(!o)return s("Unable to locate assignees field");let i=F(o.id).find(l=>l.props?.value===t);if(!i)return c("Issue is not assigned to that contributor",null);let a={...i,isDeleted:!0};return this.updateNode(a),c("Assignee removed",a)},createNode(e){let t=ae(n=>({...n,nodes:{...n.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 n={...t,readonly:!0},r=ae(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?s(r.message):c("Locked node",n)},updateNode(e){let t=ae(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:c("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return F(e)}};var Y={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:Y.cyan,accent2:Y.magenta,primary:Y.white,secondary:Y.grayDark,secondary2:Y.grayLight,gray:Y.gray,green:Y.green,yellow:Y.yellow,red:Y.red};var h={red:Y.red,yellow:Y.yellow,green:Y.green,blue:Y.blue,magenta:Y.magenta,cyan:Y.cyan},rt={urgent:h.red,critical:h.red,important:h.red,blocker:h.red,asap:h.red,immediate:h.red,fail:h.red,failure:h.red,broken:h.red,bug:h.red,error:h.red,incident:h.red,outage:h.red,production:h.red,crash:h.red,security:h.red,warning:h.yellow,warn:h.yellow,risky:h.yellow,risk:h.yellow,attention:h.yellow,pending:h.yellow,review:h.yellow,"needs-review":h.yellow,qa:h.yellow,testing:h.yellow,test:h.yellow,validate:h.yellow,verification:h.yellow,staging:h.yellow,check:h.yellow,"follow-up":h.yellow,followup:h.yellow,waiting:h.yellow,blocked:h.yellow,hold:h.yellow,done:h.green,complete:h.green,completed:h.green,success:h.green,ok:h.green,stable:h.green,resolved:h.green,fixed:h.green,closed:h.green,merged:h.green,released:h.green,deployed:h.green,approved:h.green,verified:h.green,working:h.green,healthy:h.green,pass:h.green,passing:h.green,info:h.blue,information:h.blue,note:h.blue,docs:h.blue,documentation:h.blue,doc:h.blue,guide:h.blue,help:h.blue,explanation:h.blue,detail:h.blue,details:h.blue,context:h.blue,design:h.blue,discussion:h.blue,proposal:h.blue,idea:h.blue,feature:h.magenta,enhancement:h.magenta,improvement:h.magenta,refactor:h.magenta,refactoring:h.magenta,cleanup:h.magenta,optimize:h.magenta,optimization:h.magenta,perf:h.magenta,performance:h.magenta,upgrade:h.magenta,migration:h.magenta,modernize:h.magenta,debt:h.magenta,todo:h.cyan,next:h.cyan,planned:h.cyan,plan:h.cyan,future:h.cyan,backlog:h.cyan,investigate:h.cyan,explore:h.cyan,prototype:h.cyan};var bo=(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):[]},er=e=>bo(e,"Tags").map(t=>b.getTag(t)).filter(t=>!!t),Jt=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!le(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",er(n)??[])},Zt=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!le(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",tr(n)??[])},tr=e=>bo(e,"Assignees").map(t=>b.getContributor(t)).filter(t=>!!t);var f={EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",RENAME:"rename",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",SET_DESCRIPTION:"edit",SET_EDITOR:"config:editor",SET_VIEW:"config:view",SET_USERNAME:"config:username",SYNC:"sync",EXPORT:"export",NONE:""};var Da=/^(\d+)(h|d|w|mo|y)$/,La=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Fa=({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},Oa=(e,t=new Date)=>{let n=e.match(Da);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}},Ba=e=>{let t=e.match(La);if(!t)return null;let[,n,r,o,i,a]=t,l=Number(n),u=Number(r),m=Number(o),p=i?Number(i):0,y=a?Number(a):0;return Fa({year:l,month:u,day:m,hour:p,minute:y})?new Date(l,u-1,m,p,y):null},Qt=e=>{let t=e.trim().toLowerCase();return Oa(t)??Ba(t)},Io=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Ua=[{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}],So=(e=Ua)=>{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 $a=["BOARD","TICKET","SWIMLANE"],Ge=[f.SYNC,f.HELP,f.EXPORT,f.SET_VIEW,f.SET_EDITOR,f.SET_USERNAME],en=[f.NEW,f.RENAME,f.DELETE,f.MOVE],nr=[f.TAG,f.UNTAG,f.ASSIGN,f.UNASSIGN,f.CLOSE_ISSUE,f.RE_OPEN_ISSUE,f.SET_DESCRIPTION],Ao=[f.FILTER,f.PEEK],_a={WORKSPACE:[...Ge,...en],BOARD:[...Ao,...Ge,...en],SWIMLANE:[...Ao,...Ge,...en],TICKET:[...Ge,...en,...nr],FIELD:[...Ge,...nr],FIELD_LIST:[...Ge,...nr],TEXT:[...Ge]},Wa=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Ha=()=>{let{currentNode:e,selectedNode:t,readOnly:n}=v();if(!tn().isSetup)return[f.HELP,f.SET_EDITOR,f.SET_USERNAME];if(!wo())return[f.HELP,f.INIT];if(n)return[f.HELP,f.PEEK,f.EXPORT,f.SET_VIEW];let o=e.context??"WORKSPACE",i=t?.context,a=i&&$a.includes(i);return _a[o].filter(l=>l===f.RENAME||l===f.DELETE||l===f.MOVE?a:!0)},z=e=>{let{currentNode:t}=v(),n=t.context??"WORKSPACE";return{[f.NONE]:Ha(),[f.EXIT]:["confirm"],[f.EXPORT]:[],[f.SYNC]:[],[f.INIT]:[],[f.HELP]:[],[f.PEEK]:[...So(),"now","prev","next"],[f.SET_USERNAME]:[],[f.SET_DESCRIPTION]:["confirm"],[f.DELETE]:["confirm"],[f.RE_OPEN_ISSUE]:["confirm"],[f.CLOSE_ISSUE]:["confirm"],[f.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[f.FILTER]:["tag","assignee","description","title","clear"],[f.SET_VIEW]:["dense","wide"],[f.SET_EDITOR]:[...so],[f.TAG]:[...new Set([...Object.keys(rt),...b.getExistingTags()])],[f.UNTAG]:[...Jt()?.value?.map(({name:o})=>o)??[]],[f.UNASSIGN]:[...Zt()?.value?.map(({name:o})=>o)??[]],[f.ASSIGN]:b.getExistingAssignees(),[f.RENAME]:[],[f.NEW]:Wa(n)}[e]??[]};import it from"chalk";import{decodeTime as To}from"ulid";var Ro=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"},Mo=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())}`},nn=e=>{try{return c("Decoded date",new Date(To(e)))}catch(t){return s("Decoding failed + "+t.message)}},rr=e=>{if(!e?.id)return null;try{return To(e.id)}catch{return null}};var Ae=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?c("Found node",n):s("Unable to find node in breadcrumb")};import ot from"chalk";var ir={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ja=(e,t,n)=>Math.max(t,Math.min(n,e)),or=(e,t,n)=>e+(t-e)*n,Po=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Ka=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,a=e/60,l=i*(1-Math.abs(a%2-1)),u=0,m=0,p=0;a>=0&&a<1?(u=i,m=l):a>=1&&a<2?(u=l,m=i):a>=2&&a<3?(m=i,p=l):a>=3&&a<4?(m=l,p=i):a>=4&&a<5?(u=l,p=i):(u=i,p=l);let y=o-i/2;return[Math.round((u+y)*255),Math.round((m+y)*255),Math.round((p+y)*255)]},Va=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,za=(e,t,n)=>[Math.round(or(e[0],t[0],n)),Math.round(or(e[1],t[1],n)),Math.round(or(e[2],t[2],n))],Et=e=>{let n=Po(e)%360,r=Ka(n,ir.stringColor.saturation,ir.stringColor.lightness);return Va(r)},qa=e=>{let t=ir.gradient.stops,n=ja(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 za(t[i],t[i+1],a)},rn=e=>Po(e.toLowerCase().trim())/4294967295,ko=e=>{let t=rn(e);return qa(t)},Ga=e=>{let[t,n,r]=ko(e);return{normal:o=>ot.bgRgb(t,n,r).black(o),cursor:o=>ot.bgRgb(t,n,r).white.bold(o)}},sr=e=>{let[t,n,r]=ko(e);return{fg:o=>ot.rgb(t,n,r)(o),fgCursor:o=>ot.rgb(t,n,r).inverse(o),bg:o=>ot.bgRgb(t,n,r).black(o),bgCursor:o=>ot.bgRgb(t,n,r).white.bold(o)}},ar=e=>Ga(e).normal(` ${e} `),X=(e,t=rt)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:Et(r)};var we={None:"none",Invalid:"invalid",Valid:"valid"};var Ya=["BOARD","TICKET","SWIMLANE"],dr=()=>{let e=v().selectedNode;return e?.context?Ya.includes(e?.context)?W():U({message:"Command not available in this context"}):U({message:"Missing target context"})},ee="<ENTER> to confirm",W=(e="",t=[])=>({message:e,validity:we.Valid,completionWordList:t}),U=({message:e,completionWordList:t=[]})=>({validity:we.Invalid,message:e,completionWordList:t}),Ct=e=>e.length===0,$e=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let u=[...t.filter(Boolean).filter(p=>p.startsWith(o.trim()))].sort((p,y)=>rn(p)-rn(y)).slice(0,r).map(ar),m=u.length>i?u.join(" "):"";return m?`${e}${m}${n}`:""},lr=({modifier:e})=>{let t="confirm";return e===t?W(ee):U({message:Ct(e)?`if you are certain, enter ${ar(t)}`:"",completionWordList:[t]})},Xa=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?W(ee):U({message:Ct(n)?t:""}),Ja=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?U({message:n}):W():U({message:Ct(r)?t:""}),Nt=({hint:e})=>({modifier:t,inputString:n})=>Ct(t)&&Ct(n)?U({message:e,completionWordList:[]}):W(ee),Za={[f.EXPORT]:()=>W(ee+", and create export markdown file"),[f.PEEK]:e=>{let t=e.modifier;if(t==="now")return W(ee);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return W(ee);let r=Qt(t);if(!t||!r)return U(n);let o=Ae(v().breadCrumb,"BOARD");if(d(o))return U({message:"Command is not applicable in this context"});let i=nn(o.value.id);return d(i)?U({message:"Unable to peek: board id is not a valid ULID"}):Io({date:r,horizonDate:i.value})?W(ee):U({message:it.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[f.EXIT]:()=>W(ee+" and exit the application"),[f.INIT]:()=>W(ee),[f.FILTER]:e=>{if(e.modifier==="clear")return W();let t=a=>z(f.FILTER).includes(a);if(!e.modifier||!t(e.modifier??""))return U({message:$e({wordList:z(f.FILTER),inputString:e.inputString}),completionWordList:z(f.FILTER)});let r=Object.values(v().tags).map(a=>a.name),o=Object.values(v().contributors).map(a=>a.name),i=e.modifier==="tag"?r:e.modifier==="assignee"?o:[];return e.inputString?i.length&&!i.includes(e.inputString.trim()??"")?U({message:$e({prefix:`existing ${e.modifier}s... `,wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i}):W():U({message:$e({prefix:"one of... ",wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i})},[f.NONE]:e=>{let t=z(f.NONE),n=/^[A-Za-z_]+:/g,r=e.inputString.match(n);return r&&r.length?t=[...t.filter(o=>o.trim().match(n))]:t=[...new Set(t.flatMap(o=>o.match(n)?.join("").replace(":","")??o))],e.command?W():U({message:$e({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[f.NEW]:e=>Ja({list:z(f.NEW),hint:$e({wordList:z(f.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[f.SET_DESCRIPTION]:()=>W(ee),[f.HELP]:()=>W(ee),[f.RENAME]:()=>{let e=dr();return e.validity==="invalid"?e:W(ee)},[f.DELETE]:e=>{let t=dr();return t.validity==="invalid"?t:lr(e)},[f.CLOSE_ISSUE]:e=>lr(e),[f.RE_OPEN_ISSUE]:e=>lr(e),[f.MOVE]:e=>{let t=dr();return t.validity==="invalid"?t:Nt({hint:$e({prefix:"hey hacker! These commands are blocked for you... ",wordList:z(f.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[f.TAG]:e=>{let t=b.getExistingTags().map(n=>` ${it.bgHex(X(n))(" "+n+" ")} `).slice(0,10);return Nt({hint:"tag name like... "+t.join("")})(e)},[f.UNTAG]:e=>{let t=Jt();if(d(t))return U({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${it.bgHex(X(r))(" "+r+" ")} `).slice(0,10);return n.length?Nt({hint:" ... "+n.join("")})(e):U({message:"Issue has not tags",completionWordList:[]})},[f.ASSIGN]:e=>{let t=b.getExistingAssignees().map(n=>` ${it.bgHex(X(n))(" "+n+" ")} `).slice(0,10);return Nt({hint:"assign to... "+t.join("")})(e)},[f.UNASSIGN]:e=>{let t=Zt();if(d(t))return U({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${it.bgHex(X(r))(" "+r+" ")} `).slice(0,10);return n.length?Nt({hint:"remove assignee... "+n.join("")})(e):U({message:"Issue has no assignees",completionWordList:[]})},[f.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=z(f.SET_EDITOR);return e.modifier?W(ee):U({message:$e({wordList:t,inputString:e.inputString})})},[f.SET_USERNAME]:e=>e.inputString?W():U({message:`Enter a username. Saved in ${it.bgBlack("~/.epiq-global/")}`}),[f.SET_VIEW]:e=>Xa({list:z(f.SET_VIEW),hint:$e({wordList:z(f.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[f.SYNC]:()=>W(ee)},Do=Object.fromEntries(Object.entries(Za).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Lo=["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 M={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",SetView:"set-view",SetEditor:"set-editor",SetUserName:"set-user-name",SetAutoSync:"set-auto-sync",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Sync:"sync",Export:"export"};var Fo=e=>Object.values(f).includes(e),Oo=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:l,completionWordList:u}=Do[n].validate(n,r,i),m=o==="command"?Object.values(f):n&&e.target==="modifier"?z(n):Lo;return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?io(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var Bo=e=>{let t=e.trimStart(),n=ed(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),a=td(e),l=Fo(r)?r:null,u=l!==null,m=r!=="",p=l?z(l)??[]:[],y=l&&p.includes(o)?o:"",N="word";n.length===0||n.length===1&&!i?N="command":(n.length===1&&i||n.length===2&&!i)&&(N="modifier");let S=i?"":a,A=Qa(t,l,y);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:a,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:i,modifier:y,target:N,inputToMatch:S,inputString:A}},Qa=(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},ed=e=>e.trim()?e.trim().split(/\s+/):[],td=e=>e.trimEnd().split(/\s+/).at(-1)??"";var Uo=" ",J={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:we.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},cr=new Set,$o=()=>{for(let e of cr)e()},_o=e=>(cr.add(e),()=>cr.delete(e)),Te=e=>{let n=e(J),r=Bo(n.value),o=n.cursorPosition===n.value.length;J={...n,commandMeta:Oo(r,o)},$o()},bt=({message:e,status:t})=>{let n=structuredClone(J);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,J=n,$o(),c(e,null)},ur=e=>{Te(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},mr=e=>{Te(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}})},Wo=()=>{Te(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}})},Ho=()=>{Te(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&t[r-1]===" ";)r--;for(;r>0&&t[r-1]!==" ";)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},j=e=>{Te(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,l=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:l,commandIsPending:!1}})},jo=()=>{Te(e=>({...e,commandIsPending:!0}))},Ko=({addToHistory:e=!0})=>{Te(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),nd()},Vo=()=>{Te(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}})},zo=()=>{Te(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},nd=()=>j(()=>""),ne=()=>J,on=()=>{let[e,...t]=J.value.split(Uo);return t.join(Uo).trim()};var rd=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",od=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",id=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",qo=(e,t)=>{if(od(e,e.sequence))return x.MoveCursorLeftOfWord;if(id(e,e.sequence))return x.MoveCursorRightOfWord;if(rd(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 sd(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 ad(e,t,n){let r=v().currentNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function Go(e,t){let n=ne();if(e.sequence===":"&&n.value==="")return x.InitCommandLine;if(t===g.MOVE)switch(e.name){case"m":case"return":return x.ConfirmMove}if(t===g.COMMAND_LINE)return qo(e,n.value);let r=sd(e);if(r){let o=t===g.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 ad(v().currentNode.childRenderAxis,r,o)}if(e.ctrl&&e.name==="c")return x.Exit;switch(e.name){case"e":return x.Edit;case"n":return x.AddItem;case"m":return x.InitMove;case"d":return x.Delete;case"return":return x.Confirm;case"space":return x.Confirm;case"v":return v().viewMode==="wide"?x.SetViewDense:x.SetViewWide;case"q":case"escape":return x.Exit;case"s":return x.Sync;default:return null}}var Yo=e=>{let{context:t}=v()?.currentNode;if(!t)return M.None;switch(e){case f.EXIT:return M.Exit;case f.EXPORT:return M.Export;case f.INIT:return M.Init;case f.DELETE:return M.Delete;case f.SET_DESCRIPTION:return M.Edit;case f.HELP:return M.ViewHelp;case f.RE_OPEN_ISSUE:return M.ReopenIssue;case f.CLOSE_ISSUE:return M.CloseIssue;case f.TAG:return M.TagTicket;case f.UNTAG:return M.UntagTicket;case f.ASSIGN:return M.AssignUserToTicket;case f.UNASSIGN:return M.UnassignUserFromTicket;case f.RENAME:return M.Rename;case f.NEW:return M.NewItem;case f.FILTER:return M.Filter;case f.MOVE:return M.Move;case f.PEEK:return M.Peek;case f.SET_USERNAME:return M.SetUserName;case f.SET_EDITOR:return M.SetEditor;case f.SET_VIEW:return M.SetView;case f.SYNC:return M.Sync;default:return M.None}};import{ulid as _}from"ulid";import li from"node:fs";import Fd from"node:path";import Od from"react";import{Box as Dd}from"ink";import un from"react";import{Box as fr,Text as hd}from"ink";import ve from"react";import{Text as Xo}from"ink";import Jo,{useEffect as Zo,useState as dd}from"react";var Qo={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},re=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=$(),r=Qo[n]??Qo.default,[o,i]=dd(0);if(Zo(()=>{i(0)},[r]),Zo(()=>{if(!e)return;let l=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return Jo.createElement(Xo,null,t);let a=r[o]??r[0]??t;return Jo.createElement(Xo,{color:E.accent,dimColor:o===1},a)};import{Box as pr,Text as ld}from"ink";import sn from"react";var an=({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)),l=Math.max(1,Math.floor(i/a)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-l),p=o?Math.min(m,Math.max(0,u-l+1)):Math.min(m,Math.floor(u/l)*l),y=p+l,N=e.slice(p,y),S=e.length>l,A=i,I=S?Math.max(1,Math.floor(l/e.length*A)):A,C=Math.max(0,A-I),T=Math.max(1,e.length-l),B=S?Math.floor(p/T*C):0;return sn.createElement(pr,{flexDirection:"row",height:i,width:"100%"},sn.createElement(pr,{flexDirection:"column",flexGrow:1,height:i},N),sn.createElement(pr,{flexDirection:"column",width:1,height:A},Array.from({length:A}).map((Oe,Be)=>sn.createElement(ld,{key:Be,color:S&&Be>=B&&Be<B+I?E.accent:E.secondary},S?"\u2502":" "))))};import{Box as dn,Text as vd}from"ink";import Ye from"react";import{Text as cd}from"ink";import ud from"react";var md=e=>e.toLowerCase().trim(),pd=(e,t=rt)=>{let n=md(e);return t[n]?t[n]:Et(n)},st=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return ud.createElement(cd,{underline:t,color:pd(n.name)},"@"+n.name)};import{Text as gd}from"ink";import fd from"react";var at=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return fd.createElement(gd,{underline:t,backgroundColor:X(n.name),color:E.primary}," "+n.name+" ")};var ei=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=_t(jn(t.title),r),i=er(t),a=tr(t);return Ye.createElement(dn,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?E.accent:E.secondary,justifyContent:"space-between"},Ye.createElement(dn,{borderBottom:!0},Ye.createElement(dn,{paddingLeft:1,flexDirection:"column"},Ye.createElement(vd,{color:E.primary},o))),Ye.createElement(dn,{flexDirection:"row",paddingLeft:1},i.map(l=>Ye.createElement(at,{key:l.id,id:l.id})),a.map(l=>Ye.createElement(st,{key:l.id,id:l.id}))))};import xd from"chalk";import{Box as It,Text as gr}from"ink";import Re from"react";var yd=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,ti=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=R(t.id),a=I=>{let C=i.find(T=>T.title===I);return C?R(C.id).map(T=>typeof T.props?.value=="string"?T.props.value:"").filter(T=>!!T):[]},l=a("Tags").map(I=>b.getTag(I)).filter(I=>!!I),u=a("Assignees").map(I=>b.getContributor(I)).filter(I=>!!I),m=1,p=l.length*(1+m),y=u.length*(2+m),N=l.map(I=>Re.createElement(It,{key:I.id,paddingRight:m},Re.createElement(gr,{color:X(I.name)},"\u25A0"))),S=u.map(I=>Re.createElement(It,{key:I.id,paddingRight:m},Re.createElement(gr,{color:Et(I.name)},"@"+I.name.at(0)))),A=n?E.accent:o===g.MOVE?E.secondary:E.primary;return Re.createElement(It,{borderBottom:!0,justifyContent:"space-between"},Re.createElement(It,null,Re.createElement(re,{isSelected:n,placeholder:xd.dim.gray(r+1+" ")}),Re.createElement(gr,{wrap:"truncate",color:A},yd(t.title,e-p-y-14))),Re.createElement(It,null,N,S))};var Ed=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:a,mode:l})=>{let{renderedChildrenIndex:u}=$(),m=u[e.id]??[],p=`${e.title} (${m.length})`,y=3,N=o?1:4,S=r-y-(o?2:1),A=ve.createElement(fr,{borderStyle:"round",borderColor:E.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},ve.createElement(re,{isSelected:t}),ve.createElement(hd,{bold:!0,color:t?E.accent:E.primary},p," ",e.readonly?"\u{1F512}":"")),I=(C,T)=>{let B=i&&a===T;return o?ve.createElement(ti,{key:C.id,index:T,width:n,ticket:C,isSelected:B,mode:l}):ve.createElement(ei,{key:C.id,width:n,ticket:C,isSelected:B})};return ve.createElement(fr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?E.accent:E.secondary,paddingRight:1,paddingLeft:1,height:r},A,ve.createElement(fr,{padding:o?1:0},m.length>0&&ve.createElement(an,{selectedIndex:a,height:S,itemHeight:N},m.map(I)),ve.createElement(re,{isSelected:i&&a===-1})))},ni=ve.memo(Ed);import{Box as yr,Text as Pd}from"ink";import _e,{useEffect as hr,useMemo as si}from"react";import Xe from"chalk";import ri from"string-width";import{decodeTime as Nd}from"ulid";var Cd=(e,t)=>e+" ".repeat(Math.max(0,t-ri(e))),bd=(e,t)=>" ".repeat(Math.max(0,t-ri(e)))+e,Id=e=>(()=>{let n={"add.issue":"Created with title","assign.issue":"Assigned to","unassign.issue":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","tag.issue":"Tagged with","untag.issue":"Removed tag","lock.node":"Locked node","move.node":"Moved issue"};return(o=>n[o]??(o.endsWith("e")?`${o}d`:`${o}ed`))(e)})(),Sd=e=>{switch(e.action){case"move.node":{let t=b.getNode(e.payload.parent);return`to ${t?Xe.dim.bgBlack(` ${t.title} `):"unknown"} with rank ${e.payload.rank}`}case"tag.issue":{let t=v().tags[e.payload.tagId];return t?Xe.bgHex(X(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=v().tags[e.payload.tagId];return t?Xe.bgHex(X(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=v().contributors[e.payload.contributor];return t?Xe.hex(X(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=v().contributors[e.payload.contributor];return t?Xe.hex(X(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""}},Ad=e=>{let t=Ro(Nd(e));return Xe.gray(bd(t,8))},wd=12,Td=e=>Cd(`${e}`,wd),oi=e=>{let t=Ad(e.id),n=Td(e.userName),r=Id(e.action),o=Sd(e),i=Xe.dim("\u203A"),a=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${a}`};import{Box as ln,Text as Rd}from"ink";import Me from"react";var ii=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=$(),{title:o}=t,i=R(t.id).map(a=>{let l=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return b.getContributor(l)?.id;if(o==="Tags")return b.getTag(l)?.id}).filter(a=>!!a);return Me.createElement(ln,{alignItems:"center",paddingTop:1},Me.createElement(ln,{minWidth:12},Me.createElement(re,{isSelected:n}),Me.createElement(Rd,{color:n?E.accent:E.secondary2},o,":")),Me.createElement(ln,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,l)=>{let u=r.id===t.id&&l===e;return Me.createElement(ln,{key:`${o}-${a}`,paddingRight:2,minHeight:1},Me.createElement(re,{isSelected:u}),o==="Assignees"?Me.createElement(st,{isSelected:u,id:a}):o==="Tags"?Me.createElement(at,{isSelected:u,id:a}):null)})))};import{Box as cn,Text as vr}from"ink";import Pe,{useEffect as Md}from"react";var xr=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:l}=$(),u=N=>String(N).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];Md(()=>{let N=[];return m.forEach((S,A)=>{let I=Ne(BigInt(A+1));if(!Ee(I))return;let C=te.text({id:`${e}-${A}`,name:`Line ${A+1}`,parentNodeId:e,rank:I.value,props:{value:S},readonly:!0}),T=b.createNode(C);Ee(T)&&N.push(T.value.id)}),()=>N.forEach(b.deleteNode)},[e,n]);let p="\u2029",y=m.map((N,S)=>{let A=l.id===e&&a===S;return Pe.createElement(cn,{key:`${e}-${S}`},Pe.createElement(vr,{color:A?E.primary:E.secondary2,dimColor:!A},`${S+1} `.padStart(5,"\xA0")),Pe.createElement(vr,{backgroundColor:A?"gray":""},u(N.length?_t(N,i-10):p)))});return Pe.createElement(cn,{flexDirection:"column",paddingTop:1},Pe.createElement(cn,null,Pe.createElement(re,{isSelected:o}),Pe.createElement(vr,{color:o?E.accent:E.secondary2},t)),Pe.createElement(cn,{flexDirection:"row",borderStyle:"round",borderColor:E.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Pe.createElement(an,{scrollByOne:!0,children:y,height:r-2,selectedIndex:a,itemHeight:1})))};var kd=e=>`${e}::log`,ai=e=>e==="Assignees"||e==="Tags",di=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=$(),o=process.stdout.columns||120,i=si(()=>kd(e.id),[e.id]),a=si(()=>[...e.log].reverse().map(oi).join(`
5
+ `),[e.log]);hr(()=>{if(b.getNode(i))return;let T=Ne(1n);if(d(T))return;let B={...te.field(i,"Log",e.id,T.value,{value:a}),readonly:!0,childRenderAxis:"vertical"};return b.createNode(B),()=>{b.deleteNode(i)}},[i,e.id,a]),hr(()=>{let C=b.getNode(i);C&&C.props.value!==a&&b.updateNode({...C,props:{...C.props,value:a},childRenderAxis:"vertical",readonly:!0})},[i,a]);let l=r.id===e.id,u=r.id===i||r.parentNodeId===i;hr(()=>{u&&(n>=0||D.navigate({selectedIndex:0}))},[u,n]);let m=R(e.id);if(u){let C=b.getNode(i),B=t-3;return _e.createElement(yr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},C?_e.createElement(xr,{id:C.id,label:"Event log",text:C.props.value??"",selected:!1,maxWidth:o,height:B}):null)}let p=m.reduce((C,T)=>ai(T.title)||T.id===i?C+1:C,0),y=2,N=p*1,A=t-3-N-y,I=(C,T)=>ai(C.title)?_e.createElement(ii,{key:C.id,parent:C,selected:T,selectedIndex:n}):C.id===i?_e.createElement(yr,{key:C.id,paddingTop:1},_e.createElement(re,{isSelected:T}),_e.createElement(Pd,{backgroundColor:E.secondary,color:T?E.accent:E.primary}," History \u203A\u203A ")):C.title==="Description"?_e.createElement(xr,{label:"Description (press e to edit)",key:C.id,id:C.id,text:C.props.value??"",selected:T,maxWidth:o,height:A}):null;return _e.createElement(yr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((C,T)=>I(C,l&&n===T)))};var Ld=({swimlanes:e,currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:a,width:l})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,p=u===P.BOARD||u===P.SWIMLANE,y=u===P.TICKET?t:r.find(C=>C.context===P.TICKET),N=Math.floor(l/3),S=Math.floor(l/Math.max(e.length,1)),A=Math.min(S,N),I=i==="dense";return un.createElement(Dd,{flexDirection:"row",height:a},p&&e.map((C,T)=>{let B=t.id===C.id,Oe=B?n:-1,Be=t.context===P.BOARD&&n===T;return un.createElement(ni,{key:C.id,height:a,width:A,swimlane:C,isSelected:Be,isDense:I,isFocused:B,listSelectedIndex:Oe,mode:o})}),m&&y&&un.createElement(di,{height:a,ticket:y}))},mn=un.memo(Ld);import{render as Bd}from"ink";import{Writable as Ud}from"node:stream";var St=e=>String(e).padStart(2,"0"),$d=e=>{let t=e.getUTCFullYear(),n=St(e.getUTCMonth()+1),r=St(e.getUTCDate()),o=St(e.getUTCHours()),i=St(e.getUTCMinutes()),a=St(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${a}`},_d=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Wd=async(e,{width:t,height:n})=>{let r="",o=new Ud({write(a,l,u){let m=Hd(a.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=Bd(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(a=>setTimeout(a,0)),i.unmount(),r},Hd=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),ci=async()=>{let{currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:r,mode:o,renderedChildrenIndex:i}=v(),a=n.find(T=>T.context==="BOARD");if(!a)return s("No board found to export");let l=120,u=40,m=await Wd(Od.createElement(mn,{height:u,width:l,swimlanes:(i[a.id]??[]).filter(T=>T!==void 0&&Qe(T)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:r,mode:o}),{width:l,height:u});if(!m)return s("Failed to render board export");let p=Se(process.cwd());if(d(p))return s("Unable to export, epiq root not found");let y=new Date,N=$d(y),S=`board_${_d(a.title)}_${N}.md`,A=uo(p.value);li.mkdirSync(A,{recursive:!0});let I=Fd.join(A,S),C=`# Board - ${a.title}
6
6
  Date: ${y.toISOString()}
7
7
 
8
8
  \`\`\`text
9
9
  ${m}
10
10
  \`\`\`
11
- `;return li.writeFileSync(I,C,"utf8"),l("Exported board layout",I)};import Qe from"node:fs";import qi from"node:path";var B="epiq/eventlog",me="origin";import Mt from"node:fs";import Qd from"node:os";import ve from"node:path";import Tt from"node:fs";import{ulid as zd}from"ulid";import{z as gn}from"zod";var qd=gn.object({projectId:gn.string().min(1),stateBranch:gn.string().min(1),createdAt:gn.string().datetime()}),Gd=()=>({projectId:zd(),stateBranch:"epiq/state",createdAt:new Date().toISOString()}),fn=e=>{let t=Ae(e);if(!Tt.existsSync(t))return s("Missing .epiq/project.json");try{let n=Tt.readFileSync(t,"utf8"),r=JSON.parse(n),o=qd.safeParse(r);return o.success?l("Read project.json",o.data):s(`Invalid .epiq/project.json: ${o.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(", ")}`)}catch(n){return s(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},mi=e=>{let t=fn(e);return c(t)?s(t.message):l("Read projectId",t.value.projectId)},pi=e=>{let t=zt(e),n=Ae(e);try{if(Tt.mkdirSync(t,{recursive:!0}),Tt.existsSync(n)){let o=fn(e);return c(o)?s(o.message):l("Project already initialized",null)}let r=Gd();return Tt.writeFileSync(n,JSON.stringify(r,null,2)+`
12
- `,"utf8"),l("Created project.json",null)}catch(r){return s(r instanceof Error?`Failed to initialize project: ${r.message}`:"Failed to initialize project")}};var Nr=(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(u=>(c(u)&&n.delete(a),u));n.set(a,d)}return n.get(a)});return o.clear=()=>n.clear(),o};import Rt from"fs";import fi from"path";import Yd from"util";var gi=1e3,vi=()=>{let e=process.cwd(),t=we(e);if(!c(t))return fi.join(t.value,Se,"log","epiq.log")};function Xd(){if(!qn)return;let e=vi();if(e===void 0||!Rt.existsSync(e))return;let n=Rt.readFileSync(e,"utf8").split(`
13
- `);if(n[n.length-1]===""&&n.pop(),n.length<=gi)return;let r=n.slice(-gi).join(`
11
+ `;return li.writeFileSync(I,C,"utf8"),c("Exported board layout",I)};import ll from"node:fs";var O="epiq/eventlog",ue="origin";import Tt from"node:fs";import Xd from"node:os";import fe from"node:path";import At from"node:fs";import{ulid as jd}from"ulid";import{z as pn}from"zod";var Kd=pn.object({projectId:pn.string().min(1),stateBranch:pn.string().min(1),createdAt:pn.string().datetime()}),Vd=()=>({projectId:jd(),stateBranch:"epiq/state",createdAt:new Date().toISOString()}),gn=e=>{let t=Vt(e);if(!At.existsSync(t))return s("Missing .epiq/project.json");try{let n=At.readFileSync(t,"utf8"),r=JSON.parse(n),o=Kd.safeParse(r);return o.success?c("Read project.json",o.data):s(`Invalid .epiq/project.json: ${o.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(", ")}`)}catch(n){return s(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},ui=e=>{let t=gn(e);return d(t)?s(t.message):c("Read projectId",t.value.projectId)},mi=e=>{let t=Kt(e),n=Vt(e);try{if(At.mkdirSync(t,{recursive:!0}),At.existsSync(n)){let o=gn(e);return d(o)?s(o.message):c("Project already initialized",null)}let r=Vd();return At.writeFileSync(n,JSON.stringify(r,null,2)+`
12
+ `,"utf8"),c("Created project.json",null)}catch(r){return s(r instanceof Error?`Failed to initialize project: ${r.message}`:"Failed to initialize project")}};var Er=(e,t)=>{let n=new Map,r=t??((...i)=>JSON.stringify(i)),o=((...i)=>{let a=r(...i);if(!n.has(a)){let l=e(...i).then(u=>(d(u)&&n.delete(a),u));n.set(a,l)}return n.get(a)});return o.clear=()=>n.clear(),o};import wt from"fs";import gi from"path";import zd from"util";var pi=1e3,fi=()=>{let e=process.cwd(),t=Se(e);if(!d(t))return gi.join(t.value,Ie,"log","epiq.log")};function qd(){if(!zn)return;let e=fi();if(e===void 0||!wt.existsSync(e))return;let n=wt.readFileSync(e,"utf8").split(`
13
+ `);if(n[n.length-1]===""&&n.pop(),n.length<=pi)return;let r=n.slice(-pi).join(`
14
14
  `)+`
15
- `;Rt.writeFileSync(e,r,"utf8")}function Cr(e,t,n=!1){if(!qn)return;let r=vi();if(!r)return;let o=Yd.format(...t),i=new Date,d=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
16
- `;Rt.mkdirSync(fi.dirname(r),{recursive:!0}),Rt.appendFileSync(r,d,"utf8"),Xd()}var oe={info(...e){Cr("[Info]",e,!1)},debug(...e){Cr("->",e,!0)},error(...e){Cr("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=oe;import{spawn as Jd}from"node:child_process";import br from"node:fs";import hi from"node:path";var q={stage:({cwd:e,pathspec:t})=>L({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>L({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>L({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>L({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>L({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push",...r?["-u"]:[],t,n]:["push"];return L({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>L({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>L({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>L({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>L({args:["worktree","prune"],cwd:e})};var xi=15e3,Zd={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Ei=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!br.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=Jd("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Zd}),i=!1,a="",d="",u=p=>{i||(i=!0,clearTimeout(m),r(p))},m=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${xi}ms`].join(`
17
- `);u(n?{stdout:a,stderr:p,exitCode:124}:s(p))},xi);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){u({stdout:a,stderr:p.message,exitCode:1});return}u(s([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
18
- `)))}),o.on("close",p=>{let y=p??1;if(n){u({stdout:a,stderr:d,exitCode:y});return}if(y!==0){u(s([`git ${e.join(" ")}`,d.trim()||a.trim()||"Git command failed"].filter(Boolean).join(`
19
- `)));return}u(l("Git command succeeded",{stdout:a,stderr:d,exitCode:y}))})}),L=({args:e,cwd:t})=>Ei({args:e,cwd:t,allowFail:!1}),lt=({args:e,cwd:t})=>Ei({args:e,cwd:t,allowFail:!0}),vn=async({cwd:e,message:t})=>{let n=await q.commit({cwd:e,message:t});if(c(n))return s(`Failed to create commit
20
- ${n.message}`);let r=await L({args:["rev-parse","HEAD"],cwd:e});return c(r)?s(`Commit created, but failed to read HEAD SHA
21
- ${r.message}`):l("Created commit and resolved SHA",r.value.stdout.trim())},Ir=async e=>{let t=await wi(e);if(c(t))return s(t.message);let n=t.value,o=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","REBASE_HEAD","rebase-merge","rebase-apply"].filter(i=>br.existsSync(hi.join(n,i)));return l("Checked for in-progress Git operation",o.length>0)},Sr=async({repoRoot:e})=>{let n=(await lt({args:["remote","get-url",me],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},xn=async({repoRoot:e,branch:t})=>{let n=await lt({args:["ls-remote","--heads",me,t],cwd:e});return n.exitCode!==0?s(n.stderr.trim()||`Unable to inspect remote branch ${me}/${t}`):l("Checked remote branch",n.stdout.trim().length>0)},Ni=async({repoRoot:e,branch:t})=>{let n=await lt({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?l("Local branch exists",!0):n.exitCode===1?l("Local branch missing",!1):s(n.stderr.trim()||`Unable to inspect branch ${t}`)},yi=e=>{try{return br.realpathSync.native(e)}catch{return hi.resolve(e)}},Ci=async({repoRoot:e,worktreeRoot:t})=>{let n=await L({args:["worktree","list","--porcelain"],cwd:e});if(c(n))return s(n.message);let r=yi(t),o=n.value.stdout.split(`
22
- `).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(yi).includes(r);return l("Checked worktree registration",o)},Ar=async e=>{let t=await lt({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},yn=async e=>{let t=await L({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return c(t)?s(t.message):l("Resolved current branch",t.value.stdout.trim())},bi=async e=>{let t=await L({args:["rev-parse","--short","HEAD"],cwd:e});return c(t)?s(t.message):l("Resolved short HEAD sha",t.value.stdout.trim())},Ii=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),hn=async({cwd:e,branch:t})=>{let n=await xn({repoRoot:e,branch:t});if(c(n))return s(n.message);if(!n.value)return l("Remote branch missing, skipped pull",!1);let r=await q.fetch({cwd:e,remote:me,branch:t});if(c(r))return s(`Failed to fetch ${t}
23
- ${r.message}`);let o=await q.pullRebase({cwd:e,remote:me,branch:t});return c(o)?s(`Failed during pull --rebase
24
- ${o.message}`):l("Pulled with rebase",!0)},Si=async e=>{let t=await L({args:["status","--porcelain"],cwd:e});return c(t)?s(t.message):l("Checked state branch changes",t.value.stdout.trim().length>0)},Ai=async e=>{let t=await yn(e);return c(t)?s(t.message):l("Checked detached HEAD state",t.value==="HEAD")};var Ti="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Ri=e=>ve.join(Se,Vt,e),Mi=()=>ve.join(Qd.homedir(),ue),Pi=()=>ve.join(Mi(),"worktrees"),ki=e=>{let t=mi(e);return c(t)?s(t.message):l("Resolved state branch root",ve.join(Pi(),t.value))},ec=e=>ve.join(e,Se),Ze=e=>ve.join(ec(e),Vt),wr=({root:e,fileName:t})=>ve.join(Ze(e),t),Pt=e=>{try{return Mt.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return s(t instanceof Error?t.message:String(t))}},Di=()=>{let e=Pt(Mi());if(c(e))return s(`Ensure epiq home failed.
25
- `+e.message);let t=Pt(Pi());return c(t)?s(`Ensure worktrees dir failed.
26
- `+t.message):l("Ensured epiq storage",!0)},Li=e=>{Mt.existsSync(e)&&(oe.debug("[sync] remove path",e),Mt.rmSync(e,{recursive:!0,force:!0}))},Fi=e=>{let t=Ze(e);if(!Mt.existsSync(t))return l("Events dir missing",[]);let n=Mt.readdirSync(t,{withFileTypes:!0}).filter(r=>r.isFile()).map(r=>r.name).filter(r=>r.endsWith(".jsonl")).sort();return l("Listed event files",n)},Bi=(e,t)=>{for(let n of[Ze(e),Ze(t)]){let r=Pt(n);if(c(r))return s(r.message)}return l("Ensured state branch",void 0)},Oi=async e=>{let t=await L({args:["ls-tree","--name-only","HEAD"],cwd:e});if(c(t))return s(`ensure state branch is storage only failed
15
+ `;wt.writeFileSync(e,r,"utf8")}function Nr(e,t,n=!1){if(!zn)return;let r=fi();if(!r)return;let o=zd.format(...t),i=new Date,l=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
16
+ `;wt.mkdirSync(gi.dirname(r),{recursive:!0}),wt.appendFileSync(r,l,"utf8"),qd()}var oe={info(...e){Nr("[Info]",e,!1)},debug(...e){Nr("->",e,!0)},error(...e){Nr("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=oe;import{spawn as Gd}from"node:child_process";import Cr from"node:fs";import yi from"node:path";var q={stage:({cwd:e,pathspec:t})=>L({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>L({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>L({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>L({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>L({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push",...r?["-u"]:[],t,n]:["push"];return L({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>L({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>L({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>L({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>L({args:["worktree","prune"],cwd:e})};var vi=15e3,Yd={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},hi=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Cr.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=Gd("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Yd}),i=!1,a="",l="",u=p=>{i||(i=!0,clearTimeout(m),r(p))},m=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${vi}ms`].join(`
17
+ `);u(n?{stdout:a,stderr:p,exitCode:124}:s(p))},vi);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(n){u({stdout:a,stderr:p.message,exitCode:1});return}u(s([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
18
+ `)))}),o.on("close",p=>{let y=p??1;if(n){u({stdout:a,stderr:l,exitCode:y});return}if(y!==0){u(s([`git ${e.join(" ")}`,l.trim()||a.trim()||"Git command failed"].filter(Boolean).join(`
19
+ `)));return}u(c("Git command succeeded",{stdout:a,stderr:l,exitCode:y}))})}),L=({args:e,cwd:t})=>hi({args:e,cwd:t,allowFail:!1}),dt=({args:e,cwd:t})=>hi({args:e,cwd:t,allowFail:!0}),fn=async({cwd:e,message:t})=>{let n=await q.commit({cwd:e,message:t});if(d(n))return s(`Failed to create commit
20
+ ${n.message}`);let r=await L({args:["rev-parse","HEAD"],cwd:e});return d(r)?s(`Commit created, but failed to read HEAD SHA
21
+ ${r.message}`):c("Created commit and resolved SHA",r.value.stdout.trim())},br=async e=>{let t=await Ai(e);if(d(t))return s(t.message);let n=t.value,o=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","REBASE_HEAD","rebase-merge","rebase-apply"].filter(i=>Cr.existsSync(yi.join(n,i)));return c("Checked for in-progress Git operation",o.length>0)},Ir=async({repoRoot:e})=>{let n=(await dt({args:["remote","get-url",ue],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},vn=async({repoRoot:e,branch:t})=>{let n=await dt({args:["ls-remote","--heads",ue,t],cwd:e});return n.exitCode!==0?s(n.stderr.trim()||`Unable to inspect remote branch ${ue}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},Ei=async({repoRoot:e,branch:t})=>{let n=await dt({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):s(n.stderr.trim()||`Unable to inspect branch ${t}`)},xi=e=>{try{return Cr.realpathSync.native(e)}catch{return yi.resolve(e)}},Ni=async({repoRoot:e,worktreeRoot:t})=>{let n=await L({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return s(n.message);let r=xi(t),o=n.value.stdout.split(`
22
+ `).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(xi).includes(r);return c("Checked worktree registration",o)},Sr=async e=>{let t=await dt({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},xn=async e=>{let t=await L({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?s(t.message):c("Resolved current branch",t.value.stdout.trim())},Ci=async e=>{let t=await L({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?s(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},bi=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),yn=async({cwd:e,branch:t})=>{let n=await vn({repoRoot:e,branch:t});if(d(n))return s(n.message);if(!n.value)return c("Remote branch missing, skipped pull",!1);let r=await q.fetch({cwd:e,remote:ue,branch:t});if(d(r))return s(`Failed to fetch ${t}
23
+ ${r.message}`);let o=await q.pullRebase({cwd:e,remote:ue,branch:t});return d(o)?s(`Failed during pull --rebase
24
+ ${o.message}`):c("Pulled with rebase",!0)},Ii=async e=>{let t=await L({args:["status","--porcelain"],cwd:e});return d(t)?s(t.message):c("Checked state branch changes",t.value.stdout.trim().length>0)},Si=async e=>{let t=await xn(e);return d(t)?s(t.message):c("Checked detached HEAD state",t.value==="HEAD")};var wi="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Ti=e=>fe.join(Ie,jt,e),Ri=()=>fe.join(Xd.homedir(),ce),Mi=()=>fe.join(Ri(),"worktrees"),Pi=e=>{let t=ui(e);return d(t)?s(t.message):c("Resolved state branch root",fe.join(Mi(),t.value))},Jd=e=>fe.join(e,Ie),Je=e=>fe.join(Jd(e),jt),Ar=({root:e,fileName:t})=>fe.join(Je(e),t),Rt=e=>{try{return Tt.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return s(t instanceof Error?t.message:String(t))}},ki=()=>{let e=Rt(Ri());if(d(e))return s(`Ensure epiq home failed.
25
+ `+e.message);let t=Rt(Mi());return d(t)?s(`Ensure worktrees dir failed.
26
+ `+t.message):c("Ensured epiq storage",!0)},Di=e=>{Tt.existsSync(e)&&(oe.debug("[sync] remove path",e),Tt.rmSync(e,{recursive:!0,force:!0}))},Li=e=>{let t=Je(e);if(!Tt.existsSync(t))return c("Events dir missing",[]);let n=Tt.readdirSync(t,{withFileTypes:!0}).filter(r=>r.isFile()).map(r=>r.name).filter(r=>r.endsWith(".jsonl")).sort();return c("Listed event files",n)},Fi=(e,t)=>{for(let n of[Je(e),Je(t)]){let r=Rt(n);if(d(r))return s(r.message)}return c("Ensured state branch",void 0)},Oi=async e=>{let t=await L({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return s(`ensure state branch is storage only failed
27
27
  `+t.message);let r=t.value.stdout.trim().split(`
28
- `).filter(Boolean).filter(a=>a!==Se);if(r.length===0)return l("State branch is storage-only",!1);let o=await L({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(c(o))return s(`Failed to clean storage branch
29
- ${o.message}`);let i=await vn({cwd:e,message:"[epiq:repair-storage-branch]"});return c(i)?s(i.message):l("Cleaned storage branch",!0)},Ui=Nr(async(e=process.cwd())=>{let t=await L({args:["rev-parse","--show-toplevel"],cwd:e});return c(t)?s("Not inside a Git repository"):l("Resolved repo root",t.value.stdout.trim())},e=>ve.resolve(e)),wi=Nr(async e=>{let t=await L({args:["rev-parse","--git-dir"],cwd:e});if(c(t))return s(t.message);let n=t.value.stdout.trim(),r=ve.isAbsolute(n)?n:ve.join(e,n);return l("Resolved git dir",r)},e=>ve.resolve(e));import ut from"node:fs";import kt from"node:path";var ji=async e=>{if((await lt({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return l("Initial commit already exists",!1);oe.info("Creating initial commit");let n=await q.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return c(n)?s(n.message):l("Created initial commit",!0)},$i=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",tc=async e=>{let t=await yn(e);if(c(t))return s(t.message);let n=await bi(e);if(c(n))return s(n.message);let r=`[epiq:sync:${$i(t.value)}:${$i(n.value)}]`;return l("Built sync commit message",r)},_i=async e=>{oe.info(`Creating ${B}`);let t=await L({args:["commit-tree",Ti,"-m","[epiq:init-state-branch]"],cwd:e});if(c(t))return s(`Failed to create state branch commit
30
- ${t.message}`);let n=t.value.stdout.trim(),r=await L({args:["update-ref",`refs/heads/${B}`,n],cwd:e});return c(r)?s(`Failed to create ${B}
31
- ${r.message}`):l("Created state branch",!0)},nc=async({repoRoot:e})=>{let t=await Ni({repoRoot:e,branch:B});if(c(t))return s(`Ensure local state branch failed
32
- `+t.message);if(t.value)return l("Local state branch already exists",!1);let n=await Sr({repoRoot:e});if(c(n))return s(`Ensure local state branch failed
33
- `+n.message);if(!n.value)return _i(e);let r=await xn({repoRoot:e,branch:B});if(c(r))return s(`Ensure local state branch failed
34
- `+r.message);if(!r.value)return _i(e);let o=await q.fetch({cwd:e,remote:me,branch:B});if(c(o))return s(`Failed to fetch ${B} from remote
35
- ${o.message}`);let i=await L({args:["branch","--track",B,`${me}/${B}`],cwd:e});return c(i)?s(`Failed to create local ${B} from remote
36
- ${i.message}`):l("Created local state branch from remote",!0)},rc=async({repoRoot:e,branch:t})=>{let n=await L({args:["worktree","list","--porcelain"],cwd:e});if(c(n))return s(n.message);let r=n.value.stdout.split(`
37
- `),o=null;for(let i of r){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return l("Found worktree for branch",o)}return l("No worktree found for branch",null)},oc=async({repoRoot:e,stateBranchRoot:t})=>{let n=Pt(kt.dirname(t));if(c(n))return s(`Failed to create state branch worktree
38
- `+n.message);ut.existsSync(t)&&!ut.existsSync(kt.join(t,".git"))&&(oe.info("Removing broken state branch worktree path"),Li(t)),oe.info("Creating state branch worktree");let r=await q.worktreeAdd({cwd:e,worktreeRoot:t,branch:B});return c(r)?s(`Failed to create state branch worktree
39
- ${r.message}`):l("Created state branch worktree",!0)},ic=async({repoRoot:e,stateBranchRoot:t})=>{let n=await rc({repoRoot:e,branch:B});if(c(n))return s(n.message);let r=kt.resolve(t),o=n.value?kt.resolve(n.value):null;if(o&&o===r&&ut.existsSync(o))return l("State branch already checked out in expected worktree",!1);if(o&&o!==r){oe.info("Moving state branch worktree to expected location");let d=await q.worktreeRemove({cwd:e,worktreeRoot:o});if(c(d))return s(`Failed to remove existing state branch worktree
40
- ${d.message}`)}if(o&&!ut.existsSync(o)){oe.info("Pruning stale state branch worktree");let d=await q.worktreePrune({cwd:e});if(c(d))return s(`Failed to prune stale worktrees
41
- ${d.message}`)}let i=await Ci({repoRoot:e,worktreeRoot:t});if(c(i))return s(i.message);let a=ut.existsSync(t);if(i.value&&a)return l("State branch worktree already exists",!1);if(i.value&&!a){oe.info("Pruning missing registered state branch worktree");let d=await q.worktreePrune({cwd:e});if(c(d))return s(`Failed to prune stale worktrees
42
- ${d.message}`)}return oc({repoRoot:e,stateBranchRoot:t})},sc=async e=>{let t=await yn(e);if(c(t))return s(t.message);if(t.value===B)return l("State branch already checked out",!1);let n=await q.checkout({cwd:e,branch:B});return c(n)?s(`Failed to checkout ${B}
43
- ${n.message}`):l("Checked out state branch",!0)},ac=async e=>{let t=await Ar(e);if(c(t))return s(t.message);if(t.value)return l("State branch upstream already configured",!1);let n=await Sr({repoRoot:e});if(c(n))return s(n.message);if(!n.value)return l("No remote available for state branch upstream",!1);let r=await xn({repoRoot:e,branch:B});if(c(r))return s(r.message);if(!r.value)return l("Remote state branch missing; upstream will be configured on first push",!1);oe.info(`Configuring ${B} upstream`);let o=await q.fetch({cwd:e,remote:me,branch:B});if(c(o))return s(`Failed to fetch ${B}
44
- ${o.message}`);let i=await q.setUpstream({cwd:e,branch:B,upstream:`${me}/${B}`});return c(i)?s(`Failed to set state branch upstream
45
- ${i.message}`):l("Configured state branch upstream",!0)},Wi=async({stateBranchRoot:e,ownEventFileName:t})=>{let n=Ri(t),r=kt.join(e,n),o=[".epiq/project.json"];ut.existsSync(r)&&o.push(n);let i=await q.stage({cwd:e,pathspec:o});return c(i)?s(`Failed to stage state branch files
46
- ${i.message}`):l("Staged state branch files",void 0)},Hi=async({repoRoot:e,stateBranchRoot:t})=>{let n=await tc(e);return c(n)?s(`Create state branch sync commit failed
47
- `+n.message):vn({cwd:t,message:n.value})},Tr=async e=>{let t=await Ar(e);if(c(t))return s(t.message);let n=t.value?await q.push({cwd:e}):await q.push({cwd:e,remote:me,branch:B,setUpstream:!0});return c(n)?s(`Failed during state branch push
48
- ${n.message}`):l("Pushed state branch",!0)},Ki=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=[Di(),await nc({repoRoot:e}),await ic({repoRoot:e,stateBranchRoot:t}),await sc(t),await Oi(t),n?await ac(t):l("Skipped state branch upstream bootstrap",!1)];for(let i of o){if(c(i))return s(i.message);r=r||!!i.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage (readonly)",r)};import En from"node:fs";import Mr from"node:path";import{decodeTime as dc}from"ulid";var Rr=e=>{let[t,n]=e.id;return`${t}:${n??""}`},Vi=e=>{let[t]=e.id;return dc(t)},cc=e=>{let{userId:t,userName:n,...r}=e;return r},lc=e=>e.length===0?"":e.map(t=>JSON.stringify(cc(t))).join(`
28
+ `).filter(Boolean).filter(a=>a!==Ie);if(r.length===0)return c("State branch is storage-only",!1);let o=await L({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return s(`Failed to clean storage branch
29
+ ${o.message}`);let i=await fn({cwd:e,message:"[epiq:repair-storage-branch]"});return d(i)?s(i.message):c("Cleaned storage branch",!0)},Bi=Er(async(e=process.cwd())=>{let t=await L({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?s("Not inside a Git repository"):c("Resolved repo root",t.value.stdout.trim())},e=>fe.resolve(e)),Ai=Er(async e=>{let t=await L({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return s(t.message);let n=t.value.stdout.trim(),r=fe.isAbsolute(n)?n:fe.join(e,n);return c("Resolved git dir",r)},e=>fe.resolve(e));import lt from"node:fs";import Mt from"node:path";var _i=async e=>{if((await dt({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);oe.info("Creating initial commit");let n=await q.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?s(n.message):c("Created initial commit",!0)},Ui=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Zd=async e=>{let t=await xn(e);if(d(t))return s(t.message);let n=await Ci(e);if(d(n))return s(n.message);let r=`[epiq:sync:${Ui(t.value)}:${Ui(n.value)}]`;return c("Built sync commit message",r)},$i=async e=>{oe.info(`Creating ${O}`);let t=await L({args:["commit-tree",wi,"-m","[epiq:init-state-branch]"],cwd:e});if(d(t))return s(`Failed to create state branch commit
30
+ ${t.message}`);let n=t.value.stdout.trim(),r=await L({args:["update-ref",`refs/heads/${O}`,n],cwd:e});return d(r)?s(`Failed to create ${O}
31
+ ${r.message}`):c("Created state branch",!0)},Qd=async({repoRoot:e})=>{let t=await Ei({repoRoot:e,branch:O});if(d(t))return s(`Ensure local state branch failed
32
+ `+t.message);if(t.value)return c("Local state branch already exists",!1);let n=await Ir({repoRoot:e});if(d(n))return s(`Ensure local state branch failed
33
+ `+n.message);if(!n.value)return $i(e);let r=await vn({repoRoot:e,branch:O});if(d(r))return s(`Ensure local state branch failed
34
+ `+r.message);if(!r.value)return $i(e);let o=await q.fetch({cwd:e,remote:ue,branch:O});if(d(o))return s(`Failed to fetch ${O} from remote
35
+ ${o.message}`);let i=await L({args:["branch","--track",O,`${ue}/${O}`],cwd:e});return d(i)?s(`Failed to create local ${O} from remote
36
+ ${i.message}`):c("Created local state branch from remote",!0)},el=async({repoRoot:e,branch:t})=>{let n=await L({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return s(n.message);let r=n.value.stdout.split(`
37
+ `),o=null;for(let i of r){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)},tl=async({repoRoot:e,stateBranchRoot:t})=>{let n=Rt(Mt.dirname(t));if(d(n))return s(`Failed to create state branch worktree
38
+ `+n.message);lt.existsSync(t)&&!lt.existsSync(Mt.join(t,".git"))&&(oe.info("Removing broken state branch worktree path"),Di(t)),oe.info("Creating state branch worktree");let r=await q.worktreeAdd({cwd:e,worktreeRoot:t,branch:O});return d(r)?s(`Failed to create state branch worktree
39
+ ${r.message}`):c("Created state branch worktree",!0)},nl=async({repoRoot:e,stateBranchRoot:t})=>{let n=await el({repoRoot:e,branch:O});if(d(n))return s(n.message);let r=Mt.resolve(t),o=n.value?Mt.resolve(n.value):null;if(o&&o===r&&lt.existsSync(o))return c("State branch already checked out in expected worktree",!1);if(o&&o!==r){oe.info("Moving state branch worktree to expected location");let l=await q.worktreeRemove({cwd:e,worktreeRoot:o});if(d(l))return s(`Failed to remove existing state branch worktree
40
+ ${l.message}`)}if(o&&!lt.existsSync(o)){oe.info("Pruning stale state branch worktree");let l=await q.worktreePrune({cwd:e});if(d(l))return s(`Failed to prune stale worktrees
41
+ ${l.message}`)}let i=await Ni({repoRoot:e,worktreeRoot:t});if(d(i))return s(i.message);let a=lt.existsSync(t);if(i.value&&a)return c("State branch worktree already exists",!1);if(i.value&&!a){oe.info("Pruning missing registered state branch worktree");let l=await q.worktreePrune({cwd:e});if(d(l))return s(`Failed to prune stale worktrees
42
+ ${l.message}`)}return tl({repoRoot:e,stateBranchRoot:t})},rl=async e=>{let t=await xn(e);if(d(t))return s(t.message);if(t.value===O)return c("State branch already checked out",!1);let n=await q.checkout({cwd:e,branch:O});return d(n)?s(`Failed to checkout ${O}
43
+ ${n.message}`):c("Checked out state branch",!0)},ol=async e=>{let t=await Sr(e);if(d(t))return s(t.message);if(t.value)return c("State branch upstream already configured",!1);let n=await Ir({repoRoot:e});if(d(n))return s(n.message);if(!n.value)return c("No remote available for state branch upstream",!1);let r=await vn({repoRoot:e,branch:O});if(d(r))return s(r.message);if(!r.value)return c("Remote state branch missing; upstream will be configured on first push",!1);oe.info(`Configuring ${O} upstream`);let o=await q.fetch({cwd:e,remote:ue,branch:O});if(d(o))return s(`Failed to fetch ${O}
44
+ ${o.message}`);let i=await q.setUpstream({cwd:e,branch:O,upstream:`${ue}/${O}`});return d(i)?s(`Failed to set state branch upstream
45
+ ${i.message}`):c("Configured state branch upstream",!0)},Wi=async({stateBranchRoot:e,ownEventFileName:t})=>{let n=Ti(t),r=Mt.join(e,n);if(!lt.existsSync(r))return c("No event file to stage",void 0);let o=await q.stage({cwd:e,pathspec:[n]});return d(o)?s(`Failed to stage state branch event file
46
+ ${o.message}`):c("Staged state branch event file",void 0)},Hi=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Zd(e);return d(n)?s(`Create state branch sync commit failed
47
+ `+n.message):fn({cwd:t,message:n.value})},wr=async e=>{let t=await Sr(e);if(d(t))return s(t.message);let n=t.value?await q.push({cwd:e}):await q.push({cwd:e,remote:ue,branch:O,setUpstream:!0});return d(n)?s(`Failed during state branch push
48
+ ${n.message}`):c("Pushed state branch",!0)},ji=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=[ki(),await Qd({repoRoot:e}),await nl({repoRoot:e,stateBranchRoot:t}),await rl(t),await Oi(t),n?await ol(t):c("Skipped state branch upstream bootstrap",!1)];for(let i of o){if(d(i))return s(i.message);r=r||!!i.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage (readonly)",r)};import hn from"node:fs";import Rr from"node:path";import{decodeTime as il}from"ulid";var Tr=e=>{let[t,n]=e.id;return`${t}:${n??""}`},Ki=e=>{let[t]=e.id;return il(t)},sl=e=>{let{userId:t,userName:n,...r}=e;return r},al=e=>e.length===0?"":e.map(t=>JSON.stringify(sl(t))).join(`
49
49
  `)+`
50
- `,uc=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(Rr(r),r);return[...n.values()].sort((r,o)=>{let i=Vi(r)-Vi(o);return i!==0?i:Rr(r).localeCompare(Rr(o))})},Pr=({sourceFile:e,targetFile:t})=>{let n=Yt(e);if(c(n))return s(n.message);let r=Yt(t);if(c(r))return s(r.message);let o=uc(r.value,n.value),i=lc(o);return(En.existsSync(t)?En.readFileSync(t,"utf8"):"")===i?l("Event file already merged",!1):(En.mkdirSync(Mr.dirname(t),{recursive:!0}),En.writeFileSync(t,i,"utf8"),l("Merged event file",!0))},kr=({repoRoot:e,stateBranchRoot:t})=>{let n=Fi(t);if(c(n))return s(n.message);let r=Ze(t),o=Ze(e),i=!1;for(let a of n.value){let d=Mr.join(r,a),u=Mr.join(o,a),m=Pr({sourceFile:d,targetFile:u});if(c(m))return s(m.message);i=i||m.value}return l("Hydrated event files from state branch",i)};var Gi=({repoRoot:e,stateBranchRoot:t})=>{let n=Ae(e),r=Ae(t);return Qe.existsSync(r)?(Qe.mkdirSync(qi.dirname(n),{recursive:!0}),Qe.copyFileSync(r,n),l("Synced project.json from state branch",!0)):l("No project.json found in state branch",!1)},mc=({repoRoot:e,stateBranchRoot:t})=>{let n=Ae(e),r=Ae(t);return Qe.existsSync(n)?(Qe.mkdirSync(qi.dirname(r),{recursive:!0}),Qe.copyFileSync(n,r),l("Synced project.json to state branch",!0)):s("Missing local .epiq/project.json")},Yi=async(e=process.cwd())=>{let t=await Xi({cwd:e,ensureUpstream:!1});if(c(t))return t;let{repoRoot:n,stateBranchRoot:r}=t.value,o=await hn({cwd:r,branch:B});if(c(o))return s(o.message);let i=Gi({repoRoot:n,stateBranchRoot:r});if(c(i))return s(i.message);let a=kr({repoRoot:n,stateBranchRoot:r});return c(a)?s(a.message):l("Synced state branch",{repoRoot:n,stateBranchRoot:r})},pc=({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=wr({root:e,fileName:n}),o=wr({root:t,fileName:n});return Qe.existsSync(r)?Pr({sourceFile:r,targetFile:o}):l("Local own event file missing, nothing to merge",!1)},Xi=async({cwd:e,ensureUpstream:t})=>{let n=await Ui(e);if(c(n))return s(n.message);let r=n.value,o=ki(r);if(c(o))return s(o.message);let i=o.value,a=await Ir(r);if(c(a))return s(a.message);if(a.value)return s("Cannot sync while a git operation is in progress in the current repo");let d=await ji(r);if(c(d))return s(d.message);let u=await Ki({repoRoot:r,stateBranchRoot:i,ensureUpstream:t});if(c(u))return s(u.message);let m=await Ir(i);if(c(m))return s(m.message);if(m.value)return s("Cannot sync while a git operation is in progress in the state branch");let p=Bi(r,i);return c(p)?s(p.message):l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:i,bootstrapped:u.value})},zi=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=pc({repoRoot:e,stateBranchRoot:t,ownEventFileName:n});if(c(r))return s(r.message);let o=mc({repoRoot:e,stateBranchRoot:t});if(c(o))return s(o.message);let i=await Si(t);if(c(i))return s(i.message);if(!r.value&&!i.value)return l("Own event file already up to date in state branch",{createdCommit:!1});let a=await Wi({stateBranchRoot:t,ownEventFileName:n});if(c(a))return s(a.message);let d=await Hi({repoRoot:e,stateBranchRoot:t});return c(d)?s(d.message):l("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:d.value})},Ji=async({cwd:e=process.cwd(),ownEventFileName:t})=>{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 n=await Xi({cwd:e,ensureUpstream:!0});if(c(n))return n;let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,a=await Ai(r);if(c(a))return s(a.message);if(a.value)return s("Cannot run :sync while the repository is in detached HEAD state");let d=!1,u,m=!1,p=!1,y=!1,N=await hn({cwd:o,branch:B});if(c(N))return s(N.message);m=N.value;let S=Gi({repoRoot:r,stateBranchRoot:o});if(c(S))return s(S.message);let A=kr({repoRoot:r,stateBranchRoot:o});if(c(A))return s(A.message);y=A.value;let I=await zi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(c(I))return s(I.message);if(d=I.value.createdCommit,u=I.value.commitSha,d||i){let C=await Tr(o),T=C;if(c(C)&&Ii(C.message)){let O=await hn({cwd:o,branch:B});if(c(O))return s(O.message);let ie=await zi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(c(ie))return s(ie.message);ie.value.createdCommit&&(d=!0,u=ie.value.commitSha),T=await Tr(o)}if(c(T))return s(T.message);p=T.value,logger.debug("[sync] pushed to state branch",p)}else logger.debug("[sync] no commit created, skipped push");if(d){let C=await L({args:["rev-parse","HEAD"],cwd:o});if(c(C))return s(C.message);u=C.value.stdout.trim()}return l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:d,commitSha:u,pulled:m,pushed:p,hydrated:y,bootstrapped:i})};var Qi=()=>{let{currentNode:e,selectedIndex:t}=v(),n=R(e.id)[t];return{currentNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:n?.parentNodeId??null,selectedIndex:t}},Zi=(e,t)=>Math.max(0,Math.min(e,Math.max(0,t-1))),es=e=>{let{nodes:t}=v(),n=t[e.currentNodeId];if(n&&!n.isDeleted&&e.selectedNodeId){let i=R(n.id).findIndex(a=>a.id===e.selectedNodeId);if(i>=0)return D.navigate({currentNode:n,selectedIndex:i}),l("Restored navigation",null)}if(e.selectedNodeId){let o=t[e.selectedNodeId];if(o&&!o.isDeleted&&o.parentNodeId){let i=t[o.parentNodeId];if(i&&!i.isDeleted){let a=R(i.id).findIndex(d=>d.id===o.id);if(a>=0)return D.navigate({currentNode:i,selectedIndex:a}),l("Restored navigation to moved node",null)}}}if(n&&!n.isDeleted){let o=R(n.id);return D.navigate({currentNode:n,selectedIndex:Zi(e.selectedIndex,o.length)}),l("Restored navigation to previous container",null)}if(e.parentNodeId){let o=t[e.parentNodeId];if(o&&!o.isDeleted){let i=R(o.id);return D.navigate({currentNode:o,selectedIndex:Zi(e.selectedIndex,i.length)}),l("Restored navigation to parent",null)}}let r=t[v().rootNodeId];return!r||r.isDeleted?s("Unable to restore navigation"):(D.navigate({currentNode:r,selectedIndex:0}),l("Restored navigation to root",null))};import{ulid as gc}from"ulid";var ts=null,We=()=>structuredClone(ts),Dt=e=>ts=e,ns=()=>{let{currentNode:e,selectedIndex:t}=v(),r=R(e.id)[t];return r?l("Resolved selected child",r):s("Target node not found")};var rs=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Q();if(c(r))return s("Unable to resolve user ID");let o=rt(t,e,n,r.value);return c(o)?o:l("Created pending move state",{id:gc(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value}})},os=e=>{Dt(e);let t=xt(e,!0);return c(t)?t:l("Node moved successfully",t.value)};function Dr(e){let t=ns();if(c(t))return t;let{currentNode:n,nodes:r}=v();if(!n.parentNodeId)return s("Missing parent node id");let o=r[n.parentNodeId];if(!o)return s("Missing parent node");let i=F(o.id),a=i.findIndex(({id:m})=>m===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 u=rs({id:t.value.id,parentId:d.id,position:{at:"end"}});return c(u)?u:os(u.value)}function Lr(e){let t=ns();if(c(t))return t;let{currentNode:n,selectedIndex:r}=v(),i=F(n.id)[r+e];if(!i)return s("Missing sibling node");let a=rs({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return c(a)?a:os(a.value)}import Cc from"node:os";import ds from"node:path";import{z as Lt}from"zod";import{accessSync as fc,copyFileSync as vc,existsSync as Nn,mkdirSync as is,readdirSync as ss,readFileSync as xc,renameSync as yc,rmSync as hc,statSync as as,unlinkSync as Ec,writeFileSync as Nc}from"node:fs";import mt from"node:path";var ce={writeToFile:(e,t)=>{try{let n=mt.dirname(e);Nn(n)||is(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Nc(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return xc(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 Nn(e)&&as(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await fc(e),!0}catch{return!1}},mkDir:e=>is(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=mt.parse(t);for(;;){let r=mt.join(t,e);try{if(Nn(r)&&as(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=mt.dirname(t)}return null},readFirstJSON(e){try{if(!ce.dirExists(e))return null;let t=ss(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=mt.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)?ss(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Ec(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{hc(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(mt.dirname(t)),!n?.overwrite&&Nn(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{yc(e,t)}catch(r){if(r?.code==="EXDEV"){vc(e,t),this.rmFile(e);return}throw r}}};var bc={userId:"",userName:"",preferredEditor:"",autoSync:!1},cs=Lt.object({preferredEditor:Lt.string().optional(),userName:Lt.string().optional(),userId:Lt.string().optional(),autoSync:Lt.boolean().optional()}).strict(),Ic="config.json",ls=()=>ds.join(Cc.homedir(),ue),Fr=()=>ds.join(ls(),Ic),Br=()=>{try{return ce.mkDir(ls()),l(`Ensured ~/${ue} exists`,null)}catch{return s(`Unable to create ~/${ue}`)}},Sc=e=>{let t;try{t=JSON.parse(e)}catch{return s(`Invalid ~/${ue}/config.json JSON`)}let n=cs.safeParse(t??{});return n.success?l("Parsed config",n.data):s(`Invalid ~/${ue}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},us=()=>{let e=Br();if(c(e))return s(e.message);let t=Fr(),n=ce.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{autoSync:!1,preferredEditor:"",userId:"",userName:""}):Sc(n)},ms=e=>{let t=Br();if(c(t))return s(t.message);let n=cs.safeParse(e);if(!n.success)return s(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Fr();try{return ce.writeToFile(r,JSON.stringify(n.data,null,2)+`
51
- `),l("Config written",null)}catch{return s(`Unable to write ~/${ue}/config.json`)}},Cn=e=>{let t=us();if(c(t))return s("Failed to read existing config");let n={...t.value,...e};return ms(n)},ps=()=>{let e=Fr(),t=Br();if(c(t))return s(`Unable to create ~/${ue}`);if(!(ce.readFile(e)!==null)){let u=ms(bc);if(c(u))throw new Error(`Unable to create ~/${ue}/config.json`)}let r=us();if(c(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:a,autoSync:d}=r.value;return!i||!a?s(`User name or ID not configured in ~/${ue}/config.json`):l("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:a,autoSync:d??!1})};import{spawnSync as Ac}from"node:child_process";import wc from"node:os";import gs from"node:path";import{ulid as Tc}from"ulid";function Rc(){let{preferredEditor:e}=fe(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Mc(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function fs(e){let t=gs.join(wc.tmpdir(),"epiq");ce.mkDir(t);let n=gs.join(t,Tc());ce.writeToFile(n,e??"");let r=Rc();for(let o of r){let i=Mc(o,n),a=Ac(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 u=d.replace(/\r?\n$/,"");return l("Successfully edited",u)}}return s("Unable to open editor")}import{monotonicFactory as Pc,ulid as bn}from"ulid";var In=Pc(),vs=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=In(),a=In(),d=In(),u=In(),m=lo();if(c(m))return m;let p=V(m.value,void 0);if(c(p))return p;let y=V(p.value,void 0);return c(y)?y:l("Created issue events",[{id:bn(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}},{id:bn(),userId:r,userName:o,action:"add.field",payload:{id:a,parent:i,name:"Description",val:"",rank:m.value}},{id:bn(),userId:r,userName:o,action:"add.field",payload:{id:d,parent:i,name:"Assignees",rank:p.value}},{id:bn(),userId:r,userName:o,action:"add.field",payload:{id:u,parent:i,name:"Tags",rank:y.value}}])};var xs=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};import Or from"node:fs";import kc from"node:path";var ys=async e=>{let t=kc.join(e,".gitignore"),n=Or.existsSync(t)?Or.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/logs/"],o=n.split(`
52
- `).map(u=>u.trim()),i=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(i.length===0)return l("Local epiq paths already ignored",!1);let d=["# [epiq]: local hydrated state is never committed",...i].join(`
50
+ `,dl=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(Tr(r),r);return[...n.values()].sort((r,o)=>{let i=Ki(r)-Ki(o);return i!==0?i:Tr(r).localeCompare(Tr(o))})},Mr=({sourceFile:e,targetFile:t})=>{let n=Gt(e);if(d(n))return s(n.message);let r=Gt(t);if(d(r))return s(r.message);let o=dl(r.value,n.value),i=al(o);return(hn.existsSync(t)?hn.readFileSync(t,"utf8"):"")===i?c("Event file already merged",!1):(hn.mkdirSync(Rr.dirname(t),{recursive:!0}),hn.writeFileSync(t,i,"utf8"),c("Merged event file",!0))},Pr=({repoRoot:e,stateBranchRoot:t})=>{let n=Li(t);if(d(n))return s(n.message);let r=Je(t),o=Je(e),i=!1;for(let a of n.value){let l=Rr.join(r,a),u=Rr.join(o,a),m=Mr({sourceFile:l,targetFile:u});if(d(m))return s(m.message);i=i||m.value}return c("Hydrated event files from state branch",i)};var zi=async(e=process.cwd())=>{let t=await qi({cwd:e,ensureUpstream:!1});if(d(t))return t;let{repoRoot:n,stateBranchRoot:r}=t.value,o=await yn({cwd:r,branch:O});if(d(o))return s(o.message);let i=Pr({repoRoot:n,stateBranchRoot:r});return d(i)?s(i.message):c("Synced state branch",{repoRoot:n,stateBranchRoot:r})},cl=({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=Ar({root:e,fileName:n}),o=Ar({root:t,fileName:n});return ll.existsSync(r)?Mr({sourceFile:r,targetFile:o}):c("Local own event file missing, nothing to merge",!1)},qi=async({cwd:e,ensureUpstream:t})=>{let n=await Bi(e);if(d(n))return s(n.message);let r=n.value,o=Pi(r);if(d(o))return s(o.message);let i=o.value,a=await br(r);if(d(a))return s(a.message);if(a.value)return s("Cannot sync while a git operation is in progress in the current repo");let l=await _i(r);if(d(l))return s(l.message);let u=await ji({repoRoot:r,stateBranchRoot:i,ensureUpstream:t});if(d(u))return s(u.message);let m=await br(i);if(d(m))return s(m.message);if(m.value)return s("Cannot sync while a git operation is in progress in the state branch");let p=Fi(r,i);return d(p)?s(p.message):c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:i,bootstrapped:u.value})},Vi=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=cl({repoRoot:e,stateBranchRoot:t,ownEventFileName:n});if(d(r))return s(r.message);let o=await Ii(t);if(d(o))return s(o.message);if(!r.value&&!o.value)return c("Own event file already up to date in state branch",{createdCommit:!1});let i=await Wi({stateBranchRoot:t,ownEventFileName:n});if(d(i))return s(i.message);let a=await Hi({repoRoot:e,stateBranchRoot:t});return d(a)?s(a.message):c("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:a.value})},Gi=async({cwd:e=process.cwd(),ownEventFileName:t})=>{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 n=await qi({cwd:e,ensureUpstream:!0});if(d(n))return n;let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,a=await Si(r);if(d(a))return s(a.message);if(a.value)return s("Cannot run :sync while the repository is in detached HEAD state");let l=!1,u,m=!1,p=!1,y=!1,N=await yn({cwd:o,branch:O});if(d(N))return s(N.message);m=N.value;let S=Pr({repoRoot:r,stateBranchRoot:o});if(d(S))return s(S.message);y=S.value;let A=await Vi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(d(A))return s(A.message);if(l=A.value.createdCommit,u=A.value.commitSha,l||i){let I=await wr(o),C=I;if(d(I)&&bi(I.message)){let T=await yn({cwd:o,branch:O});if(d(T))return s(T.message);let B=await Vi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(d(B))return s(B.message);B.value.createdCommit&&(l=!0,u=B.value.commitSha),C=await wr(o)}if(d(C))return s(C.message);p=C.value,logger.debug("[sync] pushed to state branch",p)}else logger.debug("[sync] no commit created, skipped push");if(l){let I=await L({args:["rev-parse","HEAD"],cwd:o});if(d(I))return s(I.message);u=I.value.stdout.trim()}return c("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,pulled:m,pushed:p,hydrated:y,bootstrapped:i})};var Xi=()=>{let{currentNode:e,selectedIndex:t}=v(),n=R(e.id)[t];return{currentNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:n?.parentNodeId??null,selectedIndex:t}},Yi=(e,t)=>Math.max(0,Math.min(e,Math.max(0,t-1))),Ji=e=>{let{nodes:t}=v(),n=t[e.currentNodeId];if(n&&!n.isDeleted&&e.selectedNodeId){let i=R(n.id).findIndex(a=>a.id===e.selectedNodeId);if(i>=0)return D.navigate({currentNode:n,selectedIndex:i}),c("Restored navigation",null)}if(e.selectedNodeId){let o=t[e.selectedNodeId];if(o&&!o.isDeleted&&o.parentNodeId){let i=t[o.parentNodeId];if(i&&!i.isDeleted){let a=R(i.id).findIndex(l=>l.id===o.id);if(a>=0)return D.navigate({currentNode:i,selectedIndex:a}),c("Restored navigation to moved node",null)}}}if(n&&!n.isDeleted){let o=R(n.id);return D.navigate({currentNode:n,selectedIndex:Yi(e.selectedIndex,o.length)}),c("Restored navigation to previous container",null)}if(e.parentNodeId){let o=t[e.parentNodeId];if(o&&!o.isDeleted){let i=R(o.id);return D.navigate({currentNode:o,selectedIndex:Yi(e.selectedIndex,i.length)}),c("Restored navigation to parent",null)}}let r=t[v().rootNodeId];return!r||r.isDeleted?s("Unable to restore navigation"):(D.navigate({currentNode:r,selectedIndex:0}),c("Restored navigation to root",null))};import{ulid as ul}from"ulid";var Zi=null,We=()=>structuredClone(Zi),Pt=e=>Zi=e,Qi=()=>{let{currentNode:e,selectedIndex:t}=v(),r=R(e.id)[t];return r?c("Resolved selected child",r):s("Target node not found")};var es=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Q();if(d(r))return s("Unable to resolve user ID");let o=tt(t,e,n,r.value);return d(o)?o:c("Created pending move state",{id:ul(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value}})},ts=e=>{Pt(e);let t=ft(e,!0);return d(t)?t:c("Node moved successfully",t.value)};function kr(e){let t=Qi();if(d(t))return t;let{currentNode:n,nodes:r}=v();if(!n.parentNodeId)return s("Missing parent node id");let o=r[n.parentNodeId];if(!o)return s("Missing parent node");let i=F(o.id),a=i.findIndex(({id:m})=>m===n.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 u=es({id:t.value.id,parentId:l.id,position:{at:"end"}});return d(u)?u:ts(u.value)}function Dr(e){let t=Qi();if(d(t))return t;let{currentNode:n,selectedIndex:r}=v(),i=F(n.id)[r+e];if(!i)return s("Missing sibling node");let a=es({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(a)?a:ts(a.value)}import hl from"node:os";import is from"node:path";import{z as kt}from"zod";import{accessSync as ml,copyFileSync as pl,existsSync as En,mkdirSync as ns,readdirSync as rs,readFileSync as gl,renameSync as fl,rmSync as vl,statSync as os,unlinkSync as xl,writeFileSync as yl}from"node:fs";import ct from"node:path";var de={writeToFile:(e,t)=>{try{let n=ct.dirname(e);En(n)||ns(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);yl(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return gl(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=de.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 En(e)&&os(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await ml(e),!0}catch{return!1}},mkDir:e=>ns(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=ct.parse(t);for(;;){let r=ct.join(t,e);try{if(En(r)&&os(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=ct.dirname(t)}return null},readFirstJSON(e){try{if(!de.dirExists(e))return null;let t=rs(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=ct.join(e,t);return de.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return de.dirExists(e)?rs(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{xl(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{vl(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(ct.dirname(t)),!n?.overwrite&&En(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{fl(e,t)}catch(r){if(r?.code==="EXDEV"){pl(e,t),this.rmFile(e);return}throw r}}};var El={userId:"",userName:"",preferredEditor:"",autoSync:!1},ss=kt.object({preferredEditor:kt.string().optional(),userName:kt.string().optional(),userId:kt.string().optional(),autoSync:kt.boolean().optional()}).strict(),Nl="config.json",as=()=>is.join(hl.homedir(),ce),Lr=()=>is.join(as(),Nl),Fr=()=>{try{return de.mkDir(as()),c(`Ensured ~/${ce} exists`,null)}catch{return s(`Unable to create ~/${ce}`)}},Cl=e=>{let t;try{t=JSON.parse(e)}catch{return s(`Invalid ~/${ce}/config.json JSON`)}let n=ss.safeParse(t??{});return n.success?c("Parsed config",n.data):s(`Invalid ~/${ce}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},ds=()=>{let e=Fr();if(d(e))return s(e.message);let t=Lr(),n=de.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{autoSync:!1,preferredEditor:"",userId:"",userName:""}):Cl(n)},ls=e=>{let t=Fr();if(d(t))return s(t.message);let n=ss.safeParse(e);if(!n.success)return s(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Lr();try{return de.writeToFile(r,JSON.stringify(n.data,null,2)+`
51
+ `),c("Config written",null)}catch{return s(`Unable to write ~/${ce}/config.json`)}},Nn=e=>{let t=ds();if(d(t))return s("Failed to read existing config");let n={...t.value,...e};return ls(n)},cs=()=>{let e=Lr(),t=Fr();if(d(t))return s(`Unable to create ~/${ce}`);if(!(de.readFile(e)!==null)){let u=ls(El);if(d(u))throw new Error(`Unable to create ~/${ce}/config.json`)}let r=ds();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:a,autoSync:l}=r.value;return!i||!a?s(`User name or ID not configured in ~/${ce}/config.json`):c("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:a,autoSync:l??!1})};import{spawnSync as bl}from"node:child_process";import Il from"node:os";import us from"node:path";import{ulid as Sl}from"ulid";function Al(){let{preferredEditor:e}=ge(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function wl(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function ms(e){let t=us.join(Il.tmpdir(),"epiq");de.mkDir(t);let n=us.join(t,Sl());de.writeToFile(n,e??"");let r=Al();for(let o of r){let i=wl(o,n),a=bl(i,{stdio:"inherit",shell:!0});if(!a.error&&a.status===0){let l=de.readFile(n);if(l==null)return s("Unable to read edited file");let u=l.replace(/\r?\n$/,"");return c("Successfully edited",u)}}return s("Unable to open editor")}import{monotonicFactory as Tl,ulid as Cn}from"ulid";var bn=Tl(),ps=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=bn(),a=bn(),l=bn(),u=bn(),m=lo();if(d(m))return m;let p=V(m.value,void 0);if(d(p))return p;let y=V(p.value,void 0);return d(y)?y:c("Created issue events",[{id:Cn(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}},{id:Cn(),userId:r,userName:o,action:"add.field",payload:{id:a,parent:i,name:"Description",val:"",rank:m.value}},{id:Cn(),userId:r,userName:o,action:"add.field",payload:{id:l,parent:i,name:"Assignees",rank:p.value}},{id:Cn(),userId:r,userName:o,action:"add.field",payload:{id:u,parent:i,name:"Tags",rank:y.value}}])};var gs=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};import Or from"node:fs";import Rl from"node:path";var fs=async e=>{let t=Rl.join(e,".gitignore"),n=Or.existsSync(t)?Or.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/logs/"],o=n.split(`
52
+ `).map(u=>u.trim()),i=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(i.length===0)return c("Local epiq paths already ignored",!1);let l=["# [epiq]: local hydrated state is never committed",...i].join(`
53
53
  `);return n=n.trimEnd()+`
54
54
 
55
- ${d}
56
- `,Or.writeFileSync(t,n,"utf8"),oe.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)};var hs=e=>Object.values(v().tags).find(t=>t.name===e),Es=e=>Object.values(v().contributors).find(t=>t.name===e),Ns=[{systemOnly:!0,intent:M.Move,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(c(e))return s("Unable to resolve user ID");let{modifier:t}=ne().commandMeta,n=()=>{let d=We();if(!d)return s("No pending move state");let u=d.payload.id;if(!v().nodes[u])return s("Moved node not found");let p=d.payload.parent,y=v().nodes[p];if(!y)return s("Move parent not found");let N=R(p).findIndex(S=>S.id===u);return N===-1?s("Moved node not found among rendered children"):(D.navigate({currentNode:y,selectedIndex:N}),l("Synchronized navigation to moved node",null))},r=d=>{if(c(d))return s(d.message);let u=n();return c(u)?s(u.message):l("Updated move preview",null)},{currentNode:o,selectedIndex:i}=v(),a=R(o.id)[i];if(!a)return w({mode:g.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=F(a.parentNodeId),u=d.findIndex(({id:A})=>A===a.id);if(u===-1)return s("Target not found among siblings");let m=d[u-1],p=d[u+1],y=p!=null?{at:"before",sibling:p.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"},N=rt(a.parentNodeId,a.id,y,e.value);if(c(N))return N;Dt({id:_(),action:"move.node",payload:{id:a.id,parent:a.parentNodeId,rank:N.value},...e.value}),w({mode:g.MOVE});let S=n();return c(S)?s(S.message):l("Move initialized",null)}if(t==="next")return w({mode:g.MOVE}),r(Lr(1));if(t==="previous")return w({mode:g.MOVE}),r(Lr(-1));if(t==="to-next")return w({mode:g.MOVE}),r(Dr(1));if(t==="to-previous")return w({mode:g.MOVE}),r(Dr(-1));if(t==="confirm"){w({mode:g.DEFAULT});let d=We();if(!d)return s("No pending move to confirm");let u=K(d);if(c(u))return u;let m=n();return c(m)?s(m.message):(Dt(null),l("Moved item",null))}return t==="cancel"?(Dt(null),w({mode:g.DEFAULT}),l("Cancelling move",null)):s("Invalid move modifier")}},{intent:M.Delete,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(c(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=R(t.id)[n];return r?K({id:_(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.Edit,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(c(e))return s("Unable to resolve user ID");let t=Te(v().breadCrumb,"TICKET");if(c(t))return s("Edit target must be an issue");let n=t.value;if(n.readonly)return s("Cannot edit readonly field");let{currentNode:r,selectedIndex:o}=v();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 u=fs(d);if(c(u))return s("Failed to edit field");let m=u.value;return m===d?l("No changes made",null):a.title==="Description"?K({id:_(),action:"edit.description",payload:{id:a.id,md:m},...e.value}):a.title==="Title"?K({id:_(),action:"edit.title",payload:{id:a.id,name:m},...e.value}):s(`Editing not supported for "${a.title}"`)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.Filter,mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ne().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(d=>z(f.FILTER).map(u=>u.split(n)[0]).includes(d))(r))return s("Invalid filter modifier");let a={target:r,operator:"=",value:t.trim()};return de(d=>({...d,filters:e==="clear"?[]:[...d.filters,a],mode:g.DEFAULT})),l("Viewing help",null)}},{intent:M.ViewHelp,mode:g.COMMAND_LINE,action:()=>(w({mode:g.HELP}),l("Viewing help",null))},{intent:M.CloseIssue,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(c(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=R(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!le(r))return s("Cannot close in this context");let o=v().nodes[be];if(!o)return s("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return s("Issue is already closed");let i=rt(o.id,r.id,{at:"end"},e.value);if(c(i))return i;let a=K({id:_(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:i.value},...e.value});return c(a)?a:l("Issue closed",null)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.ReopenIssue,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(c(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=R(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):$e(r.id,"TICKET");if(c(o))return s("Cannot reopen in this context");let i=o.value,a=v().nodes[be];if(!a)return s("Unable to locate closed swimlane");if(i.parentNodeId!==a.id)return s("Issue is not closed");if(!le(i))return s("Target node is not issue");let d=xs(i);if(!d)return s("Unable to resolve previous parent from issue history");if(d===a.id)return s("Previous parent resolves to closed swimlane");let u=v().nodes[d];if(!u)return s("Previous parent no longer exists");let m=rt(u.id,i.id,{at:"end"},e.value);if(c(m))return m;let p=K({id:_(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:m.value},...e.value});return c(p)?p:l("Issue reopened",null)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.SetUserName,mode:g.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:n}=fe(),r=sn()?.trim();if(!r)return s("No username provided");let o=r??n,i=e??_();if(!o||!i)return s("Unable to resolve user name or id");let a=Cn({userName:o,userId:i,preferredEditor:t??""});return c(a)?a:(nt({userName:o,userId:i}),w({mode:g.DEFAULT}),l(`Username set to "${r}"`,null))}},{intent:M.Init,mode:g.COMMAND_LINE,action:async()=>{let e=pi(process.cwd());if(c(e))return e;let t=await ys(process.cwd());if(c(t))return t;let n=$r();if(c(n))return n;let{rootNodeId:r,nodes:o}=v();return D.navigate({currentNode:o[r],selectedIndex:0}),w({hasProject:!0,mode:g.DEFAULT}),l("Project initialized",null)}},{intent:M.SetEditor,mode:g.COMMAND_LINE,action:()=>{let e=sn()?.trim();if(!e)return s("No editor provided");let t=Cn({preferredEditor:e});return c(t)?t:(nt({preferredEditor:e}),w({mode:g.DEFAULT}),l(`Editor configuration set to "${e}"`,null))}},{intent:M.SetAutoSync,mode:g.COMMAND_LINE,action:()=>{let e=ne().commandMeta.modifier;if(e!=="true"&&e!=="false")return s("Invalid response");let t=e.toLowerCase()==="true",n=Cn({autoSync:t});return c(n)?n:(nt({autoSync:t}),w({mode:g.DEFAULT}),l(`Auto synchronization set to "${t}"`,null))}},{intent:M.NewItem,mode:g.COMMAND_LINE,action:(e,t)=>{let n=Q();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}=v(),a=d=>{let u=K(d);if(c(u))return u;let m=b.getNode(u.value.result.id);if(!m)return s("Created node not found");if(!m.parentNodeId)return u;let p=b.getNode(m.parentNodeId);return p?(D.navigate({currentNode:p,selectedIndex:b.getSiblings(m.parentNodeId).findIndex(({id:y})=>y===m.id)}),u):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:d}=v(),u=b.getNode(d);if(!u)return s("Workspace not found");let m=ot(u.id,n.value);return c(m)?m:a({id:_(),action:"add.board",payload:{id:_(),name:t.inputString,parent:u.id,rank:m.value},...n.value})}if(t.modifier==="swimlane"){let d=Te(r,"BOARD");if(c(d))return s("Unable to add swimlane in this context");let u=ot(d.value.id,n.value);return c(u)?u:a({id:_(),action:"add.swimlane",payload:{id:_(),name:t.inputString,parent:d.value.id,rank:u.value},...n.value})}if(t.modifier==="issue"){let d=R(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&d?.context==="SWIMLANE"?d:(()=>{let C=Te(r,"SWIMLANE");return c(C)?null:C.value})();if(!u)return s("Unable to add issue in this context");let m=ot(u.id,n.value);if(c(m))return m;let p=vs({name:t.inputString,parent:u.id,rank:m.value,user:n.value});if(c(p))return p;let y=p.value,N=Eo(y);if(N.some(C=>c(C)))return s("Issue create failed: "+N.filter(c).map(C=>C.message).filter(Boolean).join(", "));let S=N[0];if(!S||c(S))return s("Issue creation failed");let I=y.find(C=>C.action==="add.issue")?.payload.id;return I?(D.navigate({currentNode:u,selectedIndex:b.getSiblings(u.id).findIndex(({id:C})=>C===I)}),l("Issue created",null)):s("Unable to determine ticket id")}return l("Success",null)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.SetView,mode:g.COMMAND_LINE,action:()=>{let{commandMeta:e}=ne();return e.validity===Re.Invalid?s("Invalid command "+Ee):(de(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),l("View set",null))},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.Rename,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(c(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=R(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=sn();return o?K({id:_(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.UntagTicket,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(c(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ne().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=hs(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid untag target");let a=$e(i.id,"TICKET");if(c(a))return s("Unable to untag issue in this context");let d=a.value,u=b.getFieldByTitle(d.id,"Tags");if(!u)return s("Unable to locate tags field");let m=R(u.id).find(p=>p.props?.value===o.id);return m?K({id:_(),action:"untag.issue",payload:{id:m.id,target:d.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.TagTicket,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(c(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ne().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=v(),a=R(i.id)[o];if(!a)return s("Invalid tag target");let d=$e(a.id,"TICKET");if(c(d))return s("Unable to tag issue in this context");let u=d.value,m=hs(r),p;if(m)p=m.id;else{let A=_(),I=K({id:_(),action:"create.tag",payload:{id:A,name:r},userId:e.value.userId,userName:e.value.userName});if(c(I))return I;p=I.value.result.id}let y=b.getFieldByTitle(u.id,"Tags");if(!y)return s("Unable to locate tags field");if(R(y.id).some(A=>A.props?.value===p))return s("Already tagged with that tag");let S=ot(y.id,e.value);return c(S)?S:K({id:_(),action:"tag.issue",payload:{id:_(),target:u.id,tagId:p,rank:S.value},...e.value})},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.AssignUserToTicket,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(c(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ne().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=v(),a=R(i.id)[o];if(!a)return s("Invalid assign target");let d=$e(a.id,"TICKET");if(c(d))return s("Unable to assign issue in this context");let u=d.value,m=Es(r),p;if(m)p=m.id;else{let A=_(),I=K({id:_(),action:"create.contributor",payload:{id:A,name:r},userId:e.value.userId,userName:e.value.userName});if(c(I))return I;p=I.value.result.id}let y=b.getFieldByTitle(u.id,"Assignees");if(!y)return s("Unable to locate assignees field");if(R(y.id).some(A=>A.props?.value===p))return s("Assignee already assigned");let S=ot(y.id,e.value);return c(S)?S:K({id:_(),action:"assign.issue",payload:{id:_(),target:u.id,contributor:p,rank:S.value},...e.value})},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.UnassignUserFromTicket,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(c(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ne().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=Es(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid unassign target");let a=$e(i.id,"TICKET");if(c(a))return s("Unable to unassign in this context");let d=a.value,u=b.getFieldByTitle(d.id,"Assignees");if(!u)return s("Unable to locate assignees field");let m=R(u.id).find(p=>p.props?.value===o.id);return m?K({id:_(),action:"unassign.issue",payload:{id:m.id,target:d.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${r}"`)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.Sync,mode:g.COMMAND_LINE,action:async()=>{let e=Qi();H(()=>""),w({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:n}=fe();if(!t)return s("Unable to resolve userId");if(!n)return s("Unable to resolve userName");let r=Ft()?$r():l("No pending default events",null);if(c(r))return s(`Unable to persist default events. ${r.message}`);let o=Q();if(c(o)||!o.value)return s("Unable to resolve event log path");let i=Jn(o.value);logger.debug("[sync-command] pending defaults",Ft());let a=await Ji({ownEventFileName:i});if(c(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 d=we(process.cwd());if(c(d))throw new Error(d.message);let u=Et(d.value);if(c(u))return s("Unable to load events");Ge(u.value);let m=es(e);return c(m)?m:l("Synced",!0)}},{intent:M.Peek,mode:g.COMMAND_LINE,action:async()=>{let e=Te(v().breadCrumb,"BOARD");if(c(e))return e;let t=we(process.cwd());if(c(t))throw new Error(t.message);let n=Et(t.value);if(c(n))return s(n.message);let r=n.value,{modifier:o}=ne().commandMeta,i;if(o==="now"){let N=Ur();if(c(N))return N;let S=Ge(r);return S.some(c)?s(S.map(A=>A.message).join(", ")):(w({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),l("Peeking now",!0))}if(o==="prev"){let N=v().eventLog.at(-2),S=or(N);if(S===null)return s("No previous event to peek");i=S}else if(o==="next"){let N=v().unappliedEvents.at(0),S=or(N);if(S===null)return s("No next event to peek");i=S}else{let N=en(o);if(!N)return s("Invalid peek date");i=N.getTime()}let a=e.value.id,{appliedEvents:d,unappliedEvents:u}=vo(r,i),m=Ur();if(c(m))return m;let p=Ge(d);if(p.some(c))return s(p.map(N=>N.message).join(", "));let y=v().nodes[a];return y?(D.navigate({currentNode:y,selectedIndex:0}),w({mode:g.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),l("Peeking ",!0)):s("Board did not exist at peek date")}},{intent:M.Export,mode:g.COMMAND_LINE,action:async()=>{let e=await ui();return c(e)?e:(w({mode:g.DEFAULT}),l("Export successful",!0))}},{intent:M.Exit,mode:g.COMMAND_LINE,action:async()=>(D.exit(),l("Exit successful",!0))}];var Dc=new Set(["peek","filter","view-help"]),pe=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ne();if(!t)return s("No command to confirm");if(!e&&n===Re.Invalid)return s("Invalid command");let i=Xo(t);if(Ko(),v().readOnly&&!Dc.has(i))return St({status:Ee.Fail,message:"Command not available in readonly state",value:null});let a=Ns.filter(u=>e||u.systemOnly!==!0).find(u=>u.intent===i);if(!a)return St({status:Ee.Fail,message:"Command not found",value:null});let d=await a.action(a,{command:t,inputString:o,modifier:r});return c(d)?St(d):(Vo({addToHistory:!e}),a.onSuccess?.(),St(d))};var Sn=[{intent:x.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(w({mode:g.COMMAND_LINE}),H(()=>"move cancel"),pe({isForceExecutedBySystem:!0}))},{intent:x.InitMove,mode:g.DEFAULT,description:"[m] move init/confirm",action:()=>(w({mode:g.COMMAND_LINE}),H(()=>"move start"),pe({isForceExecutedBySystem:!0}))},{intent:x.ConfirmMove,mode:g.MOVE,action:()=>(w({mode:g.COMMAND_LINE}),H(()=>"move confirm"),pe({isForceExecutedBySystem:!0}))}],An=[{intent:x.MovePreviousItem,mode:g.MOVE,action:()=>We()?(w({mode:g.COMMAND_LINE}),H(()=>"move previous"),pe({isForceExecutedBySystem:!0})):s("No pending move")},{intent:x.MoveNextItem,mode:g.MOVE,action:()=>We()?(w({mode:g.COMMAND_LINE}),H(()=>"move next"),pe({isForceExecutedBySystem:!0})):s("No pending move")}],Cs=[{intent:x.MoveToNextContainer,mode:g.MOVE,action:()=>We()?(w({mode:g.COMMAND_LINE}),H(()=>"move to-next"),pe({isForceExecutedBySystem:!0})):s("No pending move")},{intent:x.MoveToPreviousContainer,mode:g.MOVE,action:()=>We()?(w({mode:g.COMMAND_LINE}),H(()=>"move to-previous"),pe({isForceExecutedBySystem:!0})):s("No pending move")}];var bs={[P.WORKSPACE]:[...Sn,...An],[P.BOARD]:[...Sn,...An],[P.SWIMLANE]:[...Sn,...An,...Cs],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var Is=[{intent:x.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(w({mode:g.COMMAND_LINE}),H(()=>`${f.NEW} `),l("Adding new item",null))},{intent:x.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(w({mode:g.COMMAND_LINE}),H(()=>`${f.DELETE} `),l("Deleting item",null))},{intent:x.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(w({mode:g.COMMAND_LINE}),H(()=>""),l("Entering command line mode",null))},{intent:x.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(D.enterChildNode(),l("Entering context",null))},{intent:x.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(D.enterParentNode(),l("Exiting context",null))},{intent:x.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(D.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:x.NavNextItem,mode:g.DEFAULT,action:()=>(D.navigateToNextItem(),l("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(D.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:g.DEFAULT,action:()=>(D.navigateToNextContainer(),l("Navigating to next container",null))},{intent:x.Edit,mode:g.DEFAULT,action:()=>(w({mode:g.COMMAND_LINE}),H(()=>"edit"),pe(),l("Fired command",!0))},{intent:x.SetViewDense,mode:g.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(w({viewMode:"dense"}),l("View set",null))},{intent:x.SetViewWide,mode:g.DEFAULT,action:()=>(w({viewMode:"wide"}),l("View set",null))}];var Lc=500,Fc=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Ss=e=>{let t=Fc(e);t&&H(n=>(n+t).slice(0,Lc))};var As=[{intent:x.ViewHelp,mode:g.DEFAULT,action:()=>(w({mode:g.HELP}),l("Viewing help",null))},{intent:x.Exit,mode:g.HELP,action:()=>(w({mode:g.DEFAULT}),l("Exiting help",null))},{intent:x.Confirm,mode:g.COMMAND_LINE,action:()=>(pe(),l("Executing command",null))},{intent:x.MoveCursorLeft,mode:g.COMMAND_LINE,action:()=>(mr(-1),l("Moving cursor left",null))},{intent:x.MoveCursorRight,mode:g.COMMAND_LINE,action:()=>(mr(1),l("Moving cursor right",null))},{intent:x.MoveCursorLeftOfWord,mode:g.COMMAND_LINE,action:()=>(pr("left"),l("Moving cursor left of word",null))},{intent:x.MoveCursorRightOfWord,mode:g.COMMAND_LINE,action:()=>(pr("right"),l("Moving cursor right of word",null))},{intent:x.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(w({mode:g.DEFAULT}),l("Exiting command line",null))},{intent:x.AutoCompleteCommand,mode:g.COMMAND_LINE,action:()=>(H((e,{remainder:t})=>t?e+t:e),l("Auto-completing command",null))},{intent:x.CaptureInput,mode:g.COMMAND_LINE,action:(e,{sequence:t})=>(Ss(t??""),l("Capturing input",null))},{intent:x.EraseInput,mode:g.COMMAND_LINE,action:()=>(Wo(),l("Erasing input",null))},{intent:x.EraseInputWord,mode:g.COMMAND_LINE,action:()=>(Ho(),l("Erasing input word",null))},{intent:x.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(zo(),l("Getting last command from history",null))},{intent:x.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(qo(),l("Getting next command from history",null))}];import Bc from"chalk";var wn=": for command line",ws="q to exit",Ts=`${Bc.hex(E.accent)("m")} to confirm`,_r={[P.WORKSPACE]:[wn],[P.BOARD]:[wn],[P.BOARD+g.COMMAND_LINE]:[wn],[P.SWIMLANE]:[wn],[P.TICKET+g.HELP]:[ws],[P.SWIMLANE+g.HELP]:[ws],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+g.MOVE]:[Ts],[P.TICKET+g.MOVE]:[Ts]};var Tn=e=>e.trim().toLocaleLowerCase(),Oc=(e,t)=>{let n=b.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},Uc=e=>{let{tags:t}=v(),n=b.getFieldByTitle(e,"Tags");return n?F(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},$c=e=>{let{contributors:t}=v(),n=b.getFieldByTitle(e,"Assignees");return n?F(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},Rs=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return Tn(e.title??"").includes(n);case"description":return Tn(Oc(e.id,"Description")).includes(n);case"tag":return Uc(e.id).map(Tn).some(d=>d.includes(n));case"assignee":return $c(e.id).map(Tn).some(d=>d.includes(n));default:return!0}};function Ms(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(),l("Breadcrumb built",o))}var Ps=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 Rn,jr,Wr=new Set,ks=()=>{for(let e of Wr)e()},jc=e=>(Wr.add(e),()=>Wr.delete(e));function Ds(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 s("Unable to derive state, currentNode not found");let u=Ms(t,o,r);if(c(u))return logger.error(u.message),u;let m=u.value,{context:p}=d,y=_r[p+n]??_r[p]??[],N=[...Is,...bs[p]??[],...As],S=Ps(N),A=Wc(o,i),I=A[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,currentNode:d,breadCrumb:m,availableHints:y,availableActions:N,actionIndex:S,selectedNode:I,renderedChildrenIndex:A})}var v=()=>(Rn||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),Rn);function zn(e){jr=e;let t=qt(process.cwd());if(c(t))return s(t.message);let n=fn(t.value),r=!c(n),o={readOnly:!1,filters:[],tags:{},contributors:{},viewMode:"dense",mode:g.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProject:r},i=Ds(o);return c(i)?i:(Rn=i.value,ks(),l("State initialized",null))}function de(e){let t=v(),n=e(t),r=Ds(n);return c(r)?s(r.message??"Unable to update state"):(Rn=r.value,ks(),l("State updated",null))}var w=e=>de(t=>({...t,...e}));var $=()=>_c(jc,v,v),Wc=(e,t)=>{let n={};for(let r of Object.values(e))le(r)&&t.length>0&&!t.every(o=>Rs(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=>v()?.renderedChildrenIndex[e]??[],Ur=()=>jr?zn(jr):s("Cannot reset state: no initial workspace found");var D={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=R(t.id)[n];!r||t.context==="FIELD"||D.navigate({currentNode:r,selectedIndex:R(r.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=R(n.id),o=r.findIndex(({id:a})=>a===e.id),i=r.length===0?-1:o>=0?o:0;D.navigate({currentNode:n,selectedIndex:i})},navigateToNextItem:()=>Ls(1),navigateToPreviousItem:()=>Ls(-1),navigateToNextContainer:()=>Fs(1),navigateToPreviousContainer:()=>Fs(-1),navigate:({currentNode:e=v().currentNode,selectedIndex:t})=>{w({currentNodeId:e.id,selectedIndex:t})}},Ls=e=>{let t=v(),n=R(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;D.navigate({selectedIndex:o})},Fs=e=>{let{currentNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let i=R(o.id),a=i.findIndex(N=>N.id===t.id);if(a<0)return;let d=i.at(a+e)??i.at(0);if(!d)return;let u=R(d.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),y=u.length?p:-1;D.navigate({currentNode:d,selectedIndex:y})};var Fe="system",Be="ACTOR",Bt=Hc(),Oe=null;function Kc(){let e=Object.values(v().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=v().renderedChildrenIndex?.[n.id]??[];return{currentNode:n,selectedIndex:r.length>0?0:-1}}else return t?{currentNode:t,selectedIndex:0}:e?{currentNode:e,selectedIndex:0}:{currentNode:v().nodes[v().rootNodeId],selectedIndex:0}}function Vc(){let e=Kc();D.navigate(e)}function zc(){let e=Bt(),t=Bt(),n=Bt(),r=Bt(),o=Bt(),i=V(void 0,void 0);if(c(i))return i;let a=V(void 0,void 0);if(c(a))return a;let d=V(a.value,void 0);if(c(d))return d;let u=V(void 0,void 0);if(c(u))return u;let m=V(u.value,void 0);if(c(m))return m;let p=V(m.value,void 0);if(c(p))return p;let y=V(void 0,void 0);return c(y)?y:l("Created default events",[{id:Le(),userId:Fe,userName:Be,action:"init.workspace",payload:{id:e,name:"Workspace",rank:i.value}},{id:Le(),userId:Fe,userName:Be,action:"add.board",payload:{id:t,name:"Default",parent:e,rank:a.value}},{id:Le(),userId:Fe,userName:Be,action:"add.swimlane",payload:{id:n,name:"Todo",parent:t,rank:u.value}},{id:Le(),userId:Fe,userName:Be,action:"add.swimlane",payload:{id:r,name:"In progress",parent:t,rank:m.value}},{id:Le(),userId:Fe,userName:Be,action:"add.swimlane",payload:{id:o,name:"Done",parent:t,rank:p.value}},{id:Le(),userId:Fe,userName:Be,action:"add.board",payload:{id:Ht,name:"Closed",parent:e,rank:d.value}},{id:Le(),userId:Fe,userName:Be,action:"add.swimlane",payload:{id:be,name:"Closed",parent:Ht,rank:y.value}},{id:Le(),userId:Fe,userName:Be,action:"lock.node",payload:{id:Ht}},{id:Le(),userId:Fe,userName:Be,action:"lock.node",payload:{id:be}}])}function Ft(){return Oe!==null}function $r(){if(!Oe||Oe.length===0)return Oe=null,l("No pending default events to persist",null);let e=Oe.map(t=>Jt({event:t})).filter(c);return e.length>0?s([pt.bold.red("Persisting default events failed"),"",...e.map((t,n)=>`${pt.dim.gray(`${n+1}.`)} ${pt.dim(t.message)}`),`
55
+ ${l}
56
+ `,Or.writeFileSync(t,n,"utf8"),oe.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)};var vs=e=>Object.values(v().tags).find(t=>t.name===e),xs=e=>Object.values(v().contributors).find(t=>t.name===e),ys=[{systemOnly:!0,intent:M.Move,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{modifier:t}=ne().commandMeta,n=()=>{let l=We();if(!l)return s("No pending move state");let u=l.payload.id;if(!v().nodes[u])return s("Moved node not found");let p=l.payload.parent,y=v().nodes[p];if(!y)return s("Move parent not found");let N=R(p).findIndex(S=>S.id===u);return N===-1?s("Moved node not found among rendered children"):(D.navigate({currentNode:y,selectedIndex:N}),c("Synchronized navigation to moved node",null))},r=l=>{if(d(l))return s(l.message);let u=n();return d(u)?s(u.message):c("Updated move preview",null)},{currentNode:o,selectedIndex:i}=v(),a=R(o.id)[i];if(!a)return w({mode:g.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 l=F(a.parentNodeId),u=l.findIndex(({id:A})=>A===a.id);if(u===-1)return s("Target not found among siblings");let m=l[u-1],p=l[u+1],y=p!=null?{at:"before",sibling:p.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"},N=tt(a.parentNodeId,a.id,y,e.value);if(d(N))return N;Pt({id:_(),action:"move.node",payload:{id:a.id,parent:a.parentNodeId,rank:N.value},...e.value}),w({mode:g.MOVE});let S=n();return d(S)?s(S.message):c("Move initialized",null)}if(t==="next")return w({mode:g.MOVE}),r(Dr(1));if(t==="previous")return w({mode:g.MOVE}),r(Dr(-1));if(t==="to-next")return w({mode:g.MOVE}),r(kr(1));if(t==="to-previous")return w({mode:g.MOVE}),r(kr(-1));if(t==="confirm"){w({mode:g.DEFAULT});let l=We();if(!l)return s("No pending move to confirm");let u=K(l);if(d(u))return u;let m=n();return d(m)?s(m.message):(Pt(null),c("Moved item",null))}return t==="cancel"?(Pt(null),w({mode:g.DEFAULT}),c("Cancelling move",null)):s("Invalid move modifier")}},{intent:M.Delete,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=R(t.id)[n];return r?K({id:_(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.Edit,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let t=Ae(v().breadCrumb,"TICKET");if(d(t))return s("Edit target must be an issue");let n=t.value;if(n.readonly)return s("Cannot edit readonly field");let{currentNode:r,selectedIndex:o}=v();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 l=a.props.value;if(typeof l!="string")return s("Selected field is not editable text");let u=ms(l);if(d(u))return s("Failed to edit field");let m=u.value;return m===l?c("No changes made",null):a.title==="Description"?K({id:_(),action:"edit.description",payload:{id:a.id,md:m},...e.value}):a.title==="Title"?K({id:_(),action:"edit.title",payload:{id:a.id,name:m},...e.value}):s(`Editing not supported for "${a.title}"`)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.Filter,mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ne().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(l=>z(f.FILTER).map(u=>u.split(n)[0]).includes(l))(r))return s("Invalid filter modifier");let a={target:r,operator:"=",value:t.trim()};return ae(l=>({...l,filters:e==="clear"?[]:[...l.filters,a],mode:g.DEFAULT})),c("Viewing help",null)}},{intent:M.ViewHelp,mode:g.COMMAND_LINE,action:()=>(w({mode:g.HELP}),c("Viewing help",null))},{intent:M.CloseIssue,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=R(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!le(r))return s("Cannot close in this context");let o=v().nodes[Ce];if(!o)return s("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return s("Issue is already closed");let i=tt(o.id,r.id,{at:"end"},e.value);if(d(i))return i;let a=K({id:_(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:i.value},...e.value});return d(a)?a:c("Issue closed",null)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.ReopenIssue,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=R(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):Ue(r.id,"TICKET");if(d(o))return s("Cannot reopen in this context");let i=o.value,a=v().nodes[Ce];if(!a)return s("Unable to locate closed swimlane");if(i.parentNodeId!==a.id)return s("Issue is not closed");if(!le(i))return s("Target node is not issue");let l=gs(i);if(!l)return s("Unable to resolve previous parent from issue history");if(l===a.id)return s("Previous parent resolves to closed swimlane");let u=v().nodes[l];if(!u)return s("Previous parent no longer exists");let m=tt(u.id,i.id,{at:"end"},e.value);if(d(m))return m;let p=K({id:_(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:m.value},...e.value});return d(p)?p:c("Issue reopened",null)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.SetUserName,mode:g.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:n}=ge(),r=on()?.trim();if(!r)return s("No username provided");let o=r??n,i=e??_();if(!o||!i)return s("Unable to resolve user name or id");let a=Nn({userName:o,userId:i,preferredEditor:t??""});return d(a)?a:(et({userName:o,userId:i}),w({mode:g.DEFAULT}),c(`Username set to "${r}"`,null))}},{intent:M.Init,mode:g.COMMAND_LINE,action:async()=>{let e=mi(process.cwd());if(d(e))return e;let t=await fs(process.cwd());if(d(t))return t;let n=Ur();if(d(n))return n;let{rootNodeId:r,nodes:o}=v();return D.navigate({currentNode:o[r],selectedIndex:0}),w({hasProject:!0,mode:g.DEFAULT}),c("Project initialized",null)}},{intent:M.SetEditor,mode:g.COMMAND_LINE,action:()=>{let e=on()?.trim();if(!e)return s("No editor provided");let t=Nn({preferredEditor:e});return d(t)?t:(et({preferredEditor:e}),w({mode:g.DEFAULT}),c(`Editor configuration set to "${e}"`,null))}},{intent:M.SetAutoSync,mode:g.COMMAND_LINE,action:()=>{let e=ne().commandMeta.modifier;if(e!=="true"&&e!=="false")return s("Invalid response");let t=e.toLowerCase()==="true",n=Nn({autoSync:t});return d(n)?n:(et({autoSync:t}),w({mode:g.DEFAULT}),c(`Auto synchronization set to "${t}"`,null))}},{intent:M.NewItem,mode:g.COMMAND_LINE,action:(e,t)=>{let n=Q();if(d(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}=v(),a=l=>{let u=K(l);if(d(u))return u;let m=b.getNode(u.value.result.id);if(!m)return s("Created node not found");if(!m.parentNodeId)return u;let p=b.getNode(m.parentNodeId);return p?(D.navigate({currentNode:p,selectedIndex:b.getSiblings(m.parentNodeId).findIndex(({id:y})=>y===m.id)}),u):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:l}=v(),u=b.getNode(l);if(!u)return s("Workspace not found");let m=nt(u.id,n.value);return d(m)?m:a({id:_(),action:"add.board",payload:{id:_(),name:t.inputString,parent:u.id,rank:m.value},...n.value})}if(t.modifier==="swimlane"){let l=Ae(r,"BOARD");if(d(l))return s("Unable to add swimlane in this context");let u=nt(l.value.id,n.value);return d(u)?u:a({id:_(),action:"add.swimlane",payload:{id:_(),name:t.inputString,parent:l.value.id,rank:u.value},...n.value})}if(t.modifier==="issue"){let l=R(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&l?.context==="SWIMLANE"?l:(()=>{let C=Ae(r,"SWIMLANE");return d(C)?null:C.value})();if(!u)return s("Unable to add issue in this context");let m=nt(u.id,n.value);if(d(m))return m;let p=ps({name:t.inputString,parent:u.id,rank:m.value,user:n.value});if(d(p))return p;let y=p.value,N=ho(y);if(N.some(C=>d(C)))return s("Issue create failed: "+N.filter(d).map(C=>C.message).filter(Boolean).join(", "));let S=N[0];if(!S||d(S))return s("Issue creation failed");let I=y.find(C=>C.action==="add.issue")?.payload.id;return I?(D.navigate({currentNode:u,selectedIndex:b.getSiblings(u.id).findIndex(({id:C})=>C===I)}),c("Issue created",null)):s("Unable to determine ticket id")}return c("Success",null)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.SetView,mode:g.COMMAND_LINE,action:()=>{let{commandMeta:e}=ne();return e.validity===we.Invalid?s("Invalid command "+he):(ae(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),c("View set",null))},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.Rename,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=R(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=on();return o?K({id:_(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.UntagTicket,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ne().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=vs(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid untag target");let a=Ue(i.id,"TICKET");if(d(a))return s("Unable to untag issue in this context");let l=a.value,u=b.getFieldByTitle(l.id,"Tags");if(!u)return s("Unable to locate tags field");let m=R(u.id).find(p=>p.props?.value===o.id);return m?K({id:_(),action:"untag.issue",payload:{id:m.id,target:l.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.TagTicket,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ne().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=v(),a=R(i.id)[o];if(!a)return s("Invalid tag target");let l=Ue(a.id,"TICKET");if(d(l))return s("Unable to tag issue in this context");let u=l.value,m=vs(r),p;if(m)p=m.id;else{let A=_(),I=K({id:_(),action:"create.tag",payload:{id:A,name:r},userId:e.value.userId,userName:e.value.userName});if(d(I))return I;p=I.value.result.id}let y=b.getFieldByTitle(u.id,"Tags");if(!y)return s("Unable to locate tags field");if(R(y.id).some(A=>A.props?.value===p))return s("Already tagged with that tag");let S=nt(y.id,e.value);return d(S)?S:K({id:_(),action:"tag.issue",payload:{id:_(),target:u.id,tagId:p,rank:S.value},...e.value})},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.AssignUserToTicket,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ne().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=v(),a=R(i.id)[o];if(!a)return s("Invalid assign target");let l=Ue(a.id,"TICKET");if(d(l))return s("Unable to assign issue in this context");let u=l.value,m=xs(r),p;if(m)p=m.id;else{let A=_(),I=K({id:_(),action:"create.contributor",payload:{id:A,name:r},userId:e.value.userId,userName:e.value.userName});if(d(I))return I;p=I.value.result.id}let y=b.getFieldByTitle(u.id,"Assignees");if(!y)return s("Unable to locate assignees field");if(R(y.id).some(A=>A.props?.value===p))return s("Assignee already assigned");let S=nt(y.id,e.value);return d(S)?S:K({id:_(),action:"assign.issue",payload:{id:_(),target:u.id,contributor:p,rank:S.value},...e.value})},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.UnassignUserFromTicket,mode:g.COMMAND_LINE,action:()=>{let e=Q();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ne().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=xs(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid unassign target");let a=Ue(i.id,"TICKET");if(d(a))return s("Unable to unassign in this context");let l=a.value,u=b.getFieldByTitle(l.id,"Assignees");if(!u)return s("Unable to locate assignees field");let m=R(u.id).find(p=>p.props?.value===o.id);return m?K({id:_(),action:"unassign.issue",payload:{id:m.id,target:l.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${r}"`)},onSuccess:()=>w({mode:g.DEFAULT})},{intent:M.Sync,mode:g.COMMAND_LINE,action:async()=>{let e=Xi();j(()=>""),w({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:n}=ge();if(!t)return s("Unable to resolve userId");if(!n)return s("Unable to resolve userName");let r=Dt()?Ur():c("No pending default events",null);if(d(r))return s(`Unable to persist default events. ${r.message}`);let o=Q();if(d(o)||!o.value)return s("Unable to resolve event log path");let i=Xn(o.value);logger.debug("[sync-command] pending defaults",Dt());let a=await Gi({ownEventFileName:i});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=Se(process.cwd());if(d(l))throw new Error(l.message);let u=yt(l.value);if(d(u))return s("Unable to load events");qe(u.value);let m=Ji(e);return d(m)?m:c("Synced",!0)}},{intent:M.Peek,mode:g.COMMAND_LINE,action:async()=>{let e=Ae(v().breadCrumb,"BOARD");if(d(e))return e;let t=Se(process.cwd());if(d(t))throw new Error(t.message);let n=yt(t.value);if(d(n))return s(n.message);let r=n.value,{modifier:o}=ne().commandMeta,i;if(o==="now"){let N=Br();if(d(N))return N;let S=qe(r);return S.some(d)?s(S.map(A=>A.message).join(", ")):(w({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}if(o==="prev"){let N=v().eventLog.at(-2),S=rr(N);if(S===null)return s("No previous event to peek");i=S}else if(o==="next"){let N=v().unappliedEvents.at(0),S=rr(N);if(S===null)return s("No next event to peek");i=S}else{let N=Qt(o);if(!N)return s("Invalid peek date");i=N.getTime()}let a=e.value.id,{appliedEvents:l,unappliedEvents:u}=fo(r,i),m=Br();if(d(m))return m;let p=qe(l);if(p.some(d))return s(p.map(N=>N.message).join(", "));let y=v().nodes[a];return y?(D.navigate({currentNode:y,selectedIndex:0}),w({mode:g.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),c("Peeking ",!0)):s("Board did not exist at peek date")}},{intent:M.Export,mode:g.COMMAND_LINE,action:async()=>{let e=await ci();return d(e)?e:(w({mode:g.DEFAULT}),c("Export successful",!0))}},{intent:M.Exit,mode:g.COMMAND_LINE,action:async()=>(D.exit(),c("Exit successful",!0))}];var Ml=new Set(["peek","filter","view-help"]),me=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ne();if(!t)return s("No command to confirm");if(!e&&n===we.Invalid)return s("Invalid command");let i=Yo(t);if(jo(),v().readOnly&&!Ml.has(i))return bt({status:he.Fail,message:"Command not available in readonly state",value:null});let a=ys.filter(u=>e||u.systemOnly!==!0).find(u=>u.intent===i);if(!a)return bt({status:he.Fail,message:"Command not found",value:null});let l=await a.action(a,{command:t,inputString:o,modifier:r});return d(l)?bt(l):(Ko({addToHistory:!e}),a.onSuccess?.(),bt(l))};var In=[{intent:x.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(w({mode:g.COMMAND_LINE}),j(()=>"move cancel"),me({isForceExecutedBySystem:!0}))},{intent:x.InitMove,mode:g.DEFAULT,description:"[m] move init/confirm",action:()=>(w({mode:g.COMMAND_LINE}),j(()=>"move start"),me({isForceExecutedBySystem:!0}))},{intent:x.ConfirmMove,mode:g.MOVE,action:()=>(w({mode:g.COMMAND_LINE}),j(()=>"move confirm"),me({isForceExecutedBySystem:!0}))}],Sn=[{intent:x.MovePreviousItem,mode:g.MOVE,action:()=>We()?(w({mode:g.COMMAND_LINE}),j(()=>"move previous"),me({isForceExecutedBySystem:!0})):s("No pending move")},{intent:x.MoveNextItem,mode:g.MOVE,action:()=>We()?(w({mode:g.COMMAND_LINE}),j(()=>"move next"),me({isForceExecutedBySystem:!0})):s("No pending move")}],hs=[{intent:x.MoveToNextContainer,mode:g.MOVE,action:()=>We()?(w({mode:g.COMMAND_LINE}),j(()=>"move to-next"),me({isForceExecutedBySystem:!0})):s("No pending move")},{intent:x.MoveToPreviousContainer,mode:g.MOVE,action:()=>We()?(w({mode:g.COMMAND_LINE}),j(()=>"move to-previous"),me({isForceExecutedBySystem:!0})):s("No pending move")}];var Es={[P.WORKSPACE]:[...In,...Sn],[P.BOARD]:[...In,...Sn],[P.SWIMLANE]:[...In,...Sn,...hs],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var Ns=[{intent:x.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(w({mode:g.COMMAND_LINE}),j(()=>`${f.NEW} `),c("Adding new item",null))},{intent:x.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(w({mode:g.COMMAND_LINE}),j(()=>`${f.DELETE} `),c("Deleting item",null))},{intent:x.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(w({mode:g.COMMAND_LINE}),j(()=>""),c("Entering command line mode",null))},{intent:x.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(D.enterChildNode(),c("Entering context",null))},{intent:x.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(D.enterParentNode(),c("Exiting context",null))},{intent:x.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(D.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:x.NavNextItem,mode:g.DEFAULT,action:()=>(D.navigateToNextItem(),c("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(D.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:g.DEFAULT,action:()=>(D.navigateToNextContainer(),c("Navigating to next container",null))},{intent:x.Edit,mode:g.DEFAULT,action:()=>(w({mode:g.COMMAND_LINE}),j(()=>"edit"),me(),c("Fired command",!0))},{intent:x.SetViewDense,mode:g.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(w({viewMode:"dense"}),c("View set",null))},{intent:x.SetViewWide,mode:g.DEFAULT,action:()=>(w({viewMode:"wide"}),c("View set",null))}];var Pl=500,kl=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Cs=e=>{let t=kl(e);t&&j(n=>(n+t).slice(0,Pl))};var bs=[{intent:x.ViewHelp,mode:g.DEFAULT,action:()=>(w({mode:g.HELP}),c("Viewing help",null))},{intent:x.Exit,mode:g.HELP,action:()=>(w({mode:g.DEFAULT}),c("Exiting help",null))},{intent:x.Confirm,mode:g.COMMAND_LINE,action:()=>(me(),c("Executing command",null))},{intent:x.MoveCursorLeft,mode:g.COMMAND_LINE,action:()=>(ur(-1),c("Moving cursor left",null))},{intent:x.MoveCursorRight,mode:g.COMMAND_LINE,action:()=>(ur(1),c("Moving cursor right",null))},{intent:x.MoveCursorLeftOfWord,mode:g.COMMAND_LINE,action:()=>(mr("left"),c("Moving cursor left of word",null))},{intent:x.MoveCursorRightOfWord,mode:g.COMMAND_LINE,action:()=>(mr("right"),c("Moving cursor right of word",null))},{intent:x.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(w({mode:g.DEFAULT}),c("Exiting command line",null))},{intent:x.AutoCompleteCommand,mode:g.COMMAND_LINE,action:()=>(j((e,{remainder:t})=>t?e+t:e),c("Auto-completing command",null))},{intent:x.CaptureInput,mode:g.COMMAND_LINE,action:(e,{sequence:t})=>(Cs(t??""),c("Capturing input",null))},{intent:x.EraseInput,mode:g.COMMAND_LINE,action:()=>(Wo(),c("Erasing input",null))},{intent:x.EraseInputWord,mode:g.COMMAND_LINE,action:()=>(Ho(),c("Erasing input word",null))},{intent:x.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(Vo(),c("Getting last command from history",null))},{intent:x.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(zo(),c("Getting next command from history",null))}];import Dl from"chalk";var An=": for command line",Is="q to exit",Ss=`${Dl.hex(E.accent)("m")} to confirm`,$r={[P.WORKSPACE]:[An],[P.BOARD]:[An],[P.BOARD+g.COMMAND_LINE]:[An],[P.SWIMLANE]:[An],[P.TICKET+g.HELP]:[Is],[P.SWIMLANE+g.HELP]:[Is],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+g.MOVE]:[Ss],[P.TICKET+g.MOVE]:[Ss]};var wn=e=>e.trim().toLocaleLowerCase(),Ll=(e,t)=>{let n=b.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},Fl=e=>{let{tags:t}=v(),n=b.getFieldByTitle(e,"Tags");return n?F(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},Ol=e=>{let{contributors:t}=v(),n=b.getFieldByTitle(e,"Assignees");return n?F(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},As=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return wn(e.title??"").includes(n);case"description":return wn(Ll(e.id,"Description")).includes(n);case"tag":return Fl(e.id).map(wn).some(l=>l.includes(n));case"assignee":return Ol(e.id).map(wn).some(l=>l.includes(n));default:return!0}};function ws(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(),c("Breadcrumb built",o))}var Ts=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var Tn,_r,Wr=new Set,Rs=()=>{for(let e of Wr)e()},Ul=e=>(Wr.add(e),()=>Wr.delete(e));function Ms(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 l=o[t];if(!l)return s("Unable to derive state, currentNode not found");let u=ws(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,y=$r[p+n]??$r[p]??[],N=[...Ns,...Es[p]??[],...bs],S=Ts(N),A=$l(o,i),I=A[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,currentNode:l,breadCrumb:m,availableHints:y,availableActions:N,actionIndex:S,selectedNode:I,renderedChildrenIndex:A})}var v=()=>(Tn||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),Tn);function Vn(e){_r=e;let t=zt(process.cwd()),n=!1;if(!d(t)){let i=gn(t.value);if(d(i))return s(i.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},viewMode:"dense",mode:g.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProject:n},o=Ms(r);return d(o)?o:(Tn=o.value,Rs(),c("State initialized",null))}function ae(e){let t=v(),n=e(t),r=Ms(n);return d(r)?s(r.message??"Unable to update state"):(Tn=r.value,Rs(),c("State updated",null))}var w=e=>ae(t=>({...t,...e}));var $=()=>Bl(Ul,v,v),$l=(e,t)=>{let n={};for(let r of Object.values(e))le(r)&&t.length>0&&!t.every(o=>As(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],l=e[i.id];return!a||!l?0:a.rank.localeCompare(l.rank)});return n},R=e=>v()?.renderedChildrenIndex[e]??[],Br=()=>_r?Vn(_r):s("Cannot reset state: no initial workspace found");var D={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=R(t.id)[n];!r||t.context==="FIELD"||D.navigate({currentNode:r,selectedIndex:R(r.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=R(n.id),o=r.findIndex(({id:a})=>a===e.id),i=r.length===0?-1:o>=0?o:0;D.navigate({currentNode:n,selectedIndex:i})},navigateToNextItem:()=>Ps(1),navigateToPreviousItem:()=>Ps(-1),navigateToNextContainer:()=>ks(1),navigateToPreviousContainer:()=>ks(-1),navigate:({currentNode:e=v().currentNode,selectedIndex:t})=>{w({currentNodeId:e.id,selectedIndex:t})}},Ps=e=>{let t=v(),n=R(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;D.navigate({selectedIndex:o})},ks=e=>{let{currentNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let i=R(o.id),a=i.findIndex(N=>N.id===t.id);if(a<0)return;let l=i.at(a+e)??i.at(0);if(!l)return;let u=R(l.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),y=u.length?p:-1;D.navigate({currentNode:l,selectedIndex:y})};var De="system",Le="ACTOR",Lt=_l(),Fe=null;function Wl(){let e=Object.values(v().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=v().renderedChildrenIndex?.[n.id]??[];return{currentNode:n,selectedIndex:r.length>0?0:-1}}else return t?{currentNode:t,selectedIndex:0}:e?{currentNode:e,selectedIndex:0}:{currentNode:v().nodes[v().rootNodeId],selectedIndex:0}}function Hl(){let e=Wl();D.navigate(e)}function jl(){let e=Lt(),t=Lt(),n=Lt(),r=Lt(),o=Lt(),i=V(void 0,void 0);if(d(i))return i;let a=V(void 0,void 0);if(d(a))return a;let l=V(a.value,void 0);if(d(l))return l;let u=V(void 0,void 0);if(d(u))return u;let m=V(u.value,void 0);if(d(m))return m;let p=V(m.value,void 0);if(d(p))return p;let y=V(void 0,void 0);return d(y)?y:c("Created default events",[{id:ke(),userId:De,userName:Le,action:"init.workspace",payload:{id:e,name:"Workspace",rank:i.value}},{id:ke(),userId:De,userName:Le,action:"add.board",payload:{id:t,name:"Default",parent:e,rank:a.value}},{id:ke(),userId:De,userName:Le,action:"add.swimlane",payload:{id:n,name:"Todo",parent:t,rank:u.value}},{id:ke(),userId:De,userName:Le,action:"add.swimlane",payload:{id:r,name:"In progress",parent:t,rank:m.value}},{id:ke(),userId:De,userName:Le,action:"add.swimlane",payload:{id:o,name:"Done",parent:t,rank:p.value}},{id:ke(),userId:De,userName:Le,action:"add.board",payload:{id:Wt,name:"Closed",parent:e,rank:l.value}},{id:ke(),userId:De,userName:Le,action:"add.swimlane",payload:{id:Ce,name:"Closed",parent:Wt,rank:y.value}},{id:ke(),userId:De,userName:Le,action:"lock.node",payload:{id:Wt}},{id:ke(),userId:De,userName:Le,action:"lock.node",payload:{id:Ce}}])}function Dt(){return Fe!==null}function Ur(){if(!Fe||Fe.length===0)return Fe=null,c("No pending default events to persist",null);let e=Fe.map(t=>Xt({event:t})).filter(d);return e.length>0?s([ut.bold.red("Persisting default events failed"),"",...e.map((t,n)=>`${ut.dim.gray(`${n+1}.`)} ${ut.dim(t.message)}`),`
57
57
  `].join(`
58
- `)):(Oe=null,l("Persisted pending default events",null))}function Bs(e){let t;if(e.some(r=>r.action==="init.workspace"))Oe=null,t=Ge(e);else{let r=zc();if(c(r))return r;Oe=r.value,t=Ge([...Oe])}let n=t.filter(c);return n.length>0?s([pt.bold.red("Materializing failed"),"",...n.map((r,o)=>`${pt.dim.gray(`${o+1}.`)} ${pt.dim(r.message)}`),`
58
+ `)):(Fe=null,c("Persisted pending default events",null))}function Ds(e){let t;if(e.some(r=>r.action==="init.workspace"))Fe=null,t=qe(e);else{let r=jl();if(d(r))return r;Fe=r.value,t=qe([...Fe])}let n=t.filter(d);return n.length>0?s([ut.bold.red("Materializing failed"),"",...n.map((r,o)=>`${ut.dim.gray(`${o+1}.`)} ${ut.dim(r.message)}`),`
59
59
  `].join(`
60
60
 
61
61
  See complete log:
62
62
 
63
63
  `)+e.map(r=>JSON.stringify(r)).join(`
64
- `)):(Vc(),l("State booted successfully",null))}var nn=()=>{let e=fe(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},To=()=>!Ft();import{Box as ll}from"ink";import Vr from"react";import Ut from"chalk";import{Box as Hr,Text as Os}from"ink";import Ot,{useEffect as qc,useMemo as Gc,useState as Yc}from"react";var Us=Ut.gray,Xc=Ut.inverse,Jc=Ut.inverse.gray,Zc={hint:"",hints:[],overlap:0,remainder:""},_s=({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}},Qc=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=X(t);return{bg:r=>Ut.bgHex(n).black(r),bgCursor:r=>Ut.bgHex(n).inverse.black(r)}}return ar(t)},el=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=_s({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}},$s=()=>({value:J.value,cursorPosition:J.cursorPosition,commandIsPending:J.commandIsPending,autoCompletion:J.commandMeta.autoCompletion??Zc,infoMessage:J.commandMeta.infoMessage,validationStatus:J.commandMeta.validity,command:J.commandMeta.command,inputString:J.commandMeta.inputString,modifier:J.commandMeta.modifier}),tl=(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,js=({width:e})=>{let[t,n]=Yc($s());qc(()=>{let y=()=>{let S=$s();n(A=>tl(A,S)?A:S)},N=jo(y);return y(),()=>{N()}},[]);let{value:r,cursorPosition:o,infoMessage:i,commandIsPending:a,autoCompletion:d,command:u,modifier:m}=t,p=Gc(()=>{let y=Math.max(0,Math.min(o,r.length)),N=_s({value:r,command:u}),S=el({value:r,command:u,modifier:m}),A=u?ar(u):null,I=Qc({command:u,modifier:m}),C=(se,ae)=>{let jn=N&&ae>=N.start&&ae<N.end,Wn=S&&ae>=S.start&&ae<S.end;return jn&&A?A.fg(se):Wn&&I?I.bg(se):se},T=(se,ae)=>{let jn=N&&ae>=N.start&&ae<N.end,Wn=S&&ae>=S.start&&ae<S.end;return jn&&A?A.fgCursor(se):Wn&&I?I.bgCursor(se):Xc(se)},O=r.slice(0,y),ie=r[y]??" ",Ue=y<r.length?r.slice(y+1):"",sa=Array.from(O).map((se,ae)=>C(se,ae)).join(""),Zr=T(ie,y),Qr=Array.from(Ue).map((se,ae)=>C(se,y+1+ae)).join("");if(d.hint){let se=d.hint[d.overlap]??ie;Zr=Jc(se),Qr=Us(d.remainder.slice(1)+Ue)}return Us(":")+sa+Zr+Qr},[r,o,d,u,m]);return Ot.createElement(Hr,{flexDirection:"column",justifyContent:"flex-start"},Ot.createElement(Hr,{flexDirection:"column",paddingX:1,borderColor:E.secondary,borderStyle:"round",width:e},Ot.createElement(Hr,null,Ot.createElement(Os,null,p),i&&Ot.createElement(Os,{wrap:"truncate",color:a?E.red:E.secondary2},` ${i} `))))};import Ws from"chalk";import{Box as nl,Text as Kr}from"ink";import Mn,{useEffect as rl,useState as ol}from"react";var il=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Hs=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)}},sl=({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)}`},al=(e,t,n)=>{let r=Hs(e),o=Hs(t);return sl({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},dl=(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 al(i,a,o)},cl=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),Ks=({width:e,availableHints:t})=>{let{syncStatus:{status:n,msg:r}}=$(),[o,i]=ol(0);rl(()=>{if(n!=="syncing"){i(0);return}let C=setInterval(()=>{i(T=>T+1)},50);return()=>clearInterval(C)},[n]);let a=[],d=0;for(let C of t){let O=(a.length>0?" | ":"").length+C.length;if(d+O>e-4)break;a.push(C),d+=O}let u=n!="synced"?r??a.join(" | "):a.join(" | "),m=Math.max(0,e-2),p=n==="syncing"?dl(il,(Math.sin(o*.12)+1)/2):E.secondary,y=Ws.hex(p??"fff"),N=Ws.hex(E.secondary2),S=y(`\u256D${"\u2500".repeat(m)}\u256E`),A=y(`\u2570${"\u2500".repeat(m)}\u256F`),I=`${y("\u2502")}${N(cl(` ${u} `,m))}${y("\u2502")}`;return Mn.createElement(nl,{flexDirection:"column",width:e},Mn.createElement(Kr,null,S),Mn.createElement(Kr,null,I),Mn.createElement(Kr,null,A))};var Pn=({width:e,mode:t,availableHints:n})=>{let r=$(),o=[],i=0;for(let a of n){let u=(o.length>0?" | ":"").length+a.length;if(i+u>e+2)break;o.push(a),i+=u}return Vr.createElement(ll,null,t===g.COMMAND_LINE&&r.syncStatus.status!=="syncing"?Vr.createElement(js,{width:e}):Vr.createElement(Ks,{width:e,mode:t,availableHints:n}))};import{Box as gt,Text as Vs}from"ink";import He from"react";var zs=({width:e})=>{let t=[...v().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"]),He.createElement(gt,{flexDirection:"column",marginTop:3,borderColor:E.secondary,borderStyle:"round",width:e,minHeight:19},He.createElement(gt,{flexDirection:"column",width:e},v().mode===g.HELP?t.map(([n,r],o)=>He.createElement(gt,{paddingLeft:1,key:o,flexDirection:"row"},He.createElement(gt,{key:o,flexDirection:"row",paddingBottom:o?0:1},He.createElement(gt,{width:20,justifyContent:"flex-end"},He.createElement(Vs,{color:o?E.accent:E.secondary},n)),He.createElement(gt,{flexGrow:1,width:40,paddingLeft:2},He.createElement(Vs,{color:o?E.primary:E.secondary},r))))):null))};import ul from"chalk";import{Box as kn,Text as Ke}from"ink";import ge from"react";var qs=({width:e,height:t})=>ge.createElement(kn,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:E.secondary,rowGap:1},ge.createElement(Ke,{color:E.accent,bold:!0},"Initialize project"),ge.createElement(Ke,null,`This folder is not an ${ul.hex(E.accent)("epiq")} project yet.`),ge.createElement(Ke,{color:E.primary},"To start tracking issues here, we need to initialize a new"," ",ge.createElement(Ke,{color:E.primary,backgroundColor:E.secondary}," .epiq/project.json ")," ","file in this repository."),ge.createElement(kn,{marginTop:1,flexDirection:"column"},ge.createElement(kn,null,ge.createElement(Ke,{color:E.accent}," "),ge.createElement(Ke,{color:E.primary},"Type "),ge.createElement(Ke,{backgroundColor:E.secondary}," :init "))),ge.createElement(kn,{marginTop:1},ge.createElement(Ke,{color:E.secondary2},"(This will create the local epiq project files)")));import{Box as $t,Text as ye}from"ink";import W from"react";var Dn=({isDone:e,command:t,value:n})=>W.createElement($t,null,W.createElement(ye,{color:E.accent,dimColor:e},e?" \u2714 ":" "),W.createElement(ye,{dimColor:e},"Type "),W.createElement(ye,{backgroundColor:E.secondary,dimColor:e}," "+t+" "),n&&W.createElement(W.Fragment,null,W.createElement(ye,{dimColor:e}," "),W.createElement(ye,{color:E.secondary,dimColor:e},"<"+n+">")));function zr({width:e,height:t,hasUserName:n,hasPreferredEditor:r,userName:o,preferredEditor:i}){let a=n&&r,d=n?r?null:":config:editor":":config:username";return W.createElement($t,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:E.secondary,rowGap:1},W.createElement(ye,{color:E.accent,bold:!0},"Welcome! \u{1F539}"),W.createElement(ye,null,"Lets get you started - its a breeze."),W.createElement(ye,{color:E.secondary2},"And remember, you can always get help with"," ",W.createElement(ye,{color:E.accent},":help"),"."),!a&&W.createElement(ye,{color:E.secondary2},d===":config:username"?"First, choose your username.":"Nice. One more step."),W.createElement($t,{flexDirection:"column"},n&&W.createElement($t,{marginBottom:1},W.createElement(Dn,{isDone:!0,command:":config:username",value:o})),!n&&W.createElement(Dn,{isDone:!1,command:":config:username"}),n&&!r&&W.createElement(Dn,{isDone:!1,command:":config:editor"}),a&&W.createElement($t,null,W.createElement(Dn,{isDone:!0,command:":config:editor",value:i}))))}import Zs from"chalk";import{Box as Fn,Text as Ve}from"ink";import Z from"react";import{Box as qr,Text as ml}from"ink";import ft from"react";var pl=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",Gs=({width:e})=>{let{breadCrumb:t,currentNode:n,selectedIndex:r,viewMode:o}=v(),i=F(n.id)[r],a=$e(i?.id??n.id,"TICKET"),d=Ne(a)?a.value:void 0,u=d?.id?F(d.id):[],m=I=>{let C=u.find(T=>T.title===I);return C?F(C.id).map(T=>typeof T.props?.value=="string"?T.props.value:"").filter(T=>!!T):[]},p=m("Tags"),y=m("Assignees"),N=d?.parentNodeId?!er(n.id,d?.parentNodeId)&&o==="dense":!1,S=t.map((I,C)=>{let T=C===t.length-1,O=F(I.id),ie=T?O?.[r]?.title:void 0;return`${C?" / ":""}${I.title??""}${ie?` \u25B8 ${ie}`:""}`}).join(""),A=pl(S,e);return ft.createElement(qr,null,ft.createElement(ml,{color:E.secondary2},A),N?p.map(I=>ft.createElement(qr,{key:I,paddingLeft:2},ft.createElement(ct,{id:I}))):null,N?y.map(I=>ft.createElement(qr,{key:I,paddingLeft:2},ft.createElement(dt,{id:I}))):null)};import{Box as gl,Text as Ys}from"ink";import Ln from"react";var fl=({filters:e})=>Ln.createElement(gl,{columnGap:1},Ln.createElement(Ys,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Ln.createElement(Ys,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Xs=Ln.memo(fl);var Js="0.4.7";function Bn({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o}=$(),{userName:i,preferredEditor:a}=fe(),d=40,u=process.stdout.columns-d-8,m=r.at(-1)?.id,p=rn(m??""),y=Ne(p)?Po(p.value):"INVALID DATE";return Z.createElement(Fn,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?Z.createElement(Ve,null," "):Z.createElement(Fn,{paddingLeft:1},e.length>0?Z.createElement(Xs,{filters:e}):Z.createElement(Gs,{width:u})),n==="live"?Z.createElement(Fn,{columnGap:1,paddingRight:2,"max-width":d,overflow:"hidden",justifyContent:"flex-end"},Z.createElement(Ve,{dimColor:!0,color:E.secondary2},Js+" "),Z.createElement(Qs,{icon:"@",value:i}),Z.createElement(Qs,{icon:"\u276F",value:a})):"",n==="peek"?Z.createElement(Fn,{paddingLeft:1},Z.createElement(Ve,{backgroundColor:E.yellow}," Readonly "),Z.createElement(Ve,{color:E.yellow}," "+o.length+" edits ago at "),Z.createElement(Ve,{backgroundColor:E.yellow,color:E.accent}," "+y+" "),Z.createElement(Ve,{color:E.yellow},". Resume with "),Z.createElement(Ve,{backgroundColor:E.yellow}," :peek now ")):"")}function Qs({icon:e,value:t}){return Z.createElement(Ve,null,Zs.dim(e)+Zs.hex(E.accent)(` ${t??"-"} `))}import{Box as vl,Text as xl}from"ink";import _t from"react";import{Box as On,Text as Gr}from"ink";import ze from"react";function Yr(){let e=$(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,a=t?.id?R(t?.id):[];return ze.createElement(On,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:E.secondary,width:i},ze.createElement(On,{padding:1,paddingTop:0,paddingBottom:0},ze.createElement(Gr,null,"Select a board:")),ze.createElement(On,{padding:1,flexDirection:"column"},a.map((d,u)=>{let m=e.currentNode.context==="WORKSPACE"&&e.selectedIndex===u,y=R(d.id).flatMap(({id:N})=>F(N)).length;return ze.createElement(On,{key:d.id??u},ze.createElement(Gr,{color:m?E.accent:E.secondary2},ze.createElement(re,{isSelected:m})),ze.createElement(Gr,{color:m?E.accent:E.secondary2},d.title," (",y," issues)",d.readonly?" \u{1F512}":""))})))}var yl=({currentNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:d}=$(),u=n.find(({context:N})=>N==="BOARD"),y=i-1-3;return _t.createElement(vl,{flexDirection:"row"},e.context==="WORKSPACE"?_t.createElement(Yr,null):u?_t.createElement(pn,{height:y,width:a,swimlanes:(d[u.id]??[]).filter(N=>N!==void 0&&tt(N)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):_t.createElement(xl,null))},ea=_t.memo(yl);function Xr({width:e,height:t}){let n=$(),r=n.filters;if(n.mode===g.HELP)return G.createElement(et,{flexDirection:"column"},G.createElement(zs,{width:e}));let{isSetup:o,hasPreferredEditor:i,hasUserName:a,userName:d,preferredEditor:u}=nn(),m=!o,p=o&&!n.hasProject;if(m)return G.createElement(et,{flexDirection:"column"},G.createElement(et,{flexDirection:"column"},G.createElement(Bn,{hideBreadCrumb:!0,filters:r}),G.createElement(zr,{height:t,width:e,hasUserName:a,hasPreferredEditor:i,userName:d??"",preferredEditor:u??""})),G.createElement(Pn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(p)return G.createElement(et,{flexDirection:"column"},G.createElement(et,{flexDirection:"column"},G.createElement(Bn,{hideBreadCrumb:!0,filters:r}),G.createElement(qs,{height:t,width:e})),G.createElement(Pn,{width:e,mode:n.mode,availableHints:n.availableHints}));let y=Te(v().breadCrumb??[],"BOARD");if(Ne(y)){let N=y.value.id,S=R(N).length,A=3,I=Math.floor(e/A),C=Math.floor(e/Math.max(S,1));e=Math.min(C,I)*Math.max(S,A)}return G.createElement(et,{flexDirection:"column"},G.createElement(et,{flexDirection:"column"},G.createElement(Bn,{filters:r}),G.createElement(ea,{width:e,height:t,currentNode:n.currentNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:n.viewMode,mode:n.mode})),G.createElement(Pn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import hl from"readline";var Un,$n,he,El=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]),ta=async e=>{if(e.ctrl&&e.name==="c")return D.exit();let{actionIndex:t,mode:n,readOnly:r}=v(),o=Yo(e,n);if(!o||r&&!El.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(a){logger.error(a)}},Nl=()=>async function(t,n){n.name!=="escape"&&(he&&(clearTimeout(he),he=void 0),await ta(n))},Cl=()=>async function(t){if(t.length===1&&t[0]===27){he&&clearTimeout(he),he=setTimeout(()=>{ta({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),he=void 0},25);return}he&&(clearTimeout(he),he=void 0)};function na(){Un&&process.stdin.removeListener("keypress",Un),$n&&process.stdin.removeListener("data",$n),Un=Nl(),$n=Cl(),hl.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",$n),process.stdin.on("keypress",Un)}Il(`${Jr.bold("Epiq CLI")}
64
+ `)):(Hl(),c("State booted successfully",null))}var tn=()=>{let e=ge(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},wo=()=>!Dt();import{Box as ac}from"ink";import Kr from"react";import Ot from"chalk";import{Box as Hr,Text as Ls}from"ink";import Ft,{useEffect as Kl,useMemo as Vl,useState as zl}from"react";var Fs=Ot.gray,ql=Ot.inverse,Gl=Ot.inverse.gray,Yl={hint:"",hints:[],overlap:0,remainder:""},Bs=({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}},Xl=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=X(t);return{bg:r=>Ot.bgHex(n).black(r),bgCursor:r=>Ot.bgHex(n).inverse.black(r)}}return sr(t)},Jl=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Bs({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}},Os=()=>({value:J.value,cursorPosition:J.cursorPosition,commandIsPending:J.commandIsPending,autoCompletion:J.commandMeta.autoCompletion??Yl,infoMessage:J.commandMeta.infoMessage,validationStatus:J.commandMeta.validity,command:J.commandMeta.command,inputString:J.commandMeta.inputString,modifier:J.commandMeta.modifier}),Zl=(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,Us=({width:e})=>{let[t,n]=zl(Os());Kl(()=>{let y=()=>{let S=Os();n(A=>Zl(A,S)?A:S)},N=_o(y);return y(),()=>{N()}},[]);let{value:r,cursorPosition:o,infoMessage:i,commandIsPending:a,autoCompletion:l,command:u,modifier:m}=t,p=Vl(()=>{let y=Math.max(0,Math.min(o,r.length)),N=Bs({value:r,command:u}),S=Jl({value:r,command:u,modifier:m}),A=u?sr(u):null,I=Xl({command:u,modifier:m}),C=(ie,se)=>{let _n=N&&se>=N.start&&se<N.end,Wn=S&&se>=S.start&&se<S.end;return _n&&A?A.fg(ie):Wn&&I?I.bg(ie):ie},T=(ie,se)=>{let _n=N&&se>=N.start&&se<N.end,Wn=S&&se>=S.start&&se<S.end;return _n&&A?A.fgCursor(ie):Wn&&I?I.bgCursor(ie):ql(ie)},B=r.slice(0,y),Oe=r[y]??" ",Be=y<r.length?r.slice(y+1):"",ra=Array.from(B).map((ie,se)=>C(ie,se)).join(""),Jr=T(Oe,y),Zr=Array.from(Be).map((ie,se)=>C(ie,y+1+se)).join("");if(l.hint){let ie=l.hint[l.overlap]??Oe;Jr=Gl(ie),Zr=Fs(l.remainder.slice(1)+Be)}return Fs(":")+ra+Jr+Zr},[r,o,l,u,m]);return Ft.createElement(Hr,{flexDirection:"column",justifyContent:"flex-start"},Ft.createElement(Hr,{flexDirection:"column",paddingX:1,borderColor:E.secondary,borderStyle:"round",width:e},Ft.createElement(Hr,null,Ft.createElement(Ls,null,p),i&&Ft.createElement(Ls,{wrap:"truncate",color:a?E.red:E.secondary2},` ${i} `))))};import $s from"chalk";import{Box as Ql,Text as jr}from"ink";import Rn,{useEffect as ec,useState as tc}from"react";var nc=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],_s=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)}},rc=({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)}`},oc=(e,t,n)=>{let r=_s(e),o=_s(t);return rc({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},ic=(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 oc(i,a,o)},sc=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),Ws=({width:e,availableHints:t})=>{let{syncStatus:{status:n,msg:r}}=$(),[o,i]=tc(0);ec(()=>{if(n!=="syncing"){i(0);return}let C=setInterval(()=>{i(T=>T+1)},50);return()=>clearInterval(C)},[n]);let a=[],l=0;for(let C of t){let B=(a.length>0?" | ":"").length+C.length;if(l+B>e-4)break;a.push(C),l+=B}let u=n!="synced"?r??a.join(" | "):a.join(" | "),m=Math.max(0,e-2),p=n==="syncing"?ic(nc,(Math.sin(o*.12)+1)/2):E.secondary,y=$s.hex(p??"fff"),N=$s.hex(E.secondary2),S=y(`\u256D${"\u2500".repeat(m)}\u256E`),A=y(`\u2570${"\u2500".repeat(m)}\u256F`),I=`${y("\u2502")}${N(sc(` ${u} `,m))}${y("\u2502")}`;return Rn.createElement(Ql,{flexDirection:"column",width:e},Rn.createElement(jr,null,S),Rn.createElement(jr,null,I),Rn.createElement(jr,null,A))};var Mn=({width:e,mode:t,availableHints:n})=>{let r=$(),o=[],i=0;for(let a of n){let u=(o.length>0?" | ":"").length+a.length;if(i+u>e+2)break;o.push(a),i+=u}return Kr.createElement(ac,null,t===g.COMMAND_LINE&&r.syncStatus.status!=="syncing"?Kr.createElement(Us,{width:e}):Kr.createElement(Ws,{width:e,mode:t,availableHints:n}))};import{Box as mt,Text as Hs}from"ink";import He from"react";var js=({width:e})=>{let t=[...v().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"]),He.createElement(mt,{flexDirection:"column",marginTop:3,borderColor:E.secondary,borderStyle:"round",width:e,minHeight:19},He.createElement(mt,{flexDirection:"column",width:e},v().mode===g.HELP?t.map(([n,r],o)=>He.createElement(mt,{paddingLeft:1,key:o,flexDirection:"row"},He.createElement(mt,{key:o,flexDirection:"row",paddingBottom:o?0:1},He.createElement(mt,{width:20,justifyContent:"flex-end"},He.createElement(Hs,{color:o?E.accent:E.secondary},n)),He.createElement(mt,{flexGrow:1,width:40,paddingLeft:2},He.createElement(Hs,{color:o?E.primary:E.secondary},r))))):null))};import dc from"chalk";import{Box as Pn,Text as je}from"ink";import pe from"react";var Ks=({width:e,height:t})=>pe.createElement(Pn,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:E.secondary,rowGap:1},pe.createElement(je,{color:E.accent,bold:!0},"Initialize project"),pe.createElement(je,null,`This folder is not an ${dc.hex(E.accent)("epiq")} project yet.`),pe.createElement(je,{color:E.primary},"To start tracking issues here, we need to initialize a new"," ",pe.createElement(je,{color:E.primary,backgroundColor:E.secondary}," .epiq/project.json ")," ","file in this repository."),pe.createElement(Pn,{marginTop:1,flexDirection:"column"},pe.createElement(Pn,null,pe.createElement(je,{color:E.accent}," "),pe.createElement(je,{color:E.primary},"Type "),pe.createElement(je,{backgroundColor:E.secondary}," :init "))),pe.createElement(Pn,{marginTop:1},pe.createElement(je,{color:E.secondary2},"(This will create the local epiq project files)")));import{Box as Bt,Text as xe}from"ink";import H from"react";var kn=({isDone:e,command:t,value:n})=>H.createElement(Bt,null,H.createElement(xe,{color:E.accent,dimColor:e},e?" \u2714 ":" "),H.createElement(xe,{dimColor:e},"Type "),H.createElement(xe,{backgroundColor:E.secondary,dimColor:e}," "+t+" "),n&&H.createElement(H.Fragment,null,H.createElement(xe,{dimColor:e}," "),H.createElement(xe,{color:E.secondary,dimColor:e},"<"+n+">")));function Vr({width:e,height:t,hasUserName:n,hasPreferredEditor:r,userName:o,preferredEditor:i}){let a=n&&r,l=n?r?null:":config:editor":":config:username";return H.createElement(Bt,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:E.secondary,rowGap:1},H.createElement(xe,{color:E.accent,bold:!0},"Welcome! \u{1F539}"),H.createElement(xe,null,"Lets get you started - its a breeze."),H.createElement(xe,{color:E.secondary2},"And remember, you can always get help with"," ",H.createElement(xe,{color:E.accent},":help"),"."),!a&&H.createElement(xe,{color:E.secondary2},l===":config:username"?"First, choose your username.":"Nice. One more step."),H.createElement(Bt,{flexDirection:"column"},n&&H.createElement(Bt,{marginBottom:1},H.createElement(kn,{isDone:!0,command:":config:username",value:o})),!n&&H.createElement(kn,{isDone:!1,command:":config:username"}),n&&!r&&H.createElement(kn,{isDone:!1,command:":config:editor"}),a&&H.createElement(Bt,null,H.createElement(kn,{isDone:!0,command:":config:editor",value:i}))))}import Ys from"chalk";import{Box as Ln,Text as Ke}from"ink";import Z from"react";import{Box as zr,Text as lc}from"ink";import pt from"react";var cc=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",Vs=({width:e})=>{let{breadCrumb:t,currentNode:n,selectedIndex:r,viewMode:o}=v(),i=F(n.id)[r],a=Ue(i?.id??n.id,"TICKET"),l=Ee(a)?a.value:void 0,u=l?.id?F(l.id):[],m=I=>{let C=u.find(T=>T.title===I);return C?F(C.id).map(T=>typeof T.props?.value=="string"?T.props.value:"").filter(T=>!!T):[]},p=m("Tags"),y=m("Assignees"),N=l?.parentNodeId?!Qn(n.id,l?.parentNodeId)&&o==="dense":!1,S=t.map((I,C)=>{let T=C===t.length-1,B=F(I.id),Oe=T?B?.[r]?.title:void 0;return`${C?" / ":""}${I.title??""}${Oe?` \u25B8 ${Oe}`:""}`}).join(""),A=cc(S,e);return pt.createElement(zr,null,pt.createElement(lc,{color:E.secondary2},A),N?p.map(I=>pt.createElement(zr,{key:I,paddingLeft:2},pt.createElement(at,{id:I}))):null,N?y.map(I=>pt.createElement(zr,{key:I,paddingLeft:2},pt.createElement(st,{id:I}))):null)};import{Box as uc,Text as zs}from"ink";import Dn from"react";var mc=({filters:e})=>Dn.createElement(uc,{columnGap:1},Dn.createElement(zs,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Dn.createElement(zs,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),qs=Dn.memo(mc);var Gs="0.4.8";function Fn({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o}=$(),{userName:i,preferredEditor:a}=ge(),l=40,u=process.stdout.columns-l-8,m=r.at(-1)?.id,p=nn(m??""),y=Ee(p)?Mo(p.value):"INVALID DATE";return Z.createElement(Ln,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?Z.createElement(Ke,null," "):Z.createElement(Ln,{paddingLeft:1},e.length>0?Z.createElement(qs,{filters:e}):Z.createElement(Vs,{width:u})),n==="live"?Z.createElement(Ln,{columnGap:1,paddingRight:2,"max-width":l,overflow:"hidden",justifyContent:"flex-end"},Z.createElement(Ke,{dimColor:!0,color:E.secondary2},Gs+" "),Z.createElement(Xs,{icon:"@",value:i}),Z.createElement(Xs,{icon:"\u276F",value:a})):"",n==="peek"?Z.createElement(Ln,{paddingLeft:1},Z.createElement(Ke,{backgroundColor:E.yellow}," Readonly "),Z.createElement(Ke,{color:E.yellow}," "+o.length+" edits ago at "),Z.createElement(Ke,{backgroundColor:E.yellow,color:E.accent}," "+y+" "),Z.createElement(Ke,{color:E.yellow},". Resume with "),Z.createElement(Ke,{backgroundColor:E.yellow}," :peek now ")):"")}function Xs({icon:e,value:t}){return Z.createElement(Ke,null,Ys.dim(e)+Ys.hex(E.accent)(` ${t??"-"} `))}import{Box as pc,Text as gc}from"ink";import Ut from"react";import{Box as On,Text as qr}from"ink";import Ve from"react";function Gr(){let e=$(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,a=t?.id?R(t?.id):[];return Ve.createElement(On,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:E.secondary,width:i},Ve.createElement(On,{padding:1,paddingTop:0,paddingBottom:0},Ve.createElement(qr,null,"Select a board:")),Ve.createElement(On,{padding:1,flexDirection:"column"},a.map((l,u)=>{let m=e.currentNode.context==="WORKSPACE"&&e.selectedIndex===u,y=R(l.id).flatMap(({id:N})=>F(N)).length;return Ve.createElement(On,{key:l.id??u},Ve.createElement(qr,{color:m?E.accent:E.secondary2},Ve.createElement(re,{isSelected:m})),Ve.createElement(qr,{color:m?E.accent:E.secondary2},l.title," (",y," issues)",l.readonly?" \u{1F512}":""))})))}var fc=({currentNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:l}=$(),u=n.find(({context:N})=>N==="BOARD"),y=i-1-3;return Ut.createElement(pc,{flexDirection:"row"},e.context==="WORKSPACE"?Ut.createElement(Gr,null):u?Ut.createElement(mn,{height:y,width:a,swimlanes:(l[u.id]??[]).filter(N=>N!==void 0&&Qe(N)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Ut.createElement(gc,null))},Js=Ut.memo(fc);function Yr({width:e,height:t}){let n=$(),r=n.filters;if(n.mode===g.HELP)return G.createElement(Ze,{flexDirection:"column"},G.createElement(js,{width:e}));let{isSetup:o,hasPreferredEditor:i,hasUserName:a,userName:l,preferredEditor:u}=tn(),m=!o,p=o&&!n.hasProject;if(m)return G.createElement(Ze,{flexDirection:"column"},G.createElement(Ze,{flexDirection:"column"},G.createElement(Fn,{hideBreadCrumb:!0,filters:r}),G.createElement(Vr,{height:t,width:e,hasUserName:a,hasPreferredEditor:i,userName:l??"",preferredEditor:u??""})),G.createElement(Mn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(p)return G.createElement(Ze,{flexDirection:"column"},G.createElement(Ze,{flexDirection:"column"},G.createElement(Fn,{hideBreadCrumb:!0,filters:r}),G.createElement(Ks,{height:t,width:e})),G.createElement(Mn,{width:e,mode:n.mode,availableHints:n.availableHints}));let y=Ae(v().breadCrumb??[],"BOARD");if(Ee(y)){let N=y.value.id,S=R(N).length,A=3,I=Math.floor(e/A),C=Math.floor(e/Math.max(S,1));e=Math.min(C,I)*Math.max(S,A)}return G.createElement(Ze,{flexDirection:"column"},G.createElement(Ze,{flexDirection:"column"},G.createElement(Fn,{filters:r}),G.createElement(Js,{width:e,height:t,currentNode:n.currentNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:n.viewMode,mode:n.mode})),G.createElement(Mn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import vc from"readline";var Bn,Un,ye,xc=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]),Zs=async e=>{if(e.ctrl&&e.name==="c")return D.exit();let{actionIndex:t,mode:n,readOnly:r}=v(),o=Go(e,n);if(!o||r&&!xc.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(a){logger.error(a)}},yc=()=>async function(t,n){n.name!=="escape"&&(ye&&(clearTimeout(ye),ye=void 0),await Zs(n))},hc=()=>async function(t){if(t.length===1&&t[0]===27){ye&&clearTimeout(ye),ye=setTimeout(()=>{Zs({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),ye=void 0},25);return}ye&&(clearTimeout(ye),ye=void 0)};function Qs(){Bn&&process.stdin.removeListener("keypress",Bn),Un&&process.stdin.removeListener("data",Un),Bn=yc(),Un=hc(),vc.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Un),process.stdin.on("keypress",Bn)}Nc(`${Xr.bold("Epiq CLI")}
65
65
 
66
- ${Jr.dim("Boot in directory:")}
67
- ${Jr.cyan("$ epiq")}
66
+ ${Xr.dim("Boot in directory:")}
67
+ ${Xr.cyan("$ epiq")}
68
68
 
69
- `,{importMeta:import.meta,flags:{init:{type:"boolean",default:!1}}});var ra=process.stdout.columns||120,oa=process.stdout.rows||20,_n=null,Al=e=>{if(!_n){_n=bl(e);return}_n.rerender(e)},ia=()=>{Al(Sl.createElement(Xr,{width:ra,height:oa}))},wl=()=>{let e=qt(process.cwd());if(c(e))return logger.info("No .epiq/project.json found, starting in init mode"),{hasProject:!1,epiqRootDir:null,events:[]};let t=Et(e.value);if(c(t)){if(t.message.includes("No events found"))return logger.info("No events found, starting with empty state"),{hasProject:!0,epiqRootDir:e.value,events:[]};throw new Error(t.message)}return{hasProject:!0,epiqRootDir:e.value,events:t.value}};async function Tl(){let e=ps();c(e)||nt(e.value);let t=wl();t.hasProject&&await Yi();let n=Bs(t.events);if(c(n))throw new Error(`Failed to boot state: ${n.message}`);w({hasProject:t.hasProject}),ia(),na()}process.stdout.on("resize",()=>{ra=process.stdout.columns||120,oa=process.stdout.rows||20,_n&&ia()});(async()=>(console.clear(),await Tl()))();
69
+ `,{importMeta:import.meta,flags:{init:{type:"boolean",default:!1}}});var ea=process.stdout.columns||120,ta=process.stdout.rows||20,$n=null,bc=e=>{if(!$n){$n=Ec(e);return}$n.rerender(e)},na=()=>{bc(Cc.createElement(Yr,{width:ea,height:ta}))},Ic=()=>{let e=zt(process.cwd());return d(e)?{hasProject:!1,epiqRootDir:null,events:[]}:{hasProject:!0,epiqRootDir:e.value,events:[]}};async function Sc(){let e=cs();d(e)||et(e.value);let t=Ic();if(t.hasProject){let r=await zi();if(d(r))throw new Error(r.message);let o=yt(t.epiqRootDir);d(o)||(t.events=o.value)}let n=Ds(t.events);if(d(n))throw new Error(`Failed to boot state: ${n.message}`);w({hasProject:t.hasProject}),na(),Qs()}process.stdout.on("resize",()=>{ea=process.stdout.columns||120,ta=process.stdout.rows||20,$n&&na()});(async()=>(console.clear(),await Sc()))();