epiq 0.4.5 → 0.4.7

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