epiq 0.4.10 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -1,58 +1,59 @@
1
1
  #!/usr/bin/env node
2
- import{McpServer as zd}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Gd}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as F}from"zod";var ge={None:"none",Success:"success",Fail:"fail"},s=e=>({status:ge.Fail,message:e,value:null}),c=(e,t)=>({status:ge.Success,message:e,value:t}),d=e=>e.status==="fail",Ze=e=>e.status==="success";import{ulid as Ji}from"ulid";import Vs from"node:fs";import tt from"node:fs";import{ulid as ls}from"ulid";import{z as St}from"zod";import Qe from"node:fs";import fe from"node:path";var bn=process.env.IS_LOCAL==="true",ve=".epiq",ie=".epiq-global",Ct="events",ds="project.json",br=e=>fe.join(e,ve),bt=e=>fe.join(e,ve),Rt=e=>fe.join(bt(e),ds),et=e=>fe.join(bt(e),Ct),cs=e=>{let t=fe.join(e,ve);return Qe.existsSync(t)&&Qe.statSync(t).isDirectory()},Rn=e=>{let t=Rt(e);return Qe.existsSync(t)&&Qe.statSync(t).isFile()},ce=e=>{let t=fe.resolve(e);for(;;){if(cs(t))return c("Resolved closest .epiq root",t);let n=fe.dirname(t);if(n===t)return s("No .epiq directory found in any parent");t=n}},Se=e=>{let t=fe.resolve(e);for(;;){if(Rn(t))return c("Resolved closest epiq project root",t);let n=fe.dirname(t);if(n===t)return s("No .epiq/project.json found in any parent");t=n}},Rr=e=>{let t=et(e);try{return Qe.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")}};var us="epiq/eventlog",ms=St.object({projectId:St.string().min(1),stateBranch:St.string().min(1),createdAt:St.string().datetime()}),Sr=()=>({projectId:ls(),stateBranch:us,createdAt:new Date().toISOString()}),Ae=e=>{let t=Rt(e);if(!tt.existsSync(t))return s("Missing .epiq/project.json");try{let n=tt.readFileSync(t,"utf8"),r=JSON.parse(n),o=ms.safeParse(r);return o.success?c("Read project.json",o.data):s(`Invalid .epiq/project.json: ${o.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(", ")}`)}catch(n){return s(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},Ar=e=>{let t=Ae(e);return d(t)?s(t.message):c("Read projectId",t.value.projectId)},wr=({repoRoot:e,fileContents:t})=>{let n=bt(e),r=Rt(e);try{if(tt.mkdirSync(n,{recursive:!0}),tt.existsSync(r)){let o=Ae(e);return d(o)?s(o.message):c("Project already initialized",null)}return tt.writeFileSync(r,JSON.stringify(t,null,2)+`
3
- `,"utf8"),c("Created project.json",null)}catch(o){return s(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var We=e=>{let t=Se(e);if(d(t))return s("Unable to resolve epiq project root");let n=Ae(t.value);return d(n)?s("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},se="origin";import ot from"node:fs";import ys from"node:os";import le from"node:path";var Sn=(e,t)=>{let n=new Map,r=t??((...i)=>JSON.stringify(i)),o=((...i)=>{let a=r(...i);if(!n.has(a)){let l=e(...i).then(u=>(d(u)&&n.delete(a),u));n.set(a,l)}return n.get(a)});return o.clear=()=>n.clear(),o};import nt from"fs";import Mr from"path";import ps from"util";var Tr=1e3,kr=()=>{let e=process.cwd(),t=ce(e);if(!d(t))return Mr.join(t.value,ve,"log","epiq.log")};function gs(){if(!bn)return;let e=kr();if(e===void 0||!nt.existsSync(e))return;let n=nt.readFileSync(e,"utf8").split(`
4
- `);if(n[n.length-1]===""&&n.pop(),n.length<=Tr)return;let r=n.slice(-Tr).join(`
5
- `)+`
6
- `;nt.writeFileSync(e,r,"utf8")}function An(e,t,n=!1){if(!bn)return;let r=kr();if(!r)return;let o=ps.format(...t),i=new Date,l=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
7
- `;nt.mkdirSync(Mr.dirname(r),{recursive:!0}),nt.appendFileSync(r,l,"utf8"),gs()}var Z={info(...e){An("[Info]",e,!1)},debug(...e){An("->",e,!0)},error(...e){An("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=Z;import{spawn as fs}from"node:child_process";import wn from"node:fs";import Lr from"node:path";var B={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 Pr=15e3,vs={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Dr=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!wn.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:p,exitCode:1});return}r(s(p));return}let o=fs("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:vs}),i=!1,a="",l="",u=p=>{i||(i=!0,clearTimeout(m),r(p))},m=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${Pr}ms`].join(`
8
- `);u(n?{stdout:a,stderr:p,exitCode:124}:s(p))},Pr);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{a+=p}),o.stderr.on("data",p=>{l+=p}),o.on("error",p=>{if(n){u({stdout:a,stderr:p.message,exitCode:1});return}u(s([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
9
- `)))}),o.on("close",p=>{let x=p??1;if(n){u({stdout:a,stderr:l,exitCode:x});return}if(x!==0){u(s([`git ${e.join(" ")}`,l.trim()||a.trim()||"Git command failed"].filter(Boolean).join(`
10
- `)));return}u(c("Git command succeeded",{stdout:a,stderr:l,exitCode:x}))})}),D=({args:e,cwd:t})=>Dr({args:e,cwd:t,allowFail:!1}),He=({args:e,cwd:t})=>Dr({args:e,cwd:t,allowFail:!0}),Ke=async({cwd:e,message:t})=>{let n=await B.commit({cwd:e,message:t});if(d(n))return s(`Failed to create commit
11
- ${n.message}`);let r=await D({args:["rev-parse","HEAD"],cwd:e});return d(r)?s(`Commit created, but failed to read HEAD SHA
12
- ${r.message}`):c("Created commit and resolved SHA",r.value.stdout.trim())},rt=async e=>{let t=await $r(e);if(d(t))return s(t.message);let n=t.value,o=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","REBASE_HEAD","rebase-merge","rebase-apply"].filter(i=>wn.existsSync(Lr.join(n,i)));return c("Checked for in-progress Git operation",o.length>0)},Tn=async({repoRoot:e})=>{let n=(await He({args:["remote","get-url",se],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},At=async({repoRoot:e,branch:t})=>{let n=await He({args:["ls-remote","--heads",se,t],cwd:e});return n.exitCode!==0?s(n.stderr.trim()||`Unable to inspect remote branch ${se}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},wt=async({repoRoot:e,branch:t})=>{let n=await He({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?c("Local branch exists",!0):n.exitCode===1?c("Local branch missing",!1):s(n.stderr.trim()||`Unable to inspect branch ${t}`)},Fr=e=>{try{return wn.realpathSync.native(e)}catch{return Lr.resolve(e)}},Or=async({repoRoot:e,worktreeRoot:t})=>{let n=await D({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return s(n.message);let r=Fr(t),o=n.value.stdout.split(`
13
- `).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(Fr).includes(r);return c("Checked worktree registration",o)},Mn=async e=>{let t=await He({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Tt=async e=>{let t=await D({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?s(t.message):c("Resolved current branch",t.value.stdout.trim())},Ur=async e=>{let t=await D({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?s(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},Br=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),kn=async({cwd:e,branch:t})=>{let n=await At({repoRoot:e,branch:t});if(d(n))return s(n.message);if(!n.value)return c("Remote branch missing, skipped pull",!1);let r=await B.fetch({cwd:e,remote:se,branch:t});if(d(r))return s(`Failed to fetch ${t}
14
- ${r.message}`);let o=await B.pullRebase({cwd:e,remote:se,branch:t});return d(o)?s(`Failed during pull --rebase
15
- ${o.message}`):c("Pulled with rebase",!0)},_r=async e=>{let t=await D({args:["status","--porcelain"],cwd:e});return d(t)?s(t.message):c("Checked state branch changes",t.value.stdout.trim().length>0)},jr=async e=>{let t=await Tt(e);return d(t)?s(t.message):c("Checked detached HEAD state",t.value==="HEAD")};var Wr="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Hr=e=>le.join(ve,Ct,e),Kr=()=>le.join(ys.homedir(),ie),Mt=()=>le.join(Kr(),"worktrees"),Vr=({repoRoot:e})=>{let t=Ar(e);return d(t)?s(t.message):c("Resolved state branch root",le.join(Mt(),t.value))},xs=e=>le.join(e,ve),De=e=>le.join(xs(e),Ct),Pn=({root:e,fileName:t})=>le.join(De(e),t),it=e=>{try{return ot.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return s(t instanceof Error?t.message:String(t))}},kt=()=>{let e=it(Kr());if(d(e))return s(`Ensure epiq home failed.
16
- `+e.message);let t=it(Mt());return d(t)?s(`Ensure worktrees dir failed.
17
- `+t.message):c("Ensured epiq storage",!0)},qr=e=>{ot.existsSync(e)&&(Z.debug("[sync] remove path",e),ot.rmSync(e,{recursive:!0,force:!0}))},zr=e=>{let t=De(e);if(!ot.existsSync(t))return c("Events dir missing",[]);let n=ot.readdirSync(t,{withFileTypes:!0}).filter(r=>r.isFile()).map(r=>r.name).filter(r=>r.endsWith(".jsonl")).sort();return c("Listed event files",n)},Gr=(e,t)=>{for(let n of[De(e),De(t)]){let r=it(n);if(d(r))return s(r.message)}return c("Ensured state branch",void 0)},Xr=async e=>{let t=await D({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return s(`ensure state branch is storage only failed
18
- `+t.message);let r=t.value.stdout.trim().split(`
19
- `).filter(Boolean).filter(a=>a!==ve);if(r.length===0)return c("State branch is storage-only",!1);let o=await D({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(d(o))return s(`Failed to clean storage branch
20
- ${o.message}`);let i=await Ke({cwd:e,message:"[epiq:repair-storage-branch]"});return d(i)?s(i.message):c("Cleaned storage branch",!0)},Pt=Sn(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=>le.resolve(e)),$r=Sn(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=le.isAbsolute(n)?n:le.join(e,n);return c("Resolved git dir",r)},e=>le.resolve(e));import Ve from"node:fs";import st from"node:path";var Yr=async e=>{if((await He({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);Z.info("Creating initial commit");let n=await B.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return d(n)?s(n.message):c("Created initial commit",!0)},Jr=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",hs=async e=>{let t=await Tt(e);if(d(t))return s(t.message);let n=await Ur(e);if(d(n))return s(n.message);let r=`[epiq:sync:${Jr(t.value)}:${Jr(n.value)}]`;return c("Built sync commit message",r)},Ft=async({repoRoot:e,stateBranchName:t})=>{Z.info(`Creating ${t}`);let n=await D({args:["commit-tree",Wr,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return s(`Failed to create state branch commit
21
- ${n.message}`);let r=n.value.stdout.trim(),o=await D({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return d(o)?s(`Failed to create ${t}
22
- ${o.message}`):c("Created state branch",!0)},Es=async({repoRoot:e,stateBranchName:t})=>{let n=await wt({repoRoot:e,branch:t});if(d(n))return s(`Ensure local state branch failed
23
- `+n.message);if(n.value)return c("Local state branch already exists",!1);let r=await Tn({repoRoot:e});if(d(r))return s(`Ensure local state branch failed
24
- `+r.message);if(!r.value)return Ft({repoRoot:e,stateBranchName:t});let o=await At({repoRoot:e,branch:t});if(d(o))return s(`Ensure local state branch failed
25
- `+o.message);if(!o.value)return Ft({repoRoot:e,stateBranchName:t});let i=await B.fetch({cwd:e,remote:se,branch:t});if(d(i))return s(`Failed to fetch ${t} from remote
26
- ${i.message}`);let a=await D({args:["branch","--track",t,`${se}/${t}`],cwd:e});return d(a)?s(`Failed to create local ${t} from remote
27
- ${a.message}`):c("Created local state branch from remote",!0)},Ns=async({repoRoot:e,branch:t})=>{let n=await D({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return s(n.message);let r=n.value.stdout.split(`
28
- `),o=null;for(let i of r){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return c("Found worktree for branch",o)}return c("No worktree found for branch",null)},Is=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=it(st.dirname(t));if(d(r))return s(`Failed to create state branch worktree
29
- `+r.message);Ve.existsSync(t)&&!Ve.existsSync(st.join(t,".git"))&&(Z.info("Removing broken state branch worktree path"),qr(t)),Z.info("Creating state branch worktree");let o=await B.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(o)?s(`Failed to create state branch worktree
30
- ${o.message}`):c("Created state branch worktree",!0)},Fn=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await Ns({repoRoot:e,branch:n});if(d(r))return s(r.message);let o=st.resolve(t),i=r.value?st.resolve(r.value):null;if(i&&i===o&&Ve.existsSync(i))return c("State branch already checked out in expected worktree",!1);if(i&&i!==o){Z.info("Moving state branch worktree to expected location");let u=await B.worktreeRemove({cwd:e,worktreeRoot:i});if(d(u))return s(`Failed to remove existing state branch worktree
31
- ${u.message}`)}if(i&&!Ve.existsSync(i)){Z.info("Pruning stale state branch worktree");let u=await B.worktreePrune({cwd:e});if(d(u))return s(`Failed to prune stale worktrees
32
- ${u.message}`)}let a=await Or({repoRoot:e,worktreeRoot:t});if(d(a))return s(a.message);let l=Ve.existsSync(t);if(a.value&&l)return c("State branch worktree already exists",!1);if(a.value&&!l){Z.info("Pruning missing registered state branch worktree");let u=await B.worktreePrune({cwd:e});if(d(u))return s(`Failed to prune stale worktrees
33
- ${u.message}`)}return Is({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Cs=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Tt(e);if(d(n))return s(n.message);if(n.value===t)return c("State branch already checked out",!1);let r=await B.checkout({cwd:e,branch:t});return d(r)?s(`Failed to checkout ${t}
34
- ${r.message}`):c("Checked out state branch",!0)},bs=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Mn(t);if(d(n))return s(n.message);if(n.value)return c("State branch upstream already configured",!1);let r=await Tn({repoRoot:t});if(d(r))return s(r.message);if(!r.value)return c("No remote available for state branch upstream",!1);let o=We(e);if(d(o))return o;let i=o.value,a=await At({repoRoot:t,branch:i});if(d(a))return s(a.message);if(!a.value)return c("Remote state branch missing; upstream will be configured on first push",!1);Z.info(`Configuring ${i} upstream`);let l=await B.fetch({cwd:t,remote:se,branch:i});if(d(l))return s(`Failed to fetch ${i}
35
- ${l.message}`);let u=await B.setUpstream({cwd:t,branch:i,upstream:`${se}/${i}`});return d(u)?s(`Failed to set state branch upstream
36
- ${u.message}`):c("Configured state branch upstream",!0)},Lt=async({stateBranchRoot:e,eventFileName:t})=>{let n=Hr(t),r=st.join(e,n);if(!Ve.existsSync(r))return c("No event file to stage",void 0);let o=await B.stage({cwd:e,pathspec:[n]});return d(o)?s(`Failed to stage state branch event file
37
- ${o.message}`):c("Staged state branch event file",void 0)},Zr=async({repoRoot:e,stateBranchRoot:t})=>{let n=await hs(e);return d(n)?s(`Create state branch sync commit failed
38
- `+n.message):Ke({cwd:t,message:n.value})},at=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Mn(t);if(d(n))return s(n.message);let r=We(e);if(d(r))return r;let o=r.value,i=n.value?await B.push({cwd:t}):await B.push({cwd:t,remote:se,branch:o,setUpstream:!0});return d(i)?s(`Failed during state branch push
39
- ${i.message}`):c("Pushed state branch",!0)},Qr=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=We(e);if(d(o))return o;let i=o.value,a=[kt(),await Es({repoRoot:e,stateBranchName:i}),await Fn({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await Cs({stateBranchRoot:t,stateBranchName:i}),await Xr(t),n?await bs({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of a){if(d(l))return s(l.message);r=r||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage (readonly)",r)};import $t from"node:fs";import Bn from"node:path";import{decodeTime as $s}from"ulid";import _t from"node:fs";import On from"node:path";import{decodeTime as Fs}from"ulid";import{z as Dn}from"zod";import Rs from"node:fs";import Ss from"node:path";import{decodeTime as As,monotonicFactory as ws}from"ulid";import{z as dt}from"zod";var Dt={autoSync:!1,preferredEditor:null,userName:null,userId:null},ue=()=>Dt,Ot=e=>(Dt={...Dt,...e},Dt);var eo=e=>({action:e.action,payload:e.payload});var no=1,to=ws(),Ts=dt.tuple([dt.string().min(1),dt.string().min(1).nullable()]),Ms=dt.looseObject({v:dt.literal(no),id:Ts}),Ln=e=>{let t=Ms.safeParse(e);return t.success?c("Parsed persisted event",t.data):s(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Ut=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",X=()=>{let{userName:e,userId:t}=ue();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:Ut(t),userName:Ut(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},we=({userId:e,userName:t})=>`${Ut(e)}.${Ut(t)}.jsonl`,ks=(e,{userId:t,userName:n})=>{let r=we({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return s(`Invalid event log file name: ${r}`);let i=Ss.join(et(e),r);return c("Successfully resolved event log path",i)},Ps=(e,t)=>{let n={[e.action]:e.payload,v:no,id:t};return Ln(n)};function Bt({event:e,rootDir:t=process.cwd()}){try{let n=ce(t);if(d(n))return n;let r=Rr(n.value);if(d(r))return r;let o=ks(n.value,{userId:e.userId,userName:e.userName});if(d(o))return o;let i=ro(n.value);if(d(i))return s(i.message);let a=i.value?to(Math.max(Date.now(),As(i.value)+1)):to(),l=Ps(eo(e),[a,i.value]);return d(l)?s(l.message):(Rs.appendFileSync(o.value,`${JSON.stringify(l.value)}
40
- `,"utf8"),c("Event persisted",{path:o.value,entry:l.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return s(`Failed to persist event: ${r}`)}}var Ls=Dn.object({userId:Dn.string().min(1).default("unknown"),userName:Dn.string().min(1).default("unknown")}),Ds=e=>{let[t,n]=On.basename(e,".jsonl").split("."),r=Ls.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):s(`Invalid event file name ${On.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Os=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?s(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?s("Invalid persisted event: action key is missing or invalid"):c("Resolved persisted action",t[0])},Us=(e,t)=>t in e,Bs=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),_s=e=>{let{userId:t,userName:n,...r}=e,o=Os(r);if(d(o))return s(o.message);let i=o.value,a=e.id?.[0];return a?Us(r,i)?c("Decoded persisted event",Bs({id:a,action:i,payload:r[i],userId:t,userName:n})):s(`Persisted event is missing payload for action: ${i}`):s("Persisted event is missing id")},jt=e=>{if(!_t.existsSync(e))return c("Event file missing",[]);let t=Ds(e);if(d(t))return s(t.message);let n=_t.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
41
- `)){let i=o.trim();if(!i)continue;let a;try{a=JSON.parse(i)}catch{return s(`Failed to parse event JSON from ${e}: ${i}`)}let l=Ln(a);if(d(l))return s(`${l.message} in ${e}: ${i}`);r.push({...l.value,userId:t.value.userId,userName:t.value.userName})}return c("Parsed persisted events file",r)};function oo(e){let t=et(e);if(!_t.existsSync(t))return c("No events found",[]);let n=_t.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>On.join(t,o)),r=[];for(let o of n){let i=jt(o);if(d(i))return s(i.message);r.push(...i.value)}return c("All events loaded",js(r))}function ct(e){let t=oo(e);if(d(t))return s(t.message);let n=[];for(let r of t.value){let o=_s(r);if(d(o))return s(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);n.push(o.value)}return c("Loaded merged events",n)}function ro(e=process.cwd()){let t=oo(e);return d(t)?s(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var js=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],x=m.id[1]??null;t.set(p,m);let E=n.get(x)??[];E.push(m),n.set(x,E)}for(let m of n.values())m.sort((p,x)=>p.id[0].localeCompare(x.id[0]));let r=[],o=new Set,i=m=>{let p=m.id[0];if(o.has(p))return;r.push(m),o.add(p);let x=n.get(p)??[];for(let E of x)i(E)},a=n.get(null)??[];for(let m of a)i(m);let l=e.filter(m=>{let p=m.id[0],x=m.id[1]??null;return!o.has(p)&&x!==null&&!t.has(x)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of l)i(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)i(m);return r},io=(e,t)=>{let n=e.findIndex(r=>{try{return Fs(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var Un=e=>{let[t,n]=e.id;return`${t}:${n??""}`},so=e=>{let[t]=e.id;return $s(t)},Ws=e=>{let{userId:t,userName:n,...r}=e;return r},Hs=e=>e.length===0?"":e.map(t=>JSON.stringify(Ws(t))).join(`
42
- `)+`
43
- `,Ks=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(Un(r),r);return[...n.values()].sort((r,o)=>{let i=so(r)-so(o);return i!==0?i:Un(r).localeCompare(Un(o))})},_n=({sourceFile:e,targetFile:t})=>{let n=jt(e);if(d(n))return s(n.message);let r=jt(t);if(d(r))return s(r.message);let o=Ks(r.value,n.value),i=Hs(o);return($t.existsSync(t)?$t.readFileSync(t,"utf8"):"")===i?c("Event file already merged",!1):($t.mkdirSync(Bn.dirname(t),{recursive:!0}),$t.writeFileSync(t,i,"utf8"),c("Merged event file",!0))},Wt=({repoRoot:e,stateBranchRoot:t})=>{let n=zr(t);if(d(n))return s(n.message);let r=De(t),o=De(e),i=!1;for(let a of n.value){let l=Bn.join(r,a),u=Bn.join(o,a),m=_n({sourceFile:l,targetFile:u});if(d(m))return s(m.message);i=i||m.value}return c("Hydrated event files from state branch",i)};var qs=({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=Pn({root:e,fileName:n}),o=Pn({root:t,fileName:n});return Vs.existsSync(r)?_n({sourceFile:r,targetFile:o}):c("Local own event file missing, nothing to merge",!1)},zs=async({cwd:e,ensureUpstream:t})=>{let n=await Pt(e);if(d(n))return s(n.message);let r=n.value,o=Vr({repoRoot:r});if(d(o))return s(o.message);let i=o.value,a=await rt(r);if(d(a))return s(a.message);if(a.value)return s("Cannot sync while a git operation is in progress in the current repo");let l=await Yr(r);if(d(l))return s(l.message);let u=await Qr({repoRoot:r,stateBranchRoot:i,ensureUpstream:t});if(d(u))return s(u.message);let m=await rt(i);if(d(m))return s(m.message);if(m.value)return s("Cannot sync while a git operation is in progress in the state branch");let p=Gr(r,i);return d(p)?s(p.message):c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:i,bootstrapped:u.value})},ao=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=qs({repoRoot:e,stateBranchRoot:t,ownEventFileName:n});if(d(r))return s(r.message);let o=await _r(t);if(d(o))return s(o.message);if(!r.value&&!o.value)return c("Own event file already up to date in state branch",{createdCommit:!1});let i=await Lt({stateBranchRoot:t,eventFileName:n});if(d(i))return s(i.message);let a=await Zr({repoRoot:e,stateBranchRoot:t});return d(a)?s(a.message):c("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:a.value})},Ht=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(t.includes("/")||t.includes("\\"))return s("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return s("Own event file must end with .jsonl");let n=await zs({cwd:e,ensureUpstream:!0});if(d(n))return n;let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,a=await jr(r);if(d(a))return s(a.message);if(a.value)return s("Cannot run :sync while the repository is in detached HEAD state");let l=!1,u,m=!1,p=!1,x=!1,E=We(r);if(d(E))return E;let I=E.value,R=await kn({cwd:o,branch:I});if(d(R))return s(R.message);m=R.value;let b=Wt({repoRoot:r,stateBranchRoot:o});if(d(b))return s(b.message);x=b.value;let N=await ao({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(d(N))return s(N.message);if(l=N.value.createdCommit,u=N.value.commitSha,l||i){let w=await at({stateBranchRoot:o,repoRoot:r}),j=w;if(d(w)&&Br(w.message)){let Re=await kn({cwd:o,branch:I});if(d(Re))return s(Re.message);let te=await ao({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(d(te))return s(te.message);te.value.createdCommit&&(l=!0,u=te.value.commitSha),j=await at({stateBranchRoot:o,repoRoot:r})}if(d(j))return s(j.message);p=j.value,logger.debug("[sync] pushed to state branch",p)}else logger.debug("[sync] no commit created, skipped push");if(l){let w=await D({args:["rev-parse","HEAD"],cwd:o});if(d(w))return s(w.message);u=w.value.stdout.trim()}return c("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,pulled:m,pushed:p,hydrated:x,bootstrapped:i})};import ta from"node:os";import mo from"node:path";import{z as lt}from"zod";import{accessSync as Gs,copyFileSync as Xs,existsSync as Kt,mkdirSync as co,readdirSync as lo,readFileSync as Js,renameSync as Ys,rmSync as Zs,statSync as uo,unlinkSync as Qs,writeFileSync as ea}from"node:fs";import qe from"node:path";var ne={writeToFile:(e,t)=>{try{let n=qe.dirname(e);Kt(n)||co(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);ea(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Js(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=ne.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 Kt(e)&&uo(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Gs(e),!0}catch{return!1}},mkDir:e=>co(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=qe.parse(t);for(;;){let r=qe.join(t,e);try{if(Kt(r)&&uo(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=qe.dirname(t)}return null},readFirstJSON(e){try{if(!ne.dirExists(e))return null;let t=lo(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=qe.join(e,t);return ne.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return ne.dirExists(e)?lo(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Qs(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Zs(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(qe.dirname(t)),!n?.overwrite&&Kt(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Ys(e,t)}catch(r){if(r?.code==="EXDEV"){Xs(e,t),this.rmFile(e);return}throw r}}};var na={userId:"",userName:"",preferredEditor:"",autoSync:!1},po=lt.object({preferredEditor:lt.string().optional(),userName:lt.string().optional(),userId:lt.string().optional(),autoSync:lt.boolean().optional()}).strict(),ra="config.json",go=()=>mo.join(ta.homedir(),ie),jn=()=>mo.join(go(),ra),$n=()=>{try{return ne.mkDir(go()),c(`Ensured ~/${ie} exists`,null)}catch{return s(`Unable to create ~/${ie}`)}},oa=e=>{let t;try{t=JSON.parse(e)}catch{return s(`Invalid ~/${ie}/config.json JSON`)}let n=po.safeParse(t??{});return n.success?c("Parsed config",n.data):s(`Invalid ~/${ie}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},fo=()=>{let e=$n();if(d(e))return s(e.message);let t=jn(),n=ne.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{autoSync:!1,preferredEditor:"",userId:"",userName:""}):oa(n)},vo=e=>{let t=$n();if(d(t))return s(t.message);let n=po.safeParse(e);if(!n.success)return s(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=jn();try{return ne.writeToFile(r,JSON.stringify(n.data,null,2)+`
44
- `),c("Config written",null)}catch{return s(`Unable to write ~/${ie}/config.json`)}},Vt=e=>{let t=fo();if(d(t))return s("Failed to read existing config");let n={...t.value,...e};return vo(n)},yo=()=>{let e=jn(),t=$n();if(d(t))return s(`Unable to create ~/${ie}`);if(!(ne.readFile(e)!==null)){let u=vo(na);if(d(u))throw new Error(`Unable to create ~/${ie}/config.json`)}let r=fo();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:a,autoSync:l}=r.value;return!i||!a?s(`User name or ID not configured in ~/${ie}/config.json`):c("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:a,autoSync:l??!1})};import{monotonicFactory as aa,ulid as qt}from"ulid";var Oe=24n,ia=Oe*4n,ut=(1n<<ia)-1n,sa=/^[0-9a-f]+$/;function xo(e){return!e||!sa.test(e)?s(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function ye(e,t=Oe){if(e<0n)return s("Negative rank not allowed");let n=e.toString(16);return c("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function V(e,t){if(!e&&!t)return ye(ut/2n,Oe);let n=e?xo(e):c("Resolved lower bound",0n);if(d(n))return n;let r=t?xo(t):c("Resolved upper bound",ut);if(d(r))return r;let o=n.value,i=r.value;if(i<=o)return ye(ut/2n,Oe);let a=(o+i)/2n;return a===o||a===i?s("No rank space available between neighbors"):ye(a,Oe)}function ho(){return ye(ut/2n,Oe)}function Eo(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=ut*BigInt(r+1)/(t+1n),i=ye(o,Oe);if(d(i))return i;n.push(i.value)}return c("Resolved evenly spaced ranks",n)}var zt=aa(),Gt=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=zt(),a=zt(),l=zt(),u=zt(),m=ho();if(d(m))return m;let p=V(m.value,void 0);if(d(p))return p;let x=V(p.value,void 0);return d(x)?x:c("Created issue events",[{id:qt(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}},{id:qt(),userId:r,userName:o,action:"add.field",payload:{id:a,parent:i,name:"Description",val:"",rank:m.value}},{id:qt(),userId:r,userName:o,action:"add.field",payload:{id:l,parent:i,name:"Assignees",rank:p.value}},{id:qt(),userId:r,userName:o,action:"add.field",payload:{id:u,parent:i,name:"Tags",rank:x.value}}])};import{monotonicFactory as Wd,ulid as be}from"ulid";import{useSyncExternalStore as _d}from"react";var k={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function Wn(e){return e.context==="WORKSPACE"}function Q(e){return e.context==="TICKET"}function No(e){return e.context==="FIELD"}var Xt=e=>e.context==="SWIMLANE",Io=e=>e.context==="BOARD";var f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function Jt(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Yt=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",ze=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var Co=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},bo=(e,t)=>t?e.get(t)??[]:[];var Ro=new WeakMap,da=e=>{let t=Ro.get(e);return t||(t=Co(e),Ro.set(e,t)),t};var So=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return bo(da(e),r).filter(i=>Jt(r,i)>=n)};var ca={hint:"",hints:[],overlap:0,remainder:""},Ao=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return ca;let o=So({wordList:r,inputToMatch:e,overlapThreshold:1});return la(t,o)},la=(e,t)=>{let n=t[0]??"",r=Jt(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 wo=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var z={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:k.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:k.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:k.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:(e,t,n,r,o={},i="horizontal")=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:k.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[]}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:k.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:k.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[]})};import{ulid as ua}from"ulid";var Hn=(e,t)=>{let n=$(e),r=Eo(n.length);if(d(r))return r;let o={};for(let i=0;i<n.length;i++){let a=n[i],l=r.value[i];if(!a||!l)return s("Unable to assign rebalance rank");o[a.id]=l}return c("Created rebalance event",{id:ua(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var ma=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[J,Zt]=ma;var P=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),pa={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=z.workspace(t,n,r),i=gt(o);if(d(i))return P(i.message,e);let a=h.createNode(o);return d(a)?P(a.message??"Failed to initialize workspace",e):Wn(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=z.workspace(t,n,r),i=h.createNode(o);return d(i)?P(i.message??"Failed to add workspace",e):Wn(i.value)?c("Added workspace",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=h.createNode(z.board(t,n,r,o));return d(i)?P(i.message??"Unable to create board",e):Io(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=h.createNode(z.swimlane(t,n,r,o));return d(i)?P(i.message??"Unable to create swimlane",e):Xt(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=h.createNode(z.ticket(t,n,r,o));return d(i)?P(i.message??"Unable to create issue",e):Q(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=h.createNode(z.field(t,n,r,i,{value:o},n.includes("Description")?"vertical":"horizontal"));return d(a)?P(a.message??`Unable to create field: ${n}`,e):No(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(!h.getNode(t))return P(`Unable to locate node with id ${t}`,e);let o=h.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=h.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=h.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=h.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})},"tag.issue":e=>{let{id:t,target:n,tagId:r,rank:o}=e.payload,i=h.tag(n,r,t,o);return d(i)?P(i.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:i.value})},"untag.issue":e=>{let{target:t,tagId:n}=e.payload,r=h.untag(t,n);return d(r)?P(r.message??"Unable to untag ",e):c("Issue untagged",{action:e.action,result:r.value})},"assign.issue":e=>{let{id:t,contributor:n,target:r,rank:o}=e.payload,i=h.assign(r,n,t,o);return d(i)?P(i.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:i.value})},"unassign.issue":e=>{let{target:t,contributor:n}=e.payload,r=h.unassign(t,n);return d(r)?P(r.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:r.value})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=h.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=h.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=h.getNode(t);if(!o)return P("Unable to locate issue",e);if(!Q(o))return P("Can only close issues",e);let i=h.getNode(J);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=h.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=h.getNode(t);if(!o)return P("Unable to locate issue",e);if(!Q(o))return P("Can only reopen issues",e);let i=h.getNode(J);if(!i)return P("Unable to locate closed swimlane",e);if(n===i.id)return P("Cannot reopen issue into closed swimlane",e);if(!h.getNode(n))return P("Reopen parent no longer exists",e);let l=h.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=h.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=h.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=h.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}})}},ga=(e,t)=>{let n=h.getNode(e);n&&h.updateNode({...n,log:[...n.log??[],t]})},fa=e=>{switch(e.action){case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"delete.node":case"move.node":case"close.issue":case"reopen.issue":return[e.payload.id];case"edit.description":let t=[e.payload.id],n=v().nodes[e.payload.id]?.parentNodeId;return n&&t.push(n),t;case"tag.issue":case"untag.issue":case"assign.issue":case"unassign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function mt(e,t=!1){let n=pa[e.action](e);if(d(n))return n;t||([...new Set(fa(e))].forEach(a=>ga(a,e)),re(a=>({...a,eventLog:[...a.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?P("Invalid user ID format",e):(h.createContributor({name:o,id:r}),n)}var pt=e=>e.map(t=>mt(t));function K(e){let t=mt(e);if(t.status!==ge.Success)return t;let n=Bt({event:e});return d(n)?n:t}function Te(e){return e.map(t=>K(t))}var To=e=>Kn($(e),{at:"end"}),Kn=(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(V(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(V(void 0,r.rank)):s("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(V(r.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let r=Mo(e,t.sibling);if(r<0)return s("Sibling not found");let o=r>0?e[r-1]:void 0,i=e[r];return i?n(V(o?.rank,i.rank)):s("Sibling not found")}case"after":{let r=Mo(e,t.sibling);if(r<0)return s("Sibling not found");let o=e[r],i=r<e.length-1?e[r+1]:void 0;return o?n(V(o.rank,i?.rank)):s("Sibling not found")}}},$=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Mo=(e,t)=>e.findIndex(n=>n.id===t),ko=(e,t,n={at:"end"})=>Kn($(t).filter(r=>r.id!==e),n),xe=(e,t,n,r)=>{let o=ko(t,e,n);if(d(o))return o;if(!o.value.needsRebalance)return c("Resolved rank",o.value.rank);let i=Hn(e,r);if(d(i))return i;let a=K(i.value);if(d(a))return a;let l=ko(t,e,n);return d(l)?l:l.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",l.value.rank)},Me=(e,t)=>{let n=To(e);if(d(n))return n;if(!n.value.needsRebalance)return c("Resolved rank",n.value.rank);let r=Hn(e,t);if(d(r))return r;let o=K(r.value);if(d(o))return o;let i=To(e);return d(i)?i:i.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",i.value.rank)};var Ge=(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}`)},va=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Vn=(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"),h={deleteNode(e){re(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=Vn(r,"edit");if(o)return o;let i={...r,props:{...r.props,value: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=Vn(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 $(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=Vn(o,"move");if(a)return a;if(va(t,e))return s("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=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 $(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?(C({nodes:l}),c("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=re(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?s("Unable to create contributor"):c("Created contributor",e)},assign(e,t,n,r){let o=this.getContributor(t),i=this.getNode(e);if(!i||!o)return s("Unable assign contributor to issue");let a=this.getFieldByTitle(i.id,"Assignees");if(!a)return s("Unable to locate assignees field");if($(a.id).some(p=>p.props?.value===t))return s("Contributor already assigned");let u=z.field(n,o.name,a.id,r,{value:t}),m=this.createNode(u);return d(m)?m:c("Assigned contributor",u)},createTag(e){let t=re(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?s("Could not create tag"):c("Tag created",e)},tag(e,t,n,r){let o=this.getTag(t),i=this.getNode(e);if(!o)return s("Unable to add tag, missing tag");if(!i)return s("Unable to add tag, missing target");let a=this.getFieldByTitle(i.id,"Tags");if(!a)return s("Unable to locate tags field");if($(a.id).some(p=>p.props?.value===t))return s("Tag already assigned");let u=z.field(n,o.name,a.id,r,{value:t}),m=this.createNode(u);return d(m)?m:c("Tag added",u)},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return s("Unable to remove tag, missing tag");if(!r)return s("Unable to remove tag, missing target");let o=this.getFieldByTitle(r.id,"Tags");if(!o)return s("Unable to locate tags field");let i=$(o.id).find(l=>l.props?.value===t);if(!i)return c("Issue is not tagged with that tag",null);let a={...i,isDeleted:!0};return this.updateNode(a),c("Tag removed",a)},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return s("Unable to unassign, missing contributor");if(!r)return s("Unable to unassign, missing target");let o=this.getFieldByTitle(r.id,"Assignees");if(!o)return s("Unable to locate assignees field");let i=$(o.id).find(l=>l.props?.value===t);if(!i)return c("Issue is not assigned to that contributor",null);let a={...i,isDeleted:!0};return this.updateNode(a),c("Assignee removed",a)},createNode(e){let t=re(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=re(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?s(r.message):c("Locked node",n)},updateNode(e){let t=re(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 $(e)}};var Qt=()=>{let e=ue(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},Po=()=>{let e=Se(process.cwd());if(d(e))return s("Unable to determine if repository is initialized");let t=Ae(e.value);return Ze(t)};var G={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"},M={accent:G.cyan,accent2:G.magenta,primary:G.white,secondary:G.grayDark,secondary2:G.grayLight,gray:G.gray,green:G.green,yellow:G.yellow,red:G.red};var y={red:G.red,yellow:G.yellow,green:G.green,blue:G.blue,magenta:G.magenta,cyan:G.cyan},Xe={urgent:y.red,critical:y.red,important:y.red,blocker:y.red,asap:y.red,immediate:y.red,fail:y.red,failure:y.red,broken:y.red,bug:y.red,error:y.red,incident:y.red,outage:y.red,production:y.red,crash:y.red,security:y.red,warning:y.yellow,warn:y.yellow,risky:y.yellow,risk:y.yellow,attention:y.yellow,pending:y.yellow,review:y.yellow,"needs-review":y.yellow,qa:y.yellow,testing:y.yellow,test:y.yellow,validate:y.yellow,verification:y.yellow,staging:y.yellow,check:y.yellow,"follow-up":y.yellow,followup:y.yellow,waiting:y.yellow,blocked:y.yellow,hold:y.yellow,done:y.green,complete:y.green,completed:y.green,success:y.green,ok:y.green,stable:y.green,resolved:y.green,fixed:y.green,closed:y.green,merged:y.green,released:y.green,deployed:y.green,approved:y.green,verified:y.green,working:y.green,healthy:y.green,pass:y.green,passing:y.green,info:y.blue,information:y.blue,note:y.blue,docs:y.blue,documentation:y.blue,doc:y.blue,guide:y.blue,help:y.blue,explanation:y.blue,detail:y.blue,details:y.blue,context:y.blue,design:y.blue,discussion:y.blue,proposal:y.blue,idea:y.blue,feature:y.magenta,enhancement:y.magenta,improvement:y.magenta,refactor:y.magenta,refactoring:y.magenta,cleanup:y.magenta,optimize:y.magenta,optimization:y.magenta,perf:y.magenta,performance:y.magenta,upgrade:y.magenta,migration:y.magenta,modernize:y.magenta,debt:y.magenta,todo:y.cyan,next:y.cyan,planned:y.cyan,plan:y.cyan,future:y.cyan,backlog:y.cyan,investigate:y.cyan,explore:y.cyan,prototype:y.cyan};var Fo=(e,t)=>{let r=S(e.id).find(o=>o.title===t);return r?S(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},qn=e=>Fo(e,"Tags").map(t=>h.getTag(t)).filter(t=>!!t),en=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!Q(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",qn(n)??[])},tn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!Q(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",zn(n)??[])},zn=e=>Fo(e,"Assignees").map(t=>h.getContributor(t)).filter(t=>!!t);var Lo=(e,t)=>{let r=S(e.id).find(o=>o.title===t);return r&&typeof r.props?.value=="string"?ze(r.props.value):""};var g={EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",RENAME:"rename",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",SET_DESCRIPTION:"edit",SET_EDITOR:"config:editor",SET_VIEW:"config:view",SET_USERNAME:"config:username",SYNC:"sync",EXPORT:"export",NONE:""};var ya=/^(\d+)(h|d|w|mo|y)$/,xa=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,ha=({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},Ea=(e,t=new Date)=>{let n=e.match(ya);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}},Na=e=>{let t=e.match(xa);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 ha({year:l,month:u,day:m,hour:p,minute:x})?new Date(l,u-1,m,p,x):null},nn=e=>{let t=e.trim().toLowerCase();return Ea(t)??Na(t)},Do=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Ia=[{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}],Oo=(e=Ia)=>{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 Ca=["BOARD","TICKET","SWIMLANE"],Ue=[g.SYNC,g.HELP,g.EXPORT,g.SET_VIEW,g.SET_EDITOR,g.SET_USERNAME],rn=[g.NEW,g.RENAME,g.DELETE,g.MOVE],Gn=[g.TAG,g.UNTAG,g.ASSIGN,g.UNASSIGN,g.CLOSE_ISSUE,g.RE_OPEN_ISSUE,g.SET_DESCRIPTION],Uo=[g.FILTER,g.PEEK],ba={WORKSPACE:[...Ue,...rn],BOARD:[...Uo,...Ue,...rn],SWIMLANE:[...Uo,...Ue,...rn],TICKET:[...Ue,...rn,...Gn],FIELD:[...Ue,...Gn],FIELD_LIST:[...Ue,...Gn],TEXT:[...Ue]},Ra=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Sa=()=>{let{currentNode:e,selectedNode:t,readOnly:n}=v();if(!Qt().isSetup)return[g.HELP,g.SET_EDITOR,g.SET_USERNAME];if(!Po())return[g.HELP,g.INIT];if(n)return[g.HELP,g.PEEK,g.EXPORT,g.SET_VIEW];let o=e.context??"WORKSPACE",i=t?.context,a=i&&Ca.includes(i);return ba[o].filter(l=>l===g.RENAME||l===g.DELETE||l===g.MOVE?a:!0)},q=e=>{let{currentNode:t}=v(),n=t.context??"WORKSPACE";return{[g.NONE]:Sa(),[g.EXIT]:["confirm"],[g.EXPORT]:[],[g.SYNC]:[],[g.INIT]:[],[g.HELP]:[],[g.PEEK]:[...Oo(),"now","prev","next"],[g.SET_USERNAME]:[],[g.SET_DESCRIPTION]:["confirm"],[g.DELETE]:["confirm"],[g.RE_OPEN_ISSUE]:["confirm"],[g.CLOSE_ISSUE]:["confirm"],[g.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[g.FILTER]:["tag","assignee","description","title","clear"],[g.SET_VIEW]:["dense","wide"],[g.SET_EDITOR]:[...wo],[g.TAG]:[...new Set([...Object.keys(Xe),...h.getExistingTags()])],[g.UNTAG]:[...en()?.value?.map(({name:o})=>o)??[]],[g.UNASSIGN]:[...tn()?.value?.map(({name:o})=>o)??[]],[g.ASSIGN]:h.getExistingAssignees(),[g.RENAME]:[],[g.NEW]:Ra(n)}[e]??[]};import Je from"chalk";import{decodeTime as Bo}from"ulid";var _o=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"};var jo=e=>{try{return c("Decoded date",new Date(Bo(e)))}catch(t){return s("Decoding failed + "+t.message)}},Xn=e=>{if(!e?.id)return null;try{return Bo(e.id)}catch{return null}};var Be=(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 $o from"chalk";var Yn={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Aa=(e,t,n)=>Math.max(t,Math.min(n,e)),Jn=(e,t,n)=>e+(t-e)*n,Wo=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},wa=(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)]},Ta=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Ma=(e,t,n)=>[Math.round(Jn(e[0],t[0],n)),Math.round(Jn(e[1],t[1],n)),Math.round(Jn(e[2],t[2],n))],ft=e=>{let n=Wo(e)%360,r=wa(n,Yn.stringColor.saturation,Yn.stringColor.lightness);return Ta(r)},ka=e=>{let t=Yn.gradient.stops,n=Aa(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 Ma(t[i],t[i+1],a)},on=e=>Wo(e.toLowerCase().trim())/4294967295,Pa=e=>{let t=on(e);return ka(t)},Fa=e=>{let[t,n,r]=Pa(e);return{normal:o=>$o.bgRgb(t,n,r).black(o),cursor:o=>$o.bgRgb(t,n,r).white.bold(o)}};var Zn=e=>Fa(e).normal(` ${e} `),ee=(e,t=Xe)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:ft(r)};var he={None:"none",Invalid:"invalid",Valid:"valid"};var La=["BOARD","TICKET","SWIMLANE"],Qn=()=>{let e=v().selectedNode;return e?.context?La.includes(e?.context)?_():O({message:"Command not available in this context"}):O({message:"Missing target context"})},Y="<ENTER> to confirm",_=(e="",t=[])=>({message:e,validity:he.Valid,completionWordList:t}),O=({message:e,completionWordList:t=[]})=>({validity:he.Invalid,message:e,completionWordList:t}),yt=e=>e.length===0,ke=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let u=[...t.filter(Boolean).filter(p=>p.startsWith(o.trim()))].sort((p,x)=>on(p)-on(x)).slice(0,r).map(Zn),m=u.length>i?u.join(" "):"";return m?`${e}${m}${n}`:""},er=({modifier:e})=>{let t="confirm";return e===t?_(Y):O({message:yt(e)?`if you are certain, enter ${Zn(t)}`:"",completionWordList:[t]})},Da=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?_(Y):O({message:yt(n)?t:""}),Oa=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?O({message:n}):_():O({message:yt(r)?t:""}),vt=({hint:e})=>({modifier:t,inputString:n})=>yt(t)&&yt(n)?O({message:e,completionWordList:[]}):_(Y),Ua={[g.EXPORT]:()=>_(Y+", and create export markdown file"),[g.PEEK]:e=>{let t=e.modifier;if(t==="now")return _(Y);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 _(Y);let r=nn(t);if(!t||!r)return O(n);let o=Be(v().breadCrumb,"BOARD");if(d(o))return O({message:"Command is not applicable in this context"});let i=jo(o.value.id);return d(i)?O({message:"Unable to peek: board id is not a valid ULID"}):Do({date:r,horizonDate:i.value})?_(Y):O({message:Je.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[g.EXIT]:()=>_(Y+" and exit the application"),[g.INIT]:()=>_(Y),[g.FILTER]:e=>{if(e.modifier==="clear")return _();let t=a=>q(g.FILTER).includes(a);if(!e.modifier||!t(e.modifier??""))return O({message:ke({wordList:q(g.FILTER),inputString:e.inputString}),completionWordList:q(g.FILTER)});let r=Object.values(v().tags).map(a=>a.name),o=Object.values(v().contributors).map(a=>a.name),i=e.modifier==="tag"?r:e.modifier==="assignee"?o:[];return e.inputString?i.length&&!i.includes(e.inputString.trim()??"")?O({message:ke({prefix:`existing ${e.modifier}s... `,wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i}):_():O({message:ke({prefix:"one of... ",wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i})},[g.NONE]:e=>{let t=q(g.NONE),n=/^[A-Za-z_]+:/g,r=e.inputString.match(n);return r&&r.length?t=[...t.filter(o=>o.trim().match(n))]:t=[...new Set(t.flatMap(o=>o.match(n)?.join("").replace(":","")??o))],e.command?_():O({message:ke({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[g.NEW]:e=>Oa({list:q(g.NEW),hint:ke({wordList:q(g.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[g.SET_DESCRIPTION]:()=>_(Y),[g.HELP]:()=>_(Y),[g.RENAME]:()=>{let e=Qn();return e.validity==="invalid"?e:_(Y)},[g.DELETE]:e=>{let t=Qn();return t.validity==="invalid"?t:er(e)},[g.CLOSE_ISSUE]:e=>er(e),[g.RE_OPEN_ISSUE]:e=>er(e),[g.MOVE]:e=>{let t=Qn();return t.validity==="invalid"?t:vt({hint:ke({prefix:"hey hacker! These commands are blocked for you... ",wordList:q(g.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[g.TAG]:e=>{let t=h.getExistingTags().map(n=>` ${Je.bgHex(ee(n))(" "+n+" ")} `).slice(0,10);return vt({hint:"tag name like... "+t.join("")})(e)},[g.UNTAG]:e=>{let t=en();if(d(t))return O({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${Je.bgHex(ee(r))(" "+r+" ")} `).slice(0,10);return n.length?vt({hint:" ... "+n.join("")})(e):O({message:"Issue has not tags",completionWordList:[]})},[g.ASSIGN]:e=>{let t=h.getExistingAssignees().map(n=>` ${Je.bgHex(ee(n))(" "+n+" ")} `).slice(0,10);return vt({hint:"assign to... "+t.join("")})(e)},[g.UNASSIGN]:e=>{let t=tn();if(d(t))return O({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${Je.bgHex(ee(r))(" "+r+" ")} `).slice(0,10);return n.length?vt({hint:"remove assignee... "+n.join("")})(e):O({message:"Issue has no assignees",completionWordList:[]})},[g.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=q(g.SET_EDITOR);return e.modifier?_(Y):O({message:ke({wordList:t,inputString:e.inputString})})},[g.SET_USERNAME]:e=>e.inputString?_():O({message:`Enter a username. Saved in ${Je.bgBlack("~/.epiq-global/")}`}),[g.SET_VIEW]:e=>Da({list:q(g.SET_VIEW),hint:ke({wordList:q(g.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[g.SYNC]:()=>_(Y)},Ho=Object.fromEntries(Object.entries(Ua).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Ko=["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 A={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",SetView:"set-view",SetEditor:"set-editor",SetUserName:"set-user-name",SetAutoSync:"set-auto-sync",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Sync:"sync",Export:"export"};var Vo=e=>Object.values(g).includes(e),qo=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:l,completionWordList:u}=Ho[n].validate(n,r,i),m=o==="command"?Object.values(g):n&&e.target==="modifier"?q(n):Ko;return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?Ao(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var zo=e=>{let t=e.trimStart(),n=_a(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),a=ja(e),l=Vo(r)?r:null,u=l!==null,m=r!=="",p=l?q(l)??[]:[],x=l&&p.includes(o)?o:"",E="word";n.length===0||n.length===1&&!i?E="command":(n.length===1&&i||n.length===2&&!i)&&(E="modifier");let I=i?"":a,R=Ba(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:E,inputToMatch:I,inputString:R}},Ba=(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},_a=e=>e.trim()?e.trim().split(/\s+/):[],ja=e=>e.trimEnd().split(/\s+/).at(-1)??"";var Go=" ",Ye={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:he.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},$a=new Set,Xo=()=>{for(let e of $a)e()};var Ee=e=>{let n=e(Ye),r=zo(n.value),o=n.cursorPosition===n.value.length;Ye={...n,commandMeta:qo(r,o)},Xo()},xt=({message:e,status:t})=>{let n=structuredClone(Ye);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Ye=n,Xo(),c(e,null)},tr=e=>{Ee(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},nr=e=>{Ee(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&n[o-1]===" ";)o--;for(;o>0&&n[o-1]!==" ";)o--}else{for(;o<n.length&&n[o]!==" ";)o++;for(;o<n.length&&n[o]===" ";)o++}return{...t,cursorPosition:o}})},Jo=()=>{Ee(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}})},Yo=()=>{Ee(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&t[r-1]===" ";)r--;for(;r>0&&t[r-1]!==" ";)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},W=e=>{Ee(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}})},Zo=()=>{Ee(e=>({...e,commandIsPending:!0}))},Qo=({addToHistory:e=!0})=>{Ee(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),Wa()},ei=()=>{Ee(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}})},ti=()=>{Ee(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Wa=()=>W(()=>""),oe=()=>Ye,sn=()=>{let[e,...t]=Ye.value.split(Go);return t.join(Go).trim()};var T={Sync:"sync",NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};var ni=e=>{let{context:t}=v()?.currentNode;if(!t)return A.None;switch(e){case g.EXIT:return A.Exit;case g.EXPORT:return A.Export;case g.INIT:return A.Init;case g.DELETE:return A.Delete;case g.SET_DESCRIPTION:return A.Edit;case g.HELP:return A.ViewHelp;case g.RE_OPEN_ISSUE:return A.ReopenIssue;case g.CLOSE_ISSUE:return A.CloseIssue;case g.TAG:return A.TagTicket;case g.UNTAG:return A.UntagTicket;case g.ASSIGN:return A.AssignUserToTicket;case g.UNASSIGN:return A.UnassignUserFromTicket;case g.RENAME:return A.Rename;case g.NEW:return A.NewItem;case g.FILTER:return A.Filter;case g.MOVE:return A.Move;case g.PEEK:return A.Peek;case g.SET_USERNAME:return A.SetUserName;case g.SET_EDITOR:return A.SetEditor;case g.SET_VIEW:return A.SetView;case g.SYNC:return A.Sync;default:return A.None}};import{ulid as U}from"ulid";import yi from"node:fs";import vd from"node:path";import yd from"react";import{Box as gd}from"ink";import gn from"react";import{Box as ir,Text as ed}from"ink";import pe from"react";import{Text as ri}from"ink";import oi,{useEffect as ii,useState as Ha}from"react";var si={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},ae=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=me(),r=si[n]??si.default,[o,i]=Ha(0);if(ii(()=>{i(0)},[r]),ii(()=>{if(!e)return;let l=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return oi.createElement(ri,null,t);let a=r[o]??r[0]??t;return oi.createElement(ri,{color:M.accent,dimColor:o===1},a)};import{Box as rr,Text as Ka}from"ink";import an from"react";var dn=({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,E=e.slice(p,x),I=e.length>l,R=i,b=I?Math.max(1,Math.floor(l/e.length*R)):R,N=Math.max(0,R-b),w=Math.max(1,e.length-l),j=I?Math.floor(p/w*N):0;return an.createElement(rr,{flexDirection:"row",height:i,width:"100%"},an.createElement(rr,{flexDirection:"column",flexGrow:1,height:i},E),an.createElement(rr,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((Re,te)=>an.createElement(Ka,{key:te,color:I&&te>=j&&te<j+b?M.accent:M.secondary},I?"\u2502":" "))))};import{Box as un,Text as Ya}from"ink";import _e from"react";import{Text as Va}from"ink";import qa from"react";var za=e=>e.toLowerCase().trim(),Ga=(e,t=Xe)=>{let n=za(e);return t[n]?t[n]:ft(n)},cn=({id:e,isSelected:t})=>{let n=h.getContributor(e);if(n)return qa.createElement(Va,{underline:t,color:Ga(n.name)},"@"+n.name)};import{Text as Xa}from"ink";import Ja from"react";var ln=({id:e,isSelected:t})=>{let n=h.getTag(e);if(n)return Ja.createElement(Xa,{underline:t,backgroundColor:ee(n.name),color:M.primary}," "+n.name+" ")};var ai=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=Yt(ze(t.title),r),i=qn(t),a=zn(t);return _e.createElement(un,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?M.accent:M.secondary,justifyContent:"space-between"},_e.createElement(un,{borderBottom:!0},_e.createElement(un,{paddingLeft:1,flexDirection:"column"},_e.createElement(Ya,{color:M.primary},o))),_e.createElement(un,{flexDirection:"row",paddingLeft:1},i.map(l=>_e.createElement(ln,{key:l.id,id:l.id})),a.map(l=>_e.createElement(cn,{key:l.id,id:l.id}))))};import Za from"chalk";import{Box as ht,Text as or}from"ink";import Ne from"react";var Qa=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,di=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=S(t.id),a=b=>{let N=i.find(w=>w.title===b);return N?S(N.id).map(w=>typeof w.props?.value=="string"?w.props.value:"").filter(w=>!!w):[]},l=a("Tags").map(b=>h.getTag(b)).filter(b=>!!b),u=a("Assignees").map(b=>h.getContributor(b)).filter(b=>!!b),m=1,p=l.length*(1+m),x=u.length*(2+m),E=l.map(b=>Ne.createElement(ht,{key:b.id,paddingRight:m},Ne.createElement(or,{color:ee(b.name)},"\u25A0"))),I=u.map(b=>Ne.createElement(ht,{key:b.id,paddingRight:m},Ne.createElement(or,{color:ft(b.name)},"@"+b.name.at(0)))),R=n?M.accent:o===f.MOVE?M.secondary:M.primary;return Ne.createElement(ht,{borderBottom:!0,justifyContent:"space-between"},Ne.createElement(ht,null,Ne.createElement(ae,{isSelected:n,placeholder:Za.dim.gray(r+1+" ")}),Ne.createElement(or,{wrap:"truncate",color:R},Qa(t.title,e-p-x-14))),Ne.createElement(ht,null,E,I))};var td=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:a,mode:l})=>{let{renderedChildrenIndex:u}=me(),m=u[e.id]??[],p=`${e.title} (${m.length})`,x=3,E=o?1:4,I=r-x-(o?2:1),R=pe.createElement(ir,{borderStyle:"round",borderColor:M.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},pe.createElement(ae,{isSelected:t}),pe.createElement(ed,{bold:!0,color:t?M.accent:M.primary},p," ",e.readonly?"\u{1F512}":"")),b=(N,w)=>{let j=i&&a===w;return o?pe.createElement(di,{key:N.id,index:w,width:n,ticket:N,isSelected:j,mode:l}):pe.createElement(ai,{key:N.id,width:n,ticket:N,isSelected:j})};return pe.createElement(ir,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?M.accent:M.secondary,paddingRight:1,paddingLeft:1,height:r},R,pe.createElement(ir,{padding:o?1:0},m.length>0&&pe.createElement(dn,{selectedIndex:a,height:I,itemHeight:E},m.map(b)),pe.createElement(ae,{isSelected:i&&a===-1})))},ci=pe.memo(td);import{Box as dr,Text as md}from"ink";import Pe,{useEffect as cr,useMemo as pi}from"react";import je from"chalk";import li from"string-width";import{decodeTime as nd}from"ulid";var rd=(e,t)=>e+" ".repeat(Math.max(0,t-li(e))),od=(e,t)=>" ".repeat(Math.max(0,t-li(e)))+e,id=e=>(()=>{let n={"add.issue":"Created with title","assign.issue":"Assigned to","unassign.issue":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","tag.issue":"Tagged with","untag.issue":"Removed tag","lock.node":"Locked node","move.node":"Moved issue"};return(o=>n[o]??(o.endsWith("e")?`${o}d`:`${o}ed`))(e)})(),sd=e=>{switch(e.action){case"move.node":{let t=h.getNode(e.payload.parent);return`to ${t?je.dim.bgBlack(` ${t.title} `):"unknown"} with rank ${e.payload.rank}`}case"tag.issue":{let t=v().tags[e.payload.tagId];return t?je.bgHex(ee(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=v().tags[e.payload.tagId];return t?je.bgHex(ee(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=v().contributors[e.payload.contributor];return t?je.hex(ee(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=v().contributors[e.payload.contributor];return t?je.hex(ee(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""}},ad=e=>{let t=_o(nd(e));return je.gray(od(t,8))},dd=12,cd=e=>rd(`${e}`,dd),ui=e=>{let t=ad(e.id),n=cd(e.userName),r=id(e.action),o=sd(e),i=je.dim("\u203A"),a=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${a}`};import{Box as mn,Text as ld}from"ink";import Ie from"react";var mi=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=me(),{title:o}=t,i=S(t.id).map(a=>{let l=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return h.getContributor(l)?.id;if(o==="Tags")return h.getTag(l)?.id}).filter(a=>!!a);return Ie.createElement(mn,{alignItems:"center",paddingTop:1},Ie.createElement(mn,{minWidth:12},Ie.createElement(ae,{isSelected:n}),Ie.createElement(ld,{color:n?M.accent:M.secondary2},o,":")),Ie.createElement(mn,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,l)=>{let u=r.id===t.id&&l===e;return Ie.createElement(mn,{key:`${o}-${a}`,paddingRight:2,minHeight:1},Ie.createElement(ae,{isSelected:u}),o==="Assignees"?Ie.createElement(cn,{isSelected:u,id:a}):o==="Tags"?Ie.createElement(ln,{isSelected:u,id:a}):null)})))};import{Box as pn,Text as sr}from"ink";import Ce,{useEffect as ud}from"react";var ar=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:l}=me(),u=E=>String(E).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];ud(()=>{let E=[];return m.forEach((I,R)=>{let b=ye(BigInt(R+1));if(!Ze(b))return;let N=z.text({id:`${e}-${R}`,name:`Line ${R+1}`,parentNodeId:e,rank:b.value,props:{value:I},readonly:!0}),w=h.createNode(N);Ze(w)&&E.push(w.value.id)}),()=>E.forEach(h.deleteNode)},[e,n]);let p="\u2029",x=m.map((E,I)=>{let R=l.id===e&&a===I;return Ce.createElement(pn,{key:`${e}-${I}`},Ce.createElement(sr,{color:R?M.primary:M.secondary2,dimColor:!R},`${I+1} `.padStart(5,"\xA0")),Ce.createElement(sr,{backgroundColor:R?"gray":""},u(E.length?Yt(E,i-10):p)))});return Ce.createElement(pn,{flexDirection:"column",paddingTop:1},Ce.createElement(pn,null,Ce.createElement(ae,{isSelected:o}),Ce.createElement(sr,{color:o?M.accent:M.secondary2},t)),Ce.createElement(pn,{flexDirection:"row",borderStyle:"round",borderColor:M.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Ce.createElement(dn,{scrollByOne:!0,children:x,height:r-2,selectedIndex:a,itemHeight:1})))};var pd=e=>`${e}::log`,gi=e=>e==="Assignees"||e==="Tags",fi=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=me(),o=process.stdout.columns||120,i=pi(()=>pd(e.id),[e.id]),a=pi(()=>[...e.log].reverse().map(ui).join(`
45
- `),[e.log]);cr(()=>{if(h.getNode(i))return;let w=ye(1n);if(d(w))return;let j={...z.field(i,"Log",e.id,w.value,{value:a}),readonly:!0,childRenderAxis:"vertical"};return h.createNode(j),()=>{h.deleteNode(i)}},[i,e.id,a]),cr(()=>{let N=h.getNode(i);N&&N.props.value!==a&&h.updateNode({...N,props:{...N.props,value:a},childRenderAxis:"vertical",readonly:!0})},[i,a]);let l=r.id===e.id,u=r.id===i||r.parentNodeId===i;cr(()=>{u&&(n>=0||L.navigate({selectedIndex:0}))},[u,n]);let m=S(e.id);if(u){let N=h.getNode(i),j=t-3;return Pe.createElement(dr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},N?Pe.createElement(ar,{id:N.id,label:"Event log",text:N.props.value??"",selected:!1,maxWidth:o,height:j}):null)}let p=m.reduce((N,w)=>gi(w.title)||w.id===i?N+1:N,0),x=2,E=p*1,R=t-3-E-x,b=(N,w)=>gi(N.title)?Pe.createElement(mi,{key:N.id,parent:N,selected:w,selectedIndex:n}):N.id===i?Pe.createElement(dr,{key:N.id,paddingTop:1},Pe.createElement(ae,{isSelected:w}),Pe.createElement(md,{backgroundColor:M.secondary,color:w?M.accent:M.primary}," History \u203A\u203A ")):N.title==="Description"?Pe.createElement(ar,{label:"Description (press e to edit)",key:N.id,id:N.id,text:N.props.value??"",selected:w,maxWidth:o,height:R}):null;return Pe.createElement(dr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((N,w)=>b(N,l&&n===w)))};var fd=({swimlanes:e,currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:a,width:l})=>{let u=t.context,m=u===k.TICKET||u===k.FIELD_LIST||u===k.FIELD,p=u===k.BOARD||u===k.SWIMLANE,x=u===k.TICKET?t:r.find(N=>N.context===k.TICKET),E=Math.floor(l/3),I=Math.floor(l/Math.max(e.length,1)),R=Math.min(I,E),b=i==="dense";return gn.createElement(gd,{flexDirection:"row",height:a},p&&e.map((N,w)=>{let j=t.id===N.id,Re=j?n:-1,te=t.context===k.BOARD&&n===w;return gn.createElement(ci,{key:N.id,height:a,width:R,swimlane:N,isSelected:te,isDense:b,isFocused:j,listSelectedIndex:Re,mode:o})}),m&&x&&gn.createElement(fi,{height:a,ticket:x}))},vi=gn.memo(fd);import{render as xd}from"ink";import{Writable as hd}from"node:stream";var Et=e=>String(e).padStart(2,"0"),Ed=e=>{let t=e.getUTCFullYear(),n=Et(e.getUTCMonth()+1),r=Et(e.getUTCDate()),o=Et(e.getUTCHours()),i=Et(e.getUTCMinutes()),a=Et(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${a}`},Nd=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Id=async(e,{width:t,height:n})=>{let r="",o=new hd({write(a,l,u){let m=Cd(a.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=xd(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(a=>setTimeout(a,0)),i.unmount(),r},Cd=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),xi=async()=>{let{currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:r,mode:o,renderedChildrenIndex:i}=v(),a=n.find(w=>w.context==="BOARD");if(!a)return s("No board found to export");let l=120,u=40,m=await Id(yd.createElement(vi,{height:u,width:l,swimlanes:(i[a.id]??[]).filter(w=>w!==void 0&&Xt(w)),currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:r,mode:o}),{width:l,height:u});if(!m)return s("Failed to render board export");let p=ce(process.cwd());if(d(p))return s("Unable to export, epiq root not found");let x=new Date,E=Ed(x),I=`board_${Nd(a.title)}_${E}.md`,R=br(p.value);yi.mkdirSync(R,{recursive:!0});let b=vd.join(R,I),N=`# Board - ${a.title}
2
+ import{McpServer as Rc}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Ac}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as F}from"zod";var Me={None:"none",Success:"success",Fail:"fail"},s=e=>({status:Me.Fail,message:e,value:null}),c=(e,t)=>({status:Me.Success,message:e,value:t}),a=e=>e.status==="fail",ct=e=>e.status==="success";import{ulid as hs}from"ulid";import Ic from"node:fs";import{useSyncExternalStore as yc}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function Mn(e){return e.context==="WORKSPACE"}function ne(e){return e.context==="TICKET"}function Lr(e){return e.context==="FIELD"}var kt=e=>e.context==="SWIMLANE",Or=e=>e.context==="BOARD";var g={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function Ft(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Dt=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Xe=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var Ur=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},Br=(e,t)=>t?e.get(t)??[]:[];var _r=new WeakMap,ks=e=>{let t=_r.get(e);return t||(t=Ur(e),_r.set(e,t)),t};var $r=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Br(ks(e),r).filter(i=>Ft(r,i)>=n)};var Fs={hint:"",hints:[],overlap:0,remainder:""},Wr=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Fs;let o=$r({wordList:r,inputToMatch:e,overlapThreshold:1});return Ds(t,o)},Ds=(e,t)=>{let n=t[0]??"",r=Ft(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),d=r<(o??"").length,l=!!i,p=(l&&d?o:n)+(l&&d?":":" "),x=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:x}};import qs from"node:fs";import Vs from"node:path";import{decodeTime as zs,monotonicFactory as Gs}from"ulid";import{z as pt}from"zod";var Lt={autoSyncIntervalMs:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},_=()=>Lt,ge=e=>(Lt={...Lt,...e},Lt);import lt from"node:fs";import he from"node:path";var Pn=process.env.IS_LOCAL==="true",Ie=".epiq",de=".epiq-global",Ot="events",Ls="project.json",jr=e=>he.join(e,Ie),Ut=e=>he.join(e,Ie),Bt=e=>he.join(Ut(e),Ls),ut=e=>he.join(Ut(e),Ot),Os=e=>{let t=he.join(e,Ie);return lt.existsSync(t)&&lt.statSync(t).isDirectory()},kn=e=>{let t=Bt(e);return lt.existsSync(t)&&lt.statSync(t).isFile()},fe=e=>{let t=he.resolve(e);for(;;){if(Os(t))return c("Resolved closest .epiq root",t);let n=he.dirname(t);if(n===t)return s("No .epiq directory found in any parent");t=n}},Pe=e=>{let t=he.resolve(e);for(;;){if(kn(t))return c("Resolved closest epiq project root",t);let n=he.dirname(t);if(n===t)return s("No .epiq/project.json found in any parent");t=n}},Hr=e=>{let t=ut(e);try{return lt.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")}};import _t from"node:fs";import Dn from"node:path";import{decodeTime as Us}from"ulid";import{z as Fn}from"zod";var Bs=Fn.object({userId:Fn.string().min(1).default("unknown"),userName:Fn.string().min(1).default("unknown")}),_s=e=>{let[t,n]=Dn.basename(e,".jsonl").split("."),r=Bs.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):s(`Invalid event file name ${Dn.basename(e)}: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},$s=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?s(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?s("Invalid persisted event: action key is missing or invalid"):c("Resolved persisted action",t[0])},Ws=(e,t)=>t in e,js=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Hs=e=>{let{userId:t,userName:n,...r}=e,o=$s(r);if(a(o))return s(o.message);let i=o.value,d=e.id?.[0];return d?Ws(r,i)?c("Decoded persisted event",js({id:d,action:i,payload:r[i],userId:t,userName:n})):s(`Persisted event is missing payload for action: ${i}`):s("Persisted event is missing id")},$t=e=>{if(!_t.existsSync(e))return c("Event file missing",[]);let t=_s(e);if(a(t))return s(t.message);let n=_t.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
3
+ `)){let i=o.trim();if(!i)continue;let d;try{d=JSON.parse(i)}catch{return s(`Failed to parse event JSON from ${e}: ${i}`)}let l=Ln(d);if(a(l))return s(`${l.message} in ${e}: ${i}`);r.push({...l.value,userId:t.value.userId,userName:t.value.userName})}return c("Parsed persisted events file",r)};function Kr(e){let t=ut(e);if(!_t.existsSync(t))return c("No events found",[]);let n=_t.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Dn.join(t,o)),r=[];for(let o of n){let i=$t(o);if(a(i))return s(i.message);r.push(...i.value)}return c("All events loaded",Ks(r))}function mt(e){let t=Kr(e);if(a(t))return s(t.message);let n=[];for(let r of t.value){let o=Hs(r);if(a(o))return s(`Failed to decode event ${r.id?.[0]??"<unknown>"}: ${o.message}`);n.push(o.value)}return c("Loaded merged events",n)}function qr(e=process.cwd()){let t=Kr(e);return a(t)?s(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Ks=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],x=m.id[1]??null;t.set(p,m);let h=n.get(x)??[];h.push(m),n.set(x,h)}for(let m of n.values())m.sort((p,x)=>p.id[0].localeCompare(x.id[0]));let r=[],o=new Set,i=m=>{let p=m.id[0];if(o.has(p))return;r.push(m),o.add(p);let x=n.get(p)??[];for(let h of x)i(h)},d=n.get(null)??[];for(let m of d)i(m);let l=e.filter(m=>{let p=m.id[0],x=m.id[1]??null;return!o.has(p)&&x!==null&&!t.has(x)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of l)i(m);let u=e.filter(m=>!o.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)i(m);return r},Vr=(e,t)=>{let n=e.findIndex(r=>{try{return Us(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var zr=e=>({action:e.action,payload:e.payload});var Yr=1,Gr=Gs(),Ys=pt.tuple([pt.string().min(1),pt.string().min(1).nullable()]),Xs=pt.looseObject({v:pt.literal(Yr),id:Ys}),Ln=e=>{let t=Xs.safeParse(e);return t.success?c("Parsed persisted event",t.data):s(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Wt=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",q=()=>{let{userName:e,userId:t}=_();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:Wt(t),userName:Wt(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},Ee=({userId:e,userName:t})=>`${Wt(e)}.${Wt(t)}.jsonl`,Js=(e,{userId:t,userName:n})=>{let r=Ee({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return s(`Invalid event log file name: ${r}`);let i=Vs.join(ut(e),r);return c("Successfully resolved event log path",i)},Zs=(e,t)=>{let n={[e.action]:e.payload,v:Yr,id:t};return Ln(n)};function jt({event:e,rootDir:t=process.cwd()}){try{let n=fe(t);if(a(n))return n;let r=Hr(n.value);if(a(r))return r;let o=Js(n.value,{userId:e.userId,userName:e.userName});if(a(o))return o;let i=qr(n.value);if(a(i))return s(i.message);let d=i.value?Gr(Math.max(Date.now(),zs(i.value)+1)):Gr(),l=Zs(zr(e),[d,i.value]);return a(l)?s(l.message):(qs.appendFileSync(o.value,`${JSON.stringify(l.value)}
4
+ `,"utf8"),c("Event persisted",{path:o.value,entry:l.value}))}catch(n){let r=n instanceof Error?n.message:"Unknown persist error";return s(`Failed to persist event: ${r}`)}}var Je=3e3,Xr=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Je?null:t},Jr=0,On,Un=!1,gt=!1,Bn=()=>Un||f().syncStatus.status==="syncing",Qs=()=>{let e=_().autoSyncIntervalMs??15e3,t=Date.now()-Jr;return Math.max(0,e-t)},Zr=()=>{On||(On=setTimeout(async()=>{if(On=void 0,Bn()){gt=!0;return}gt=!1,await ea()},Qs()))},ea=async()=>{if(Bn())return gt=!0,s("Sync already in progress");let e=q();if(a(e)||!e.value)return s("Unable to resolve event log path");Un=!0,Jr=Date.now();try{let t=Ee(e.value);return await Ze({ownEventFileName:t})}finally{Un=!1,gt&&Zr()}},Qr=()=>{gt=!0,!Bn()&&Zr()};import ft from"node:fs";import{ulid as ta}from"ulid";import{z as Ht}from"zod";var na="epiq/eventlog",ra=Ht.object({projectId:Ht.string().min(1),stateBranch:Ht.string().min(1),createdAt:Ht.iso.datetime()}),eo=()=>({projectId:ta(),stateBranch:na,createdAt:new Date().toISOString()}),ke=e=>{let t=Bt(e);if(!ft.existsSync(t))return s("Missing .epiq/project.json");try{let n=ft.readFileSync(t,"utf8"),r=JSON.parse(n),o=ra.safeParse(r);return o.success?c("Read project.json",o.data):s(`Invalid .epiq/project.json: ${o.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(", ")}`)}catch(n){return s(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},to=e=>{let t=ke(e);return a(t)?s(t.message):c("Read projectId",t.value.projectId)},no=({repoRoot:e,fileContents:t})=>{let n=Ut(e),r=Bt(e);try{if(ft.mkdirSync(n,{recursive:!0}),ft.existsSync(r)){let o=ke(e);return a(o)?s(o.message):c("Project already initialized",null)}return ft.writeFileSync(r,JSON.stringify(t,null,2)+`
5
+ `,"utf8"),c("Created project.json",null)}catch(o){return s(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var Kt=()=>{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}},ro=()=>{let e=Pe(process.cwd());if(a(e))return s("Unable to determine if repository is initialized");let t=ke(e.value);return ct(t)},oo=e=>e===!0?"yes":e===!1?"no":null,io=e=>e==="yes"?!0:e==="no"?!1:null;var J={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:P.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:i="horizontal",isVirtual:d=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.FIELD,childRenderAxis:i,parentNodeId:n,readonly:!1,log:[],isVirtual:d}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:P.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:i=!0,isVirtual:d=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:P.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:i,log:[],isVirtual:d})};import{ulid as sa}from"ulid";var $e=24n,oa=$e*4n,We=(1n<<oa)-1n,ia=/^[0-9a-f]+$/;function so(e){return!e||!ia.test(e)?s(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function Ce(e,t=$e){if(e<0n)return s("Negative rank not allowed");let n=e.toString(16);return c("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function z(e,t){if(!e&&!t)return Ce(We/2n,$e);let n=e?so(e):c("Resolved lower bound",0n);if(a(n))return n;let r=t?so(t):c("Resolved upper bound",We);if(a(r))return r;let o=n.value,i=r.value;if(i<=o)return Ce(We/2n,$e);let d=(o+i)/2n;return d===o||d===i?s("No rank space available between neighbors"):Ce(d,$e)}function ao(){return Ce(We/2n,$e)}function co(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=We*BigInt(r+1)/(t+1n),i=Ce(o,$e);if(a(i))return i;n.push(i.value)}return c("Resolved evenly spaced ranks",n)}var _n=(e,t)=>{let n=$(e),r=co(n.length);if(a(r))return r;let o={};for(let i=0;i<n.length;i++){let d=n[i],l=r.value[i];if(!d||!l)return s("Unable to assign rebalance rank");o[d.id]=l}return c("Created rebalance event",{id:sa(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var G={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History"};var aa=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[te,qt]=aa;var k=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),da={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=J.workspace(t,n,r),i=xt(o);if(a(i))return k(i.message,e);let d=N.createNode(o);return a(d)?k(d.message??"Failed to initialize workspace",e):Mn(d.value)?c("Workspace initialized",{action:e.action,result:d.value}):s("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=J.workspace(t,n,r),i=N.createNode(o);return a(i)?k(i.message??"Failed to add workspace",e):Mn(i.value)?c("Added workspace",{action:e.action,result:i.value}):s("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,i=N.createNode(J.board(t,n,r,o));return a(i)?k(i.message??"Unable to create board",e):Or(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=N.createNode(J.swimlane(t,n,r,o));return a(i)?k(i.message??"Unable to create swimlane",e):kt(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=N.createNode(J.ticket(t,n,r,o));return a(i)?k(i.message??"Unable to create issue",e):ne(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,d=N.createNode(J.field({id:t,name:n,parentNodeId:r,rank:i,props:{value:o},childRenderAxis:n.includes(G.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?k(d.message??`Unable to create field: ${n}`,e):Lr(d.value)?c("Added field",{action:e.action,result:d.value}):s("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!N.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=N.renameNode(t,n);return a(o)?k(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=N.tombstoneNode(t);return a(n)?k(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=N.createTag({id:t,name:n});return a(r)?k(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=N.createContributor({id:t,name:n});return a(r)?k(r.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:r.value})},"tag.issue":e=>{let{id:t,target:n,tagId:r,rank:o}=e.payload,i=N.tag(n,r,t,o);return a(i)?k(i.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:i.value})},"untag.issue":e=>{let{target:t,tagId:n}=e.payload,r=N.untag(t,n);return a(r)?k(r.message??"Unable to untag ",e):c("Issue untagged",{action:e.action,result:r.value})},"assign.issue":e=>{let{id:t,contributor:n,target:r,rank:o}=e.payload,i=N.assign(r,n,t,o);return a(i)?k(i.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:i.value})},"unassign.issue":e=>{let{target:t,contributor:n}=e.payload,r=N.unassign(t,n);return a(r)?k(r.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:r.value})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?k(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=N.editValue(t,n);return a(r)?k(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=N.getNode(t);if(!o)return k("Unable to locate issue",e);if(!ne(o))return k("Can only close issues",e);let i=N.getNode(te);if(!i)return k("Unable to locate target swimlane",e);if(n!==i.id)return k("Close target must be closed swimlane",e);let d=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(d)?k(d.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=N.getNode(t);if(!o)return k("Unable to locate issue",e);if(!ne(o))return k("Can only reopen issues",e);let i=N.getNode(te);if(!i)return k("Unable to locate closed swimlane",e);if(n===i.id)return k("Cannot reopen issue into closed swimlane",e);if(!N.getNode(n))return k("Reopen parent no longer exists",e);let l=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(l)?k(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=N.lockNode(t);return a(n)?k(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=N.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 d=N.updateNode({...i,rank:o});if(a(d))return k(d.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})}},ca=(e,t)=>{let n=N.getNode(e);n&&N.updateNode({...n,log:[...n.log??[],t]})},la=e=>{switch(e.action){case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"delete.node":case"move.node":case"close.issue":case"reopen.issue":return[e.payload.id];case"edit.description":let t=[e.payload.id],n=f().nodes[e.payload.id]?.parentNodeId;return n&&t.push(n),t;case"tag.issue":case"untag.issue":case"assign.issue":case"unassign.issue":return[e.payload.id,e.payload.target];case"create.tag":case"create.contributor":default:return[]}};function vt(e,t=!1){let n=da[e.action](e);if(a(n))return n;t||([...new Set(la(e))].forEach(d=>ca(d,e)),ce(d=>({...d,eventLog:[...d.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?k("Invalid user ID format",e):(N.createContributor({name:o,id:r}),n)}var yt=e=>e.map(t=>vt(t));function W(e){let t=vt(e);if(t.status!==Me.Success)return t;let n=jt({event:e});return a(n)?n:t}function Fe(e){return e.map(t=>W(t))}var lo=e=>$n($(e),{at:"end"}),$n=(e,t={at:"end"})=>{let n=r=>a(r)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(z(void 0,void 0));switch(t.at){case"start":{let r=e[0];return r?n(z(void 0,r.rank)):s("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(z(r.rank,void 0)):s("Unable to resolve last sibling")}case"before":{let r=uo(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(z(o?.rank,i.rank)):s("Sibling not found")}case"after":{let r=uo(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(z(o.rank,i?.rank)):s("Sibling not found")}}},$=e=>Object.values(f().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),uo=(e,t)=>e.findIndex(n=>n.id===t),mo=(e,t,n={at:"end"})=>$n($(t).filter(r=>r.id!==e),n),ye=(e,t,n,r)=>{let o=mo(t,e,n);if(a(o))return o;if(!o.value.needsRebalance)return c("Resolved rank",o.value.rank);let i=_n(e,r);if(a(i))return i;let d=W(i.value);if(a(d))return d;let l=mo(t,e,n);return a(l)?l:l.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",l.value.rank)},De=(e,t)=>{let n=lo(e);if(a(n))return n;if(!n.value.needsRebalance)return c("Resolved rank",n.value.rank);let r=_n(e,t);if(a(r))return r;let o=W(r.value);if(a(o))return o;let i=lo(e);return a(i)?i:i.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",i.value.rank)};var Qe=(e,t)=>{let{nodes:n}=f(),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}`)},ua=(e,t)=>{let{nodes:n}=f(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Wn=(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"),N={deleteNode(e){ce(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},editValue(e,t){let{nodes:n}=f(),r=n[e];if(!r)return s("Edit target node not found");let o=Wn(r,"edit");if(o)return o;let i={...r,props:{...r.props,value: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=Wn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return $(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=f(),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 d=Wn(o,"move");if(d)return d;if(ua(t,e))return s("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,currentNodeId:n,rootNodeId:r}=f(),o=this.getNode(e);if(!o)return s("Node not found");if(r===e)return s("Cannot delete root node");let i=new Set,d=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let p of $(m.id))d(p.id)}};d(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?(I({nodes:l}),c("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=ce(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?s("Unable to create contributor"):c("Created contributor",e)},assign(e,t,n,r){let o=this.getContributor(t),i=this.getNode(e);if(!i||!o)return s("Unable assign contributor to issue");let d=this.getFieldByTitle(i.id,"Assignees");if(!d)return s("Unable to locate assignees field");if($(d.id).some(p=>p.props?.value===t))return s("Contributor already assigned");let u=J.field({id:n,name:o.name,parentNodeId:d.id,rank:r,props:{value:t}}),m=this.createNode(u);return a(m)?m:c("Assigned contributor",u)},createTag(e){let t=ce(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?s("Could not create tag"):c("Tag created",e)},tag(e,t,n,r){let o=this.getTag(t),i=this.getNode(e);if(!o)return s("Unable to add tag, missing tag");if(!i)return s("Unable to add tag, missing target");let d=this.getFieldByTitle(i.id,"Tags");if(!d)return s("Unable to locate tags field");if($(d.id).some(p=>p.props?.value===t))return s("Tag already assigned");let u=J.field({id:n,name:o.name,parentNodeId:d.id,rank:r,props:{value:t}}),m=this.createNode(u);return a(m)?m:c("Tag added",u)},untag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return s("Unable to remove tag, missing tag");if(!r)return s("Unable to remove tag, missing target");let o=this.getFieldByTitle(r.id,"Tags");if(!o)return s("Unable to locate tags field");let i=$(o.id).find(l=>l.props?.value===t);if(!i)return c("Issue is not tagged with that tag",null);let d={...i,isDeleted:!0};return this.updateNode(d),c("Tag removed",d)},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return s("Unable to unassign, missing contributor");if(!r)return s("Unable to unassign, missing target");let o=this.getFieldByTitle(r.id,"Assignees");if(!o)return s("Unable to locate assignees field");let i=$(o.id).find(l=>l.props?.value===t);if(!i)return c("Issue is not assigned to that contributor",null);let d={...i,isDeleted:!0};return this.updateNode(d),c("Assignee removed",d)},createNode(e){let t=ce(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(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=ce(o=>({...o,nodes:{...o.nodes,[e]:n}}));return a(r)?s(r.message):c("Locked node",n)},updateNode(e){let t=ce(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?t:c("Updated node",e)},getContributor(e){return f().contributors[e]},getTag(e){return f().tags[e]},getNode(e){return f().nodes[e]},getSiblings(e){return $(e)}};var Z={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"},M={accent:Z.cyan,accent2:Z.magenta,primary:Z.white,secondary:Z.grayDark,secondary2:Z.grayLight,gray:Z.gray,green:Z.green,yellow:Z.yellow,red:Z.red};var y={red:Z.red,yellow:Z.yellow,green:Z.green,blue:Z.blue,magenta:Z.magenta,cyan:Z.cyan},et={urgent:y.red,critical:y.red,important:y.red,blocker:y.red,asap:y.red,immediate:y.red,fail:y.red,failure:y.red,broken:y.red,bug:y.red,error:y.red,incident:y.red,outage:y.red,production:y.red,crash:y.red,security:y.red,warning:y.yellow,warn:y.yellow,risky:y.yellow,risk:y.yellow,attention:y.yellow,pending:y.yellow,review:y.yellow,"needs-review":y.yellow,qa:y.yellow,testing:y.yellow,test:y.yellow,validate:y.yellow,verification:y.yellow,staging:y.yellow,check:y.yellow,"follow-up":y.yellow,followup:y.yellow,waiting:y.yellow,blocked:y.yellow,hold:y.yellow,done:y.green,complete:y.green,completed:y.green,success:y.green,ok:y.green,stable:y.green,resolved:y.green,fixed:y.green,closed:y.green,merged:y.green,released:y.green,deployed:y.green,approved:y.green,verified:y.green,working:y.green,healthy:y.green,pass:y.green,passing:y.green,info:y.blue,information:y.blue,note:y.blue,docs:y.blue,documentation:y.blue,doc:y.blue,guide:y.blue,help:y.blue,explanation:y.blue,detail:y.blue,details:y.blue,context:y.blue,design:y.blue,discussion:y.blue,proposal:y.blue,idea:y.blue,feature:y.magenta,enhancement:y.magenta,improvement:y.magenta,refactor:y.magenta,refactoring:y.magenta,cleanup:y.magenta,optimize:y.magenta,optimization:y.magenta,perf:y.magenta,performance:y.magenta,upgrade:y.magenta,migration:y.magenta,modernize:y.magenta,debt:y.magenta,todo:y.cyan,next:y.cyan,planned:y.cyan,plan:y.cyan,future:y.cyan,backlog:y.cyan,investigate:y.cyan,explore:y.cyan,prototype:y.cyan};var po=(e,t)=>{let r=b(e.id).find(o=>o.title===t);return r?b(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},jn=e=>po(e,"Tags").map(t=>N.getTag(t)).filter(t=>!!t),Vt=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ne(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",jn(n)??[])},zt=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ne(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Hn(n)??[])},Hn=e=>po(e,"Assignees").map(t=>N.getContributor(t)).filter(t=>!!t);var go=(e,t)=>{let r=b(e.id).find(o=>o.title===t);return r&&typeof r.props?.value=="string"?Xe(r.props.value):""};var v={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 ma=/^(\d+)(h|d|w|mo|y)$/,pa=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,ga=({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},fa=(e,t=new Date)=>{let n=e.match(ma);if(!n)return null;let[,r,o]=n,i=Number(r);if(!Number.isInteger(i)||i<=0)return null;let d=new Date(t);switch(o){case"h":return d.setHours(d.getHours()-i),d;case"d":return d.setDate(d.getDate()-i),d;case"w":return d.setDate(d.getDate()-i*7),d;case"mo":return d.setMonth(d.getMonth()-i),d;case"y":return d.setFullYear(d.getFullYear()-i),d;default:return null}},va=e=>{let t=e.match(pa);if(!t)return null;let[,n,r,o,i,d]=t,l=Number(n),u=Number(r),m=Number(o),p=i?Number(i):0,x=d?Number(d):0;return ga({year:l,month:u,day:m,hour:p,minute:x})?new Date(l,u-1,m,p,x):null},Gt=e=>{let t=e.trim().toLowerCase();return fa(t)??va(t)},fo=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,ya=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],vo=(e=ya)=>{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 xa=["BOARD","TICKET","SWIMLANE"],Y={EDITOR:"editor",VIEW:"view",USERNAME:"userName",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs"},Le={TITLE:"title",DESCRIPTION:"description"},Na=[Y.EDITOR,Y.VIEW,Y.USERNAME,Y.AUTOSYNC,Y.SYNC_DEBOUNCE_MS],ha=[Le.TITLE,Le.DESCRIPTION],qn=[String(Je),"5000","15000","30000","60000"],je=[v.SYNC,v.HELP,v.EXPORT,v.CONFIG],Yt=[v.NEW,v.EDIT,v.DELETE,v.MOVE],Kn=[v.TAG,v.UNTAG,v.ASSIGN,v.UNASSIGN,v.CLOSE_ISSUE,v.RE_OPEN_ISSUE,v.EDIT],yo=[v.FILTER,v.PEEK],Ia={WORKSPACE:[...je,...Yt],BOARD:[...yo,...je,...Yt],SWIMLANE:[...yo,...je,...Yt],TICKET:[...je,...Yt,...Kn],FIELD:[...je,...Kn],FIELD_LIST:[...je,...Kn],TEXT:[...je]},Ea=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Ca=()=>{let{selectedNode:e,readOnly:t,breadCrumb:n}=f(),{isSetupDone:r}=Kt();if(!r)return[v.HELP,v.CONFIG];if(!ro())return[v.HELP,v.INIT];if(t)return[v.HELP,v.PEEK,v.EXPORT,v.CONFIG];let o=e?.context,i=o&&xa.includes(o);return[...new Set([...n,e].map(l=>l?.context).flatMap(l=>l?Ia[l]:[]))].filter(l=>l===v.MOVE?!1:l===v.EDIT||l===v.DELETE?i:!0)},Q=e=>{let{currentNode:t}=f(),n=t.context??"WORKSPACE";return{[v.NONE]:Ca(),[v.EXIT]:["confirm"],[v.EXPORT]:[],[v.SYNC]:[],[v.INIT]:[],[v.HELP]:[],[v.PEEK]:[...vo(),"now","prev","next"],[v.EDIT]:[...ha],[v.DELETE]:["confirm"],[v.RE_OPEN_ISSUE]:["confirm"],[v.CLOSE_ISSUE]:["confirm"],[v.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[v.FILTER]:["tag","assignee","description","title","clear"],[v.TAG]:[...new Set([...Object.keys(et),...N.getExistingTags()])],[v.UNTAG]:[...Vt()?.value?.map(({name:o})=>o)??[]],[v.UNASSIGN]:[...zt()?.value?.map(({name:o})=>o)??[]],[v.ASSIGN]:N.getExistingAssignees(),[v.NEW]:Ea(n),[v.CONFIG]:[...Na]}[e]??[]};import tt from"chalk";var xo=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import{decodeTime as No}from"ulid";var ho=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"};var Io=e=>{try{return c("Decoded date",new Date(No(e)))}catch(t){return s("Decoding failed + "+t.message)}},Vn=e=>{if(!e?.id)return null;try{return No(e.id)}catch{return null}};var Oe=(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 Eo from"chalk";var Gn={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ba=(e,t,n)=>Math.max(t,Math.min(n,e)),zn=(e,t,n)=>e+(t-e)*n,Co=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Sa=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,d=e/60,l=i*(1-Math.abs(d%2-1)),u=0,m=0,p=0;d>=0&&d<1?(u=i,m=l):d>=1&&d<2?(u=l,m=i):d>=2&&d<3?(m=i,p=l):d>=3&&d<4?(m=l,p=i):d>=4&&d<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)]},Ra=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Aa=(e,t,n)=>[Math.round(zn(e[0],t[0],n)),Math.round(zn(e[1],t[1],n)),Math.round(zn(e[2],t[2],n))],Nt=e=>{let n=Co(e)%360,r=Sa(n,Gn.stringColor.saturation,Gn.stringColor.lightness);return Ra(r)},wa=e=>{let t=Gn.gradient.stops,n=ba(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),d=o-i;return Aa(t[i],t[i+1],d)},Xt=e=>Co(e.toLowerCase().trim())/4294967295,Ta=e=>{let t=Xt(e);return wa(t)},Ma=e=>{let[t,n,r]=Ta(e);return{normal:o=>Eo.bgRgb(t,n,r).black(o),cursor:o=>Eo.bgRgb(t,n,r).white.bold(o)}};var Yn=e=>Ma(e).normal(` ${e} `),re=(e,t=et)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:Nt(r)};var He={None:"none",Invalid:"invalid",Valid:"valid"};var Pa=["BOARD","TICKET","SWIMLANE"],Jn=()=>{let e=f().selectedNode;return e?.context?Pa.includes(e.context)?B():O({message:"Command not available in this context"}):O({message:"Missing target context"})},X="<ENTER> to confirm",B=(e="",t=[])=>({message:e,validity:He.Valid,completionWordList:t}),O=({message:e,completionWordList:t=[]})=>({validity:He.Invalid,message:e,completionWordList:t}),Jt=e=>e.length===0,se=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:i=1})=>{let d=o.trim();if(d.length<i)return"";let p=[...t.filter(Boolean).filter(x=>x.startsWith(d))].sort((x,h)=>Xt(x)-Xt(h)).slice(0,r).map(Yn).join(" ");return p?`${e}${p}${n}`:""},Xn=({modifier:e})=>{let t="confirm";return e===t?B(X):O({message:Jt(e)?`if you are certain, enter ${Yn(t)}`:"",completionWordList:[t]})},ka=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?O({message:n}):B():O({message:Jt(r)?t:"",completionWordList:[...e]}),ht=({hint:e})=>({modifier:t,inputString:n})=>Jt(t)&&Jt(n)?O({message:e,completionWordList:[]}):B(X),Fa=({modifier:e,inputString:t})=>{let n=Q(v.CONFIG);if(!n.includes(e))return O({message:se({prefix:"config... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case Y.EDITOR:{let r=[...xo];return t.trim()?r.includes(t.trim())?B(X):O({message:se({prefix:"known editors... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):O({message:se({prefix:"editor... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case Y.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?B(X):O({message:se({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case Y.USERNAME:return t.trim()?B(X):O({message:`Enter a username. Saved in ${tt.bgBlack("~/.epiq-global/config.json")}`});case Y.AUTOSYNC:{let r=["yes","no"],o=_().autoSync;return r.includes(t.trim())?B(X):O({message:se({prefix:`should auto-sync (recommended), currently: ${oo(o)} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}case Y.SYNC_DEBOUNCE_MS:{let r=_().autoSyncIntervalMs,o=Xr(t);if(!t.trim()||o===null||o<Je){let i=se({prefix:" examples: ",wordList:qn,minLengthForHints:0,inputString:t});return O({message:`provide duration above ${Je}ms. current duration: ${r}ms.`+i,completionWordList:qn})}return B(X)}default:return O({message:"Unknown config option",completionWordList:n})}},Da=({modifier:e})=>{let t=Q(v.EDIT);if(!t.includes(e)){let r=se({prefix:"edit... ",wordList:t,inputString:e,minLengthForHints:0});return O({message:r||"Unknown edit option",completionWordList:t})}let n=Jn();if(n.validity==="invalid")return n;switch(e){case Le.TITLE:return B(X);case Le.DESCRIPTION:return B("<ENTER> to edit in "+_().preferredEditor);default:return O({message:"Unknown edit option",completionWordList:t})}},La={[v.EXPORT]:()=>B(X+", and create export markdown file"),[v.PEEK]:e=>{let t=e.modifier;if(t==="now")return B(X);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 B(X);let r=Gt(t);if(!t||!r)return O(n);let o=Oe(f().breadCrumb,"BOARD");if(a(o))return O({message:"Command is not applicable in this context"});let i=Io(o.value.id);return a(i)?O({message:"Unable to peek: board id is not a valid ULID"}):fo({date:r,horizonDate:i.value})?B(X):O({message:tt.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[v.EXIT]:()=>B(X+" and exit the application"),[v.INIT]:()=>B(X),[v.FILTER]:e=>{if(e.modifier==="clear")return B();let t=i=>Q(v.FILTER).includes(i);if(!e.modifier||!t(e.modifier))return O({message:se({wordList:Q(v.FILTER),inputString:e.inputString}),completionWordList:Q(v.FILTER)});let n=Object.values(f().tags).map(i=>i.name),r=Object.values(f().contributors).map(i=>i.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?O({message:se({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o}):B():O({message:se({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString}),completionWordList:o})},[v.NONE]:e=>{let t=Q(v.NONE);return e.command?B():O({message:se({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[v.NEW]:e=>ka({list:Q(v.NEW),hint:se({wordList:Q(v.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[v.HELP]:()=>B(X),[v.EDIT]:Da,[v.CONFIG]:Fa,[v.DELETE]:e=>{let t=Jn();return t.validity==="invalid"?t:Xn(e)},[v.CLOSE_ISSUE]:e=>Xn(e),[v.RE_OPEN_ISSUE]:e=>Xn(e),[v.MOVE]:e=>{let t=Jn();return t.validity==="invalid"?t:ht({hint:se({prefix:"hey hacker! These commands are blocked for you... ",wordList:Q(v.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[v.TAG]:e=>{let n=N.getExistingTags().map(r=>` ${tt.bgHex(re(r))(" "+r+" ")} `).slice(0,10).join("");return ht({hint:n.length?"existing tags ... "+n:"create tag ..."})(e)},[v.UNTAG]:e=>{let t=Vt();if(a(t))return O({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${tt.bgHex(re(r))(" "+r+" ")} `).slice(0,10);return n.length?ht({hint:" ... "+n.join("")})(e):O({message:"Issue has no tags",completionWordList:[]})},[v.ASSIGN]:e=>{let t=N.getExistingAssignees().map(n=>` ${tt.bgHex(re(n))(" "+n+" ")} `).slice(0,10);return ht({hint:"assign to... "+t.join("")})(e)},[v.UNASSIGN]:e=>{let t=zt();if(a(t))return O({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${tt.bgHex(re(r))(" "+r+" ")} `).slice(0,10);return n.length?ht({hint:"remove assignee... "+n.join("")})(e):O({message:"Issue has no assignees",completionWordList:[]})},[v.SYNC]:()=>B(X)},bo=Object.fromEntries(Object.entries(La).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var So=["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 w={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Sync:"sync",Export:"export"};var Ro=e=>Object.values(v).includes(e),Ao=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:d,validity:l,completionWordList:u}=bo[n].validate(n,r,i),m=o==="command"||o==="modifier"?Q(n):So;return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:d??"",autoCompletion:t?Wr(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var wo=e=>{let t=e.trimStart(),n=Ua(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),d=Ba(e),l=Ro(r)?r:null,u=l!==null,m=r!=="",p=l?Q(l)??[]:[],x=l&&p.includes(o)?o:"",h="word";n.length===0||n.length===1&&!i?h="command":(n.length===1&&i||n.length===2&&!i)&&(h="modifier");let C=i?"":d,R=Oa(t,l,x);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:i,modifier:x,target:h,inputToMatch:C,inputString:R}},Oa=(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},Ua=e=>e.trim()?e.trim().split(/\s+/):[],Ba=e=>e.trimEnd().split(/\s+/).at(-1)??"";var nt=e=>e===Zn||e===":",Zn=" ",rt={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:He.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},_a=new Set,To=()=>{for(let e of _a)e()};var be=e=>{let n=e(rt),r=wo(n.value),o=n.cursorPosition===n.value.length;rt={...n,commandMeta:Ao(r,o)},To()},It=({message:e,status:t})=>{let n=structuredClone(rt);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,rt=n,To(),c(e,null)},Qn=e=>{be(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},er=e=>{be(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&nt(n[o-1]);)o--;for(;o>0&&!nt(n[o-1]);)o--}else{for(;o<n.length&&!nt(n[o]);)o++;for(;o<n.length&&nt(n[o]);)o++}return{...t,cursorPosition:o}})},Mo=()=>{be(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},Po=()=>{be(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&nt(t[r-1]);)r--;for(;r>0&&!nt(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},U=e=>{be(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),d=i+o,l=Math.max(0,Math.min(i.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},ko=()=>{be(e=>({...e,commandIsPending:!0}))},Fo=({addToHistory:e=!0})=>{be(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),$a()},Do=()=>{be(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}})},Lo=()=>{be(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},$a=()=>U(()=>""),ee=()=>rt,Oo=()=>{let[e,...t]=rt.value.split(Zn);return t.join(Zn).trim()};var T={Sync:"sync",NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"};var Uo=e=>{let{context:t}=f()?.currentNode;if(!t)return w.None;switch(e){case v.EXIT:return w.Exit;case v.EXPORT:return w.Export;case v.INIT:return w.Init;case v.DELETE:return w.Delete;case v.EDIT:return w.Edit;case v.HELP:return w.ViewHelp;case v.RE_OPEN_ISSUE:return w.ReopenIssue;case v.CLOSE_ISSUE:return w.CloseIssue;case v.TAG:return w.TagTicket;case v.UNTAG:return w.UntagTicket;case v.ASSIGN:return w.AssignUserToTicket;case v.UNASSIGN:return w.UnassignUserFromTicket;case v.NEW:return w.NewItem;case v.FILTER:return w.Filter;case v.MOVE:return w.Move;case v.PEEK:return w.Peek;case v.CONFIG:return w.Config;case v.SYNC:return w.Sync;default:return w.None}};import{ulid as V}from"ulid";import ei from"node:fs";import gd from"node:path";import fd from"react";import{Box as md}from"ink";import sn from"react";import{Box as rr,Text as Za}from"ink";import Ne from"react";import{Text as Bo}from"ink";import _o,{useEffect as $o,useState as Wa}from"react";var Wo={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},le=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=xe(),r=Wo[n]??Wo.default,[o,i]=Wa(0);if($o(()=>{i(0)},[r]),$o(()=>{if(!e)return;let l=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return _o.createElement(Bo,null,t);let d=r[o]??r[0]??t;return _o.createElement(Bo,{color:M.accent,dimColor:o===1},d)};import{Box as tr,Text as ja}from"ink";import Zt from"react";var Qt=({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)),d=Math.max(1,Math.ceil(r)),l=Math.max(1,Math.floor(i/d)),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,h=e.slice(p,x),C=e.length>l,R=i,S=C?Math.max(1,Math.floor(l/e.length*R)):R,E=Math.max(0,R-S),A=Math.max(1,e.length-l),K=C?Math.floor(p/A*E):0;return Zt.createElement(tr,{flexDirection:"row",height:i,width:"100%"},Zt.createElement(tr,{flexDirection:"column",flexGrow:1,height:i},h),Zt.createElement(tr,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((Te,ie)=>Zt.createElement(ja,{key:ie,color:C&&ie>=K&&ie<K+S?M.accent:M.secondary},C?"\u2502":" "))))};import{Box as nn,Text as Ya}from"ink";import Ke from"react";import{Text as Ha}from"ink";import Ka from"react";var qa=e=>e.toLowerCase().trim(),Va=(e,t=et)=>{let n=qa(e);return t[n]?t[n]:Nt(n)},en=({id:e,isSelected:t})=>{let n=N.getContributor(e);if(n)return Ka.createElement(Ha,{underline:t,color:Va(n.name)},"@"+n.name)};import{Text as za}from"ink";import Ga from"react";var tn=({id:e,isSelected:t})=>{let n=N.getTag(e);if(n)return Ga.createElement(za,{underline:t,backgroundColor:re(n.name),color:M.primary}," "+n.name+" ")};var jo=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=Dt(Xe(t.title),r),i=jn(t),d=Hn(t);return Ke.createElement(nn,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?M.accent:M.secondary,justifyContent:"space-between"},Ke.createElement(nn,{borderBottom:!0},Ke.createElement(nn,{paddingLeft:1,flexDirection:"column"},Ke.createElement(Ya,{color:M.primary},o))),Ke.createElement(nn,{flexDirection:"row",paddingLeft:1},i.map(l=>Ke.createElement(tn,{key:l.id,id:l.id})),d.map(l=>Ke.createElement(en,{key:l.id,id:l.id}))))};import Xa from"chalk";import{Box as Et,Text as nr}from"ink";import Se from"react";var Ja=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Ho=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=b(t.id),d=S=>{let E=i.find(A=>A.title===S);return E?b(E.id).map(A=>typeof A.props?.value=="string"?A.props.value:"").filter(A=>!!A):[]},l=d("Tags").map(S=>N.getTag(S)).filter(S=>!!S),u=d("Assignees").map(S=>N.getContributor(S)).filter(S=>!!S),m=1,p=l.length*(1+m),x=u.length*(2+m),h=l.map(S=>Se.createElement(Et,{key:S.id,paddingRight:m},Se.createElement(nr,{color:re(S.name)},"\u25A0"))),C=u.map(S=>Se.createElement(Et,{key:S.id,paddingRight:m},Se.createElement(nr,{color:Nt(S.name)},"@"+S.name.at(0)))),R=n?M.accent:o===g.MOVE?M.secondary:M.primary;return Se.createElement(Et,{borderBottom:!0,justifyContent:"space-between"},Se.createElement(Et,null,Se.createElement(le,{isSelected:n,placeholder:Xa.dim.gray(r+1+" ")}),Se.createElement(nr,{wrap:"truncate",color:R},Ja(t.title,e-p-x-14))),Se.createElement(Et,null,h,C))};var Qa=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u}=xe(),m=u[e.id]??[],p=`${e.title} (${m.length})`,x=3,h=o?1:4,C=r-x-(o?2:1),R=Ne.createElement(rr,{borderStyle:"round",borderColor:M.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},Ne.createElement(le,{isSelected:t}),Ne.createElement(Za,{bold:!0,color:t?M.accent:M.primary},p," ",e.readonly?"\u{1F512}":"")),S=(E,A)=>{let K=i&&d===A;return o?Ne.createElement(Ho,{key:E.id,index:A,width:n,ticket:E,isSelected:K,mode:l}):Ne.createElement(jo,{key:E.id,width:n,ticket:E,isSelected:K})};return Ne.createElement(rr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?M.accent:M.secondary,paddingRight:1,paddingLeft:1,height:r},R,Ne.createElement(rr,{padding:o?1:0},m.length>0&&Ne.createElement(Qt,{selectedIndex:d,height:C,itemHeight:h},m.map(S)),Ne.createElement(le,{isSelected:i&&d===-1})))},Ko=Ne.memo(Qa);import{Box as sr,Text as ld}from"ink";import Ue,{useEffect as ar,useMemo as Xo}from"react";import qe from"chalk";import qo from"string-width";import{decodeTime as ed}from"ulid";var td=(e,t)=>e+" ".repeat(Math.max(0,t-qo(e))),nd=(e,t)=>" ".repeat(Math.max(0,t-qo(e)))+e,rd=e=>(()=>{let n={"add.issue":"Created with title","assign.issue":"Assigned to","unassign.issue":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","tag.issue":"Tagged with","untag.issue":"Removed tag","lock.node":"Locked node","move.node":"Moved issue"};return(o=>n[o]??(o.endsWith("e")?`${o}d`:`${o}ed`))(e)})(),od=e=>{switch(e.action){case"move.node":{let t=N.getNode(e.payload.parent);return`to ${t?qe.dim.bgBlack(` ${t.title} `):"unknown"} with rank ${e.payload.rank}`}case"tag.issue":{let t=f().tags[e.payload.tagId];return t?qe.bgHex(re(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=f().tags[e.payload.tagId];return t?qe.bgHex(re(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=f().contributors[e.payload.contributor];return t?qe.hex(re(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=f().contributors[e.payload.contributor];return t?qe.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""}},id=e=>{let t=ho(ed(e));return qe.gray(nd(t,8))},sd=12,ad=e=>td(`${e}`,sd),Vo=e=>{let t=id(e.id),n=ad(e.userName),r=rd(e.action),o=od(e),i=qe.dim("\u203A"),d=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${d}`};var D={exit(){process.exit(0)},enterChildNode(){let e=f(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=b(t.id)[n];!r||t.context==="FIELD"||D.navigate({currentNode:r,selectedIndex:b(r.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=f();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=b(n.id),o=r.findIndex(({id:d})=>d===e.id),i=r.length===0?-1:o>=0?o:0;D.navigate({currentNode:n,selectedIndex:i})},navigateToNextItem:()=>zo(1),navigateToPreviousItem:()=>zo(-1),navigateToNextContainer:()=>Go(1),navigateToPreviousContainer:()=>Go(-1),navigate:({currentNode:e=f().currentNode,selectedIndex:t})=>{I({currentNodeId:e.id,selectedIndex:t})}},zo=e=>{let t=f(),n=b(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;D.navigate({selectedIndex:o})},Go=e=>{let{currentNode:t,nodes:n,selectedIndex:r}=f();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let i=b(o.id),d=i.findIndex(h=>h.id===t.id);if(d<0)return;let l=i.at(d+e)??i.at(0);if(!l)return;let u=b(l.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),x=u.length?p:-1;D.navigate({currentNode:l,selectedIndex:x})};import{Box as rn,Text as dd}from"ink";import Re from"react";var Yo=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=xe(),{title:o}=t,i=b(t.id).map(d=>{let l=typeof d.props?.value=="string"?d.props.value:"";if(o==="Assignees")return N.getContributor(l)?.id;if(o==="Tags")return N.getTag(l)?.id}).filter(d=>!!d);return Re.createElement(rn,{alignItems:"center",paddingTop:1},Re.createElement(rn,{minWidth:12},Re.createElement(le,{isSelected:n}),Re.createElement(dd,{color:n?M.accent:M.secondary2},o,":")),Re.createElement(rn,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((d,l)=>{let u=r.id===t.id&&l===e;return Re.createElement(rn,{key:`${o}-${d}`,paddingRight:2,minHeight:1},Re.createElement(le,{isSelected:u}),o==="Assignees"?Re.createElement(en,{isSelected:u,id:d}):o==="Tags"?Re.createElement(tn,{isSelected:u,id:d}):null)})))};import{Box as on,Text as or}from"ink";import Ae,{useEffect as cd}from"react";var ir=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:d,currentNode:l}=xe(),u=h=>String(h).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];cd(()=>{let h=[];return m.forEach((C,R)=>{let S=Ce(BigInt(R+1));if(!ct(S))return;let E=J.text({id:`${e}-${R}`,name:`Line ${R+1}`,parentNodeId:e,rank:S.value,props:{value:C},readonly:!0,isVirtual:!0}),A=N.createNode(E);ct(A)&&h.push(A.value.id)}),()=>h.forEach(N.deleteNode)},[e,n]);let p="\u2029",x=m.map((h,C)=>{let R=l.id===e&&d===C;return Ae.createElement(on,{key:`${e}-${C}`},Ae.createElement(or,{color:R?M.primary:M.secondary2,dimColor:!R},`${C+1} `.padStart(5,"\xA0")),Ae.createElement(or,{backgroundColor:R?"gray":""},u(h.length?Dt(h,i-10):p)))});return Ae.createElement(on,{flexDirection:"column",paddingTop:1},Ae.createElement(on,null,Ae.createElement(le,{isSelected:o}),Ae.createElement(or,{color:o?M.accent:M.secondary2},t)),Ae.createElement(on,{flexDirection:"row",borderStyle:"round",borderColor:M.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Ae.createElement(Qt,{scrollByOne:!0,children:x,height:r-2,selectedIndex:d,itemHeight:1})))};var ud=e=>`${e}::log`,Jo=e=>e==="Assignees"||e==="Tags",Zo=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=xe(),o=process.stdout.columns||120,i=Xo(()=>ud(e.id),[e.id]),d=Xo(()=>[...e.log].reverse().map(Vo).join(`
6
+ `),[e.log]);ar(()=>{if(N.getNode(i))return;let A=Ce(We);if(a(A))return;let K={...J.field({id:i,name:G.HISTORY,parentNodeId:e.id,rank:A.value,props:{value:d},isVirtual:!0}),readonly:!0,childRenderAxis:"vertical"};return N.createNode(K),()=>{N.deleteNode(i)}},[i,e.id,d]),ar(()=>{let E=N.getNode(i);E&&E.props.value!==d&&N.updateNode({...E,props:{...E.props,value:d},childRenderAxis:"vertical",readonly:!0})},[i,d]);let l=r.id===e.id,u=r.id===i||r.parentNodeId===i;ar(()=>{u&&(n>=0||D.navigate({selectedIndex:0}))},[u,n]);let m=b(e.id);if(u){let E=N.getNode(i),K=t-3;return Ue.createElement(sr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},E?Ue.createElement(ir,{id:E.id,label:"Event log",text:E.props.value??"",selected:!1,maxWidth:o,height:K}):null)}let p=m.reduce((E,A)=>Jo(A.title)||A.id===i?E+1:E,0),x=2,h=p*1,R=t-3-h-x,S=(E,A)=>Jo(E.title)?Ue.createElement(Yo,{key:E.id,parent:E,selected:A,selectedIndex:n}):E.id===i?Ue.createElement(sr,{key:E.id,paddingTop:1},Ue.createElement(le,{isSelected:A}),Ue.createElement(ld,{backgroundColor:M.secondary,color:A?M.accent:M.primary}," History \u203A\u203A ")):E.title===G.DESCRIPTION?Ue.createElement(ir,{label:"Description (press e to edit)",key:E.id,id:E.id,text:E.props.value??"",selected:A,maxWidth:o,height:R}):null;return Ue.createElement(sr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((E,A)=>S(E,l&&n===A)))};var pd=({swimlanes:e,currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:i,height:d,width:l})=>{let u=t.context,m=u===P.TICKET||u===P.FIELD_LIST||u===P.FIELD,p=u===P.BOARD||u===P.SWIMLANE,x=u===P.TICKET?t:r.find(E=>E.context===P.TICKET),h=Math.floor(l/3),C=Math.floor(l/Math.max(e.length,1)),R=Math.min(C,h),S=i==="dense";return sn.createElement(md,{flexDirection:"row",height:d},p&&e.map((E,A)=>{let K=t.id===E.id,Te=K?n:-1,ie=t.context===P.BOARD&&n===A;return sn.createElement(Ko,{key:E.id,height:d,width:R,swimlane:E,isSelected:ie,isDense:S,isFocused:K,listSelectedIndex:Te,mode:o})}),m&&x&&sn.createElement(Zo,{height:d,ticket:x}))},Qo=sn.memo(pd);import{render as vd}from"ink";import{Writable as yd}from"node:stream";var Ct=e=>String(e).padStart(2,"0"),xd=e=>{let t=e.getUTCFullYear(),n=Ct(e.getUTCMonth()+1),r=Ct(e.getUTCDate()),o=Ct(e.getUTCHours()),i=Ct(e.getUTCMinutes()),d=Ct(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${d}`},Nd=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",hd=async(e,{width:t,height:n})=>{let r="",o=new yd({write(d,l,u){let m=Id(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=vd(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),i.unmount(),r},Id=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),ti=async()=>{let{viewMode:e}=_(),{currentNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:i}=f(),d=r.find(A=>A.context==="BOARD");if(!d)return s("No board found to export");let l=120,u=40,m=await hd(fd.createElement(Qo,{height:u,width:l,swimlanes:(i[d.id]??[]).filter(A=>A!==void 0&&kt(A)),currentNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:u});if(!m)return s("Failed to render board export");let p=fe(process.cwd());if(a(p))return s("Unable to export, epiq root not found");let x=new Date,h=xd(x),C=`board_${Nd(d.title)}_${h}.md`,R=jr(p.value);ei.mkdirSync(R,{recursive:!0});let S=gd.join(R,C),E=`# Board - ${d.title}
46
7
  Date: ${x.toISOString()}
47
8
 
48
9
  \`\`\`text
49
10
  ${m}
50
11
  \`\`\`
51
- `;return yi.writeFileSync(b,N,"utf8"),c("Exported board layout",b)};var Ei=()=>{let{currentNode:e,selectedIndex:t}=v(),n=S(e.id)[t];return{currentNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:n?.parentNodeId??null,selectedIndex:t}},hi=(e,t)=>Math.max(0,Math.min(e,Math.max(0,t-1))),Ni=e=>{let{nodes:t}=v(),n=t[e.currentNodeId];if(n&&!n.isDeleted&&e.selectedNodeId){let i=S(n.id).findIndex(a=>a.id===e.selectedNodeId);if(i>=0)return L.navigate({currentNode:n,selectedIndex:i}),c("Restored navigation",null)}if(e.selectedNodeId){let o=t[e.selectedNodeId];if(o&&!o.isDeleted&&o.parentNodeId){let i=t[o.parentNodeId];if(i&&!i.isDeleted){let a=S(i.id).findIndex(l=>l.id===o.id);if(a>=0)return L.navigate({currentNode:i,selectedIndex:a}),c("Restored navigation to moved node",null)}}}if(n&&!n.isDeleted){let o=S(n.id);return L.navigate({currentNode:n,selectedIndex:hi(e.selectedIndex,o.length)}),c("Restored navigation to previous container",null)}if(e.parentNodeId){let o=t[e.parentNodeId];if(o&&!o.isDeleted){let i=S(o.id);return L.navigate({currentNode:o,selectedIndex:hi(e.selectedIndex,i.length)}),c("Restored navigation to parent",null)}}let r=t[v().rootNodeId];return!r||r.isDeleted?s("Unable to restore navigation"):(L.navigate({currentNode:r,selectedIndex:0}),c("Restored navigation to root",null))};import{ulid as bd}from"ulid";var Ii=null,Fe=()=>structuredClone(Ii),Nt=e=>Ii=e,Ci=()=>{let{currentNode:e,selectedIndex:t}=v(),r=S(e.id)[t];return r?c("Resolved selected child",r):s("Target node not found")};var bi=({id:e,parentId:t,position:n={at:"end"}})=>{let r=X();if(d(r))return s("Unable to resolve user ID");let o=xe(t,e,n,r.value);return d(o)?o:c("Created pending move state",{id:bd(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value}})},Ri=e=>{Nt(e);let t=mt(e,!0);return d(t)?t:c("Node moved successfully",t.value)};function lr(e){let t=Ci();if(d(t))return t;let{currentNode:n,nodes:r}=v();if(!n.parentNodeId)return s("Missing parent node id");let o=r[n.parentNodeId];if(!o)return s("Missing parent node");let i=$(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=bi({id:t.value.id,parentId:l.id,position:{at:"end"}});return d(u)?u:Ri(u.value)}function ur(e){let t=Ci();if(d(t))return t;let{currentNode:n,selectedIndex:r}=v(),i=$(n.id)[r+e];if(!i)return s("Missing sibling node");let a=bi({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return d(a)?a:Ri(a.value)}import{spawnSync as Rd}from"node:child_process";import Sd from"node:os";import Si from"node:path";import{ulid as Ad}from"ulid";function wd(){let{preferredEditor:e}=ue(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Td(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function Ai(e){let t=Si.join(Sd.tmpdir(),"epiq");ne.mkDir(t);let n=Si.join(t,Ad());ne.writeToFile(n,e??"");let r=wd();for(let o of r){let i=Td(o,n),a=Rd(i,{stdio:"inherit",shell:!0});if(!a.error&&a.status===0){let l=ne.readFile(n);if(l==null)return s("Unable to read edited file");let u=l.replace(/\r?\n$/,"");return c("Successfully edited",u)}}return s("Unable to open editor")}var wi=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};import kd from"node:fs";import Mi from"node:path";import mr from"node:fs";import Md from"node:path";var Ti=async e=>{let t=Md.join(e,".gitignore"),n=mr.existsSync(t)?mr.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/logs/"],o=n.split(`
12
+ `;return ei.writeFileSync(S,E,"utf8"),c("Exported board layout",S)};var ri=()=>{let{currentNode:e,selectedIndex:t}=f(),n=b(e.id)[t];return{currentNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:n?.parentNodeId??null,selectedIndex:t}},ni=(e,t)=>Math.max(0,Math.min(e,Math.max(0,t-1))),oi=e=>{let{nodes:t}=f(),n=t[e.currentNodeId];if(n&&!n.isDeleted&&e.selectedNodeId){let i=b(n.id).findIndex(d=>d.id===e.selectedNodeId);if(i>=0)return D.navigate({currentNode:n,selectedIndex:i}),c("Restored navigation",null)}if(e.selectedNodeId){let o=t[e.selectedNodeId];if(o&&!o.isDeleted&&o.parentNodeId){let i=t[o.parentNodeId];if(i&&!i.isDeleted){let d=b(i.id).findIndex(l=>l.id===o.id);if(d>=0)return D.navigate({currentNode:i,selectedIndex:d}),c("Restored navigation to moved node",null)}}}if(n&&!n.isDeleted){let o=b(n.id);return D.navigate({currentNode:n,selectedIndex:ni(e.selectedIndex,o.length)}),c("Restored navigation to previous container",null)}if(e.parentNodeId){let o=t[e.parentNodeId];if(o&&!o.isDeleted){let i=b(o.id);return D.navigate({currentNode:o,selectedIndex:ni(e.selectedIndex,i.length)}),c("Restored navigation to parent",null)}}let r=t[f().rootNodeId];return!r||r.isDeleted?s("Unable to restore navigation"):(D.navigate({currentNode:r,selectedIndex:0}),c("Restored navigation to root",null))};import Td from"node:os";import di from"node:path";import{z as Ve}from"zod";import{accessSync as Ed,copyFileSync as Cd,existsSync as an,mkdirSync as ii,readdirSync as si,readFileSync as bd,renameSync as Sd,rmSync as Rd,statSync as ai,unlinkSync as Ad,writeFileSync as wd}from"node:fs";import ot from"node:path";var ae={writeToFile:(e,t)=>{try{let n=ot.dirname(e);an(n)||ii(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);wd(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return bd(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=ae.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 an(e)&&ai(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Ed(e),!0}catch{return!1}},mkDir:e=>ii(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=ot.parse(t);for(;;){let r=ot.join(t,e);try{if(an(r)&&ai(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=ot.dirname(t)}return null},readFirstJSON(e){try{if(!ae.dirExists(e))return null;let t=si(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=ot.join(e,t);return ae.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return ae.dirExists(e)?si(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Ad(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Rd(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(ot.dirname(t)),!n?.overwrite&&an(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Sd(e,t)}catch(r){if(r?.code==="EXDEV"){Cd(e,t),this.rmFile(e);return}throw r}}};var Md={userId:"",userName:"",preferredEditor:"",autoSync:!1},ci=Ve.object({preferredEditor:Ve.string().optional(),userName:Ve.string().optional(),userId:Ve.string().optional(),autoSync:Ve.boolean().nullable().optional(),autoSyncDebounceMs:Ve.number().optional(),viewMode:Ve.enum(["dense","wide"]).optional()}),Pd="config.json",li=()=>di.join(Td.homedir(),de),dr=()=>di.join(li(),Pd),cr=()=>{try{return ae.mkDir(li()),c(`Ensured ~/${de} exists`,null)}catch{return s(`Unable to create ~/${de}`)}},kd=e=>{let t;try{t=JSON.parse(e)}catch{return s(`Invalid ~/${de}/config.json JSON`)}let n=ci.safeParse(t??{});return n.success?c("Parsed config",n.data):s(`Invalid ~/${de}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},ui=()=>{let e=cr();if(a(e))return s(e.message);let t=dr(),n=ae.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{autoSync:!1,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:15e3}):kd(n)},mi=e=>{let t=cr();if(a(t))return s(t.message);let n=ci.safeParse(e);if(!n.success)return s(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=dr();try{return ae.writeToFile(r,JSON.stringify(n.data,null,2)+`
13
+ `),c("Config written",null)}catch{return s(`Unable to write ~/${de}/config.json`)}},ze=e=>{let t=ui();if(a(t))return s("Failed to read existing config");let n={...t.value,...e};return mi(n)},pi=()=>{let e=dr(),t=cr();if(a(t))return s(`Unable to create ~/${de}`);if(!(ae.readFile(e)!==null)){let m=mi(Md);if(a(m))throw new Error(`Unable to create ~/${de}/config.json`)}let r=ui();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:d,autoSync:l,autoSyncDebounceMs:u}=r.value;return!i||!d?s(`User name or ID not configured in ~/${de}/config.json`):c("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:d,autoSync:l??!1,autoSyncIntervalMs:u??15e3,viewMode:"dense"})};import{monotonicFactory as Fd,ulid as dn}from"ulid";var cn=Fd(),ln=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=cn(),d=cn(),l=cn(),u=cn(),m=ao();if(a(m))return m;let p=z(m.value,void 0);if(a(p))return p;let x=z(p.value,void 0);return a(x)?x:c("Created issue events",[{id:dn(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}},{id:dn(),userId:r,userName:o,action:"add.field",payload:{id:d,parent:i,name:G.DESCRIPTION,val:"",rank:m.value}},{id:dn(),userId:r,userName:o,action:"add.field",payload:{id:l,parent:i,name:"Assignees",rank:p.value}},{id:dn(),userId:r,userName:o,action:"add.field",payload:{id:u,parent:i,name:"Tags",rank:x.value}}])};import{monotonicFactory as Dd,ulid as we}from"ulid";var bt=Dd();function Ld(){let e=Object.values(f().nodes).find(r=>r.context==="WORKSPACE");if(!e)throw new Error("No workspace found in event log");let[t]=b(e.id),[n]=t?b(t.id):[];if(logger.debug("Boot navigation target:",{workspace:e?.id,firstBoard:t?.id,firstSwimlane:n?.id}),n){let r=f().renderedChildrenIndex?.[n.id]??[];return{currentNode:n,selectedIndex:r.length>0?0:-1}}else return t?{currentNode:t,selectedIndex:0}:e?{currentNode:e,selectedIndex:0}:{currentNode:f().nodes[f().rootNodeId],selectedIndex:0}}function Od(){let e=Ld();D.navigate(e)}function gi({userId:e,userName:t}){let n=bt(),r=bt(),o=bt(),i=bt(),d=bt(),l=z(void 0,void 0);if(a(l))return l;let u=z(void 0,void 0);if(a(u))return u;let m=z(u.value,void 0);if(a(m))return m;let p=z(void 0,void 0);if(a(p))return p;let x=z(p.value,void 0);if(a(x))return x;let h=z(x.value,void 0);if(a(h))return h;let C=z(void 0,void 0);return a(C)?C:c("Created default events",[{id:we(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:we(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:we(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:we(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"In progress",parent:r,rank:x.value}},{id:we(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:r,rank:h.value}},{id:we(),userId:e,userName:t,action:"add.board",payload:{id:qt,name:"Closed",parent:n,rank:m.value}},{id:we(),userId:e,userName:t,action:"add.swimlane",payload:{id:te,name:"Closed",parent:qt,rank:C.value}},{id:we(),userId:e,userName:t,action:"lock.node",payload:{id:qt}},{id:we(),userId:e,userName:t,action:"lock.node",payload:{id:te}}])}function un({hasProject:e,eventLog:t}){if(!e){let o=J.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=xt(o);return a(i)?i:(I({hasProject:!1,mode:g.DEFAULT}),c("Booted uninitialized workspace placeholder",null))}if(!t.some(o=>o.action==="init.workspace"))return s("Initialized Epiq project has no workspace init event");let r=yt(t).filter(a);return r.length>0?s(`Materializing failed:
14
+ ${r.map(o=>o.message).join(`
15
+ `)}`):(Od(),I({hasProject:!0}),c("State booted successfully",null))}var fi=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};import{ulid as xi}from"ulid";import{spawnSync as Ud}from"node:child_process";import Bd from"node:os";import vi from"node:path";import{ulid as _d}from"ulid";function $d(){let{preferredEditor:e}=_(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Wd(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function yi(e){let t=vi.join(Bd.tmpdir(),"epiq");ae.mkDir(t);let n=vi.join(t,_d());ae.writeToFile(n,e??"");let r=$d();for(let o of r){let i=Wd(o,n),d=Ud(i,{stdio:"inherit",shell:!0});if(!d.error&&d.status===0){let l=ae.readFile(n);if(l==null)return s("Unable to read edited file");let u=l.replace(/\r?\n$/,"");return c("Successfully edited",u)}}return s("Unable to open editor")}var Ni=()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{breadCrumb:t,selectedNode:n}=f(),r=Oe([...t,n],"TICKET");if(a(r))return s("Edit target must be an issue");let o=r.value;if(o.readonly)return s("Cannot edit readonly field");let i=b(o.id).find(m=>m.title===G.DESCRIPTION);if(!i)return s("No target found");if(i.readonly)return s("Cannot edit readonly field");let d=i.props.value;if(typeof d!="string")return s("Selected field is not editable text");let l=yi(d);if(a(l))return s("Failed to edit field");let u=l.value;return u===d?c("No changes made",null):i.title===G.DESCRIPTION?W({id:xi(),action:"edit.description",payload:{id:i.id,md:u},...e.value}):i.title==="Title"?W({id:xi(),action:"edit.title",payload:{id:i.id,name:u},...e.value}):s(`Editing not supported for "${i.title}"`)};import ic from"node:fs";import zi from"node:path";import ur from"node:fs";import Kd from"node:path";import St from"fs";import Ii from"path";import jd from"util";var hi=1e3,Ei=()=>{let e=process.cwd(),t=fe(e);if(!a(t))return Ii.join(t.value,Ie,"log","epiq.log")};function Hd(){if(!Pn)return;let e=Ei();if(e===void 0||!St.existsSync(e))return;let n=St.readFileSync(e,"utf8").split(`
16
+ `);if(n[n.length-1]===""&&n.pop(),n.length<=hi)return;let r=n.slice(-hi).join(`
17
+ `)+`
18
+ `;St.writeFileSync(e,r,"utf8")}function lr(e,t,n=!1){if(!Pn)return;let r=Ei();if(!r)return;let o=jd.format(...t),i=new Date,l=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
19
+ `;St.mkdirSync(Ii.dirname(r),{recursive:!0}),St.appendFileSync(r,l,"utf8"),Hd()}var oe={info(...e){lr("[Info]",e,!1)},debug(...e){lr("->",e,!0)},error(...e){lr("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=oe;var Ci=async e=>{let t=Kd.join(e,".gitignore"),n=ur.existsSync(t)?ur.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
52
20
  `).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 c("Local epiq paths already ignored",!1);let l=["# [epiq]: local hydrated state is never committed",...i].join(`
53
21
  `);return n=n.trimEnd()+`
54
22
 
55
23
  ${l}
56
- `,mr.writeFileSync(t,n,"utf8"),Z.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)};var H=(e,t,n)=>s(`[init:${e}] ${t}: ${n}`),ki=async()=>{let e=Sr(),t=await Pt(process.cwd());if(d(t))return H(1,"resolve git repo",t.message);let n=t.value,r=await rt(n);if(d(r))return H(2,"check pending git operation",r.message);if(r.value)return H(2,"pending git operation","Cannot initialize Epiq while a git operation is in progress");if(Rn(n))return H(3,"check existing project","Epiq project already initialized");let o=Qt();if(!o.isSetup||!o.userName)return H(4,"resolve user config","Missing Epiq user configuration (userId / userName). Run setup first.");let i=ue(),a=i.userName,l=i.userId;if(!l||!a)return H(4,"resolve user config","Missing Epiq user id");let u=we({userId:l,userName:a}),m=e.stateBranch,p=await wt({repoRoot:n,branch:m});if(d(p))return H(5,"check state branch",p.message);let x=await Ft({repoRoot:n,stateBranchName:e.stateBranch});if(d(x))return H(5,"create state branch",x.message);let E=kt();if(d(E))return H(6,"ensure worktrees dir",E.message);let I=Mi.join(Mt(),e.projectId),R=await Fn({repoRoot:n,stateBranchRoot:I,stateBranchName:e.stateBranch});if(d(R))return H(7,"ensure state worktree",R.message);let b=Mi.join(I,".epiq");kd.mkdirSync(b,{recursive:!0});let N=Pi({userId:l,userName:a});if(d(N))return H(8,"create default events",N.message);for(let Cn of N.value){let Cr=Bt({event:Cn,rootDir:I});if(d(Cr))return H(8,"persist initial event log",Cr.message)}let w=await Lt({stateBranchRoot:I,eventFileName:we({userId:l,userName:a})});if(d(w))return H(9,"stage state event file",w.message);let j=await Ke({cwd:I,message:"[epiq:init]"});if(d(j))return H(9,"commit state branch",j.message);let Re=await Ti(n);if(d(Re))return H(11,"ensure gitignore",Re.message);let te=wr({repoRoot:n,fileContents:e});if(d(te))return H(12,"create project file",te.message);let yr=await B.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(d(yr))return H(13,"stage project file",yr.message);let xr=await B.commit({cwd:n,message:"[epiq:init-project]"});if(d(xr))return H(13,"commit project file",xr.message);let hr=Wt({repoRoot:n,stateBranchRoot:I});if(d(hr))return H(14,"hydrate local events",hr.message);let In="Project initialized!",Er=await at({repoRoot:n,stateBranchRoot:I});d(Er)&&(In+=` Warn: [init:15] ${Er.message}`);let Nr=await B.push({cwd:n});d(Nr)&&(In+=` Warn: [init:16] ${Nr.message}`);let Ir=Te(N.value).filter(d);if(Ir.length>0)return H(17,"boot app",Ir.map(Cn=>Cn.message).join(`
57
- `));let{rootNodeId:ss,nodes:as}=v();return L.navigate({currentNode:as[ss],selectedIndex:0}),C({hasProject:!0,mode:f.DEFAULT}),c(In,null)};var Fi=e=>Object.values(v().tags).find(t=>t.name===e),Li=e=>Object.values(v().contributors).find(t=>t.name===e),Di=[{systemOnly:!0,intent:A.Move,mode:f.COMMAND_LINE,action:()=>{let e=X();if(d(e))return s("Unable to resolve user ID");let{modifier:t}=oe().commandMeta,n=()=>{let l=Fe();if(!l)return s("No pending move state");let u=l.payload.id;if(!v().nodes[u])return s("Moved node not found");let p=l.payload.parent,x=v().nodes[p];if(!x)return s("Move parent not found");let E=S(p).findIndex(I=>I.id===u);return E===-1?s("Moved node not found among rendered children"):(L.navigate({currentNode:x,selectedIndex:E}),c("Synchronized navigation to moved node",null))},r=l=>{if(d(l))return s(l.message);let u=n();return d(u)?s(u.message):c("Updated move preview",null)},{currentNode:o,selectedIndex:i}=v(),a=S(o.id)[i];if(!a)return C({mode:f.DEFAULT}),s("No move target");if(t==="start"){if(a.readonly)return s("Target node is read-only");if(i===-1)return s("No item selected");if(!a.parentNodeId)return s("Target has no parent");let l=$(a.parentNodeId),u=l.findIndex(({id:R})=>R===a.id);if(u===-1)return s("Target not found among siblings");let m=l[u-1],p=l[u+1],x=p!=null?{at:"before",sibling:p.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"},E=xe(a.parentNodeId,a.id,x,e.value);if(d(E))return E;Nt({id:U(),action:"move.node",payload:{id:a.id,parent:a.parentNodeId,rank:E.value},...e.value}),C({mode:f.MOVE});let I=n();return d(I)?s(I.message):c("Move initialized",null)}if(t==="next")return C({mode:f.MOVE}),r(ur(1));if(t==="previous")return C({mode:f.MOVE}),r(ur(-1));if(t==="to-next")return C({mode:f.MOVE}),r(lr(1));if(t==="to-previous")return C({mode:f.MOVE}),r(lr(-1));if(t==="confirm"){C({mode:f.DEFAULT});let l=Fe();if(!l)return s("No pending move to confirm");let u=K(l);if(d(u))return u;let m=n();return d(m)?s(m.message):(Nt(null),c("Moved item",null))}return t==="cancel"?(Nt(null),C({mode:f.DEFAULT}),c("Cancelling move",null)):s("Invalid move modifier")}},{intent:A.Delete,mode:f.COMMAND_LINE,action:()=>{let e=X();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=S(t.id)[n];return r?K({id:U(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>C({mode:f.DEFAULT})},{intent:A.Edit,mode:f.COMMAND_LINE,action:()=>{let e=X();if(d(e))return s("Unable to resolve user ID");let t=Be(v().breadCrumb,"TICKET");if(d(t))return s("Edit target must be an issue");let n=t.value;if(n.readonly)return s("Cannot edit readonly field");let{currentNode:r,selectedIndex:o}=v();if(!S(n.id)[o])return s("No selected field");let a=S(r.id)[o];if(!a)return s("No selected field");if(a.readonly)return s("Cannot edit readonly field");let l=a.props.value;if(typeof l!="string")return s("Selected field is not editable text");let u=Ai(l);if(d(u))return s("Failed to edit field");let m=u.value;return m===l?c("No changes made",null):a.title==="Description"?K({id:U(),action:"edit.description",payload:{id:a.id,md:m},...e.value}):a.title==="Title"?K({id:U(),action:"edit.title",payload:{id:a.id,name:m},...e.value}):s(`Editing not supported for "${a.title}"`)},onSuccess:()=>C({mode:f.DEFAULT})},{intent:A.Filter,mode:f.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=oe().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(l=>q(g.FILTER).map(u=>u.split(n)[0]).includes(l))(r))return s("Invalid filter modifier");let a={target:r,operator:"=",value:t.trim()};return re(l=>({...l,filters:e==="clear"?[]:[...l.filters,a],mode:f.DEFAULT})),c("Viewing help",null)}},{intent:A.ViewHelp,mode:f.COMMAND_LINE,action:()=>(C({mode:f.HELP}),c("Viewing help",null))},{intent:A.CloseIssue,mode:f.COMMAND_LINE,action:()=>{let e=X();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=S(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!Q(r))return s("Cannot close in this context");let o=v().nodes[J];if(!o)return s("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return s("Issue is already closed");let i=xe(o.id,r.id,{at:"end"},e.value);if(d(i))return i;let a=K({id:U(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:i.value},...e.value});return d(a)?a:c("Issue closed",null)},onSuccess:()=>C({mode:f.DEFAULT})},{intent:A.ReopenIssue,mode:f.COMMAND_LINE,action:()=>{let e=X();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=S(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):Ge(r.id,"TICKET");if(d(o))return s("Cannot reopen in this context");let i=o.value,a=v().nodes[J];if(!a)return s("Unable to locate closed swimlane");if(i.parentNodeId!==a.id)return s("Issue is not closed");if(!Q(i))return s("Target node is not issue");let l=wi(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=xe(u.id,i.id,{at:"end"},e.value);if(d(m))return m;let p=K({id:U(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:m.value},...e.value});return d(p)?p:c("Issue reopened",null)},onSuccess:()=>C({mode:f.DEFAULT})},{intent:A.SetUserName,mode:f.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:n}=ue(),r=sn()?.trim();if(!r)return s("No username provided");let o=r??n,i=e??U();if(!o||!i)return s("Unable to resolve user name or id");let a=Vt({userName:o,userId:i,preferredEditor:t??""});return d(a)?a:(Ot({userName:o,userId:i}),C({mode:f.DEFAULT}),c(`Username set to "${r}"`,null))}},{intent:A.Init,mode:f.COMMAND_LINE,action:ki},{intent:A.SetEditor,mode:f.COMMAND_LINE,action:()=>{let e=sn()?.trim();if(!e)return s("No editor provided");let t=Vt({preferredEditor:e});return d(t)?t:(Ot({preferredEditor:e}),C({mode:f.DEFAULT}),c(`Editor configuration set to "${e}"`,null))}},{intent:A.SetAutoSync,mode:f.COMMAND_LINE,action:()=>{let e=oe().commandMeta.modifier;if(e!=="true"&&e!=="false")return s("Invalid response");let t=e.toLowerCase()==="true",n=Vt({autoSync:t});return d(n)?n:(Ot({autoSync:t}),C({mode:f.DEFAULT}),c(`Auto synchronization set to "${t}"`,null))}},{intent:A.NewItem,mode:f.COMMAND_LINE,action:(e,t)=>{let n=X();if(d(n))return s("Unable to resolve user ID");if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:r,currentNode:o,selectedIndex:i}=v(),a=l=>{let u=K(l);if(d(u))return u;let m=h.getNode(u.value.result.id);if(!m)return s("Created node not found");if(!m.parentNodeId)return u;let p=h.getNode(m.parentNodeId);return p?(L.navigate({currentNode:p,selectedIndex:h.getSiblings(m.parentNodeId).findIndex(({id:x})=>x===m.id)}),u):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:l}=v(),u=h.getNode(l);if(!u)return s("Workspace not found");let m=Me(u.id,n.value);return d(m)?m:a({id:U(),action:"add.board",payload:{id:U(),name:t.inputString,parent:u.id,rank:m.value},...n.value})}if(t.modifier==="swimlane"){let l=Be(r,"BOARD");if(d(l))return s("Unable to add swimlane in this context");let u=Me(l.value.id,n.value);return d(u)?u:a({id:U(),action:"add.swimlane",payload:{id:U(),name:t.inputString,parent:l.value.id,rank:u.value},...n.value})}if(t.modifier==="issue"){let l=S(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&l?.context==="SWIMLANE"?l:(()=>{let N=Be(r,"SWIMLANE");return d(N)?null:N.value})();if(!u)return s("Unable to add issue in this context");let m=Me(u.id,n.value);if(d(m))return m;let p=Gt({name:t.inputString,parent:u.id,rank:m.value,user:n.value});if(d(p))return p;let x=p.value,E=Te(x);if(E.some(N=>d(N)))return s("Issue create failed: "+E.filter(d).map(N=>N.message).filter(Boolean).join(", "));let I=E[0];if(!I||d(I))return s("Issue creation failed");let b=x.find(N=>N.action==="add.issue")?.payload.id;return b?(L.navigate({currentNode:u,selectedIndex:h.getSiblings(u.id).findIndex(({id:N})=>N===b)}),c("Issue created",null)):s("Unable to determine ticket id")}return c("Success",null)},onSuccess:()=>C({mode:f.DEFAULT})},{intent:A.SetView,mode:f.COMMAND_LINE,action:()=>{let{commandMeta:e}=oe();return e.validity===he.Invalid?s("Invalid command "+ge):(re(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),c("View set",null))},onSuccess:()=>C({mode:f.DEFAULT})},{intent:A.Rename,mode:f.COMMAND_LINE,action:()=>{let e=X();if(d(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=S(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=sn();return o?K({id:U(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>C({mode:f.DEFAULT})},{intent:A.UntagTicket,mode:f.COMMAND_LINE,action:()=>{let e=X();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=oe().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=Fi(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid untag target");let a=Ge(i.id,"TICKET");if(d(a))return s("Unable to untag issue in this context");let l=a.value,u=h.getFieldByTitle(l.id,"Tags");if(!u)return s("Unable to locate tags field");let m=S(u.id).find(p=>p.props?.value===o.id);return m?K({id:U(),action:"untag.issue",payload:{id:m.id,target:l.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>C({mode:f.DEFAULT})},{intent:A.TagTicket,mode:f.COMMAND_LINE,action:()=>{let e=X();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=oe().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=v(),a=S(i.id)[o];if(!a)return s("Invalid tag target");let l=Ge(a.id,"TICKET");if(d(l))return s("Unable to tag issue in this context");let u=l.value,m=Fi(r),p;if(m)p=m.id;else{let R=U(),b=K({id:U(),action:"create.tag",payload:{id:R,name:r},userId:e.value.userId,userName:e.value.userName});if(d(b))return b;p=b.value.result.id}let x=h.getFieldByTitle(u.id,"Tags");if(!x)return s("Unable to locate tags field");if(S(x.id).some(R=>R.props?.value===p))return s("Already tagged with that tag");let I=Me(x.id,e.value);return d(I)?I:K({id:U(),action:"tag.issue",payload:{id:U(),target:u.id,tagId:p,rank:I.value},...e.value})},onSuccess:()=>C({mode:f.DEFAULT})},{intent:A.AssignUserToTicket,mode:f.COMMAND_LINE,action:()=>{let e=X();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=oe().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=v(),a=S(i.id)[o];if(!a)return s("Invalid assign target");let l=Ge(a.id,"TICKET");if(d(l))return s("Unable to assign issue in this context");let u=l.value,m=Li(r),p;if(m)p=m.id;else{let R=U(),b=K({id:U(),action:"create.contributor",payload:{id:R,name:r},userId:e.value.userId,userName:e.value.userName});if(d(b))return b;p=b.value.result.id}let x=h.getFieldByTitle(u.id,"Assignees");if(!x)return s("Unable to locate assignees field");if(S(x.id).some(R=>R.props?.value===p))return s("Assignee already assigned");let I=Me(x.id,e.value);return d(I)?I:K({id:U(),action:"assign.issue",payload:{id:U(),target:u.id,contributor:p,rank:I.value},...e.value})},onSuccess:()=>C({mode:f.DEFAULT})},{intent:A.UnassignUserFromTicket,mode:f.COMMAND_LINE,action:()=>{let e=X();if(d(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=oe().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=Li(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid unassign target");let a=Ge(i.id,"TICKET");if(d(a))return s("Unable to unassign in this context");let l=a.value,u=h.getFieldByTitle(l.id,"Assignees");if(!u)return s("Unable to locate assignees field");let m=S(u.id).find(p=>p.props?.value===o.id);return m?K({id:U(),action:"unassign.issue",payload:{id:m.id,target:l.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${r}"`)},onSuccess:()=>C({mode:f.DEFAULT})},{intent:A.Sync,mode:f.COMMAND_LINE,action:async()=>{let e=Ei();W(()=>""),C({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:n}=ue();if(!t)return s("Unable to resolve userId");if(!n)return s("Unable to resolve userName");let r=X();if(d(r)||!r.value)return s("Unable to resolve event log path");let o=we(r.value),i=await Ht({ownEventFileName:o});if(d(i))return C({syncStatus:{msg:i.message,status:"outOfSync"}}),s(`Unable to sync state. ${i.message}`);let a=Se(process.cwd());if(d(a))return a;let l=ct(a.value);if(d(l))return s(`Unable to load events. ${l.message}`);let u=fn({eventLog:l.value,hasProject:!0});if(d(u))return s(`Unable to boot synced state. ${u.message}`);C({hasProject:!0,syncStatus:{msg:"Synced",status:"synced"},mode:f.DEFAULT});let m=Ni(e);return d(m)?m:c("Synced",!0)}},{intent:A.Peek,mode:f.COMMAND_LINE,action:async()=>{let e=Be(v().breadCrumb,"BOARD");if(d(e))return e;let t=ce(process.cwd());if(d(t))throw new Error(t.message);let n=ct(t.value);if(d(n))return s(n.message);let r=n.value,{modifier:o}=oe().commandMeta,i;if(o==="now"){let E=pr();if(d(E))return E;let I=pt(r);return I.some(d)?s(I.map(R=>R.message).join(", ")):(C({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}if(o==="prev"){let E=v().eventLog.at(-2),I=Xn(E);if(I===null)return s("No previous event to peek");i=I}else if(o==="next"){let E=v().unappliedEvents.at(0),I=Xn(E);if(I===null)return s("No next event to peek");i=I}else{let E=nn(o);if(!E)return s("Invalid peek date");i=E.getTime()}let a=e.value.id,{appliedEvents:l,unappliedEvents:u}=io(r,i),m=pr();if(d(m))return m;let p=pt(l);if(p.some(d))return s(p.map(E=>E.message).join(", "));let x=v().nodes[a];return x?(L.navigate({currentNode:x,selectedIndex:0}),C({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),c("Peeking ",!0)):s("Board did not exist at peek date")}},{intent:A.Export,mode:f.COMMAND_LINE,action:async()=>{let e=await xi();return d(e)?e:(C({mode:f.DEFAULT}),c("Export successful",!0))}},{intent:A.Exit,mode:f.COMMAND_LINE,action:async()=>(L.exit(),c("Exit successful",!0))}];var Pd=new Set(["peek","filter","view-help"]),de=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=oe();if(!t)return s("No command to confirm");if(!e&&n===he.Invalid)return s("Invalid command");let i=ni(t);if(Zo(),v().readOnly&&!Pd.has(i))return xt({status:ge.Fail,message:"Command not available in readonly state",value:null});let a=Di.filter(u=>e||u.systemOnly!==!0).find(u=>u.intent===i);if(!a)return xt({status:ge.Fail,message:"Command not found",value:null});let l=await a.action(a,{command:t,inputString:o,modifier:r});return d(l)?xt(l):(Qo({addToHistory:!e}),a.onSuccess?.(),xt(l))};var vn=[{intent:T.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(C({mode:f.COMMAND_LINE}),W(()=>"move cancel"),de({isForceExecutedBySystem:!0}))},{intent:T.InitMove,mode:f.DEFAULT,description:"[m] move init/confirm",action:()=>(C({mode:f.COMMAND_LINE}),W(()=>"move start"),de({isForceExecutedBySystem:!0}))},{intent:T.ConfirmMove,mode:f.MOVE,action:()=>(C({mode:f.COMMAND_LINE}),W(()=>"move confirm"),de({isForceExecutedBySystem:!0}))}],yn=[{intent:T.MovePreviousItem,mode:f.MOVE,action:()=>Fe()?(C({mode:f.COMMAND_LINE}),W(()=>"move previous"),de({isForceExecutedBySystem:!0})):s("No pending move")},{intent:T.MoveNextItem,mode:f.MOVE,action:()=>Fe()?(C({mode:f.COMMAND_LINE}),W(()=>"move next"),de({isForceExecutedBySystem:!0})):s("No pending move")}],Oi=[{intent:T.MoveToNextContainer,mode:f.MOVE,action:()=>Fe()?(C({mode:f.COMMAND_LINE}),W(()=>"move to-next"),de({isForceExecutedBySystem:!0})):s("No pending move")},{intent:T.MoveToPreviousContainer,mode:f.MOVE,action:()=>Fe()?(C({mode:f.COMMAND_LINE}),W(()=>"move to-previous"),de({isForceExecutedBySystem:!0})):s("No pending move")}];var Ui={[k.WORKSPACE]:[...vn,...yn],[k.BOARD]:[...vn,...yn],[k.SWIMLANE]:[...vn,...yn,...Oi],[k.TICKET]:[],[k.FIELD]:[],[k.FIELD_LIST]:[],[k.TEXT]:[]};var Bi=[{intent:T.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(C({mode:f.COMMAND_LINE}),W(()=>`${g.NEW} `),c("Adding new item",null))},{intent:T.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(C({mode:f.COMMAND_LINE}),W(()=>`${g.DELETE} `),c("Deleting item",null))},{intent:T.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(C({mode:f.COMMAND_LINE}),W(()=>""),c("Entering command line mode",null))},{intent:T.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(L.enterChildNode(),c("Entering context",null))},{intent:T.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(L.enterParentNode(),c("Exiting context",null))},{intent:T.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(L.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:T.NavNextItem,mode:f.DEFAULT,action:()=>(L.navigateToNextItem(),c("Navigating to next item",null))},{intent:T.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(L.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:T.NavToNextContainer,mode:f.DEFAULT,action:()=>(L.navigateToNextContainer(),c("Navigating to next container",null))},{intent:T.Edit,mode:f.DEFAULT,action:()=>(C({mode:f.COMMAND_LINE}),W(()=>"edit"),de(),c("Fired command",!0))},{intent:T.SetViewDense,mode:f.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(C({viewMode:"dense"}),c("View set",null))},{intent:T.SetViewWide,mode:f.DEFAULT,action:()=>(C({viewMode:"wide"}),c("View set",null))}];var Fd=500,Ld=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),_i=e=>{let t=Ld(e);t&&W(n=>(n+t).slice(0,Fd))};var ji=[{intent:T.ViewHelp,mode:f.DEFAULT,action:()=>(C({mode:f.HELP}),c("Viewing help",null))},{intent:T.Exit,mode:f.HELP,action:()=>(C({mode:f.DEFAULT}),c("Exiting help",null))},{intent:T.Confirm,mode:f.COMMAND_LINE,action:()=>(de(),c("Executing command",null))},{intent:T.MoveCursorLeft,mode:f.COMMAND_LINE,action:()=>(tr(-1),c("Moving cursor left",null))},{intent:T.MoveCursorRight,mode:f.COMMAND_LINE,action:()=>(tr(1),c("Moving cursor right",null))},{intent:T.MoveCursorLeftOfWord,mode:f.COMMAND_LINE,action:()=>(nr("left"),c("Moving cursor left of word",null))},{intent:T.MoveCursorRightOfWord,mode:f.COMMAND_LINE,action:()=>(nr("right"),c("Moving cursor right of word",null))},{intent:T.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(C({mode:f.DEFAULT}),c("Exiting command line",null))},{intent:T.AutoCompleteCommand,mode:f.COMMAND_LINE,action:()=>(W((e,{remainder:t})=>t?e+t:e),c("Auto-completing command",null))},{intent:T.CaptureInput,mode:f.COMMAND_LINE,action:(e,{sequence:t})=>(_i(t??""),c("Capturing input",null))},{intent:T.EraseInput,mode:f.COMMAND_LINE,action:()=>(Jo(),c("Erasing input",null))},{intent:T.EraseInputWord,mode:f.COMMAND_LINE,action:()=>(Yo(),c("Erasing input word",null))},{intent:T.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(ei(),c("Getting last command from history",null))},{intent:T.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(ti(),c("Getting next command from history",null))}];import Dd from"chalk";var xn=": for command line",$i="q to exit",Wi=`${Dd.hex(M.accent)("m")} to confirm`,gr={[k.WORKSPACE]:[xn],[k.BOARD]:[xn],[k.BOARD+f.COMMAND_LINE]:[xn],[k.SWIMLANE]:[xn],[k.TICKET+f.HELP]:[$i],[k.SWIMLANE+f.HELP]:[$i],[k.TICKET]:[],[k.FIELD]:[],[k.SWIMLANE+f.MOVE]:[Wi],[k.TICKET+f.MOVE]:[Wi]};var hn=e=>e.trim().toLocaleLowerCase(),Od=(e,t)=>{let n=h.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},Ud=e=>{let{tags:t}=v(),n=h.getFieldByTitle(e,"Tags");return n?$(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},Bd=e=>{let{contributors:t}=v(),n=h.getFieldByTitle(e,"Assignees");return n?$(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},Hi=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return hn(e.title??"").includes(n);case"description":return hn(Od(e.id,"Description")).includes(n);case"tag":return Ud(e.id).map(hn).some(l=>l.includes(n));case"assignee":return Bd(e.id).map(hn).some(l=>l.includes(n));default:return!0}};function Ki(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 Vi=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 En,fr,vr=new Set,qi=()=>{for(let e of vr)e()},jd=e=>(vr.add(e),()=>vr.delete(e));function zi(e){let{currentNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return s("derive(): currentNodeId is missing");if(!r)return s("derive(): rootNode is missing");if(!o[r])return s("derive(): unable to find root node");let l=o[t];if(!l)return s("Unable to derive state, currentNode not found");let u=Ki(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,x=gr[p+n]??gr[p]??[],E=[...Bi,...Ui[p]??[],...ji],I=Vi(E),R=$d(o,i),b=R[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,currentNode:l,breadCrumb:m,availableHints:x,availableActions:E,actionIndex:I,selectedNode:b,renderedChildrenIndex:R})}var v=()=>(En||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),En);function gt(e){fr=e;let t=Se(process.cwd()),n=!1;if(!d(t)){let i=Ae(t.value);if(d(i))return s(i.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},viewMode:"dense",mode:f.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProject:n},o=zi(r);return d(o)?o:(En=o.value,qi(),c("State initialized",null))}function re(e){let t=v(),n=e(t),r=zi(n);return d(r)?s(r.message??"Unable to update state"):(En=r.value,qi(),c("State updated",null))}var C=e=>re(t=>({...t,...e}));var me=()=>_d(jd,v,v),$d=(e,t)=>{let n={};for(let r of Object.values(e))Q(r)&&t.length>0&&!t.every(o=>Hi(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},S=e=>v()?.renderedChildrenIndex[e]??[],pr=()=>fr?gt(fr):s("Cannot reset state: no initial workspace found");var L={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.currentNode,n=Math.max(0,e.selectedIndex),r=S(t.id)[n];!r||t.context==="FIELD"||L.navigate({currentNode:r,selectedIndex:S(r.id).length?0:-1})},enterParentNode(){let{currentNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=S(n.id),o=r.findIndex(({id:a})=>a===e.id),i=r.length===0?-1:o>=0?o:0;L.navigate({currentNode:n,selectedIndex:i})},navigateToNextItem:()=>Gi(1),navigateToPreviousItem:()=>Gi(-1),navigateToNextContainer:()=>Xi(1),navigateToPreviousContainer:()=>Xi(-1),navigate:({currentNode:e=v().currentNode,selectedIndex:t})=>{C({currentNodeId:e.id,selectedIndex:t})}},Gi=e=>{let t=v(),n=S(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;L.navigate({selectedIndex:o})},Xi=e=>{let{currentNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!t||!o)return;let i=S(o.id),a=i.findIndex(E=>E.id===t.id);if(a<0)return;let l=i.at(a+e)??i.at(0);if(!l)return;let u=S(l.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),x=u.length?p:-1;L.navigate({currentNode:l,selectedIndex:x})};var It=Wd();function Hd(){let e=Object.values(v().nodes).find(r=>r.context==="WORKSPACE");if(!e)throw new Error("No workspace found in event log");let[t]=S(e.id),[n]=t?S(t.id):[];if(logger.debug("Boot navigation target:",{workspace:e?.id,firstBoard:t?.id,firstSwimlane:n?.id}),n){let r=v().renderedChildrenIndex?.[n.id]??[];return{currentNode:n,selectedIndex:r.length>0?0:-1}}else return t?{currentNode:t,selectedIndex:0}:e?{currentNode:e,selectedIndex:0}:{currentNode:v().nodes[v().rootNodeId],selectedIndex:0}}function Kd(){let e=Hd();L.navigate(e)}function Pi({userId:e,userName:t}){let n=It(),r=It(),o=It(),i=It(),a=It(),l=V(void 0,void 0);if(d(l))return l;let u=V(void 0,void 0);if(d(u))return u;let m=V(u.value,void 0);if(d(m))return m;let p=V(void 0,void 0);if(d(p))return p;let x=V(p.value,void 0);if(d(x))return x;let E=V(x.value,void 0);if(d(E))return E;let I=V(void 0,void 0);return d(I)?I:c("Created default events",[{id:be(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:be(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:be(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:be(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"In progress",parent:r,rank:x.value}},{id:be(),userId:e,userName:t,action:"add.swimlane",payload:{id:a,name:"Done",parent:r,rank:E.value}},{id:be(),userId:e,userName:t,action:"add.board",payload:{id:Zt,name:"Closed",parent:n,rank:m.value}},{id:be(),userId:e,userName:t,action:"add.swimlane",payload:{id:J,name:"Closed",parent:Zt,rank:I.value}},{id:be(),userId:e,userName:t,action:"lock.node",payload:{id:Zt}},{id:be(),userId:e,userName:t,action:"lock.node",payload:{id:J}}])}function fn({hasProject:e,eventLog:t}){if(!e){let o=z.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=gt(o);return d(i)?i:(C({hasProject:!1,mode:f.DEFAULT}),c("Booted uninitialized workspace placeholder",null))}if(!t.some(o=>o.action==="init.workspace"))return s("Initialized Epiq project has no workspace init event");let r=pt(t).filter(d);return r.length>0?s(r.map(o=>o.message).join(`
58
- `)):(Kd(),C({hasProject:!0}),c("State booted successfully",null))}var $e=e=>{let t=ce(e??process.cwd());if(d(t))return t;let n=ct(t.value);if(d(n))return s(n.message);let r=fn({eventLog:n.value,hasProject:!0});return d(r)?s(r.message):c("Booted Epiq state",{root:t.value})},Nn=()=>{let e=yo();return d(e)?s(e.message):e.value.userId?e.value.userName?c("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):s("Unable to retrieve user name"):s("Unable to retrieve user id")},Yi=(e,t)=>{let r=S(e.id).find(o=>o.title===t);return r?S(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},Vd=e=>Yi(e,"Tags").map(t=>h.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),qd=e=>Yi(e,"Assignees").map(t=>h.getContributor(t)).filter(Boolean).map(t=>({id:t.id,name:t.name})),Zi=(e={})=>{let t=$e(e.repoRoot);if(d(t))return t;let n=Object.values(v().nodes).filter(r=>r.context==="BOARD").map(r=>({id:r.id,title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return c("Listed boards",n)},Qi=(e={})=>{let t=$e(e.repoRoot);if(d(t))return t;let n=Object.values(v().nodes).filter(r=>r.context==="SWIMLANE").filter(r=>!e.boardId||r.parentNodeId===e.boardId).map(r=>({id:r.id,title:r.title,boardId:r.parentNodeId,isClosed:r.id===J,readonly:!!r.readonly}));return c("Listed swimlanes",n)},es=e=>{let t=$e(e.repoRoot);if(d(t))return t;let n=Object.values(v().nodes).filter(Q).filter(r=>e.includeClosed||r.parentNodeId!==J).map(r=>({id:r.id,title:ze(r.title),description:Lo(r,"Description"),parentId:r.parentNodeId,isClosed:r.parentNodeId===J,readonly:!!r.readonly,tags:Vd(r),assignees:qd(r)}));return c("Listed issues",n)},ts=e=>{let t=$e(e.repoRoot);if(d(t))return t;let n=Nn();if(d(n))return n;let r=Me(e.parentId,n.value);if(d(r))return r;let o=Gt({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(d(o))return o;let i=o.value,l=Te(i).find(d);if(l)return s(l.message);let u=i.find(m=>m.action==="add.issue")?.payload.id;return u?c("Created issue",{id:u,title:e.title,parentId:e.parentId}):s("Unable to determine created issue id")},ns=e=>{let t=$e(e.repoRoot);if(d(t))return t;let n=Nn();if(d(n))return n;let r=xe(J,e.issueId,{at:"end"},n.value);if(d(r))return r;let o={id:Ji(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:J,rank:r.value}},a=Te([o]).find(d);return a?s(a.message):c("Closed issue",{id:e.issueId})},rs=e=>{let t=$e(e.repoRoot);if(d(t))return t;let n=Nn();if(d(n))return n;let r=xe(e.parentId,e.issueId,e.position??{at:"end"},n.value);if(d(r))return r;let o={id:Ji(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:r.value}},a=Te([o]).find(d);return a?s(a.message):c("Moved issue",{id:e.issueId,parentId:e.parentId})},os=async(e={})=>{let t=ce(e.repoRoot??process.cwd());if(d(t))return s("Sync failed");let n=Nn();if(d(n))return n;let r=await Ht({cwd:t.value,ownEventFileName:we(n.value)});return d(r)?r:c("Synced",r.value)},is=(e={})=>{let t=$e(e.repoRoot);return d(t)?t:c("Retrieved Epiq state",{root:t.value.root,nodes:v().nodes,rootNodeId:v().rootNodeId,currentNode:v().currentNode,selectedIndex:v().selectedIndex,eventLog:v().eventLog})};var Le=e=>({isError:d(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Xd=()=>{let e=new zd({name:"epiq",version:"0.2.30"});return e.registerTool("epiq_state_get",{description:"Get the full current Epiq state, including nodes and event log",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>Le(await is(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:F.object({repoRoot:F.string().optional(),includeClosed:F.boolean().optional()})},async t=>Le(await es(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>Le(await Zi(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:F.object({repoRoot:F.string().optional(),boardId:F.string().optional()})},async t=>Le(await Qi(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue",inputSchema:F.object({title:F.string().min(1),parentId:F.string().min(1),repoRoot:F.string().optional()})},async t=>Le(await ts(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:F.object({issueId:F.string().min(1),repoRoot:F.string().optional()})},async t=>Le(await ns(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:F.object({issueId:F.string().min(1),parentId:F.string().min(1),position:F.discriminatedUnion("at",[F.object({at:F.literal("start")}),F.object({at:F.literal("end")}),F.object({at:F.literal("before"),sibling:F.string().min(1)}),F.object({at:F.literal("after"),sibling:F.string().min(1)})]).optional(),repoRoot:F.string().optional()})},async t=>Le(await rs(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>Le(await os(t))),e},Jd=async()=>{let e=Xd(),t=new Gd;await e.connect(t)};await Jd();export{Xd as createMcpServer,Le as resultJson,Jd as startMcpServer};
24
+ `,ur.writeFileSync(t,n,"utf8"),oe.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)};import{spawn as zd}from"node:child_process";import gr from"node:fs";import Li from"node:path";import Rt from"node:fs";import qd from"node:os";import ve from"node:path";var mr=(e,t)=>{let n=new Map,r=t??((...i)=>JSON.stringify(i)),o=((...i)=>{let d=r(...i);if(!n.has(d)){let l=e(...i).then(u=>(a(u)&&n.delete(d),u));n.set(d,l)}return n.get(d)});return o.clear=()=>n.clear(),o};var bi="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Si=e=>ve.join(Ie,Ot,e),Ri=()=>ve.join(qd.homedir(),de),mn=()=>ve.join(Ri(),"worktrees"),Ai=({repoRoot:e})=>{let t=to(e);return a(t)?s(t.message):c("Resolved state branch root",ve.join(mn(),t.value))},Vd=e=>ve.join(e,Ie),Ge=e=>ve.join(Vd(e),Ot),pr=({root:e,fileName:t})=>ve.join(Ge(e),t),At=e=>{try{return Rt.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return s(t instanceof Error?t.message:String(t))}},pn=()=>{let e=At(Ri());if(a(e))return s(`Ensure epiq home failed.
25
+ `+e.message);let t=At(mn());return a(t)?s(`Ensure worktrees dir failed.
26
+ `+t.message):c("Ensured epiq storage",!0)},wi=e=>{Rt.existsSync(e)&&(oe.debug("[sync] remove path",e),Rt.rmSync(e,{recursive:!0,force:!0}))},Ti=e=>{let t=Ge(e);if(!Rt.existsSync(t))return c("Events dir missing",[]);let n=Rt.readdirSync(t,{withFileTypes:!0}).filter(r=>r.isFile()).map(r=>r.name).filter(r=>r.endsWith(".jsonl")).sort();return c("Listed event files",n)},Mi=(e,t)=>{for(let n of[Ge(e),Ge(t)]){let r=At(n);if(a(r))return s(r.message)}return c("Ensured state branch",void 0)},Pi=async e=>{let t=await L({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return s(`ensure state branch is storage only failed
27
+ `+t.message);let r=t.value.stdout.trim().split(`
28
+ `).filter(Boolean).filter(d=>d!==Ie);if(r.length===0)return c("State branch is storage-only",!1);let o=await L({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(a(o))return s(`Failed to clean storage branch
29
+ ${o.message}`);let i=await it({cwd:e,message:"[epiq:repair-storage-branch]"});return a(i)?s(i.message):c("Cleaned storage branch",!0)},gn=mr(async(e=process.cwd())=>{let t=await L({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?s("Not inside a Git repository"):c("Resolved repo root",t.value.stdout.trim())},e=>ve.resolve(e)),ki=mr(async e=>{let t=await L({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return s(t.message);let n=t.value.stdout.trim(),r=ve.isAbsolute(n)?n:ve.join(e,n);return c("Resolved git dir",r)},e=>ve.resolve(e));var st=e=>{let t=Pe(e);if(a(t))return s("Unable to resolve epiq project root");let n=ke(t.value);return a(n)?s("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},ue="origin";var Fi=15e3,Gd={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Oi=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!gr.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:p,exitCode:1});return}r(s(p));return}let o=zd("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Gd}),i=!1,d="",l="",u=p=>{i||(i=!0,clearTimeout(m),r(p))},m=setTimeout(()=>{o.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${Fi}ms`].join(`
30
+ `);u(n?{stdout:d,stderr:p,exitCode:124}:s(p))},Fi);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",p=>{d+=p}),o.stderr.on("data",p=>{l+=p}),o.on("error",p=>{if(n){u({stdout:d,stderr:p.message,exitCode:1});return}u(s([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
31
+ `)))}),o.on("close",p=>{let x=p??1;if(n){u({stdout:d,stderr:l,exitCode:x});return}if(x!==0){u(s([`git ${e.join(" ")}`,l.trim()||d.trim()||"Git command failed"].filter(Boolean).join(`
32
+ `)));return}u(c("Git command succeeded",{stdout:d,stderr:l,exitCode:x}))})}),L=({args:e,cwd:t})=>Oi({args:e,cwd:t,allowFail:!1}),at=({args:e,cwd:t})=>Oi({args:e,cwd:t,allowFail:!0}),it=async({cwd:e,message:t})=>{let n=await H.commit({cwd:e,message:t});if(a(n))return s(`Failed to create commit
33
+ ${n.message}`);let r=await L({args:["rev-parse","HEAD"],cwd:e});return a(r)?s(`Commit created, but failed to read HEAD SHA
34
+ ${r.message}`):c("Created commit and resolved SHA",r.value.stdout.trim())},wt=async e=>{let t=await ki(e);if(a(t))return s(t.message);let n=t.value,o=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","REBASE_HEAD","rebase-merge","rebase-apply"].filter(i=>gr.existsSync(Li.join(n,i)));return c("Checked for in-progress Git operation",o.length>0)},fr=async({repoRoot:e})=>{let n=(await at({args:["remote","get-url",ue],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},fn=async({repoRoot:e,branch:t})=>{let n=await at({args:["ls-remote","--heads",ue,t],cwd:e});return n.exitCode!==0?s(n.stderr.trim()||`Unable to inspect remote branch ${ue}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},vn=async({repoRoot:e,branch:t})=>{let n=await at({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?c("Local branch exists",!0):n.exitCode===1?c("Local branch missing",!1):s(n.stderr.trim()||`Unable to inspect branch ${t}`)},Di=e=>{try{return gr.realpathSync.native(e)}catch{return Li.resolve(e)}},Ui=async({repoRoot:e,worktreeRoot:t})=>{let n=await L({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return s(n.message);let r=Di(t),o=n.value.stdout.split(`
35
+ `).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(Di).includes(r);return c("Checked worktree registration",o)},vr=async e=>{let t=await at({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},yn=async e=>{let t=await L({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?s(t.message):c("Resolved current branch",t.value.stdout.trim())},Bi=async e=>{let t=await L({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?s(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},_i=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),yr=async({cwd:e,branch:t})=>{let n=await fn({repoRoot:e,branch:t});if(a(n))return s(n.message);if(!n.value)return c("Remote branch missing, skipped pull",!1);let r=await H.fetch({cwd:e,remote:ue,branch:t});if(a(r))return s(`Failed to fetch ${t}
36
+ ${r.message}`);let o=await H.pullRebase({cwd:e,remote:ue,branch:t});return a(o)?s(`Failed during pull --rebase
37
+ ${o.message}`):c("Pulled with rebase",!0)},$i=async e=>{let t=await L({args:["status","--porcelain"],cwd:e});return a(t)?s(t.message):c("Checked state branch changes",t.value.stdout.trim().length>0)},Wi=async e=>{let t=await yn(e);return a(t)?s(t.message):c("Checked detached HEAD state",t.value==="HEAD")};var H={stage:({cwd:e,pathspec:t})=>L({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>L({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>L({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>L({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>L({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 L({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>L({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>L({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>L({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>L({args:["worktree","prune"],cwd:e})};import dt from"node:fs";import Tt from"node:path";var Hi=async e=>{if((await at({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);oe.info("Creating initial commit");let n=await H.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return a(n)?s(n.message):c("Created initial commit",!0)},ji=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Yd=async e=>{let t=await yn(e);if(a(t))return s(t.message);let n=await Bi(e);if(a(n))return s(n.message);let r=`[epiq:sync:${ji(t.value)}:${ji(n.value)}]`;return c("Built sync commit message",r)},xn=async({repoRoot:e,stateBranchName:t})=>{oe.info(`Creating ${t}`);let n=await L({args:["commit-tree",bi,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return s(`Failed to create state branch commit
38
+ ${n.message}`);let r=n.value.stdout.trim(),o=await L({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return a(o)?s(`Failed to create ${t}
39
+ ${o.message}`):c("Created state branch",!0)},Xd=async({repoRoot:e,stateBranchName:t})=>{let n=await vn({repoRoot:e,branch:t});if(a(n))return s(`Ensure local state branch failed
40
+ `+n.message);if(n.value)return c("Local state branch already exists",!1);let r=await fr({repoRoot:e});if(a(r))return s(`Ensure local state branch failed
41
+ `+r.message);if(!r.value)return xn({repoRoot:e,stateBranchName:t});let o=await fn({repoRoot:e,branch:t});if(a(o))return s(`Ensure local state branch failed
42
+ `+o.message);if(!o.value)return xn({repoRoot:e,stateBranchName:t});let i=await H.fetch({cwd:e,remote:ue,branch:t});if(a(i))return s(`Failed to fetch ${t} from remote
43
+ ${i.message}`);let d=await L({args:["branch","--track",t,`${ue}/${t}`],cwd:e});return a(d)?s(`Failed to create local ${t} from remote
44
+ ${d.message}`):c("Created local state branch from remote",!0)},Jd=async({repoRoot:e,branch:t})=>{let n=await L({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return s(n.message);let r=n.value.stdout.split(`
45
+ `),o=null;for(let i of r){if(i.startsWith("worktree ")){o=i.slice(9);continue}if(i===`branch refs/heads/${t}`&&o)return c("Found worktree for branch",o)}return c("No worktree found for branch",null)},Zd=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=At(Tt.dirname(t));if(a(r))return s(`Failed to create state branch worktree
46
+ `+r.message);dt.existsSync(t)&&!dt.existsSync(Tt.join(t,".git"))&&(oe.info("Removing broken state branch worktree path"),wi(t)),oe.info("Creating state branch worktree");let o=await H.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(o)?s(`Failed to create state branch worktree
47
+ ${o.message}`):c("Created state branch worktree",!0)},xr=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await Jd({repoRoot:e,branch:n});if(a(r))return s(r.message);let o=Tt.resolve(t),i=r.value?Tt.resolve(r.value):null;if(i&&i===o&&dt.existsSync(i))return c("State branch already checked out in expected worktree",!1);if(i&&i!==o){oe.info("Moving state branch worktree to expected location");let u=await H.worktreeRemove({cwd:e,worktreeRoot:i});if(a(u))return s(`Failed to remove existing state branch worktree
48
+ ${u.message}`)}if(i&&!dt.existsSync(i)){oe.info("Pruning stale state branch worktree");let u=await H.worktreePrune({cwd:e});if(a(u))return s(`Failed to prune stale worktrees
49
+ ${u.message}`)}let d=await Ui({repoRoot:e,worktreeRoot:t});if(a(d))return s(d.message);let l=dt.existsSync(t);if(d.value&&l)return c("State branch worktree already exists",!1);if(d.value&&!l){oe.info("Pruning missing registered state branch worktree");let u=await H.worktreePrune({cwd:e});if(a(u))return s(`Failed to prune stale worktrees
50
+ ${u.message}`)}return Zd({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Qd=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await yn(e);if(a(n))return s(n.message);if(n.value===t)return c("State branch already checked out",!1);let r=await H.checkout({cwd:e,branch:t});return a(r)?s(`Failed to checkout ${t}
51
+ ${r.message}`):c("Checked out state branch",!0)},ec=async({repoRoot:e,stateBranchRoot:t})=>{let n=await vr(t);if(a(n))return s(n.message);if(n.value)return c("State branch upstream already configured",!1);let r=await fr({repoRoot:t});if(a(r))return s(r.message);if(!r.value)return c("No remote available for state branch upstream",!1);let o=st(e);if(a(o))return o;let i=o.value,d=await fn({repoRoot:t,branch:i});if(a(d))return s(d.message);if(!d.value)return c("Remote state branch missing; upstream will be configured on first push",!1);oe.info(`Configuring ${i} upstream`);let l=await H.fetch({cwd:t,remote:ue,branch:i});if(a(l))return s(`Failed to fetch ${i}
52
+ ${l.message}`);let u=await H.setUpstream({cwd:t,branch:i,upstream:`${ue}/${i}`});return a(u)?s(`Failed to set state branch upstream
53
+ ${u.message}`):c("Configured state branch upstream",!0)},Nn=async({stateBranchRoot:e,eventFileName:t})=>{let n=Si(t),r=Tt.join(e,n);if(!dt.existsSync(r))return c("No event file to stage",void 0);let o=await H.stage({cwd:e,pathspec:[n]});return a(o)?s(`Failed to stage state branch event file
54
+ ${o.message}`):c("Staged state branch event file",void 0)},Ki=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Yd(e);return a(n)?s(`Create state branch sync commit failed
55
+ `+n.message):it({cwd:t,message:n.value})},Mt=async({repoRoot:e,stateBranchRoot:t})=>{let n=await vr(t);if(a(n))return s(n.message);let r=st(e);if(a(r))return r;let o=r.value,i=n.value?await H.push({cwd:t}):await H.push({cwd:t,remote:ue,branch:o,setUpstream:!0});return a(i)?s(`Failed during state branch push
56
+ ${i.message}`):c("Pushed state branch",!0)},qi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=st(e);if(a(o))return o;let i=o.value,d=[pn(),await Xd({repoRoot:e,stateBranchName:i}),await xr({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await Qd({stateBranchRoot:t,stateBranchName:i}),await Pi(t),n?await ec({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of d){if(a(l))return s(l.message);r=r||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage (readonly)",r)};import hn from"node:fs";import hr from"node:path";import{decodeTime as tc}from"ulid";var Nr=e=>{let[t,n]=e.id;return`${t}:${n??""}`},Vi=e=>{let[t]=e.id;return tc(t)},nc=e=>{let{userId:t,userName:n,...r}=e;return r},rc=e=>e.length===0?"":e.map(t=>JSON.stringify(nc(t))).join(`
57
+ `)+`
58
+ `,oc=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(Nr(r),r);return[...n.values()].sort((r,o)=>{let i=Vi(r)-Vi(o);return i!==0?i:Nr(r).localeCompare(Nr(o))})},Ir=({sourceFile:e,targetFile:t})=>{let n=$t(e);if(a(n))return s(n.message);let r=$t(t);if(a(r))return s(r.message);let o=oc(r.value,n.value),i=rc(o);return(hn.existsSync(t)?hn.readFileSync(t,"utf8"):"")===i?c("Event file already merged",!1):(hn.mkdirSync(hr.dirname(t),{recursive:!0}),hn.writeFileSync(t,i,"utf8"),c("Merged event file",!0))},In=({repoRoot:e,stateBranchRoot:t})=>{let n=Ti(t);if(a(n))return s(n.message);let r=Ge(t),o=Ge(e),i=!1;for(let d of n.value){let l=hr.join(r,d),u=hr.join(o,d),m=Ir({sourceFile:l,targetFile:u});if(a(m))return s(m.message);i=i||m.value}return c("Hydrated event files from state branch",i)};var sc=async e=>{let t=await L({cwd:e,args:["status","--porcelain"]});return a(t)?t:c("Checked git diff",t.value.stdout.trim().length>0)},j=(e,t)=>s(`[${e}] ${t}`),Gi=async()=>{let e=eo(),t=await gn(process.cwd());if(a(t))return j(1,t.message);let n=t.value,r=await wt(n);if(a(r))return j(2,r.message);if(r.value)return j(2,"Cannot initialize Epiq while a git operation is in progress");let o=await sc(n);if(a(o))return j(2.5,o.message);if(o.value)return j(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(kn(n))return j(4,"Epiq project already initialized");let i=Kt();if(!i.isSetupDone||!i.userName)return j(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let d=_(),l=d.userName,u=d.userId;if(!u||!l)return j(5,"Missing Epiq user id");let m=e.stateBranch,p=await vn({repoRoot:n,branch:m});if(a(p))return j(6,p.message);let x=await xn({repoRoot:n,stateBranchName:e.stateBranch});if(a(x))return j(6,x.message);let h=pn();if(a(h))return j(7,h.message);let C=zi.join(mn(),e.projectId),R=await xr({repoRoot:n,stateBranchRoot:C,stateBranchName:e.stateBranch});if(a(R))return j(8,R.message);let S=zi.join(C,".epiq");ic.mkdirSync(S,{recursive:!0});let E=gi({userId:u,userName:l});if(a(E))return j(9,E.message);for(let Tn of E.value){let Dr=jt({event:Tn,rootDir:C});if(a(Dr))return j(9,Dr.message)}let A=await Nn({stateBranchRoot:C,eventFileName:Ee({userId:u,userName:l})});if(a(A))return j(10,A.message);let K=await it({cwd:C,message:"[epiq:init]"});if(a(K))return j(10,K.message);let Te=await Ci(n);if(a(Te))return j(12,Te.message);let ie=no({repoRoot:n,fileContents:e});if(a(ie))return j(13,ie.message);let wr=await H.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(wr))return j(14,wr.message);let Tr=await H.commit({cwd:n,message:"[epiq:init-project]"});if(a(Tr))return j(14,Tr.message);let Mr=In({repoRoot:n,stateBranchRoot:C});if(a(Mr))return j(15,Mr.message);let wn="Project initialized!",Pr=await Mt({repoRoot:n,stateBranchRoot:C});a(Pr)&&(wn+=` Warn: [init:16] ${Pr.message}`);let kr=await H.push({cwd:n});a(kr)&&(wn+=` Warn: [init:17] ${kr.message}`);let Fr=Fe(E.value).filter(a);if(Fr.length>0)return j(18,Fr.map(Tn=>Tn.message).join(`
59
+ `));let{rootNodeId:Ms,nodes:Ps}=f();return D.navigate({currentNode:Ps[Ms],selectedIndex:0}),I({hasProject:!0,mode:g.DEFAULT}),c(wn,null)};import{ulid as dc}from"ulid";import{ulid as ac}from"ulid";var Yi=null,Be=()=>structuredClone(Yi),Pt=e=>Yi=e,Xi=()=>{let{currentNode:e,selectedIndex:t}=f(),r=b(e.id)[t];return r?c("Resolved selected child",r):s("Target node not found")};var Ji=({id:e,parentId:t,position:n={at:"end"}})=>{let r=q();if(a(r))return s("Unable to resolve user ID");let o=ye(t,e,n,r.value);return a(o)?o:c("Created pending move state",{id:ac(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value}})},Zi=e=>{Pt(e);let t=vt(e,!0);return a(t)?t:c("Node moved successfully",t.value)};function Er(e){let t=Xi();if(a(t))return t;let{currentNode:n,nodes:r}=f();if(!n.parentNodeId)return s("Missing parent node id");let o=r[n.parentNodeId];if(!o)return s("Missing parent node");let i=$(o.id),d=i.findIndex(({id:m})=>m===n.id);if(d<0)return s("Current node not found among siblings");let l=i[d+e];if(!l)return s("Missing sibling node");let u=Ji({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Zi(u.value)}function Cr(e){let t=Xi();if(a(t))return t;let{currentNode:n,selectedIndex:r}=f(),i=$(n.id)[r+e];if(!i)return s("Missing sibling node");let d=Ji({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return a(d)?d:Zi(d.value)}var Qi=()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{modifier:t}=ee().commandMeta,n=()=>{let l=Be();if(!l)return s("No pending move state");let u=l.payload.id;if(!f().nodes[u])return s("Moved node not found");let p=l.payload.parent,x=f().nodes[p];if(!x)return s("Move parent not found");let h=b(p).findIndex(C=>C.id===u);return h===-1?s("Moved node not found among rendered children"):(D.navigate({currentNode:x,selectedIndex:h}),c("Synchronized navigation to moved node",null))},r=l=>{if(a(l))return s(l.message);let u=n();return a(u)?s(u.message):c("Updated move preview",null)},{currentNode:o,selectedIndex:i}=f(),d=b(o.id)[i];if(!d)return I({mode:g.DEFAULT}),s("No move target");if(t==="start"){if(d.readonly)return s("Target node is read-only");if(i===-1)return s("No item selected");if(!d.parentNodeId)return s("Target has no parent");let l=$(d.parentNodeId),u=l.findIndex(({id:R})=>R===d.id);if(u===-1)return s("Target not found among siblings");let m=l[u-1],p=l[u+1],x=p!=null?{at:"before",sibling:p.id}:m!=null?{at:"after",sibling:m.id}:{at:"start"},h=ye(d.parentNodeId,d.id,x,e.value);if(a(h))return h;Pt({id:dc(),action:"move.node",payload:{id:d.id,parent:d.parentNodeId,rank:h.value},...e.value}),I({mode:g.MOVE});let C=n();return a(C)?s(C.message):c("Move initialized",null)}if(t==="next")return I({mode:g.MOVE}),r(Cr(1));if(t==="previous")return I({mode:g.MOVE}),r(Cr(-1));if(t==="to-next")return I({mode:g.MOVE}),r(Er(1));if(t==="to-previous")return I({mode:g.MOVE}),r(Er(-1));if(t==="confirm"){I({mode:g.DEFAULT});let l=Be();if(!l)return s("No pending move to confirm");let u=W(l);if(a(u))return u;let m=n();return a(m)?s(m.message):(Pt(null),c("Moved item",null))}return t==="cancel"?(Pt(null),I({mode:g.DEFAULT}),c("Cancelling move",null)):s("Invalid move modifier")};import cc from"zod";var es=()=>{let e=ee().commandMeta.inputString,t=cc.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=ze({autoSyncDebounceMs:t.data});return a(n)?n:(ge({autoSyncIntervalMs:t.data}),I({mode:g.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))};var ts=()=>{let e=ee().commandMeta.modifier;if(e!=="yes"&&e!=="no")return s("Invalid response");let t=io(e),n=ze({autoSync:t});return a(n)?n:(ge({autoSync:t}),I({mode:g.DEFAULT}),c(`Auto sync set to "${e}"`,null))};var ns=e=>Object.values(f().tags).find(t=>t.name===e),rs=e=>Object.values(f().contributors).find(t=>t.name===e),os=[{systemOnly:!0,intent:w.Move,mode:g.COMMAND_LINE,action:Qi},{intent:w.Delete,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=f(),r=b(t.id)[n];return r?W({id:V(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.Filter,mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ee().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(l=>Q(v.FILTER).map(u=>u.split(n)[0]).includes(l))(r))return s("Invalid filter modifier");let d={target:r,operator:"=",value:t.trim()};return ce(l=>({...l,filters:e==="clear"?[]:[...l.filters,d],mode:g.DEFAULT})),c("Viewing help",null)}},{intent:w.ViewHelp,mode:g.COMMAND_LINE,action:()=>(I({mode:g.HELP}),c("Viewing help",null))},{intent:w.CloseIssue,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=f(),r=b(t.id)[n];if(!r)return s("Unable to close issue, no target found");if(!ne(r))return s("Cannot close in this context");let o=f().nodes[te];if(!o)return s("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return s("Issue is already closed");let i=ye(o.id,r.id,{at:"end"},e.value);if(a(i))return i;let d=W({id:V(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:i.value},...e.value});return a(d)?d:c("Issue closed",null)},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.ReopenIssue,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=f(),r=b(t.id)[n];if(!r)return s("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):Qe(r.id,"TICKET");if(a(o))return s("Cannot reopen in this context");let i=o.value,d=f().nodes[te];if(!d)return s("Unable to locate closed swimlane");if(i.parentNodeId!==d.id)return s("Issue is not closed");if(!ne(i))return s("Target node is not issue");let l=fi(i);if(!l)return s("Unable to resolve previous parent from issue history");if(l===d.id)return s("Previous parent resolves to closed swimlane");let u=f().nodes[l];if(!u)return s("Previous parent no longer exists");let m=ye(u.id,i.id,{at:"end"},e.value);if(a(m))return m;let p=W({id:V(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:m.value},...e.value});return a(p)?p:c("Issue reopened",null)},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.Init,mode:g.COMMAND_LINE,action:Gi},{intent:w.NewItem,mode:g.COMMAND_LINE,action:(e,t)=>{let n=q();if(a(n))return s("Unable to resolve user ID");if(!t.inputString)return s(`provide a name for your ${t.modifier}`);let{breadCrumb:r,currentNode:o,selectedIndex:i}=f(),d=l=>{let u=W(l);if(a(u))return u;let m=N.getNode(u.value.result.id);if(!m)return s("Created node not found");if(!m.parentNodeId)return u;let p=N.getNode(m.parentNodeId);return p?(D.navigate({currentNode:p,selectedIndex:N.getSiblings(m.parentNodeId).findIndex(({id:x})=>x===m.id)}),u):s("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:l}=f(),u=N.getNode(l);if(!u)return s("Workspace not found");let m=De(u.id,n.value);return a(m)?m:d({id:V(),action:"add.board",payload:{id:V(),name:t.inputString,parent:u.id,rank:m.value},...n.value})}if(t.modifier==="swimlane"){let l=Oe(r,"BOARD");if(a(l))return s("Unable to add swimlane in this context");let u=De(l.value.id,n.value);return a(u)?u:d({id:V(),action:"add.swimlane",payload:{id:V(),name:t.inputString,parent:l.value.id,rank:u.value},...n.value})}if(t.modifier==="issue"){let l=b(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&l?.context==="SWIMLANE"?l:(()=>{let E=Oe(r,"SWIMLANE");return a(E)?null:E.value})();if(!u)return s("Unable to add issue in this context");let m=De(u.id,n.value);if(a(m))return m;let p=ln({name:t.inputString,parent:u.id,rank:m.value,user:n.value});if(a(p))return p;let x=p.value,h=Fe(x);if(h.some(E=>a(E)))return s("Issue create failed: "+h.filter(a).map(E=>E.message).filter(Boolean).join(", "));let C=h[0];if(!C||a(C))return s("Issue creation failed");let S=x.find(E=>E.action==="add.issue")?.payload.id;return S?(D.navigate({currentNode:u,selectedIndex:N.getSiblings(u.id).findIndex(({id:E})=>E===S)}),c("Issue created",null)):s("Unable to determine ticket id")}return c("Success",null)},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.Rename,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=f(),r=b(t.id)[n];if(!r)return s("Missing node");if(r.readonly)return s("Cannot rename readonly node");let o=Oo();return o?W({id:V(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.UntagTicket,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=ns(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=f();if(!i)return s("Invalid untag target");let d=Qe(i.id,"TICKET");if(a(d))return s("Unable to untag issue in this context");let l=d.value,u=N.getFieldByTitle(l.id,"Tags");if(!u)return s("Unable to locate tags field");let m=b(u.id).find(p=>p.props?.value===o.id);return m?W({id:V(),action:"untag.issue",payload:{id:m.id,target:l.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.TagTicket,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=f(),d=b(i.id)[o];if(!d)return s("Invalid tag target");let l=Qe(d.id,"TICKET");if(a(l))return s("Unable to tag issue in this context");let u=l.value,m=ns(r),p;if(m)p=m.id;else{let R=V(),S=W({id:V(),action:"create.tag",payload:{id:R,name:r},userId:e.value.userId,userName:e.value.userName});if(a(S))return S;p=S.value.result.id}let x=N.getFieldByTitle(u.id,"Tags");if(!x)return s("Unable to locate tags field");if(b(x.id).some(R=>R.props?.value===p))return s("Already tagged with that tag");let C=De(x.id,e.value);return a(C)?C:W({id:V(),action:"tag.issue",payload:{id:V(),target:u.id,tagId:p,rank:C.value},...e.value})},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.AssignUserToTicket,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=f(),d=b(i.id)[o];if(!d)return s("Invalid assign target");let l=Qe(d.id,"TICKET");if(a(l))return s("Unable to assign issue in this context");let u=l.value,m=rs(r),p;if(m)p=m.id;else{let R=V(),S=W({id:V(),action:"create.contributor",payload:{id:R,name:r},userId:e.value.userId,userName:e.value.userName});if(a(S))return S;p=S.value.result.id}let x=N.getFieldByTitle(u.id,"Assignees");if(!x)return s("Unable to locate assignees field");if(b(x.id).some(R=>R.props?.value===p))return s("Assignee already assigned");let C=De(x.id,e.value);return a(C)?C:W({id:V(),action:"assign.issue",payload:{id:V(),target:u.id,contributor:p,rank:C.value},...e.value})},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.UnassignUserFromTicket,mode:g.COMMAND_LINE,action:()=>{let e=q();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ee().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=rs(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=f();if(!i)return s("Invalid unassign target");let d=Qe(i.id,"TICKET");if(a(d))return s("Unable to unassign in this context");let l=d.value,u=N.getFieldByTitle(l.id,"Assignees");if(!u)return s("Unable to locate assignees field");let m=b(u.id).find(p=>p.props?.value===o.id);return m?W({id:V(),action:"unassign.issue",payload:{id:m.id,target:l.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${r}"`)},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.Sync,mode:g.COMMAND_LINE,action:async()=>{if(f().syncStatus.status==="syncing")return s("Sync already in progress");let e=ri();U(()=>""),I({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:n}=_();if(!t)return s("Unable to resolve userId");if(!n)return s("Unable to resolve userName");let r=q();if(a(r)||!r.value)return s("Unable to resolve event log path");let o=Ee(r.value),i=await Ze({ownEventFileName:o});if(a(i))return I({syncStatus:{msg:i.message,status:"outOfSync"}}),s(`Unable to sync state. ${i.message}`);let d=Pe(process.cwd());if(a(d))return d;let l=mt(d.value);if(a(l))return s(`Unable to load events. ${l.message}`);let u=un({eventLog:l.value,hasProject:!0});if(a(u))return s(`Unable to boot synced state. ${u.message}`);I({hasProject:!0,syncStatus:{msg:"Synced",status:"synced"},mode:g.DEFAULT});let m=oi(e);return a(m)?m:c("Synced",!0)}},{intent:w.Peek,mode:g.COMMAND_LINE,action:async()=>{let e=Oe(f().breadCrumb,"BOARD");if(a(e))return e;let t=fe(process.cwd());if(a(t))throw new Error(t.message);let n=mt(t.value);if(a(n))return s(n.message);let r=n.value,{modifier:o}=ee().commandMeta,i;if(o==="now"){let h=br();if(a(h))return h;let C=yt(r);return C.some(a)?s(C.map(R=>R.message).join(", ")):(I({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}if(o==="prev"){let h=f().eventLog.at(-2),C=Vn(h);if(C===null)return s("No previous event to peek");i=C}else if(o==="next"){let h=f().unappliedEvents.at(0),C=Vn(h);if(C===null)return s("No next event to peek");i=C}else{let h=Gt(o);if(!h)return s("Invalid peek date");i=h.getTime()}let d=e.value.id,{appliedEvents:l,unappliedEvents:u}=Vr(r,i),m=br();if(a(m))return m;let p=yt(l);if(p.some(a))return s(p.map(h=>h.message).join(", "));let x=f().nodes[d];return x?(D.navigate({currentNode:x,selectedIndex:0}),I({mode:g.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),c("Peeking ",!0)):s("Board did not exist at peek date")}},{intent:w.Export,mode:g.COMMAND_LINE,action:async()=>{let e=await ti();return a(e)?e:(I({mode:g.DEFAULT}),c("Export successful",!0))}},{intent:w.Exit,mode:g.COMMAND_LINE,action:async()=>(D.exit(),c("Exit successful",!0))},{intent:w.Edit,mode:g.COMMAND_LINE,action:(e,t)=>{if(t.modifier===Le.DESCRIPTION)return Ni();if(t.modifier===Le.TITLE){let n=q();if(a(n))return s("Unable to resolve user ID");let{currentNode:r,selectedIndex:o}=f(),i=b(r.id)[o];if(!i)return s("Missing node");if(i.readonly)return s("Cannot rename readonly node");let d=t.inputString.trim();return d?W({id:V(),action:"edit.title",payload:{id:i.id,name:d},...n.value}):s("Provide a new name")}return s("Unknown edit command")},onSuccess:()=>I({mode:g.DEFAULT})},{intent:w.Config,mode:g.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case Y.USERNAME:{let{userId:r,preferredEditor:o,userName:i}=_(),d=n||i,l=r??V();if(!d||!l)return s("Unable to resolve user name or id");let u=ze({userName:d,userId:l,preferredEditor:o??""});return a(u)?u:(ge({userName:d,userId:l}),I({mode:g.DEFAULT}),c(`Username set to "${d}"`,null))}case Y.EDITOR:{if(!n)return s("No editor provided");let r=ze({preferredEditor:n});return a(r)?r:(ge({preferredEditor:n}),I({mode:g.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case Y.VIEW:return n!=="wide"&&n!=="dense"?s("Invalid view mode"):(ge({viewMode:n}),c(`View set to "${n}"`,null));case Y.AUTOSYNC:return ts();case Y.SYNC_DEBOUNCE_MS:return es();default:return s("Unknown config command")}}}];var lc=new Set(["peek","filter","view-help"]),me=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ee();if(!t)return s("No command to confirm");if(!e&&n===He.Invalid)return s("Invalid command");let i=Uo(t);ko();let{readOnly:d}=f();if(d&&!lc.has(i))return It({status:Me.Fail,message:"Command not available in readonly state",value:null});let l=os.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===i);if(!l)return It({status:Me.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return It({status:Me.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?It(u):(Fo({addToHistory:!e}),l.onSuccess?.(),_().autoSync&&Qr(),u)};var En=[{intent:T.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(I({mode:g.COMMAND_LINE}),U(()=>"move cancel"),me({isForceExecutedBySystem:!0}))},{intent:T.InitMove,mode:g.DEFAULT,description:"[m] move init/confirm",action:()=>(I({mode:g.COMMAND_LINE}),U(()=>"move start"),me({isForceExecutedBySystem:!0}))},{intent:T.ConfirmMove,mode:g.MOVE,action:()=>(I({mode:g.COMMAND_LINE}),U(()=>"move confirm"),me({isForceExecutedBySystem:!0}))}],Cn=[{intent:T.MovePreviousItem,mode:g.MOVE,action:()=>Be()?(I({mode:g.COMMAND_LINE}),U(()=>"move previous"),me({isForceExecutedBySystem:!0})):s("No pending move")},{intent:T.MoveNextItem,mode:g.MOVE,action:()=>Be()?(I({mode:g.COMMAND_LINE}),U(()=>"move next"),me({isForceExecutedBySystem:!0})):s("No pending move")}],is=[{intent:T.MoveToNextContainer,mode:g.MOVE,action:()=>Be()?(I({mode:g.COMMAND_LINE}),U(()=>"move to-next"),me({isForceExecutedBySystem:!0})):s("No pending move")},{intent:T.MoveToPreviousContainer,mode:g.MOVE,action:()=>Be()?(I({mode:g.COMMAND_LINE}),U(()=>"move to-previous"),me({isForceExecutedBySystem:!0})):s("No pending move")}];var ss={[P.WORKSPACE]:[...En,...Cn],[P.BOARD]:[...En,...Cn],[P.SWIMLANE]:[...En,...Cn,...is],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var as=[{intent:T.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(I({mode:g.COMMAND_LINE}),U(()=>`${v.NEW} `),c("Adding new item",null))},{intent:T.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(I({mode:g.COMMAND_LINE}),U(()=>`${v.DELETE} `),c("Deleting item",null))},{intent:T.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(I({mode:g.COMMAND_LINE}),U(()=>""),c("Entering command line mode",null))},{intent:T.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,currentNode:t}=f();if(!$(e?.id??"")?.length){if(e?.title===G.DESCRIPTION)return U(()=>v.EDIT+"description "),I({mode:g.COMMAND_LINE}),c("Propose command",!0);if(e?.title===G.ASSIGNEES)return U(()=>v.ASSIGN+" "),I({mode:g.COMMAND_LINE}),c("Propose command",!0);if(e?.title===G.TAGS)return U(()=>v.TAG+" "),I({mode:g.COMMAND_LINE}),c("Propose command",!0);if(t.title===G.DESCRIPTION&&e?.context==="TEXT")return U(()=>v.EDIT+"description "),I({mode:g.COMMAND_LINE}),c("Propose command",!0)}return D.enterChildNode(),c("Entering context",null)}},{intent:T.Exit,mode:g.DEFAULT,description:"[q] exit context",action:()=>(D.enterParentNode(),c("Exiting context",null))},{intent:T.NavPreviousItem,mode:g.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(D.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:T.NavNextItem,mode:g.DEFAULT,action:()=>(D.navigateToNextItem(),c("Navigating to next item",null))},{intent:T.NavToPreviousContainer,mode:g.DEFAULT,action:()=>(D.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:T.NavToNextContainer,mode:g.DEFAULT,action:()=>(D.navigateToNextContainer(),c("Navigating to next container",null))},{intent:T.Edit,mode:g.DEFAULT,action:()=>(I({mode:g.COMMAND_LINE}),U(()=>"edit"),me(),c("Fired command",!0))},{intent:T.SetViewDense,mode:g.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(ge({viewMode:"dense"}),c("View set",null))},{intent:T.SetViewWide,mode:g.DEFAULT,action:()=>(ge({viewMode:"wide"}),c("View set",null))}];var uc=500,mc=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),ds=e=>{let t=mc(e);t&&U(n=>(n+t).slice(0,uc))};var cs=[{intent:T.ViewHelp,mode:g.DEFAULT,action:()=>(I({mode:g.HELP}),c("Viewing help",null))},{intent:T.Exit,mode:g.HELP,action:()=>(I({mode:g.DEFAULT}),c("Exiting help",null))},{intent:T.Confirm,mode:g.COMMAND_LINE,action:()=>(me(),c("Executing command",null))},{intent:T.MoveCursorLeft,mode:g.COMMAND_LINE,action:()=>(Qn(-1),c("Moving cursor left",null))},{intent:T.MoveCursorRight,mode:g.COMMAND_LINE,action:()=>(Qn(1),c("Moving cursor right",null))},{intent:T.MoveCursorLeftOfWord,mode:g.COMMAND_LINE,action:()=>(er("left"),c("Moving cursor left of word",null))},{intent:T.MoveCursorRightOfWord,mode:g.COMMAND_LINE,action:()=>(er("right"),c("Moving cursor right of word",null))},{intent:T.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(I({mode:g.DEFAULT}),c("Exiting command line",null))},{intent:T.AutoCompleteCommand,mode:g.COMMAND_LINE,action:()=>(U((e,{remainder:t})=>t?e+t:e),c("Auto-completing command",null))},{intent:T.CaptureInput,mode:g.COMMAND_LINE,action:(e,{sequence:t})=>(ds(t??""),c("Capturing input",null))},{intent:T.EraseInput,mode:g.COMMAND_LINE,action:()=>(Mo(),c("Erasing input",null))},{intent:T.EraseInputWord,mode:g.COMMAND_LINE,action:()=>(Po(),c("Erasing input word",null))},{intent:T.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(Do(),c("Getting last command from history",null))},{intent:T.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(Lo(),c("Getting next command from history",null))}];import pc from"chalk";var bn=": for command line",ls="q to exit",us=`${pc.hex(M.accent)("m")} to confirm`,Sr={[P.WORKSPACE]:[bn],[P.BOARD]:[bn],[P.BOARD+g.COMMAND_LINE]:[bn],[P.SWIMLANE]:[bn],[P.TICKET+g.HELP]:[ls],[P.SWIMLANE+g.HELP]:[ls],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+g.MOVE]:[us],[P.TICKET+g.MOVE]:[us]};var Sn=e=>e.trim().toLocaleLowerCase(),gc=(e,t)=>{let n=N.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},fc=e=>{let{tags:t}=f(),n=N.getFieldByTitle(e,"Tags");return n?$(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},vc=e=>{let{contributors:t}=f(),n=N.getFieldByTitle(e,"Assignees");return n?$(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},ms=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return Sn(e.title??"").includes(n);case"description":return Sn(gc(e.id,G.DESCRIPTION)).includes(n);case"tag":return fc(e.id).map(Sn).some(l=>l.includes(n));case"assignee":return vc(e.id).map(Sn).some(l=>l.includes(n));default:return!0}};function ps(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 d=o[o.length-1];return!d||d.id!==n?s("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var gs=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 Rn,Rr,Ar=new Set,fs=()=>{for(let e of Ar)e()},xc=e=>(Ar.add(e),()=>Ar.delete(e));function vs(e){let{currentNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:i}=e;if(!t)return s("derive(): currentNodeId is missing");if(!r)return s("derive(): rootNode is missing");if(!o[r])return s("derive(): unable to find root node");let l=o[t];if(!l)return s("Unable to derive state, currentNode not found");let u=ps(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,x=Sr[p+n]??Sr[p]??[],h=[...as,...ss[p]??[],...cs],C=gs(h),R=Nc(o,i),S=R[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,currentNode:l,breadCrumb:m,availableHints:x,availableActions:h,actionIndex:C,selectedNode:S,renderedChildrenIndex:R})}var f=()=>(Rn||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),Rn);function xt(e){Rr=e;let t=Pe(process.cwd()),n=!1;if(!a(t)){let i=ke(t.value);if(a(i))return s(i.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:g.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,currentNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],timeMode:"live",hasProject:n},o=vs(r);return a(o)?o:(Rn=o.value,fs(),c("State initialized",null))}function ce(e){let t=f(),n=e(t),r=vs(n);return a(r)?s(r.message??"Unable to update state"):(Rn=r.value,fs(),c("State updated",null))}var I=e=>ce(t=>({...t,...e}));var xe=()=>yc(xc,f,f),Nc=(e,t)=>{let n={};for(let r of Object.values(e))ne(r)&&t.length>0&&!t.every(o=>ms(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 d=e[o.id],l=e[i.id];return!d||!l?0:d.rank.localeCompare(l.rank)});return n},b=e=>f()?.renderedChildrenIndex[e]??[],br=()=>Rr?xt(Rr):s("Cannot reset state: no initial workspace found");var ys=(e="Syncing...")=>{I({syncStatus:{status:"syncing",msg:e}})},xs=(e="Synced")=>{I({syncStatus:{status:"synced",msg:e}})},hc=e=>{I({syncStatus:{status:"outOfSync",msg:e}})},pe=e=>(hc(e),s(e));var Ec=({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=pr({root:e,fileName:n}),o=pr({root:t,fileName:n});return Ic.existsSync(r)?Ir({sourceFile:r,targetFile:o}):c("Local own event file missing, nothing to merge",!1)},Cc=async({cwd:e,ensureUpstream:t})=>{let n=await gn(e);if(a(n))return s(n.message);let r=n.value,o=Ai({repoRoot:r});if(a(o))return s(o.message);let i=o.value,d=await wt(r);if(a(d))return s(d.message);if(d.value)return s("Cannot sync while a git operation is in progress in the current repo");let l=await Hi(r);if(a(l))return s(l.message);let u=await qi({repoRoot:r,stateBranchRoot:i,ensureUpstream:t});if(a(u))return s(u.message);let m=await wt(i);if(a(m))return s(m.message);if(m.value)return s("Cannot sync while a git operation is in progress in the state branch");let p=Mi(r,i);return a(p)?s(p.message):c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:i,bootstrapped:u.value})},Ns=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=Ec({repoRoot:e,stateBranchRoot:t,ownEventFileName:n});if(a(r))return s(r.message);let o=await $i(t);if(a(o))return s(o.message);if(!r.value&&!o.value)return c("Own event file already up to date in state branch",{createdCommit:!1});let i=await Nn({stateBranchRoot:t,eventFileName:n});if(a(i))return s(i.message);let d=await Ki({repoRoot:e,stateBranchRoot:t});return a(d)?s(d.message):c("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:d.value})},Ze=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(t.includes("/")||t.includes("\\"))return s("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return s("Own event file must end with .jsonl");ys("Syncing");let n=await Cc({cwd:e,ensureUpstream:!0});if(a(n))return pe(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,d=await Wi(r);if(a(d))return pe(d.message);if(d.value)return pe("Cannot run :sync while the repository is in detached HEAD state");let l=!1,u,m=!1,p=!1,x=!1,h=st(r);if(a(h))return pe(h.message);let C=h.value,R=await yr({cwd:o,branch:C});if(a(R))return pe(R.message);m=R.value;let S=In({repoRoot:r,stateBranchRoot:o});if(a(S))return pe(S.message);x=S.value;let E=await Ns({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(a(E))return pe(E.message);if(l=E.value.createdCommit,u=E.value.commitSha,l||i){let A=await Mt({stateBranchRoot:o,repoRoot:r}),K=A;if(a(A)&&_i(A.message)){let Te=await yr({cwd:o,branch:C});if(a(Te))return pe(Te.message);let ie=await Ns({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(a(ie))return pe(ie.message);ie.value.createdCommit&&(l=!0,u=ie.value.commitSha),K=await Mt({stateBranchRoot:o,repoRoot:r})}if(a(K))return pe(K.message);p=K.value,logger.debug("[sync] pushed to state branch",p)}else logger.debug("[sync] no commit created, skipped push");if(l){let A=await L({args:["rev-parse","HEAD"],cwd:o});if(a(A))return pe(A.message);u=A.value.stdout.trim()}return xs(p?"Synced and pushed":m||x||l?"Synced local state":"Already synced"),c("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,pulled:m,pushed:p,hydrated:x,bootstrapped:i})};var Ye=e=>{let t=fe(e??process.cwd());if(a(t))return t;let n=mt(t.value);if(a(n))return s(n.message);let r=un({eventLog:n.value,hasProject:!0});return a(r)?s(r.message):c("Booted Epiq state",{root:t.value})},An=()=>{let e=pi();return a(e)?s(e.message):e.value.userId?e.value.userName?c("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):s("Unable to retrieve user name"):s("Unable to retrieve user id")},Is=(e,t)=>{let r=b(e.id).find(o=>o.title===t);return r?b(r.id).map(o=>typeof o.props?.value=="string"?o.props.value:"").filter(o=>!!o):[]},bc=e=>Is(e,"Tags").map(t=>N.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),Sc=e=>Is(e,"Assignees").map(t=>N.getContributor(t)).filter(Boolean).map(t=>({id:t.id,name:t.name})),Es=(e={})=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=Object.values(f().nodes).filter(r=>r.context==="BOARD").map(r=>({id:r.id,title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return c("Listed boards",n)},Cs=(e={})=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=Object.values(f().nodes).filter(r=>r.context==="SWIMLANE").filter(r=>!e.boardId||r.parentNodeId===e.boardId).map(r=>({id:r.id,title:r.title,boardId:r.parentNodeId,isClosed:r.id===te,readonly:!!r.readonly}));return c("Listed swimlanes",n)},bs=e=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=Object.values(f().nodes).filter(ne).filter(r=>e.includeClosed||r.parentNodeId!==te).map(r=>({id:r.id,title:Xe(r.title),description:go(r,"Description"),parentId:r.parentNodeId,isClosed:r.parentNodeId===te,readonly:!!r.readonly,tags:bc(r),assignees:Sc(r)}));return c("Listed issues",n)},Ss=e=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=An();if(a(n))return n;let r=De(e.parentId,n.value);if(a(r))return r;let o=ln({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(a(o))return o;let i=o.value,l=Fe(i).find(a);if(l)return s(l.message);let u=i.find(m=>m.action==="add.issue")?.payload.id;return u?c("Created issue",{id:u,title:e.title,parentId:e.parentId}):s("Unable to determine created issue id")},Rs=e=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=An();if(a(n))return n;let r=ye(te,e.issueId,{at:"end"},n.value);if(a(r))return r;let o={id:hs(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:te,rank:r.value}},d=Fe([o]).find(a);return d?s(d.message):c("Closed issue",{id:e.issueId})},As=e=>{let t=Ye(e.repoRoot);if(a(t))return t;let n=An();if(a(n))return n;let r=ye(e.parentId,e.issueId,e.position??{at:"end"},n.value);if(a(r))return r;let o={id:hs(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:r.value}},d=Fe([o]).find(a);return d?s(d.message):c("Moved issue",{id:e.issueId,parentId:e.parentId})},ws=async(e={})=>{let t=fe(e.repoRoot??process.cwd());if(a(t))return s("Sync failed");let n=An();if(a(n))return n;let r=await Ze({cwd:t.value,ownEventFileName:Ee(n.value)});return a(r)?r:c("Synced",r.value)},Ts=(e={})=>{let t=Ye(e.repoRoot);return a(t)?t:c("Retrieved Epiq state",{root:t.value.root,nodes:f().nodes,rootNodeId:f().rootNodeId,currentNode:f().currentNode,selectedIndex:f().selectedIndex,eventLog:f().eventLog})};var _e=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),wc=()=>{let e=new Rc({name:"epiq",version:"0.2.30"});return e.registerTool("epiq_state_get",{description:"Get the full current Epiq state, including nodes and event log",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>_e(await Ts(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:F.object({repoRoot:F.string().optional(),includeClosed:F.boolean().optional()})},async t=>_e(await bs(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>_e(await Es(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:F.object({repoRoot:F.string().optional(),boardId:F.string().optional()})},async t=>_e(await Cs(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue",inputSchema:F.object({title:F.string().min(1),parentId:F.string().min(1),repoRoot:F.string().optional()})},async t=>_e(await Ss(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:F.object({issueId:F.string().min(1),repoRoot:F.string().optional()})},async t=>_e(await Rs(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:F.object({issueId:F.string().min(1),parentId:F.string().min(1),position:F.discriminatedUnion("at",[F.object({at:F.literal("start")}),F.object({at:F.literal("end")}),F.object({at:F.literal("before"),sibling:F.string().min(1)}),F.object({at:F.literal("after"),sibling:F.string().min(1)})]).optional(),repoRoot:F.string().optional()})},async t=>_e(await As(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>_e(await ws(t))),e},Tc=async()=>{let e=wc(),t=new Ac;await e.connect(t)};await Tc();export{wc as createMcpServer,_e as resultJson,Tc as startMcpServer};