epiq 0.3.7 → 0.3.9

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "epiq",
3
- "version": "0.3.7",
3
+ "version": "0.3.9",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "EPIQ - CLI based issue tracker",
@@ -21,7 +21,7 @@
21
21
  "vim-inspired"
22
22
  ],
23
23
  "bin": {
24
- "epiq": "dist/cli.js",
24
+ "epiq": "dist/index.js",
25
25
  "epiq-mcp": "dist/mcp.js"
26
26
  },
27
27
  "engines": {
@@ -29,14 +29,14 @@
29
29
  },
30
30
  "scripts": {
31
31
  "build": "tsc --noEmit",
32
- "build:npm": "rm -rf ./dist && esbuild source/cli.tsx --bundle --packages=external --platform=node --format=esm --target=node18 --minify --outfile=dist/cli.js --banner:js='#!/usr/bin/env node' && esbuild source/mcp/server.ts --bundle --packages=external --platform=node --format=esm --target=node18 --minify --outfile=dist/mcp.js --banner:js='#!/usr/bin/env node'",
33
- "build:sea:bundle": "rm -rf ./dist && esbuild source/cli.tsx --bundle --platform=node --format=cjs --target=node18 --minify --outfile=dist/sea.cjs",
32
+ "build:npm": "rm -rf ./dist && esbuild source/Index.tsx --bundle --packages=external --platform=node --format=esm --target=node18 --minify --outfile=dist/index.js --banner:js='#!/usr/bin/env node' && esbuild source/mcp/server.ts --bundle --packages=external --platform=node --format=esm --target=node18 --minify --outfile=dist/mcp.js --banner:js='#!/usr/bin/env node'",
33
+ "build:sea:bundle": "rm -rf ./dist && esbuild source/Index.tsx --bundle --platform=node --format=cjs --target=node18 --minify --outfile=dist/sea.cjs",
34
34
  "build:sea": "node --build-sea sea-config.json",
35
35
  "build:publish": "pnpm build:npm",
36
36
  "build:binary": "pnpm build:sea:bundle && pnpm build:sea",
37
37
  "dev": "IS_LOCAL=true tsc --watch --noEmit",
38
- "dev:start": "IS_LOCAL=true tsx source/cli.tsx",
39
- "start": "IS_LOCAL=true tsx source/cli.tsx",
38
+ "dev:start": "IS_LOCAL=true tsx source/Index.tsx",
39
+ "start": "IS_LOCAL=true tsx source/Index.tsx",
40
40
  "test": "prettier --check \"**/*.{ts,tsx}\" && vitest run --coverage",
41
41
  "prepack": "pnpm build:publish",
42
42
  "pack:check": "rm -f epiq-*.tgz && npm pack && FILE=$(ls -t epiq-*.tgz | head -n 1) && echo \"$FILE\" && tar -tf \"$FILE\"",
package/readme.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  _Distributed CLI based issue tracker TUI_ backed by git.
6
6
 
7
- Issue tracking is a part of the development lifecycle, but it often becomes a painful context switching exercise with poor ergonomics. `Epiq` provides issue tracking as a portable, integrated part of the development environment, with access to all the powerful tooling developers are used to. Epiq is a **CLI-native issue tracker** — powered by Git in which you can manage all your projects directly via the command line in a visual kanban board and edit content in your favorite, personalized editor.
7
+ Issue tracking is a part of the development lifecycle, but it often becomes a painful context switching exercise with poor ergonomics. `Epiq` provides issue tracking as a portable, integrated part of the development environment, with access to all the powerful tooling developers are used to. Epiq allows you to manage all your projects directly via the command line in a visual kanban board and edit content in your favorite editor.
8
8
 
9
9
  With great attention to user ergonomics, epiq intends to make project management painless and friction free again, and has developer satisfaction as its primary target.
10
10
 
@@ -113,7 +113,7 @@ If it is your first run, this opens the interactive setup wizard that sets you u
113
113
 
114
114
  From here, you can start running commands or use keyboard shortcuts to navigate.
115
115
 
116
- This creates local settings in `~/.epiq/**` and initializes synchronization for your repository. A local `.epiq` folder will also be created in your repository.
116
+ This creates settings in `~/.epiq-global/**` and initializes synchronization for your repository. A local `.epiq` folder will also be created in your repository.
117
117
 
118
118
  > Epiq will execute git commands on your behalf in order to sync your work with a dedicated state branch remotely.
119
119
 
@@ -168,7 +168,7 @@ Epiq uses Git in the background to synchronize state between clients. No manual
168
168
  - Your issue data is stored in a dedicated branch managed automatically by epiq
169
169
  - A local `.epiq/` folder is created in your project as a local cache
170
170
 
171
- The `.epiq/` folder is non-authoritative and used for caching and local tracking. It can optionally be committed if you want your board state versioned alongside your code.
171
+ The `.epiq/` folder is non-authoritative and used for caching and local tracking. Epiq automatically ensures it is gitignored on every sync.
172
172
 
173
173
  ## Conflict Avoidance & Data Integrity
174
174
 
package/dist/cli.js DELETED
@@ -1,46 +0,0 @@
1
- #!/usr/bin/env node
2
- import{render as Ic}from"ink";import Sc from"meow";import Tc from"react";import vc from"chalk";import{Box as fe,Text as _e}from"ink";import O from"react";import at from"chalk";import{monotonicFactory as yd,ulid as Te}from"ulid";import{useSyncExternalStore as pd}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function ye(e){return e.context==="TICKET"}var Ur=e=>e.context==="SWIMLANE";var p={INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",RENAME:"rename",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",SET_DESCRIPTION:"edit",SET_EDITOR:"config:editor",SET_VIEW:"config:view",SET_USERNAME:"config:username",SYNC:"sync",NONE:""},Ne={None:"none",Invalid:"invalid",Valid:"valid"},xe={None:"none",Success:"success",Fail:"fail"},s=e=>({result:xe.Fail,message:e,data:null}),u=(e,t)=>({result:xe.Success,message:e,data:t}),Wr=()=>({result:xe.None,message:"No result",data:null}),c=e=>e.result==="fail",Fe=e=>e.result==="success";var f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function Pt(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Dt=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Dn=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var Hr=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),i=t.get(o);i?i.push(n):t.set(o,[n])}return t},$r=(e,t)=>t?e.get(t)??[]:[];var _r=new WeakMap,us=e=>{let t=_r.get(e);return t||(t=Hr(e),_r.set(e,t)),t};var Kr=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return $r(us(e),r).filter(i=>Pt(r,i)>=n)};var Vr=({inputToMatch:e,lastWord:t},n)=>{if(t.endsWith(" "))return{hint:"",hints:[],overlap:0,remainder:""};let r=Kr({wordList:n,inputToMatch:e,overlapThreshold:1});return ms(t,r)},ms=(e,t)=>{let n=t[0]??"",r=Pt(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),a=r<(o??"").length,d=!!i,g=(d&&a?o:n)+(d&&a?":":" "),y=g.slice(r);return{hint:g,hints:t,overlap:r,remainder:y}};var jr=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var qe=24n,ps=qe*4n,Ft=(1n<<ps)-1n,gs=/^[0-9a-f]+$/;function zr(e){if(!e||!gs.test(e))throw new Error(`Invalid hex rank: ${e}`);return BigInt("0x"+e)}function kt(e,t=qe){if(e<0n)throw new Error("Negative rank not allowed");return e.toString(16).padStart(Number(t),"0")}function mt(e,t){if(!e&&!t)return kt(Ft/2n,qe);let n=e?zr(e):0n,r=t?zr(t):Ft;if(r<=n)return kt(Ft/2n,qe);let o=(n+r)/2n;return o===n||o===r?"":kt(o,qe)}function me(){return kt(Ft/2n,qe)}var ne={workspace:(e,t)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r=!1)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:(e,t,n,r={},o="horizontal")=>({id:e,title:t,rank:me(),isDeleted:!1,props:r,context:P.FIELD,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[]}),ticket:(e,t,n)=>({id:e,title:t,rank:me(),isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,props:r={},readonly:o=!0})=>({id:e,title:t,rank:me(),isDeleted:!1,props:r,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[]})};var W=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Gr=(e,t)=>e.findIndex(n=>n.id===t),Fn=(e,t={at:"end"})=>{if(e.length===0)return u("Resolved rank",me());switch(t.at){case"start":{let n=e[0];return n?u("Resolved rank",mt(void 0,n.rank)):s("Unable to resolve first sibling")}case"end":{let n=e[e.length-1];return n?u("Resolved rank",mt(n.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let n=Gr(e,t.sibling);if(n<0)return s("Sibling not found");let r=n>0?e[n-1]:void 0,o=e[n];return o?u("Resolved rank",mt(r?.rank,o.rank)):s("Sibling not found")}case"after":{let n=Gr(e,t.sibling);if(n<0)return s("Sibling not found");let r=e[n],o=n<e.length-1?e[n+1]:void 0;return r?u("Resolved rank",mt(r.rank,o?.rank)):s("Sibling not found")}}};var ke=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return s("Node not found");if(r.context===t)return u("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return u("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return s(`No ancestor found for context: ${t}`)},On=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},kn=(e,t)=>e?e.readonly?s({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:s("Node not found"),C={deleteNode(e){de(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return s("Edit target node not found");let o=kn(r,"edit");if(o)return o;let i={...r,props:{...r.props,value:t}};return C.updateNode(i),u("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return s("Rename target node not found");let r=kn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),u("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return W(e).find(n=>n.title===t)},moveNode({id:e,parentId:t,position:n={at:"end"}}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let a=kn(o,"move");if(a)return a;if(On(t,e))return s("Cannot move node into its own descendant");let d=W(t).filter(g=>g.id!==e),l=Fn(d,n);if(c(l))return l;let m={...o,parentNodeId:t,rank:l.data};return this.updateNode(m),u("Moved node successfully",m)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,a=l=>{let m=t[l];if(!(!m||i.has(l))){i.add(l);for(let g of W(m.id))a(g.id)}};a(e);let d={...structuredClone(t)};for(let l of i){if(!d[l])return s("Unable to locate node to delete");d[l]={...d[l],isDeleted:!0}}return n?(A({nodes:d}),u("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=de(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return c(t)?s("Unable to create contributor"):u("Created contributor",e)},assign(e,t,n){let r=C.getContributor(t),o=C.getNode(e);if(!o||!r)return s("Unable assign contributor to issue");let i=this.getFieldByTitle(o.id,"Assignees");if(!i)return s("Unable to locate assignees field");if(W(i.id).some(l=>l.props?.value===t))return s("Contributor already assigned");let d=this.createNodeAtPosition(ne.field(n,r.name,i.id,{value:t}));return c(d)?d:u("Assigned contributor",d.data)},createTag(e){let t=de(n=>({...n,tags:{...n.tags,[e.id]:e}}));return c(t)?s("Could not create tag"):u("Tag created",e)},tag(e,t,n){let r=C.getTag(t),o=C.getNode(e);if(!r)return s("Unable to add tag, missing tag");if(!o)return s("Unable to add tag, missing target");let i=this.getFieldByTitle(o.id,"Tags");if(!i)return s("Unable to locate tags field");if(W(i.id).some(l=>l.props?.value===t))return s("Tag already assigned");let d=this.createNodeAtPosition(ne.field(n,r.name,i.id,{value:t}));return c(d)?d:u("Tag added",d.data)},untag(e,t){let n=C.getTag(t),r=C.getNode(e);if(!n)return s("Unable to remove tag, missing tag");if(!r)return s("Unable to remove tag, missing target");let o=this.getFieldByTitle(r.id,"Tags");if(!o)return s("Unable to locate tags field");let i=W(o.id).find(d=>d.props?.value===t);if(!i)return u("Issue is not tagged with that tag",null);let a={...i,isDeleted:!0};return this.updateNode(a),u("Tag removed",a)},unassign(e,t){let n=C.getContributor(t),r=C.getNode(e);if(!n)return s("Unable to unassign, missing contributor");if(!r)return s("Unable to unassign, missing target");let o=this.getFieldByTitle(r.id,"Assignees");if(!o)return s("Unable to locate assignees field");let i=W(o.id).find(d=>d.props?.value===t);if(!i)return u("Issue is not assigned to that contributor",null);let a={...i,isDeleted:!0};return this.updateNode(a),u("Assignee removed",a)},createNodeAtPosition(e,t={at:"end"}){if(!e.parentNodeId){let i={...e,rank:me()};return this.createNode(i),u("Created node",i)}let n=W(e.parentNodeId),r=Fn(n,t);if(c(r))return r;let o={...e,rank:r.data};return this.createNode(o),u("Created node",o)},createNode(e){let t=de(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return c(t)?s("Unable to create node"):u("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let n={...t,readonly:!0},r=de(o=>({...o,nodes:{...o.nodes,[e]:n}}));return c(r)?s(r.message):u("Locked node",n)},updateNode(e){let t=de(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return c(t)?t:u("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings:e=>Object.values(v().nodes).filter(t=>!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank))};var Ot={autoSync:!1,preferredEditor:null,userName:null,userId:null},pe=()=>Ot,Ye=e=>(Ot={...Ot,...e},Ot);var Bt=()=>{let e=pe(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},qr=()=>!Ke();var q={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#2a2f45",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},E={accent:q.cyan,accent2:q.magenta,primary:q.white,secondary:q.grayDark,secondary2:q.grayLight,gray:q.gray,green:q.green,yellow:q.yellow,red:q.red};var h={red:q.red,yellow:q.yellow,green:q.green,blue:q.blue,magenta:q.magenta,cyan:q.cyan},Je={urgent:h.red,critical:h.red,important:h.red,blocker:h.red,asap:h.red,immediate:h.red,fail:h.red,failure:h.red,broken:h.red,bug:h.red,error:h.red,incident:h.red,outage:h.red,production:h.red,crash:h.red,security:h.red,warning:h.yellow,warn:h.yellow,risky:h.yellow,risk:h.yellow,attention:h.yellow,pending:h.yellow,review:h.yellow,"needs-review":h.yellow,qa:h.yellow,testing:h.yellow,test:h.yellow,validate:h.yellow,verification:h.yellow,staging:h.yellow,check:h.yellow,"follow-up":h.yellow,followup:h.yellow,waiting:h.yellow,blocked:h.yellow,hold:h.yellow,done:h.green,complete:h.green,completed:h.green,success:h.green,ok:h.green,stable:h.green,resolved:h.green,fixed:h.green,closed:h.green,merged:h.green,released:h.green,deployed:h.green,approved:h.green,verified:h.green,working:h.green,healthy:h.green,pass:h.green,passing:h.green,info:h.blue,information:h.blue,note:h.blue,docs:h.blue,documentation:h.blue,doc:h.blue,guide:h.blue,help:h.blue,explanation:h.blue,detail:h.blue,details:h.blue,context:h.blue,design:h.blue,discussion:h.blue,proposal:h.blue,idea:h.blue,feature:h.magenta,enhancement:h.magenta,improvement:h.magenta,refactor:h.magenta,refactoring:h.magenta,cleanup:h.magenta,optimize:h.magenta,optimization:h.magenta,perf:h.magenta,performance:h.magenta,upgrade:h.magenta,migration:h.magenta,modernize:h.magenta,debt:h.magenta,todo:h.cyan,next:h.cyan,planned:h.cyan,plan:h.cyan,future:h.cyan,backlog:h.cyan,investigate:h.cyan,explore:h.cyan,prototype:h.cyan};var Yr=(e,t)=>{let r=M(e.id).find(o=>o.title===t);return r?M(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},Bn=e=>Yr(e,"Tags").map(t=>C.getTag(t)).filter(t=>!!t),Ut=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ye(n)?s("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",Bn(n)??[])},Wt=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ye(n)?s("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",Un(n)??[])},Un=e=>Yr(e,"Assignees").map(t=>C.getContributor(t)).filter(t=>!!t);var fs=/^(\d+)(h|d|w|mo|y)$/,ys=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,xs=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let i=new Date(e,t-1,n,r,o);return i.getFullYear()===e&&i.getMonth()===t-1&&i.getDate()===n&&i.getHours()===r&&i.getMinutes()===o},vs=(e,t=new Date)=>{let n=e.match(fs);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let a=new Date(t);switch(o){case"h":return a.setHours(a.getHours()-i),a;case"d":return a.setDate(a.getDate()-i),a;case"w":return a.setDate(a.getDate()-i*7),a;case"mo":return a.setMonth(a.getMonth()-i),a;case"y":return a.setFullYear(a.getFullYear()-i),a;default:return null}},hs=e=>{let t=e.match(ys);if(!t)return null;let[,n,r,o,i,a]=t,d=Number(n),l=Number(r),m=Number(o),g=i?Number(i):0,y=a?Number(a):0;return xs({year:d,month:l,day:m,hour:g,minute:y})?new Date(d,l-1,m,g,y):null},Ht=e=>{let t=e.trim().toLowerCase();return vs(t)??hs(t)},Jr=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Es=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],Xr=(e=Es)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let i=r;i<=o;i++)t.push(`${i}${n}`);return t};var Cs=["BOARD","TICKET","SWIMLANE"],z=e=>{let{currentNode:t,readOnly:n,selectedNode:r}=v(),o=Bt().isSetup,i=t.context,a=r?.context,d=[p.SYNC,p.HELP,p.SET_VIEW,p.SET_EDITOR,p.SET_USERNAME],l=[p.NEW,p.RENAME,p.DELETE],m=[p.TAG,p.UNTAG,p.ASSIGN,p.UNASSIGN,p.CLOSE_ISSUE,p.RE_OPEN_ISSUE,p.SET_DESCRIPTION],g=[p.FILTER,p.PEEK],y={WORKSPACE:[...d,...l],BOARD:[...g,...d,...l],SWIMLANE:[...g,...d,...l],TICKET:[...d,...l,...m],FIELD:[...d,...m],FIELD_LIST:[...d,...m],TEXT:[...d]},N=a&&Cs.includes(a),b=[...y[i||"WORKSPACE"]].filter(T=>[p.RENAME,p.DELETE,p.MOVE].includes(T)?N:!0),I={[p.PEEK]:[...Xr(),"now","prev","next"],[p.SYNC]:[],[p.INIT]:[],[p.SET_USERNAME]:[],[p.SET_DESCRIPTION]:["confirm"],[p.DELETE]:["confirm"],[p.RE_OPEN_ISSUE]:["confirm"],[p.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[p.CLOSE_ISSUE]:["confirm"],[p.FILTER]:["tag","assignee","description","title","clear"],[p.SET_VIEW]:["dense","wide"],[p.SET_EDITOR]:[...jr,"vim"],[p.TAG]:[...new Set([...Object.keys(Je),...C.getExistingTags()])],[p.UNTAG]:[...Ut()?.data?.map(({name:T})=>T)??[]],[p.UNASSIGN]:[...Wt()?.data?.map(({name:T})=>T)??[]],[p.ASSIGN]:C.getExistingAssignees(),[p.HELP]:[],[p.RENAME]:[],[p.NEW]:i==="TICKET"||i==="FIELD"||i==="FIELD_LIST"?["issue","swimlane","board"]:i==="SWIMLANE"?["issue","swimlane","board"]:i==="BOARD"?["issue","swimlane","board"]:["board"],[p.NONE]:b};return o?qr()?n&&(I={[p.NONE]:[p.HELP,p.PEEK],[p.HELP]:I[p.HELP],[p.PEEK]:I[p.PEEK]}):I={[p.NONE]:[p.HELP,p.INIT],[p.HELP]:I[p.HELP],[p.INIT]:I[p.INIT]}:I={[p.NONE]:[p.HELP,p.SET_EDITOR,p.SET_USERNAME],[p.HELP]:I[p.HELP],[p.SET_EDITOR]:I[p.SET_EDITOR],[p.SET_USERNAME]:I[p.SET_USERNAME]},I[e]??[]};import Qe from"chalk";import{decodeTime as Qr}from"ulid";var Zr=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let i=Math.floor(t/o);if(i>=1)return`${i}${r} ago`}return"just now"},eo=e=>{let t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`},$t=e=>{try{return u("Decoded date",new Date(Qr(e)))}catch(t){return s("Decoding failed + "+t.message)}},Wn=e=>{if(!e?.id)return null;try{return Qr(e.id)}catch{return null}};var be=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?u("Found node",n):s("Unable to find node in breadcrumb")};import Xe from"chalk";var $n={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Ns=(e,t,n)=>Math.max(t,Math.min(n,e)),Hn=(e,t,n)=>e+(t-e)*n,to=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},bs=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,a=e/60,d=i*(1-Math.abs(a%2-1)),l=0,m=0,g=0;a>=0&&a<1?(l=i,m=d):a>=1&&a<2?(l=d,m=i):a>=2&&a<3?(m=i,g=d):a>=3&&a<4?(m=d,g=i):a>=4&&a<5?(l=d,g=i):(l=i,g=d);let y=o-i/2;return[Math.round((l+y)*255),Math.round((m+y)*255),Math.round((g+y)*255)]},Is=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Ss=(e,t,n)=>[Math.round(Hn(e[0],t[0],n)),Math.round(Hn(e[1],t[1],n)),Math.round(Hn(e[2],t[2],n))],pt=e=>{let n=to(e)%360,r=bs(n,$n.stringColor.saturation,$n.stringColor.lightness);return Is(r)},Ts=e=>{let t=$n.gradient.stops,n=Ns(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,i=Math.min(Math.floor(o),r-1),a=o-i;return Ss(t[i],t[i+1],a)},_t=e=>to(e.toLowerCase().trim())/4294967295,no=e=>{let t=_t(e);return Ts(t)},As=e=>{let[t,n,r]=no(e);return{normal:o=>Xe.bgRgb(t,n,r).black(o),cursor:o=>Xe.bgRgb(t,n,r).white.bold(o)}},_n=e=>{let[t,n,r]=no(e);return{fg:o=>Xe.rgb(t,n,r)(o),fgCursor:o=>Xe.rgb(t,n,r).inverse(o),bg:o=>Xe.bgRgb(t,n,r).black(o),bgCursor:o=>Xe.bgRgb(t,n,r).white.bold(o)}},Kn=e=>As(e).normal(` ${e} `),Y=(e,t=Je)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:pt(r)};var ws=["BOARD","TICKET","SWIMLANE"],Vn=()=>{let e=v().selectedNode;return e?.context?ws.includes(e?.context)?V():H({message:"Command not available in this context"}):H({message:"Missing target context"})},ce="<ENTER> to confirm",V=(e="",t=[])=>({message:e,validity:Ne.Valid,completionWordList:t}),H=({message:e,completionWordList:t=[]})=>({validity:Ne.Invalid,message:e,completionWordList:t}),ft=e=>e.length===0,Oe=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let l=[...t.filter(Boolean).filter(g=>g.startsWith(o.trim()))].sort((g,y)=>_t(g)-_t(y)).slice(0,r).map(Kn),m=l.length>i?l.join(" "):"";return m?`${e}${m}${n}`:""},jn=({modifier:e})=>{let t="confirm";return e===t?V(ce):H({message:ft(e)?`if you are certain, enter ${Kn(t)}`:"",completionWordList:[t]})},Rs=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?V(ce):H({message:ft(n)?t:""}),Ms=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?H({message:n}):V():H({message:ft(r)?t:""}),gt=({hint:e})=>({modifier:t,inputString:n})=>ft(t)&&ft(n)?H({message:e,completionWordList:[]}):V(ce),Ls={[p.PEEK]:e=>{let t=e.modifier;if(t==="now")return V(ce);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return V(ce);let r=Ht(t);if(!t||!r)return H(n);let o=be(v().breadCrumb,"BOARD");if(c(o))return H({message:"Command is not applicable in this context"});let i=$t(o.data.id);return c(i)?H({message:"Unable to peek: board id is not a valid ULID"}):Jr({date:r,horizonDate:i.data})?V(ce):H({message:Qe.red(`nothing to peek before ${i.data.toISOString().slice(0,16).replace("T"," ")}`)})},[p.INIT]:()=>V(ce),[p.FILTER]:e=>{if(e.modifier==="clear")return V();let t=a=>z(p.FILTER).includes(a);if(!e.modifier||!t(e.modifier??""))return H({message:Oe({wordList:z(p.FILTER),inputString:e.inputString}),completionWordList:z(p.FILTER)});let r=Object.values(v().tags).map(a=>a.name),o=Object.values(v().contributors).map(a=>a.name),i=e.modifier==="tag"?r:e.modifier==="assignee"?o:[];return e.inputString?i.length&&!i.includes(e.inputString.trim()??"")?H({message:Oe({prefix:`existing ${e.modifier}s... `,wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i}):V():H({message:Oe({prefix:"one of... ",wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i})},[p.NONE]:e=>{let t=z(p.NONE),n=/^[A-Za-z_]+:/g,r=e.inputString.match(n);return r&&r.length?t=[...t.filter(o=>o.trim().match(n))]:t=[...new Set(t.flatMap(o=>o.match(n)?.join("").replace(":","")??o))],e.command?V():H({message:Oe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[p.NEW]:e=>Ms({list:z(p.NEW),hint:Oe({wordList:z(p.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[p.SET_DESCRIPTION]:()=>V(ce),[p.HELP]:()=>V(ce),[p.RENAME]:()=>{let e=Vn();return e.validity==="invalid"?e:V(ce)},[p.DELETE]:e=>{let t=Vn();return t.validity==="invalid"?t:jn(e)},[p.CLOSE_ISSUE]:e=>jn(e),[p.RE_OPEN_ISSUE]:e=>jn(e),[p.MOVE]:e=>{let t=Vn();return t.validity==="invalid"?t:gt({hint:Oe({prefix:"hey hacker! These commands are blocked for you... ",wordList:z(p.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[p.TAG]:e=>{let t=C.getExistingTags().map(n=>` ${Qe.bgHex(Y(n))(" "+n+" ")} `).slice(0,10);return gt({hint:"tag name like... "+t.join("")})(e)},[p.UNTAG]:e=>{let t=Ut();if(c(t))return H({message:"Invalid untag target",completionWordList:[]});let n=t.data.map(({name:r})=>r).map(r=>` ${Qe.bgHex(Y(r))(" "+r+" ")} `).slice(0,10);return n.length?gt({hint:" ... "+n.join("")})(e):H({message:"Issue has not tags",completionWordList:[]})},[p.ASSIGN]:e=>{let t=C.getExistingAssignees().map(n=>` ${Qe.bgHex(Y(n))(" "+n+" ")} `).slice(0,10);return gt({hint:"assign to... "+t.join("")})(e)},[p.UNASSIGN]:e=>{let t=Wt();if(c(t))return H({message:"Invalid unassign target",completionWordList:[]});let n=t.data.map(({name:r})=>r).map(r=>` ${Qe.bgHex(Y(r))(" "+r+" ")} `).slice(0,10);return n.length?gt({hint:"remove assignee... "+n.join("")})(e):H({message:"Issue has no assignees",completionWordList:[]})},[p.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=z(p.SET_EDITOR);return e.modifier?V(ce):H({message:Oe({wordList:t,inputString:e.inputString})})},[p.SET_USERNAME]:e=>e.inputString?V():H({message:`Enter a username. Saved in ${Qe.bgBlack("~/.epiq/")}`}),[p.SET_VIEW]:e=>Rs({list:z(p.SET_VIEW),hint:Oe({wordList:z(p.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[p.SYNC]:()=>V(ce)},ro=Object.fromEntries(Object.entries(Ls).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var oo=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"];var L={Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",SetView:"set-view",SetEditor:"set-editor",SetUserName:"set-user-name",SetAutoSync:"set-auto-sync",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Sync:"sync"};var io=e=>Object.values(p).includes(e),so=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:d,completionWordList:l}=ro[n].validate(n,r,i),m=o==="command"?Object.values(p):n&&e.target==="modifier"?z(n):oo;return{validity:d,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?Vr(e,[...l,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var ao=e=>{let t=e.trimStart(),n=Ds(t),r=(n[0]??"").trimStart().trimEnd(),o=(n[1]??"").trimStart().trimEnd(),i=Fs(e),a=io(r)?r:null,d=a!==null,l=r!=="",m=e.endsWith(" "),g=a?z(a)??[]:[],y=a&&g.includes(o)?o:"",N="word";n.length<=1?N="command":n.length===2&&(N="modifier");let b=Ps(t,a,y);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:l,command:a,isCommandKeyword:d,isLastWordCompleted:m,modifier:y,target:N,inputToMatch:i,inputString:b}},Ps=(e,t,n)=>{let r=e;return t&&r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/^\s+/,""),n&&r.startsWith(n)&&(r=r.slice(n.length),r=r.replace(/^\s+/,"")),r},Ds=e=>e?e.split(/\s+/):[],Fs=e=>e.trimEnd().split(/\s+/).at(-1)??"";var co=" ",J={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Ne.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},zn=new Set,lo=()=>{for(let e of zn)e()},uo=e=>(zn.add(e),()=>zn.delete(e)),Ie=e=>{let n=e(J),r=ao(n.value),o=n.cursorPosition===n.value.length;J={...n,commandMeta:so(r,o)},lo()},yt=({message:e,result:t})=>{let n=structuredClone(J);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,J=n,lo(),u(e,null)},Gn=e=>{Ie(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},qn=e=>{Ie(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&n[o-1]===" ";)o--;for(;o>0&&n[o-1]!==" ";)o--}else{for(;o<n.length&&n[o]!==" ";)o++;for(;o<n.length&&n[o]===" ";)o++}return{...t,cursorPosition:o}})},mo=()=>{Ie(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},po=()=>{Ie(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&t[r-1]===" ";)r--;for(;r>0&&t[r-1]!==" ";)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},j=e=>{Ie(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),i=e(r,t.commandMeta.autoCompletion),a=i+o,d=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:d,commandIsPending:!1}})},go=()=>{Ie(e=>({...e,commandIsPending:!0}))},fo=({addToHistory:e=!0})=>{Ie(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),ks()},yo=()=>{Ie(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},xo=()=>{Ie(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ks=()=>j(()=>""),re=()=>J,Kt=()=>{let[e,...t]=J.value.split(co);return t.join(co).trim()};var Os=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Bs=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",Us=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",vo=(e,t)=>{if(Bs(e,e.sequence))return x.MoveCursorLeftOfWord;if(Us(e,e.sequence))return x.MoveCursorRightOfWord;if(Os(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.GetLastCommandFromHistory;case"down":return x.GetNextCommandFromHistory;case"left":return x.MoveCursorLeft;case"right":return x.MoveCursorRight;case"return":return x.Confirm;case"backspace":return t?x.EraseInput:x.ExitCommandLine;case"escape":return x.ExitCommandLine;default:return x.CaptureInput}};var x={Sync:"sync",NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function Ws(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function Hs(e,t,n){let r=v().currentNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function ho(e,t){let n=re();if(e.sequence===":"&&n.value==="")return x.InitCommandLine;if(t===f.MOVE)switch(e.name){case"m":case"return":return x.ConfirmMove}if(t===f.COMMAND_LINE)return vo(e,n.value);let r=Ws(e);if(r){let o=t===f.MOVE?{prevItem:x.MovePreviousItem,nextItem:x.MoveNextItem,prevContainer:x.MoveToPreviousContainer,nextContainer:x.MoveToNextContainer}:{prevItem:x.NavPreviousItem,nextItem:x.NavNextItem,prevContainer:x.NavToPreviousContainer,nextContainer:x.NavToNextContainer};return Hs(v().currentNode.childRenderAxis,r,o)}if(e.ctrl&&e.name==="c")return x.Exit;switch(e.name){case"e":return x.Edit;case"n":return x.AddItem;case"m":return x.InitMove;case"d":return x.Delete;case"return":return x.Confirm;case"space":return x.Confirm;case"v":return v().viewMode==="wide"?x.SetViewDense:x.SetViewWide;case"q":case"escape":return x.Exit;case"s":return x.Sync;default:return null}}var Eo=e=>{let{context:t}=v()?.currentNode;if(!t)return L.None;switch(e){case p.INIT:return L.Init;case p.DELETE:return L.Delete;case p.SET_DESCRIPTION:return L.Edit;case p.HELP:return L.ViewHelp;case p.RE_OPEN_ISSUE:return L.ReopenIssue;case p.CLOSE_ISSUE:return L.CloseIssue;case p.TAG:return L.TagTicket;case p.UNTAG:return L.UntagTicket;case p.ASSIGN:return L.AssignUserToTicket;case p.UNASSIGN:return L.UnassignUserFromTicket;case p.RENAME:return L.Rename;case p.NEW:return L.NewItem;case p.FILTER:return L.Filter;case p.MOVE:return L.Move;case p.PEEK:return L.Peek;case p.SET_USERNAME:return L.SetUserName;case p.SET_EDITOR:return L.SetEditor;case p.SET_VIEW:return L.SetView;case p.SYNC:return L.Sync;default:return L.None}};import{ulid as $}from"ulid";import{spawnSync as qs}from"node:child_process";import Ys from"node:os";import Io from"node:path";import{ulid as Js}from"ulid";import{accessSync as $s,copyFileSync as _s,existsSync as Vt,mkdirSync as Co,readdirSync as No,readFileSync as Ks,renameSync as Vs,rmSync as js,statSync as bo,unlinkSync as zs,writeFileSync as Gs}from"node:fs";import Ze from"node:path";var le={writeToFile:(e,t)=>{try{let n=Ze.dirname(e);Vt(n)||Co(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Gs(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Ks(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=le.readFile(e);return t===null?null:JSON.parse(t)}catch(t){return logger.error(`Failed to read JSON at ${e}:`,t),null}},dirExists:e=>{try{return Vt(e)&&bo(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await $s(e),!0}catch{return!1}},mkDir:e=>Co(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Ze.parse(t);for(;;){let r=Ze.join(t,e);try{if(Vt(r)&&bo(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Ze.dirname(t)}return null},readFirstJSON(e){try{if(!le.dirExists(e))return null;let t=No(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Ze.join(e,t);return le.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return le.dirExists(e)?No(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{zs(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{js(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Ze.dirname(t)),!n?.overwrite&&Vt(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Vs(e,t)}catch(r){if(r?.code==="EXDEV"){_s(e,t),this.rmFile(e);return}throw r}}};function Xs(){let{preferredEditor:e}=pe(),t=[e,process.env.VISUAL,process.env.EDITOR,"vim","nano"].filter(n=>!!n?.trim());return[...new Set(t)]}function Qs(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function So(e){let t=Io.join(Ys.tmpdir(),"epiq");le.mkDir(t);let n=Io.join(t,Js());le.writeToFile(n,e??"");let r=Xs();for(let o of r){let i=Qs(o,n),a=qs(i,{stdio:"inherit",shell:!0});if(!a.error&&a.status===0){let d=le.readFile(n);if(d==null)return s("Unable to read edited file");let l=d.replace(/\r?\n$/,"");return u("Successfully edited",l)}}return s("Unable to open editor")}import{monotonicFactory as Zs,ulid as jt}from"ulid";var zt=Zs(),To=({name:e,parent:t,user:{userId:n,userName:r}})=>{let o=zt(),i=zt(),a=zt(),d=zt();return[{id:jt(),userId:n,userName:r,action:"add.issue",payload:{id:o,parent:t,name:e}},{id:jt(),userId:n,userName:r,action:"add.field",payload:{id:i,parent:o,name:"Description",val:""}},{id:jt(),userId:n,userName:r,action:"add.field",payload:{id:a,parent:o,name:"Assignees"}},{id:jt(),userId:n,userName:r,action:"add.field",payload:{id:d,parent:o,name:"Tags"}}]};import Xt from"node:fs";import Qt from"node:path";import{z as Xn}from"zod";var Gt=process.env.IS_LOCAL==="true",Se=()=>".epiq";import qt from"node:fs";import ea from"node:os";import Be from"node:path";import{decodeTime as ta,monotonicFactory as na}from"ulid";import{z as xt}from"zod";var Ao=e=>({action:e.action,payload:e.payload});var ra=Be.resolve(ea.homedir(),".epiq"),Ro=1,wo=na(),oa="events",ia=xt.tuple([xt.string().min(1),xt.string().min(1).nullable()]),sa=xt.looseObject({v:xt.literal(Ro),id:ia}),Yn=e=>{let t=sa.safeParse(e);return t.success?u("Parsed persisted event",t.data):s(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Yt=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",X=()=>{let{userName:e,userId:t}=pe();return e?t?e.trim()?u("Successfully resolved actor ID",{userId:Yt(t),userName:Yt(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},aa=e=>Be.resolve(e)===ra,da=e=>{let t=Be.join(e,Se());return!aa(t)&&qt.existsSync(t)&&qt.statSync(t).isDirectory()},et=e=>{let t=Be.resolve(e);for(;;){if(da(t))return t;let n=Be.dirname(t);if(n===t)return Be.resolve(e);t=n}},Mo=e=>Be.join(et(e),Se(),oa),Jn=({userId:e,userName:t})=>`${Yt(e)}.${Yt(t)}.jsonl`,ca=(e,{userId:t,userName:n})=>{let r=Jn({userId:t,userName:n});return/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r)?u("Successfully resolved event log path",Be.join(Mo(e),r)):s(`Invalid event log file name: ${r}`)},la=(e,t)=>{let n={[e.action]:e.payload,v:Ro,id:t};return Yn(n)};function Jt({event:e,rootDir:t=process.cwd()}){try{let n=et(t),r=Mo(n),o=ca(n,{userId:e.userId,userName:e.userName});if(c(o))return o;qt.mkdirSync(r,{recursive:!0});let i=Lo(n);if(c(i))return s(i.message);let a=i.data?wo(Math.max(Date.now(),ta(i.data)+1)):wo(),d=la(Ao(e),[a,i.data]);return c(d)?s(d.message):(qt.appendFileSync(o.data,`${JSON.stringify(d.data)}
3
- `,"utf8"),u("Event persisted",{path:o.data,entry:d.data}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return s(`Failed to persist event: ${r}`)}}import{decodeTime as ua}from"ulid";var ma=Se(),pa="events",ga=Xn.object({userId:Xn.string().min(1).default("unknown"),userName:Xn.string().min(1).default("unknown")}),fa=(e=process.cwd())=>Qt.join(et(e),ma,pa),ya=e=>{let[t,n]=Qt.basename(e,".jsonl").split("."),r=ga.safeParse({userId:t,userName:n});return r.success?u("Parsed event file actor",r.data):s(`Invalid event file name ${Qt.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},xa=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?s(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?s("Invalid persisted event: action key is missing or invalid"):u("Resolved persisted action",t[0])},va=(e,t)=>t in e,ha=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Ea=e=>{let{userId:t,userName:n,...r}=e,o=xa(r);if(c(o))return s(o.message);let i=o.data,a=e.id?.[0];return a?va(r,i)?u("Decoded persisted event",ha({id:a,action:i,payload:r[i],userId:t,userName:n})):s(`Persisted event is missing payload for action: ${i}`):s("Persisted event is missing id")},Zt=e=>{if(!Xt.existsSync(e))return u("Event file missing",[]);let t=ya(e);if(c(t))return s(t.message);let n=Xt.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
4
- `)){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{return s(`Failed to parse event JSON from ${e}: ${i}`)}let d=Yn(a);if(c(d))return s(`${d.message} in ${e}: ${i}`);r.push({...d.data,userId:t.data.userId,userName:t.data.userName})}return u("Parsed persisted events file",r)};function Po(e=process.cwd()){let t=fa(e);if(!Xt.existsSync(t))return s("No events found");let n=Xt.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Qt.join(t,o)),r=[];for(let o of n){let i=Zt(o);if(c(i))return s(i.message);r.push(...i.data)}return u("All events loaded",Ca(r))}function vt(e=process.cwd()){let t=Po(e);if(c(t))return s(t.message);let n=[];for(let r of t.data){let o=Ea(r);if(c(o))return s(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);n.push(o.data)}return u("Loaded merged events",n)}function Lo(e=process.cwd()){let t=Po(e);return c(t)?s(t.message):u("Loaded edge reference",t.data.at(-1)?.id?.[0]??null)}var Ca=e=>{let t=new Map(e.map(d=>[d.id[0],d])),n=new Map;for(let d of e){let l=d.id[1],m=n.get(l)??[];m.push(d),n.set(l,m)}for(let d of n.values())d.sort((l,m)=>{let[g]=l.id,[y]=m.id;return g.localeCompare(y)});let r=[],o=new Set,i=d=>{let l=n.get(d)??[];for(let m of l){let[g]=m.id;o.has(g)||(o.add(g),r.push(m),i(g))}};i(null);let a=[...e].filter(d=>{let[l]=d.id;return!o.has(l)}).sort((d,l)=>{let[m,g]=d.id,[y,N]=l.id,b=g===null||t.has(g),I=N===null||t.has(N);if(b&&!I)return-1;if(!b&&I)return 1;let T=(g??"").localeCompare(N??"");return T!==0?T:m.localeCompare(y)});return[...r,...a]},Do=(e,t)=>{let n=e.findIndex(r=>{try{return ua(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var Fo=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id)return r.payload.parent}return null};var Na=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[tt,en]=Na;var D=(e,t)=>s(`${t.split(".").join(" ")+" failed, "+e.toLowerCase()}`),ba={"init.workspace":({action:e,payload:t})=>{let{id:n,name:r}=t,o=ne.workspace(n,r);Qn(o);let i=C.createNodeAtPosition(o);return c(i)?D(i.message??"Failed to initialize workspace",e):u("Workspace initialized",{action:e,result:i.data})},"add.workspace":({action:e,payload:t})=>{let{id:n,name:r}=t,o=ne.workspace(n,r),i=C.createNodeAtPosition(o);return c(i)?D(i.message??"Failed to add workspace",e):u("Added workspace",{action:e,result:i.data})},"add.board":({action:e,payload:t})=>{let{id:n,name:r,parent:o}=t,i=C.createNodeAtPosition(ne.board(n,r,o));return c(i)?D(i.message??"Unable to create board",e):u("Added board",{action:e,result:i.data})},"add.swimlane":({action:e,payload:t})=>{let{id:n,name:r,parent:o}=t,i=C.createNodeAtPosition(ne.swimlane(n,r,o));return c(i)?D(i.message??"Unable to create swimlane",e):u("Added swimlane",{action:e,result:i.data})},"add.issue":({action:e,payload:t})=>{let{id:n,name:r,parent:o}=t,i=C.createNodeAtPosition(ne.ticket(n,r,o));return c(i)?D(i.message??"Unable to create issue",e):u("Added issue",{action:e,result:i.data})},"add.field":({action:e,payload:t})=>{let{id:n,name:r,parent:o,val:i}=t,a=C.createNodeAtPosition(ne.field(n,r,o,{value:i},r.includes("Description")?"vertical":"horizontal"));return c(a)?D(a.message??`Unable to create field: ${r}`,e):u("Added field",{action:e,result:a.data})},"edit.title":({action:e,payload:t})=>{let{id:n,name:r}=t;if(!C.getNode(n))return D("Unable to locate node",e);let i=C.renameNode(n,r);return c(i)?D(i.message??"Unable to edit title",e):u("Edited title",{action:e,result:i.data})},"delete.node":({action:e,payload:t})=>{let{id:n}=t,r=C.tombstoneNode(n);return c(r)?D(r.message??"Unable to delete node",e):u("Deleted node",{action:e,result:r.data})},"create.tag":({action:e,payload:t})=>{let{id:n,name:r}=t,o=C.createTag({id:n,name:r});return c(o)?D(o.message??"Unable to create tag",e):u("Tag added",{action:e,result:o.data})},"create.contributor":({action:e,payload:t})=>{let{id:n,name:r}=t,o=C.createContributor({id:n,name:r});return c(o)?D(o.message??"Unable to create contributor",e):u("Contributor created",{action:e,result:o.data})},"tag.issue":({action:e,payload:t})=>{let{id:n,target:r,tagId:o}=t,i=C.tag(r,o,n);return c(i)?D(i.message??"Unable to tag issue",e):u("Issue tagged",{action:e,result:i.data})},"untag.issue":({action:e,payload:t})=>{let{target:n,tagId:r}=t,o=C.untag(n,r);return c(o)?D(o.message??"Unable to untag ",e):u("Issue untagged",{action:e,result:o.data})},"assign.issue":({action:e,payload:t})=>{let{id:n,contributor:r,target:o}=t,i=C.assign(o,r,n);return c(i)?D(i.message??"Unable to assign issue",e):u("Assigned successfully",{action:e,result:i.data})},"unassign.issue":({action:e,payload:t})=>{let{target:n,contributor:r}=t,o=C.unassign(n,r);return c(o)?D(o.message??"Unable to unassign issue",e):u("Issue unassigned",{action:e,result:o.data})},"move.node":({action:e,payload:t})=>{let{id:n,parent:r,pos:o}=t,i=C.moveNode({id:n,parentId:r,position:o});return c(i)?D(i.message??"Failed to move node",e):u("Moved node",{action:e,result:i.data})},"edit.description":({action:e,payload:t})=>{let{id:n,md:r}=t,o=C.editValue(n,r);return c(o)?D(o.message??"Unable to edit description",e):u("Set node value",{action:e,result:o.data})},"close.issue":({action:e,payload:t})=>{let{id:n}=t,r=C.getNode(n);if(!r)return D("Unable to locate issue",e);if(!ye(r))return D("Can only close issues",e);let o=C.getNode(tt);if(!o)return D("Unable to locate target swimlane",e);if(o.id===r.parentNodeId)return D("Cannot close closed issue",e);let a=C.moveNode({id:n,parentId:o.id});return c(a)?D(a.message??"Unable to close issue",e):u("Issue closed",{action:e,result:a.data})},"reopen.issue":({action:e,payload:t})=>{let{id:n}=t,r=C.getNode(n);if(!r)return D("Unable to locate issue",e);if(!ye(r))return D("Can only reopen issues",e);let o=C.getNode(tt);if(!o)return D("Unable to locate closed swimlane",e);if(!(r.parentNodeId===o.id))return D("Issue is not closed",e);let a=Fo(r);if(!a)return D("Unable to resolve previous parent from issue history",e);if(a===o.id)return D("Previous parent resolves to closed swimlane",e);if(!C.getNode(a))return D("Previous parent no longer exists",e);let l=C.moveNode({id:n,parentId:a});return c(l)?D(l.message??"Unable to reopen issue",e):u("Issue reopened",{action:e,result:l.data})},"lock.node":({action:e,payload:t})=>{let{id:n}=t,r=C.lockNode(n);return c(r)?D(r.message??"Unable to lock node",e):u("Node locked",{action:e,result:r.data})}},Ia=(e,t)=>{let n=C.getNode(e);n&&C.updateNode({...n,log:[...n.log??[],t]})},Sa=e=>{switch(e.action){case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"delete.node":case"move.node":case"close.issue":case"reopen.issue":return[e.payload.id];case"edit.description":let t=[e.payload.id],n=v().nodes[e.payload.id]?.parentNodeId;return n&&t.push(n),t;case"tag.issue":case"untag.issue":case"assign.issue":case"unassign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function nt(e,t=!1){let n=ba[e.action](e);if(c(n))return n;t||([...new Set(Sa(e))].forEach(a=>Ia(a,e)),de(a=>({...a,eventLog:[...a.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?D("Invalid user ID format",e.action):(C.createContributor({name:o,id:r}),n)}var Ve=e=>e.map(t=>nt(t));function Q(e){let t=nt(e);if(t.result!==xe.Success)return t;let n=Jt({event:e});return c(n)?n:t}function ko(e){return e.map(t=>Q(t))}import bt from"node:fs";import{spawn as wa}from"node:child_process";import er from"node:fs";import rt from"node:path";var ht=(e,t)=>{let n=new Map,r=t??((...i)=>JSON.stringify(i)),o=((...i)=>{let a=r(...i);if(!n.has(a)){let d=e(...i).then(l=>(c(l)&&n.delete(a),l));n.set(a,d)}return n.get(a)});return o.clear=()=>n.clear(),o};import Et from"fs";import Bo from"path";import Ta from"util";var Oo=1e3,Uo=(e=process.cwd())=>Bo.join(et(e),Se(),"log","epiq.log");function Aa(e=process.cwd()){if(!Gt)return;let t=Uo(e);if(!Et.existsSync(t))return;let r=Et.readFileSync(t,"utf8").split(`
5
- `);if(r[r.length-1]===""&&r.pop(),r.length<=Oo)return;let o=r.slice(-Oo).join(`
6
- `)+`
7
- `;Et.writeFileSync(t,o,"utf8")}function Zn(e,t,n=!1,r=process.cwd()){if(!Gt)return;let o=Uo(r),i=Ta.format(...t),a=new Date,l=`[${n?a.toISOString().slice(11,19):a.toISOString()}] ${e} ${i}
8
- `;Et.mkdirSync(Bo.dirname(o),{recursive:!0}),Et.appendFileSync(o,l,"utf8"),Aa(r)}var w={info(...e){Zn("[Info]",e,!1)},debug(...e){Zn("->",e,!0)},error(...e){Zn("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=w;var Wo=15e3,Ra={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},$o=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!er.existsSync(t)){let g=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:g,exitCode:1});return}r(s(g));return}let o=wa("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Ra}),i=!1,a="",d="",l=g=>{i||(i=!0,clearTimeout(m),r(g))},m=setTimeout(()=>{o.kill("SIGTERM");let g=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${Wo}ms`].join(`
9
- `);l(n?{stdout:a,stderr:g,exitCode:124}:s(g))},Wo);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",g=>{a+=g}),o.stderr.on("data",g=>{d+=g}),o.on("error",g=>{if(n){l({stdout:a,stderr:g.message,exitCode:1});return}l(s([`git ${e.join(" ")}`,`cwd=${t}`,g.message].join(`
10
- `)))}),o.on("close",g=>{let y=g??1;if(n){l({stdout:a,stderr:d,exitCode:y});return}if(y!==0){l(s([`git ${e.join(" ")}`,d.trim()||a.trim()||"Git command failed"].filter(Boolean).join(`
11
- `)));return}l(u("Git command succeeded",{stdout:a,stderr:d,exitCode:y}))})}),F=({args:e,cwd:t})=>$o({args:e,cwd:t,allowFail:!1}),je=({args:e,cwd:t})=>$o({args:e,cwd:t,allowFail:!0}),tr=ht(async(e=process.cwd())=>{let t=await F({args:["rev-parse","--show-toplevel"],cwd:e});return c(t)?s("Not inside a Git repository"):u("Resolved repo root",t.data.stdout.trim())},e=>rt.resolve(e)),Ma=ht(async e=>{let t=await F({args:["rev-parse","--git-dir"],cwd:e});if(c(t))return s(t.message);let n=t.data.stdout.trim(),r=rt.isAbsolute(n)?n:rt.join(e,n);return u("Resolved git dir",r)},e=>rt.resolve(e)),nr=async({cwd:e,message:t})=>{let n=await F({args:["commit","-m",t],cwd:e});if(c(n))return s(`Failed to create commit
12
- ${n.message}`);let r=await F({args:["rev-parse","HEAD"],cwd:e});return c(r)?s(`Commit created, but failed to read HEAD SHA
13
- ${r.message}`):u("Created commit and resolved SHA",r.data.stdout.trim())},Ct=async e=>{let t=await Ma(e);if(c(t))return s(t.message);let n=t.data,o=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","REBASE_HEAD","rebase-merge","rebase-apply"].filter(i=>er.existsSync(rt.join(n,i)));return u("Checked for in-progress Git operation",o.length>0)},tn=async({repoRoot:e,remote:t})=>{let n=await je({args:["remote","get-url",t],cwd:e});return u("Checked remote",n.exitCode===0)},nn=async({repoRoot:e,remote:t,branch:n})=>{let r=await je({args:["ls-remote","--heads",t,n],cwd:e});return r.exitCode!==0?s(r.stderr.trim()||`Unable to inspect remote branch ${t}/${n}`):u("Checked remote branch",r.stdout.trim().length>0)},_o=async({repoRoot:e,branch:t})=>{let n=await je({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?u("Local branch exists",!0):n.exitCode===1?u("Local branch missing",!1):s(n.stderr.trim()||`Unable to inspect branch ${t}`)},Ho=e=>{try{return er.realpathSync.native(e)}catch{return rt.resolve(e)}},Ko=async({repoRoot:e,worktreeRoot:t})=>{let n=await F({args:["worktree","list","--porcelain"],cwd:e});if(c(n))return s(n.message);let r=Ho(t),o=n.data.stdout.split(`
14
- `).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(Ho).includes(r);return u("Checked worktree registration",o)},rr=async e=>{let t=await je({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return u("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},rn=async e=>{let t=await F({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return c(t)?s(t.message):u("Resolved current branch",t.data.stdout.trim())},Vo=async e=>{let t=await F({args:["rev-parse","--short","HEAD"],cwd:e});return c(t)?s(t.message):u("Resolved short HEAD sha",t.data.stdout.trim())},jo=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),on=async({cwd:e,remote:t,branch:n})=>{let r=await nn({repoRoot:e,remote:t,branch:n});if(c(r))return s(r.message);if(!r.data)return u("Remote branch missing, skipped pull",!1);w.debug("[git] fetch start",{cwd:e,remote:t,branch:n});let o=await F({args:["fetch",t,n],cwd:e});if(w.debug("[git] fetch done",o),c(o))return s(`Failed to fetch ${n}
15
- ${o.message}`);w.debug("[git] pull start",{cwd:e,remote:t,branch:n});let i=await F({args:["pull","--rebase",t,n],cwd:e});return w.debug("[git] pull done",i),c(i)?s(`Failed during pull --rebase
16
- ${i.message}`):u("Pulled with rebase",!0)},zo=async e=>{let t=await F({args:["status","--porcelain"],cwd:e});return c(t)?s(t.message):u("Checked remote worktree changes",t.data.stdout.trim().length>0)},Go=async e=>{let t=await rn(e);return c(t)?s(t.message):u("Checked detached HEAD state",t.data==="HEAD")};import{createHash as Oa}from"node:crypto";import ve from"node:fs";import Ba from"node:os";import ee from"node:path";import sn from"node:fs";import La from"node:path";import{decodeTime as Pa}from"ulid";var or=e=>{let[t,n]=e.id;return`${t}:${n??""}`},qo=e=>{let[t]=e.id;return Pa(t)},Da=e=>{let{userId:t,userName:n,...r}=e;return r},Fa=e=>e.length===0?"":e.map(t=>JSON.stringify(Da(t))).join(`
17
- `)+`
18
- `,ka=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(or(r),r);return[...n.values()].sort((r,o)=>{let i=qo(r)-qo(o);return i!==0?i:or(r).localeCompare(or(o))})},an=({sourceFile:e,targetFile:t})=>{let n=Zt(e);if(c(n))return s(n.message);let r=Zt(t);if(c(r))return s(r.message);let o=ka(r.data,n.data),i=Fa(o);return(sn.existsSync(t)?sn.readFileSync(t,"utf8"):"")===i?u("Event file already merged",!1):(sn.mkdirSync(La.dirname(t),{recursive:!0}),sn.writeFileSync(t,i,"utf8"),u("Merged event file",!0))};var k="epiq/events",Z="origin",ir=Se(),Jo="events",Ua="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Wa=e=>ee.join(ir,Jo,e),Ha=e=>Oa("sha1").update(ee.resolve(e)).digest("hex").slice(0,12),Xo=()=>ee.join(Ba.homedir(),".epiq"),Qo=()=>ee.join(Xo(),"worktrees"),sr=e=>ee.join(Qo(),Ha(e)),$a=e=>ee.join(e,ir),ot=e=>ee.join($a(e),Jo),Nt=({root:e,fileName:t})=>ee.join(ot(e),t),dn=e=>(w.debug("[sync] ensure dir",e),ve.mkdirSync(e,{recursive:!0}),u("Ensured directory",void 0)),_a=()=>{w.debug("[sync] ensure epiq storage");let e=dn(Xo());if(c(e))return s(e.message);let t=dn(Qo());return c(t)?s(t.message):u("Ensured epiq storage",void 0)},Ka=e=>{ve.existsSync(e)&&(w.debug("[sync] remove path",e),ve.rmSync(e,{recursive:!0,force:!0}))},Va=e=>{let t=ot(e);if(!ve.existsSync(t))return w.debug("[sync] events dir missing",t),u("Events dir missing",[]);let n=ve.readdirSync(t,{withFileTypes:!0}).filter(r=>r.isFile()).map(r=>r.name).filter(r=>r.endsWith(".jsonl")).sort();return w.debug("[sync] listed event files",{eventsDir:t,count:n.length}),u("Listed event files",n)},ja=async e=>{w.debug("[sync] inspect local HEAD",e);let t=await je({args:["rev-parse","--verify","HEAD"],cwd:e});return t.exitCode===0?u("Repo has HEAD",!0):t.exitCode===1?u("Repo has no HEAD",!1):s(t.stderr.trim()||"Unable to inspect HEAD")},za=ht(async e=>{w.debug("[sync] inspect remote history",{repoRoot:e,remote:Z});let t=await tn({repoRoot:e,remote:Z});if(c(t))return s(t.message);if(!t.data)return u("No remote configured",!1);let n=await je({args:["ls-remote","--heads",Z],cwd:e});if(n.exitCode!==0)return s(n.stderr.trim()||"Unable to inspect remote heads");let r=n.stdout.trim().length>0;return w.debug("[sync] remote history",r),u("Checked remote history",r)},e=>ee.resolve(e)),ar=async e=>{w.debug("[sync] ensure initial commit");let t=await ja(e);if(c(t))return s(t.message);if(t.data)return w.debug("[sync] local HEAD exists"),u("Repo already initialized",!1);let n=await za(e);if(c(n))return s(n.message);if(n.data)return w.debug("[sync] skip local init commit due to remote history"),u("Skipped local init commit because remote history exists",!1);w.debug("[sync] create empty init commit");let r=await F({args:["commit","--allow-empty","-m","[epiq:init]"],cwd:e});return c(r)?s(`Failed to create initial commit
19
- ${r.message}`):u("Created initial commit",!0)},dr=({repoRoot:e,worktreeRoot:t})=>{let n=Va(t);if(c(n))return s(n.message);let r=ot(t),o=ot(e),i=!1;for(let a of n.data){let d=ee.join(r,a),l=ee.join(o,a);w.debug("[sync] hydrate event file",{from:d,to:l});let m=an({sourceFile:d,targetFile:l});if(c(m))return s(m.message);i=i||m.data}return w.debug("[sync] hydrate changed",i),u("Hydrated event files from remote worktree",i)},Yo=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Ga=async e=>{let t=await rn(e);if(c(t))return s(t.message);let n=await Vo(e);if(c(n))return s(n.message);let r=`[epiq:sync:${Yo(t.data)}:${Yo(n.data)}]`;return w.debug("[sync] commit message",r),u("Built sync commit message",r)},qa=async e=>{w.debug("[sync] create empty storage branch",k);let t=await F({args:["commit-tree",Ua,"-m","[epiq:init-storage-branch]"],cwd:e});if(c(t))return s(`Failed to create storage branch commit
20
- ${t.message}`);let n=t.data.stdout.trim(),r=await F({args:["update-ref",`refs/heads/${k}`,n],cwd:e});return c(r)?s(`Failed to create ${k}
21
- ${r.message}`):u("Created empty storage branch",!0)},Ya=async({repoRoot:e})=>{w.debug("[sync] ensure local remote branch",k);let t=await _o({repoRoot:e,branch:k});if(c(t))return s(t.message);if(t.data)return w.debug("[sync] local remote branch exists"),u("Local remote branch already exists",!1);let n=await tn({repoRoot:e,remote:Z});if(c(n))return s(n.message);if(n.data){let r=await nn({repoRoot:e,remote:Z,branch:k});if(c(r))return s(r.message);if(r.data){w.debug("[sync] fetch remote branch before local track");let o=await F({args:["fetch",Z,k],cwd:e});if(c(o))return s(`Failed to fetch ${k} from remote
22
- ${o.message}`);w.debug("[sync] create local tracking branch",k);let i=await F({args:["branch","--track",k,`${Z}/${k}`],cwd:e});return c(i)?s(`Failed to create local ${k} from remote
23
- ${i.message}`):u("Created local remote branch from remote",!0)}}return qa(e)},Ja=async({repoRoot:e,branch:t})=>{let n=await F({args:["worktree","list","--porcelain"],cwd:e});if(c(n))return s(n.message);let r=n.data.stdout.split(`
24
- `),o=null;for(let i of r){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return u("Found worktree for branch",o)}return u("No worktree found for branch",null)},Xa=async({repoRoot:e,worktreeRoot:t})=>{w.debug("[sync] create remote worktree",t);let n=dn(ee.dirname(t));if(c(n))return s(n.message);ve.existsSync(t)&&!ve.existsSync(ee.join(t,".git"))&&(w.debug("[sync] remove broken remote worktree path",t),Ka(t));let r=await F({args:["worktree","add",t,k],cwd:e});return c(r)?s(`Failed to create remote worktree
25
- ${r.message}`):u("Created remote worktree",!0)},Qa=async({repoRoot:e,worktreeRoot:t})=>{w.debug("[sync] ensure remote worktree",t);let n=await Ja({repoRoot:e,branch:k});if(c(n))return s(n.message);let r=n.data,o=ee.resolve(t),i=r?ee.resolve(r):null;if(i&&i===o&&ve.existsSync(i))return w.debug("[sync] reuse existing remote branch worktree",{expected:o,actual:i}),u("Remote branch already checked out in expected worktree",!1);if(i&&i!==o){w.debug("[sync] remove old remote branch worktree",{expected:o,actual:i});let l=await F({args:["worktree","remove","--force",i],cwd:e});if(c(l))return s(`Failed to remove existing remote worktree
26
- ${l.message}`)}if(i&&!ve.existsSync(i)){w.debug("[sync] prune stale branch worktree registration",{existingBranchWorktree:i});let l=await F({args:["worktree","prune"],cwd:e});if(c(l))return s(`Failed to prune stale worktrees
27
- ${l.message}`)}let a=await Ko({repoRoot:e,worktreeRoot:t});if(c(a))return s(a.message);let d=ve.existsSync(t);if(a.data&&d)return w.debug("[sync] remote worktree exists"),u("Remote worktree already exists",!1);if(a.data&&!d){w.debug("[sync] prune stale remote worktree registration");let l=await F({args:["worktree","prune"],cwd:e});if(c(l))return s(`Failed to prune stale worktrees
28
- ${l.message}`)}return Xa({repoRoot:e,worktreeRoot:t})},Za=async e=>{let t=await rn(e);if(c(t))return s(t.message);if(t.data===k)return w.debug("[sync] remote branch already checked out"),u("Remote branch already checked out",!1);w.debug("[sync] checkout remote branch",k);let n=await F({args:["checkout",k],cwd:e});return c(n)?s(`Failed to checkout ${k}
29
- ${n.message}`):u("Checked out remote branch",!0)},ed=async e=>{let t=await F({args:["ls-tree","--name-only","HEAD"],cwd:e});if(c(t))return s(t.message);let r=t.data.stdout.trim().split(`
30
- `).filter(Boolean).filter(a=>a!==ir);if(r.length===0)return u("Remote branch is storage-only",!1);w.debug("[sync] remove app files from storage branch",r);let o=await F({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(c(o))return s(`Failed to clean storage branch
31
- ${o.message}`);let i=await nr({cwd:e,message:"[epiq:repair-storage-branch]"});return c(i)?s(i.message):u("Cleaned storage branch",!0)},td=async e=>{w.debug("[sync] ensure remote upstream",k);let t=await rr(e);if(c(t))return s(t.message);if(t.data)return w.debug("[sync] remote upstream already configured"),u("Remote upstream already configured",!1);let n=await tn({repoRoot:e,remote:Z});if(c(n))return s(n.message);if(!n.data)return w.debug("[sync] no remote configured for upstream"),u("No remote available for upstream",!1);let r=await nn({repoRoot:e,remote:Z,branch:k});if(c(r))return s(r.message);if(!r.data)return w.debug("[sync] remote branch missing; upstream will be configured on first push"),u("Deferred upstream until first push",!1);w.debug("[sync] fetch remote branch before upstream set");let o=await F({args:["fetch",Z,k],cwd:e});if(c(o))return s(`Failed to fetch ${k}
32
- ${o.message}`);w.debug("[sync] set upstream to remote branch");let i=await F({args:["branch","--set-upstream-to",`${Z}/${k}`,k],cwd:e});return c(i)?s(`Failed to set remote upstream
33
- ${i.message}`):u("Configured remote upstream",!0)},Zo=async({worktreeRoot:e,ownEventFileName:t})=>{w.debug("[sync] stage own event file in remote worktree",t);let n=await F({args:["add",Wa(t)],cwd:e});return c(n)?s(`Failed to stage remote own event file
34
- ${n.message}`):u("Staged remote own event file",void 0)},ei=async({repoRoot:e,worktreeRoot:t})=>{let n=await Ga(e);return c(n)?s(n.message):(w.debug("[sync] create remote sync commit"),nr({cwd:t,message:n.data}))},cr=async e=>{w.debug("[sync] push remote worktree");let t=await rr(e);if(c(t))return s(t.message);let n=await F({args:t.data?["push"]:["push","-u",Z,k],cwd:e});return w.debug("[sync] push result",n),c(n)?s(`Failed during remote push
35
- ${n.message}`):u("Pushed remote",!0)},lr=async({repoRoot:e,worktreeRoot:t,ensureUpstream:n})=>{w.debug("[sync] bootstrap remote storage",{repoRoot:e,worktreeRoot:t,ensureUpstream:n});let r=!1,o=[_a(),await Ya({repoRoot:e}),await Qa({repoRoot:e,worktreeRoot:t}),await Za(t),await ed(t),n?await td(t):u("Skipped remote upstream bootstrap",!1)];for(let i of o){if(c(i))return s(i.message);r=r||!!i.data}return w.debug("[sync] bootstrap changed",r),u(n?"Bootstrapped remote storage":"Bootstrapped remote storage (readonly)",r)},ur=(e,t)=>{for(let n of[ot(e),ot(t)]){let r=dn(n);if(c(r))return s(r.message)}return u("Ensured remote layout",void 0)};var ri=async(e=process.cwd())=>{logger.debug("[sync] start readonly sync",{cwd:e});let t=await tr(e);if(c(t))return s(t.message);let n=t.data,r=sr(n);logger.debug("[sync] resolved readonly roots",{repoRoot:n,worktreeRoot:r});let o=await Ct(n);if(c(o))return s(o.message);if(o.data)return s("Cannot sync while a git operation is in progress in the current repo");let i=await ar(n);if(c(i))return s(i.message);logger.debug("[sync] readonly ensure initial commit changed",i.data);let a=await lr({repoRoot:n,worktreeRoot:r,ensureUpstream:!1});if(c(a))return s(a.message);let d=await Ct(r);if(c(d))return s(d.message);if(d.data)return s("Cannot sync while a git operation is in progress in the remote worktree");let l=ur(n,r);if(c(l))return s(l.message);logger.debug("[sync] readonly pull remote branch");let m=await on({cwd:r,remote:Z,branch:k});if(c(m))return s(m.message);logger.debug("[sync] readonly pulled remote",m.data);let g=dr({repoRoot:n,worktreeRoot:r});return c(g)?s(g.message):(logger.debug("[sync] readonly hydrated from remote",g.data),u("Synced from remote",{repoRoot:n,worktreeRoot:r}))},nd=({repoRoot:e,worktreeRoot:t,ownEventFileName:n})=>{let r=Nt({root:e,fileName:n}),o=Nt({root:t,fileName:n});return bt.existsSync(r)?(logger.debug("[sync] merge own event file to remote",{ownEventFileName:n,localFile:r,remoteFile:o}),an({sourceFile:r,targetFile:o})):(logger.debug("[sync] local own event file missing",r),u("Local own event file missing, nothing to merge",!1))},ti=async({repoRoot:e,worktreeRoot:t,ownEventFileName:n})=>{let r=nd({repoRoot:e,worktreeRoot:t,ownEventFileName:n});if(c(r))return s(r.message);let o=await zo(t);if(c(o))return s(o.message);if(!r.data&&!o.data)return u("Own event file already up to date in remote worktree",{createdCommit:!1});let i=await Zo({worktreeRoot:t,ownEventFileName:n});if(c(i))return s(i.message);let a=await ei({repoRoot:e,worktreeRoot:t});return c(a)?s(a.message):u("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:a.data})},ni=({repoRoot:e,worktreeRoot:t,ownEventFileName:n})=>{let r=Nt({root:e,fileName:n}),o=Nt({root:t,fileName:n});logger.debug("[sync] own event file sizes",{local:bt.existsSync(r)?bt.statSync(r).size:0,remote:bt.existsSync(o)?bt.statSync(o).size:0})},oi=async({cwd:e=process.cwd(),ownEventFileName:t})=>{logger.debug("[sync] start write sync",{cwd:e,ownEventFileName:t});let n=await tr(e);if(c(n))return s(n.message);let r=n.data,o=sr(r);logger.debug("[sync] resolved roots",{repoRoot:r,worktreeRoot:o});let i=await ar(r);if(c(i))return s(`Failed to ensure initial commit: ${i.message}`);logger.debug("[sync] ensure initial commit changed",i.data);let a=await Go(r);if(c(a))return s(a.message);if(a.data)return s("Cannot run :sync while the repository is in detached HEAD state");if(t.includes("/")||t.includes("\\"))return s("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return s("Own event file must end with .jsonl");let d=await Ct(r);if(c(d))return s(d.message);if(d.data)return s("Cannot run :sync while a merge, rebase, cherry-pick, or revert is in progress in the current repo");let l=await lr({repoRoot:r,worktreeRoot:o,ensureUpstream:!0});if(c(l))return s(l.message);let m=await Ct(o);if(c(m))return s(m.message);if(m.data)return s("Cannot run :sync while a merge, rebase, cherry-pick, or revert is in progress in the remote worktree");let g=ur(r,o);if(c(g))return s(g.message);let y=!1,N,b=!1,I=!1,T=!1;logger.debug("[sync] pull remote branch before local copy");let S=await on({cwd:o,remote:Z,branch:k});if(c(S))return s(S.message);b=S.data,logger.debug("[sync] pulled remote",b);let R=dr({repoRoot:r,worktreeRoot:o});if(c(R))return s(R.message);T=R.data,logger.debug("[sync] hydrated from remote",T);let B=await ti({repoRoot:r,worktreeRoot:o,ownEventFileName:t});if(c(B))return s(B.message);if(y=B.data.createdCommit,N=B.data.commitSha,ni({repoRoot:r,worktreeRoot:o,ownEventFileName:t}),logger.debug("[sync] sync own file result",B.data),y||l.data){let G=await cr(o),ie=G;if(c(G)&&jo(G.message)){let Lt=await on({cwd:o,remote:Z,branch:k});if(c(Lt))return s(Lt.message);let De=await ti({repoRoot:r,worktreeRoot:o,ownEventFileName:t});if(c(De))return s(De.message);De.data.createdCommit&&(y=!0,N=De.data.commitSha),ni({repoRoot:r,worktreeRoot:o,ownEventFileName:t}),logger.debug("[sync] retry sync own file result",De.data),ie=await cr(o)}if(c(ie))return s(ie.message);I=ie.data,logger.debug("[sync] pushed remote",I)}else logger.debug("[sync] no commit created, skipped push");if(y){let G=await F({args:["rev-parse","HEAD"],cwd:o});if(c(G))return s(G.message);N=G.data.stdout.trim()}return u("Synced event logs with remote",{repoRoot:r,worktreeRoot:o,createdCommit:y,commitSha:N,pulled:b,pushed:I,hydrated:T,bootstrapped:l.data})};import{ulid as ii}from"ulid";var it=null,Ue=()=>structuredClone(it),st=e=>it=e,si=()=>{let{currentNode:e,selectedIndex:t}=v(),r=M(e.id)[t];return r?u("Resolved selected child",r):s("Target node not found")};function mr(e){let t=si();if(c(t))return t;let{currentNode:n,nodes:r}=v();if(!n.parentNodeId)return s("Missing parent node id");let o=r[n.parentNodeId];if(!o)return s("Missing parent node");let i=W(o.id),a=i.findIndex(({id:N})=>N===n.id);if(a<0)return s("Current node not found among siblings");let d=i[a+e];if(!d)return s("Missing sibling node");let l=X();if(c(l))return s("Unable to resolve user ID");let{userId:m,userName:g}=l.data;if(st({id:ii(),userId:m,userName:g,action:"move.node",payload:{id:t.data.id,parent:d.id,pos:{at:"end"}}}),!it)return s("Could not materialize move state");let y=nt(it,!0);return c(y)?y:u("Node moved successfully",y.data)}function pr(e){let t=si();if(c(t))return t;let{currentNode:n,selectedIndex:r}=v(),i=W(n.id)[r+e];if(!i)return s("Missing sibling node");let a=X();if(c(a))return s("Unable to resolve user ID");let{userId:d,userName:l}=a.data;if(st({id:ii(),userId:d,userName:l,action:"move.node",payload:{id:t.data.id,parent:n.id,pos:{at:e===1?"after":"before",sibling:i.id}}}),!it)return s("Could not materialize move state");let m=nt(it,!0);return c(m)?m:u("Node moved successfully",m.data)}import rd from"node:os";import ai from"node:path";import{z as It}from"zod";var od={userId:"",userName:"",preferredEditor:"",autoSync:!1},di=It.object({preferredEditor:It.string().optional(),userName:It.string().optional(),userId:It.string().optional(),autoSync:It.boolean().optional()}).strict(),id=".epiq",sd="config.json",ci=()=>ai.join(rd.homedir(),id),gr=()=>ai.join(ci(),sd),fr=()=>{try{return le.mkDir(ci()),u("Ensured ~/.epiq exists",null)}catch{return s("Unable to create ~/.epiq")}},ad=e=>{let t;try{t=JSON.parse(e)}catch{return s("Invalid ~/.epiq/config.json JSON")}let n=di.safeParse(t??{});return n.success?u("Parsed config",n.data):s(`Invalid ~/.epiq/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},li=()=>{let e=fr();if(c(e))return s(e.message);let t=gr(),n=le.readFile(t);return n==null||n.trim()===""?u("No config found, using empty config",{autoSync:!1,preferredEditor:"",userId:"",userName:""}):ad(n)},ui=e=>{let t=fr();if(c(t))return s(t.message);let n=di.safeParse(e);if(!n.success)return s(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=gr();try{return le.writeToFile(r,JSON.stringify(n.data,null,2)+`
36
- `),u("Config written",null)}catch{return s("Unable to write ~/.epiq/config.json")}},cn=e=>{let t=li();if(c(t))return s("Failed to read existing config");let n={...t.data,...e};return ui(n)},mi=()=>{let e=gr(),t=fr();if(c(t))return s("Unable to create ~/.epiq");if(!(le.readFile(e)!==null)){let l=ui(od);if(c(l))throw new Error("Unable to create ~/.epiq/config.json")}let r=li();if(c(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:a,autoSync:d}=r.data;return!i||!a?s("User name or ID not configured in ~/.epiq/config.json"):u("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:a,autoSync:d??!1})};var pi=e=>Object.values(v().tags).find(t=>t.name===e),gi=e=>Object.values(v().contributors).find(t=>t.name===e),fi=[{systemOnly:!0,intent:L.Move,mode:f.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{modifier:t}=re().commandMeta,n=()=>{let d=Ue();if(!d)return s("No pending move state");let l=d.payload.id;if(!v().nodes[l])return s("Moved node not found");let g=d.payload.parent,y=v().nodes[g];if(!y)return s("Move parent not found");let N=M(g).findIndex(b=>b.id===l);return N===-1?s("Moved node not found among rendered children"):(U.navigate({currentNode:y,selectedIndex:N}),u("Synchronized navigation to moved node",null))},r=d=>{if(c(d))return s(d.message);let l=n();return c(l)?s(l.message):u("Updated move preview",null)},{currentNode:o,selectedIndex:i}=v(),a=M(o.id)[i];if(!a)return A({mode:f.DEFAULT}),s("No move target");if(t==="start"){if(a.readonly)return s("Target node is read-only");if(i===-1)return s("No item selected");if(!a.parentNodeId)return s("Target has no parent");let d=M(a.parentNodeId),l=d.findIndex(({id:b})=>b===a.id);if(l===-1)return s("Target not found among siblings");let m=d[l-1],g=d[l+1],y=g!=null?{at:"before",sibling:g.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"};st({id:$(),action:"move.node",payload:{id:a.id,parent:a.parentNodeId,pos:y},...e.data}),A({mode:f.MOVE});let N=n();return c(N)?s(N.message):u("Move initialized",null)}if(t==="next")return A({mode:f.MOVE}),r(pr(1));if(t==="previous")return A({mode:f.MOVE}),r(pr(-1));if(t==="to-next")return A({mode:f.MOVE}),r(mr(1));if(t==="to-previous")return A({mode:f.MOVE}),r(mr(-1));if(t==="confirm"){A({mode:f.DEFAULT});let d=Ue();if(!d)return s("No pending move to confirm");let l=Q(d);if(c(l))return l;let m=n();return c(m)?s(m.message):(st(null),u("Moved item",null))}return t==="cancel"?(st(null),A({mode:f.DEFAULT}),u("Cancelling move",null)):s("Invalid move modifier")}},{intent:L.Delete,mode:f.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=M(t.id)[n];return r?Q({id:$(),action:"delete.node",payload:{id:r.id},...e.data}):s("Unable to resolve child to delete")},onSuccess:()=>A({mode:f.DEFAULT})},{intent:L.Edit,mode:f.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let t=be(v().breadCrumb,"TICKET");if(c(t))return s("Edit target must be an issue");let n=t.data;if(n.readonly)return s("Cannot edit readonly field");let{currentNode:r,selectedIndex:o}=v();if(!M(n.id)[o])return s("No selected field");let a=M(r.id)[o];if(!a)return s("No selected field");if(a.readonly)return s("Cannot edit readonly field");let d=a.props.value;if(typeof d!="string")return s("Selected field is not editable text");let l=So(d);if(c(l))return s("Failed to edit field");let m=l.data;return m===d?u("No changes made",null):a.title==="Description"?Q({id:$(),action:"edit.description",payload:{id:a.id,md:m},...e.data}):a.title==="Title"?Q({id:$(),action:"edit.title",payload:{id:a.id,name:m},...e.data}):s(`Editing not supported for "${a.title}"`)},onSuccess:()=>A({mode:f.DEFAULT})},{intent:L.Filter,mode:f.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=re().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(d=>z(p.FILTER).map(l=>l.split(n)[0]).includes(d))(r))return s("Invalid filter modifier");let a={target:r,operator:"=",value:t.trim()};return de(d=>({...d,filters:e==="clear"?[]:[...d.filters,a],mode:f.DEFAULT})),u("Viewing help",null)}},{intent:L.ViewHelp,mode:f.COMMAND_LINE,action:()=>(A({mode:f.HELP}),u("Viewing help",null))},{intent:L.CloseIssue,mode:f.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=M(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!r.parentNodeId)return s("No target parent found");if(!ye(r))return s("Cannot close in this context");let o=Q({id:$(),action:"close.issue",payload:{id:r.id,parent:r.parentNodeId},...e.data});return c(o)?o:u("Viewing help",null)}},{intent:L.ReopenIssue,mode:f.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=M(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?u("Resolved ticket",r):ke(r.id,"TICKET");if(c(o))return s("Cannot reopen in this context");let i=o.data,a=Q({id:$(),action:"reopen.issue",payload:{id:i.id},...e.data});return c(a)?a:u("Issue reopened",null)},onSuccess:()=>A({mode:f.DEFAULT})},{intent:L.SetUserName,mode:f.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:n}=pe(),r=Kt()?.trim();if(!r)return s("No username provided");let o=r??n,i=e??$();if(!o||!i)return s("Unable to resolve user name or id");let a=cn({userName:o,userId:i,preferredEditor:t??""});return c(a)?a:(Ye({userName:o,userId:i}),A({mode:f.DEFAULT}),u(`Username set to "${r}"`,null))}},{intent:L.Init,mode:f.COMMAND_LINE,action:()=>{let e=xr();if(c(e))return e;let{rootNodeId:t,nodes:n}=v();return U.navigate({currentNode:n[t],selectedIndex:0}),A({mode:f.DEFAULT}),u("Project initialized",null)}},{intent:L.SetEditor,mode:f.COMMAND_LINE,action:()=>{let e=Kt()?.trim();if(!e)return s("No editor provided");let t=cn({preferredEditor:e});return c(t)?t:(Ye({preferredEditor:e}),A({mode:f.DEFAULT}),u(`Editor configuration set to "${e}"`,null))}},{intent:L.SetAutoSync,mode:f.COMMAND_LINE,action:()=>{let e=re().commandMeta.modifier;if(e!=="true"&&e!=="false")return s("Invalid response");let t=e.toLowerCase()==="true",n=cn({autoSync:t});return c(n)?n:(Ye({autoSync:t}),A({mode:f.DEFAULT}),u(`Auto synchronization set to "${t}"`,null))}},{intent:L.NewItem,mode:f.COMMAND_LINE,action:(e,t)=>{let n=X();if(c(n))return s("Unable to resolve user ID");if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:r,currentNode:o,selectedIndex:i}=v(),a=d=>{let l=Q(d);if(c(l))return l;let m=C.getNode(l.data.result.id);if(!m)return s("Created node not found");if(!m.parentNodeId)return l;let g=C.getNode(m.parentNodeId);return g?(U.navigate({currentNode:g,selectedIndex:C.getSiblings(m.parentNodeId).findIndex(({id:y})=>y===m.id)}),l):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:d}=v(),l=C.getNode(d);return l?a({id:$(),action:"add.board",payload:{id:$(),name:t.inputString,parent:l.id},...n.data}):s("Workspace not found")}if(t.modifier==="swimlane"){let d=be(r,"BOARD");return c(d)?s("Unable to add swimlane in this context"):a({id:$(),action:"add.swimlane",payload:{id:$(),name:t.inputString,parent:d.data.id},...n.data})}if(t.modifier==="issue"){let d=M(o.id)[i],l=o.context==="SWIMLANE"?o:o.context==="BOARD"&&d?.context==="SWIMLANE"?d:(()=>{let b=be(r,"SWIMLANE");return c(b)?null:b.data})();if(!l)return s("Unable to add issue in this context");let m=To({name:t.inputString,parent:l.id,user:n.data}),g=ko(m);if(g.some(b=>c(b)))return s("Issue create failed: "+g.filter(c).map(b=>b.message).filter(Boolean).join(", "));let y=g[0];if(!y||c(y))return s("Issue creation failed");let N=m[0]?.payload.id;return N?(U.navigate({currentNode:l,selectedIndex:C.getSiblings(l.id).findIndex(({id:b})=>b===N)}),u("Issue created",null)):s("Unable to determine ticket id")}return Wr()},onSuccess:()=>A({mode:f.DEFAULT})},{intent:L.SetView,mode:f.COMMAND_LINE,action:()=>{let{commandMeta:e}=re();return e.validity===Ne.Invalid?s("Invalid command "+xe):(de(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),u("View set",null))},onSuccess:()=>A({mode:f.DEFAULT})},{intent:L.Rename,mode:f.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=M(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=Kt();return o?Q({id:$(),action:"edit.title",payload:{id:r.id,name:o},...e.data}):s("Provide a new name")},onSuccess:()=>A({mode:f.DEFAULT})},{intent:L.UntagTicket,mode:f.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=re().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=pi(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid untag target");let a=ke(i.id,"TICKET");if(c(a))return s("Unable to untag issue in this context");let d=a.data,l=C.getFieldByTitle(d.id,"Tags");if(!l)return s("Unable to locate tags field");let m=M(l.id).find(g=>g.props?.value===o.id);return m?Q({id:$(),action:"untag.issue",payload:{id:m.id,target:d.id,tagId:o.id},...e.data}):s("Issue is not tagged with that tag")},onSuccess:()=>A({mode:f.DEFAULT})},{intent:L.TagTicket,mode:f.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=re().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=v(),a=M(i.id)[o];if(!a)return s("Invalid tag target");let d=ke(a.id,"TICKET");if(c(d))return s("Unable to tag issue in this context");let l=d.data,m=pi(r),g;if(m)g=m.id;else{let b=$(),I=Q({id:$(),action:"create.tag",payload:{id:b,name:r},userId:e.data.userId,userName:e.data.userName});if(c(I))return I;g=I.data.result.id}let y=C.getFieldByTitle(l.id,"Tags");return y?M(y.id).some(b=>b.props?.value===g)?s("Already tagged with that tag"):Q({id:$(),action:"tag.issue",payload:{id:$(),target:l.id,tagId:g},...e.data}):s("Unable to locate tags field")},onSuccess:()=>A({mode:f.DEFAULT})},{intent:L.AssignUserToTicket,mode:f.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=re().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=v(),a=M(i.id)[o];if(!a)return s("Invalid assign target");let d=ke(a.id,"TICKET");if(c(d))return s("Unable to assign issue in this context");let l=d.data,m=gi(r),g;if(m)g=m.id;else{let b=$(),I=Q({id:$(),action:"create.contributor",payload:{id:b,name:r},userId:e.data.userId,userName:e.data.userName});if(c(I))return I;g=I.data.result.id}let y=C.getFieldByTitle(l.id,"Assignees");return y?M(y.id).some(b=>b.props?.value===g)?s("Assignee already assigned"):Q({id:$(),action:"assign.issue",payload:{id:$(),target:l.id,contributor:g},...e.data}):s("Unable to locate assignees field")},onSuccess:()=>A({mode:f.DEFAULT})},{intent:L.UnassignUserFromTicket,mode:f.COMMAND_LINE,action:()=>{let e=X();if(c(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=re().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=gi(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid unassign target");let a=ke(i.id,"TICKET");if(c(a))return s("Unable to unassign in this context");let d=a.data,l=C.getFieldByTitle(d.id,"Assignees");if(!l)return s("Unable to locate assignees field");let m=M(l.id).find(g=>g.props?.value===o.id);return m?Q({id:$(),action:"unassign.issue",payload:{id:m.id,target:d.id,contributor:o.id},...e.data}):s(`Issue is not assigned to "${r}"`)},onSuccess:()=>A({mode:f.DEFAULT})},{intent:L.Sync,mode:f.COMMAND_LINE,action:async()=>{j(()=>""),A({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:e,userName:t}=pe();if(!e)return s("Unable to resolve userId");if(!t)return s("Unable to resolve userName");let n=Ke()?xr():u("No pending default events",null);if(c(n))return s(`Unable to persist default events. ${n.message}`);let r=X();if(c(r)||!r.data)return s("Unable to resolve event log path");let o=Jn(r.data);logger.debug("[sync-command] pending defaults",Ke());let i=await oi({ownEventFileName:o});if(c(i))return A({syncStatus:{msg:i.message,status:"outOfSync"}}),s(`Unable to sync state. ${i.message}`);A({syncStatus:{msg:"Synced",status:"synced"},mode:f.DEFAULT});let a=vt();return c(a)?s("Unable to load events"):(Ve(a.data),u("Synced",!0))}},{intent:L.Peek,mode:f.COMMAND_LINE,action:async()=>{let e=be(v().breadCrumb,"BOARD");if(c(e))return e;let t=vt();if(c(t))return s(t.message);let n=t.data,{modifier:r}=re().commandMeta,o;if(r==="now"){let y=yr();if(c(y))return y;let N=Ve(n);return N.some(c)?s(N.map(b=>b.message).join(", ")):(A({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),u("Peeking now",!0))}if(r==="prev"){let y=v().eventLog.at(-2),N=Wn(y);if(N===null)return s("No previous event to peek");o=N}else if(r==="next"){let y=v().unappliedEvents.at(0),N=Wn(y);if(N===null)return s("No next event to peek");o=N}else{let y=Ht(r);if(!y)return s("Invalid peek date");o=y.getTime()}let i=e.data.id,{appliedEvents:a,unappliedEvents:d}=Do(n,o),l=yr();if(c(l))return l;let m=Ve(a);if(m.some(c))return s(m.map(y=>y.message).join(", "));let g=v().nodes[i];return g?(U.navigate({currentNode:g,selectedIndex:0}),A({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:d}),u("Peeking ",!0)):s("Board did not exist at peek date")}}];var dd=new Set(["peek","filter","view-help"]),ue=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=re();if(!t)return s("No command to confirm");if(!e&&n===Ne.Invalid)return s("Invalid command");let i=Eo(t);if(go(),v().readOnly&&!dd.has(i))return yt({result:xe.Fail,message:"Command not available in readonly state",data:null});let a=fi.filter(l=>e||l.systemOnly!==!0).find(l=>l.intent===i);if(!a)return yt({result:xe.Fail,message:"Command not found",data:null});let d=await a.action(a,{command:t,inputString:o,modifier:r});return c(d)?yt(d):(fo({addToHistory:!e}),a.onSuccess?.(),yt(d))};var ln=[{intent:x.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(A({mode:f.COMMAND_LINE}),j(()=>"move cancel"),ue({isForceExecutedBySystem:!0}))},{intent:x.InitMove,mode:f.DEFAULT,description:"[m] move init/confirm",action:()=>(A({mode:f.COMMAND_LINE}),j(()=>"move start"),ue({isForceExecutedBySystem:!0}))},{intent:x.ConfirmMove,mode:f.MOVE,action:()=>(A({mode:f.COMMAND_LINE}),j(()=>"move confirm"),ue({isForceExecutedBySystem:!0}))}],un=[{intent:x.MovePreviousItem,mode:f.MOVE,action:()=>Ue()?(A({mode:f.COMMAND_LINE}),j(()=>"move previous"),ue({isForceExecutedBySystem:!0})):s("No pending move")},{intent:x.MoveNextItem,mode:f.MOVE,action:()=>Ue()?(A({mode:f.COMMAND_LINE}),j(()=>"move next"),ue({isForceExecutedBySystem:!0})):s("No pending move")}],yi=[{intent:x.MoveToNextContainer,mode:f.MOVE,action:()=>Ue()?(A({mode:f.COMMAND_LINE}),j(()=>"move to-next"),ue({isForceExecutedBySystem:!0})):s("No pending move")},{intent:x.MoveToPreviousContainer,mode:f.MOVE,action:()=>Ue()?(A({mode:f.COMMAND_LINE}),j(()=>"move to-previous"),ue({isForceExecutedBySystem:!0})):s("No pending move")}];var xi={[P.WORKSPACE]:[...ln,...un],[P.BOARD]:[...ln,...un],[P.SWIMLANE]:[...ln,...un,...yi],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var vi=[{intent:x.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(A({mode:f.COMMAND_LINE}),j(()=>`${p.NEW} `),u("Adding new item",null))},{intent:x.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(A({mode:f.COMMAND_LINE}),j(()=>`${p.DELETE} `),u("Deleting item",null))},{intent:x.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(A({mode:f.COMMAND_LINE}),j(()=>""),u("Entering command line mode",null))},{intent:x.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(U.enterChildNode(),u("Entering context",null))},{intent:x.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(U.enterParentNode(),u("Exiting context",null))},{intent:x.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:x.NavNextItem,mode:f.DEFAULT,action:()=>(U.navigateToNextItem(),u("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(U.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:f.DEFAULT,action:()=>(U.navigateToNextContainer(),u("Navigating to next container",null))},{intent:x.Edit,mode:f.DEFAULT,action:()=>(A({mode:f.COMMAND_LINE}),j(()=>"edit"),ue(),u("Fired command",!0))},{intent:x.SetViewDense,mode:f.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(A({viewMode:"dense"}),u("View set",null))},{intent:x.SetViewWide,mode:f.DEFAULT,action:()=>(A({viewMode:"wide"}),u("View set",null))}];var hi=[{intent:x.ViewHelp,mode:f.DEFAULT,action:()=>(A({mode:f.HELP}),u("Viewing help",null))},{intent:x.Exit,mode:f.HELP,action:()=>(A({mode:f.DEFAULT}),u("Exiting help",null))},{intent:x.Confirm,mode:f.COMMAND_LINE,action:()=>(ue(),u("Executing command",null))},{intent:x.MoveCursorLeft,mode:f.COMMAND_LINE,action:()=>(Gn(-1),u("Moving cursor left",null))},{intent:x.MoveCursorRight,mode:f.COMMAND_LINE,action:()=>(Gn(1),u("Moving cursor right",null))},{intent:x.MoveCursorLeftOfWord,mode:f.COMMAND_LINE,action:()=>(qn("left"),u("Moving cursor left of word",null))},{intent:x.MoveCursorRightOfWord,mode:f.COMMAND_LINE,action:()=>(qn("right"),u("Moving cursor right of word",null))},{intent:x.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(A({mode:f.DEFAULT}),u("Exiting command line",null))},{intent:x.AutoCompleteCommand,mode:f.COMMAND_LINE,action:()=>(j((e,{remainder:t})=>t?e+t:e),u("Auto-completing command",null))},{intent:x.CaptureInput,mode:f.COMMAND_LINE,action:(e,{sequence:t})=>(j(n=>n+t),u("Capturing input",null))},{intent:x.EraseInput,mode:f.COMMAND_LINE,action:()=>(mo(),u("Erasing input",null))},{intent:x.EraseInputWord,mode:f.COMMAND_LINE,action:()=>(po(),u("Erasing input word",null))},{intent:x.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(yo(),u("Getting last command from history",null))},{intent:x.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(xo(),u("Getting next command from history",null))}];import cd from"chalk";var mn=": for command line",Ei="q to exit",Ci=`${cd.hex(E.accent)("m")} to confirm`,vr={[P.WORKSPACE]:[mn],[P.BOARD]:[mn],[P.BOARD+f.COMMAND_LINE]:[mn],[P.SWIMLANE]:[mn],[P.TICKET+f.HELP]:[Ei],[P.SWIMLANE+f.HELP]:[Ei],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+f.MOVE]:[Ci],[P.TICKET+f.MOVE]:[Ci]};var pn=e=>e.trim().toLocaleLowerCase(),ld=(e,t)=>{let n=C.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},ud=e=>{let{tags:t}=v(),n=C.getFieldByTitle(e,"Tags");return n?W(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},md=e=>{let{contributors:t}=v(),n=C.getFieldByTitle(e,"Assignees");return n?W(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},Ni=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return pn(e.title??"").includes(n);case"description":return pn(ld(e.id,"Description")).includes(n);case"tag":return ud(e.id).map(pn).some(d=>d.includes(n));case"assignee":return md(e.id).map(pn).some(d=>d.includes(n));default:return!0}};function bi(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(),u("Breadcrumb built",o))}var Ii=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 gn,hr,Er=new Set,Si=()=>{for(let e of Er)e()},gd=e=>(Er.add(e),()=>Er.delete(e));function Ti(e){let{currentNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return s("derive(): currentNodeId is missing");if(!r)return s("derive(): rootNode is missing");if(!o[r])return s("derive(): unable to find root node");let d=o[t];if(!d)return logger.error("Unable to derive state, currentNode not found"),s("Unable to derive state, currentNode not found");let l=bi(t,o,r);if(c(l))return logger.error(l.message),l;let m=l.data,{context:g}=d,y=vr[g+n]??vr[g]??[],N=[...vi,...xi[g]??[],...hi],b=Ii(N),I=fd(o,i),T=I[t]?.[e.selectedIndex]??null;return u("Derived successfully",{...e,currentNode:d,breadCrumb:m,availableHints:y,availableActions:N,actionIndex:b,selectedNode:T,renderedChildrenIndex:I})}var v=()=>(gn||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),gn);function Qn(e){hr=e;let t={readOnly:!1,filters:[],tags:{},contributors:{},viewMode:"dense",mode:f.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live"},n=Ti(t);return c(n)?n:(gn=n.data,Si(),u("State initialized",null))}function de(e){let t=v(),n=e(t),r=Ti(n);return c(r)?s(r.message??"Unable to update state"):(gn=r.data,Si(),u("State updated",null))}var A=e=>de(t=>({...t,...e}));var _=()=>pd(gd,v,v),fd=(e,t)=>{let n={};for(let r of Object.values(e))ye(r)&&t.length>0&&!t.every(o=>Ni(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,i)=>{let a=e[o.id],d=e[i.id];return!a||!d?0:a.rank.localeCompare(d.rank)});return n},M=e=>v()?.renderedChildrenIndex[e]??[],yr=()=>hr?Qn(hr):s("Cannot reset state: no initial workspace found");var U={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=M(t.id)[n];!r||t.context==="FIELD"||U.navigate({currentNode:r,selectedIndex:M(r.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=M(n.id),o=r.findIndex(({id:a})=>a===e.id),i=r.length===0?-1:o>=0?o:0;U.navigate({currentNode:n,selectedIndex:i})},navigateToNextItem:()=>Ai(1),navigateToPreviousItem:()=>Ai(-1),navigateToNextContainer:()=>wi(1),navigateToPreviousContainer:()=>wi(-1),navigate:({currentNode:e=v().currentNode,selectedIndex:t})=>{A({currentNodeId:e.id,selectedIndex:t})}},Ai=e=>{let t=v(),n=M(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;U.navigate({selectedIndex:o})},wi=e=>{let{currentNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let i=M(o.id),a=i.findIndex(N=>N.id===t.id);if(a<0)return;let d=i.at(a+e)??i.at(0);if(!d)return;let l=M(d.id),m=Math.max(0,l.length-1),g=Math.min(Math.max(0,r),m),y=l.length?g:-1;U.navigate({currentNode:d,selectedIndex:y})};var Ae="system",we="ACTOR",St=yd(),Re=null;function xd(){let e=Object.values(v().nodes).find(r=>r.context==="WORKSPACE");if(!e)throw new Error("No workspace found in event log");let[t]=M(e.id),[n]=t?M(t.id):[];if(logger.debug("Boot navigation target:",{workspace:e?.id,firstBoard:t?.id,firstSwimlane:n?.id}),n){let r=v().renderedChildrenIndex?.[n.id]??[];return{currentNode:n,selectedIndex:r.length>0?0:-1}}else return t?{currentNode:t,selectedIndex:0}:e?{currentNode:e,selectedIndex:0}:{currentNode:v().nodes[v().rootNodeId],selectedIndex:0}}function vd(){let e=xd();U.navigate(e)}function hd(){let e=St(),t=St(),n=St(),r=St(),o=St();return[{id:Te(),userId:Ae,userName:we,action:"init.workspace",payload:{id:e,name:"Workspace"}},{id:Te(),userId:Ae,userName:we,action:"add.board",payload:{id:t,name:"Default",parent:e}},{id:Te(),userId:Ae,userName:we,action:"add.swimlane",payload:{id:n,name:"Todo",parent:t}},{id:Te(),userId:Ae,userName:we,action:"add.swimlane",payload:{id:r,name:"In progress",parent:t}},{id:Te(),userId:Ae,userName:we,action:"add.swimlane",payload:{id:o,name:"Done",parent:t}},{id:Te(),userId:Ae,userName:we,action:"add.board",payload:{id:en,name:"Closed",parent:e}},{id:Te(),userId:Ae,userName:we,action:"add.swimlane",payload:{id:tt,name:"Closed",parent:en}},{id:Te(),userId:Ae,userName:we,action:"lock.node",payload:{id:en}},{id:Te(),userId:Ae,userName:we,action:"lock.node",payload:{id:tt}}]}function Ke(){return Re!==null}function xr(){if(!Re||Re.length===0)return Re=null,u("No pending default events to persist",null);let e=Re.map(t=>Jt({event:t})).filter(c);return e.length>0?s([at.bold.red("Persisting default events failed"),"",...e.map((t,n)=>`${at.dim.gray(`${n+1}.`)} ${at.dim(t.message)}`),`
37
- `].join(`
38
- `)):(Re=null,u("Persisted pending default events",null))}function Ri(e){let t;e.some(r=>r.action==="init.workspace")?(Re=null,t=Ve(e)):(Re=hd(),t=Ve([...Re]));let n=t.filter(c);return n.length>0?s([at.bold.red("Materializing failed"),"",...n.map((r,o)=>`${at.dim.gray(`${o+1}.`)} ${at.dim(r.message)}`),`
39
- `].join(`
40
- `)):(vd(),u("State booted successfully",null))}import{Box as Bd}from"ink";import br from"react";import At from"chalk";import{Box as Cr,Text as Mi}from"ink";import Tt,{useEffect as Ed,useMemo as Cd,useState as Nd}from"react";var Li=At.gray,bd=At.inverse,Id=At.inverse.gray,Sd={hint:"",hints:[],overlap:0,remainder:""},Di=({value:e,command:t})=>{if(!t)return null;let n=e.trimStart(),o=e.length-n.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},Td=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=Y(t);return{bg:r=>At.bgHex(n).black(r),bgCursor:r=>At.bgHex(n).inverse.black(r)}}return _n(t)},Ad=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Di({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}},Pi=()=>({value:J.value,cursorPosition:J.cursorPosition,commandIsPending:J.commandIsPending,autoCompletion:J.commandMeta.autoCompletion??Sd,infoMessage:J.commandMeta.infoMessage,validationStatus:J.commandMeta.validity,command:J.commandMeta.command,inputString:J.commandMeta.inputString,modifier:J.commandMeta.modifier}),wd=(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,Fi=({width:e})=>{let[t,n]=Nd(Pi());Ed(()=>{let y=()=>{let b=Pi();n(I=>wd(I,b)?I:b)},N=uo(y);return y(),()=>{N()}},[]);let{value:r,cursorPosition:o,infoMessage:i,commandIsPending:a,autoCompletion:d,command:l,modifier:m}=t,g=Cd(()=>{let y=Math.max(0,Math.min(o,r.length)),N=Di({value:r,command:l}),b=Ad({value:r,command:l,modifier:m}),I=l?_n(l):null,T=Td({command:l,modifier:m}),S=(se,ae)=>{let Ln=N&&ae>=N.start&&ae<N.end,Pn=b&&ae>=b.start&&ae<b.end;return Ln&&I?I.fg(se):Pn&&T?T.bg(se):se},R=(se,ae)=>{let Ln=N&&ae>=N.start&&ae<N.end,Pn=b&&ae>=b.start&&ae<b.end;return Ln&&I?I.fgCursor(se):Pn&&T?T.bgCursor(se):bd(se)},B=r.slice(0,y),G=r[y]??" ",ie=y<r.length?r.slice(y+1):"",Lt=Array.from(B).map((se,ae)=>S(se,ae)).join(""),De=R(G,y),Br=Array.from(ie).map((se,ae)=>S(se,y+1+ae)).join("");if(d.hint){let se=d.hint[d.overlap]??G;De=Id(se),Br=Li(d.remainder.slice(1)+ie)}return Li(":")+Lt+De+Br},[r,o,d,l,m]);return Tt.createElement(Cr,{flexDirection:"column",justifyContent:"flex-start"},Tt.createElement(Cr,{flexDirection:"column",paddingX:1,borderColor:E.secondary,borderStyle:"round",width:e},Tt.createElement(Cr,null,Tt.createElement(Mi,null,g),i&&Tt.createElement(Mi,{wrap:"truncate",color:a?E.red:E.secondary2},` ${i} `))))};import ki from"chalk";import{Box as Rd,Text as Nr}from"ink";import fn,{useEffect as Md,useState as Ld}from"react";var Pd=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Oi=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)}},Dd=({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)}`},Fd=(e,t,n)=>{let r=Oi(e),o=Oi(t);return Dd({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},kd=(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 Fd(i,a,o)},Od=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),Bi=({width:e,availableHints:t})=>{let{syncStatus:{status:n,msg:r}}=_(),[o,i]=Ld(0);Md(()=>{if(n!=="syncing"){i(0);return}let S=setInterval(()=>{i(R=>R+1)},50);return()=>clearInterval(S)},[n]);let a=[],d=0;for(let S of t){let B=(a.length>0?" | ":"").length+S.length;if(d+B>e-4)break;a.push(S),d+=B}let l=n!="synced"?r??a.join(" | "):a.join(" | "),m=Math.max(0,e-2),g=n==="syncing"?kd(Pd,(Math.sin(o*.12)+1)/2):E.secondary,y=ki.hex(g??"fff"),N=ki.hex(E.secondary2),b=y(`\u256D${"\u2500".repeat(m)}\u256E`),I=y(`\u2570${"\u2500".repeat(m)}\u256F`),T=`${y("\u2502")}${N(Od(` ${l} `,m))}${y("\u2502")}`;return fn.createElement(Rd,{flexDirection:"column",width:e},fn.createElement(Nr,null,b),fn.createElement(Nr,null,T),fn.createElement(Nr,null,I))};var yn=({width:e,mode:t,availableHints:n})=>{let r=_(),o=[],i=0;for(let a of n){let l=(o.length>0?" | ":"").length+a.length;if(i+l>e+2)break;o.push(a),i+=l}return br.createElement(Bd,null,t===f.COMMAND_LINE&&r.syncStatus.status!=="syncing"?br.createElement(Fi,{width:e}):br.createElement(Bi,{width:e,mode:t,availableHints:n}))};import{Box as dt,Text as Ui}from"ink";import We from"react";var Wi=({width:e})=>{let t=[...v().availableActions].map(n=>n.description).filter(n=>n!==void 0).map(n=>{let[r,o]=n.split("]"),i=r?.replace("[",""),a=o?.trim();return[i,a]}).filter(n=>n[0]!==void 0&&n[1]!==void 0).sort(([n],[r])=>n.length===1&&r.length!==1?-1:n.length!==1&&r.length===1?1:n.localeCompare(r,void 0,{sensitivity:"base"}));return t.unshift(["Key(s)","Action"]),We.createElement(dt,{flexDirection:"column",marginTop:3,borderColor:E.secondary,borderStyle:"round",width:e,minHeight:19},We.createElement(dt,{flexDirection:"column",width:e},v().mode===f.HELP?t.map(([n,r],o)=>We.createElement(dt,{paddingLeft:1,key:o,flexDirection:"row"},We.createElement(dt,{key:o,flexDirection:"row",paddingBottom:o?0:1},We.createElement(dt,{width:20,justifyContent:"flex-end"},We.createElement(Ui,{color:o?E.accent:E.secondary},n)),We.createElement(dt,{flexGrow:1,width:40,paddingLeft:2},We.createElement(Ui,{color:o?E.primary:E.secondary},r))))):null))};import Ki from"chalk";import{Box as vn,Text as ze}from"ink";import te from"react";import{Box as Ir,Text as Vd}from"ink";import ut from"react";import{Text as Ud}from"ink";import Wd from"react";var Hd=e=>e.toLowerCase().trim(),$d=(e,t=Je)=>{let n=Hd(e);return t[n]?t[n]:pt(n)},ct=({id:e,isSelected:t})=>{let n=C.getContributor(e);if(n)return Wd.createElement(Ud,{underline:t,color:$d(n.name)},"@"+n.name)};import{Text as _d}from"ink";import Kd from"react";var lt=({id:e,isSelected:t})=>{let n=C.getTag(e);if(n)return Kd.createElement(_d,{underline:t,backgroundColor:Y(n.name),color:E.primary}," "+n.name+" ")};var jd=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",Hi=({width:e})=>{let{breadCrumb:t,currentNode:n,selectedIndex:r,viewMode:o}=v(),i=W(n.id)[r],a=ke(i?.id??n.id,"TICKET"),d=Fe(a)?a.data:void 0,l=d?.id?W(d.id):[],m=T=>{let S=l.find(R=>R.title===T);return S?W(S.id).map(R=>typeof R.props?.value=="string"?R.props.value:"").filter(R=>!!R):[]},g=m("Tags"),y=m("Assignees"),N=d?.parentNodeId?!On(n.id,d?.parentNodeId)&&o==="dense":!1,b=t.map((T,S)=>{let R=S===t.length-1,B=W(T.id),G=R?B?.[r]?.title:void 0;return`${S?" / ":""}${T.title??""}${G?` \u25B8 ${G}`:""}`}).join(""),I=jd(b,e);return ut.createElement(Ir,null,ut.createElement(Vd,{color:E.secondary2},I),N?g.map(T=>ut.createElement(Ir,{key:T,paddingLeft:2},ut.createElement(lt,{id:T}))):null,N?y.map(T=>ut.createElement(Ir,{key:T,paddingLeft:2},ut.createElement(ct,{id:T}))):null)};import{Box as zd,Text as $i}from"ink";import xn from"react";var Gd=({filters:e})=>xn.createElement(zd,{columnGap:1},xn.createElement($i,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>xn.createElement($i,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),_i=xn.memo(Gd);function hn({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o}=_(),{userName:i,preferredEditor:a}=pe(),d=40,l=process.stdout.columns-d-8,m=r.at(-1)?.id,g=$t(m??""),y=Fe(g)?eo(g.data):"INVALID DATE";return te.createElement(vn,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?te.createElement(ze,null," "):te.createElement(vn,{paddingLeft:1},e.length>0?te.createElement(_i,{filters:e}):te.createElement(Hi,{width:l})),n==="live"?te.createElement(vn,{columnGap:1,paddingRight:2,"max-width":d,overflow:"hidden",justifyContent:"flex-end"},te.createElement(Vi,{icon:"@",value:i}),te.createElement(Vi,{icon:"\u276F",value:a})):"",n==="peek"?te.createElement(vn,{paddingLeft:1},te.createElement(ze,{backgroundColor:E.yellow}," Readonly "),te.createElement(ze,{color:E.yellow}," "+o.length+" edits ago at "),te.createElement(ze,{backgroundColor:E.yellow,color:E.accent}," "+y+" "),te.createElement(ze,{color:E.yellow},". Resume with "),te.createElement(ze,{backgroundColor:E.yellow}," :peek now ")):"")}function Vi({icon:e,value:t}){return te.createElement(ze,null,Ki.dim(e)+Ki.hex(E.accent)(` ${t??"-"} `))}import{Box as fc,Text as yc}from"ink";import Rt from"react";import{Box as En,Text as Sr}from"ink";import He from"react";import{Text as ji}from"ink";import zi,{useEffect as Gi,useState as qd}from"react";var qi={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},oe=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=_(),r=qi[n]??qi.default,[o,i]=qd(0);if(Gi(()=>{i(0)},[r]),Gi(()=>{if(!e)return;let d=setInterval(()=>{i(l=>(l+1)%r.length)},500);return()=>clearInterval(d)},[e,r]),!e)return zi.createElement(ji,null,t);let a=r[o]??r[0]??t;return zi.createElement(ji,{color:E.accent,dimColor:o===1},a)};function Tr(){let e=_(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,a=t?.id?M(t?.id):[];return He.createElement(En,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:E.secondary,width:i},He.createElement(En,{padding:1,paddingTop:0,paddingBottom:0},He.createElement(Sr,null,"Select a board:")),He.createElement(En,{padding:1,flexDirection:"column"},a.map((d,l)=>{let m=e.currentNode.context==="WORKSPACE"&&e.selectedIndex===l,y=M(d.id).flatMap(({id:N})=>W(N)).length;return He.createElement(En,{key:d.id??l},He.createElement(Sr,{color:m?E.accent:E.secondary2},He.createElement(oe,{isSelected:m})),He.createElement(Sr,{color:m?E.accent:E.secondary2},d.title," (",y," issues)",d.readonly?" \u{1F512}":""))})))}import{Box as pc}from"ink";import Tn from"react";import{Box as Rr,Text as Zd}from"ink";import he from"react";import{Box as Ar,Text as Yd}from"ink";import Cn from"react";var Nn=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),a=Math.max(1,Math.ceil(r)),d=Math.max(1,Math.floor(i/a)),l=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-d),g=o?Math.min(m,Math.max(0,l-d+1)):Math.min(m,Math.floor(l/d)*d),y=g+d,N=e.slice(g,y),b=e.length>d,I=i,T=b?Math.max(1,Math.floor(d/e.length*I)):I,S=Math.max(0,I-T),R=Math.max(1,e.length-d),B=b?Math.floor(g/R*S):0;return Cn.createElement(Ar,{flexDirection:"row",height:i,width:"100%"},Cn.createElement(Ar,{flexDirection:"column",flexGrow:1,height:i},N),Cn.createElement(Ar,{flexDirection:"column",width:1,height:I},Array.from({length:I}).map((G,ie)=>Cn.createElement(Yd,{key:ie,color:b&&ie>=B&&ie<B+T?E.accent:E.secondary},b?"\u2502":" "))))};import{Box as bn,Text as Jd}from"ink";import Ge from"react";var Yi=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=Dt(Dn(t.title),r),i=Bn(t),a=Un(t);return Ge.createElement(bn,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?E.accent:E.secondary,justifyContent:"space-between"},Ge.createElement(bn,{borderBottom:!0},Ge.createElement(bn,{paddingLeft:1,flexDirection:"column"},Ge.createElement(Jd,{color:E.primary},o))),Ge.createElement(bn,{flexDirection:"row",paddingLeft:1},i.map(d=>Ge.createElement(lt,{key:d.id,id:d.id})),a.map(d=>Ge.createElement(ct,{key:d.id,id:d.id}))))};import Xd from"chalk";import{Box as wt,Text as wr}from"ink";import Me from"react";var Qd=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Ji=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=M(t.id),a=T=>{let S=i.find(R=>R.title===T);return S?M(S.id).map(R=>typeof R.props?.value=="string"?R.props.value:"").filter(R=>!!R):[]},d=a("Tags").map(T=>C.getTag(T)).filter(T=>!!T),l=a("Assignees").map(T=>C.getContributor(T)).filter(T=>!!T),m=1,g=d.length*(1+m),y=l.length*(2+m),N=d.map(T=>Me.createElement(wt,{key:T.id,paddingRight:m},Me.createElement(wr,{color:Y(T.name)},"\u25A0"))),b=l.map(T=>Me.createElement(wt,{key:T.id,paddingRight:m},Me.createElement(wr,{color:pt(T.name)},"@"+T.name.at(0)))),I=n?E.accent:o===f.MOVE?E.secondary:E.primary;return Me.createElement(wt,{borderBottom:!0,justifyContent:"space-between"},Me.createElement(wt,null,Me.createElement(oe,{isSelected:n,placeholder:Xd.dim.gray(r+1+" ")}),Me.createElement(wr,{wrap:"truncate",color:I},Qd(t.title,e-g-y-14))),Me.createElement(wt,null,N,b))};var ec=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:a,mode:d})=>{let{renderedChildrenIndex:l}=_(),m=l[e.id]??[],g=`${e.title} (${m.length})`,y=3,N=o?1:4,b=r-y-(o?2:1),I=he.createElement(Rr,{borderStyle:"round",borderColor:E.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},he.createElement(oe,{isSelected:t}),he.createElement(Zd,{bold:!0,color:t?E.accent:E.primary},g," ",e.readonly?"\u{1F512}":"")),T=(S,R)=>{let B=i&&a===R;return o?he.createElement(Ji,{key:S.id,index:R,width:n,ticket:S,isSelected:B,mode:d}):he.createElement(Yi,{key:S.id,width:n,ticket:S,isSelected:B})};return he.createElement(Rr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?E.accent:E.secondary,paddingRight:1,paddingLeft:1,height:r},I,he.createElement(Rr,{padding:o?1:0},m.length>0&&he.createElement(Nn,{selectedIndex:a,height:b,itemHeight:N},m.map(T)),he.createElement(oe,{isSelected:i&&a===-1})))},Xi=he.memo(ec);import{Box as Pr,Text as uc}from"ink";import $e,{useEffect as Dr,useMemo as ts}from"react";import ge from"chalk";import Qi from"string-width";import{decodeTime as tc}from"ulid";var nc=(e,t)=>e+" ".repeat(Math.max(0,t-Qi(e))),rc=(e,t)=>" ".repeat(Math.max(0,t-Qi(e)))+e,oc=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)})(),ic=e=>{switch(e.action){case"move.node":{let t=C.getNode(e.payload.parent),n=t?ge.dim.bgBlack(` ${t.title} `):"unknown",r=e.payload.pos;if(!r)return`to ${n}`;switch(r.at){case"start":return`to ${n} ${ge.dim("(to top of list)")}`;case"end":return`to ${n} ${ge.dim("(to bottom of list)")}`;case"before":return`to ${n} ${ge.dim("(up in list)")}`;case"after":return`to ${n} ${ge.dim("(down in list)")}`}}case"tag.issue":{let t=v().tags[e.payload.tagId];return t?ge.bgHex(Y(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=v().tags[e.payload.tagId];return t?ge.bgHex(Y(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=v().contributors[e.payload.contributor];return t?ge.hex(Y(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=v().contributors[e.payload.contributor];return t?ge.hex(Y(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""}},sc=e=>{let t=Zr(tc(e));return ge.gray(rc(t,8))},ac=12,dc=e=>nc(`${e}`,ac),Zi=e=>{let t=sc(e.id),n=dc(e.userName),r=oc(e.action),o=ic(e),i=ge.dim("\u203A"),a=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${a}`};import{Box as In,Text as cc}from"ink";import Le from"react";var es=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=_(),{title:o}=t,i=M(t.id).map(a=>{let d=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return C.getContributor(d)?.id;if(o==="Tags")return C.getTag(d)?.id}).filter(a=>!!a);return Le.createElement(In,{alignItems:"center",paddingTop:1},Le.createElement(In,{minWidth:12},Le.createElement(oe,{isSelected:n}),Le.createElement(cc,{color:n?E.accent:E.secondary2},o,":")),Le.createElement(In,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,d)=>{let l=r.id===t.id&&d===e;return Le.createElement(In,{key:`${o}-${a}`,paddingRight:2,minHeight:1},Le.createElement(oe,{isSelected:l}),o==="Assignees"?Le.createElement(ct,{isSelected:l,id:a}):o==="Tags"?Le.createElement(lt,{isSelected:l,id:a}):null)})))};import{Box as Sn,Text as Mr}from"ink";import Pe,{useEffect as lc}from"react";var Lr=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:d}=_(),l=N=>String(N).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];lc(()=>{let N=[];return m.forEach((b,I)=>{let T=ne.text({id:`${I}`,name:`Line ${I+1}`,parentNodeId:e,props:{value:b},readonly:!0}),S=C.createNodeAtPosition(T);Fe(S)&&N.push(S.data.id)}),()=>N.forEach(C.deleteNode)},[e,n]);let g="\u2029",y=m.map((N,b)=>{let I=d.id===e&&a===b;return Pe.createElement(Sn,{key:`${e}-${b}`},Pe.createElement(Mr,{color:I?E.primary:E.secondary2,dimColor:!I},`${b+1} `.padStart(5,"\xA0")),Pe.createElement(Mr,{backgroundColor:I?"gray":""},l(N.length?Dt(N,i-10):g)))});return Pe.createElement(Sn,{flexDirection:"column",paddingTop:1},Pe.createElement(Sn,null,Pe.createElement(oe,{isSelected:o}),Pe.createElement(Mr,{color:o?E.accent:E.secondary2},t)),Pe.createElement(Sn,{flexDirection:"row",borderStyle:"round",borderColor:E.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Pe.createElement(Nn,{scrollByOne:!0,children:y,height:r-2,selectedIndex:a,itemHeight:1})))};var mc=e=>`${e}::log`,ns=e=>e==="Assignees"||e==="Tags",rs=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=_(),o=process.stdout.columns||120,i=ts(()=>mc(e.id),[e.id]),a=ts(()=>[...e.log].reverse().map(Zi).join(`
41
- `),[e.log]);Dr(()=>{if(C.getNode(i))return;let R={...ne.field(i,"Log",e.id,{value:a}),readonly:!0,childRenderAxis:"vertical"};return C.createNodeAtPosition(R),()=>{C.deleteNode(i)}},[i,e.id,a]),Dr(()=>{let S=C.getNode(i);S&&S.props.value!==a&&C.updateNode({...S,props:{...S.props,value:a},childRenderAxis:"vertical",readonly:!0})},[i,a]);let d=r.id===e.id,l=r.id===i||r.parentNodeId===i;Dr(()=>{l&&(n>=0||U.navigate({selectedIndex:0}))},[l,n]);let m=M(e.id);if(l){let S=C.getNode(i),B=t-3;return $e.createElement(Pr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},S?$e.createElement(Lr,{id:S.id,label:"Event log",text:S.props.value??"",selected:!1,maxWidth:o,height:B}):null)}let g=m.reduce((S,R)=>ns(R.title)||R.id===i?S+1:S,0),y=2,N=g*1,I=t-3-N-y,T=(S,R)=>ns(S.title)?$e.createElement(es,{key:S.id,parent:S,selected:R,selectedIndex:n}):S.id===i?$e.createElement(Pr,{key:S.id,paddingTop:1},$e.createElement(oe,{isSelected:R}),$e.createElement(uc,{backgroundColor:E.secondary,color:R?E.accent:E.primary}," History \u203A\u203A ")):S.title==="Description"?$e.createElement(Lr,{label:"Description (press e to edit)",key:S.id,id:S.id,text:S.props.value??"",selected:R,maxWidth:o,height:I}):null;return $e.createElement(Pr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((S,R)=>T(S,d&&n===R)))};var gc=({swimlanes:e,currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:a,width:d})=>{let l=t.context,m=l===P.TICKET||l===P.FIELD_LIST||l===P.FIELD,g=l===P.BOARD||l===P.SWIMLANE,y=l===P.TICKET?t:r.find(S=>S.context===P.TICKET),N=Math.floor(d/3),b=Math.floor(d/Math.max(e.length,1)),I=Math.min(b,N),T=i==="dense";return Tn.createElement(pc,{flexDirection:"row",height:a},g&&e.map((S,R)=>{let B=t.id===S.id,G=B?n:-1,ie=t.context===P.BOARD&&n===R;return Tn.createElement(Xi,{key:S.id,height:a,width:I,swimlane:S,isSelected:ie,isDense:T,isFocused:B,listSelectedIndex:G,mode:o})}),m&&y&&Tn.createElement(rs,{height:a,ticket:y}))},os=Tn.memo(gc);var xc=({currentNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:d}=_(),l=n.find(({context:N})=>N==="BOARD"),y=i-1-3;return Rt.createElement(fc,{flexDirection:"row"},e.context==="WORKSPACE"?Rt.createElement(Tr,null):l?Rt.createElement(os,{height:y,width:a,swimlanes:(d[l.id]??[]).filter(N=>N!==void 0&&Ur(N)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Rt.createElement(yc,null))},is=Rt.memo(xc);import{Box as Mt,Text as Ee}from"ink";import K from"react";var An=({isDone:e,command:t,value:n})=>K.createElement(Mt,null,K.createElement(Ee,{color:E.accent,dimColor:e},e?" \u2714 ":" "),K.createElement(Ee,{dimColor:e},"Type "),K.createElement(Ee,{backgroundColor:E.secondary,dimColor:e}," "+t+" "),n&&K.createElement(K.Fragment,null,K.createElement(Ee,{dimColor:e}," "),K.createElement(Ee,{color:E.secondary,dimColor:e},"<"+n+">")));function Fr({width:e,height:t,hasUserName:n,hasPreferredEditor:r,userName:o,preferredEditor:i}){let a=n&&r,d=n?r?null:":config:editor":":config:username";return K.createElement(Mt,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:E.secondary,rowGap:1},K.createElement(Ee,{color:E.accent,bold:!0},"Welcome! \u{1F539}"),K.createElement(Ee,null,"Lets get you started - its a breeze."),K.createElement(Ee,{color:E.secondary2},"And remember, you can always get help with"," ",K.createElement(Ee,{color:E.accent},":help"),"."),!a&&K.createElement(Ee,{color:E.secondary2},d===":config:username"?"First, choose your username.":"Nice. One more step."),K.createElement(Mt,{flexDirection:"column"},n&&K.createElement(Mt,{marginBottom:1},K.createElement(An,{isDone:!0,command:":config:username",value:o})),!n&&K.createElement(An,{isDone:!1,command:":config:username"}),n&&!r&&K.createElement(An,{isDone:!1,command:":config:editor"}),a&&K.createElement(Mt,null,K.createElement(An,{isDone:!0,command:":config:editor",value:i}))))}var hc=({width:e,height:t})=>O.createElement(fe,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:E.secondary,rowGap:1},O.createElement(_e,{color:E.accent,bold:!0},"Initialize project"),O.createElement(_e,null,`This folder is not an ${vc.hex(E.accent)("epiq")} project yet.`),O.createElement(_e,{color:E.primary},"To start tracking issues here, we need to initialize a new"," ",O.createElement(_e,{color:E.primary,backgroundColor:E.secondary}," .epiq/ ")," ","directory in this repository."),O.createElement(fe,{marginTop:1,flexDirection:"column"},O.createElement(fe,null,O.createElement(_e,{color:E.accent}," "),O.createElement(_e,{color:E.primary},"Type "),O.createElement(_e,{backgroundColor:E.secondary}," :init "))),O.createElement(fe,{marginTop:1},O.createElement(_e,{color:E.secondary2},"(This will create the local epiq project files)")));function kr({width:e,height:t}){let n=_(),r=n.filters;if(n.mode===f.HELP)return O.createElement(fe,{flexDirection:"column"},O.createElement(Wi,{width:e}));let{isSetup:o,hasPreferredEditor:i,hasUserName:a,userName:d,preferredEditor:l}=Bt(),m=!o,g=o&&Ke();if(m)return O.createElement(fe,{flexDirection:"column"},O.createElement(fe,{flexDirection:"column"},O.createElement(hn,{hideBreadCrumb:!0,filters:r}),O.createElement(Fr,{height:t,width:e,hasUserName:a,hasPreferredEditor:i,userName:d??"",preferredEditor:l??""})),O.createElement(yn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(g)return O.createElement(fe,{flexDirection:"column"},O.createElement(fe,{flexDirection:"column"},O.createElement(hn,{hideBreadCrumb:!0,filters:r}),O.createElement(hc,{height:t,width:e})),O.createElement(yn,{width:e,mode:n.mode,availableHints:n.availableHints}));let y=be(v().breadCrumb??[],"BOARD");if(Fe(y)){let N=y.data.id,b=M(N).length,I=3,T=Math.floor(e/I),S=Math.floor(e/Math.max(b,1));e=Math.min(S,T)*Math.max(b,I)}return O.createElement(fe,{flexDirection:"column"},O.createElement(fe,{flexDirection:"column"},O.createElement(hn,{filters:r}),O.createElement(is,{width:e,height:t,currentNode:n.currentNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:n.viewMode,mode:n.mode})),O.createElement(yn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import Ec from"readline";var wn,Rn,Ce,Cc=new Set([x.MoveCursorLeft,x.EraseInputWord,x.MoveCursorLeftOfWord,x.MoveCursorRight,x.MoveCursorRightOfWord,x.NavToPreviousContainer,x.NavToNextContainer,x.NavPreviousItem,x.NavNextItem,x.SetViewDense,x.SetViewWide,x.Confirm,x.Exit,x.InitCommandLine,x.ExitCommandLine,x.CaptureInput,x.EraseInput,x.EraseInputWord,x.HideHelp,x.ViewHelp,x.SetViewDense,x.SetViewWide,x.GetLastCommandFromHistory,x.GetNextCommandFromHistory,x.AutoCompleteCommand]),ss=async e=>{if(e.ctrl&&e.name==="c")return U.exit();let{actionIndex:t,mode:n,readOnly:r}=v(),o=ho(e,n);if(!o||r&&!Cc.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(a){logger.error(a)}},Nc=()=>async function(t,n){n.name!=="escape"&&(Ce&&(clearTimeout(Ce),Ce=void 0),await ss(n))},bc=()=>async function(t){if(t.length===1&&t[0]===27){Ce&&clearTimeout(Ce),Ce=setTimeout(()=>{ss({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),Ce=void 0},25);return}Ce&&(clearTimeout(Ce),Ce=void 0)};function as(){wn&&process.stdin.removeListener("keypress",wn),Rn&&process.stdin.removeListener("data",Rn),wn=Nc(),Rn=bc(),Ec.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Rn),process.stdin.on("keypress",wn)}import Or from"chalk";Sc(`${Or.bold("Epiq CLI")}
42
-
43
- ${Or.dim("Boot in directory:")}
44
- ${Or.cyan("$ epiq")}
45
-
46
- `,{importMeta:import.meta,flags:{init:{type:"string"}}});var ds=process.stdout.columns||120,cs=process.stdout.rows||20,Mn=null,Ac=e=>{if(!Mn){Mn=Ic(e);return}Mn.rerender(e)},ls=()=>{Ac(Tc.createElement(kr,{width:ds,height:cs}))},wc=()=>{let e=vt();if(c(e)){if(e.message.includes("No events found"))return logger.info("No events found, starting with empty state"),[];throw new Error(e.message)}return e.data},Rc=e=>{let t=Ri(e);if(c(t))throw new Error(`Failed to boot state: ${t.message}`)};async function Mc(){let e=mi();c(e)||Ye(e.data),await ri();let t=wc();Rc(t),ls(),as()}process.stdout.on("resize",()=>{ds=process.stdout.columns||120,cs=process.stdout.rows||20,Mn&&ls()});(async()=>(console.clear(),await Mc()))();