epiq 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gui/main.js +1 -1
- package/dist/index.js +54 -54
- package/dist/mcp.js +48 -48
- package/package.json +1 -1
- package/readme.md +1 -1
package/dist/index.js
CHANGED
|
@@ -1,66 +1,66 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`,"utf8"),l("Created project.json",null)}catch(
|
|
4
|
-
`);if(n[n.length-1]===""&&n.pop(),n.length<=
|
|
2
|
+
import jt from"chalk";import{render as rv}from"ink";import ov from"meow";import sv from"react";import zf from"chalk";var bt={Success:"success",Fail:"fail"},a=e=>({status:bt.Fail,message:e,value:null}),l=(e,t)=>({status:bt.Success,message:e,value:t}),d=e=>e.status==="fail",te=e=>e.status==="success";import{spawn as Dl}from"node:child_process";import Ho from"node:process";var li=e=>{let t=Ho.platform==="darwin"?"open":Ho.platform==="win32"?"cmd":"xdg-open",n=Ho.platform==="win32"?["/c","start","",e]:[e];Dl(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as Of}from"node:fs/promises";import _f from"node:http";import sn from"node:path";import{fileURLToPath as $f}from"node:url";import{decodeTime as Bf,ulid as Ie}from"ulid";import Qo from"node:fs";import ql from"node:os";import Je from"node:path";import wn from"node:fs";import{ulid as Ul}from"ulid";import{z as fr}from"zod";import An from"node:fs";import lt from"node:path";var hv=process.env.IS_LOCAL==="true",ut=".epiq",Ue=".epiq-global",lr="events",Fl="project.json",ur=e=>lt.join(e,ut),mr=e=>lt.join(ur(e),Fl),Tn=e=>lt.join(ur(e),lr),ui=e=>lt.join(e,ut),Bl=e=>{let t=lt.join(e,ut);return An.existsSync(t)&&An.statSync(t).isDirectory()},jo=e=>{let t=mr(e);return An.existsSync(t)&&An.statSync(t).isFile()},pr=e=>{let t=lt.resolve(e);for(;;){if(Bl(t))return l("Resolved closest .epiq root",t);let n=lt.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},Ke=e=>{let t=lt.resolve(e);for(;;){if(jo(t))return l("Resolved closest epiq project root",t);let n=lt.dirname(t);if(n===t)return a("No .epiq/project.json found in any parent");t=n}},mi=e=>{let t=Tn(e);try{return An.mkdirSync(t,{recursive:!0}),l("Resolved events dir",t)}catch(n){return a(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},qe=async()=>{let e=await Ye(process.cwd());if(d(e))return e;let t=Te({repoRoot:e.value});return d(t)?t:l("Resolved persist root",t.value)};var Ol="__epiq_state__",_l=fr.object({projectId:fr.string().min(1),stateBranch:fr.string().min(1),createdAt:fr.iso.datetime()}),an=()=>({projectId:Ul(),stateBranch:Ol,createdAt:new Date().toISOString()}),Ct=e=>{let t=mr(e);if(!wn.existsSync(t))return a("Missing .epiq/project.json");try{let n=wn.readFileSync(t,"utf8"),r=JSON.parse(n),o=_l.safeParse(r);return o.success?l("Read project.json",o.data):a(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return a(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},pi=e=>{let t=Ct(e);return d(t)?a(t.message):l("Read projectId",t.value.projectId)},fi=({repoRoot:e,fileContents:t})=>{let n=ur(e),r=mr(e);try{if(wn.mkdirSync(n,{recursive:!0}),wn.existsSync(r)){let o=Ct(e);return d(o)?a(o.message):l("Project already initialized",null)}return wn.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,"utf8"),l("Created project.json",null)}catch(o){return a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var Vo=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let i=r(...s);if(!n.has(i)){let c=e(...s).then(u=>(d(u)&&n.delete(i),u));n.set(i,c)}return n.get(i)});return o.clear=()=>n.clear(),o};import Mn from"fs";import qo from"path";import $l from"util";var gi=1e3,Wl=50,Go=0,vi=()=>process.env.EPIQ_MCP==="true",yi=()=>{let e=process.cwd(),t=pr(e);return d(t)?vi()?qo.join(process.cwd(),".epiq-mcp.log"):void 0:qo.join(t.value,ut,"log","epiq.log")};function Hl(){let e=yi();if(!e||!Mn.existsSync(e))return;let n=Mn.readFileSync(e,"utf8").split(`
|
|
4
|
+
`);if(n[n.length-1]===""&&n.pop(),n.length<=gi)return;let r=n.slice(-gi).join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`;
|
|
7
|
-
`;
|
|
8
|
-
`);u(n?{stdout:i,stderr:p,exitCode:124}:a(p))},
|
|
9
|
-
`)))}),
|
|
10
|
-
`)));return}u(l("Git command succeeded",{stdout:i,stderr:c,exitCode:v}))})}),
|
|
11
|
-
${n.message}`);let
|
|
12
|
-
${
|
|
13
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(
|
|
14
|
-
${
|
|
15
|
-
${s.message}`):l("Pulled with rebase",!0)},
|
|
16
|
-
`+e.message);let t=
|
|
17
|
-
`+t.message):l("Ensured epiq storage",!0)},
|
|
18
|
-
`+t.message);let
|
|
19
|
-
`).filter(Boolean).filter(i=>i!==
|
|
20
|
-
${
|
|
21
|
-
${n.message}`);let
|
|
22
|
-
${
|
|
23
|
-
`+n.message);let
|
|
24
|
-
`+
|
|
25
|
-
${c.message}`)}let i=await
|
|
26
|
-
`+i.message);if(i.value)return l("Local state branch already exists",!1);if(s){let c=await
|
|
27
|
-
${c.message}`):l("Created local state branch from remote",!0)}return
|
|
28
|
-
`),
|
|
29
|
-
`+
|
|
30
|
-
${
|
|
31
|
-
${u.message}`)}if(s&&!
|
|
32
|
-
${u.message}`)}let i=await
|
|
33
|
-
${u.message}`)}return
|
|
34
|
-
${
|
|
35
|
-
${c.message}`);let u=await
|
|
36
|
-
${u.message}`):l("Configured state branch upstream",!0)},
|
|
37
|
-
${
|
|
38
|
-
`+n.message):
|
|
39
|
-
${s.message}`):l("Pushed state branch",!0)},fi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let o=!1,r=on(e);if(d(r))return r;let s=r.value,i=[po(),await yl({repoRoot:e,stateBranchName:s}),await $t({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Il({stateBranchRoot:t,stateBranchName:s}),await ui(t),n?await bl({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(d(c))return a(c.message);o=o||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",o)};import{WebSocket as Cl}from"ws";var fo=new Set,vi=e=>{fo.add(e),e.on("close",()=>{fo.delete(e)}),e.on("error",()=>{fo.delete(e)})},_t=e=>{let t=JSON.stringify(e);for(let n of fo)n.readyState===Cl.OPEN&&n.send(t)};import{useSyncExternalStore as Hp}from"react";var w={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function Ur(e){return e.context===w.WORKSPACE}function T(e){return e.context===w.TICKET}function bt(e){return e.context===w.TEXT}function Ke(e){return e.context===w.FIELD}function Rn(e){return e.context===w.FIELD_LIST}var Ct=e=>e.context===w.SWIMLANE,vo=e=>e.context===w.BOARD,Tn=e=>e.context===w.COMMENT;var f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var yi=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",hi=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",xi=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Ii=(e,t)=>{if(hi(e,e.sequence))return x.MoveCursorLeftOfWord;if(xi(e,e.sequence))return x.MoveCursorRightOfWord;if(yi(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}},bi=(e,t)=>{if(hi(e,e.sequence))return x.MoveCursorLeftOfWord;if(xi(e,e.sequence))return x.MoveCursorRightOfWord;if(yi(e,e.sequence))return x.EraseInputWord;switch(e.name){case"tab":return x.AutoCompleteCommand;case"up":return x.NavPreviousItem;case"down":return x.NavNextItem;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}};function yo(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}var ho=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",St=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Ci=e=>e.charAt(0).toUpperCase()+e.slice(1);var Si=e=>{let t=new Map;for(let n of e)for(let o=1;o<=n.length;o++){let r=n.slice(0,o),s=t.get(r);s?s.push(n):t.set(r,[n])}return t},Ni=(e,t)=>t?e.get(t)??[]:[];var Ei=new WeakMap,Sl=e=>{let t=Ei.get(e);return t||(t=Si(e),Ei.set(e,t)),t};var Ri=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let o=t.toLowerCase();return Ni(Sl(e),o).filter(s=>yo(o,s)>=n)};var Nl={hint:"",hints:[],overlap:0,remainder:""},Ti=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},o)=>{if(n||e==="")return Nl;let r=Ri({wordList:o,inputToMatch:e,overlapThreshold:1});return El(t,r)},El=(e,t)=>{let n=t[0]??"",o=yo(e.toLowerCase(),n.toLowerCase()),[r,s]=n.split(":"),i=o<(r??"").length,c=!!s,p=(c&&i?r:n)+(c&&i?":":" "),v=p.slice(o);return{hint:p,hints:t,overlap:o,remainder:v}};import{useSyncExternalStore as Rl}from"react";var An={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Or=new Set,Tl=()=>{for(let e of Or)e()},_=()=>An,Ai=()=>Rl(e=>(Or.add(e),()=>{Or.delete(e)}),()=>An),Fe=e=>(An={...An,...e},Tl(),An);import{ulid as Ml}from"ulid";var an=24n,Al=an*4n,qe=(1n<<Al)-1n,wl=/^[0-9a-f]+$/;function wi(e){return!e||!wl.test(e)?a(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function Be(e,t=an){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Ce(e,t){if(!e&&!t)return Be(qe/2n,an);let n=e?wi(e):l("Resolved lower bound",0n);if(d(n))return n;let o=t?wi(t):l("Resolved upper bound",qe);if(d(o))return o;let r=n.value,s=o.value;if(s<=r)return Be(qe/2n,an);let i=(r+s)/2n;return i===r||i===s?a("No rank space available between neighbors"):Be(i,an)}function Mi(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let o=0;o<e;o++){let r=qe*BigInt(o+1)/(t+1n),s=Be(r,an);if(d(s))return s;n.push(s.value)}return l("Resolved evenly spaced ranks",n)}var Wr=(e,t)=>{let n=H(e),o=Mi(n.length);if(d(o))return o;let r={};for(let s=0;s<n.length;s++){let i=n[s],c=o.value[s];if(!i||!c)return a("Unable to assign rebalance rank");r[i.id]=c}return l("Created rebalance event",{id:Ml(),action:"rebalance.children",payload:{parent:e,ranks:r},...t})};import{ulid as Lu}from"ulid";var it=(e,t)=>{let{nodes:n}=g(),o=n[e];if(!o)return a("Node not found");if(o.context===t)return l("Resolved ancestor node",o);let r=o.parentNodeId?n[o.parentNodeId]:void 0;for(;r;){if(r.context===t)return l("Resolved ancestor node",r);r=r.parentNodeId?n[r.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},$r=(e,t)=>{let{nodes:n}=g(),o=n[e];for(;o?.parentNodeId;){if(o.parentNodeId===t)return!0;o=n[o.parentNodeId]}return!1},jt=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:a("Node not found"),I={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.userId&&n.userId!==t)return a("Contributor is already linked to another user");let o={...n,userId:t},r=ue(s=>({...s,contributors:{...s.contributors,[e]:o}}));return d(r)?a("Unable to link contributor to user"):l("Linked contributor to user",o)},deleteNode(e){ue(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create comment, missing issue");if(!T(t))return a("Can only comment on issues");let n=ue(o=>({...o,comments:{...o.comments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create comment"):l("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return a("Unable to edit comment, missing comment");let o=this.getNode(n.issue);if(!o)return a("Unable to edit comment, missing issue");if(!T(o))return a("Can only edit issue comments");let r={...n,md:t,deleted:!1},s=ue(i=>({...i,comments:{...i.comments??{},[e]:r}}));return d(s)?a("Unable to edit comment"):l("Edited comment",r)},deleteComment(e){let t=this.getComment(e);if(!t)return a("Unable to delete comment, missing comment");let n={...t,deleted:!0},o=ue(r=>({...r,comments:{...r.comments??{},[e]:n}}));return d(o)?a("Unable to delete comment"):l("Deleted comment",n)},getComment(e){return g().comments?.[e]},getCommentsByIssue(e){return Object.values(g().comments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=g(),o=n[e];if(!o)return a("Edit target node not found");let r=jt(o,"edit");if(r)return r;let s={...o,props:{...o.props,description:t}};return this.updateNode(s),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return a("Rename target node not found");let o=jt(n,"rename");if(o)return o;let r={...n,title:t};return this.updateNode(r),l("Renamed node",r)},getExistingTags(){let{tags:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return H(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:o}=g(),r=this.getNode(e),s=this.getNode(t);if(!r)return a("Node not found");if(!s)return a("Target parent not found");if(o===e)return a("Cannot move root node");if(e===t)return a("Cannot move node into itself");let i=jt(r,"move");if(i)return i;if($r(t,e))return a("Cannot move node into its own descendant");let c={...r,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:o}=g(),r=this.getNode(e);if(!r)return a("Node not found");if(o===e)return a("Cannot delete root node");let s=new Set,i=u=>{let m=t[u];if(!(!m||s.has(u))){s.add(u);for(let p of H(m.id))i(p.id)}};i(e);let c={...structuredClone(t)};for(let u of s){if(!c[u])return a("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(C({nodes:c}),l("Successfully tomb stoned",r)):a("Unable to delete undefined")},createContributor(e){let t=ue(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):l("Created contributor",e)},assign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return a("Unable to assign contributor, missing contributor");if(!o)return a("Unable to assign contributor, missing target");let r=jt(o,"edit");if(r)return r;if(!T(o))return a("Target is not an issue");let s=o.props.assignees??[];if(s.includes(t))return a("Contributor already assigned");let i={...o,props:{...o.props,assignees:[...s,t]}};return this.updateNode(i),l("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return a("Unable to unassign, missing contributor");if(!o)return a("Unable to unassign, missing target");let r=jt(o,"edit");if(r)return r;if(!T(o))return a("Target is not an issue");let s=o.props.assignees??[];if(!s.includes(t))return l("Issue is not assigned to that contributor",{assignee:t});let i={...o,props:{...o.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),l("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),o=this.getNode(e);if(!n)return a("Unable to add tag, missing tag");if(!o)return a("Unable to add tag, missing target");let r=jt(o,"edit");if(r)return r;if(!T(o))return a("Target is not an issue");let s=o.props.tags??[];if(s.includes(t))return a("Tag already assigned");let i={...o,props:{...o.props,tags:[...s,t]}};return this.updateNode(i),l("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),o=this.getNode(e);if(!n)return a("Unable to remove tag, missing tag");if(!o)return a("Unable to remove tag, missing target");let r=jt(o,"edit");if(r)return r;if(!T(o))return a("Target is not an issue");let s=o.props.tags??[];if(!s.includes(t))return l("Issue is not tagged with that tag",{tag:t});let i={...o,props:{...o.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),l("Tag removed",{tag:t})},createTag(e){let t=ue(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):l("Tag created",e)},createNode(e){let t=ue(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?a("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},o=ue(r=>({...r,nodes:{...r.nodes,[e]:n}}));return d(o)?a(o.message):l("Locked node",n)},updateNode(e){let t=ue(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return g().contributors[e]},getTag(e){return g().tags[e]},getNode(e){return g().nodes[e]},getSiblings(e){return H(e)}};var oe={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments"};var Y={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:w.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,o,r=!1)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:w.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:w.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:o,props:r={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:w.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:o,childRenderAxis:r="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:w.FIELD_LIST,childRenderAxis:r,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:w.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!0,isVirtual:s=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:w.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:r,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:o,props:r={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:w.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};import Ht from"chalk";import Bi from"string-width";import{decodeTime as Ol}from"ulid";import cn from"chalk";var me={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},y={accent:me.cyan,accent2:me.magenta,primary:me.white,secondary:me.grayDark,secondary2:me.grayLight,gray:me.gray,green:me.green,yellow:me.yellow,red:me.red};var b={red:me.red,yellow:me.yellow,green:me.green,blue:me.blue,magenta:me.magenta,cyan:me.cyan},dn={urgent:b.red,critical:b.red,important:b.red,blocker:b.red,asap:b.red,immediate:b.red,fail:b.red,failure:b.red,broken:b.red,bug:b.red,error:b.red,incident:b.red,outage:b.red,production:b.red,crash:b.red,security:b.red,warning:b.yellow,warn:b.yellow,risky:b.yellow,risk:b.yellow,attention:b.yellow,pending:b.yellow,review:b.yellow,"needs-review":b.yellow,qa:b.yellow,testing:b.yellow,test:b.yellow,validate:b.yellow,verification:b.yellow,staging:b.yellow,check:b.yellow,"follow-up":b.yellow,followup:b.yellow,waiting:b.yellow,blocked:b.yellow,hold:b.yellow,done:b.green,complete:b.green,completed:b.green,success:b.green,ok:b.green,stable:b.green,resolved:b.green,fixed:b.green,closed:b.green,merged:b.green,released:b.green,deployed:b.green,approved:b.green,verified:b.green,working:b.green,healthy:b.green,pass:b.green,passing:b.green,info:b.blue,information:b.blue,note:b.blue,docs:b.blue,documentation:b.blue,doc:b.blue,guide:b.blue,help:b.blue,explanation:b.blue,detail:b.blue,details:b.blue,context:b.blue,design:b.blue,discussion:b.blue,proposal:b.blue,idea:b.blue,feature:b.magenta,enhancement:b.magenta,improvement:b.magenta,refactor:b.magenta,refactoring:b.magenta,cleanup:b.magenta,optimize:b.magenta,optimization:b.magenta,perf:b.magenta,performance:b.magenta,upgrade:b.magenta,migration:b.magenta,modernize:b.magenta,debt:b.magenta,todo:b.cyan,next:b.cyan,planned:b.cyan,plan:b.cyan,future:b.cyan,backlog:b.cyan,investigate:b.cyan,explore:b.cyan,prototype:b.cyan};var jr={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Pi=(e,t,n)=>Math.max(t,Math.min(n,e)),_r=(e,t,n)=>e+(t-e)*n,Li=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Pl=e=>e.toLowerCase().trim(),Ll=(e,t,n)=>{let o=t/100,r=n/100,s=(1-Math.abs(2*r-1))*o,i=e/60,c=s*(1-Math.abs(i%2-1)),u=0,m=0,p=0;i>=0&&i<1?(u=s,m=c):i>=1&&i<2?(u=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<5?(u=c,p=s):(u=s,p=c);let v=r-s/2;return[Math.round((u+v)*255),Math.round((m+v)*255),Math.round((p+v)*255)]},kl=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var Dl=(e,t,n)=>{let o=Pi(n,0,1);return[Math.round(_r(e[0],t[0],o)),Math.round(_r(e[1],t[1],o)),Math.round(_r(e[2],t[2],o))]};var Fl=(e,t,n)=>Dl(e,t,n),wn=e=>{let n=Li(e)%360,o=Ll(n,jr.stringColor.saturation,jr.stringColor.lightness);return kl(o)},re=(e,t=dn)=>{let n=Pl(e);return n&&t[n]?t[n]:wn(n)};var Bl=e=>{let t=jr.gradient.stops,n=Pi(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let o=t.length-1,r=n*o,s=Math.min(Math.floor(r),o-1),i=r-s;return Fl(t[s],t[s+1],i)},xo=e=>Li(e.toLowerCase().trim())/4294967295,ki=e=>{let t=xo(e);return Bl(t)},Ul=e=>{let[t,n,o]=ki(e);return{normal:r=>cn.bgRgb(t,n,o).black(r),cursor:r=>cn.bgRgb(t,n,o).white.bold(r)}},Hr=e=>{let[t,n,o]=ki(e);return{fg:r=>cn.rgb(t,n,o)(r),fgCursor:r=>cn.rgb(t,n,o).inverse(r),bg:r=>cn.bgRgb(t,n,o).black(r),bgCursor:r=>cn.bgRgb(t,n,o).white.bold(r)}},Io=e=>Ul(e).normal(` ${e} `);import{decodeTime as Di}from"ulid";var bo=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:o,ms:r}of n){let s=Math.floor(t/r);if(s>=1)return`${s}${o} ago`}return"just now"},Fi=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())}`},Co=e=>{try{return l("Decoded date",new Date(Di(e)))}catch(t){return a("Decoding failed + "+t.message)}},Vr=e=>{if(!e?.id)return null;try{return Di(e.id)}catch{return null}};var Wl=(e,t)=>e+" ".repeat(Math.max(0,t-Bi(e))),$l=(e,t)=>" ".repeat(Math.max(0,t-Bi(e)))+e,_l=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),jl=(e,t)=>t?e<t?"up":e>t?"down":null:null,Hl=(e,t)=>{let n=I.getNode(e.payload.parent),o=n?Ht.dim.bgBlack(` ${n.title} `):"unknown",r=t.at(-1);if(r&&"parent"in r&&"rank"in r&&r.parent===e.payload.parent){let s=jl(e.payload.rank,r.rank);if(s)return`Moved ${s} in ${o}`}return`Moved issue to ${o}`},Vl=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Ht.bgHex(re(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Ht.bgHex(re(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Ht.hex(re(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Ht.hex(re(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;default:return""}},Gl=e=>{let t=bo(Ol(e));return Ht.gray($l(t,8))},zl=12,Kl=e=>Wl(`${e}`,zl),Ui=(e,t)=>{let n=Gl(e.id),o=Kl(e.userName),r=Ht.dim("\u203A"),s=e.action==="move.node"?Hl(e,t):[_l(e.action),Vl(e)].filter(Boolean).join(" ");return`${o} ${n} ${r} ${s}`};import{createHash as ql}from"node:crypto";var Yl="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Xl=e=>{let t=ql("sha256").update(e).digest(),n=0n;for(let r=0;r<16;r++)n=n<<8n|BigInt(t[r]);let o="";for(let r=0;r<26;r++){let s=BigInt((25-r)*5);o+=Yl[Number(n>>s&31n)]}return o},Se=(e,t)=>Xl(`${e}:virtual:${t}`);var Jl=e=>Se(e,"comments"),Ql=e=>Se(e,"description"),Zl=e=>Se(e,"assignees"),eu=e=>Se(e,"tags"),tu=e=>Se(e,"history"),Gr=({id:e,name:t,parentNodeId:n,rank:o,value:r,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=I.getNode(e);if(!c){let p=I.createNode({...Y.field({id:e,name:t,parentNodeId:n,rank:o,props:{value:r},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:l("Virtual field created",void 0)}if(!Ke(c))return a(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==o||c.props.value!==r||c.readonly!==s||c.childRenderAxis!==i))return l("Virtual field unchanged",void 0);let m=I.updateNode({...c,title:t,parentNodeId:n,rank:o,props:{...c.props,value:r},readonly:s,childRenderAxis:i});return d(m)?m:l("Virtual field updated",void 0)},Oi=({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!1,childRenderAxis:s="horizontal"})=>{let i=I.getNode(e);if(!i){let m=I.createNode({...Y.fieldList({id:e,name:t,parentNodeId:n,rank:o,isVirtual:!0}),readonly:r,childRenderAxis:s});return d(m)?m:l("Virtual field list created",void 0)}if(!Rn(i))return a(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==o||i.readonly!==r||i.childRenderAxis!==s))return l("Virtual field list unchanged",void 0);let u=I.updateNode({...i,title:t,parentNodeId:n,rank:o,readonly:r,childRenderAxis:s});return d(u)?u:l("Virtual field list updated",void 0)},Wi=e=>{let t=Be(qe/4n),n=Be(qe/2n),o=Be(qe*3n/4n),r=Be(qe*7n/8n),s=Be(qe*13n/16n);if(d(t))return t;if(d(n))return n;if(d(o))return o;if(d(r))return r;if(d(s))return s;let i=Gr({id:Ql(e.id),name:oe.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(i))return i;let c=Oi({id:Zl(e.id),name:oe.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(c))return c;let u=Oi({id:eu(e.id),name:oe.TAGS,parentNodeId:e.id,rank:o.value,readonly:!0});if(d(u))return u;let m=Gr({id:Jl(e.id),name:oe.COMMENTS,parentNodeId:e.id,rank:r.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(m))return m;let p=Gr({id:tu(e.id),name:oe.HISTORY,parentNodeId:e.id,rank:s.value,value:nu(e),readonly:!0,childRenderAxis:"vertical"});return d(p)?p:l("Ticket virtual nodes materialized",void 0)},nu=e=>{let t=[...e.log].reverse(),n=new Map;for(let o of t){let r=n.get(o.action)??[];r.push(o.payload),n.set(o.action,r)}return t.map(o=>Ui(o,n.get(o.action)??[])).join(`
|
|
40
|
-
`)};var
|
|
41
|
-
`)){let s=
|
|
42
|
-
`,"utf8"),l("Event persisted",{path:
|
|
43
|
-
${n.map(
|
|
44
|
-
`)}`):(Ou(),C({hasProjectDefinition:!0}),l("State booted successfully",null))}var qt=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),Ao=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}},G=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);var Ye=null,wo=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Ye,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),Ye)return logger.debug("[sync] syncAndReloadState joining existing promise"),Ye;logger.debug("[sync] syncAndReloadState creating promise"),Ye=Wu();try{let e=await Ye;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:g().syncStatus?.status,statusMessageAfterResolve:g().syncStatus?.msg}),d(e)&&g().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),C({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),Ye||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),Ye=null}},Wu=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=sa();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(Ye)return Ye;logger.debug("[sync] syncAndReloadState:start");let t=G("resolveActorId",X());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:d(t)?t.message:"Missing actor id"}),a("Unable to resolve event log path");C({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:g().syncStatus});let n=Gt(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let o=G("syncEpiqWithRemote",await Mo({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!d(o),message:(d(o),o.message)}),d(o))return logger.error("[sync] syncAndReloadState:sync failed",o.message),C({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),Oe(`Unable to sync state. ${o.message}`);let{stateBranchRoot:r}=o.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:r});let s=G("loadMergedEvents",at(r));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(s),message:(d(s),s.message),count:d(s)?void 0:s.value.length}),d(s))return C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:g().syncStatus}),a(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let i=sa();if(i)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:i.message,syncStatus:g().syncStatus}),i;let c=ta(),u=g().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:c,selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id,selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual}),!g().selectedNode?.isVirtual&&!g().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let p=G("bootStateFromEventLog",Kt(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(p),message:(d(p),p.message)}),d(p))return C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:g().syncStatus}),a(`Unable to boot synced state. ${p.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),C({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=G("restoreNavigationAnchor",oa(c));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(m),message:d(m)?m.message:"Navigation restored",selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id}),d(m)?(C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),m):(C({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),l("Synced",!0))},sa=()=>g().mode===f.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),C({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var un=3e3,ia=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<un?null:t},aa=0,Jr,Qr=!1,Dn=!1,Zr=()=>{if(Qr)return!0;let e=Ue();return d(e)?!1:e.value.syncStatus.status==="syncing"},$u=()=>{let e=_().autoSyncIntervalMs??1e4,t=Date.now()-aa;return Math.max(0,e-t)},da=()=>{Jr||(Jr=setTimeout(async()=>{if(Jr=void 0,!!mn()){if(Zr()){Dn=!0;return}Dn=!1,await _u()}},$u()))},_u=async()=>{if(g().readOnly||g().timeMode==="peek")return a("Cannot auto-sync while peeking");if(!mn())return a("Cannot auto-sync before state is initialized");if(Zr())return Dn=!0,a("Sync already in progress");Qr=!0,aa=Date.now(),C({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await wo()}finally{Qr=!1,Dn&&da()}},Po=()=>{mn()&&(Dn=!0,!Zr()&&da())};var Nt=()=>{let e=_(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),o=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&o,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:o}},ca=()=>{let e=He(process.cwd());if(d(e))return!1;let t=It(e.value);return Z(t)},la=e=>e===!0?"on":e===!1?"off":null,ua=e=>e==="on"?!0:e==="off"?!1:null;var ju=e=>e.props.tags??[],Hu=e=>e.props.assignees??[],Fn=e=>ju(e).map(t=>I.getTag(t)).filter(t=>!!t),Bn=e=>Hu(e).map(t=>I.getContributor(t)).filter(t=>!!t),Lo=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!T(n)?a("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Fn(n))},ko=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!T(n)?a("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",Bn(n))};var h={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""};var Vu=/^(\d+)(h|d|w|mo|y)$/,Gu=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,zu=({year:e,month:t,day:n,hour:o=0,minute:r=0})=>{let s=new Date(e,t-1,n,o,r);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===o&&s.getMinutes()===r},Ku=(e,t=new Date)=>{let n=e.match(Vu);if(!n)return null;let[,o,r]=n,s=Number(o);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(r){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},qu=e=>{let t=e.match(Gu);if(!t)return null;let[,n,o,r,s,i]=t,c=Number(n),u=Number(o),m=Number(r),p=s?Number(s):0,v=i?Number(i):0;return zu({year:c,month:u,day:m,hour:p,minute:v})?new Date(c,u-1,m,p,v):null},Do=e=>{let t=e.trim().toLowerCase();return Ku(t)??qu(t)},ma=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Yu=[{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}],pa=(e=Yu)=>{let t=[];for(let{unit:n,from:o,to:r}of e)for(let s=o;s<=r;s++)t.push(`${s}${n}`);return t};var Xu=["BOARD","TICKET","SWIMLANE","COMMENT"],se={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},$e={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Ju=[se.EDITOR,se.VIEW,se.USERNAME,se.AUTOSYNC,se.SYNC_DEBOUNCE_MS,se.LOG_LEVEL],Qu=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[$e.TITLE,$e.DESCRIPTION];case"BOARD":case"SWIMLANE":return[$e.TITLE];case"COMMENT":return[$e.COMMENT];default:return[]}},ts=[String(un),"5000","15000","30000","60000"],Yt=[h.COFFEE,h.EXIT,h.SYNC,h.HELP,h.EXPORT,h.CONFIG],Fo=[h.NEW,h.EDIT,h.DELETE,h.MOVE],es=[h.TAG,h.UNTAG,h.ASSIGN,h.UNASSIGN,h.CLOSE_ISSUE,h.RE_OPEN_ISSUE,h.EDIT,h.COMMENT],ga=[h.FILTER,h.PEEK],Zu={WORKSPACE:[...Yt,...Fo],BOARD:[...ga,...Yt,...Fo],SWIMLANE:[...ga,...Yt,...Fo],TICKET:[...Yt,...Fo,...es],FIELD:[...Yt,...es],FIELD_LIST:[...Yt,...es],TEXT:[...Yt],COMMENT:[h.EDIT,h.DELETE]},em=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],tm=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&T(n)),fa=e=>e.parentNodeId===ie,nm=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:o}=Nt();if(!o)return[h.HELP,h.CONFIG];if(!ca())return[h.HELP,h.INIT];if(t)return[h.HELP,h.PEEK,h.EXPORT,h.CONFIG];let r=e?.context,s=r&&Xu.includes(r),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?Zu[u]:[]))],c=tm({breadCrumb:n,selectedNode:e});return i.filter(u=>u===h.MOVE?!1:u===h.EDIT||u===h.DELETE?s:u===h.UNTAG?!!(c&&Fn(c).length>0):u===h.UNASSIGN?!!(c&&Bn(c).length>0):u===h.RE_OPEN_ISSUE?!!(c&&fa(c)):u===h.CLOSE_ISSUE?!!(c&&!fa(c)):!0)},ae=(e,{contextNode:t,selectedNode:n,readOnly:o,breadCrumb:r}=g())=>{let s=t.context??"WORKSPACE";return{[h.NONE]:nm({breadCrumb:r,readOnly:o,selectedNode:n}),[h.EXIT]:["confirm"],[h.EXPORT]:[],[h.SYNC]:[],[h.INIT]:[],[h.HELP]:[],[h.PEEK]:[...pa(),"now","prev","next"],[h.EDIT]:Qu(n?.context),[h.COMMENT]:[],[h.DELETE]:["confirm"],[h.RE_OPEN_ISSUE]:["confirm"],[h.CLOSE_ISSUE]:["confirm"],[h.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[h.FILTER]:["tag","assignee","description","title","clear"],[h.TAG]:[...new Set([...Object.keys(dn),...I.getExistingTags()])],[h.UNTAG]:[...Lo()?.value?.map(({name:c})=>c)??[]],[h.UNASSIGN]:[...ko()?.value?.map(({name:c})=>c)??[]],[h.ASSIGN]:I.getExistingAssignees(),[h.NEW]:em(s),[h.CONFIG]:[...Ju],[h.COFFEE]:["1","3","5","20","custom"]}[e]??[]};import xa from"chalk";var va=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var Ee=(e,t)=>{let n=e.find(o=>o.context===t);return n!==void 0?l("Found node",n):a("Unable to find node in breadcrumb")};import ya from"chalk";var J=e=>ya.dim(e),he=e=>ya.hex(y.primary)(e),pe=({prefix:e="",wordList:t,postfix:n="",noOfHints:o=100,inputString:r,minLengthForHints:s=1})=>{let i=r.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(v=>v.startsWith(i))].sort((v,S)=>xo(v)-xo(S)).slice(0,o).map(v=>Io(v)).join(" ");return p?`${J(e)}${p}${J(n)}`:""};var Et={None:"none",Invalid:"invalid",Valid:"valid"};var pn=140,om=["BOARD","TICKET","SWIMLANE"],ha=()=>{let e=g().selectedNode;if(!e?.context)return U({message:J("Missing target context")});if(om.includes(e.context))return V();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===Se(t?.parentNodeId??"","comments"))return V()}return U({message:J("Command not available in this context")})},ee="<ENTER> to confirm",V=(e="",t=[])=>({message:J(e),validity:Et.Valid,completionWordList:t}),U=({message:e,completionWordList:t=[]})=>({validity:Et.Invalid,message:e,completionWordList:t}),Uo=e=>e.length===0,Bo=e=>` ${xa.hex("#000").bgHex(re(e))(` ${e} `)} `,ns=({modifier:e})=>{let t="confirm";return e===t?V(ee):U({message:Uo(e)?J("if you are certain, enter ")+Io(t):"",completionWordList:[t]})},rm=({list:e,hint:t,onValue:n})=>({modifier:o,inputString:r})=>e.includes(o)?r.trim().length<1?U({message:J(n)}):V():U({message:Uo(o)?t:"",completionWordList:[...e]}),Xt=({hint:e,onOk:t})=>({modifier:n,inputString:o})=>Uo(n)&&Uo(o)?U({message:e,completionWordList:[]}):V(t??ee),sm=({modifier:e,inputString:t})=>{let n=ae(h.CONFIG);if(!n.includes(e))return U({message:pe({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case se.EDITOR:{let o=[...va];return t.trim()?o.includes(t.trim())?V(ee):U({message:pe({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o}):U({message:pe({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case se.VIEW:{let o=["dense","wide"];return o.includes(t.trim())?V(ee):U({message:pe({prefix:"view... ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case se.USERNAME:return t.trim()?V(ee):U({message:he("Enter a user name. Saved in ")+xa.bgBlack("~/.epiq-global/config.json")});case se.LOG_LEVEL:{let o=["debug","error","info"],r=t.trim();return o.includes(r)?V(ee):U({message:pe({prefix:"one of: ",wordList:[...o],inputString:r,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...o]})}case se.AUTOSYNC:{let o=["on","off"],r=_().autoSync;if(!o.includes(t.trim())){let s=la(r);return U({message:pe({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:o,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:o})}return V(ee)}case se.SYNC_DEBOUNCE_MS:{let o=_().autoSyncIntervalMs,r=ia(t);if(!t.trim()||r===null||r<un){let s=pe({prefix:" examples: ",wordList:ts,minLengthForHints:0,inputString:t});return U({message:he(`provide duration above ${un}ms. current duration: ${o}ms.`)+s,completionWordList:ts})}return V(ee)}default:return U({message:he("Unknown config option"),completionWordList:n})}},im=({modifier:e,inputString:t})=>{let n=ae(h.EDIT);if(!n.length)return U({message:he("Command not available in this context")});if(!n.includes(e)){let o=pe({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return U({message:o||he("Unknown edit option"),completionWordList:n})}switch(e){case $e.COMMENT:return t.trim()?V(ee):U({message:J("write a comment...")});case $e.TITLE:return V(ee);case $e.DESCRIPTION:{let{preferredEditor:o}=_();return o?V(J("<ENTER> to edit in ")+o):U({message:"No editor selected"})}default:return U({message:he("Unknown edit option"),completionWordList:n})}},am={[h.EXPORT]:()=>V(ee+J(", and create export markdown file")),[h.PEEK]:e=>{let t=e.modifier;if(t==="now")return V(ee);let n={message:J("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")};if(t==="prev"||t==="next")return V(ee);let o=t||e.inputString,r=Do(o);if(!o||!r)return U(n);let s=Ee(g().breadCrumb,"BOARD");if(d(s))return U({message:he("Command is not applicable in this context")});let i=Co(s.value.id);return d(i)?U({message:he("Unable to peek: board id is not a valid ULID")}):ma({date:r,horizonDate:i.value})?V(ee):U({message:he(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[h.EXIT]:()=>V(ee+J(" and exit the application")),[h.INIT]:()=>V(ee),[h.PALETTE]:()=>V(ee),[h.FILTER]:e=>{if(e.modifier==="clear")return V(ee);let t=s=>ae(h.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return U({message:pe({wordList:ae(h.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:ae(h.FILTER)});let n=Object.values(g().tags).map(s=>s.name),o=Object.values(g().contributors).map(s=>s.name),r=e.modifier==="tag"?n:e.modifier==="assignee"?o:[];return e.inputString?r.length&&!r.includes(e.inputString.trim())?U({message:pe({prefix:`existing ${e.modifier}s... `,wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r}):V():U({message:pe({prefix:"one of... ",wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r})},[h.NONE]:e=>{let t=ae(h.NONE);return U({message:pe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[h.NEW]:e=>rm({list:ae(h.NEW),hint:pe({wordList:ae(h.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[h.HELP]:()=>V(ee),[h.EDIT]:im,[h.COMMENT]:e=>{let t=Xt({hint:J(`write a comment (max ${pn} char)...`),onOk:J(`(${e.inputString.length}/${pn})`)})(e);return t.validity===Et.Invalid?t:e.inputString.length>pn?V(he("max input exceeded")):t},[h.CONFIG]:sm,[h.DELETE]:e=>{let t=ha();return t.validity==="invalid"?t:ns(e)},[h.CLOSE_ISSUE]:e=>ns(e),[h.RE_OPEN_ISSUE]:e=>ns(e),[h.MOVE]:e=>{let t=ha();return t.validity==="invalid"?t:Xt({hint:pe({prefix:"hey hacker! These commands are blocked for you... ",wordList:ae(h.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[h.TAG]:e=>{let n=I.getExistingTags().slice(0,10).map(Bo).join("");return Xt({hint:n.length?J("create tag or reuse:")+n+J(""):J("create tag ...")})(e)},[h.UNTAG]:e=>{let t=Lo();if(d(t))return U({message:he("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(Bo).slice(0,10);return n.length?Xt({hint:J(" ... ")+n.join("")})(e):U({message:he("Issue has no tags"),completionWordList:[]})},[h.ASSIGN]:e=>{let t=I.getExistingAssignees().map(Bo).slice(0,10);return Xt({hint:J("assignees... ")+t.join("")})(e)},[h.UNASSIGN]:e=>{let t=ko();if(d(t))return U({message:he("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(Bo).slice(0,10);return n.length?Xt({hint:J("remove assignee... ")+n.join("")})(e):U({message:he("Issue has no assignees"),completionWordList:[]})},[h.SYNC]:()=>V(ee),[h.COFFEE]:e=>{let{modifier:t}=e,n=ae(h.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?U({message:J("enter an amount ... "),completionWordList:n.filter(o=>o.startsWith(t))}):Xt({hint:pe({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},Ia=Object.fromEntries(Object.entries(am).map(([e,t])=>[e,{validate:(n,o,r)=>t({modifier:o,command:n,inputString:r})}]));var Oo=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"];var dm=3,cm=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),lm=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let o=n.props;typeof o.description=="string"&&t.push(o.description),typeof o.value=="string"&&t.push(o.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},um=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=dm&&!cm.has(t)&&!/^\d+$/.test(t)),mm=e=>{let t=new Map;for(let s of lm(e))for(let i of um(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),o=new Set(n),r=Oo.filter(s=>!o.has(s));return[...n,...r]},ba=Oo,Ca=-1,Sa=()=>{let e=Ue();if(d(e))return Oo;let t=e.value,n=t.eventLog.length;return n!==Ca&&(ba=mm(t),Ca=n),ba};var Na=e=>Object.values(h).includes(e),Ea=(e,t)=>{let n=e.command??"",{modifier:o,target:r,inputString:s}=e,{message:i,validity:c,completionWordList:u}=Ia[n].validate(n,o,s),m=r==="command"||r==="modifier"?ae(n):Sa(),{mode:p}=g(),v=p===f.COMMAND_LINE?i??"":"",S=[...u,...m];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:v,autoCompletion:t?Ti(e,S):{hint:"",hints:[],remainder:"",overlap:0}}};var Ra=e=>{let t=e.trimStart(),n=gm(t),o=n[0]??"",r=n[1]??"",s=/\s$/.test(e),i=fm(e),c=Na(o)?o:null,u=c!==null,m=o!=="",p=c?ae(c)??[]:[],v=c&&p.includes(r)?r:"",S="word";n.length===0||n.length===1&&!s?S="command":(n.length===1&&s||n.length===2&&!s)&&(S="modifier");let N=s?"":i,E=pm(t,c,v);return{raw:e,trimmedStart:t,words:n,firstWord:o,lastWord:i,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:v,target:S,inputToMatch:N,inputString:E}},pm=(e,t,n)=>{let o=e;return t&&o.startsWith(t)&&(o=o.slice(t.length)),o=o.replace(/^\s+/,""),n&&o.startsWith(n)&&(o=o.slice(n.length),o=o.replace(/^\s+/,"")),o},gm=e=>e.trim()?e.trim().split(/\s+/):[],fm=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as vm}from"react";var gn=e=>e===os||e===":",os=" ",ge={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Et.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},rs=new Set,Ta=()=>{for(let e of rs)e()},ss=e=>(rs.add(e),()=>rs.delete(e)),Xe=e=>{let n=e(ge),o=Ra(n.value),r=n.cursorPosition===n.value.length;ge={...n,commandMeta:Ea(o,r)},Ta()},Un=({message:e,status:t})=>{let n=structuredClone(ge);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,ge=n,Ta(),l(e,null)},is=e=>{Xe(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},as=e=>{Xe(t=>{let{value:n,cursorPosition:o}=t,r=o;if(e==="left"){for(;r>0&&gn(n[r-1]);)r--;for(;r>0&&!gn(n[r-1]);)r--}else{for(;r<n.length&&!gn(n[r]);)r++;for(;r<n.length&&gn(n[r]);)r++}return{...t,cursorPosition:r}})},Aa=()=>{Xe(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}})},wa=()=>{Xe(e=>{let{value:t,cursorPosition:n}=e,o=n;for(;o>0&&gn(t[o-1]);)o--;for(;o>0&&!gn(t[o-1]);)o--;let r=t.slice(n);return{...e,value:t.slice(0,o)+r,cursorPosition:o,commandIsPending:!1}})},Wo=e=>{Xe(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),o=t.value.slice(0,n),r=t.value.slice(n),s=e(o,t.commandMeta.autoCompletion),i=s+r,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},Ma=()=>{Xe(e=>({...e,commandIsPending:!0}))},W=e=>{Xe(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Pa=({addToHistory:e=!0})=>{Xe(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},La=()=>{Xe(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}})},ka=()=>{Xe(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},q=()=>ge,Da=()=>vm(ss,q,q),Fa=()=>{let[e,...t]=ge.value.split(os);return t.join(os).trim()};var x={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",InitCommandPalette:"initCommandPalette",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",EditTitle:"editTitle",EditDescription:"editDescription",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function ym(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function hm(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function xm(e,t,n){let o=g().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:o?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:o?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:o?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:o?n.nextContainer:null}}function Ba(e,t){let n=q();if(e.sequence==="?"&&t!==f.PALETTE)return x.InitCommandPalette;if(e.sequence===":"&&t!==f.COMMAND_LINE)return x.InitCommandLine;if(t===f.MOVE)switch(e.name){case"m":case"return":return x.ConfirmMove}if(t===f.COMMAND_LINE)return Ii(e,n.value);if(t===f.PALETTE)return bi(e,n.value);let o=ym(e)||hm(e);if(o)return Im(o,t);if(e.ctrl&&e.name==="c")return x.Exit;switch(e.name){case"r":return x.EditTitle;case"e":return x.EditDescription;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 _().viewMode==="wide"?x.SetViewDense:x.SetViewWide;case"q":case"escape":return x.Exit;default:return null}}function Im(e,t){let n=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 xm(g().contextNode.childRenderAxis,e,n)}var $o=e=>{let{context:t}=g().contextNode;if(!t)return P.None;switch(e){case h.EXIT:return P.Exit;case h.EXPORT:return P.Export;case h.COFFEE:return P.Coffee;case h.INIT:return P.Init;case h.DELETE:return P.Delete;case h.EDIT:return P.Edit;case h.COMMENT:return P.Comment;case h.HELP:return P.ViewHelp;case h.RE_OPEN_ISSUE:return P.ReopenIssue;case h.CLOSE_ISSUE:return P.CloseIssue;case h.TAG:return P.TagTicket;case h.UNTAG:return P.UntagTicket;case h.ASSIGN:return P.AssignUserToTicket;case h.UNASSIGN:return P.UnassignUserFromTicket;case h.NEW:return P.NewItem;case h.FILTER:return P.Filter;case h.MOVE:return P.Move;case h.PEEK:return P.Peek;case h.CONFIG:return P.Config;case h.SYNC:return P.Sync;default:return P.None}},P={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Config:"config",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",Comment:"comment-issue",Sync:"sync",Export:"export",Coffee:"coffee"};import{ulid as fe}from"ulid";import ed from"node:fs";import Xm from"node:path";import Jm from"react";import{Box as qm}from"ink";import zo from"react";import Pm from"chalk";import{Box as cs,Text as Lm}from"ink";import Qe from"react";import{Text as Ua}from"ink";import Oa,{useEffect as Wa,useState as bm}from"react";var $a={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},xe=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=z(),o=$a[n]??$a.default,[r,s]=bm(0);if(Wa(()=>{s(0)},[o]),Wa(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%o.length)},500);return()=>clearInterval(c)},[e,o]),!e)return Oa.createElement(Ua,null,t);let i=o[r]??o[0]??t;return Oa.createElement(Ua,{color:y.accent,dimColor:r===1},i)};import{Box as ds,Text as Cm}from"ink";import _o from"react";var Je=({children:e=[],height:t,selectedIndex:n,itemHeight:o=1,scrollByOne:r=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),i=Math.max(1,Math.ceil(o)),c=Math.max(1,Math.floor(s/i)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=r?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),v=p+c,S=e.slice(p,v),N=e.length>c,E=s,R=N?Math.max(1,Math.floor(c/e.length*E)):E,M=Math.max(0,E-R),D=Math.max(1,e.length-c),j=N?Math.floor(p/D*M):0;return _o.createElement(ds,{flexDirection:"row",height:s,width:"100%"},_o.createElement(ds,{flexDirection:"column",flexGrow:1,height:s},S),_o.createElement(ds,{flexDirection:"column",width:1,height:E},Array.from({length:E}).map((O,k)=>_o.createElement(Cm,{key:k,color:N&&k>=j&&k<j+R?y.accent:y.secondary},N?"\u2502":" "))))};import{Box as jo,Text as wm}from"ink";import Jt from"react";import{Text as Sm}from"ink";import Nm from"react";var Em=e=>e.toLowerCase().trim(),Rm=(e,t=dn)=>{let n=Em(e);return t[n]?t[n]:wn(n)},Rt=({id:e,isSelected:t})=>{let n=I.getContributor(e);if(n)return Nm.createElement(Sm,{underline:t,color:Rm(n.name)},"@"+n.name)};import{Text as Tm}from"ink";import Am from"react";var fn=({id:e,isSelected:t})=>{let n=I.getTag(e);if(n)return Am.createElement(Tm,{underline:t,backgroundColor:re(n.name),color:y.secondary}," "+n.name+" ")};var _a=({width:e,ticket:t,isSelected:n})=>{let o=e-14,r=ho(St(t.title),o),s=Fn(t),i=Bn(t);return Jt.createElement(jo,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?y.accent:y.secondary,justifyContent:"space-between"},Jt.createElement(jo,{borderBottom:!0},Jt.createElement(jo,{paddingLeft:1,flexDirection:"column"},Jt.createElement(wm,{color:y.primary},r))),Jt.createElement(jo,{flexDirection:"row",paddingLeft:1},s.map(c=>Jt.createElement(fn,{key:c.id,id:c.id})),i.map(c=>Jt.createElement(Rt,{key:c.id,id:c.id}))))};import{Box as Qt,Text as On}from"ink";import Re from"react";var Mm=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,ja=({width:e,ticket:t,isSelected:n,index:o,mode:r})=>{let s=(t.props.tags??[]).map(D=>I.getTag(D)).filter(D=>!!D),i=(t.props.assignees??[]).map(D=>I.getContributor(D)).filter(D=>!!D),c=1,u=s.length*(1+c),m=i.length*(2+c),p=s.map(D=>Re.createElement(Qt,{key:D.id,paddingRight:c},Re.createElement(On,{color:re(D.name)},"\u25A0"))),v=i.map(D=>Re.createElement(Qt,{key:D.id,paddingRight:c},Re.createElement(On,{color:wn(D.name)},"@"+D.name.at(0)))),S=n?y.accent:r===f.MOVE?y.secondary:y.primary,N=4,E=I.getCommentsByIssue(t.id),R=E.length?String(E.length).length+2+c:0,M=E.length?Re.createElement(Qt,{paddingRight:c},Re.createElement(On,{color:y.accent},"[",E.length,"]")):null;return Re.createElement(Qt,{borderBottom:!0,justifyContent:"space-between"},Re.createElement(Qt,null,Re.createElement(Qt,{width:N},n?Re.createElement(xe,{isSelected:n}):Re.createElement(On,{color:"gray",dimColor:!0},o+1)),Re.createElement(On,{wrap:"truncate",color:S},Mm(t.title,e-u-m-R-18))),Re.createElement(Qt,null,p,v,M))};var km=({swimlane:e,isSelected:t,width:n,height:o,isDense:r,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u}=z(),m=u[e.id]??[],p=`${e.title} ${Pm.hex(y.secondary2).dim("("+m.length+")")}`,v=3,S=r?1:4,N=o-v-(r?2:1),E=Qe.createElement(cs,{borderStyle:"round",borderColor:y.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Qe.createElement(xe,{isSelected:t}),Qe.createElement(Lm,{bold:!0,color:t?y.accent:y.primary},p," ",e.readonly?"\u{1F512}":"")),R=(M,D)=>{let j=s&&i===D;return T(M)?r?Qe.createElement(ja,{key:M.id,index:D,width:n,ticket:M,isSelected:j,mode:c}):Qe.createElement(_a,{key:M.id,width:n,ticket:M,isSelected:j}):null};return Qe.createElement(cs,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:1,paddingLeft:1,height:o},E,Qe.createElement(cs,{padding:r?1:0},m.length>0&&Qe.createElement(Je,{selectedIndex:i,height:N,itemHeight:S},m.map(R)),Qe.createElement(xe,{isSelected:s&&i===-1})))},Ha=Qe.memo(km);import{Box as Wn,Text as Qa}from"ink";import Te,{useMemo as Go}from"react";import{Box as Ho,Text as Dm}from"ink";import ct from"react";var Va=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:o}=z(),{title:r}=t,s=t.parentNodeId?I.getNode(t.parentNodeId):void 0,i=s&&T(s)?r===oe.ASSIGNEES?s.props.assignees??[]:r===oe.TAGS?s.props.tags??[]:[]:[];return ct.createElement(Ho,{alignItems:"center",paddingTop:1},ct.createElement(Ho,{minWidth:12},ct.createElement(xe,{isSelected:n}),ct.createElement(Dm,{color:n?y.accent:y.secondary2},r,":")),ct.createElement(Ho,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let m=o.id===t.id&&u===e;return ct.createElement(Ho,{key:`${r}-${c}`,paddingRight:2,minHeight:1},ct.createElement(xe,{isSelected:m}),r===oe.ASSIGNEES?ct.createElement(Rt,{isSelected:m,id:c}):r===oe.TAGS?ct.createElement(fn,{isSelected:m,id:c}):null)})))};import{Box as Vo,Text as ls}from"ink";import lt,{useEffect as Fm,useMemo as Ga}from"react";var Bm="\u2029",za=(e,t)=>`${e}::inline-line::${t}`,us=new Map,Ka=e=>{let t=us.get(e)??[];us.delete(e);for(let n of t)I.deleteNode(n)},Um=(e,t)=>{Ka(e);let n=[];t.forEach((o,r)=>{let s=Be(BigInt(r+1));if(!Z(s))return;let i=I.createNode(Y.text({id:za(e,r),name:`Line ${r+1}`,parentNodeId:e,rank:s.value,props:{value:o},readonly:!0,isVirtual:!0}));Z(i)&&n.push(i.value.id)}),us.set(e,n)},ms=({id:e,label:t,text:n,height:o,selected:r,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=z(),u=Ga(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Ga(()=>u.join("\0"),[u]);Fm(()=>(Um(e,u),()=>{Ka(e)}),[e,m]);let p=S=>String(S).replace(/\r?\n/g,""),v=u.map((S,N)=>{let E=c.id===e&&i===N;return lt.createElement(Vo,{key:za(e,N)},lt.createElement(ls,{color:E?y.primary:y.secondary2,dimColor:!E},`${N+1} `.padStart(5,"\xA0")),lt.createElement(ls,{backgroundColor:E?"gray":void 0},p(S.length?ho(S,s-10):Bm)))});return lt.createElement(Vo,{flexDirection:"column",paddingTop:1},lt.createElement(Vo,null,lt.createElement(xe,{isSelected:r}),lt.createElement(ls,{color:r?y.accent:y.secondary2},t)),lt.createElement(Vo,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1},lt.createElement(Je,{scrollByOne:!0,height:o-3,selectedIndex:i,itemHeight:1},v)))};import{Box as Tt,Text as ut}from"ink";import de,{useEffect as Om,useMemo as Wm,useRef as $m}from"react";import{decodeTime as ps}from"ulid";var qa=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},Ya=(e,t,n)=>Y.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});var _m=e=>Se(e,"comments"),jm=e=>I.getCommentsByIssue(e.id).sort((t,n)=>ps(t.id)-ps(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),Xa=e=>{for(let t of e)I.deleteNode(t.id)},Hm=(e,t)=>{let n=I.getNode(_m(e.id));if(!n||!Ke(n))return[];let o=t.map((r,s)=>Ya(r,s,n.id)).map(I.createNode).filter(Z).map(({value:r})=>r).filter(Tn);return t.length>0&&g().selectedIndex<0&&A.navigate({contextNode:n,selectedIndex:0}),o},Vm=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`};function Ja({ticket:e,width:t,height:n}){let o=Wm(()=>jm(e),[e]),r=$m([]);Om(()=>(Xa(r.current),r.current=Hm(e,o),()=>{Xa(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=z(),c=Math.max(1,n-4),u=Math.max(20,t-8);return o.length===0?de.createElement(Tt,{flexDirection:"column",width:t,height:n,padding:1},de.createElement(ut,{color:y.primary},"No comments yet."),de.createElement(Tt,{paddingTop:1},de.createElement(ut,{color:y.primary},"Use"),de.createElement(ut,{color:y.accent}," :comment "),de.createElement(ut,{color:y.primary},"to add the first one."))):de.createElement(Tt,{flexDirection:"column",width:t,height:n},de.createElement(Tt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},de.createElement(ut,{color:y.secondary2},"Comments (",o.length,") ")),de.createElement(Je,{height:c,itemHeight:4,selectedIndex:s},o.map((m,p)=>{let v=p===s;return de.createElement(Tt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},de.createElement(Tt,{flexDirection:"row",paddingBottom:1},de.createElement(ut,{color:y.accent},v?"\u276F ":" "),de.createElement(Tt,{paddingLeft:1},de.createElement(ut,{color:y.secondary2},`#${p+1} `),de.createElement(Rt,{id:m.authorId}),de.createElement(ut,{color:y.secondary2}," "+bo(ps(m.id))))),de.createElement(Tt,{paddingLeft:3,paddingBottom:1},de.createElement(ut,{color:y.primary},Vm(m.md,u))))})))}var Gm=e=>Se(e,"description"),zm=e=>Se(e,"comments"),Km=e=>Se(e,"history"),Za=({ticket:e,height:t})=>{let n=Go(()=>qa(e),[e]),{selectedIndex:o,contextNode:r}=z(),s=process.stdout.columns||120,i=Go(()=>Gm(e.id),[e.id]),c=Go(()=>zm(e.id),[e.id]),u=Go(()=>Km(e.id),[e.id]),m=r.id===e.id,p=r.id===c||r.parentNodeId===c,v=r.id===u||r.parentNodeId===u,S=$(e.id);if(p){let k=t-3;return Te.createElement(Wn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Te.createElement(Ja,{ticket:e,width:s,height:k}))}if(v){let O=I.getNode(u),k=O&&Ke(O)?O.props.value??"":"",ft=t-3;return Te.createElement(Wn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},O?Te.createElement(ms,{id:O.id,label:"Event log",text:k,selected:!1,maxWidth:s,height:ft}):null)}let N=S.reduce((O,k)=>Rn(k)||k.id===c||k.id===u?O+1:O,0),E=2,R=3,M=N,D=t-R-M-E,j=(O,k)=>O.id===i?Te.createElement(ms,{key:O.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:k,maxWidth:s,height:D}):Rn(O)?Te.createElement(Va,{key:O.id,parent:O,selected:k,selectedIndex:o}):O.id===c?Te.createElement(Wn,{key:O.id,paddingTop:1},Te.createElement(xe,{isSelected:k}),Te.createElement(Qa,{backgroundColor:y.secondary,color:k?y.accent:y.primary},` Comments (${n}) \u203A\u203A `)):O.id===u?Te.createElement(Wn,{key:O.id,paddingTop:1},Te.createElement(xe,{isSelected:k}),Te.createElement(Qa,{backgroundColor:y.secondary,color:k?y.accent:y.primary}," History \u203A\u203A ")):null;return Te.createElement(Wn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},S.map((O,k)=>j(O,m&&o===k)))};var Ym=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,viewMode:s,height:i,width:c})=>{let u=t.context,m=u===w.TICKET||u===w.FIELD_LIST||u===w.FIELD,p=u===w.BOARD||u===w.SWIMLANE,v=u===w.TICKET?t:o.find(M=>M.context===w.TICKET),S=Math.floor(c/3),N=Math.floor(c/Math.max(e.length,1)),E=Math.min(N,S),R=s==="dense";return zo.createElement(qm,{flexDirection:"row",height:i},p&&e.map((M,D)=>{let j=t.id===M.id,O=j?n:-1,k=t.context===w.BOARD&&n===D;return zo.createElement(Ha,{key:M.id,height:i,width:E,swimlane:M,isSelected:k,isDense:R,isFocused:j,listSelectedIndex:O,mode:r})}),m&&v&&zo.createElement(Za,{height:i,ticket:v}))},Ko=zo.memo(Ym);import{render as Qm}from"ink";import{Writable as Zm}from"node:stream";var $n=e=>String(e).padStart(2,"0"),ep=e=>{let t=e.getUTCFullYear(),n=$n(e.getUTCMonth()+1),o=$n(e.getUTCDate()),r=$n(e.getUTCHours()),s=$n(e.getUTCMinutes()),i=$n(e.getUTCSeconds());return`${t}-${n}-${o}_${r}-${s}-${i}`},tp=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",np=async(e,{width:t,height:n})=>{let o="",r=new Zm({write(i,c,u){let m=op(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(o=m),u()}});r.columns=t,r.rows=n,r.isTTY=!0;let s=Qm(e,{stdout:r,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),o},op=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),td=async()=>{let{viewMode:e}=_(),{contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,renderedChildrenIndex:s}=g(),i=o.find(D=>D.context==="BOARD");if(!i)return a("No board found to export");let c=120,u=40,m=await np(Jm.createElement(Ko,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(D=>D!==void 0&&Ct(D)),contextNode:t,selectedIndex:n,breadCrumb:o,viewMode:e??"dense",mode:r}),{width:c,height:u});if(!m)return a("Failed to render board export");let p=ro(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let v=new Date,S=ep(v),N=`board_${tp(i.title)}_${S}.md`,E=Gs(p.value);ed.mkdirSync(E,{recursive:!0});let R=Xm.join(E,N),M=`# Board - ${i.title}
|
|
6
|
+
`;Mn.writeFileSync(e,r,"utf8")}function zo(e,t,n=!1){let r=yi();if(!r)return;let o=$l.format(...t),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
7
|
+
`;Mn.mkdirSync(qo.dirname(r),{recursive:!0}),Mn.appendFileSync(r,c,"utf8"),Go++,Go>=Wl&&(Go=0,Hl())}var Ko=()=>vi()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",re={info(...e){let t=Ko();(t==="info"||t==="debug")&&zo("[Info]",e,!1)},debug(...e){Ko()==="debug"&&zo("[Debug]",e,!0)},error(...e){let t=Ko();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;zo("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=re;import{spawn as jl}from"node:child_process";import gr from"node:fs";import Pn from"node:path";var oe={stage:({cwd:e,pathspec:t})=>U({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>U({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>U({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>U({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>U({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push",...r?["-u"]:[],t,n]:["push"];return U({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>U({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>U({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>U({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>U({args:["worktree","prune"],cwd:e})};var dn=e=>{let t=Ke(e);if(d(t))return a("Unable to resolve epiq project root");let n=Ct(t.value);return d(n)?a("Unable to read project.json"):l("Resolved state branch",n.value.stateBranch)},Oe="origin";var hi=1e4,Vl={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Ii=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!gr.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:p,exitCode:1});return}r(a(p));return}let o=jl("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Vl}),s=!1,i="",c="",u=p=>{s||(s=!0,clearTimeout(m),r(p))},m=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${hi}ms`].join(`
|
|
8
|
+
`);u(n?{stdout:i,stderr:p,exitCode:124}:a(p))},hi);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{i+=p}),o.stderr.on("data",p=>{c+=p}),o.on("error",p=>{if(n){u({stdout:i,stderr:p.message,exitCode:1});return}u(a([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
|
|
9
|
+
`)))}),o.on("close",p=>{let v=p??1;if(n){u({stdout:i,stderr:c,exitCode:v});return}if(v!==0){u(a([`git ${e.join(" ")}`,c.trim()||i.trim()||"Git command failed"].filter(Boolean).join(`
|
|
10
|
+
`)));return}u(l("Git command succeeded",{stdout:i,stderr:c,exitCode:v}))})}),U=({args:e,cwd:t})=>Ii({args:e,cwd:t,allowFail:!1}),Xe=({args:e,cwd:t})=>Ii({args:e,cwd:t,allowFail:!0}),cn=async({cwd:e,message:t})=>{let n=await oe.commit({cwd:e,message:t});if(d(n))return a(`Failed to create commit
|
|
11
|
+
${n.message}`);let r=await U({args:["rev-parse","HEAD"],cwd:e});return d(r)?a(`Commit created, but failed to read HEAD SHA
|
|
12
|
+
${r.message}`):l("Created commit and resolved SHA",r.value.stdout.trim())},Gl=async e=>{let t=await U({cwd:e,args:["rev-parse","--git-dir"]});if(d(t))return a(t.message);let n=t.value.stdout.trim();return l("Resolved git dir",Pn.isAbsolute(n)?n:Pn.resolve(e,n))},zl=async e=>{let t=await Gl(e);if(d(t))return a(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(r))if(gr.existsSync(Pn.join(n,s)))return l("Checked for in-progress Git operation",i);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,i]of Object.entries(o))if(gr.existsSync(Pn.join(n,s)))return l("Checked for in-progress Git operation",i);return l("Checked for in-progress Git operation",null)},vr=async e=>{let t=await zl(e);return d(t)?a(t.message):l("Checked for in-progress Git operation",t.value!==null)},Yo=async({repoRoot:e})=>{let n=(await Xe({args:["remote","get-url",Oe],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},yr=async({repoRoot:e,branch:t})=>{let n=await Xe({args:["ls-remote","--heads",Oe,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${Oe}/${t}`):l("Checked remote branch",n.stdout.trim().length>0)},hr=async({repoRoot:e,branch:t})=>{let n=await Xe({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?l("Local branch exists",!0):n.exitCode===1?l("Local branch missing",!1):a(n.stderr.trim()||`Unable to inspect branch ${t}`)},xi=e=>{try{return gr.realpathSync.native(e)}catch{return Pn.resolve(e)}},bi=async({repoRoot:e,worktreeRoot:t})=>{let n=await U({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=xi(t),o=n.value.stdout.split(`
|
|
13
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(xi).includes(r);return l("Checked worktree registration",o)},Xo=async e=>{let t=await Xe({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},xr=async e=>{let t=await U({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?a(t.message):l("Resolved current branch",t.value.stdout.trim())},Ci=async e=>{let t=await U({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?a(t.message):l("Resolved short HEAD sha",t.value.stdout.trim())},Si=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Kl=async e=>(await Xe({cwd:e,args:["rebase","--abort"]})).exitCode===0?l("Aborted stale rebase",!0):l("No rebase to abort",!1);var Jo=async({cwd:e,branch:t})=>{let n=await yr({repoRoot:e,branch:t});if(d(n))return a(n.message);if(!n.value)return l("Remote branch missing, skipped pull",!1);let r=await Kl(e);if(d(r))return a(r.message);let o=await oe.fetch({cwd:e,remote:Oe,branch:t});if(d(o))return a(`Failed to fetch ${t}
|
|
14
|
+
${o.message}`);let s=await oe.pullRebase({cwd:e,remote:Oe,branch:t});return d(s)?a(`Failed during pull --rebase
|
|
15
|
+
${s.message}`):l("Pulled with rebase",!0)},Ei=async e=>{let t=await Xe({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?l("No staged changes",!1):t.exitCode===1?l("Has staged changes",!0):a(t.stderr.trim()||"Unable to inspect staged changes")};var Ni=async e=>{let t=await xr(e);return d(t)?a(t.message):l("Checked detached HEAD state",t.value==="HEAD")};var Ai="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Zo=e=>Je.join(ut,lr,e),Ti=()=>Je.join(ql.homedir(),Ue),Ir=()=>Je.join(Ti(),"worktrees"),Te=({repoRoot:e})=>{let t=pi(e);return d(t)?a(t.message):l("Resolved state branch root",Je.join(Ir(),t.value))},Yl=e=>Je.join(e,ut),Ri=e=>Je.join(Yl(e),lr);var Ln=e=>{try{return Qo.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},br=()=>{let e=Ln(Ti());if(d(e))return a(`Ensure epiq home failed.
|
|
16
|
+
`+e.message);let t=Ln(Ir());return d(t)?a(`Ensure worktrees dir failed.
|
|
17
|
+
`+t.message):l("Ensured epiq storage",!0)},wi=e=>{Qo.existsSync(e)&&(re.debug("[sync] remove path",e),Qo.rmSync(e,{recursive:!0,force:!0}))};var Mi=(e,t)=>{for(let n of[Ri(e),Ri(t)]){let r=Ln(n);if(d(r))return a(r.message)}return l("Ensured state branch",void 0)},Pi=async e=>{let t=await U({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return a(`ensure state branch is storage only failed
|
|
18
|
+
`+t.message);let r=t.value.stdout.trim().split(`
|
|
19
|
+
`).filter(Boolean).filter(i=>i!==ut);if(r.length===0)return l("State branch is storage-only",!1);let o=await U({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return a(`Failed to clean storage branch
|
|
20
|
+
${o.message}`);let s=await cn({cwd:e,message:"[epiq:repair-storage-branch]"});return d(s)?a(s.message):l("Cleaned storage branch",!0)},Ye=Vo(async(e=process.cwd())=>{let t=await U({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?a("Not inside a Git repository"):l("Resolved repo root",t.value.stdout.trim())},e=>Je.resolve(e)),ay=Vo(async e=>{let t=await U({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return a(t.message);let n=t.value.stdout.trim(),r=Je.isAbsolute(n)?n:Je.join(e,n);return l("Resolved git dir",r)},e=>Je.resolve(e));import ln from"node:fs";import kn from"node:path";var ki=async e=>{if((await Xe({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return l("Initial commit already exists",!1);re.info("Creating initial commit");let n=await oe.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?a(n.message):l("Created initial commit",!0)},Li=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Xl=async e=>{let t=await xr(e);if(d(t))return a(t.message);let n=await Ci(e);return d(n)?a(n.message):l("Built sync commit message",`[sync|branch:${Li(t.value)}:sha:${Li(n.value)}]`)},es=async({repoRoot:e,stateBranchName:t})=>{re.info(`Creating ${t}`);let n=await U({args:["commit-tree",Ai,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return a(`Failed to create state branch commit
|
|
21
|
+
${n.message}`);let r=n.value.stdout.trim(),o=await U({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return d(o)?a(`Failed to create ${t}
|
|
22
|
+
${o.message}`):l("Created state branch",!0)},Jl=async({repoRoot:e,stateBranchName:t})=>{let n=await Yo({repoRoot:e});if(d(n))return a(`Ensure local state branch failed
|
|
23
|
+
`+n.message);let r=n.value,o=r?await yr({repoRoot:e,branch:t}):l("No remote, no remote state branch",!1);if(d(o))return a(`Ensure local state branch failed
|
|
24
|
+
`+o.message);let s=o.value;if(r&&s){let c=await oe.fetch({cwd:e,remote:Oe,branch:t});if(d(c))return a(`Failed to fetch ${t} from remote
|
|
25
|
+
${c.message}`)}let i=await hr({repoRoot:e,branch:t});if(d(i))return a(`Ensure local state branch failed
|
|
26
|
+
`+i.message);if(i.value)return l("Local state branch already exists",!1);if(s){let c=await U({args:["branch","--track",t,`${Oe}/${t}`],cwd:e});return d(c)?a(`Failed to create local ${t} from remote
|
|
27
|
+
${c.message}`):l("Created local state branch from remote",!0)}return es({repoRoot:e,stateBranchName:t})},Ql=async({repoRoot:e,branch:t})=>{let n=await U({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=n.value.stdout.split(`
|
|
28
|
+
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return l("Found worktree for branch",o)}return l("No worktree found for branch",null)},Zl=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Ln(kn.dirname(t));if(d(r))return a(`Failed to create state branch worktree
|
|
29
|
+
`+r.message);ln.existsSync(t)&&!ln.existsSync(kn.join(t,".git"))&&(re.info("Removing broken state branch worktree path"),wi(t)),re.info("Creating state branch worktree");let o=await oe.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(o)?a(`Failed to create state branch worktree
|
|
30
|
+
${o.message}`):l("Created state branch worktree",!0)},Vt=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await Ql({repoRoot:e,branch:n});if(d(r))return a(r.message);let o=kn.resolve(t),s=r.value?kn.resolve(r.value):null;if(s&&s===o&&ln.existsSync(s))return l("State branch already checked out in expected worktree",!1);if(s&&s!==o){re.info("Moving state branch worktree to expected location");let u=await oe.worktreeRemove({cwd:e,worktreeRoot:s});if(d(u))return a(`Failed to remove existing state branch worktree
|
|
31
|
+
${u.message}`)}if(s&&!ln.existsSync(s)){re.info("Pruning stale state branch worktree");let u=await oe.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
|
|
32
|
+
${u.message}`)}let i=await bi({repoRoot:e,worktreeRoot:t});if(d(i))return a(i.message);let c=ln.existsSync(t);if(i.value&&c)return l("State branch worktree already exists",!1);if(i.value&&!c){re.info("Pruning missing registered state branch worktree");let u=await oe.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
|
|
33
|
+
${u.message}`)}return Zl({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},eu=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await xr(e);if(d(n))return a(n.message);if(n.value===t)return l("State branch already checked out",!1);(await Xe({cwd:e,args:["rebase","--abort"]})).exitCode===0&&re.info("Aborted stale state branch rebase");let o=await oe.checkout({cwd:e,branch:t});return d(o)?a(`Failed to checkout ${t}
|
|
34
|
+
${o.message}`):l("Checked out state branch",!0)},tu=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Xo(t);if(d(n))return a(n.message);if(n.value)return l("State branch upstream already configured",!1);let r=await Yo({repoRoot:t});if(d(r))return a(r.message);if(!r.value)return l("No remote available for state branch upstream",!1);let o=dn(e);if(d(o))return o;let s=o.value,i=await yr({repoRoot:t,branch:s});if(d(i))return a(i.message);if(!i.value)return l("Remote state branch missing; upstream will be configured on first push",!1);re.info(`Configuring ${s} upstream`);let c=await oe.fetch({cwd:t,remote:Oe,branch:s});if(d(c))return a(`Failed to fetch ${s}
|
|
35
|
+
${c.message}`);let u=await oe.setUpstream({cwd:t,branch:s,upstream:`${Oe}/${s}`});return d(u)?a(`Failed to set state branch upstream
|
|
36
|
+
${u.message}`):l("Configured state branch upstream",!0)},Cr=async({stateBranchRoot:e,eventFileName:t})=>{let n=Zo(t),r=kn.join(e,n);if(!ln.existsSync(r))return l("No event file to stage",void 0);let o=await oe.stage({cwd:e,pathspec:[n]});return d(o)?a(`Failed to stage state branch event file
|
|
37
|
+
${o.message}`):l("Staged state branch event file",void 0)},Di=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Xl(e);return d(n)?a(`Create state branch sync commit failed
|
|
38
|
+
`+n.message):cn({cwd:t,message:n.value})},Dn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Xo(t);if(d(n))return a(n.message);let r=dn(e);if(d(r))return r;let o=r.value,s=n.value?await oe.push({cwd:t}):await oe.push({cwd:t,remote:Oe,branch:o,setUpstream:!0});return d(s)?a(`Failed during state branch push
|
|
39
|
+
${s.message}`):l("Pushed state branch",!0)},Fi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=dn(e);if(d(o))return o;let s=o.value,i=[br(),await Jl({repoRoot:e,stateBranchName:s}),await Vt({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await eu({stateBranchRoot:t,stateBranchName:s}),await Pi(t),n?await tu({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(d(c))return a(c.message);r=r||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{WebSocket as nu}from"ws";var Sr=new Set,Bi=e=>{Sr.add(e),e.on("close",()=>{Sr.delete(e)}),e.on("error",()=>{Sr.delete(e)})},Gt=e=>{let t=JSON.stringify(e);for(let n of Sr)n.readyState===nu.OPEN&&n.send(t)};import{useSyncExternalStore as Pf}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function ts(e){return e.context===P.WORKSPACE}function w(e){return e.context===P.TICKET}function St(e){return e.context===P.TEXT}function Qe(e){return e.context===P.FIELD}function Fn(e){return e.context===P.FIELD_LIST}var Et=e=>e.context===P.SWIMLANE,Er=e=>e.context===P.BOARD,Bn=e=>e.context===P.COMMENT;var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var Ui=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Oi=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",_i=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",$i=(e,t)=>{if(Oi(e,e.sequence))return h.MoveCursorLeftOfWord;if(_i(e,e.sequence))return h.MoveCursorRightOfWord;if(Ui(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.GetLastCommandFromHistory;case"down":return h.GetNextCommandFromHistory;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}},Wi=(e,t)=>{if(Oi(e,e.sequence))return h.MoveCursorLeftOfWord;if(_i(e,e.sequence))return h.MoveCursorRightOfWord;if(Ui(e,e.sequence))return h.EraseInputWord;switch(e.name){case"tab":return h.AutoCompleteCommand;case"up":return h.NavPreviousItem;case"down":return h.NavNextItem;case"left":return h.MoveCursorLeft;case"right":return h.MoveCursorRight;case"return":return h.Confirm;case"backspace":return t?h.EraseInput:h.ExitCommandLine;case"escape":return h.ExitCommandLine;default:return h.CaptureInput}};function Nr(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var un=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Nt=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Hi=e=>e.charAt(0).toUpperCase()+e.slice(1);var ji=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},Vi=(e,t)=>t?e.get(t)??[]:[];var Gi=new WeakMap,ru=e=>{let t=Gi.get(e);return t||(t=ji(e),Gi.set(e,t)),t};var zi=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Vi(ru(e),r).filter(s=>Nr(r,s)>=n)};var ou={hint:"",hints:[],overlap:0,remainder:""},Ki=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return ou;let o=zi({wordList:r,inputToMatch:e,overlapThreshold:1});return su(t,o)},su=(e,t)=>{let n=t[0]??"",r=Nr(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,c=!!s,p=(c&&i?o:n)+(c&&i?":":" "),v=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:v}};import{useSyncExternalStore as iu}from"react";var Un={logLevel:"info",autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},ns=new Set,au=()=>{for(let e of ns)e()},H=()=>Un,qi=()=>iu(e=>(ns.add(e),()=>{ns.delete(e)}),()=>Un),_e=e=>(Un={...Un,...e},au(),Un);import{ulid as lu}from"ulid";var mn=24n,du=mn*4n,Ze=(1n<<du)-1n,cu=/^[0-9a-f]+$/;function Yi(e){return!e||!cu.test(e)?a(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function $e(e,t=mn){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Ee(e,t){if(!e&&!t)return $e(Ze/2n,mn);let n=e?Yi(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?Yi(t):l("Resolved upper bound",Ze);if(d(r))return r;let o=n.value,s=r.value;if(s<=o)return $e(Ze/2n,mn);let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):$e(i,mn)}function Xi(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Ze*BigInt(r+1)/(t+1n),s=$e(o,mn);if(d(s))return s;n.push(s.value)}return l("Resolved evenly spaced ranks",n)}var rs=(e,t)=>{let n=z(e),r=Xi(n.length);if(d(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],c=r.value[s];if(!i||!c)return a("Unable to assign rebalance rank");o[i.id]=c}return l("Created rebalance event",{id:lu(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as cm}from"ulid";var mt=(e,t)=>{let{nodes:n}=f(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return l("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return l("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},os=(e,t)=>{let{nodes:n}=f(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},zt=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:a("Node not found"),b={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.userId&&n.userId!==t)return a("Contributor is already linked to another user");let r={...n,userId:t},o=fe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return d(o)?a("Unable to link contributor to user"):l("Linked contributor to user",r)},deleteNode(e){fe(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create comment, missing issue");if(!w(t))return a("Can only comment on issues");let n=fe(r=>({...r,comments:{...r.comments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create comment"):l("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return a("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return a("Unable to edit comment, missing issue");if(!w(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=fe(i=>({...i,comments:{...i.comments??{},[e]:o}}));return d(s)?a("Unable to edit comment"):l("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return a("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=fe(o=>({...o,comments:{...o.comments??{},[e]:n}}));return d(r)?a("Unable to delete comment"):l("Deleted comment",n)},getComment(e){return f().comments?.[e]},getCommentsByIssue(e){return Object.values(f().comments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=f(),r=n[e];if(!r)return a("Edit target node not found");let o=zt(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return a("Rename target node not found");let r=zt(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return z(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=f(),o=this.getNode(e),s=this.getNode(t);if(!o)return a("Node not found");if(!s)return a("Target parent not found");if(r===e)return a("Cannot move root node");if(e===t)return a("Cannot move node into itself");let i=zt(o,"move");if(i)return i;if(os(t,e))return a("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=f(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=new Set,i=u=>{let m=t[u];if(!(!m||s.has(u))){s.add(u);for(let p of z(m.id))i(p.id)}};i(e);let c={...structuredClone(t)};for(let u of s){if(!c[u])return a("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(C({nodes:c}),l("Successfully tomb stoned",o)):a("Unable to delete undefined")},createContributor(e){let t=fe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):l("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to assign contributor, missing contributor");if(!r)return a("Unable to assign contributor, missing target");let o=zt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return a("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),l("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to unassign, missing contributor");if(!r)return a("Unable to unassign, missing target");let o=zt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return l("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),l("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to add tag, missing tag");if(!r)return a("Unable to add tag, missing target");let o=zt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return a("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),l("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to remove tag, missing tag");if(!r)return a("Unable to remove tag, missing target");let o=zt(r,"edit");if(o)return o;if(!w(r))return a("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return l("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),l("Tag removed",{tag:t})},createTag(e){let t=fe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):l("Tag created",e)},createNode(e){let t=fe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?a("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=fe(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):l("Locked node",n)},updateNode(e){let t=fe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return f().contributors[e]},getTag(e){return f().tags[e]},getNode(e){return f().nodes[e]},getSiblings(e){return z(e)}};var se={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments"};var Q={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};import Kt from"chalk";import ra from"string-width";import{decodeTime as vu}from"ulid";import fn from"chalk";var ge={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},y={accent:ge.cyan,accent2:ge.magenta,primary:ge.white,secondary:ge.grayDark,secondary2:ge.grayLight,gray:ge.gray,green:ge.green,yellow:ge.yellow,red:ge.red};var S={red:ge.red,yellow:ge.yellow,green:ge.green,blue:ge.blue,magenta:ge.magenta,cyan:ge.cyan},pn={urgent:S.red,critical:S.red,important:S.red,blocker:S.red,asap:S.red,immediate:S.red,fail:S.red,failure:S.red,broken:S.red,bug:S.red,error:S.red,incident:S.red,outage:S.red,production:S.red,crash:S.red,security:S.red,warning:S.yellow,warn:S.yellow,risky:S.yellow,risk:S.yellow,attention:S.yellow,pending:S.yellow,review:S.yellow,"needs-review":S.yellow,qa:S.yellow,testing:S.yellow,test:S.yellow,validate:S.yellow,verification:S.yellow,staging:S.yellow,check:S.yellow,"follow-up":S.yellow,followup:S.yellow,waiting:S.yellow,blocked:S.yellow,hold:S.yellow,done:S.green,complete:S.green,completed:S.green,success:S.green,ok:S.green,stable:S.green,resolved:S.green,fixed:S.green,closed:S.green,merged:S.green,released:S.green,deployed:S.green,approved:S.green,verified:S.green,working:S.green,healthy:S.green,pass:S.green,passing:S.green,info:S.blue,information:S.blue,note:S.blue,docs:S.blue,documentation:S.blue,doc:S.blue,guide:S.blue,help:S.blue,explanation:S.blue,detail:S.blue,details:S.blue,context:S.blue,design:S.blue,discussion:S.blue,proposal:S.blue,idea:S.blue,feature:S.magenta,enhancement:S.magenta,improvement:S.magenta,refactor:S.magenta,refactoring:S.magenta,cleanup:S.magenta,optimize:S.magenta,optimization:S.magenta,perf:S.magenta,performance:S.magenta,upgrade:S.magenta,migration:S.magenta,modernize:S.magenta,debt:S.magenta,todo:S.cyan,next:S.cyan,planned:S.cyan,plan:S.cyan,future:S.cyan,backlog:S.cyan,investigate:S.cyan,explore:S.cyan,prototype:S.cyan};var is={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Ji=(e,t,n)=>Math.max(t,Math.min(n,e)),ss=(e,t,n)=>e+(t-e)*n,Qi=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},uu=e=>e.toLowerCase().trim(),mu=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,c=s*(1-Math.abs(i%2-1)),u=0,m=0,p=0;i>=0&&i<1?(u=s,m=c):i>=1&&i<2?(u=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<5?(u=c,p=s):(u=s,p=c);let v=o-s/2;return[Math.round((u+v)*255),Math.round((m+v)*255),Math.round((p+v)*255)]},Zi=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var pu=(e,t,n)=>{let r=Ji(n,0,1);return[Math.round(ss(e[0],t[0],r)),Math.round(ss(e[1],t[1],r)),Math.round(ss(e[2],t[2],r))]};var fu=(e,t,n)=>pu(e,t,n),On=e=>{let n=Qi(e)%360,r=mu(n,is.stringColor.saturation,is.stringColor.lightness);return Zi(r)},ie=(e,t=pn)=>{let n=uu(e);return n&&t[n]?t[n]:On(n)};var ea=e=>{let t=is.gradient.stops,n=Ji(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,s=Math.min(Math.floor(o),r-1),i=o-s;return fu(t[s],t[s+1],i)},Rr=e=>Zi(ea(e)),Ar=e=>Qi(e.toLowerCase().trim())/4294967295,ta=e=>{let t=Ar(e);return ea(t)},gu=e=>{let[t,n,r]=ta(e);return{normal:o=>fn.bgRgb(t,n,r).black(o),cursor:o=>fn.bgRgb(t,n,r).white.bold(o)}},as=e=>{let[t,n,r]=ta(e);return{fg:o=>fn.rgb(t,n,r)(o),fgCursor:o=>fn.rgb(t,n,r).inverse(o),bg:o=>fn.bgRgb(t,n,r).black(o),bgCursor:o=>fn.bgRgb(t,n,r).white.bold(o)}},Tr=e=>gu(e).normal(` ${e} `);import{decodeTime as na}from"ulid";var wr=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"},Mr=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())}`},Pr=e=>{try{return l("Decoded date",new Date(na(e)))}catch(t){return a("Decoding failed + "+t.message)}},gn=e=>{if(!e?.id)return null;try{return na(e.id)}catch{return null}};var yu=(e,t)=>e+" ".repeat(Math.max(0,t-ra(e))),hu=(e,t)=>" ".repeat(Math.max(0,t-ra(e)))+e,oa=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),xu=(e,t)=>t?e<t?"up":e>t?"down":null:null,Iu=(e,t)=>{let n=b.getNode(e.payload.parent),r=n?Kt.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=xu(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},bu=e=>{switch(e.action){case"add.issue.tag":{let t=f().tags[e.payload.tag];return t?Kt.bgHex(ie(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?Kt.bgHex(ie(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?Kt.hex(ie(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?Kt.hex(ie(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""}},Cu=e=>{let t=wr(vu(e));return Kt.gray(hu(t,8))},Su=12,Eu=e=>yu(`${e}`,Su),Nu=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?t.name:""}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}"`:"";case"move.node":{let t=b.getNode(e.payload.parent);return t?`to ${t.title}`:""}default:return""}},sa=e=>[oa(e.action),Nu(e)].filter(Boolean).join(" "),ia=(e,t)=>{let n=Cu(e.id),r=Eu(e.userName),o=Kt.dim("\u203A"),s=e.action==="move.node"?Iu(e,t):[oa(e.action),bu(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};import{createHash as Ru}from"node:crypto";var Au="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Tu=e=>{let t=Ru("sha256").update(e).digest(),n=0n;for(let o=0;o<16;o++)n=n<<8n|BigInt(t[o]);let r="";for(let o=0;o<26;o++){let s=BigInt((25-o)*5);r+=Au[Number(n>>s&31n)]}return r},Ne=(e,t)=>Tu(`${e}:virtual:${t}`);var wu=e=>Ne(e,"comments"),Mu=e=>Ne(e,"description"),Pu=e=>Ne(e,"assignees"),Lu=e=>Ne(e,"tags"),ku=e=>Ne(e,"history"),ds=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=b.getNode(e);if(!c){let p=b.createNode({...Q.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:l("Virtual field created",void 0)}if(!Qe(c))return a(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==i))return l("Virtual field unchanged",void 0);let m=b.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:i});return d(m)?m:l("Virtual field updated",void 0)},aa=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=b.getNode(e);if(!i){let m=b.createNode({...Q.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return d(m)?m:l("Virtual field list created",void 0)}if(!Fn(i))return a(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return l("Virtual field list unchanged",void 0);let u=b.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return d(u)?u:l("Virtual field list updated",void 0)},da=e=>{let t=$e(Ze/4n),n=$e(Ze/2n),r=$e(Ze*3n/4n),o=$e(Ze*7n/8n),s=$e(Ze*13n/16n);if(d(t))return t;if(d(n))return n;if(d(r))return r;if(d(o))return o;if(d(s))return s;let i=ds({id:Mu(e.id),name:se.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(i))return i;let c=aa({id:Pu(e.id),name:se.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(c))return c;let u=aa({id:Lu(e.id),name:se.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(d(u))return u;let m=ds({id:wu(e.id),name:se.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(m))return m;let p=ds({id:ku(e.id),name:se.HISTORY,parentNodeId:e.id,rank:s.value,value:Du(e),readonly:!0,childRenderAxis:"vertical"});return d(p)?p:l("Ticket virtual nodes materialized",void 0)},Du=e=>{let t=[...e.log].reverse(),n=new Map;for(let r of t){let o=n.get(r.action)??[];o.push(r.payload),n.set(r.action,o)}return t.map(r=>ia(r,n.get(r.action)??[])).join(`
|
|
40
|
+
`)};var Fu=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ce,Lr]=Fu;var D=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),ca=e=>{let t=b.getNode(e);if(!t||!w(t)||t.isDeleted)return null;let n=da(t);return d(n)?n:null},Bu=e=>{for(let t of e){let n=ca(t);if(n)return n;let r=f().nodes[t]?.parentNodeId;if(!r)continue;let o=ca(r);if(o)return o}return null},Uu=(e,t)=>{let n=b.getNode(e);n&&b.updateNode({...n,log:[...n.log??[],t]})},Ou=e=>{let t=[e],n=f().nodes[e]?.parentNodeId;return n&&t.push(n),t},cs=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":return[e.payload.issue];case"delete.node":case"edit.description":return Ou(e.payload.id);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"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"create.contributor":case"link.contributor.user":default:return[]}},_u=e=>{fe(t=>({...t,eventLog:[...t.eventLog,e]}))},$u=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?D("Invalid user ID format",e):l("Valid user",null)},Wu=(e,t)=>{let n=$u(e);if(d(n))return n;let r=[...new Set(cs(e))];t||(r.forEach(s=>Uu(s,e)),_u(e));let o=Bu(r);return o||null},Hu={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Q.workspace(t,n,r),s=_n(o);if(d(s))return D(s.message,e);let i=b.createNode(o);return d(i)?D(i.message??"Failed to initialize workspace",e):ts(i.value)?l("Workspace initialized",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=b.createNode(Q.workspace(t,n,r));return d(o)?D(o.message??"Failed to add workspace",e):ts(o.value)?l("Added workspace",{action:e.action,result:o.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=b.createNode(Q.board(t,n,r,o));return d(s)?D(s.message??"Unable to create board",e):Er(s.value)?l("Added board",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=b.createNode(Q.swimlane(t,n,r,o));return d(s)?D(s.message??"Unable to create swimlane",e):Et(s.value)?l("Added swimlane",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=b.createNode(Q.ticket(t,n,r,o));return d(s)?D(s.message??"Unable to create issue",e):w(s.value)?l("Added issue",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=b.createNode(Q.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(se.DESCRIPTION)?"vertical":"horizontal"}));return d(i)?D(i.message??`Unable to create field: ${n}`,e):Qe(i.value)?l("Added field",{action:e.action,result:i.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!b.getNode(t))return D(`Unable to locate node with id ${t}`,e);let o=b.renameNode(t,n);return d(o)?D(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=b.tombstoneNode(t);return d(n)?D(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=b.createTag({id:t,name:n});return d(r)?D(r.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=b.createContributor({id:t,name:n});return d(r)?D(r.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=b.tag(t,n);return d(r)?D(r.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=b.untag(t,n);return d(r)?D(r.message??"Unable to untag issue",e):l("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=b.assign(t,n);return d(r)?D(r.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=b.unassign(t,n);return d(r)?D(r.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?D(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=b.editValue(t,n);return d(r)?D(r.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return D("Unable to locate issue",e);if(!w(o))return D("Can only close issues",e);let s=b.getNode(ce);if(!s)return D("Unable to locate target swimlane",e);if(n!==s.id)return D("Close target must be closed swimlane",e);let i=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(i)?D(i.message??"Unable to close issue",e):l("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return D("Unable to locate issue",e);if(!w(o))return D("Can only reopen issues",e);let s=b.getNode(ce);if(!s)return D("Unable to locate closed swimlane",e);if(n===s.id)return D("Cannot reopen issue into closed swimlane",e);if(!b.getNode(n))return D("Reopen parent no longer exists",e);let c=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?D(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=b.lockNode(t);return d(n)?D(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let s=b.getNode(r);if(!s)return D(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return D(`Node ${r} is not child of ${t}`,e);let i=b.updateNode({...s,rank:o});if(d(i))return D(i.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=b.createComment({id:t,issue:n,authorId:r,authorName:b.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return d(s)?D(s.message??"Unable to add comment",e):l("Comment added",{action:e.action,result:{id:t,issue:n,author:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=e.payload,o=b.getComment(t);if(!o)return D("Unable to locate comment",e);if(o.issue!==n)return D("Comment does not belong to issue",e);let s=b.editComment(t,r);return d(s)?D(s.message??"Unable to edit comment",e):l("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=b.getComment(t);if(!r)return D("Unable to locate comment",e);if(r.issue!==n)return D("Comment does not belong to issue",e);let o=b.deleteComment(t);return d(o)?D(o.message??"Unable to delete comment",e):l("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=b.linkUserId({contributorId:t,userId:e.userId});return d(n)?D(n.message??"Unable to link contributor",e):l("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function Rt(e,t=!1){let n=Hu[e.action](e);if(d(n))return n;let r=Wu(e,t);return r||n}var At=e=>e.map(t=>Rt(t));import Zu from"node:fs";import em from"node:path";import{decodeTime as tm,monotonicFactory as nm}from"ulid";import{z as $n}from"zod";import kr from"node:fs";import us from"node:path";import{decodeTime as ju}from"ulid";import{z as ls}from"zod";var Vu=ls.object({userId:ls.string().min(1).default("unknown"),userName:ls.string().min(1).default("unknown")}),Gu=e=>{let[t,n]=us.basename(e,".jsonl").split("."),r=Vu.safeParse({userId:t,userName:n});return r.success?l("Parsed event file actor",r.data):a(`Invalid event file name ${us.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},zu=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?a(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?a("Invalid persisted event: action key is missing or invalid"):l("Resolved persisted action",t[0])},Ku=(e,t)=>t in e,qu=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Yu=e=>{let{userId:t,userName:n,...r}=e,o=zu(r);if(d(o))return a(o.message);let s=o.value,i=e.id?.[0];return i?Ku(r,s)?l("Decoded persisted event",qu({id:i,action:s,payload:r[s],userId:t,userName:n})):a(`Persisted event is missing payload for action: ${s}`):a("Persisted event is missing id")},ms=e=>{let t=[];for(let n of e){let r=Yu(n);if(d(r))return a(`Failed to decode event ${n.id?.[0]??"<unknown>"}: ${r.message}`);t.push(r.value)}return l("Decoded reconstructed events",t)},Xu=e=>{if(!kr.existsSync(e))return l("Event file missing",[]);let t=Gu(e);if(d(t))return a(t.message);let n=kr.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
|
|
41
|
+
`)){let s=o.trim();if(!s)continue;let i;try{i=JSON.parse(s)}catch{return a(`Failed to parse event JSON from ${e}: ${s}`)}let c=fs(i);if(d(c))return a(`${c.message} in ${e}: ${s}`);r.push({...c.value,userId:t.value.userId,userName:t.value.userName})}return l("Parsed persisted events file",r)};function ps(e){let t=Tn(e);if(!kr.existsSync(t))return l("No events found",[]);let n=kr.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>us.join(t,o)),r=[];for(let o of n){let s=Xu(o);if(d(s))return a(s.message);r.push(...s.value)}return l("All events loaded",Ju(r))}function pt(e){let t=ps(e);return d(t)?a(t.message):ms(t.value)}function la(e,t){let n=ps(e);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=Qu(n.value,t),s=ms(r);if(d(s))return a(s.message);let i=ms(o);return d(i)?a(i.message):l("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:i.value})}function ua(e=process.cwd()){let t=ps(e);return d(t)?a(t.message):l("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Ju=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],v=m.id[1]??null;t.set(p,m);let I=n.get(v)??[];I.push(m),n.set(v,I)}for(let m of n.values())m.sort((p,v)=>p.id[0].localeCompare(v.id[0]));let r=[],o=new Set,s=m=>{let p=m.id[0];if(o.has(p))return;r.push(m),o.add(p);let v=n.get(p)??[];for(let I of v)s(I)},i=n.get(null)??[];for(let m of i)s(m);let c=e.filter(m=>{let p=m.id[0],v=m.id[1]??null;return!o.has(p)&&v!==null&&!t.has(v)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of c)s(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)s(m);return r},Qu=(e,t)=>{let n=new Set,r=[],o=[];for(let s of e){let i=s.id[0],c=s.id[1],u=!1;try{u=ju(i)<t}catch{u=!1}!u||c&&n.has(c)?(n.add(i),o.push(s)):r.push(s)}return{appliedEvents:r,unappliedEvents:o}};var ma=e=>({action:e.action,payload:e.payload});var ga=1,pa=nm(),rm=$n.tuple([$n.string().min(1),$n.string().min(1).nullable()]),om=$n.looseObject({v:$n.literal(ga),id:rm}),fs=e=>{let t=om.safeParse(e);return t.success?l("Parsed persisted event",t.data):a(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},fa=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",sm=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),im=e=>e.trim().length>0&&e.length<=80,Z=()=>{let{userName:e,userId:t}=H();return e?t?sm(t)?im(e)?l("Successfully resolved actor ID",{userId:t,userName:e}):a("Invalid user name in config"):a("Invalid user ID in config"):a("User ID not configured"):a("User name not configured")},qt=({userId:e,userName:t})=>`${fa(e)}.${fa(t)}.jsonl`,am=(e,{userId:t,userName:n})=>{let r=qt({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return a(`Invalid event log file name: ${r}`);let s=em.join(Tn(e),r);return l("Successfully resolved event log path",s)},dm=(e,t)=>{let n={[e.action]:e.payload,v:ga,id:t};return fs(n)};function Dr({event:e,rootDir:t}){try{let n=mi(t);if(d(n))return n;let r=am(t,{userId:e.userId,userName:e.userName});if(d(r))return r;let o=ua(t);if(d(o))return a(o.message);let s=o.value?pa(Math.max(Date.now(),tm(o.value)+1)):pa(),i=dm(ma(e),[s,o.value]);return d(i)?a(i.message):(Zu.appendFileSync(r.value,`${JSON.stringify(i.value)}
|
|
42
|
+
`,"utf8"),l("Event persisted",{path:r.value,entry:i.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return a(`Failed to persist event: ${r}`)}}function va(e,t){let n=Rt(e);if(n.status!==bt.Success)return n;let r=Dr({event:e,rootDir:t});return d(r)?r:n}function B(e,t){if(e.length===0||!e[0])return a("No events provided");let n=lm(e[0],t);if(d(n))return n;let r=e.map(s=>va(s,t)),o=r.filter(d);return o.length>0?a("Materialize and persist failed: "+o.map(s=>s.message).join(", ")):l("Materialization succeeded",r.map(s=>s.value))}var lm=(e,t)=>{if(e.action==="create.contributor")return l("Contributor already being created",void 0);if(b.getContributor(e.userId))return l("Contributor exists",void 0);let n={id:cm(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},r=va(n,t);return d(r)?a(r.message):l("Contributor created",void 0)};var ya=e=>Fr(z(e),{at:"end"}),Fr=(e,t={at:"end"})=>{let n=r=>d(r)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(Ee(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(Ee(void 0,r.rank)):a("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(Ee(r.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let r=ha(e,t.sibling);if(r<0)return a("Sibling not found");let o=r>0?e[r-1]:void 0,s=e[r];return s?n(Ee(o?.rank,s.rank)):a("Sibling not found")}case"after":{let r=ha(e,t.sibling);if(r<0)return a("Sibling not found");let o=e[r],s=r<e.length-1?e[r+1]:void 0;return o?n(Ee(o.rank,s?.rank)):a("Sibling not found")}}},z=e=>Object.values(f().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),ha=(e,t)=>e.findIndex(n=>n.id===t),xa=(e,t,n={at:"end"})=>Fr(z(t).filter(r=>r.id!==e),n),Yt=(e,t,n,r,o)=>{let s=xa(t,e,n);if(d(s))return s;if(!s.value.needsRebalance)return l("Resolved rank",s.value.rank);let i=rs(e,r);if(d(i))return i;let c=B([i.value],o);if(d(c))return c;let u=xa(t,e,n);return d(u)?u:u.value.needsRebalance?a("Rank rebalance failed to create space"):l("Resolved rank after rebalance",u.value.rank)},vn=(e,t,n)=>{let r=ya(e);if(d(r))return r;if(!r.value.needsRebalance)return l("Resolved rank",r.value.rank);let o=rs(e,t);if(d(o))return o;let s=B([o.value],n);if(d(s))return s;let i=ya(e);return d(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)};var M={exit(){process.exit(0)},enterChildNode(){let e=f(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=W(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||M.navigate({contextNode:o,selectedIndex:W(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=f();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=W(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;M.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Ia(1),navigateToPreviousItem:()=>Ia(-1),navigateToNextContainer:()=>ba(1),navigateToPreviousContainer:()=>ba(-1),navigate:({contextNode:e,selectedIndex:t})=>{C({contextNodeId:e.id,selectedIndex:t})}},Ia=e=>{let{selectedIndex:t,contextNode:n}=f(),r=W(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;M.navigate({selectedIndex:s,contextNode:n})},ba=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=f();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=W(o.id),i=s.findIndex(I=>I.id===t.id);if(i<0)return;let c=s.at(i+e)??s.at(0);if(!c)return;let u=W(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),v=u.length?p:-1;M.navigate({contextNode:c,selectedIndex:v})};var Sa=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Ea=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=f();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},um=e=>{let t=f().nodes[e];return!!t&&!t.isDeleted&&Qe(t)&&t.childRenderAxis==="vertical"},Br=(e,t)=>{let{nodes:n}=f(),r=n[e];if(!r||r.isDeleted)return!1;let o=z(r.id);return M.navigate({contextNode:r,selectedIndex:Sa(t,o.length)}),!0},Na=e=>{let{nodes:t}=f(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Br(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=z(o.id).findIndex(c=>c.id===n.id);return i>=0?(M.navigate({contextNode:o,selectedIndex:i}),!0):Na(o.id)},Ca=e=>{let{nodes:t}=f(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Na(n))return!0;n=t[n]?.parentNodeId}return!1},mm=e=>{if(!e)return!1;let t=f().nodes[e];return!!t&&!t.isDeleted},Ra=e=>{let{nodes:t,rootNodeId:n}=f();if(um(e.contextNodeId)&&Br(e.contextNodeId,e.selectedIndex))return l("Restored navigation inside text container",null);if(mm(e.selectedNodeId)&&e.selectedNodeId&&Ca(e.selectedNodeId))return l("Restored navigation to selected node or ancestor",null);if(Br(e.contextNodeId,e.selectedIndex))return l("Restored navigation to previous container",null);if(e.parentNodeId&&Br(e.parentNodeId,e.selectedIndex))return l("Restored navigation to previous parent",null);if(Ca(e.contextNodeId))return l("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return a("Unable to restore navigation");let o=z(r.id);return M.navigate({contextNode:r,selectedIndex:Sa(e.selectedIndex,o.length)}),l("Restored navigation to root",null)};import{monotonicFactory as pm,ulid as ft}from"ulid";var Wn=pm();function fm(){let e=We();if(d(e))return a("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)throw new Error("No workspace found in event log");let[r]=W(n.id),[o]=r?W(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return l("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?l("Resolved boot nav target",{contextNode:r,selectedIndex:0}):n?l("Resolved boot nav target",{contextNode:n,selectedIndex:0}):l("Resolved boot nav target",{contextNode:t.nodes[t.rootNodeId],selectedIndex:0})}function gm(){let e=fm();return d(e)?e:M.navigate(e.value)}function Aa({userId:e,userName:t}){let n=Wn(),r=Wn(),o=Wn(),s=Wn(),i=Wn(),c=Ee(void 0,void 0);if(d(c))return c;let u=Ee(void 0,void 0);if(d(u))return u;let m=Ee(u.value,void 0);if(d(m))return m;let p=Ee(void 0,void 0);if(d(p))return p;let v=Ee(p.value,void 0);if(d(v))return v;let I=Ee(v.value,void 0);if(d(I))return I;let E=Ee(void 0,void 0);return d(E)?E:l("Created default events",[{id:ft(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:ft(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:v.value}},{id:ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:I.value}},{id:ft(),userId:e,userName:t,action:"add.board",payload:{id:Lr,name:"Closed",parent:n,rank:m.value}},{id:ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:ce,name:"Closed",parent:Lr,rank:E.value}},{id:ft(),userId:e,userName:t,action:"lock.node",payload:{id:Lr}},{id:ft(),userId:e,userName:t,action:"lock.node",payload:{id:ce}}])}function Xt(e){if(!e.length){let r=Q.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=_n(r);return d(o)?o:(C({hasProjectDefinition:!1,mode:g.DEFAULT}),l("Booted uninitialized workspace placeholder",null))}if(!e.some(r=>r.action==="init.workspace"))return a("Initialized Epiq project has no workspace init event");let n=At(e).filter(d);return n.length>0?a(`Materializing failed:
|
|
43
|
+
${n.map(r=>r.message).join(`
|
|
44
|
+
`)}`):(gm(),C({hasProjectDefinition:!0}),l("State booted successfully",null))}var Jt=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),Ur=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}},K=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);var et=null,Or=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!et,currentStatus:f().syncStatus?.status,currentMessage:f().syncStatus?.msg}),et)return logger.debug("[sync] syncAndReloadState joining existing promise"),et;logger.debug("[sync] syncAndReloadState creating promise"),et=vm();try{let e=await et;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:f().syncStatus?.status,statusMessageAfterResolve:f().syncStatus?.msg}),d(e)&&f().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),C({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),et||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:f().syncStatus?.status,statusMessageBeforeClear:f().syncStatus?.msg}),et=null}},vm=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:f().mode,syncStatus:f().syncStatus});let e=Ta();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:f().mode,message:e.message,syncStatus:f().syncStatus}),e;if(et)return et;logger.debug("[sync] syncAndReloadState:start");let t=K("resolveActorId",Z());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:d(t)?t.message:"Missing actor id"}),a("Unable to resolve event log path");C({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:f().syncStatus});let n=qt(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=K("syncEpiqWithRemote",await _r({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!d(r),message:(d(r),r.message)}),d(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),C({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:f().syncStatus}),He(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let s=K("loadMergedEvents",pt(o));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(s),message:(d(s),s.message),count:d(s)?void 0:s.value.length}),d(s))return C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:f().syncStatus}),a(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let i=Ta();if(i)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:f().mode,message:i.message,syncStatus:f().syncStatus}),i;let c=Ea(),u=f().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:c,selectedNodeId:f().selectedNode?.id,contextNodeId:f().contextNode?.id,selectedNodeIsVirtual:f().selectedNode?.isVirtual,contextNodeIsVirtual:f().contextNode?.isVirtual}),!f().selectedNode?.isVirtual&&!f().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let p=K("bootStateFromEventLog",Xt(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(p),message:(d(p),p.message)}),d(p))return C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:f().syncStatus}),a(`Unable to boot synced state. ${p.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:f().selectedNode?.isVirtual,contextNodeIsVirtual:f().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),C({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=K("restoreNavigationAnchor",Ra(c));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(m),message:d(m)?m.message:"Navigation restored",selectedNodeId:f().selectedNode?.id,contextNodeId:f().contextNode?.id}),d(m)?(C({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:f().syncStatus}),m):(C({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:f().syncStatus}),l("Synced",!0))},Ta=()=>f().mode===g.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:f().mode,syncStatus:f().syncStatus}),C({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var yn=3e3,wa=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<yn?null:t},Ma=0,gs,vs=!1,Hn=!1,ys=()=>{if(vs)return!0;let e=We();return d(e)?!1:e.value.syncStatus.status==="syncing"},ym=()=>{let e=H().autoSyncIntervalMs??1e4,t=Date.now()-Ma;return Math.max(0,e-t)},Pa=()=>{gs||(gs=setTimeout(async()=>{if(gs=void 0,!!hn()){if(ys()){Hn=!0;return}Hn=!1,await hm()}},ym()))},hm=async()=>{if(f().readOnly||f().timeMode==="peek"||f().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!hn())return a("Cannot auto-sync before state is initialized");if(ys())return Hn=!0,a("Sync already in progress");vs=!0,Ma=Date.now(),C({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Or()}finally{vs=!1,Hn&&Pa()}},$r=()=>{hn()&&(Hn=!0,!ys()&&Pa())};var Tt=()=>{let e=H(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},La=()=>{let e=Ke(process.cwd());if(d(e))return!1;let t=Ct(e.value);return te(t)},ka=e=>e===!0?"on":e===!1?"off":null,Da=e=>e==="on"?!0:e==="off"?!1:null;var xm=e=>e.props.tags??[],Im=e=>e.props.assignees??[],jn=e=>xm(e).map(t=>b.getTag(t)).filter(t=>!!t),Vn=e=>Im(e).map(t=>b.getContributor(t)).filter(t=>!!t),Wr=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!w(n)?a("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",jn(n))},Hr=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!w(n)?a("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",Vn(n))};var x={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""};var bm=/^(\d+)(h|d|w|mo|y)$/,Cm=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Sm=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let s=new Date(e,t-1,n,r,o);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===r&&s.getMinutes()===o},Em=(e,t=new Date)=>{let n=e.match(bm);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(o){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},Nm=e=>{let t=e.match(Cm);if(!t)return null;let[,n,r,o,s,i]=t,c=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,v=i?Number(i):0;return Sm({year:c,month:u,day:m,hour:p,minute:v})?new Date(c,u-1,m,p,v):null},Qt=e=>{let t=e.trim().toLowerCase();return Em(t)??Nm(t)};var Fa=/^(\d+)(s|m)?$/,jr=e=>{let t=e.trim().toLowerCase().match(Fa);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Vr=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Fa.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Ba=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Rm=[{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}],hs=(e=Rm)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let s=r;s<=o;s++)t.push(`${s}${n}`);return t};var Am=["BOARD","TICKET","SWIMLANE","COMMENT"],ae={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",LOG_LEVEL:"logLevel"},we={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Tm=[ae.EDITOR,ae.VIEW,ae.USERNAME,ae.AUTOSYNC,ae.SYNC_DEBOUNCE_MS,ae.LOG_LEVEL],wm=(e=f().selectedNode?.context)=>{switch(e){case"TICKET":return[we.TITLE,we.DESCRIPTION];case"BOARD":case"SWIMLANE":return[we.TITLE];case"COMMENT":return[we.COMMENT];default:return[]}},Is=[String(yn),"5000","15000","30000","60000"],_a=["10s","20s","30s","45s"],Zt=[x.COFFEE,x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG],Gr=[x.NEW,x.EDIT,x.DELETE,x.MOVE],xs=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT,x.COMMENT],Ua=[x.FILTER,x.PEEK,x.REPLAY],Mm={WORKSPACE:[...Zt,...Gr],BOARD:[...Ua,...Zt,...Gr],SWIMLANE:[...Ua,...Zt,...Gr],TICKET:[...Zt,...Gr,...xs],FIELD:[...Zt,...xs],FIELD_LIST:[...Zt,...xs],TEXT:[...Zt],COMMENT:[x.EDIT,x.DELETE]},Pm=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],$a=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&w(n)),Oa=e=>e.parentNodeId===ce,Lm=({selectedNode:e,breadCrumb:t})=>{let n=wm(e?.context);return $a({breadCrumb:t,selectedNode:e})?n.includes(we.DESCRIPTION)?n:[...n,we.DESCRIPTION]:n},km=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Tt();if(!r)return[x.HELP,x.CONFIG];if(!La())return[x.HELP,x.INIT];if(t)return[x.HELP,x.PEEK,x.REPLAY,x.EXPORT,x.CONFIG];let o=e?.context,s=o&&Am.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?Mm[u]:[]))],c=$a({breadCrumb:n,selectedNode:e});return i.filter(u=>u===x.MOVE?!1:u===x.EDIT?s||!!c:u===x.DELETE?s:u===x.UNTAG?!!(c&&jn(c).length>0):u===x.UNASSIGN?!!(c&&Vn(c).length>0):u===x.RE_OPEN_ISSUE?!!(c&&Oa(c)):u===x.CLOSE_ISSUE?!!(c&&!Oa(c)):!0)},le=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=f())=>{let s=t.context??"WORKSPACE";return{[x.NONE]:km({breadCrumb:o,readOnly:r,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.HELP]:[],[x.PEEK]:[...hs(),"now","prev","next"],[x.REPLAY]:[...hs()],[x.EDIT]:Lm({selectedNode:n,breadCrumb:o}),[x.COMMENT]:[],[x.DELETE]:["confirm"],[x.RE_OPEN_ISSUE]:["confirm"],[x.CLOSE_ISSUE]:["confirm"],[x.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[x.FILTER]:["tag","assignee","description","title","clear"],[x.TAG]:[...new Set([...Object.keys(pn),...b.getExistingTags()])],[x.UNTAG]:[...Wr()?.value?.map(({name:c})=>c)??[]],[x.UNASSIGN]:[...Hr()?.value?.map(({name:c})=>c)??[]],[x.ASSIGN]:b.getExistingAssignees(),[x.NEW]:Pm(s),[x.CONFIG]:[...Tm],[x.COFFEE]:["1","3","5","20","custom"]}[e]??[]};import Ga from"chalk";var Wa=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var be=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?l("Found node",n):a("Unable to find node in breadcrumb")};import Ha from"chalk";var J=e=>Ha.dim(e),ve=e=>Ha.hex(y.primary)(e),ye=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(v=>v.startsWith(i))].sort((v,I)=>Ar(v)-Ar(I)).slice(0,r).map(v=>Tr(v)).join(" ");return p?`${J(e)}${p}${J(n)}`:""};var wt={None:"none",Invalid:"invalid",Valid:"valid"};var xn=140,Dm=["BOARD","TICKET","SWIMLANE"],ja=()=>{let e=f().selectedNode;if(!e?.context)return F({message:J("Missing target context")});if(Dm.includes(e.context))return j();if(e.parentNodeId){let t=f().nodes[e.parentNodeId];if(t?.id===Ne(t?.parentNodeId??"","comments"))return j()}return F({message:J("Command not available in this context")})},ne="<ENTER> to confirm",j=(e="",t=[])=>({message:J(e),validity:wt.Valid,completionWordList:t}),F=({message:e,completionWordList:t=[]})=>({validity:wt.Invalid,message:e,completionWordList:t}),Kr=e=>e.length===0,Va=(e,t)=>{let n=be(f().breadCrumb,"BOARD");if(d(n))return F({message:ve("Command is not applicable in this context")});let r=Pr(n.value.id);return d(r)?F({message:ve(`Unable to ${t}: board id is not a valid ULID`)}):Ba({date:e,horizonDate:r.value})?null:F({message:ve(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},zr=e=>` ${Ga.hex("#000").bgHex(ie(e))(` ${e} `)} `,bs=({modifier:e})=>{let t="confirm";return e===t?j(ne):F({message:Kr(e)?J("if you are certain, enter ")+Tr(t):"",completionWordList:[t]})},Fm=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?F({message:J(n)}):j():F({message:Kr(r)?t:"",completionWordList:[...e]}),en=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>Kr(n)&&Kr(r)?F({message:e,completionWordList:[]}):j(t??ne),Bm=({modifier:e,inputString:t})=>{let n=le(x.CONFIG);if(!n.includes(e))return F({message:ye({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ae.EDITOR:{let r=[...Wa];return t.trim()?r.includes(t.trim())?j(ne):F({message:ye({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):F({message:ye({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ae.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?j(ne):F({message:ye({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ae.USERNAME:return t.trim()?j(ne):F({message:ve("Enter a user name. Saved in ")+Ga.bgBlack("~/.epiq-global/config.json")});case ae.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?j(ne):F({message:ye({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ae.AUTOSYNC:{let r=["on","off"],o=H().autoSync;if(!r.includes(t.trim())){let s=ka(o);return F({message:ye({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return j(ne)}case ae.SYNC_DEBOUNCE_MS:{let r=H().autoSyncIntervalMs,o=wa(t);if(!t.trim()||o===null||o<yn){let s=ye({prefix:" examples: ",wordList:Is,minLengthForHints:0,inputString:t});return F({message:ve(`provide duration above ${yn}ms. current duration: ${r}ms.`)+s,completionWordList:Is})}return j(ne)}default:return F({message:ve("Unknown config option"),completionWordList:n})}},Um=({modifier:e,inputString:t})=>{let n=le(x.EDIT);if(!n.length)return F({message:ve("Command not available in this context")});if(!n.includes(e)){let r=ye({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return F({message:r||ve("Unknown edit option"),completionWordList:n})}switch(e){case we.COMMENT:return t.trim()?j(ne):F({message:J("write a comment...")});case we.TITLE:return j(ne);case we.DESCRIPTION:{let{preferredEditor:r}=H();return r?j(J("<ENTER> to edit in ")+r):F({message:"No editor selected"})}default:return F({message:ve("Unknown edit option"),completionWordList:n})}},Om={[x.EXPORT]:()=>j(ne+J(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return j(ne);let n={message:J("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Qt(r);if(!r||!o)return F(n);let s=Va(o,"peek");return s||j(ne)},[x.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Vr(e.modifier,e.inputString),r={message:J("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Qt(t);if(!t||!o)return F(r);let s=Va(o,"replay");return s||(n&&jr(n)===null?F({message:ve("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):j("<ENTER> to replay board history",n?_a:[]))},[x.EXIT]:()=>j(ne+J(" and exit the application")),[x.INIT]:()=>j(ne),[x.PALETTE]:()=>j(ne),[x.FILTER]:e=>{if(e.modifier==="clear")return j(ne);let t=s=>le(x.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return F({message:ye({wordList:le(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:le(x.FILTER)});let n=Object.values(f().tags).map(s=>s.name),r=Object.values(f().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?F({message:ye({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):j():F({message:ye({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[x.NONE]:e=>{let t=le(x.NONE);return F({message:ye({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>Fm({list:le(x.NEW),hint:ye({wordList:le(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>j(ne),[x.EDIT]:Um,[x.COMMENT]:e=>{let t=en({hint:J(`write a comment (max ${xn} char)...`),onOk:J(`(${e.inputString.length}/${xn})`)})(e);return t.validity===wt.Invalid?t:e.inputString.length>xn?j(ve("max input exceeded")):t},[x.CONFIG]:Bm,[x.DELETE]:e=>{let t=ja();return t.validity==="invalid"?t:bs(e)},[x.CLOSE_ISSUE]:e=>bs(e),[x.RE_OPEN_ISSUE]:e=>bs(e),[x.MOVE]:e=>{let t=ja();return t.validity==="invalid"?t:en({hint:ye({prefix:"hey hacker! These commands are blocked for you... ",wordList:le(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=b.getExistingTags().slice(0,10).map(zr).join("");return en({hint:n.length?J("create tag or reuse:")+n+J(""):J("create tag ...")})(e)},[x.UNTAG]:e=>{let t=Wr();if(d(t))return F({message:ve("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(zr).slice(0,10);return n.length?en({hint:J(" ... ")+n.join("")})(e):F({message:ve("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=b.getExistingAssignees().map(zr).slice(0,10);return en({hint:J("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=Hr();if(d(t))return F({message:ve("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(zr).slice(0,10);return n.length?en({hint:J("remove assignee... ")+n.join("")})(e):F({message:ve("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>j(ne),[x.COFFEE]:e=>{let{modifier:t}=e,n=le(x.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?F({message:J("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):en({hint:ye({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},za=Object.fromEntries(Object.entries(Om).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var qr=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"];var _m=3,$m=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),Wm=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let r=n.props;typeof r.description=="string"&&t.push(r.description),typeof r.value=="string"&&t.push(r.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},Hm=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=_m&&!$m.has(t)&&!/^\d+$/.test(t)),jm=e=>{let t=new Map;for(let s of Wm(e))for(let i of Hm(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),r=new Set(n),o=qr.filter(s=>!r.has(s));return[...n,...o]},Ka=qr,qa=-1,Ya=()=>{let e=We();if(d(e))return qr;let t=e.value,n=t.eventLog.length;return n!==qa&&(Ka=jm(t),qa=n),Ka};var Xa=e=>Object.values(x).includes(e),Ja=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:c,completionWordList:u}=za[n].validate(n,r,s),m=n!==x.PEEK&&n!==x.REPLAY,p=o==="command"||o==="modifier"?le(n):m?Ya():[],{mode:v}=f(),I=v===g.COMMAND_LINE?i??"":"",E=[...u,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:I,autoCompletion:t?Ki(e,E):{hint:"",hints:[],remainder:"",overlap:0}}};var Qa=e=>{let t=e.trimStart(),n=Gm(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=zm(e),c=Xa(r)?r:null,u=c!==null,m=r!=="",p=c?le(c)??[]:[],v=c&&p.includes(o)?o:"",I="word";n.length===0||n.length===1&&!s?I="command":(n.length===1&&s||n.length===2&&!s)&&(I="modifier");let E=s?"":i,N=Vm(t,c,v);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:v,target:I,inputToMatch:E,inputString:N}},Vm=(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},Gm=e=>e.trim()?e.trim().split(/\s+/):[],zm=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as Km}from"react";var In=e=>e===Cs||e===":",Cs=" ",he={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:wt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Ss=new Set,Za=()=>{for(let e of Ss)e()},Es=e=>(Ss.add(e),()=>Ss.delete(e)),tt=e=>{let n=e(he),r=Qa(n.value),o=n.cursorPosition===n.value.length;he={...n,commandMeta:Ja(r,o)},Za()},Gn=({message:e,status:t})=>{let n=structuredClone(he);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,he=n,Za(),l(e,null)},Ns=e=>{tt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Rs=e=>{tt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&In(n[o-1]);)o--;for(;o>0&&!In(n[o-1]);)o--}else{for(;o<n.length&&!In(n[o]);)o++;for(;o<n.length&&In(n[o]);)o++}return{...t,cursorPosition:o}})},ed=()=>{tt(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}})},td=()=>{tt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&In(t[r-1]);)r--;for(;r>0&&!In(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Yr=e=>{tt(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},nd=()=>{tt(e=>({...e,commandIsPending:!0}))},_=e=>{tt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},rd=({addToHistory:e=!0})=>{tt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},od=()=>{tt(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}})},sd=()=>{tt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},q=()=>he,id=()=>Km(Es,q,q),ad=()=>{let[e,...t]=he.value.split(Cs);return t.join(Cs).trim()};var h={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",InitCommandPalette:"initCommandPalette",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",EditTitle:"editTitle",EditDescription:"editDescription",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function qm(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function Ym(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function Xm(e,t,n){let r=f().contextNode.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 dd(e,t){let n=q();if(e.sequence==="?"&&t!==g.PALETTE)return h.InitCommandPalette;if(e.sequence===":"&&t!==g.COMMAND_LINE)return h.InitCommandLine;if(t===g.MOVE)switch(e.name){case"m":case"return":return h.ConfirmMove}if(t===g.COMMAND_LINE)return $i(e,n.value);if(t===g.PALETTE)return Wi(e,n.value);let r=qm(e)||Ym(e);if(r)return Jm(r,t);if(e.ctrl&&e.name==="c")return h.Exit;switch(e.name){case"r":return h.EditTitle;case"e":return h.EditDescription;case"n":return h.AddItem;case"m":return h.InitMove;case"d":return h.Delete;case"return":return h.Confirm;case"space":return h.Confirm;case"v":return H().viewMode==="wide"?h.SetViewDense:h.SetViewWide;case"q":case"escape":return h.Exit;default:return null}}function Jm(e,t){let n=t===g.MOVE?{prevItem:h.MovePreviousItem,nextItem:h.MoveNextItem,prevContainer:h.MoveToPreviousContainer,nextContainer:h.MoveToNextContainer}:{prevItem:h.NavPreviousItem,nextItem:h.NavNextItem,prevContainer:h.NavToPreviousContainer,nextContainer:h.NavToNextContainer};return Xm(f().contextNode.childRenderAxis,e,n)}var Xr=e=>{let{context:t}=f().contextNode;if(!t)return L.None;switch(e){case x.EXIT:return L.Exit;case x.EXPORT:return L.Export;case x.COFFEE:return L.Coffee;case x.INIT:return L.Init;case x.DELETE:return L.Delete;case x.EDIT:return L.Edit;case x.COMMENT:return L.Comment;case x.HELP:return L.ViewHelp;case x.RE_OPEN_ISSUE:return L.ReopenIssue;case x.CLOSE_ISSUE:return L.CloseIssue;case x.TAG:return L.TagTicket;case x.UNTAG:return L.UntagTicket;case x.ASSIGN:return L.AssignUserToTicket;case x.UNASSIGN:return L.UnassignUserFromTicket;case x.NEW:return L.NewItem;case x.FILTER:return L.Filter;case x.MOVE:return L.Move;case x.PEEK:return L.Peek;case x.REPLAY:return L.Replay;case x.CONFIG:return L.Config;case x.SYNC:return L.Sync;default:return L.None}},L={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Config:"config",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",Comment:"comment-issue",Sync:"sync",Export:"export",Coffee:"coffee"};import{ulid as xe}from"ulid";import Ad from"node:fs";import Lp from"node:path";import kp from"react";import{Box as Mp}from"ink";import ro from"react";import pp from"chalk";import{Box as Ts,Text as fp}from"ink";import rt from"react";import{Text as cd}from"ink";import ld,{useEffect as ud,useState as Qm}from"react";var md={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ce=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=$(),r=md[n]??md.default,[o,s]=Qm(0);if(ud(()=>{s(0)},[r]),ud(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return ld.createElement(cd,null,t);let i=r[o]??r[0]??t;return ld.createElement(cd,{color:y.accent,dimColor:o===1},i)};import{Box as As,Text as Zm}from"ink";import Jr from"react";var nt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),i=Math.max(1,Math.ceil(r)),c=Math.max(1,Math.floor(s/i)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),v=p+c,I=e.slice(p,v),E=e.length>c,N=s,T=E?Math.max(1,Math.floor(c/e.length*N)):N,k=Math.max(0,N-T),O=Math.max(1,e.length-c),V=E?Math.floor(p/O*k):0;return Jr.createElement(As,{flexDirection:"row",height:s,width:"100%"},Jr.createElement(As,{flexDirection:"column",flexGrow:1,height:s},I),Jr.createElement(As,{flexDirection:"column",width:1,height:N},Array.from({length:N}).map((R,A)=>Jr.createElement(Zm,{key:A,color:E&&A>=V&&A<V+T?y.accent:y.secondary},E?"\u2502":" "))))};import{Box as Zr,Text as up}from"ink";import tn from"react";import{Text as ep}from"ink";import tp from"react";var np=e=>e.toLowerCase().trim(),rp=(e,t=pn)=>{let n=np(e);return t[n]?t[n]:On(n)},Mt=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return tp.createElement(ep,{underline:t,color:rp(n.name)},"@"+n.name)};import{Text as op}from"ink";import sp from"react";var bn=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return sp.createElement(op,{underline:t,backgroundColor:ie(n.name),color:y.secondary}," "+n.name+" ")};import{useEffect as ip,useState as ap}from"react";var dp=80,pd=1400,Qr=new Set,zn=null,cp=e=>(Qr.add(e),zn||(zn=setInterval(()=>{for(let t of Qr)t()},dp)),()=>{Qr.delete(e),Qr.size===0&&zn&&(clearInterval(zn),zn=null)}),lp=()=>{let e=Date.now()%pd/pd;return e<.5?e*2:(1-e)*2},Cn=e=>{let[,t]=ap(0);return ip(()=>{if(e)return cp(()=>t(n=>n+1))},[e]),Rr(lp())};var fd=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Cn(r),s=e-14,i=un(Nt(t.title),s),c=jn(t),u=Vn(t);return tn.createElement(Zr,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:r?o:n?y.accent:y.secondary,justifyContent:"space-between"},tn.createElement(Zr,{borderBottom:!0},tn.createElement(Zr,{paddingLeft:1,flexDirection:"column"},tn.createElement(up,{color:y.primary},i))),tn.createElement(Zr,{flexDirection:"row",paddingLeft:1},c.map(m=>tn.createElement(bn,{key:m.id,id:m.id})),u.map(m=>tn.createElement(Mt,{key:m.id,id:m.id}))))};import{Box as nn,Text as Kn}from"ink";import Me from"react";var mp=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,gd=({width:e,ticket:t,isSelected:n,isFlashing:r=!1,index:o,mode:s})=>{let i=Cn(r),c=(t.props.tags??[]).map(R=>b.getTag(R)).filter(R=>!!R),u=(t.props.assignees??[]).map(R=>b.getContributor(R)).filter(R=>!!R),m=1,p=c.length*(1+m),v=u.length*(2+m),I=c.map(R=>Me.createElement(nn,{key:R.id,paddingRight:m},Me.createElement(Kn,{color:ie(R.name)},"\u25A0"))),E=u.map(R=>Me.createElement(nn,{key:R.id,paddingRight:m},Me.createElement(Kn,{color:On(R.name)},"@"+R.name.at(0)))),N=r?i:n?y.accent:s===g.MOVE?y.secondary:y.primary,T=4,k=b.getCommentsByIssue(t.id),O=k.length?String(k.length).length+2+m:0,V=k.length?Me.createElement(nn,{paddingRight:m},Me.createElement(Kn,{color:y.accent},"[",k.length,"]")):null;return Me.createElement(nn,{borderBottom:!0,justifyContent:"space-between"},Me.createElement(nn,null,Me.createElement(nn,{width:T},n?Me.createElement(Ce,{isSelected:n}):Me.createElement(Kn,{color:"gray",dimColor:!0},o+1)),Me.createElement(Kn,{wrap:"truncate",color:N},mp(t.title,e-p-v-O-18))),Me.createElement(nn,null,I,E,V))};var gp=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:m}=$(),p=u[e.id]??[],v=m?new Set(m.flashNodeIds):null,I=v?.has(e.id)??!1,E=Cn(I),N=`${e.title} ${pp.hex(y.secondary2).dim("("+p.length+")")}`,T=3,k=o?1:4,O=r-T-(o?2:1),V=rt.createElement(Ts,{borderStyle:"round",borderColor:y.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},rt.createElement(Ce,{isSelected:t}),rt.createElement(fp,{bold:!0,color:I?E:t?y.accent:y.primary},N," ",e.readonly?"\u{1F512}":"")),R=(A,G)=>{let Re=s&&i===G;if(!w(A))return null;let Ae=v?.has(A.id)??!1;return o?rt.createElement(gd,{key:A.id,index:G,width:n,ticket:A,isSelected:Re,isFlashing:Ae,mode:c}):rt.createElement(fd,{key:A.id,width:n,ticket:A,isSelected:Re,isFlashing:Ae})};return rt.createElement(Ts,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:1,paddingLeft:1,height:r},V,rt.createElement(Ts,{padding:o?1:0},p.length>0&&rt.createElement(nt,{selectedIndex:i,height:O,itemHeight:k},p.map(R)),rt.createElement(Ce,{isSelected:s&&i===-1})))},vd=rt.memo(gp);import{Box as qn,Text as Nd}from"ink";import Pe,{useMemo as no}from"react";import{Box as eo,Text as vp}from"ink";import gt from"react";var yd=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=$(),{title:o}=t,s=t.parentNodeId?b.getNode(t.parentNodeId):void 0,i=s&&w(s)?o===se.ASSIGNEES?s.props.assignees??[]:o===se.TAGS?s.props.tags??[]:[]:[];return gt.createElement(eo,{alignItems:"center",paddingTop:1},gt.createElement(eo,{minWidth:12},gt.createElement(Ce,{isSelected:n}),gt.createElement(vp,{color:n?y.accent:y.secondary2},o,":")),gt.createElement(eo,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let m=r.id===t.id&&u===e;return gt.createElement(eo,{key:`${o}-${c}`,paddingRight:2,minHeight:1},gt.createElement(Ce,{isSelected:m}),o===se.ASSIGNEES?gt.createElement(Mt,{isSelected:m,id:c}):o===se.TAGS?gt.createElement(bn,{isSelected:m,id:c}):null)})))};import{Box as to,Text as ws}from"ink";import vt,{useEffect as yp,useMemo as hd}from"react";var hp="\u2029",xd=(e,t)=>`${e}::inline-line::${t}`,Ms=new Map,Id=e=>{let t=Ms.get(e)??[];Ms.delete(e);for(let n of t)b.deleteNode(n)},xp=(e,t)=>{Id(e);let n=[];t.forEach((r,o)=>{let s=$e(BigInt(o+1));if(!te(s))return;let i=b.createNode(Q.text({id:xd(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));te(i)&&n.push(i.value.id)}),Ms.set(e,n)},Ps=({id:e,label:t,text:n,height:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=$(),u=hd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=hd(()=>u.join("\0"),[u]);yp(()=>(xp(e,u),()=>{Id(e)}),[e,m]);let p=I=>String(I).replace(/\r?\n/g,""),v=u.map((I,E)=>{let N=c.id===e&&i===E;return vt.createElement(to,{key:xd(e,E)},vt.createElement(ws,{color:N?y.primary:y.secondary2,dimColor:!N},`${E+1} `.padStart(5,"\xA0")),vt.createElement(ws,{backgroundColor:N?"gray":void 0},p(I.length?un(I,s-10):hp)))});return vt.createElement(to,{flexDirection:"column",paddingTop:1},vt.createElement(to,null,vt.createElement(Ce,{isSelected:o}),vt.createElement(ws,{color:o?y.accent:y.secondary2},t)),vt.createElement(to,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1},vt.createElement(nt,{scrollByOne:!0,height:r-3,selectedIndex:i,itemHeight:1},v)))};import{Box as Pt,Text as yt}from"ink";import ue,{useEffect as Ip,useMemo as bp,useRef as Cp}from"react";import{decodeTime as Ls}from"ulid";var bd=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},Cd=(e,t,n)=>Q.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});var Sp=e=>Ne(e,"comments"),Ep=e=>b.getCommentsByIssue(e.id).sort((t,n)=>Ls(t.id)-Ls(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),Sd=e=>{for(let t of e)b.deleteNode(t.id)},Np=(e,t)=>{let n=b.getNode(Sp(e.id));if(!n||!Qe(n))return[];let r=t.map((o,s)=>Cd(o,s,n.id)).map(b.createNode).filter(te).map(({value:o})=>o).filter(Bn);return t.length>0&&f().selectedIndex<0&&M.navigate({contextNode:n,selectedIndex:0}),r},Rp=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`};function Ed({ticket:e,width:t,height:n}){let r=bp(()=>Ep(e),[e]),o=Cp([]);Ip(()=>(Sd(o.current),o.current=Np(e,r),()=>{Sd(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=$(),c=Math.max(1,n-4),u=Math.max(20,t-8);return r.length===0?ue.createElement(Pt,{flexDirection:"column",width:t,height:n,padding:1},ue.createElement(yt,{color:y.primary},"No comments yet."),ue.createElement(Pt,{paddingTop:1},ue.createElement(yt,{color:y.primary},"Use"),ue.createElement(yt,{color:y.accent}," :comment "),ue.createElement(yt,{color:y.primary},"to add the first one."))):ue.createElement(Pt,{flexDirection:"column",width:t,height:n},ue.createElement(Pt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},ue.createElement(yt,{color:y.secondary2},"Comments (",r.length,") ")),ue.createElement(nt,{height:c,itemHeight:4,selectedIndex:s},r.map((m,p)=>{let v=p===s;return ue.createElement(Pt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},ue.createElement(Pt,{flexDirection:"row",paddingBottom:1},ue.createElement(yt,{color:y.accent},v?"\u276F ":" "),ue.createElement(Pt,{paddingLeft:1},ue.createElement(yt,{color:y.secondary2},`#${p+1} `),ue.createElement(Mt,{id:m.authorId}),ue.createElement(yt,{color:y.secondary2}," "+wr(Ls(m.id))))),ue.createElement(Pt,{paddingLeft:3,paddingBottom:1},ue.createElement(yt,{color:y.primary},Rp(m.md,u))))})))}var Ap=e=>Ne(e,"description"),Tp=e=>Ne(e,"comments"),wp=e=>Ne(e,"history"),Rd=({ticket:e,height:t})=>{let n=no(()=>bd(e),[e]),{selectedIndex:r,contextNode:o}=$(),s=process.stdout.columns||120,i=no(()=>Ap(e.id),[e.id]),c=no(()=>Tp(e.id),[e.id]),u=no(()=>wp(e.id),[e.id]),m=o.id===e.id,p=o.id===c||o.parentNodeId===c,v=o.id===u||o.parentNodeId===u,I=W(e.id);if(p){let A=t-3;return Pe.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Pe.createElement(Ed,{ticket:e,width:s,height:A}))}if(v){let R=b.getNode(u),A=R&&Qe(R)?R.props.value??"":"",Re=t-3;return Pe.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R?Pe.createElement(Ps,{id:R.id,label:"Event log",text:A,selected:!1,maxWidth:s,height:Re}):null)}let E=I.reduce((R,A)=>Fn(A)||A.id===c||A.id===u?R+1:R,0),N=2,T=3,k=E,O=t-T-k-N,V=(R,A)=>R.id===i?Pe.createElement(Ps,{key:R.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:A,maxWidth:s,height:O}):Fn(R)?Pe.createElement(yd,{key:R.id,parent:R,selected:A,selectedIndex:r}):R.id===c?Pe.createElement(qn,{key:R.id,paddingTop:1},Pe.createElement(Ce,{isSelected:A}),Pe.createElement(Nd,{backgroundColor:y.secondary,color:A?y.accent:y.primary},` Comments (${n}) \u203A\u203A `)):R.id===u?Pe.createElement(qn,{key:R.id,paddingTop:1},Pe.createElement(Ce,{isSelected:A}),Pe.createElement(Nd,{backgroundColor:y.secondary,color:A?y.accent:y.primary}," History \u203A\u203A ")):null;return Pe.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},I.map((R,A)=>V(R,m&&r===A)))};var Pp=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:c})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,p=u===P.BOARD||u===P.SWIMLANE,v=u===P.TICKET?t:r.find(k=>k.context===P.TICKET),I=Math.floor(c/3),E=Math.floor(c/Math.max(e.length,1)),N=Math.min(E,I),T=s==="dense";return ro.createElement(Mp,{flexDirection:"row",height:i},p&&e.map((k,O)=>{let V=t.id===k.id,R=V?n:-1,A=t.context===P.BOARD&&n===O;return ro.createElement(vd,{key:k.id,height:i,width:N,swimlane:k,isSelected:A,isDense:T,isFocused:V,listSelectedIndex:R,mode:o})}),m&&v&&ro.createElement(Rd,{height:i,ticket:v}))},oo=ro.memo(Pp);import{render as Dp}from"ink";import{Writable as Fp}from"node:stream";var Yn=e=>String(e).padStart(2,"0"),Bp=e=>{let t=e.getUTCFullYear(),n=Yn(e.getUTCMonth()+1),r=Yn(e.getUTCDate()),o=Yn(e.getUTCHours()),s=Yn(e.getUTCMinutes()),i=Yn(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},Up=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Op=async(e,{width:t,height:n})=>{let r="",o=new Fp({write(i,c,u){let m=_p(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=Dp(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},_p=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Td=async()=>{let{viewMode:e}=H(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=f(),i=r.find(O=>O.context==="BOARD");if(!i)return a("No board found to export");let c=120,u=40,m=await Op(kp.createElement(oo,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(O=>O!==void 0&&Et(O)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,height:u});if(!m)return a("Failed to render board export");let p=pr(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let v=new Date,I=Bp(v),E=`board_${Up(i.title)}_${I}.md`,N=ui(p.value);Ad.mkdirSync(N,{recursive:!0});let T=Lp.join(N,E),k=`# Board - ${i.title}
|
|
45
45
|
Date: ${v.toISOString()}
|
|
46
46
|
|
|
47
47
|
\`\`\`text
|
|
48
48
|
${m}
|
|
49
49
|
\`\`\`
|
|
50
|
-
`;return
|
|
51
|
-
`),l("Config written",null)}catch{return a(`Unable to write ~/${
|
|
52
|
-
`).map(u=>u.trim()),s=
|
|
50
|
+
`;return Ad.writeFileSync(T,k,"utf8"),l("Exported board layout",T)};import Kp from"node:os";import Ld from"node:path";import{z as Lt}from"zod";import{accessSync as $p,copyFileSync as Wp,existsSync as so,mkdirSync as wd,readdirSync as Md,readFileSync as Hp,renameSync as jp,rmSync as Vp,statSync as Pd,unlinkSync as Gp,writeFileSync as zp}from"node:fs";import Sn from"node:path";var ks=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Le={writeToFile:(e,t)=>{try{let n=Sn.dirname(e);so(n)||wd(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);zp(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Hp(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 so(e)&&Pd(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await $p(e),!0}catch{return!1}},mkDir:e=>wd(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Sn.parse(t);for(;;){let r=Sn.join(t,e);try{if(so(r)&&Pd(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Sn.dirname(t)}return null},readFirstJSON(e){try{if(!Le.dirExists(e))return null;let t=Md(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Sn.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)?Md(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Gp(e)}catch(t){(!ks(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Vp(e,{recursive:!0,force:!0})}catch(t){(!ks(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Sn.dirname(t)),!n?.overwrite&&so(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{jp(e,t)}catch(r){if(ks(r)&&r.code==="EXDEV"){Wp(e,t),this.rmFile(e);return}throw r}}};var qp={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},kd=Lt.object({logLevel:Lt.enum(["info","error","debug"]),preferredEditor:Lt.string().optional(),userName:Lt.string().optional(),userId:Lt.string().optional(),autoSync:Lt.boolean().nullable().optional(),autoSyncDebounceMs:Lt.number().optional(),viewMode:Lt.enum(["dense","wide"]).optional()}).partial(),Yp="config.json",Dd=()=>Ld.join(Kp.homedir(),Ue),Ds=()=>Ld.join(Dd(),Yp),Fs=()=>{try{return Le.mkDir(Dd()),l(`Ensured ~/${Ue} exists`,null)}catch{return a(`Unable to create ~/${Ue}`)}},Xp=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${Ue}/config.json JSON`)}let n=kd.safeParse(t??{});return n.success?l("Parsed config",n.data):a(`Invalid ~/${Ue}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Xn=()=>{let e=Fs();if(d(e))return a(e.message);let t=Ds(),n=Le.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Xp(n)},Fd=e=>{let t=Fs();if(d(t))return a(t.message);let n=kd.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Ds();try{return Le.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
51
|
+
`),l("Config written",null)}catch{return a(`Unable to write ~/${Ue}/config.json`)}},ht=e=>{let t=Xn();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return Fd(n)},Jn=()=>{let e=Ds(),t=Fs();if(d(t))return a(`Unable to create ~/${Ue}`);if(!(Le.readFile(e)!==null)){let p=Fd(qp);if(d(p))throw new Error(`Unable to create ~/${Ue}/config.json`)}let r=Xn();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:c,autoSyncDebounceMs:u,logLevel:m}=r.value;return!s||!i?a(`User name or ID not configured in ~/${Ue}/config.json`):(process.env.EPIQ_LOG_LEVEL=m,l("successfully loaded settings",{logLevel:m??"debug",preferredEditor:o??"",userName:s,userId:i,autoSync:c??!1,autoSyncIntervalMs:u??1e4,viewMode:"dense"}))};var io=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){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null};import{useSyncExternalStore as ZE}from"react";var ao,Jp=new Set,Bd=()=>{for(let e of Jp)e()};var kt=()=>{if(!ao)throw new Error("Ui state not initialized. Call initUiState() first.");return ao};var Ud=(e={})=>(ao=e,Bd(),l("UX state initialized",null)),Qp=e=>{let t=kt();return ao=e(t),Bd(),l("UX state updated",null)},Dt=e=>Qp(t=>({...t,...e}));import{spawn as Zp}from"node:child_process";function Bs(e){let t=process.platform,o=Zp(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}import{ulid as Us}from"ulid";import{spawnSync as ef}from"node:child_process";import tf from"node:os";import Od from"node:path";import{ulid as nf}from"ulid";function rf(){let{preferredEditor:e}=H(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function of(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function _d(e){let t=Od.join(tf.tmpdir(),"epiq");Le.mkDir(t);let n=Od.join(t,nf());Le.writeToFile(n,e??"");let r=rf();for(let o of r){let s=of(o,n),i=ef(s,{stdio:"inherit",shell:!0});if(!i.error&&i.status===0){let c=Le.readFile(n);if(c==null)return a("Unable to read edited file");let u=c.replace(/\r?\n$/,"");return l("Successfully edited",u)}}return a("Unable to open editor")}var $d=async e=>{let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(e.modifier===we.DESCRIPTION)return af();if(r&&Bn(r))return sf(e);if(e.modifier===we.TITLE){let o=Z();if(d(o))return a("Unable to resolve user ID");let s=r;if(!s)return a("Missing node");if(s.readonly)return a("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return a("Provide a title");let c=await qe();return d(c)?c:B([{id:Us(),action:"edit.title",payload:{id:s.id,name:i},...o.value}],c.value)}return a("Unknown edit command")},sf=async e=>{let t=Z();if(d(t))return a("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=f(),o=W(n.id)[r];if(!o||!Bn(o))return a("Select a comment first");if(o.readonly)return a("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return a("Unable to resolve comment issue");let i=f().nodes[s];if(!i||!w(i))return a("Unable to resolve comment issue");if(i.readonly)return a("Cannot edit readonly issue");let c=o.id.split(":").at(0)??"",u=b.getComment(c);if(!u||u.deleted)return a("Unable to resolve comment");if(u.issue!==i.id)return a("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return a("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return a("Provide a comment");let p=await qe();if(d(p))return p;let v=p.value;return B([{id:Us(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:m},...t.value}],v)},af=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let t=await qe();if(d(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=f(),s=be([...r,o],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!w(i))return a("Edit target must be an issue");if(i.readonly)return a("Cannot edit readonly issue");let c=W(i.id).find(v=>v.title===se.DESCRIPTION);if(!c)return a("No target found");if(c.readonly)return a("Cannot edit readonly field");let u=i.props.description??"";if(typeof u!="string")return a("Selected field is not editable text");let m=_d(u);if(d(m))return a("Failed to edit field");let p=m.value;return p===u?l("No changes made",null):B([{id:Us(),action:"edit.description",payload:{id:i.id,md:p},...e.value}],n)};import cf from"node:fs";import Hd from"node:path";import Os from"node:fs";import df from"node:path";var Wd=async e=>{let t=df.join(e,".gitignore"),n=Os.existsSync(t)?Os.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
52
|
+
`).map(u=>u.trim()),s=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(s.length===0)return l("Local epiq paths already ignored",!1);let c=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
53
53
|
`);return n=n.trimEnd()+`
|
|
54
54
|
|
|
55
55
|
${c}
|
|
56
|
-
`,
|
|
57
|
-
`));let Wt=Ue();if(d(Wt))return K(16,Wt.message);let{rootNodeId:Qc,nodes:Zc}=Wt.value,js=Zc[Qc];return js?(A.navigate({contextNode:js,selectedIndex:0}),C({hasProjectDefinition:!0,mode:f.DEFAULT}),l(vt,null)):K(16,"Unable to resolve initialized root node")};import{ulid as wp}from"ulid";import{ulid as Ap}from"ulid";var yd=null,Pt=()=>structuredClone(yd),Hn=e=>{yd=e},hd=()=>{let{contextNode:e,selectedIndex:t}=g(),o=H(e.id)[t];return o?l("Resolved selected child",o):a("Target node not found")},Is=({id:e,parentId:t,position:n={at:"end"}})=>{let o=H(t).filter(r=>r.id!==e);return Ro(o,n)},xd=({id:e,parentId:t,position:n={at:"end"}})=>{let o=X();if(d(o))return a("Unable to resolve user ID");let r=Is({parentId:t,id:e,position:n});return d(r)?r:l("Created pending move state",{id:Ap(),...o.value,action:"move.node",payload:{id:e,parent:t,rank:r.value.rank}})},Id=e=>{Hn(e);let t=Mn(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function bs(e){let t=hd();if(d(t))return t;let{contextNode:n,nodes:o}=g();if(!n.parentNodeId)return a("Missing parent node id");let r=o[n.parentNodeId];if(!r)return a("Missing parent node");let s=H(r.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let c=s[i+e];if(!c)return a("Missing sibling node");let u=xd({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:Id(u.value)}function Cs(e){let t=hd();if(d(t))return t;let{contextNode:n,selectedIndex:o}=g(),s=H(n.id)[o+e];if(!s)return a("Missing sibling node");let i=xd({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:Id(i.value)}var bd=()=>{let e=Pt();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,o=g().nodes[n];if(!o)return a("Move parent not found");let r=H(n).findIndex(s=>s.id===t);return r===-1?a("Moved node not found among rendered children"):(A.navigate({contextNode:o,selectedIndex:r}),l("Synchronized navigation to moved node",null))},Jo=(e,t="Moved preview")=>{if(d(e))return e;let n=bd();return d(n)?n:(C({mode:f.MOVE}),l(t,null))},Cd=async()=>{let e=X();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=q().commandMeta,{contextNode:n,selectedIndex:o}=g(),r=H(n.id)[o];if(!r)return C({mode:f.DEFAULT}),a("No move target");if(t==="start"){if(r.readonly)return a("Target node is read-only");if(o===-1)return a("No item selected");if(!r.parentNodeId)return a("Target has no parent");let s=H(r.parentNodeId),i=s.findIndex(({id:v})=>v===r.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],u=s[i+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=Is({parentId:r.parentNodeId,id:r.id,position:m});return d(p)?p:(Hn({id:wp(),action:"move.node",payload:{id:r.id,parent:r.parentNodeId,rank:p.value.rank},...e.value}),C({mode:f.MOVE}),l("Move initialized",null))}if(t==="next")return Jo(Cs(1));if(t==="previous")return Jo(Cs(-1));if(t==="to-next")return Jo(bs(1));if(t==="to-previous")return Jo(bs(-1));if(t==="confirm"){let s=Pt();if(!s)return a("No pending move to confirm");let i=await Ve();if(d(i))return i;let c=F([s],i.value);if(d(c))return c;let u=bd();return d(u)?u:(Hn(null),C({mode:f.DEFAULT}),l("Moved item",null))}return t==="cancel"?(Hn(null),C({mode:f.DEFAULT}),l("Cancelling move",null)):a("Invalid move modifier")};import{ulid as Zo}from"ulid";import{monotonicFactory as Mp,ulid as Pp}from"ulid";var Lp=Mp(),Qo=({name:e,parent:t,rank:n,user:{userId:o,userName:r}})=>{let s=Lp();return l("Created issue events",[{id:Pp(),userId:o,userName:r,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var Sd=async(e,t)=>{let n=X();if(d(n))return a("Unable to resolve user ID");let o=await Ve();if(d(o))return o;let r=o.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=g(),u=m=>{let p=F([m],r);if(d(p))return p;let v=I.getNode(p.value[0].result.id);if(!v)return a("Created node not found");if(!v.parentNodeId)return p;let S=I.getNode(v.parentNodeId);return S?(A.navigate({contextNode:S,selectedIndex:I.getSiblings(v.parentNodeId).findIndex(({id:N})=>N===v.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=I.getNode(m);if(!p)return a("Workspace not found");let v=ln(p.id,n.value,r);return d(v)?v:u({id:Zo(),action:"add.board",payload:{id:Zo(),name:t.inputString,parent:p.id,rank:v.value},...n.value})}if(t.modifier==="swimlane"){let m=Ee(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=ln(m.value.id,n.value,r);return d(p)?p:u({id:Zo(),action:"add.swimlane",payload:{id:Zo(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=$(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let j=Ee(s,"SWIMLANE");return d(j)?null:j.value})();if(!p)return a("Unable to add issue in this context");let v=ln(p.id,n.value,r);if(d(v))return v;let S=Qo({name:t.inputString,parent:p.id,rank:v.value,user:n.value});if(d(S))return S;let N=S.value,E=F([...N],r);if(d(E))return E;if(!E.value[0])return a("Issue creation failed");let D=N.find(j=>j.action==="add.issue")?.payload.id;return D?(A.navigate({contextNode:p,selectedIndex:I.getSiblings(p.id).findIndex(({id:j})=>j===D)}),l("Issue created",null)):a("Unable to determine ticket id")}return l("Success",null)};var Nd=async()=>{let e=Ee(g().breadCrumb,"BOARD");if(d(e))return e;let t=await xt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=We({repoRoot:t.value});if(d(n))throw new Error(n.message);let{modifier:o,inputString:r}=q().commandMeta;if(o==="now"){let R=at(n.value);if(d(R))return a(R.message);let M=Vn();if(d(M))return M;let j=Vt(R.value).filter(d);return j.length>0?a(j.map(O=>O.message).join(", ")):(C({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),l("Peeking now",!0))}let s;if(o==="prev"){let R=g().eventLog.at(-1),M=Vr(R);if(M===null)return a("No previous event to peek");s=M}else if(o==="next"){let R=g().unappliedEvents.at(0),M=Vr(R);if(M===null)return a("No next event to peek");s=M+1}else{let R=Do(o||r);if(!R)return a("Invalid peek date");s=R.getTime()}let i=g(),c=e.value.id,u=_i(n.value,s);if(d(u))return a(u.message);let{appliedEvents:m,unappliedEvents:p}=u.value,v=Vn();if(d(v))return v;let N=Vt(m).filter(d);if(N.length>0)return Vn(),C(i),a(N.map(R=>R.message).join(", "));let E=g().nodes[c];return E?(A.navigate({contextNode:E,selectedIndex:0}),C({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:p}),l("Peeking",!0)):(Vn(),C(i),a("Board did not exist at peek date"))};import kp from"zod";var Ed=()=>{let e=q().commandMeta.inputString,t=kp.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return a("Auto sync duration must be a number of at least 3000 ms");let n=mt({autoSyncDebounceMs:t.data});return d(n)?n:(Fe({autoSyncIntervalMs:t.data}),C({mode:f.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))};var Rd=()=>{let e=q().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=ua(e),n=mt({autoSync:t});return d(n)?n:(Fe({autoSync:t}),C({mode:f.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var Td=()=>{let e=q().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=mt({logLevel:e});return d(n)?n:(Fe({logLevel:e}),C({mode:f.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var Ad=async()=>{W(""),C({mode:f.DEFAULT});let e=Ue();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");C({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await wo();return d(t)?(C({syncStatus:{msg:t.message,status:"failed"}}),t):(C({mode:f.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var Dp=e=>e.action==="add.issue.comment",wd=e=>Object.values(g().tags).find(t=>t.name===e),Md=e=>Object.values(g().contributors).find(t=>t.name===e),pt=async()=>{let e=await Ve();return d(e)?e:l("Resolved persist root",e.value)},er=[{systemOnly:!0,intent:P.Move,description:"Internal move-state command",mode:f.COMMAND_LINE,action:Cd},{intent:P.Delete,description:"Delete the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=$(t.id)[n];if(!o)return a("Unable to resolve child to delete");let r=await pt();if(d(r))return r;if(o.context==="COMMENT"){let s=o.id,i=T(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=g().nodes[i];if(!c||!T(c))return a("Unable to resolve comment issue");let u=c.log?.filter(Dp).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):F([{id:fe(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],r.value):a("Unable to resolve comment")}return F([{id:fe(),action:"delete.node",payload:{id:o.id},...e.value}],r.value)},onSuccess:()=>C({mode:f.DEFAULT})},{intent:P.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:f.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=q().commandMeta,n=/(!=|=)/,[o]=e.split(n);if(!o||!(i=>ae(h.FILTER).map(c=>c.split(n)[0]).includes(i))(o))return a("Invalid filter modifier");let s={target:o,operator:"=",value:t.trim()};return ue(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:f.DEFAULT})),l("Filter updated",null)}},{intent:P.ViewHelp,description:"Open the help screen",mode:f.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return Mt({pendingNavTarget:{contextNode:e,breadCrumb:o,selectedIndex:t,selectedNode:n}}),C({mode:f.HELP}),l("Viewing help",null)}},{intent:P.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=$(t.id)[n];if(!o)return a("Unable to close issue, no target found");if(!T(o))return a("Cannot close in this context");let r=g().nodes[ie];if(!r)return a("Unable to locate closed swimlane");if(o.parentNodeId===r.id)return a("Issue is already closed");let s=await pt();if(d(s))return s;let i=s.value,c=zt(r.id,o.id,{at:"end"},e.value,i);if(d(c))return c;let u=F([{id:fe(),action:"close.issue",payload:{id:o.id,parent:r.id,rank:c.value},...e.value}],i);return d(u)?u:l("Issue closed",null)},onSuccess:()=>C({mode:f.DEFAULT})},{intent:P.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=$(t.id)[n];if(!o)return a("Unable to reopen issue, no target found");let r=o.context==="TICKET"?l("Resolved ticket",o):it(o.id,"TICKET");if(d(r))return a("Cannot reopen in this context");let s=r.value,i=g().nodes[ie];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!T(s))return a("Target node is not issue");let c=Yo(s);if(!c)return a("Unable to resolve previous parent from issue history");if(c===i.id)return a("Previous parent resolves to closed swimlane");let u=g().nodes[c];if(!u)return a("Previous parent no longer exists");let m=await pt();if(d(m))return m;let p=m.value,v=zt(u.id,s.id,{at:"end"},e.value,p);if(d(v))return v;let S=F([{id:fe(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:v.value},...e.value}],p);return d(S)?S:l("Issue reopened",null)},onSuccess:()=>C({mode:f.DEFAULT})},{intent:P.Init,description:"Initialize Epiq in the current git repository",mode:f.COMMAND_LINE,action:vd},{intent:P.NewItem,description:"Create a new board, swimlane, or issue",mode:f.COMMAND_LINE,action:Sd,onSuccess:()=>C({mode:f.DEFAULT})},{intent:P.Rename,description:"itle] Rename the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=$(t.id)[n];if(!o)return a("Missing node");if(o.readonly)return a("Cannot rename readonly node");let r=Fa();if(!r)return a("Provide a title");let s=await pt();return d(s)?s:F([{id:fe(),action:"edit.title",payload:{id:o.id,name:r},...e.value}],s.value)},onSuccess:()=>C({mode:f.DEFAULT})},{intent:P.UntagTicket,description:"Remove a tag from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,o=(t||n).trim();if(!o)return a("Provide a tag");let r=wd(o);if(!r)return a(`Tag "${o}" does not exist`);let{selectedNode:s}=g();if(!s)return a("Invalid untag target");let i=it(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let c=i.value;if(!T(c))return a("Target node is not issue");if(!(c.props.tags??[]).includes(r.id))return a("Issue is not tagged with that tag");let m=await pt();return d(m)?m:F([{id:fe(),action:"remove.issue.tag",payload:{id:c.id,tag:r.id},...e.value}],m.value)},onSuccess:()=>C({mode:f.DEFAULT})},{intent:P.TagTicket,description:"Add or create a tag on the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,o=(t||n).trim();if(!o)return a("Provide a tag");let{selectedNode:r}=g();if(!r)return a("Invalid tag target");let s=it(r.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!T(i))return a("Target node is not issue");let c=await pt();if(d(c))return c;let u=wd(o),m=u?.id??fe();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):F([...u?[]:[{id:fe(),action:"create.tag",payload:{id:m,name:o},...e.value}],{id:fe(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)},onSuccess:()=>C({mode:f.DEFAULT})},{intent:P.AssignUserToTicket,description:"Assign a user to the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,o=(t||n).trim();if(!o)return a("Provide an assignee");let{selectedIndex:r,contextNode:s}=g(),i=$(s.id)[r];if(!i)return a("Invalid assign target");let c=it(i.id,"TICKET");if(d(c))return a("Unable to assign issue in this context");let u=c.value;if(!T(u))return a("Target node is not issue");let m=await pt();if(d(m))return m;let p=Md(o),v=p?.id??fe();return(u.props.assignees??[]).includes(v)?a("Assignee already assigned"):F([...p?[]:[{id:fe(),action:"create.contributor",payload:{id:v,name:o},...e.value}],{id:fe(),action:"add.issue.assignee",payload:{id:u.id,assignee:v},...e.value}],m.value)},onSuccess:()=>C({mode:f.DEFAULT})},{intent:P.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=X();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,o=(t||n).trim();if(!o)return a("Provide an assignee to remove");let r=Md(o);if(!r)return a(`Assignee "${o}" does not exist`);let{selectedNode:s}=g();if(!s)return a("Invalid unassign target");let i=it(s.id,"TICKET");if(d(i))return a("Unable to unassign in this context");let c=i.value;if(!T(c))return a("Target node is not issue");if(!(c.props.assignees??[]).includes(r.id))return a(`Issue is not assigned to "${o}"`);let m=await pt();return d(m)?m:F([{id:fe(),action:"remove.issue.assignee",payload:{id:c.id,assignee:r.id},...e.value}],m.value)},onSuccess:()=>C({mode:f.DEFAULT})},{intent:P.Comment,description:"Add a comment to the selected issue",mode:f.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return a("Provide a comment");if(n.length>pn)return a(`Cannot exceed ${pn} characters`);let o=X();if(d(o))return a("Unable to resolve user ID");let{breadCrumb:r,selectedNode:s}=g(),i=Ee([...r,s],"TICKET");if(d(i))return a("Edit target must be an issue");let c=i.value;if(!c)return a("Invalid comment target");let u=c.context==="TICKET"?l("Resolved ticket",c):it(c.id,"TICKET");if(d(u))return a("Unable to comment on issue in this context");let m=u.value;if(!T(m))return a("Target node is not issue");let p=await pt();return d(p)?p:F([{id:fe(),action:"add.issue.comment",payload:{id:fe(),issue:m.id,author:o.value.userId,md:n},...o.value}],p.value)},onSuccess:()=>C({mode:f.DEFAULT})},{intent:P.Sync,description:"Pull, commit, and push Epiq state",mode:f.COMMAND_LINE,action:Ad},{intent:P.Peek,description:"View board state at another point in time",mode:f.COMMAND_LINE,action:Nd},{intent:P.Export,description:"Export the current board layout to markdown",mode:f.COMMAND_LINE,action:async()=>{let e=await td();return d(e)?e:(C({mode:f.DEFAULT}),l("Export successful",!0))}},{intent:P.Exit,description:"Exit the application",mode:f.COMMAND_LINE,action:async()=>(A.exit(),l("Exit successful",!0))},{intent:P.Edit,description:"Edit title or description",mode:f.COMMAND_LINE,action:async(e,t)=>pd(t),onSuccess:()=>C({mode:f.DEFAULT})},{intent:P.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:f.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case se.USERNAME:{let{userId:o,preferredEditor:r,userName:s}=_(),i=n||s,c=o??fe();if(!i||!c)return a("Unable to resolve user name or id");let u=mt({userName:i,userId:c,preferredEditor:r??""});return d(u)?u:(Fe({userName:i,userId:c}),C({mode:f.DEFAULT}),l(`Username set to "${i}"`,null))}case se.EDITOR:{if(!n)return a("No editor provided");let o=mt({preferredEditor:n});return d(o)?o:(Fe({preferredEditor:n}),C({mode:f.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case se.VIEW:return n!=="wide"&&n!=="dense"?a("Invalid view mode"):(Fe({viewMode:n}),l(`View set to "${n}"`,null));case se.AUTOSYNC:return Rd();case se.LOG_LEVEL:return Td();case se.SYNC_DEBOUNCE_MS:return Ed();default:return a("Unknown config command")}}},{intent:P.Coffee,description:"Sponsor the development of Epiq!",mode:f.COMMAND_LINE,action:()=>{let e=q().commandMeta.modifier;return e==="custom"?ys("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):ys(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),W(""),l("Thanks you!",null)}}];var Fp=new Set(["peek","filter","view-help"]),Ze=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:o,inputString:r}}=q();if(!t)return a("No command to confirm");if(!e&&n===Et.Invalid)return a("Invalid command");let s=$o(t);Ma();let{readOnly:i}=g();if(i&&!Fp.has(s))return Un({status:ht.Fail,message:"Command not available in readonly state",value:null});let c=er.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return Un({status:ht.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:r,modifier:o})}catch(m){return Un({status:ht.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?Un(u):(Pa({addToHistory:!e}),c.onSuccess?.(),_().autoSync&&Po(),u)};var tr=[{intent:x.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(C({mode:f.COMMAND_LINE}),W("move cancel"),Ze({isForceExecutedBySystem:!0}))},{intent:x.InitMove,mode:f.DEFAULT,description:"[m] move (init/confirm)",action:()=>(C({mode:f.COMMAND_LINE}),W("move start"),Ze({isForceExecutedBySystem:!0}))},{intent:x.ConfirmMove,mode:f.MOVE,action:()=>(C({mode:f.COMMAND_LINE}),W("move confirm"),Ze({isForceExecutedBySystem:!0}))}],nr=[{intent:x.MovePreviousItem,mode:f.MOVE,action:()=>Pt()?(C({mode:f.COMMAND_LINE}),W("move previous"),Ze({isForceExecutedBySystem:!0})):a("No pending move")},{intent:x.MoveNextItem,mode:f.MOVE,action:()=>Pt()?(C({mode:f.COMMAND_LINE}),W("move next"),Ze({isForceExecutedBySystem:!0})):a("No pending move")}],Pd=[{intent:x.MoveToNextContainer,mode:f.MOVE,action:()=>Pt()?(C({mode:f.COMMAND_LINE}),W("move to-next"),Ze({isForceExecutedBySystem:!0})):a("No pending move")},{intent:x.MoveToPreviousContainer,mode:f.MOVE,action:()=>Pt()?(C({mode:f.COMMAND_LINE}),W("move to-previous"),Ze({isForceExecutedBySystem:!0})):a("No pending move")}];var Ld={[w.WORKSPACE]:[...tr,...nr],[w.BOARD]:[...tr,...nr],[w.SWIMLANE]:[...tr,...nr,...Pd],[w.TICKET]:[],[w.FIELD]:[],[w.FIELD_LIST]:[],[w.TEXT]:[],[w.COMMENT]:[]};var kd=()=>{W("");let{pendingNavTarget:e}=wt();C({mode:f.DEFAULT}),e&&A.navigate(e),Mt({pendingNavTarget:void 0})},Dd=[{intent:x.ExitCommandLine,mode:f.HELP,action:()=>(kd(),l("Exiting help",null))},{intent:x.Exit,mode:f.HELP,action:()=>(kd(),l("Closed help",null))},{intent:x.NavPreviousItem,mode:f.HELP,description:"[arrows/hjkl] navigate",action:()=>(A.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:x.NavNextItem,mode:f.HELP,action:()=>(A.navigateToNextItem(),l("Navigating to next help item",null))},{intent:x.NavToPreviousContainer,mode:f.HELP,action:()=>(A.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:x.NavToNextContainer,mode:f.HELP,action:()=>(A.navigateToNextContainer(),l("Navigating to next help container",null))}];var Bp=e=>{C({mode:f.COMMAND_LINE});let{pendingNavTarget:t}=wt();t&&A.navigate(t),Mt({pendingNavTarget:void 0}),W(`${e} `)},Fd=()=>{W("");let{pendingNavTarget:e}=wt();e&&A.navigate(e),Mt({pendingNavTarget:void 0}),C({mode:f.DEFAULT})},Bd=[{intent:x.InitCommandPalette,mode:f.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{W("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return Mt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}}),C({mode:f.PALETTE}),l("Opening command palette",null)}},{intent:x.Confirm,mode:f.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!bt(e))return a("Command only applicable on text nodes");if(e.props.disabled)return a("Command is not available in this context");let t=e.title;return t?(Bp(t),l("Selected command",t)):l("No command selected",null)}},{intent:x.ExitCommandLine,mode:f.PALETTE,action:()=>(Fd(),l("Exiting palette",null))},{intent:x.Exit,mode:f.PALETTE,action:()=>(Fd(),l("Closed command palette",null))},{intent:x.NavPreviousItem,mode:f.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(A.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:x.NavNextItem,mode:f.PALETTE,action:()=>(A.navigateToNextItem(),l("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:f.PALETTE,action:()=>(A.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:f.PALETTE,action:()=>(A.navigateToNextContainer(),l("Navigating to next container",null))}];var Ud=[...Dd,...Bd,{intent:x.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(C({mode:f.COMMAND_LINE}),W(`${h.NEW} `),l("Adding new item",null))},{intent:x.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(C({mode:f.COMMAND_LINE}),W(`${h.DELETE} `),l("Deleting item",null))},{intent:x.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(C({mode:f.COMMAND_LINE}),W(""),l("Entering command line mode",null))},{intent:x.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!H(e?.id??"")?.length){if(e?.title===oe.DESCRIPTION)return C({mode:f.COMMAND_LINE}),W(`${h.EDIT} description `),l("Propose command",!0);if(e?.title===oe.ASSIGNEES)return C({mode:f.COMMAND_LINE}),W(`${h.ASSIGN} `),l("Propose command",!0);if(e?.title===oe.TAGS)return C({mode:f.COMMAND_LINE}),W(`${h.TAG} `),l("Propose command",!0);if(t.title===oe.DESCRIPTION&&e?.context==="TEXT")return C({mode:f.COMMAND_LINE}),W(`${h.EDIT} description `),l("Propose command",!0)}return A.enterChildNode(),l("Entering context",null)}},{intent:x.EditTitle,mode:f.DEFAULT,description:"[r] rename title",action:()=>(C({mode:f.COMMAND_LINE}),W(`${h.EDIT} title ${g().selectedNode?.title}`),l("Exiting context",null))},{intent:x.EditDescription,mode:f.DEFAULT,description:"[e] edit description",action:()=>(C({mode:f.COMMAND_LINE}),W(`${h.EDIT} description `),l("Exiting context",null))},{intent:x.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(A.enterParentNode(),l("Exiting context",null))},{intent:x.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(A.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:x.NavNextItem,mode:f.DEFAULT,action:()=>(A.navigateToNextItem(),l("Navigating to next item",null))},{intent:x.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(A.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:x.NavToNextContainer,mode:f.DEFAULT,action:()=>(A.navigateToNextContainer(),l("Navigating to next container",null))}];var Up=500,Op=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Od=e=>{let t=Op(e);t&&Wo(n=>(n+t).slice(0,Up))};var Wp=[f.COMMAND_LINE,f.PALETTE],$p=e=>[{intent:x.MoveCursorLeft,mode:e,action:()=>(is(-1),l("Moving cursor left",null))},{intent:x.MoveCursorRight,mode:e,action:()=>(is(1),l("Moving cursor right",null))},{intent:x.MoveCursorLeftOfWord,mode:e,action:()=>(as("left"),l("Moving cursor left of word",null))},{intent:x.MoveCursorRightOfWord,mode:e,action:()=>(as("right"),l("Moving cursor right of word",null))},{intent:x.AutoCompleteCommand,mode:e,action:()=>(Wo((t,{remainder:n})=>{let o=n?t+n:t,r="";return o==="edit title "&&(r=g().selectedNode?.title??""),o+r}),l("Auto-completing command",null))},{intent:x.CaptureInput,mode:e,action:(t,{sequence:n})=>(Od(n??""),l("Capturing input",null))},{intent:x.EraseInput,mode:e,action:()=>(Aa(),l("Erasing input",null))},{intent:x.EraseInputWord,mode:e,action:()=>(wa(),l("Erasing input word",null))}],Wd=[{intent:x.Confirm,mode:f.COMMAND_LINE,action:()=>(Ze(),l("Executing command",null))},{intent:x.ViewHelp,mode:f.DEFAULT,action:()=>(C({mode:f.HELP}),l("Viewing help",null))},...Wp.flatMap($p),{intent:x.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(C({mode:f.DEFAULT}),l("Exiting command line",null))},{intent:x.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(La(),l("Getting last command from history",null))},{intent:x.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(ka(),l("Getting next command from history",null))}];import jd from"chalk";var or=jd.dim.hex(y.secondary2)(": for command line"),$d="q to exit",_d=`${jd.hex(y.accent)("m")} to confirm`,Ss={[w.WORKSPACE]:[or],[w.BOARD]:[or],[w.BOARD+f.COMMAND_LINE]:[or],[w.SWIMLANE]:[or],[w.TICKET+f.HELP]:[$d],[w.SWIMLANE+f.HELP]:[$d],[w.TICKET]:[],[w.FIELD]:[],[w.SWIMLANE+f.MOVE]:[_d],[w.TICKET+f.MOVE]:[_d]};var Gn=e=>e.trim().toLocaleLowerCase(),_p=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},jp=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},Hd=(e,t)=>{let n=Gn(t.value);if(!n)return!0;switch(t.target){case"title":return Gn(e.title??"").includes(n);case"description":return Gn(e.props.description??"").includes(n);case"tag":return _p(e).map(Gn).some(r=>r.includes(n));case"assignee":return jp(e).map(Gn).some(r=>r.includes(n));default:return!0}};function Vd(e,t,n){let o=t[e];if(!o)return a("buildBreadCrumb(): current node not found");let r=[],s=o;for(;s&&(r.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let i=r[r.length-1];return!i||i.id!==n?a("buildBreadCrumb(): node is not connected to root"):(r.reverse(),l("Breadcrumb built",r))}var Gd=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 Zt,Ns,Es=new Set,zd=()=>{for(let e of Es)e()},Vp=e=>(Es.add(e),()=>Es.delete(e));function Kd(e){let{contextNodeId:t,mode:n,rootNodeId:o,nodes:r,filters:s}=e;if(!t)return a("derive(): contextNodeId is missing");if(!o)return a("derive(): rootNode is missing");if(!r[o])return a("derive(): unable to find root node");let c=r[t];if(!c)return a("Unable to derive state, contextNode not found");let u=Vd(t,r,o);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,v=Ss[p+n]??Ss[p]??[],S=[...Ud,...Ld[p]??[],...Wd],N=Gd(S),E=Gp(r,s),R=E[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:v,availableActions:S,actionIndex:N,selectedNode:R,renderedChildrenIndex:E})}var g=()=>{if(!Zt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Zt},Ue=()=>Zt?l("Retrieved state",Zt):a("State not initialized. Call initWorkspaceState() first.");function Pn(e){Ns=e;let t=He(process.cwd()),n=!1;if(!d(t)){let s=It(t.value);if(d(s))return a(s.message);n=!0}let o={readOnly:!1,filters:[],tags:{},contributors:{},mode:f.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{}},r=Kd(o);return d(r)?r:(Zt=r.value,zd(),l("State initialized",null))}function ue(e){let t=g(),n=e(t),o=Kd(n);return d(o)?a(o.message??"Unable to update state"):(Zt=o.value,zd(),l("State updated",null))}var C=e=>ue(t=>({...t,...e}));var z=()=>Hp(Vp,g,g),Gp=(e,t)=>{let n={};for(let o of Object.values(e))T(o)&&t.length>0&&!t.every(r=>Hd(o,r))||!o.parentNodeId||o.isDeleted||((!o.parentNodeId||!n[o.parentNodeId])&&(n[o.parentNodeId]=[]),n[o.parentNodeId].push(o));for(let o of Object.keys(n))n[o].sort((r,s)=>{let i=e[r.id],c=e[s.id];return!i||!c?0:i.rank.localeCompare(c.rank)});return n},$=e=>g()?.renderedChildrenIndex[e]??[],Vn=()=>Ns?Pn(Ns):a("Cannot reset state: no initial workspace found"),mn=()=>Zt!==void 0;var Rs=e=>{mn()&&(C({syncStatus:e}),_t({type:"sync-status",payload:e}))},rr=(e="Syncing...")=>{Rs({status:"syncing",msg:e})},sr=(e="Synced")=>{Rs({status:"synced",msg:e})},Ts=e=>{Rs({status:"failed",msg:e})},Oe=e=>(Ts(e),a(e));import{decodeTime as tw}from"ulid";var zp=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=G("getRepoRootDir",await xt(e));if(d(n))return a(n.message);let o=n.value;logger.debug("[sync] repo root",o);let r=G("getStateBranchRoot",We({repoRoot:o}));if(d(r))return a(r.message);let s=r.value;logger.debug("[sync] state branch root",s);let i=G("ensureInitialCommit",await pi(o));if(d(i))return a(i.message);logger.debug("[sync] initial commit result",{created:i.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:s,ensureUpstream:t});let c=G("bootstrapStateBranchStorage",await fi({repoRoot:o,stateBranchRoot:s,ensureUpstream:t}));if(d(c))return a(c.message);logger.debug("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let u=G("hasInProgressGitOperation(stateBranchRoot)",await ao(s));if(d(u))return a(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value)return logger.info("[sync] state branch git operation in progress"),a("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:s});let m=G("ensureStateBranchLayout",li(o,s));return d(m)?a(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:s,bootstrapped:c.value}),l("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:s,bootstrapped:c.value}))},Kp=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let o=G("stageStateBranchOwnEventFile",await go({stateBranchRoot:t,eventFileName:n}));if(d(o))return a(o.message);let r=G("hasStagedChanges(after stage)",await ri(t));if(d(r))return a(r.message);if(logger.debug("[sync] state branch change check after stage result",{changed:r.value}),!r.value)return logger.info("[sync] no own event file changes to commit"),l("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let s=G("createStateBranchSyncCommit",await gi({repoRoot:e,stateBranchRoot:t}));return d(s)?a(s.message):(logger.debug("[sync] created sync commit",s.value),l("Committed own event file",{createdCommit:!0,commitSha:s.value}))},Mo=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),a("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),a("Own event file must end with .jsonl");rr();let n=G("ensureSyncReady",await zp({cwd:e,ensureUpstream:!0}));if(d(n))return Oe(n.message);let{repoRoot:o,stateBranchRoot:r,bootstrapped:s}=n.value,i=G("isDetachedHead(stateBranchRoot)",await si(r));if(d(i))return Oe(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return Oe("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,v=G("getStateBranch",on(o));if(d(v))return Oe(v.message);let S=v.value;logger.debug("[sync] resolved state branch",{stateBranch:S,stateBranchRoot:r});let N=G("commitOwnEventFileToStateBranch",await Kp({repoRoot:o,stateBranchRoot:r,ownEventFileName:t}));if(d(N))return Oe(N.message);c=N.value.createdCommit,u=N.value.commitSha;let E=G("pullBranchRebaseIfPresent",await kr({cwd:r,branch:S}));if(d(E))return Oe(E.message);if(m=E.value,c||s){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:r});let R=G("pushStateBranch",await En({stateBranchRoot:r,repoRoot:o}));if(d(R)&&oi(R.message)){let M=G("pullBranchRebaseIfPresent(retry)",await kr({cwd:r,branch:S}));if(d(M))return Oe(M.message);m=m||M.value,R=G("pushStateBranch(retry)",await En({stateBranchRoot:r,repoRoot:o}))}if(d(R))return Oe(R.message);p=R.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:r});let R=G("git rev-parse HEAD",await B({args:["rev-parse","HEAD"],cwd:r}));if(d(R))return Oe(R.message);u=R.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return sr(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),l("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:s})};var As=e=>{let t=He(e??process.cwd());return d(t)?a(t.message):l("Resolved Epiq repo root",t.value)},we=async e=>{let t=As(e);if(d(t))return t;let n=We({repoRoot:t.value});if(d(n))return a(n.message);let o=nn(),r=await $t({repoRoot:t.value,stateBranchRoot:n.value,stateBranchName:o.stateBranch});if(d(r))return a(r.message);let s=await B({cwd:n.value,args:["pull","--ff-only"]});d(s)&&te.info(3,s.message);let i=at(n.value);if(d(i))return a(i.message);let c=Kt(i.value);return d(c)?a(c.message):l("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:n.value})},Me=()=>{let e=jn();return d(e)?a(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},_e=()=>{let e=Ue();return d(e)?a(e.message):e},qd=e=>(e.props.tags??[]).map(t=>I.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:re(t.name)})),Yd=e=>(e.props.assignees??[]).map(t=>I.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:re(t.name)}));var Xd=async e=>{let t=await we(e.repoRoot);if(d(t))return t;let n=_e();if(d(n))return n;let o=Object.values(n.value.nodes).filter(T).filter(r=>e.includeClosed||r.parentNodeId!==ie).map(r=>({id:r.id,title:St(r.title),description:r.props.description??"",parentNodeId:r.parentNodeId,isClosed:r.parentNodeId===ie,readonly:!!r.readonly,tags:qd(r),assignees:Yd(r)}));return l("Listed issues",o)},Jd=async e=>{let t=await we(e.repoRoot);if(d(t))return t;let n=Me();if(d(n))return n;let o=ln(e.parentId,n.value,t.value.stateBranchRoot);if(d(o))return o;let r=Qo({name:e.title,parent:e.parentId,user:n.value,rank:o.value});if(d(r))return r;let s=r.value,i=F([...s],t.value.stateBranchRoot);if(d(i))return a(i.message);let c=s.find(u=>u.action==="add.issue")?.payload.id;return c?l("Created issue",{id:c,title:e.title,parentId:e.parentId}):a("Unable to determine created issue id")},Qd=async e=>{let t=await we(e.repoRoot);if(d(t))return t;let n=Me();if(d(n))return n;let o=zt(ie,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(d(o))return o;let r={id:ve(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ie,rank:o.value}},s=F([r],t.value.stateBranchRoot);return d(s)?a(s.message):l("Closed issue",{id:e.issueId})},Zd=async e=>{let t=await we(e.repoRoot);if(d(t))return t;let n=Me();if(d(n))return n;let o=_e();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!T(r))return a("Target node is not issue");if(r.parentNodeId!==ie)return a("Issue is not closed");let s=Yo(r);if(!s)return a("Unable to resolve previous parent from issue history");if(s===ie)return a("Previous parent resolves to closed swimlane");let i=o.value.nodes[s];if(!i)return a("Previous parent no longer exists");let c=zt(i.id,r.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(c))return c;let u={id:ve(),...n.value,action:"reopen.issue",payload:{id:r.id,parent:i.id,rank:c.value}},m=F([u],t.value.stateBranchRoot);return d(m)?a(m.message):l("Reopened issue",{id:r.id,parentId:i.id})},ec=async e=>{let t=As(e.repoRoot);if(d(t))return t;let n=Me();if(d(n))return n;let o=We({repoRoot:t.value});if(d(o))return o;let r=at(o.value);if(d(r))return r;let s=Kt(r.value);if(d(s))return s;let i=zt(e.parentId,e.issueId,e.position??{at:"end"},n.value,o.value);if(d(i))return i;let c={id:ve(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:i.value}},u=F([c],o.value);return d(u)?a(u.message):l("Moved issue",{id:e.issueId,parentId:e.parentId})},ir=async(e={})=>{rr();let t=As(e.repoRoot);if(d(t))return a("Sync failed");let n=Me();if(d(n))return n;let o=await Mo({cwd:t.value,ownEventFileName:Gt(n.value)});return d(o)?(Ts(o.message),o):(sr(),l("Synced",o.value))};var Lt=async(e={})=>{let t=await we(e.repoRoot);if(d(t))return t;let n=_e();if(d(n))return n;let o=Object.values(n.value.nodes),r=o.filter(m=>vo(m)&&!m.isDeleted),s=new Map,i=new Map;for(let m of o)if(!m.isDeleted){if(Ct(m)&&m.parentNodeId){let p=s.get(m.parentNodeId)??[];p.push(m),s.set(m.parentNodeId,p)}if(T(m)&&m.parentNodeId){let p=i.get(m.parentNodeId)??[];p.push(m),i.set(m.parentNodeId,p)}}let c=jn();if(d(c))return c;let u={};for(let m of o.filter(T))m.isDeleted||(u[m.id]=I.getCommentsByIssue(m.id).map(p=>{let v=I.getContributor(p.authorId);return{id:p.id,issueId:p.issue,body:p.md,author:{id:p.authorId,name:v?.name??"Unknown",color:re(v?.name??p.authorId)},createdAt:qp(p.id)}}));return l("Retrieved Epiq GUI state",{boards:r.sort((m,p)=>m.rank.localeCompare(p.rank)).map(m=>({id:m.id,title:m.title,swimlanes:(s.get(m.id)??[]).sort((p,v)=>p.rank.localeCompare(v.rank)).map(p=>({id:p.id,title:p.title,readonly:!!p.readonly,issues:(i.get(p.id)??[]).sort((v,S)=>v.rank.localeCompare(S.rank)).map(v=>({id:v.id,title:St(v.title),description:v.props.description??"",readonly:!!v.readonly,tags:qd(v),assignees:Yd(v),parentNodeId:v.parentNodeId,isClosed:v.parentNodeId===ie})),parentNodeId:p.parentNodeId}))})),tags:Object.values(n.value.tags).map(m=>({...m,color:re(m.name)})),contributors:Object.values(n.value.contributors).map(m=>({...m,color:re(m.name)})),user:{name:c.value.userName??"",id:c.value.userId??"",color:re(c.value.userName??"")},commentsByIssueId:u})},tc=async e=>{let t=await we(e.repoRoot);if(d(t))return t;let n=Me();if(d(n))return n;let o=_e();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!T(r))return a("Edit target must be an issue");if(r.readonly)return a("Cannot edit readonly issue");let s=r.props.description??"";if(s===e.description)return l("No changes made",{id:e.issueId,description:s});let i={id:ve(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=F([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue description",{id:e.issueId,description:e.description})},nc=async e=>{let t=await we(e.repoRoot);if(d(t))return t;let n=Me();if(d(n))return n;let o=_e();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!T(r))return a("Edit target must be an issue");if(r.readonly)return a("Cannot edit readonly issue");let s=St(e.title);if(!s.trim())return a("Issue title cannot be empty");if(r.title===s)return l("No changes made",{id:e.issueId,title:s});let i={id:ve(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=F([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue title",{id:e.issueId,title:s})},oc=async e=>{let t=await we(e.repoRoot);if(d(t))return t;let n=Me();if(d(n))return n;let o=_e();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!T(r))return a("Tag target must be an issue");if(r.readonly)return a("Cannot tag readonly issue");let s=St(e.tagName).trim();if(!s)return a("Tag name cannot be empty");let i=Object.values(o.value.tags).find(p=>p.name===s),c=i?.id??ve(),u=[...i?[]:[{id:ve(),...n.value,action:"create.tag",payload:{id:c,name:s}}],{id:ve(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:c}}],m=F(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue tag",{id:e.issueId,tag:{id:c,name:s}})},rc=async e=>{let t=await we(e.repoRoot);if(d(t))return t;let n=Me();if(d(n))return n;let o=_e();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!T(r))return a("Untag target must be an issue");if(r.readonly)return a("Cannot untag readonly issue");if(!o.value.tags[e.tagId])return a("Tag not found");let s={id:ve(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=F([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue tag",{id:e.issueId,tagId:e.tagId})},sc=async e=>{let t=await we(e.repoRoot);if(d(t))return t;let n=Me();if(d(n))return n;let o=_e();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!T(r))return a("Assign target must be an issue");if(r.readonly)return a("Cannot assign readonly issue");let s=St(e.assigneeName).trim();if(!s)return a("Assignee name cannot be empty");let i=Object.values(o.value.contributors).find(p=>p.name===s),c=i?.id??ve(),u=[...i?[]:[{id:ve(),...n.value,action:"create.contributor",payload:{id:c,name:s}}],{id:ve(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:c}}],m=F(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue assignee",{id:e.issueId,assignee:{id:c,name:s}})},ic=async e=>{let t=await we(e.repoRoot);if(d(t))return t;let n=Me();if(d(n))return n;let o=_e();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!T(r))return a("Unassign target must be an issue");if(r.readonly)return a("Cannot unassign readonly issue");if(!o.value.contributors[e.assigneeId])return a("Assignee not found");let s={id:ve(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=F([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},ar=async e=>{let t=await we(e.repoRoot);if(d(t))return t;let n=Me();if(d(n))return n;let o=_e();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!T(r))return a("Comment target must be an issue");if(r.readonly)return a("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return a("Comment cannot be empty");let i=ve(),c={id:ve(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},u=F([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Added issue comment",{id:i,issueId:e.issueId,body:s})},dr=async e=>{let t=await we(e.repoRoot);if(d(t))return t;let n=Me();if(d(n))return n;let o=_e();if(d(o))return o;let r=o.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!r)return a("Unable to resolve comment");if(r.payload.author!==n.value.userId)return a("You can only delete your own comments");let s=o.value.nodes[r.payload.issue];if(!s)return a("Issue not found");if(!T(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot delete comment on readonly issue");if(o.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return l("Comment already deleted",{id:e.commentId,issueId:r.payload.issue});let c={id:ve(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:r.payload.issue}},u=F([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Deleted issue comment",{id:e.commentId,issueId:r.payload.issue})};var ac=e=>{let t,n,o=!1,r=!1,s=!1,i=()=>{let p=_n();if(d(p))return te.error(p.message);let{autoSync:v,userName:S,preferredEditor:N}=p.value;return!!(v&&S&&N)},c=async()=>{if(!o){if(r){s=!0;return}r=!0;try{await ir({repoRoot:e.repoRoot}),_t({type:"state",payload:await Lt({repoRoot:e.repoRoot})})}finally{r=!1,s&&(s=!1,c())}}},u=(p=750)=>{o||(n&&clearTimeout(n),n=setTimeout(()=>{c()},p))},m=()=>{if(o)return;let p=_n();if(d(p))return te.error(p.message);let{autoSyncDebounceMs:v}=p.value;i()&&(t=setTimeout(()=>{c(),m()},v??15e3))};return m(),{scheduleSync:u,dispose:()=>{o=!0,t&&clearTimeout(t),n&&clearTimeout(n)}}};import{WebSocketServer as Yp}from"ws";var Pe=(e,t)=>{e.send(JSON.stringify(t))},zn=async(e,t)=>Pe(e,{type:"state",payload:await Lt({repoRoot:t})}),et=async(e,t,n,o,r)=>{if(Pe(e,{type:o,payload:r}),d(r))return Pe(e,{type:"failed",payload:r.message});n(),zn(e,t)},dc=(e,t,{onStateChanged:n})=>{new Yp({server:e,path:"/ws"}).on("connection",r=>{vi(r),r.on("message",async s=>{try{let i=JSON.parse(s.toString()),{type:c}=i;if(c==="state:get")return zn(r,t);if(c==="sync"){let u=await ir({repoRoot:t});return Pe(r,{type:"sync:result",payload:u}),n(),zn(r,t)}if(c==="issue:comment:add"){let u=await ar({repoRoot:t,...i.payload});return et(r,t,n,"issue:comment:add:result",u)}if(c==="issue:comment:delete"){let u=await dr({repoRoot:t,...i.payload});return Pe(r,{type:"issue:comment:delete:result",payload:u}),d(u)?Pe(r,{type:"failed",payload:u.message}):(n(),zn(r,t))}if(c==="issue:edit:description"){let u=await tc({repoRoot:t,...i.payload});return et(r,t,n,"issue:edit:description:result",u)}if(c==="issue:edit:title"){let u=await nc({repoRoot:t,...i.payload});return et(r,t,n,"issue:edit:title:result",u)}if(c==="issue:tag:add"){let u=await oc({repoRoot:t,...i.payload});return et(r,t,n,"issue:tag:add:result",u)}if(c==="issue:tag:remove"){let u=await rc({repoRoot:t,...i.payload});return et(r,t,n,"issue:tag:remove:result",u)}if(c==="issue:assignee:add"){let u=await sc({repoRoot:t,...i.payload});return et(r,t,n,"issue:assignee:add:result",u)}if(c==="issue:assignee:remove"){let u=await ic({repoRoot:t,...i.payload});return et(r,t,n,"issue:assignee:remove:result",u)}if(c==="issues:list")return Pe(r,{type:"issues",payload:await Xd({repoRoot:t})});if(c==="issues:create"){let u=await Jd({...i.payload,repoRoot:t});return Pe(r,{type:"issues:create:result",payload:u}),d(u)?_t({type:"failed",payload:u.message}):(_t({type:"issue:created",payload:u.value}),n(),zn(r,t))}if(c==="issues:move"){if(!i.payload.position)return Pe(r,{type:"error",message:"Missing move position"});let u=await ec({...i.payload,repoRoot:t});return et(r,t,n,"issues:move:result",u)}if(c==="issue:close"){if(!i.payload.issueId)return Pe(r,{type:"error",message:"Missing issueId"});let u=await Qd({repoRoot:t,issueId:i.payload.issueId});return et(r,t,n,"issue:close:result",u)}if(c==="issue:reopen"){if(!i.payload.issueId)return Pe(r,{type:"error",message:"Missing issueId"});let u=await Zd({repoRoot:t,issueId:i.payload.issueId});return et(r,t,n,"issue:reopen:result",u)}return Pe(r,{type:"error",message:"Unknown message type"})}catch(i){return Pe(r,{type:"error",message:i instanceof Error?i.message:String(i)})}})})};var Zp=en.dirname(Qp(import.meta.url)),eg=process.env.IS_LOCAL==="true"?en.resolve(process.cwd(),"dist/gui"):en.join(Zp,"gui"),tt=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},tg=async e=>new Promise((t,n)=>{let o="";e.on("data",r=>{o+=r}),e.on("end",()=>{try{t(o?JSON.parse(o):{})}catch{n(new Error("Invalid JSON body"))}}),e.on("error",n)}),ng=e=>e.endsWith(".html")?"text/html; charset=utf-8":e.endsWith(".js")?"text/javascript; charset=utf-8":e.endsWith(".css")?"text/css; charset=utf-8":e.endsWith(".json")?"application/json; charset=utf-8":e.endsWith(".ico")?"image/x-icon":"application/octet-stream",cc=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),o=en.resolve(eg),r=en.resolve(o,n),s=en.relative(o,r);if(s.startsWith("..")||en.isAbsolute(s))return tt(t,403,{isError:!0,message:"Forbidden"});try{let i=await Xp(r);return t.writeHead(200,{"content-type":ng(r)}),t.end(i)}catch{return tt(t,404,{isError:!0,message:`Not found: ${n}`})}},og=async(e,t=3710)=>new Promise((n,o)=>{let r=s=>{let i=u=>{if(e.off("listening",c),u.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),r(0);return}o(u)},c=()=>{e.off("error",i);let u=e.address();if(!u||typeof u=="string"){o(new Error("Unable to resolve address"));return}n(u.port)};e.once("error",i),e.once("listening",c),e.listen(s,"127.0.0.1")};r(t)}),lc=async e=>{let t=Jp.createServer(async(r,s)=>{let i=new URL(r.url??"/","http://127.0.0.1");if(i.pathname==="/api/state")return tt(s,200,await Lt({repoRoot:e.repoRoot}));if(r.method==="POST"&&i.pathname==="/api/comments")try{let c=await tg(r);if(!c.issueId||!c.body?.trim())return tt(s,400,{isError:!0,message:"Missing issueId or body"});let u=await ar({repoRoot:e.repoRoot,issueId:c.issueId,body:c.body});return"isError"in u&&u.isError?tt(s,400,u):tt(s,200,await Lt({repoRoot:e.repoRoot}))}catch(c){return tt(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add comment"})}if(r.method==="DELETE"&&i.pathname.startsWith("/api/comments/")){let c=decodeURIComponent(i.pathname.replace("/api/comments/",""));if(!c)return tt(s,400,{isError:!0,message:"Missing comment id"});let u=await dr({repoRoot:e.repoRoot,commentId:c});return"isError"in u&&u.isError?tt(s,400,u):tt(s,200,await Lt({repoRoot:e.repoRoot}))}return i.pathname.startsWith("/board/")?cc("/",s):cc(i.pathname,s)});try{await og(t)}catch(r){return a(r instanceof Error?`Unable to start GUI server: ${r.message}`:`Unable to start GUI server: ${String(r)}`)}let n=ac({repoRoot:e.repoRoot});dc(t,e.repoRoot,{onStateChanged:()=>n.scheduleSync()}),t.on("close",n.dispose);let o=t.address();return!o||typeof o=="string"?(t.close(),a("Unable to resolve GUI server address")):l("Started GUI server",{url:`http://epiq.localhost:${o.port}${e.boardId?`/board/${e.boardId}`:""}`,server:t})};var uc=async e=>{let t=await lc({...e,boardId:""});if(d(t))return t;let{url:n}=t.value;return console.log(`Epiq GUI running at ${rg.cyan(n)}`),Vs(n),l("Started GUI",{url:n})};import{Box as Ut}from"ink";import Q from"react";import{Box as ws,Text as Kn}from"ink";import je,{useEffect as sg,useMemo as ig}from"react";import{ulid as ag}from"ulid";var mc=({text:e,match:t,color:n,highlightColor:o=y.secondary,dimColor:r=!1})=>{if(!t)return je.createElement(Kn,{color:n,dimColor:r},e);let s=e.toLowerCase(),i=t.toLowerCase(),c=s.indexOf(i);return c===-1?je.createElement(Kn,{color:n,dimColor:r},e):je.createElement(Kn,{color:n,dimColor:r},e.slice(0,c),je.createElement(Kn,{backgroundColor:o,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},pc=ag(),dg=e=>`${e}`,cg=e=>{let{pendingNavTarget:t}=wt();if(!t)return[];let{breadCrumb:n,contextNode:o,selectedNode:r}=t,s=new Set(ae(h.NONE,{breadCrumb:n,contextNode:o,readOnly:g().readOnly,selectedNode:r}));return[...new Set(Object.values(h))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==h.PALETTE).map(i=>{let c=$o(i),u=er.find(m=>m.intent===c);return{command:i,description:u?.description??`[${i}] Run command`,isAvailable:s.has(i)}}).filter(i=>i.command.toLowerCase().startsWith(e)||e.length>=2&&i.description.toLowerCase().includes(e)).sort((i,c)=>i.isAvailable!==c.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(c.command))},lg=e=>Y.text({id:pc,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),ug=(e,t,n)=>Y.text({id:dg(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Ms=[],mg=e=>{gc();let t=I.createNode(lg(g().rootNodeId));d(t)||!bt(t.value)||(Ms=[t.value,...e.map((n,o)=>ug(n,o,pc)).map(I.createNode).filter(Z).map(({value:n})=>n).filter(bt)],A.navigate({contextNode:t.value,selectedIndex:0}))},gc=()=>{let e=Ms.map(t=>t.id);Ms=[];for(let t of e)I.deleteNode(t)};function fc({width:e,height:t}){let o=Da().value.trim().toLowerCase(),r=ig(()=>cg(o),[o]);sg(()=>(mg(r),()=>{gc()}),[r]);let s=g().selectedIndex;return je.createElement(ws,{flexDirection:"column",width:e,height:t-2},je.createElement(Je,{height:t-4,itemHeight:3,selectedIndex:s},r.map((i,c)=>{let u=c===s,m=i.isAvailable?y.accent:y.secondary2,p=i.isAvailable?"":"[unavailable] ";return je.createElement(ws,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},je.createElement(Kn,{color:m,dimColor:!i.isAvailable},u?"\u276F ":" ",je.createElement(mc,{text:Ci(i.command),match:o,color:m,dimColor:!i.isAvailable})),je.createElement(ws,{paddingLeft:2},je.createElement(mc,{text:p+i.description,match:o.length>=2?o:"",color:u&&i.isAvailable?y.primary:y.secondary2,dimColor:!i.isAvailable})))})))}import{Box as Eg}from"ink";import Ls from"react";import Yn from"chalk";import{Box as Ps,Text as vc}from"ink";import qn,{useEffect as pg,useMemo as gg,useState as fg}from"react";var yc=Yn.hex(y.secondary),vg=Yn.inverse,yg=Yn.inverse.hex(y.secondary2),hg={hint:"",hints:[],overlap:0,remainder:""},xc=({value:e,command:t})=>{if(!t)return null;let n=e.trimStart(),r=e.length-n.length;return e.slice(r,r+t.length)!==t?null:{start:r,end:r+t.length}},xg=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=re(t);return{bg:o=>Yn.bgHex(n).black(o),bgCursor:o=>Yn.bgHex(n).inverse.black(o)}}return Hr(t)},Ig=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let o=xc({value:e,command:t});if(!o)return null;let s=e.slice(o.end).match(/^\s*/)?.[0].length??0,i=o.end+s;return e.slice(i,i+n.length)!==n?null:{start:i,end:i+n.length}},hc=()=>({value:ge.value,cursorPosition:ge.cursorPosition,commandIsPending:ge.commandIsPending,autoCompletion:ge.commandMeta.autoCompletion??hg,infoMessage:ge.commandMeta.infoMessage,validationStatus:ge.commandMeta.validity,command:ge.commandMeta.command,inputString:ge.commandMeta.inputString,modifier:ge.commandMeta.modifier}),bg=(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,Ic=({width:e,mode:t})=>{let[n,o]=fg(hc());pg(()=>{let S=()=>{let E=hc();o(R=>bg(R,E)?R:E)},N=ss(S);return S(),()=>{N()}},[]);let{value:r,cursorPosition:s,infoMessage:i,commandIsPending:c,autoCompletion:u,command:m,modifier:p}=n,v=gg(()=>{let S=Math.max(0,Math.min(s,r.length)),N=xc({value:r,command:m}),E=Ig({value:r,command:m,modifier:p}),R=m?Hr(m):null,M=xg({command:m,modifier:p}),D=(le,be)=>{let tn=N&&be>=N.start&&be<N.end,Wt=E&&be>=E.start&&be<E.end;return tn&&R?R.fg(le):Wt&&M?M.bg(le):le},j=(le,be)=>{let tn=N&&be>=N.start&&be<N.end,Wt=E&&be>=E.start&&be<E.end;return tn&&R?R.fgCursor(le):Wt&&M?M.bgCursor(le):vg(le)},O=r.slice(0,S),k=r[S]??" ",Ne=S<r.length?r.slice(S+1):"",ft=Array.from(O).map((le,be)=>D(le,be)).join(""),vt=j(k,S),yt=Array.from(Ne).map((le,be)=>D(le,S+1+be)).join("");if(u.hint){let le=u.hint[u.overlap]??k;vt=yg(le),yt=yc(u.remainder.slice(1)+Ne)}return yc(t===f.PALETTE?"?":":")+ft+vt+yt},[r,s,u,m,p]);return qn.createElement(Ps,{flexDirection:"column",justifyContent:"flex-start"},qn.createElement(Ps,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},qn.createElement(Ps,null,qn.createElement(vc,null,v),i&&qn.createElement(vc,{wrap:"truncate",color:c?y.red:y.secondary2},` ${i} `))))};import{Box as Cg,Text as Sg}from"ink";import bc from"react";var Ng=(e,t)=>{let n=[],o=0;for(let r of e){let i=(n.length>0?" | ":"").length+r.length;if(o+i>t-4)break;n.push(r),o+=i}return n},Cc=({width:e,availableHints:t})=>{let n=Ng(t,e).join(" | ");return bc.createElement(Cg,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1},bc.createElement(Sg,{color:y.secondary2},n.length?n:"\xA0"))};var Xn=({width:e,mode:t,availableHints:n})=>{let o=[],r=0;for(let s of n){let c=(o.length>0?" | ":"").length+s.length;if(r+c>e+2)break;o.push(s),r+=c}return Ls.createElement(Eg,null,t===f.COMMAND_LINE||t===f.PALETTE?Ls.createElement(Ic,{width:e,mode:t}):Ls.createElement(Cc,{width:e,mode:t,availableHints:n}))};import{Box as kt,Text as yn}from"ink";import Ie,{useEffect as Rg,useMemo as Tg}from"react";import{ulid as Sc}from"ulid";var lr=Sc(),Ag=()=>[...new Set([...g().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(e=>{let[t,n]=e.split("]"),o=t?.replace("[",""),r=n?.trim();return[o,r]}).filter(e=>e[0]!==void 0&&e[1]!==void 0).sort(([e],[t])=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(([e,t])=>({keys:e,action:t})),wg=e=>Y.text({id:lr,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),Mg=(e,t,n)=>Y.text({id:Sc(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),cr=[],Nc=()=>{let e=cr.filter(n=>n.id!==lr).map(n=>n.id),t=cr.filter(n=>n.id===lr).map(n=>n.id);cr=[];for(let n of[...e,...t])I.deleteNode(n)},Pg=e=>{Nc();let t=I.createNode(wg(g().rootNodeId));if(d(t)||!bt(t.value))return logger.error("Could not attach help nodes");cr=[t.value,...e.map((n,o)=>Mg(n,o,lr)).map(I.createNode).filter(Z).map(({value:n})=>n).filter(bt)],A.navigate({contextNode:t.value,selectedIndex:0})},Ec=({width:e,height:t})=>{let n=Tg(()=>Ag(),[]);Rg(()=>(Pg(n),()=>{Nc()}),[n]);let o=g().selectedIndex;return Ie.createElement(kt,{flexDirection:"column",marginTop:3,borderColor:y.secondary,borderStyle:"round",width:e,height:t-2},Ie.createElement(kt,{paddingX:1,justifyContent:"center"},Ie.createElement(yn,{color:y.accent},"Help"),Ie.createElement(yn,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),Ie.createElement(kt,{paddingX:1,marginTop:1},Ie.createElement(kt,{width:20,justifyContent:"flex-end"},Ie.createElement(yn,{color:y.secondary},"Key(s)")),Ie.createElement(kt,{flexGrow:1,width:40,paddingLeft:2},Ie.createElement(yn,{color:y.secondary},"Action"))),Ie.createElement(Je,{height:t-7,itemHeight:1,selectedIndex:o},n.map(({keys:r,action:s},i)=>{let c=i===o;return Ie.createElement(kt,{paddingX:1,key:`${r}-${s}-${i}`,flexDirection:"row"},Ie.createElement(kt,{width:20,justifyContent:"flex-end"},Ie.createElement(yn,{color:y.accent},r)),Ie.createElement(kt,{flexGrow:1,width:40,paddingLeft:2},Ie.createElement(yn,{color:c?y.primary:y.secondary2},s)))})))};import Lg from"chalk";import{Box as ur,Text as gt}from"ink";import Le from"react";var Rc=({width:e,height:t})=>Le.createElement(ur,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},Le.createElement(gt,{color:y.accent,bold:!0},"Initialize project"),Le.createElement(gt,null,`This folder is not an ${Lg.hex(y.accent)("epiq")} project yet.`),Le.createElement(gt,{color:y.primary},"To start tracking issues here, we need to initialize a new",Le.createElement(gt,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json "),"file in this repository."),Le.createElement(ur,{marginTop:1,flexDirection:"column"},Le.createElement(ur,null,Le.createElement(gt,{color:y.accent}," "),Le.createElement(gt,{color:y.primary},"Type "),Le.createElement(gt,{backgroundColor:y.secondary}," :init "))),Le.createElement(ur,{marginTop:1},Le.createElement(gt,{color:y.secondary2},"This will create, commit and push "),Le.createElement(gt,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json ")));import{Box as mr,Text as nt}from"ink";import ce from"react";var kg=({isDone:e,command:t,value:n})=>ce.createElement(mr,null,ce.createElement(nt,{color:y.accent,dimColor:e},e?" \u2714 ":" "),ce.createElement(nt,{dimColor:e},"Type "),ce.createElement(nt,{backgroundColor:y.secondary,dimColor:e}," "+t+" "),n!==void 0&&ce.createElement(ce.Fragment,null,ce.createElement(nt,{dimColor:e}," "),ce.createElement(nt,{color:y.secondary,dimColor:e},"<"+n+">"))),Dg=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function ks({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:o,userName:r,preferredEditor:s,autoSync:i,isSetAutoSync:c}=Nt(),u=[{key:"username",done:o,command:":config username",value:r,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:s,message:"Nice. Now pick your editor."},{key:"autosync",done:c,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=u.findIndex(v=>!v.done),p=m===-1?void 0:u[m];return ce.createElement(mr,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},ce.createElement(nt,{color:y.accent,bold:!0},"Welcome! \u{1F539}"),ce.createElement(nt,null,"Let's get you started - it's a breeze."),ce.createElement(nt,{color:y.secondary2},"Remember - you can always search available commands by typing:",ce.createElement(nt,{color:y.accent}," ? ")),p&&ce.createElement(nt,{color:y.secondary2},p.message),ce.createElement(mr,{flexDirection:"column"},u.map((v,S)=>m===-1||S<=m?ce.createElement(mr,{key:v.key,marginBottom:1},ce.createElement(kg,{isDone:v.done,command:v.command,value:v.done?Dg(v.value):void 0})):null)))}import yr from"chalk";import{Box as vr,Text as Qn}from"ink";import ye from"react";import{Box as pr,Text as Tc}from"ink";import Dt from"react";var Fg=e=>(I.getTag(e)?.name??"").length+3,Bg=e=>(I.getContributor(e)?.name??"").length+3,Ac=({width:e})=>{let{viewMode:t}=_(),n=z(),{breadCrumb:o,contextNode:r,selectedIndex:s,renderedChildrenIndex:i}=n,c=i[r.id]?.[s],u=it(c?.id??r.id,"TICKET"),m=Z(u)?u.value:void 0,p=m?.props.tags??[],v=m?.props.assignees??[],S=m?.parentNodeId?!$r(r.id,m.parentNodeId)&&t==="dense":!1,N=o.map((k,Ne)=>{let ft=Ne===o.length-1,vt=H(k.id),yt=ft?vt?.[s]?.title:void 0;return`${Ne?" / ":""}${k.title??""}${yt?` \u25B8 ${yt}`:""}`}).join(""),E=m?I.getCommentsByIssue(m.id):[],R=E.length?String(E.length).length+11:0,M=S?p.reduce((k,Ne)=>k+Fg(Ne),0)+v.reduce((k,Ne)=>k+Bg(Ne),0)+R:0,D=Math.max(0,e-M),j=N.substring(0,D),O=S?[...p.map(k=>Dt.createElement(pr,{key:`tag-${k}`,paddingLeft:1},Dt.createElement(fn,{id:k}))),...v.map(k=>Dt.createElement(pr,{key:`assignee-${k}`,paddingLeft:1},Dt.createElement(Rt,{id:k}))),E.length?Dt.createElement(pr,{key:"comments",paddingLeft:1},Dt.createElement(Tc,{color:y.accent},"[",E.length," comment",E.length===1?"":"s","]")):null]:[];return Dt.createElement(pr,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},Dt.createElement(Tc,{color:y.secondary2},j),O)};import{Box as Ug,Text as wc}from"ink";import gr from"react";var Og=({filters:e})=>gr.createElement(Ug,{columnGap:1},gr.createElement(wc,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:o})=>gr.createElement(wc,{backgroundColor:"black",color:"white"},` ${n}${o}"${t}" `))),Mc=gr.memo(Og);import{Box as Wg,Text as fr}from"ink";import Jn from"react";function Pc(){let{eventLog:e,unappliedEvents:t}=z(),n=e.at(-1)?.id,o=Co(n??""),r=Z(o)?Fi(o.value):"INVALID DATE";return Jn.createElement(Wg,{paddingLeft:1},Jn.createElement(fr,{backgroundColor:y.accent,color:y.secondary}," Readonly "),Jn.createElement(fr,{color:y.accent}," "+t.length+" edits ago at "+r+"."),Jn.createElement(fr,{color:y.accent}," Resume with "),Jn.createElement(fr,{backgroundColor:y.accent,color:y.secondary}," ",":peek now"," "))}import Ds from"chalk";import{Box as $g,Text as Lc}from"ink";import Fs,{useEffect as _g,useState as jg}from"react";var Hg=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Vg=150,kc=12,Gg=.36,Dc=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)}},zg=({r:e,g:t,b:n})=>{let o=r=>Math.round(Math.max(0,Math.min(255,r))).toString(16).padStart(2,"0");return`#${o(e)}${o(t)}${o(n)}`},Kg=(e,t,n)=>{let o=Dc(e),r=Dc(t);return zg({r:o.r+(r.r-o.r)*n,g:o.g+(r.g-o.g)*n,b:o.b+(r.b-o.b)*n})},qg=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),o=Math.floor(n),r=n-o,s=e[o],i=e[Math.min(o+1,e.length-1)];return Kg(s,i,r)};function Fc({syncStatus:e,autoSync:t}){let[n,o]=jg(0);_g(()=>{if(e.status!=="syncing"){o(0);return}let c=0,u=setInterval(()=>{c+=1;let m=(Math.sin(c*Gg)+1)/2,p=Math.round(m*(kc-1));o(v=>v===p?v:p)},Vg);return()=>clearInterval(u)},[e.status]);let r={synced:" ",failed:"---",syncing:"...",pending:"idle"},i={synced:y.secondary2,failed:y.yellow,pending:y.secondary2,syncing:qg(Hg,n/(kc-1))??""}[e.status];return Fs.createElement($g,null,Fs.createElement(Lc,null,Ds.hex(y.secondary2).dim(t?"Sync (auto): ":"Sync: ")),Fs.createElement(Lc,null,Ds.hex(i)("\u25CF")+Ds.hex(y.secondary2).dim(` ${r[e.status].padEnd(4)} `)))}import $c from"chalk";import{Text as _c}from"ink";import jc,{useEffect as Qg,useState as Zg}from"react";var Ft="1.0.0";import Bs from"chalk";var Yg="https://registry.npmjs.org/epiq/latest",Us=null,Bc=0,Xg=1e3*60*60*24,Uc=e=>e.replace(/^v/,""),Jg=(e,t)=>{let n=Uc(e).split(".").map(Number),o=Uc(t).split(".").map(Number);for(let r=0;r<Math.max(n.length,o.length);r++){let s=n[r]??0,i=o[r]??0;if(s>i)return 1;if(s<i)return-1}return 0},Oc=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(Us&&Date.now()-Bc<Xg)return Us;try{let t=await fetch(Yg);if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.status}`);let o=(await t.json()).version??null,r={current:e,latest:o,updateAvailable:o?Jg(o,e)>0:!1};return Us=r,Bc=Date.now(),r}catch{return{current:e,latest:null,updateAvailable:!1}}},Wc=(e,t)=>{let n=e.split("."),o=t.split("."),r=o.findIndex((s,i)=>s!=n[i]);return o.map((s,i)=>i>=r?Bs.hex(y.accent).dim(s):Bs.hex(y.secondary).dim(s)).join(Bs.hex(y.secondary2).dim("."))};function Hc(){let[e,t]=Zg({current:Ft,latest:null,updateAvailable:!1});return Qg(()=>{let n=!0;return Oc(Ft).then(o=>{n&&t(o)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?jc.createElement(_c,{dimColor:!0,color:y.secondary2},Ft+" "):jc.createElement(_c,null,$c.hex(y.secondary2).dim(Ft),$c.hex(y.accent).dim(" \u2197 "),Wc(Ft,e.latest))}function Zn({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:o,mode:r}=z(),{userName:s,preferredEditor:i,autoSync:c}=_(),u=64,m=process.stdout.columns-u-8;return ye.createElement(vr,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?ye.createElement(Qn,null," "):r===f.PALETTE?ye.createElement(vr,null,ye.createElement(Qn,{color:y.accent},"Command Palette"),ye.createElement(Qn,{dimColor:!0,color:y.secondary2}," ","- search, select and press enter")):ye.createElement(vr,{paddingLeft:1},e.length>0?ye.createElement(Mc,{filters:e}):ye.createElement(Ac,{width:m})),n==="live"?ye.createElement(vr,{columnGap:1,paddingRight:2,"max-width":u,overflow:"hidden",justifyContent:"flex-end"},ye.createElement(Fc,{autoSync:!!c,syncStatus:o}),ye.createElement(Qn,null,yr.hex(y.secondary2).dim("Mode: ")+yr.hex(y.secondary2).dim(r.padEnd(8," "))," "),ye.createElement(Vc,{icon:"@",value:s}),ye.createElement(Vc,{icon:"\u276F",value:i}),ye.createElement(Hc,null)):"",n==="peek"?ye.createElement(Pc,null):"")}function Vc({icon:e,value:t}){return ye.createElement(Qn,null,yr.dim(e)+yr.hex(y.accent)(` ${t??"-"} `))}import{Box as ef,Text as tf}from"ink";import eo from"react";import{Box as hr,Text as Os}from"ink";import Bt from"react";function Ws(){let e=z(),t=e.nodes[e.rootNodeId],r=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?$(t?.id):[];return Bt.createElement(hr,{flexDirection:"column",height:r,padding:1,borderStyle:"round",borderColor:y.secondary,width:s},Bt.createElement(hr,{padding:1,paddingTop:0,paddingBottom:0},Bt.createElement(Os,null,"Select a board:")),Bt.createElement(hr,{padding:1,flexDirection:"column"},i.map((c,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,v=$(c.id).flatMap(({id:S})=>H(S)).length;return Bt.createElement(hr,{key:c.id??u},Bt.createElement(Os,{color:m?y.accent:y.secondary2},Bt.createElement(xe,{isSelected:m})),Bt.createElement(Os,{color:m?y.accent:y.secondary2},c.title," (",v," issues)",c.readonly?" \u{1F512}":""))})))}var nf=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:o,viewMode:r,height:s,width:i})=>{let{renderedChildrenIndex:c}=z(),u=n.find(({context:S})=>S==="BOARD"),v=s-1-3;return eo.createElement(ef,{flexDirection:"row"},e.context==="WORKSPACE"?eo.createElement(Ws,null):u?eo.createElement(Ko,{height:v,width:i,swimlanes:(c[u.id]??[]).filter(S=>S!==void 0&&Ct(S)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:r,mode:o}):eo.createElement(tf,null))},Gc=eo.memo(nf);import{useEffect as of}from"react";var rf=e=>{of(()=>{if(!e)return;let t,n=!1,o=()=>{if(n)return;let{autoSyncIntervalMs:r,userName:s,preferredEditor:i}=_();i&&s&&r&&(t=setTimeout(()=>{if(n)return;let{readOnly:c,mode:u}=g();u==="default"&&!c&&Po(),o()},r))};return o(),()=>{n=!0,t&&clearTimeout(t)}},[e])},zc=({autoSync:e})=>(rf(e),null);function $s({width:e,height:t}){let n=z(),{autoSync:o,viewMode:r}=Ai(),s=n.filters;if(n.mode===f.HELP)return Q.createElement(Ut,{flexDirection:"column"},Q.createElement(Ec,{width:e,height:t}));if(n.mode===f.PALETTE)return Q.createElement(Ut,{flexDirection:"column"},Q.createElement(Zn,{filters:s}),Q.createElement(fc,{width:e,height:t-2}),Q.createElement(Xn,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Nt(),c=!i,u=i&&!n.hasProjectDefinition;if(c)return Q.createElement(Ut,{flexDirection:"column"},Q.createElement(Ut,{flexDirection:"column"},Q.createElement(Zn,{hideBreadCrumb:!0,filters:s}),Q.createElement(ks,{height:t,width:e})),Q.createElement(Xn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(u)return Q.createElement(Ut,{flexDirection:"column"},Q.createElement(Ut,{flexDirection:"column"},Q.createElement(Zn,{hideBreadCrumb:!0,filters:s}),Q.createElement(Rc,{height:t,width:e})),Q.createElement(Xn,{width:e,mode:n.mode,availableHints:n.availableHints}));let m=Ee(n.breadCrumb??[],"BOARD");if(Z(m)){let p=m.value.id,v=$(p).length,S=3,N=Math.floor(e/S),E=Math.floor(e/Math.max(v,1));e=Math.min(E,N)*Math.max(v,S)}return Q.createElement(Ut,{flexDirection:"column"},Q.createElement(zc,{autoSync:o}),Q.createElement(Ut,{flexDirection:"column"},Q.createElement(Zn,{filters:s}),Q.createElement(Gc,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:r??"dense",mode:n.mode})),Q.createElement(Xn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import sf from"readline";var xr,Ir,ot,af=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.InitCommandPalette,x.ExitCommandLine,x.CaptureInput,x.EraseInput,x.EraseInputWord,x.HideHelp,x.ViewHelp,x.SetViewDense,x.SetViewWide,x.GetLastCommandFromHistory,x.GetNextCommandFromHistory,x.AutoCompleteCommand]),Kc=async e=>{if(e.ctrl&&e.name==="c")return A.exit();let{actionIndex:t,mode:n,readOnly:o}=g(),r=Ba(e,n);if(!r||o&&!af.has(r))return;let s=t[n]?.[r];if(s?.action)try{await s.action(s,e)}catch(i){logger.error(i)}},df=()=>async function(t,n){n.name!=="escape"&&(ot&&(clearTimeout(ot),ot=void 0),await Kc(n))},cf=()=>async function(t){if(t.length===1&&t[0]===27){ot&&clearTimeout(ot),ot=setTimeout(()=>{Kc({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),ot=void 0},25);return}ot&&(clearTimeout(ot),ot=void 0)};function qc(){xr&&process.stdin.removeListener("keypress",xr),Ir&&process.stdin.removeListener("data",Ir),xr=df(),Ir=cf(),sf.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Ir),process.stdin.on("keypress",xr)}async function Yc(){try{let e=jn();Z(e)&&Fe(e.value);let t=He(process.cwd()),n=[];if(Z(t)){let s=We({repoRoot:t.value});if(d(s))return qt(3,s.message);let i=nn(),c=await $t({repoRoot:t.value,stateBranchRoot:s.value,stateBranchName:i.stateBranch});if(d(c))return qt(3,c.message);let u=await B({cwd:s.value,args:["pull","--ff-only"]});d(u)&&logger.info(3,u.message);let m=at(s.value);if(d(m))return qt(3,m.message);n=m.value}let o=Kt(n);if(d(o))return qt(4,o.message);C({hasProjectDefinition:Z(t),hasInitializingEvents:!!n.length});let r=_s();return d(r)?qt(6,r.message):(qc(),l("Booted Epiq",void 0))}catch(e){return qt(0,Ao(e))}}ld();var pf=`${Ot.bold("Epiq CLI")}
|
|
56
|
+
`,Os.writeFileSync(t,n,"utf8"),re.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)};var lf=async e=>{let t=await U({cwd:e,args:["status","--porcelain"]});return d(t)?t:l("Checked git diff",t.value.stdout.trim().length>0)},Y=(e,t)=>a(`[${e}] ${t}`),jd=async()=>{_("");let e=an(),t=await Ye(process.cwd());if(d(t))return Y(1,t.message);let n=t.value,r=await vr(n);if(d(r))return Y(2,r.message);if(r.value)return Y(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await lf(n);if(d(o))return Y(2.5,o.message);if(o.value)return Y(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(jo(n))return Y(4,"Epiq project already initialized");let s=Tt();if(!s.isSetupDone||!s.userName)return Y(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let i=H(),c=i.userName,u=i.userId;if(!u||!c)return Y(5,"Missing Epiq user id");let m=e.stateBranch,p=await hr({repoRoot:n,branch:m});if(d(p))return Y(6,p.message);if(p.value)return Y(6,`State branch already exists: ${m}`);let v=await es({repoRoot:n,stateBranchName:m});if(d(v))return Y(6,v.message);let I=br();if(d(I))return Y(7,I.message);let E=Hd.join(Ir(),e.projectId),N=await Vt({repoRoot:n,stateBranchRoot:E,stateBranchName:m});if(d(N))return Y(8,N.message);let T=Hd.join(E,".epiq");cf.mkdirSync(T,{recursive:!0});let k=Aa({userId:u,userName:c});if(d(k))return Y(9,k.message);for(let Wo of k.value){let ci=Dr({event:Wo,rootDir:E});if(d(ci))return Y(9,ci.message)}let O=await Cr({stateBranchRoot:E,eventFileName:qt({userId:u,userName:c})});if(d(O))return Y(10,O.message);let V=await cn({cwd:E,message:"[epiq:init]"});if(d(V))return Y(10,V.message);let R=await Wd(n);if(d(R))return Y(11,R.message);let A=fi({repoRoot:n,fileContents:e});if(d(A))return Y(12,A.message);let G=await oe.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d(G))return Y(13,G.message);let Re=await oe.commit({cwd:n,message:"[epiq:init-project]"});if(d(Re))return Y(13,Re.message);let Ae="Project initialized!",Ge=await U({cwd:n,args:["push","-u","origin","HEAD"]});d(Ge)&&(Ae+=` Warn: [init:14] ${Ge.message}`);let de=await Dn({repoRoot:n,stateBranchRoot:E});d(de)&&(Ae+=` Warn: [init:15] ${de.message}`);let ct=At(k.value).filter(d);if(ct.length>0)return Y(16,ct.map(Wo=>Wo.message).join(`
|
|
57
|
+
`));let ze=We();if(d(ze))return Y(16,ze.message);let{rootNodeId:Ll,nodes:kl}=ze.value,di=kl[Ll];return di?(M.navigate({contextNode:di,selectedIndex:0}),C({hasProjectDefinition:!0,mode:g.DEFAULT}),l(Ae,null)):Y(16,"Unable to resolve initialized root node")};import{ulid as mf}from"ulid";import{ulid as uf}from"ulid";var Vd=null,Ft=()=>structuredClone(Vd),Qn=e=>{Vd=e},Gd=()=>{let{contextNode:e,selectedIndex:t}=f(),r=z(e.id)[t];return r?l("Resolved selected child",r):a("Target node not found")},_s=({id:e,parentId:t,position:n={at:"end"}})=>{let r=z(t).filter(o=>o.id!==e);return Fr(r,n)},zd=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Z();if(d(r))return a("Unable to resolve user ID");let o=_s({parentId:t,id:e,position:n});return d(o)?o:l("Created pending move state",{id:uf(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Kd=e=>{Qn(e);let t=Rt(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function $s(e){let t=Gd();if(d(t))return t;let{contextNode:n,nodes:r}=f();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=z(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let c=s[i+e];if(!c)return a("Missing sibling node");let u=zd({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:Kd(u.value)}function Ws(e){let t=Gd();if(d(t))return t;let{contextNode:n,selectedIndex:r}=f(),s=z(n.id)[r+e];if(!s)return a("Missing sibling node");let i=zd({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:Kd(i.value)}var qd=()=>{let e=Ft();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=f().nodes[n];if(!r)return a("Move parent not found");let o=z(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(M.navigate({contextNode:r,selectedIndex:o}),l("Synchronized navigation to moved node",null))},co=(e,t="Moved preview")=>{if(d(e))return e;let n=qd();return d(n)?n:(C({mode:g.MOVE}),l(t,null))},Yd=async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=q().commandMeta,{contextNode:n,selectedIndex:r}=f(),o=z(n.id)[r];if(!o)return C({mode:g.DEFAULT}),a("No move target");if(t==="start"){if(o.readonly)return a("Target node is read-only");if(r===-1)return a("No item selected");if(!o.parentNodeId)return a("Target has no parent");let s=z(o.parentNodeId),i=s.findIndex(({id:v})=>v===o.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],u=s[i+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=_s({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(Qn({id:mf(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),C({mode:g.MOVE}),l("Move initialized",null))}if(t==="next")return co(Ws(1));if(t==="previous")return co(Ws(-1));if(t==="to-next")return co($s(1));if(t==="to-previous")return co($s(-1));if(t==="confirm"){let s=Ft();if(!s)return a("No pending move to confirm");let i=await qe();if(d(i))return i;let c=B([s],i.value);if(d(c))return c;let u=qd();return d(u)?u:(Qn(null),C({mode:g.DEFAULT}),l("Moved item",null))}return t==="cancel"?(Qn(null),C({mode:g.DEFAULT}),l("Cancelling move",null)):a("Invalid move modifier")};import{ulid as uo}from"ulid";import{monotonicFactory as pf,ulid as ff}from"ulid";var gf=pf(),lo=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=gf();return l("Created issue events",[{id:ff(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var Xd=async(e,t)=>{let n=Z();if(d(n))return a("Unable to resolve user ID");let r=await qe();if(d(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=f(),u=m=>{let p=B([m],o);if(d(p))return p;let v=b.getNode(p.value[0].result.id);if(!v)return a("Created node not found");if(!v.parentNodeId)return p;let I=b.getNode(v.parentNodeId);return I?(M.navigate({contextNode:I,selectedIndex:b.getSiblings(v.parentNodeId).findIndex(({id:E})=>E===v.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=f(),p=b.getNode(m);if(!p)return a("Workspace not found");let v=vn(p.id,n.value,o);return d(v)?v:u({id:uo(),action:"add.board",payload:{id:uo(),name:t.inputString,parent:p.id,rank:v.value},...n.value})}if(t.modifier==="swimlane"){let m=be(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=vn(m.value.id,n.value,o);return d(p)?p:u({id:uo(),action:"add.swimlane",payload:{id:uo(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=W(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let V=be(s,"SWIMLANE");return d(V)?null:V.value})();if(!p)return a("Unable to add issue in this context");let v=vn(p.id,n.value,o);if(d(v))return v;let I=lo({name:t.inputString,parent:p.id,rank:v.value,user:n.value});if(d(I))return I;let E=I.value,N=B([...E],o);if(d(N))return N;if(!N.value[0])return a("Issue creation failed");let O=E.find(V=>V.action==="add.issue")?.payload.id;return O?(M.navigate({contextNode:p,selectedIndex:b.getSiblings(p.id).findIndex(({id:V})=>V===O)}),l("Issue created",null)):a("Unable to determine ticket id")}return l("Success",null)};var mo=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=f(),s=la(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=Bt();if(d(u))return u;let p=At(i).filter(d);if(p.length>0)return Bt(),C(o),a(p.map(I=>I.message).join(", "));let v=f().nodes[e];return v?(M.navigate({contextNode:v,selectedIndex:r}),l("",{unappliedEvents:c})):(Bt(),C(o),a("Board did not exist at that date"))};var vf=20,yf=16,hf=150,po=null,fo=null;var rn=()=>{po!==null&&(clearInterval(po),po=null),fo!==null&&(clearTimeout(fo),fo=null)},Jd=()=>{rn(),C({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},xf=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)},Qd=({events:e,startTime:t,durationMs:n})=>{rn();let r=e.length,o=e.map(v=>gn(v)??t),s=o[r-1]??Date.now(),i=xf(o),c=Math.max(1,Math.round(n*vf/1e3)),u=Math.max(Math.round(n/c),yf),m=0,p=0;C({mode:g.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),po=setInterval(()=>{m++;let v=m/c,I=[],E;for(;p<r&&i[p]<=v;){let T=e[p],k=Rt(T);if(d(k)){Jd();return}I.push(...cs(T)),E=T,p++}if(p>=r||m>=c){for(;p<r;p++){let k=Rt(e[p]);if(d(k))break}let T=f().replay;C({unappliedEvents:[],replay:T&&{...T,progress:1,appliedCount:r}}),rn(),fo=setTimeout(Jd,hf);return}let N=f().replay;C({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,v),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:E?gn(E)??N?.currentTime??t:N?.currentTime??t,currentLabel:E?sa(E):N?.currentLabel??"",flashNodeIds:E?[...new Set(I)]:N?.flashNodeIds??[]}})},u)};var Zd=async()=>{let e=be(f().breadCrumb,"BOARD");if(d(e))return e;let t=await Ye(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Te({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=q().commandMeta;if(rn(),r==="now"){let c=pt(n.value);if(d(c))return a(c.message);let u=Bt();if(d(u))return u;let p=At(c.value).filter(d);return p.length>0?a(p.map(v=>v.message).join(", ")):(C({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),l("Peeking now",!0))}let s;if(r==="prev"){let c=f().eventLog.at(-1),u=gn(c);if(u===null)return a("No previous event to peek");s=u}else if(r==="next"){let c=f().unappliedEvents.at(0),u=gn(c);if(u===null)return a("No next event to peek");s=u+1}else{let c=Qt(r||o.trim());if(!c)return a("Invalid peek date");s=c.getTime()}let i=mo({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(C({mode:g.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),l("Peeking",!0))};var ec=async()=>{let e=be(f().breadCrumb,"BOARD");if(d(e))return e;let t=await Ye(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Te({repoRoot:t.value});if(d(n))return n;let{modifier:r,inputString:o}=q().commandMeta,{dateInput:s,durationInput:i}=Vr(r,o);if(rn(),f().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let c=Qt(s);if(!c)return a("Invalid replay date");let u=i?jr(i):15e3;if(u===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=f(),v=mo({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(d(v))return v;let{unappliedEvents:I}=v.value;return I.length===0?(Bt(),C(p),l("Nothing to replay from that point",!0)):(Qd({events:I,startTime:m,durationMs:u}),l("Replaying board history",!0))};import bf from"zod";var tc=()=>{let e=q().commandMeta.inputString,t=bf.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return a("Auto sync duration must be a number of at least 3000 ms");let n=ht({autoSyncDebounceMs:t.data});return d(n)?n:(_e({autoSyncIntervalMs:t.data}),C({mode:g.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))};var nc=()=>{let e=q().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Da(e),n=ht({autoSync:t});return d(n)?n:(_e({autoSync:t}),C({mode:g.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var rc=()=>{let e=q().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=ht({logLevel:e});return d(n)?n:(_e({logLevel:e}),C({mode:g.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var oc=async()=>{_(""),C({mode:g.DEFAULT});let e=We();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");C({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Or();return d(t)?(C({syncStatus:{msg:t.message,status:"failed"}}),t):(C({mode:g.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var Cf=e=>e.action==="add.issue.comment",sc=e=>Object.values(f().tags).find(t=>t.name===e),ic=e=>Object.values(f().contributors).find(t=>t.name===e),xt=async()=>{let e=await qe();return d(e)?e:l("Resolved persist root",e.value)},go=[{systemOnly:!0,intent:L.Move,description:"Internal move-state command",mode:g.COMMAND_LINE,action:Yd},{intent:L.Delete,description:"Delete the currently selected node",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await xt();if(d(o))return o;if(r.context==="COMMENT"){let s=r.id,i=w(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=f().nodes[i];if(!c||!w(c))return a("Unable to resolve comment issue");let u=c.log?.filter(Cf).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):B([{id:xe(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):a("Unable to resolve comment")}return B([{id:xe(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=q().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>le(x.FILTER).map(c=>c.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return fe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:g.DEFAULT})),l("Filter updated",null)}},{intent:L.ViewHelp,description:"Open the help screen",mode:g.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=f();return Dt({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),C({mode:g.HELP}),l("Viewing help",null)}},{intent:L.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!w(r))return a("Cannot close in this context");let o=f().nodes[ce];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await xt();if(d(s))return s;let i=s.value,c=Yt(o.id,r.id,{at:"end"},e.value,i);if(d(c))return c;let u=B([{id:xe(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value}],i);return d(u)?u:l("Issue closed",null)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):mt(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let s=o.value,i=f().nodes[ce];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!w(s))return a("Target node is not issue");let c=io(s);if(!c)return a("Unable to resolve previous parent from issue history");if(c===i.id)return a("Previous parent resolves to closed swimlane");let u=f().nodes[c];if(!u)return a("Previous parent no longer exists");let m=await xt();if(d(m))return m;let p=m.value,v=Yt(u.id,s.id,{at:"end"},e.value,p);if(d(v))return v;let I=B([{id:xe(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:v.value},...e.value}],p);return d(I)?I:l("Issue reopened",null)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Init,description:"Initialize Epiq in the current git repository",mode:g.COMMAND_LINE,action:jd},{intent:L.NewItem,description:"Create a new board, swimlane, or issue",mode:g.COMMAND_LINE,action:Xd,onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Rename,description:"itle] Rename the currently selected node",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=W(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=ad();if(!o)return a("Provide a title");let s=await xt();return d(s)?s:B([{id:xe(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.UntagTicket,description:"Remove a tag from the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=sc(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=f();if(!s)return a("Invalid untag target");let i=mt(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let c=i.value;if(!w(c))return a("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let m=await xt();return d(m)?m:B([{id:xe(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.TagTicket,description:"Add or create a tag on the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=f();if(!o)return a("Invalid tag target");let s=mt(o.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!w(i))return a("Target node is not issue");let c=await xt();if(d(c))return c;let u=sc(r),m=u?.id??xe();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):B([...u?[]:[{id:xe(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:xe(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.AssignUserToTicket,description:"Assign a user to the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let{selectedIndex:o,contextNode:s}=f(),i=W(s.id)[o];if(!i)return a("Invalid assign target");let c=mt(i.id,"TICKET");if(d(c))return a("Unable to assign issue in this context");let u=c.value;if(!w(u))return a("Target node is not issue");let m=await xt();if(d(m))return m;let p=ic(r),v=p?.id??xe();return(u.props.assignees??[]).includes(v)?a("Assignee already assigned"):B([...p?[]:[{id:xe(),action:"create.contributor",payload:{id:v,name:r},...e.value}],{id:xe(),action:"add.issue.assignee",payload:{id:u.id,assignee:v},...e.value}],m.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:g.COMMAND_LINE,action:async()=>{let e=Z();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let o=ic(r);if(!o)return a(`Assignee "${r}" does not exist`);let{selectedNode:s}=f();if(!s)return a("Invalid unassign target");let i=mt(s.id,"TICKET");if(d(i))return a("Unable to unassign in this context");let c=i.value;if(!w(c))return a("Target node is not issue");if(!(c.props.assignees??[]).includes(o.id))return a(`Issue is not assigned to "${r}"`);let m=await xt();return d(m)?m:B([{id:xe(),action:"remove.issue.assignee",payload:{id:c.id,assignee:o.id},...e.value}],m.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Comment,description:"Add a comment to the selected issue",mode:g.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return a("Provide a comment");if(n.length>xn)return a(`Cannot exceed ${xn} characters`);let r=Z();if(d(r))return a("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=f(),i=be([...o,s],"TICKET");if(d(i))return a("Edit target must be an issue");let c=i.value;if(!c)return a("Invalid comment target");let u=c.context==="TICKET"?l("Resolved ticket",c):mt(c.id,"TICKET");if(d(u))return a("Unable to comment on issue in this context");let m=u.value;if(!w(m))return a("Target node is not issue");let p=await xt();return d(p)?p:B([{id:xe(),action:"add.issue.comment",payload:{id:xe(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Sync,description:"Pull, commit, and push Epiq state",mode:g.COMMAND_LINE,action:oc},{intent:L.Peek,description:"View board state at another point in time",mode:g.COMMAND_LINE,action:Zd},{intent:L.Replay,description:"Replay board history forward from a point in time",mode:g.COMMAND_LINE,action:ec},{intent:L.Export,description:"Export the current board layout to markdown",mode:g.COMMAND_LINE,action:async()=>{let e=await Td();return d(e)?e:(C({mode:g.DEFAULT}),l("Export successful",!0))}},{intent:L.Exit,description:"Exit the application",mode:g.COMMAND_LINE,action:async()=>(M.exit(),l("Exit successful",!0))},{intent:L.Edit,description:"Edit title or description",mode:g.COMMAND_LINE,action:async(e,t)=>$d(t),onSuccess:()=>C({mode:g.DEFAULT})},{intent:L.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:g.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case ae.USERNAME:{let{userId:r,preferredEditor:o,userName:s}=H(),i=n||s,c=r??xe();if(!i||!c)return a("Unable to resolve user name or id");let u=ht({userName:i,userId:c,preferredEditor:o??""});return d(u)?u:(_e({userName:i,userId:c}),C({mode:g.DEFAULT}),l(`Username set to "${i}"`,null))}case ae.EDITOR:{if(!n)return a("No editor provided");let r=ht({preferredEditor:n});return d(r)?r:(_e({preferredEditor:n}),C({mode:g.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case ae.VIEW:return n!=="wide"&&n!=="dense"?a("Invalid view mode"):(_e({viewMode:n}),l(`View set to "${n}"`,null));case ae.AUTOSYNC:return nc();case ae.LOG_LEVEL:return rc();case ae.SYNC_DEBOUNCE_MS:return tc();default:return a("Unknown config command")}}},{intent:L.Coffee,description:"Sponsor the development of Epiq!",mode:g.COMMAND_LINE,action:()=>{let e=q().commandMeta.modifier;return e==="custom"?Bs("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):Bs(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),_(""),l("Thanks you!",null)}}];var Sf=new Set(["peek","replay","filter","view-help"]),ot=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=q();if(!t)return a("No command to confirm");if(!e&&n===wt.Invalid)return a("Invalid command");let s=Xr(t);nd();let{readOnly:i}=f();if(i&&!Sf.has(s))return Gn({status:bt.Fail,message:"Command not available in readonly state",value:null});let c=go.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return Gn({status:bt.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return Gn({status:bt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?Gn(u):(rd({addToHistory:!e}),c.onSuccess?.(),H().autoSync&&$r(),u)};var vo=[{intent:h.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(C({mode:g.COMMAND_LINE}),_("move cancel"),ot({isForceExecutedBySystem:!0}))},{intent:h.InitMove,mode:g.DEFAULT,description:"[m] move (init/confirm)",action:()=>(C({mode:g.COMMAND_LINE}),_("move start"),ot({isForceExecutedBySystem:!0}))},{intent:h.ConfirmMove,mode:g.MOVE,action:()=>(C({mode:g.COMMAND_LINE}),_("move confirm"),ot({isForceExecutedBySystem:!0}))}],yo=[{intent:h.MovePreviousItem,mode:g.MOVE,action:()=>Ft()?(C({mode:g.COMMAND_LINE}),_("move previous"),ot({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveNextItem,mode:g.MOVE,action:()=>Ft()?(C({mode:g.COMMAND_LINE}),_("move next"),ot({isForceExecutedBySystem:!0})):a("No pending move")}],ac=[{intent:h.MoveToNextContainer,mode:g.MOVE,action:()=>Ft()?(C({mode:g.COMMAND_LINE}),_("move to-next"),ot({isForceExecutedBySystem:!0})):a("No pending move")},{intent:h.MoveToPreviousContainer,mode:g.MOVE,action:()=>Ft()?(C({mode:g.COMMAND_LINE}),_("move to-previous"),ot({isForceExecutedBySystem:!0})):a("No pending move")}];var dc={[P.WORKSPACE]:[...vo,...yo],[P.BOARD]:[...vo,...yo],[P.SWIMLANE]:[...vo,...yo,...ac],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[],[P.COMMENT]:[]};var cc=()=>{_("");let{pendingNavTarget:e}=kt();C({mode:g.DEFAULT}),e&&M.navigate(e),Dt({pendingNavTarget:void 0})},lc=[{intent:h.ExitCommandLine,mode:g.HELP,action:()=>(cc(),l("Exiting help",null))},{intent:h.Exit,mode:g.HELP,action:()=>(cc(),l("Closed help",null))},{intent:h.NavPreviousItem,mode:g.HELP,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:h.NavNextItem,mode:g.HELP,action:()=>(M.navigateToNextItem(),l("Navigating to next help item",null))},{intent:h.NavToPreviousContainer,mode:g.HELP,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:h.NavToNextContainer,mode:g.HELP,action:()=>(M.navigateToNextContainer(),l("Navigating to next help container",null))}];var Ef=e=>{C({mode:g.COMMAND_LINE});let{pendingNavTarget:t}=kt();t&&M.navigate(t),Dt({pendingNavTarget:void 0}),_(`${e} `)},uc=()=>{_("");let{pendingNavTarget:e}=kt();e&&M.navigate(e),Dt({pendingNavTarget:void 0}),C({mode:g.DEFAULT})},mc=[{intent:h.InitCommandPalette,mode:g.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{_("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=f();return Dt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),C({mode:g.PALETTE}),l("Opening command palette",null)}},{intent:h.Confirm,mode:g.PALETTE,action:()=>{let{selectedNode:e}=f();if(!e||!St(e))return a("Command only applicable on text nodes");if(e.props.disabled)return a("Command is not available in this context");let t=e.title;return t?(Ef(t),l("Selected command",t)):l("No command selected",null)}},{intent:h.ExitCommandLine,mode:g.PALETTE,action:()=>(uc(),l("Exiting palette",null))},{intent:h.Exit,mode:g.PALETTE,action:()=>(uc(),l("Closed command palette",null))},{intent:h.NavPreviousItem,mode:g.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:g.PALETTE,action:()=>(M.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:g.PALETTE,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:g.PALETTE,action:()=>(M.navigateToNextContainer(),l("Navigating to next container",null))}];var pc=[...lc,...mc,{intent:h.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.NEW} `),l("Adding new item",null))},{intent:h.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.DELETE} `),l("Deleting item",null))},{intent:h.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(C({mode:g.COMMAND_LINE}),_(""),l("Entering command line mode",null))},{intent:h.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=f();if(!z(e?.id??"")?.length){if(e?.title===se.DESCRIPTION)return C({mode:g.COMMAND_LINE}),_(`${x.EDIT} description `),l("Propose command",!0);if(e?.title===se.ASSIGNEES)return C({mode:g.COMMAND_LINE}),_(`${x.ASSIGN} `),l("Propose command",!0);if(e?.title===se.TAGS)return C({mode:g.COMMAND_LINE}),_(`${x.TAG} `),l("Propose command",!0);if(t.title===se.DESCRIPTION&&e?.context==="TEXT")return C({mode:g.COMMAND_LINE}),_(`${x.EDIT} description `),l("Propose command",!0)}return M.enterChildNode(),l("Entering context",null)}},{intent:h.EditTitle,mode:g.DEFAULT,description:"[r] rename title",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.EDIT} title ${f().selectedNode?.title}`),l("Exiting context",null))},{intent:h.EditDescription,mode:g.DEFAULT,description:"[e] edit description",action:()=>(C({mode:g.COMMAND_LINE}),_(`${x.EDIT} description `),l("Exiting context",null))},{intent:h.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(M.enterParentNode(),l("Exiting context",null))},{intent:h.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:h.NavNextItem,mode:g.DEFAULT,action:()=>(M.navigateToNextItem(),l("Navigating to next item",null))},{intent:h.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:h.NavToNextContainer,mode:g.DEFAULT,action:()=>(M.navigateToNextContainer(),l("Navigating to next container",null))}];var Nf=500,Rf=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),fc=e=>{let t=Rf(e);t&&Yr(n=>(n+t).slice(0,Nf))};var Af=[g.COMMAND_LINE,g.PALETTE],Tf=e=>[{intent:h.MoveCursorLeft,mode:e,action:()=>(Ns(-1),l("Moving cursor left",null))},{intent:h.MoveCursorRight,mode:e,action:()=>(Ns(1),l("Moving cursor right",null))},{intent:h.MoveCursorLeftOfWord,mode:e,action:()=>(Rs("left"),l("Moving cursor left of word",null))},{intent:h.MoveCursorRightOfWord,mode:e,action:()=>(Rs("right"),l("Moving cursor right of word",null))},{intent:h.AutoCompleteCommand,mode:e,action:()=>(Yr((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=f().selectedNode?.title??""),r+o}),l("Auto-completing command",null))},{intent:h.CaptureInput,mode:e,action:(t,{sequence:n})=>(fc(n??""),l("Capturing input",null))},{intent:h.EraseInput,mode:e,action:()=>(ed(),l("Erasing input",null))},{intent:h.EraseInputWord,mode:e,action:()=>(td(),l("Erasing input word",null))}],gc=[{intent:h.Confirm,mode:g.COMMAND_LINE,action:()=>(ot(),l("Executing command",null))},{intent:h.ViewHelp,mode:g.DEFAULT,action:()=>(C({mode:g.HELP}),l("Viewing help",null))},...Af.flatMap(Tf),{intent:h.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(C({mode:g.DEFAULT}),l("Exiting command line",null))},{intent:h.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(od(),l("Getting last command from history",null))},{intent:h.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(sd(),l("Getting next command from history",null))}];import hc from"chalk";var ho=hc.dim.hex(y.secondary2)(": for command line"),vc="q to exit",yc=`${hc.hex(y.accent)("m")} to confirm`,Hs={[P.WORKSPACE]:[ho],[P.BOARD]:[ho],[P.BOARD+g.COMMAND_LINE]:[ho],[P.SWIMLANE]:[ho],[P.TICKET+g.HELP]:[vc],[P.SWIMLANE+g.HELP]:[vc],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+g.MOVE]:[yc],[P.TICKET+g.MOVE]:[yc]};var Zn=e=>e.trim().toLocaleLowerCase(),wf=e=>{let{tags:t}=f();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Mf=e=>{let{contributors:t}=f();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},xc=(e,t)=>{let n=Zn(t.value);if(!n)return!0;switch(t.target){case"title":return Zn(e.title??"").includes(n);case"description":return Zn(e.props.description??"").includes(n);case"tag":return wf(e).map(Zn).some(o=>o.includes(n));case"assignee":return Mf(e).map(Zn).some(o=>o.includes(n));default:return!0}};function Ic(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=r;for(;s&&(o.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let i=o[o.length-1];return!i||i.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var bc=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 on,js,Vs=new Set,Cc=()=>{for(let e of Vs)e()},Lf=e=>(Vs.add(e),()=>Vs.delete(e));function Sc(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return a("derive(): contextNodeId is missing");if(!r)return a("derive(): rootNode is missing");if(!o[r])return a("derive(): unable to find root node");let c=o[t];if(!c)return a("Unable to derive state, contextNode not found");let u=Ic(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,v=Hs[p+n]??Hs[p]??[],I=[...pc,...dc[p]??[],...gc],E=bc(I),N=kf(o,s),T=N[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:v,availableActions:I,actionIndex:E,selectedNode:T,renderedChildrenIndex:N})}var f=()=>{if(!on)throw new Error("State not initialized. Call initWorkspaceState() first.");return on},We=()=>on?l("Retrieved state",on):a("State not initialized. Call initWorkspaceState() first.");function _n(e){js=e;let t=Ke(process.cwd()),n=!1;if(!d(t)){let s=Ct(t.value);if(d(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:g.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{}},o=Sc(r);return d(o)?o:(on=o.value,Cc(),l("State initialized",null))}function fe(e){let t=f(),n=e(t),r=Sc(n);return d(r)?a(r.message??"Unable to update state"):(on=r.value,Cc(),l("State updated",null))}var C=e=>fe(t=>({...t,...e}));var $=()=>Pf(Lf,f,f),kf=(e,t)=>{let n={};for(let r of Object.values(e))w(r)&&t.length>0&&!t.every(o=>xc(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,s)=>{let i=e[o.id],c=e[s.id];return!i||!c?0:i.rank.localeCompare(c.rank)});return n},W=e=>f()?.renderedChildrenIndex[e]??[],Bt=()=>js?_n(js):a("Cannot reset state: no initial workspace found"),hn=()=>on!==void 0;var Gs=e=>{hn()&&(C({syncStatus:e}),Gt({type:"sync-status",payload:e}))},xo=(e="Syncing...")=>{Gs({status:"syncing",msg:e})},Io=(e="Synced")=>{Gs({status:"synced",msg:e})},zs=e=>{Gs({status:"failed",msg:e})},He=e=>(zs(e),a(e));import{decodeTime as NM}from"ulid";var Df=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=K("getRepoRootDir",await Ye(e));if(d(n))return a(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=K("getStateBranchRoot",Te({repoRoot:r}));if(d(o))return a(o.message);let s=o.value;logger.debug("[sync] state branch root",s);let i=K("ensureInitialCommit",await ki(r));if(d(i))return a(i.message);logger.debug("[sync] initial commit result",{created:i.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let c=K("bootstrapStateBranchStorage",await Fi({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(d(c))return a(c.message);logger.debug("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let u=K("hasInProgressGitOperation(stateBranchRoot)",await vr(s));if(d(u))return a(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value)return logger.info("[sync] state branch git operation in progress"),a("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:s});let m=K("ensureStateBranchLayout",Mi(r,s));return d(m)?a(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}),l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:c.value}))},Ff=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=K("stageStateBranchOwnEventFile",await Cr({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=K("hasStagedChanges(after stage)",await Ei(t));if(d(o))return a(o.message);if(logger.debug("[sync] state branch change check after stage result",{changed:o.value}),!o.value)return logger.info("[sync] no own event file changes to commit"),l("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let s=K("createStateBranchSyncCommit",await Di({repoRoot:e,stateBranchRoot:t}));return d(s)?a(s.message):(logger.debug("[sync] created sync commit",s.value),l("Committed own event file",{createdCommit:!0,commitSha:s.value}))},_r=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),a("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),a("Own event file must end with .jsonl");xo();let n=K("ensureSyncReady",await Df({cwd:e,ensureUpstream:!0}));if(d(n))return He(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=K("isDetachedHead(stateBranchRoot)",await Ni(o));if(d(i))return He(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return He("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,v=K("getStateBranch",dn(r));if(d(v))return He(v.message);let I=v.value;logger.debug("[sync] resolved state branch",{stateBranch:I,stateBranchRoot:o});let E=K("commitOwnEventFileToStateBranch",await Ff({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(E))return He(E.message);c=E.value.createdCommit,u=E.value.commitSha;let N=K("pullBranchRebaseIfPresent",await Jo({cwd:o,branch:I}));if(d(N))return He(N.message);if(m=N.value,c||s){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:o});let T=K("pushStateBranch",await Dn({stateBranchRoot:o,repoRoot:r}));if(d(T)&&Si(T.message)){let k=K("pullBranchRebaseIfPresent(retry)",await Jo({cwd:o,branch:I}));if(d(k))return He(k.message);m=m||k.value,T=K("pushStateBranch(retry)",await Dn({stateBranchRoot:o,repoRoot:r}))}if(d(T))return He(T.message);p=T.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let T=K("git rev-parse HEAD",await U({args:["rev-parse","HEAD"],cwd:o}));if(d(T))return He(T.message);u=T.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Io(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:s})};var Ks=e=>{let t=Ke(e??process.cwd());return d(t)?a(t.message):l("Resolved Epiq repo root",t.value)},ke=async e=>{let t=Ks(e);if(d(t))return t;let n=Te({repoRoot:t.value});if(d(n))return a(n.message);let r=an(),o=await Vt({repoRoot:t.value,stateBranchRoot:n.value,stateBranchName:r.stateBranch});if(d(o))return a(o.message);let s=await U({cwd:n.value,args:["pull","--ff-only"]});d(s)&&re.info(3,s.message);let i=pt(n.value);if(d(i))return a(i.message);let c=Xt(i.value);return d(c)?a(c.message):l("Booted Epiq state",{repoRoot:t.value,stateBranchRoot:n.value})},De=()=>{let e=Jn();return d(e)?a(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},je=()=>{let e=We();return d(e)?a(e.message):e},Ec=e=>(e.props.tags??[]).map(t=>b.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:ie(t.name)})),Nc=e=>(e.props.assignees??[]).map(t=>b.getContributor(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:ie(t.name)}));var Rc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=je();if(d(n))return n;let r=Object.values(n.value.nodes).filter(w).filter(o=>e.includeClosed||o.parentNodeId!==ce).map(o=>({id:o.id,title:Nt(o.title),description:o.props.description??"",parentNodeId:o.parentNodeId,isClosed:o.parentNodeId===ce,readonly:!!o.readonly,tags:Ec(o),assignees:Nc(o)}));return l("Listed issues",r)},Ac=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=vn(e.parentId,n.value,t.value.stateBranchRoot);if(d(r))return r;let o=lo({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(d(o))return o;let s=o.value,i=B([...s],t.value.stateBranchRoot);if(d(i))return a(i.message);let c=s.find(u=>u.action==="add.issue")?.payload.id;return c?l("Created issue",{id:c,title:e.title,parentId:e.parentId}):a("Unable to determine created issue id")},Tc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=Yt(ce,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(d(r))return r;let o={id:Ie(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ce,rank:r.value}},s=B([o],t.value.stateBranchRoot);return d(s)?a(s.message):l("Closed issue",{id:e.issueId})},wc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Target node is not issue");if(o.parentNodeId!==ce)return a("Issue is not closed");let s=io(o);if(!s)return a("Unable to resolve previous parent from issue history");if(s===ce)return a("Previous parent resolves to closed swimlane");let i=r.value.nodes[s];if(!i)return a("Previous parent no longer exists");let c=Yt(i.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(c))return c;let u={id:Ie(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:i.id,rank:c.value}},m=B([u],t.value.stateBranchRoot);return d(m)?a(m.message):l("Reopened issue",{id:o.id,parentId:i.id})},Mc=async e=>{let t=Ks(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=Te({repoRoot:t.value});if(d(r))return r;let o=pt(r.value);if(d(o))return o;let s=Xt(o.value);if(d(s))return s;let i=Yt(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(d(i))return i;let c={id:Ie(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:i.value}},u=B([c],r.value);return d(u)?a(u.message):l("Moved issue",{id:e.issueId,parentId:e.parentId})},bo=async(e={})=>{xo();let t=Ks(e.repoRoot);if(d(t))return a("Sync failed");let n=De();if(d(n))return n;let r=await _r({cwd:t.value,ownEventFileName:qt(n.value)});return d(r)?(zs(r.message),r):(Io(),l("Synced",r.value))};var Ut=async(e={})=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=je();if(d(n))return n;let r=Object.values(n.value.nodes),o=r.filter(m=>Er(m)&&!m.isDeleted),s=new Map,i=new Map;for(let m of r)if(!m.isDeleted){if(Et(m)&&m.parentNodeId){let p=s.get(m.parentNodeId)??[];p.push(m),s.set(m.parentNodeId,p)}if(w(m)&&m.parentNodeId){let p=i.get(m.parentNodeId)??[];p.push(m),i.set(m.parentNodeId,p)}}let c=Jn();if(d(c))return c;let u={};for(let m of r.filter(w))m.isDeleted||(u[m.id]=b.getCommentsByIssue(m.id).map(p=>{let v=b.getContributor(p.authorId);return{id:p.id,issueId:p.issue,body:p.md,author:{id:p.authorId,name:v?.name??"Unknown",color:ie(v?.name??p.authorId)},createdAt:Bf(p.id)}}));return l("Retrieved Epiq GUI state",{boards:o.sort((m,p)=>m.rank.localeCompare(p.rank)).map(m=>({id:m.id,title:m.title,swimlanes:(s.get(m.id)??[]).sort((p,v)=>p.rank.localeCompare(v.rank)).map(p=>({id:p.id,title:p.title,readonly:!!p.readonly,issues:(i.get(p.id)??[]).sort((v,I)=>v.rank.localeCompare(I.rank)).map(v=>({id:v.id,title:Nt(v.title),description:v.props.description??"",readonly:!!v.readonly,tags:Ec(v),assignees:Nc(v),parentNodeId:v.parentNodeId,isClosed:v.parentNodeId===ce})),parentNodeId:p.parentNodeId}))})),tags:Object.values(n.value.tags).map(m=>({...m,color:ie(m.name)})),contributors:Object.values(n.value.contributors).map(m=>({...m,color:ie(m.name)})),user:{name:c.value.userName??"",id:c.value.userId??"",color:ie(c.value.userName??"")},commentsByIssueId:u})},Pc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=o.props.description??"";if(s===e.description)return l("No changes made",{id:e.issueId,description:s});let i={id:Ie(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},c=B([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue description",{id:e.issueId,description:e.description})},Lc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Edit target must be an issue");if(o.readonly)return a("Cannot edit readonly issue");let s=Nt(e.title);if(!s.trim())return a("Issue title cannot be empty");if(o.title===s)return l("No changes made",{id:e.issueId,title:s});let i={id:Ie(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},c=B([i],t.value.stateBranchRoot);return d(c)?a(c.message):l("Edited issue title",{id:e.issueId,title:s})},kc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Tag target must be an issue");if(o.readonly)return a("Cannot tag readonly issue");let s=Nt(e.tagName).trim();if(!s)return a("Tag name cannot be empty");let i=Object.values(r.value.tags).find(p=>p.name===s),c=i?.id??Ie(),u=[...i?[]:[{id:Ie(),...n.value,action:"create.tag",payload:{id:c,name:s}}],{id:Ie(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:c}}],m=B(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue tag",{id:e.issueId,tag:{id:c,name:s}})},Dc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Untag target must be an issue");if(o.readonly)return a("Cannot untag readonly issue");if(!r.value.tags[e.tagId])return a("Tag not found");let s={id:Ie(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue tag",{id:e.issueId,tagId:e.tagId})},Fc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Assign target must be an issue");if(o.readonly)return a("Cannot assign readonly issue");let s=Nt(e.assigneeName).trim();if(!s)return a("Assignee name cannot be empty");let i=Object.values(r.value.contributors).find(p=>p.name===s),c=i?.id??Ie(),u=[...i?[]:[{id:Ie(),...n.value,action:"create.contributor",payload:{id:c,name:s}}],{id:Ie(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:c}}],m=B(u,t.value.stateBranchRoot);return d(m)?a(m.message):l("Added issue assignee",{id:e.issueId,assignee:{id:c,name:s}})},Bc=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Unassign target must be an issue");if(o.readonly)return a("Cannot unassign readonly issue");if(!r.value.contributors[e.assigneeId])return a("Assignee not found");let s={id:Ie(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=B([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},Co=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.nodes[e.issueId];if(!o)return a("Issue not found");if(!w(o))return a("Comment target must be an issue");if(o.readonly)return a("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return a("Comment cannot be empty");let i=Ie(),c={id:Ie(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Added issue comment",{id:i,issueId:e.issueId,body:s})},So=async e=>{let t=await ke(e.repoRoot);if(d(t))return t;let n=De();if(d(n))return n;let r=je();if(d(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return a("Unable to resolve comment");if(o.payload.author!==n.value.userId)return a("You can only delete your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return a("Issue not found");if(!w(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot delete comment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return l("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:Ie(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=B([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})};var Uc=e=>{let t,n,r=!1,o=!1,s=!1,i=()=>{let p=Xn();if(d(p))return re.error(p.message);let{autoSync:v,userName:I,preferredEditor:E}=p.value;return!!(v&&I&&E)},c=async()=>{if(!r){if(o){s=!0;return}o=!0;try{await bo({repoRoot:e.repoRoot}),Gt({type:"state",payload:await Ut({repoRoot:e.repoRoot})})}finally{o=!1,s&&(s=!1,c())}}},u=(p=750)=>{r||(n&&clearTimeout(n),n=setTimeout(()=>{c()},p))},m=()=>{if(r)return;let p=Xn();if(d(p))return re.error(p.message);let{autoSyncDebounceMs:v}=p.value;i()&&(t=setTimeout(()=>{c(),m()},v??15e3))};return m(),{scheduleSync:u,dispose:()=>{r=!0,t&&clearTimeout(t),n&&clearTimeout(n)}}};import{WebSocketServer as Uf}from"ws";var Fe=(e,t)=>{e.send(JSON.stringify(t))},er=async(e,t)=>Fe(e,{type:"state",payload:await Ut({repoRoot:t})}),st=async(e,t,n,r,o)=>{if(Fe(e,{type:r,payload:o}),d(o))return Fe(e,{type:"failed",payload:o.message});n(),er(e,t)},Oc=(e,t,{onStateChanged:n})=>{new Uf({server:e,path:"/ws"}).on("connection",o=>{Bi(o),o.on("message",async s=>{try{let i=JSON.parse(s.toString()),{type:c}=i;if(c==="state:get")return er(o,t);if(c==="sync"){let u=await bo({repoRoot:t});return Fe(o,{type:"sync:result",payload:u}),n(),er(o,t)}if(c==="issue:comment:add"){let u=await Co({repoRoot:t,...i.payload});return st(o,t,n,"issue:comment:add:result",u)}if(c==="issue:comment:delete"){let u=await So({repoRoot:t,...i.payload});return Fe(o,{type:"issue:comment:delete:result",payload:u}),d(u)?Fe(o,{type:"failed",payload:u.message}):(n(),er(o,t))}if(c==="issue:edit:description"){let u=await Pc({repoRoot:t,...i.payload});return st(o,t,n,"issue:edit:description:result",u)}if(c==="issue:edit:title"){let u=await Lc({repoRoot:t,...i.payload});return st(o,t,n,"issue:edit:title:result",u)}if(c==="issue:tag:add"){let u=await kc({repoRoot:t,...i.payload});return st(o,t,n,"issue:tag:add:result",u)}if(c==="issue:tag:remove"){let u=await Dc({repoRoot:t,...i.payload});return st(o,t,n,"issue:tag:remove:result",u)}if(c==="issue:assignee:add"){let u=await Fc({repoRoot:t,...i.payload});return st(o,t,n,"issue:assignee:add:result",u)}if(c==="issue:assignee:remove"){let u=await Bc({repoRoot:t,...i.payload});return st(o,t,n,"issue:assignee:remove:result",u)}if(c==="issues:list")return Fe(o,{type:"issues",payload:await Rc({repoRoot:t})});if(c==="issues:create"){let u=await Ac({...i.payload,repoRoot:t});return Fe(o,{type:"issues:create:result",payload:u}),d(u)?Gt({type:"failed",payload:u.message}):(Gt({type:"issue:created",payload:u.value}),n(),er(o,t))}if(c==="issues:move"){if(!i.payload.position)return Fe(o,{type:"error",message:"Missing move position"});let u=await Mc({...i.payload,repoRoot:t});return st(o,t,n,"issues:move:result",u)}if(c==="issue:close"){if(!i.payload.issueId)return Fe(o,{type:"error",message:"Missing issueId"});let u=await Tc({repoRoot:t,issueId:i.payload.issueId});return st(o,t,n,"issue:close:result",u)}if(c==="issue:reopen"){if(!i.payload.issueId)return Fe(o,{type:"error",message:"Missing issueId"});let u=await wc({repoRoot:t,issueId:i.payload.issueId});return st(o,t,n,"issue:reopen:result",u)}return Fe(o,{type:"error",message:"Unknown message type"})}catch(i){return Fe(o,{type:"error",message:i instanceof Error?i.message:String(i)})}})})};var Wf=sn.dirname($f(import.meta.url)),Hf=process.env.IS_LOCAL==="true"?sn.resolve(process.cwd(),"dist/gui"):sn.join(Wf,"gui"),it=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},jf=async e=>new Promise((t,n)=>{let r="";e.on("data",o=>{r+=o}),e.on("end",()=>{try{t(r?JSON.parse(r):{})}catch{n(new Error("Invalid JSON body"))}}),e.on("error",n)}),Vf=e=>e.endsWith(".html")?"text/html; charset=utf-8":e.endsWith(".js")?"text/javascript; charset=utf-8":e.endsWith(".css")?"text/css; charset=utf-8":e.endsWith(".json")?"application/json; charset=utf-8":e.endsWith(".ico")?"image/x-icon":"application/octet-stream",_c=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=sn.resolve(Hf),o=sn.resolve(r,n),s=sn.relative(r,o);if(s.startsWith("..")||sn.isAbsolute(s))return it(t,403,{isError:!0,message:"Forbidden"});try{let i=await Of(o);return t.writeHead(200,{"content-type":Vf(o)}),t.end(i)}catch{return it(t,404,{isError:!0,message:`Not found: ${n}`})}},Gf=async(e,t=3710)=>new Promise((n,r)=>{let o=s=>{let i=u=>{if(e.off("listening",c),u.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(u)},c=()=>{e.off("error",i);let u=e.address();if(!u||typeof u=="string"){r(new Error("Unable to resolve address"));return}n(u.port)};e.once("error",i),e.once("listening",c),e.listen(s,"127.0.0.1")};o(t)}),$c=async e=>{let t=_f.createServer(async(o,s)=>{let i=new URL(o.url??"/","http://127.0.0.1");if(i.pathname==="/api/state")return it(s,200,await Ut({repoRoot:e.repoRoot}));if(o.method==="POST"&&i.pathname==="/api/comments")try{let c=await jf(o);if(!c.issueId||!c.body?.trim())return it(s,400,{isError:!0,message:"Missing issueId or body"});let u=await Co({repoRoot:e.repoRoot,issueId:c.issueId,body:c.body});return"isError"in u&&u.isError?it(s,400,u):it(s,200,await Ut({repoRoot:e.repoRoot}))}catch(c){return it(s,400,{isError:!0,message:c instanceof Error?c.message:"Unable to add comment"})}if(o.method==="DELETE"&&i.pathname.startsWith("/api/comments/")){let c=decodeURIComponent(i.pathname.replace("/api/comments/",""));if(!c)return it(s,400,{isError:!0,message:"Missing comment id"});let u=await So({repoRoot:e.repoRoot,commentId:c});return"isError"in u&&u.isError?it(s,400,u):it(s,200,await Ut({repoRoot:e.repoRoot}))}return i.pathname.startsWith("/board/")?_c("/",s):_c(i.pathname,s)});try{await Gf(t)}catch(o){return a(o instanceof Error?`Unable to start GUI server: ${o.message}`:`Unable to start GUI server: ${String(o)}`)}let n=Uc({repoRoot:e.repoRoot});Oc(t,e.repoRoot,{onStateChanged:()=>n.scheduleSync()}),t.on("close",n.dispose);let r=t.address();return!r||typeof r=="string"?(t.close(),a("Unable to resolve GUI server address")):l("Started GUI server",{url:`http://epiq.localhost:${r.port}${e.boardId?`/board/${e.boardId}`:""}`,server:t})};var Wc=async e=>{let t=await $c({...e,boardId:""});if(d(t))return t;let{url:n}=t.value;return console.log(`Epiq GUI running at ${zf.cyan(n)}`),li(n),l("Started GUI",{url:n})};import{Box as Ht}from"ink";import ee from"react";import{Box as qs,Text as tr}from"ink";import Ve,{useEffect as Kf,useMemo as qf}from"react";import{ulid as Yf}from"ulid";var Hc=({text:e,match:t,color:n,highlightColor:r=y.secondary,dimColor:o=!1})=>{if(!t)return Ve.createElement(tr,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),c=s.indexOf(i);return c===-1?Ve.createElement(tr,{color:n,dimColor:o},e):Ve.createElement(tr,{color:n,dimColor:o},e.slice(0,c),Ve.createElement(tr,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},jc=Yf(),Xf=e=>`${e}`,Jf=e=>{let{pendingNavTarget:t}=kt();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(le(x.NONE,{breadCrumb:n,contextNode:r,readOnly:f().readOnly,selectedNode:o}));return[...new Set(Object.values(x))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==x.PALETTE).map(i=>{let c=Xr(i),u=go.find(m=>m.intent===c);return{command:i,description:u?.description??`[${i}] Run command`,isAvailable:s.has(i)}}).filter(i=>i.command.toLowerCase().startsWith(e)||e.length>=2&&i.description.toLowerCase().includes(e)).sort((i,c)=>i.isAvailable!==c.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(c.command))},Qf=e=>Q.text({id:jc,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),Zf=(e,t,n)=>Q.text({id:Xf(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Ys=[],eg=e=>{Vc();let t=b.createNode(Qf(f().rootNodeId));d(t)||!St(t.value)||(Ys=[t.value,...e.map((n,r)=>Zf(n,r,jc)).map(b.createNode).filter(te).map(({value:n})=>n).filter(St)],M.navigate({contextNode:t.value,selectedIndex:0}))},Vc=()=>{let e=Ys.map(t=>t.id);Ys=[];for(let t of e)b.deleteNode(t)};function Gc({width:e,height:t}){let r=id().value.trim().toLowerCase(),o=qf(()=>Jf(r),[r]);Kf(()=>(eg(o),()=>{Vc()}),[o]);let s=f().selectedIndex;return Ve.createElement(qs,{flexDirection:"column",width:e,height:t-2},Ve.createElement(nt,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,c)=>{let u=c===s,m=i.isAvailable?y.accent:y.secondary2,p=i.isAvailable?"":"[unavailable] ";return Ve.createElement(qs,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Ve.createElement(tr,{color:m,dimColor:!i.isAvailable},u?"\u276F ":" ",Ve.createElement(Hc,{text:Hi(i.command),match:r,color:m,dimColor:!i.isAvailable})),Ve.createElement(qs,{paddingLeft:2},Ve.createElement(Hc,{text:p+i.description,match:r.length>=2?r:"",color:u&&i.isAvailable?y.primary:y.secondary2,dimColor:!i.isAvailable})))})))}import{Box as yg}from"ink";import Ro from"react";import rr from"chalk";import{Box as Xs,Text as zc}from"ink";import nr,{useEffect as tg,useMemo as ng,useState as rg}from"react";var Kc=rr.hex(y.secondary),og=rr.inverse,sg=rr.inverse.hex(y.secondary2),ig={hint:"",hints:[],overlap:0,remainder:""},Yc=({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}},ag=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=ie(t);return{bg:r=>rr.bgHex(n).black(r),bgCursor:r=>rr.bgHex(n).inverse.black(r)}}return as(t)},dg=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=Yc({value:e,command:t});if(!r)return null;let s=e.slice(r.end).match(/^\s*/)?.[0].length??0,i=r.end+s;return e.slice(i,i+n.length)!==n?null:{start:i,end:i+n.length}},qc=()=>({value:he.value,cursorPosition:he.cursorPosition,commandIsPending:he.commandIsPending,autoCompletion:he.commandMeta.autoCompletion??ig,infoMessage:he.commandMeta.infoMessage,validationStatus:he.commandMeta.validity,command:he.commandMeta.command,inputString:he.commandMeta.inputString,modifier:he.commandMeta.modifier}),cg=(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,Xc=({width:e,mode:t})=>{let[n,r]=rg(qc());tg(()=>{let I=()=>{let N=qc();r(T=>cg(T,N)?T:N)},E=Es(I);return I(),()=>{E()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:c,autoCompletion:u,command:m,modifier:p}=n,v=ng(()=>{let I=Math.max(0,Math.min(s,o.length)),E=Yc({value:o,command:m}),N=dg({value:o,command:m,modifier:p}),T=m?as(m):null,k=ag({command:m,modifier:p}),O=(de,X)=>{let ct=E&&X>=E.start&&X<E.end,ze=N&&X>=N.start&&X<N.end;return ct&&T?T.fg(de):ze&&k?k.bg(de):de},V=(de,X)=>{let ct=E&&X>=E.start&&X<E.end,ze=N&&X>=N.start&&X<N.end;return ct&&T?T.fgCursor(de):ze&&k?k.bgCursor(de):og(de)},R=o.slice(0,I),A=o[I]??" ",G=I<o.length?o.slice(I+1):"",Re=Array.from(R).map((de,X)=>O(de,X)).join(""),Ae=V(A,I),Ge=Array.from(G).map((de,X)=>O(de,I+1+X)).join("");if(u.hint){let de=u.hint[u.overlap]??A;Ae=sg(de),Ge=Kc(u.remainder.slice(1)+G)}return Kc(t===g.PALETTE?"?":":")+Re+Ae+Ge},[o,s,u,m,p]);return nr.createElement(Xs,{flexDirection:"column",justifyContent:"flex-start"},nr.createElement(Xs,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},nr.createElement(Xs,null,nr.createElement(zc,null,v),i&&nr.createElement(zc,{wrap:"truncate",color:c?y.red:y.secondary2},` ${i} `))))};import{Box as lg,Text as ug}from"ink";import Jc from"react";var mg=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?" | ":"").length+o.length;if(r+i>t-4)break;n.push(o),r+=i}return n},Qc=({width:e,availableHints:t})=>{let n=mg(t,e).join(" | ");return Jc.createElement(lg,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1},Jc.createElement(ug,{color:y.secondary2},n.length?n:"\xA0"))};import{Box as pg,Text as Eo}from"ink";import or,{useEffect as fg,useRef as En,useState as gg}from"react";var vg=40,No=.3,Js="\u2500",Zc=1,el=16,tl=({width:e})=>{let{replay:t}=$(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*Zc,[c,u]=gg(0),m=En(r);m.current=r;let p=En(0),v=En(0),I=En(0),E=En(0),N=En(0);if(fg(()=>{if(!n){p.current=0,I.current=0,E.current=0,N.current=0,u(0);return}p.current=m.current,v.current=Date.now(),I.current=m.current;let R=setInterval(()=>{let A=Date.now(),G=m.current;if(G!==I.current){let X=G-I.current,ct=A-v.current;if(X<0)E.current=0,N.current=0;else if(X>0&&ct>0){let ze=X/ct;E.current=E.current===0?ze:E.current*(1-No)+ze*No,N.current=N.current===0?X:N.current*(1-No)+X*No}p.current=G,v.current=A,I.current=G}let Re=A-v.current,Ae=Math.min(N.current,E.current*Re),Ge=Math.min(1,p.current+Ae),de=Math.round(Ge*i);u(X=>X===de?X:de)},vg);return()=>clearInterval(R)},[n,i]),!t)return null;let T=R=>{let A=s>1?R/(s-1):0,G=Math.round(A*(el-1))/(el-1);return Rr(G)},k=Math.min(s,Math.floor(c/Zc)),O=[];for(let R=0;R<k;R++){let A=T(R),G=O[O.length-1];G&&G.color===A?G.text+=Js:O.push({text:Js,color:A})}let V=Js.repeat(Math.max(0,s-k));return or.createElement(pg,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1,columnGap:1},or.createElement(Eo,{color:y.secondary2},"\u25B6"),or.createElement(Eo,null,O.map((R,A)=>or.createElement(Eo,{key:A,color:R.color},R.text)),or.createElement(Eo,{color:y.secondary,dimColor:!0},V)))};var sr=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=$(),o=t===g.COMMAND_LINE||t===g.PALETTE;return Ro.createElement(yg,null,o?Ro.createElement(Xc,{width:e,mode:t}):r==="replay"?Ro.createElement(tl,{width:e}):Ro.createElement(Qc,{width:e,mode:t,availableHints:n}))};import{Box as Ot,Text as Nn}from"ink";import Se,{useEffect as hg,useMemo as xg}from"react";import{ulid as nl}from"ulid";var To=nl(),Ig=()=>[...new Set([...f().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(e=>{let[t,n]=e.split("]"),r=t?.replace("[",""),o=n?.trim();return[r,o]}).filter(e=>e[0]!==void 0&&e[1]!==void 0).sort(([e],[t])=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(([e,t])=>({keys:e,action:t})),bg=e=>Q.text({id:To,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),Cg=(e,t,n)=>Q.text({id:nl(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),Ao=[],rl=()=>{let e=Ao.filter(n=>n.id!==To).map(n=>n.id),t=Ao.filter(n=>n.id===To).map(n=>n.id);Ao=[];for(let n of[...e,...t])b.deleteNode(n)},Sg=e=>{rl();let t=b.createNode(bg(f().rootNodeId));if(d(t)||!St(t.value))return logger.error("Could not attach help nodes");Ao=[t.value,...e.map((n,r)=>Cg(n,r,To)).map(b.createNode).filter(te).map(({value:n})=>n).filter(St)],M.navigate({contextNode:t.value,selectedIndex:0})},ol=({width:e,height:t})=>{let n=xg(()=>Ig(),[]);hg(()=>(Sg(n),()=>{rl()}),[n]);let r=f().selectedIndex;return Se.createElement(Ot,{flexDirection:"column",marginTop:3,borderColor:y.secondary,borderStyle:"round",width:e,height:t-2},Se.createElement(Ot,{paddingX:1,justifyContent:"center"},Se.createElement(Nn,{color:y.accent},"Help"),Se.createElement(Nn,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),Se.createElement(Ot,{paddingX:1,marginTop:1},Se.createElement(Ot,{width:20,justifyContent:"flex-end"},Se.createElement(Nn,{color:y.secondary},"Key(s)")),Se.createElement(Ot,{flexGrow:1,width:40,paddingLeft:2},Se.createElement(Nn,{color:y.secondary},"Action"))),Se.createElement(nt,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let c=i===r;return Se.createElement(Ot,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},Se.createElement(Ot,{width:20,justifyContent:"flex-end"},Se.createElement(Nn,{color:y.accent},o)),Se.createElement(Ot,{flexGrow:1,width:40,paddingLeft:2},Se.createElement(Nn,{color:c?y.primary:y.secondary2},s)))})))};import Eg from"chalk";import{Box as wo,Text as It}from"ink";import Be from"react";var sl=({width:e,height:t})=>Be.createElement(wo,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},Be.createElement(It,{color:y.accent,bold:!0},"Initialize project"),Be.createElement(It,null,`This folder is not an ${Eg.hex(y.accent)("epiq")} project yet.`),Be.createElement(It,{color:y.primary},"To start tracking issues here, we need to initialize a new",Be.createElement(It,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json "),"file in this repository."),Be.createElement(wo,{marginTop:1,flexDirection:"column"},Be.createElement(wo,null,Be.createElement(It,{color:y.accent}," "),Be.createElement(It,{color:y.primary},"Type "),Be.createElement(It,{backgroundColor:y.secondary}," :init "))),Be.createElement(wo,{marginTop:1},Be.createElement(It,{color:y.secondary2},"This will create, commit and push "),Be.createElement(It,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json ")));import{Box as Mo,Text as at}from"ink";import pe from"react";var Ng=({isDone:e,command:t,value:n})=>pe.createElement(Mo,null,pe.createElement(at,{color:y.accent,dimColor:e},e?" \u2714 ":" "),pe.createElement(at,{dimColor:e},"Type "),pe.createElement(at,{backgroundColor:y.secondary,dimColor:e}," "+t+" "),n!==void 0&&pe.createElement(pe.Fragment,null,pe.createElement(at,{dimColor:e}," "),pe.createElement(at,{color:y.secondary,dimColor:e},"<"+n+">"))),Rg=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function Qs({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:c}=Tt(),u=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:s,message:"Nice. Now pick your editor."},{key:"autosync",done:c,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=u.findIndex(v=>!v.done),p=m===-1?void 0:u[m];return pe.createElement(Mo,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},pe.createElement(at,{color:y.accent,bold:!0},"Welcome! \u{1F539}"),pe.createElement(at,null,"Let's get you started - it's a breeze."),pe.createElement(at,{color:y.secondary2},"Remember - you can always search available commands by typing:",pe.createElement(at,{color:y.accent}," ? ")),p&&pe.createElement(at,{color:y.secondary2},p.message),pe.createElement(Mo,{flexDirection:"column"},u.map((v,I)=>m===-1||I<=m?pe.createElement(Mo,{key:v.key,marginBottom:1},pe.createElement(Ng,{isDone:v.done,command:v.command,value:v.done?Rg(v.value):void 0})):null)))}import Fo from"chalk";import{Box as ar,Text as Rn}from"ink";import me from"react";import{Box as Po,Text as il}from"ink";import _t from"react";var Ag=e=>(b.getTag(e)?.name??"").length+3,Tg=e=>(b.getContributor(e)?.name??"").length+3,al=({width:e})=>{let{viewMode:t}=H(),n=$(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,c=i[o.id]?.[s],u=mt(c?.id??o.id,"TICKET"),m=te(u)?u.value:void 0,p=m?.props.tags??[],v=m?.props.assignees??[],I=m?.parentNodeId?!os(o.id,m.parentNodeId)&&t==="dense":!1,E=r.map((A,G)=>{let Re=G===r.length-1,Ae=z(A.id),Ge=Re?Ae?.[s]?.title:void 0;return`${G?" / ":""}${A.title??""}${Ge?` \u25B8 ${Ge}`:""}`}).join(""),N=m?b.getCommentsByIssue(m.id):[],T=N.length?String(N.length).length+11:0,k=I?p.reduce((A,G)=>A+Ag(G),0)+v.reduce((A,G)=>A+Tg(G),0)+T:0,O=Math.max(0,e-k),V=E.substring(0,O),R=I?[...p.map(A=>_t.createElement(Po,{key:`tag-${A}`,paddingLeft:1},_t.createElement(bn,{id:A}))),...v.map(A=>_t.createElement(Po,{key:`assignee-${A}`,paddingLeft:1},_t.createElement(Mt,{id:A}))),N.length?_t.createElement(Po,{key:"comments",paddingLeft:1},_t.createElement(il,{color:y.accent},"[",N.length," comment",N.length===1?"":"s","]")):null]:[];return _t.createElement(Po,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},_t.createElement(il,{color:y.secondary2},V),R)};import{Box as wg,Text as dl}from"ink";import Lo from"react";var Mg=({filters:e})=>Lo.createElement(wg,{columnGap:1},Lo.createElement(dl,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Lo.createElement(dl,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),cl=Lo.memo(Mg);import{Box as Pg,Text as ko}from"ink";import ir from"react";function ll(){let{eventLog:e,unappliedEvents:t}=$(),n=e.at(-1)?.id,r=Pr(n??""),o=te(r)?Mr(r.value):"INVALID DATE";return ir.createElement(Pg,{paddingLeft:1},ir.createElement(ko,{backgroundColor:y.accent,color:y.secondary}," Readonly "),ir.createElement(ko,{color:y.accent}," "+t.length+" edits ago at "+o+"."),ir.createElement(ko,{color:y.accent}," Resume with "),ir.createElement(ko,{backgroundColor:y.accent,color:y.secondary}," ",":peek now"," "))}import{Box as Lg,Text as Zs}from"ink";import Do from"react";function ul(){let{replay:e}=$();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return Do.createElement(Lg,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},Do.createElement(Zs,{backgroundColor:y.accent,color:y.secondary}," \u25B6 REPLAY "),Do.createElement(Zs,{color:y.secondary2},Mr(new Date(r))),Do.createElement(Zs,{color:y.accent},`${t}/${n} edits`))}import ei from"chalk";import{Box as kg,Text as ml}from"ink";import ti,{useEffect as Dg,useState as Fg}from"react";var Bg=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Ug=150,pl=12,Og=.36,fl=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)}},_g=({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)}`},$g=(e,t,n)=>{let r=fl(e),o=fl(t);return _g({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Wg=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,s=e[r],i=e[Math.min(r+1,e.length-1)];return $g(s,i,o)};function gl({syncStatus:e,autoSync:t}){let[n,r]=Fg(0);Dg(()=>{if(e.status!=="syncing"){r(0);return}let c=0,u=setInterval(()=>{c+=1;let m=(Math.sin(c*Og)+1)/2,p=Math.round(m*(pl-1));r(v=>v===p?v:p)},Ug);return()=>clearInterval(u)},[e.status]);let o={synced:" ",failed:"---",syncing:"...",pending:"idle"},i={synced:y.secondary2,failed:y.yellow,pending:y.secondary2,syncing:Wg(Bg,n/(pl-1))??""}[e.status];return ti.createElement(kg,null,ti.createElement(ml,null,ei.hex(y.secondary2).dim(t?"Sync (auto): ":"Sync: ")),ti.createElement(ml,null,ei.hex(i)("\u25CF")+ei.hex(y.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import Il from"chalk";import{Text as bl}from"ink";import Cl,{useEffect as Gg,useState as zg}from"react";var $t="1.1.0";import ni from"chalk";var Hg="https://registry.npmjs.org/epiq/latest",ri=null,vl=0,jg=1e3*60*60*24,yl=e=>e.replace(/^v/,""),Vg=(e,t)=>{let n=yl(e).split(".").map(Number),r=yl(t).split(".").map(Number);for(let o=0;o<Math.max(n.length,r.length);o++){let s=n[o]??0,i=r[o]??0;if(s>i)return 1;if(s<i)return-1}return 0},hl=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(ri&&Date.now()-vl<jg)return ri;try{let t=await fetch(Hg);if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.status}`);let r=(await t.json()).version??null,o={current:e,latest:r,updateAvailable:r?Vg(r,e)>0:!1};return ri=o,vl=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},xl=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?ni.hex(y.accent).dim(s):ni.hex(y.secondary).dim(s)).join(ni.hex(y.secondary2).dim("."))};function Sl(){let[e,t]=zg({current:$t,latest:null,updateAvailable:!1});return Gg(()=>{let n=!0;return hl($t).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?Cl.createElement(bl,{dimColor:!0,color:y.secondary2},$t+" "):Cl.createElement(bl,null,Il.hex(y.secondary2).dim($t),Il.hex(y.accent).dim(" \u2197 "),xl($t,e.latest))}function dr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=$(),{userName:i,preferredEditor:c,autoSync:u}=H(),m=64,p=process.stdout.columns-m-8,v=t||n==="replay",I=s?un(s.currentLabel,Math.max(0,p)):"";return me.createElement(ar,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?me.createElement(ar,{paddingLeft:1},me.createElement(Rn,{color:y.secondary2},I)):v?me.createElement(Rn,null," "):o===g.PALETTE?me.createElement(ar,null,me.createElement(Rn,{color:y.accent},"Command Palette"),me.createElement(Rn,{dimColor:!0,color:y.secondary2}," ","- search, select and press enter")):me.createElement(ar,{paddingLeft:1},e.length>0?me.createElement(cl,{filters:e}):me.createElement(al,{width:p})),n==="live"?me.createElement(ar,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},me.createElement(gl,{autoSync:!!u,syncStatus:r}),me.createElement(Rn,null,Fo.hex(y.secondary2).dim("Mode: ")+Fo.hex(y.secondary2).dim(o.padEnd(8," "))," "),me.createElement(El,{icon:"@",value:i}),me.createElement(El,{icon:"\u276F",value:c}),me.createElement(Sl,null)):"",n==="peek"?me.createElement(ll,null):"",n==="replay"?me.createElement(ul,null):"")}function El({icon:e,value:t}){return me.createElement(Rn,null,Fo.dim(e)+Fo.hex(y.accent)(` ${t??"-"} `))}import{Box as Kg,Text as qg}from"ink";import cr from"react";import{Box as Bo,Text as oi}from"ink";import Wt from"react";function si(){let e=$(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?W(t?.id):[];return Wt.createElement(Bo,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:y.secondary,width:s},Wt.createElement(Bo,{padding:1,paddingTop:0,paddingBottom:0},Wt.createElement(oi,null,"Select a board:")),Wt.createElement(Bo,{padding:1,flexDirection:"column"},i.map((c,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,v=W(c.id).flatMap(({id:I})=>z(I)).length;return Wt.createElement(Bo,{key:c.id??u},Wt.createElement(oi,{color:m?y.accent:y.secondary2},Wt.createElement(Ce,{isSelected:m})),Wt.createElement(oi,{color:m?y.accent:y.secondary2},c.title," (",v," issues)",c.readonly?" \u{1F512}":""))})))}var Yg=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:c}=$(),u=n.find(({context:I})=>I==="BOARD"),v=s-1-3;return cr.createElement(Kg,{flexDirection:"row"},e.context==="WORKSPACE"?cr.createElement(si,null):u?cr.createElement(oo,{height:v,width:i,swimlanes:(c[u.id]??[]).filter(I=>I!==void 0&&Et(I)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):cr.createElement(qg,null))},Nl=cr.memo(Yg);import{useEffect as Xg}from"react";var Jg=e=>{Xg(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=H();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:c,mode:u}=f();u==="default"&&!c&&$r(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},Rl=({autoSync:e})=>(Jg(e),null);function ii({width:e,height:t}){let n=$(),{autoSync:r,viewMode:o}=qi(),s=n.filters;if(n.mode===g.HELP)return ee.createElement(Ht,{flexDirection:"column"},ee.createElement(ol,{width:e,height:t}));if(n.mode===g.PALETTE)return ee.createElement(Ht,{flexDirection:"column"},ee.createElement(dr,{filters:s}),ee.createElement(Gc,{width:e,height:t-2}),ee.createElement(sr,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Tt(),c=!i,u=i&&!n.hasProjectDefinition;if(c)return ee.createElement(Ht,{flexDirection:"column"},ee.createElement(Ht,{flexDirection:"column"},ee.createElement(dr,{hideBreadCrumb:!0,filters:s}),ee.createElement(Qs,{height:t,width:e})),ee.createElement(sr,{width:e,mode:n.mode,availableHints:n.availableHints}));if(u)return ee.createElement(Ht,{flexDirection:"column"},ee.createElement(Ht,{flexDirection:"column"},ee.createElement(dr,{hideBreadCrumb:!0,filters:s}),ee.createElement(sl,{height:t,width:e})),ee.createElement(sr,{width:e,mode:n.mode,availableHints:n.availableHints}));let m=be(n.breadCrumb??[],"BOARD");if(te(m)){let p=m.value.id,v=W(p).length,I=3,E=Math.floor(e/I),N=Math.floor(e/Math.max(v,1));e=Math.min(N,E)*Math.max(v,I)}return ee.createElement(Ht,{flexDirection:"column"},ee.createElement(Rl,{autoSync:r}),ee.createElement(Ht,{flexDirection:"column"},ee.createElement(dr,{filters:s}),ee.createElement(Nl,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),ee.createElement(sr,{width:e,mode:n.mode,availableHints:n.availableHints}))}import Qg from"readline";var Uo,Oo,dt,Zg=new Set([h.MoveCursorLeft,h.EraseInputWord,h.MoveCursorLeftOfWord,h.MoveCursorRight,h.MoveCursorRightOfWord,h.NavToPreviousContainer,h.NavToNextContainer,h.NavPreviousItem,h.NavNextItem,h.SetViewDense,h.SetViewWide,h.Confirm,h.Exit,h.InitCommandLine,h.InitCommandPalette,h.ExitCommandLine,h.CaptureInput,h.EraseInput,h.EraseInputWord,h.HideHelp,h.ViewHelp,h.SetViewDense,h.SetViewWide,h.GetLastCommandFromHistory,h.GetNextCommandFromHistory,h.AutoCompleteCommand]),ev=new Set([h.NavPreviousItem,h.NavNextItem,h.NavToPreviousContainer,h.NavToNextContainer,h.Confirm,h.Exit,h.InitCommandPalette,h.InitMove,h.MoveNextItem,h.MovePreviousItem,h.MoveToNextContainer,h.MoveToPreviousContainer,h.Delete,h.AddItem,h.EditTitle,h.EditDescription,h.ConfirmMove,h.Edit,h.ViewHelp]),Al=async e=>{if(e.ctrl&&e.name==="c")return M.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=f(),s=dd(e,n);if(!s||r&&!Zg.has(s)||o==="replay"&&n===g.DEFAULT&&ev.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(c){logger.error(c)}},tv=()=>async function(t,n){n.name!=="escape"&&(dt&&(clearTimeout(dt),dt=void 0),await Al(n))},nv=()=>async function(t){if(t.length===1&&t[0]===27){dt&&clearTimeout(dt),dt=setTimeout(()=>{Al({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),dt=void 0},25);return}dt&&(clearTimeout(dt),dt=void 0)};function Tl(){Uo&&process.stdin.removeListener("keypress",Uo),Oo&&process.stdin.removeListener("data",Oo),Uo=tv(),Oo=nv(),Qg.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Oo),process.stdin.on("keypress",Uo)}async function wl(){try{let e=Jn();te(e)&&_e(e.value);let t=Ke(process.cwd()),n=[];if(te(t)){let s=Te({repoRoot:t.value});if(d(s))return Jt(3,s.message);let i=an(),c=await Vt({repoRoot:t.value,stateBranchRoot:s.value,stateBranchName:i.stateBranch});if(d(c))return Jt(3,c.message);let u=await U({cwd:s.value,args:["pull","--ff-only"]});d(u)&&logger.info(3,u.message);let m=pt(s.value);if(d(m))return Jt(3,m.message);n=m.value}let r=Xt(n);if(d(r))return Jt(4,r.message);C({hasProjectDefinition:te(t),hasInitializingEvents:!!n.length});let o=ai();return d(o)?Jt(6,o.message):(Tl(),l("Booted Epiq",void 0))}catch(e){return Jt(0,Ur(e))}}Ud();var iv=`${jt.bold("Epiq CLI")}
|
|
58
58
|
|
|
59
|
-
${
|
|
60
|
-
${
|
|
59
|
+
${jt.dim("Boot in directory:")}
|
|
60
|
+
${jt.cyan("$ epiq")}
|
|
61
61
|
|
|
62
|
-
${
|
|
63
|
-
${
|
|
64
|
-
`,
|
|
65
|
-
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await
|
|
66
|
-
${e.message}`)),process.exitCode=1)}export{
|
|
62
|
+
${jt.dim("Launch GUI:")}
|
|
63
|
+
${jt.cyan("$ epiq gui")}
|
|
64
|
+
`,av=ov(iv,{importMeta:import.meta,version:$t,flags:{init:{type:"boolean",default:!1}}}),_o=av.input[0];_o&&_o!=="gui"&&(console.error(jt.red(`Unknown command: ${_o}`)),process.exit(1));var Ml=process.stdout.columns||120,Pl=process.stdout.rows||20,$o=null,dv=e=>{try{return $o?($o.rerender(e),l("Rerendered app",void 0)):($o=rv(e),l("Rendered app",void 0))}catch(t){return a(`Unable to render app: ${Ur(t)}`)}},ai=()=>dv(sv.createElement(ii,{width:Ml,height:Pl}));process.stdout.on("resize",()=>{if(Ml=process.stdout.columns||120,Pl=process.stdout.rows||20,!$o)return;let e=ai();d(e)&&logger.info(`[boot:resize] ${e.message}`)});if(_o==="gui"){let e=await Wc({repoRoot:process.cwd()});d(e)&&(console.error(jt.red(`Failed to start Epiq GUI:
|
|
65
|
+
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await wl();d(e)&&(logger.info(e.message),console.error(jt.red(`Failed to boot Epiq:
|
|
66
|
+
${e.message}`)),process.exitCode=1)}export{ai as renderApp};
|