epiq 0.4.9 → 0.4.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +52 -57
- package/dist/mcp.js +47 -52
- package/package.json +1 -1
- package/readme.md +38 -31
package/dist/mcp.js
CHANGED
|
@@ -1,63 +1,58 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{McpServer as
|
|
3
|
-
`,"utf8"),
|
|
4
|
-
`);if(n[n.length-1]===""&&n.pop(),n.length<=
|
|
2
|
+
import{McpServer as Jd}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Zd}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as F}from"zod";var fe={None:"none",Success:"success",Fail:"fail"},s=e=>({status:fe.Fail,message:e,value:null}),c=(e,t)=>({status:fe.Success,message:e,value:t}),a=e=>e.status==="fail",et=e=>e.status==="success";import{ulid as Qi}from"ulid";import Gs from"node:fs";import rt from"node:fs";import{ulid as ps}from"ulid";import{z as At}from"zod";import tt from"node:fs";import ve from"node:path";var Sn=process.env.IS_LOCAL==="true",ye=".epiq",se=".epiq-global",bt="events",us="project.json",Rr=e=>ve.join(e,ye),Rt=e=>ve.join(e,ye),St=e=>ve.join(Rt(e),us),nt=e=>ve.join(Rt(e),bt),ms=e=>{let t=ve.join(e,ye);return tt.existsSync(t)&&tt.statSync(t).isDirectory()},An=e=>{let t=St(e);return tt.existsSync(t)&&tt.statSync(t).isFile()},le=e=>{let t=ve.resolve(e);for(;;){if(ms(t))return c("Resolved closest .epiq root",t);let n=ve.dirname(t);if(n===t)return s("No .epiq directory found in any parent");t=n}},Ae=e=>{let t=ve.resolve(e);for(;;){if(An(t))return c("Resolved closest epiq project root",t);let n=ve.dirname(t);if(n===t)return s("No .epiq/project.json found in any parent");t=n}},Sr=e=>{let t=nt(e);try{return tt.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 gs="epiq/eventlog",fs=At.object({projectId:At.string().min(1),stateBranch:At.string().min(1),createdAt:At.iso.datetime()}),Ar=()=>({projectId:ps(),stateBranch:gs,createdAt:new Date().toISOString()}),we=e=>{let t=St(e);if(!rt.existsSync(t))return s("Missing .epiq/project.json");try{let n=rt.readFileSync(t,"utf8"),r=JSON.parse(n),o=fs.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")}},wr=e=>{let t=we(e);return a(t)?s(t.message):c("Read projectId",t.value.projectId)},Tr=({repoRoot:e,fileContents:t})=>{let n=Rt(e),r=St(e);try{if(rt.mkdirSync(n,{recursive:!0}),rt.existsSync(r)){let o=we(e);return a(o)?s(o.message):c("Project already initialized",null)}return rt.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 Ke=e=>{let t=Ae(e);if(a(t))return s("Unable to resolve epiq project root");let n=we(t.value);return a(n)?s("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},ae="origin";import st from"node:fs";import Ns from"node:os";import ue from"node:path";var wn=(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};import ot from"fs";import Pr from"path";import vs from"util";var Mr=1e3,kr=()=>{let e=process.cwd(),t=le(e);if(!a(t))return Pr.join(t.value,ye,"log","epiq.log")};function ys(){if(!Sn)return;let e=kr();if(e===void 0||!ot.existsSync(e))return;let n=ot.readFileSync(e,"utf8").split(`
|
|
4
|
+
`);if(n[n.length-1]===""&&n.pop(),n.length<=Mr)return;let r=n.slice(-Mr).join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`;
|
|
7
|
-
`;
|
|
8
|
-
`);u(n?{stdout:
|
|
9
|
-
`)))}),o.on("close",p=>{let x=p??1;if(n){u({stdout:
|
|
10
|
-
`)));return}u(
|
|
11
|
-
${n.message}`);let r=await L({args:["rev-parse","HEAD"],cwd:e});return
|
|
12
|
-
${r.message}`):
|
|
13
|
-
`).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(
|
|
14
|
-
${r.message}`);let o=await
|
|
15
|
-
${o.message}`):
|
|
16
|
-
`+e.message);let t=
|
|
17
|
-
`+t.message):
|
|
6
|
+
`;ot.writeFileSync(e,r,"utf8")}function Tn(e,t,n=!1){if(!Sn)return;let r=kr();if(!r)return;let o=vs.format(...t),i=new Date,l=`[${n?i.toISOString().slice(11,19):i.toISOString()}] ${e} ${o}
|
|
7
|
+
`;ot.mkdirSync(Pr.dirname(r),{recursive:!0}),ot.appendFileSync(r,l,"utf8"),ys()}var Q={info(...e){Tn("[Info]",e,!1)},debug(...e){Tn("->",e,!0)},error(...e){Tn("[Error]",[...e,new Error().stack],!1)}};globalThis.logger=Q;import{spawn as xs}from"node:child_process";import Mn from"node:fs";import Dr from"node:path";var j={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})};var Fr=15e3,hs={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo"},Or=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Mn.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=xs("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:hs}),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 ${Fr}ms`].join(`
|
|
8
|
+
`);u(n?{stdout:d,stderr:p,exitCode:124}:s(p))},Fr);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(`
|
|
9
|
+
`)))}),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(`
|
|
10
|
+
`)));return}u(c("Git command succeeded",{stdout:d,stderr:l,exitCode:x}))})}),L=({args:e,cwd:t})=>Or({args:e,cwd:t,allowFail:!1}),Ve=({args:e,cwd:t})=>Or({args:e,cwd:t,allowFail:!0}),qe=async({cwd:e,message:t})=>{let n=await j.commit({cwd:e,message:t});if(a(n))return s(`Failed to create commit
|
|
11
|
+
${n.message}`);let r=await L({args:["rev-parse","HEAD"],cwd:e});return a(r)?s(`Commit created, but failed to read HEAD SHA
|
|
12
|
+
${r.message}`):c("Created commit and resolved SHA",r.value.stdout.trim())},it=async e=>{let t=await Wr(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=>Mn.existsSync(Dr.join(n,i)));return c("Checked for in-progress Git operation",o.length>0)},Pn=async({repoRoot:e})=>{let n=(await Ve({args:["remote","get-url",ae],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},wt=async({repoRoot:e,branch:t})=>{let n=await Ve({args:["ls-remote","--heads",ae,t],cwd:e});return n.exitCode!==0?s(n.stderr.trim()||`Unable to inspect remote branch ${ae}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},Tt=async({repoRoot:e,branch:t})=>{let n=await Ve({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}`)},Lr=e=>{try{return Mn.realpathSync.native(e)}catch{return Dr.resolve(e)}},Ur=async({repoRoot:e,worktreeRoot:t})=>{let n=await L({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return s(n.message);let r=Lr(t),o=n.value.stdout.split(`
|
|
13
|
+
`).filter(i=>i.startsWith("worktree ")).map(i=>i.slice(9)).map(Lr).includes(r);return c("Checked worktree registration",o)},kn=async e=>{let t=await Ve({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Mt=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())},Br=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())},_r=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Fn=async({cwd:e,branch:t})=>{let n=await wt({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 j.fetch({cwd:e,remote:ae,branch:t});if(a(r))return s(`Failed to fetch ${t}
|
|
14
|
+
${r.message}`);let o=await j.pullRebase({cwd:e,remote:ae,branch:t});return a(o)?s(`Failed during pull --rebase
|
|
15
|
+
${o.message}`):c("Pulled with rebase",!0)},jr=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)},$r=async e=>{let t=await Mt(e);return a(t)?s(t.message):c("Checked detached HEAD state",t.value==="HEAD")};var Hr="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Kr=e=>ue.join(ye,bt,e),Vr=()=>ue.join(Ns.homedir(),se),Pt=()=>ue.join(Vr(),"worktrees"),qr=({repoRoot:e})=>{let t=wr(e);return a(t)?s(t.message):c("Resolved state branch root",ue.join(Pt(),t.value))},Es=e=>ue.join(e,ye),Oe=e=>ue.join(Es(e),bt),Ln=({root:e,fileName:t})=>ue.join(Oe(e),t),at=e=>{try{return st.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return s(t instanceof Error?t.message:String(t))}},kt=()=>{let e=at(Vr());if(a(e))return s(`Ensure epiq home failed.
|
|
16
|
+
`+e.message);let t=at(Pt());return a(t)?s(`Ensure worktrees dir failed.
|
|
17
|
+
`+t.message):c("Ensured epiq storage",!0)},zr=e=>{st.existsSync(e)&&(Q.debug("[sync] remove path",e),st.rmSync(e,{recursive:!0,force:!0}))},Gr=e=>{let t=Oe(e);if(!st.existsSync(t))return c("Events dir missing",[]);let n=st.readdirSync(t,{withFileTypes:!0}).filter(r=>r.isFile()).map(r=>r.name).filter(r=>r.endsWith(".jsonl")).sort();return c("Listed event files",n)},Xr=(e,t)=>{for(let n of[Oe(e),Oe(t)]){let r=at(n);if(a(r))return s(r.message)}return c("Ensured state branch",void 0)},Yr=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
|
|
18
18
|
`+t.message);let r=t.value.stdout.trim().split(`
|
|
19
|
-
`).filter(Boolean).filter(
|
|
20
|
-
${o.message}`);let i=await
|
|
21
|
-
${
|
|
22
|
-
${
|
|
23
|
-
`+
|
|
24
|
-
`+
|
|
25
|
-
`+
|
|
26
|
-
${
|
|
27
|
-
${
|
|
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
|
|
29
|
-
`+
|
|
30
|
-
${
|
|
31
|
-
${
|
|
32
|
-
${
|
|
33
|
-
${
|
|
34
|
-
${
|
|
35
|
-
${
|
|
36
|
-
${
|
|
37
|
-
${o.message}`):
|
|
38
|
-
`+n.message):
|
|
39
|
-
${
|
|
40
|
-
`,"utf8"),
|
|
41
|
-
`)){let i=o.trim();if(!i)continue;let
|
|
19
|
+
`).filter(Boolean).filter(d=>d!==ye);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
|
|
20
|
+
${o.message}`);let i=await qe({cwd:e,message:"[epiq:repair-storage-branch]"});return a(i)?s(i.message):c("Cleaned storage branch",!0)},Ft=wn(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=>ue.resolve(e)),Wr=wn(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=ue.isAbsolute(n)?n:ue.join(e,n);return c("Resolved git dir",r)},e=>ue.resolve(e));import ze from"node:fs";import dt from"node:path";var Zr=async e=>{if((await Ve({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);Q.info("Creating initial commit");let n=await j.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return a(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",Is=async e=>{let t=await Mt(e);if(a(t))return s(t.message);let n=await Br(e);if(a(n))return s(n.message);let r=`[epiq:sync:${Jr(t.value)}:${Jr(n.value)}]`;return c("Built sync commit message",r)},Lt=async({repoRoot:e,stateBranchName:t})=>{Q.info(`Creating ${t}`);let n=await L({args:["commit-tree",Hr,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return s(`Failed to create state branch commit
|
|
21
|
+
${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}
|
|
22
|
+
${o.message}`):c("Created state branch",!0)},Cs=async({repoRoot:e,stateBranchName:t})=>{let n=await Tt({repoRoot:e,branch:t});if(a(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 Pn({repoRoot:e});if(a(r))return s(`Ensure local state branch failed
|
|
24
|
+
`+r.message);if(!r.value)return Lt({repoRoot:e,stateBranchName:t});let o=await wt({repoRoot:e,branch:t});if(a(o))return s(`Ensure local state branch failed
|
|
25
|
+
`+o.message);if(!o.value)return Lt({repoRoot:e,stateBranchName:t});let i=await j.fetch({cwd:e,remote:ae,branch:t});if(a(i))return s(`Failed to fetch ${t} from remote
|
|
26
|
+
${i.message}`);let d=await L({args:["branch","--track",t,`${ae}/${t}`],cwd:e});return a(d)?s(`Failed to create local ${t} from remote
|
|
27
|
+
${d.message}`):c("Created local state branch from remote",!0)},bs=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(`
|
|
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)},Rs=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=at(dt.dirname(t));if(a(r))return s(`Failed to create state branch worktree
|
|
29
|
+
`+r.message);ze.existsSync(t)&&!ze.existsSync(dt.join(t,".git"))&&(Q.info("Removing broken state branch worktree path"),zr(t)),Q.info("Creating state branch worktree");let o=await j.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(o)?s(`Failed to create state branch worktree
|
|
30
|
+
${o.message}`):c("Created state branch worktree",!0)},Dn=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await bs({repoRoot:e,branch:n});if(a(r))return s(r.message);let o=dt.resolve(t),i=r.value?dt.resolve(r.value):null;if(i&&i===o&&ze.existsSync(i))return c("State branch already checked out in expected worktree",!1);if(i&&i!==o){Q.info("Moving state branch worktree to expected location");let u=await j.worktreeRemove({cwd:e,worktreeRoot:i});if(a(u))return s(`Failed to remove existing state branch worktree
|
|
31
|
+
${u.message}`)}if(i&&!ze.existsSync(i)){Q.info("Pruning stale state branch worktree");let u=await j.worktreePrune({cwd:e});if(a(u))return s(`Failed to prune stale worktrees
|
|
32
|
+
${u.message}`)}let d=await Ur({repoRoot:e,worktreeRoot:t});if(a(d))return s(d.message);let l=ze.existsSync(t);if(d.value&&l)return c("State branch worktree already exists",!1);if(d.value&&!l){Q.info("Pruning missing registered state branch worktree");let u=await j.worktreePrune({cwd:e});if(a(u))return s(`Failed to prune stale worktrees
|
|
33
|
+
${u.message}`)}return Rs({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Ss=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Mt(e);if(a(n))return s(n.message);if(n.value===t)return c("State branch already checked out",!1);let r=await j.checkout({cwd:e,branch:t});return a(r)?s(`Failed to checkout ${t}
|
|
34
|
+
${r.message}`):c("Checked out state branch",!0)},As=async({repoRoot:e,stateBranchRoot:t})=>{let n=await kn(t);if(a(n))return s(n.message);if(n.value)return c("State branch upstream already configured",!1);let r=await Pn({repoRoot:t});if(a(r))return s(r.message);if(!r.value)return c("No remote available for state branch upstream",!1);let o=Ke(e);if(a(o))return o;let i=o.value,d=await wt({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);Q.info(`Configuring ${i} upstream`);let l=await j.fetch({cwd:t,remote:ae,branch:i});if(a(l))return s(`Failed to fetch ${i}
|
|
35
|
+
${l.message}`);let u=await j.setUpstream({cwd:t,branch:i,upstream:`${ae}/${i}`});return a(u)?s(`Failed to set state branch upstream
|
|
36
|
+
${u.message}`):c("Configured state branch upstream",!0)},Dt=async({stateBranchRoot:e,eventFileName:t})=>{let n=Kr(t),r=dt.join(e,n);if(!ze.existsSync(r))return c("No event file to stage",void 0);let o=await j.stage({cwd:e,pathspec:[n]});return a(o)?s(`Failed to stage state branch event file
|
|
37
|
+
${o.message}`):c("Staged state branch event file",void 0)},Qr=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Is(e);return a(n)?s(`Create state branch sync commit failed
|
|
38
|
+
`+n.message):qe({cwd:t,message:n.value})},ct=async({repoRoot:e,stateBranchRoot:t})=>{let n=await kn(t);if(a(n))return s(n.message);let r=Ke(e);if(a(r))return r;let o=r.value,i=n.value?await j.push({cwd:t}):await j.push({cwd:t,remote:ae,branch:o,setUpstream:!0});return a(i)?s(`Failed during state branch push
|
|
39
|
+
${i.message}`):c("Pushed state branch",!0)},eo=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Ke(e);if(a(o))return o;let i=o.value,d=[kt(),await Cs({repoRoot:e,stateBranchName:i}),await Dn({repoRoot:e,stateBranchRoot:t,stateBranchName:i}),await Ss({stateBranchRoot:t,stateBranchName:i}),await Yr(t),n?await As({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 Wt from"node:fs";import jn from"node:path";import{decodeTime as Ks}from"ulid";import jt from"node:fs";import Bn from"node:path";import{decodeTime as Os}from"ulid";import{z as Un}from"zod";import ws from"node:fs";import Ts from"node:path";import{decodeTime as Ms,monotonicFactory as Ps}from"ulid";import{z as lt}from"zod";var Ot={autoSync:!1,preferredEditor:null,userName:null,userId:null},me=()=>Ot,Ut=e=>(Ot={...Ot,...e},Ot);var to=e=>({action:e.action,payload:e.payload});var ro=1,no=Ps(),ks=lt.tuple([lt.string().min(1),lt.string().min(1).nullable()]),Fs=lt.looseObject({v:lt.literal(ro),id:ks}),On=e=>{let t=Fs.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(", ")}`)},Bt=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown",G=()=>{let{userName:e,userId:t}=me();return e?t?e.trim()?c("Successfully resolved actor ID",{userId:Bt(t),userName:Bt(e)}):s("Unable to resolve actor ID from settings or OS user info"):s("User ID not configured"):s("User name not configured")},Ue=({userId:e,userName:t})=>`${Bt(e)}.${Bt(t)}.jsonl`,Ls=(e,{userId:t,userName:n})=>{let r=Ue({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return s(`Invalid event log file name: ${r}`);let i=Ts.join(nt(e),r);return c("Successfully resolved event log path",i)},Ds=(e,t)=>{let n={[e.action]:e.payload,v:ro,id:t};return On(n)};function _t({event:e,rootDir:t=process.cwd()}){try{let n=le(t);if(a(n))return n;let r=Sr(n.value);if(a(r))return r;let o=Ls(n.value,{userId:e.userId,userName:e.userName});if(a(o))return o;let i=oo(n.value);if(a(i))return s(i.message);let d=i.value?no(Math.max(Date.now(),Ms(i.value)+1)):no(),l=Ds(to(e),[d,i.value]);return a(l)?s(l.message):(ws.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 Us=Un.object({userId:Un.string().min(1).default("unknown"),userName:Un.string().min(1).default("unknown")}),Bs=e=>{let[t,n]=Bn.basename(e,".jsonl").split("."),r=Us.safeParse({userId:t,userName:n});return r.success?c("Parsed event file actor",r.data):s(`Invalid event file name ${Bn.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])},js=(e,t)=>t in e,$s=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Ws=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?js(r,i)?c("Decoded persisted event",$s({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(!jt.existsSync(e))return c("Event file missing",[]);let t=Bs(e);if(a(t))return s(t.message);let n=jt.readFileSync(e,"utf8"),r=[];for(let o of n.split(`
|
|
41
|
+
`)){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=On(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 io(e){let t=nt(e);if(!jt.existsSync(t))return c("No events found",[]);let n=jt.readdirSync(t).filter(o=>o.endsWith(".jsonl")).map(o=>Bn.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",Hs(r))}function ut(e){let t=io(e);if(a(t))return s(t.message);let n=[];for(let r of t.value){let o=Ws(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 oo(e=process.cwd()){let t=io(e);return a(t)?s(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Hs=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 N=n.get(x)??[];N.push(m),n.set(x,N)}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 N of x)i(N)},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},so=(e,t)=>{let n=e.findIndex(r=>{try{return Os(r.id)>t}catch{return!0}});return n===-1?{appliedEvents:e,unappliedEvents:[]}:{appliedEvents:e.slice(0,n),unappliedEvents:e.slice(n)}};var _n=e=>{let[t,n]=e.id;return`${t}:${n??""}`},ao=e=>{let[t]=e.id;return Ks(t)},Vs=e=>{let{userId:t,userName:n,...r}=e;return r},qs=e=>e.length===0?"":e.map(t=>JSON.stringify(Vs(t))).join(`
|
|
42
42
|
`)+`
|
|
43
|
-
`,
|
|
44
|
-
`),l("Config written",null)}catch{return s(`Unable to write ~/${ie}/config.json`)}},Dt=e=>{let t=ro();if(d(t))return s("Failed to read existing config");let n={...t.value,...e};return oo(n)},io=()=>{let e=An(),t=wn();if(d(t))return s(`Unable to create ~/${ie}`);if(!(te.readFile(e)!==null)){let u=oo(Ks);if(d(u))throw new Error(`Unable to create ~/${ie}/config.json`)}let r=ro();if(d(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:a,autoSync:c}=r.value;return!i||!a?s(`User name or ID not configured in ~/${ie}/config.json`):l("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:a,autoSync:c??!1})};import{monotonicFactory as Xs,ulid as Ot}from"ulid";var Pe=24n,zs=Pe*4n,dt=(1n<<zs)-1n,Gs=/^[0-9a-f]+$/;function so(e){return!e||!Gs.test(e)?s(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function ve(e,t=Pe){if(e<0n)return s("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function V(e,t){if(!e&&!t)return ve(dt/2n,Pe);let n=e?so(e):l("Resolved lower bound",0n);if(d(n))return n;let r=t?so(t):l("Resolved upper bound",dt);if(d(r))return r;let o=n.value,i=r.value;if(i<=o)return ve(dt/2n,Pe);let a=(o+i)/2n;return a===o||a===i?s("No rank space available between neighbors"):ve(a,Pe)}function ao(){return ve(dt/2n,Pe)}function lo(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=dt*BigInt(r+1)/(t+1n),i=ve(o,Pe);if(d(i))return i;n.push(i.value)}return l("Resolved evenly spaced ranks",n)}var Ut=Xs(),Bt=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=Ut(),a=Ut(),c=Ut(),u=Ut(),m=ao();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:l("Created issue events",[{id:Ot(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}},{id:Ot(),userId:r,userName:o,action:"add.field",payload:{id:a,parent:i,name:"Description",val:"",rank:m.value}},{id:Ot(),userId:r,userName:o,action:"add.field",payload:{id:c,parent:i,name:"Assignees",rank:p.value}},{id:Ot(),userId:r,userName:o,action:"add.field",payload:{id:u,parent:i,name:"Tags",rank:x.value}}])};import or from"chalk";import{monotonicFactory as Td,ulid as Ce}from"ulid";import{useSyncExternalStore as Rd}from"react";var k={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function Tn(e){return e.context==="WORKSPACE"}function Q(e){return e.context==="TICKET"}function co(e){return e.context==="FIELD"}var _t=e=>e.context==="SWIMLANE",uo=e=>e.context==="BOARD";var f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"command-line"};function $t(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Wt=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Ke=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim();var mo=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},po=(e,t)=>t?e.get(t)??[]:[];var go=new WeakMap,Ys=e=>{let t=go.get(e);return t||(t=mo(e),go.set(e,t)),t};var fo=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return po(Ys(e),r).filter(i=>$t(r,i)>=n)};var Js={hint:"",hints:[],overlap:0,remainder:""},vo=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Js;let o=fo({wordList:r,inputToMatch:e,overlapThreshold:1});return Zs(t,o)},Zs=(e,t)=>{let n=t[0]??"",r=$t(e.toLowerCase(),n.toLowerCase()),[o,i]=n.split(":"),a=r<(o??"").length,c=!!i,p=(c&&a?o:n)+(c&&a?":":" "),x=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:x}};var yo=["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 Qs}from"ulid";var Mn=(e,t)=>{let n=$(e),r=lo(n.length);if(d(r))return r;let o={};for(let i=0;i<n.length;i++){let a=n[i],c=r.value[i];if(!a||!c)return s("Unable to assign rebalance rank");o[a.id]=c}return l("Created rebalance event",{id:Qs(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var ea=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[Y,jt]=ea;var P=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),ta={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=z.workspace(t,n,r),i=ut(o);if(d(i))return P(i.message,e);let a=N.createNode(o);return d(a)?P(a.message??"Failed to initialize workspace",e):Tn(a.value)?l("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=N.createNode(o);return d(i)?P(i.message??"Failed to add workspace",e):Tn(i.value)?l("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(z.board(t,n,r,o));return d(i)?P(i.message??"Unable to create board",e):uo(i.value)?l("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(z.swimlane(t,n,r,o));return d(i)?P(i.message??"Unable to create swimlane",e):_t(i.value)?l("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(z.ticket(t,n,r,o));return d(i)?P(i.message??"Unable to create issue",e):Q(i.value)?l("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=N.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):co(a.value)?l("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(!N.getNode(t))return P(`Unable to locate node with id ${t}`,e);let o=N.renameNode(t,n);return d(o)?P(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=N.tombstoneNode(t);return d(n)?P(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=N.createTag({id:t,name:n});return d(r)?P(r.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=N.createContributor({id:t,name:n});return d(r)?P(r.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:r.value})},"tag.issue":e=>{let{id:t,target:n,tagId:r,rank:o}=e.payload,i=N.tag(n,r,t,o);return d(i)?P(i.message??"Unable to tag issue",e):l("Issue tagged",{action:e.action,result:i.value})},"untag.issue":e=>{let{target:t,tagId:n}=e.payload,r=N.untag(t,n);return d(r)?P(r.message??"Unable to untag ",e):l("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 d(i)?P(i.message??"Unable to assign issue",e):l("Assigned successfully",{action:e.action,result:i.value})},"unassign.issue":e=>{let{target:t,contributor:n}=e.payload,r=N.unassign(t,n);return d(r)?P(r.message??"Unable to unassign issue",e):l("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 d(o)?P(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=N.editValue(t,n);return d(r)?P(r.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.getNode(t);if(!o)return P("Unable to locate issue",e);if(!Q(o))return P("Can only close issues",e);let i=N.getNode(Y);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=N.moveNodeToRank({id:t,parentId:n,rank:r});return d(a)?P(a.message??"Unable to close issue",e):l("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.getNode(t);if(!o)return P("Unable to locate issue",e);if(!Q(o))return P("Can only reopen issues",e);let i=N.getNode(Y);if(!i)return P("Unable to locate closed swimlane",e);if(n===i.id)return P("Cannot reopen issue into closed swimlane",e);if(!N.getNode(n))return P("Reopen parent no longer exists",e);let c=N.moveNodeToRank({id:t,parentId:n,rank:r});return d(c)?P(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=N.lockNode(t);return d(n)?P(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let i=N.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=N.updateNode({...i,rank:o});if(d(a))return P(a.message??"Unable to rebalance child",e)}return l("Rebalanced children",{action:e.action,result:{parent:t}})}},na=(e,t)=>{let n=N.getNode(e);n&&N.updateNode({...n,log:[...n.log??[],t]})},ra=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 lt(e,t=!1){let n=ta[e.action](e);if(d(n))return n;t||([...new Set(ra(e))].forEach(a=>na(a,e)),ne(a=>({...a,eventLog:[...a.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?P("Invalid user ID format",e):(N.createContributor({name:o,id:r}),n)}var ct=e=>e.map(t=>lt(t));function j(e){let t=lt(e);if(t.status!==me.Success)return t;let n=Kr({event:e});return d(n)?n:t}function Fe(e){return e.map(t=>j(t))}var xo=e=>kn($(e),{at:"end"}),kn=(e,t={at:"end"})=>{let n=r=>d(r)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(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=No(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=No(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)),No=(e,t)=>e.findIndex(n=>n.id===t),Eo=(e,t,n={at:"end"})=>kn($(t).filter(r=>r.id!==e),n),ye=(e,t,n,r)=>{let o=Eo(t,e,n);if(d(o))return o;if(!o.value.needsRebalance)return l("Resolved rank",o.value.rank);let i=Mn(e,r);if(d(i))return i;let a=j(i.value);if(d(a))return a;let c=Eo(t,e,n);return d(c)?c:c.value.needsRebalance?s("Rank rebalance failed to create space"):l("Resolved rank after rebalance",c.value.rank)},Re=(e,t)=>{let n=xo(e);if(d(n))return n;if(!n.value.needsRebalance)return l("Resolved rank",n.value.rank);let r=Mn(e,t);if(d(r))return r;let o=j(r.value);if(d(o))return o;let i=xo(e);return d(i)?i:i.value.needsRebalance?s("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)};var Ve=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return s("Node not found");if(r.context===t)return l("Resolved ancestor node",r);let o=r.parentNodeId?n[r.parentNodeId]:void 0;for(;o;){if(o.context===t)return l("Resolved ancestor node",o);o=o.parentNodeId?n[o.parentNodeId]:void 0}return s(`No ancestor found for context: ${t}`)},oa=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},Pn=(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){ne(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=Pn(r,"edit");if(o)return o;let i={...r,props:{...r.props,value:t}};return this.updateNode(i),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return s("Rename target node not found");let r=Pn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return $(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return 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=Pn(o,"move");if(a)return a;if(oa(t,e))return s("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,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 c={...structuredClone(t)};for(let u of i){if(!c[u])return s("Unable to locate node to delete");c[u]={...c[u],isDeleted:!0}}return n?(I({nodes:c}),l("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=ne(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?s("Unable to create contributor"):l("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:l("Assigned contributor",u)},createTag(e){let t=ne(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?s("Could not create tag"):l("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:l("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(c=>c.props?.value===t);if(!i)return l("Issue is not tagged with that tag",null);let a={...i,isDeleted:!0};return this.updateNode(a),l("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(c=>c.props?.value===t);if(!i)return l("Issue is not assigned to that contributor",null);let a={...i,isDeleted:!0};return this.updateNode(a),l("Assignee removed",a)},createNode(e){let t=ne(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?s("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return s("Failed to locate node");let n={...t,readonly:!0},r=ne(o=>({...o,nodes:{...o.nodes,[e]:n}}));return d(r)?s(r.message):l("Locked node",n)},updateNode(e){let t=ne(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return d(t)?t:l("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return $(e)}};var ho=()=>{let e=fe(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},Io=()=>{let e=_e(process.cwd());if(d(e))return s("Unable to determine if repository is initialized");let t=$e(e.value);return Ye(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},qe={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 Co=(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):[]},Fn=e=>Co(e,"Tags").map(t=>N.getTag(t)).filter(t=>!!t),Ht=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!Q(n)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Fn(n)??[])},Kt=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!Q(n)?s("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Ln(n)??[])},Ln=e=>Co(e,"Assignees").map(t=>N.getContributor(t)).filter(t=>!!t);var bo=(e,t)=>{let r=S(e.id).find(o=>o.title===t);return r&&typeof r.props?.value=="string"?Ke(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 ia=/^(\d+)(h|d|w|mo|y)$/,sa=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,aa=({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},da=(e,t=new Date)=>{let n=e.match(ia);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}},la=e=>{let t=e.match(sa);if(!t)return null;let[,n,r,o,i,a]=t,c=Number(n),u=Number(r),m=Number(o),p=i?Number(i):0,x=a?Number(a):0;return aa({year:c,month:u,day:m,hour:p,minute:x})?new Date(c,u-1,m,p,x):null},Vt=e=>{let t=e.trim().toLowerCase();return da(t)??la(t)},So=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,ca=[{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}],Ro=(e=ca)=>{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 ua=["BOARD","TICKET","SWIMLANE"],Le=[g.SYNC,g.HELP,g.EXPORT,g.SET_VIEW,g.SET_EDITOR,g.SET_USERNAME],qt=[g.NEW,g.RENAME,g.DELETE,g.MOVE],Dn=[g.TAG,g.UNTAG,g.ASSIGN,g.UNASSIGN,g.CLOSE_ISSUE,g.RE_OPEN_ISSUE,g.SET_DESCRIPTION],Ao=[g.FILTER,g.PEEK],ma={WORKSPACE:[...Le,...qt],BOARD:[...Ao,...Le,...qt],SWIMLANE:[...Ao,...Le,...qt],TICKET:[...Le,...qt,...Dn],FIELD:[...Le,...Dn],FIELD_LIST:[...Le,...Dn],TEXT:[...Le]},pa=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],ga=()=>{let{currentNode:e,selectedNode:t,readOnly:n}=v();if(!ho().isSetup)return[g.HELP,g.SET_EDITOR,g.SET_USERNAME];if(!Io())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&&ua.includes(i);return ma[o].filter(c=>c===g.RENAME||c===g.DELETE||c===g.MOVE?a:!0)},q=e=>{let{currentNode:t}=v(),n=t.context??"WORKSPACE";return{[g.NONE]:ga(),[g.EXIT]:["confirm"],[g.EXPORT]:[],[g.SYNC]:[],[g.INIT]:[],[g.HELP]:[],[g.PEEK]:[...Ro(),"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]:[...yo],[g.TAG]:[...new Set([...Object.keys(qe),...N.getExistingTags()])],[g.UNTAG]:[...Ht()?.value?.map(({name:o})=>o)??[]],[g.UNASSIGN]:[...Kt()?.value?.map(({name:o})=>o)??[]],[g.ASSIGN]:N.getExistingAssignees(),[g.RENAME]:[],[g.NEW]:pa(n)}[e]??[]};import ze from"chalk";import{decodeTime as wo}from"ulid";var To=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 Mo=e=>{try{return l("Decoded date",new Date(wo(e)))}catch(t){return s("Decoding failed + "+t.message)}},On=e=>{if(!e?.id)return null;try{return wo(e.id)}catch{return null}};var De=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?l("Found node",n):s("Unable to find node in breadcrumb")};import ko from"chalk";var Bn={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},fa=(e,t,n)=>Math.max(t,Math.min(n,e)),Un=(e,t,n)=>e+(t-e)*n,Po=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},va=(e,t,n)=>{let r=t/100,o=n/100,i=(1-Math.abs(2*o-1))*r,a=e/60,c=i*(1-Math.abs(a%2-1)),u=0,m=0,p=0;a>=0&&a<1?(u=i,m=c):a>=1&&a<2?(u=c,m=i):a>=2&&a<3?(m=i,p=c):a>=3&&a<4?(m=c,p=i):a>=4&&a<5?(u=c,p=i):(u=i,p=c);let x=o-i/2;return[Math.round((u+x)*255),Math.round((m+x)*255),Math.round((p+x)*255)]},ya=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,xa=(e,t,n)=>[Math.round(Un(e[0],t[0],n)),Math.round(Un(e[1],t[1],n)),Math.round(Un(e[2],t[2],n))],mt=e=>{let n=Po(e)%360,r=va(n,Bn.stringColor.saturation,Bn.stringColor.lightness);return ya(r)},Na=e=>{let t=Bn.gradient.stops,n=fa(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 xa(t[i],t[i+1],a)},zt=e=>Po(e.toLowerCase().trim())/4294967295,Ea=e=>{let t=zt(e);return Na(t)},ha=e=>{let[t,n,r]=Ea(e);return{normal:o=>ko.bgRgb(t,n,r).black(o),cursor:o=>ko.bgRgb(t,n,r).white.bold(o)}};var _n=e=>ha(e).normal(` ${e} `),ee=(e,t=qe)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:mt(r)};var xe={None:"none",Invalid:"invalid",Valid:"valid"};var Ia=["BOARD","TICKET","SWIMLANE"],$n=()=>{let e=v().selectedNode;return e?.context?Ia.includes(e?.context)?_():U({message:"Command not available in this context"}):U({message:"Missing target context"})},J="<ENTER> to confirm",_=(e="",t=[])=>({message:e,validity:xe.Valid,completionWordList:t}),U=({message:e,completionWordList:t=[]})=>({validity:xe.Invalid,message:e,completionWordList:t}),gt=e=>e.length===0,Ae=({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)=>zt(p)-zt(x)).slice(0,r).map(_n),m=u.length>i?u.join(" "):"";return m?`${e}${m}${n}`:""},Wn=({modifier:e})=>{let t="confirm";return e===t?_(J):U({message:gt(e)?`if you are certain, enter ${_n(t)}`:"",completionWordList:[t]})},Ca=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?_(J):U({message:gt(n)?t:""}),ba=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?U({message:n}):_():U({message:gt(r)?t:""}),pt=({hint:e})=>({modifier:t,inputString:n})=>gt(t)&>(n)?U({message:e,completionWordList:[]}):_(J),Sa={[g.EXPORT]:()=>_(J+", and create export markdown file"),[g.PEEK]:e=>{let t=e.modifier;if(t==="now")return _(J);let n={message:"historical state from: '1h', '2d', '23h', '1mo', '2y', 'previous', 'next' or full date as YYYY-MM-DD"};if(t==="prev"||t==="next")return _(J);let r=Vt(t);if(!t||!r)return U(n);let o=De(v().breadCrumb,"BOARD");if(d(o))return U({message:"Command is not applicable in this context"});let i=Mo(o.value.id);return d(i)?U({message:"Unable to peek: board id is not a valid ULID"}):So({date:r,horizonDate:i.value})?_(J):U({message:ze.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[g.EXIT]:()=>_(J+" and exit the application"),[g.INIT]:()=>_(J),[g.FILTER]:e=>{if(e.modifier==="clear")return _();let t=a=>q(g.FILTER).includes(a);if(!e.modifier||!t(e.modifier??""))return U({message:Ae({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()??"")?U({message:Ae({prefix:`existing ${e.modifier}s... `,wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i}):_():U({message:Ae({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?_():U({message:Ae({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[g.NEW]:e=>ba({list:q(g.NEW),hint:Ae({wordList:q(g.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[g.SET_DESCRIPTION]:()=>_(J),[g.HELP]:()=>_(J),[g.RENAME]:()=>{let e=$n();return e.validity==="invalid"?e:_(J)},[g.DELETE]:e=>{let t=$n();return t.validity==="invalid"?t:Wn(e)},[g.CLOSE_ISSUE]:e=>Wn(e),[g.RE_OPEN_ISSUE]:e=>Wn(e),[g.MOVE]:e=>{let t=$n();return t.validity==="invalid"?t:pt({hint:Ae({prefix:"hey hacker! These commands are blocked for you... ",wordList:q(g.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[g.TAG]:e=>{let t=N.getExistingTags().map(n=>` ${ze.bgHex(ee(n))(" "+n+" ")} `).slice(0,10);return pt({hint:"tag name like... "+t.join("")})(e)},[g.UNTAG]:e=>{let t=Ht();if(d(t))return U({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${ze.bgHex(ee(r))(" "+r+" ")} `).slice(0,10);return n.length?pt({hint:" ... "+n.join("")})(e):U({message:"Issue has not tags",completionWordList:[]})},[g.ASSIGN]:e=>{let t=N.getExistingAssignees().map(n=>` ${ze.bgHex(ee(n))(" "+n+" ")} `).slice(0,10);return pt({hint:"assign to... "+t.join("")})(e)},[g.UNASSIGN]:e=>{let t=Kt();if(d(t))return U({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${ze.bgHex(ee(r))(" "+r+" ")} `).slice(0,10);return n.length?pt({hint:"remove assignee... "+n.join("")})(e):U({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?_(J):U({message:Ae({wordList:t,inputString:e.inputString})})},[g.SET_USERNAME]:e=>e.inputString?_():U({message:`Enter a username. Saved in ${ze.bgBlack("~/.epiq-global/")}`}),[g.SET_VIEW]:e=>Ca({list:q(g.SET_VIEW),hint:Ae({wordList:q(g.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[g.SYNC]:()=>_(J)},Fo=Object.fromEntries(Object.entries(Sa).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Lo=["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 Do=e=>Object.values(g).includes(e),Oo=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:a,validity:c,completionWordList:u}=Fo[n].validate(n,r,i),m=o==="command"?Object.values(g):n&&e.target==="modifier"?q(n):Lo;return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:a??"",autoCompletion:t?vo(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var Uo=e=>{let t=e.trimStart(),n=Aa(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),a=wa(e),c=Do(r)?r:null,u=c!==null,m=r!=="",p=c?q(c)??[]:[],x=c&&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 C=i?"":a,R=Ra(t,c,x);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:a,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:i,modifier:x,target:E,inputToMatch:C,inputString:R}},Ra=(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},Aa=e=>e.trim()?e.trim().split(/\s+/):[],wa=e=>e.trimEnd().split(/\s+/).at(-1)??"";var Bo=" ",Ge={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:xe.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Ta=new Set,_o=()=>{for(let e of Ta)e()};var Ne=e=>{let n=e(Ge),r=Uo(n.value),o=n.cursorPosition===n.value.length;Ge={...n,commandMeta:Oo(r,o)},_o()},ft=({message:e,status:t})=>{let n=structuredClone(Ge);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Ge=n,_o(),l(e,null)},jn=e=>{Ne(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Hn=e=>{Ne(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}})},$o=()=>{Ne(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}})},Wo=()=>{Ne(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=>{Ne(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,c=Math.max(0,Math.min(i.length,a.length));return{...t,value:a,cursorPosition:c,commandIsPending:!1}})},jo=()=>{Ne(e=>({...e,commandIsPending:!0}))},Ho=({addToHistory:e=!0})=>{Ne(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),Ma()},Ko=()=>{Ne(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}})},Vo=()=>{Ne(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Ma=()=>W(()=>""),re=()=>Ge,Gt=()=>{let[e,...t]=Ge.value.split(Bo);return t.join(Bo).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 qo=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 B}from"ulid";import ai from"node:fs";import od from"node:path";import id from"react";import{Box as nd}from"ink";import nn from"react";import{Box as qn,Text as ja}from"ink";import ue from"react";import{Text as zo}from"ink";import Go,{useEffect as Xo,useState as ka}from"react";var Yo={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},se=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=ce(),r=Yo[n]??Yo.default,[o,i]=ka(0);if(Xo(()=>{i(0)},[r]),Xo(()=>{if(!e)return;let c=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return Go.createElement(zo,null,t);let a=r[o]??r[0]??t;return Go.createElement(zo,{color:M.accent,dimColor:o===1},a)};import{Box as Kn,Text as Pa}from"ink";import Xt from"react";var Yt=({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)),c=Math.max(1,Math.floor(i/a)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-c),p=o?Math.min(m,Math.max(0,u-c+1)):Math.min(m,Math.floor(u/c)*c),x=p+c,E=e.slice(p,x),C=e.length>c,R=i,b=C?Math.max(1,Math.floor(c/e.length*R)):R,h=Math.max(0,R-b),w=Math.max(1,e.length-c),H=C?Math.floor(p/w*h):0;return Xt.createElement(Kn,{flexDirection:"row",height:i,width:"100%"},Xt.createElement(Kn,{flexDirection:"column",flexGrow:1,height:i},E),Xt.createElement(Kn,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((ir,Xe)=>Xt.createElement(Pa,{key:Xe,color:C&&Xe>=H&&Xe<H+b?M.accent:M.secondary},C?"\u2502":" "))))};import{Box as Qt,Text as _a}from"ink";import Oe from"react";import{Text as Fa}from"ink";import La from"react";var Da=e=>e.toLowerCase().trim(),Oa=(e,t=qe)=>{let n=Da(e);return t[n]?t[n]:mt(n)},Jt=({id:e,isSelected:t})=>{let n=N.getContributor(e);if(n)return La.createElement(Fa,{underline:t,color:Oa(n.name)},"@"+n.name)};import{Text as Ua}from"ink";import Ba from"react";var Zt=({id:e,isSelected:t})=>{let n=N.getTag(e);if(n)return Ba.createElement(Ua,{underline:t,backgroundColor:ee(n.name),color:M.primary}," "+n.name+" ")};var Jo=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=Wt(Ke(t.title),r),i=Fn(t),a=Ln(t);return Oe.createElement(Qt,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?M.accent:M.secondary,justifyContent:"space-between"},Oe.createElement(Qt,{borderBottom:!0},Oe.createElement(Qt,{paddingLeft:1,flexDirection:"column"},Oe.createElement(_a,{color:M.primary},o))),Oe.createElement(Qt,{flexDirection:"row",paddingLeft:1},i.map(c=>Oe.createElement(Zt,{key:c.id,id:c.id})),a.map(c=>Oe.createElement(Jt,{key:c.id,id:c.id}))))};import $a from"chalk";import{Box as vt,Text as Vn}from"ink";import Ee from"react";var Wa=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Zo=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=S(t.id),a=b=>{let h=i.find(w=>w.title===b);return h?S(h.id).map(w=>typeof w.props?.value=="string"?w.props.value:"").filter(w=>!!w):[]},c=a("Tags").map(b=>N.getTag(b)).filter(b=>!!b),u=a("Assignees").map(b=>N.getContributor(b)).filter(b=>!!b),m=1,p=c.length*(1+m),x=u.length*(2+m),E=c.map(b=>Ee.createElement(vt,{key:b.id,paddingRight:m},Ee.createElement(Vn,{color:ee(b.name)},"\u25A0"))),C=u.map(b=>Ee.createElement(vt,{key:b.id,paddingRight:m},Ee.createElement(Vn,{color:mt(b.name)},"@"+b.name.at(0)))),R=n?M.accent:o===f.MOVE?M.secondary:M.primary;return Ee.createElement(vt,{borderBottom:!0,justifyContent:"space-between"},Ee.createElement(vt,null,Ee.createElement(se,{isSelected:n,placeholder:$a.dim.gray(r+1+" ")}),Ee.createElement(Vn,{wrap:"truncate",color:R},Wa(t.title,e-p-x-14))),Ee.createElement(vt,null,E,C))};var Ha=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:a,mode:c})=>{let{renderedChildrenIndex:u}=ce(),m=u[e.id]??[],p=`${e.title} (${m.length})`,x=3,E=o?1:4,C=r-x-(o?2:1),R=ue.createElement(qn,{borderStyle:"round",borderColor:M.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},ue.createElement(se,{isSelected:t}),ue.createElement(ja,{bold:!0,color:t?M.accent:M.primary},p," ",e.readonly?"\u{1F512}":"")),b=(h,w)=>{let H=i&&a===w;return o?ue.createElement(Zo,{key:h.id,index:w,width:n,ticket:h,isSelected:H,mode:c}):ue.createElement(Jo,{key:h.id,width:n,ticket:h,isSelected:H})};return ue.createElement(qn,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?M.accent:M.secondary,paddingRight:1,paddingLeft:1,height:r},R,ue.createElement(qn,{padding:o?1:0},m.length>0&&ue.createElement(Yt,{selectedIndex:a,height:C,itemHeight:E},m.map(b)),ue.createElement(se,{isSelected:i&&a===-1})))},Qo=ue.memo(Ha);import{Box as Xn,Text as ed}from"ink";import we,{useEffect as Yn,useMemo as ri}from"react";import Ue from"chalk";import ei from"string-width";import{decodeTime as Ka}from"ulid";var Va=(e,t)=>e+" ".repeat(Math.max(0,t-ei(e))),qa=(e,t)=>" ".repeat(Math.max(0,t-ei(e)))+e,za=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)})(),Ga=e=>{switch(e.action){case"move.node":{let t=N.getNode(e.payload.parent);return`to ${t?Ue.dim.bgBlack(` ${t.title} `):"unknown"} with rank ${e.payload.rank}`}case"tag.issue":{let t=v().tags[e.payload.tagId];return t?Ue.bgHex(ee(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=v().tags[e.payload.tagId];return t?Ue.bgHex(ee(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=v().contributors[e.payload.contributor];return t?Ue.hex(ee(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=v().contributors[e.payload.contributor];return t?Ue.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""}},Xa=e=>{let t=To(Ka(e));return Ue.gray(qa(t,8))},Ya=12,Ja=e=>Va(`${e}`,Ya),ti=e=>{let t=Xa(e.id),n=Ja(e.userName),r=za(e.action),o=Ga(e),i=Ue.dim("\u203A"),a=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${a}`};import{Box as en,Text as Za}from"ink";import he from"react";var ni=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=ce(),{title:o}=t,i=S(t.id).map(a=>{let c=typeof a.props?.value=="string"?a.props.value:"";if(o==="Assignees")return N.getContributor(c)?.id;if(o==="Tags")return N.getTag(c)?.id}).filter(a=>!!a);return he.createElement(en,{alignItems:"center",paddingTop:1},he.createElement(en,{minWidth:12},he.createElement(se,{isSelected:n}),he.createElement(Za,{color:n?M.accent:M.secondary2},o,":")),he.createElement(en,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((a,c)=>{let u=r.id===t.id&&c===e;return he.createElement(en,{key:`${o}-${a}`,paddingRight:2,minHeight:1},he.createElement(se,{isSelected:u}),o==="Assignees"?he.createElement(Jt,{isSelected:u,id:a}):o==="Tags"?he.createElement(Zt,{isSelected:u,id:a}):null)})))};import{Box as tn,Text as zn}from"ink";import Ie,{useEffect as Qa}from"react";var Gn=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:a,currentNode:c}=ce(),u=E=>String(E).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];Qa(()=>{let E=[];return m.forEach((C,R)=>{let b=ve(BigInt(R+1));if(!Ye(b))return;let h=z.text({id:`${e}-${R}`,name:`Line ${R+1}`,parentNodeId:e,rank:b.value,props:{value:C},readonly:!0}),w=N.createNode(h);Ye(w)&&E.push(w.value.id)}),()=>E.forEach(N.deleteNode)},[e,n]);let p="\u2029",x=m.map((E,C)=>{let R=c.id===e&&a===C;return Ie.createElement(tn,{key:`${e}-${C}`},Ie.createElement(zn,{color:R?M.primary:M.secondary2,dimColor:!R},`${C+1} `.padStart(5,"\xA0")),Ie.createElement(zn,{backgroundColor:R?"gray":""},u(E.length?Wt(E,i-10):p)))});return Ie.createElement(tn,{flexDirection:"column",paddingTop:1},Ie.createElement(tn,null,Ie.createElement(se,{isSelected:o}),Ie.createElement(zn,{color:o?M.accent:M.secondary2},t)),Ie.createElement(tn,{flexDirection:"row",borderStyle:"round",borderColor:M.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},Ie.createElement(Yt,{scrollByOne:!0,children:x,height:r-2,selectedIndex:a,itemHeight:1})))};var td=e=>`${e}::log`,oi=e=>e==="Assignees"||e==="Tags",ii=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=ce(),o=process.stdout.columns||120,i=ri(()=>td(e.id),[e.id]),a=ri(()=>[...e.log].reverse().map(ti).join(`
|
|
45
|
-
`),[e.log]);
|
|
43
|
+
`,zs=(e,t)=>{let n=new Map;for(let r of[...t,...e])n.set(_n(r),r);return[...n.values()].sort((r,o)=>{let i=ao(r)-ao(o);return i!==0?i:_n(r).localeCompare(_n(o))})},$n=({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=zs(r.value,n.value),i=qs(o);return(Wt.existsSync(t)?Wt.readFileSync(t,"utf8"):"")===i?c("Event file already merged",!1):(Wt.mkdirSync(jn.dirname(t),{recursive:!0}),Wt.writeFileSync(t,i,"utf8"),c("Merged event file",!0))},Ht=({repoRoot:e,stateBranchRoot:t})=>{let n=Gr(t);if(a(n))return s(n.message);let r=Oe(t),o=Oe(e),i=!1;for(let d of n.value){let l=jn.join(r,d),u=jn.join(o,d),m=$n({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 Xs=({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=Ln({root:e,fileName:n}),o=Ln({root:t,fileName:n});return Gs.existsSync(r)?$n({sourceFile:r,targetFile:o}):c("Local own event file missing, nothing to merge",!1)},Ys=async({cwd:e,ensureUpstream:t})=>{let n=await Ft(e);if(a(n))return s(n.message);let r=n.value,o=qr({repoRoot:r});if(a(o))return s(o.message);let i=o.value,d=await it(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 Zr(r);if(a(l))return s(l.message);let u=await eo({repoRoot:r,stateBranchRoot:i,ensureUpstream:t});if(a(u))return s(u.message);let m=await it(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=Xr(r,i);return a(p)?s(p.message):c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:i,bootstrapped:u.value})},co=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{let r=Xs({repoRoot:e,stateBranchRoot:t,ownEventFileName:n});if(a(r))return s(r.message);let o=await jr(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 Dt({stateBranchRoot:t,eventFileName:n});if(a(i))return s(i.message);let d=await Qr({repoRoot:e,stateBranchRoot:t});return a(d)?s(d.message):c("Merged, staged, and committed own event file",{createdCommit:!0,commitSha:d.value})},Kt=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 Ys({cwd:e,ensureUpstream:!0});if(a(n))return n;let{repoRoot:r,stateBranchRoot:o,bootstrapped:i}=n.value,d=await $r(r);if(a(d))return s(d.message);if(d.value)return s("Cannot run :sync while the repository is in detached HEAD state");let l=!1,u,m=!1,p=!1,x=!1,N=Ke(r);if(a(N))return N;let I=N.value,R=await Fn({cwd:o,branch:I});if(a(R))return s(R.message);m=R.value;let b=Ht({repoRoot:r,stateBranchRoot:o});if(a(b))return s(b.message);x=b.value;let E=await co({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(a(E))return s(E.message);if(l=E.value.createdCommit,u=E.value.commitSha,l||i){let w=await ct({stateBranchRoot:o,repoRoot:r}),W=w;if(a(w)&&_r(w.message)){let Se=await Fn({cwd:o,branch:I});if(a(Se))return s(Se.message);let ne=await co({repoRoot:r,stateBranchRoot:o,ownEventFileName:t});if(a(ne))return s(ne.message);ne.value.createdCommit&&(l=!0,u=ne.value.commitSha),W=await ct({stateBranchRoot:o,repoRoot:r})}if(a(W))return s(W.message);p=W.value,logger.debug("[sync] pushed to state branch",p)}else logger.debug("[sync] no commit created, skipped push");if(l){let w=await L({args:["rev-parse","HEAD"],cwd:o});if(a(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 oa from"node:os";import po from"node:path";import{z as mt}from"zod";import{accessSync as Js,copyFileSync as Zs,existsSync as Vt,mkdirSync as lo,readdirSync as uo,readFileSync as Qs,renameSync as ea,rmSync as ta,statSync as mo,unlinkSync as na,writeFileSync as ra}from"node:fs";import Ge from"node:path";var re={writeToFile:(e,t)=>{try{let n=Ge.dirname(e);Vt(n)||lo(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);ra(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Qs(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=re.readFile(e);return t===null?null:JSON.parse(t)}catch(t){return logger.error(`Failed to read JSON at ${e}:`,t),null}},dirExists:e=>{try{return Vt(e)&&mo(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Js(e),!0}catch{return!1}},mkDir:e=>lo(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Ge.parse(t);for(;;){let r=Ge.join(t,e);try{if(Vt(r)&&mo(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Ge.dirname(t)}return null},readFirstJSON(e){try{if(!re.dirExists(e))return null;let t=uo(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=Ge.join(e,t);return re.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return re.dirExists(e)?uo(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{na(e)}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{ta(e,{recursive:!0,force:!0})}catch(t){t?.code!=="ENOENT"&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Ge.dirname(t)),!n?.overwrite&&Vt(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{ea(e,t)}catch(r){if(r?.code==="EXDEV"){Zs(e,t),this.rmFile(e);return}throw r}}};var ia={userId:"",userName:"",preferredEditor:"",autoSync:!1},go=mt.object({preferredEditor:mt.string().optional(),userName:mt.string().optional(),userId:mt.string().optional(),autoSync:mt.boolean().optional()}).strict(),sa="config.json",fo=()=>po.join(oa.homedir(),se),Wn=()=>po.join(fo(),sa),Hn=()=>{try{return re.mkDir(fo()),c(`Ensured ~/${se} exists`,null)}catch{return s(`Unable to create ~/${se}`)}},aa=e=>{let t;try{t=JSON.parse(e)}catch{return s(`Invalid ~/${se}/config.json JSON`)}let n=go.safeParse(t??{});return n.success?c("Parsed config",n.data):s(`Invalid ~/${se}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},vo=()=>{let e=Hn();if(a(e))return s(e.message);let t=Wn(),n=re.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{autoSync:!1,preferredEditor:"",userId:"",userName:""}):aa(n)},yo=e=>{let t=Hn();if(a(t))return s(t.message);let n=go.safeParse(e);if(!n.success)return s(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Wn();try{return re.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
44
|
+
`),c("Config written",null)}catch{return s(`Unable to write ~/${se}/config.json`)}},qt=e=>{let t=vo();if(a(t))return s("Failed to read existing config");let n={...t.value,...e};return yo(n)},xo=()=>{let e=Wn(),t=Hn();if(a(t))return s(`Unable to create ~/${se}`);if(!(re.readFile(e)!==null)){let u=yo(ia);if(a(u))throw new Error(`Unable to create ~/${se}/config.json`)}let r=vo();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:i,userId:d,autoSync:l}=r.value;return!i||!d?s(`User name or ID not configured in ~/${se}/config.json`):c("successfully loaded settings",{preferredEditor:o??"",userName:i,userId:d,autoSync:l??!1})};import{monotonicFactory as la,ulid as zt}from"ulid";var Be=24n,da=Be*4n,_e=(1n<<da)-1n,ca=/^[0-9a-f]+$/;function ho(e){return!e||!ca.test(e)?s(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function xe(e,t=Be){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 xe(_e/2n,Be);let n=e?ho(e):c("Resolved lower bound",0n);if(a(n))return n;let r=t?ho(t):c("Resolved upper bound",_e);if(a(r))return r;let o=n.value,i=r.value;if(i<=o)return xe(_e/2n,Be);let d=(o+i)/2n;return d===o||d===i?s("No rank space available between neighbors"):xe(d,Be)}function No(){return xe(_e/2n,Be)}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=_e*BigInt(r+1)/(t+1n),i=xe(o,Be);if(a(i))return i;n.push(i.value)}return c("Resolved evenly spaced ranks",n)}var q={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History"};var Gt=la(),Xt=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let i=Gt(),d=Gt(),l=Gt(),u=Gt(),m=No();if(a(m))return m;let p=V(m.value,void 0);if(a(p))return p;let x=V(p.value,void 0);return a(x)?x:c("Created issue events",[{id:zt(),userId:r,userName:o,action:"add.issue",payload:{id:i,parent:t,name:e,rank:n}},{id:zt(),userId:r,userName:o,action:"add.field",payload:{id:d,parent:i,name:q.DESCRIPTION,val:"",rank:m.value}},{id:zt(),userId:r,userName:o,action:"add.field",payload:{id:l,parent:i,name:"Assignees",rank:p.value}},{id:zt(),userId:r,userName:o,action:"add.field",payload:{id:u,parent:i,name:"Tags",rank:x.value}}])};import{monotonicFactory as qd,ulid as Re}from"ulid";import{useSyncExternalStore as Hd}from"react";var P={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT"};function Kn(e){return e.context==="WORKSPACE"}function ee(e){return e.context==="TICKET"}function Io(e){return e.context==="FIELD"}var Yt=e=>e.context==="SWIMLANE",Co=e=>e.context==="BOARD";var g={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 Zt=(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 bo=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},Ro=(e,t)=>t?e.get(t)??[]:[];var So=new WeakMap,ua=e=>{let t=So.get(e);return t||(t=bo(e),So.set(e,t)),t};var Ao=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Ro(ua(e),r).filter(i=>Jt(r,i)>=n)};var ma={hint:"",hints:[],overlap:0,remainder:""},wo=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return ma;let o=Ao({wordList:r,inputToMatch:e,overlapThreshold:1});return pa(t,o)},pa=(e,t)=>{let n=t[0]??"",r=Jt(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}};var To=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];var X={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 ga}from"ulid";var Vn=(e,t)=>{let n=U(e),r=Eo(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:ga(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};var fa=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[J,Qt]=fa;var k=(e,t)=>s(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),va={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=X.workspace(t,n,r),i=ft(o);if(a(i))return k(i.message,e);let d=h.createNode(o);return a(d)?k(d.message??"Failed to initialize workspace",e):Kn(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=X.workspace(t,n,r),i=h.createNode(o);return a(i)?k(i.message??"Failed to add workspace",e):Kn(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(X.board(t,n,r,o));return a(i)?k(i.message??"Unable to create board",e):Co(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(X.swimlane(t,n,r,o));return a(i)?k(i.message??"Unable to create swimlane",e):Yt(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(X.ticket(t,n,r,o));return a(i)?k(i.message??"Unable to create issue",e):ee(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=h.createNode(X.field({id:t,name:n,parentNodeId:r,rank:i,props:{value:o},childRenderAxis:n.includes(q.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?k(d.message??`Unable to create field: ${n}`,e):Io(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(!h.getNode(t))return k(`Unable to locate node with id ${t}`,e);let o=h.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=h.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=h.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=h.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=h.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=h.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=h.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=h.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=h.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=h.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=h.getNode(t);if(!o)return k("Unable to locate issue",e);if(!ee(o))return k("Can only close issues",e);let i=h.getNode(J);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=h.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=h.getNode(t);if(!o)return k("Unable to locate issue",e);if(!ee(o))return k("Can only reopen issues",e);let i=h.getNode(J);if(!i)return k("Unable to locate closed swimlane",e);if(n===i.id)return k("Cannot reopen issue into closed swimlane",e);if(!h.getNode(n))return k("Reopen parent no longer exists",e);let l=h.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=h.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=h.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=h.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}})}},ya=(e,t)=>{let n=h.getNode(e);n&&h.updateNode({...n,log:[...n.log??[],t]})},xa=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 pt(e,t=!1){let n=va[e.action](e);if(a(n))return n;t||([...new Set(xa(e))].forEach(d=>ya(d,e)),oe(d=>({...d,eventLog:[...d.eventLog,e]})));let r=e.userId,o=e.userName;return!r?.length||!o?.length?k("Invalid user ID format",e):(h.createContributor({name:o,id:r}),n)}var gt=e=>e.map(t=>pt(t));function H(e){let t=pt(e);if(t.status!==fe.Success)return t;let n=_t({event:e});return a(n)?n:t}function Te(e){return e.map(t=>H(t))}var Mo=e=>qn(U(e),{at:"end"}),qn=(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(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=Po(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=Po(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")}}},U=e=>Object.values(v().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Po=(e,t)=>e.findIndex(n=>n.id===t),ko=(e,t,n={at:"end"})=>qn(U(t).filter(r=>r.id!==e),n),he=(e,t,n,r)=>{let o=ko(t,e,n);if(a(o))return o;if(!o.value.needsRebalance)return c("Resolved rank",o.value.rank);let i=Vn(e,r);if(a(i))return i;let d=H(i.value);if(a(d))return d;let l=ko(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)},Me=(e,t)=>{let n=Mo(e);if(a(n))return n;if(!n.value.needsRebalance)return c("Resolved rank",n.value.rank);let r=Vn(e,t);if(a(r))return r;let o=H(r.value);if(a(o))return o;let i=Mo(e);return a(i)?i:i.value.needsRebalance?s("Rank rebalance failed to create space"):c("Resolved rank after rebalance",i.value.rank)};var Ye=(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}`)},ha=(e,t)=>{let{nodes:n}=v(),r=n[e];for(;r?.parentNodeId;){if(r.parentNodeId===t)return!0;r=n[r.parentNodeId]}return!1},zn=(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){oe(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=zn(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=zn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return U(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),i=this.getNode(t);if(!o)return s("Node not found");if(!i)return s("Target parent not found");if(r===e)return s("Cannot move root node");if(e===t)return s("Cannot move node into itself");let d=zn(o,"move");if(d)return d;if(ha(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,d=u=>{let m=t[u];if(!(!m||i.has(u))){i.add(u);for(let p of U(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?(C({nodes:l}),c("Successfully tomb stoned",o)):s("Unable to delete undefined")},createContributor(e){let t=oe(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(U(d.id).some(p=>p.props?.value===t))return s("Contributor already assigned");let u=X.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=oe(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(U(d.id).some(p=>p.props?.value===t))return s("Tag already assigned");let u=X.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=U(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=U(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=oe(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=oe(o=>({...o,nodes:{...o.nodes,[e]:n}}));return a(r)?s(r.message):c("Locked node",n)},updateNode(e){let t=oe(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?t:c("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){return v().tags[e]},getNode(e){return v().nodes[e]},getSiblings(e){return U(e)}};var en=()=>{let e=me(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim();return{isSetup:n&&t,hasPreferredEditor:n,hasUserName:t,userName:e.userName,preferredEditor:e.preferredEditor}},Fo=()=>{let e=Ae(process.cwd());if(a(e))return s("Unable to determine if repository is initialized");let t=we(e.value);return et(t)};var Y={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:Y.cyan,accent2:Y.magenta,primary:Y.white,secondary:Y.grayDark,secondary2:Y.grayLight,gray:Y.gray,green:Y.green,yellow:Y.yellow,red:Y.red};var y={red:Y.red,yellow:Y.yellow,green:Y.green,blue:Y.blue,magenta:Y.magenta,cyan:Y.cyan},Je={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 Lo=(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):[]},Gn=e=>Lo(e,"Tags").map(t=>h.getTag(t)).filter(t=>!!t),tn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ee(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Gn(n)??[])},nn=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!ee(n)?s("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Xn(n)??[])},Xn=e=>Lo(e,"Assignees").map(t=>h.getContributor(t)).filter(t=>!!t);var Do=(e,t)=>{let r=S(e.id).find(o=>o.title===t);return r&&typeof r.props?.value=="string"?Xe(r.props.value):""};var f={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 Na=/^(\d+)(h|d|w|mo|y)$/,Ea=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Ia=({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},Ca=(e,t=new Date)=>{let n=e.match(Na);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}},ba=e=>{let t=e.match(Ea);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 Ia({year:l,month:u,day:m,hour:p,minute:x})?new Date(l,u-1,m,p,x):null},rn=e=>{let t=e.trim().toLowerCase();return Ca(t)??ba(t)},Oo=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Ra=[{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}],Uo=(e=Ra)=>{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 Sa=["BOARD","TICKET","SWIMLANE"],je=[f.SYNC,f.HELP,f.EXPORT,f.SET_VIEW,f.SET_EDITOR,f.SET_USERNAME],on=[f.NEW,f.RENAME,f.DELETE,f.MOVE],sn=[f.TAG,f.UNTAG,f.ASSIGN,f.UNASSIGN,f.CLOSE_ISSUE,f.RE_OPEN_ISSUE,f.SET_DESCRIPTION],Bo=[f.FILTER,f.PEEK],Aa={WORKSPACE:[...je,...on],BOARD:[...Bo,...je,...on],SWIMLANE:[...Bo,...je,...on,...sn],TICKET:[...je,...on,...sn],FIELD:[...je,...sn],FIELD_LIST:[...je,...sn],TEXT:[...je]},wa=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Ta=()=>{let{currentNode:e,selectedNode:t,readOnly:n}=v();if(!en().isSetup)return[f.HELP,f.SET_EDITOR,f.SET_USERNAME];if(!Fo())return[f.HELP,f.INIT];if(n)return[f.HELP,f.PEEK,f.EXPORT,f.SET_VIEW];let o=e.context??"WORKSPACE",i=t?.context,d=i&&Sa.includes(i);return Aa[o].filter(l=>l===f.RENAME||l===f.DELETE||l===f.MOVE?d:!0)},z=e=>{let{currentNode:t}=v(),n=t.context??"WORKSPACE";return{[f.NONE]:Ta(),[f.EXIT]:["confirm"],[f.EXPORT]:[],[f.SYNC]:[],[f.INIT]:[],[f.HELP]:[],[f.PEEK]:[...Uo(),"now","prev","next"],[f.SET_USERNAME]:[],[f.SET_DESCRIPTION]:["confirm"],[f.DELETE]:["confirm"],[f.RE_OPEN_ISSUE]:["confirm"],[f.CLOSE_ISSUE]:["confirm"],[f.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[f.FILTER]:["tag","assignee","description","title","clear"],[f.SET_VIEW]:["dense","wide"],[f.SET_EDITOR]:[...To],[f.TAG]:[...new Set([...Object.keys(Je),...h.getExistingTags()])],[f.UNTAG]:[...tn()?.value?.map(({name:o})=>o)??[]],[f.UNASSIGN]:[...nn()?.value?.map(({name:o})=>o)??[]],[f.ASSIGN]:h.getExistingAssignees(),[f.RENAME]:[],[f.NEW]:wa(n)}[e]??[]};import Ze from"chalk";import{decodeTime as _o}from"ulid";var jo=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 $o=e=>{try{return c("Decoded date",new Date(_o(e)))}catch(t){return s("Decoding failed + "+t.message)}},Yn=e=>{if(!e?.id)return null;try{return _o(e.id)}catch{return null}};var Pe=(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 Wo from"chalk";var Zn={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Ma=(e,t,n)=>Math.max(t,Math.min(n,e)),Jn=(e,t,n)=>e+(t-e)*n,Ho=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Pa=(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)]},ka=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Fa=(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))],vt=e=>{let n=Ho(e)%360,r=Pa(n,Zn.stringColor.saturation,Zn.stringColor.lightness);return ka(r)},La=e=>{let t=Zn.gradient.stops,n=Ma(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 Fa(t[i],t[i+1],d)},an=e=>Ho(e.toLowerCase().trim())/4294967295,Da=e=>{let t=an(e);return La(t)},Oa=e=>{let[t,n,r]=Da(e);return{normal:o=>Wo.bgRgb(t,n,r).black(o),cursor:o=>Wo.bgRgb(t,n,r).white.bold(o)}};var Qn=e=>Oa(e).normal(` ${e} `),te=(e,t=Je)=>{let r=(o=>o.toLowerCase().trim())(e);return r&&t[r]?t[r]:vt(r)};var Ne={None:"none",Invalid:"invalid",Valid:"valid"};var Ua=["BOARD","TICKET","SWIMLANE"],er=()=>{let e=v().selectedNode;return e?.context?Ua.includes(e?.context)?$():B({message:"Command not available in this context"}):B({message:"Missing target context"})},Z="<ENTER> to confirm",$=(e="",t=[])=>({message:e,validity:Ne.Valid,completionWordList:t}),B=({message:e,completionWordList:t=[]})=>({validity:Ne.Invalid,message:e,completionWordList:t}),xt=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)=>an(p)-an(x)).slice(0,r).map(Qn),m=u.length>i?u.join(" "):"";return m?`${e}${m}${n}`:""},tr=({modifier:e})=>{let t="confirm";return e===t?$(Z):B({message:xt(e)?`if you are certain, enter ${Qn(t)}`:"",completionWordList:[t]})},Ba=({list:e,hint:t})=>({modifier:n})=>e.includes(n)?$(Z):B({message:xt(n)?t:""}),_a=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?B({message:n}):$():B({message:xt(r)?t:""}),yt=({hint:e})=>({modifier:t,inputString:n})=>xt(t)&&xt(n)?B({message:e,completionWordList:[]}):$(Z),ja={[f.EXPORT]:()=>$(Z+", and create export markdown file"),[f.PEEK]:e=>{let t=e.modifier;if(t==="now")return $(Z);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 $(Z);let r=rn(t);if(!t||!r)return B(n);let o=Pe(v().breadCrumb,"BOARD");if(a(o))return B({message:"Command is not applicable in this context"});let i=$o(o.value.id);return a(i)?B({message:"Unable to peek: board id is not a valid ULID"}):Oo({date:r,horizonDate:i.value})?$(Z):B({message:Ze.red(`nothing to peek before ${i.value.toISOString().slice(0,16).replace("T"," ")}`)})},[f.EXIT]:()=>$(Z+" and exit the application"),[f.INIT]:()=>$(Z),[f.FILTER]:e=>{if(e.modifier==="clear")return $();let t=d=>z(f.FILTER).includes(d);if(!e.modifier||!t(e.modifier??""))return B({message:ke({wordList:z(f.FILTER),inputString:e.inputString}),completionWordList:z(f.FILTER)});let r=Object.values(v().tags).map(d=>d.name),o=Object.values(v().contributors).map(d=>d.name),i=e.modifier==="tag"?r:e.modifier==="assignee"?o:[];return e.inputString?i.length&&!i.includes(e.inputString.trim()??"")?B({message:ke({prefix:`existing ${e.modifier}s... `,wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i}):$():B({message:ke({prefix:"one of... ",wordList:i,noOfHints:10,inputString:e.inputString}),completionWordList:i})},[f.NONE]:e=>{let t=z(f.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?$():B({message:ke({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0})})},[f.NEW]:e=>_a({list:z(f.NEW),hint:ke({wordList:z(f.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[f.SET_DESCRIPTION]:()=>$(Z),[f.HELP]:()=>$(Z),[f.RENAME]:()=>{let e=er();return e.validity==="invalid"?e:$(Z)},[f.DELETE]:e=>{let t=er();return t.validity==="invalid"?t:tr(e)},[f.CLOSE_ISSUE]:e=>tr(e),[f.RE_OPEN_ISSUE]:e=>tr(e),[f.MOVE]:e=>{let t=er();return t.validity==="invalid"?t:yt({hint:ke({prefix:"hey hacker! These commands are blocked for you... ",wordList:z(f.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[f.TAG]:e=>{let t=h.getExistingTags().map(n=>` ${Ze.bgHex(te(n))(" "+n+" ")} `).slice(0,10);return yt({hint:"tag name like... "+t.join("")})(e)},[f.UNTAG]:e=>{let t=tn();if(a(t))return B({message:"Invalid untag target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${Ze.bgHex(te(r))(" "+r+" ")} `).slice(0,10);return n.length?yt({hint:" ... "+n.join("")})(e):B({message:"Issue has not tags",completionWordList:[]})},[f.ASSIGN]:e=>{let t=h.getExistingAssignees().map(n=>` ${Ze.bgHex(te(n))(" "+n+" ")} `).slice(0,10);return yt({hint:"assign to... "+t.join("")})(e)},[f.UNASSIGN]:e=>{let t=nn();if(a(t))return B({message:"Invalid unassign target",completionWordList:[]});let n=t.value.map(({name:r})=>r).map(r=>` ${Ze.bgHex(te(r))(" "+r+" ")} `).slice(0,10);return n.length?yt({hint:"remove assignee... "+n.join("")})(e):B({message:"Issue has no assignees",completionWordList:[]})},[f.SET_EDITOR]:e=>{logger.debug(`Validating command: ${e.command} ${e.modifier} ${e.inputString}`);let t=z(f.SET_EDITOR);return e.modifier?$(Z):B({message:ke({wordList:t,inputString:e.inputString})})},[f.SET_USERNAME]:e=>e.inputString?$():B({message:`Enter a username. Saved in ${Ze.bgBlack("~/.epiq-global/")}`}),[f.SET_VIEW]:e=>Ba({list:z(f.SET_VIEW),hint:ke({wordList:z(f.SET_VIEW),noOfHints:3,inputString:e.inputString})})(e),[f.SYNC]:()=>$(Z)},Ko=Object.fromEntries(Object.entries(ja).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Vo=["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 qo=e=>Object.values(f).includes(e),zo=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:i}=e,{message:d,validity:l,completionWordList:u}=Ko[n].validate(n,r,i),m=o==="command"?Object.values(f):n&&e.target==="modifier"?z(n):Vo;return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:d??"",autoCompletion:t?wo(e,[...u,...m]):{hint:"",hints:[],remainder:"",overlap:0}}};var Go=e=>{let t=e.trimStart(),n=Wa(t),r=n[0]??"",o=n[1]??"",i=/\s$/.test(e),d=Ha(e),l=qo(r)?r:null,u=l!==null,m=r!=="",p=l?z(l)??[]:[],x=l&&p.includes(o)?o:"",N="word";n.length===0||n.length===1&&!i?N="command":(n.length===1&&i||n.length===2&&!i)&&(N="modifier");let I=i?"":d,R=$a(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:N,inputToMatch:I,inputString:R}},$a=(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},Wa=e=>e.trim()?e.trim().split(/\s+/):[],Ha=e=>e.trimEnd().split(/\s+/).at(-1)??"";var Xo=" ",Qe={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Ne.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Ka=new Set,Yo=()=>{for(let e of Ka)e()};var Ee=e=>{let n=e(Qe),r=Go(n.value),o=n.cursorPosition===n.value.length;Qe={...n,commandMeta:zo(r,o)},Yo()},ht=({message:e,status:t})=>{let n=structuredClone(Qe);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Qe=n,Yo(),c(e,null)},nr=e=>{Ee(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},rr=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}})},Zo=()=>{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}})},O=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),d=i+o,l=Math.max(0,Math.min(i.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},Qo=()=>{Ee(e=>({...e,commandIsPending:!0}))},ei=({addToHistory:e=!0})=>{Ee(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1})),Va()},ti=()=>{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}})},ni=()=>{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}})},Va=()=>O(()=>""),ie=()=>Qe,dn=()=>{let[e,...t]=Qe.value.split(Xo);return t.join(Xo).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 ri=e=>{let{context:t}=v()?.currentNode;if(!t)return A.None;switch(e){case f.EXIT:return A.Exit;case f.EXPORT:return A.Export;case f.INIT:return A.Init;case f.DELETE:return A.Delete;case f.SET_DESCRIPTION:return A.Edit;case f.HELP:return A.ViewHelp;case f.RE_OPEN_ISSUE:return A.ReopenIssue;case f.CLOSE_ISSUE:return A.CloseIssue;case f.TAG:return A.TagTicket;case f.UNTAG:return A.UntagTicket;case f.ASSIGN:return A.AssignUserToTicket;case f.UNASSIGN:return A.UnassignUserFromTicket;case f.RENAME:return A.Rename;case f.NEW:return A.NewItem;case f.FILTER:return A.Filter;case f.MOVE:return A.Move;case f.PEEK:return A.Peek;case f.SET_USERNAME:return A.SetUserName;case f.SET_EDITOR:return A.SetEditor;case f.SET_VIEW:return A.SetView;case f.SYNC:return A.Sync;default:return A.None}};import{ulid as K}from"ulid";import xi from"node:fs";import hd from"node:path";import Nd from"react";import{Box as yd}from"ink";import vn from"react";import{Box as sr,Text as rd}from"ink";import ge from"react";import{Text as oi}from"ink";import ii,{useEffect as si,useState as qa}from"react";var ai={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"command-line":["\u276F "]},de=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=pe(),r=ai[n]??ai.default,[o,i]=qa(0);if(si(()=>{i(0)},[r]),si(()=>{if(!e)return;let l=setInterval(()=>{i(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return ii.createElement(oi,null,t);let d=r[o]??r[0]??t;return ii.createElement(oi,{color:M.accent,dimColor:o===1},d)};import{Box as or,Text as za}from"ink";import cn from"react";var ln=({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,N=e.slice(p,x),I=e.length>l,R=i,b=I?Math.max(1,Math.floor(l/e.length*R)):R,E=Math.max(0,R-b),w=Math.max(1,e.length-l),W=I?Math.floor(p/w*E):0;return cn.createElement(or,{flexDirection:"row",height:i,width:"100%"},cn.createElement(or,{flexDirection:"column",flexGrow:1,height:i},N),cn.createElement(or,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((Se,ne)=>cn.createElement(za,{key:ne,color:I&&ne>=W&&ne<W+b?M.accent:M.secondary},I?"\u2502":" "))))};import{Box as pn,Text as ed}from"ink";import $e from"react";import{Text as Ga}from"ink";import Xa from"react";var Ya=e=>e.toLowerCase().trim(),Ja=(e,t=Je)=>{let n=Ya(e);return t[n]?t[n]:vt(n)},un=({id:e,isSelected:t})=>{let n=h.getContributor(e);if(n)return Xa.createElement(Ga,{underline:t,color:Ja(n.name)},"@"+n.name)};import{Text as Za}from"ink";import Qa from"react";var mn=({id:e,isSelected:t})=>{let n=h.getTag(e);if(n)return Qa.createElement(Za,{underline:t,backgroundColor:te(n.name),color:M.primary}," "+n.name+" ")};var di=({width:e,ticket:t,isSelected:n})=>{let r=e-14,o=Zt(Xe(t.title),r),i=Gn(t),d=Xn(t);return $e.createElement(pn,{borderStyle:"round",width:e-7,height:4,flexDirection:"column",borderColor:n?M.accent:M.secondary,justifyContent:"space-between"},$e.createElement(pn,{borderBottom:!0},$e.createElement(pn,{paddingLeft:1,flexDirection:"column"},$e.createElement(ed,{color:M.primary},o))),$e.createElement(pn,{flexDirection:"row",paddingLeft:1},i.map(l=>$e.createElement(mn,{key:l.id,id:l.id})),d.map(l=>$e.createElement(un,{key:l.id,id:l.id}))))};import td from"chalk";import{Box as Nt,Text as ir}from"ink";import Ie from"react";var nd=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,ci=({width:e,ticket:t,isSelected:n,index:r,mode:o})=>{let i=S(t.id),d=b=>{let E=i.find(w=>w.title===b);return E?S(E.id).map(w=>typeof w.props?.value=="string"?w.props.value:"").filter(w=>!!w):[]},l=d("Tags").map(b=>h.getTag(b)).filter(b=>!!b),u=d("Assignees").map(b=>h.getContributor(b)).filter(b=>!!b),m=1,p=l.length*(1+m),x=u.length*(2+m),N=l.map(b=>Ie.createElement(Nt,{key:b.id,paddingRight:m},Ie.createElement(ir,{color:te(b.name)},"\u25A0"))),I=u.map(b=>Ie.createElement(Nt,{key:b.id,paddingRight:m},Ie.createElement(ir,{color:vt(b.name)},"@"+b.name.at(0)))),R=n?M.accent:o===g.MOVE?M.secondary:M.primary;return Ie.createElement(Nt,{borderBottom:!0,justifyContent:"space-between"},Ie.createElement(Nt,null,Ie.createElement(de,{isSelected:n,placeholder:td.dim.gray(r+1+" ")}),Ie.createElement(ir,{wrap:"truncate",color:R},nd(t.title,e-p-x-14))),Ie.createElement(Nt,null,N,I))};var od=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:i,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u}=pe(),m=u[e.id]??[],p=`${e.title} (${m.length})`,x=3,N=o?1:4,I=r-x-(o?2:1),R=ge.createElement(sr,{borderStyle:"round",borderColor:M.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},ge.createElement(de,{isSelected:t}),ge.createElement(rd,{bold:!0,color:t?M.accent:M.primary},p," ",e.readonly?"\u{1F512}":"")),b=(E,w)=>{let W=i&&d===w;return o?ge.createElement(ci,{key:E.id,index:w,width:n,ticket:E,isSelected:W,mode:l}):ge.createElement(di,{key:E.id,width:n,ticket:E,isSelected:W})};return ge.createElement(sr,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?M.accent:M.secondary,paddingRight:1,paddingLeft:1,height:r},R,ge.createElement(sr,{padding:o?1:0},m.length>0&&ge.createElement(ln,{selectedIndex:d,height:I,itemHeight:N},m.map(b)),ge.createElement(de,{isSelected:i&&d===-1})))},li=ge.memo(od);import{Box as cr,Text as fd}from"ink";import Fe,{useEffect as lr,useMemo as gi}from"react";import We from"chalk";import ui from"string-width";import{decodeTime as id}from"ulid";var sd=(e,t)=>e+" ".repeat(Math.max(0,t-ui(e))),ad=(e,t)=>" ".repeat(Math.max(0,t-ui(e)))+e,dd=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)})(),cd=e=>{switch(e.action){case"move.node":{let t=h.getNode(e.payload.parent);return`to ${t?We.dim.bgBlack(` ${t.title} `):"unknown"} with rank ${e.payload.rank}`}case"tag.issue":{let t=v().tags[e.payload.tagId];return t?We.bgHex(te(t.name))(` ${t.name} `):"unknown tag"}case"untag.issue":{let t=v().tags[e.payload.tagId];return t?We.bgHex(te(t.name))(` ${t.name} `):"unknown tag"}case"assign.issue":{let t=v().contributors[e.payload.contributor];return t?We.hex(te(t.name))(` ${t.name} `):"unknown user"}case"unassign.issue":{let t=v().contributors[e.payload.contributor];return t?We.hex(te(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""}},ld=e=>{let t=jo(id(e));return We.gray(ad(t,8))},ud=12,md=e=>sd(`${e}`,ud),mi=e=>{let t=ld(e.id),n=md(e.userName),r=dd(e.action),o=cd(e),i=We.dim("\u203A"),d=[r,o].filter(Boolean).join(" ");return`${n} ${t} ${i} ${d}`};import{Box as gn,Text as pd}from"ink";import Ce from"react";var pi=({selectedIndex:e,parent:t,selected:n})=>{let{currentNode:r}=pe(),{title:o}=t,i=S(t.id).map(d=>{let l=typeof d.props?.value=="string"?d.props.value:"";if(o==="Assignees")return h.getContributor(l)?.id;if(o==="Tags")return h.getTag(l)?.id}).filter(d=>!!d);return Ce.createElement(gn,{alignItems:"center",paddingTop:1},Ce.createElement(gn,{minWidth:12},Ce.createElement(de,{isSelected:n}),Ce.createElement(pd,{color:n?M.accent:M.secondary2},o,":")),Ce.createElement(gn,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((d,l)=>{let u=r.id===t.id&&l===e;return Ce.createElement(gn,{key:`${o}-${d}`,paddingRight:2,minHeight:1},Ce.createElement(de,{isSelected:u}),o==="Assignees"?Ce.createElement(un,{isSelected:u,id:d}):o==="Tags"?Ce.createElement(mn,{isSelected:u,id:d}):null)})))};import{Box as fn,Text as ar}from"ink";import be,{useEffect as gd}from"react";var dr=({id:e,label:t,text:n,height:r,selected:o,maxWidth:i})=>{let{selectedIndex:d,currentNode:l}=pe(),u=N=>String(N).replace(/\r?\n/g,""),m=typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[];gd(()=>{let N=[];return m.forEach((I,R)=>{let b=xe(BigInt(R+1));if(!et(b))return;let E=X.text({id:`${e}-${R}`,name:`Line ${R+1}`,parentNodeId:e,rank:b.value,props:{value:I},readonly:!0,isVirtual:!0}),w=h.createNode(E);et(w)&&N.push(w.value.id)}),()=>N.forEach(h.deleteNode)},[e,n]);let p="\u2029",x=m.map((N,I)=>{let R=l.id===e&&d===I;return be.createElement(fn,{key:`${e}-${I}`},be.createElement(ar,{color:R?M.primary:M.secondary2,dimColor:!R},`${I+1} `.padStart(5,"\xA0")),be.createElement(ar,{backgroundColor:R?"gray":""},u(N.length?Zt(N,i-10):p)))});return be.createElement(fn,{flexDirection:"column",paddingTop:1},be.createElement(fn,null,be.createElement(de,{isSelected:o}),be.createElement(ar,{color:o?M.accent:M.secondary2},t)),be.createElement(fn,{flexDirection:"row",borderStyle:"round",borderColor:M.secondary,paddingLeft:1,paddingRight:1,marginLeft:1},be.createElement(ln,{scrollByOne:!0,children:x,height:r-2,selectedIndex:d,itemHeight:1})))};var vd=e=>`${e}::log`,fi=e=>e==="Assignees"||e==="Tags",vi=({ticket:e,height:t})=>{let{selectedIndex:n,currentNode:r}=pe(),o=process.stdout.columns||120,i=gi(()=>vd(e.id),[e.id]),d=gi(()=>[...e.log].reverse().map(mi).join(`
|
|
45
|
+
`),[e.log]);lr(()=>{if(h.getNode(i))return;let w=xe(_e);if(a(w))return;let W={...X.field({id:i,name:q.HISTORY,parentNodeId:e.id,rank:w.value,props:{value:d},isVirtual:!0}),readonly:!0,childRenderAxis:"vertical"};return h.createNode(W),()=>{h.deleteNode(i)}},[i,e.id,d]),lr(()=>{let E=h.getNode(i);E&&E.props.value!==d&&h.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;lr(()=>{u&&(n>=0||D.navigate({selectedIndex:0}))},[u,n]);let m=S(e.id);if(u){let E=h.getNode(i),W=t-3;return Fe.createElement(cr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},E?Fe.createElement(dr,{id:E.id,label:"Event log",text:E.props.value??"",selected:!1,maxWidth:o,height:W}):null)}let p=m.reduce((E,w)=>fi(w.title)||w.id===i?E+1:E,0),x=2,N=p*1,R=t-3-N-x,b=(E,w)=>fi(E.title)?Fe.createElement(pi,{key:E.id,parent:E,selected:w,selectedIndex:n}):E.id===i?Fe.createElement(cr,{key:E.id,paddingTop:1},Fe.createElement(de,{isSelected:w}),Fe.createElement(fd,{backgroundColor:M.secondary,color:w?M.accent:M.primary}," History \u203A\u203A ")):E.title===q.DESCRIPTION?Fe.createElement(dr,{label:"Description (press e to edit)",key:E.id,id:E.id,text:E.props.value??"",selected:w,maxWidth:o,height:R}):null;return Fe.createElement(cr,{width:o,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},m.map((E,w)=>b(E,l&&n===w)))};var xd=({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),N=Math.floor(l/3),I=Math.floor(l/Math.max(e.length,1)),R=Math.min(I,N),b=i==="dense";return vn.createElement(yd,{flexDirection:"row",height:d},p&&e.map((E,w)=>{let W=t.id===E.id,Se=W?n:-1,ne=t.context===P.BOARD&&n===w;return vn.createElement(li,{key:E.id,height:d,width:R,swimlane:E,isSelected:ne,isDense:b,isFocused:W,listSelectedIndex:Se,mode:o})}),m&&x&&vn.createElement(vi,{height:d,ticket:x}))},yi=vn.memo(xd);import{render as Ed}from"ink";import{Writable as Id}from"node:stream";var Et=e=>String(e).padStart(2,"0"),Cd=e=>{let t=e.getUTCFullYear(),n=Et(e.getUTCMonth()+1),r=Et(e.getUTCDate()),o=Et(e.getUTCHours()),i=Et(e.getUTCMinutes()),d=Et(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${i}-${d}`},bd=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",Rd=async(e,{width:t,height:n})=>{let r="",o=new Id({write(d,l,u){let m=Sd(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let i=Ed(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),i.unmount(),r},Sd=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),hi=async()=>{let{currentNode:e,selectedIndex:t,breadCrumb:n,viewMode:r,mode:o,renderedChildrenIndex:i}=v(),d=n.find(w=>w.context==="BOARD");if(!d)return s("No board found to export");let l=120,u=40,m=await Rd(Nd.createElement(yi,{height:u,width:l,swimlanes:(i[d.id]??[]).filter(w=>w!==void 0&&Yt(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=le(process.cwd());if(a(p))return s("Unable to export, epiq root not found");let x=new Date,N=Cd(x),I=`board_${bd(d.title)}_${N}.md`,R=Rr(p.value);xi.mkdirSync(R,{recursive:!0});let b=hd.join(R,I),E=`# Board - ${d.title}
|
|
46
46
|
Date: ${x.toISOString()}
|
|
47
47
|
|
|
48
48
|
\`\`\`text
|
|
49
49
|
${m}
|
|
50
50
|
\`\`\`
|
|
51
|
-
`;return
|
|
52
|
-
`).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
|
|
51
|
+
`;return xi.writeFileSync(b,E,"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}},Ni=(e,t)=>Math.max(0,Math.min(e,Math.max(0,t-1))),Ii=e=>{let{nodes:t}=v(),n=t[e.currentNodeId];if(n&&!n.isDeleted&&e.selectedNodeId){let i=S(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=S(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=S(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=S(o.id);return D.navigate({currentNode:o,selectedIndex:Ni(e.selectedIndex,i.length)}),c("Restored navigation to parent",null)}}let r=t[v().rootNodeId];return!r||r.isDeleted?s("Unable to restore navigation"):(D.navigate({currentNode:r,selectedIndex:0}),c("Restored navigation to root",null))};import{ulid as Ad}from"ulid";var Ci=null,Le=()=>structuredClone(Ci),It=e=>Ci=e,bi=()=>{let{currentNode:e,selectedIndex:t}=v(),r=S(e.id)[t];return r?c("Resolved selected child",r):s("Target node not found")};var Ri=({id:e,parentId:t,position:n={at:"end"}})=>{let r=G();if(a(r))return s("Unable to resolve user ID");let o=he(t,e,n,r.value);return a(o)?o:c("Created pending move state",{id:Ad(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value}})},Si=e=>{It(e);let t=pt(e,!0);return a(t)?t:c("Node moved successfully",t.value)};function ur(e){let t=bi();if(a(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=U(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=Ri({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Si(u.value)}function mr(e){let t=bi();if(a(t))return t;let{currentNode:n,selectedIndex:r}=v(),i=U(n.id)[r+e];if(!i)return s("Missing sibling node");let d=Ri({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:i.id}});return a(d)?d:Si(d.value)}var Ai=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 Mi}from"ulid";import{spawnSync as wd}from"node:child_process";import Td from"node:os";import wi from"node:path";import{ulid as Md}from"ulid";function Pd(){let{preferredEditor:e}=me(),t=[e,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function kd(e,t){return/(^|\/)code(-insiders)?$/.test(e.trim())?`${e} --wait "${t}"`:`${e} "${t}"`}function Ti(e){let t=wi.join(Td.tmpdir(),"epiq");re.mkDir(t);let n=wi.join(t,Md());re.writeToFile(n,e??"");let r=Pd();for(let o of r){let i=kd(o,n),d=wd(i,{stdio:"inherit",shell:!0});if(!d.error&&d.status===0){let l=re.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 Pi=()=>{let e=G();if(a(e))return s("Unable to resolve user ID");let{breadCrumb:t,selectedNode:n}=v(),r=Pe([...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=S(o.id).find(m=>m.title===q.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=Ti(d);if(a(l))return s("Failed to edit field");let u=l.value;return u===d?c("No changes made",null):i.title===q.DESCRIPTION?H({id:Mi(),action:"edit.description",payload:{id:i.id,md:u},...e.value}):i.title==="Title"?H({id:Mi(),action:"edit.title",payload:{id:i.id,name:u},...e.value}):s(`Editing not supported for "${i.title}"`)};import Ld from"node:fs";import Fi from"node:path";import pr from"node:fs";import Fd from"node:path";var ki=async e=>{let t=Fd.join(e,".gitignore"),n=pr.existsSync(t)?pr.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
52
|
+
`).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
53
|
`);return n=n.trimEnd()+`
|
|
54
54
|
|
|
55
|
-
${
|
|
56
|
-
`,
|
|
57
|
-
`));let{rootNodeId:i,nodes:a}=v();return D.navigate({currentNode:a[i],selectedIndex:0}),I({hasProject:!0,mode:f.DEFAULT}),l("Project initialized",null)}},{intent:A.SetEditor,mode:f.COMMAND_LINE,action:()=>{let e=Gt()?.trim();if(!e)return s("No editor provided");let t=Dt({preferredEditor:e});return d(t)?t:(wt({preferredEditor:e}),I({mode:f.DEFAULT}),l(`Editor configuration set to "${e}"`,null))}},{intent:A.SetAutoSync,mode:f.COMMAND_LINE,action:()=>{let e=re().commandMeta.modifier;if(e!=="true"&&e!=="false")return s("Invalid response");let t=e.toLowerCase()==="true",n=Dt({autoSync:t});return d(n)?n:(wt({autoSync:t}),I({mode:f.DEFAULT}),l(`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=c=>{let u=j(c);if(d(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:c}=v(),u=N.getNode(c);if(!u)return s("Workspace not found");let m=Re(u.id,n.value);return d(m)?m:a({id:B(),action:"add.board",payload:{id:B(),name:t.inputString,parent:u.id,rank:m.value},...n.value})}if(t.modifier==="swimlane"){let c=De(r,"BOARD");if(d(c))return s("Unable to add swimlane in this context");let u=Re(c.value.id,n.value);return d(u)?u:a({id:B(),action:"add.swimlane",payload:{id:B(),name:t.inputString,parent:c.value.id,rank:u.value},...n.value})}if(t.modifier==="issue"){let c=S(o.id)[i],u=o.context==="SWIMLANE"?o:o.context==="BOARD"&&c?.context==="SWIMLANE"?c:(()=>{let h=De(r,"SWIMLANE");return d(h)?null:h.value})();if(!u)return s("Unable to add issue in this context");let m=Re(u.id,n.value);if(d(m))return m;let p=Bt({name:t.inputString,parent:u.id,rank:m.value,user:n.value});if(d(p))return p;let x=p.value,E=Fe(x);if(E.some(h=>d(h)))return s("Issue create failed: "+E.filter(d).map(h=>h.message).filter(Boolean).join(", "));let C=E[0];if(!C||d(C))return s("Issue creation failed");let b=x.find(h=>h.action==="add.issue")?.payload.id;return b?(D.navigate({currentNode:u,selectedIndex:N.getSiblings(u.id).findIndex(({id:h})=>h===b)}),l("Issue created",null)):s("Unable to determine ticket id")}return l("Success",null)},onSuccess:()=>I({mode:f.DEFAULT})},{intent:A.SetView,mode:f.COMMAND_LINE,action:()=>{let{commandMeta:e}=re();return e.validity===xe.Invalid?s("Invalid command "+me):(ne(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),l("View set",null))},onSuccess:()=>I({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=Gt();return o?j({id:B(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>I({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}=re().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=Ei(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid untag target");let a=Ve(i.id,"TICKET");if(d(a))return s("Unable to untag issue in this context");let c=a.value,u=N.getFieldByTitle(c.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?j({id:B(),action:"untag.issue",payload:{id:m.id,target:c.id,tagId:o.id},...e.value}):s("Issue is not tagged with that tag")},onSuccess:()=>I({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}=re().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 c=Ve(a.id,"TICKET");if(d(c))return s("Unable to tag issue in this context");let u=c.value,m=Ei(r),p;if(m)p=m.id;else{let R=B(),b=j({id:B(),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=N.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 C=Re(x.id,e.value);return d(C)?C:j({id:B(),action:"tag.issue",payload:{id:B(),target:u.id,tagId:p,rank:C.value},...e.value})},onSuccess:()=>I({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}=re().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 c=Ve(a.id,"TICKET");if(d(c))return s("Unable to assign issue in this context");let u=c.value,m=hi(r),p;if(m)p=m.id;else{let R=B(),b=j({id:B(),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=N.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 C=Re(x.id,e.value);return d(C)?C:j({id:B(),action:"assign.issue",payload:{id:B(),target:u.id,contributor:p,rank:C.value},...e.value})},onSuccess:()=>I({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}=re().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=hi(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid unassign target");let a=Ve(i.id,"TICKET");if(d(a))return s("Unable to unassign in this context");let c=a.value,u=N.getFieldByTitle(c.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?j({id:B(),action:"unassign.issue",payload:{id:m.id,target:c.id,contributor:o.id},...e.value}):s(`Issue is not assigned to "${r}"`)},onSuccess:()=>I({mode:f.DEFAULT})},{intent:A.Sync,mode:f.COMMAND_LINE,action:async()=>{let e=ui();W(()=>""),I({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:n}=fe();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=it(r.value),i=await Ft({ownEventFileName:o});if(d(i))return I({syncStatus:{msg:i.message,status:"outOfSync"}}),s(`Unable to sync state. ${i.message}`);let a=_e(process.cwd());if(d(a))return a;let c=st(a.value);if(d(c))return s(`Unable to load events. ${c.message}`);let u=rn(c.value);if(d(u))return s(`Unable to boot synced state. ${u.message}`);I({hasProject:!0,syncStatus:{msg:"Synced",status:"synced"},mode:f.DEFAULT});let m=mi(e);return d(m)?m:l("Synced",!0)}},{intent:A.Peek,mode:f.COMMAND_LINE,action:async()=>{let e=De(v().breadCrumb,"BOARD");if(d(e))return e;let t=de(process.cwd());if(d(t))throw new Error(t.message);let n=st(t.value);if(d(n))return s(n.message);let r=n.value,{modifier:o}=re().commandMeta,i;if(o==="now"){let E=er();if(d(E))return E;let C=ct(r);return C.some(d)?s(C.map(R=>R.message).join(", ")):(I({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),l("Peeking now",!0))}if(o==="prev"){let E=v().eventLog.at(-2),C=On(E);if(C===null)return s("No previous event to peek");i=C}else if(o==="next"){let E=v().unappliedEvents.at(0),C=On(E);if(C===null)return s("No next event to peek");i=C}else{let E=Vt(o);if(!E)return s("Invalid peek date");i=E.getTime()}let a=e.value.id,{appliedEvents:c,unappliedEvents:u}=zr(r,i),m=er();if(d(m))return m;let p=ct(c);if(p.some(d))return s(p.map(E=>E.message).join(", "));let x=v().nodes[a];return x?(D.navigate({currentNode:x,selectedIndex:0}),I({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),l("Peeking ",!0)):s("Board did not exist at peek date")}},{intent:A.Export,mode:f.COMMAND_LINE,action:async()=>{let e=await di();return d(e)?e:(I({mode:f.DEFAULT}),l("Export successful",!0))}},{intent:A.Exit,mode:f.COMMAND_LINE,action:async()=>(D.exit(),l("Exit successful",!0))}];var Nd=new Set(["peek","filter","view-help"]),ae=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=re();if(!t)return s("No command to confirm");if(!e&&n===xe.Invalid)return s("Invalid command");let i=qo(t);if(jo(),v().readOnly&&!Nd.has(i))return ft({status:me.Fail,message:"Command not available in readonly state",value:null});let a=Ii.filter(u=>e||u.systemOnly!==!0).find(u=>u.intent===i);if(!a)return ft({status:me.Fail,message:"Command not found",value:null});let c=await a.action(a,{command:t,inputString:o,modifier:r});return d(c)?ft(c):(Ho({addToHistory:!e}),a.onSuccess?.(),ft(c))};var on=[{intent:T.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(I({mode:f.COMMAND_LINE}),W(()=>"move cancel"),ae({isForceExecutedBySystem:!0}))},{intent:T.InitMove,mode:f.DEFAULT,description:"[m] move init/confirm",action:()=>(I({mode:f.COMMAND_LINE}),W(()=>"move start"),ae({isForceExecutedBySystem:!0}))},{intent:T.ConfirmMove,mode:f.MOVE,action:()=>(I({mode:f.COMMAND_LINE}),W(()=>"move confirm"),ae({isForceExecutedBySystem:!0}))}],sn=[{intent:T.MovePreviousItem,mode:f.MOVE,action:()=>Te()?(I({mode:f.COMMAND_LINE}),W(()=>"move previous"),ae({isForceExecutedBySystem:!0})):s("No pending move")},{intent:T.MoveNextItem,mode:f.MOVE,action:()=>Te()?(I({mode:f.COMMAND_LINE}),W(()=>"move next"),ae({isForceExecutedBySystem:!0})):s("No pending move")}],bi=[{intent:T.MoveToNextContainer,mode:f.MOVE,action:()=>Te()?(I({mode:f.COMMAND_LINE}),W(()=>"move to-next"),ae({isForceExecutedBySystem:!0})):s("No pending move")},{intent:T.MoveToPreviousContainer,mode:f.MOVE,action:()=>Te()?(I({mode:f.COMMAND_LINE}),W(()=>"move to-previous"),ae({isForceExecutedBySystem:!0})):s("No pending move")}];var Si={[k.WORKSPACE]:[...on,...sn],[k.BOARD]:[...on,...sn],[k.SWIMLANE]:[...on,...sn,...bi],[k.TICKET]:[],[k.FIELD]:[],[k.FIELD_LIST]:[],[k.TEXT]:[]};var Ri=[{intent:T.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(I({mode:f.COMMAND_LINE}),W(()=>`${g.NEW} `),l("Adding new item",null))},{intent:T.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(I({mode:f.COMMAND_LINE}),W(()=>`${g.DELETE} `),l("Deleting item",null))},{intent:T.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(I({mode:f.COMMAND_LINE}),W(()=>""),l("Entering command line mode",null))},{intent:T.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>(D.enterChildNode(),l("Entering context",null))},{intent:T.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(D.enterParentNode(),l("Exiting context",null))},{intent:T.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(D.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:T.NavNextItem,mode:f.DEFAULT,action:()=>(D.navigateToNextItem(),l("Navigating to next item",null))},{intent:T.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(D.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:T.NavToNextContainer,mode:f.DEFAULT,action:()=>(D.navigateToNextContainer(),l("Navigating to next container",null))},{intent:T.Edit,mode:f.DEFAULT,action:()=>(I({mode:f.COMMAND_LINE}),W(()=>"edit"),ae(),l("Fired command",!0))},{intent:T.SetViewDense,mode:f.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(I({viewMode:"dense"}),l("View set",null))},{intent:T.SetViewWide,mode:f.DEFAULT,action:()=>(I({viewMode:"wide"}),l("View set",null))}];var Ed=500,hd=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Ai=e=>{let t=hd(e);t&&W(n=>(n+t).slice(0,Ed))};var wi=[{intent:T.ViewHelp,mode:f.DEFAULT,action:()=>(I({mode:f.HELP}),l("Viewing help",null))},{intent:T.Exit,mode:f.HELP,action:()=>(I({mode:f.DEFAULT}),l("Exiting help",null))},{intent:T.Confirm,mode:f.COMMAND_LINE,action:()=>(ae(),l("Executing command",null))},{intent:T.MoveCursorLeft,mode:f.COMMAND_LINE,action:()=>(jn(-1),l("Moving cursor left",null))},{intent:T.MoveCursorRight,mode:f.COMMAND_LINE,action:()=>(jn(1),l("Moving cursor right",null))},{intent:T.MoveCursorLeftOfWord,mode:f.COMMAND_LINE,action:()=>(Hn("left"),l("Moving cursor left of word",null))},{intent:T.MoveCursorRightOfWord,mode:f.COMMAND_LINE,action:()=>(Hn("right"),l("Moving cursor right of word",null))},{intent:T.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(I({mode:f.DEFAULT}),l("Exiting command line",null))},{intent:T.AutoCompleteCommand,mode:f.COMMAND_LINE,action:()=>(W((e,{remainder:t})=>t?e+t:e),l("Auto-completing command",null))},{intent:T.CaptureInput,mode:f.COMMAND_LINE,action:(e,{sequence:t})=>(Ai(t??""),l("Capturing input",null))},{intent:T.EraseInput,mode:f.COMMAND_LINE,action:()=>($o(),l("Erasing input",null))},{intent:T.EraseInputWord,mode:f.COMMAND_LINE,action:()=>(Wo(),l("Erasing input word",null))},{intent:T.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Ko(),l("Getting last command from history",null))},{intent:T.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Vo(),l("Getting next command from history",null))}];import Id from"chalk";var an=": for command line",Ti="q to exit",Mi=`${Id.hex(M.accent)("m")} to confirm`,tr={[k.WORKSPACE]:[an],[k.BOARD]:[an],[k.BOARD+f.COMMAND_LINE]:[an],[k.SWIMLANE]:[an],[k.TICKET+f.HELP]:[Ti],[k.SWIMLANE+f.HELP]:[Ti],[k.TICKET]:[],[k.FIELD]:[],[k.SWIMLANE+f.MOVE]:[Mi],[k.TICKET+f.MOVE]:[Mi]};var dn=e=>e.trim().toLocaleLowerCase(),Cd=(e,t)=>{let n=N.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},bd=e=>{let{tags:t}=v(),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):[]},Sd=e=>{let{contributors:t}=v(),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):[]},ki=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return dn(e.title??"").includes(n);case"description":return dn(Cd(e.id,"Description")).includes(n);case"tag":return bd(e.id).map(dn).some(c=>c.includes(n));case"assignee":return Sd(e.id).map(dn).some(c=>c.includes(n));default:return!0}};function Pi(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(),l("Breadcrumb built",o))}var Fi=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 ln,nr,rr=new Set,Li=()=>{for(let e of rr)e()},Ad=e=>(rr.add(e),()=>rr.delete(e));function Di(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 c=o[t];if(!c)return s("Unable to derive state, currentNode not found");let u=Pi(t,o,r);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,x=tr[p+n]??tr[p]??[],E=[...Ri,...Si[p]??[],...wi],C=Fi(E),R=wd(o,i),b=R[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,currentNode:c,breadCrumb:m,availableHints:x,availableActions:E,actionIndex:C,selectedNode:b,renderedChildrenIndex:R})}var v=()=>(ln||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),ln);function ut(e){nr=e;let t=_e(process.cwd()),n=!1;if(!d(t)){let i=$e(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=Di(r);return d(o)?o:(ln=o.value,Li(),l("State initialized",null))}function ne(e){let t=v(),n=e(t),r=Di(n);return d(r)?s(r.message??"Unable to update state"):(ln=r.value,Li(),l("State updated",null))}var I=e=>ne(t=>({...t,...e}));var ce=()=>Rd(Ad,v,v),wd=(e,t)=>{let n={};for(let r of Object.values(e))Q(r)&&t.length>0&&!t.every(o=>ki(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],c=e[i.id];return!a||!c?0:a.rank.localeCompare(c.rank)});return n},S=e=>v()?.renderedChildrenIndex[e]??[],er=()=>nr?ut(nr):s("Cannot reset state: no initial workspace found");var D={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"||D.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;D.navigate({currentNode:n,selectedIndex:i})},navigateToNextItem:()=>Oi(1),navigateToPreviousItem:()=>Oi(-1),navigateToNextContainer:()=>Ui(1),navigateToPreviousContainer:()=>Ui(-1),navigate:({currentNode:e=v().currentNode,selectedIndex:t})=>{I({currentNodeId:e.id,selectedIndex:t})}},Oi=e=>{let t=v(),n=S(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;D.navigate({selectedIndex:o})},Ui=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 c=i.at(a+e)??i.at(0);if(!c)return;let u=S(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),x=u.length?p:-1;D.navigate({currentNode:c,selectedIndex:x})};var be="system",Se="ACTOR",Nt=Td();function Md(){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=Md();D.navigate(e)}function Ci(){let e=Nt(),t=Nt(),n=Nt(),r=Nt(),o=Nt(),i=V(void 0,void 0);if(d(i))return i;let a=V(void 0,void 0);if(d(a))return a;let c=V(a.value,void 0);if(d(c))return c;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(m.value,void 0);if(d(p))return p;let x=V(void 0,void 0);return d(x)?x:l("Created default events",[{id:Ce(),userId:be,userName:Se,action:"init.workspace",payload:{id:e,name:"Workspace",rank:i.value}},{id:Ce(),userId:be,userName:Se,action:"add.board",payload:{id:t,name:"Default",parent:e,rank:a.value}},{id:Ce(),userId:be,userName:Se,action:"add.swimlane",payload:{id:n,name:"Todo",parent:t,rank:u.value}},{id:Ce(),userId:be,userName:Se,action:"add.swimlane",payload:{id:r,name:"In progress",parent:t,rank:m.value}},{id:Ce(),userId:be,userName:Se,action:"add.swimlane",payload:{id:o,name:"Done",parent:t,rank:p.value}},{id:Ce(),userId:be,userName:Se,action:"add.board",payload:{id:jt,name:"Closed",parent:e,rank:c.value}},{id:Ce(),userId:be,userName:Se,action:"add.swimlane",payload:{id:Y,name:"Closed",parent:jt,rank:x.value}},{id:Ce(),userId:be,userName:Se,action:"lock.node",payload:{id:jt}},{id:Ce(),userId:be,userName:Se,action:"lock.node",payload:{id:Y}}])}function rn(e){if(!e.some(r=>r.action==="init.workspace")){let r=z.workspace("temporary-uninitialized-workspace","Workspace","a0"),o=ut(r);return d(o)?o:(I({hasProject:!1,mode:f.DEFAULT}),l("Booted uninitialized workspace placeholder",null))}let n=ct(e).filter(d);return n.length>0?s([or.bold.red("Materializing failed"),"",...n.map((r,o)=>`${or.dim.gray(`${o+1}.`)} ${or.dim(r.message)}`),`
|
|
58
|
-
`].
|
|
59
|
-
|
|
60
|
-
See complete log:
|
|
61
|
-
|
|
62
|
-
`)+e.map(r=>JSON.stringify(r)).join(`
|
|
63
|
-
`)):(kd(),l("State booted successfully",null))}var Be=e=>{let t=de(e??process.cwd());if(d(t))return t;let n=st(t.value);if(d(n))return s(n.message);let r=rn(n.value);return d(r)?s(r.message):l("Booted Epiq state",{root:t.value})},cn=()=>{let e=io();return d(e)?s(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):s("Unable to retrieve user name"):s("Unable to retrieve user id")},_i=(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):[]},Pd=e=>_i(e,"Tags").map(t=>N.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),Fd=e=>_i(e,"Assignees").map(t=>N.getContributor(t)).filter(Boolean).map(t=>({id:t.id,name:t.name})),$i=(e={})=>{let t=Be(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 l("Listed boards",n)},Wi=(e={})=>{let t=Be(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===Y,readonly:!!r.readonly}));return l("Listed swimlanes",n)},ji=e=>{let t=Be(e.repoRoot);if(d(t))return t;let n=Object.values(v().nodes).filter(Q).filter(r=>e.includeClosed||r.parentNodeId!==Y).map(r=>({id:r.id,title:Ke(r.title),description:bo(r,"Description"),parentId:r.parentNodeId,isClosed:r.parentNodeId===Y,readonly:!!r.readonly,tags:Pd(r),assignees:Fd(r)}));return l("Listed issues",n)},Hi=e=>{let t=Be(e.repoRoot);if(d(t))return t;let n=cn();if(d(n))return n;let r=Re(e.parentId,n.value);if(d(r))return r;let o=Bt({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(d(o))return o;let i=o.value,c=Fe(i).find(d);if(c)return s(c.message);let u=i.find(m=>m.action==="add.issue")?.payload.id;return u?l("Created issue",{id:u,title:e.title,parentId:e.parentId}):s("Unable to determine created issue id")},Ki=e=>{let t=Be(e.repoRoot);if(d(t))return t;let n=cn();if(d(n))return n;let r=ye(Y,e.issueId,{at:"end"},n.value);if(d(r))return r;let o={id:Bi(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:Y,rank:r.value}},a=Fe([o]).find(d);return a?s(a.message):l("Closed issue",{id:e.issueId})},Vi=e=>{let t=Be(e.repoRoot);if(d(t))return t;let n=cn();if(d(n))return n;let r=ye(e.parentId,e.issueId,e.position??{at:"end"},n.value);if(d(r))return r;let o={id:Bi(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:r.value}},a=Fe([o]).find(d);return a?s(a.message):l("Moved issue",{id:e.issueId,parentId:e.parentId})},qi=async(e={})=>{let t=de(e.repoRoot??process.cwd());if(d(t))return s("Sync failed");let n=cn();if(d(n))return n;let r=await Ft({cwd:t.value,ownEventFileName:it(n.value)});return d(r)?r:l("Synced",r.value)},zi=(e={})=>{let t=Be(e.repoRoot);return d(t)?t:l("Retrieved Epiq state",{root:t.value.root,nodes:v().nodes,rootNodeId:v().rootNodeId,currentNode:v().currentNode,selectedIndex:v().selectedIndex,eventLog:v().eventLog})};var Me=e=>({isError:d(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Od=()=>{let e=new Ld({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=>Me(await zi(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:F.object({repoRoot:F.string().optional(),includeClosed:F.boolean().optional()})},async t=>Me(await ji(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>Me(await $i(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:F.object({repoRoot:F.string().optional(),boardId:F.string().optional()})},async t=>Me(await Wi(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=>Me(await Hi(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=>Me(await Ki(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=>Me(await Vi(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>Me(await qi(t))),e},Ud=async()=>{let e=Od(),t=new Dd;await e.connect(t)};await Ud();export{Od as createMcpServer,Me as resultJson,Ud as startMcpServer};
|
|
55
|
+
${l}
|
|
56
|
+
`,pr.writeFileSync(t,n,"utf8"),Q.info(`Added ${i.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)};var Dd=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)},_=(e,t)=>s(`[${e}] ${t}`),Li=async()=>{let e=Ar(),t=await Ft(process.cwd());if(a(t))return _(1,t.message);let n=t.value,r=await it(n);if(a(r))return _(2,r.message);if(r.value)return _(2,"Cannot initialize Epiq while a git operation is in progress");let o=await Dd(n);if(a(o))return _(2.5,o.message);if(o.value)return _(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(An(n))return _(4,"Epiq project already initialized");let i=en();if(!i.isSetup||!i.userName)return _(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let d=me(),l=d.userName,u=d.userId;if(!u||!l)return _(5,"Missing Epiq user id");let m=e.stateBranch,p=await Tt({repoRoot:n,branch:m});if(a(p))return _(6,p.message);let x=await Lt({repoRoot:n,stateBranchName:e.stateBranch});if(a(x))return _(6,x.message);let N=kt();if(a(N))return _(7,N.message);let I=Fi.join(Pt(),e.projectId),R=await Dn({repoRoot:n,stateBranchRoot:I,stateBranchName:e.stateBranch});if(a(R))return _(8,R.message);let b=Fi.join(I,".epiq");Ld.mkdirSync(b,{recursive:!0});let E=Di({userId:u,userName:l});if(a(E))return _(9,E.message);for(let Rn of E.value){let br=_t({event:Rn,rootDir:I});if(a(br))return _(9,br.message)}let w=await Dt({stateBranchRoot:I,eventFileName:Ue({userId:u,userName:l})});if(a(w))return _(10,w.message);let W=await qe({cwd:I,message:"[epiq:init]"});if(a(W))return _(10,W.message);let Se=await ki(n);if(a(Se))return _(12,Se.message);let ne=Tr({repoRoot:n,fileContents:e});if(a(ne))return _(13,ne.message);let xr=await j.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(xr))return _(14,xr.message);let hr=await j.commit({cwd:n,message:"[epiq:init-project]"});if(a(hr))return _(14,hr.message);let Nr=Ht({repoRoot:n,stateBranchRoot:I});if(a(Nr))return _(15,Nr.message);let bn="Project initialized!",Er=await ct({repoRoot:n,stateBranchRoot:I});a(Er)&&(bn+=` Warn: [init:16] ${Er.message}`);let Ir=await j.push({cwd:n});a(Ir)&&(bn+=` Warn: [init:17] ${Ir.message}`);let Cr=Te(E.value).filter(a);if(Cr.length>0)return _(18,Cr.map(Rn=>Rn.message).join(`
|
|
57
|
+
`));let{rootNodeId:cs,nodes:ls}=v();return D.navigate({currentNode:ls[cs],selectedIndex:0}),C({hasProject:!0,mode:g.DEFAULT}),c(bn,null)};var Oi=e=>Object.values(v().tags).find(t=>t.name===e),Ui=e=>Object.values(v().contributors).find(t=>t.name===e),Bi=[{systemOnly:!0,intent:A.Move,mode:g.COMMAND_LINE,action:()=>{let e=G();if(a(e))return s("Unable to resolve user ID");let{modifier:t}=ie().commandMeta,n=()=>{let l=Le();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 N=S(p).findIndex(I=>I.id===u);return N===-1?s("Moved node not found among rendered children"):(D.navigate({currentNode:x,selectedIndex:N}),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}=v(),d=S(o.id)[i];if(!d)return C({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=U(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"},N=he(d.parentNodeId,d.id,x,e.value);if(a(N))return N;It({id:K(),action:"move.node",payload:{id:d.id,parent:d.parentNodeId,rank:N.value},...e.value}),C({mode:g.MOVE});let I=n();return a(I)?s(I.message):c("Move initialized",null)}if(t==="next")return C({mode:g.MOVE}),r(mr(1));if(t==="previous")return C({mode:g.MOVE}),r(mr(-1));if(t==="to-next")return C({mode:g.MOVE}),r(ur(1));if(t==="to-previous")return C({mode:g.MOVE}),r(ur(-1));if(t==="confirm"){C({mode:g.DEFAULT});let l=Le();if(!l)return s("No pending move to confirm");let u=H(l);if(a(u))return u;let m=n();return a(m)?s(m.message):(It(null),c("Moved item",null))}return t==="cancel"?(It(null),C({mode:g.DEFAULT}),c("Cancelling move",null)):s("Invalid move modifier")}},{intent:A.Delete,mode:g.COMMAND_LINE,action:()=>{let e=G();if(a(e))return s("Unable to resolve user ID");let{currentNode:t,selectedIndex:n}=v(),r=S(t.id)[n];return r?H({id:K(),action:"delete.node",payload:{id:r.id},...e.value}):s("Unable to resolve child to delete")},onSuccess:()=>C({mode:g.DEFAULT})},{intent:A.Edit,mode:g.COMMAND_LINE,action:Pi,onSuccess:()=>C({mode:g.DEFAULT})},{intent:A.Filter,mode:g.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ie().commandMeta,n=/(!=|=)/,[r,o]=e.split(n);if(!r||!(l=>z(f.FILTER).map(u=>u.split(n)[0]).includes(l))(r))return s("Invalid filter modifier");let d={target:r,operator:"=",value:t.trim()};return oe(l=>({...l,filters:e==="clear"?[]:[...l.filters,d],mode:g.DEFAULT})),c("Viewing help",null)}},{intent:A.ViewHelp,mode:g.COMMAND_LINE,action:()=>(C({mode:g.HELP}),c("Viewing help",null))},{intent:A.CloseIssue,mode:g.COMMAND_LINE,action:()=>{let e=G();if(a(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(!ee(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=he(o.id,r.id,{at:"end"},e.value);if(a(i))return i;let d=H({id:K(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:i.value},...e.value});return a(d)?d:c("Issue closed",null)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:A.ReopenIssue,mode:g.COMMAND_LINE,action:()=>{let e=G();if(a(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):Ye(r.id,"TICKET");if(a(o))return s("Cannot reopen in this context");let i=o.value,d=v().nodes[J];if(!d)return s("Unable to locate closed swimlane");if(i.parentNodeId!==d.id)return s("Issue is not closed");if(!ee(i))return s("Target node is not issue");let l=Ai(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=v().nodes[l];if(!u)return s("Previous parent no longer exists");let m=he(u.id,i.id,{at:"end"},e.value);if(a(m))return m;let p=H({id:K(),action:"reopen.issue",payload:{id:i.id,parent:u.id,rank:m.value},...e.value});return a(p)?p:c("Issue reopened",null)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:A.SetUserName,mode:g.COMMAND_LINE,action:()=>{let{userId:e,preferredEditor:t,userName:n}=me(),r=dn()?.trim();if(!r)return s("No username provided");let o=r??n,i=e??K();if(!o||!i)return s("Unable to resolve user name or id");let d=qt({userName:o,userId:i,preferredEditor:t??""});return a(d)?d:(Ut({userName:o,userId:i}),C({mode:g.DEFAULT}),c(`Username set to "${r}"`,null))}},{intent:A.Init,mode:g.COMMAND_LINE,action:Li},{intent:A.SetEditor,mode:g.COMMAND_LINE,action:()=>{let e=dn()?.trim();if(!e)return s("No editor provided");let t=qt({preferredEditor:e});return a(t)?t:(Ut({preferredEditor:e}),C({mode:g.DEFAULT}),c(`Editor configuration set to "${e}"`,null))}},{intent:A.SetAutoSync,mode:g.COMMAND_LINE,action:()=>{let e=ie().commandMeta.modifier;if(e!=="true"&&e!=="false")return s("Invalid response");let t=e.toLowerCase()==="true",n=qt({autoSync:t});return a(n)?n:(Ut({autoSync:t}),C({mode:g.DEFAULT}),c(`Auto synchronization set to "${t}"`,null))}},{intent:A.NewItem,mode:g.COMMAND_LINE,action:(e,t)=>{let n=G();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}=v(),d=l=>{let u=H(l);if(a(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?(D.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 a(m)?m:d({id:K(),action:"add.board",payload:{id:K(),name:t.inputString,parent:u.id,rank:m.value},...n.value})}if(t.modifier==="swimlane"){let l=Pe(r,"BOARD");if(a(l))return s("Unable to add swimlane in this context");let u=Me(l.value.id,n.value);return a(u)?u:d({id:K(),action:"add.swimlane",payload:{id:K(),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 E=Pe(r,"SWIMLANE");return a(E)?null:E.value})();if(!u)return s("Unable to add issue in this context");let m=Me(u.id,n.value);if(a(m))return m;let p=Xt({name:t.inputString,parent:u.id,rank:m.value,user:n.value});if(a(p))return p;let x=p.value,N=Te(x);if(N.some(E=>a(E)))return s("Issue create failed: "+N.filter(a).map(E=>E.message).filter(Boolean).join(", "));let I=N[0];if(!I||a(I))return s("Issue creation failed");let b=x.find(E=>E.action==="add.issue")?.payload.id;return b?(D.navigate({currentNode:u,selectedIndex:h.getSiblings(u.id).findIndex(({id:E})=>E===b)}),c("Issue created",null)):s("Unable to determine ticket id")}return c("Success",null)},onSuccess:()=>C({mode:g.DEFAULT})},{intent:A.SetView,mode:g.COMMAND_LINE,action:()=>{let{commandMeta:e}=ie();return e.validity===Ne.Invalid?s("Invalid command "+fe):(oe(t=>({...t,viewMode:e.modifier==="wide"?"wide":e.modifier==="dense"?"dense":t.viewMode})),c("View set",null))},onSuccess:()=>C({mode:g.DEFAULT})},{intent:A.Rename,mode:g.COMMAND_LINE,action:()=>{let e=G();if(a(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=dn();return o?H({id:K(),action:"edit.title",payload:{id:r.id,name:o},...e.value}):s("Provide a new name")},onSuccess:()=>C({mode:g.DEFAULT})},{intent:A.UntagTicket,mode:g.COMMAND_LINE,action:()=>{let e=G();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ie().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let o=Oi(r);if(!o)return s(`Tag "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid untag target");let d=Ye(i.id,"TICKET");if(a(d))return s("Unable to untag issue in this context");let l=d.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?H({id:K(),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:g.DEFAULT})},{intent:A.TagTicket,mode:g.COMMAND_LINE,action:()=>{let e=G();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ie().commandMeta,r=(t||n).trim();if(!r)return s("Provide a tag");let{selectedIndex:o,currentNode:i}=v(),d=S(i.id)[o];if(!d)return s("Invalid tag target");let l=Ye(d.id,"TICKET");if(a(l))return s("Unable to tag issue in this context");let u=l.value,m=Oi(r),p;if(m)p=m.id;else{let R=K(),b=H({id:K(),action:"create.tag",payload:{id:R,name:r},userId:e.value.userId,userName:e.value.userName});if(a(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 a(I)?I:H({id:K(),action:"tag.issue",payload:{id:K(),target:u.id,tagId:p,rank:I.value},...e.value})},onSuccess:()=>C({mode:g.DEFAULT})},{intent:A.AssignUserToTicket,mode:g.COMMAND_LINE,action:()=>{let e=G();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ie().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee");let{selectedIndex:o,currentNode:i}=v(),d=S(i.id)[o];if(!d)return s("Invalid assign target");let l=Ye(d.id,"TICKET");if(a(l))return s("Unable to assign issue in this context");let u=l.value,m=Ui(r),p;if(m)p=m.id;else{let R=K(),b=H({id:K(),action:"create.contributor",payload:{id:R,name:r},userId:e.value.userId,userName:e.value.userName});if(a(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 a(I)?I:H({id:K(),action:"assign.issue",payload:{id:K(),target:u.id,contributor:p,rank:I.value},...e.value})},onSuccess:()=>C({mode:g.DEFAULT})},{intent:A.UnassignUserFromTicket,mode:g.COMMAND_LINE,action:()=>{let e=G();if(a(e))return s("Unable to resolve user ID");let{modifier:t,inputString:n}=ie().commandMeta,r=(t||n).trim();if(!r)return s("Provide an assignee to remove");let o=Ui(r);if(!o)return s(`Assignee "${r}" does not exist`);let{selectedNode:i}=v();if(!i)return s("Invalid unassign target");let d=Ye(i.id,"TICKET");if(a(d))return s("Unable to unassign in this context");let l=d.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?H({id:K(),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:g.DEFAULT})},{intent:A.Sync,mode:g.COMMAND_LINE,action:async()=>{let e=Ei();O(()=>""),C({syncStatus:{msg:"Syncing",status:"syncing"}});let{userId:t,userName:n}=me();if(!t)return s("Unable to resolve userId");if(!n)return s("Unable to resolve userName");let r=G();if(a(r)||!r.value)return s("Unable to resolve event log path");let o=Ue(r.value),i=await Kt({ownEventFileName:o});if(a(i))return C({syncStatus:{msg:i.message,status:"outOfSync"}}),s(`Unable to sync state. ${i.message}`);let d=Ae(process.cwd());if(a(d))return d;let l=ut(d.value);if(a(l))return s(`Unable to load events. ${l.message}`);let u=yn({eventLog:l.value,hasProject:!0});if(a(u))return s(`Unable to boot synced state. ${u.message}`);C({hasProject:!0,syncStatus:{msg:"Synced",status:"synced"},mode:g.DEFAULT});let m=Ii(e);return a(m)?m:c("Synced",!0)}},{intent:A.Peek,mode:g.COMMAND_LINE,action:async()=>{let e=Pe(v().breadCrumb,"BOARD");if(a(e))return e;let t=le(process.cwd());if(a(t))throw new Error(t.message);let n=ut(t.value);if(a(n))return s(n.message);let r=n.value,{modifier:o}=ie().commandMeta,i;if(o==="now"){let N=gr();if(a(N))return N;let I=gt(r);return I.some(a)?s(I.map(R=>R.message).join(", ")):(C({mode:g.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[]}),c("Peeking now",!0))}if(o==="prev"){let N=v().eventLog.at(-2),I=Yn(N);if(I===null)return s("No previous event to peek");i=I}else if(o==="next"){let N=v().unappliedEvents.at(0),I=Yn(N);if(I===null)return s("No next event to peek");i=I}else{let N=rn(o);if(!N)return s("Invalid peek date");i=N.getTime()}let d=e.value.id,{appliedEvents:l,unappliedEvents:u}=so(r,i),m=gr();if(a(m))return m;let p=gt(l);if(p.some(a))return s(p.map(N=>N.message).join(", "));let x=v().nodes[d];return x?(D.navigate({currentNode:x,selectedIndex:0}),C({mode:g.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:u}),c("Peeking ",!0)):s("Board did not exist at peek date")}},{intent:A.Export,mode:g.COMMAND_LINE,action:async()=>{let e=await hi();return a(e)?e:(C({mode:g.DEFAULT}),c("Export successful",!0))}},{intent:A.Exit,mode:g.COMMAND_LINE,action:async()=>(D.exit(),c("Exit successful",!0))}];var Od=new Set(["peek","filter","view-help"]),ce=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=ie();if(!t)return s("No command to confirm");if(!e&&n===Ne.Invalid)return s("Invalid command");let i=ri(t);if(Qo(),v().readOnly&&!Od.has(i))return ht({status:fe.Fail,message:"Command not available in readonly state",value:null});let d=Bi.filter(u=>e||u.systemOnly!==!0).find(u=>u.intent===i);if(!d)return ht({status:fe.Fail,message:"Command not found",value:null});let l=await d.action(d,{command:t,inputString:o,modifier:r});return a(l)?ht(l):(ei({addToHistory:!e}),d.onSuccess?.(),ht(l))};var xn=[{intent:T.Exit,mode:g.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(C({mode:g.COMMAND_LINE}),O(()=>"move cancel"),ce({isForceExecutedBySystem:!0}))},{intent:T.InitMove,mode:g.DEFAULT,description:"[m] move init/confirm",action:()=>(C({mode:g.COMMAND_LINE}),O(()=>"move start"),ce({isForceExecutedBySystem:!0}))},{intent:T.ConfirmMove,mode:g.MOVE,action:()=>(C({mode:g.COMMAND_LINE}),O(()=>"move confirm"),ce({isForceExecutedBySystem:!0}))}],hn=[{intent:T.MovePreviousItem,mode:g.MOVE,action:()=>Le()?(C({mode:g.COMMAND_LINE}),O(()=>"move previous"),ce({isForceExecutedBySystem:!0})):s("No pending move")},{intent:T.MoveNextItem,mode:g.MOVE,action:()=>Le()?(C({mode:g.COMMAND_LINE}),O(()=>"move next"),ce({isForceExecutedBySystem:!0})):s("No pending move")}],_i=[{intent:T.MoveToNextContainer,mode:g.MOVE,action:()=>Le()?(C({mode:g.COMMAND_LINE}),O(()=>"move to-next"),ce({isForceExecutedBySystem:!0})):s("No pending move")},{intent:T.MoveToPreviousContainer,mode:g.MOVE,action:()=>Le()?(C({mode:g.COMMAND_LINE}),O(()=>"move to-previous"),ce({isForceExecutedBySystem:!0})):s("No pending move")}];var ji={[P.WORKSPACE]:[...xn,...hn],[P.BOARD]:[...xn,...hn],[P.SWIMLANE]:[...xn,...hn,..._i],[P.TICKET]:[],[P.FIELD]:[],[P.FIELD_LIST]:[],[P.TEXT]:[]};var $i=[{intent:T.AddItem,mode:g.DEFAULT,description:"[n] new...",action:()=>(C({mode:g.COMMAND_LINE}),O(()=>`${f.NEW} `),c("Adding new item",null))},{intent:T.Delete,mode:g.DEFAULT,description:"[d] delete",action:()=>(C({mode:g.COMMAND_LINE}),O(()=>`${f.DELETE} `),c("Deleting item",null))},{intent:T.InitCommandLine,mode:g.DEFAULT,description:"[:] focus command line",action:()=>(C({mode:g.COMMAND_LINE}),O(()=>""),c("Entering command line mode",null))},{intent:T.Confirm,mode:g.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,currentNode:t}=v();if(!U(e?.id??"")?.length){if(e?.title===q.DESCRIPTION)return O(()=>"edit "),C({mode:g.COMMAND_LINE}),c("Propose command",!0);if(e?.title===q.ASSIGNEES)return O(()=>"assign "),C({mode:g.COMMAND_LINE}),c("Propose command",!0);if(e?.title===q.TAGS)return O(()=>"tag "),C({mode:g.COMMAND_LINE}),c("Propose command",!0);if(t.title===q.DESCRIPTION&&e?.context==="TEXT")return O(()=>"edit "),C({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:()=>(C({mode:g.COMMAND_LINE}),O(()=>"edit"),ce(),c("Fired command",!0))},{intent:T.SetViewDense,mode:g.DEFAULT,description:"[v] view change (wide/dense)",action:()=>(C({viewMode:"dense"}),c("View set",null))},{intent:T.SetViewWide,mode:g.DEFAULT,action:()=>(C({viewMode:"wide"}),c("View set",null))}];var Ud=500,Bd=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Wi=e=>{let t=Bd(e);t&&O(n=>(n+t).slice(0,Ud))};var Hi=[{intent:T.ViewHelp,mode:g.DEFAULT,action:()=>(C({mode:g.HELP}),c("Viewing help",null))},{intent:T.Exit,mode:g.HELP,action:()=>(C({mode:g.DEFAULT}),c("Exiting help",null))},{intent:T.Confirm,mode:g.COMMAND_LINE,action:()=>(ce(),c("Executing command",null))},{intent:T.MoveCursorLeft,mode:g.COMMAND_LINE,action:()=>(nr(-1),c("Moving cursor left",null))},{intent:T.MoveCursorRight,mode:g.COMMAND_LINE,action:()=>(nr(1),c("Moving cursor right",null))},{intent:T.MoveCursorLeftOfWord,mode:g.COMMAND_LINE,action:()=>(rr("left"),c("Moving cursor left of word",null))},{intent:T.MoveCursorRightOfWord,mode:g.COMMAND_LINE,action:()=>(rr("right"),c("Moving cursor right of word",null))},{intent:T.ExitCommandLine,mode:g.COMMAND_LINE,action:()=>(C({mode:g.DEFAULT}),c("Exiting command line",null))},{intent:T.AutoCompleteCommand,mode:g.COMMAND_LINE,action:()=>(O((e,{remainder:t})=>t?e+t:e),c("Auto-completing command",null))},{intent:T.CaptureInput,mode:g.COMMAND_LINE,action:(e,{sequence:t})=>(Wi(t??""),c("Capturing input",null))},{intent:T.EraseInput,mode:g.COMMAND_LINE,action:()=>(Jo(),c("Erasing input",null))},{intent:T.EraseInputWord,mode:g.COMMAND_LINE,action:()=>(Zo(),c("Erasing input word",null))},{intent:T.GetLastCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(ti(),c("Getting last command from history",null))},{intent:T.GetNextCommandFromHistory,mode:g.COMMAND_LINE,action:()=>(ni(),c("Getting next command from history",null))}];import _d from"chalk";var Nn=": for command line",Ki="q to exit",Vi=`${_d.hex(M.accent)("m")} to confirm`,fr={[P.WORKSPACE]:[Nn],[P.BOARD]:[Nn],[P.BOARD+g.COMMAND_LINE]:[Nn],[P.SWIMLANE]:[Nn],[P.TICKET+g.HELP]:[Ki],[P.SWIMLANE+g.HELP]:[Ki],[P.TICKET]:[],[P.FIELD]:[],[P.SWIMLANE+g.MOVE]:[Vi],[P.TICKET+g.MOVE]:[Vi]};var En=e=>e.trim().toLocaleLowerCase(),jd=(e,t)=>{let n=h.getFieldByTitle(e,t);if(!n)return"";let r=n.props?.value;return typeof r=="string"?r:""},$d=e=>{let{tags:t}=v(),n=h.getFieldByTitle(e,"Tags");return n?U(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},Wd=e=>{let{contributors:t}=v(),n=h.getFieldByTitle(e,"Assignees");return n?U(n.id).map(r=>{let o=r.props?.value;return typeof o=="string"?t[o]?.name:void 0}).filter(r=>!!r):[]},qi=(e,t)=>{let n=t.value;if(!n)return!0;switch(t.target){case"title":return En(e.title??"").includes(n);case"description":return En(jd(e.id,q.DESCRIPTION)).includes(n);case"tag":return $d(e.id).map(En).some(l=>l.includes(n));case"assignee":return Wd(e.id).map(En).some(l=>l.includes(n));default:return!0}};function zi(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 Gi=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 In,vr,yr=new Set,Xi=()=>{for(let e of yr)e()},Kd=e=>(yr.add(e),()=>yr.delete(e));function Yi(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=zi(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,x=fr[p+n]??fr[p]??[],N=[...$i,...ji[p]??[],...Hi],I=Gi(N),R=Vd(o,i),b=R[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,currentNode:l,breadCrumb:m,availableHints:x,availableActions:N,actionIndex:I,selectedNode:b,renderedChildrenIndex:R})}var v=()=>(In||logger.error("State not initialized. Call initWorkspaceState() first.",new Error().stack),In);function ft(e){vr=e;let t=Ae(process.cwd()),n=!1;if(!a(t)){let i=we(t.value);if(a(i))return s(i.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},viewMode:"dense",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=Yi(r);return a(o)?o:(In=o.value,Xi(),c("State initialized",null))}function oe(e){let t=v(),n=e(t),r=Yi(n);return a(r)?s(r.message??"Unable to update state"):(In=r.value,Xi(),c("State updated",null))}var C=e=>oe(t=>({...t,...e}));var pe=()=>Hd(Kd,v,v),Vd=(e,t)=>{let n={};for(let r of Object.values(e))ee(r)&&t.length>0&&!t.every(o=>qi(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},S=e=>v()?.renderedChildrenIndex[e]??[],gr=()=>vr?ft(vr):s("Cannot reset state: no initial workspace found");var D={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"||D.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:d})=>d===e.id),i=r.length===0?-1:o>=0?o:0;D.navigate({currentNode:n,selectedIndex:i})},navigateToNextItem:()=>Ji(1),navigateToPreviousItem:()=>Ji(-1),navigateToNextContainer:()=>Zi(1),navigateToPreviousContainer:()=>Zi(-1),navigate:({currentNode:e=v().currentNode,selectedIndex:t})=>{C({currentNodeId:e.id,selectedIndex:t})}},Ji=e=>{let t=v(),n=S(t.currentNode.id).length;if(n===0)return;let o=(Math.max(0,t.selectedIndex)+e+n)%n;D.navigate({selectedIndex:o})},Zi=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),d=i.findIndex(N=>N.id===t.id);if(d<0)return;let l=i.at(d+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;D.navigate({currentNode:l,selectedIndex:x})};var Ct=qd();function zd(){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 Gd(){let e=zd();D.navigate(e)}function Di({userId:e,userName:t}){let n=Ct(),r=Ct(),o=Ct(),i=Ct(),d=Ct(),l=V(void 0,void 0);if(a(l))return l;let u=V(void 0,void 0);if(a(u))return u;let m=V(u.value,void 0);if(a(m))return m;let p=V(void 0,void 0);if(a(p))return p;let x=V(p.value,void 0);if(a(x))return x;let N=V(x.value,void 0);if(a(N))return N;let I=V(void 0,void 0);return a(I)?I:c("Created default events",[{id:Re(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:Re(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Re(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Re(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"In progress",parent:r,rank:x.value}},{id:Re(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:r,rank:N.value}},{id:Re(),userId:e,userName:t,action:"add.board",payload:{id:Qt,name:"Closed",parent:n,rank:m.value}},{id:Re(),userId:e,userName:t,action:"add.swimlane",payload:{id:J,name:"Closed",parent:Qt,rank:I.value}},{id:Re(),userId:e,userName:t,action:"lock.node",payload:{id:Qt}},{id:Re(),userId:e,userName:t,action:"lock.node",payload:{id:J}}])}function yn({hasProject:e,eventLog:t}){if(!e){let o=X.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=ft(o);return a(i)?i:(C({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=gt(t).filter(a);return r.length>0?s(r.map(o=>o.message).join(`
|
|
58
|
+
`)):(Gd(),C({hasProject:!0}),c("State booted successfully",null))}var He=e=>{let t=le(e??process.cwd());if(a(t))return t;let n=ut(t.value);if(a(n))return s(n.message);let r=yn({eventLog:n.value,hasProject:!0});return a(r)?s(r.message):c("Booted Epiq state",{root:t.value})},Cn=()=>{let e=xo();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")},es=(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):[]},Xd=e=>es(e,"Tags").map(t=>h.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name})),Yd=e=>es(e,"Assignees").map(t=>h.getContributor(t)).filter(Boolean).map(t=>({id:t.id,name:t.name})),ts=(e={})=>{let t=He(e.repoRoot);if(a(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)},ns=(e={})=>{let t=He(e.repoRoot);if(a(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)},rs=e=>{let t=He(e.repoRoot);if(a(t))return t;let n=Object.values(v().nodes).filter(ee).filter(r=>e.includeClosed||r.parentNodeId!==J).map(r=>({id:r.id,title:Xe(r.title),description:Do(r,"Description"),parentId:r.parentNodeId,isClosed:r.parentNodeId===J,readonly:!!r.readonly,tags:Xd(r),assignees:Yd(r)}));return c("Listed issues",n)},os=e=>{let t=He(e.repoRoot);if(a(t))return t;let n=Cn();if(a(n))return n;let r=Me(e.parentId,n.value);if(a(r))return r;let o=Xt({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(a(o))return o;let i=o.value,l=Te(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")},is=e=>{let t=He(e.repoRoot);if(a(t))return t;let n=Cn();if(a(n))return n;let r=he(J,e.issueId,{at:"end"},n.value);if(a(r))return r;let o={id:Qi(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:J,rank:r.value}},d=Te([o]).find(a);return d?s(d.message):c("Closed issue",{id:e.issueId})},ss=e=>{let t=He(e.repoRoot);if(a(t))return t;let n=Cn();if(a(n))return n;let r=he(e.parentId,e.issueId,e.position??{at:"end"},n.value);if(a(r))return r;let o={id:Qi(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:r.value}},d=Te([o]).find(a);return d?s(d.message):c("Moved issue",{id:e.issueId,parentId:e.parentId})},as=async(e={})=>{let t=le(e.repoRoot??process.cwd());if(a(t))return s("Sync failed");let n=Cn();if(a(n))return n;let r=await Kt({cwd:t.value,ownEventFileName:Ue(n.value)});return a(r)?r:c("Synced",r.value)},ds=(e={})=>{let t=He(e.repoRoot);return a(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 De=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Qd=()=>{let e=new Jd({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=>De(await ds(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues",inputSchema:F.object({repoRoot:F.string().optional(),includeClosed:F.boolean().optional()})},async t=>De(await rs(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>De(await ts(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:F.object({repoRoot:F.string().optional(),boardId:F.string().optional()})},async t=>De(await ns(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=>De(await os(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=>De(await is(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=>De(await ss(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote",inputSchema:F.object({repoRoot:F.string().optional()})},async t=>De(await as(t))),e},ec=async()=>{let e=Qd(),t=new Zd;await e.connect(t)};await ec();export{Qd as createMcpServer,De as resultJson,ec as startMcpServer};
|