epiq 0.6.2 → 0.6.4
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 +54 -54
- package/dist/mcp.js +46 -46
- 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 Dr from"chalk";import{render as pp}from"ink";import gp from"meow";import fp from"react";import we from"node:fs";import Mt from"node:path";var M={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function Ur(e){return e.context===M.WORKSPACE}function W(e){return e.context===M.TICKET}function Je(e){return e.context===M.TEXT}function Qe(e){return e.context===M.FIELD}function Xt(e){return e.context===M.FIELD_LIST}var Lt=e=>e.context===M.SWIMLANE,ni=e=>e.context===M.BOARD;var Ze={None:"none",Success:"success",Fail:"fail"},a=e=>({status:Ze.Fail,message:e,value:null}),l=(e,t)=>({status:Ze.Success,message:e,value:t}),d=e=>e.status==="fail",X=e=>e.status==="success";import{ulid as Vd}from"ulid";var Dt=24n,jd=Dt*4n,He=(1n<<jd)-1n,Kd=/^[0-9a-f]+$/;function ri(e){return!e||!Kd.test(e)?a(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function Me(e,t=Dt){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 pe(e,t){if(!e&&!t)return Me(He/2n,Dt);let n=e?ri(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?ri(t):l("Resolved upper bound",He);if(d(r))return r;let o=n.value,i=r.value;if(i<=o)return Me(He/2n,Dt);let s=(o+i)/2n;return s===o||s===i?a("No rank space available between neighbors"):Me(s,Dt)}function oi(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=He*BigInt(r+1)/(t+1n),i=Me(o,Dt);if(d(i))return i;n.push(i.value)}return l("Resolved evenly spaced ranks",n)}var Or=(e,t)=>{let n=$(e),r=oi(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:Vd(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import nn from"node:fs";import _e from"node:path";import Vr from"node:fs";import nc from"node:os";import Le from"node:path";import Jt from"node:fs";import{ulid as zd}from"ulid";import{z as Rn}from"zod";var Gd="_epiq/_evt",qd=Rn.object({projectId:Rn.string().min(1),stateBranch:Rn.string().min(1),createdAt:Rn.iso.datetime()}),ii=()=>({projectId:zd(),stateBranch:Gd,createdAt:new Date().toISOString()}),et=e=>{let t=Tn(e);if(!Jt.existsSync(t))return a("Missing .epiq/project.json");try{let n=Jt.readFileSync(t,"utf8"),r=JSON.parse(n),o=qd.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")}},si=e=>{let t=et(e);return d(t)?a(t.message):l("Read projectId",t.value.projectId)},ai=({repoRoot:e,fileContents:t})=>{let n=An(e),r=Tn(e);try{if(Jt.mkdirSync(n,{recursive:!0}),Jt.existsSync(r)){let o=et(e);return d(o)?a(o.message):l("Project already initialized",null)}return Jt.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 $r=(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 Qt from"fs";import ci from"path";import Yd from"util";var di=1e3,Xd=50,Hr=0,li=()=>{let e=process.cwd(),t=wn(e);if(!d(t))return ci.join(t.value,We,"log","epiq.log")};function Jd(){let e=li();if(!e||!Qt.existsSync(e))return;let n=Qt.readFileSync(e,"utf8").split(`
|
|
4
|
+
`);if(n[n.length-1]===""&&n.pop(),n.length<=di)return;let r=n.slice(-di).join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`;
|
|
7
|
-
`;
|
|
8
|
-
`);u(n?{stdout:
|
|
9
|
-
`)))}),o.on("close",
|
|
10
|
-
`)));return}u(
|
|
11
|
-
${n.message}`);let r=await D({args:["rev-parse","HEAD"],cwd:e});return d(r)?
|
|
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 K.pullRebase({cwd:e,remote:
|
|
17
|
-
${i.message}`):
|
|
18
|
-
`+e.message);let t=
|
|
19
|
-
`+t.message):
|
|
6
|
+
`;Qt.writeFileSync(e,r,"utf8")}function Wr(e,t,n=!1){let r=li();if(!r)return;let o=Yd.format(...t),i=new Date,c=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
|
|
7
|
+
`;Qt.mkdirSync(ci.dirname(r),{recursive:!0}),Qt.appendFileSync(r,c,"utf8"),Hr++,Hr>=Xd&&(Hr=0,Jd())}var le={info(...e){Wr("[Info]",e,!1)},debug(...e){Wr("[debug]",e,!0)},error(...e){let t=e.find(n=>n instanceof Error)instanceof Error?void 0:new Error().stack;Wr("[Error]",[...e,t].filter(Boolean),!1)}};globalThis.logger=le;import{spawn as Qd}from"node:child_process";import Mn from"node:fs";import Zt 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 yt=e=>{let t=tt(e);if(d(t))return a("Unable to resolve epiq project root");let n=et(t.value);return d(n)?a("Unable to read project.json"):l("Resolved state branch",n.value.stateBranch)},ge="origin";var ui=1e4,Zd={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},pi=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Mn.existsSync(t)){let g=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:g,exitCode:1});return}r(a(g));return}let o=Qd("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Zd}),i=!1,s="",c="",u=g=>{i||(i=!0,clearTimeout(m),r(g))},m=setTimeout(()=>{o.kill("SIGTERM");let g=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${ui}ms`].join(`
|
|
8
|
+
`);u(n?{stdout:s,stderr:g,exitCode:124}:a(g))},ui);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",g=>{s+=g}),o.stderr.on("data",g=>{c+=g}),o.on("error",g=>{if(n){u({stdout:s,stderr:g.message,exitCode:1});return}u(a([`git ${e.join(" ")}`,`cwd=${t}`,g.message].join(`
|
|
9
|
+
`)))}),o.on("close",g=>{let y=g??1;if(n){u({stdout:s,stderr:c,exitCode:y});return}if(y!==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:y}))})}),D=({args:e,cwd:t})=>pi({args:e,cwd:t,allowFail:!1}),Se=({args:e,cwd:t})=>pi({args:e,cwd:t,allowFail:!0}),Ft=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())},ec=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",Zt.isAbsolute(n)?n:Zt.resolve(e,n))},tc=async e=>{let t=await ec(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(Mn.existsSync(Zt.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(Mn.existsSync(Zt.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)},Pn=async e=>{let t=await tc(e);return d(t)?a(t.message):l("Checked for in-progress Git operation",t.value!==null)},_r=async({repoRoot:e})=>{let n=(await Se({args:["remote","get-url",ge],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},en=async({repoRoot:e,branch:t})=>{let n=await Se({args:["ls-remote","--heads",ge,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${ge}/${t}`):l("Checked remote branch",n.stdout.trim().length>0)},kn=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}`)},mi=e=>{try{return Mn.realpathSync.native(e)}catch{return Zt.resolve(e)}},gi=async({repoRoot:e,worktreeRoot:t})=>{let n=await D({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let r=mi(t),o=n.value.stdout.split(`
|
|
13
|
+
`).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(mi).includes(r);return l("Checked worktree registration",o)},jr=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)},Ln=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())},fi=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())},vi=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),xi=async e=>(await Se({cwd:e,args:["rebase","--abort"]})).exitCode===0?l("Aborted stale rebase",!0):l("No rebase to abort",!1),yi=async({cwd:e,branch:t})=>{let n=await en({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:ge,branch:t});if(d(r))return a(`Failed to fetch ${t}
|
|
14
|
+
${r.message}`);let o=await xi(e);if(d(o))return a(o.message);let i=await D({cwd:e,args:["reset","--hard",`${ge}/${t}`]});return d(i)?a(`Failed to reset ${t} from remote
|
|
15
|
+
${i.message}`):l("Reset branch from remote",!0)},Kr=async({cwd:e,branch:t})=>{let n=await en({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 xi(e);if(d(r))return a(r.message);let o=await K.fetch({cwd:e,remote:ge,branch:t});if(d(o))return a(`Failed to fetch ${t}
|
|
16
|
+
${o.message}`);let i=await K.pullRebase({cwd:e,remote:ge,branch:t});return d(i)?a(`Failed during pull --rebase
|
|
17
|
+
${i.message}`):l("Pulled with rebase",!0)},hi=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 Ci=async e=>{let t=await Ln(e);return d(t)?a(t.message):l("Checked detached HEAD state",t.value==="HEAD")};var Ei="4b825dc642cb6eb9a060e54bf8d69288fbee4904",ht=e=>Le.join(We,Bn,e),Si=()=>Le.join(nc.homedir(),be),Dn=()=>Le.join(Si(),"worktrees"),Bt=({repoRoot:e})=>{let t=si(e);return d(t)?a(t.message):l("Resolved state branch root",Le.join(Dn(),t.value))},rc=e=>Le.join(e,We),Ni=e=>Le.join(rc(e),Bn);var tn=e=>{try{return Vr.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},Fn=()=>{let e=tn(Si());if(d(e))return a(`Ensure epiq home failed.
|
|
18
|
+
`+e.message);let t=tn(Dn());return d(t)?a(`Ensure worktrees dir failed.
|
|
19
|
+
`+t.message):l("Ensured epiq storage",!0)},bi=e=>{Vr.existsSync(e)&&(le.debug("[sync] remove path",e),Vr.rmSync(e,{recursive:!0,force:!0}))};var Ii=(e,t)=>{for(let n of[Ni(e),Ni(t)]){let r=tn(n);if(d(r))return a(r.message)}return l("Ensured state branch",void 0)},Ri=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 Rt({cwd:e,message:"[epiq:repair-storage-branch]"});return d(i)?s(i.message):c("Cleaned storage branch",!0)},At=kr(async(e=process.cwd())=>{let t=await D({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=>Te.resolve(e)),Hp=kr(async e=>{let t=await D({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return s(t.message);let n=t.value.stdout.trim(),r=Te.isAbsolute(n)?n:Te.join(e,n);return c("Resolved git dir",r)},e=>Te.resolve(e));var Yp=process.env.IS_LOCAL==="true",Oe=".epiq",Ee=".epiq-global",Mn="events",$d="project.json",En=e=>Ue.join(e,Oe),Sn=e=>Ue.join(En(e),$d),Qt=e=>Ue.join(En(e),Mn),hi=e=>Ue.join(e,Oe),Wd=e=>{let t=Ue.join(e,Oe);return Jt.existsSync(t)&&Jt.statSync(t).isDirectory()},$r=e=>{let t=Sn(e);return Jt.existsSync(t)&&Jt.statSync(t).isFile()},It=e=>{let t=Ue.resolve(e);for(;;){if(Wd(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($r(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}},Ci=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")}},Ae=async()=>{let e=await At(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 gu}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)+"...",Ei=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var Si=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},Ni=(e,t)=>t?e.get(t)??[]:[];var bi=new WeakMap,_d=e=>{let t=bi.get(e);return t||(t=Si(e),bi.set(e,t)),t};var Ii=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Ni(_d(e),r).filter(i=>Pn(r,i)>=n)};var Hd={hint:"",hints:[],overlap:0,remainder:""},Ri=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Hd;let o=Ii({wordList:r,inputToMatch:e,overlapThreshold:1});return jd(t,o)},jd=(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?":":" "),x=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:x}};var Ln={autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},$=()=>Ln,Me=e=>(Ln={...Ln,...e},Ln);var wt=3e3,Ai=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<wt?null:t},wi=0,Wr,_r=!1,Zt=!1,Hr=()=>{if(_r)return!0;let e=Qe();return d(e)?!1:e.value.syncStatus.status==="syncing"},Kd=()=>{let e=$().autoSyncIntervalMs??1e4,t=Date.now()-wi;return Math.max(0,e-t)},Ti=()=>{Wr||(Wr=setTimeout(async()=>{if(Wr=void 0,!!Tt()){if(Hr()){Zt=!0;return}Zt=!1,await Vd()}},Kd()))},Vd=async()=>{if(!Tt())return s("Cannot auto-sync before state is initialized");if(Hr())return Zt=!0,s("Sync already in progress");_r=!0,wi=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Dn()}finally{_r=!1,Zt&&Ti()}},Mi=()=>{Tt()&&(Zt=!0,!Hr()&&Ti())};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}},Pi=()=>{let e=Je(process.cwd());if(d(e))return!1;let t=Xe(e.value);return te(t)},ki=e=>e===!0?"yes":e===!1?"no":null,Li=e=>e==="yes"?!0:e==="no"?!1:null;var ae={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:ae.cyan,accent2:ae.magenta,primary:ae.white,secondary:ae.grayDark,secondary2:ae.grayLight,gray:ae.gray,green:ae.green,yellow:ae.yellow,red:ae.red};var S={red:ae.red,yellow:ae.yellow,green:ae.green,blue:ae.blue,magenta:ae.magenta,cyan:ae.cyan},Mt={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 zd=e=>e.props.tags??[],Gd=e=>e.props.assignees??[],jr=e=>zd(e).map(t=>b.getTag(t)).filter(t=>!!t),Kr=e=>Gd(e).map(t=>b.getContributor(t)).filter(t=>!!t),Fn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!W(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",jr(n))},Bn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!W(n)?s("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",Kr(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 qd=/^(\d+)(h|d|w|mo|y)$/,Yd=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Xd=({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},Jd=(e,t=new Date)=>{let n=e.match(qd);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}},Qd=e=>{let t=e.match(Yd);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,x=a?Number(a):0;return Xd({year:l,month:u,day:m,hour:p,minute:x})?new Date(l,u-1,m,p,x):null},On=e=>{let t=e.trim().toLowerCase();return Jd(t)??Qd(t)},Di=({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}],Fi=(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 ec=["BOARD","TICKET","SWIMLANE"],ne={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs"},et={TITLE:"title",DESCRIPTION:"description"},tc=[ne.EDITOR,ne.VIEW,ne.USERNAME,ne.AUTOSYNC,ne.SYNC_DEBOUNCE_MS],nc=[et.TITLE,et.DESCRIPTION],zr=[String(wt),"5000","15000","30000","60000"],mt=[y.SYNC,y.HELP,y.EXPORT,y.CONFIG],Un=[y.NEW,y.EDIT,y.DELETE,y.MOVE],Vr=[y.TAG,y.UNTAG,y.ASSIGN,y.UNASSIGN,y.CLOSE_ISSUE,y.RE_OPEN_ISSUE,y.EDIT],Bi=[y.FILTER,y.PEEK],rc={WORKSPACE:[...mt,...Un],BOARD:[...Bi,...mt,...Un],SWIMLANE:[...Bi,...mt,...Un],TICKET:[...mt,...Un,...Vr],FIELD:[...mt,...Vr],FIELD_LIST:[...mt,...Vr],TEXT:[...mt]},oc=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],ic=()=>{let{selectedNode:e,readOnly:t,breadCrumb:n}=v(),{isSetupDone:r}=Ze();if(!r)return[y.HELP,y.CONFIG];if(!Pi())return[y.HELP,y.INIT];if(t)return[y.HELP,y.PEEK,y.EXPORT,y.CONFIG];let o=e?.context,i=o&&ec.includes(o);return[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?rc[l]:[]))].filter(l=>l===y.MOVE?!1:l===y.EDIT||l===y.DELETE?i:!0)},X=e=>{let{contextNode:t}=v(),n=t.context??"WORKSPACE";return{[y.NONE]:ic(),[y.EXIT]:["confirm"],[y.EXPORT]:[],[y.SYNC]:[],[y.INIT]:[],[y.HELP]:[],[y.PEEK]:[...Fi(),"now","prev","next"],[y.EDIT]:[...nc],[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(Mt),...b.getExistingTags()])],[y.UNTAG]:[...Fn()?.value?.map(({name:o})=>o)??[]],[y.UNASSIGN]:[...Bn()?.value?.map(({name:o})=>o)??[]],[y.ASSIGN]:b.getExistingAssignees(),[y.NEW]:oc(n),[y.CONFIG]:[...tc]}[e]??[]};import kt from"chalk";var Oi=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import{decodeTime as Ui}from"ulid";var $i=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"},Wi=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(Ui(e)))}catch(t){return s("Decoding failed + "+t.message)}},Gr=e=>{if(!e?.id)return null;try{return Ui(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 Pt from"chalk";var Yr={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},sc=(e,t,n)=>Math.max(t,Math.min(n,e)),qr=(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},ac=(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 x=o-i/2;return[Math.round((u+x)*255),Math.round((m+x)*255),Math.round((p+x)*255)]},dc=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,cc=(e,t,n)=>[Math.round(qr(e[0],t[0],n)),Math.round(qr(e[1],t[1],n)),Math.round(qr(e[2],t[2],n))],en=e=>{let n=_i(e)%360,r=ac(n,Yr.stringColor.saturation,Yr.stringColor.lightness);return dc(r)},lc=e=>{let t=Yr.gradient.stops,n=sc(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 cc(t[i],t[i+1],a)},Wn=e=>_i(e.toLowerCase().trim())/4294967295,Hi=e=>{let t=Wn(e);return lc(t)},uc=e=>{let[t,n,r]=Hi(e);return{normal:o=>Pt.bgRgb(t,n,r).black(o),cursor:o=>Pt.bgRgb(t,n,r).white.bold(o)}},Xr=e=>{let[t,n,r]=Hi(e);return{fg:o=>Pt.rgb(t,n,r)(o),fgCursor:o=>Pt.rgb(t,n,r).inverse(o),bg:o=>Pt.bgRgb(t,n,r).black(o),bgCursor:o=>Pt.bgRgb(t,n,r).white.bold(o)}},Jr=e=>uc(e).normal(` ${e} `),de=(e,t=Mt)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:en(r)};var pt={None:"none",Invalid:"invalid",Valid:"valid"};var mc=["BOARD","TICKET","SWIMLANE"],ji=()=>{let e=v().selectedNode;return e?.context?mc.includes(e.context)?j():B({message:"Command not available in this context"}):B({message:"Missing target context"})},J="<ENTER> to confirm",j=(e="",t=[])=>({message:e,validity:pt.Valid,completionWordList:t}),B=({message:e,completionWordList:t=[]})=>({validity:pt.Invalid,message:e,completionWordList:t}),_n=e=>e.length===0,ve=({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(x=>x.startsWith(a))].sort((x,C)=>Wn(x)-Wn(C)).slice(0,r).map(Jr).join(" ");return p?`${e}${p}${n}`:""},Qr=({modifier:e})=>{let t="confirm";return e===t?j(J):B({message:_n(e)?`if you are certain, enter ${Jr(t)}`:"",completionWordList:[t]})},pc=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?B({message:n}):j():B({message:_n(r)?t:"",completionWordList:[...e]}),tn=({hint:e})=>({modifier:t,inputString:n})=>_n(t)&&_n(n)?B({message:e,completionWordList:[]}):j(J),fc=({modifier:e,inputString:t})=>{let n=X(y.CONFIG);if(!n.includes(e))return B({message:ve({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ne.EDITOR:{let r=[...Oi];return t.trim()?r.includes(t.trim())?j(J):B({message:ve({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):B({message:ve({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ne.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?j(J):B({message:ve({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ne.USERNAME:return t.trim()?j(J):B({message:`Enter a user name. Saved in ${kt.bgBlack("~/.epiq-global/config.json")}`});case ne.AUTOSYNC:{let r=["yes","no"],o=$().autoSync;if(!r.includes(t.trim())){let i=ki(o);return B({message:ve({prefix:`should auto-sync (recommended)${i!==null?", currently: "+i:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return j(J)}case ne.SYNC_DEBOUNCE_MS:{let r=$().autoSyncIntervalMs,o=Ai(t);if(!t.trim()||o===null||o<wt){let i=ve({prefix:" examples: ",wordList:zr,minLengthForHints:0,inputString:t});return B({message:`provide duration above ${wt}ms. current duration: ${r}ms.`+i,completionWordList:zr})}return j(J)}default:return B({message:"Unknown config option",completionWordList:n})}},gc=({modifier:e})=>{let t=X(y.EDIT);if(!t.includes(e)){let i=ve({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return B({message:i||"Unknown edit option",completionWordList:t})}let{breadCrumb:n,selectedNode:r}=v();if(!Se([...n,r],"TICKET"))return B({message:"Command not available in this context"});switch(e){case et.TITLE:return j(J);case et.DESCRIPTION:return j("<ENTER> to edit in "+$().preferredEditor);default:return B({message:"Unknown edit option",completionWordList:t})}},vc={[y.EXPORT]:()=>j(J+", and create export markdown file"),[y.PEEK]:e=>{let t=e.modifier;if(t==="now")return j(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 j(J);let r=On(t);if(!t||!r)return B(n);let o=Se(v().breadCrumb,"BOARD");if(d(o))return B({message:"Command is not applicable in this context"});let i=$n(o.value.id);return d(i)?B({message:"Unable to peek: board id is not a valid ULID"}):Di({date:r,horizonDate:i.value})?j(J):B({message:kt.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[y.EXIT]:()=>j(J+" and exit the application"),[y.INIT]:()=>j(J),[y.PALETTE]:()=>j(J),[y.FILTER]:e=>{if(e.modifier==="clear")return j();let t=i=>X(y.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return B({message:ve({wordList:X(y.FILTER),inputString:e.inputString}),completionWordList:X(y.FILTER)});let n=Object.values(v().tags).map(i=>i.name),r=Object.values(v().contributors).map(i=>i.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?B({message:ve({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):j():B({message:ve({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[y.NONE]:e=>{let t=X(y.NONE);return B({message:ve({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[y.NEW]:e=>pc({list:X(y.NEW),hint:ve({wordList:X(y.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[y.HELP]:()=>j(J),[y.EDIT]:gc,[y.CONFIG]:fc,[y.DELETE]:e=>{let t=ji();return t.validity==="invalid"?t:Qr(e)},[y.CLOSE_ISSUE]:e=>Qr(e),[y.RE_OPEN_ISSUE]:e=>Qr(e),[y.MOVE]:e=>{let t=ji();return t.validity==="invalid"?t:tn({hint:ve({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().map(r=>` ${kt.bgHex(de(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 B({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${kt.bgHex(de(r))(" "+r+" ")} `).slice(0,10);return n.length?tn({hint:" ... "+n.join("")})(e):B({message:"Issue has no tags",completionWordList:[]})},[y.ASSIGN]:e=>{let t=b.getExistingAssignees().map(n=>` ${kt.bgHex(de(n))(" "+n+" ")} `).slice(0,10);return tn({hint:"assign to... "+t.join("")})(e)},[y.UNASSIGN]:e=>{let t=Bn();if(d(t))return B({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${kt.bgHex(de(r))(" "+r+" ")} `).slice(0,10);return n.length?tn({hint:"remove assignee... "+n.join("")})(e):B({message:"Issue has no assignees",completionWordList:[]})},[y.SYNC]:()=>j(J)},Ki=Object.fromEntries(Object.entries(vc).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Vi=["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 zi=e=>Object.values(y).includes(e),Gi=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:l,completionWordList:u}=Ki[n].validate(n,r,i),m=o==="command"||o==="modifier"?X(n):Vi,{mode:p}=v(),x=p===f.COMMAND_LINE?a??"":"",C=[...u,...m];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:x,autoCompletion:t?Ri(e,C):{hint:"",hints:[],remainder:"",overlap:0}}};var qi=e=>{let t=e.trimStart(),n=yc(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),a=hc(e),l=zi(r)?r:null,u=l!==null,m=r!=="",p=l?X(l)??[]:[],x=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=xc(t,l,x);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:a,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:i,modifier:x,target:C,inputToMatch:E,inputString:I}},xc=(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},yc=e=>e.trim()?e.trim().split(/\s+/):[],hc=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as Cc}from"react";var Lt=e=>e===Zr||e===":",Zr=" ",ce={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:pt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},eo=new Set,Yi=()=>{for(let e of eo)e()},to=e=>(eo.add(e),()=>eo.delete(e)),$e=e=>{let n=e(ce),r=qi(n.value),o=n.cursorPosition===n.value.length;ce={...n,commandMeta:Gi(r,o)},Yi()},nn=({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,Yi(),c(e,null)},no=e=>{$e(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},ro=e=>{$e(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Lt(n[o-1]);)o--;for(;o>0&&!Lt(n[o-1]);)o--}else{for(;o<n.length&&!Lt(n[o]);)o++;for(;o<n.length&&Lt(n[o]);)o++}return{...t,cursorPosition:o}})},Xi=()=>{$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}})},Ji=()=>{$e(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Lt(t[r-1]);)r--;for(;r>0&&!Lt(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}})},Qi=()=>{$e(e=>({...e,commandIsPending:!0}))},Zi=({addToHistory:e=!0})=>{$e(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),Ec()},es=()=>{$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}})},ts=()=>{$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}})},Ec=()=>_(()=>""),V=()=>ce,ns=()=>Cc(to,V,V),rs=()=>{let[e,...t]=ce.value.split(Zr);return t.join(Zr).trim()};var os=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",is=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",ss=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",as=(e,t)=>{if(is(e,e.sequence))return g.MoveCursorLeftOfWord;if(ss(e,e.sequence))return g.MoveCursorRightOfWord;if(os(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}},ds=(e,t)=>{if(is(e,e.sequence))return g.MoveCursorLeftOfWord;if(ss(e,e.sequence))return g.MoveCursorRightOfWord;if(os(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 Sc(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function Nc(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function bc(e,t,n){let r=v().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 cs(e,t){let n=V();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 as(e,n.value);if(t===f.PALETTE)return ds(e,n.value);let r=Sc(e)||Nc(e);if(r)return Ic(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 Ic(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 bc(v().contextNode.childRenderAxis,e,n)}var Hn=e=>{let{context:t}=v().contextNode;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 ge}from"ulid";import Cs from"node:fs";import Jc from"node:path";import Qc from"react";import{Box as Yc}from"ink";import Gn from"react";import{Box as so,Text as Oc}from"ink";import Pe from"react";import{Text as ls}from"ink";import us,{useEffect as ms,useState as Rc}from"react";var ps={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},fe=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Q(),r=ps[n]??ps.default,[o,i]=Rc(0);if(ms(()=>{i(0)},[r]),ms(()=>{if(!e)return;let l=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return us.createElement(ls,null,t);let a=r[o]??r[0]??t;return us.createElement(ls,{color:h.accent,dimColor:o===1},a)};import{Box as oo,Text as Ac}from"ink";import jn from"react";var Dt=({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),x=p+l,C=e.slice(p,x),E=e.length>l,I=i,k=E?Math.max(1,Math.floor(l/e.length*I)):I,R=Math.max(0,I-k),w=Math.max(1,e.length-l),F=E?Math.floor(p/w*R):0;return jn.createElement(oo,{flexDirection:"row",height:i,width:"100%"},jn.createElement(oo,{flexDirection:"column",flexGrow:1,height:i},C),jn.createElement(oo,{flexDirection:"column",width:1,height:I},Array.from({length:I}).map((ee,ie)=>jn.createElement(Ac,{key:ie,color:E&&ie>=F&&ie<F+k?h.accent:h.secondary},E?"\u2502":" "))))};import{Box as Kn,Text as Dc}from"ink";import ft from"react";import{Text as wc}from"ink";import Tc from"react";var Mc=e=>e.toLowerCase().trim(),Pc=(e,t=Mt)=>{let n=Mc(e);return t[n]?t[n]:en(n)},Ft=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return Tc.createElement(wc,{underline:t,color:Pc(n.name)},"@"+n.name)};import{Text as kc}from"ink";import Lc from"react";var Bt=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return Lc.createElement(kc,{underline:t,backgroundColor:de(n.name),color:h.primary}," "+n.name+" ")};var fs=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=kn(Ei(t.title),r),i=jr(t),a=Kr(t);return ft.createElement(Kn,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?h.accent:h.secondary,justifyContent:"space-between"},ft.createElement(Kn,{borderBottom:!0},ft.createElement(Kn,{paddingLeft:1,flexDirection:"column"},ft.createElement(Dc,{color:h.primary},o))),ft.createElement(Kn,{flexDirection:"row",paddingLeft:1},i.map(l=>ft.createElement(Bt,{key:l.id,id:l.id})),a.map(l=>ft.createElement(Ft,{key:l.id,id:l.id}))))};import Fc from"chalk";import{Box as rn,Text as io}from"ink";import We from"react";var Bc=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,gs=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=(t.props.tags??[]).map(E=>b.getTag(E)).filter(E=>!!E),a=(t.props.assignees??[]).map(E=>b.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(io,{color:de(E.name)},"\u25A0"))),x=a.map(E=>We.createElement(rn,{key:E.id,paddingRight:l},We.createElement(io,{color:en(E.name)},"@"+E.name.at(0)))),C=n?h.accent:o===f.MOVE?h.secondary:h.primary;return We.createElement(rn,{borderBottom:!0,justifyContent:"space-between"},We.createElement(rn,null,We.createElement(fe,{isSelected:n,placeholder:Fc.dim.gray(r+1+" ")}),We.createElement(io,{wrap:"truncate",color:C},Bc(t.title,e-u-m-14))),We.createElement(rn,null,p,x))};import Uc from"chalk";var $c=({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} ${Uc.hex(h.secondary2).dim("("+m.length+")")}`,x=3,C=o?1:4,E=r-x-(o?2:1),I=Pe.createElement(so,{borderStyle:"round",borderColor:h.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Pe.createElement(fe,{isSelected:t}),Pe.createElement(Oc,{bold:!0,color:t?h.accent:h.primary},p," ",e.readonly?"\u{1F512}":"")),k=(R,w)=>{let F=i&&a===w;return o?Pe.createElement(gs,{key:R.id,index:w,width:n,ticket:R,isSelected:F,mode:l}):Pe.createElement(fs,{key:R.id,width:n,ticket:R,isSelected:F})};return Pe.createElement(so,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?h.accent:h.secondary,paddingRight:1,paddingLeft:1,height:r},I,Pe.createElement(so,{padding:o?1:0},m.length>0&&Pe.createElement(Dt,{selectedIndex:a,height:E,itemHeight:C},m.map(k)),Pe.createElement(fe,{isSelected:i&&a===-1})))},vs=Pe.memo($c);import{Box as lo,Text as zc}from"ink";import nt,{useMemo as ys}from"react";import{decodeTime as Wc,encodeTime as _c}from"ulid";var Hc="0123456789ABCDEFGHJKMNPQRSTVWXYZ",jc=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+=Hc[Number(n%32n)];return r},tt=(e,t)=>{let n=Wc(e);return _c(n,10)+jc(`${e}:${t}`)};import{Box as Vn,Text as Kc}from"ink";import _e from"react";var xs=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Q(),{title:o}=t,i=t.parentNodeId?b.getNode(t.parentNodeId):void 0,a=i&&W(i)?o===Y.ASSIGNEES?i.props.assignees??[]:o===Y.TAGS?i.props.tags??[]:[]:[];return _e.createElement(Vn,{alignItems:"center",paddingTop:1},_e.createElement(Vn,{minWidth:12},_e.createElement(fe,{isSelected:n}),_e.createElement(Kc,{color:n?h.accent:h.secondary2},o,":")),_e.createElement(Vn,{flexDirection:"row",marginLeft:1,paddingRight:1},a.map((l,u)=>{let m=r.id===t.id&&u===e;return _e.createElement(Vn,{key:`${o}-${l}`,paddingRight:2,minHeight:1},_e.createElement(fe,{isSelected:m}),o===Y.ASSIGNEES?_e.createElement(Ft,{isSelected:m,id:l}):o===Y.TAGS?_e.createElement(Bt,{isSelected:m,id:l}):null)})))};import{Box as zn,Text as ao}from"ink";import He,{useEffect as Vc}from"react";var re={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 co=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:a,contextNode:l}=Q(),u=C=>String(C).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];Vc(()=>{let C=[];return m.forEach((E,I)=>{let k=Re(BigInt(I+1));if(!te(k))return;let R=re.text({id:`${e}-${I}`,name:`Line ${I+1}`,parentNodeId:e,rank:k.value,props:{value:E},readonly:!0,isVirtual:!0}),w=b.createNode(R);te(w)&&C.push(w.value.id)}),()=>C.forEach(b.deleteNode)},[e,n]);let p="\u2029",x=m.map((C,E)=>{let I=l.id===e&&a===E;return He.createElement(zn,{key:`${e}-${E}`},He.createElement(ao,{color:I?h.primary:h.secondary2,dimColor:!I},`${E+1} `.padStart(5,"\xA0")),He.createElement(ao,{backgroundColor:I?"gray":""},u(C.length?kn(C,i-10):p)))});return He.createElement(zn,{flexDirection:"column",paddingTop:1},He.createElement(zn,null,He.createElement(fe,{isSelected:o}),He.createElement(ao,{color:o?h.accent:h.secondary2},t)),He.createElement(zn,{flexDirection:"row",borderStyle:"round",borderColor:h.secondary,paddingLeft:1,marginLeft:1},He.createElement(Dt,{scrollByOne:!0,children:x,height:r-2,selectedIndex:a,itemHeight:1})))};var Gc=e=>tt(e,"description"),qc=e=>tt(e,"history"),hs=({ticket:e,height:t})=>{let{selectedIndex:n,contextNode:r}=Q(),o=process.stdout.columns||120,i=ys(()=>Gc(e.id),[e.id]),a=ys(()=>qc(e.id),[e.id]),l=r.id===e.id,u=r.id===a||r.parentNodeId===a,m=O(e.id);if(u){let R=b.getNode(a),w=R&&qe(R)?R.props.value??"":"",ee=t-3;return nt.createElement(lo,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R?nt.createElement(co,{id:R.id,label:"Event log",text:w,selected:!1,maxWidth:o,height:ee}):null)}let p=m.reduce((R,w)=>Vt(w)||w.id===a?R+1:R,0),x=2,C=3,E=p,I=t-C-E-x,k=(R,w)=>R.id===i?nt.createElement(co,{key:R.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:w,maxWidth:o,height:I}):Vt(R)?nt.createElement(xs,{key:R.id,parent:R,selected:w,selectedIndex:n}):R.id===a?nt.createElement(lo,{key:R.id,paddingTop:1},nt.createElement(fe,{isSelected:w}),nt.createElement(zc,{backgroundColor:h.secondary,color:w?h.accent:h.primary}," History \u203A\u203A ")):null;return nt.createElement(lo,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((R,w)=>k(R,l&&n===w)))};var Xc=({swimlanes:e,contextNode: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,x=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),k=i==="dense";return Gn.createElement(Yc,{flexDirection:"row",height:a},p&&e.map((R,w)=>{let F=t.id===R.id,ee=F?n:-1,ie=t.context===A.BOARD&&n===w;return Gn.createElement(vs,{key:R.id,height:a,width:I,swimlane:R,isSelected:ie,isDense:k,isFocused:F,listSelectedIndex:ee,mode:o})}),m&&x&&Gn.createElement(hs,{height:a,ticket:x}))},qn=Gn.memo(Xc);import{render as Zc}from"ink";import{Writable as el}from"node:stream";var on=e=>String(e).padStart(2,"0"),tl=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}`},nl=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",rl=async(e,{width:t,height:n})=>{let r="",o=new el({write(a,l,u){let m=ol(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},ol=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Es=async()=>{let{viewMode:e}=$(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:i}=v(),a=r.find(w=>w.context==="BOARD");if(!a)return s("No board found to export");let l=120,u=40,m=await rl(Qc.createElement(qn,{height:u,width:l,swimlanes:(i[a.id]??[]).filter(w=>w!==void 0&&Nt(w)),contextNode: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=It(process.cwd());if(d(p))return s("Unable to export, epiq root not found");let x=new Date,C=tl(x),E=`board_${nl(a.title)}_${C}.md`,I=hi(p.value);Cs.mkdirSync(I,{recursive:!0});let k=Jc.join(I,E),R=`# Board - ${a.title}
|
|
23
|
-
Date: ${
|
|
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 Ft({cwd:e,message:"[epiq:repair-storage-branch]"});return d(i)?a(i.message):l("Cleaned storage branch",!0)},nt=$r(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=>Le.resolve(e)),vg=$r(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=Le.isAbsolute(n)?n:Le.join(e,n);return l("Resolved git dir",r)},e=>Le.resolve(e));var Sg=process.env.IS_LOCAL==="true",We=".epiq",be=".epiq-global",Bn="events",oc="project.json",An=e=>_e.join(e,We),Tn=e=>_e.join(An(e),oc),rn=e=>_e.join(An(e),Bn),Ai=e=>_e.join(e,We),ic=e=>{let t=_e.join(e,We);return nn.existsSync(t)&&nn.statSync(t).isDirectory()},zr=e=>{let t=Tn(e);return nn.existsSync(t)&&nn.statSync(t).isFile()},wn=e=>{let t=_e.resolve(e);for(;;){if(ic(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}},tt=e=>{let t=_e.resolve(e);for(;;){if(zr(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}},Ti=e=>{let t=rn(e);try{return nn.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")}},Pe=async()=>{let e=await nt(process.cwd());if(d(e))return e;let t=Bt({repoRoot:e.value});return d(t)?t:l("Resolved persist root",t.value)};var J={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History"};import{useSyncExternalStore as Uu}from"react";var p={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};function Un(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var On=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",wi=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Mi=e=>e.charAt(0).toUpperCase()+e.slice(1);var Pi=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},ki=(e,t)=>t?e.get(t)??[]:[];var Li=new WeakMap,sc=e=>{let t=Li.get(e);return t||(t=Pi(e),Li.set(e,t)),t};var Di=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return ki(sc(e),r).filter(i=>Un(r,i)>=n)};var ac={hint:"",hints:[],overlap:0,remainder:""},Fi=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return ac;let o=Di({wordList:r,inputToMatch:e,overlapThreshold:1});return dc(t,o)},dc=(e,t)=>{let n=t[0]??"",r=Un(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),s=r<(o??"").length,c=!!i,g=(c&&s?o:n)+(c&&s?":":" "),y=g.slice(r);return{hint:g,hints:t,overlap:r,remainder:y}};var $n={autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},H=()=>$n,De=e=>($n={...$n,...e},$n);var Ut=3e3,Bi=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Ut?null:t},Ui=0,Gr,qr=!1,on=!1,Yr=()=>{if(qr)return!0;let e=rt();return d(e)?!1:e.value.syncStatus.status==="syncing"},cc=()=>{let e=H().autoSyncIntervalMs??1e4,t=Date.now()-Ui;return Math.max(0,e-t)},Oi=()=>{Gr||(Gr=setTimeout(async()=>{if(Gr=void 0,!!Ot()){if(Yr()){on=!0;return}on=!1,await lc()}},cc()))},lc=async()=>{if(v().readOnly||v().timeMode==="peek")return a("Cannot auto-sync while peeking");if(!Ot())return a("Cannot auto-sync before state is initialized");if(Yr())return on=!0,a("Sync already in progress");qr=!0,Ui=Date.now(),S({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Hn()}finally{qr=!1,on&&Oi()}},$i=()=>{Ot()&&(on=!0,!Yr()&&Oi())};var ot=()=>{let e=H(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},Hi=()=>{let e=tt(process.cwd());if(d(e))return!1;let t=et(e.value);return X(t)},Wi=e=>e===!0?"yes":e===!1?"no":null,_i=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 C={red:de.red,yellow:de.yellow,green:de.green,blue:de.blue,magenta:de.magenta,cyan:de.cyan},Ct={urgent:C.red,critical:C.red,important:C.red,blocker:C.red,asap:C.red,immediate:C.red,fail:C.red,failure:C.red,broken:C.red,bug:C.red,error:C.red,incident:C.red,outage:C.red,production:C.red,crash:C.red,security:C.red,warning:C.yellow,warn:C.yellow,risky:C.yellow,risk:C.yellow,attention:C.yellow,pending:C.yellow,review:C.yellow,"needs-review":C.yellow,qa:C.yellow,testing:C.yellow,test:C.yellow,validate:C.yellow,verification:C.yellow,staging:C.yellow,check:C.yellow,"follow-up":C.yellow,followup:C.yellow,waiting:C.yellow,blocked:C.yellow,hold:C.yellow,done:C.green,complete:C.green,completed:C.green,success:C.green,ok:C.green,stable:C.green,resolved:C.green,fixed:C.green,closed:C.green,merged:C.green,released:C.green,deployed:C.green,approved:C.green,verified:C.green,working:C.green,healthy:C.green,pass:C.green,passing:C.green,info:C.blue,information:C.blue,note:C.blue,docs:C.blue,documentation:C.blue,doc:C.blue,guide:C.blue,help:C.blue,explanation:C.blue,detail:C.blue,details:C.blue,context:C.blue,design:C.blue,discussion:C.blue,proposal:C.blue,idea:C.blue,feature:C.magenta,enhancement:C.magenta,improvement:C.magenta,refactor:C.magenta,refactoring:C.magenta,cleanup:C.magenta,optimize:C.magenta,optimization:C.magenta,perf:C.magenta,performance:C.magenta,upgrade:C.magenta,migration:C.magenta,modernize:C.magenta,debt:C.magenta,todo:C.cyan,next:C.cyan,planned:C.cyan,plan:C.cyan,future:C.cyan,backlog:C.cyan,investigate:C.cyan,explore:C.cyan,prototype:C.cyan};var uc=e=>e.props.tags??[],mc=e=>e.props.assignees??[],Xr=e=>uc(e).map(t=>b.getTag(t)).filter(t=>!!t),Jr=e=>mc(e).map(t=>b.getContributor(t)).filter(t=>!!t),Wn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!W(n)?a("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Xr(n))},_n=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!W(n)?a("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",Jr(n))};var x={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 pc=/^(\d+)(h|d|w|mo|y)$/,gc=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,fc=({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},vc=(e,t=new Date)=>{let n=e.match(pc);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}},xc=e=>{let t=e.match(gc);if(!t)return null;let[,n,r,o,i,s]=t,c=Number(n),u=Number(r),m=Number(o),g=i?Number(i):0,y=s?Number(s):0;return fc({year:c,month:u,day:m,hour:g,minute:y})?new Date(c,u-1,m,g,y):null},jn=e=>{let t=e.trim().toLowerCase();return vc(t)??xc(t)},ji=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,yc=[{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}],Ki=(e=yc)=>{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 hc=["BOARD","TICKET","SWIMLANE"],oe={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs"},it={TITLE:"title",DESCRIPTION:"description"},Cc=[oe.EDITOR,oe.VIEW,oe.USERNAME,oe.AUTOSYNC,oe.SYNC_DEBOUNCE_MS],Nc=[it.TITLE,it.DESCRIPTION],Zr=[String(Ut),"5000","15000","30000","60000"],Nt=[x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG],Kn=[x.NEW,x.EDIT,x.DELETE,x.MOVE],Qr=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT],Vi=[x.FILTER,x.PEEK],Ec={WORKSPACE:[...Nt,...Kn],BOARD:[...Vi,...Nt,...Kn],SWIMLANE:[...Vi,...Nt,...Kn],TICKET:[...Nt,...Kn,...Qr],FIELD:[...Nt,...Qr],FIELD_LIST:[...Nt,...Qr],TEXT:[...Nt]},Sc=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],bc=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=ot();if(!r)return[x.HELP,x.CONFIG];if(!Hi())return[x.HELP,x.INIT];if(t)return[x.HELP,x.PEEK,x.EXPORT,x.CONFIG];let o=e?.context,i=o&&hc.includes(o);return[...new Set([...n,e].map(c=>c?.context).flatMap(c=>c?Ec[c]:[]))].filter(c=>c===x.MOVE?!1:c===x.EDIT||c===x.DELETE?i:!0)},Q=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let i=t.context??"WORKSPACE";return{[x.NONE]:bc({breadCrumb:o,readOnly:r,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.HELP]:[],[x.PEEK]:[...Ki(),"now","prev","next"],[x.EDIT]:[...Nc],[x.DELETE]:["confirm"],[x.RE_OPEN_ISSUE]:["confirm"],[x.CLOSE_ISSUE]:["confirm"],[x.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[x.FILTER]:["tag","assignee","description","title","clear"],[x.TAG]:[...new Set([...Object.keys(Ct),...b.getExistingTags()])],[x.UNTAG]:[...Wn()?.value?.map(({name:c})=>c)??[]],[x.UNASSIGN]:[..._n()?.value?.map(({name:c})=>c)??[]],[x.ASSIGN]:b.getExistingAssignees(),[x.NEW]:Sc(i),[x.CONFIG]:[...Cc]}[e]??[]};import os from"chalk";var zi=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import{decodeTime as Gi}from"ulid";var qi=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"},Yi=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())}`},Vn=e=>{try{return l("Decoded date",new Date(Gi(e)))}catch(t){return a("Decoding failed + "+t.message)}},eo=e=>{if(!e?.id)return null;try{return Gi(e.id)}catch{return null}};var Ie=(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 $t from"chalk";var Ic=[0,0,0],ro=.2,no={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Xi=(e,t,n)=>Math.max(t,Math.min(n,e)),to=(e,t,n)=>e+(t-e)*n,Ji=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Rc=e=>e.toLowerCase().trim(),Ac=(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,g=0;s>=0&&s<1?(u=i,m=c):s>=1&&s<2?(u=c,m=i):s>=2&&s<3?(m=i,g=c):s>=3&&s<4?(m=c,g=i):s>=4&&s<5?(u=c,g=i):(u=i,g=c);let y=o-i/2;return[Math.round((u+y)*255),Math.round((m+y)*255),Math.round((g+y)*255)]},Qi=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Tc=e=>{let t=e.replace("#","");return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]},Zi=(e,t,n)=>{let r=Xi(n,0,1);return[Math.round(to(e[0],t[0],r)),Math.round(to(e[1],t[1],r)),Math.round(to(e[2],t[2],r))]},wc=(e,t=ro)=>Zi(e,Ic,t),Mc=(e,t=ro)=>Qi(wc(Tc(e),t)),Pc=(e,t,n)=>Zi(e,t,n),sn=e=>{let n=Ji(e)%360,r=Ac(n,no.stringColor.saturation,no.stringColor.lightness);return Qi(r)},Re=(e,t=Ct)=>{let n=Rc(e);return n&&t[n]?t[n]:sn(n)},es=(e,t=Ct,n=ro)=>Mc(Re(e,t),n),kc=e=>{let t=no.gradient.stops,n=Xi(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 Pc(t[i],t[i+1],s)},zn=e=>Ji(e.toLowerCase().trim())/4294967295,ts=e=>{let t=zn(e);return kc(t)},Lc=e=>{let[t,n,r]=ts(e);return{normal:o=>$t.bgRgb(t,n,r).black(o),cursor:o=>$t.bgRgb(t,n,r).white.bold(o)}},oo=e=>{let[t,n,r]=ts(e);return{fg:o=>$t.rgb(t,n,r)(o),fgCursor:o=>$t.rgb(t,n,r).inverse(o),bg:o=>$t.bgRgb(t,n,r).black(o),bgCursor:o=>$t.bgRgb(t,n,r).white.bold(o)}},Gn=e=>Lc(e).normal(` ${e} `);import ns from"chalk";var Z=e=>ns.dim(e),fe=e=>ns.hex(h.primary)(e),ve=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let s=o.trim();if(s.length<i)return"";let g=[...t.filter(Boolean).filter(y=>y.startsWith(s))].sort((y,N)=>zn(y)-zn(N)).slice(0,r).map(y=>Gn(y)).join(" ");return g?`${Z(e)}${g}${Z(n)}`:""};var Et={None:"none",Invalid:"invalid",Valid:"valid"};var Dc=["BOARD","TICKET","SWIMLANE"],rs=()=>{let e=v().selectedNode;return e?.context?Dc.includes(e.context)?j():B({message:Z("Command not available in this context")}):B({message:Z("Missing target context")})},ee="<ENTER> to confirm",j=(e="",t=[])=>({message:Z(e),validity:Et.Valid,completionWordList:t}),B=({message:e,completionWordList:t=[]})=>({validity:Et.Invalid,message:e,completionWordList:t}),Yn=e=>e.length===0,qn=e=>` ${os.dim.bgHex(es(e))(` ${e} `)} `,io=({modifier:e})=>{let t="confirm";return e===t?j(ee):B({message:Yn(e)?Z("if you are certain, enter ")+Gn(t):"",completionWordList:[t]})},Fc=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?B({message:Z(n)}):j():B({message:Yn(r)?t:"",completionWordList:[...e]}),an=({hint:e})=>({modifier:t,inputString:n})=>Yn(t)&&Yn(n)?B({message:e,completionWordList:[]}):j(ee),Bc=({modifier:e,inputString:t})=>{let n=Q(x.CONFIG);if(!n.includes(e))return B({message:ve({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case oe.EDITOR:{let r=[...zi];return t.trim()?r.includes(t.trim())?j(ee):B({message:ve({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):B({message:ve({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case oe.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?j(ee):B({message:ve({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case oe.USERNAME:return t.trim()?j(ee):B({message:fe("Enter a user name. Saved in ")+os.bgBlack("~/.epiq-global/config.json")});case oe.AUTOSYNC:{let r=["yes","no"],o=H().autoSync;if(!r.includes(t.trim())){let i=Wi(o);return B({message:ve({prefix:`should auto-sync (recommended)${i!==null?", currently: "+i:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return j(ee)}case oe.SYNC_DEBOUNCE_MS:{let r=H().autoSyncIntervalMs,o=Bi(t);if(!t.trim()||o===null||o<Ut){let i=ve({prefix:" examples: ",wordList:Zr,minLengthForHints:0,inputString:t});return B({message:fe(`provide duration above ${Ut}ms. current duration: ${r}ms.`)+i,completionWordList:Zr})}return j(ee)}default:return B({message:fe("Unknown config option"),completionWordList:n})}},Uc=({modifier:e})=>{let t=Q(x.EDIT);if(!t.includes(e)){let i=ve({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return B({message:i||fe("Unknown edit option"),completionWordList:t})}let{breadCrumb:n,selectedNode:r}=v();if(!Ie([...n,r],"TICKET"))return B({message:fe("Command not available in this context")});switch(e){case it.TITLE:return j(ee);case it.DESCRIPTION:let{preferredEditor:i}=H();return i?j(Z("<ENTER> to edit in ")+i):B({message:"No editor selected"});default:return B({message:fe("Unknown edit option"),completionWordList:t})}},Oc={[x.EXPORT]:()=>j(ee+Z(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now")return j(ee);let n={message:Z("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")};if(t==="prev"||t==="next")return j(ee);let r=jn(t);if(!t||!r)return B(n);let o=Ie(v().breadCrumb,"BOARD");if(d(o))return B({message:fe("Command is not applicable in this context")});let i=Vn(o.value.id);return d(i)?B({message:fe("Unable to peek: board id is not a valid ULID")}):ji({date:r,horizonDate:i.value})?j(ee):B({message:fe(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[x.EXIT]:()=>j(ee+Z(" and exit the application")),[x.INIT]:()=>j(ee),[x.PALETTE]:()=>j(ee),[x.FILTER]:e=>{if(e.modifier==="clear")return j();let t=i=>Q(x.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return B({message:ve({wordList:Q(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Q(x.FILTER)});let n=Object.values(v().tags).map(i=>i.name),r=Object.values(v().contributors).map(i=>i.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?B({message:ve({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):j():B({message:ve({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[x.NONE]:e=>{let t=Q(x.NONE);return B({message:ve({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>Fc({list:Q(x.NEW),hint:ve({wordList:Q(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>j(ee),[x.EDIT]:Uc,[x.CONFIG]:Bc,[x.DELETE]:e=>{let t=rs();return t.validity==="invalid"?t:io(e)},[x.CLOSE_ISSUE]:e=>io(e),[x.RE_OPEN_ISSUE]:e=>io(e),[x.MOVE]:e=>{let t=rs();return t.validity==="invalid"?t:an({hint:ve({prefix:"hey hacker! These commands are blocked for you... ",wordList:Q(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=b.getExistingTags().slice(0,10).map(qn).join("");return an({hint:n.length?Z("create tag or reuse:")+n+Z(""):Z("create tag ...")})(e)},[x.UNTAG]:e=>{let t=Wn();if(d(t))return B({message:fe("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(qn).slice(0,10);return n.length?an({hint:Z(" ... ")+n.join("")})(e):B({message:fe("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=b.getExistingAssignees().map(qn).slice(0,10);return an({hint:Z("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=_n();if(d(t))return B({message:fe("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(qn).slice(0,10);return n.length?an({hint:Z("remove assignee... ")+n.join("")})(e):B({message:fe("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>j(ee)},is=Object.fromEntries(Object.entries(Oc).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var ss=["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 as=e=>Object.values(x).includes(e),ds=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:s,validity:c,completionWordList:u}=is[n].validate(n,r,i),m=o==="command"||o==="modifier"?Q(n):ss,{mode:g}=v(),y=g===p.COMMAND_LINE?s??"":"",N=[...u,...m];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:y,autoCompletion:t?Fi(e,N):{hint:"",hints:[],remainder:"",overlap:0}}};var cs=e=>{let t=e.trimStart(),n=Hc(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),s=Wc(e),c=as(r)?r:null,u=c!==null,m=r!=="",g=c?Q(c)??[]:[],y=c&&g.includes(o)?o:"",N="word";n.length===0||n.length===1&&!i?N="command":(n.length===1&&i||n.length===2&&!i)&&(N="modifier");let E=i?"":s,I=$c(t,c,y);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:s,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:i,modifier:y,target:N,inputToMatch:E,inputString:I}},$c=(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},Hc=e=>e.trim()?e.trim().split(/\s+/):[],Wc=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as _c}from"react";var Ht=e=>e===so||e===":",so=" ",ce={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Et.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},ao=new Set,ls=()=>{for(let e of ao)e()},co=e=>(ao.add(e),()=>ao.delete(e)),je=e=>{let n=e(ce),r=cs(n.value),o=n.cursorPosition===n.value.length;ce={...n,commandMeta:ds(r,o)},ls()},dn=({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,ls(),l(e,null)},lo=e=>{je(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},uo=e=>{je(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Ht(n[o-1]);)o--;for(;o>0&&!Ht(n[o-1]);)o--}else{for(;o<n.length&&!Ht(n[o]);)o++;for(;o<n.length&&Ht(n[o]);)o++}return{...t,cursorPosition:o}})},us=()=>{je(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}})},ms=()=>{je(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Ht(t[r-1]);)r--;for(;r>0&&!Ht(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},U=e=>{je(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}})},ps=()=>{je(e=>({...e,commandIsPending:!0}))},gs=({addToHistory:e=!0})=>{je(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),jc()},fs=()=>{je(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}})},vs=()=>{je(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},jc=()=>U(()=>""),V=()=>ce,xs=()=>_c(co,V,V),ys=()=>{let[e,...t]=ce.value.split(so);return t.join(so).trim()};var hs=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Cs=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",Ns=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Es=(e,t)=>{if(Cs(e,e.sequence))return f.MoveCursorLeftOfWord;if(Ns(e,e.sequence))return f.MoveCursorRightOfWord;if(hs(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}},Ss=(e,t)=>{if(Cs(e,e.sequence))return f.MoveCursorLeftOfWord;if(Ns(e,e.sequence))return f.MoveCursorRightOfWord;if(hs(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",EditTitle:"editTitle",EditDescription:"editDescription",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};function Kc(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 zc(e,t,n){let r=v().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 bs(e,t){let n=V();if(e.sequence==="?"&&n.value==="")return f.InitCommandPalette;if(e.sequence===":"&&n.value==="")return f.InitCommandLine;if(t===p.MOVE)switch(e.name){case"m":case"return":return f.ConfirmMove}if(t===p.COMMAND_LINE)return Es(e,n.value);if(t===p.PALETTE)return Ss(e,n.value);let r=Kc(e)||Vc(e);if(r)return Gc(r,t);if(e.ctrl&&e.name==="c")return f.Exit;switch(e.name){case"r":return f.EditTitle;case"e":return f.EditDescription;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 H().viewMode==="wide"?f.SetViewDense:f.SetViewWide;case"q":case"escape":return f.Exit;default:return null}}function Gc(e,t){let n=t===p.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 zc(v().contextNode.childRenderAxis,e,n)}var Xn=e=>{let{context:t}=v().contextNode;if(!t)return P.None;switch(e){case x.EXIT:return P.Exit;case x.EXPORT:return P.Export;case x.INIT:return P.Init;case x.DELETE:return P.Delete;case x.EDIT:return P.Edit;case x.HELP:return P.ViewHelp;case x.RE_OPEN_ISSUE:return P.ReopenIssue;case x.CLOSE_ISSUE:return P.CloseIssue;case x.TAG:return P.TagTicket;case x.UNTAG:return P.UntagTicket;case x.ASSIGN:return P.AssignUserToTicket;case x.UNASSIGN:return P.UnassignUserFromTicket;case x.NEW:return P.NewItem;case x.FILTER:return P.Filter;case x.MOVE:return P.Move;case x.PEEK:return P.Peek;case x.CONFIG:return P.Config;case x.SYNC:return P.Sync;default:return P.None}},P={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Sync:"sync",Export:"export"};import{ulid as ye}from"ulid";import Fs from"node:fs";import hl from"node:path";import Cl from"react";import{Box as xl}from"ink";import tr from"react";import{Box as go,Text as il}from"ink";import Fe from"react";import{Text as Is}from"ink";import Rs,{useEffect as As,useState as qc}from"react";var Ts={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},xe=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=te(),r=Ts[n]??Ts.default,[o,i]=qc(0);if(As(()=>{i(0)},[r]),As(()=>{if(!e)return;let c=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return Rs.createElement(Is,null,t);let s=r[o]??r[0]??t;return Rs.createElement(Is,{color:h.accent,dimColor:o===1},s)};import{Box as mo,Text as Yc}from"ink";import Jn from"react";var st=({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),g=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),y=g+c,N=e.slice(g,y),E=e.length>c,I=i,w=E?Math.max(1,Math.floor(c/e.length*I)):I,R=Math.max(0,I-w),T=Math.max(1,e.length-c),F=E?Math.floor(g/T*R):0;return Jn.createElement(mo,{flexDirection:"row",height:i,width:"100%"},Jn.createElement(mo,{flexDirection:"column",flexGrow:1,height:i},N),Jn.createElement(mo,{flexDirection:"column",width:1,height:I},Array.from({length:I}).map((re,se)=>Jn.createElement(Yc,{key:se,color:E&&se>=F&&se<F+w?h.accent:h.secondary},E?"\u2502":" "))))};import{Box as Qn,Text as nl}from"ink";import St from"react";import{Text as Xc}from"ink";import Jc from"react";var Qc=e=>e.toLowerCase().trim(),Zc=(e,t=Ct)=>{let n=Qc(e);return t[n]?t[n]:sn(n)},Wt=({id:e,isSelected:t})=>{let n=b.getContributor(e);if(n)return Jc.createElement(Xc,{underline:t,color:Zc(n.name)},"@"+n.name)};import{Text as el}from"ink";import tl from"react";var _t=({id:e,isSelected:t})=>{let n=b.getTag(e);if(n)return tl.createElement(el,{underline:t,backgroundColor:Re(n.name),color:h.primary}," "+n.name+" ")};var ws=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=On(wi(t.title),r),i=Xr(t),s=Jr(t);return St.createElement(Qn,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?h.accent:h.secondary,justifyContent:"space-between"},St.createElement(Qn,{borderBottom:!0},St.createElement(Qn,{paddingLeft:1,flexDirection:"column"},St.createElement(nl,{color:h.primary},o))),St.createElement(Qn,{flexDirection:"row",paddingLeft:1},i.map(c=>St.createElement(_t,{key:c.id,id:c.id})),s.map(c=>St.createElement(Wt,{key:c.id,id:c.id}))))};import rl from"chalk";import{Box as cn,Text as po}from"ink";import Ke from"react";var ol=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Ms=({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),g=i.map(E=>Ke.createElement(cn,{key:E.id,paddingRight:c},Ke.createElement(po,{color:Re(E.name)},"\u25A0"))),y=s.map(E=>Ke.createElement(cn,{key:E.id,paddingRight:c},Ke.createElement(po,{color:sn(E.name)},"@"+E.name.at(0)))),N=n?h.accent:o===p.MOVE?h.secondary:h.primary;return Ke.createElement(cn,{borderBottom:!0,justifyContent:"space-between"},Ke.createElement(cn,null,Ke.createElement(xe,{isSelected:n,placeholder:rl.dim.gray(r+1+" ")}),Ke.createElement(po,{wrap:"truncate",color:N},ol(t.title,e-u-m-14))),Ke.createElement(cn,null,g,y))};import sl from"chalk";var al=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:s,mode:c})=>{let{renderedChildrenIndex:u}=te(),m=u[e.id]??[],g=`${e.title} ${sl.hex(h.secondary2).dim("("+m.length+")")}`,y=3,N=o?1:4,E=r-y-(o?2:1),I=Fe.createElement(go,{borderStyle:"round",borderColor:h.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Fe.createElement(xe,{isSelected:t}),Fe.createElement(il,{bold:!0,color:t?h.accent:h.primary},g," ",e.readonly?"\u{1F512}":"")),w=(R,T)=>{let F=i&&s===T;return o?Fe.createElement(Ms,{key:R.id,index:T,width:n,ticket:R,isSelected:F,mode:c}):Fe.createElement(ws,{key:R.id,width:n,ticket:R,isSelected:F})};return Fe.createElement(go,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?h.accent:h.secondary,paddingRight:1,paddingLeft:1,height:r},I,Fe.createElement(go,{padding:o?1:0},m.length>0&&Fe.createElement(st,{selectedIndex:s,height:E,itemHeight:N},m.map(w)),Fe.createElement(xe,{isSelected:i&&s===-1})))},Ps=Fe.memo(al);import{Box as xo,Text as gl}from"ink";import dt,{useMemo as Ls}from"react";import{decodeTime as dl,encodeTime as cl}from"ulid";var ll="0123456789ABCDEFGHJKMNPQRSTVWXYZ",ul=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+=ll[Number(n%32n)];return r},at=(e,t)=>{let n=dl(e);return cl(n,10)+ul(`${e}:${t}`)};import{Box as Zn,Text as ml}from"ink";import Ve from"react";var ks=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=te(),{title:o}=t,i=t.parentNodeId?b.getNode(t.parentNodeId):void 0,s=i&&W(i)?o===J.ASSIGNEES?i.props.assignees??[]:o===J.TAGS?i.props.tags??[]:[]:[];return Ve.createElement(Zn,{alignItems:"center",paddingTop:1},Ve.createElement(Zn,{minWidth:12},Ve.createElement(xe,{isSelected:n}),Ve.createElement(ml,{color:n?h.accent:h.secondary2},o,":")),Ve.createElement(Zn,{flexDirection:"row",marginLeft:1,paddingRight:1},s.map((c,u)=>{let m=r.id===t.id&&u===e;return Ve.createElement(Zn,{key:`${o}-${c}`,paddingRight:2,minHeight:1},Ve.createElement(xe,{isSelected:m}),o===J.ASSIGNEES?Ve.createElement(Wt,{isSelected:m,id:c}):o===J.TAGS?Ve.createElement(_t,{isSelected:m,id:c}):null)})))};import{Box as er,Text as fo}from"ink";import ze,{useEffect as pl}from"react";var z={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:M.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:M.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:M.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:M.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:M.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:M.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:M.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[],isVirtual:s})};var vo=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:s,contextNode:c}=te(),u=N=>String(N).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];pl(()=>{let N=[];return m.forEach((E,I)=>{let w=Me(BigInt(I+1));if(!X(w))return;let R=z.text({id:`${e}-${I}`,name:`Line ${I+1}`,parentNodeId:e,rank:w.value,props:{value:E},readonly:!0,isVirtual:!0}),T=b.createNode(R);X(T)&&N.push(T.value.id)}),()=>N.forEach(b.deleteNode)},[e,n]);let g="\u2029",y=m.map((N,E)=>{let I=c.id===e&&s===E;return ze.createElement(er,{key:`${e}-${E}`},ze.createElement(fo,{color:I?h.primary:h.secondary2,dimColor:!I},`${E+1} `.padStart(5,"\xA0")),ze.createElement(fo,{backgroundColor:I?"gray":""},u(N.length?On(N,i-10):g)))});return ze.createElement(er,{flexDirection:"column",paddingTop:1},ze.createElement(er,null,ze.createElement(xe,{isSelected:o}),ze.createElement(fo,{color:o?h.accent:h.secondary2},t)),ze.createElement(er,{flexDirection:"row",borderStyle:"round",borderColor:h.secondary,paddingLeft:1,marginLeft:1},ze.createElement(st,{scrollByOne:!0,children:y,height:r-2,selectedIndex:s,itemHeight:1})))};var fl=e=>at(e,"description"),vl=e=>at(e,"history"),Ds=({ticket:e,height:t})=>{let{selectedIndex:n,contextNode:r}=te(),o=process.stdout.columns||120,i=Ls(()=>fl(e.id),[e.id]),s=Ls(()=>vl(e.id),[e.id]),c=r.id===e.id,u=r.id===s||r.parentNodeId===s,m=O(e.id);if(u){let R=b.getNode(s),T=R&&Qe(R)?R.props.value??"":"",re=t-3;return dt.createElement(xo,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R?dt.createElement(vo,{id:R.id,label:"Event log",text:T,selected:!1,maxWidth:o,height:re}):null)}let g=m.reduce((R,T)=>Xt(T)||T.id===s?R+1:R,0),y=2,N=3,E=g,I=t-N-E-y,w=(R,T)=>R.id===i?dt.createElement(vo,{key:R.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:T,maxWidth:o,height:I}):Xt(R)?dt.createElement(ks,{key:R.id,parent:R,selected:T,selectedIndex:n}):R.id===s?dt.createElement(xo,{key:R.id,paddingTop:1},dt.createElement(xe,{isSelected:T}),dt.createElement(gl,{backgroundColor:h.secondary,color:T?h.accent:h.primary}," History \u203A\u203A ")):null;return dt.createElement(xo,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((R,T)=>w(R,c&&n===T)))};var yl=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:s,width:c})=>{let u=t.context,m=u===M.TICKET||u===M.FIELD_LIST||u===M.FIELD,g=u===M.BOARD||u===M.SWIMLANE,y=u===M.TICKET?t:r.find(R=>R.context===M.TICKET),N=Math.floor(c/3),E=Math.floor(c/Math.max(e.length,1)),I=Math.min(E,N),w=i==="dense";return tr.createElement(xl,{flexDirection:"row",height:s},g&&e.map((R,T)=>{let F=t.id===R.id,re=F?n:-1,se=t.context===M.BOARD&&n===T;return tr.createElement(Ps,{key:R.id,height:s,width:I,swimlane:R,isSelected:se,isDense:w,isFocused:F,listSelectedIndex:re,mode:o})}),m&&y&&tr.createElement(Ds,{height:s,ticket:y}))},nr=tr.memo(yl);import{render as Nl}from"ink";import{Writable as El}from"node:stream";var ln=e=>String(e).padStart(2,"0"),Sl=e=>{let t=e.getUTCFullYear(),n=ln(e.getUTCMonth()+1),r=ln(e.getUTCDate()),o=ln(e.getUTCHours()),i=ln(e.getUTCMinutes()),s=ln(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${s}`},bl=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Il=async(e,{width:t,height:n})=>{let r="",o=new El({write(s,c,u){let m=Rl(s.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=Nl(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(s=>setTimeout(s,0)),i.unmount(),r},Rl=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Bs=async()=>{let{viewMode:e}=H(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:i}=v(),s=r.find(T=>T.context==="BOARD");if(!s)return a("No board found to export");let c=120,u=40,m=await Il(Cl.createElement(nr,{height:u,width:c,swimlanes:(i[s.id]??[]).filter(T=>T!==void 0&&Lt(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 g=wn(process.cwd());if(d(g))return a("Unable to export, epiq root not found");let y=new Date,N=Sl(y),E=`board_${bl(s.title)}_${N}.md`,I=Ai(g.value);Fs.mkdirSync(I,{recursive:!0});let w=hl.join(I,E),R=`# Board - ${s.title}
|
|
23
|
+
Date: ${y.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 Fs.writeFileSync(w,R,"utf8"),l("Exported board layout",w)};var A={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=$(t.id)[n];!r||t.context==="FIELD"||A.navigate({contextNode:r,selectedIndex:O(r.id).length?0:-1})},enterParentNode(){let{contextNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=O(n.id),o=r.findIndex(({id:s})=>s===e.id),i=r.length===0?-1:o>=0?o:0;A.navigate({contextNode:n,selectedIndex:i})},navigateToNextItem:()=>Us(1),navigateToPreviousItem:()=>Us(-1),navigateToNextContainer:()=>Os(1),navigateToPreviousContainer:()=>Os(-1),navigate:({contextNode:e,selectedIndex:t})=>{S({contextNodeId:e.id,selectedIndex:t})}},Us=e=>{let{selectedIndex:t,contextNode:n}=v(),r=O(n.id).length;if(r===0)return;let i=(Math.max(0,t)+e+r)%r;A.navigate({selectedIndex:i,contextNode:n})},Os=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let i=O(o.id),s=i.findIndex(N=>N.id===t.id);if(s<0)return;let c=i.at(s+e)??i.at(0);if(!c)return;let u=O(c.id),m=Math.max(0,u.length-1),g=Math.min(Math.max(0,r),m),y=u.length?g:-1;A.navigate({contextNode:c,selectedIndex:y})};import Dl from"node:os";import _s from"node:path";import{z as bt}from"zod";import{accessSync as Al,copyFileSync as Tl,existsSync as rr,mkdirSync as $s,readdirSync as Hs,readFileSync as wl,renameSync as Ml,rmSync as Pl,statSync as Ws,unlinkSync as kl,writeFileSync as Ll}from"node:fs";import jt from"node:path";var Ce={writeToFile:(e,t)=>{try{let n=jt.dirname(e);rr(n)||$s(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Ll(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return wl(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Ce.readFile(e);return t===null?null:JSON.parse(t)}catch(t){return logger.error(`Failed to read JSON at ${e}:`,t),null}},dirExists:e=>{try{return rr(e)&&Ws(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Al(e),!0}catch{return!1}},mkDir:e=>$s(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=jt.parse(t);for(;;){let r=jt.join(t,e);try{if(rr(r)&&Ws(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=jt.dirname(t)}return null},readFirstJSON(e){try{if(!Ce.dirExists(e))return null;let t=Hs(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=jt.join(e,t);return Ce.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Ce.dirExists(e)?Hs(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{kl(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Pl(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(jt.dirname(t)),!n?.overwrite&&rr(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Ml(e,t)}catch(r){if(r?.code==="EXDEV"){Tl(e,t),this.rmFile(e);return}throw r}}};var Fl={userId:"",userName:"",preferredEditor:"",autoSync:!1},js=bt.object({preferredEditor:bt.string().optional(),userName:bt.string().optional(),userId:bt.string().optional(),autoSync:bt.boolean().nullable().optional(),autoSyncDebounceMs:bt.number().optional(),viewMode:bt.enum(["dense","wide"]).optional()}),Bl="config.json",Ks=()=>_s.join(Dl.homedir(),be),yo=()=>_s.join(Ks(),Bl),ho=()=>{try{return Ce.mkDir(Ks()),l(`Ensured ~/${be} exists`,null)}catch{return a(`Unable to create ~/${be}`)}},Ul=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${be}/config.json JSON`)}let n=js.safeParse(t??{});return n.success?l("Parsed config",n.data):a(`Invalid ~/${be}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Vs=()=>{let e=ho();if(d(e))return a(e.message);let t=yo(),n=Ce.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Ul(n)},zs=e=>{let t=ho();if(d(t))return a(t.message);let n=js.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=yo();try{return Ce.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
29
|
+
`),l("Config written",null)}catch{return a(`Unable to write ~/${be}/config.json`)}},It=e=>{let t=Vs();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return zs(n)},Gs=()=>{let e=yo(),t=ho();if(d(t))return a(`Unable to create ~/${be}`);if(!(Ce.readFile(e)!==null)){let m=zs(Fl);if(d(m))throw new Error(`Unable to create ~/${be}/config.json`)}let r=Vs();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 ~/${be}/config.json`):l("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:s,autoSync:c??!1,autoSyncIntervalMs:u??1e4,viewMode:"dense"})};import ql from"node:fs";import Yl from"node:path";import{decodeTime as Xl,monotonicFactory as Jl}from"ulid";import{z as un}from"zod";import or from"node:fs";import No from"node:path";import{decodeTime as Ol}from"ulid";import{z as Co}from"zod";var $l=Co.object({userId:Co.string().min(1).default("unknown"),userName:Co.string().min(1).default("unknown")}),Hl=e=>{let[t,n]=No.basename(e,".jsonl").split("."),r=$l.safeParse({userId:t,userName:n});return r.success?l("Parsed event file actor",r.data):a(`Invalid event file name ${No.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Wl=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])},_l=(e,t)=>t in e,jl=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Kl=e=>{let{userId:t,userName:n,...r}=e,o=Wl(r);if(d(o))return a(o.message);let i=o.value,s=e.id?.[0];return s?_l(r,i)?l("Decoded persisted event",jl({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")},Eo=e=>{let t=[];for(let n of e){let r=Kl(n);if(d(r))return a(`Failed to decode event ${n.id?.[0]??"<unknown>"}: ${r.message}`);t.push(r.value)}return l("Decoded reconstructed events",t)},Vl=e=>{if(!or.existsSync(e))return l("Event file missing",[]);let t=Hl(e);if(d(t))return a(t.message);let n=or.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=bo(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 So(e){let t=rn(e);if(!or.existsSync(t))return l("No events found",[]);let n=or.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>No.join(t,o)),r=[];for(let o of n){let i=Vl(o);if(d(i))return a(i.message);r.push(...i.value)}return l("All events loaded",zl(r))}function Kt(e){let t=So(e);return d(t)?a(t.message):Eo(t.value)}function qs(e,t){let n=So(e);if(d(n))return a(n.message);let{appliedEvents:r,unappliedEvents:o}=Gl(n.value,t),i=Eo(r);if(d(i))return a(i.message);let s=Eo(o);return d(s)?a(s.message):l("Loaded merged events before time",{appliedEvents:i.value,unappliedEvents:s.value})}function Ys(e=process.cwd()){let t=So(e);return d(t)?a(t.message):l("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var zl=e=>{let t=new Map,n=new Map;for(let m of e){let g=m.id[0],y=m.id[1]??null;t.set(g,m);let N=n.get(y)??[];N.push(m),n.set(y,N)}for(let m of n.values())m.sort((g,y)=>g.id[0].localeCompare(y.id[0]));let r=[],o=new Set,i=m=>{let g=m.id[0];if(o.has(g))return;r.push(m),o.add(g);let y=n.get(g)??[];for(let N of y)i(N)},s=n.get(null)??[];for(let m of s)i(m);let c=e.filter(m=>{let g=m.id[0],y=m.id[1]??null;return!o.has(g)&&y!==null&&!t.has(y)}).sort((m,g)=>m.id[0].localeCompare(g.id[0]));for(let m of c)i(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,g)=>m.id[0].localeCompare(g.id[0]));for(let m of u)i(m);return r},Gl=(e,t)=>{let n=new Set,r=[],o=[];for(let i of e){let s=i.id[0],c=i.id[1],u=!1;try{u=Ol(s)<t}catch{u=!1}!u||c&&n.has(c)?(n.add(s),o.push(i)):r.push(i)}return{appliedEvents:r,unappliedEvents:o}};var Xs=e=>({action:e.action,payload:e.payload});var Qs=1,Js=Jl(),Ql=un.tuple([un.string().min(1),un.string().min(1).nullable()]),Zl=un.looseObject({v:un.literal(Qs),id:Ql}),bo=e=>{let t=Zl.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(", ")}`)},ir=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",G=()=>{let{userName:e,userId:t}=H();return e?t?e.trim()?l("Successfully resolved actor ID",{userId:ir(t),userName:ir(e)}):a("Unable to resolve actor ID from settings or OS user info"):a("User ID not configured"):a("User name not configured")},mn=({userId:e,userName:t})=>`${ir(e)}.${ir(t)}.jsonl`,eu=(e,{userId:t,userName:n})=>{let r=mn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return a(`Invalid event log file name: ${r}`);let i=Yl.join(rn(e),r);return l("Successfully resolved event log path",i)},tu=(e,t)=>{let n={[e.action]:e.payload,v:Qs,id:t};return bo(n)};function sr({event:e,rootDir:t}){try{let n=Ti(t);if(d(n))return n;let r=eu(t,{userId:e.userId,userName:e.userName});if(d(r))return r;let o=Ys(t);if(d(o))return a(o.message);let i=o.value?Js(Math.max(Date.now(),Xl(o.value)+1)):Js(),s=tu(Xs(e),[i,o.value]);return d(s)?a(s.message):(ql.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 Zs=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 nu=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[Ge,ar]=nu;import{ulid as du}from"ulid";import{spawnSync as ru}from"node:child_process";import ou from"node:os";import ea from"node:path";import{ulid as iu}from"ulid";function su(){let{preferredEditor:e}=H(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function au(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function ta(e){let t=ea.join(ou.tmpdir(),"epiq");Ce.mkDir(t);let n=ea.join(t,iu());Ce.writeToFile(n,e??"");let r=su();for(let o of r){let i=au(o,n),s=ru(i,{stdio:"inherit",shell:!0});if(!s.error&&s.status===0){let c=Ce.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 na=async()=>{let e=G();if(d(e))return a("Unable to resolve user ID");let t=await Pe();if(d(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=v(),i=Ie([...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=O(s.id).find(y=>y.title===J.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=ta(u);if(d(m))return a("Failed to edit field");let g=m.value;return g===u?l("No changes made",null):ke({id:du(),action:"edit.description",payload:{id:s.id,md:g},...e.value},n)};import hu from"node:fs";import ca from"node:path";import Io from"node:fs";import cu from"node:path";var ra=async e=>{let t=cu.join(e,".gitignore"),n=Io.existsSync(t)?Io.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 D({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return d(o)?
|
|
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
|
+
`,Io.writeFileSync(t,n,"utf8"),le.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)};import Vt from"node:fs";import pn from"node:path";var ia=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)},oa=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",lu=async e=>{let t=await Ln(e);if(d(t))return a(t.message);let n=await fi(e);return d(n)?a(n.message):l("Built sync commit message",`[epiq:sync:${oa(t.value)}:${oa(n.value)}]`)},Ro=async({repoRoot:e,stateBranchName:t})=>{le.info(`Creating ${t}`);let n=await D({args:["commit-tree",Ei,"-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)},uu=async({repoRoot:e,stateBranchName:t})=>{let n=await _r({repoRoot:e});if(d(n))return a(`Ensure local state branch failed
|
|
39
|
+
`+n.message);let r=n.value,o=r?await en({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:ge,branch:t});if(d(c))return a(`Failed to fetch ${t} from remote
|
|
41
|
+
${c.message}`)}let s=await kn({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,`${ge}/${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 Ro({repoRoot:e,stateBranchName:t})},mu=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)},pu=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=tn(pn.dirname(t));if(d(r))return a(`Failed to create state branch worktree
|
|
45
|
+
`+r.message);Vt.existsSync(t)&&!Vt.existsSync(pn.join(t,".git"))&&(le.info("Removing broken state branch worktree path"),bi(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)},Ao=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await mu({repoRoot:e,branch:n});if(d(r))return a(r.message);let o=pn.resolve(t),i=r.value?pn.resolve(r.value):null;if(i&&i===o&&Vt.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&&!Vt.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 gi({repoRoot:e,worktreeRoot:t});if(d(s))return a(s.message);let c=Vt.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 pu({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},gu=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Ln(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)},fu=async({repoRoot:e,stateBranchRoot:t})=>{let n=await jr(t);if(d(n))return a(n.message);if(n.value)return l("State branch upstream already configured",!1);let r=await _r({repoRoot:t});if(d(r))return a(r.message);if(!r.value)return l("No remote available for state branch upstream",!1);let o=yt(e);if(d(o))return o;let i=o.value,s=await en({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:ge,branch:i});if(d(c))return a(`Failed to fetch ${i}
|
|
51
|
+
${c.message}`);let u=await K.setUpstream({cwd:t,branch:i,upstream:`${ge}/${i}`});return d(u)?a(`Failed to set state branch upstream
|
|
52
|
+
${u.message}`):l("Configured state branch upstream",!0)},dr=async({stateBranchRoot:e,eventFileName:t})=>{let n=ht(t),r=pn.join(e,n);if(!Vt.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)},sa=async({repoRoot:e,stateBranchRoot:t})=>{let n=await lu(e);return d(n)?a(`Create state branch sync commit failed
|
|
54
|
+
`+n.message):Ft({cwd:t,message:n.value})},gn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await jr(t);if(d(n))return a(n.message);let r=yt(e);if(d(r))return r;let o=r.value,i=n.value?await K.push({cwd:t}):await K.push({cwd:t,remote:ge,branch:o,setUpstream:!0});return d(i)?a(`Failed during state branch push
|
|
55
|
+
${i.message}`):l("Pushed state branch",!0)},aa=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=yt(e);if(d(o))return o;let i=o.value,s=[Fn(),await uu({repoRoot:e,stateBranchName:i}),await Ao({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await gu({stateBranchRoot:t,stateBranchName:i}),await Ri(t),n?await fu({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 vu,ulid as qe}from"ulid";var fn=vu();function xu(){let e=rt();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]=O(n.id),[o]=r?O(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 yu(){let e=xu();return d(e)?e:A.navigate(e.value)}function da({userId:e,userName:t}){let n=fn(),r=fn(),o=fn(),i=fn(),s=fn(),c=pe(void 0,void 0);if(d(c))return c;let u=pe(void 0,void 0);if(d(u))return u;let m=pe(u.value,void 0);if(d(m))return m;let g=pe(void 0,void 0);if(d(g))return g;let y=pe(g.value,void 0);if(d(y))return y;let N=pe(y.value,void 0);if(d(N))return N;let E=pe(void 0,void 0);return d(E)?E:l("Created default events",[{id:qe(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:qe(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:qe(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:g.value}},{id:qe(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"In progress",parent:r,rank:y.value}},{id:qe(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"Done",parent:r,rank:N.value}},{id:qe(),userId:e,userName:t,action:"add.board",payload:{id:ar,name:"Closed",parent:n,rank:m.value}},{id:qe(),userId:e,userName:t,action:"add.swimlane",payload:{id:Ge,name:"Closed",parent:ar,rank:E.value}},{id:qe(),userId:e,userName:t,action:"lock.node",payload:{id:ar}},{id:qe(),userId:e,userName:t,action:"lock.node",payload:{id:Ge}}])}function cr(e){if(!e.length){let r=z.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=vn(r);return d(o)?o:(S({hasProjectDefinition:!1,mode:p.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=Rt(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 H(16,ct.message);let{rootNodeId:Sd,nodes:Nd}=ct.value,zo=Nd[Sd];return zo?(M.navigate({contextNode:zo,selectedIndex:0}),N({hasProjectDefinition:!0,mode:f.DEFAULT}),c(he,null)):H(16,"Unable to resolve initialized root node")};import{ulid as Zl}from"ulid";import{ulid as Ql}from"ulid";var Js=null,rt=()=>structuredClone(Js),mn=e=>{Js=e},Qs=()=>{let{contextNode:e,selectedIndex:t}=v(),r=U(e.id)[t];return r?c("Resolved selected child",r):s("Target node not found")},ho=({id:e,parentId:t,position:n={at:"end"}})=>{let r=U(t).filter(o=>o.id!==e);return nr(r,n)},Zs=({id:e,parentId:t,position:n={at:"end"}})=>{let r=z();if(d(r))return s("Unable to resolve user ID");let o=ho({parentId:t,id:e,position:n});return d(o)?o:c("Created pending move state",{id:Ql(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},ea=e=>{mn(e);let t=pn(e,!0);return d(t)?t:c("Node moved successfully",t.value)};function Co(e){let t=Qs();if(d(t))return t;let{contextNode:n,nodes:r}=v();if(!n.parentNodeId)return s("Missing parent node id");let o=r[n.parentNodeId];if(!o)return s("Missing parent node");let i=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=Zs({id:t.value.id,parentId:l.id,position:{at:"end"}});return d(u)?u:ea(u.value)}function Eo(e){let t=Qs();if(d(t))return t;let{contextNode:n,selectedIndex:r}=v(),i=U(n.id)[r+e];if(!i)return s("Missing sibling node");let a=Zs({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(a)?a:ea(a.value)}var ta=()=>{let e=rt();if(!e)return s("No pending move state");let t=e.payload.id,n=e.payload.parent,r=v().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"):(M.navigate({contextNode:r,selectedIndex:o}),c("Synchronized navigation to moved node",null))},rr=(e,t="Moved preview")=>{if(d(e))return e;let n=ta();return d(n)?n:(N({mode:f.MOVE}),c(t,null))},na=async()=>{let e=z();if(d(e))return s("Unable to resolve user ID");let{modifier:t}=V().commandMeta,{contextNode:n,selectedIndex:r}=v(),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:x})=>x===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=ho({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(Eo(1));if(t==="previous")return rr(Eo(-1));if(t==="to-next")return rr(Co(1));if(t==="to-previous")return rr(Co(-1));if(t==="confirm"){let i=rt();if(!i)return s("No pending move to confirm");let a=await Ae();if(d(a))return a;let l=we(i,a.value);if(d(l))return l;let u=ta();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 eu,ulid as tu}from"ulid";var nu=eu(),ra=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=nu();return c("Created issue events",[{id:tu(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}}])};var oa=async(e,t)=>{let n=z();if(d(n))return s("Unable to resolve user ID");let r=await Ae();if(d(r))return r;let o=r.value;if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:i,contextNode:a,selectedIndex:l}=v(),u=m=>{let p=we(m,o);if(d(p))return p;let x=b.getNode(p.value.result.id);if(!x)return s("Created node not found");if(!x.parentNodeId)return p;let C=b.getNode(x.parentNodeId);return C?(M.navigate({contextNode:C,selectedIndex:b.getSiblings(x.parentNodeId).findIndex(({id:E})=>E===x.id)}),p):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=v(),p=b.getNode(m);if(!p)return s("Workspace not found");let x=ir(p.id,n.value,o);return d(x)?x:u({id:or(),action:"add.board",payload:{id:or(),name:t.inputString,parent:p.id,rank:x.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 F=Se(i,"SWIMLANE");return d(F)?null:F.value})();if(!p)return s("Unable to add issue in this context");let x=ir(p.id,n.value,o);if(d(x))return x;let C=ra({name:t.inputString,parent:p.id,rank:x.value,user:n.value});if(d(C))return C;let E=C.value,I=ia(E,o);if(I.some(F=>d(F)))return s("Issue create failed: "+I.filter(d).map(F=>F.message).filter(Boolean).join(", "));let k=I[0];if(!k||d(k))return s("Issue creation failed");let w=E.find(F=>F.action==="add.issue")?.payload.id;return w?(M.navigate({contextNode:p,selectedIndex:b.getSiblings(p.id).findIndex(({id:F})=>F===w)}),c("Issue created",null)):s("Unable to determine ticket id")}return c("Success",null)};var sa=async()=>{let e=Se(v().breadCrumb,"BOARD");if(d(e))return e;let t=It(process.cwd());if(d(t))throw new Error(t.message);let n=Ut(t.value);if(d(n))return s(n.message);let r=n.value,{modifier:o}=V().commandMeta,i;if(o==="now"){let C=So();if(d(C))return C;let E=xt(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=v().eventLog.at(-2),E=Gr(C);if(E===null)return s("No previous event to peek");i=E}else if(o==="next"){let C=v().unappliedEvents.at(0),E=Gr(C);if(E===null)return s("No next event to peek");i=E}else{let C=On(o);if(!C)return s("Invalid peek date");i=C.getTime()}let a=e.value.id,{appliedEvents:l,unappliedEvents:u}=Fs(r,i),m=So();if(d(m))return m;let p=xt(l);if(p.some(d))return s(p.map(C=>C.message).join(", "));let x=v().nodes[a];return x?(M.navigate({contextNode:x,selectedIndex:0}),N({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),c("Peeking ",!0)):s("Board did not exist at peek date")};import ru from"zod";var aa=()=>{let e=V().commandMeta.inputString,t=ru.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:(Me({autoSyncIntervalMs:t.data}),N({mode:f.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))};var da=()=>{let e=V().commandMeta.inputString.trim();if(e!=="yes"&&e!=="no")return s("Invalid response");let t=Li(e),n=vt({autoSync:t});return d(n)?n:(Me({autoSync:t}),N({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))};var ca=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 la=e=>Object.values(v().tags).find(t=>t.name===e),ua=e=>Object.values(v().contributors).find(t=>t.name===e),sr=[{systemOnly:!0,intent:T.Move,description:"Internal move-state command",mode:f.COMMAND_LINE,action:na},{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{contextNode:t,selectedIndex:n}=v(),r=O(t.id)[n];return r?Ne({id:ge(),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}=V().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 be(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{contextNode:t,selectedIndex:n}=v(),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=v().nodes[je];if(!o)return s("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return s("Issue is already closed");let i=await Ae();if(d(i))return i;let a=i.value,l=No(o.id,r.id,{at:"end"},e.value,a);if(d(l))return l;let u=await Ne({id:ge(),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{contextNode:t,selectedIndex:n}=v(),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=v().nodes[je];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=$s(i);if(!l)return s("Unable to resolve previous parent from issue history");if(l===a.id)return s("Previous parent resolves to closed swimlane");let u=v().nodes[l];if(!u)return s("Previous parent no longer exists");let m=await Ae();if(d(m))return m;let p=m.value,x=No(u.id,i.id,{at:"end"},e.value,p);if(d(x))return x;let C=await Ne({id:ge(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:x.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:Xs},{intent:T.NewItem,description:"Create a new board, swimlane, or issue",mode:f.COMMAND_LINE,action:oa,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{contextNode:t,selectedIndex:n}=v(),r=O(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=rs();return o?Ne({id:ge(),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}=V().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=la(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();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)?Ne({id:ge(),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}=V().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedNode:o}=v();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=la(r),u;if(l)u=l.id;else{let p=ge(),x=await Ne({id:ge(),action:"create.tag",payload:{id:p,name:r},...e.value});if(d(x))return x;u=x.value.result.id}return(a.props.tags??[]).includes(u)?s("Already tagged with that tag"):Ne({id:ge(),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}=V().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,contextNode:i}=v(),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=ua(r),p;if(m)p=m.id;else{let C=ge(),E=await Ne({id:ge(),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"):Ne({id:ge(),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}=V().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=ua(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();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)?Ne({id:ge(),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:ca},{intent:T.Peek,description:"View board state at another point in time",mode:f.COMMAND_LINE,action:sa},{intent:T.Export,description:"Export the current board layout to markdown",mode:f.COMMAND_LINE,action:async()=>{let e=await Es();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()=>(M.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 Hs();if(t.modifier===et.TITLE){let n=z();if(d(n))return s("Unable to resolve user ID");let{contextNode:r,selectedIndex:o}=v(),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?Ne({id:ge(),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 ne.USERNAME:{let{userId:r,preferredEditor:o,userName:i}=$(),a=n||i,l=r??ge();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:(Me({userName:a,userId:l}),N({mode:f.DEFAULT}),c(`Username set to "${a}"`,null))}case ne.EDITOR:{if(!n)return s("No editor provided");let r=vt({preferredEditor:n});return d(r)?r:(Me({preferredEditor:n}),N({mode:f.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case ne.VIEW:return n!=="wide"&&n!=="dense"?s("Invalid view mode"):(Me({viewMode:n}),c(`View set to "${n}"`,null));case ne.AUTOSYNC:return da();case ne.SYNC_DEBOUNCE_MS:return aa();default:return s("Unknown config command")}}}];var ou=new Set(["peek","filter","view-help"]),ke=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=V();if(!t)return s("No command to confirm");if(!e&&n===pt.Invalid)return s("Invalid command");let i=Hn(t);Qi();let{readOnly:a}=v();if(a&&!ou.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):(Zi({addToHistory:!e}),l.onSuccess?.(),$().autoSync&&Mi(),u)};var ar=[{intent:g.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(N({mode:f.COMMAND_LINE}),_(()=>"move cancel"),ke({isForceExecutedBySystem:!0}))},{intent:g.InitMove,mode:f.DEFAULT,description:"[m] move init/confirm",action:()=>(N({mode:f.COMMAND_LINE}),_(()=>"move start"),ke({isForceExecutedBySystem:!0}))},{intent:g.ConfirmMove,mode:f.MOVE,action:()=>(N({mode:f.COMMAND_LINE}),_(()=>"move confirm"),ke({isForceExecutedBySystem:!0}))}],dr=[{intent:g.MovePreviousItem,mode:f.MOVE,action:()=>rt()?(N({mode:f.COMMAND_LINE}),_(()=>"move previous"),ke({isForceExecutedBySystem:!0})):s("No pending move")},{intent:g.MoveNextItem,mode:f.MOVE,action:()=>rt()?(N({mode:f.COMMAND_LINE}),_(()=>"move next"),ke({isForceExecutedBySystem:!0})):s("No pending move")}],ma=[{intent:g.MoveToNextContainer,mode:f.MOVE,action:()=>rt()?(N({mode:f.COMMAND_LINE}),_(()=>"move to-next"),ke({isForceExecutedBySystem:!0})):s("No pending move")},{intent:g.MoveToPreviousContainer,mode:f.MOVE,action:()=>rt()?(N({mode:f.COMMAND_LINE}),_(()=>"move to-previous"),ke({isForceExecutedBySystem:!0})):s("No pending move")}];var pa={[A.WORKSPACE]:[...ar,...dr],[A.BOARD]:[...ar,...dr],[A.SWIMLANE]:[...ar,...dr,...ma],[A.TICKET]:[],[A.FIELD]:[],[A.FIELD_LIST]:[],[A.TEXT]:[]};import{useSyncExternalStore as bS}from"react";var cr,iu=new Set,fa=()=>{for(let e of iu)e()};var lr=()=>{if(!cr)throw new Error("Ui state not initialized. Call initUiState() first.");return cr};var ga=(e={})=>(cr=e,fa(),c("UX state initialized",null)),su=e=>{let t=lr();return cr=e(t),fa(),c("UX state updated",null)},ur=e=>su(t=>({...t,...e}));var au=e=>{let{pendingNavTarget:t}=lr();N({mode:f.COMMAND_LINE}),t&&M.navigate(t),ur({pendingNavTarget:void 0}),_(()=>`${e} `)},va=()=>{_(()=>"");let{pendingNavTarget:e}=lr();N({mode:f.DEFAULT}),e&&M.navigate(e),ur({pendingNavTarget:void 0})},xa=[{intent:g.InitCommandPalette,mode:f.DEFAULT,description:"[?] command palette",action:()=>{let{contextNode:e,selectedIndex:t}=v();return ur({pendingNavTarget:{contextNode:e,selectedIndex:t}}),N({mode:f.PALETTE}),c("Opening command palette",null)}},{intent:g.Confirm,mode:f.PALETTE,description:"[<Enter>] select command",action:()=>{let{selectedNode:e}=v();if(!e||!Kt(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?(au(t),c("Selected command",t)):c("No command selected",null)}},{intent:g.ExitCommandLine,mode:f.PALETTE,action:()=>(va(),c("Exiting palette",null))},{intent:g.Exit,mode:f.PALETTE,description:"[q] close palette",action:()=>(va(),c("Closed command palette",null))},{intent:g.NavPreviousItem,mode:f.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:g.NavNextItem,mode:f.PALETTE,action:()=>(M.navigateToNextItem(),c("Navigating to next item",null))},{intent:g.NavToPreviousContainer,mode:f.PALETTE,action:()=>(M.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:g.NavToNextContainer,mode:f.PALETTE,action:()=>(M.navigateToNextContainer(),c("Navigating to next container",null))}];var ya=[...xa,{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.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,contextNode:t}=v();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 M.enterChildNode(),c("Entering context",null)}},{intent:g.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(M.enterParentNode(),c("Exiting context",null))},{intent:g.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(M.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:g.NavNextItem,mode:f.DEFAULT,action:()=>(M.navigateToNextItem(),c("Navigating to next item",null))},{intent:g.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(M.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:g.NavToNextContainer,mode:f.DEFAULT,action:()=>(M.navigateToNextContainer(),c("Navigating to next container",null))}];var du=500,cu=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),ha=e=>{let t=cu(e);t&&_(n=>(n+t).slice(0,du))};var lu=[f.COMMAND_LINE,f.PALETTE],uu=e=>[{intent:g.MoveCursorLeft,mode:e,action:()=>(no(-1),c("Moving cursor left",null))},{intent:g.MoveCursorRight,mode:e,action:()=>(no(1),c("Moving cursor right",null))},{intent:g.MoveCursorLeftOfWord,mode:e,action:()=>(ro("left"),c("Moving cursor left of word",null))},{intent:g.MoveCursorRightOfWord,mode:e,action:()=>(ro("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})=>(ha(n??""),c("Capturing input",null))},{intent:g.EraseInput,mode:e,action:()=>(Xi(),c("Erasing input",null))},{intent:g.EraseInputWord,mode:e,action:()=>(Ji(),c("Erasing input word",null))}],Ca=[{intent:g.Confirm,mode:f.COMMAND_LINE,action:()=>(ke(),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))},...lu.flatMap(uu),{intent:g.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(N({mode:f.DEFAULT}),c("Exiting command line",null))},{intent:g.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(es(),c("Getting last command from history",null))},{intent:g.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(ts(),c("Getting next command from history",null))}];import mu from"chalk";var mr=": for command line",Ea="q to exit",Sa=`${mu.hex(h.accent)("m")} to confirm`,bo={[A.WORKSPACE]:[mr],[A.BOARD]:[mr],[A.BOARD+f.COMMAND_LINE]:[mr],[A.SWIMLANE]:[mr],[A.TICKET+f.HELP]:[Ea],[A.SWIMLANE+f.HELP]:[Ea],[A.TICKET]:[],[A.FIELD]:[],[A.SWIMLANE+f.MOVE]:[Sa],[A.TICKET+f.MOVE]:[Sa]};var fn=e=>e.trim().toLocaleLowerCase(),pu=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},fu=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},Na=(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 pu(e).map(fn).some(o=>o.includes(n));case"assignee":return fu(e).map(fn).some(o=>o.includes(n));default:return!0}};function ba(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 Ia=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 yt,Io,Ro=new Set,Ra=()=>{for(let e of Ro)e()},vu=e=>(Ro.add(e),()=>Ro.delete(e));function Aa(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return s("derive(): contextNodeId 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, contextNode not found");let u=ba(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,x=bo[p+n]??bo[p]??[],C=[...ya,...pa[p]??[],...Ca],E=Ia(C),I=xu(o,i),k=I[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:x,availableActions:C,actionIndex:E,selectedNode:k,renderedChildrenIndex:I})}var v=()=>{if(!yt)throw new Error("State not initialized. Call initWorkspaceState() first.");return yt},Qe=()=>yt?c("Retrieved state",yt):s("State not initialized. Call initWorkspaceState() first.");function un(e){Io=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,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1},o=Aa(r);return d(o)?o:(yt=o.value,Ra(),c("State initialized",null))}function be(e){let t=v(),n=e(t),r=Aa(n);return d(r)?s(r.message??"Unable to update state"):(yt=r.value,Ra(),c("State updated",null))}var N=e=>be(t=>({...t,...e}));var Q=()=>gu(vu,v,v),xu=(e,t)=>{let n={};for(let r of Object.values(e))W(r)&&t.length>0&&!t.every(o=>Na(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=>v()?.renderedChildrenIndex[e]??[],So=()=>Io?un(Io):s("Cannot reset state: no initial workspace found"),Tt=()=>yt!==void 0;var ot=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return s("Node not found");if(r.context===t)return c("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return c("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return s(`No ancestor found for context: ${t}`)},Ao=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},ht=(e,t)=>e?e.readonly?s({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node"}[t]):null:s("Node not found"),b={deleteNode(e){be(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return s("Edit target node not found");let o=ht(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=ht(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return U(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let a=ht(o,"move");if(a)return a;if(Ao(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,contextNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,a=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let p of 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=be(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=ht(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=ht(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=ht(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=ht(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=be(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?s("Could not create tag"):c("Tag created",e)},createNode(e){let t=be(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=be(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?s(r.message):c("Locked node",n)},updateNode(e){let t=be(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:c("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return U(e)}};import Ct from"chalk";import wa from"string-width";import{decodeTime as yu}from"ulid";var hu=(e,t)=>e+" ".repeat(Math.max(0,t-wa(e))),Cu=(e,t)=>" ".repeat(Math.max(0,t-wa(e)))+e,Eu=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`),Su=(e,t)=>t?e<t?"up":e>t?"down":null:null,Nu=(e,t)=>{let n=b.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=Su(e.payload.rank,o.rank);if(i)return`Moved ${i} in ${r}`}return`Moved issue to ${r}`},bu=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?Ct.bgHex(de(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?Ct.bgHex(de(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Ct.hex(de(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Ct.hex(de(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""}},Iu=e=>{let t=$i(yu(e));return Ct.gray(Cu(t,8))},Ru=12,Au=e=>hu(`${e}`,Ru),Ta=(e,t)=>{let n=Iu(e.id),r=Au(e.userName),o=Ct.dim("\u203A"),i=e.action==="move.node"?Nu(e,t):[Eu(e.action),bu(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${i}`};var wu=e=>tt(e,"description"),Tu=e=>tt(e,"assignees"),Mu=e=>tt(e,"tags"),Pu=e=>tt(e,"history"),Ma=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:i=!1,childRenderAxis:a="horizontal"})=>{let l=b.getNode(e);if(!l){b.createNode({...re.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)||b.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:i,childRenderAxis:a})},Pa=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:i="horizontal"})=>{let a=b.getNode(e);if(!a){b.createNode({...re.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:i});return}!Vt(a)||!(a.title!==t||a.parentNodeId!==n||a.rank!==r||a.readonly!==o||a.childRenderAxis!==i)||b.updateNode({...a,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:i})},ka=e=>{let t=Re(Be/4n),n=Re(Be/2n),r=Re(Be*3n/4n),o=Re(Be);d(t)||d(n)||d(r)||d(o)||(Ma({id:wu(e.id),name:Y.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"}),Pa({id:Tu(e.id),name:Y.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0}),Pa({id:Mu(e.id),name:Y.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0}),Ma({id:Pu(e.id),name:Y.HISTORY,parentNodeId:e.id,rank:o.value,value:ku(e),readonly:!0,childRenderAxis:"vertical"}))},ku=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=>Ta(r,n.get(r.action)??[])).join(`
|
|
59
|
-
`)};var P=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),La=e=>{let t=b.getNode(e);!t||!W(t)||t.isDeleted||ka(t)},Lu=e=>{for(let t of e){La(t);let n=v().nodes[t]?.parentNodeId;n&&La(n)}},Du=(e,t)=>{let n=b.getNode(e);n&&b.updateNode({...n,log:[...n.log??[],t]})},Fu=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},Bu=e=>{switch(e.action){case"delete.node":case"edit.description":return Fu(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[]}},Ou=e=>{be(t=>({...t,eventLog:[...t.eventLog,e]}))},Uu=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},$u=(e,t)=>{let n=Uu(e);if(n)return n;let r=[...new Set(Bu(e))];return t||(r.forEach(o=>Du(o,e)),Ou(e)),Lu(r),null},Wu={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=re.workspace(t,n,r),i=un(o);if(d(i))return P(i.message,e);let a=b.createNode(o);return d(a)?P(a.message??"Failed to initialize workspace",e):Mr(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=b.createNode(re.workspace(t,n,r));return d(o)?P(o.message??"Failed to add workspace",e):Mr(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=b.createNode(re.board(t,n,r,o));return d(i)?P(i.message??"Unable to create board",e):qo(i.value)?c("Added board",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=b.createNode(re.swimlane(t,n,r,o));return d(i)?P(i.message??"Unable to create swimlane",e):Nt(i.value)?c("Added swimlane",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=b.createNode(re.ticket(t,n,r,o));return d(i)?P(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=b.createNode(re.field({id:t,name:n,parentNodeId:r,rank:i,props:{value:o},childRenderAxis:n.includes(Y.DESCRIPTION)?"vertical":"horizontal"}));return d(a)?P(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(!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):c("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):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=b.createTag({id:t,name:n});return d(r)?P(r.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=b.createContributor({id:t,name:n});return d(r)?P(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=b.tag(t,n);return d(r)?P(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=b.untag(t,n);return d(r)?P(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=b.assign(t,n);return d(r)?P(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=b.unassign(t,n);return d(r)?P(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=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(o)?P(o.message??"Failed to move node",e):c("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=b.editValue(t,n);return d(r)?P(r.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return P("Unable to locate issue",e);if(!W(o))return P("Can only close issues",e);let i=b.getNode(je);if(!i)return P("Unable to locate target swimlane",e);if(n!==i.id)return P("Close target must be closed swimlane",e);let a=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(a)?P(a.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return P("Unable to locate issue",e);if(!W(o))return P("Can only reopen issues",e);let i=b.getNode(je);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 l=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(l)?P(l.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=b.lockNode(t);return d(n)?P(n.message??"Unable to lock node",e):c("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let i=b.getNode(r);if(!i)return P(`Unable to locate node ${r}`,e);if(i.parentNodeId!==t)return P(`Node ${r} is not child of ${t}`,e);let a=b.updateNode({...i,rank:o});if(d(a))return P(a.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})}};function pn(e,t=!1){let n=Wu[e.action](e);if(d(n))return n;let r=$u(e,t);return r||n}var xt=e=>e.map(t=>pn(t));function we(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 ia(e,t){return e.map(n=>we(n,t))}var Ne=async e=>{let t=await Ae();return d(t)?t:we(e,t.value)};var Da=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(me(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(me(void 0,r.rank)):s("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(me(r.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let r=Fa(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(me(o?.rank,i.rank)):s("Sibling not found")}case"after":{let r=Fa(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(me(o.rank,i?.rank)):s("Sibling not found")}}},U=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Fa=(e,t)=>e.findIndex(n=>n.id===t),Ba=(e,t,n={at:"end"})=>nr(U(t).filter(r=>r.id!==e),n),No=(e,t,n,r,o)=>{let i=Ba(t,e,n);if(d(i))return i;if(!i.value.needsRebalance)return c("Resolved rank",i.value.rank);let a=Pr(e,r);if(d(a))return a;let l=we(a.value,o);if(d(l))return l;let u=Ba(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=Da(e);if(d(r))return r;if(!r.value.needsRebalance)return c("Resolved rank",r.value.rank);let o=Pr(e,t);if(d(o))return o;let i=we(o.value,n);if(d(i))return i;let a=Da(e);return d(a)?a:a.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",a.value.rank)};var Ua=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),$a=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},_u=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&&qe(t)&&t.childRenderAxis==="vertical"},pr=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=O(r.id);return M.navigate({contextNode:r,selectedIndex:Ua(t,o.length)}),!0},Wa=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return pr(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?(M.navigate({contextNode:o,selectedIndex:a}),!0):Wa(o.id)},Oa=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Wa(n))return!0;n=t[n]?.parentNodeId}return!1},Hu=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},_a=e=>{let{nodes:t,rootNodeId:n}=v();if(_u(e.contextNodeId)&&pr(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(Hu(e.selectedNodeId)&&e.selectedNodeId&&Oa(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(pr(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&pr(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(Oa(e.contextNodeId))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 M.navigate({contextNode:r,selectedIndex:Ua(e.selectedIndex,o.length)}),c("Restored navigation to root",null)};var wo=({status:e,msg:t})=>{Tt()&&N({syncStatus:{status:e,msg:t}})},To=(e="Syncing...")=>{wo({status:"syncing",msg:e})},Mo=(e="Synced")=>{wo({status:"synced",msg:e})},ju=e=>{wo({status:"failed",msg:e})},G=e=>(ju(e),s(e));var Wt=(e,t)=>(logger.error(`[boot:${e}] ${t}`),s(`[boot:${e}] ${t}`)),Po=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 Ku}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
|
+
`)}`):(yu(),S({hasProjectDefinition:!0}),l("State booted successfully",null))}var Cu=async e=>{let t=await D({cwd:e,args:["status","--porcelain"]});return d(t)?t:l("Checked git diff",t.value.stdout.trim().length>0)},_=(e,t)=>a(`[${e}] ${t}`),la=async()=>{let e=ii(),t=await nt(process.cwd());if(d(t))return _(1,t.message);let n=t.value,r=await Pn(n);if(d(r))return _(2,r.message);if(r.value)return _(2,"Cannot initialize Epiq while a git operation is in progress");let o=await Cu(n);if(d(o))return _(2.5,o.message);if(o.value)return _(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(zr(n))return _(4,"Epiq project already initialized");let i=ot();if(!i.isSetupDone||!i.userName)return _(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let s=H(),c=s.userName,u=s.userId;if(!u||!c)return _(5,"Missing Epiq user id");let m=e.stateBranch,g=await kn({repoRoot:n,branch:m});if(d(g))return _(6,g.message);if(g.value)return _(6,`State branch already exists: ${m}`);let y=await Ro({repoRoot:n,stateBranchName:m});if(d(y))return _(6,y.message);let N=Fn();if(d(N))return _(7,N.message);let E=ca.join(Dn(),e.projectId),I=await Ao({repoRoot:n,stateBranchRoot:E,stateBranchName:m});if(d(I))return _(8,I.message);let w=ca.join(E,".epiq");hu.mkdirSync(w,{recursive:!0});let R=da({userId:u,userName:c});if(d(R))return _(9,R.message);for(let Br of R.value){let ti=sr({event:Br,rootDir:E});if(d(ti))return _(9,ti.message)}let T=await dr({stateBranchRoot:E,eventFileName:mn({userId:u,userName:c})});if(d(T))return _(10,T.message);let F=await Ft({cwd:E,message:"[epiq:init]"});if(d(F))return _(10,F.message);let re=await ra(n);if(d(re))return _(11,re.message);let se=ai({repoRoot:n,fileContents:e});if(d(se))return _(12,se.message);let $e=await K.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d($e))return _(13,$e.message);let vt=await K.commit({cwd:n,message:"[epiq:init-project]"});if(d(vt))return _(13,vt.message);let Ee="Project initialized!",Yt=await D({cwd:n,args:["push","-u","origin","HEAD"]});d(Yt)&&(Ee+=` Warn: [init:14] ${Yt.message}`);let ae=await gn({repoRoot:n,stateBranchRoot:E});d(ae)&&(Ee+=` Warn: [init:15] ${ae.message}`);let kt=Rt(R.value).filter(d);if(kt.length>0)return _(16,kt.map(Br=>Br.message).join(`
|
|
58
|
+
`));let xt=rt();if(d(xt))return _(16,xt.message);let{rootNodeId:Wd,nodes:_d}=xt.value,ei=_d[Wd];return ei?(A.navigate({contextNode:ei,selectedIndex:0}),S({hasProjectDefinition:!0,mode:p.DEFAULT}),l(Ee,null)):_(16,"Unable to resolve initialized root node")};import{ulid as Eu}from"ulid";import{ulid as Nu}from"ulid";var ua=null,ct=()=>structuredClone(ua),xn=e=>{ua=e},ma=()=>{let{contextNode:e,selectedIndex:t}=v(),r=$(e.id)[t];return r?l("Resolved selected child",r):a("Target node not found")},To=({id:e,parentId:t,position:n={at:"end"}})=>{let r=$(t).filter(o=>o.id!==e);return lr(r,n)},pa=({id:e,parentId:t,position:n={at:"end"}})=>{let r=G();if(d(r))return a("Unable to resolve user ID");let o=To({parentId:t,id:e,position:n});return d(o)?o:l("Created pending move state",{id:Nu(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},ga=e=>{xn(e);let t=yn(e,!0);return d(t)?t:l("Node moved successfully",t.value)};function wo(e){let t=ma();if(d(t))return t;let{contextNode:n,nodes:r}=v();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let i=$(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=pa({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:ga(u.value)}function Mo(e){let t=ma();if(d(t))return t;let{contextNode:n,selectedIndex:r}=v(),i=$(n.id)[r+e];if(!i)return a("Missing sibling node");let s=pa({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(s)?s:ga(s.value)}var fa=()=>{let e=ct();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=v().nodes[n];if(!r)return a("Move parent not found");let o=$(n).findIndex(i=>i.id===t);return o===-1?a("Moved node not found among rendered children"):(A.navigate({contextNode:r,selectedIndex:o}),l("Synchronized navigation to moved node",null))},ur=(e,t="Moved preview")=>{if(d(e))return e;let n=fa();return d(n)?n:(S({mode:p.MOVE}),l(t,null))},va=async()=>{let e=G();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=V().commandMeta,{contextNode:n,selectedIndex:r}=v(),o=$(n.id)[r];if(!o)return S({mode:p.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=$(o.parentNodeId),s=i.findIndex(({id:y})=>y===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"},g=To({parentId:o.parentNodeId,id:o.id,position:m});return d(g)?g:(xn({id:Eu(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:g.value.rank},...e.value}),S({mode:p.MOVE}),l("Move initialized",null))}if(t==="next")return ur(Mo(1));if(t==="previous")return ur(Mo(-1));if(t==="to-next")return ur(wo(1));if(t==="to-previous")return ur(wo(-1));if(t==="confirm"){let i=ct();if(!i)return a("No pending move to confirm");let s=await Pe();if(d(s))return s;let c=ke(i,s.value);if(d(c))return c;let u=fa();return d(u)?u:(xn(null),S({mode:p.DEFAULT}),l("Moved item",null))}return t==="cancel"?(xn(null),S({mode:p.DEFAULT}),l("Cancelling move",null)):a("Invalid move modifier")};import{ulid as mr}from"ulid";import{monotonicFactory as Su,ulid as bu}from"ulid";var Iu=Su(),xa=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=Iu();return l("Created issue events",[{id:bu(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}}])};var ya=async(e,t)=>{let n=G();if(d(n))return a("Unable to resolve user ID");let r=await Pe();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}=v(),u=m=>{let g=ke(m,o);if(d(g))return g;let y=b.getNode(g.value.result.id);if(!y)return a("Created node not found");if(!y.parentNodeId)return g;let N=b.getNode(y.parentNodeId);return N?(A.navigate({contextNode:N,selectedIndex:b.getSiblings(y.parentNodeId).findIndex(({id:E})=>E===y.id)}),g):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=v(),g=b.getNode(m);if(!g)return a("Workspace not found");let y=pr(g.id,n.value,o);return d(y)?y:u({id:mr(),action:"add.board",payload:{id:mr(),name:t.inputString,parent:g.id,rank:y.value},...n.value})}if(t.modifier==="swimlane"){let m=Ie(i,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let g=pr(m.value.id,n.value,o);return d(g)?g:u({id:mr(),action:"add.swimlane",payload:{id:mr(),name:t.inputString,parent:m.value.id,rank:g.value},...n.value})}if(t.modifier==="issue"){let m=O(s.id)[c],g=s.context==="SWIMLANE"?s:s.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let F=Ie(i,"SWIMLANE");return d(F)?null:F.value})();if(!g)return a("Unable to add issue in this context");let y=pr(g.id,n.value,o);if(d(y))return y;let N=xa({name:t.inputString,parent:g.id,rank:y.value,user:n.value});if(d(N))return N;let E=N.value,I=ha(E,o);if(I.some(F=>d(F)))return a("Issue create failed: "+I.filter(d).map(F=>F.message).filter(Boolean).join(", "));let w=I[0];if(!w||d(w))return a("Issue creation failed");let T=E.find(F=>F.action==="add.issue")?.payload.id;return T?(A.navigate({contextNode:g,selectedIndex:b.getSiblings(g.id).findIndex(({id:F})=>F===T)}),l("Issue created",null)):a("Unable to determine ticket id")}return l("Success",null)};var Ca=async()=>{let e=Ie(v().breadCrumb,"BOARD");if(d(e))return e;let t=await nt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=Bt({repoRoot:t.value});if(d(n))throw new Error(n.message);let{modifier:r}=V().commandMeta;if(r==="now"){let I=Kt(n.value);if(d(I))return a(I.message);let w=hn();if(d(w))return w;let T=Rt(I.value).filter(d);return T.length>0?a(T.map(F=>F.message).join(", ")):(S({mode:p.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),l("Peeking now",!0))}let o;if(r==="prev"){let I=v().eventLog.at(-1),w=eo(I);if(w===null)return a("No previous event to peek");o=w}else if(r==="next"){let I=v().unappliedEvents.at(0),w=eo(I);if(w===null)return a("No next event to peek");o=w+1}else{let I=jn(r);if(!I)return a("Invalid peek date");o=I.getTime()}let i=v(),s=e.value.id,c=qs(n.value,o);if(d(c))return a(c.message);let{appliedEvents:u,unappliedEvents:m}=c.value,g=hn();if(d(g))return g;let N=Rt(u).filter(d);if(N.length>0)return hn(),S(i),a(N.map(I=>I.message).join(", "));let E=v().nodes[s];return E?(A.navigate({contextNode:E,selectedIndex:0}),S({mode:p.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:m}),l("Peeking",!0)):(hn(),S(i),a("Board did not exist at peek date"))};import Ru from"zod";var Na=()=>{let e=V().commandMeta.inputString,t=Ru.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=It({autoSyncDebounceMs:t.data});return d(n)?n:(De({autoSyncIntervalMs:t.data}),S({mode:p.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))};var Ea=()=>{let e=V().commandMeta.inputString.trim();if(e!=="yes"&&e!=="no")return a("Invalid response");let t=_i(e),n=It({autoSync:t});return d(n)?n:(De({autoSync:t}),S({mode:p.DEFAULT}),l(`Auto sync set to "${e}"`,null))};var Sa=async()=>{U(()=>""),S({mode:p.DEFAULT});let e=rt();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");S({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Hn();return d(t)?(S({syncStatus:{msg:t.message,status:"failed"}}),t):(S({mode:p.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{useSyncExternalStore as iE}from"react";var gr,Au=new Set,ba=()=>{for(let e of Au)e()};var lt=()=>{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)),Tu=e=>{let t=lt();return gr=e(t),ba(),l("UX state updated",null)},ut=e=>Tu(t=>({...t,...e}));var Ra=e=>Object.values(v().tags).find(t=>t.name===e),Aa=e=>Object.values(v().contributors).find(t=>t.name===e),fr=[{systemOnly:!0,intent:P.Move,description:"Internal move-state command",mode:p.COMMAND_LINE,action:va},{intent:P.Delete,description:"Delete the currently selected node",mode:p.COMMAND_LINE,action:async()=>{let e=G();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=O(t.id)[n];return r?Ae({id:ye(),action:"delete.node",payload:{id:r.id},...e.value}):a("Unable to resolve child to delete")},onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:p.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=V().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(s=>Q(x.FILTER).map(c=>c.split(n)[0]).includes(s))(r))return a("Invalid filter modifier");let i={target:r,operator:"=",value:t.trim()};return Te(s=>({...s,filters:e==="clear"?[]:[...s.filters,i],mode:p.DEFAULT})),l("Filter updated",null)}},{intent:P.ViewHelp,description:"Open the help screen",mode:p.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return ut({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),S({mode:p.HELP}),l("Viewing help",null)}},{intent:P.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:p.COMMAND_LINE,action:async()=>{let e=G();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=O(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=v().nodes[Ge];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let i=await Pe();if(d(i))return i;let s=i.value,c=Po(o.id,r.id,{at:"end"},e.value,s);if(d(c))return c;let u=await Ae({id:ye(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value});return d(u)?u:l("Issue closed",null)},onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:p.COMMAND_LINE,action:async()=>{let e=G();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=O(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?l("Resolved ticket",r):mt(r.id,"TICKET");if(d(o))return a("Cannot reopen in this context");let i=o.value,s=v().nodes[Ge];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=Zs(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=v().nodes[c];if(!u)return a("Previous parent no longer exists");let m=await Pe();if(d(m))return m;let g=m.value,y=Po(u.id,i.id,{at:"end"},e.value,g);if(d(y))return y;let N=await Ae({id:ye(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:y.value},...e.value});return d(N)?N:l("Issue reopened",null)},onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.Init,description:"Initialize Epiq in the current git repository",mode:p.COMMAND_LINE,action:la},{intent:P.NewItem,description:"Create a new board, swimlane, or issue",mode:p.COMMAND_LINE,action:ya,onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.Rename,description:"itle] Rename the currently selected node",mode:p.COMMAND_LINE,action:async()=>{let e=G();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=O(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=ys();return o?Ae({id:ye(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):a("Provide a title")},onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.UntagTicket,description:"Remove a tag from the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=G();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=Ra(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return a("Invalid untag target");let s=mt(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)?Ae({id:ye(),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:()=>S({mode:p.DEFAULT})},{intent:P.TagTicket,description:"Add or create a tag on the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=G();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}=v();if(!o)return a("Invalid tag target");let i=mt(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=Ra(r),u;if(c)u=c.id;else{let g=ye(),y=await Ae({id:ye(),action:"create.tag",payload:{id:g,name:r},...e.value});if(d(y))return y;u=y.value.result.id}return(s.props.tags??[]).includes(u)?a("Already tagged with that tag"):Ae({id:ye(),action:"add.issue.tag",payload:{id:s.id,tag:u},...e.value})},onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.AssignUserToTicket,description:"Assign a user to the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=G();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}=v(),s=O(i.id)[o];if(!s)return a("Invalid assign target");let c=mt(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=Aa(r),g;if(m)g=m.id;else{let N=ye(),E=await Ae({id:ye(),action:"create.contributor",payload:{id:N,name:r},...e.value});if(d(E))return E;g=E.value.result.id}return(u.props.assignees??[]).includes(g)?a("Assignee already assigned"):Ae({id:ye(),action:"add.issue.assignee",payload:{id:u.id,assignee:g},...e.value})},onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:p.COMMAND_LINE,action:async()=>{let e=G();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=Aa(r);if(!o)return a(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return a("Invalid unassign target");let s=mt(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)?Ae({id:ye(),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:()=>S({mode:p.DEFAULT})},{intent:P.Sync,description:"Pull, commit, and push Epiq state",mode:p.COMMAND_LINE,action:Sa},{intent:P.Peek,description:"View board state at another point in time",mode:p.COMMAND_LINE,action:Ca},{intent:P.Export,description:"Export the current board layout to markdown",mode:p.COMMAND_LINE,action:async()=>{let e=await Bs();return d(e)?e:(S({mode:p.DEFAULT}),l("Export successful",!0))}},{intent:P.Exit,description:"Exit the application",mode:p.COMMAND_LINE,action:async()=>(A.exit(),l("Exit successful",!0))},{intent:P.Edit,description:"Edit title or description",mode:p.COMMAND_LINE,action:async(e,t)=>{if(t.modifier===it.DESCRIPTION)return na();if(t.modifier===it.TITLE){let n=G();if(d(n))return a("Unable to resolve user ID");let{contextNode:r,selectedIndex:o}=v(),i=O(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?Ae({id:ye(),action:"edit.title",payload:{id:i.id,name:s},...n.value}):a("Provide a title")}return a("Unknown edit command")},onSuccess:()=>S({mode:p.DEFAULT})},{intent:P.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:p.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case oe.USERNAME:{let{userId:r,preferredEditor:o,userName:i}=H(),s=n||i,c=r??ye();if(!s||!c)return a("Unable to resolve user name or id");let u=It({userName:s,userId:c,preferredEditor:o??""});return d(u)?u:(De({userName:s,userId:c}),S({mode:p.DEFAULT}),l(`Username set to "${s}"`,null))}case oe.EDITOR:{if(!n)return a("No editor provided");let r=It({preferredEditor:n});return d(r)?r:(De({preferredEditor:n}),S({mode:p.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case oe.VIEW:return n!=="wide"&&n!=="dense"?a("Invalid view mode"):(De({viewMode:n}),l(`View set to "${n}"`,null));case oe.AUTOSYNC:return Ea();case oe.SYNC_DEBOUNCE_MS:return Na();default:return a("Unknown config command")}}}];var wu=new Set(["peek","filter","view-help"]),Be=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===Et.Invalid)return a("Invalid command");let i=Xn(t);ps();let{readOnly:s}=v();if(s&&!wu.has(i))return dn({status:Ze.Fail,message:"Command not available in readonly state",value:null});let c=fr.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===i);if(!c)return dn({status:Ze.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return dn({status:Ze.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?dn(u):(gs({addToHistory:!e}),c.onSuccess?.(),H().autoSync&&$i(),u)};var vr=[{intent:f.Exit,mode:p.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(S({mode:p.COMMAND_LINE}),U(()=>"move cancel"),Be({isForceExecutedBySystem:!0}))},{intent:f.InitMove,mode:p.DEFAULT,description:"[m] move (init/confirm)",action:()=>(S({mode:p.COMMAND_LINE}),U(()=>"move start"),Be({isForceExecutedBySystem:!0}))},{intent:f.ConfirmMove,mode:p.MOVE,action:()=>(S({mode:p.COMMAND_LINE}),U(()=>"move confirm"),Be({isForceExecutedBySystem:!0}))}],xr=[{intent:f.MovePreviousItem,mode:p.MOVE,action:()=>ct()?(S({mode:p.COMMAND_LINE}),U(()=>"move previous"),Be({isForceExecutedBySystem:!0})):a("No pending move")},{intent:f.MoveNextItem,mode:p.MOVE,action:()=>ct()?(S({mode:p.COMMAND_LINE}),U(()=>"move next"),Be({isForceExecutedBySystem:!0})):a("No pending move")}],Ta=[{intent:f.MoveToNextContainer,mode:p.MOVE,action:()=>ct()?(S({mode:p.COMMAND_LINE}),U(()=>"move to-next"),Be({isForceExecutedBySystem:!0})):a("No pending move")},{intent:f.MoveToPreviousContainer,mode:p.MOVE,action:()=>ct()?(S({mode:p.COMMAND_LINE}),U(()=>"move to-previous"),Be({isForceExecutedBySystem:!0})):a("No pending move")}];var wa={[M.WORKSPACE]:[...vr,...xr],[M.BOARD]:[...vr,...xr],[M.SWIMLANE]:[...vr,...xr,...Ta],[M.TICKET]:[],[M.FIELD]:[],[M.FIELD_LIST]:[],[M.TEXT]:[]};var Ma=()=>{U(()=>"");let{pendingNavTarget:e}=lt();S({mode:p.DEFAULT}),e&&A.navigate(e),ut({pendingNavTarget:void 0})},Pa=[{intent:f.ExitCommandLine,mode:p.HELP,action:()=>(Ma(),l("Exiting help",null))},{intent:f.Exit,mode:p.HELP,action:()=>(Ma(),l("Closed help",null))},{intent:f.NavPreviousItem,mode:p.HELP,description:"[arrows/hjkl] navigate",action:()=>(A.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:f.NavNextItem,mode:p.HELP,action:()=>(A.navigateToNextItem(),l("Navigating to next help item",null))},{intent:f.NavToPreviousContainer,mode:p.HELP,action:()=>(A.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:f.NavToNextContainer,mode:p.HELP,action:()=>(A.navigateToNextContainer(),l("Navigating to next help container",null))}];var Mu=e=>{S({mode:p.COMMAND_LINE});let{pendingNavTarget:t}=lt();t&&A.navigate(t),ut({pendingNavTarget:void 0}),U(()=>`${e} `)},ka=()=>{U(()=>"");let{pendingNavTarget:e}=lt();e&&A.navigate(e),ut({pendingNavTarget:void 0}),S({mode:p.DEFAULT})},La=[{intent:f.InitCommandPalette,mode:p.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{U(()=>"");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return ut({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),S({mode:p.PALETTE}),l("Opening command palette",null)}},{intent:f.Confirm,mode:p.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!Je(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?(Mu(t),l("Selected command",t)):l("No command selected",null)}},{intent:f.ExitCommandLine,mode:p.PALETTE,action:()=>(ka(),l("Exiting palette",null))},{intent:f.Exit,mode:p.PALETTE,action:()=>(ka(),l("Closed command palette",null))},{intent:f.NavPreviousItem,mode:p.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(A.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:f.NavNextItem,mode:p.PALETTE,action:()=>(A.navigateToNextItem(),l("Navigating to next item",null))},{intent:f.NavToPreviousContainer,mode:p.PALETTE,action:()=>(A.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:f.NavToNextContainer,mode:p.PALETTE,action:()=>(A.navigateToNextContainer(),l("Navigating to next container",null))}];var Da=[...Pa,...La,{intent:f.AddItem,mode:p.DEFAULT,description:"[n] new...",action:()=>(S({mode:p.COMMAND_LINE}),U(()=>`${x.NEW} `),l("Adding new item",null))},{intent:f.Delete,mode:p.DEFAULT,description:"[d] delete",action:()=>(S({mode:p.COMMAND_LINE}),U(()=>`${x.DELETE} `),l("Deleting item",null))},{intent:f.InitCommandLine,mode:p.DEFAULT,description:"[:] focus command line",action:()=>(S({mode:p.COMMAND_LINE}),U(()=>""),l("Entering command line mode",null))},{intent:f.Confirm,mode:p.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!$(e?.id??"")?.length){if(e?.title===J.DESCRIPTION)return S({mode:p.COMMAND_LINE}),U(()=>`${x.EDIT} description `),l("Propose command",!0);if(e?.title===J.ASSIGNEES)return S({mode:p.COMMAND_LINE}),U(()=>`${x.ASSIGN} `),l("Propose command",!0);if(e?.title===J.TAGS)return S({mode:p.COMMAND_LINE}),U(()=>`${x.TAG} `),l("Propose command",!0);if(t.title===J.DESCRIPTION&&e?.context==="TEXT")return S({mode:p.COMMAND_LINE}),U(()=>`${x.EDIT} description `),l("Propose command",!0)}return A.enterChildNode(),l("Entering context",null)}},{intent:f.EditTitle,mode:p.DEFAULT,description:"[r] rename title",action:()=>(S({mode:p.COMMAND_LINE}),U(()=>`${x.EDIT} title ${v().selectedNode?.title}`),l("Exiting context",null))},{intent:f.EditDescription,mode:p.DEFAULT,description:"[e] edit description",action:()=>(S({mode:p.COMMAND_LINE}),U(()=>`${x.EDIT} description `),l("Exiting context",null))},{intent:f.Exit,mode:p.DEFAULT,description:"[q] exit context",action:()=>(S({mode:p.DEFAULT}),A.enterParentNode(),l("Exiting context",null))},{intent:f.NavPreviousItem,mode:p.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(A.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:f.NavNextItem,mode:p.DEFAULT,action:()=>(A.navigateToNextItem(),l("Navigating to next item",null))},{intent:f.NavToPreviousContainer,mode:p.DEFAULT,action:()=>(A.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:f.NavToNextContainer,mode:p.DEFAULT,action:()=>(A.navigateToNextContainer(),l("Navigating to next container",null))}];var Pu=500,ku=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Fa=e=>{let t=ku(e);t&&U(n=>(n+t).slice(0,Pu))};var Lu=[p.COMMAND_LINE,p.PALETTE],Du=e=>[{intent:f.MoveCursorLeft,mode:e,action:()=>(lo(-1),l("Moving cursor left",null))},{intent:f.MoveCursorRight,mode:e,action:()=>(lo(1),l("Moving cursor right",null))},{intent:f.MoveCursorLeftOfWord,mode:e,action:()=>(uo("left"),l("Moving cursor left of word",null))},{intent:f.MoveCursorRightOfWord,mode:e,action:()=>(uo("right"),l("Moving cursor right of word",null))},{intent:f.AutoCompleteCommand,mode:e,action:()=>(U((t,{remainder:n})=>n?t+n:t),l("Auto-completing command",null))},{intent:f.CaptureInput,mode:e,action:(t,{sequence:n})=>(Fa(n??""),l("Capturing input",null))},{intent:f.EraseInput,mode:e,action:()=>(us(),l("Erasing input",null))},{intent:f.EraseInputWord,mode:e,action:()=>(ms(),l("Erasing input word",null))}],Ba=[{intent:f.Confirm,mode:p.COMMAND_LINE,action:()=>(Be(),l("Executing command",null))},{intent:f.ViewHelp,mode:p.DEFAULT,action:()=>(S({mode:p.HELP}),l("Viewing help",null))},...Lu.flatMap(Du),{intent:f.ExitCommandLine,mode:p.COMMAND_LINE,action:()=>(S({mode:p.DEFAULT}),l("Exiting command line",null))},{intent:f.GetLastCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(fs(),l("Getting last command from history",null))},{intent:f.GetNextCommandFromHistory,mode:p.COMMAND_LINE,action:()=>(vs(),l("Getting next command from history",null))}];import $a from"chalk";var yr=$a.dim.hex(h.secondary2)(": for command line"),Ua="q to exit",Oa=`${$a.hex(h.accent)("m")} to confirm`,ko={[M.WORKSPACE]:[yr],[M.BOARD]:[yr],[M.BOARD+p.COMMAND_LINE]:[yr],[M.SWIMLANE]:[yr],[M.TICKET+p.HELP]:[Ua],[M.SWIMLANE+p.HELP]:[Ua],[M.TICKET]:[],[M.FIELD]:[],[M.SWIMLANE+p.MOVE]:[Oa],[M.TICKET+p.MOVE]:[Oa]};var Cn=e=>e.trim().toLocaleLowerCase(),Fu=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Bu=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>t[n]?.name).filter(n=>!!n)},Ha=(e,t)=>{let n=Cn(t.value);if(!n)return!0;switch(t.target){case"title":return Cn(e.title??"").includes(n);case"description":return Cn(e.props.description??"").includes(n);case"tag":return Fu(e).map(Cn).some(o=>o.includes(n));case"assignee":return Bu(e).map(Cn).some(o=>o.includes(n));default:return!0}};function Wa(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 _a=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 At,Lo,Do=new Set,ja=()=>{for(let e of Do)e()},Ou=e=>(Do.add(e),()=>Do.delete(e));function Ka(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=Wa(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:g}=c,y=ko[g+n]??ko[g]??[],N=[...Da,...wa[g]??[],...Ba],E=_a(N),I=$u(o,i),w=I[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:y,availableActions:N,actionIndex:E,selectedNode:w,renderedChildrenIndex:I})}var v=()=>{if(!At)throw new Error("State not initialized. Call initWorkspaceState() first.");return At},rt=()=>At?l("Retrieved state",At):a("State not initialized. Call initWorkspaceState() first.");function vn(e){Lo=e;let t=tt(process.cwd()),n=!1;if(!d(t)){let i=et(t.value);if(d(i))return a(i.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:p.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=Ka(r);return d(o)?o:(At=o.value,ja(),l("State initialized",null))}function Te(e){let t=v(),n=e(t),r=Ka(n);return d(r)?a(r.message??"Unable to update state"):(At=r.value,ja(),l("State updated",null))}var S=e=>Te(t=>({...t,...e}));var te=()=>Uu(Ou,v,v),$u=(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 s=e[o.id],c=e[i.id];return!s||!c?0:s.rank.localeCompare(c.rank)});return n},O=e=>v()?.renderedChildrenIndex[e]??[],hn=()=>Lo?vn(Lo):a("Cannot reset state: no initial workspace found"),Ot=()=>At!==void 0;var mt=(e,t)=>{let{nodes:n}=v(),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}`)},Fo=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Tt=(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){Te(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return a("Edit target node not found");let o=Tt(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=Tt(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return $(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return 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=Tt(o,"move");if(s)return s;if(Fo(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}=v(),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 g of $(m.id))s(g.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?(S({nodes:c}),l("Successfully tomb stoned",o)):a("Unable to delete undefined")},createContributor(e){let t=Te(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=Tt(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=Tt(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=Tt(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=Tt(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=Te(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):l("Tag created",e)},createNode(e){let t=Te(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=Te(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?a(r.message):l("Locked node",n)},updateNode(e){let t=Te(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return $(e)}};import wt from"chalk";import Va from"string-width";import{decodeTime as Hu}from"ulid";var Wu=(e,t)=>e+" ".repeat(Math.max(0,t-Va(e))),_u=(e,t)=>" ".repeat(Math.max(0,t-Va(e)))+e,ju=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`),Ku=(e,t)=>t?e<t?"up":e>t?"down":null:null,Vu=(e,t)=>{let n=b.getNode(e.payload.parent),r=n?wt.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let i=Ku(e.payload.rank,o.rank);if(i)return`Moved ${i} in ${r}`}return`Moved issue to ${r}`},zu=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?wt.bgHex(Re(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?wt.bgHex(Re(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?wt.hex(Re(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?wt.hex(Re(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;default:return""}},Gu=e=>{let t=qi(Hu(e));return wt.gray(_u(t,8))},qu=12,Yu=e=>Wu(`${e}`,qu),za=(e,t)=>{let n=Gu(e.id),r=Yu(e.userName),o=wt.dim("\u203A"),i=e.action==="move.node"?Vu(e,t):[ju(e.action),zu(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${i}`};var Xu=e=>at(e,"description"),Ju=e=>at(e,"assignees"),Qu=e=>at(e,"tags"),Zu=e=>at(e,"history"),Ga=({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({...z.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:i,childRenderAxis:s});return}!Qe(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})},qa=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:i="horizontal"})=>{let s=b.getNode(e);if(!s){b.createNode({...z.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:i});return}!Xt(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})},Ya=e=>{let t=Me(He/4n),n=Me(He/2n),r=Me(He*3n/4n),o=Me(He);d(t)||d(n)||d(r)||d(o)||(Ga({id:Xu(e.id),name:J.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"}),qa({id:Ju(e.id),name:J.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0}),qa({id:Qu(e.id),name:J.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0}),Ga({id:Zu(e.id),name:J.HISTORY,parentNodeId:e.id,rank:o.value,value:em(e),readonly:!0,childRenderAxis:"vertical"}))},em=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=>za(r,n.get(r.action)??[])).join(`
|
|
59
|
+
`)};var k=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Xa=e=>{let t=b.getNode(e);!t||!W(t)||t.isDeleted||Ya(t)},tm=e=>{for(let t of e){Xa(t);let n=v().nodes[t]?.parentNodeId;n&&Xa(n)}},nm=(e,t)=>{let n=b.getNode(e);n&&b.updateNode({...n,log:[...n.log??[],t]})},rm=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},om=e=>{switch(e.action){case"delete.node":case"edit.description":return rm(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[]}},im=e=>{Te(t=>({...t,eventLog:[...t.eventLog,e]}))},sm=e=>{let t=e.userId,n=e.userName;if(!t?.length||!n?.length)return k("Invalid user ID format",e);let r=b.createContributor({id:t,name:n});return d(r)?k(r.message,e):null},am=(e,t)=>{let n=sm(e);if(n)return n;let r=[...new Set(om(e))];return t||(r.forEach(o=>nm(o,e)),im(e)),tm(r),null},dm={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=z.workspace(t,n,r),i=vn(o);if(d(i))return k(i.message,e);let s=b.createNode(o);return d(s)?k(s.message??"Failed to initialize workspace",e):Ur(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(z.workspace(t,n,r));return d(o)?k(o.message??"Failed to add workspace",e):Ur(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(z.board(t,n,r,o));return d(i)?k(i.message??"Unable to create board",e):ni(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(z.swimlane(t,n,r,o));return d(i)?k(i.message??"Unable to create swimlane",e):Lt(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(z.ticket(t,n,r,o));return d(i)?k(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(z.field({id:t,name:n,parentNodeId:r,rank:i,props:{value:o},childRenderAxis:n.includes(J.DESCRIPTION)?"vertical":"horizontal"}));return d(s)?k(s.message??`Unable to create field: ${n}`,e):Qe(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 k(`Unable to locate node with id ${t}`,e);let o=b.renameNode(t,n);return d(o)?k(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=b.tombstoneNode(t);return d(n)?k(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=b.createTag({id:t,name:n});return d(r)?k(r.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=b.createContributor({id:t,name:n});return d(r)?k(r.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=b.tag(t,n);return d(r)?k(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)?k(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)?k(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)?k(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)?k(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=b.editValue(t,n);return d(r)?k(r.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=b.getNode(t);if(!o)return k("Unable to locate issue",e);if(!W(o))return k("Can only close issues",e);let i=b.getNode(Ge);if(!i)return k("Unable to locate target swimlane",e);if(n!==i.id)return k("Close target must be closed swimlane",e);let s=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(s)?k(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 k("Unable to locate issue",e);if(!W(o))return k("Can only reopen issues",e);let i=b.getNode(Ge);if(!i)return k("Unable to locate closed swimlane",e);if(n===i.id)return k("Cannot reopen issue into closed swimlane",e);if(!b.getNode(n))return k("Reopen parent no longer exists",e);let c=b.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?k(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=b.lockNode(t);return d(n)?k(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let i=b.getNode(r);if(!i)return k(`Unable to locate node ${r}`,e);if(i.parentNodeId!==t)return k(`Node ${r} is not child of ${t}`,e);let s=b.updateNode({...i,rank:o});if(d(s))return k(s.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})}};function yn(e,t=!1){let n=dm[e.action](e);if(d(n))return n;let r=am(e,t);return r||n}var Rt=e=>e.map(t=>yn(t));function ke(e,t){let n=yn(e);if(n.status!==Ze.Success)return n;let r=sr({event:e,rootDir:t});return d(r)?r:n}function ha(e,t){return e.map(n=>ke(n,t))}var Ae=async e=>{let t=await Pe();return d(t)?t:ke(e,t.value)};var Ja=e=>lr($(e),{at:"end"}),lr=(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(pe(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(pe(void 0,r.rank)):a("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(pe(r.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let r=Qa(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(pe(o?.rank,i.rank)):a("Sibling not found")}case"after":{let r=Qa(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(pe(o.rank,i?.rank)):a("Sibling not found")}}},$=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Qa=(e,t)=>e.findIndex(n=>n.id===t),Za=(e,t,n={at:"end"})=>lr($(t).filter(r=>r.id!==e),n),Po=(e,t,n,r,o)=>{let i=Za(t,e,n);if(d(i))return i;if(!i.value.needsRebalance)return l("Resolved rank",i.value.rank);let s=Or(e,r);if(d(s))return s;let c=ke(s.value,o);if(d(c))return c;let u=Za(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)},pr=(e,t,n)=>{let r=Ja(e);if(d(r))return r;if(!r.value.needsRebalance)return l("Resolved rank",r.value.rank);let o=Or(e,t);if(d(o))return o;let i=ke(o.value,n);if(d(i))return i;let s=Ja(e);return d(s)?s:s.value.needsRebalance?a("Rank rebalance failed to create space"):l("Resolved rank after rebalance",s.value.rank)};var td=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),nd=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},cm=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&&Qe(t)&&t.childRenderAxis==="vertical"},hr=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=O(r.id);return A.navigate({contextNode:r,selectedIndex:td(t,o.length)}),!0},rd=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return hr(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let s=$(o.id).findIndex(c=>c.id===n.id);return s>=0?(A.navigate({contextNode:o,selectedIndex:s}),!0):rd(o.id)},ed=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),rd(n))return!0;n=t[n]?.parentNodeId}return!1},lm=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},od=e=>{let{nodes:t,rootNodeId:n}=v();if(cm(e.contextNodeId)&&hr(e.contextNodeId,e.selectedIndex))return l("Restored navigation inside text container",null);if(lm(e.selectedNodeId)&&e.selectedNodeId&&ed(e.selectedNodeId))return l("Restored navigation to selected node or ancestor",null);if(hr(e.contextNodeId,e.selectedIndex))return l("Restored navigation to previous container",null);if(e.parentNodeId&&hr(e.parentNodeId,e.selectedIndex))return l("Restored navigation to previous parent",null);if(ed(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=O(r.id);return A.navigate({contextNode:r,selectedIndex:td(e.selectedIndex,o.length)}),l("Restored navigation to root",null)};var Bo=({status:e,msg:t})=>{Ot()&&S({syncStatus:{status:e,msg:t}})},Uo=(e="Syncing...")=>{Bo({status:"syncing",msg:e})},Oo=(e="Synced")=>{Bo({status:"synced",msg:e})},um=e=>{Bo({status:"failed",msg:e})},q=e=>(um(e),a(e));var zt=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),$o=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 mm}from"ulid";var Nn=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)},Ho=e=>{let[t,n]=e.id;return`${t}:${n??""}`},id=e=>{try{return mm(e.id[0])}catch{return 0}},Wo=(e,t)=>{let n=new Map;for(let r of[...e,...t])n.set(Ho(r),r);return[...n.values()].sort((r,o)=>{let i=id(r)-id(o);return i!==0?i:Ho(r).localeCompare(Ho(o))})},_o=e=>e.length===0?"":e.map(t=>JSON.stringify(t)).join(`
|
|
61
61
|
`)+`
|
|
62
|
-
`;var fr=e=>Ie.existsSync(e)?Ie.readFileSync(e,"utf8"):null,za=(e,t)=>fr(e)===t?!1:(Ie.mkdirSync(Et.dirname(e),{recursive:!0}),Ie.writeFileSync(e,t,"utf8"),!0),Vu=({stateBranchRoot:e,ownEventFileName:t})=>Et.join(e,ut(t)),zu=async({stateBranchRoot:e,ownEventFileName:t})=>{let n=ut(t),r=Et.join(e,n);return(await Ce({cwd:e,args:["checkout","--",n]})).exitCode!==0&&Ie.existsSync(r)&&Ie.rmSync(r,{force:!0}),c("Restored own event file to HEAD",null)},ja=({ownEventPath:e,ownSnapshot:t})=>{if(t===null)return c("No own snapshot to merge",!1);let n=fr(e)??"",r=gn(n);if(d(r))return s(r.message);let o=gn(t);if(d(o))return s(o.message);let i=Lo(r.value,o.value),a=za(e,Do(i));return c("Merged own snapshot",a)},Gu=e=>{let t=Et.join(e,".epiq","events"),n=new Map;if(!Ie.existsSync(t))return c("No event files to snapshot",n);for(let r of Ie.readdirSync(t)){if(!r.endsWith(".jsonl"))continue;let o=Et.join(t,r);Ie.statSync(o).isFile()&&n.set(r,Ie.readFileSync(o,"utf8"))}return c("Snapshotted event files",n)},qu=async e=>{if((await Ce({cwd:e,args:["checkout","--",ut("")]})).exitCode!==0){let n=Et.join(e,".epiq","events");Ie.existsSync(n)&&Ie.rmSync(n,{recursive:!0,force:!0})}return c("Restored event files to HEAD",null)},Yu=({stateBranchRoot:e,snapshots:t})=>{let n=!1;for(let[r,o]of t){let i=Et.join(e,ut(r)),a=fr(i)??"",l=gn(a);if(d(l))return s(l.message);let u=gn(o);if(d(u))return s(u.message);let m=Lo(l.value,u.value);n=za(i,Do(m))||n}return c("Merged event snapshots",n)},Ga=async(e=process.cwd())=>{logger.info("[sync] syncEpiqFromRemote:start",e),To("Syncing from remote");let t=L("ensureSyncReady",await qa({cwd:e,ensureUpstream:!1}));if(d(t))return G(t.message);let{repoRoot:n,stateBranchRoot:r}=t.value,o=L("getStateBranch",lt(n));if(d(o))return G(o.message);let i=o.value,a=L("snapshotEventFiles",Gu(r));if(d(a))return G(a.message);let l=L("restoreEventFilesToHead",await qu(r));if(d(l))return G(l.message);let u=L("resetBranchHardToRemote",await li({cwd:r,branch:i}));if(d(u))return G(u.message);let m=L("mergeEventSnapshots",Yu({stateBranchRoot:r,snapshots:a.value}));return d(m)?G(m.message):(Mo(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}))},qa=async({cwd:e,ensureUpstream:t})=>{logger.info("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=L("getRepoRootDir",await At(e));if(d(n))return s(n.message);let r=n.value;logger.info("[sync] repo root",r);let o=L("getStateBranchRoot",wn({repoRoot:r}));if(d(o))return s(o.message);let i=o.value;logger.info("[sync] state branch root",i);let a=L("ensureInitialCommit",await Vs(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=L("bootstrapStateBranchStorage",await Gs({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=L("hasInProgressGitOperation(stateBranchRoot)",await bn(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=L("ensureStateBranchLayout",xi(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}))},Ka=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 er({stateBranchRoot:t,eventFileName:n}));if(d(r))return s(r.message);let o=L("hasStagedChanges(after stage)",await ui(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=L("createStateBranchSyncCommit",await zs({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}))},Xu=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");To("Syncing");let n=L("ensureSyncReady",await qa({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=L("isDetachedHead(stateBranchRoot)",await mi(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,x=L("getStateBranch",lt(r));if(d(x))return G(x.message);let C=x.value;logger.info("[sync] resolved state branch",{stateBranch:C,stateBranchRoot:o});let E=Vu({stateBranchRoot:o,ownEventFileName:t}),I=fr(E),k=L("restoreOwnEventFileToHead",await zu({stateBranchRoot:o,ownEventFileName:t}));if(d(k))return G(k.message);let R=L("pullBranchRebaseIfPresent",await Or({cwd:o,branch:C}));if(d(R))return G(R.message);m=R.value;let w=L("mergeOwnSnapshot",ja({ownEventPath:E,ownSnapshot:I}));if(d(w))return G(w.message);let F=L("commitOwnEventFileToStateBranch",await Ka({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(F))return G(F.message);if(l=F.value.createdCommit,u=F.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=L("pushStateBranch(initial)",await cn({stateBranchRoot:o,repoRoot:r})),ie=ee;if(d(ee)&&di(ee.message)){logger.info("[sync] non-fast-forward, retrying sync");let Fe=L("pullBranchRebaseIfPresent(retry)",await Or({cwd:o,branch:C}));if(d(Fe))return G(Fe.message);logger.info("[sync] pull retry result",Fe.value);let dt=L("mergeOwnSnapshot(retry)",ja({ownEventPath:E,ownSnapshot:I}));if(d(dt))return G(dt.message);let he=L("commitOwnEventFileToStateBranch(retry)",await Ka({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(he))return G(he.message);logger.info("[sync] retry sync result",he.value),he.value.createdCommit&&(l=!0,u=he.value.commitSha),ie=L("pushStateBranch(retry)",await cn({stateBranchRoot:o,repoRoot:r}))}if(d(ie))return G(ie.message);p=ie.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=L("git rev-parse HEAD",await D({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 Mo(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=Va();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"),s("Unable to resolve event log path");let n=an(t.value);logger.info("[sync] resolved own event file name",{ownEventFileName:n});let r=L("syncEpiqWithRemote",await Xu({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=L("loadMergedEvents",Ut(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=Va();if(a)return a;let l=$a(),u=L("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=L("restoreNavigationAnchor",_a(l));return d(m)?m:(logger.info("[sync] syncAndReloadState:done"),c("Synced",!0))},Va=()=>v().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 gr,Text as vr}from"ink";import Ve,{useEffect as Ju,useMemo as Qu}from"react";import{ulid as Zu}from"ulid";var Ya=Zu(),em=e=>`${e}`,tm=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=Hn(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))},nm=e=>re.text({id:Ya,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),rm=(e,t,n)=>re.text({id:em(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Fo=[],om=e=>{Xa();let t=b.createNode(nm(v().rootNodeId));d(t)||!Kt(t.value)||(Fo=[t.value,...e.map((n,r)=>rm(n,r,Ya)).map(b.createNode).filter(te).map(({value:n})=>n).filter(Kt)],M.navigate({contextNode:t.value,selectedIndex:0}))},Xa=()=>{let e=Fo.map(t=>t.id);Fo=[];for(let t of e)b.deleteNode(t)};function Ja({width:e,height:t}){let r=ns().value.trim().toLowerCase(),o=Qu(()=>tm(r),[r]);Ju(()=>(om(o),()=>{Xa()}),[o]);let i=v().selectedIndex;return Ve.createElement(gr,{flexDirection:"column",width:e,height:t-2},Ve.createElement(gr,{paddingX:1},Ve.createElement(vr,{color:h.accent},"Command Palette"),Ve.createElement(vr,{dimColor:!0}," \u2014 select a command and press enter")),Ve.createElement(Dt,{height:t-4,itemHeight:3,selectedIndex:i},o.map((a,l)=>{let u=l===i,m=a.isAvailable?h.accent:h.secondary2,p=a.isAvailable?"":"[unavailable] ";return Ve.createElement(gr,{key:a.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderColor:h.secondary,borderStyle:"single"},Ve.createElement(vr,{color:m,dimColor:!a.isAvailable,backgroundColor:u&&a.isAvailable?h.secondary:void 0},u?"\u276F ":" ",":"+a.command),Ve.createElement(gr,{paddingLeft:2},Ve.createElement(vr,{dimColor:!a.isAvailable,color:h.secondary2},p+a.description)))})))}import{Box as xm}from"ink";import Uo from"react";import xn from"chalk";import{Box as Bo,Text as Qa}from"ink";import vn,{useEffect as im,useMemo as sm,useState as am}from"react";var Za=xn.gray,dm=xn.inverse,cm=xn.inverse.gray,lm={hint:"",hints:[],overlap:0,remainder:""},td=({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}},um=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=de(t);return{bg:r=>xn.bgHex(n).black(r),bgCursor:r=>xn.bgHex(n).inverse.black(r)}}return Xr(t)},mm=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=td({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}},ed=()=>({value:ce.value,cursorPosition:ce.cursorPosition,commandIsPending:ce.commandIsPending,autoCompletion:ce.commandMeta.autoCompletion??lm,infoMessage:ce.commandMeta.infoMessage,validationStatus:ce.commandMeta.validity,command:ce.commandMeta.command,inputString:ce.commandMeta.inputString,modifier:ce.commandMeta.modifier}),pm=(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,nd=({width:e,mode:t})=>{let[n,r]=am(ed());im(()=>{let C=()=>{let I=ed();r(k=>pm(k,I)?k:I)},E=to(C);return C(),()=>{E()}},[]);let{value:o,cursorPosition:i,infoMessage:a,commandIsPending:l,autoCompletion:u,command:m,modifier:p}=n,x=sm(()=>{let C=Math.max(0,Math.min(i,o.length)),E=td({value:o,command:m}),I=mm({value:o,command:m,modifier:p}),k=m?Xr(m):null,R=um({command:m,modifier:p}),w=(se,ue)=>{let St=E&&ue>=E.start&&ue<E.end,ct=I&&ue>=I.start&&ue<I.end;return St&&k?k.fg(se):ct&&R?R.bg(se):se},F=(se,ue)=>{let St=E&&ue>=E.start&&ue<E.end,ct=I&&ue>=I.start&&ue<I.end;return St&&k?k.fgCursor(se):ct&&R?R.bgCursor(se):dm(se)},ee=o.slice(0,C),ie=o[C]??" ",Fe=C<o.length?o.slice(C+1):"",dt=Array.from(ee).map((se,ue)=>w(se,ue)).join(""),he=F(ie,C),jt=Array.from(Fe).map((se,ue)=>w(se,C+1+ue)).join("");if(u.hint){let se=u.hint[u.overlap]??ie;he=cm(se),jt=Za(u.remainder.slice(1)+Fe)}return Za(t===f.PALETTE?"?":":")+dt+he+jt},[o,i,u,m,p]);return vn.createElement(Bo,{flexDirection:"column",justifyContent:"flex-start"},vn.createElement(Bo,{flexDirection:"column",paddingX:1,borderColor:h.secondary,borderStyle:"round",width:e},vn.createElement(Bo,null,vn.createElement(Qa,null,x),a&&vn.createElement(Qa,{wrap:"truncate",color:l?h.red:h.secondary2},` ${a} `))))};import rd from"chalk";import{Box as fm,Text as Oo}from"ink";import xr from"react";var gm=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),vm=(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},od=({width:e,availableHints:t})=>{let n=Math.max(0,e-2),r=vm(t,e).join(" | "),o=rd.hex(h.secondary),i=rd.hex(h.secondary2),a=o(`\u256D${"\u2500".repeat(n)}\u256E`),l=o(`\u2570${"\u2500".repeat(n)}\u256F`),u=`${o("\u2502")}${i(gm(` ${r} `,n))}${o("\u2502")}`;return xr.createElement(fm,{flexDirection:"column",width:e},xr.createElement(Oo,null,a),xr.createElement(Oo,null,u),xr.createElement(Oo,null,l))};var yn=({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 Uo.createElement(xm,null,t===f.COMMAND_LINE||t===f.PALETTE?Uo.createElement(nd,{width:e,mode:t}):Uo.createElement(od,{width:e,mode:t,availableHints:n}))};import{Box as _t,Text as id}from"ink";import it from"react";var sd=({width:e})=>{let t=[...v().availableActions].map(n=>n.description).filter(n=>n!==void 0).map(n=>{let[r,o]=n.split("]"),i=r?.replace("[",""),a=o?.trim();return[i,a]}).filter(n=>n[0]!==void 0&&n[1]!==void 0).sort(([n],[r])=>n.length===1&&r.length!==1?-1:n.length!==1&&r.length===1?1:n.localeCompare(r,void 0,{sensitivity:"base"}));return t.unshift(["Key(s)","Action"]),it.createElement(_t,{flexDirection:"column",marginTop:3,borderColor:h.secondary,borderStyle:"round",width:e,minHeight:19},it.createElement(_t,{flexDirection:"column",width:e},v().mode===f.HELP?t.map(([n,r],o)=>it.createElement(_t,{paddingLeft:1,key:o,flexDirection:"row"},it.createElement(_t,{key:o,flexDirection:"row",paddingBottom:o?0:1},it.createElement(_t,{width:20,justifyContent:"flex-end"},it.createElement(id,{color:o?h.accent:h.secondary},n)),it.createElement(_t,{flexGrow:1,width:40,paddingLeft:2},it.createElement(id,{color:o?h.primary:h.secondary},r))))):null))};import ym from"chalk";import{Box as yr,Text as ze}from"ink";import ye from"react";var ad=({width:e,height:t})=>ye.createElement(yr,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},ye.createElement(ze,{color:h.accent,bold:!0},"Initialize project"),ye.createElement(ze,null,`This folder is not an ${ym.hex(h.accent)("epiq")} project yet.`),ye.createElement(ze,{color:h.primary},"To start tracking issues here, we need to initialize a new",ye.createElement(ze,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json "),"file in this repository."),ye.createElement(yr,{marginTop:1,flexDirection:"column"},ye.createElement(yr,null,ye.createElement(ze,{color:h.accent}," "),ye.createElement(ze,{color:h.primary},"Type "),ye.createElement(ze,{backgroundColor:h.secondary}," :init "))),ye.createElement(yr,{marginTop:1},ye.createElement(ze,{color:h.secondary2},"This will create, commit and push "),ye.createElement(ze,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json ")));import{Box as hr,Text as Le}from"ink";import oe from"react";var hm=({isDone:e,command:t,value:n})=>oe.createElement(hr,null,oe.createElement(Le,{color:h.accent,dimColor:e},e?" \u2714 ":" "),oe.createElement(Le,{dimColor:e},"Type "),oe.createElement(Le,{backgroundColor:h.secondary,dimColor:e}," "+t+" "),n!==void 0&&oe.createElement(oe.Fragment,null,oe.createElement(Le,{dimColor:e}," "),oe.createElement(Le,{color:h.secondary,dimColor:e},"<"+n+">"))),Cm=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"yes":"no"};function $o({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(x=>!x.done),p=m===-1?void 0:u[m];return oe.createElement(hr,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},oe.createElement(Le,{color:h.accent,bold:!0},"Welcome! \u{1F539}"),oe.createElement(Le,null,"Let's get you started - it's a breeze."),oe.createElement(Le,{color:h.secondary2},"Remember - you can always search available commands by typing:",oe.createElement(Le,{color:h.accent}," ? ")),p&&oe.createElement(Le,{color:h.secondary2},p.message),oe.createElement(hr,{flexDirection:"column"},u.map((x,C)=>m===-1||C<=m?oe.createElement(hr,{key:x.key,marginBottom:1},oe.createElement(hm,{isDone:x.done,command:x.command,value:x.done?Cm(x.value):void 0})):null)))}import Sr from"chalk";import{Box as Er,Text as Ge}from"ink";import Z from"react";import{Box as Wo,Text as Em}from"ink";import Ht from"react";var Sm=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",dd=({width:e})=>{let{viewMode:t}=$(),{breadCrumb:n,contextNode:r,selectedIndex:o}=v(),i=U(r.id)[o],a=ot(i?.id??r.id,"TICKET"),l=te(a)?a.value:void 0,u=l?.props.tags??[],m=l?.props.assignees??[],p=l?.parentNodeId?!Ao(r.id,l.parentNodeId)&&t==="dense":!1,x=n.map((E,I)=>{let k=I===n.length-1,R=U(E.id),w=k?R?.[o]?.title:void 0;return`${I?" / ":""}${E.title??""}${w?` \u25B8 ${w}`:""}`}).join(""),C=Sm(x,e);return Ht.createElement(Wo,null,Ht.createElement(Em,{color:h.secondary2},C),p?u.map(E=>Ht.createElement(Wo,{key:E,paddingLeft:2},Ht.createElement(Bt,{id:E}))):null,p?m.map(E=>Ht.createElement(Wo,{key:E,paddingLeft:2},Ht.createElement(Ft,{id:E}))):null)};import{Box as Nm,Text as cd}from"ink";import Cr from"react";var bm=({filters:e})=>Cr.createElement(Nm,{columnGap:1},Cr.createElement(cd,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Cr.createElement(cd,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),ld=Cr.memo(bm);var ud="0.6.2";import _o from"chalk";import{Box as Im,Text as md}from"ink";import Ho,{useEffect as Rm,useState as Am}from"react";var wm=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],pd=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)}},Tm=({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)}`},Mm=(e,t,n)=>{let r=pd(e),o=pd(t);return Tm({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},Pm=(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 Mm(i,a,o)};function fd({syncStatus:e,autoSync:t}){let[n,r]=Am(0);Rm(()=>{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:h.secondary2,failed:h.yellow,pending:h.secondary2,syncing:Pm(wm,(Math.sin(n*.12)+1)/2)??""}[e.status];return Ho.createElement(Im,null,Ho.createElement(md,null,_o.hex(h.secondary2).dim(t?"AutoSync: ":"Sync: ")),Ho.createElement(md,null,_o.hex(a)("\u25CF")+_o.hex(h.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}function Nr({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,x=process.stdout.columns-p-8,C=r.at(-1)?.id,E=$n(C??""),I=te(E)?Wi(E.value):"INVALID DATE";return Z.createElement(Er,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?Z.createElement(Ge,null," "):Z.createElement(Er,{paddingLeft:1},e.length>0?Z.createElement(ld,{filters:e}):Z.createElement(dd,{width:x})),n==="live"?Z.createElement(Er,{columnGap:1,paddingRight:2,"max-width":p,overflow:"hidden",justifyContent:"flex-end"},Z.createElement(fd,{autoSync:!!m,syncStatus:i}),Z.createElement(Ge,null,Sr.hex(h.secondary2).dim("Mode: ")+Sr.hex(h.secondary2).dim(a.padEnd(8," "))," "),Z.createElement(gd,{icon:"@",value:l}),Z.createElement(gd,{icon:"\u276F",value:u}),Z.createElement(Ge,{dimColor:!0,color:h.secondary2},ud+" ")):"",n==="peek"?Z.createElement(Er,{paddingLeft:1},Z.createElement(Ge,{backgroundColor:h.yellow}," Readonly "),Z.createElement(Ge,{color:h.yellow}," "+o.length+" edits ago at "),Z.createElement(Ge,{backgroundColor:h.yellow,color:h.accent}," "+I+" "),Z.createElement(Ge,{color:h.yellow},". Resume with "),Z.createElement(Ge,{backgroundColor:h.yellow}," :peek now ")):"")}function gd({icon:e,value:t}){return Z.createElement(Ge,null,Sr.dim(e)+Sr.hex(h.accent)(` ${t??"-"} `))}import{Box as km,Text as Lm}from"ink";import hn from"react";import{Box as br,Text as jo}from"ink";import st from"react";function Ko(){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(br,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:h.secondary,width:i},st.createElement(br,{padding:1,paddingTop:0,paddingBottom:0},st.createElement(jo,null,"Select a board:")),st.createElement(br,{padding:1,flexDirection:"column"},a.map((l,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,x=O(l.id).flatMap(({id:C})=>U(C)).length;return st.createElement(br,{key:l.id??u},st.createElement(jo,{color:m?h.accent:h.secondary2},st.createElement(fe,{isSelected:m})),st.createElement(jo,{color:m?h.accent:h.secondary2},l.title," (",x," issues)",l.readonly?" \u{1F512}":""))})))}var Dm=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:a})=>{let{renderedChildrenIndex:l}=Q(),u=n.find(({context:C})=>C==="BOARD"),x=i-1-3;return hn.createElement(km,{flexDirection:"row"},e.context==="WORKSPACE"?hn.createElement(Ko,null):u?hn.createElement(qn,{height:x,width:a,swimlanes:(l[u.id]??[]).filter(C=>C!==void 0&&Nt(C)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):hn.createElement(Lm,null))},vd=hn.memo(Dm);function Vo({width:e,height:t}){let n=Q(),r=n.filters;if(n.mode===f.HELP)return q.createElement(at,{flexDirection:"column"},q.createElement(sd,{width:e}));if(n.mode===f.PALETTE)return q.createElement(at,{flexDirection:"column"},q.createElement(Ja,{width:e,height:t}),q.createElement(yn,{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(Nr,{hideBreadCrumb:!0,filters:r}),q.createElement($o,{height:t,width:e})),q.createElement(yn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(a)return q.createElement(at,{flexDirection:"column"},q.createElement(at,{flexDirection:"column"},q.createElement(Nr,{hideBreadCrumb:!0,filters:r}),q.createElement(ad,{height:t,width:e})),q.createElement(yn,{width:e,mode:n.mode,availableHints:n.availableHints}));let l=Se(n.breadCrumb??[],"BOARD");if(te(l)){let u=l.value.id,m=O(u).length,p=3,x=Math.floor(e/p),C=Math.floor(e/Math.max(m,1));e=Math.min(C,x)*Math.max(m,p)}return q.createElement(at,{flexDirection:"column"},q.createElement(at,{flexDirection:"column"},q.createElement(Nr,{filters:r}),q.createElement(vd,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:$().viewMode??"dense",mode:n.mode})),q.createElement(yn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import Fm from"readline";var Ir,Rr,De,Bm=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]),xd=async e=>{if(e.ctrl&&e.name==="c")return M.exit();let{actionIndex:t,mode:n,readOnly:r}=v(),o=cs(e,n);if(!o||r&&!Bm.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(a){logger.error(a)}},Om=()=>async function(t,n){n.name!=="escape"&&(De&&(clearTimeout(De),De=void 0),await xd(n))},Um=()=>async function(t){if(t.length===1&&t[0]===27){De&&clearTimeout(De),De=setTimeout(()=>{xd({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),De=void 0},25);return}De&&(clearTimeout(De),De=void 0)};function yd(){Ir&&process.stdin.removeListener("keypress",Ir),Rr&&process.stdin.removeListener("data",Rr),Ir=Om(),Rr=Um(),Fm.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Rr),process.stdin.on("keypress",Ir)}ga();Wm(`${Ar.bold("Epiq CLI")}
|
|
62
|
+
`;var Cr=e=>we.existsSync(e)?we.readFileSync(e,"utf8"):null,cd=(e,t)=>Cr(e)===t?!1:(we.mkdirSync(Mt.dirname(e),{recursive:!0}),we.writeFileSync(e,t,"utf8"),!0),pm=({stateBranchRoot:e,ownEventFileName:t})=>Mt.join(e,ht(t)),gm=async({stateBranchRoot:e,ownEventFileName:t})=>{let n=ht(t),r=Mt.join(e,n);return(await Se({cwd:e,args:["checkout","--",n]})).exitCode!==0&&we.existsSync(r)&&we.rmSync(r,{force:!0}),l("Restored own event file to HEAD",null)},sd=({ownEventPath:e,ownSnapshot:t})=>{if(t===null)return l("No own snapshot to merge",!1);let n=Cr(e)??"",r=Nn(n);if(d(r))return a(r.message);let o=Nn(t);if(d(o))return a(o.message);let i=Wo(r.value,o.value),s=cd(e,_o(i));return l("Merged own snapshot",s)},fm=e=>{let t=Mt.join(e,".epiq","events"),n=new Map;if(!we.existsSync(t))return l("No event files to snapshot",n);for(let r of we.readdirSync(t)){if(!r.endsWith(".jsonl"))continue;let o=Mt.join(t,r);we.statSync(o).isFile()&&n.set(r,we.readFileSync(o,"utf8"))}return l("Snapshotted event files",n)},vm=async e=>{if((await Se({cwd:e,args:["checkout","--",ht("")]})).exitCode!==0){let n=Mt.join(e,".epiq","events");we.existsSync(n)&&we.rmSync(n,{recursive:!0,force:!0})}return l("Restored event files to HEAD",null)},xm=({stateBranchRoot:e,snapshots:t})=>{let n=!1;for(let[r,o]of t){let i=Mt.join(e,ht(r)),s=Cr(i)??"",c=Nn(s);if(d(c))return a(c.message);let u=Nn(o);if(d(u))return a(u.message);let m=Wo(c.value,u.value);n=cd(i,_o(m))||n}return l("Merged event snapshots",n)},ld=async(e=process.cwd())=>{logger.info("[sync] syncEpiqFromRemote:start",e),Uo("Syncing from remote");let t=L("ensureSyncReady",await ud({cwd:e,ensureUpstream:!1}));if(d(t))return q(t.message);let{repoRoot:n,stateBranchRoot:r}=t.value,o=L("getStateBranch",yt(n));if(d(o))return q(o.message);let i=o.value,s=L("snapshotEventFiles",fm(r));if(d(s))return q(s.message);let c=L("restoreEventFilesToHead",await vm(r));if(d(c))return q(c.message);let u=L("resetBranchHardToRemote",await yi({cwd:r,branch:i}));if(d(u))return q(u.message);let m=L("mergeEventSnapshots",xm({stateBranchRoot:r,snapshots:s.value}));return d(m)?q(m.message):(Oo(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}))},ud=async({cwd:e,ensureUpstream:t})=>{logger.info("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=L("getRepoRootDir",await nt(e));if(d(n))return a(n.message);let r=n.value;logger.info("[sync] repo root",r);let o=L("getStateBranchRoot",Bt({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 ia(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 aa({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 Pn(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",Ii(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}))},ad=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 dr({stateBranchRoot:t,eventFileName:n}));if(d(r))return a(r.message);let o=L("hasStagedChanges(after stage)",await hi(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 sa({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}))},ym=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");Uo("Syncing");let n=L("ensureSyncReady",await ud({cwd:e,ensureUpstream:!0}));if(d(n))return q(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 Ci(o));if(d(s))return q(s.message);if(logger.info("[sync] detached state branch check result",{detached:s.value}),s.value)return logger.info("[sync] state branch is detached"),q("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,g=!1,y=L("getStateBranch",yt(r));if(d(y))return q(y.message);let N=y.value;logger.info("[sync] resolved state branch",{stateBranch:N,stateBranchRoot:o});let E=pm({stateBranchRoot:o,ownEventFileName:t}),I=Cr(E),w=L("restoreOwnEventFileToHead",await gm({stateBranchRoot:o,ownEventFileName:t}));if(d(w))return q(w.message);let R=L("pullBranchRebaseIfPresent",await Kr({cwd:o,branch:N}));if(d(R))return q(R.message);m=R.value;let T=L("mergeOwnSnapshot",sd({ownEventPath:E,ownSnapshot:I}));if(d(T))return q(T.message);let F=L("commitOwnEventFileToStateBranch",await ad({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(F))return q(F.message);if(c=F.value.createdCommit,u=F.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 re=L("pushStateBranch(initial)",await gn({stateBranchRoot:o,repoRoot:r})),se=re;if(d(re)&&vi(re.message)){logger.info("[sync] non-fast-forward, retrying sync");let $e=L("pullBranchRebaseIfPresent(retry)",await Kr({cwd:o,branch:N}));if(d($e))return q($e.message);logger.info("[sync] pull retry result",$e.value);let vt=L("mergeOwnSnapshot(retry)",sd({ownEventPath:E,ownSnapshot:I}));if(d(vt))return q(vt.message);let Ee=L("commitOwnEventFileToStateBranch(retry)",await ad({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(d(Ee))return q(Ee.message);logger.info("[sync] retry sync result",Ee.value),Ee.value.createdCommit&&(c=!0,u=Ee.value.commitSha),se=L("pushStateBranch(retry)",await gn({stateBranchRoot:o,repoRoot:r}))}if(d(se))return q(se.message);g=se.value,logger.info("[sync] pushed to state branch",g)}else logger.info("[sync] no commit created, skipped push");if(c){logger.info("[sync] resolving final sync commit sha",{stateBranchRoot:o});let re=L("git rev-parse HEAD",await D({args:["rev-parse","HEAD"],cwd:o}));if(d(re))return q(re.message);u=re.value.stdout.trim(),logger.info("[sync] final sync commit sha",u)}return Oo(g?"Synced and pushed":m||c||T.value?"Synced local state":"Already synced"),logger.info("[sync] syncEpiqWithRemote:done",{pulled:m,pushed:g,createdCommit:c,bootstrapped:i,commitSha:u}),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:g,bootstrapped:i})},Hn=async()=>{let e=dd();if(e)return e;logger.info("[sync] syncAndReloadState:start");let t=L("resolveActorId",G());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id"),a("Unable to resolve event log path");let n=mn(t.value);logger.info("[sync] resolved own event file name",{ownEventFileName:n});let r=L("syncEpiqWithRemote",await ym({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",Kt(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=dd();if(s)return s;let c=nd(),u=L("bootStateFromEventLog",cr(i.value));if(d(u))return a(`Unable to boot synced state. ${u.message}`);logger.info("[sync] booted state from synced events"),S({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}});let m=L("restoreNavigationAnchor",od(c));return d(m)?m:(logger.info("[sync] syncAndReloadState:done"),l("Synced",!0))},dd=()=>v().mode===p.DEFAULT?null:(S({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 ft}from"ink";import Y from"react";import{Box as Nr,Text as Pt}from"ink";import he,{useEffect as hm,useMemo as Cm}from"react";import{ulid as Nm}from"ulid";var md=({text:e,match:t,color:n,highlightColor:r=h.secondary,dimColor:o=!1})=>{if(!t)return he.createElement(Pt,{color:n,dimColor:o},e);let i=e.toLowerCase(),s=t.toLowerCase(),c=i.indexOf(s);return c===-1?he.createElement(Pt,{color:n,dimColor:o},e):he.createElement(Pt,{color:n,dimColor:o},e.slice(0,c),he.createElement(Pt,{backgroundColor:r,bold:!0},e.slice(c,c+t.length)),e.slice(c+t.length))},pd=Nm(),Em=e=>`${e}`,Sm=e=>{let{pendingNavTarget:t}=lt();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,i=new Set(Q(x.NONE,{breadCrumb:n,contextNode:r,readOnly:v().readOnly,selectedNode:o}));return[...new Set(Object.values(x))].filter(s=>s!=="move").filter(s=>s.length>0).filter(s=>s!==x.PALETTE).map(s=>{let c=Xn(s),u=fr.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))},bm=e=>z.text({id:pd,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),Im=(e,t,n)=>z.text({id:Em(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),jo=[],Rm=e=>{gd();let t=b.createNode(bm(v().rootNodeId));d(t)||!Je(t.value)||(jo=[t.value,...e.map((n,r)=>Im(n,r,pd)).map(b.createNode).filter(X).map(({value:n})=>n).filter(Je)],A.navigate({contextNode:t.value,selectedIndex:0}))},gd=()=>{let e=jo.map(t=>t.id);jo=[];for(let t of e)b.deleteNode(t)};function fd({width:e,height:t}){let r=xs().value.trim().toLowerCase(),o=Cm(()=>Sm(r),[r]);hm(()=>(Rm(o),()=>{gd()}),[o]);let i=v().selectedIndex;return he.createElement(Nr,{flexDirection:"column",width:e,height:t-2},he.createElement(Nr,{paddingX:1},he.createElement(Pt,{color:h.accent},"Command Palette"),he.createElement(Pt,{dimColor:!0}," \u2014 select a command and press enter")),he.createElement(st,{height:t-4,itemHeight:3,selectedIndex:i},o.map((s,c)=>{let u=c===i,m=s.isAvailable?h.accent:h.secondary2,g=s.isAvailable?"":"[unavailable] ";return he.createElement(Nr,{key:s.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:h.secondary,borderStyle:"single"},he.createElement(Pt,{color:m,dimColor:!s.isAvailable},u?"\u276F ":" ",he.createElement(md,{text:Mi(s.command),match:r,color:m,dimColor:!s.isAvailable})),he.createElement(Nr,{paddingLeft:2},he.createElement(md,{text:g+s.description,match:r.length>=2?r:"",color:u&&s.isAvailable?h.primary:h.secondary2,dimColor:!s.isAvailable})))})))}import{Box as $m}from"ink";import zo from"react";import Sn from"chalk";import{Box as Ko,Text as vd}from"ink";import En,{useEffect as Am,useMemo as Tm,useState as wm}from"react";var xd=Sn.gray,Mm=Sn.inverse,Pm=Sn.inverse.gray,km={hint:"",hints:[],overlap:0,remainder:""},hd=({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}},Lm=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=Re(t);return{bg:r=>Sn.bgHex(n).black(r),bgCursor:r=>Sn.bgHex(n).inverse.black(r)}}return oo(t)},Dm=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=hd({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}},yd=()=>({value:ce.value,cursorPosition:ce.cursorPosition,commandIsPending:ce.commandIsPending,autoCompletion:ce.commandMeta.autoCompletion??km,infoMessage:ce.commandMeta.infoMessage,validationStatus:ce.commandMeta.validity,command:ce.commandMeta.command,inputString:ce.commandMeta.inputString,modifier:ce.commandMeta.modifier}),Fm=(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,Cd=({width:e,mode:t})=>{let[n,r]=wm(yd());Am(()=>{let N=()=>{let I=yd();r(w=>Fm(w,I)?w:I)},E=co(N);return N(),()=>{E()}},[]);let{value:o,cursorPosition:i,infoMessage:s,commandIsPending:c,autoCompletion:u,command:m,modifier:g}=n,y=Tm(()=>{let N=Math.max(0,Math.min(i,o.length)),E=hd({value:o,command:m}),I=Dm({value:o,command:m,modifier:g}),w=m?oo(m):null,R=Lm({command:m,modifier:g}),T=(ae,me)=>{let kt=E&&me>=E.start&&me<E.end,xt=I&&me>=I.start&&me<I.end;return kt&&w?w.fg(ae):xt&&R?R.bg(ae):ae},F=(ae,me)=>{let kt=E&&me>=E.start&&me<E.end,xt=I&&me>=I.start&&me<I.end;return kt&&w?w.fgCursor(ae):xt&&R?R.bgCursor(ae):Mm(ae)},re=o.slice(0,N),se=o[N]??" ",$e=N<o.length?o.slice(N+1):"",vt=Array.from(re).map((ae,me)=>T(ae,me)).join(""),Ee=F(se,N),Yt=Array.from($e).map((ae,me)=>T(ae,N+1+me)).join("");if(u.hint){let ae=u.hint[u.overlap]??se;Ee=Pm(ae),Yt=xd(u.remainder.slice(1)+$e)}return xd(t===p.PALETTE?"?":":")+vt+Ee+Yt},[o,i,u,m,g]);return En.createElement(Ko,{flexDirection:"column",justifyContent:"flex-start"},En.createElement(Ko,{flexDirection:"column",paddingX:1,borderColor:h.secondary,borderStyle:"round",width:e},En.createElement(Ko,null,En.createElement(vd,null,y),s&&En.createElement(vd,{wrap:"truncate",color:c?h.red:h.secondary2},` ${s} `))))};import Nd from"chalk";import{Box as Bm,Text as Vo}from"ink";import Er from"react";var Um=(e,t)=>e.length===t?e:e.length>t?e.slice(0,t):e.padEnd(t," "),Om=(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},Ed=({width:e,availableHints:t})=>{let n=Math.max(0,e-2),r=Om(t,e).join(" | "),o=Nd.hex(h.secondary),i=Nd.hex(h.secondary2),s=o(`\u256D${"\u2500".repeat(n)}\u256E`),c=o(`\u2570${"\u2500".repeat(n)}\u256F`),u=`${o("\u2502")}${i(Um(` ${r} `,n))}${o("\u2502")}`;return Er.createElement(Bm,{flexDirection:"column",width:e},Er.createElement(Vo,null,s),Er.createElement(Vo,null,u),Er.createElement(Vo,null,c))};var bn=({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 zo.createElement($m,null,t===p.COMMAND_LINE||t===p.PALETTE?zo.createElement(Cd,{width:e,mode:t}):zo.createElement(Ed,{width:e,mode:t,availableHints:n}))};import{Box as pt,Text as Gt}from"ink";import ue,{useEffect as Hm,useMemo as Wm}from"react";import{ulid as Sd}from"ulid";var br=Sd(),_m=()=>[...new Set([...v().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(e=>{let[t,n]=e.split("]"),r=t?.replace("[",""),o=n?.trim();return[r,o]}).filter(e=>e[0]!==void 0&&e[1]!==void 0).sort(([e],[t])=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(([e,t])=>({keys:e,action:t})),jm=e=>z.text({id:br,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),Km=(e,t,n)=>z.text({id:Sd(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),Sr=[],bd=()=>{let e=Sr.filter(n=>n.id!==br).map(n=>n.id),t=Sr.filter(n=>n.id===br).map(n=>n.id);Sr=[];for(let n of[...e,...t])b.deleteNode(n)},Vm=e=>{bd();let t=b.createNode(jm(v().rootNodeId));if(d(t)||!Je(t.value))return logger.error("Could not attach help nodes");Sr=[t.value,...e.map((n,r)=>Km(n,r,br)).map(b.createNode).filter(X).map(({value:n})=>n).filter(Je)],A.navigate({contextNode:t.value,selectedIndex:0})},Id=({width:e,height:t})=>{let n=Wm(()=>_m(),[]);Hm(()=>(Vm(n),()=>{bd()}),[n]);let r=v().selectedIndex;return ue.createElement(pt,{flexDirection:"column",marginTop:3,borderColor:h.secondary,borderStyle:"round",width:e,height:t-2},ue.createElement(pt,{paddingX:1,justifyContent:"center"},ue.createElement(Gt,{color:h.accent},"Help"),ue.createElement(Gt,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),ue.createElement(pt,{paddingX:1,marginTop:1},ue.createElement(pt,{width:20,justifyContent:"flex-end"},ue.createElement(Gt,{color:h.secondary},"Key(s)")),ue.createElement(pt,{flexGrow:1,width:40,paddingLeft:2},ue.createElement(Gt,{color:h.secondary},"Action"))),ue.createElement(st,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:i},s)=>{let c=s===r;return ue.createElement(pt,{paddingX:1,key:`${o}-${i}-${s}`,flexDirection:"row"},ue.createElement(pt,{width:20,justifyContent:"flex-end"},ue.createElement(Gt,{color:h.accent},o)),ue.createElement(pt,{flexGrow:1,width:40,paddingLeft:2},ue.createElement(Gt,{color:c?h.primary:h.secondary2},i)))})))};import zm from"chalk";import{Box as Ir,Text as Ye}from"ink";import Ne from"react";var Rd=({width:e,height:t})=>Ne.createElement(Ir,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},Ne.createElement(Ye,{color:h.accent,bold:!0},"Initialize project"),Ne.createElement(Ye,null,`This folder is not an ${zm.hex(h.accent)("epiq")} project yet.`),Ne.createElement(Ye,{color:h.primary},"To start tracking issues here, we need to initialize a new",Ne.createElement(Ye,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json "),"file in this repository."),Ne.createElement(Ir,{marginTop:1,flexDirection:"column"},Ne.createElement(Ir,null,Ne.createElement(Ye,{color:h.accent}," "),Ne.createElement(Ye,{color:h.primary},"Type "),Ne.createElement(Ye,{backgroundColor:h.secondary}," :init "))),Ne.createElement(Ir,{marginTop:1},Ne.createElement(Ye,{color:h.secondary2},"This will create, commit and push "),Ne.createElement(Ye,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json ")));import{Box as Rr,Text as Ue}from"ink";import ie from"react";var Gm=({isDone:e,command:t,value:n})=>ie.createElement(Rr,null,ie.createElement(Ue,{color:h.accent,dimColor:e},e?" \u2714 ":" "),ie.createElement(Ue,{dimColor:e},"Type "),ie.createElement(Ue,{backgroundColor:h.secondary,dimColor:e}," "+t+" "),n!==void 0&&ie.createElement(ie.Fragment,null,ie.createElement(Ue,{dimColor:e}," "),ie.createElement(Ue,{color:h.secondary,dimColor:e},"<"+n+">"))),qm=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"yes":"no"};function Go({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:i,autoSync:s,isSetAutoSync:c}=ot(),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(y=>!y.done),g=m===-1?void 0:u[m];return ie.createElement(Rr,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},ie.createElement(Ue,{color:h.accent,bold:!0},"Welcome! \u{1F539}"),ie.createElement(Ue,null,"Let's get you started - it's a breeze."),ie.createElement(Ue,{color:h.secondary2},"Remember - you can always search available commands by typing:",ie.createElement(Ue,{color:h.accent}," ? ")),g&&ie.createElement(Ue,{color:h.secondary2},g.message),ie.createElement(Rr,{flexDirection:"column"},u.map((y,N)=>m===-1||N<=m?ie.createElement(Rr,{key:y.key,marginBottom:1},ie.createElement(Gm,{isDone:y.done,command:y.command,value:y.done?qm(y.value):void 0})):null)))}import wr from"chalk";import{Box as Tr,Text as Xe}from"ink";import ne from"react";import{Box as qo,Text as Ym}from"ink";import qt from"react";var Xm=(e,t)=>e.length<=t?e:t<=1?"\u2026":e.slice(0,t-1)+"\u2026",Ad=({width:e})=>{let{viewMode:t}=H(),{breadCrumb:n,contextNode:r,selectedIndex:o}=v(),i=$(r.id)[o],s=mt(i?.id??r.id,"TICKET"),c=X(s)?s.value:void 0,u=c?.props.tags??[],m=c?.props.assignees??[],g=c?.parentNodeId?!Fo(r.id,c.parentNodeId)&&t==="dense":!1,y=n.map((E,I)=>{let w=I===n.length-1,R=$(E.id),T=w?R?.[o]?.title:void 0;return`${I?" / ":""}${E.title??""}${T?` \u25B8 ${T}`:""}`}).join(""),N=Xm(y,e);return qt.createElement(qo,null,qt.createElement(Ym,{color:h.secondary2},N),g?u.map(E=>qt.createElement(qo,{key:E,paddingLeft:2},qt.createElement(_t,{id:E}))):null,g?m.map(E=>qt.createElement(qo,{key:E,paddingLeft:2},qt.createElement(Wt,{id:E}))):null)};import{Box as Jm,Text as Td}from"ink";import Ar from"react";var Qm=({filters:e})=>Ar.createElement(Jm,{columnGap:1},Ar.createElement(Td,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Ar.createElement(Td,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),wd=Ar.memo(Qm);var Md="0.6.4";import Yo from"chalk";import{Box as Zm,Text as Pd}from"ink";import Xo,{useEffect as ep,useState as tp}from"react";var np=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],kd=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)}},rp=({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)}`},op=(e,t,n)=>{let r=kd(e),o=kd(t);return rp({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},ip=(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 op(i,s,o)};function Ld({syncStatus:e,autoSync:t}){let[n,r]=tp(0);ep(()=>{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:ip(np,(Math.sin(n*.12)+1)/2)??""}[e.status];return Xo.createElement(Zm,null,Xo.createElement(Pd,null,Yo.hex(h.secondary2).dim(t?"AutoSync: ":"Sync: ")),Xo.createElement(Pd,null,Yo.hex(s)("\u25CF")+Yo.hex(h.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}function Mr({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,eventLog:r,unappliedEvents:o,syncStatus:i,mode:s}=te(),{userName:c,preferredEditor:u,autoSync:m}=H(),g=56,y=process.stdout.columns-g-8,N=r.at(-1)?.id,E=Vn(N??""),I=X(E)?Yi(E.value):"INVALID DATE";return ne.createElement(Tr,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},t?ne.createElement(Xe,null," "):ne.createElement(Tr,{paddingLeft:1},e.length>0?ne.createElement(wd,{filters:e}):ne.createElement(Ad,{width:y})),n==="live"?ne.createElement(Tr,{columnGap:1,paddingRight:2,"max-width":g,overflow:"hidden",justifyContent:"flex-end"},ne.createElement(Ld,{autoSync:!!m,syncStatus:i}),ne.createElement(Xe,null,wr.hex(h.secondary2).dim("Mode: ")+wr.hex(h.secondary2).dim(s.padEnd(8," "))," "),ne.createElement(Dd,{icon:"@",value:c}),ne.createElement(Dd,{icon:"\u276F",value:u}),ne.createElement(Xe,{dimColor:!0,color:h.secondary2},Md+" ")):"",n==="peek"?ne.createElement(Tr,{paddingLeft:1},ne.createElement(Xe,{backgroundColor:h.yellow}," Readonly "),ne.createElement(Xe,{color:h.yellow}," "+o.length+" edits ago at "),ne.createElement(Xe,{backgroundColor:h.yellow,color:h.accent}," "+I+" "),ne.createElement(Xe,{color:h.yellow},". Resume with "),ne.createElement(Xe,{backgroundColor:h.yellow}," :peek now ")):"")}function Dd({icon:e,value:t}){return ne.createElement(Xe,null,wr.dim(e)+wr.hex(h.accent)(` ${t??"-"} `))}import{Box as sp,Text as ap}from"ink";import In from"react";import{Box as Pr,Text as Jo}from"ink";import gt from"react";function Qo(){let e=te(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,i=process.stdout.columns||120,s=t?.id?O(t?.id):[];return gt.createElement(Pr,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:h.secondary,width:i},gt.createElement(Pr,{padding:1,paddingTop:0,paddingBottom:0},gt.createElement(Jo,null,"Select a board:")),gt.createElement(Pr,{padding:1,flexDirection:"column"},s.map((c,u)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===u,y=O(c.id).flatMap(({id:N})=>$(N)).length;return gt.createElement(Pr,{key:c.id??u},gt.createElement(Jo,{color:m?h.accent:h.secondary2},gt.createElement(xe,{isSelected:m})),gt.createElement(Jo,{color:m?h.accent:h.secondary2},c.title," (",y," issues)",c.readonly?" \u{1F512}":""))})))}var dp=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:i,width:s})=>{let{renderedChildrenIndex:c}=te(),u=n.find(({context:N})=>N==="BOARD"),y=i-1-3;return In.createElement(sp,{flexDirection:"row"},e.context==="WORKSPACE"?In.createElement(Qo,null):u?In.createElement(nr,{height:y,width:s,swimlanes:(c[u.id]??[]).filter(N=>N!==void 0&&Lt(N)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):In.createElement(ap,null))},Fd=In.memo(dp);function Zo({width:e,height:t}){let n=te(),r=n.filters;if(n.mode===p.HELP)return Y.createElement(ft,{flexDirection:"column"},Y.createElement(Id,{width:e,height:t}));if(n.mode===p.PALETTE)return Y.createElement(ft,{flexDirection:"column"},Y.createElement(fd,{width:e,height:t}),Y.createElement(bn,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:o}=ot(),i=!o,s=o&&!n.hasProjectDefinition;if(i)return Y.createElement(ft,{flexDirection:"column"},Y.createElement(ft,{flexDirection:"column"},Y.createElement(Mr,{hideBreadCrumb:!0,filters:r}),Y.createElement(Go,{height:t,width:e})),Y.createElement(bn,{width:e,mode:n.mode,availableHints:n.availableHints}));if(s)return Y.createElement(ft,{flexDirection:"column"},Y.createElement(ft,{flexDirection:"column"},Y.createElement(Mr,{hideBreadCrumb:!0,filters:r}),Y.createElement(Rd,{height:t,width:e})),Y.createElement(bn,{width:e,mode:n.mode,availableHints:n.availableHints}));let c=Ie(n.breadCrumb??[],"BOARD");if(X(c)){let u=c.value.id,m=O(u).length,g=3,y=Math.floor(e/g),N=Math.floor(e/Math.max(m,1));e=Math.min(N,y)*Math.max(m,g)}return Y.createElement(ft,{flexDirection:"column"},Y.createElement(ft,{flexDirection:"column"},Y.createElement(Mr,{filters:r}),Y.createElement(Fd,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:H().viewMode??"dense",mode:n.mode})),Y.createElement(bn,{width:e,mode:n.mode,availableHints:n.availableHints}))}import cp from"readline";var kr,Lr,Oe,lp=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]),Bd=async e=>{if(e.ctrl&&e.name==="c")return A.exit();let{actionIndex:t,mode:n,readOnly:r}=v(),o=bs(e,n);if(!o||r&&!lp.has(o))return;let i=t[n]?.[o];if(i?.action)try{await i.action(i,e)}catch(s){logger.error(s)}},up=()=>async function(t,n){n.name!=="escape"&&(Oe&&(clearTimeout(Oe),Oe=void 0),await Bd(n))},mp=()=>async function(t){if(t.length===1&&t[0]===27){Oe&&clearTimeout(Oe),Oe=setTimeout(()=>{Bd({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),Oe=void 0},25);return}Oe&&(clearTimeout(Oe),Oe=void 0)};function Ud(){kr&&process.stdin.removeListener("keypress",kr),Lr&&process.stdin.removeListener("data",Lr),kr=up(),Lr=mp(),cp.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Lr),process.stdin.on("keypress",kr)}Ia();gp(`${Dr.bold("Epiq CLI")}
|
|
63
63
|
|
|
64
|
-
${
|
|
65
|
-
${
|
|
64
|
+
${Dr.dim("Boot in directory:")}
|
|
65
|
+
${Dr.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 Od=process.stdout.columns||120,$d=process.stdout.rows||20,Fr=null,vp=e=>{try{return Fr?(Fr.rerender(e),l("Rerendered app",void 0)):(Fr=pp(e),l("Rendered app",void 0))}catch(t){return a(`Unable to render app: ${$o(t)}`)}},Hd=()=>vp(fp.createElement(Zo,{width:Od,height:$d}));async function xp(){try{let e=Gs();X(e)&&De(e.value);let t=tt(process.cwd()),n=[];if(X(t)){let i=t.value,s=await ld(i);if(d(s))return zt(3,s.message);let c=Kt(s.value.stateBranchRoot);if(d(c))return zt(3,c.message);n=c.value}let r=cr(n);if(d(r))return zt(4,r.message);S({hasProjectDefinition:X(t),hasInitializingEvents:!!n.length});let o=Hd();return d(o)?zt(6,o.message):(Ud(),l("Booted Epiq",void 0))}catch(e){return zt(0,$o(e))}}process.stdout.on("resize",()=>{if(Od=process.stdout.columns||120,$d=process.stdout.rows||20,!Fr)return;let e=Hd();d(e)&&logger.info(`[boot:resize] ${e.message}`)});(async()=>{console.clear();let e=await xp();d(e)&&(logger.info(e.message),console.error(Dr.red(`Failed to boot Epiq:
|
|
68
68
|
${e.message}`)),process.exitCode=1)})();
|