epiq 1.8.0 → 1.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gui/main.js +3005 -2800
- package/dist/index.js +72 -70
- package/dist/mcp.js +65 -63
- package/package.json +5 -5
- package/readme.md +13 -1
package/dist/mcp.js
CHANGED
|
@@ -1,73 +1,75 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`,"utf8"),
|
|
4
|
-
`);u(n?{stdout:d,stderr:
|
|
5
|
-
`)))}),
|
|
6
|
-
`)));return}u(
|
|
7
|
-
${
|
|
8
|
-
${
|
|
9
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(
|
|
10
|
-
${
|
|
11
|
-
${s.message}`);let d=await
|
|
12
|
-
`+
|
|
13
|
-
`+
|
|
14
|
-
|
|
15
|
-
`+t.message);let
|
|
16
|
-
`).filter(Boolean).filter(d=>d
|
|
17
|
-
${
|
|
18
|
-
`);if(n[n.length-1]===""&&n.pop(),n.length<=
|
|
2
|
+
var Gf=Object.defineProperty;var h=(e,t)=>()=>(e&&(t=e(e=0)),t);var Jr=(e,t)=>{for(var n in t)Gf(e,n,{get:t[n],enumerable:!0})};var hc={};Jr(hc,{failed:()=>i,isFail:()=>a,isSuccess:()=>wt,resultStatuses:()=>Vt,succeeded:()=>l});var Vt,i,l,a,wt,R=h(()=>{"use strict";Vt={Success:"success",Fail:"fail"},i=e=>({status:Vt.Fail,message:e,value:null}),l=(e,t)=>({status:Vt.Success,message:e,value:t}),a=e=>e.status==="fail",wt=e=>e.status==="success"});var bc={};Jr(bc,{ACTOR_ID_ENV:()=>zo,ACTOR_NAME_ENV:()=>lt,applyActorNameArgument:()=>Ti,deriveActorId:()=>yc,isValidUserId:()=>Qr,isValidUserName:()=>Vo,resolveEnvActor:()=>wi});import zf from"node:crypto";var lt,zo,vc,Vf,Ci,Qr,Vo,io,yc,wi,Ti,Mn=h(()=>{"use strict";R();lt="EPIQ_USER_NAME",zo="EPIQ_USER_ID",vc="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Vf=26,Ci=80,Qr=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),Vo=e=>e.trim().length>0&&e.length<=Ci,io=e=>e.trim().toLowerCase(),yc=e=>{let t=zf.createHash("sha256").update(`epiq:actor:${io(e)}`).digest(),n="";for(let o=0;o<Vf;o++)n+=vc[(t[o]??0)%vc.length];return n},wi=(e,t=process.env)=>{let n=(t[lt]??"").trim(),o=(t[zo]??"").trim();return n?Vo(n)?!o&&e.userId&&e.userName&&io(e.userName)===io(n)?l("Actor override names the configured user",{userId:e.userId,userName:e.userName}):o&&!Qr(o)?i(`${zo} must be 26 characters of Crockford base32`):o&&e.userId&&o===e.userId?i(`${zo} is the configured user's own id; using it under a different name would rename them on the board`):l("Resolved actor from environment",{userId:o||yc(n),userName:o?n:io(n)}):i(`${lt} must be 1-${Ci} characters of text`):o?i(`${zo} is set without ${lt}`):l("No actor override",null)},Ti=(e,t,n=process.env)=>{let o=e.trim();if(!Vo(o))return i(`${t} must be 1-${Ci} characters of text`);let r=(n[lt]??"").trim();return r&&io(r)!==io(o)?i(`${t} names ${o}, but ${lt} names ${r}`):(n[lt]=o,l("Applied actor name argument",o))}});import{decodeTime as Ic}from"ulid";var Zr,Mi,Ze,Ko,xc,Yo,et=h(()=>{"use strict";R();Zr=1440*60*1e3,Mi=(e,t=Date.now())=>e>t+Zr?t:e,Ze=e=>Mi(Ic(e)),Ko=e=>{let t=Date.now()+Zr,n=e.find(r=>r!==null&&r<=t)??null;if(n===null)return[...e];let o=null;return e.map(r=>{if(r===null)return null;let s=r<=t?r:o??n;return o=s,s})},xc=e=>{try{return l("Decoded date",new Date(Ze(e)))}catch(t){return i("Decoding failed + "+t.message)}},Yo=e=>{if(!e?.id)return null;try{return Ic(e.id)}catch{return null}}});var es,tt,Ec,Tt=h(()=>{"use strict";R();es="removed",tt=(e,t)=>{let n=e.find(o=>o.context===t);return n!==void 0?l("Found node",n):i("Unable to find node in breadcrumb")},Ec=["png","jpg","gif","webp"]});function ki(e){return e.context===z.WORKSPACE}function k(e){return e.context===z.TICKET}function Rc(e){return e.context===z.TEXT}function nt(e){return e.context===z.FIELD}function Xo(e){return e.context===z.FIELD_LIST}var z,pn,Jo,Qo,V=h(()=>{"use strict";z={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};pn=e=>e.context===z.SWIMLANE,Jo=e=>e.context===z.BOARD,Qo=e=>e.context===z.COMMENT});var y,me=h(()=>{"use strict";y={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var Sc=h(()=>{"use strict";kn()});import Nc from"string-width";function ts(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}var Pn,Kf,Pi,Yf,Li,pe,ot=h(()=>{"use strict";Pn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Kf=/\u001B\[[0-9;]*m/,Pi="\x1B[0m",Yf=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),Li=(e,t)=>{if(t<=0)return"";if(Nc(e)<=t)return e;if(t<=3)return"...".slice(0,t);let o=t-3,r="",s=0,d=!1;for(let c of e.split(/(\u001B\[[0-9;]*m)/))if(c!==""){if(Kf.test(c)){r+=c,d=c!==Pi&&c!=="\x1B[m";continue}for(let u of Yf(c)){let m=Nc(u);if(s+m>o)return`${r}...${d?Pi:""}`;r+=u,s+=m}}return`${r}...${d?Pi:""}`},pe=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var Ac,Cc,wc=h(()=>{"use strict";Ac=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},Cc=(e,t)=>t?e.get(t)??[]:[]});var Tc,Xf,Mc,kc=h(()=>{"use strict";ot();wc();Tc=new WeakMap,Xf=e=>{let t=Tc.get(e);return t||(t=Ac(e),Tc.set(e,t)),t},Mc=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let o=t.toLowerCase();return Cc(Xf(e),o).filter(s=>ts(o,s)>=n)}});var Jf,Pc,Qf,Lc=h(()=>{"use strict";ot();kc();Jf={hint:"",hints:[],overlap:0,remainder:""},Pc=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},o)=>{if(n||e==="")return Jf;let r=Mc({wordList:o,inputToMatch:e,overlapThreshold:1});return Qf(t,r)},Qf=(e,t)=>{let n=t[0]??"",o=ts(e.toLowerCase(),n.toLowerCase()),[r,s]=n.split(":"),d=o<(r??"").length,c=!!s,p=(c&&d?r:n)+(c&&d?":":" "),f=p.slice(o);return{hint:p,hints:t,overlap:o,remainder:f}}});import{useSyncExternalStore as RE}from"react";var ns,Zf,eh,Ie,ut,Be=h(()=>{"use strict";ns={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Zf=new Set,eh=()=>{for(let e of Zf)e()},Ie=()=>ns,ut=e=>(ns={...ns,...e},eh(),ns)});function Dc(e){return!e||!nh.test(e)?i(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function mt(e,t=Zo){if(e<0n)return i("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Oe(e,t){if(!e&&!t)return mt(Mt/2n,Zo);let n=e?Dc(e):l("Resolved lower bound",0n);if(a(n))return n;let o=t?Dc(t):l("Resolved upper bound",Mt);if(a(o))return o;let r=n.value,s=o.value;if(s<=r)return i("Neighbouring ranks leave no space between them");let d=(r+s)/2n;return d===r||d===s?i("No rank space available between neighbors"):mt(d,Zo)}function Fc(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let o=0;o<e;o++){let r=Mt*BigInt(o+1)/(t+1n),s=mt(r,Zo);if(a(s))return s;n.push(s.value)}return l("Resolved evenly spaced ranks",n)}var Zo,th,Mt,nh,ao=h(()=>{"use strict";R();Zo=24n,th=Zo*4n,Mt=(1n<<th)-1n,nh=/^[0-9a-f]+$/});import{ulid as oh}from"ulid";var Di,_c=h(()=>{"use strict";R();pt();ao();Di=(e,t)=>{let n=ge(e),o=Fc(n.length);if(a(o))return o;let r={};for(let s=0;s<n.length;s++){let d=n[s],c=o.value[s];if(!d||!c)return i("Unable to assign rebalance rank");r[d.id]=c}return l("Created rebalance event",{id:oh(),action:"rebalance.children",payload:{parent:e,ranks:r},...t})}});import er from"node:fs";import{ulid as rh}from"ulid";import{z as os}from"zod";var sh,ih,rs,Kt,tr,Bc,Yt=h(()=>{"use strict";R();ae();sh="__epiq_state__",ih=os.object({projectId:os.string().min(1),stateBranch:os.string().min(1),createdAt:os.iso.datetime()}),rs=()=>({projectId:rh(),stateBranch:sh,createdAt:new Date().toISOString()}),Kt=e=>{let t=ss(e);if(!er.existsSync(t))return i("Missing .epiq/project.json");try{let n=er.readFileSync(t,"utf8"),o=JSON.parse(n),r=ih.safeParse(o);return r.success?l("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")}},tr=e=>{let t=Kt(e);return a(t)?i(t.message):l("Read projectId",t.value.projectId)},Bc=({repoRoot:e,fileContents:t})=>{let n=Ln(e),o=ss(e);try{if(er.mkdirSync(n,{recursive:!0}),er.existsSync(o)){let r=Kt(e);return a(r)?i(r.message):l("Project already initialized",null)}return er.writeFileSync(o,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,"utf8"),l("Created project.json",null)}catch(r){return i(r instanceof Error?`Failed to initialize project: ${r.message}`:"Failed to initialize project")}}});import ah from"node:os";import dh from"node:path";var St,Xt,is=h(()=>{"use strict";St=".epiq-global",Xt=()=>process.env.EPIQ_GLOBAL_DIR??dh.join(ah.homedir(),St)});var Fi,Oc=h(()=>{"use strict";R();Fi=(e,t)=>{let n=new Map,o=t??((...s)=>JSON.stringify(s)),r=((...s)=>{let d=o(...s);if(!n.has(d)){let c=e(...s).then(u=>(a(u)&&n.delete(d),u));n.set(d,c)}return n.get(d)});return r.clear=()=>n.clear(),r}});var ye,as=h(()=>{"use strict";Nt();ye={stage:({cwd:e,pathspec:t,ignoreRemoval:n=!1})=>q({args:["add",...n?["--ignore-removal"]:[],...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1,pathspec:o})=>q({args:["commit","--no-verify",...n?["--allow-empty"]:[],"-m",t,...o?.length?["--",...o]:[]],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>q({args:["fetch",t,`+refs/heads/${n}:refs/remotes/${t}/${n}`],cwd:e}),rebaseOnto:({cwd:e,ref:t})=>q({args:["-c","rebase.autoStash=true","rebase",t],cwd:e}),checkout:({cwd:e,branch:t})=>q({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:o=!1})=>{let r=t&&n?["push","--no-verify",...o?["-u"]:[],t,n]:["push","--no-verify"];return q({args:r,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>q({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>q({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>q({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>q({args:["worktree","prune"],cwd:e})}});var kt,gt,co=h(()=>{"use strict";Yt();R();ae();kt=e=>{let t=Ue(e);if(a(t))return i("Unable to resolve epiq project root");let n=Kt(t.value);return a(n)?i("Unable to read project.json"):l("Resolved state branch",n.value.stateBranch)},gt="origin"});import{spawn as ch}from"node:child_process";import Dn from"node:fs";import Fn from"node:path";var lh,uh,mh,ph,gh,fh,hh,$c,q,He,lo,_i,vh,ds,_n,Bi,cs,nr,jc,Oi,ls,Hc,Wc,yh,Uc,or,bh,rr,qc,Gc,zc,Vc,Nt=h(()=>{"use strict";R();as();co();lh=1e4,uh=12e4,mh=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),ph=e=>{let t=e.find((n,o)=>!n.startsWith("-")&&e[o-1]!=="-c");return t&&mh.has(t)?uh:lh},gh=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(Fn.delimiter))if(t)for(let n of e){let o=Fn.join(t,n);try{if(!Dn.statSync(o).isFile())continue;return Dn.accessSync(o,Dn.constants.X_OK),o}catch{continue}}return"git"},fh=gh(),hh={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},$c=({args:e,cwd:t,allowFail:n})=>new Promise(o=>{if(!Dn.existsSync(t)){let f=`Git cwd does not exist: ${t}`;if(n){o({stdout:"",stderr:f,exitCode:1});return}o(i(f));return}let r=ch(fh,e,{cwd:t,stdio:["ignore","pipe","pipe"],env:hh}),s=!1,d="",c="",u=f=>{s||(s=!0,clearTimeout(p),o(f))},m=ph(e),p=setTimeout(()=>{r.kill("SIGTERM");let f=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${m}ms`].join(`
|
|
4
|
+
`);u(n?{stdout:d,stderr:f,exitCode:124}:i(f))},m);r.stdout.setEncoding("utf8"),r.stderr.setEncoding("utf8"),r.stdout.on("data",f=>{d+=f}),r.stderr.on("data",f=>{c+=f}),r.on("error",f=>{if(n){u({stdout:d,stderr:f.message,exitCode:1});return}u(i([`git ${e.join(" ")}`,`cwd=${t}`,f.message].join(`
|
|
5
|
+
`)))}),r.on("close",f=>{let x=f??1;if(n){u({stdout:d,stderr:c,exitCode:x});return}if(x!==0){u(i([`git ${e.join(" ")}`,c.trim()||d.trim()||"Git command failed"].filter(Boolean).join(`
|
|
6
|
+
`)));return}u(l("Git command succeeded",{stdout:d,stderr:c,exitCode:x}))})}),q=({args:e,cwd:t})=>$c({args:e,cwd:t,allowFail:!1}),He=({args:e,cwd:t})=>$c({args:e,cwd:t,allowFail:!0}),lo=async({cwd:e,message:t,pathspec:n})=>{let o=await ye.commit({cwd:e,message:t,pathspec:n});if(a(o))return i(`Failed to create commit
|
|
7
|
+
${o.message}`);let r=await q({args:["rev-parse","HEAD"],cwd:e});return a(r)?i(`Commit created, but failed to read HEAD SHA
|
|
8
|
+
${r.message}`):l("Created commit and resolved SHA",r.value.stdout.trim())},_i=async e=>{let t=await q({cwd:e,args:["rev-parse","--git-dir"]});if(a(t))return i(t.message);let n=t.value.stdout.trim();return l("Resolved git dir",Fn.isAbsolute(n)?n:Fn.resolve(e,n))},vh=async e=>{let t=await _i(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(Dn.existsSync(Fn.join(n,s)))return l("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(Dn.existsSync(Fn.join(n,s)))return l("Checked for in-progress Git operation",d);return l("Checked for in-progress Git operation",null)},ds=async e=>{let t=await vh(e);return a(t)?i(t.message):l("Checked for in-progress Git operation",t.value!==null)},_n=async({repoRoot:e})=>{let n=(await He({args:["remote","get-url",gt],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},Bi=async({repoRoot:e,branch:t})=>{let n=await He({args:["ls-remote","--heads",gt,t],cwd:e});return n.exitCode!==0?i(n.stderr.trim()||`Unable to inspect remote branch ${gt}/${t}`):l("Checked remote branch",n.stdout.trim().length>0)},cs=async({repoRoot:e,branch:t})=>{let n=await He({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?l("Local branch exists",!0):n.exitCode===1?l("Local branch missing",!1):i(n.stderr.trim()||`Unable to inspect branch ${t}`)},nr=e=>{try{return Dn.realpathSync.native(e)}catch{return Fn.resolve(e)}},jc=async({repoRoot:e,worktreeRoot:t})=>{let n=await q({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let o=nr(t),r=n.value.stdout.split(`
|
|
9
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(nr).includes(o);return l("Checked worktree registration",r)},Oi=async e=>{let t=await He({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},ls=async e=>{let t=await q({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?i(t.message):l("Resolved current branch",t.value.stdout.trim())},Hc=async e=>{let t=await q({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?i(t.message):l("Resolved short HEAD sha",t.value.stdout.trim())},Wc=e=>e.includes("fetch first")||e.includes("non-fast-forward"),yh=async e=>(await He({cwd:e,args:["rebase","--abort"]})).exitCode===0?l("Aborted stale rebase",!0):l("No rebase to abort",!1),Uc=async e=>{let t=await He({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},or=e=>/could not resolve host/i.test(e)||/connection refused|connection timed out|operation timed out/i.test(e)||/network is unreachable|no route to host/i.test(e)||/failed to connect to/i.test(e),bh=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),rr=async({cwd:e,branch:t})=>{let n=await yh(e);if(a(n))return i(n.message);let o=await Uc(e),r=await ye.fetch({cwd:e,remote:gt,branch:t});if(a(r))return bh(r.message)?l("Remote branch missing, skipped pull",!1):i(`Failed to fetch ${t}
|
|
10
|
+
${r.message}`);let s=await ye.rebaseOnto({cwd:e,ref:`${gt}/${t}`});if(a(s))return i(`Failed during rebase
|
|
11
|
+
${s.message}`);let d=await Uc(e),c=o!==null&&d!==null&&o!==d;return l(c?"Pulled with rebase":"Already up to date",c)},qc=async e=>{let t=await He({args:["rev-list","--count","@{u}..HEAD"],cwd:e});return t.exitCode!==0?l("No upstream to compare against",!1):l("Compared against upstream",Number(t.stdout.trim())>0)},Gc=async e=>{let t=await He({args:["status","--porcelain","--untracked-files=all"],cwd:e});return t.exitCode!==0?i(t.stderr.trim()||"Unable to inspect the worktree for changes"):l("Inspected worktree for changes",t.stdout.trim().length>0)},zc=async(e,t)=>{let n=await He({args:["diff","--cached","--quiet",...t?.length?["--",...t]:[]],cwd:e});return n.exitCode===0?l("No staged changes",!1):n.exitCode===1?l("Has staged changes",!0):i(n.stderr.trim()||"Unable to inspect staged changes")},Vc=async e=>{let t=await ls(e);return a(t)?i(t.message):l("Checked detached HEAD state",t.value==="HEAD")}});import gn from"node:fs";import ft from"node:path";var Yc,Xc,Jc,Qc,us,ve,Ih,Kc,sr,ms,Zc,Ui,$i,el,tl,rt,yR,We=h(()=>{"use strict";Yt();R();is();ae();Oc();ht();Nt();Yc="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Xc=e=>ft.join(qe,fn,e),Jc=()=>ft.join(qe,ji),Qc=Xt,us=()=>ft.join(Qc(),"worktrees"),ve=({repoRoot:e})=>{let t=tr(e);return a(t)?i(t.message):l("Resolved state branch root",ft.join(us(),t.value))},Ih=e=>ft.join(e,qe),Kc=e=>ft.join(Ih(e),fn),sr=e=>{try{return gn.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return i(t instanceof Error?t.message:String(t))}},ms=()=>{let e=Qc(),t=us(),n=!gn.existsSync(e)||!gn.existsSync(t),o=sr(e);if(a(o))return i(`Ensure epiq home failed.
|
|
12
|
+
`+o.message);let r=sr(t);return a(r)?i(`Ensure worktrees dir failed.
|
|
13
|
+
`+r.message):l("Ensured epiq storage",n)},Zc=e=>{gn.existsSync(e)&&(X.debug("[sync] remove path",e),gn.rmSync(e,{recursive:!0,force:!0}))},Ui=`*.jsonl merge=union
|
|
14
|
+
`,$i=()=>ft.join(qe,fn,".gitattributes"),el=(e,t)=>{for(let o of[Kc(e),Kc(t)]){let r=sr(o);if(a(r))return i(r.message)}let n=ft.join(t,$i());try{gn.readFileSync(n,"utf8")!==Ui&&gn.writeFileSync(n,Ui)}catch{gn.writeFileSync(n,Ui)}return l("Ensured state branch",void 0)},tl=async e=>{let t=await q({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return i(`ensure state branch is storage only failed
|
|
15
|
+
`+t.message);let o=t.value.stdout.trim().split(`
|
|
16
|
+
`).filter(Boolean).filter(d=>d!==qe);if(o.length===0)return l("State branch is storage-only",!1);let r=await q({args:["rm","-r","--ignore-unmatch","--",...o],cwd:e});if(a(r))return i(`Failed to clean storage branch
|
|
17
|
+
${r.message}`);let s=await lo({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:o});return a(s)?i(s.message):l("Cleaned storage branch",!0)},rt=Fi(async(e=process.cwd())=>{let t=await q({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?i("Not inside a Git repository"):l("Resolved repo root",t.value.stdout.trim())},e=>ft.resolve(e)),yR=Fi(async e=>{let t=await q({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return i(t.message);let n=t.value.stdout.trim(),o=ft.isAbsolute(n)?n:ft.join(e,n);return l("Resolved git dir",o)},e=>ft.resolve(e))});import ir from"node:fs";import Pt from"node:path";var NR,qe,fn,ji,xh,Ln,ss,Bn,ps,nl,Eh,ar,gs,Rh,Ue,ol,Lt,ae=h(()=>{"use strict";R();We();is();NR=process.env.IS_LOCAL==="true",qe=".epiq",fn="events",ji="media",xh="project.json",Ln=e=>Pt.join(e,qe),ss=e=>Pt.join(Ln(e),xh),Bn=e=>Pt.join(Ln(e),fn),ps=e=>Pt.join(Ln(e),ji),nl=e=>Pt.join(e,qe),Eh=e=>{let t=Pt.join(e,qe);return ir.existsSync(t)&&ir.statSync(t).isDirectory()},ar=e=>{let t=ss(e);return ir.existsSync(t)&&ir.statSync(t).isFile()},gs=e=>{let t=Pt.resolve(e);for(;;){if(Eh(t))return l("Resolved closest .epiq root",t);let n=Pt.dirname(t);if(n===t)return i("No .epiq directory found in any parent");t=n}},Rh="No .epiq/project.json found in any parent",Ue=e=>{let t=Pt.resolve(e);for(;;){if(ar(t))return l("Resolved closest epiq project root",t);let n=Pt.dirname(t);if(n===t)return i(Rh);t=n}},ol=e=>{let t=Bn(e);try{return ir.mkdirSync(t,{recursive:!0}),l("Resolved events dir",t)}catch(n){return i(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},Lt=async()=>{let e=await rt(process.cwd());if(a(e))return e;let t=ve({repoRoot:e.value});return a(t)?t:l("Resolved persist root",t.value)}});import At from"fs";import zi from"path";import Sh from"util";function wh(e){if(!At.existsSync(e))return;let t=At.statSync(e).size,n=Ch(e,Vi).split(`
|
|
18
|
+
`);if(n[n.length-1]===""&&n.pop(),t<=Vi&&n.length<=rl)return;let o=n.slice(-rl).join(`
|
|
19
19
|
`)+`
|
|
20
|
-
`;
|
|
21
|
-
`;Br.mkdirSync(Ci.dirname(r),{recursive:!0}),Br.appendFileSync(r,l,"utf8"),Ri++,Ri>=If&&(Ri=0,Ef())}var oc,If,Ri,sc,ic,Ni,X,Et=y(()=>{"use strict";C();re();oc=1e3,If=50,Ri=0,sc=()=>process.env.EPIQ_MCP==="true",ic=()=>{let e=process.cwd(),t=Vo(e);return a(t)?sc()?Ci.join(process.cwd(),".epiq-mcp.log"):void 0:Ci.join(t.value,$e,"log","epiq.log")};Ni=()=>sc()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",X={info(...e){let t=Ni();(t==="info"||t==="debug")&&Si("[Info]",e,!1)},debug(...e){Ni()==="debug"&&Si("[Debug]",e,!0)},error(...e){let t=Ni();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;Si("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=X});var ie,tr=y(()=>{"use strict";ie={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var z,_r,tn=y(()=>{"use strict";z=e=>e.slice(-7).toUpperCase(),_r=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?z(e).includes(n):!0}});var Ne,An=y(()=>{"use strict";ge();tn();Ne={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:_.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:z(e)},context:_.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:_.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:d=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:_.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:d}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:_.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:z(e)},context:_.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:_.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:d=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:_.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:d})}});var Rf,ye,Ko,nr=y(()=>{"use strict";Rf=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ye,Ko]=Rf});function nn(e,t=!1){let n=Mf[e.action];if(!n)return i(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);if(!ot()&&e.action!=="init.workspace")return L(`${e.action} arrived before the workspace was initialized`,e);if(e.action==="init.workspace"&&je){if(je.genesisApplied)return L("the workspace is already initialized",e);je.genesisApplied=!0}let r;try{r=n(e)}catch(s){return L(`threw while materializing (${s instanceof Error?s.message:String(s)})`,e)}if(a(r))return r;let o=wf(e,t);return o||r}var Ai,L,$r,Tn,wn,ac,dc,Sf,Nf,Ti,Cf,Af,je,Tf,wf,Ur,Mf,Bt,_t=y(()=>{"use strict";Et();ge();C();tr();me();An();k();wi();nr();Ai=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),L=(e,t)=>({...Ai(e,t),convergence:!0}),$r=e=>a(e)&&e.convergence===!0,Tn=e=>{let t=e.filter(a);return{fatal:t.filter(n=>!$r(n)),skipped:t.filter($r)}},wn=e=>{e.length!==0&&X.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},ac=e=>{let t=x.getNode(e);if(!t||!P(t)||t.isDeleted)return null;let n=zo(t);return a(n)?n:null},dc=e=>{if(!Yo())return null;for(let t of e){let n=ac(t);if(n)return n;let r=f().nodes[t]?.parentNodeId;if(!r)continue;let o=ac(r);if(o)return o}return null},Sf=(e,t)=>{let n=x.getNode(e);n&&x.updateNode({...n,log:[...n.log??[],t]})},Nf=e=>{let t=[e],n=f().nodes[e]?.parentNodeId;return n&&t.push(n),t},Ti=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 Nf(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"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":default:return[]}},Cf=e=>{Ie(t=>({...t,eventLog:[...t.eventLog,e]}))},Af=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?Ai("Invalid user ID format",e):c("Valid user",null)},je=null,Tf=e=>{for(let[t,n]of e.nodeLog){let r=x.getNode(t);r&&x.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&Ie(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),dc([...e.virtualNodeIds])},wf=(e,t)=>{let n=Af(e);if(a(n))return n;let r=[...new Set(Ti(e))];if(je){for(let s of r){if(!t){let d=je.nodeLog.get(s);d?d.push(e):je.nodeLog.set(s,[e])}if(Yo()){je.virtualNodeIds.add(s);let d=f().nodes[s]?.parentNodeId;d&&je.virtualNodeIds.add(d)}}return t||je.appLog.push(e),null}t||(r.forEach(s=>Sf(s,e)),Cf(e));let o=dc(r);return o||null},Ur=(e,t,n)=>x.getNode(e)?L(`a node with id ${e} already exists`,n):t===e?L("a node cannot be its own parent",n):null,Mf={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Ne.workspace(t,n,r),s=jr(o);if(a(s))return Ai(s.message,e);let d=x.createNode(o);return a(d)?L(d.message??"Failed to initialize workspace",e):ci(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:r}=e.payload,o=Ur(t,void 0,e);if(o)return o;let s=x.createNode(Ne.workspace(t,n,r));return a(s)?L(s.message??"Failed to add workspace",e):ci(s.value)?c("Added workspace",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Ur(t,r,e);if(s)return s;let d=x.createNode(Ne.board(t,n,r,o));return a(d)?L(d.message??"Unable to create board",e):Lo(d.value)?c("Added board",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Ur(t,r,e);if(s)return s;let d=x.createNode(Ne.swimlane(t,n,r,o));return a(d)?L(d.message??"Unable to create swimlane",e):bn(d.value)?c("Added swimlane",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Ur(t,r,e);if(s)return s;let d=x.createNode(Ne.ticket(t,n,r,o));return a(d)?L(d.message??"Unable to create issue",e):P(d.value)?c("Added issue",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,d=Ur(t,r,e);if(d)return d;let l=x.createNode(Ne.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(ie.DESCRIPTION)?"vertical":"horizontal"}));return a(l)?L(l.message??`Unable to create field: ${n}`,e):Ye(l.value)?c("Added field",{action:e.action,result:l.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 o=x.renameNode(t,n);return a(o)?L(o.message??"Unable to edit title",e):c("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=x.tombstoneNode(t);return 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,r=x.createTag({id:t,name:n});return a(r)?L(r.message??"Unable to create tag",e):c("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=x.tombstoneTag(t);return a(n)?L(n.message??"Unable to delete tag",e):c("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=x.restoreTag(t,n);return a(r)?L(r.message??"Unable to restore tag",e):c("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=x.createContributor({id:t,name:n});return a(r)?L(r.message??"Unable to create contributor",e):c("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=x.renameContributor(t,n);return a(r)?L(r.message??"Unable to rename contributor",e):c("Contributor renamed",{action:e.action,result:r.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,r=x.restoreContributor(t,n);return a(r)?L(r.message??"Unable to restore contributor",e):c("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=x.tag(t,n);return a(r)?L(r.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,r=x.untag(t,n);return a(r)?L(r.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,r=x.assign(t,n);return a(r)?L(r.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,r=x.unassign(t,n);return a(r)?L(r.message??"Unable to unassign issue",e):c("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=x.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?L(o.message??"Failed to move node",e):c("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=x.editValue(t,n);return a(r)?L(r.message??"Unable to edit description",e):c("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=x.getNode(t);if(!o)return L("Unable to locate issue",e);if(!P(o))return L("Can only close issues",e);let s=x.getNode(ye);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:r});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:r}=e.payload,o=x.getNode(t);if(!o)return L("Unable to locate issue",e);if(!P(o))return L("Can only reopen issues",e);let s=x.getNode(ye);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:r});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[r,o]of Object.entries(n)){let s=x.getNode(r);if(!s)return L(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return L(`Node ${r} is not child of ${t}`,e);let d=x.updateNode({...s,rank:o});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:r,md:o}=e.payload,s=x.createComment({id:t,issue:n,authorId:r,authorName:x.getContributor(r)?.name??"Unknown",md:o,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:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=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 s=x.editComment(t,r);return a(s)?L(s.message??"Unable to edit comment",e):c("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=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 o=x.deleteComment(t);return a(o)?L(o.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:r,ext:o,name:s,bytes:d}=e.payload,l=x.createAttachment({id:t,issue:n,hash:r,ext:o,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:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=x.getAttachment(t);if(!r)return L("Unable to locate attachment",e);if(r.issue!==n)return L("Attachment does not belong to issue",e);let o=x.deleteAttachment(t);return a(o)?L(o.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=cc(()=>{let n=je===null;n&&(je={appLog:[],nodeLog:new Map,virtualNodeIds:new Set,genesisApplied:!1});try{let r=e.map(o=>nn(o));if(n&&je){let o=Tf(je);if(o)return e.map(()=>o)}return r}finally{n&&(je=null)}});return a(t)?e.map(()=>i(t.message)):t.value}});var Mi,lc=y(()=>{"use strict";Mi=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown"});import{existsSync as kf,readdirSync as Lf,statSync as Pf}from"node:fs";import Df from"node:path";var Mn,uc,ki,rn,mc,pc,gc,Hr=y(()=>{"use strict";re();Mn=e=>{let t=Cn(e);return kf(t)?Lf(t).filter(n=>n.endsWith(".jsonl")).sort().map(n=>{let{size:r,mtimeMs:o}=Pf(Df.join(t,n));return`${n}:${r}:${o}`}).join("|"):"none"},uc=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),ki=(e,t,n)=>{let r=uc(t),o=Mn(e),s=uc(o);for(let[d,l]of s)if(d!==n&&r.get(d)!==l)return null;for(let d of r.keys())if(d!==n&&!s.has(d))return null;return o},rn=null,mc=e=>rn&&rn.root===e?rn.signature:null,pc=(e,t)=>{rn={root:e,signature:t}},gc=(e,t)=>{if(!rn||rn.root!==e)return;let n=ki(e,rn.signature,t);rn=n===null?null:{root:e,signature:n}}});var Ff,Of,fc,hc,Li=y(()=>{"use strict";Ff=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","tombstone.tag","restore.tag","create.contributor","rename.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"],Of=new Set(Ff),fc=e=>Of.has(e),hc=e=>({action:e.action,payload:e.payload})});import{z as V}from"zod";var W,pt,on,Xo,Pi,Bf,vc,yc=y(()=>{"use strict";C();W=V.string().min(1),pt=V.string(),on=V.string(),Xo=V.looseObject({id:W}),Pi=V.looseObject({id:W,name:pt,parent:W,rank:on}),Bf={"init.workspace":V.looseObject({id:W,name:pt,rank:on}),"add.workspace":V.looseObject({id:W,name:pt,rank:on}),"add.board":Pi,"add.swimlane":Pi,"add.issue":Pi,"add.field":V.looseObject({id:W,name:pt,parent:W,rank:on}),"edit.title":V.looseObject({id:W,name:pt}),"delete.node":Xo,"lock.node":Xo,"move.node":V.looseObject({id:W,parent:W,rank:on}),"edit.description":V.looseObject({id:W,md:V.string()}),"close.issue":V.looseObject({id:W,parent:W,rank:on}),"reopen.issue":V.looseObject({id:W,parent:W,rank:on}),"create.tag":V.looseObject({id:W,name:pt}),"tombstone.tag":Xo,"restore.tag":V.looseObject({id:W,name:pt}),"create.contributor":V.looseObject({id:W,name:pt}),"rename.contributor":V.looseObject({id:W,name:pt}),"tombstone.contributor":Xo,"restore.contributor":V.looseObject({id:W,name:pt}),"link.contributor.user":V.looseObject({contributor:W}),"add.issue.assignee":V.looseObject({id:W,assignee:W}),"remove.issue.assignee":V.looseObject({id:W,assignee:W}),"add.issue.tag":V.looseObject({id:W,tag:W}),"remove.issue.tag":V.looseObject({id:W,tag:W}),"add.issue.comment":V.looseObject({id:W,issue:W,md:V.string()}),"edit.issue.comment":V.looseObject({id:W,issue:W,md:V.string()}),"delete.issue.comment":V.looseObject({id:W,issue:W}),"add.issue.attachment":V.looseObject({id:W,issue:W,hash:V.string().min(1),ext:V.string().min(1),name:pt,bytes:V.number()}),"delete.issue.attachment":V.looseObject({id:W,issue:W}),"rebalance.children":V.looseObject({parent:W,ranks:V.record(V.string(),on)})},vc=(e,t)=>{let r=Bf[e].safeParse(t);return r.success?c("Payload is readable",void 0):i(`${e}: ${r.error.issues.map(o=>`${o.path.join(".")||"payload"} ${o.message}`).join(", ")}`)}});import Qo from"node:fs";import Zo from"node:path";import{decodeTime as _f}from"ulid";import{z as Di}from"zod";function Wr(e,t){let n=Cn(e),r=Mn(e);if(!Qo.existsSync(n))return c("No events found",[]);let o=Qo.readdirSync(n).filter(l=>l.endsWith(".jsonl")).map(l=>Zo.join(n,l)),s=[];for(let l of o){let u=Kf(l,t);if(a(u))return i(u.message);s.push(...u.value)}let d=Yf(s);return Ut={root:e,signature:r,edge:d.at(-1)?.id?.[0]??null},c("All events loaded",d)}function $t(e){let t=[],n=Wr(e,t);if(a(n))return i(n.message);let r=Oi(n.value,t);return a(r)?i(r.message):(zf=t,c("Loaded merged events",{events:r.value,unreadable:t}))}function Bi(e){let t=Wr(e);return a(t)?i(t.message):c("Loaded event actors",t.value.map(({userId:n,userName:r})=>({userId:n,userName:r})))}function kn(e){let t=$t(e);return a(t)?i(t.message):c("Loaded merged events",t.value.events)}function _i(e,t){let n=Wr(e);if(a(n))return i(n.message);let{appliedEvents:r,unappliedEvents:o}=Xf(n.value,t),s=Oi(r);if(a(s))return i(s.message);let d=Oi(o);return a(d)?i(d.message):c("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function bc(e=process.cwd()){let t=Mn(e);if(Ut&&Ut.root===e&&Ut.signature===t)return c("Loaded edge reference, unchanged",Ut.edge);let n=Wr(e);return a(n)?i(n.message):c("Loaded edge reference",n.value.at(-1)?.id?.[0]??null)}function xc(e,t,n){if(!Ut||Ut.root!==e)return;let r=ki(e,Ut.signature,t);Ut=r===null?null:{root:e,signature:r,edge:n}}function Ui(e){let t=Wr(e);if(a(t))return i(t.message);let n=Ic(t.value);return c("Loaded effective event times",new Map(t.value.map((r,o)=>[r.id[0],n[o]??null])))}var Uf,Jo,$f,jf,Hf,Wf,Gf,qf,Vf,Oi,Kf,zf,Ut,Fi,Yf,Ic,Xf,jt=y(()=>{"use strict";Et();C();re();Hr();dt();Li();gt();yc();Uf=Di.object({userId:Di.string().min(1).default("unknown"),userName:Di.string().min(1).default("unknown")}),Jo=e=>{let t=Object.entries(e).filter(([o])=>o!=="id"&&o!=="v"&&o!=="userId"&&o!=="userName");if(t.length!==1)return null;let n=t[0]?.[1];if(typeof n!="object"||n===null)return null;let r=n.id;return typeof r=="string"&&r.length>0?r:null},$f=/^[0-9a-hjkmnp-tv-z]{26}$/i,jf=e=>$f.test(e)?e.toUpperCase():e,Hf=e=>{let t=Zo.basename(e,".jsonl"),n=t.indexOf("."),r=n===-1?t:t.slice(0,n),o=n===-1?void 0:t.slice(n+1),s=Uf.safeParse({userId:jf(r),userName:o});return s.success?c("Parsed event file actor",s.data):i(`Invalid event file name ${Zo.basename(e)}: ${s.error.issues.map(d=>d.path.join(".")||d.message).join(", ")}`)},Wf=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])},Gf=(e,t)=>t in e,qf=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Vf=e=>{let{userId:t,userName:n,...r}=e,o=Wf(r);if(a(o))return i(o.message);let s=o.value,d=e.id?.[0];return d?Gf(r,s)?c("Decoded persisted event",qf({id:d,action:s,payload:r[s],userId:t,userName:n})):i(`Persisted event is missing payload for action: ${s}`):i("Persisted event is missing id")},Oi=(e,t)=>{let n=[],r=new Map,o=new Map;for(let s of e){if(!Rc(s.v)){o.set(s.v,(o.get(s.v)??0)+1),t?.push({eventId:s.id[0],reason:"unsupported-schema-version",detail:`v${s.v}`,targetNodeId:Jo(s)});continue}let d=Vf(s);if(a(d)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:d.message,targetNodeId:Jo(s)});continue}let l=d.value.action;if(!fc(l)){r.set(l,(r.get(l)??0)+1),t?.push({eventId:s.id[0],reason:"unknown-action",detail:l,targetNodeId:Jo(s)});continue}let u=vc(l,d.value.payload);if(a(u)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:u.message,targetNodeId:Jo(s)});continue}n.push(d.value)}if(r.size>0){let s=[...r.entries()].map(([d,l])=>`${d} (x${l})`).join(", ");X.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${s}. Upgrade to apply them.`)}if(o.size>0){let s=[...o.entries()].map(([d,l])=>`v${d} (x${l})`).join(", ");X.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${s}. Upgrade to apply them.`)}return c("Decoded reconstructed events",n)},Kf=(e,t)=>{if(!Qo.existsSync(e))return c("Event file missing",[]);let n=Hf(e);if(a(n))return i(n.message);let r=Qo.readFileSync(e,"utf8"),o=[],s=Zo.basename(e),d=(l,u)=>{t?.push({eventId:null,reason:"corrupt-line",detail:`${s}:${l} (${u})`,targetNodeId:null})};for(let[l,u]of r.split(`
|
|
22
|
-
`).entries()){let m=u.trim();if(!m)continue;let p;try{p=JSON.parse(m)}catch{d(l+1,"invalid JSON");continue}let g=Ec(p);if(a(g)){d(l+1,g.message);continue}o.push({...g.value,userId:n.value.userId,userName:n.value.userName})}return c("Parsed persisted events file",o)};zf=[];Ut=null;Fi=(e,t)=>{let n=e.id[0].localeCompare(t.id[0]);return n!==0?n:JSON.stringify(e).localeCompare(JSON.stringify(t))},Yf=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],g=m.id[1]??null;t.set(p,m);let I=n.get(g)??[];I.push(m),n.set(g,I)}for(let m of n.values())m.sort(Fi);let r=[],o=new Set,s=m=>{let p=[m];for(;p.length>0;){let g=p.pop(),I=g.id[0];if(o.has(I))continue;r.push(g),o.add(I);let N=n.get(I)??[];for(let A=N.length-1;A>=0;A--)p.push(N[A])}},d=(n.get(null)??[]).filter(m=>{let p=Object.keys(m).filter(g=>g!=="id"&&g!=="v"&&g!=="userId"&&g!=="userName");return p.length===1&&p[0]==="init.workspace"});for(let m of d)s(m);let l=e.filter(m=>{let p=m.id[0],g=m.id[1]??null;return o.has(p)?!1:g===null||!t.has(g)}).sort(Fi);for(let m of l)s(m);let u=e.filter(m=>!o.has(m.id[0])).sort(Fi);for(let m of u)s(m);return r},Ic=e=>Nr(e.map(t=>{try{return _f(t.id[0])}catch{return null}}));Xf=(e,t)=>{let n=new Set,r=[],o=[],s=Ic(e);for(let d=0;d<e.length;d++){let l=e[d],u=l.id[0],m=l.id[1],p=s[d]??null;!(p!==null&&p<t)||m&&n.has(m)?(n.add(u),o.push(l)):r.push(l)}return{appliedEvents:r,unappliedEvents:o}}});import Jf from"node:fs";import Nc from"node:path";import{decodeTime as Qf,monotonicFactory as Zf}from"ulid";import{z as Ln}from"zod";function $i(e,t){let n;if(t&&t.current!==void 0)n=t.current;else{let o=bc(e);if(a(o))return i(o.message);n=o.value}let r=n?Sc(nh(n)):Sc();return c("Minted event id",[r,n])}function es({event:e,rootDir:t,edge:n,id:r}){try{let o=rc(t);if(a(o))return o;let s=dh(t,{userId:e.userId,userName:e.userName});if(a(s))return s;let d=r?c("Minted event id",r):$i(t,n);if(a(d))return i(d.message);let[l,u]=d.value,m=ch(hc(e),[l,u]);if(a(m))return i(m.message);Jf.appendFileSync(s.value,`${JSON.stringify(m.value)}
|
|
23
|
-
`,"utf8"),n&&(n.current=l);let p=Nc.basename(s.value);return xc(t,p,l),gc(t,p),c("Event persisted",{path:s.value,entry:m.value})}catch(o){let s=o instanceof Error?o.message:"Unknown persist error";return i(`Failed to persist event: ${s}`)}}var Cc,Sc,eh,th,nh,Ac,rh,oh,Ec,sh,ih,Rc,ah,fe,Pn,dh,ch,gt=y(()=>{"use strict";Et();Qn();C();Be();re();lc();dt();jt();Hr();Li();Cc=1,Sc=Zf(),eh=0xffffffffffff,th=Mo,nh=e=>{let t=Date.now(),n;try{n=Qf(e)}catch{return t}return n>=eh?t:n>t+th?(X.error("[persist] edge id is too far in the future; seeding from the wall clock instead",{edgeRef:e,edgeTime:n,now:t}),t):Math.max(t,n+1)},Ac=Ln.tuple([Ln.string().min(1),Ln.string().min(1).nullable()]),rh=Ln.looseObject({v:Ln.literal(Cc),id:Ac}),oh=Ln.looseObject({v:Ln.number().int().positive(),id:Ac}),Ec=e=>{let t=oh.safeParse(e);return t.success?c("Parsed persisted event envelope",t.data):i(`Invalid persisted event envelope: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},sh=[1],ih=new Set(sh),Rc=e=>ih.has(e),ah=e=>{let t=rh.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(", ")}`)},fe=()=>{let{userName:e,userId:t}=ve();return e?t?wo(t)?Sr(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")},Pn=({userId:e,userName:t})=>`${Mi(e)}.${Mi(t)}.jsonl`,dh=(e,{userId:t,userName:n})=>{let r=Pn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return i(`Invalid event log file name: ${r}`);let s=Nc.join(Cn(e),r);return c("Successfully resolved event log path",s)},ch=(e,t)=>{let n={[e.action]:e.payload,v:Cc,id:t};return ah(n)}});import{ulid as lh}from"ulid";function Tc(e,t,n){let r=$i(t,n);if(a(r))return i(r.message);let o={...e,id:r.value[0]},s=nn(o);if(s.status!==Dt.Success)return s;let d=es({event:o,rootDir:t,edge:n,id:r.value});return a(d)?d:s}function B(e,t){if(e.length===0||!e[0])return i("No events provided");if(f().readOnly)return i(f().readOnlyReason??"Cannot change the board while time travelling");let n={},r=uh(e[0],t,n);if(a(r))return r;let o=e.map(d=>Tc(d,t,n)),s=o.filter(a);return s.length>0?i("Materialize and persist failed: "+s.map(d=>d.message).join(", ")):c("Materialization succeeded",o.map(d=>d.value))}var uh,Dn=y(()=>{"use strict";C();me();k();_t();gt();uh=(e,t,n)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return c("Contributor write already in flight",void 0);let r=x.getContributor(e.userId),o={id:lh(),action:r?"rename.contributor":"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName};if(r&&(r.tombstoned||r.name===e.userName))return c("Contributor name is current",void 0);let s=Tc(o,t,n);return a(s)?i(s.message):c("Contributor name recorded",void 0)}});var Fn,ji,wc=y(()=>{"use strict";tn();Fn=e=>e.trim().toLocaleLowerCase(),ji=(e,t)=>Fn(e).includes(Fn(t))});var mh,ph,Mc,kc,gh,fh,Lc,Pc=y(()=>{"use strict";k();tn();wc();mh=e=>{let{tags:t}=f();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},ph=e=>{let{contributors:t}=f();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},Mc=null,kc=new Map,gh=()=>{let e=f().eventLog??[];if(e===Mc)return kc;let t=new Map;for(let n of e){if(!n.userId)continue;let r=n.payload;for(let o of[r.id,r.issue]){if(typeof o!="string")continue;let s=t.get(o)??new Set;s.add(n.userId),t.set(o,s)}}return Mc=e,kc=t,t},fh=e=>{let{contributors:t}=f(),n=gh().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},Lc=(e,t)=>{let n=Fn(t.value);if(!n)return!0;switch(t.target){case"title":return ji(e.title??"",n);case"description":return ji(e.props.description??"",n);case"tag":return mh(e).map(Fn).some(o=>o.includes(n));case"assignee":return ph(e).map(Fn).some(o=>o.includes(n));case"actor":return fh(e).map(Fn).some(o=>o.includes(n));case"ref":return _r(e.id,t.value);default:return!0}}});var Dc,hh,Fc,Oc,Hi=y(()=>{"use strict";ge();Pc();Dc=(e,t)=>e.rank.localeCompare(t.rank),hh=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,Fc=(e,t)=>Object.values(e).filter(n=>hh(n,t)).sort(Dc),Oc=(e,t)=>{let n={};for(let r of Object.values(e)){if(P(r)&&t.length>0&&!t.every(s=>Lc(r,s))||!r.parentNodeId||r.isDeleted)continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(Dc);return n}});var Bc,ts,ue,_c,Uc,sn,On,It=y(()=>{"use strict";Od();Dn();C();k();Hi();Zn();Bc=e=>ts(ue(e),{at:"end"}),ts=(e,t={at:"end"})=>{let n=o=>a(o)?c("Rank space exhausted",{rank:"",needsRebalance:!0}):c("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(_e(void 0,void 0));let r=()=>n(_e(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(_e(void 0,o.rank)):i("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(_e(o.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let o=_c(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let d=o>0?e[o-1]:void 0;return n(_e(d?.rank,s.rank))}case"after":{let o=_c(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let d=o<e.length-1?e[o+1]:void 0;return n(_e(s.rank,d?.rank))}}},ue=e=>{let t=f();if(!$c()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return Fc(t.nodes,e)},_c=(e,t)=>e.findIndex(n=>n.id===t),Uc=(e,t,n={at:"end"})=>ts(ue(t).filter(r=>r.id!==e),n),sn=(e,t,n,r,o)=>{let s=Uc(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return c("Resolved rank",s.value.rank);let d=mi(e,r);if(a(d))return d;let l=B([d.value],o);if(a(l))return l;let u=Uc(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)},On=(e,t,n)=>{let r=Bc(e);if(a(r))return r;if(!r.value.needsRebalance)return c("Resolved rank",r.value.rank);let o=mi(e,t);if(a(o))return o;let s=B([o.value],n);if(a(s))return s;let d=Bc(e);return a(d)?d:d.value.needsRebalance?i("Rank rebalance failed to create space"):c("Resolved rank after rebalance",d.value.rank)}});var U,jc,Hc,Je=y(()=>{"use strict";k();U={exit(){process.exit(0)},enterChildNode(){let e=f(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=ae(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||U.navigate({contextNode:o,selectedIndex:ae(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=f();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=ae(n.id),o=r.findIndex(({id:d})=>d===e.id),s=r.length===0?-1:o>=0?o:0;U.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>jc(1),navigateToPreviousItem:()=>jc(-1),navigateToNextContainer:()=>Hc(1),navigateToPreviousContainer:()=>Hc(-1),navigate:({contextNode:e,selectedIndex:t})=>{E({contextNodeId:e.id,selectedIndex:t})}},jc=e=>{let{selectedIndex:t,contextNode:n}=f(),r=ae(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;U.navigate({selectedIndex:s,contextNode:n})},Hc=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=f();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=ae(o.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=ae(l.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),g=u.length?p:-1;U.navigate({contextNode:l,selectedIndex:g})}});var Gc,qc,vh,ns,Vc,Wc,yh,Kc,zc=y(()=>{"use strict";ge();C();It();k();Je();Gc=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),qc=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=f();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},vh=e=>{let t=f().nodes[e];return!!t&&!t.isDeleted&&Ye(t)&&t.childRenderAxis==="vertical"},ns=(e,t)=>{let{nodes:n}=f(),r=n[e];if(!r||r.isDeleted)return!1;let o=ue(r.id);return U.navigate({contextNode:r,selectedIndex:Gc(t,o.length)}),!0},Vc=e=>{let{nodes:t}=f(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return ns(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let d=ue(o.id).findIndex(l=>l.id===n.id);return d>=0?(U.navigate({contextNode:o,selectedIndex:d}),!0):Vc(o.id)},Wc=e=>{let{nodes:t}=f(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Vc(n))return!0;n=t[n]?.parentNodeId}return!1},yh=e=>{if(!e)return!1;let t=f().nodes[e];return!!t&&!t.isDeleted},Kc=e=>{let{nodes:t,rootNodeId:n}=f();if(vh(e.contextNodeId)&&ns(e.contextNodeId,e.selectedIndex))return c("Restored navigation inside text container",null);if(yh(e.selectedNodeId)&&e.selectedNodeId&&Wc(e.selectedNodeId))return c("Restored navigation to selected node or ancestor",null);if(ns(e.contextNodeId,e.selectedIndex))return c("Restored navigation to previous container",null);if(e.parentNodeId&&ns(e.parentNodeId,e.selectedIndex))return c("Restored navigation to previous parent",null);if(Wc(e.contextNodeId))return c("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return i("Unable to restore navigation");let o=ue(r.id);return U.navigate({contextNode:r,selectedIndex:Gc(e.selectedIndex,o.length)}),c("Restored navigation to root",null)}});import{monotonicFactory as bh,ulid as Nt}from"ulid";function xh(){let e=He();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)return i("No workspace found in event log");let[r]=ae(n.id),[o]=r?ae(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return c("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?c("Resolved boot nav target",{contextNode:r,selectedIndex:0}):c("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function Ih(){let e=xh();return a(e)?e:U.navigate(e.value)}function Yc({userId:e,userName:t}){let n=Gr(),r=Gr(),o=Gr(),s=Gr(),d=Gr(),l=_e(void 0,void 0);if(a(l))return l;let u=_e(void 0,void 0);if(a(u))return u;let m=_e(u.value,void 0);if(a(m))return m;let p=_e(void 0,void 0);if(a(p))return p;let g=_e(p.value,void 0);if(a(g))return g;let I=_e(g.value,void 0);if(a(I))return I;let N=_e(void 0,void 0);return a(N)?N: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:"create.contributor",payload:{id:e,name:t}},{id:Nt(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Nt(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Nt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:g.value}},{id:Nt(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:r,rank:I.value}},{id:Nt(),userId:e,userName:t,action:"add.board",payload:{id:Ko,name:"Closed",parent:n,rank:m.value}},{id:Nt(),userId:e,userName:t,action:"add.swimlane",payload:{id:ye,name:"Closed",parent:Ko,rank:N.value}},{id:Nt(),userId:e,userName:t,action:"lock.node",payload:{id:Ko}},{id:Nt(),userId:e,userName:t,action:"lock.node",payload:{id:ye}}])}function an(e,t=[]){if(Eh())return c("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Ne.workspace("temporary-uninitialized-workspace","Workspace","a0"),d=jr(s);return a(d)?d:(E({hasProjectDefinition:!1,mode:h.DEFAULT}),c("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return i("Initialized Epiq project has no workspace init event");let n=Bt(e),{fatal:r,skipped:o}=Tn(n);return r.length>0?i(`Materializing failed:
|
|
24
|
-
${r.map(s=>s.message).join(`
|
|
25
|
-
|
|
26
|
-
`)
|
|
27
|
-
`);
|
|
20
|
+
`;At.writeFileSync(e,o,"utf8")}function qi(e,t,n=!1){let o=Ah();if(!o)return;let r=Th(Sh.format(...t)),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${r}
|
|
21
|
+
`;try{At.mkdirSync(zi.dirname(o),{recursive:!0}),At.appendFileSync(o,c,"utf8"),Wi++,(Wi>=Nh||At.statSync(o).size>Vi)&&(Wi=0,wh(o))}catch{}}var rl,Vi,Hi,Nh,Wi,sl,Ah,Ch,Th,Gi,X,ht=h(()=>{"use strict";R();ae();rl=500,Vi=4*1024*1024,Hi=16*1024,Nh=50,Wi=0,sl=()=>process.env.EPIQ_MCP==="true",Ah=()=>{let e=process.cwd(),t=gs(e);return a(t)?sl()?zi.join(Xt(),"epiq-mcp.log"):void 0:zi.join(t.value,qe,"log","epiq.log")},Ch=(e,t)=>{let n=At.statSync(e).size;if(n<=t)return At.readFileSync(e,"utf8");let o=At.openSync(e,"r");try{let r=Buffer.alloc(t);At.readSync(o,r,0,t,n-t);let s=r.toString("utf8"),d=s.indexOf(`
|
|
22
|
+
`);return d===-1?"":s.slice(d+1)}finally{At.closeSync(o)}};Th=e=>{if(e.length<=Hi)return e;let t=e.length-Hi;return`${e.slice(0,Hi)} \u2026 [${t} more chars]`};Gi=()=>sl()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",X={info(...e){let t=Gi();(t==="info"||t==="debug")&&qi("[Info]",e,!1)},debug(...e){Gi()==="debug"&&qi("[Debug]",e,!0)},error(...e){let t=Gi();if(t==="error"||t==="info"||t==="debug"){let o=e.some(r=>r instanceof Error)?void 0:new Error().stack;qi("[Error]",[...e,o].filter(Boolean),!1)}}};globalThis.logger=X});var le,uo=h(()=>{"use strict";le={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var j,dr,st=h(()=>{"use strict";j=e=>e.slice(-7).toUpperCase(),dr=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?j(e).includes(n):!0}});var Te,On=h(()=>{"use strict";V();st();Te={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:z.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:j(e)},context:z.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:z.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:z.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:z.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:j(e)},context:z.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:z.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:z.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:d})}});var Mh,fe,fs,Jt=h(()=>{"use strict";Mh=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[fe,fs]=Mh});function hn(e,t=!1){let n=Bh[e.action];if(!n)return i(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);if(!vt()&&e.action!=="init.workspace")return D(`${e.action} arrived before the workspace was initialized`,e);if(e.action==="init.workspace"&&Ge){if(Ge.genesisApplied)return D("the workspace is already initialized",e);Ge.genesisApplied=!0}let o;try{o=n(e)}catch(s){return D(`threw while materializing (${s instanceof Error?s.message:String(s)})`,e)}if(a(o))return o;let r=_h(e,t);return r||o}var Ki,D,lr,Un,$n,il,al,kh,Ph,Yi,Lh,Dh,Ge,Fh,_h,cr,Bh,Qt,Zt=h(()=>{"use strict";ht();V();R();uo();te();On();M();Xi();Jt();Ki=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),D=(e,t)=>({...Ki(e,t),convergence:!0}),lr=e=>a(e)&&e.convergence===!0,Un=e=>{let t=e.filter(a);return{fatal:t.filter(n=>!lr(n)),skipped:t.filter(lr)}},$n=e=>{e.length!==0&&X.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},il=e=>{let t=I.getNode(e);if(!t||!k(t)||t.isDeleted)return null;let n=hs(t);return a(n)?n:null},al=e=>{if(!vs())return null;for(let t of e){let n=il(t);if(n)return n;let o=g().nodes[t]?.parentNodeId;if(!o)continue;let r=il(o);if(r)return r}return null},kh=(e,t)=>{let n=I.getNode(e);n&&I.updateNode({...n,log:[...n.log??[],t]})},Ph=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},Yi=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 Ph(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"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":default:return[]}},Lh=e=>{Re(t=>({...t,eventLog:[...t.eventLog,e]}))},Dh=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?Ki("Invalid user ID format",e):l("Valid user",null)},Ge=null,Fh=e=>{for(let[t,n]of e.nodeLog){let o=I.getNode(t);o&&I.updateNode({...o,log:[...o.log??[],...n]})}return e.appLog.length>0&&Re(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),al([...e.virtualNodeIds])},_h=(e,t)=>{let n=Dh(e);if(a(n))return n;let o=[...new Set(Yi(e))];if(Ge){for(let s of o){if(!t){let d=Ge.nodeLog.get(s);d?d.push(e):Ge.nodeLog.set(s,[e])}if(vs()){Ge.virtualNodeIds.add(s);let d=g().nodes[s]?.parentNodeId;d&&Ge.virtualNodeIds.add(d)}}return t||Ge.appLog.push(e),null}t||(o.forEach(s=>kh(s,e)),Lh(e));let r=al(o);return r||null},cr=(e,t,n)=>I.getNode(e)?D(`a node with id ${e} already exists`,n):t===e?D("a node cannot be its own parent",n):null,Bh={"init.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=Te.workspace(t,n,o),s=ur(r);if(a(s))return Ki(s.message,e);let d=I.createNode(r);return a(d)?D(d.message??"Failed to initialize workspace",e):ki(d.value)?l("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=cr(t,void 0,e);if(r)return r;let s=I.createNode(Te.workspace(t,n,o));return a(s)?D(s.message??"Failed to add workspace",e):ki(s.value)?l("Added workspace",{action:e.action,result:s.value}):i("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=cr(t,o,e);if(s)return s;let d=I.createNode(Te.board(t,n,o,r));return a(d)?D(d.message??"Unable to create board",e):Jo(d.value)?l("Added board",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=cr(t,o,e);if(s)return s;let d=I.createNode(Te.swimlane(t,n,o,r));return a(d)?D(d.message??"Unable to create swimlane",e):pn(d.value)?l("Added swimlane",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=cr(t,o,e);if(s)return s;let d=I.createNode(Te.ticket(t,n,o,r));return a(d)?D(d.message??"Unable to create issue",e):k(d.value)?l("Added issue",{action:e.action,result:d.value}):i("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:o,val:r,rank:s}=e.payload,d=cr(t,o,e);if(d)return d;let c=I.createNode(Te.field({id:t,name:n,parentNodeId:o,rank:s,props:{value:r},childRenderAxis:n.includes(le.DESCRIPTION)?"vertical":"horizontal"}));return a(c)?D(c.message??`Unable to create field: ${n}`,e):nt(c.value)?l("Added field",{action:e.action,result:c.value}):i("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!I.getNode(t))return D(`Unable to locate node with id ${t}`,e);let r=I.renameNode(t,n);return a(r)?D(r.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:r.value})},"delete.node":e=>{let{id:t}=e.payload,n=I.tombstoneNode(t);return a(n)?D(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,o=I.createTag({id:t,name:n});return a(o)?D(o.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:o.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=I.tombstoneTag(t);return a(n)?D(n.message??"Unable to delete tag",e):l("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,o=I.restoreTag(t,n);return a(o)?D(o.message??"Unable to restore tag",e):l("Tag restored",{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)?D(o.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:o.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,o=I.renameContributor(t,n);return a(o)?D(o.message??"Unable to rename contributor",e):l("Contributor renamed",{action:e.action,result:o.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=I.tombstoneContributor(t);return a(n)?D(n.message??"Unable to remove contributor",e):l("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)?D(o.message??"Unable to restore contributor",e):l("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)?D(o.message??"Unable to tag issue",e):l("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)?D(o.message??"Unable to untag issue",e):l("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)?D(o.message??"Unable to assign issue",e):l("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)?D(o.message??"Unable to unassign issue",e):l("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)?D(r.message??"Failed to move node",e):l("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)?D(o.message??"Unable to edit description",e):l("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 D("Unable to locate issue",e);if(!k(r))return D("Can only close issues",e);let s=I.getNode(fe);if(!s)return D("Unable to locate target swimlane",e);if(n!==s.id)return D("Close target must be closed swimlane",e);let d=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(d)?D(d.message??"Unable to close issue",e):l("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 D("Unable to locate issue",e);if(!k(r))return D("Can only reopen issues",e);let s=I.getNode(fe);if(!s)return D("Unable to locate closed swimlane",e);if(n===s.id)return D("Cannot reopen issue into closed swimlane",e);if(!I.getNode(n))return D("Reopen parent no longer exists",e);let c=I.moveNodeToRank({id:t,parentId:n,rank:o});return a(c)?D(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=I.lockNode(t);return a(n)?D(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[o,r]of Object.entries(n)){let s=I.getNode(o);if(!s)return D(`Unable to locate node ${o}`,e);if(s.parentNodeId!==t)return D(`Node ${o} is not child of ${t}`,e);let d=I.updateNode({...s,rank:r});if(a(d))return D(d.message??"Unable to rebalance child",e)}return l("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)?D(s.message??"Unable to add comment",e):l("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 D("Unable to locate comment",e);if(r.issue!==n)return D("Comment does not belong to issue",e);let s=I.editComment(t,o);return a(s)?D(s.message??"Unable to edit comment",e):l("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 D("Unable to locate comment",e);if(o.issue!==n)return D("Comment does not belong to issue",e);let r=I.deleteComment(t);return a(r)?D(r.message??"Unable to delete comment",e):l("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,c=I.createAttachment({id:t,issue:n,hash:o,ext:r,name:s,bytes:d,deleted:!1});return a(c)?D(c.message??"Unable to add attachment",e):l("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 D("Unable to locate attachment",e);if(o.issue!==n)return D("Attachment does not belong to issue",e);let r=I.deleteAttachment(t);return a(r)?D(r.message??"Unable to delete attachment",e):l("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)?D(n.message??"Unable to link contributor",e):l("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};Qt=e=>{let t=dl(()=>{let n=Ge===null;n&&(Ge={appLog:[],nodeLog:new Map,virtualNodeIds:new Set,genesisApplied:!1});try{let o=e.map(r=>hn(r));if(n&&Ge){let r=Fh(Ge);if(r)return e.map(()=>r)}return o}finally{n&&(Ge=null)}});return a(t)?e.map(()=>i(t.message)):t.value}});var Ji,cl=h(()=>{"use strict";Ji=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown"});import{existsSync as Oh,readdirSync as Uh,statSync as $h}from"node:fs";import jh from"node:path";var jn,ll,Qi,vn,ul,ml,pl,mr=h(()=>{"use strict";ae();jn=e=>{let t=Bn(e);return Oh(t)?Uh(t).filter(n=>n.endsWith(".jsonl")).sort().map(n=>{let{size:o,mtimeMs:r}=$h(jh.join(t,n));return`${n}:${o}:${r}`}).join("|"):"none"},ll=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),Qi=(e,t,n)=>{let o=ll(t),r=jn(e),s=ll(r);for(let[d,c]of s)if(d!==n&&o.get(d)!==c)return null;for(let d of o.keys())if(d!==n&&!s.has(d))return null;return r},vn=null,ul=e=>vn&&vn.root===e?vn.signature:null,ml=(e,t)=>{vn={root:e,signature:t}},pl=(e,t)=>{if(!vn||vn.root!==e)return;let n=Qi(e,vn.signature,t);vn=n===null?null:{root:e,signature:n}}});var Hh,Wh,gl,fl,Zi=h(()=>{"use strict";Hh=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","tombstone.tag","restore.tag","create.contributor","rename.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"],Wh=new Set(Hh),gl=e=>Wh.has(e),fl=e=>({action:e.action,payload:e.payload})});import{z as G}from"zod";var H,Ct,yn,ys,ea,qh,hl,vl=h(()=>{"use strict";R();H=G.string().min(1),Ct=G.string(),yn=G.string(),ys=G.looseObject({id:H}),ea=G.looseObject({id:H,name:Ct,parent:H,rank:yn}),qh={"init.workspace":G.looseObject({id:H,name:Ct,rank:yn}),"add.workspace":G.looseObject({id:H,name:Ct,rank:yn}),"add.board":ea,"add.swimlane":ea,"add.issue":ea,"add.field":G.looseObject({id:H,name:Ct,parent:H,rank:yn}),"edit.title":G.looseObject({id:H,name:Ct}),"delete.node":ys,"lock.node":ys,"move.node":G.looseObject({id:H,parent:H,rank:yn}),"edit.description":G.looseObject({id:H,md:G.string()}),"close.issue":G.looseObject({id:H,parent:H,rank:yn}),"reopen.issue":G.looseObject({id:H,parent:H,rank:yn}),"create.tag":G.looseObject({id:H,name:Ct}),"tombstone.tag":ys,"restore.tag":G.looseObject({id:H,name:Ct}),"create.contributor":G.looseObject({id:H,name:Ct}),"rename.contributor":G.looseObject({id:H,name:Ct}),"tombstone.contributor":ys,"restore.contributor":G.looseObject({id:H,name:Ct}),"link.contributor.user":G.looseObject({contributor:H}),"add.issue.assignee":G.looseObject({id:H,assignee:H}),"remove.issue.assignee":G.looseObject({id:H,assignee:H}),"add.issue.tag":G.looseObject({id:H,tag:H}),"remove.issue.tag":G.looseObject({id:H,tag:H}),"add.issue.comment":G.looseObject({id:H,issue:H,md:G.string()}),"edit.issue.comment":G.looseObject({id:H,issue:H,md:G.string()}),"delete.issue.comment":G.looseObject({id:H,issue:H}),"add.issue.attachment":G.looseObject({id:H,issue:H,hash:G.string().min(1),ext:G.string().min(1),name:Ct,bytes:G.number()}),"delete.issue.attachment":G.looseObject({id:H,issue:H}),"rebalance.children":G.looseObject({parent:H,ranks:G.record(G.string(),yn)})},hl=(e,t)=>{let o=qh[e].safeParse(t);return o.success?l("Payload is readable",void 0):i(`${e}: ${o.error.issues.map(r=>`${r.path.join(".")||"payload"} ${r.message}`).join(", ")}`)}});import Is from"node:fs";import xs from"node:path";import{decodeTime as Gh}from"ulid";import{z as ta}from"zod";function pr(e,t){let n=Bn(e),o=jn(e);if(!Is.existsSync(n))return l("No events found",[]);let r=Is.readdirSync(n).filter(c=>c.endsWith(".jsonl")).map(c=>xs.join(n,c)),s=[];for(let c of r){let u=ev(c,t);if(a(u))return i(u.message);s.push(...u.value)}let d=nv(s);return en={root:e,signature:o,edge:d.at(-1)?.id?.[0]??null},l("All events loaded",d)}function yt(e){let t=[],n=pr(e,t);if(a(n))return i(n.message);let o=oa(n.value,t);return a(o)?i(o.message):(tv=t,l("Loaded merged events",{events:o.value,unreadable:t}))}function ra(e){let t=pr(e);return a(t)?i(t.message):l("Loaded event actors",t.value.map(({userId:n,userName:o})=>({userId:n,userName:o})))}function Hn(e){let t=yt(e);return a(t)?i(t.message):l("Loaded merged events",t.value.events)}function sa(e,t){let n=pr(e);if(a(n))return i(n.message);let{appliedEvents:o,unappliedEvents:r}=ov(n.value,t),s=oa(o);if(a(s))return i(s.message);let d=oa(r);return a(d)?i(d.message):l("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function yl(e=process.cwd()){let t=jn(e);if(en&&en.root===e&&en.signature===t)return l("Loaded edge reference, unchanged",en.edge);let n=pr(e);return a(n)?i(n.message):l("Loaded edge reference",n.value.at(-1)?.id?.[0]??null)}function bl(e,t,n){if(!en||en.root!==e)return;let o=Qi(e,en.signature,t);en=o===null?null:{root:e,signature:o,edge:n}}function ia(e){let t=pr(e);if(a(t))return i(t.message);let n=Il(t.value);return l("Loaded effective event times",new Map(t.value.map((o,r)=>[o.id[0],n[r]??null])))}var zh,bs,Vh,Kh,Yh,Xh,Jh,Qh,Zh,oa,ev,tv,en,na,nv,Il,ov,bt=h(()=>{"use strict";ht();R();ae();mr();et();Zi();Se();vl();zh=ta.object({userId:ta.string().min(1).default("unknown"),userName:ta.string().min(1).default("unknown")}),bs=e=>{let t=Object.entries(e).filter(([r])=>r!=="id"&&r!=="v"&&r!=="userId"&&r!=="userName");if(t.length!==1)return null;let n=t[0]?.[1];if(typeof n!="object"||n===null)return null;let o=n.id;return typeof o=="string"&&o.length>0?o:null},Vh=/^[0-9a-hjkmnp-tv-z]{26}$/i,Kh=e=>Vh.test(e)?e.toUpperCase():e,Yh=e=>{let t=xs.basename(e,".jsonl"),n=t.indexOf("."),o=n===-1?t:t.slice(0,n),r=n===-1?void 0:t.slice(n+1),s=zh.safeParse({userId:Kh(o),userName:r});return s.success?l("Parsed event file actor",s.data):i(`Invalid event file name ${xs.basename(e)}: ${s.error.issues.map(d=>d.path.join(".")||d.message).join(", ")}`)},Xh=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"):l("Resolved persisted action",t[0])},Jh=(e,t)=>t in e,Qh=({id:e,action:t,payload:n,userId:o,userName:r})=>({id:e,action:t,payload:n,userId:o,userName:r}),Zh=e=>{let{userId:t,userName:n,...o}=e,r=Xh(o);if(a(r))return i(r.message);let s=r.value,d=e.id?.[0];return d?Jh(o,s)?l("Decoded persisted event",Qh({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")},oa=(e,t)=>{let n=[],o=new Map,r=new Map;for(let s of e){if(!El(s.v)){r.set(s.v,(r.get(s.v)??0)+1),t?.push({eventId:s.id[0],reason:"unsupported-schema-version",detail:`v${s.v}`,targetNodeId:bs(s)});continue}let d=Zh(s);if(a(d)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:d.message,targetNodeId:bs(s)});continue}let c=d.value.action;if(!gl(c)){o.set(c,(o.get(c)??0)+1),t?.push({eventId:s.id[0],reason:"unknown-action",detail:c,targetNodeId:bs(s)});continue}let u=hl(c,d.value.payload);if(a(u)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:u.message,targetNodeId:bs(s)});continue}n.push(d.value)}if(o.size>0){let s=[...o.entries()].map(([d,c])=>`${d} (x${c})`).join(", ");X.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${s}. Upgrade to apply them.`)}if(r.size>0){let s=[...r.entries()].map(([d,c])=>`v${d} (x${c})`).join(", ");X.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${s}. Upgrade to apply them.`)}return l("Decoded reconstructed events",n)},ev=(e,t)=>{if(!Is.existsSync(e))return l("Event file missing",[]);let n=Yh(e);if(a(n))return i(n.message);let o=Is.readFileSync(e,"utf8"),r=[],s=xs.basename(e),d=(c,u)=>{t?.push({eventId:null,reason:"corrupt-line",detail:`${s}:${c} (${u})`,targetNodeId:null})};for(let[c,u]of o.split(`
|
|
23
|
+
`).entries()){let m=u.trim();if(!m)continue;let p;try{p=JSON.parse(m)}catch{d(c+1,"invalid JSON");continue}let f=xl(p);if(a(f)){d(c+1,f.message);continue}r.push({...f.value,userId:n.value.userId,userName:n.value.userName})}return l("Parsed persisted events file",r)};tv=[];en=null;na=(e,t)=>{let n=e.id[0].localeCompare(t.id[0]);return n!==0?n:JSON.stringify(e).localeCompare(JSON.stringify(t))},nv=e=>{let t=new Map,n=new Map;for(let m of e){let p=m.id[0],f=m.id[1]??null;t.set(p,m);let x=n.get(f)??[];x.push(m),n.set(f,x)}for(let m of n.values())m.sort(na);let o=[],r=new Set,s=m=>{let p=[m];for(;p.length>0;){let f=p.pop(),x=f.id[0];if(r.has(x))continue;o.push(f),r.add(x);let S=n.get(x)??[];for(let A=S.length-1;A>=0;A--)p.push(S[A])}},d=(n.get(null)??[]).filter(m=>{let p=Object.keys(m).filter(f=>f!=="id"&&f!=="v"&&f!=="userId"&&f!=="userName");return p.length===1&&p[0]==="init.workspace"});for(let m of d)s(m);let c=e.filter(m=>{let p=m.id[0],f=m.id[1]??null;return r.has(p)?!1:f===null||!t.has(f)}).sort(na);for(let m of c)s(m);let u=e.filter(m=>!r.has(m.id[0])).sort(na);for(let m of u)s(m);return o},Il=e=>Ko(e.map(t=>{try{return Gh(t.id[0])}catch{return null}}));ov=(e,t)=>{let n=new Set,o=[],r=[],s=Il(e);for(let d=0;d<e.length;d++){let c=e[d],u=c.id[0],m=c.id[1],p=s[d]??null;!(p!==null&&p<t)||m&&n.has(m)?(n.add(u),r.push(c)):o.push(c)}return{appliedEvents:o,unappliedEvents:r}}});import rv from"node:fs";import Sl from"node:path";import{decodeTime as sv,monotonicFactory as iv}from"ulid";import{z as Wn}from"zod";function aa(e,t){let n;if(t&&t.current!==void 0)n=t.current;else{let r=yl(e);if(a(r))return i(r.message);n=r.value}let o=n?Rl(cv(n)):Rl();return l("Minted event id",[o,n])}function Es({event:e,rootDir:t,edge:n,id:o}){try{let r=ol(t);if(a(r))return r;let s=fv(t,{userId:e.userId,userName:e.userName});if(a(s))return s;let d=o?l("Minted event id",o):aa(t,n);if(a(d))return i(d.message);let[c,u]=d.value,m=hv(fl(e),[c,u]);if(a(m))return i(m.message);rv.appendFileSync(s.value,`${JSON.stringify(m.value)}
|
|
24
|
+
`,"utf8"),n&&(n.current=c);let p=Sl.basename(s.value);return bl(t,p,c),pl(t,p),l("Event persisted",{path:s.value,entry:m.value})}catch(r){let s=r instanceof Error?r.message:"Unknown persist error";return i(`Failed to persist event: ${s}`)}}var Nl,Rl,av,dv,cv,Al,lv,uv,xl,mv,pv,El,gv,ne,qn,fv,hv,Se=h(()=>{"use strict";ht();Mn();R();Be();ae();cl();et();bt();mr();Zi();Nl=1,Rl=iv(),av=0xffffffffffff,dv=Zr,cv=e=>{let t=Date.now(),n;try{n=sv(e)}catch{return t}return n>=av?t:n>t+dv?(X.error("[persist] edge id is too far in the future; seeding from the wall clock instead",{edgeRef:e,edgeTime:n,now:t}),t):Math.max(t,n+1)},Al=Wn.tuple([Wn.string().min(1),Wn.string().min(1).nullable()]),lv=Wn.looseObject({v:Wn.literal(Nl),id:Al}),uv=Wn.looseObject({v:Wn.number().int().positive(),id:Al}),xl=e=>{let t=uv.safeParse(e);return t.success?l("Parsed persisted event envelope",t.data):i(`Invalid persisted event envelope: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},mv=[1],pv=new Set(mv),El=e=>pv.has(e),gv=e=>{let t=lv.safeParse(e);return t.success?l("Parsed persisted event",t.data):i(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},ne=()=>{let{userName:e,userId:t}=Ie();return e?t?Qr(t)?Vo(e)?l("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")},qn=({userId:e,userName:t})=>`${Ji(e)}.${Ji(t)}.jsonl`,fv=(e,{userId:t,userName:n})=>{let o=qn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(o))return i(`Invalid event log file name: ${o}`);let s=Sl.join(Bn(e),o);return l("Successfully resolved event log path",s)},hv=(e,t)=>{let n={[e.action]:e.payload,v:Nl,id:t};return gv(n)}});import{ulid as vv}from"ulid";function Cl(e,t,n){let o=aa(t,n);if(a(o))return i(o.message);let r={...e,id:o.value[0]},s=hn(r);if(s.status!==Vt.Success)return s;let d=Es({event:r,rootDir:t,edge:n,id:o.value});return a(d)?d:s}function L(e,t){if(e.length===0||!e[0])return i("No events provided");if(g().readOnly)return i(g().readOnlyReason??"Cannot change the board while time travelling");let n={},o=yv(e[0],t,n);if(a(o))return o;let r=e.map(d=>Cl(d,t,n)),s=r.filter(a);return s.length>0?i("Materialize and persist failed: "+s.map(d=>d.message).join(", ")):l("Materialization succeeded",r.map(d=>d.value))}var yv,xe=h(()=>{"use strict";R();te();M();Zt();Se();yv=(e,t,n)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return l("Contributor write already in flight",void 0);let o=I.getContributor(e.userId),r={id:vv(),action:o?"rename.contributor":"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName};if(o&&(o.tombstoned||o.name===e.userName))return l("Contributor name is current",void 0);let s=Cl(r,t,n);return a(s)?i(s.message):l("Contributor name recorded",void 0)}});var Gn,da,wl=h(()=>{"use strict";st();Gn=e=>e.trim().toLocaleLowerCase(),da=(e,t)=>Gn(e).includes(Gn(t))});var bv,Iv,Tl,Ml,xv,Ev,kl,Pl=h(()=>{"use strict";M();st();wl();bv=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},Iv=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>{let o=t[n];return o?o.name:void 0}).filter(n=>!!n)},Tl=null,Ml=new Map,xv=()=>{let e=g().eventLog??[];if(e===Tl)return Ml;let t=new Map;for(let n of e){if(!n.userId)continue;let o=n.payload;for(let r of[o.id,o.issue]){if(typeof r!="string")continue;let s=t.get(r)??new Set;s.add(n.userId),t.set(r,s)}}return Tl=e,Ml=t,t},Ev=e=>{let{contributors:t}=g(),n=xv().get(e.id);return n?[...n].map(o=>t[o]?.name).filter(o=>!!o):[]},kl=(e,t)=>{let n=Gn(t.value);if(!n)return!0;switch(t.target){case"title":return da(e.title??"",n);case"description":return da(e.props.description??"",n);case"tag":return bv(e).map(Gn).some(r=>r.includes(n));case"assignee":return Iv(e).map(Gn).some(r=>r.includes(n));case"actor":return Ev(e).map(Gn).some(r=>r.includes(n));case"ref":return dr(e.id,t.value);default:return!0}}});var Ll,Rv,Dl,Fl,ca=h(()=>{"use strict";V();Pl();Ll=(e,t)=>e.rank.localeCompare(t.rank),Rv=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,Dl=(e,t)=>Object.values(e).filter(n=>Rv(n,t)).sort(Ll),Fl=(e,t)=>{let n={};for(let o of Object.values(e)){if(k(o)&&t.length>0&&!t.every(s=>kl(o,s))||!o.parentNodeId||o.isDeleted)continue;let r=n[o.parentNodeId];r?r.push(o):n[o.parentNodeId]=[o]}for(let o of Object.keys(n))n[o].sort(Ll);return n}});var _l,Rs,ge,Bl,Ol,Dt,bn,pt=h(()=>{"use strict";_c();xe();R();M();ca();ao();_l=e=>Rs(ge(e),{at:"end"}),Rs=(e,t={at:"end"})=>{let n=r=>a(r)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(Oe(void 0,void 0));let o=()=>n(Oe(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let r=e[0];return r?n(Oe(void 0,r.rank)):i("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(Oe(r.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let r=Bl(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(Oe(d?.rank,s.rank))}case"after":{let r=Bl(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(Oe(s.rank,d?.rank))}}},ge=e=>{let t=g();if(!Ul()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return Dl(t.nodes,e)},Bl=(e,t)=>e.findIndex(n=>n.id===t),Ol=(e,t,n={at:"end"})=>Rs(ge(t).filter(o=>o.id!==e),n),Dt=(e,t,n,o,r)=>{let s=Ol(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return l("Resolved rank",s.value.rank);let d=Di(e,o);if(a(d))return d;let c=L([d.value],r);if(a(c))return c;let u=Ol(t,e,n);return a(u)?u:u.value.needsRebalance?i("Rank rebalance failed to create space"):l("Resolved rank after rebalance",u.value.rank)},bn=(e,t,n)=>{let o=_l(e);if(a(o))return o;if(!o.value.needsRebalance)return l("Resolved rank",o.value.rank);let r=Di(e,t);if(a(r))return r;let s=L([r.value],n);if(a(s))return s;let d=_l(e);return a(d)?d:d.value.needsRebalance?i("Rank rebalance failed to create space"):l("Resolved rank after rebalance",d.value.rank)}});var U,$l,jl,it=h(()=>{"use strict";M();U={exit(){process.exit(0)},enterChildNode(){let e=g(),t=e.contextNode,n=Math.max(0,e.selectedIndex),o=oe(t.id),r=o[n];r&&(t.context==="FIELD"&&o.length===0||r.context==="COMMENT"||r.context==="TEXT"||U.navigate({contextNode:r,selectedIndex:oe(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=oe(n.id),r=o.findIndex(({id:d})=>d===e.id),s=o.length===0?-1:r>=0?r:0;U.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>$l(1),navigateToPreviousItem:()=>$l(-1),navigateToNextContainer:()=>jl(1),navigateToPreviousContainer:()=>jl(-1),navigate:({contextNode:e,selectedIndex:t})=>{E({contextNodeId:e.id,selectedIndex:t})}},$l=e=>{let{selectedIndex:t,contextNode:n}=g(),o=oe(n.id).length;if(o===0)return;let s=(Math.max(0,t)+e+o)%o;U.navigate({selectedIndex:s,contextNode:n})},jl=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=oe(r.id),d=s.findIndex(x=>x.id===t.id);if(d<0)return;let c=s.at(d+e)??s.at(0);if(!c)return;let u=oe(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,o),m),f=u.length?p:-1;U.navigate({contextNode:c,selectedIndex:f})}});var Wl,ql,Sv,Ss,Gl,Hl,Nv,zl,Vl=h(()=>{"use strict";V();R();pt();M();it();Wl=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),ql=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},Sv=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&nt(t)&&t.childRenderAxis==="vertical"},Ss=(e,t)=>{let{nodes:n}=g(),o=n[e];if(!o||o.isDeleted)return!1;let r=ge(o.id);return U.navigate({contextNode:o,selectedIndex:Wl(t,r.length)}),!0},Gl=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let o=n.parentNodeId;if(!o)return Ss(n.id,0);let r=t[o];if(!r||r.isDeleted)return!1;let d=ge(r.id).findIndex(c=>c.id===n.id);return d>=0?(U.navigate({contextNode:r,selectedIndex:d}),!0):Gl(r.id)},Hl=e=>{let{nodes:t}=g(),n=e,o=new Set;for(;n&&!o.has(n);){if(o.add(n),Gl(n))return!0;n=t[n]?.parentNodeId}return!1},Nv=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},zl=e=>{let{nodes:t,rootNodeId:n}=g();if(Sv(e.contextNodeId)&&Ss(e.contextNodeId,e.selectedIndex))return l("Restored navigation inside text container",null);if(Nv(e.selectedNodeId)&&e.selectedNodeId&&Hl(e.selectedNodeId))return l("Restored navigation to selected node or ancestor",null);if(Ss(e.contextNodeId,e.selectedIndex))return l("Restored navigation to previous container",null);if(e.parentNodeId&&Ss(e.parentNodeId,e.selectedIndex))return l("Restored navigation to previous parent",null);if(Hl(e.contextNodeId))return l("Restored navigation to previous container or ancestor",null);let o=t[n];if(!o||o.isDeleted)return i("Unable to restore navigation");let r=ge(o.id);return U.navigate({contextNode:o,selectedIndex:Wl(e.selectedIndex,r.length)}),l("Restored navigation to root",null)}});import{monotonicFactory as Av,ulid as Ft}from"ulid";function Cv(){let e=$e();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)return i("No workspace found in event log");let[o]=oe(n.id),[r]=o?oe(o.id):[];if(r){let s=t.renderedChildrenIndex?.[r.id]??[];return l("Resolved boot nav target",{contextNode:r,selectedIndex:s.length>0?0:-1})}else return o?l("Resolved boot nav target",{contextNode:o,selectedIndex:0}):l("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function wv(){let e=Cv();return a(e)?e:U.navigate(e.value)}function Kl({userId:e,userName:t}){let n=gr(),o=gr(),r=gr(),s=gr(),d=gr(),c=Oe(void 0,void 0);if(a(c))return c;let u=Oe(void 0,void 0);if(a(u))return u;let m=Oe(u.value,void 0);if(a(m))return m;let p=Oe(void 0,void 0);if(a(p))return p;let f=Oe(p.value,void 0);if(a(f))return f;let x=Oe(f.value,void 0);if(a(x))return x;let S=Oe(void 0,void 0);return a(S)?S:l("Created default events",[{id:Ft(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:Ft(),userId:e,userName:t,action:"create.contributor",payload:{id:e,name:t}},{id:Ft(),userId:e,userName:t,action:"add.board",payload:{id:o,name:"Default",parent:n,rank:u.value}},{id:Ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:r,name:"Todo",parent:o,rank:p.value}},{id:Ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:o,rank:f.value}},{id:Ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:o,rank:x.value}},{id:Ft(),userId:e,userName:t,action:"add.board",payload:{id:fs,name:"Closed",parent:n,rank:m.value}},{id:Ft(),userId:e,userName:t,action:"add.swimlane",payload:{id:fe,name:"Closed",parent:fs,rank:S.value}},{id:Ft(),userId:e,userName:t,action:"lock.node",payload:{id:fs}},{id:Ft(),userId:e,userName:t,action:"lock.node",payload:{id:fe}}])}function _t(e,t=[]){if(Tv())return l("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Te.workspace("temporary-uninitialized-workspace","Workspace","a0"),d=ur(s);return a(d)?d:(E({hasProjectDefinition:!1,mode:y.DEFAULT}),l("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return i("Initialized Epiq project has no workspace init event");let n=Qt(e),{fatal:o,skipped:r}=Un(n);return o.length>0?i(`Materializing failed:
|
|
25
|
+
${o.map(s=>s.message).join(`
|
|
26
|
+
`)}`):($n(r),wv(),E({hasProjectDefinition:!0}),Mv(t),l("State booted successfully",null))}var gr,Tv,Mv,zn=h(()=>{"use strict";ht();it();me();R();On();M();ao();Zt();Jt();gr=Av();Tv=()=>{let e=$e();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},Mv=e=>{if(e.length===0)return;let t=e.filter(o=>o.reason==="corrupt-line"||o.reason==="invalid-payload"),n=e.filter(o=>o.reason==="unsupported-schema-version"||o.reason==="unknown-action");if(n.length>0){let o=[...new Set(n.map(r=>r.detail))].join(", ");X.info(`This build cannot read ${n.length} event(s) in the log (${o}). They are skipped, so anything they changed may be out of date until you upgrade.`)}if(t.length>0){let o=[...new Set(t.map(r=>r.detail))].join(", ");X.info(`Skipped ${t.length} corrupt line(s) in the event log (${o}). The rest of the board loaded normally; those events are unrecoverable.`)}}});import{WebSocket as kv}from"ws";var Pv,Yl,Xl=h(()=>{"use strict";Pv=new Set,Yl=e=>{let t=JSON.stringify(e);for(let n of Pv)n.readyState===kv.OPEN&&n.send(t)}});var Ns,mo,Vn,la,As,Ee,fr=h(()=>{"use strict";Xl();R();M();Ns=e=>{vt()&&(E({syncStatus:e}),Yl({type:"sync-status",payload:e}))},mo=(e="Syncing...")=>{Ns({status:"syncing",msg:e})},Vn=(e="Synced")=>{Ns({status:"synced",msg:e})},la=e=>{Ns({status:"failed",msg:e})},As=e=>{Ns({status:"offline",msg:e})},Ee=e=>(la(e),i(e))});var po,Jl,re,Cs=h(()=>{"use strict";R();po=(e,t)=>(logger.error(`[boot:${e}] ${t}`),i(`[boot:${e}] ${t}`)),Jl=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}},re=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});import Bt from"node:fs";import hr from"node:path";var go,Ql,Zl,eu,Lv,tu,Dv,Fv,nu,ua=h(()=>{"use strict";Nt();R();ae();go=e=>e.split(`
|
|
27
|
+
`).filter(t=>t.trim().length>0),Ql=e=>{let t=hr.join(e,qe,fn);try{if(!Bt.existsSync(t))return l("No events directory",[]);let n=Bt.readdirSync(t).filter(o=>o.endsWith(".jsonl")).filter(o=>go(Bt.readFileSync(hr.join(t,o),"utf8")).length>0);return l("Looked for stranded event logs",n)}catch(n){return i(`Unable to check ${t} for event logs before deleting it: ${n instanceof Error?n.message:String(n)}`)}},Zl=e=>hr.join(e,qe,fn),eu=e=>{let t=Zl(e),n=new Map;try{if(!Bt.existsSync(t))return n;for(let o of Bt.readdirSync(t))o.endsWith(".jsonl")&&n.set(o,go(Bt.readFileSync(hr.join(t,o),"utf8")))}catch{return n}return n},Lv=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},tu=(e,t)=>{if(t.size===0)return[];let n=Zl(e),o=[];for(let[r,s]of t){if(s.length===0)continue;let d=hr.join(n,r);try{let c=Bt.existsSync(d)?Bt.readFileSync(d,"utf8"):null,u=new Set(c===null?[]:go(c)),m=s.filter(f=>!u.has(f)).filter(Lv);if(m.length===0)continue;Bt.mkdirSync(n,{recursive:!0});let p=c!==null&&c.length>0&&!c.endsWith(`
|
|
28
|
+
`);Bt.appendFileSync(d,`${p?`
|
|
28
29
|
`:""}${m.join(`
|
|
29
30
|
`)}
|
|
30
|
-
`,"utf8"),
|
|
31
|
-
`),
|
|
32
|
-
`));X.info("Creating initial commit");let
|
|
33
|
-
${n.message}`);let
|
|
34
|
-
${
|
|
35
|
-
`+n.message);if(n.value)return
|
|
36
|
-
`+
|
|
37
|
-
`+s.message);let d=s.value;if(
|
|
38
|
-
${
|
|
39
|
-
${
|
|
40
|
-
`),
|
|
41
|
-
`+
|
|
42
|
-
`));X.info("Removing broken state branch worktree path"),
|
|
43
|
-
${
|
|
44
|
-
`));X.info("Moving state branch worktree to expected location");let m=await
|
|
45
|
-
${m.message}`)}if(s&&!
|
|
46
|
-
${u.message}`)}let d=await
|
|
47
|
-
${u.message}`)}return
|
|
48
|
-
${
|
|
49
|
-
${
|
|
50
|
-
${u.message}`):
|
|
51
|
-
${s.message}`):
|
|
52
|
-
${
|
|
53
|
-
${n.message}`):
|
|
54
|
-
`+
|
|
55
|
-
${s.message}`);let d=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return c(d?"Pushed state branch":"Remote already up to date",d)},cl=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Qt(e);if(a(o))return o;let s=o.value,d=[Go(),await Vi({repoRoot:e,stateBranchName:s}),await Bn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Ph({stateBranchRoot:t,stateBranchName:s}),await tc(t),n?await Dh({stateBranchRoot:t,repoRoot:e}):c("Skipped state branch upstream bootstrap",!1)];for(let l of d){if(a(l))return i(l.message);r=r||!!l.value}return c(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)}});import cs from"node:fs";import zi from"node:os";import Fh from"node:path";var Oh,ll,Bh,_h,Uh,ml,Ki,ul,$h,pl,gl=y(()=>{"use strict";C();lt();Et();Oh="epiq-sync.lock",ll=600*1e3,Bh=e=>{try{let t=JSON.parse(e);return typeof t.pid!="number"||typeof t.hostname!="string"||typeof t.startedAt!="number"||typeof t.operation!="string"?null:t}catch{return null}},_h=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Uh=e=>e&&(e.hostname!==zi.hostname()||_h(e.pid))?Date.now()-e.startedAt>ll:!0,ml=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,Ki=e=>{try{return Bh(cs.readFileSync(e,"utf8"))}catch{return null}},ul=(e,t)=>{let n={pid:process.pid,hostname:zi.hostname(),startedAt:Date.now(),operation:t};try{return cs.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},$h=async({worktreeRoot:e,operation:t})=>{let n=await gi(e);if(a(n))return i(n.message);let r=Fh.join(n.value,Oh),o=()=>{try{let l=Ki(r);l&&l.pid===process.pid&&cs.rmSync(r)}catch{}};if(ul(r,t))return c("Acquired sync lock",{acquired:!0,release:o});let s=Ki(r);if(!Uh(s))return c("Sync lock is held",{acquired:!1,heldBy:s});X.info(`Breaking an abandoned sync lock: ${s?ml(s):"unreadable lock file"}`);try{cs.rmSync(r,{force:!0})}catch{}if(ul(r,t))return c("Acquired sync lock after breaking a stale one",{acquired:!0,release:o});let d=Ki(r);return c("Sync lock taken by another process",{acquired:!1,heldBy:d??{pid:-1,hostname:zi.hostname(),startedAt:Date.now(),operation:"unknown"}})},pl=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await $h({worktreeRoot:e,operation:t});if(a(r))return i(r.message);if(!r.value.acquired)return X.info(`Skipping ${t}: the state worktree is held by ${ml(r.value.heldBy)}`),c("State worktree is held by another process",null);let{release:o}=r.value;try{return c("Ran under the sync lock",await n())}finally{o()}}});import jh from"node:fs";var Hh,Wh,fl,hl,Gh,ls,Yi=y(()=>{"use strict";C();is();as();Lr();mt();lt();Xr();Gi();gl();Hh=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=Z("getRepoRootDir",await ut(e));if(a(n))return i(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=Z("getStateBranchRoot",Se({repoRoot:r}));if(a(o))return i(o.message);let s=o.value;logger.debug("[sync] state branch root",s),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let d=Z("bootstrapStateBranchStorage",await cl({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(a(d))return i(d.message);logger.debug("[sync] bootstrap result",{bootstrapped:d.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let l=Z("hasInProgressGitOperation(stateBranchRoot)",await $o(s));if(a(l))return i(l.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:l.value}),l.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:r,stateBranchRoot:s});let u=Z("ensureStateBranchLayout",ec(r,s));return a(u)?i(u.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:d.value}),c("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:d.value}))},Wh=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 r=Z("stageStateBranchOwnEventFile",await ds({stateBranchRoot:t,eventFileName:n}));if(a(r))return i(r.message);let o=Z("stageStateBranchMediaFiles",await il({stateBranchRoot:t}));if(a(o))return i(o.message);let s=Z("stageStateBranchEventAttributes",await al({stateBranchRoot:t}));if(a(s))return i(s.message);let d=[r.value,o.value,s.value].filter(m=>m!==null);if(d.length===0)return c("Nothing to stage",{createdCommit:!1});let l=Z("hasStagedChanges(after stage)",await Vd(t,d));if(a(l))return i(l.message);if(logger.debug("[sync] state branch change check after stage result",{changed:l.value}),!l.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 u=Z("createStateBranchSyncCommit",await dl({repoRoot:e,stateBranchRoot:t,pathspec:d}));return a(u)?i(u.message):(logger.debug("[sync] created sync commit",u.value),c("Committed own event file",{createdCommit:!0,commitSha:u.value}))},fl=e=>{let t=e.createdCommit?"Committed locally, offline":"Offline";return Qc(t),c(t,{...e,pulled:!1,pushed:!1,offline:!0})},hl=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");os();let n=Z("ensureSyncReady",await Hh({cwd:e,ensureUpstream:!0}));if(a(n))return ke(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,d=Z("isDetachedHead(stateBranchRoot)",await Kd(o));if(a(d))return ke(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return ke("Cannot run :sync while the state branch is in detached HEAD state");let l=!1,u,m=!1,p=!1,g=Z("getStateBranch",Qt(r));if(a(g))return ke(g.message);let I=g.value;logger.debug("[sync] resolved state branch",{stateBranch:I,stateBranchRoot:o});let N=Z("commitOwnEventFileToStateBranch",await Wh({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(a(N))return ke(N.message);l=N.value.createdCommit,u=N.value.commitSha;let A=Z("pullBranchRebaseIfPresent",await bi({cwd:o,branch:I}));if(a(A))return yi(A.message)?fl({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,bootstrapped:s}):ke(A.message);m=A.value;let w=Z("isAheadOfUpstream",await Gd(o));if(a(w))return ke(w.message);if(l||s||w.value){logger.info("[sync] pushing state branch",{createdCommit:l,bootstrapped:s,stateBranchRoot:o});let T=Z("pushStateBranch",await Yr({stateBranchRoot:o,repoRoot:r}));if(a(T)&&Wd(T.message)){let M=Z("pullBranchRebaseIfPresent(retry)",await bi({cwd:o,branch:I}));if(a(M))return ke(M.message);m=m||M.value,T=Z("pushStateBranch(retry)",await Yr({stateBranchRoot:o,repoRoot:r}))}if(a(T))return yi(T.message)?fl({repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,bootstrapped:s}):ke(T.message);p=T.value}if(l){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let T=Z("git rev-parse HEAD",await G({args:["rev-parse","HEAD"],cwd:o}));if(a(T))return ke(T.message);u=T.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return ss(p?"Synced and pushed":m||l?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),c("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:l,commitSha:u,pulled:m,pushed:p,bootstrapped:s,offline:!1})},Gh=async(e,t)=>{let n=tl(e);try{return await t()}finally{let r=nl(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},ls=async e=>{let t=e.cwd??process.cwd(),n=await ut(t);if(a(n))return ke(n.message);let r=Se({repoRoot:n.value});if(a(r))return ke(r.message);let o=r.value;if(!jh.existsSync(o))return hl(e);let s=await pl({worktreeRoot:o,operation:"sync",fn:()=>Gh(o,()=>hl(e))});return a(s)?ke(s.message):s.value===null?c("Another process is syncing this board",{repoRoot:n.value,stateBranchRoot:o,createdCommit:!1,pulled:!1,pushed:!1,bootstrapped:!1,offline:!1,skipped:!0}):s.value}});var At,us,qh,vl,Xi=y(()=>{"use strict";zc();qr();jt();gt();le();C();k();is();as();Yi();At=null,us=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!At,currentStatus:f().syncStatus?.status,currentMessage:f().syncStatus?.msg}),At)return logger.debug("[sync] syncAndReloadState joining existing promise"),At;logger.debug("[sync] syncAndReloadState creating promise"),At=qh();try{let e=await At;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:f().syncStatus?.status,statusMessageAfterResolve:f().syncStatus?.msg}),a(e)&&f().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}),At||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:f().syncStatus?.status,statusMessageBeforeClear:f().syncStatus?.msg}),At=null}},qh=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:f().mode,syncStatus:f().syncStatus});let e=vl();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:f().mode,message:e.message,syncStatus:f().syncStatus}),e;if(At)return At;logger.debug("[sync] syncAndReloadState:start");let t=Z("resolveActorId",fe());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:f().syncStatus});let n=Pn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=Z("syncEpiqWithRemote",await ls({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(r),message:(a(r),r.message)}),a(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),E({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:f().syncStatus}),ke(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value;logger.debug("[sync] loading merged events after sync",{stateBranchRoot:o});let d=Z("loadMergedEvents",$t(o));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(d),message:(a(d),d.message),count:a(d)?void 0:d.value.events.length}),a(d))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:f().syncStatus}),i(`Unable to load events. ${d.message}`);logger.debug("[sync] loaded merged events after sync",{count:d.value.events.length});let l=vl();if(l)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:f().mode,message:l.message,syncStatus:f().syncStatus}),l;let u=qc(),m=f().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:u,selectedNodeId:f().selectedNode?.id,contextNodeId:f().contextNode?.id,selectedNodeIsVirtual:f().selectedNode?.isVirtual,contextNodeIsVirtual:f().contextNode?.isVirtual}),!f().selectedNode?.isVirtual&&!f().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:d.value.events.length});let g=Z("bootStateFromEventLog",an(d.value.events,d.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(g),message:(a(g),g.message)}),a(g))return E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:f().syncStatus}),i(`Unable to boot synced state. ${g.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:f().selectedNode?.isVirtual,contextNodeIsVirtual:f().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),E({filters:m}),logger.debug("[sync] restoreNavigationAnchor:start");let p=Z("restoreNavigationAnchor",Kc(u));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(p),message:a(p)?p.message:"Navigation restored",selectedNodeId:f().selectedNode?.id,contextNodeId:f().contextNode?.id}),a(p)?(E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:f().syncStatus}),p):(E({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:f().syncStatus}),c("Synced",!0))},vl=()=>f().mode===h.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:f().mode,syncStatus:f().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 or,yl,bl,Ji,Qi,Jr,Zi,Vh,xl,Kh,Il,ms=y(()=>{"use strict";C();Be();k();Xi();or=3e3,yl=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<or?null:t},bl=0,Qi=!1,Jr=!1,Zi=()=>{if(Qi)return!0;let e=He();return a(e)?!1:e.value.syncStatus.status==="syncing"},Vh=()=>{let e=ve().autoSyncIntervalMs??1e4,t=Date.now()-bl;return Math.max(0,e-t)},xl=()=>{Ji||(Ji=setTimeout(async()=>{if(Ji=void 0,!!ot()){if(Zi()){Jr=!0;return}Jr=!1,await Kh()}},Vh()))},Kh=async()=>{if(f().readOnly||f().timeMode==="peek"||f().timeMode==="replay")return i("Cannot auto-sync while peeking");if(!ot())return i("Cannot auto-sync before state is initialized");if(Zi())return Jr=!0,i("Sync already in progress");Qi=!0,bl=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await us()}finally{Qi=!1,Jr&&xl()}},Il=()=>{ot()&&(Jr=!0,!Zi()&&xl())}});import Qr from"node:fs";import Zr from"node:path";import{z as sr}from"zod";var ps,zh,Yh,Xh,Rl,Sl,El,Nl,Cl,Al,Jh,gs,ea,eo=y(()=>{"use strict";C();Ot();_o();re();ps="recent-projects.json",zh=20,Yh=sr.object({projectId:sr.string().min(1),root:sr.string().min(1),lastOpenedAt:sr.number().finite()}),Xh=sr.object({projects:sr.array(Yh)}),Rl=()=>Zr.join(Rn(),ps),Sl=e=>Zr.basename(e)||e,El=e=>{let t=Zr.resolve(e);try{return Qr.realpathSync(t)}catch{return t}},Nl=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Cl=e=>{if(!Or(e.root))return!1;let t=kr(e.root);return!a(t)&&t.value===e.projectId},Al=()=>{let e=Rl();if(!Qr.existsSync(e))return c("No recent projects recorded",[]);let t;try{t=JSON.parse(Qr.readFileSync(e,"utf8"))}catch(r){return i(`Invalid ${ps}: ${r instanceof Error?r.message:String(r)}`)}let n=Xh.safeParse(t);return n.success?c("Read recent projects",n.data.projects):i(`Invalid ${ps} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Jh=e=>{let t=Rl();try{Qr.mkdirSync(Zr.dirname(t),{recursive:!0}),Qr.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
56
|
-
`,"utf8")}catch(n){return i(`Unable to write ${ps}: ${n instanceof Error?n.message:String(n)}`)}return c("Recorded recent project",e)},gs=({exclude:e}={})=>{let t=Al();if(a(t))return t;let n=e===void 0?null:El(e);return c("Listed recent projects",t.value.filter(r=>n===null||El(r.root)!==n).filter(Cl).sort(Nl))},ea=({root:e,now:t=Date.now()})=>{let n=Zr.resolve(e),r=kr(n);if(a(r))return i(r.message);let o=r.value,s=Al(),d=a(s)?[]:s.value,l=[{projectId:o,root:n,lastOpenedAt:t},...d.filter(u=>u.projectId!==o&&u.root!==n)].filter(Cl).sort(Nl).slice(0,zh);return Jh(l)}});var fs,Tl,wl,Ml,to=y(()=>{"use strict";C();Ot();Be();re();fs=()=>{let e=ve(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1;return{isSetupDone:n&&t&&r,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r}},Tl=()=>{let e=Xe(process.cwd());if(a(e))return!1;let t=Ft(e.value);return ht(t)},wl=e=>e===!0?"on":e===!1?"off":null,Ml=e=>e==="on"?!0:e==="off"?!1:null});var Le,S,Pe=y(()=>{"use strict";Le={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"},S={accent:Le.cyan,accent2:Le.magenta,primary:Le.white,secondary:Le.grayDark,secondary2:Le.grayLight,gray:Le.gray,green:Le.green,yellow:Le.yellow,red:Le.red}});var R,ir,hs=y(()=>{"use strict";Pe();R={red:Le.red,yellow:Le.yellow,green:Le.green,blue:Le.blue,magenta:Le.magenta,cyan:Le.cyan},ir={urgent:R.red,critical:R.red,important:R.red,blocker:R.red,asap:R.red,immediate:R.red,fail:R.red,failure:R.red,broken:R.red,bug:R.red,error:R.red,incident:R.red,outage:R.red,production:R.red,crash:R.red,security:R.red,warning:R.yellow,warn:R.yellow,risky:R.yellow,risk:R.yellow,attention:R.yellow,pending:R.yellow,review:R.yellow,"needs-review":R.yellow,qa:R.yellow,testing:R.yellow,test:R.yellow,validate:R.yellow,verification:R.yellow,staging:R.yellow,check:R.yellow,"follow-up":R.yellow,followup:R.yellow,waiting:R.yellow,blocked:R.yellow,hold:R.yellow,done:R.green,complete:R.green,completed:R.green,success:R.green,ok:R.green,stable:R.green,resolved:R.green,fixed:R.green,closed:R.green,merged:R.green,released:R.green,deployed:R.green,approved:R.green,verified:R.green,working:R.green,healthy:R.green,pass:R.green,passing:R.green,info:R.blue,information:R.blue,note:R.blue,docs:R.blue,documentation:R.blue,doc:R.blue,guide:R.blue,help:R.blue,explanation:R.blue,detail:R.blue,details:R.blue,context:R.blue,design:R.blue,discussion:R.blue,proposal:R.blue,idea:R.blue,feature:R.magenta,enhancement:R.magenta,improvement:R.magenta,refactor:R.magenta,refactoring:R.magenta,cleanup:R.magenta,optimize:R.magenta,optimization:R.magenta,perf:R.magenta,performance:R.magenta,upgrade:R.magenta,migration:R.magenta,modernize:R.magenta,debt:R.magenta,todo:R.cyan,next:R.cyan,planned:R.cyan,plan:R.cyan,future:R.cyan,backlog:R.cyan,investigate:R.cyan,explore:R.cyan,prototype:R.cyan}});var Qh,Zh,dn,cn,vs,ys,no=y(()=>{"use strict";ge();C();me();k();Qh=e=>e.props.tags??[],Zh=e=>e.props.assignees??[],dn=e=>Qh(e).map(t=>x.getTag(t)).filter(t=>!!t),cn=e=>Zh(e).map(t=>x.getContributor(t)).filter(t=>!!t),vs=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!P(n)?i("Invalid untag target"):c("Retrieved tags from ticket in breadcrumb",dn(n))},ys=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!P(n)?i("Invalid unassign target"):c("Retrieved assignees from ticket in breadcrumb",cn(n))}});var v,_n=y(()=>{"use strict";v={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",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 ev,tv,nv,rv,ov,Un,kl,bs,xs,Ll,sv,ta,ro=y(()=>{"use strict";ev=/^(\d+)(h|d|w|mo|y)$/,tv=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,nv=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let s=new Date(e,t-1,n,r,o);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===r&&s.getMinutes()===o},rv=(e,t=new Date)=>{let n=e.match(ev);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let d=new Date(t);switch(o){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}},ov=e=>{let t=e.match(tv);if(!t)return null;let[,n,r,o,s,d]=t,l=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,g=d?Number(d):0;return nv({year:l,month:u,day:m,hour:p,minute:g})?new Date(l,u-1,m,p,g):null},Un=e=>{let t=e.trim().toLowerCase();return rv(t)??ov(t)},kl=/^(\d+)(s|m)?$/,bs=e=>{let t=e.trim().toLowerCase().match(kl);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},xs=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&kl.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Ll=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,sv=[{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}],ta=(e=sv)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let s=r;s<=o;s++)t.push(`${s}${n}`);return t}});var iv,pe,Qe,Ee,av,dv,ra,oa,Fl,$n,Is,na,Pl,cv,lv,oo,Dl,uv,mv,sa,pv,be,ln=y(()=>{"use strict";ms();eo();C();to();nr();ge();me();k();hs();no();_n();ro();iv=["BOARD","TICKET","SWIMLANE","COMMENT"],pe={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},Qe={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Ee={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},av=[pe.EDITOR,pe.VIEW,pe.USERNAME,pe.AUTOSYNC,pe.SYNC_DEBOUNCE_MS,pe.ATTACHMENT_MAX_KB,pe.LOG_LEVEL],dv=(e=f().selectedNode?.context)=>{switch(e){case"TICKET":return[Qe.TITLE,Qe.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Qe.TITLE];case"COMMENT":return[Qe.COMMENT];default:return[]}},ra=[String(or),"5000","15000","30000","60000"],oa=["250","500","1000"],Fl=["10s","20s","30s","45s"],$n=[v.COFFEE,v.EXIT,v.SYNC,v.HELP,v.EXPORT,v.CONFIG,v.YANK],Is=[v.NEW,v.EDIT,v.DELETE,v.MOVE],na=[v.TAG,v.UNTAG,v.ASSIGN,v.UNASSIGN,v.CLOSE_ISSUE,v.RE_OPEN_ISSUE,v.EDIT,v.COMMENT],Pl=[v.FILTER,v.PEEK,v.REPLAY],cv={WORKSPACE:[...$n,...Is],BOARD:[...Pl,...$n,...Is],SWIMLANE:[...Pl,...$n,...Is],TICKET:[...$n,...Is,...na],FIELD:[...$n,...na],FIELD_LIST:[...$n,...na],TEXT:[...$n],COMMENT:[v.EDIT,v.DELETE,v.YANK]},lv=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],oo=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&P(n)),Dl=e=>e.parentNodeId===ye,uv=({selectedNode:e,breadCrumb:t})=>{let n=dv(e?.context);return oo({breadCrumb:t,selectedNode:e})?n.includes(Qe.DESCRIPTION)?n:[...n,Qe.DESCRIPTION]:n},mv=({selectedNode:e,breadCrumb:t})=>{let n=oo({breadCrumb:t,selectedNode:e});return n?[Ee.REF,Ee.TITLE,...n.props?.description?.trim()?[Ee.DESCRIPTION]:[],...dn(n).length>0?[Ee.TAGS]:[],...cn(n).length>0?[Ee.ASSIGNEES]:[]]:e?[Ee.REF,Ee.TITLE]:[]},sa=()=>{let e=gs({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},pv=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=fs();if(!r)return[v.HELP,v.CONFIG];if(!Tl())return[v.HELP,v.INIT,v.OPEN];if(t)return[v.HELP,v.PEEK,v.REPLAY,v.EXPORT,v.CONFIG,v.YANK];let o=e?.context,s=o&&iv.includes(o),d=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?cv[u]:[]))],l=oo({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&&dn(l).length>0):u===v.UNASSIGN?!!(l&&cn(l).length>0):u===v.RE_OPEN_ISSUE?!!(l&&Dl(l)):u===v.CLOSE_ISSUE?!!(l&&!Dl(l)):!0)},be=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=f())=>{let s=t.context??"WORKSPACE";return{[v.NONE]:pv({breadCrumb:o,readOnly:r,selectedNode:n}),[v.EXIT]:["confirm"],[v.EXPORT]:[],[v.SYNC]:[],[v.INIT]:[],[v.OPEN]:e===v.OPEN?sa():[],[v.HELP]:[],[v.PEEK]:[...ta(),"now","prev","next"],[v.REPLAY]:[...ta()],[v.EDIT]:uv({selectedNode:n,breadCrumb:o}),[v.YANK]:mv({selectedNode:n,breadCrumb:o}),[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","actor","description","title","ref","clear"],[v.TAG]:[...new Set([...Object.keys(ir),...x.getExistingTags()])],[v.UNTAG]:[...vs()?.value?.map(({name:l})=>l)??[]],[v.UNASSIGN]:[...ys()?.value?.map(({name:l})=>l)??[]],[v.ASSIGN]:x.getExistingAssignees(),[v.NEW]:lv(s),[v.CONFIG]:[...av],[v.COFFEE]:["1","3","5","20","custom"]}[e]??[]}});var Ol,Bl=y(()=>{"use strict";Ol=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{accessSync as gv,copyFileSync as fv,existsSync as Es,mkdirSync as _l,readdirSync as Ul,readFileSync as hv,renameSync as vv,rmSync as yv,statSync as $l,unlinkSync as bv,writeFileSync as xv}from"node:fs";import ar from"node:path";var ia,We,Rs=y(()=>{"use strict";ia=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",We={writeToFile:(e,t)=>{try{let n=ar.dirname(e);Es(n)||_l(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);xv(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return hv(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=We.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 Es(e)&&$l(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await gv(e),!0}catch{return!1}},mkDir:e=>_l(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=ar.parse(t);for(;;){let r=ar.join(t,e);try{if(Es(r)&&$l(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=ar.dirname(t)}return null},readFirstJSON(e){try{if(!We.dirExists(e))return null;let t=Ul(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=ar.join(e,t);return We.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return We.dirExists(e)?Ul(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{bv(e)}catch(t){(!ia(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{yv(e,{recursive:!0,force:!0})}catch(t){(!ia(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(ar.dirname(t)),!n?.overwrite&&Es(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{vv(e,t)}catch(r){if(ia(r)&&r.code==="EXDEV"){fv(e,t),this.rmFile(e);return}throw r}}}});import Iv from"node:path";import{z as Wt}from"zod";var Ev,jl,Rv,Hl,aa,da,Sv,Ss,Wl,st,ca,jn=y(()=>{"use strict";Qn();re();C();Rs();Ev={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},jl=Wt.object({logLevel:Wt.enum(["info","error","debug"]),preferredEditor:Wt.string().optional(),userName:Wt.string().optional(),userId:Wt.string().optional(),autoSync:Wt.boolean().nullable().optional(),autoSyncDebounceMs:Wt.number().optional(),attachmentMaxKb:Wt.number().optional(),viewMode:Wt.enum(["dense","wide"]).optional()}).partial(),Rv="config.json",Hl=Rn,aa=()=>Iv.join(Hl(),Rv),da=()=>{try{return We.mkDir(Hl()),c(`Ensured ~/${ct} exists`,null)}catch{return i(`Unable to create ~/${ct}`)}},Sv=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${ct}/config.json JSON`)}let n=jl.safeParse(t??{});return n.success?c("Parsed config",n.data):i(`Invalid ~/${ct}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Ss=()=>{let e=da();if(a(e))return i(e.message);let t=aa(),n=We.readFile(t);return n==null||n.trim()===""?c("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Sv(n)},Wl=e=>{let t=da();if(a(t))return i(t.message);let n=jl.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=aa();try{return We.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
57
|
-
`),c("Config written",null)}catch{return i(`Unable to write ~/${ct}/config.json`)}},st=e=>{let t=Ss();if(a(t))return i("Failed to read existing config");let n={...t.value,...e};return Wl(n)},ca=()=>{let e=aa(),t=da();if(a(t))return i(`Unable to create ~/${ct}`);if(!(We.readFile(e)!==null)){let A=Wl(Ev);if(a(A))throw new Error(`Unable to create ~/${ct}/config.json`)}let r=Ss();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:d,autoSync:l,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:g}=r.value,I=ii({userId:d,userName:s});if(a(I))return i(I.message);let N=I.value??{userId:d,userName:s};return!N.userName||!N.userId?i(`User name or ID not configured in ~/${ct}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,c("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:N.userName,userId:N.userId,autoSync:l??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:g??"dense"}))}});var Gl,ql,la,Vl=y(()=>{"use strict";Gl="/media/",ql=e=>`${Gl}${e}`,la=(e,t)=>`})`});import Nv from"node:crypto";import ua from"node:fs";import Cv from"node:path";var Gt,so,Av,Tv,wv,Kl,io=y(()=>{"use strict";bt();C();re();Vl();Gt=500,so=(e,t)=>`${e}.${t}`,Av=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?c("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?c("Sniffed image type","jpg"):e.length>=6&&(e.subarray(0,6).equals(Buffer.from("GIF87a","ascii"))||e.subarray(0,6).equals(Buffer.from("GIF89a","ascii")))?c("Sniffed image type","gif"):e.length>=12&&e.subarray(0,4).equals(Buffer.from("RIFF","ascii"))&&e.subarray(8,12).equals(Buffer.from("WEBP","ascii"))?c("Sniffed image type","webp"):i(`Unsupported image format. Allowed: ${Ed.join(", ")}`),Tv=e=>Nv.createHash("sha256").update(e).digest("hex"),wv=(e,t=Gt)=>{if(e.length===0)return i("Attachment is empty");if(e.length>t*1024)return i(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=Av(e);return a(n)?n:c("Validated attachment data",{hash:Tv(e),ext:n.value,bytes:e.length})},Kl=(e,t,n=Gt)=>{let r=wv(t,n);if(a(r))return r;let o=qo(e),s=Cv.join(o,so(r.value.hash,r.value.ext));try{ua.existsSync(s)||(ua.mkdirSync(o,{recursive:!0}),ua.writeFileSync(s,t))}catch(d){return i(`Unable to write attachment blob: ${d instanceof Error?d.message:String(d)}`)}return c("Wrote attachment blob",r.value)}});import Mv from"zod";var ao,co,zl,ma=y(()=>{"use strict";jn();io();le();C();xe();Be();k();ao=50,co=5e3,zl=()=>{let e=de().commandMeta.inputString,t=Mv.coerce.number().int().min(ao).max(co).safeParse(e);if(!t.success)return i(`Attachment size cap must be ${ao}-${co} KB (default ${Gt})`);let n=st({attachmentMaxKb:t.data});return a(n)?n:(et({attachmentMaxKb:t.data}),E({mode:h.DEFAULT}),c(`Attachment size cap set to ${t.data} KB`,null))}});import Yl from"chalk";var ga,Xl,pa,Jl,kv,Lv,Ql,Pv,Dv,lo,De,Zl,eu,Ns,Fv,Ov,Cs,Tt=y(()=>{"use strict";hs();ga={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Xl=(e,t,n)=>Math.max(t,Math.min(n,e)),pa=(e,t,n)=>e+(t-e)*n,Jl=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},kv=e=>e.toLowerCase().trim(),Lv=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,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 g=o-s/2;return[Math.round((u+g)*255),Math.round((m+g)*255),Math.round((p+g)*255)]},Ql=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Pv=(e,t,n)=>{let r=Xl(n,0,1);return[Math.round(pa(e[0],t[0],r)),Math.round(pa(e[1],t[1],r)),Math.round(pa(e[2],t[2],r))]},Dv=(e,t,n)=>Pv(e,t,n),lo=e=>{let t=Jl(e)%360,n=Lv(t,ga.stringColor.saturation,ga.stringColor.lightness);return Ql(n)},De=(e,t=ir)=>{let n=kv(e??"");return n&&t[n]?t[n]:lo(n)},Zl=e=>{let t=ga.gradient.stops,n=Xl(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,s=Math.min(Math.floor(o),r-1),d=o-s;return Dv(t[s],t[s+1],d)},eu=e=>Ql(Zl(e)),Ns=e=>Jl(e.toLowerCase().trim())/4294967295,Fv=e=>{let t=Ns(e);return Zl(t)},Ov=e=>{let[t,n,r]=Fv(e);return{normal:o=>Yl.bgRgb(t,n,r).black(o),cursor:o=>Yl.bgRgb(t,n,r).white.bold(o)}},Cs=e=>Ov(e).normal(` ${e} `)});var ft,uo=y(()=>{"use strict";ft=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null});import{createHash as Bv}from"node:crypto";var _v,Uv,Ce,dr=y(()=>{"use strict";_v="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Uv=e=>{let t=Bv("sha256").update(e).digest(),n=0n;for(let o=0;o<16;o++)n=n<<8n|BigInt(t[o]);let r="";for(let o=0;o<26;o++){let s=BigInt((25-o)*5);r+=_v[Number(n>>s&31n)]}return r},Ce=(e,t)=>Uv(`${e}:virtual:${t}`)});import tu from"chalk";var te,Ae,Te,nu=y(()=>{"use strict";Tt();Pe();te=e=>tu.dim(e),Ae=e=>tu.hex(S.primary)(e),Te=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let d=o.trim();if(d.length<s)return"";let p=[...t.filter(Boolean).filter(g=>g.startsWith(d))].sort((g,I)=>Ns(g)-Ns(I)).slice(0,r).map(g=>Cs(g)).join(" ");return p?`${te(e)}${p}${te(n)}`:""}});var un,As=y(()=>{"use strict";un={None:"none",Invalid:"invalid",Valid:"valid"}});import su from"chalk";var $v,ru,ce,Y,j,cr,ou,Ts,fa,jv,Hn,Hv,Wv,Gv,qv,Vv,iu,au=y(()=>{"use strict";ms();to();Bl();dt();bt();C();me();Be();ma();io();k();Tt();uo();no();dr();nu();_n();As();ln();ro();$v=["BOARD","TICKET","SWIMLANE"],ru=()=>{let e=f().selectedNode;if(!e?.context)return j({message:te("Missing target context")});if($v.includes(e.context))return Y();if(e.parentNodeId){let t=f().nodes[e.parentNodeId];if(t?.id===Ce(t?.parentNodeId??"","comments"))return Y()}return j({message:te("Command not available in this context")})},ce="<ENTER> to confirm",Y=(e="",t=[])=>({message:te(e),validity:un.Valid,completionWordList:t}),j=({message:e,completionWordList:t=[]})=>({validity:un.Invalid,message:e,completionWordList:t}),cr=e=>e.length===0,ou=(e,t)=>{let n=ze(f().breadCrumb,"BOARD");if(a(n))return j({message:Ae("Command is not applicable in this context")});let r=Id(n.value.id);return a(r)?j({message:Ae(`Unable to ${t}: board id is not a valid ULID`)}):Ll({date:e,horizonDate:r.value})?null:j({message:Ae(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},Ts=e=>` ${su.hex("#000").bgHex(De(e))(` ${e} `)} `,fa=({modifier:e})=>{let t="confirm";return e===t?Y(ce):j({message:cr(e)?te("if you are certain, enter ")+Cs(t):"",completionWordList:[t]})},jv=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?j({message:te(n)}):Y():j({message:cr(r)?t:"",completionWordList:[...e]}),Hn=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>cr(n)&&cr(r)?j({message:e,completionWordList:[]}):Y(t??ce),Hv=({modifier:e,inputString:t})=>{let n=sa();return!cr(e)||!cr(t)?Y(ce):j({message:n.length?te("number from the list, or a path"):te("path to an epiq project"),completionWordList:n})},Wv=({modifier:e,inputString:t})=>{let n=be(v.CONFIG);if(!n.includes(e))return j({message:Te({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case pe.EDITOR:{let r=[...Ol];return t.trim()?r.includes(t.trim())?Y(ce):j({message:Te({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):j({message:Te({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case pe.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?Y(ce):j({message:Te({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case pe.USERNAME:return t.trim()?Y(ce):j({message:Ae("Enter a user name. Saved in ")+su.bgBlack("~/.epiq-global/config.json")});case pe.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?Y(ce):j({message:Te({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case pe.AUTOSYNC:{let r=["on","off"],o=ve().autoSync;if(!r.includes(t.trim())){let s=wl(o);return j({message:Te({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return Y(ce)}case pe.ATTACHMENT_MAX_KB:{let r=ve().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<ao||o>co){let s=Te({prefix:" examples: ",wordList:oa,minLengthForHints:0,inputString:t});return j({message:Ae(`provide a size cap in KB (${ao}-${co}). current: ${r??Gt} KB.`)+s,completionWordList:oa})}return Y(ce)}case pe.SYNC_DEBOUNCE_MS:{let r=ve().autoSyncIntervalMs,o=yl(t);if(!t.trim()||o===null||o<or){let s=Te({prefix:" examples: ",wordList:ra,minLengthForHints:0,inputString:t});return j({message:Ae(`provide duration above ${or}ms. current duration: ${r}ms.`)+s,completionWordList:ra})}return Y(ce)}default:return j({message:Ae("Unknown config option"),completionWordList:n})}},Gv=({modifier:e,inputString:t})=>{let n=be(v.EDIT);if(!n.length)return j({message:Ae("Command not available in this context")});if(!n.includes(e)){let r=Te({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return j({message:r||Ae("Unknown edit option"),completionWordList:n})}switch(e){case Qe.COMMENT:return t.trim()?Y(ce):j({message:te("write a comment...")});case Qe.TITLE:return Y(ce);case Qe.DESCRIPTION:{let{preferredEditor:r}=ve();return r?Y(te("<ENTER> to edit in ")+r):j({message:"No editor selected"})}default:return j({message:Ae("Unknown edit option"),completionWordList:n})}},qv=({modifier:e})=>{let t=be(v.YANK);return t.length?t.includes(e)?Y(ce+te(" and copy to clipboard")):j({message:Te({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):j({message:Ae("Nothing selected to copy from")})},Vv={[v.EXPORT]:()=>Y(ce+te(", and create export markdown file")),[v.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return Y(ce);let n={message:te("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Un(r);if(!r||!o)return j(n);let s=ou(o,"peek");return s||Y(ce)},[v.REPLAY]:e=>{let{dateInput:t,durationInput:n}=xs(e.modifier,e.inputString),r={message:te("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Un(t);if(!t||!o)return j(r);let s=ou(o,"replay");return s||(n&&bs(n)===null?j({message:Ae("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):Y("<ENTER> to replay board history",n?Fl:[]))},[v.EXIT]:()=>Y(ce+te(" and exit the application")),[v.INIT]:()=>Y(ce),[v.OPEN]:Hv,[v.PALETTE]:()=>Y(ce),[v.FILTER]:e=>{if(e.modifier==="clear")return Y(ce);let t=s=>be(v.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return j({message:Te({wordList:be(v.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:be(v.FILTER)});let n=Object.values(f().tags).map(s=>s.name),r=Object.values(f().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?j({message:Te({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):Y():j({message:Te({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[v.NONE]:e=>{let t=be(v.NONE);return j({message:Te({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[v.NEW]:e=>jv({list:be(v.NEW),hint:Te({wordList:be(v.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[v.HELP]:()=>Y(ce),[v.EDIT]:Gv,[v.COMMENT]:e=>{let t=Hn({hint:te(`write a comment (max ${4e3} char)...`),onOk:te(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===un.Invalid?t:e.inputString.length>4e3?Y(Ae("max input exceeded")):t},[v.CONFIG]:Wv,[v.YANK]:qv,[v.DELETE]:e=>{let t=ru();return t.validity==="invalid"?t:fa(e)},[v.CLOSE_ISSUE]:e=>fa(e),[v.RE_OPEN_ISSUE]:e=>fa(e),[v.MOVE]:e=>{let t=ru();return t.validity==="invalid"?t:Hn({hint:Te({prefix:"hey hacker! These commands are blocked for you... ",wordList:be(v.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[v.TAG]:e=>{let n=x.getExistingTags().slice(0,10).map(Ts).join("");return Hn({hint:n.length?te("create tag or reuse:")+n+te(""):te("create tag ...")})(e)},[v.UNTAG]:e=>{let t=vs();if(a(t))return j({message:Ae("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Ts).slice(0,10);return n.length?Hn({hint:te(" ... ")+n.join("")})(e):j({message:Ae("Issue has no tags"),completionWordList:[]})},[v.ASSIGN]:e=>{let t=x.getExistingAssignees().map(Ts).slice(0,10);return Hn({hint:te("assignees... ")+t.join("")})(e)},[v.UNASSIGN]:e=>{let t=ys();if(a(t))return j({message:Ae("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Ts).slice(0,10);return n.length?Hn({hint:te("remove assignee... ")+n.join("")})(e):j({message:Ae("Issue has no assignees"),completionWordList:[]})},[v.SYNC]:()=>Y(ce),[v.COFFEE]:e=>{let{modifier:t}=e,n=be(v.COFFEE);return t.length&&t.length<=1&&!n.includes(t)?j({message:te("enter an amount ... "),completionWordList:n.filter(r=>r.startsWith(t))}):Hn({hint:Te({prefix:"fuel continued development with ... $ ",wordList:["1"," 3 ","5","20","custom"],inputString:"",minLengthForHints:0}),onOk:"Thank you for your support! \u{1FAE1}"})(e)}},iu=Object.fromEntries(Object.entries(Vv).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]))});var ws,du=y(()=>{"use strict";ws=["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 Kv,zv,Yv,Xv,Jv,cu,lu,uu,mu=y(()=>{"use strict";C();k();du();Kv=3,zv=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"]),Yv=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let r=n.props;typeof r.description=="string"&&t.push(r.description),typeof r.value=="string"&&t.push(r.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},Xv=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=Kv&&!zv.has(t)&&!/^\d+$/.test(t)),Jv=e=>{let t=new Map;for(let s of Yv(e))for(let d of Xv(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),r=new Set(n),o=ws.filter(s=>!r.has(s));return[...n,...o]},cu=ws,lu=-1,uu=()=>{let e=He();if(a(e))return ws;let t=e.value,n=t.eventLog.length;return n!==lu&&(cu=Jv(t),lu=n),cu}});var pu,gu,ha=y(()=>{"use strict";Pd();ln();_n();au();mu();k();le();pu=e=>Object.values(v).includes(e),gu=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:d,validity:l,completionWordList:u}=iu[n].validate(n,r,s),m=n!==v.PEEK&&n!==v.REPLAY,p=o==="command"||o==="modifier"?be(n):m?uu():[],{mode:g}=f(),I=g===h.COMMAND_LINE?d??"":"",N=[...u,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:I,autoCompletion:t?Ld(e,N):{hint:"",hints:[],remainder:"",overlap:0}}}});var fu,Qv,Zv,ey,hu=y(()=>{"use strict";ha();ln();fu=e=>{let t=e.trimStart(),n=Zv(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),d=ey(e),l=pu(r)?r:null,u=l!==null,m=r!=="",p=l?be(l)??[]:[],g=l&&p.includes(o)?o:"",I="word";n.length===0||n.length===1&&!s?I="command":(n.length===1&&s||n.length===2&&!s)&&(I="modifier");let N=s?"":d,A=Qv(t,l,g);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:d,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:s,modifier:g,target:I,inputToMatch:N,inputString:A}},Qv=(e,t,n)=>{let r=e;return t&&r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/^\s+/,""),n&&r.startsWith(n)&&(r=r.slice(n.length),r=r.replace(/^\s+/,"")),r},Zv=e=>e.trim()?e.trim().split(/\s+/):[],ey=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as aT}from"react";var lr,va,ur,ty,vu,wt,mo,ya,ba,yu,bu,Ms,xu,K,Iu,Eu,Ru,de,ks,xe=y(()=>{"use strict";ha();hu();C();As();lr=e=>e===va||e===":",va=" ",ur={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:un.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},ty=new Set,vu=()=>{for(let e of ty)e()},wt=e=>{let n=e(ur),r=fu(n.value),o=n.cursorPosition===n.value.length;ur={...n,commandMeta:gu(r,o)},vu()},mo=({message:e,status:t})=>{let n=structuredClone(ur);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,ur=n,vu(),c(e,null)},ya=e=>{wt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},ba=e=>{wt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&lr(n[o-1]);)o--;for(;o>0&&!lr(n[o-1]);)o--}else{for(;o<n.length&&!lr(n[o]);)o++;for(;o<n.length&&lr(n[o]);)o++}return{...t,cursorPosition:o}})},yu=()=>{wt(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}})},bu=()=>{wt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&lr(t[r-1]);)r--;for(;r>0&&!lr(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Ms=e=>{wt(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),d=s+o,l=Math.max(0,Math.min(s.length,d.length));return{...t,value:d,cursorPosition:l,commandIsPending:!1}})},xu=()=>{wt(e=>({...e,commandIsPending:!0}))},K=e=>{wt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Iu=({addToHistory:e=!0})=>{wt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Eu=()=>{wt(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}})},Ru=()=>{wt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},de=()=>ur,ks=()=>{let[e,...t]=ur.value.split(va);return t.join(va).trim()}});var D,xn=y(()=>{"use strict";le();Sd();k();xe();Be();D={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 Su,F,xa=y(()=>{"use strict";k();_n();Su=e=>{let{context:t}=f().contextNode;if(!t)return F.None;switch(e){case v.EXIT:return F.Exit;case v.EXPORT:return F.Export;case v.COFFEE:return F.Coffee;case v.INIT:return F.Init;case v.OPEN:return F.OpenProject;case v.DELETE:return F.Delete;case v.EDIT:return F.Edit;case v.COMMENT:return F.Comment;case v.HELP:return F.ViewHelp;case v.RE_OPEN_ISSUE:return F.ReopenIssue;case v.CLOSE_ISSUE:return F.CloseIssue;case v.TAG:return F.TagTicket;case v.UNTAG:return F.UntagTicket;case v.ASSIGN:return F.AssignUserToTicket;case v.UNASSIGN:return F.UnassignUserFromTicket;case v.NEW:return F.NewItem;case v.FILTER:return F.Filter;case v.MOVE:return F.Move;case v.PEEK:return F.Peek;case v.REPLAY:return F.Replay;case v.CONFIG:return F.Config;case v.YANK:return F.Yank;case v.SYNC:return F.Sync;default:return F.None}},F={Exit:"exit",Init:"init",OpenProject:"open-project",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 Nu}from"ink";import Cu,{useEffect as Au,useState as ny}from"react";var Tu,qe,mr=y(()=>{"use strict";k();Pe();Tu={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},qe=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Ve(),r=Tu[n]??Tu.default,[o,s]=ny(0);if(Au(()=>{s(0)},[r]),Au(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return Cu.createElement(Nu,null,t);let d=r[o]??r[0]??t;return Cu.createElement(Nu,{color:S.accent,dimColor:o===1},d)}});import{Box as Ia,Text as ry}from"ink";import Ls from"react";var oy,mn,po=y(()=>{"use strict";Pe();oy=(e,t,n,r)=>{let o=u=>Math.max(1,e[u]??1),s=n,d=n+1,l=o(n);for(;d<t&&l+o(d)<=r;)l+=o(d),d++;for(;s>0&&l+o(s-1)<=r;)s--,l+=o(s);return{start:s,end:d}},mn=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let d=Math.max(1,Math.floor(t)),l=Math.max(1,Math.ceil(r)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(1,Math.floor(d/l)),p=Math.max(0,e.length-m),{start:g,end:I}=o?oy(o,e.length,u,d):s?{start:Math.min(p,Math.max(0,u-m+1)),end:Math.min(p,Math.max(0,u-m+1))+m}:{start:Math.min(p,Math.floor(u/m)*m),end:Math.min(p,Math.floor(u/m)*m)+m},N=Math.max(1,I-g),A=e.slice(g,I),w=e.length>N,T=d,M=w?Math.max(1,Math.floor(N/e.length*T)):T,$=Math.max(0,T-M),O=Math.max(1,e.length-N),H=w?Math.floor(g/O*$):0;return Ls.createElement(Ia,{flexDirection:"row",height:d,width:"100%"},Ls.createElement(Ia,{flexDirection:"column",flexGrow:1,height:d},A),Ls.createElement(Ia,{flexDirection:"column",width:1,height:T},Array.from({length:T}).map((Q,Xt)=>Ls.createElement(ry,{key:Xt,color:w&&Xt>=H&&Xt<H+M?S.accent:S.secondary},w?"\u2502":" "))))}});var wu,Ea,sy,Ps,Ra=y(()=>{"use strict";k();sy=()=>{let{eventLog:e=[]}=f();if(Ea&&wu===e)return Ea;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return wu=e,Ea=t,t},Ps=e=>sy().has(e)});import{Text as iy}from"ink";import ay from"react";var dy,cy,pr,Ds=y(()=>{"use strict";hs();Tt();me();Ra();Jt();dy=e=>e.toLowerCase().trim(),cy=(e,t=ir)=>{let n=dy(e);return t[n]?t[n]:lo(n)},pr=({id:e,isSelected:t,maxWidth:n})=>{let r=x.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:In(o,n);return ay.createElement(iy,{underline:t,color:cy(o)},"@"+s,Ps(e)?"":"\u2197")}});import{Text as ly}from"ink";import uy from"react";var Fs,Sa=y(()=>{"use strict";me();Pe();Tt();Jt();Fs=({id:e,isSelected:t,maxWidth:n})=>{let r=x.getTag(e);if(!r)return;let o=n===void 0?r.name:In(r.name,n);return uy.createElement(ly,{underline:t,backgroundColor:De(r.name),color:S.secondary}," "+o+" ")}});import{useEffect as my,useState as py}from"react";var gy,Mu,Os,go,fy,hy,gr,Bs=y(()=>{"use strict";Tt();gy=80,Mu=1400,Os=new Set,go=null,fy=e=>(Os.add(e),go||(go=setInterval(()=>{for(let t of Os)t()},gy)),()=>{Os.delete(e),Os.size===0&&go&&(clearInterval(go),go=null)}),hy=()=>{let e=Date.now()%Mu/Mu;return e<.5?e*2:(1-e)*2},gr=e=>{let[,t]=py(0);return my(()=>{if(e)return fy(()=>t(n=>n+1))},[e]),eu(hy())}});import{Box as fr,Text as hr}from"ink";import Ke from"react";var vy,ku,yy,by,Pu,Du=y(()=>{"use strict";me();Pe();Jt();Ra();tn();no();Ds();Sa();Bs();vy=(e,t,n)=>{if(e.length<=t)return[e,null];let r=e.lastIndexOf(" ",t),o=r>0?r:t;return[e.slice(0,o),In(e.slice(o).trim(),n)]},ku=3,yy=2,by=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let d=e.length-o-1,l=d>0?String(d).length+1:0;if(r+s.width+l>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},Pu=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=gr(r),s=e-4,d=s-7-1,[l,u]=vy(Me(t.title),d,s),m=u?null:In(Me(t.props.description),s)||null,p=dn(t),g=cn(t).map(M=>({...M,name:M.name})),I=Math.max(1,s-ku),N=x.getCommentsByIssue(t.id),A=N.length?String(N.length).length+2+1:0,{shown:w,hidden:T}=by([...p.map(M=>({id:M.id,isTag:!0,width:Math.min(M.name.length,I)+ku})),...g.map(M=>({id:M.id,isTag:!1,width:Math.min(M.name.length,I)+yy+(Ps(M.id)?0:1)}))],s-A);return Ke.createElement(fr,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?S.accent:S.secondary,justifyContent:"space-between"},Ke.createElement(fr,{paddingLeft:1,paddingRight:1,flexDirection:"column"},Ke.createElement(fr,{justifyContent:"space-between"},Ke.createElement(hr,{color:S.primary},l),Ke.createElement(hr,{color:S.secondary2,dimColor:!0},z(t.id))),u&&Ke.createElement(hr,{color:S.primary},u),m&&Ke.createElement(hr,{color:S.secondary2,dimColor:!0},m)),Ke.createElement(fr,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},Ke.createElement(fr,{flexDirection:"row"},w.map(M=>Ke.createElement(fr,{paddingRight:1,key:M.id},M.isTag?Ke.createElement(Fs,{id:M.id,maxWidth:I}):Ke.createElement(pr,{id:M.id,maxWidth:I}))),T>0&&Ke.createElement(hr,{color:S.secondary2,dimColor:!0},"+",T)),N.length>0&&Ke.createElement(hr,{color:S.accent},"[",N.length,"]")))}});import{Box as Wn,Text as fo}from"ink";import Ze from"react";var xy,Fu,Ou=y(()=>{"use strict";le();me();Pe();Tt();mr();Bs();xy=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,Fu=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:d})=>{let l=gr(s),u=(r.props.tags??[]).map(Q=>x.getTag(Q)).filter(Q=>!!Q),m=(r.props.assignees??[]).map(Q=>x.getContributor(Q)).map(Q=>Q&&{...Q,name:Q.name}).filter(Q=>!!Q),p=1,g=u.length*(1+p),I=m.length*(2+p),N=u.map(Q=>Ze.createElement(Wn,{key:Q.id,paddingRight:p},Ze.createElement(fo,{color:De(Q.name)},"\u25A0"))),A=m.map(Q=>Ze.createElement(Wn,{key:Q.id,paddingRight:p},Ze.createElement(fo,{color:lo(Q.name)},"@"+Q.name.at(0)))),w=s?l:o?S.accent:d===h.MOVE?S.secondary:S.primary,T=x.getCommentsByIssue(r.id),M=T.length?String(T.length).length+2+p:0,$=T.length?Ze.createElement(Wn,{paddingRight:p},Ze.createElement(fo,{color:S.accent},"[",T.length,"]")):null,O=g+I+M,H=Math.max(1,n-t-O-(O>0?1:0));return Ze.createElement(Wn,{justifyContent:"space-between"},Ze.createElement(Wn,null,Ze.createElement(Wn,{width:t},o?Ze.createElement(qe,{isSelected:!0}):Ze.createElement(fo,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),Ze.createElement(fo,{wrap:"truncate",color:w},xy(r.title,H))),Ze.createElement(Wn,null,N,A,$))}});import Iy from"chalk";import{Box as Na,Text as Ey}from"ink";import Mt from"react";var Ry,Bu,_u=y(()=>{"use strict";ge();k();Pe();mr();po();Du();Ou();Bs();Ry=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:d,mode:l})=>{let{renderedChildrenIndex:u,replay:m}=Ve(),p=u[e.id]??[],g=m?new Set(m.flashNodeIds):null,I=g?.has(e.id)??!1,N=gr(I),A=`${e.title} ${Iy.hex(S.secondary2).dim("("+p.length+")")}`,w=3,T=o?1:5,M=s&&d===-1,$=n-3-(o?1:0)-(M?2:0),O=Math.max(2,String(p.length).length+1),H=r-w-1,Q=Mt.createElement(Na,{borderStyle:"round",borderColor:S.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},Mt.createElement(qe,{isSelected:t}),Mt.createElement(Ey,{bold:!0,color:I?N:t?S.accent:S.primary},A," ",e.readonly?"\u{1F512}":"")),Xt=(Pt,Xn)=>{let Ir=s&&d===Xn;if(!P(Pt))return null;let Er=g?.has(Pt.id)??!1;return o?Mt.createElement(Fu,{key:Pt.id,index:Xn,labelWidth:O,width:$,ticket:Pt,isSelected:Ir,isFlashing:Er,mode:l}):Mt.createElement(Pu,{key:Pt.id,width:$,ticket:Pt,isSelected:Ir,isFlashing:Er})};return Mt.createElement(Na,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?S.accent:S.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},Q,Mt.createElement(Na,null,p.length>0&&Mt.createElement(mn,{selectedIndex:d,height:H,itemHeight:T},p.map(Xt)),M&&Mt.createElement(qe,{isSelected:!0})))},Bu=Mt.memo(Ry)});var Uu,$u,Ca=y(()=>{"use strict";An();Uu=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},$u=(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})});var vr,_s=y(()=>{"use strict";vr=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"}});import{Box as yr,Text as qt}from"ink";import Fe,{useEffect as Sy,useMemo as Ny,useRef as Cy}from"react";import{decodeTime as ju}from"ulid";function Wu({ticket:e,width:t,height:n}){let r=Ny(()=>Ty(e),[e]),o=Cy([]);Sy(()=>(Hu(o.current),o.current=My(e,r),()=>{Hu(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Ve(),l=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?Fe.createElement(yr,{flexDirection:"column",width:t,height:n,padding:1},Fe.createElement(qt,{color:S.primary},"No attachments yet."),Fe.createElement(yr,{paddingTop:1},Fe.createElement(qt,{color:S.primary},"Attach images from the browser GUI"),Fe.createElement(qt,{color:S.accent}," epiq gui "),Fe.createElement(qt,{color:S.primary},"by dropping or pasting them."))):Fe.createElement(yr,{flexDirection:"column",width:t,height:n},Fe.createElement(yr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:S.secondary,borderStyle:"single",paddingBottom:1},Fe.createElement(qt,{color:S.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),Fe.createElement(mn,{height:l,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let g=p===s,I=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return Fe.createElement(yr,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},Fe.createElement(qt,{color:S.accent},g?"\u276F ":" "),Fe.createElement(yr,{paddingLeft:1},Fe.createElement(qt,{color:S.secondary2},`#${p+1} `),Fe.createElement(qt,{color:g?S.accent:S.primary},I),Fe.createElement(qt,{color:S.secondary2}," "+ky(m.bytes)+" "+vr(yt(m.id)))))})))}var Ay,Ty,Hu,wy,My,ky,Gu=y(()=>{"use strict";Je();dt();_s();ge();C();me();An();k();Pe();dr();po();Ay=e=>Ce(e,"attachments"),Ty=e=>x.getAttachmentsByIssue(e.id).sort((t,n)=>ju(t.id)-ju(n.id)),Hu=e=>{for(let t of e)x.deleteNode(t.id)},wy=(e,t,n)=>Ne.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),My=(e,t)=>{let n=x.getNode(Ay(e.id));if(!n||!Ye(n))return[];let r=t.map((o,s)=>wy(o,s,n.id)).map(o=>x.createNode(o)).filter(ht).map(({value:o})=>o).filter(Ye);return t.length>0&&f().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),r},ky=e=>`${Math.max(1,Math.round(e/1024))} KB`});var Vu,Aa,qu,Ta,Ku,zu,Ly,Yu,Py,wa,Xu=y(()=>{"use strict";Vu=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,Aa=e=>e.replace(Vu,""),qu=e=>e==="additions"||e==="deletions",Ta=e=>{let t=Vu.exec(e);if(!t?.[1])return null;let n;try{n=JSON.parse(t[1])}catch{return null}let r=n;return typeof r?.filePath!="string"||typeof r.start!="number"||typeof r.end!="number"||typeof r.note!="string"||!qu(r.side)||!qu(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r},Ku=/```\n([\s\S]*?)\n?```\s*$/,zu=e=>Ku.exec(e)?.[1]??null,Ly=/`[^`\n]+`[^\n]*\n?$/,Yu=e=>Aa(e).replace(Ku,"").replace(Ly,"").trim(),Py=e=>{let n=(e.endSide??e.side)==="deletions"?"removed":"added";return e.start===e.end?`line ${e.start} (${n})`:`lines ${e.start}-${e.end} (${n})`},wa=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${Py(e)}`});var Dy,ho,Fy,Oy,By,_y,Qu,Ma,Zu,Ju,em,ka=y(()=>{"use strict";Xu();Dy=(e,t)=>{let n=Math.max(1,Math.floor(t)),r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[""];let o=[],s="";for(let d of r){let l=d;for(;l.length>n;)s&&(o.push(s),s=""),o.push(l.slice(0,n)),l=l.slice(n);s?s.length+1+l.length<=n?s=`${s} ${l}`:(o.push(s),s=l):s=l}return s&&o.push(s),o},ho=e=>{let t=e.split("`");return t.length%2===0?[{text:e}]:t.map((n,r)=>r%2===1?{text:n,code:!0}:{text:n}).filter(n=>n.text.length>0)},Fy=/!\[([^\]]*)\]\([^)]*\)/g,Oy=e=>e.replace(Fy,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),By=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),_y=4,Qu=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(_y)),Ma=e=>{let t=!1;return e.map(Qu).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=Ta(n);if(r)return{kind:"caption",text:wa(r)};let o=Oy(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:ho(s[1]??"")}:{kind:"text",spans:ho(o)}})},Zu=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Ju=(e,t)=>{let n=[];for(let r of Ma(e))if(r.kind!=="fence"){if(r.kind==="blank"){n.length>0&&n[n.length-1]?.kind!=="blank"&&n.push(r);continue}if(r.kind==="code"){for(let o of Zu(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of Dy(By(r.spans),t))n.push({kind:r.kind,spans:ho(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},em=(e,t)=>{let n=Ta(e),r=n?zu(e):null;if(!n||r===null)return Ju(Aa(e).split(`
|
|
58
|
-
`),t);let
|
|
59
|
-
`).map(
|
|
60
|
-
`),t),{kind:"blank"}]:[],{kind:"caption",text:wa(n)},...s.flatMap((u,m)=>Zu(u,Math.max(1,t-l)).map((p,g)=>({kind:"code",text:p,number:d===void 0||g>0?void 0:d+m})))]}});import{Box as tm,Text as Gn}from"ink";import it from"react";var nm,La,rm,Pa=y(()=>{"use strict";Pe();nm=({spans:e,bold:t,wrap:n})=>it.createElement(Gn,{color:S.primary,bold:t,wrap:n},e.map((r,o)=>r.code?it.createElement(Gn,{key:o,color:S.yellow},r.text):it.createElement(Gn,{key:o},r.text))),La=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return it.createElement(Gn,null," ");case"fence":return it.createElement(Gn,{color:S.secondary2},"```");case"caption":return it.createElement(Gn,{color:S.accent,wrap:r},e.text);case"heading":return it.createElement(nm,{spans:e.spans,bold:!0,wrap:r});case"text":return it.createElement(nm,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return it.createElement(Gn,{backgroundColor:S.secondary,color:S.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},rm=({lines:e,width:t})=>{let n=e.flatMap(o=>o.kind==="code"&&o.number!==void 0?[o.number]:[]),r=n.length>0?String(Math.max(...n)).length+3:0;return it.createElement(tm,{flexDirection:"column"},e.map((o,s)=>it.createElement(tm,{key:s},it.createElement(La,{line:o,width:t,gutter:r}))))}});import{Box as pn,Text as gn}from"ink";import Re,{useEffect as Uy,useMemo as om,useRef as $y}from"react";import{decodeTime as sm}from"ulid";function am({ticket:e,width:t,height:n}){let r=om(()=>Wy(e),[e]),o=$y([]);Uy(()=>(im(o.current),o.current=Gy(e,r),()=>{im(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Ve(),l=Math.max(1,n-4),u=Math.max(20,t-8),m=om(()=>r.map(g=>{let I=em(g.md,u);return I.length>0?I:[{kind:"blank"}]}),[r,u]),p=m.map(g=>g.length+jy);return r.length===0?Re.createElement(pn,{flexDirection:"column",width:t,height:n,padding:1},Re.createElement(gn,{color:S.primary},"No comments yet."),Re.createElement(pn,{paddingTop:1},Re.createElement(gn,{color:S.primary},"Use"),Re.createElement(gn,{color:S.accent}," :comment "),Re.createElement(gn,{color:S.primary},"to add the first one."))):Re.createElement(pn,{flexDirection:"column",width:t,height:n},Re.createElement(pn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:S.secondary,borderStyle:"single",paddingBottom:1},Re.createElement(gn,{color:S.secondary2},"Comments (",r.length,") ")),Re.createElement(mn,{height:l,itemHeights:p,selectedIndex:s},r.map((g,I)=>{let N=I===s;return Re.createElement(pn,{key:g.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:S.secondary,borderStyle:"single"},Re.createElement(pn,{flexDirection:"row",paddingBottom:1},Re.createElement(gn,{color:S.accent},N?"\u276F ":" "),Re.createElement(pn,{paddingLeft:1},Re.createElement(gn,{color:S.secondary2},`#${I+1} `),Re.createElement(pr,{id:g.authorId}),Re.createElement(gn,{color:S.secondary2}," "+vr(yt(g.id))))),Re.createElement(pn,{paddingLeft:3,paddingBottom:1},Re.createElement(rm,{lines:m[I]??[],width:u})))})))}var jy,Hy,Wy,im,Gy,dm=y(()=>{"use strict";Je();dt();_s();ge();C();me();k();Pe();dr();Ds();po();Ca();ka();Pa();jy=4,Hy=e=>Ce(e,"comments"),Wy=e=>x.getCommentsByIssue(e.id).sort((t,n)=>sm(t.id)-sm(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),im=e=>{for(let t of e)x.deleteNode(t.id)},Gy=(e,t)=>{let n=x.getNode(Hy(e.id));if(!n||!Ye(n))return[];let r=t.map((o,s)=>$u(o,s,n.id)).map(x.createNode).filter(ht).map(({value:o})=>o).filter(Tr);return t.length>0&&f().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),r}});import{Box as Us,Text as qy}from"ink";import Vt from"react";var cm,lm=y(()=>{"use strict";ge();me();tr();k();Pe();Ds();mr();Sa();cm=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Ve(),{title:o}=t,s=t.parentNodeId?x.getNode(t.parentNodeId):void 0,d=s&&P(s)?o===ie.ASSIGNEES?s.props.assignees??[]:o===ie.TAGS?(s.props.tags??[]).filter(l=>x.getTag(l)):[]:[];return Vt.createElement(Us,{alignItems:"center",paddingTop:1},Vt.createElement(Us,{minWidth:12},Vt.createElement(qe,{isSelected:n}),Vt.createElement(qy,{color:n?S.accent:S.secondary2},o,":")),Vt.createElement(Us,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((l,u)=>{let m=r.id===t.id&&u===e;return Vt.createElement(Us,{key:`${o}-${l}`,paddingRight:2,minHeight:1},Vt.createElement(qe,{isSelected:m}),o===ie.ASSIGNEES?Vt.createElement(pr,{isSelected:m,id:l}):o===ie.TAGS?Vt.createElement(Fs,{isSelected:m,id:l}):null)})))}});var Da,um,Fa,Oa=y(()=>{"use strict";Da=e=>Math.max(5,String(Math.max(e,1)).length+3),um=(e,t)=>Math.max(0,e-6-Da(t)),Fa=(e,t=0)=>Math.max(1,e-5-2*t)});import{Box as br,Text as Ba}from"ink";import at,{useEffect as Vy,useMemo as _a}from"react";var Ky,mm,Ua,pm,zy,$a,gm=y(()=>{"use strict";me();C();An();k();Pe();Jt();Oa();mr();po();Pa();ka();Zn();Ky="\u2029",mm=(e,t)=>`${e}::inline-line::${t}`,Ua=new Map,pm=e=>{let t=Ua.get(e)??[];Ua.delete(e);for(let n of t)x.deleteNode(n)},zy=(e,t)=>{pm(e);let n=[];t.forEach((r,o)=>{let s=tt(BigInt(o+1));if(!ht(s))return;let d=x.createNode(Ne.text({id:mm(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));ht(d)&&n.push(d.value.id)}),Ua.set(e,n)},$a=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:d,contextNode:l}=Ve(),u=_a(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=_a(()=>u.join("\0"),[u]);Vy(()=>(zy(e,u),()=>{pm(e)}),[e,m]);let p=Da(u.length),g=um(s,u.length),N=_a(()=>Ma(u).map(A=>{if(A.kind==="code"||A.kind==="caption")return{...A,text:ui(A.text,g)};if(A.kind==="text"||A.kind==="heading"){let w=A.spans.map(T=>T.code?`\`${T.text}\``:T.text).join("");return{...A,spans:ho(ui(w,g))}}return A}),[u,g]).map((A,w)=>{let T=l.id===e&&d===w;return at.createElement(br,{key:mm(e,w)},at.createElement(br,{flexShrink:0},at.createElement(Ba,{color:T?S.primary:S.secondary2,dimColor:!T},`${w+1} `.padStart(p,"\xA0"))),A.kind==="blank"?at.createElement(Ba,{backgroundColor:T?"gray":void 0},Ky):at.createElement(br,null,at.createElement(La,{line:A,width:A.kind==="code"?g:0,wrap:"truncate-end"})))});return at.createElement(br,{flexDirection:"column",paddingTop:1},at.createElement(br,null,at.createElement(qe,{isSelected:o}),at.createElement(Ba,{color:o?S.accent:S.secondary2},t)),at.createElement(br,{flexDirection:"row",borderStyle:"round",borderColor:S.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},at.createElement(mn,{scrollByOne:!0,height:r,selectedIndex:d,itemHeight:1},N)))}});import{Box as qn,Text as ja}from"ink";import we,{useMemo as vo}from"react";var Yy,Xy,Jy,Qy,fm,hm=y(()=>{"use strict";ge();me();k();Pe();Ca();dr();Gu();dm();mr();lm();gm();Oa();Yy=e=>Ce(e,"description"),Xy=e=>Ce(e,"comments"),Jy=e=>Ce(e,"history"),Qy=e=>Ce(e,"attachments"),fm=({ticket:e,height:t})=>{let n=vo(()=>Uu(e),[e]),{selectedIndex:r,contextNode:o}=Ve(),s=process.stdout.columns||120,d=vo(()=>Yy(e.id),[e.id]),l=vo(()=>Xy(e.id),[e.id]),u=vo(()=>Jy(e.id),[e.id]),m=vo(()=>Qy(e.id),[e.id]),p=x.getAttachmentsByIssue(e.id).length,g=o.id===e.id,I=o.id===l||o.parentNodeId===l,N=o.id===u||o.parentNodeId===u,A=o.id===m||o.parentNodeId===m,w=ae(e.id);if(I){let H=t-3;return we.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},we.createElement(am,{ticket:e,width:s,height:H}))}if(A){let H=t-3;return we.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},we.createElement(Wu,{ticket:e,width:s,height:H}))}if(N){let O=x.getNode(u),H=O&&Ye(O)?O.props.value??"":"",Q=Fa(t);return we.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},O?we.createElement($a,{id:O.id,label:"Event log",text:H,selected:!1,maxWidth:s,rows:Q}):null)}let T=w.reduce((O,H)=>Ar(H)||H.id===l||H.id===m||H.id===u?O+1:O,0),M=Fa(t,T),$=(O,H)=>O.id===d?we.createElement($a,{key:O.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:H,maxWidth:s,rows:M}):Ar(O)?we.createElement(cm,{key:O.id,parent:O,selected:H,selectedIndex:r}):O.id===l?we.createElement(qn,{key:O.id,paddingTop:1},we.createElement(qe,{isSelected:H}),we.createElement(ja,{backgroundColor:S.secondary,color:H?S.accent:S.primary},` Comments (${n}) \u203A\u203A `)):O.id===m?we.createElement(qn,{key:O.id,paddingTop:1},we.createElement(qe,{isSelected:H}),we.createElement(ja,{backgroundColor:S.secondary,color:H?S.accent:S.primary},` Attachments (${p}) \u203A\u203A `)):O.id===u?we.createElement(qn,{key:O.id,paddingTop:1},we.createElement(qe,{isSelected:H}),we.createElement(ja,{backgroundColor:S.secondary,color:H?S.accent:S.primary}," History \u203A\u203A ")):null;return we.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},w.map((O,H)=>$(O,g&&r===H)))}});import{Box as Zy}from"ink";import $s from"react";var eb,vm,ym=y(()=>{"use strict";ge();_u();hm();eb=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:d,width:l})=>{let u=t.context,m=u===_.TICKET||u===_.FIELD_LIST||u===_.FIELD,p=u===_.BOARD||u===_.SWIMLANE,g=u===_.TICKET?t:r.find(T=>T.context===_.TICKET),I=Math.floor(l/3),N=Math.floor(l/Math.max(e.length,1)),A=Math.min(N,I),w=s==="dense";return $s.createElement(Zy,{flexDirection:"row",height:d},p&&e.map((T,M)=>{let $=t.id===T.id,O=$?n:-1,H=t.context===_.BOARD&&n===M;return $s.createElement(Bu,{key:T.id,height:d,width:A,swimlane:T,isSelected:H,isDense:w,isFocused:$,listSelectedIndex:O,mode:o})}),m&&g&&$s.createElement(fm,{height:d,ticket:g}))},vm=$s.memo(eb)});import bm from"node:fs";import tb from"node:path";import nb from"react";import{render as rb}from"ink";import{Writable as ob}from"node:stream";var yo,sb,ib,ab,db,xm,Im=y(()=>{"use strict";ym();ge();C();k();re();Be();yo=e=>String(e).padStart(2,"0"),sb=e=>{let t=e.getUTCFullYear(),n=yo(e.getUTCMonth()+1),r=yo(e.getUTCDate()),o=yo(e.getUTCHours()),s=yo(e.getUTCMinutes()),d=yo(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${d}`},ib=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",ab=async(e,{width:t,height:n})=>{let r="",o=new ob({write(d,l,u){let m=db(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=rb(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),r},db=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),xm=async()=>{let{viewMode:e}=ve(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=f(),d=r.find(M=>M.context==="BOARD");if(!d)return i("No board found to export");let l=120,u=40,m=await ab(nb.createElement(vm,{height:u,width:l,swimlanes:(s[d.id]??[]).filter(M=>M!==void 0&&bn(M)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:u});if(!m)return i("Failed to render board export");let p=Vo(process.cwd());if(a(p))return i("Unable to export, epiq root not found");let g=new Date,I=sb(g),N=`board_${ib(d.title)}_${I}.md`,A=nc(p.value);bm.mkdirSync(A,{recursive:!0});let w=tb.join(A,N),T=`# Board - ${d.title}
|
|
61
|
-
Date: ${
|
|
31
|
+
`,"utf8"),o.push(`${r} (${m.length})`)}catch{continue}}return o},Dv=(e,t)=>{let n=new Set(go(t));return go(e).filter(o=>!n.has(o))},Fv=(e,t,n)=>[`Refusing to commit ${e}: it is missing ${t.length} of the ${n} event(s) already committed.`,"","The event log is append-only, so a line can never legitimately go","missing. The working copy on disk is damaged; committing it would","publish that damage to everyone who pulls, and the log carries no way","to undo it.","","Nothing has been committed. The committed history is intact \u2014 recover","the file from it before syncing again:",` git show HEAD:${e}`,"","First dropped event:",` ${t[0]?.slice(0,200)??"<none>"}`].join(`
|
|
32
|
+
`),nu=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let o=await He({args:["show",`HEAD:${t}`],cwd:e});if(o.exitCode!==0)return l("No committed log to compare against",void 0);let r=Dv(o.stdout,n);return r.length>0?i(Fv(t,r,go(o.stdout).length)):l("Event log only grew",void 0)}});import tn from"node:fs";import vr from"node:path";var _v,ru,ou,Bv,ma,pa,Ov,Uv,Kn,$v,jv,ws,su,iu,au,yr,du,br=h(()=>{"use strict";R();ht();as();co();ua();We();Nt();_v="[epiq:init-repo]",ru=async e=>{let t=await He({args:["rev-parse","--verify","--quiet","HEAD"],cwd:e});if(t.exitCode===0)return l("Initial commit already exists",!1);if(!(t.exitCode===1&&t.stdout.trim()===""&&t.stderr.trim()===""))return i(["Could not determine whether the repository has any commits, so nothing was written.",`git rev-parse exited ${t.exitCode}`,t.stderr.trim()].filter(Boolean).join(`
|
|
33
|
+
`));X.info("Creating initial commit");let o=await q({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(a(o))return i(o.message);let r=await q({args:["commit-tree",o.value.stdout.trim(),"-m",_v],cwd:e});if(a(r))return i(r.message);let s=await q({args:["update-ref","HEAD",r.value.stdout.trim()],cwd:e});return a(s)?i(s.message):l("Created initial commit",!0)},ou=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Bv=async e=>{let t=await ls(e);if(a(t))return i(t.message);let n=await Hc(e);return a(n)?i(n.message):l("Built sync commit message",`[sync|branch:${ou(t.value)}:sha:${ou(n.value)}]`)},ma=async({repoRoot:e,stateBranchName:t})=>{X.info(`Creating ${t}`);let n=await q({args:["commit-tree",Yc,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return i(`Failed to create state branch commit
|
|
34
|
+
${n.message}`);let o=n.value.stdout.trim(),r=await q({args:["update-ref",`refs/heads/${t}`,o],cwd:e});return a(r)?i(`Failed to create ${t}
|
|
35
|
+
${r.message}`):l("Created state branch",!0)},pa=async({repoRoot:e,stateBranchName:t})=>{let n=await cs({repoRoot:e,branch:t});if(a(n))return i(`Ensure local state branch failed
|
|
36
|
+
`+n.message);if(n.value)return l("Local state branch already exists",!1);let o=await _n({repoRoot:e});if(a(o))return i(`Ensure local state branch failed
|
|
37
|
+
`+o.message);let r=o.value,s=r?await Bi({repoRoot:e,branch:t}):l("No remote, no remote state branch",!1);if(a(s))return i(`Ensure local state branch failed
|
|
38
|
+
`+s.message);let d=s.value;if(r&&d){let c=await ye.fetch({cwd:e,remote:gt,branch:t});if(a(c))return i(`Failed to fetch ${t} from remote
|
|
39
|
+
${c.message}`)}if(d){let c=await q({args:["branch","--track",t,`${gt}/${t}`],cwd:e});return a(c)?i(`Failed to create local ${t} from remote
|
|
40
|
+
${c.message}`):l("Created local state branch from remote",!0)}return ma({repoRoot:e,stateBranchName:t})},Ov=async({repoRoot:e,branch:t})=>{let n=await q({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let o=n.value.stdout.split(`
|
|
41
|
+
`),r=null;for(let s of o){if(s.startsWith("worktree ")){r=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&r)return l("Found worktree for branch",r)}return l("No worktree found for branch",null)},Uv=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=sr(vr.dirname(t));if(a(o))return i(`Failed to create state branch worktree
|
|
42
|
+
`+o.message);if(tn.existsSync(t)&&!tn.existsSync(vr.join(t,".git"))){let s=Ql(t);if(a(s))return i(s.message);if(s.value.length>0)return i([`Refusing to delete ${t}.`,"","It is not a usable worktree \u2014 it has no .git \u2014 but it still holds",`${s.value.length} event log(s) with content:`,...s.value.map(d=>` ${d}`),"","Deleting it would destroy them, and with no .git here there is no","committed copy to recover from. Move the directory aside and","salvage the logs before letting epiq recreate the worktree."].join(`
|
|
43
|
+
`));X.info("Removing broken state branch worktree path"),Zc(t)}X.info("Creating state branch worktree");let r=await ye.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(r)?i(`Failed to create state branch worktree
|
|
44
|
+
${r.message}`):l("Created state branch worktree",!0)},Kn=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=await Ov({repoRoot:e,branch:n});if(a(o))return i(o.message);let r=nr(t),s=o.value?nr(o.value):null;if(s&&s===r&&tn.existsSync(s))return l("State branch already checked out in expected worktree",!1);if(s&&s!==r){let u=await Gc(s);if(a(u))return i(u.message);if(u.value)return i([`Refusing to move the state branch worktree away from ${s}.`,"","It holds changes that are not committed yet, which for this","branch means events no sync has published. Removing it would","destroy them outright \u2014 there is no stash or reflog to recover","a deleted worktree from.","",`This worktree is expected at ${r}, so something else is`,"using a different EPIQ_GLOBAL_DIR against the same repository.","Sync from that location first, or point both at the same one."].join(`
|
|
45
|
+
`));X.info("Moving state branch worktree to expected location");let m=await ye.worktreeRemove({cwd:e,worktreeRoot:s});if(a(m))return i(`Failed to remove existing state branch worktree
|
|
46
|
+
${m.message}`)}if(s&&!tn.existsSync(s)){X.info("Pruning stale state branch worktree");let u=await ye.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
|
|
47
|
+
${u.message}`)}let d=await jc({repoRoot:e,worktreeRoot:t});if(a(d))return i(d.message);let c=tn.existsSync(t);if(d.value&&c)return l("State branch worktree already exists",!1);if(d.value&&!c){X.info("Pruning missing registered state branch worktree");let u=await ye.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
|
|
48
|
+
${u.message}`)}return Uv({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},$v=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await ls(e);if(a(n))return i(n.message);if(n.value===t)return l("State branch already checked out",!1);(await He({cwd:e,args:["rebase","--abort"]})).exitCode===0&&X.info("Aborted stale state branch rebase");let r=await ye.checkout({cwd:e,branch:t});return a(r)?i(`Failed to checkout ${t}
|
|
49
|
+
${r.message}`):l("Checked out state branch",!0)},jv=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Oi(t);if(a(n))return i(n.message);if(n.value)return l("State branch upstream already configured",!1);let o=await _n({repoRoot:t});if(a(o))return i(o.message);if(!o.value)return l("No remote available for state branch upstream",!1);let r=kt(e);if(a(r))return r;let s=r.value,d=await Bi({repoRoot:t,branch:s});if(a(d))return i(d.message);if(!d.value)return l("Remote state branch missing; upstream will be configured on first push",!1);X.info(`Configuring ${s} upstream`);let c=await ye.fetch({cwd:t,remote:gt,branch:s});if(a(c))return i(`Failed to fetch ${s}
|
|
50
|
+
${c.message}`);let u=await ye.setUpstream({cwd:t,branch:s,upstream:`${gt}/${s}`});return a(u)?i(`Failed to set state branch upstream
|
|
51
|
+
${u.message}`):l("Configured state branch upstream",!0)},ws=async({stateBranchRoot:e,eventFileName:t})=>{let n=Xc(t),o=vr.join(e,n);if(!tn.existsSync(o))return l("No event file to stage",null);let r=await nu({stateBranchRoot:e,relativePath:n,workingContent:tn.readFileSync(o,"utf8")});if(a(r))return i(r.message);let s=await ye.stage({cwd:e,pathspec:[n]});return a(s)?i(`Failed to stage state branch event file
|
|
52
|
+
${s.message}`):l("Staged state branch event file",n)},su=async({stateBranchRoot:e})=>{let t=Jc(),n=vr.join(e,t);if(!tn.existsSync(n))return l("No media directory to stage",null);let o=await ye.stage({cwd:e,pathspec:[t],ignoreRemoval:!0});return a(o)?i(`Failed to stage state branch media files
|
|
53
|
+
${o.message}`):l("Staged state branch media files",t)},iu=async({stateBranchRoot:e})=>{let t=$i();if(!tn.existsSync(vr.join(e,t)))return l("No event log attributes to stage",null);let n=await ye.stage({cwd:e,pathspec:[t]});return a(n)?i(`Failed to stage event log attributes
|
|
54
|
+
${n.message}`):l("Staged event log attributes",t)},au=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let o=await Bv(e);return a(o)?i(`Create state branch sync commit failed
|
|
55
|
+
`+o.message):lo({cwd:t,message:o.value,pathspec:n})},yr=async({repoRoot:e,stateBranchRoot:t})=>{let n=await Oi(t);if(a(n))return i(n.message);let o=kt(e);if(a(o))return o;let r=o.value,s=n.value?await ye.push({cwd:t}):await ye.push({cwd:t,remote:gt,branch:r,setUpstream:!0});if(a(s))return i(`Failed during state branch push
|
|
56
|
+
${s.message}`);let d=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return l(d?"Pushed state branch":"Remote already up to date",d)},du=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let o=!1,r=kt(e);if(a(r))return r;let s=r.value,d=[ms(),await pa({repoRoot:e,stateBranchName:s}),await Kn({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await $v({stateBranchRoot:t,stateBranchName:s}),await tl(t),n?await jv({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of d){if(a(c))return i(c.message);o=o||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",o)}});import Ts from"node:fs";import fa from"node:os";import Hv from"node:path";var Wv,cu,qv,Gv,zv,uu,ga,lu,Vv,Ms,ha=h(()=>{"use strict";R();Nt();ht();Wv="epiq-sync.lock",cu=600*1e3,qv=e=>{try{let t=JSON.parse(e);return typeof t.pid!="number"||typeof t.hostname!="string"||typeof t.startedAt!="number"||typeof t.operation!="string"?null:t}catch{return null}},Gv=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},zv=e=>e&&(e.hostname!==fa.hostname()||Gv(e.pid))?Date.now()-e.startedAt>cu:!0,uu=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,ga=e=>{try{return qv(Ts.readFileSync(e,"utf8"))}catch{return null}},lu=(e,t)=>{let n={pid:process.pid,hostname:fa.hostname(),startedAt:Date.now(),operation:t};try{return Ts.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},Vv=async({worktreeRoot:e,operation:t})=>{let n=await _i(e);if(a(n))return i(n.message);let o=Hv.join(n.value,Wv),r=()=>{try{let c=ga(o);c&&c.pid===process.pid&&Ts.rmSync(o)}catch{}};if(lu(o,t))return l("Acquired sync lock",{acquired:!0,release:r});let s=ga(o);if(!zv(s))return l("Sync lock is held",{acquired:!1,heldBy:s});X.info(`Breaking an abandoned sync lock: ${s?uu(s):"unreadable lock file"}`);try{Ts.rmSync(o,{force:!0})}catch{}if(lu(o,t))return l("Acquired sync lock after breaking a stale one",{acquired:!0,release:r});let d=ga(o);return l("Sync lock taken by another process",{acquired:!1,heldBy:d??{pid:-1,hostname:fa.hostname(),startedAt:Date.now(),operation:"unknown"}})},Ms=async({worktreeRoot:e,operation:t,fn:n})=>{let o=await Vv({worktreeRoot:e,operation:t});if(a(o))return i(o.message);if(!o.value.acquired)return X.info(`Skipping ${t}: the state worktree is held by ${uu(o.value.heldBy)}`),l("State worktree is held by another process",null);let{release:r}=o.value;try{return l("Ran under the sync lock",await n())}finally{r()}}});import Kv from"node:fs";var Yv,Xv,va,mu,ya,ks,Ps=h(()=>{"use strict";R();fr();Cs();co();We();Nt();br();ua();ha();Yv=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=re("getRepoRootDir",await rt(e));if(a(n))return i(n.message);let o=n.value;logger.debug("[sync] repo root",o);let r=re("getStateBranchRoot",ve({repoRoot:o}));if(a(r))return i(r.message);let s=r.value;logger.debug("[sync] state branch root",s),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:s,ensureUpstream:t});let d=re("bootstrapStateBranchStorage",await du({repoRoot:o,stateBranchRoot:s,ensureUpstream:t}));if(a(d))return i(d.message);logger.debug("[sync] bootstrap result",{bootstrapped:d.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let c=re("hasInProgressGitOperation(stateBranchRoot)",await ds(s));if(a(c))return i(c.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:c.value}),c.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 u=re("ensureStateBranchLayout",el(o,s));return a(u)?i(u.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:s,bootstrapped:d.value}),l("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:s,bootstrapped:d.value}))},Xv=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=re("stageStateBranchOwnEventFile",await ws({stateBranchRoot:t,eventFileName:n}));if(a(o))return i(o.message);let r=re("stageStateBranchMediaFiles",await su({stateBranchRoot:t}));if(a(r))return i(r.message);let s=re("stageStateBranchEventAttributes",await iu({stateBranchRoot:t}));if(a(s))return i(s.message);let d=[o.value,r.value,s.value].filter(m=>m!==null);if(d.length===0)return l("Nothing to stage",{createdCommit:!1});let c=re("hasStagedChanges(after stage)",await zc(t,d));if(a(c))return i(c.message);if(logger.debug("[sync] state branch change check after stage result",{changed:c.value}),!c.value)return logger.info("[sync] no own event file changes to commit"),l("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let u=re("createStateBranchSyncCommit",await au({repoRoot:e,stateBranchRoot:t,pathspec:d}));return a(u)?i(u.message):(logger.debug("[sync] created sync commit",u.value),l("Committed own event file",{createdCommit:!0,commitSha:u.value}))},va=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return As(n),l(n,{...e,pulled:!1,pushed:!1,offline:!0})},mu=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");mo();let n=re("ensureSyncReady",await Yv({cwd:e,ensureUpstream:!0}));if(a(n))return Ee(n.message);let{repoRoot:o,stateBranchRoot:r,bootstrapped:s}=n.value,d=re("isDetachedHead(stateBranchRoot)",await Vc(r));if(a(d))return Ee(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return Ee("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,f=re("getStateBranch",kt(o));if(a(f))return Ee(f.message);let x=f.value;logger.debug("[sync] resolved state branch",{stateBranch:x,stateBranchRoot:r});let S=re("commitOwnEventFileToStateBranch",await Xv({repoRoot:o,stateBranchRoot:r,ownEventFileName:t}));if(a(S))return Ee(S.message);c=S.value.createdCommit,u=S.value.commitSha;let A=re("hasRemote",await _n({repoRoot:r}));if(a(A))return Ee(A.message);if(!A.value)return va({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s},"no remote");let P=re("pullBranchRebaseIfPresent",await rr({cwd:r,branch:x}));if(a(P))return or(P.message)?va({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s}):Ee(P.message);m=P.value;let T=re("isAheadOfUpstream",await qc(r));if(a(T))return Ee(T.message);if(c||s||T.value){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:r});let w=re("pushStateBranch",await yr({stateBranchRoot:r,repoRoot:o}));if(a(w)&&Wc(w.message)){let _=re("pullBranchRebaseIfPresent(retry)",await rr({cwd:r,branch:x}));if(a(_))return Ee(_.message);m=m||_.value,w=re("pushStateBranch(retry)",await yr({stateBranchRoot:r,repoRoot:o}))}if(a(w))return or(w.message)?va({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s}):Ee(w.message);p=w.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:r});let w=re("git rev-parse HEAD",await q({args:["rev-parse","HEAD"],cwd:r}));if(a(w))return Ee(w.message);u=w.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return Vn(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),l("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:s,offline:!1})},ya=async(e,t)=>{let n=eu(e);try{return await t()}finally{let o=tu(e,n);o.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${o.join(", ")}`)}},ks=async e=>{let t=e.cwd??process.cwd(),n=await rt(t);if(a(n))return Ee(n.message);let o=ve({repoRoot:n.value});if(a(o))return Ee(o.message);let r=o.value;if(!Kv.existsSync(r))return mu(e);let s=await Ms({worktreeRoot:r,operation:"sync",fn:()=>ya(r,()=>mu(e))});return a(s)?Ee(s.message):s.value===null?l("Another process is syncing this board",{repoRoot:n.value,stateBranchRoot:r,createdCommit:!1,pulled:!1,pushed:!1,bootstrapped:!1,offline:!1,skipped:!0}):s.value}});var Ot,Ls,Jv,ba,pu,Ds=h(()=>{"use strict";Vl();zn();bt();Se();me();R();M();fr();Cs();Ps();Ot=null,Ls=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Ot,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),Ot)return logger.debug("[sync] syncAndReloadState joining existing promise"),Ot;logger.debug("[sync] syncAndReloadState creating promise"),Ot=Jv();try{let e=await Ot;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}),Ot||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),Ot=null}},Jv=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=pu();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(Ot)return Ot;logger.debug("[sync] syncAndReloadState:start");let t=re("resolveActorId",ne());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=qn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let o=re("syncEpiqWithRemote",await ks({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}),Ee(`Unable to sync state. ${o.message}`);let{stateBranchRoot:r,offline:s}=o.value,d=ba(r);return a(d)?d:(E({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:g().syncStatus}),l("Synced",!0))},ba=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=re("loadMergedEvents",yt(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(t),message:(a(t),t.message),count:a(t)?void 0:t.value.events.length}),a(t))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. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=pu();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:n.message,syncStatus:g().syncStatus}),n;let o=ql(),r=g().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:o,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:t.value.events.length});let d=re("bootStateFromEventLog",_t(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(d),message:(a(d),d.message)}),a(d))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. ${d.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:r}),logger.debug("[sync] restoreNavigationAnchor:start");let s=re("restoreNavigationAnchor",zl(o));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(s),message:a(s)?s.message:"Navigation restored",selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id}),a(s)?(E({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:g().syncStatus}),s):l("Reloaded state from event log",null)},pu=()=>g().mode===y.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 fo,gu,fu,Ia,xa,Ir,Ea,Qv,hu,Zv,vu,Fs=h(()=>{"use strict";R();Be();M();Ds();fo=3e3,gu=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<fo?null:t},fu=0,xa=!1,Ir=!1,Ea=()=>{if(xa)return!0;let e=$e();return a(e)?!1:e.value.syncStatus.status==="syncing"},Qv=()=>{let e=Ie().autoSyncIntervalMs??1e4,t=Date.now()-fu;return Math.max(0,e-t)},hu=()=>{Ia||(Ia=setTimeout(async()=>{if(Ia=void 0,!!vt()){if(Ea()){Ir=!0;return}Ir=!1,await Zv()}},Qv()))},Zv=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return i("Cannot auto-sync while peeking");if(!vt())return i("Cannot auto-sync before state is initialized");if(Ea())return Ir=!0,i("Sync already in progress");xa=!0,fu=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Ls()}finally{xa=!1,Ir&&hu()}},vu=()=>{vt()&&(Ir=!0,!Ea()&&hu())}});import xr from"node:fs";import Er from"node:path";import{z as ho}from"zod";var _s,ey,ty,ny,bu,Iu,yu,xu,Eu,Ru,oy,Bs,Rr,vo=h(()=>{"use strict";R();Yt();is();ae();_s="recent-projects.json",ey=20,ty=ho.object({projectId:ho.string().min(1),root:ho.string().min(1),lastOpenedAt:ho.number().finite()}),ny=ho.object({projects:ho.array(ty)}),bu=()=>Er.join(Xt(),_s),Iu=e=>Er.basename(e)||e,yu=e=>{let t=Er.resolve(e);try{return xr.realpathSync(t)}catch{return t}},xu=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Eu=e=>{if(!ar(e.root))return!1;let t=tr(e.root);return!a(t)&&t.value===e.projectId},Ru=()=>{let e=bu();if(!xr.existsSync(e))return l("No recent projects recorded",[]);let t;try{t=JSON.parse(xr.readFileSync(e,"utf8"))}catch(o){return i(`Invalid ${_s}: ${o instanceof Error?o.message:String(o)}`)}let n=ny.safeParse(t);return n.success?l("Read recent projects",n.data.projects):i(`Invalid ${_s} shape: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},oy=e=>{let t=bu();try{xr.mkdirSync(Er.dirname(t),{recursive:!0}),xr.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
57
|
+
`,"utf8")}catch(n){return i(`Unable to write ${_s}: ${n instanceof Error?n.message:String(n)}`)}return l("Recorded recent project",e)},Bs=({exclude:e}={})=>{let t=Ru();if(a(t))return t;let n=e===void 0?null:yu(e);return l("Listed recent projects",t.value.filter(o=>n===null||yu(o.root)!==n).filter(Eu).sort(xu))},Rr=({root:e,now:t=Date.now()})=>{let n=Er.resolve(e),o=tr(n);if(a(o))return i(o.message);let r=o.value,s=Ru(),d=a(s)?[]:s.value,c=[{projectId:r,root:n,lastOpenedAt:t},...d.filter(u=>u.projectId!==r&&u.root!==n)].filter(Eu).sort(xu).slice(0,ey);return oy(c)}});var Os,Su,Nu,Au,Sr=h(()=>{"use strict";R();Yt();Be();ae();Os=()=>{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}},Su=()=>{let e=Ue(process.cwd());if(a(e))return!1;let t=Kt(e.value);return wt(t)},Nu=e=>e===!0?"on":e===!1?"off":null,Au=e=>e==="on"?!0:e==="off"?!1:null});var Fe,C,je=h(()=>{"use strict";Fe={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:Fe.cyan,accent2:Fe.magenta,primary:Fe.white,secondary:Fe.grayDark,secondary2:Fe.grayLight,gray:Fe.gray,green:Fe.green,yellow:Fe.yellow,red:Fe.red}});var N,yo,Us=h(()=>{"use strict";je();N={red:Fe.red,yellow:Fe.yellow,green:Fe.green,blue:Fe.blue,magenta:Fe.magenta,cyan:Fe.cyan},yo={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}});var ry,sy,In,xn,$s,js,Nr=h(()=>{"use strict";V();R();te();M();ry=e=>e.props.tags??[],sy=e=>e.props.assignees??[],In=e=>ry(e).map(t=>I.getTag(t)).filter(t=>!!t),xn=e=>sy(e).map(t=>I.getContributor(t)).filter(t=>!!t),$s=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!k(n)?i("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",In(n))},js=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!k(n)?i("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",xn(n))}});var b,Yn=h(()=>{"use strict";b={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",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",NONE:""}});var iy,ay,dy,cy,ly,Xn,Cu,Hs,Ws,wu,uy,Ra,Ar=h(()=>{"use strict";iy=/^(\d+)(h|d|w|mo|y)$/,ay=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,dy=({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},cy=(e,t=new Date)=>{let n=e.match(iy);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}},ly=e=>{let t=e.match(ay);if(!t)return null;let[,n,o,r,s,d]=t,c=Number(n),u=Number(o),m=Number(r),p=s?Number(s):0,f=d?Number(d):0;return dy({year:c,month:u,day:m,hour:p,minute:f})?new Date(c,u-1,m,p,f):null},Xn=e=>{let t=e.trim().toLowerCase();return cy(t)??ly(t)},Cu=/^(\d+)(s|m)?$/,Hs=e=>{let t=e.trim().toLowerCase().match(Cu);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Ws=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),o=n.length>0&&Cu.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:o}},wu=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,uy=[{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}],Ra=(e=uy)=>{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 my,he,at,Ne,py,gy,Na,Aa,ku,Jn,qs,Sa,Tu,fy,hy,Cr,Mu,vy,yy,Ca,by,Ae,nn=h(()=>{"use strict";Fs();vo();R();Sr();Jt();V();te();M();Us();Nr();Yn();Ar();my=["BOARD","TICKET","SWIMLANE","COMMENT"],he={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},at={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Ne={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},py=[he.EDITOR,he.VIEW,he.USERNAME,he.AUTOSYNC,he.SYNC_DEBOUNCE_MS,he.ATTACHMENT_MAX_KB,he.LOG_LEVEL],gy=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[at.TITLE,at.DESCRIPTION];case"BOARD":case"SWIMLANE":return[at.TITLE];case"COMMENT":return[at.COMMENT];default:return[]}},Na=[String(fo),"5000","15000","30000","60000"],Aa=["250","500","1000"],ku=["10s","20s","30s","45s"],Jn=[b.EXIT,b.SYNC,b.HELP,b.EXPORT,b.CONFIG,b.YANK],qs=[b.NEW,b.EDIT,b.DELETE,b.MOVE],Sa=[b.TAG,b.UNTAG,b.ASSIGN,b.UNASSIGN,b.CLOSE_ISSUE,b.RE_OPEN_ISSUE,b.EDIT,b.COMMENT],Tu=[b.FILTER,b.PEEK,b.REPLAY],fy={WORKSPACE:[...Jn,...qs],BOARD:[...Tu,...Jn,...qs],SWIMLANE:[...Tu,...Jn,...qs],TICKET:[...Jn,...qs,...Sa],FIELD:[...Jn,...Sa],FIELD_LIST:[...Jn,...Sa],TEXT:[...Jn],COMMENT:[b.EDIT,b.DELETE,b.YANK]},hy=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Cr=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&k(n)),Mu=e=>e.parentNodeId===fe,vy=({selectedNode:e,breadCrumb:t})=>{let n=gy(e?.context);return Cr({breadCrumb:t,selectedNode:e})?n.includes(at.DESCRIPTION)?n:[...n,at.DESCRIPTION]:n},yy=({selectedNode:e,breadCrumb:t})=>{let n=Cr({breadCrumb:t,selectedNode:e});return n?[Ne.REF,Ne.TITLE,...n.props?.description?.trim()?[Ne.DESCRIPTION]:[],...In(n).length>0?[Ne.TAGS]:[],...xn(n).length>0?[Ne.ASSIGNEES]:[]]:e?[Ne.REF,Ne.TITLE]:[]},Ca=()=>{let e=Bs({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},by=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:o}=Os();if(!o)return[b.HELP,b.CONFIG];if(!Su())return[b.HELP,b.INIT,b.OPEN];if(t)return[b.HELP,b.PEEK,b.REPLAY,b.EXPORT,b.CONFIG,b.YANK];let r=e?.context,s=r&&my.includes(r),d=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?fy[u]:[]))],c=Cr({breadCrumb:n,selectedNode:e});return d.filter(u=>u===b.MOVE?!1:u===b.YANK?!!(c??e):u===b.EDIT?s||!!c:u===b.DELETE?s:u===b.UNTAG?!!(c&&In(c).length>0):u===b.UNASSIGN?!!(c&&xn(c).length>0):u===b.RE_OPEN_ISSUE?!!(c&&Mu(c)):u===b.CLOSE_ISSUE?!!(c&&!Mu(c)):!0)},Ae=(e,{contextNode:t,selectedNode:n,readOnly:o,breadCrumb:r}=g())=>{let s=t.context??"WORKSPACE";return{[b.NONE]:by({breadCrumb:r,readOnly:o,selectedNode:n}),[b.EXIT]:["confirm"],[b.EXPORT]:[],[b.SYNC]:[],[b.INIT]:[],[b.OPEN]:e===b.OPEN?Ca():[],[b.HELP]:[],[b.PEEK]:[...Ra(),"now","prev","next"],[b.REPLAY]:[...Ra()],[b.EDIT]:vy({selectedNode:n,breadCrumb:r}),[b.YANK]:yy({selectedNode:n,breadCrumb:r}),[b.COMMENT]:[],[b.DELETE]:["confirm"],[b.RE_OPEN_ISSUE]:["confirm"],[b.CLOSE_ISSUE]:["confirm"],[b.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[b.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[b.TAG]:[...new Set([...Object.keys(yo),...I.getExistingTags()])],[b.UNTAG]:[...$s()?.value?.map(({name:c})=>c)??[]],[b.UNASSIGN]:[...js()?.value?.map(({name:c})=>c)??[]],[b.ASSIGN]:I.getExistingAssignees(),[b.NEW]:hy(s),[b.CONFIG]:[...py]}[e]??[]}});var Pu,Lu=h(()=>{"use strict";Pu=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{accessSync as Iy,copyFileSync as xy,existsSync as Gs,mkdirSync as Du,readdirSync as Fu,readFileSync as Ey,renameSync as Ry,rmSync as Sy,statSync as _u,unlinkSync as Ny,writeFileSync as Ay}from"node:fs";import bo from"node:path";var wa,ze,zs=h(()=>{"use strict";wa=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",ze={writeToFile:(e,t)=>{try{let n=bo.dirname(e);Gs(n)||Du(n,{recursive:!0});let o=typeof t=="string"?t:JSON.stringify(t,null,2);Ay(e,o,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Ey(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=ze.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 Gs(e)&&_u(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Iy(e),!0}catch{return!1}},mkDir:e=>Du(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=bo.parse(t);for(;;){let o=bo.join(t,e);try{if(Gs(o)&&_u(o).isDirectory())return o}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=bo.dirname(t)}return null},readFirstJSON(e){try{if(!ze.dirExists(e))return null;let t=Fu(e).filter(o=>o.endsWith(".json")).sort()[0];if(!t)return null;let n=bo.join(e,t);return ze.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return ze.dirExists(e)?Fu(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Ny(e)}catch(t){(!wa(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Sy(e,{recursive:!0,force:!0})}catch(t){(!wa(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(bo.dirname(t)),!n?.overwrite&&Gs(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Ry(e,t)}catch(o){if(wa(o)&&o.code==="EXDEV"){xy(e,t),this.rmFile(e);return}throw o}}}});import Cy from"node:path";import{z as on}from"zod";var wy,Bu,Ty,Ou,Ta,Ma,My,Io,Uu,Ve,wr,Ut=h(()=>{"use strict";Mn();ae();R();zs();wy={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},Bu=on.object({logLevel:on.enum(["info","error","debug"]),preferredEditor:on.string().optional(),userName:on.string().optional(),userId:on.string().optional(),autoSync:on.boolean().nullable().optional(),autoSyncDebounceMs:on.number().optional(),attachmentMaxKb:on.number().optional(),viewMode:on.enum(["dense","wide"]).optional()}).partial(),Ty="config.json",Ou=Xt,Ta=()=>Cy.join(Ou(),Ty),Ma=()=>{try{return ze.mkDir(Ou()),l(`Ensured ~/${St} exists`,null)}catch{return i(`Unable to create ~/${St}`)}},My=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${St}/config.json JSON`)}let n=Bu.safeParse(t??{});return n.success?l("Parsed config",n.data):i(`Invalid ~/${St}/config.json shape: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},Io=()=>{let e=Ma();if(a(e))return i(e.message);let t=Ta(),n=ze.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):My(n)},Uu=e=>{let t=Ma();if(a(t))return i(t.message);let n=Bu.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`);let o=Ta();try{return ze.writeToFile(o,JSON.stringify(n.data,null,2)+`
|
|
58
|
+
`),l("Config written",null)}catch{return i(`Unable to write ~/${St}/config.json`)}},Ve=e=>{let t=Io();if(a(t))return i("Failed to read existing config");let n={...t.value,...e};return Uu(n)},wr=()=>{let e=Ta(),t=Ma();if(a(t))return i(`Unable to create ~/${St}`);if(!(ze.readFile(e)!==null)){let A=Uu(wy);if(a(A))throw new Error(`Unable to create ~/${St}/config.json`)}let o=Io();if(a(o))throw new Error(o.message||"Unable to load settings");let{preferredEditor:r,userName:s,userId:d,autoSync:c,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:f}=o.value,x=wi({userId:d,userName:s});if(a(x))return i(x.message);let S=x.value??{userId:d,userName:s};return!S.userName||!S.userId?i(`User name or ID not configured in ~/${St}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,l("successfully loaded settings",{logLevel:p??"debug",preferredEditor:r??"",userName:S.userName,userId:S.userId,autoSync:c??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))}});var $u,ju,ka,Hu=h(()=>{"use strict";$u="/media/",ju=e=>`${$u}${e}`,ka=(e,t)=>`})`});import ky from"node:crypto";import Pa from"node:fs";import Py from"node:path";var rn,xo,Ly,Dy,Fy,Wu,Eo=h(()=>{"use strict";Tt();R();ae();Hu();rn=500,xo=(e,t)=>`${e}.${t}`,Ly=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?l("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?l("Sniffed image type","jpg"):e.length>=6&&(e.subarray(0,6).equals(Buffer.from("GIF87a","ascii"))||e.subarray(0,6).equals(Buffer.from("GIF89a","ascii")))?l("Sniffed image type","gif"):e.length>=12&&e.subarray(0,4).equals(Buffer.from("RIFF","ascii"))&&e.subarray(8,12).equals(Buffer.from("WEBP","ascii"))?l("Sniffed image type","webp"):i(`Unsupported image format. Allowed: ${Ec.join(", ")}`),Dy=e=>ky.createHash("sha256").update(e).digest("hex"),Fy=(e,t=rn)=>{if(e.length===0)return i("Attachment is empty");if(e.length>t*1024)return i(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=Ly(e);return a(n)?n:l("Validated attachment data",{hash:Dy(e),ext:n.value,bytes:e.length})},Wu=(e,t,n=rn)=>{let o=Fy(t,n);if(a(o))return o;let r=ps(e),s=Py.join(r,xo(o.value.hash,o.value.ext));try{Pa.existsSync(s)||(Pa.mkdirSync(r,{recursive:!0}),Pa.writeFileSync(s,t))}catch(d){return i(`Unable to write attachment blob: ${d instanceof Error?d.message:String(d)}`)}return l("Wrote attachment blob",o.value)}});import _y from"zod";var Tr,Mr,qu,La=h(()=>{"use strict";Ut();Eo();me();R();de();Be();M();Tr=50,Mr=5e3,qu=()=>{let e=ie().commandMeta.inputString,t=_y.coerce.number().int().min(Tr).max(Mr).safeParse(e);if(!t.success)return i(`Attachment size cap must be ${Tr}-${Mr} KB (default ${rn})`);let n=Ve({attachmentMaxKb:t.data});return a(n)?n:(ut({attachmentMaxKb:t.data}),E({mode:y.DEFAULT}),l(`Attachment size cap set to ${t.data} KB`,null))}});import Gu from"chalk";var Fa,zu,Da,Vu,By,Oy,Ku,Uy,$y,kr,Ce,Yu,Xu,Vs,jy,Hy,Ks,dt=h(()=>{"use strict";Us();Fa={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},zu=(e,t,n)=>Math.max(t,Math.min(n,e)),Da=(e,t,n)=>e+(t-e)*n,Vu=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},By=e=>e.toLowerCase().trim(),Oy=(e,t,n)=>{let o=t/100,r=n/100,s=(1-Math.abs(2*r-1))*o,d=e/60,c=s*(1-Math.abs(d%2-1)),u=0,m=0,p=0;d>=0&&d<1?(u=s,m=c):d>=1&&d<2?(u=c,m=s):d>=2&&d<3?(m=s,p=c):d>=3&&d<4?(m=c,p=s):d>=4&&d<5?(u=c,p=s):(u=s,p=c);let f=r-s/2;return[Math.round((u+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},Ku=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Uy=(e,t,n)=>{let o=zu(n,0,1);return[Math.round(Da(e[0],t[0],o)),Math.round(Da(e[1],t[1],o)),Math.round(Da(e[2],t[2],o))]},$y=(e,t,n)=>Uy(e,t,n),kr=e=>{let t=Vu(e)%360,n=Oy(t,Fa.stringColor.saturation,Fa.stringColor.lightness);return Ku(n)},Ce=(e,t=yo)=>{let n=By(e??"");return n&&t[n]?t[n]:kr(n)},Yu=e=>{let t=Fa.gradient.stops,n=zu(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 $y(t[s],t[s+1],d)},Xu=e=>Ku(Yu(e)),Vs=e=>Vu(e.toLowerCase().trim())/4294967295,jy=e=>{let t=Vs(e);return Yu(t)},Hy=e=>{let[t,n,o]=jy(e);return{normal:r=>Gu.bgRgb(t,n,o).black(r),cursor:r=>Gu.bgRgb(t,n,o).white.bold(r)}},Ks=e=>Hy(e).normal(` ${e} `)});var Ke,sn=h(()=>{"use strict";Ke=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null});import{createHash as Wy}from"node:crypto";var qy,Gy,Me,Ro=h(()=>{"use strict";qy="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Gy=e=>{let t=Wy("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+=qy[Number(n>>s&31n)]}return o},Me=(e,t)=>Gy(`${e}:virtual:${t}`)});import Ju from"chalk";var ce,ke,De,Qu=h(()=>{"use strict";dt();je();ce=e=>Ju.dim(e),ke=e=>Ju.hex(C.primary)(e),De=({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(f=>f.startsWith(d))].sort((f,x)=>Vs(f)-Vs(x)).slice(0,o).map(f=>Ks(f)).join(" ");return p?`${ce(e)}${p}${ce(n)}`:""}});var En,Ys=h(()=>{"use strict";En={None:"none",Invalid:"invalid",Valid:"valid"}});import tm from"chalk";var zy,Zu,ue,Z,W,No,em,Xs,_a,Vy,So,Ky,Yy,Xy,Jy,Qy,nm,om=h(()=>{"use strict";Fs();Sr();Lu();et();Tt();R();te();Be();La();Eo();M();dt();sn();Nr();Ro();Qu();Yn();Ys();nn();Ar();zy=["BOARD","TICKET","SWIMLANE"],Zu=()=>{let e=g().selectedNode;if(!e?.context)return W({message:ce("Missing target context")});if(zy.includes(e.context))return Z();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===Me(t?.parentNodeId??"","comments"))return Z()}return W({message:ce("Command not available in this context")})},ue="<ENTER> to confirm",Z=(e="",t=[])=>({message:ce(e),validity:En.Valid,completionWordList:t}),W=({message:e,completionWordList:t=[]})=>({validity:En.Invalid,message:e,completionWordList:t}),No=e=>e.length===0,em=(e,t)=>{let n=tt(g().breadCrumb,"BOARD");if(a(n))return W({message:ke("Command is not applicable in this context")});let o=xc(n.value.id);return a(o)?W({message:ke(`Unable to ${t}: board id is not a valid ULID`)}):wu({date:e,horizonDate:o.value})?null:W({message:ke(`nothing to ${t} before ${o.value.toISOString().slice(0,16).replace("T"," ")}`)})},Xs=e=>` ${tm.hex("#000").bgHex(Ce(e))(` ${e} `)} `,_a=({modifier:e})=>{let t="confirm";return e===t?Z(ue):W({message:No(e)?ce("if you are certain, enter ")+Ks(t):"",completionWordList:[t]})},Vy=({list:e,hint:t,onValue:n})=>({modifier:o,inputString:r})=>e.includes(o)?r.trim().length<1?W({message:ce(n)}):Z():W({message:No(o)?t:"",completionWordList:[...e]}),So=({hint:e,onOk:t})=>({modifier:n,inputString:o})=>No(n)&&No(o)?W({message:e,completionWordList:[]}):Z(t??ue),Ky=({modifier:e,inputString:t})=>{let n=Ca();return!No(e)||!No(t)?Z(ue):W({message:n.length?ce("number from the list, or a path"):ce("path to an epiq project"),completionWordList:n})},Yy=({modifier:e,inputString:t})=>{let n=Ae(b.CONFIG);if(!n.includes(e))return W({message:De({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case he.EDITOR:{let o=[...Pu];return t.trim()?o.includes(t.trim())?Z(ue):W({message:De({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o}):W({message:De({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case he.VIEW:{let o=["dense","wide"];return o.includes(t.trim())?Z(ue):W({message:De({prefix:"view... ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case he.USERNAME:return t.trim()?Z(ue):W({message:ke("Enter a user name. Saved in ")+tm.bgBlack("~/.epiq-global/config.json")});case he.LOG_LEVEL:{let o=["debug","error","info"],r=t.trim();return o.includes(r)?Z(ue):W({message:De({prefix:"one of: ",wordList:[...o],inputString:r,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...o]})}case he.AUTOSYNC:{let o=["on","off"],r=Ie().autoSync;if(!o.includes(t.trim())){let s=Nu(r);return W({message:De({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:o,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:o})}return Z(ue)}case he.ATTACHMENT_MAX_KB:{let o=Ie().attachmentMaxKb,r=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(r)||r<Tr||r>Mr){let s=De({prefix:" examples: ",wordList:Aa,minLengthForHints:0,inputString:t});return W({message:ke(`provide a size cap in KB (${Tr}-${Mr}). current: ${o??rn} KB.`)+s,completionWordList:Aa})}return Z(ue)}case he.SYNC_DEBOUNCE_MS:{let o=Ie().autoSyncIntervalMs,r=gu(t);if(!t.trim()||r===null||r<fo){let s=De({prefix:" examples: ",wordList:Na,minLengthForHints:0,inputString:t});return W({message:ke(`provide duration above ${fo}ms. current duration: ${o}ms.`)+s,completionWordList:Na})}return Z(ue)}default:return W({message:ke("Unknown config option"),completionWordList:n})}},Xy=({modifier:e,inputString:t})=>{let n=Ae(b.EDIT);if(!n.length)return W({message:ke("Command not available in this context")});if(!n.includes(e)){let o=De({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return W({message:o||ke("Unknown edit option"),completionWordList:n})}switch(e){case at.COMMENT:return t.trim()?Z(ue):W({message:ce("write a comment...")});case at.TITLE:return Z(ue);case at.DESCRIPTION:{let{preferredEditor:o}=Ie();return o?Z(ce("<ENTER> to edit in ")+o):W({message:"No editor selected"})}default:return W({message:ke("Unknown edit option"),completionWordList:n})}},Jy=({modifier:e})=>{let t=Ae(b.YANK);return t.length?t.includes(e)?Z(ue+ce(" and copy to clipboard")):W({message:De({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):W({message:ke("Nothing selected to copy from")})},Qy={[b.EXPORT]:()=>Z(ue+ce(", and create export markdown file")),[b.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return Z(ue);let n={message:ce("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},o=t||e.inputString.trim(),r=Xn(o);if(!o||!r)return W(n);let s=em(r,"peek");return s||Z(ue)},[b.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Ws(e.modifier,e.inputString),o={message:ce("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},r=Xn(t);if(!t||!r)return W(o);let s=em(r,"replay");return s||(n&&Hs(n)===null?W({message:ke("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):Z("<ENTER> to replay board history",n?ku:[]))},[b.EXIT]:()=>Z(ue+ce(" and exit the application")),[b.INIT]:()=>Z(ue),[b.OPEN]:Ky,[b.PALETTE]:()=>Z(ue),[b.FILTER]:e=>{if(e.modifier==="clear")return Z(ue);let t=s=>Ae(b.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return W({message:De({wordList:Ae(b.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Ae(b.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())?W({message:De({prefix:`existing ${e.modifier}s... `,wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r}):Z():W({message:De({prefix:"one of... ",wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r})},[b.NONE]:e=>{let t=Ae(b.NONE);return W({message:De({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[b.NEW]:e=>Vy({list:Ae(b.NEW),hint:De({wordList:Ae(b.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[b.HELP]:()=>Z(ue),[b.EDIT]:Xy,[b.COMMENT]:e=>{let t=So({hint:ce(`write a comment (max ${4e3} char)...`),onOk:ce(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===En.Invalid?t:e.inputString.length>4e3?Z(ke("max input exceeded")):t},[b.CONFIG]:Yy,[b.YANK]:Jy,[b.DELETE]:e=>{let t=Zu();return t.validity==="invalid"?t:_a(e)},[b.CLOSE_ISSUE]:e=>_a(e),[b.RE_OPEN_ISSUE]:e=>_a(e),[b.MOVE]:e=>{let t=Zu();return t.validity==="invalid"?t:So({hint:De({prefix:"hey hacker! These commands are blocked for you... ",wordList:Ae(b.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[b.TAG]:e=>{let n=I.getExistingTags().slice(0,10).map(Xs).join("");return So({hint:n.length?ce("create tag or reuse:")+n+ce(""):ce("create tag ...")})(e)},[b.UNTAG]:e=>{let t=$s();if(a(t))return W({message:ke("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(Xs).slice(0,10);return n.length?So({hint:ce(" ... ")+n.join("")})(e):W({message:ke("Issue has no tags"),completionWordList:[]})},[b.ASSIGN]:e=>{let t=I.getExistingAssignees().map(Xs).slice(0,10);return So({hint:ce("assignees... ")+t.join("")})(e)},[b.UNASSIGN]:e=>{let t=js();if(a(t))return W({message:ke("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(Xs).slice(0,10);return n.length?So({hint:ce("remove assignee... ")+n.join("")})(e):W({message:ke("Issue has no assignees"),completionWordList:[]})},[b.SYNC]:()=>Z(ue)},nm=Object.fromEntries(Object.entries(Qy).map(([e,t])=>[e,{validate:(n,o,r)=>t({modifier:o,command:n,inputString:r})}]))});var Js,rm=h(()=>{"use strict";Js=["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 Zy,eb,tb,nb,ob,sm,im,am,dm=h(()=>{"use strict";R();M();rm();Zy=3,eb=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"]),tb=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},nb=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=Zy&&!eb.has(t)&&!/^\d+$/.test(t)),ob=e=>{let t=new Map;for(let s of tb(e))for(let d of nb(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=Js.filter(s=>!o.has(s));return[...n,...r]},sm=Js,im=-1,am=()=>{let e=$e();if(a(e))return Js;let t=e.value,n=t.eventLog.length;return n!==im&&(sm=ob(t),im=n),sm}});var cm,lm,Ba=h(()=>{"use strict";Lc();nn();Yn();om();dm();M();me();cm=e=>Object.values(b).includes(e),lm=(e,t)=>{let n=e.command??"",{modifier:o,target:r,inputString:s}=e,{message:d,validity:c,completionWordList:u}=nm[n].validate(n,o,s),m=n!==b.PEEK&&n!==b.REPLAY,p=r==="command"||r==="modifier"?Ae(n):m?am():[],{mode:f}=g(),x=f===y.COMMAND_LINE?d??"":"",S=[...u,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:x,autoCompletion:t?Pc(e,S):{hint:"",hints:[],remainder:"",overlap:0}}}});var um,rb,sb,ib,mm=h(()=>{"use strict";Ba();nn();um=e=>{let t=e.trimStart(),n=sb(t),o=n[0]??"",r=n[1]??"",s=/\s$/.test(e),d=ib(e),c=cm(o)?o:null,u=c!==null,m=o!=="",p=c?Ae(c)??[]:[],f=c&&p.includes(r)?r:"",x="word";n.length===0||n.length===1&&!s?x="command":(n.length===1&&s||n.length===2&&!s)&&(x="modifier");let S=s?"":d,A=rb(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:o,lastWord:d,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:x,inputToMatch:S,inputString:A}},rb=(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},sb=e=>e.trim()?e.trim().split(/\s+/):[],ib=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as AT}from"react";var Ao,Oa,Co,ab,pm,$t,Pr,Ua,$a,gm,fm,Qs,hm,ee,vm,ym,bm,ie,Zs,de=h(()=>{"use strict";Ba();mm();R();Ys();Ao=e=>e===Oa||e===":",Oa=" ",Co={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:En.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},ab=new Set,pm=()=>{for(let e of ab)e()},$t=e=>{let n=e(Co),o=um(n.value),r=n.cursorPosition===n.value.length;Co={...n,commandMeta:lm(o,r)},pm()},Pr=({message:e,status:t})=>{let n=structuredClone(Co);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Co=n,pm(),l(e,null)},Ua=e=>{$t(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},$a=e=>{$t(t=>{let{value:n,cursorPosition:o}=t,r=o;if(e==="left"){for(;r>0&&Ao(n[r-1]);)r--;for(;r>0&&!Ao(n[r-1]);)r--}else{for(;r<n.length&&!Ao(n[r]);)r++;for(;r<n.length&&Ao(n[r]);)r++}return{...t,cursorPosition:r}})},gm=()=>{$t(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}})},fm=()=>{$t(e=>{let{value:t,cursorPosition:n}=e,o=n;for(;o>0&&Ao(t[o-1]);)o--;for(;o>0&&!Ao(t[o-1]);)o--;let r=t.slice(n);return{...e,value:t.slice(0,o)+r,cursorPosition:o,commandIsPending:!1}})},Qs=e=>{$t(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,c=Math.max(0,Math.min(s.length,d.length));return{...t,value:d,cursorPosition:c,commandIsPending:!1}})},hm=()=>{$t(e=>({...e,commandIsPending:!0}))},ee=e=>{$t(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},vm=({addToHistory:e=!0})=>{$t(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},ym=()=>{$t(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}})},bm=()=>{$t(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ie=()=>Co,Zs=()=>{let[e,...t]=Co.value.split(Oa);return t.join(Oa).trim()}});var F,kn=h(()=>{"use strict";me();Sc();M();de();Be();F={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 Im,O,ja=h(()=>{"use strict";M();Yn();Im=e=>{let{context:t}=g().contextNode;if(!t)return O.None;switch(e){case b.EXIT:return O.Exit;case b.EXPORT:return O.Export;case b.INIT:return O.Init;case b.OPEN:return O.OpenProject;case b.DELETE:return O.Delete;case b.EDIT:return O.Edit;case b.COMMENT:return O.Comment;case b.HELP:return O.ViewHelp;case b.RE_OPEN_ISSUE:return O.ReopenIssue;case b.CLOSE_ISSUE:return O.CloseIssue;case b.TAG:return O.TagTicket;case b.UNTAG:return O.UntagTicket;case b.ASSIGN:return O.AssignUserToTicket;case b.UNASSIGN:return O.UnassignUserFromTicket;case b.NEW:return O.NewItem;case b.FILTER:return O.Filter;case b.MOVE:return O.Move;case b.PEEK:return O.Peek;case b.REPLAY:return O.Replay;case b.CONFIG:return O.Config;case b.YANK:return O.Yank;case b.SYNC:return O.Sync;default:return O.None}},O={Exit:"exit",Init:"init",OpenProject:"open-project",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"}});import{Text as xm}from"ink";import Em,{useEffect as Rm,useState as db}from"react";var Sm,Xe,wo=h(()=>{"use strict";M();je();Sm={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},Xe=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Je(),o=Sm[n]??Sm.default,[r,s]=db(0);if(Rm(()=>{s(0)},[o]),Rm(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%o.length)},500);return()=>clearInterval(c)},[e,o]),!e)return Em.createElement(xm,null,t);let d=o[r]??o[0]??t;return Em.createElement(xm,{color:C.accent,dimColor:r===1},d)}});import{Box as Ha,Text as cb}from"ink";import ei from"react";var lb,Rn,Lr=h(()=>{"use strict";je();lb=(e,t,n,o)=>{let r=u=>Math.max(1,e[u]??1),s=n,d=n+1,c=r(n);for(;d<t&&c+r(d)<=o;)c+=r(d),d++;for(;s>0&&c+r(s-1)<=o;)s--,c+=r(s);return{start:s,end:d}},Rn=({children:e=[],height:t,selectedIndex:n,itemHeight:o=1,itemHeights:r,scrollByOne:s=!1})=>{if(e.length===0)return null;let d=Math.max(1,Math.floor(t)),c=Math.max(1,Math.ceil(o)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(1,Math.floor(d/c)),p=Math.max(0,e.length-m),{start:f,end:x}=r?lb(r,e.length,u,d):s?{start:Math.min(p,Math.max(0,u-m+1)),end:Math.min(p,Math.max(0,u-m+1))+m}:{start:Math.min(p,Math.floor(u/m)*m),end:Math.min(p,Math.floor(u/m)*m)+m},S=Math.max(1,x-f),A=e.slice(f,x),P=e.length>S,T=d,w=P?Math.max(1,Math.floor(S/e.length*T)):T,_=Math.max(0,T-w),B=Math.max(1,e.length-S),$=P?Math.floor(f/B*_):0;return ei.createElement(Ha,{flexDirection:"row",height:d,width:"100%"},ei.createElement(Ha,{flexDirection:"column",flexGrow:1,height:d},A),ei.createElement(Ha,{flexDirection:"column",width:1,height:T},Array.from({length:T}).map((se,mn)=>ei.createElement(cb,{key:mn,color:P&&mn>=$&&mn<$+w?C.accent:C.secondary},P?"\u2502":" "))))}});var Nm,Wa,ub,ti,qa=h(()=>{"use strict";M();ub=()=>{let{eventLog:e=[]}=g();if(Wa&&Nm===e)return Wa;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Nm=e,Wa=t,t},ti=e=>ub().has(e)});import{Text as mb}from"ink";import pb from"react";var gb,fb,To,ni=h(()=>{"use strict";Us();dt();te();qa();ot();gb=e=>e.toLowerCase().trim(),fb=(e,t=yo)=>{let n=gb(e);return t[n]?t[n]:kr(n)},To=({id:e,isSelected:t,maxWidth:n})=>{let o=I.getContributor(e);if(!o)return;let r=o.name,s=n===void 0?r:Pn(r,n);return pb.createElement(mb,{underline:t,color:fb(r)},"@"+s,ti(e)?"":"\u2197")}});import{Text as hb}from"ink";import vb from"react";var oi,Ga=h(()=>{"use strict";te();je();dt();ot();oi=({id:e,isSelected:t,maxWidth:n})=>{let o=I.getTag(e);if(!o)return;let r=n===void 0?o.name:Pn(o.name,n);return vb.createElement(hb,{underline:t,backgroundColor:Ce(o.name),color:C.secondary}," "+r+" ")}});import{useEffect as yb,useState as bb}from"react";var Ib,Am,ri,Dr,xb,Eb,Mo,si=h(()=>{"use strict";dt();Ib=80,Am=1400,ri=new Set,Dr=null,xb=e=>(ri.add(e),Dr||(Dr=setInterval(()=>{for(let t of ri)t()},Ib)),()=>{ri.delete(e),ri.size===0&&Dr&&(clearInterval(Dr),Dr=null)}),Eb=()=>{let e=Date.now()%Am/Am;return e<.5?e*2:(1-e)*2},Mo=e=>{let[,t]=bb(0);return yb(()=>{if(e)return xb(()=>t(n=>n+1))},[e]),Xu(Eb())}});import{Box as ko,Text as Po}from"ink";import Qe from"react";var Rb,Cm,Sb,Nb,Tm,Mm=h(()=>{"use strict";te();je();ot();qa();st();Nr();ni();Ga();si();Rb=(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),Pn(e.slice(r).trim(),n)]},Cm=3,Sb=2,Nb=(e,t)=>{let n=[],o=0;for(let[r,s]of e.entries()){let d=e.length-r-1,c=d>0?String(d).length+1:0;if(o+s.width+c>t)break;o+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},Tm=({width:e,ticket:t,isSelected:n,isFlashing:o=!1})=>{let r=Mo(o),s=e-4,d=s-7-1,[c,u]=Rb(pe(t.title),d,s),m=u?null:Pn(pe(t.props.description),s)||null,p=In(t),f=xn(t).map(w=>({...w,name:w.name})),x=Math.max(1,s-Cm),S=I.getCommentsByIssue(t.id),A=S.length?String(S.length).length+2+1:0,{shown:P,hidden:T}=Nb([...p.map(w=>({id:w.id,isTag:!0,width:Math.min(w.name.length,x)+Cm})),...f.map(w=>({id:w.id,isTag:!1,width:Math.min(w.name.length,x)+Sb+(ti(w.id)?0:1)}))],s-A);return Qe.createElement(ko,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:o?r:n?C.accent:C.secondary,justifyContent:"space-between"},Qe.createElement(ko,{paddingLeft:1,paddingRight:1,flexDirection:"column"},Qe.createElement(ko,{justifyContent:"space-between"},Qe.createElement(Po,{color:C.primary},c),Qe.createElement(Po,{color:C.secondary2,dimColor:!0},j(t.id))),u&&Qe.createElement(Po,{color:C.primary},u),m&&Qe.createElement(Po,{color:C.secondary2,dimColor:!0},m)),Qe.createElement(ko,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},Qe.createElement(ko,{flexDirection:"row"},P.map(w=>Qe.createElement(ko,{paddingRight:1,key:w.id},w.isTag?Qe.createElement(oi,{id:w.id,maxWidth:x}):Qe.createElement(To,{id:w.id,maxWidth:x}))),T>0&&Qe.createElement(Po,{color:C.secondary2,dimColor:!0},"+",T)),S.length>0&&Qe.createElement(Po,{color:C.accent},"[",S.length,"]")))}});import{Box as Qn,Text as Fr}from"ink";import ct from"react";var Ab,km,Pm=h(()=>{"use strict";me();te();je();dt();wo();si();Ab=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,km=({index:e,labelWidth:t,width:n,ticket:o,isSelected:r,isFlashing:s=!1,mode:d})=>{let c=Mo(s),u=(o.props.tags??[]).map(se=>I.getTag(se)).filter(se=>!!se),m=(o.props.assignees??[]).map(se=>I.getContributor(se)).map(se=>se&&{...se,name:se.name}).filter(se=>!!se),p=1,f=u.length*(1+p),x=m.length*(2+p),S=u.map(se=>ct.createElement(Qn,{key:se.id,paddingRight:p},ct.createElement(Fr,{color:Ce(se.name)},"\u25A0"))),A=m.map(se=>ct.createElement(Qn,{key:se.id,paddingRight:p},ct.createElement(Fr,{color:kr(se.name)},"@"+se.name.at(0)))),P=s?c:r?C.accent:d===y.MOVE?C.secondary:C.primary,T=I.getCommentsByIssue(o.id),w=T.length?String(T.length).length+2+p:0,_=T.length?ct.createElement(Qn,{paddingRight:p},ct.createElement(Fr,{color:C.accent},"[",T.length,"]")):null,B=f+x+w,$=Math.max(1,n-t-B-(B>0?1:0));return ct.createElement(Qn,{justifyContent:"space-between"},ct.createElement(Qn,null,ct.createElement(Qn,{width:t},r?ct.createElement(Xe,{isSelected:!0}):ct.createElement(Fr,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),ct.createElement(Fr,{wrap:"truncate",color:P},Ab(o.title,$))),ct.createElement(Qn,null,S,A,_))}});import Cb from"chalk";import{Box as za,Text as wb}from"ink";import jt from"react";var Tb,Lm,Dm=h(()=>{"use strict";V();M();je();wo();Lr();Mm();Pm();si();Tb=({swimlane:e,isSelected:t,width:n,height:o,isDense:r,isFocused:s,listSelectedIndex:d,mode:c})=>{let{renderedChildrenIndex:u,replay:m}=Je(),p=u[e.id]??[],f=m?new Set(m.flashNodeIds):null,x=f?.has(e.id)??!1,S=Mo(x),A=`${e.title} ${Cb.hex(C.secondary2).dim("("+p.length+")")}`,P=3,T=r?1:5,w=s&&d===-1,_=n-3-(r?1:0)-(w?2:0),B=Math.max(2,String(p.length).length+1),$=o-P-1,se=jt.createElement(za,{borderStyle:"round",borderColor:C.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:r?1:0},jt.createElement(Xe,{isSelected:t}),jt.createElement(wb,{bold:!0,color:x?S:t?C.accent:C.primary},A," ",e.readonly?"\u{1F512}":"")),mn=(zt,so)=>{let qo=s&&d===so;if(!k(zt))return null;let Go=f?.has(zt.id)??!1;return r?jt.createElement(km,{key:zt.id,index:so,labelWidth:B,width:_,ticket:zt,isSelected:qo,isFlashing:Go,mode:c}):jt.createElement(Tm,{key:zt.id,width:_,ticket:zt,isSelected:qo,isFlashing:Go})};return jt.createElement(za,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?C.accent:C.secondary,paddingRight:0,paddingLeft:r?1:0,height:o},se,jt.createElement(za,null,p.length>0&&jt.createElement(Rn,{selectedIndex:d,height:$,itemHeight:T},p.map(mn)),w&&jt.createElement(Xe,{isSelected:!0})))},Lm=jt.memo(Tb)});var Fm,_m,Va=h(()=>{"use strict";On();Fm=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},_m=(e,t,n)=>Te.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0})});var Lo,ii=h(()=>{"use strict";Lo=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{Box as Do,Text as an}from"ink";import _e,{useEffect as Mb,useMemo as kb,useRef as Pb}from"react";import{decodeTime as Bm}from"ulid";function Um({ticket:e,width:t,height:n}){let o=kb(()=>Db(e),[e]),r=Pb([]);Mb(()=>(Om(r.current),r.current=_b(e,o),()=>{Om(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=Je(),c=Math.max(1,n-4),u=Math.max(12,t-32);return o.length===0?_e.createElement(Do,{flexDirection:"column",width:t,height:n,padding:1},_e.createElement(an,{color:C.primary},"No attachments yet."),_e.createElement(Do,{paddingTop:1},_e.createElement(an,{color:C.primary},"Attach images from the browser GUI"),_e.createElement(an,{color:C.accent}," epiq gui "),_e.createElement(an,{color:C.primary},"by dropping or pasting them."))):_e.createElement(Do,{flexDirection:"column",width:t,height:n},_e.createElement(Do,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:C.secondary,borderStyle:"single",paddingBottom:1},_e.createElement(an,{color:C.secondary2},"Attachments (",o.length,") \u2014 enter to open"," ")),_e.createElement(Rn,{height:c,itemHeight:2,selectedIndex:s},o.map((m,p)=>{let f=p===s,x=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return _e.createElement(Do,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},_e.createElement(an,{color:C.accent},f?"\u276F ":" "),_e.createElement(Do,{paddingLeft:1},_e.createElement(an,{color:C.secondary2},`#${p+1} `),_e.createElement(an,{color:f?C.accent:C.primary},x),_e.createElement(an,{color:C.secondary2}," "+Bb(m.bytes)+" "+Lo(Ze(m.id)))))})))}var Lb,Db,Om,Fb,_b,Bb,$m=h(()=>{"use strict";it();et();ii();V();R();te();On();M();je();Ro();Lr();Lb=e=>Me(e,"attachments"),Db=e=>I.getAttachmentsByIssue(e.id).sort((t,n)=>Bm(t.id)-Bm(n.id)),Om=e=>{for(let t of e)I.deleteNode(t.id)},Fb=(e,t,n)=>Te.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),_b=(e,t)=>{let n=I.getNode(Lb(e.id));if(!n||!nt(n))return[];let o=t.map((r,s)=>Fb(r,s,n.id)).map(r=>I.createNode(r)).filter(wt).map(({value:r})=>r).filter(nt);return t.length>0&&g().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),o},Bb=e=>`${Math.max(1,Math.round(e/1024))} KB`});var Hm,Ka,jm,Ya,Wm,qm,Ob,Gm,Ub,Xa,zm=h(()=>{"use strict";Hm=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,Ka=e=>e.replace(Hm,""),jm=e=>e==="additions"||e==="deletions",Ya=e=>{let t=Hm.exec(e);if(!t?.[1])return null;let n;try{n=JSON.parse(t[1])}catch{return null}let o=n;return typeof o?.filePath!="string"||typeof o.start!="number"||typeof o.end!="number"||typeof o.note!="string"||!jm(o.side)||!jm(o.endSide)||o.sha!==void 0&&typeof o.sha!="string"||o.issueRef!==void 0&&typeof o.issueRef!="string"?null:o},Wm=/```\n([\s\S]*?)\n?```\s*$/,qm=e=>Wm.exec(e)?.[1]??null,Ob=/`[^`\n]+`[^\n]*\n?$/,Gm=e=>Ka(e).replace(Wm,"").replace(Ob,"").trim(),Ub=e=>{let n=(e.endSide??e.side)==="deletions"?"removed":"added";return e.start===e.end?`line ${e.start} (${n})`:`lines ${e.start}-${e.end} (${n})`},Xa=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${Ub(e)}`});var $b,_r,jb,Hb,Wb,qb,Km,Ja,Ym,Vm,Xm,Qa=h(()=>{"use strict";zm();$b=(e,t)=>{let n=Math.max(1,Math.floor(t)),o=e.split(/\s+/).filter(Boolean);if(o.length===0)return[""];let r=[],s="";for(let d of o){let c=d;for(;c.length>n;)s&&(r.push(s),s=""),r.push(c.slice(0,n)),c=c.slice(n);s?s.length+1+c.length<=n?s=`${s} ${c}`:(r.push(s),s=c):s=c}return s&&r.push(s),r},_r=e=>{let t=e.split("`");return t.length%2===0?[{text:e}]:t.map((n,o)=>o%2===1?{text:n,code:!0}:{text:n}).filter(n=>n.text.length>0)},jb=/!\[([^\]]*)\]\([^)]*\)/g,Hb=e=>e.replace(jb,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),Wb=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),qb=4,Km=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(qb)),Ja=e=>{let t=!1;return e.map(Km).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let o=Ya(n);if(o)return{kind:"caption",text:Xa(o)};let r=Hb(n);if(r.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(r);return s?{kind:"heading",spans:_r(s[1]??"")}:{kind:"text",spans:_r(r)}})},Ym=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Vm=(e,t)=>{let n=[];for(let o of Ja(e))if(o.kind!=="fence"){if(o.kind==="blank"){n.length>0&&n[n.length-1]?.kind!=="blank"&&n.push(o);continue}if(o.kind==="code"){for(let r of Ym(o.text,t))n.push({kind:"code",text:r});continue}if(o.kind==="caption"){n.push(o);continue}for(let r of $b(Wb(o.spans),t))n.push({kind:o.kind,spans:_r(r)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},Xm=(e,t)=>{let n=Ya(e),o=n?qm(e):null;if(!n||o===null)return Vm(Ka(e).split(`
|
|
59
|
+
`),t);let r=Gm(e),s=o.split(`
|
|
60
|
+
`).map(Km),d=n.side===n.endSide?n.start:void 0,c=d===void 0?0:String(d+s.length-1).length+3;return[...r?[...Vm(r.split(`
|
|
61
|
+
`),t),{kind:"blank"}]:[],{kind:"caption",text:Xa(n)},...s.flatMap((u,m)=>Ym(u,Math.max(1,t-c)).map((p,f)=>({kind:"code",text:p,number:d===void 0||f>0?void 0:d+m})))]}});import{Box as Jm,Text as Zn}from"ink";import It from"react";var Qm,Za,Zm,ed=h(()=>{"use strict";je();Qm=({spans:e,bold:t,wrap:n})=>It.createElement(Zn,{color:C.primary,bold:t,wrap:n},e.map((o,r)=>o.code?It.createElement(Zn,{key:r,color:C.yellow},o.text):It.createElement(Zn,{key:r},o.text))),Za=({line:e,width:t,gutter:n=0,wrap:o})=>{switch(e.kind){case"blank":return It.createElement(Zn,null," ");case"fence":return It.createElement(Zn,{color:C.secondary2},"```");case"caption":return It.createElement(Zn,{color:C.accent,wrap:o},e.text);case"heading":return It.createElement(Qm,{spans:e.spans,bold:!0,wrap:o});case"text":return It.createElement(Qm,{spans:e.spans,wrap:o});case"code":{let r=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return It.createElement(Zn,{backgroundColor:C.secondary,color:C.primary,wrap:o},r,e.text.padEnd(Math.max(0,t-r.length)))}}},Zm=({lines:e,width:t})=>{let n=e.flatMap(r=>r.kind==="code"&&r.number!==void 0?[r.number]:[]),o=n.length>0?String(Math.max(...n)).length+3:0;return It.createElement(Jm,{flexDirection:"column"},e.map((r,s)=>It.createElement(Jm,{key:s},It.createElement(Za,{line:r,width:t,gutter:o}))))}});import{Box as Sn,Text as Nn}from"ink";import we,{useEffect as Gb,useMemo as ep,useRef as zb}from"react";import{decodeTime as tp}from"ulid";function op({ticket:e,width:t,height:n}){let o=ep(()=>Yb(e),[e]),r=zb([]);Gb(()=>(np(r.current),r.current=Xb(e,o),()=>{np(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=Je(),c=Math.max(1,n-4),u=Math.max(20,t-8),m=ep(()=>o.map(f=>{let x=Xm(f.md,u);return x.length>0?x:[{kind:"blank"}]}),[o,u]),p=m.map(f=>f.length+Vb);return o.length===0?we.createElement(Sn,{flexDirection:"column",width:t,height:n,padding:1},we.createElement(Nn,{color:C.primary},"No comments yet."),we.createElement(Sn,{paddingTop:1},we.createElement(Nn,{color:C.primary},"Use"),we.createElement(Nn,{color:C.accent}," :comment "),we.createElement(Nn,{color:C.primary},"to add the first one."))):we.createElement(Sn,{flexDirection:"column",width:t,height:n},we.createElement(Sn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:C.secondary,borderStyle:"single",paddingBottom:1},we.createElement(Nn,{color:C.secondary2},"Comments (",o.length,") ")),we.createElement(Rn,{height:c,itemHeights:p,selectedIndex:s},o.map((f,x)=>{let S=x===s;return we.createElement(Sn,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:C.secondary,borderStyle:"single"},we.createElement(Sn,{flexDirection:"row",paddingBottom:1},we.createElement(Nn,{color:C.accent},S?"\u276F ":" "),we.createElement(Sn,{paddingLeft:1},we.createElement(Nn,{color:C.secondary2},`#${x+1} `),we.createElement(To,{id:f.authorId}),we.createElement(Nn,{color:C.secondary2}," "+Lo(Ze(f.id))))),we.createElement(Sn,{paddingLeft:3,paddingBottom:1},we.createElement(Zm,{lines:m[x]??[],width:u})))})))}var Vb,Kb,Yb,np,Xb,rp=h(()=>{"use strict";it();et();ii();V();R();te();M();je();Ro();ni();Lr();Va();Qa();ed();Vb=4,Kb=e=>Me(e,"comments"),Yb=e=>I.getCommentsByIssue(e.id).sort((t,n)=>tp(t.id)-tp(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),np=e=>{for(let t of e)I.deleteNode(t.id)},Xb=(e,t)=>{let n=I.getNode(Kb(e.id));if(!n||!nt(n))return[];let o=t.map((r,s)=>_m(r,s,n.id)).map(I.createNode).filter(wt).map(({value:r})=>r).filter(Qo);return t.length>0&&g().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),o}});import{Box as ai,Text as Jb}from"ink";import dn from"react";var sp,ip=h(()=>{"use strict";V();te();uo();M();je();ni();wo();Ga();sp=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:o}=Je(),{title:r}=t,s=t.parentNodeId?I.getNode(t.parentNodeId):void 0,d=s&&k(s)?r===le.ASSIGNEES?s.props.assignees??[]:r===le.TAGS?(s.props.tags??[]).filter(c=>I.getTag(c)):[]:[];return dn.createElement(ai,{alignItems:"center",paddingTop:1},dn.createElement(ai,{minWidth:12},dn.createElement(Xe,{isSelected:n}),dn.createElement(Jb,{color:n?C.accent:C.secondary2},r,":")),dn.createElement(ai,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((c,u)=>{let m=o.id===t.id&&u===e;return dn.createElement(ai,{key:`${r}-${c}`,paddingRight:2,minHeight:1},dn.createElement(Xe,{isSelected:m}),r===le.ASSIGNEES?dn.createElement(To,{isSelected:m,id:c}):r===le.TAGS?dn.createElement(oi,{isSelected:m,id:c}):null)})))}});var td,ap,nd,od=h(()=>{"use strict";td=e=>Math.max(5,String(Math.max(e,1)).length+3),ap=(e,t)=>Math.max(0,e-6-td(t)),nd=(e,t=0)=>Math.max(1,e-5-2*t)});import{Box as Fo,Text as rd}from"ink";import xt,{useEffect as Qb,useMemo as sd}from"react";var Zb,dp,id,cp,eI,ad,lp=h(()=>{"use strict";te();R();On();M();je();ot();od();wo();Lr();ed();Qa();ao();Zb="\u2029",dp=(e,t)=>`${e}::inline-line::${t}`,id=new Map,cp=e=>{let t=id.get(e)??[];id.delete(e);for(let n of t)I.deleteNode(n)},eI=(e,t)=>{cp(e);let n=[];t.forEach((o,r)=>{let s=mt(BigInt(r+1));if(!wt(s))return;let d=I.createNode(Te.text({id:dp(e,r),name:`Line ${r+1}`,parentNodeId:e,rank:s.value,props:{value:o},readonly:!0,isVirtual:!0}));wt(d)&&n.push(d.value.id)}),id.set(e,n)},ad=({id:e,label:t,text:n,rows:o,selected:r,maxWidth:s})=>{let{selectedIndex:d,contextNode:c}=Je(),u=sd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=sd(()=>u.join("\0"),[u]);Qb(()=>(eI(e,u),()=>{cp(e)}),[e,m]);let p=td(u.length),f=ap(s,u.length),S=sd(()=>Ja(u).map(A=>{if(A.kind==="code"||A.kind==="caption")return{...A,text:Li(A.text,f)};if(A.kind==="text"||A.kind==="heading"){let P=A.spans.map(T=>T.code?`\`${T.text}\``:T.text).join("");return{...A,spans:_r(Li(P,f))}}return A}),[u,f]).map((A,P)=>{let T=c.id===e&&d===P;return xt.createElement(Fo,{key:dp(e,P)},xt.createElement(Fo,{flexShrink:0},xt.createElement(rd,{color:T?C.primary:C.secondary2,dimColor:!T},`${P+1} `.padStart(p,"\xA0"))),A.kind==="blank"?xt.createElement(rd,{backgroundColor:T?"gray":void 0},Zb):xt.createElement(Fo,null,xt.createElement(Za,{line:A,width:A.kind==="code"?f:0,wrap:"truncate-end"})))});return xt.createElement(Fo,{flexDirection:"column",paddingTop:1},xt.createElement(Fo,null,xt.createElement(Xe,{isSelected:r}),xt.createElement(rd,{color:r?C.accent:C.secondary2},t)),xt.createElement(Fo,{flexDirection:"row",borderStyle:"round",borderColor:C.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},xt.createElement(Rn,{scrollByOne:!0,height:o,selectedIndex:d,itemHeight:1},S)))}});import{Box as eo,Text as dd}from"ink";import Pe,{useMemo as Br}from"react";var tI,nI,oI,rI,up,mp=h(()=>{"use strict";V();te();M();je();Va();Ro();$m();rp();wo();ip();lp();od();tI=e=>Me(e,"description"),nI=e=>Me(e,"comments"),oI=e=>Me(e,"history"),rI=e=>Me(e,"attachments"),up=({ticket:e,height:t})=>{let n=Br(()=>Fm(e),[e]),{selectedIndex:o,contextNode:r}=Je(),s=process.stdout.columns||120,d=Br(()=>tI(e.id),[e.id]),c=Br(()=>nI(e.id),[e.id]),u=Br(()=>oI(e.id),[e.id]),m=Br(()=>rI(e.id),[e.id]),p=I.getAttachmentsByIssue(e.id).length,f=r.id===e.id,x=r.id===c||r.parentNodeId===c,S=r.id===u||r.parentNodeId===u,A=r.id===m||r.parentNodeId===m,P=oe(e.id);if(x){let $=t-3;return Pe.createElement(eo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Pe.createElement(op,{ticket:e,width:s,height:$}))}if(A){let $=t-3;return Pe.createElement(eo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Pe.createElement(Um,{ticket:e,width:s,height:$}))}if(S){let B=I.getNode(u),$=B&&nt(B)?B.props.value??"":"",se=nd(t);return Pe.createElement(eo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},B?Pe.createElement(ad,{id:B.id,label:"Event log",text:$,selected:!1,maxWidth:s,rows:se}):null)}let T=P.reduce((B,$)=>Xo($)||$.id===c||$.id===m||$.id===u?B+1:B,0),w=nd(t,T),_=(B,$)=>B.id===d?Pe.createElement(ad,{key:B.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:$,maxWidth:s,rows:w}):Xo(B)?Pe.createElement(sp,{key:B.id,parent:B,selected:$,selectedIndex:o}):B.id===c?Pe.createElement(eo,{key:B.id,paddingTop:1},Pe.createElement(Xe,{isSelected:$}),Pe.createElement(dd,{backgroundColor:C.secondary,color:$?C.accent:C.primary},` Comments (${n}) \u203A\u203A `)):B.id===m?Pe.createElement(eo,{key:B.id,paddingTop:1},Pe.createElement(Xe,{isSelected:$}),Pe.createElement(dd,{backgroundColor:C.secondary,color:$?C.accent:C.primary},` Attachments (${p}) \u203A\u203A `)):B.id===u?Pe.createElement(eo,{key:B.id,paddingTop:1},Pe.createElement(Xe,{isSelected:$}),Pe.createElement(dd,{backgroundColor:C.secondary,color:$?C.accent:C.primary}," History \u203A\u203A ")):null;return Pe.createElement(eo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},P.map((B,$)=>_(B,f&&o===$)))}});import{Box as sI}from"ink";import di from"react";var iI,pp,gp=h(()=>{"use strict";V();Dm();mp();iI=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,viewMode:s,height:d,width:c})=>{let u=t.context,m=u===z.TICKET||u===z.FIELD_LIST||u===z.FIELD,p=u===z.BOARD||u===z.SWIMLANE,f=u===z.TICKET?t:o.find(T=>T.context===z.TICKET),x=Math.floor(c/3),S=Math.floor(c/Math.max(e.length,1)),A=Math.min(S,x),P=s==="dense";return di.createElement(sI,{flexDirection:"row",height:d},p&&e.map((T,w)=>{let _=t.id===T.id,B=_?n:-1,$=t.context===z.BOARD&&n===w;return di.createElement(Lm,{key:T.id,height:d,width:A,swimlane:T,isSelected:$,isDense:P,isFocused:_,listSelectedIndex:B,mode:r})}),m&&f&&di.createElement(up,{height:d,ticket:f}))},pp=di.memo(iI)});import fp from"node:fs";import aI from"node:path";import dI from"react";import{render as cI}from"ink";import{Writable as lI}from"node:stream";var Or,uI,mI,pI,gI,hp,vp=h(()=>{"use strict";gp();V();R();M();ae();Be();Or=e=>String(e).padStart(2,"0"),uI=e=>{let t=e.getUTCFullYear(),n=Or(e.getUTCMonth()+1),o=Or(e.getUTCDate()),r=Or(e.getUTCHours()),s=Or(e.getUTCMinutes()),d=Or(e.getUTCSeconds());return`${t}-${n}-${o}_${r}-${s}-${d}`},mI=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",pI=async(e,{width:t,height:n})=>{let o="",r=new lI({write(d,c,u){let m=gI(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(o=m),u()}});r.columns=t,r.rows=n,r.isTTY=!0;let s=cI(e,{stdout:r,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),o},gI=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),hp=async()=>{let{viewMode:e}=Ie(),{contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,renderedChildrenIndex:s}=g(),d=o.find(w=>w.context==="BOARD");if(!d)return i("No board found to export");let c=120,u=40,m=await pI(dI.createElement(pp,{height:u,width:c,swimlanes:(s[d.id]??[]).filter(w=>w!==void 0&&pn(w)),contextNode:t,selectedIndex:n,breadCrumb:o,viewMode:e??"dense",mode:r}),{width:c,height:u});if(!m)return i("Failed to render board export");let p=gs(process.cwd());if(a(p))return i("Unable to export, epiq root not found");let f=new Date,x=uI(f),S=`board_${mI(d.title)}_${x}.md`,A=nl(p.value);fp.mkdirSync(A,{recursive:!0});let P=aI.join(A,S),T=`# Board - ${d.title}
|
|
62
|
+
Date: ${f.toISOString()}
|
|
62
63
|
|
|
63
64
|
\`\`\`text
|
|
64
65
|
${m}
|
|
65
66
|
\`\`\`
|
|
66
|
-
`;return
|
|
67
|
-
`).map(u=>u.trim()),s=
|
|
67
|
+
`;return fp.writeFileSync(P,T,"utf8"),l("Exported board layout",P)}});import{useSyncExternalStore as iL}from"react";var cd,fI,hI,_o,vI,An,ci=h(()=>{"use strict";R();fI=new Set,hI=()=>{for(let e of fI)e()},_o=()=>{if(!cd)throw new Error("Ui state not initialized. Call initUiState() first.");return cd},vI=e=>{let t=_o();return cd=e(t),hI(),l("UX state updated",null)},An=e=>vI(t=>({...t,...e}))});import{spawn as uL,spawnSync as yI}from"node:child_process";import bI from"node:os";import yp from"node:path";import{ulid as II}from"ulid";function bp(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 xI(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Ip(){let{preferredEditor:e}=Ie(),t=[e?xI(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function xp(e){let[t=""]=bp(e);return/(^|\/)code(-insiders)?$/.test(t)}function EI(e,t){let[n="",...o]=bp(e);return{command:n,args:[...o,...t]}}function RI(e,t){return EI(e,xp(e)?["--wait",t]:[t])}function Ep(e){let t=yp.join(bI.tmpdir(),"epiq");ze.mkDir(t);let n=yp.join(t,II());ze.writeToFile(n,e??"");let o=Ip();for(let r of o){let{command:s,args:d}=RI(r,n);if(!s)continue;let c=yI(s,d,{stdio:"inherit"});if(!c.error&&c.status===0){let u=ze.readFile(n);if(u==null)return i("Unable to read edited file");let m=u.replace(/\r?\n$/,"");return l("Successfully edited",m)}}return i("Unable to open editor")}var ld=h(()=>{"use strict";R();Be();zs()});import{ulid as ud}from"ulid";var Rp,SI,NI,Sp=h(()=>{"use strict";ld();xe();Se();Tt();V();R();uo();te();M();ae();nn();Rp=async e=>{let{contextNode:t,selectedIndex:n}=g(),o=oe(t.id)[n];if(e.modifier===at.DESCRIPTION)return NI();if(o&&Qo(o))return SI(e);if(e.modifier===at.TITLE){let r=ne();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 c=await Lt();return a(c)?c:L([{id:ud(),action:"edit.title",payload:{id:s.id,name:d},...r.value}],c.value)}return i("Unknown edit command")},SI=async e=>{let t=ne();if(a(t))return i("Unable to resolve user ID");let{contextNode:n,selectedIndex:o}=g(),r=oe(n.id)[o];if(!r||!Qo(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 c=r.id.split(":").at(0)??"",u=I.getComment(c);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 Lt();if(a(p))return p;let f=p.value;return L([{id:ud(),action:"edit.issue.comment",payload:{id:u.id,issue:d.id,md:m},...t.value}],f)},NI=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let t=await Lt();if(a(t))return t;let n=t.value,{breadCrumb:o,selectedNode:r}=g(),s=tt([...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 c=oe(d.id).find(f=>f.title===le.DESCRIPTION);if(!c)return i("No target found");if(c.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=Ep(u);if(a(m))return i("Failed to edit field");let p=m.value;return p===u?l("No changes made",null):L([{id:ud(),action:"edit.description",payload:{id:d.id,md:p},...e.value}],n)}});import md from"node:fs";import AI from"node:path";var Np,Ap=h(()=>{"use strict";R();ht();Np=async e=>{let t=AI.join(e,".gitignore"),n=md.existsSync(t)?md.readFileSync(t,"utf8"):"",o=[".epiq/events/",".epiq/log/"],r=n.split(`
|
|
68
|
+
`).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 l("Local epiq paths already ignored",!1);let c=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
68
69
|
`);return n=n.trimEnd()+`
|
|
69
70
|
|
|
70
|
-
${
|
|
71
|
-
`,
|
|
72
|
-
`));let ri=He();if(a(ri))return oe(16,ri.message);let{rootNodeId:_g,nodes:Ug}=ri.value,gd=Ug[_g];return gd?(U.navigate({contextNode:gd,selectedIndex:0}),E({hasProjectDefinition:!0,mode:h.DEFAULT}),c(Xn,null)):oe(16,"Unable to resolve initialized root node")}});import{ulid as Sb}from"ulid";function Ya(e){let t=Fm();if(a(t))return t;let{contextNode:n,nodes:r}=f();if(!n.parentNodeId)return i("Missing parent node id");let o=r[n.parentNodeId];if(!o)return i("Missing parent node");let s=ue(o.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=Om({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(u)?u:Bm(u.value)}function Xa(e){let t=Fm();if(a(t))return t;let{contextNode:n,selectedIndex:r}=f(),s=ue(n.id)[r+e];if(!s)return i("Missing sibling node");let d=Om({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:Bm(d.value)}var Dm,hn,xo,Fm,za,Om,Bm,Ja=y(()=>{"use strict";_t();gt();C();It();k();Dm=null,hn=()=>structuredClone(Dm),xo=e=>{Dm=e},Fm=()=>{let{contextNode:e,selectedIndex:t}=f(),r=ue(e.id)[t];return r?c("Resolved selected child",r):i("Target node not found")},za=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ue(t).filter(o=>o.id!==e);return ts(r,n)},Om=({id:e,parentId:t,position:n={at:"end"}})=>{let r=fe();if(a(r))return i("Unable to resolve user ID");let o=za({parentId:t,id:e,position:n});return a(o)?o:c("Created pending move state",{id:Sb(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Bm=e=>{xo(e);let t=nn(e,!0);return a(t)?t:c("Node moved successfully",t.value)}});import{ulid as Nb}from"ulid";var _m,Ws,Um,$m=y(()=>{"use strict";Je();Ja();Dn();gt();le();C();It();xe();k();re();_m=()=>{let e=hn();if(!e)return i("No pending move state");let t=e.payload.id,n=e.payload.parent,r=f().nodes[n];if(!r)return i("Move parent not found");let o=ue(n).findIndex(s=>s.id===t);return o===-1?i("Moved node not found among rendered children"):(U.navigate({contextNode:r,selectedIndex:o}),c("Synchronized navigation to moved node",null))},Ws=(e,t="Moved preview")=>{if(a(e))return e;let n=_m();return a(n)?n:(E({mode:h.MOVE}),c(t,null))},Um=async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=de().commandMeta,{contextNode:n,selectedIndex:r}=f(),o=ue(n.id)[r];if(!o)return E({mode:h.DEFAULT}),i("No move target");if(t==="start"){if(o.readonly)return i("Target node is read-only");if(r===-1)return i("No item selected");if(!o.parentNodeId)return i("Target has no parent");let s=ue(o.parentNodeId),d=s.findIndex(({id:g})=>g===o.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=za({parentId:o.parentNodeId,id:o.id,position:m});return a(p)?p:(xo({id:Nb(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),E({mode:h.MOVE}),c("Move initialized",null))}if(t==="next")return Ws(Xa(1));if(t==="previous")return Ws(Xa(-1));if(t==="to-next")return Ws(Ya(1));if(t==="to-previous")return Ws(Ya(-1));if(t==="confirm"){let s=hn();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=_m();return a(u)?u:(xo(null),E({mode:h.DEFAULT}),c("Moved item",null))}return t==="cancel"?(xo(null),E({mode:h.DEFAULT}),c("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as Cb,ulid as Ab}from"ulid";var Tb,Gs,Qa=y(()=>{"use strict";C();Tb=Cb(),Gs=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=Tb();return c("Created issue events",[{id:Ab(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as qs}from"ulid";var jm,Hm=y(()=>{"use strict";Je();Qa();Dn();gt();bt();C();me();It();k();re();jm=async(e,t)=>{let n=fe();if(a(n))return i("Unable to resolve user ID");let r=await St();if(a(r))return r;let o=r.value;if(!t.inputString)return i(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:d,selectedIndex:l}=f(),u=m=>{let p=B([m],o);if(a(p))return p;let g=x.getNode(p.value[0].result.id);if(!g)return i("Created node not found");if(!g.parentNodeId)return p;let I=x.getNode(g.parentNodeId);return I?(U.navigate({contextNode:I,selectedIndex:x.getSiblings(g.parentNodeId).findIndex(({id:N})=>N===g.id)}),p):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=f(),p=x.getNode(m);if(!p)return i("Workspace not found");let g=On(p.id,n.value,o);return a(g)?g:u({id:qs(),action:"add.board",payload:{id:qs(),name:t.inputString,parent:p.id,rank:g.value},...n.value})}if(t.modifier==="swimlane"){let m=ze(s,"BOARD");if(a(m))return i("Unable to add swimlane in this context");let p=On(m.value.id,n.value,o);return a(p)?p:u({id:qs(),action:"add.swimlane",payload:{id:qs(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=ae(d.id)[l],p=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let $=ze(s,"SWIMLANE");return a($)?null:$.value})();if(!p)return i("Unable to add issue in this context");let g=On(p.id,n.value,o);if(a(g))return g;let I=Gs({name:t.inputString,parent:p.id,rank:g.value,user:n.value});if(a(I))return I;let N=I.value,A=B([...N],o);if(a(A))return A;if(!A.value[0])return i("Issue creation failed");let M=N.find($=>$.action==="add.issue")?.payload.id;return M?(U.navigate({contextNode:p,selectedIndex:x.getSiblings(p.id).findIndex(({id:$})=>$===M)}),c("Issue created",null)):i("Unable to determine ticket id")}return c("Success",null)}});var Wm,Gm=y(()=>{"use strict";mt();lt();Xr();eo();qr();jt();C();Ot();k();as();Wm=async e=>{let t=Se({repoRoot:e});if(a(t))return Vr(3,t.message);let n=await Bn({repoRoot:e,stateBranchRoot:t.value,stateBranchName:Oo().stateBranch});if(a(n))return Vr(3,n.message);let r=await G({cwd:t.value,args:["pull","--ff-only"]});a(r)&&logger.info(3,r.message);let o=$t(t.value);if(a(o))return Vr(3,o.message);let{events:s,unreadable:d}=o.value,l=an(s,d);if(a(l))return Vr(4,l.message);E({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let u=ea({root:e});return a(u)&&logger.info(u.message),c("Loaded project",void 0)}});import wb from"node:os";import qm from"node:path";var Mb,kb,Vm,Km=y(()=>{"use strict";Gm();eo();C();xe();k();re();Mb=e=>e==="~"||e.startsWith("~/")?qm.join(wb.homedir(),e.slice(1)):e,kb=(e,t)=>{let n=e.trim();if(!n)return i("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?c("Resolved recent project",o.root):i(`No recent project #${n}`)}let r=Xe(qm.resolve(Mb(n)));return a(r)?i(`No epiq project at ${n}`):c("Resolved project path",r.value)},Vm=async()=>{let e=ks();if(K(""),f().hasProjectDefinition)return i("Already in a project; run epiq from another directory");let t=gs({exclude:process.cwd()}),n=a(t)?[]:t.value,r=kb(e,n);if(a(r))return i(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(l){return i(`Unable to enter ${o}: ${l instanceof Error?l.message:String(l)}`)}let d=await Wm(o);return a(d)?(process.chdir(s),i(d.message)):c(`Opened ${Sl(o)}`,null)}});var Vs,Za=y(()=>{"use strict";Je();jt();_t();C();k();Vs=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=f(),s=_i(n,t);if(a(s))return i(s.message);let{appliedEvents:d,unappliedEvents:l}=s.value,u=Kt();if(a(u))return u;let m=Bt(d),{fatal:p,skipped:g}=Tn(m);if(p.length>0)return Kt(),E(o),i(p.map(N=>N.message).join(", "));wn(g);let I=f().nodes[e];return I?(U.navigate({contextNode:I,selectedIndex:r}),c("",{unappliedEvents:l})):(Kt(),E(o),i("Board did not exist at that date"))}});var zm,Ym=y(()=>{"use strict";zm=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)}});var Lb,Pb,Db,Ks,zs,Vn,Xm,Jm,ed=y(()=>{"use strict";dt();Io();_t();le();C();Ym();k();Lb=20,Pb=16,Db=150,Ks=null,zs=null,Vn=()=>{Ks!==null&&(clearInterval(Ks),Ks=null),zs!==null&&(clearTimeout(zs),zs=null)},Xm=()=>{Vn(),E({mode:h.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Jm=({events:e,startTime:t,durationMs:n})=>{Vn();let r=e.length,o=Nr(e.map(g=>Cr(g))).map(g=>g??t),s=o[r-1]??Date.now(),d=zm(o),l=Math.max(1,Math.round(n*Lb/1e3)),u=Math.max(Math.round(n/l),Pb),m=0,p=0;E({mode:h.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Ks=setInterval(()=>{m++;let g=m/l,I=[],N,A;for(;p<r&&d[p]<=g;){let T=e[p],M=nn(T);if(a(M)){if($r(M)){p++;continue}Xm();return}I.push(...Ti(T)),N=T,A=o[p],p++}if(p>=r||m>=l){for(;p<r;p++){let M=nn(e[p]);if(a(M)&&!$r(M))break}let T=f().replay;E({unappliedEvents:[],replay:T&&{...T,progress:1,appliedCount:r}}),Vn(),zs=setTimeout(Xm,Db);return}let w=f().replay;E({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,g),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:N?A??w?.currentTime??t:w?.currentTime??t,currentLabel:N?td(N):w?.currentLabel??"",flashNodeIds:N?[...new Set(I)]:w?.flashNodeIds??[]}})},u)}});var Qm,Zm=y(()=>{"use strict";mt();dt();jt();_t();le();bt();C();xe();k();ro();Za();ed();Qm=async()=>{let e=ze(f().breadCrumb,"BOARD");if(a(e))return e;let t=await ut(process.cwd());if(a(t))return i("Unable to locate repo root");let n=Se({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=de().commandMeta;if(Vn(),r==="now"){let l=kn(n.value);if(a(l))return i(l.message);let u=Kt();if(a(u))return u;let m=Bt(l.value),{fatal:p,skipped:g}=Tn(m);return p.length>0?i(p.map(I=>I.message).join(", ")):(wn(g),E({mode:h.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),c("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let l=Ui(n.value);if(a(l))return l;let u=r==="prev"?f().eventLog.at(-1):f().unappliedEvents.at(0),m=u===void 0?null:Cr(u),p=(u===void 0?null:l.value.get(u.id)??null)??(m===null?null:di(m));if(p===null)return i(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?p:p+1}else{let l=Un(r||o.trim());if(!l)return i("Invalid peek date");s=l.getTime()}let d=Vs({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(d)?d:(E({mode:h.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:d.value.unappliedEvents,replay:null}),c("Peeking",!0))}});var ep,tp=y(()=>{"use strict";mt();bt();C();xe();k();ro();Za();ed();ep=async()=>{let e=ze(f().breadCrumb,"BOARD");if(a(e))return e;let t=await ut(process.cwd());if(a(t))return i("Unable to locate repo root");let n=Se({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=de().commandMeta,{dateInput:s,durationInput:d}=xs(r,o);if(Vn(),f().syncStatus.status==="syncing")return i("Cannot replay while syncing, try again in a moment");let l=Un(s);if(!l)return i("Invalid replay date");let u=d?bs(d):15e3;if(u===null)return i("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=f(),g=Vs({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(g))return g;let{unappliedEvents:I}=g.value;return I.length===0?(Kt(),E(p),c("Nothing to replay from that point",!0)):(Jm({events:I,startTime:m,durationMs:u}),c("Replaying board history",!0))}});import Ob from"zod";var np,rp=y(()=>{"use strict";jn();le();C();xe();Be();k();np=()=>{let e=de().commandMeta.inputString,t=Ob.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=st({autoSyncDebounceMs:t.data});return a(n)?n:(et({autoSyncIntervalMs:t.data}),E({mode:h.DEFAULT}),c(`Auto sync interval set to ${t.data}ms`,null))}});var op,sp=y(()=>{"use strict";to();jn();le();C();xe();Be();k();op=()=>{let e=de().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=Ml(e),n=st({autoSync:t});return a(n)?n:(et({autoSync:t}),E({mode:h.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});var ip,ap=y(()=>{"use strict";jn();le();C();xe();Be();k();ip=()=>{let e=de().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return i("Invalid response");let n=st({logLevel:e});return a(n)?n:(et({logLevel:e}),E({mode:h.DEFAULT}),c(`Auto sync set to "${e}"`,null))}});import{spawn as Bb}from"node:child_process";var _b,dp,cp=y(()=>{"use strict";C();_b=()=>{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"]}}},dp=async e=>new Promise(t=>{let{command:n,args:r}=_b();try{let o=Bb(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(i(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?c("Copied to clipboard",null):i(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(i(`Clipboard tool not available (${n})`))}})});var Eo,lp,up=y(()=>{"use strict";C();k();cp();tn();no();ln();Eo=async(e,t)=>{if(!e.trim())return i(`Nothing to copy: ${t} is empty`);let n=await dp(e);return a(n)?n:c(`Copied ${t} to clipboard`,null)},lp=async e=>{let{breadCrumb:t,selectedNode:n}=f(),r=oo({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return i("Nothing selected to copy from");switch(e.modifier){case Ee.REF:return Eo(z(o.id),"ref");case Ee.TITLE:return Eo(o.title,"title");case Ee.DESCRIPTION:return r?Eo(r.props?.description??"","description"):i("No issue in scope");case Ee.TAGS:{if(!r)return i("No issue in scope");let s=dn(r).map(({name:d})=>d);return Eo(s.join(", "),"tags")}case Ee.ASSIGNEES:{if(!r)return i("No issue in scope");let s=cn(r).map(({name:d})=>d);return Eo(s.join(", "),"assignees")}default:return i("Yank one of: ref, title, description, tags, assignees")}}});var mp,pp=y(()=>{"use strict";Xi();le();C();xe();k();mp=async()=>{K(""),E({mode:h.DEFAULT});let e=He();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 us();return a(t)?(E({syncStatus:{msg:t.message,status:"failed"}}),t):(E({mode:h.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});import{ulid as Oe}from"ulid";var Ub,gp,zt,fp,hp=y(()=>{"use strict";me();Im();Je();Qn();jn();Dn();gt();Ha();nr();le();bt();ge();C();me();It();xe();Be();k();Hs();re();Ga();_n();xa();ln();uo();Tm();Pm();$m();Hm();Km();Zm();tp();rp();ma();sp();ap();up();pp();Ub=e=>e.action==="add.issue.comment",gp=()=>{let{eventLog:e=[],contributors:t}=f(),n=new Map,r=new Set;for(let o of e)o.userId&&(n.set(o.userId,o.userName??""),r.add(o.userId));for(let o of Object.values(t))n.set(o.id,o.name);return[...n.entries()].map(([o,s])=>({id:o,name:s,isExternal:!r.has(o)}))},zt=async()=>{let e=await St();return a(e)?e:c("Resolved persist root",e.value)},fp=[{systemOnly:!0,intent:F.Move,description:"Internal move-state command",mode:h.COMMAND_LINE,action:Um},{intent:F.Delete,description:"Delete the currently selected node",mode:h.COMMAND_LINE,action:async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=ae(t.id)[n];if(!r)return i("Unable to resolve child to delete");let o=await zt();if(a(o))return o;if(r.context==="COMMENT"){let s=r.id,d=P(t)?t.id:t.parentNodeId;if(!d)return i("Unable to resolve comment issue");let l=f().nodes[d];if(!l||!P(l))return i("Unable to resolve comment issue");let u=l.log?.filter(Ub).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):B([{id:Oe(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],o.value):i("Unable to resolve comment")}return B([{id:Oe(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:h.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=de().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(d=>be(v.FILTER).map(l=>l.split(n)[0]).includes(d))(r))return i("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return Ie(d=>({...d,filters:e==="clear"?[]:[...d.filters,s],mode:h.DEFAULT})),c("Filter updated",null)}},{intent:F.ViewHelp,description:"Open the help screen",mode:h.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=f();return fn({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),E({mode:h.HELP}),c("Viewing help",null)}},{intent:F.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:h.COMMAND_LINE,action:async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=ae(t.id)[n];if(!r)return i("Unable to close issue, no target found");if(!P(r))return i("Cannot close in this context");let o=f().nodes[ye];if(!o)return i("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return i("Issue is already closed");let s=await zt();if(a(s))return s;let d=s.value,l=sn(o.id,r.id,{at:"end"},e.value,d);if(a(l))return l;let u=B([{id:Oe(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...e.value}],d);return a(u)?u:c("Issue closed",null)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:h.COMMAND_LINE,action:async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=ae(t.id)[n];if(!r)return i("Unable to reopen issue, no target found");let o=r.context==="TICKET"?c("Resolved ticket",r):Kn(r.id,"TICKET");if(a(o))return i("Cannot reopen in this context");let s=o.value,d=f().nodes[ye];if(!d)return i("Unable to locate closed swimlane");if(s.parentNodeId!==d.id)return i("Issue is not closed");if(!P(s))return i("Target node is not issue");let l=js(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=f().nodes[l];if(!u)return i("Previous parent no longer exists");let m=await zt();if(a(m))return m;let p=m.value,g=sn(u.id,s.id,{at:"end"},e.value,p);if(a(g))return g;let I=B([{id:Oe(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:g.value},...e.value}],p);return a(I)?I:c("Issue reopened",null)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Init,description:"Initialize Epiq in the current git repository",mode:h.COMMAND_LINE,action:Lm},{intent:F.OpenProject,description:"Open a recently used epiq project, by number or path",mode:h.COMMAND_LINE,action:Vm,onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.NewItem,description:"Create a new board, swimlane, or issue",mode:h.COMMAND_LINE,action:jm,onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Rename,description:"Rename the currently selected node",mode:h.COMMAND_LINE,action:async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=f(),r=ae(t.id)[n];if(!r)return i("Missing node");if(r.readonly)return i("Cannot rename readonly node");let o=ks();if(!o)return i("Provide a title");let s=await zt();return a(s)?s:B([{id:Oe(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.UntagTicket,description:"Remove a tag from the selected issue",mode:h.COMMAND_LINE,action:async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=de().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let o=x.findTagByName(r);if(!o)return i(`Tag "${r}" does not exist`);let{selectedNode:s}=f();if(!s)return i("Invalid untag target");let d=Kn(s.id,"TICKET");if(a(d))return i("Unable to untag issue in this context");let l=d.value;if(!P(l))return i("Target node is not issue");if(!(l.props.tags??[]).includes(o.id))return i("Issue is not tagged with that tag");let m=await zt();return a(m)?m:B([{id:Oe(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...e.value}],m.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.TagTicket,description:"Add or create a tag on the selected issue",mode:h.COMMAND_LINE,action:async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=de().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let{selectedNode:o}=f();if(!o)return i("Invalid tag target");let s=Kn(o.id,"TICKET");if(a(s))return i("Unable to tag issue in this context");let d=s.value;if(!P(d))return i("Target node is not issue");let l=await zt();if(a(l))return l;let u=x.findTagByName(r),m=u?.id??Oe();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):B([...u?[]:[{id:Oe(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:Oe(),action:"add.issue.tag",payload:{id:d.id,tag:m},...e.value}],l.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.AssignUserToTicket,description:"Assign a user to the selected issue",mode:h.COMMAND_LINE,action:async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=de().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return i("Provide an assignee");let{selectedIndex:d,contextNode:l}=f(),u=ae(l.id)[d];if(!u)return i("Invalid assign target");let m=Kn(u.id,"TICKET");if(a(m))return i("Unable to assign issue in this context");let p=m.value;if(!P(p))return i("Target node is not issue");let g=await zt();if(a(g))return g;let I=gp(),N=!o&&s.toLowerCase()==="me",A,w;if(N)A=e.value.userId,w=I.find($=>$.id===A)?.name??e.value.userName;else{let $=I.filter(H=>H.name===s);if($.length>1)return i(`"${s}" matches ${$.length} contributors (${$.map(H=>H.id).join(", ")}). Assign from the GUI to choose by id.`);let O=$[0];if(!O&&!o)return i(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);A=O?.id??Oe(),w=O?.name??s}if((p.props.assignees??[]).includes(A))return i("Assignee already assigned");let M=!!f().contributors[A];return B([...M?[]:[{id:Oe(),action:"create.contributor",payload:{id:A,name:w},...e.value}],{id:Oe(),action:"add.issue.assignee",payload:{id:p.id,assignee:A},...e.value}],g.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:h.COMMAND_LINE,action:async()=>{let e=fe();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=de().commandMeta,r=(t||n).trim();if(!r)return i("Provide an assignee to remove");let{selectedNode:o}=f();if(!o)return i("Invalid unassign target");let s=Kn(o.id,"TICKET");if(a(s))return i("Unable to unassign in this context");let d=s.value;if(!P(d))return i("Target node is not issue");let l=d.props.assignees??[],u=r.toLowerCase()==="me",m=u?l.filter(I=>I===e.value.userId):gp().filter(I=>I.name===r&&l.includes(I.id)).map(I=>I.id);if(m.length>1)return i(`"${r}" 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 "${r}"`);let g=await zt();return a(g)?g:B([{id:Oe(),action:"remove.issue.assignee",payload:{id:d.id,assignee:p},...e.value}],g.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Comment,description:"Add a comment to the selected issue",mode:h.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 r=fe();if(a(r))return i("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=f(),d=ze([...o,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):Kn(l.id,"TICKET");if(a(u))return i("Unable to comment on issue in this context");let m=u.value;if(!P(m))return i("Target node is not issue");let p=await zt();return a(p)?p:B([{id:Oe(),action:"add.issue.comment",payload:{id:Oe(),issue:m.id,author:r.value.userId,md:n},...r.value}],p.value)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Sync,description:"Pull, commit, and push Epiq state",mode:h.COMMAND_LINE,action:mp},{intent:F.Peek,description:"View board state at another point in time",mode:h.COMMAND_LINE,action:Qm},{intent:F.Replay,description:"Replay board history forward from a point in time",mode:h.COMMAND_LINE,action:ep},{intent:F.Export,description:"Export the current board layout to markdown",mode:h.COMMAND_LINE,action:async()=>{let e=await xm();return a(e)?e:(E({mode:h.DEFAULT}),c("Export successful",!0))}},{intent:F.Exit,description:"Exit the application",mode:h.COMMAND_LINE,action:async()=>(U.exit(),c("Exit successful",!0))},{intent:F.Edit,description:"Edit title or description",mode:h.COMMAND_LINE,action:async(e,t)=>Am(t),onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:h.COMMAND_LINE,action:async(e,t)=>lp(t),onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:h.COMMAND_LINE,action:(e,t)=>{let n=t.inputString.trim();switch(t.modifier){case pe.USERNAME:{if(process.env[vt])return i(`Cannot change the configured user while ${vt} names this process`);let r=Ss();if(a(r))return r;let{userId:o,preferredEditor:s,userName:d}=r.value,l=n||d,u=o||Oe();if(!l||!u)return i("Unable to resolve user name or id");let m=st({userName:l,userId:u,preferredEditor:s??""});return a(m)?m:(et({userName:l,userId:u}),E({mode:h.DEFAULT}),c(`Username set to "${l}"`,null))}case pe.EDITOR:{if(!n)return i("No editor provided");let r=st({preferredEditor:n});return a(r)?r:(et({preferredEditor:n}),E({mode:h.DEFAULT}),c(`Editor configuration set to "${n}"`,null))}case pe.VIEW:{if(n!=="wide"&&n!=="dense")return i("Invalid view mode");let r=st({viewMode:n});return a(r)?r:(et({viewMode:n}),E({mode:h.DEFAULT}),c(`View set to "${n}"`,null))}case pe.AUTOSYNC:return op();case pe.LOG_LEVEL:return ip();case pe.SYNC_DEBOUNCE_MS:return np();case pe.ATTACHMENT_MAX_KB:return zl();default:return i("Unknown config command")}}},{intent:F.Coffee,description:"Sponsor the development of Epiq!",mode:h.COMMAND_LINE,action:()=>{let e=de().commandMeta.modifier;return e==="custom"?bo("https://github.com/sponsors/ljtn?frequency=one-time&sponsor=ljtn"):bo(`https://github.com/sponsors/ljtn/sponsorships?sponsor=ljtn&preview=true&frequency=one-time&amount=${e}`),K(""),c("Thanks you!",null)}}]});var $b,kt,nd=y(()=>{"use strict";ms();As();xa();hp();C();xe();Be();k();$b=new Set(["peek","replay","filter","view-help","yank"]),kt=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=de();if(!t)return i("No command to confirm");if(!e&&n===un.Invalid)return i("Invalid command");let s=Su(t);xu();let{readOnly:d}=f();if(d&&!$b.has(s))return mo({status:Dt.Fail,message:"Command not available in readonly state",value:null});let l=fp.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!l)return mo({status:Dt.Fail,message:"Command not found",value:null});let u;try{u=await l.action(l,{command:t,inputString:o,modifier:r})}catch(m){return mo({status:Dt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?mo(u):(Iu({addToHistory:!e}),l.onSuccess?.(),ve().autoSync&&Il(),u)}});var Ys,Xs,vp,yp=y(()=>{"use strict";C();le();k();xn();nd();Ja();xe();Ys=[{intent:D.Exit,mode:h.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:h.COMMAND_LINE}),K("move cancel"),kt({isForceExecutedBySystem:!0}))},{intent:D.InitMove,mode:h.DEFAULT,description:"[m] move (init/confirm)",action:()=>(E({mode:h.COMMAND_LINE}),K("move start"),kt({isForceExecutedBySystem:!0}))},{intent:D.ConfirmMove,mode:h.MOVE,action:()=>(E({mode:h.COMMAND_LINE}),K("move confirm"),kt({isForceExecutedBySystem:!0}))}],Xs=[{intent:D.MovePreviousItem,mode:h.MOVE,action:()=>hn()?(E({mode:h.COMMAND_LINE}),K("move previous"),kt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:D.MoveNextItem,mode:h.MOVE,action:()=>hn()?(E({mode:h.COMMAND_LINE}),K("move next"),kt({isForceExecutedBySystem:!0})):i("No pending move")}],vp=[{intent:D.MoveToNextContainer,mode:h.MOVE,action:()=>hn()?(E({mode:h.COMMAND_LINE}),K("move to-next"),kt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:D.MoveToPreviousContainer,mode:h.MOVE,action:()=>hn()?(E({mode:h.COMMAND_LINE}),K("move to-previous"),kt({isForceExecutedBySystem:!0})):i("No pending move")}]});var bp,xp=y(()=>{"use strict";ge();yp();bp={[_.WORKSPACE]:[...Ys,...Xs],[_.BOARD]:[...Ys,...Xs],[_.SWIMLANE]:[...Ys,...Xs,...vp],[_.TICKET]:[],[_.FIELD]:[],[_.FIELD_LIST]:[],[_.TEXT]:[],[_.COMMENT]:[]}});import jb from"node:fs";import Hb from"node:path";var Ip,Ep=y(()=>{"use strict";mt();io();C();re();Ga();Ip=e=>{let t=Xe(process.cwd());if(a(t))return i("Unable to resolve project root");let n=Se({repoRoot:t.value});if(a(n))return i(n.message);let r=so(e.hash,e.ext),o=Hb.join(qo(n.value),r);return jb.existsSync(o)?(bo(o),c(`Opened ${e.name}`,null)):i("Attachment file not found \u2014 run :sync to fetch it")}});var Rp,Sp,Np=y(()=>{"use strict";le();C();xe();k();Hs();xn();Je();Rp=()=>{K("");let{pendingNavTarget:e}=xr();E({mode:h.DEFAULT}),e&&U.navigate(e),fn({pendingNavTarget:void 0})},Sp=[{intent:D.ExitCommandLine,mode:h.HELP,action:()=>(Rp(),c("Exiting help",null))},{intent:D.Exit,mode:h.HELP,action:()=>(Rp(),c("Closed help",null))},{intent:D.NavPreviousItem,mode:h.HELP,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),c("Navigating to previous help item",null))},{intent:D.NavNextItem,mode:h.HELP,action:()=>(U.navigateToNextItem(),c("Navigating to next help item",null))},{intent:D.NavToPreviousContainer,mode:h.HELP,action:()=>(U.navigateToPreviousContainer(),c("Navigating to previous help container",null))},{intent:D.NavToNextContainer,mode:h.HELP,action:()=>(U.navigateToNextContainer(),c("Navigating to next help container",null))}]});var Wb,Cp,Ap,Tp=y(()=>{"use strict";le();ge();C();xe();k();Hs();xn();Je();Wb=e=>{E({mode:h.COMMAND_LINE});let{pendingNavTarget:t}=xr();t&&U.navigate(t),fn({pendingNavTarget:void 0}),K(`${e} `)},Cp=()=>{K("");let{pendingNavTarget:e}=xr();e&&U.navigate(e),fn({pendingNavTarget:void 0}),E({mode:h.DEFAULT})},Ap=[{intent:D.InitCommandPalette,mode:h.DEFAULT,description:"[?] view command palette (explore descriptions for every command)",action:()=>{K("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=f();return fn({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),E({mode:h.PALETTE}),c("Opening command palette",null)}},{intent:D.Confirm,mode:h.PALETTE,action:()=>{let{selectedNode:e}=f();if(!e||!Rd(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?(Wb(t),c("Selected command",t)):c("No command selected",null)}},{intent:D.ExitCommandLine,mode:h.PALETTE,action:()=>(Cp(),c("Exiting palette",null))},{intent:D.Exit,mode:h.PALETTE,action:()=>(Cp(),c("Closed command palette",null))},{intent:D.NavPreviousItem,mode:h.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:D.NavNextItem,mode:h.PALETTE,action:()=>(U.navigateToNextItem(),c("Navigating to next item",null))},{intent:D.NavToPreviousContainer,mode:h.PALETTE,action:()=>(U.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:D.NavToNextContainer,mode:h.PALETTE,action:()=>(U.navigateToNextContainer(),c("Navigating to next container",null))}]});var wp,Mp=y(()=>{"use strict";_n();ln();le();C();tr();me();It();xe();k();Ep();xn();Np();Tp();Je();wp=[...Sp,...Ap,{intent:D.AddItem,mode:h.DEFAULT,description:"[n] new...",action:()=>(E({mode:h.COMMAND_LINE}),K(`${v.NEW} `),c("Adding new item",null))},{intent:D.Delete,mode:h.DEFAULT,description:"[d] delete",action:()=>(E({mode:h.COMMAND_LINE}),K(`${v.DELETE} `),c("Deleting item",null))},{intent:D.InitCommandLine,mode:h.DEFAULT,description:"[:] focus command line",action:()=>(E({mode:h.COMMAND_LINE}),K(""),c("Entering command line mode",null))},{intent:D.Confirm,mode:h.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=f();if(!ue(e?.id??"")?.length){let r=e?x.getAttachment(e.id):void 0;if(r)return Ip(r);if(e?.title===ie.DESCRIPTION)return E({mode:h.COMMAND_LINE}),K(`${v.EDIT} description `),c("Propose command",!0);if(e?.title===ie.ASSIGNEES)return E({mode:h.COMMAND_LINE}),K(`${v.ASSIGN} `),c("Propose command",!0);if(e?.title===ie.TAGS)return E({mode:h.COMMAND_LINE}),K(`${v.TAG} `),c("Propose command",!0);if(t.title===ie.DESCRIPTION&&e?.context==="TEXT")return E({mode:h.COMMAND_LINE}),K(`${v.EDIT} description `),c("Propose command",!0)}return U.enterChildNode(),c("Entering context",null)}},{intent:D.Yank,mode:h.DEFAULT,description:"[y] yank to clipboard",action:()=>{let{selectedNode:e}=f(),t=e?.title===ie.DESCRIPTION?Ee.DESCRIPTION:e?.title===ie.TAGS?Ee.TAGS:e?.title===ie.ASSIGNEES?Ee.ASSIGNEES:Ee.REF,r=be(v.YANK).includes(t)?t:Ee.REF;return E({mode:h.COMMAND_LINE}),K(`${v.YANK} ${r}`),c("Propose command",!0)}},{intent:D.EditTitle,mode:h.DEFAULT,description:"[r] rename title",action:()=>(E({mode:h.COMMAND_LINE}),K(`${v.EDIT} title ${f().selectedNode?.title}`),c("Exiting context",null))},{intent:D.EditDescription,mode:h.DEFAULT,description:"[e] edit description",action:()=>(E({mode:h.COMMAND_LINE}),K(`${v.EDIT} description `),c("Exiting context",null))},{intent:D.Exit,mode:h.DEFAULT,description:"[q] exit context",action:()=>(U.enterParentNode(),c("Exiting context",null))},{intent:D.NavPreviousItem,mode:h.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),c("Navigating to previous item",null))},{intent:D.NavNextItem,mode:h.DEFAULT,action:()=>(U.navigateToNextItem(),c("Navigating to next item",null))},{intent:D.NavToPreviousContainer,mode:h.DEFAULT,action:()=>(U.navigateToPreviousContainer(),c("Navigating to previous container",null))},{intent:D.NavToNextContainer,mode:h.DEFAULT,action:()=>(U.navigateToNextContainer(),c("Navigating to next container",null))}]});var Gb,qb,kp,Lp=y(()=>{"use strict";xe();Gb=500,qb=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),kp=e=>{let t=qb(e);t&&Ms(n=>(n+t).slice(0,Gb))}});var Vb,Kb,Pp,Dp=y(()=>{"use strict";Lp();le();C();xe();k();xn();nd();Vb=[h.COMMAND_LINE,h.PALETTE],Kb=e=>[{intent:D.MoveCursorLeft,mode:e,action:()=>(ya(-1),c("Moving cursor left",null))},{intent:D.MoveCursorRight,mode:e,action:()=>(ya(1),c("Moving cursor right",null))},{intent:D.MoveCursorLeftOfWord,mode:e,action:()=>(ba("left"),c("Moving cursor left of word",null))},{intent:D.MoveCursorRightOfWord,mode:e,action:()=>(ba("right"),c("Moving cursor right of word",null))},{intent:D.AutoCompleteCommand,mode:e,action:()=>(Ms((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=f().selectedNode?.title??""),r+o}),c("Auto-completing command",null))},{intent:D.CaptureInput,mode:e,action:(t,{sequence:n})=>(kp(n??""),c("Capturing input",null))},{intent:D.EraseInput,mode:e,action:()=>(yu(),c("Erasing input",null))},{intent:D.EraseInputWord,mode:e,action:()=>(bu(),c("Erasing input word",null))}],Pp=[{intent:D.Confirm,mode:h.COMMAND_LINE,action:()=>(kt(),c("Executing command",null))},{intent:D.ViewHelp,mode:h.DEFAULT,action:()=>(E({mode:h.HELP}),c("Viewing help",null))},...Vb.flatMap(Kb),{intent:D.ExitCommandLine,mode:h.COMMAND_LINE,action:()=>(E({mode:h.DEFAULT}),c("Exiting command line",null))},{intent:D.GetLastCommandFromHistory,mode:h.COMMAND_LINE,action:()=>(Eu(),c("Getting last command from history",null))},{intent:D.GetNextCommandFromHistory,mode:h.COMMAND_LINE,action:()=>(Ru(),c("Getting next command from history",null))}]});import Bp from"chalk";var Js,Fp,Op,rd,_p=y(()=>{"use strict";le();ge();Pe();Js=Bp.dim.hex(S.secondary2)(": for command line"),Fp="q to exit",Op=`${Bp.hex(S.accent)("m")} to confirm`,rd={[_.WORKSPACE]:[Js],[_.BOARD]:[Js],[_.BOARD+h.COMMAND_LINE]:[Js],[_.SWIMLANE]:[Js],[_.TICKET+h.HELP]:[Fp],[_.SWIMLANE+h.HELP]:[Fp],[_.TICKET]:[],[_.FIELD]:[],[_.SWIMLANE+h.MOVE]:[Op],[_.TICKET+h.MOVE]:[Op]}});function Up(e,t,n){let r=t[e];if(!r)return i("buildBreadCrumb(): current node not found");let o=[],s=new Set,d=r;for(;d&&!s.has(d.id)&&(o.push(d),s.add(d.id),!(d.id===n||!d.parentNodeId));)d=t[d.parentNodeId];let l=o[o.length-1];return!l||l.id!==n?i("buildBreadCrumb(): node is not connected to root"):(o.reverse(),c("Breadcrumb built",o))}var $p=y(()=>{"use strict";C()});var jp,Hp=y(()=>{"use strict";jp=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 zb}from"react";function ad(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return i("derive(): contextNodeId is missing");if(!r)return i("derive(): rootNode is missing");if(!o[r])return i("derive(): unable to find root node");let l=o[t];if(!l)return i("Unable to derive state, contextNode not found");let u=Up(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,g=rd[p+n]??rd[p]??[],I=[...wp,...bp[p]??[],...Pp],N=jp(I),A=Xb(o,s),w=A[t]?.[e.selectedIndex]??null;return c("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:g,availableActions:I,actionIndex:N,selectedNode:w,renderedChildrenIndex:A})}function jr(e){od=e;let t=Xe(process.cwd()),n=!1;if(!a(t)){let s=Ft(t.value);if(a(s))return i(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:h.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:{}},o=ad(r);return a(o)?o:(Lt=o.value,id(),c("State initialized",null))}function Ie(e){let t=f(),n=e(t);if(zn)return Ro=n,Lt={...t,...n},c("State updated",null);let r=ad(n);return a(r)?i(r.message??"Unable to update state"):(Lt=r.value,id(),c("State updated",null))}function cc(e){if(zn)return c("Joined batch",e());zn=!0,Ro=null;let t=()=>{let n=Ro;if(zn=!1,Ro=null,n===null)return null;let r=ad(n);return a(r)?i(r.message??"Unable to update state"):(Lt=r.value,id(),c("State updated",null))};try{let n=e(),r=t();return r&&a(r)?i(r.message):c("State updated",n)}finally{zn&&t()}}function Yn(e,t,n){if(!zn)return Ie(d=>({...d,[e]:{...d[e]??{},[t]:n}}));let r=f(),o=r[e]??{};o[t]=n;let s={...r,[e]:o};return Ro=s,Lt={...r,...s},c("State updated",null)}var Lt,od,sd,id,Yb,f,He,zn,Ro,$c,E,Ve,Xb,ae,Kt,ot,k=y(()=>{"use strict";xp();Mp();Dp();_p();Ot();le();C();re();Hi();$p();Hp();sd=new Set,id=()=>{for(let e of sd)e()},Yb=e=>(sd.add(e),()=>sd.delete(e));f=()=>{if(!Lt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Lt},He=()=>Lt?c("Retrieved state",Lt):i("State not initialized. Call initWorkspaceState() first.");zn=!1,Ro=null;$c=()=>zn,E=e=>Ie(t=>({...t,...e}));Ve=()=>zb(Yb,f,f),Xb=Oc,ae=e=>f()?.renderedChildrenIndex[e]??[],Kt=()=>od?jr(od):i("Cannot reset state: no initial workspace found"),ot=()=>Lt!==void 0});var Kn,Jb,vn,x,me=y(()=>{"use strict";bt();ge();C();k();It();Kn=(e,t)=>{let{nodes:n}=f(),r=n[e];if(!r)return i("Node not found");if(r.context===t)return c("Resolved ancestor node",r);let o=new Set([r.id]),s=r.parentNodeId?n[r.parentNodeId]:void 0;for(;s&&!o.has(s.id);){if(s.context===t)return c("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return i(`No ancestor found for context: ${t}`)},Jb=(e,t)=>{let{nodes:n}=f(),r=new Set,o=n[e];for(;o?.parentNodeId&&!r.has(o.id);){if(o.parentNodeId===t)return!0;r.add(o.id),o=n[o.parentNodeId]}return!1},vn=(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 r={...n,userId:t},o=Ie(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?i("Unable to link contributor to user"):c("Linked contributor to user",r)},deleteNode(e){Ie(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(!P(t))return i("Can only comment on issues");let n=Yn("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 r=this.getNode(n.issue);if(!r)return i("Unable to edit comment, missing issue");if(!P(r))return i("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=Yn("comments",e,o);return a(s)?i("Unable to edit comment"):c("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return i("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=Yn("comments",e,n);return a(r)?i("Unable to delete comment"):c("Deleted comment",n)},getComment(e){return f().comments?.[e]},getCommentsByIssue(e){return Object.values(f().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(f().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return i("Unable to create attachment, missing issue");if(!P(t))return i("Can only attach to issues");let n=Ie(r=>({...r,attachments:{...r.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},r=Ie(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return a(r)?i("Unable to delete attachment"):c("Deleted attachment",n)},getAttachment(e){return f().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(f().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(f().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=f(),r=n[e];if(!r)return i("Edit target node not found");let o=vn(r,"edit");if(o)return o;let s={...r,props:{...r.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 r=vn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),c("Renamed node",o)},getExistingTags(){let{tags:e}=f();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=f();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return ue(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=f(),o=this.getNode(e),s=this.getNode(t);if(!o)return i("Node not found");if(!s)return i("Target parent not found");if(r===e)return i("Cannot move root node");if(e===t)return i("Cannot move node into itself");let d=vn(o,"move");if(d)return d;if(Jb(t,e))return i("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),c("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=f(),o=this.getNode(e);if(!o)return i("Node not found");if(r===e)return i("Cannot delete root node");let s=vn(o,"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 g of ue(p.id))l(g.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",o)):i("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return i("Contributor not found");let n={...t,name:ko,tombstoned:!0},r=Ie(o=>({...o,contributors:{...o.contributors,[e]:n}}));return a(r)?i("Unable to remove contributor"):c("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return i("Contributor not found");if(n.tombstoned)return i("Cannot rename a removed contributor");let r={...n,name:t},o=Ie(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?i("Unable to rename contributor"):c("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return i("Contributor not found");let r={...n,name:t,tombstoned:!1},o=Ie(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?i("Unable to restore contributor"):c("Restored contributor",r)},createContributor(e){let t=Ie(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),r=this.getNode(e);if(!n)return i("Unable to assign contributor, missing contributor");if(!r)return i("Unable to assign contributor, missing target");let o=vn(r,"edit");if(o)return o;if(!P(r))return i("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return i("Contributor already assigned");let d={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(d),c("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return i("Unable to unassign, missing contributor");if(!r)return i("Unable to unassign, missing target");let o=vn(r,"edit");if(o)return o;if(!P(r))return i("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return c("Issue is not assigned to that contributor",{assignee:t});let d={...r,props:{...r.props,assignees:s.filter(l=>l!==t)}};return this.updateNode(d),c("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return i("Unable to add tag, missing tag");if(!r)return i("Unable to add tag, missing target");let o=vn(r,"edit");if(o)return o;if(!P(r))return i("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return i("Tag already assigned");let d={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(d),c("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),r=this.getNode(e);if(!n)return i("Unable to remove tag, missing tag");if(!r)return i("Unable to remove tag, missing target");let o=vn(r,"edit");if(o)return o;if(!P(r))return i("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return c("Issue is not tagged with that tag",{tag:t});let d={...r,props:{...r.props,tags:s.filter(l=>l!==t)}};return this.updateNode(d),c("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return i("Tag not found");let n={...t,tombstoned:!0},r=Ie(o=>({...o,tags:{...o.tags,[e]:n}}));return a(r)?i("Unable to delete tag"):c("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return i("Tag not found");let r={...n,name:t,tombstoned:!1},o=Ie(s=>({...s,tags:{...s.tags,[e]:r}}));return a(o)?i("Unable to restore tag"):c("Restored tag",r)},createTag(e){let t=Ie(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?i("Could not create tag"):c("Tag created",e)},createNode(e){let t=Yn("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},r=Yn("nodes",e,n);return a(r)?i(r.message):c("Locked node",n)},updateNode(e){let t=Yn("nodes",e.id,e);return a(t)?t:c("Updated node",e)},getContributor(e){return f().contributors[e]},getTag(e){let t=f().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return f().tags[e]},getTags(){return Object.values(f().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return f().nodes[e]},getSiblings(e){return ue(e)}}});import yn from"chalk";import Wp from"string-width";var Qb,Zb,dd,ex,tx,Gp,qp,nx,rx,ox,sx,ix,td,Vp,Io=y(()=>{"use strict";dt();me();k();Tt();_s();Qb=(e,t)=>e+" ".repeat(Math.max(0,t-Wp(e))),Zb=(e,t)=>" ".repeat(Math.max(0,t-Wp(e)))+e,dd=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","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed 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`),ex=(e,t)=>t?e<t?"up":e>t?"down":null:null,tx=(e,t)=>{let n=x.getNode(e.payload.parent),r=n?yn.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=ex(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Gp=e=>`${Math.max(1,Math.round(e/1024))} KB`,qp=e=>x.getAttachment(e)?.name??"",nx=e=>{switch(e.action){case"add.issue.tag":{let t=f().tags[e.payload.tag];return t?yn.bgHex(De(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?yn.bgHex(De(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=f().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?yn.hex(De(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?yn.hex(De(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${yn.dim(`(${Gp(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=qp(e.payload.id);return t?`"${t}"`:""}default:return""}},rx=e=>{let t=vr(yt(e));return yn.gray(Zb(t,8))},ox=12,sx=e=>Qb(`${e}`,ox),ix=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=f().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.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}" (${Gp(e.payload.bytes)})`;case"delete.issue.attachment":{let t=qp(e.payload.id);return t?`"${t}"`:""}default:return""}},td=e=>[dd(e.action),ix(e)].filter(Boolean).join(" "),Vp=(e,t)=>{let n=rx(e.id),r=sx(e.userName),o=yn.dim("\u203A"),s=e.action==="move.node"?tx(e,t):[dd(e.action),nx(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`}});var zp={};To(zp,{areVirtualNodesEnabled:()=>Yo,createOrUpdateVirtualField:()=>So,createOrUpdateVirtualFieldList:()=>cd,materializeTicketVirtualNodes:()=>zo,materializeVirtualNodes:()=>fx,setVirtualNodesEnabled:()=>gx});var ax,dx,cx,lx,ux,mx,So,cd,zo,px,Kp,gx,Yo,fx,wi=y(()=>{"use strict";Io();ge();C();tr();me();An();k();Zn();dr();ax=e=>Ce(e,"comments"),dx=e=>Ce(e,"description"),cx=e=>Ce(e,"assignees"),lx=e=>Ce(e,"tags"),ux=e=>Ce(e,"history"),mx=e=>Ce(e,"attachments"),So=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:d="horizontal"})=>{let l=x.getNode(e);if(!l){let p=x.createNode({...Ne.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:d});return a(p)?p:c("Virtual field created",void 0)}if(!Ye(l))return i(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==r||l.props.value!==o||l.readonly!==s||l.childRenderAxis!==d))return c("Virtual field unchanged",void 0);let m=x.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:s,childRenderAxis:d});return a(m)?m:c("Virtual field updated",void 0)},cd=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let d=x.getNode(e);if(!d){let m=x.createNode({...Ne.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return a(m)?m:c("Virtual field list created",void 0)}if(!Ar(d))return i(`Existing virtual node ${e} is not a field list`);if(!(d.title!==t||d.parentNodeId!==n||d.rank!==r||d.readonly!==o||d.childRenderAxis!==s))return c("Virtual field list unchanged",void 0);let u=x.updateNode({...d,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(u)?u:c("Virtual field list updated",void 0)},zo=e=>{let t=tt(xt/4n),n=tt(xt/2n),r=tt(xt*3n/4n),o=tt(xt*7n/8n),s=tt(xt*15n/16n),d=tt(xt*13n/16n);if(a(t))return t;if(a(n))return n;if(a(r))return r;if(a(o))return o;if(a(s))return s;if(a(d))return d;let l=So({id:dx(e.id),name:ie.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(l))return l;let u=cd({id:cx(e.id),name:ie.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(u))return u;let m=cd({id:lx(e.id),name:ie.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(a(m))return m;let p=So({id:ax(e.id),name:ie.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(p))return p;let g=So({id:mx(e.id),name:ie.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(g))return g;let I=So({id:ux(e.id),name:ie.HISTORY,parentNodeId:e.id,rank:d.value,value:px(e),readonly:!0,childRenderAxis:"vertical"});return a(I)?I:c("Ticket virtual nodes materialized",void 0)},px=e=>{let t=[...e.log].reverse(),n=new Map;for(let r of t){let o=n.get(r.action)??[];o.push(r.payload),n.set(r.action,o)}return t.map(r=>Vp(r,n.get(r.action)??[])).join(`
|
|
73
|
-
`)},Kp=!0,gx=e=>{Kp=e},Yo=()=>Kp,fx=()=>{let{nodes:e}=f();for(let t of Object.values(e)){if(!P(t))continue;let n=zo(t);if(a(n))return n}return c("Virtual nodes materialized",void 0)}});var hx,Yp,ld=y(()=>{"use strict";dt();jt();Hr();Io();C();Tt();hx=e=>{let t=new Map,n=new Set,r=o=>{let s=new Set,d=o;for(;d&&!s.has(d);){if(n.has(d))return d;s.add(d),d=t.get(d)}return null};return e.map(o=>{let s=o.payload,d=s?.id;if(!d)return null;o.action==="add.board"&&n.add(d);let l=s.parent??s.issue;return l&&t.set(d,l),n.has(d)?d:r(d)})},Yp=(e,t)=>{let n=hx(e);return e.filter((r,o)=>n[o]===t)}});var vx,Xp,Jp,ud,md=y(()=>{"use strict";mt();lt();tn();qa();jt();_t();C();Ot();Rs();re();k();ld();vx=null,Xp=Promise.resolve(),Jp=e=>{let t=Xp.then(e,e);return Xp=t.then(()=>{},()=>{}),t},ud=()=>{if(!ot())return{mode:"live",asOfTime:null};let{timeMode:e}=f();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:vx}}});import Qp from"node:fs";import yx from"node:path";import{ulid as q}from"ulid";var bx,xx,ti,Qs,ee,se,ne,Zp,Ix,eg,tg,ng,rg,og,sg,ig,ag,dg,cg,lg,ug,mg,pg,gg,fg,tU,hg,vg,yg,bg,xg,Ig,Eg,Rg,Sg,Ng,Ex,Cg,Ag,Tg,wg,Mg,kg,Lg,Pg=y(()=>{"use strict";mt();lt();Lr();Xr();Yi();Qn();jn();Qa();dt();qr();Hr();re();jt();Dn();gt();ld();Ha();nr();ge();C();me();It();k();is();eo();re();bt();Io();Tt();uo();tn();Jt();io();Et();md();bx=e=>{if(e.filePath)try{return c("Read attachment file",{data:Qp.readFileSync(e.filePath),name:e.name??yx.basename(e.filePath)})}catch(t){return i(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?c("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):i("Provide either filePath or dataBase64")},xx=()=>{let e=ca();return a(e)?Gt:e.value.attachmentMaxKb??Gt},ti=e=>{let t=Xe(e??process.cwd());return a(t)?i(t.message):c("Resolved Epiq repo root",t.value)},Qs=null,ee=async(e,t)=>{let n=ti(e);if(a(n))return n;let r=Se({repoRoot:n.value});if(a(r))return i(r.message);let o=Qt(n.value);if(a(o))return i(o.message);if(!(Qs!==null&&Qs.repoRoot===n.value&&Qs.stateBranchRoot===r.value&&Qp.existsSync(En(r.value)))){let p=await Vi({repoRoot:n.value,stateBranchName:o.value});if(a(p))return i(p.message);let g=await Bn({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(a(g))return i(g.message);Qs={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let p=await G({cwd:r.value,args:["pull","--ff-only"]});a(p)&&X.info(3,p.message)}let d={repoRoot:n.value,stateBranchRoot:r.value},l=Mn(r.value);if(mc(r.value)===l&&ot()&&ud().mode==="live")return c("Booted Epiq state, unchanged",d);let u=$t(r.value);if(a(u))return i(u.message);let m=an(u.value.events,u.value.unreadable);return a(m)?i(m.message):(pc(r.value,l),c("Booted Epiq state",d))},se=()=>{let e=ca();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")},ne=()=>{let e=He();return a(e)?i(e.message):e},Zp=e=>(e.props.tags??[]).map(t=>x.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:De(t.name)})),Ix=()=>{let e=He(),t=a(e)?[]:e.value.eventLog??[],n=new Map;for(let r of t)r.userId&&r.userName&&n.set(r.userId,r.userName);return n},eg=(e,t)=>{let n=new Map(e);for(let r of Object.values(t))n.set(r.id,r.name);return n},tg=e=>(e.props.assignees??[]).map(t=>x.getContributor(t)).filter(t=>t!=null).map(({id:t,name:n})=>({id:t,name:n,color:De(n)})),ng=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=ne();if(a(n))return n;let r=Object.values(n.value.nodes).filter(o=>o.context==="BOARD"&&!o.isDeleted).map(o=>({id:o.id,ref:z(o.id),title:o.title,parentId:o.parentNodeId,readonly:!!o.readonly}));return c("Listed boards",r)},rg=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=ne();if(a(n))return n;let r=Object.values(n.value.nodes).filter(o=>o.context==="SWIMLANE"&&!o.isDeleted).filter(o=>!e.boardId||o.parentNodeId===e.boardId).map(o=>({id:o.id,title:o.title,boardId:o.parentNodeId,isClosed:o.id===ye,readonly:!!o.readonly}));return c("Listed swimlanes",r)},og=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=ne();if(a(n))return n;let r=e.idOrRef.trim();if(!r)return i("Provide an issue id or ref");let o=Object.values(n.value.nodes).filter(P).filter(u=>!u.isDeleted),s=o.find(u=>u.id===r),d=s?[s]:o.filter(u=>_r(u.id,r));if(d.length===0)return i(`No issue matches "${r}"`);if(d.length>1)return i(`"${r}" matches ${d.length} issues: ${d.map(u=>`${z(u.id)} (${Me(u.title)})`).join(", ")}. Use a full ref or id.`);let l=d[0];return c("Found issue",{id:l.id,ref:z(l.id),title:Me(l.title),description:l.props.description??"",createdAt:yt(l.id),parentNodeId:l.parentNodeId,isClosed:l.parentNodeId===ye,readonly:!!l.readonly,tags:Zp(l),assignees:tg(l)})},sg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=ne();if(a(n))return n;let r=n.value.nodes,o=Object.values(r).filter(P).filter(s=>!s.isDeleted).filter(s=>e.includeClosed||s.parentNodeId!==ye).filter(s=>e.boardId?(s.parentNodeId?r[s.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).map(s=>({id:s.id,ref:z(s.id),title:Me(s.title),description:s.props.description??"",createdAt:yt(s.id),parentNodeId:s.parentNodeId,isClosed:s.parentNodeId===ye,readonly:!!s.readonly,tags:Zp(s),assignees:tg(s)}));return c("Listed issues",o)},ig=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=Me(e.title);if(!o)return i("Issue title cannot be empty");let s=e.description??"",d=ft("Issue title",o,300)??ft("Issue description",s,2e4);if(d)return i(d);if((e.tagNames?.length??0)>20)return i(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return i(`Cannot set more than ${20} assignees at once`);let l=On(e.parentId,n.value,t.value.stateBranchRoot);if(a(l))return l;let u=Gs({name:o,parent:e.parentId,user:n.value,rank:l.value});if(a(u))return u;let m=[...u.value],p=m.find(A=>A.action==="add.issue")?.payload.id;if(!p)return i("Unable to determine created issue id");s&&m.push({id:q(),...n.value,action:"edit.description",payload:{id:p,md:s}});let g=[];for(let A of e.tagNames??[]){let w=Me(A).trim();if(!w||g.some(O=>O.name===w))continue;let T=ft("Tag name",w,60);if(T)return i(T);let M=x.findTagByName(w),$=M?.id??q();M||m.push({id:q(),...n.value,action:"create.tag",payload:{id:$,name:w}}),m.push({id:q(),...n.value,action:"add.issue.tag",payload:{id:p,tag:$}}),g.push({id:$,name:w})}let I=[];for(let A of e.assigneeNames??[]){let w=Me(A).trim();if(!w||I.some(O=>O.name===w))continue;let T=ft("Assignee name",w,80);if(T)return i(T);let M=Object.values(r.value.contributors).find(O=>O.name===w),$=M?.id??q();M||m.push({id:q(),...n.value,action:"create.contributor",payload:{id:$,name:w}}),m.push({id:q(),...n.value,action:"add.issue.assignee",payload:{id:p,assignee:$}}),I.push({id:$,name:w})}let N=B(m,t.value.stateBranchRoot);return a(N)?i(N.message):c("Created issue",{id:p,ref:z(p),title:o,parentId:e.parentId,description:s,tags:g,assignees:I})},ag=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=sn(ye,e.issueId,{at:"end"},n.value,t.value.stateBranchRoot);if(a(r))return r;let o={id:q(),...n.value,action:"close.issue",payload:{id:e.issueId,parent:ye,rank:r.value}},s=B([o],t.value.stateBranchRoot);return a(s)?i(s.message):c("Closed issue",{id:e.issueId,ref:z(e.issueId)})},dg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Target node is not issue");if(o.parentNodeId!==ye)return i("Issue is not closed");let s=js(o);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=r.value.nodes[s];if(!d)return i("Previous parent no longer exists");let l=sn(d.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(l))return l;let u={id:q(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:d.id,rank:l.value}},m=B([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Reopened issue",{id:o.id,ref:z(o.id),parentId:d.id})},cg=async e=>{let t=ti(e.repoRoot);if(a(t))return t;let n=se();if(a(n))return n;let r=Se({repoRoot:t.value});if(a(r))return r;let o=$t(r.value);if(a(o))return o;let s=an(o.value.events,o.value.unreadable);if(a(s))return s;let d=sn(e.parentId,e.issueId,e.position??{at:"end"},n.value,r.value);if(a(d))return d;let l={id:q(),...n.value,action:"move.node",payload:{id:e.issueId,parent:e.parentId,rank:d.value}},u=B([l],r.value);return a(u)?i(u.message):c("Moved issue",{id:e.issueId,ref:z(e.issueId),parentId:e.parentId})},lg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.boardId];if(!o)return i("Board not found");if(!Lo(o))return i("Target parent must be a board");if(o.readonly)return i("Cannot add a swimlane to a readonly board");if(ud().mode!=="live")return i("Cannot add a swimlane while time travelling");let s=Me(e.title);if(!s.trim())return i("Swimlane title cannot be empty");let d=ft("Swimlane title",s,300);if(d)return i(d);let l=On(e.boardId,n.value,t.value.stateBranchRoot);if(a(l))return l;let u=q(),m={id:q(),...n.value,action:"add.swimlane",payload:{id:u,name:s,parent:e.boardId,rank:l.value}},p=B([m],t.value.stateBranchRoot);return a(p)?i(p.message):c("Created swimlane",{id:u,ref:z(u),title:s,boardId:e.boardId})},ug=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.swimlaneId];if(!o)return i("Swimlane not found");if(!bn(o))return i("Edit target must be a swimlane");if(o.readonly)return i("Cannot edit readonly swimlane");let s=Me(e.title);if(!s.trim())return i("Swimlane title cannot be empty");let d=ft("Swimlane title",s,300);if(d)return i(d);if(o.title===s)return c("No changes made",{id:e.swimlaneId,ref:z(e.swimlaneId),title:s});let l={id:q(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:s}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Edited swimlane title",{id:e.swimlaneId,ref:z(e.swimlaneId),title:s})},mg=async e=>{let t=ti(e.repoRoot);if(a(t))return t;let n=se();if(a(n))return n;let r=Se({repoRoot:t.value});if(a(r))return r;let o=$t(r.value);if(a(o))return o;let s=an(o.value.events,o.value.unreadable);if(a(s))return s;let d=sn(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(a(d))return d;let l={id:q(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:d.value}},u=B([l],r.value);return a(u)?i(u.message):c("Moved swimlane",{id:e.swimlaneId,ref:z(e.swimlaneId),boardId:e.boardId})},pg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.swimlaneId];if(!o)return i("Swimlane not found");if(!bn(o))return i("Delete target must be a swimlane");let s={id:q(),...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,ref:z(e.swimlaneId)})},gg=async(e={})=>{os();let t=ti(e.repoRoot);if(a(t))return i("Sync failed");let n=se();if(a(n))return n;let r=await ls({cwd:t.value,ownEventFileName:Pn(n.value)});return a(r)?(Wi(r.message),r):(ss(),c("Synced",r.value))},fg=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=ne();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})},tU=365*24*60*60*1e3,hg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Edit target must be an issue");if(o.readonly)return i("Cannot edit readonly issue");let s=ft("Issue description",e.description,2e4);if(s)return i(s);let d=o.props.description??"";if(d===e.description)return c("No changes made",{id:e.issueId,ref:z(e.issueId),description:d});let l={id:q(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Edited issue description",{id:e.issueId,ref:z(e.issueId),description:e.description})},vg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Edit target must be an issue");if(o.readonly)return i("Cannot edit readonly issue");let s=Me(e.title);if(!s.trim())return i("Issue title cannot be empty");let d=ft("Issue title",s,300);if(d)return i(d);if(o.title===s)return c("No changes made",{id:e.issueId,ref:z(e.issueId),title:s});let l={id:q(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Edited issue title",{id:e.issueId,ref:z(e.issueId),title:s})},yg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Tag target must be an issue");if(o.readonly)return i("Cannot tag readonly issue");let s=Me(e.tagName).trim();if(!s)return i("Tag name cannot be empty");let d=ft("Tag name",s,60);if(d)return i(d);let l=x.findTagByName(s),u=l?.id??q(),m=[...l?[]:[{id:q(),...n.value,action:"create.tag",payload:{id:u,name:s}}],{id:q(),...n.value,action:"add.issue.tag",payload:{id:e.issueId,tag:u}}],p=B(m,t.value.stateBranchRoot);return a(p)?i(p.message):c("Added issue tag",{id:e.issueId,ref:z(e.issueId),tag:{id:u,name:s}})},bg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return i("Tag not found");if(o.tombstoned)return i("Tag is already deleted");let s=[{id:q(),...n.value,action:"tombstone.tag",payload:{id:e.tagId}}],d=B(s,t.value.stateBranchRoot);return a(d)?i(d.message):c("Deleted tag",{id:o.id,name:o.name})},xg=async e=>{let t=ai(e.name,"name");if(a(t))return i(t.message);let n=await ee(e.repoRoot,{pull:!1});if(a(n))return n;let r=se();if(a(r))return r;let o=ne();if(a(o))return o;let s=r.value,d=!!o.value.contributors[s.userId];if(!d){let l=B([{id:q(),...s,action:"create.contributor",payload:{id:s.userId,name:s.userName}}],n.value.stateBranchRoot);if(a(l))return i(l.message)}return c(`Assumed ${s.userName}`,{...s,registered:!d})},Ig=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return i("Tag not found");if(!o.tombstoned)return i("Tag is not deleted");if(x.findTagByName(o.name))return i(`Cannot restore: another tag is already named "${o.name}"`);let s=[{id:q(),...n.value,action:"restore.tag",payload:{id:e.tagId,name:o.name}}],d=B(s,t.value.stateBranchRoot);return a(d)?i(d.message):c("Restored tag",{id:o.id,name:o.name})},Eg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Untag target must be an issue");if(o.readonly)return i("Cannot untag readonly issue");if(!r.value.tags[e.tagId])return i("Tag not found");let s={id:q(),...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,ref:z(e.issueId),tagId:e.tagId})},Rg=async(e,t)=>{let n=Bi(e);if(a(n))return;let r;for(let o of n.value)o.userId===t&&(r=o.userName??r);return r===void 0?void 0:{id:t,name:r}},Sg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Assign target must be an issue");if(o.readonly)return i("Cannot assign readonly issue");let s=e.self?n.value.userId:e.assigneeId;if(s){let T=r.value.contributors[s],M=T?void 0:await Rg(t.value.stateBranchRoot,s);if(!T&&!M)return i("Unknown assignee id");let $=T??M,O=[...T?[]:[{id:q(),...n.value,action:"create.contributor",payload:{id:$.id,name:$.name}}],{id:q(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:$.id}}],H=B(O,t.value.stateBranchRoot);return a(H)?i(H.message):c("Added issue assignee",{id:e.issueId,ref:z(e.issueId),assignee:{id:$.id,name:$.name}})}let d=Me(e.assigneeName??"").trim();if(!d)return i("Provide assigneeId, self or assigneeName");let l=ft("Assignee name",d,80);if(l)return i(l);let m=[...eg(Ix(),r.value.contributors).entries()].filter(([,T])=>T===d);if(m.length>1)return i(`"${d}" matches ${m.length} contributors (${m.map(([T])=>T).join(", ")}). Assign by assigneeId to choose.`);let p=m[0];if(!p&&!e.createUnlinked)return i(`No contributor named "${d}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[g=q(),I=d]=p??[],A=[...!!r.value.contributors[g]?[]:[{id:q(),...n.value,action:"create.contributor",payload:{id:g,name:I}}],{id:q(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:g}}],w=B(A,t.value.stateBranchRoot);return a(w)?i(w.message):c("Added issue assignee",{id:e.issueId,ref:z(e.issueId),assignee:{id:g,name:I}})},Ng=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;if(!r.value.contributors[e.contributorId])return i("Contributor not found");if(await Rg(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:q(),...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:ko})},Ex=async(e,t)=>{let n=kn(e);if(a(n))return;let r;for(let o of n.value){if(o.action!=="create.contributor")continue;let s=o.payload;s.id===t&&s.name&&(r=s.name)}return r},Cg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.contributors[e.contributorId];if(!o)return i("Contributor not found");if(!o.tombstoned)return i("Contributor is not tombstoned");let s=await Ex(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:q(),...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})},Ag=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=kn(t.value.stateBranchRoot);if(a(o))return i(o.message);let s=e.boardId?Yp(o.value,e.boardId):o.value,d=new Map,l=new Set,u=new Set,m=Bi(t.value.stateBranchRoot);if(a(m))return i(m.message);for(let N of m.value)N.userId&&u.add(N.userId);for(let N of s)N.userId&&(d.set(N.userId,N.userName??""),l.add(N.userId));let p=r.value.contributors,I=[...eg(d,p).entries()].map(([N,A])=>({id:N,name:A,color:De(A),isSelf:N===n.value.userId,isExternal:!l.has(N),isRemoved:p[N]?.tombstoned===!0,hasAuthoredAnywhere:u.has(N)}));return c("Listed board contributors",I)},Tg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Unassign target must be an issue");if(o.readonly)return i("Cannot unassign readonly issue");if(!r.value.contributors[e.assigneeId])return i("Assignee not found");let s={id:q(),...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,ref:z(e.issueId),assigneeId:e.assigneeId})},wg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Comment target must be an issue");if(o.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=q(),l={id:q(),...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})},Mg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return i("Unable to resolve comment");if(o.payload.author!==n.value.userId)return i("You can only delete your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return i("Issue not found");if(!P(s))return i("Comment target must be an issue");if(s.readonly)return i("Cannot delete comment on readonly issue");if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return c("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let l={id:q(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=B([l],t.value.stateBranchRoot);return a(u)?i(u.message):c("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},kg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.eventLog.find(p=>p.action==="add.issue.comment"&&p.payload.id===e.commentId);if(!o)return i("Unable to resolve comment");if(o.payload.author!==n.value.userId)return i("You can only edit your own comments");let s=r.value.nodes[o.payload.issue];if(!s)return i("Issue not found");if(!P(s))return i("Comment target must be an issue");if(s.readonly)return i("Cannot edit comment on readonly issue");if(r.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return i("Comment was deleted");let l=e.body.trim();if(!l)return i("Comment cannot be empty");if(l.length>4e3)return i(`Comment cannot exceed ${4e3} characters (got ${l.length})`);let u={id:q(),...n.value,action:"edit.issue.comment",payload:{id:e.commentId,issue:o.payload.issue,md:l}},m=B([u],t.value.stateBranchRoot);return a(m)?i(m.message):c("Edited issue comment",{id:e.commentId,issueId:o.payload.issue,body:l})},Lg=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=ne();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o)return i("Issue not found");if(!P(o))return i("Attachment target must be an issue");if(o.readonly)return i("Cannot attach to readonly issue");let s=bx(e);if(a(s))return s;let d=Kl(t.value.stateBranchRoot,s.value.data,xx());if(a(d))return d;let l=Me(s.value.name).trim()||"image",u=q(),m={id:q(),...n.value,action:"add.issue.attachment",payload:{id:u,issue:e.issueId,author:n.value.userId,hash:d.value.hash,ext:d.value.ext,name:l,bytes:d.value.bytes}},p=B([m],t.value.stateBranchRoot);if(a(p))return i(p.message);let g=so(d.value.hash,d.value.ext);return c("Added issue attachment",{id:u,issueId:e.issueId,fileName:g,bytes:d.value.bytes,markdown:la(l,g)})}});var Og={};To(Og,{createMcpServer:()=>Fg,resultJson:()=>Dg,startMcpServer:()=>Cx});import{McpServer as Sx}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Nx}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as b}from"zod";var Dg,J,Fg,Cx,Bg=y(()=>{"use strict";C();uo();Pg();md();Dg=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),J=e=>t=>Jp(async()=>Dg(await e(t))),Fg=()=>{let e=new Sx({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()})},J(fg)),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()})},J(sg)),e.registerTool("epiq_issue_get",{description:"Get one Epiq issue by its full id or its 7-character ref. Use this rather than listing the whole board when you already know which issue you want.",inputSchema:b.object({idOrRef:b.string().min(1),repoRoot:b.string().optional()})},J(og)),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:b.object({repoRoot:b.string().optional()})},J(ng)),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:b.object({repoRoot:b.string().optional(),boardId:b.string().optional()})},J(rg)),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).max(300)})},J(lg)),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).max(300)})},J(ug)),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()})},J(mg)),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)})},J(pg)),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).max(300),parentId:b.string().min(1),repoRoot:b.string().optional(),description:b.string().max(2e4).optional(),tagNames:b.array(b.string().max(60)).max(20).optional(),assigneeNames:b.array(b.string().max(80)).max(20).optional()})},J(ig)),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().max(2e4),repoRoot:b.string().optional()})},J(hg)),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).max(300),repoRoot:b.string().optional()})},J(vg)),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).max(60),repoRoot:b.string().optional()})},J(yg)),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()})},J(Eg)),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()})},J(Ag)),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()})},J(Ng)),e.registerTool("epiq_tag_remove",{description:"Delete a tag from the whole workspace. It disappears from every ticket, picker and filter, but its id and history stay in the event log, and the name is free for a new tag.",inputSchema:b.object({tagId:b.string().min(1),repoRoot:b.string().optional()})},J(bg)),e.registerTool("epiq_tag_restore",{description:"Put back a tag deleted with epiq_tag_remove, on every ticket that still carried it.",inputSchema:b.object({tagId:b.string().min(1),repoRoot:b.string().optional()})},J(Ig)),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()})},J(Cg)),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).max(80).optional(),createUnlinked:b.boolean().optional(),repoRoot:b.string().optional()})},J(Sg)),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()})},J(Tg)),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).max(4e3),repoRoot:b.string().optional()})},J(wg)),e.registerTool("epiq_issue_attachment_add",{description:"Attach an image file to an Epiq issue. Returns `markdown` \u2014 paste it into a comment or description body to render the image inline.",inputSchema:b.object({issueId:b.string().min(1),filePath:b.string().min(1),name:b.string().min(1).max(200).optional(),repoRoot:b.string().optional()})},J(Lg)),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()})},J(Mg)),e.registerTool("epiq_issue_comment_edit",{description:"Replace the body of one of your own comments on an Epiq issue",inputSchema:b.object({commentId:b.string().min(1),body:b.string().min(1).max(4e3),repoRoot:b.string().optional()})},J(kg)),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()})},J(dg)),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue",inputSchema:b.object({issueId:b.string().min(1),repoRoot:b.string().optional()})},J(ag)),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()})},J(cg)),e.registerTool("epiq_actor_assume",{description:'Take a board identity for the rest of this session, so your writes are attributed to you rather than to the user. Pass the name you announced \u2014 the model provider, a slash, then a short human first name, e.g. "claude/peter". Takes effect on the very next write; no relaunch. A name the server was launched with wins, and re-assuming the same name is harmless. Reuse an existing agent identity (epiq_contributor_list) before inventing one: a name is permanent once it has authored anything.',inputSchema:b.object({name:b.string().min(1).max(80),repoRoot:b.string().optional()})},J(xg)),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()})},J(gg)),e},Cx=async()=>{let e=Fg(),t=new Nx;await e.connect(t)}});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;var{applyActorNameArgument:Ax}=await Promise.resolve().then(()=>(Qn(),bd)),{isFail:Tx}=await Promise.resolve().then(()=>(C(),hd)),ni=process.argv.slice(2);ni.length>1&&(console.error(`Expected at most one name argument, got ${ni.length}`),process.exit(1));if(ni[0]!==void 0){let e=Ax(ni[0],"The name argument");Tx(e)&&(console.error(e.message),process.exit(1))}var{setVirtualNodesEnabled:wx}=await Promise.resolve().then(()=>(wi(),zp));wx(!1);var{startMcpServer:Mx}=await Promise.resolve().then(()=>(Bg(),Og));await Mx();
|
|
71
|
+
${c}
|
|
72
|
+
`,md.writeFileSync(t,n,"utf8"),X.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)}});import CI from"node:fs";import Cp from"node:path";var wI,be,li,pd=h(()=>{"use strict";Ap();as();We();Nt();br();zn();Se();R();ae();Yt();wI=async e=>{let t=await q({cwd:e,args:["status","--porcelain"]});return a(t)?t:l("Checked git diff",t.value.stdout.split(`
|
|
73
|
+
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},be=(e,t)=>i(`[${e}] ${t}`),li=async({cwd:e,user:t})=>{let n=rs(),o=await rt(e);if(a(o))return be(1,o.message);let r=o.value,s=await ds(r);if(a(s))return be(2,s.message);if(s.value)return be(2,`Cannot initialize Epiq while a git operation is in progress: ${s.value}`);let d=await wI(r);if(a(d))return be(2.5,d.message);if(d.value.length>0)return be(3,`Cannot initialize Epiq with uncommitted changes (${d.value.join(", ")}). Commit or stash your changes first.`);if(ar(r))return be(4,"Epiq project already initialized");let{userId:c,userName:u}=t;if(!c||!u)return be(5,"Missing Epiq user id");let m=await ru(r);if(a(m))return be(6,m.message);let p=n.stateBranch,f=await cs({repoRoot:r,branch:p});if(a(f))return be(6,f.message);if(f.value)return be(6,`State branch already exists: ${p}`);let x=await ma({repoRoot:r,stateBranchName:p});if(a(x))return be(6,x.message);let S=ms();if(a(S))return be(7,S.message);let A=Cp.join(us(),n.projectId),P=await Kn({repoRoot:r,stateBranchRoot:A,stateBranchName:p});if(a(P))return be(8,P.message);let T=Cp.join(A,".epiq");CI.mkdirSync(T,{recursive:!0});let w=Kl({userId:c,userName:u});if(a(w))return be(9,w.message);for(let qf of w.value){let fc=Es({event:qf,rootDir:A});if(a(fc))return be(9,fc.message)}let _=await ws({stateBranchRoot:A,eventFileName:qn({userId:c,userName:u})});if(a(_))return be(10,_.message);let B=await lo({cwd:A,message:"[epiq:init]"});if(a(B))return be(10,B.message);let $=await Np(r);if(a($))return be(11,$.message);let se=Bc({repoRoot:r,fileContents:n});if(a(se))return be(12,se.message);let mn=await ye.stage({cwd:r,pathspec:[".epiq/project.json",".gitignore"]});if(a(mn))return be(13,mn.message);let zt=await ye.commit({cwd:r,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(a(zt))return be(13,zt.message);let so=[],qo=await q({cwd:r,args:["push","-u","origin","HEAD"]});a(qo)&&so.push(`[init:14] ${qo.message}`);let Go=await yr({repoRoot:r,stateBranchRoot:A});return a(Go)&&so.push(`[init:15] ${Go.message}`),l("Project initialized",{repoRoot:r,projectId:n.projectId,stateBranch:p,stateBranchRoot:A,defaultEvents:w.value,warnings:so})}});var Ur,wp,Tp=h(()=>{"use strict";it();Sr();Zt();me();R();pd();de();Be();M();Ur=(e,t)=>i(`[${e}] ${t}`),wp=async()=>{ee("");let e=Os();if(!e.isSetupDone||!e.userName)return Ur(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let t=Ie(),n=t.userName,o=t.userId;if(!o||!n)return Ur(5,"Missing Epiq user id");let r=await li({cwd:process.cwd(),user:{userId:o,userName:n}});if(a(r))return r;let s="Project initialized!";for(let x of r.value.warnings)s+=` Warn: ${x}`;let c=Qt(r.value.defaultEvents).filter(a);if(c.length>0)return Ur(16,c.map(x=>x.message).join(`
|
|
74
|
+
`));let u=$e();if(a(u))return Ur(16,u.message);let{rootNodeId:m,nodes:p}=u.value,f=p[m];return f?(U.navigate({contextNode:f,selectedIndex:0}),E({hasProjectDefinition:!0,mode:y.DEFAULT}),l(s,null)):Ur(16,"Unable to resolve initialized root node")}});import{ulid as TI}from"ulid";function fd(e){let t=kp();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=ge(r.id),d=s.findIndex(({id:m})=>m===n.id);if(d<0)return i("Current node not found among siblings");let c=s[d+e];if(!c)return i("Missing sibling node");let u=Pp({id:t.value.id,parentId:c.id,position:{at:"end"}});return a(u)?u:Lp(u.value)}function hd(e){let t=kp();if(a(t))return t;let{contextNode:n,selectedIndex:o}=g(),s=ge(n.id)[o+e];if(!s)return i("Missing sibling node");let d=Pp({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:Lp(d.value)}var Mp,Cn,$r,kp,gd,Pp,Lp,vd=h(()=>{"use strict";Zt();Se();R();pt();M();Mp=null,Cn=()=>structuredClone(Mp),$r=e=>{Mp=e},kp=()=>{let{contextNode:e,selectedIndex:t}=g(),o=ge(e.id)[t];return o?l("Resolved selected child",o):i("Target node not found")},gd=({id:e,parentId:t,position:n={at:"end"}})=>{let o=ge(t).filter(r=>r.id!==e);return Rs(o,n)},Pp=({id:e,parentId:t,position:n={at:"end"}})=>{let o=ne();if(a(o))return i("Unable to resolve user ID");let r=gd({parentId:t,id:e,position:n});return a(r)?r:l("Created pending move state",{id:TI(),...o.value,action:"move.node",payload:{id:e,parent:t,rank:r.value.rank}})},Lp=e=>{$r(e);let t=hn(e,!0);return a(t)?t:l("Node moved successfully",t.value)}});import{ulid as MI}from"ulid";var Dp,ui,Fp,_p=h(()=>{"use strict";it();vd();xe();Se();me();R();pt();de();M();ae();Dp=()=>{let e=Cn();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=ge(n).findIndex(s=>s.id===t);return r===-1?i("Moved node not found among rendered children"):(U.navigate({contextNode:o,selectedIndex:r}),l("Synchronized navigation to moved node",null))},ui=(e,t="Moved preview")=>{if(a(e))return e;let n=Dp();return a(n)?n:(E({mode:y.MOVE}),l(t,null))},Fp=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=ie().commandMeta,{contextNode:n,selectedIndex:o}=g(),r=ge(n.id)[o];if(!r)return E({mode:y.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=ge(r.parentNodeId),d=s.findIndex(({id:f})=>f===r.id);if(d===-1)return i("Target not found among siblings");let c=s[d-1],u=s[d+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=gd({parentId:r.parentNodeId,id:r.id,position:m});return a(p)?p:($r({id:MI(),action:"move.node",payload:{id:r.id,parent:r.parentNodeId,rank:p.value.rank},...e.value}),E({mode:y.MOVE}),l("Move initialized",null))}if(t==="next")return ui(hd(1));if(t==="previous")return ui(hd(-1));if(t==="to-next")return ui(fd(1));if(t==="to-previous")return ui(fd(-1));if(t==="confirm"){let s=Cn();if(!s)return i("No pending move to confirm");let d=await Lt();if(a(d))return d;let c=L([s],d.value);if(a(c))return c;let u=Dp();return a(u)?u:($r(null),E({mode:y.DEFAULT}),l("Moved item",null))}return t==="cancel"?($r(null),E({mode:y.DEFAULT}),l("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as kI,ulid as PI}from"ulid";var LI,mi,yd=h(()=>{"use strict";R();LI=kI(),mi=({name:e,parent:t,rank:n,user:{userId:o,userName:r}})=>{let s=LI();return l("Created issue events",[{id:PI(),userId:o,userName:r,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as pi}from"ulid";var Bp,Op=h(()=>{"use strict";it();yd();xe();Se();Tt();R();te();pt();M();ae();Bp=async(e,t)=>{let n=ne();if(a(n))return i("Unable to resolve user ID");let o=await Lt();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:c}=g(),u=m=>{let p=L([m],r);if(a(p))return p;let f=I.getNode(p.value[0].result.id);if(!f)return i("Created node not found");if(!f.parentNodeId)return p;let x=I.getNode(f.parentNodeId);return x?(U.navigate({contextNode:x,selectedIndex:I.getSiblings(f.parentNodeId).findIndex(({id:S})=>S===f.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 f=bn(p.id,n.value,r);return a(f)?f:u({id:pi(),action:"add.board",payload:{id:pi(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=tt(s,"BOARD");if(a(m))return i("Unable to add swimlane in this context");let p=bn(m.value.id,n.value,r);return a(p)?p:u({id:pi(),action:"add.swimlane",payload:{id:pi(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=oe(d.id)[c],p=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let _=tt(s,"SWIMLANE");return a(_)?null:_.value})();if(!p)return i("Unable to add issue in this context");let f=bn(p.id,n.value,r);if(a(f))return f;let x=mi({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(a(x))return x;let S=x.value,A=L([...S],r);if(a(A))return A;if(!A.value[0])return i("Issue creation failed");let w=S.find(_=>_.action==="add.issue")?.payload.id;return w?(U.navigate({contextNode:p,selectedIndex:I.getSiblings(p.id).findIndex(({id:_})=>_===w)}),l("Issue created",null)):i("Unable to determine ticket id")}return l("Success",null)}});var DI,Up,FI,$p,_I,jp,Hp=h(()=>{"use strict";co();We();Nt();br();Ds();ha();Ps();vo();zn();bt();R();Yt();M();fr();ae();Cs();DI=e=>e.some(t=>t.action==="init.workspace"),Up=async(e,t)=>{let n=kt(e);return a(n)?i(n.message):rr({cwd:t,branch:n.value})},FI=e=>{let t=Ue(process.cwd());if(a(t))return!1;let n=ve({repoRoot:t.value});return!a(n)&&n.value===e},$p=async e=>{let t=ve({repoRoot:e});if(a(t))return po(3,t.message);let n=t.value,o=await Kn({repoRoot:e,stateBranchRoot:n,stateBranchName:rs().stateBranch});if(a(o))return po(3,o.message);let r=yt(n);if(a(r))return po(3,r.message);if(!DI(r.value.events)){let m=await Up(e,n);if(a(m)&&logger.info(3,m.message),r=yt(n),a(r))return po(3,r.message)}let{events:s,unreadable:d}=r.value,c=_t(s,d);if(a(c))return po(4,c.message);E({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let u=Rr({root:e});return a(u)&&logger.info(u.message),l("Loaded project",void 0)},_I=async e=>{let t=ve({repoRoot:e});if(a(t))return i(t.message);let n=t.value,o=await _n({repoRoot:n});if(a(o))return i(o.message);if(!o.value)return l("No remote to pull",void 0);let r=await Ms({worktreeRoot:n,operation:"boot pull",fn:()=>ya(n,()=>(mo("Pulling"),Up(e,n)))});if(a(r))return Ee(r.message);if(r.value===null)return l("Another process holds the state worktree",void 0);let s=r.value;if(a(s))return or(s.message)?(As("Offline"),l("Offline",void 0)):Ee(s.message);if(!s.value)return Vn("Already synced"),l("Already synced",void 0);if(!FI(n))return l("Project changed during the pull",void 0);let d=ba(n);return a(d)?d:(Vn("Pulled"),l("Pulled and reloaded",void 0))},jp=e=>{_I(e).then(t=>{a(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${Jl(t)}`)})}});import BI from"node:os";import Wp from"node:path";var OI,UI,qp,Gp=h(()=>{"use strict";Hp();vo();R();de();M();ae();OI=e=>e==="~"||e.startsWith("~/")?Wp.join(BI.homedir(),e.slice(1)):e,UI=(e,t)=>{let n=e.trim();if(!n)return i("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let r=t[Number(n)-1];return r?l("Resolved recent project",r.root):i(`No recent project #${n}`)}let o=Ue(Wp.resolve(OI(n)));return a(o)?i(`No epiq project at ${n}`):l("Resolved project path",o.value)},qp=async()=>{let e=Zs();if(ee(""),g().hasProjectDefinition)return i("Already in a project; run epiq from another directory");let t=Bs({exclude:process.cwd()}),n=a(t)?[]:t.value,o=UI(e,n);if(a(o))return i(o.message);let r=o.value,s=process.cwd();try{process.chdir(r)}catch(c){return i(`Unable to enter ${r}: ${c instanceof Error?c.message:String(c)}`)}let d=await $p(r);return a(d)?(process.chdir(s),i(d.message)):(jp(r),l(`Opened ${Iu(r)}`,null))}});var gi,bd=h(()=>{"use strict";it();bt();Zt();R();M();gi=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:o})=>{let r=g(),s=sa(n,t);if(a(s))return i(s.message);let{appliedEvents:d,unappliedEvents:c}=s.value,u=cn();if(a(u))return u;let m=Qt(d),{fatal:p,skipped:f}=Un(m);if(p.length>0)return cn(),E(r),i(p.map(S=>S.message).join(", "));$n(f);let x=g().nodes[e];return x?(U.navigate({contextNode:x,selectedIndex:o}),l("",{unappliedEvents:c})):(cn(),E(r),i("Board did not exist at that date"))}});var zp,Vp=h(()=>{"use strict";zp=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)}});var $I,jI,HI,fi,hi,to,Kp,Yp,Id=h(()=>{"use strict";et();jr();Zt();me();R();Vp();M();$I=20,jI=16,HI=150,fi=null,hi=null,to=()=>{fi!==null&&(clearInterval(fi),fi=null),hi!==null&&(clearTimeout(hi),hi=null)},Kp=()=>{to(),E({mode:y.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Yp=({events:e,startTime:t,durationMs:n})=>{to();let o=e.length,r=Ko(e.map(f=>Yo(f))).map(f=>f??t),s=r[o-1]??Date.now(),d=zp(r),c=Math.max(1,Math.round(n*$I/1e3)),u=Math.max(Math.round(n/c),jI),m=0,p=0;E({mode:y.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:o,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),fi=setInterval(()=>{m++;let f=m/c,x=[],S,A;for(;p<o&&d[p]<=f;){let T=e[p],w=hn(T);if(a(w)){if(lr(w)){p++;continue}Kp();return}x.push(...Yi(T)),S=T,A=r[p],p++}if(p>=o||m>=c){for(;p<o;p++){let w=hn(e[p]);if(a(w)&&!lr(w))break}let T=g().replay;E({unappliedEvents:[],replay:T&&{...T,progress:1,appliedCount:o}}),to(),hi=setTimeout(Kp,HI);return}let P=g().replay;E({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:o,startTime:t,endTime:s,currentTime:S?A??P?.currentTime??t:P?.currentTime??t,currentLabel:S?xd(S):P?.currentLabel??"",flashNodeIds:S?[...new Set(x)]:P?.flashNodeIds??[]}})},u)}});var Xp,Jp=h(()=>{"use strict";We();et();bt();Zt();me();Tt();R();de();M();Ar();bd();Id();Xp=async()=>{let e=tt(g().breadCrumb,"BOARD");if(a(e))return e;let t=await rt(process.cwd());if(a(t))return i("Unable to locate repo root");let n=ve({repoRoot:t.value});if(a(n))return n;let{modifier:o,inputString:r}=ie().commandMeta;if(to(),o==="now"){let c=Hn(n.value);if(a(c))return i(c.message);let u=cn();if(a(u))return u;let m=Qt(c.value),{fatal:p,skipped:f}=Un(m);return p.length>0?i(p.map(x=>x.message).join(", ")):($n(f),E({mode:y.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),l("Peeking now",!0))}let s;if(o==="prev"||o==="next"){let c=ia(n.value);if(a(c))return c;let u=o==="prev"?g().eventLog.at(-1):g().unappliedEvents.at(0),m=u===void 0?null:Yo(u),p=(u===void 0?null:c.value.get(u.id)??null)??(m===null?null:Mi(m));if(p===null)return i(o==="prev"?"No previous event to peek":"No next event to peek");s=o==="prev"?p:p+1}else{let c=Xn(o||r.trim());if(!c)return i("Invalid peek date");s=c.getTime()}let d=gi({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(d)?d:(E({mode:y.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:d.value.unappliedEvents,replay:null}),l("Peeking",!0))}});var Qp,Zp=h(()=>{"use strict";We();Tt();R();de();M();Ar();bd();Id();Qp=async()=>{let e=tt(g().breadCrumb,"BOARD");if(a(e))return e;let t=await rt(process.cwd());if(a(t))return i("Unable to locate repo root");let n=ve({repoRoot:t.value});if(a(n))return n;let{modifier:o,inputString:r}=ie().commandMeta,{dateInput:s,durationInput:d}=Ws(o,r);if(to(),g().syncStatus.status==="syncing")return i("Cannot replay while syncing, try again in a moment");let c=Xn(s);if(!c)return i("Invalid replay date");let u=d?Hs(d):15e3;if(u===null)return i("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=g(),f=gi({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(f))return f;let{unappliedEvents:x}=f.value;return x.length===0?(cn(),E(p),l("Nothing to replay from that point",!0)):(Yp({events:x,startTime:m,durationMs:u}),l("Replaying board history",!0))}});import{spawn as qI}from"node:child_process";var GI,eg,tg=h(()=>{"use strict";R();GI=()=>{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"]}}},eg=async e=>new Promise(t=>{let{command:n,args:o}=GI();try{let r=qI(n,o,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>t(i(`Clipboard tool not available (${n})`))),r.on("close",s=>t(s===0?l("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 Hr,ng,og=h(()=>{"use strict";R();M();tg();st();Nr();nn();Hr=async(e,t)=>{if(!e.trim())return i(`Nothing to copy: ${t} is empty`);let n=await eg(e);return a(n)?n:l(`Copied ${t} to clipboard`,null)},ng=async e=>{let{breadCrumb:t,selectedNode:n}=g(),o=Cr({breadCrumb:t,selectedNode:n}),r=o??n;if(!r)return i("Nothing selected to copy from");switch(e.modifier){case Ne.REF:return Hr(j(r.id),"ref");case Ne.TITLE:return Hr(r.title,"title");case Ne.DESCRIPTION:return o?Hr(o.props?.description??"","description"):i("No issue in scope");case Ne.TAGS:{if(!o)return i("No issue in scope");let s=In(o).map(({name:d})=>d);return Hr(s.join(", "),"tags")}case Ne.ASSIGNEES:{if(!o)return i("No issue in scope");let s=xn(o).map(({name:d})=>d);return Hr(s.join(", "),"assignees")}default:return i("Yank one of: ref, title, description, tags, assignees")}}});var rg,sg=h(()=>{"use strict";Ds();me();R();de();M();rg=async()=>{ee(""),E({mode:y.DEFAULT});let e=$e();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 Ls();return a(t)?(E({syncStatus:{msg:t.message,status:"failed"}}),t):(E({mode:y.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});var Le,Ht=h(()=>{"use strict";R();ae();Le=async()=>{let e=await Lt();return a(e)?e:l("Resolved persist root",e.value)}});import{ulid as ig}from"ulid";var zI,ag,dg=h(()=>{"use strict";xe();Se();V();R();M();Ht();zI=e=>e.action==="add.issue.comment",ag=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=oe(t.id)[n];if(!o)return i("Unable to resolve child to delete");let r=await Le();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 c=g().nodes[d];if(!c||!k(c))return i("Unable to resolve comment issue");let u=c.log?.filter(zI).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?i("You can only delete your own comments"):L([{id:ig(),action:"delete.issue.comment",payload:{id:s,issue:d},...e.value}],r.value):i("Unable to resolve comment")}return L([{id:ig(),action:"delete.node",payload:{id:o.id},...e.value}],r.value)}});import{ulid as VI}from"ulid";var cg,lg=h(()=>{"use strict";xe();Se();Jt();V();R();pt();M();Ht();cg=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=oe(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[fe];if(!r)return i("Unable to locate closed swimlane");if(o.parentNodeId===r.id)return i("Issue is already closed");let s=await Le();if(a(s))return s;let d=s.value,c=Dt(r.id,o.id,{at:"end"},e.value,d);if(a(c))return c;let u=L([{id:VI(),action:"close.issue",payload:{id:o.id,parent:r.id,rank:c.value},...e.value}],d);return a(u)?u:l("Issue closed",null)}});var vi,Ed=h(()=>{"use strict";vi=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{ulid as KI}from"ulid";var ug,mg=h(()=>{"use strict";xe();Se();Ed();Jt();V();R();te();pt();M();Ht();ug=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=oe(t.id)[n];if(!o)return i("Unable to reopen issue, no target found");let r=o.context==="TICKET"?l("Resolved ticket",o):Et(o.id,"TICKET");if(a(r))return i("Cannot reopen in this context");let s=r.value,d=g().nodes[fe];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 c=vi(s);if(!c)return i("Unable to resolve previous parent from issue history");if(c===d.id)return i("Previous parent resolves to closed swimlane");let u=g().nodes[c];if(!u)return i("Previous parent no longer exists");let m=await Le();if(a(m))return m;let p=m.value,f=Dt(u.id,s.id,{at:"end"},e.value,p);if(a(f))return f;let x=L([{id:KI(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...e.value}],p);return a(x)?x:l("Issue reopened",null)}});import{ulid as YI}from"ulid";var pg,gg=h(()=>{"use strict";xe();Se();R();de();M();Ht();pg=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=oe(t.id)[n];if(!o)return i("Missing node");if(o.readonly)return i("Cannot rename readonly node");let r=Zs();if(!r)return i("Provide a title");let s=await Le();return a(s)?s:L([{id:YI(),action:"edit.title",payload:{id:o.id,name:r},...e.value}],s.value)}});import{ulid as XI}from"ulid";var fg,hg=h(()=>{"use strict";te();xe();Se();V();R();de();M();Ht();fg=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=ie().commandMeta,o=(t||n).trim();if(!o)return i("Provide a tag");let r=I.findTagByName(o);if(!r)return i(`Tag "${o}" does not exist`);let{selectedNode:s}=g();if(!s)return i("Invalid untag target");let d=Et(s.id,"TICKET");if(a(d))return i("Unable to untag issue in this context");let c=d.value;if(!k(c))return i("Target node is not issue");if(!(c.props.tags??[]).includes(r.id))return i("Issue is not tagged with that tag");let m=await Le();return a(m)?m:L([{id:XI(),action:"remove.issue.tag",payload:{id:c.id,tag:r.id},...e.value}],m.value)}});import{ulid as Rd}from"ulid";var vg,yg=h(()=>{"use strict";te();xe();Se();V();R();de();M();Ht();vg=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=ie().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=Et(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 c=await Le();if(a(c))return c;let u=I.findTagByName(o),m=u?.id??Rd();return(d.props.tags??[]).includes(m)?i("Already tagged with that tag"):L([...u?[]:[{id:Rd(),action:"create.tag",payload:{id:m,name:o},...e.value}],{id:Rd(),action:"add.issue.tag",payload:{id:d.id,tag:m},...e.value}],c.value)}});var yi,Sd=h(()=>{"use strict";M();yi=()=>{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))n.set(r.id,r.name);return[...n.entries()].map(([r,s])=>({id:r,name:s,isExternal:!o.has(r)}))}});import{ulid as Nd}from"ulid";var bg,Ig=h(()=>{"use strict";xe();Se();V();R();te();de();M();Sd();Ht();bg=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=ie().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:c}=g(),u=oe(c.id)[d];if(!u)return i("Invalid assign target");let m=Et(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 f=await Le();if(a(f))return f;let x=yi(),S=!r&&s.toLowerCase()==="me",A,P;if(S)A=e.value.userId,P=x.find(_=>_.id===A)?.name??e.value.userName;else{let _=x.filter($=>$.name===s);if(_.length>1)return i(`"${s}" matches ${_.length} contributors (${_.map($=>$.id).join(", ")}). Assign from the GUI to choose by id.`);let B=_[0];if(!B&&!r)return i(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);A=B?.id??Nd(),P=B?.name??s}if((p.props.assignees??[]).includes(A))return i("Assignee already assigned");let w=!!g().contributors[A];return L([...w?[]:[{id:Nd(),action:"create.contributor",payload:{id:A,name:P},...e.value}],{id:Nd(),action:"add.issue.assignee",payload:{id:p.id,assignee:A},...e.value}],f.value)}});import{ulid as JI}from"ulid";var xg,Eg=h(()=>{"use strict";xe();Se();V();R();te();de();M();Sd();Ht();xg=async()=>{let e=ne();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=ie().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=Et(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 c=d.props.assignees??[],u=o.toLowerCase()==="me",m=u?c.filter(x=>x===e.value.userId):yi().filter(x=>x.name===o&&c.includes(x.id)).map(x=>x.id);if(m.length>1)return i(`"${o}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return i(u?"Issue is not assigned to you":`Issue is not assigned to "${o}"`);let f=await Le();return a(f)?f:L([{id:JI(),action:"remove.issue.assignee",payload:{id:d.id,assignee:p},...e.value}],f.value)}});import{ulid as Rg}from"ulid";var Sg,Ng=h(()=>{"use strict";xe();Se();Tt();V();R();te();M();sn();Ht();Sg=async e=>{let t=e.inputString.trim();if(!t)return i("Provide a comment");if(t.length>4e3)return i(`Cannot exceed ${4e3} characters`);let n=ne();if(a(n))return i("Unable to resolve user ID");let{breadCrumb:o,selectedNode:r}=g(),s=tt([...o,r],"TICKET");if(a(s))return i("Edit target must be an issue");let d=s.value;if(!d)return i("Invalid comment target");let c=d.context==="TICKET"?l("Resolved ticket",d):Et(d.id,"TICKET");if(a(c))return i("Unable to comment on issue in this context");let u=c.value;if(!k(u))return i("Target node is not issue");let m=await Le();return a(m)?m:L([{id:Rg(),action:"add.issue.comment",payload:{id:Rg(),issue:u.id,author:n.value.userId,md:t},...n.value}],m.value)}});import QI from"zod";var Ag,Cg=h(()=>{"use strict";Ut();me();R();de();Be();M();Ag=()=>{let e=ie().commandMeta.inputString,t=QI.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=Ve({autoSyncDebounceMs:t.data});return a(n)?n:(ut({autoSyncIntervalMs:t.data}),E({mode:y.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))}});var wg,Tg=h(()=>{"use strict";Sr();Ut();me();R();de();Be();M();wg=()=>{let e=ie().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=Au(e),n=Ve({autoSync:t});return a(n)?n:(ut({autoSync:t}),E({mode:y.DEFAULT}),l(`Auto sync set to "${e}"`,null))}});var Mg,kg=h(()=>{"use strict";Ut();me();R();de();Be();M();Mg=()=>{let e=ie().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return i("Invalid response");let n=Ve({logLevel:e});return a(n)?n:(ut({logLevel:e}),E({mode:y.DEFAULT}),l(`Auto sync set to "${e}"`,null))}});import{ulid as ZI}from"ulid";var Pg,Lg=h(()=>{"use strict";Mn();Ut();me();R();Be();M();nn();Cg();La();Tg();kg();Pg=e=>{let t=e.inputString.trim();switch(e.modifier){case he.USERNAME:{if(process.env[lt])return i(`Cannot change the configured user while ${lt} names this process`);let n=Io();if(a(n))return n;let{userId:o,preferredEditor:r,userName:s}=n.value,d=t||s,c=o||ZI();if(!d||!c)return i("Unable to resolve user name or id");let u=Ve({userName:d,userId:c,preferredEditor:r??""});return a(u)?u:(ut({userName:d,userId:c}),E({mode:y.DEFAULT}),l(`Username set to "${d}"`,null))}case he.EDITOR:{if(!t)return i("No editor provided");let n=Ve({preferredEditor:t});return a(n)?n:(ut({preferredEditor:t}),E({mode:y.DEFAULT}),l(`Editor configuration set to "${t}"`,null))}case he.VIEW:{if(t!=="wide"&&t!=="dense")return i("Invalid view mode");let n=Ve({viewMode:t});return a(n)?n:(ut({viewMode:t}),E({mode:y.DEFAULT}),l(`View set to "${t}"`,null))}case he.AUTOSYNC:return wg();case he.LOG_LEVEL:return Mg();case he.SYNC_DEBOUNCE_MS:return Ag();case he.ATTACHMENT_MAX_KB:return qu();default:return i("Unknown config command")}}});var Dg,Fg=h(()=>{"use strict";vp();it();me();R();de();M();ci();Yn();ja();nn();Sp();Tp();_p();Op();Gp();Jp();Zp();og();sg();dg();lg();mg();gg();hg();yg();Ig();Eg();Ng();Lg();Dg=[{systemOnly:!0,intent:O.Move,description:"Internal move-state command",mode:y.COMMAND_LINE,action:Fp},{intent:O.Delete,description:"Delete the currently selected node",mode:y.COMMAND_LINE,action:ag,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:y.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ie().commandMeta,n=/(!=|=)/,[o]=e.split(n);if(!o||!(d=>Ae(b.FILTER).map(c=>c.split(n)[0]).includes(d))(o))return i("Invalid filter modifier");let s={target:o,operator:"=",value:t.trim()};return Re(d=>({...d,filters:e==="clear"?[]:[...d.filters,s],mode:y.DEFAULT})),l("Filter updated",null)}},{intent:O.ViewHelp,description:"Open the help screen",mode:y.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return An({pendingNavTarget:{contextNode:e,breadCrumb:o,selectedIndex:t,selectedNode:n}}),E({mode:y.HELP}),l("Viewing help",null)}},{intent:O.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:y.COMMAND_LINE,action:cg,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:y.COMMAND_LINE,action:ug,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.Init,description:"Initialize Epiq in the current git repository",mode:y.COMMAND_LINE,action:wp},{intent:O.OpenProject,description:"Open a recently used epiq project, by number or path",mode:y.COMMAND_LINE,action:qp,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.NewItem,description:"Create a new board, swimlane, or issue",mode:y.COMMAND_LINE,action:Bp,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.Rename,description:"Rename the currently selected node",mode:y.COMMAND_LINE,action:pg,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.UntagTicket,description:"Remove a tag from the selected issue",mode:y.COMMAND_LINE,action:fg,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.TagTicket,description:"Add or create a tag on the selected issue",mode:y.COMMAND_LINE,action:vg,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.AssignUserToTicket,description:"Assign a user to the selected issue",mode:y.COMMAND_LINE,action:bg,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:y.COMMAND_LINE,action:xg,onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.Comment,description:"Add a comment to the selected issue",mode:y.COMMAND_LINE,action:async(e,t)=>Sg(t),onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.Sync,description:"Pull, commit, and push Epiq state",mode:y.COMMAND_LINE,action:rg},{intent:O.Peek,description:"View board state at another point in time",mode:y.COMMAND_LINE,action:Xp},{intent:O.Replay,description:"Replay board history forward from a point in time",mode:y.COMMAND_LINE,action:Qp},{intent:O.Export,description:"Export the current board layout to markdown",mode:y.COMMAND_LINE,action:async()=>{let e=await hp();return a(e)?e:(E({mode:y.DEFAULT}),l("Export successful",!0))}},{intent:O.Exit,description:"Exit the application",mode:y.COMMAND_LINE,action:async()=>(U.exit(),l("Exit successful",!0))},{intent:O.Edit,description:"Edit title or description",mode:y.COMMAND_LINE,action:async(e,t)=>Rp(t),onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:y.COMMAND_LINE,action:async(e,t)=>ng(t),onSuccess:()=>E({mode:y.DEFAULT})},{intent:O.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:y.COMMAND_LINE,action:(e,t)=>Pg(t)}]});var ex,Wt,Ad=h(()=>{"use strict";Fs();Ys();ja();Fg();R();de();Be();M();ex=new Set(["peek","replay","filter","view-help","yank"]),Wt=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:o,inputString:r}}=ie();if(!t)return i("No command to confirm");if(!e&&n===En.Invalid)return i("Invalid command");let s=Im(t);hm();let{readOnly:d}=g();if(d&&!ex.has(s))return Pr({status:Vt.Fail,message:"Command not available in readonly state",value:null});let c=Dg.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return Pr({status:Vt.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:r,modifier:o})}catch(m){return Pr({status:Vt.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?Pr(u):(vm({addToHistory:!e}),c.onSuccess?.(),Ie().autoSync&&vu(),u)}});var bi,Ii,_g,Bg=h(()=>{"use strict";R();me();M();kn();Ad();vd();de();bi=[{intent:F.Exit,mode:y.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:y.COMMAND_LINE}),ee("move cancel"),Wt({isForceExecutedBySystem:!0}))},{intent:F.InitMove,mode:y.DEFAULT,description:"[m] move",action:()=>(E({mode:y.COMMAND_LINE}),ee("move start"),Wt({isForceExecutedBySystem:!0}))},{intent:F.ConfirmMove,mode:y.MOVE,description:"[m] confirm move",action:()=>(E({mode:y.COMMAND_LINE}),ee("move confirm"),Wt({isForceExecutedBySystem:!0}))}],Ii=[{intent:F.MovePreviousItem,mode:y.MOVE,action:()=>Cn()?(E({mode:y.COMMAND_LINE}),ee("move previous"),Wt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:F.MoveNextItem,mode:y.MOVE,action:()=>Cn()?(E({mode:y.COMMAND_LINE}),ee("move next"),Wt({isForceExecutedBySystem:!0})):i("No pending move")}],_g=[{intent:F.MoveToNextContainer,mode:y.MOVE,action:()=>Cn()?(E({mode:y.COMMAND_LINE}),ee("move to-next"),Wt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:F.MoveToPreviousContainer,mode:y.MOVE,action:()=>Cn()?(E({mode:y.COMMAND_LINE}),ee("move to-previous"),Wt({isForceExecutedBySystem:!0})):i("No pending move")}]});var Og,Ug=h(()=>{"use strict";V();Bg();Og={[z.WORKSPACE]:[...bi,...Ii],[z.BOARD]:[...bi,...Ii],[z.SWIMLANE]:[...bi,...Ii,..._g],[z.TICKET]:[],[z.FIELD]:[],[z.FIELD_LIST]:[],[z.TEXT]:[],[z.COMMENT]:[]}});import{spawn as tx}from"node:child_process";function $g(e){let t=process.platform,r=tx(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 jg=h(()=>{"use strict"});import nx from"node:fs";import ox from"node:path";var Hg,Wg=h(()=>{"use strict";We();Eo();R();ae();jg();Hg=e=>{let t=Ue(process.cwd());if(a(t))return i("Unable to resolve project root");let n=ve({repoRoot:t.value});if(a(n))return i(n.message);let o=xo(e.hash,e.ext),r=ox.join(ps(n.value),o);return nx.existsSync(r)?($g(r),l(`Opened ${e.name}`,null)):i("Attachment file not found \u2014 run :sync to fetch it")}});var qg,Gg,zg=h(()=>{"use strict";me();R();de();M();ci();kn();it();qg=()=>{ee("");let{pendingNavTarget:e}=_o();E({mode:y.DEFAULT}),e&&U.navigate(e),An({pendingNavTarget:void 0})},Gg=[{intent:F.ExitCommandLine,mode:y.HELP,action:()=>(qg(),l("Exiting help",null))},{intent:F.Exit,mode:y.HELP,action:()=>(qg(),l("Closed help",null))},{intent:F.NavPreviousItem,mode:y.HELP,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:F.NavNextItem,mode:y.HELP,action:()=>(U.navigateToNextItem(),l("Navigating to next help item",null))},{intent:F.NavToPreviousContainer,mode:y.HELP,action:()=>(U.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:F.NavToNextContainer,mode:y.HELP,action:()=>(U.navigateToNextContainer(),l("Navigating to next help container",null))}]});var rx,Vg,Kg,Yg=h(()=>{"use strict";me();V();R();de();M();ci();kn();it();rx=e=>{E({mode:y.COMMAND_LINE});let{pendingNavTarget:t}=_o();t&&U.navigate(t),An({pendingNavTarget:void 0}),ee(`${e} `)},Vg=()=>{ee("");let{pendingNavTarget:e}=_o();e&&U.navigate(e),An({pendingNavTarget:void 0}),E({mode:y.DEFAULT})},Kg=[{intent:F.InitCommandPalette,mode:y.DEFAULT,description:"[?] command palette",action:()=>{ee("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return An({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}}),E({mode:y.PALETTE}),l("Opening command palette",null)}},{intent:F.Confirm,mode:y.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!Rc(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?(rx(t),l("Selected command",t)):l("No command selected",null)}},{intent:F.ExitCommandLine,mode:y.PALETTE,action:()=>(Vg(),l("Exiting palette",null))},{intent:F.Exit,mode:y.PALETTE,action:()=>(Vg(),l("Closed command palette",null))},{intent:F.NavPreviousItem,mode:y.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:F.NavNextItem,mode:y.PALETTE,action:()=>(U.navigateToNextItem(),l("Navigating to next item",null))},{intent:F.NavToPreviousContainer,mode:y.PALETTE,action:()=>(U.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:F.NavToNextContainer,mode:y.PALETTE,action:()=>(U.navigateToNextContainer(),l("Navigating to next container",null))}]});var Xg,Jg=h(()=>{"use strict";Yn();nn();me();R();uo();te();pt();de();M();Wg();kn();zg();Yg();it();Xg=[{intent:F.InitCommandLine,mode:y.DEFAULT,description:"[:] write command",action:()=>(E({mode:y.COMMAND_LINE}),ee(""),l("Entering command line mode",null))},...Gg,...Kg,{intent:F.AddItem,mode:y.DEFAULT,description:"[n] new...",action:()=>(E({mode:y.COMMAND_LINE}),ee(`${b.NEW} `),l("Adding new item",null))},{intent:F.Delete,mode:y.DEFAULT,description:"[d] delete",action:()=>(E({mode:y.COMMAND_LINE}),ee(`${b.DELETE} `),l("Deleting item",null))},{intent:F.Confirm,mode:y.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!ge(e?.id??"")?.length){let o=e?I.getAttachment(e.id):void 0;if(o)return Hg(o);if(e?.title===le.DESCRIPTION)return E({mode:y.COMMAND_LINE}),ee(`${b.EDIT} description `),l("Propose command",!0);if(e?.title===le.ASSIGNEES)return E({mode:y.COMMAND_LINE}),ee(`${b.ASSIGN} `),l("Propose command",!0);if(e?.title===le.TAGS)return E({mode:y.COMMAND_LINE}),ee(`${b.TAG} `),l("Propose command",!0);if(t.title===le.DESCRIPTION&&e?.context==="TEXT")return E({mode:y.COMMAND_LINE}),ee(`${b.EDIT} description `),l("Propose command",!0)}return U.enterChildNode(),l("Entering context",null)}},{intent:F.Yank,mode:y.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=g(),t=e?.title===le.DESCRIPTION?Ne.DESCRIPTION:e?.title===le.TAGS?Ne.TAGS:e?.title===le.ASSIGNEES?Ne.ASSIGNEES:Ne.REF,o=Ae(b.YANK).includes(t)?t:Ne.REF;return E({mode:y.COMMAND_LINE}),ee(`${b.YANK} ${o}`),l("Propose command",!0)}},{intent:F.EditTitle,mode:y.DEFAULT,description:"[r] rename title",action:()=>(E({mode:y.COMMAND_LINE}),ee(`${b.EDIT} title ${g().selectedNode?.title}`),l("Exiting context",null))},{intent:F.EditDescription,mode:y.DEFAULT,description:"[e] edit desc",action:()=>(E({mode:y.COMMAND_LINE}),ee(`${b.EDIT} description `),l("Exiting context",null))},{intent:F.Exit,mode:y.DEFAULT,description:"[q] exit context",action:()=>(U.enterParentNode(),l("Exiting context",null))},{intent:F.NavPreviousItem,mode:y.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:F.NavNextItem,mode:y.DEFAULT,action:()=>(U.navigateToNextItem(),l("Navigating to next item",null))},{intent:F.NavToPreviousContainer,mode:y.DEFAULT,action:()=>(U.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:F.NavToNextContainer,mode:y.DEFAULT,action:()=>(U.navigateToNextContainer(),l("Navigating to next container",null))}]});var sx,ix,Qg,Zg=h(()=>{"use strict";de();sx=500,ix=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Qg=e=>{let t=ix(e);t&&Qs(n=>(n+t).slice(0,sx))}});var ax,dx,ef,tf=h(()=>{"use strict";Zg();me();R();de();M();kn();Ad();ax=[y.COMMAND_LINE,y.PALETTE],dx=e=>[{intent:F.MoveCursorLeft,mode:e,action:()=>(Ua(-1),l("Moving cursor left",null))},{intent:F.MoveCursorRight,mode:e,action:()=>(Ua(1),l("Moving cursor right",null))},{intent:F.MoveCursorLeftOfWord,mode:e,action:()=>($a("left"),l("Moving cursor left of word",null))},{intent:F.MoveCursorRightOfWord,mode:e,action:()=>($a("right"),l("Moving cursor right of word",null))},{intent:F.AutoCompleteCommand,mode:e,action:()=>(Qs((t,{remainder:n})=>{let o=n?t+n:t,r="";return o==="edit title "&&(r=g().selectedNode?.title??""),o+r}),l("Auto-completing command",null))},{intent:F.CaptureInput,mode:e,action:(t,{sequence:n})=>(Qg(n??""),l("Capturing input",null))},{intent:F.EraseInput,mode:e,action:()=>(gm(),l("Erasing input",null))},{intent:F.EraseInputWord,mode:e,action:()=>(fm(),l("Erasing input word",null))}],ef=[{intent:F.Confirm,mode:y.COMMAND_LINE,action:()=>(Wt(),l("Executing command",null))},{intent:F.ViewHelp,mode:y.DEFAULT,action:()=>(E({mode:y.HELP}),l("Viewing help",null))},...ax.flatMap(dx),{intent:F.ExitCommandLine,mode:y.COMMAND_LINE,action:()=>(E({mode:y.DEFAULT}),l("Exiting command line",null))},{intent:F.GetLastCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(ym(),l("Getting last command from history",null))},{intent:F.GetNextCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(bm(),l("Getting next command from history",null))}]});var cx,nf,of,rf=h(()=>{"use strict";cx=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},nf=({keys:e})=>e.length===1?0:1,of=(e,t)=>{let n=new Set;for(let o of e)o.mode!==t||!o.description||n.add(o.description);return[...n].map(cx).filter(o=>o!==null).sort((o,r)=>nf(o)-nf(r))}});function sf(e,t,n){let o=t[e];if(!o)return i("buildBreadCrumb(): current node not found");let r=[],s=new Set,d=o;for(;d&&!s.has(d.id)&&(r.push(d),s.add(d.id),!(d.id===n||!d.parentNodeId));)d=t[d.parentNodeId];let c=r[r.length-1];return!c||c.id!==n?i("buildBreadCrumb(): node is not connected to root"):(r.reverse(),l("Breadcrumb built",r))}var af=h(()=>{"use strict";R()});var df,cf=h(()=>{"use strict";df=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 lx}from"react";function Md(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 c=r[t];if(!c)return i("Unable to derive state, contextNode not found");let u=sf(t,r,o);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,f=[...Xg,...Og[p]??[],...ef],x=of(f,n),S=df(f),A=mx(r,s),P=A[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:x,availableActions:f,actionIndex:S,selectedNode:P,renderedChildrenIndex:A})}function ur(e){Cd=e;let t=Ue(process.cwd()),n=!1;if(!a(t)){let s=Kt(t.value);if(a(s))return i(s.message);n=!0}let o={readOnly:!1,filters:[],tags:{},contributors:{},mode:y.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=Md(o);return a(r)?r:(qt=r.value,Td(),l("State initialized",null))}function Re(e){let t=g(),n=e(t);if(no)return Wr=n,qt={...t,...n},l("State updated",null);let o=Md(n);return a(o)?i(o.message??"Unable to update state"):(qt=o.value,Td(),l("State updated",null))}function dl(e){if(no)return l("Joined batch",e());no=!0,Wr=null;let t=()=>{let n=Wr;if(no=!1,Wr=null,n===null)return null;let o=Md(n);return a(o)?i(o.message??"Unable to update state"):(qt=o.value,Td(),l("State updated",null))};try{let n=e(),o=t();return o&&a(o)?i(o.message):l("State updated",n)}finally{no&&t()}}function oo(e,t,n){if(!no)return Re(d=>({...d,[e]:{...d[e]??{},[t]:n}}));let o=g(),r=o[e]??{};r[t]=n;let s={...o,[e]:r};return Wr=s,qt={...o,...s},l("State updated",null)}var qt,Cd,wd,Td,ux,g,$e,no,Wr,Ul,E,Je,mx,oe,cn,vt,M=h(()=>{"use strict";Ug();Jg();tf();rf();Yt();me();R();ae();ca();af();cf();wd=new Set,Td=()=>{for(let e of wd)e()},ux=e=>(wd.add(e),()=>wd.delete(e));g=()=>{if(!qt)throw new Error("State not initialized. Call initWorkspaceState() first.");return qt},$e=()=>qt?l("Retrieved state",qt):i("State not initialized. Call initWorkspaceState() first.");no=!1,Wr=null;Ul=()=>no,E=e=>Re(t=>({...t,...e}));Je=()=>lx(ux,g,g),mx=Fl,oe=e=>g()?.renderedChildrenIndex[e]??[],cn=()=>Cd?ur(Cd):i("Cannot reset state: no initial workspace found"),vt=()=>qt!==void 0});var Et,px,wn,I,te=h(()=>{"use strict";Tt();V();R();M();pt();Et=(e,t)=>{let{nodes:n}=g(),o=n[e];if(!o)return i("Node not found");if(o.context===t)return l("Resolved ancestor node",o);let r=new Set([o.id]),s=o.parentNodeId?n[o.parentNodeId]:void 0;for(;s&&!r.has(s.id);){if(s.context===t)return l("Resolved ancestor node",s);r.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return i(`No ancestor found for context: ${t}`)},px=(e,t)=>{let{nodes:n}=g(),o=new Set,r=n[e];for(;r?.parentNodeId&&!o.has(r.id);){if(r.parentNodeId===t)return!0;o.add(r.id),r=n[r.parentNodeId]}return!1},wn=(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=Re(s=>({...s,contributors:{...s.contributors,[e]:o}}));return a(r)?i("Unable to link contributor to user"):l("Linked contributor to user",o)},deleteNode(e){Re(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=oo("comments",e.id,{...e,deleted:!1});return a(n)?i("Unable to create comment"):l("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=oo("comments",e,r);return a(s)?i("Unable to edit comment"):l("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=oo("comments",e,n);return a(o)?i("Unable to delete comment"):l("Deleted comment",n)},getComment(e){return g().comments?.[e]},getCommentsByIssue(e){return Object.values(g().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(g().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},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=Re(o=>({...o,attachments:{...o.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?i("Unable to create attachment"):l("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=Re(r=>({...r,attachments:{...r.attachments??{},[e]:n}}));return a(o)?i("Unable to delete attachment"):l("Deleted attachment",n)},getAttachment(e){return g().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(g().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(g().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=g(),o=n[e];if(!o)return i("Edit target node not found");let r=wn(o,"edit");if(r)return r;let s={...o,props:{...o.props,description:t}};return this.updateNode(s),l("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return i("Rename target node not found");let o=wn(n,"rename");if(o)return o;let r={...n,title:t};return this.updateNode(r),l("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 ge(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=wn(r,"move");if(d)return d;if(px(t,e))return i("Cannot move node into its own descendant");let c={...r,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},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=wn(r,"delete");if(s)return s;let d=new Set,c=m=>{let p=t[m];if(!(!p||d.has(m))){d.add(m);for(let f of ge(p.id))c(f.id)}};c(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}),l("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:es,tombstoned:!0},o=Re(r=>({...r,contributors:{...r.contributors,[e]:n}}));return a(o)?i("Unable to remove contributor"):l("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return i("Contributor not found");if(n.tombstoned)return i("Cannot rename a removed contributor");let o={...n,name:t},r=Re(s=>({...s,contributors:{...s.contributors,[e]:o}}));return a(r)?i("Unable to rename contributor"):l("Renamed contributor",o)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return i("Contributor not found");let o={...n,name:t,tombstoned:!1},r=Re(s=>({...s,contributors:{...s.contributors,[e]:o}}));return a(r)?i("Unable to restore contributor"):l("Restored contributor",o)},createContributor(e){let t=Re(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?i("Unable to create contributor"):l("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=wn(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),l("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=wn(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 l("Issue is not assigned to that contributor",{assignee:t});let d={...o,props:{...o.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(d),l("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=wn(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),l("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(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=wn(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 l("Issue is not tagged with that tag",{tag:t});let d={...o,props:{...o.props,tags:s.filter(c=>c!==t)}};return this.updateNode(d),l("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return i("Tag not found");let n={...t,tombstoned:!0},o=Re(r=>({...r,tags:{...r.tags,[e]:n}}));return a(o)?i("Unable to delete tag"):l("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return i("Tag not found");let o={...n,name:t,tombstoned:!1},r=Re(s=>({...s,tags:{...s.tags,[e]:o}}));return a(r)?i("Unable to restore tag"):l("Restored tag",o)},createTag(e){let t=Re(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?i("Could not create tag"):l("Tag created",e)},createNode(e){let t=oo("nodes",e.id,e);return a(t)?i("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return i("Failed to locate node");let n={...t,readonly:!0},o=oo("nodes",e,n);return a(o)?i(o.message):l("Locked node",n)},updateNode(e){let t=oo("nodes",e.id,e);return a(t)?t:l("Updated node",e)},getContributor(e){return g().contributors[e]},getTag(e){let t=g().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return g().tags[e]},getTags(){return Object.values(g().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return g().nodes[e]},getSiblings(e){return ge(e)}}});import Tn from"chalk";import lf from"string-width";var gx,fx,kd,hx,vx,uf,mf,yx,bx,Ix,xx,Ex,xd,pf,jr=h(()=>{"use strict";et();te();M();dt();ii();gx=(e,t)=>e+" ".repeat(Math.max(0,t-lf(e))),fx=(e,t)=>" ".repeat(Math.max(0,t-lf(e)))+e,kd=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","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed 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`),hx=(e,t)=>t?e<t?"up":e>t?"down":null:null,vx=(e,t)=>{let n=I.getNode(e.payload.parent),o=n?Tn.dim.bgBlack(` ${n.title} `):"unknown",r=t.at(-1);if(r&&"parent"in r&&"rank"in r&&r.parent===e.payload.parent){let s=hx(e.payload.rank,r.rank);if(s)return`Moved ${s} in ${o}`}return`Moved issue to ${o}`},uf=e=>`${Math.max(1,Math.round(e/1024))} KB`,mf=e=>I.getAttachment(e)?.name??"",yx=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Tn.bgHex(Ce(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Tn.bgHex(Ce(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=g().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Tn.hex(Ce(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Tn.hex(Ce(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Tn.dim(`(${uf(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=mf(e.payload.id);return t?`"${t}"`:""}default:return""}},bx=e=>{let t=Lo(Ze(e));return Tn.gray(fx(t,8))},Ix=12,xx=e=>gx(`${e}`,Ix),Ex=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"tombstone.tag":{let t=g().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.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}" (${uf(e.payload.bytes)})`;case"delete.issue.attachment":{let t=mf(e.payload.id);return t?`"${t}"`:""}default:return""}},xd=e=>[kd(e.action),Ex(e)].filter(Boolean).join(" "),pf=(e,t)=>{let n=bx(e.id),o=xx(e.userName),r=Tn.dim("\u203A"),s=e.action==="move.node"?vx(e,t):[kd(e.action),yx(e)].filter(Boolean).join(" ");return`${o} ${n} ${r} ${s}`}});var ff={};Jr(ff,{areVirtualNodesEnabled:()=>vs,createOrUpdateVirtualField:()=>qr,createOrUpdateVirtualFieldList:()=>Pd,materializeTicketVirtualNodes:()=>hs,materializeVirtualNodes:()=>kx,setVirtualNodesEnabled:()=>Mx});var Rx,Sx,Nx,Ax,Cx,wx,qr,Pd,hs,Tx,gf,Mx,vs,kx,Xi=h(()=>{"use strict";jr();V();R();uo();te();On();M();ao();Ro();Rx=e=>Me(e,"comments"),Sx=e=>Me(e,"description"),Nx=e=>Me(e,"assignees"),Ax=e=>Me(e,"tags"),Cx=e=>Me(e,"history"),wx=e=>Me(e,"attachments"),qr=({id:e,name:t,parentNodeId:n,rank:o,value:r,readonly:s=!1,childRenderAxis:d="horizontal"})=>{let c=I.getNode(e);if(!c){let p=I.createNode({...Te.field({id:e,name:t,parentNodeId:n,rank:o,props:{value:r},isVirtual:!0}),readonly:s,childRenderAxis:d});return a(p)?p:l("Virtual field created",void 0)}if(!nt(c))return i(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==o||c.props.value!==r||c.readonly!==s||c.childRenderAxis!==d))return l("Virtual field unchanged",void 0);let m=I.updateNode({...c,title:t,parentNodeId:n,rank:o,props:{...c.props,value:r},readonly:s,childRenderAxis:d});return a(m)?m:l("Virtual field updated",void 0)},Pd=({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({...Te.fieldList({id:e,name:t,parentNodeId:n,rank:o,isVirtual:!0}),readonly:r,childRenderAxis:s});return a(m)?m:l("Virtual field list created",void 0)}if(!Xo(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 l("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:l("Virtual field list updated",void 0)},hs=e=>{let t=mt(Mt/4n),n=mt(Mt/2n),o=mt(Mt*3n/4n),r=mt(Mt*7n/8n),s=mt(Mt*15n/16n),d=mt(Mt*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 c=qr({id:Sx(e.id),name:le.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(c))return c;let u=Pd({id:Nx(e.id),name:le.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(u))return u;let m=Pd({id:Ax(e.id),name:le.TAGS,parentNodeId:e.id,rank:o.value,readonly:!0});if(a(m))return m;let p=qr({id:Rx(e.id),name:le.COMMENTS,parentNodeId:e.id,rank:r.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(p))return p;let f=qr({id:wx(e.id),name:le.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(f))return f;let x=qr({id:Cx(e.id),name:le.HISTORY,parentNodeId:e.id,rank:d.value,value:Tx(e),readonly:!0,childRenderAxis:"vertical"});return a(x)?x:l("Ticket virtual nodes materialized",void 0)},Tx=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=>pf(o,n.get(o.action)??[])).join(`
|
|
75
|
+
`)},gf=!0,Mx=e=>{gf=e},vs=()=>gf,kx=()=>{let{nodes:e}=g();for(let t of Object.values(e)){if(!k(t))continue;let n=hs(t);if(a(n))return n}return l("Virtual nodes materialized",void 0)}});var Px,hf,Ld=h(()=>{"use strict";et();bt();mr();jr();R();dt();Px=e=>{let t=new Map,n=new Set,o=r=>{let s=new Set,d=r;for(;d&&!s.has(d);){if(n.has(d))return d;s.add(d),d=t.get(d)}return null};return e.map(r=>{let s=r.payload,d=s?.id;if(!d)return null;r.action==="add.board"&&n.add(d);let c=s.parent??s.issue;return c&&t.set(d,c),n.has(d)?d:o(d)})},hf=(e,t)=>{let n=Px(e);return e.filter((o,r)=>n[r]===t)}});var Lx,vf,yf,Gr,zr=h(()=>{"use strict";We();Nt();st();ld();bt();Zt();R();Yt();zs();ae();M();Ld();Lx=null,vf=Promise.resolve(),yf=e=>{let t=vf.then(e,e);return vf=t.then(()=>{},()=>{}),t},Gr=()=>{if(!vt())return{mode:"live",asOfTime:null};let{timeMode:e}=g();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:Lx}}});import Dx from"node:fs";var ro,xi,K,J,Y,ln=h(()=>{"use strict";We();Nt();co();br();Ut();zn();mr();ae();bt();R();M();ht();zr();ro=e=>{let t=Ue(e??process.cwd());return a(t)?i(t.message):l("Resolved Epiq repo root",t.value)},xi=null,K=async(e,t)=>{let n=ro(e);if(a(n))return n;let o=ve({repoRoot:n.value});if(a(o))return i(o.message);let r=kt(n.value);if(a(r))return i(r.message);if(!(xi!==null&&xi.repoRoot===n.value&&xi.stateBranchRoot===o.value&&Dx.existsSync(Ln(o.value)))){let p=await pa({repoRoot:n.value,stateBranchName:r.value});if(a(p))return i(p.message);let f=await Kn({repoRoot:n.value,stateBranchRoot:o.value,stateBranchName:r.value});if(a(f))return i(f.message);xi={repoRoot:n.value,stateBranchRoot:o.value}}if(t?.pull??!1){let p=await q({cwd:o.value,args:["pull","--ff-only"]});a(p)&&X.info(3,p.message)}let d={repoRoot:n.value,stateBranchRoot:o.value},c=jn(o.value);if(ul(o.value)===c&&vt()&&Gr().mode==="live")return l("Booted Epiq state, unchanged",d);let u=yt(o.value);if(a(u))return i(u.message);let m=_t(u.value.events,u.value.unreadable);return a(m)?i(m.message):(ml(o.value,c),l("Booted Epiq state",d))},J=()=>{let e=wr();return a(e)?i(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):i("Unable to retrieve user name"):i("Unable to retrieve user id")},Y=()=>{let e=$e();return a(e)?i(e.message):e}});var Bo,bf,Oo,Dd=h(()=>{"use strict";et();te();dt();Bo=e=>(e.props.tags??[]).map(t=>I.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Ce(t.name)})),bf=e=>I.getCommentsByIssue(e).sort((t,n)=>t.id<n.id?-1:t.id>n.id?1:0).map(t=>({id:t.id,author:I.getContributor(t.authorId)?.name??t.authorName??"Unknown",createdAt:Ze(t.id),body:t.md})),Oo=e=>(e.props.assignees??[]).map(t=>I.getContributor(t)).filter(t=>t!=null).map(({id:t,name:n})=>({id:t,name:n,color:Ce(n)}))});import Fx from"node:fs";import _x from"node:path";import{ulid as If}from"ulid";var Bx,xf,Fd,_d=h(()=>{"use strict";Ut();xe();V();R();ot();Eo();ln();Bx=e=>{if(e.filePath)try{return l("Read attachment file",{data:Fx.readFileSync(e.filePath),name:e.name??_x.basename(e.filePath)})}catch(t){return i(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?l("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):i("Provide either filePath or dataBase64")},xf=()=>{let e=wr();return a(e)?rn:e.value.attachmentMaxKb??rn},Fd=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.nodes[e.issueId];if(!r)return i("Issue not found");if(!k(r))return i("Attachment target must be an issue");if(r.readonly)return i("Cannot attach to readonly issue");let s=Bx(e);if(a(s))return s;let d=Wu(t.value.stateBranchRoot,s.value.data,xf());if(a(d))return d;let c=pe(s.value.name).trim()||"image",u=If(),m={id:If(),...n.value,action:"add.issue.attachment",payload:{id:u,issue:e.issueId,author:n.value.userId,hash:d.value.hash,ext:d.value.ext,name:c,bytes:d.value.bytes}},p=L([m],t.value.stateBranchRoot);if(a(p))return i(p.message);let f=xo(d.value.hash,d.value.ext);return l("Added issue attachment",{id:u,issueId:e.issueId,fileName:f,bytes:d.value.bytes,markdown:ka(c,f)})}});var Bd,k1,Od,Ef=h(()=>{"use strict";Ut();et();Jt();V();R();te();vo();dt();st();ot();Eo();ht();zr();ln();Dd();_d();Ps();Se();fr();Bd=async(e={})=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Y();return a(n)?n:l("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})},k1=365*24*60*60*1e3,Od=async(e={})=>{mo();let t=ro(e.repoRoot);if(a(t))return i("Sync failed");let n=J();if(a(n))return n;let o=await ks({cwd:t.value,ownEventFileName:qn(n.value)});return a(o)?(la(o.message),o):(Vn(),l("Synced",o.value))}});var Vr,Uo,Ud,Kr,$d=h(()=>{"use strict";V();R();st();ln();Vr=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?l("Resolved targets",t):i("Provide issueId or issueIds")},Uo=(e,t)=>{let n=t.done.length,o=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?l(o,t):i(`${o}: ${t.failed.map(r=>`${r.ref} ${r.reason}`).join("; ")}`)},Ud=(e,t)=>{let n={done:[],failed:[]};for(let o of e){let r=t(o);a(r)?n.failed.push({id:o,ref:j(o),reason:r.message}):n.done.push({id:o,ref:j(o)})}return n},Kr=e=>{let t=Y();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?i("Issue not found"):k(n)?n.readonly?i("Issue is readonly"):l("Found issue",n):i("Target must be an issue")}});import{ulid as Rt}from"ulid";async function Hd(e){let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Y();if(a(n))return n;let o=n.value.nodes,r=e.query?.trim().toLowerCase(),s=Object.values(o).filter(k).filter(c=>!c.isDeleted).filter(c=>e.includeClosed||c.parentNodeId!==fe).filter(c=>e.boardId?(c.parentNodeId?o[c.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(c=>!e.swimlaneId||c.parentNodeId===e.swimlaneId).filter(c=>!e.tag||Bo(c).some(u=>Rf(u.name,e.tag))).filter(c=>!e.assignee||Oo(c).some(u=>Rf(u.name,e.assignee))).filter(c=>!r||c.title.toLowerCase().includes(r)||(c.props.description??"").toLowerCase().includes(r)),d=c=>pe((c.parentNodeId?o[c.parentNodeId]?.title:void 0)??"");return e.brief?l("Listed issues",s.map(c=>({id:c.id,ref:j(c.id),title:pe(c.title),swimlane:d(c),tags:Bo(c).map(u=>u.name),assignees:Oo(c).map(u=>u.name)}))):l("Listed issues",s.map(c=>({id:c.id,ref:j(c.id),title:pe(c.title),description:c.props.description??"",createdAt:Ze(c.id),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===fe,readonly:!!c.readonly,tags:Bo(c),assignees:Oo(c)})))}async function qd(e){let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Vr(e);if(a(o))return o;let r=s=>Ox(s,n.value,t.value.stateBranchRoot);return e.issueIds?Uo("Closed",Ud(o.value,r)):r(o.value[0])}async function zd(e){let t=ro(e.repoRoot);if(a(t))return t;let n=J();if(a(n))return n;let o=ve({repoRoot:t.value});if(a(o))return o;let r=yt(o.value);if(a(r))return r;let s=_t(r.value.events,r.value.unreadable);if(a(s))return s;let d=Vr(e);if(a(d))return d;let c=u=>Ux(u,e,n.value,o.value);return e.issueIds?Uo("Moved",Ud(d.value,c)):c(d.value[0])}var jd,Rf,Wd,Ox,Gd,Ux,Vd,Kd,Sf=h(()=>{"use strict";We();yd();et();zn();bt();xe();Ed();Jt();V();R();te();pt();jr();dt();sn();st();ot();ln();Dd();$d();jd=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Y();if(a(n))return n;let o=e.idOrRef.trim();if(!o)return i("Provide an issue id or ref");let r=Object.values(n.value.nodes).filter(k).filter(u=>!u.isDeleted),s=r.find(u=>u.id===o),d=s?[s]:r.filter(u=>dr(u.id,o));if(d.length===0)return i(`No issue matches "${o}"`);if(d.length>1)return i(`"${o}" matches ${d.length} issues: ${d.map(u=>`${j(u.id)} (${pe(u.title)})`).join(", ")}. Use a full ref or id.`);let c=d[0];return l("Found issue",{id:c.id,ref:j(c.id),title:pe(c.title),description:c.props.description??"",createdAt:Ze(c.id),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===fe,readonly:!!c.readonly,tags:Bo(c),assignees:Oo(c),comments:bf(c.id)})},Rf=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();Wd=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=pe(e.title);if(!r)return i("Issue title cannot be empty");let s=e.description??"",d=Ke("Issue title",r,300)??Ke("Issue description",s,2e4);if(d)return i(d);if((e.tagNames?.length??0)>20)return i(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return i(`Cannot set more than ${20} assignees at once`);let c=bn(e.parentId,n.value,t.value.stateBranchRoot);if(a(c))return c;let u=mi({name:r,parent:e.parentId,user:n.value,rank:c.value});if(a(u))return u;let m=[...u.value],p=m.find(A=>A.action==="add.issue")?.payload.id;if(!p)return i("Unable to determine created issue id");s&&m.push({id:Rt(),...n.value,action:"edit.description",payload:{id:p,md:s}});let f=[];for(let A of e.tagNames??[]){let P=pe(A).trim();if(!P||f.some(B=>B.name===P))continue;let T=Ke("Tag name",P,60);if(T)return i(T);let w=I.findTagByName(P),_=w?.id??Rt();w||m.push({id:Rt(),...n.value,action:"create.tag",payload:{id:_,name:P}}),m.push({id:Rt(),...n.value,action:"add.issue.tag",payload:{id:p,tag:_}}),f.push({id:_,name:P})}let x=[];for(let A of e.assigneeNames??[]){let P=pe(A).trim();if(!P||x.some(B=>B.name===P))continue;let T=Ke("Assignee name",P,80);if(T)return i(T);let w=Object.values(o.value.contributors).find(B=>B.name===P),_=w?.id??Rt();w||m.push({id:Rt(),...n.value,action:"create.contributor",payload:{id:_,name:P}}),m.push({id:Rt(),...n.value,action:"add.issue.assignee",payload:{id:p,assignee:_}}),x.push({id:_,name:P})}let S=L(m,t.value.stateBranchRoot);return a(S)?i(S.message):l("Created issue",{id:p,ref:j(p),title:r,parentId:e.parentId,description:s,tags:f,assignees:x})},Ox=(e,t,n)=>{let o=Kr(e);if(a(o))return o;let r=Dt(fe,e,{at:"end"},t,n);if(a(r))return r;let s={id:Rt(),...t,action:"close.issue",payload:{id:e,parent:fe,rank:r.value}},d=L([s],n);return a(d)?i(d.message):l("Closed issue",{id:e,ref:j(e)})};Gd=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();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!==fe)return i("Issue is not closed");let s=vi(r);if(!s)return i("Unable to resolve previous parent from issue history");if(s===fe)return i("Previous parent resolves to closed swimlane");let d=o.value.nodes[s];if(!d)return i("Previous parent no longer exists");let c=Dt(d.id,r.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(c))return c;let u={id:Rt(),...n.value,action:"reopen.issue",payload:{id:r.id,parent:d.id,rank:c.value}},m=L([u],t.value.stateBranchRoot);return a(m)?i(m.message):l("Reopened issue",{id:r.id,ref:j(r.id),parentId:d.id})},Ux=(e,t,n,o)=>{let r=Kr(e);if(a(r))return r;let s=Dt(t.parentId,e,t.position??{at:"end"},n,o);if(a(s))return s;let d={id:Rt(),...n,action:"move.node",payload:{id:e,parent:t.parentId,rank:s.value}},c=L([d],o);return a(c)?i(c.message):l("Moved issue",{id:e,ref:j(e),parentId:t.parentId})};Vd=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();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=Ke("Issue description",e.description,2e4);if(s)return i(s);let d=r.props.description??"";if(d===e.description)return l("No changes made",{id:e.issueId,ref:j(e.issueId),description:d});let c={id:Rt(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},u=L([c],t.value.stateBranchRoot);return a(u)?i(u.message):l("Edited issue description",{id:e.issueId,ref:j(e.issueId),description:e.description})},Kd=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();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=pe(e.title);if(!s.trim())return i("Issue title cannot be empty");let d=Ke("Issue title",s,300);if(d)return i(d);if(r.title===s)return l("No changes made",{id:e.issueId,ref:j(e.issueId),title:s});let c={id:Rt(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},u=L([c],t.value.stateBranchRoot);return a(u)?i(u.message):l("Edited issue title",{id:e.issueId,ref:j(e.issueId),title:s})}});import{ulid as Xr}from"ulid";var Yd,Xd,Jd,Qd,Zd,ec,Nf=h(()=>{"use strict";We();zn();bt();xe();Jt();V();R();pt();sn();st();ot();zr();ln();Yd=async(e={})=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Y();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:j(r.id),title:r.title,parentId:r.parentNodeId,readonly:!!r.readonly}));return l("Listed boards",o)},Xd=async(e={})=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=Y();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===fe,readonly:!!r.readonly}));return l("Listed swimlanes",o)},Jd=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.nodes[e.boardId];if(!r)return i("Board not found");if(!Jo(r))return i("Target parent must be a board");if(r.readonly)return i("Cannot add a swimlane to a readonly board");if(Gr().mode!=="live")return i("Cannot add a swimlane while time travelling");let s=pe(e.title);if(!s.trim())return i("Swimlane title cannot be empty");let d=Ke("Swimlane title",s,300);if(d)return i(d);let c=bn(e.boardId,n.value,t.value.stateBranchRoot);if(a(c))return c;let u=Xr(),m={id:Xr(),...n.value,action:"add.swimlane",payload:{id:u,name:s,parent:e.boardId,rank:c.value}},p=L([m],t.value.stateBranchRoot);return a(p)?i(p.message):l("Created swimlane",{id:u,ref:j(u),title:s,boardId:e.boardId})},Qd=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.nodes[e.swimlaneId];if(!r)return i("Swimlane not found");if(!pn(r))return i("Edit target must be a swimlane");if(r.readonly)return i("Cannot edit readonly swimlane");let s=pe(e.title);if(!s.trim())return i("Swimlane title cannot be empty");let d=Ke("Swimlane title",s,300);if(d)return i(d);if(r.title===s)return l("No changes made",{id:e.swimlaneId,ref:j(e.swimlaneId),title:s});let c={id:Xr(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:s}},u=L([c],t.value.stateBranchRoot);return a(u)?i(u.message):l("Edited swimlane title",{id:e.swimlaneId,ref:j(e.swimlaneId),title:s})},Zd=async e=>{let t=ro(e.repoRoot);if(a(t))return t;let n=J();if(a(n))return n;let o=ve({repoRoot:t.value});if(a(o))return o;let r=yt(o.value);if(a(r))return r;let s=_t(r.value.events,r.value.unreadable);if(a(s))return s;let d=Dt(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,o.value);if(a(d))return d;let c={id:Xr(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:d.value}},u=L([c],o.value);return a(u)?i(u.message):l("Moved swimlane",{id:e.swimlaneId,ref:j(e.swimlaneId),boardId:e.boardId})},ec=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.nodes[e.swimlaneId];if(!r)return i("Swimlane not found");if(!pn(r))return i("Delete target must be a swimlane");let s={id:Xr(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},d=L([s],t.value.stateBranchRoot);return a(d)?i(d.message):l("Deleted swimlane",{id:e.swimlaneId,ref:j(e.swimlaneId)})}});import{ulid as Ho}from"ulid";async function tc(e){let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Vr(e);if(a(o))return o;let r=pe(e.tagName).trim();if(!r)return i("Tag name cannot be empty");let s=Ke("Tag name",r,60);if(s)return i(s);let d={done:[],failed:[]};for(let S of o.value){let A=Kr(S);a(A)?d.failed.push({id:S,ref:j(S),reason:A.message}):d.done.push({id:S,ref:j(S)})}if(!e.issueIds&&d.failed[0])return i(d.failed[0].reason);if(d.done.length===0)return i(Uo("Tagged",d).message);let c=I.findTagByName(r),u=c?.id??Ho(),m=[...c?[]:[{id:Ho(),...n.value,action:"create.tag",payload:{id:u,name:r}}],...d.done.map(({id:S})=>({id:Ho(),...n.value,action:"add.issue.tag",payload:{id:S,tag:u}}))],p=L(m,t.value.stateBranchRoot);if(a(p))return i(p.message);let f={id:u,name:r};if(!e.issueIds)return l("Added issue tag",{...d.done[0],tag:f});let x=Uo("Tagged",d);return a(x)?x:l(x.message,{...x.value,tag:f})}var nc,oc,rc,Af=h(()=>{"use strict";xe();V();R();te();sn();st();ot();ln();$d();nc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.tags[e.tagId];if(!r)return i("Tag not found");if(r.tombstoned)return i("Tag is already deleted");let s=[{id:Ho(),...n.value,action:"tombstone.tag",payload:{id:e.tagId}}],d=L(s,t.value.stateBranchRoot);return a(d)?i(d.message):l("Deleted tag",{id:r.id,name:r.name})},oc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.tags[e.tagId];if(!r)return i("Tag not found");if(!r.tombstoned)return i("Tag is not deleted");if(I.findTagByName(r.name))return i(`Cannot restore: another tag is already named "${r.name}"`);let s=[{id:Ho(),...n.value,action:"restore.tag",payload:{id:e.tagId,name:r.name}}],d=L(s,t.value.stateBranchRoot);return a(d)?i(d.message):l("Restored tag",{id:r.id,name:r.name})},rc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();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:Ho(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},d=L([s],t.value.stateBranchRoot);return a(d)?i(d.message):l("Removed issue tag",{id:e.issueId,ref:j(e.issueId),tagId:e.tagId})}});import{ulid as un}from"ulid";var $x,Cf,sc,wf,ic,ac,jx,dc,cc,lc,Tf=h(()=>{"use strict";R();M();Tt();Mn();bt();xe();Ld();V();dt();sn();st();ot();ln();$x=()=>{let e=$e(),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},Cf=(e,t)=>{let n=new Map(e);for(let o of Object.values(t))n.set(o.id,o.name);return n},sc=async e=>{let t=Ti(e.name,"name");if(a(t))return i(t.message);let n=await K(e.repoRoot,{pull:!1});if(a(n))return n;let o=J();if(a(o))return o;let r=Y();if(a(r))return r;let s=o.value,d=!!r.value.contributors[s.userId];if(!d){let c=L([{id:un(),...s,action:"create.contributor",payload:{id:s.userId,name:s.userName}}],n.value.stateBranchRoot);if(a(c))return i(c.message)}return l(`Assumed ${s.userName}`,{...s,registered:!d})},wf=async(e,t)=>{let n=ra(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}},ic=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();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],w=T?void 0:await wf(t.value.stateBranchRoot,s);if(!T&&!w)return i("Unknown assignee id");let _=T??w,B=[...T?[]:[{id:un(),...n.value,action:"create.contributor",payload:{id:_.id,name:_.name}}],{id:un(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:_.id}}],$=L(B,t.value.stateBranchRoot);return a($)?i($.message):l("Added issue assignee",{id:e.issueId,ref:j(e.issueId),assignee:{id:_.id,name:_.name}})}let d=pe(e.assigneeName??"").trim();if(!d)return i("Provide assigneeId, self or assigneeName");let c=Ke("Assignee name",d,80);if(c)return i(c);let m=[...Cf($x(),o.value.contributors).entries()].filter(([,T])=>T===d);if(m.length>1)return i(`"${d}" matches ${m.length} contributors (${m.map(([T])=>T).join(", ")}). Assign by assigneeId to choose.`);let p=m[0];if(!p&&!e.createUnlinked)return i(`No contributor named "${d}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[f=un(),x=d]=p??[],A=[...!!o.value.contributors[f]?[]:[{id:un(),...n.value,action:"create.contributor",payload:{id:f,name:x}}],{id:un(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:f}}],P=L(A,t.value.stateBranchRoot);return a(P)?i(P.message):l("Added issue assignee",{id:e.issueId,ref:j(e.issueId),assignee:{id:f,name:x}})},ac=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;if(!o.value.contributors[e.contributorId])return i("Contributor not found");if(await wf(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:un(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],c=L(d,t.value.stateBranchRoot);return a(c)?i(c.message):l("Tombstoned contributor",{id:e.contributorId,name:es})},jx=async(e,t)=>{let n=Hn(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},dc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();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 jx(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:un(),...n.value,action:"restore.contributor",payload:{id:e.contributorId,name:s}}],c=L(d,t.value.stateBranchRoot);return a(c)?i(c.message):l("Restored contributor",{id:e.contributorId,name:s})},cc=async(e={})=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=Hn(t.value.stateBranchRoot);if(a(r))return i(r.message);let s=e.boardId?hf(r.value,e.boardId):r.value,d=new Map,c=new Set,u=new Set,m=ra(t.value.stateBranchRoot);if(a(m))return i(m.message);for(let S of m.value)S.userId&&u.add(S.userId);for(let S of s)S.userId&&(d.set(S.userId,S.userName??""),c.add(S.userId));let p=o.value.contributors,x=[...Cf(d,p).entries()].map(([S,A])=>({id:S,name:A,color:Ce(A),isSelf:S===n.value.userId,isExternal:!c.has(S),isRemoved:p[S]?.tombstoned===!0,hasAuthoredAnywhere:u.has(S)}));return l("Listed board contributors",x)},lc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();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:un(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},d=L([s],t.value.stateBranchRoot);return a(d)?i(d.message):l("Removed issue assignee",{id:e.issueId,ref:j(e.issueId),assigneeId:e.assigneeId})}});import{ulid as Si}from"ulid";var uc,mc,pc,Mf=h(()=>{"use strict";xe();V();R();sn();ln();uc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();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=Si(),c={id:Si(),...n.value,action:"add.issue.comment",payload:{id:d,issue:e.issueId,md:s,author:n.value.userId}},u=L([c],t.value.stateBranchRoot);return a(u)?i(u.message):l("Added issue comment",{id:d,issueId:e.issueId,body:s})},mc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();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 l("Comment already deleted",{id:e.commentId,issueId:r.payload.issue});let c={id:Si(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:r.payload.issue}},u=L([c],t.value.stateBranchRoot);return a(u)?i(u.message):l("Deleted issue comment",{id:e.commentId,issueId:r.payload.issue})},pc=async e=>{let t=await K(e.repoRoot,{pull:!1});if(a(t))return t;let n=J();if(a(n))return n;let o=Y();if(a(o))return o;let r=o.value.eventLog.find(p=>p.action==="add.issue.comment"&&p.payload.id===e.commentId);if(!r)return i("Unable to resolve comment");if(r.payload.author!==n.value.userId)return i("You can only edit 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 edit comment on readonly issue");if(o.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return i("Comment was deleted");let c=e.body.trim();if(!c)return i("Comment cannot be empty");if(c.length>4e3)return i(`Comment cannot exceed ${4e3} characters (got ${c.length})`);let u={id:Si(),...n.value,action:"edit.issue.comment",payload:{id:e.commentId,issue:r.payload.issue,md:c}},m=L([u],t.value.stateBranchRoot);return a(m)?i(m.message):l("Edited issue comment",{id:e.commentId,issueId:r.payload.issue,body:c})}});var kf=h(()=>{"use strict";Ef();Sf();Nf();Af();Tf();Mf();_d()});import{ulid as Hx}from"ulid";var Pf,Lf,Df,Ff=h(()=>{"use strict";Mn();vo();Ut();R();pd();ht();Pf=[{name:"userName",question:"the name they want to appear under on the board"},{name:"preferredEditor",question:'the command that opens a file for editing, e.g. "vim", "nano" or "code --wait"'},{name:"autoSync",question:"whether the TUI and GUI should sync with the git remote on their own (true or false)"}],Lf=e=>e.trim().toLowerCase(),Df=async(e={})=>{let t=Io();if(a(t))return i(t.message);let n=t.value,o=e.userName?.trim(),r=(process.env[lt]??"").trim();if(o&&r&&Lf(o)===Lf(r))return i(`userName "${o}" is this agent's own identity. Pass the user's name, the one they want the TUI and GUI to write as.`);let s={userName:o||void 0,preferredEditor:e.preferredEditor?.trim()||void 0,autoSync:e.autoSync},d={userName:n.userName?.trim()||void 0,preferredEditor:n.preferredEditor?.trim()||void 0,autoSync:typeof n.autoSync=="boolean"?n.autoSync:void 0};for(let T of Pf){let w=s[T.name],_=d[T.name];if(!(w===void 0||_===void 0||w===_))return i(`This machine is already set up with ${T.name} ${JSON.stringify(_)}; epiq_project_init does not change it. Call again without ${T.name}, or let the user change it in the TUI with :config.`)}let c={};if(s.userName&&!d.userName&&(c.userName=s.userName),s.preferredEditor&&!d.preferredEditor&&(c.preferredEditor=s.preferredEditor),s.autoSync!==void 0&&d.autoSync===void 0&&(c.autoSync=s.autoSync),(c.userName||d.userName)&&!n.userId&&(c.userId=Hx()),Object.keys(c).length>0){let T=Ve(c);if(a(T))return i(T.message)}let u={...n,...c},m=Pf.filter(T=>{let w=u[T.name];return typeof w=="boolean"?!1:!w?.trim()});if(m.length>0){let T=m.map(w=>`${w.name} (${w.question})`).join("; ");return i(`Setup incomplete. Ask the user for: ${T}. Then call epiq_project_init again with the answers; what was given so far is saved.`)}let p={userId:u.userId??"",userName:u.userName??""};if(!p.userId||!p.userName)return i("Missing Epiq user id");let f=await li({cwd:e.repoRoot??process.cwd(),user:p});if(a(f))return f;let{defaultEvents:x,...S}=f.value,A=Rr({root:S.repoRoot});a(A)&&X.info(A.message);let P=S.warnings.length===0?"Project initialized":`Project initialized, with warnings: ${S.warnings.join(" ")}`;return l(P,{...S,user:p})}});var Wo,gc,_f=h(()=>{"use strict";Wo=".claude/skills/epiq/SKILL.md",gc="---\nname: epiq\ndescription: Workflow rules for working the epiq issue board \u2014 use the epiq MCP, sync on demand, scope tickets small, keep status/tags accurate, and communicate via comments.\n---\n\n# Epiq board workflow\n\n- **Never test against the real board.** Point any dev server, manual test or test run at a throwaway project, never at this repo's own. Deleting test tickets afterwards does not undo the events. Stop the dev server when you're done rather than leaving it autosyncing.\n- **Use the epiq MCP tools** (`epiq_*`) for all board operations \u2014 never the `epiq` CLI or hand-edited state files.\n- **Never edit the state branch directly.** Don't check it out, don't write to its worktree, don't touch the event log or any file under it by hand or by script \u2014 go through the MCP for every read and write. The event log is the system of record: an edit made outside it bypasses validation and ordering, and can corrupt history in ways no later fix can undo.\n- **Sync is on-demand only.** MCP reads/writes operate on local state and never pull/push automatically. Call `epiq_sync` explicitly when you need the latest remote state or want to publish local changes.\n- **Break work into small, scoped tickets.** One ticket per independent unit of work, not one giant ticket for a whole feature/epic. Small tickets move through the board cleanly and are easier to review.\n- **A small request tightly coupled to a ticket goes into that ticket, not a new one.** When the user asks for a tweak that only makes sense as part of work a ticket already covers \u2014 halving a limit it just introduced, moving a control it just added \u2014 do not file a fresh ticket for it. Record the new requirement as a comment on the original ticket and fold it into the description, move the ticket back to Ongoing if it had already reached Done, prefix the follow-up's commits with that ticket's ref, and add a further `Solution:` comment when it lands, so the ticket's own commit list tells the whole story. `QPPR7PE` is what this avoids: a one-line follow-up to `MBB6WY5` (halve the log cap it had just introduced) that now lives on a ticket of its own. The original does not have to be the ticket you took this session: any ticket open on the board and assigned to you counts. A new ticket is for work that stands on its own \u2014 that someone else could pick up cold, or that needs more than a line or two to describe.\n- **Keep the status column current as work progresses**\n- **Assign the ticket to yourself when you pick it up**, alongside moving it to Ongoing \u2014 so the board shows who is on what, not just what is in flight.\n- **A ticket you file for work you will do this session is assigned to you as you file it.** Filing it unassigned and picking it up a minute later leaves a window where the board shows nobody on it. Picking up a ticket assigned to somebody else is fine \u2014 but ask the user first: it may be mid-flight in another session, and the assignee is what says so.\n- **Take a name as soon as this skill loads, and say it.** Your board identity is `provider/human-name` \u2014 the model provider, a slash, then a short human first name: `claude/peter`, `codex/fred`. Announce it as your first line, exactly `Assuming claude/peter`, and work under it for the whole session so the log reads \"claude/peter did X\" rather than signing the user's name to your work. Before inventing one, call `epiq_contributor_list` and reuse an existing identity for your provider if there is one \u2014 a name is permanent once it has authored anything (`tombstoneContributor` refuses authors), and each new one adds a contributor and an event log file forever. Keep the name stable across sessions; never rename yourself mid-session.\n- **Make the name true with `epiq_actor_assume`, before your first board write.** Announcing alone changes nothing: the writes would still be signed with the user's name. The tool takes the identity for the rest of the session and registers it, so the board carries `claude/peter` rather than the sanitized `claude-peter` the log file name would give. It is idempotent, so re-announcing is free; if it refuses because the server was launched under a name, that name wins \u2014 work under the one it reports and say so. Never claim an attribution the tool did not confirm.\n- **Boot your own MCP instance, and never share one.** `epiq_actor_assume` binds the name to the server process it is called on, so two sessions on one server \u2014 or a session on the user's own instance \u2014 would sign every write with whichever name was assumed last, and the log would fold them into one contributor. Every session therefore needs a server process of its own before its first board call: the one Claude Code spawns for the session counts, and if that never connected (a `CONNECT_TIMEOUT` at boot), start one yourself \u2014 `npx -y -p epiq@latest epiq-mcp` speaks MCP JSON-RPC over stdio, so a small script holding that process and forwarding `tools/call` requests is enough \u2014 rather than waiting on the user or borrowing another session's. Assume the name on *that* process; a restart forgets it, so assume it again before the next write. Kill what you started when the session ends, including the `epiq-mcp` child, which outlives its parent.\n- **When other agents may be running, ask which name to take rather than picking one.** Nothing stops two live agents answering to one name \u2014 the log is a CRDT and takes concurrent writers happily, so they would converge into one indistinguishable identity rather than fail. Another session is likely whenever there is more than one `epiq-mcp` process, another worktree with recent changes, or the user says so; in that case list the existing names for your provider from `epiq_contributor_list` and ask the user which one is free, before `epiq_actor_assume` \u2014 a name once assumed binds the server process, and a second name is refused until it restarts. Ask with the names in the question, not \"which name?\": the user is choosing between identities they can see on the board.\n- **Name the terminal window after the identity.** Several sessions look alike; the name in the tab is how the user tells which window is `claude/peter`. The session cannot reach the terminal itself \u2014 the shell it runs has no tty \u2014 so put the request in the announcement line: `Assuming claude/peter \u2014 please /rename claude/peter so this window carries the name.`\n- **Prefix commits with the ticket ref. **Retrieve the ref programmatically, NEVER DERIVE IT.\\*\\* Read the `ref` field off the MCP response (`epiq_issue_list` and `epiq_board_list` include it on every entry). This is what link-by-reference feature matches on.\n- **Work in a worktree, and leave the root checkout alone.** Take one before the first edit (`EnterWorktree`, or `git worktree add .claude/worktrees/<ref>-<slug>` for a branch that already exists), and never check a feature branch out at the root: the root is where `main` belongs and where the user checks it out themselves, and a branch checked out anywhere is unavailable everywhere else. For the same reason `main` never goes *into* a worktree. Several sessions share this repository at once, so a shared checkout also means one session's `checkout` or `reset` quietly discarding another's work. A fresh worktree needs its own `npm install` before the hooks and suites will run there.\n- **Never work on main, and never merge into it locally. Every change reaches main through a pull request.** Branch before the first edit, push the branch, open the PR, let the gate run, then integrate it. A local merge into `main` looks like it worked and is invisible to everyone else: the work is on nobody's remote, no PR ran the gate over it, and it is one `git fetch origin +main:main` away from vanishing from the branch you are sitting on. That has already happened here \u2014 a tag-filter feature and a scrubber-URL feature lived only in one machine's local `main` for a day, and disappeared the moment somebody synced main with the remote. If you find yourself with commits on local `main`, move them onto a branch and open a PR before doing anything else.\n- **Always rebase onto the target, never merge into it.** Rebase the branch onto the target first, then integrate with a rebase merge \u2014 `gh pr merge --rebase`, never `--merge`. Main stays a flat sequence of ref-prefixed commits, which is what the commit\u2194ticket linking reads. A merge commit adds a subject carrying no ref and buries the branch's commits behind it.\n- **Squashing the branch down first is fine \u2014 one commit per ticket ref.** A branch's worth of fixups is history nobody needs on main, so collapsing it into a single commit (`git rebase -i`, or `gh pr merge --squash` with a ref-prefixed subject) is welcome, provided every commit that lands still opens with its ticket's ref. What the linking cannot survive is a squash *across* refs: fold two tickets' commits into one subject and one of them loses its commits for good. So a branch carrying two refs squashes to two commits, not one \u2014 and check the resulting subject before integrating, because `--squash` defaults to the PR title, which is only right if the title carries the ref.\n- **The git user is the sole author of every commit you write.** Commit under the repo's configured `user.name` / `user.email` and nothing else: no `Co-Authored-By:` line, no `Claude-Session:` line, no `\u{1F916} Generated with` footer, and never an `--author` override naming Claude or a tool. The commit body ends with the last line of prose. This holds for amends and rebases too \u2014 check `git log --format='%an <%ae>%n%b'` over the branch before pushing, because a trailer added by a default template survives a rebase and reaches main unnoticed. It does **not** license rewriting anyone else's authorship: commits by other contributors keep their author, and reassigning them would both misattribute their work and mean force-pushing main.\n- **Tag tickets properly.** Reuse existing tags where they fit (check current issues/tags first) instead of inventing near-duplicates.\n- **Read the ticket's comments before starting, not just its description.** The description is what was known when the ticket was written; comments carry later context \u2014 narrowed scope, a decision already taken, a dead end someone hit, a correction to the original diagnosis. Working from the description alone risks redoing settled work or implementing something that was already ruled out.\n- **Use comments to communicate deviations.** If the work diverges from what the ticket describes \u2014 scope changes, findings, blockers, test results \u2014 record it as a comment on the ticket, not just in chat.\n- When a ticket is done, **Document the outcome in a comment starting with `Solution:`.** Use that exact prefix as the comment's opening line, so `^Solution:` finds every resolved ticket on the board. Say what actually resolved it \u2014 the commit, the approach taken, and anything a reader would otherwise have to reverse-engineer from the diff; a bare commit hash is not a solution. Use the same prefix when a ticket is closed _without_ a code change, and say why.\n- **Attach a screenshot only when a picture carries what words cannot** \u2014 a layout that has to be seen, a rendering bug, a chart whose shape is the point. It is the special case, not a routine part of a `Solution:` comment: most outcomes are better described than photographed, and a screenshot of something a sentence already covers costs everyone the bytes below. When one does earn its place, use `epiq_issue_attachment_add` (it takes a file path) and paste the `markdown` it returns into the comment.\n- **Crop and compress it first.** `epiq_issue_attachment_add` stores the file exactly as it finds it \u2014 only the GUI compresses on upload \u2014 so a raw full-screen capture goes in at full size, up to the 500 KB cap. The blob lands in `.epiq/media/` on the state branch, replicates to every clone, and is never removed: deleting an attachment writes a tombstone and the bytes stay, so time travel can still resolve them. Crop to the region that makes the point, scale it down, and land well under the cap rather than against it. An oversized image is permanent, for everybody \u2014 the same reason the text limits exist.\n- **Be concise.** Titles, descriptions, and comments should be scannable, not essays.\n- If a ticket is blocked, **record the blocker in a comment** and move it to Blocked (or tag it blocked if there is no Blocked column).\n- If a you decide to take a new approach, make sure to document the fork in a new comment, and tag the ticket with a \"fork\" tag, **update the description** to reflect the new plan. Don't leave it as-is and expect readers to infer the change from comments.\n- **Park decisions that are the user's to make.** A design fork, a change with blast radius beyond its ticket, anything you'd want a second opinion on \u2014 file a ticket tagged `human-input-needed` naming the options and the trade-off, then carry on with whatever doesn't depend on the answer. Settling it alone in chat, while nobody is reading, is a decision the user never made.\n- **Findings from a code review get their own tickets**, tagged `from-review`, with the description saying which branch or PR the review covered \u2014 so the provenance survives even if the tag doesn't.\n"});import Ni from"node:fs";import Bf from"node:path";var Of,Uf=h(()=>{"use strict";We();R();_f();Of=async(e={})=>{let t=await rt(e.repoRoot??process.cwd());if(a(t))return i(t.message);let n=Bf.join(t.value,Wo);if(Ni.existsSync(n)){if(Ni.readFileSync(n,"utf8")===gc)return l("Skill already installed and up to date",{path:n,written:!1});if(!e.force)return i(`${Wo} already exists and differs from the bundled skill. Pass force:true to overwrite it.`)}try{Ni.mkdirSync(Bf.dirname(n),{recursive:!0}),Ni.writeFileSync(n,gc,"utf8")}catch(o){return i(o instanceof Error?`Failed to write ${Wo}: ${o.message}`:`Failed to write ${Wo}`)}return l(`Installed skill at ${Wo}`,{path:n,written:!0})}});var Hf={};Jr(Hf,{createMcpServer:()=>jf,resultJson:()=>$f,startMcpServer:()=>zx});import{McpServer as qx}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Gx}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as v}from"zod";var $f,Q,jf,zx,Wf=h(()=>{"use strict";R();sn();kf();Ff();Uf();zr();$f=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Q=e=>t=>yf(async()=>$f(await e(t))),jf=()=>{let e=new qx({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:v.object({repoRoot:v.string().optional()})},Q(Bd)),e.registerTool("epiq_issue_list",{description:"List Epiq issues. Narrow with boardId, swimlaneId, tag, assignee or query (matched against title and description), and pass brief to get id, ref, title, swimlane, tag names and assignee names only \u2014 descriptions are the bulk of a board. Read one ticket with epiq_issue_get.",inputSchema:v.object({repoRoot:v.string().optional(),includeClosed:v.boolean().optional(),boardId:v.string().optional(),swimlaneId:v.string().optional(),tag:v.string().optional(),assignee:v.string().optional(),query:v.string().optional(),brief:v.boolean().optional()})},Q(Hd)),e.registerTool("epiq_issue_get",{description:"Get one Epiq issue by its full id or its 7-character ref, with its comments in log order. Use this rather than listing the whole board when you already know which issue you want, and rather than epiq_state_get to read a thread.",inputSchema:v.object({idOrRef:v.string().min(1),repoRoot:v.string().optional()})},Q(jd)),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:v.object({repoRoot:v.string().optional()})},Q(Yd)),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:v.object({repoRoot:v.string().optional(),boardId:v.string().optional()})},Q(Xd)),e.registerTool("epiq_swimlane_create",{description:"Create an Epiq swimlane on a board",inputSchema:v.object({repoRoot:v.string().optional(),boardId:v.string().min(1),title:v.string().min(1).max(300)})},Q(Jd)),e.registerTool("epiq_swimlane_title_edit",{description:"Edit an Epiq swimlane title",inputSchema:v.object({repoRoot:v.string().optional(),swimlaneId:v.string().min(1),title:v.string().min(1).max(300)})},Q(Qd)),e.registerTool("epiq_swimlane_move",{description:"Move/reorder an Epiq swimlane, optionally to another board",inputSchema:v.object({repoRoot:v.string().optional(),swimlaneId:v.string().min(1),boardId:v.string().min(1),position:v.discriminatedUnion("at",[v.object({at:v.literal("start")}),v.object({at:v.literal("end")}),v.object({at:v.literal("before"),sibling:v.string().min(1)}),v.object({at:v.literal("after"),sibling:v.string().min(1)})]).optional()})},Q(Zd)),e.registerTool("epiq_swimlane_delete",{description:"Delete (archive) an Epiq swimlane. This also archives every issue contained in it.",inputSchema:v.object({repoRoot:v.string().optional(),swimlaneId:v.string().min(1)})},Q(ec)),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:v.object({title:v.string().min(1).max(300),parentId:v.string().min(1),repoRoot:v.string().optional(),description:v.string().max(2e4).optional(),tagNames:v.array(v.string().max(60)).max(20).optional(),assigneeNames:v.array(v.string().max(80)).max(20).optional()})},Q(Wd)),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),description:v.string().max(2e4),repoRoot:v.string().optional()})},Q(Vd)),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),title:v.string().min(1).max(300),repoRoot:v.string().optional()})},Q(Kd)),e.registerTool("epiq_issue_tag_add",{description:"Add a tag to an Epiq issue, or to many at once with issueIds, creating the tag if it does not exist",inputSchema:v.object({issueId:v.string().min(1).optional(),issueIds:v.array(v.string().min(1)).min(1).max(200).optional(),tagName:v.string().min(1).max(60),repoRoot:v.string().optional()})},Q(tc)),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),tagId:v.string().min(1),repoRoot:v.string().optional()})},Q(rc)),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:v.object({boardId:v.string().min(1).optional(),repoRoot:v.string().optional()})},Q(cc)),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:v.object({contributorId:v.string().min(1),repoRoot:v.string().optional()})},Q(ac)),e.registerTool("epiq_tag_remove",{description:"Delete a tag from the whole workspace. It disappears from every ticket, picker and filter, but its id and history stay in the event log, and the name is free for a new tag.",inputSchema:v.object({tagId:v.string().min(1),repoRoot:v.string().optional()})},Q(nc)),e.registerTool("epiq_tag_restore",{description:"Put back a tag deleted with epiq_tag_remove, on every ticket that still carried it.",inputSchema:v.object({tagId:v.string().min(1),repoRoot:v.string().optional()})},Q(oc)),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:v.object({contributorId:v.string().min(1),repoRoot:v.string().optional()})},Q(dc)),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:v.object({issueId:v.string().min(1),assigneeId:v.string().min(1).optional(),self:v.boolean().optional(),assigneeName:v.string().min(1).max(80).optional(),createUnlinked:v.boolean().optional(),repoRoot:v.string().optional()})},Q(ic)),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),assigneeId:v.string().min(1),repoRoot:v.string().optional()})},Q(lc)),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:v.object({issueId:v.string().min(1),body:v.string().min(1).max(4e3),repoRoot:v.string().optional()})},Q(uc)),e.registerTool("epiq_issue_attachment_add",{description:"Attach an image file to an Epiq issue. Returns `markdown` \u2014 paste it into a comment or description body to render the image inline.",inputSchema:v.object({issueId:v.string().min(1),filePath:v.string().min(1),name:v.string().min(1).max(200).optional(),repoRoot:v.string().optional()})},Q(Fd)),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:v.object({commentId:v.string().min(1),repoRoot:v.string().optional()})},Q(mc)),e.registerTool("epiq_issue_comment_edit",{description:"Replace the body of one of your own comments on an Epiq issue",inputSchema:v.object({commentId:v.string().min(1),body:v.string().min(1).max(4e3),repoRoot:v.string().optional()})},Q(pc)),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:v.object({issueId:v.string().min(1),repoRoot:v.string().optional()})},Q(Gd)),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue, or many at once with issueIds \u2014 one call, an outcome per ticket",inputSchema:v.object({issueId:v.string().min(1).optional(),issueIds:v.array(v.string().min(1)).min(1).max(200).optional(),repoRoot:v.string().optional()})},Q(qd)),e.registerTool("epiq_issue_move",{description:"Move an Epiq issue to another swimlane, or many at once with issueIds \u2014 one call, an outcome per ticket",inputSchema:v.object({issueId:v.string().min(1).optional(),issueIds:v.array(v.string().min(1)).min(1).max(200).optional(),parentId:v.string().min(1),position:v.discriminatedUnion("at",[v.object({at:v.literal("start")}),v.object({at:v.literal("end")}),v.object({at:v.literal("before"),sibling:v.string().min(1)}),v.object({at:v.literal("after"),sibling:v.string().min(1)})]).optional(),repoRoot:v.string().optional()})},Q(zd)),e.registerTool("epiq_actor_assume",{description:'Take a board identity for the rest of this session, so your writes are attributed to you rather than to the user. Pass the name you announced \u2014 the model provider, a slash, then a short human first name, e.g. "claude/peter". Takes effect on the very next write; no relaunch. A name the server was launched with wins, and re-assuming the same name is harmless. Reuse an existing agent identity (epiq_contributor_list) before inventing one: a name is permanent once it has authored anything.',inputSchema:v.object({name:v.string().min(1).max(80),repoRoot:v.string().optional()})},Q(sc)),e.registerTool("epiq_project_init",{description:`Set up a new Epiq board in a git repository without the TUI. Runs in the repository at repoRoot (default: the current directory), which must have no uncommitted changes. The first time on a machine it also records the user's setup: ask the user for userName (how they want to appear on the board), preferredEditor (e.g. "vim" or "code --wait") and autoSync (whether the TUI and GUI sync with the remote on their own) and pass them here; called without them it fails naming what is still missing, keeping whatever was given. It fills in answers the machine lacks and refuses to change ones it has. Pass the user's name, never your own agent identity. Commits the state branch and .epiq/project.json and tries to push both; a push that fails is a warning, not an error. Afterwards the other tools work in that repository.`,inputSchema:v.object({repoRoot:v.string().optional(),userName:v.string().min(1).max(80).optional(),preferredEditor:v.string().min(1).max(200).optional(),autoSync:v.boolean().optional()})},Q(Df)),e.registerTool("epiq_skill_install",{description:"Write the official Epiq workflow skill into the repository at .claude/skills/epiq/SKILL.md, so agents working there follow the same board rules. Run it after epiq_project_init, not before: the new file is an uncommitted change that init refuses. In a project that already has a board, run it any time. Refuses to overwrite a differing file unless force is true; an identical file is left alone.",inputSchema:v.object({repoRoot:v.string().optional(),force:v.boolean().optional()})},Q(Of)),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:v.object({repoRoot:v.string().optional()})},Q(Od)),e},zx=async()=>{let e=jf(),t=new Gx;await e.connect(t)}});process.env.EPIQ_MCP="true";console.log=console.error;console.info=console.error;console.debug=console.error;console.warn=console.error;var{applyActorNameArgument:Vx}=await Promise.resolve().then(()=>(Mn(),bc)),{isFail:Kx}=await Promise.resolve().then(()=>(R(),hc)),Ai=process.argv.slice(2);Ai.length>1&&(console.error(`Expected at most one name argument, got ${Ai.length}`),process.exit(1));if(Ai[0]!==void 0){let e=Vx(Ai[0],"The name argument");Kx(e)&&(console.error(e.message),process.exit(1))}var{setVirtualNodesEnabled:Yx}=await Promise.resolve().then(()=>(Xi(),ff));Yx(!1);var{startMcpServer:Xx}=await Promise.resolve().then(()=>(Wf(),Hf));await Xx();
|