epiq 1.4.1 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -1,58 +1,58 @@
1
1
  #!/usr/bin/env node
2
- var Cu=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var Au=(e,t)=>{for(var n in t)Cu(e,n,{get:t[n],enumerable:!0})};var wt,i,c,a,vt,S=y(()=>{"use strict";wt={Success:"success",Fail:"fail"},i=e=>({status:wt.Fail,message:e,value:null}),c=(e,t)=>({status:wt.Success,message:e,value:t}),a=e=>e.status==="fail",vt=e=>e.status==="success"});import Tu from"node:os";import wu from"node:path";var Qe,jn,Gr=y(()=>{"use strict";Qe=".epiq-global",jn=()=>process.env.EPIQ_GLOBAL_DIR??wu.join(Tu.homedir(),Qe)});import Wn from"node:fs";import ot from"node:path";var fv,rt,Ao,Yr,Mu,Hn,To,Kn,Xr,Ri,ku,Jr,wo,Ze,Si,st,ue=y(()=>{"use strict";S();at();Gr();fv=process.env.IS_LOCAL==="true",rt=".epiq",Ao="events",Yr="media",Mu="project.json",Hn=e=>ot.join(e,rt),To=e=>ot.join(Hn(e),Mu),Kn=e=>ot.join(Hn(e),Ao),Xr=e=>ot.join(Hn(e),Yr),Ri=e=>ot.join(e,rt),ku=e=>{let t=ot.join(e,rt);return Wn.existsSync(t)&&Wn.statSync(t).isDirectory()},Jr=e=>{let t=To(e);return Wn.existsSync(t)&&Wn.statSync(t).isFile()},wo=e=>{let t=ot.resolve(e);for(;;){if(ku(t))return c("Resolved closest .epiq root",t);let n=ot.dirname(t);if(n===t)return i("No .epiq directory found in any parent");t=n}},Ze=e=>{let t=ot.resolve(e);for(;;){if(Jr(t))return c("Resolved closest epiq project root",t);let n=ot.dirname(t);if(n===t)return i("No .epiq/project.json found in any parent");t=n}},Si=e=>{let t=Kn(e);try{return Wn.mkdirSync(t,{recursive:!0}),c("Resolved events dir",t)}catch(n){return i(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},st=async()=>{let e=await it(process.cwd());if(a(e))return e;let t=Me({repoRoot:e.value});return a(t)?t:c("Resolved persist root",t.value)}});import qn from"node:fs";import{ulid as Lu}from"ulid";import{z as Mo}from"zod";var Pu,Du,ko,ht,Ci,Ai,Mt=y(()=>{"use strict";S();ue();Pu="__epiq_state__",Du=Mo.object({projectId:Mo.string().min(1),stateBranch:Mo.string().min(1),createdAt:Mo.iso.datetime()}),ko=()=>({projectId:Lu(),stateBranch:Pu,createdAt:new Date().toISOString()}),ht=e=>{let t=To(e);if(!qn.existsSync(t))return i("Missing .epiq/project.json");try{let n=qn.readFileSync(t,"utf8"),o=JSON.parse(n),r=Du.safeParse(o);return r.success?c("Read project.json",r.data):i(`Invalid .epiq/project.json: ${r.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return i(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},Ci=e=>{let t=ht(e);return a(t)?i(t.message):c("Read projectId",t.value.projectId)},Ai=({repoRoot:e,fileContents:t})=>{let n=Hn(e),o=To(e);try{if(qn.mkdirSync(n,{recursive:!0}),qn.existsSync(o)){let r=ht(e);return a(r)?i(r.message):c("Project already initialized",null)}return qn.writeFileSync(o,JSON.stringify(t,null,2)+`
3
- `,"utf8"),c("Created project.json",null)}catch(r){return i(r instanceof Error?`Failed to initialize project: ${r.message}`:"Failed to initialize project")}}});var Qr,Ti=y(()=>{"use strict";S();Qr=(e,t)=>{let n=new Map,o=t??((...s)=>JSON.stringify(s)),r=((...s)=>{let d=o(...s);if(!n.has(d)){let l=e(...s).then(u=>(a(u)&&n.delete(d),u));n.set(d,l)}return n.get(d)});return r.clear=()=>n.clear(),r}});import zn from"fs";import ns from"path";import Fu from"util";function Ou(){let e=ki();if(!e||!zn.existsSync(e))return;let n=zn.readFileSync(e,"utf8").split(`
2
+ var Au=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var Tu=(e,t)=>{for(var n in t)Au(e,n,{get:t[n],enumerable:!0})};var Mt,i,c,a,vt,C=y(()=>{"use strict";Mt={Success:"success",Fail:"fail"},i=e=>({status:Mt.Fail,message:e,value:null}),c=(e,t)=>({status:Mt.Success,message:e,value:t}),a=e=>e.status==="fail",vt=e=>e.status==="success"});import wu from"node:os";import Mu from"node:path";var Qe,jn,Yr=y(()=>{"use strict";Qe=".epiq-global",jn=()=>process.env.EPIQ_GLOBAL_DIR??Mu.join(wu.homedir(),Qe)});import Wn from"node:fs";import ot from"node:path";var vv,rt,Ao,Xr,Lu,Hn,To,Kn,Jr,Ri,ku,Qr,wo,Ze,Ci,st,ue=y(()=>{"use strict";C();at();Yr();vv=process.env.IS_LOCAL==="true",rt=".epiq",Ao="events",Xr="media",Lu="project.json",Hn=e=>ot.join(e,rt),To=e=>ot.join(Hn(e),Lu),Kn=e=>ot.join(Hn(e),Ao),Jr=e=>ot.join(Hn(e),Xr),Ri=e=>ot.join(e,rt),ku=e=>{let t=ot.join(e,rt);return Wn.existsSync(t)&&Wn.statSync(t).isDirectory()},Qr=e=>{let t=To(e);return Wn.existsSync(t)&&Wn.statSync(t).isFile()},wo=e=>{let t=ot.resolve(e);for(;;){if(ku(t))return c("Resolved closest .epiq root",t);let n=ot.dirname(t);if(n===t)return i("No .epiq directory found in any parent");t=n}},Ze=e=>{let t=ot.resolve(e);for(;;){if(Qr(t))return c("Resolved closest epiq project root",t);let n=ot.dirname(t);if(n===t)return i("No .epiq/project.json found in any parent");t=n}},Ci=e=>{let t=Kn(e);try{return Wn.mkdirSync(t,{recursive:!0}),c("Resolved events dir",t)}catch(n){return i(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},st=async()=>{let e=await it(process.cwd());if(a(e))return e;let t=Me({repoRoot:e.value});return a(t)?t:c("Resolved persist root",t.value)}});import qn from"node:fs";import{ulid as Pu}from"ulid";import{z as Mo}from"zod";var Du,Fu,Lo,ht,Si,Ai,Lt=y(()=>{"use strict";C();ue();Du="__epiq_state__",Fu=Mo.object({projectId:Mo.string().min(1),stateBranch:Mo.string().min(1),createdAt:Mo.iso.datetime()}),Lo=()=>({projectId:Pu(),stateBranch:Du,createdAt:new Date().toISOString()}),ht=e=>{let t=To(e);if(!qn.existsSync(t))return i("Missing .epiq/project.json");try{let n=qn.readFileSync(t,"utf8"),o=JSON.parse(n),r=Fu.safeParse(o);return r.success?c("Read project.json",r.data):i(`Invalid .epiq/project.json: ${r.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return i(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},Si=e=>{let t=ht(e);return a(t)?i(t.message):c("Read projectId",t.value.projectId)},Ai=({repoRoot:e,fileContents:t})=>{let n=Hn(e),o=To(e);try{if(qn.mkdirSync(n,{recursive:!0}),qn.existsSync(o)){let r=ht(e);return a(r)?i(r.message):c("Project already initialized",null)}return qn.writeFileSync(o,JSON.stringify(t,null,2)+`
3
+ `,"utf8"),c("Created project.json",null)}catch(r){return i(r instanceof Error?`Failed to initialize project: ${r.message}`:"Failed to initialize project")}}});var Zr,Ti=y(()=>{"use strict";C();Zr=(e,t)=>{let n=new Map,o=t??((...s)=>JSON.stringify(s)),r=((...s)=>{let d=o(...s);if(!n.has(d)){let l=e(...s).then(u=>(a(u)&&n.delete(d),u));n.set(d,l)}return n.get(d)});return r.clear=()=>n.clear(),r}});import zn from"fs";import os from"path";import Bu from"util";function Uu(){let e=Li();if(!e||!zn.existsSync(e))return;let n=zn.readFileSync(e,"utf8").split(`
4
4
  `);if(n[n.length-1]===""&&n.pop(),n.length<=wi)return;let o=n.slice(-wi).join(`
5
5
  `)+`
6
- `;zn.writeFileSync(e,o,"utf8")}function es(e,t,n=!1){let o=ki();if(!o)return;let r=Fu.format(...t),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${r}
7
- `;zn.mkdirSync(ns.dirname(o),{recursive:!0}),zn.appendFileSync(o,l,"utf8"),Zr++,Zr>=Bu&&(Zr=0,Ou())}var wi,Bu,Zr,Mi,ki,ts,ve,gn=y(()=>{"use strict";S();ue();wi=1e3,Bu=50,Zr=0,Mi=()=>process.env.EPIQ_MCP==="true",ki=()=>{let e=process.cwd(),t=wo(e);return a(t)?Mi()?ns.join(process.cwd(),".epiq-mcp.log"):void 0:ns.join(t.value,rt,"log","epiq.log")};ts=()=>Mi()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",ve={info(...e){let t=ts();(t==="info"||t==="debug")&&es("[Info]",e,!1)},debug(...e){ts()==="debug"&&es("[Debug]",e,!0)},error(...e){let t=ts();if(t==="error"||t==="info"||t==="debug"){let o=e.some(r=>r instanceof Error)?void 0:new Error().stack;es("[Error]",[...e,o].filter(Boolean),!1)}}};globalThis.logger=ve});var de,Lo=y(()=>{"use strict";kt();de={stage:({cwd:e,pathspec:t})=>j({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>j({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>j({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>j({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>j({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:o=!1})=>{let r=t&&n?["push",...o?["-u"]:[],t,n]:["push"];return j({args:r,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>j({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>j({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>j({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>j({args:["worktree","prune"],cwd:e})}});var fn,qe,Po=y(()=>{"use strict";Mt();S();ue();fn=e=>{let t=Ze(e);if(a(t))return i("Unable to resolve epiq project root");let n=ht(t.value);return a(n)?i("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},qe="origin"});import{spawn as Uu}from"node:child_process";import Do from"node:fs";import Vn from"node:path";var Li,_u,Pi,j,dt,vn,$u,ju,Fo,os,Bo,Oo,Gn,Di,rs,Uo,Fi,Bi,Wu,ss,Oi,Ui,kt=y(()=>{"use strict";S();Lo();Po();Li=1e4,_u={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Pi=({args:e,cwd:t,allowFail:n})=>new Promise(o=>{if(!Do.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){o({stdout:"",stderr:p,exitCode:1});return}o(i(p));return}let r=Uu("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:_u}),s=!1,d="",l="",u=p=>{s||(s=!0,clearTimeout(m),o(p))},m=setTimeout(()=>{r.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${Li}ms`].join(`
8
- `);u(n?{stdout:d,stderr:p,exitCode:124}:i(p))},Li);r.stdout.setEncoding("utf8"),r.stderr.setEncoding("utf8"),r.stdout.on("data",p=>{d+=p}),r.stderr.on("data",p=>{l+=p}),r.on("error",p=>{if(n){u({stdout:d,stderr:p.message,exitCode:1});return}u(i([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
6
+ `;zn.writeFileSync(e,o,"utf8")}function ts(e,t,n=!1){let o=Li();if(!o)return;let r=Bu.format(...t),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${r}
7
+ `;zn.mkdirSync(os.dirname(o),{recursive:!0}),zn.appendFileSync(o,l,"utf8"),es++,es>=Ou&&(es=0,Uu())}var wi,Ou,es,Mi,Li,ns,ve,fn=y(()=>{"use strict";C();ue();wi=1e3,Ou=50,es=0,Mi=()=>process.env.EPIQ_MCP==="true",Li=()=>{let e=process.cwd(),t=wo(e);return a(t)?Mi()?os.join(process.cwd(),".epiq-mcp.log"):void 0:os.join(t.value,rt,"log","epiq.log")};ns=()=>Mi()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",ve={info(...e){let t=ns();(t==="info"||t==="debug")&&ts("[Info]",e,!1)},debug(...e){ns()==="debug"&&ts("[Debug]",e,!0)},error(...e){let t=ns();if(t==="error"||t==="info"||t==="debug"){let o=e.some(r=>r instanceof Error)?void 0:new Error().stack;ts("[Error]",[...e,o].filter(Boolean),!1)}}};globalThis.logger=ve});var de,ko=y(()=>{"use strict";kt();de={stage:({cwd:e,pathspec:t})=>j({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>j({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>j({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>j({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>j({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:o=!1})=>{let r=t&&n?["push",...o?["-u"]:[],t,n]:["push"];return j({args:r,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>j({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>j({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>j({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>j({args:["worktree","prune"],cwd:e})}});var vn,qe,Po=y(()=>{"use strict";Lt();C();ue();vn=e=>{let t=Ze(e);if(a(t))return i("Unable to resolve epiq project root");let n=ht(t.value);return a(n)?i("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},qe="origin"});import{spawn as _u}from"node:child_process";import Do from"node:fs";import Vn from"node:path";var ki,$u,Pi,j,dt,hn,ju,Wu,Fo,rs,Bo,Oo,Gn,Di,ss,Uo,Fi,Bi,Hu,is,Oi,Ui,kt=y(()=>{"use strict";C();ko();Po();ki=1e4,$u={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Pi=({args:e,cwd:t,allowFail:n})=>new Promise(o=>{if(!Do.existsSync(t)){let p=`Git cwd does not exist: ${t}`;if(n){o({stdout:"",stderr:p,exitCode:1});return}o(i(p));return}let r=_u("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:$u}),s=!1,d="",l="",u=p=>{s||(s=!0,clearTimeout(m),o(p))},m=setTimeout(()=>{r.kill("SIGTERM");let p=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${ki}ms`].join(`
8
+ `);u(n?{stdout:d,stderr:p,exitCode:124}:i(p))},ki);r.stdout.setEncoding("utf8"),r.stderr.setEncoding("utf8"),r.stdout.on("data",p=>{d+=p}),r.stderr.on("data",p=>{l+=p}),r.on("error",p=>{if(n){u({stdout:d,stderr:p.message,exitCode:1});return}u(i([`git ${e.join(" ")}`,`cwd=${t}`,p.message].join(`
9
9
  `)))}),r.on("close",p=>{let v=p??1;if(n){u({stdout:d,stderr:l,exitCode:v});return}if(v!==0){u(i([`git ${e.join(" ")}`,l.trim()||d.trim()||"Git command failed"].filter(Boolean).join(`
10
- `)));return}u(c("Git command succeeded",{stdout:d,stderr:l,exitCode:v}))})}),j=({args:e,cwd:t})=>Pi({args:e,cwd:t,allowFail:!1}),dt=({args:e,cwd:t})=>Pi({args:e,cwd:t,allowFail:!0}),vn=async({cwd:e,message:t})=>{let n=await de.commit({cwd:e,message:t});if(a(n))return i(`Failed to create commit
10
+ `)));return}u(c("Git command succeeded",{stdout:d,stderr:l,exitCode:v}))})}),j=({args:e,cwd:t})=>Pi({args:e,cwd:t,allowFail:!1}),dt=({args:e,cwd:t})=>Pi({args:e,cwd:t,allowFail:!0}),hn=async({cwd:e,message:t})=>{let n=await de.commit({cwd:e,message:t});if(a(n))return i(`Failed to create commit
11
11
  ${n.message}`);let o=await j({args:["rev-parse","HEAD"],cwd:e});return a(o)?i(`Commit created, but failed to read HEAD SHA
12
- ${o.message}`):c("Created commit and resolved SHA",o.value.stdout.trim())},$u=async e=>{let t=await j({cwd:e,args:["rev-parse","--git-dir"]});if(a(t))return i(t.message);let n=t.value.stdout.trim();return c("Resolved git dir",Vn.isAbsolute(n)?n:Vn.resolve(e,n))},ju=async e=>{let t=await $u(e);if(a(t))return i(t.message);let n=t.value,o={MERGE_HEAD:"merge in progress"};for(let[s,d]of Object.entries(o))if(Do.existsSync(Vn.join(n,s)))return c("Checked for in-progress Git operation",d);let r={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,d]of Object.entries(r))if(Do.existsSync(Vn.join(n,s)))return c("Checked for in-progress Git operation",d);return c("Checked for in-progress Git operation",null)},Fo=async e=>{let t=await ju(e);return a(t)?i(t.message):c("Checked for in-progress Git operation",t.value!==null)},os=async({repoRoot:e})=>{let n=(await dt({args:["remote","get-url",qe],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},Bo=async({repoRoot:e,branch:t})=>{let n=await dt({args:["ls-remote","--heads",qe,t],cwd:e});return n.exitCode!==0?i(n.stderr.trim()||`Unable to inspect remote branch ${qe}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},Oo=async({repoRoot:e,branch:t})=>{let n=await dt({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):i(n.stderr.trim()||`Unable to inspect branch ${t}`)},Gn=e=>{try{return Do.realpathSync.native(e)}catch{return Vn.resolve(e)}},Di=async({repoRoot:e,worktreeRoot:t})=>{let n=await j({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let o=Gn(t),r=n.value.stdout.split(`
13
- `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Gn).includes(o);return c("Checked worktree registration",r)},rs=async e=>{let t=await dt({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Uo=async e=>{let t=await j({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved current branch",t.value.stdout.trim())},Fi=async e=>{let t=await j({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},Bi=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Wu=async e=>(await dt({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1),ss=async({cwd:e,branch:t})=>{let n=await Bo({repoRoot:e,branch:t});if(a(n))return i(n.message);if(!n.value)return c("Remote branch missing, skipped pull",!1);let o=await Wu(e);if(a(o))return i(o.message);let r=await de.fetch({cwd:e,remote:qe,branch:t});if(a(r))return i(`Failed to fetch ${t}
12
+ ${o.message}`):c("Created commit and resolved SHA",o.value.stdout.trim())},ju=async e=>{let t=await j({cwd:e,args:["rev-parse","--git-dir"]});if(a(t))return i(t.message);let n=t.value.stdout.trim();return c("Resolved git dir",Vn.isAbsolute(n)?n:Vn.resolve(e,n))},Wu=async e=>{let t=await ju(e);if(a(t))return i(t.message);let n=t.value,o={MERGE_HEAD:"merge in progress"};for(let[s,d]of Object.entries(o))if(Do.existsSync(Vn.join(n,s)))return c("Checked for in-progress Git operation",d);let r={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,d]of Object.entries(r))if(Do.existsSync(Vn.join(n,s)))return c("Checked for in-progress Git operation",d);return c("Checked for in-progress Git operation",null)},Fo=async e=>{let t=await Wu(e);return a(t)?i(t.message):c("Checked for in-progress Git operation",t.value!==null)},rs=async({repoRoot:e})=>{let n=(await dt({args:["remote","get-url",qe],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},Bo=async({repoRoot:e,branch:t})=>{let n=await dt({args:["ls-remote","--heads",qe,t],cwd:e});return n.exitCode!==0?i(n.stderr.trim()||`Unable to inspect remote branch ${qe}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},Oo=async({repoRoot:e,branch:t})=>{let n=await dt({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):i(n.stderr.trim()||`Unable to inspect branch ${t}`)},Gn=e=>{try{return Do.realpathSync.native(e)}catch{return Vn.resolve(e)}},Di=async({repoRoot:e,worktreeRoot:t})=>{let n=await j({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let o=Gn(t),r=n.value.stdout.split(`
13
+ `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Gn).includes(o);return c("Checked worktree registration",r)},ss=async e=>{let t=await dt({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Uo=async e=>{let t=await j({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved current branch",t.value.stdout.trim())},Fi=async e=>{let t=await j({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},Bi=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Hu=async e=>(await dt({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1),is=async({cwd:e,branch:t})=>{let n=await Bo({repoRoot:e,branch:t});if(a(n))return i(n.message);if(!n.value)return c("Remote branch missing, skipped pull",!1);let o=await Hu(e);if(a(o))return i(o.message);let r=await de.fetch({cwd:e,remote:qe,branch:t});if(a(r))return i(`Failed to fetch ${t}
14
14
  ${r.message}`);let s=await de.pullRebase({cwd:e,remote:qe,branch:t});return a(s)?i(`Failed during pull --rebase
15
- ${s.message}`):c("Pulled with rebase",!0)},Oi=async e=>{let t=await dt({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?c("No staged changes",!1):t.exitCode===1?c("Has staged changes",!0):i(t.stderr.trim()||"Unable to inspect staged changes")},Ui=async e=>{let t=await Uo(e);return a(t)?i(t.message):c("Checked detached HEAD state",t.value==="HEAD")}});import is from"node:fs";import ct from"node:path";var $i,as,ji,Wi,_o,Me,Hu,_i,Yn,$o,Hi,Ki,qi,it,sh,at=y(()=>{"use strict";Mt();S();Gr();ue();Ti();gn();kt();$i="4b825dc642cb6eb9a060e54bf8d69288fbee4904",as=e=>ct.join(rt,Ao,e),ji=()=>ct.join(rt,Yr),Wi=jn,_o=()=>ct.join(Wi(),"worktrees"),Me=({repoRoot:e})=>{let t=Ci(e);return a(t)?i(t.message):c("Resolved state branch root",ct.join(_o(),t.value))},Hu=e=>ct.join(e,rt),_i=e=>ct.join(Hu(e),Ao),Yn=e=>{try{return is.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return i(t instanceof Error?t.message:String(t))}},$o=()=>{let e=Yn(Wi());if(a(e))return i(`Ensure epiq home failed.
15
+ ${s.message}`):c("Pulled with rebase",!0)},Oi=async e=>{let t=await dt({args:["diff","--cached","--quiet"],cwd:e});return t.exitCode===0?c("No staged changes",!1):t.exitCode===1?c("Has staged changes",!0):i(t.stderr.trim()||"Unable to inspect staged changes")},Ui=async e=>{let t=await Uo(e);return a(t)?i(t.message):c("Checked detached HEAD state",t.value==="HEAD")}});import as from"node:fs";import ct from"node:path";var $i,ds,ji,Wi,_o,Me,Ku,_i,Yn,$o,Hi,Ki,qi,it,ih,at=y(()=>{"use strict";Lt();C();Yr();ue();Ti();fn();kt();$i="4b825dc642cb6eb9a060e54bf8d69288fbee4904",ds=e=>ct.join(rt,Ao,e),ji=()=>ct.join(rt,Xr),Wi=jn,_o=()=>ct.join(Wi(),"worktrees"),Me=({repoRoot:e})=>{let t=Si(e);return a(t)?i(t.message):c("Resolved state branch root",ct.join(_o(),t.value))},Ku=e=>ct.join(e,rt),_i=e=>ct.join(Ku(e),Ao),Yn=e=>{try{return as.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return i(t instanceof Error?t.message:String(t))}},$o=()=>{let e=Yn(Wi());if(a(e))return i(`Ensure epiq home failed.
16
16
  `+e.message);let t=Yn(_o());return a(t)?i(`Ensure worktrees dir failed.
17
- `+t.message):c("Ensured epiq storage",!0)},Hi=e=>{is.existsSync(e)&&(ve.debug("[sync] remove path",e),is.rmSync(e,{recursive:!0,force:!0}))},Ki=(e,t)=>{for(let n of[_i(e),_i(t)]){let o=Yn(n);if(a(o))return i(o.message)}return c("Ensured state branch",void 0)},qi=async e=>{let t=await j({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return i(`ensure state branch is storage only failed
17
+ `+t.message):c("Ensured epiq storage",!0)},Hi=e=>{as.existsSync(e)&&(ve.debug("[sync] remove path",e),as.rmSync(e,{recursive:!0,force:!0}))},Ki=(e,t)=>{for(let n of[_i(e),_i(t)]){let o=Yn(n);if(a(o))return i(o.message)}return c("Ensured state branch",void 0)},qi=async e=>{let t=await j({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return i(`ensure state branch is storage only failed
18
18
  `+t.message);let o=t.value.stdout.trim().split(`
19
19
  `).filter(Boolean).filter(d=>d!==rt);if(o.length===0)return c("State branch is storage-only",!1);let r=await j({args:["rm","-r","--ignore-unmatch","--",...o],cwd:e});if(a(r))return i(`Failed to clean storage branch
20
- ${r.message}`);let s=await vn({cwd:e,message:"[epiq:repair-storage-branch]"});return a(s)?i(s.message):c("Cleaned storage branch",!0)},it=Qr(async(e=process.cwd())=>{let t=await j({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?i("Not inside a Git repository"):c("Resolved repo root",t.value.stdout.trim())},e=>ct.resolve(e)),sh=Qr(async e=>{let t=await j({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return i(t.message);let n=t.value.stdout.trim(),o=ct.isAbsolute(n)?n:ct.join(e,n);return c("Resolved git dir",o)},e=>ct.resolve(e))});import qt from"node:fs";import jo from"node:path";var Vi,zi,Ku,ds,qu,zu,Vu,Xn,Gu,Yu,Wo,Gi,Yi,Jn,Xi,Ho=y(()=>{"use strict";S();gn();Lo();Po();at();kt();Vi=async e=>{if((await dt({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);ve.info("Creating initial commit");let n=await de.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return a(n)?i(n.message):c("Created initial commit",!0)},zi=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Ku=async e=>{let t=await Uo(e);if(a(t))return i(t.message);let n=await Fi(e);return a(n)?i(n.message):c("Built sync commit message",`[sync|branch:${zi(t.value)}:sha:${zi(n.value)}]`)},ds=async({repoRoot:e,stateBranchName:t})=>{ve.info(`Creating ${t}`);let n=await j({args:["commit-tree",$i,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return i(`Failed to create state branch commit
20
+ ${r.message}`);let s=await hn({cwd:e,message:"[epiq:repair-storage-branch]"});return a(s)?i(s.message):c("Cleaned storage branch",!0)},it=Zr(async(e=process.cwd())=>{let t=await j({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?i("Not inside a Git repository"):c("Resolved repo root",t.value.stdout.trim())},e=>ct.resolve(e)),ih=Zr(async e=>{let t=await j({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return i(t.message);let n=t.value.stdout.trim(),o=ct.isAbsolute(n)?n:ct.join(e,n);return c("Resolved git dir",o)},e=>ct.resolve(e))});import zt from"node:fs";import jo from"node:path";var Vi,zi,qu,cs,zu,Vu,Gu,Xn,Yu,Xu,Wo,Gi,Yi,Jn,Xi,Ho=y(()=>{"use strict";C();fn();ko();Po();at();kt();Vi=async e=>{if((await dt({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);ve.info("Creating initial commit");let n=await de.commit({cwd:e,message:"Initial commit",allowEmpty:!0});return a(n)?i(n.message):c("Created initial commit",!0)},zi=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",qu=async e=>{let t=await Uo(e);if(a(t))return i(t.message);let n=await Fi(e);return a(n)?i(n.message):c("Built sync commit message",`[sync|branch:${zi(t.value)}:sha:${zi(n.value)}]`)},cs=async({repoRoot:e,stateBranchName:t})=>{ve.info(`Creating ${t}`);let n=await j({args:["commit-tree",$i,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return i(`Failed to create state branch commit
21
21
  ${n.message}`);let o=n.value.stdout.trim(),r=await j({args:["update-ref",`refs/heads/${t}`,o],cwd:e});return a(r)?i(`Failed to create ${t}
22
- ${r.message}`):c("Created state branch",!0)},qu=async({repoRoot:e,stateBranchName:t})=>{let n=await os({repoRoot:e});if(a(n))return i(`Ensure local state branch failed
22
+ ${r.message}`):c("Created state branch",!0)},zu=async({repoRoot:e,stateBranchName:t})=>{let n=await rs({repoRoot:e});if(a(n))return i(`Ensure local state branch failed
23
23
  `+n.message);let o=n.value,r=o?await Bo({repoRoot:e,branch:t}):c("No remote, no remote state branch",!1);if(a(r))return i(`Ensure local state branch failed
24
24
  `+r.message);let s=r.value;if(o&&s){let l=await de.fetch({cwd:e,remote:qe,branch:t});if(a(l))return i(`Failed to fetch ${t} from remote
25
25
  ${l.message}`)}let d=await Oo({repoRoot:e,branch:t});if(a(d))return i(`Ensure local state branch failed
26
26
  `+d.message);if(d.value)return c("Local state branch already exists",!1);if(s){let l=await j({args:["branch","--track",t,`${qe}/${t}`],cwd:e});return a(l)?i(`Failed to create local ${t} from remote
27
- ${l.message}`):c("Created local state branch from remote",!0)}return ds({repoRoot:e,stateBranchName:t})},zu=async({repoRoot:e,branch:t})=>{let n=await j({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let o=n.value.stdout.split(`
28
- `),r=null;for(let s of o){if(s.startsWith("worktree ")){r=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&r)return c("Found worktree for branch",r)}return c("No worktree found for branch",null)},Vu=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=Yn(jo.dirname(t));if(a(o))return i(`Failed to create state branch worktree
29
- `+o.message);qt.existsSync(t)&&!qt.existsSync(jo.join(t,".git"))&&(ve.info("Removing broken state branch worktree path"),Hi(t)),ve.info("Creating state branch worktree");let r=await de.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(r)?i(`Failed to create state branch worktree
30
- ${r.message}`):c("Created state branch worktree",!0)},Xn=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=await zu({repoRoot:e,branch:n});if(a(o))return i(o.message);let r=Gn(t),s=o.value?Gn(o.value):null;if(s&&s===r&&qt.existsSync(s))return c("State branch already checked out in expected worktree",!1);if(s&&s!==r){ve.info("Moving state branch worktree to expected location");let u=await de.worktreeRemove({cwd:e,worktreeRoot:s});if(a(u))return i(`Failed to remove existing state branch worktree
31
- ${u.message}`)}if(s&&!qt.existsSync(s)){ve.info("Pruning stale state branch worktree");let u=await de.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
32
- ${u.message}`)}let d=await Di({repoRoot:e,worktreeRoot:t});if(a(d))return i(d.message);let l=qt.existsSync(t);if(d.value&&l)return c("State branch worktree already exists",!1);if(d.value&&!l){ve.info("Pruning missing registered state branch worktree");let u=await de.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
33
- ${u.message}`)}return Vu({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Gu=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Uo(e);if(a(n))return i(n.message);if(n.value===t)return c("State branch already checked out",!1);(await dt({cwd:e,args:["rebase","--abort"]})).exitCode===0&&ve.info("Aborted stale state branch rebase");let r=await de.checkout({cwd:e,branch:t});return a(r)?i(`Failed to checkout ${t}
34
- ${r.message}`):c("Checked out state branch",!0)},Yu=async({repoRoot:e,stateBranchRoot:t})=>{let n=await rs(t);if(a(n))return i(n.message);if(n.value)return c("State branch upstream already configured",!1);let o=await os({repoRoot:t});if(a(o))return i(o.message);if(!o.value)return c("No remote available for state branch upstream",!1);let r=fn(e);if(a(r))return r;let s=r.value,d=await Bo({repoRoot:t,branch:s});if(a(d))return i(d.message);if(!d.value)return c("Remote state branch missing; upstream will be configured on first push",!1);ve.info(`Configuring ${s} upstream`);let l=await de.fetch({cwd:t,remote:qe,branch:s});if(a(l))return i(`Failed to fetch ${s}
27
+ ${l.message}`):c("Created local state branch from remote",!0)}return cs({repoRoot:e,stateBranchName:t})},Vu=async({repoRoot:e,branch:t})=>{let n=await j({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let o=n.value.stdout.split(`
28
+ `),r=null;for(let s of o){if(s.startsWith("worktree ")){r=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&r)return c("Found worktree for branch",r)}return c("No worktree found for branch",null)},Gu=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=Yn(jo.dirname(t));if(a(o))return i(`Failed to create state branch worktree
29
+ `+o.message);zt.existsSync(t)&&!zt.existsSync(jo.join(t,".git"))&&(ve.info("Removing broken state branch worktree path"),Hi(t)),ve.info("Creating state branch worktree");let r=await de.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(r)?i(`Failed to create state branch worktree
30
+ ${r.message}`):c("Created state branch worktree",!0)},Xn=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=await Vu({repoRoot:e,branch:n});if(a(o))return i(o.message);let r=Gn(t),s=o.value?Gn(o.value):null;if(s&&s===r&&zt.existsSync(s))return c("State branch already checked out in expected worktree",!1);if(s&&s!==r){ve.info("Moving state branch worktree to expected location");let u=await de.worktreeRemove({cwd:e,worktreeRoot:s});if(a(u))return i(`Failed to remove existing state branch worktree
31
+ ${u.message}`)}if(s&&!zt.existsSync(s)){ve.info("Pruning stale state branch worktree");let u=await de.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
32
+ ${u.message}`)}let d=await Di({repoRoot:e,worktreeRoot:t});if(a(d))return i(d.message);let l=zt.existsSync(t);if(d.value&&l)return c("State branch worktree already exists",!1);if(d.value&&!l){ve.info("Pruning missing registered state branch worktree");let u=await de.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
33
+ ${u.message}`)}return Gu({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Yu=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Uo(e);if(a(n))return i(n.message);if(n.value===t)return c("State branch already checked out",!1);(await dt({cwd:e,args:["rebase","--abort"]})).exitCode===0&&ve.info("Aborted stale state branch rebase");let r=await de.checkout({cwd:e,branch:t});return a(r)?i(`Failed to checkout ${t}
34
+ ${r.message}`):c("Checked out state branch",!0)},Xu=async({repoRoot:e,stateBranchRoot:t})=>{let n=await ss(t);if(a(n))return i(n.message);if(n.value)return c("State branch upstream already configured",!1);let o=await rs({repoRoot:t});if(a(o))return i(o.message);if(!o.value)return c("No remote available for state branch upstream",!1);let r=vn(e);if(a(r))return r;let s=r.value,d=await Bo({repoRoot:t,branch:s});if(a(d))return i(d.message);if(!d.value)return c("Remote state branch missing; upstream will be configured on first push",!1);ve.info(`Configuring ${s} upstream`);let l=await de.fetch({cwd:t,remote:qe,branch:s});if(a(l))return i(`Failed to fetch ${s}
35
35
  ${l.message}`);let u=await de.setUpstream({cwd:t,branch:s,upstream:`${qe}/${s}`});return a(u)?i(`Failed to set state branch upstream
36
- ${u.message}`):c("Configured state branch upstream",!0)},Wo=async({stateBranchRoot:e,eventFileName:t})=>{let n=as(t),o=jo.join(e,n);if(!qt.existsSync(o))return c("No event file to stage",void 0);let r=await de.stage({cwd:e,pathspec:[n]});return a(r)?i(`Failed to stage state branch event file
37
- ${r.message}`):c("Staged state branch event file",void 0)},Gi=async({stateBranchRoot:e})=>{let t=ji(),n=jo.join(e,t);if(!qt.existsSync(n))return c("No media directory to stage",void 0);let o=await de.stage({cwd:e,pathspec:[t]});return a(o)?i(`Failed to stage state branch media files
38
- ${o.message}`):c("Staged state branch media files",void 0)},Yi=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Ku(e);return a(n)?i(`Create state branch sync commit failed
39
- `+n.message):vn({cwd:t,message:n.value})},Jn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await rs(t);if(a(n))return i(n.message);let o=fn(e);if(a(o))return o;let r=o.value,s=n.value?await de.push({cwd:t}):await de.push({cwd:t,remote:qe,branch:r,setUpstream:!0});return a(s)?i(`Failed during state branch push
40
- ${s.message}`):c("Pushed state branch",!0)},Xi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let o=!1,r=fn(e);if(a(r))return r;let s=r.value,d=[$o(),await qu({repoRoot:e,stateBranchName:s}),await Xn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Gu({stateBranchRoot:t,stateBranchName:s}),await qi(t),n?await Yu({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of d){if(a(l))return i(l.message);o=o||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",o)}});import{WebSocket as Xu}from"ws";var Ju,Ji,Qi=y(()=>{"use strict";Ju=new Set,Ji=e=>{let t=JSON.stringify(e);for(let n of Ju)n.readyState===Xu.OPEN&&n.send(t)}});function cs(e){return e.context===D.WORKSPACE}function k(e){return e.context===D.TICKET}function Zi(e){return e.context===D.TEXT}function _e(e){return e.context===D.FIELD}function Qn(e){return e.context===D.FIELD_LIST}var D,zt,Ko,Zn,se=y(()=>{"use strict";D={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};zt=e=>e.context===D.SWIMLANE,Ko=e=>e.context===D.BOARD,Zn=e=>e.context===D.COMMENT});var f,te=y(()=>{"use strict";f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var ea=y(()=>{"use strict";Vt()});function qo(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}var eo,ze,hn=y(()=>{"use strict";eo=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",ze=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var ta,na,oa=y(()=>{"use strict";ta=e=>{let t=new Map;for(let n of e)for(let o=1;o<=n.length;o++){let r=n.slice(0,o),s=t.get(r);s?s.push(n):t.set(r,[n])}return t},na=(e,t)=>t?e.get(t)??[]:[]});var ra,Qu,sa,ia=y(()=>{"use strict";hn();oa();ra=new WeakMap,Qu=e=>{let t=ra.get(e);return t||(t=ta(e),ra.set(e,t)),t},sa=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let o=t.toLowerCase();return na(Qu(e),o).filter(s=>qo(o,s)>=n)}});var Zu,aa,em,da=y(()=>{"use strict";hn();ia();Zu={hint:"",hints:[],overlap:0,remainder:""},aa=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},o)=>{if(n||e==="")return Zu;let r=sa({wordList:o,inputToMatch:e,overlapThreshold:1});return em(t,r)},em=(e,t)=>{let n=t[0]??"",o=qo(e.toLowerCase(),n.toLowerCase()),[r,s]=n.split(":"),d=o<(r??"").length,l=!!s,p=(l&&d?r:n)+(l&&d?":":" "),v=p.slice(o);return{hint:p,hints:t,overlap:o,remainder:v}}});import{useSyncExternalStore as Ph}from"react";var zo,tm,nm,ie,Ve,ke=y(()=>{"use strict";zo={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},tm=new Set,nm=()=>{for(let e of tm)e()},ie=()=>zo,Ve=e=>(zo={...zo,...e},nm(),zo)});function ca(e){return!e||!rm.test(e)?i(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function $e(e,t=yn){if(e<0n)return i("Negative rank not allowed");let n=e.toString(16);return c("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function De(e,t){if(!e&&!t)return $e(et/2n,yn);let n=e?ca(e):c("Resolved lower bound",0n);if(a(n))return n;let o=t?ca(t):c("Resolved upper bound",et);if(a(o))return o;let r=n.value,s=o.value;if(s<=r)return $e(et/2n,yn);let d=(r+s)/2n;return d===r||d===s?i("No rank space available between neighbors"):$e(d,yn)}function la(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let o=0;o<e;o++){let r=et*BigInt(o+1)/(t+1n),s=$e(r,yn);if(a(s))return s;n.push(s.value)}return c("Resolved evenly spaced ranks",n)}var yn,om,et,rm,bn=y(()=>{"use strict";S();yn=24n,om=yn*4n,et=(1n<<om)-1n,rm=/^[0-9a-f]+$/});import{ulid as sm}from"ulid";var ls,ua=y(()=>{"use strict";S();lt();bn();ls=(e,t)=>{let n=ne(e),o=la(n.length);if(a(o))return o;let r={};for(let s=0;s<n.length;s++){let d=n[s],l=o.value[s];if(!d||!l)return i("Unable to assign rebalance rank");r[d.id]=l}return c("Created rebalance event",{id:sm(),action:"rebalance.children",payload:{parent:e,ranks:r},...t})}});var Vo,je,ut=y(()=>{"use strict";S();Vo="removed",je=(e,t)=>{let n=e.find(o=>o.context===t);return n!==void 0?c("Found node",n):i("Unable to find node in breadcrumb")}});var Gt,im,Lt,I,ce=y(()=>{"use strict";ut();se();S();w();lt();Gt=(e,t)=>{let{nodes:n}=g(),o=n[e];if(!o)return i("Node not found");if(o.context===t)return c("Resolved ancestor node",o);let r=o.parentNodeId?n[o.parentNodeId]:void 0;for(;r;){if(r.context===t)return c("Resolved ancestor node",r);r=r.parentNodeId?n[r.parentNodeId]:void 0}return i(`No ancestor found for context: ${t}`)},im=(e,t)=>{let{nodes:n}=g(),o=n[e];for(;o?.parentNodeId;){if(o.parentNodeId===t)return!0;o=n[o.parentNodeId]}return!1},Lt=(e,t)=>e?e.readonly?i({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:i("Node not found"),I={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return i("Contributor not found");if(n.userId&&n.userId!==t)return i("Contributor is already linked to another user");let o={...n,userId:t},r=me(s=>({...s,contributors:{...s.contributors,[e]:o}}));return a(r)?i("Unable to link contributor to user"):c("Linked contributor to user",o)},deleteNode(e){me(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create comment, missing issue");if(!k(t))return i("Can only comment on issues");let n=me(o=>({...o,comments:{...o.comments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?i("Unable to create comment"):c("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return i("Unable to edit comment, missing comment");let o=this.getNode(n.issue);if(!o)return i("Unable to edit comment, missing issue");if(!k(o))return i("Can only edit issue comments");let r={...n,md:t,deleted:!1},s=me(d=>({...d,comments:{...d.comments??{},[e]:r}}));return a(s)?i("Unable to edit comment"):c("Edited comment",r)},deleteComment(e){let t=this.getComment(e);if(!t)return i("Unable to delete comment, missing comment");let n={...t,deleted:!0},o=me(r=>({...r,comments:{...r.comments??{},[e]:n}}));return a(o)?i("Unable to delete comment"):c("Deleted comment",n)},getComment(e){return g().comments?.[e]},getCommentsByIssue(e){return Object.values(g().comments??{}).filter(t=>t.issue===e&&!t.deleted)},createAttachment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create attachment, missing issue");if(!k(t))return i("Can only attach to issues");let n=me(o=>({...o,attachments:{...o.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?i("Unable to create attachment"):c("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return i("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},o=me(r=>({...r,attachments:{...r.attachments??{},[e]:n}}));return a(o)?i("Unable to delete attachment"):c("Deleted attachment",n)},getAttachment(e){return g().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(g().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=g(),o=n[e];if(!o)return i("Edit target node not found");let r=Lt(o,"edit");if(r)return r;let s={...o,props:{...o.props,description:t}};return this.updateNode(s),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return i("Rename target node not found");let o=Lt(n,"rename");if(o)return o;let r={...n,title:t};return this.updateNode(r),c("Renamed node",r)},getExistingTags(){let{tags:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=g();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return ne(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:o}=g(),r=this.getNode(e),s=this.getNode(t);if(!r)return i("Node not found");if(!s)return i("Target parent not found");if(o===e)return i("Cannot move root node");if(e===t)return i("Cannot move node into itself");let d=Lt(r,"move");if(d)return d;if(im(t,e))return i("Cannot move node into its own descendant");let l={...r,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:o}=g(),r=this.getNode(e);if(!r)return i("Node not found");if(o===e)return i("Cannot delete root node");let s=Lt(r,"delete");if(s)return s;let d=new Set,l=m=>{let p=t[m];if(!(!p||d.has(m))){d.add(m);for(let v of ne(p.id))l(v.id)}};l(e);let u={...structuredClone(t)};for(let m of d){if(!u[m])return i("Unable to locate node to delete");u[m]={...u[m],isDeleted:!0}}return n?(E({nodes:u}),c("Successfully tomb stoned",r)):i("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return i("Contributor not found");let n={...t,name:Vo,tombstoned:!0},o=me(r=>({...r,contributors:{...r.contributors,[e]:n}}));return a(o)?i("Unable to remove contributor"):c("Tombstoned contributor",n)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return i("Contributor not found");let o={...n,name:t,tombstoned:!1},r=me(s=>({...s,contributors:{...s.contributors,[e]:o}}));return a(r)?i("Unable to restore contributor"):c("Restored contributor",o)},createContributor(e){let t=me(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?i("Unable to create contributor"):c("Created contributor",e)},assign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return i("Unable to assign contributor, missing contributor");if(!o)return i("Unable to assign contributor, missing target");let r=Lt(o,"edit");if(r)return r;if(!k(o))return i("Target is not an issue");let s=o.props.assignees??[];if(s.includes(t))return i("Contributor already assigned");let d={...o,props:{...o.props,assignees:[...s,t]}};return this.updateNode(d),c("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return i("Unable to unassign, missing contributor");if(!o)return i("Unable to unassign, missing target");let r=Lt(o,"edit");if(r)return r;if(!k(o))return i("Target is not an issue");let s=o.props.assignees??[];if(!s.includes(t))return c("Issue is not assigned to that contributor",{assignee:t});let d={...o,props:{...o.props,assignees:s.filter(l=>l!==t)}};return this.updateNode(d),c("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),o=this.getNode(e);if(!n)return i("Unable to add tag, missing tag");if(!o)return i("Unable to add tag, missing target");let r=Lt(o,"edit");if(r)return r;if(!k(o))return i("Target is not an issue");let s=o.props.tags??[];if(s.includes(t))return i("Tag already assigned");let d={...o,props:{...o.props,tags:[...s,t]}};return this.updateNode(d),c("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),o=this.getNode(e);if(!n)return i("Unable to remove tag, missing tag");if(!o)return i("Unable to remove tag, missing target");let r=Lt(o,"edit");if(r)return r;if(!k(o))return i("Target is not an issue");let s=o.props.tags??[];if(!s.includes(t))return c("Issue is not tagged with that tag",{tag:t});let d={...o,props:{...o.props,tags:s.filter(l=>l!==t)}};return this.updateNode(d),c("Tag removed",{tag:t})},createTag(e){let t=me(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?i("Could not create tag"):c("Tag created",e)},createNode(e){let t=me(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?i("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return i("Failed to locate node");let n={...t,readonly:!0},o=me(r=>({...r,nodes:{...r.nodes,[e]:n}}));return a(o)?i(o.message):c("Locked node",n)},updateNode(e){let t=me(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?t:c("Updated node",e)},getContributor(e){return g().contributors[e]},getTag(e){return g().tags[e]},getNode(e){return g().nodes[e]},getSiblings(e){return ne(e)}}});var X,xn=y(()=>{"use strict";X={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var tt,ma,In=y(()=>{"use strict";tt=e=>e.slice(-7).toUpperCase(),ma=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?tt(e).includes(n):!0}});var Ie,Yt=y(()=>{"use strict";se();In();Ie={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:D.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,o,r=!1)=>({id:e,title:t,rank:o,isDeleted:!1,props:{ref:tt(e)},context:D.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:D.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:o,props:r={},childRenderAxis:s="horizontal",isVirtual:d=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:D.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:d}),fieldList:({id:e,name:t,parentNodeId:n,rank:o,childRenderAxis:r="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:D.FIELD_LIST,childRenderAxis:r,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{ref:tt(e)},context:D.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!0,isVirtual:s=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:D.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:r,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:o,props:r={},readonly:s=!0,isVirtual:d=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:D.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:d})}});var Ae,R,Le=y(()=>{"use strict";Ae={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},R={accent:Ae.cyan,accent2:Ae.magenta,primary:Ae.white,secondary:Ae.grayDark,secondary2:Ae.grayLight,gray:Ae.gray,green:Ae.green,yellow:Ae.yellow,red:Ae.red}});var N,En,Go=y(()=>{"use strict";Le();N={red:Ae.red,yellow:Ae.yellow,green:Ae.green,blue:Ae.blue,magenta:Ae.magenta,cyan:Ae.cyan},En={urgent:N.red,critical:N.red,important:N.red,blocker:N.red,asap:N.red,immediate:N.red,fail:N.red,failure:N.red,broken:N.red,bug:N.red,error:N.red,incident:N.red,outage:N.red,production:N.red,crash:N.red,security:N.red,warning:N.yellow,warn:N.yellow,risky:N.yellow,risk:N.yellow,attention:N.yellow,pending:N.yellow,review:N.yellow,"needs-review":N.yellow,qa:N.yellow,testing:N.yellow,test:N.yellow,validate:N.yellow,verification:N.yellow,staging:N.yellow,check:N.yellow,"follow-up":N.yellow,followup:N.yellow,waiting:N.yellow,blocked:N.yellow,hold:N.yellow,done:N.green,complete:N.green,completed:N.green,success:N.green,ok:N.green,stable:N.green,resolved:N.green,fixed:N.green,closed:N.green,merged:N.green,released:N.green,deployed:N.green,approved:N.green,verified:N.green,working:N.green,healthy:N.green,pass:N.green,passing:N.green,info:N.blue,information:N.blue,note:N.blue,docs:N.blue,documentation:N.blue,doc:N.blue,guide:N.blue,help:N.blue,explanation:N.blue,detail:N.blue,details:N.blue,context:N.blue,design:N.blue,discussion:N.blue,proposal:N.blue,idea:N.blue,feature:N.magenta,enhancement:N.magenta,improvement:N.magenta,refactor:N.magenta,refactoring:N.magenta,cleanup:N.magenta,optimize:N.magenta,optimization:N.magenta,perf:N.magenta,performance:N.magenta,upgrade:N.magenta,migration:N.magenta,modernize:N.magenta,debt:N.magenta,todo:N.cyan,next:N.cyan,planned:N.cyan,plan:N.cyan,future:N.cyan,backlog:N.cyan,investigate:N.cyan,explore:N.cyan,prototype:N.cyan}});import pa from"chalk";var ms,ga,us,fa,am,dm,va,cm,lm,to,Pe,ha,ya,Yo,um,mm,Xo,yt=y(()=>{"use strict";Go();ms={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ga=(e,t,n)=>Math.max(t,Math.min(n,e)),us=(e,t,n)=>e+(t-e)*n,fa=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},am=e=>e.toLowerCase().trim(),dm=(e,t,n)=>{let o=t/100,r=n/100,s=(1-Math.abs(2*r-1))*o,d=e/60,l=s*(1-Math.abs(d%2-1)),u=0,m=0,p=0;d>=0&&d<1?(u=s,m=l):d>=1&&d<2?(u=l,m=s):d>=2&&d<3?(m=s,p=l):d>=3&&d<4?(m=l,p=s):d>=4&&d<5?(u=l,p=s):(u=s,p=l);let v=r-s/2;return[Math.round((u+v)*255),Math.round((m+v)*255),Math.round((p+v)*255)]},va=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,cm=(e,t,n)=>{let o=ga(n,0,1);return[Math.round(us(e[0],t[0],o)),Math.round(us(e[1],t[1],o)),Math.round(us(e[2],t[2],o))]},lm=(e,t,n)=>cm(e,t,n),to=e=>{let n=fa(e)%360,o=dm(n,ms.stringColor.saturation,ms.stringColor.lightness);return va(o)},Pe=(e,t=En)=>{let n=am(e);return n&&t[n]?t[n]:to(n)},ha=e=>{let t=ms.gradient.stops,n=ga(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let o=t.length-1,r=n*o,s=Math.min(Math.floor(r),o-1),d=r-s;return lm(t[s],t[s+1],d)},ya=e=>va(ha(e)),Yo=e=>fa(e.toLowerCase().trim())/4294967295,um=e=>{let t=Yo(e);return ha(t)},mm=e=>{let[t,n,o]=um(e);return{normal:r=>pa.bgRgb(t,n,o).black(r),cursor:r=>pa.bgRgb(t,n,o).white.bold(r)}},Xo=e=>mm(e).normal(` ${e} `)});var Nn,Jo=y(()=>{"use strict";Nn=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:o,ms:r}of n){let s=Math.floor(t/r);if(s>=1)return`${s}${o} ago`}return"just now"}});import Pt from"chalk";import ba from"string-width";import{decodeTime as pm}from"ulid";var gm,fm,xa,vm,hm,Ia,Ea,ym,bm,xm,Im,Em,Na,Ra,ps=y(()=>{"use strict";ce();w();yt();Jo();gm=(e,t)=>e+" ".repeat(Math.max(0,t-ba(e))),fm=(e,t)=>" ".repeat(Math.max(0,t-ba(e)))+e,xa=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),vm=(e,t)=>t?e<t?"up":e>t?"down":null:null,hm=(e,t)=>{let n=I.getNode(e.payload.parent),o=n?Pt.dim.bgBlack(` ${n.title} `):"unknown",r=t.at(-1);if(r&&"parent"in r&&"rank"in r&&r.parent===e.payload.parent){let s=vm(e.payload.rank,r.rank);if(s)return`Moved ${s} in ${o}`}return`Moved issue to ${o}`},Ia=e=>`${Math.max(1,Math.round(e/1024))} KB`,Ea=e=>I.getAttachment(e)?.name??"",ym=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Pt.bgHex(Pe(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Pt.bgHex(Pe(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Pt.hex(Pe(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Pt.hex(Pe(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:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Pt.dim(`(${Ia(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Ea(e.payload.id);return t?`"${t}"`:""}default:return""}},bm=e=>{let t=Nn(pm(e));return Pt.gray(fm(t,8))},xm=12,Im=e=>gm(`${e}`,xm),Em=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?t.name:""}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}"`:"";case"move.node":{let t=I.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Ia(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Ea(e.payload.id);return t?`"${t}"`:""}default:return""}},Na=e=>[xa(e.action),Em(e)].filter(Boolean).join(" "),Ra=(e,t)=>{let n=bm(e.id),o=Im(e.userName),r=Pt.dim("\u203A"),s=e.action==="move.node"?hm(e,t):[xa(e.action),ym(e)].filter(Boolean).join(" ");return`${o} ${n} ${r} ${s}`}});import{createHash as Nm}from"node:crypto";var Rm,Sm,Ee,Rn=y(()=>{"use strict";Rm="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Sm=e=>{let t=Nm("sha256").update(e).digest(),n=0n;for(let r=0;r<16;r++)n=n<<8n|BigInt(t[r]);let o="";for(let r=0;r<26;r++){let s=BigInt((25-r)*5);o+=Rm[Number(n>>s&31n)]}return o},Ee=(e,t)=>Sm(`${e}:virtual:${t}`)});var Cm,Am,Tm,wm,Mm,km,Qo,Sa,Ca,Lm,Aa=y(()=>{"use strict";ps();se();S();xn();ce();Yt();w();bn();Rn();Cm=e=>Ee(e,"comments"),Am=e=>Ee(e,"description"),Tm=e=>Ee(e,"assignees"),wm=e=>Ee(e,"tags"),Mm=e=>Ee(e,"history"),km=e=>Ee(e,"attachments"),Qo=({id:e,name:t,parentNodeId:n,rank:o,value:r,readonly:s=!1,childRenderAxis:d="horizontal"})=>{let l=I.getNode(e);if(!l){let p=I.createNode({...Ie.field({id:e,name:t,parentNodeId:n,rank:o,props:{value:r},isVirtual:!0}),readonly:s,childRenderAxis:d});return a(p)?p:c("Virtual field created",void 0)}if(!_e(l))return i(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==o||l.props.value!==r||l.readonly!==s||l.childRenderAxis!==d))return c("Virtual field unchanged",void 0);let m=I.updateNode({...l,title:t,parentNodeId:n,rank:o,props:{...l.props,value:r},readonly:s,childRenderAxis:d});return a(m)?m:c("Virtual field updated",void 0)},Sa=({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!1,childRenderAxis:s="horizontal"})=>{let d=I.getNode(e);if(!d){let m=I.createNode({...Ie.fieldList({id:e,name:t,parentNodeId:n,rank:o,isVirtual:!0}),readonly:r,childRenderAxis:s});return a(m)?m:c("Virtual field list created",void 0)}if(!Qn(d))return i(`Existing virtual node ${e} is not a field list`);if(!(d.title!==t||d.parentNodeId!==n||d.rank!==o||d.readonly!==r||d.childRenderAxis!==s))return c("Virtual field list unchanged",void 0);let u=I.updateNode({...d,title:t,parentNodeId:n,rank:o,readonly:r,childRenderAxis:s});return a(u)?u:c("Virtual field list updated",void 0)},Ca=e=>{let t=$e(et/4n),n=$e(et/2n),o=$e(et*3n/4n),r=$e(et*7n/8n),s=$e(et*15n/16n),d=$e(et*13n/16n);if(a(t))return t;if(a(n))return n;if(a(o))return o;if(a(r))return r;if(a(s))return s;if(a(d))return d;let l=Qo({id:Am(e.id),name:X.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(l))return l;let u=Sa({id:Tm(e.id),name:X.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(u))return u;let m=Sa({id:wm(e.id),name:X.TAGS,parentNodeId:e.id,rank:o.value,readonly:!0});if(a(m))return m;let p=Qo({id:Cm(e.id),name:X.COMMENTS,parentNodeId:e.id,rank:r.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(p))return p;let v=Qo({id:km(e.id),name:X.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(v))return v;let x=Qo({id:Mm(e.id),name:X.HISTORY,parentNodeId:e.id,rank:d.value,value:Lm(e),readonly:!0,childRenderAxis:"vertical"});return a(x)?x:c("Ticket virtual nodes materialized",void 0)},Lm=e=>{let t=[...e.log].reverse(),n=new Map;for(let o of t){let r=n.get(o.action)??[];r.push(o.payload),n.set(o.action,r)}return t.map(o=>Ra(o,n.get(o.action)??[])).join(`
41
- `)}});var Pm,he,Zo,Sn=y(()=>{"use strict";Pm=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[he,Zo]=Pm});function Dt(e,t=!1){let n=$m[e.action];if(!n)return i(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);let o=n(e);if(a(o))return o;let r=_m(e,t);return r||o}var L,Ta,Dm,Fm,Bm,gs,Om,Um,_m,$m,bt,xt=y(()=>{"use strict";se();S();xn();ce();Yt();w();Aa();Sn();L=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Ta=e=>{let t=I.getNode(e);if(!t||!k(t)||t.isDeleted)return null;let n=Ca(t);return a(n)?n:null},Dm=e=>{for(let t of e){let n=Ta(t);if(n)return n;let o=g().nodes[t]?.parentNodeId;if(!o)continue;let r=Ta(o);if(r)return r}return null},Fm=(e,t)=>{let n=I.getNode(e);n&&I.updateNode({...n,log:[...n.log??[],t]})},Bm=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},gs=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":case"add.issue.attachment":case"delete.issue.attachment":return[e.payload.issue];case"delete.node":case"edit.description":return Bm(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"create.contributor":case"link.contributor.user":default:return[]}},Om=e=>{me(t=>({...t,eventLog:[...t.eventLog,e]}))},Um=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?L("Invalid user ID format",e):c("Valid user",null)},_m=(e,t)=>{let n=Um(e);if(a(n))return n;let o=[...new Set(gs(e))];t||(o.forEach(s=>Fm(s,e)),Om(e));let r=Dm(o);return r||null},$m={"init.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=Ie.workspace(t,n,o),s=no(r);if(a(s))return L(s.message,e);let d=I.createNode(r);return a(d)?L(d.message??"Failed to initialize workspace",e):cs(d.value)?c("Workspace initialized",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=I.createNode(Ie.workspace(t,n,o));return a(r)?L(r.message??"Failed to add workspace",e):cs(r.value)?c("Added workspace",{action:e.action,result:r.value}):i("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=I.createNode(Ie.board(t,n,o,r));return a(s)?L(s.message??"Unable to create board",e):Ko(s.value)?c("Added board",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=I.createNode(Ie.swimlane(t,n,o,r));return a(s)?L(s.message??"Unable to create swimlane",e):zt(s.value)?c("Added swimlane",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=I.createNode(Ie.ticket(t,n,o,r));return a(s)?L(s.message??"Unable to create issue",e):k(s.value)?c("Added issue",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:o,val:r,rank:s}=e.payload,d=I.createNode(Ie.field({id:t,name:n,parentNodeId:o,rank:s,props:{value:r},childRenderAxis:n.includes(X.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?L(d.message??`Unable to create field: ${n}`,e):_e(d.value)?c("Added field",{action:e.action,result:d.value}):i("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!I.getNode(t))return L(`Unable to locate node with id ${t}`,e);let r=I.renameNode(t,n);return a(r)?L(r.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:r.value})},"delete.node":e=>{let{id:t}=e.payload,n=I.tombstoneNode(t);return a(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,o=I.createTag({id:t,name:n});return a(o)?L(o.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:o.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,o=I.createContributor({id:t,name:n});return a(o)?L(o.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:o.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=I.tombstoneContributor(t);return a(n)?L(n.message??"Unable to remove contributor",e):c("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,o=I.restoreContributor(t,n);return a(o)?L(o.message??"Unable to restore contributor",e):c("Contributor restored",{action:e.action,result:o.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,o=I.tag(t,n);return a(o)?L(o.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,o=I.untag(t,n);return a(o)?L(o.message??"Unable to untag issue",e):c("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,o=I.assign(t,n);return a(o)?L(o.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,o=I.unassign(t,n);return a(o)?L(o.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:o}=e.payload,r=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(r)?L(r.message??"Failed to move node",e):c("Moved node",{action:e.action,result:r.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,o=I.editValue(t,n);return a(o)?L(o.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:o.value})},"close.issue":e=>{let{id:t,parent:n,rank:o}=e.payload,r=I.getNode(t);if(!r)return L("Unable to locate issue",e);if(!k(r))return L("Can only close issues",e);let s=I.getNode(he);if(!s)return L("Unable to locate target swimlane",e);if(n!==s.id)return L("Close target must be closed swimlane",e);let d=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(d)?L(d.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:o}=e.payload,r=I.getNode(t);if(!r)return L("Unable to locate issue",e);if(!k(r))return L("Can only reopen issues",e);let s=I.getNode(he);if(!s)return L("Unable to locate closed swimlane",e);if(n===s.id)return L("Cannot reopen issue into closed swimlane",e);if(!I.getNode(n))return L("Reopen parent no longer exists",e);let l=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(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=I.lockNode(t);return a(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[o,r]of Object.entries(n)){let s=I.getNode(o);if(!s)return L(`Unable to locate node ${o}`,e);if(s.parentNodeId!==t)return L(`Node ${o} is not child of ${t}`,e);let d=I.updateNode({...s,rank:r});if(a(d))return L(d.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:o,md:r}=e.payload,s=I.createComment({id:t,issue:n,authorId:o,authorName:I.getContributor(o)?.name??"Unknown",md:r,deleted:!1});return a(s)?L(s.message??"Unable to add comment",e):c("Comment added",{action:e.action,result:{id:t,issue:n,author:o,md:r}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:o}=e.payload,r=I.getComment(t);if(!r)return L("Unable to locate comment",e);if(r.issue!==n)return L("Comment does not belong to issue",e);let s=I.editComment(t,o);return a(s)?L(s.message??"Unable to edit comment",e):c("Comment edited",{action:e.action,result:{id:t,issue:n,md:o}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,o=I.getComment(t);if(!o)return L("Unable to locate comment",e);if(o.issue!==n)return L("Comment does not belong to issue",e);let r=I.deleteComment(t);return a(r)?L(r.message??"Unable to delete comment",e):c("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:o,ext:r,name:s,bytes:d}=e.payload,l=I.createAttachment({id:t,issue:n,hash:o,ext:r,name:s,bytes:d,deleted:!1});return a(l)?L(l.message??"Unable to add attachment",e):c("Attachment added",{action:e.action,result:{id:t,issue:n,hash:o}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,o=I.getAttachment(t);if(!o)return L("Unable to locate attachment",e);if(o.issue!==n)return L("Attachment does not belong to issue",e);let r=I.deleteAttachment(t);return a(r)?L(r.message??"Unable to delete attachment",e):c("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=I.linkUserId({contributorId:t,userId:e.userId});return a(n)?L(n.message??"Unable to link contributor",e):c("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};bt=e=>e.map(t=>Dt(t))});var oo,fs=y(()=>{"use strict";oo=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"});var jm,Wm,wa,Ma,vs=y(()=>{"use strict";jm=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","create.contributor","tombstone.contributor","restore.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","move.node","edit.description","add.issue.comment","edit.issue.comment","delete.issue.comment","add.issue.attachment","delete.issue.attachment","close.issue","reopen.issue","lock.node","rebalance.children","link.contributor.user"],Wm=new Set(jm),wa=e=>Wm.has(e),Ma=e=>({action:e.action,payload:e.payload})});import er from"node:fs";import ys from"node:path";import{decodeTime as Hm}from"ulid";import{z as hs}from"zod";function xs(e){let t=Kn(e);if(!er.existsSync(t))return c("No events found",[]);let n=er.readdirSync(t).filter(r=>r.endsWith(".jsonl")).map(r=>ys.join(t,r)),o=[];for(let r of n){let s=Qm(r);if(a(s))return i(s.message);o.push(...s.value)}return c("All events loaded",Zm(o))}function Ge(e){let t=xs(e);return a(t)?i(t.message):bs(t.value)}function Is(e,t){let n=xs(e);if(a(n))return i(n.message);let{appliedEvents:o,unappliedEvents:r}=ep(n.value,t),s=bs(o);if(a(s))return i(s.message);let d=bs(r);return a(d)?i(d.message):c("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function ka(e=process.cwd()){let t=xs(e);return a(t)?i(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Km,qm,zm,Vm,Gm,Ym,Xm,Jm,bs,Qm,Zm,ep,Xt=y(()=>{"use strict";gn();S();ue();vs();nt();Km=hs.object({userId:hs.string().min(1).default("unknown"),userName:hs.string().min(1).default("unknown")}),qm=/^[0-9a-hjkmnp-tv-z]{26}$/i,zm=e=>qm.test(e)?e.toUpperCase():e,Vm=e=>{let t=ys.basename(e,".jsonl"),n=t.indexOf("."),o=n===-1?t:t.slice(0,n),r=n===-1?void 0:t.slice(n+1),s=Km.safeParse({userId:zm(o),userName:r});return s.success?c("Parsed event file actor",s.data):i(`Invalid event file name ${ys.basename(e)}: ${s.error.issues.map(d=>d.path.join(".")||d.message).join(", ")}`)},Gm=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?i(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?i("Invalid persisted event: action key is missing or invalid"):c("Resolved persisted action",t[0])},Ym=(e,t)=>t in e,Xm=({id:e,action:t,payload:n,userId:o,userName:r})=>({id:e,action:t,payload:n,userId:o,userName:r}),Jm=e=>{let{userId:t,userName:n,...o}=e,r=Gm(o);if(a(r))return i(r.message);let s=r.value,d=e.id?.[0];return d?Ym(o,s)?c("Decoded persisted event",Xm({id:d,action:s,payload:o[s],userId:t,userName:n})):i(`Persisted event is missing payload for action: ${s}`):i("Persisted event is missing id")},bs=e=>{let t=[],n=new Map;for(let o of e){let r=Jm(o);if(a(r))return i(`Failed to decode event ${o.id?.[0]??"<unknown>"}: ${r.message}`);let s=r.value.action;if(!wa(s)){n.set(s,(n.get(s)??0)+1);continue}t.push(r.value)}if(n.size>0){let o=[...n.entries()].map(([r,s])=>`${r} (x${s})`).join(", ");ve.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${o}. Upgrade to apply them.`)}return c("Decoded reconstructed events",t)},Qm=e=>{if(!er.existsSync(e))return c("Event file missing",[]);let t=Vm(e);if(a(t))return i(t.message);let n=er.readFileSync(e,"utf8"),o=[];for(let r of n.split(`
42
- `)){let s=r.trim();if(!s)continue;let d;try{d=JSON.parse(s)}catch{return i(`Failed to parse event JSON from ${e}: ${s}`)}let l=Es(d);if(a(l))return i(`${l.message} in ${e}: ${s}`);o.push({...l.value,userId:t.value.userId,userName:t.value.userName})}return c("Parsed persisted events file",o)};Zm=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],v=m.id[1]??null;t.set(p,m);let x=n.get(v)??[];x.push(m),n.set(v,x)}for(let m of n.values())m.sort((p,v)=>p.id[0].localeCompare(v.id[0]));let o=[],r=new Set,s=m=>{let p=m.id[0];if(r.has(p))return;o.push(m),r.add(p);let v=n.get(p)??[];for(let x of v)s(x)},d=n.get(null)??[];for(let m of d)s(m);let l=e.filter(m=>{let p=m.id[0],v=m.id[1]??null;return!r.has(p)&&v!==null&&!t.has(v)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of l)s(m);let u=e.filter(m=>!r.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)s(m);return o},ep=(e,t)=>{let n=new Set,o=[],r=[];for(let s of e){let d=s.id[0],l=s.id[1],u=!1;try{u=Hm(d)<t}catch{u=!1}!u||l&&n.has(l)?(n.add(d),r.push(s)):o.push(s)}return{appliedEvents:o,unappliedEvents:r}}});import tp from"node:fs";import np from"node:path";import{decodeTime as op,monotonicFactory as rp}from"ulid";import{z as ro}from"zod";function tr({event:e,rootDir:t}){try{let n=Si(t);if(a(n))return n;let o=cp(t,{userId:e.userId,userName:e.userName});if(a(o))return o;let r=ka(t);if(a(r))return i(r.message);let s=r.value?La(Math.max(Date.now(),op(r.value)+1)):La(),d=lp(Ma(e),[s,r.value]);return a(d)?i(d.message):(tp.appendFileSync(o.value,`${JSON.stringify(d.value)}
43
- `,"utf8"),c("Event persisted",{path:o.value,entry:d.value}))}catch(n){let o=n instanceof Error?n.message:"Unknown persist error";return i(`Failed to persist event: ${o}`)}}var Pa,La,sp,ip,Es,ap,dp,ae,Jt,cp,lp,nt=y(()=>{"use strict";S();ke();ue();fs();Xt();vs();Pa=1,La=rp(),sp=ro.tuple([ro.string().min(1),ro.string().min(1).nullable()]),ip=ro.looseObject({v:ro.literal(Pa),id:sp}),Es=e=>{let t=ip.safeParse(e);return t.success?c("Parsed persisted event",t.data):i(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},ap=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),dp=e=>e.trim().length>0&&e.length<=80,ae=()=>{let{userName:e,userId:t}=ie();return e?t?ap(t)?dp(e)?c("Successfully resolved actor ID",{userId:t,userName:e}):i("Invalid user name in config"):i("Invalid user ID in config"):i("User ID not configured"):i("User name not configured")},Jt=({userId:e,userName:t})=>`${oo(e)}.${oo(t)}.jsonl`,cp=(e,{userId:t,userName:n})=>{let o=Jt({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(o))return i(`Invalid event log file name: ${o}`);let s=np.join(Kn(e),o);return c("Successfully resolved event log path",s)},lp=(e,t)=>{let n={[e.action]:e.payload,v:Pa,id:t};return Es(n)}});import{ulid as up}from"ulid";function Da(e,t){let n=Dt(e);if(n.status!==wt.Success)return n;let o=tr({event:e,rootDir:t});return a(o)?o:n}function B(e,t){if(e.length===0||!e[0])return i("No events provided");let n=mp(e[0],t);if(a(n))return n;let o=e.map(s=>Da(s,t)),r=o.filter(a);return r.length>0?i("Materialize and persist failed: "+r.map(s=>s.message).join(", ")):c("Materialization succeeded",o.map(s=>s.value))}var mp,Qt=y(()=>{"use strict";S();ce();xt();nt();mp=(e,t)=>{if(e.action==="create.contributor")return c("Contributor already being created",void 0);if(I.getContributor(e.userId))return c("Contributor exists",void 0);let n={id:up(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},o=Da(n,t);return a(o)?i(o.message):c("Contributor created",void 0)}});var Fa,nr,ne,Ba,Oa,Ft,Zt,lt=y(()=>{"use strict";ua();Qt();S();w();bn();Fa=e=>nr(ne(e),{at:"end"}),nr=(e,t={at:"end"})=>{let n=o=>a(o)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(De(void 0,void 0));switch(t.at){case"start":{let o=e[0];return o?n(De(void 0,o.rank)):i("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(De(o.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let o=Ba(e,t.sibling);if(o<0)return i("Sibling not found");let r=o>0?e[o-1]:void 0,s=e[o];return s?n(De(r?.rank,s.rank)):i("Sibling not found")}case"after":{let o=Ba(e,t.sibling);if(o<0)return i("Sibling not found");let r=e[o],s=o<e.length-1?e[o+1]:void 0;return r?n(De(r.rank,s?.rank)):i("Sibling not found")}}},ne=e=>Object.values(g().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Ba=(e,t)=>e.findIndex(n=>n.id===t),Oa=(e,t,n={at:"end"})=>nr(ne(t).filter(o=>o.id!==e),n),Ft=(e,t,n,o,r)=>{let s=Oa(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return c("Resolved rank",s.value.rank);let d=ls(e,o);if(a(d))return d;let l=B([d.value],r);if(a(l))return l;let u=Oa(t,e,n);return a(u)?u:u.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",u.value.rank)},Zt=(e,t,n)=>{let o=Fa(e);if(a(o))return o;if(!o.value.needsRebalance)return c("Resolved rank",o.value.rank);let r=ls(e,t);if(a(r))return r;let s=B([r.value],n);if(a(s))return s;let d=Fa(e);return a(d)?d:d.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",d.value.rank)}});var F,Ua,_a,We=y(()=>{"use strict";w();F={exit(){process.exit(0)},enterChildNode(){let e=g(),t=e.contextNode,n=Math.max(0,e.selectedIndex),o=J(t.id),r=o[n];r&&(t.context==="FIELD"&&o.length===0||r.context==="COMMENT"||r.context==="TEXT"||F.navigate({contextNode:r,selectedIndex:J(r.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=g();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let o=J(n.id),r=o.findIndex(({id:d})=>d===e.id),s=o.length===0?-1:r>=0?r:0;F.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Ua(1),navigateToPreviousItem:()=>Ua(-1),navigateToNextContainer:()=>_a(1),navigateToPreviousContainer:()=>_a(-1),navigate:({contextNode:e,selectedIndex:t})=>{E({contextNodeId:e.id,selectedIndex:t})}},Ua=e=>{let{selectedIndex:t,contextNode:n}=g(),o=J(n.id).length;if(o===0)return;let s=(Math.max(0,t)+e+o)%o;F.navigate({selectedIndex:s,contextNode:n})},_a=e=>{let{contextNode:t,nodes:n,selectedIndex:o}=g();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let r=n[t.parentNodeId];if(!r)return;let s=J(r.id),d=s.findIndex(x=>x.id===t.id);if(d<0)return;let l=s.at(d+e)??s.at(0);if(!l)return;let u=J(l.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,o),m),v=u.length?p:-1;F.navigate({contextNode:l,selectedIndex:v})}});var ja,Wa,pp,or,Ha,$a,gp,Ka,qa=y(()=>{"use strict";se();S();lt();w();We();ja=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Wa=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},pp=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&_e(t)&&t.childRenderAxis==="vertical"},or=(e,t)=>{let{nodes:n}=g(),o=n[e];if(!o||o.isDeleted)return!1;let r=ne(o.id);return F.navigate({contextNode:o,selectedIndex:ja(t,r.length)}),!0},Ha=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let o=n.parentNodeId;if(!o)return or(n.id,0);let r=t[o];if(!r||r.isDeleted)return!1;let d=ne(r.id).findIndex(l=>l.id===n.id);return d>=0?(F.navigate({contextNode:r,selectedIndex:d}),!0):Ha(r.id)},$a=e=>{let{nodes:t}=g(),n=e,o=new Set;for(;n&&!o.has(n);){if(o.add(n),Ha(n))return!0;n=t[n]?.parentNodeId}return!1},gp=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},Ka=e=>{let{nodes:t,rootNodeId:n}=g();if(pp(e.contextNodeId)&&or(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(gp(e.selectedNodeId)&&e.selectedNodeId&&$a(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(or(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&or(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if($a(e.contextNodeId))return c("Restored navigation to previous container or ancestor",null);let o=t[n];if(!o||o.isDeleted)return i("Unable to restore navigation");let r=ne(o.id);return F.navigate({contextNode:o,selectedIndex:ja(e.selectedIndex,r.length)}),c("Restored navigation to root",null)}});import{monotonicFactory as fp,ulid as It}from"ulid";function vp(){let e=Fe();if(a(e))return i("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)throw new Error("No workspace found in event log");let[o]=J(n.id),[r]=o?J(o.id):[];if(r){let s=t.renderedChildrenIndex?.[r.id]??[];return c("Resolved boot nav target",{contextNode:r,selectedIndex:s.length>0?0:-1})}else return o?c("Resolved boot nav target",{contextNode:o,selectedIndex:0}):n?c("Resolved boot nav target",{contextNode:n,selectedIndex:0}):c("Resolved boot nav target",{contextNode:t.nodes[t.rootNodeId],selectedIndex:0})}function hp(){let e=vp();return a(e)?e:F.navigate(e.value)}function za({userId:e,userName:t}){let n=so(),o=so(),r=so(),s=so(),d=so(),l=De(void 0,void 0);if(a(l))return l;let u=De(void 0,void 0);if(a(u))return u;let m=De(u.value,void 0);if(a(m))return m;let p=De(void 0,void 0);if(a(p))return p;let v=De(p.value,void 0);if(a(v))return v;let x=De(v.value,void 0);if(a(x))return x;let C=De(void 0,void 0);return a(C)?C:c("Created default events",[{id:It(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:It(),userId:e,userName:t,action:"add.board",payload:{id:o,name:"Default",parent:n,rank:u.value}},{id:It(),userId:e,userName:t,action:"add.swimlane",payload:{id:r,name:"Todo",parent:o,rank:p.value}},{id:It(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:o,rank:v.value}},{id:It(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:o,rank:x.value}},{id:It(),userId:e,userName:t,action:"add.board",payload:{id:Zo,name:"Closed",parent:n,rank:m.value}},{id:It(),userId:e,userName:t,action:"add.swimlane",payload:{id:he,name:"Closed",parent:Zo,rank:C.value}},{id:It(),userId:e,userName:t,action:"lock.node",payload:{id:Zo}},{id:It(),userId:e,userName:t,action:"lock.node",payload:{id:he}}])}function Cn(e){if(yp())return c("Skipped boot while checked out at a historical point",null);if(!e.length){let o=Ie.workspace("temporary-uninitialized-workspace","Workspace","a0"),r=no(o);return a(r)?r:(E({hasProjectDefinition:!1,mode:f.DEFAULT}),c("Booted uninitialized workspace placeholder",null))}if(!e.some(o=>o.action==="init.workspace"))return i("Initialized Epiq project has no workspace init event");let n=bt(e).filter(a);return n.length>0?i(`Materializing failed:
36
+ ${u.message}`):c("Configured state branch upstream",!0)},Wo=async({stateBranchRoot:e,eventFileName:t})=>{let n=ds(t),o=jo.join(e,n);if(!zt.existsSync(o))return c("No event file to stage",void 0);let r=await de.stage({cwd:e,pathspec:[n]});return a(r)?i(`Failed to stage state branch event file
37
+ ${r.message}`):c("Staged state branch event file",void 0)},Gi=async({stateBranchRoot:e})=>{let t=ji(),n=jo.join(e,t);if(!zt.existsSync(n))return c("No media directory to stage",void 0);let o=await de.stage({cwd:e,pathspec:[t]});return a(o)?i(`Failed to stage state branch media files
38
+ ${o.message}`):c("Staged state branch media files",void 0)},Yi=async({repoRoot:e,stateBranchRoot:t})=>{let n=await qu(e);return a(n)?i(`Create state branch sync commit failed
39
+ `+n.message):hn({cwd:t,message:n.value})},Jn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await ss(t);if(a(n))return i(n.message);let o=vn(e);if(a(o))return o;let r=o.value,s=n.value?await de.push({cwd:t}):await de.push({cwd:t,remote:qe,branch:r,setUpstream:!0});return a(s)?i(`Failed during state branch push
40
+ ${s.message}`):c("Pushed state branch",!0)},Xi=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let o=!1,r=vn(e);if(a(r))return r;let s=r.value,d=[$o(),await zu({repoRoot:e,stateBranchName:s}),await Xn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Yu({stateBranchRoot:t,stateBranchName:s}),await qi(t),n?await Xu({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of d){if(a(l))return i(l.message);o=o||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",o)}});import{WebSocket as Ju}from"ws";var Qu,Ji,Qi=y(()=>{"use strict";Qu=new Set,Ji=e=>{let t=JSON.stringify(e);for(let n of Qu)n.readyState===Ju.OPEN&&n.send(t)}});function ls(e){return e.context===D.WORKSPACE}function L(e){return e.context===D.TICKET}function Zi(e){return e.context===D.TEXT}function _e(e){return e.context===D.FIELD}function Qn(e){return e.context===D.FIELD_LIST}var D,Vt,Ko,Zn,se=y(()=>{"use strict";D={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};Vt=e=>e.context===D.SWIMLANE,Ko=e=>e.context===D.BOARD,Zn=e=>e.context===D.COMMENT});var f,te=y(()=>{"use strict";f={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var ea=y(()=>{"use strict";Gt()});function qo(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}var eo,ze,yn=y(()=>{"use strict";eo=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",ze=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var ta,na,oa=y(()=>{"use strict";ta=e=>{let t=new Map;for(let n of e)for(let o=1;o<=n.length;o++){let r=n.slice(0,o),s=t.get(r);s?s.push(n):t.set(r,[n])}return t},na=(e,t)=>t?e.get(t)??[]:[]});var ra,Zu,sa,ia=y(()=>{"use strict";yn();oa();ra=new WeakMap,Zu=e=>{let t=ra.get(e);return t||(t=ta(e),ra.set(e,t)),t},sa=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let o=t.toLowerCase();return na(Zu(e),o).filter(s=>qo(o,s)>=n)}});var em,aa,tm,da=y(()=>{"use strict";yn();ia();em={hint:"",hints:[],overlap:0,remainder:""},aa=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},o)=>{if(n||e==="")return em;let r=sa({wordList:o,inputToMatch:e,overlapThreshold:1});return tm(t,r)},tm=(e,t)=>{let n=t[0]??"",o=qo(e.toLowerCase(),n.toLowerCase()),[r,s]=n.split(":"),d=o<(r??"").length,l=!!s,p=(l&&d?r:n)+(l&&d?":":" "),v=p.slice(o);return{hint:p,hints:t,overlap:o,remainder:v}}});import{useSyncExternalStore as Dh}from"react";var zo,nm,om,ie,Ve,Le=y(()=>{"use strict";zo={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},nm=new Set,om=()=>{for(let e of nm)e()},ie=()=>zo,Ve=e=>(zo={...zo,...e},om(),zo)});function ca(e){return!e||!sm.test(e)?i(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function $e(e,t=bn){if(e<0n)return i("Negative rank not allowed");let n=e.toString(16);return c("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function ke(e,t){if(!e&&!t)return $e(et/2n,bn);let n=e?ca(e):c("Resolved lower bound",0n);if(a(n))return n;let o=t?ca(t):c("Resolved upper bound",et);if(a(o))return o;let r=n.value,s=o.value;if(s<=r)return $e(et/2n,bn);let d=(r+s)/2n;return d===r||d===s?i("No rank space available between neighbors"):$e(d,bn)}function la(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let o=0;o<e;o++){let r=et*BigInt(o+1)/(t+1n),s=$e(r,bn);if(a(s))return s;n.push(s.value)}return c("Resolved evenly spaced ranks",n)}var bn,rm,et,sm,xn=y(()=>{"use strict";C();bn=24n,rm=bn*4n,et=(1n<<rm)-1n,sm=/^[0-9a-f]+$/});import{ulid as im}from"ulid";var us,ua=y(()=>{"use strict";C();lt();xn();us=(e,t)=>{let n=ne(e),o=la(n.length);if(a(o))return o;let r={};for(let s=0;s<n.length;s++){let d=n[s],l=o.value[s];if(!d||!l)return i("Unable to assign rebalance rank");r[d.id]=l}return c("Created rebalance event",{id:im(),action:"rebalance.children",payload:{parent:e,ranks:r},...t})}});var Vo,je,ut=y(()=>{"use strict";C();Vo="removed",je=(e,t)=>{let n=e.find(o=>o.context===t);return n!==void 0?c("Found node",n):i("Unable to find node in breadcrumb")}});var Yt,am,Pt,I,ce=y(()=>{"use strict";ut();se();C();w();lt();Yt=(e,t)=>{let{nodes:n}=g(),o=n[e];if(!o)return i("Node not found");if(o.context===t)return c("Resolved ancestor node",o);let r=o.parentNodeId?n[o.parentNodeId]:void 0;for(;r;){if(r.context===t)return c("Resolved ancestor node",r);r=r.parentNodeId?n[r.parentNodeId]:void 0}return i(`No ancestor found for context: ${t}`)},am=(e,t)=>{let{nodes:n}=g(),o=n[e];for(;o?.parentNodeId;){if(o.parentNodeId===t)return!0;o=n[o.parentNodeId]}return!1},Pt=(e,t)=>e?e.readonly?i({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:i("Node not found"),I={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return i("Contributor not found");if(n.userId&&n.userId!==t)return i("Contributor is already linked to another user");let o={...n,userId:t},r=me(s=>({...s,contributors:{...s.contributors,[e]:o}}));return a(r)?i("Unable to link contributor to user"):c("Linked contributor to user",o)},deleteNode(e){me(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create comment, missing issue");if(!L(t))return i("Can only comment on issues");let n=me(o=>({...o,comments:{...o.comments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?i("Unable to create comment"):c("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return i("Unable to edit comment, missing comment");let o=this.getNode(n.issue);if(!o)return i("Unable to edit comment, missing issue");if(!L(o))return i("Can only edit issue comments");let r={...n,md:t,deleted:!1},s=me(d=>({...d,comments:{...d.comments??{},[e]:r}}));return a(s)?i("Unable to edit comment"):c("Edited comment",r)},deleteComment(e){let t=this.getComment(e);if(!t)return i("Unable to delete comment, missing comment");let n={...t,deleted:!0},o=me(r=>({...r,comments:{...r.comments??{},[e]:n}}));return a(o)?i("Unable to delete comment"):c("Deleted comment",n)},getComment(e){return g().comments?.[e]},getCommentsByIssue(e){return Object.values(g().comments??{}).filter(t=>t.issue===e&&!t.deleted)},createAttachment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create attachment, missing issue");if(!L(t))return i("Can only attach to issues");let n=me(o=>({...o,attachments:{...o.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?i("Unable to create attachment"):c("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return i("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},o=me(r=>({...r,attachments:{...r.attachments??{},[e]:n}}));return a(o)?i("Unable to delete attachment"):c("Deleted attachment",n)},getAttachment(e){return g().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(g().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},editValue(e,t){let{nodes:n}=g(),o=n[e];if(!o)return i("Edit target node not found");let r=Pt(o,"edit");if(r)return r;let s={...o,props:{...o.props,description:t}};return this.updateNode(s),c("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return i("Rename target node not found");let o=Pt(n,"rename");if(o)return o;let r={...n,title:t};return this.updateNode(r),c("Renamed node",r)},getExistingTags(){let{tags:e}=g();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=g();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return ne(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:o}=g(),r=this.getNode(e),s=this.getNode(t);if(!r)return i("Node not found");if(!s)return i("Target parent not found");if(o===e)return i("Cannot move root node");if(e===t)return i("Cannot move node into itself");let d=Pt(r,"move");if(d)return d;if(am(t,e))return i("Cannot move node into its own descendant");let l={...r,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:o}=g(),r=this.getNode(e);if(!r)return i("Node not found");if(o===e)return i("Cannot delete root node");let s=Pt(r,"delete");if(s)return s;let d=new Set,l=m=>{let p=t[m];if(!(!p||d.has(m))){d.add(m);for(let v of ne(p.id))l(v.id)}};l(e);let u={...structuredClone(t)};for(let m of d){if(!u[m])return i("Unable to locate node to delete");u[m]={...u[m],isDeleted:!0}}return n?(E({nodes:u}),c("Successfully tomb stoned",r)):i("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return i("Contributor not found");let n={...t,name:Vo,tombstoned:!0},o=me(r=>({...r,contributors:{...r.contributors,[e]:n}}));return a(o)?i("Unable to remove contributor"):c("Tombstoned contributor",n)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return i("Contributor not found");let o={...n,name:t,tombstoned:!1},r=me(s=>({...s,contributors:{...s.contributors,[e]:o}}));return a(r)?i("Unable to restore contributor"):c("Restored contributor",o)},createContributor(e){let t=me(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?i("Unable to create contributor"):c("Created contributor",e)},assign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return i("Unable to assign contributor, missing contributor");if(!o)return i("Unable to assign contributor, missing target");let r=Pt(o,"edit");if(r)return r;if(!L(o))return i("Target is not an issue");let s=o.props.assignees??[];if(s.includes(t))return i("Contributor already assigned");let d={...o,props:{...o.props,assignees:[...s,t]}};return this.updateNode(d),c("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return i("Unable to unassign, missing contributor");if(!o)return i("Unable to unassign, missing target");let r=Pt(o,"edit");if(r)return r;if(!L(o))return i("Target is not an issue");let s=o.props.assignees??[];if(!s.includes(t))return c("Issue is not assigned to that contributor",{assignee:t});let d={...o,props:{...o.props,assignees:s.filter(l=>l!==t)}};return this.updateNode(d),c("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),o=this.getNode(e);if(!n)return i("Unable to add tag, missing tag");if(!o)return i("Unable to add tag, missing target");let r=Pt(o,"edit");if(r)return r;if(!L(o))return i("Target is not an issue");let s=o.props.tags??[];if(s.includes(t))return i("Tag already assigned");let d={...o,props:{...o.props,tags:[...s,t]}};return this.updateNode(d),c("Tag added",{tag:t})},untag(e,t){let n=this.getTag(t),o=this.getNode(e);if(!n)return i("Unable to remove tag, missing tag");if(!o)return i("Unable to remove tag, missing target");let r=Pt(o,"edit");if(r)return r;if(!L(o))return i("Target is not an issue");let s=o.props.tags??[];if(!s.includes(t))return c("Issue is not tagged with that tag",{tag:t});let d={...o,props:{...o.props,tags:s.filter(l=>l!==t)}};return this.updateNode(d),c("Tag removed",{tag:t})},createTag(e){let t=me(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?i("Could not create tag"):c("Tag created",e)},createNode(e){let t=me(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?i("Unable to create node"):c("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return i("Failed to locate node");let n={...t,readonly:!0},o=me(r=>({...r,nodes:{...r.nodes,[e]:n}}));return a(o)?i(o.message):c("Locked node",n)},updateNode(e){let t=me(n=>({...n,nodes:{...n.nodes,[e.id]:e}}));return a(t)?t:c("Updated node",e)},getContributor(e){return g().contributors[e]},getTag(e){return g().tags[e]},getNode(e){return g().nodes[e]},getSiblings(e){return ne(e)}}});var X,In=y(()=>{"use strict";X={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var tt,ma,En=y(()=>{"use strict";tt=e=>e.slice(-7).toUpperCase(),ma=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?tt(e).includes(n):!0}});var Ie,Xt=y(()=>{"use strict";se();En();Ie={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:D.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,o,r=!1)=>({id:e,title:t,rank:o,isDeleted:!1,props:{ref:tt(e)},context:D.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:D.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:o,props:r={},childRenderAxis:s="horizontal",isVirtual:d=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:D.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:d}),fieldList:({id:e,name:t,parentNodeId:n,rank:o,childRenderAxis:r="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:D.FIELD_LIST,childRenderAxis:r,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{ref:tt(e)},context:D.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!0,isVirtual:s=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:D.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:r,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:o,props:r={},readonly:s=!0,isVirtual:d=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:D.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:d})}});var Ae,R,Pe=y(()=>{"use strict";Ae={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},R={accent:Ae.cyan,accent2:Ae.magenta,primary:Ae.white,secondary:Ae.grayDark,secondary2:Ae.grayLight,gray:Ae.gray,green:Ae.green,yellow:Ae.yellow,red:Ae.red}});var N,Nn,Go=y(()=>{"use strict";Pe();N={red:Ae.red,yellow:Ae.yellow,green:Ae.green,blue:Ae.blue,magenta:Ae.magenta,cyan:Ae.cyan},Nn={urgent:N.red,critical:N.red,important:N.red,blocker:N.red,asap:N.red,immediate:N.red,fail:N.red,failure:N.red,broken:N.red,bug:N.red,error:N.red,incident:N.red,outage:N.red,production:N.red,crash:N.red,security:N.red,warning:N.yellow,warn:N.yellow,risky:N.yellow,risk:N.yellow,attention:N.yellow,pending:N.yellow,review:N.yellow,"needs-review":N.yellow,qa:N.yellow,testing:N.yellow,test:N.yellow,validate:N.yellow,verification:N.yellow,staging:N.yellow,check:N.yellow,"follow-up":N.yellow,followup:N.yellow,waiting:N.yellow,blocked:N.yellow,hold:N.yellow,done:N.green,complete:N.green,completed:N.green,success:N.green,ok:N.green,stable:N.green,resolved:N.green,fixed:N.green,closed:N.green,merged:N.green,released:N.green,deployed:N.green,approved:N.green,verified:N.green,working:N.green,healthy:N.green,pass:N.green,passing:N.green,info:N.blue,information:N.blue,note:N.blue,docs:N.blue,documentation:N.blue,doc:N.blue,guide:N.blue,help:N.blue,explanation:N.blue,detail:N.blue,details:N.blue,context:N.blue,design:N.blue,discussion:N.blue,proposal:N.blue,idea:N.blue,feature:N.magenta,enhancement:N.magenta,improvement:N.magenta,refactor:N.magenta,refactoring:N.magenta,cleanup:N.magenta,optimize:N.magenta,optimization:N.magenta,perf:N.magenta,performance:N.magenta,upgrade:N.magenta,migration:N.magenta,modernize:N.magenta,debt:N.magenta,todo:N.cyan,next:N.cyan,planned:N.cyan,plan:N.cyan,future:N.cyan,backlog:N.cyan,investigate:N.cyan,explore:N.cyan,prototype:N.cyan}});import pa from"chalk";var ps,ga,ms,fa,dm,cm,va,lm,um,to,De,ha,ya,Yo,mm,pm,Xo,yt=y(()=>{"use strict";Go();ps={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ga=(e,t,n)=>Math.max(t,Math.min(n,e)),ms=(e,t,n)=>e+(t-e)*n,fa=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},dm=e=>e.toLowerCase().trim(),cm=(e,t,n)=>{let o=t/100,r=n/100,s=(1-Math.abs(2*r-1))*o,d=e/60,l=s*(1-Math.abs(d%2-1)),u=0,m=0,p=0;d>=0&&d<1?(u=s,m=l):d>=1&&d<2?(u=l,m=s):d>=2&&d<3?(m=s,p=l):d>=3&&d<4?(m=l,p=s):d>=4&&d<5?(u=l,p=s):(u=s,p=l);let v=r-s/2;return[Math.round((u+v)*255),Math.round((m+v)*255),Math.round((p+v)*255)]},va=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,lm=(e,t,n)=>{let o=ga(n,0,1);return[Math.round(ms(e[0],t[0],o)),Math.round(ms(e[1],t[1],o)),Math.round(ms(e[2],t[2],o))]},um=(e,t,n)=>lm(e,t,n),to=e=>{let n=fa(e)%360,o=cm(n,ps.stringColor.saturation,ps.stringColor.lightness);return va(o)},De=(e,t=Nn)=>{let n=dm(e);return n&&t[n]?t[n]:to(n)},ha=e=>{let t=ps.gradient.stops,n=ga(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let o=t.length-1,r=n*o,s=Math.min(Math.floor(r),o-1),d=r-s;return um(t[s],t[s+1],d)},ya=e=>va(ha(e)),Yo=e=>fa(e.toLowerCase().trim())/4294967295,mm=e=>{let t=Yo(e);return ha(t)},pm=e=>{let[t,n,o]=mm(e);return{normal:r=>pa.bgRgb(t,n,o).black(r),cursor:r=>pa.bgRgb(t,n,o).white.bold(r)}},Xo=e=>pm(e).normal(` ${e} `)});var Rn,Jo=y(()=>{"use strict";Rn=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:o,ms:r}of n){let s=Math.floor(t/r);if(s>=1)return`${s}${o} ago`}return"just now"}});import Dt from"chalk";import ba from"string-width";import{decodeTime as gm}from"ulid";var fm,vm,xa,hm,ym,Ia,Ea,bm,xm,Im,Em,Nm,Na,Ra,gs=y(()=>{"use strict";ce();w();yt();Jo();fm=(e,t)=>e+" ".repeat(Math.max(0,t-ba(e))),vm=(e,t)=>" ".repeat(Math.max(0,t-ba(e)))+e,xa=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),hm=(e,t)=>t?e<t?"up":e>t?"down":null:null,ym=(e,t)=>{let n=I.getNode(e.payload.parent),o=n?Dt.dim.bgBlack(` ${n.title} `):"unknown",r=t.at(-1);if(r&&"parent"in r&&"rank"in r&&r.parent===e.payload.parent){let s=hm(e.payload.rank,r.rank);if(s)return`Moved ${s} in ${o}`}return`Moved issue to ${o}`},Ia=e=>`${Math.max(1,Math.round(e/1024))} KB`,Ea=e=>I.getAttachment(e)?.name??"",bm=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Dt.bgHex(De(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Dt.bgHex(De(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Dt.hex(De(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Dt.hex(De(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Dt.dim(`(${Ia(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Ea(e.payload.id);return t?`"${t}"`:""}default:return""}},xm=e=>{let t=Rn(gm(e));return Dt.gray(vm(t,8))},Im=12,Em=e=>fm(`${e}`,Im),Nm=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?t.name:""}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}"`:"";case"move.node":{let t=I.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Ia(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Ea(e.payload.id);return t?`"${t}"`:""}default:return""}},Na=e=>[xa(e.action),Nm(e)].filter(Boolean).join(" "),Ra=(e,t)=>{let n=xm(e.id),o=Em(e.userName),r=Dt.dim("\u203A"),s=e.action==="move.node"?ym(e,t):[xa(e.action),bm(e)].filter(Boolean).join(" ");return`${o} ${n} ${r} ${s}`}});import{createHash as Rm}from"node:crypto";var Cm,Sm,Ee,Cn=y(()=>{"use strict";Cm="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Sm=e=>{let t=Rm("sha256").update(e).digest(),n=0n;for(let r=0;r<16;r++)n=n<<8n|BigInt(t[r]);let o="";for(let r=0;r<26;r++){let s=BigInt((25-r)*5);o+=Cm[Number(n>>s&31n)]}return o},Ee=(e,t)=>Sm(`${e}:virtual:${t}`)});var Am,Tm,wm,Mm,Lm,km,Qo,Ca,Sa,Pm,Aa=y(()=>{"use strict";gs();se();C();In();ce();Xt();w();xn();Cn();Am=e=>Ee(e,"comments"),Tm=e=>Ee(e,"description"),wm=e=>Ee(e,"assignees"),Mm=e=>Ee(e,"tags"),Lm=e=>Ee(e,"history"),km=e=>Ee(e,"attachments"),Qo=({id:e,name:t,parentNodeId:n,rank:o,value:r,readonly:s=!1,childRenderAxis:d="horizontal"})=>{let l=I.getNode(e);if(!l){let p=I.createNode({...Ie.field({id:e,name:t,parentNodeId:n,rank:o,props:{value:r},isVirtual:!0}),readonly:s,childRenderAxis:d});return a(p)?p:c("Virtual field created",void 0)}if(!_e(l))return i(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==o||l.props.value!==r||l.readonly!==s||l.childRenderAxis!==d))return c("Virtual field unchanged",void 0);let m=I.updateNode({...l,title:t,parentNodeId:n,rank:o,props:{...l.props,value:r},readonly:s,childRenderAxis:d});return a(m)?m:c("Virtual field updated",void 0)},Ca=({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!1,childRenderAxis:s="horizontal"})=>{let d=I.getNode(e);if(!d){let m=I.createNode({...Ie.fieldList({id:e,name:t,parentNodeId:n,rank:o,isVirtual:!0}),readonly:r,childRenderAxis:s});return a(m)?m:c("Virtual field list created",void 0)}if(!Qn(d))return i(`Existing virtual node ${e} is not a field list`);if(!(d.title!==t||d.parentNodeId!==n||d.rank!==o||d.readonly!==r||d.childRenderAxis!==s))return c("Virtual field list unchanged",void 0);let u=I.updateNode({...d,title:t,parentNodeId:n,rank:o,readonly:r,childRenderAxis:s});return a(u)?u:c("Virtual field list updated",void 0)},Sa=e=>{let t=$e(et/4n),n=$e(et/2n),o=$e(et*3n/4n),r=$e(et*7n/8n),s=$e(et*15n/16n),d=$e(et*13n/16n);if(a(t))return t;if(a(n))return n;if(a(o))return o;if(a(r))return r;if(a(s))return s;if(a(d))return d;let l=Qo({id:Tm(e.id),name:X.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(l))return l;let u=Ca({id:wm(e.id),name:X.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(u))return u;let m=Ca({id:Mm(e.id),name:X.TAGS,parentNodeId:e.id,rank:o.value,readonly:!0});if(a(m))return m;let p=Qo({id:Am(e.id),name:X.COMMENTS,parentNodeId:e.id,rank:r.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(p))return p;let v=Qo({id:km(e.id),name:X.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(v))return v;let x=Qo({id:Lm(e.id),name:X.HISTORY,parentNodeId:e.id,rank:d.value,value:Pm(e),readonly:!0,childRenderAxis:"vertical"});return a(x)?x:c("Ticket virtual nodes materialized",void 0)},Pm=e=>{let t=[...e.log].reverse(),n=new Map;for(let o of t){let r=n.get(o.action)??[];r.push(o.payload),n.set(o.action,r)}return t.map(o=>Ra(o,n.get(o.action)??[])).join(`
41
+ `)}});var Dm,he,Zo,Sn=y(()=>{"use strict";Dm=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[he,Zo]=Dm});function Ft(e,t=!1){let n=jm[e.action];if(!n)return i(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);let o=n(e);if(a(o))return o;let r=$m(e,t);return r||o}var k,Ta,Fm,Bm,Om,fs,Um,_m,$m,jm,bt,xt=y(()=>{"use strict";se();C();In();ce();Xt();w();Aa();Sn();k=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Ta=e=>{let t=I.getNode(e);if(!t||!L(t)||t.isDeleted)return null;let n=Sa(t);return a(n)?n:null},Fm=e=>{for(let t of e){let n=Ta(t);if(n)return n;let o=g().nodes[t]?.parentNodeId;if(!o)continue;let r=Ta(o);if(r)return r}return null},Bm=(e,t)=>{let n=I.getNode(e);n&&I.updateNode({...n,log:[...n.log??[],t]})},Om=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},fs=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":case"add.issue.attachment":case"delete.issue.attachment":return[e.payload.issue];case"delete.node":case"edit.description":return Om(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"create.contributor":case"link.contributor.user":default:return[]}},Um=e=>{me(t=>({...t,eventLog:[...t.eventLog,e]}))},_m=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?k("Invalid user ID format",e):c("Valid user",null)},$m=(e,t)=>{let n=_m(e);if(a(n))return n;let o=[...new Set(fs(e))];t||(o.forEach(s=>Bm(s,e)),Um(e));let r=Fm(o);return r||null},jm={"init.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=Ie.workspace(t,n,o),s=no(r);if(a(s))return k(s.message,e);let d=I.createNode(r);return a(d)?k(d.message??"Failed to initialize workspace",e):ls(d.value)?c("Workspace initialized",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=I.createNode(Ie.workspace(t,n,o));return a(r)?k(r.message??"Failed to add workspace",e):ls(r.value)?c("Added workspace",{action:e.action,result:r.value}):i("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=I.createNode(Ie.board(t,n,o,r));return a(s)?k(s.message??"Unable to create board",e):Ko(s.value)?c("Added board",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=I.createNode(Ie.swimlane(t,n,o,r));return a(s)?k(s.message??"Unable to create swimlane",e):Vt(s.value)?c("Added swimlane",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=I.createNode(Ie.ticket(t,n,o,r));return a(s)?k(s.message??"Unable to create issue",e):L(s.value)?c("Added issue",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:o,val:r,rank:s}=e.payload,d=I.createNode(Ie.field({id:t,name:n,parentNodeId:o,rank:s,props:{value:r},childRenderAxis:n.includes(X.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?k(d.message??`Unable to create field: ${n}`,e):_e(d.value)?c("Added field",{action:e.action,result:d.value}):i("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!I.getNode(t))return k(`Unable to locate node with id ${t}`,e);let r=I.renameNode(t,n);return a(r)?k(r.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:r.value})},"delete.node":e=>{let{id:t}=e.payload,n=I.tombstoneNode(t);return a(n)?k(n.message??"Unable to delete node",e):c("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,o=I.createTag({id:t,name:n});return a(o)?k(o.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:o.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,o=I.createContributor({id:t,name:n});return a(o)?k(o.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:o.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=I.tombstoneContributor(t);return a(n)?k(n.message??"Unable to remove contributor",e):c("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,o=I.restoreContributor(t,n);return a(o)?k(o.message??"Unable to restore contributor",e):c("Contributor restored",{action:e.action,result:o.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,o=I.tag(t,n);return a(o)?k(o.message??"Unable to tag issue",e):c("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,o=I.untag(t,n);return a(o)?k(o.message??"Unable to untag issue",e):c("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,o=I.assign(t,n);return a(o)?k(o.message??"Unable to assign issue",e):c("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,o=I.unassign(t,n);return a(o)?k(o.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:o}=e.payload,r=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(r)?k(r.message??"Failed to move node",e):c("Moved node",{action:e.action,result:r.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,o=I.editValue(t,n);return a(o)?k(o.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:o.value})},"close.issue":e=>{let{id:t,parent:n,rank:o}=e.payload,r=I.getNode(t);if(!r)return k("Unable to locate issue",e);if(!L(r))return k("Can only close issues",e);let s=I.getNode(he);if(!s)return k("Unable to locate target swimlane",e);if(n!==s.id)return k("Close target must be closed swimlane",e);let d=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(d)?k(d.message??"Unable to close issue",e):c("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:o}=e.payload,r=I.getNode(t);if(!r)return k("Unable to locate issue",e);if(!L(r))return k("Can only reopen issues",e);let s=I.getNode(he);if(!s)return k("Unable to locate closed swimlane",e);if(n===s.id)return k("Cannot reopen issue into closed swimlane",e);if(!I.getNode(n))return k("Reopen parent no longer exists",e);let l=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(l)?k(l.message??"Unable to reopen issue",e):c("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=I.lockNode(t);return a(n)?k(n.message??"Unable to lock node",e):c("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[o,r]of Object.entries(n)){let s=I.getNode(o);if(!s)return k(`Unable to locate node ${o}`,e);if(s.parentNodeId!==t)return k(`Node ${o} is not child of ${t}`,e);let d=I.updateNode({...s,rank:r});if(a(d))return k(d.message??"Unable to rebalance child",e)}return c("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:o,md:r}=e.payload,s=I.createComment({id:t,issue:n,authorId:o,authorName:I.getContributor(o)?.name??"Unknown",md:r,deleted:!1});return a(s)?k(s.message??"Unable to add comment",e):c("Comment added",{action:e.action,result:{id:t,issue:n,author:o,md:r}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:o}=e.payload,r=I.getComment(t);if(!r)return k("Unable to locate comment",e);if(r.issue!==n)return k("Comment does not belong to issue",e);let s=I.editComment(t,o);return a(s)?k(s.message??"Unable to edit comment",e):c("Comment edited",{action:e.action,result:{id:t,issue:n,md:o}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,o=I.getComment(t);if(!o)return k("Unable to locate comment",e);if(o.issue!==n)return k("Comment does not belong to issue",e);let r=I.deleteComment(t);return a(r)?k(r.message??"Unable to delete comment",e):c("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:o,ext:r,name:s,bytes:d}=e.payload,l=I.createAttachment({id:t,issue:n,hash:o,ext:r,name:s,bytes:d,deleted:!1});return a(l)?k(l.message??"Unable to add attachment",e):c("Attachment added",{action:e.action,result:{id:t,issue:n,hash:o}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,o=I.getAttachment(t);if(!o)return k("Unable to locate attachment",e);if(o.issue!==n)return k("Attachment does not belong to issue",e);let r=I.deleteAttachment(t);return a(r)?k(r.message??"Unable to delete attachment",e):c("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=I.linkUserId({contributorId:t,userId:e.userId});return a(n)?k(n.message??"Unable to link contributor",e):c("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};bt=e=>e.map(t=>Ft(t))});var oo,vs=y(()=>{"use strict";oo=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"});var Wm,Hm,wa,Ma,hs=y(()=>{"use strict";Wm=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","create.contributor","tombstone.contributor","restore.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","move.node","edit.description","add.issue.comment","edit.issue.comment","delete.issue.comment","add.issue.attachment","delete.issue.attachment","close.issue","reopen.issue","lock.node","rebalance.children","link.contributor.user"],Hm=new Set(Wm),wa=e=>Hm.has(e),Ma=e=>({action:e.action,payload:e.payload})});import er from"node:fs";import bs from"node:path";import{decodeTime as Km}from"ulid";import{z as ys}from"zod";function Is(e){let t=Kn(e);if(!er.existsSync(t))return c("No events found",[]);let n=er.readdirSync(t).filter(r=>r.endsWith(".jsonl")).map(r=>bs.join(t,r)),o=[];for(let r of n){let s=Zm(r);if(a(s))return i(s.message);o.push(...s.value)}return c("All events loaded",ep(o))}function Ge(e){let t=Is(e);return a(t)?i(t.message):xs(t.value)}function Es(e,t){let n=Is(e);if(a(n))return i(n.message);let{appliedEvents:o,unappliedEvents:r}=tp(n.value,t),s=xs(o);if(a(s))return i(s.message);let d=xs(r);return a(d)?i(d.message):c("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function La(e=process.cwd()){let t=Is(e);return a(t)?i(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var qm,zm,Vm,Gm,Ym,Xm,Jm,Qm,xs,Zm,ep,tp,Jt=y(()=>{"use strict";fn();C();ue();hs();nt();qm=ys.object({userId:ys.string().min(1).default("unknown"),userName:ys.string().min(1).default("unknown")}),zm=/^[0-9a-hjkmnp-tv-z]{26}$/i,Vm=e=>zm.test(e)?e.toUpperCase():e,Gm=e=>{let t=bs.basename(e,".jsonl"),n=t.indexOf("."),o=n===-1?t:t.slice(0,n),r=n===-1?void 0:t.slice(n+1),s=qm.safeParse({userId:Vm(o),userName:r});return s.success?c("Parsed event file actor",s.data):i(`Invalid event file name ${bs.basename(e)}: ${s.error.issues.map(d=>d.path.join(".")||d.message).join(", ")}`)},Ym=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?i(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?i("Invalid persisted event: action key is missing or invalid"):c("Resolved persisted action",t[0])},Xm=(e,t)=>t in e,Jm=({id:e,action:t,payload:n,userId:o,userName:r})=>({id:e,action:t,payload:n,userId:o,userName:r}),Qm=e=>{let{userId:t,userName:n,...o}=e,r=Ym(o);if(a(r))return i(r.message);let s=r.value,d=e.id?.[0];return d?Xm(o,s)?c("Decoded persisted event",Jm({id:d,action:s,payload:o[s],userId:t,userName:n})):i(`Persisted event is missing payload for action: ${s}`):i("Persisted event is missing id")},xs=e=>{let t=[],n=new Map;for(let o of e){let r=Qm(o);if(a(r))return i(`Failed to decode event ${o.id?.[0]??"<unknown>"}: ${r.message}`);let s=r.value.action;if(!wa(s)){n.set(s,(n.get(s)??0)+1);continue}t.push(r.value)}if(n.size>0){let o=[...n.entries()].map(([r,s])=>`${r} (x${s})`).join(", ");ve.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${o}. Upgrade to apply them.`)}return c("Decoded reconstructed events",t)},Zm=e=>{if(!er.existsSync(e))return c("Event file missing",[]);let t=Gm(e);if(a(t))return i(t.message);let n=er.readFileSync(e,"utf8"),o=[];for(let r of n.split(`
42
+ `)){let s=r.trim();if(!s)continue;let d;try{d=JSON.parse(s)}catch{return i(`Failed to parse event JSON from ${e}: ${s}`)}let l=Ns(d);if(a(l))return i(`${l.message} in ${e}: ${s}`);o.push({...l.value,userId:t.value.userId,userName:t.value.userName})}return c("Parsed persisted events file",o)};ep=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],v=m.id[1]??null;t.set(p,m);let x=n.get(v)??[];x.push(m),n.set(v,x)}for(let m of n.values())m.sort((p,v)=>p.id[0].localeCompare(v.id[0]));let o=[],r=new Set,s=m=>{let p=m.id[0];if(r.has(p))return;o.push(m),r.add(p);let v=n.get(p)??[];for(let x of v)s(x)},d=n.get(null)??[];for(let m of d)s(m);let l=e.filter(m=>{let p=m.id[0],v=m.id[1]??null;return!r.has(p)&&v!==null&&!t.has(v)}).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of l)s(m);let u=e.filter(m=>!r.has(m.id[0])).sort((m,p)=>m.id[0].localeCompare(p.id[0]));for(let m of u)s(m);return o},tp=(e,t)=>{let n=new Set,o=[],r=[];for(let s of e){let d=s.id[0],l=s.id[1],u=!1;try{u=Km(d)<t}catch{u=!1}!u||l&&n.has(l)?(n.add(d),r.push(s)):o.push(s)}return{appliedEvents:o,unappliedEvents:r}}});import np from"node:fs";import op from"node:path";import{decodeTime as rp,monotonicFactory as sp}from"ulid";import{z as ro}from"zod";function tr({event:e,rootDir:t}){try{let n=Ci(t);if(a(n))return n;let o=lp(t,{userId:e.userId,userName:e.userName});if(a(o))return o;let r=La(t);if(a(r))return i(r.message);let s=r.value?ka(Math.max(Date.now(),rp(r.value)+1)):ka(),d=up(Ma(e),[s,r.value]);return a(d)?i(d.message):(np.appendFileSync(o.value,`${JSON.stringify(d.value)}
43
+ `,"utf8"),c("Event persisted",{path:o.value,entry:d.value}))}catch(n){let o=n instanceof Error?n.message:"Unknown persist error";return i(`Failed to persist event: ${o}`)}}var Pa,ka,ip,ap,Ns,dp,cp,ae,Qt,lp,up,nt=y(()=>{"use strict";C();Le();ue();vs();Jt();hs();Pa=1,ka=sp(),ip=ro.tuple([ro.string().min(1),ro.string().min(1).nullable()]),ap=ro.looseObject({v:ro.literal(Pa),id:ip}),Ns=e=>{let t=ap.safeParse(e);return t.success?c("Parsed persisted event",t.data):i(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},dp=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),cp=e=>e.trim().length>0&&e.length<=80,ae=()=>{let{userName:e,userId:t}=ie();return e?t?dp(t)?cp(e)?c("Successfully resolved actor ID",{userId:t,userName:e}):i("Invalid user name in config"):i("Invalid user ID in config"):i("User ID not configured"):i("User name not configured")},Qt=({userId:e,userName:t})=>`${oo(e)}.${oo(t)}.jsonl`,lp=(e,{userId:t,userName:n})=>{let o=Qt({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(o))return i(`Invalid event log file name: ${o}`);let s=op.join(Kn(e),o);return c("Successfully resolved event log path",s)},up=(e,t)=>{let n={[e.action]:e.payload,v:Pa,id:t};return Ns(n)}});import{ulid as mp}from"ulid";function Da(e,t){let n=Ft(e);if(n.status!==Mt.Success)return n;let o=tr({event:e,rootDir:t});return a(o)?o:n}function B(e,t){if(e.length===0||!e[0])return i("No events provided");let n=pp(e[0],t);if(a(n))return n;let o=e.map(s=>Da(s,t)),r=o.filter(a);return r.length>0?i("Materialize and persist failed: "+r.map(s=>s.message).join(", ")):c("Materialization succeeded",o.map(s=>s.value))}var pp,Zt=y(()=>{"use strict";C();ce();xt();nt();pp=(e,t)=>{if(e.action==="create.contributor")return c("Contributor already being created",void 0);if(I.getContributor(e.userId))return c("Contributor exists",void 0);let n={id:mp(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},o=Da(n,t);return a(o)?i(o.message):c("Contributor created",void 0)}});var Fa,nr,ne,Ba,Oa,Bt,en,lt=y(()=>{"use strict";ua();Zt();C();w();xn();Fa=e=>nr(ne(e),{at:"end"}),nr=(e,t={at:"end"})=>{let n=r=>a(r)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(ke(void 0,void 0));let o=()=>n(ke(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let r=e[0];return r?n(ke(void 0,r.rank)):i("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(ke(r.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let r=Ba(e,t.sibling),s=r<0?void 0:e[r];if(!s)return o();let d=r>0?e[r-1]:void 0;return n(ke(d?.rank,s.rank))}case"after":{let r=Ba(e,t.sibling),s=r<0?void 0:e[r];if(!s)return o();let d=r<e.length-1?e[r+1]:void 0;return n(ke(s.rank,d?.rank))}}},ne=e=>Object.values(g().nodes).filter(t=>!!t&&!t.isDeleted&&t.parentNodeId===e).sort((t,n)=>t.rank.localeCompare(n.rank)),Ba=(e,t)=>e.findIndex(n=>n.id===t),Oa=(e,t,n={at:"end"})=>nr(ne(t).filter(o=>o.id!==e),n),Bt=(e,t,n,o,r)=>{let s=Oa(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return c("Resolved rank",s.value.rank);let d=us(e,o);if(a(d))return d;let l=B([d.value],r);if(a(l))return l;let u=Oa(t,e,n);return a(u)?u:u.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",u.value.rank)},en=(e,t,n)=>{let o=Fa(e);if(a(o))return o;if(!o.value.needsRebalance)return c("Resolved rank",o.value.rank);let r=us(e,t);if(a(r))return r;let s=B([r.value],n);if(a(s))return s;let d=Fa(e);return a(d)?d:d.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",d.value.rank)}});var F,Ua,_a,We=y(()=>{"use strict";w();F={exit(){process.exit(0)},enterChildNode(){let e=g(),t=e.contextNode,n=Math.max(0,e.selectedIndex),o=J(t.id),r=o[n];r&&(t.context==="FIELD"&&o.length===0||r.context==="COMMENT"||r.context==="TEXT"||F.navigate({contextNode:r,selectedIndex:J(r.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=g();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let o=J(n.id),r=o.findIndex(({id:d})=>d===e.id),s=o.length===0?-1:r>=0?r:0;F.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Ua(1),navigateToPreviousItem:()=>Ua(-1),navigateToNextContainer:()=>_a(1),navigateToPreviousContainer:()=>_a(-1),navigate:({contextNode:e,selectedIndex:t})=>{E({contextNodeId:e.id,selectedIndex:t})}},Ua=e=>{let{selectedIndex:t,contextNode:n}=g(),o=J(n.id).length;if(o===0)return;let s=(Math.max(0,t)+e+o)%o;F.navigate({selectedIndex:s,contextNode:n})},_a=e=>{let{contextNode:t,nodes:n,selectedIndex:o}=g();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let r=n[t.parentNodeId];if(!r)return;let s=J(r.id),d=s.findIndex(x=>x.id===t.id);if(d<0)return;let l=s.at(d+e)??s.at(0);if(!l)return;let u=J(l.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,o),m),v=u.length?p:-1;F.navigate({contextNode:l,selectedIndex:v})}});var ja,Wa,gp,or,Ha,$a,fp,Ka,qa=y(()=>{"use strict";se();C();lt();w();We();ja=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Wa=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},gp=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&_e(t)&&t.childRenderAxis==="vertical"},or=(e,t)=>{let{nodes:n}=g(),o=n[e];if(!o||o.isDeleted)return!1;let r=ne(o.id);return F.navigate({contextNode:o,selectedIndex:ja(t,r.length)}),!0},Ha=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let o=n.parentNodeId;if(!o)return or(n.id,0);let r=t[o];if(!r||r.isDeleted)return!1;let d=ne(r.id).findIndex(l=>l.id===n.id);return d>=0?(F.navigate({contextNode:r,selectedIndex:d}),!0):Ha(r.id)},$a=e=>{let{nodes:t}=g(),n=e,o=new Set;for(;n&&!o.has(n);){if(o.add(n),Ha(n))return!0;n=t[n]?.parentNodeId}return!1},fp=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},Ka=e=>{let{nodes:t,rootNodeId:n}=g();if(gp(e.contextNodeId)&&or(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(fp(e.selectedNodeId)&&e.selectedNodeId&&$a(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(or(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&or(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if($a(e.contextNodeId))return c("Restored navigation to previous container or ancestor",null);let o=t[n];if(!o||o.isDeleted)return i("Unable to restore navigation");let r=ne(o.id);return F.navigate({contextNode:o,selectedIndex:ja(e.selectedIndex,r.length)}),c("Restored navigation to root",null)}});import{monotonicFactory as vp,ulid as It}from"ulid";function hp(){let e=Fe();if(a(e))return i("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)throw new Error("No workspace found in event log");let[o]=J(n.id),[r]=o?J(o.id):[];if(r){let s=t.renderedChildrenIndex?.[r.id]??[];return c("Resolved boot nav target",{contextNode:r,selectedIndex:s.length>0?0:-1})}else return o?c("Resolved boot nav target",{contextNode:o,selectedIndex:0}):n?c("Resolved boot nav target",{contextNode:n,selectedIndex:0}):c("Resolved boot nav target",{contextNode:t.nodes[t.rootNodeId],selectedIndex:0})}function yp(){let e=hp();return a(e)?e:F.navigate(e.value)}function za({userId:e,userName:t}){let n=so(),o=so(),r=so(),s=so(),d=so(),l=ke(void 0,void 0);if(a(l))return l;let u=ke(void 0,void 0);if(a(u))return u;let m=ke(u.value,void 0);if(a(m))return m;let p=ke(void 0,void 0);if(a(p))return p;let v=ke(p.value,void 0);if(a(v))return v;let x=ke(v.value,void 0);if(a(x))return x;let S=ke(void 0,void 0);return a(S)?S:c("Created default events",[{id:It(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:It(),userId:e,userName:t,action:"add.board",payload:{id:o,name:"Default",parent:n,rank:u.value}},{id:It(),userId:e,userName:t,action:"add.swimlane",payload:{id:r,name:"Todo",parent:o,rank:p.value}},{id:It(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:o,rank:v.value}},{id:It(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:o,rank:x.value}},{id:It(),userId:e,userName:t,action:"add.board",payload:{id:Zo,name:"Closed",parent:n,rank:m.value}},{id:It(),userId:e,userName:t,action:"add.swimlane",payload:{id:he,name:"Closed",parent:Zo,rank:S.value}},{id:It(),userId:e,userName:t,action:"lock.node",payload:{id:Zo}},{id:It(),userId:e,userName:t,action:"lock.node",payload:{id:he}}])}function An(e){if(bp())return c("Skipped boot while checked out at a historical point",null);if(!e.length){let o=Ie.workspace("temporary-uninitialized-workspace","Workspace","a0"),r=no(o);return a(r)?r:(E({hasProjectDefinition:!1,mode:f.DEFAULT}),c("Booted uninitialized workspace placeholder",null))}if(!e.some(o=>o.action==="init.workspace"))return i("Initialized Epiq project has no workspace init event");let n=bt(e).filter(a);return n.length>0?i(`Materializing failed:
44
44
  ${n.map(o=>o.message).join(`
45
- `)}`):(hp(),E({hasProjectDefinition:!0}),c("State booted successfully",null))}var so,yp,rr=y(()=>{"use strict";We();te();S();Yt();w();bn();xt();Sn();so=fp();yp=()=>{let e=Fe();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"}});var G,Ns=y(()=>{"use strict";S();G=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});var mt,sr,bp,Va,Rs=y(()=>{"use strict";qa();rr();Xt();nt();te();S();w();ir();Ns();Ss();mt=null,sr=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!mt,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),mt)return logger.debug("[sync] syncAndReloadState joining existing promise"),mt;logger.debug("[sync] syncAndReloadState creating promise"),mt=bp();try{let e=await mt;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:g().syncStatus?.status,statusMessageAfterResolve:g().syncStatus?.msg}),a(e)&&g().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),E({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),mt||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),mt=null}},bp=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=Va();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(mt)return mt;logger.debug("[sync] syncAndReloadState:start");let t=G("resolveActorId",ae());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),i("Unable to resolve event log path");E({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:g().syncStatus});let n=Jt(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let o=G("syncEpiqWithRemote",await ar({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(o),message:(a(o),o.message)}),a(o))return logger.error("[sync] syncAndReloadState:sync failed",o.message),E({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),Ye(`Unable to sync state. ${o.message}`);let{stateBranchRoot:r}=o.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:r});let s=G("loadMergedEvents",Ge(r));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(s),message:(a(s),s.message),count:a(s)?void 0:s.value.length}),a(s))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:g().syncStatus}),i(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let d=Va();if(d)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:d.message,syncStatus:g().syncStatus}),d;let l=Wa(),u=g().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:l,selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id,selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual}),!g().selectedNode?.isVirtual&&!g().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let p=G("bootStateFromEventLog",Cn(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(p),message:(a(p),p.message)}),a(p))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:g().syncStatus}),i(`Unable to boot synced state. ${p.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),E({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=G("restoreNavigationAnchor",Ka(l));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(m),message:a(m)?m.message:"Navigation restored",selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id}),a(m)?(E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),m):(E({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),c("Synced",!0))},Va=()=>g().mode===f.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),E({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),i("Will not re-materialize if not in default mode, to not lose edit data"))});var An,Ga,Ya,Cs,As,io,Ts,xp,Xa,Ip,Ja,dr=y(()=>{"use strict";S();ke();w();Rs();An=3e3,Ga=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<An?null:t},Ya=0,As=!1,io=!1,Ts=()=>{if(As)return!0;let e=Fe();return a(e)?!1:e.value.syncStatus.status==="syncing"},xp=()=>{let e=ie().autoSyncIntervalMs??1e4,t=Date.now()-Ya;return Math.max(0,e-t)},Xa=()=>{Cs||(Cs=setTimeout(async()=>{if(Cs=void 0,!!en()){if(Ts()){io=!0;return}io=!1,await Ip()}},xp()))},Ip=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return i("Cannot auto-sync while peeking");if(!en())return i("Cannot auto-sync before state is initialized");if(Ts())return io=!0,i("Sync already in progress");As=!0,Ya=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await sr()}finally{As=!1,io&&Xa()}},Ja=()=>{en()&&(io=!0,!Ts()&&Xa())}});var cr,Qa,Za,ed,ao=y(()=>{"use strict";S();Mt();ke();ue();cr=()=>{let e=ie(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),o=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&o,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:o}},Qa=()=>{let e=Ze(process.cwd());if(a(e))return!1;let t=ht(e.value);return vt(t)},Za=e=>e===!0?"on":e===!1?"off":null,ed=e=>e==="on"?!0:e==="off"?!1:null});var Ep,Np,Bt,Ot,lr,ur,co=y(()=>{"use strict";se();S();ce();w();Ep=e=>e.props.tags??[],Np=e=>e.props.assignees??[],Bt=e=>Ep(e).map(t=>I.getTag(t)).filter(t=>!!t),Ot=e=>Np(e).map(t=>I.getContributor(t)).filter(t=>!!t),lr=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!k(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Bt(n))},ur=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!k(n)?i("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",Ot(n))}});var h,tn=y(()=>{"use strict";h={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""}});var Rp,Sp,Cp,Ap,Tp,nn,td,mr,pr,nd,wp,ws,lo=y(()=>{"use strict";Rp=/^(\d+)(h|d|w|mo|y)$/,Sp=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Cp=({year:e,month:t,day:n,hour:o=0,minute:r=0})=>{let s=new Date(e,t-1,n,o,r);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===o&&s.getMinutes()===r},Ap=(e,t=new Date)=>{let n=e.match(Rp);if(!n)return null;let[,o,r]=n,s=Number(o);if(!Number.isInteger(s)||s<=0)return null;let d=new Date(t);switch(r){case"h":return d.setHours(d.getHours()-s),d;case"d":return d.setDate(d.getDate()-s),d;case"w":return d.setDate(d.getDate()-s*7),d;case"mo":return d.setMonth(d.getMonth()-s),d;case"y":return d.setFullYear(d.getFullYear()-s),d;default:return null}},Tp=e=>{let t=e.match(Sp);if(!t)return null;let[,n,o,r,s,d]=t,l=Number(n),u=Number(o),m=Number(r),p=s?Number(s):0,v=d?Number(d):0;return Cp({year:l,month:u,day:m,hour:p,minute:v})?new Date(l,u-1,m,p,v):null},nn=e=>{let t=e.trim().toLowerCase();return Ap(t)??Tp(t)},td=/^(\d+)(s|m)?$/,mr=e=>{let t=e.trim().toLowerCase().match(td);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},pr=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),o=n.length>0&&td.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:o}},nd=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,wp=[{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}],ws=(e=wp)=>{let t=[];for(let{unit:n,from:o,to:r}of e)for(let s=o;s<=r;s++)t.push(`${s}${n}`);return t}});var Mp,oe,He,ye,kp,Lp,ks,Ls,sd,on,gr,Ms,od,Pp,Dp,uo,rd,Fp,Bp,Op,pe,Ut=y(()=>{"use strict";dr();ao();Sn();se();ce();w();Go();co();tn();lo();Mp=["BOARD","TICKET","SWIMLANE","COMMENT"],oe={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},He={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},ye={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},kp=[oe.EDITOR,oe.VIEW,oe.USERNAME,oe.AUTOSYNC,oe.SYNC_DEBOUNCE_MS,oe.ATTACHMENT_MAX_KB,oe.LOG_LEVEL],Lp=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[He.TITLE,He.DESCRIPTION];case"BOARD":case"SWIMLANE":return[He.TITLE];case"COMMENT":return[He.COMMENT];default:return[]}},ks=[String(An),"5000","15000","30000","60000"],Ls=["250","500","1000"],sd=["10s","20s","30s","45s"],on=[h.COFFEE,h.EXIT,h.SYNC,h.HELP,h.EXPORT,h.CONFIG,h.YANK],gr=[h.NEW,h.EDIT,h.DELETE,h.MOVE],Ms=[h.TAG,h.UNTAG,h.ASSIGN,h.UNASSIGN,h.CLOSE_ISSUE,h.RE_OPEN_ISSUE,h.EDIT,h.COMMENT],od=[h.FILTER,h.PEEK,h.REPLAY],Pp={WORKSPACE:[...on,...gr],BOARD:[...od,...on,...gr],SWIMLANE:[...od,...on,...gr],TICKET:[...on,...gr,...Ms],FIELD:[...on,...Ms],FIELD_LIST:[...on,...Ms],TEXT:[...on],COMMENT:[h.EDIT,h.DELETE,h.YANK]},Dp=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],uo=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&k(n)),rd=e=>e.parentNodeId===he,Fp=({selectedNode:e,breadCrumb:t})=>{let n=Lp(e?.context);return uo({breadCrumb:t,selectedNode:e})?n.includes(He.DESCRIPTION)?n:[...n,He.DESCRIPTION]:n},Bp=({selectedNode:e,breadCrumb:t})=>{let n=uo({breadCrumb:t,selectedNode:e});return n?[ye.REF,ye.TITLE,...n.props?.description?.trim()?[ye.DESCRIPTION]:[],...Bt(n).length>0?[ye.TAGS]:[],...Ot(n).length>0?[ye.ASSIGNEES]:[]]:e?[ye.REF,ye.TITLE]:[]},Op=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:o}=cr();if(!o)return[h.HELP,h.CONFIG];if(!Qa())return[h.HELP,h.INIT];if(t)return[h.HELP,h.PEEK,h.REPLAY,h.EXPORT,h.CONFIG,h.YANK];let r=e?.context,s=r&&Mp.includes(r),d=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?Pp[u]:[]))],l=uo({breadCrumb:n,selectedNode:e});return d.filter(u=>u===h.MOVE?!1:u===h.YANK?!!(l??e):u===h.EDIT?s||!!l:u===h.DELETE?s:u===h.UNTAG?!!(l&&Bt(l).length>0):u===h.UNASSIGN?!!(l&&Ot(l).length>0):u===h.RE_OPEN_ISSUE?!!(l&&rd(l)):u===h.CLOSE_ISSUE?!!(l&&!rd(l)):!0)},pe=(e,{contextNode:t,selectedNode:n,readOnly:o,breadCrumb:r}=g())=>{let s=t.context??"WORKSPACE";return{[h.NONE]:Op({breadCrumb:r,readOnly:o,selectedNode:n}),[h.EXIT]:["confirm"],[h.EXPORT]:[],[h.SYNC]:[],[h.INIT]:[],[h.HELP]:[],[h.PEEK]:[...ws(),"now","prev","next"],[h.REPLAY]:[...ws()],[h.EDIT]:Fp({selectedNode:n,breadCrumb:r}),[h.YANK]:Bp({selectedNode:n,breadCrumb:r}),[h.COMMENT]:[],[h.DELETE]:["confirm"],[h.RE_OPEN_ISSUE]:["confirm"],[h.CLOSE_ISSUE]:["confirm"],[h.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[h.FILTER]:["tag","assignee","description","title","ref","clear"],[h.TAG]:[...new Set([...Object.keys(En),...I.getExistingTags()])],[h.UNTAG]:[...lr()?.value?.map(({name:l})=>l)??[]],[h.UNASSIGN]:[...ur()?.value?.map(({name:l})=>l)??[]],[h.ASSIGN]:I.getExistingAssignees(),[h.NEW]:Dp(s),[h.CONFIG]:[...kp],[h.COFFEE]:["1","3","5","20","custom"]}[e]??[]}});var id,ad=y(()=>{"use strict";id=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{decodeTime as dd}from"ulid";var cd,rn,mo=y(()=>{"use strict";S();cd=e=>{try{return c("Decoded date",new Date(dd(e)))}catch(t){return i("Decoding failed + "+t.message)}},rn=e=>{if(!e?.id)return null;try{return dd(e.id)}catch{return null}}});import{accessSync as Up,copyFileSync as _p,existsSync as fr,mkdirSync as ld,readdirSync as ud,readFileSync as $p,renameSync as jp,rmSync as Wp,statSync as md,unlinkSync as Hp,writeFileSync as Kp}from"node:fs";import Tn from"node:path";var Ps,Be,vr=y(()=>{"use strict";Ps=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Be={writeToFile:(e,t)=>{try{let n=Tn.dirname(e);fr(n)||ld(n,{recursive:!0});let o=typeof t=="string"?t:JSON.stringify(t,null,2);Kp(e,o,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return $p(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Be.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 fr(e)&&md(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Up(e),!0}catch{return!1}},mkDir:e=>ld(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=Tn.parse(t);for(;;){let o=Tn.join(t,e);try{if(fr(o)&&md(o).isDirectory())return o}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=Tn.dirname(t)}return null},readFirstJSON(e){try{if(!Be.dirExists(e))return null;let t=ud(e).filter(o=>o.endsWith(".json")).sort()[0];if(!t)return null;let n=Tn.join(e,t);return Be.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Be.dirExists(e)?ud(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Hp(e)}catch(t){(!Ps(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Wp(e,{recursive:!0,force:!0})}catch(t){(!Ps(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(Tn.dirname(t)),!n?.overwrite&&fr(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{jp(e,t)}catch(o){if(Ps(o)&&o.code==="EXDEV"){_p(e,t),this.rmFile(e);return}throw o}}}});import qp from"node:path";import{z as Et}from"zod";var zp,pd,Vp,gd,Ds,Fs,Gp,fd,vd,Xe,hd,sn=y(()=>{"use strict";ue();S();vr();zp={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},pd=Et.object({logLevel:Et.enum(["info","error","debug"]),preferredEditor:Et.string().optional(),userName:Et.string().optional(),userId:Et.string().optional(),autoSync:Et.boolean().nullable().optional(),autoSyncDebounceMs:Et.number().optional(),attachmentMaxKb:Et.number().optional(),viewMode:Et.enum(["dense","wide"]).optional()}).partial(),Vp="config.json",gd=jn,Ds=()=>qp.join(gd(),Vp),Fs=()=>{try{return Be.mkDir(gd()),c(`Ensured ~/${Qe} exists`,null)}catch{return i(`Unable to create ~/${Qe}`)}},Gp=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${Qe}/config.json JSON`)}let n=pd.safeParse(t??{});return n.success?c("Parsed config",n.data):i(`Invalid ~/${Qe}/config.json shape: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},fd=()=>{let e=Fs();if(a(e))return i(e.message);let t=Ds(),n=Be.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Gp(n)},vd=e=>{let t=Fs();if(a(t))return i(t.message);let n=pd.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`);let o=Ds();try{return Be.writeToFile(o,JSON.stringify(n.data,null,2)+`
46
- `),c("Config written",null)}catch{return i(`Unable to write ~/${Qe}/config.json`)}},Xe=e=>{let t=fd();if(a(t))return i("Failed to read existing config");let n={...t.value,...e};return vd(n)},hd=()=>{let e=Ds(),t=Fs();if(a(t))return i(`Unable to create ~/${Qe}`);if(!(Be.readFile(e)!==null)){let x=vd(zp);if(a(x))throw new Error(`Unable to create ~/${Qe}/config.json`)}let o=fd();if(a(o))throw new Error(o.message||"Unable to load settings");let{preferredEditor:r,userName:s,userId:d,autoSync:l,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:v}=o.value;return!s||!d?i(`User name or ID not configured in ~/${Qe}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,c("successfully loaded settings",{logLevel:p??"debug",preferredEditor:r??"",userName:s,userId:d,autoSync:l??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:v??"dense"}))}});var po,Bs,go=y(()=>{"use strict";ut();S();ue();po=500,Bs=(e,t)=>`${e}.${t}`});import Yp from"zod";var fo,vo,yd,Os=y(()=>{"use strict";sn();go();te();S();be();ke();w();fo=50,vo=5e3,yd=()=>{let e=Q().commandMeta.inputString,t=Yp.coerce.number().int().min(fo).max(vo).safeParse(e);if(!t.success)return i(`Attachment size cap must be ${fo}-${vo} KB (default ${po})`);let n=Xe({attachmentMaxKb:t.data});return a(n)?n:(Ve({attachmentMaxKb:t.data}),E({mode:f.DEFAULT}),c(`Attachment size cap set to ${t.data} KB`,null))}});import bd from"chalk";var Z,Ne,Re,xd=y(()=>{"use strict";yt();Le();Z=e=>bd.dim(e),Ne=e=>bd.hex(R.primary)(e),Re=({prefix:e="",wordList:t,postfix:n="",noOfHints:o=100,inputString:r,minLengthForHints:s=1})=>{let d=r.trim();if(d.length<s)return"";let p=[...t.filter(Boolean).filter(v=>v.startsWith(d))].sort((v,x)=>Yo(v)-Yo(x)).slice(0,o).map(v=>Xo(v)).join(" ");return p?`${Z(e)}${p}${Z(n)}`:""}});var _t,hr=y(()=>{"use strict";_t={None:"none",Invalid:"invalid",Valid:"valid"}});import Nd from"chalk";var wn,Xp,Id,re,q,O,br,Ed,yr,Us,Jp,an,Qp,Zp,eg,tg,Rd,_s=y(()=>{"use strict";dr();ao();ad();mo();ut();S();ce();ke();Os();go();w();yt();co();Rn();xd();tn();hr();Ut();lo();wn=140,Xp=["BOARD","TICKET","SWIMLANE"],Id=()=>{let e=g().selectedNode;if(!e?.context)return O({message:Z("Missing target context")});if(Xp.includes(e.context))return q();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===Ee(t?.parentNodeId??"","comments"))return q()}return O({message:Z("Command not available in this context")})},re="<ENTER> to confirm",q=(e="",t=[])=>({message:Z(e),validity:_t.Valid,completionWordList:t}),O=({message:e,completionWordList:t=[]})=>({validity:_t.Invalid,message:e,completionWordList:t}),br=e=>e.length===0,Ed=(e,t)=>{let n=je(g().breadCrumb,"BOARD");if(a(n))return O({message:Ne("Command is not applicable in this context")});let o=cd(n.value.id);return a(o)?O({message:Ne(`Unable to ${t}: board id is not a valid ULID`)}):nd({date:e,horizonDate:o.value})?null:O({message:Ne(`nothing to ${t} before ${o.value.toISOString().slice(0,16).replace("T"," ")}`)})},yr=e=>` ${Nd.hex("#000").bgHex(Pe(e))(` ${e} `)} `,Us=({modifier:e})=>{let t="confirm";return e===t?q(re):O({message:br(e)?Z("if you are certain, enter ")+Xo(t):"",completionWordList:[t]})},Jp=({list:e,hint:t,onValue:n})=>({modifier:o,inputString:r})=>e.includes(o)?r.trim().length<1?O({message:Z(n)}):q():O({message:br(o)?t:"",completionWordList:[...e]}),an=({hint:e,onOk:t})=>({modifier:n,inputString:o})=>br(n)&&br(o)?O({message:e,completionWordList:[]}):q(t??re),Qp=({modifier:e,inputString:t})=>{let n=pe(h.CONFIG);if(!n.includes(e))return O({message:Re({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case oe.EDITOR:{let o=[...id];return t.trim()?o.includes(t.trim())?q(re):O({message:Re({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o}):O({message:Re({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case oe.VIEW:{let o=["dense","wide"];return o.includes(t.trim())?q(re):O({message:Re({prefix:"view... ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case oe.USERNAME:return t.trim()?q(re):O({message:Ne("Enter a user name. Saved in ")+Nd.bgBlack("~/.epiq-global/config.json")});case oe.LOG_LEVEL:{let o=["debug","error","info"],r=t.trim();return o.includes(r)?q(re):O({message:Re({prefix:"one of: ",wordList:[...o],inputString:r,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...o]})}case oe.AUTOSYNC:{let o=["on","off"],r=ie().autoSync;if(!o.includes(t.trim())){let s=Za(r);return O({message:Re({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:o,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:o})}return q(re)}case oe.ATTACHMENT_MAX_KB:{let o=ie().attachmentMaxKb,r=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(r)||r<fo||r>vo){let s=Re({prefix:" examples: ",wordList:Ls,minLengthForHints:0,inputString:t});return O({message:Ne(`provide a size cap in KB (${fo}-${vo}). current: ${o??po} KB.`)+s,completionWordList:Ls})}return q(re)}case oe.SYNC_DEBOUNCE_MS:{let o=ie().autoSyncIntervalMs,r=Ga(t);if(!t.trim()||r===null||r<An){let s=Re({prefix:" examples: ",wordList:ks,minLengthForHints:0,inputString:t});return O({message:Ne(`provide duration above ${An}ms. current duration: ${o}ms.`)+s,completionWordList:ks})}return q(re)}default:return O({message:Ne("Unknown config option"),completionWordList:n})}},Zp=({modifier:e,inputString:t})=>{let n=pe(h.EDIT);if(!n.length)return O({message:Ne("Command not available in this context")});if(!n.includes(e)){let o=Re({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return O({message:o||Ne("Unknown edit option"),completionWordList:n})}switch(e){case He.COMMENT:return t.trim()?q(re):O({message:Z("write a comment...")});case He.TITLE:return q(re);case He.DESCRIPTION:{let{preferredEditor:o}=ie();return o?q(Z("<ENTER> to edit in ")+o):O({message:"No editor selected"})}default:return O({message:Ne("Unknown edit option"),completionWordList:n})}},eg=({modifier:e})=>{let t=pe(h.YANK);return t.length?t.includes(e)?q(re+Z(" and copy to clipboard")):O({message:Re({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):O({message:Ne("Nothing selected to copy from")})},tg={[h.EXPORT]:()=>q(re+Z(", and create export markdown file")),[h.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return q(re);let n={message:Z("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},o=t||e.inputString.trim(),r=nn(o);if(!o||!r)return O(n);let s=Ed(r,"peek");return s||q(re)},[h.REPLAY]:e=>{let{dateInput:t,durationInput:n}=pr(e.modifier,e.inputString),o={message:Z("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},r=nn(t);if(!t||!r)return O(o);let s=Ed(r,"replay");return s||(n&&mr(n)===null?O({message:Ne("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):q("<ENTER> to replay board history",n?sd:[]))},[h.EXIT]:()=>q(re+Z(" and exit the application")),[h.INIT]:()=>q(re),[h.PALETTE]:()=>q(re),[h.FILTER]:e=>{if(e.modifier==="clear")return q(re);let t=s=>pe(h.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return O({message:Re({wordList:pe(h.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:pe(h.FILTER)});let n=Object.values(g().tags).map(s=>s.name),o=Object.values(g().contributors).map(s=>s.name),r=e.modifier==="tag"?n:e.modifier==="assignee"?o:[];return e.inputString?r.length&&!r.includes(e.inputString.trim())?O({message:Re({prefix:`existing ${e.modifier}s... `,wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r}):q():O({message:Re({prefix:"one of... ",wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r})},[h.NONE]:e=>{let t=pe(h.NONE);return O({message:Re({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[h.NEW]:e=>Jp({list:pe(h.NEW),hint:Re({wordList:pe(h.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[h.HELP]:()=>q(re),[h.EDIT]:Zp,[h.COMMENT]:e=>{let t=an({hint:Z(`write a comment (max ${wn} char)...`),onOk:Z(`(${e.inputString.length}/${wn})`)})(e);return t.validity===_t.Invalid?t:e.inputString.length>wn?q(Ne("max input exceeded")):t},[h.CONFIG]:Qp,[h.YANK]:eg,[h.DELETE]:e=>{let t=Id();return t.validity==="invalid"?t:Us(e)},[h.CLOSE_ISSUE]:e=>Us(e),[h.RE_OPEN_ISSUE]:e=>Us(e),[h.MOVE]:e=>{let t=Id();return t.validity==="invalid"?t:an({hint:Re({prefix:"hey hacker! These commands are blocked for you... ",wordList:pe(h.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[h.TAG]:e=>{let n=I.getExistingTags().slice(0,10).map(yr).join("");return an({hint:n.length?Z("create tag or reuse:")+n+Z(""):Z("create tag ...")})(e)},[h.UNTAG]:e=>{let t=lr();if(a(t))return O({message:Ne("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(yr).slice(0,10);return n.length?an({hint:Z(" ... ")+n.join("")})(e):O({message:Ne("Issue has no tags"),completionWordList:[]})},[h.ASSIGN]:e=>{let t=I.getExistingAssignees().map(yr).slice(0,10);return an({hint:Z("assignees... ")+t.join("")})(e)},[h.UNASSIGN]:e=>{let t=ur();if(a(t))return O({message:Ne("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(yr).slice(0,10);return n.length?an({hint:Z("remove assignee... ")+n.join("")})(e):O({message:Ne("Issue has no assignees"),completionWordList:[]})},[h.SYNC]:()=>q(re),[h.COFFEE]:e=>{let{modifier:t}=e,n=pe(h.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?O({message:Z("enter an amount ... "),completionWordList:n.filter(o=>o.startsWith(t))}):an({hint:Re({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},Rd=Object.fromEntries(Object.entries(tg).map(([e,t])=>[e,{validate:(n,o,r)=>t({modifier:o,command:n,inputString:r})}]))});var xr,Sd=y(()=>{"use strict";xr=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"]});var ng,og,rg,sg,ig,Cd,Ad,Td,wd=y(()=>{"use strict";S();w();Sd();ng=3,og=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),rg=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let o=n.props;typeof o.description=="string"&&t.push(o.description),typeof o.value=="string"&&t.push(o.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},sg=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=ng&&!og.has(t)&&!/^\d+$/.test(t)),ig=e=>{let t=new Map;for(let s of rg(e))for(let d of sg(s))t.set(d,(t.get(d)??0)+1);let n=[...t.entries()].sort((s,d)=>d[1]-s[1]||s[0].localeCompare(d[0])).map(([s])=>s),o=new Set(n),r=xr.filter(s=>!o.has(s));return[...n,...r]},Cd=xr,Ad=-1,Td=()=>{let e=Fe();if(a(e))return xr;let t=e.value,n=t.eventLog.length;return n!==Ad&&(Cd=ig(t),Ad=n),Cd}});var Md,kd,$s=y(()=>{"use strict";da();Ut();tn();_s();wd();w();te();Md=e=>Object.values(h).includes(e),kd=(e,t)=>{let n=e.command??"",{modifier:o,target:r,inputString:s}=e,{message:d,validity:l,completionWordList:u}=Rd[n].validate(n,o,s),m=n!==h.PEEK&&n!==h.REPLAY,p=r==="command"||r==="modifier"?pe(n):m?Td():[],{mode:v}=g(),x=v===f.COMMAND_LINE?d??"":"",C=[...u,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:x,autoCompletion:t?aa(e,C):{hint:"",hints:[],remainder:"",overlap:0}}}});var Ld,ag,dg,cg,Pd=y(()=>{"use strict";$s();Ut();Ld=e=>{let t=e.trimStart(),n=dg(t),o=n[0]??"",r=n[1]??"",s=/\s$/.test(e),d=cg(e),l=Md(o)?o:null,u=l!==null,m=o!=="",p=l?pe(l)??[]:[],v=l&&p.includes(r)?r:"",x="word";n.length===0||n.length===1&&!s?x="command":(n.length===1&&s||n.length===2&&!s)&&(x="modifier");let C=s?"":d,A=ag(t,l,v);return{raw:e,trimmedStart:t,words:n,firstWord:o,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:s,modifier:v,target:x,inputToMatch:C,inputString:A}},ag=(e,t,n)=>{let o=e;return t&&o.startsWith(t)&&(o=o.slice(t.length)),o=o.replace(/^\s+/,""),n&&o.startsWith(n)&&(o=o.slice(n.length),o=o.replace(/^\s+/,"")),o},dg=e=>e.trim()?e.trim().split(/\s+/):[],cg=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as $E}from"react";var Mn,js,kn,lg,Dd,pt,ho,Ws,Hs,Fd,Bd,Ir,Od,H,Ud,_d,$d,Q,jd,be=y(()=>{"use strict";$s();Pd();S();hr();Mn=e=>e===js||e===":",js=" ",kn={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:_t.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},lg=new Set,Dd=()=>{for(let e of lg)e()},pt=e=>{let n=e(kn),o=Ld(n.value),r=n.cursorPosition===n.value.length;kn={...n,commandMeta:kd(o,r)},Dd()},ho=({message:e,status:t})=>{let n=structuredClone(kn);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,kn=n,Dd(),c(e,null)},Ws=e=>{pt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Hs=e=>{pt(t=>{let{value:n,cursorPosition:o}=t,r=o;if(e==="left"){for(;r>0&&Mn(n[r-1]);)r--;for(;r>0&&!Mn(n[r-1]);)r--}else{for(;r<n.length&&!Mn(n[r]);)r++;for(;r<n.length&&Mn(n[r]);)r++}return{...t,cursorPosition:r}})},Fd=()=>{pt(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}})},Bd=()=>{pt(e=>{let{value:t,cursorPosition:n}=e,o=n;for(;o>0&&Mn(t[o-1]);)o--;for(;o>0&&!Mn(t[o-1]);)o--;let r=t.slice(n);return{...e,value:t.slice(0,o)+r,cursorPosition:o,commandIsPending:!1}})},Ir=e=>{pt(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),o=t.value.slice(0,n),r=t.value.slice(n),s=e(o,t.commandMeta.autoCompletion),d=s+r,l=Math.max(0,Math.min(s.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},Od=()=>{pt(e=>({...e,commandIsPending:!0}))},H=e=>{pt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Ud=({addToHistory:e=!0})=>{pt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},_d=()=>{pt(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}})},$d=()=>{pt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Q=()=>kn,jd=()=>{let[e,...t]=kn.value.split(js);return t.join(js).trim()}});var M,Vt=y(()=>{"use strict";te();ea();w();be();ke();M={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"}});var Wd,P,Ks=y(()=>{"use strict";w();tn();Wd=e=>{let{context:t}=g().contextNode;if(!t)return P.None;switch(e){case h.EXIT:return P.Exit;case h.EXPORT:return P.Export;case h.COFFEE:return P.Coffee;case h.INIT:return P.Init;case h.DELETE:return P.Delete;case h.EDIT:return P.Edit;case h.COMMENT:return P.Comment;case h.HELP:return P.ViewHelp;case h.RE_OPEN_ISSUE:return P.ReopenIssue;case h.CLOSE_ISSUE:return P.CloseIssue;case h.TAG:return P.TagTicket;case h.UNTAG:return P.UntagTicket;case h.ASSIGN:return P.AssignUserToTicket;case h.UNASSIGN:return P.UnassignUserFromTicket;case h.NEW:return P.NewItem;case h.FILTER:return P.Filter;case h.MOVE:return P.Move;case h.PEEK:return P.Peek;case h.REPLAY:return P.Replay;case h.CONFIG:return P.Config;case h.YANK:return P.Yank;case h.SYNC:return P.Sync;default:return P.None}},P={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export",Coffee:"coffee"}});import{Text as Hd}from"ink";import Kd,{useEffect as qd,useState as ug}from"react";var zd,Oe,Ln=y(()=>{"use strict";w();Le();zd={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Oe=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Ue(),o=zd[n]??zd.default,[r,s]=ug(0);if(qd(()=>{s(0)},[o]),qd(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%o.length)},500);return()=>clearInterval(l)},[e,o]),!e)return Kd.createElement(Hd,null,t);let d=o[r]??o[0]??t;return Kd.createElement(Hd,{color:R.accent,dimColor:r===1},d)}});import{Box as qs,Text as mg}from"ink";import Er from"react";var $t,yo=y(()=>{"use strict";Le();$t=({children:e=[],height:t,selectedIndex:n,itemHeight:o=1,scrollByOne:r=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),d=Math.max(1,Math.ceil(o)),l=Math.max(1,Math.floor(s/d)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-l),p=r?Math.min(m,Math.max(0,u-l+1)):Math.min(m,Math.floor(u/l)*l),v=p+l,x=e.slice(p,v),C=e.length>l,A=s,T=C?Math.max(1,Math.floor(l/e.length*A)):A,_=Math.max(0,A-T),z=Math.max(1,e.length-l),K=C?Math.floor(p/z*_):0;return Er.createElement(qs,{flexDirection:"row",height:s,width:"100%"},Er.createElement(qs,{flexDirection:"column",flexGrow:1,height:s},x),Er.createElement(qs,{flexDirection:"column",width:1,height:A},Array.from({length:A}).map((U,Ce)=>Er.createElement(mg,{key:Ce,color:C&&Ce>=K&&Ce<K+T?R.accent:R.secondary},C?"\u2502":" "))))}});var Pn,Vd,Nr,Gd,Dn,Yd,Fn=y(()=>{"use strict";w();fs();Pn=(e,t)=>t?e&&oo(e)===t?e:t:e,Gd=()=>{let{eventLog:e=[]}=g();if(Nr&&Vd===e)return Nr;let t=new Map,n=new Set;for(let o of e)o?.userId&&(n.add(o.userId),o.userName&&t.set(o.userId,o.userName));return Vd=e,Nr={latestNames:t,authors:n},Nr},Dn=(e,t)=>{let{contributors:n={}}=g();return n[e]?.tombstoned?t:Pn(t,Gd().latestNames.get(e))??t},Yd=e=>Gd().authors.has(e)});import{Text as pg}from"ink";import gg from"react";var fg,vg,Bn,Rr=y(()=>{"use strict";Go();yt();ce();Fn();fg=e=>e.toLowerCase().trim(),vg=(e,t=En)=>{let n=fg(e);return t[n]?t[n]:to(n)},Bn=({id:e,isSelected:t})=>{let n=I.getContributor(e);if(!n)return;let o=Dn(e,n.name);return gg.createElement(pg,{underline:t,color:vg(o)},"@"+o,Yd(e)?"":"\u2197")}});import{Text as hg}from"ink";import yg from"react";var Sr,zs=y(()=>{"use strict";ce();Le();yt();Sr=({id:e,isSelected:t})=>{let n=I.getTag(e);if(n)return yg.createElement(hg,{underline:t,backgroundColor:Pe(n.name),color:R.secondary}," "+n.name+" ")}});import{useEffect as bg,useState as xg}from"react";var Ig,Xd,Cr,bo,Eg,Ng,On,Ar=y(()=>{"use strict";yt();Ig=80,Xd=1400,Cr=new Set,bo=null,Eg=e=>(Cr.add(e),bo||(bo=setInterval(()=>{for(let t of Cr)t()},Ig)),()=>{Cr.delete(e),Cr.size===0&&bo&&(clearInterval(bo),bo=null)}),Ng=()=>{let e=Date.now()%Xd/Xd;return e<.5?e*2:(1-e)*2},On=e=>{let[,t]=xg(0);return bg(()=>{if(e)return Eg(()=>t(n=>n+1))},[e]),ya(Ng())}});import{Box as Un,Text as Tr}from"ink";import Je from"react";var Rg,Jd,Qd=y(()=>{"use strict";Le();hn();In();co();Rr();zs();Ar();Rg=(e,t)=>{if(e.length<=t)return[e,null];let n=e.lastIndexOf(" ",t),o=n>0?n:t;return[e.slice(0,o),eo(e.slice(o).trim(),t)]},Jd=({width:e,ticket:t,isSelected:n,isFlashing:o=!1})=>{let r=On(o),s=e-4,[d,l]=Rg(ze(t.title),s),u=l?null:eo(ze(t.props.description),s)||null,m=Bt(t),p=Ot(t);return Je.createElement(Un,{borderStyle:"round",height:5,flexDirection:"column",borderDimColor:!n,borderColor:o?r:n?R.accent:R.secondary,justifyContent:"space-between"},Je.createElement(Un,{paddingLeft:1,flexDirection:"column"},Je.createElement(Tr,{color:R.primary},d),l&&Je.createElement(Tr,{color:R.primary},l),u&&Je.createElement(Tr,{color:R.secondary2,dimColor:!0},u)),Je.createElement(Un,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1,paddingRight:1},Je.createElement(Un,{flexDirection:"row"},m.map(v=>Je.createElement(Un,{paddingRight:1,key:v.id},Je.createElement(Sr,{key:v.id,id:v.id}))),p.map(v=>Je.createElement(Un,{paddingRight:1,key:v.id},Je.createElement(Bn,{key:v.id,id:v.id})))),Je.createElement(Tr,{wrap:"truncate",color:R.secondary2,dimColor:!0},tt(t.id))))}});import{Box as dn,Text as xo}from"ink";import Ke from"react";var Sg,Zd,ec=y(()=>{"use strict";te();ce();Fn();Le();yt();Ln();Ar();Sg=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,Zd=({width:e,ticket:t,isSelected:n,isFlashing:o=!1,index:r,mode:s})=>{let d=On(o),l=(t.props.tags??[]).map(U=>I.getTag(U)).filter(U=>!!U),u=(t.props.assignees??[]).map(U=>I.getContributor(U)).map(U=>U&&{...U,name:Dn(U.id,U.name)}).filter(U=>!!U),m=1,p=l.length*(1+m),v=u.length*(2+m),x=l.map(U=>Ke.createElement(dn,{key:U.id,paddingRight:m},Ke.createElement(xo,{color:Pe(U.name)},"\u25A0"))),C=u.map(U=>Ke.createElement(dn,{key:U.id,paddingRight:m},Ke.createElement(xo,{color:to(U.name)},"@"+U.name.at(0)))),A=o?d:n?R.accent:s===f.MOVE?R.secondary:R.primary,T=4,_=I.getCommentsByIssue(t.id),z=_.length?String(_.length).length+2+m:0,K=_.length?Ke.createElement(dn,{paddingRight:m},Ke.createElement(xo,{color:R.accent},"[",_.length,"]")):null;return Ke.createElement(dn,{borderBottom:!0,justifyContent:"space-between"},Ke.createElement(dn,null,Ke.createElement(dn,{width:T},n?Ke.createElement(Oe,{isSelected:n}):Ke.createElement(xo,{color:"gray",dimColor:!0},r+1)),Ke.createElement(xo,{wrap:"truncate",color:A},Sg(t.title,e-p-v-z-18))),Ke.createElement(dn,null,x,C,K))}});import Cg from"chalk";import{Box as Vs,Text as Ag}from"ink";import gt from"react";var Tg,tc,nc=y(()=>{"use strict";se();w();Le();Ln();yo();Qd();ec();Ar();Tg=({swimlane:e,isSelected:t,width:n,height:o,isDense:r,isFocused:s,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u,replay:m}=Ue(),p=u[e.id]??[],v=m?new Set(m.flashNodeIds):null,x=v?.has(e.id)??!1,C=On(x),A=`${e.title} ${Cg.hex(R.secondary2).dim("("+p.length+")")}`,T=3,_=r?1:5,z=s&&d===-1,K=n-(z?7:5),U=o-T-(r?2:1),Ce=gt.createElement(Vs,{borderStyle:"round",borderColor:R.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},gt.createElement(Oe,{isSelected:t}),gt.createElement(Ag,{bold:!0,color:x?C:t?R.accent:R.primary},A," ",e.readonly?"\u{1F512}":"")),mn=($,V)=>{let pn=s&&d===V;if(!k($))return null;let Kt=v?.has($.id)??!1;return r?gt.createElement(Zd,{key:$.id,index:V,width:n,ticket:$,isSelected:pn,isFlashing:Kt,mode:l}):gt.createElement(Jd,{key:$.id,width:K,ticket:$,isSelected:pn,isFlashing:Kt})};return gt.createElement(Vs,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?R.accent:R.secondary,paddingRight:1,paddingLeft:1,height:o},Ce,gt.createElement(Vs,{padding:r?1:0},p.length>0&&gt.createElement($t,{selectedIndex:d,height:U,itemHeight:_},p.map(mn)),z&&gt.createElement(Oe,{isSelected:!0})))},tc=gt.memo(Tg)});var oc,rc,Gs=y(()=>{"use strict";Yt();oc=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},rc=(e,t,n)=>Ie.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0})});import{Box as _n,Text as Nt}from"ink";import Te,{useEffect as wg,useMemo as Mg,useRef as kg}from"react";import{decodeTime as Ys}from"ulid";function ic({ticket:e,width:t,height:n}){let o=Mg(()=>Pg(e),[e]),r=kg([]);wg(()=>(sc(r.current),r.current=Fg(e,o),()=>{sc(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=Ue(),l=Math.max(1,n-4),u=Math.max(12,t-32);return o.length===0?Te.createElement(_n,{flexDirection:"column",width:t,height:n,padding:1},Te.createElement(Nt,{color:R.primary},"No attachments yet."),Te.createElement(_n,{paddingTop:1},Te.createElement(Nt,{color:R.primary},"Attach images from the browser GUI"),Te.createElement(Nt,{color:R.accent}," epiq gui "),Te.createElement(Nt,{color:R.primary},"by dropping or pasting them."))):Te.createElement(_n,{flexDirection:"column",width:t,height:n},Te.createElement(_n,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:R.secondary,borderStyle:"single",paddingBottom:1},Te.createElement(Nt,{color:R.secondary2},"Attachments (",o.length,") \u2014 enter to open"," ")),Te.createElement($t,{height:l,itemHeight:2,selectedIndex:s},o.map((m,p)=>{let v=p===s,x=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return Te.createElement(_n,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},Te.createElement(Nt,{color:R.accent},v?"\u276F ":" "),Te.createElement(_n,{paddingLeft:1},Te.createElement(Nt,{color:R.secondary2},`#${p+1} `),Te.createElement(Nt,{color:v?R.accent:R.primary},x),Te.createElement(Nt,{color:R.secondary2}," "+Bg(m.bytes)+" "+Nn(Ys(m.id)))))})))}var Lg,Pg,sc,Dg,Fg,Bg,ac=y(()=>{"use strict";We();Jo();se();S();ce();Yt();w();Le();Rn();yo();Lg=e=>Ee(e,"attachments"),Pg=e=>I.getAttachmentsByIssue(e.id).sort((t,n)=>Ys(t.id)-Ys(n.id)),sc=e=>{for(let t of e)I.deleteNode(t.id)},Dg=(e,t,n)=>Ie.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),Fg=(e,t)=>{let n=I.getNode(Lg(e.id));if(!n||!_e(n))return[];let o=t.map((r,s)=>Dg(r,s,n.id)).map(r=>I.createNode(r)).filter(vt).map(({value:r})=>r).filter(_e);return t.length>0&&g().selectedIndex<0&&F.navigate({contextNode:n,selectedIndex:0}),o},Bg=e=>`${Math.max(1,Math.round(e/1024))} KB`});import{Box as jt,Text as Rt}from"ink";import xe,{useEffect as Og,useMemo as Ug,useRef as _g}from"react";import{decodeTime as Xs}from"ulid";function cc({ticket:e,width:t,height:n}){let o=Ug(()=>jg(e),[e]),r=_g([]);Og(()=>(dc(r.current),r.current=Wg(e,o),()=>{dc(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=Ue(),l=Math.max(1,n-4),u=Math.max(20,t-8);return o.length===0?xe.createElement(jt,{flexDirection:"column",width:t,height:n,padding:1},xe.createElement(Rt,{color:R.primary},"No comments yet."),xe.createElement(jt,{paddingTop:1},xe.createElement(Rt,{color:R.primary},"Use"),xe.createElement(Rt,{color:R.accent}," :comment "),xe.createElement(Rt,{color:R.primary},"to add the first one."))):xe.createElement(jt,{flexDirection:"column",width:t,height:n},xe.createElement(jt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:R.secondary,borderStyle:"single",paddingBottom:1},xe.createElement(Rt,{color:R.secondary2},"Comments (",o.length,") ")),xe.createElement($t,{height:l,itemHeight:4,selectedIndex:s},o.map((m,p)=>{let v=p===s;return xe.createElement(jt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:R.secondary,borderStyle:"single"},xe.createElement(jt,{flexDirection:"row",paddingBottom:1},xe.createElement(Rt,{color:R.accent},v?"\u276F ":" "),xe.createElement(jt,{paddingLeft:1},xe.createElement(Rt,{color:R.secondary2},`#${p+1} `),xe.createElement(Bn,{id:m.authorId}),xe.createElement(Rt,{color:R.secondary2}," "+Nn(Xs(m.id))))),xe.createElement(jt,{paddingLeft:3,paddingBottom:1},xe.createElement(Rt,{color:R.primary},Hg(m.md,u))))})))}var $g,jg,dc,Wg,Hg,lc=y(()=>{"use strict";We();Jo();se();S();ce();w();Le();Rn();Rr();yo();Gs();$g=e=>Ee(e,"comments"),jg=e=>I.getCommentsByIssue(e.id).sort((t,n)=>Xs(t.id)-Xs(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),dc=e=>{for(let t of e)I.deleteNode(t.id)},Wg=(e,t)=>{let n=I.getNode($g(e.id));if(!n||!_e(n))return[];let o=t.map((r,s)=>rc(r,s,n.id)).map(I.createNode).filter(vt).map(({value:r})=>r).filter(Zn);return t.length>0&&g().selectedIndex<0&&F.navigate({contextNode:n,selectedIndex:0}),o},Hg=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`}});import{Box as wr,Text as Kg}from"ink";import St from"react";var uc,mc=y(()=>{"use strict";se();ce();xn();w();Le();Rr();Ln();zs();uc=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:o}=Ue(),{title:r}=t,s=t.parentNodeId?I.getNode(t.parentNodeId):void 0,d=s&&k(s)?r===X.ASSIGNEES?s.props.assignees??[]:r===X.TAGS?s.props.tags??[]:[]:[];return St.createElement(wr,{alignItems:"center",paddingTop:1},St.createElement(wr,{minWidth:12},St.createElement(Oe,{isSelected:n}),St.createElement(Kg,{color:n?R.accent:R.secondary2},r,":")),St.createElement(wr,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=o.id===t.id&&u===e;return St.createElement(wr,{key:`${r}-${l}`,paddingRight:2,minHeight:1},St.createElement(Oe,{isSelected:m}),r===X.ASSIGNEES?St.createElement(Bn,{isSelected:m,id:l}):r===X.TAGS?St.createElement(Sr,{isSelected:m,id:l}):null)})))}});import{Box as Mr,Text as Js}from"ink";import Ct,{useEffect as qg,useMemo as pc}from"react";var zg,gc,Qs,fc,Vg,Zs,vc=y(()=>{"use strict";ce();S();Yt();w();Le();hn();Ln();yo();bn();zg="\u2029",gc=(e,t)=>`${e}::inline-line::${t}`,Qs=new Map,fc=e=>{let t=Qs.get(e)??[];Qs.delete(e);for(let n of t)I.deleteNode(n)},Vg=(e,t)=>{fc(e);let n=[];t.forEach((o,r)=>{let s=$e(BigInt(r+1));if(!vt(s))return;let d=I.createNode(Ie.text({id:gc(e,r),name:`Line ${r+1}`,parentNodeId:e,rank:s.value,props:{value:o},readonly:!0,isVirtual:!0}));vt(d)&&n.push(d.value.id)}),Qs.set(e,n)},Zs=({id:e,label:t,text:n,height:o,selected:r,maxWidth:s})=>{let{selectedIndex:d,contextNode:l}=Ue(),u=pc(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=pc(()=>u.join("\0"),[u]);qg(()=>(Vg(e,u),()=>{fc(e)}),[e,m]);let p=x=>String(x).replace(/\r?\n/g,""),v=u.map((x,C)=>{let A=l.id===e&&d===C;return Ct.createElement(Mr,{key:gc(e,C)},Ct.createElement(Js,{color:A?R.primary:R.secondary2,dimColor:!A},`${C+1} `.padStart(5,"\xA0")),Ct.createElement(Js,{backgroundColor:A?"gray":void 0},p(x.length?eo(x,s-10):zg)))});return Ct.createElement(Mr,{flexDirection:"column",paddingTop:1},Ct.createElement(Mr,null,Ct.createElement(Oe,{isSelected:r}),Ct.createElement(Js,{color:r?R.accent:R.secondary2},t)),Ct.createElement(Mr,{flexDirection:"row",borderStyle:"round",borderColor:R.secondary,paddingLeft:1,marginLeft:1},Ct.createElement($t,{scrollByOne:!0,height:o-3,selectedIndex:d,itemHeight:1},v)))}});import{Box as cn,Text as ei}from"ink";import Se,{useMemo as Io}from"react";var Gg,Yg,Xg,Jg,hc,yc=y(()=>{"use strict";se();ce();w();Le();Gs();Rn();ac();lc();Ln();mc();vc();Gg=e=>Ee(e,"description"),Yg=e=>Ee(e,"comments"),Xg=e=>Ee(e,"history"),Jg=e=>Ee(e,"attachments"),hc=({ticket:e,height:t})=>{let n=Io(()=>oc(e),[e]),{selectedIndex:o,contextNode:r}=Ue(),s=process.stdout.columns||120,d=Io(()=>Gg(e.id),[e.id]),l=Io(()=>Yg(e.id),[e.id]),u=Io(()=>Xg(e.id),[e.id]),m=Io(()=>Jg(e.id),[e.id]),p=I.getAttachmentsByIssue(e.id).length,v=r.id===e.id,x=r.id===l||r.parentNodeId===l,C=r.id===u||r.parentNodeId===u,A=r.id===m||r.parentNodeId===m,T=J(e.id);if(x){let V=t-3;return Se.createElement(cn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Se.createElement(cc,{ticket:e,width:s,height:V}))}if(A){let V=t-3;return Se.createElement(cn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Se.createElement(ic,{ticket:e,width:s,height:V}))}if(C){let $=I.getNode(u),V=$&&_e($)?$.props.value??"":"",Kt=t-3;return Se.createElement(cn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},$?Se.createElement(Zs,{id:$.id,label:"Event log",text:V,selected:!1,maxWidth:s,height:Kt}):null)}let _=T.reduce(($,V)=>Qn(V)||V.id===l||V.id===m||V.id===u?$+1:$,0),z=2,K=3,U=_,Ce=t-K-U-z,mn=($,V)=>$.id===d?Se.createElement(Zs,{key:$.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:V,maxWidth:s,height:Ce}):Qn($)?Se.createElement(uc,{key:$.id,parent:$,selected:V,selectedIndex:o}):$.id===l?Se.createElement(cn,{key:$.id,paddingTop:1},Se.createElement(Oe,{isSelected:V}),Se.createElement(ei,{backgroundColor:R.secondary,color:V?R.accent:R.primary},` Comments (${n}) \u203A\u203A `)):$.id===m?Se.createElement(cn,{key:$.id,paddingTop:1},Se.createElement(Oe,{isSelected:V}),Se.createElement(ei,{backgroundColor:R.secondary,color:V?R.accent:R.primary},` Attachments (${p}) \u203A\u203A `)):$.id===u?Se.createElement(cn,{key:$.id,paddingTop:1},Se.createElement(Oe,{isSelected:V}),Se.createElement(ei,{backgroundColor:R.secondary,color:V?R.accent:R.primary}," History \u203A\u203A ")):null;return Se.createElement(cn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},T.map(($,V)=>mn($,v&&o===V)))}});import{Box as Qg}from"ink";import kr from"react";var Zg,bc,xc=y(()=>{"use strict";se();nc();yc();Zg=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,viewMode:s,height:d,width:l})=>{let u=t.context,m=u===D.TICKET||u===D.FIELD_LIST||u===D.FIELD,p=u===D.BOARD||u===D.SWIMLANE,v=u===D.TICKET?t:o.find(_=>_.context===D.TICKET),x=Math.floor(l/3),C=Math.floor(l/Math.max(e.length,1)),A=Math.min(C,x),T=s==="dense";return kr.createElement(Qg,{flexDirection:"row",height:d},p&&e.map((_,z)=>{let K=t.id===_.id,U=K?n:-1,Ce=t.context===D.BOARD&&n===z;return kr.createElement(tc,{key:_.id,height:d,width:A,swimlane:_,isSelected:Ce,isDense:T,isFocused:K,listSelectedIndex:U,mode:r})}),m&&v&&kr.createElement(hc,{height:d,ticket:v}))},bc=kr.memo(Zg)});import Ic from"node:fs";import ef from"node:path";import tf from"react";import{render as nf}from"ink";import{Writable as of}from"node:stream";var Eo,rf,sf,af,df,Ec,Nc=y(()=>{"use strict";xc();se();S();w();ue();ke();Eo=e=>String(e).padStart(2,"0"),rf=e=>{let t=e.getUTCFullYear(),n=Eo(e.getUTCMonth()+1),o=Eo(e.getUTCDate()),r=Eo(e.getUTCHours()),s=Eo(e.getUTCMinutes()),d=Eo(e.getUTCSeconds());return`${t}-${n}-${o}_${r}-${s}-${d}`},sf=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",af=async(e,{width:t,height:n})=>{let o="",r=new of({write(d,l,u){let m=df(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(o=m),u()}});r.columns=t,r.rows=n,r.isTTY=!0;let s=nf(e,{stdout:r,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),o},df=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Ec=async()=>{let{viewMode:e}=ie(),{contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,renderedChildrenIndex:s}=g(),d=o.find(z=>z.context==="BOARD");if(!d)return i("No board found to export");let l=120,u=40,m=await af(tf.createElement(bc,{height:u,width:l,swimlanes:(s[d.id]??[]).filter(z=>z!==void 0&&zt(z)),contextNode:t,selectedIndex:n,breadCrumb:o,viewMode:e??"dense",mode:r}),{width:l,height:u});if(!m)return i("Failed to render board export");let p=wo(process.cwd());if(a(p))return i("Unable to export, epiq root not found");let v=new Date,x=rf(v),C=`board_${sf(d.title)}_${x}.md`,A=Ri(p.value);Ic.mkdirSync(A,{recursive:!0});let T=ef.join(A,C),_=`# Board - ${d.title}
45
+ `)}`):(yp(),E({hasProjectDefinition:!0}),c("State booted successfully",null))}var so,bp,rr=y(()=>{"use strict";We();te();C();Xt();w();xn();xt();Sn();so=vp();bp=()=>{let e=Fe();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"}});var G,Rs=y(()=>{"use strict";C();G=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});var mt,sr,xp,Va,Cs=y(()=>{"use strict";qa();rr();Jt();nt();te();C();w();ir();Rs();Ss();mt=null,sr=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!mt,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),mt)return logger.debug("[sync] syncAndReloadState joining existing promise"),mt;logger.debug("[sync] syncAndReloadState creating promise"),mt=xp();try{let e=await mt;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:g().syncStatus?.status,statusMessageAfterResolve:g().syncStatus?.msg}),a(e)&&g().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),E({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),mt||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),mt=null}},xp=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=Va();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(mt)return mt;logger.debug("[sync] syncAndReloadState:start");let t=G("resolveActorId",ae());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),i("Unable to resolve event log path");E({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:g().syncStatus});let n=Qt(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let o=G("syncEpiqWithRemote",await ar({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(o),message:(a(o),o.message)}),a(o))return logger.error("[sync] syncAndReloadState:sync failed",o.message),E({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),Ye(`Unable to sync state. ${o.message}`);let{stateBranchRoot:r}=o.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:r});let s=G("loadMergedEvents",Ge(r));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(s),message:(a(s),s.message),count:a(s)?void 0:s.value.length}),a(s))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:g().syncStatus}),i(`Unable to load events. ${s.message}`);logger.debug("[sync] loaded merged events after sync",{count:s.value.length});let d=Va();if(d)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:d.message,syncStatus:g().syncStatus}),d;let l=Wa(),u=g().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:l,selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id,selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual}),!g().selectedNode?.isVirtual&&!g().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:s.value.length});let p=G("bootStateFromEventLog",An(s.value));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(p),message:(a(p),p.message)}),a(p))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:g().syncStatus}),i(`Unable to boot synced state. ${p.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:g().selectedNode?.isVirtual,contextNodeIsVirtual:g().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),E({filters:u}),logger.debug("[sync] restoreNavigationAnchor:start");let m=G("restoreNavigationAnchor",Ka(l));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(m),message:a(m)?m.message:"Navigation restored",selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id}),a(m)?(E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),m):(E({hasProjectDefinition:!0,syncStatus:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),c("Synced",!0))},Va=()=>g().mode===f.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),E({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),i("Will not re-materialize if not in default mode, to not lose edit data"))});var Tn,Ga,Ya,As,Ts,io,ws,Ip,Xa,Ep,Ja,dr=y(()=>{"use strict";C();Le();w();Cs();Tn=3e3,Ga=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Tn?null:t},Ya=0,Ts=!1,io=!1,ws=()=>{if(Ts)return!0;let e=Fe();return a(e)?!1:e.value.syncStatus.status==="syncing"},Ip=()=>{let e=ie().autoSyncIntervalMs??1e4,t=Date.now()-Ya;return Math.max(0,e-t)},Xa=()=>{As||(As=setTimeout(async()=>{if(As=void 0,!!tn()){if(ws()){io=!0;return}io=!1,await Ep()}},Ip()))},Ep=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return i("Cannot auto-sync while peeking");if(!tn())return i("Cannot auto-sync before state is initialized");if(ws())return io=!0,i("Sync already in progress");Ts=!0,Ya=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await sr()}finally{Ts=!1,io&&Xa()}},Ja=()=>{tn()&&(io=!0,!ws()&&Xa())}});var cr,Qa,Za,ed,ao=y(()=>{"use strict";C();Lt();Le();ue();cr=()=>{let e=ie(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),o=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&o,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:o}},Qa=()=>{let e=Ze(process.cwd());if(a(e))return!1;let t=ht(e.value);return vt(t)},Za=e=>e===!0?"on":e===!1?"off":null,ed=e=>e==="on"?!0:e==="off"?!1:null});var Np,Rp,Ot,Ut,lr,ur,co=y(()=>{"use strict";se();C();ce();w();Np=e=>e.props.tags??[],Rp=e=>e.props.assignees??[],Ot=e=>Np(e).map(t=>I.getTag(t)).filter(t=>!!t),Ut=e=>Rp(e).map(t=>I.getContributor(t)).filter(t=>!!t),lr=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!L(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",Ot(n))},ur=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!L(n)?i("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",Ut(n))}});var h,nn=y(()=>{"use strict";h={PALETTE:"?",EXIT:"exit",INIT:"init",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",COFFEE:"coffee",NONE:""}});var Cp,Sp,Ap,Tp,wp,on,td,mr,pr,nd,Mp,Ms,lo=y(()=>{"use strict";Cp=/^(\d+)(h|d|w|mo|y)$/,Sp=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Ap=({year:e,month:t,day:n,hour:o=0,minute:r=0})=>{let s=new Date(e,t-1,n,o,r);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===o&&s.getMinutes()===r},Tp=(e,t=new Date)=>{let n=e.match(Cp);if(!n)return null;let[,o,r]=n,s=Number(o);if(!Number.isInteger(s)||s<=0)return null;let d=new Date(t);switch(r){case"h":return d.setHours(d.getHours()-s),d;case"d":return d.setDate(d.getDate()-s),d;case"w":return d.setDate(d.getDate()-s*7),d;case"mo":return d.setMonth(d.getMonth()-s),d;case"y":return d.setFullYear(d.getFullYear()-s),d;default:return null}},wp=e=>{let t=e.match(Sp);if(!t)return null;let[,n,o,r,s,d]=t,l=Number(n),u=Number(o),m=Number(r),p=s?Number(s):0,v=d?Number(d):0;return Ap({year:l,month:u,day:m,hour:p,minute:v})?new Date(l,u-1,m,p,v):null},on=e=>{let t=e.trim().toLowerCase();return Tp(t)??wp(t)},td=/^(\d+)(s|m)?$/,mr=e=>{let t=e.trim().toLowerCase().match(td);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},pr=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),o=n.length>0&&td.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:o}},nd=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Mp=[{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}],Ms=(e=Mp)=>{let t=[];for(let{unit:n,from:o,to:r}of e)for(let s=o;s<=r;s++)t.push(`${s}${n}`);return t}});var Lp,oe,He,ye,kp,Pp,ks,Ps,sd,rn,gr,Ls,od,Dp,Fp,uo,rd,Bp,Op,Up,pe,_t=y(()=>{"use strict";dr();ao();Sn();se();ce();w();Go();co();nn();lo();Lp=["BOARD","TICKET","SWIMLANE","COMMENT"],oe={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},He={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},ye={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},kp=[oe.EDITOR,oe.VIEW,oe.USERNAME,oe.AUTOSYNC,oe.SYNC_DEBOUNCE_MS,oe.ATTACHMENT_MAX_KB,oe.LOG_LEVEL],Pp=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[He.TITLE,He.DESCRIPTION];case"BOARD":case"SWIMLANE":return[He.TITLE];case"COMMENT":return[He.COMMENT];default:return[]}},ks=[String(Tn),"5000","15000","30000","60000"],Ps=["250","500","1000"],sd=["10s","20s","30s","45s"],rn=[h.COFFEE,h.EXIT,h.SYNC,h.HELP,h.EXPORT,h.CONFIG,h.YANK],gr=[h.NEW,h.EDIT,h.DELETE,h.MOVE],Ls=[h.TAG,h.UNTAG,h.ASSIGN,h.UNASSIGN,h.CLOSE_ISSUE,h.RE_OPEN_ISSUE,h.EDIT,h.COMMENT],od=[h.FILTER,h.PEEK,h.REPLAY],Dp={WORKSPACE:[...rn,...gr],BOARD:[...od,...rn,...gr],SWIMLANE:[...od,...rn,...gr],TICKET:[...rn,...gr,...Ls],FIELD:[...rn,...Ls],FIELD_LIST:[...rn,...Ls],TEXT:[...rn],COMMENT:[h.EDIT,h.DELETE,h.YANK]},Fp=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],uo=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&L(n)),rd=e=>e.parentNodeId===he,Bp=({selectedNode:e,breadCrumb:t})=>{let n=Pp(e?.context);return uo({breadCrumb:t,selectedNode:e})?n.includes(He.DESCRIPTION)?n:[...n,He.DESCRIPTION]:n},Op=({selectedNode:e,breadCrumb:t})=>{let n=uo({breadCrumb:t,selectedNode:e});return n?[ye.REF,ye.TITLE,...n.props?.description?.trim()?[ye.DESCRIPTION]:[],...Ot(n).length>0?[ye.TAGS]:[],...Ut(n).length>0?[ye.ASSIGNEES]:[]]:e?[ye.REF,ye.TITLE]:[]},Up=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:o}=cr();if(!o)return[h.HELP,h.CONFIG];if(!Qa())return[h.HELP,h.INIT];if(t)return[h.HELP,h.PEEK,h.REPLAY,h.EXPORT,h.CONFIG,h.YANK];let r=e?.context,s=r&&Lp.includes(r),d=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?Dp[u]:[]))],l=uo({breadCrumb:n,selectedNode:e});return d.filter(u=>u===h.MOVE?!1:u===h.YANK?!!(l??e):u===h.EDIT?s||!!l:u===h.DELETE?s:u===h.UNTAG?!!(l&&Ot(l).length>0):u===h.UNASSIGN?!!(l&&Ut(l).length>0):u===h.RE_OPEN_ISSUE?!!(l&&rd(l)):u===h.CLOSE_ISSUE?!!(l&&!rd(l)):!0)},pe=(e,{contextNode:t,selectedNode:n,readOnly:o,breadCrumb:r}=g())=>{let s=t.context??"WORKSPACE";return{[h.NONE]:Up({breadCrumb:r,readOnly:o,selectedNode:n}),[h.EXIT]:["confirm"],[h.EXPORT]:[],[h.SYNC]:[],[h.INIT]:[],[h.HELP]:[],[h.PEEK]:[...Ms(),"now","prev","next"],[h.REPLAY]:[...Ms()],[h.EDIT]:Bp({selectedNode:n,breadCrumb:r}),[h.YANK]:Op({selectedNode:n,breadCrumb:r}),[h.COMMENT]:[],[h.DELETE]:["confirm"],[h.RE_OPEN_ISSUE]:["confirm"],[h.CLOSE_ISSUE]:["confirm"],[h.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[h.FILTER]:["tag","assignee","description","title","ref","clear"],[h.TAG]:[...new Set([...Object.keys(Nn),...I.getExistingTags()])],[h.UNTAG]:[...lr()?.value?.map(({name:l})=>l)??[]],[h.UNASSIGN]:[...ur()?.value?.map(({name:l})=>l)??[]],[h.ASSIGN]:I.getExistingAssignees(),[h.NEW]:Fp(s),[h.CONFIG]:[...kp],[h.COFFEE]:["1","3","5","20","custom"]}[e]??[]}});var id,ad=y(()=>{"use strict";id=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{decodeTime as dd}from"ulid";var cd,sn,mo=y(()=>{"use strict";C();cd=e=>{try{return c("Decoded date",new Date(dd(e)))}catch(t){return i("Decoding failed + "+t.message)}},sn=e=>{if(!e?.id)return null;try{return dd(e.id)}catch{return null}}});import{accessSync as _p,copyFileSync as $p,existsSync as fr,mkdirSync as ld,readdirSync as ud,readFileSync as jp,renameSync as Wp,rmSync as Hp,statSync as md,unlinkSync as Kp,writeFileSync as qp}from"node:fs";import wn from"node:path";var Ds,Be,vr=y(()=>{"use strict";Ds=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Be={writeToFile:(e,t)=>{try{let n=wn.dirname(e);fr(n)||ld(n,{recursive:!0});let o=typeof t=="string"?t:JSON.stringify(t,null,2);qp(e,o,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return jp(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Be.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 fr(e)&&md(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await _p(e),!0}catch{return!1}},mkDir:e=>ld(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=wn.parse(t);for(;;){let o=wn.join(t,e);try{if(fr(o)&&md(o).isDirectory())return o}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=wn.dirname(t)}return null},readFirstJSON(e){try{if(!Be.dirExists(e))return null;let t=ud(e).filter(o=>o.endsWith(".json")).sort()[0];if(!t)return null;let n=wn.join(e,t);return Be.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Be.dirExists(e)?ud(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Kp(e)}catch(t){(!Ds(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Hp(e,{recursive:!0,force:!0})}catch(t){(!Ds(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(wn.dirname(t)),!n?.overwrite&&fr(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Wp(e,t)}catch(o){if(Ds(o)&&o.code==="EXDEV"){$p(e,t),this.rmFile(e);return}throw o}}}});import zp from"node:path";import{z as Et}from"zod";var Vp,pd,Gp,gd,Fs,Bs,Yp,fd,vd,Xe,hd,an=y(()=>{"use strict";ue();C();vr();Vp={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},pd=Et.object({logLevel:Et.enum(["info","error","debug"]),preferredEditor:Et.string().optional(),userName:Et.string().optional(),userId:Et.string().optional(),autoSync:Et.boolean().nullable().optional(),autoSyncDebounceMs:Et.number().optional(),attachmentMaxKb:Et.number().optional(),viewMode:Et.enum(["dense","wide"]).optional()}).partial(),Gp="config.json",gd=jn,Fs=()=>zp.join(gd(),Gp),Bs=()=>{try{return Be.mkDir(gd()),c(`Ensured ~/${Qe} exists`,null)}catch{return i(`Unable to create ~/${Qe}`)}},Yp=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${Qe}/config.json JSON`)}let n=pd.safeParse(t??{});return n.success?c("Parsed config",n.data):i(`Invalid ~/${Qe}/config.json shape: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},fd=()=>{let e=Bs();if(a(e))return i(e.message);let t=Fs(),n=Be.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Yp(n)},vd=e=>{let t=Bs();if(a(t))return i(t.message);let n=pd.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`);let o=Fs();try{return Be.writeToFile(o,JSON.stringify(n.data,null,2)+`
46
+ `),c("Config written",null)}catch{return i(`Unable to write ~/${Qe}/config.json`)}},Xe=e=>{let t=fd();if(a(t))return i("Failed to read existing config");let n={...t.value,...e};return vd(n)},hd=()=>{let e=Fs(),t=Bs();if(a(t))return i(`Unable to create ~/${Qe}`);if(!(Be.readFile(e)!==null)){let x=vd(Vp);if(a(x))throw new Error(`Unable to create ~/${Qe}/config.json`)}let o=fd();if(a(o))throw new Error(o.message||"Unable to load settings");let{preferredEditor:r,userName:s,userId:d,autoSync:l,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:v}=o.value;return!s||!d?i(`User name or ID not configured in ~/${Qe}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,c("successfully loaded settings",{logLevel:p??"debug",preferredEditor:r??"",userName:s,userId:d,autoSync:l??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:v??"dense"}))}});var po,Os,go=y(()=>{"use strict";ut();C();ue();po=500,Os=(e,t)=>`${e}.${t}`});import Xp from"zod";var fo,vo,yd,Us=y(()=>{"use strict";an();go();te();C();be();Le();w();fo=50,vo=5e3,yd=()=>{let e=Q().commandMeta.inputString,t=Xp.coerce.number().int().min(fo).max(vo).safeParse(e);if(!t.success)return i(`Attachment size cap must be ${fo}-${vo} KB (default ${po})`);let n=Xe({attachmentMaxKb:t.data});return a(n)?n:(Ve({attachmentMaxKb:t.data}),E({mode:f.DEFAULT}),c(`Attachment size cap set to ${t.data} KB`,null))}});var hr=y(()=>{"use strict"});import bd from"chalk";var Z,Ne,Re,xd=y(()=>{"use strict";yt();Pe();Z=e=>bd.dim(e),Ne=e=>bd.hex(R.primary)(e),Re=({prefix:e="",wordList:t,postfix:n="",noOfHints:o=100,inputString:r,minLengthForHints:s=1})=>{let d=r.trim();if(d.length<s)return"";let p=[...t.filter(Boolean).filter(v=>v.startsWith(d))].sort((v,x)=>Yo(v)-Yo(x)).slice(0,o).map(v=>Xo(v)).join(" ");return p?`${Z(e)}${p}${Z(n)}`:""}});var $t,yr=y(()=>{"use strict";$t={None:"none",Invalid:"invalid",Valid:"valid"}});import Nd from"chalk";var Jp,Id,re,q,O,xr,Ed,br,_s,Qp,dn,Zp,eg,tg,ng,Rd,Cd=y(()=>{"use strict";dr();ao();ad();mo();ut();C();ce();Le();Us();go();w();yt();hr();co();Cn();xd();nn();yr();_t();lo();Jp=["BOARD","TICKET","SWIMLANE"],Id=()=>{let e=g().selectedNode;if(!e?.context)return O({message:Z("Missing target context")});if(Jp.includes(e.context))return q();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===Ee(t?.parentNodeId??"","comments"))return q()}return O({message:Z("Command not available in this context")})},re="<ENTER> to confirm",q=(e="",t=[])=>({message:Z(e),validity:$t.Valid,completionWordList:t}),O=({message:e,completionWordList:t=[]})=>({validity:$t.Invalid,message:e,completionWordList:t}),xr=e=>e.length===0,Ed=(e,t)=>{let n=je(g().breadCrumb,"BOARD");if(a(n))return O({message:Ne("Command is not applicable in this context")});let o=cd(n.value.id);return a(o)?O({message:Ne(`Unable to ${t}: board id is not a valid ULID`)}):nd({date:e,horizonDate:o.value})?null:O({message:Ne(`nothing to ${t} before ${o.value.toISOString().slice(0,16).replace("T"," ")}`)})},br=e=>` ${Nd.hex("#000").bgHex(De(e))(` ${e} `)} `,_s=({modifier:e})=>{let t="confirm";return e===t?q(re):O({message:xr(e)?Z("if you are certain, enter ")+Xo(t):"",completionWordList:[t]})},Qp=({list:e,hint:t,onValue:n})=>({modifier:o,inputString:r})=>e.includes(o)?r.trim().length<1?O({message:Z(n)}):q():O({message:xr(o)?t:"",completionWordList:[...e]}),dn=({hint:e,onOk:t})=>({modifier:n,inputString:o})=>xr(n)&&xr(o)?O({message:e,completionWordList:[]}):q(t??re),Zp=({modifier:e,inputString:t})=>{let n=pe(h.CONFIG);if(!n.includes(e))return O({message:Re({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case oe.EDITOR:{let o=[...id];return t.trim()?o.includes(t.trim())?q(re):O({message:Re({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o}):O({message:Re({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case oe.VIEW:{let o=["dense","wide"];return o.includes(t.trim())?q(re):O({message:Re({prefix:"view... ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case oe.USERNAME:return t.trim()?q(re):O({message:Ne("Enter a user name. Saved in ")+Nd.bgBlack("~/.epiq-global/config.json")});case oe.LOG_LEVEL:{let o=["debug","error","info"],r=t.trim();return o.includes(r)?q(re):O({message:Re({prefix:"one of: ",wordList:[...o],inputString:r,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...o]})}case oe.AUTOSYNC:{let o=["on","off"],r=ie().autoSync;if(!o.includes(t.trim())){let s=Za(r);return O({message:Re({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:o,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:o})}return q(re)}case oe.ATTACHMENT_MAX_KB:{let o=ie().attachmentMaxKb,r=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(r)||r<fo||r>vo){let s=Re({prefix:" examples: ",wordList:Ps,minLengthForHints:0,inputString:t});return O({message:Ne(`provide a size cap in KB (${fo}-${vo}). current: ${o??po} KB.`)+s,completionWordList:Ps})}return q(re)}case oe.SYNC_DEBOUNCE_MS:{let o=ie().autoSyncIntervalMs,r=Ga(t);if(!t.trim()||r===null||r<Tn){let s=Re({prefix:" examples: ",wordList:ks,minLengthForHints:0,inputString:t});return O({message:Ne(`provide duration above ${Tn}ms. current duration: ${o}ms.`)+s,completionWordList:ks})}return q(re)}default:return O({message:Ne("Unknown config option"),completionWordList:n})}},eg=({modifier:e,inputString:t})=>{let n=pe(h.EDIT);if(!n.length)return O({message:Ne("Command not available in this context")});if(!n.includes(e)){let o=Re({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return O({message:o||Ne("Unknown edit option"),completionWordList:n})}switch(e){case He.COMMENT:return t.trim()?q(re):O({message:Z("write a comment...")});case He.TITLE:return q(re);case He.DESCRIPTION:{let{preferredEditor:o}=ie();return o?q(Z("<ENTER> to edit in ")+o):O({message:"No editor selected"})}default:return O({message:Ne("Unknown edit option"),completionWordList:n})}},tg=({modifier:e})=>{let t=pe(h.YANK);return t.length?t.includes(e)?q(re+Z(" and copy to clipboard")):O({message:Re({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):O({message:Ne("Nothing selected to copy from")})},ng={[h.EXPORT]:()=>q(re+Z(", and create export markdown file")),[h.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return q(re);let n={message:Z("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},o=t||e.inputString.trim(),r=on(o);if(!o||!r)return O(n);let s=Ed(r,"peek");return s||q(re)},[h.REPLAY]:e=>{let{dateInput:t,durationInput:n}=pr(e.modifier,e.inputString),o={message:Z("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},r=on(t);if(!t||!r)return O(o);let s=Ed(r,"replay");return s||(n&&mr(n)===null?O({message:Ne("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):q("<ENTER> to replay board history",n?sd:[]))},[h.EXIT]:()=>q(re+Z(" and exit the application")),[h.INIT]:()=>q(re),[h.PALETTE]:()=>q(re),[h.FILTER]:e=>{if(e.modifier==="clear")return q(re);let t=s=>pe(h.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return O({message:Re({wordList:pe(h.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:pe(h.FILTER)});let n=Object.values(g().tags).map(s=>s.name),o=Object.values(g().contributors).map(s=>s.name),r=e.modifier==="tag"?n:e.modifier==="assignee"?o:[];return e.inputString?r.length&&!r.includes(e.inputString.trim())?O({message:Re({prefix:`existing ${e.modifier}s... `,wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r}):q():O({message:Re({prefix:"one of... ",wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r})},[h.NONE]:e=>{let t=pe(h.NONE);return O({message:Re({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[h.NEW]:e=>Qp({list:pe(h.NEW),hint:Re({wordList:pe(h.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[h.HELP]:()=>q(re),[h.EDIT]:eg,[h.COMMENT]:e=>{let t=dn({hint:Z(`write a comment (max ${4e3} char)...`),onOk:Z(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===$t.Invalid?t:e.inputString.length>4e3?q(Ne("max input exceeded")):t},[h.CONFIG]:Zp,[h.YANK]:tg,[h.DELETE]:e=>{let t=Id();return t.validity==="invalid"?t:_s(e)},[h.CLOSE_ISSUE]:e=>_s(e),[h.RE_OPEN_ISSUE]:e=>_s(e),[h.MOVE]:e=>{let t=Id();return t.validity==="invalid"?t:dn({hint:Re({prefix:"hey hacker! These commands are blocked for you... ",wordList:pe(h.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[h.TAG]:e=>{let n=I.getExistingTags().slice(0,10).map(br).join("");return dn({hint:n.length?Z("create tag or reuse:")+n+Z(""):Z("create tag ...")})(e)},[h.UNTAG]:e=>{let t=lr();if(a(t))return O({message:Ne("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(br).slice(0,10);return n.length?dn({hint:Z(" ... ")+n.join("")})(e):O({message:Ne("Issue has no tags"),completionWordList:[]})},[h.ASSIGN]:e=>{let t=I.getExistingAssignees().map(br).slice(0,10);return dn({hint:Z("assignees... ")+t.join("")})(e)},[h.UNASSIGN]:e=>{let t=ur();if(a(t))return O({message:Ne("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(br).slice(0,10);return n.length?dn({hint:Z("remove assignee... ")+n.join("")})(e):O({message:Ne("Issue has no assignees"),completionWordList:[]})},[h.SYNC]:()=>q(re),[h.COFFEE]:e=>{let{modifier:t}=e,n=pe(h.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?O({message:Z("enter an amount ... "),completionWordList:n.filter(o=>o.startsWith(t))}):dn({hint:Re({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},Rd=Object.fromEntries(Object.entries(ng).map(([e,t])=>[e,{validate:(n,o,r)=>t({modifier:o,command:n,inputString:r})}]))});var Ir,Sd=y(()=>{"use strict";Ir=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"]});var og,rg,sg,ig,ag,Ad,Td,wd,Md=y(()=>{"use strict";C();w();Sd();og=3,rg=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),sg=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let o=n.props;typeof o.description=="string"&&t.push(o.description),typeof o.value=="string"&&t.push(o.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},ig=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=og&&!rg.has(t)&&!/^\d+$/.test(t)),ag=e=>{let t=new Map;for(let s of sg(e))for(let d of ig(s))t.set(d,(t.get(d)??0)+1);let n=[...t.entries()].sort((s,d)=>d[1]-s[1]||s[0].localeCompare(d[0])).map(([s])=>s),o=new Set(n),r=Ir.filter(s=>!o.has(s));return[...n,...r]},Ad=Ir,Td=-1,wd=()=>{let e=Fe();if(a(e))return Ir;let t=e.value,n=t.eventLog.length;return n!==Td&&(Ad=ag(t),Td=n),Ad}});var Ld,kd,$s=y(()=>{"use strict";da();_t();nn();Cd();Md();w();te();Ld=e=>Object.values(h).includes(e),kd=(e,t)=>{let n=e.command??"",{modifier:o,target:r,inputString:s}=e,{message:d,validity:l,completionWordList:u}=Rd[n].validate(n,o,s),m=n!==h.PEEK&&n!==h.REPLAY,p=r==="command"||r==="modifier"?pe(n):m?wd():[],{mode:v}=g(),x=v===f.COMMAND_LINE?d??"":"",S=[...u,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:x,autoCompletion:t?aa(e,S):{hint:"",hints:[],remainder:"",overlap:0}}}});var Pd,dg,cg,lg,Dd=y(()=>{"use strict";$s();_t();Pd=e=>{let t=e.trimStart(),n=cg(t),o=n[0]??"",r=n[1]??"",s=/\s$/.test(e),d=lg(e),l=Ld(o)?o:null,u=l!==null,m=o!=="",p=l?pe(l)??[]:[],v=l&&p.includes(r)?r:"",x="word";n.length===0||n.length===1&&!s?x="command":(n.length===1&&s||n.length===2&&!s)&&(x="modifier");let S=s?"":d,A=dg(t,l,v);return{raw:e,trimmedStart:t,words:n,firstWord:o,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:s,modifier:v,target:x,inputToMatch:S,inputString:A}},dg=(e,t,n)=>{let o=e;return t&&o.startsWith(t)&&(o=o.slice(t.length)),o=o.replace(/^\s+/,""),n&&o.startsWith(n)&&(o=o.slice(n.length),o=o.replace(/^\s+/,"")),o},cg=e=>e.trim()?e.trim().split(/\s+/):[],lg=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as HE}from"react";var Mn,js,Ln,ug,Fd,pt,ho,Ws,Hs,Bd,Od,Er,Ud,H,_d,$d,jd,Q,Wd,be=y(()=>{"use strict";$s();Dd();C();yr();Mn=e=>e===js||e===":",js=" ",Ln={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:$t.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},ug=new Set,Fd=()=>{for(let e of ug)e()},pt=e=>{let n=e(Ln),o=Pd(n.value),r=n.cursorPosition===n.value.length;Ln={...n,commandMeta:kd(o,r)},Fd()},ho=({message:e,status:t})=>{let n=structuredClone(Ln);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Ln=n,Fd(),c(e,null)},Ws=e=>{pt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Hs=e=>{pt(t=>{let{value:n,cursorPosition:o}=t,r=o;if(e==="left"){for(;r>0&&Mn(n[r-1]);)r--;for(;r>0&&!Mn(n[r-1]);)r--}else{for(;r<n.length&&!Mn(n[r]);)r++;for(;r<n.length&&Mn(n[r]);)r++}return{...t,cursorPosition:r}})},Bd=()=>{pt(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}})},Od=()=>{pt(e=>{let{value:t,cursorPosition:n}=e,o=n;for(;o>0&&Mn(t[o-1]);)o--;for(;o>0&&!Mn(t[o-1]);)o--;let r=t.slice(n);return{...e,value:t.slice(0,o)+r,cursorPosition:o,commandIsPending:!1}})},Er=e=>{pt(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),o=t.value.slice(0,n),r=t.value.slice(n),s=e(o,t.commandMeta.autoCompletion),d=s+r,l=Math.max(0,Math.min(s.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},Ud=()=>{pt(e=>({...e,commandIsPending:!0}))},H=e=>{pt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},_d=({addToHistory:e=!0})=>{pt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},$d=()=>{pt(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}})},jd=()=>{pt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},Q=()=>Ln,Wd=()=>{let[e,...t]=Ln.value.split(js);return t.join(js).trim()}});var M,Gt=y(()=>{"use strict";te();ea();w();be();Le();M={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"}});var Hd,P,Ks=y(()=>{"use strict";w();nn();Hd=e=>{let{context:t}=g().contextNode;if(!t)return P.None;switch(e){case h.EXIT:return P.Exit;case h.EXPORT:return P.Export;case h.COFFEE:return P.Coffee;case h.INIT:return P.Init;case h.DELETE:return P.Delete;case h.EDIT:return P.Edit;case h.COMMENT:return P.Comment;case h.HELP:return P.ViewHelp;case h.RE_OPEN_ISSUE:return P.ReopenIssue;case h.CLOSE_ISSUE:return P.CloseIssue;case h.TAG:return P.TagTicket;case h.UNTAG:return P.UntagTicket;case h.ASSIGN:return P.AssignUserToTicket;case h.UNASSIGN:return P.UnassignUserFromTicket;case h.NEW:return P.NewItem;case h.FILTER:return P.Filter;case h.MOVE:return P.Move;case h.PEEK:return P.Peek;case h.REPLAY:return P.Replay;case h.CONFIG:return P.Config;case h.YANK:return P.Yank;case h.SYNC:return P.Sync;default:return P.None}},P={Exit:"exit",Init:"init",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export",Coffee:"coffee"}});import{Text as Kd}from"ink";import qd,{useEffect as zd,useState as mg}from"react";var Vd,Oe,kn=y(()=>{"use strict";w();Pe();Vd={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Oe=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Ue(),o=Vd[n]??Vd.default,[r,s]=mg(0);if(zd(()=>{s(0)},[o]),zd(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%o.length)},500);return()=>clearInterval(l)},[e,o]),!e)return qd.createElement(Kd,null,t);let d=o[r]??o[0]??t;return qd.createElement(Kd,{color:R.accent,dimColor:r===1},d)}});import{Box as qs,Text as pg}from"ink";import Nr from"react";var jt,yo=y(()=>{"use strict";Pe();jt=({children:e=[],height:t,selectedIndex:n,itemHeight:o=1,scrollByOne:r=!1})=>{if(e.length===0)return null;let s=Math.max(1,Math.floor(t)),d=Math.max(1,Math.ceil(o)),l=Math.max(1,Math.floor(s/d)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(0,e.length-l),p=r?Math.min(m,Math.max(0,u-l+1)):Math.min(m,Math.floor(u/l)*l),v=p+l,x=e.slice(p,v),S=e.length>l,A=s,T=S?Math.max(1,Math.floor(l/e.length*A)):A,_=Math.max(0,A-T),z=Math.max(1,e.length-l),K=S?Math.floor(p/z*_):0;return Nr.createElement(qs,{flexDirection:"row",height:s,width:"100%"},Nr.createElement(qs,{flexDirection:"column",flexGrow:1,height:s},x),Nr.createElement(qs,{flexDirection:"column",width:1,height:A},Array.from({length:A}).map((U,Se)=>Nr.createElement(pg,{key:Se,color:S&&Se>=K&&Se<K+T?R.accent:R.secondary},S?"\u2502":" "))))}});var Pn,Gd,Rr,Yd,Dn,Xd,Fn=y(()=>{"use strict";w();vs();Pn=(e,t)=>t?e&&oo(e)===t?e:t:e,Yd=()=>{let{eventLog:e=[]}=g();if(Rr&&Gd===e)return Rr;let t=new Map,n=new Set;for(let o of e)o?.userId&&(n.add(o.userId),o.userName&&t.set(o.userId,o.userName));return Gd=e,Rr={latestNames:t,authors:n},Rr},Dn=(e,t)=>{let{contributors:n={}}=g();return n[e]?.tombstoned?t:Pn(t,Yd().latestNames.get(e))??t},Xd=e=>Yd().authors.has(e)});import{Text as gg}from"ink";import fg from"react";var vg,hg,Bn,Cr=y(()=>{"use strict";Go();yt();ce();Fn();vg=e=>e.toLowerCase().trim(),hg=(e,t=Nn)=>{let n=vg(e);return t[n]?t[n]:to(n)},Bn=({id:e,isSelected:t})=>{let n=I.getContributor(e);if(!n)return;let o=Dn(e,n.name);return fg.createElement(gg,{underline:t,color:hg(o)},"@"+o,Xd(e)?"":"\u2197")}});import{Text as yg}from"ink";import bg from"react";var Sr,zs=y(()=>{"use strict";ce();Pe();yt();Sr=({id:e,isSelected:t})=>{let n=I.getTag(e);if(n)return bg.createElement(yg,{underline:t,backgroundColor:De(n.name),color:R.secondary}," "+n.name+" ")}});import{useEffect as xg,useState as Ig}from"react";var Eg,Jd,Ar,bo,Ng,Rg,On,Tr=y(()=>{"use strict";yt();Eg=80,Jd=1400,Ar=new Set,bo=null,Ng=e=>(Ar.add(e),bo||(bo=setInterval(()=>{for(let t of Ar)t()},Eg)),()=>{Ar.delete(e),Ar.size===0&&bo&&(clearInterval(bo),bo=null)}),Rg=()=>{let e=Date.now()%Jd/Jd;return e<.5?e*2:(1-e)*2},On=e=>{let[,t]=Ig(0);return xg(()=>{if(e)return Ng(()=>t(n=>n+1))},[e]),ya(Rg())}});import{Box as Un,Text as wr}from"ink";import Je from"react";var Cg,Qd,Zd=y(()=>{"use strict";Pe();yn();En();co();Cr();zs();Tr();Cg=(e,t)=>{if(e.length<=t)return[e,null];let n=e.lastIndexOf(" ",t),o=n>0?n:t;return[e.slice(0,o),eo(e.slice(o).trim(),t)]},Qd=({width:e,ticket:t,isSelected:n,isFlashing:o=!1})=>{let r=On(o),s=e-4,[d,l]=Cg(ze(t.title),s),u=l?null:eo(ze(t.props.description),s)||null,m=Ot(t),p=Ut(t);return Je.createElement(Un,{borderStyle:"round",height:5,flexDirection:"column",borderDimColor:!n,borderColor:o?r:n?R.accent:R.secondary,justifyContent:"space-between"},Je.createElement(Un,{paddingLeft:1,flexDirection:"column"},Je.createElement(wr,{color:R.primary},d),l&&Je.createElement(wr,{color:R.primary},l),u&&Je.createElement(wr,{color:R.secondary2,dimColor:!0},u)),Je.createElement(Un,{flexDirection:"row",justifyContent:"space-between",paddingLeft:1,paddingRight:1},Je.createElement(Un,{flexDirection:"row"},m.map(v=>Je.createElement(Un,{paddingRight:1,key:v.id},Je.createElement(Sr,{key:v.id,id:v.id}))),p.map(v=>Je.createElement(Un,{paddingRight:1,key:v.id},Je.createElement(Bn,{key:v.id,id:v.id})))),Je.createElement(wr,{wrap:"truncate",color:R.secondary2,dimColor:!0},tt(t.id))))}});import{Box as cn,Text as xo}from"ink";import Ke from"react";var Sg,ec,tc=y(()=>{"use strict";te();ce();Fn();Pe();yt();kn();Tr();Sg=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,ec=({width:e,ticket:t,isSelected:n,isFlashing:o=!1,index:r,mode:s})=>{let d=On(o),l=(t.props.tags??[]).map(U=>I.getTag(U)).filter(U=>!!U),u=(t.props.assignees??[]).map(U=>I.getContributor(U)).map(U=>U&&{...U,name:Dn(U.id,U.name)}).filter(U=>!!U),m=1,p=l.length*(1+m),v=u.length*(2+m),x=l.map(U=>Ke.createElement(cn,{key:U.id,paddingRight:m},Ke.createElement(xo,{color:De(U.name)},"\u25A0"))),S=u.map(U=>Ke.createElement(cn,{key:U.id,paddingRight:m},Ke.createElement(xo,{color:to(U.name)},"@"+U.name.at(0)))),A=o?d:n?R.accent:s===f.MOVE?R.secondary:R.primary,T=4,_=I.getCommentsByIssue(t.id),z=_.length?String(_.length).length+2+m:0,K=_.length?Ke.createElement(cn,{paddingRight:m},Ke.createElement(xo,{color:R.accent},"[",_.length,"]")):null;return Ke.createElement(cn,{borderBottom:!0,justifyContent:"space-between"},Ke.createElement(cn,null,Ke.createElement(cn,{width:T},n?Ke.createElement(Oe,{isSelected:n}):Ke.createElement(xo,{color:"gray",dimColor:!0},r+1)),Ke.createElement(xo,{wrap:"truncate",color:A},Sg(t.title,e-p-v-z-18))),Ke.createElement(cn,null,x,S,K))}});import Ag from"chalk";import{Box as Vs,Text as Tg}from"ink";import gt from"react";var wg,nc,oc=y(()=>{"use strict";se();w();Pe();kn();yo();Zd();tc();Tr();wg=({swimlane:e,isSelected:t,width:n,height:o,isDense:r,isFocused:s,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u,replay:m}=Ue(),p=u[e.id]??[],v=m?new Set(m.flashNodeIds):null,x=v?.has(e.id)??!1,S=On(x),A=`${e.title} ${Ag.hex(R.secondary2).dim("("+p.length+")")}`,T=3,_=r?1:5,z=s&&d===-1,K=n-(z?7:5),U=o-T-(r?2:1),Se=gt.createElement(Vs,{borderStyle:"round",borderColor:R.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},gt.createElement(Oe,{isSelected:t}),gt.createElement(Tg,{bold:!0,color:x?S:t?R.accent:R.primary},A," ",e.readonly?"\u{1F512}":"")),pn=($,V)=>{let gn=s&&d===V;if(!L($))return null;let qt=v?.has($.id)??!1;return r?gt.createElement(ec,{key:$.id,index:V,width:n,ticket:$,isSelected:gn,isFlashing:qt,mode:l}):gt.createElement(Qd,{key:$.id,width:K,ticket:$,isSelected:gn,isFlashing:qt})};return gt.createElement(Vs,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?R.accent:R.secondary,paddingRight:1,paddingLeft:1,height:o},Se,gt.createElement(Vs,{padding:r?1:0},p.length>0&&gt.createElement(jt,{selectedIndex:d,height:U,itemHeight:_},p.map(pn)),z&&gt.createElement(Oe,{isSelected:!0})))},nc=gt.memo(wg)});var rc,sc,Gs=y(()=>{"use strict";Xt();rc=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},sc=(e,t,n)=>Ie.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0})});import{Box as _n,Text as Rt}from"ink";import Te,{useEffect as Mg,useMemo as Lg,useRef as kg}from"react";import{decodeTime as Ys}from"ulid";function ac({ticket:e,width:t,height:n}){let o=Lg(()=>Dg(e),[e]),r=kg([]);Mg(()=>(ic(r.current),r.current=Bg(e,o),()=>{ic(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=Ue(),l=Math.max(1,n-4),u=Math.max(12,t-32);return o.length===0?Te.createElement(_n,{flexDirection:"column",width:t,height:n,padding:1},Te.createElement(Rt,{color:R.primary},"No attachments yet."),Te.createElement(_n,{paddingTop:1},Te.createElement(Rt,{color:R.primary},"Attach images from the browser GUI"),Te.createElement(Rt,{color:R.accent}," epiq gui "),Te.createElement(Rt,{color:R.primary},"by dropping or pasting them."))):Te.createElement(_n,{flexDirection:"column",width:t,height:n},Te.createElement(_n,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:R.secondary,borderStyle:"single",paddingBottom:1},Te.createElement(Rt,{color:R.secondary2},"Attachments (",o.length,") \u2014 enter to open"," ")),Te.createElement(jt,{height:l,itemHeight:2,selectedIndex:s},o.map((m,p)=>{let v=p===s,x=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return Te.createElement(_n,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},Te.createElement(Rt,{color:R.accent},v?"\u276F ":" "),Te.createElement(_n,{paddingLeft:1},Te.createElement(Rt,{color:R.secondary2},`#${p+1} `),Te.createElement(Rt,{color:v?R.accent:R.primary},x),Te.createElement(Rt,{color:R.secondary2}," "+Og(m.bytes)+" "+Rn(Ys(m.id)))))})))}var Pg,Dg,ic,Fg,Bg,Og,dc=y(()=>{"use strict";We();Jo();se();C();ce();Xt();w();Pe();Cn();yo();Pg=e=>Ee(e,"attachments"),Dg=e=>I.getAttachmentsByIssue(e.id).sort((t,n)=>Ys(t.id)-Ys(n.id)),ic=e=>{for(let t of e)I.deleteNode(t.id)},Fg=(e,t,n)=>Ie.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),Bg=(e,t)=>{let n=I.getNode(Pg(e.id));if(!n||!_e(n))return[];let o=t.map((r,s)=>Fg(r,s,n.id)).map(r=>I.createNode(r)).filter(vt).map(({value:r})=>r).filter(_e);return t.length>0&&g().selectedIndex<0&&F.navigate({contextNode:n,selectedIndex:0}),o},Og=e=>`${Math.max(1,Math.round(e/1024))} KB`});import{Box as Wt,Text as Ct}from"ink";import xe,{useEffect as Ug,useMemo as _g,useRef as $g}from"react";import{decodeTime as Xs}from"ulid";function lc({ticket:e,width:t,height:n}){let o=_g(()=>Wg(e),[e]),r=$g([]);Ug(()=>(cc(r.current),r.current=Hg(e,o),()=>{cc(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=Ue(),l=Math.max(1,n-4),u=Math.max(20,t-8);return o.length===0?xe.createElement(Wt,{flexDirection:"column",width:t,height:n,padding:1},xe.createElement(Ct,{color:R.primary},"No comments yet."),xe.createElement(Wt,{paddingTop:1},xe.createElement(Ct,{color:R.primary},"Use"),xe.createElement(Ct,{color:R.accent}," :comment "),xe.createElement(Ct,{color:R.primary},"to add the first one."))):xe.createElement(Wt,{flexDirection:"column",width:t,height:n},xe.createElement(Wt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:R.secondary,borderStyle:"single",paddingBottom:1},xe.createElement(Ct,{color:R.secondary2},"Comments (",o.length,") ")),xe.createElement(jt,{height:l,itemHeight:4,selectedIndex:s},o.map((m,p)=>{let v=p===s;return xe.createElement(Wt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:R.secondary,borderStyle:"single"},xe.createElement(Wt,{flexDirection:"row",paddingBottom:1},xe.createElement(Ct,{color:R.accent},v?"\u276F ":" "),xe.createElement(Wt,{paddingLeft:1},xe.createElement(Ct,{color:R.secondary2},`#${p+1} `),xe.createElement(Bn,{id:m.authorId}),xe.createElement(Ct,{color:R.secondary2}," "+Rn(Xs(m.id))))),xe.createElement(Wt,{paddingLeft:3,paddingBottom:1},xe.createElement(Ct,{color:R.primary},Kg(m.md,u))))})))}var jg,Wg,cc,Hg,Kg,uc=y(()=>{"use strict";We();Jo();se();C();ce();w();Pe();Cn();Cr();yo();Gs();jg=e=>Ee(e,"comments"),Wg=e=>I.getCommentsByIssue(e.id).sort((t,n)=>Xs(t.id)-Xs(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),cc=e=>{for(let t of e)I.deleteNode(t.id)},Hg=(e,t)=>{let n=I.getNode(jg(e.id));if(!n||!_e(n))return[];let o=t.map((r,s)=>sc(r,s,n.id)).map(I.createNode).filter(vt).map(({value:r})=>r).filter(Zn);return t.length>0&&g().selectedIndex<0&&F.navigate({contextNode:n,selectedIndex:0}),o},Kg=(e,t)=>{let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`}});import{Box as Mr,Text as qg}from"ink";import St from"react";var mc,pc=y(()=>{"use strict";se();ce();In();w();Pe();Cr();kn();zs();mc=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:o}=Ue(),{title:r}=t,s=t.parentNodeId?I.getNode(t.parentNodeId):void 0,d=s&&L(s)?r===X.ASSIGNEES?s.props.assignees??[]:r===X.TAGS?s.props.tags??[]:[]:[];return St.createElement(Mr,{alignItems:"center",paddingTop:1},St.createElement(Mr,{minWidth:12},St.createElement(Oe,{isSelected:n}),St.createElement(qg,{color:n?R.accent:R.secondary2},r,":")),St.createElement(Mr,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=o.id===t.id&&u===e;return St.createElement(Mr,{key:`${r}-${l}`,paddingRight:2,minHeight:1},St.createElement(Oe,{isSelected:m}),r===X.ASSIGNEES?St.createElement(Bn,{isSelected:m,id:l}):r===X.TAGS?St.createElement(Sr,{isSelected:m,id:l}):null)})))}});import{Box as Lr,Text as Js}from"ink";import At,{useEffect as zg,useMemo as gc}from"react";var Vg,fc,Qs,vc,Gg,Zs,hc=y(()=>{"use strict";ce();C();Xt();w();Pe();yn();kn();yo();xn();Vg="\u2029",fc=(e,t)=>`${e}::inline-line::${t}`,Qs=new Map,vc=e=>{let t=Qs.get(e)??[];Qs.delete(e);for(let n of t)I.deleteNode(n)},Gg=(e,t)=>{vc(e);let n=[];t.forEach((o,r)=>{let s=$e(BigInt(r+1));if(!vt(s))return;let d=I.createNode(Ie.text({id:fc(e,r),name:`Line ${r+1}`,parentNodeId:e,rank:s.value,props:{value:o},readonly:!0,isVirtual:!0}));vt(d)&&n.push(d.value.id)}),Qs.set(e,n)},Zs=({id:e,label:t,text:n,height:o,selected:r,maxWidth:s})=>{let{selectedIndex:d,contextNode:l}=Ue(),u=gc(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=gc(()=>u.join("\0"),[u]);zg(()=>(Gg(e,u),()=>{vc(e)}),[e,m]);let p=x=>String(x).replace(/\r?\n/g,""),v=u.map((x,S)=>{let A=l.id===e&&d===S;return At.createElement(Lr,{key:fc(e,S)},At.createElement(Js,{color:A?R.primary:R.secondary2,dimColor:!A},`${S+1} `.padStart(5,"\xA0")),At.createElement(Js,{backgroundColor:A?"gray":void 0},p(x.length?eo(x,s-10):Vg)))});return At.createElement(Lr,{flexDirection:"column",paddingTop:1},At.createElement(Lr,null,At.createElement(Oe,{isSelected:r}),At.createElement(Js,{color:r?R.accent:R.secondary2},t)),At.createElement(Lr,{flexDirection:"row",borderStyle:"round",borderColor:R.secondary,paddingLeft:1,marginLeft:1},At.createElement(jt,{scrollByOne:!0,height:o-3,selectedIndex:d,itemHeight:1},v)))}});import{Box as ln,Text as ei}from"ink";import Ce,{useMemo as Io}from"react";var Yg,Xg,Jg,Qg,yc,bc=y(()=>{"use strict";se();ce();w();Pe();Gs();Cn();dc();uc();kn();pc();hc();Yg=e=>Ee(e,"description"),Xg=e=>Ee(e,"comments"),Jg=e=>Ee(e,"history"),Qg=e=>Ee(e,"attachments"),yc=({ticket:e,height:t})=>{let n=Io(()=>rc(e),[e]),{selectedIndex:o,contextNode:r}=Ue(),s=process.stdout.columns||120,d=Io(()=>Yg(e.id),[e.id]),l=Io(()=>Xg(e.id),[e.id]),u=Io(()=>Jg(e.id),[e.id]),m=Io(()=>Qg(e.id),[e.id]),p=I.getAttachmentsByIssue(e.id).length,v=r.id===e.id,x=r.id===l||r.parentNodeId===l,S=r.id===u||r.parentNodeId===u,A=r.id===m||r.parentNodeId===m,T=J(e.id);if(x){let V=t-3;return Ce.createElement(ln,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ce.createElement(lc,{ticket:e,width:s,height:V}))}if(A){let V=t-3;return Ce.createElement(ln,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ce.createElement(ac,{ticket:e,width:s,height:V}))}if(S){let $=I.getNode(u),V=$&&_e($)?$.props.value??"":"",qt=t-3;return Ce.createElement(ln,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},$?Ce.createElement(Zs,{id:$.id,label:"Event log",text:V,selected:!1,maxWidth:s,height:qt}):null)}let _=T.reduce(($,V)=>Qn(V)||V.id===l||V.id===m||V.id===u?$+1:$,0),z=2,K=3,U=_,Se=t-K-U-z,pn=($,V)=>$.id===d?Ce.createElement(Zs,{key:$.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:V,maxWidth:s,height:Se}):Qn($)?Ce.createElement(mc,{key:$.id,parent:$,selected:V,selectedIndex:o}):$.id===l?Ce.createElement(ln,{key:$.id,paddingTop:1},Ce.createElement(Oe,{isSelected:V}),Ce.createElement(ei,{backgroundColor:R.secondary,color:V?R.accent:R.primary},` Comments (${n}) \u203A\u203A `)):$.id===m?Ce.createElement(ln,{key:$.id,paddingTop:1},Ce.createElement(Oe,{isSelected:V}),Ce.createElement(ei,{backgroundColor:R.secondary,color:V?R.accent:R.primary},` Attachments (${p}) \u203A\u203A `)):$.id===u?Ce.createElement(ln,{key:$.id,paddingTop:1},Ce.createElement(Oe,{isSelected:V}),Ce.createElement(ei,{backgroundColor:R.secondary,color:V?R.accent:R.primary}," History \u203A\u203A ")):null;return Ce.createElement(ln,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},T.map(($,V)=>pn($,v&&o===V)))}});import{Box as Zg}from"ink";import kr from"react";var ef,xc,Ic=y(()=>{"use strict";se();oc();bc();ef=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,viewMode:s,height:d,width:l})=>{let u=t.context,m=u===D.TICKET||u===D.FIELD_LIST||u===D.FIELD,p=u===D.BOARD||u===D.SWIMLANE,v=u===D.TICKET?t:o.find(_=>_.context===D.TICKET),x=Math.floor(l/3),S=Math.floor(l/Math.max(e.length,1)),A=Math.min(S,x),T=s==="dense";return kr.createElement(Zg,{flexDirection:"row",height:d},p&&e.map((_,z)=>{let K=t.id===_.id,U=K?n:-1,Se=t.context===D.BOARD&&n===z;return kr.createElement(nc,{key:_.id,height:d,width:A,swimlane:_,isSelected:Se,isDense:T,isFocused:K,listSelectedIndex:U,mode:r})}),m&&v&&kr.createElement(yc,{height:d,ticket:v}))},xc=kr.memo(ef)});import Ec from"node:fs";import tf from"node:path";import nf from"react";import{render as of}from"ink";import{Writable as rf}from"node:stream";var Eo,sf,af,df,cf,Nc,Rc=y(()=>{"use strict";Ic();se();C();w();ue();Le();Eo=e=>String(e).padStart(2,"0"),sf=e=>{let t=e.getUTCFullYear(),n=Eo(e.getUTCMonth()+1),o=Eo(e.getUTCDate()),r=Eo(e.getUTCHours()),s=Eo(e.getUTCMinutes()),d=Eo(e.getUTCSeconds());return`${t}-${n}-${o}_${r}-${s}-${d}`},af=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",df=async(e,{width:t,height:n})=>{let o="",r=new rf({write(d,l,u){let m=cf(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(o=m),u()}});r.columns=t,r.rows=n,r.isTTY=!0;let s=of(e,{stdout:r,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),o},cf=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Nc=async()=>{let{viewMode:e}=ie(),{contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,renderedChildrenIndex:s}=g(),d=o.find(z=>z.context==="BOARD");if(!d)return i("No board found to export");let l=120,u=40,m=await df(nf.createElement(xc,{height:u,width:l,swimlanes:(s[d.id]??[]).filter(z=>z!==void 0&&Vt(z)),contextNode:t,selectedIndex:n,breadCrumb:o,viewMode:e??"dense",mode:r}),{width:l,height:u});if(!m)return i("Failed to render board export");let p=wo(process.cwd());if(a(p))return i("Unable to export, epiq root not found");let v=new Date,x=sf(v),S=`board_${af(d.title)}_${x}.md`,A=Ri(p.value);Ec.mkdirSync(A,{recursive:!0});let T=tf.join(A,S),_=`# Board - ${d.title}
47
47
  Date: ${v.toISOString()}
48
48
 
49
49
  \`\`\`text
50
50
  ${m}
51
51
  \`\`\`
52
- `;return Ic.writeFileSync(T,_,"utf8"),c("Exported board layout",T)}});var Lr,ti=y(()=>{"use strict";Lr=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let o=t[n];if(o&&o.action==="close.issue"&&o.payload.id===e.id){for(let r=n-1;r>=0;r--){let s=t[r];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null}});import{useSyncExternalStore as eC}from"react";var ni,cf,lf,$n,uf,Wt,Pr=y(()=>{"use strict";S();cf=new Set,lf=()=>{for(let e of cf)e()},$n=()=>{if(!ni)throw new Error("Ui state not initialized. Call initUiState() first.");return ni},uf=e=>{let t=$n();return ni=e(t),lf(),c("UX state updated",null)},Wt=e=>uf(t=>({...t,...e}))});import{spawn as mf}from"node:child_process";function No(e){let t=process.platform,r=mf(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return r.unref(),r.on("error",()=>{}),!0}var oi=y(()=>{"use strict"});import{spawn as aC,spawnSync as pf}from"node:child_process";import gf from"node:os";import Rc from"node:path";import{ulid as ff}from"ulid";function Sc(e){let t=[],n="",o=!1,r=null;for(let s of e.trim()){if(r){s===r?r=null:n+=s;continue}if(s==='"'||s==="'"){r=s,o=!0;continue}if(/\s/.test(s)){o&&t.push(n),n="",o=!1;continue}n+=s,o=!0}return o&&t.push(n),t}function vf(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Cc(){let{preferredEditor:e}=ie(),t=[e?vf(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Ac(e){let[t=""]=Sc(e);return/(^|\/)code(-insiders)?$/.test(t)}function hf(e,t){let[n="",...o]=Sc(e);return{command:n,args:[...o,...t]}}function yf(e,t){return hf(e,Ac(e)?["--wait",t]:[t])}function Tc(e){let t=Rc.join(gf.tmpdir(),"epiq");Be.mkDir(t);let n=Rc.join(t,ff());Be.writeToFile(n,e??"");let o=Cc();for(let r of o){let{command:s,args:d}=yf(r,n);if(!s)continue;let l=pf(s,d,{stdio:"inherit"});if(!l.error&&l.status===0){let u=Be.readFile(n);if(u==null)return i("Unable to read edited file");let m=u.replace(/\r?\n$/,"");return c("Successfully edited",m)}}return i("Unable to open editor")}var ri=y(()=>{"use strict";S();ke();vr()});import{ulid as si}from"ulid";var wc,bf,xf,Mc=y(()=>{"use strict";ri();Qt();nt();ut();se();S();xn();ce();w();ue();Ut();wc=async e=>{let{contextNode:t,selectedIndex:n}=g(),o=J(t.id)[n];if(e.modifier===He.DESCRIPTION)return xf();if(o&&Zn(o))return bf(e);if(e.modifier===He.TITLE){let r=ae();if(a(r))return i("Unable to resolve user ID");let s=o;if(!s)return i("Missing node");if(s.readonly)return i("Cannot rename readonly node");let d=e.inputString.trim();if(!d)return i("Provide a title");let l=await st();return a(l)?l:B([{id:si(),action:"edit.title",payload:{id:s.id,name:d},...r.value}],l.value)}return i("Unknown edit command")},bf=async e=>{let t=ae();if(a(t))return i("Unable to resolve user ID");let{contextNode:n,selectedIndex:o}=g(),r=J(n.id)[o];if(!r||!Zn(r))return i("Select a comment first");if(r.readonly)return i("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return i("Unable to resolve comment issue");let d=g().nodes[s];if(!d||!k(d))return i("Unable to resolve comment issue");if(d.readonly)return i("Cannot edit readonly issue");let l=r.id.split(":").at(0)??"",u=I.getComment(l);if(!u||u.deleted)return i("Unable to resolve comment");if(u.issue!==d.id)return i("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return i("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return i("Provide a comment");let p=await st();if(a(p))return p;let v=p.value;return B([{id:si(),action:"edit.issue.comment",payload:{id:u.id,issue:d.id,md:m},...t.value}],v)},xf=async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let t=await st();if(a(t))return t;let n=t.value,{breadCrumb:o,selectedNode:r}=g(),s=je([...o,r],"TICKET");if(a(s))return i("Edit target must be an issue");let d=s.value;if(!k(d))return i("Edit target must be an issue");if(d.readonly)return i("Cannot edit readonly issue");let l=J(d.id).find(v=>v.title===X.DESCRIPTION);if(!l)return i("No target found");if(l.readonly)return i("Cannot edit readonly field");let u=d.props.description??"";if(typeof u!="string")return i("Selected field is not editable text");let m=Tc(u);if(a(m))return i("Failed to edit field");let p=m.value;return p===u?c("No changes made",null):B([{id:si(),action:"edit.description",payload:{id:d.id,md:p},...e.value}],n)}});import ii from"node:fs";import If from"node:path";var kc,Lc=y(()=>{"use strict";S();gn();kc=async e=>{let t=If.join(e,".gitignore"),n=ii.existsSync(t)?ii.readFileSync(t,"utf8"):"",o=[".epiq/events/",".epiq/log/"],r=n.split(`
52
+ `;return Ec.writeFileSync(T,_,"utf8"),c("Exported board layout",T)}});var Pr,ti=y(()=>{"use strict";Pr=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let o=t[n];if(o&&o.action==="close.issue"&&o.payload.id===e.id){for(let r=n-1;r>=0;r--){let s=t[r];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null}});import{useSyncExternalStore as oS}from"react";var ni,lf,uf,$n,mf,Ht,Dr=y(()=>{"use strict";C();lf=new Set,uf=()=>{for(let e of lf)e()},$n=()=>{if(!ni)throw new Error("Ui state not initialized. Call initUiState() first.");return ni},mf=e=>{let t=$n();return ni=e(t),uf(),c("UX state updated",null)},Ht=e=>mf(t=>({...t,...e}))});import{spawn as pf}from"node:child_process";function No(e){let t=process.platform,r=pf(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return r.unref(),r.on("error",()=>{}),!0}var oi=y(()=>{"use strict"});import{spawn as lS,spawnSync as gf}from"node:child_process";import ff from"node:os";import Cc from"node:path";import{ulid as vf}from"ulid";function Sc(e){let t=[],n="",o=!1,r=null;for(let s of e.trim()){if(r){s===r?r=null:n+=s;continue}if(s==='"'||s==="'"){r=s,o=!0;continue}if(/\s/.test(s)){o&&t.push(n),n="",o=!1;continue}n+=s,o=!0}return o&&t.push(n),t}function hf(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Ac(){let{preferredEditor:e}=ie(),t=[e?hf(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Tc(e){let[t=""]=Sc(e);return/(^|\/)code(-insiders)?$/.test(t)}function yf(e,t){let[n="",...o]=Sc(e);return{command:n,args:[...o,...t]}}function bf(e,t){return yf(e,Tc(e)?["--wait",t]:[t])}function wc(e){let t=Cc.join(ff.tmpdir(),"epiq");Be.mkDir(t);let n=Cc.join(t,vf());Be.writeToFile(n,e??"");let o=Ac();for(let r of o){let{command:s,args:d}=bf(r,n);if(!s)continue;let l=gf(s,d,{stdio:"inherit"});if(!l.error&&l.status===0){let u=Be.readFile(n);if(u==null)return i("Unable to read edited file");let m=u.replace(/\r?\n$/,"");return c("Successfully edited",m)}}return i("Unable to open editor")}var ri=y(()=>{"use strict";C();Le();vr()});import{ulid as si}from"ulid";var Mc,xf,If,Lc=y(()=>{"use strict";ri();Zt();nt();ut();se();C();In();ce();w();ue();_t();Mc=async e=>{let{contextNode:t,selectedIndex:n}=g(),o=J(t.id)[n];if(e.modifier===He.DESCRIPTION)return If();if(o&&Zn(o))return xf(e);if(e.modifier===He.TITLE){let r=ae();if(a(r))return i("Unable to resolve user ID");let s=o;if(!s)return i("Missing node");if(s.readonly)return i("Cannot rename readonly node");let d=e.inputString.trim();if(!d)return i("Provide a title");let l=await st();return a(l)?l:B([{id:si(),action:"edit.title",payload:{id:s.id,name:d},...r.value}],l.value)}return i("Unknown edit command")},xf=async e=>{let t=ae();if(a(t))return i("Unable to resolve user ID");let{contextNode:n,selectedIndex:o}=g(),r=J(n.id)[o];if(!r||!Zn(r))return i("Select a comment first");if(r.readonly)return i("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return i("Unable to resolve comment issue");let d=g().nodes[s];if(!d||!L(d))return i("Unable to resolve comment issue");if(d.readonly)return i("Cannot edit readonly issue");let l=r.id.split(":").at(0)??"",u=I.getComment(l);if(!u||u.deleted)return i("Unable to resolve comment");if(u.issue!==d.id)return i("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return i("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return i("Provide a comment");let p=await st();if(a(p))return p;let v=p.value;return B([{id:si(),action:"edit.issue.comment",payload:{id:u.id,issue:d.id,md:m},...t.value}],v)},If=async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let t=await st();if(a(t))return t;let n=t.value,{breadCrumb:o,selectedNode:r}=g(),s=je([...o,r],"TICKET");if(a(s))return i("Edit target must be an issue");let d=s.value;if(!L(d))return i("Edit target must be an issue");if(d.readonly)return i("Cannot edit readonly issue");let l=J(d.id).find(v=>v.title===X.DESCRIPTION);if(!l)return i("No target found");if(l.readonly)return i("Cannot edit readonly field");let u=d.props.description??"";if(typeof u!="string")return i("Selected field is not editable text");let m=wc(u);if(a(m))return i("Failed to edit field");let p=m.value;return p===u?c("No changes made",null):B([{id:si(),action:"edit.description",payload:{id:d.id,md:p},...e.value}],n)}});import ii from"node:fs";import Ef from"node:path";var kc,Pc=y(()=>{"use strict";C();fn();kc=async e=>{let t=Ef.join(e,".gitignore"),n=ii.existsSync(t)?ii.readFileSync(t,"utf8"):"",o=[".epiq/events/",".epiq/log/"],r=n.split(`
53
53
  `).map(u=>u.trim()),s=o.filter(u=>!r.some(m=>m===u||m===u.replace(/\/$/,"")||m==="/"+u||m==="/"+u.replace(/\/$/,"")));if(s.length===0)return c("Local epiq paths already ignored",!1);let l=["# [epiq]: local hydrated state is never committed",...s].join(`
54
54
  `);return n=n.trimEnd()+`
55
55
 
56
56
  ${l}
57
- `,ii.writeFileSync(t,n,"utf8"),ve.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)}});import Ef from"node:fs";import Pc from"node:path";var Nf,ee,Dc,Fc=y(()=>{"use strict";Lc();Lo();at();kt();Ho();We();ao();rr();xt();nt();te();S();Mt();be();ke();w();ue();Nf=async e=>{let t=await j({cwd:e,args:["status","--porcelain"]});return a(t)?t:c("Checked git diff",t.value.stdout.trim().length>0)},ee=(e,t)=>i(`[${e}] ${t}`),Dc=async()=>{H("");let e=ko(),t=await it(process.cwd());if(a(t))return ee(1,t.message);let n=t.value,o=await Fo(n);if(a(o))return ee(2,o.message);if(o.value)return ee(2,`Cannot initialize Epiq while a git operation is in progress: ${o.value}`);let r=await Nf(n);if(a(r))return ee(2.5,r.message);if(r.value)return ee(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(Jr(n))return ee(4,"Epiq project already initialized");let s=cr();if(!s.isSetupDone||!s.userName)return ee(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let d=ie(),l=d.userName,u=d.userId;if(!u||!l)return ee(5,"Missing Epiq user id");let m=e.stateBranch,p=await Oo({repoRoot:n,branch:m});if(a(p))return ee(6,p.message);if(p.value)return ee(6,`State branch already exists: ${m}`);let v=await ds({repoRoot:n,stateBranchName:m});if(a(v))return ee(6,v.message);let x=$o();if(a(x))return ee(7,x.message);let C=Pc.join(_o(),e.projectId),A=await Xn({repoRoot:n,stateBranchRoot:C,stateBranchName:m});if(a(A))return ee(8,A.message);let T=Pc.join(C,".epiq");Ef.mkdirSync(T,{recursive:!0});let _=za({userId:u,userName:l});if(a(_))return ee(9,_.message);for(let Vr of _.value){let Ni=tr({event:Vr,rootDir:C});if(a(Ni))return ee(9,Ni.message)}let z=await Wo({stateBranchRoot:C,eventFileName:Jt({userId:u,userName:l})});if(a(z))return ee(10,z.message);let K=await vn({cwd:C,message:"[epiq:init]"});if(a(K))return ee(10,K.message);let U=await kc(n);if(a(U))return ee(11,U.message);let Ce=Ai({repoRoot:n,fileContents:e});if(a(Ce))return ee(12,Ce.message);let mn=await de.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(mn))return ee(13,mn.message);let $=await de.commit({cwd:n,message:"[epiq:init-project]"});if(a($))return ee(13,$.message);let V="Project initialized!",pn=await j({cwd:n,args:["push","-u","origin","HEAD"]});a(pn)&&(V+=` Warn: [init:14] ${pn.message}`);let Kt=await Jn({repoRoot:n,stateBranchRoot:C});a(Kt)&&(V+=` Warn: [init:15] ${Kt.message}`);let Ii=bt(_.value).filter(a);if(Ii.length>0)return ee(16,Ii.map(Vr=>Vr.message).join(`
58
- `));let zr=Fe();if(a(zr))return ee(16,zr.message);let{rootNodeId:Ru,nodes:Su}=zr.value,Ei=Su[Ru];return Ei?(F.navigate({contextNode:Ei,selectedIndex:0}),E({hasProjectDefinition:!0,mode:f.DEFAULT}),c(V,null)):ee(16,"Unable to resolve initialized root node")}});import{ulid as Rf}from"ulid";function di(e){let t=Oc();if(a(t))return t;let{contextNode:n,nodes:o}=g();if(!n.parentNodeId)return i("Missing parent node id");let r=o[n.parentNodeId];if(!r)return i("Missing parent node");let s=ne(r.id),d=s.findIndex(({id:m})=>m===n.id);if(d<0)return i("Current node not found among siblings");let l=s[d+e];if(!l)return i("Missing sibling node");let u=Uc({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:_c(u.value)}function ci(e){let t=Oc();if(a(t))return t;let{contextNode:n,selectedIndex:o}=g(),s=ne(n.id)[o+e];if(!s)return i("Missing sibling node");let d=Uc({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:_c(d.value)}var Bc,Ht,Ro,Oc,ai,Uc,_c,li=y(()=>{"use strict";xt();nt();S();lt();w();Bc=null,Ht=()=>structuredClone(Bc),Ro=e=>{Bc=e},Oc=()=>{let{contextNode:e,selectedIndex:t}=g(),o=ne(e.id)[t];return o?c("Resolved selected child",o):i("Target node not found")},ai=({id:e,parentId:t,position:n={at:"end"}})=>{let o=ne(t).filter(r=>r.id!==e);return nr(o,n)},Uc=({id:e,parentId:t,position:n={at:"end"}})=>{let o=ae();if(a(o))return i("Unable to resolve user ID");let r=ai({parentId:t,id:e,position:n});return a(r)?r:c("Created pending move state",{id:Rf(),...o.value,action:"move.node",payload:{id:e,parent:t,rank:r.value.rank}})},_c=e=>{Ro(e);let t=Dt(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as Sf}from"ulid";var $c,Dr,jc,Wc=y(()=>{"use strict";We();li();Qt();nt();te();S();lt();be();w();ue();$c=()=>{let e=Ht();if(!e)return i("No pending move state");let t=e.payload.id,n=e.payload.parent,o=g().nodes[n];if(!o)return i("Move parent not found");let r=ne(n).findIndex(s=>s.id===t);return r===-1?i("Moved node not found among rendered children"):(F.navigate({contextNode:o,selectedIndex:r}),c("Synchronized navigation to moved node",null))},Dr=(e,t="Moved preview")=>{if(a(e))return e;let n=$c();return a(n)?n:(E({mode:f.MOVE}),c(t,null))},jc=async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=Q().commandMeta,{contextNode:n,selectedIndex:o}=g(),r=ne(n.id)[o];if(!r)return E({mode:f.DEFAULT}),i("No move target");if(t==="start"){if(r.readonly)return i("Target node is read-only");if(o===-1)return i("No item selected");if(!r.parentNodeId)return i("Target has no parent");let s=ne(r.parentNodeId),d=s.findIndex(({id:v})=>v===r.id);if(d===-1)return i("Target not found among siblings");let l=s[d-1],u=s[d+1],m=u!=null?{at:"before",sibling:u.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},p=ai({parentId:r.parentNodeId,id:r.id,position:m});return a(p)?p:(Ro({id:Sf(),action:"move.node",payload:{id:r.id,parent:r.parentNodeId,rank:p.value.rank},...e.value}),E({mode:f.MOVE}),c("Move initialized",null))}if(t==="next")return Dr(ci(1));if(t==="previous")return Dr(ci(-1));if(t==="to-next")return Dr(di(1));if(t==="to-previous")return Dr(di(-1));if(t==="confirm"){let s=Ht();if(!s)return i("No pending move to confirm");let d=await st();if(a(d))return d;let l=B([s],d.value);if(a(l))return l;let u=$c();return a(u)?u:(Ro(null),E({mode:f.DEFAULT}),c("Moved item",null))}return t==="cancel"?(Ro(null),E({mode:f.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as Cf,ulid as Af}from"ulid";var Tf,Fr,ui=y(()=>{"use strict";S();Tf=Cf(),Fr=({name:e,parent:t,rank:n,user:{userId:o,userName:r}})=>{let s=Tf();return c("Created issue events",[{id:Af(),userId:o,userName:r,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as Br}from"ulid";var Hc,Kc=y(()=>{"use strict";We();ui();Qt();nt();ut();S();ce();lt();w();ue();Hc=async(e,t)=>{let n=ae();if(a(n))return i("Unable to resolve user ID");let o=await st();if(a(o))return o;let r=o.value;if(!t.inputString)return i(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:d,selectedIndex:l}=g(),u=m=>{let p=B([m],r);if(a(p))return p;let v=I.getNode(p.value[0].result.id);if(!v)return i("Created node not found");if(!v.parentNodeId)return p;let x=I.getNode(v.parentNodeId);return x?(F.navigate({contextNode:x,selectedIndex:I.getSiblings(v.parentNodeId).findIndex(({id:C})=>C===v.id)}),p):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=I.getNode(m);if(!p)return i("Workspace not found");let v=Zt(p.id,n.value,r);return a(v)?v:u({id:Br(),action:"add.board",payload:{id:Br(),name:t.inputString,parent:p.id,rank:v.value},...n.value})}if(t.modifier==="swimlane"){let m=je(s,"BOARD");if(a(m))return i("Unable to add swimlane in this context");let p=Zt(m.value.id,n.value,r);return a(p)?p:u({id:Br(),action:"add.swimlane",payload:{id:Br(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=J(d.id)[l],p=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let K=je(s,"SWIMLANE");return a(K)?null:K.value})();if(!p)return i("Unable to add issue in this context");let v=Zt(p.id,n.value,r);if(a(v))return v;let x=Fr({name:t.inputString,parent:p.id,rank:v.value,user:n.value});if(a(x))return x;let C=x.value,A=B([...C],r);if(a(A))return A;if(!A.value[0])return i("Issue creation failed");let z=C.find(K=>K.action==="add.issue")?.payload.id;return z?(F.navigate({contextNode:p,selectedIndex:I.getSiblings(p.id).findIndex(({id:K})=>K===z)}),c("Issue created",null)):i("Unable to determine ticket id")}return c("Success",null)}});var Or,mi=y(()=>{"use strict";We();Xt();xt();S();w();Or=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:o})=>{let r=g(),s=Is(n,t);if(a(s))return i(s.message);let{appliedEvents:d,unappliedEvents:l}=s.value,u=At();if(a(u))return u;let p=bt(d).filter(a);if(p.length>0)return At(),E(r),i(p.map(x=>x.message).join(", "));let v=g().nodes[e];return v?(F.navigate({contextNode:v,selectedIndex:o}),c("",{unappliedEvents:l})):(At(),E(r),i("Board did not exist at that date"))}});var wf,Mf,kf,Ur,_r,ln,qc,Lf,zc,pi=y(()=>{"use strict";mo();ps();xt();te();S();w();wf=20,Mf=16,kf=150,Ur=null,_r=null,ln=()=>{Ur!==null&&(clearInterval(Ur),Ur=null),_r!==null&&(clearTimeout(_r),_r=null)},qc=()=>{ln(),E({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Lf=e=>{let t=[],n=0;for(let r=0;r<e.length;r++){let s=r===0?0:Math.max(0,e[r]-e[r-1]);n+=Math.sqrt(s),t[r]=n}let o=n;return t.map((r,s)=>o>0?r/o:(s+1)/e.length)},zc=({events:e,startTime:t,durationMs:n})=>{ln();let o=e.length,r=e.map(v=>rn(v)??t),s=r[o-1]??Date.now(),d=Lf(r),l=Math.max(1,Math.round(n*wf/1e3)),u=Math.max(Math.round(n/l),Mf),m=0,p=0;E({mode:f.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:o,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Ur=setInterval(()=>{m++;let v=m/l,x=[],C;for(;p<o&&d[p]<=v;){let T=e[p],_=Dt(T);if(a(_)){qc();return}x.push(...gs(T)),C=T,p++}if(p>=o||m>=l){for(;p<o;p++){let _=Dt(e[p]);if(a(_))break}let T=g().replay;E({unappliedEvents:[],replay:T&&{...T,progress:1,appliedCount:o}}),ln(),_r=setTimeout(qc,kf);return}let A=g().replay;E({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,v),appliedCount:p,totalCount:o,startTime:t,endTime:s,currentTime:C?rn(C)??A?.currentTime??t:A?.currentTime??t,currentLabel:C?Na(C):A?.currentLabel??"",flashNodeIds:C?[...new Set(x)]:A?.flashNodeIds??[]}})},u)}});var Vc,Gc=y(()=>{"use strict";at();mo();Xt();xt();te();ut();S();be();w();lo();mi();pi();Vc=async()=>{let e=je(g().breadCrumb,"BOARD");if(a(e))return e;let t=await it(process.cwd());if(a(t))return i("Unable to locate repo root");let n=Me({repoRoot:t.value});if(a(n))return n;let{modifier:o,inputString:r}=Q().commandMeta;if(ln(),o==="now"){let l=Ge(n.value);if(a(l))return i(l.message);let u=At();if(a(u))return u;let p=bt(l.value).filter(a);return p.length>0?i(p.map(v=>v.message).join(", ")):(E({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),c("Peeking now",!0))}let s;if(o==="prev"){let l=g().eventLog.at(-1),u=rn(l);if(u===null)return i("No previous event to peek");s=u}else if(o==="next"){let l=g().unappliedEvents.at(0),u=rn(l);if(u===null)return i("No next event to peek");s=u+1}else{let l=nn(o||r.trim());if(!l)return i("Invalid peek date");s=l.getTime()}let d=Or({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(d)?d:(E({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:d.value.unappliedEvents,replay:null}),c("Peeking",!0))}});var Yc,Xc=y(()=>{"use strict";at();ut();S();be();w();lo();mi();pi();Yc=async()=>{let e=je(g().breadCrumb,"BOARD");if(a(e))return e;let t=await it(process.cwd());if(a(t))return i("Unable to locate repo root");let n=Me({repoRoot:t.value});if(a(n))return n;let{modifier:o,inputString:r}=Q().commandMeta,{dateInput:s,durationInput:d}=pr(o,r);if(ln(),g().syncStatus.status==="syncing")return i("Cannot replay while syncing, try again in a moment");let l=nn(s);if(!l)return i("Invalid replay date");let u=d?mr(d):15e3;if(u===null)return i("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=g(),v=Or({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(v))return v;let{unappliedEvents:x}=v.value;return x.length===0?(At(),E(p),c("Nothing to replay from that point",!0)):(zc({events:x,startTime:m,durationMs:u}),c("Replaying board history",!0))}});import Df from"zod";var Jc,Qc=y(()=>{"use strict";sn();te();S();be();ke();w();Jc=()=>{let e=Q().commandMeta.inputString,t=Df.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return i("Auto sync duration must be a number of at least 3000 ms");let n=Xe({autoSyncDebounceMs:t.data});return a(n)?n:(Ve({autoSyncIntervalMs:t.data}),E({mode:f.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))}});var Zc,el=y(()=>{"use strict";ao();sn();te();S();be();ke();w();Zc=()=>{let e=Q().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=ed(e),n=Xe({autoSync:t});return a(n)?n:(Ve({autoSync:t}),E({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var tl,nl=y(()=>{"use strict";sn();te();S();be();ke();w();tl=()=>{let e=Q().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return i("Invalid response");let n=Xe({logLevel:e});return a(n)?n:(Ve({logLevel:e}),E({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});import{spawn as Ff}from"node:child_process";var Bf,ol,rl=y(()=>{"use strict";S();Bf=()=>{switch(process.platform){case"darwin":return{command:"pbcopy",args:[]};case"win32":return{command:"clip",args:[]};default:return process.env.WAYLAND_DISPLAY?{command:"wl-copy",args:[]}:{command:"xclip",args:["-selection","clipboard"]}}},ol=async e=>new Promise(t=>{let{command:n,args:o}=Bf();try{let r=Ff(n,o,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>t(i(`Clipboard tool not available (${n})`))),r.on("close",s=>t(s===0?c("Copied to clipboard",null):i(`Clipboard tool failed (${n})`))),r.stdin.on("error",()=>{}),r.stdin.write(e),r.stdin.end()}catch{t(i(`Clipboard tool not available (${n})`))}})});var So,sl,il=y(()=>{"use strict";S();w();rl();In();co();Ut();So=async(e,t)=>{if(!e.trim())return i(`Nothing to copy: ${t} is empty`);let n=await ol(e);return a(n)?n:c(`Copied ${t} to clipboard`,null)},sl=async e=>{let{breadCrumb:t,selectedNode:n}=g(),o=uo({breadCrumb:t,selectedNode:n}),r=o??n;if(!r)return i("Nothing selected to copy from");switch(e.modifier){case ye.REF:return So(tt(r.id),"ref");case ye.TITLE:return So(r.title,"title");case ye.DESCRIPTION:return o?So(o.props?.description??"","description"):i("No issue in scope");case ye.TAGS:{if(!o)return i("No issue in scope");let s=Bt(o).map(({name:d})=>d);return So(s.join(", "),"tags")}case ye.ASSIGNEES:{if(!o)return i("No issue in scope");let s=Ot(o).map(({name:d})=>d);return So(s.join(", "),"assignees")}default:return i("Yank one of: ref, title, description, tags, assignees")}}});var al,dl=y(()=>{"use strict";Rs();te();S();be();w();al=async()=>{H(""),E({mode:f.DEFAULT});let e=Fe();if(a(e))return i(e.message);if(e.value.syncStatus.status==="syncing")return i("Sync already in progress");E({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await sr();return a(t)?(E({syncStatus:{msg:t.message,status:"failed"}}),t):(E({mode:f.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as we}from"ulid";var Of,cl,ll,Tt,ul,ml=y(()=>{"use strict";Nc();We();sn();Qt();nt();ti();Sn();te();ut();se();S();ce();lt();be();ke();w();Pr();ue();Fn();oi();tn();Ks();Ut();_s();Mc();Fc();Wc();Kc();Gc();Xc();Qc();Os();el();nl();il();dl();Of=e=>e.action==="add.issue.comment",cl=e=>Object.values(g().tags).find(t=>t.name===e),ll=()=>{let{eventLog:e=[],contributors:t}=g(),n=new Map,o=new Set;for(let r of e)r.userId&&(n.set(r.userId,r.userName??""),o.add(r.userId));for(let r of Object.values(t)){if(r.tombstoned){n.set(r.id,r.name);continue}n.set(r.id,Pn(r.name,n.get(r.id))??r.name)}return[...n.entries()].map(([r,s])=>({id:r,name:s,isExternal:!o.has(r)}))},Tt=async()=>{let e=await st();return a(e)?e:c("Resolved persist root",e.value)},ul=[{systemOnly:!0,intent:P.Move,description:"Internal move-state command",mode:f.COMMAND_LINE,action:jc},{intent:P.Delete,description:"Delete the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=J(t.id)[n];if(!o)return i("Unable to resolve child to delete");let r=await Tt();if(a(r))return r;if(o.context==="COMMENT"){let s=o.id,d=k(t)?t.id:t.parentNodeId;if(!d)return i("Unable to resolve comment issue");let l=g().nodes[d];if(!l||!k(l))return i("Unable to resolve comment issue");let u=l.log?.filter(Of).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):B([{id:we(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],r.value):i("Unable to resolve comment")}return B([{id:we(),action:"delete.node",payload:{id:o.id},...e.value}],r.value)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:f.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=Q().commandMeta,n=/(!=|=)/,[o]=e.split(n);if(!o||!(d=>pe(h.FILTER).map(l=>l.split(n)[0]).includes(d))(o))return i("Invalid filter modifier");let s={target:o,operator:"=",value:t.trim()};return me(d=>({...d,filters:e==="clear"?[]:[...d.filters,s],mode:f.DEFAULT})),c("Filter updated",null)}},{intent:P.ViewHelp,description:"Open the help screen",mode:f.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return Wt({pendingNavTarget:{contextNode:e,breadCrumb:o,selectedIndex:t,selectedNode:n}}),E({mode:f.HELP}),c("Viewing help",null)}},{intent:P.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=J(t.id)[n];if(!o)return i("Unable to close issue, no target found");if(!k(o))return i("Cannot close in this context");let r=g().nodes[he];if(!r)return i("Unable to locate closed swimlane");if(o.parentNodeId===r.id)return i("Issue is already closed");let s=await Tt();if(a(s))return s;let d=s.value,l=Ft(r.id,o.id,{at:"end"},e.value,d);if(a(l))return l;let u=B([{id:we(),action:"close.issue",payload:{id:o.id,parent:r.id,rank:l.value},...e.value}],d);return a(u)?u:c("Issue closed",null)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=J(t.id)[n];if(!o)return i("Unable to reopen issue, no target found");let r=o.context==="TICKET"?c("Resolved ticket",o):Gt(o.id,"TICKET");if(a(r))return i("Cannot reopen in this context");let s=r.value,d=g().nodes[he];if(!d)return i("Unable to locate closed swimlane");if(s.parentNodeId!==d.id)return i("Issue is not closed");if(!k(s))return i("Target node is not issue");let l=Lr(s);if(!l)return i("Unable to resolve previous parent from issue history");if(l===d.id)return i("Previous parent resolves to closed swimlane");let u=g().nodes[l];if(!u)return i("Previous parent no longer exists");let m=await Tt();if(a(m))return m;let p=m.value,v=Ft(u.id,s.id,{at:"end"},e.value,p);if(a(v))return v;let x=B([{id:we(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:v.value},...e.value}],p);return a(x)?x:c("Issue reopened",null)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.Init,description:"Initialize Epiq in the current git repository",mode:f.COMMAND_LINE,action:Dc},{intent:P.NewItem,description:"Create a new board, swimlane, or issue",mode:f.COMMAND_LINE,action:Hc,onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.Rename,description:"Rename the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=J(t.id)[n];if(!o)return i("Missing node");if(o.readonly)return i("Cannot rename readonly node");let r=jd();if(!r)return i("Provide a title");let s=await Tt();return a(s)?s:B([{id:we(),action:"edit.title",payload:{id:o.id,name:r},...e.value}],s.value)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.UntagTicket,description:"Remove a tag from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,o=(t||n).trim();if(!o)return i("Provide a tag");let r=cl(o);if(!r)return i(`Tag "${o}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid untag target");let d=Gt(s.id,"TICKET");if(a(d))return i("Unable to untag issue in this context");let l=d.value;if(!k(l))return i("Target node is not issue");if(!(l.props.tags??[]).includes(r.id))return i("Issue is not tagged with that tag");let m=await Tt();return a(m)?m:B([{id:we(),action:"remove.issue.tag",payload:{id:l.id,tag:r.id},...e.value}],m.value)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.TagTicket,description:"Add or create a tag on the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,o=(t||n).trim();if(!o)return i("Provide a tag");let{selectedNode:r}=g();if(!r)return i("Invalid tag target");let s=Gt(r.id,"TICKET");if(a(s))return i("Unable to tag issue in this context");let d=s.value;if(!k(d))return i("Target node is not issue");let l=await Tt();if(a(l))return l;let u=cl(o),m=u?.id??we();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):B([...u?[]:[{id:we(),action:"create.tag",payload:{id:m,name:o},...e.value}],{id:we(),action:"add.issue.tag",payload:{id:d.id,tag:m},...e.value}],l.value)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.AssignUserToTicket,description:"Assign a user to the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,o=(t||n).trim();if(!o)return i("Provide an assignee");let r=o.startsWith("!"),s=(r?o.slice(1):o).trim();if(!s)return i("Provide an assignee");let{selectedIndex:d,contextNode:l}=g(),u=J(l.id)[d];if(!u)return i("Invalid assign target");let m=Gt(u.id,"TICKET");if(a(m))return i("Unable to assign issue in this context");let p=m.value;if(!k(p))return i("Target node is not issue");let v=await Tt();if(a(v))return v;let x=ll(),C=!r&&s.toLowerCase()==="me",A,T;if(C)A=e.value.userId,T=x.find(K=>K.id===A)?.name??e.value.userName;else{let K=x.filter(Ce=>Ce.name===s);if(K.length>1)return i(`"${s}" matches ${K.length} contributors (${K.map(Ce=>Ce.id).join(", ")}). Assign from the GUI to choose by id.`);let U=K[0];if(!U&&!r)return i(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);A=U?.id??we(),T=U?.name??s}if((p.props.assignees??[]).includes(A))return i("Assignee already assigned");let z=!!g().contributors[A];return B([...z?[]:[{id:we(),action:"create.contributor",payload:{id:A,name:T},...e.value}],{id:we(),action:"add.issue.assignee",payload:{id:p.id,assignee:A},...e.value}],v.value)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,o=(t||n).trim();if(!o)return i("Provide an assignee to remove");let{selectedNode:r}=g();if(!r)return i("Invalid unassign target");let s=Gt(r.id,"TICKET");if(a(s))return i("Unable to unassign in this context");let d=s.value;if(!k(d))return i("Target node is not issue");let l=d.props.assignees??[],u=o.toLowerCase()==="me",m=u?l.filter(x=>x===e.value.userId):ll().filter(x=>x.name===o&&l.includes(x.id)).map(x=>x.id);if(m.length>1)return i(`"${o}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return i(u?"Issue is not assigned to you":`Issue is not assigned to "${o}"`);let v=await Tt();return a(v)?v:B([{id:we(),action:"remove.issue.assignee",payload:{id:d.id,assignee:p},...e.value}],v.value)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.Comment,description:"Add a comment to the selected issue",mode:f.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return i("Provide a comment");if(n.length>wn)return i(`Cannot exceed ${wn} characters`);let o=ae();if(a(o))return i("Unable to resolve user ID");let{breadCrumb:r,selectedNode:s}=g(),d=je([...r,s],"TICKET");if(a(d))return i("Edit target must be an issue");let l=d.value;if(!l)return i("Invalid comment target");let u=l.context==="TICKET"?c("Resolved ticket",l):Gt(l.id,"TICKET");if(a(u))return i("Unable to comment on issue in this context");let m=u.value;if(!k(m))return i("Target node is not issue");let p=await Tt();return a(p)?p:B([{id:we(),action:"add.issue.comment",payload:{id:we(),issue:m.id,author:o.value.userId,md:n},...o.value}],p.value)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.Sync,description:"Pull, commit, and push Epiq state",mode:f.COMMAND_LINE,action:al},{intent:P.Peek,description:"View board state at another point in time",mode:f.COMMAND_LINE,action:Vc},{intent:P.Replay,description:"Replay board history forward from a point in time",mode:f.COMMAND_LINE,action:Yc},{intent:P.Export,description:"Export the current board layout to markdown",mode:f.COMMAND_LINE,action:async()=>{let e=await Ec();return a(e)?e:(E({mode:f.DEFAULT}),c("Export successful",!0))}},{intent:P.Exit,description:"Exit the application",mode:f.COMMAND_LINE,action:async()=>(F.exit(),c("Exit successful",!0))},{intent:P.Edit,description:"Edit title or description",mode:f.COMMAND_LINE,action:async(e,t)=>wc(t),onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:f.COMMAND_LINE,action:async(e,t)=>sl(t),onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:f.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case oe.USERNAME:{let{userId:o,preferredEditor:r,userName:s}=ie(),d=n||s,l=o??we();if(!d||!l)return i("Unable to resolve user name or id");let u=Xe({userName:d,userId:l,preferredEditor:r??""});return a(u)?u:(Ve({userName:d,userId:l}),E({mode:f.DEFAULT}),c(`Username set to "${d}"`,null))}case oe.EDITOR:{if(!n)return i("No editor provided");let o=Xe({preferredEditor:n});return a(o)?o:(Ve({preferredEditor:n}),E({mode:f.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case oe.VIEW:{if(n!=="wide"&&n!=="dense")return i("Invalid view mode");let o=Xe({viewMode:n});return a(o)?o:(Ve({viewMode:n}),E({mode:f.DEFAULT}),c(`View set to "${n}"`,null))}case oe.AUTOSYNC:return Zc();case oe.LOG_LEVEL:return tl();case oe.SYNC_DEBOUNCE_MS:return Jc();case oe.ATTACHMENT_MAX_KB:return yd();default:return i("Unknown config command")}}},{intent:P.Coffee,description:"Sponsor the development of Epiq!",mode:f.COMMAND_LINE,action:()=>{let e=Q().commandMeta.modifier;return e==="custom"?No("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):No(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),H(""),c("Thanks you!",null)}}]});var Uf,ft,gi=y(()=>{"use strict";dr();hr();Ks();ml();S();be();ke();w();Uf=new Set(["peek","replay","filter","view-help","yank"]),ft=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:o,inputString:r}}=Q();if(!t)return i("No command to confirm");if(!e&&n===_t.Invalid)return i("Invalid command");let s=Wd(t);Od();let{readOnly:d}=g();if(d&&!Uf.has(s))return ho({status:wt.Fail,message:"Command not available in readonly state",value:null});let l=ul.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return ho({status:wt.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:r,modifier:o})}catch(m){return ho({status:wt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?ho(u):(Ud({addToHistory:!e}),l.onSuccess?.(),ie().autoSync&&Ja(),u)}});var $r,jr,pl,gl=y(()=>{"use strict";S();te();w();Vt();gi();li();be();$r=[{intent:M.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:f.COMMAND_LINE}),H("move cancel"),ft({isForceExecutedBySystem:!0}))},{intent:M.InitMove,mode:f.DEFAULT,description:"[m] move (init/confirm)",action:()=>(E({mode:f.COMMAND_LINE}),H("move start"),ft({isForceExecutedBySystem:!0}))},{intent:M.ConfirmMove,mode:f.MOVE,action:()=>(E({mode:f.COMMAND_LINE}),H("move confirm"),ft({isForceExecutedBySystem:!0}))}],jr=[{intent:M.MovePreviousItem,mode:f.MOVE,action:()=>Ht()?(E({mode:f.COMMAND_LINE}),H("move previous"),ft({isForceExecutedBySystem:!0})):i("No pending move")},{intent:M.MoveNextItem,mode:f.MOVE,action:()=>Ht()?(E({mode:f.COMMAND_LINE}),H("move next"),ft({isForceExecutedBySystem:!0})):i("No pending move")}],pl=[{intent:M.MoveToNextContainer,mode:f.MOVE,action:()=>Ht()?(E({mode:f.COMMAND_LINE}),H("move to-next"),ft({isForceExecutedBySystem:!0})):i("No pending move")},{intent:M.MoveToPreviousContainer,mode:f.MOVE,action:()=>Ht()?(E({mode:f.COMMAND_LINE}),H("move to-previous"),ft({isForceExecutedBySystem:!0})):i("No pending move")}]});var fl,vl=y(()=>{"use strict";se();gl();fl={[D.WORKSPACE]:[...$r,...jr],[D.BOARD]:[...$r,...jr],[D.SWIMLANE]:[...$r,...jr,...pl],[D.TICKET]:[],[D.FIELD]:[],[D.FIELD_LIST]:[],[D.TEXT]:[],[D.COMMENT]:[]}});import _f from"node:fs";import $f from"node:path";var hl,yl=y(()=>{"use strict";at();go();S();ue();oi();hl=e=>{let t=Ze(process.cwd());if(a(t))return i("Unable to resolve project root");let n=Me({repoRoot:t.value});if(a(n))return i(n.message);let o=Bs(e.hash,e.ext),r=$f.join(Xr(n.value),o);return _f.existsSync(r)?(No(r),c(`Opened ${e.name}`,null)):i("Attachment file not found \u2014 run :sync to fetch it")}});var bl,xl,Il=y(()=>{"use strict";te();S();be();w();Pr();Vt();We();bl=()=>{H("");let{pendingNavTarget:e}=$n();E({mode:f.DEFAULT}),e&&F.navigate(e),Wt({pendingNavTarget:void 0})},xl=[{intent:M.ExitCommandLine,mode:f.HELP,action:()=>(bl(),c("Exiting help",null))},{intent:M.Exit,mode:f.HELP,action:()=>(bl(),c("Closed help",null))},{intent:M.NavPreviousItem,mode:f.HELP,description:"[arrows/hjkl] navigate",action:()=>(F.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:M.NavNextItem,mode:f.HELP,action:()=>(F.navigateToNextItem(),c("Navigating to next help item",null))},{intent:M.NavToPreviousContainer,mode:f.HELP,action:()=>(F.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:M.NavToNextContainer,mode:f.HELP,action:()=>(F.navigateToNextContainer(),c("Navigating to next help container",null))}]});var jf,El,Nl,Rl=y(()=>{"use strict";te();se();S();be();w();Pr();Vt();We();jf=e=>{E({mode:f.COMMAND_LINE});let{pendingNavTarget:t}=$n();t&&F.navigate(t),Wt({pendingNavTarget:void 0}),H(`${e} `)},El=()=>{H("");let{pendingNavTarget:e}=$n();e&&F.navigate(e),Wt({pendingNavTarget:void 0}),E({mode:f.DEFAULT})},Nl=[{intent:M.InitCommandPalette,mode:f.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{H("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return Wt({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}}),E({mode:f.PALETTE}),c("Opening command palette",null)}},{intent:M.Confirm,mode:f.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!Zi(e))return i("Command only applicable on text nodes");if(e.props.disabled)return i("Command is not available in this context");let t=e.title;return t?(jf(t),c("Selected command",t)):c("No command selected",null)}},{intent:M.ExitCommandLine,mode:f.PALETTE,action:()=>(El(),c("Exiting palette",null))},{intent:M.Exit,mode:f.PALETTE,action:()=>(El(),c("Closed command palette",null))},{intent:M.NavPreviousItem,mode:f.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(F.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:M.NavNextItem,mode:f.PALETTE,action:()=>(F.navigateToNextItem(),c("Navigating to next item",null))},{intent:M.NavToPreviousContainer,mode:f.PALETTE,action:()=>(F.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:M.NavToNextContainer,mode:f.PALETTE,action:()=>(F.navigateToNextContainer(),c("Navigating to next container",null))}]});var Sl,Cl=y(()=>{"use strict";tn();Ut();te();S();xn();ce();lt();be();w();yl();Vt();Il();Rl();We();Sl=[...xl,...Nl,{intent:M.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(E({mode:f.COMMAND_LINE}),H(`${h.NEW} `),c("Adding new item",null))},{intent:M.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(E({mode:f.COMMAND_LINE}),H(`${h.DELETE} `),c("Deleting item",null))},{intent:M.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(E({mode:f.COMMAND_LINE}),H(""),c("Entering command line mode",null))},{intent:M.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!ne(e?.id??"")?.length){let o=e?I.getAttachment(e.id):void 0;if(o)return hl(o);if(e?.title===X.DESCRIPTION)return E({mode:f.COMMAND_LINE}),H(`${h.EDIT} description `),c("Propose command",!0);if(e?.title===X.ASSIGNEES)return E({mode:f.COMMAND_LINE}),H(`${h.ASSIGN} `),c("Propose command",!0);if(e?.title===X.TAGS)return E({mode:f.COMMAND_LINE}),H(`${h.TAG} `),c("Propose command",!0);if(t.title===X.DESCRIPTION&&e?.context==="TEXT")return E({mode:f.COMMAND_LINE}),H(`${h.EDIT} description `),c("Propose command",!0)}return F.enterChildNode(),c("Entering context",null)}},{intent:M.Yank,mode:f.DEFAULT,description:"[y] yank to clipboard",action:()=>{let{selectedNode:e}=g(),t=e?.title===X.DESCRIPTION?ye.DESCRIPTION:e?.title===X.TAGS?ye.TAGS:e?.title===X.ASSIGNEES?ye.ASSIGNEES:ye.REF,o=pe(h.YANK).includes(t)?t:ye.REF;return E({mode:f.COMMAND_LINE}),H(`${h.YANK} ${o}`),c("Propose command",!0)}},{intent:M.EditTitle,mode:f.DEFAULT,description:"[r] rename title",action:()=>(E({mode:f.COMMAND_LINE}),H(`${h.EDIT} title ${g().selectedNode?.title}`),c("Exiting context",null))},{intent:M.EditDescription,mode:f.DEFAULT,description:"[e] edit description",action:()=>(E({mode:f.COMMAND_LINE}),H(`${h.EDIT} description `),c("Exiting context",null))},{intent:M.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(F.enterParentNode(),c("Exiting context",null))},{intent:M.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(F.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:M.NavNextItem,mode:f.DEFAULT,action:()=>(F.navigateToNextItem(),c("Navigating to next item",null))},{intent:M.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(F.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:M.NavToNextContainer,mode:f.DEFAULT,action:()=>(F.navigateToNextContainer(),c("Navigating to next container",null))}]});var Wf,Hf,Al,Tl=y(()=>{"use strict";be();Wf=500,Hf=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Al=e=>{let t=Hf(e);t&&Ir(n=>(n+t).slice(0,Wf))}});var Kf,qf,wl,Ml=y(()=>{"use strict";Tl();te();S();be();w();Vt();gi();Kf=[f.COMMAND_LINE,f.PALETTE],qf=e=>[{intent:M.MoveCursorLeft,mode:e,action:()=>(Ws(-1),c("Moving cursor left",null))},{intent:M.MoveCursorRight,mode:e,action:()=>(Ws(1),c("Moving cursor right",null))},{intent:M.MoveCursorLeftOfWord,mode:e,action:()=>(Hs("left"),c("Moving cursor left of word",null))},{intent:M.MoveCursorRightOfWord,mode:e,action:()=>(Hs("right"),c("Moving cursor right of word",null))},{intent:M.AutoCompleteCommand,mode:e,action:()=>(Ir((t,{remainder:n})=>{let o=n?t+n:t,r="";return o==="edit title "&&(r=g().selectedNode?.title??""),o+r}),c("Auto-completing command",null))},{intent:M.CaptureInput,mode:e,action:(t,{sequence:n})=>(Al(n??""),c("Capturing input",null))},{intent:M.EraseInput,mode:e,action:()=>(Fd(),c("Erasing input",null))},{intent:M.EraseInputWord,mode:e,action:()=>(Bd(),c("Erasing input word",null))}],wl=[{intent:M.Confirm,mode:f.COMMAND_LINE,action:()=>(ft(),c("Executing command",null))},{intent:M.ViewHelp,mode:f.DEFAULT,action:()=>(E({mode:f.HELP}),c("Viewing help",null))},...Kf.flatMap(qf),{intent:M.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(E({mode:f.DEFAULT}),c("Exiting command line",null))},{intent:M.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(_d(),c("Getting last command from history",null))},{intent:M.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>($d(),c("Getting next command from history",null))}]});import Pl from"chalk";var Wr,kl,Ll,fi,Dl=y(()=>{"use strict";te();se();Le();Wr=Pl.dim.hex(R.secondary2)(": for command line"),kl="q to exit",Ll=`${Pl.hex(R.accent)("m")} to confirm`,fi={[D.WORKSPACE]:[Wr],[D.BOARD]:[Wr],[D.BOARD+f.COMMAND_LINE]:[Wr],[D.SWIMLANE]:[Wr],[D.TICKET+f.HELP]:[kl],[D.SWIMLANE+f.HELP]:[kl],[D.TICKET]:[],[D.FIELD]:[],[D.SWIMLANE+f.MOVE]:[Ll],[D.TICKET+f.MOVE]:[Ll]}});var Co,zf,Vf,Fl,Bl=y(()=>{"use strict";w();Fn();In();Co=e=>e.trim().toLocaleLowerCase(),zf=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Vf=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>{let o=t[n];return o?Dn(n,o.name):void 0}).filter(n=>!!n)},Fl=(e,t)=>{let n=Co(t.value);if(!n)return!0;switch(t.target){case"title":return Co(e.title??"").includes(n);case"description":return Co(e.props.description??"").includes(n);case"tag":return zf(e).map(Co).some(r=>r.includes(n));case"assignee":return Vf(e).map(Co).some(r=>r.includes(n));case"ref":return ma(e.id,t.value);default:return!0}}});function Ol(e,t,n){let o=t[e];if(!o)return i("buildBreadCrumb(): current node not found");let r=[],s=o;for(;s&&(r.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let d=r[r.length-1];return!d||d.id!==n?i("buildBreadCrumb(): node is not connected to root"):(r.reverse(),c("Breadcrumb built",r))}var Ul=y(()=>{"use strict";S()});var _l,$l=y(()=>{"use strict";_l=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t}});import{useSyncExternalStore as Gf}from"react";function Wl(e){let{contextNodeId:t,mode:n,rootNodeId:o,nodes:r,filters:s}=e;if(!t)return i("derive(): contextNodeId is missing");if(!o)return i("derive(): rootNode is missing");if(!r[o])return i("derive(): unable to find root node");let l=r[t];if(!l)return i("Unable to derive state, contextNode not found");let u=Ol(t,r,o);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,v=fi[p+n]??fi[p]??[],x=[...Sl,...fl[p]??[],...wl],C=_l(x),A=Xf(r,s),T=A[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:v,availableActions:x,actionIndex:C,selectedNode:T,renderedChildrenIndex:A})}function no(e){vi=e;let t=Ze(process.cwd()),n=!1;if(!a(t)){let s=ht(t.value);if(a(s))return i(s.message);n=!0}let o={readOnly:!1,filters:[],tags:{},contributors:{},mode:f.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{},attachments:{}},r=Wl(o);return a(r)?r:(un=r.value,jl(),c("State initialized",null))}function me(e){let t=g(),n=e(t),o=Wl(n);return a(o)?i(o.message??"Unable to update state"):(un=o.value,jl(),c("State updated",null))}var un,vi,hi,jl,Yf,g,Fe,E,Ue,Xf,J,At,en,w=y(()=>{"use strict";vl();Cl();Ml();Dl();Mt();te();se();S();ue();Bl();Ul();$l();hi=new Set,jl=()=>{for(let e of hi)e()},Yf=e=>(hi.add(e),()=>hi.delete(e));g=()=>{if(!un)throw new Error("State not initialized. Call initWorkspaceState() first.");return un},Fe=()=>un?c("Retrieved state",un):i("State not initialized. Call initWorkspaceState() first.");E=e=>me(t=>({...t,...e})),Ue=()=>Gf(Yf,g,g),Xf=(e,t)=>{let n={};for(let o of Object.values(e))k(o)&&t.length>0&&!t.every(r=>Fl(o,r))||!o.parentNodeId||o.isDeleted||((!o.parentNodeId||!n[o.parentNodeId])&&(n[o.parentNodeId]=[]),n[o.parentNodeId].push(o));for(let o of Object.keys(n))n[o].sort((r,s)=>{let d=e[r.id],l=e[s.id];return!d||!l?0:d.rank.localeCompare(l.rank)});return n},J=e=>g()?.renderedChildrenIndex[e]??[],At=()=>vi?no(vi):i("Cannot reset state: no initial workspace found"),en=()=>un!==void 0});var yi,Hr,Kr,bi,Ye,ir=y(()=>{"use strict";Qi();S();w();yi=e=>{en()&&(E({syncStatus:e}),Ji({type:"sync-status",payload:e}))},Hr=(e="Syncing...")=>{yi({status:"syncing",msg:e})},Kr=(e="Synced")=>{yi({status:"synced",msg:e})},bi=e=>{yi({status:"failed",msg:e})},Ye=e=>(bi(e),i(e))});import{decodeTime as nL}from"ulid";var Hl=y(()=>{"use strict";S()});var Jf,Qf,ar,Ss=y(()=>{"use strict";S();ir();Ns();Po();at();kt();Ho();Hl();Jf=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=G("getRepoRootDir",await it(e));if(a(n))return i(n.message);let o=n.value;logger.debug("[sync] repo root",o);let r=G("getStateBranchRoot",Me({repoRoot:o}));if(a(r))return i(r.message);let s=r.value;logger.debug("[sync] state branch root",s);let d=G("ensureInitialCommit",await Vi(o));if(a(d))return i(d.message);logger.debug("[sync] initial commit result",{created:d.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:s,ensureUpstream:t});let l=G("bootstrapStateBranchStorage",await Xi({repoRoot:o,stateBranchRoot:s,ensureUpstream:t}));if(a(l))return i(l.message);logger.debug("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let u=G("hasInProgressGitOperation(stateBranchRoot)",await Fo(s));if(a(u))return i(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value)return logger.info("[sync] state branch git operation in progress"),i("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:s});let m=G("ensureStateBranchLayout",Ki(o,s));return a(m)?i(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:s,bootstrapped:l.value}),c("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:s,bootstrapped:l.value}))},Qf=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let o=G("stageStateBranchOwnEventFile",await Wo({stateBranchRoot:t,eventFileName:n}));if(a(o))return i(o.message);let r=G("stageStateBranchMediaFiles",await Gi({stateBranchRoot:t}));if(a(r))return i(r.message);let s=G("hasStagedChanges(after stage)",await Oi(t));if(a(s))return i(s.message);if(logger.debug("[sync] state branch change check after stage result",{changed:s.value}),!s.value)return logger.info("[sync] no own event file changes to commit"),c("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let d=G("createStateBranchSyncCommit",await Yi({repoRoot:e,stateBranchRoot:t}));return a(d)?i(d.message):(logger.debug("[sync] created sync commit",d.value),c("Committed own event file",{createdCommit:!0,commitSha:d.value}))},ar=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),i("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),i("Own event file must end with .jsonl");Hr();let n=G("ensureSyncReady",await Jf({cwd:e,ensureUpstream:!0}));if(a(n))return Ye(n.message);let{repoRoot:o,stateBranchRoot:r,bootstrapped:s}=n.value,d=G("isDetachedHead(stateBranchRoot)",await Ui(r));if(a(d))return Ye(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return Ye("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,p=!1,v=G("getStateBranch",fn(o));if(a(v))return Ye(v.message);let x=v.value;logger.debug("[sync] resolved state branch",{stateBranch:x,stateBranchRoot:r});let C=G("commitOwnEventFileToStateBranch",await Qf({repoRoot:o,stateBranchRoot:r,ownEventFileName:t}));if(a(C))return Ye(C.message);l=C.value.createdCommit,u=C.value.commitSha;let A=G("pullBranchRebaseIfPresent",await ss({cwd:r,branch:x}));if(a(A))return Ye(A.message);if(m=A.value,l||s){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:s,stateBranchRoot:r});let T=G("pushStateBranch",await Jn({stateBranchRoot:r,repoRoot:o}));if(a(T)&&Bi(T.message)){let _=G("pullBranchRebaseIfPresent(retry)",await ss({cwd:r,branch:x}));if(a(_))return Ye(_.message);m=m||_.value,T=G("pushStateBranch(retry)",await Jn({stateBranchRoot:r,repoRoot:o}))}if(a(T))return Ye(T.message);p=T.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:r});let T=G("git rev-parse HEAD",await j({args:["rev-parse","HEAD"],cwd:r}));if(a(T))return Ye(T.message);u=T.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Kr(p?"Synced and pushed":m||l?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),c("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:r,createdCommit:l,commitSha:u,pulled:m,pushed:p,bootstrapped:s})}});var Kl=y(()=>{"use strict"});var OL,ql,xi=y(()=>{"use strict";at();kt();ri();mo();Xt();xt();Kl();S();Mt();vr();ue();w();OL=Promise.resolve(),ql=(e,t)=>{let n=new Map,o=new Set,r=d=>{let l=new Set,u=d;for(;u&&!l.has(u);){if(o.has(u))return u;l.add(u),u=n.get(u)}return null},s=[];for(let d of e){let l=d.payload,u=l?.id;u&&(d.action==="add.board"&&o.add(u),l.parent&&n.set(u,l.parent),(u===t||r(u)===t)&&s.push(d))}return s}});import{decodeTime as HL,ulid as W}from"ulid";var qr,le,ge,fe,Zf,zl,Vl,ev,Gl,Yl,Xl,Jl,Ql,Zl,eu,tu,nu,ou,ru,su,iu,au,du,cu,lu,uu,mu,pu,tv,gu,fu,vu,hu,yu,bu=y(()=>{"use strict";at();kt();Ho();Ss();sn();ui();rr();Xt();Qt();nt();xi();ti();Sn();se();S();Mt();ce();lt();w();ir();ue();ut();Fn();yt();In();hn();go();gn();xi();qr=e=>{let t=Ze(e??process.cwd());return a(t)?i(t.message):c("Resolved Epiq repo root",t.value)},le=async(e,t)=>{let n=qr(e);if(a(n))return n;let o=Me({repoRoot:n.value});if(a(o))return i(o.message);let r=ko(),s=await Xn({repoRoot:n.value,stateBranchRoot:o.value,stateBranchName:r.stateBranch});if(a(s))return i(s.message);if(t?.pull??!1){let u=await j({cwd:o.value,args:["pull","--ff-only"]});a(u)&&ve.info(3,u.message)}let d=Ge(o.value);if(a(d))return i(d.message);let l=Cn(d.value);return a(l)?i(l.message):c("Booted Epiq state",{repoRoot:n.value,stateBranchRoot:o.value})},ge=()=>{let e=hd();return a(e)?i(e.message):e.value.userId?e.value.userName?c("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):i("Unable to retrieve user name"):i("Unable to retrieve user id")},fe=()=>{let e=Fe();return a(e)?i(e.message):e},Zf=e=>(e.props.tags??[]).map(t=>I.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Pe(t.name)})),zl=()=>{let e=Fe(),t=a(e)?[]:e.value.eventLog??[],n=new Map;for(let o of t)o.userId&&o.userName&&n.set(o.userId,o.userName);return n},Vl=(e,t)=>{let n=new Map(e);for(let o of Object.values(t)){if(o.tombstoned){n.set(o.id,o.name);continue}n.set(o.id,Pn(o.name,n.get(o.id))??o.name)}return n},ev=(e,t=new Map)=>(e.props.assignees??[]).map(n=>I.getContributor(n)).filter(n=>n!=null).map(n=>{let o=n.tombstoned?n.name:Pn(n.name,t.get(n.id))??n.name;return{id:n.id,name:o,color:Pe(o)}}),Gl=async(e={})=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=fe();if(a(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="BOARD"&&!r.isDeleted).map(r=>({id:r.id,ref:tt(r.id),title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return c("Listed boards",o)},Yl=async(e={})=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=fe();if(a(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="SWIMLANE"&&!r.isDeleted).filter(r=>!e.boardId||r.parentNodeId===e.boardId).map(r=>({id:r.id,title:r.title,boardId:r.parentNodeId,isClosed:r.id===he,readonly:!!r.readonly}));return c("Listed swimlanes",o)},Xl=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=fe();if(a(n))return n;let o=n.value.nodes,r=zl(),s=Object.values(o).filter(k).filter(d=>!d.isDeleted).filter(d=>e.includeClosed||d.parentNodeId!==he).filter(d=>e.boardId?(d.parentNodeId?o[d.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).map(d=>({id:d.id,ref:tt(d.id),title:ze(d.title),description:d.props.description??"",parentNodeId:d.parentNodeId,isClosed:d.parentNodeId===he,readonly:!!d.readonly,tags:Zf(d),assignees:ev(d,r)}));return c("Listed issues",s)},Jl=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=Zt(e.parentId,n.value,t.value.stateBranchRoot);if(a(r))return r;let s=Fr({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(a(s))return s;let d=[...s.value],l=d.find(v=>v.action==="add.issue")?.payload.id;if(!l)return i("Unable to determine created issue id");e.description&&d.push({id:W(),...n.value,action:"edit.description",payload:{id:l,md:e.description}});let u=[];for(let v of e.tagNames??[]){let x=ze(v).trim();if(!x||u.some(T=>T.name===x))continue;let C=Object.values(o.value.tags).find(T=>T.name===x),A=C?.id??W();C||d.push({id:W(),...n.value,action:"create.tag",payload:{id:A,name:x}}),d.push({id:W(),...n.value,action:"add.issue.tag",payload:{id:l,tag:A}}),u.push({id:A,name:x})}let m=[];for(let v of e.assigneeNames??[]){let x=ze(v).trim();if(!x||m.some(T=>T.name===x))continue;let C=Object.values(o.value.contributors).find(T=>T.name===x),A=C?.id??W();C||d.push({id:W(),...n.value,action:"create.contributor",payload:{id:A,name:x}}),d.push({id:W(),...n.value,action:"add.issue.assignee",payload:{id:l,assignee:A}}),m.push({id:A,name:x})}let p=B(d,t.value.stateBranchRoot);return a(p)?i(p.message):c("Created issue",{id:l,title:e.title,parentId:e.parentId,description:e.description??"",tags:u,assignees:m})},Ql=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=Ft(he,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(o))return o;let r={id:W(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:he,rank:o.value}},s=B([r],t.value.stateBranchRoot);return a(s)?i(s.message):c("Closed issue",{id:e.issueId})},Zl=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Target node is not issue");if(r.parentNodeId!==he)return i("Issue is not closed");let s=Lr(r);if(!s)return i("Unable to resolve previous parent from issue history");if(s===he)return i("Previous parent resolves to closed swimlane");let d=o.value.nodes[s];if(!d)return i("Previous parent no longer exists");let l=Ft(d.id,r.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(l))return l;let u={id:W(),...n.value,action:"reopen.issue",payload:{id:r.id,parent:d.id,rank:l.value}},m=B([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Reopened issue",{id:r.id,parentId:d.id})},eu=async e=>{let t=qr(e.repoRoot);if(a(t))return t;let n=ge();if(a(n))return n;let o=Me({repoRoot:t.value});if(a(o))return o;let r=Ge(o.value);if(a(r))return r;let s=Cn(r.value);if(a(s))return s;let d=Ft(e.parentId,e.issueId,e.position??{at:"end"},n.value,o.value);if(a(d))return d;let l={id:W(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:d.value}},u=B([l],o.value);return a(u)?i(u.message):c("Moved issue",{id:e.issueId,parentId:e.parentId})},tu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.boardId];if(!r)return i("Board not found");if(!Ko(r))return i("Target parent must be a board");let s=ze(e.title);if(!s.trim())return i("Swimlane title cannot be empty");let d=Zt(e.boardId,n.value,t.value.stateBranchRoot);if(a(d))return d;let l=W(),u={id:W(),...n.value,action:"add.swimlane",payload:{id:l,name:s,parent:e.boardId,rank:d.value}},m=B([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Created swimlane",{id:l,title:s,boardId:e.boardId})},nu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.swimlaneId];if(!r)return i("Swimlane not found");if(!zt(r))return i("Edit target must be a swimlane");if(r.readonly)return i("Cannot edit readonly swimlane");let s=ze(e.title);if(!s.trim())return i("Swimlane title cannot be empty");if(r.title===s)return c("No changes made",{id:e.swimlaneId,title:s});let d={id:W(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:s}},l=B([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited swimlane title",{id:e.swimlaneId,title:s})},ou=async e=>{let t=qr(e.repoRoot);if(a(t))return t;let n=ge();if(a(n))return n;let o=Me({repoRoot:t.value});if(a(o))return o;let r=Ge(o.value);if(a(r))return r;let s=Cn(r.value);if(a(s))return s;let d=Ft(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,o.value);if(a(d))return d;let l={id:W(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:d.value}},u=B([l],o.value);return a(u)?i(u.message):c("Moved swimlane",{id:e.swimlaneId,boardId:e.boardId})},ru=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.swimlaneId];if(!r)return i("Swimlane not found");if(!zt(r))return i("Delete target must be a swimlane");let s={id:W(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},d=B([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Deleted swimlane",{id:e.swimlaneId})},su=async(e={})=>{Hr();let t=qr(e.repoRoot);if(a(t))return i("Sync failed");let n=ge();if(a(n))return n;let o=await ar({cwd:t.value,ownEventFileName:Jt(n.value)});return a(o)?(bi(o.message),o):(Kr(),c("Synced",o.value))},iu=async(e={})=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=fe();return a(n)?n:c("Retrieved Epiq state",{root:t.value.repoRoot,stateBranchRoot:t.value.stateBranchRoot,nodes:n.value.nodes,rootNodeId:n.value.rootNodeId,contextNode:n.value.contextNode,selectedIndex:n.value.selectedIndex,eventLog:n.value.eventLog})},au=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Edit target must be an issue");if(r.readonly)return i("Cannot edit readonly issue");let s=r.props.description??"";if(s===e.description)return c("No changes made",{id:e.issueId,description:s});let d={id:W(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},l=B([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited issue description",{id:e.issueId,description:e.description})},du=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Edit target must be an issue");if(r.readonly)return i("Cannot edit readonly issue");let s=ze(e.title);if(!s.trim())return i("Issue title cannot be empty");if(r.title===s)return c("No changes made",{id:e.issueId,title:s});let d={id:W(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},l=B([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited issue title",{id:e.issueId,title:s})},cu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Tag target must be an issue");if(r.readonly)return i("Cannot tag readonly issue");let s=ze(e.tagName).trim();if(!s)return i("Tag name cannot be empty");let d=Object.values(o.value.tags).find(p=>p.name===s),l=d?.id??W(),u=[...d?[]:[{id:W(),...n.value,action:"create.tag",payload:{id:l,name:s}}],{id:W(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:l}}],m=B(u,t.value.stateBranchRoot);return a(m)?i(m.message):c("Added issue tag",{id:e.issueId,tag:{id:l,name:s}})},lu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Untag target must be an issue");if(r.readonly)return i("Cannot untag readonly issue");if(!o.value.tags[e.tagId])return i("Tag not found");let s={id:W(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},d=B([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue tag",{id:e.issueId,tagId:e.tagId})},uu=async(e,t)=>{let n=Ge(e);if(a(n))return;let o;for(let r of n.value)r.userId===t&&(o=r.userName??o);return o===void 0?void 0:{id:t,name:o}},mu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Assign target must be an issue");if(r.readonly)return i("Cannot assign readonly issue");let s=e.self?n.value.userId:e.assigneeId;if(s){let T=o.value.contributors[s],_=T?void 0:await uu(t.value.stateBranchRoot,s);if(!T&&!_)return i("Unknown assignee id");let z=T??_,K=[...T?[]:[{id:W(),...n.value,action:"create.contributor",payload:{id:z.id,name:z.name}}],{id:W(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:z.id}}],U=B(K,t.value.stateBranchRoot);return a(U)?i(U.message):c("Added issue assignee",{id:e.issueId,assignee:{id:z.id,name:z.name}})}let d=ze(e.assigneeName??"").trim();if(!d)return i("Provide assigneeId, self or assigneeName");let u=[...Vl(zl(),o.value.contributors).entries()].filter(([,T])=>T===d);if(u.length>1)return i(`"${d}" matches ${u.length} contributors (${u.map(([T])=>T).join(", ")}). Assign by assigneeId to choose.`);let m=u[0];if(!m&&!e.createUnlinked)return i(`No contributor named "${d}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[p=W(),v=d]=m??[],C=[...!!o.value.contributors[p]?[]:[{id:W(),...n.value,action:"create.contributor",payload:{id:p,name:v}}],{id:W(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:p}}],A=B(C,t.value.stateBranchRoot);return a(A)?i(A.message):c("Added issue assignee",{id:e.issueId,assignee:{id:p,name:v}})},pu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;if(!o.value.contributors[e.contributorId])return i("Contributor not found");if(await uu(t.value.stateBranchRoot,e.contributorId))return i("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let d=[{id:W(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],l=B(d,t.value.stateBranchRoot);return a(l)?i(l.message):c("Tombstoned contributor",{id:e.contributorId,name:Vo})},tv=async(e,t)=>{let n=Ge(e);if(a(n))return;let o;for(let r of n.value){if(r.action!=="create.contributor")continue;let s=r.payload;s.id===t&&s.name&&(o=s.name)}return o},gu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.contributors[e.contributorId];if(!r)return i("Contributor not found");if(!r.tombstoned)return i("Contributor is not tombstoned");let s=await tv(t.value.stateBranchRoot,e.contributorId);if(!s)return i("Cannot restore this contributor \u2014 no original name found in the event log");let d=[{id:W(),...n.value,action:"restore.contributor",payload:{id:e.contributorId,name:s}}],l=B(d,t.value.stateBranchRoot);return a(l)?i(l.message):c("Restored contributor",{id:e.contributorId,name:s})},fu=async(e={})=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=Ge(t.value.stateBranchRoot);if(a(r))return i(r.message);let s=e.boardId?ql(r.value,e.boardId):r.value,d=new Map,l=new Set,u=new Set;for(let x of r.value)x.userId&&u.add(x.userId);for(let x of s)x.userId&&(d.set(x.userId,x.userName??""),l.add(x.userId));let m=o.value.contributors,v=[...Vl(d,m).entries()].map(([x,C])=>({id:x,name:C,color:Pe(C),isSelf:x===n.value.userId,isExternal:!l.has(x),isRemoved:m[x]?.tombstoned===!0,hasAuthoredAnywhere:u.has(x)}));return c("Listed board contributors",v)},vu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Unassign target must be an issue");if(r.readonly)return i("Cannot unassign readonly issue");if(!o.value.contributors[e.assigneeId])return i("Assignee not found");let s={id:W(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},d=B([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},hu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Comment target must be an issue");if(r.readonly)return i("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return i("Comment cannot be empty");let d=W(),l={id:W(),...n.value,action:"add.issue.comment",payload:{id:d,issue:e.issueId,md:s,author:n.value.userId}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Added issue comment",{id:d,issueId:e.issueId,body:s})},yu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!r)return i("Unable to resolve comment");if(r.payload.author!==n.value.userId)return i("You can only delete your own comments");let s=o.value.nodes[r.payload.issue];if(!s)return i("Issue not found");if(!k(s))return i("Comment target must be an issue");if(s.readonly)return i("Cannot delete comment on readonly issue");if(o.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return c("Comment already deleted",{id:e.commentId,issueId:r.payload.issue});let l={id:W(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:r.payload.issue}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Deleted issue comment",{id:e.commentId,issueId:r.payload.issue})}});var Eu={};Au(Eu,{createMcpServer:()=>xu,resultJson:()=>Y,startMcpServer:()=>Iu});import{McpServer as nv}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as ov}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as b}from"zod";var Y,xu,Iu,Nu=y(async()=>{"use strict";S();bu();Y=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),xu=()=>{let e=new nv({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:b.object({repoRoot:b.string().optional()})},async t=>Y(await iu(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues. Pass boardId to scope results to a single board and reduce response size.",inputSchema:b.object({repoRoot:b.string().optional(),includeClosed:b.boolean().optional(),boardId:b.string().optional()})},async t=>Y(await Xl(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:b.object({repoRoot:b.string().optional()})},async t=>Y(await Gl(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:b.object({repoRoot:b.string().optional(),boardId:b.string().optional()})},async t=>Y(await Yl(t))),e.registerTool("epiq_swimlane_create",{description:"Create an Epiq swimlane on a board",inputSchema:b.object({repoRoot:b.string().optional(),boardId:b.string().min(1),title:b.string().min(1)})},async t=>Y(await tu(t))),e.registerTool("epiq_swimlane_title_edit",{description:"Edit an Epiq swimlane title",inputSchema:b.object({repoRoot:b.string().optional(),swimlaneId:b.string().min(1),title:b.string().min(1)})},async t=>Y(await nu(t))),e.registerTool("epiq_swimlane_move",{description:"Move/reorder an Epiq swimlane, optionally to another board",inputSchema:b.object({repoRoot:b.string().optional(),swimlaneId:b.string().min(1),boardId:b.string().min(1),position:b.discriminatedUnion("at",[b.object({at:b.literal("start")}),b.object({at:b.literal("end")}),b.object({at:b.literal("before"),sibling:b.string().min(1)}),b.object({at:b.literal("after"),sibling:b.string().min(1)})]).optional()})},async t=>Y(await ou(t))),e.registerTool("epiq_swimlane_delete",{description:"Delete (archive) an Epiq swimlane. This also archives every issue contained in it.",inputSchema:b.object({repoRoot:b.string().optional(),swimlaneId:b.string().min(1)})},async t=>Y(await ru(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue. Optionally set description, tags, and assignees atomically in the same call instead of separate follow-up edits.",inputSchema:b.object({title:b.string().min(1),parentId:b.string().min(1),repoRoot:b.string().optional(),description:b.string().optional(),tagNames:b.array(b.string()).optional(),assigneeNames:b.array(b.string()).optional()})},async t=>Y(await Jl(t))),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),description:b.string(),repoRoot:b.string().optional()})},async t=>Y(await au(t))),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),title:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await du(t))),e.registerTool("epiq_issue_tag_add",{description:"Add a tag to an Epiq issue, creating the tag if it does not exist",inputSchema:b.object({issueId:b.string().min(1),tagName:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await cu(t))),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),tagId:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await lu(t))),e.registerTool("epiq_contributor_list",{description:"List people who can be assigned: everyone who has authored an event (optionally scoped to one board) unioned with the contributor registry. Use these ids with epiq_issue_assignee_add rather than assigning by name.",inputSchema:b.object({boardId:b.string().min(1).optional(),repoRoot:b.string().optional()})},async t=>Y(await fu(t))),e.registerTool("epiq_contributor_remove",{description:"Remove an external contributor from the assignee suggestion lists. Their id and every reference to it survive, so existing assignments stay intact and the event log is untouched. Refused for anyone who has authored events, since their name is in the log regardless.",inputSchema:b.object({contributorId:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await pu(t))),e.registerTool("epiq_contributor_restore",{description:"Put a contributor removed with epiq_contributor_remove back into the suggestion lists, under the name they were created with.",inputSchema:b.object({contributorId:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await gu(t))),e.registerTool("epiq_issue_assignee_add",{description:"Assign a contributor to an Epiq issue. Pass self:true to assign yourself. Prefer assigneeId otherwise, which assigns a known contributor (from the registry or the event log) and fails if the id is unknown. assigneeName matches an existing contributor by name; to create somebody new from a name you must also pass createUnlinked, which adds them as an external (non-contributor) assignee.",inputSchema:b.object({issueId:b.string().min(1),assigneeId:b.string().min(1).optional(),self:b.boolean().optional(),assigneeName:b.string().min(1).optional(),createUnlinked:b.boolean().optional(),repoRoot:b.string().optional()})},async t=>Y(await mu(t))),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),assigneeId:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await vu(t))),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),body:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await hu(t))),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:b.object({commentId:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await yu(t))),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:b.object({issueId:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await Zl(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await Ql(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:b.object({issueId:b.string().min(1),parentId:b.string().min(1),position:b.discriminatedUnion("at",[b.object({at:b.literal("start")}),b.object({at:b.literal("end")}),b.object({at:b.literal("before"),sibling:b.string().min(1)}),b.object({at:b.literal("after"),sibling:b.string().min(1)})]).optional(),repoRoot:b.string().optional()})},async t=>Y(await eu(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote (pull remote changes and push local ones). Other Epiq MCP tools only read and write local state and never sync automatically \u2014 call this on demand when you need to see or publish the latest remote changes.",inputSchema:b.object({repoRoot:b.string().optional()})},async t=>Y(await su(t))),e},Iu=async()=>{let e=xu(),t=new ov;await e.connect(t)};await Iu()});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;await Nu().then(()=>Eu);
57
+ `,ii.writeFileSync(t,n,"utf8"),ve.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)}});import Nf from"node:fs";import Dc from"node:path";var Rf,ee,Fc,Bc=y(()=>{"use strict";Pc();ko();at();kt();Ho();We();ao();rr();xt();nt();te();C();Lt();be();Le();w();ue();Rf=async e=>{let t=await j({cwd:e,args:["status","--porcelain"]});return a(t)?t:c("Checked git diff",t.value.stdout.trim().length>0)},ee=(e,t)=>i(`[${e}] ${t}`),Fc=async()=>{H("");let e=Lo(),t=await it(process.cwd());if(a(t))return ee(1,t.message);let n=t.value,o=await Fo(n);if(a(o))return ee(2,o.message);if(o.value)return ee(2,`Cannot initialize Epiq while a git operation is in progress: ${o.value}`);let r=await Rf(n);if(a(r))return ee(2.5,r.message);if(r.value)return ee(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(Qr(n))return ee(4,"Epiq project already initialized");let s=cr();if(!s.isSetupDone||!s.userName)return ee(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let d=ie(),l=d.userName,u=d.userId;if(!u||!l)return ee(5,"Missing Epiq user id");let m=e.stateBranch,p=await Oo({repoRoot:n,branch:m});if(a(p))return ee(6,p.message);if(p.value)return ee(6,`State branch already exists: ${m}`);let v=await cs({repoRoot:n,stateBranchName:m});if(a(v))return ee(6,v.message);let x=$o();if(a(x))return ee(7,x.message);let S=Dc.join(_o(),e.projectId),A=await Xn({repoRoot:n,stateBranchRoot:S,stateBranchName:m});if(a(A))return ee(8,A.message);let T=Dc.join(S,".epiq");Nf.mkdirSync(T,{recursive:!0});let _=za({userId:u,userName:l});if(a(_))return ee(9,_.message);for(let Gr of _.value){let Ni=tr({event:Gr,rootDir:S});if(a(Ni))return ee(9,Ni.message)}let z=await Wo({stateBranchRoot:S,eventFileName:Qt({userId:u,userName:l})});if(a(z))return ee(10,z.message);let K=await hn({cwd:S,message:"[epiq:init]"});if(a(K))return ee(10,K.message);let U=await kc(n);if(a(U))return ee(11,U.message);let Se=Ai({repoRoot:n,fileContents:e});if(a(Se))return ee(12,Se.message);let pn=await de.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(pn))return ee(13,pn.message);let $=await de.commit({cwd:n,message:"[epiq:init-project]"});if(a($))return ee(13,$.message);let V="Project initialized!",gn=await j({cwd:n,args:["push","-u","origin","HEAD"]});a(gn)&&(V+=` Warn: [init:14] ${gn.message}`);let qt=await Jn({repoRoot:n,stateBranchRoot:S});a(qt)&&(V+=` Warn: [init:15] ${qt.message}`);let Ii=bt(_.value).filter(a);if(Ii.length>0)return ee(16,Ii.map(Gr=>Gr.message).join(`
58
+ `));let Vr=Fe();if(a(Vr))return ee(16,Vr.message);let{rootNodeId:Cu,nodes:Su}=Vr.value,Ei=Su[Cu];return Ei?(F.navigate({contextNode:Ei,selectedIndex:0}),E({hasProjectDefinition:!0,mode:f.DEFAULT}),c(V,null)):ee(16,"Unable to resolve initialized root node")}});import{ulid as Cf}from"ulid";function di(e){let t=Uc();if(a(t))return t;let{contextNode:n,nodes:o}=g();if(!n.parentNodeId)return i("Missing parent node id");let r=o[n.parentNodeId];if(!r)return i("Missing parent node");let s=ne(r.id),d=s.findIndex(({id:m})=>m===n.id);if(d<0)return i("Current node not found among siblings");let l=s[d+e];if(!l)return i("Missing sibling node");let u=_c({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:$c(u.value)}function ci(e){let t=Uc();if(a(t))return t;let{contextNode:n,selectedIndex:o}=g(),s=ne(n.id)[o+e];if(!s)return i("Missing sibling node");let d=_c({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:$c(d.value)}var Oc,Kt,Ro,Uc,ai,_c,$c,li=y(()=>{"use strict";xt();nt();C();lt();w();Oc=null,Kt=()=>structuredClone(Oc),Ro=e=>{Oc=e},Uc=()=>{let{contextNode:e,selectedIndex:t}=g(),o=ne(e.id)[t];return o?c("Resolved selected child",o):i("Target node not found")},ai=({id:e,parentId:t,position:n={at:"end"}})=>{let o=ne(t).filter(r=>r.id!==e);return nr(o,n)},_c=({id:e,parentId:t,position:n={at:"end"}})=>{let o=ae();if(a(o))return i("Unable to resolve user ID");let r=ai({parentId:t,id:e,position:n});return a(r)?r:c("Created pending move state",{id:Cf(),...o.value,action:"move.node",payload:{id:e,parent:t,rank:r.value.rank}})},$c=e=>{Ro(e);let t=Ft(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as Sf}from"ulid";var jc,Fr,Wc,Hc=y(()=>{"use strict";We();li();Zt();nt();te();C();lt();be();w();ue();jc=()=>{let e=Kt();if(!e)return i("No pending move state");let t=e.payload.id,n=e.payload.parent,o=g().nodes[n];if(!o)return i("Move parent not found");let r=ne(n).findIndex(s=>s.id===t);return r===-1?i("Moved node not found among rendered children"):(F.navigate({contextNode:o,selectedIndex:r}),c("Synchronized navigation to moved node",null))},Fr=(e,t="Moved preview")=>{if(a(e))return e;let n=jc();return a(n)?n:(E({mode:f.MOVE}),c(t,null))},Wc=async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=Q().commandMeta,{contextNode:n,selectedIndex:o}=g(),r=ne(n.id)[o];if(!r)return E({mode:f.DEFAULT}),i("No move target");if(t==="start"){if(r.readonly)return i("Target node is read-only");if(o===-1)return i("No item selected");if(!r.parentNodeId)return i("Target has no parent");let s=ne(r.parentNodeId),d=s.findIndex(({id:v})=>v===r.id);if(d===-1)return i("Target not found among siblings");let l=s[d-1],u=s[d+1],m=u!=null?{at:"before",sibling:u.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},p=ai({parentId:r.parentNodeId,id:r.id,position:m});return a(p)?p:(Ro({id:Sf(),action:"move.node",payload:{id:r.id,parent:r.parentNodeId,rank:p.value.rank},...e.value}),E({mode:f.MOVE}),c("Move initialized",null))}if(t==="next")return Fr(ci(1));if(t==="previous")return Fr(ci(-1));if(t==="to-next")return Fr(di(1));if(t==="to-previous")return Fr(di(-1));if(t==="confirm"){let s=Kt();if(!s)return i("No pending move to confirm");let d=await st();if(a(d))return d;let l=B([s],d.value);if(a(l))return l;let u=jc();return a(u)?u:(Ro(null),E({mode:f.DEFAULT}),c("Moved item",null))}return t==="cancel"?(Ro(null),E({mode:f.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as Af,ulid as Tf}from"ulid";var wf,Br,ui=y(()=>{"use strict";C();wf=Af(),Br=({name:e,parent:t,rank:n,user:{userId:o,userName:r}})=>{let s=wf();return c("Created issue events",[{id:Tf(),userId:o,userName:r,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as Or}from"ulid";var Kc,qc=y(()=>{"use strict";We();ui();Zt();nt();ut();C();ce();lt();w();ue();Kc=async(e,t)=>{let n=ae();if(a(n))return i("Unable to resolve user ID");let o=await st();if(a(o))return o;let r=o.value;if(!t.inputString)return i(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:d,selectedIndex:l}=g(),u=m=>{let p=B([m],r);if(a(p))return p;let v=I.getNode(p.value[0].result.id);if(!v)return i("Created node not found");if(!v.parentNodeId)return p;let x=I.getNode(v.parentNodeId);return x?(F.navigate({contextNode:x,selectedIndex:I.getSiblings(v.parentNodeId).findIndex(({id:S})=>S===v.id)}),p):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=I.getNode(m);if(!p)return i("Workspace not found");let v=en(p.id,n.value,r);return a(v)?v:u({id:Or(),action:"add.board",payload:{id:Or(),name:t.inputString,parent:p.id,rank:v.value},...n.value})}if(t.modifier==="swimlane"){let m=je(s,"BOARD");if(a(m))return i("Unable to add swimlane in this context");let p=en(m.value.id,n.value,r);return a(p)?p:u({id:Or(),action:"add.swimlane",payload:{id:Or(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=J(d.id)[l],p=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let K=je(s,"SWIMLANE");return a(K)?null:K.value})();if(!p)return i("Unable to add issue in this context");let v=en(p.id,n.value,r);if(a(v))return v;let x=Br({name:t.inputString,parent:p.id,rank:v.value,user:n.value});if(a(x))return x;let S=x.value,A=B([...S],r);if(a(A))return A;if(!A.value[0])return i("Issue creation failed");let z=S.find(K=>K.action==="add.issue")?.payload.id;return z?(F.navigate({contextNode:p,selectedIndex:I.getSiblings(p.id).findIndex(({id:K})=>K===z)}),c("Issue created",null)):i("Unable to determine ticket id")}return c("Success",null)}});var Ur,mi=y(()=>{"use strict";We();Jt();xt();C();w();Ur=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:o})=>{let r=g(),s=Es(n,t);if(a(s))return i(s.message);let{appliedEvents:d,unappliedEvents:l}=s.value,u=Tt();if(a(u))return u;let p=bt(d).filter(a);if(p.length>0)return Tt(),E(r),i(p.map(x=>x.message).join(", "));let v=g().nodes[e];return v?(F.navigate({contextNode:v,selectedIndex:o}),c("",{unappliedEvents:l})):(Tt(),E(r),i("Board did not exist at that date"))}});var Mf,Lf,kf,_r,$r,un,zc,Pf,Vc,pi=y(()=>{"use strict";mo();gs();xt();te();C();w();Mf=20,Lf=16,kf=150,_r=null,$r=null,un=()=>{_r!==null&&(clearInterval(_r),_r=null),$r!==null&&(clearTimeout($r),$r=null)},zc=()=>{un(),E({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Pf=e=>{let t=[],n=0;for(let r=0;r<e.length;r++){let s=r===0?0:Math.max(0,e[r]-e[r-1]);n+=Math.sqrt(s),t[r]=n}let o=n;return t.map((r,s)=>o>0?r/o:(s+1)/e.length)},Vc=({events:e,startTime:t,durationMs:n})=>{un();let o=e.length,r=e.map(v=>sn(v)??t),s=r[o-1]??Date.now(),d=Pf(r),l=Math.max(1,Math.round(n*Mf/1e3)),u=Math.max(Math.round(n/l),Lf),m=0,p=0;E({mode:f.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:o,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),_r=setInterval(()=>{m++;let v=m/l,x=[],S;for(;p<o&&d[p]<=v;){let T=e[p],_=Ft(T);if(a(_)){zc();return}x.push(...fs(T)),S=T,p++}if(p>=o||m>=l){for(;p<o;p++){let _=Ft(e[p]);if(a(_))break}let T=g().replay;E({unappliedEvents:[],replay:T&&{...T,progress:1,appliedCount:o}}),un(),$r=setTimeout(zc,kf);return}let A=g().replay;E({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,v),appliedCount:p,totalCount:o,startTime:t,endTime:s,currentTime:S?sn(S)??A?.currentTime??t:A?.currentTime??t,currentLabel:S?Na(S):A?.currentLabel??"",flashNodeIds:S?[...new Set(x)]:A?.flashNodeIds??[]}})},u)}});var Gc,Yc=y(()=>{"use strict";at();mo();Jt();xt();te();ut();C();be();w();lo();mi();pi();Gc=async()=>{let e=je(g().breadCrumb,"BOARD");if(a(e))return e;let t=await it(process.cwd());if(a(t))return i("Unable to locate repo root");let n=Me({repoRoot:t.value});if(a(n))return n;let{modifier:o,inputString:r}=Q().commandMeta;if(un(),o==="now"){let l=Ge(n.value);if(a(l))return i(l.message);let u=Tt();if(a(u))return u;let p=bt(l.value).filter(a);return p.length>0?i(p.map(v=>v.message).join(", ")):(E({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null}),c("Peeking now",!0))}let s;if(o==="prev"){let l=g().eventLog.at(-1),u=sn(l);if(u===null)return i("No previous event to peek");s=u}else if(o==="next"){let l=g().unappliedEvents.at(0),u=sn(l);if(u===null)return i("No next event to peek");s=u+1}else{let l=on(o||r.trim());if(!l)return i("Invalid peek date");s=l.getTime()}let d=Ur({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(d)?d:(E({mode:f.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:d.value.unappliedEvents,replay:null}),c("Peeking",!0))}});var Xc,Jc=y(()=>{"use strict";at();ut();C();be();w();lo();mi();pi();Xc=async()=>{let e=je(g().breadCrumb,"BOARD");if(a(e))return e;let t=await it(process.cwd());if(a(t))return i("Unable to locate repo root");let n=Me({repoRoot:t.value});if(a(n))return n;let{modifier:o,inputString:r}=Q().commandMeta,{dateInput:s,durationInput:d}=pr(o,r);if(un(),g().syncStatus.status==="syncing")return i("Cannot replay while syncing, try again in a moment");let l=on(s);if(!l)return i("Invalid replay date");let u=d?mr(d):15e3;if(u===null)return i("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=g(),v=Ur({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(v))return v;let{unappliedEvents:x}=v.value;return x.length===0?(Tt(),E(p),c("Nothing to replay from that point",!0)):(Vc({events:x,startTime:m,durationMs:u}),c("Replaying board history",!0))}});import Ff from"zod";var Qc,Zc=y(()=>{"use strict";an();te();C();be();Le();w();Qc=()=>{let e=Q().commandMeta.inputString,t=Ff.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return i("Auto sync duration must be a number of at least 3000 ms");let n=Xe({autoSyncDebounceMs:t.data});return a(n)?n:(Ve({autoSyncIntervalMs:t.data}),E({mode:f.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))}});var el,tl=y(()=>{"use strict";ao();an();te();C();be();Le();w();el=()=>{let e=Q().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=ed(e),n=Xe({autoSync:t});return a(n)?n:(Ve({autoSync:t}),E({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var nl,ol=y(()=>{"use strict";an();te();C();be();Le();w();nl=()=>{let e=Q().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return i("Invalid response");let n=Xe({logLevel:e});return a(n)?n:(Ve({logLevel:e}),E({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});import{spawn as Bf}from"node:child_process";var Of,rl,sl=y(()=>{"use strict";C();Of=()=>{switch(process.platform){case"darwin":return{command:"pbcopy",args:[]};case"win32":return{command:"clip",args:[]};default:return process.env.WAYLAND_DISPLAY?{command:"wl-copy",args:[]}:{command:"xclip",args:["-selection","clipboard"]}}},rl=async e=>new Promise(t=>{let{command:n,args:o}=Of();try{let r=Bf(n,o,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>t(i(`Clipboard tool not available (${n})`))),r.on("close",s=>t(s===0?c("Copied to clipboard",null):i(`Clipboard tool failed (${n})`))),r.stdin.on("error",()=>{}),r.stdin.write(e),r.stdin.end()}catch{t(i(`Clipboard tool not available (${n})`))}})});var Co,il,al=y(()=>{"use strict";C();w();sl();En();co();_t();Co=async(e,t)=>{if(!e.trim())return i(`Nothing to copy: ${t} is empty`);let n=await rl(e);return a(n)?n:c(`Copied ${t} to clipboard`,null)},il=async e=>{let{breadCrumb:t,selectedNode:n}=g(),o=uo({breadCrumb:t,selectedNode:n}),r=o??n;if(!r)return i("Nothing selected to copy from");switch(e.modifier){case ye.REF:return Co(tt(r.id),"ref");case ye.TITLE:return Co(r.title,"title");case ye.DESCRIPTION:return o?Co(o.props?.description??"","description"):i("No issue in scope");case ye.TAGS:{if(!o)return i("No issue in scope");let s=Ot(o).map(({name:d})=>d);return Co(s.join(", "),"tags")}case ye.ASSIGNEES:{if(!o)return i("No issue in scope");let s=Ut(o).map(({name:d})=>d);return Co(s.join(", "),"assignees")}default:return i("Yank one of: ref, title, description, tags, assignees")}}});var dl,cl=y(()=>{"use strict";Cs();te();C();be();w();dl=async()=>{H(""),E({mode:f.DEFAULT});let e=Fe();if(a(e))return i(e.message);if(e.value.syncStatus.status==="syncing")return i("Sync already in progress");E({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await sr();return a(t)?(E({syncStatus:{msg:t.message,status:"failed"}}),t):(E({mode:f.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as we}from"ulid";var Uf,ll,ul,wt,ml,pl=y(()=>{"use strict";Rc();We();an();Zt();nt();ti();Sn();te();ut();se();C();ce();lt();be();Le();w();Dr();ue();Fn();oi();nn();Ks();_t();hr();Lc();Bc();Hc();qc();Yc();Jc();Zc();Us();tl();ol();al();cl();Uf=e=>e.action==="add.issue.comment",ll=e=>Object.values(g().tags).find(t=>t.name===e),ul=()=>{let{eventLog:e=[],contributors:t}=g(),n=new Map,o=new Set;for(let r of e)r.userId&&(n.set(r.userId,r.userName??""),o.add(r.userId));for(let r of Object.values(t)){if(r.tombstoned){n.set(r.id,r.name);continue}n.set(r.id,Pn(r.name,n.get(r.id))??r.name)}return[...n.entries()].map(([r,s])=>({id:r,name:s,isExternal:!o.has(r)}))},wt=async()=>{let e=await st();return a(e)?e:c("Resolved persist root",e.value)},ml=[{systemOnly:!0,intent:P.Move,description:"Internal move-state command",mode:f.COMMAND_LINE,action:Wc},{intent:P.Delete,description:"Delete the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=J(t.id)[n];if(!o)return i("Unable to resolve child to delete");let r=await wt();if(a(r))return r;if(o.context==="COMMENT"){let s=o.id,d=L(t)?t.id:t.parentNodeId;if(!d)return i("Unable to resolve comment issue");let l=g().nodes[d];if(!l||!L(l))return i("Unable to resolve comment issue");let u=l.log?.filter(Uf).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):B([{id:we(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],r.value):i("Unable to resolve comment")}return B([{id:we(),action:"delete.node",payload:{id:o.id},...e.value}],r.value)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:f.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=Q().commandMeta,n=/(!=|=)/,[o]=e.split(n);if(!o||!(d=>pe(h.FILTER).map(l=>l.split(n)[0]).includes(d))(o))return i("Invalid filter modifier");let s={target:o,operator:"=",value:t.trim()};return me(d=>({...d,filters:e==="clear"?[]:[...d.filters,s],mode:f.DEFAULT})),c("Filter updated",null)}},{intent:P.ViewHelp,description:"Open the help screen",mode:f.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return Ht({pendingNavTarget:{contextNode:e,breadCrumb:o,selectedIndex:t,selectedNode:n}}),E({mode:f.HELP}),c("Viewing help",null)}},{intent:P.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=J(t.id)[n];if(!o)return i("Unable to close issue, no target found");if(!L(o))return i("Cannot close in this context");let r=g().nodes[he];if(!r)return i("Unable to locate closed swimlane");if(o.parentNodeId===r.id)return i("Issue is already closed");let s=await wt();if(a(s))return s;let d=s.value,l=Bt(r.id,o.id,{at:"end"},e.value,d);if(a(l))return l;let u=B([{id:we(),action:"close.issue",payload:{id:o.id,parent:r.id,rank:l.value},...e.value}],d);return a(u)?u:c("Issue closed",null)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:f.COMMAND_LINE,action:async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=J(t.id)[n];if(!o)return i("Unable to reopen issue, no target found");let r=o.context==="TICKET"?c("Resolved ticket",o):Yt(o.id,"TICKET");if(a(r))return i("Cannot reopen in this context");let s=r.value,d=g().nodes[he];if(!d)return i("Unable to locate closed swimlane");if(s.parentNodeId!==d.id)return i("Issue is not closed");if(!L(s))return i("Target node is not issue");let l=Pr(s);if(!l)return i("Unable to resolve previous parent from issue history");if(l===d.id)return i("Previous parent resolves to closed swimlane");let u=g().nodes[l];if(!u)return i("Previous parent no longer exists");let m=await wt();if(a(m))return m;let p=m.value,v=Bt(u.id,s.id,{at:"end"},e.value,p);if(a(v))return v;let x=B([{id:we(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:v.value},...e.value}],p);return a(x)?x:c("Issue reopened",null)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.Init,description:"Initialize Epiq in the current git repository",mode:f.COMMAND_LINE,action:Fc},{intent:P.NewItem,description:"Create a new board, swimlane, or issue",mode:f.COMMAND_LINE,action:Kc,onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.Rename,description:"Rename the currently selected node",mode:f.COMMAND_LINE,action:async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=J(t.id)[n];if(!o)return i("Missing node");if(o.readonly)return i("Cannot rename readonly node");let r=Wd();if(!r)return i("Provide a title");let s=await wt();return a(s)?s:B([{id:we(),action:"edit.title",payload:{id:o.id,name:r},...e.value}],s.value)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.UntagTicket,description:"Remove a tag from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,o=(t||n).trim();if(!o)return i("Provide a tag");let r=ll(o);if(!r)return i(`Tag "${o}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid untag target");let d=Yt(s.id,"TICKET");if(a(d))return i("Unable to untag issue in this context");let l=d.value;if(!L(l))return i("Target node is not issue");if(!(l.props.tags??[]).includes(r.id))return i("Issue is not tagged with that tag");let m=await wt();return a(m)?m:B([{id:we(),action:"remove.issue.tag",payload:{id:l.id,tag:r.id},...e.value}],m.value)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.TagTicket,description:"Add or create a tag on the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,o=(t||n).trim();if(!o)return i("Provide a tag");let{selectedNode:r}=g();if(!r)return i("Invalid tag target");let s=Yt(r.id,"TICKET");if(a(s))return i("Unable to tag issue in this context");let d=s.value;if(!L(d))return i("Target node is not issue");let l=await wt();if(a(l))return l;let u=ll(o),m=u?.id??we();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):B([...u?[]:[{id:we(),action:"create.tag",payload:{id:m,name:o},...e.value}],{id:we(),action:"add.issue.tag",payload:{id:d.id,tag:m},...e.value}],l.value)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.AssignUserToTicket,description:"Assign a user to the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,o=(t||n).trim();if(!o)return i("Provide an assignee");let r=o.startsWith("!"),s=(r?o.slice(1):o).trim();if(!s)return i("Provide an assignee");let{selectedIndex:d,contextNode:l}=g(),u=J(l.id)[d];if(!u)return i("Invalid assign target");let m=Yt(u.id,"TICKET");if(a(m))return i("Unable to assign issue in this context");let p=m.value;if(!L(p))return i("Target node is not issue");let v=await wt();if(a(v))return v;let x=ul(),S=!r&&s.toLowerCase()==="me",A,T;if(S)A=e.value.userId,T=x.find(K=>K.id===A)?.name??e.value.userName;else{let K=x.filter(Se=>Se.name===s);if(K.length>1)return i(`"${s}" matches ${K.length} contributors (${K.map(Se=>Se.id).join(", ")}). Assign from the GUI to choose by id.`);let U=K[0];if(!U&&!r)return i(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);A=U?.id??we(),T=U?.name??s}if((p.props.assignees??[]).includes(A))return i("Assignee already assigned");let z=!!g().contributors[A];return B([...z?[]:[{id:we(),action:"create.contributor",payload:{id:A,name:T},...e.value}],{id:we(),action:"add.issue.assignee",payload:{id:p.id,assignee:A},...e.value}],v.value)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:f.COMMAND_LINE,action:async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=Q().commandMeta,o=(t||n).trim();if(!o)return i("Provide an assignee to remove");let{selectedNode:r}=g();if(!r)return i("Invalid unassign target");let s=Yt(r.id,"TICKET");if(a(s))return i("Unable to unassign in this context");let d=s.value;if(!L(d))return i("Target node is not issue");let l=d.props.assignees??[],u=o.toLowerCase()==="me",m=u?l.filter(x=>x===e.value.userId):ul().filter(x=>x.name===o&&l.includes(x.id)).map(x=>x.id);if(m.length>1)return i(`"${o}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return i(u?"Issue is not assigned to you":`Issue is not assigned to "${o}"`);let v=await wt();return a(v)?v:B([{id:we(),action:"remove.issue.assignee",payload:{id:d.id,assignee:p},...e.value}],v.value)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.Comment,description:"Add a comment to the selected issue",mode:f.COMMAND_LINE,action:async(e,t)=>{let n=t.inputString.trim();if(!n)return i("Provide a comment");if(n.length>4e3)return i(`Cannot exceed ${4e3} characters`);let o=ae();if(a(o))return i("Unable to resolve user ID");let{breadCrumb:r,selectedNode:s}=g(),d=je([...r,s],"TICKET");if(a(d))return i("Edit target must be an issue");let l=d.value;if(!l)return i("Invalid comment target");let u=l.context==="TICKET"?c("Resolved ticket",l):Yt(l.id,"TICKET");if(a(u))return i("Unable to comment on issue in this context");let m=u.value;if(!L(m))return i("Target node is not issue");let p=await wt();return a(p)?p:B([{id:we(),action:"add.issue.comment",payload:{id:we(),issue:m.id,author:o.value.userId,md:n},...o.value}],p.value)},onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.Sync,description:"Pull, commit, and push Epiq state",mode:f.COMMAND_LINE,action:dl},{intent:P.Peek,description:"View board state at another point in time",mode:f.COMMAND_LINE,action:Gc},{intent:P.Replay,description:"Replay board history forward from a point in time",mode:f.COMMAND_LINE,action:Xc},{intent:P.Export,description:"Export the current board layout to markdown",mode:f.COMMAND_LINE,action:async()=>{let e=await Nc();return a(e)?e:(E({mode:f.DEFAULT}),c("Export successful",!0))}},{intent:P.Exit,description:"Exit the application",mode:f.COMMAND_LINE,action:async()=>(F.exit(),c("Exit successful",!0))},{intent:P.Edit,description:"Edit title or description",mode:f.COMMAND_LINE,action:async(e,t)=>Mc(t),onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:f.COMMAND_LINE,action:async(e,t)=>il(t),onSuccess:()=>E({mode:f.DEFAULT})},{intent:P.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:f.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case oe.USERNAME:{let{userId:o,preferredEditor:r,userName:s}=ie(),d=n||s,l=o??we();if(!d||!l)return i("Unable to resolve user name or id");let u=Xe({userName:d,userId:l,preferredEditor:r??""});return a(u)?u:(Ve({userName:d,userId:l}),E({mode:f.DEFAULT}),c(`Username set to "${d}"`,null))}case oe.EDITOR:{if(!n)return i("No editor provided");let o=Xe({preferredEditor:n});return a(o)?o:(Ve({preferredEditor:n}),E({mode:f.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case oe.VIEW:{if(n!=="wide"&&n!=="dense")return i("Invalid view mode");let o=Xe({viewMode:n});return a(o)?o:(Ve({viewMode:n}),E({mode:f.DEFAULT}),c(`View set to "${n}"`,null))}case oe.AUTOSYNC:return el();case oe.LOG_LEVEL:return nl();case oe.SYNC_DEBOUNCE_MS:return Qc();case oe.ATTACHMENT_MAX_KB:return yd();default:return i("Unknown config command")}}},{intent:P.Coffee,description:"Sponsor the development of Epiq!",mode:f.COMMAND_LINE,action:()=>{let e=Q().commandMeta.modifier;return e==="custom"?No("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):No(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),H(""),c("Thanks you!",null)}}]});var _f,ft,gi=y(()=>{"use strict";dr();yr();Ks();pl();C();be();Le();w();_f=new Set(["peek","replay","filter","view-help","yank"]),ft=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:o,inputString:r}}=Q();if(!t)return i("No command to confirm");if(!e&&n===$t.Invalid)return i("Invalid command");let s=Hd(t);Ud();let{readOnly:d}=g();if(d&&!_f.has(s))return ho({status:Mt.Fail,message:"Command not available in readonly state",value:null});let l=ml.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return ho({status:Mt.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:r,modifier:o})}catch(m){return ho({status:Mt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?ho(u):(_d({addToHistory:!e}),l.onSuccess?.(),ie().autoSync&&Ja(),u)}});var jr,Wr,gl,fl=y(()=>{"use strict";C();te();w();Gt();gi();li();be();jr=[{intent:M.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:f.COMMAND_LINE}),H("move cancel"),ft({isForceExecutedBySystem:!0}))},{intent:M.InitMove,mode:f.DEFAULT,description:"[m] move (init/confirm)",action:()=>(E({mode:f.COMMAND_LINE}),H("move start"),ft({isForceExecutedBySystem:!0}))},{intent:M.ConfirmMove,mode:f.MOVE,action:()=>(E({mode:f.COMMAND_LINE}),H("move confirm"),ft({isForceExecutedBySystem:!0}))}],Wr=[{intent:M.MovePreviousItem,mode:f.MOVE,action:()=>Kt()?(E({mode:f.COMMAND_LINE}),H("move previous"),ft({isForceExecutedBySystem:!0})):i("No pending move")},{intent:M.MoveNextItem,mode:f.MOVE,action:()=>Kt()?(E({mode:f.COMMAND_LINE}),H("move next"),ft({isForceExecutedBySystem:!0})):i("No pending move")}],gl=[{intent:M.MoveToNextContainer,mode:f.MOVE,action:()=>Kt()?(E({mode:f.COMMAND_LINE}),H("move to-next"),ft({isForceExecutedBySystem:!0})):i("No pending move")},{intent:M.MoveToPreviousContainer,mode:f.MOVE,action:()=>Kt()?(E({mode:f.COMMAND_LINE}),H("move to-previous"),ft({isForceExecutedBySystem:!0})):i("No pending move")}]});var vl,hl=y(()=>{"use strict";se();fl();vl={[D.WORKSPACE]:[...jr,...Wr],[D.BOARD]:[...jr,...Wr],[D.SWIMLANE]:[...jr,...Wr,...gl],[D.TICKET]:[],[D.FIELD]:[],[D.FIELD_LIST]:[],[D.TEXT]:[],[D.COMMENT]:[]}});import $f from"node:fs";import jf from"node:path";var yl,bl=y(()=>{"use strict";at();go();C();ue();oi();yl=e=>{let t=Ze(process.cwd());if(a(t))return i("Unable to resolve project root");let n=Me({repoRoot:t.value});if(a(n))return i(n.message);let o=Os(e.hash,e.ext),r=jf.join(Jr(n.value),o);return $f.existsSync(r)?(No(r),c(`Opened ${e.name}`,null)):i("Attachment file not found \u2014 run :sync to fetch it")}});var xl,Il,El=y(()=>{"use strict";te();C();be();w();Dr();Gt();We();xl=()=>{H("");let{pendingNavTarget:e}=$n();E({mode:f.DEFAULT}),e&&F.navigate(e),Ht({pendingNavTarget:void 0})},Il=[{intent:M.ExitCommandLine,mode:f.HELP,action:()=>(xl(),c("Exiting help",null))},{intent:M.Exit,mode:f.HELP,action:()=>(xl(),c("Closed help",null))},{intent:M.NavPreviousItem,mode:f.HELP,description:"[arrows/hjkl] navigate",action:()=>(F.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:M.NavNextItem,mode:f.HELP,action:()=>(F.navigateToNextItem(),c("Navigating to next help item",null))},{intent:M.NavToPreviousContainer,mode:f.HELP,action:()=>(F.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:M.NavToNextContainer,mode:f.HELP,action:()=>(F.navigateToNextContainer(),c("Navigating to next help container",null))}]});var Wf,Nl,Rl,Cl=y(()=>{"use strict";te();se();C();be();w();Dr();Gt();We();Wf=e=>{E({mode:f.COMMAND_LINE});let{pendingNavTarget:t}=$n();t&&F.navigate(t),Ht({pendingNavTarget:void 0}),H(`${e} `)},Nl=()=>{H("");let{pendingNavTarget:e}=$n();e&&F.navigate(e),Ht({pendingNavTarget:void 0}),E({mode:f.DEFAULT})},Rl=[{intent:M.InitCommandPalette,mode:f.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{H("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return Ht({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}}),E({mode:f.PALETTE}),c("Opening command palette",null)}},{intent:M.Confirm,mode:f.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!Zi(e))return i("Command only applicable on text nodes");if(e.props.disabled)return i("Command is not available in this context");let t=e.title;return t?(Wf(t),c("Selected command",t)):c("No command selected",null)}},{intent:M.ExitCommandLine,mode:f.PALETTE,action:()=>(Nl(),c("Exiting palette",null))},{intent:M.Exit,mode:f.PALETTE,action:()=>(Nl(),c("Closed command palette",null))},{intent:M.NavPreviousItem,mode:f.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(F.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:M.NavNextItem,mode:f.PALETTE,action:()=>(F.navigateToNextItem(),c("Navigating to next item",null))},{intent:M.NavToPreviousContainer,mode:f.PALETTE,action:()=>(F.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:M.NavToNextContainer,mode:f.PALETTE,action:()=>(F.navigateToNextContainer(),c("Navigating to next container",null))}]});var Sl,Al=y(()=>{"use strict";nn();_t();te();C();In();ce();lt();be();w();bl();Gt();El();Cl();We();Sl=[...Il,...Rl,{intent:M.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(E({mode:f.COMMAND_LINE}),H(`${h.NEW} `),c("Adding new item",null))},{intent:M.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(E({mode:f.COMMAND_LINE}),H(`${h.DELETE} `),c("Deleting item",null))},{intent:M.InitCommandLine,mode:f.DEFAULT,description:"[:] focus command line",action:()=>(E({mode:f.COMMAND_LINE}),H(""),c("Entering command line mode",null))},{intent:M.Confirm,mode:f.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!ne(e?.id??"")?.length){let o=e?I.getAttachment(e.id):void 0;if(o)return yl(o);if(e?.title===X.DESCRIPTION)return E({mode:f.COMMAND_LINE}),H(`${h.EDIT} description `),c("Propose command",!0);if(e?.title===X.ASSIGNEES)return E({mode:f.COMMAND_LINE}),H(`${h.ASSIGN} `),c("Propose command",!0);if(e?.title===X.TAGS)return E({mode:f.COMMAND_LINE}),H(`${h.TAG} `),c("Propose command",!0);if(t.title===X.DESCRIPTION&&e?.context==="TEXT")return E({mode:f.COMMAND_LINE}),H(`${h.EDIT} description `),c("Propose command",!0)}return F.enterChildNode(),c("Entering context",null)}},{intent:M.Yank,mode:f.DEFAULT,description:"[y] yank to clipboard",action:()=>{let{selectedNode:e}=g(),t=e?.title===X.DESCRIPTION?ye.DESCRIPTION:e?.title===X.TAGS?ye.TAGS:e?.title===X.ASSIGNEES?ye.ASSIGNEES:ye.REF,o=pe(h.YANK).includes(t)?t:ye.REF;return E({mode:f.COMMAND_LINE}),H(`${h.YANK} ${o}`),c("Propose command",!0)}},{intent:M.EditTitle,mode:f.DEFAULT,description:"[r] rename title",action:()=>(E({mode:f.COMMAND_LINE}),H(`${h.EDIT} title ${g().selectedNode?.title}`),c("Exiting context",null))},{intent:M.EditDescription,mode:f.DEFAULT,description:"[e] edit description",action:()=>(E({mode:f.COMMAND_LINE}),H(`${h.EDIT} description `),c("Exiting context",null))},{intent:M.Exit,mode:f.DEFAULT,description:"[q] exit context",action:()=>(F.enterParentNode(),c("Exiting context",null))},{intent:M.NavPreviousItem,mode:f.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(F.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:M.NavNextItem,mode:f.DEFAULT,action:()=>(F.navigateToNextItem(),c("Navigating to next item",null))},{intent:M.NavToPreviousContainer,mode:f.DEFAULT,action:()=>(F.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:M.NavToNextContainer,mode:f.DEFAULT,action:()=>(F.navigateToNextContainer(),c("Navigating to next container",null))}]});var Hf,Kf,Tl,wl=y(()=>{"use strict";be();Hf=500,Kf=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Tl=e=>{let t=Kf(e);t&&Er(n=>(n+t).slice(0,Hf))}});var qf,zf,Ml,Ll=y(()=>{"use strict";wl();te();C();be();w();Gt();gi();qf=[f.COMMAND_LINE,f.PALETTE],zf=e=>[{intent:M.MoveCursorLeft,mode:e,action:()=>(Ws(-1),c("Moving cursor left",null))},{intent:M.MoveCursorRight,mode:e,action:()=>(Ws(1),c("Moving cursor right",null))},{intent:M.MoveCursorLeftOfWord,mode:e,action:()=>(Hs("left"),c("Moving cursor left of word",null))},{intent:M.MoveCursorRightOfWord,mode:e,action:()=>(Hs("right"),c("Moving cursor right of word",null))},{intent:M.AutoCompleteCommand,mode:e,action:()=>(Er((t,{remainder:n})=>{let o=n?t+n:t,r="";return o==="edit title "&&(r=g().selectedNode?.title??""),o+r}),c("Auto-completing command",null))},{intent:M.CaptureInput,mode:e,action:(t,{sequence:n})=>(Tl(n??""),c("Capturing input",null))},{intent:M.EraseInput,mode:e,action:()=>(Bd(),c("Erasing input",null))},{intent:M.EraseInputWord,mode:e,action:()=>(Od(),c("Erasing input word",null))}],Ml=[{intent:M.Confirm,mode:f.COMMAND_LINE,action:()=>(ft(),c("Executing command",null))},{intent:M.ViewHelp,mode:f.DEFAULT,action:()=>(E({mode:f.HELP}),c("Viewing help",null))},...qf.flatMap(zf),{intent:M.ExitCommandLine,mode:f.COMMAND_LINE,action:()=>(E({mode:f.DEFAULT}),c("Exiting command line",null))},{intent:M.GetLastCommandFromHistory,mode:f.COMMAND_LINE,action:()=>($d(),c("Getting last command from history",null))},{intent:M.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(jd(),c("Getting next command from history",null))}]});import Dl from"chalk";var Hr,kl,Pl,fi,Fl=y(()=>{"use strict";te();se();Pe();Hr=Dl.dim.hex(R.secondary2)(": for command line"),kl="q to exit",Pl=`${Dl.hex(R.accent)("m")} to confirm`,fi={[D.WORKSPACE]:[Hr],[D.BOARD]:[Hr],[D.BOARD+f.COMMAND_LINE]:[Hr],[D.SWIMLANE]:[Hr],[D.TICKET+f.HELP]:[kl],[D.SWIMLANE+f.HELP]:[kl],[D.TICKET]:[],[D.FIELD]:[],[D.SWIMLANE+f.MOVE]:[Pl],[D.TICKET+f.MOVE]:[Pl]}});var So,Vf,Gf,Bl,Ol=y(()=>{"use strict";w();Fn();En();So=e=>e.trim().toLocaleLowerCase(),Vf=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Gf=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>{let o=t[n];return o?Dn(n,o.name):void 0}).filter(n=>!!n)},Bl=(e,t)=>{let n=So(t.value);if(!n)return!0;switch(t.target){case"title":return So(e.title??"").includes(n);case"description":return So(e.props.description??"").includes(n);case"tag":return Vf(e).map(So).some(r=>r.includes(n));case"assignee":return Gf(e).map(So).some(r=>r.includes(n));case"ref":return ma(e.id,t.value);default:return!0}}});function Ul(e,t,n){let o=t[e];if(!o)return i("buildBreadCrumb(): current node not found");let r=[],s=o;for(;s&&(r.push(s),!(s.id===n||!s.parentNodeId));)s=t[s.parentNodeId];let d=r[r.length-1];return!d||d.id!==n?i("buildBreadCrumb(): node is not connected to root"):(r.reverse(),c("Breadcrumb built",r))}var _l=y(()=>{"use strict";C()});var $l,jl=y(()=>{"use strict";$l=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t}});import{useSyncExternalStore as Yf}from"react";function Hl(e){let{contextNodeId:t,mode:n,rootNodeId:o,nodes:r,filters:s}=e;if(!t)return i("derive(): contextNodeId is missing");if(!o)return i("derive(): rootNode is missing");if(!r[o])return i("derive(): unable to find root node");let l=r[t];if(!l)return i("Unable to derive state, contextNode not found");let u=Ul(t,r,o);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,v=fi[p+n]??fi[p]??[],x=[...Sl,...vl[p]??[],...Ml],S=$l(x),A=Jf(r,s),T=A[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:v,availableActions:x,actionIndex:S,selectedNode:T,renderedChildrenIndex:A})}function no(e){vi=e;let t=Ze(process.cwd()),n=!1;if(!a(t)){let s=ht(t.value);if(a(s))return i(s.message);n=!0}let o={readOnly:!1,filters:[],tags:{},contributors:{},mode:f.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{},attachments:{}},r=Hl(o);return a(r)?r:(mn=r.value,Wl(),c("State initialized",null))}function me(e){let t=g(),n=e(t),o=Hl(n);return a(o)?i(o.message??"Unable to update state"):(mn=o.value,Wl(),c("State updated",null))}var mn,vi,hi,Wl,Xf,g,Fe,E,Ue,Jf,J,Tt,tn,w=y(()=>{"use strict";hl();Al();Ll();Fl();Lt();te();se();C();ue();Ol();_l();jl();hi=new Set,Wl=()=>{for(let e of hi)e()},Xf=e=>(hi.add(e),()=>hi.delete(e));g=()=>{if(!mn)throw new Error("State not initialized. Call initWorkspaceState() first.");return mn},Fe=()=>mn?c("Retrieved state",mn):i("State not initialized. Call initWorkspaceState() first.");E=e=>me(t=>({...t,...e})),Ue=()=>Yf(Xf,g,g),Jf=(e,t)=>{let n={};for(let o of Object.values(e))L(o)&&t.length>0&&!t.every(r=>Bl(o,r))||!o.parentNodeId||o.isDeleted||((!o.parentNodeId||!n[o.parentNodeId])&&(n[o.parentNodeId]=[]),n[o.parentNodeId].push(o));for(let o of Object.keys(n))n[o].sort((r,s)=>{let d=e[r.id],l=e[s.id];return!d||!l?0:d.rank.localeCompare(l.rank)});return n},J=e=>g()?.renderedChildrenIndex[e]??[],Tt=()=>vi?no(vi):i("Cannot reset state: no initial workspace found"),tn=()=>mn!==void 0});var yi,Kr,qr,bi,Ye,ir=y(()=>{"use strict";Qi();C();w();yi=e=>{tn()&&(E({syncStatus:e}),Ji({type:"sync-status",payload:e}))},Kr=(e="Syncing...")=>{yi({status:"syncing",msg:e})},qr=(e="Synced")=>{yi({status:"synced",msg:e})},bi=e=>{yi({status:"failed",msg:e})},Ye=e=>(bi(e),i(e))});import{decodeTime as sk}from"ulid";var Kl=y(()=>{"use strict";C()});var Qf,Zf,ar,Ss=y(()=>{"use strict";C();ir();Rs();Po();at();kt();Ho();Kl();Qf=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=G("getRepoRootDir",await it(e));if(a(n))return i(n.message);let o=n.value;logger.debug("[sync] repo root",o);let r=G("getStateBranchRoot",Me({repoRoot:o}));if(a(r))return i(r.message);let s=r.value;logger.debug("[sync] state branch root",s);let d=G("ensureInitialCommit",await Vi(o));if(a(d))return i(d.message);logger.debug("[sync] initial commit result",{created:d.value}),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:s,ensureUpstream:t});let l=G("bootstrapStateBranchStorage",await Xi({repoRoot:o,stateBranchRoot:s,ensureUpstream:t}));if(a(l))return i(l.message);logger.debug("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let u=G("hasInProgressGitOperation(stateBranchRoot)",await Fo(s));if(a(u))return i(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value)return logger.info("[sync] state branch git operation in progress"),i("Cannot sync while a git operation is in progress in the state branch");logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:s});let m=G("ensureStateBranchLayout",Ki(o,s));return a(m)?i(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:s,bootstrapped:l.value}),c("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:s,bootstrapped:l.value}))},Zf=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let o=G("stageStateBranchOwnEventFile",await Wo({stateBranchRoot:t,eventFileName:n}));if(a(o))return i(o.message);let r=G("stageStateBranchMediaFiles",await Gi({stateBranchRoot:t}));if(a(r))return i(r.message);let s=G("hasStagedChanges(after stage)",await Oi(t));if(a(s))return i(s.message);if(logger.debug("[sync] state branch change check after stage result",{changed:s.value}),!s.value)return logger.info("[sync] no own event file changes to commit"),c("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let d=G("createStateBranchSyncCommit",await Yi({repoRoot:e,stateBranchRoot:t}));return a(d)?i(d.message):(logger.debug("[sync] created sync commit",d.value),c("Committed own event file",{createdCommit:!0,commitSha:d.value}))},ar=async({cwd:e=process.cwd(),ownEventFileName:t})=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),i("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),i("Own event file must end with .jsonl");Kr();let n=G("ensureSyncReady",await Qf({cwd:e,ensureUpstream:!0}));if(a(n))return Ye(n.message);let{repoRoot:o,stateBranchRoot:r,bootstrapped:s}=n.value,d=G("isDetachedHead(stateBranchRoot)",await Ui(r));if(a(d))return Ye(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return Ye("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,p=!1,v=G("getStateBranch",vn(o));if(a(v))return Ye(v.message);let x=v.value;logger.debug("[sync] resolved state branch",{stateBranch:x,stateBranchRoot:r});let S=G("commitOwnEventFileToStateBranch",await Zf({repoRoot:o,stateBranchRoot:r,ownEventFileName:t}));if(a(S))return Ye(S.message);l=S.value.createdCommit,u=S.value.commitSha;let A=G("pullBranchRebaseIfPresent",await is({cwd:r,branch:x}));if(a(A))return Ye(A.message);if(m=A.value,l||s){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:s,stateBranchRoot:r});let T=G("pushStateBranch",await Jn({stateBranchRoot:r,repoRoot:o}));if(a(T)&&Bi(T.message)){let _=G("pullBranchRebaseIfPresent(retry)",await is({cwd:r,branch:x}));if(a(_))return Ye(_.message);m=m||_.value,T=G("pushStateBranch(retry)",await Jn({stateBranchRoot:r,repoRoot:o}))}if(a(T))return Ye(T.message);p=T.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:r});let T=G("git rev-parse HEAD",await j({args:["rev-parse","HEAD"],cwd:r}));if(a(T))return Ye(T.message);u=T.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return qr(p?"Synced and pushed":m||l?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),c("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:r,createdCommit:l,commitSha:u,pulled:m,pushed:p,bootstrapped:s})}});var ql=y(()=>{"use strict"});var $k,zl,xi=y(()=>{"use strict";at();kt();ri();mo();Jt();xt();ql();C();Lt();vr();ue();w();$k=Promise.resolve(),zl=(e,t)=>{let n=new Map,o=new Set,r=d=>{let l=new Set,u=d;for(;u&&!l.has(u);){if(o.has(u))return u;l.add(u),u=n.get(u)}return null},s=[];for(let d of e){let l=d.payload,u=l?.id;u&&(d.action==="add.board"&&o.add(u),l.parent&&n.set(u,l.parent),(u===t||r(u)===t)&&s.push(d))}return s}});import{decodeTime as zk,ulid as W}from"ulid";var zr,le,ge,fe,ev,Vl,Gl,tv,Yl,Xl,Jl,Ql,Zl,eu,tu,nu,ou,ru,su,iu,au,du,cu,lu,uu,mu,pu,gu,nv,fu,vu,hu,yu,bu,xu=y(()=>{"use strict";at();kt();Ho();Ss();an();ui();rr();Jt();Zt();nt();xi();ti();Sn();se();C();Lt();ce();lt();w();ir();ue();ut();Fn();yt();hr();En();yn();go();fn();xi();zr=e=>{let t=Ze(e??process.cwd());return a(t)?i(t.message):c("Resolved Epiq repo root",t.value)},le=async(e,t)=>{let n=zr(e);if(a(n))return n;let o=Me({repoRoot:n.value});if(a(o))return i(o.message);let r=Lo(),s=await Xn({repoRoot:n.value,stateBranchRoot:o.value,stateBranchName:r.stateBranch});if(a(s))return i(s.message);if(t?.pull??!1){let u=await j({cwd:o.value,args:["pull","--ff-only"]});a(u)&&ve.info(3,u.message)}let d=Ge(o.value);if(a(d))return i(d.message);let l=An(d.value);return a(l)?i(l.message):c("Booted Epiq state",{repoRoot:n.value,stateBranchRoot:o.value})},ge=()=>{let e=hd();return a(e)?i(e.message):e.value.userId?e.value.userName?c("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):i("Unable to retrieve user name"):i("Unable to retrieve user id")},fe=()=>{let e=Fe();return a(e)?i(e.message):e},ev=e=>(e.props.tags??[]).map(t=>I.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:De(t.name)})),Vl=()=>{let e=Fe(),t=a(e)?[]:e.value.eventLog??[],n=new Map;for(let o of t)o.userId&&o.userName&&n.set(o.userId,o.userName);return n},Gl=(e,t)=>{let n=new Map(e);for(let o of Object.values(t)){if(o.tombstoned){n.set(o.id,o.name);continue}n.set(o.id,Pn(o.name,n.get(o.id))??o.name)}return n},tv=(e,t=new Map)=>(e.props.assignees??[]).map(n=>I.getContributor(n)).filter(n=>n!=null).map(n=>{let o=n.tombstoned?n.name:Pn(n.name,t.get(n.id))??n.name;return{id:n.id,name:o,color:De(o)}}),Yl=async(e={})=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=fe();if(a(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="BOARD"&&!r.isDeleted).map(r=>({id:r.id,ref:tt(r.id),title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return c("Listed boards",o)},Xl=async(e={})=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=fe();if(a(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="SWIMLANE"&&!r.isDeleted).filter(r=>!e.boardId||r.parentNodeId===e.boardId).map(r=>({id:r.id,title:r.title,boardId:r.parentNodeId,isClosed:r.id===he,readonly:!!r.readonly}));return c("Listed swimlanes",o)},Jl=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=fe();if(a(n))return n;let o=n.value.nodes,r=Vl(),s=Object.values(o).filter(L).filter(d=>!d.isDeleted).filter(d=>e.includeClosed||d.parentNodeId!==he).filter(d=>e.boardId?(d.parentNodeId?o[d.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).map(d=>({id:d.id,ref:tt(d.id),title:ze(d.title),description:d.props.description??"",parentNodeId:d.parentNodeId,isClosed:d.parentNodeId===he,readonly:!!d.readonly,tags:ev(d),assignees:tv(d,r)}));return c("Listed issues",s)},Ql=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=en(e.parentId,n.value,t.value.stateBranchRoot);if(a(r))return r;let s=Br({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(a(s))return s;let d=[...s.value],l=d.find(v=>v.action==="add.issue")?.payload.id;if(!l)return i("Unable to determine created issue id");e.description&&d.push({id:W(),...n.value,action:"edit.description",payload:{id:l,md:e.description}});let u=[];for(let v of e.tagNames??[]){let x=ze(v).trim();if(!x||u.some(T=>T.name===x))continue;let S=Object.values(o.value.tags).find(T=>T.name===x),A=S?.id??W();S||d.push({id:W(),...n.value,action:"create.tag",payload:{id:A,name:x}}),d.push({id:W(),...n.value,action:"add.issue.tag",payload:{id:l,tag:A}}),u.push({id:A,name:x})}let m=[];for(let v of e.assigneeNames??[]){let x=ze(v).trim();if(!x||m.some(T=>T.name===x))continue;let S=Object.values(o.value.contributors).find(T=>T.name===x),A=S?.id??W();S||d.push({id:W(),...n.value,action:"create.contributor",payload:{id:A,name:x}}),d.push({id:W(),...n.value,action:"add.issue.assignee",payload:{id:l,assignee:A}}),m.push({id:A,name:x})}let p=B(d,t.value.stateBranchRoot);return a(p)?i(p.message):c("Created issue",{id:l,title:e.title,parentId:e.parentId,description:e.description??"",tags:u,assignees:m})},Zl=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=Bt(he,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(o))return o;let r={id:W(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:he,rank:o.value}},s=B([r],t.value.stateBranchRoot);return a(s)?i(s.message):c("Closed issue",{id:e.issueId})},eu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!L(r))return i("Target node is not issue");if(r.parentNodeId!==he)return i("Issue is not closed");let s=Pr(r);if(!s)return i("Unable to resolve previous parent from issue history");if(s===he)return i("Previous parent resolves to closed swimlane");let d=o.value.nodes[s];if(!d)return i("Previous parent no longer exists");let l=Bt(d.id,r.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(l))return l;let u={id:W(),...n.value,action:"reopen.issue",payload:{id:r.id,parent:d.id,rank:l.value}},m=B([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Reopened issue",{id:r.id,parentId:d.id})},tu=async e=>{let t=zr(e.repoRoot);if(a(t))return t;let n=ge();if(a(n))return n;let o=Me({repoRoot:t.value});if(a(o))return o;let r=Ge(o.value);if(a(r))return r;let s=An(r.value);if(a(s))return s;let d=Bt(e.parentId,e.issueId,e.position??{at:"end"},n.value,o.value);if(a(d))return d;let l={id:W(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:d.value}},u=B([l],o.value);return a(u)?i(u.message):c("Moved issue",{id:e.issueId,parentId:e.parentId})},nu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.boardId];if(!r)return i("Board not found");if(!Ko(r))return i("Target parent must be a board");let s=ze(e.title);if(!s.trim())return i("Swimlane title cannot be empty");let d=en(e.boardId,n.value,t.value.stateBranchRoot);if(a(d))return d;let l=W(),u={id:W(),...n.value,action:"add.swimlane",payload:{id:l,name:s,parent:e.boardId,rank:d.value}},m=B([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Created swimlane",{id:l,title:s,boardId:e.boardId})},ou=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.swimlaneId];if(!r)return i("Swimlane not found");if(!Vt(r))return i("Edit target must be a swimlane");if(r.readonly)return i("Cannot edit readonly swimlane");let s=ze(e.title);if(!s.trim())return i("Swimlane title cannot be empty");if(r.title===s)return c("No changes made",{id:e.swimlaneId,title:s});let d={id:W(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:s}},l=B([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited swimlane title",{id:e.swimlaneId,title:s})},ru=async e=>{let t=zr(e.repoRoot);if(a(t))return t;let n=ge();if(a(n))return n;let o=Me({repoRoot:t.value});if(a(o))return o;let r=Ge(o.value);if(a(r))return r;let s=An(r.value);if(a(s))return s;let d=Bt(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,o.value);if(a(d))return d;let l={id:W(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:d.value}},u=B([l],o.value);return a(u)?i(u.message):c("Moved swimlane",{id:e.swimlaneId,boardId:e.boardId})},su=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.swimlaneId];if(!r)return i("Swimlane not found");if(!Vt(r))return i("Delete target must be a swimlane");let s={id:W(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},d=B([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Deleted swimlane",{id:e.swimlaneId})},iu=async(e={})=>{Kr();let t=zr(e.repoRoot);if(a(t))return i("Sync failed");let n=ge();if(a(n))return n;let o=await ar({cwd:t.value,ownEventFileName:Qt(n.value)});return a(o)?(bi(o.message),o):(qr(),c("Synced",o.value))},au=async(e={})=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=fe();return a(n)?n:c("Retrieved Epiq state",{root:t.value.repoRoot,stateBranchRoot:t.value.stateBranchRoot,nodes:n.value.nodes,rootNodeId:n.value.rootNodeId,contextNode:n.value.contextNode,selectedIndex:n.value.selectedIndex,eventLog:n.value.eventLog})},du=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!L(r))return i("Edit target must be an issue");if(r.readonly)return i("Cannot edit readonly issue");let s=r.props.description??"";if(s===e.description)return c("No changes made",{id:e.issueId,description:s});let d={id:W(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},l=B([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited issue description",{id:e.issueId,description:e.description})},cu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!L(r))return i("Edit target must be an issue");if(r.readonly)return i("Cannot edit readonly issue");let s=ze(e.title);if(!s.trim())return i("Issue title cannot be empty");if(r.title===s)return c("No changes made",{id:e.issueId,title:s});let d={id:W(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},l=B([d],t.value.stateBranchRoot);return a(l)?i(l.message):c("Edited issue title",{id:e.issueId,title:s})},lu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!L(r))return i("Tag target must be an issue");if(r.readonly)return i("Cannot tag readonly issue");let s=ze(e.tagName).trim();if(!s)return i("Tag name cannot be empty");let d=Object.values(o.value.tags).find(p=>p.name===s),l=d?.id??W(),u=[...d?[]:[{id:W(),...n.value,action:"create.tag",payload:{id:l,name:s}}],{id:W(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:l}}],m=B(u,t.value.stateBranchRoot);return a(m)?i(m.message):c("Added issue tag",{id:e.issueId,tag:{id:l,name:s}})},uu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!L(r))return i("Untag target must be an issue");if(r.readonly)return i("Cannot untag readonly issue");if(!o.value.tags[e.tagId])return i("Tag not found");let s={id:W(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},d=B([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue tag",{id:e.issueId,tagId:e.tagId})},mu=async(e,t)=>{let n=Ge(e);if(a(n))return;let o;for(let r of n.value)r.userId===t&&(o=r.userName??o);return o===void 0?void 0:{id:t,name:o}},pu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!L(r))return i("Assign target must be an issue");if(r.readonly)return i("Cannot assign readonly issue");let s=e.self?n.value.userId:e.assigneeId;if(s){let T=o.value.contributors[s],_=T?void 0:await mu(t.value.stateBranchRoot,s);if(!T&&!_)return i("Unknown assignee id");let z=T??_,K=[...T?[]:[{id:W(),...n.value,action:"create.contributor",payload:{id:z.id,name:z.name}}],{id:W(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:z.id}}],U=B(K,t.value.stateBranchRoot);return a(U)?i(U.message):c("Added issue assignee",{id:e.issueId,assignee:{id:z.id,name:z.name}})}let d=ze(e.assigneeName??"").trim();if(!d)return i("Provide assigneeId, self or assigneeName");let u=[...Gl(Vl(),o.value.contributors).entries()].filter(([,T])=>T===d);if(u.length>1)return i(`"${d}" matches ${u.length} contributors (${u.map(([T])=>T).join(", ")}). Assign by assigneeId to choose.`);let m=u[0];if(!m&&!e.createUnlinked)return i(`No contributor named "${d}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[p=W(),v=d]=m??[],S=[...!!o.value.contributors[p]?[]:[{id:W(),...n.value,action:"create.contributor",payload:{id:p,name:v}}],{id:W(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:p}}],A=B(S,t.value.stateBranchRoot);return a(A)?i(A.message):c("Added issue assignee",{id:e.issueId,assignee:{id:p,name:v}})},gu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;if(!o.value.contributors[e.contributorId])return i("Contributor not found");if(await mu(t.value.stateBranchRoot,e.contributorId))return i("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let d=[{id:W(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],l=B(d,t.value.stateBranchRoot);return a(l)?i(l.message):c("Tombstoned contributor",{id:e.contributorId,name:Vo})},nv=async(e,t)=>{let n=Ge(e);if(a(n))return;let o;for(let r of n.value){if(r.action!=="create.contributor")continue;let s=r.payload;s.id===t&&s.name&&(o=s.name)}return o},fu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.contributors[e.contributorId];if(!r)return i("Contributor not found");if(!r.tombstoned)return i("Contributor is not tombstoned");let s=await nv(t.value.stateBranchRoot,e.contributorId);if(!s)return i("Cannot restore this contributor \u2014 no original name found in the event log");let d=[{id:W(),...n.value,action:"restore.contributor",payload:{id:e.contributorId,name:s}}],l=B(d,t.value.stateBranchRoot);return a(l)?i(l.message):c("Restored contributor",{id:e.contributorId,name:s})},vu=async(e={})=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=Ge(t.value.stateBranchRoot);if(a(r))return i(r.message);let s=e.boardId?zl(r.value,e.boardId):r.value,d=new Map,l=new Set,u=new Set;for(let x of r.value)x.userId&&u.add(x.userId);for(let x of s)x.userId&&(d.set(x.userId,x.userName??""),l.add(x.userId));let m=o.value.contributors,v=[...Gl(d,m).entries()].map(([x,S])=>({id:x,name:S,color:De(S),isSelf:x===n.value.userId,isExternal:!l.has(x),isRemoved:m[x]?.tombstoned===!0,hasAuthoredAnywhere:u.has(x)}));return c("Listed board contributors",v)},hu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!L(r))return i("Unassign target must be an issue");if(r.readonly)return i("Cannot unassign readonly issue");if(!o.value.contributors[e.assigneeId])return i("Assignee not found");let s={id:W(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},d=B([s],t.value.stateBranchRoot);return a(d)?i(d.message):c("Removed issue assignee",{id:e.issueId,assigneeId:e.assigneeId})},yu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!L(r))return i("Comment target must be an issue");if(r.readonly)return i("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return i("Comment cannot be empty");if(s.length>4e3)return i(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let d=W(),l={id:W(),...n.value,action:"add.issue.comment",payload:{id:d,issue:e.issueId,md:s,author:n.value.userId}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Added issue comment",{id:d,issueId:e.issueId,body:s})},bu=async e=>{let t=await le(e.repoRoot,{pull:!1});if(a(t))return t;let n=ge();if(a(n))return n;let o=fe();if(a(o))return o;let r=o.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!r)return i("Unable to resolve comment");if(r.payload.author!==n.value.userId)return i("You can only delete your own comments");let s=o.value.nodes[r.payload.issue];if(!s)return i("Issue not found");if(!L(s))return i("Comment target must be an issue");if(s.readonly)return i("Cannot delete comment on readonly issue");if(o.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return c("Comment already deleted",{id:e.commentId,issueId:r.payload.issue});let l={id:W(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:r.payload.issue}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Deleted issue comment",{id:e.commentId,issueId:r.payload.issue})}});var Nu={};Tu(Nu,{createMcpServer:()=>Iu,resultJson:()=>Y,startMcpServer:()=>Eu});import{McpServer as ov}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as rv}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as b}from"zod";var Y,Iu,Eu,Ru=y(async()=>{"use strict";C();xu();Y=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Iu=()=>{let e=new ov({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:b.object({repoRoot:b.string().optional()})},async t=>Y(await au(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues. Pass boardId to scope results to a single board and reduce response size.",inputSchema:b.object({repoRoot:b.string().optional(),includeClosed:b.boolean().optional(),boardId:b.string().optional()})},async t=>Y(await Jl(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:b.object({repoRoot:b.string().optional()})},async t=>Y(await Yl(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:b.object({repoRoot:b.string().optional(),boardId:b.string().optional()})},async t=>Y(await Xl(t))),e.registerTool("epiq_swimlane_create",{description:"Create an Epiq swimlane on a board",inputSchema:b.object({repoRoot:b.string().optional(),boardId:b.string().min(1),title:b.string().min(1)})},async t=>Y(await nu(t))),e.registerTool("epiq_swimlane_title_edit",{description:"Edit an Epiq swimlane title",inputSchema:b.object({repoRoot:b.string().optional(),swimlaneId:b.string().min(1),title:b.string().min(1)})},async t=>Y(await ou(t))),e.registerTool("epiq_swimlane_move",{description:"Move/reorder an Epiq swimlane, optionally to another board",inputSchema:b.object({repoRoot:b.string().optional(),swimlaneId:b.string().min(1),boardId:b.string().min(1),position:b.discriminatedUnion("at",[b.object({at:b.literal("start")}),b.object({at:b.literal("end")}),b.object({at:b.literal("before"),sibling:b.string().min(1)}),b.object({at:b.literal("after"),sibling:b.string().min(1)})]).optional()})},async t=>Y(await ru(t))),e.registerTool("epiq_swimlane_delete",{description:"Delete (archive) an Epiq swimlane. This also archives every issue contained in it.",inputSchema:b.object({repoRoot:b.string().optional(),swimlaneId:b.string().min(1)})},async t=>Y(await su(t))),e.registerTool("epiq_issue_create",{description:"Create an Epiq issue. Optionally set description, tags, and assignees atomically in the same call instead of separate follow-up edits.",inputSchema:b.object({title:b.string().min(1),parentId:b.string().min(1),repoRoot:b.string().optional(),description:b.string().optional(),tagNames:b.array(b.string()).optional(),assigneeNames:b.array(b.string()).optional()})},async t=>Y(await Ql(t))),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),description:b.string(),repoRoot:b.string().optional()})},async t=>Y(await du(t))),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),title:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await cu(t))),e.registerTool("epiq_issue_tag_add",{description:"Add a tag to an Epiq issue, creating the tag if it does not exist",inputSchema:b.object({issueId:b.string().min(1),tagName:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await lu(t))),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),tagId:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await uu(t))),e.registerTool("epiq_contributor_list",{description:"List people who can be assigned: everyone who has authored an event (optionally scoped to one board) unioned with the contributor registry. Use these ids with epiq_issue_assignee_add rather than assigning by name.",inputSchema:b.object({boardId:b.string().min(1).optional(),repoRoot:b.string().optional()})},async t=>Y(await vu(t))),e.registerTool("epiq_contributor_remove",{description:"Remove an external contributor from the assignee suggestion lists. Their id and every reference to it survive, so existing assignments stay intact and the event log is untouched. Refused for anyone who has authored events, since their name is in the log regardless.",inputSchema:b.object({contributorId:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await gu(t))),e.registerTool("epiq_contributor_restore",{description:"Put a contributor removed with epiq_contributor_remove back into the suggestion lists, under the name they were created with.",inputSchema:b.object({contributorId:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await fu(t))),e.registerTool("epiq_issue_assignee_add",{description:"Assign a contributor to an Epiq issue. Pass self:true to assign yourself. Prefer assigneeId otherwise, which assigns a known contributor (from the registry or the event log) and fails if the id is unknown. assigneeName matches an existing contributor by name; to create somebody new from a name you must also pass createUnlinked, which adds them as an external (non-contributor) assignee.",inputSchema:b.object({issueId:b.string().min(1),assigneeId:b.string().min(1).optional(),self:b.boolean().optional(),assigneeName:b.string().min(1).optional(),createUnlinked:b.boolean().optional(),repoRoot:b.string().optional()})},async t=>Y(await pu(t))),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),assigneeId:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await hu(t))),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),body:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await yu(t))),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:b.object({commentId:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await bu(t))),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:b.object({issueId:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await eu(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),repoRoot:b.string().optional()})},async t=>Y(await Zl(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:b.object({issueId:b.string().min(1),parentId:b.string().min(1),position:b.discriminatedUnion("at",[b.object({at:b.literal("start")}),b.object({at:b.literal("end")}),b.object({at:b.literal("before"),sibling:b.string().min(1)}),b.object({at:b.literal("after"),sibling:b.string().min(1)})]).optional(),repoRoot:b.string().optional()})},async t=>Y(await tu(t))),e.registerTool("epiq_sync",{description:"Sync Epiq state with the configured Git remote (pull remote changes and push local ones). Other Epiq MCP tools only read and write local state and never sync automatically \u2014 call this on demand when you need to see or publish the latest remote changes.",inputSchema:b.object({repoRoot:b.string().optional()})},async t=>Y(await iu(t))),e},Eu=async()=>{let e=Iu(),t=new rv;await e.connect(t)};await Eu()});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;await Ru().then(()=>Nu);