epiq 0.4.9 → 0.4.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,68 +1,63 @@
1
1
  #!/usr/bin/env node
2
- import Gr from"chalk";import{render as xl}from"ink";import yl from"meow";import hl from"react";import{Box as Je}from"ink";import G from"react";import ft from"node:fs";import{ulid as ia}from"ulid";import{z as jt}from"zod";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}),d=e=>e.status==="fail",ge=e=>e.status==="success";import pt from"node:fs";import Ne from"node:path";var _n=process.env.IS_LOCAL==="true",Ce=".epiq",ce=".epiq-global",$t="events",na="project.json",Jr=e=>Ne.join(e,Ce),_t=e=>Ne.join(e,Ce),Wt=e=>Ne.join(_t(e),na),gt=e=>Ne.join(_t(e),$t),ra=e=>{let t=Ne.join(e,Ce);return pt.existsSync(t)&&pt.statSync(t).isDirectory()},oa=e=>{let t=Wt(e);return pt.existsSync(t)&&pt.statSync(t).isFile()},Oe=e=>{let t=Ne.resolve(e);for(;;){if(ra(t))return l("Resolved closest .epiq root",t);let n=Ne.dirname(t);if(n===t)return s("No .epiq directory found in any parent");t=n}},Be=e=>{let t=Ne.resolve(e);for(;;){if(oa(t))return l("Resolved closest epiq project root",t);let n=Ne.dirname(t);if(n===t)return s("No .epiq/project.json found in any parent");t=n}},Zr=e=>{let t=gt(e);try{return pt.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")}};var sa=jt.object({projectId:jt.string().min(1),stateBranch:jt.string().min(1),createdAt:jt.string().datetime()}),aa=()=>({projectId:ia(),stateBranch:"epiq/state",createdAt:new Date().toISOString()}),Ze=e=>{let t=Wt(e);if(!ft.existsSync(t))return s("Missing .epiq/project.json");try{let n=ft.readFileSync(t,"utf8"),r=JSON.parse(n),o=sa.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")}},Qr=e=>{let t=Ze(e);return d(t)?s(t.message):l("Read projectId",t.value.projectId)},eo=e=>{let t=_t(e),n=Wt(e);try{if(ft.mkdirSync(t,{recursive:!0}),ft.existsSync(n)){let o=Ze(e);return d(o)?s(o.message):l("Project already initialized",null)}let r=aa();return ft.writeFileSync(n,JSON.stringify(r,null,2)+`
3
- `,"utf8"),l("Created project.json",null)}catch(r){return s(r instanceof Error?`Failed to initialize project: ${r.message}`:"Failed to initialize project")}};var Ht={autoSync:!1,preferredEditor:null,userName:null,userId:null},fe=()=>Ht,Qe=e=>(Ht={...Ht,...e},Ht);var Kt=()=>{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=()=>{let e=Be(process.cwd());if(d(e))return s("Unable to determine if repository is initialized");let t=Ze(e.value);return ge(t)};var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};var be=(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{useSyncExternalStore as Uc}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function Wn(e){return e.context==="WORKSPACE"}function le(e){return e.context==="TICKET"}function no(e){return e.context==="FIELD"}var et=e=>e.context==="SWIMLANE",ro=e=>e.context==="BOARD";function Vt(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var zt=(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 oo=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},io=(e,t)=>t?e.get(t)??[]:[];var so=new WeakMap,da=e=>{let t=so.get(e);return t||(t=oo(e),so.set(e,t)),t};var ao=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return io(da(e),r).filter(i=>Vt(r,i)>=n)};var ca={hint:"",hints:[],overlap:0,remainder:""},co=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return ca;let o=ao({wordList:r,inputToMatch:e,overlapThreshold:1});return la(t,o)},la=(e,t)=>{let n=t[0]??"",r=Vt(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),a=r<(o??"").length,c=!!i,p=(c&&a?o:n)+(c&&a?":":" "),v=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:v}};var lo=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var Y={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 pa}from"ulid";var ze=24n,ua=ze*4n,vt=(1n<<ua)-1n,ma=/^[0-9a-f]+$/;function uo(e){return!e||!ma.test(e)?s(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function Ie(e,t=ze){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 Ie(vt/2n,ze);let n=e?uo(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?uo(t):l("Resolved upper bound",vt);if(d(r))return r;let o=n.value,i=r.value;if(i<=o)return Ie(vt/2n,ze);let a=(o+i)/2n;return a===o||a===i?s("No rank space available between neighbors"):Ie(a,ze)}function mo(){return Ie(vt/2n,ze)}function po(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=Ie(o,ze);if(d(i))return i;n.push(i.value)}return l("Resolved evenly spaced ranks",n)}var Hn=(e,t)=>{let n=F(e),r=po(n.length);if(d(r))return r;let o={};for(let i=0;i<n.length;i++){let a=n[i],c=r.value[i];if(!a||!c)return s("Unable to assign rebalance rank");o[a.id]=c}return l("Created rebalance event",{id:pa(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var ga=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[Se,qt]=ga;var k=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),fa={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Y.workspace(t,n,r),i=ht(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):Wn(a.value)?l("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=Y.workspace(t,n,r),i=b.createNode(o);return d(i)?k(i.message??"Failed to add workspace",e):Wn(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(Y.board(t,n,r,o));return d(i)?k(i.message??"Unable to create board",e):ro(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(Y.swimlane(t,n,r,o));return d(i)?k(i.message??"Unable to create swimlane",e):et(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(Y.ticket(t,n,r,o));return d(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(Y.field(t,n,r,i,{value:o},n.includes("Description")?"vertical":"horizontal"));return d(a)?k(a.message??`Unable to create field: ${n}`,e):no(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 d(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 d(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 d(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 d(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 d(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 d(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 d(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 d(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 d(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 d(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(Se);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):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(Se);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 c=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?k(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=b.lockNode(t);return d(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(d(a))return k(a.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})}},va=(e,t)=>{let n=b.getNode(e);n&&b.updateNode({...n,log:[...n.log??[],t]})},xa=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=x().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=fa[e.action](e);if(d(n))return n;t||([...new Set(xa(e))].forEach(a=>va(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 yt=e=>e.map(t=>xt(t));import Aa from"node:fs";import Ra from"node:path";import{decodeTime as Ta,monotonicFactory as wa}from"ulid";import{z as Nt}from"zod";import Gt from"node:fs";import Vn from"node:path";import{decodeTime as ya}from"ulid";import{z as Kn}from"zod";var ha=Kn.object({userId:Kn.string().min(1).default("unknown"),userName:Kn.string().min(1).default("unknown")}),Ea=e=>{let[t,n]=Vn.basename(e,".jsonl").split("."),r=ha.safeParse({userId:t,userName:n});return r.success?l("Parsed event file actor",r.data):s(`Invalid event file name ${Vn.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Na=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])},Ca=(e,t)=>t in e,ba=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Ia=e=>{let{userId:t,userName:n,...r}=e,o=Na(r);if(d(o))return s(o.message);let i=o.value,a=e.id?.[0];return a?Ca(r,i)?l("Decoded persisted event",ba({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=Ea(e);if(d(t))return s(t.message);let n=Gt.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
4
- `)){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{return s(`Failed to parse event JSON from ${e}: ${i}`)}let c=zn(a);if(d(c))return s(`${c.message} in ${e}: ${i}`);r.push({...c.value,userId:t.value.userId,userName:t.value.userName})}return l("Parsed persisted events file",r)};function go(e){let t=gt(e);if(!Gt.existsSync(t))return l("No events found",[]);let n=Gt.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Vn.join(t,o)),r=[];for(let o of n){let i=Yt(o);if(d(i))return s(i.message);r.push(...i.value)}return l("All events loaded",Sa(r))}function Et(e){let t=go(e);if(d(t))return s(t.message);let n=[];for(let r of t.value){let o=Ia(r);if(d(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 d(t)?s(t.message):l("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Sa=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],v=m.id[1]??null;t.set(p,m);let E=n.get(v)??[];E.push(m),n.set(v,E)}for(let m of n.values())m.sort((p,v)=>p.id[0].localeCompare(v.id[0]));let r=[],o=new Set,i=m=>{let p=m.id[0];if(o.has(p))return;r.push(m),o.add(p);let v=n.get(p)??[];for(let E of v)i(E)},a=n.get(null)??[];for(let m of a)i(m);let c=e.filter(m=>{let p=m.id[0],v=m.id[1]??null;return!o.has(p)&&v!==null&&!t.has(v)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of c)i(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)i(m);return r},vo=(e,t)=>{let n=e.findIndex(r=>{try{return ya(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=wa(),Ma=Nt.tuple([Nt.string().min(1),Nt.string().min(1).nullable()]),Pa=Nt.looseObject({v:Nt.literal(ho),id:Ma}),zn=e=>{let t=Pa.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",ee=()=>{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")},qn=({userId:e,userName:t})=>`${Xt(e)}.${Xt(t)}.jsonl`,ka=(e,{userId:t,userName:n})=>{let r=qn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return s(`Invalid event log file name: ${r}`);let i=Ra.join(gt(e),r);return l("Successfully resolved event log path",i)},La=(e,t)=>{let n={[e.action]:e.payload,v:ho,id:t};return zn(n)};function Eo({event:e,rootDir:t=process.cwd()}){try{let n=Oe(t);if(d(n))return n;let r=Zr(n.value);if(d(r))return r;let o=ka(n.value,{userId:e.userId,userName:e.userName});if(d(o))return o;let i=fo(n.value);if(d(i))return s(i.message);let a=i.value?yo(Math.max(Date.now(),Ta(i.value)+1)):yo(),c=La(xo(e),[a,i.value]);return d(c)?s(c.message):(Aa.appendFileSync(o.value,`${JSON.stringify(c.value)}
5
- `,"utf8"),l("Event persisted",{path:o.value,entry:c.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=Eo({event:e});return d(n)?n:t}function Gn(e){return e.map(t=>K(t))}var No=e=>Yn(F(e),{at:"end"}),Yn=(e,t={at:"end"})=>{let n=r=>d(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(x().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"})=>Yn(F(t).filter(r=>r.id!==e),n),tt=(e,t,n,r)=>{let o=bo(t,e,n);if(d(o))return o;if(!o.value.needsRebalance)return l("Resolved rank",o.value.rank);let i=Hn(e,r);if(d(i))return i;let a=K(i.value);if(d(a))return a;let c=bo(t,e,n);return d(c)?c:c.value.needsRebalance?s("Rank rebalance failed to create space"):l("Resolved rank after rebalance",c.value.rank)},nt=(e,t)=>{let n=No(e);if(d(n))return n;if(!n.value.needsRebalance)return l("Resolved rank",n.value.rank);let r=Hn(e,t);if(d(r))return r;let o=K(r.value);if(d(o))return o;let i=No(e);return d(i)?i:i.value.needsRebalance?s("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)};var Ue=(e,t)=>{let{nodes:n}=x(),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}`)},Jn=(e,t)=>{let{nodes:n}=x(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Xn=(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}=x(),r=n[e];if(!r)return s("Edit target node not found");let o=Xn(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=Xn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=x();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=x();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}=x(),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=Xn(o,"move");if(a)return a;if(Jn(t,e))return s("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=x(),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 c={...structuredClone(t)};for(let u of i){if(!c[u])return s("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(R({nodes:c}),l("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"):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=Y.field(n,o.name,a.id,r,{value:t}),m=this.createNode(u);return d(m)?m:l("Assigned contributor",u)},createTag(e){let t=ae(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(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=Y.field(n,o.name,a.id,r,{value:t}),m=this.createNode(u);return d(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(c=>c.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(c=>c.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=ae(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(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=ae(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?s(r.message):l("Locked node",n)},updateNode(e){let t=ae(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return x().contributors[e]},getTag(e){return x().tags[e]},getNode(e){return x().nodes[e]},getSiblings(e){return F(e)}};var X={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"},N={accent:X.cyan,accent2:X.magenta,primary:X.white,secondary:X.grayDark,secondary2:X.grayLight,gray:X.gray,green:X.green,yellow:X.yellow,red:X.red};var h={red:X.red,yellow:X.yellow,green:X.green,blue:X.blue,magenta:X.magenta,cyan:X.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 Io=(e,t)=>{let r=w(e.id).find(o=>o.title===t);return r?w(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},Zn=e=>Io(e,"Tags").map(t=>b.getTag(t)).filter(t=>!!t),Jt=()=>{let{breadCrumb:e,selectedNode:t}=x(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!le(n)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Zn(n)??[])},Zt=()=>{let{breadCrumb:e,selectedNode:t}=x(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!le(n)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Qn(n)??[])},Qn=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 Da=/^(\d+)(h|d|w|mo|y)$/,Fa=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Oa=({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},Ba=(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}},Ua=e=>{let t=e.match(Fa);if(!t)return null;let[,n,r,o,i,a]=t,c=Number(n),u=Number(r),m=Number(o),p=i?Number(i):0,v=a?Number(a):0;return Oa({year:c,month:u,day:m,hour:p,minute:v})?new Date(c,u-1,m,p,v):null},Qt=e=>{let t=e.trim().toLowerCase();return Ba(t)??Ua(t)},So=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,$a=[{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=$a)=>{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"],qe=[f.SYNC,f.HELP,f.EXPORT,f.SET_VIEW,f.SET_EDITOR,f.SET_USERNAME],en=[f.NEW,f.RENAME,f.DELETE,f.MOVE],er=[f.TAG,f.UNTAG,f.ASSIGN,f.UNASSIGN,f.CLOSE_ISSUE,f.RE_OPEN_ISSUE,f.SET_DESCRIPTION],Ro=[f.FILTER,f.PEEK],Wa={WORKSPACE:[...qe,...en],BOARD:[...Ro,...qe,...en],SWIMLANE:[...Ro,...qe,...en],TICKET:[...qe,...en,...er],FIELD:[...qe,...er],FIELD_LIST:[...qe,...er],TEXT:[...qe]},ja=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Ha=()=>{let{currentNode:e,selectedNode:t,readOnly:n}=x();if(!Kt().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&&_a.includes(i);return Wa[o].filter(c=>c===f.RENAME||c===f.DELETE||c===f.MOVE?a:!0)},z=e=>{let{currentNode:t}=x(),n=t.context??"WORKSPACE";return{[f.NONE]:Ha(),[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]:[...lo],[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]:ja(n)}[e]??[]};import it from"chalk";import{decodeTime as To}from"ulid";var wo=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())}`},tn=e=>{try{return l("Decoded date",new Date(To(e)))}catch(t){return s("Decoding failed + "+t.message)}},tr=e=>{if(!e?.id)return null;try{return To(e.id)}catch{return null}};import ot from"chalk";var rr={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Ka=(e,t,n)=>Math.max(t,Math.min(n,e)),nr=(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},Va=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,a=e/60,c=i*(1-Math.abs(a%2-1)),u=0,m=0,p=0;a>=0&&a<1?(u=i,m=c):a>=1&&a<2?(u=c,m=i):a>=2&&a<3?(m=i,p=c):a>=3&&a<4?(m=c,p=i):a>=4&&a<5?(u=c,p=i):(u=i,p=c);let v=o-i/2;return[Math.round((u+v)*255),Math.round((m+v)*255),Math.round((p+v)*255)]},za=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,qa=(e,t,n)=>[Math.round(nr(e[0],t[0],n)),Math.round(nr(e[1],t[1],n)),Math.round(nr(e[2],t[2],n))],Ct=e=>{let n=Po(e)%360,r=Va(n,rr.stringColor.saturation,rr.stringColor.lightness);return za(r)},Ga=e=>{let t=rr.gradient.stops,n=Ka(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 qa(t[i],t[i+1],a)},nn=e=>Po(e.toLowerCase().trim())/4294967295,ko=e=>{let t=nn(e);return Ga(t)},Ya=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)}},or=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)}},ir=e=>Ya(e).normal(` ${e} `),J=(e,t=rt)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:Ct(r)};var Ae={None:"none",Invalid:"invalid",Valid:"valid"};var Xa=["BOARD","TICKET","SWIMLANE"],sr=()=>{let e=x().selectedNode;return e?.context?Xa.includes(e?.context)?W():U({message:"Command not available in this context"}):U({message:"Missing target context"})},te="<ENTER> to confirm",W=(e="",t=[])=>({message:e,validity:Ae.Valid,completionWordList:t}),U=({message:e,completionWordList:t=[]})=>({validity:Ae.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,v)=>nn(p)-nn(v)).slice(0,r).map(ir),m=u.length>i?u.join(" "):"";return m?`${e}${m}${n}`:""},ar=({modifier:e})=>{let t="confirm";return e===t?W(te):U({message:It(e)?`if you are certain, enter ${ir(t)}`:"",completionWordList:[t]})},Ja=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?W(te):U({message:It(n)?t:""}),Za=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?U({message:n}):W():U({message:It(r)?t:""}),bt=({hint:e})=>({modifier:t,inputString:n})=>It(t)&&It(n)?U({message:e,completionWordList:[]}):W(te),Qa={[f.EXPORT]:()=>W(te+", and create export markdown file"),[f.PEEK]:e=>{let t=e.modifier;if(t==="now")return W(te);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(te);let r=Qt(t);if(!t||!r)return U(n);let o=be(x().breadCrumb,"BOARD");if(d(o))return U({message:"Command is not applicable in this context"});let i=tn(o.value.id);return d(i)?U({message:"Unable to peek: board id is not a valid ULID"}):So({date:r,horizonDate:i.value})?W(te):U({message:it.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[f.EXIT]:()=>W(te+" and exit the application"),[f.INIT]:()=>W(te),[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(x().tags).map(a=>a.name),o=Object.values(x().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=>Za({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(te),[f.HELP]:()=>W(te),[f.RENAME]:()=>{let e=sr();return e.validity==="invalid"?e:W(te)},[f.DELETE]:e=>{let t=sr();return t.validity==="invalid"?t:ar(e)},[f.CLOSE_ISSUE]:e=>ar(e),[f.RE_OPEN_ISSUE]:e=>ar(e),[f.MOVE]:e=>{let t=sr();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=>` ${it.bgHex(J(n))(" "+n+" ")} `).slice(0,10);return bt({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(J(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=>` ${it.bgHex(J(n))(" "+n+" ")} `).slice(0,10);return bt({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(J(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?W(te):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=>Ja({list:z(f.SET_VIEW),hint:$e({wordList:z(f.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[f.SYNC]:()=>W(te)},Lo=Object.fromEntries(Object.entries(Qa).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Do=["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:c,completionWordList:u}=Lo[n].validate(n,r,i),m=o==="command"?Object.values(f):n&&e.target==="modifier"?z(n):Do;return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?co(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var Bo=e=>{let t=e.trimStart(),n=td(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),a=nd(e),c=Fo(r)?r:null,u=c!==null,m=r!=="",p=c?z(c)??[]:[],v=c&&p.includes(o)?o:"",E="word";n.length===0||n.length===1&&!i?E="command":(n.length===1&&i||n.length===2&&!i)&&(E="modifier");let S=i?"":a,A=ed(t,c,v);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:a,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:i,modifier:v,target:E,inputToMatch:S,inputString:A}},ed=(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},td=e=>e.trim()?e.trim().split(/\s+/):[],nd=e=>e.trimEnd().split(/\s+/).at(-1)??"";var Uo=" ",Z={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Ae.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},dr=new Set,$o=()=>{for(let e of dr)e()},_o=e=>(dr.add(e),()=>dr.delete(e)),Re=e=>{let n=e(Z),r=Bo(n.value),o=n.cursorPosition===n.value.length;Z={...n,commandMeta:Oo(r,o)},$o()},St=({message:e,status:t})=>{let n=structuredClone(Z);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Z=n,$o(),l(e,null)},cr=e=>{Re(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},lr=e=>{Re(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=()=>{Re(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}})},jo=()=>{Re(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=>{Re(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,c=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:c,commandIsPending:!1}})},Ho=()=>{Re(e=>({...e,commandIsPending:!0}))},Ko=({addToHistory:e=!0})=>{Re(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),rd()},Vo=()=>{Re(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=()=>{Re(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},rd=()=>H(()=>""),ne=()=>Z,rn=()=>{let[e,...t]=Z.value.split(Uo);return t.join(Uo).trim()};var od=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",id=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",sd=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",qo=(e,t)=>{if(id(e,e.sequence))return y.MoveCursorLeftOfWord;if(sd(e,e.sequence))return y.MoveCursorRightOfWord;if(od(e,e.sequence))return y.EraseInputWord;switch(e.name){case"tab":return y.AutoCompleteCommand;case"up":return y.GetLastCommandFromHistory;case"down":return y.GetNextCommandFromHistory;case"left":return y.MoveCursorLeft;case"right":return y.MoveCursorRight;case"return":return y.Confirm;case"backspace":return t?y.EraseInput:y.ExitCommandLine;case"escape":return y.ExitCommandLine;default:return y.CaptureInput}};var y={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 ad(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 dd(e,t,n){let r=x().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 y.InitCommandLine;if(t===g.MOVE)switch(e.name){case"m":case"return":return y.ConfirmMove}if(t===g.COMMAND_LINE)return qo(e,n.value);let r=ad(e);if(r){let o=t===g.MOVE?{prevItem:y.MovePreviousItem,nextItem:y.MoveNextItem,prevContainer:y.MoveToPreviousContainer,nextContainer:y.MoveToNextContainer}:{prevItem:y.NavPreviousItem,nextItem:y.NavNextItem,prevContainer:y.NavToPreviousContainer,nextContainer:y.NavToNextContainer};return dd(x().currentNode.childRenderAxis,r,o)}if(e.ctrl&&e.name==="c")return y.Exit;switch(e.name){case"e":return y.Edit;case"n":return y.AddItem;case"m":return y.InitMove;case"d":return y.Delete;case"return":return y.Confirm;case"space":return y.Confirm;case"v":return x().viewMode==="wide"?y.SetViewDense:y.SetViewWide;case"q":case"escape":return y.Exit;case"s":return y.Sync;default:return null}}var Yo=e=>{let{context:t}=x()?.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 ui from"node:fs";import Od from"node:path";import Bd from"react";import{Box as Dd}from"ink";import ln from"react";import{Box as pr,Text as Ed}from"ink";import xe from"react";import{Text as Xo}from"ink";import Jo,{useEffect as Zo,useState as cd}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]=cd(0);if(Zo(()=>{i(0)},[r]),Zo(()=>{if(!e)return;let c=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return Jo.createElement(Xo,null,t);let a=r[o]??r[0]??t;return Jo.createElement(Xo,{color:N.accent,dimColor:o===1},a)};import{Box as ur,Text as ld}from"ink";import on from"react";var sn=({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)),c=Math.max(1,Math.floor(i/a)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),v=p+c,E=e.slice(p,v),S=e.length>c,A=i,I=S?Math.max(1,Math.floor(c/e.length*A)):A,C=Math.max(0,A-I),T=Math.max(1,e.length-c),B=S?Math.floor(p/T*C):0;return on.createElement(ur,{flexDirection:"row",height:i,width:"100%"},on.createElement(ur,{flexDirection:"column",flexGrow:1,height:i},E),on.createElement(ur,{flexDirection:"column",width:1,height:A},Array.from({length:A}).map((De,Fe)=>on.createElement(ld,{key:Fe,color:S&&Fe>=B&&Fe<B+I?N.accent:N.secondary},S?"\u2502":" "))))};import{Box as an,Text as xd}from"ink";import Ge from"react";import{Text as ud}from"ink";import md from"react";var pd=e=>e.toLowerCase().trim(),gd=(e,t=rt)=>{let n=pd(e);return t[n]?t[n]:Ct(n)},st=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return md.createElement(ud,{underline:t,color:gd(n.name)},"@"+n.name)};import{Text as fd}from"ink";import vd from"react";var at=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return vd.createElement(fd,{underline:t,backgroundColor:J(n.name),color:N.primary}," "+n.name+" ")};var ei=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=zt(jn(t.title),r),i=Zn(t),a=Qn(t);return Ge.createElement(an,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?N.accent:N.secondary,justifyContent:"space-between"},Ge.createElement(an,{borderBottom:!0},Ge.createElement(an,{paddingLeft:1,flexDirection:"column"},Ge.createElement(xd,{color:N.primary},o))),Ge.createElement(an,{flexDirection:"row",paddingLeft:1},i.map(c=>Ge.createElement(at,{key:c.id,id:c.id})),a.map(c=>Ge.createElement(st,{key:c.id,id:c.id}))))};import yd from"chalk";import{Box as At,Text as mr}from"ink";import Te from"react";var hd=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,ti=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=w(t.id),a=I=>{let C=i.find(T=>T.title===I);return C?w(C.id).map(T=>typeof T.props?.value=="string"?T.props.value:"").filter(T=>!!T):[]},c=a("Tags").map(I=>b.getTag(I)).filter(I=>!!I),u=a("Assignees").map(I=>b.getContributor(I)).filter(I=>!!I),m=1,p=c.length*(1+m),v=u.length*(2+m),E=c.map(I=>Te.createElement(At,{key:I.id,paddingRight:m},Te.createElement(mr,{color:J(I.name)},"\u25A0"))),S=u.map(I=>Te.createElement(At,{key:I.id,paddingRight:m},Te.createElement(mr,{color:Ct(I.name)},"@"+I.name.at(0)))),A=n?N.accent:o===g.MOVE?N.secondary:N.primary;return Te.createElement(At,{borderBottom:!0,justifyContent:"space-between"},Te.createElement(At,null,Te.createElement(re,{isSelected:n,placeholder:yd.dim.gray(r+1+" ")}),Te.createElement(mr,{wrap:"truncate",color:A},hd(t.title,e-p-v-14))),Te.createElement(At,null,E,S))};var Nd=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:a,mode:c})=>{let{renderedChildrenIndex:u}=$(),m=u[e.id]??[],p=`${e.title} (${m.length})`,v=3,E=o?1:4,S=r-v-(o?2:1),A=xe.createElement(pr,{borderStyle:"round",borderColor:N.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},xe.createElement(re,{isSelected:t}),xe.createElement(Ed,{bold:!0,color:t?N.accent:N.primary},p," ",e.readonly?"\u{1F512}":"")),I=(C,T)=>{let B=i&&a===T;return o?xe.createElement(ti,{key:C.id,index:T,width:n,ticket:C,isSelected:B,mode:c}):xe.createElement(ei,{key:C.id,width:n,ticket:C,isSelected:B})};return xe.createElement(pr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?N.accent:N.secondary,paddingRight:1,paddingLeft:1,height:r},A,xe.createElement(pr,{padding:o?1:0},m.length>0&&xe.createElement(sn,{selectedIndex:a,height:S,itemHeight:E},m.map(I)),xe.createElement(re,{isSelected:i&&a===-1})))},ni=xe.memo(Nd);import{Box as vr,Text as kd}from"ink";import _e,{useEffect as xr,useMemo as di}from"react";import Ye from"chalk";import ri from"string-width";import{decodeTime as Cd}from"ulid";var bd=(e,t)=>e+" ".repeat(Math.max(0,t-ri(e))),Id=(e,t)=>" ".repeat(Math.max(0,t-ri(e)))+e,Sd=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)})(),Ad=e=>{switch(e.action){case"move.node":{let t=b.getNode(e.payload.parent);return`to ${t?Ye.dim.bgBlack(` ${t.title} `):"unknown"} with rank ${e.payload.rank}`}case"tag.issue":{let t=x().tags[e.payload.tagId];return t?Ye.bgHex(J(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=x().tags[e.payload.tagId];return t?Ye.bgHex(J(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=x().contributors[e.payload.contributor];return t?Ye.hex(J(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=x().contributors[e.payload.contributor];return t?Ye.hex(J(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;default:return""}},Rd=e=>{let t=wo(Cd(e));return Ye.gray(Id(t,8))},Td=12,wd=e=>bd(`${e}`,Td),oi=e=>{let t=Rd(e.id),n=wd(e.userName),r=Sd(e.action),o=Ad(e),i=Ye.dim("\u203A"),a=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${a}`};var L={exit(){process.exit(0)},enterChildNode(){let e=x(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=w(t.id)[n];!r||t.context==="FIELD"||L.navigate({currentNode:r,selectedIndex:w(r.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=x();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=w(n.id),o=r.findIndex(({id:a})=>a===e.id),i=r.length===0?-1:o>=0?o:0;L.navigate({currentNode:n,selectedIndex:i})},navigateToNextItem:()=>ii(1),navigateToPreviousItem:()=>ii(-1),navigateToNextContainer:()=>si(1),navigateToPreviousContainer:()=>si(-1),navigate:({currentNode:e=x().currentNode,selectedIndex:t})=>{R({currentNodeId:e.id,selectedIndex:t})}},ii=e=>{let t=x(),n=w(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;L.navigate({selectedIndex:o})},si=e=>{let{currentNode:t,nodes:n,selectedIndex:r}=x();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=w(o.id),a=i.findIndex(E=>E.id===t.id);if(a<0)return;let c=i.at(a+e)??i.at(0);if(!c)return;let u=w(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),v=u.length?p:-1;L.navigate({currentNode:c,selectedIndex:v})};import{Box as dn,Text as Md}from"ink";import we from"react";var ai=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=$(),{title:o}=t,i=w(t.id).map(a=>{let c=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return b.getContributor(c)?.id;if(o==="Tags")return b.getTag(c)?.id}).filter(a=>!!a);return we.createElement(dn,{alignItems:"center",paddingTop:1},we.createElement(dn,{minWidth:12},we.createElement(re,{isSelected:n}),we.createElement(Md,{color:n?N.accent:N.secondary2},o,":")),we.createElement(dn,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,c)=>{let u=r.id===t.id&&c===e;return we.createElement(dn,{key:`${o}-${a}`,paddingRight:2,minHeight:1},we.createElement(re,{isSelected:u}),o==="Assignees"?we.createElement(st,{isSelected:u,id:a}):o==="Tags"?we.createElement(at,{isSelected:u,id:a}):null)})))};import{Box as cn,Text as gr}from"ink";import Me,{useEffect as Pd}from"react";var fr=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:c}=$(),u=E=>String(E).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];Pd(()=>{let E=[];return m.forEach((S,A)=>{let I=Ie(BigInt(A+1));if(!ge(I))return;let C=Y.text({id:`${e}-${A}`,name:`Line ${A+1}`,parentNodeId:e,rank:I.value,props:{value:S},readonly:!0}),T=b.createNode(C);ge(T)&&E.push(T.value.id)}),()=>E.forEach(b.deleteNode)},[e,n]);let p="\u2029",v=m.map((E,S)=>{let A=c.id===e&&a===S;return Me.createElement(cn,{key:`${e}-${S}`},Me.createElement(gr,{color:A?N.primary:N.secondary2,dimColor:!A},`${S+1} `.padStart(5,"\xA0")),Me.createElement(gr,{backgroundColor:A?"gray":""},u(E.length?zt(E,i-10):p)))});return Me.createElement(cn,{flexDirection:"column",paddingTop:1},Me.createElement(cn,null,Me.createElement(re,{isSelected:o}),Me.createElement(gr,{color:o?N.accent:N.secondary2},t)),Me.createElement(cn,{flexDirection:"row",borderStyle:"round",borderColor:N.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Me.createElement(sn,{scrollByOne:!0,children:v,height:r-2,selectedIndex:a,itemHeight:1})))};var Ld=e=>`${e}::log`,ci=e=>e==="Assignees"||e==="Tags",li=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=$(),o=process.stdout.columns||120,i=di(()=>Ld(e.id),[e.id]),a=di(()=>[...e.log].reverse().map(oi).join(`
6
- `),[e.log]);xr(()=>{if(b.getNode(i))return;let T=Ie(1n);if(d(T))return;let B={...Y.field(i,"Log",e.id,T.value,{value:a}),readonly:!0,childRenderAxis:"vertical"};return b.createNode(B),()=>{b.deleteNode(i)}},[i,e.id,a]),xr(()=>{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 c=r.id===e.id,u=r.id===i||r.parentNodeId===i;xr(()=>{u&&(n>=0||L.navigate({selectedIndex:0}))},[u,n]);let m=w(e.id);if(u){let C=b.getNode(i),B=t-3;return _e.createElement(vr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},C?_e.createElement(fr,{id:C.id,label:"Event log",text:C.props.value??"",selected:!1,maxWidth:o,height:B}):null)}let p=m.reduce((C,T)=>ci(T.title)||T.id===i?C+1:C,0),v=2,E=p*1,A=t-3-E-v,I=(C,T)=>ci(C.title)?_e.createElement(ai,{key:C.id,parent:C,selected:T,selectedIndex:n}):C.id===i?_e.createElement(vr,{key:C.id,paddingTop:1},_e.createElement(re,{isSelected:T}),_e.createElement(kd,{backgroundColor:N.secondary,color:T?N.accent:N.primary}," History \u203A\u203A ")):C.title==="Description"?_e.createElement(fr,{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(vr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((C,T)=>I(C,c&&n===T)))};var Fd=({swimlanes:e,currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:a,width:c})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,p=u===P.BOARD||u===P.SWIMLANE,v=u===P.TICKET?t:r.find(C=>C.context===P.TICKET),E=Math.floor(c/3),S=Math.floor(c/Math.max(e.length,1)),A=Math.min(S,E),I=i==="dense";return ln.createElement(Dd,{flexDirection:"row",height:a},p&&e.map((C,T)=>{let B=t.id===C.id,De=B?n:-1,Fe=t.context===P.BOARD&&n===T;return ln.createElement(ni,{key:C.id,height:a,width:A,swimlane:C,isSelected:Fe,isDense:I,isFocused:B,listSelectedIndex:De,mode:o})}),m&&v&&ln.createElement(li,{height:a,ticket:v}))},un=ln.memo(Fd);import{render as Ud}from"ink";import{Writable as $d}from"node:stream";var Rt=e=>String(e).padStart(2,"0"),_d=e=>{let t=e.getUTCFullYear(),n=Rt(e.getUTCMonth()+1),r=Rt(e.getUTCDate()),o=Rt(e.getUTCHours()),i=Rt(e.getUTCMinutes()),a=Rt(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${a}`},Wd=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",jd=async(e,{width:t,height:n})=>{let r="",o=new $d({write(a,c,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=Ud(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,""),mi=async()=>{let{currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:r,mode:o,renderedChildrenIndex:i}=x(),a=n.find(T=>T.context==="BOARD");if(!a)return s("No board found to export");let c=120,u=40,m=await jd(Bd.createElement(un,{height:u,width:c,swimlanes:(i[a.id]??[]).filter(T=>T!==void 0&&et(T)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:r,mode:o}),{width:c,height:u});if(!m)return s("Failed to render board export");let p=Oe(process.cwd());if(d(p))return s("Unable to export, epiq root not found");let v=new Date,E=_d(v),S=`board_${Wd(a.title)}_${E}.md`,A=Jr(p.value);ui.mkdirSync(A,{recursive:!0});let I=Od.join(A,S),C=`# Board - ${a.title}
2
+ import so from"chalk";import{render as wl}from"ink";import Tl from"meow";import Ml from"react";import{Box as Qe}from"ink";import X from"react";import Nt from"node:fs";import{ulid as fa}from"ulid";import{z as Qt}from"zod";var Se={None:"none",Success:"success",Fail:"fail"},s=e=>({status:Se.Fail,message:e,value:null}),l=(e,t)=>({status:Se.Success,message:e,value:t}),d=e=>e.status==="fail",he=e=>e.status==="success";import yt from"node:fs";import Re from"node:path";var rn=process.env.IS_LOCAL==="true",Ae=".epiq",pe=".epiq-global",Xt="events",pa="project.json",lo=e=>Re.join(e,Ae),Jt=e=>Re.join(e,Ae),Zt=e=>Re.join(Jt(e),pa),Et=e=>Re.join(Jt(e),Xt),ga=e=>{let t=Re.join(e,Ae);return yt.existsSync(t)&&yt.statSync(t).isDirectory()},nn=e=>{let t=Zt(e);return yt.existsSync(t)&&yt.statSync(t).isFile()},Be=e=>{let t=Re.resolve(e);for(;;){if(ga(t))return l("Resolved closest .epiq root",t);let r=Re.dirname(t);if(r===t)return s("No .epiq directory found in any parent");t=r}},Ee=e=>{let t=Re.resolve(e);for(;;){if(nn(t))return l("Resolved closest epiq project root",t);let r=Re.dirname(t);if(r===t)return s("No .epiq/project.json found in any parent");t=r}},uo=e=>{let t=Et(e);try{return yt.mkdirSync(t,{recursive:!0}),l("Resolved events dir",t)}catch(r){return s(r instanceof Error?`Failed to ensure events dir: ${r.message}`:"Failed to ensure events dir")}};var va="epiq/eventlog",xa=Qt.object({projectId:Qt.string().min(1),stateBranch:Qt.string().min(1),createdAt:Qt.iso.datetime()}),mo=()=>({projectId:fa(),stateBranch:va,createdAt:new Date().toISOString()}),Oe=e=>{let t=Zt(e);if(!Nt.existsSync(t))return s("Missing .epiq/project.json");try{let r=Nt.readFileSync(t,"utf8"),n=JSON.parse(r),o=xa.safeParse(n);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(r){return s(r instanceof Error?`Failed to read .epiq/project.json: ${r.message}`:"Failed to read .epiq/project.json")}},po=e=>{let t=Oe(e);return d(t)?s(t.message):l("Read projectId",t.value.projectId)},go=({repoRoot:e,fileContents:t})=>{let r=Jt(e),n=Zt(e);try{if(Nt.mkdirSync(r,{recursive:!0}),Nt.existsSync(n)){let o=Oe(e);return d(o)?s(o.message):l("Project already initialized",null)}return Nt.writeFileSync(n,JSON.stringify(t,null,2)+`
3
+ `,"utf8"),l("Created project.json",null)}catch(o){return s(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var er={autoSync:!1,preferredEditor:null,userName:null,userId:null},le=()=>er,tt=e=>(er={...er,...e},er);var rt=()=>{let e=le(),t=!!e.userName?.trim(),r=!!e.preferredEditor?.trim();return{isSetup:r&&t,hasPreferredEditor:r,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},fo=()=>{let e=Ee(process.cwd());if(d(e))return s("Unable to determine if repository is initialized");let t=Oe(e.value);return he(t)};var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};var Ne=(e,t)=>{let r=e.find(n=>n.context===t);return r!==void 0?l("Found node",r):s("Unable to find node in breadcrumb")};import{useSyncExternalStore as Yc}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function on(e){return e.context==="WORKSPACE"}function ge(e){return e.context==="TICKET"}function vo(e){return e.context==="FIELD"}var nt=e=>e.context==="SWIMLANE",xo=e=>e.context==="BOARD";function tr(e,t){let r=Math.min(e.length,t.length),n=0;for(;n<r&&e[n]===t[n];)n++;return n}var rr=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",sn=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var ho=e=>{let t=new Map;for(let r of e)for(let n=1;n<=r.length;n++){let o=r.slice(0,n),i=t.get(o);i?i.push(r):t.set(o,[r])}return t},yo=(e,t)=>t?e.get(t)??[]:[];var Eo=new WeakMap,ha=e=>{let t=Eo.get(e);return t||(t=ho(e),Eo.set(e,t)),t};var No=({wordList:e,inputToMatch:t,overlapThreshold:r=1})=>{let n=t.toLowerCase();return yo(ha(e),n).filter(i=>tr(n,i)>=r)};var ya={hint:"",hints:[],overlap:0,remainder:""},Co=({inputToMatch:e,lastWord:t,isLastWordCompleted:r},n)=>{if(r||e==="")return ya;let o=No({wordList:n,inputToMatch:e,overlapThreshold:1});return Ea(t,o)},Ea=(e,t)=>{let r=t[0]??"",n=tr(e.toLowerCase(),r.toLowerCase()),[o,i]=r.split(":"),a=n<(o??"").length,c=!!i,p=(c&&a?o:r)+(c&&a?":":" "),v=p.slice(n);return{hint:p,hints:t,overlap:n,remainder:v}};var Io=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var Q={workspace:(e,t,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,r,n,o=!1)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:r,readonly:o,log:[]}),swimlane:(e,t,r,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:r,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:r,rank:n,props:o={},childRenderAxis:i="horizontal",isVirtual:a=!1})=>({id:e,title:t,rank:n,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:i,parentNodeId:r,readonly:!1,log:[],isVirtual:a}),ticket:(e,t,r,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:r,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:r,rank:n,props:o={},readonly:i=!0,isVirtual:a=!0})=>({id:e,title:t,rank:n,isDeleted:!1,props:o,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:r,readonly:i,log:[],isVirtual:a})};import{ulid as Ia}from"ulid";var qe=24n,Na=qe*4n,ze=(1n<<Na)-1n,Ca=/^[0-9a-f]+$/;function bo(e){return!e||!Ca.test(e)?s(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function we(e,t=qe){if(e<0n)return s("Negative rank not allowed");let r=e.toString(16);return l("Converted bigint to hex rank",r.padStart(Number(t),"0"))}function z(e,t){if(!e&&!t)return we(ze/2n,qe);let r=e?bo(e):l("Resolved lower bound",0n);if(d(r))return r;let n=t?bo(t):l("Resolved upper bound",ze);if(d(n))return n;let o=r.value,i=n.value;if(i<=o)return we(ze/2n,qe);let a=(o+i)/2n;return a===o||a===i?s("No rank space available between neighbors"):we(a,qe)}function So(){return we(ze/2n,qe)}function Ro(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),r=[];for(let n=0;n<e;n++){let o=ze*BigInt(n+1)/(t+1n),i=we(o,qe);if(d(i))return i;r.push(i.value)}return l("Resolved evenly spaced ranks",r)}var an=(e,t)=>{let r=F(e),n=Ro(r.length);if(d(n))return n;let o={};for(let i=0;i<r.length;i++){let a=r[i],c=n.value[i];if(!a||!c)return s("Unable to assign rebalance rank");o[a.id]=c}return l("Created rebalance event",{id:Ia(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var G={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History"};var ba=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[Te,nr]=ba;var k=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Sa={"init.workspace":e=>{let{id:t,name:r,rank:n}=e.payload,o=Q.workspace(t,r,n),i=bt(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):on(a.value)?l("Workspace initialized",{action:e.action,result:a.value}):s("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:r,rank:n}=e.payload,o=Q.workspace(t,r,n),i=b.createNode(o);return d(i)?k(i.message??"Failed to add workspace",e):on(i.value)?l("Added workspace",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.board":e=>{let{id:t,name:r,parent:n,rank:o}=e.payload,i=b.createNode(Q.board(t,r,n,o));return d(i)?k(i.message??"Unable to create board",e):xo(i.value)?l("Added board",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:r,parent:n,rank:o}=e.payload,i=b.createNode(Q.swimlane(t,r,n,o));return d(i)?k(i.message??"Unable to create swimlane",e):nt(i.value)?l("Added swimlane",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:r,parent:n,rank:o}=e.payload,i=b.createNode(Q.ticket(t,r,n,o));return d(i)?k(i.message??"Unable to create issue",e):ge(i.value)?l("Added issue",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.field":e=>{let{id:t,name:r,parent:n,val:o,rank:i}=e.payload,a=b.createNode(Q.field({id:t,name:r,parentNodeId:n,rank:i,props:{value:o},childRenderAxis:r.includes(G.DESCRIPTION)?"vertical":"horizontal"}));return d(a)?k(a.message??`Unable to create field: ${r}`,e):vo(a.value)?l("Added field",{action:e.action,result:a.value}):s("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:r}=e.payload;if(!b.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=b.renameNode(t,r);return d(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,r=b.tombstoneNode(t);return d(r)?k(r.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:r.value})},"create.tag":e=>{let{id:t,name:r}=e.payload,n=b.createTag({id:t,name:r});return d(n)?k(n.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:n.value})},"create.contributor":e=>{let{id:t,name:r}=e.payload,n=b.createContributor({id:t,name:r});return d(n)?k(n.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:n.value})},"tag.issue":e=>{let{id:t,target:r,tagId:n,rank:o}=e.payload,i=b.tag(r,n,t,o);return d(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:r}=e.payload,n=b.untag(t,r);return d(n)?k(n.message??"Unable to untag ",e):l("Issue untagged",{action:e.action,result:n.value})},"assign.issue":e=>{let{id:t,contributor:r,target:n,rank:o}=e.payload,i=b.assign(n,r,t,o);return d(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:r}=e.payload,n=b.unassign(t,r);return d(n)?k(n.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:n.value})},"move.node":e=>{let{id:t,parent:r,rank:n}=e.payload,o=b.moveNodeToRank({id:t,parentId:r,rank:n});return d(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:r}=e.payload,n=b.editValue(t,r);return d(n)?k(n.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:n.value})},"close.issue":e=>{let{id:t,parent:r,rank:n}=e.payload,o=b.getNode(t);if(!o)return k("Unable to locate issue",e);if(!ge(o))return k("Can only close issues",e);let i=b.getNode(Te);if(!i)return k("Unable to locate target swimlane",e);if(r!==i.id)return k("Close target must be closed swimlane",e);let a=b.moveNodeToRank({id:t,parentId:r,rank:n});return d(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:r,rank:n}=e.payload,o=b.getNode(t);if(!o)return k("Unable to locate issue",e);if(!ge(o))return k("Can only reopen issues",e);let i=b.getNode(Te);if(!i)return k("Unable to locate closed swimlane",e);if(r===i.id)return k("Cannot reopen issue into closed swimlane",e);if(!b.getNode(r))return k("Reopen parent no longer exists",e);let c=b.moveNodeToRank({id:t,parentId:r,rank:n});return d(c)?k(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,r=b.lockNode(t);return d(r)?k(r.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:r.value})},"rebalance.children":e=>{let{parent:t,ranks:r}=e.payload;for(let[n,o]of Object.entries(r)){let i=b.getNode(n);if(!i)return k(`Unable to locate node ${n}`,e);if(i.parentNodeId!==t)return k(`Node ${n} 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 l("Rebalanced children",{action:e.action,result:{parent:t}})}},Ra=(e,t)=>{let r=b.getNode(e);r&&b.updateNode({...r,log:[...r.log??[],t]})},Aa=e=>{switch(e.action){case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"delete.node":case"move.node":case"close.issue":case"reopen.issue":return[e.payload.id];case"edit.description":let t=[e.payload.id],r=x().nodes[e.payload.id]?.parentNodeId;return r&&t.push(r),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 Ct(e,t=!1){let r=Sa[e.action](e);if(d(r))return r;t||([...new Set(Aa(e))].forEach(a=>Ra(a,e)),ue(a=>({...a,eventLog:[...a.eventLog,e]})));let n=e.userId,o=e.userName;return!n?.length||!o?.length?k("Invalid user ID format",e):(b.createContributor({name:o,id:n}),r)}var It=e=>e.map(t=>Ct(t));import Ba from"node:fs";import Oa from"node:path";import{decodeTime as Ua,monotonicFactory as $a}from"ulid";import{z as Rt}from"zod";import or from"node:fs";import cn from"node:path";import{decodeTime as wa}from"ulid";import{z as dn}from"zod";var Ta=dn.object({userId:dn.string().min(1).default("unknown"),userName:dn.string().min(1).default("unknown")}),Ma=e=>{let[t,r]=cn.basename(e,".jsonl").split("."),n=Ta.safeParse({userId:t,userName:r});return n.success?l("Parsed event file actor",n.data):s(`Invalid event file name ${cn.basename(e)}: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Pa=e=>{let t=Object.keys(e).filter(r=>r!=="id"&&r!=="v");return t.length!==1?s(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?s("Invalid persisted event: action key is missing or invalid"):l("Resolved persisted action",t[0])},ka=(e,t)=>t in e,La=({id:e,action:t,payload:r,userId:n,userName:o})=>({id:e,action:t,payload:r,userId:n,userName:o}),Da=e=>{let{userId:t,userName:r,...n}=e,o=Pa(n);if(d(o))return s(o.message);let i=o.value,a=e.id?.[0];return a?ka(n,i)?l("Decoded persisted event",La({id:a,action:i,payload:n[i],userId:t,userName:r})):s(`Persisted event is missing payload for action: ${i}`):s("Persisted event is missing id")},ir=e=>{if(!or.existsSync(e))return l("Event file missing",[]);let t=Ma(e);if(d(t))return s(t.message);let r=or.readFileSync(e,"utf8"),n=[];for(let o of r.split(`
4
+ `)){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{return s(`Failed to parse event JSON from ${e}: ${i}`)}let c=ln(a);if(d(c))return s(`${c.message} in ${e}: ${i}`);n.push({...c.value,userId:t.value.userId,userName:t.value.userName})}return l("Parsed persisted events file",n)};function Ao(e){let t=Et(e);if(!or.existsSync(t))return l("No events found",[]);let r=or.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>cn.join(t,o)),n=[];for(let o of r){let i=ir(o);if(d(i))return s(i.message);n.push(...i.value)}return l("All events loaded",Fa(n))}function St(e){let t=Ao(e);if(d(t))return s(t.message);let r=[];for(let n of t.value){let o=Da(n);if(d(o))return s(`Failed to decode event ${n.id?.[0]??"<unknown>"}: ${o.message}`);r.push(o.value)}return l("Loaded merged events",r)}function wo(e=process.cwd()){let t=Ao(e);return d(t)?s(t.message):l("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Fa=e=>{let t=new Map,r=new Map;for(let m of e){let p=m.id[0],v=m.id[1]??null;t.set(p,m);let y=r.get(v)??[];y.push(m),r.set(v,y)}for(let m of r.values())m.sort((p,v)=>p.id[0].localeCompare(v.id[0]));let n=[],o=new Set,i=m=>{let p=m.id[0];if(o.has(p))return;n.push(m),o.add(p);let v=r.get(p)??[];for(let y of v)i(y)},a=r.get(null)??[];for(let m of a)i(m);let c=e.filter(m=>{let p=m.id[0],v=m.id[1]??null;return!o.has(p)&&v!==null&&!t.has(v)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of c)i(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)i(m);return n},To=(e,t)=>{let r=e.findIndex(n=>{try{return wa(n.id)>t}catch{return!0}});return r===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,r),unappliedEvents:e.slice(r)}};var Mo=e=>({action:e.action,payload:e.payload});var ko=1,Po=$a(),_a=Rt.tuple([Rt.string().min(1),Rt.string().min(1).nullable()]),Wa=Rt.looseObject({v:Rt.literal(ko),id:_a}),ln=e=>{let t=Wa.safeParse(e);return t.success?l("Parsed persisted event",t.data):s(`Invalid persisted event: ${t.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},sr=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",ee=()=>{let{userName:e,userId:t}=le();return e?t?e.trim()?l("Successfully resolved actor ID",{userId:sr(t),userName:sr(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},At=({userId:e,userName:t})=>`${sr(e)}.${sr(t)}.jsonl`,ja=(e,{userId:t,userName:r})=>{let n=At({userId:t,userName:r});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(n))return s(`Invalid event log file name: ${n}`);let i=Oa.join(Et(e),n);return l("Successfully resolved event log path",i)},Ha=(e,t)=>{let r={[e.action]:e.payload,v:ko,id:t};return ln(r)};function ar({event:e,rootDir:t=process.cwd()}){try{let r=Be(t);if(d(r))return r;let n=uo(r.value);if(d(n))return n;let o=ja(r.value,{userId:e.userId,userName:e.userName});if(d(o))return o;let i=wo(r.value);if(d(i))return s(i.message);let a=i.value?Po(Math.max(Date.now(),Ua(i.value)+1)):Po(),c=Ha(Mo(e),[a,i.value]);return d(c)?s(c.message):(Ba.appendFileSync(o.value,`${JSON.stringify(c.value)}
5
+ `,"utf8"),l("Event persisted",{path:o.value,entry:c.value}))}catch(r){let n=r instanceof Error?r.message:"Unknown persist error";return s(`Failed to persist event: ${n}`)}}function K(e){let t=Ct(e);if(t.status!==Se.Success)return t;let r=ar({event:e});return d(r)?r:t}function dr(e){return e.map(t=>K(t))}var Lo=e=>un(F(e),{at:"end"}),un=(e,t={at:"end"})=>{let r=n=>d(n)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:n.value,needsRebalance:!1});if(e.length===0)return r(z(void 0,void 0));switch(t.at){case"start":{let n=e[0];return n?r(z(void 0,n.rank)):s("Unable to resolve first sibling")}case"end":{let n=e[e.length-1];return n?r(z(n.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let n=Do(e,t.sibling);if(n<0)return s("Sibling not found");let o=n>0?e[n-1]:void 0,i=e[n];return i?r(z(o?.rank,i.rank)):s("Sibling not found")}case"after":{let n=Do(e,t.sibling);if(n<0)return s("Sibling not found");let o=e[n],i=n<e.length-1?e[n+1]:void 0;return o?r(z(o.rank,i?.rank)):s("Sibling not found")}}},F=e=>Object.values(x().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,r)=>t.rank.localeCompare(r.rank)),Do=(e,t)=>e.findIndex(r=>r.id===t),Fo=(e,t,r={at:"end"})=>un(F(t).filter(n=>n.id!==e),r),ot=(e,t,r,n)=>{let o=Fo(t,e,r);if(d(o))return o;if(!o.value.needsRebalance)return l("Resolved rank",o.value.rank);let i=an(e,n);if(d(i))return i;let a=K(i.value);if(d(a))return a;let c=Fo(t,e,r);return d(c)?c:c.value.needsRebalance?s("Rank rebalance failed to create space"):l("Resolved rank after rebalance",c.value.rank)},it=(e,t)=>{let r=Lo(e);if(d(r))return r;if(!r.value.needsRebalance)return l("Resolved rank",r.value.rank);let n=an(e,t);if(d(n))return n;let o=K(n.value);if(d(o))return o;let i=Lo(e);return d(i)?i:i.value.needsRebalance?s("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)};var Ue=(e,t)=>{let{nodes:r}=x(),n=r[e];if(!n)return s("Node not found");if(n.context===t)return l("Resolved ancestor node",n);let o=n.parentNodeId?r[n.parentNodeId]:void 0;for(;o;){if(o.context===t)return l("Resolved ancestor node",o);o=o.parentNodeId?r[o.parentNodeId]:void 0}return s(`No ancestor found for context: ${t}`)},pn=(e,t)=>{let{nodes:r}=x(),n=r[e];for(;n?.parentNodeId;){if(n.parentNodeId===t)return!0;n=r[n.parentNodeId]}return!1},mn=(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){ue(t=>{let r={...t.nodes};return delete r[e],{...t,nodes:r}})},editValue(e,t){let{nodes:r}=x(),n=r[e];if(!n)return s("Edit target node not found");let o=mn(n,"edit");if(o)return o;let i={...n,props:{...n.props,value:t}};return this.updateNode(i),l("Issue description updated",{md:t})},renameNode(e,t){let r=this.getNode(e);if(!r)return s("Rename target node not found");let n=mn(r,"rename");if(n)return n;let o={...r,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=x();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=x();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return F(e).find(r=>r.title===t)},moveNodeToRank({id:e,parentId:t,rank:r}){let{rootNodeId:n}=x(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(n===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let a=mn(o,"move");if(a)return a;if(pn(t,e))return s("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:r};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,currentNodeId:r,rootNodeId:n}=x(),o=this.getNode(e);if(!o)return s("Node not found");if(n===e)return s("Cannot delete root node");let i=new Set,a=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 c={...structuredClone(t)};for(let u of i){if(!c[u])return s("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return r?(A({nodes:c}),l("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=ue(r=>({...r,contributors:{...r.contributors,[e.id]:e}}));return d(t)?s("Unable to create contributor"):l("Created contributor",e)},assign(e,t,r,n){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=Q.field({id:r,name:o.name,parentNodeId:a.id,rank:n,props:{value:t}}),m=this.createNode(u);return d(m)?m:l("Assigned contributor",u)},createTag(e){let t=ue(r=>({...r,tags:{...r.tags,[e.id]:e}}));return d(t)?s("Could not create tag"):l("Tag created",e)},tag(e,t,r,n){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=Q.field({id:r,name:o.name,parentNodeId:a.id,rank:n,props:{value:t}}),m=this.createNode(u);return d(m)?m:l("Tag added",u)},untag(e,t){let r=this.getTag(t),n=this.getNode(e);if(!r)return s("Unable to remove tag, missing tag");if(!n)return s("Unable to remove tag, missing target");let o=this.getFieldByTitle(n.id,"Tags");if(!o)return s("Unable to locate tags field");let i=F(o.id).find(c=>c.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 r=this.getContributor(t),n=this.getNode(e);if(!r)return s("Unable to unassign, missing contributor");if(!n)return s("Unable to unassign, missing target");let o=this.getFieldByTitle(n.id,"Assignees");if(!o)return s("Unable to locate assignees field");let i=F(o.id).find(c=>c.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=ue(r=>({...r,nodes:{...r.nodes,[e.id]:e}}));return d(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 r={...t,readonly:!0},n=ue(o=>({...o,nodes:{...o.nodes,[e]:r}}));return d(n)?s(n.message):l("Locked node",r)},updateNode(e){let t=ue(r=>({...r,nodes:{...r.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return x().contributors[e]},getTag(e){return x().tags[e]},getNode(e){return x().nodes[e]},getSiblings(e){return F(e)}};var te={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"},N={accent:te.cyan,accent2:te.magenta,primary:te.white,secondary:te.grayDark,secondary2:te.grayLight,gray:te.gray,green:te.green,yellow:te.yellow,red:te.red};var E={red:te.red,yellow:te.yellow,green:te.green,blue:te.blue,magenta:te.magenta,cyan:te.cyan},st={urgent:E.red,critical:E.red,important:E.red,blocker:E.red,asap:E.red,immediate:E.red,fail:E.red,failure:E.red,broken:E.red,bug:E.red,error:E.red,incident:E.red,outage:E.red,production:E.red,crash:E.red,security:E.red,warning:E.yellow,warn:E.yellow,risky:E.yellow,risk:E.yellow,attention:E.yellow,pending:E.yellow,review:E.yellow,"needs-review":E.yellow,qa:E.yellow,testing:E.yellow,test:E.yellow,validate:E.yellow,verification:E.yellow,staging:E.yellow,check:E.yellow,"follow-up":E.yellow,followup:E.yellow,waiting:E.yellow,blocked:E.yellow,hold:E.yellow,done:E.green,complete:E.green,completed:E.green,success:E.green,ok:E.green,stable:E.green,resolved:E.green,fixed:E.green,closed:E.green,merged:E.green,released:E.green,deployed:E.green,approved:E.green,verified:E.green,working:E.green,healthy:E.green,pass:E.green,passing:E.green,info:E.blue,information:E.blue,note:E.blue,docs:E.blue,documentation:E.blue,doc:E.blue,guide:E.blue,help:E.blue,explanation:E.blue,detail:E.blue,details:E.blue,context:E.blue,design:E.blue,discussion:E.blue,proposal:E.blue,idea:E.blue,feature:E.magenta,enhancement:E.magenta,improvement:E.magenta,refactor:E.magenta,refactoring:E.magenta,cleanup:E.magenta,optimize:E.magenta,optimization:E.magenta,perf:E.magenta,performance:E.magenta,upgrade:E.magenta,migration:E.magenta,modernize:E.magenta,debt:E.magenta,todo:E.cyan,next:E.cyan,planned:E.cyan,plan:E.cyan,future:E.cyan,backlog:E.cyan,investigate:E.cyan,explore:E.cyan,prototype:E.cyan};var Bo=(e,t)=>{let n=T(e.id).find(o=>o.title===t);return n?T(n.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},gn=e=>Bo(e,"Tags").map(t=>b.getTag(t)).filter(t=>!!t),cr=()=>{let{breadCrumb:e,selectedNode:t}=x(),r=[...e,t].find(n=>n?.context==="TICKET");return!r||!ge(r)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",gn(r)??[])},lr=()=>{let{breadCrumb:e,selectedNode:t}=x(),r=[...e,t].find(n=>n?.context==="TICKET");return!r||!ge(r)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",fn(r)??[])},fn=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 Ka=/^(\d+)(h|d|w|mo|y)$/,Va=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,qa=({year:e,month:t,day:r,hour:n=0,minute:o=0})=>{let i=new Date(e,t-1,r,n,o);return i.getFullYear()===e&&i.getMonth()===t-1&&i.getDate()===r&&i.getHours()===n&&i.getMinutes()===o},za=(e,t=new Date)=>{let r=e.match(Ka);if(!r)return null;let[,n,o]=r,i=Number(n);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}},Ga=e=>{let t=e.match(Va);if(!t)return null;let[,r,n,o,i,a]=t,c=Number(r),u=Number(n),m=Number(o),p=i?Number(i):0,v=a?Number(a):0;return qa({year:c,month:u,day:m,hour:p,minute:v})?new Date(c,u-1,m,p,v):null},ur=e=>{let t=e.trim().toLowerCase();return za(t)??Ga(t)},Oo=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Ya=[{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}],Uo=(e=Ya)=>{let t=[];for(let{unit:r,from:n,to:o}of e)for(let i=n;i<=o;i++)t.push(`${i}${r}`);return t};var Xa=["BOARD","TICKET","SWIMLANE"],Ge=[f.SYNC,f.HELP,f.EXPORT,f.SET_VIEW,f.SET_EDITOR,f.SET_USERNAME],mr=[f.NEW,f.RENAME,f.DELETE,f.MOVE],pr=[f.TAG,f.UNTAG,f.ASSIGN,f.UNASSIGN,f.CLOSE_ISSUE,f.RE_OPEN_ISSUE,f.SET_DESCRIPTION],$o=[f.FILTER,f.PEEK],Ja={WORKSPACE:[...Ge,...mr],BOARD:[...$o,...Ge,...mr],SWIMLANE:[...$o,...Ge,...mr,...pr],TICKET:[...Ge,...mr,...pr],FIELD:[...Ge,...pr],FIELD_LIST:[...Ge,...pr],TEXT:[...Ge]},Za=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Qa=()=>{let{currentNode:e,selectedNode:t,readOnly:r}=x();if(!rt().isSetup)return[f.HELP,f.SET_EDITOR,f.SET_USERNAME];if(!fo())return[f.HELP,f.INIT];if(r)return[f.HELP,f.PEEK,f.EXPORT,f.SET_VIEW];let o=e.context??"WORKSPACE",i=t?.context,a=i&&Xa.includes(i);return Ja[o].filter(c=>c===f.RENAME||c===f.DELETE||c===f.MOVE?a:!0)},Y=e=>{let{currentNode:t}=x(),r=t.context??"WORKSPACE";return{[f.NONE]:Qa(),[f.EXIT]:["confirm"],[f.EXPORT]:[],[f.SYNC]:[],[f.INIT]:[],[f.HELP]:[],[f.PEEK]:[...Uo(),"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]:[...Io],[f.TAG]:[...new Set([...Object.keys(st),...b.getExistingTags()])],[f.UNTAG]:[...cr()?.value?.map(({name:o})=>o)??[]],[f.UNASSIGN]:[...lr()?.value?.map(({name:o})=>o)??[]],[f.ASSIGN]:b.getExistingAssignees(),[f.RENAME]:[],[f.NEW]:Za(r)}[e]??[]};import dt from"chalk";import{decodeTime as _o}from"ulid";var Wo=e=>{let t=Date.now()-e,r=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:n,ms:o}of r){let i=Math.floor(t/o);if(i>=1)return`${i}${n} ago`}return"just now"},jo=e=>{let t=r=>String(r).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},gr=e=>{try{return l("Decoded date",new Date(_o(e)))}catch(t){return s("Decoding failed + "+t.message)}},vn=e=>{if(!e?.id)return null;try{return _o(e.id)}catch{return null}};import at from"chalk";var hn={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ed=(e,t,r)=>Math.max(t,Math.min(r,e)),xn=(e,t,r)=>e+(t-e)*r,Ho=e=>{let t=0;for(let r=0;r<e.length;r++)t=t*31+e.charCodeAt(r)>>>0;return t},td=(e,t,r)=>{let n=t/100,o=r/100,i=(1-Math.abs(2*o-1))*n,a=e/60,c=i*(1-Math.abs(a%2-1)),u=0,m=0,p=0;a>=0&&a<1?(u=i,m=c):a>=1&&a<2?(u=c,m=i):a>=2&&a<3?(m=i,p=c):a>=3&&a<4?(m=c,p=i):a>=4&&a<5?(u=c,p=i):(u=i,p=c);let v=o-i/2;return[Math.round((u+v)*255),Math.round((m+v)*255),Math.round((p+v)*255)]},rd=([e,t,r])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}`,nd=(e,t,r)=>[Math.round(xn(e[0],t[0],r)),Math.round(xn(e[1],t[1],r)),Math.round(xn(e[2],t[2],r))],wt=e=>{let r=Ho(e)%360,n=td(r,hn.stringColor.saturation,hn.stringColor.lightness);return rd(n)},od=e=>{let t=hn.gradient.stops,r=ed(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let n=t.length-1,o=r*n,i=Math.min(Math.floor(o),n-1),a=o-i;return nd(t[i],t[i+1],a)},fr=e=>Ho(e.toLowerCase().trim())/4294967295,Ko=e=>{let t=fr(e);return od(t)},id=e=>{let[t,r,n]=Ko(e);return{normal:o=>at.bgRgb(t,r,n).black(o),cursor:o=>at.bgRgb(t,r,n).white.bold(o)}},yn=e=>{let[t,r,n]=Ko(e);return{fg:o=>at.rgb(t,r,n)(o),fgCursor:o=>at.rgb(t,r,n).inverse(o),bg:o=>at.bgRgb(t,r,n).black(o),bgCursor:o=>at.bgRgb(t,r,n).white.bold(o)}},En=e=>id(e).normal(` ${e} `),re=(e,t=st)=>{let n=(o=>o.toLowerCase().trim())(e);return n&&t[n]?t[n]:wt(n)};var Me={None:"none",Invalid:"invalid",Valid:"valid"};var sd=["BOARD","TICKET","SWIMLANE"],Nn=()=>{let e=x().selectedNode;return e?.context?sd.includes(e?.context)?W():U({message:"Command not available in this context"}):U({message:"Missing target context"})},ie="<ENTER> to confirm",W=(e="",t=[])=>({message:e,validity:Me.Valid,completionWordList:t}),U=({message:e,completionWordList:t=[]})=>({validity:Me.Invalid,message:e,completionWordList:t}),Mt=e=>e.length===0,$e=({prefix:e="",wordList:t,postfix:r="",noOfHints:n=100,inputString:o,minLengthForHints:i=1})=>{let u=[...t.filter(Boolean).filter(p=>p.startsWith(o.trim()))].sort((p,v)=>fr(p)-fr(v)).slice(0,n).map(En),m=u.length>i?u.join(" "):"";return m?`${e}${m}${r}`:""},Cn=({modifier:e})=>{let t="confirm";return e===t?W(ie):U({message:Mt(e)?`if you are certain, enter ${En(t)}`:"",completionWordList:[t]})},ad=({list:e,hint:t})=>({modifier:r})=>e.includes(r)?W(ie):U({message:Mt(r)?t:""}),dd=({list:e,hint:t,onValue:r})=>({modifier:n,inputString:o})=>e.includes(n)?o.trim().length<1?U({message:r}):W():U({message:Mt(n)?t:""}),Tt=({hint:e})=>({modifier:t,inputString:r})=>Mt(t)&&Mt(r)?U({message:e,completionWordList:[]}):W(ie),cd={[f.EXPORT]:()=>W(ie+", and create export markdown file"),[f.PEEK]:e=>{let t=e.modifier;if(t==="now")return W(ie);let r={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(ie);let n=ur(t);if(!t||!n)return U(r);let o=Ne(x().breadCrumb,"BOARD");if(d(o))return U({message:"Command is not applicable in this context"});let i=gr(o.value.id);return d(i)?U({message:"Unable to peek: board id is not a valid ULID"}):Oo({date:n,horizonDate:i.value})?W(ie):U({message:dt.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[f.EXIT]:()=>W(ie+" and exit the application"),[f.INIT]:()=>W(ie),[f.FILTER]:e=>{if(e.modifier==="clear")return W();let t=a=>Y(f.FILTER).includes(a);if(!e.modifier||!t(e.modifier??""))return U({message:$e({wordList:Y(f.FILTER),inputString:e.inputString}),completionWordList:Y(f.FILTER)});let n=Object.values(x().tags).map(a=>a.name),o=Object.values(x().contributors).map(a=>a.name),i=e.modifier==="tag"?n: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=Y(f.NONE),r=/^[A-Za-z_]+:/g,n=e.inputString.match(r);return n&&n.length?t=[...t.filter(o=>o.trim().match(r))]:t=[...new Set(t.flatMap(o=>o.match(r)?.join("").replace(":","")??o))],e.command?W():U({message:$e({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[f.NEW]:e=>dd({list:Y(f.NEW),hint:$e({wordList:Y(f.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[f.SET_DESCRIPTION]:()=>W(ie),[f.HELP]:()=>W(ie),[f.RENAME]:()=>{let e=Nn();return e.validity==="invalid"?e:W(ie)},[f.DELETE]:e=>{let t=Nn();return t.validity==="invalid"?t:Cn(e)},[f.CLOSE_ISSUE]:e=>Cn(e),[f.RE_OPEN_ISSUE]:e=>Cn(e),[f.MOVE]:e=>{let t=Nn();return t.validity==="invalid"?t:Tt({hint:$e({prefix:"hey hacker! These commands are blocked for you... ",wordList:Y(f.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[f.TAG]:e=>{let t=b.getExistingTags().map(r=>` ${dt.bgHex(re(r))(" "+r+" ")} `).slice(0,10);return Tt({hint:"tag name like... "+t.join("")})(e)},[f.UNTAG]:e=>{let t=cr();if(d(t))return U({message:"Invalid untag target",completionWordList:[]});let r=t.value.map(({name:n})=>n).map(n=>` ${dt.bgHex(re(n))(" "+n+" ")} `).slice(0,10);return r.length?Tt({hint:" ... "+r.join("")})(e):U({message:"Issue has not tags",completionWordList:[]})},[f.ASSIGN]:e=>{let t=b.getExistingAssignees().map(r=>` ${dt.bgHex(re(r))(" "+r+" ")} `).slice(0,10);return Tt({hint:"assign to... "+t.join("")})(e)},[f.UNASSIGN]:e=>{let t=lr();if(d(t))return U({message:"Invalid unassign target",completionWordList:[]});let r=t.value.map(({name:n})=>n).map(n=>` ${dt.bgHex(re(n))(" "+n+" ")} `).slice(0,10);return r.length?Tt({hint:"remove assignee... "+r.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=Y(f.SET_EDITOR);return e.modifier?W(ie):U({message:$e({wordList:t,inputString:e.inputString})})},[f.SET_USERNAME]:e=>e.inputString?W():U({message:`Enter a username. Saved in ${dt.bgBlack("~/.epiq-global/")}`}),[f.SET_VIEW]:e=>ad({list:Y(f.SET_VIEW),hint:$e({wordList:Y(f.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[f.SYNC]:()=>W(ie)},Vo=Object.fromEntries(Object.entries(cd).map(([e,t])=>[e,{validate:(r,n,o)=>t({modifier:n,command:r,inputString:o})}]));var qo=["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 zo=e=>Object.values(f).includes(e),Go=(e,t)=>{let r=e.command??"",{modifier:n,target:o,inputString:i}=e,{message:a,validity:c,completionWordList:u}=Vo[r].validate(r,n,i),m=o==="command"?Object.values(f):r&&e.target==="modifier"?Y(r):qo;return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?Co(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var Yo=e=>{let t=e.trimStart(),r=ud(t),n=r[0]??"",o=r[1]??"",i=/\s$/.test(e),a=md(e),c=zo(n)?n:null,u=c!==null,m=n!=="",p=c?Y(c)??[]:[],v=c&&p.includes(o)?o:"",y="word";r.length===0||r.length===1&&!i?y="command":(r.length===1&&i||r.length===2&&!i)&&(y="modifier");let I=i?"":a,R=ld(t,c,v);return{raw:e,trimmedStart:t,words:r,firstWord:n,lastWord:a,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:i,modifier:v,target:y,inputToMatch:I,inputString:R}},ld=(e,t,r)=>{let n=e;return t&&n.startsWith(t)&&(n=n.slice(t.length)),n=n.replace(/^\s+/,""),r&&n.startsWith(r)&&(n=n.slice(r.length),n=n.replace(/^\s+/,"")),n},ud=e=>e.trim()?e.trim().split(/\s+/):[],md=e=>e.trimEnd().split(/\s+/).at(-1)??"";var Xo=" ",ne={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Me.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},In=new Set,Jo=()=>{for(let e of In)e()},Zo=e=>(In.add(e),()=>In.delete(e)),Pe=e=>{let r=e(ne),n=Yo(r.value),o=r.cursorPosition===r.value.length;ne={...r,commandMeta:Go(n,o)},Jo()},Pt=({message:e,status:t})=>{let r=structuredClone(ne);return r.commandMeta={...r.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},r.commandIsPending=!0,ne=r,Jo(),l(e,null)},bn=e=>{Pe(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Sn=e=>{Pe(t=>{let{value:r,cursorPosition:n}=t,o=n;if(e==="left"){for(;o>0&&r[o-1]===" ";)o--;for(;o>0&&r[o-1]!==" ";)o--}else{for(;o<r.length&&r[o]!==" ";)o++;for(;o<r.length&&r[o]===" ";)o++}return{...t,cursorPosition:o}})},Qo=()=>{Pe(e=>{let t=e.value.slice(e.cursorPosition),r=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,r)+t,cursorPosition:r,commandIsPending:!1}})},ei=()=>{Pe(e=>{let{value:t,cursorPosition:r}=e,n=r;for(;n>0&&t[n-1]===" ";)n--;for(;n>0&&t[n-1]!==" ";)n--;let o=t.slice(r);return{...e,value:t.slice(0,n)+o,cursorPosition:n,commandIsPending:!1}})},O=e=>{Pe(t=>{let r=Math.max(0,Math.min(t.cursorPosition,t.value.length)),n=t.value.slice(0,r),o=t.value.slice(r),i=e(n,t.commandMeta.autoCompletion),a=i+o,c=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:c,commandIsPending:!1}})},ti=()=>{Pe(e=>({...e,commandIsPending:!0}))},ri=({addToHistory:e=!0})=>{Pe(r=>({...r,commandHistory:e?[r.value,...r.commandHistory].slice(0,40):r.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),pd()},ni=()=>{Pe(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),r=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:r,cursorPosition:r.length}})},oi=()=>{Pe(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),r=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:r,cursorPosition:r.length}})},pd=()=>O(()=>""),ae=()=>ne,vr=()=>{let[e,...t]=ne.value.split(Xo);return t.join(Xo).trim()};var gd=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",fd=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",vd=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",ii=(e,t)=>{if(fd(e,e.sequence))return h.MoveCursorLeftOfWord;if(vd(e,e.sequence))return h.MoveCursorRightOfWord;if(gd(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.GetLastCommandFromHistory;case"down":return h.GetNextCommandFromHistory;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}};var h={Sync:"sync",NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function xd(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 hd(e,t,r){let n=x().currentNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?r.prevItem:n?r.prevContainer:null;case"down":return e==="vertical"?r.nextItem:n?r.nextContainer:null;case"left":return e==="horizontal"?r.prevItem:n?r.prevContainer:null;case"right":return e==="horizontal"?r.nextItem:n?r.nextContainer:null}}function si(e,t){let r=ae();if(e.sequence===":"&&r.value==="")return h.InitCommandLine;if(t===g.MOVE)switch(e.name){case"m":case"return":return h.ConfirmMove}if(t===g.COMMAND_LINE)return ii(e,r.value);let n=xd(e);if(n){let o=t===g.MOVE?{prevItem:h.MovePreviousItem,nextItem:h.MoveNextItem,prevContainer:h.MoveToPreviousContainer,nextContainer:h.MoveToNextContainer}:{prevItem:h.NavPreviousItem,nextItem:h.NavNextItem,prevContainer:h.NavToPreviousContainer,nextContainer:h.NavToNextContainer};return hd(x().currentNode.childRenderAxis,n,o)}if(e.ctrl&&e.name==="c")return h.Exit;switch(e.name){case"e":return h.Edit;case"n":return h.AddItem;case"m":return h.InitMove;case"d":return h.Delete;case"return":return h.Confirm;case"space":return h.Confirm;case"v":return x().viewMode==="wide"?h.SetViewDense:h.SetViewWide;case"q":case"escape":return h.Exit;case"s":return h.Sync;default:return null}}var ai=e=>{let{context:t}=x()?.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 V}from"ulid";import Ii from"node:fs";import qd from"node:path";import zd from"react";import{Box as Kd}from"ink";import Cr from"react";import{Box as wn,Text as Md}from"ink";import Ce from"react";import{Text as di}from"ink";import ci,{useEffect as li,useState as yd}from"react";var ui={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},de=({isSelected:e,placeholder:t=" "})=>{let{mode:r}=$(),n=ui[r]??ui.default,[o,i]=yd(0);if(li(()=>{i(0)},[n]),li(()=>{if(!e)return;let c=setInterval(()=>{i(u=>(u+1)%n.length)},500);return()=>clearInterval(c)},[e,n]),!e)return ci.createElement(di,null,t);let a=n[o]??n[0]??t;return ci.createElement(di,{color:N.accent,dimColor:o===1},a)};import{Box as Rn,Text as Ed}from"ink";import xr from"react";var hr=({children:e=[],height:t,selectedIndex:r,itemHeight:n=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),a=Math.max(1,Math.ceil(n)),c=Math.max(1,Math.floor(i/a)),u=Math.max(0,Math.min(r,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),v=p+c,y=e.slice(p,v),I=e.length>c,R=i,S=I?Math.max(1,Math.floor(c/e.length*R)):R,C=Math.max(0,R-S),w=Math.max(1,e.length-c),B=I?Math.floor(p/w*C):0;return xr.createElement(Rn,{flexDirection:"row",height:i,width:"100%"},xr.createElement(Rn,{flexDirection:"column",flexGrow:1,height:i},y),xr.createElement(Rn,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((se,J)=>xr.createElement(Ed,{key:J,color:I&&J>=B&&J<B+S?N.accent:N.secondary},I?"\u2502":" "))))};import{Box as yr,Text as Ad}from"ink";import Ye from"react";import{Text as Nd}from"ink";import Cd from"react";var Id=e=>e.toLowerCase().trim(),bd=(e,t=st)=>{let r=Id(e);return t[r]?t[r]:wt(r)},ct=({id:e,isSelected:t})=>{let r=b.getContributor(e);if(r)return Cd.createElement(Nd,{underline:t,color:bd(r.name)},"@"+r.name)};import{Text as Sd}from"ink";import Rd from"react";var lt=({id:e,isSelected:t})=>{let r=b.getTag(e);if(r)return Rd.createElement(Sd,{underline:t,backgroundColor:re(r.name),color:N.primary}," "+r.name+" ")};var mi=({width:e,ticket:t,isSelected:r})=>{let n=e-14,o=rr(sn(t.title),n),i=gn(t),a=fn(t);return Ye.createElement(yr,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:r?N.accent:N.secondary,justifyContent:"space-between"},Ye.createElement(yr,{borderBottom:!0},Ye.createElement(yr,{paddingLeft:1,flexDirection:"column"},Ye.createElement(Ad,{color:N.primary},o))),Ye.createElement(yr,{flexDirection:"row",paddingLeft:1},i.map(c=>Ye.createElement(lt,{key:c.id,id:c.id})),a.map(c=>Ye.createElement(ct,{key:c.id,id:c.id}))))};import wd from"chalk";import{Box as kt,Text as An}from"ink";import ke from"react";var Td=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,pi=({width:e,ticket:t,isSelected:r,index:n,mode:o})=>{let i=T(t.id),a=S=>{let C=i.find(w=>w.title===S);return C?T(C.id).map(w=>typeof w.props?.value=="string"?w.props.value:"").filter(w=>!!w):[]},c=a("Tags").map(S=>b.getTag(S)).filter(S=>!!S),u=a("Assignees").map(S=>b.getContributor(S)).filter(S=>!!S),m=1,p=c.length*(1+m),v=u.length*(2+m),y=c.map(S=>ke.createElement(kt,{key:S.id,paddingRight:m},ke.createElement(An,{color:re(S.name)},"\u25A0"))),I=u.map(S=>ke.createElement(kt,{key:S.id,paddingRight:m},ke.createElement(An,{color:wt(S.name)},"@"+S.name.at(0)))),R=r?N.accent:o===g.MOVE?N.secondary:N.primary;return ke.createElement(kt,{borderBottom:!0,justifyContent:"space-between"},ke.createElement(kt,null,ke.createElement(de,{isSelected:r,placeholder:wd.dim.gray(n+1+" ")}),ke.createElement(An,{wrap:"truncate",color:R},Td(t.title,e-p-v-14))),ke.createElement(kt,null,y,I))};var Pd=({swimlane:e,isSelected:t,width:r,height:n,isDense:o,isFocused:i,listSelectedIndex:a,mode:c})=>{let{renderedChildrenIndex:u}=$(),m=u[e.id]??[],p=`${e.title} (${m.length})`,v=3,y=o?1:4,I=n-v-(o?2:1),R=Ce.createElement(wn,{borderStyle:"round",borderColor:N.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Ce.createElement(de,{isSelected:t}),Ce.createElement(Md,{bold:!0,color:t?N.accent:N.primary},p," ",e.readonly?"\u{1F512}":"")),S=(C,w)=>{let B=i&&a===w;return o?Ce.createElement(pi,{key:C.id,index:w,width:r,ticket:C,isSelected:B,mode:c}):Ce.createElement(mi,{key:C.id,width:r,ticket:C,isSelected:B})};return Ce.createElement(wn,{flexDirection:"column",width:r,borderStyle:"round",borderColor:t?N.accent:N.secondary,paddingRight:1,paddingLeft:1,height:n},R,Ce.createElement(wn,{padding:o?1:0},m.length>0&&Ce.createElement(hr,{selectedIndex:a,height:I,itemHeight:y},m.map(S)),Ce.createElement(de,{isSelected:i&&a===-1})))},gi=Ce.memo(Pd);import{Box as Pn,Text as jd}from"ink";import _e,{useEffect as kn,useMemo as Ei}from"react";import Xe from"chalk";import fi from"string-width";import{decodeTime as kd}from"ulid";var Ld=(e,t)=>e+" ".repeat(Math.max(0,t-fi(e))),Dd=(e,t)=>" ".repeat(Math.max(0,t-fi(e)))+e,Fd=e=>(()=>{let r={"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=>r[o]??(o.endsWith("e")?`${o}d`:`${o}ed`))(e)})(),Bd=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=x().tags[e.payload.tagId];return t?Xe.bgHex(re(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=x().tags[e.payload.tagId];return t?Xe.bgHex(re(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=x().contributors[e.payload.contributor];return t?Xe.hex(re(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=x().contributors[e.payload.contributor];return t?Xe.hex(re(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;default:return""}},Od=e=>{let t=Wo(kd(e));return Xe.gray(Dd(t,8))},Ud=12,$d=e=>Ld(`${e}`,Ud),vi=e=>{let t=Od(e.id),r=$d(e.userName),n=Fd(e.action),o=Bd(e),i=Xe.dim("\u203A"),a=[n,o].filter(Boolean).join(" ");return`${r} ${t} ${i} ${a}`};var L={exit(){process.exit(0)},enterChildNode(){let e=x(),t=e.currentNode,r=Math.max(0,e.selectedIndex),n=T(t.id)[r];!n||t.context==="FIELD"||L.navigate({currentNode:n,selectedIndex:T(n.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=x();if(!e.parentNodeId){logger.info("Missing parent node id");return}let r=t[e.parentNodeId];if(!r){logger.error("Parent not found");return}let n=T(r.id),o=n.findIndex(({id:a})=>a===e.id),i=n.length===0?-1:o>=0?o:0;L.navigate({currentNode:r,selectedIndex:i})},navigateToNextItem:()=>xi(1),navigateToPreviousItem:()=>xi(-1),navigateToNextContainer:()=>hi(1),navigateToPreviousContainer:()=>hi(-1),navigate:({currentNode:e=x().currentNode,selectedIndex:t})=>{A({currentNodeId:e.id,selectedIndex:t})}},xi=e=>{let t=x(),r=T(t.currentNode.id).length;if(r===0)return;let o=(Math.max(0,t.selectedIndex)+e+r)%r;L.navigate({selectedIndex:o})},hi=e=>{let{currentNode:t,nodes:r,selectedIndex:n}=x();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=r[t.parentNodeId];if(!t||!o)return;let i=T(o.id),a=i.findIndex(y=>y.id===t.id);if(a<0)return;let c=i.at(a+e)??i.at(0);if(!c)return;let u=T(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,n),m),v=u.length?p:-1;L.navigate({currentNode:c,selectedIndex:v})};import{Box as Er,Text as _d}from"ink";import Le from"react";var yi=({selectedIndex:e,parent:t,selected:r})=>{let{currentNode:n}=$(),{title:o}=t,i=T(t.id).map(a=>{let c=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return b.getContributor(c)?.id;if(o==="Tags")return b.getTag(c)?.id}).filter(a=>!!a);return Le.createElement(Er,{alignItems:"center",paddingTop:1},Le.createElement(Er,{minWidth:12},Le.createElement(de,{isSelected:r}),Le.createElement(_d,{color:r?N.accent:N.secondary2},o,":")),Le.createElement(Er,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,c)=>{let u=n.id===t.id&&c===e;return Le.createElement(Er,{key:`${o}-${a}`,paddingRight:2,minHeight:1},Le.createElement(de,{isSelected:u}),o==="Assignees"?Le.createElement(ct,{isSelected:u,id:a}):o==="Tags"?Le.createElement(lt,{isSelected:u,id:a}):null)})))};import{Box as Nr,Text as Tn}from"ink";import De,{useEffect as Wd}from"react";var Mn=({id:e,label:t,text:r,height:n,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:c}=$(),u=y=>String(y).replace(/\r?\n/g,""),m=typeof r=="string"?r.split(/\r?\n|\u2028|\u2029/):[];Wd(()=>{let y=[];return m.forEach((I,R)=>{let S=we(BigInt(R+1));if(!he(S))return;let C=Q.text({id:`${e}-${R}`,name:`Line ${R+1}`,parentNodeId:e,rank:S.value,props:{value:I},readonly:!0,isVirtual:!0}),w=b.createNode(C);he(w)&&y.push(w.value.id)}),()=>y.forEach(b.deleteNode)},[e,r]);let p="\u2029",v=m.map((y,I)=>{let R=c.id===e&&a===I;return De.createElement(Nr,{key:`${e}-${I}`},De.createElement(Tn,{color:R?N.primary:N.secondary2,dimColor:!R},`${I+1} `.padStart(5,"\xA0")),De.createElement(Tn,{backgroundColor:R?"gray":""},u(y.length?rr(y,i-10):p)))});return De.createElement(Nr,{flexDirection:"column",paddingTop:1},De.createElement(Nr,null,De.createElement(de,{isSelected:o}),De.createElement(Tn,{color:o?N.accent:N.secondary2},t)),De.createElement(Nr,{flexDirection:"row",borderStyle:"round",borderColor:N.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},De.createElement(hr,{scrollByOne:!0,children:v,height:n-2,selectedIndex:a,itemHeight:1})))};var Hd=e=>`${e}::log`,Ni=e=>e==="Assignees"||e==="Tags",Ci=({ticket:e,height:t})=>{let{selectedIndex:r,currentNode:n}=$(),o=process.stdout.columns||120,i=Ei(()=>Hd(e.id),[e.id]),a=Ei(()=>[...e.log].reverse().map(vi).join(`
6
+ `),[e.log]);kn(()=>{if(b.getNode(i))return;let w=we(ze);if(d(w))return;let B={...Q.field({id:i,name:G.HISTORY,parentNodeId:e.id,rank:w.value,props:{value:a},isVirtual:!0}),readonly:!0,childRenderAxis:"vertical"};return b.createNode(B),()=>{b.deleteNode(i)}},[i,e.id,a]),kn(()=>{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 c=n.id===e.id,u=n.id===i||n.parentNodeId===i;kn(()=>{u&&(r>=0||L.navigate({selectedIndex:0}))},[u,r]);let m=T(e.id);if(u){let C=b.getNode(i),B=t-3;return _e.createElement(Pn,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},C?_e.createElement(Mn,{id:C.id,label:"Event log",text:C.props.value??"",selected:!1,maxWidth:o,height:B}):null)}let p=m.reduce((C,w)=>Ni(w.title)||w.id===i?C+1:C,0),v=2,y=p*1,R=t-3-y-v,S=(C,w)=>Ni(C.title)?_e.createElement(yi,{key:C.id,parent:C,selected:w,selectedIndex:r}):C.id===i?_e.createElement(Pn,{key:C.id,paddingTop:1},_e.createElement(de,{isSelected:w}),_e.createElement(jd,{backgroundColor:N.secondary,color:w?N.accent:N.primary}," History \u203A\u203A ")):C.title===G.DESCRIPTION?_e.createElement(Mn,{label:"Description (press e to edit)",key:C.id,id:C.id,text:C.props.value??"",selected:w,maxWidth:o,height:R}):null;return _e.createElement(Pn,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((C,w)=>S(C,c&&r===w)))};var Vd=({swimlanes:e,currentNode:t,selectedIndex:r,breadCrumb:n,mode:o,viewMode:i,height:a,width:c})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,p=u===P.BOARD||u===P.SWIMLANE,v=u===P.TICKET?t:n.find(C=>C.context===P.TICKET),y=Math.floor(c/3),I=Math.floor(c/Math.max(e.length,1)),R=Math.min(I,y),S=i==="dense";return Cr.createElement(Kd,{flexDirection:"row",height:a},p&&e.map((C,w)=>{let B=t.id===C.id,se=B?r:-1,J=t.context===P.BOARD&&r===w;return Cr.createElement(gi,{key:C.id,height:a,width:R,swimlane:C,isSelected:J,isDense:S,isFocused:B,listSelectedIndex:se,mode:o})}),m&&v&&Cr.createElement(Ci,{height:a,ticket:v}))},Ir=Cr.memo(Vd);import{render as Gd}from"ink";import{Writable as Yd}from"node:stream";var Lt=e=>String(e).padStart(2,"0"),Xd=e=>{let t=e.getUTCFullYear(),r=Lt(e.getUTCMonth()+1),n=Lt(e.getUTCDate()),o=Lt(e.getUTCHours()),i=Lt(e.getUTCMinutes()),a=Lt(e.getUTCSeconds());return`${t}-${r}-${n}_${o}-${i}-${a}`},Jd=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Zd=async(e,{width:t,height:r})=>{let n="",o=new Yd({write(a,c,u){let m=Qd(a.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(n=m),u()}});o.columns=t,o.rows=r,o.isTTY=!0;let i=Gd(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(a=>setTimeout(a,0)),i.unmount(),n},Qd=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),bi=async()=>{let{currentNode:e,selectedIndex:t,breadCrumb:r,viewMode:n,mode:o,renderedChildrenIndex:i}=x(),a=r.find(w=>w.context==="BOARD");if(!a)return s("No board found to export");let c=120,u=40,m=await Zd(zd.createElement(Ir,{height:u,width:c,swimlanes:(i[a.id]??[]).filter(w=>w!==void 0&&nt(w)),currentNode:e,selectedIndex:t,breadCrumb:r,viewMode:n,mode:o}),{width:c,height:u});if(!m)return s("Failed to render board export");let p=Be(process.cwd());if(d(p))return s("Unable to export, epiq root not found");let v=new Date,y=Xd(v),I=`board_${Jd(a.title)}_${y}.md`,R=lo(p.value);Ii.mkdirSync(R,{recursive:!0});let S=qd.join(R,I),C=`# Board - ${a.title}
7
7
  Date: ${v.toISOString()}
8
8
 
9
9
  \`\`\`text
10
10
  ${m}
11
11
  \`\`\`
12
- `;return ui.writeFileSync(I,C,"utf8"),l("Exported board layout",I)};import hr from"node:fs";import zd from"node:path";import Tt from"fs";import gi from"path";import Kd from"util";var pi=1e3,fi=()=>{let e=process.cwd(),t=Oe(e);if(!d(t))return gi.join(t.value,Ce,"log","epiq.log")};function Vd(){if(!_n)return;let e=fi();if(e===void 0||!Tt.existsSync(e))return;let n=Tt.readFileSync(e,"utf8").split(`
13
- `);if(n[n.length-1]===""&&n.pop(),n.length<=pi)return;let r=n.slice(-pi).join(`
12
+ `;return Ii.writeFileSync(S,C,"utf8"),l("Exported board layout",S)};import vc from"node:fs";var Je=e=>{let t=Ee(e);if(d(t))return s("Unable to resolve epiq project root");let r=Oe(t.value);return d(r)?s("Unable to read project.json"):l("Resolved state branch",r.value.stateBranch)},fe="origin";import Bt from"node:fs";import oc from"node:os";import ye from"node:path";var Ln=(e,t)=>{let r=new Map,n=t??((...i)=>JSON.stringify(i)),o=((...i)=>{let a=n(...i);if(!r.has(a)){let c=e(...i).then(u=>(d(u)&&r.delete(a),u));r.set(a,c)}return r.get(a)});return o.clear=()=>r.clear(),o};import Dt from"fs";import Ri from"path";import ec from"util";var Si=1e3,Ai=()=>{let e=process.cwd(),t=Be(e);if(!d(t))return Ri.join(t.value,Ae,"log","epiq.log")};function tc(){if(!rn)return;let e=Ai();if(e===void 0||!Dt.existsSync(e))return;let r=Dt.readFileSync(e,"utf8").split(`
13
+ `);if(r[r.length-1]===""&&r.pop(),r.length<=Si)return;let n=r.slice(-Si).join(`
14
14
  `)+`
15
- `;Tt.writeFileSync(e,r,"utf8")}function yr(e,t,n=!1){if(!_n)return;let r=fi();if(!r)return;let o=Kd.format(...t),i=new Date,c=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
16
- `;Tt.mkdirSync(gi.dirname(r),{recursive:!0}),Tt.appendFileSync(r,c,"utf8"),Vd()}var oe={info(...e){yr("[Info]",e,!1)},debug(...e){yr("->",e,!0)},error(...e){yr("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=oe;var vi=async e=>{let t=zd.join(e,".gitignore"),n=hr.existsSync(t)?hr.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/logs/"],o=n.split(`
17
- `).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 c=["# [epiq]: local hydrated state is never committed",...i].join(`
18
- `);return n=n.trimEnd()+`
19
-
20
- ${c}
21
- `,hr.writeFileSync(t,n,"utf8"),oe.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)};import dc from"node:fs";var O="epiq/eventlog",ue="origin";import wt from"node:fs";import Yd from"node:os";import ve from"node:path";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 c=e(...i).then(u=>(d(u)&&n.delete(a),u));n.set(a,c)}return n.get(a)});return o.clear=()=>n.clear(),o};import{spawn as qd}from"node:child_process";import Nr from"node:fs";import hi from"node:path";var q={stage:({cwd:e,pathspec:t})=>D({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>D({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>D({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>D({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>D({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 D({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>D({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>D({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>D({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>D({args:["worktree","prune"],cwd:e})};var xi=15e3,Gd={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Ei=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Nr.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=qd("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Gd}),i=!1,a="",c="",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(`
22
- `);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=>{c+=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(`
23
- `)))}),o.on("close",p=>{let v=p??1;if(n){u({stdout:a,stderr:c,exitCode:v});return}if(v!==0){u(s([`git ${e.join(" ")}`,c.trim()||a.trim()||"Git command failed"].filter(Boolean).join(`
24
- `)));return}u(l("Git command succeeded",{stdout:a,stderr:c,exitCode:v}))})}),D=({args:e,cwd:t})=>Ei({args:e,cwd:t,allowFail:!1}),dt=({args:e,cwd:t})=>Ei({args:e,cwd:t,allowFail:!0}),mn=async({cwd:e,message:t})=>{let n=await q.commit({cwd:e,message:t});if(d(n))return s(`Failed to create commit
25
- ${n.message}`);let r=await D({args:["rev-parse","HEAD"],cwd:e});return d(r)?s(`Commit created, but failed to read HEAD SHA
26
- ${r.message}`):l("Created commit and resolved SHA",r.value.stdout.trim())},Cr=async e=>{let t=await Ri(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=>Nr.existsSync(hi.join(n,i)));return l("Checked for in-progress Git operation",o.length>0)},br=async({repoRoot:e})=>{let n=(await dt({args:["remote","get-url",ue],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},pn=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}`):l("Checked remote branch",n.stdout.trim().length>0)},Ni=async({repoRoot:e,branch:t})=>{let n=await dt({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 Nr.realpathSync.native(e)}catch{return hi.resolve(e)}},Ci=async({repoRoot:e,worktreeRoot:t})=>{let n=await D({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return s(n.message);let r=yi(t),o=n.value.stdout.split(`
27
- `).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(yi).includes(r);return l("Checked worktree registration",o)},Ir=async e=>{let t=await dt({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},gn=async e=>{let t=await D({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?s(t.message):l("Resolved current branch",t.value.stdout.trim())},bi=async e=>{let t=await D({args:["rev-parse","--short","HEAD"],cwd:e});return d(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"),fn=async({cwd:e,branch:t})=>{let n=await pn({repoRoot:e,branch:t});if(d(n))return s(n.message);if(!n.value)return l("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}
28
- ${r.message}`);let o=await q.pullRebase({cwd:e,remote:ue,branch:t});return d(o)?s(`Failed during pull --rebase
29
- ${o.message}`):l("Pulled with rebase",!0)},Si=async e=>{let t=await D({args:["status","--porcelain"],cwd:e});return d(t)?s(t.message):l("Checked state branch changes",t.value.stdout.trim().length>0)},Ai=async e=>{let t=await gn(e);return d(t)?s(t.message):l("Checked detached HEAD state",t.value==="HEAD")};var Ti="4b825dc642cb6eb9a060e54bf8d69288fbee4904",wi=e=>ve.join(Ce,$t,e),Mi=()=>ve.join(Yd.homedir(),ce),Pi=()=>ve.join(Mi(),"worktrees"),ki=e=>{let t=Qr(e);return d(t)?s(t.message):l("Resolved state branch root",ve.join(Pi(),t.value))},Xd=e=>ve.join(e,Ce),Xe=e=>ve.join(Xd(e),$t),Sr=({root:e,fileName:t})=>ve.join(Xe(e),t),Mt=e=>{try{return wt.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return s(t instanceof Error?t.message:String(t))}},Li=()=>{let e=Mt(Mi());if(d(e))return s(`Ensure epiq home failed.
30
- `+e.message);let t=Mt(Pi());return d(t)?s(`Ensure worktrees dir failed.
31
- `+t.message):l("Ensured epiq storage",!0)},Di=e=>{wt.existsSync(e)&&(oe.debug("[sync] remove path",e),wt.rmSync(e,{recursive:!0,force:!0}))},Fi=e=>{let t=Xe(e);if(!wt.existsSync(t))return l("Events dir missing",[]);let n=wt.readdirSync(t,{withFileTypes:!0}).filter(r=>r.isFile()).map(r=>r.name).filter(r=>r.endsWith(".jsonl")).sort();return l("Listed event files",n)},Oi=(e,t)=>{for(let n of[Xe(e),Xe(t)]){let r=Mt(n);if(d(r))return s(r.message)}return l("Ensured state branch",void 0)},Bi=async e=>{let t=await D({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return s(`ensure state branch is storage only failed
32
- `+t.message);let r=t.value.stdout.trim().split(`
33
- `).filter(Boolean).filter(a=>a!==Ce);if(r.length===0)return l("State branch is storage-only",!1);let o=await D({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return s(`Failed to clean storage branch
34
- ${o.message}`);let i=await mn({cwd:e,message:"[epiq:repair-storage-branch]"});return d(i)?s(i.message):l("Cleaned storage branch",!0)},Ui=Er(async(e=process.cwd())=>{let t=await D({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?s("Not inside a Git repository"):l("Resolved repo root",t.value.stdout.trim())},e=>ve.resolve(e)),Ri=Er(async e=>{let t=await D({args:["rev-parse","--git-dir"],cwd:e});if(d(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 ct from"node:fs";import Pt from"node:path";var Wi=async e=>{if((await dt({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 d(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",Jd=async e=>{let t=await gn(e);if(d(t))return s(t.message);let n=await bi(e);if(d(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 ${O}`);let t=await D({args:["commit-tree",Ti,"-m","[epiq:init-state-branch]"],cwd:e});if(d(t))return s(`Failed to create state branch commit
35
- ${t.message}`);let n=t.value.stdout.trim(),r=await D({args:["update-ref",`refs/heads/${O}`,n],cwd:e});return d(r)?s(`Failed to create ${O}
36
- ${r.message}`):l("Created state branch",!0)},Zd=async({repoRoot:e})=>{let t=await Ni({repoRoot:e,branch:O});if(d(t))return s(`Ensure local state branch failed
37
- `+t.message);if(t.value)return l("Local state branch already exists",!1);let n=await br({repoRoot:e});if(d(n))return s(`Ensure local state branch failed
38
- `+n.message);if(!n.value)return _i(e);let r=await pn({repoRoot:e,branch:O});if(d(r))return s(`Ensure local state branch failed
39
- `+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
40
- ${o.message}`);let i=await D({args:["branch","--track",O,`${ue}/${O}`],cwd:e});return d(i)?s(`Failed to create local ${O} from remote
41
- ${i.message}`):l("Created local state branch from remote",!0)},Qd=async({repoRoot:e,branch:t})=>{let n=await D({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return s(n.message);let r=n.value.stdout.split(`
42
- `),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)},ec=async({repoRoot:e,stateBranchRoot:t})=>{let n=Mt(Pt.dirname(t));if(d(n))return s(`Failed to create state branch worktree
43
- `+n.message);ct.existsSync(t)&&!ct.existsSync(Pt.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
44
- ${r.message}`):l("Created state branch worktree",!0)},tc=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Qd({repoRoot:e,branch:O});if(d(n))return s(n.message);let r=Pt.resolve(t),o=n.value?Pt.resolve(n.value):null;if(o&&o===r&&ct.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 c=await q.worktreeRemove({cwd:e,worktreeRoot:o});if(d(c))return s(`Failed to remove existing state branch worktree
45
- ${c.message}`)}if(o&&!ct.existsSync(o)){oe.info("Pruning stale state branch worktree");let c=await q.worktreePrune({cwd:e});if(d(c))return s(`Failed to prune stale worktrees
46
- ${c.message}`)}let i=await Ci({repoRoot:e,worktreeRoot:t});if(d(i))return s(i.message);let a=ct.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 c=await q.worktreePrune({cwd:e});if(d(c))return s(`Failed to prune stale worktrees
47
- ${c.message}`)}return ec({repoRoot:e,stateBranchRoot:t})},nc=async e=>{let t=await gn(e);if(d(t))return s(t.message);if(t.value===O)return l("State branch already checked out",!1);let n=await q.checkout({cwd:e,branch:O});return d(n)?s(`Failed to checkout ${O}
48
- ${n.message}`):l("Checked out state branch",!0)},rc=async e=>{let t=await Ir(e);if(d(t))return s(t.message);if(t.value)return l("State branch upstream already configured",!1);let n=await br({repoRoot:e});if(d(n))return s(n.message);if(!n.value)return l("No remote available for state branch upstream",!1);let r=await pn({repoRoot:e,branch:O});if(d(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 ${O} upstream`);let o=await q.fetch({cwd:e,remote:ue,branch:O});if(d(o))return s(`Failed to fetch ${O}
49
- ${o.message}`);let i=await q.setUpstream({cwd:e,branch:O,upstream:`${ue}/${O}`});return d(i)?s(`Failed to set state branch upstream
50
- ${i.message}`):l("Configured state branch upstream",!0)},ji=async({stateBranchRoot:e,ownEventFileName:t})=>{let n=wi(t),r=Pt.join(e,n);if(!ct.existsSync(r))return l("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
51
- ${o.message}`):l("Staged state branch event file",void 0)},Hi=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Jd(e);return d(n)?s(`Create state branch sync commit failed
52
- `+n.message):mn({cwd:t,message:n.value})},Ar=async e=>{let t=await Ir(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
53
- ${n.message}`):l("Pushed state branch",!0)},Ki=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=[Li(),await Zd({repoRoot:e}),await tc({repoRoot:e,stateBranchRoot:t}),await nc(t),await Bi(t),n?await rc(t):l("Skipped state branch upstream bootstrap",!1)];for(let i of o){if(d(i))return s(i.message);r=r||!!i.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage (readonly)",r)};import vn from"node:fs";import Tr from"node:path";import{decodeTime as oc}from"ulid";var Rr=e=>{let[t,n]=e.id;return`${t}:${n??""}`},Vi=e=>{let[t]=e.id;return oc(t)},ic=e=>{let{userId:t,userName:n,...r}=e;return r},sc=e=>e.length===0?"":e.map(t=>JSON.stringify(ic(t))).join(`
15
+ `;Dt.writeFileSync(e,n,"utf8")}function Dn(e,t,r=!1){if(!rn)return;let n=Ai();if(!n)return;let o=ec.format(...t),i=new Date,c=`[${r?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
16
+ `;Dt.mkdirSync(Ri.dirname(n),{recursive:!0}),Dt.appendFileSync(n,c,"utf8"),tc()}var ce={info(...e){Dn("[Info]",e,!1)},debug(...e){Dn("->",e,!0)},error(...e){Dn("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=ce;import{spawn as rc}from"node:child_process";import Fn from"node:fs";import Mi from"node:path";var j={stage:({cwd:e,pathspec:t})=>D({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:r=!1})=>D({args:["commit",...r?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:r})=>D({args:["fetch",t,r],cwd:e}),pullRebase:({cwd:e,remote:t,branch:r})=>D({args:["pull","--rebase",t,r],cwd:e}),checkout:({cwd:e,branch:t})=>D({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:r,setUpstream:n=!1})=>{let o=t&&r?["push",...n?["-u"]:[],t,r]:["push"];return D({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:r})=>D({args:["branch","--set-upstream-to",r,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:r})=>D({args:["worktree","add",t,r],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>D({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>D({args:["worktree","prune"],cwd:e})};var wi=15e3,nc={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Pi=({args:e,cwd:t,allowFail:r})=>new Promise(n=>{if(!Fn.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(r){n({stdout:"",stderr:p,exitCode:1});return}n(s(p));return}let o=rc("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:nc}),i=!1,a="",c="",u=p=>{i||(i=!0,clearTimeout(m),n(p))},m=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${wi}ms`].join(`
17
+ `);u(r?{stdout:a,stderr:p,exitCode:124}:s(p))},wi);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{a+=p}),o.stderr.on("data",p=>{c+=p}),o.on("error",p=>{if(r){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 v=p??1;if(r){u({stdout:a,stderr:c,exitCode:v});return}if(v!==0){u(s([`git ${e.join(" ")}`,c.trim()||a.trim()||"Git command failed"].filter(Boolean).join(`
19
+ `)));return}u(l("Git command succeeded",{stdout:a,stderr:c,exitCode:v}))})}),D=({args:e,cwd:t})=>Pi({args:e,cwd:t,allowFail:!1}),ut=({args:e,cwd:t})=>Pi({args:e,cwd:t,allowFail:!0}),mt=async({cwd:e,message:t})=>{let r=await j.commit({cwd:e,message:t});if(d(r))return s(`Failed to create commit
20
+ ${r.message}`);let n=await D({args:["rev-parse","HEAD"],cwd:e});return d(n)?s(`Commit created, but failed to read HEAD SHA
21
+ ${n.message}`):l("Created commit and resolved SHA",n.value.stdout.trim())},Ft=async e=>{let t=await Oi(e);if(d(t))return s(t.message);let r=t.value,o=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","REBASE_HEAD","rebase-merge","rebase-apply"].filter(i=>Fn.existsSync(Mi.join(r,i)));return l("Checked for in-progress Git operation",o.length>0)},Bn=async({repoRoot:e})=>{let r=(await ut({args:["remote","get-url",fe],cwd:e})).exitCode===0;return l(`Checked remote ${r}`,r)},br=async({repoRoot:e,branch:t})=>{let r=await ut({args:["ls-remote","--heads",fe,t],cwd:e});return r.exitCode!==0?s(r.stderr.trim()||`Unable to inspect remote branch ${fe}/${t}`):l("Checked remote branch",r.stdout.trim().length>0)},Sr=async({repoRoot:e,branch:t})=>{let r=await ut({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return r.exitCode===0?l("Local branch exists",!0):r.exitCode===1?l("Local branch missing",!1):s(r.stderr.trim()||`Unable to inspect branch ${t}`)},Ti=e=>{try{return Fn.realpathSync.native(e)}catch{return Mi.resolve(e)}},ki=async({repoRoot:e,worktreeRoot:t})=>{let r=await D({args:["worktree","list","--porcelain"],cwd:e});if(d(r))return s(r.message);let n=Ti(t),o=r.value.stdout.split(`
22
+ `).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(Ti).includes(n);return l("Checked worktree registration",o)},On=async e=>{let t=await ut({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Rr=async e=>{let t=await D({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?s(t.message):l("Resolved current branch",t.value.stdout.trim())},Li=async e=>{let t=await D({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?s(t.message):l("Resolved short HEAD sha",t.value.stdout.trim())},Di=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Ar=async({cwd:e,branch:t})=>{let r=await br({repoRoot:e,branch:t});if(d(r))return s(r.message);if(!r.value)return l("Remote branch missing, skipped pull",!1);let n=await j.fetch({cwd:e,remote:fe,branch:t});if(d(n))return s(`Failed to fetch ${t}
23
+ ${n.message}`);let o=await j.pullRebase({cwd:e,remote:fe,branch:t});return d(o)?s(`Failed during pull --rebase
24
+ ${o.message}`):l("Pulled with rebase",!0)},Fi=async e=>{let t=await D({args:["status","--porcelain"],cwd:e});return d(t)?s(t.message):l("Checked state branch changes",t.value.stdout.trim().length>0)},Bi=async e=>{let t=await Rr(e);return d(t)?s(t.message):l("Checked detached HEAD state",t.value==="HEAD")};var Ui="4b825dc642cb6eb9a060e54bf8d69288fbee4904",$i=e=>ye.join(Ae,Xt,e),_i=()=>ye.join(oc.homedir(),pe),wr=()=>ye.join(_i(),"worktrees"),Wi=({repoRoot:e})=>{let t=po(e);return d(t)?s(t.message):l("Resolved state branch root",ye.join(wr(),t.value))},ic=e=>ye.join(e,Ae),Ze=e=>ye.join(ic(e),Xt),Un=({root:e,fileName:t})=>ye.join(Ze(e),t),Ot=e=>{try{return Bt.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return s(t instanceof Error?t.message:String(t))}},Tr=()=>{let e=Ot(_i());if(d(e))return s(`Ensure epiq home failed.
25
+ `+e.message);let t=Ot(wr());return d(t)?s(`Ensure worktrees dir failed.
26
+ `+t.message):l("Ensured epiq storage",!0)},ji=e=>{Bt.existsSync(e)&&(ce.debug("[sync] remove path",e),Bt.rmSync(e,{recursive:!0,force:!0}))},Hi=e=>{let t=Ze(e);if(!Bt.existsSync(t))return l("Events dir missing",[]);let r=Bt.readdirSync(t,{withFileTypes:!0}).filter(n=>n.isFile()).map(n=>n.name).filter(n=>n.endsWith(".jsonl")).sort();return l("Listed event files",r)},Ki=(e,t)=>{for(let r of[Ze(e),Ze(t)]){let n=Ot(r);if(d(n))return s(n.message)}return l("Ensured state branch",void 0)},Vi=async e=>{let t=await D({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return s(`ensure state branch is storage only failed
27
+ `+t.message);let n=t.value.stdout.trim().split(`
28
+ `).filter(Boolean).filter(a=>a!==Ae);if(n.length===0)return l("State branch is storage-only",!1);let o=await D({args:["rm","-r","--ignore-unmatch","--",...n],cwd:e});if(d(o))return s(`Failed to clean storage branch
29
+ ${o.message}`);let i=await mt({cwd:e,message:"[epiq:repair-storage-branch]"});return d(i)?s(i.message):l("Cleaned storage branch",!0)},Mr=Ln(async(e=process.cwd())=>{let t=await D({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?s("Not inside a Git repository"):l("Resolved repo root",t.value.stdout.trim())},e=>ye.resolve(e)),Oi=Ln(async e=>{let t=await D({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return s(t.message);let r=t.value.stdout.trim(),n=ye.isAbsolute(r)?r:ye.join(e,r);return l("Resolved git dir",n)},e=>ye.resolve(e));import pt from"node:fs";import Ut from"node:path";var zi=async e=>{if((await ut({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return l("Initial commit already exists",!1);ce.info("Creating initial commit");let r=await j.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(r)?s(r.message):l("Created initial commit",!0)},qi=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",sc=async e=>{let t=await Rr(e);if(d(t))return s(t.message);let r=await Li(e);if(d(r))return s(r.message);let n=`[epiq:sync:${qi(t.value)}:${qi(r.value)}]`;return l("Built sync commit message",n)},Pr=async({repoRoot:e,stateBranchName:t})=>{ce.info(`Creating ${t}`);let r=await D({args:["commit-tree",Ui,"-m","[epiq:init-state-branch]"],cwd:e});if(d(r))return s(`Failed to create state branch commit
30
+ ${r.message}`);let n=r.value.stdout.trim(),o=await D({args:["update-ref",`refs/heads/${t}`,n],cwd:e});return d(o)?s(`Failed to create ${t}
31
+ ${o.message}`):l("Created state branch",!0)},ac=async({repoRoot:e,stateBranchName:t})=>{let r=await Sr({repoRoot:e,branch:t});if(d(r))return s(`Ensure local state branch failed
32
+ `+r.message);if(r.value)return l("Local state branch already exists",!1);let n=await Bn({repoRoot:e});if(d(n))return s(`Ensure local state branch failed
33
+ `+n.message);if(!n.value)return Pr({repoRoot:e,stateBranchName:t});let o=await br({repoRoot:e,branch:t});if(d(o))return s(`Ensure local state branch failed
34
+ `+o.message);if(!o.value)return Pr({repoRoot:e,stateBranchName:t});let i=await j.fetch({cwd:e,remote:fe,branch:t});if(d(i))return s(`Failed to fetch ${t} from remote
35
+ ${i.message}`);let a=await D({args:["branch","--track",t,`${fe}/${t}`],cwd:e});return d(a)?s(`Failed to create local ${t} from remote
36
+ ${a.message}`):l("Created local state branch from remote",!0)},dc=async({repoRoot:e,branch:t})=>{let r=await D({args:["worktree","list","--porcelain"],cwd:e});if(d(r))return s(r.message);let n=r.value.stdout.split(`
37
+ `),o=null;for(let i of n){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)},cc=async({repoRoot:e,stateBranchRoot:t,stateBranchName:r})=>{let n=Ot(Ut.dirname(t));if(d(n))return s(`Failed to create state branch worktree
38
+ `+n.message);pt.existsSync(t)&&!pt.existsSync(Ut.join(t,".git"))&&(ce.info("Removing broken state branch worktree path"),ji(t)),ce.info("Creating state branch worktree");let o=await j.worktreeAdd({cwd:e,worktreeRoot:t,branch:r});return d(o)?s(`Failed to create state branch worktree
39
+ ${o.message}`):l("Created state branch worktree",!0)},$n=async({repoRoot:e,stateBranchRoot:t,stateBranchName:r})=>{let n=await dc({repoRoot:e,branch:r});if(d(n))return s(n.message);let o=Ut.resolve(t),i=n.value?Ut.resolve(n.value):null;if(i&&i===o&&pt.existsSync(i))return l("State branch already checked out in expected worktree",!1);if(i&&i!==o){ce.info("Moving state branch worktree to expected location");let u=await j.worktreeRemove({cwd:e,worktreeRoot:i});if(d(u))return s(`Failed to remove existing state branch worktree
40
+ ${u.message}`)}if(i&&!pt.existsSync(i)){ce.info("Pruning stale state branch worktree");let u=await j.worktreePrune({cwd:e});if(d(u))return s(`Failed to prune stale worktrees
41
+ ${u.message}`)}let a=await ki({repoRoot:e,worktreeRoot:t});if(d(a))return s(a.message);let c=pt.existsSync(t);if(a.value&&c)return l("State branch worktree already exists",!1);if(a.value&&!c){ce.info("Pruning missing registered state branch worktree");let u=await j.worktreePrune({cwd:e});if(d(u))return s(`Failed to prune stale worktrees
42
+ ${u.message}`)}return cc({repoRoot:e,stateBranchRoot:t,stateBranchName:r})},lc=async({stateBranchRoot:e,stateBranchName:t})=>{let r=await Rr(e);if(d(r))return s(r.message);if(r.value===t)return l("State branch already checked out",!1);let n=await j.checkout({cwd:e,branch:t});return d(n)?s(`Failed to checkout ${t}
43
+ ${n.message}`):l("Checked out state branch",!0)},uc=async({repoRoot:e,stateBranchRoot:t})=>{let r=await On(t);if(d(r))return s(r.message);if(r.value)return l("State branch upstream already configured",!1);let n=await Bn({repoRoot:t});if(d(n))return s(n.message);if(!n.value)return l("No remote available for state branch upstream",!1);let o=Je(e);if(d(o))return o;let i=o.value,a=await br({repoRoot:t,branch:i});if(d(a))return s(a.message);if(!a.value)return l("Remote state branch missing; upstream will be configured on first push",!1);ce.info(`Configuring ${i} upstream`);let c=await j.fetch({cwd:t,remote:fe,branch:i});if(d(c))return s(`Failed to fetch ${i}
44
+ ${c.message}`);let u=await j.setUpstream({cwd:t,branch:i,upstream:`${fe}/${i}`});return d(u)?s(`Failed to set state branch upstream
45
+ ${u.message}`):l("Configured state branch upstream",!0)},kr=async({stateBranchRoot:e,eventFileName:t})=>{let r=$i(t),n=Ut.join(e,r);if(!pt.existsSync(n))return l("No event file to stage",void 0);let o=await j.stage({cwd:e,pathspec:[r]});return d(o)?s(`Failed to stage state branch event file
46
+ ${o.message}`):l("Staged state branch event file",void 0)},Gi=async({repoRoot:e,stateBranchRoot:t})=>{let r=await sc(e);return d(r)?s(`Create state branch sync commit failed
47
+ `+r.message):mt({cwd:t,message:r.value})},$t=async({repoRoot:e,stateBranchRoot:t})=>{let r=await On(t);if(d(r))return s(r.message);let n=Je(e);if(d(n))return n;let o=n.value,i=r.value?await j.push({cwd:t}):await j.push({cwd:t,remote:fe,branch:o,setUpstream:!0});return d(i)?s(`Failed during state branch push
48
+ ${i.message}`):l("Pushed state branch",!0)},Yi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:r})=>{let n=!1,o=Je(e);if(d(o))return o;let i=o.value,a=[Tr(),await ac({repoRoot:e,stateBranchName:i}),await $n({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await lc({stateBranchRoot:t,stateBranchName:i}),await Vi(t),r?await uc({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of a){if(d(c))return s(c.message);n=n||!!c.value}return l(r?"Bootstrapped state storage":"Bootstrapped state storage (readonly)",n)};import Lr from"node:fs";import Wn from"node:path";import{decodeTime as mc}from"ulid";var _n=e=>{let[t,r]=e.id;return`${t}:${r??""}`},Xi=e=>{let[t]=e.id;return mc(t)},pc=e=>{let{userId:t,userName:r,...n}=e;return n},gc=e=>e.length===0?"":e.map(t=>JSON.stringify(pc(t))).join(`
54
49
  `)+`
55
- `,ac=(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))})},wr=({sourceFile:e,targetFile:t})=>{let n=Yt(e);if(d(n))return s(n.message);let r=Yt(t);if(d(r))return s(r.message);let o=ac(r.value,n.value),i=sc(o);return(vn.existsSync(t)?vn.readFileSync(t,"utf8"):"")===i?l("Event file already merged",!1):(vn.mkdirSync(Tr.dirname(t),{recursive:!0}),vn.writeFileSync(t,i,"utf8"),l("Merged event file",!0))},Mr=({repoRoot:e,stateBranchRoot:t})=>{let n=Fi(t);if(d(n))return s(n.message);let r=Xe(t),o=Xe(e),i=!1;for(let a of n.value){let c=Tr.join(r,a),u=Tr.join(o,a),m=wr({sourceFile:c,targetFile:u});if(d(m))return s(m.message);i=i||m.value}return l("Hydrated event files from state branch",i)};var qi=async(e=process.cwd())=>{let t=await Gi({cwd:e,ensureUpstream:!1});if(d(t))return t;let{repoRoot:n,stateBranchRoot:r}=t.value,o=await fn({cwd:r,branch:O});if(d(o))return s(o.message);let i=Mr({repoRoot:n,stateBranchRoot:r});return d(i)?s(i.message):l("Synced state branch",{repoRoot:n,stateBranchRoot:r})},cc=({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=Sr({root:e,fileName:n}),o=Sr({root:t,fileName:n});return dc.existsSync(r)?wr({sourceFile:r,targetFile:o}):l("Local own event file missing, nothing to merge",!1)},Gi=async({cwd:e,ensureUpstream:t})=>{let n=await Ui(e);if(d(n))return s(n.message);let r=n.value,o=ki(r);if(d(o))return s(o.message);let i=o.value,a=await Cr(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 c=await Wi(r);if(d(c))return s(c.message);let u=await Ki({repoRoot:r,stateBranchRoot:i,ensureUpstream:t});if(d(u))return s(u.message);let m=await Cr(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=Oi(r,i);return d(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=cc({repoRoot:e,stateBranchRoot:t,ownEventFileName:n});if(d(r))return s(r.message);let o=await Si(t);if(d(o))return s(o.message);if(!r.value&&!o.value)return l("Own event file already up to date in state branch",{createdCommit:!1});let i=await ji({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):l("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:a.value})},Yi=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 Gi({cwd:e,ensureUpstream:!0});if(d(n))return n;let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,a=await Ai(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 c=!1,u,m=!1,p=!1,v=!1,E=await fn({cwd:o,branch:O});if(d(E))return s(E.message);m=E.value;let S=Mr({repoRoot:r,stateBranchRoot:o});if(d(S))return s(S.message);v=S.value;let A=await zi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(d(A))return s(A.message);if(c=A.value.createdCommit,u=A.value.commitSha,c||i){let I=await Ar(o),C=I;if(d(I)&&Ii(I.message)){let T=await fn({cwd:o,branch:O});if(d(T))return s(T.message);let B=await zi({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(d(B))return s(B.message);B.value.createdCommit&&(c=!0,u=B.value.commitSha),C=await Ar(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(c){let I=await D({args:["rev-parse","HEAD"],cwd:o});if(d(I))return s(I.message);u=I.value.stdout.trim()}return l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,hydrated:v,bootstrapped:i})};var Ji=()=>{let{currentNode:e,selectedIndex:t}=x(),n=w(e.id)[t];return{currentNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:n?.parentNodeId??null,selectedIndex:t}},Xi=(e,t)=>Math.max(0,Math.min(e,Math.max(0,t-1))),Zi=e=>{let{nodes:t}=x(),n=t[e.currentNodeId];if(n&&!n.isDeleted&&e.selectedNodeId){let i=w(n.id).findIndex(a=>a.id===e.selectedNodeId);if(i>=0)return L.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=w(i.id).findIndex(c=>c.id===o.id);if(a>=0)return L.navigate({currentNode:i,selectedIndex:a}),l("Restored navigation to moved node",null)}}}if(n&&!n.isDeleted){let o=w(n.id);return L.navigate({currentNode:n,selectedIndex:Xi(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=w(o.id);return L.navigate({currentNode:o,selectedIndex:Xi(e.selectedIndex,i.length)}),l("Restored navigation to parent",null)}}let r=t[x().rootNodeId];return!r||r.isDeleted?s("Unable to restore navigation"):(L.navigate({currentNode:r,selectedIndex:0}),l("Restored navigation to root",null))};import{ulid as lc}from"ulid";var Qi=null,We=()=>structuredClone(Qi),kt=e=>Qi=e,es=()=>{let{currentNode:e,selectedIndex:t}=x(),r=w(e.id)[t];return r?l("Resolved selected child",r):s("Target node not found")};var ts=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ee();if(d(r))return s("Unable to resolve user ID");let o=tt(t,e,n,r.value);return d(o)?o:l("Created pending move state",{id:lc(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value}})},ns=e=>{kt(e);let t=xt(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function Pr(e){let t=es();if(d(t))return t;let{currentNode:n,nodes:r}=x();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 c=i[a+e];if(!c)return s("Missing sibling node");let u=ts({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:ns(u.value)}function kr(e){let t=es();if(d(t))return t;let{currentNode:n,selectedIndex:r}=x(),i=F(n.id)[r+e];if(!i)return s("Missing sibling node");let a=ts({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(a)?a:ns(a.value)}import yc from"node:os";import ss from"node:path";import{z as Lt}from"zod";import{accessSync as uc,copyFileSync as mc,existsSync as xn,mkdirSync as rs,readdirSync as os,readFileSync as pc,renameSync as gc,rmSync as fc,statSync as is,unlinkSync as vc,writeFileSync as xc}from"node:fs";import lt from"node:path";var de={writeToFile:(e,t)=>{try{let n=lt.dirname(e);xn(n)||rs(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);xc(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return pc(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 xn(e)&&is(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await uc(e),!0}catch{return!1}},mkDir:e=>rs(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=lt.parse(t);for(;;){let r=lt.join(t,e);try{if(xn(r)&&is(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=lt.dirname(t)}return null},readFirstJSON(e){try{if(!de.dirExists(e))return null;let t=os(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=lt.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)?os(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{vc(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{fc(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(lt.dirname(t)),!n?.overwrite&&xn(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{gc(e,t)}catch(r){if(r?.code==="EXDEV"){mc(e,t),this.rmFile(e);return}throw r}}};var hc={userId:"",userName:"",preferredEditor:"",autoSync:!1},as=Lt.object({preferredEditor:Lt.string().optional(),userName:Lt.string().optional(),userId:Lt.string().optional(),autoSync:Lt.boolean().optional()}).strict(),Ec="config.json",ds=()=>ss.join(yc.homedir(),ce),Lr=()=>ss.join(ds(),Ec),Dr=()=>{try{return de.mkDir(ds()),l(`Ensured ~/${ce} exists`,null)}catch{return s(`Unable to create ~/${ce}`)}},Nc=e=>{let t;try{t=JSON.parse(e)}catch{return s(`Invalid ~/${ce}/config.json JSON`)}let n=as.safeParse(t??{});return n.success?l("Parsed config",n.data):s(`Invalid ~/${ce}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},cs=()=>{let e=Dr();if(d(e))return s(e.message);let t=Lr(),n=de.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{autoSync:!1,preferredEditor:"",userId:"",userName:""}):Nc(n)},ls=e=>{let t=Dr();if(d(t))return s(t.message);let n=as.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)+`
56
- `),l("Config written",null)}catch{return s(`Unable to write ~/${ce}/config.json`)}},yn=e=>{let t=cs();if(d(t))return s("Failed to read existing config");let n={...t.value,...e};return ls(n)},us=()=>{let e=Lr(),t=Dr();if(d(t))return s(`Unable to create ~/${ce}`);if(!(de.readFile(e)!==null)){let u=ls(hc);if(d(u))throw new Error(`Unable to create ~/${ce}/config.json`)}let r=cs();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:a,autoSync:c}=r.value;return!i||!a?s(`User name or ID not configured in ~/${ce}/config.json`):l("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:a,autoSync:c??!1})};import{spawnSync as Cc}from"node:child_process";import bc from"node:os";import ms from"node:path";import{ulid as Ic}from"ulid";function Sc(){let{preferredEditor:e}=fe(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Ac(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function ps(e){let t=ms.join(bc.tmpdir(),"epiq");de.mkDir(t);let n=ms.join(t,Ic());de.writeToFile(n,e??"");let r=Sc();for(let o of r){let i=Ac(o,n),a=Cc(i,{stdio:"inherit",shell:!0});if(!a.error&&a.status===0){let c=de.readFile(n);if(c==null)return s("Unable to read edited file");let u=c.replace(/\r?\n$/,"");return l("Successfully edited",u)}}return s("Unable to open editor")}import{monotonicFactory as Rc,ulid as hn}from"ulid";var En=Rc(),gs=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=En(),a=En(),c=En(),u=En(),m=mo();if(d(m))return m;let p=V(m.value,void 0);if(d(p))return p;let v=V(p.value,void 0);return d(v)?v:l("Created issue events",[{id:hn(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}},{id:hn(),userId:r,userName:o,action:"add.field",payload:{id:a,parent:i,name:"Description",val:"",rank:m.value}},{id:hn(),userId:r,userName:o,action:"add.field",payload:{id:c,parent:i,name:"Assignees",rank:p.value}},{id:hn(),userId:r,userName:o,action:"add.field",payload:{id:u,parent:i,name:"Tags",rank:v.value}}])};import Fr from"chalk";import{monotonicFactory as Tc,ulid as Pe}from"ulid";var ke="system",Le="ACTOR",Dt=Tc();function wc(){let e=Object.values(x().nodes).find(r=>r.context==="WORKSPACE");if(!e)throw new Error("No workspace found in event log");let[t]=w(e.id),[n]=t?w(t.id):[];if(logger.debug("Boot navigation target:",{workspace:e?.id,firstBoard:t?.id,firstSwimlane:n?.id}),n){let r=x().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:x().nodes[x().rootNodeId],selectedIndex:0}}function Mc(){let e=wc();L.navigate(e)}function fs(){let e=Dt(),t=Dt(),n=Dt(),r=Dt(),o=Dt(),i=V(void 0,void 0);if(d(i))return i;let a=V(void 0,void 0);if(d(a))return a;let c=V(a.value,void 0);if(d(c))return c;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 v=V(void 0,void 0);return d(v)?v:l("Created default events",[{id:Pe(),userId:ke,userName:Le,action:"init.workspace",payload:{id:e,name:"Workspace",rank:i.value}},{id:Pe(),userId:ke,userName:Le,action:"add.board",payload:{id:t,name:"Default",parent:e,rank:a.value}},{id:Pe(),userId:ke,userName:Le,action:"add.swimlane",payload:{id:n,name:"Todo",parent:t,rank:u.value}},{id:Pe(),userId:ke,userName:Le,action:"add.swimlane",payload:{id:r,name:"In progress",parent:t,rank:m.value}},{id:Pe(),userId:ke,userName:Le,action:"add.swimlane",payload:{id:o,name:"Done",parent:t,rank:p.value}},{id:Pe(),userId:ke,userName:Le,action:"add.board",payload:{id:qt,name:"Closed",parent:e,rank:c.value}},{id:Pe(),userId:ke,userName:Le,action:"add.swimlane",payload:{id:Se,name:"Closed",parent:qt,rank:v.value}},{id:Pe(),userId:ke,userName:Le,action:"lock.node",payload:{id:qt}},{id:Pe(),userId:ke,userName:Le,action:"lock.node",payload:{id:Se}}])}function Nn(e){if(!e.some(r=>r.action==="init.workspace")){let r=Y.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=ht(r);return d(o)?o:(R({hasProject:!1,mode:g.DEFAULT}),l("Booted uninitialized workspace placeholder",null))}let n=yt(e).filter(d);return n.length>0?s([Fr.bold.red("Materializing failed"),"",...n.map((r,o)=>`${Fr.dim.gray(`${o+1}.`)} ${Fr.dim(r.message)}`),`
57
- `].join(`
50
+ `,fc=(e,t)=>{let r=new Map;for(let n of[...t,...e])r.set(_n(n),n);return[...r.values()].sort((n,o)=>{let i=Xi(n)-Xi(o);return i!==0?i:_n(n).localeCompare(_n(o))})},jn=({sourceFile:e,targetFile:t})=>{let r=ir(e);if(d(r))return s(r.message);let n=ir(t);if(d(n))return s(n.message);let o=fc(n.value,r.value),i=gc(o);return(Lr.existsSync(t)?Lr.readFileSync(t,"utf8"):"")===i?l("Event file already merged",!1):(Lr.mkdirSync(Wn.dirname(t),{recursive:!0}),Lr.writeFileSync(t,i,"utf8"),l("Merged event file",!0))},_t=({repoRoot:e,stateBranchRoot:t})=>{let r=Hi(t);if(d(r))return s(r.message);let n=Ze(t),o=Ze(e),i=!1;for(let a of r.value){let c=Wn.join(n,a),u=Wn.join(o,a),m=jn({sourceFile:c,targetFile:u});if(d(m))return s(m.message);i=i||m.value}return l("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:r,stateBranchRoot:n}=t.value,o=Je(e);if(d(o))return o;let i=o.value,a=await Ar({cwd:n,branch:i});if(d(a))return s(a.message);let c=_t({repoRoot:r,stateBranchRoot:n});return d(c)?s(c.message):l("Synced state branch",{repoRoot:r,stateBranchRoot:n})},xc=({repoRoot:e,stateBranchRoot:t,ownEventFileName:r})=>{let n=Un({root:e,fileName:r}),o=Un({root:t,fileName:r});return vc.existsSync(n)?jn({sourceFile:n,targetFile:o}):l("Local own event file missing, nothing to merge",!1)},Qi=async({cwd:e,ensureUpstream:t})=>{let r=await Mr(e);if(d(r))return s(r.message);let n=r.value,o=Wi({repoRoot:n});if(d(o))return s(o.message);let i=o.value,a=await Ft(n);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 c=await zi(n);if(d(c))return s(c.message);let u=await Yi({repoRoot:n,stateBranchRoot:i,ensureUpstream:t});if(d(u))return s(u.message);let m=await Ft(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=Ki(n,i);return d(p)?s(p.message):l("Sync preconditions satisfied",{repoRoot:n,stateBranchRoot:i,bootstrapped:u.value})},Ji=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:r})=>{let n=xc({repoRoot:e,stateBranchRoot:t,ownEventFileName:r});if(d(n))return s(n.message);let o=await Fi(t);if(d(o))return s(o.message);if(!n.value&&!o.value)return l("Own event file already up to date in state branch",{createdCommit:!1});let i=await kr({stateBranchRoot:t,eventFileName:r});if(d(i))return s(i.message);let a=await Gi({repoRoot:e,stateBranchRoot:t});return d(a)?s(a.message):l("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:a.value})},es=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 r=await Qi({cwd:e,ensureUpstream:!0});if(d(r))return r;let{repoRoot:n,stateBranchRoot:o,bootstrapped:i}=r.value,a=await Bi(n);if(d(a))return s(a.message);if(a.value)return s("Cannot run :sync while the repository is in detached HEAD state");let c=!1,u,m=!1,p=!1,v=!1,y=Je(n);if(d(y))return y;let I=y.value,R=await Ar({cwd:o,branch:I});if(d(R))return s(R.message);m=R.value;let S=_t({repoRoot:n,stateBranchRoot:o});if(d(S))return s(S.message);v=S.value;let C=await Ji({repoRoot:n,stateBranchRoot:o,ownEventFileName:t});if(d(C))return s(C.message);if(c=C.value.createdCommit,u=C.value.commitSha,c||i){let w=await $t({stateBranchRoot:o,repoRoot:n}),B=w;if(d(w)&&Di(w.message)){let se=await Ar({cwd:o,branch:I});if(d(se))return s(se.message);let J=await Ji({repoRoot:n,stateBranchRoot:o,ownEventFileName:t});if(d(J))return s(J.message);J.value.createdCommit&&(c=!0,u=J.value.commitSha),B=await $t({stateBranchRoot:o,repoRoot:n})}if(d(B))return s(B.message);p=B.value,logger.debug("[sync] pushed to state branch",p)}else logger.debug("[sync] no commit created, skipped push");if(c){let w=await D({args:["rev-parse","HEAD"],cwd:o});if(d(w))return s(w.message);u=w.value.stdout.trim()}return l("Synced event logs with state branch",{repoRoot:n,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,hydrated:v,bootstrapped:i})};var rs=()=>{let{currentNode:e,selectedIndex:t}=x(),r=T(e.id)[t];return{currentNodeId:e.id,selectedNodeId:r?.id??null,parentNodeId:r?.parentNodeId??null,selectedIndex:t}},ts=(e,t)=>Math.max(0,Math.min(e,Math.max(0,t-1))),ns=e=>{let{nodes:t}=x(),r=t[e.currentNodeId];if(r&&!r.isDeleted&&e.selectedNodeId){let i=T(r.id).findIndex(a=>a.id===e.selectedNodeId);if(i>=0)return L.navigate({currentNode:r,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=T(i.id).findIndex(c=>c.id===o.id);if(a>=0)return L.navigate({currentNode:i,selectedIndex:a}),l("Restored navigation to moved node",null)}}}if(r&&!r.isDeleted){let o=T(r.id);return L.navigate({currentNode:r,selectedIndex:ts(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=T(o.id);return L.navigate({currentNode:o,selectedIndex:ts(e.selectedIndex,i.length)}),l("Restored navigation to parent",null)}}let n=t[x().rootNodeId];return!n||n.isDeleted?s("Unable to restore navigation"):(L.navigate({currentNode:n,selectedIndex:0}),l("Restored navigation to root",null))};import{ulid as hc}from"ulid";var os=null,We=()=>structuredClone(os),Wt=e=>os=e,is=()=>{let{currentNode:e,selectedIndex:t}=x(),n=T(e.id)[t];return n?l("Resolved selected child",n):s("Target node not found")};var ss=({id:e,parentId:t,position:r={at:"end"}})=>{let n=ee();if(d(n))return s("Unable to resolve user ID");let o=ot(t,e,r,n.value);return d(o)?o:l("Created pending move state",{id:hc(),...n.value,action:"move.node",payload:{id:e,parent:t,rank:o.value}})},as=e=>{Wt(e);let t=Ct(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function Hn(e){let t=is();if(d(t))return t;let{currentNode:r,nodes:n}=x();if(!r.parentNodeId)return s("Missing parent node id");let o=n[r.parentNodeId];if(!o)return s("Missing parent node");let i=F(o.id),a=i.findIndex(({id:m})=>m===r.id);if(a<0)return s("Current node not found among siblings");let c=i[a+e];if(!c)return s("Missing sibling node");let u=ss({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:as(u.value)}function Kn(e){let t=is();if(d(t))return t;let{currentNode:r,selectedIndex:n}=x(),i=F(r.id)[n+e];if(!i)return s("Missing sibling node");let a=ss({id:t.value.id,parentId:r.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(a)?a:as(a.value)}import Rc from"node:os";import us from"node:path";import{z as jt}from"zod";import{accessSync as yc,copyFileSync as Ec,existsSync as Dr,mkdirSync as ds,readdirSync as cs,readFileSync as Nc,renameSync as Cc,rmSync as Ic,statSync as ls,unlinkSync as bc,writeFileSync as Sc}from"node:fs";import gt from"node:path";var me={writeToFile:(e,t)=>{try{let r=gt.dirname(e);Dr(r)||ds(r,{recursive:!0});let n=typeof t=="string"?t:JSON.stringify(t,null,2);Sc(e,n,"utf-8")}catch(r){logger.error(`Failed to write file at ${e}:`,r)}},readFile:e=>{try{return Nc(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=me.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 Dr(e)&&ls(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await yc(e),!0}catch{return!1}},mkDir:e=>ds(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:r}=gt.parse(t);for(;;){let n=gt.join(t,e);try{if(Dr(n)&&ls(n).isDirectory())return n}catch{logger.error(`Unable to locate folder ${e}`)}if(t===r)break;t=gt.dirname(t)}return null},readFirstJSON(e){try{if(!me.dirExists(e))return null;let t=cs(e).filter(n=>n.endsWith(".json")).sort()[0];if(!t)return null;let r=gt.join(e,t);return me.readFileJSON(r)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return me.dirExists(e)?cs(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{bc(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Ic(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,r){if(this.mkDir(gt.dirname(t)),!r?.overwrite&&Dr(t))throw new Error(`moveFile: destination exists: ${t}`);r?.overwrite&&this.rmFile(t);try{Cc(e,t)}catch(n){if(n?.code==="EXDEV"){Ec(e,t),this.rmFile(e);return}throw n}}};var Ac={userId:"",userName:"",preferredEditor:"",autoSync:!1},ms=jt.object({preferredEditor:jt.string().optional(),userName:jt.string().optional(),userId:jt.string().optional(),autoSync:jt.boolean().optional()}).strict(),wc="config.json",ps=()=>us.join(Rc.homedir(),pe),Vn=()=>us.join(ps(),wc),qn=()=>{try{return me.mkDir(ps()),l(`Ensured ~/${pe} exists`,null)}catch{return s(`Unable to create ~/${pe}`)}},Tc=e=>{let t;try{t=JSON.parse(e)}catch{return s(`Invalid ~/${pe}/config.json JSON`)}let r=ms.safeParse(t??{});return r.success?l("Parsed config",r.data):s(`Invalid ~/${pe}/config.json shape: ${r.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},gs=()=>{let e=qn();if(d(e))return s(e.message);let t=Vn(),r=me.readFile(t);return r==null||r.trim()===""?l("No config found, using empty config",{autoSync:!1,preferredEditor:"",userId:"",userName:""}):Tc(r)},fs=e=>{let t=qn();if(d(t))return s(t.message);let r=ms.safeParse(e);if(!r.success)return s(`Invalid config: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let n=Vn();try{return me.writeToFile(n,JSON.stringify(r.data,null,2)+`
51
+ `),l("Config written",null)}catch{return s(`Unable to write ~/${pe}/config.json`)}},Fr=e=>{let t=gs();if(d(t))return s("Failed to read existing config");let r={...t.value,...e};return fs(r)},vs=()=>{let e=Vn(),t=qn();if(d(t))return s(`Unable to create ~/${pe}`);if(!(me.readFile(e)!==null)){let u=fs(Ac);if(d(u))throw new Error(`Unable to create ~/${pe}/config.json`)}let n=gs();if(d(n))throw new Error(n.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:a,autoSync:c}=n.value;return!i||!a?s(`User name or ID not configured in ~/${pe}/config.json`):l("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:a,autoSync:c??!1})};import{monotonicFactory as Mc,ulid as Br}from"ulid";var Or=Mc(),xs=({name:e,parent:t,rank:r,user:{userId:n,userName:o}})=>{let i=Or(),a=Or(),c=Or(),u=Or(),m=So();if(d(m))return m;let p=z(m.value,void 0);if(d(p))return p;let v=z(p.value,void 0);return d(v)?v:l("Created issue events",[{id:Br(),userId:n,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:r}},{id:Br(),userId:n,userName:o,action:"add.field",payload:{id:a,parent:i,name:G.DESCRIPTION,val:"",rank:m.value}},{id:Br(),userId:n,userName:o,action:"add.field",payload:{id:c,parent:i,name:"Assignees",rank:p.value}},{id:Br(),userId:n,userName:o,action:"add.field",payload:{id:u,parent:i,name:"Tags",rank:v.value}}])};import{monotonicFactory as Pc,ulid as Fe}from"ulid";var Ht=Pc();function kc(){let e=Object.values(x().nodes).find(n=>n.context==="WORKSPACE");if(!e)throw new Error("No workspace found in event log");let[t]=T(e.id),[r]=t?T(t.id):[];if(logger.debug("Boot navigation target:",{workspace:e?.id,firstBoard:t?.id,firstSwimlane:r?.id}),r){let n=x().renderedChildrenIndex?.[r.id]??[];return{currentNode:r,selectedIndex:n.length>0?0:-1}}else return t?{currentNode:t,selectedIndex:0}:e?{currentNode:e,selectedIndex:0}:{currentNode:x().nodes[x().rootNodeId],selectedIndex:0}}function Lc(){let e=kc();L.navigate(e)}function hs({userId:e,userName:t}){let r=Ht(),n=Ht(),o=Ht(),i=Ht(),a=Ht(),c=z(void 0,void 0);if(d(c))return c;let u=z(void 0,void 0);if(d(u))return u;let m=z(u.value,void 0);if(d(m))return m;let p=z(void 0,void 0);if(d(p))return p;let v=z(p.value,void 0);if(d(v))return v;let y=z(v.value,void 0);if(d(y))return y;let I=z(void 0,void 0);return d(I)?I:l("Created default events",[{id:Fe(),userId:e,userName:t,action:"init.workspace",payload:{id:r,name:"Workspace",rank:c.value}},{id:Fe(),userId:e,userName:t,action:"add.board",payload:{id:n,name:"Default",parent:r,rank:u.value}},{id:Fe(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:n,rank:p.value}},{id:Fe(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"In progress",parent:n,rank:v.value}},{id:Fe(),userId:e,userName:t,action:"add.swimlane",payload:{id:a,name:"Done",parent:n,rank:y.value}},{id:Fe(),userId:e,userName:t,action:"add.board",payload:{id:nr,name:"Closed",parent:r,rank:m.value}},{id:Fe(),userId:e,userName:t,action:"add.swimlane",payload:{id:Te,name:"Closed",parent:nr,rank:I.value}},{id:Fe(),userId:e,userName:t,action:"lock.node",payload:{id:nr}},{id:Fe(),userId:e,userName:t,action:"lock.node",payload:{id:Te}}])}function Ur({hasProject:e,eventLog:t}){if(!e){let o=Q.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=bt(o);return d(i)?i:(A({hasProject:!1,mode:g.DEFAULT}),l("Booted uninitialized workspace placeholder",null))}if(!t.some(o=>o.action==="init.workspace"))return s("Initialized Epiq project has no workspace init event");let n=It(t).filter(d);return n.length>0?s(n.map(o=>o.message).join(`
52
+ `)):(Lc(),A({hasProject:!0}),l("State booted successfully",null))}var ys=e=>{let t=e.log??[];for(let r=t.length-1;r>=0;r--){let n=t[r];if(n&&n.action==="close.issue"&&n.payload.id===e.id)return n.payload.parent}return null};import{ulid as Cs}from"ulid";import{spawnSync as Dc}from"node:child_process";import Fc from"node:os";import Es from"node:path";import{ulid as Bc}from"ulid";function Oc(){let{preferredEditor:e}=le(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(r=>!!r?.trim());return[...new Set(t)]}function Uc(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function Ns(e){let t=Es.join(Fc.tmpdir(),"epiq");me.mkDir(t);let r=Es.join(t,Bc());me.writeToFile(r,e??"");let n=Oc();for(let o of n){let i=Uc(o,r),a=Dc(i,{stdio:"inherit",shell:!0});if(!a.error&&a.status===0){let c=me.readFile(r);if(c==null)return s("Unable to read edited file");let u=c.replace(/\r?\n$/,"");return l("Successfully edited",u)}}return s("Unable to open editor")}var Is=()=>{let e=ee();if(d(e))return s("Unable to resolve user ID");let{breadCrumb:t,selectedNode:r}=x(),n=Ne([...t,r],"TICKET");if(d(n))return s("Edit target must be an issue");let o=n.value;if(o.readonly)return s("Cannot edit readonly field");let i=T(o.id).find(m=>m.title===G.DESCRIPTION);if(!i)return s("No target found");if(i.readonly)return s("Cannot edit readonly field");let a=i.props.value;if(typeof a!="string")return s("Selected field is not editable text");let c=Ns(a);if(d(c))return s("Failed to edit field");let u=c.value;return u===a?l("No changes made",null):i.title===G.DESCRIPTION?K({id:Cs(),action:"edit.description",payload:{id:i.id,md:u},...e.value}):i.title==="Title"?K({id:Cs(),action:"edit.title",payload:{id:i.id,name:u},...e.value}):s(`Editing not supported for "${i.title}"`)};import _c from"node:fs";import Ss from"node:path";import zn from"node:fs";import $c from"node:path";var bs=async e=>{let t=$c.join(e,".gitignore"),r=zn.existsSync(t)?zn.readFileSync(t,"utf8"):"",n=[".epiq/events/",".epiq/log/"],o=r.split(`
53
+ `).map(u=>u.trim()),i=n.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 c=["# [epiq]: local hydrated state is never committed",...i].join(`
54
+ `);return r=r.trimEnd()+`
58
55
 
59
- See complete log:
60
-
61
- `)+e.map(r=>JSON.stringify(r)).join(`
62
- `)):(Mc(),l("State booted successfully",null))}var vs=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id)return r.payload.parent}return null};var xs=e=>Object.values(x().tags).find(t=>t.name===e),ys=e=>Object.values(x().contributors).find(t=>t.name===e),hs=[{systemOnly:!0,intent:M.Move,mode:g.COMMAND_LINE,action:()=>{let e=ee();if(d(e))return s("Unable to resolve user ID");let{modifier:t}=ne().commandMeta,n=()=>{let c=We();if(!c)return s("No pending move state");let u=c.payload.id;if(!x().nodes[u])return s("Moved node not found");let p=c.payload.parent,v=x().nodes[p];if(!v)return s("Move parent not found");let E=w(p).findIndex(S=>S.id===u);return E===-1?s("Moved node not found among rendered children"):(L.navigate({currentNode:v,selectedIndex:E}),l("Synchronized navigation to moved node",null))},r=c=>{if(d(c))return s(c.message);let u=n();return d(u)?s(u.message):l("Updated move preview",null)},{currentNode:o,selectedIndex:i}=x(),a=w(o.id)[i];if(!a)return R({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 c=F(a.parentNodeId),u=c.findIndex(({id:A})=>A===a.id);if(u===-1)return s("Target not found among siblings");let m=c[u-1],p=c[u+1],v=p!=null?{at:"before",sibling:p.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"},E=tt(a.parentNodeId,a.id,v,e.value);if(d(E))return E;kt({id:_(),action:"move.node",payload:{id:a.id,parent:a.parentNodeId,rank:E.value},...e.value}),R({mode:g.MOVE});let S=n();return d(S)?s(S.message):l("Move initialized",null)}if(t==="next")return R({mode:g.MOVE}),r(kr(1));if(t==="previous")return R({mode:g.MOVE}),r(kr(-1));if(t==="to-next")return R({mode:g.MOVE}),r(Pr(1));if(t==="to-previous")return R({mode:g.MOVE}),r(Pr(-1));if(t==="confirm"){R({mode:g.DEFAULT});let c=We();if(!c)return s("No pending move to confirm");let u=K(c);if(d(u))return u;let m=n();return d(m)?s(m.message):(kt(null),l("Moved item",null))}return t==="cancel"?(kt(null),R({mode:g.DEFAULT}),l("Cancelling move",null)):s("Invalid move modifier")}},{intent:M.Delete,mode:g.COMMAND_LINE,action:()=>{let e=ee();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=x(),r=w(t.id)[n];return r?K({id:_(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>R({mode:g.DEFAULT})},{intent:M.Edit,mode:g.COMMAND_LINE,action:()=>{let e=ee();if(d(e))return s("Unable to resolve user ID");let t=be(x().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}=x();if(!w(n.id)[o])return s("No selected field");let a=w(r.id)[o];if(!a)return s("No selected field");if(a.readonly)return s("Cannot edit readonly field");let c=a.props.value;if(typeof c!="string")return s("Selected field is not editable text");let u=ps(c);if(d(u))return s("Failed to edit field");let m=u.value;return m===c?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:()=>R({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||!(c=>z(f.FILTER).map(u=>u.split(n)[0]).includes(c))(r))return s("Invalid filter modifier");let a={target:r,operator:"=",value:t.trim()};return ae(c=>({...c,filters:e==="clear"?[]:[...c.filters,a],mode:g.DEFAULT})),l("Viewing help",null)}},{intent:M.ViewHelp,mode:g.COMMAND_LINE,action:()=>(R({mode:g.HELP}),l("Viewing help",null))},{intent:M.CloseIssue,mode:g.COMMAND_LINE,action:()=>{let e=ee();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=x(),r=w(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=x().nodes[Se];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:l("Issue closed",null)},onSuccess:()=>R({mode:g.DEFAULT})},{intent:M.ReopenIssue,mode:g.COMMAND_LINE,action:()=>{let e=ee();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=x(),r=w(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):Ue(r.id,"TICKET");if(d(o))return s("Cannot reopen in this context");let i=o.value,a=x().nodes[Se];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 c=vs(i);if(!c)return s("Unable to resolve previous parent from issue history");if(c===a.id)return s("Previous parent resolves to closed swimlane");let u=x().nodes[c];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:l("Issue reopened",null)},onSuccess:()=>R({mode:g.DEFAULT})},{intent:M.SetUserName,mode:g.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:n}=fe(),r=rn()?.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=yn({userName:o,userId:i,preferredEditor:t??""});return d(a)?a:(Qe({userName:o,userId:i}),R({mode:g.DEFAULT}),l(`Username set to "${r}"`,null))}},{intent:M.Init,mode:g.COMMAND_LINE,action:async()=>{let e=eo(process.cwd());if(d(e))return e;let t=await vi(process.cwd());if(d(t))return t;let n=fs();if(d(n))return n;let o=Gn(n.value).filter(d);if(o.length>0)return s(o.map(c=>c.message).join(`
63
- `));let{rootNodeId:i,nodes:a}=x();return L.navigate({currentNode:a[i],selectedIndex:0}),R({hasProject:!0,mode:g.DEFAULT}),l("Project initialized",null)}},{intent:M.SetEditor,mode:g.COMMAND_LINE,action:()=>{let e=rn()?.trim();if(!e)return s("No editor provided");let t=yn({preferredEditor:e});return d(t)?t:(Qe({preferredEditor:e}),R({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=yn({autoSync:t});return d(n)?n:(Qe({autoSync:t}),R({mode:g.DEFAULT}),l(`Auto synchronization set to "${t}"`,null))}},{intent:M.NewItem,mode:g.COMMAND_LINE,action:(e,t)=>{let n=ee();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}=x(),a=c=>{let u=K(c);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?(L.navigate({currentNode:p,selectedIndex:b.getSiblings(m.parentNodeId).findIndex(({id:v})=>v===m.id)}),u):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:c}=x(),u=b.getNode(c);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 c=be(r,"BOARD");if(d(c))return s("Unable to add swimlane in this context");let u=nt(c.value.id,n.value);return d(u)?u:a({id:_(),action:"add.swimlane",payload:{id:_(),name:t.inputString,parent:c.value.id,rank:u.value},...n.value})}if(t.modifier==="issue"){let c=w(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&c?.context==="SWIMLANE"?c:(()=>{let C=be(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=gs({name:t.inputString,parent:u.id,rank:m.value,user:n.value});if(d(p))return p;let v=p.value,E=Gn(v);if(E.some(C=>d(C)))return s("Issue create failed: "+E.filter(d).map(C=>C.message).filter(Boolean).join(", "));let S=E[0];if(!S||d(S))return s("Issue creation failed");let I=v.find(C=>C.action==="add.issue")?.payload.id;return I?(L.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:()=>R({mode:g.DEFAULT})},{intent:M.SetView,mode:g.COMMAND_LINE,action:()=>{let{commandMeta:e}=ne();return e.validity===Ae.Invalid?s("Invalid command "+Ee):(ae(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),l("View set",null))},onSuccess:()=>R({mode:g.DEFAULT})},{intent:M.Rename,mode:g.COMMAND_LINE,action:()=>{let e=ee();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=x(),r=w(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=rn();return o?K({id:_(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>R({mode:g.DEFAULT})},{intent:M.UntagTicket,mode:g.COMMAND_LINE,action:()=>{let e=ee();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=xs(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=x();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 c=a.value,u=b.getFieldByTitle(c.id,"Tags");if(!u)return s("Unable to locate tags field");let m=w(u.id).find(p=>p.props?.value===o.id);return m?K({id:_(),action:"untag.issue",payload:{id:m.id,target:c.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>R({mode:g.DEFAULT})},{intent:M.TagTicket,mode:g.COMMAND_LINE,action:()=>{let e=ee();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}=x(),a=w(i.id)[o];if(!a)return s("Invalid tag target");let c=Ue(a.id,"TICKET");if(d(c))return s("Unable to tag issue in this context");let u=c.value,m=xs(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 v=b.getFieldByTitle(u.id,"Tags");if(!v)return s("Unable to locate tags field");if(w(v.id).some(A=>A.props?.value===p))return s("Already tagged with that tag");let S=nt(v.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:()=>R({mode:g.DEFAULT})},{intent:M.AssignUserToTicket,mode:g.COMMAND_LINE,action:()=>{let e=ee();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}=x(),a=w(i.id)[o];if(!a)return s("Invalid assign target");let c=Ue(a.id,"TICKET");if(d(c))return s("Unable to assign issue in this context");let u=c.value,m=ys(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 v=b.getFieldByTitle(u.id,"Assignees");if(!v)return s("Unable to locate assignees field");if(w(v.id).some(A=>A.props?.value===p))return s("Assignee already assigned");let S=nt(v.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:()=>R({mode:g.DEFAULT})},{intent:M.UnassignUserFromTicket,mode:g.COMMAND_LINE,action:()=>{let e=ee();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=ys(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=x();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 c=a.value,u=b.getFieldByTitle(c.id,"Assignees");if(!u)return s("Unable to locate assignees field");let m=w(u.id).find(p=>p.props?.value===o.id);return m?K({id:_(),action:"unassign.issue",payload:{id:m.id,target:c.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${r}"`)},onSuccess:()=>R({mode:g.DEFAULT})},{intent:M.Sync,mode:g.COMMAND_LINE,action:async()=>{let e=Ji();H(()=>""),R({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=ee();if(d(r)||!r.value)return s("Unable to resolve event log path");let o=qn(r.value),i=await Yi({ownEventFileName:o});if(d(i))return R({syncStatus:{msg:i.message,status:"outOfSync"}}),s(`Unable to sync state. ${i.message}`);let a=Be(process.cwd());if(d(a))return a;let c=Et(a.value);if(d(c))return s(`Unable to load events. ${c.message}`);let u=Nn(c.value);if(d(u))return s(`Unable to boot synced state. ${u.message}`);R({hasProject:!0,syncStatus:{msg:"Synced",status:"synced"},mode:g.DEFAULT});let m=Zi(e);return d(m)?m:l("Synced",!0)}},{intent:M.Peek,mode:g.COMMAND_LINE,action:async()=>{let e=be(x().breadCrumb,"BOARD");if(d(e))return e;let t=Oe(process.cwd());if(d(t))throw new Error(t.message);let n=Et(t.value);if(d(n))return s(n.message);let r=n.value,{modifier:o}=ne().commandMeta,i;if(o==="now"){let E=Or();if(d(E))return E;let S=yt(r);return S.some(d)?s(S.map(A=>A.message).join(", ")):(R({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),l("Peeking now",!0))}if(o==="prev"){let E=x().eventLog.at(-2),S=tr(E);if(S===null)return s("No previous event to peek");i=S}else if(o==="next"){let E=x().unappliedEvents.at(0),S=tr(E);if(S===null)return s("No next event to peek");i=S}else{let E=Qt(o);if(!E)return s("Invalid peek date");i=E.getTime()}let a=e.value.id,{appliedEvents:c,unappliedEvents:u}=vo(r,i),m=Or();if(d(m))return m;let p=yt(c);if(p.some(d))return s(p.map(E=>E.message).join(", "));let v=x().nodes[a];return v?(L.navigate({currentNode:v,selectedIndex:0}),R({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 mi();return d(e)?e:(R({mode:g.DEFAULT}),l("Export successful",!0))}},{intent:M.Exit,mode:g.COMMAND_LINE,action:async()=>(L.exit(),l("Exit successful",!0))}];var Pc=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===Ae.Invalid)return s("Invalid command");let i=Yo(t);if(Ho(),x().readOnly&&!Pc.has(i))return St({status:Ee.Fail,message:"Command not available in readonly state",value:null});let a=hs.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 c=await a.action(a,{command:t,inputString:o,modifier:r});return d(c)?St(c):(Ko({addToHistory:!e}),a.onSuccess?.(),St(c))};var Cn=[{intent:y.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(R({mode:g.COMMAND_LINE}),H(()=>"move cancel"),me({isForceExecutedBySystem:!0}))},{intent:y.InitMove,mode:g.DEFAULT,description:"[m] move init/confirm",action:()=>(R({mode:g.COMMAND_LINE}),H(()=>"move start"),me({isForceExecutedBySystem:!0}))},{intent:y.ConfirmMove,mode:g.MOVE,action:()=>(R({mode:g.COMMAND_LINE}),H(()=>"move confirm"),me({isForceExecutedBySystem:!0}))}],bn=[{intent:y.MovePreviousItem,mode:g.MOVE,action:()=>We()?(R({mode:g.COMMAND_LINE}),H(()=>"move previous"),me({isForceExecutedBySystem:!0})):s("No pending move")},{intent:y.MoveNextItem,mode:g.MOVE,action:()=>We()?(R({mode:g.COMMAND_LINE}),H(()=>"move next"),me({isForceExecutedBySystem:!0})):s("No pending move")}],Es=[{intent:y.MoveToNextContainer,mode:g.MOVE,action:()=>We()?(R({mode:g.COMMAND_LINE}),H(()=>"move to-next"),me({isForceExecutedBySystem:!0})):s("No pending move")},{intent:y.MoveToPreviousContainer,mode:g.MOVE,action:()=>We()?(R({mode:g.COMMAND_LINE}),H(()=>"move to-previous"),me({isForceExecutedBySystem:!0})):s("No pending move")}];var Ns={[P.WORKSPACE]:[...Cn,...bn],[P.BOARD]:[...Cn,...bn],[P.SWIMLANE]:[...Cn,...bn,...Es],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var Cs=[{intent:y.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(R({mode:g.COMMAND_LINE}),H(()=>`${f.NEW} `),l("Adding new item",null))},{intent:y.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(R({mode:g.COMMAND_LINE}),H(()=>`${f.DELETE} `),l("Deleting item",null))},{intent:y.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(R({mode:g.COMMAND_LINE}),H(()=>""),l("Entering command line mode",null))},{intent:y.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(L.enterChildNode(),l("Entering context",null))},{intent:y.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(L.enterParentNode(),l("Exiting context",null))},{intent:y.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(L.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:y.NavNextItem,mode:g.DEFAULT,action:()=>(L.navigateToNextItem(),l("Navigating to next item",null))},{intent:y.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(L.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:y.NavToNextContainer,mode:g.DEFAULT,action:()=>(L.navigateToNextContainer(),l("Navigating to next container",null))},{intent:y.Edit,mode:g.DEFAULT,action:()=>(R({mode:g.COMMAND_LINE}),H(()=>"edit"),me(),l("Fired command",!0))},{intent:y.SetViewDense,mode:g.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(R({viewMode:"dense"}),l("View set",null))},{intent:y.SetViewWide,mode:g.DEFAULT,action:()=>(R({viewMode:"wide"}),l("View set",null))}];var kc=500,Lc=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),bs=e=>{let t=Lc(e);t&&H(n=>(n+t).slice(0,kc))};var Is=[{intent:y.ViewHelp,mode:g.DEFAULT,action:()=>(R({mode:g.HELP}),l("Viewing help",null))},{intent:y.Exit,mode:g.HELP,action:()=>(R({mode:g.DEFAULT}),l("Exiting help",null))},{intent:y.Confirm,mode:g.COMMAND_LINE,action:()=>(me(),l("Executing command",null))},{intent:y.MoveCursorLeft,mode:g.COMMAND_LINE,action:()=>(cr(-1),l("Moving cursor left",null))},{intent:y.MoveCursorRight,mode:g.COMMAND_LINE,action:()=>(cr(1),l("Moving cursor right",null))},{intent:y.MoveCursorLeftOfWord,mode:g.COMMAND_LINE,action:()=>(lr("left"),l("Moving cursor left of word",null))},{intent:y.MoveCursorRightOfWord,mode:g.COMMAND_LINE,action:()=>(lr("right"),l("Moving cursor right of word",null))},{intent:y.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(R({mode:g.DEFAULT}),l("Exiting command line",null))},{intent:y.AutoCompleteCommand,mode:g.COMMAND_LINE,action:()=>(H((e,{remainder:t})=>t?e+t:e),l("Auto-completing command",null))},{intent:y.CaptureInput,mode:g.COMMAND_LINE,action:(e,{sequence:t})=>(bs(t??""),l("Capturing input",null))},{intent:y.EraseInput,mode:g.COMMAND_LINE,action:()=>(Wo(),l("Erasing input",null))},{intent:y.EraseInputWord,mode:g.COMMAND_LINE,action:()=>(jo(),l("Erasing input word",null))},{intent:y.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(Vo(),l("Getting last command from history",null))},{intent:y.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(zo(),l("Getting next command from history",null))}];import Dc from"chalk";var In=": for command line",Ss="q to exit",As=`${Dc.hex(N.accent)("m")} to confirm`,Br={[P.WORKSPACE]:[In],[P.BOARD]:[In],[P.BOARD+g.COMMAND_LINE]:[In],[P.SWIMLANE]:[In],[P.TICKET+g.HELP]:[Ss],[P.SWIMLANE+g.HELP]:[Ss],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+g.MOVE]:[As],[P.TICKET+g.MOVE]:[As]};var Sn=e=>e.trim().toLocaleLowerCase(),Fc=(e,t)=>{let n=b.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},Oc=e=>{let{tags:t}=x(),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):[]},Bc=e=>{let{contributors:t}=x(),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 Sn(e.title??"").includes(n);case"description":return Sn(Fc(e.id,"Description")).includes(n);case"tag":return Oc(e.id).map(Sn).some(c=>c.includes(n));case"assignee":return Bc(e.id).map(Sn).some(c=>c.includes(n));default:return!0}};function Ts(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 ws=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 An,Ur,$r=new Set,Ms=()=>{for(let e of $r)e()},$c=e=>($r.add(e),()=>$r.delete(e));function Ps(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 c=o[t];if(!c)return s("Unable to derive state, currentNode not found");let u=Ts(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,v=Br[p+n]??Br[p]??[],E=[...Cs,...Ns[p]??[],...Is],S=ws(E),A=_c(o,i),I=A[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,currentNode:c,breadCrumb:m,availableHints:v,availableActions:E,actionIndex:S,selectedNode:I,renderedChildrenIndex:A})}var x=()=>(An||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),An);function ht(e){Ur=e;let t=Be(process.cwd()),n=!1;if(!d(t)){let i=Ze(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=Ps(r);return d(o)?o:(An=o.value,Ms(),l("State initialized",null))}function ae(e){let t=x(),n=e(t),r=Ps(n);return d(r)?s(r.message??"Unable to update state"):(An=r.value,Ms(),l("State updated",null))}var R=e=>ae(t=>({...t,...e}));var $=()=>Uc($c,x,x),_c=(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],c=e[i.id];return!a||!c?0:a.rank.localeCompare(c.rank)});return n},w=e=>x()?.renderedChildrenIndex[e]??[],Or=()=>Ur?ht(Ur):s("Cannot reset state: no initial workspace found");import{Box as ol}from"ink";import jr from"react";import Ot from"chalk";import{Box as _r,Text as ks}from"ink";import Ft,{useEffect as Wc,useMemo as jc,useState as Hc}from"react";var Ls=Ot.gray,Kc=Ot.inverse,Vc=Ot.inverse.gray,zc={hint:"",hints:[],overlap:0,remainder:""},Fs=({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=J(t);return{bg:r=>Ot.bgHex(n).black(r),bgCursor:r=>Ot.bgHex(n).inverse.black(r)}}return or(t)},Gc=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Fs({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}},Ds=()=>({value:Z.value,cursorPosition:Z.cursorPosition,commandIsPending:Z.commandIsPending,autoCompletion:Z.commandMeta.autoCompletion??zc,infoMessage:Z.commandMeta.infoMessage,validationStatus:Z.commandMeta.validity,command:Z.commandMeta.command,inputString:Z.commandMeta.inputString,modifier:Z.commandMeta.modifier}),Yc=(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,Os=({width:e})=>{let[t,n]=Hc(Ds());Wc(()=>{let v=()=>{let S=Ds();n(A=>Yc(A,S)?A:S)},E=_o(v);return v(),()=>{E()}},[]);let{value:r,cursorPosition:o,infoMessage:i,commandIsPending:a,autoCompletion:c,command:u,modifier:m}=t,p=jc(()=>{let v=Math.max(0,Math.min(o,r.length)),E=Fs({value:r,command:u}),S=Gc({value:r,command:u,modifier:m}),A=u?or(u):null,I=qc({command:u,modifier:m}),C=(ie,se)=>{let Un=E&&se>=E.start&&se<E.end,$n=S&&se>=S.start&&se<S.end;return Un&&A?A.fg(ie):$n&&I?I.bg(ie):ie},T=(ie,se)=>{let Un=E&&se>=E.start&&se<E.end,$n=S&&se>=S.start&&se<S.end;return Un&&A?A.fgCursor(ie):$n&&I?I.bgCursor(ie):Kc(ie)},B=r.slice(0,v),De=r[v]??" ",Fe=v<r.length?r.slice(v+1):"",ta=Array.from(B).map((ie,se)=>C(ie,se)).join(""),Yr=T(De,v),Xr=Array.from(Fe).map((ie,se)=>C(ie,v+1+se)).join("");if(c.hint){let ie=c.hint[c.overlap]??De;Yr=Vc(ie),Xr=Ls(c.remainder.slice(1)+Fe)}return Ls(":")+ta+Yr+Xr},[r,o,c,u,m]);return Ft.createElement(_r,{flexDirection:"column",justifyContent:"flex-start"},Ft.createElement(_r,{flexDirection:"column",paddingX:1,borderColor:N.secondary,borderStyle:"round",width:e},Ft.createElement(_r,null,Ft.createElement(ks,null,p),i&&Ft.createElement(ks,{wrap:"truncate",color:a?N.red:N.secondary2},` ${i} `))))};import Bs from"chalk";import{Box as Xc,Text as Wr}from"ink";import Rn,{useEffect as Jc,useState as Zc}from"react";var Qc=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Us=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)}},el=({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)}`},tl=(e,t,n)=>{let r=Us(e),o=Us(t);return el({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},nl=(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 tl(i,a,o)},rl=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),$s=({width:e,availableHints:t})=>{let{syncStatus:{status:n,msg:r}}=$(),[o,i]=Zc(0);Jc(()=>{if(n!=="syncing"){i(0);return}let C=setInterval(()=>{i(T=>T+1)},50);return()=>clearInterval(C)},[n]);let a=[],c=0;for(let C of t){let B=(a.length>0?" | ":"").length+C.length;if(c+B>e-4)break;a.push(C),c+=B}let u=n!="synced"?r??a.join(" | "):a.join(" | "),m=Math.max(0,e-2),p=n==="syncing"?nl(Qc,(Math.sin(o*.12)+1)/2):N.secondary,v=Bs.hex(p??"fff"),E=Bs.hex(N.secondary2),S=v(`\u256D${"\u2500".repeat(m)}\u256E`),A=v(`\u2570${"\u2500".repeat(m)}\u256F`),I=`${v("\u2502")}${E(rl(` ${u} `,m))}${v("\u2502")}`;return Rn.createElement(Xc,{flexDirection:"column",width:e},Rn.createElement(Wr,null,S),Rn.createElement(Wr,null,I),Rn.createElement(Wr,null,A))};var Tn=({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 jr.createElement(ol,null,t===g.COMMAND_LINE&&r.syncStatus.status!=="syncing"?jr.createElement(Os,{width:e}):jr.createElement($s,{width:e,mode:t,availableHints:n}))};import{Box as ut,Text as _s}from"ink";import je from"react";var Ws=({width:e})=>{let t=[...x().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"]),je.createElement(ut,{flexDirection:"column",marginTop:3,borderColor:N.secondary,borderStyle:"round",width:e,minHeight:19},je.createElement(ut,{flexDirection:"column",width:e},x().mode===g.HELP?t.map(([n,r],o)=>je.createElement(ut,{paddingLeft:1,key:o,flexDirection:"row"},je.createElement(ut,{key:o,flexDirection:"row",paddingBottom:o?0:1},je.createElement(ut,{width:20,justifyContent:"flex-end"},je.createElement(_s,{color:o?N.accent:N.secondary},n)),je.createElement(ut,{flexGrow:1,width:40,paddingLeft:2},je.createElement(_s,{color:o?N.primary:N.secondary},r))))):null))};import il from"chalk";import{Box as wn,Text as He}from"ink";import pe from"react";var js=({width:e,height:t})=>pe.createElement(wn,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:N.secondary,rowGap:1},pe.createElement(He,{color:N.accent,bold:!0},"Initialize project"),pe.createElement(He,null,`This folder is not an ${il.hex(N.accent)("epiq")} project yet.`),pe.createElement(He,{color:N.primary},"To start tracking issues here, we need to initialize a new"," ",pe.createElement(He,{color:N.primary,backgroundColor:N.secondary}," .epiq/project.json ")," ","file in this repository."),pe.createElement(wn,{marginTop:1,flexDirection:"column"},pe.createElement(wn,null,pe.createElement(He,{color:N.accent}," "),pe.createElement(He,{color:N.primary},"Type "),pe.createElement(He,{backgroundColor:N.secondary}," :init "))),pe.createElement(wn,{marginTop:1},pe.createElement(He,{color:N.secondary2},"(This will create the local epiq project files)")));import{Box as Bt,Text as ye}from"ink";import j from"react";var Mn=({isDone:e,command:t,value:n})=>j.createElement(Bt,null,j.createElement(ye,{color:N.accent,dimColor:e},e?" \u2714 ":" "),j.createElement(ye,{dimColor:e},"Type "),j.createElement(ye,{backgroundColor:N.secondary,dimColor:e}," "+t+" "),n&&j.createElement(j.Fragment,null,j.createElement(ye,{dimColor:e}," "),j.createElement(ye,{color:N.secondary,dimColor:e},"<"+n+">")));function Hr({width:e,height:t,hasUserName:n,hasPreferredEditor:r,userName:o,preferredEditor:i}){let a=n&&r,c=n?r?null:":config:editor":":config:username";return j.createElement(Bt,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:N.secondary,rowGap:1},j.createElement(ye,{color:N.accent,bold:!0},"Welcome! \u{1F539}"),j.createElement(ye,null,"Lets get you started - its a breeze."),j.createElement(ye,{color:N.secondary2},"And remember, you can always get help with"," ",j.createElement(ye,{color:N.accent},":help"),"."),!a&&j.createElement(ye,{color:N.secondary2},c===":config:username"?"First, choose your username.":"Nice. One more step."),j.createElement(Bt,{flexDirection:"column"},n&&j.createElement(Bt,{marginBottom:1},j.createElement(Mn,{isDone:!0,command:":config:username",value:o})),!n&&j.createElement(Mn,{isDone:!1,command:":config:username"}),n&&!r&&j.createElement(Mn,{isDone:!1,command:":config:editor"}),a&&j.createElement(Bt,null,j.createElement(Mn,{isDone:!0,command:":config:editor",value:i}))))}import qs from"chalk";import{Box as kn,Text as Ke}from"ink";import Q from"react";import{Box as Kr,Text as sl}from"ink";import mt from"react";var al=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",Hs=({width:e})=>{let{breadCrumb:t,currentNode:n,selectedIndex:r,viewMode:o}=x(),i=F(n.id)[r],a=Ue(i?.id??n.id,"TICKET"),c=ge(a)?a.value:void 0,u=c?.id?F(c.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"),v=m("Assignees"),E=c?.parentNodeId?!Jn(n.id,c?.parentNodeId)&&o==="dense":!1,S=t.map((I,C)=>{let T=C===t.length-1,B=F(I.id),De=T?B?.[r]?.title:void 0;return`${C?" / ":""}${I.title??""}${De?` \u25B8 ${De}`:""}`}).join(""),A=al(S,e);return mt.createElement(Kr,null,mt.createElement(sl,{color:N.secondary2},A),E?p.map(I=>mt.createElement(Kr,{key:I,paddingLeft:2},mt.createElement(at,{id:I}))):null,E?v.map(I=>mt.createElement(Kr,{key:I,paddingLeft:2},mt.createElement(st,{id:I}))):null)};import{Box as dl,Text as Ks}from"ink";import Pn from"react";var cl=({filters:e})=>Pn.createElement(dl,{columnGap:1},Pn.createElement(Ks,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Pn.createElement(Ks,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Vs=Pn.memo(cl);var zs="0.4.9";function Ln({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o}=$(),{userName:i,preferredEditor:a}=fe(),c=40,u=process.stdout.columns-c-8,m=r.at(-1)?.id,p=tn(m??""),v=ge(p)?Mo(p.value):"INVALID DATE";return Q.createElement(kn,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?Q.createElement(Ke,null," "):Q.createElement(kn,{paddingLeft:1},e.length>0?Q.createElement(Vs,{filters:e}):Q.createElement(Hs,{width:u})),n==="live"?Q.createElement(kn,{columnGap:1,paddingRight:2,"max-width":c,overflow:"hidden",justifyContent:"flex-end"},Q.createElement(Ke,{dimColor:!0,color:N.secondary2},zs+" "),Q.createElement(Gs,{icon:"@",value:i}),Q.createElement(Gs,{icon:"\u276F",value:a})):"",n==="peek"?Q.createElement(kn,{paddingLeft:1},Q.createElement(Ke,{backgroundColor:N.yellow}," Readonly "),Q.createElement(Ke,{color:N.yellow}," "+o.length+" edits ago at "),Q.createElement(Ke,{backgroundColor:N.yellow,color:N.accent}," "+v+" "),Q.createElement(Ke,{color:N.yellow},". Resume with "),Q.createElement(Ke,{backgroundColor:N.yellow}," :peek now ")):"")}function Gs({icon:e,value:t}){return Q.createElement(Ke,null,qs.dim(e)+qs.hex(N.accent)(` ${t??"-"} `))}import{Box as ll,Text as ul}from"ink";import Ut from"react";import{Box as Dn,Text as Vr}from"ink";import Ve from"react";function zr(){let e=$(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,a=t?.id?w(t?.id):[];return Ve.createElement(Dn,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:N.secondary,width:i},Ve.createElement(Dn,{padding:1,paddingTop:0,paddingBottom:0},Ve.createElement(Vr,null,"Select a board:")),Ve.createElement(Dn,{padding:1,flexDirection:"column"},a.map((c,u)=>{let m=e.currentNode.context==="WORKSPACE"&&e.selectedIndex===u,v=w(c.id).flatMap(({id:E})=>F(E)).length;return Ve.createElement(Dn,{key:c.id??u},Ve.createElement(Vr,{color:m?N.accent:N.secondary2},Ve.createElement(re,{isSelected:m})),Ve.createElement(Vr,{color:m?N.accent:N.secondary2},c.title," (",v," issues)",c.readonly?" \u{1F512}":""))})))}var ml=({currentNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:c}=$(),u=n.find(({context:E})=>E==="BOARD"),v=i-1-3;return Ut.createElement(ll,{flexDirection:"row"},e.context==="WORKSPACE"?Ut.createElement(zr,null):u?Ut.createElement(un,{height:v,width:a,swimlanes:(c[u.id]??[]).filter(E=>E!==void 0&&et(E)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Ut.createElement(ul,null))},Ys=Ut.memo(ml);function qr({width:e,height:t}){let n=$(),r=n.filters;if(n.mode===g.HELP)return G.createElement(Je,{flexDirection:"column"},G.createElement(Ws,{width:e}));let{isSetup:o,hasPreferredEditor:i,hasUserName:a,userName:c,preferredEditor:u}=Kt(),m=!o,p=o&&!n.hasProject;if(m)return G.createElement(Je,{flexDirection:"column"},G.createElement(Je,{flexDirection:"column"},G.createElement(Ln,{hideBreadCrumb:!0,filters:r}),G.createElement(Hr,{height:t,width:e,hasUserName:a,hasPreferredEditor:i,userName:c??"",preferredEditor:u??""})),G.createElement(Tn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(p)return G.createElement(Je,{flexDirection:"column"},G.createElement(Je,{flexDirection:"column"},G.createElement(Ln,{hideBreadCrumb:!0,filters:r}),G.createElement(js,{height:t,width:e})),G.createElement(Tn,{width:e,mode:n.mode,availableHints:n.availableHints}));let v=be(x().breadCrumb??[],"BOARD");if(ge(v)){let E=v.value.id,S=w(E).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(Je,{flexDirection:"column"},G.createElement(Je,{flexDirection:"column"},G.createElement(Ln,{filters:r}),G.createElement(Ys,{width:e,height:t,currentNode:n.currentNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:n.viewMode,mode:n.mode})),G.createElement(Tn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import pl from"readline";var Fn,On,he,gl=new Set([y.MoveCursorLeft,y.EraseInputWord,y.MoveCursorLeftOfWord,y.MoveCursorRight,y.MoveCursorRightOfWord,y.NavToPreviousContainer,y.NavToNextContainer,y.NavPreviousItem,y.NavNextItem,y.SetViewDense,y.SetViewWide,y.Confirm,y.Exit,y.InitCommandLine,y.ExitCommandLine,y.CaptureInput,y.EraseInput,y.EraseInputWord,y.HideHelp,y.ViewHelp,y.SetViewDense,y.SetViewWide,y.GetLastCommandFromHistory,y.GetNextCommandFromHistory,y.AutoCompleteCommand]),Xs=async e=>{if(e.ctrl&&e.name==="c")return L.exit();let{actionIndex:t,mode:n,readOnly:r}=x(),o=Go(e,n);if(!o||r&&!gl.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(a){logger.error(a)}},fl=()=>async function(t,n){n.name!=="escape"&&(he&&(clearTimeout(he),he=void 0),await Xs(n))},vl=()=>async function(t){if(t.length===1&&t[0]===27){he&&clearTimeout(he),he=setTimeout(()=>{Xs({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),he=void 0},25);return}he&&(clearTimeout(he),he=void 0)};function Js(){Fn&&process.stdin.removeListener("keypress",Fn),On&&process.stdin.removeListener("data",On),Fn=fl(),On=vl(),pl.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",On),process.stdin.on("keypress",Fn)}yl(`${Gr.bold("Epiq CLI")}
56
+ ${c}
57
+ `,zn.writeFileSync(t,r,"utf8"),ce.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)};var Wc=async e=>{let t=await D({cwd:e,args:["status","--porcelain"]});return d(t)?t:l("Checked git diff",t.value.stdout.trim().length>0)},_=(e,t)=>s(`[${e}] ${t}`),Rs=async()=>{let e=mo(),t=await Mr(process.cwd());if(d(t))return _(1,t.message);let r=t.value,n=await Ft(r);if(d(n))return _(2,n.message);if(n.value)return _(2,"Cannot initialize Epiq while a git operation is in progress");let o=await Wc(r);if(d(o))return _(2.5,o.message);if(o.value)return _(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(nn(r))return _(4,"Epiq project already initialized");let i=rt();if(!i.isSetup||!i.userName)return _(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let a=le(),c=a.userName,u=a.userId;if(!u||!c)return _(5,"Missing Epiq user id");let m=e.stateBranch,p=await Sr({repoRoot:r,branch:m});if(d(p))return _(6,p.message);let v=await Pr({repoRoot:r,stateBranchName:e.stateBranch});if(d(v))return _(6,v.message);let y=Tr();if(d(y))return _(7,y.message);let I=Ss.join(wr(),e.projectId),R=await $n({repoRoot:r,stateBranchRoot:I,stateBranchName:e.stateBranch});if(d(R))return _(8,R.message);let S=Ss.join(I,".epiq");_c.mkdirSync(S,{recursive:!0});let C=hs({userId:u,userName:c});if(d(C))return _(9,C.message);for(let tn of C.value){let co=ar({event:tn,rootDir:I});if(d(co))return _(9,co.message)}let w=await kr({stateBranchRoot:I,eventFileName:At({userId:u,userName:c})});if(d(w))return _(10,w.message);let B=await mt({cwd:I,message:"[epiq:init]"});if(d(B))return _(10,B.message);let se=await bs(r);if(d(se))return _(12,se.message);let J=go({repoRoot:r,fileContents:e});if(d(J))return _(13,J.message);let Gt=await j.stage({cwd:r,pathspec:[".epiq/project.json",".gitignore"]});if(d(Gt))return _(14,Gt.message);let xt=await j.commit({cwd:r,message:"[epiq:init-project]"});if(d(xt))return _(14,xt.message);let ht=_t({repoRoot:r,stateBranchRoot:I});if(d(ht))return _(15,ht.message);let q="Project initialized!",Z=await $t({repoRoot:r,stateBranchRoot:I});d(Z)&&(q+=` Warn: [init:16] ${Z.message}`);let et=await j.push({cwd:r});d(et)&&(q+=` Warn: [init:17] ${et.message}`);let ao=dr(C.value).filter(d);if(ao.length>0)return _(18,ao.map(tn=>tn.message).join(`
58
+ `));let{rootNodeId:ua,nodes:ma}=x();return L.navigate({currentNode:ma[ua],selectedIndex:0}),A({hasProject:!0,mode:g.DEFAULT}),l(q,null)};var As=e=>Object.values(x().tags).find(t=>t.name===e),ws=e=>Object.values(x().contributors).find(t=>t.name===e),Ts=[{systemOnly:!0,intent:M.Move,mode:g.COMMAND_LINE,action:()=>{let e=ee();if(d(e))return s("Unable to resolve user ID");let{modifier:t}=ae().commandMeta,r=()=>{let c=We();if(!c)return s("No pending move state");let u=c.payload.id;if(!x().nodes[u])return s("Moved node not found");let p=c.payload.parent,v=x().nodes[p];if(!v)return s("Move parent not found");let y=T(p).findIndex(I=>I.id===u);return y===-1?s("Moved node not found among rendered children"):(L.navigate({currentNode:v,selectedIndex:y}),l("Synchronized navigation to moved node",null))},n=c=>{if(d(c))return s(c.message);let u=r();return d(u)?s(u.message):l("Updated move preview",null)},{currentNode:o,selectedIndex:i}=x(),a=T(o.id)[i];if(!a)return A({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 c=F(a.parentNodeId),u=c.findIndex(({id:R})=>R===a.id);if(u===-1)return s("Target not found among siblings");let m=c[u-1],p=c[u+1],v=p!=null?{at:"before",sibling:p.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"},y=ot(a.parentNodeId,a.id,v,e.value);if(d(y))return y;Wt({id:V(),action:"move.node",payload:{id:a.id,parent:a.parentNodeId,rank:y.value},...e.value}),A({mode:g.MOVE});let I=r();return d(I)?s(I.message):l("Move initialized",null)}if(t==="next")return A({mode:g.MOVE}),n(Kn(1));if(t==="previous")return A({mode:g.MOVE}),n(Kn(-1));if(t==="to-next")return A({mode:g.MOVE}),n(Hn(1));if(t==="to-previous")return A({mode:g.MOVE}),n(Hn(-1));if(t==="confirm"){A({mode:g.DEFAULT});let c=We();if(!c)return s("No pending move to confirm");let u=K(c);if(d(u))return u;let m=r();return d(m)?s(m.message):(Wt(null),l("Moved item",null))}return t==="cancel"?(Wt(null),A({mode:g.DEFAULT}),l("Cancelling move",null)):s("Invalid move modifier")}},{intent:M.Delete,mode:g.COMMAND_LINE,action:()=>{let e=ee();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:r}=x(),n=T(t.id)[r];return n?K({id:V(),action:"delete.node",payload:{id:n.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.Edit,mode:g.COMMAND_LINE,action:Is,onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.Filter,mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ae().commandMeta,r=/(!=|=)/,[n,o]=e.split(r);if(!n||!(c=>Y(f.FILTER).map(u=>u.split(r)[0]).includes(c))(n))return s("Invalid filter modifier");let a={target:n,operator:"=",value:t.trim()};return ue(c=>({...c,filters:e==="clear"?[]:[...c.filters,a],mode:g.DEFAULT})),l("Viewing help",null)}},{intent:M.ViewHelp,mode:g.COMMAND_LINE,action:()=>(A({mode:g.HELP}),l("Viewing help",null))},{intent:M.CloseIssue,mode:g.COMMAND_LINE,action:()=>{let e=ee();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:r}=x(),n=T(t.id)[r];if(!n)return s("Unable to close issue, no target found");if(!ge(n))return s("Cannot close in this context");let o=x().nodes[Te];if(!o)return s("Unable to locate closed swimlane");if(n.parentNodeId===o.id)return s("Issue is already closed");let i=ot(o.id,n.id,{at:"end"},e.value);if(d(i))return i;let a=K({id:V(),action:"close.issue",payload:{id:n.id,parent:o.id,rank:i.value},...e.value});return d(a)?a:l("Issue closed",null)},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.ReopenIssue,mode:g.COMMAND_LINE,action:()=>{let e=ee();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:r}=x(),n=T(t.id)[r];if(!n)return s("Unable to reopen issue, no target found");let o=n.context==="TICKET"?l("Resolved ticket",n):Ue(n.id,"TICKET");if(d(o))return s("Cannot reopen in this context");let i=o.value,a=x().nodes[Te];if(!a)return s("Unable to locate closed swimlane");if(i.parentNodeId!==a.id)return s("Issue is not closed");if(!ge(i))return s("Target node is not issue");let c=ys(i);if(!c)return s("Unable to resolve previous parent from issue history");if(c===a.id)return s("Previous parent resolves to closed swimlane");let u=x().nodes[c];if(!u)return s("Previous parent no longer exists");let m=ot(u.id,i.id,{at:"end"},e.value);if(d(m))return m;let p=K({id:V(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:m.value},...e.value});return d(p)?p:l("Issue reopened",null)},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.SetUserName,mode:g.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:r}=le(),n=vr()?.trim();if(!n)return s("No username provided");let o=n??r,i=e??V();if(!o||!i)return s("Unable to resolve user name or id");let a=Fr({userName:o,userId:i,preferredEditor:t??""});return d(a)?a:(tt({userName:o,userId:i}),A({mode:g.DEFAULT}),l(`Username set to "${n}"`,null))}},{intent:M.Init,mode:g.COMMAND_LINE,action:Rs},{intent:M.SetEditor,mode:g.COMMAND_LINE,action:()=>{let e=vr()?.trim();if(!e)return s("No editor provided");let t=Fr({preferredEditor:e});return d(t)?t:(tt({preferredEditor:e}),A({mode:g.DEFAULT}),l(`Editor configuration set to "${e}"`,null))}},{intent:M.SetAutoSync,mode:g.COMMAND_LINE,action:()=>{let e=ae().commandMeta.modifier;if(e!=="true"&&e!=="false")return s("Invalid response");let t=e.toLowerCase()==="true",r=Fr({autoSync:t});return d(r)?r:(tt({autoSync:t}),A({mode:g.DEFAULT}),l(`Auto synchronization set to "${t}"`,null))}},{intent:M.NewItem,mode:g.COMMAND_LINE,action:(e,t)=>{let r=ee();if(d(r))return s("Unable to resolve user ID");if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:n,currentNode:o,selectedIndex:i}=x(),a=c=>{let u=K(c);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?(L.navigate({currentNode:p,selectedIndex:b.getSiblings(m.parentNodeId).findIndex(({id:v})=>v===m.id)}),u):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:c}=x(),u=b.getNode(c);if(!u)return s("Workspace not found");let m=it(u.id,r.value);return d(m)?m:a({id:V(),action:"add.board",payload:{id:V(),name:t.inputString,parent:u.id,rank:m.value},...r.value})}if(t.modifier==="swimlane"){let c=Ne(n,"BOARD");if(d(c))return s("Unable to add swimlane in this context");let u=it(c.value.id,r.value);return d(u)?u:a({id:V(),action:"add.swimlane",payload:{id:V(),name:t.inputString,parent:c.value.id,rank:u.value},...r.value})}if(t.modifier==="issue"){let c=T(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&c?.context==="SWIMLANE"?c:(()=>{let C=Ne(n,"SWIMLANE");return d(C)?null:C.value})();if(!u)return s("Unable to add issue in this context");let m=it(u.id,r.value);if(d(m))return m;let p=xs({name:t.inputString,parent:u.id,rank:m.value,user:r.value});if(d(p))return p;let v=p.value,y=dr(v);if(y.some(C=>d(C)))return s("Issue create failed: "+y.filter(d).map(C=>C.message).filter(Boolean).join(", "));let I=y[0];if(!I||d(I))return s("Issue creation failed");let S=v.find(C=>C.action==="add.issue")?.payload.id;return S?(L.navigate({currentNode:u,selectedIndex:b.getSiblings(u.id).findIndex(({id:C})=>C===S)}),l("Issue created",null)):s("Unable to determine ticket id")}return l("Success",null)},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.SetView,mode:g.COMMAND_LINE,action:()=>{let{commandMeta:e}=ae();return e.validity===Me.Invalid?s("Invalid command "+Se):(ue(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),l("View set",null))},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.Rename,mode:g.COMMAND_LINE,action:()=>{let e=ee();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:r}=x(),n=T(t.id)[r];if(!n)return s("Missing node");if(n.readonly)return s("Cannot rename readonly node");let o=vr();return o?K({id:V(),action:"edit.title",payload:{id:n.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.UntagTicket,mode:g.COMMAND_LINE,action:()=>{let e=ee();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:r}=ae().commandMeta,n=(t||r).trim();if(!n)return s("Provide a tag");let o=As(n);if(!o)return s(`Tag "${n}" does not exist`);let{selectedNode:i}=x();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 c=a.value,u=b.getFieldByTitle(c.id,"Tags");if(!u)return s("Unable to locate tags field");let m=T(u.id).find(p=>p.props?.value===o.id);return m?K({id:V(),action:"untag.issue",payload:{id:m.id,target:c.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.TagTicket,mode:g.COMMAND_LINE,action:()=>{let e=ee();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:r}=ae().commandMeta,n=(t||r).trim();if(!n)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=x(),a=T(i.id)[o];if(!a)return s("Invalid tag target");let c=Ue(a.id,"TICKET");if(d(c))return s("Unable to tag issue in this context");let u=c.value,m=As(n),p;if(m)p=m.id;else{let R=V(),S=K({id:V(),action:"create.tag",payload:{id:R,name:n},userId:e.value.userId,userName:e.value.userName});if(d(S))return S;p=S.value.result.id}let v=b.getFieldByTitle(u.id,"Tags");if(!v)return s("Unable to locate tags field");if(T(v.id).some(R=>R.props?.value===p))return s("Already tagged with that tag");let I=it(v.id,e.value);return d(I)?I:K({id:V(),action:"tag.issue",payload:{id:V(),target:u.id,tagId:p,rank:I.value},...e.value})},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.AssignUserToTicket,mode:g.COMMAND_LINE,action:()=>{let e=ee();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:r}=ae().commandMeta,n=(t||r).trim();if(!n)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=x(),a=T(i.id)[o];if(!a)return s("Invalid assign target");let c=Ue(a.id,"TICKET");if(d(c))return s("Unable to assign issue in this context");let u=c.value,m=ws(n),p;if(m)p=m.id;else{let R=V(),S=K({id:V(),action:"create.contributor",payload:{id:R,name:n},userId:e.value.userId,userName:e.value.userName});if(d(S))return S;p=S.value.result.id}let v=b.getFieldByTitle(u.id,"Assignees");if(!v)return s("Unable to locate assignees field");if(T(v.id).some(R=>R.props?.value===p))return s("Assignee already assigned");let I=it(v.id,e.value);return d(I)?I:K({id:V(),action:"assign.issue",payload:{id:V(),target:u.id,contributor:p,rank:I.value},...e.value})},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.UnassignUserFromTicket,mode:g.COMMAND_LINE,action:()=>{let e=ee();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:r}=ae().commandMeta,n=(t||r).trim();if(!n)return s("Provide an assignee to remove");let o=ws(n);if(!o)return s(`Assignee "${n}" does not exist`);let{selectedNode:i}=x();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 c=a.value,u=b.getFieldByTitle(c.id,"Assignees");if(!u)return s("Unable to locate assignees field");let m=T(u.id).find(p=>p.props?.value===o.id);return m?K({id:V(),action:"unassign.issue",payload:{id:m.id,target:c.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${n}"`)},onSuccess:()=>A({mode:g.DEFAULT})},{intent:M.Sync,mode:g.COMMAND_LINE,action:async()=>{let e=rs();O(()=>""),A({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:r}=le();if(!t)return s("Unable to resolve userId");if(!r)return s("Unable to resolve userName");let n=ee();if(d(n)||!n.value)return s("Unable to resolve event log path");let o=At(n.value),i=await es({ownEventFileName:o});if(d(i))return A({syncStatus:{msg:i.message,status:"outOfSync"}}),s(`Unable to sync state. ${i.message}`);let a=Ee(process.cwd());if(d(a))return a;let c=St(a.value);if(d(c))return s(`Unable to load events. ${c.message}`);let u=Ur({eventLog:c.value,hasProject:!0});if(d(u))return s(`Unable to boot synced state. ${u.message}`);A({hasProject:!0,syncStatus:{msg:"Synced",status:"synced"},mode:g.DEFAULT});let m=ns(e);return d(m)?m:l("Synced",!0)}},{intent:M.Peek,mode:g.COMMAND_LINE,action:async()=>{let e=Ne(x().breadCrumb,"BOARD");if(d(e))return e;let t=Be(process.cwd());if(d(t))throw new Error(t.message);let r=St(t.value);if(d(r))return s(r.message);let n=r.value,{modifier:o}=ae().commandMeta,i;if(o==="now"){let y=Gn();if(d(y))return y;let I=It(n);return I.some(d)?s(I.map(R=>R.message).join(", ")):(A({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),l("Peeking now",!0))}if(o==="prev"){let y=x().eventLog.at(-2),I=vn(y);if(I===null)return s("No previous event to peek");i=I}else if(o==="next"){let y=x().unappliedEvents.at(0),I=vn(y);if(I===null)return s("No next event to peek");i=I}else{let y=ur(o);if(!y)return s("Invalid peek date");i=y.getTime()}let a=e.value.id,{appliedEvents:c,unappliedEvents:u}=To(n,i),m=Gn();if(d(m))return m;let p=It(c);if(p.some(d))return s(p.map(y=>y.message).join(", "));let v=x().nodes[a];return v?(L.navigate({currentNode:v,selectedIndex:0}),A({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 bi();return d(e)?e:(A({mode:g.DEFAULT}),l("Export successful",!0))}},{intent:M.Exit,mode:g.COMMAND_LINE,action:async()=>(L.exit(),l("Exit successful",!0))}];var jc=new Set(["peek","filter","view-help"]),ve=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:r,modifier:n,inputString:o}}=ae();if(!t)return s("No command to confirm");if(!e&&r===Me.Invalid)return s("Invalid command");let i=ai(t);if(ti(),x().readOnly&&!jc.has(i))return Pt({status:Se.Fail,message:"Command not available in readonly state",value:null});let a=Ts.filter(u=>e||u.systemOnly!==!0).find(u=>u.intent===i);if(!a)return Pt({status:Se.Fail,message:"Command not found",value:null});let c=await a.action(a,{command:t,inputString:o,modifier:n});return d(c)?Pt(c):(ri({addToHistory:!e}),a.onSuccess?.(),Pt(c))};var $r=[{intent:h.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(A({mode:g.COMMAND_LINE}),O(()=>"move cancel"),ve({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:g.DEFAULT,description:"[m] move init/confirm",action:()=>(A({mode:g.COMMAND_LINE}),O(()=>"move start"),ve({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:g.MOVE,action:()=>(A({mode:g.COMMAND_LINE}),O(()=>"move confirm"),ve({isForceExecutedBySystem:!0}))}],_r=[{intent:h.MovePreviousItem,mode:g.MOVE,action:()=>We()?(A({mode:g.COMMAND_LINE}),O(()=>"move previous"),ve({isForceExecutedBySystem:!0})):s("No pending move")},{intent:h.MoveNextItem,mode:g.MOVE,action:()=>We()?(A({mode:g.COMMAND_LINE}),O(()=>"move next"),ve({isForceExecutedBySystem:!0})):s("No pending move")}],Ms=[{intent:h.MoveToNextContainer,mode:g.MOVE,action:()=>We()?(A({mode:g.COMMAND_LINE}),O(()=>"move to-next"),ve({isForceExecutedBySystem:!0})):s("No pending move")},{intent:h.MoveToPreviousContainer,mode:g.MOVE,action:()=>We()?(A({mode:g.COMMAND_LINE}),O(()=>"move to-previous"),ve({isForceExecutedBySystem:!0})):s("No pending move")}];var Ps={[P.WORKSPACE]:[...$r,..._r],[P.BOARD]:[...$r,..._r],[P.SWIMLANE]:[...$r,..._r,...Ms],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var ks=[{intent:h.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(A({mode:g.COMMAND_LINE}),O(()=>`${f.NEW} `),l("Adding new item",null))},{intent:h.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(A({mode:g.COMMAND_LINE}),O(()=>`${f.DELETE} `),l("Deleting item",null))},{intent:h.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(A({mode:g.COMMAND_LINE}),O(()=>""),l("Entering command line mode",null))},{intent:h.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,currentNode:t}=x();if(!F(e?.id??"")?.length){if(e?.title===G.DESCRIPTION)return O(()=>"edit "),A({mode:g.COMMAND_LINE}),l("Propose command",!0);if(e?.title===G.ASSIGNEES)return O(()=>"assign "),A({mode:g.COMMAND_LINE}),l("Propose command",!0);if(e?.title===G.TAGS)return O(()=>"tag "),A({mode:g.COMMAND_LINE}),l("Propose command",!0);if(t.title===G.DESCRIPTION&&e?.context==="TEXT")return O(()=>"edit "),A({mode:g.COMMAND_LINE}),l("Propose command",!0)}return L.enterChildNode(),l("Entering context",null)}},{intent:h.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(L.enterParentNode(),l("Exiting context",null))},{intent:h.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(L.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:g.DEFAULT,action:()=>(L.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(L.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:g.DEFAULT,action:()=>(L.navigateToNextContainer(),l("Navigating to next container",null))},{intent:h.Edit,mode:g.DEFAULT,action:()=>(A({mode:g.COMMAND_LINE}),O(()=>"edit"),ve(),l("Fired command",!0))},{intent:h.SetViewDense,mode:g.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(A({viewMode:"dense"}),l("View set",null))},{intent:h.SetViewWide,mode:g.DEFAULT,action:()=>(A({viewMode:"wide"}),l("View set",null))}];var Hc=500,Kc=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Ls=e=>{let t=Kc(e);t&&O(r=>(r+t).slice(0,Hc))};var Ds=[{intent:h.ViewHelp,mode:g.DEFAULT,action:()=>(A({mode:g.HELP}),l("Viewing help",null))},{intent:h.Exit,mode:g.HELP,action:()=>(A({mode:g.DEFAULT}),l("Exiting help",null))},{intent:h.Confirm,mode:g.COMMAND_LINE,action:()=>(ve(),l("Executing command",null))},{intent:h.MoveCursorLeft,mode:g.COMMAND_LINE,action:()=>(bn(-1),l("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:g.COMMAND_LINE,action:()=>(bn(1),l("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:g.COMMAND_LINE,action:()=>(Sn("left"),l("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:g.COMMAND_LINE,action:()=>(Sn("right"),l("Moving cursor right of word",null))},{intent:h.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(A({mode:g.DEFAULT}),l("Exiting command line",null))},{intent:h.AutoCompleteCommand,mode:g.COMMAND_LINE,action:()=>(O((e,{remainder:t})=>t?e+t:e),l("Auto-completing command",null))},{intent:h.CaptureInput,mode:g.COMMAND_LINE,action:(e,{sequence:t})=>(Ls(t??""),l("Capturing input",null))},{intent:h.EraseInput,mode:g.COMMAND_LINE,action:()=>(Qo(),l("Erasing input",null))},{intent:h.EraseInputWord,mode:g.COMMAND_LINE,action:()=>(ei(),l("Erasing input word",null))},{intent:h.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(ni(),l("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(oi(),l("Getting next command from history",null))}];import Vc from"chalk";var Wr=": for command line",Fs="q to exit",Bs=`${Vc.hex(N.accent)("m")} to confirm`,Yn={[P.WORKSPACE]:[Wr],[P.BOARD]:[Wr],[P.BOARD+g.COMMAND_LINE]:[Wr],[P.SWIMLANE]:[Wr],[P.TICKET+g.HELP]:[Fs],[P.SWIMLANE+g.HELP]:[Fs],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+g.MOVE]:[Bs],[P.TICKET+g.MOVE]:[Bs]};var jr=e=>e.trim().toLocaleLowerCase(),qc=(e,t)=>{let r=b.getFieldByTitle(e,t);if(!r)return"";let n=r.props?.value;return typeof n=="string"?n:""},zc=e=>{let{tags:t}=x(),r=b.getFieldByTitle(e,"Tags");return r?F(r.id).map(n=>{let o=n.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(n=>!!n):[]},Gc=e=>{let{contributors:t}=x(),r=b.getFieldByTitle(e,"Assignees");return r?F(r.id).map(n=>{let o=n.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(n=>!!n):[]},Os=(e,t)=>{let r=t.value;if(!r)return!0;switch(t.target){case"title":return jr(e.title??"").includes(r);case"description":return jr(qc(e.id,G.DESCRIPTION)).includes(r);case"tag":return zc(e.id).map(jr).some(c=>c.includes(r));case"assignee":return Gc(e.id).map(jr).some(c=>c.includes(r));default:return!0}};function Us(e,t,r){let n=t[e];if(!n)return s("buildBreadCrumb(): current node not found");let o=[],i=n;for(;i&&(o.push(i),!(i.id===r||!i.parentNodeId));)i=t[i.parentNodeId];let a=o[o.length-1];return!a||a.id!==r?s("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var $s=e=>{let t={};for(let r of e)r.intent&&(t[r.mode]||(t[r.mode]={}),t[r.mode][r.intent]=r);return t};var Hr,Xn,Jn=new Set,_s=()=>{for(let e of Jn)e()},Xc=e=>(Jn.add(e),()=>Jn.delete(e));function Ws(e){let{currentNodeId:t,mode:r,rootNodeId:n,nodes:o,filters:i}=e;if(!t)return s("derive(): currentNodeId is missing");if(!n)return s("derive(): rootNode is missing");if(!o[n])return s("derive(): unable to find root node");let c=o[t];if(!c)return s("Unable to derive state, currentNode not found");let u=Us(t,o,n);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,v=Yn[p+r]??Yn[p]??[],y=[...ks,...Ps[p]??[],...Ds],I=$s(y),R=Jc(o,i),S=R[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,currentNode:c,breadCrumb:m,availableHints:v,availableActions:y,actionIndex:I,selectedNode:S,renderedChildrenIndex:R})}var x=()=>(Hr||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),Hr);function bt(e){Xn=e;let t=Ee(process.cwd()),r=!1;if(!d(t)){let i=Oe(t.value);if(d(i))return s(i.message);r=!0}let n={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},o=Ws(n);return d(o)?o:(Hr=o.value,_s(),l("State initialized",null))}function ue(e){let t=x(),r=e(t),n=Ws(r);return d(n)?s(n.message??"Unable to update state"):(Hr=n.value,_s(),l("State updated",null))}var A=e=>ue(t=>({...t,...e}));var $=()=>Yc(Xc,x,x),Jc=(e,t)=>{let r={};for(let n of Object.values(e))ge(n)&&t.length>0&&!t.every(o=>Os(n,o))||!n.parentNodeId||n.isDeleted||((!n.parentNodeId||!r[n.parentNodeId])&&(r[n.parentNodeId]=[]),r[n.parentNodeId].push(n));for(let n of Object.keys(r))r[n].sort((o,i)=>{let a=e[o.id],c=e[i.id];return!a||!c?0:a.rank.localeCompare(c.rank)});return r},T=e=>x()?.renderedChildrenIndex[e]??[],Gn=()=>Xn?bt(Xn):s("Cannot reset state: no initial workspace found");import{Box as fl}from"ink";import eo from"react";import Vt from"chalk";import{Box as Zn,Text as js}from"ink";import Kt,{useEffect as Zc,useMemo as Qc,useState as el}from"react";var Hs=Vt.gray,tl=Vt.inverse,rl=Vt.inverse.gray,nl={hint:"",hints:[],overlap:0,remainder:""},Vs=({value:e,command:t})=>{if(!t)return null;let r=e.trimStart(),o=e.length-r.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},ol=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let r=re(t);return{bg:n=>Vt.bgHex(r).black(n),bgCursor:n=>Vt.bgHex(r).inverse.black(n)}}return yn(t)},il=({value:e,command:t,modifier:r})=>{if(!t||!r)return null;let n=Vs({value:e,command:t});if(!n)return null;let i=e.slice(n.end).match(/^\s*/)?.[0].length??0,a=n.end+i;return e.slice(a,a+r.length)!==r?null:{start:a,end:a+r.length}},Ks=()=>({value:ne.value,cursorPosition:ne.cursorPosition,commandIsPending:ne.commandIsPending,autoCompletion:ne.commandMeta.autoCompletion??nl,infoMessage:ne.commandMeta.infoMessage,validationStatus:ne.commandMeta.validity,command:ne.commandMeta.command,inputString:ne.commandMeta.inputString,modifier:ne.commandMeta.modifier}),sl=(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,qs=({width:e})=>{let[t,r]=el(Ks());Zc(()=>{let v=()=>{let I=Ks();r(R=>sl(R,I)?R:I)},y=Zo(v);return v(),()=>{y()}},[]);let{value:n,cursorPosition:o,infoMessage:i,commandIsPending:a,autoCompletion:c,command:u,modifier:m}=t,p=Qc(()=>{let v=Math.max(0,Math.min(o,n.length)),y=Vs({value:n,command:u}),I=il({value:n,command:u,modifier:m}),R=u?yn(u):null,S=ol({command:u,modifier:m}),C=(q,Z)=>{let et=y&&Z>=y.start&&Z<y.end,Yt=I&&Z>=I.start&&Z<I.end;return et&&R?R.fg(q):Yt&&S?S.bg(q):q},w=(q,Z)=>{let et=y&&Z>=y.start&&Z<y.end,Yt=I&&Z>=I.start&&Z<I.end;return et&&R?R.fgCursor(q):Yt&&S?S.bgCursor(q):tl(q)},B=n.slice(0,v),se=n[v]??" ",J=v<n.length?n.slice(v+1):"",Gt=Array.from(B).map((q,Z)=>C(q,Z)).join(""),xt=w(se,v),ht=Array.from(J).map((q,Z)=>C(q,v+1+Z)).join("");if(c.hint){let q=c.hint[c.overlap]??se;xt=rl(q),ht=Hs(c.remainder.slice(1)+J)}return Hs(":")+Gt+xt+ht},[n,o,c,u,m]);return Kt.createElement(Zn,{flexDirection:"column",justifyContent:"flex-start"},Kt.createElement(Zn,{flexDirection:"column",paddingX:1,borderColor:N.secondary,borderStyle:"round",width:e},Kt.createElement(Zn,null,Kt.createElement(js,null,p),i&&Kt.createElement(js,{wrap:"truncate",color:a?N.red:N.secondary2},` ${i} `))))};import zs from"chalk";import{Box as al,Text as Qn}from"ink";import Kr,{useEffect as dl,useState as cl}from"react";var ll=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Gs=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)}},ul=({r:e,g:t,b:r})=>{let n=o=>Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0");return`#${n(e)}${n(t)}${n(r)}`},ml=(e,t,r)=>{let n=Gs(e),o=Gs(t);return ul({r:n.r+(o.r-n.r)*r,g:n.g+(o.g-n.g)*r,b:n.b+(o.b-n.b)*r})},pl=(e,t)=>{if(e.length===1)return e[0];let r=t*(e.length-1),n=Math.floor(r),o=r-n,i=e[n],a=e[Math.min(n+1,e.length-1)];return ml(i,a,o)},gl=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),Ys=({width:e,availableHints:t})=>{let{syncStatus:{status:r,msg:n}}=$(),[o,i]=cl(0);dl(()=>{if(r!=="syncing"){i(0);return}let C=setInterval(()=>{i(w=>w+1)},50);return()=>clearInterval(C)},[r]);let a=[],c=0;for(let C of t){let B=(a.length>0?" | ":"").length+C.length;if(c+B>e-4)break;a.push(C),c+=B}let u=r!="synced"?n??a.join(" | "):a.join(" | "),m=Math.max(0,e-2),p=r==="syncing"?pl(ll,(Math.sin(o*.12)+1)/2):N.secondary,v=zs.hex(p??"fff"),y=zs.hex(N.secondary2),I=v(`\u256D${"\u2500".repeat(m)}\u256E`),R=v(`\u2570${"\u2500".repeat(m)}\u256F`),S=`${v("\u2502")}${y(gl(` ${u} `,m))}${v("\u2502")}`;return Kr.createElement(al,{flexDirection:"column",width:e},Kr.createElement(Qn,null,I),Kr.createElement(Qn,null,S),Kr.createElement(Qn,null,R))};var Vr=({width:e,mode:t,availableHints:r})=>{let n=$(),o=[],i=0;for(let a of r){let u=(o.length>0?" | ":"").length+a.length;if(i+u>e+2)break;o.push(a),i+=u}return eo.createElement(fl,null,t===g.COMMAND_LINE&&n.syncStatus.status!=="syncing"?eo.createElement(qs,{width:e}):eo.createElement(Ys,{width:e,mode:t,availableHints:r}))};import{Box as ft,Text as Xs}from"ink";import je from"react";var Js=({width:e})=>{let t=[...x().availableActions].map(r=>r.description).filter(r=>r!==void 0).map(r=>{let[n,o]=r.split("]"),i=n?.replace("[",""),a=o?.trim();return[i,a]}).filter(r=>r[0]!==void 0&&r[1]!==void 0).sort(([r],[n])=>r.length===1&&n.length!==1?-1:r.length!==1&&n.length===1?1:r.localeCompare(n,void 0,{sensitivity:"base"}));return t.unshift(["Key(s)","Action"]),je.createElement(ft,{flexDirection:"column",marginTop:3,borderColor:N.secondary,borderStyle:"round",width:e,minHeight:19},je.createElement(ft,{flexDirection:"column",width:e},x().mode===g.HELP?t.map(([r,n],o)=>je.createElement(ft,{paddingLeft:1,key:o,flexDirection:"row"},je.createElement(ft,{key:o,flexDirection:"row",paddingBottom:o?0:1},je.createElement(ft,{width:20,justifyContent:"flex-end"},je.createElement(Xs,{color:o?N.accent:N.secondary},r)),je.createElement(ft,{flexGrow:1,width:40,paddingLeft:2},je.createElement(Xs,{color:o?N.primary:N.secondary},n))))):null))};import vl from"chalk";import{Box as qr,Text as He}from"ink";import xe from"react";var Zs=({width:e,height:t})=>xe.createElement(qr,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:N.secondary,rowGap:1},xe.createElement(He,{color:N.accent,bold:!0},"Initialize project"),xe.createElement(He,null,`This folder is not an ${vl.hex(N.accent)("epiq")} project yet.`),xe.createElement(He,{color:N.primary},"To start tracking issues here, we need to initialize a new"," ",xe.createElement(He,{color:N.primary,backgroundColor:N.secondary}," .epiq/project.json ")," ","file in this repository."),xe.createElement(qr,{marginTop:1,flexDirection:"column"},xe.createElement(qr,null,xe.createElement(He,{color:N.accent}," "),xe.createElement(He,{color:N.primary},"Type "),xe.createElement(He,{backgroundColor:N.secondary}," :init "))),xe.createElement(qr,{marginTop:1},xe.createElement(He,{color:N.secondary2},"(This will create the local epiq project files)")));import{Box as qt,Text as Ie}from"ink";import H from"react";var zr=({isDone:e,command:t,value:r})=>H.createElement(qt,null,H.createElement(Ie,{color:N.accent,dimColor:e},e?" \u2714 ":" "),H.createElement(Ie,{dimColor:e},"Type "),H.createElement(Ie,{backgroundColor:N.secondary,dimColor:e}," "+t+" "),r&&H.createElement(H.Fragment,null,H.createElement(Ie,{dimColor:e}," "),H.createElement(Ie,{color:N.secondary,dimColor:e},"<"+r+">")));function to({width:e,height:t,hasUserName:r,hasPreferredEditor:n,userName:o,preferredEditor:i}){let a=r&&n,c=r?n?null:":config:editor":":config:username";return H.createElement(qt,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:N.secondary,rowGap:1},H.createElement(Ie,{color:N.accent,bold:!0},"Welcome! \u{1F539}"),H.createElement(Ie,null,"Lets get you started - its a breeze."),H.createElement(Ie,{color:N.secondary2},"And remember, you can always get help with"," ",H.createElement(Ie,{color:N.accent},":help"),"."),!a&&H.createElement(Ie,{color:N.secondary2},c===":config:username"?"First, choose your username.":"Nice. One more step."),H.createElement(qt,{flexDirection:"column"},r&&H.createElement(qt,{marginBottom:1},H.createElement(zr,{isDone:!0,command:":config:username",value:o})),!r&&H.createElement(zr,{isDone:!1,command:":config:username"}),r&&!n&&H.createElement(zr,{isDone:!1,command:":config:editor"}),a&&H.createElement(qt,null,H.createElement(zr,{isDone:!0,command:":config:editor",value:i}))))}import na from"chalk";import{Box as Yr,Text as Ke}from"ink";import oe from"react";import{Box as ro,Text as xl}from"ink";import vt from"react";var hl=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",Qs=({width:e})=>{let{breadCrumb:t,currentNode:r,selectedIndex:n,viewMode:o}=x(),i=F(r.id)[n],a=Ue(i?.id??r.id,"TICKET"),c=he(a)?a.value:void 0,u=c?.id?F(c.id):[],m=S=>{let C=u.find(w=>w.title===S);return C?F(C.id).map(w=>typeof w.props?.value=="string"?w.props.value:"").filter(w=>!!w):[]},p=m("Tags"),v=m("Assignees"),y=c?.parentNodeId?!pn(r.id,c?.parentNodeId)&&o==="dense":!1,I=t.map((S,C)=>{let w=C===t.length-1,B=F(S.id),se=w?B?.[n]?.title:void 0;return`${C?" / ":""}${S.title??""}${se?` \u25B8 ${se}`:""}`}).join(""),R=hl(I,e);return vt.createElement(ro,null,vt.createElement(xl,{color:N.secondary2},R),y?p.map(S=>vt.createElement(ro,{key:S,paddingLeft:2},vt.createElement(lt,{id:S}))):null,y?v.map(S=>vt.createElement(ro,{key:S,paddingLeft:2},vt.createElement(ct,{id:S}))):null)};import{Box as yl,Text as ea}from"ink";import Gr from"react";var El=({filters:e})=>Gr.createElement(yl,{columnGap:1},Gr.createElement(ea,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:r,operator:n})=>Gr.createElement(ea,{backgroundColor:"black",color:"white"},` ${r}${n}"${t}" `))),ta=Gr.memo(El);var ra="0.4.11";function Xr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:r,eventLog:n,unappliedEvents:o}=$(),{userName:i,preferredEditor:a}=le(),c=40,u=process.stdout.columns-c-8,m=n.at(-1)?.id,p=gr(m??""),v=he(p)?jo(p.value):"INVALID DATE";return oe.createElement(Yr,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?oe.createElement(Ke,null," "):oe.createElement(Yr,{paddingLeft:1},e.length>0?oe.createElement(ta,{filters:e}):oe.createElement(Qs,{width:u})),r==="live"?oe.createElement(Yr,{columnGap:1,paddingRight:2,"max-width":c,overflow:"hidden",justifyContent:"flex-end"},oe.createElement(Ke,{dimColor:!0,color:N.secondary2},ra+" "),oe.createElement(oa,{icon:"@",value:i}),oe.createElement(oa,{icon:"\u276F",value:a})):"",r==="peek"?oe.createElement(Yr,{paddingLeft:1},oe.createElement(Ke,{backgroundColor:N.yellow}," Readonly "),oe.createElement(Ke,{color:N.yellow}," "+o.length+" edits ago at "),oe.createElement(Ke,{backgroundColor:N.yellow,color:N.accent}," "+v+" "),oe.createElement(Ke,{color:N.yellow},". Resume with "),oe.createElement(Ke,{backgroundColor:N.yellow}," :peek now ")):"")}function oa({icon:e,value:t}){return oe.createElement(Ke,null,na.dim(e)+na.hex(N.accent)(` ${t??"-"} `))}import{Box as Nl,Text as Cl}from"ink";import zt from"react";import{Box as Jr,Text as no}from"ink";import Ve from"react";function oo(){let e=$(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,a=t?.id?T(t?.id):[];return Ve.createElement(Jr,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:N.secondary,width:i},Ve.createElement(Jr,{padding:1,paddingTop:0,paddingBottom:0},Ve.createElement(no,null,"Select a board:")),Ve.createElement(Jr,{padding:1,flexDirection:"column"},a.map((c,u)=>{let m=e.currentNode.context==="WORKSPACE"&&e.selectedIndex===u,v=T(c.id).flatMap(({id:y})=>F(y)).length;return Ve.createElement(Jr,{key:c.id??u},Ve.createElement(no,{color:m?N.accent:N.secondary2},Ve.createElement(de,{isSelected:m})),Ve.createElement(no,{color:m?N.accent:N.secondary2},c.title," (",v," issues)",c.readonly?" \u{1F512}":""))})))}var Il=({currentNode:e,selectedIndex:t,breadCrumb:r,mode:n,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:c}=$(),u=r.find(({context:y})=>y==="BOARD"),v=i-1-3;return zt.createElement(Nl,{flexDirection:"row"},e.context==="WORKSPACE"?zt.createElement(oo,null):u?zt.createElement(Ir,{height:v,width:a,swimlanes:(c[u.id]??[]).filter(y=>y!==void 0&&nt(y)),currentNode:e,selectedIndex:t,breadCrumb:r,viewMode:o,mode:n}):zt.createElement(Cl,null))},ia=zt.memo(Il);function io({width:e,height:t}){let r=$(),n=r.filters;if(r.mode===g.HELP)return X.createElement(Qe,{flexDirection:"column"},X.createElement(Js,{width:e}));let{isSetup:o,hasPreferredEditor:i,hasUserName:a,userName:c,preferredEditor:u}=rt(),m=!o,p=o&&!r.hasProject;if(m)return X.createElement(Qe,{flexDirection:"column"},X.createElement(Qe,{flexDirection:"column"},X.createElement(Xr,{hideBreadCrumb:!0,filters:n}),X.createElement(to,{height:t,width:e,hasUserName:a,hasPreferredEditor:i,userName:c??"",preferredEditor:u??""})),X.createElement(Vr,{width:e,mode:r.mode,availableHints:r.availableHints}));if(p)return X.createElement(Qe,{flexDirection:"column"},X.createElement(Qe,{flexDirection:"column"},X.createElement(Xr,{hideBreadCrumb:!0,filters:n}),X.createElement(Zs,{height:t,width:e})),X.createElement(Vr,{width:e,mode:r.mode,availableHints:r.availableHints}));let v=Ne(x().breadCrumb??[],"BOARD");if(he(v)){let y=v.value.id,I=T(y).length,R=3,S=Math.floor(e/R),C=Math.floor(e/Math.max(I,1));e=Math.min(C,S)*Math.max(I,R)}return X.createElement(Qe,{flexDirection:"column"},X.createElement(Qe,{flexDirection:"column"},X.createElement(Xr,{filters:n}),X.createElement(ia,{width:e,height:t,currentNode:r.currentNode,selectedIndex:r.selectedIndex,breadCrumb:r.breadCrumb,viewMode:r.viewMode,mode:r.mode})),X.createElement(Vr,{width:e,mode:r.mode,availableHints:r.availableHints}))}import bl from"readline";var Zr,Qr,be,Sl=new Set([h.MoveCursorLeft,h.EraseInputWord,h.MoveCursorLeftOfWord,h.MoveCursorRight,h.MoveCursorRightOfWord,h.NavToPreviousContainer,h.NavToNextContainer,h.NavPreviousItem,h.NavNextItem,h.SetViewDense,h.SetViewWide,h.Confirm,h.Exit,h.InitCommandLine,h.ExitCommandLine,h.CaptureInput,h.EraseInput,h.EraseInputWord,h.HideHelp,h.ViewHelp,h.SetViewDense,h.SetViewWide,h.GetLastCommandFromHistory,h.GetNextCommandFromHistory,h.AutoCompleteCommand]),sa=async e=>{if(e.ctrl&&e.name==="c")return L.exit();let{actionIndex:t,mode:r,readOnly:n}=x(),o=si(e,r);if(!o||n&&!Sl.has(o))return;let i=t[r]?.[o];if(i?.action)try{await i.action(i,e)}catch(a){logger.error(a)}},Rl=()=>async function(t,r){r.name!=="escape"&&(be&&(clearTimeout(be),be=void 0),await sa(r))},Al=()=>async function(t){if(t.length===1&&t[0]===27){be&&clearTimeout(be),be=setTimeout(()=>{sa({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),be=void 0},25);return}be&&(clearTimeout(be),be=void 0)};function aa(){Zr&&process.stdin.removeListener("keypress",Zr),Qr&&process.stdin.removeListener("data",Qr),Zr=Rl(),Qr=Al(),bl.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Qr),process.stdin.on("keypress",Zr)}Tl(`${so.bold("Epiq CLI")}
64
59
 
65
- ${Gr.dim("Boot in directory:")}
66
- ${Gr.cyan("$ epiq")}
60
+ ${so.dim("Boot in directory:")}
61
+ ${so.cyan("$ epiq")}
67
62
 
68
- `,{importMeta:import.meta,flags:{init:{type:"boolean",default:!1}}});var Zs=process.stdout.columns||120,Qs=process.stdout.rows||20,Bn=null,El=e=>{if(!Bn){Bn=xl(e);return}Bn.rerender(e)},ea=()=>{El(hl.createElement(qr,{width:Zs,height:Qs}))},Nl=()=>{let e=Be(process.cwd());return d(e)?{hasProject:!1,epiqRootDir:null,events:[]}:{hasProject:!0,epiqRootDir:e.value,events:[]}};async function Cl(){let e=us();d(e)||Qe(e.value);let t=Nl();if(t.hasProject){await qi();let r=Et(t.epiqRootDir);d(r)||(t.events=r.value)}let n=Nn(t.events);d(n)&&logger.info(`Failed to boot state: ${n.message}`),R({hasProject:t.hasProject}),ea(),Js()}process.stdout.on("resize",()=>{Zs=process.stdout.columns||120,Qs=process.stdout.rows||20,Bn&&ea()});(async()=>(console.clear(),await Cl()))();
63
+ `,{importMeta:import.meta,flags:{init:{type:"boolean",default:!1}}});var da=process.stdout.columns||120,ca=process.stdout.rows||20,en=null,Pl=e=>{if(!en){en=wl(e);return}en.rerender(e)},la=()=>{Pl(Ml.createElement(io,{width:da,height:ca}))},kl=()=>{let e=Ee(process.cwd());return d(e)?{hasProject:!1,epiqRootDir:null,events:[]}:{hasProject:!0,epiqRootDir:e.value,events:[]}};async function Ll(){let e=vs();d(e)||tt(e.value);let t=kl();if(t.hasProject){await Zi();let n=St(t.epiqRootDir);d(n)||(t.events=n.value)}let r=Ur({hasProject:t.hasProject,eventLog:t.events});d(r)&&logger.info(`Failed to boot state: ${r.message}`),A({hasProject:t.hasProject}),la(),aa()}process.stdout.on("resize",()=>{da=process.stdout.columns||120,ca=process.stdout.rows||20,en&&la()});(async()=>(console.clear(),await Ll()))();