epiq 1.4.3 → 1.4.5

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 Mu=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var ku=(e,t)=>{for(var n in t)Mu(e,n,{get:t[n],enumerable:!0})};var kt,i,c,a,ht,C=y(()=>{"use strict";kt={Success:"success",Fail:"fail"},i=e=>({status:kt.Fail,message:e,value:null}),c=(e,t)=>({status:kt.Success,message:e,value:t}),a=e=>e.status==="fail",ht=e=>e.status==="success"});import Lu from"node:os";import Pu from"node:path";var Qe,jn,Qr=y(()=>{"use strict";Qe=".epiq-global",jn=()=>process.env.EPIQ_GLOBAL_DIR??Pu.join(Lu.homedir(),Qe)});import Wn from"node:fs";import ot from"node:path";var bv,rt,To,Zr,Du,Hn,wo,Kn,es,wi,Fu,ts,Mo,Ze,Mi,st,ue=y(()=>{"use strict";C();at();Qr();bv=process.env.IS_LOCAL==="true",rt=".epiq",To="events",Zr="media",Du="project.json",Hn=e=>ot.join(e,rt),wo=e=>ot.join(Hn(e),Du),Kn=e=>ot.join(Hn(e),To),es=e=>ot.join(Hn(e),Zr),wi=e=>ot.join(e,rt),Fu=e=>{let t=ot.join(e,rt);return Wn.existsSync(t)&&Wn.statSync(t).isDirectory()},ts=e=>{let t=wo(e);return Wn.existsSync(t)&&Wn.statSync(t).isFile()},Mo=e=>{let t=ot.resolve(e);for(;;){if(Fu(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(ts(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}},Mi=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=ke({repoRoot:e.value});return a(t)?t:c("Resolved persist root",t.value)}});import qn from"node:fs";import{ulid as Bu}from"ulid";import{z as ko}from"zod";var Ou,Uu,Lo,yt,ki,Li,Lt=y(()=>{"use strict";C();ue();Ou="__epiq_state__",Uu=ko.object({projectId:ko.string().min(1),stateBranch:ko.string().min(1),createdAt:ko.iso.datetime()}),Lo=()=>({projectId:Bu(),stateBranch:Ou,createdAt:new Date().toISOString()}),yt=e=>{let t=wo(e);if(!qn.existsSync(t))return i("Missing .epiq/project.json");try{let n=qn.readFileSync(t,"utf8"),o=JSON.parse(n),r=Uu.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")}},ki=e=>{let t=yt(e);return a(t)?i(t.message):c("Read projectId",t.value.projectId)},Li=({repoRoot:e,fileContents:t})=>{let n=Hn(e),o=wo(e);try{if(qn.mkdirSync(n,{recursive:!0}),qn.existsSync(o)){let r=yt(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 ns,Pi=y(()=>{"use strict";C();ns=(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 is from"path";import _u from"util";function ju(){let e=Bi();if(!e||!zn.existsSync(e))return;let n=zn.readFileSync(e,"utf8").split(`
4
- `);if(n[n.length-1]===""&&n.pop(),n.length<=Di)return;let o=n.slice(-Di).join(`
2
+ var ku=Object.defineProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var Pu=(e,t)=>{for(var n in t)ku(e,n,{get:t[n],enumerable:!0})};var Pt,i,c,a,yt,S=y(()=>{"use strict";Pt={Success:"success",Fail:"fail"},i=e=>({status:Pt.Fail,message:e,value:null}),c=(e,t)=>({status:Pt.Success,message:e,value:t}),a=e=>e.status==="fail",yt=e=>e.status==="success"});import Du from"node:os";import Fu from"node:path";var Ze,jn,es=y(()=>{"use strict";Ze=".epiq-global",jn=()=>process.env.EPIQ_GLOBAL_DIR??Fu.join(Du.homedir(),Ze)});import Wn from"node:fs";import rt from"node:path";var Nv,st,wo,ts,Bu,Hn,Mo,Kn,ns,Li,Ou,os,Lo,et,ki,it,ue=y(()=>{"use strict";S();dt();es();Nv=process.env.IS_LOCAL==="true",st=".epiq",wo="events",ts="media",Bu="project.json",Hn=e=>rt.join(e,st),Mo=e=>rt.join(Hn(e),Bu),Kn=e=>rt.join(Hn(e),wo),ns=e=>rt.join(Hn(e),ts),Li=e=>rt.join(e,st),Ou=e=>{let t=rt.join(e,st);return Wn.existsSync(t)&&Wn.statSync(t).isDirectory()},os=e=>{let t=Mo(e);return Wn.existsSync(t)&&Wn.statSync(t).isFile()},Lo=e=>{let t=rt.resolve(e);for(;;){if(Ou(t))return c("Resolved closest .epiq root",t);let n=rt.dirname(t);if(n===t)return i("No .epiq directory found in any parent");t=n}},et=e=>{let t=rt.resolve(e);for(;;){if(os(t))return c("Resolved closest epiq project root",t);let n=rt.dirname(t);if(n===t)return i("No .epiq/project.json found in any parent");t=n}},ki=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")}},it=async()=>{let e=await at(process.cwd());if(a(e))return e;let t=ke({repoRoot:e.value});return a(t)?t:c("Resolved persist root",t.value)}});import qn from"node:fs";import{ulid as Uu}from"ulid";import{z as ko}from"zod";var _u,$u,Po,bt,Pi,Di,Dt=y(()=>{"use strict";S();ue();_u="__epiq_state__",$u=ko.object({projectId:ko.string().min(1),stateBranch:ko.string().min(1),createdAt:ko.iso.datetime()}),Po=()=>({projectId:Uu(),stateBranch:_u,createdAt:new Date().toISOString()}),bt=e=>{let t=Mo(e);if(!qn.existsSync(t))return i("Missing .epiq/project.json");try{let n=qn.readFileSync(t,"utf8"),o=JSON.parse(n),r=$u.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")}},Pi=e=>{let t=bt(e);return a(t)?i(t.message):c("Read projectId",t.value.projectId)},Di=({repoRoot:e,fileContents:t})=>{let n=Hn(e),o=Mo(e);try{if(qn.mkdirSync(n,{recursive:!0}),qn.existsSync(o)){let r=bt(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 rs,Fi=y(()=>{"use strict";S();rs=(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 ds from"path";import ju from"util";function Hu(){let e=Ui();if(!e||!zn.existsSync(e))return;let n=zn.readFileSync(e,"utf8").split(`
4
+ `);if(n[n.length-1]===""&&n.pop(),n.length<=Bi)return;let o=n.slice(-Bi).join(`
5
5
  `)+`
6
- `;zn.writeFileSync(e,o,"utf8")}function rs(e,t,n=!1){let o=Bi();if(!o)return;let r=_u.format(...t),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${r}
7
- `;zn.mkdirSync(is.dirname(o),{recursive:!0}),zn.appendFileSync(o,l,"utf8"),os++,os>=$u&&(os=0,ju())}var Di,$u,os,Fi,Bi,ss,ve,fn=y(()=>{"use strict";C();ue();Di=1e3,$u=50,os=0,Fi=()=>process.env.EPIQ_MCP==="true",Bi=()=>{let e=process.cwd(),t=Mo(e);return a(t)?Fi()?is.join(process.cwd(),".epiq-mcp.log"):void 0:is.join(t.value,rt,"log","epiq.log")};ss=()=>Fi()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",ve={info(...e){let t=ss();(t==="info"||t==="debug")&&rs("[Info]",e,!1)},debug(...e){ss()==="debug"&&rs("[Debug]",e,!0)},error(...e){let t=ss();if(t==="error"||t==="info"||t==="debug"){let o=e.some(r=>r instanceof Error)?void 0:new Error().stack;rs("[Error]",[...e,o].filter(Boolean),!1)}}};globalThis.logger=ve});var de,Po=y(()=>{"use strict";Pt();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,Do=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=yt(t.value);return a(n)?i("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},qe="origin"});import{spawn as Wu}from"node:child_process";import Fo from"node:fs";import Vn from"node:path";var Oi,Hu,Ui,j,dt,hn,Ku,qu,Bo,as,Oo,Uo,Gn,_i,ds,_o,$i,ji,zu,cs,Wi,Hi,Pt=y(()=>{"use strict";C();Po();Do();Oi=1e4,Hu={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Ui=({args:e,cwd:t,allowFail:n})=>new Promise(o=>{if(!Fo.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=Wu("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Hu}),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 ${Oi}ms`].join(`
8
- `);u(n?{stdout:d,stderr:p,exitCode:124}:i(p))},Oi);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
- `)))}),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})=>Ui({args:e,cwd:t,allowFail:!1}),dt=({args:e,cwd:t})=>Ui({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
- ${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())},Ku=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))},qu=async e=>{let t=await Ku(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(Fo.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(Fo.existsSync(Vn.join(n,s)))return c("Checked for in-progress Git operation",d);return c("Checked for in-progress Git operation",null)},Bo=async e=>{let t=await qu(e);return a(t)?i(t.message):c("Checked for in-progress Git operation",t.value!==null)},as=async({repoRoot:e})=>{let n=(await dt({args:["remote","get-url",qe],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},Oo=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)},Uo=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 Fo.realpathSync.native(e)}catch{return Vn.resolve(e)}},_i=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)},ds=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)},_o=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())},$i=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())},ji=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),zu=async e=>(await dt({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1),cs=async({cwd:e,branch:t})=>{let n=await Oo({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 zu(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
- ${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)},Wi=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")},Hi=async e=>{let t=await _o(e);return a(t)?i(t.message):c("Checked detached HEAD state",t.value==="HEAD")}});import ls from"node:fs";import ct from"node:path";var qi,us,zi,Vi,$o,ke,Vu,Ki,Yn,jo,Gi,Yi,Xi,it,ch,at=y(()=>{"use strict";Lt();C();Qr();ue();Pi();fn();Pt();qi="4b825dc642cb6eb9a060e54bf8d69288fbee4904",us=e=>ct.join(rt,To,e),zi=()=>ct.join(rt,Zr),Vi=jn,$o=()=>ct.join(Vi(),"worktrees"),ke=({repoRoot:e})=>{let t=ki(e);return a(t)?i(t.message):c("Resolved state branch root",ct.join($o(),t.value))},Vu=e=>ct.join(e,rt),Ki=e=>ct.join(Vu(e),To),Yn=e=>{try{return ls.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return i(t instanceof Error?t.message:String(t))}},jo=()=>{let e=Yn(Vi());if(a(e))return i(`Ensure epiq home failed.
16
- `+e.message);let t=Yn($o());return a(t)?i(`Ensure worktrees dir failed.
17
- `+t.message):c("Ensured epiq storage",!0)},Gi=e=>{ls.existsSync(e)&&(ve.debug("[sync] remove path",e),ls.rmSync(e,{recursive:!0,force:!0}))},Yi=(e,t)=>{for(let n of[Ki(e),Ki(t)]){let o=Yn(n);if(a(o))return i(o.message)}return c("Ensured state branch",void 0)},Xi=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
6
+ `;zn.writeFileSync(e,o,"utf8")}function is(e,t,n=!1){let o=Ui();if(!o)return;let r=ju.format(...t),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${r}
7
+ `;zn.mkdirSync(ds.dirname(o),{recursive:!0}),zn.appendFileSync(o,l,"utf8"),ss++,ss>=Wu&&(ss=0,Hu())}var Bi,Wu,ss,Oi,Ui,as,he,bn=y(()=>{"use strict";S();ue();Bi=1e3,Wu=50,ss=0,Oi=()=>process.env.EPIQ_MCP==="true",Ui=()=>{let e=process.cwd(),t=Lo(e);return a(t)?Oi()?ds.join(process.cwd(),".epiq-mcp.log"):void 0:ds.join(t.value,st,"log","epiq.log")};as=()=>Oi()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",he={info(...e){let t=as();(t==="info"||t==="debug")&&is("[Info]",e,!1)},debug(...e){as()==="debug"&&is("[Debug]",e,!0)},error(...e){let t=as();if(t==="error"||t==="info"||t==="debug"){let o=e.some(r=>r instanceof Error)?void 0:new Error().stack;is("[Error]",[...e,o].filter(Boolean),!1)}}};globalThis.logger=he});var de,Do=y(()=>{"use strict";Ft();de={stage:({cwd:e,pathspec:t})=>_({args:["add",...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1})=>_({args:["commit",...n?["--allow-empty"]:[],"-m",t],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>_({args:["fetch",t,n],cwd:e}),pullRebase:({cwd:e,remote:t,branch:n})=>_({args:["pull","--rebase",t,n],cwd:e}),checkout:({cwd:e,branch:t})=>_({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 _({args:r,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>_({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>_({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>_({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>_({args:["worktree","prune"],cwd:e})}});var xn,ze,Fo=y(()=>{"use strict";Dt();S();ue();xn=e=>{let t=et(e);if(a(t))return i("Unable to resolve epiq project root");let n=bt(t.value);return a(n)?i("Unable to read project.json"):c("Resolved state branch",n.value.stateBranch)},ze="origin"});import{spawn as Ku}from"node:child_process";import Bo from"node:fs";import Gn from"node:path";var _i,qu,$i,_,ct,In,zu,Gu,Oo,cs,Uo,_o,Vn,ji,ls,$o,Wi,Hi,Vu,us,Ki,qi,Ft=y(()=>{"use strict";S();Do();Fo();_i=1e4,qu={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},$i=({args:e,cwd:t,allowFail:n})=>new Promise(o=>{if(!Bo.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=Ku("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:qu}),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 ${_i}ms`].join(`
8
+ `);u(n?{stdout:d,stderr:p,exitCode:124}:i(p))},_i);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
+ `)))}),r.on("close",p=>{let h=p??1;if(n){u({stdout:d,stderr:l,exitCode:h});return}if(h!==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:h}))})}),_=({args:e,cwd:t})=>$i({args:e,cwd:t,allowFail:!1}),ct=({args:e,cwd:t})=>$i({args:e,cwd:t,allowFail:!0}),In=async({cwd:e,message:t})=>{let n=await de.commit({cwd:e,message:t});if(a(n))return i(`Failed to create commit
11
+ ${n.message}`);let o=await _({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())},zu=async e=>{let t=await _({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",Gn.isAbsolute(n)?n:Gn.resolve(e,n))},Gu=async e=>{let t=await zu(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(Bo.existsSync(Gn.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(Bo.existsSync(Gn.join(n,s)))return c("Checked for in-progress Git operation",d);return c("Checked for in-progress Git operation",null)},Oo=async e=>{let t=await Gu(e);return a(t)?i(t.message):c("Checked for in-progress Git operation",t.value!==null)},cs=async({repoRoot:e})=>{let n=(await ct({args:["remote","get-url",ze],cwd:e})).exitCode===0;return c(`Checked remote ${n}`,n)},Uo=async({repoRoot:e,branch:t})=>{let n=await ct({args:["ls-remote","--heads",ze,t],cwd:e});return n.exitCode!==0?i(n.stderr.trim()||`Unable to inspect remote branch ${ze}/${t}`):c("Checked remote branch",n.stdout.trim().length>0)},_o=async({repoRoot:e,branch:t})=>{let n=await ct({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}`)},Vn=e=>{try{return Bo.realpathSync.native(e)}catch{return Gn.resolve(e)}},ji=async({repoRoot:e,worktreeRoot:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let o=Vn(t),r=n.value.stdout.split(`
13
+ `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Vn).includes(o);return c("Checked worktree registration",r)},ls=async e=>{let t=await ct({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return c("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},$o=async e=>{let t=await _({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved current branch",t.value.stdout.trim())},Wi=async e=>{let t=await _({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?i(t.message):c("Resolved short HEAD sha",t.value.stdout.trim())},Hi=e=>e.includes("fetch first")||e.includes("non-fast-forward")||e.includes("failed to push some refs"),Vu=async e=>(await ct({cwd:e,args:["rebase","--abort"]})).exitCode===0?c("Aborted stale rebase",!0):c("No rebase to abort",!1),us=async({cwd:e,branch:t})=>{let n=await Uo({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 Vu(e);if(a(o))return i(o.message);let r=await de.fetch({cwd:e,remote:ze,branch:t});if(a(r))return i(`Failed to fetch ${t}
14
+ ${r.message}`);let s=await de.pullRebase({cwd:e,remote:ze,branch:t});return a(s)?i(`Failed during pull --rebase
15
+ ${s.message}`):c("Pulled with rebase",!0)},Ki=async e=>{let t=await ct({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")},qi=async e=>{let t=await $o(e);return a(t)?i(t.message):c("Checked detached HEAD state",t.value==="HEAD")}});import ms from"node:fs";import lt from"node:path";var Gi,ps,Vi,Yi,jo,ke,Yu,zi,Yn,Wo,Xi,Ji,Qi,at,ph,dt=y(()=>{"use strict";Dt();S();es();ue();Fi();bn();Ft();Gi="4b825dc642cb6eb9a060e54bf8d69288fbee4904",ps=e=>lt.join(st,wo,e),Vi=()=>lt.join(st,ts),Yi=jn,jo=()=>lt.join(Yi(),"worktrees"),ke=({repoRoot:e})=>{let t=Pi(e);return a(t)?i(t.message):c("Resolved state branch root",lt.join(jo(),t.value))},Yu=e=>lt.join(e,st),zi=e=>lt.join(Yu(e),wo),Yn=e=>{try{return ms.mkdirSync(e,{recursive:!0}),c("Ensured directory",void 0)}catch(t){return i(t instanceof Error?t.message:String(t))}},Wo=()=>{let e=Yn(Yi());if(a(e))return i(`Ensure epiq home failed.
16
+ `+e.message);let t=Yn(jo());return a(t)?i(`Ensure worktrees dir failed.
17
+ `+t.message):c("Ensured epiq storage",!0)},Xi=e=>{ms.existsSync(e)&&(he.debug("[sync] remove path",e),ms.rmSync(e,{recursive:!0,force:!0}))},Ji=(e,t)=>{for(let n of[zi(e),zi(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 _({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
- `).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 hn({cwd:e,message:"[epiq:repair-storage-branch]"});return a(s)?i(s.message):c("Cleaned storage branch",!0)},it=ns(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)),ch=ns(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 Vt from"node:fs";import Wo from"node:path";var Qi,Ji,Gu,ms,Yu,Xu,Ju,Xn,Qu,Zu,Ho,Zi,ea,Jn,ta,Ko=y(()=>{"use strict";C();fn();Po();Do();at();Pt();Qi=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)},Ji=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Gu=async e=>{let t=await _o(e);if(a(t))return i(t.message);let n=await $i(e);return a(n)?i(n.message):c("Built sync commit message",`[sync|branch:${Ji(t.value)}:sha:${Ji(n.value)}]`)},ms=async({repoRoot:e,stateBranchName:t})=>{ve.info(`Creating ${t}`);let n=await j({args:["commit-tree",qi,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return i(`Failed to create state branch commit
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)},Yu=async({repoRoot:e,stateBranchName:t})=>{let n=await as({repoRoot:e});if(a(n))return i(`Ensure local state branch failed
23
- `+n.message);let o=n.value,r=o?await Oo({repoRoot:e,branch:t}):c("No remote, no remote state branch",!1);if(a(r))return i(`Ensure local state branch failed
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
- ${l.message}`)}let d=await Uo({repoRoot:e,branch:t});if(a(d))return i(`Ensure local state branch failed
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 ms({repoRoot:e,stateBranchName:t})},Xu=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)},Ju=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=Yn(Wo.dirname(t));if(a(o))return i(`Failed to create state branch worktree
29
- `+o.message);Vt.existsSync(t)&&!Vt.existsSync(Wo.join(t,".git"))&&(ve.info("Removing broken state branch worktree path"),Gi(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 Xu({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&&Vt.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&&!Vt.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 _i({repoRoot:e,worktreeRoot:t});if(a(d))return i(d.message);let l=Vt.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 Ju({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Qu=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await _o(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)},Zu=async({repoRoot:e,stateBranchRoot:t})=>{let n=await ds(t);if(a(n))return i(n.message);if(n.value)return c("State branch upstream already configured",!1);let o=await as({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 Oo({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
- ${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)},Ho=async({stateBranchRoot:e,eventFileName:t})=>{let n=us(t),o=Wo.join(e,n);if(!Vt.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)},Zi=async({stateBranchRoot:e})=>{let t=zi(),n=Wo.join(e,t);if(!Vt.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)},ea=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Gu(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 ds(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)},ta=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let o=!1,r=vn(e);if(a(r))return r;let s=r.value,d=[jo(),await Yu({repoRoot:e,stateBranchName:s}),await Xn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Qu({stateBranchRoot:t,stateBranchName:s}),await Xi(t),n?await Zu({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 em}from"ws";var tm,na,oa=y(()=>{"use strict";tm=new Set,na=e=>{let t=JSON.stringify(e);for(let n of tm)n.readyState===em.OPEN&&n.send(t)}});function ps(e){return e.context===D.WORKSPACE}function k(e){return e.context===D.TICKET}function ra(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,Gt,qo,Zn,se=y(()=>{"use strict";D={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};Gt=e=>e.context===D.SWIMLANE,qo=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 sa=y(()=>{"use strict";Yt()});function zo(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 ia,aa,da=y(()=>{"use strict";ia=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},aa=(e,t)=>t?e.get(t)??[]:[]});var ca,nm,la,ua=y(()=>{"use strict";yn();da();ca=new WeakMap,nm=e=>{let t=ca.get(e);return t||(t=ia(e),ca.set(e,t)),t},la=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let o=t.toLowerCase();return aa(nm(e),o).filter(s=>zo(o,s)>=n)}});var om,ma,rm,pa=y(()=>{"use strict";yn();ua();om={hint:"",hints:[],overlap:0,remainder:""},ma=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},o)=>{if(n||e==="")return om;let r=la({wordList:o,inputToMatch:e,overlapThreshold:1});return rm(t,r)},rm=(e,t)=>{let n=t[0]??"",o=zo(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 Oh}from"react";var Vo,sm,im,ie,Ve,Le=y(()=>{"use strict";Vo={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},sm=new Set,im=()=>{for(let e of sm)e()},ie=()=>Vo,Ve=e=>(Vo={...Vo,...e},im(),Vo)});function ga(e){return!e||!dm.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 Pe(e,t){if(!e&&!t)return $e(et/2n,bn);let n=e?ga(e):c("Resolved lower bound",0n);if(a(n))return n;let o=t?ga(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 fa(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,am,et,dm,In=y(()=>{"use strict";C();bn=24n,am=bn*4n,et=(1n<<am)-1n,dm=/^[0-9a-f]+$/});import{ulid as cm}from"ulid";var gs,va=y(()=>{"use strict";C();lt();In();gs=(e,t)=>{let n=ne(e),o=fa(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:cm(),action:"rebalance.children",payload:{parent:e,ranks:r},...t})}});var Go,je,ut=y(()=>{"use strict";C();Go="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 Xt,lm,Dt,x,ce=y(()=>{"use strict";ut();se();C();w();lt();Xt=(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}`)},lm=(e,t)=>{let{nodes:n}=g(),o=n[e];for(;o?.parentNodeId;){if(o.parentNodeId===t)return!0;o=n[o.parentNodeId]}return!1},Dt=(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"),x={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=Dt(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=Dt(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=Dt(r,"move");if(d)return d;if(lm(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=Dt(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:Go,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=Dt(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=Dt(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=Dt(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=Dt(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,ha,En=y(()=>{"use strict";tt=e=>e.slice(-7).toUpperCase(),ha=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?tt(e).includes(n):!0}});var xe,Jt=y(()=>{"use strict";se();En();xe={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,De=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,Yo=y(()=>{"use strict";De();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 ya from"chalk";var vs,ba,fs,Ia,um,mm,xa,pm,gm,to,Te,Ea,Na,Xo,fm,vm,Jo,mt=y(()=>{"use strict";Yo();vs={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},ba=(e,t,n)=>Math.max(t,Math.min(n,e)),fs=(e,t,n)=>e+(t-e)*n,Ia=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},um=e=>e.toLowerCase().trim(),mm=(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)]},xa=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,pm=(e,t,n)=>{let o=ba(n,0,1);return[Math.round(fs(e[0],t[0],o)),Math.round(fs(e[1],t[1],o)),Math.round(fs(e[2],t[2],o))]},gm=(e,t,n)=>pm(e,t,n),to=e=>{let t=Ia(e)%360,n=mm(t,vs.stringColor.saturation,vs.stringColor.lightness);return xa(n)},Te=(e,t=Nn)=>{let n=um(e);return n&&t[n]?t[n]:to(n)},Ea=e=>{let t=vs.gradient.stops,n=ba(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 gm(t[s],t[s+1],d)},Na=e=>xa(Ea(e)),Xo=e=>Ia(e.toLowerCase().trim())/4294967295,fm=e=>{let t=Xo(e);return Ea(t)},vm=e=>{let[t,n,o]=fm(e);return{normal:r=>ya.bgRgb(t,n,o).black(r),cursor:r=>ya.bgRgb(t,n,o).white.bold(r)}},Jo=e=>vm(e).normal(` ${e} `)});var Rn,Qo=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 Ft from"chalk";import Ra from"string-width";import{decodeTime as hm}from"ulid";var ym,bm,hs,Im,xm,Ca,Sa,Em,Nm,Rm,Cm,Sm,Aa,Ta,Zo=y(()=>{"use strict";ce();w();mt();Qo();ym=(e,t)=>e+" ".repeat(Math.max(0,t-Ra(e))),bm=(e,t)=>" ".repeat(Math.max(0,t-Ra(e)))+e,hs=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","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","create.contributor":"Added contributor","link.contributor.user":"Linked contributor","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),Im=(e,t)=>t?e<t?"up":e>t?"down":null:null,xm=(e,t)=>{let n=x.getNode(e.payload.parent),o=n?Ft.dim.bgBlack(` ${n.title} `):"unknown",r=t.at(-1);if(r&&"parent"in r&&"rank"in r&&r.parent===e.payload.parent){let s=Im(e.payload.rank,r.rank);if(s)return`Moved ${s} in ${o}`}return`Moved issue to ${o}`},Ca=e=>`${Math.max(1,Math.round(e/1024))} KB`,Sa=e=>x.getAttachment(e)?.name??"",Em=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Ft.bgHex(Te(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Ft.bgHex(Te(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Ft.hex(Te(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Ft.hex(Te(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"create.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Ft.dim(`(${Ca(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Sa(e.payload.id);return t?`"${t}"`:""}default:return""}},Nm=e=>{let t=Rn(hm(e));return Ft.gray(bm(t,8))},Rm=12,Cm=e=>ym(`${e}`,Rm),Sm=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=x.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Ca(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Sa(e.payload.id);return t?`"${t}"`:""}default:return""}},Aa=e=>[hs(e.action),Sm(e)].filter(Boolean).join(" "),Ta=(e,t)=>{let n=Nm(e.id),o=Cm(e.userName),r=Ft.dim("\u203A"),s=e.action==="move.node"?xm(e,t):[hs(e.action),Em(e)].filter(Boolean).join(" ");return`${o} ${n} ${r} ${s}`}});import{createHash as Am}from"node:crypto";var Tm,wm,Ee,Cn=y(()=>{"use strict";Tm="0123456789ABCDEFGHJKMNPQRSTVWXYZ",wm=e=>{let t=Am("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+=Tm[Number(n>>s&31n)]}return o},Ee=(e,t)=>wm(`${e}:virtual:${t}`)});var Mm,km,Lm,Pm,Dm,Fm,er,wa,Ma,Bm,ka=y(()=>{"use strict";Zo();se();C();xn();ce();Jt();w();In();Cn();Mm=e=>Ee(e,"comments"),km=e=>Ee(e,"description"),Lm=e=>Ee(e,"assignees"),Pm=e=>Ee(e,"tags"),Dm=e=>Ee(e,"history"),Fm=e=>Ee(e,"attachments"),er=({id:e,name:t,parentNodeId:n,rank:o,value:r,readonly:s=!1,childRenderAxis:d="horizontal"})=>{let l=x.getNode(e);if(!l){let p=x.createNode({...xe.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=x.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)},wa=({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!1,childRenderAxis:s="horizontal"})=>{let d=x.getNode(e);if(!d){let m=x.createNode({...xe.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=x.updateNode({...d,title:t,parentNodeId:n,rank:o,readonly:r,childRenderAxis:s});return a(u)?u:c("Virtual field list updated",void 0)},Ma=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=er({id:km(e.id),name:X.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(l))return l;let u=wa({id:Lm(e.id),name:X.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(u))return u;let m=wa({id:Pm(e.id),name:X.TAGS,parentNodeId:e.id,rank:o.value,readonly:!0});if(a(m))return m;let p=er({id:Mm(e.id),name:X.COMMENTS,parentNodeId:e.id,rank:r.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(p))return p;let v=er({id:Fm(e.id),name:X.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(v))return v;let I=er({id:Dm(e.id),name:X.HISTORY,parentNodeId:e.id,rank:d.value,value:Bm(e),readonly:!0,childRenderAxis:"vertical"});return a(I)?I:c("Ticket virtual nodes materialized",void 0)},Bm=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=>Ta(o,n.get(o.action)??[])).join(`
41
- `)}});var Om,he,tr,Sn=y(()=>{"use strict";Om=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[he,tr]=Om});function Bt(e,t=!1){let n=Km[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=Hm(e,t);return r||o}var L,La,Um,_m,$m,ys,jm,Wm,Hm,Km,bt,It=y(()=>{"use strict";se();C();xn();ce();Jt();w();ka();Sn();L=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),La=e=>{let t=x.getNode(e);if(!t||!k(t)||t.isDeleted)return null;let n=Ma(t);return a(n)?n:null},Um=e=>{for(let t of e){let n=La(t);if(n)return n;let o=g().nodes[t]?.parentNodeId;if(!o)continue;let r=La(o);if(r)return r}return null},_m=(e,t)=>{let n=x.getNode(e);n&&x.updateNode({...n,log:[...n.log??[],t]})},$m=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},ys=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 $m(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[]}},jm=e=>{me(t=>({...t,eventLog:[...t.eventLog,e]}))},Wm=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?L("Invalid user ID format",e):c("Valid user",null)},Hm=(e,t)=>{let n=Wm(e);if(a(n))return n;let o=[...new Set(ys(e))];t||(o.forEach(s=>_m(s,e)),jm(e));let r=Um(o);return r||null},Km={"init.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=xe.workspace(t,n,o),s=no(r);if(a(s))return L(s.message,e);let d=x.createNode(r);return a(d)?L(d.message??"Failed to initialize workspace",e):ps(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=x.createNode(xe.workspace(t,n,o));return a(r)?L(r.message??"Failed to add workspace",e):ps(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=x.createNode(xe.board(t,n,o,r));return a(s)?L(s.message??"Unable to create board",e):qo(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=x.createNode(xe.swimlane(t,n,o,r));return a(s)?L(s.message??"Unable to create swimlane",e):Gt(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=x.createNode(xe.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=x.createNode(xe.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(!x.getNode(t))return L(`Unable to locate node with id ${t}`,e);let r=x.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=x.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=x.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=x.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=x.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=x.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=x.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=x.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=x.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=x.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=x.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=x.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=x.getNode(t);if(!r)return L("Unable to locate issue",e);if(!k(r))return L("Can only close issues",e);let s=x.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=x.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=x.getNode(t);if(!r)return L("Unable to locate issue",e);if(!k(r))return L("Can only reopen issues",e);let s=x.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(!x.getNode(n))return L("Reopen parent no longer exists",e);let l=x.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=x.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=x.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=x.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=x.createComment({id:t,issue:n,authorId:o,authorName:x.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=x.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=x.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=x.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=x.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=x.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=x.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=x.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=x.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=>{let t=Pa(()=>e.map(n=>Bt(n)));return a(t)?e.map(()=>i(t.message)):t.value}});var oo,bs=y(()=>{"use strict";oo=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"});var qm,zm,Da,Fa,Is=y(()=>{"use strict";qm=["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"],zm=new Set(qm),Da=e=>zm.has(e),Fa=e=>({action:e.action,payload:e.payload})});import nr from"node:fs";import Es from"node:path";import{decodeTime as Vm}from"ulid";import{z as xs}from"zod";function Rs(e){let t=Kn(e);if(!nr.existsSync(t))return c("No events found",[]);let n=nr.readdirSync(t).filter(r=>r.endsWith(".jsonl")).map(r=>Es.join(t,r)),o=[];for(let r of n){let s=np(r);if(a(s))return i(s.message);o.push(...s.value)}return c("All events loaded",op(o))}function Ge(e){let t=Rs(e);return a(t)?i(t.message):Ns(t.value)}function Cs(e,t){let n=Rs(e);if(a(n))return i(n.message);let{appliedEvents:o,unappliedEvents:r}=rp(n.value,t),s=Ns(o);if(a(s))return i(s.message);let d=Ns(r);return a(d)?i(d.message):c("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function Ba(e=process.cwd()){let t=Rs(e);return a(t)?i(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Gm,Ym,Xm,Jm,Qm,Zm,ep,tp,Ns,np,op,rp,Qt=y(()=>{"use strict";fn();C();ue();Is();nt();Gm=xs.object({userId:xs.string().min(1).default("unknown"),userName:xs.string().min(1).default("unknown")}),Ym=/^[0-9a-hjkmnp-tv-z]{26}$/i,Xm=e=>Ym.test(e)?e.toUpperCase():e,Jm=e=>{let t=Es.basename(e,".jsonl"),n=t.indexOf("."),o=n===-1?t:t.slice(0,n),r=n===-1?void 0:t.slice(n+1),s=Gm.safeParse({userId:Xm(o),userName:r});return s.success?c("Parsed event file actor",s.data):i(`Invalid event file name ${Es.basename(e)}: ${s.error.issues.map(d=>d.path.join(".")||d.message).join(", ")}`)},Qm=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])},Zm=(e,t)=>t in e,ep=({id:e,action:t,payload:n,userId:o,userName:r})=>({id:e,action:t,payload:n,userId:o,userName:r}),tp=e=>{let{userId:t,userName:n,...o}=e,r=Qm(o);if(a(r))return i(r.message);let s=r.value,d=e.id?.[0];return d?Zm(o,s)?c("Decoded persisted event",ep({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")},Ns=e=>{let t=[],n=new Map;for(let o of e){let r=tp(o);if(a(r))return i(`Failed to decode event ${o.id?.[0]??"<unknown>"}: ${r.message}`);let s=r.value.action;if(!Da(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)},np=e=>{if(!nr.existsSync(e))return c("Event file missing",[]);let t=Jm(e);if(a(t))return i(t.message);let n=nr.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=Ss(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)};op=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 I=n.get(v)??[];I.push(m),n.set(v,I)}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 I of v)s(I)},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},rp=(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=Vm(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 sp from"node:fs";import ip from"node:path";import{decodeTime as ap,monotonicFactory as dp}from"ulid";import{z as ro}from"zod";function or({event:e,rootDir:t}){try{let n=Mi(t);if(a(n))return n;let o=pp(t,{userId:e.userId,userName:e.userName});if(a(o))return o;let r=Ba(t);if(a(r))return i(r.message);let s=r.value?Oa(Math.max(Date.now(),ap(r.value)+1)):Oa(),d=gp(Fa(e),[s,r.value]);return a(d)?i(d.message):(sp.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 Ua,Oa,cp,lp,Ss,up,mp,ae,Zt,pp,gp,nt=y(()=>{"use strict";C();Le();ue();bs();Qt();Is();Ua=1,Oa=dp(),cp=ro.tuple([ro.string().min(1),ro.string().min(1).nullable()]),lp=ro.looseObject({v:ro.literal(Ua),id:cp}),Ss=e=>{let t=lp.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(", ")}`)},up=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),mp=e=>e.trim().length>0&&e.length<=80,ae=()=>{let{userName:e,userId:t}=ie();return e?t?up(t)?mp(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")},Zt=({userId:e,userName:t})=>`${oo(e)}.${oo(t)}.jsonl`,pp=(e,{userId:t,userName:n})=>{let o=Zt({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(o))return i(`Invalid event log file name: ${o}`);let s=ip.join(Kn(e),o);return c("Successfully resolved event log path",s)},gp=(e,t)=>{let n={[e.action]:e.payload,v:Ua,id:t};return Ss(n)}});import{ulid as fp}from"ulid";function _a(e,t){let n=Bt(e);if(n.status!==kt.Success)return n;let o=or({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=vp(e[0],t);if(a(n))return n;let o=e.map(s=>_a(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 vp,en=y(()=>{"use strict";C();ce();It();nt();vp=(e,t)=>{if(e.action==="create.contributor")return c("Contributor already being created",void 0);if(x.getContributor(e.userId))return c("Contributor exists",void 0);let n={id:fp(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},o=_a(n,t);return a(o)?i(o.message):c("Contributor created",void 0)}});var $a,rr,ne,ja,Wa,Ot,tn,lt=y(()=>{"use strict";va();en();C();w();In();$a=e=>rr(ne(e),{at:"end"}),rr=(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(Pe(void 0,void 0));let o=()=>n(Pe(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let r=e[0];return r?n(Pe(void 0,r.rank)):i("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(Pe(r.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let r=ja(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(Pe(d?.rank,s.rank))}case"after":{let r=ja(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(Pe(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)),ja=(e,t)=>e.findIndex(n=>n.id===t),Wa=(e,t,n={at:"end"})=>rr(ne(t).filter(o=>o.id!==e),n),Ot=(e,t,n,o,r)=>{let s=Wa(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return c("Resolved rank",s.value.rank);let d=gs(e,o);if(a(d))return d;let l=B([d.value],r);if(a(l))return l;let u=Wa(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)},tn=(e,t,n)=>{let o=$a(e);if(a(o))return o;if(!o.value.needsRebalance)return c("Resolved rank",o.value.rank);let r=gs(e,t);if(a(r))return r;let s=B([r.value],n);if(a(s))return s;let d=$a(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,Ha,Ka,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:()=>Ha(1),navigateToPreviousItem:()=>Ha(-1),navigateToNextContainer:()=>Ka(1),navigateToPreviousContainer:()=>Ka(-1),navigate:({contextNode:e,selectedIndex:t})=>{E({contextNodeId:e.id,selectedIndex:t})}},Ha=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})},Ka=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(I=>I.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 za,Va,hp,sr,Ga,qa,yp,Ya,Xa=y(()=>{"use strict";se();C();lt();w();We();za=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Va=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},hp=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&_e(t)&&t.childRenderAxis==="vertical"},sr=(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:za(t,r.length)}),!0},Ga=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let o=n.parentNodeId;if(!o)return sr(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):Ga(r.id)},qa=e=>{let{nodes:t}=g(),n=e,o=new Set;for(;n&&!o.has(n);){if(o.add(n),Ga(n))return!0;n=t[n]?.parentNodeId}return!1},yp=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},Ya=e=>{let{nodes:t,rootNodeId:n}=g();if(hp(e.contextNodeId)&&sr(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(yp(e.selectedNodeId)&&e.selectedNodeId&&qa(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(sr(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&sr(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(qa(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:za(e.selectedIndex,r.length)}),c("Restored navigation to root",null)}});import{monotonicFactory as bp,ulid as xt}from"ulid";function Ip(){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 xp(){let e=Ip();return a(e)?e:F.navigate(e.value)}function Ja({userId:e,userName:t}){let n=so(),o=so(),r=so(),s=so(),d=so(),l=Pe(void 0,void 0);if(a(l))return l;let u=Pe(void 0,void 0);if(a(u))return u;let m=Pe(u.value,void 0);if(a(m))return m;let p=Pe(void 0,void 0);if(a(p))return p;let v=Pe(p.value,void 0);if(a(v))return v;let I=Pe(v.value,void 0);if(a(I))return I;let S=Pe(void 0,void 0);return a(S)?S:c("Created default events",[{id:xt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:xt(),userId:e,userName:t,action:"add.board",payload:{id:o,name:"Default",parent:n,rank:u.value}},{id:xt(),userId:e,userName:t,action:"add.swimlane",payload:{id:r,name:"Todo",parent:o,rank:p.value}},{id:xt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:o,rank:v.value}},{id:xt(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:o,rank:I.value}},{id:xt(),userId:e,userName:t,action:"add.board",payload:{id:tr,name:"Closed",parent:n,rank:m.value}},{id:xt(),userId:e,userName:t,action:"add.swimlane",payload:{id:he,name:"Closed",parent:tr,rank:S.value}},{id:xt(),userId:e,userName:t,action:"lock.node",payload:{id:tr}},{id:xt(),userId:e,userName:t,action:"lock.node",payload:{id:he}}])}function An(e){if(Ep())return c("Skipped boot while checked out at a historical point",null);if(!e.length){let o=xe.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:
19
+ `).filter(Boolean).filter(d=>d!==st);if(o.length===0)return c("State branch is storage-only",!1);let r=await _({args:["rm","-r","--ignore-unmatch","--",...o],cwd:e});if(a(r))return i(`Failed to clean storage branch
20
+ ${r.message}`);let s=await In({cwd:e,message:"[epiq:repair-storage-branch]"});return a(s)?i(s.message):c("Cleaned storage branch",!0)},at=rs(async(e=process.cwd())=>{let t=await _({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=>lt.resolve(e)),ph=rs(async e=>{let t=await _({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return i(t.message);let n=t.value.stdout.trim(),o=lt.isAbsolute(n)?n:lt.join(e,n);return c("Resolved git dir",o)},e=>lt.resolve(e))});import Jt from"node:fs";import Ho from"node:path";var ea,Zi,Xu,gs,Ju,Qu,Zu,Xn,em,tm,Ko,ta,na,Jn,oa,qo=y(()=>{"use strict";S();bn();Do();Fo();dt();Ft();ea=async e=>{if((await ct({args:["rev-parse","--verify","HEAD"],cwd:e})).exitCode===0)return c("Initial commit already exists",!1);he.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",Xu=async e=>{let t=await $o(e);if(a(t))return i(t.message);let n=await Wi(e);return a(n)?i(n.message):c("Built sync commit message",`[sync|branch:${Zi(t.value)}:sha:${Zi(n.value)}]`)},gs=async({repoRoot:e,stateBranchName:t})=>{he.info(`Creating ${t}`);let n=await _({args:["commit-tree",Gi,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return i(`Failed to create state branch commit
21
+ ${n.message}`);let o=n.value.stdout.trim(),r=await _({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)},Ju=async({repoRoot:e,stateBranchName:t})=>{let n=await cs({repoRoot:e});if(a(n))return i(`Ensure local state branch failed
23
+ `+n.message);let o=n.value,r=o?await Uo({repoRoot:e,branch:t}):c("No remote, no remote state branch",!1);if(a(r))return i(`Ensure local state branch failed
24
+ `+r.message);let s=r.value;if(o&&s){let l=await de.fetch({cwd:e,remote:ze,branch:t});if(a(l))return i(`Failed to fetch ${t} from remote
25
+ ${l.message}`)}let d=await _o({repoRoot:e,branch:t});if(a(d))return i(`Ensure local state branch failed
26
+ `+d.message);if(d.value)return c("Local state branch already exists",!1);if(s){let l=await _({args:["branch","--track",t,`${ze}/${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 gs({repoRoot:e,stateBranchName:t})},Qu=async({repoRoot:e,branch:t})=>{let n=await _({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)},Zu=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=Yn(Ho.dirname(t));if(a(o))return i(`Failed to create state branch worktree
29
+ `+o.message);Jt.existsSync(t)&&!Jt.existsSync(Ho.join(t,".git"))&&(he.info("Removing broken state branch worktree path"),Xi(t)),he.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 Qu({repoRoot:e,branch:n});if(a(o))return i(o.message);let r=Vn(t),s=o.value?Vn(o.value):null;if(s&&s===r&&Jt.existsSync(s))return c("State branch already checked out in expected worktree",!1);if(s&&s!==r){he.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&&!Jt.existsSync(s)){he.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 ji({repoRoot:e,worktreeRoot:t});if(a(d))return i(d.message);let l=Jt.existsSync(t);if(d.value&&l)return c("State branch worktree already exists",!1);if(d.value&&!l){he.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 Zu({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},em=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await $o(e);if(a(n))return i(n.message);if(n.value===t)return c("State branch already checked out",!1);(await ct({cwd:e,args:["rebase","--abort"]})).exitCode===0&&he.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)},tm=async({repoRoot:e,stateBranchRoot:t})=>{let n=await ls(t);if(a(n))return i(n.message);if(n.value)return c("State branch upstream already configured",!1);let o=await cs({repoRoot:t});if(a(o))return i(o.message);if(!o.value)return c("No remote available for state branch upstream",!1);let r=xn(e);if(a(r))return r;let s=r.value,d=await Uo({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);he.info(`Configuring ${s} upstream`);let l=await de.fetch({cwd:t,remote:ze,branch:s});if(a(l))return i(`Failed to fetch ${s}
35
+ ${l.message}`);let u=await de.setUpstream({cwd:t,branch:s,upstream:`${ze}/${s}`});return a(u)?i(`Failed to set state branch upstream
36
+ ${u.message}`):c("Configured state branch upstream",!0)},Ko=async({stateBranchRoot:e,eventFileName:t})=>{let n=ps(t),o=Ho.join(e,n);if(!Jt.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)},ta=async({stateBranchRoot:e})=>{let t=Vi(),n=Ho.join(e,t);if(!Jt.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)},na=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Xu(e);return a(n)?i(`Create state branch sync commit failed
39
+ `+n.message):In({cwd:t,message:n.value})},Jn=async({repoRoot:e,stateBranchRoot:t})=>{let n=await ls(t);if(a(n))return i(n.message);let o=xn(e);if(a(o))return o;let r=o.value,s=n.value?await de.push({cwd:t}):await de.push({cwd:t,remote:ze,branch:r,setUpstream:!0});return a(s)?i(`Failed during state branch push
40
+ ${s.message}`):c("Pushed state branch",!0)},oa=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let o=!1,r=xn(e);if(a(r))return r;let s=r.value,d=[Wo(),await Ju({repoRoot:e,stateBranchName:s}),await Xn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await em({stateBranchRoot:t,stateBranchName:s}),await Qi(t),n?await tm({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 nm}from"ws";var om,ra,sa=y(()=>{"use strict";om=new Set,ra=e=>{let t=JSON.stringify(e);for(let n of om)n.readyState===nm.OPEN&&n.send(t)}});function fs(e){return e.context===D.WORKSPACE}function L(e){return e.context===D.TICKET}function ia(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,Qt,zo,Zn,se=y(()=>{"use strict";D={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};Qt=e=>e.context===D.SWIMLANE,zo=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 aa=y(()=>{"use strict";Zt()});function Go(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}var xt,Ge,Bt=y(()=>{"use strict";xt=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Ge=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var da,ca,la=y(()=>{"use strict";da=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},ca=(e,t)=>t?e.get(t)??[]:[]});var ua,rm,ma,pa=y(()=>{"use strict";Bt();la();ua=new WeakMap,rm=e=>{let t=ua.get(e);return t||(t=da(e),ua.set(e,t)),t},ma=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let o=t.toLowerCase();return ca(rm(e),o).filter(s=>Go(o,s)>=n)}});var sm,ga,im,fa=y(()=>{"use strict";Bt();pa();sm={hint:"",hints:[],overlap:0,remainder:""},ga=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},o)=>{if(n||e==="")return sm;let r=ma({wordList:o,inputToMatch:e,overlapThreshold:1});return im(t,r)},im=(e,t)=>{let n=t[0]??"",o=Go(e.toLowerCase(),n.toLowerCase()),[r,s]=n.split(":"),d=o<(r??"").length,l=!!s,p=(l&&d?r:n)+(l&&d?":":" "),h=p.slice(o);return{hint:p,hints:t,overlap:o,remainder:h}}});import{useSyncExternalStore as jh}from"react";var Vo,am,dm,ie,Ve,Pe=y(()=>{"use strict";Vo={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},am=new Set,dm=()=>{for(let e of am)e()},ie=()=>Vo,Ve=e=>(Vo={...Vo,...e},dm(),Vo)});function va(e){return!e||!lm.test(e)?i(`Invalid hex rank: ${e}`):c("Converted rank to bigint",BigInt("0x"+e))}function je(e,t=En){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 je(tt/2n,En);let n=e?va(e):c("Resolved lower bound",0n);if(a(n))return n;let o=t?va(t):c("Resolved upper bound",tt);if(a(o))return o;let r=n.value,s=o.value;if(s<=r)return je(tt/2n,En);let d=(r+s)/2n;return d===r||d===s?i("No rank space available between neighbors"):je(d,En)}function ha(e){if(e<=0)return c("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let o=0;o<e;o++){let r=tt*BigInt(o+1)/(t+1n),s=je(r,En);if(a(s))return s;n.push(s.value)}return c("Resolved evenly spaced ranks",n)}var En,cm,tt,lm,Nn=y(()=>{"use strict";S();En=24n,cm=En*4n,tt=(1n<<cm)-1n,lm=/^[0-9a-f]+$/});import{ulid as um}from"ulid";var vs,ya=y(()=>{"use strict";S();ut();Nn();vs=(e,t)=>{let n=ne(e),o=ha(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:um(),action:"rebalance.children",payload:{parent:e,ranks:r},...t})}});var Yo,We,mt=y(()=>{"use strict";S();Yo="removed",We=(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 en,mm,Ot,I,ce=y(()=>{"use strict";mt();se();S();w();ut();en=(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}`)},mm=(e,t)=>{let{nodes:n}=g(),o=n[e];for(;o?.parentNodeId;){if(o.parentNodeId===t)return!0;o=n[o.parentNodeId]}return!1},Ot=(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=Ot(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=Ot(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=Ot(r,"move");if(d)return d;if(mm(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=Ot(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 h of ne(p.id))l(h.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:Yo,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=Ot(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=Ot(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=Ot(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=Ot(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,Rn=y(()=>{"use strict";X={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var nt,ba,Cn=y(()=>{"use strict";nt=e=>e.slice(-7).toUpperCase(),ba=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?nt(e).includes(n):!0}});var Ne,tn=y(()=>{"use strict";se();Cn();Ne={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:nt(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:nt(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 Te,C,Fe=y(()=>{"use strict";Te={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"},C={accent:Te.cyan,accent2:Te.magenta,primary:Te.white,secondary:Te.grayDark,secondary2:Te.grayLight,gray:Te.gray,green:Te.green,yellow:Te.yellow,red:Te.red}});var N,Sn,Xo=y(()=>{"use strict";Fe();N={red:Te.red,yellow:Te.yellow,green:Te.green,blue:Te.blue,magenta:Te.magenta,cyan:Te.cyan},Sn={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 xa from"chalk";var ys,Ia,hs,Ea,pm,gm,Na,fm,vm,eo,we,Ra,Ca,Jo,hm,ym,Qo,pt=y(()=>{"use strict";Xo();ys={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Ia=(e,t,n)=>Math.max(t,Math.min(n,e)),hs=(e,t,n)=>e+(t-e)*n,Ea=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},pm=e=>e.toLowerCase().trim(),gm=(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 h=r-s/2;return[Math.round((u+h)*255),Math.round((m+h)*255),Math.round((p+h)*255)]},Na=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,fm=(e,t,n)=>{let o=Ia(n,0,1);return[Math.round(hs(e[0],t[0],o)),Math.round(hs(e[1],t[1],o)),Math.round(hs(e[2],t[2],o))]},vm=(e,t,n)=>fm(e,t,n),eo=e=>{let t=Ea(e)%360,n=gm(t,ys.stringColor.saturation,ys.stringColor.lightness);return Na(n)},we=(e,t=Sn)=>{let n=pm(e);return n&&t[n]?t[n]:eo(n)},Ra=e=>{let t=ys.gradient.stops,n=Ia(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 vm(t[s],t[s+1],d)},Ca=e=>Na(Ra(e)),Jo=e=>Ea(e.toLowerCase().trim())/4294967295,hm=e=>{let t=Jo(e);return Ra(t)},ym=e=>{let[t,n,o]=hm(e);return{normal:r=>xa.bgRgb(t,n,o).black(r),cursor:r=>xa.bgRgb(t,n,o).white.bold(r)}},Qo=e=>ym(e).normal(` ${e} `)});var An,Zo=y(()=>{"use strict";An=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 Ut from"chalk";import Sa from"string-width";import{decodeTime as bm}from"ulid";var xm,Im,bs,Em,Nm,Aa,Ta,Rm,Cm,Sm,Am,Tm,wa,Ma,er=y(()=>{"use strict";ce();w();pt();Zo();xm=(e,t)=>e+" ".repeat(Math.max(0,t-Sa(e))),Im=(e,t)=>" ".repeat(Math.max(0,t-Sa(e)))+e,bs=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","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","create.contributor":"Added contributor","link.contributor.user":"Linked contributor","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),Em=(e,t)=>t?e<t?"up":e>t?"down":null:null,Nm=(e,t)=>{let n=I.getNode(e.payload.parent),o=n?Ut.dim.bgBlack(` ${n.title} `):"unknown",r=t.at(-1);if(r&&"parent"in r&&"rank"in r&&r.parent===e.payload.parent){let s=Em(e.payload.rank,r.rank);if(s)return`Moved ${s} in ${o}`}return`Moved issue to ${o}`},Aa=e=>`${Math.max(1,Math.round(e/1024))} KB`,Ta=e=>I.getAttachment(e)?.name??"",Rm=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Ut.bgHex(we(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Ut.bgHex(we(t.name))(` ${t.name} `):"unknown tag"}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Ut.hex(we(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Ut.hex(we(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}" ${Ut.dim(`(${Aa(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Ta(e.payload.id);return t?`"${t}"`:""}default:return""}},Cm=e=>{let t=An(bm(e));return Ut.gray(Im(t,8))},Sm=12,Am=e=>xm(`${e}`,Sm),Tm=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}" (${Aa(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Ta(e.payload.id);return t?`"${t}"`:""}default:return""}},wa=e=>[bs(e.action),Tm(e)].filter(Boolean).join(" "),Ma=(e,t)=>{let n=Cm(e.id),o=Am(e.userName),r=Ut.dim("\u203A"),s=e.action==="move.node"?Nm(e,t):[bs(e.action),Rm(e)].filter(Boolean).join(" ");return`${o} ${n} ${r} ${s}`}});import{createHash as wm}from"node:crypto";var Mm,Lm,Re,Tn=y(()=>{"use strict";Mm="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Lm=e=>{let t=wm("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+=Mm[Number(n>>s&31n)]}return o},Re=(e,t)=>Lm(`${e}:virtual:${t}`)});var km,Pm,Dm,Fm,Bm,Om,tr,La,ka,Um,Pa=y(()=>{"use strict";er();se();S();Rn();ce();tn();w();Nn();Tn();km=e=>Re(e,"comments"),Pm=e=>Re(e,"description"),Dm=e=>Re(e,"assignees"),Fm=e=>Re(e,"tags"),Bm=e=>Re(e,"history"),Om=e=>Re(e,"attachments"),tr=({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({...Ne.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)},La=({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({...Ne.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)},ka=e=>{let t=je(tt/4n),n=je(tt/2n),o=je(tt*3n/4n),r=je(tt*7n/8n),s=je(tt*15n/16n),d=je(tt*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=tr({id:Pm(e.id),name:X.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(l))return l;let u=La({id:Dm(e.id),name:X.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(u))return u;let m=La({id:Fm(e.id),name:X.TAGS,parentNodeId:e.id,rank:o.value,readonly:!0});if(a(m))return m;let p=tr({id:km(e.id),name:X.COMMENTS,parentNodeId:e.id,rank:r.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(p))return p;let h=tr({id:Om(e.id),name:X.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(h))return h;let b=tr({id:Bm(e.id),name:X.HISTORY,parentNodeId:e.id,rank:d.value,value:Um(e),readonly:!0,childRenderAxis:"vertical"});return a(b)?b:c("Ticket virtual nodes materialized",void 0)},Um=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=>Ma(o,n.get(o.action)??[])).join(`
41
+ `)}});var _m,ye,nr,wn=y(()=>{"use strict";_m=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ye,nr]=_m});function _t(e,t=!1){let n=zm[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=qm(e,t);return r||o}var k,Da,$m,jm,Wm,xs,Hm,Km,qm,zm,It,Et=y(()=>{"use strict";se();S();Rn();ce();tn();w();Pa();wn();k=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),Da=e=>{let t=I.getNode(e);if(!t||!L(t)||t.isDeleted)return null;let n=ka(t);return a(n)?n:null},$m=e=>{for(let t of e){let n=Da(t);if(n)return n;let o=g().nodes[t]?.parentNodeId;if(!o)continue;let r=Da(o);if(r)return r}return null},jm=(e,t)=>{let n=I.getNode(e);n&&I.updateNode({...n,log:[...n.log??[],t]})},Wm=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},xs=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 Wm(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[]}},Hm=e=>{me(t=>({...t,eventLog:[...t.eventLog,e]}))},Km=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?k("Invalid user ID format",e):c("Valid user",null)},qm=(e,t)=>{let n=Km(e);if(a(n))return n;let o=[...new Set(xs(e))];t||(o.forEach(s=>jm(s,e)),Hm(e));let r=$m(o);return r||null},zm={"init.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=Ne.workspace(t,n,o),s=to(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):fs(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(Ne.workspace(t,n,o));return a(r)?k(r.message??"Failed to add workspace",e):fs(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(Ne.board(t,n,o,r));return a(s)?k(s.message??"Unable to create board",e):zo(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(Ne.swimlane(t,n,o,r));return a(s)?k(s.message??"Unable to create swimlane",e):Qt(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(Ne.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(Ne.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(ye);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(ye);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}})}};It=e=>{let t=Fa(()=>e.map(n=>_t(n)));return a(t)?e.map(()=>i(t.message)):t.value}});var no,Is=y(()=>{"use strict";no=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"});var Gm,Vm,Ba,Oa,Es=y(()=>{"use strict";Gm=["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"],Vm=new Set(Gm),Ba=e=>Vm.has(e),Oa=e=>({action:e.action,payload:e.payload})});import or from"node:fs";import Rs from"node:path";import{decodeTime as Ym}from"ulid";import{z as Ns}from"zod";function Ss(e){let t=Kn(e);if(!or.existsSync(t))return c("No events found",[]);let n=or.readdirSync(t).filter(r=>r.endsWith(".jsonl")).map(r=>Rs.join(t,r)),o=[];for(let r of n){let s=rp(r);if(a(s))return i(s.message);o.push(...s.value)}return c("All events loaded",sp(o))}function Ye(e){let t=Ss(e);return a(t)?i(t.message):Cs(t.value)}function As(e,t){let n=Ss(e);if(a(n))return i(n.message);let{appliedEvents:o,unappliedEvents:r}=ip(n.value,t),s=Cs(o);if(a(s))return i(s.message);let d=Cs(r);return a(d)?i(d.message):c("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function Ua(e=process.cwd()){let t=Ss(e);return a(t)?i(t.message):c("Loaded edge reference",t.value.at(-1)?.id?.[0]??null)}var Xm,Jm,Qm,Zm,ep,tp,np,op,Cs,rp,sp,ip,nn=y(()=>{"use strict";bn();S();ue();Es();ot();Xm=Ns.object({userId:Ns.string().min(1).default("unknown"),userName:Ns.string().min(1).default("unknown")}),Jm=/^[0-9a-hjkmnp-tv-z]{26}$/i,Qm=e=>Jm.test(e)?e.toUpperCase():e,Zm=e=>{let t=Rs.basename(e,".jsonl"),n=t.indexOf("."),o=n===-1?t:t.slice(0,n),r=n===-1?void 0:t.slice(n+1),s=Xm.safeParse({userId:Qm(o),userName:r});return s.success?c("Parsed event file actor",s.data):i(`Invalid event file name ${Rs.basename(e)}: ${s.error.issues.map(d=>d.path.join(".")||d.message).join(", ")}`)},ep=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])},tp=(e,t)=>t in e,np=({id:e,action:t,payload:n,userId:o,userName:r})=>({id:e,action:t,payload:n,userId:o,userName:r}),op=e=>{let{userId:t,userName:n,...o}=e,r=ep(o);if(a(r))return i(r.message);let s=r.value,d=e.id?.[0];return d?tp(o,s)?c("Decoded persisted event",np({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")},Cs=e=>{let t=[],n=new Map;for(let o of e){let r=op(o);if(a(r))return i(`Failed to decode event ${o.id?.[0]??"<unknown>"}: ${r.message}`);let s=r.value.action;if(!Ba(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(", ");he.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${o}. Upgrade to apply them.`)}return c("Decoded reconstructed events",t)},rp=e=>{if(!or.existsSync(e))return c("Event file missing",[]);let t=Zm(e);if(a(t))return i(t.message);let n=or.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=Ts(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)};sp=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],h=m.id[1]??null;t.set(p,m);let b=n.get(h)??[];b.push(m),n.set(h,b)}for(let m of n.values())m.sort((p,h)=>p.id[0].localeCompare(h.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 h=n.get(p)??[];for(let b of h)s(b)},d=n.get(null)??[];for(let m of d)s(m);let l=e.filter(m=>{let p=m.id[0],h=m.id[1]??null;return!r.has(p)&&h!==null&&!t.has(h)}).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},ip=(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=Ym(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 ap from"node:fs";import dp from"node:path";import{decodeTime as cp,monotonicFactory as lp}from"ulid";import{z as oo}from"zod";function rr({event:e,rootDir:t}){try{let n=ki(t);if(a(n))return n;let o=fp(t,{userId:e.userId,userName:e.userName});if(a(o))return o;let r=Ua(t);if(a(r))return i(r.message);let s=r.value?_a(Math.max(Date.now(),cp(r.value)+1)):_a(),d=vp(Oa(e),[s,r.value]);return a(d)?i(d.message):(ap.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 $a,_a,up,mp,Ts,pp,gp,ae,on,fp,vp,ot=y(()=>{"use strict";S();Pe();ue();Is();nn();Es();$a=1,_a=lp(),up=oo.tuple([oo.string().min(1),oo.string().min(1).nullable()]),mp=oo.looseObject({v:oo.literal($a),id:up}),Ts=e=>{let t=mp.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(", ")}`)},pp=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),gp=e=>e.trim().length>0&&e.length<=80,ae=()=>{let{userName:e,userId:t}=ie();return e?t?pp(t)?gp(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")},on=({userId:e,userName:t})=>`${no(e)}.${no(t)}.jsonl`,fp=(e,{userId:t,userName:n})=>{let o=on({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(o))return i(`Invalid event log file name: ${o}`);let s=dp.join(Kn(e),o);return c("Successfully resolved event log path",s)},vp=(e,t)=>{let n={[e.action]:e.payload,v:$a,id:t};return Ts(n)}});import{ulid as hp}from"ulid";function ja(e,t){let n=_t(e);if(n.status!==Pt.Success)return n;let o=rr({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=yp(e[0],t);if(a(n))return n;let o=e.map(s=>ja(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 yp,rn=y(()=>{"use strict";S();ce();Et();ot();yp=(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:hp(),action:"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName},o=ja(n,t);return a(o)?i(o.message):c("Contributor created",void 0)}});var Wa,sr,ne,Ha,Ka,$t,sn,ut=y(()=>{"use strict";ya();rn();S();w();Nn();Wa=e=>sr(ne(e),{at:"end"}),sr=(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(De(void 0,void 0));let o=()=>n(De(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let r=e[0];return r?n(De(void 0,r.rank)):i("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(De(r.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let r=Ha(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(De(d?.rank,s.rank))}case"after":{let r=Ha(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(De(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)),Ha=(e,t)=>e.findIndex(n=>n.id===t),Ka=(e,t,n={at:"end"})=>sr(ne(t).filter(o=>o.id!==e),n),$t=(e,t,n,o,r)=>{let s=Ka(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return c("Resolved rank",s.value.rank);let d=vs(e,o);if(a(d))return d;let l=B([d.value],r);if(a(l))return l;let u=Ka(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)},sn=(e,t,n)=>{let o=Wa(e);if(a(o))return o;if(!o.value.needsRebalance)return c("Resolved rank",o.value.rank);let r=vs(e,t);if(a(r))return r;let s=B([r.value],n);if(a(s))return s;let d=Wa(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,qa,za,He=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:()=>qa(1),navigateToPreviousItem:()=>qa(-1),navigateToNextContainer:()=>za(1),navigateToPreviousContainer:()=>za(-1),navigate:({contextNode:e,selectedIndex:t})=>{E({contextNodeId:e.id,selectedIndex:t})}},qa=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})},za=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(b=>b.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),h=u.length?p:-1;F.navigate({contextNode:l,selectedIndex:h})}});var Va,Ya,bp,ir,Xa,Ga,xp,Ja,Qa=y(()=>{"use strict";se();S();ut();w();He();Va=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Ya=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},bp=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&$e(t)&&t.childRenderAxis==="vertical"},ir=(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:Va(t,r.length)}),!0},Xa=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let o=n.parentNodeId;if(!o)return ir(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):Xa(r.id)},Ga=e=>{let{nodes:t}=g(),n=e,o=new Set;for(;n&&!o.has(n);){if(o.add(n),Xa(n))return!0;n=t[n]?.parentNodeId}return!1},xp=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},Ja=e=>{let{nodes:t,rootNodeId:n}=g();if(bp(e.contextNodeId)&&ir(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(xp(e.selectedNodeId)&&e.selectedNodeId&&Ga(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(ir(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&ir(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(Ga(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:Va(e.selectedIndex,r.length)}),c("Restored navigation to root",null)}});import{monotonicFactory as Ip,ulid as Nt}from"ulid";function Ep(){let e=Be();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 Np(){let e=Ep();return a(e)?e:F.navigate(e.value)}function Za({userId:e,userName:t}){let n=ro(),o=ro(),r=ro(),s=ro(),d=ro(),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 h=De(p.value,void 0);if(a(h))return h;let b=De(h.value,void 0);if(a(b))return b;let A=De(void 0,void 0);return a(A)?A:c("Created default events",[{id:Nt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:Nt(),userId:e,userName:t,action:"add.board",payload:{id:o,name:"Default",parent:n,rank:u.value}},{id:Nt(),userId:e,userName:t,action:"add.swimlane",payload:{id:r,name:"Todo",parent:o,rank:p.value}},{id:Nt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:o,rank:h.value}},{id:Nt(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:o,rank:b.value}},{id:Nt(),userId:e,userName:t,action:"add.board",payload:{id:nr,name:"Closed",parent:n,rank:m.value}},{id:Nt(),userId:e,userName:t,action:"add.swimlane",payload:{id:ye,name:"Closed",parent:nr,rank:A.value}},{id:Nt(),userId:e,userName:t,action:"lock.node",payload:{id:nr}},{id:Nt(),userId:e,userName:t,action:"lock.node",payload:{id:ye}}])}function Mn(e){if(Rp())return c("Skipped boot while checked out at a historical point",null);if(!e.length){let o=Ne.workspace("temporary-uninitialized-workspace","Workspace","a0"),r=to(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=It(e).filter(a);return n.length>0?i(`Materializing failed:
44
44
  ${n.map(o=>o.message).join(`
45
- `)}`):(xp(),E({hasProjectDefinition:!0}),c("State booted successfully",null))}var so,Ep,ir=y(()=>{"use strict";We();te();C();Jt();w();In();It();Sn();so=bp();Ep=()=>{let e=Fe();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"}});var G,As=y(()=>{"use strict";C();G=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});var pt,ar,Np,Qa,Ts=y(()=>{"use strict";Xa();ir();Qt();nt();te();C();w();dr();As();ws();pt=null,ar=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!pt,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),pt)return logger.debug("[sync] syncAndReloadState joining existing promise"),pt;logger.debug("[sync] syncAndReloadState creating promise"),pt=Np();try{let e=await pt;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}),pt||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),pt=null}},Np=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=Qa();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(pt)return pt;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=Zt(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let o=G("syncEpiqWithRemote",await cr({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=Qa();if(d)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:d.message,syncStatus:g().syncStatus}),d;let l=Va(),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",Ya(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))},Qa=()=>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,Za,ed,Ms,ks,io,Ls,Rp,td,Cp,nd,lr=y(()=>{"use strict";C();Le();w();Ts();Tn=3e3,Za=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Tn?null:t},ed=0,ks=!1,io=!1,Ls=()=>{if(ks)return!0;let e=Fe();return a(e)?!1:e.value.syncStatus.status==="syncing"},Rp=()=>{let e=ie().autoSyncIntervalMs??1e4,t=Date.now()-ed;return Math.max(0,e-t)},td=()=>{Ms||(Ms=setTimeout(async()=>{if(Ms=void 0,!!nn()){if(Ls()){io=!0;return}io=!1,await Cp()}},Rp()))},Cp=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return i("Cannot auto-sync while peeking");if(!nn())return i("Cannot auto-sync before state is initialized");if(Ls())return io=!0,i("Sync already in progress");ks=!0,ed=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await ar()}finally{ks=!1,io&&td()}},nd=()=>{nn()&&(io=!0,!Ls()&&td())}});var ur,od,rd,sd,ao=y(()=>{"use strict";C();Lt();Le();ue();ur=()=>{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}},od=()=>{let e=Ze(process.cwd());if(a(e))return!1;let t=yt(e.value);return ht(t)},rd=e=>e===!0?"on":e===!1?"off":null,sd=e=>e==="on"?!0:e==="off"?!1:null});var Sp,Ap,Ut,_t,mr,pr,co=y(()=>{"use strict";se();C();ce();w();Sp=e=>e.props.tags??[],Ap=e=>e.props.assignees??[],Ut=e=>Sp(e).map(t=>x.getTag(t)).filter(t=>!!t),_t=e=>Ap(e).map(t=>x.getContributor(t)).filter(t=>!!t),mr=()=>{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",Ut(n))},pr=()=>{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",_t(n))}});var h,on=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 Tp,wp,Mp,kp,Lp,rn,id,gr,fr,ad,Pp,Ps,lo=y(()=>{"use strict";Tp=/^(\d+)(h|d|w|mo|y)$/,wp=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Mp=({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},kp=(e,t=new Date)=>{let n=e.match(Tp);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}},Lp=e=>{let t=e.match(wp);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 Mp({year:l,month:u,day:m,hour:p,minute:v})?new Date(l,u-1,m,p,v):null},rn=e=>{let t=e.trim().toLowerCase();return kp(t)??Lp(t)},id=/^(\d+)(s|m)?$/,gr=e=>{let t=e.trim().toLowerCase().match(id);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},fr=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),o=n.length>0&&id.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:o}},ad=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Pp=[{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}],Ps=(e=Pp)=>{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 Dp,oe,He,ye,Fp,Bp,Fs,Bs,ld,sn,vr,Ds,dd,Op,Up,uo,cd,_p,$p,jp,pe,$t=y(()=>{"use strict";lr();ao();Sn();se();ce();w();Yo();co();on();lo();Dp=["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"},Fp=[oe.EDITOR,oe.VIEW,oe.USERNAME,oe.AUTOSYNC,oe.SYNC_DEBOUNCE_MS,oe.ATTACHMENT_MAX_KB,oe.LOG_LEVEL],Bp=(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[]}},Fs=[String(Tn),"5000","15000","30000","60000"],Bs=["250","500","1000"],ld=["10s","20s","30s","45s"],sn=[h.COFFEE,h.EXIT,h.SYNC,h.HELP,h.EXPORT,h.CONFIG,h.YANK],vr=[h.NEW,h.EDIT,h.DELETE,h.MOVE],Ds=[h.TAG,h.UNTAG,h.ASSIGN,h.UNASSIGN,h.CLOSE_ISSUE,h.RE_OPEN_ISSUE,h.EDIT,h.COMMENT],dd=[h.FILTER,h.PEEK,h.REPLAY],Op={WORKSPACE:[...sn,...vr],BOARD:[...dd,...sn,...vr],SWIMLANE:[...dd,...sn,...vr],TICKET:[...sn,...vr,...Ds],FIELD:[...sn,...Ds],FIELD_LIST:[...sn,...Ds],TEXT:[...sn],COMMENT:[h.EDIT,h.DELETE,h.YANK]},Up=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],uo=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&k(n)),cd=e=>e.parentNodeId===he,_p=({selectedNode:e,breadCrumb:t})=>{let n=Bp(e?.context);return uo({breadCrumb:t,selectedNode:e})?n.includes(He.DESCRIPTION)?n:[...n,He.DESCRIPTION]:n},$p=({selectedNode:e,breadCrumb:t})=>{let n=uo({breadCrumb:t,selectedNode:e});return n?[ye.REF,ye.TITLE,...n.props?.description?.trim()?[ye.DESCRIPTION]:[],...Ut(n).length>0?[ye.TAGS]:[],..._t(n).length>0?[ye.ASSIGNEES]:[]]:e?[ye.REF,ye.TITLE]:[]},jp=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:o}=ur();if(!o)return[h.HELP,h.CONFIG];if(!od())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&&Dp.includes(r),d=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?Op[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&&Ut(l).length>0):u===h.UNASSIGN?!!(l&&_t(l).length>0):u===h.RE_OPEN_ISSUE?!!(l&&cd(l)):u===h.CLOSE_ISSUE?!!(l&&!cd(l)):!0)},pe=(e,{contextNode:t,selectedNode:n,readOnly:o,breadCrumb:r}=g())=>{let s=t.context??"WORKSPACE";return{[h.NONE]:jp({breadCrumb:r,readOnly:o,selectedNode:n}),[h.EXIT]:["confirm"],[h.EXPORT]:[],[h.SYNC]:[],[h.INIT]:[],[h.HELP]:[],[h.PEEK]:[...Ps(),"now","prev","next"],[h.REPLAY]:[...Ps()],[h.EDIT]:_p({selectedNode:n,breadCrumb:r}),[h.YANK]:$p({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),...x.getExistingTags()])],[h.UNTAG]:[...mr()?.value?.map(({name:l})=>l)??[]],[h.UNASSIGN]:[...pr()?.value?.map(({name:l})=>l)??[]],[h.ASSIGN]:x.getExistingAssignees(),[h.NEW]:Up(s),[h.CONFIG]:[...Fp],[h.COFFEE]:["1","3","5","20","custom"]}[e]??[]}});var ud,md=y(()=>{"use strict";ud=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{decodeTime as pd}from"ulid";var gd,an,mo=y(()=>{"use strict";C();gd=e=>{try{return c("Decoded date",new Date(pd(e)))}catch(t){return i("Decoding failed + "+t.message)}},an=e=>{if(!e?.id)return null;try{return pd(e.id)}catch{return null}}});import{accessSync as Wp,copyFileSync as Hp,existsSync as hr,mkdirSync as fd,readdirSync as vd,readFileSync as Kp,renameSync as qp,rmSync as zp,statSync as hd,unlinkSync as Vp,writeFileSync as Gp}from"node:fs";import wn from"node:path";var Os,Be,yr=y(()=>{"use strict";Os=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Be={writeToFile:(e,t)=>{try{let n=wn.dirname(e);hr(n)||fd(n,{recursive:!0});let o=typeof t=="string"?t:JSON.stringify(t,null,2);Gp(e,o,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Kp(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 hr(e)&&hd(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Wp(e),!0}catch{return!1}},mkDir:e=>fd(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=wn.parse(t);for(;;){let o=wn.join(t,e);try{if(hr(o)&&hd(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=vd(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)?vd(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Vp(e)}catch(t){(!Os(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{zp(e,{recursive:!0,force:!0})}catch(t){(!Os(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(wn.dirname(t)),!n?.overwrite&&hr(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{qp(e,t)}catch(o){if(Os(o)&&o.code==="EXDEV"){Hp(e,t),this.rmFile(e);return}throw o}}}});import Yp from"node:path";import{z as Et}from"zod";var Xp,yd,Jp,bd,Us,_s,Qp,Id,xd,Xe,Ed,dn=y(()=>{"use strict";ue();C();yr();Xp={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},yd=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(),Jp="config.json",bd=jn,Us=()=>Yp.join(bd(),Jp),_s=()=>{try{return Be.mkDir(bd()),c(`Ensured ~/${Qe} exists`,null)}catch{return i(`Unable to create ~/${Qe}`)}},Qp=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${Qe}/config.json JSON`)}let n=yd.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(", ")}`)},Id=()=>{let e=_s();if(a(e))return i(e.message);let t=Us(),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}):Qp(n)},xd=e=>{let t=_s();if(a(t))return i(t.message);let n=yd.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`);let o=Us();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=Id();if(a(t))return i("Failed to read existing config");let n={...t.value,...e};return xd(n)},Ed=()=>{let e=Us(),t=_s();if(a(t))return i(`Unable to create ~/${Qe}`);if(!(Be.readFile(e)!==null)){let I=xd(Xp);if(a(I))throw new Error(`Unable to create ~/${Qe}/config.json`)}let o=Id();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,$s,go=y(()=>{"use strict";ut();C();ue();po=500,$s=(e,t)=>`${e}.${t}`});import Zp from"zod";var fo,vo,Nd,js=y(()=>{"use strict";dn();go();te();C();be();Le();w();fo=50,vo=5e3,Nd=()=>{let e=Q().commandMeta.inputString,t=Zp.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 br=y(()=>{"use strict"});import Rd from"chalk";var Z,Ne,Re,Cd=y(()=>{"use strict";mt();De();Z=e=>Rd.dim(e),Ne=e=>Rd.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,I)=>Xo(v)-Xo(I)).slice(0,o).map(v=>Jo(v)).join(" ");return p?`${Z(e)}${p}${Z(n)}`:""}});var jt,Ir=y(()=>{"use strict";jt={None:"none",Invalid:"invalid",Valid:"valid"}});import Td from"chalk";var eg,Sd,re,q,O,Er,Ad,xr,Ws,tg,cn,ng,og,rg,sg,wd,Md=y(()=>{"use strict";lr();ao();md();mo();ut();C();ce();Le();js();go();w();mt();br();co();Cn();Cd();on();Ir();$t();lo();eg=["BOARD","TICKET","SWIMLANE"],Sd=()=>{let e=g().selectedNode;if(!e?.context)return O({message:Z("Missing target context")});if(eg.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:jt.Valid,completionWordList:t}),O=({message:e,completionWordList:t=[]})=>({validity:jt.Invalid,message:e,completionWordList:t}),Er=e=>e.length===0,Ad=(e,t)=>{let n=je(g().breadCrumb,"BOARD");if(a(n))return O({message:Ne("Command is not applicable in this context")});let o=gd(n.value.id);return a(o)?O({message:Ne(`Unable to ${t}: board id is not a valid ULID`)}):ad({date:e,horizonDate:o.value})?null:O({message:Ne(`nothing to ${t} before ${o.value.toISOString().slice(0,16).replace("T"," ")}`)})},xr=e=>` ${Td.hex("#000").bgHex(Te(e))(` ${e} `)} `,Ws=({modifier:e})=>{let t="confirm";return e===t?q(re):O({message:Er(e)?Z("if you are certain, enter ")+Jo(t):"",completionWordList:[t]})},tg=({list:e,hint:t,onValue:n})=>({modifier:o,inputString:r})=>e.includes(o)?r.trim().length<1?O({message:Z(n)}):q():O({message:Er(o)?t:"",completionWordList:[...e]}),cn=({hint:e,onOk:t})=>({modifier:n,inputString:o})=>Er(n)&&Er(o)?O({message:e,completionWordList:[]}):q(t??re),ng=({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=[...ud];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 ")+Td.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=rd(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:Bs,minLengthForHints:0,inputString:t});return O({message:Ne(`provide a size cap in KB (${fo}-${vo}). current: ${o??po} KB.`)+s,completionWordList:Bs})}return q(re)}case oe.SYNC_DEBOUNCE_MS:{let o=ie().autoSyncIntervalMs,r=Za(t);if(!t.trim()||r===null||r<Tn){let s=Re({prefix:" examples: ",wordList:Fs,minLengthForHints:0,inputString:t});return O({message:Ne(`provide duration above ${Tn}ms. current duration: ${o}ms.`)+s,completionWordList:Fs})}return q(re)}default:return O({message:Ne("Unknown config option"),completionWordList:n})}},og=({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})}},rg=({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")})},sg={[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=rn(o);if(!o||!r)return O(n);let s=Ad(r,"peek");return s||q(re)},[h.REPLAY]:e=>{let{dateInput:t,durationInput:n}=fr(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=rn(t);if(!t||!r)return O(o);let s=Ad(r,"replay");return s||(n&&gr(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?ld:[]))},[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=>tg({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]:og,[h.COMMENT]:e=>{let t=cn({hint:Z(`write a comment (max ${4e3} char)...`),onOk:Z(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===jt.Invalid?t:e.inputString.length>4e3?q(Ne("max input exceeded")):t},[h.CONFIG]:ng,[h.YANK]:rg,[h.DELETE]:e=>{let t=Sd();return t.validity==="invalid"?t:Ws(e)},[h.CLOSE_ISSUE]:e=>Ws(e),[h.RE_OPEN_ISSUE]:e=>Ws(e),[h.MOVE]:e=>{let t=Sd();return t.validity==="invalid"?t:cn({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=x.getExistingTags().slice(0,10).map(xr).join("");return cn({hint:n.length?Z("create tag or reuse:")+n+Z(""):Z("create tag ...")})(e)},[h.UNTAG]:e=>{let t=mr();if(a(t))return O({message:Ne("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(xr).slice(0,10);return n.length?cn({hint:Z(" ... ")+n.join("")})(e):O({message:Ne("Issue has no tags"),completionWordList:[]})},[h.ASSIGN]:e=>{let t=x.getExistingAssignees().map(xr).slice(0,10);return cn({hint:Z("assignees... ")+t.join("")})(e)},[h.UNASSIGN]:e=>{let t=pr();if(a(t))return O({message:Ne("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(xr).slice(0,10);return n.length?cn({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))}):cn({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)}},wd=Object.fromEntries(Object.entries(sg).map(([e,t])=>[e,{validate:(n,o,r)=>t({modifier:o,command:n,inputString:r})}]))});var Nr,kd=y(()=>{"use strict";Nr=["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 ig,ag,dg,cg,lg,Ld,Pd,Dd,Fd=y(()=>{"use strict";C();w();kd();ig=3,ag=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"]),dg=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},cg=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=ig&&!ag.has(t)&&!/^\d+$/.test(t)),lg=e=>{let t=new Map;for(let s of dg(e))for(let d of cg(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=Nr.filter(s=>!o.has(s));return[...n,...r]},Ld=Nr,Pd=-1,Dd=()=>{let e=Fe();if(a(e))return Nr;let t=e.value,n=t.eventLog.length;return n!==Pd&&(Ld=lg(t),Pd=n),Ld}});var Bd,Od,Hs=y(()=>{"use strict";pa();$t();on();Md();Fd();w();te();Bd=e=>Object.values(h).includes(e),Od=(e,t)=>{let n=e.command??"",{modifier:o,target:r,inputString:s}=e,{message:d,validity:l,completionWordList:u}=wd[n].validate(n,o,s),m=n!==h.PEEK&&n!==h.REPLAY,p=r==="command"||r==="modifier"?pe(n):m?Dd():[],{mode:v}=g(),I=v===f.COMMAND_LINE?d??"":"",S=[...u,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:I,autoCompletion:t?ma(e,S):{hint:"",hints:[],remainder:"",overlap:0}}}});var Ud,ug,mg,pg,_d=y(()=>{"use strict";Hs();$t();Ud=e=>{let t=e.trimStart(),n=mg(t),o=n[0]??"",r=n[1]??"",s=/\s$/.test(e),d=pg(e),l=Bd(o)?o:null,u=l!==null,m=o!=="",p=l?pe(l)??[]:[],v=l&&p.includes(r)?r:"",I="word";n.length===0||n.length===1&&!s?I="command":(n.length===1&&s||n.length===2&&!s)&&(I="modifier");let S=s?"":d,A=ug(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:I,inputToMatch:S,inputString:A}},ug=(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},mg=e=>e.trim()?e.trim().split(/\s+/):[],pg=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as zE}from"react";var Mn,Ks,kn,gg,$d,gt,ho,qs,zs,jd,Wd,Rr,Hd,H,Kd,qd,zd,Q,Vd,be=y(()=>{"use strict";Hs();_d();C();Ir();Mn=e=>e===Ks||e===":",Ks=" ",kn={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:jt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},gg=new Set,$d=()=>{for(let e of gg)e()},gt=e=>{let n=e(kn),o=Ud(n.value),r=n.cursorPosition===n.value.length;kn={...n,commandMeta:Od(o,r)},$d()},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,$d(),c(e,null)},qs=e=>{gt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},zs=e=>{gt(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}})},jd=()=>{gt(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}})},Wd=()=>{gt(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}})},Rr=e=>{gt(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}})},Hd=()=>{gt(e=>({...e,commandIsPending:!0}))},H=e=>{gt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Kd=({addToHistory:e=!0})=>{gt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},qd=()=>{gt(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}})},zd=()=>{gt(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,Vd=()=>{let[e,...t]=kn.value.split(Ks);return t.join(Ks).trim()}});var M,Yt=y(()=>{"use strict";te();sa();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 Gd,P,Vs=y(()=>{"use strict";w();on();Gd=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 Yd}from"ink";import Xd,{useEffect as Jd,useState as fg}from"react";var Qd,Oe,Ln=y(()=>{"use strict";w();De();Qd={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Oe=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Ue(),o=Qd[n]??Qd.default,[r,s]=fg(0);if(Jd(()=>{s(0)},[o]),Jd(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%o.length)},500);return()=>clearInterval(l)},[e,o]),!e)return Xd.createElement(Yd,null,t);let d=o[r]??o[0]??t;return Xd.createElement(Yd,{color:R.accent,dimColor:r===1},d)}});import{Box as Gs,Text as vg}from"ink";import Cr from"react";var Wt,yo=y(()=>{"use strict";De();Wt=({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,I=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 Cr.createElement(Gs,{flexDirection:"row",height:s,width:"100%"},Cr.createElement(Gs,{flexDirection:"column",flexGrow:1,height:s},I),Cr.createElement(Gs,{flexDirection:"column",width:1,height:A},Array.from({length:A}).map((U,Se)=>Cr.createElement(vg,{key:Se,color:S&&Se>=K&&Se<K+T?R.accent:R.secondary},S?"\u2502":" "))))}});var Pn,Zd,Sr,ec,Dn,tc,Fn=y(()=>{"use strict";w();bs();Pn=(e,t)=>t?e&&oo(e)===t?e:t:e,ec=()=>{let{eventLog:e=[]}=g();if(Sr&&Zd===e)return Sr;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 Zd=e,Sr={latestNames:t,authors:n},Sr},Dn=(e,t)=>{let{contributors:n={}}=g();return n[e]?.tombstoned?t:Pn(t,ec().latestNames.get(e))??t},tc=e=>ec().authors.has(e)});import{Text as hg}from"ink";import yg from"react";var bg,Ig,Bn,Ar=y(()=>{"use strict";Yo();mt();ce();Fn();bg=e=>e.toLowerCase().trim(),Ig=(e,t=Nn)=>{let n=bg(e);return t[n]?t[n]:to(n)},Bn=({id:e,isSelected:t})=>{let n=x.getContributor(e);if(!n)return;let o=Dn(e,n.name);return yg.createElement(hg,{underline:t,color:Ig(o)},"@"+o,tc(e)?"":"\u2197")}});import{Text as xg}from"ink";import Eg from"react";var Tr,Ys=y(()=>{"use strict";ce();De();mt();Tr=({id:e,isSelected:t})=>{let n=x.getTag(e);if(n)return Eg.createElement(xg,{underline:t,backgroundColor:Te(n.name),color:R.secondary}," "+n.name+" ")}});import{useEffect as Ng,useState as Rg}from"react";var Cg,nc,wr,bo,Sg,Ag,On,Mr=y(()=>{"use strict";mt();Cg=80,nc=1400,wr=new Set,bo=null,Sg=e=>(wr.add(e),bo||(bo=setInterval(()=>{for(let t of wr)t()},Cg)),()=>{wr.delete(e),wr.size===0&&bo&&(clearInterval(bo),bo=null)}),Ag=()=>{let e=Date.now()%nc/nc;return e<.5?e*2:(1-e)*2},On=e=>{let[,t]=Rg(0);return Ng(()=>{if(e)return Sg(()=>t(n=>n+1))},[e]),Na(Ag())}});import{Box as Un,Text as kr}from"ink";import Je from"react";var Tg,oc,rc=y(()=>{"use strict";De();yn();En();co();Ar();Ys();Mr();Tg=(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)]},oc=({width:e,ticket:t,isSelected:n,isFlashing:o=!1})=>{let r=On(o),s=e-4,[d,l]=Tg(ze(t.title),s),u=l?null:eo(ze(t.props.description),s)||null,m=Ut(t),p=_t(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(kr,{color:R.primary},d),l&&Je.createElement(kr,{color:R.primary},l),u&&Je.createElement(kr,{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(Tr,{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(kr,{wrap:"truncate",color:R.secondary2,dimColor:!0},tt(t.id))))}});import{Box as ln,Text as Io}from"ink";import Ke from"react";var wg,sc,ic=y(()=>{"use strict";te();ce();Fn();De();mt();Ln();Mr();wg=(e,t)=>e.length>=t?e.slice(0,t)+"...":e,sc=({width:e,ticket:t,isSelected:n,isFlashing:o=!1,index:r,mode:s})=>{let d=On(o),l=(t.props.tags??[]).map(U=>x.getTag(U)).filter(U=>!!U),u=(t.props.assignees??[]).map(U=>x.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),I=l.map(U=>Ke.createElement(ln,{key:U.id,paddingRight:m},Ke.createElement(Io,{color:Te(U.name)},"\u25A0"))),S=u.map(U=>Ke.createElement(ln,{key:U.id,paddingRight:m},Ke.createElement(Io,{color:to(U.name)},"@"+U.name.at(0)))),A=o?d:n?R.accent:s===f.MOVE?R.secondary:R.primary,T=4,_=x.getCommentsByIssue(t.id),z=_.length?String(_.length).length+2+m:0,K=_.length?Ke.createElement(ln,{paddingRight:m},Ke.createElement(Io,{color:R.accent},"[",_.length,"]")):null;return Ke.createElement(ln,{borderBottom:!0,justifyContent:"space-between"},Ke.createElement(ln,null,Ke.createElement(ln,{width:T},n?Ke.createElement(Oe,{isSelected:n}):Ke.createElement(Io,{color:"gray",dimColor:!0},r+1)),Ke.createElement(Io,{wrap:"truncate",color:A},wg(t.title,e-p-v-z-18))),Ke.createElement(ln,null,I,S,K))}});import Mg from"chalk";import{Box as Xs,Text as kg}from"ink";import ft from"react";var Lg,ac,dc=y(()=>{"use strict";se();w();De();Ln();yo();rc();ic();Mr();Lg=({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,I=v?.has(e.id)??!1,S=On(I),A=`${e.title} ${Mg.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=ft.createElement(Xs,{borderStyle:"round",borderColor:R.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1},ft.createElement(Oe,{isSelected:t}),ft.createElement(kg,{bold:!0,color:I?S:t?R.accent:R.primary},A," ",e.readonly?"\u{1F512}":"")),pn=($,V)=>{let gn=s&&d===V;if(!k($))return null;let zt=v?.has($.id)??!1;return r?ft.createElement(sc,{key:$.id,index:V,width:n,ticket:$,isSelected:gn,isFlashing:zt,mode:l}):ft.createElement(oc,{key:$.id,width:K,ticket:$,isSelected:gn,isFlashing:zt})};return ft.createElement(Xs,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?R.accent:R.secondary,paddingRight:1,paddingLeft:1,height:o},Se,ft.createElement(Xs,{padding:r?1:0},p.length>0&&ft.createElement(Wt,{selectedIndex:d,height:U,itemHeight:_},p.map(pn)),z&&ft.createElement(Oe,{isSelected:!0})))},ac=ft.memo(Lg)});var cc,lc,Js=y(()=>{"use strict";Jt();cc=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},lc=(e,t,n)=>xe.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 we,{useEffect as Pg,useMemo as Dg,useRef as Fg}from"react";import{decodeTime as Qs}from"ulid";function mc({ticket:e,width:t,height:n}){let o=Dg(()=>Og(e),[e]),r=Fg([]);Pg(()=>(uc(r.current),r.current=_g(e,o),()=>{uc(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?we.createElement(_n,{flexDirection:"column",width:t,height:n,padding:1},we.createElement(Rt,{color:R.primary},"No attachments yet."),we.createElement(_n,{paddingTop:1},we.createElement(Rt,{color:R.primary},"Attach images from the browser GUI"),we.createElement(Rt,{color:R.accent}," epiq gui "),we.createElement(Rt,{color:R.primary},"by dropping or pasting them."))):we.createElement(_n,{flexDirection:"column",width:t,height:n},we.createElement(_n,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:R.secondary,borderStyle:"single",paddingBottom:1},we.createElement(Rt,{color:R.secondary2},"Attachments (",o.length,") \u2014 enter to open"," ")),we.createElement(Wt,{height:l,itemHeight:2,selectedIndex:s},o.map((m,p)=>{let v=p===s,I=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return we.createElement(_n,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},we.createElement(Rt,{color:R.accent},v?"\u276F ":" "),we.createElement(_n,{paddingLeft:1},we.createElement(Rt,{color:R.secondary2},`#${p+1} `),we.createElement(Rt,{color:v?R.accent:R.primary},I),we.createElement(Rt,{color:R.secondary2}," "+$g(m.bytes)+" "+Rn(Qs(m.id)))))})))}var Bg,Og,uc,Ug,_g,$g,pc=y(()=>{"use strict";We();Qo();se();C();ce();Jt();w();De();Cn();yo();Bg=e=>Ee(e,"attachments"),Og=e=>x.getAttachmentsByIssue(e.id).sort((t,n)=>Qs(t.id)-Qs(n.id)),uc=e=>{for(let t of e)x.deleteNode(t.id)},Ug=(e,t,n)=>xe.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),_g=(e,t)=>{let n=x.getNode(Bg(e.id));if(!n||!_e(n))return[];let o=t.map((r,s)=>Ug(r,s,n.id)).map(r=>x.createNode(r)).filter(ht).map(({value:r})=>r).filter(_e);return t.length>0&&g().selectedIndex<0&&F.navigate({contextNode:n,selectedIndex:0}),o},$g=e=>`${Math.max(1,Math.round(e/1024))} KB`});import{Box as Ht,Text as Ct}from"ink";import Ie,{useEffect as jg,useMemo as Wg,useRef as Hg}from"react";import{decodeTime as Zs}from"ulid";function fc({ticket:e,width:t,height:n}){let o=Wg(()=>qg(e),[e]),r=Hg([]);jg(()=>(gc(r.current),r.current=zg(e,o),()=>{gc(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?Ie.createElement(Ht,{flexDirection:"column",width:t,height:n,padding:1},Ie.createElement(Ct,{color:R.primary},"No comments yet."),Ie.createElement(Ht,{paddingTop:1},Ie.createElement(Ct,{color:R.primary},"Use"),Ie.createElement(Ct,{color:R.accent}," :comment "),Ie.createElement(Ct,{color:R.primary},"to add the first one."))):Ie.createElement(Ht,{flexDirection:"column",width:t,height:n},Ie.createElement(Ht,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:R.secondary,borderStyle:"single",paddingBottom:1},Ie.createElement(Ct,{color:R.secondary2},"Comments (",o.length,") ")),Ie.createElement(Wt,{height:l,itemHeight:4,selectedIndex:s},o.map((m,p)=>{let v=p===s;return Ie.createElement(Ht,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:R.secondary,borderStyle:"single"},Ie.createElement(Ht,{flexDirection:"row",paddingBottom:1},Ie.createElement(Ct,{color:R.accent},v?"\u276F ":" "),Ie.createElement(Ht,{paddingLeft:1},Ie.createElement(Ct,{color:R.secondary2},`#${p+1} `),Ie.createElement(Bn,{id:m.authorId}),Ie.createElement(Ct,{color:R.secondary2}," "+Rn(Zs(m.id))))),Ie.createElement(Ht,{paddingLeft:3,paddingBottom:1},Ie.createElement(Ct,{color:R.primary},Vg(m.md,u))))})))}var Kg,qg,gc,zg,Vg,vc=y(()=>{"use strict";We();Qo();se();C();ce();w();De();Cn();Ar();yo();Js();Kg=e=>Ee(e,"comments"),qg=e=>x.getCommentsByIssue(e.id).sort((t,n)=>Zs(t.id)-Zs(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),gc=e=>{for(let t of e)x.deleteNode(t.id)},zg=(e,t)=>{let n=x.getNode(Kg(e.id));if(!n||!_e(n))return[];let o=t.map((r,s)=>lc(r,s,n.id)).map(x.createNode).filter(ht).map(({value:r})=>r).filter(Zn);return t.length>0&&g().selectedIndex<0&&F.navigate({contextNode:n,selectedIndex:0}),o},Vg=(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 Lr,Text as Gg}from"ink";import St from"react";var hc,yc=y(()=>{"use strict";se();ce();xn();w();De();Ar();Ln();Ys();hc=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:o}=Ue(),{title:r}=t,s=t.parentNodeId?x.getNode(t.parentNodeId):void 0,d=s&&k(s)?r===X.ASSIGNEES?s.props.assignees??[]:r===X.TAGS?s.props.tags??[]:[]:[];return St.createElement(Lr,{alignItems:"center",paddingTop:1},St.createElement(Lr,{minWidth:12},St.createElement(Oe,{isSelected:n}),St.createElement(Gg,{color:n?R.accent:R.secondary2},r,":")),St.createElement(Lr,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=o.id===t.id&&u===e;return St.createElement(Lr,{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(Tr,{isSelected:m,id:l}):null)})))}});import{Box as Pr,Text as ei}from"ink";import At,{useEffect as Yg,useMemo as bc}from"react";var Xg,Ic,ti,xc,Jg,ni,Ec=y(()=>{"use strict";ce();C();Jt();w();De();yn();Ln();yo();In();Xg="\u2029",Ic=(e,t)=>`${e}::inline-line::${t}`,ti=new Map,xc=e=>{let t=ti.get(e)??[];ti.delete(e);for(let n of t)x.deleteNode(n)},Jg=(e,t)=>{xc(e);let n=[];t.forEach((o,r)=>{let s=$e(BigInt(r+1));if(!ht(s))return;let d=x.createNode(xe.text({id:Ic(e,r),name:`Line ${r+1}`,parentNodeId:e,rank:s.value,props:{value:o},readonly:!0,isVirtual:!0}));ht(d)&&n.push(d.value.id)}),ti.set(e,n)},ni=({id:e,label:t,text:n,height:o,selected:r,maxWidth:s})=>{let{selectedIndex:d,contextNode:l}=Ue(),u=bc(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=bc(()=>u.join("\0"),[u]);Yg(()=>(Jg(e,u),()=>{xc(e)}),[e,m]);let p=I=>String(I).replace(/\r?\n/g,""),v=u.map((I,S)=>{let A=l.id===e&&d===S;return At.createElement(Pr,{key:Ic(e,S)},At.createElement(ei,{color:A?R.primary:R.secondary2,dimColor:!A},`${S+1} `.padStart(5,"\xA0")),At.createElement(ei,{backgroundColor:A?"gray":void 0},p(I.length?eo(I,s-10):Xg)))});return At.createElement(Pr,{flexDirection:"column",paddingTop:1},At.createElement(Pr,null,At.createElement(Oe,{isSelected:r}),At.createElement(ei,{color:r?R.accent:R.secondary2},t)),At.createElement(Pr,{flexDirection:"row",borderStyle:"round",borderColor:R.secondary,paddingLeft:1,marginLeft:1},At.createElement(Wt,{scrollByOne:!0,height:o-3,selectedIndex:d,itemHeight:1},v)))}});import{Box as un,Text as oi}from"ink";import Ce,{useMemo as xo}from"react";var Qg,Zg,ef,tf,Nc,Rc=y(()=>{"use strict";se();ce();w();De();Js();Cn();pc();vc();Ln();yc();Ec();Qg=e=>Ee(e,"description"),Zg=e=>Ee(e,"comments"),ef=e=>Ee(e,"history"),tf=e=>Ee(e,"attachments"),Nc=({ticket:e,height:t})=>{let n=xo(()=>cc(e),[e]),{selectedIndex:o,contextNode:r}=Ue(),s=process.stdout.columns||120,d=xo(()=>Qg(e.id),[e.id]),l=xo(()=>Zg(e.id),[e.id]),u=xo(()=>ef(e.id),[e.id]),m=xo(()=>tf(e.id),[e.id]),p=x.getAttachmentsByIssue(e.id).length,v=r.id===e.id,I=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(I){let V=t-3;return Ce.createElement(un,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ce.createElement(fc,{ticket:e,width:s,height:V}))}if(A){let V=t-3;return Ce.createElement(un,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ce.createElement(mc,{ticket:e,width:s,height:V}))}if(S){let $=x.getNode(u),V=$&&_e($)?$.props.value??"":"",zt=t-3;return Ce.createElement(un,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},$?Ce.createElement(ni,{id:$.id,label:"Event log",text:V,selected:!1,maxWidth:s,height:zt}):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(ni,{key:$.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:V,maxWidth:s,height:Se}):Qn($)?Ce.createElement(hc,{key:$.id,parent:$,selected:V,selectedIndex:o}):$.id===l?Ce.createElement(un,{key:$.id,paddingTop:1},Ce.createElement(Oe,{isSelected:V}),Ce.createElement(oi,{backgroundColor:R.secondary,color:V?R.accent:R.primary},` Comments (${n}) \u203A\u203A `)):$.id===m?Ce.createElement(un,{key:$.id,paddingTop:1},Ce.createElement(Oe,{isSelected:V}),Ce.createElement(oi,{backgroundColor:R.secondary,color:V?R.accent:R.primary},` Attachments (${p}) \u203A\u203A `)):$.id===u?Ce.createElement(un,{key:$.id,paddingTop:1},Ce.createElement(Oe,{isSelected:V}),Ce.createElement(oi,{backgroundColor:R.secondary,color:V?R.accent:R.primary}," History \u203A\u203A ")):null;return Ce.createElement(un,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},T.map(($,V)=>pn($,v&&o===V)))}});import{Box as nf}from"ink";import Dr from"react";var of,Cc,Sc=y(()=>{"use strict";se();dc();Rc();of=({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),I=Math.floor(l/3),S=Math.floor(l/Math.max(e.length,1)),A=Math.min(S,I),T=s==="dense";return Dr.createElement(nf,{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 Dr.createElement(ac,{key:_.id,height:d,width:A,swimlane:_,isSelected:Se,isDense:T,isFocused:K,listSelectedIndex:U,mode:r})}),m&&v&&Dr.createElement(Nc,{height:d,ticket:v}))},Cc=Dr.memo(of)});import Ac from"node:fs";import rf from"node:path";import sf from"react";import{render as af}from"ink";import{Writable as df}from"node:stream";var Eo,cf,lf,uf,mf,Tc,wc=y(()=>{"use strict";Sc();se();C();w();ue();Le();Eo=e=>String(e).padStart(2,"0"),cf=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}`},lf=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",uf=async(e,{width:t,height:n})=>{let o="",r=new df({write(d,l,u){let m=mf(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(o=m),u()}});r.columns=t,r.rows=n,r.isTTY=!0;let s=af(e,{stdout:r,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),o},mf=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Tc=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 uf(sf.createElement(Cc,{height:u,width:l,swimlanes:(s[d.id]??[]).filter(z=>z!==void 0&&Gt(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=Mo(process.cwd());if(a(p))return i("Unable to export, epiq root not found");let v=new Date,I=cf(v),S=`board_${lf(d.title)}_${I}.md`,A=wi(p.value);Ac.mkdirSync(A,{recursive:!0});let T=rf.join(A,S),_=`# Board - ${d.title}
47
- Date: ${v.toISOString()}
45
+ `)}`):(Np(),E({hasProjectDefinition:!0}),c("State booted successfully",null))}var ro,Rp,ar=y(()=>{"use strict";He();te();S();tn();w();Nn();Et();wn();ro=Ip();Rp=()=>{let e=Be();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"}});var V,ws=y(()=>{"use strict";S();V=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});var gt,dr,Cp,ed,Ms=y(()=>{"use strict";Qa();ar();nn();ot();te();S();w();cr();ws();Ls();gt=null,dr=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!gt,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),gt)return logger.debug("[sync] syncAndReloadState joining existing promise"),gt;logger.debug("[sync] syncAndReloadState creating promise"),gt=Cp();try{let e=await gt;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}),gt||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),gt=null}},Cp=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=ed();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(gt)return gt;logger.debug("[sync] syncAndReloadState:start");let t=V("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=on(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let o=V("syncEpiqWithRemote",await lr({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}),Xe(`Unable to sync state. ${o.message}`);let{stateBranchRoot:r}=o.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:r});let s=V("loadMergedEvents",Ye(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=ed();if(d)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:d.message,syncStatus:g().syncStatus}),d;let l=Ya(),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=V("bootStateFromEventLog",Mn(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=V("restoreNavigationAnchor",Ja(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))},ed=()=>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 Ln,td,nd,ks,Ps,so,Ds,Sp,od,Ap,rd,ur=y(()=>{"use strict";S();Pe();w();Ms();Ln=3e3,td=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Ln?null:t},nd=0,Ps=!1,so=!1,Ds=()=>{if(Ps)return!0;let e=Be();return a(e)?!1:e.value.syncStatus.status==="syncing"},Sp=()=>{let e=ie().autoSyncIntervalMs??1e4,t=Date.now()-nd;return Math.max(0,e-t)},od=()=>{ks||(ks=setTimeout(async()=>{if(ks=void 0,!!an()){if(Ds()){so=!0;return}so=!1,await Ap()}},Sp()))},Ap=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return i("Cannot auto-sync while peeking");if(!an())return i("Cannot auto-sync before state is initialized");if(Ds())return so=!0,i("Sync already in progress");Ps=!0,nd=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await dr()}finally{Ps=!1,so&&od()}},rd=()=>{an()&&(so=!0,!Ds()&&od())}});var mr,sd,id,ad,io=y(()=>{"use strict";S();Dt();Pe();ue();mr=()=>{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}},sd=()=>{let e=et(process.cwd());if(a(e))return!1;let t=bt(e.value);return yt(t)},id=e=>e===!0?"on":e===!1?"off":null,ad=e=>e==="on"?!0:e==="off"?!1:null});var Tp,wp,jt,Wt,pr,gr,ao=y(()=>{"use strict";se();S();ce();w();Tp=e=>e.props.tags??[],wp=e=>e.props.assignees??[],jt=e=>Tp(e).map(t=>I.getTag(t)).filter(t=>!!t),Wt=e=>wp(e).map(t=>I.getContributor(t)).filter(t=>!!t),pr=()=>{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",jt(n))},gr=()=>{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",Wt(n))}});var v,dn=y(()=>{"use strict";v={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 Mp,Lp,kp,Pp,Dp,cn,dd,fr,vr,cd,Fp,Fs,co=y(()=>{"use strict";Mp=/^(\d+)(h|d|w|mo|y)$/,Lp=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,kp=({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},Pp=(e,t=new Date)=>{let n=e.match(Mp);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}},Dp=e=>{let t=e.match(Lp);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,h=d?Number(d):0;return kp({year:l,month:u,day:m,hour:p,minute:h})?new Date(l,u-1,m,p,h):null},cn=e=>{let t=e.trim().toLowerCase();return Pp(t)??Dp(t)},dd=/^(\d+)(s|m)?$/,fr=e=>{let t=e.trim().toLowerCase().match(dd);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},vr=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),o=n.length>0&&dd.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:o}},cd=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Fp=[{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}],Fs=(e=Fp)=>{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 Bp,oe,Ke,be,Op,Up,Os,Us,md,ln,hr,Bs,ld,_p,$p,lo,ud,jp,Wp,Hp,pe,Ht=y(()=>{"use strict";ur();io();wn();se();ce();w();Xo();ao();dn();co();Bp=["BOARD","TICKET","SWIMLANE","COMMENT"],oe={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},Ke={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},be={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},Op=[oe.EDITOR,oe.VIEW,oe.USERNAME,oe.AUTOSYNC,oe.SYNC_DEBOUNCE_MS,oe.ATTACHMENT_MAX_KB,oe.LOG_LEVEL],Up=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[Ke.TITLE,Ke.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Ke.TITLE];case"COMMENT":return[Ke.COMMENT];default:return[]}},Os=[String(Ln),"5000","15000","30000","60000"],Us=["250","500","1000"],md=["10s","20s","30s","45s"],ln=[v.COFFEE,v.EXIT,v.SYNC,v.HELP,v.EXPORT,v.CONFIG,v.YANK],hr=[v.NEW,v.EDIT,v.DELETE,v.MOVE],Bs=[v.TAG,v.UNTAG,v.ASSIGN,v.UNASSIGN,v.CLOSE_ISSUE,v.RE_OPEN_ISSUE,v.EDIT,v.COMMENT],ld=[v.FILTER,v.PEEK,v.REPLAY],_p={WORKSPACE:[...ln,...hr],BOARD:[...ld,...ln,...hr],SWIMLANE:[...ld,...ln,...hr],TICKET:[...ln,...hr,...Bs],FIELD:[...ln,...Bs],FIELD_LIST:[...ln,...Bs],TEXT:[...ln],COMMENT:[v.EDIT,v.DELETE,v.YANK]},$p=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],lo=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&L(n)),ud=e=>e.parentNodeId===ye,jp=({selectedNode:e,breadCrumb:t})=>{let n=Up(e?.context);return lo({breadCrumb:t,selectedNode:e})?n.includes(Ke.DESCRIPTION)?n:[...n,Ke.DESCRIPTION]:n},Wp=({selectedNode:e,breadCrumb:t})=>{let n=lo({breadCrumb:t,selectedNode:e});return n?[be.REF,be.TITLE,...n.props?.description?.trim()?[be.DESCRIPTION]:[],...jt(n).length>0?[be.TAGS]:[],...Wt(n).length>0?[be.ASSIGNEES]:[]]:e?[be.REF,be.TITLE]:[]},Hp=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:o}=mr();if(!o)return[v.HELP,v.CONFIG];if(!sd())return[v.HELP,v.INIT];if(t)return[v.HELP,v.PEEK,v.REPLAY,v.EXPORT,v.CONFIG,v.YANK];let r=e?.context,s=r&&Bp.includes(r),d=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?_p[u]:[]))],l=lo({breadCrumb:n,selectedNode:e});return d.filter(u=>u===v.MOVE?!1:u===v.YANK?!!(l??e):u===v.EDIT?s||!!l:u===v.DELETE?s:u===v.UNTAG?!!(l&&jt(l).length>0):u===v.UNASSIGN?!!(l&&Wt(l).length>0):u===v.RE_OPEN_ISSUE?!!(l&&ud(l)):u===v.CLOSE_ISSUE?!!(l&&!ud(l)):!0)},pe=(e,{contextNode:t,selectedNode:n,readOnly:o,breadCrumb:r}=g())=>{let s=t.context??"WORKSPACE";return{[v.NONE]:Hp({breadCrumb:r,readOnly:o,selectedNode:n}),[v.EXIT]:["confirm"],[v.EXPORT]:[],[v.SYNC]:[],[v.INIT]:[],[v.HELP]:[],[v.PEEK]:[...Fs(),"now","prev","next"],[v.REPLAY]:[...Fs()],[v.EDIT]:jp({selectedNode:n,breadCrumb:r}),[v.YANK]:Wp({selectedNode:n,breadCrumb:r}),[v.COMMENT]:[],[v.DELETE]:["confirm"],[v.RE_OPEN_ISSUE]:["confirm"],[v.CLOSE_ISSUE]:["confirm"],[v.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[v.FILTER]:["tag","assignee","description","title","ref","clear"],[v.TAG]:[...new Set([...Object.keys(Sn),...I.getExistingTags()])],[v.UNTAG]:[...pr()?.value?.map(({name:l})=>l)??[]],[v.UNASSIGN]:[...gr()?.value?.map(({name:l})=>l)??[]],[v.ASSIGN]:I.getExistingAssignees(),[v.NEW]:$p(s),[v.CONFIG]:[...Op],[v.COFFEE]:["1","3","5","20","custom"]}[e]??[]}});var pd,gd=y(()=>{"use strict";pd=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{decodeTime as fd}from"ulid";var vd,un,uo=y(()=>{"use strict";S();vd=e=>{try{return c("Decoded date",new Date(fd(e)))}catch(t){return i("Decoding failed + "+t.message)}},un=e=>{if(!e?.id)return null;try{return fd(e.id)}catch{return null}}});import{accessSync as Kp,copyFileSync as qp,existsSync as yr,mkdirSync as hd,readdirSync as yd,readFileSync as zp,renameSync as Gp,rmSync as Vp,statSync as bd,unlinkSync as Yp,writeFileSync as Xp}from"node:fs";import kn from"node:path";var _s,Oe,br=y(()=>{"use strict";_s=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Oe={writeToFile:(e,t)=>{try{let n=kn.dirname(e);yr(n)||hd(n,{recursive:!0});let o=typeof t=="string"?t:JSON.stringify(t,null,2);Xp(e,o,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return zp(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Oe.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 yr(e)&&bd(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Kp(e),!0}catch{return!1}},mkDir:e=>hd(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=kn.parse(t);for(;;){let o=kn.join(t,e);try{if(yr(o)&&bd(o).isDirectory())return o}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=kn.dirname(t)}return null},readFirstJSON(e){try{if(!Oe.dirExists(e))return null;let t=yd(e).filter(o=>o.endsWith(".json")).sort()[0];if(!t)return null;let n=kn.join(e,t);return Oe.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Oe.dirExists(e)?yd(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Yp(e)}catch(t){(!_s(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Vp(e,{recursive:!0,force:!0})}catch(t){(!_s(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(kn.dirname(t)),!n?.overwrite&&yr(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Gp(e,t)}catch(o){if(_s(o)&&o.code==="EXDEV"){qp(e,t),this.rmFile(e);return}throw o}}}});import Jp from"node:path";import{z as Rt}from"zod";var Qp,xd,Zp,Id,$s,js,eg,Ed,Nd,Je,Rd,mn=y(()=>{"use strict";ue();S();br();Qp={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},xd=Rt.object({logLevel:Rt.enum(["info","error","debug"]),preferredEditor:Rt.string().optional(),userName:Rt.string().optional(),userId:Rt.string().optional(),autoSync:Rt.boolean().nullable().optional(),autoSyncDebounceMs:Rt.number().optional(),attachmentMaxKb:Rt.number().optional(),viewMode:Rt.enum(["dense","wide"]).optional()}).partial(),Zp="config.json",Id=jn,$s=()=>Jp.join(Id(),Zp),js=()=>{try{return Oe.mkDir(Id()),c(`Ensured ~/${Ze} exists`,null)}catch{return i(`Unable to create ~/${Ze}`)}},eg=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${Ze}/config.json JSON`)}let n=xd.safeParse(t??{});return n.success?c("Parsed config",n.data):i(`Invalid ~/${Ze}/config.json shape: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Ed=()=>{let e=js();if(a(e))return i(e.message);let t=$s(),n=Oe.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):eg(n)},Nd=e=>{let t=js();if(a(t))return i(t.message);let n=xd.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`);let o=$s();try{return Oe.writeToFile(o,JSON.stringify(n.data,null,2)+`
46
+ `),c("Config written",null)}catch{return i(`Unable to write ~/${Ze}/config.json`)}},Je=e=>{let t=Ed();if(a(t))return i("Failed to read existing config");let n={...t.value,...e};return Nd(n)},Rd=()=>{let e=$s(),t=js();if(a(t))return i(`Unable to create ~/${Ze}`);if(!(Oe.readFile(e)!==null)){let b=Nd(Qp);if(a(b))throw new Error(`Unable to create ~/${Ze}/config.json`)}let o=Ed();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:h}=o.value;return!s||!d?i(`User name or ID not configured in ~/${Ze}/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:h??"dense"}))}});var mo,Ws,po=y(()=>{"use strict";mt();S();ue();mo=500,Ws=(e,t)=>`${e}.${t}`});import tg from"zod";var go,fo,Cd,Hs=y(()=>{"use strict";mn();po();te();S();xe();Pe();w();go=50,fo=5e3,Cd=()=>{let e=Q().commandMeta.inputString,t=tg.coerce.number().int().min(go).max(fo).safeParse(e);if(!t.success)return i(`Attachment size cap must be ${go}-${fo} KB (default ${mo})`);let n=Je({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 xr=y(()=>{"use strict"});import Sd from"chalk";var Z,Ce,Se,Ad=y(()=>{"use strict";pt();Fe();Z=e=>Sd.dim(e),Ce=e=>Sd.hex(C.primary)(e),Se=({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(h=>h.startsWith(d))].sort((h,b)=>Jo(h)-Jo(b)).slice(0,o).map(h=>Qo(h)).join(" ");return p?`${Z(e)}${p}${Z(n)}`:""}});var Kt,Ir=y(()=>{"use strict";Kt={None:"none",Invalid:"invalid",Valid:"valid"}});import Md from"chalk";var ng,Td,re,K,O,Nr,wd,Er,Ks,og,pn,rg,sg,ig,ag,Ld,kd=y(()=>{"use strict";ur();io();gd();uo();mt();S();ce();Pe();Hs();po();w();pt();xr();ao();Tn();Ad();dn();Ir();Ht();co();ng=["BOARD","TICKET","SWIMLANE"],Td=()=>{let e=g().selectedNode;if(!e?.context)return O({message:Z("Missing target context")});if(ng.includes(e.context))return K();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===Re(t?.parentNodeId??"","comments"))return K()}return O({message:Z("Command not available in this context")})},re="<ENTER> to confirm",K=(e="",t=[])=>({message:Z(e),validity:Kt.Valid,completionWordList:t}),O=({message:e,completionWordList:t=[]})=>({validity:Kt.Invalid,message:e,completionWordList:t}),Nr=e=>e.length===0,wd=(e,t)=>{let n=We(g().breadCrumb,"BOARD");if(a(n))return O({message:Ce("Command is not applicable in this context")});let o=vd(n.value.id);return a(o)?O({message:Ce(`Unable to ${t}: board id is not a valid ULID`)}):cd({date:e,horizonDate:o.value})?null:O({message:Ce(`nothing to ${t} before ${o.value.toISOString().slice(0,16).replace("T"," ")}`)})},Er=e=>` ${Md.hex("#000").bgHex(we(e))(` ${e} `)} `,Ks=({modifier:e})=>{let t="confirm";return e===t?K(re):O({message:Nr(e)?Z("if you are certain, enter ")+Qo(t):"",completionWordList:[t]})},og=({list:e,hint:t,onValue:n})=>({modifier:o,inputString:r})=>e.includes(o)?r.trim().length<1?O({message:Z(n)}):K():O({message:Nr(o)?t:"",completionWordList:[...e]}),pn=({hint:e,onOk:t})=>({modifier:n,inputString:o})=>Nr(n)&&Nr(o)?O({message:e,completionWordList:[]}):K(t??re),rg=({modifier:e,inputString:t})=>{let n=pe(v.CONFIG);if(!n.includes(e))return O({message:Se({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case oe.EDITOR:{let o=[...pd];return t.trim()?o.includes(t.trim())?K(re):O({message:Se({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o}):O({message:Se({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case oe.VIEW:{let o=["dense","wide"];return o.includes(t.trim())?K(re):O({message:Se({prefix:"view... ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case oe.USERNAME:return t.trim()?K(re):O({message:Ce("Enter a user name. Saved in ")+Md.bgBlack("~/.epiq-global/config.json")});case oe.LOG_LEVEL:{let o=["debug","error","info"],r=t.trim();return o.includes(r)?K(re):O({message:Se({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=id(r);return O({message:Se({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:o,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:o})}return K(re)}case oe.ATTACHMENT_MAX_KB:{let o=ie().attachmentMaxKb,r=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(r)||r<go||r>fo){let s=Se({prefix:" examples: ",wordList:Us,minLengthForHints:0,inputString:t});return O({message:Ce(`provide a size cap in KB (${go}-${fo}). current: ${o??mo} KB.`)+s,completionWordList:Us})}return K(re)}case oe.SYNC_DEBOUNCE_MS:{let o=ie().autoSyncIntervalMs,r=td(t);if(!t.trim()||r===null||r<Ln){let s=Se({prefix:" examples: ",wordList:Os,minLengthForHints:0,inputString:t});return O({message:Ce(`provide duration above ${Ln}ms. current duration: ${o}ms.`)+s,completionWordList:Os})}return K(re)}default:return O({message:Ce("Unknown config option"),completionWordList:n})}},sg=({modifier:e,inputString:t})=>{let n=pe(v.EDIT);if(!n.length)return O({message:Ce("Command not available in this context")});if(!n.includes(e)){let o=Se({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return O({message:o||Ce("Unknown edit option"),completionWordList:n})}switch(e){case Ke.COMMENT:return t.trim()?K(re):O({message:Z("write a comment...")});case Ke.TITLE:return K(re);case Ke.DESCRIPTION:{let{preferredEditor:o}=ie();return o?K(Z("<ENTER> to edit in ")+o):O({message:"No editor selected"})}default:return O({message:Ce("Unknown edit option"),completionWordList:n})}},ig=({modifier:e})=>{let t=pe(v.YANK);return t.length?t.includes(e)?K(re+Z(" and copy to clipboard")):O({message:Se({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):O({message:Ce("Nothing selected to copy from")})},ag={[v.EXPORT]:()=>K(re+Z(", and create export markdown file")),[v.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return K(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=cn(o);if(!o||!r)return O(n);let s=wd(r,"peek");return s||K(re)},[v.REPLAY]:e=>{let{dateInput:t,durationInput:n}=vr(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=cn(t);if(!t||!r)return O(o);let s=wd(r,"replay");return s||(n&&fr(n)===null?O({message:Ce("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):K("<ENTER> to replay board history",n?md:[]))},[v.EXIT]:()=>K(re+Z(" and exit the application")),[v.INIT]:()=>K(re),[v.PALETTE]:()=>K(re),[v.FILTER]:e=>{if(e.modifier==="clear")return K(re);let t=s=>pe(v.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return O({message:Se({wordList:pe(v.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:pe(v.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:Se({prefix:`existing ${e.modifier}s... `,wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r}):K():O({message:Se({prefix:"one of... ",wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r})},[v.NONE]:e=>{let t=pe(v.NONE);return O({message:Se({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[v.NEW]:e=>og({list:pe(v.NEW),hint:Se({wordList:pe(v.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[v.HELP]:()=>K(re),[v.EDIT]:sg,[v.COMMENT]:e=>{let t=pn({hint:Z(`write a comment (max ${4e3} char)...`),onOk:Z(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===Kt.Invalid?t:e.inputString.length>4e3?K(Ce("max input exceeded")):t},[v.CONFIG]:rg,[v.YANK]:ig,[v.DELETE]:e=>{let t=Td();return t.validity==="invalid"?t:Ks(e)},[v.CLOSE_ISSUE]:e=>Ks(e),[v.RE_OPEN_ISSUE]:e=>Ks(e),[v.MOVE]:e=>{let t=Td();return t.validity==="invalid"?t:pn({hint:Se({prefix:"hey hacker! These commands are blocked for you... ",wordList:pe(v.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[v.TAG]:e=>{let n=I.getExistingTags().slice(0,10).map(Er).join("");return pn({hint:n.length?Z("create tag or reuse:")+n+Z(""):Z("create tag ...")})(e)},[v.UNTAG]:e=>{let t=pr();if(a(t))return O({message:Ce("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(Er).slice(0,10);return n.length?pn({hint:Z(" ... ")+n.join("")})(e):O({message:Ce("Issue has no tags"),completionWordList:[]})},[v.ASSIGN]:e=>{let t=I.getExistingAssignees().map(Er).slice(0,10);return pn({hint:Z("assignees... ")+t.join("")})(e)},[v.UNASSIGN]:e=>{let t=gr();if(a(t))return O({message:Ce("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(Er).slice(0,10);return n.length?pn({hint:Z("remove assignee... ")+n.join("")})(e):O({message:Ce("Issue has no assignees"),completionWordList:[]})},[v.SYNC]:()=>K(re),[v.COFFEE]:e=>{let{modifier:t}=e,n=pe(v.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?O({message:Z("enter an amount ... "),completionWordList:n.filter(o=>o.startsWith(t))}):pn({hint:Se({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},Ld=Object.fromEntries(Object.entries(ag).map(([e,t])=>[e,{validate:(n,o,r)=>t({modifier:o,command:n,inputString:r})}]))});var Rr,Pd=y(()=>{"use strict";Rr=["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 dg,cg,lg,ug,mg,Dd,Fd,Bd,Od=y(()=>{"use strict";S();w();Pd();dg=3,cg=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"]),lg=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},ug=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=dg&&!cg.has(t)&&!/^\d+$/.test(t)),mg=e=>{let t=new Map;for(let s of lg(e))for(let d of ug(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=Rr.filter(s=>!o.has(s));return[...n,...r]},Dd=Rr,Fd=-1,Bd=()=>{let e=Be();if(a(e))return Rr;let t=e.value,n=t.eventLog.length;return n!==Fd&&(Dd=mg(t),Fd=n),Dd}});var Ud,_d,qs=y(()=>{"use strict";fa();Ht();dn();kd();Od();w();te();Ud=e=>Object.values(v).includes(e),_d=(e,t)=>{let n=e.command??"",{modifier:o,target:r,inputString:s}=e,{message:d,validity:l,completionWordList:u}=Ld[n].validate(n,o,s),m=n!==v.PEEK&&n!==v.REPLAY,p=r==="command"||r==="modifier"?pe(n):m?Bd():[],{mode:h}=g(),b=h===f.COMMAND_LINE?d??"":"",A=[...u,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:b,autoCompletion:t?ga(e,A):{hint:"",hints:[],remainder:"",overlap:0}}}});var $d,pg,gg,fg,jd=y(()=>{"use strict";qs();Ht();$d=e=>{let t=e.trimStart(),n=gg(t),o=n[0]??"",r=n[1]??"",s=/\s$/.test(e),d=fg(e),l=Ud(o)?o:null,u=l!==null,m=o!=="",p=l?pe(l)??[]:[],h=l&&p.includes(r)?r:"",b="word";n.length===0||n.length===1&&!s?b="command":(n.length===1&&s||n.length===2&&!s)&&(b="modifier");let A=s?"":d,T=pg(t,l,h);return{raw:e,trimmedStart:t,words:n,firstWord:o,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:s,modifier:h,target:b,inputToMatch:A,inputString:T}},pg=(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},gg=e=>e.trim()?e.trim().split(/\s+/):[],fg=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as XE}from"react";var Pn,zs,Dn,vg,Wd,ft,vo,Gs,Vs,Hd,Kd,Cr,qd,H,zd,Gd,Vd,Q,Yd,xe=y(()=>{"use strict";qs();jd();S();Ir();Pn=e=>e===zs||e===":",zs=" ",Dn={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Kt.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},vg=new Set,Wd=()=>{for(let e of vg)e()},ft=e=>{let n=e(Dn),o=$d(n.value),r=n.cursorPosition===n.value.length;Dn={...n,commandMeta:_d(o,r)},Wd()},vo=({message:e,status:t})=>{let n=structuredClone(Dn);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Dn=n,Wd(),c(e,null)},Gs=e=>{ft(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Vs=e=>{ft(t=>{let{value:n,cursorPosition:o}=t,r=o;if(e==="left"){for(;r>0&&Pn(n[r-1]);)r--;for(;r>0&&!Pn(n[r-1]);)r--}else{for(;r<n.length&&!Pn(n[r]);)r++;for(;r<n.length&&Pn(n[r]);)r++}return{...t,cursorPosition:r}})},Hd=()=>{ft(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}})},Kd=()=>{ft(e=>{let{value:t,cursorPosition:n}=e,o=n;for(;o>0&&Pn(t[o-1]);)o--;for(;o>0&&!Pn(t[o-1]);)o--;let r=t.slice(n);return{...e,value:t.slice(0,o)+r,cursorPosition:o,commandIsPending:!1}})},Cr=e=>{ft(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}})},qd=()=>{ft(e=>({...e,commandIsPending:!0}))},H=e=>{ft(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},zd=({addToHistory:e=!0})=>{ft(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Gd=()=>{ft(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}})},Vd=()=>{ft(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=()=>Dn,Yd=()=>{let[e,...t]=Dn.value.split(zs);return t.join(zs).trim()}});var M,Zt=y(()=>{"use strict";te();aa();w();xe();Pe();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 Xd,P,Ys=y(()=>{"use strict";w();dn();Xd=e=>{let{context:t}=g().contextNode;if(!t)return P.None;switch(e){case v.EXIT:return P.Exit;case v.EXPORT:return P.Export;case v.COFFEE:return P.Coffee;case v.INIT:return P.Init;case v.DELETE:return P.Delete;case v.EDIT:return P.Edit;case v.COMMENT:return P.Comment;case v.HELP:return P.ViewHelp;case v.RE_OPEN_ISSUE:return P.ReopenIssue;case v.CLOSE_ISSUE:return P.CloseIssue;case v.TAG:return P.TagTicket;case v.UNTAG:return P.UntagTicket;case v.ASSIGN:return P.AssignUserToTicket;case v.UNASSIGN:return P.UnassignUserFromTicket;case v.NEW:return P.NewItem;case v.FILTER:return P.Filter;case v.MOVE:return P.Move;case v.PEEK:return P.Peek;case v.REPLAY:return P.Replay;case v.CONFIG:return P.Config;case v.YANK:return P.Yank;case v.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 Jd}from"ink";import Qd,{useEffect as Zd,useState as hg}from"react";var ec,Ue,Fn=y(()=>{"use strict";w();Fe();ec={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Ue=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=_e(),o=ec[n]??ec.default,[r,s]=hg(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(Jd,null,t);let d=o[r]??o[0]??t;return Qd.createElement(Jd,{color:C.accent,dimColor:r===1},d)}});import{Box as Xs,Text as yg}from"ink";import Sr from"react";var qt,ho=y(()=>{"use strict";Fe();qt=({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),h=p+l,b=e.slice(p,h),A=e.length>l,T=s,R=A?Math.max(1,Math.floor(l/e.length*T)):T,U=Math.max(0,T-R),q=Math.max(1,e.length-l),W=A?Math.floor(p/q*U):0;return Sr.createElement(Xs,{flexDirection:"row",height:s,width:"100%"},Sr.createElement(Xs,{flexDirection:"column",flexGrow:1,height:s},b),Sr.createElement(Xs,{flexDirection:"column",width:1,height:T},Array.from({length:T}).map((ve,Ee)=>Sr.createElement(yg,{key:Ee,color:A&&Ee>=W&&Ee<W+R?C.accent:C.secondary},A?"\u2502":" "))))}});var Bn,tc,Ar,nc,zt,Tr,gn=y(()=>{"use strict";w();Is();Bn=(e,t)=>t?e&&no(e)===t?e:t:e,nc=()=>{let{eventLog:e=[]}=g();if(Ar&&tc===e)return Ar;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 tc=e,Ar={latestNames:t,authors:n},Ar},zt=(e,t)=>{let{contributors:n={}}=g();return n[e]?.tombstoned?t:Bn(t,nc().latestNames.get(e))??t},Tr=e=>nc().authors.has(e)});import{Text as bg}from"ink";import xg from"react";var Ig,Eg,On,wr=y(()=>{"use strict";Xo();pt();ce();gn();Bt();Ig=e=>e.toLowerCase().trim(),Eg=(e,t=Sn)=>{let n=Ig(e);return t[n]?t[n]:eo(n)},On=({id:e,isSelected:t,maxWidth:n})=>{let o=I.getContributor(e);if(!o)return;let r=zt(e,o.name),s=n===void 0?r:xt(r,n);return xg.createElement(bg,{underline:t,color:Eg(s)},"@"+s,Tr(e)?"":"\u2197")}});import{Text as Ng}from"ink";import Rg from"react";var Mr,Js=y(()=>{"use strict";ce();Fe();pt();Bt();Mr=({id:e,isSelected:t,maxWidth:n})=>{let o=I.getTag(e);if(!o)return;let r=n===void 0?o.name:xt(o.name,n);return Rg.createElement(Ng,{underline:t,backgroundColor:we(o.name),color:C.secondary}," "+r+" ")}});import{useEffect as Cg,useState as Sg}from"react";var Ag,oc,Lr,yo,Tg,wg,Un,kr=y(()=>{"use strict";pt();Ag=80,oc=1400,Lr=new Set,yo=null,Tg=e=>(Lr.add(e),yo||(yo=setInterval(()=>{for(let t of Lr)t()},Ag)),()=>{Lr.delete(e),Lr.size===0&&yo&&(clearInterval(yo),yo=null)}),wg=()=>{let e=Date.now()%oc/oc;return e<.5?e*2:(1-e)*2},Un=e=>{let[,t]=Sg(0);return Cg(()=>{if(e)return Tg(()=>t(n=>n+1))},[e]),Ca(wg())}});import{Box as bo,Text as xo}from"ink";import Qe from"react";var Lg,rc,kg,Pg,sc,ic=y(()=>{"use strict";Fe();Bt();gn();Cn();ao();wr();Js();kr();Lg=(e,t,n)=>{if(e.length<=t)return[e,null];let o=e.lastIndexOf(" ",t),r=o>0?o:t;return[e.slice(0,r),xt(e.slice(r).trim(),n)]},rc=3,kg=2,Pg=(e,t)=>{let n=[],o=0;for(let[r,s]of e.entries()){let d=e.length-r-1,l=d>0?String(d).length+1:0;if(o+s.width+l>t)break;o+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},sc=({width:e,ticket:t,isSelected:n,isFlashing:o=!1})=>{let r=Un(o),s=e-4,d=s-7-1,[l,u]=Lg(Ge(t.title),d,s),m=u?null:xt(Ge(t.props.description),s)||null,p=jt(t),h=Wt(t).map(R=>({...R,name:zt(R.id,R.name)})),b=Math.max(1,s-rc),{shown:A,hidden:T}=Pg([...p.map(R=>({id:R.id,isTag:!0,width:Math.min(R.name.length,b)+rc})),...h.map(R=>({id:R.id,isTag:!1,width:Math.min(R.name.length,b)+kg+(Tr(R.id)?0:1)}))],s);return Qe.createElement(bo,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:o?r:n?C.accent:C.secondary,justifyContent:"space-between"},Qe.createElement(bo,{paddingLeft:1,paddingRight:1,flexDirection:"column"},Qe.createElement(bo,{justifyContent:"space-between"},Qe.createElement(xo,{color:C.primary},l),Qe.createElement(xo,{color:C.secondary2,dimColor:!0},nt(t.id))),u&&Qe.createElement(xo,{color:C.primary},u),m&&Qe.createElement(xo,{color:C.secondary2,dimColor:!0},m)),Qe.createElement(bo,{flexDirection:"row",paddingLeft:1,paddingRight:1},A.map(R=>Qe.createElement(bo,{paddingRight:1,key:R.id},R.isTag?Qe.createElement(Mr,{id:R.id,maxWidth:b}):Qe.createElement(On,{id:R.id,maxWidth:b}))),T>0&&Qe.createElement(xo,{color:C.secondary2,dimColor:!0},"+",T)))}});import{Box as fn,Text as Io}from"ink";import qe from"react";var Dg,ac,dc=y(()=>{"use strict";te();ce();gn();Fe();pt();Fn();kr();Dg=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,ac=({index:e,labelWidth:t,width:n,ticket:o,isSelected:r,isFlashing:s=!1,mode:d})=>{let l=Un(s),u=(o.props.tags??[]).map(G=>I.getTag(G)).filter(G=>!!G),m=(o.props.assignees??[]).map(G=>I.getContributor(G)).map(G=>G&&{...G,name:zt(G.id,G.name)}).filter(G=>!!G),p=1,h=u.length*(1+p),b=m.length*(2+p),A=u.map(G=>qe.createElement(fn,{key:G.id,paddingRight:p},qe.createElement(Io,{color:we(G.name)},"\u25A0"))),T=m.map(G=>qe.createElement(fn,{key:G.id,paddingRight:p},qe.createElement(Io,{color:eo(G.name)},"@"+G.name.at(0)))),R=s?l:r?C.accent:d===f.MOVE?C.secondary:C.primary,U=I.getCommentsByIssue(o.id),q=U.length?String(U.length).length+2+p:0,W=U.length?qe.createElement(fn,{paddingRight:p},qe.createElement(Io,{color:C.accent},"[",U.length,"]")):null,ve=h+b+q,Ee=Math.max(1,n-t-ve-(ve>0?1:0));return qe.createElement(fn,{justifyContent:"space-between"},qe.createElement(fn,null,qe.createElement(fn,{width:t},r?qe.createElement(Ue,{isSelected:!0}):qe.createElement(Io,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),qe.createElement(Io,{wrap:"truncate",color:R},Dg(o.title,Ee))),qe.createElement(fn,null,A,T,W))}});import Fg from"chalk";import{Box as Qs,Text as Bg}from"ink";import vt from"react";var Og,cc,lc=y(()=>{"use strict";se();w();Fe();Fn();ho();ic();dc();kr();Og=({swimlane:e,isSelected:t,width:n,height:o,isDense:r,isFocused:s,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u,replay:m}=_e(),p=u[e.id]??[],h=m?new Set(m.flashNodeIds):null,b=h?.has(e.id)??!1,A=Un(b),T=`${e.title} ${Fg.hex(C.secondary2).dim("("+p.length+")")}`,R=3,U=r?1:5,q=s&&d===-1,W=n-3-(r?1:0)-(q?2:0),ve=Math.max(2,String(p.length).length+1),Ee=o-R-1,G=vt.createElement(Qs,{borderStyle:"round",borderColor:C.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:r?1:0},vt.createElement(Ue,{isSelected:t}),vt.createElement(Bg,{bold:!0,color:b?A:t?C.accent:C.primary},T," ",e.readonly?"\u{1F512}":"")),z=($,yn)=>{let Xt=s&&d===yn;if(!L($))return null;let Jr=h?.has($.id)??!1;return r?vt.createElement(ac,{key:$.id,index:yn,labelWidth:ve,width:W,ticket:$,isSelected:Xt,isFlashing:Jr,mode:l}):vt.createElement(sc,{key:$.id,width:W,ticket:$,isSelected:Xt,isFlashing:Jr})};return vt.createElement(Qs,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?C.accent:C.secondary,paddingRight:0,paddingLeft:r?1:0,height:o},G,vt.createElement(Qs,null,p.length>0&&vt.createElement(qt,{selectedIndex:d,height:Ee,itemHeight:U},p.map(z)),q&&vt.createElement(Ue,{isSelected:!0})))},cc=vt.memo(Og)});var uc,mc,Zs=y(()=>{"use strict";tn();uc=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},mc=(e,t,n)=>Ne.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 St}from"ink";import Me,{useEffect as Ug,useMemo as _g,useRef as $g}from"react";import{decodeTime as ei}from"ulid";function gc({ticket:e,width:t,height:n}){let o=_g(()=>Wg(e),[e]),r=$g([]);Ug(()=>(pc(r.current),r.current=Kg(e,o),()=>{pc(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=_e(),l=Math.max(1,n-4),u=Math.max(12,t-32);return o.length===0?Me.createElement(_n,{flexDirection:"column",width:t,height:n,padding:1},Me.createElement(St,{color:C.primary},"No attachments yet."),Me.createElement(_n,{paddingTop:1},Me.createElement(St,{color:C.primary},"Attach images from the browser GUI"),Me.createElement(St,{color:C.accent}," epiq gui "),Me.createElement(St,{color:C.primary},"by dropping or pasting them."))):Me.createElement(_n,{flexDirection:"column",width:t,height:n},Me.createElement(_n,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:C.secondary,borderStyle:"single",paddingBottom:1},Me.createElement(St,{color:C.secondary2},"Attachments (",o.length,") \u2014 enter to open"," ")),Me.createElement(qt,{height:l,itemHeight:2,selectedIndex:s},o.map((m,p)=>{let h=p===s,b=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return Me.createElement(_n,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},Me.createElement(St,{color:C.accent},h?"\u276F ":" "),Me.createElement(_n,{paddingLeft:1},Me.createElement(St,{color:C.secondary2},`#${p+1} `),Me.createElement(St,{color:h?C.accent:C.primary},b),Me.createElement(St,{color:C.secondary2}," "+qg(m.bytes)+" "+An(ei(m.id)))))})))}var jg,Wg,pc,Hg,Kg,qg,fc=y(()=>{"use strict";He();Zo();se();S();ce();tn();w();Fe();Tn();ho();jg=e=>Re(e,"attachments"),Wg=e=>I.getAttachmentsByIssue(e.id).sort((t,n)=>ei(t.id)-ei(n.id)),pc=e=>{for(let t of e)I.deleteNode(t.id)},Hg=(e,t,n)=>Ne.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),Kg=(e,t)=>{let n=I.getNode(jg(e.id));if(!n||!$e(n))return[];let o=t.map((r,s)=>Hg(r,s,n.id)).map(r=>I.createNode(r)).filter(yt).map(({value:r})=>r).filter($e);return t.length>0&&g().selectedIndex<0&&F.navigate({contextNode:n,selectedIndex:0}),o},qg=e=>`${Math.max(1,Math.round(e/1024))} KB`});import{Box as Gt,Text as At}from"ink";import Ie,{useEffect as zg,useMemo as Gg,useRef as Vg}from"react";import{decodeTime as ti}from"ulid";function hc({ticket:e,width:t,height:n}){let o=Gg(()=>Xg(e),[e]),r=Vg([]);zg(()=>(vc(r.current),r.current=Jg(e,o),()=>{vc(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=_e(),l=Math.max(1,n-4),u=Math.max(20,t-8);return o.length===0?Ie.createElement(Gt,{flexDirection:"column",width:t,height:n,padding:1},Ie.createElement(At,{color:C.primary},"No comments yet."),Ie.createElement(Gt,{paddingTop:1},Ie.createElement(At,{color:C.primary},"Use"),Ie.createElement(At,{color:C.accent}," :comment "),Ie.createElement(At,{color:C.primary},"to add the first one."))):Ie.createElement(Gt,{flexDirection:"column",width:t,height:n},Ie.createElement(Gt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:C.secondary,borderStyle:"single",paddingBottom:1},Ie.createElement(At,{color:C.secondary2},"Comments (",o.length,") ")),Ie.createElement(qt,{height:l,itemHeight:4,selectedIndex:s},o.map((m,p)=>{let h=p===s;return Ie.createElement(Gt,{key:m.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:C.secondary,borderStyle:"single"},Ie.createElement(Gt,{flexDirection:"row",paddingBottom:1},Ie.createElement(At,{color:C.accent},h?"\u276F ":" "),Ie.createElement(Gt,{paddingLeft:1},Ie.createElement(At,{color:C.secondary2},`#${p+1} `),Ie.createElement(On,{id:m.authorId}),Ie.createElement(At,{color:C.secondary2}," "+An(ti(m.id))))),Ie.createElement(Gt,{paddingLeft:3,paddingBottom:1},Ie.createElement(At,{color:C.primary},Qg(m.md,u))))})))}var Yg,Xg,vc,Jg,Qg,yc=y(()=>{"use strict";He();Zo();se();S();ce();w();Fe();Tn();wr();ho();Zs();Yg=e=>Re(e,"comments"),Xg=e=>I.getCommentsByIssue(e.id).sort((t,n)=>ti(t.id)-ti(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),vc=e=>{for(let t of e)I.deleteNode(t.id)},Jg=(e,t)=>{let n=I.getNode(Yg(e.id));if(!n||!$e(n))return[];let o=t.map((r,s)=>mc(r,s,n.id)).map(I.createNode).filter(yt).map(({value:r})=>r).filter(Zn);return t.length>0&&g().selectedIndex<0&&F.navigate({contextNode:n,selectedIndex:0}),o},Qg=(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 Pr,Text as Zg}from"ink";import Tt from"react";var bc,xc=y(()=>{"use strict";se();ce();Rn();w();Fe();wr();Fn();Js();bc=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:o}=_e(),{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 Tt.createElement(Pr,{alignItems:"center",paddingTop:1},Tt.createElement(Pr,{minWidth:12},Tt.createElement(Ue,{isSelected:n}),Tt.createElement(Zg,{color:n?C.accent:C.secondary2},r,":")),Tt.createElement(Pr,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=o.id===t.id&&u===e;return Tt.createElement(Pr,{key:`${r}-${l}`,paddingRight:2,minHeight:1},Tt.createElement(Ue,{isSelected:m}),r===X.ASSIGNEES?Tt.createElement(On,{isSelected:m,id:l}):r===X.TAGS?Tt.createElement(Mr,{isSelected:m,id:l}):null)})))}});import{Box as Dr,Text as ni}from"ink";import wt,{useEffect as ef,useMemo as Ic}from"react";var tf,Ec,oi,Nc,nf,ri,Rc=y(()=>{"use strict";ce();S();tn();w();Fe();Bt();Fn();ho();Nn();tf="\u2029",Ec=(e,t)=>`${e}::inline-line::${t}`,oi=new Map,Nc=e=>{let t=oi.get(e)??[];oi.delete(e);for(let n of t)I.deleteNode(n)},nf=(e,t)=>{Nc(e);let n=[];t.forEach((o,r)=>{let s=je(BigInt(r+1));if(!yt(s))return;let d=I.createNode(Ne.text({id:Ec(e,r),name:`Line ${r+1}`,parentNodeId:e,rank:s.value,props:{value:o},readonly:!0,isVirtual:!0}));yt(d)&&n.push(d.value.id)}),oi.set(e,n)},ri=({id:e,label:t,text:n,height:o,selected:r,maxWidth:s})=>{let{selectedIndex:d,contextNode:l}=_e(),u=Ic(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Ic(()=>u.join("\0"),[u]);ef(()=>(nf(e,u),()=>{Nc(e)}),[e,m]);let p=b=>String(b).replace(/\r?\n/g,""),h=u.map((b,A)=>{let T=l.id===e&&d===A;return wt.createElement(Dr,{key:Ec(e,A)},wt.createElement(ni,{color:T?C.primary:C.secondary2,dimColor:!T},`${A+1} `.padStart(5,"\xA0")),wt.createElement(ni,{backgroundColor:T?"gray":void 0},p(b.length?xt(b,s-10):tf)))});return wt.createElement(Dr,{flexDirection:"column",paddingTop:1},wt.createElement(Dr,null,wt.createElement(Ue,{isSelected:r}),wt.createElement(ni,{color:r?C.accent:C.secondary2},t)),wt.createElement(Dr,{flexDirection:"row",borderStyle:"round",borderColor:C.secondary,paddingLeft:1,marginLeft:1},wt.createElement(qt,{scrollByOne:!0,height:o-3,selectedIndex:d,itemHeight:1},h)))}});import{Box as vn,Text as si}from"ink";import Ae,{useMemo as Eo}from"react";var of,rf,sf,af,Cc,Sc=y(()=>{"use strict";se();ce();w();Fe();Zs();Tn();fc();yc();Fn();xc();Rc();of=e=>Re(e,"description"),rf=e=>Re(e,"comments"),sf=e=>Re(e,"history"),af=e=>Re(e,"attachments"),Cc=({ticket:e,height:t})=>{let n=Eo(()=>uc(e),[e]),{selectedIndex:o,contextNode:r}=_e(),s=process.stdout.columns||120,d=Eo(()=>of(e.id),[e.id]),l=Eo(()=>rf(e.id),[e.id]),u=Eo(()=>sf(e.id),[e.id]),m=Eo(()=>af(e.id),[e.id]),p=I.getAttachmentsByIssue(e.id).length,h=r.id===e.id,b=r.id===l||r.parentNodeId===l,A=r.id===u||r.parentNodeId===u,T=r.id===m||r.parentNodeId===m,R=J(e.id);if(b){let $=t-3;return Ae.createElement(vn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ae.createElement(hc,{ticket:e,width:s,height:$}))}if(T){let $=t-3;return Ae.createElement(vn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ae.createElement(gc,{ticket:e,width:s,height:$}))}if(A){let z=I.getNode(u),$=z&&$e(z)?z.props.value??"":"",Xt=t-3;return Ae.createElement(vn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},z?Ae.createElement(ri,{id:z.id,label:"Event log",text:$,selected:!1,maxWidth:s,height:Xt}):null)}let U=R.reduce((z,$)=>Qn($)||$.id===l||$.id===m||$.id===u?z+1:z,0),q=2,W=3,ve=U,Ee=t-W-ve-q,G=(z,$)=>z.id===d?Ae.createElement(ri,{key:z.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:$,maxWidth:s,height:Ee}):Qn(z)?Ae.createElement(bc,{key:z.id,parent:z,selected:$,selectedIndex:o}):z.id===l?Ae.createElement(vn,{key:z.id,paddingTop:1},Ae.createElement(Ue,{isSelected:$}),Ae.createElement(si,{backgroundColor:C.secondary,color:$?C.accent:C.primary},` Comments (${n}) \u203A\u203A `)):z.id===m?Ae.createElement(vn,{key:z.id,paddingTop:1},Ae.createElement(Ue,{isSelected:$}),Ae.createElement(si,{backgroundColor:C.secondary,color:$?C.accent:C.primary},` Attachments (${p}) \u203A\u203A `)):z.id===u?Ae.createElement(vn,{key:z.id,paddingTop:1},Ae.createElement(Ue,{isSelected:$}),Ae.createElement(si,{backgroundColor:C.secondary,color:$?C.accent:C.primary}," History \u203A\u203A ")):null;return Ae.createElement(vn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},R.map((z,$)=>G(z,h&&o===$)))}});import{Box as df}from"ink";import Fr from"react";var cf,Ac,Tc=y(()=>{"use strict";se();lc();Sc();cf=({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,h=u===D.TICKET?t:o.find(U=>U.context===D.TICKET),b=Math.floor(l/3),A=Math.floor(l/Math.max(e.length,1)),T=Math.min(A,b),R=s==="dense";return Fr.createElement(df,{flexDirection:"row",height:d},p&&e.map((U,q)=>{let W=t.id===U.id,ve=W?n:-1,Ee=t.context===D.BOARD&&n===q;return Fr.createElement(cc,{key:U.id,height:d,width:T,swimlane:U,isSelected:Ee,isDense:R,isFocused:W,listSelectedIndex:ve,mode:r})}),m&&h&&Fr.createElement(Cc,{height:d,ticket:h}))},Ac=Fr.memo(cf)});import wc from"node:fs";import lf from"node:path";import uf from"react";import{render as mf}from"ink";import{Writable as pf}from"node:stream";var No,gf,ff,vf,hf,Mc,Lc=y(()=>{"use strict";Tc();se();S();w();ue();Pe();No=e=>String(e).padStart(2,"0"),gf=e=>{let t=e.getUTCFullYear(),n=No(e.getUTCMonth()+1),o=No(e.getUTCDate()),r=No(e.getUTCHours()),s=No(e.getUTCMinutes()),d=No(e.getUTCSeconds());return`${t}-${n}-${o}_${r}-${s}-${d}`},ff=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",vf=async(e,{width:t,height:n})=>{let o="",r=new pf({write(d,l,u){let m=hf(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(o=m),u()}});r.columns=t,r.rows=n,r.isTTY=!0;let s=mf(e,{stdout:r,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),o},hf=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Mc=async()=>{let{viewMode:e}=ie(),{contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,renderedChildrenIndex:s}=g(),d=o.find(q=>q.context==="BOARD");if(!d)return i("No board found to export");let l=120,u=40,m=await vf(uf.createElement(Ac,{height:u,width:l,swimlanes:(s[d.id]??[]).filter(q=>q!==void 0&&Qt(q)),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=Lo(process.cwd());if(a(p))return i("Unable to export, epiq root not found");let h=new Date,b=gf(h),A=`board_${ff(d.title)}_${b}.md`,T=Li(p.value);wc.mkdirSync(T,{recursive:!0});let R=lf.join(T,A),U=`# Board - ${d.title}
47
+ Date: ${h.toISOString()}
48
48
 
49
49
  \`\`\`text
50
50
  ${m}
51
51
  \`\`\`
52
- `;return Ac.writeFileSync(T,_,"utf8"),c("Exported board layout",T)}});var Fr,ri=y(()=>{"use strict";Fr=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 iS}from"react";var si,pf,gf,$n,ff,Kt,Br=y(()=>{"use strict";C();pf=new Set,gf=()=>{for(let e of pf)e()},$n=()=>{if(!si)throw new Error("Ui state not initialized. Call initUiState() first.");return si},ff=e=>{let t=$n();return si=e(t),gf(),c("UX state updated",null)},Kt=e=>ff(t=>({...t,...e}))});import{spawn as vf}from"node:child_process";function No(e){let t=process.platform,r=vf(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 ii=y(()=>{"use strict"});import{spawn as pS,spawnSync as hf}from"node:child_process";import yf from"node:os";import Mc from"node:path";import{ulid as bf}from"ulid";function kc(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 If(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Lc(){let{preferredEditor:e}=ie(),t=[e?If(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Pc(e){let[t=""]=kc(e);return/(^|\/)code(-insiders)?$/.test(t)}function xf(e,t){let[n="",...o]=kc(e);return{command:n,args:[...o,...t]}}function Ef(e,t){return xf(e,Pc(e)?["--wait",t]:[t])}function Dc(e){let t=Mc.join(yf.tmpdir(),"epiq");Be.mkDir(t);let n=Mc.join(t,bf());Be.writeToFile(n,e??"");let o=Lc();for(let r of o){let{command:s,args:d}=Ef(r,n);if(!s)continue;let l=hf(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 ai=y(()=>{"use strict";C();Le();yr()});import{ulid as di}from"ulid";var Fc,Nf,Rf,Bc=y(()=>{"use strict";ai();en();nt();ut();se();C();xn();ce();w();ue();$t();Fc=async e=>{let{contextNode:t,selectedIndex:n}=g(),o=J(t.id)[n];if(e.modifier===He.DESCRIPTION)return Rf();if(o&&Zn(o))return Nf(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:di(),action:"edit.title",payload:{id:s.id,name:d},...r.value}],l.value)}return i("Unknown edit command")},Nf=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=x.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:di(),action:"edit.issue.comment",payload:{id:u.id,issue:d.id,md:m},...t.value}],v)},Rf=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=Dc(u);if(a(m))return i("Failed to edit field");let p=m.value;return p===u?c("No changes made",null):B([{id:di(),action:"edit.description",payload:{id:d.id,md:p},...e.value}],n)}});import ci from"node:fs";import Cf from"node:path";var Oc,Uc=y(()=>{"use strict";C();fn();Oc=async e=>{let t=Cf.join(e,".gitignore"),n=ci.existsSync(t)?ci.readFileSync(t,"utf8"):"",o=[".epiq/events/",".epiq/log/"],r=n.split(`
52
+ `;return wc.writeFileSync(R,U,"utf8"),c("Exported board layout",R)}});var Br,ii=y(()=>{"use strict";Br=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 pS}from"react";var ai,yf,bf,$n,xf,Vt,Or=y(()=>{"use strict";S();yf=new Set,bf=()=>{for(let e of yf)e()},$n=()=>{if(!ai)throw new Error("Ui state not initialized. Call initUiState() first.");return ai},xf=e=>{let t=$n();return ai=e(t),bf(),c("UX state updated",null)},Vt=e=>xf(t=>({...t,...e}))});import{spawn as If}from"node:child_process";function Ro(e){let t=process.platform,r=If(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 di=y(()=>{"use strict"});import{spawn as xS,spawnSync as Ef}from"node:child_process";import Nf from"node:os";import kc from"node:path";import{ulid as Rf}from"ulid";function Pc(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 Cf(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Dc(){let{preferredEditor:e}=ie(),t=[e?Cf(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Fc(e){let[t=""]=Pc(e);return/(^|\/)code(-insiders)?$/.test(t)}function Sf(e,t){let[n="",...o]=Pc(e);return{command:n,args:[...o,...t]}}function Af(e,t){return Sf(e,Fc(e)?["--wait",t]:[t])}function Bc(e){let t=kc.join(Nf.tmpdir(),"epiq");Oe.mkDir(t);let n=kc.join(t,Rf());Oe.writeToFile(n,e??"");let o=Dc();for(let r of o){let{command:s,args:d}=Af(r,n);if(!s)continue;let l=Ef(s,d,{stdio:"inherit"});if(!l.error&&l.status===0){let u=Oe.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 ci=y(()=>{"use strict";S();Pe();br()});import{ulid as li}from"ulid";var Oc,Tf,wf,Uc=y(()=>{"use strict";ci();rn();ot();mt();se();S();Rn();ce();w();ue();Ht();Oc=async e=>{let{contextNode:t,selectedIndex:n}=g(),o=J(t.id)[n];if(e.modifier===Ke.DESCRIPTION)return wf();if(o&&Zn(o))return Tf(e);if(e.modifier===Ke.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 it();return a(l)?l:B([{id:li(),action:"edit.title",payload:{id:s.id,name:d},...r.value}],l.value)}return i("Unknown edit command")},Tf=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 it();if(a(p))return p;let h=p.value;return B([{id:li(),action:"edit.issue.comment",payload:{id:u.id,issue:d.id,md:m},...t.value}],h)},wf=async()=>{let e=ae();if(a(e))return i("Unable to resolve user ID");let t=await it();if(a(t))return t;let n=t.value,{breadCrumb:o,selectedNode:r}=g(),s=We([...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(h=>h.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=Bc(u);if(a(m))return i("Failed to edit field");let p=m.value;return p===u?c("No changes made",null):B([{id:li(),action:"edit.description",payload:{id:d.id,md:p},...e.value}],n)}});import ui from"node:fs";import Mf from"node:path";var _c,$c=y(()=>{"use strict";S();bn();_c=async e=>{let t=Mf.join(e,".gitignore"),n=ui.existsSync(t)?ui.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
- `,ci.writeFileSync(t,n,"utf8"),ve.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)}});import Sf from"node:fs";import _c from"node:path";var Af,ee,$c,jc=y(()=>{"use strict";Uc();Po();at();Pt();Ko();We();ao();ir();It();nt();te();C();Lt();be();Le();w();ue();Af=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}`),$c=async()=>{H("");let e=Lo(),t=await it(process.cwd());if(a(t))return ee(1,t.message);let n=t.value,o=await Bo(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 Af(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(ts(n))return ee(4,"Epiq project already initialized");let s=ur();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 Uo({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 ms({repoRoot:n,stateBranchName:m});if(a(v))return ee(6,v.message);let I=jo();if(a(I))return ee(7,I.message);let S=_c.join($o(),e.projectId),A=await Xn({repoRoot:n,stateBranchRoot:S,stateBranchName:m});if(a(A))return ee(8,A.message);let T=_c.join(S,".epiq");Sf.mkdirSync(T,{recursive:!0});let _=Ja({userId:u,userName:l});if(a(_))return ee(9,_.message);for(let Jr of _.value){let Ti=or({event:Jr,rootDir:S});if(a(Ti))return ee(9,Ti.message)}let z=await Ho({stateBranchRoot:S,eventFileName:Zt({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 Oc(n);if(a(U))return ee(11,U.message);let Se=Li({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 zt=await Jn({repoRoot:n,stateBranchRoot:S});a(zt)&&(V+=` Warn: [init:15] ${zt.message}`);let Si=bt(_.value).filter(a);if(Si.length>0)return ee(16,Si.map(Jr=>Jr.message).join(`
58
- `));let Xr=Fe();if(a(Xr))return ee(16,Xr.message);let{rootNodeId:Tu,nodes:wu}=Xr.value,Ai=wu[Tu];return Ai?(F.navigate({contextNode:Ai,selectedIndex:0}),E({hasProjectDefinition:!0,mode:f.DEFAULT}),c(V,null)):ee(16,"Unable to resolve initialized root node")}});import{ulid as Tf}from"ulid";function ui(e){let t=Hc();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=Kc({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:qc(u.value)}function mi(e){let t=Hc();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=Kc({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:qc(d.value)}var Wc,qt,Ro,Hc,li,Kc,qc,pi=y(()=>{"use strict";It();nt();C();lt();w();Wc=null,qt=()=>structuredClone(Wc),Ro=e=>{Wc=e},Hc=()=>{let{contextNode:e,selectedIndex:t}=g(),o=ne(e.id)[t];return o?c("Resolved selected child",o):i("Target node not found")},li=({id:e,parentId:t,position:n={at:"end"}})=>{let o=ne(t).filter(r=>r.id!==e);return rr(o,n)},Kc=({id:e,parentId:t,position:n={at:"end"}})=>{let o=ae();if(a(o))return i("Unable to resolve user ID");let r=li({parentId:t,id:e,position:n});return a(r)?r:c("Created pending move state",{id:Tf(),...o.value,action:"move.node",payload:{id:e,parent:t,rank:r.value.rank}})},qc=e=>{Ro(e);let t=Bt(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as wf}from"ulid";var zc,Or,Vc,Gc=y(()=>{"use strict";We();pi();en();nt();te();C();lt();be();w();ue();zc=()=>{let e=qt();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))},Or=(e,t="Moved preview")=>{if(a(e))return e;let n=zc();return a(n)?n:(E({mode:f.MOVE}),c(t,null))},Vc=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=li({parentId:r.parentNodeId,id:r.id,position:m});return a(p)?p:(Ro({id:wf(),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 Or(mi(1));if(t==="previous")return Or(mi(-1));if(t==="to-next")return Or(ui(1));if(t==="to-previous")return Or(ui(-1));if(t==="confirm"){let s=qt();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=zc();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 Mf,ulid as kf}from"ulid";var Lf,Ur,gi=y(()=>{"use strict";C();Lf=Mf(),Ur=({name:e,parent:t,rank:n,user:{userId:o,userName:r}})=>{let s=Lf();return c("Created issue events",[{id:kf(),userId:o,userName:r,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as _r}from"ulid";var Yc,Xc=y(()=>{"use strict";We();gi();en();nt();ut();C();ce();lt();w();ue();Yc=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=x.getNode(p.value[0].result.id);if(!v)return i("Created node not found");if(!v.parentNodeId)return p;let I=x.getNode(v.parentNodeId);return I?(F.navigate({contextNode:I,selectedIndex:x.getSiblings(v.parentNodeId).findIndex(({id:S})=>S===v.id)}),p):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=x.getNode(m);if(!p)return i("Workspace not found");let v=tn(p.id,n.value,r);return a(v)?v:u({id:_r(),action:"add.board",payload:{id:_r(),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=tn(m.value.id,n.value,r);return a(p)?p:u({id:_r(),action:"add.swimlane",payload:{id:_r(),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=tn(p.id,n.value,r);if(a(v))return v;let I=Ur({name:t.inputString,parent:p.id,rank:v.value,user:n.value});if(a(I))return I;let S=I.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:x.getSiblings(p.id).findIndex(({id:K})=>K===z)}),c("Issue created",null)):i("Unable to determine ticket id")}return c("Success",null)}});var $r,fi=y(()=>{"use strict";We();Qt();It();C();w();$r=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:o})=>{let r=g(),s=Cs(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(I=>I.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 Pf,Df,Ff,jr,Wr,mn,Jc,Bf,Qc,vi=y(()=>{"use strict";mo();Zo();It();te();C();w();Pf=20,Df=16,Ff=150,jr=null,Wr=null,mn=()=>{jr!==null&&(clearInterval(jr),jr=null),Wr!==null&&(clearTimeout(Wr),Wr=null)},Jc=()=>{mn(),E({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Bf=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)},Qc=({events:e,startTime:t,durationMs:n})=>{mn();let o=e.length,r=e.map(v=>an(v)??t),s=r[o-1]??Date.now(),d=Bf(r),l=Math.max(1,Math.round(n*Pf/1e3)),u=Math.max(Math.round(n/l),Df),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:[]}}),jr=setInterval(()=>{m++;let v=m/l,I=[],S;for(;p<o&&d[p]<=v;){let T=e[p],_=Bt(T);if(a(_)){Jc();return}I.push(...ys(T)),S=T,p++}if(p>=o||m>=l){for(;p<o;p++){let _=Bt(e[p]);if(a(_))break}let T=g().replay;E({unappliedEvents:[],replay:T&&{...T,progress:1,appliedCount:o}}),mn(),Wr=setTimeout(Jc,Ff);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?an(S)??A?.currentTime??t:A?.currentTime??t,currentLabel:S?Aa(S):A?.currentLabel??"",flashNodeIds:S?[...new Set(I)]:A?.flashNodeIds??[]}})},u)}});var Zc,el=y(()=>{"use strict";at();mo();Qt();It();te();ut();C();be();w();lo();fi();vi();Zc=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=ke({repoRoot:t.value});if(a(n))return n;let{modifier:o,inputString:r}=Q().commandMeta;if(mn(),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=an(l);if(u===null)return i("No previous event to peek");s=u}else if(o==="next"){let l=g().unappliedEvents.at(0),u=an(l);if(u===null)return i("No next event to peek");s=u+1}else{let l=rn(o||r.trim());if(!l)return i("Invalid peek date");s=l.getTime()}let d=$r({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 tl,nl=y(()=>{"use strict";at();ut();C();be();w();lo();fi();vi();tl=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=ke({repoRoot:t.value});if(a(n))return n;let{modifier:o,inputString:r}=Q().commandMeta,{dateInput:s,durationInput:d}=fr(o,r);if(mn(),g().syncStatus.status==="syncing")return i("Cannot replay while syncing, try again in a moment");let l=rn(s);if(!l)return i("Invalid replay date");let u=d?gr(d):15e3;if(u===null)return i("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=g(),v=$r({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(v))return v;let{unappliedEvents:I}=v.value;return I.length===0?(Tt(),E(p),c("Nothing to replay from that point",!0)):(Qc({events:I,startTime:m,durationMs:u}),c("Replaying board history",!0))}});import Uf from"zod";var ol,rl=y(()=>{"use strict";dn();te();C();be();Le();w();ol=()=>{let e=Q().commandMeta.inputString,t=Uf.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 sl,il=y(()=>{"use strict";ao();dn();te();C();be();Le();w();sl=()=>{let e=Q().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=sd(e),n=Xe({autoSync:t});return a(n)?n:(Ve({autoSync:t}),E({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var al,dl=y(()=>{"use strict";dn();te();C();be();Le();w();al=()=>{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 _f}from"node:child_process";var $f,cl,ll=y(()=>{"use strict";C();$f=()=>{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"]}}},cl=async e=>new Promise(t=>{let{command:n,args:o}=$f();try{let r=_f(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,ul,ml=y(()=>{"use strict";C();w();ll();En();co();$t();Co=async(e,t)=>{if(!e.trim())return i(`Nothing to copy: ${t} is empty`);let n=await cl(e);return a(n)?n:c(`Copied ${t} to clipboard`,null)},ul=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=Ut(o).map(({name:d})=>d);return Co(s.join(", "),"tags")}case ye.ASSIGNEES:{if(!o)return i("No issue in scope");let s=_t(o).map(({name:d})=>d);return Co(s.join(", "),"assignees")}default:return i("Yank one of: ref, title, description, tags, assignees")}}});var pl,gl=y(()=>{"use strict";Ts();te();C();be();w();pl=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 ar();return a(t)?(E({syncStatus:{msg:t.message,status:"failed"}}),t):(E({mode:f.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as Me}from"ulid";var jf,fl,vl,wt,hl,yl=y(()=>{"use strict";wc();We();dn();en();nt();ri();Sn();te();ut();se();C();ce();lt();be();Le();w();Br();ue();Fn();ii();on();Vs();$t();br();Bc();jc();Gc();Xc();el();nl();rl();js();il();dl();ml();gl();jf=e=>e.action==="add.issue.comment",fl=e=>Object.values(g().tags).find(t=>t.name===e),vl=()=>{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)},hl=[{systemOnly:!0,intent:P.Move,description:"Internal move-state command",mode:f.COMMAND_LINE,action:Vc},{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=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(jf).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):B([{id:Me(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],r.value):i("Unable to resolve comment")}return B([{id:Me(),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 Kt({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 wt();if(a(s))return s;let d=s.value,l=Ot(r.id,o.id,{at:"end"},e.value,d);if(a(l))return l;let u=B([{id:Me(),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):Xt(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=Fr(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=Ot(u.id,s.id,{at:"end"},e.value,p);if(a(v))return v;let I=B([{id:Me(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:v.value},...e.value}],p);return a(I)?I: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:$c},{intent:P.NewItem,description:"Create a new board, swimlane, or issue",mode:f.COMMAND_LINE,action:Yc,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=Vd();if(!r)return i("Provide a title");let s=await wt();return a(s)?s:B([{id:Me(),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=fl(o);if(!r)return i(`Tag "${o}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid untag target");let d=Xt(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 wt();return a(m)?m:B([{id:Me(),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=Xt(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 wt();if(a(l))return l;let u=fl(o),m=u?.id??Me();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):B([...u?[]:[{id:Me(),action:"create.tag",payload:{id:m,name:o},...e.value}],{id:Me(),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=Xt(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 wt();if(a(v))return v;let I=vl(),S=!r&&s.toLowerCase()==="me",A,T;if(S)A=e.value.userId,T=I.find(K=>K.id===A)?.name??e.value.userName;else{let K=I.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??Me(),T=U?.name??s}if((p.props.assignees??[]).includes(A))return i("Assignee already assigned");let z=!!g().contributors[A];return B([...z?[]:[{id:Me(),action:"create.contributor",payload:{id:A,name:T},...e.value}],{id:Me(),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=Xt(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(I=>I===e.value.userId):vl().filter(I=>I.name===o&&l.includes(I.id)).map(I=>I.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:Me(),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):Xt(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 wt();return a(p)?p:B([{id:Me(),action:"add.issue.comment",payload:{id:Me(),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:pl},{intent:P.Peek,description:"View board state at another point in time",mode:f.COMMAND_LINE,action:Zc},{intent:P.Replay,description:"Replay board history forward from a point in time",mode:f.COMMAND_LINE,action:tl},{intent:P.Export,description:"Export the current board layout to markdown",mode:f.COMMAND_LINE,action:async()=>{let e=await Tc();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)=>Fc(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)=>ul(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??Me();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 sl();case oe.LOG_LEVEL:return al();case oe.SYNC_DEBOUNCE_MS:return ol();case oe.ATTACHMENT_MAX_KB:return Nd();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 Wf,vt,hi=y(()=>{"use strict";lr();Ir();Vs();yl();C();be();Le();w();Wf=new Set(["peek","replay","filter","view-help","yank"]),vt=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===jt.Invalid)return i("Invalid command");let s=Gd(t);Hd();let{readOnly:d}=g();if(d&&!Wf.has(s))return ho({status:kt.Fail,message:"Command not available in readonly state",value:null});let l=hl.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return ho({status:kt.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:kt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?ho(u):(Kd({addToHistory:!e}),l.onSuccess?.(),ie().autoSync&&nd(),u)}});var Hr,Kr,bl,Il=y(()=>{"use strict";C();te();w();Yt();hi();pi();be();Hr=[{intent:M.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:f.COMMAND_LINE}),H("move cancel"),vt({isForceExecutedBySystem:!0}))},{intent:M.InitMove,mode:f.DEFAULT,description:"[m] move (init/confirm)",action:()=>(E({mode:f.COMMAND_LINE}),H("move start"),vt({isForceExecutedBySystem:!0}))},{intent:M.ConfirmMove,mode:f.MOVE,action:()=>(E({mode:f.COMMAND_LINE}),H("move confirm"),vt({isForceExecutedBySystem:!0}))}],Kr=[{intent:M.MovePreviousItem,mode:f.MOVE,action:()=>qt()?(E({mode:f.COMMAND_LINE}),H("move previous"),vt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:M.MoveNextItem,mode:f.MOVE,action:()=>qt()?(E({mode:f.COMMAND_LINE}),H("move next"),vt({isForceExecutedBySystem:!0})):i("No pending move")}],bl=[{intent:M.MoveToNextContainer,mode:f.MOVE,action:()=>qt()?(E({mode:f.COMMAND_LINE}),H("move to-next"),vt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:M.MoveToPreviousContainer,mode:f.MOVE,action:()=>qt()?(E({mode:f.COMMAND_LINE}),H("move to-previous"),vt({isForceExecutedBySystem:!0})):i("No pending move")}]});var xl,El=y(()=>{"use strict";se();Il();xl={[D.WORKSPACE]:[...Hr,...Kr],[D.BOARD]:[...Hr,...Kr],[D.SWIMLANE]:[...Hr,...Kr,...bl],[D.TICKET]:[],[D.FIELD]:[],[D.FIELD_LIST]:[],[D.TEXT]:[],[D.COMMENT]:[]}});import Hf from"node:fs";import Kf from"node:path";var Nl,Rl=y(()=>{"use strict";at();go();C();ue();ii();Nl=e=>{let t=Ze(process.cwd());if(a(t))return i("Unable to resolve project root");let n=ke({repoRoot:t.value});if(a(n))return i(n.message);let o=$s(e.hash,e.ext),r=Kf.join(es(n.value),o);return Hf.existsSync(r)?(No(r),c(`Opened ${e.name}`,null)):i("Attachment file not found \u2014 run :sync to fetch it")}});var Cl,Sl,Al=y(()=>{"use strict";te();C();be();w();Br();Yt();We();Cl=()=>{H("");let{pendingNavTarget:e}=$n();E({mode:f.DEFAULT}),e&&F.navigate(e),Kt({pendingNavTarget:void 0})},Sl=[{intent:M.ExitCommandLine,mode:f.HELP,action:()=>(Cl(),c("Exiting help",null))},{intent:M.Exit,mode:f.HELP,action:()=>(Cl(),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 qf,Tl,wl,Ml=y(()=>{"use strict";te();se();C();be();w();Br();Yt();We();qf=e=>{E({mode:f.COMMAND_LINE});let{pendingNavTarget:t}=$n();t&&F.navigate(t),Kt({pendingNavTarget:void 0}),H(`${e} `)},Tl=()=>{H("");let{pendingNavTarget:e}=$n();e&&F.navigate(e),Kt({pendingNavTarget:void 0}),E({mode:f.DEFAULT})},wl=[{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 Kt({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||!ra(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?(qf(t),c("Selected command",t)):c("No command selected",null)}},{intent:M.ExitCommandLine,mode:f.PALETTE,action:()=>(Tl(),c("Exiting palette",null))},{intent:M.Exit,mode:f.PALETTE,action:()=>(Tl(),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 kl,Ll=y(()=>{"use strict";on();$t();te();C();xn();ce();lt();be();w();Rl();Yt();Al();Ml();We();kl=[...Sl,...wl,{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?x.getAttachment(e.id):void 0;if(o)return Nl(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 zf,Vf,Pl,Dl=y(()=>{"use strict";be();zf=500,Vf=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Pl=e=>{let t=Vf(e);t&&Rr(n=>(n+t).slice(0,zf))}});var Gf,Yf,Fl,Bl=y(()=>{"use strict";Dl();te();C();be();w();Yt();hi();Gf=[f.COMMAND_LINE,f.PALETTE],Yf=e=>[{intent:M.MoveCursorLeft,mode:e,action:()=>(qs(-1),c("Moving cursor left",null))},{intent:M.MoveCursorRight,mode:e,action:()=>(qs(1),c("Moving cursor right",null))},{intent:M.MoveCursorLeftOfWord,mode:e,action:()=>(zs("left"),c("Moving cursor left of word",null))},{intent:M.MoveCursorRightOfWord,mode:e,action:()=>(zs("right"),c("Moving cursor right of word",null))},{intent:M.AutoCompleteCommand,mode:e,action:()=>(Rr((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})=>(Pl(n??""),c("Capturing input",null))},{intent:M.EraseInput,mode:e,action:()=>(jd(),c("Erasing input",null))},{intent:M.EraseInputWord,mode:e,action:()=>(Wd(),c("Erasing input word",null))}],Fl=[{intent:M.Confirm,mode:f.COMMAND_LINE,action:()=>(vt(),c("Executing command",null))},{intent:M.ViewHelp,mode:f.DEFAULT,action:()=>(E({mode:f.HELP}),c("Viewing help",null))},...Gf.flatMap(Yf),{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:()=>(qd(),c("Getting last command from history",null))},{intent:M.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(zd(),c("Getting next command from history",null))}]});import _l from"chalk";var qr,Ol,Ul,yi,$l=y(()=>{"use strict";te();se();De();qr=_l.dim.hex(R.secondary2)(": for command line"),Ol="q to exit",Ul=`${_l.hex(R.accent)("m")} to confirm`,yi={[D.WORKSPACE]:[qr],[D.BOARD]:[qr],[D.BOARD+f.COMMAND_LINE]:[qr],[D.SWIMLANE]:[qr],[D.TICKET+f.HELP]:[Ol],[D.SWIMLANE+f.HELP]:[Ol],[D.TICKET]:[],[D.FIELD]:[],[D.SWIMLANE+f.MOVE]:[Ul],[D.TICKET+f.MOVE]:[Ul]}});var So,Xf,Jf,jl,Wl=y(()=>{"use strict";w();Fn();En();So=e=>e.trim().toLocaleLowerCase(),Xf=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},Jf=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)},jl=(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 Xf(e).map(So).some(r=>r.includes(n));case"assignee":return Jf(e).map(So).some(r=>r.includes(n));case"ref":return ha(e.id,t.value);default:return!0}}});function Hl(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 Kl=y(()=>{"use strict";C()});var ql,zl=y(()=>{"use strict";ql=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 Qf}from"react";function Ei(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=Hl(t,r,o);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,v=yi[p+n]??yi[p]??[],I=[...kl,...xl[p]??[],...Fl],S=ql(I),A=ev(r,s),T=A[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:v,availableActions:I,actionIndex:S,selectedNode:T,renderedChildrenIndex:A})}function no(e){bi=e;let t=Ze(process.cwd()),n=!1;if(!a(t)){let s=yt(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=Ei(o);return a(r)?r:(Mt=r.value,xi(),c("State initialized",null))}function me(e){let t=g(),n=e(t);if(Ao)return zr=n,Mt={...t,...n},c("State updated",null);let o=Ei(n);return a(o)?i(o.message??"Unable to update state"):(Mt=o.value,xi(),c("State updated",null))}function Pa(e){if(Ao)return c("Joined batch",e());Ao=!0,zr=null;let t=()=>{let n=zr;if(Ao=!1,zr=null,n===null)return null;let o=Ei(n);return a(o)?i(o.message??"Unable to update state"):(Mt=o.value,xi(),c("State updated",null))};try{let n=e(),o=t();return o&&a(o)?i(o.message):c("State updated",n)}finally{Ao&&t()}}var Mt,bi,Ii,xi,Zf,g,Fe,Ao,zr,E,Ue,ev,J,Tt,nn,w=y(()=>{"use strict";El();Ll();Bl();$l();Lt();te();se();C();ue();Wl();Kl();zl();Ii=new Set,xi=()=>{for(let e of Ii)e()},Zf=e=>(Ii.add(e),()=>Ii.delete(e));g=()=>{if(!Mt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Mt},Fe=()=>Mt?c("Retrieved state",Mt):i("State not initialized. Call initWorkspaceState() first.");Ao=!1,zr=null;E=e=>me(t=>({...t,...e})),Ue=()=>Qf(Zf,g,g),ev=(e,t)=>{let n={};for(let o of Object.values(e))k(o)&&t.length>0&&!t.every(r=>jl(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=()=>bi?no(bi):i("Cannot reset state: no initial workspace found"),nn=()=>Mt!==void 0});var Ni,Vr,Gr,Ri,Ye,dr=y(()=>{"use strict";oa();C();w();Ni=e=>{nn()&&(E({syncStatus:e}),na({type:"sync-status",payload:e}))},Vr=(e="Syncing...")=>{Ni({status:"syncing",msg:e})},Gr=(e="Synced")=>{Ni({status:"synced",msg:e})},Ri=e=>{Ni({status:"failed",msg:e})},Ye=e=>(Ri(e),i(e))});import{decodeTime as dL}from"ulid";var Vl=y(()=>{"use strict";C()});var tv,nv,cr,ws=y(()=>{"use strict";C();dr();As();Do();at();Pt();Ko();Vl();tv=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",ke({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 Qi(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 ta({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 Bo(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",Yi(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}))},nv=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 Ho({stateBranchRoot:t,eventFileName:n}));if(a(o))return i(o.message);let r=G("stageStateBranchMediaFiles",await Zi({stateBranchRoot:t}));if(a(r))return i(r.message);let s=G("hasStagedChanges(after stage)",await Wi(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 ea({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}))},cr=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");Vr();let n=G("ensureSyncReady",await tv({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 Hi(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 I=v.value;logger.debug("[sync] resolved state branch",{stateBranch:I,stateBranchRoot:r});let S=G("commitOwnEventFileToStateBranch",await nv({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 cs({cwd:r,branch:I}));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)&&ji(T.message)){let _=G("pullBranchRebaseIfPresent(retry)",await cs({cwd:r,branch:I}));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 Gr(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 Gl=y(()=>{"use strict"});var qL,Yl,Ci=y(()=>{"use strict";at();Pt();ai();mo();Zo();mt();Qt();It();Gl();C();Lt();yr();ue();w();qL=Promise.resolve(),Yl=(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;if(!u)continue;d.action==="add.board"&&o.add(u);let m=l.parent??l.issue;m&&n.set(u,m),(u===t||r(u)===t)&&s.push(d)}return s}});import{decodeTime as JL,ulid as W}from"ulid";var Yr,le,ge,fe,ov,Xl,Jl,rv,Ql,Zl,eu,tu,nu,ou,ru,su,iu,au,du,cu,lu,uu,mu,pu,gu,fu,vu,hu,sv,yu,bu,Iu,xu,Eu,Nu=y(()=>{"use strict";at();Pt();Ko();ws();dn();gi();ir();Qt();en();nt();Ci();ri();Sn();se();C();Lt();ce();lt();w();dr();ue();ut();Fn();mt();br();En();yn();go();fn();Ci();Yr=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=Yr(e);if(a(n))return n;let o=ke({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=Ed();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},ov=e=>(e.props.tags??[]).map(t=>x.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Te(t.name)})),Xl=()=>{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},Jl=(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},rv=(e,t=new Map)=>(e.props.assignees??[]).map(n=>x.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:Te(o)}}),Ql=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)},Zl=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)},eu=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=Xl(),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:ov(d),assignees:rv(d,r)}));return c("Listed issues",s)},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=tn(e.parentId,n.value,t.value.stateBranchRoot);if(a(r))return r;let s=Ur({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 I=ze(v).trim();if(!I||u.some(T=>T.name===I))continue;let S=Object.values(o.value.tags).find(T=>T.name===I),A=S?.id??W();S||d.push({id:W(),...n.value,action:"create.tag",payload:{id:A,name:I}}),d.push({id:W(),...n.value,action:"add.issue.tag",payload:{id:l,tag:A}}),u.push({id:A,name:I})}let m=[];for(let v of e.assigneeNames??[]){let I=ze(v).trim();if(!I||m.some(T=>T.name===I))continue;let S=Object.values(o.value.contributors).find(T=>T.name===I),A=S?.id??W();S||d.push({id:W(),...n.value,action:"create.contributor",payload:{id:A,name:I}}),d.push({id:W(),...n.value,action:"add.issue.assignee",payload:{id:l,assignee:A}}),m.push({id:A,name:I})}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})},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=Ot(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})},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.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=Fr(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=Ot(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})},ru=async e=>{let t=Yr(e.repoRoot);if(a(t))return t;let n=ge();if(a(n))return n;let o=ke({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=Ot(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})},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.boardId];if(!r)return i("Board not found");if(!qo(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=tn(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})},iu=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(!Gt(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})},au=async e=>{let t=Yr(e.repoRoot);if(a(t))return t;let n=ge();if(a(n))return n;let o=ke({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=Ot(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})},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.swimlaneId];if(!r)return i("Swimlane not found");if(!Gt(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})},cu=async(e={})=>{Vr();let t=Yr(e.repoRoot);if(a(t))return i("Sync failed");let n=ge();if(a(n))return n;let o=await cr({cwd:t.value,ownEventFileName:Zt(n.value)});return a(o)?(Ri(o.message),o):(Gr(),c("Synced",o.value))},lu=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})},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(!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})},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("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})},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(!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}})},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.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})},fu=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}},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("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 fu(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=[...Jl(Xl(),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}})},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;if(!o.value.contributors[e.contributorId])return i("Contributor not found");if(await fu(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:Go})},sv=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},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.contributors[e.contributorId];if(!r)return i("Contributor not found");if(!r.tombstoned)return i("Contributor is not tombstoned");let s=await sv(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})},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=Ge(t.value.stateBranchRoot);if(a(r))return i(r.message);let s=e.boardId?Yl(r.value,e.boardId):r.value,d=new Map,l=new Set,u=new Set;for(let I of r.value)I.userId&&u.add(I.userId);for(let I of s)I.userId&&(d.set(I.userId,I.userName??""),l.add(I.userId));let m=o.value.contributors,v=[...Jl(d,m).entries()].map(([I,S])=>({id:I,name:S,color:Te(S),isSelf:I===n.value.userId,isExternal:!l.has(I),isRemoved:m[I]?.tombstoned===!0,hasAuthoredAnywhere:u.has(I)}));return c("Listed board contributors",v)},Iu=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})},xu=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");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})},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.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 Su={};ku(Su,{createMcpServer:()=>Ru,resultJson:()=>Y,startMcpServer:()=>Cu});import{McpServer as iv}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as av}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as b}from"zod";var Y,Ru,Cu,Au=y(async()=>{"use strict";C();Nu();Y=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Ru=()=>{let e=new iv({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 lu(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 eu(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:b.object({repoRoot:b.string().optional()})},async t=>Y(await Ql(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 Zl(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 su(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 iu(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 au(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 du(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 tu(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 uu(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 mu(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 pu(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 gu(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 bu(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 hu(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 yu(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 vu(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 Iu(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 xu(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 Eu(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 ou(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 nu(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 ru(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 cu(t))),e},Cu=async()=>{let e=Ru(),t=new av;await e.connect(t)};await Cu()});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;await Au().then(()=>Su);
57
+ `,ui.writeFileSync(t,n,"utf8"),he.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),c("Local epiq paths ignored",!0)}});import Lf from"node:fs";import jc from"node:path";var kf,ee,Wc,Hc=y(()=>{"use strict";$c();Do();dt();Ft();qo();He();io();ar();Et();ot();te();S();Dt();xe();Pe();w();ue();kf=async e=>{let t=await _({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}`),Wc=async()=>{H("");let e=Po(),t=await at(process.cwd());if(a(t))return ee(1,t.message);let n=t.value,o=await Oo(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 kf(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(os(n))return ee(4,"Epiq project already initialized");let s=mr();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 _o({repoRoot:n,branch:m});if(a(p))return ee(6,p.message);if(p.value)return ee(6,`State branch already exists: ${m}`);let h=await gs({repoRoot:n,stateBranchName:m});if(a(h))return ee(6,h.message);let b=Wo();if(a(b))return ee(7,b.message);let A=jc.join(jo(),e.projectId),T=await Xn({repoRoot:n,stateBranchRoot:A,stateBranchName:m});if(a(T))return ee(8,T.message);let R=jc.join(A,".epiq");Lf.mkdirSync(R,{recursive:!0});let U=Za({userId:u,userName:l});if(a(U))return ee(9,U.message);for(let Zr of U.value){let Mi=rr({event:Zr,rootDir:A});if(a(Mi))return ee(9,Mi.message)}let q=await Ko({stateBranchRoot:A,eventFileName:on({userId:u,userName:l})});if(a(q))return ee(10,q.message);let W=await In({cwd:A,message:"[epiq:init]"});if(a(W))return ee(10,W.message);let ve=await _c(n);if(a(ve))return ee(11,ve.message);let Ee=Di({repoRoot:n,fileContents:e});if(a(Ee))return ee(12,Ee.message);let G=await de.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(G))return ee(13,G.message);let z=await de.commit({cwd:n,message:"[epiq:init-project]"});if(a(z))return ee(13,z.message);let $="Project initialized!",yn=await _({cwd:n,args:["push","-u","origin","HEAD"]});a(yn)&&($+=` Warn: [init:14] ${yn.message}`);let Xt=await Jn({repoRoot:n,stateBranchRoot:A});a(Xt)&&($+=` Warn: [init:15] ${Xt.message}`);let Ti=It(U.value).filter(a);if(Ti.length>0)return ee(16,Ti.map(Zr=>Zr.message).join(`
58
+ `));let Qr=Be();if(a(Qr))return ee(16,Qr.message);let{rootNodeId:Mu,nodes:Lu}=Qr.value,wi=Lu[Mu];return wi?(F.navigate({contextNode:wi,selectedIndex:0}),E({hasProjectDefinition:!0,mode:f.DEFAULT}),c($,null)):ee(16,"Unable to resolve initialized root node")}});import{ulid as Pf}from"ulid";function pi(e){let t=qc();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=zc({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Gc(u.value)}function gi(e){let t=qc();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=zc({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:Gc(d.value)}var Kc,Yt,Co,qc,mi,zc,Gc,fi=y(()=>{"use strict";Et();ot();S();ut();w();Kc=null,Yt=()=>structuredClone(Kc),Co=e=>{Kc=e},qc=()=>{let{contextNode:e,selectedIndex:t}=g(),o=ne(e.id)[t];return o?c("Resolved selected child",o):i("Target node not found")},mi=({id:e,parentId:t,position:n={at:"end"}})=>{let o=ne(t).filter(r=>r.id!==e);return sr(o,n)},zc=({id:e,parentId:t,position:n={at:"end"}})=>{let o=ae();if(a(o))return i("Unable to resolve user ID");let r=mi({parentId:t,id:e,position:n});return a(r)?r:c("Created pending move state",{id:Pf(),...o.value,action:"move.node",payload:{id:e,parent:t,rank:r.value.rank}})},Gc=e=>{Co(e);let t=_t(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as Df}from"ulid";var Vc,Ur,Yc,Xc=y(()=>{"use strict";He();fi();rn();ot();te();S();ut();xe();w();ue();Vc=()=>{let e=Yt();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))},Ur=(e,t="Moved preview")=>{if(a(e))return e;let n=Vc();return a(n)?n:(E({mode:f.MOVE}),c(t,null))},Yc=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:h})=>h===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=mi({parentId:r.parentNodeId,id:r.id,position:m});return a(p)?p:(Co({id:Df(),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 Ur(gi(1));if(t==="previous")return Ur(gi(-1));if(t==="to-next")return Ur(pi(1));if(t==="to-previous")return Ur(pi(-1));if(t==="confirm"){let s=Yt();if(!s)return i("No pending move to confirm");let d=await it();if(a(d))return d;let l=B([s],d.value);if(a(l))return l;let u=Vc();return a(u)?u:(Co(null),E({mode:f.DEFAULT}),c("Moved item",null))}return t==="cancel"?(Co(null),E({mode:f.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as Ff,ulid as Bf}from"ulid";var Of,_r,vi=y(()=>{"use strict";S();Of=Ff(),_r=({name:e,parent:t,rank:n,user:{userId:o,userName:r}})=>{let s=Of();return c("Created issue events",[{id:Bf(),userId:o,userName:r,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as $r}from"ulid";var Jc,Qc=y(()=>{"use strict";He();vi();rn();ot();mt();S();ce();ut();w();ue();Jc=async(e,t)=>{let n=ae();if(a(n))return i("Unable to resolve user ID");let o=await it();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 h=I.getNode(p.value[0].result.id);if(!h)return i("Created node not found");if(!h.parentNodeId)return p;let b=I.getNode(h.parentNodeId);return b?(F.navigate({contextNode:b,selectedIndex:I.getSiblings(h.parentNodeId).findIndex(({id:A})=>A===h.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 h=sn(p.id,n.value,r);return a(h)?h:u({id:$r(),action:"add.board",payload:{id:$r(),name:t.inputString,parent:p.id,rank:h.value},...n.value})}if(t.modifier==="swimlane"){let m=We(s,"BOARD");if(a(m))return i("Unable to add swimlane in this context");let p=sn(m.value.id,n.value,r);return a(p)?p:u({id:$r(),action:"add.swimlane",payload:{id:$r(),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 W=We(s,"SWIMLANE");return a(W)?null:W.value})();if(!p)return i("Unable to add issue in this context");let h=sn(p.id,n.value,r);if(a(h))return h;let b=_r({name:t.inputString,parent:p.id,rank:h.value,user:n.value});if(a(b))return b;let A=b.value,T=B([...A],r);if(a(T))return T;if(!T.value[0])return i("Issue creation failed");let q=A.find(W=>W.action==="add.issue")?.payload.id;return q?(F.navigate({contextNode:p,selectedIndex:I.getSiblings(p.id).findIndex(({id:W})=>W===q)}),c("Issue created",null)):i("Unable to determine ticket id")}return c("Success",null)}});var jr,hi=y(()=>{"use strict";He();nn();Et();S();w();jr=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:o})=>{let r=g(),s=As(n,t);if(a(s))return i(s.message);let{appliedEvents:d,unappliedEvents:l}=s.value,u=Mt();if(a(u))return u;let p=It(d).filter(a);if(p.length>0)return Mt(),E(r),i(p.map(b=>b.message).join(", "));let h=g().nodes[e];return h?(F.navigate({contextNode:h,selectedIndex:o}),c("",{unappliedEvents:l})):(Mt(),E(r),i("Board did not exist at that date"))}});var Uf,_f,$f,Wr,Hr,hn,Zc,jf,el,yi=y(()=>{"use strict";uo();er();Et();te();S();w();Uf=20,_f=16,$f=150,Wr=null,Hr=null,hn=()=>{Wr!==null&&(clearInterval(Wr),Wr=null),Hr!==null&&(clearTimeout(Hr),Hr=null)},Zc=()=>{hn(),E({mode:f.DEFAULT,readOnly:!1,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},jf=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)},el=({events:e,startTime:t,durationMs:n})=>{hn();let o=e.length,r=e.map(h=>un(h)??t),s=r[o-1]??Date.now(),d=jf(r),l=Math.max(1,Math.round(n*Uf/1e3)),u=Math.max(Math.round(n/l),_f),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:[]}}),Wr=setInterval(()=>{m++;let h=m/l,b=[],A;for(;p<o&&d[p]<=h;){let R=e[p],U=_t(R);if(a(U)){Zc();return}b.push(...xs(R)),A=R,p++}if(p>=o||m>=l){for(;p<o;p++){let U=_t(e[p]);if(a(U))break}let R=g().replay;E({unappliedEvents:[],replay:R&&{...R,progress:1,appliedCount:o}}),hn(),Hr=setTimeout(Zc,$f);return}let T=g().replay;E({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,h),appliedCount:p,totalCount:o,startTime:t,endTime:s,currentTime:A?un(A)??T?.currentTime??t:T?.currentTime??t,currentLabel:A?wa(A):T?.currentLabel??"",flashNodeIds:A?[...new Set(b)]:T?.flashNodeIds??[]}})},u)}});var tl,nl=y(()=>{"use strict";dt();uo();nn();Et();te();mt();S();xe();w();co();hi();yi();tl=async()=>{let e=We(g().breadCrumb,"BOARD");if(a(e))return e;let t=await at(process.cwd());if(a(t))return i("Unable to locate repo root");let n=ke({repoRoot:t.value});if(a(n))return n;let{modifier:o,inputString:r}=Q().commandMeta;if(hn(),o==="now"){let l=Ye(n.value);if(a(l))return i(l.message);let u=Mt();if(a(u))return u;let p=It(l.value).filter(a);return p.length>0?i(p.map(h=>h.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=un(l);if(u===null)return i("No previous event to peek");s=u}else if(o==="next"){let l=g().unappliedEvents.at(0),u=un(l);if(u===null)return i("No next event to peek");s=u+1}else{let l=cn(o||r.trim());if(!l)return i("Invalid peek date");s=l.getTime()}let d=jr({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 ol,rl=y(()=>{"use strict";dt();mt();S();xe();w();co();hi();yi();ol=async()=>{let e=We(g().breadCrumb,"BOARD");if(a(e))return e;let t=await at(process.cwd());if(a(t))return i("Unable to locate repo root");let n=ke({repoRoot:t.value});if(a(n))return n;let{modifier:o,inputString:r}=Q().commandMeta,{dateInput:s,durationInput:d}=vr(o,r);if(hn(),g().syncStatus.status==="syncing")return i("Cannot replay while syncing, try again in a moment");let l=cn(s);if(!l)return i("Invalid replay date");let u=d?fr(d):15e3;if(u===null)return i("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=g(),h=jr({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(h))return h;let{unappliedEvents:b}=h.value;return b.length===0?(Mt(),E(p),c("Nothing to replay from that point",!0)):(el({events:b,startTime:m,durationMs:u}),c("Replaying board history",!0))}});import Hf from"zod";var sl,il=y(()=>{"use strict";mn();te();S();xe();Pe();w();sl=()=>{let e=Q().commandMeta.inputString,t=Hf.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=Je({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 al,dl=y(()=>{"use strict";io();mn();te();S();xe();Pe();w();al=()=>{let e=Q().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=ad(e),n=Je({autoSync:t});return a(n)?n:(Ve({autoSync:t}),E({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var cl,ll=y(()=>{"use strict";mn();te();S();xe();Pe();w();cl=()=>{let e=Q().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return i("Invalid response");let n=Je({logLevel:e});return a(n)?n:(Ve({logLevel:e}),E({mode:f.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});import{spawn as Kf}from"node:child_process";var qf,ul,ml=y(()=>{"use strict";S();qf=()=>{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"]}}},ul=async e=>new Promise(t=>{let{command:n,args:o}=qf();try{let r=Kf(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,pl,gl=y(()=>{"use strict";S();w();ml();Cn();ao();Ht();So=async(e,t)=>{if(!e.trim())return i(`Nothing to copy: ${t} is empty`);let n=await ul(e);return a(n)?n:c(`Copied ${t} to clipboard`,null)},pl=async e=>{let{breadCrumb:t,selectedNode:n}=g(),o=lo({breadCrumb:t,selectedNode:n}),r=o??n;if(!r)return i("Nothing selected to copy from");switch(e.modifier){case be.REF:return So(nt(r.id),"ref");case be.TITLE:return So(r.title,"title");case be.DESCRIPTION:return o?So(o.props?.description??"","description"):i("No issue in scope");case be.TAGS:{if(!o)return i("No issue in scope");let s=jt(o).map(({name:d})=>d);return So(s.join(", "),"tags")}case be.ASSIGNEES:{if(!o)return i("No issue in scope");let s=Wt(o).map(({name:d})=>d);return So(s.join(", "),"assignees")}default:return i("Yank one of: ref, title, description, tags, assignees")}}});var fl,vl=y(()=>{"use strict";Ms();te();S();xe();w();fl=async()=>{H(""),E({mode:f.DEFAULT});let e=Be();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 dr();return a(t)?(E({syncStatus:{msg:t.message,status:"failed"}}),t):(E({mode:f.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as Le}from"ulid";var zf,hl,yl,Lt,bl,xl=y(()=>{"use strict";Lc();He();mn();rn();ot();ii();wn();te();mt();se();S();ce();ut();xe();Pe();w();Or();ue();gn();di();dn();Ys();Ht();xr();Uc();Hc();Xc();Qc();nl();rl();il();Hs();dl();ll();gl();vl();zf=e=>e.action==="add.issue.comment",hl=e=>Object.values(g().tags).find(t=>t.name===e),yl=()=>{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,Bn(r.name,n.get(r.id))??r.name)}return[...n.entries()].map(([r,s])=>({id:r,name:s,isExternal:!o.has(r)}))},Lt=async()=>{let e=await it();return a(e)?e:c("Resolved persist root",e.value)},bl=[{systemOnly:!0,intent:P.Move,description:"Internal move-state command",mode:f.COMMAND_LINE,action:Yc},{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 Lt();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(zf).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):B([{id:Le(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],r.value):i("Unable to resolve comment")}return B([{id:Le(),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(v.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 Vt({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[ye];if(!r)return i("Unable to locate closed swimlane");if(o.parentNodeId===r.id)return i("Issue is already closed");let s=await Lt();if(a(s))return s;let d=s.value,l=$t(r.id,o.id,{at:"end"},e.value,d);if(a(l))return l;let u=B([{id:Le(),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):en(o.id,"TICKET");if(a(r))return i("Cannot reopen in this context");let s=r.value,d=g().nodes[ye];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=Br(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 Lt();if(a(m))return m;let p=m.value,h=$t(u.id,s.id,{at:"end"},e.value,p);if(a(h))return h;let b=B([{id:Le(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:h.value},...e.value}],p);return a(b)?b: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:Wc},{intent:P.NewItem,description:"Create a new board, swimlane, or issue",mode:f.COMMAND_LINE,action:Jc,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=Yd();if(!r)return i("Provide a title");let s=await Lt();return a(s)?s:B([{id:Le(),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=hl(o);if(!r)return i(`Tag "${o}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid untag target");let d=en(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 Lt();return a(m)?m:B([{id:Le(),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=en(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 Lt();if(a(l))return l;let u=hl(o),m=u?.id??Le();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):B([...u?[]:[{id:Le(),action:"create.tag",payload:{id:m,name:o},...e.value}],{id:Le(),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=en(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 h=await Lt();if(a(h))return h;let b=yl(),A=!r&&s.toLowerCase()==="me",T,R;if(A)T=e.value.userId,R=b.find(W=>W.id===T)?.name??e.value.userName;else{let W=b.filter(Ee=>Ee.name===s);if(W.length>1)return i(`"${s}" matches ${W.length} contributors (${W.map(Ee=>Ee.id).join(", ")}). Assign from the GUI to choose by id.`);let ve=W[0];if(!ve&&!r)return i(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);T=ve?.id??Le(),R=ve?.name??s}if((p.props.assignees??[]).includes(T))return i("Assignee already assigned");let q=!!g().contributors[T];return B([...q?[]:[{id:Le(),action:"create.contributor",payload:{id:T,name:R},...e.value}],{id:Le(),action:"add.issue.assignee",payload:{id:p.id,assignee:T},...e.value}],h.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=en(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(b=>b===e.value.userId):yl().filter(b=>b.name===o&&l.includes(b.id)).map(b=>b.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 h=await Lt();return a(h)?h:B([{id:Le(),action:"remove.issue.assignee",payload:{id:d.id,assignee:p},...e.value}],h.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=We([...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):en(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 Lt();return a(p)?p:B([{id:Le(),action:"add.issue.comment",payload:{id:Le(),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:fl},{intent:P.Peek,description:"View board state at another point in time",mode:f.COMMAND_LINE,action:tl},{intent:P.Replay,description:"Replay board history forward from a point in time",mode:f.COMMAND_LINE,action:ol},{intent:P.Export,description:"Export the current board layout to markdown",mode:f.COMMAND_LINE,action:async()=>{let e=await Mc();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)=>Oc(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)=>pl(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??Le();if(!d||!l)return i("Unable to resolve user name or id");let u=Je({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=Je({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=Je({viewMode:n});return a(o)?o:(Ve({viewMode:n}),E({mode:f.DEFAULT}),c(`View set to "${n}"`,null))}case oe.AUTOSYNC:return al();case oe.LOG_LEVEL:return cl();case oe.SYNC_DEBOUNCE_MS:return sl();case oe.ATTACHMENT_MAX_KB:return Cd();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"?Ro("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):Ro(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),H(""),c("Thanks you!",null)}}]});var Gf,ht,bi=y(()=>{"use strict";ur();Ir();Ys();xl();S();xe();Pe();w();Gf=new Set(["peek","replay","filter","view-help","yank"]),ht=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===Kt.Invalid)return i("Invalid command");let s=Xd(t);qd();let{readOnly:d}=g();if(d&&!Gf.has(s))return vo({status:Pt.Fail,message:"Command not available in readonly state",value:null});let l=bl.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return vo({status:Pt.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:r,modifier:o})}catch(m){return vo({status:Pt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?vo(u):(zd({addToHistory:!e}),l.onSuccess?.(),ie().autoSync&&rd(),u)}});var Kr,qr,Il,El=y(()=>{"use strict";S();te();w();Zt();bi();fi();xe();Kr=[{intent:M.Exit,mode:f.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:f.COMMAND_LINE}),H("move cancel"),ht({isForceExecutedBySystem:!0}))},{intent:M.InitMove,mode:f.DEFAULT,description:"[m] move (init/confirm)",action:()=>(E({mode:f.COMMAND_LINE}),H("move start"),ht({isForceExecutedBySystem:!0}))},{intent:M.ConfirmMove,mode:f.MOVE,action:()=>(E({mode:f.COMMAND_LINE}),H("move confirm"),ht({isForceExecutedBySystem:!0}))}],qr=[{intent:M.MovePreviousItem,mode:f.MOVE,action:()=>Yt()?(E({mode:f.COMMAND_LINE}),H("move previous"),ht({isForceExecutedBySystem:!0})):i("No pending move")},{intent:M.MoveNextItem,mode:f.MOVE,action:()=>Yt()?(E({mode:f.COMMAND_LINE}),H("move next"),ht({isForceExecutedBySystem:!0})):i("No pending move")}],Il=[{intent:M.MoveToNextContainer,mode:f.MOVE,action:()=>Yt()?(E({mode:f.COMMAND_LINE}),H("move to-next"),ht({isForceExecutedBySystem:!0})):i("No pending move")},{intent:M.MoveToPreviousContainer,mode:f.MOVE,action:()=>Yt()?(E({mode:f.COMMAND_LINE}),H("move to-previous"),ht({isForceExecutedBySystem:!0})):i("No pending move")}]});var Nl,Rl=y(()=>{"use strict";se();El();Nl={[D.WORKSPACE]:[...Kr,...qr],[D.BOARD]:[...Kr,...qr],[D.SWIMLANE]:[...Kr,...qr,...Il],[D.TICKET]:[],[D.FIELD]:[],[D.FIELD_LIST]:[],[D.TEXT]:[],[D.COMMENT]:[]}});import Vf from"node:fs";import Yf from"node:path";var Cl,Sl=y(()=>{"use strict";dt();po();S();ue();di();Cl=e=>{let t=et(process.cwd());if(a(t))return i("Unable to resolve project root");let n=ke({repoRoot:t.value});if(a(n))return i(n.message);let o=Ws(e.hash,e.ext),r=Yf.join(ns(n.value),o);return Vf.existsSync(r)?(Ro(r),c(`Opened ${e.name}`,null)):i("Attachment file not found \u2014 run :sync to fetch it")}});var Al,Tl,wl=y(()=>{"use strict";te();S();xe();w();Or();Zt();He();Al=()=>{H("");let{pendingNavTarget:e}=$n();E({mode:f.DEFAULT}),e&&F.navigate(e),Vt({pendingNavTarget:void 0})},Tl=[{intent:M.ExitCommandLine,mode:f.HELP,action:()=>(Al(),c("Exiting help",null))},{intent:M.Exit,mode:f.HELP,action:()=>(Al(),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 Xf,Ml,Ll,kl=y(()=>{"use strict";te();se();S();xe();w();Or();Zt();He();Xf=e=>{E({mode:f.COMMAND_LINE});let{pendingNavTarget:t}=$n();t&&F.navigate(t),Vt({pendingNavTarget:void 0}),H(`${e} `)},Ml=()=>{H("");let{pendingNavTarget:e}=$n();e&&F.navigate(e),Vt({pendingNavTarget:void 0}),E({mode:f.DEFAULT})},Ll=[{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 Vt({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||!ia(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?(Xf(t),c("Selected command",t)):c("No command selected",null)}},{intent:M.ExitCommandLine,mode:f.PALETTE,action:()=>(Ml(),c("Exiting palette",null))},{intent:M.Exit,mode:f.PALETTE,action:()=>(Ml(),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 Pl,Dl=y(()=>{"use strict";dn();Ht();te();S();Rn();ce();ut();xe();w();Sl();Zt();wl();kl();He();Pl=[...Tl,...Ll,{intent:M.AddItem,mode:f.DEFAULT,description:"[n] new...",action:()=>(E({mode:f.COMMAND_LINE}),H(`${v.NEW} `),c("Adding new item",null))},{intent:M.Delete,mode:f.DEFAULT,description:"[d] delete",action:()=>(E({mode:f.COMMAND_LINE}),H(`${v.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 Cl(o);if(e?.title===X.DESCRIPTION)return E({mode:f.COMMAND_LINE}),H(`${v.EDIT} description `),c("Propose command",!0);if(e?.title===X.ASSIGNEES)return E({mode:f.COMMAND_LINE}),H(`${v.ASSIGN} `),c("Propose command",!0);if(e?.title===X.TAGS)return E({mode:f.COMMAND_LINE}),H(`${v.TAG} `),c("Propose command",!0);if(t.title===X.DESCRIPTION&&e?.context==="TEXT")return E({mode:f.COMMAND_LINE}),H(`${v.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?be.DESCRIPTION:e?.title===X.TAGS?be.TAGS:e?.title===X.ASSIGNEES?be.ASSIGNEES:be.REF,o=pe(v.YANK).includes(t)?t:be.REF;return E({mode:f.COMMAND_LINE}),H(`${v.YANK} ${o}`),c("Propose command",!0)}},{intent:M.EditTitle,mode:f.DEFAULT,description:"[r] rename title",action:()=>(E({mode:f.COMMAND_LINE}),H(`${v.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(`${v.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 Jf,Qf,Fl,Bl=y(()=>{"use strict";xe();Jf=500,Qf=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Fl=e=>{let t=Qf(e);t&&Cr(n=>(n+t).slice(0,Jf))}});var Zf,ev,Ol,Ul=y(()=>{"use strict";Bl();te();S();xe();w();Zt();bi();Zf=[f.COMMAND_LINE,f.PALETTE],ev=e=>[{intent:M.MoveCursorLeft,mode:e,action:()=>(Gs(-1),c("Moving cursor left",null))},{intent:M.MoveCursorRight,mode:e,action:()=>(Gs(1),c("Moving cursor right",null))},{intent:M.MoveCursorLeftOfWord,mode:e,action:()=>(Vs("left"),c("Moving cursor left of word",null))},{intent:M.MoveCursorRightOfWord,mode:e,action:()=>(Vs("right"),c("Moving cursor right of word",null))},{intent:M.AutoCompleteCommand,mode:e,action:()=>(Cr((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})=>(Fl(n??""),c("Capturing input",null))},{intent:M.EraseInput,mode:e,action:()=>(Hd(),c("Erasing input",null))},{intent:M.EraseInputWord,mode:e,action:()=>(Kd(),c("Erasing input word",null))}],Ol=[{intent:M.Confirm,mode:f.COMMAND_LINE,action:()=>(ht(),c("Executing command",null))},{intent:M.ViewHelp,mode:f.DEFAULT,action:()=>(E({mode:f.HELP}),c("Viewing help",null))},...Zf.flatMap(ev),{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:()=>(Gd(),c("Getting last command from history",null))},{intent:M.GetNextCommandFromHistory,mode:f.COMMAND_LINE,action:()=>(Vd(),c("Getting next command from history",null))}]});import jl from"chalk";var zr,_l,$l,xi,Wl=y(()=>{"use strict";te();se();Fe();zr=jl.dim.hex(C.secondary2)(": for command line"),_l="q to exit",$l=`${jl.hex(C.accent)("m")} to confirm`,xi={[D.WORKSPACE]:[zr],[D.BOARD]:[zr],[D.BOARD+f.COMMAND_LINE]:[zr],[D.SWIMLANE]:[zr],[D.TICKET+f.HELP]:[_l],[D.SWIMLANE+f.HELP]:[_l],[D.TICKET]:[],[D.FIELD]:[],[D.SWIMLANE+f.MOVE]:[$l],[D.TICKET+f.MOVE]:[$l]}});var Ao,tv,nv,Hl,Kl=y(()=>{"use strict";w();gn();Cn();Ao=e=>e.trim().toLocaleLowerCase(),tv=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]?.name).filter(n=>!!n)},nv=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>{let o=t[n];return o?zt(n,o.name):void 0}).filter(n=>!!n)},Hl=(e,t)=>{let n=Ao(t.value);if(!n)return!0;switch(t.target){case"title":return Ao(e.title??"").includes(n);case"description":return Ao(e.props.description??"").includes(n);case"tag":return tv(e).map(Ao).some(r=>r.includes(n));case"assignee":return nv(e).map(Ao).some(r=>r.includes(n));case"ref":return ba(e.id,t.value);default:return!0}}});function ql(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 zl=y(()=>{"use strict";S()});var Gl,Vl=y(()=>{"use strict";Gl=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 ov}from"react";function Ri(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=ql(t,r,o);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,h=xi[p+n]??xi[p]??[],b=[...Pl,...Nl[p]??[],...Ol],A=Gl(b),T=sv(r,s),R=T[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:h,availableActions:b,actionIndex:A,selectedNode:R,renderedChildrenIndex:T})}function to(e){Ii=e;let t=et(process.cwd()),n=!1;if(!a(t)){let s=bt(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=Ri(o);return a(r)?r:(kt=r.value,Ni(),c("State initialized",null))}function me(e){let t=g(),n=e(t);if(To)return Gr=n,kt={...t,...n},c("State updated",null);let o=Ri(n);return a(o)?i(o.message??"Unable to update state"):(kt=o.value,Ni(),c("State updated",null))}function Fa(e){if(To)return c("Joined batch",e());To=!0,Gr=null;let t=()=>{let n=Gr;if(To=!1,Gr=null,n===null)return null;let o=Ri(n);return a(o)?i(o.message??"Unable to update state"):(kt=o.value,Ni(),c("State updated",null))};try{let n=e(),o=t();return o&&a(o)?i(o.message):c("State updated",n)}finally{To&&t()}}var kt,Ii,Ei,Ni,rv,g,Be,To,Gr,E,_e,sv,J,Mt,an,w=y(()=>{"use strict";Rl();Dl();Ul();Wl();Dt();te();se();S();ue();Kl();zl();Vl();Ei=new Set,Ni=()=>{for(let e of Ei)e()},rv=e=>(Ei.add(e),()=>Ei.delete(e));g=()=>{if(!kt)throw new Error("State not initialized. Call initWorkspaceState() first.");return kt},Be=()=>kt?c("Retrieved state",kt):i("State not initialized. Call initWorkspaceState() first.");To=!1,Gr=null;E=e=>me(t=>({...t,...e})),_e=()=>ov(rv,g,g),sv=(e,t)=>{let n={};for(let o of Object.values(e))L(o)&&t.length>0&&!t.every(r=>Hl(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]??[],Mt=()=>Ii?to(Ii):i("Cannot reset state: no initial workspace found"),an=()=>kt!==void 0});var Ci,Vr,Yr,Si,Xe,cr=y(()=>{"use strict";sa();S();w();Ci=e=>{an()&&(E({syncStatus:e}),ra({type:"sync-status",payload:e}))},Vr=(e="Syncing...")=>{Ci({status:"syncing",msg:e})},Yr=(e="Synced")=>{Ci({status:"synced",msg:e})},Si=e=>{Ci({status:"failed",msg:e})},Xe=e=>(Si(e),i(e))});import{decodeTime as fk}from"ulid";var Yl=y(()=>{"use strict";S()});var iv,av,lr,Ls=y(()=>{"use strict";S();cr();ws();Fo();dt();Ft();qo();Yl();iv=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=V("getRepoRootDir",await at(e));if(a(n))return i(n.message);let o=n.value;logger.debug("[sync] repo root",o);let r=V("getStateBranchRoot",ke({repoRoot:o}));if(a(r))return i(r.message);let s=r.value;logger.debug("[sync] state branch root",s);let d=V("ensureInitialCommit",await ea(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=V("bootstrapStateBranchStorage",await oa({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=V("hasInProgressGitOperation(stateBranchRoot)",await Oo(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=V("ensureStateBranchLayout",Ji(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}))},av=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=V("stageStateBranchOwnEventFile",await Ko({stateBranchRoot:t,eventFileName:n}));if(a(o))return i(o.message);let r=V("stageStateBranchMediaFiles",await ta({stateBranchRoot:t}));if(a(r))return i(r.message);let s=V("hasStagedChanges(after stage)",await Ki(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=V("createStateBranchSyncCommit",await na({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}))},lr=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");Vr();let n=V("ensureSyncReady",await iv({cwd:e,ensureUpstream:!0}));if(a(n))return Xe(n.message);let{repoRoot:o,stateBranchRoot:r,bootstrapped:s}=n.value,d=V("isDetachedHead(stateBranchRoot)",await qi(r));if(a(d))return Xe(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return Xe("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,p=!1,h=V("getStateBranch",xn(o));if(a(h))return Xe(h.message);let b=h.value;logger.debug("[sync] resolved state branch",{stateBranch:b,stateBranchRoot:r});let A=V("commitOwnEventFileToStateBranch",await av({repoRoot:o,stateBranchRoot:r,ownEventFileName:t}));if(a(A))return Xe(A.message);l=A.value.createdCommit,u=A.value.commitSha;let T=V("pullBranchRebaseIfPresent",await us({cwd:r,branch:b}));if(a(T))return Xe(T.message);if(m=T.value,l||s){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:s,stateBranchRoot:r});let R=V("pushStateBranch",await Jn({stateBranchRoot:r,repoRoot:o}));if(a(R)&&Hi(R.message)){let U=V("pullBranchRebaseIfPresent(retry)",await us({cwd:r,branch:b}));if(a(U))return Xe(U.message);m=m||U.value,R=V("pushStateBranch(retry)",await Jn({stateBranchRoot:r,repoRoot:o}))}if(a(R))return Xe(R.message);p=R.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:r});let R=V("git rev-parse HEAD",await _({args:["rev-parse","HEAD"],cwd:r}));if(a(R))return Xe(R.message);u=R.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Yr(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 Xl=y(()=>{"use strict"});var Qk,Jl,Ai=y(()=>{"use strict";dt();Ft();ci();uo();er();pt();nn();Et();Xl();S();Dt();br();ue();w();Qk=Promise.resolve(),Jl=(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;if(!u)continue;d.action==="add.board"&&o.add(u);let m=l.parent??l.issue;m&&n.set(u,m),(u===t||r(u)===t)&&s.push(d)}return s}});import{decodeTime as rP,ulid as j}from"ulid";var Xr,le,ge,fe,dv,Ql,Zl,cv,eu,tu,nu,ou,ru,su,iu,au,du,cu,lu,uu,mu,pu,gu,fu,vu,hu,yu,bu,lv,xu,Iu,Eu,Nu,Ru,Cu=y(()=>{"use strict";dt();Ft();qo();Ls();mn();vi();ar();nn();rn();ot();Ai();ii();wn();se();S();Dt();ce();ut();w();cr();ue();mt();gn();pt();xr();Cn();Bt();po();bn();Ai();Xr=e=>{let t=et(e??process.cwd());return a(t)?i(t.message):c("Resolved Epiq repo root",t.value)},le=async(e,t)=>{let n=Xr(e);if(a(n))return n;let o=ke({repoRoot:n.value});if(a(o))return i(o.message);let r=Po(),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 _({cwd:o.value,args:["pull","--ff-only"]});a(u)&&he.info(3,u.message)}let d=Ye(o.value);if(a(d))return i(d.message);let l=Mn(d.value);return a(l)?i(l.message):c("Booted Epiq state",{repoRoot:n.value,stateBranchRoot:o.value})},ge=()=>{let e=Rd();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=Be();return a(e)?i(e.message):e},dv=e=>(e.props.tags??[]).map(t=>I.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:we(t.name)})),Ql=()=>{let e=Be(),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},Zl=(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,Bn(o.name,n.get(o.id))??o.name)}return n},cv=(e,t=new Map)=>(e.props.assignees??[]).map(n=>I.getContributor(n)).filter(n=>n!=null).map(n=>{let o=n.tombstoned?n.name:Bn(n.name,t.get(n.id))??n.name;return{id:n.id,name:o,color:we(o)}}),eu=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:nt(r.id),title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return c("Listed boards",o)},tu=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===ye,readonly:!!r.readonly}));return c("Listed swimlanes",o)},nu=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=Ql(),s=Object.values(o).filter(L).filter(d=>!d.isDeleted).filter(d=>e.includeClosed||d.parentNodeId!==ye).filter(d=>e.boardId?(d.parentNodeId?o[d.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).map(d=>({id:d.id,ref:nt(d.id),title:Ge(d.title),description:d.props.description??"",parentNodeId:d.parentNodeId,isClosed:d.parentNodeId===ye,readonly:!!d.readonly,tags:dv(d),assignees:cv(d,r)}));return c("Listed issues",s)},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=sn(e.parentId,n.value,t.value.stateBranchRoot);if(a(r))return r;let s=_r({name:e.title,parent:e.parentId,user:n.value,rank:r.value});if(a(s))return s;let d=[...s.value],l=d.find(h=>h.action==="add.issue")?.payload.id;if(!l)return i("Unable to determine created issue id");e.description&&d.push({id:j(),...n.value,action:"edit.description",payload:{id:l,md:e.description}});let u=[];for(let h of e.tagNames??[]){let b=Ge(h).trim();if(!b||u.some(R=>R.name===b))continue;let A=Object.values(o.value.tags).find(R=>R.name===b),T=A?.id??j();A||d.push({id:j(),...n.value,action:"create.tag",payload:{id:T,name:b}}),d.push({id:j(),...n.value,action:"add.issue.tag",payload:{id:l,tag:T}}),u.push({id:T,name:b})}let m=[];for(let h of e.assigneeNames??[]){let b=Ge(h).trim();if(!b||m.some(R=>R.name===b))continue;let A=Object.values(o.value.contributors).find(R=>R.name===b),T=A?.id??j();A||d.push({id:j(),...n.value,action:"create.contributor",payload:{id:T,name:b}}),d.push({id:j(),...n.value,action:"add.issue.assignee",payload:{id:l,assignee:T}}),m.push({id:T,name:b})}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})},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=$t(ye,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(o))return o;let r={id:j(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ye,rank:o.value}},s=B([r],t.value.stateBranchRoot);return a(s)?i(s.message):c("Closed issue",{id:e.issueId})},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.issueId];if(!r)return i("Issue not found");if(!L(r))return i("Target node is not issue");if(r.parentNodeId!==ye)return i("Issue is not closed");let s=Br(r);if(!s)return i("Unable to resolve previous parent from issue history");if(s===ye)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=$t(d.id,r.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(l))return l;let u={id:j(),...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})},iu=async e=>{let t=Xr(e.repoRoot);if(a(t))return t;let n=ge();if(a(n))return n;let o=ke({repoRoot:t.value});if(a(o))return o;let r=Ye(o.value);if(a(r))return r;let s=Mn(r.value);if(a(s))return s;let d=$t(e.parentId,e.issueId,e.position??{at:"end"},n.value,o.value);if(a(d))return d;let l={id:j(),...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})},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.boardId];if(!r)return i("Board not found");if(!zo(r))return i("Target parent must be a board");let s=Ge(e.title);if(!s.trim())return i("Swimlane title cannot be empty");let d=sn(e.boardId,n.value,t.value.stateBranchRoot);if(a(d))return d;let l=j(),u={id:j(),...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})},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.swimlaneId];if(!r)return i("Swimlane not found");if(!Qt(r))return i("Edit target must be a swimlane");if(r.readonly)return i("Cannot edit readonly swimlane");let s=Ge(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:j(),...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})},cu=async e=>{let t=Xr(e.repoRoot);if(a(t))return t;let n=ge();if(a(n))return n;let o=ke({repoRoot:t.value});if(a(o))return o;let r=Ye(o.value);if(a(r))return r;let s=Mn(r.value);if(a(s))return s;let d=$t(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,o.value);if(a(d))return d;let l={id:j(),...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})},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.swimlaneId];if(!r)return i("Swimlane not found");if(!Qt(r))return i("Delete target must be a swimlane");let s={id:j(),...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})},uu=async(e={})=>{Vr();let t=Xr(e.repoRoot);if(a(t))return i("Sync failed");let n=ge();if(a(n))return n;let o=await lr({cwd:t.value,ownEventFileName:on(n.value)});return a(o)?(Si(o.message),o):(Yr(),c("Synced",o.value))},mu=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})},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("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:j(),...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})},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.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=Ge(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:j(),...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})},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.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=Ge(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??j(),u=[...d?[]:[{id:j(),...n.value,action:"create.tag",payload:{id:l,name:s}}],{id:j(),...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}})},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(!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:j(),...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})},hu=async(e,t)=>{let n=Ye(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}},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("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 R=o.value.contributors[s],U=R?void 0:await hu(t.value.stateBranchRoot,s);if(!R&&!U)return i("Unknown assignee id");let q=R??U,W=[...R?[]:[{id:j(),...n.value,action:"create.contributor",payload:{id:q.id,name:q.name}}],{id:j(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:q.id}}],ve=B(W,t.value.stateBranchRoot);return a(ve)?i(ve.message):c("Added issue assignee",{id:e.issueId,assignee:{id:q.id,name:q.name}})}let d=Ge(e.assigneeName??"").trim();if(!d)return i("Provide assigneeId, self or assigneeName");let u=[...Zl(Ql(),o.value.contributors).entries()].filter(([,R])=>R===d);if(u.length>1)return i(`"${d}" matches ${u.length} contributors (${u.map(([R])=>R).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=j(),h=d]=m??[],A=[...!!o.value.contributors[p]?[]:[{id:j(),...n.value,action:"create.contributor",payload:{id:p,name:h}}],{id:j(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:p}}],T=B(A,t.value.stateBranchRoot);return a(T)?i(T.message):c("Added issue assignee",{id:e.issueId,assignee:{id:p,name:h}})},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;if(!o.value.contributors[e.contributorId])return i("Contributor not found");if(await hu(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:j(),...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:Yo})},lv=async(e,t)=>{let n=Ye(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},xu=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 lv(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:j(),...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})},Iu=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=Ye(t.value.stateBranchRoot);if(a(r))return i(r.message);let s=e.boardId?Jl(r.value,e.boardId):r.value,d=new Map,l=new Set,u=new Set;for(let b of r.value)b.userId&&u.add(b.userId);for(let b of s)b.userId&&(d.set(b.userId,b.userName??""),l.add(b.userId));let m=o.value.contributors,h=[...Zl(d,m).entries()].map(([b,A])=>({id:b,name:A,color:we(A),isSelf:b===n.value.userId,isExternal:!l.has(b),isRemoved:m[b]?.tombstoned===!0,hasAuthoredAnywhere:u.has(b)}));return c("Listed board contributors",h)},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("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:j(),...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})},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.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=j(),l={id:j(),...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})},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.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:j(),...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 Tu={};Pu(Tu,{createMcpServer:()=>Su,resultJson:()=>Y,startMcpServer:()=>Au});import{McpServer as uv}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as mv}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as x}from"zod";var Y,Su,Au,wu=y(async()=>{"use strict";S();Cu();Y=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Su=()=>{let e=new uv({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:x.object({repoRoot:x.string().optional()})},async t=>Y(await mu(t))),e.registerTool("epiq_issue_list",{description:"List Epiq issues. Pass boardId to scope results to a single board and reduce response size.",inputSchema:x.object({repoRoot:x.string().optional(),includeClosed:x.boolean().optional(),boardId:x.string().optional()})},async t=>Y(await nu(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:x.object({repoRoot:x.string().optional()})},async t=>Y(await eu(t))),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:x.object({repoRoot:x.string().optional(),boardId:x.string().optional()})},async t=>Y(await tu(t))),e.registerTool("epiq_swimlane_create",{description:"Create an Epiq swimlane on a board",inputSchema:x.object({repoRoot:x.string().optional(),boardId:x.string().min(1),title:x.string().min(1)})},async t=>Y(await au(t))),e.registerTool("epiq_swimlane_title_edit",{description:"Edit an Epiq swimlane title",inputSchema:x.object({repoRoot:x.string().optional(),swimlaneId:x.string().min(1),title:x.string().min(1)})},async t=>Y(await du(t))),e.registerTool("epiq_swimlane_move",{description:"Move/reorder an Epiq swimlane, optionally to another board",inputSchema:x.object({repoRoot:x.string().optional(),swimlaneId:x.string().min(1),boardId:x.string().min(1),position:x.discriminatedUnion("at",[x.object({at:x.literal("start")}),x.object({at:x.literal("end")}),x.object({at:x.literal("before"),sibling:x.string().min(1)}),x.object({at:x.literal("after"),sibling:x.string().min(1)})]).optional()})},async t=>Y(await cu(t))),e.registerTool("epiq_swimlane_delete",{description:"Delete (archive) an Epiq swimlane. This also archives every issue contained in it.",inputSchema:x.object({repoRoot:x.string().optional(),swimlaneId:x.string().min(1)})},async t=>Y(await lu(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:x.object({title:x.string().min(1),parentId:x.string().min(1),repoRoot:x.string().optional(),description:x.string().optional(),tagNames:x.array(x.string()).optional(),assigneeNames:x.array(x.string()).optional()})},async t=>Y(await ou(t))),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:x.object({issueId:x.string().min(1),description:x.string(),repoRoot:x.string().optional()})},async t=>Y(await pu(t))),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:x.object({issueId:x.string().min(1),title:x.string().min(1),repoRoot:x.string().optional()})},async t=>Y(await gu(t))),e.registerTool("epiq_issue_tag_add",{description:"Add a tag to an Epiq issue, creating the tag if it does not exist",inputSchema:x.object({issueId:x.string().min(1),tagName:x.string().min(1),repoRoot:x.string().optional()})},async t=>Y(await fu(t))),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:x.object({issueId:x.string().min(1),tagId:x.string().min(1),repoRoot:x.string().optional()})},async t=>Y(await vu(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:x.object({boardId:x.string().min(1).optional(),repoRoot:x.string().optional()})},async t=>Y(await Iu(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:x.object({contributorId:x.string().min(1),repoRoot:x.string().optional()})},async t=>Y(await bu(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:x.object({contributorId:x.string().min(1),repoRoot:x.string().optional()})},async t=>Y(await xu(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:x.object({issueId:x.string().min(1),assigneeId:x.string().min(1).optional(),self:x.boolean().optional(),assigneeName:x.string().min(1).optional(),createUnlinked:x.boolean().optional(),repoRoot:x.string().optional()})},async t=>Y(await yu(t))),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:x.object({issueId:x.string().min(1),assigneeId:x.string().min(1),repoRoot:x.string().optional()})},async t=>Y(await Eu(t))),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:x.object({issueId:x.string().min(1),body:x.string().min(1),repoRoot:x.string().optional()})},async t=>Y(await Nu(t))),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:x.object({commentId:x.string().min(1),repoRoot:x.string().optional()})},async t=>Y(await Ru(t))),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:x.object({issueId:x.string().min(1),repoRoot:x.string().optional()})},async t=>Y(await su(t))),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:x.object({issueId:x.string().min(1),repoRoot:x.string().optional()})},async t=>Y(await ru(t))),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane",inputSchema:x.object({issueId:x.string().min(1),parentId:x.string().min(1),position:x.discriminatedUnion("at",[x.object({at:x.literal("start")}),x.object({at:x.literal("end")}),x.object({at:x.literal("before"),sibling:x.string().min(1)}),x.object({at:x.literal("after"),sibling:x.string().min(1)})]).optional(),repoRoot:x.string().optional()})},async t=>Y(await iu(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:x.object({repoRoot:x.string().optional()})},async t=>Y(await uu(t))),e},Au=async()=>{let e=Su(),t=new mv;await e.connect(t)};await Au()});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;await wu().then(()=>Tu);