epiq 0.6.1 → 0.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +53 -53
- package/dist/mcp.js +47 -47
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,68 +1,68 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`,"utf8"),
|
|
4
|
-
`);if(n[n.length-1]===""&&n.pop(),n.length<=
|
|
2
|
+
import Mr from"chalk";import{render as Zm}from"ink";import ep from"meow";import tp from"react";import Te from"node:fs";import bt from"node:path";var A={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function Lr(e){return e.context===A.WORKSPACE}function W(e){return e.context===A.TICKET}function Gt(e){return e.context===A.TEXT}function Xe(e){return e.context===A.FIELD}function qt(e){return e.context===A.FIELD_LIST}var At=e=>e.context===A.SWIMLANE,Jo=e=>e.context===A.BOARD;var Je={None:"none",Success:"success",Fail:"fail"},a=e=>({status:Je.Fail,message:e,value:null}),l=(e,t)=>({status:Je.Success,message:e,value:t}),d=e=>e.status==="fail",ne=e=>e.status==="success";import{ulid as Ud}from"ulid";var Tt=24n,Od=Tt*4n,$e=(1n<<Od)-1n,Bd=/^[0-9a-f]+$/;function Qo(e){return!e||!Bd.test(e)?a(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function we(e,t=Tt){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 me(e,t){if(!e&&!t)return we($e/2n,Tt);let n=e?Qo(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?Qo(t):l("Resolved upper bound",$e);if(d(r))return r;let o=n.value,i=r.value;if(i<=o)return we($e/2n,Tt);let s=(o+i)/2n;return s===o||s===i?a("No rank space available between neighbors"):we(s,Tt)}function Zo(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=$e*BigInt(r+1)/(t+1n),i=we(o,Tt);if(d(i))return i;n.push(i.value)}return l("Resolved evenly spaced ranks",n)}var Dr=(e,t)=>{let n=U(e),r=Zo(n.length);if(d(r))return r;let o={};for(let i=0;i<n.length;i++){let s=n[i],c=r.value[i];if(!s||!c)return a("Unable to assign rebalance rank");o[s.id]=c}return l("Created rebalance event",{id:Ud(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import en from"node:fs";import _e from"node:path";import _r from"node:fs";import Yd from"node:os";import ke from"node:path";import Yt from"node:fs";import{ulid as $d}from"ulid";import{z as Nn}from"zod";var Wd="_epiq/_evt",_d=Nn.object({projectId:Nn.string().min(1),stateBranch:Nn.string().min(1),createdAt:Nn.iso.datetime()}),ei=()=>({projectId:$d(),stateBranch:Wd,createdAt:new Date().toISOString()}),Qe=e=>{let t=In(e);if(!Yt.existsSync(t))return a("Missing .epiq/project.json");try{let n=Yt.readFileSync(t,"utf8"),r=JSON.parse(n),o=_d.safeParse(r);return o.success?l("Read project.json",o.data):a(`Invalid .epiq/project.json: ${o.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(", ")}`)}catch(n){return a(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},ti=e=>{let t=Qe(e);return d(t)?a(t.message):l("Read projectId",t.value.projectId)},ni=({repoRoot:e,fileContents:t})=>{let n=bn(e),r=In(e);try{if(Yt.mkdirSync(n,{recursive:!0}),Yt.existsSync(r)){let o=Qe(e);return d(o)?a(o.message):l("Project already initialized",null)}return Yt.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 Fr=(e,t)=>{let n=new Map,r=t??((...i)=>JSON.stringify(i)),o=((...i)=>{let s=r(...i);if(!n.has(s)){let c=e(...i).then(u=>(d(u)&&n.delete(s),u));n.set(s,c)}return n.get(s)});return o.clear=()=>n.clear(),o};import Xt from"fs";import oi from"path";import Hd from"util";var ri=1e3,jd=50,Or=0,ii=()=>{let e=process.cwd(),t=wt(e);if(!d(t))return oi.join(t.value,We,"log","epiq.log")};function Kd(){let e=ii();if(!e||!Xt.existsSync(e))return;let n=Xt.readFileSync(e,"utf8").split(`
|
|
4
|
+
`);if(n[n.length-1]===""&&n.pop(),n.length<=ri)return;let r=n.slice(-ri).join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`;
|
|
7
|
-
`;
|
|
8
|
-
`);u(n?{stdout:
|
|
9
|
-
`)))}),o.on("close",p=>{let v=p??1;if(n){u({stdout:
|
|
10
|
-
`)));return}u(
|
|
11
|
-
${n.message}`);let r=await
|
|
12
|
-
${r.message}`):
|
|
13
|
-
`).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(
|
|
14
|
-
${r.message}`);let o=await
|
|
15
|
-
${i.message}`):
|
|
16
|
-
${o.message}`);let i=await
|
|
17
|
-
${i.message}`):
|
|
18
|
-
`+e.message);let t=
|
|
19
|
-
`+t.message):
|
|
6
|
+
`;Xt.writeFileSync(e,r,"utf8")}function Br(e,t,n=!1){let r=ii();if(!r)return;let o=Hd.format(...t),i=new Date,c=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
|
|
7
|
+
`;Xt.mkdirSync(oi.dirname(r),{recursive:!0}),Xt.appendFileSync(r,c,"utf8"),Or++,Or>=jd&&(Or=0,Kd())}var le={info(...e){Br("[Info]",e,!1)},debug(...e){Br("[debug]",e,!0)},error(...e){let t=e.find(n=>n instanceof Error)instanceof Error?void 0:new Error().stack;Br("[Error]",[...e,t].filter(Boolean),!1)}};globalThis.logger=le;import{spawn as Vd}from"node:child_process";import Rn from"node:fs";import Jt from"node:path";var K={stage:({cwd:e,pathspec:t})=>D({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>D({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>D({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>D({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>D({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push",...r?["-u"]:[],t,n]:["push"];return D({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>D({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>D({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>D({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>D({args:["worktree","prune"],cwd:e})};var mt=e=>{let t=Ze(e);if(d(t))return a("Unable to resolve epiq project root");let n=Qe(t.value);return d(n)?a("Unable to read project.json"):l("Resolved state branch",n.value.stateBranch)},pe="origin";var si=1e4,zd={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},di=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Rn.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=Vd("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:zd}),i=!1,s="",c="",u=p=>{i||(i=!0,clearTimeout(m),r(p))},m=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${si}ms`].join(`
|
|
8
|
+
`);u(n?{stdout:s,stderr:p,exitCode:124}:a(p))},si);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{s+=p}),o.stderr.on("data",p=>{c+=p}),o.on("error",p=>{if(n){u({stdout:s,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:s,stderr:c,exitCode:v});return}if(v!==0){u(a([`git ${e.join(" ")}`,c.trim()||s.trim()||"Git command failed"].filter(Boolean).join(`
|
|
10
|
+
`)));return}u(l("Git command succeeded",{stdout:s,stderr:c,exitCode:v}))})}),D=({args:e,cwd:t})=>di({args:e,cwd:t,allowFail:!1}),Se=({args:e,cwd:t})=>di({args:e,cwd:t,allowFail:!0}),Mt=async({cwd:e,message:t})=>{let n=await K.commit({cwd:e,message:t});if(d(n))return a(`Failed to create commit
|
|
11
|
+
${n.message}`);let r=await D({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())},Gd=async e=>{let t=await D({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",Jt.isAbsolute(n)?n:Jt.resolve(e,n))},qd=async e=>{let t=await Gd(e);if(d(t))return a(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress",REBASE_HEAD:"rebase in progress",CHERRY_PICK_HEAD:"cherry-pick in progress",REVERT_HEAD:"revert in progress",BISECT_LOG:"bisect in progress"};for(let[u,m]of Object.entries(r))if(Rn.existsSync(Jt.join(n,u)))return l("Checked for in-progress Git operation",m);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[u,m]of Object.entries(o))if(Rn.existsSync(Jt.join(n,u)))return l("Checked for in-progress Git operation",m);let i=await D({cwd:e,args:["status","--porcelain=v1","--branch"]});if(d(i))return a(i.message);let s=i.value.stdout.toLowerCase(),c=["rebase in progress","merge in progress","cherry-pick in progress","revert in progress","bisect in progress"].find(u=>s.includes(u));return l("Checked for in-progress Git operation",c??null)},An=async e=>{let t=await qd(e);return d(t)?a(t.message):l("Checked for in-progress Git operation",t.value!==null)},Ur=async({repoRoot:e})=>{let n=(await Se({args:["remote","get-url",pe],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},Qt=async({repoRoot:e,branch:t})=>{let n=await Se({args:["ls-remote","--heads",pe,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${pe}/${t}`):l("Checked remote branch",n.stdout.trim().length>0)},Tn=async({repoRoot:e,branch:t})=>{let n=await Se({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}`)},ai=e=>{try{return Rn.realpathSync.native(e)}catch{return Jt.resolve(e)}},ci=async({repoRoot:e,worktreeRoot:t})=>{let n=await D({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=ai(t),o=n.value.stdout.split(`
|
|
13
|
+
`).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(ai).includes(r);return l("Checked worktree registration",o)},$r=async e=>{let t=await Se({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},wn=async e=>{let t=await D({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?a(t.message):l("Resolved current branch",t.value.stdout.trim())},li=async e=>{let t=await D({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?a(t.message):l("Resolved short HEAD sha",t.value.stdout.trim())},ui=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),mi=async e=>(await Se({cwd:e,args:["rebase","--abort"]})).exitCode===0?l("Aborted stale rebase",!0):l("No rebase to abort",!1),pi=async({cwd:e,branch:t})=>{let n=await Qt({repoRoot:e,branch:t});if(d(n))return a(n.message);if(!n.value)return l("Remote branch missing, skipped reset",!1);let r=await K.fetch({cwd:e,remote:pe,branch:t});if(d(r))return a(`Failed to fetch ${t}
|
|
14
|
+
${r.message}`);let o=await mi(e);if(d(o))return a(o.message);let i=await D({cwd:e,args:["reset","--hard",`${pe}/${t}`]});return d(i)?a(`Failed to reset ${t} from remote
|
|
15
|
+
${i.message}`):l("Reset branch from remote",!0)},Wr=async({cwd:e,branch:t})=>{let n=await Qt({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 mi(e);if(d(r))return a(r.message);let o=await K.fetch({cwd:e,remote:pe,branch:t});if(d(o))return a(`Failed to fetch ${t}
|
|
16
|
+
${o.message}`);let i=await K.pullRebase({cwd:e,remote:pe,branch:t});return d(i)?a(`Failed during pull --rebase
|
|
17
|
+
${i.message}`):l("Pulled with rebase",!0)},gi=async e=>{let t=await Se({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 fi=async e=>{let t=await wn(e);return d(t)?a(t.message):l("Checked detached HEAD state",t.value==="HEAD")};var xi="4b825dc642cb6eb9a060e54bf8d69288fbee4904",pt=e=>ke.join(We,Ln,e),yi=()=>ke.join(Yd.homedir(),Ne),Mn=()=>ke.join(yi(),"worktrees"),Pn=({repoRoot:e})=>{let t=ti(e);return d(t)?a(t.message):l("Resolved state branch root",ke.join(Mn(),t.value))},Xd=e=>ke.join(e,We),vi=e=>ke.join(Xd(e),Ln);var Zt=e=>{try{return _r.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},kn=()=>{let e=Zt(yi());if(d(e))return a(`Ensure epiq home failed.
|
|
18
|
+
`+e.message);let t=Zt(Mn());return d(t)?a(`Ensure worktrees dir failed.
|
|
19
|
+
`+t.message):l("Ensured epiq storage",!0)},hi=e=>{_r.existsSync(e)&&(le.debug("[sync] remove path",e),_r.rmSync(e,{recursive:!0,force:!0}))};var Ci=(e,t)=>{for(let n of[vi(e),vi(t)]){let r=Zt(n);if(d(r))return a(r.message)}return l("Ensured state branch",void 0)},Ei=async e=>{let t=await D({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return a(`ensure state branch is storage only failed
|
|
20
20
|
`+t.message);let r=t.value.stdout.trim().split(`
|
|
21
|
-
`).filter(Boolean).filter(
|
|
22
|
-
${o.message}`);let i=await At({cwd:e,message:"[epiq:repair-storage-branch]"});return d(i)?s(i.message):c("Cleaned storage branch",!0)},wt=Tr(async(e=process.cwd())=>{let t=await L({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?s("Not inside a Git repository"):c("Resolved repo root",t.value.stdout.trim())},e=>Pe.resolve(e)),kp=Tr(async e=>{let t=await L({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return s(t.message);let n=t.value.stdout.trim(),r=Pe.isAbsolute(n)?n:Pe.join(e,n);return c("Resolved git dir",r)},e=>Pe.resolve(e));var $p=process.env.IS_LOCAL==="true",Be=".epiq",Ne=".epiq-global",Mn="events",kd="project.json",En=e=>Ue.join(e,Be),bn=e=>Ue.join(En(e),kd),Qt=e=>Ue.join(En(e),Mn),yi=e=>Ue.join(e,Be),Ld=e=>{let t=Ue.join(e,Be);return Jt.existsSync(t)&&Jt.statSync(t).isDirectory()},Or=e=>{let t=bn(e);return Jt.existsSync(t)&&Jt.statSync(t).isFile()},Rt=e=>{let t=Ue.resolve(e);for(;;){if(Ld(t))return c("Resolved closest .epiq root",t);let n=Ue.dirname(t);if(n===t)return s("No .epiq directory found in any parent");t=n}},Je=e=>{let t=Ue.resolve(e);for(;;){if(Or(t))return c("Resolved closest epiq project root",t);let n=Ue.dirname(t);if(n===t)return s("No .epiq/project.json found in any parent");t=n}},hi=e=>{let t=Qt(e);try{return Jt.mkdirSync(t,{recursive:!0}),c("Resolved events dir",t)}catch(n){return s(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},Te=async()=>{let e=await wt(process.cwd());if(d(e))return e;let t=wn({repoRoot:e.value});return d(t)?t:c("Resolved persist root",t.value)};var Y={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History"};import{useSyncExternalStore as iu}from"react";var f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};function Pn(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var kn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",xi=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var Ci=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),i=t.get(o);i?i.push(n):t.set(o,[n])}return t},Ei=(e,t)=>t?e.get(t)??[]:[];var bi=new WeakMap,Dd=e=>{let t=bi.get(e);return t||(t=Ci(e),bi.set(e,t)),t};var Ni=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Ei(Dd(e),r).filter(i=>Pn(r,i)>=n)};var Fd={hint:"",hints:[],overlap:0,remainder:""},Si=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Fd;let o=Ni({wordList:r,inputToMatch:e,overlapThreshold:1});return Od(t,o)},Od=(e,t)=>{let n=t[0]??"",r=Pn(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),a=r<(o??"").length,l=!!i,p=(l&&a?o:n)+(l&&a?":":" "),v=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:v}};var Ln={autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},$=()=>Ln,ye=e=>(Ln={...Ln,...e},Ln);var Tt=3e3,Ii=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Tt?null:t},Ri=0,Br,Ur=!1,Zt=!1,$r=()=>{if(Ur)return!0;let e=Qe();return d(e)?!1:e.value.syncStatus.status==="syncing"},Bd=()=>{let e=$().autoSyncIntervalMs??1e4,t=Date.now()-Ri;return Math.max(0,e-t)},Ai=()=>{Br||(Br=setTimeout(async()=>{if(Br=void 0,!!Mt()){if($r()){Zt=!0;return}Zt=!1,await Ud()}},Bd()))},Ud=async()=>{if(!Mt())return s("Cannot auto-sync before state is initialized");if($r())return Zt=!0,s("Sync already in progress");Ur=!0,Ri=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Dn()}finally{Ur=!1,Zt&&Ai()}},wi=()=>{Mt()&&(Zt=!0,!$r()&&Ai())};var Ze=()=>{let e=$(),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}},Ti=()=>{let e=Je(process.cwd());if(d(e))return!1;let t=Xe(e.value);return ce(t)},Mi=e=>e===!0?"yes":e===!1?"no":null,Pi=e=>e==="yes"?!0:e==="no"?!1:null;var se={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#2a2f45",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},x={accent:se.cyan,accent2:se.magenta,primary:se.white,secondary:se.grayDark,secondary2:se.grayLight,gray:se.gray,green:se.green,yellow:se.yellow,red:se.red};var b={red:se.red,yellow:se.yellow,green:se.green,blue:se.blue,magenta:se.magenta,cyan:se.cyan},Pt={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 $d=e=>e.props.tags??[],Wd=e=>e.props.assignees??[],Wr=e=>$d(e).map(t=>S.getTag(t)).filter(t=>!!t),_r=e=>Wd(e).map(t=>S.getContributor(t)).filter(t=>!!t),Fn=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!W(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Wr(n))},On=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!W(n)?s("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",_r(n))};var y={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",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",NONE:""};var _d=/^(\d+)(h|d|w|mo|y)$/,jd=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Hd=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let i=new Date(e,t-1,n,r,o);return i.getFullYear()===e&&i.getMonth()===t-1&&i.getDate()===n&&i.getHours()===r&&i.getMinutes()===o},Vd=(e,t=new Date)=>{let n=e.match(_d);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let a=new Date(t);switch(o){case"h":return a.setHours(a.getHours()-i),a;case"d":return a.setDate(a.getDate()-i),a;case"w":return a.setDate(a.getDate()-i*7),a;case"mo":return a.setMonth(a.getMonth()-i),a;case"y":return a.setFullYear(a.getFullYear()-i),a;default:return null}},Kd=e=>{let t=e.match(jd);if(!t)return null;let[,n,r,o,i,a]=t,l=Number(n),u=Number(r),m=Number(o),p=i?Number(i):0,v=a?Number(a):0;return Hd({year:l,month:u,day:m,hour:p,minute:v})?new Date(l,u-1,m,p,v):null},Bn=e=>{let t=e.trim().toLowerCase();return Vd(t)??Kd(t)},ki=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,zd=[{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}],Li=(e=zd)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let i=r;i<=o;i++)t.push(`${i}${n}`);return t};var Gd=["BOARD","TICKET","SWIMLANE"],te={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs"},et={TITLE:"title",DESCRIPTION:"description"},qd=[te.EDITOR,te.VIEW,te.USERNAME,te.AUTOSYNC,te.SYNC_DEBOUNCE_MS],Yd=[et.TITLE,et.DESCRIPTION],Hr=[String(Tt),"5000","15000","30000","60000"],mt=[y.SYNC,y.HELP,y.EXPORT,y.CONFIG],Un=[y.NEW,y.EDIT,y.DELETE,y.MOVE],jr=[y.TAG,y.UNTAG,y.ASSIGN,y.UNASSIGN,y.CLOSE_ISSUE,y.RE_OPEN_ISSUE,y.EDIT],Di=[y.FILTER,y.PEEK],Xd={WORKSPACE:[...mt,...Un],BOARD:[...Di,...mt,...Un],SWIMLANE:[...Di,...mt,...Un],TICKET:[...mt,...Un,...jr],FIELD:[...mt,...jr],FIELD_LIST:[...mt,...jr],TEXT:[...mt]},Jd=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Qd=()=>{let{selectedNode:e,readOnly:t,breadCrumb:n}=h(),{isSetupDone:r}=Ze();if(!r)return[y.HELP,y.CONFIG];if(!Ti())return[y.HELP,y.INIT];if(t)return[y.HELP,y.PEEK,y.EXPORT,y.CONFIG];let o=e?.context,i=o&&Gd.includes(o);return[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?Xd[l]:[]))].filter(l=>l===y.MOVE?!1:l===y.EDIT||l===y.DELETE?i:!0)},X=e=>{let{currentNode:t}=h(),n=t.context??"WORKSPACE";return{[y.NONE]:Qd(),[y.EXIT]:["confirm"],[y.EXPORT]:[],[y.SYNC]:[],[y.INIT]:[],[y.HELP]:[],[y.PEEK]:[...Li(),"now","prev","next"],[y.EDIT]:[...Yd],[y.DELETE]:["confirm"],[y.RE_OPEN_ISSUE]:["confirm"],[y.CLOSE_ISSUE]:["confirm"],[y.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[y.FILTER]:["tag","assignee","description","title","clear"],[y.TAG]:[...new Set([...Object.keys(Pt),...S.getExistingTags()])],[y.UNTAG]:[...Fn()?.value?.map(({name:o})=>o)??[]],[y.UNASSIGN]:[...On()?.value?.map(({name:o})=>o)??[]],[y.ASSIGN]:S.getExistingAssignees(),[y.NEW]:Jd(n),[y.CONFIG]:[...qd]}[e]??[]};import Lt from"chalk";var Fi=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import{decodeTime as Oi}from"ulid";var Bi=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let i=Math.floor(t/o);if(i>=1)return`${i}${r} ago`}return"just now"},Ui=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())}`},$n=e=>{try{return c("Decoded date",new Date(Oi(e)))}catch(t){return s("Decoding failed + "+t.message)}},Vr=e=>{if(!e?.id)return null;try{return Oi(e.id)}catch{return null}};var Se=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?c("Found node",n):s("Unable to find node in breadcrumb")};import kt from"chalk";var zr={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Zd=(e,t,n)=>Math.max(t,Math.min(n,e)),Kr=(e,t,n)=>e+(t-e)*n,$i=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},ec=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,a=e/60,l=i*(1-Math.abs(a%2-1)),u=0,m=0,p=0;a>=0&&a<1?(u=i,m=l):a>=1&&a<2?(u=l,m=i):a>=2&&a<3?(m=i,p=l):a>=3&&a<4?(m=l,p=i):a>=4&&a<5?(u=l,p=i):(u=i,p=l);let v=o-i/2;return[Math.round((u+v)*255),Math.round((m+v)*255),Math.round((p+v)*255)]},tc=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,nc=(e,t,n)=>[Math.round(Kr(e[0],t[0],n)),Math.round(Kr(e[1],t[1],n)),Math.round(Kr(e[2],t[2],n))],en=e=>{let n=$i(e)%360,r=ec(n,zr.stringColor.saturation,zr.stringColor.lightness);return tc(r)},rc=e=>{let t=zr.gradient.stops,n=Zd(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,i=Math.min(Math.floor(o),r-1),a=o-i;return nc(t[i],t[i+1],a)},Wn=e=>$i(e.toLowerCase().trim())/4294967295,Wi=e=>{let t=Wn(e);return rc(t)},oc=e=>{let[t,n,r]=Wi(e);return{normal:o=>kt.bgRgb(t,n,r).black(o),cursor:o=>kt.bgRgb(t,n,r).white.bold(o)}},Gr=e=>{let[t,n,r]=Wi(e);return{fg:o=>kt.rgb(t,n,r)(o),fgCursor:o=>kt.rgb(t,n,r).inverse(o),bg:o=>kt.bgRgb(t,n,r).black(o),bgCursor:o=>kt.bgRgb(t,n,r).white.bold(o)}},qr=e=>oc(e).normal(` ${e} `),ae=(e,t=Pt)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:en(r)};var pt={None:"none",Invalid:"invalid",Valid:"valid"};var ic=["BOARD","TICKET","SWIMLANE"],_i=()=>{let e=h().selectedNode;return e?.context?ic.includes(e.context)?H():F({message:"Command not available in this context"}):F({message:"Missing target context"})},J="<ENTER> to confirm",H=(e="",t=[])=>({message:e,validity:pt.Valid,completionWordList:t}),F=({message:e,completionWordList:t=[]})=>({validity:pt.Invalid,message:e,completionWordList:t}),_n=e=>e.length===0,he=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let a=o.trim();if(a.length<i)return"";let p=[...t.filter(Boolean).filter(v=>v.startsWith(a))].sort((v,C)=>Wn(v)-Wn(C)).slice(0,r).map(qr).join(" ");return p?`${e}${p}${n}`:""},Yr=({modifier:e})=>{let t="confirm";return e===t?H(J):F({message:_n(e)?`if you are certain, enter ${qr(t)}`:"",completionWordList:[t]})},sc=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?F({message:n}):H():F({message:_n(r)?t:"",completionWordList:[...e]}),tn=({hint:e})=>({modifier:t,inputString:n})=>_n(t)&&_n(n)?F({message:e,completionWordList:[]}):H(J),ac=({modifier:e,inputString:t})=>{let n=X(y.CONFIG);if(!n.includes(e))return F({message:he({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case te.EDITOR:{let r=[...Fi];return t.trim()?r.includes(t.trim())?H(J):F({message:he({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):F({message:he({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case te.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?H(J):F({message:he({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case te.USERNAME:return t.trim()?H(J):F({message:`Enter a user name. Saved in ${Lt.bgBlack("~/.epiq-global/config.json")}`});case te.AUTOSYNC:{let r=["yes","no"],o=$().autoSync;if(!r.includes(t.trim())){let i=Mi(o);return F({message:he({prefix:`should auto-sync (recommended)${i!==null?", currently: "+i:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return H(J)}case te.SYNC_DEBOUNCE_MS:{let r=$().autoSyncIntervalMs,o=Ii(t);if(!t.trim()||o===null||o<Tt){let i=he({prefix:" examples: ",wordList:Hr,minLengthForHints:0,inputString:t});return F({message:`provide duration above ${Tt}ms. current duration: ${r}ms.`+i,completionWordList:Hr})}return H(J)}default:return F({message:"Unknown config option",completionWordList:n})}},dc=({modifier:e})=>{let t=X(y.EDIT);if(!t.includes(e)){let i=he({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return F({message:i||"Unknown edit option",completionWordList:t})}let{breadCrumb:n,selectedNode:r}=h();if(!Se([...n,r],"TICKET"))return F({message:"Command not available in this context"});switch(e){case et.TITLE:return H(J);case et.DESCRIPTION:return H("<ENTER> to edit in "+$().preferredEditor);default:return F({message:"Unknown edit option",completionWordList:t})}},cc={[y.EXPORT]:()=>H(J+", and create export markdown file"),[y.PEEK]:e=>{let t=e.modifier;if(t==="now")return H(J);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return H(J);let r=Bn(t);if(!t||!r)return F(n);let o=Se(h().breadCrumb,"BOARD");if(d(o))return F({message:"Command is not applicable in this context"});let i=$n(o.value.id);return d(i)?F({message:"Unable to peek: board id is not a valid ULID"}):ki({date:r,horizonDate:i.value})?H(J):F({message:Lt.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[y.EXIT]:()=>H(J+" and exit the application"),[y.INIT]:()=>H(J),[y.PALETTE]:()=>H(J),[y.FILTER]:e=>{if(e.modifier==="clear")return H();let t=i=>X(y.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return F({message:he({wordList:X(y.FILTER),inputString:e.inputString}),completionWordList:X(y.FILTER)});let n=Object.values(h().tags).map(i=>i.name),r=Object.values(h().contributors).map(i=>i.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?F({message:he({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):H():F({message:he({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[y.NONE]:e=>{let t=X(y.NONE);return F({message:he({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[y.NEW]:e=>sc({list:X(y.NEW),hint:he({wordList:X(y.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[y.HELP]:()=>H(J),[y.EDIT]:dc,[y.CONFIG]:ac,[y.DELETE]:e=>{let t=_i();return t.validity==="invalid"?t:Yr(e)},[y.CLOSE_ISSUE]:e=>Yr(e),[y.RE_OPEN_ISSUE]:e=>Yr(e),[y.MOVE]:e=>{let t=_i();return t.validity==="invalid"?t:tn({hint:he({prefix:"hey hacker! These commands are blocked for you... ",wordList:X(y.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[y.TAG]:e=>{let n=S.getExistingTags().map(r=>` ${Lt.bgHex(ae(r))(" "+r+" ")} `).slice(0,10).join("");return tn({hint:n.length?"existing tags ... "+n:"create tag ..."})(e)},[y.UNTAG]:e=>{let t=Fn();if(d(t))return F({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${Lt.bgHex(ae(r))(" "+r+" ")} `).slice(0,10);return n.length?tn({hint:" ... "+n.join("")})(e):F({message:"Issue has no tags",completionWordList:[]})},[y.ASSIGN]:e=>{let t=S.getExistingAssignees().map(n=>` ${Lt.bgHex(ae(n))(" "+n+" ")} `).slice(0,10);return tn({hint:"assign to... "+t.join("")})(e)},[y.UNASSIGN]:e=>{let t=On();if(d(t))return F({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${Lt.bgHex(ae(r))(" "+r+" ")} `).slice(0,10);return n.length?tn({hint:"remove assignee... "+n.join("")})(e):F({message:"Issue has no assignees",completionWordList:[]})},[y.SYNC]:()=>H(J)},ji=Object.fromEntries(Object.entries(cc).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Hi=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"];var Vi=e=>Object.values(y).includes(e),Ki=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:l,completionWordList:u}=ji[n].validate(n,r,i),m=o==="command"||o==="modifier"?X(n):Hi,{mode:p}=h(),v=p===f.COMMAND_LINE?a??"":"",C=[...u,...m];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:v,autoCompletion:t?Si(e,C):{hint:"",hints:[],remainder:"",overlap:0}}};var zi=e=>{let t=e.trimStart(),n=uc(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),a=mc(e),l=Vi(r)?r:null,u=l!==null,m=r!=="",p=l?X(l)??[]:[],v=l&&p.includes(o)?o:"",C="word";n.length===0||n.length===1&&!i?C="command":(n.length===1&&i||n.length===2&&!i)&&(C="modifier");let E=i?"":a,I=lc(t,l,v);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:a,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:i,modifier:v,target:C,inputToMatch:E,inputString:I}},lc=(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},uc=e=>e.trim()?e.trim().split(/\s+/):[],mc=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as pc}from"react";var Dt=e=>e===Xr||e===":",Xr=" ",de={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:pt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Jr=new Set,Gi=()=>{for(let e of Jr)e()},Qr=e=>(Jr.add(e),()=>Jr.delete(e)),$e=e=>{let n=e(de),r=zi(n.value),o=n.cursorPosition===n.value.length;de={...n,commandMeta:Ki(r,o)},Gi()},nn=({message:e,status:t})=>{let n=structuredClone(de);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,de=n,Gi(),c(e,null)},Zr=e=>{$e(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},eo=e=>{$e(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Dt(n[o-1]);)o--;for(;o>0&&!Dt(n[o-1]);)o--}else{for(;o<n.length&&!Dt(n[o]);)o++;for(;o<n.length&&Dt(n[o]);)o++}return{...t,cursorPosition:o}})},qi=()=>{$e(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}})},Yi=()=>{$e(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Dt(t[r-1]);)r--;for(;r>0&&!Dt(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},_=e=>{$e(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),i=e(r,t.commandMeta.autoCompletion),a=i+o,l=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:l,commandIsPending:!1}})},Xi=()=>{$e(e=>({...e,commandIsPending:!0}))},Ji=({addToHistory:e=!0})=>{$e(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),fc()},Qi=()=>{$e(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}})},Zi=()=>{$e(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},fc=()=>_(()=>""),K=()=>de,es=()=>pc(Qr,K,K),ts=()=>{let[e,...t]=de.value.split(Xr);return t.join(Xr).trim()};var ns=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",rs=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",os=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",is=(e,t)=>{if(rs(e,e.sequence))return g.MoveCursorLeftOfWord;if(os(e,e.sequence))return g.MoveCursorRightOfWord;if(ns(e,e.sequence))return g.EraseInputWord;switch(e.name){case"tab":return g.AutoCompleteCommand;case"up":return g.GetLastCommandFromHistory;case"down":return g.GetNextCommandFromHistory;case"left":return g.MoveCursorLeft;case"right":return g.MoveCursorRight;case"return":return g.Confirm;case"backspace":return t?g.EraseInput:g.ExitCommandLine;case"escape":return g.ExitCommandLine;default:return g.CaptureInput}},ss=(e,t)=>{if(rs(e,e.sequence))return g.MoveCursorLeftOfWord;if(os(e,e.sequence))return g.MoveCursorRightOfWord;if(ns(e,e.sequence))return g.EraseInputWord;switch(e.name){case"tab":return g.AutoCompleteCommand;case"up":return g.NavPreviousItem;case"down":return g.NavNextItem;case"left":return g.MoveCursorLeft;case"right":return g.MoveCursorRight;case"return":return g.Confirm;case"backspace":return t?g.EraseInput:g.ExitCommandLine;case"escape":return g.ExitCommandLine;default:return g.CaptureInput}};var g={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",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function gc(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function vc(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function yc(e,t,n){let r=h().currentNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function as(e,t){let n=K();if(e.sequence==="?"&&n.value==="")return g.InitCommandPalette;if(e.sequence===":"&&n.value==="")return g.InitCommandLine;if(t===f.MOVE)switch(e.name){case"m":case"return":return g.ConfirmMove}if(t===f.COMMAND_LINE)return is(e,n.value);if(t===f.PALETTE)return ss(e,n.value);let r=gc(e)||vc(e);if(r)return hc(r,t);if(e.ctrl&&e.name==="c")return g.Exit;switch(e.name){case"e":return g.Edit;case"n":return g.AddItem;case"m":return g.InitMove;case"d":return g.Delete;case"return":return g.Confirm;case"space":return g.Confirm;case"v":return $().viewMode==="wide"?g.SetViewDense:g.SetViewWide;case"q":case"escape":return g.Exit;default:return null}}function hc(e,t){let n=t===f.MOVE?{prevItem:g.MovePreviousItem,nextItem:g.MoveNextItem,prevContainer:g.MoveToPreviousContainer,nextContainer:g.MoveToNextContainer}:{prevItem:g.NavPreviousItem,nextItem:g.NavNextItem,prevContainer:g.NavToPreviousContainer,nextContainer:g.NavToNextContainer};return yc(h().currentNode.childRenderAxis,e,n)}var jn=e=>{let{context:t}=h().currentNode;if(!t)return T.None;switch(e){case y.EXIT:return T.Exit;case y.EXPORT:return T.Export;case y.INIT:return T.Init;case y.DELETE:return T.Delete;case y.EDIT:return T.Edit;case y.HELP:return T.ViewHelp;case y.RE_OPEN_ISSUE:return T.ReopenIssue;case y.CLOSE_ISSUE:return T.CloseIssue;case y.TAG:return T.TagTicket;case y.UNTAG:return T.UntagTicket;case y.ASSIGN:return T.AssignUserToTicket;case y.UNASSIGN:return T.UnassignUserFromTicket;case y.NEW:return T.NewItem;case y.FILTER:return T.Filter;case y.MOVE:return T.Move;case y.PEEK:return T.Peek;case y.CONFIG:return T.Config;case y.SYNC:return T.Sync;default:return T.None}},T={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",Sync:"sync",Export:"export"};import{ulid as ve}from"ulid";import hs from"node:fs";import Vc from"node:path";import Kc from"react";import{Box as jc}from"ink";import Gn from"react";import{Box as ro,Text as Mc}from"ink";import ke from"react";import{Text as ds}from"ink";import cs,{useEffect as ls,useState as xc}from"react";var us={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},ge=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Q(),r=us[n]??us.default,[o,i]=xc(0);if(ls(()=>{i(0)},[r]),ls(()=>{if(!e)return;let l=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return cs.createElement(ds,null,t);let a=r[o]??r[0]??t;return cs.createElement(ds,{color:x.accent,dimColor:o===1},a)};import{Box as to,Text as Cc}from"ink";import Hn from"react";var Ft=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),a=Math.max(1,Math.ceil(r)),l=Math.max(1,Math.floor(i/a)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-l),p=o?Math.min(m,Math.max(0,u-l+1)):Math.min(m,Math.floor(u/l)*l),v=p+l,C=e.slice(p,v),E=e.length>l,I=i,P=E?Math.max(1,Math.floor(l/e.length*I)):I,R=Math.max(0,I-P),w=Math.max(1,e.length-l),D=E?Math.floor(p/w*R):0;return Hn.createElement(to,{flexDirection:"row",height:i,width:"100%"},Hn.createElement(to,{flexDirection:"column",flexGrow:1,height:i},C),Hn.createElement(to,{flexDirection:"column",width:1,height:I},Array.from({length:I}).map((ee,oe)=>Hn.createElement(Cc,{key:oe,color:E&&oe>=D&&oe<D+P?x.accent:x.secondary},E?"\u2502":" "))))};import{Box as Vn,Text as Ac}from"ink";import ft from"react";import{Text as Ec}from"ink";import bc from"react";var Nc=e=>e.toLowerCase().trim(),Sc=(e,t=Pt)=>{let n=Nc(e);return t[n]?t[n]:en(n)},Ot=({id:e,isSelected:t})=>{let n=S.getContributor(e);if(n)return bc.createElement(Ec,{underline:t,color:Sc(n.name)},"@"+n.name)};import{Text as Ic}from"ink";import Rc from"react";var Bt=({id:e,isSelected:t})=>{let n=S.getTag(e);if(n)return Rc.createElement(Ic,{underline:t,backgroundColor:ae(n.name),color:x.primary}," "+n.name+" ")};var ms=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=kn(xi(t.title),r),i=Wr(t),a=_r(t);return ft.createElement(Vn,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?x.accent:x.secondary,justifyContent:"space-between"},ft.createElement(Vn,{borderBottom:!0},ft.createElement(Vn,{paddingLeft:1,flexDirection:"column"},ft.createElement(Ac,{color:x.primary},o))),ft.createElement(Vn,{flexDirection:"row",paddingLeft:1},i.map(l=>ft.createElement(Bt,{key:l.id,id:l.id})),a.map(l=>ft.createElement(Ot,{key:l.id,id:l.id}))))};import wc from"chalk";import{Box as rn,Text as no}from"ink";import We from"react";var Tc=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,ps=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=(t.props.tags??[]).map(E=>S.getTag(E)).filter(E=>!!E),a=(t.props.assignees??[]).map(E=>S.getContributor(E)).filter(E=>!!E),l=1,u=i.length*(1+l),m=a.length*(2+l),p=i.map(E=>We.createElement(rn,{key:E.id,paddingRight:l},We.createElement(no,{color:ae(E.name)},"\u25A0"))),v=a.map(E=>We.createElement(rn,{key:E.id,paddingRight:l},We.createElement(no,{color:en(E.name)},"@"+E.name.at(0)))),C=n?x.accent:o===f.MOVE?x.secondary:x.primary;return We.createElement(rn,{borderBottom:!0,justifyContent:"space-between"},We.createElement(rn,null,We.createElement(ge,{isSelected:n,placeholder:wc.dim.gray(r+1+" ")}),We.createElement(no,{wrap:"truncate",color:C},Tc(t.title,e-u-m-14))),We.createElement(rn,null,p,v))};import Pc from"chalk";var kc=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:a,mode:l})=>{let{renderedChildrenIndex:u}=Q(),m=u[e.id]??[],p=`${e.title} ${Pc.hex(x.secondary2).dim("("+m.length+")")}`,v=3,C=o?1:4,E=r-v-(o?2:1),I=ke.createElement(ro,{borderStyle:"round",borderColor:x.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},ke.createElement(ge,{isSelected:t}),ke.createElement(Mc,{bold:!0,color:t?x.accent:x.primary},p," ",e.readonly?"\u{1F512}":"")),P=(R,w)=>{let D=i&&a===w;return o?ke.createElement(ps,{key:R.id,index:w,width:n,ticket:R,isSelected:D,mode:l}):ke.createElement(ms,{key:R.id,width:n,ticket:R,isSelected:D})};return ke.createElement(ro,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?x.accent:x.secondary,paddingRight:1,paddingLeft:1,height:r},I,ke.createElement(ro,{padding:o?1:0},m.length>0&&ke.createElement(Ft,{selectedIndex:a,height:E,itemHeight:C},m.map(P)),ke.createElement(ge,{isSelected:i&&a===-1})))},fs=ke.memo(kc);import{Box as so,Text as $c}from"ink";import nt,{useMemo as vs}from"react";import{decodeTime as Lc,encodeTime as Dc}from"ulid";var Fc="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Oc=e=>{let t=2166136261;for(let o of e)t^=o.charCodeAt(0),t=Math.imul(t,16777619);let n=BigInt(t>>>0),r="";for(let o=0;o<16;o++)n=n*1103515245n+12345n&0xffffffffn,r+=Fc[Number(n%32n)];return r},tt=(e,t)=>{let n=Lc(e);return Dc(n,10)+Oc(`${e}:${t}`)};import{Box as Kn,Text as Bc}from"ink";import _e from"react";var gs=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=Q(),{title:o}=t,i=t.parentNodeId?S.getNode(t.parentNodeId):void 0,a=i&&W(i)?o===Y.ASSIGNEES?i.props.assignees??[]:o===Y.TAGS?i.props.tags??[]:[]:[];return _e.createElement(Kn,{alignItems:"center",paddingTop:1},_e.createElement(Kn,{minWidth:12},_e.createElement(ge,{isSelected:n}),_e.createElement(Bc,{color:n?x.accent:x.secondary2},o,":")),_e.createElement(Kn,{flexDirection:"row",marginLeft:1,paddingRight:1},a.map((l,u)=>{let m=r.id===t.id&&u===e;return _e.createElement(Kn,{key:`${o}-${l}`,paddingRight:2,minHeight:1},_e.createElement(ge,{isSelected:m}),o===Y.ASSIGNEES?_e.createElement(Ot,{isSelected:m,id:l}):o===Y.TAGS?_e.createElement(Bt,{isSelected:m,id:l}):null)})))};import{Box as zn,Text as oo}from"ink";import je,{useEffect as Uc}from"react";var ne={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:A.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:A.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:A.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:i="horizontal",isVirtual:a=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:A.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[],isVirtual:a}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:A.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:A.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:i=!0,isVirtual:a=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:A.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[],isVirtual:a})};var io=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:l}=Q(),u=C=>String(C).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];Uc(()=>{let C=[];return m.forEach((E,I)=>{let P=we(BigInt(I+1));if(!ce(P))return;let R=ne.text({id:`${e}-${I}`,name:`Line ${I+1}`,parentNodeId:e,rank:P.value,props:{value:E},readonly:!0,isVirtual:!0}),w=S.createNode(R);ce(w)&&C.push(w.value.id)}),()=>C.forEach(S.deleteNode)},[e,n]);let p="\u2029",v=m.map((C,E)=>{let I=l.id===e&&a===E;return je.createElement(zn,{key:`${e}-${E}`},je.createElement(oo,{color:I?x.primary:x.secondary2,dimColor:!I},`${E+1} `.padStart(5,"\xA0")),je.createElement(oo,{backgroundColor:I?"gray":""},u(C.length?kn(C,i-10):p)))});return je.createElement(zn,{flexDirection:"column",paddingTop:1},je.createElement(zn,null,je.createElement(ge,{isSelected:o}),je.createElement(oo,{color:o?x.accent:x.secondary2},t)),je.createElement(zn,{flexDirection:"row",borderStyle:"round",borderColor:x.secondary,paddingLeft:1,marginLeft:1},je.createElement(Ft,{scrollByOne:!0,children:v,height:r-2,selectedIndex:a,itemHeight:1})))};var Wc=e=>tt(e,"description"),_c=e=>tt(e,"history"),ys=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=Q(),o=process.stdout.columns||120,i=vs(()=>Wc(e.id),[e.id]),a=vs(()=>_c(e.id),[e.id]),l=r.id===e.id,u=r.id===a||r.parentNodeId===a,m=O(e.id);if(u){let R=S.getNode(a),w=R&&qe(R)?R.props.value??"":"",ee=t-3;return nt.createElement(so,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R?nt.createElement(io,{id:R.id,label:"Event log",text:w,selected:!1,maxWidth:o,height:ee}):null)}let p=m.reduce((R,w)=>Kt(w)||w.id===a?R+1:R,0),v=2,C=3,E=p,I=t-C-E-v,P=(R,w)=>R.id===i?nt.createElement(io,{key:R.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:w,maxWidth:o,height:I}):Kt(R)?nt.createElement(gs,{key:R.id,parent:R,selected:w,selectedIndex:n}):R.id===a?nt.createElement(so,{key:R.id,paddingTop:1},nt.createElement(ge,{isSelected:w}),nt.createElement($c,{backgroundColor:x.secondary,color:w?x.accent:x.primary}," History \u203A\u203A ")):null;return nt.createElement(so,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((R,w)=>P(R,l&&n===w)))};var Hc=({swimlanes:e,currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:a,width:l})=>{let u=t.context,m=u===A.TICKET||u===A.FIELD_LIST||u===A.FIELD,p=u===A.BOARD||u===A.SWIMLANE,v=u===A.TICKET?t:r.find(R=>R.context===A.TICKET),C=Math.floor(l/3),E=Math.floor(l/Math.max(e.length,1)),I=Math.min(E,C),P=i==="dense";return Gn.createElement(jc,{flexDirection:"row",height:a},p&&e.map((R,w)=>{let D=t.id===R.id,ee=D?n:-1,oe=t.context===A.BOARD&&n===w;return Gn.createElement(fs,{key:R.id,height:a,width:I,swimlane:R,isSelected:oe,isDense:P,isFocused:D,listSelectedIndex:ee,mode:o})}),m&&v&&Gn.createElement(ys,{height:a,ticket:v}))},qn=Gn.memo(Hc);import{render as zc}from"ink";import{Writable as Gc}from"node:stream";var on=e=>String(e).padStart(2,"0"),qc=e=>{let t=e.getUTCFullYear(),n=on(e.getUTCMonth()+1),r=on(e.getUTCDate()),o=on(e.getUTCHours()),i=on(e.getUTCMinutes()),a=on(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${a}`},Yc=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Xc=async(e,{width:t,height:n})=>{let r="",o=new Gc({write(a,l,u){let m=Jc(a.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=zc(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(a=>setTimeout(a,0)),i.unmount(),r},Jc=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),xs=async()=>{let{viewMode:e}=$(),{currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:i}=h(),a=r.find(w=>w.context==="BOARD");if(!a)return s("No board found to export");let l=120,u=40,m=await Xc(Kc.createElement(qn,{height:u,width:l,swimlanes:(i[a.id]??[]).filter(w=>w!==void 0&&St(w)),currentNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:u});if(!m)return s("Failed to render board export");let p=Rt(process.cwd());if(d(p))return s("Unable to export, epiq root not found");let v=new Date,C=qc(v),E=`board_${Yc(a.title)}_${C}.md`,I=yi(p.value);hs.mkdirSync(I,{recursive:!0});let P=Vc.join(I,E),R=`# Board - ${a.title}
|
|
21
|
+
`).filter(Boolean).filter(s=>s!==We);if(r.length===0)return l("State branch is storage-only",!1);let o=await D({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return a(`Failed to clean storage branch
|
|
22
|
+
${o.message}`);let i=await Mt({cwd:e,message:"[epiq:repair-storage-branch]"});return d(i)?a(i.message):l("Cleaned storage branch",!0)},Pt=Fr(async(e=process.cwd())=>{let t=await D({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=>ke.resolve(e)),ng=Fr(async e=>{let t=await D({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return a(t.message);let n=t.value.stdout.trim(),r=ke.isAbsolute(n)?n:ke.join(e,n);return l("Resolved git dir",r)},e=>ke.resolve(e));var cg=process.env.IS_LOCAL==="true",We=".epiq",Ne=".epiq-global",Ln="events",Jd="project.json",bn=e=>_e.join(e,We),In=e=>_e.join(bn(e),Jd),tn=e=>_e.join(bn(e),Ln),Si=e=>_e.join(e,We),Qd=e=>{let t=_e.join(e,We);return en.existsSync(t)&&en.statSync(t).isDirectory()},Hr=e=>{let t=In(e);return en.existsSync(t)&&en.statSync(t).isFile()},wt=e=>{let t=_e.resolve(e);for(;;){if(Qd(t))return l("Resolved closest .epiq root",t);let n=_e.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},Ze=e=>{let t=_e.resolve(e);for(;;){if(Hr(t))return l("Resolved closest epiq project root",t);let n=_e.dirname(t);if(n===t)return a("No .epiq/project.json found in any parent");t=n}},Ni=e=>{let t=tn(e);try{return en.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")}},Me=async()=>{let e=await Pt(process.cwd());if(d(e))return e;let t=Pn({repoRoot:e.value});return d(t)?t:l("Resolved persist root",t.value)};var Y={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History"};import{useSyncExternalStore as wu}from"react";var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};function Dn(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Fn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",bi=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Ii=e=>e.charAt(0).toUpperCase()+e.slice(1);var Ri=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),i=t.get(o);i?i.push(n):t.set(o,[n])}return t},Ai=(e,t)=>t?e.get(t)??[]:[];var Ti=new WeakMap,Zd=e=>{let t=Ti.get(e);return t||(t=Ri(e),Ti.set(e,t)),t};var wi=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Ai(Zd(e),r).filter(i=>Dn(r,i)>=n)};var ec={hint:"",hints:[],overlap:0,remainder:""},Mi=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return ec;let o=wi({wordList:r,inputToMatch:e,overlapThreshold:1});return tc(t,o)},tc=(e,t)=>{let n=t[0]??"",r=Dn(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),s=r<(o??"").length,c=!!i,p=(c&&s?o:n)+(c&&s?":":" "),v=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:v}};var On={autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},$=()=>On,Le=e=>(On={...On,...e},On);var kt=3e3,Pi=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<kt?null:t},ki=0,jr,Kr=!1,nn=!1,Vr=()=>{if(Kr)return!0;let e=et();return d(e)?!1:e.value.syncStatus.status==="syncing"},nc=()=>{let e=$().autoSyncIntervalMs??1e4,t=Date.now()-ki;return Math.max(0,e-t)},Li=()=>{jr||(jr=setTimeout(async()=>{if(jr=void 0,!!Lt()){if(Vr()){nn=!0;return}nn=!1,await rc()}},nc()))},rc=async()=>{if(!Lt())return a("Cannot auto-sync before state is initialized");if(Vr())return nn=!0,a("Sync already in progress");Kr=!0,ki=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Bn()}finally{Kr=!1,nn&&Li()}},Di=()=>{Lt()&&(nn=!0,!Vr()&&Li())};var tt=()=>{let e=$(),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}},Fi=()=>{let e=Ze(process.cwd());if(d(e))return!1;let t=Qe(e.value);return ne(t)},Oi=e=>e===!0?"yes":e===!1?"no":null,Bi=e=>e==="yes"?!0:e==="no"?!1:null;var de={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#2a2f45",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},h={accent:de.cyan,accent2:de.magenta,primary:de.white,secondary:de.grayDark,secondary2:de.grayLight,gray:de.gray,green:de.green,yellow:de.yellow,red:de.red};var S={red:de.red,yellow:de.yellow,green:de.green,blue:de.blue,magenta:de.magenta,cyan:de.cyan},gt={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 oc=e=>e.props.tags??[],ic=e=>e.props.assignees??[],zr=e=>oc(e).map(t=>b.getTag(t)).filter(t=>!!t),Gr=e=>ic(e).map(t=>b.getContributor(t)).filter(t=>!!t),Un=()=>{let{breadCrumb:e,selectedNode:t}=x(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!W(n)?a("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",zr(n))},$n=()=>{let{breadCrumb:e,selectedNode:t}=x(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!W(n)?a("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",Gr(n))};var y={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",CONFIG:"config",EDIT:"edit",SYNC:"sync",EXPORT:"export",NONE:""};var sc=/^(\d+)(h|d|w|mo|y)$/,ac=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,dc=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let i=new Date(e,t-1,n,r,o);return i.getFullYear()===e&&i.getMonth()===t-1&&i.getDate()===n&&i.getHours()===r&&i.getMinutes()===o},cc=(e,t=new Date)=>{let n=e.match(sc);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let s=new Date(t);switch(o){case"h":return s.setHours(s.getHours()-i),s;case"d":return s.setDate(s.getDate()-i),s;case"w":return s.setDate(s.getDate()-i*7),s;case"mo":return s.setMonth(s.getMonth()-i),s;case"y":return s.setFullYear(s.getFullYear()-i),s;default:return null}},lc=e=>{let t=e.match(ac);if(!t)return null;let[,n,r,o,i,s]=t,c=Number(n),u=Number(r),m=Number(o),p=i?Number(i):0,v=s?Number(s):0;return dc({year:c,month:u,day:m,hour:p,minute:v})?new Date(c,u-1,m,p,v):null},Wn=e=>{let t=e.trim().toLowerCase();return cc(t)??lc(t)},Ui=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,uc=[{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}],$i=(e=uc)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let i=r;i<=o;i++)t.push(`${i}${n}`);return t};var mc=["BOARD","TICKET","SWIMLANE"],re={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs"},nt={TITLE:"title",DESCRIPTION:"description"},pc=[re.EDITOR,re.VIEW,re.USERNAME,re.AUTOSYNC,re.SYNC_DEBOUNCE_MS],gc=[nt.TITLE,nt.DESCRIPTION],Yr=[String(kt),"5000","15000","30000","60000"],ft=[y.EXIT,y.SYNC,y.HELP,y.EXPORT,y.CONFIG],_n=[y.NEW,y.EDIT,y.DELETE,y.MOVE],qr=[y.TAG,y.UNTAG,y.ASSIGN,y.UNASSIGN,y.CLOSE_ISSUE,y.RE_OPEN_ISSUE,y.EDIT],Wi=[y.FILTER,y.PEEK],fc={WORKSPACE:[...ft,..._n],BOARD:[...Wi,...ft,..._n],SWIMLANE:[...Wi,...ft,..._n],TICKET:[...ft,..._n,...qr],FIELD:[...ft,...qr],FIELD_LIST:[...ft,...qr],TEXT:[...ft]},vc=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],xc=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=tt();if(!r)return[y.HELP,y.CONFIG];if(!Fi())return[y.HELP,y.INIT];if(t)return[y.HELP,y.PEEK,y.EXPORT,y.CONFIG];let o=e?.context,i=o&&mc.includes(o);return[...new Set([...n,e].map(c=>c?.context).flatMap(c=>c?fc[c]:[]))].filter(c=>c===y.MOVE?!1:c===y.EDIT||c===y.DELETE?i:!0)},X=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=x())=>{let i=t.context??"WORKSPACE";return{[y.NONE]:xc({breadCrumb:o,readOnly:r,selectedNode:n}),[y.EXIT]:["confirm"],[y.EXPORT]:[],[y.SYNC]:[],[y.INIT]:[],[y.HELP]:[],[y.PEEK]:[...$i(),"now","prev","next"],[y.EDIT]:[...gc],[y.DELETE]:["confirm"],[y.RE_OPEN_ISSUE]:["confirm"],[y.CLOSE_ISSUE]:["confirm"],[y.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[y.FILTER]:["tag","assignee","description","title","clear"],[y.TAG]:[...new Set([...Object.keys(gt),...b.getExistingTags()])],[y.UNTAG]:[...Un()?.value?.map(({name:c})=>c)??[]],[y.UNASSIGN]:[...$n()?.value?.map(({name:c})=>c)??[]],[y.ASSIGN]:b.getExistingAssignees(),[y.NEW]:vc(i),[y.CONFIG]:[...pc]}[e]??[]};import Zi from"chalk";var _i=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import{decodeTime as Hi}from"ulid";var ji=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let i=Math.floor(t/o);if(i>=1)return`${i}${r} ago`}return"just now"},Ki=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())}`},Hn=e=>{try{return l("Decoded date",new Date(Hi(e)))}catch(t){return a("Decoding failed + "+t.message)}},Xr=e=>{if(!e?.id)return null;try{return Hi(e.id)}catch{return null}};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 Dt from"chalk";var yc=[0,0,0],Zr=.2,Qr={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Vi=(e,t,n)=>Math.max(t,Math.min(n,e)),Jr=(e,t,n)=>e+(t-e)*n,zi=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},hc=e=>e.toLowerCase().trim(),Cc=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,s=e/60,c=i*(1-Math.abs(s%2-1)),u=0,m=0,p=0;s>=0&&s<1?(u=i,m=c):s>=1&&s<2?(u=c,m=i):s>=2&&s<3?(m=i,p=c):s>=3&&s<4?(m=c,p=i):s>=4&&s<5?(u=c,p=i):(u=i,p=c);let v=o-i/2;return[Math.round((u+v)*255),Math.round((m+v)*255),Math.round((p+v)*255)]},Gi=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Ec=e=>{let t=e.replace("#","");return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]},qi=(e,t,n)=>{let r=Vi(n,0,1);return[Math.round(Jr(e[0],t[0],r)),Math.round(Jr(e[1],t[1],r)),Math.round(Jr(e[2],t[2],r))]},Sc=(e,t=Zr)=>qi(e,yc,t),Nc=(e,t=Zr)=>Gi(Sc(Ec(e),t)),bc=(e,t,n)=>qi(e,t,n),rn=e=>{let n=zi(e)%360,r=Cc(n,Qr.stringColor.saturation,Qr.stringColor.lightness);return Gi(r)},Ie=(e,t=gt)=>{let n=hc(e);return n&&t[n]?t[n]:rn(n)},Yi=(e,t=gt,n=Zr)=>Nc(Ie(e,t),n),Ic=e=>{let t=Qr.gradient.stops,n=Vi(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,i=Math.min(Math.floor(o),r-1),s=o-i;return bc(t[i],t[i+1],s)},jn=e=>zi(e.toLowerCase().trim())/4294967295,Xi=e=>{let t=jn(e);return Ic(t)},Rc=e=>{let[t,n,r]=Xi(e);return{normal:o=>Dt.bgRgb(t,n,r).black(o),cursor:o=>Dt.bgRgb(t,n,r).white.bold(o)}},eo=e=>{let[t,n,r]=Xi(e);return{fg:o=>Dt.rgb(t,n,r)(o),fgCursor:o=>Dt.rgb(t,n,r).inverse(o),bg:o=>Dt.bgRgb(t,n,r).black(o),bgCursor:o=>Dt.bgRgb(t,n,r).white.bold(o)}},Kn=e=>Rc(e).normal(` ${e} `);import Ji from"chalk";var J=e=>Ji.dim(e),ge=e=>Ji.hex(h.primary)(e),fe=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let s=o.trim();if(s.length<i)return"";let p=[...t.filter(Boolean).filter(v=>v.startsWith(s))].sort((v,C)=>jn(v)-jn(C)).slice(0,r).map(v=>Kn(v)).join(" ");return p?`${J(e)}${p}${J(n)}`:""};var vt={None:"none",Invalid:"invalid",Valid:"valid"};var Ac=["BOARD","TICKET","SWIMLANE"],Qi=()=>{let e=x().selectedNode;return e?.context?Ac.includes(e.context)?j():F({message:J("Command not available in this context")}):F({message:J("Missing target context")})},Q="<ENTER> to confirm",j=(e="",t=[])=>({message:J(e),validity:vt.Valid,completionWordList:t}),F=({message:e,completionWordList:t=[]})=>({validity:vt.Invalid,message:e,completionWordList:t}),zn=e=>e.length===0,Vn=e=>` ${Zi.dim.bgHex(Yi(e))(` ${e} `)} `,to=({modifier:e})=>{let t="confirm";return e===t?j(Q):F({message:zn(e)?J("if you are certain, enter ")+Kn(t):"",completionWordList:[t]})},Tc=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?F({message:J(n)}):j():F({message:zn(r)?t:"",completionWordList:[...e]}),on=({hint:e})=>({modifier:t,inputString:n})=>zn(t)&&zn(n)?F({message:e,completionWordList:[]}):j(Q),wc=({modifier:e,inputString:t})=>{let n=X(y.CONFIG);if(!n.includes(e))return F({message:fe({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case re.EDITOR:{let r=[..._i];return t.trim()?r.includes(t.trim())?j(Q):F({message:fe({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):F({message:fe({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case re.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?j(Q):F({message:fe({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case re.USERNAME:return t.trim()?j(Q):F({message:ge("Enter a user name. Saved in ")+Zi.bgBlack("~/.epiq-global/config.json")});case re.AUTOSYNC:{let r=["yes","no"],o=$().autoSync;if(!r.includes(t.trim())){let i=Oi(o);return F({message:fe({prefix:`should auto-sync (recommended)${i!==null?", currently: "+i:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return j(Q)}case re.SYNC_DEBOUNCE_MS:{let r=$().autoSyncIntervalMs,o=Pi(t);if(!t.trim()||o===null||o<kt){let i=fe({prefix:" examples: ",wordList:Yr,minLengthForHints:0,inputString:t});return F({message:ge(`provide duration above ${kt}ms. current duration: ${r}ms.`)+i,completionWordList:Yr})}return j(Q)}default:return F({message:ge("Unknown config option"),completionWordList:n})}},Mc=({modifier:e})=>{let t=X(y.EDIT);if(!t.includes(e)){let i=fe({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return F({message:i||ge("Unknown edit option"),completionWordList:t})}let{breadCrumb:n,selectedNode:r}=x();if(!be([...n,r],"TICKET"))return F({message:ge("Command not available in this context")});switch(e){case nt.TITLE:return j(Q);case nt.DESCRIPTION:let{preferredEditor:i}=$();return i?j(J("<ENTER> to edit in ")+i):F({message:"No editor selected"});default:return F({message:ge("Unknown edit option"),completionWordList:t})}},Pc={[y.EXPORT]:()=>j(Q+J(", and create export markdown file")),[y.PEEK]:e=>{let t=e.modifier;if(t==="now")return j(Q);let n={message:J("historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD")};if(t==="prev"||t==="next")return j(Q);let r=Wn(t);if(!t||!r)return F(n);let o=be(x().breadCrumb,"BOARD");if(d(o))return F({message:ge("Command is not applicable in this context")});let i=Hn(o.value.id);return d(i)?F({message:ge("Unable to peek: board id is not a valid ULID")}):Ui({date:r,horizonDate:i.value})?j(Q):F({message:ge(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[y.EXIT]:()=>j(Q+J(" and exit the application")),[y.INIT]:()=>j(Q),[y.PALETTE]:()=>j(Q),[y.FILTER]:e=>{if(e.modifier==="clear")return j();let t=i=>X(y.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return F({message:fe({wordList:X(y.FILTER),inputString:e.inputString}),completionWordList:X(y.FILTER)});let n=Object.values(x().tags).map(i=>i.name),r=Object.values(x().contributors).map(i=>i.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?F({message:fe({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):j():F({message:fe({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[y.NONE]:e=>{let t=X(y.NONE);return F({message:fe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[y.NEW]:e=>Tc({list:X(y.NEW),hint:fe({wordList:X(y.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[y.HELP]:()=>j(Q),[y.EDIT]:Mc,[y.CONFIG]:wc,[y.DELETE]:e=>{let t=Qi();return t.validity==="invalid"?t:to(e)},[y.CLOSE_ISSUE]:e=>to(e),[y.RE_OPEN_ISSUE]:e=>to(e),[y.MOVE]:e=>{let t=Qi();return t.validity==="invalid"?t:on({hint:fe({prefix:"hey hacker! These commands are blocked for you... ",wordList:X(y.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[y.TAG]:e=>{let n=b.getExistingTags().slice(0,10).map(Vn).join("");return on({hint:n.length?J("create tag or reuse:")+n+J(""):J("create tag ...")})(e)},[y.UNTAG]:e=>{let t=Un();if(d(t))return F({message:ge("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Vn).slice(0,10);return n.length?on({hint:J(" ... ")+n.join("")})(e):F({message:ge("Issue has no tags"),completionWordList:[]})},[y.ASSIGN]:e=>{let t=b.getExistingAssignees().map(Vn).slice(0,10);return on({hint:J("assignees... ")+t.join("")})(e)},[y.UNASSIGN]:e=>{let t=$n();if(d(t))return F({message:ge("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Vn).slice(0,10);return n.length?on({hint:J("remove assignee... ")+n.join("")})(e):F({message:ge("Issue has no assignees"),completionWordList:[]})},[y.SYNC]:()=>j(Q)},es=Object.fromEntries(Object.entries(Pc).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var ts=["frontend","backend","infrastructure","architecture","integration","configuration","implementation","application","deployment","environment","framework","platform","service","component","module","gateway","pipeline","containerization","orchestrator","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","reproducibility","reproduction","investigation","triage","workaround","mitigation","remediation","optimization","stabilization","refinement","failure","outage","blocking","criticality","severity","escalation","diagnostics","analysis","resolution","corruption","inconsistency","validation","verification","authorization","authentication","confidentiality","availability","accessibility","reliability","compliance","governance","encryption","decryption","integrity","auditing","traceability","accountability","protection","privileges","permissions","dependency","orchestration","provisioning","synchronization","compatibility","incompatibility","interoperability","observability","instrumentation","telemetry","loadbalancing","discovery","registration","scheduling","coordination","distribution","isolation","virtualization","serialization","deserialization","initialization","instantiation","propagation","aggregation","consolidation","normalization","standardization","transformation","reconciliation","correlation","processing","indexing","partitioning","enrichment","validation","filtering","streaming","batching","concurrency","parallelism","contention","deadlock","throttling","ratelimiting","backpressure","fragmentation","saturation","exhaustion","partitioning","replication","redundancy","failover","deprecation","obsolescence","starvation","overload","underutilization","latency","throughput","refactoring","modularization","encapsulation","abstraction","extensibility","configurability","maintainability","recoverability","sustainability","readability","testability","debuggability","reusability","simplicity","consistency","performance","functionality","requirement","recommendation","improvement","enhancement","clarification","documentation","description","acceptance","criteria","estimation","prioritization","dependency","deliverable","milestone","iteration"];var ns=e=>Object.values(y).includes(e),rs=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:s,validity:c,completionWordList:u}=es[n].validate(n,r,i),m=o==="command"||o==="modifier"?X(n):ts,{mode:p}=x(),v=p===g.COMMAND_LINE?s??"":"",C=[...u,...m];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:v,autoCompletion:t?Mi(e,C):{hint:"",hints:[],remainder:"",overlap:0}}};var os=e=>{let t=e.trimStart(),n=Lc(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),s=Dc(e),c=ns(r)?r:null,u=c!==null,m=r!=="",p=c?X(c)??[]:[],v=c&&p.includes(o)?o:"",C="word";n.length===0||n.length===1&&!i?C="command":(n.length===1&&i||n.length===2&&!i)&&(C="modifier");let E=i?"":s,I=kc(t,c,v);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:s,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:i,modifier:v,target:C,inputToMatch:E,inputString:I}},kc=(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},Lc=e=>e.trim()?e.trim().split(/\s+/):[],Dc=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as Fc}from"react";var Ft=e=>e===no||e===":",no=" ",ce={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:vt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},ro=new Set,is=()=>{for(let e of ro)e()},oo=e=>(ro.add(e),()=>ro.delete(e)),He=e=>{let n=e(ce),r=os(n.value),o=n.cursorPosition===n.value.length;ce={...n,commandMeta:rs(r,o)},is()},sn=({message:e,status:t})=>{let n=structuredClone(ce);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,ce=n,is(),l(e,null)},io=e=>{He(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},so=e=>{He(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Ft(n[o-1]);)o--;for(;o>0&&!Ft(n[o-1]);)o--}else{for(;o<n.length&&!Ft(n[o]);)o++;for(;o<n.length&&Ft(n[o]);)o++}return{...t,cursorPosition:o}})},ss=()=>{He(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}})},as=()=>{He(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Ft(t[r-1]);)r--;for(;r>0&&!Ft(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},_=e=>{He(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),i=e(r,t.commandMeta.autoCompletion),s=i+o,c=Math.max(0,Math.min(i.length,s.length));return{...t,value:s,cursorPosition:c,commandIsPending:!1}})},ds=()=>{He(e=>({...e,commandIsPending:!0}))},cs=({addToHistory:e=!0})=>{He(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),Oc()},ls=()=>{He(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}})},us=()=>{He(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Oc=()=>_(()=>""),V=()=>ce,ms=()=>Fc(oo,V,V),ps=()=>{let[e,...t]=ce.value.split(no);return t.join(no).trim()};var gs=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",fs=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",vs=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",xs=(e,t)=>{if(fs(e,e.sequence))return f.MoveCursorLeftOfWord;if(vs(e,e.sequence))return f.MoveCursorRightOfWord;if(gs(e,e.sequence))return f.EraseInputWord;switch(e.name){case"tab":return f.AutoCompleteCommand;case"up":return f.GetLastCommandFromHistory;case"down":return f.GetNextCommandFromHistory;case"left":return f.MoveCursorLeft;case"right":return f.MoveCursorRight;case"return":return f.Confirm;case"backspace":return t?f.EraseInput:f.ExitCommandLine;case"escape":return f.ExitCommandLine;default:return f.CaptureInput}},ys=(e,t)=>{if(fs(e,e.sequence))return f.MoveCursorLeftOfWord;if(vs(e,e.sequence))return f.MoveCursorRightOfWord;if(gs(e,e.sequence))return f.EraseInputWord;switch(e.name){case"tab":return f.AutoCompleteCommand;case"up":return f.NavPreviousItem;case"down":return f.NavNextItem;case"left":return f.MoveCursorLeft;case"right":return f.MoveCursorRight;case"return":return f.Confirm;case"backspace":return t?f.EraseInput:f.ExitCommandLine;case"escape":return f.ExitCommandLine;default:return f.CaptureInput}};var f={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",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function Bc(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function Uc(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function $c(e,t,n){let r=x().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 hs(e,t){let n=V();if(e.sequence==="?"&&n.value==="")return f.InitCommandPalette;if(e.sequence===":"&&n.value==="")return f.InitCommandLine;if(t===g.MOVE)switch(e.name){case"m":case"return":return f.ConfirmMove}if(t===g.COMMAND_LINE)return xs(e,n.value);if(t===g.PALETTE)return ys(e,n.value);let r=Bc(e)||Uc(e);if(r)return Wc(r,t);if(e.ctrl&&e.name==="c")return f.Exit;switch(e.name){case"e":return f.Edit;case"n":return f.AddItem;case"m":return f.InitMove;case"d":return f.Delete;case"return":return f.Confirm;case"space":return f.Confirm;case"v":return $().viewMode==="wide"?f.SetViewDense:f.SetViewWide;case"q":case"escape":return f.Exit;default:return null}}function Wc(e,t){let n=t===g.MOVE?{prevItem:f.MovePreviousItem,nextItem:f.MoveNextItem,prevContainer:f.MoveToPreviousContainer,nextContainer:f.MoveToNextContainer}:{prevItem:f.NavPreviousItem,nextItem:f.NavNextItem,prevContainer:f.NavToPreviousContainer,nextContainer:f.NavToNextContainer};return $c(x().contextNode.childRenderAxis,e,n)}var Gn=e=>{let{context:t}=x().contextNode;if(!t)return w.None;switch(e){case y.EXIT:return w.Exit;case y.EXPORT:return w.Export;case y.INIT:return w.Init;case y.DELETE:return w.Delete;case y.EDIT:return w.Edit;case y.HELP:return w.ViewHelp;case y.RE_OPEN_ISSUE:return w.ReopenIssue;case y.CLOSE_ISSUE:return w.CloseIssue;case y.TAG:return w.TagTicket;case y.UNTAG:return w.UntagTicket;case y.ASSIGN:return w.AssignUserToTicket;case y.UNASSIGN:return w.UnassignUserFromTicket;case y.NEW:return w.NewItem;case y.FILTER:return w.Filter;case y.MOVE:return w.Move;case y.PEEK:return w.Peek;case y.CONFIG:return w.Config;case y.SYNC:return w.Sync;default:return w.None}},w={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",Sync:"sync",Export:"export"};import{ulid as xe}from"ulid";import Ms from"node:fs";import ml from"node:path";import pl from"react";import{Box as ll}from"ink";import Qn from"react";import{Box as lo,Text as Qc}from"ink";import De from"react";import{Text as Cs}from"ink";import Es,{useEffect as Ss,useState as _c}from"react";var Ns={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},ve=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Z(),r=Ns[n]??Ns.default,[o,i]=_c(0);if(Ss(()=>{i(0)},[r]),Ss(()=>{if(!e)return;let c=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return Es.createElement(Cs,null,t);let s=r[o]??r[0]??t;return Es.createElement(Cs,{color:h.accent,dimColor:o===1},s)};import{Box as ao,Text as Hc}from"ink";import qn from"react";var Ot=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,scrollByOne:o=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),s=Math.max(1,Math.ceil(r)),c=Math.max(1,Math.floor(i/s)),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,C=e.slice(p,v),E=e.length>c,I=i,k=E?Math.max(1,Math.floor(c/e.length*I)):I,R=Math.max(0,I-k),T=Math.max(1,e.length-c),O=E?Math.floor(p/T*R):0;return qn.createElement(ao,{flexDirection:"row",height:i,width:"100%"},qn.createElement(ao,{flexDirection:"column",flexGrow:1,height:i},C),qn.createElement(ao,{flexDirection:"column",width:1,height:I},Array.from({length:I}).map((te,se)=>qn.createElement(Hc,{key:se,color:E&&se>=O&&se<O+k?h.accent:h.secondary},E?"\u2502":" "))))};import{Box as Yn,Text as Yc}from"ink";import xt from"react";import{Text as jc}from"ink";import Kc from"react";var Vc=e=>e.toLowerCase().trim(),zc=(e,t=gt)=>{let n=Vc(e);return t[n]?t[n]:rn(n)},Bt=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return Kc.createElement(jc,{underline:t,color:zc(n.name)},"@"+n.name)};import{Text as Gc}from"ink";import qc from"react";var Ut=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return qc.createElement(Gc,{underline:t,backgroundColor:Ie(n.name),color:h.primary}," "+n.name+" ")};var bs=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=Fn(bi(t.title),r),i=zr(t),s=Gr(t);return xt.createElement(Yn,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?h.accent:h.secondary,justifyContent:"space-between"},xt.createElement(Yn,{borderBottom:!0},xt.createElement(Yn,{paddingLeft:1,flexDirection:"column"},xt.createElement(Yc,{color:h.primary},o))),xt.createElement(Yn,{flexDirection:"row",paddingLeft:1},i.map(c=>xt.createElement(Ut,{key:c.id,id:c.id})),s.map(c=>xt.createElement(Bt,{key:c.id,id:c.id}))))};import Xc from"chalk";import{Box as an,Text as co}from"ink";import je from"react";var Jc=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Is=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=(t.props.tags??[]).map(E=>b.getTag(E)).filter(E=>!!E),s=(t.props.assignees??[]).map(E=>b.getContributor(E)).filter(E=>!!E),c=1,u=i.length*(1+c),m=s.length*(2+c),p=i.map(E=>je.createElement(an,{key:E.id,paddingRight:c},je.createElement(co,{color:Ie(E.name)},"\u25A0"))),v=s.map(E=>je.createElement(an,{key:E.id,paddingRight:c},je.createElement(co,{color:rn(E.name)},"@"+E.name.at(0)))),C=n?h.accent:o===g.MOVE?h.secondary:h.primary;return je.createElement(an,{borderBottom:!0,justifyContent:"space-between"},je.createElement(an,null,je.createElement(ve,{isSelected:n,placeholder:Xc.dim.gray(r+1+" ")}),je.createElement(co,{wrap:"truncate",color:C},Jc(t.title,e-u-m-14))),je.createElement(an,null,p,v))};import Zc from"chalk";var el=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:s,mode:c})=>{let{renderedChildrenIndex:u}=Z(),m=u[e.id]??[],p=`${e.title} ${Zc.hex(h.secondary2).dim("("+m.length+")")}`,v=3,C=o?1:4,E=r-v-(o?2:1),I=De.createElement(lo,{borderStyle:"round",borderColor:h.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},De.createElement(ve,{isSelected:t}),De.createElement(Qc,{bold:!0,color:t?h.accent:h.primary},p," ",e.readonly?"\u{1F512}":"")),k=(R,T)=>{let O=i&&s===T;return o?De.createElement(Is,{key:R.id,index:T,width:n,ticket:R,isSelected:O,mode:c}):De.createElement(bs,{key:R.id,width:n,ticket:R,isSelected:O})};return De.createElement(lo,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?h.accent:h.secondary,paddingRight:1,paddingLeft:1,height:r},I,De.createElement(lo,{padding:o?1:0},m.length>0&&De.createElement(Ot,{selectedIndex:s,height:E,itemHeight:C},m.map(k)),De.createElement(ve,{isSelected:i&&s===-1})))},Rs=De.memo(el);import{Box as po,Text as al}from"ink";import ot,{useMemo as Ts}from"react";import{decodeTime as tl,encodeTime as nl}from"ulid";var rl="0123456789ABCDEFGHJKMNPQRSTVWXYZ",ol=e=>{let t=2166136261;for(let o of e)t^=o.charCodeAt(0),t=Math.imul(t,16777619);let n=BigInt(t>>>0),r="";for(let o=0;o<16;o++)n=n*1103515245n+12345n&0xffffffffn,r+=rl[Number(n%32n)];return r},rt=(e,t)=>{let n=tl(e);return nl(n,10)+ol(`${e}:${t}`)};import{Box as Xn,Text as il}from"ink";import Ke from"react";var As=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Z(),{title:o}=t,i=t.parentNodeId?b.getNode(t.parentNodeId):void 0,s=i&&W(i)?o===Y.ASSIGNEES?i.props.assignees??[]:o===Y.TAGS?i.props.tags??[]:[]:[];return Ke.createElement(Xn,{alignItems:"center",paddingTop:1},Ke.createElement(Xn,{minWidth:12},Ke.createElement(ve,{isSelected:n}),Ke.createElement(il,{color:n?h.accent:h.secondary2},o,":")),Ke.createElement(Xn,{flexDirection:"row",marginLeft:1,paddingRight:1},s.map((c,u)=>{let m=r.id===t.id&&u===e;return Ke.createElement(Xn,{key:`${o}-${c}`,paddingRight:2,minHeight:1},Ke.createElement(ve,{isSelected:m}),o===Y.ASSIGNEES?Ke.createElement(Bt,{isSelected:m,id:c}):o===Y.TAGS?Ke.createElement(Ut,{isSelected:m,id:c}):null)})))};import{Box as Jn,Text as uo}from"ink";import Ve,{useEffect as sl}from"react";var oe={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:A.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:A.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:A.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:i="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:A.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:A.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:A.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:i=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:A.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[],isVirtual:s})};var mo=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:s,contextNode:c}=Z(),u=C=>String(C).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];sl(()=>{let C=[];return m.forEach((E,I)=>{let k=we(BigInt(I+1));if(!ne(k))return;let R=oe.text({id:`${e}-${I}`,name:`Line ${I+1}`,parentNodeId:e,rank:k.value,props:{value:E},readonly:!0,isVirtual:!0}),T=b.createNode(R);ne(T)&&C.push(T.value.id)}),()=>C.forEach(b.deleteNode)},[e,n]);let p="\u2029",v=m.map((C,E)=>{let I=c.id===e&&s===E;return Ve.createElement(Jn,{key:`${e}-${E}`},Ve.createElement(uo,{color:I?h.primary:h.secondary2,dimColor:!I},`${E+1} `.padStart(5,"\xA0")),Ve.createElement(uo,{backgroundColor:I?"gray":""},u(C.length?Fn(C,i-10):p)))});return Ve.createElement(Jn,{flexDirection:"column",paddingTop:1},Ve.createElement(Jn,null,Ve.createElement(ve,{isSelected:o}),Ve.createElement(uo,{color:o?h.accent:h.secondary2},t)),Ve.createElement(Jn,{flexDirection:"row",borderStyle:"round",borderColor:h.secondary,paddingLeft:1,marginLeft:1},Ve.createElement(Ot,{scrollByOne:!0,children:v,height:r-2,selectedIndex:s,itemHeight:1})))};var dl=e=>rt(e,"description"),cl=e=>rt(e,"history"),ws=({ticket:e,height:t})=>{let{selectedIndex:n,contextNode:r}=Z(),o=process.stdout.columns||120,i=Ts(()=>dl(e.id),[e.id]),s=Ts(()=>cl(e.id),[e.id]),c=r.id===e.id,u=r.id===s||r.parentNodeId===s,m=B(e.id);if(u){let R=b.getNode(s),T=R&&Xe(R)?R.props.value??"":"",te=t-3;return ot.createElement(po,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R?ot.createElement(mo,{id:R.id,label:"Event log",text:T,selected:!1,maxWidth:o,height:te}):null)}let p=m.reduce((R,T)=>qt(T)||T.id===s?R+1:R,0),v=2,C=3,E=p,I=t-C-E-v,k=(R,T)=>R.id===i?ot.createElement(mo,{key:R.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:T,maxWidth:o,height:I}):qt(R)?ot.createElement(As,{key:R.id,parent:R,selected:T,selectedIndex:n}):R.id===s?ot.createElement(po,{key:R.id,paddingTop:1},ot.createElement(ve,{isSelected:T}),ot.createElement(al,{backgroundColor:h.secondary,color:T?h.accent:h.primary}," History \u203A\u203A ")):null;return ot.createElement(po,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((R,T)=>k(R,c&&n===T)))};var ul=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:s,width:c})=>{let u=t.context,m=u===A.TICKET||u===A.FIELD_LIST||u===A.FIELD,p=u===A.BOARD||u===A.SWIMLANE,v=u===A.TICKET?t:r.find(R=>R.context===A.TICKET),C=Math.floor(c/3),E=Math.floor(c/Math.max(e.length,1)),I=Math.min(E,C),k=i==="dense";return Qn.createElement(ll,{flexDirection:"row",height:s},p&&e.map((R,T)=>{let O=t.id===R.id,te=O?n:-1,se=t.context===A.BOARD&&n===T;return Qn.createElement(Rs,{key:R.id,height:s,width:I,swimlane:R,isSelected:se,isDense:k,isFocused:O,listSelectedIndex:te,mode:o})}),m&&v&&Qn.createElement(ws,{height:s,ticket:v}))},Zn=Qn.memo(ul);import{render as gl}from"ink";import{Writable as fl}from"node:stream";var dn=e=>String(e).padStart(2,"0"),vl=e=>{let t=e.getUTCFullYear(),n=dn(e.getUTCMonth()+1),r=dn(e.getUTCDate()),o=dn(e.getUTCHours()),i=dn(e.getUTCMinutes()),s=dn(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${s}`},xl=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",yl=async(e,{width:t,height:n})=>{let r="",o=new fl({write(s,c,u){let m=hl(s.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=gl(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(s=>setTimeout(s,0)),i.unmount(),r},hl=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Ps=async()=>{let{viewMode:e}=$(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:i}=x(),s=r.find(T=>T.context==="BOARD");if(!s)return a("No board found to export");let c=120,u=40,m=await yl(pl.createElement(Zn,{height:u,width:c,swimlanes:(i[s.id]??[]).filter(T=>T!==void 0&&At(T)),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=wt(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let v=new Date,C=vl(v),E=`board_${xl(s.title)}_${C}.md`,I=Si(p.value);Ms.mkdirSync(I,{recursive:!0});let k=ml.join(I,E),R=`# Board - ${s.title}
|
|
23
23
|
Date: ${v.toISOString()}
|
|
24
24
|
|
|
25
25
|
\`\`\`text
|
|
26
26
|
${m}
|
|
27
27
|
\`\`\`
|
|
28
|
-
`;return
|
|
29
|
-
`),
|
|
30
|
-
`)){let i=o.trim();if(!i)continue;let
|
|
31
|
-
`,"utf8"),
|
|
32
|
-
`).map(u=>u.trim()),i=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(i.length===0)return
|
|
28
|
+
`;return Ms.writeFileSync(k,R,"utf8"),l("Exported board layout",k)};var M={exit(){process.exit(0)},enterChildNode(){let e=x(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=U(t.id)[n];!r||t.context==="FIELD"||M.navigate({contextNode:r,selectedIndex:B(r.id).length?0:-1})},enterParentNode(){let{contextNode:e,nodes:t}=x();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=B(n.id),o=r.findIndex(({id:s})=>s===e.id),i=r.length===0?-1:o>=0?o:0;M.navigate({contextNode:n,selectedIndex:i})},navigateToNextItem:()=>ks(1),navigateToPreviousItem:()=>ks(-1),navigateToNextContainer:()=>Ls(1),navigateToPreviousContainer:()=>Ls(-1),navigate:({contextNode:e,selectedIndex:t})=>{N({contextNodeId:e.id,selectedIndex:t})}},ks=e=>{let{selectedIndex:t,contextNode:n}=x(),r=B(n.id).length;if(r===0)return;let i=(Math.max(0,t)+e+r)%r;M.navigate({selectedIndex:i,contextNode:n})},Ls=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=x();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let i=B(o.id),s=i.findIndex(C=>C.id===t.id);if(s<0)return;let c=i.at(s+e)??i.at(0);if(!c)return;let u=B(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})};import Al from"node:os";import Bs from"node:path";import{z as yt}from"zod";import{accessSync as Cl,copyFileSync as El,existsSync as er,mkdirSync as Ds,readdirSync as Fs,readFileSync as Sl,renameSync as Nl,rmSync as bl,statSync as Os,unlinkSync as Il,writeFileSync as Rl}from"node:fs";import $t from"node:path";var he={writeToFile:(e,t)=>{try{let n=$t.dirname(e);er(n)||Ds(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Rl(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Sl(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=he.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 er(e)&&Os(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Cl(e),!0}catch{return!1}},mkDir:e=>Ds(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=$t.parse(t);for(;;){let r=$t.join(t,e);try{if(er(r)&&Os(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=$t.dirname(t)}return null},readFirstJSON(e){try{if(!he.dirExists(e))return null;let t=Fs(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=$t.join(e,t);return he.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return he.dirExists(e)?Fs(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Il(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{bl(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir($t.dirname(t)),!n?.overwrite&&er(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Nl(e,t)}catch(r){if(r?.code==="EXDEV"){El(e,t),this.rmFile(e);return}throw r}}};var Tl={userId:"",userName:"",preferredEditor:"",autoSync:!1},Us=yt.object({preferredEditor:yt.string().optional(),userName:yt.string().optional(),userId:yt.string().optional(),autoSync:yt.boolean().nullable().optional(),autoSyncDebounceMs:yt.number().optional(),viewMode:yt.enum(["dense","wide"]).optional()}),wl="config.json",$s=()=>Bs.join(Al.homedir(),Ne),go=()=>Bs.join($s(),wl),fo=()=>{try{return he.mkDir($s()),l(`Ensured ~/${Ne} exists`,null)}catch{return a(`Unable to create ~/${Ne}`)}},Ml=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${Ne}/config.json JSON`)}let n=Us.safeParse(t??{});return n.success?l("Parsed config",n.data):a(`Invalid ~/${Ne}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Ws=()=>{let e=fo();if(d(e))return a(e.message);let t=go(),n=he.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Ml(n)},_s=e=>{let t=fo();if(d(t))return a(t.message);let n=Us.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=go();try{return he.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
29
|
+
`),l("Config written",null)}catch{return a(`Unable to write ~/${Ne}/config.json`)}},ht=e=>{let t=Ws();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return _s(n)},Hs=()=>{let e=go(),t=fo();if(d(t))return a(`Unable to create ~/${Ne}`);if(!(he.readFile(e)!==null)){let m=_s(Tl);if(d(m))throw new Error(`Unable to create ~/${Ne}/config.json`)}let r=Ws();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:s,autoSync:c,autoSyncDebounceMs:u}=r.value;return!i||!s?a(`User name or ID not configured in ~/${Ne}/config.json`):l("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:s,autoSync:c??!1,autoSyncIntervalMs:u??1e4,viewMode:"dense"})};import Wl from"node:fs";import _l from"node:path";import{decodeTime as Hl,monotonicFactory as jl}from"ulid";import{z as cn}from"zod";import tr from"node:fs";import xo from"node:path";import{decodeTime as Pl}from"ulid";import{z as vo}from"zod";var kl=vo.object({userId:vo.string().min(1).default("unknown"),userName:vo.string().min(1).default("unknown")}),Ll=e=>{let[t,n]=xo.basename(e,".jsonl").split("."),r=kl.safeParse({userId:t,userName:n});return r.success?l("Parsed event file actor",r.data):a(`Invalid event file name ${xo.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Dl=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])},Fl=(e,t)=>t in e,Ol=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Bl=e=>{let{userId:t,userName:n,...r}=e,o=Dl(r);if(d(o))return a(o.message);let i=o.value,s=e.id?.[0];return s?Fl(r,i)?l("Decoded persisted event",Ol({id:s,action:i,payload:r[i],userId:t,userName:n})):a(`Persisted event is missing payload for action: ${i}`):a("Persisted event is missing id")},Ul=e=>{if(!tr.existsSync(e))return l("Event file missing",[]);let t=Ll(e);if(d(t))return a(t.message);let n=tr.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
|
|
30
|
+
`)){let i=o.trim();if(!i)continue;let s;try{s=JSON.parse(i)}catch{return a(`Failed to parse event JSON from ${e}: ${i}`)}let c=yo(s);if(d(c))return a(`${c.message} in ${e}: ${i}`);r.push({...c.value,userId:t.value.userId,userName:t.value.userName})}return l("Parsed persisted events file",r)};function js(e){let t=tn(e);if(!tr.existsSync(t))return l("No events found",[]);let n=tr.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>xo.join(t,o)),r=[];for(let o of n){let i=Ul(o);if(d(i))return a(i.message);r.push(...i.value)}return l("All events loaded",$l(r))}function Wt(e){let t=js(e);if(d(t))return a(t.message);let n=[];for(let r of t.value){let o=Bl(r);if(d(o))return a(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);n.push(o.value)}return l("Loaded merged events",n)}function Ks(e=process.cwd()){let t=js(e);return d(t)?a(t.message):l("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var $l=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 C=n.get(v)??[];C.push(m),n.set(v,C)}for(let m of n.values())m.sort((p,v)=>p.id[0].localeCompare(v.id[0]));let r=[],o=new Set,i=m=>{let p=m.id[0];if(o.has(p))return;r.push(m),o.add(p);let v=n.get(p)??[];for(let C of v)i(C)},s=n.get(null)??[];for(let m of s)i(m);let c=e.filter(m=>{let p=m.id[0],v=m.id[1]??null;return!o.has(p)&&v!==null&&!t.has(v)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of c)i(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)i(m);return r},Vs=(e,t)=>{let n=e.findIndex(r=>{try{return Pl(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var zs=e=>({action:e.action,payload:e.payload});var qs=1,Gs=jl(),Kl=cn.tuple([cn.string().min(1),cn.string().min(1).nullable()]),Vl=cn.looseObject({v:cn.literal(qs),id:Kl}),yo=e=>{let t=Vl.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(", ")}`)},nr=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",z=()=>{let{userName:e,userId:t}=$();return e?t?e.trim()?l("Successfully resolved actor ID",{userId:nr(t),userName:nr(e)}):a("Unable to resolve actor ID from settings or OS user info"):a("User ID not configured"):a("User name not configured")},ln=({userId:e,userName:t})=>`${nr(e)}.${nr(t)}.jsonl`,zl=(e,{userId:t,userName:n})=>{let r=ln({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return a(`Invalid event log file name: ${r}`);let i=_l.join(tn(e),r);return l("Successfully resolved event log path",i)},Gl=(e,t)=>{let n={[e.action]:e.payload,v:qs,id:t};return yo(n)};function rr({event:e,rootDir:t}){try{let n=Ni(t);if(d(n))return n;let r=zl(t,{userId:e.userId,userName:e.userName});if(d(r))return r;let o=Ks(t);if(d(o))return a(o.message);let i=o.value?Gs(Math.max(Date.now(),Hl(o.value)+1)):Gs(),s=Gl(zs(e),[i,o.value]);return d(s)?a(s.message):(Wl.appendFileSync(r.value,`${JSON.stringify(s.value)}
|
|
31
|
+
`,"utf8"),l("Event persisted",{path:r.value,entry:s.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return a(`Failed to persist event: ${r}`)}}var Ys=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id)return r.payload.parent}return null};var ql=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ze,or]=ql;import{ulid as eu}from"ulid";import{spawnSync as Yl}from"node:child_process";import Xl from"node:os";import Xs from"node:path";import{ulid as Jl}from"ulid";function Ql(){let{preferredEditor:e}=$(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Zl(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function Js(e){let t=Xs.join(Xl.tmpdir(),"epiq");he.mkDir(t);let n=Xs.join(t,Jl());he.writeToFile(n,e??"");let r=Ql();for(let o of r){let i=Zl(o,n),s=Yl(i,{stdio:"inherit",shell:!0});if(!s.error&&s.status===0){let c=he.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 Qs=async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let t=await Me();if(d(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=x(),i=be([...r,o],"TICKET");if(d(i))return a("Edit target must be an issue");let s=i.value;if(!W(s))return a("Edit target must be an issue");if(s.readonly)return a("Cannot edit readonly issue");let c=B(s.id).find(v=>v.title===Y.DESCRIPTION);if(!c)return a("No target found");if(c.readonly)return a("Cannot edit readonly field");let u=s.props.description??"";if(typeof u!="string")return a("Selected field is not editable text");let m=Js(u);if(d(m))return a("Failed to edit field");let p=m.value;return p===u?l("No changes made",null):Pe({id:eu(),action:"edit.description",payload:{id:s.id,md:p},...e.value},n)};import uu from"node:fs";import ia from"node:path";import ho from"node:fs";import tu from"node:path";var Zs=async e=>{let t=tu.join(e,".gitignore"),n=ho.existsSync(t)?ho.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
32
|
+
`).map(u=>u.trim()),i=r.filter(u=>!o.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(i.length===0)return l("Local epiq paths already ignored",!1);let c=["# [epiq]: local hydrated state is never committed",...i].join(`
|
|
33
33
|
`);return n=n.trimEnd()+`
|
|
34
34
|
|
|
35
|
-
${
|
|
36
|
-
`,
|
|
37
|
-
${n.message}`);let r=n.value.stdout.trim(),o=await
|
|
38
|
-
${o.message}`):
|
|
39
|
-
`+n.message);let r=n.value,o=r?await
|
|
40
|
-
`+o.message);let i=o.value;if(r&&i){let
|
|
41
|
-
${
|
|
42
|
-
`+
|
|
43
|
-
${
|
|
44
|
-
`),o=null;for(let i of r){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return
|
|
45
|
-
`+r.message);
|
|
46
|
-
${o.message}`):
|
|
47
|
-
${u.message}`)}if(i&&!
|
|
48
|
-
${u.message}`)}let
|
|
49
|
-
${u.message}`)}return
|
|
50
|
-
${o.message}`):
|
|
51
|
-
${
|
|
52
|
-
${u.message}`):
|
|
53
|
-
${o.message}`):
|
|
54
|
-
`+n.message):
|
|
55
|
-
${i.message}`):
|
|
35
|
+
${c}
|
|
36
|
+
`,ho.writeFileSync(t,n,"utf8"),le.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)};import _t from"node:fs";import un from"node:path";var ta=async e=>{if((await Se({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return l("Initial commit already exists",!1);le.info("Creating initial commit");let n=await K.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?a(n.message):l("Created initial commit",!0)},ea=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",nu=async e=>{let t=await wn(e);if(d(t))return a(t.message);let n=await li(e);return d(n)?a(n.message):l("Built sync commit message",`[epiq:sync:${ea(t.value)}:${ea(n.value)}]`)},Co=async({repoRoot:e,stateBranchName:t})=>{le.info(`Creating ${t}`);let n=await D({args:["commit-tree",xi,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return a(`Failed to create state branch commit
|
|
37
|
+
${n.message}`);let r=n.value.stdout.trim(),o=await D({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return d(o)?a(`Failed to create ${t}
|
|
38
|
+
${o.message}`):l("Created state branch",!0)},ru=async({repoRoot:e,stateBranchName:t})=>{let n=await Ur({repoRoot:e});if(d(n))return a(`Ensure local state branch failed
|
|
39
|
+
`+n.message);let r=n.value,o=r?await Qt({repoRoot:e,branch:t}):l("No remote, no remote state branch",!1);if(d(o))return a(`Ensure local state branch failed
|
|
40
|
+
`+o.message);let i=o.value;if(r&&i){let c=await K.fetch({cwd:e,remote:pe,branch:t});if(d(c))return a(`Failed to fetch ${t} from remote
|
|
41
|
+
${c.message}`)}let s=await Tn({repoRoot:e,branch:t});if(d(s))return a(`Ensure local state branch failed
|
|
42
|
+
`+s.message);if(s.value)return l("Local state branch already exists",!1);if(i){let c=await D({args:["branch","--track",t,`${pe}/${t}`],cwd:e});return d(c)?a(`Failed to create local ${t} from remote
|
|
43
|
+
${c.message}`):l("Created local state branch from remote",!0)}return Co({repoRoot:e,stateBranchName:t})},ou=async({repoRoot:e,branch:t})=>{let n=await D({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=n.value.stdout.split(`
|
|
44
|
+
`),o=null;for(let i of r){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return l("Found worktree for branch",o)}return l("No worktree found for branch",null)},iu=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Zt(un.dirname(t));if(d(r))return a(`Failed to create state branch worktree
|
|
45
|
+
`+r.message);_t.existsSync(t)&&!_t.existsSync(un.join(t,".git"))&&(le.info("Removing broken state branch worktree path"),hi(t)),le.info("Creating state branch worktree");let o=await K.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(o)?a(`Failed to create state branch worktree
|
|
46
|
+
${o.message}`):l("Created state branch worktree",!0)},Eo=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await ou({repoRoot:e,branch:n});if(d(r))return a(r.message);let o=un.resolve(t),i=r.value?un.resolve(r.value):null;if(i&&i===o&&_t.existsSync(i))return l("State branch already checked out in expected worktree",!1);if(i&&i!==o){le.info("Moving state branch worktree to expected location");let u=await K.worktreeRemove({cwd:e,worktreeRoot:i});if(d(u))return a(`Failed to remove existing state branch worktree
|
|
47
|
+
${u.message}`)}if(i&&!_t.existsSync(i)){le.info("Pruning stale state branch worktree");let u=await K.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
|
|
48
|
+
${u.message}`)}let s=await ci({repoRoot:e,worktreeRoot:t});if(d(s))return a(s.message);let c=_t.existsSync(t);if(s.value&&c)return l("State branch worktree already exists",!1);if(s.value&&!c){le.info("Pruning missing registered state branch worktree");let u=await K.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
|
|
49
|
+
${u.message}`)}return iu({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},su=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await wn(e);if(d(n))return a(n.message);if(n.value===t)return l("State branch already checked out",!1);(await Se({cwd:e,args:["rebase","--abort"]})).exitCode===0&&le.info("Aborted stale state branch rebase");let o=await K.checkout({cwd:e,branch:t});return d(o)?a(`Failed to checkout ${t}
|
|
50
|
+
${o.message}`):l("Checked out state branch",!0)},au=async({repoRoot:e,stateBranchRoot:t})=>{let n=await $r(t);if(d(n))return a(n.message);if(n.value)return l("State branch upstream already configured",!1);let r=await Ur({repoRoot:t});if(d(r))return a(r.message);if(!r.value)return l("No remote available for state branch upstream",!1);let o=mt(e);if(d(o))return o;let i=o.value,s=await Qt({repoRoot:t,branch:i});if(d(s))return a(s.message);if(!s.value)return l("Remote state branch missing; upstream will be configured on first push",!1);le.info(`Configuring ${i} upstream`);let c=await K.fetch({cwd:t,remote:pe,branch:i});if(d(c))return a(`Failed to fetch ${i}
|
|
51
|
+
${c.message}`);let u=await K.setUpstream({cwd:t,branch:i,upstream:`${pe}/${i}`});return d(u)?a(`Failed to set state branch upstream
|
|
52
|
+
${u.message}`):l("Configured state branch upstream",!0)},ir=async({stateBranchRoot:e,eventFileName:t})=>{let n=pt(t),r=un.join(e,n);if(!_t.existsSync(r))return l("No event file to stage",void 0);let o=await K.stage({cwd:e,pathspec:[n]});return d(o)?a(`Failed to stage state branch event file
|
|
53
|
+
${o.message}`):l("Staged state branch event file",void 0)},na=async({repoRoot:e,stateBranchRoot:t})=>{let n=await nu(e);return d(n)?a(`Create state branch sync commit failed
|
|
54
|
+
`+n.message):Mt({cwd:t,message:n.value})},mn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await $r(t);if(d(n))return a(n.message);let r=mt(e);if(d(r))return r;let o=r.value,i=n.value?await K.push({cwd:t}):await K.push({cwd:t,remote:pe,branch:o,setUpstream:!0});return d(i)?a(`Failed during state branch push
|
|
55
|
+
${i.message}`):l("Pushed state branch",!0)},ra=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=mt(e);if(d(o))return o;let i=o.value,s=[kn(),await ru({repoRoot:e,stateBranchName:i}),await Eo({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await su({stateBranchRoot:t,stateBranchName:i}),await Ei(t),n?await au({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of s){if(d(c))return a(c.message);r=r||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import{monotonicFactory as du,ulid as Ge}from"ulid";var pn=du();function cu(){let e=et();if(d(e))return a("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(i=>i.context==="WORKSPACE");if(!n)throw new Error("No workspace found in event log");let[r]=B(n.id),[o]=r?B(r.id):[];if(o){let i=t.renderedChildrenIndex?.[o.id]??[];return l("Resolved boot nav target",{contextNode:o,selectedIndex:i.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 lu(){let e=cu();return d(e)?e:M.navigate(e.value)}function oa({userId:e,userName:t}){let n=pn(),r=pn(),o=pn(),i=pn(),s=pn(),c=me(void 0,void 0);if(d(c))return c;let u=me(void 0,void 0);if(d(u))return u;let m=me(u.value,void 0);if(d(m))return m;let p=me(void 0,void 0);if(d(p))return p;let v=me(p.value,void 0);if(d(v))return v;let C=me(v.value,void 0);if(d(C))return C;let E=me(void 0,void 0);return d(E)?E:l("Created default events",[{id:Ge(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:Ge(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Ge(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Ge(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"In progress",parent:r,rank:v.value}},{id:Ge(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"Done",parent:r,rank:C.value}},{id:Ge(),userId:e,userName:t,action:"add.board",payload:{id:or,name:"Closed",parent:n,rank:m.value}},{id:Ge(),userId:e,userName:t,action:"add.swimlane",payload:{id:ze,name:"Closed",parent:or,rank:E.value}},{id:Ge(),userId:e,userName:t,action:"lock.node",payload:{id:or}},{id:Ge(),userId:e,userName:t,action:"lock.node",payload:{id:ze}}])}function sr(e){if(!e.length){let r=oe.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=gn(r);return d(o)?o:(N({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=Ct(e).filter(d);return n.length>0?a(`Materializing failed:
|
|
56
56
|
${n.map(r=>r.message).join(`
|
|
57
|
-
`)}`):(
|
|
58
|
-
`));let ct=Qe();if(d(ct))return j(16,ct.message);let{rootNodeId:gd,nodes:vd}=ct.value,Ho=vd[gd];return Ho?(B.navigate({currentNode:Ho,selectedIndex:0}),N({hasProjectDefinition:!0,mode:f.DEFAULT}),c(Ee,null)):j(16,"Unable to resolve initialized root node")};import{ulid as zl}from"ulid";import{ulid as Kl}from"ulid";var Ys=null,rt=()=>structuredClone(Ys),mn=e=>{Ys=e},Xs=()=>{let{currentNode:e,selectedIndex:t}=h(),r=U(e.id)[t];return r?c("Resolved selected child",r):s("Target node not found")},vo=({id:e,parentId:t,position:n={at:"end"}})=>{let r=U(t).filter(o=>o.id!==e);return nr(r,n)},Js=({id:e,parentId:t,position:n={at:"end"}})=>{let r=z();if(d(r))return s("Unable to resolve user ID");let o=vo({parentId:t,id:e,position:n});return d(o)?o:c("Created pending move state",{id:Kl(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Qs=e=>{mn(e);let t=pn(e,!0);return d(t)?t:c("Node moved successfully",t.value)};function yo(e){let t=Xs();if(d(t))return t;let{currentNode:n,nodes:r}=h();if(!n.parentNodeId)return s("Missing parent node id");let o=r[n.parentNodeId];if(!o)return s("Missing parent node");let i=U(o.id),a=i.findIndex(({id:m})=>m===n.id);if(a<0)return s("Current node not found among siblings");let l=i[a+e];if(!l)return s("Missing sibling node");let u=Js({id:t.value.id,parentId:l.id,position:{at:"end"}});return d(u)?u:Qs(u.value)}function ho(e){let t=Xs();if(d(t))return t;let{currentNode:n,selectedIndex:r}=h(),i=U(n.id)[r+e];if(!i)return s("Missing sibling node");let a=Js({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(a)?a:Qs(a.value)}var Zs=()=>{let e=rt();if(!e)return s("No pending move state");let t=e.payload.id,n=e.payload.parent,r=h().nodes[n];if(!r)return s("Move parent not found");let o=U(n).findIndex(i=>i.id===t);return o===-1?s("Moved node not found among rendered children"):(B.navigate({currentNode:r,selectedIndex:o}),c("Synchronized navigation to moved node",null))},rr=(e,t="Moved preview")=>{if(d(e))return e;let n=Zs();return d(n)?n:(N({mode:f.MOVE}),c(t,null))},ea=async()=>{let e=z();if(d(e))return s("Unable to resolve user ID");let{modifier:t}=K().commandMeta,{currentNode:n,selectedIndex:r}=h(),o=U(n.id)[r];if(!o)return N({mode:f.DEFAULT}),s("No move target");if(t==="start"){if(o.readonly)return s("Target node is read-only");if(r===-1)return s("No item selected");if(!o.parentNodeId)return s("Target has no parent");let i=U(o.parentNodeId),a=i.findIndex(({id:v})=>v===o.id);if(a===-1)return s("Target not found among siblings");let l=i[a-1],u=i[a+1],m=u!=null?{at:"before",sibling:u.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},p=vo({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(mn({id:zl(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),N({mode:f.MOVE}),c("Move initialized",null))}if(t==="next")return rr(ho(1));if(t==="previous")return rr(ho(-1));if(t==="to-next")return rr(yo(1));if(t==="to-previous")return rr(yo(-1));if(t==="confirm"){let i=rt();if(!i)return s("No pending move to confirm");let a=await Te();if(d(a))return a;let l=Me(i,a.value);if(d(l))return l;let u=Zs();return d(u)?u:(mn(null),N({mode:f.DEFAULT}),c("Moved item",null))}return t==="cancel"?(mn(null),N({mode:f.DEFAULT}),c("Cancelling move",null)):s("Invalid move modifier")};import{ulid as or}from"ulid";import{monotonicFactory as Gl,ulid as ql}from"ulid";var Yl=Gl(),ta=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=Yl();return c("Created issue events",[{id:ql(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}}])};var na=async(e,t)=>{let n=z();if(d(n))return s("Unable to resolve user ID");let r=await Te();if(d(r))return r;let o=r.value;if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:i,currentNode:a,selectedIndex:l}=h(),u=m=>{let p=Me(m,o);if(d(p))return p;let v=S.getNode(p.value.result.id);if(!v)return s("Created node not found");if(!v.parentNodeId)return p;let C=S.getNode(v.parentNodeId);return C?(B.navigate({currentNode:C,selectedIndex:S.getSiblings(v.parentNodeId).findIndex(({id:E})=>E===v.id)}),p):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=h(),p=S.getNode(m);if(!p)return s("Workspace not found");let v=ir(p.id,n.value,o);return d(v)?v:u({id:or(),action:"add.board",payload:{id:or(),name:t.inputString,parent:p.id,rank:v.value},...n.value})}if(t.modifier==="swimlane"){let m=Se(i,"BOARD");if(d(m))return s("Unable to add swimlane in this context");let p=ir(m.value.id,n.value,o);return d(p)?p:u({id:or(),action:"add.swimlane",payload:{id:or(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=O(a.id)[l],p=a.context==="SWIMLANE"?a:a.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let D=Se(i,"SWIMLANE");return d(D)?null:D.value})();if(!p)return s("Unable to add issue in this context");let v=ir(p.id,n.value,o);if(d(v))return v;let C=ta({name:t.inputString,parent:p.id,rank:v.value,user:n.value});if(d(C))return C;let E=C.value,I=ra(E,o);if(I.some(D=>d(D)))return s("Issue create failed: "+I.filter(d).map(D=>D.message).filter(Boolean).join(", "));let P=I[0];if(!P||d(P))return s("Issue creation failed");let w=E.find(D=>D.action==="add.issue")?.payload.id;return w?(B.navigate({currentNode:p,selectedIndex:S.getSiblings(p.id).findIndex(({id:D})=>D===w)}),c("Issue created",null)):s("Unable to determine ticket id")}return c("Success",null)};var oa=async()=>{let e=Se(h().breadCrumb,"BOARD");if(d(e))return e;let t=Rt(process.cwd());if(d(t))throw new Error(t.message);let n=$t(t.value);if(d(n))return s(n.message);let r=n.value,{modifier:o}=K().commandMeta,i;if(o==="now"){let C=xo();if(d(C))return C;let E=yt(r);return E.some(d)?s(E.map(I=>I.message).join(", ")):(N({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}if(o==="prev"){let C=h().eventLog.at(-2),E=Vr(C);if(E===null)return s("No previous event to peek");i=E}else if(o==="next"){let C=h().unappliedEvents.at(0),E=Vr(C);if(E===null)return s("No next event to peek");i=E}else{let C=Bn(o);if(!C)return s("Invalid peek date");i=C.getTime()}let a=e.value.id,{appliedEvents:l,unappliedEvents:u}=Ls(r,i),m=xo();if(d(m))return m;let p=yt(l);if(p.some(d))return s(p.map(C=>C.message).join(", "));let v=h().nodes[a];return v?(B.navigate({currentNode:v,selectedIndex:0}),N({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),c("Peeking ",!0)):s("Board did not exist at peek date")};import Xl from"zod";var ia=()=>{let e=K().commandMeta.inputString,t=Xl.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return s("Auto sync duration must be a number of at least 3000 ms");let n=vt({autoSyncDebounceMs:t.data});return d(n)?n:(ye({autoSyncIntervalMs:t.data}),N({mode:f.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))};var sa=()=>{let e=K().commandMeta.inputString.trim();if(e!=="yes"&&e!=="no")return s("Invalid response");let t=Pi(e),n=vt({autoSync:t});return d(n)?n:(ye({autoSync:t}),N({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))};var aa=async()=>{_(()=>""),N({mode:f.DEFAULT});let e=Qe();if(d(e))return s(e.message);if(e.value.syncStatus.status==="syncing")return s("Sync already in progress");N({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Dn();return d(t)?(N({syncStatus:{msg:t.message,status:"failed"}}),t):(N({mode:f.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var da=e=>Object.values(h().tags).find(t=>t.name===e),ca=e=>Object.values(h().contributors).find(t=>t.name===e),sr=[{systemOnly:!0,intent:T.Move,description:"Internal move-state command",mode:f.COMMAND_LINE,action:ea},{intent:T.Delete,description:"Delete the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=h(),r=O(t.id)[n];return r?Ie({id:ve(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>N({mode:f.DEFAULT})},{intent:T.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:f.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=K().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(a=>X(y.FILTER).map(l=>l.split(n)[0]).includes(a))(r))return s("Invalid filter modifier");let i={target:r,operator:"=",value:t.trim()};return ue(a=>({...a,filters:e==="clear"?[]:[...a.filters,i],mode:f.DEFAULT})),c("Filter updated",null)}},{intent:T.ViewHelp,description:"Open the help screen",mode:f.COMMAND_LINE,action:()=>(N({mode:f.HELP}),c("Viewing help",null))},{intent:T.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=h(),r=O(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!W(r))return s("Cannot close in this context");let o=h().nodes[He];if(!o)return s("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return s("Issue is already closed");let i=await Te();if(d(i))return i;let a=i.value,l=Co(o.id,r.id,{at:"end"},e.value,a);if(d(l))return l;let u=await Ie({id:ve(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...e.value});return d(u)?u:c("Issue closed",null)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:T.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=h(),r=O(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):ot(r.id,"TICKET");if(d(o))return s("Cannot reopen in this context");let i=o.value,a=h().nodes[He];if(!a)return s("Unable to locate closed swimlane");if(i.parentNodeId!==a.id)return s("Issue is not closed");if(!W(i))return s("Target node is not issue");let l=Bs(i);if(!l)return s("Unable to resolve previous parent from issue history");if(l===a.id)return s("Previous parent resolves to closed swimlane");let u=h().nodes[l];if(!u)return s("Previous parent no longer exists");let m=await Te();if(d(m))return m;let p=m.value,v=Co(u.id,i.id,{at:"end"},e.value,p);if(d(v))return v;let C=await Ie({id:ve(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:v.value},...e.value});return d(C)?C:c("Issue reopened",null)},onSuccess:()=>N({mode:f.DEFAULT})},{intent:T.Init,description:"Initialize Epiq in the current git repository",mode:f.COMMAND_LINE,action:qs},{intent:T.NewItem,description:"Create a new board, swimlane, or issue",mode:f.COMMAND_LINE,action:na,onSuccess:()=>N({mode:f.DEFAULT})},{intent:T.Rename,description:"itle] Rename the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=h(),r=O(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=ts();return o?Ie({id:ve(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>N({mode:f.DEFAULT})},{intent:T.UntagTicket,description:"Remove a tag from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=K().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=da(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=h();if(!i)return s("Invalid untag target");let a=ot(i.id,"TICKET");if(d(a))return s("Unable to untag issue in this context");let l=a.value;return W(l)?(l.props.tags??[]).includes(o.id)?Ie({id:ve(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...e.value}):s("Issue is not tagged with that tag"):s("Target node is not issue")},onSuccess:()=>N({mode:f.DEFAULT})},{intent:T.TagTicket,description:"Add or create a tag on the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=K().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedNode:o}=h();if(!o)return s("Invalid tag target");let i=ot(o.id,"TICKET");if(d(i))return s("Unable to tag issue in this context");let a=i.value;if(!W(a))return s("Target node is not issue");let l=da(r),u;if(l)u=l.id;else{let p=ve(),v=await Ie({id:ve(),action:"create.tag",payload:{id:p,name:r},...e.value});if(d(v))return v;u=v.value.result.id}return(a.props.tags??[]).includes(u)?s("Already tagged with that tag"):Ie({id:ve(),action:"add.issue.tag",payload:{id:a.id,tag:u},...e.value})},onSuccess:()=>N({mode:f.DEFAULT})},{intent:T.AssignUserToTicket,description:"Assign a user to the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=K().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=h(),a=O(i.id)[o];if(!a)return s("Invalid assign target");let l=ot(a.id,"TICKET");if(d(l))return s("Unable to assign issue in this context");let u=l.value;if(!W(u))return s("Target node is not issue");let m=ca(r),p;if(m)p=m.id;else{let C=ve(),E=await Ie({id:ve(),action:"create.contributor",payload:{id:C,name:r},...e.value});if(d(E))return E;p=E.value.result.id}return(u.props.assignees??[]).includes(p)?s("Assignee already assigned"):Ie({id:ve(),action:"add.issue.assignee",payload:{id:u.id,assignee:p},...e.value})},onSuccess:()=>N({mode:f.DEFAULT})},{intent:T.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=z();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=K().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=ca(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=h();if(!i)return s("Invalid unassign target");let a=ot(i.id,"TICKET");if(d(a))return s("Unable to unassign in this context");let l=a.value;return W(l)?(l.props.assignees??[]).includes(o.id)?Ie({id:ve(),action:"remove.issue.assignee",payload:{id:l.id,assignee:o.id},...e.value}):s(`Issue is not assigned to "${r}"`):s("Target node is not issue")},onSuccess:()=>N({mode:f.DEFAULT})},{intent:T.Sync,description:"Pull, commit, and push Epiq state",mode:f.COMMAND_LINE,action:aa},{intent:T.Peek,description:"View board state at another point in time",mode:f.COMMAND_LINE,action:oa},{intent:T.Export,description:"Export the current board layout to markdown",mode:f.COMMAND_LINE,action:async()=>{let e=await xs();return d(e)?e:(N({mode:f.DEFAULT}),c("Export successful",!0))}},{intent:T.Exit,description:"Exit the application",mode:f.COMMAND_LINE,action:async()=>(B.exit(),c("Exit successful",!0))},{intent:T.Edit,description:"Edit title or description",mode:f.COMMAND_LINE,action:async(e,t)=>{if(t.modifier===et.DESCRIPTION)return Ws();if(t.modifier===et.TITLE){let n=z();if(d(n))return s("Unable to resolve user ID");let{currentNode:r,selectedIndex:o}=h(),i=O(r.id)[o];if(!i)return s("Missing node");if(i.readonly)return s("Cannot rename readonly node");let a=t.inputString.trim();return a?Ie({id:ve(),action:"edit.title",payload:{id:i.id,name:a},...n.value}):s("Provide a new name")}return s("Unknown edit command")},onSuccess:()=>N({mode:f.DEFAULT})},{intent:T.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 te.USERNAME:{let{userId:r,preferredEditor:o,userName:i}=$(),a=n||i,l=r??ve();if(!a||!l)return s("Unable to resolve user name or id");let u=vt({userName:a,userId:l,preferredEditor:o??""});return d(u)?u:(ye({userName:a,userId:l}),N({mode:f.DEFAULT}),c(`Username set to "${a}"`,null))}case te.EDITOR:{if(!n)return s("No editor provided");let r=vt({preferredEditor:n});return d(r)?r:(ye({preferredEditor:n}),N({mode:f.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case te.VIEW:return n!=="wide"&&n!=="dense"?s("Invalid view mode"):(ye({viewMode:n}),c(`View set to "${n}"`,null));case te.AUTOSYNC:return sa();case te.SYNC_DEBOUNCE_MS:return ia();default:return s("Unknown config command")}}}];var Jl=new Set(["peek","filter","view-help"]),Re=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=K();if(!t)return s("No command to confirm");if(!e&&n===pt.Invalid)return s("Invalid command");let i=jn(t);Xi();let{readOnly:a}=h();if(a&&!Jl.has(i))return nn({status:Ye.Fail,message:"Command not available in readonly state",value:null});let l=sr.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===i);if(!l)return nn({status:Ye.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return nn({status:Ye.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?nn(u):(Ji({addToHistory:!e}),l.onSuccess?.(),$().autoSync&&wi(),u)};var ar=[{intent:g.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(N({mode:f.COMMAND_LINE}),_(()=>"move cancel"),Re({isForceExecutedBySystem:!0}))},{intent:g.InitMove,mode:f.DEFAULT,description:"[m] move init/confirm",action:()=>(N({mode:f.COMMAND_LINE}),_(()=>"move start"),Re({isForceExecutedBySystem:!0}))},{intent:g.ConfirmMove,mode:f.MOVE,action:()=>(N({mode:f.COMMAND_LINE}),_(()=>"move confirm"),Re({isForceExecutedBySystem:!0}))}],dr=[{intent:g.MovePreviousItem,mode:f.MOVE,action:()=>rt()?(N({mode:f.COMMAND_LINE}),_(()=>"move previous"),Re({isForceExecutedBySystem:!0})):s("No pending move")},{intent:g.MoveNextItem,mode:f.MOVE,action:()=>rt()?(N({mode:f.COMMAND_LINE}),_(()=>"move next"),Re({isForceExecutedBySystem:!0})):s("No pending move")}],la=[{intent:g.MoveToNextContainer,mode:f.MOVE,action:()=>rt()?(N({mode:f.COMMAND_LINE}),_(()=>"move to-next"),Re({isForceExecutedBySystem:!0})):s("No pending move")},{intent:g.MoveToPreviousContainer,mode:f.MOVE,action:()=>rt()?(N({mode:f.COMMAND_LINE}),_(()=>"move to-previous"),Re({isForceExecutedBySystem:!0})):s("No pending move")}];var ua={[A.WORKSPACE]:[...ar,...dr],[A.BOARD]:[...ar,...dr],[A.SWIMLANE]:[...ar,...dr,...la],[A.TICKET]:[],[A.FIELD]:[],[A.FIELD_LIST]:[],[A.TEXT]:[]};var ma=e=>[{intent:g.NavPreviousItem,mode:e,description:"[arrows/hjkl] navigate",action:()=>(B.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:g.NavNextItem,mode:e,action:()=>(B.navigateToNextItem(),c("Navigating to next item",null))},{intent:g.NavToPreviousContainer,mode:e,action:()=>(B.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:g.NavToNextContainer,mode:e,action:()=>(B.navigateToNextContainer(),c("Navigating to next container",null))}],pa=[{intent:g.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(N({mode:f.COMMAND_LINE}),_(()=>`${y.NEW} `),c("Adding new item",null))},{intent:g.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(N({mode:f.COMMAND_LINE}),_(()=>`${y.DELETE} `),c("Deleting item",null))},{intent:g.InitCommandPalette,mode:f.DEFAULT,description:"[?] command palette",action:()=>(N({mode:f.PALETTE}),c("Opening command palette",null))},{intent:g.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(N({mode:f.COMMAND_LINE}),_(()=>""),c("Entering command line mode",null))},{intent:g.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,currentNode:t}=h();if(!U(e?.id??"")?.length){if(e?.title===Y.DESCRIPTION)return _(()=>`${y.EDIT} description `),N({mode:f.COMMAND_LINE}),c("Propose command",!0);if(e?.title===Y.ASSIGNEES)return _(()=>`${y.ASSIGN} `),N({mode:f.COMMAND_LINE}),c("Propose command",!0);if(e?.title===Y.TAGS)return _(()=>`${y.TAG} `),N({mode:f.COMMAND_LINE}),c("Propose command",!0);if(t.title===Y.DESCRIPTION&&e?.context==="TEXT")return _(()=>`${y.EDIT} description `),N({mode:f.COMMAND_LINE}),c("Propose command",!0)}return B.enterChildNode(),c("Entering context",null)}},{intent:g.Confirm,mode:f.PALETTE,description:"[<Enter>] select command",action:()=>{let{selectedNode:e}=h();if(!e||!Ko(e))return s("Command only applicable on text nodes");if(e.props.disabled)return s("Command is not available in this context");let t=e?.title;return t?(N({mode:f.COMMAND_LINE}),_(()=>`${t} `),c("Selected command",t)):c("No command selected",null)}},{intent:g.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(B.enterParentNode(),c("Exiting context",null))},{intent:g.Exit,mode:f.PALETTE,description:"[q] close palette",action:()=>(N({mode:f.DEFAULT}),_(()=>""),c("Closed command palette",null))},...ma(f.DEFAULT),...ma(f.PALETTE),{intent:g.Edit,mode:f.DEFAULT,action:()=>(N({mode:f.COMMAND_LINE}),_(()=>y.EDIT+" "),Re(),c("Fired command",!0))},{intent:g.SetViewDense,mode:f.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(ye({viewMode:"dense"}),c("View set",null))},{intent:g.SetViewWide,mode:f.DEFAULT,action:()=>(ye({viewMode:"wide"}),c("View set",null))}];var Ql=500,Zl=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),fa=e=>{let t=Zl(e);t&&_(n=>(n+t).slice(0,Ql))};var eu=[f.COMMAND_LINE,f.PALETTE],tu=e=>[{intent:g.MoveCursorLeft,mode:e,action:()=>(Zr(-1),c("Moving cursor left",null))},{intent:g.MoveCursorRight,mode:e,action:()=>(Zr(1),c("Moving cursor right",null))},{intent:g.MoveCursorLeftOfWord,mode:e,action:()=>(eo("left"),c("Moving cursor left of word",null))},{intent:g.MoveCursorRightOfWord,mode:e,action:()=>(eo("right"),c("Moving cursor right of word",null))},{intent:g.AutoCompleteCommand,mode:e,action:()=>(_((t,{remainder:n})=>n?t+n:t),c("Auto-completing command",null))},{intent:g.CaptureInput,mode:e,action:(t,{sequence:n})=>(fa(n??""),c("Capturing input",null))},{intent:g.EraseInput,mode:e,action:()=>(qi(),c("Erasing input",null))},{intent:g.EraseInputWord,mode:e,action:()=>(Yi(),c("Erasing input word",null))}],ga=[{intent:g.Confirm,mode:f.COMMAND_LINE,action:()=>(Re(),c("Executing command",null))},{intent:g.ViewHelp,mode:f.DEFAULT,action:()=>(N({mode:f.HELP}),c("Viewing help",null))},{intent:g.Exit,mode:f.HELP,action:()=>(N({mode:f.DEFAULT}),c("Exiting help",null))},...eu.flatMap(tu),{intent:g.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(N({mode:f.DEFAULT}),c("Exiting command line",null))},{intent:g.ExitCommandLine,mode:f.PALETTE,action:()=>(N({mode:f.DEFAULT}),c("Exiting palette",null))},{intent:g.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Qi(),c("Getting last command from history",null))},{intent:g.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Zi(),c("Getting next command from history",null))}];import nu from"chalk";var cr=": for command line",va="q to exit",ya=`${nu.hex(x.accent)("m")} to confirm`,Eo={[A.WORKSPACE]:[cr],[A.BOARD]:[cr],[A.BOARD+f.COMMAND_LINE]:[cr],[A.SWIMLANE]:[cr],[A.TICKET+f.HELP]:[va],[A.SWIMLANE+f.HELP]:[va],[A.TICKET]:[],[A.FIELD]:[],[A.SWIMLANE+f.MOVE]:[ya],[A.TICKET+f.MOVE]:[ya]};var fn=e=>e.trim().toLocaleLowerCase(),ru=e=>{let{tags:t}=h();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},ou=e=>{let{contributors:t}=h();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},ha=(e,t)=>{let n=fn(t.value);if(!n)return!0;switch(t.target){case"title":return fn(e.title??"").includes(n);case"description":return fn(e.props.description??"").includes(n);case"tag":return ru(e).map(fn).some(o=>o.includes(n));case"assignee":return ou(e).map(fn).some(o=>o.includes(n));default:return!0}};function xa(e,t,n){let r=t[e];if(!r)return s("buildBreadCrumb(): current node not found");let o=[],i=r;for(;i&&(o.push(i),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let a=o[o.length-1];return!a||a.id!==n?s("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var Ca=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 ht,bo,No=new Set,Ea=()=>{for(let e of No)e()},su=e=>(No.add(e),()=>No.delete(e));function ba(e){let{currentNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return s("derive(): currentNodeId is missing");if(!r)return s("derive(): rootNode is missing");if(!o[r])return s("derive(): unable to find root node");let l=o[t];if(!l)return s("Unable to derive state, currentNode not found");let u=xa(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,v=Eo[p+n]??Eo[p]??[],C=[...pa,...ua[p]??[],...ga],E=Ca(C),I=au(o,i),P=I[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,currentNode:l,breadCrumb:m,availableHints:v,availableActions:C,actionIndex:E,selectedNode:P,renderedChildrenIndex:I})}var h=()=>{if(!ht)throw new Error("State not initialized. Call initWorkspaceState() first.");return ht},Qe=()=>ht?c("Retrieved state",ht):s("State not initialized. Call initWorkspaceState() first.");function un(e){bo=e;let t=Je(process.cwd()),n=!1;if(!d(t)){let i=Xe(t.value);if(d(i))return s(i.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:f.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1},o=ba(r);return d(o)?o:(ht=o.value,Ea(),c("State initialized",null))}function ue(e){let t=h(),n=e(t),r=ba(n);return d(r)?s(r.message??"Unable to update state"):(ht=r.value,Ea(),c("State updated",null))}var N=e=>ue(t=>({...t,...e}));var Q=()=>iu(su,h,h),au=(e,t)=>{let n={};for(let r of Object.values(e))W(r)&&t.length>0&&!t.every(o=>ha(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,i)=>{let a=e[o.id],l=e[i.id];return!a||!l?0:a.rank.localeCompare(l.rank)});return n},O=e=>h()?.renderedChildrenIndex[e]??[],xo=()=>bo?un(bo):s("Cannot reset state: no initial workspace found"),Mt=()=>ht!==void 0;var ot=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r)return s("Node not found");if(r.context===t)return c("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return c("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return s(`No ancestor found for context: ${t}`)},So=(e,t)=>{let{nodes:n}=h(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},xt=(e,t)=>e?e.readonly?s({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:s("Node not found"),S={deleteNode(e){ue(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=h(),r=n[e];if(!r)return s("Edit target node not found");let o=xt(r,"edit");if(o)return o;let i={...r,props:{...r.props,description:t}};return this.updateNode(i),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return s("Rename target node not found");let r=xt(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=h();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=h();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return U(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=h(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let a=xt(o,"move");if(a)return a;if(So(t,e))return s("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=h(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,a=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let p of U(m.id))a(p.id)}};a(e);let l={...structuredClone(t)};for(let u of i){if(!l[u])return s("Unable to locate node to delete");l[u]={...l[u],isDeleted:!0}}return n?(N({nodes:l}),c("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=ue(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?s("Unable to create contributor"):c("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return s("Unable to assign contributor, missing contributor");if(!r)return s("Unable to assign contributor, missing target");let o=xt(r,"edit");if(o)return o;if(!W(r))return s("Target is not an issue");let i=r.props.assignees??[];if(i.includes(t))return s("Contributor already assigned");let a={...r,props:{...r.props,assignees:[...i,t]}};return this.updateNode(a),c("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return s("Unable to unassign, missing contributor");if(!r)return s("Unable to unassign, missing target");let o=xt(r,"edit");if(o)return o;if(!W(r))return s("Target is not an issue");let i=r.props.assignees??[];if(!i.includes(t))return c("Issue is not assigned to that contributor",{assignee:t});let a={...r,props:{...r.props,assignees:i.filter(l=>l!==t)}};return this.updateNode(a),c("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return s("Unable to add tag, missing tag");if(!r)return s("Unable to add tag, missing target");let o=xt(r,"edit");if(o)return o;if(!W(r))return s("Target is not an issue");let i=r.props.tags??[];if(i.includes(t))return s("Tag already assigned");let a={...r,props:{...r.props,tags:[...i,t]}};return this.updateNode(a),c("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return s("Unable to remove tag, missing tag");if(!r)return s("Unable to remove tag, missing target");let o=xt(r,"edit");if(o)return o;if(!W(r))return s("Target is not an issue");let i=r.props.tags??[];if(!i.includes(t))return c("Issue is not tagged with that tag",{tag:t});let a={...r,props:{...r.props,tags:i.filter(l=>l!==t)}};return this.updateNode(a),c("Tag removed",{tag:t})},createTag(e){let t=ue(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?s("Could not create tag"):c("Tag created",e)},createNode(e){let t=ue(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?s("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let n={...t,readonly:!0},r=ue(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?s(r.message):c("Locked node",n)},updateNode(e){let t=ue(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:c("Updated node",e)},getContributor(e){return h().contributors[e]},getTag(e){return h().tags[e]},getNode(e){return h().nodes[e]},getSiblings(e){return U(e)}};import Ct from"chalk";import Na from"string-width";import{decodeTime as du}from"ulid";var cu=(e,t)=>e+" ".repeat(Math.max(0,t-Na(e))),lu=(e,t)=>" ".repeat(Math.max(0,t-Na(e)))+e,uu=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"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),mu=(e,t)=>t?e<t?"up":e>t?"down":null:null,pu=(e,t)=>{let n=S.getNode(e.payload.parent),r=n?Ct.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let i=mu(e.payload.rank,o.rank);if(i)return`Moved ${i} in ${r}`}return`Moved issue to ${r}`},fu=e=>{switch(e.action){case"add.issue.tag":{let t=h().tags[e.payload.tag];return t?Ct.bgHex(ae(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=h().tags[e.payload.tag];return t?Ct.bgHex(ae(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?Ct.hex(ae(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?Ct.hex(ae(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""}},gu=e=>{let t=Bi(du(e));return Ct.gray(lu(t,8))},vu=12,yu=e=>cu(`${e}`,vu),Sa=(e,t)=>{let n=gu(e.id),r=yu(e.userName),o=Ct.dim("\u203A"),i=e.action==="move.node"?pu(e,t):[uu(e.action),fu(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${i}`};var hu=e=>tt(e,"description"),xu=e=>tt(e,"assignees"),Cu=e=>tt(e,"tags"),Eu=e=>tt(e,"history"),Ia=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:i=!1,childRenderAxis:a="horizontal"})=>{let l=S.getNode(e);if(!l){S.createNode({...ne.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:i,childRenderAxis:a});return}!qe(l)||!(l.title!==t||l.parentNodeId!==n||l.rank!==r||l.props.value!==o||l.readonly!==i||l.childRenderAxis!==a)||S.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:i,childRenderAxis:a})},Ra=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:i="horizontal"})=>{let a=S.getNode(e);if(!a){S.createNode({...ne.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:i});return}!Kt(a)||!(a.title!==t||a.parentNodeId!==n||a.rank!==r||a.readonly!==o||a.childRenderAxis!==i)||S.updateNode({...a,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:i})},Aa=e=>{let t=we(Oe/4n),n=we(Oe/2n),r=we(Oe*3n/4n),o=we(Oe);d(t)||d(n)||d(r)||d(o)||(Ia({id:hu(e.id),name:Y.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"}),Ra({id:xu(e.id),name:Y.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0}),Ra({id:Cu(e.id),name:Y.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0}),Ia({id:Eu(e.id),name:Y.HISTORY,parentNodeId:e.id,rank:o.value,value:bu(e),readonly:!0,childRenderAxis:"vertical"}))},bu=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=>Sa(r,n.get(r.action)??[])).join(`
|
|
59
|
-
`)};var M=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),wa=e=>{let t=S.getNode(e);!t||!W(t)||t.isDeleted||Aa(t)},Nu=e=>{for(let t of e){wa(t);let n=h().nodes[t]?.parentNodeId;n&&wa(n)}},Su=(e,t)=>{let n=S.getNode(e);n&&S.updateNode({...n,log:[...n.log??[],t]})},Iu=e=>{let t=[e],n=h().nodes[e]?.parentNodeId;return n&&t.push(n),t},Ru=e=>{switch(e.action){case"delete.node":case"edit.description":return Iu(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":default:return[]}},Au=e=>{ue(t=>({...t,eventLog:[...t.eventLog,e]}))},wu=e=>{let t=e.userId,n=e.userName;if(!t?.length||!n?.length)return M("Invalid user ID format",e);let r=S.createContributor({id:t,name:n});return d(r)?M(r.message,e):null},Tu=(e,t)=>{let n=wu(e);if(n)return n;let r=[...new Set(Ru(e))];return t||(r.forEach(o=>Su(o,e)),Au(e)),Nu(r),null},Mu={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=ne.workspace(t,n,r),i=un(o);if(d(i))return M(i.message,e);let a=S.createNode(o);return d(a)?M(a.message??"Failed to initialize workspace",e):Ar(a.value)?c("Workspace initialized",{action:e.action,result:a.value}):s("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=S.createNode(ne.workspace(t,n,r));return d(o)?M(o.message??"Failed to add workspace",e):Ar(o.value)?c("Added workspace",{action:e.action,result:o.value}):s("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=S.createNode(ne.board(t,n,r,o));return d(i)?M(i.message??"Unable to create board",e):zo(i.value)?c("Added board",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=S.createNode(ne.swimlane(t,n,r,o));return d(i)?M(i.message??"Unable to create swimlane",e):St(i.value)?c("Added swimlane",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=S.createNode(ne.ticket(t,n,r,o));return d(i)?M(i.message??"Unable to create issue",e):W(i.value)?c("Added issue",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:i}=e.payload,a=S.createNode(ne.field({id:t,name:n,parentNodeId:r,rank:i,props:{value:o},childRenderAxis:n.includes(Y.DESCRIPTION)?"vertical":"horizontal"}));return d(a)?M(a.message??`Unable to create field: ${n}`,e):qe(a.value)?c("Added field",{action:e.action,result:a.value}):s("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!S.getNode(t))return M(`Unable to locate node with id ${t}`,e);let o=S.renameNode(t,n);return d(o)?M(o.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=S.tombstoneNode(t);return d(n)?M(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=S.createTag({id:t,name:n});return d(r)?M(r.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=S.createContributor({id:t,name:n});return d(r)?M(r.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=S.tag(t,n);return d(r)?M(r.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=S.untag(t,n);return d(r)?M(r.message??"Unable to untag issue",e):c("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=S.assign(t,n);return d(r)?M(r.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=S.unassign(t,n);return d(r)?M(r.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=S.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?M(o.message??"Failed to move node",e):c("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=S.editValue(t,n);return d(r)?M(r.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=S.getNode(t);if(!o)return M("Unable to locate issue",e);if(!W(o))return M("Can only close issues",e);let i=S.getNode(He);if(!i)return M("Unable to locate target swimlane",e);if(n!==i.id)return M("Close target must be closed swimlane",e);let a=S.moveNodeToRank({id:t,parentId:n,rank:r});return d(a)?M(a.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=S.getNode(t);if(!o)return M("Unable to locate issue",e);if(!W(o))return M("Can only reopen issues",e);let i=S.getNode(He);if(!i)return M("Unable to locate closed swimlane",e);if(n===i.id)return M("Cannot reopen issue into closed swimlane",e);if(!S.getNode(n))return M("Reopen parent no longer exists",e);let l=S.moveNodeToRank({id:t,parentId:n,rank:r});return d(l)?M(l.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=S.lockNode(t);return d(n)?M(n.message??"Unable to lock node",e):c("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let i=S.getNode(r);if(!i)return M(`Unable to locate node ${r}`,e);if(i.parentNodeId!==t)return M(`Node ${r} is not child of ${t}`,e);let a=S.updateNode({...i,rank:o});if(d(a))return M(a.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})}};function pn(e,t=!1){let n=Mu[e.action](e);if(d(n))return n;let r=Tu(e,t);return r||n}var yt=e=>e.map(t=>pn(t));function Me(e,t){let n=pn(e);if(n.status!==Ye.Success)return n;let r=Qn({event:e,rootDir:t});return d(r)?r:n}function ra(e,t){return e.map(n=>Me(n,t))}var Ie=async e=>{let t=await Te();return d(t)?t:Me(e,t.value)};var Ta=e=>nr(U(e),{at:"end"}),nr=(e,t={at:"end"})=>{let n=r=>d(r)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(pe(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(pe(void 0,r.rank)):s("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(pe(r.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let r=Ma(e,t.sibling);if(r<0)return s("Sibling not found");let o=r>0?e[r-1]:void 0,i=e[r];return i?n(pe(o?.rank,i.rank)):s("Sibling not found")}case"after":{let r=Ma(e,t.sibling);if(r<0)return s("Sibling not found");let o=e[r],i=r<e.length-1?e[r+1]:void 0;return o?n(pe(o.rank,i?.rank)):s("Sibling not found")}}},U=e=>Object.values(h().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Ma=(e,t)=>e.findIndex(n=>n.id===t),Pa=(e,t,n={at:"end"})=>nr(U(t).filter(r=>r.id!==e),n),Co=(e,t,n,r,o)=>{let i=Pa(t,e,n);if(d(i))return i;if(!i.value.needsRebalance)return c("Resolved rank",i.value.rank);let a=wr(e,r);if(d(a))return a;let l=Me(a.value,o);if(d(l))return l;let u=Pa(t,e,n);return d(u)?u:u.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",u.value.rank)},ir=(e,t,n)=>{let r=Ta(e);if(d(r))return r;if(!r.value.needsRebalance)return c("Resolved rank",r.value.rank);let o=wr(e,t);if(d(o))return o;let i=Me(o.value,n);if(d(i))return i;let a=Ta(e);return d(a)?a:a.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",a.value.rank)};var La=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Da=()=>{let{currentNode:e,selectedIndex:t,selectedNode:n}=h();return{currentNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},Pu=e=>{let t=h().nodes[e];return!!t&&!t.isDeleted&&qe(t)&&t.childRenderAxis==="vertical"},lr=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r||r.isDeleted)return!1;let o=O(r.id);return B.navigate({currentNode:r,selectedIndex:La(t,o.length)}),!0},Fa=e=>{let{nodes:t}=h(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return lr(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let a=U(o.id).findIndex(l=>l.id===n.id);return a>=0?(B.navigate({currentNode:o,selectedIndex:a}),!0):Fa(o.id)},ka=e=>{let{nodes:t}=h(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Fa(n))return!0;n=t[n]?.parentNodeId}return!1},ku=e=>{if(!e)return!1;let t=h().nodes[e];return!!t&&!t.isDeleted},Oa=e=>{let{nodes:t,rootNodeId:n}=h();if(Pu(e.currentNodeId)&&lr(e.currentNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(ku(e.selectedNodeId)&&e.selectedNodeId&&ka(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(lr(e.currentNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&lr(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(ka(e.currentNodeId))return c("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return s("Unable to restore navigation");let o=O(r.id);return B.navigate({currentNode:r,selectedIndex:La(e.selectedIndex,o.length)}),c("Restored navigation to root",null)};var Io=({status:e,msg:t})=>{Mt()&&N({syncStatus:{status:e,msg:t}})},Ro=(e="Syncing...")=>{Io({status:"syncing",msg:e})},Ao=(e="Synced")=>{Io({status:"synced",msg:e})},Lu=e=>{Io({status:"failed",msg:e})},G=e=>(Lu(e),s(e));var _t=(e,t)=>(logger.error(`[boot:${e}] ${t}`),s(`[boot:${e}] ${t}`)),wo=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);import{decodeTime as Du}from"ulid";var gn=e=>{let t=[];for(let n of e.split(`
|
|
60
|
-
`)){let r=n.trim();if(r)try{t.push(JSON.parse(r))}catch{return
|
|
57
|
+
`)}`):(lu(),N({hasProjectDefinition:!0}),l("State booted successfully",null))}var mu=async e=>{let t=await D({cwd:e,args:["status","--porcelain"]});return d(t)?t:l("Checked git diff",t.value.stdout.trim().length>0)},H=(e,t)=>a(`[${e}] ${t}`),sa=async()=>{let e=ei(),t=await Pt(process.cwd());if(d(t))return H(1,t.message);let n=t.value,r=await An(n);if(d(r))return H(2,r.message);if(r.value)return H(2,"Cannot initialize Epiq while a git operation is in progress");let o=await mu(n);if(d(o))return H(2.5,o.message);if(o.value)return H(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(Hr(n))return H(4,"Epiq project already initialized");let i=tt();if(!i.isSetupDone||!i.userName)return H(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let s=$(),c=s.userName,u=s.userId;if(!u||!c)return H(5,"Missing Epiq user id");let m=e.stateBranch,p=await Tn({repoRoot:n,branch:m});if(d(p))return H(6,p.message);if(p.value)return H(6,`State branch already exists: ${m}`);let v=await Co({repoRoot:n,stateBranchName:m});if(d(v))return H(6,v.message);let C=kn();if(d(C))return H(7,C.message);let E=ia.join(Mn(),e.projectId),I=await Eo({repoRoot:n,stateBranchRoot:E,stateBranchName:m});if(d(I))return H(8,I.message);let k=ia.join(E,".epiq");uu.mkdirSync(k,{recursive:!0});let R=oa({userId:u,userName:c});if(d(R))return H(9,R.message);for(let kr of R.value){let Xo=rr({event:kr,rootDir:E});if(d(Xo))return H(9,Xo.message)}let T=await ir({stateBranchRoot:E,eventFileName:ln({userId:u,userName:c})});if(d(T))return H(10,T.message);let O=await Mt({cwd:E,message:"[epiq:init]"});if(d(O))return H(10,O.message);let te=await Zs(n);if(d(te))return H(11,te.message);let se=ni({repoRoot:n,fileContents:e});if(d(se))return H(12,se.message);let Ue=await K.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d(Ue))return H(13,Ue.message);let lt=await K.commit({cwd:n,message:"[epiq:init-project]"});if(d(lt))return H(13,lt.message);let Ee="Project initialized!",zt=await D({cwd:n,args:["push","-u","origin","HEAD"]});d(zt)&&(Ee+=` Warn: [init:14] ${zt.message}`);let ae=await mn({repoRoot:n,stateBranchRoot:E});d(ae)&&(Ee+=` Warn: [init:15] ${ae.message}`);let Rt=Ct(R.value).filter(d);if(Rt.length>0)return H(16,Rt.map(kr=>kr.message).join(`
|
|
58
|
+
`));let ut=et();if(d(ut))return H(16,ut.message);let{rootNodeId:Dd,nodes:Fd}=ut.value,Yo=Fd[Dd];return Yo?(M.navigate({contextNode:Yo,selectedIndex:0}),N({hasProjectDefinition:!0,mode:g.DEFAULT}),l(Ee,null)):H(16,"Unable to resolve initialized root node")};import{ulid as gu}from"ulid";import{ulid as pu}from"ulid";var aa=null,it=()=>structuredClone(aa),fn=e=>{aa=e},da=()=>{let{contextNode:e,selectedIndex:t}=x(),r=U(e.id)[t];return r?l("Resolved selected child",r):a("Target node not found")},So=({id:e,parentId:t,position:n={at:"end"}})=>{let r=U(t).filter(o=>o.id!==e);return ar(r,n)},ca=({id:e,parentId:t,position:n={at:"end"}})=>{let r=z();if(d(r))return a("Unable to resolve user ID");let o=So({parentId:t,id:e,position:n});return d(o)?o:l("Created pending move state",{id:pu(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},la=e=>{fn(e);let t=vn(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function No(e){let t=da();if(d(t))return t;let{contextNode:n,nodes:r}=x();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let i=U(o.id),s=i.findIndex(({id:m})=>m===n.id);if(s<0)return a("Current node not found among siblings");let c=i[s+e];if(!c)return a("Missing sibling node");let u=ca({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:la(u.value)}function bo(e){let t=da();if(d(t))return t;let{contextNode:n,selectedIndex:r}=x(),i=U(n.id)[r+e];if(!i)return a("Missing sibling node");let s=ca({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(s)?s:la(s.value)}var ua=()=>{let e=it();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=x().nodes[n];if(!r)return a("Move parent not found");let o=U(n).findIndex(i=>i.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))},dr=(e,t="Moved preview")=>{if(d(e))return e;let n=ua();return d(n)?n:(N({mode:g.MOVE}),l(t,null))},ma=async()=>{let e=z();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=V().commandMeta,{contextNode:n,selectedIndex:r}=x(),o=U(n.id)[r];if(!o)return N({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 i=U(o.parentNodeId),s=i.findIndex(({id:v})=>v===o.id);if(s===-1)return a("Target not found among siblings");let c=i[s-1],u=i[s+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=So({parentId:o.parentNodeId,id:o.id,position:m});return d(p)?p:(fn({id:gu(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),N({mode:g.MOVE}),l("Move initialized",null))}if(t==="next")return dr(bo(1));if(t==="previous")return dr(bo(-1));if(t==="to-next")return dr(No(1));if(t==="to-previous")return dr(No(-1));if(t==="confirm"){let i=it();if(!i)return a("No pending move to confirm");let s=await Me();if(d(s))return s;let c=Pe(i,s.value);if(d(c))return c;let u=ua();return d(u)?u:(fn(null),N({mode:g.DEFAULT}),l("Moved item",null))}return t==="cancel"?(fn(null),N({mode:g.DEFAULT}),l("Cancelling move",null)):a("Invalid move modifier")};import{ulid as cr}from"ulid";import{monotonicFactory as fu,ulid as vu}from"ulid";var xu=fu(),pa=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=xu();return l("Created issue events",[{id:vu(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}}])};var ga=async(e,t)=>{let n=z();if(d(n))return a("Unable to resolve user ID");let r=await Me();if(d(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:i,contextNode:s,selectedIndex:c}=x(),u=m=>{let p=Pe(m,o);if(d(p))return p;let v=b.getNode(p.value.result.id);if(!v)return a("Created node not found");if(!v.parentNodeId)return p;let C=b.getNode(v.parentNodeId);return C?(M.navigate({contextNode:C,selectedIndex:b.getSiblings(v.parentNodeId).findIndex(({id:E})=>E===v.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=x(),p=b.getNode(m);if(!p)return a("Workspace not found");let v=lr(p.id,n.value,o);return d(v)?v:u({id:cr(),action:"add.board",payload:{id:cr(),name:t.inputString,parent:p.id,rank:v.value},...n.value})}if(t.modifier==="swimlane"){let m=be(i,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=lr(m.value.id,n.value,o);return d(p)?p:u({id:cr(),action:"add.swimlane",payload:{id:cr(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=B(s.id)[c],p=s.context==="SWIMLANE"?s:s.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let O=be(i,"SWIMLANE");return d(O)?null:O.value})();if(!p)return a("Unable to add issue in this context");let v=lr(p.id,n.value,o);if(d(v))return v;let C=pa({name:t.inputString,parent:p.id,rank:v.value,user:n.value});if(d(C))return C;let E=C.value,I=fa(E,o);if(I.some(O=>d(O)))return a("Issue create failed: "+I.filter(d).map(O=>O.message).filter(Boolean).join(", "));let k=I[0];if(!k||d(k))return a("Issue creation failed");let T=E.find(O=>O.action==="add.issue")?.payload.id;return T?(M.navigate({contextNode:p,selectedIndex:b.getSiblings(p.id).findIndex(({id:O})=>O===T)}),l("Issue created",null)):a("Unable to determine ticket id")}return l("Success",null)};var va=async()=>{let e=be(x().breadCrumb,"BOARD");if(d(e))return e;let t=wt(process.cwd());if(d(t))throw new Error(t.message);let n=Wt(t.value);if(d(n))return a(n.message);let r=n.value,{modifier:o}=V().commandMeta,i;if(o==="now"){let C=Io();if(d(C))return C;let E=Ct(r);return E.some(d)?a(E.map(I=>I.message).join(", ")):(N({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),l("Peeking now",!0))}if(o==="prev"){let C=x().eventLog.at(-2),E=Xr(C);if(E===null)return a("No previous event to peek");i=E}else if(o==="next"){let C=x().unappliedEvents.at(0),E=Xr(C);if(E===null)return a("No next event to peek");i=E}else{let C=Wn(o);if(!C)return a("Invalid peek date");i=C.getTime()}let s=e.value.id,{appliedEvents:c,unappliedEvents:u}=Vs(r,i),m=Io();if(d(m))return m;let p=Ct(c);if(p.some(d))return a(p.map(C=>C.message).join(", "));let v=x().nodes[s];return v?(M.navigate({contextNode:v,selectedIndex:0}),N({mode:g.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),l("Peeking ",!0)):a("Board did not exist at peek date")};import yu from"zod";var xa=()=>{let e=V().commandMeta.inputString,t=yu.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:(Le({autoSyncIntervalMs:t.data}),N({mode:g.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))};var ya=()=>{let e=V().commandMeta.inputString.trim();if(e!=="yes"&&e!=="no")return a("Invalid response");let t=Bi(e),n=ht({autoSync:t});return d(n)?n:(Le({autoSync:t}),N({mode:g.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var ha=async()=>{_(()=>""),N({mode:g.DEFAULT});let e=et();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");N({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Bn();return d(t)?(N({syncStatus:{msg:t.message,status:"failed"}}),t):(N({mode:g.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};var Ca=e=>Object.values(x().tags).find(t=>t.name===e),Ea=e=>Object.values(x().contributors).find(t=>t.name===e),ur=[{systemOnly:!0,intent:w.Move,description:"Internal move-state command",mode:g.COMMAND_LINE,action:ma},{intent:w.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}=x(),r=B(t.id)[n];return r?Re({id:xe(),action:"delete.node",payload:{id:r.id},...e.value}):a("Unable to resolve child to delete")},onSuccess:()=>N({mode:g.DEFAULT})},{intent:w.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=V().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(s=>X(y.FILTER).map(c=>c.split(n)[0]).includes(s))(r))return a("Invalid filter modifier");let i={target:r,operator:"=",value:t.trim()};return Ae(s=>({...s,filters:e==="clear"?[]:[...s.filters,i],mode:g.DEFAULT})),l("Filter updated",null)}},{intent:w.ViewHelp,description:"Open the help screen",mode:g.COMMAND_LINE,action:()=>(N({mode:g.HELP}),l("Viewing help",null))},{intent:w.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}=x(),r=B(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=x().nodes[ze];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let i=await Me();if(d(i))return i;let s=i.value,c=Ro(o.id,r.id,{at:"end"},e.value,s);if(d(c))return c;let u=await Re({id:xe(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value});return d(u)?u:l("Issue closed",null)},onSuccess:()=>N({mode:g.DEFAULT})},{intent:w.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}=x(),r=B(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):st(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let i=o.value,s=x().nodes[ze];if(!s)return a("Unable to locate closed swimlane");if(i.parentNodeId!==s.id)return a("Issue is not closed");if(!W(i))return a("Target node is not issue");let c=Ys(i);if(!c)return a("Unable to resolve previous parent from issue history");if(c===s.id)return a("Previous parent resolves to closed swimlane");let u=x().nodes[c];if(!u)return a("Previous parent no longer exists");let m=await Me();if(d(m))return m;let p=m.value,v=Ro(u.id,i.id,{at:"end"},e.value,p);if(d(v))return v;let C=await Re({id:xe(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:v.value},...e.value});return d(C)?C:l("Issue reopened",null)},onSuccess:()=>N({mode:g.DEFAULT})},{intent:w.Init,description:"Initialize Epiq in the current git repository",mode:g.COMMAND_LINE,action:sa},{intent:w.NewItem,description:"Create a new board, swimlane, or issue",mode:g.COMMAND_LINE,action:ga,onSuccess:()=>N({mode:g.DEFAULT})},{intent:w.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}=x(),r=B(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=ps();return o?Re({id:xe(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):a("Provide a title")},onSuccess:()=>N({mode:g.DEFAULT})},{intent:w.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}=V().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=Ca(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:i}=x();if(!i)return a("Invalid untag target");let s=st(i.id,"TICKET");if(d(s))return a("Unable to untag issue in this context");let c=s.value;return W(c)?(c.props.tags??[]).includes(o.id)?Re({id:xe(),action:"remove.issue.tag",payload:{id:c.id,tag:o.id},...e.value}):a("Issue is not tagged with that tag"):a("Target node is not issue")},onSuccess:()=>N({mode:g.DEFAULT})},{intent:w.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}=V().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=x();if(!o)return a("Invalid tag target");let i=st(o.id,"TICKET");if(d(i))return a("Unable to tag issue in this context");let s=i.value;if(!W(s))return a("Target node is not issue");let c=Ca(r),u;if(c)u=c.id;else{let p=xe(),v=await Re({id:xe(),action:"create.tag",payload:{id:p,name:r},...e.value});if(d(v))return v;u=v.value.result.id}return(s.props.tags??[]).includes(u)?a("Already tagged with that tag"):Re({id:xe(),action:"add.issue.tag",payload:{id:s.id,tag:u},...e.value})},onSuccess:()=>N({mode:g.DEFAULT})},{intent:w.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}=V().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let{selectedIndex:o,contextNode:i}=x(),s=B(i.id)[o];if(!s)return a("Invalid assign target");let c=st(s.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=Ea(r),p;if(m)p=m.id;else{let C=xe(),E=await Re({id:xe(),action:"create.contributor",payload:{id:C,name:r},...e.value});if(d(E))return E;p=E.value.result.id}return(u.props.assignees??[]).includes(p)?a("Assignee already assigned"):Re({id:xe(),action:"add.issue.assignee",payload:{id:u.id,assignee:p},...e.value})},onSuccess:()=>N({mode:g.DEFAULT})},{intent:w.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}=V().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let o=Ea(r);if(!o)return a(`Assignee "${r}" does not exist`);let{selectedNode:i}=x();if(!i)return a("Invalid unassign target");let s=st(i.id,"TICKET");if(d(s))return a("Unable to unassign in this context");let c=s.value;return W(c)?(c.props.assignees??[]).includes(o.id)?Re({id:xe(),action:"remove.issue.assignee",payload:{id:c.id,assignee:o.id},...e.value}):a(`Issue is not assigned to "${r}"`):a("Target node is not issue")},onSuccess:()=>N({mode:g.DEFAULT})},{intent:w.Sync,description:"Pull, commit, and push Epiq state",mode:g.COMMAND_LINE,action:ha},{intent:w.Peek,description:"View board state at another point in time",mode:g.COMMAND_LINE,action:va},{intent:w.Export,description:"Export the current board layout to markdown",mode:g.COMMAND_LINE,action:async()=>{let e=await Ps();return d(e)?e:(N({mode:g.DEFAULT}),l("Export successful",!0))}},{intent:w.Exit,description:"Exit the application",mode:g.COMMAND_LINE,action:async()=>(M.exit(),l("Exit successful",!0))},{intent:w.Edit,description:"Edit title or description",mode:g.COMMAND_LINE,action:async(e,t)=>{if(t.modifier===nt.DESCRIPTION)return Qs();if(t.modifier===nt.TITLE){let n=z();if(d(n))return a("Unable to resolve user ID");let{contextNode:r,selectedIndex:o}=x(),i=B(r.id)[o];if(!i)return a("Missing node");if(i.readonly)return a("Cannot rename readonly node");let s=t.inputString.trim();return s?Re({id:xe(),action:"edit.title",payload:{id:i.id,name:s},...n.value}):a("Provide a title")}return a("Unknown edit command")},onSuccess:()=>N({mode:g.DEFAULT})},{intent:w.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 re.USERNAME:{let{userId:r,preferredEditor:o,userName:i}=$(),s=n||i,c=r??xe();if(!s||!c)return a("Unable to resolve user name or id");let u=ht({userName:s,userId:c,preferredEditor:o??""});return d(u)?u:(Le({userName:s,userId:c}),N({mode:g.DEFAULT}),l(`Username set to "${s}"`,null))}case re.EDITOR:{if(!n)return a("No editor provided");let r=ht({preferredEditor:n});return d(r)?r:(Le({preferredEditor:n}),N({mode:g.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case re.VIEW:return n!=="wide"&&n!=="dense"?a("Invalid view mode"):(Le({viewMode:n}),l(`View set to "${n}"`,null));case re.AUTOSYNC:return ya();case re.SYNC_DEBOUNCE_MS:return xa();default:return a("Unknown config command")}}}];var hu=new Set(["peek","filter","view-help"]),Fe=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=V();if(!t)return a("No command to confirm");if(!e&&n===vt.Invalid)return a("Invalid command");let i=Gn(t);ds();let{readOnly:s}=x();if(s&&!hu.has(i))return sn({status:Je.Fail,message:"Command not available in readonly state",value:null});let c=ur.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===i);if(!c)return sn({status:Je.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return sn({status:Je.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?sn(u):(cs({addToHistory:!e}),c.onSuccess?.(),$().autoSync&&Di(),u)};var mr=[{intent:f.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(N({mode:g.COMMAND_LINE}),_(()=>"move cancel"),Fe({isForceExecutedBySystem:!0}))},{intent:f.InitMove,mode:g.DEFAULT,description:"[m] move init/confirm",action:()=>(N({mode:g.COMMAND_LINE}),_(()=>"move start"),Fe({isForceExecutedBySystem:!0}))},{intent:f.ConfirmMove,mode:g.MOVE,action:()=>(N({mode:g.COMMAND_LINE}),_(()=>"move confirm"),Fe({isForceExecutedBySystem:!0}))}],pr=[{intent:f.MovePreviousItem,mode:g.MOVE,action:()=>it()?(N({mode:g.COMMAND_LINE}),_(()=>"move previous"),Fe({isForceExecutedBySystem:!0})):a("No pending move")},{intent:f.MoveNextItem,mode:g.MOVE,action:()=>it()?(N({mode:g.COMMAND_LINE}),_(()=>"move next"),Fe({isForceExecutedBySystem:!0})):a("No pending move")}],Sa=[{intent:f.MoveToNextContainer,mode:g.MOVE,action:()=>it()?(N({mode:g.COMMAND_LINE}),_(()=>"move to-next"),Fe({isForceExecutedBySystem:!0})):a("No pending move")},{intent:f.MoveToPreviousContainer,mode:g.MOVE,action:()=>it()?(N({mode:g.COMMAND_LINE}),_(()=>"move to-previous"),Fe({isForceExecutedBySystem:!0})):a("No pending move")}];var Na={[A.WORKSPACE]:[...mr,...pr],[A.BOARD]:[...mr,...pr],[A.SWIMLANE]:[...mr,...pr,...Sa],[A.TICKET]:[],[A.FIELD]:[],[A.FIELD_LIST]:[],[A.TEXT]:[]};import{useSyncExternalStore as jS}from"react";var gr,Cu=new Set,ba=()=>{for(let e of Cu)e()};var Ht=()=>{if(!gr)throw new Error("Ui state not initialized. Call initUiState() first.");return gr};var Ia=(e={})=>(gr=e,ba(),l("UX state initialized",null)),Eu=e=>{let t=Ht();return gr=e(t),ba(),l("UX state updated",null)},fr=e=>Eu(t=>({...t,...e}));var Su=e=>{N({mode:g.COMMAND_LINE});let{pendingNavTarget:t}=Ht();t&&M.navigate(t),fr({pendingNavTarget:void 0}),_(()=>`${e} `)},Ra=()=>{_(()=>"");let{pendingNavTarget:e}=Ht();e&&M.navigate(e),fr({pendingNavTarget:void 0}),N({mode:g.DEFAULT})},Aa=[{intent:f.InitCommandPalette,mode:g.DEFAULT,description:"[?] command palette",action:()=>{_(()=>"");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=x();return fr({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),N({mode:g.PALETTE}),l("Opening command palette",null)}},{intent:f.Confirm,mode:g.PALETTE,description:"[<Enter>] select command",action:()=>{let{selectedNode:e}=x();if(!e||!Gt(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?(Su(t),l("Selected command",t)):l("No command selected",null)}},{intent:f.ExitCommandLine,mode:g.PALETTE,action:()=>(Ra(),l("Exiting palette",null))},{intent:f.Exit,mode:g.PALETTE,description:"[q] close palette",action:()=>(Ra(),l("Closed command palette",null))},{intent:f.NavPreviousItem,mode:g.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:f.NavNextItem,mode:g.PALETTE,action:()=>(M.navigateToNextItem(),l("Navigating to next item",null))},{intent:f.NavToPreviousContainer,mode:g.PALETTE,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:f.NavToNextContainer,mode:g.PALETTE,action:()=>(M.navigateToNextContainer(),l("Navigating to next container",null))}];var Ta=[...Aa,{intent:f.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(N({mode:g.COMMAND_LINE}),_(()=>`${y.NEW} `),l("Adding new item",null))},{intent:f.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(N({mode:g.COMMAND_LINE}),_(()=>`${y.DELETE} `),l("Deleting item",null))},{intent:f.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(N({mode:g.COMMAND_LINE}),_(()=>""),l("Entering command line mode",null))},{intent:f.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=x();if(!U(e?.id??"")?.length){if(e?.title===Y.DESCRIPTION)return N({mode:g.COMMAND_LINE}),_(()=>`${y.EDIT} description `),l("Propose command",!0);if(e?.title===Y.ASSIGNEES)return N({mode:g.COMMAND_LINE}),_(()=>`${y.ASSIGN} `),l("Propose command",!0);if(e?.title===Y.TAGS)return N({mode:g.COMMAND_LINE}),_(()=>`${y.TAG} `),l("Propose command",!0);if(t.title===Y.DESCRIPTION&&e?.context==="TEXT")return N({mode:g.COMMAND_LINE}),_(()=>`${y.EDIT} description `),l("Propose command",!0)}return M.enterChildNode(),l("Entering context",null)}},{intent:f.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(M.enterParentNode(),l("Exiting context",null))},{intent:f.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:f.NavNextItem,mode:g.DEFAULT,action:()=>(M.navigateToNextItem(),l("Navigating to next item",null))},{intent:f.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(M.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:f.NavToNextContainer,mode:g.DEFAULT,action:()=>(M.navigateToNextContainer(),l("Navigating to next container",null))}];var Nu=500,bu=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),wa=e=>{let t=bu(e);t&&_(n=>(n+t).slice(0,Nu))};var Iu=[g.COMMAND_LINE,g.PALETTE],Ru=e=>[{intent:f.MoveCursorLeft,mode:e,action:()=>(io(-1),l("Moving cursor left",null))},{intent:f.MoveCursorRight,mode:e,action:()=>(io(1),l("Moving cursor right",null))},{intent:f.MoveCursorLeftOfWord,mode:e,action:()=>(so("left"),l("Moving cursor left of word",null))},{intent:f.MoveCursorRightOfWord,mode:e,action:()=>(so("right"),l("Moving cursor right of word",null))},{intent:f.AutoCompleteCommand,mode:e,action:()=>(_((t,{remainder:n})=>n?t+n:t),l("Auto-completing command",null))},{intent:f.CaptureInput,mode:e,action:(t,{sequence:n})=>(wa(n??""),l("Capturing input",null))},{intent:f.EraseInput,mode:e,action:()=>(ss(),l("Erasing input",null))},{intent:f.EraseInputWord,mode:e,action:()=>(as(),l("Erasing input word",null))}],Ma=[{intent:f.Confirm,mode:g.COMMAND_LINE,action:()=>(Fe(),l("Executing command",null))},{intent:f.ViewHelp,mode:g.DEFAULT,action:()=>(N({mode:g.HELP}),l("Viewing help",null))},{intent:f.Exit,mode:g.HELP,action:()=>(N({mode:g.DEFAULT}),l("Exiting help",null))},...Iu.flatMap(Ru),{intent:f.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(N({mode:g.DEFAULT}),l("Exiting command line",null))},{intent:f.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(ls(),l("Getting last command from history",null))},{intent:f.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(us(),l("Getting next command from history",null))}];import La from"chalk";var vr=La.dim.hex(h.secondary2)(": for command line"),Pa="q to exit",ka=`${La.hex(h.accent)("m")} to confirm`,Ao={[A.WORKSPACE]:[vr],[A.BOARD]:[vr],[A.BOARD+g.COMMAND_LINE]:[vr],[A.SWIMLANE]:[vr],[A.TICKET+g.HELP]:[Pa],[A.SWIMLANE+g.HELP]:[Pa],[A.TICKET]:[],[A.FIELD]:[],[A.SWIMLANE+g.MOVE]:[ka],[A.TICKET+g.MOVE]:[ka]};var xn=e=>e.trim().toLocaleLowerCase(),Au=e=>{let{tags:t}=x();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Tu=e=>{let{contributors:t}=x();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},Da=(e,t)=>{let n=xn(t.value);if(!n)return!0;switch(t.target){case"title":return xn(e.title??"").includes(n);case"description":return xn(e.props.description??"").includes(n);case"tag":return Au(e).map(xn).some(o=>o.includes(n));case"assignee":return Tu(e).map(xn).some(o=>o.includes(n));default:return!0}};function Fa(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],i=r;for(;i&&(o.push(i),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let s=o[o.length-1];return!s||s.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var Oa=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 Et,To,wo=new Set,Ba=()=>{for(let e of wo)e()},Mu=e=>(wo.add(e),()=>wo.delete(e));function Ua(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=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=Fa(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,v=Ao[p+n]??Ao[p]??[],C=[...Ta,...Na[p]??[],...Ma],E=Oa(C),I=Pu(o,i),k=I[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:v,availableActions:C,actionIndex:E,selectedNode:k,renderedChildrenIndex:I})}var x=()=>{if(!Et)throw new Error("State not initialized. Call initWorkspaceState() first.");return Et},et=()=>Et?l("Retrieved state",Et):a("State not initialized. Call initWorkspaceState() first.");function gn(e){To=e;let t=Ze(process.cwd()),n=!1;if(!d(t)){let i=Qe(t.value);if(d(i))return a(i.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:[],timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1},o=Ua(r);return d(o)?o:(Et=o.value,Ba(),l("State initialized",null))}function Ae(e){let t=x(),n=e(t),r=Ua(n);return d(r)?a(r.message??"Unable to update state"):(Et=r.value,Ba(),l("State updated",null))}var N=e=>Ae(t=>({...t,...e}));var Z=()=>wu(Mu,x,x),Pu=(e,t)=>{let n={};for(let r of Object.values(e))W(r)&&t.length>0&&!t.every(o=>Da(r,o))||!r.parentNodeId||r.isDeleted||((!r.parentNodeId||!n[r.parentNodeId])&&(n[r.parentNodeId]=[]),n[r.parentNodeId].push(r));for(let r of Object.keys(n))n[r].sort((o,i)=>{let s=e[o.id],c=e[i.id];return!s||!c?0:s.rank.localeCompare(c.rank)});return n},B=e=>x()?.renderedChildrenIndex[e]??[],Io=()=>To?gn(To):a("Cannot reset state: no initial workspace found"),Lt=()=>Et!==void 0;var st=(e,t)=>{let{nodes:n}=x(),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}`)},Mo=(e,t)=>{let{nodes:n}=x(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},St=(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={deleteNode(e){Ae(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=x(),r=n[e];if(!r)return a("Edit target node not found");let o=St(r,"edit");if(o)return o;let i={...r,props:{...r.props,description:t}};return this.updateNode(i),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=St(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=x();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=x();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return U(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=x(),o=this.getNode(e),i=this.getNode(t);if(!o)return a("Node not found");if(!i)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 s=St(o,"move");if(s)return s;if(Mo(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}=x(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let i=new Set,s=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let p of U(m.id))s(p.id)}};s(e);let c={...structuredClone(t)};for(let u of i){if(!c[u])return a("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(N({nodes:c}),l("Successfully tomb stoned",o)):a("Unable to delete undefined")},createContributor(e){let t=Ae(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=St(r,"edit");if(o)return o;if(!W(r))return a("Target is not an issue");let i=r.props.assignees??[];if(i.includes(t))return a("Contributor already assigned");let s={...r,props:{...r.props,assignees:[...i,t]}};return this.updateNode(s),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=St(r,"edit");if(o)return o;if(!W(r))return a("Target is not an issue");let i=r.props.assignees??[];if(!i.includes(t))return l("Issue is not assigned to that contributor",{assignee:t});let s={...r,props:{...r.props,assignees:i.filter(c=>c!==t)}};return this.updateNode(s),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=St(r,"edit");if(o)return o;if(!W(r))return a("Target is not an issue");let i=r.props.tags??[];if(i.includes(t))return a("Tag already assigned");let s={...r,props:{...r.props,tags:[...i,t]}};return this.updateNode(s),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=St(r,"edit");if(o)return o;if(!W(r))return a("Target is not an issue");let i=r.props.tags??[];if(!i.includes(t))return l("Issue is not tagged with that tag",{tag:t});let s={...r,props:{...r.props,tags:i.filter(c=>c!==t)}};return this.updateNode(s),l("Tag removed",{tag:t})},createTag(e){let t=Ae(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):l("Tag created",e)},createNode(e){let t=Ae(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=Ae(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):l("Locked node",n)},updateNode(e){let t=Ae(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return x().contributors[e]},getTag(e){return x().tags[e]},getNode(e){return x().nodes[e]},getSiblings(e){return U(e)}};import Nt from"chalk";import $a from"string-width";import{decodeTime as ku}from"ulid";var Lu=(e,t)=>e+" ".repeat(Math.max(0,t-$a(e))),Du=(e,t)=>" ".repeat(Math.max(0,t-$a(e)))+e,Fu=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"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),Ou=(e,t)=>t?e<t?"up":e>t?"down":null:null,Bu=(e,t)=>{let n=b.getNode(e.payload.parent),r=n?Nt.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let i=Ou(e.payload.rank,o.rank);if(i)return`Moved ${i} in ${r}`}return`Moved issue to ${r}`},Uu=e=>{switch(e.action){case"add.issue.tag":{let t=x().tags[e.payload.tag];return t?Nt.bgHex(Ie(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=x().tags[e.payload.tag];return t?Nt.bgHex(Ie(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=x().contributors[e.payload.assignee];return t?Nt.hex(Ie(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=x().contributors[e.payload.assignee];return t?Nt.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""}},$u=e=>{let t=ji(ku(e));return Nt.gray(Du(t,8))},Wu=12,_u=e=>Lu(`${e}`,Wu),Wa=(e,t)=>{let n=$u(e.id),r=_u(e.userName),o=Nt.dim("\u203A"),i=e.action==="move.node"?Bu(e,t):[Fu(e.action),Uu(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${i}`};var Hu=e=>rt(e,"description"),ju=e=>rt(e,"assignees"),Ku=e=>rt(e,"tags"),Vu=e=>rt(e,"history"),_a=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:i=!1,childRenderAxis:s="horizontal"})=>{let c=b.getNode(e);if(!c){b.createNode({...oe.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:i,childRenderAxis:s});return}!Xe(c)||!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==i||c.childRenderAxis!==s)||b.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:i,childRenderAxis:s})},Ha=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:i="horizontal"})=>{let s=b.getNode(e);if(!s){b.createNode({...oe.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:i});return}!qt(s)||!(s.title!==t||s.parentNodeId!==n||s.rank!==r||s.readonly!==o||s.childRenderAxis!==i)||b.updateNode({...s,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:i})},ja=e=>{let t=we($e/4n),n=we($e/2n),r=we($e*3n/4n),o=we($e);d(t)||d(n)||d(r)||d(o)||(_a({id:Hu(e.id),name:Y.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"}),Ha({id:ju(e.id),name:Y.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0}),Ha({id:Ku(e.id),name:Y.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0}),_a({id:Vu(e.id),name:Y.HISTORY,parentNodeId:e.id,rank:o.value,value:zu(e),readonly:!0,childRenderAxis:"vertical"}))},zu=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=>Wa(r,n.get(r.action)??[])).join(`
|
|
59
|
+
`)};var P=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Ka=e=>{let t=b.getNode(e);!t||!W(t)||t.isDeleted||ja(t)},Gu=e=>{for(let t of e){Ka(t);let n=x().nodes[t]?.parentNodeId;n&&Ka(n)}},qu=(e,t)=>{let n=b.getNode(e);n&&b.updateNode({...n,log:[...n.log??[],t]})},Yu=e=>{let t=[e],n=x().nodes[e]?.parentNodeId;return n&&t.push(n),t},Xu=e=>{switch(e.action){case"delete.node":case"edit.description":return Yu(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":default:return[]}},Ju=e=>{Ae(t=>({...t,eventLog:[...t.eventLog,e]}))},Qu=e=>{let t=e.userId,n=e.userName;if(!t?.length||!n?.length)return P("Invalid user ID format",e);let r=b.createContributor({id:t,name:n});return d(r)?P(r.message,e):null},Zu=(e,t)=>{let n=Qu(e);if(n)return n;let r=[...new Set(Xu(e))];return t||(r.forEach(o=>qu(o,e)),Ju(e)),Gu(r),null},em={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=oe.workspace(t,n,r),i=gn(o);if(d(i))return P(i.message,e);let s=b.createNode(o);return d(s)?P(s.message??"Failed to initialize workspace",e):Lr(s.value)?l("Workspace initialized",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=b.createNode(oe.workspace(t,n,r));return d(o)?P(o.message??"Failed to add workspace",e):Lr(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,i=b.createNode(oe.board(t,n,r,o));return d(i)?P(i.message??"Unable to create board",e):Jo(i.value)?l("Added board",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=b.createNode(oe.swimlane(t,n,r,o));return d(i)?P(i.message??"Unable to create swimlane",e):At(i.value)?l("Added swimlane",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=b.createNode(oe.ticket(t,n,r,o));return d(i)?P(i.message??"Unable to create issue",e):W(i.value)?l("Added issue",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:i}=e.payload,s=b.createNode(oe.field({id:t,name:n,parentNodeId:r,rank:i,props:{value:o},childRenderAxis:n.includes(Y.DESCRIPTION)?"vertical":"horizontal"}));return d(s)?P(s.message??`Unable to create field: ${n}`,e):Xe(s.value)?l("Added field",{action:e.action,result:s.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!b.getNode(t))return P(`Unable to locate node with id ${t}`,e);let o=b.renameNode(t,n);return d(o)?P(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)?P(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)?P(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)?P(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)?P(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)?P(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)?P(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)?P(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)?P(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)?P(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 P("Unable to locate issue",e);if(!W(o))return P("Can only close issues",e);let i=b.getNode(ze);if(!i)return P("Unable to locate target swimlane",e);if(n!==i.id)return P("Close target must be closed swimlane",e);let s=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(s)?P(s.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 P("Unable to locate issue",e);if(!W(o))return P("Can only reopen issues",e);let i=b.getNode(ze);if(!i)return P("Unable to locate closed swimlane",e);if(n===i.id)return P("Cannot reopen issue into closed swimlane",e);if(!b.getNode(n))return P("Reopen parent no longer exists",e);let c=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?P(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)?P(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let i=b.getNode(r);if(!i)return P(`Unable to locate node ${r}`,e);if(i.parentNodeId!==t)return P(`Node ${r} is not child of ${t}`,e);let s=b.updateNode({...i,rank:o});if(d(s))return P(s.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})}};function vn(e,t=!1){let n=em[e.action](e);if(d(n))return n;let r=Zu(e,t);return r||n}var Ct=e=>e.map(t=>vn(t));function Pe(e,t){let n=vn(e);if(n.status!==Je.Success)return n;let r=rr({event:e,rootDir:t});return d(r)?r:n}function fa(e,t){return e.map(n=>Pe(n,t))}var Re=async e=>{let t=await Me();return d(t)?t:Pe(e,t.value)};var Va=e=>ar(U(e),{at:"end"}),ar=(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(me(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(me(void 0,r.rank)):a("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(me(r.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let r=za(e,t.sibling);if(r<0)return a("Sibling not found");let o=r>0?e[r-1]:void 0,i=e[r];return i?n(me(o?.rank,i.rank)):a("Sibling not found")}case"after":{let r=za(e,t.sibling);if(r<0)return a("Sibling not found");let o=e[r],i=r<e.length-1?e[r+1]:void 0;return o?n(me(o.rank,i?.rank)):a("Sibling not found")}}},U=e=>Object.values(x().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),za=(e,t)=>e.findIndex(n=>n.id===t),Ga=(e,t,n={at:"end"})=>ar(U(t).filter(r=>r.id!==e),n),Ro=(e,t,n,r,o)=>{let i=Ga(t,e,n);if(d(i))return i;if(!i.value.needsRebalance)return l("Resolved rank",i.value.rank);let s=Dr(e,r);if(d(s))return s;let c=Pe(s.value,o);if(d(c))return c;let u=Ga(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)},lr=(e,t,n)=>{let r=Va(e);if(d(r))return r;if(!r.value.needsRebalance)return l("Resolved rank",r.value.rank);let o=Dr(e,t);if(d(o))return o;let i=Pe(o.value,n);if(d(i))return i;let s=Va(e);return d(s)?s:s.value.needsRebalance?a("Rank rebalance failed to create space"):l("Resolved rank after rebalance",s.value.rank)};var Ya=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Xa=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=x();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},tm=e=>{let t=x().nodes[e];return!!t&&!t.isDeleted&&Xe(t)&&t.childRenderAxis==="vertical"},xr=(e,t)=>{let{nodes:n}=x(),r=n[e];if(!r||r.isDeleted)return!1;let o=B(r.id);return M.navigate({contextNode:r,selectedIndex:Ya(t,o.length)}),!0},Ja=e=>{let{nodes:t}=x(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return xr(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let s=U(o.id).findIndex(c=>c.id===n.id);return s>=0?(M.navigate({contextNode:o,selectedIndex:s}),!0):Ja(o.id)},qa=e=>{let{nodes:t}=x(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Ja(n))return!0;n=t[n]?.parentNodeId}return!1},nm=e=>{if(!e)return!1;let t=x().nodes[e];return!!t&&!t.isDeleted},Qa=e=>{let{nodes:t,rootNodeId:n}=x();if(tm(e.contextNodeId)&&xr(e.contextNodeId,e.selectedIndex))return l("Restored navigation inside text container",null);if(nm(e.selectedNodeId)&&e.selectedNodeId&&qa(e.selectedNodeId))return l("Restored navigation to selected node or ancestor",null);if(xr(e.contextNodeId,e.selectedIndex))return l("Restored navigation to previous container",null);if(e.parentNodeId&&xr(e.parentNodeId,e.selectedIndex))return l("Restored navigation to previous parent",null);if(qa(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=B(r.id);return M.navigate({contextNode:r,selectedIndex:Ya(e.selectedIndex,o.length)}),l("Restored navigation to root",null)};var Po=({status:e,msg:t})=>{Lt()&&N({syncStatus:{status:e,msg:t}})},ko=(e="Syncing...")=>{Po({status:"syncing",msg:e})},Lo=(e="Synced")=>{Po({status:"synced",msg:e})},rm=e=>{Po({status:"failed",msg:e})},G=e=>(rm(e),a(e));var jt=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),Do=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)}},L=(e,t)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t);import{decodeTime as om}from"ulid";var yn=e=>{let t=[];for(let n of e.split(`
|
|
60
|
+
`)){let r=n.trim();if(r)try{t.push(JSON.parse(r))}catch{return a("Failed to parse persisted events")}}return l("Parsed persisted events",t)},Fo=e=>{let[t,n]=e.id;return`${t}:${n??""}`},Za=e=>{try{return om(e.id[0])}catch{return 0}},Oo=(e,t)=>{let n=new Map;for(let r of[...e,...t])n.set(Fo(r),r);return[...n.values()].sort((r,o)=>{let i=Za(r)-Za(o);return i!==0?i:Fo(r).localeCompare(Fo(o))})},Bo=e=>e.length===0?"":e.map(t=>JSON.stringify(t)).join(`
|
|
61
61
|
`)+`
|
|
62
|
-
`;var ur=e=>Ae.existsSync(e)?Ae.readFileSync(e,"utf8"):null,_a=(e,t)=>ur(e)===t?!1:(Ae.mkdirSync(Et.dirname(e),{recursive:!0}),Ae.writeFileSync(e,t,"utf8"),!0),Fu=({stateBranchRoot:e,ownEventFileName:t})=>Et.join(e,ut(t)),Ou=async({stateBranchRoot:e,ownEventFileName:t})=>{let n=ut(t),r=Et.join(e,n);return(await be({cwd:e,args:["checkout","--",n]})).exitCode!==0&&Ae.existsSync(r)&&Ae.rmSync(r,{force:!0}),c("Restored own event file to HEAD",null)},Ua=({ownEventPath:e,ownSnapshot:t})=>{if(t===null)return c("No own snapshot to merge",!1);let n=ur(e)??"",r=gn(n);if(d(r))return s(r.message);let o=gn(t);if(d(o))return s(o.message);let i=Mo(r.value,o.value),a=_a(e,Po(i));return c("Merged own snapshot",a)},Bu=e=>{let t=Et.join(e,".epiq","events"),n=new Map;if(!Ae.existsSync(t))return c("No event files to snapshot",n);for(let r of Ae.readdirSync(t)){if(!r.endsWith(".jsonl"))continue;let o=Et.join(t,r);Ae.statSync(o).isFile()&&n.set(r,Ae.readFileSync(o,"utf8"))}return c("Snapshotted event files",n)},Uu=async e=>{if((await be({cwd:e,args:["checkout","--",ut("")]})).exitCode!==0){let n=Et.join(e,".epiq","events");Ae.existsSync(n)&&Ae.rmSync(n,{recursive:!0,force:!0})}return c("Restored event files to HEAD",null)},$u=({stateBranchRoot:e,snapshots:t})=>{let n=!1;for(let[r,o]of t){let i=Et.join(e,ut(r)),a=ur(i)??"",l=gn(a);if(d(l))return s(l.message);let u=gn(o);if(d(u))return s(u.message);let m=Mo(l.value,u.value);n=_a(i,Po(m))||n}return c("Merged event snapshots",n)},ja=async(e=process.cwd())=>{logger.info("[sync] syncEpiqFromRemote:start",e),Ro("Syncing from remote");let t=k("ensureSyncReady",await Ha({cwd:e,ensureUpstream:!1}));if(d(t))return G(t.message);let{repoRoot:n,stateBranchRoot:r}=t.value,o=k("getStateBranch",lt(n));if(d(o))return G(o.message);let i=o.value,a=k("snapshotEventFiles",Bu(r));if(d(a))return G(a.message);let l=k("restoreEventFilesToHead",await Uu(r));if(d(l))return G(l.message);let u=k("resetBranchHardToRemote",await di({cwd:r,branch:i}));if(d(u))return G(u.message);let m=k("mergeEventSnapshots",$u({stateBranchRoot:r,snapshots:a.value}));return d(m)?G(m.message):(Ao(m.value?"Synced and merged local state":"Synced from remote"),logger.info("[sync] syncEpiqFromRemote:done"),c("Synced state branch from remote",{repoRoot:n,stateBranchRoot:r}))},Ha=async({cwd:e,ensureUpstream:t})=>{logger.info("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=k("getRepoRootDir",await wt(e));if(d(n))return s(n.message);let r=n.value;logger.info("[sync] repo root",r);let o=k("getStateBranchRoot",wn({repoRoot:r}));if(d(o))return s(o.message);let i=o.value;logger.info("[sync] state branch root",i);let a=k("ensureInitialCommit",await Hs(r));if(d(a))return s(a.message);logger.info("[sync] initial commit result",{created:a.value}),logger.info("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:i,ensureUpstream:t});let l=k("bootstrapStateBranchStorage",await Ks({repoRoot:r,stateBranchRoot:i,ensureUpstream:t}));if(d(l))return s(l.message);logger.info("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:i}),logger.info("[sync] checking state branch git operation",{stateBranchRoot:i});let u=k("hasInProgressGitOperation(stateBranchRoot)",await Sn(i));if(d(u))return s(u.message);if(logger.info("[sync] state branch git operation check result",{inProgress:u.value}),u.value)return logger.info("[sync] state branch git operation in progress"),s("Cannot sync while a git operation is in progress in the state branch");logger.info("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:i});let m=k("ensureStateBranchLayout",gi(r,i));return d(m)?s(m.message):(logger.info("[sync] state branch layout ready"),logger.info("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:i,bootstrapped:l.value}),c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:i,bootstrapped:l.value}))},$a=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.info("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.info("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=k("stageStateBranchOwnEventFile",await er({stateBranchRoot:t,eventFileName:n}));if(d(r))return s(r.message);let o=k("hasStagedChanges(after stage)",await ci(t));if(d(o))return s(o.message);if(logger.info("[sync] state branch change check after stage result",{changed:o.value}),!o.value)return logger.info("[sync] no own event file changes to commit"),c("No own event file changes to commit",{createdCommit:!1});logger.info("[sync] creating sync commit");let i=k("createStateBranchSyncCommit",await Vs({repoRoot:e,stateBranchRoot:t}));return d(i)?s(i.message):(logger.info("[sync] created sync commit",i.value),c("Committed own event file",{createdCommit:!0,commitSha:i.value}))},Wu=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.info("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.info("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),s("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.info("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),s("Own event file must end with .jsonl");Ro("Syncing");let n=k("ensureSyncReady",await Ha({cwd:e,ensureUpstream:!0}));if(d(n))return G(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value;logger.info("[sync] sync preconditions ready",{repoRoot:r,stateBranchRoot:o,bootstrapped:i}),logger.info("[sync] checking detached state branch",{stateBranchRoot:o});let a=k("isDetachedHead(stateBranchRoot)",await li(o));if(d(a))return G(a.message);if(logger.info("[sync] detached state branch check result",{detached:a.value}),a.value)return logger.info("[sync] state branch is detached"),G("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,p=!1,v=k("getStateBranch",lt(r));if(d(v))return G(v.message);let C=v.value;logger.info("[sync] resolved state branch",{stateBranch:C,stateBranchRoot:o});let E=Fu({stateBranchRoot:o,ownEventFileName:t}),I=ur(E),P=k("restoreOwnEventFileToHead",await Ou({stateBranchRoot:o,ownEventFileName:t}));if(d(P))return G(P.message);let R=k("pullBranchRebaseIfPresent",await Dr({cwd:o,branch:C}));if(d(R))return G(R.message);m=R.value;let w=k("mergeOwnSnapshot",Ua({ownEventPath:E,ownSnapshot:I}));if(d(w))return G(w.message);let D=k("commitOwnEventFileToStateBranch",await $a({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(D))return G(D.message);if(l=D.value.createdCommit,u=D.value.commitSha,logger.info("[sync] sync own result",{createdCommit:l,commitSha:u}),l||i){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:i,stateBranchRoot:o});let ee=k("pushStateBranch(initial)",await cn({stateBranchRoot:o,repoRoot:r})),oe=ee;if(d(ee)&&si(ee.message)){logger.info("[sync] non-fast-forward, retrying sync");let Fe=k("pullBranchRebaseIfPresent(retry)",await Dr({cwd:o,branch:C}));if(d(Fe))return G(Fe.message);logger.info("[sync] pull retry result",Fe.value);let dt=k("mergeOwnSnapshot(retry)",Ua({ownEventPath:E,ownSnapshot:I}));if(d(dt))return G(dt.message);let Ee=k("commitOwnEventFileToStateBranch(retry)",await $a({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(Ee))return G(Ee.message);logger.info("[sync] retry sync result",Ee.value),Ee.value.createdCommit&&(l=!0,u=Ee.value.commitSha),oe=k("pushStateBranch(retry)",await cn({stateBranchRoot:o,repoRoot:r}))}if(d(oe))return G(oe.message);p=oe.value,logger.info("[sync] pushed to state branch",p)}else logger.info("[sync] no commit created, skipped push");if(l){logger.info("[sync] resolving final sync commit sha",{stateBranchRoot:o});let ee=k("git rev-parse HEAD",await L({args:["rev-parse","HEAD"],cwd:o}));if(d(ee))return G(ee.message);u=ee.value.stdout.trim(),logger.info("[sync] final sync commit sha",u)}return Ao(p?"Synced and pushed":m||l||w.value?"Synced local state":"Already synced"),logger.info("[sync] syncEpiqWithRemote:done",{pulled:m,pushed:p,createdCommit:l,bootstrapped:i,commitSha:u}),c("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,pulled:m,pushed:p,bootstrapped:i})},Dn=async()=>{let e=Wa();if(e)return e;logger.info("[sync] syncAndReloadState:start");let t=k("resolveActorId",z());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id"),s("Unable to resolve event log path");let n=an(t.value);logger.info("[sync] resolved own event file name",{ownEventFileName:n});let r=k("syncEpiqWithRemote",await Wu({ownEventFileName:n}));if(d(r))return logger.info("[sync] syncAndReloadState:sync failed",r.message),s(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.info("[sync] loading merged events after sync",{stateBranchRoot:o});let i=k("loadMergedEvents",$t(o));if(d(i))return s(`Unable to load events. ${i.message}`);logger.info("[sync] loaded merged events after sync",{count:i.value.length});let a=Wa();if(a)return a;let l=Da(),u=k("bootStateFromEventLog",tr(i.value));if(d(u))return s(`Unable to boot synced state. ${u.message}`);logger.info("[sync] booted state from synced events"),N({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}});let m=k("restoreNavigationAnchor",Oa(l));return d(m)?m:(logger.info("[sync] syncAndReloadState:done"),c("Synced",!0))},Wa=()=>h().mode===f.DEFAULT?null:(N({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),s("Will not re-materialize if not in default mode, to not lose edit data"));import{Box as at}from"ink";import q from"react";import{Box as mr,Text as pr}from"ink";import Ke,{useEffect as _u,useMemo as ju}from"react";var bt="__epiq_palette_root__",ko="__epiq_palette_command__",Hu=e=>`${ko}${e}`,Vu=e=>{let t=new Set(X(y.NONE));return[...new Set(Object.values(y))].filter(n=>n!=="move").filter(n=>n.length>0).filter(n=>n!==y.PALETTE).map(n=>{let r=jn(n),o=sr.find(i=>i.intent===r);return{command:n,description:o?.description??`[${n}] Run command`,isAvailable:t.has(n)}}).filter(n=>n.command.toLowerCase().startsWith(e)||e.length>=2&&n.description.toLowerCase().includes(e)).sort((n,r)=>n.isAvailable!==r.isAvailable?n.isAvailable?-1:1:n.command.localeCompare(r.command))},Ku=e=>ne.text({id:bt,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),zu=(e,t,n)=>ne.text({id:Hu(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Gu=e=>{ue(t=>{let n=Ku(t.rootNodeId),r=Object.fromEntries(Object.entries(t.nodes).filter(([i])=>i!==bt&&!i.startsWith(ko))),o=Object.fromEntries(e.map((i,a)=>{let l=zu(i,a,bt);return[l.id,l]}));return{...t,mode:f.PALETTE,currentNodeId:bt,selectedIndex:e.length>0?0:-1,nodes:{...r,[bt]:n,...o}}})},qu=()=>{ue(e=>{let t=Object.fromEntries(Object.entries(e.nodes).filter(([n,r])=>n!==bt&&!n.startsWith(ko)&&!r.isVirtual));return{...e,nodes:t,currentNodeId:e.currentNodeId===bt?e.rootNodeId:e.currentNodeId,selectedIndex:0}})};function Va({width:e,height:t}){let r=es().value.trim().toLowerCase(),o=ju(()=>Vu(r),[r]);_u(()=>(Gu(o),()=>{qu()}),[o]);let i=h().selectedIndex;return Ke.createElement(mr,{flexDirection:"column",width:e,height:t-2},Ke.createElement(mr,{paddingX:1},Ke.createElement(pr,{color:x.accent},"Command Palette"),Ke.createElement(pr,{dimColor:!0}," \u2014 select a command and press enter")),Ke.createElement(Ft,{height:t-4,itemHeight:3,selectedIndex:i},o.map((a,l)=>{let u=l===i,m=a.isAvailable?x.accent:x.secondary2,p=a.isAvailable?"":"[unavailable] ";return Ke.createElement(mr,{key:a.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderColor:x.secondary,borderStyle:"single"},Ke.createElement(pr,{color:m,dimColor:!a.isAvailable,backgroundColor:u&&a.isAvailable?x.secondary:void 0},u?"\u276F ":" ",":"+a.command),Ke.createElement(mr,{paddingLeft:2},Ke.createElement(pr,{dimColor:!a.isAvailable,color:x.secondary2},p+a.description)))})))}import{Box as am}from"ink";import Fo from"react";import yn from"chalk";import{Box as Lo,Text as Ka}from"ink";import vn,{useEffect as Yu,useMemo as Xu,useState as Ju}from"react";var za=yn.gray,Qu=yn.inverse,Zu=yn.inverse.gray,em={hint:"",hints:[],overlap:0,remainder:""},qa=({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}},tm=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=ae(t);return{bg:r=>yn.bgHex(n).black(r),bgCursor:r=>yn.bgHex(n).inverse.black(r)}}return Gr(t)},nm=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=qa({value:e,command:t});if(!r)return null;let i=e.slice(r.end).match(/^\s*/)?.[0].length??0,a=r.end+i;return e.slice(a,a+n.length)!==n?null:{start:a,end:a+n.length}},Ga=()=>({value:de.value,cursorPosition:de.cursorPosition,commandIsPending:de.commandIsPending,autoCompletion:de.commandMeta.autoCompletion??em,infoMessage:de.commandMeta.infoMessage,validationStatus:de.commandMeta.validity,command:de.commandMeta.command,inputString:de.commandMeta.inputString,modifier:de.commandMeta.modifier}),rm=(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,Ya=({width:e,mode:t})=>{let[n,r]=Ju(Ga());Yu(()=>{let C=()=>{let I=Ga();r(P=>rm(P,I)?P:I)},E=Qr(C);return C(),()=>{E()}},[]);let{value:o,cursorPosition:i,infoMessage:a,commandIsPending:l,autoCompletion:u,command:m,modifier:p}=n,v=Xu(()=>{let C=Math.max(0,Math.min(i,o.length)),E=qa({value:o,command:m}),I=nm({value:o,command:m,modifier:p}),P=m?Gr(m):null,R=tm({command:m,modifier:p}),w=(ie,me)=>{let Nt=E&&me>=E.start&&me<E.end,ct=I&&me>=I.start&&me<I.end;return Nt&&P?P.fg(ie):ct&&R?R.bg(ie):ie},D=(ie,me)=>{let Nt=E&&me>=E.start&&me<E.end,ct=I&&me>=I.start&&me<I.end;return Nt&&P?P.fgCursor(ie):ct&&R?R.bgCursor(ie):Qu(ie)},ee=o.slice(0,C),oe=o[C]??" ",Fe=C<o.length?o.slice(C+1):"",dt=Array.from(ee).map((ie,me)=>w(ie,me)).join(""),Ee=D(oe,C),Vt=Array.from(Fe).map((ie,me)=>w(ie,C+1+me)).join("");if(u.hint){let ie=u.hint[u.overlap]??oe;Ee=Zu(ie),Vt=za(u.remainder.slice(1)+Fe)}return za(t===f.PALETTE?"?":":")+dt+Ee+Vt},[o,i,u,m,p]);return vn.createElement(Lo,{flexDirection:"column",justifyContent:"flex-start"},vn.createElement(Lo,{flexDirection:"column",paddingX:1,borderColor:x.secondary,borderStyle:"round",width:e},vn.createElement(Lo,null,vn.createElement(Ka,null,v),a&&vn.createElement(Ka,{wrap:"truncate",color:l?x.red:x.secondary2},` ${a} `))))};import Xa from"chalk";import{Box as om,Text as Do}from"ink";import fr from"react";var im=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),sm=(e,t)=>{let n=[],r=0;for(let o of e){let a=(n.length>0?" | ":"").length+o.length;if(r+a>t-4)break;n.push(o),r+=a}return n},Ja=({width:e,availableHints:t})=>{let n=Math.max(0,e-2),r=sm(t,e).join(" | "),o=Xa.hex(x.secondary),i=Xa.hex(x.secondary2),a=o(`\u256D${"\u2500".repeat(n)}\u256E`),l=o(`\u2570${"\u2500".repeat(n)}\u256F`),u=`${o("\u2502")}${i(im(` ${r} `,n))}${o("\u2502")}`;return fr.createElement(om,{flexDirection:"column",width:e},fr.createElement(Do,null,a),fr.createElement(Do,null,u),fr.createElement(Do,null,l))};var hn=({width:e,mode:t,availableHints:n})=>{let r=[],o=0;for(let i of n){let l=(r.length>0?" | ":"").length+i.length;if(o+l>e+2)break;r.push(i),o+=l}return Fo.createElement(am,null,t===f.COMMAND_LINE||t===f.PALETTE?Fo.createElement(Ya,{width:e,mode:t}):Fo.createElement(Ja,{width:e,mode:t,availableHints:n}))};import{Box as jt,Text as Qa}from"ink";import it from"react";var Za=({width:e})=>{let t=[...h().availableActions].map(n=>n.description).filter(n=>n!==void 0).map(n=>{let[r,o]=n.split("]"),i=r?.replace("[",""),a=o?.trim();return[i,a]}).filter(n=>n[0]!==void 0&&n[1]!==void 0).sort(([n],[r])=>n.length===1&&r.length!==1?-1:n.length!==1&&r.length===1?1:n.localeCompare(r,void 0,{sensitivity:"base"}));return t.unshift(["Key(s)","Action"]),it.createElement(jt,{flexDirection:"column",marginTop:3,borderColor:x.secondary,borderStyle:"round",width:e,minHeight:19},it.createElement(jt,{flexDirection:"column",width:e},h().mode===f.HELP?t.map(([n,r],o)=>it.createElement(jt,{paddingLeft:1,key:o,flexDirection:"row"},it.createElement(jt,{key:o,flexDirection:"row",paddingBottom:o?0:1},it.createElement(jt,{width:20,justifyContent:"flex-end"},it.createElement(Qa,{color:o?x.accent:x.secondary},n)),it.createElement(jt,{flexGrow:1,width:40,paddingLeft:2},it.createElement(Qa,{color:o?x.primary:x.secondary},r))))):null))};import dm from"chalk";import{Box as gr,Text as ze}from"ink";import Ce from"react";var ed=({width:e,height:t})=>Ce.createElement(gr,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:x.secondary,rowGap:1},Ce.createElement(ze,{color:x.accent,bold:!0},"Initialize project"),Ce.createElement(ze,null,`This folder is not an ${dm.hex(x.accent)("epiq")} project yet.`),Ce.createElement(ze,{color:x.primary},"To start tracking issues here, we need to initialize a new",Ce.createElement(ze,{color:x.primary,backgroundColor:x.secondary}," .epiq/project.json "),"file in this repository."),Ce.createElement(gr,{marginTop:1,flexDirection:"column"},Ce.createElement(gr,null,Ce.createElement(ze,{color:x.accent}," "),Ce.createElement(ze,{color:x.primary},"Type "),Ce.createElement(ze,{backgroundColor:x.secondary}," :init "))),Ce.createElement(gr,{marginTop:1},Ce.createElement(ze,{color:x.secondary2},"This will create, commit and push "),Ce.createElement(ze,{color:x.primary,backgroundColor:x.secondary}," .epiq/project.json ")));import{Box as vr,Text as Le}from"ink";import re from"react";var cm=({isDone:e,command:t,value:n})=>re.createElement(vr,null,re.createElement(Le,{color:x.accent,dimColor:e},e?" \u2714 ":" "),re.createElement(Le,{dimColor:e},"Type "),re.createElement(Le,{backgroundColor:x.secondary,dimColor:e}," "+t+" "),n!==void 0&&re.createElement(re.Fragment,null,re.createElement(Le,{dimColor:e}," "),re.createElement(Le,{color:x.secondary,dimColor:e},"<"+n+">"))),lm=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"yes":"no"};function Oo({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:i,autoSync:a,isSetAutoSync:l}=Ze(),u=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:i,message:"Nice. Now pick your editor."},{key:"autosync",done:l,command:":config autosync",value:a,message:"Almost there. Configure auto sync."}],m=u.findIndex(v=>!v.done),p=m===-1?void 0:u[m];return re.createElement(vr,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:x.secondary,rowGap:1},re.createElement(Le,{color:x.accent,bold:!0},"Welcome! \u{1F539}"),re.createElement(Le,null,"Let's get you started - it's a breeze."),re.createElement(Le,{color:x.secondary2},"Remember - you can always search available commands by typing:",re.createElement(Le,{color:x.accent}," ? ")),p&&re.createElement(Le,{color:x.secondary2},p.message),re.createElement(vr,{flexDirection:"column"},u.map((v,C)=>m===-1||C<=m?re.createElement(vr,{key:v.key,marginBottom:1},re.createElement(cm,{isDone:v.done,command:v.command,value:v.done?lm(v.value):void 0})):null)))}import xr from"chalk";import{Box as hr,Text as Ge}from"ink";import Z from"react";import{Box as Bo,Text as um}from"ink";import Ht from"react";var mm=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",td=({width:e})=>{let{viewMode:t}=$(),{breadCrumb:n,currentNode:r,selectedIndex:o}=h(),i=U(r.id)[o],a=ot(i?.id??r.id,"TICKET"),l=ce(a)?a.value:void 0,u=l?.props.tags??[],m=l?.props.assignees??[],p=l?.parentNodeId?!So(r.id,l.parentNodeId)&&t==="dense":!1,v=n.map((E,I)=>{let P=I===n.length-1,R=U(E.id),w=P?R?.[o]?.title:void 0;return`${I?" / ":""}${E.title??""}${w?` \u25B8 ${w}`:""}`}).join(""),C=mm(v,e);return Ht.createElement(Bo,null,Ht.createElement(um,{color:x.secondary2},C),p?u.map(E=>Ht.createElement(Bo,{key:E,paddingLeft:2},Ht.createElement(Bt,{id:E}))):null,p?m.map(E=>Ht.createElement(Bo,{key:E,paddingLeft:2},Ht.createElement(Ot,{id:E}))):null)};import{Box as pm,Text as nd}from"ink";import yr from"react";var fm=({filters:e})=>yr.createElement(pm,{columnGap:1},yr.createElement(nd,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>yr.createElement(nd,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),rd=yr.memo(fm);var od="0.6.1";import Uo from"chalk";import{Box as gm,Text as id}from"ink";import $o,{useEffect as vm,useState as ym}from"react";var hm=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],sd=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)}},xm=({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)}`},Cm=(e,t,n)=>{let r=sd(e),o=sd(t);return xm({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Em=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,i=e[r],a=e[Math.min(r+1,e.length-1)];return Cm(i,a,o)};function ad({syncStatus:e,autoSync:t}){let[n,r]=ym(0);vm(()=>{if(e.status!=="syncing"){r(0);return}let l=setInterval(()=>{r(u=>u+1)},50);return()=>clearInterval(l)},[e.status]);let o={synced:" ",failed:"retry",syncing:"...",pending:"wait"},a={synced:x.secondary2,failed:x.yellow,pending:x.secondary2,syncing:Em(hm,(Math.sin(n*.12)+1)/2)??""}[e.status];return $o.createElement(gm,null,$o.createElement(id,null,Uo.hex(x.secondary2).dim(t?"AutoSync: ":"Sync: ")),$o.createElement(id,null,Uo.hex(a)("\u25CF")+Uo.hex(x.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}function Cr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o,syncStatus:i,mode:a}=Q(),{userName:l,preferredEditor:u,autoSync:m}=$(),p=56,v=process.stdout.columns-p-8,C=r.at(-1)?.id,E=$n(C??""),I=ce(E)?Ui(E.value):"INVALID DATE";return Z.createElement(hr,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?Z.createElement(Ge,null," "):Z.createElement(hr,{paddingLeft:1},e.length>0?Z.createElement(rd,{filters:e}):Z.createElement(td,{width:v})),n==="live"?Z.createElement(hr,{columnGap:1,paddingRight:2,"max-width":p,overflow:"hidden",justifyContent:"flex-end"},Z.createElement(ad,{autoSync:!!m,syncStatus:i}),Z.createElement(Ge,null,xr.hex(x.secondary2).dim("Mode: ")+xr.hex(x.secondary2).dim(a.padEnd(8," "))," "),Z.createElement(dd,{icon:"@",value:l}),Z.createElement(dd,{icon:"\u276F",value:u}),Z.createElement(Ge,{dimColor:!0,color:x.secondary2},od+" ")):"",n==="peek"?Z.createElement(hr,{paddingLeft:1},Z.createElement(Ge,{backgroundColor:x.yellow}," Readonly "),Z.createElement(Ge,{color:x.yellow}," "+o.length+" edits ago at "),Z.createElement(Ge,{backgroundColor:x.yellow,color:x.accent}," "+I+" "),Z.createElement(Ge,{color:x.yellow},". Resume with "),Z.createElement(Ge,{backgroundColor:x.yellow}," :peek now ")):"")}function dd({icon:e,value:t}){return Z.createElement(Ge,null,xr.dim(e)+xr.hex(x.accent)(` ${t??"-"} `))}import{Box as bm,Text as Nm}from"ink";import xn from"react";import{Box as Er,Text as Wo}from"ink";import st from"react";function _o(){let e=Q(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,a=t?.id?O(t?.id):[];return st.createElement(Er,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:x.secondary,width:i},st.createElement(Er,{padding:1,paddingTop:0,paddingBottom:0},st.createElement(Wo,null,"Select a board:")),st.createElement(Er,{padding:1,flexDirection:"column"},a.map((l,u)=>{let m=e.currentNode.context==="WORKSPACE"&&e.selectedIndex===u,v=O(l.id).flatMap(({id:C})=>U(C)).length;return st.createElement(Er,{key:l.id??u},st.createElement(Wo,{color:m?x.accent:x.secondary2},st.createElement(ge,{isSelected:m})),st.createElement(Wo,{color:m?x.accent:x.secondary2},l.title," (",v," issues)",l.readonly?" \u{1F512}":""))})))}var Sm=({currentNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:l}=Q(),u=n.find(({context:C})=>C==="BOARD"),v=i-1-3;return xn.createElement(bm,{flexDirection:"row"},e.context==="WORKSPACE"?xn.createElement(_o,null):u?xn.createElement(qn,{height:v,width:a,swimlanes:(l[u.id]??[]).filter(C=>C!==void 0&&St(C)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):xn.createElement(Nm,null))},cd=xn.memo(Sm);function jo({width:e,height:t}){let n=Q(),r=n.filters;if(n.mode===f.HELP)return q.createElement(at,{flexDirection:"column"},q.createElement(Za,{width:e}));if(n.mode===f.PALETTE)return q.createElement(at,{flexDirection:"column"},q.createElement(Va,{width:e,height:t}),q.createElement(hn,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:o}=Ze(),i=!o,a=o&&!n.hasProjectDefinition;if(i)return q.createElement(at,{flexDirection:"column"},q.createElement(at,{flexDirection:"column"},q.createElement(Cr,{hideBreadCrumb:!0,filters:r}),q.createElement(Oo,{height:t,width:e})),q.createElement(hn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(a)return q.createElement(at,{flexDirection:"column"},q.createElement(at,{flexDirection:"column"},q.createElement(Cr,{hideBreadCrumb:!0,filters:r}),q.createElement(ed,{height:t,width:e})),q.createElement(hn,{width:e,mode:n.mode,availableHints:n.availableHints}));let l=Se(n.breadCrumb??[],"BOARD");if(ce(l)){let u=l.value.id,m=O(u).length,p=3,v=Math.floor(e/p),C=Math.floor(e/Math.max(m,1));e=Math.min(C,v)*Math.max(m,p)}return q.createElement(at,{flexDirection:"column"},q.createElement(at,{flexDirection:"column"},q.createElement(Cr,{filters:r}),q.createElement(cd,{width:e,height:t,currentNode:n.currentNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:$().viewMode??"dense",mode:n.mode})),q.createElement(hn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import Im from"readline";var br,Nr,De,Rm=new Set([g.MoveCursorLeft,g.EraseInputWord,g.MoveCursorLeftOfWord,g.MoveCursorRight,g.MoveCursorRightOfWord,g.NavToPreviousContainer,g.NavToNextContainer,g.NavPreviousItem,g.NavNextItem,g.SetViewDense,g.SetViewWide,g.Confirm,g.Exit,g.InitCommandLine,g.InitCommandPalette,g.ExitCommandLine,g.CaptureInput,g.EraseInput,g.EraseInputWord,g.HideHelp,g.ViewHelp,g.SetViewDense,g.SetViewWide,g.GetLastCommandFromHistory,g.GetNextCommandFromHistory,g.AutoCompleteCommand]),ld=async e=>{if(e.ctrl&&e.name==="c")return B.exit();let{actionIndex:t,mode:n,readOnly:r}=h(),o=as(e,n);if(!o||r&&!Rm.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(a){logger.error(a)}},Am=()=>async function(t,n){n.name!=="escape"&&(De&&(clearTimeout(De),De=void 0),await ld(n))},wm=()=>async function(t){if(t.length===1&&t[0]===27){De&&clearTimeout(De),De=setTimeout(()=>{ld({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),De=void 0},25);return}De&&(clearTimeout(De),De=void 0)};function ud(){br&&process.stdin.removeListener("keypress",br),Nr&&process.stdin.removeListener("data",Nr),br=Am(),Nr=wm(),Im.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Nr),process.stdin.on("keypress",br)}Mm(`${Sr.bold("Epiq CLI")}
|
|
62
|
+
`;var yr=e=>Te.existsSync(e)?Te.readFileSync(e,"utf8"):null,rd=(e,t)=>yr(e)===t?!1:(Te.mkdirSync(bt.dirname(e),{recursive:!0}),Te.writeFileSync(e,t,"utf8"),!0),im=({stateBranchRoot:e,ownEventFileName:t})=>bt.join(e,pt(t)),sm=async({stateBranchRoot:e,ownEventFileName:t})=>{let n=pt(t),r=bt.join(e,n);return(await Se({cwd:e,args:["checkout","--",n]})).exitCode!==0&&Te.existsSync(r)&&Te.rmSync(r,{force:!0}),l("Restored own event file to HEAD",null)},ed=({ownEventPath:e,ownSnapshot:t})=>{if(t===null)return l("No own snapshot to merge",!1);let n=yr(e)??"",r=yn(n);if(d(r))return a(r.message);let o=yn(t);if(d(o))return a(o.message);let i=Oo(r.value,o.value),s=rd(e,Bo(i));return l("Merged own snapshot",s)},am=e=>{let t=bt.join(e,".epiq","events"),n=new Map;if(!Te.existsSync(t))return l("No event files to snapshot",n);for(let r of Te.readdirSync(t)){if(!r.endsWith(".jsonl"))continue;let o=bt.join(t,r);Te.statSync(o).isFile()&&n.set(r,Te.readFileSync(o,"utf8"))}return l("Snapshotted event files",n)},dm=async e=>{if((await Se({cwd:e,args:["checkout","--",pt("")]})).exitCode!==0){let n=bt.join(e,".epiq","events");Te.existsSync(n)&&Te.rmSync(n,{recursive:!0,force:!0})}return l("Restored event files to HEAD",null)},cm=({stateBranchRoot:e,snapshots:t})=>{let n=!1;for(let[r,o]of t){let i=bt.join(e,pt(r)),s=yr(i)??"",c=yn(s);if(d(c))return a(c.message);let u=yn(o);if(d(u))return a(u.message);let m=Oo(c.value,u.value);n=rd(i,Bo(m))||n}return l("Merged event snapshots",n)},od=async(e=process.cwd())=>{logger.info("[sync] syncEpiqFromRemote:start",e),ko("Syncing from remote");let t=L("ensureSyncReady",await id({cwd:e,ensureUpstream:!1}));if(d(t))return G(t.message);let{repoRoot:n,stateBranchRoot:r}=t.value,o=L("getStateBranch",mt(n));if(d(o))return G(o.message);let i=o.value,s=L("snapshotEventFiles",am(r));if(d(s))return G(s.message);let c=L("restoreEventFilesToHead",await dm(r));if(d(c))return G(c.message);let u=L("resetBranchHardToRemote",await pi({cwd:r,branch:i}));if(d(u))return G(u.message);let m=L("mergeEventSnapshots",cm({stateBranchRoot:r,snapshots:s.value}));return d(m)?G(m.message):(Lo(m.value?"Synced and merged local state":"Synced from remote"),logger.info("[sync] syncEpiqFromRemote:done"),l("Synced state branch from remote",{repoRoot:n,stateBranchRoot:r}))},id=async({cwd:e,ensureUpstream:t})=>{logger.info("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=L("getRepoRootDir",await Pt(e));if(d(n))return a(n.message);let r=n.value;logger.info("[sync] repo root",r);let o=L("getStateBranchRoot",Pn({repoRoot:r}));if(d(o))return a(o.message);let i=o.value;logger.info("[sync] state branch root",i);let s=L("ensureInitialCommit",await ta(r));if(d(s))return a(s.message);logger.info("[sync] initial commit result",{created:s.value}),logger.info("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:i,ensureUpstream:t});let c=L("bootstrapStateBranchStorage",await ra({repoRoot:r,stateBranchRoot:i,ensureUpstream:t}));if(d(c))return a(c.message);logger.info("[sync] bootstrap result",{bootstrapped:c.value,stateBranchRoot:i}),logger.info("[sync] checking state branch git operation",{stateBranchRoot:i});let u=L("hasInProgressGitOperation(stateBranchRoot)",await An(i));if(d(u))return a(u.message);if(logger.info("[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.info("[sync] ensuring state branch layout",{repoRoot:r,stateBranchRoot:i});let m=L("ensureStateBranchLayout",Ci(r,i));return d(m)?a(m.message):(logger.info("[sync] state branch layout ready"),logger.info("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:i,bootstrapped:c.value}),l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:i,bootstrapped:c.value}))},td=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.info("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.info("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=L("stageStateBranchOwnEventFile",await ir({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=L("hasStagedChanges(after stage)",await gi(t));if(d(o))return a(o.message);if(logger.info("[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.info("[sync] creating sync commit");let i=L("createStateBranchSyncCommit",await na({repoRoot:e,stateBranchRoot:t}));return d(i)?a(i.message):(logger.info("[sync] created sync commit",i.value),l("Committed own event file",{createdCommit:!0,commitSha:i.value}))},lm=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.info("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.info("[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.info("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),a("Own event file must end with .jsonl");ko("Syncing");let n=L("ensureSyncReady",await id({cwd:e,ensureUpstream:!0}));if(d(n))return G(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value;logger.info("[sync] sync preconditions ready",{repoRoot:r,stateBranchRoot:o,bootstrapped:i}),logger.info("[sync] checking detached state branch",{stateBranchRoot:o});let s=L("isDetachedHead(stateBranchRoot)",await fi(o));if(d(s))return G(s.message);if(logger.info("[sync] detached state branch check result",{detached:s.value}),s.value)return logger.info("[sync] state branch is detached"),G("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,v=L("getStateBranch",mt(r));if(d(v))return G(v.message);let C=v.value;logger.info("[sync] resolved state branch",{stateBranch:C,stateBranchRoot:o});let E=im({stateBranchRoot:o,ownEventFileName:t}),I=yr(E),k=L("restoreOwnEventFileToHead",await sm({stateBranchRoot:o,ownEventFileName:t}));if(d(k))return G(k.message);let R=L("pullBranchRebaseIfPresent",await Wr({cwd:o,branch:C}));if(d(R))return G(R.message);m=R.value;let T=L("mergeOwnSnapshot",ed({ownEventPath:E,ownSnapshot:I}));if(d(T))return G(T.message);let O=L("commitOwnEventFileToStateBranch",await td({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(O))return G(O.message);if(c=O.value.createdCommit,u=O.value.commitSha,logger.info("[sync] sync own result",{createdCommit:c,commitSha:u}),c||i){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:i,stateBranchRoot:o});let te=L("pushStateBranch(initial)",await mn({stateBranchRoot:o,repoRoot:r})),se=te;if(d(te)&&ui(te.message)){logger.info("[sync] non-fast-forward, retrying sync");let Ue=L("pullBranchRebaseIfPresent(retry)",await Wr({cwd:o,branch:C}));if(d(Ue))return G(Ue.message);logger.info("[sync] pull retry result",Ue.value);let lt=L("mergeOwnSnapshot(retry)",ed({ownEventPath:E,ownSnapshot:I}));if(d(lt))return G(lt.message);let Ee=L("commitOwnEventFileToStateBranch(retry)",await td({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(Ee))return G(Ee.message);logger.info("[sync] retry sync result",Ee.value),Ee.value.createdCommit&&(c=!0,u=Ee.value.commitSha),se=L("pushStateBranch(retry)",await mn({stateBranchRoot:o,repoRoot:r}))}if(d(se))return G(se.message);p=se.value,logger.info("[sync] pushed to state branch",p)}else logger.info("[sync] no commit created, skipped push");if(c){logger.info("[sync] resolving final sync commit sha",{stateBranchRoot:o});let te=L("git rev-parse HEAD",await D({args:["rev-parse","HEAD"],cwd:o}));if(d(te))return G(te.message);u=te.value.stdout.trim(),logger.info("[sync] final sync commit sha",u)}return Lo(p?"Synced and pushed":m||c||T.value?"Synced local state":"Already synced"),logger.info("[sync] syncEpiqWithRemote:done",{pulled:m,pushed:p,createdCommit:c,bootstrapped:i,commitSha:u}),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:i})},Bn=async()=>{let e=nd();if(e)return e;logger.info("[sync] syncAndReloadState:start");let t=L("resolveActorId",z());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id"),a("Unable to resolve event log path");let n=ln(t.value);logger.info("[sync] resolved own event file name",{ownEventFileName:n});let r=L("syncEpiqWithRemote",await lm({ownEventFileName:n}));if(d(r))return logger.info("[sync] syncAndReloadState:sync failed",r.message),a(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o}=r.value;logger.info("[sync] loading merged events after sync",{stateBranchRoot:o});let i=L("loadMergedEvents",Wt(o));if(d(i))return a(`Unable to load events. ${i.message}`);logger.info("[sync] loaded merged events after sync",{count:i.value.length});let s=nd();if(s)return s;let c=Xa(),u=L("bootStateFromEventLog",sr(i.value));if(d(u))return a(`Unable to boot synced state. ${u.message}`);logger.info("[sync] booted state from synced events"),N({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}});let m=L("restoreNavigationAnchor",Qa(c));return d(m)?m:(logger.info("[sync] syncAndReloadState:done"),l("Synced",!0))},nd=()=>x().mode===g.DEFAULT?null:(N({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));import{Box as ct}from"ink";import q from"react";import{Box as hr,Text as It}from"ink";import ye,{useEffect as um,useMemo as mm}from"react";import{ulid as pm}from"ulid";var sd=({text:e,match:t,color:n,highlightColor:r=h.secondary,dimColor:o=!1})=>{if(!t)return ye.createElement(It,{color:n,dimColor:o},e);let i=e.toLowerCase(),s=t.toLowerCase(),c=i.indexOf(s);return c===-1?ye.createElement(It,{color:n,dimColor:o},e):ye.createElement(It,{color:n,dimColor:o},e.slice(0,c),ye.createElement(It,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},ad=pm(),gm=e=>`${e}`,fm=e=>{let{pendingNavTarget:t}=Ht();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,i=new Set(X(y.NONE,{breadCrumb:n,contextNode:r,readOnly:x().readOnly,selectedNode:o}));return[...new Set(Object.values(y))].filter(s=>s!=="move").filter(s=>s.length>0).filter(s=>s!==y.PALETTE).map(s=>{let c=Gn(s),u=ur.find(m=>m.intent===c);return{command:s,description:u?.description??`[${s}] Run command`,isAvailable:i.has(s)}}).filter(s=>s.command.toLowerCase().startsWith(e)||e.length>=2&&s.description.toLowerCase().includes(e)).sort((s,c)=>s.isAvailable!==c.isAvailable?s.isAvailable?-1:1:s.command.localeCompare(c.command))},vm=e=>oe.text({id:ad,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),xm=(e,t,n)=>oe.text({id:gm(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Uo=[],ym=e=>{dd();let t=b.createNode(vm(x().rootNodeId));d(t)||!Gt(t.value)||(Uo=[t.value,...e.map((n,r)=>xm(n,r,ad)).map(b.createNode).filter(ne).map(({value:n})=>n).filter(Gt)],M.navigate({contextNode:t.value,selectedIndex:0}))},dd=()=>{let e=Uo.map(t=>t.id);Uo=[];for(let t of e)b.deleteNode(t)};function cd({width:e,height:t}){let r=ms().value.trim().toLowerCase(),o=mm(()=>fm(r),[r]);um(()=>(ym(o),()=>{dd()}),[o]);let i=x().selectedIndex;return ye.createElement(hr,{flexDirection:"column",width:e,height:t-2},ye.createElement(hr,{paddingX:1},ye.createElement(It,{color:h.accent},"Command Palette"),ye.createElement(It,{dimColor:!0}," \u2014 select a command and press enter")),ye.createElement(Ot,{height:t-4,itemHeight:3,selectedIndex:i},o.map((s,c)=>{let u=c===i,m=s.isAvailable?h.accent:h.secondary2,p=s.isAvailable?"":"[unavailable] ";return ye.createElement(hr,{key:s.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:h.secondary,borderStyle:"single"},ye.createElement(It,{color:m,dimColor:!s.isAvailable},u?"\u276F ":" ",ye.createElement(sd,{text:Ii(s.command),match:r,color:m,dimColor:!s.isAvailable})),ye.createElement(hr,{paddingLeft:2},ye.createElement(sd,{text:p+s.description,match:r.length>=2?r:"",color:u&&s.isAvailable?h.primary:h.secondary2,dimColor:!s.isAvailable})))})))}import{Box as Pm}from"ink";import _o from"react";import Cn from"chalk";import{Box as $o,Text as ld}from"ink";import hn,{useEffect as hm,useMemo as Cm,useState as Em}from"react";var ud=Cn.gray,Sm=Cn.inverse,Nm=Cn.inverse.gray,bm={hint:"",hints:[],overlap:0,remainder:""},pd=({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}},Im=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=Ie(t);return{bg:r=>Cn.bgHex(n).black(r),bgCursor:r=>Cn.bgHex(n).inverse.black(r)}}return eo(t)},Rm=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=pd({value:e,command:t});if(!r)return null;let i=e.slice(r.end).match(/^\s*/)?.[0].length??0,s=r.end+i;return e.slice(s,s+n.length)!==n?null:{start:s,end:s+n.length}},md=()=>({value:ce.value,cursorPosition:ce.cursorPosition,commandIsPending:ce.commandIsPending,autoCompletion:ce.commandMeta.autoCompletion??bm,infoMessage:ce.commandMeta.infoMessage,validationStatus:ce.commandMeta.validity,command:ce.commandMeta.command,inputString:ce.commandMeta.inputString,modifier:ce.commandMeta.modifier}),Am=(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,gd=({width:e,mode:t})=>{let[n,r]=Em(md());hm(()=>{let C=()=>{let I=md();r(k=>Am(k,I)?k:I)},E=oo(C);return C(),()=>{E()}},[]);let{value:o,cursorPosition:i,infoMessage:s,commandIsPending:c,autoCompletion:u,command:m,modifier:p}=n,v=Cm(()=>{let C=Math.max(0,Math.min(i,o.length)),E=pd({value:o,command:m}),I=Rm({value:o,command:m,modifier:p}),k=m?eo(m):null,R=Im({command:m,modifier:p}),T=(ae,ue)=>{let Rt=E&&ue>=E.start&&ue<E.end,ut=I&&ue>=I.start&&ue<I.end;return Rt&&k?k.fg(ae):ut&&R?R.bg(ae):ae},O=(ae,ue)=>{let Rt=E&&ue>=E.start&&ue<E.end,ut=I&&ue>=I.start&&ue<I.end;return Rt&&k?k.fgCursor(ae):ut&&R?R.bgCursor(ae):Sm(ae)},te=o.slice(0,C),se=o[C]??" ",Ue=C<o.length?o.slice(C+1):"",lt=Array.from(te).map((ae,ue)=>T(ae,ue)).join(""),Ee=O(se,C),zt=Array.from(Ue).map((ae,ue)=>T(ae,C+1+ue)).join("");if(u.hint){let ae=u.hint[u.overlap]??se;Ee=Nm(ae),zt=ud(u.remainder.slice(1)+Ue)}return ud(t===g.PALETTE?"?":":")+lt+Ee+zt},[o,i,u,m,p]);return hn.createElement($o,{flexDirection:"column",justifyContent:"flex-start"},hn.createElement($o,{flexDirection:"column",paddingX:1,borderColor:h.secondary,borderStyle:"round",width:e},hn.createElement($o,null,hn.createElement(ld,null,v),s&&hn.createElement(ld,{wrap:"truncate",color:c?h.red:h.secondary2},` ${s} `))))};import fd from"chalk";import{Box as Tm,Text as Wo}from"ink";import Cr from"react";var wm=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),Mm=(e,t)=>{let n=[],r=0;for(let o of e){let s=(n.length>0?" | ":"").length+o.length;if(r+s>t-4)break;n.push(o),r+=s}return n},vd=({width:e,availableHints:t})=>{let n=Math.max(0,e-2),r=Mm(t,e).join(" | "),o=fd.hex(h.secondary),i=fd.hex(h.secondary2),s=o(`\u256D${"\u2500".repeat(n)}\u256E`),c=o(`\u2570${"\u2500".repeat(n)}\u256F`),u=`${o("\u2502")}${i(wm(` ${r} `,n))}${o("\u2502")}`;return Cr.createElement(Tm,{flexDirection:"column",width:e},Cr.createElement(Wo,null,s),Cr.createElement(Wo,null,u),Cr.createElement(Wo,null,c))};var En=({width:e,mode:t,availableHints:n})=>{let r=[],o=0;for(let i of n){let c=(r.length>0?" | ":"").length+i.length;if(o+c>e+2)break;r.push(i),o+=c}return _o.createElement(Pm,null,t===g.COMMAND_LINE||t===g.PALETTE?_o.createElement(gd,{width:e,mode:t}):_o.createElement(vd,{width:e,mode:t,availableHints:n}))};import{Box as Kt,Text as xd}from"ink";import at from"react";var yd=({width:e})=>{let t=[...x().availableActions].map(n=>n.description).filter(n=>n!==void 0).map(n=>{let[r,o]=n.split("]"),i=r?.replace("[",""),s=o?.trim();return[i,s]}).filter(n=>n[0]!==void 0&&n[1]!==void 0).sort(([n],[r])=>n.length===1&&r.length!==1?-1:n.length!==1&&r.length===1?1:n.localeCompare(r,void 0,{sensitivity:"base"}));return t.unshift(["Key(s)","Action"]),at.createElement(Kt,{flexDirection:"column",marginTop:3,borderColor:h.secondary,borderStyle:"round",width:e,minHeight:19},at.createElement(Kt,{flexDirection:"column",width:e},x().mode===g.HELP?t.map(([n,r],o)=>at.createElement(Kt,{paddingLeft:1,key:o,flexDirection:"row"},at.createElement(Kt,{key:o,flexDirection:"row",paddingBottom:o?0:1},at.createElement(Kt,{width:20,justifyContent:"flex-end"},at.createElement(xd,{color:o?h.accent:h.secondary},n)),at.createElement(Kt,{flexGrow:1,width:40,paddingLeft:2},at.createElement(xd,{color:o?h.primary:h.secondary},r))))):null))};import km from"chalk";import{Box as Er,Text as qe}from"ink";import Ce from"react";var hd=({width:e,height:t})=>Ce.createElement(Er,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},Ce.createElement(qe,{color:h.accent,bold:!0},"Initialize project"),Ce.createElement(qe,null,`This folder is not an ${km.hex(h.accent)("epiq")} project yet.`),Ce.createElement(qe,{color:h.primary},"To start tracking issues here, we need to initialize a new",Ce.createElement(qe,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json "),"file in this repository."),Ce.createElement(Er,{marginTop:1,flexDirection:"column"},Ce.createElement(Er,null,Ce.createElement(qe,{color:h.accent}," "),Ce.createElement(qe,{color:h.primary},"Type "),Ce.createElement(qe,{backgroundColor:h.secondary}," :init "))),Ce.createElement(Er,{marginTop:1},Ce.createElement(qe,{color:h.secondary2},"This will create, commit and push "),Ce.createElement(qe,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json ")));import{Box as Sr,Text as Oe}from"ink";import ie from"react";var Lm=({isDone:e,command:t,value:n})=>ie.createElement(Sr,null,ie.createElement(Oe,{color:h.accent,dimColor:e},e?" \u2714 ":" "),ie.createElement(Oe,{dimColor:e},"Type "),ie.createElement(Oe,{backgroundColor:h.secondary,dimColor:e}," "+t+" "),n!==void 0&&ie.createElement(ie.Fragment,null,ie.createElement(Oe,{dimColor:e}," "),ie.createElement(Oe,{color:h.secondary,dimColor:e},"<"+n+">"))),Dm=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"yes":"no"};function Ho({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:i,autoSync:s,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:i,message:"Nice. Now pick your editor."},{key:"autosync",done:c,command:":config autosync",value:s,message:"Almost there. Configure auto sync."}],m=u.findIndex(v=>!v.done),p=m===-1?void 0:u[m];return ie.createElement(Sr,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},ie.createElement(Oe,{color:h.accent,bold:!0},"Welcome! \u{1F539}"),ie.createElement(Oe,null,"Let's get you started - it's a breeze."),ie.createElement(Oe,{color:h.secondary2},"Remember - you can always search available commands by typing:",ie.createElement(Oe,{color:h.accent}," ? ")),p&&ie.createElement(Oe,{color:h.secondary2},p.message),ie.createElement(Sr,{flexDirection:"column"},u.map((v,C)=>m===-1||C<=m?ie.createElement(Sr,{key:v.key,marginBottom:1},ie.createElement(Lm,{isDone:v.done,command:v.command,value:v.done?Dm(v.value):void 0})):null)))}import Ir from"chalk";import{Box as br,Text as Ye}from"ink";import ee from"react";import{Box as jo,Text as Fm}from"ink";import Vt from"react";var Om=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",Cd=({width:e})=>{let{viewMode:t}=$(),{breadCrumb:n,contextNode:r,selectedIndex:o}=x(),i=U(r.id)[o],s=st(i?.id??r.id,"TICKET"),c=ne(s)?s.value:void 0,u=c?.props.tags??[],m=c?.props.assignees??[],p=c?.parentNodeId?!Mo(r.id,c.parentNodeId)&&t==="dense":!1,v=n.map((E,I)=>{let k=I===n.length-1,R=U(E.id),T=k?R?.[o]?.title:void 0;return`${I?" / ":""}${E.title??""}${T?` \u25B8 ${T}`:""}`}).join(""),C=Om(v,e);return Vt.createElement(jo,null,Vt.createElement(Fm,{color:h.secondary2},C),p?u.map(E=>Vt.createElement(jo,{key:E,paddingLeft:2},Vt.createElement(Ut,{id:E}))):null,p?m.map(E=>Vt.createElement(jo,{key:E,paddingLeft:2},Vt.createElement(Bt,{id:E}))):null)};import{Box as Bm,Text as Ed}from"ink";import Nr from"react";var Um=({filters:e})=>Nr.createElement(Bm,{columnGap:1},Nr.createElement(Ed,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Nr.createElement(Ed,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Sd=Nr.memo(Um);var Nd="0.6.3";import Ko from"chalk";import{Box as $m,Text as bd}from"ink";import Vo,{useEffect as Wm,useState as _m}from"react";var Hm=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],Id=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)}},jm=({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)}`},Km=(e,t,n)=>{let r=Id(e),o=Id(t);return jm({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Vm=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,i=e[r],s=e[Math.min(r+1,e.length-1)];return Km(i,s,o)};function Rd({syncStatus:e,autoSync:t}){let[n,r]=_m(0);Wm(()=>{if(e.status!=="syncing"){r(0);return}let c=setInterval(()=>{r(u=>u+1)},50);return()=>clearInterval(c)},[e.status]);let o={synced:" ",failed:"retry",syncing:"...",pending:"wait"},s={synced:h.secondary2,failed:h.yellow,pending:h.secondary2,syncing:Vm(Hm,(Math.sin(n*.12)+1)/2)??""}[e.status];return Vo.createElement($m,null,Vo.createElement(bd,null,Ko.hex(h.secondary2).dim(t?"AutoSync: ":"Sync: ")),Vo.createElement(bd,null,Ko.hex(s)("\u25CF")+Ko.hex(h.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}function Rr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o,syncStatus:i,mode:s}=Z(),{userName:c,preferredEditor:u,autoSync:m}=$(),p=56,v=process.stdout.columns-p-8,C=r.at(-1)?.id,E=Hn(C??""),I=ne(E)?Ki(E.value):"INVALID DATE";return ee.createElement(br,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?ee.createElement(Ye,null," "):ee.createElement(br,{paddingLeft:1},e.length>0?ee.createElement(Sd,{filters:e}):ee.createElement(Cd,{width:v})),n==="live"?ee.createElement(br,{columnGap:1,paddingRight:2,"max-width":p,overflow:"hidden",justifyContent:"flex-end"},ee.createElement(Rd,{autoSync:!!m,syncStatus:i}),ee.createElement(Ye,null,Ir.hex(h.secondary2).dim("Mode: ")+Ir.hex(h.secondary2).dim(s.padEnd(8," "))," "),ee.createElement(Ad,{icon:"@",value:c}),ee.createElement(Ad,{icon:"\u276F",value:u}),ee.createElement(Ye,{dimColor:!0,color:h.secondary2},Nd+" ")):"",n==="peek"?ee.createElement(br,{paddingLeft:1},ee.createElement(Ye,{backgroundColor:h.yellow}," Readonly "),ee.createElement(Ye,{color:h.yellow}," "+o.length+" edits ago at "),ee.createElement(Ye,{backgroundColor:h.yellow,color:h.accent}," "+I+" "),ee.createElement(Ye,{color:h.yellow},". Resume with "),ee.createElement(Ye,{backgroundColor:h.yellow}," :peek now ")):"")}function Ad({icon:e,value:t}){return ee.createElement(Ye,null,Ir.dim(e)+Ir.hex(h.accent)(` ${t??"-"} `))}import{Box as zm,Text as Gm}from"ink";import Sn from"react";import{Box as Ar,Text as zo}from"ink";import dt from"react";function Go(){let e=Z(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,s=t?.id?B(t?.id):[];return dt.createElement(Ar,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:h.secondary,width:i},dt.createElement(Ar,{padding:1,paddingTop:0,paddingBottom:0},dt.createElement(zo,null,"Select a board:")),dt.createElement(Ar,{padding:1,flexDirection:"column"},s.map((c,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,v=B(c.id).flatMap(({id:C})=>U(C)).length;return dt.createElement(Ar,{key:c.id??u},dt.createElement(zo,{color:m?h.accent:h.secondary2},dt.createElement(ve,{isSelected:m})),dt.createElement(zo,{color:m?h.accent:h.secondary2},c.title," (",v," issues)",c.readonly?" \u{1F512}":""))})))}var qm=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:s})=>{let{renderedChildrenIndex:c}=Z(),u=n.find(({context:C})=>C==="BOARD"),v=i-1-3;return Sn.createElement(zm,{flexDirection:"row"},e.context==="WORKSPACE"?Sn.createElement(Go,null):u?Sn.createElement(Zn,{height:v,width:s,swimlanes:(c[u.id]??[]).filter(C=>C!==void 0&&At(C)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Sn.createElement(Gm,null))},Td=Sn.memo(qm);function qo({width:e,height:t}){let n=Z(),r=n.filters;if(n.mode===g.HELP)return q.createElement(ct,{flexDirection:"column"},q.createElement(yd,{width:e}));if(n.mode===g.PALETTE)return q.createElement(ct,{flexDirection:"column"},q.createElement(cd,{width:e,height:t}),q.createElement(En,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:o}=tt(),i=!o,s=o&&!n.hasProjectDefinition;if(i)return q.createElement(ct,{flexDirection:"column"},q.createElement(ct,{flexDirection:"column"},q.createElement(Rr,{hideBreadCrumb:!0,filters:r}),q.createElement(Ho,{height:t,width:e})),q.createElement(En,{width:e,mode:n.mode,availableHints:n.availableHints}));if(s)return q.createElement(ct,{flexDirection:"column"},q.createElement(ct,{flexDirection:"column"},q.createElement(Rr,{hideBreadCrumb:!0,filters:r}),q.createElement(hd,{height:t,width:e})),q.createElement(En,{width:e,mode:n.mode,availableHints:n.availableHints}));let c=be(n.breadCrumb??[],"BOARD");if(ne(c)){let u=c.value.id,m=B(u).length,p=3,v=Math.floor(e/p),C=Math.floor(e/Math.max(m,1));e=Math.min(C,v)*Math.max(m,p)}return q.createElement(ct,{flexDirection:"column"},q.createElement(ct,{flexDirection:"column"},q.createElement(Rr,{filters:r}),q.createElement(Td,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:$().viewMode??"dense",mode:n.mode})),q.createElement(En,{width:e,mode:n.mode,availableHints:n.availableHints}))}import Ym from"readline";var Tr,wr,Be,Xm=new Set([f.MoveCursorLeft,f.EraseInputWord,f.MoveCursorLeftOfWord,f.MoveCursorRight,f.MoveCursorRightOfWord,f.NavToPreviousContainer,f.NavToNextContainer,f.NavPreviousItem,f.NavNextItem,f.SetViewDense,f.SetViewWide,f.Confirm,f.Exit,f.InitCommandLine,f.InitCommandPalette,f.ExitCommandLine,f.CaptureInput,f.EraseInput,f.EraseInputWord,f.HideHelp,f.ViewHelp,f.SetViewDense,f.SetViewWide,f.GetLastCommandFromHistory,f.GetNextCommandFromHistory,f.AutoCompleteCommand]),wd=async e=>{if(e.ctrl&&e.name==="c")return M.exit();let{actionIndex:t,mode:n,readOnly:r}=x(),o=hs(e,n);if(!o||r&&!Xm.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(s){logger.error(s)}},Jm=()=>async function(t,n){n.name!=="escape"&&(Be&&(clearTimeout(Be),Be=void 0),await wd(n))},Qm=()=>async function(t){if(t.length===1&&t[0]===27){Be&&clearTimeout(Be),Be=setTimeout(()=>{wd({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),Be=void 0},25);return}Be&&(clearTimeout(Be),Be=void 0)};function Md(){Tr&&process.stdin.removeListener("keypress",Tr),wr&&process.stdin.removeListener("data",wr),Tr=Jm(),wr=Qm(),Ym.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",wr),process.stdin.on("keypress",Tr)}Ia();ep(`${Mr.bold("Epiq CLI")}
|
|
63
63
|
|
|
64
|
-
${
|
|
65
|
-
${
|
|
64
|
+
${Mr.dim("Boot in directory:")}
|
|
65
|
+
${Mr.cyan("$ epiq")}
|
|
66
66
|
|
|
67
|
-
`,{importMeta:import.meta,flags:{init:{type:"boolean",default:!1}}});var
|
|
67
|
+
`,{importMeta:import.meta,flags:{init:{type:"boolean",default:!1}}});var Pd=process.stdout.columns||120,kd=process.stdout.rows||20,Pr=null,np=e=>{try{return Pr?(Pr.rerender(e),l("Rerendered app",void 0)):(Pr=Zm(e),l("Rendered app",void 0))}catch(t){return a(`Unable to render app: ${Do(t)}`)}},Ld=()=>np(tp.createElement(qo,{width:Pd,height:kd}));async function rp(){try{let e=Hs();ne(e)&&Le(e.value);let t=Ze(process.cwd()),n=[];if(ne(t)){let i=t.value,s=await od(i);if(d(s))return jt(3,s.message);let c=Wt(s.value.stateBranchRoot);if(d(c))return jt(3,c.message);n=c.value}let r=sr(n);if(d(r))return jt(4,r.message);N({hasProjectDefinition:ne(t),hasInitializingEvents:!!n.length});let o=Ld();return d(o)?jt(6,o.message):(Md(),l("Booted Epiq",void 0))}catch(e){return jt(0,Do(e))}}process.stdout.on("resize",()=>{if(Pd=process.stdout.columns||120,kd=process.stdout.rows||20,!Pr)return;let e=Ld();d(e)&&logger.info(`[boot:resize] ${e.message}`)});(async()=>{console.clear();let e=await rp();d(e)&&(logger.info(e.message),console.error(Mr.red(`Failed to boot Epiq:
|
|
68
68
|
${e.message}`)),process.exitCode=1)})();
|