epiq 1.8.1 → 1.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -1,74 +1,98 @@
1
1
  #!/usr/bin/env node
2
- var Wg=Object.defineProperty;var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var To=(e,t)=>{for(var n in t)Wg(e,n,{get:t[n],enumerable:!0})};var Id={};To(Id,{failed:()=>i,isFail:()=>a,isSuccess:()=>yt,resultStatuses:()=>Ot,succeeded:()=>l});var Ot,i,l,a,yt,N=v(()=>{"use strict";Ot={Success:"success",Fail:"fail"},i=e=>({status:Ot.Fail,message:e,value:null}),l=(e,t)=>({status:Ot.Success,message:e,value:t}),a=e=>e.status==="fail",yt=e=>e.status==="success"});var Rd={};To(Rd,{ACTOR_ID_ENV:()=>Sr,ACTOR_NAME_ENV:()=>bt,applyActorNameArgument:()=>ci,deriveActorId:()=>Ed,isValidUserId:()=>wo,isValidUserName:()=>Nr,resolveEnvActor:()=>di});import Gg from"node:crypto";var bt,Sr,xd,qg,ai,wo,Nr,Jn,Ed,di,ci,Qn=v(()=>{"use strict";N();bt="EPIQ_USER_NAME",Sr="EPIQ_USER_ID",xd="0123456789ABCDEFGHJKMNPQRSTVWXYZ",qg=26,ai=80,wo=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),Nr=e=>e.trim().length>0&&e.length<=ai,Jn=e=>e.trim().toLowerCase(),Ed=e=>{let t=Gg.createHash("sha256").update(`epiq:actor:${Jn(e)}`).digest(),n="";for(let r=0;r<qg;r++)n+=xd[(t[r]??0)%xd.length];return n},di=(e,t=process.env)=>{let n=(t[bt]??"").trim(),r=(t[Sr]??"").trim();return n?Nr(n)?!r&&e.userId&&e.userName&&Jn(e.userName)===Jn(n)?l("Actor override names the configured user",{userId:e.userId,userName:e.userName}):r&&!wo(r)?i(`${Sr} must be 26 characters of Crockford base32`):r&&e.userId&&r===e.userId?i(`${Sr} 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:r||Ed(n),userName:r?n:Jn(n)}):i(`${bt} must be 1-${ai} characters of text`):r?i(`${Sr} is set without ${bt}`):l("No actor override",null)},ci=(e,t,n=process.env)=>{let r=e.trim();if(!Nr(r))return i(`${t} must be 1-${ai} characters of text`);let o=(n[bt]??"").trim();return o&&Jn(o)!==Jn(r)?i(`${t} names ${r}, but ${bt} names ${o}`):(n[bt]=r,l("Applied actor name argument",r))}});import{decodeTime as Sd}from"ulid";var Mo,li,dt,Cr,Nd,Ar,ct=v(()=>{"use strict";N();Mo=1440*60*1e3,li=(e,t=Date.now())=>e>t+Mo?t:e,dt=e=>li(Sd(e)),Cr=e=>{let t=Date.now()+Mo,n=e.find(o=>o!==null&&o<=t)??null;if(n===null)return[...e];let r=null;return e.map(o=>{if(o===null)return null;let s=o<=t?o:r??n;return r=s,s})},Nd=e=>{try{return l("Decoded date",new Date(dt(e)))}catch(t){return i("Decoding failed + "+t.message)}},Ar=e=>{if(!e?.id)return null;try{return Sd(e.id)}catch{return null}}});var ko,Ke,Cd,It=v(()=>{"use strict";N();ko="removed",Ke=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?l("Found node",n):i("Unable to find node in breadcrumb")},Cd=["png","jpg","gif","webp"]});function ui(e){return e.context===V.WORKSPACE}function P(e){return e.context===V.TICKET}function Ad(e){return e.context===V.TEXT}function Ye(e){return e.context===V.FIELD}function Tr(e){return e.context===V.FIELD_LIST}var V,In,Lo,wr,fe=v(()=>{"use strict";V={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};In=e=>e.context===V.SWIMLANE,Lo=e=>e.context===V.BOARD,wr=e=>e.context===V.COMMENT});var h,pe=v(()=>{"use strict";h={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var Td=v(()=>{"use strict";xn()});import wd from"string-width";function Po(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var En,Vg,mi,zg,pi,Se,Qt=v(()=>{"use strict";En=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Vg=/\u001B\[[0-9;]*m/,mi="\x1B[0m",zg=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),pi=(e,t)=>{if(t<=0)return"";if(wd(e)<=t)return e;if(t<=3)return"...".slice(0,t);let r=t-3,o="",s=0,d=!1;for(let c of e.split(/(\u001B\[[0-9;]*m)/))if(c!==""){if(Vg.test(c)){o+=c,d=c!==mi&&c!=="\x1B[m";continue}for(let u of zg(c)){let m=wd(u);if(s+m>r)return`${o}...${d?mi:""}`;o+=u,s+=m}}return`${o}...${d?mi:""}`},Se=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var Md,kd,Ld=v(()=>{"use strict";Md=e=>{let t=new Map;for(let n of e)for(let r=1;r<=n.length;r++){let o=n.slice(0,r),s=t.get(o);s?s.push(n):t.set(o,[n])}return t},kd=(e,t)=>t?e.get(t)??[]:[]});var Pd,Kg,Dd,Od=v(()=>{"use strict";Qt();Ld();Pd=new WeakMap,Kg=e=>{let t=Pd.get(e);return t||(t=Md(e),Pd.set(e,t)),t},Dd=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return kd(Kg(e),r).filter(s=>Po(r,s)>=n)}});var Yg,Bd,Xg,Fd=v(()=>{"use strict";Qt();Od();Yg={hint:"",hints:[],overlap:0,remainder:""},Bd=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return Yg;let o=Dd({wordList:r,inputToMatch:e,overlapThreshold:1});return Xg(t,o)},Xg=(e,t)=>{let n=t[0]??"",r=Po(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),d=r<(o??"").length,c=!!s,p=(c&&d?o:n)+(c&&d?":":" "),g=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:g}}});import{useSyncExternalStore as gx}from"react";var Do,Jg,Qg,ve,et,Be=v(()=>{"use strict";Do={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Jg=new Set,Qg=()=>{for(let e of Jg)e()},ve=()=>Do,et=e=>(Do={...Do,...e},Qg(),Do)});function _d(e){return!e||!ef.test(e)?i(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function tt(e,t=Mr){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 Fe(e,t){if(!e&&!t)return tt(xt/2n,Mr);let n=e?_d(e):l("Resolved lower bound",0n);if(a(n))return n;let r=t?_d(t):l("Resolved upper bound",xt);if(a(r))return r;let o=n.value,s=r.value;if(s<=o)return i("Neighbouring ranks leave no space between them");let d=(o+s)/2n;return d===o||d===s?i("No rank space available between neighbors"):tt(d,Mr)}function Ud(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=xt*BigInt(r+1)/(t+1n),s=tt(o,Mr);if(a(s))return s;n.push(s.value)}return l("Resolved evenly spaced ranks",n)}var Mr,Zg,xt,ef,Zn=v(()=>{"use strict";N();Mr=24n,Zg=Mr*4n,xt=(1n<<Zg)-1n,ef=/^[0-9a-f]+$/});import{ulid as tf}from"ulid";var gi,$d=v(()=>{"use strict";N();Et();Zn();gi=(e,t)=>{let n=ce(e),r=Ud(n.length);if(a(r))return r;let o={};for(let s=0;s<n.length;s++){let d=n[s],c=r.value[s];if(!d||!c)return i("Unable to assign rebalance rank");o[d.id]=c}return l("Created rebalance event",{id:tf(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})}});import kr from"node:fs";import{ulid as nf}from"ulid";import{z as Oo}from"zod";var rf,of,Bo,Bt,Lr,jd,Ft=v(()=>{"use strict";N();ne();rf="__epiq_state__",of=Oo.object({projectId:Oo.string().min(1),stateBranch:Oo.string().min(1),createdAt:Oo.iso.datetime()}),Bo=()=>({projectId:nf(),stateBranch:rf,createdAt:new Date().toISOString()}),Bt=e=>{let t=Fo(e);if(!kr.existsSync(t))return i("Missing .epiq/project.json");try{let n=kr.readFileSync(t,"utf8"),r=JSON.parse(n),o=of.safeParse(r);return o.success?l("Read project.json",o.data):i(`Invalid .epiq/project.json: ${o.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")}},Lr=e=>{let t=Bt(e);return a(t)?i(t.message):l("Read projectId",t.value.projectId)},jd=({repoRoot:e,fileContents:t})=>{let n=Rn(e),r=Fo(e);try{if(kr.mkdirSync(n,{recursive:!0}),kr.existsSync(r)){let o=Bt(e);return a(o)?i(o.message):l("Project already initialized",null)}return kr.writeFileSync(r,JSON.stringify(t,null,2)+`
3
- `,"utf8"),l("Created project.json",null)}catch(o){return i(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}}});import sf from"node:os";import af from"node:path";var lt,Sn,_o=v(()=>{"use strict";lt=".epiq-global",Sn=()=>process.env.EPIQ_GLOBAL_DIR??af.join(sf.homedir(),lt)});var fi,Hd=v(()=>{"use strict";N();fi=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let d=r(...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 o.clear=()=>n.clear(),o}});var he,Uo=v(()=>{"use strict";ut();he={stage:({cwd:e,pathspec:t,ignoreRemoval:n=!1})=>W({args:["add",...n?["--ignore-removal"]:[],...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1,pathspec:r})=>W({args:["commit","--no-verify",...n?["--allow-empty"]:[],"-m",t,...r?.length?["--",...r]:[]],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>W({args:["fetch",t,`+refs/heads/${n}:refs/remotes/${t}/${n}`],cwd:e}),rebaseOnto:({cwd:e,ref:t})=>W({args:["-c","rebase.autoStash=true","rebase",t],cwd:e}),checkout:({cwd:e,branch:t})=>W({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push","--no-verify",...r?["-u"]:[],t,n]:["push","--no-verify"];return W({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>W({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>W({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>W({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>W({args:["worktree","prune"],cwd:e})}});var Zt,nt,Pr=v(()=>{"use strict";Ft();N();ne();Zt=e=>{let t=Xe(e);if(a(t))return i("Unable to resolve epiq project root");let n=Bt(t.value);return a(n)?i("Unable to read project.json"):l("Resolved state branch",n.value.stateBranch)},nt="origin"});import{spawn as df}from"node:child_process";import Nn from"node:fs";import Cn from"node:path";var cf,lf,uf,mf,pf,gf,ff,Gd,W,Ue,er,hi,hf,$o,Or,vi,jo,Dr,qd,yi,Ho,Vd,zd,vf,Wd,bi,yf,Ii,Kd,Yd,Xd,Jd,ut=v(()=>{"use strict";N();Uo();Pr();cf=1e4,lf=12e4,uf=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),mf=e=>{let t=e.find((n,r)=>!n.startsWith("-")&&e[r-1]!=="-c");return t&&uf.has(t)?lf:cf},pf=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(Cn.delimiter))if(t)for(let n of e){let r=Cn.join(t,n);try{if(!Nn.statSync(r).isFile())continue;return Nn.accessSync(r,Nn.constants.X_OK),r}catch{continue}}return"git"},gf=pf(),ff={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Gd=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Nn.existsSync(t)){let g=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:g,exitCode:1});return}r(i(g));return}let o=df(gf,e,{cwd:t,stdio:["ignore","pipe","pipe"],env:ff}),s=!1,d="",c="",u=g=>{s||(s=!0,clearTimeout(p),r(g))},m=mf(e),p=setTimeout(()=>{o.kill("SIGTERM");let g=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${m}ms`].join(`
4
- `);u(n?{stdout:d,stderr:g,exitCode:124}:i(g))},m);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",g=>{d+=g}),o.stderr.on("data",g=>{c+=g}),o.on("error",g=>{if(n){u({stdout:d,stderr:g.message,exitCode:1});return}u(i([`git ${e.join(" ")}`,`cwd=${t}`,g.message].join(`
5
- `)))}),o.on("close",g=>{let x=g??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}))})}),W=({args:e,cwd:t})=>Gd({args:e,cwd:t,allowFail:!1}),Ue=({args:e,cwd:t})=>Gd({args:e,cwd:t,allowFail:!0}),er=async({cwd:e,message:t,pathspec:n})=>{let r=await he.commit({cwd:e,message:t,pathspec:n});if(a(r))return i(`Failed to create commit
7
- ${r.message}`);let o=await W({args:["rev-parse","HEAD"],cwd:e});return a(o)?i(`Commit created, but failed to read HEAD SHA
8
- ${o.message}`):l("Created commit and resolved SHA",o.value.stdout.trim())},hi=async e=>{let t=await W({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",Cn.isAbsolute(n)?n:Cn.resolve(e,n))},hf=async e=>{let t=await hi(e);if(a(t))return i(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,d]of Object.entries(r))if(Nn.existsSync(Cn.join(n,s)))return l("Checked for in-progress Git operation",d);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,d]of Object.entries(o))if(Nn.existsSync(Cn.join(n,s)))return l("Checked for in-progress Git operation",d);return l("Checked for in-progress Git operation",null)},$o=async e=>{let t=await hf(e);return a(t)?i(t.message):l("Checked for in-progress Git operation",t.value!==null)},Or=async({repoRoot:e})=>{let n=(await Ue({args:["remote","get-url",nt],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},vi=async({repoRoot:e,branch:t})=>{let n=await Ue({args:["ls-remote","--heads",nt,t],cwd:e});return n.exitCode!==0?i(n.stderr.trim()||`Unable to inspect remote branch ${nt}/${t}`):l("Checked remote branch",n.stdout.trim().length>0)},jo=async({repoRoot:e,branch:t})=>{let n=await Ue({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}`)},Dr=e=>{try{return Nn.realpathSync.native(e)}catch{return Cn.resolve(e)}},qd=async({repoRoot:e,worktreeRoot:t})=>{let n=await W({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let r=Dr(t),o=n.value.stdout.split(`
9
- `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(Dr).includes(r);return l("Checked worktree registration",o)},yi=async e=>{let t=await Ue({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Ho=async e=>{let t=await W({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?i(t.message):l("Resolved current branch",t.value.stdout.trim())},Vd=async e=>{let t=await W({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?i(t.message):l("Resolved short HEAD sha",t.value.stdout.trim())},zd=e=>e.includes("fetch first")||e.includes("non-fast-forward"),vf=async e=>(await Ue({cwd:e,args:["rebase","--abort"]})).exitCode===0?l("Aborted stale rebase",!0):l("No rebase to abort",!1),Wd=async e=>{let t=await Ue({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},bi=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),yf=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),Ii=async({cwd:e,branch:t})=>{let n=await vf(e);if(a(n))return i(n.message);let r=await Wd(e),o=await he.fetch({cwd:e,remote:nt,branch:t});if(a(o))return yf(o.message)?l("Remote branch missing, skipped pull",!1):i(`Failed to fetch ${t}
10
- ${o.message}`);let s=await he.rebaseOnto({cwd:e,ref:`${nt}/${t}`});if(a(s))return i(`Failed during rebase
11
- ${s.message}`);let d=await Wd(e),c=r!==null&&d!==null&&r!==d;return l(c?"Pulled with rebase":"Already up to date",c)},Kd=async e=>{let t=await Ue({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)},Yd=async e=>{let t=await Ue({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)},Xd=async(e,t)=>{let n=await Ue({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")},Jd=async e=>{let t=await Ho(e);return a(t)?i(t.message):l("Checked detached HEAD state",t.value==="HEAD")}});import en from"node:fs";import rt from"node:path";var Zd,ec,tc,nc,Wo,Ne,bf,Qd,Br,Go,rc,xi,Ei,oc,sc,mt,cE,pt=v(()=>{"use strict";Ft();N();_o();ne();Hd();Rt();ut();Zd="4b825dc642cb6eb9a060e54bf8d69288fbee4904",ec=e=>rt.join($e,tn,e),tc=()=>rt.join($e,Ri),nc=Sn,Wo=()=>rt.join(nc(),"worktrees"),Ne=({repoRoot:e})=>{let t=Lr(e);return a(t)?i(t.message):l("Resolved state branch root",rt.join(Wo(),t.value))},bf=e=>rt.join(e,$e),Qd=e=>rt.join(bf(e),tn),Br=e=>{try{return en.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return i(t instanceof Error?t.message:String(t))}},Go=()=>{let e=nc(),t=Wo(),n=!en.existsSync(e)||!en.existsSync(t),r=Br(e);if(a(r))return i(`Ensure epiq home failed.
12
- `+r.message);let o=Br(t);return a(o)?i(`Ensure worktrees dir failed.
13
- `+o.message):l("Ensured epiq storage",n)},rc=e=>{en.existsSync(e)&&(X.debug("[sync] remove path",e),en.rmSync(e,{recursive:!0,force:!0}))},xi=`*.jsonl merge=union
14
- `,Ei=()=>rt.join($e,tn,".gitattributes"),oc=(e,t)=>{for(let r of[Qd(e),Qd(t)]){let o=Br(r);if(a(o))return i(o.message)}let n=rt.join(t,Ei());try{en.readFileSync(n,"utf8")!==xi&&en.writeFileSync(n,xi)}catch{en.writeFileSync(n,xi)}return l("Ensured state branch",void 0)},sc=async e=>{let t=await W({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return i(`ensure state branch is storage only failed
15
- `+t.message);let r=t.value.stdout.trim().split(`
16
- `).filter(Boolean).filter(d=>d!==$e);if(r.length===0)return l("State branch is storage-only",!1);let o=await W({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(a(o))return i(`Failed to clean storage branch
17
- ${o.message}`);let s=await er({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:r});return a(s)?i(s.message):l("Cleaned storage branch",!0)},mt=fi(async(e=process.cwd())=>{let t=await W({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=>rt.resolve(e)),cE=fi(async e=>{let t=await W({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return i(t.message);let n=t.value.stdout.trim(),r=rt.isAbsolute(n)?n:rt.join(e,n);return l("Resolved git dir",r)},e=>rt.resolve(e))});import Fr from"node:fs";import St from"node:path";var hE,$e,tn,Ri,If,Rn,Fo,An,qo,ic,xf,_r,Vo,Ef,Xe,ac,Nt,ne=v(()=>{"use strict";N();pt();_o();hE=process.env.IS_LOCAL==="true",$e=".epiq",tn="events",Ri="media",If="project.json",Rn=e=>St.join(e,$e),Fo=e=>St.join(Rn(e),If),An=e=>St.join(Rn(e),tn),qo=e=>St.join(Rn(e),Ri),ic=e=>St.join(e,$e),xf=e=>{let t=St.join(e,$e);return Fr.existsSync(t)&&Fr.statSync(t).isDirectory()},_r=e=>{let t=Fo(e);return Fr.existsSync(t)&&Fr.statSync(t).isFile()},Vo=e=>{let t=St.resolve(e);for(;;){if(xf(t))return l("Resolved closest .epiq root",t);let n=St.dirname(t);if(n===t)return i("No .epiq directory found in any parent");t=n}},Ef="No .epiq/project.json found in any parent",Xe=e=>{let t=St.resolve(e);for(;;){if(_r(t))return l("Resolved closest epiq project root",t);let n=St.dirname(t);if(n===t)return i(Ef);t=n}},ac=e=>{let t=An(e);try{return Fr.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")}},Nt=async()=>{let e=await mt(process.cwd());if(a(e))return e;let t=Ne({repoRoot:e.value});return a(t)?t:l("Resolved persist root",t.value)}});import gt from"fs";import Ti from"path";import Rf from"util";function Af(e){if(!gt.existsSync(e))return;let t=gt.statSync(e).size,n=Cf(e,wi).split(`
18
- `);if(n[n.length-1]===""&&n.pop(),t<=wi&&n.length<=dc)return;let r=n.slice(-dc).join(`
2
+ var Rv=Object.defineProperty;var h=(e,t)=>()=>(e&&(t=e(e=0)),t);var cr=(e,t)=>{for(var n in t)Rv(e,n,{get:t[n],enumerable:!0})};var rl={};cr(rl,{failed:()=>a,isFail:()=>d,isSuccess:()=>Dt,resultStatuses:()=>tn,succeeded:()=>l});var tn,a,l,d,Dt,R=h(()=>{"use strict";tn={Success:"success",Fail:"fail"},a=e=>({status:tn.Fail,message:e,value:null}),l=(e,t)=>({status:tn.Success,message:e,value:t}),d=e=>e.status==="fail",Dt=e=>e.status==="success"});var al={};cr(al,{ACTOR_ID_ENV:()=>lr,ACTOR_NAME_ENV:()=>gt,applyActorNameArgument:()=>na,deriveActorId:()=>il,isValidUserId:()=>vs,isValidUserName:()=>ur,resolveEnvActor:()=>ta});import Nv from"node:crypto";var gt,lr,sl,Cv,ea,vs,ur,vo,il,ta,na,Un=h(()=>{"use strict";R();gt="EPIQ_USER_NAME",lr="EPIQ_USER_ID",sl="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Cv=26,ea=80,vs=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),ur=e=>e.trim().length>0&&e.length<=ea,vo=e=>e.trim().toLowerCase(),il=e=>{let t=Nv.createHash("sha256").update(`epiq:actor:${vo(e)}`).digest(),n="";for(let o=0;o<Cv;o++)n+=sl[(t[o]??0)%sl.length];return n},ta=(e,t=process.env)=>{let n=(t[gt]??"").trim(),o=(t[lr]??"").trim();return n?ur(n)?!o&&e.userId&&e.userName&&vo(e.userName)===vo(n)?l("Actor override names the configured user",{userId:e.userId,userName:e.userName}):o&&!vs(o)?a(`${lr} must be 26 characters of Crockford base32`):o&&e.userId&&o===e.userId?a(`${lr} 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||il(n),userName:o?n:vo(n)}):a(`${gt} must be 1-${ea} characters of text`):o?a(`${lr} is set without ${gt}`):l("No actor override",null)},na=(e,t,n=process.env)=>{let o=e.trim();if(!ur(o))return a(`${t} must be 1-${ea} characters of text`);let r=(n[gt]??"").trim();return r&&vo(r)!==vo(o)?a(`${t} names ${o}, but ${gt} names ${r}`):(r||(n[gt]=o),l("Applied actor name argument",r||o))}});var oa,dl=h(()=>{"use strict";oa="1.8.3"});var cl={};cr(cl,{parseMcpArgs:()=>wv});var Av,wv,ll=h(()=>{"use strict";dl();Av=`epiq-mcp ${oa}
3
+
4
+ Usage: epiq-mcp [name]
5
+
6
+ name the board identity this server writes under, e.g. claude/peter
7
+ (equivalent to setting EPIQ_USER_NAME)
8
+
9
+ Options:
10
+ -v, --version print the version
11
+ -h, --help print this help
12
+ `,wv=e=>{if(e.length>1)return{kind:"error",message:`Expected at most one name argument, got ${e.length}`};let t=e[0];return t===void 0?{kind:"none"}:t==="--version"||t==="-v"?{kind:"print",text:`${oa}
13
+ `}:t==="--help"||t==="-h"?{kind:"print",text:Av}:t.startsWith("-")?{kind:"error",message:`Unknown option ${t}; expected a name, e.g. epiq-mcp claude/peter`}:{kind:"name",name:t}}});import{decodeTime as ul}from"ulid";var ys,mr,He,pr,ml,$n,Ke=h(()=>{"use strict";R();ys=1440*60*1e3,mr=(e,t=Date.now())=>e>t+ys?t:e,He=e=>mr(ul(e)),pr=e=>{let t=Date.now()+ys,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})},ml=e=>{try{return l("Decoded date",new Date(He(e)))}catch(t){return a("Decoding failed + "+t.message)}},$n=e=>{if(!e?.id)return null;try{return ul(e.id)}catch{return null}}});var bs,it,pl,Ft=h(()=>{"use strict";R();bs="removed",it=(e,t)=>{let n=e.find(o=>o.context===t);return n!==void 0?l("Found node",n):a("Unable to find node in breadcrumb")},pl=["png","jpg","gif","webp"]});function ra(e){return e.context===V.WORKSPACE}function P(e){return e.context===V.TICKET}function fl(e){return e.context===V.TEXT}function at(e){return e.context===V.FIELD}function fr(e){return e.context===V.FIELD_LIST}var V,Sn,gr,hr,K=h(()=>{"use strict";V={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};Sn=e=>e.context===V.SWIMLANE,gr=e=>e.context===V.BOARD,hr=e=>e.context===V.COMMENT});var b,pe=h(()=>{"use strict";b={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"}});var gl=h(()=>{"use strict";jn()});import hl from"string-width";function xs(e,t){let n=Math.min(e.length,t.length),o=0;for(;o<n&&e[o]===t[o];)o++;return o}var Hn,Tv,sa,kv,ia,fe,dt=h(()=>{"use strict";Hn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Tv=/\u001B\[[0-9;]*m/,sa="\x1B[0m",kv=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),ia=(e,t)=>{if(t<=0)return"";if(hl(e)<=t)return e;if(t<=3)return"...".slice(0,t);let o=t-3,r="",s=0,i=!1;for(let c of e.split(/(\u001B\[[0-9;]*m)/))if(c!==""){if(Tv.test(c)){r+=c,i=c!==sa&&c!=="\x1B[m";continue}for(let u of kv(c)){let m=hl(u);if(s+m>o)return`${r}...${i?sa:""}`;r+=u,s+=m}}return`${r}...${i?sa:""}`},fe=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim()});var vl,yl,bl=h(()=>{"use strict";vl=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},yl=(e,t)=>t?e.get(t)??[]:[]});var xl,Mv,Il,El=h(()=>{"use strict";dt();bl();xl=new WeakMap,Mv=e=>{let t=xl.get(e);return t||(t=vl(e),xl.set(e,t)),t},Il=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let o=t.toLowerCase();return yl(Mv(e),o).filter(s=>xs(o,s)>=n)}});var Pv,Sl,Lv,Rl=h(()=>{"use strict";dt();El();Pv={hint:"",hints:[],overlap:0,remainder:""},Sl=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},o)=>{if(n||e==="")return Pv;let r=Il({wordList:o,inputToMatch:e,overlapThreshold:1});return Lv(t,r)},Lv=(e,t)=>{let n=t[0]??"",o=xs(e.toLowerCase(),n.toLowerCase()),[r,s]=n.split(":"),i=o<(r??"").length,c=!!s,p=(c&&i?r:n)+(c&&i?":":" "),f=p.slice(o);return{hint:p,hints:t,overlap:o,remainder:f}}});import{useSyncExternalStore as VR}from"react";var Is,Dv,Fv,Ie,ht,We=h(()=>{"use strict";Is={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},Dv=new Set,Fv=()=>{for(let e of Dv)e()},Ie=()=>Is,ht=e=>(Is={...Is,...e},Fv(),Is)});function Nl(e){return!e||!Ov.test(e)?a(`Invalid hex rank: ${e}`):l("Converted rank to bigint",BigInt("0x"+e))}function vt(e,t=vr){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return l("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function qe(e,t){if(!e&&!t)return vt(_t/2n,vr);let n=e?Nl(e):l("Resolved lower bound",0n);if(d(n))return n;let o=t?Nl(t):l("Resolved upper bound",_t);if(d(o))return o;let r=n.value,s=o.value;if(s<=r)return a("Neighbouring ranks leave no space between them");let i=(r+s)/2n;return i===r||i===s?a("No rank space available between neighbors"):vt(i,vr)}function Cl(e){if(e<=0)return l("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let o=0;o<e;o++){let r=_t*BigInt(o+1)/(t+1n),s=vt(r,vr);if(d(s))return s;n.push(s.value)}return l("Resolved evenly spaced ranks",n)}var vr,_v,_t,Ov,yo=h(()=>{"use strict";R();vr=24n,_v=vr*4n,_t=(1n<<_v)-1n,Ov=/^[0-9a-f]+$/});import{ulid as Bv}from"ulid";var aa,Al=h(()=>{"use strict";R();yt();yo();aa=(e,t)=>{let n=ge(e),o=Cl(n.length);if(d(o))return o;let r={};for(let s=0;s<n.length;s++){let i=n[s],c=o.value[s];if(!i||!c)return a("Unable to assign rebalance rank");r[i.id]=c}return l("Created rebalance event",{id:Bv(),action:"rebalance.children",payload:{parent:e,ranks:r},...t})}});import yr from"node:fs";import{ulid as Uv}from"ulid";import{z as Es}from"zod";var $v,jv,Ss,Ot,br,wl,nn=h(()=>{"use strict";R();ae();$v="__epiq_state__",jv=Es.object({projectId:Es.string().min(1),stateBranch:Es.string().min(1),createdAt:Es.iso.datetime()}),Ss=()=>({projectId:Uv(),stateBranch:$v,createdAt:new Date().toISOString()}),Ot=e=>{let t=Rs(e);if(!yr.existsSync(t))return a("Missing .epiq/project.json");try{let n=yr.readFileSync(t,"utf8"),o=JSON.parse(n),r=jv.safeParse(o);return r.success?l("Read project.json",r.data):a(`Invalid .epiq/project.json: ${r.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return a(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},br=e=>{let t=Ot(e);return d(t)?a(t.message):l("Read projectId",t.value.projectId)},wl=({repoRoot:e,fileContents:t})=>{let n=Wn(e),o=Rs(e);try{if(yr.mkdirSync(n,{recursive:!0}),yr.existsSync(o)){let r=Ot(e);return d(r)?a(r.message):l("Project already initialized",null)}return yr.writeFileSync(o,JSON.stringify(t,null,2)+`
14
+ `,"utf8"),l("Created project.json",null)}catch(r){return a(r instanceof Error?`Failed to initialize project: ${r.message}`:"Failed to initialize project")}}});import Hv from"node:os";import Wv from"node:path";var Tt,on,Ns=h(()=>{"use strict";Tt=".epiq-global",on=()=>process.env.EPIQ_GLOBAL_DIR??Wv.join(Hv.homedir(),Tt)});var da,Tl=h(()=>{"use strict";R();da=(e,t)=>{let n=new Map,o=t??((...s)=>JSON.stringify(s)),r=((...s)=>{let i=o(...s);if(!n.has(i)){let c=e(...s).then(u=>(d(u)&&n.delete(i),u));n.set(i,c)}return n.get(i)});return r.clear=()=>n.clear(),r}});var ye,Cs=h(()=>{"use strict";ct();ye={stage:({cwd:e,pathspec:t,ignoreRemoval:n=!1})=>W({args:["add",...n?["--ignore-removal"]:[],...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1,pathspec:o})=>W({args:["commit","--no-verify",...n?["--allow-empty"]:[],"-m",t,...o?.length?["--",...o]:[]],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>W({args:["fetch",t,`+refs/heads/${n}:refs/remotes/${t}/${n}`],cwd:e}),rebaseOnto:({cwd:e,ref:t})=>W({args:["-c","rebase.autoStash=true","rebase",t],cwd:e}),checkout:({cwd:e,branch:t})=>W({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 W({args:r,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>W({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>W({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>W({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>W({args:["worktree","prune"],cwd:e})}});var Bt,bt,bo=h(()=>{"use strict";nn();R();ae();Bt=e=>{let t=Me(e);if(d(t))return a("Unable to resolve epiq project root");let n=Ot(t.value);return d(n)?a("Unable to read project.json"):l("Resolved state branch",n.value.stateBranch)},bt="origin"});import{spawn as Ml}from"node:child_process";import rn from"node:fs";import sn from"node:path";var ca,qv,Gv,zv,Vv,Pl,Ll,Dl,W,Be,la,xo,ua,Kv,As,qn,ma,ws,xr,Fl,pa,Ts,_l,Ol,Bl,Yv,Xv,Jv,Qv,Zv,kl,Ir,ey,Er,Ul,$l,jl,Hl,ct=h(()=>{"use strict";R();Cs();bo();ca=1e4,qv=12e4,Gv=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),zv=e=>{let t=e.find((n,o)=>!n.startsWith("-")&&e[o-1]!=="-c");return t&&Gv.has(t)?qv:ca},Vv=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(sn.delimiter))if(t)for(let n of e){let o=sn.join(t,n);try{if(!rn.statSync(o).isFile())continue;return rn.accessSync(o,rn.constants.X_OK),o}catch{continue}}return"git"},Pl=Vv(),Ll={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Dl=({args:e,cwd:t,allowFail:n})=>new Promise(o=>{if(!rn.existsSync(t)){let f=`Git cwd does not exist: ${t}`;if(n){o({stdout:"",stderr:f,exitCode:1});return}o(a(f));return}let r=Ml(Pl,e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Ll}),s=!1,i="",c="",u=f=>{s||(s=!0,clearTimeout(p),o(f))},m=zv(e),p=setTimeout(()=>{r.kill("SIGTERM");let f=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${m}ms`].join(`
15
+ `);u(n?{stdout:i,stderr:f,exitCode:124}:a(f))},m);r.stdout.setEncoding("utf8"),r.stderr.setEncoding("utf8"),r.stdout.on("data",f=>{i+=f}),r.stderr.on("data",f=>{c+=f}),r.on("error",f=>{if(n){u({stdout:i,stderr:f.message,exitCode:1});return}u(a([`git ${e.join(" ")}`,`cwd=${t}`,f.message].join(`
16
+ `)))}),r.on("close",f=>{let y=f??1;if(n){u({stdout:i,stderr:c,exitCode:y});return}if(y!==0){u(a([`git ${e.join(" ")}`,c.trim()||i.trim()||"Git command failed"].filter(Boolean).join(`
17
+ `)));return}u(l("Git command succeeded",{stdout:i,stderr:c,exitCode:y}))})}),W=({args:e,cwd:t})=>Dl({args:e,cwd:t,allowFail:!1}),Be=({args:e,cwd:t})=>Dl({args:e,cwd:t,allowFail:!0}),la=(e,t)=>new Promise(n=>{if(e.length===0){n(l("No blobs to read",new Map));return}let o=Ml(Pl,["cat-file","--batch"],{cwd:t,stdio:["pipe","pipe","pipe"],env:Ll}),r=[],s="",i=!1,c=m=>{i||(i=!0,clearTimeout(u),n(m))},u=setTimeout(()=>{o.kill("SIGTERM"),c(a(`git cat-file --batch timed out after ${ca}ms`))},ca);o.stdout.on("data",m=>r.push(m)),o.stderr.setEncoding("utf8"),o.stderr.on("data",m=>{s+=m}),o.on("error",m=>c(a(m.message))),o.on("close",m=>{if(m!==0){c(a(`git cat-file --batch exited ${m}${s?`
18
+ ${s}`:""}`));return}let p=Buffer.concat(r),f=new Map,y=0;for(let I of e){let S=p.indexOf(10,y);if(S===-1){c(a(`git cat-file --batch output ended before a header for ${I}`));return}let A=p.toString("utf8",y,S);y=S+1;let w=/^[0-9a-f]{4,64} \S+ (\d+)$/.exec(A);if(!w||!w[1]){c(a(`Unexpected git cat-file --batch header: "${A}"`));return}let k=Number(w[1]);f.set(I,p.toString("utf8",y,y+k)),y+=k+1}c(l("Read blobs",f))}),o.stdin.write(e.join(`
19
+ `)+`
20
+ `),o.stdin.end()}),xo=async({cwd:e,message:t,pathspec:n})=>{let o=await ye.commit({cwd:e,message:t,pathspec:n});if(d(o))return a(`Failed to create commit
21
+ ${o.message}`);let r=await W({args:["rev-parse","HEAD"],cwd:e});return d(r)?a(`Commit created, but failed to read HEAD SHA
22
+ ${r.message}`):l("Created commit and resolved SHA",r.value.stdout.trim())},ua=async e=>{let t=await W({cwd:e,args:["rev-parse","--git-dir"]});if(d(t))return a(t.message);let n=t.value.stdout.trim();return l("Resolved git dir",sn.isAbsolute(n)?n:sn.resolve(e,n))},Kv=async e=>{let t=await ua(e);if(d(t))return a(t.message);let n=t.value,o={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(o))if(rn.existsSync(sn.join(n,s)))return l("Checked for in-progress Git operation",i);let r={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,i]of Object.entries(r))if(rn.existsSync(sn.join(n,s)))return l("Checked for in-progress Git operation",i);return l("Checked for in-progress Git operation",null)},As=async e=>{let t=await Kv(e);return d(t)?a(t.message):l("Checked for in-progress Git operation",t.value!==null)},qn=async({repoRoot:e})=>{let n=(await Be({args:["remote","get-url",bt],cwd:e})).exitCode===0;return l(`Checked remote ${n}`,n)},ma=async({repoRoot:e,branch:t})=>{let n=await Be({args:["ls-remote","--heads",bt,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${bt}/${t}`):l("Checked remote branch",n.stdout.trim().length>0)},ws=async({repoRoot:e,branch:t})=>{let n=await Be({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):a(n.stderr.trim()||`Unable to inspect branch ${t}`)},xr=e=>{try{return rn.realpathSync.native(e)}catch{return sn.resolve(e)}},Fl=async({repoRoot:e,worktreeRoot:t})=>{let n=await W({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let o=xr(t),r=n.value.stdout.split(`
23
+ `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(xr).includes(o);return l("Checked worktree registration",r)},pa=async e=>{let t=await Be({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return l("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Ts=async e=>{let t=await W({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return d(t)?a(t.message):l("Resolved current branch",t.value.stdout.trim())},_l=async e=>{let t=await W({args:["rev-parse","--short","HEAD"],cwd:e});return d(t)?a(t.message):l("Resolved short HEAD sha",t.value.stdout.trim())},Ol=e=>e.includes("fetch first")||e.includes("non-fast-forward"),Bl=async e=>{let t=await Be({cwd:e,args:["rev-parse","--absolute-git-dir"]});if(t.exitCode!==0)return!1;let n=t.stdout.trim();return n?rn.existsSync(sn.join(n,"rebase-merge"))||rn.existsSync(sn.join(n,"rebase-apply")):!1},Yv=3,Xv=120,Jv=e=>new Promise(t=>setTimeout(t,e)),Qv=async(e,t)=>{let n=await ye.rebaseOnto({cwd:e,ref:t});for(let o=1;o<Yv;o+=1){if(!d(n)||await Bl(e))return n;await Jv(Xv),n=await ye.rebaseOnto({cwd:e,ref:t})}return n},Zv=async e=>{if(!await Bl(e))return l("No rebase to abort",!1);let t=await Be({cwd:e,args:["rebase","--abort"]});return t.exitCode!==0?a(`Failed to abort the rebase in progress at ${e}
24
+ ${t.stderr.trim()}`):l("Aborted stale rebase",!0)},kl=async e=>{let t=await Be({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},Ir=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),ey=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),Er=async({cwd:e,branch:t})=>{let n=await Zv(e);if(d(n))return a(n.message);let o=await kl(e),r=await ye.fetch({cwd:e,remote:bt,branch:t});if(d(r))return ey(r.message)?l("Remote branch missing, skipped pull",!1):a(`Failed to fetch ${t}
25
+ ${r.message}`);let s=await Qv(e,`${bt}/${t}`);if(d(s))return a(`Failed during rebase
26
+ ${s.message}`);let i=await kl(e),c=o!==null&&i!==null&&o!==i;return l(c?"Pulled with rebase":"Already up to date",c)},Ul=async e=>{let t=await Be({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)},$l=async e=>{let t=await Be({args:["status","--porcelain","--untracked-files=all"],cwd:e});return t.exitCode!==0?a(t.stderr.trim()||"Unable to inspect the worktree for changes"):l("Inspected worktree for changes",t.stdout.trim().length>0)},jl=async(e,t)=>{let n=await Be({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):a(n.stderr.trim()||"Unable to inspect staged changes")},Hl=async e=>{let t=await Ts(e);return d(t)?a(t.message):l("Checked detached HEAD state",t.value==="HEAD")}});import Rn from"node:fs";import Ye from"node:path";var Gl,zl,Vl,Kl,ks,be,ty,Wl,Sr,Ms,Yl,ny,oy,fa,ga,ql,Xl,Jl,lt,HN,Xe=h(()=>{"use strict";nn();R();Ns();ae();Tl();xt();ct();Gl="4b825dc642cb6eb9a060e54bf8d69288fbee4904",zl=e=>Ye.join(Ge,an,e),Vl=()=>Ye.join(Ge,ha),Kl=on,ks=()=>Ye.join(Kl(),"worktrees"),be=({repoRoot:e})=>{let t=br(e);return d(t)?a(t.message):l("Resolved state branch root",Ye.join(ks(),t.value))},ty=e=>Ye.join(e,Ge),Wl=e=>Ye.join(ty(e),an),Sr=e=>{try{return Rn.mkdirSync(e,{recursive:!0}),l("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},Ms=()=>{let e=Kl(),t=ks(),n=!Rn.existsSync(e)||!Rn.existsSync(t),o=Sr(e);if(d(o))return a(`Ensure epiq home failed.
27
+ `+o.message);let r=Sr(t);return d(r)?a(`Ensure worktrees dir failed.
28
+ `+r.message):l("Ensured epiq storage",n)},Yl=e=>{Rn.existsSync(e)&&(J.debug("[sync] remove path",e),Rn.rmSync(e,{recursive:!0,force:!0}))},ny=`*.jsonl merge=union
29
+ `,oy=`*~pending*.jsonl
30
+ `,fa=()=>Ye.join(Ge,an,".gitattributes"),ga=()=>Ye.join(Ge,an,".gitignore"),ql=(e,t)=>{try{Rn.readFileSync(e,"utf8")!==t&&Rn.writeFileSync(e,t)}catch{Rn.writeFileSync(e,t)}},Xl=(e,t)=>{for(let n of[Wl(e),Wl(t)]){let o=Sr(n);if(d(o))return a(o.message)}return ql(Ye.join(t,fa()),ny),ql(Ye.join(t,ga()),oy),l("Ensured state branch",void 0)},Jl=async e=>{let t=await W({args:["ls-tree","--name-only","HEAD"],cwd:e});if(d(t))return a(`ensure state branch is storage only failed
31
+ `+t.message);let o=t.value.stdout.trim().split(`
32
+ `).filter(Boolean).filter(i=>i!==Ge);if(o.length===0)return l("State branch is storage-only",!1);let r=await W({args:["rm","-r","--ignore-unmatch","--",...o],cwd:e});if(d(r))return a(`Failed to clean storage branch
33
+ ${r.message}`);let s=await xo({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:o});return d(s)?a(s.message):l("Cleaned storage branch",!0)},lt=da(async(e=process.cwd())=>{let t=await W({args:["rev-parse","--show-toplevel"],cwd:e});return d(t)?a("Not inside a Git repository"):l("Resolved repo root",t.value.stdout.trim())},e=>Ye.resolve(e)),HN=da(async e=>{let t=await W({args:["rev-parse","--git-dir"],cwd:e});if(d(t))return a(t.message);let n=t.value.stdout.trim(),o=Ye.isAbsolute(n)?n:Ye.join(e,n);return l("Resolved git dir",o)},e=>Ye.resolve(e))});import Rr from"node:fs";import Ut from"node:path";var YN,Ge,an,ha,ry,Wn,Rs,kt,Ps,Ql,sy,Nr,Ls,iy,Me,Zl,$t,ae=h(()=>{"use strict";R();Xe();Ns();YN=process.env.IS_LOCAL==="true",Ge=".epiq",an="events",ha="media",ry="project.json",Wn=e=>Ut.join(e,Ge),Rs=e=>Ut.join(Wn(e),ry),kt=e=>Ut.join(Wn(e),an),Ps=e=>Ut.join(Wn(e),ha),Ql=e=>Ut.join(e,Ge),sy=e=>{let t=Ut.join(e,Ge);return Rr.existsSync(t)&&Rr.statSync(t).isDirectory()},Nr=e=>{let t=Rs(e);return Rr.existsSync(t)&&Rr.statSync(t).isFile()},Ls=e=>{let t=Ut.resolve(e);for(;;){if(sy(t))return l("Resolved closest .epiq root",t);let n=Ut.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},iy="No .epiq/project.json found in any parent",Me=e=>{let t=Ut.resolve(e);for(;;){if(Nr(t))return l("Resolved closest epiq project root",t);let n=Ut.dirname(t);if(n===t)return a(iy);t=n}},Zl=e=>{let t=kt(e);try{return Rr.mkdirSync(t,{recursive:!0}),l("Resolved events dir",t)}catch(n){return a(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},$t=async()=>{let e=await lt(process.cwd());if(d(e))return e;let t=be({repoRoot:e.value});return d(t)?t:l("Resolved persist root",t.value)}});import Mt from"fs";import Ia from"path";import ay from"util";function uy(e){if(!Mt.existsSync(e))return;let t=Mt.statSync(e).size,n=ly(e,Ea).split(`
34
+ `);if(n[n.length-1]===""&&n.pop(),t<=Ea&&n.length<=eu)return;let o=n.slice(-eu).join(`
19
35
  `)+`
20
- `;gt.writeFileSync(e,r,"utf8")}function Ci(e,t,n=!1){let r=Nf();if(!r)return;let o=Tf(Rf.format(...t)),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
21
- `;try{gt.mkdirSync(Ti.dirname(r),{recursive:!0}),gt.appendFileSync(r,c,"utf8"),Ni++,(Ni>=Sf||gt.statSync(r).size>wi)&&(Ni=0,Af(r))}catch{}}var dc,wi,Si,Sf,Ni,cc,Nf,Cf,Tf,Ai,X,Rt=v(()=>{"use strict";N();ne();dc=500,wi=4*1024*1024,Si=16*1024,Sf=50,Ni=0,cc=()=>process.env.EPIQ_MCP==="true",Nf=()=>{let e=process.cwd(),t=Vo(e);return a(t)?cc()?Ti.join(process.cwd(),".epiq-mcp.log"):void 0:Ti.join(t.value,$e,"log","epiq.log")},Cf=(e,t)=>{let n=gt.statSync(e).size;if(n<=t)return gt.readFileSync(e,"utf8");let r=gt.openSync(e,"r");try{let o=Buffer.alloc(t);gt.readSync(r,o,0,t,n-t);let s=o.toString("utf8"),d=s.indexOf(`
22
- `);return d===-1?"":s.slice(d+1)}finally{gt.closeSync(r)}};Tf=e=>{if(e.length<=Si)return e;let t=e.length-Si;return`${e.slice(0,Si)} \u2026 [${t} more chars]`};Ai=()=>cc()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",X={info(...e){let t=Ai();(t==="info"||t==="debug")&&Ci("[Info]",e,!1)},debug(...e){Ai()==="debug"&&Ci("[Debug]",e,!0)},error(...e){let t=Ai();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;Ci("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=X});var ie,tr=v(()=>{"use strict";ie={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var z,Ur,nn=v(()=>{"use strict";z=e=>e.slice(-7).toUpperCase(),Ur=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?z(e).includes(n):!0}});var Ce,Tn=v(()=>{"use strict";fe();nn();Ce={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:V.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:V.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:V.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:V.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:V.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:V.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:V.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:V.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:d})}});var wf,ye,zo,nr=v(()=>{"use strict";wf=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ye,zo]=wf});function rn(e,t=!1){let n=Bf[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=Of(e,t);return o||r}var Mi,L,jr,wn,Mn,lc,uc,Mf,kf,ki,Lf,Pf,je,Df,Of,$r,Bf,_t,Ut=v(()=>{"use strict";Rt();fe();N();tr();le();Tn();k();Li();nr();Mi=(e,t)=>i(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),L=(e,t)=>({...Mi(e,t),convergence:!0}),jr=e=>a(e)&&e.convergence===!0,wn=e=>{let t=e.filter(a);return{fatal:t.filter(n=>!jr(n)),skipped:t.filter(jr)}},Mn=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("; ")}`)},lc=e=>{let t=I.getNode(e);if(!t||!P(t)||t.isDeleted)return null;let n=Ko(t);return a(n)?n:null},uc=e=>{if(!Yo())return null;for(let t of e){let n=lc(t);if(n)return n;let r=f().nodes[t]?.parentNodeId;if(!r)continue;let o=lc(r);if(o)return o}return null},Mf=(e,t)=>{let n=I.getNode(e);n&&I.updateNode({...n,log:[...n.log??[],t]})},kf=e=>{let t=[e],n=f().nodes[e]?.parentNodeId;return n&&t.push(n),t},ki=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 kf(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[]}},Lf=e=>{Ie(t=>({...t,eventLog:[...t.eventLog,e]}))},Pf=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?Mi("Invalid user ID format",e):l("Valid user",null)},je=null,Df=e=>{for(let[t,n]of e.nodeLog){let r=I.getNode(t);r&&I.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&Ie(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),uc([...e.virtualNodeIds])},Of=(e,t)=>{let n=Pf(e);if(a(n))return n;let r=[...new Set(ki(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=>Mf(s,e)),Lf(e));let o=uc(r);return o||null},$r=(e,t,n)=>I.getNode(e)?L(`a node with id ${e} already exists`,n):t===e?L("a node cannot be its own parent",n):null,Bf={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Ce.workspace(t,n,r),s=Hr(o);if(a(s))return Mi(s.message,e);let d=I.createNode(o);return a(d)?L(d.message??"Failed to initialize workspace",e):ui(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:r}=e.payload,o=$r(t,void 0,e);if(o)return o;let s=I.createNode(Ce.workspace(t,n,r));return a(s)?L(s.message??"Failed to add workspace",e):ui(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:r,rank:o}=e.payload,s=$r(t,r,e);if(s)return s;let d=I.createNode(Ce.board(t,n,r,o));return a(d)?L(d.message??"Unable to create board",e):Lo(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:r,rank:o}=e.payload,s=$r(t,r,e);if(s)return s;let d=I.createNode(Ce.swimlane(t,n,r,o));return a(d)?L(d.message??"Unable to create swimlane",e):In(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:r,rank:o}=e.payload,s=$r(t,r,e);if(s)return s;let d=I.createNode(Ce.ticket(t,n,r,o));return a(d)?L(d.message??"Unable to create issue",e):P(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:r,val:o,rank:s}=e.payload,d=$r(t,r,e);if(d)return d;let c=I.createNode(Ce.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(ie.DESCRIPTION)?"vertical":"horizontal"}));return a(c)?L(c.message??`Unable to create field: ${n}`,e):Ye(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 L(`Unable to locate node with id ${t}`,e);let o=I.renameNode(t,n);return a(o)?L(o.message??"Unable to edit title",e):l("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=I.tombstoneNode(t);return a(n)?L(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=I.createTag({id:t,name:n});return a(r)?L(r.message??"Unable to create tag",e):l("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=I.tombstoneTag(t);return a(n)?L(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,r=I.restoreTag(t,n);return a(r)?L(r.message??"Unable to restore tag",e):l("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=I.createContributor({id:t,name:n});return a(r)?L(r.message??"Unable to create contributor",e):l("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=I.renameContributor(t,n);return a(r)?L(r.message??"Unable to rename contributor",e):l("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=I.tombstoneContributor(t);return a(n)?L(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,r=I.restoreContributor(t,n);return a(r)?L(r.message??"Unable to restore contributor",e):l("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=I.tag(t,n);return a(r)?L(r.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,r=I.untag(t,n);return a(r)?L(r.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,r=I.assign(t,n);return a(r)?L(r.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,r=I.unassign(t,n);return a(r)?L(r.message??"Unable to unassign issue",e):l("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?L(o.message??"Failed to move node",e):l("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=I.editValue(t,n);return a(r)?L(r.message??"Unable to edit description",e):l("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=I.getNode(t);if(!o)return L("Unable to locate issue",e);if(!P(o))return L("Can only close issues",e);let s=I.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=I.moveNodeToRank({id:t,parentId:n,rank:r});return a(d)?L(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:r}=e.payload,o=I.getNode(t);if(!o)return L("Unable to locate issue",e);if(!P(o))return L("Can only reopen issues",e);let s=I.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(!I.getNode(n))return L("Reopen parent no longer exists",e);let c=I.moveNodeToRank({id:t,parentId:n,rank:r});return a(c)?L(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)?L(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let s=I.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=I.updateNode({...s,rank:o});if(a(d))return L(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:r,md:o}=e.payload,s=I.createComment({id:t,issue:n,authorId:r,authorName:I.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return a(s)?L(s.message??"Unable to add comment",e):l("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=I.getComment(t);if(!o)return L("Unable to locate comment",e);if(o.issue!==n)return L("Comment does not belong to issue",e);let s=I.editComment(t,r);return a(s)?L(s.message??"Unable to edit comment",e):l("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=I.getComment(t);if(!r)return L("Unable to locate comment",e);if(r.issue!==n)return L("Comment does not belong to issue",e);let o=I.deleteComment(t);return a(o)?L(o.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:r,ext:o,name:s,bytes:d}=e.payload,c=I.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:d,deleted:!1});return a(c)?L(c.message??"Unable to add attachment",e):l("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=I.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=I.deleteAttachment(t);return a(o)?L(o.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)?L(n.message??"Unable to link contributor",e):l("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};_t=e=>{let t=mc(()=>{let n=je===null;n&&(je={appLog:[],nodeLog:new Map,virtualNodeIds:new Set,genesisApplied:!1});try{let r=e.map(o=>rn(o));if(n&&je){let o=Df(je);if(o)return e.map(()=>o)}return r}finally{n&&(je=null)}});return a(t)?e.map(()=>i(t.message)):t.value}});var Pi,pc=v(()=>{"use strict";Pi=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown"});import{existsSync as Ff,readdirSync as _f,statSync as Uf}from"node:fs";import $f from"node:path";var kn,gc,Di,on,fc,hc,vc,Wr=v(()=>{"use strict";ne();kn=e=>{let t=An(e);return Ff(t)?_f(t).filter(n=>n.endsWith(".jsonl")).sort().map(n=>{let{size:r,mtimeMs:o}=Uf($f.join(t,n));return`${n}:${r}:${o}`}).join("|"):"none"},gc=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),Di=(e,t,n)=>{let r=gc(t),o=kn(e),s=gc(o);for(let[d,c]of s)if(d!==n&&r.get(d)!==c)return null;for(let d of r.keys())if(d!==n&&!s.has(d))return null;return o},on=null,fc=e=>on&&on.root===e?on.signature:null,hc=(e,t)=>{on={root:e,signature:t}},vc=(e,t)=>{if(!on||on.root!==e)return;let n=Di(e,on.signature,t);on=n===null?null:{root:e,signature:n}}});var jf,Hf,yc,bc,Oi=v(()=>{"use strict";jf=["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"],Hf=new Set(jf),yc=e=>Hf.has(e),bc=e=>({action:e.action,payload:e.payload})});import{z as q}from"zod";var j,ft,sn,Xo,Bi,Wf,Ic,xc=v(()=>{"use strict";N();j=q.string().min(1),ft=q.string(),sn=q.string(),Xo=q.looseObject({id:j}),Bi=q.looseObject({id:j,name:ft,parent:j,rank:sn}),Wf={"init.workspace":q.looseObject({id:j,name:ft,rank:sn}),"add.workspace":q.looseObject({id:j,name:ft,rank:sn}),"add.board":Bi,"add.swimlane":Bi,"add.issue":Bi,"add.field":q.looseObject({id:j,name:ft,parent:j,rank:sn}),"edit.title":q.looseObject({id:j,name:ft}),"delete.node":Xo,"lock.node":Xo,"move.node":q.looseObject({id:j,parent:j,rank:sn}),"edit.description":q.looseObject({id:j,md:q.string()}),"close.issue":q.looseObject({id:j,parent:j,rank:sn}),"reopen.issue":q.looseObject({id:j,parent:j,rank:sn}),"create.tag":q.looseObject({id:j,name:ft}),"tombstone.tag":Xo,"restore.tag":q.looseObject({id:j,name:ft}),"create.contributor":q.looseObject({id:j,name:ft}),"rename.contributor":q.looseObject({id:j,name:ft}),"tombstone.contributor":Xo,"restore.contributor":q.looseObject({id:j,name:ft}),"link.contributor.user":q.looseObject({contributor:j}),"add.issue.assignee":q.looseObject({id:j,assignee:j}),"remove.issue.assignee":q.looseObject({id:j,assignee:j}),"add.issue.tag":q.looseObject({id:j,tag:j}),"remove.issue.tag":q.looseObject({id:j,tag:j}),"add.issue.comment":q.looseObject({id:j,issue:j,md:q.string()}),"edit.issue.comment":q.looseObject({id:j,issue:j,md:q.string()}),"delete.issue.comment":q.looseObject({id:j,issue:j}),"add.issue.attachment":q.looseObject({id:j,issue:j,hash:q.string().min(1),ext:q.string().min(1),name:ft,bytes:q.number()}),"delete.issue.attachment":q.looseObject({id:j,issue:j}),"rebalance.children":q.looseObject({parent:j,ranks:q.record(q.string(),sn)})},Ic=(e,t)=>{let r=Wf[e].safeParse(t);return r.success?l("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 Gf}from"ulid";import{z as Fi}from"zod";function Gr(e,t){let n=An(e),r=kn(e);if(!Qo.existsSync(n))return l("No events found",[]);let o=Qo.readdirSync(n).filter(c=>c.endsWith(".jsonl")).map(c=>Zo.join(n,c)),s=[];for(let c of o){let u=Zf(c,t);if(a(u))return i(u.message);s.push(...u.value)}let d=th(s);return $t={root:e,signature:r,edge:d.at(-1)?.id?.[0]??null},l("All events loaded",d)}function jt(e){let t=[],n=Gr(e,t);if(a(n))return i(n.message);let r=Ui(n.value,t);return a(r)?i(r.message):(eh=t,l("Loaded merged events",{events:r.value,unreadable:t}))}function $i(e){let t=Gr(e);return a(t)?i(t.message):l("Loaded event actors",t.value.map(({userId:n,userName:r})=>({userId:n,userName:r})))}function Ln(e){let t=jt(e);return a(t)?i(t.message):l("Loaded merged events",t.value.events)}function ji(e,t){let n=Gr(e);if(a(n))return i(n.message);let{appliedEvents:r,unappliedEvents:o}=nh(n.value,t),s=Ui(r);if(a(s))return i(s.message);let d=Ui(o);return a(d)?i(d.message):l("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:d.value})}function Ec(e=process.cwd()){let t=kn(e);if($t&&$t.root===e&&$t.signature===t)return l("Loaded edge reference, unchanged",$t.edge);let n=Gr(e);return a(n)?i(n.message):l("Loaded edge reference",n.value.at(-1)?.id?.[0]??null)}function Rc(e,t,n){if(!$t||$t.root!==e)return;let r=Di(e,$t.signature,t);$t=r===null?null:{root:e,signature:r,edge:n}}function Hi(e){let t=Gr(e);if(a(t))return i(t.message);let n=Sc(t.value);return l("Loaded effective event times",new Map(t.value.map((r,o)=>[r.id[0],n[o]??null])))}var qf,Jo,Vf,zf,Kf,Yf,Xf,Jf,Qf,Ui,Zf,eh,$t,_i,th,Sc,nh,Ht=v(()=>{"use strict";Rt();N();ne();Wr();ct();Oi();ht();xc();qf=Fi.object({userId:Fi.string().min(1).default("unknown"),userName:Fi.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},Vf=/^[0-9a-hjkmnp-tv-z]{26}$/i,zf=e=>Vf.test(e)?e.toUpperCase():e,Kf=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=qf.safeParse({userId:zf(r),userName:o});return s.success?l("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(", ")}`)},Yf=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])},Xf=(e,t)=>t in e,Jf=({id:e,action:t,payload:n,userId:r,userName:o})=>({id:e,action:t,payload:n,userId:r,userName:o}),Qf=e=>{let{userId:t,userName:n,...r}=e,o=Yf(r);if(a(o))return i(o.message);let s=o.value,d=e.id?.[0];return d?Xf(r,s)?l("Decoded persisted event",Jf({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")},Ui=(e,t)=>{let n=[],r=new Map,o=new Map;for(let s of e){if(!Cc(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=Qf(s);if(a(d)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:d.message,targetNodeId:Jo(s)});continue}let c=d.value.action;if(!yc(c)){r.set(c,(r.get(c)??0)+1),t?.push({eventId:s.id[0],reason:"unknown-action",detail:c,targetNodeId:Jo(s)});continue}let u=Ic(c,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,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(o.size>0){let s=[...o.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)},Zf=(e,t)=>{if(!Qo.existsSync(e))return l("Event file missing",[]);let n=Kf(e);if(a(n))return i(n.message);let r=Qo.readFileSync(e,"utf8"),o=[],s=Zo.basename(e),d=(c,u)=>{t?.push({eventId:null,reason:"corrupt-line",detail:`${s}:${c} (${u})`,targetNodeId:null})};for(let[c,u]of r.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 g=Nc(p);if(a(g)){d(c+1,g.message);continue}o.push({...g.value,userId:n.value.userId,userName:n.value.userName})}return l("Parsed persisted events file",o)};eh=[];$t=null;_i=(e,t)=>{let n=e.id[0].localeCompare(t.id[0]);return n!==0?n:JSON.stringify(e).localeCompare(JSON.stringify(t))},th=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 x=n.get(g)??[];x.push(m),n.set(g,x)}for(let m of n.values())m.sort(_i);let r=[],o=new Set,s=m=>{let p=[m];for(;p.length>0;){let g=p.pop(),x=g.id[0];if(o.has(x))continue;r.push(g),o.add(x);let S=n.get(x)??[];for(let C=S.length-1;C>=0;C--)p.push(S[C])}},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 c=e.filter(m=>{let p=m.id[0],g=m.id[1]??null;return o.has(p)?!1:g===null||!t.has(g)}).sort(_i);for(let m of c)s(m);let u=e.filter(m=>!o.has(m.id[0])).sort(_i);for(let m of u)s(m);return r},Sc=e=>Cr(e.map(t=>{try{return Gf(t.id[0])}catch{return null}}));nh=(e,t)=>{let n=new Set,r=[],o=[],s=Sc(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),o.push(c)):r.push(c)}return{appliedEvents:r,unappliedEvents:o}}});import rh from"node:fs";import Tc from"node:path";import{decodeTime as oh,monotonicFactory as sh}from"ulid";import{z as Pn}from"zod";function Wi(e,t){let n;if(t&&t.current!==void 0)n=t.current;else{let o=Ec(e);if(a(o))return i(o.message);n=o.value}let r=n?Ac(dh(n)):Ac();return l("Minted event id",[r,n])}function es({event:e,rootDir:t,edge:n,id:r}){try{let o=ac(t);if(a(o))return o;let s=gh(t,{userId:e.userId,userName:e.userName});if(a(s))return s;let d=r?l("Minted event id",r):Wi(t,n);if(a(d))return i(d.message);let[c,u]=d.value,m=fh(bc(e),[c,u]);if(a(m))return i(m.message);rh.appendFileSync(s.value,`${JSON.stringify(m.value)}
24
- `,"utf8"),n&&(n.current=c);let p=Tc.basename(s.value);return Rc(t,p,c),vc(t,p),l("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 wc,Ac,ih,ah,dh,Mc,ch,lh,Nc,uh,mh,Cc,ph,ge,Dn,gh,fh,ht=v(()=>{"use strict";Rt();Qn();N();Be();ne();pc();ct();Ht();Wr();Oi();wc=1,Ac=sh(),ih=0xffffffffffff,ah=Mo,dh=e=>{let t=Date.now(),n;try{n=oh(e)}catch{return t}return n>=ih?t:n>t+ah?(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)},Mc=Pn.tuple([Pn.string().min(1),Pn.string().min(1).nullable()]),ch=Pn.looseObject({v:Pn.literal(wc),id:Mc}),lh=Pn.looseObject({v:Pn.number().int().positive(),id:Mc}),Nc=e=>{let t=lh.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(", ")}`)},uh=[1],mh=new Set(uh),Cc=e=>mh.has(e),ph=e=>{let t=ch.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(", ")}`)},ge=()=>{let{userName:e,userId:t}=ve();return e?t?wo(t)?Nr(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")},Dn=({userId:e,userName:t})=>`${Pi(e)}.${Pi(t)}.jsonl`,gh=(e,{userId:t,userName:n})=>{let r=Dn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(r))return i(`Invalid event log file name: ${r}`);let s=Tc.join(An(e),r);return l("Successfully resolved event log path",s)},fh=(e,t)=>{let n={[e.action]:e.payload,v:wc,id:t};return ph(n)}});import{ulid as hh}from"ulid";function kc(e,t,n){let r=Wi(t,n);if(a(r))return i(r.message);let o={...e,id:r.value[0]},s=rn(o);if(s.status!==Ot.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=vh(e[0],t,n);if(a(r))return r;let o=e.map(d=>kc(d,t,n)),s=o.filter(a);return s.length>0?i("Materialize and persist failed: "+s.map(d=>d.message).join(", ")):l("Materialization succeeded",o.map(d=>d.value))}var vh,On=v(()=>{"use strict";N();le();k();Ut();ht();vh=(e,t,n)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return l("Contributor write already in flight",void 0);let r=I.getContributor(e.userId),o={id:hh(),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 l("Contributor name is current",void 0);let s=kc(o,t,n);return a(s)?i(s.message):l("Contributor name recorded",void 0)}});var Bn,Gi,Lc=v(()=>{"use strict";nn();Bn=e=>e.trim().toLocaleLowerCase(),Gi=(e,t)=>Bn(e).includes(Bn(t))});var yh,bh,Pc,Dc,Ih,xh,Oc,Bc=v(()=>{"use strict";k();nn();Lc();yh=e=>{let{tags:t}=f();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},bh=e=>{let{contributors:t}=f();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},Pc=null,Dc=new Map,Ih=()=>{let e=f().eventLog??[];if(e===Pc)return Dc;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 Pc=e,Dc=t,t},xh=e=>{let{contributors:t}=f(),n=Ih().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},Oc=(e,t)=>{let n=Bn(t.value);if(!n)return!0;switch(t.target){case"title":return Gi(e.title??"",n);case"description":return Gi(e.props.description??"",n);case"tag":return yh(e).map(Bn).some(o=>o.includes(n));case"assignee":return bh(e).map(Bn).some(o=>o.includes(n));case"actor":return xh(e).map(Bn).some(o=>o.includes(n));case"ref":return Ur(e.id,t.value);default:return!0}}});var Fc,Eh,_c,Uc,qi=v(()=>{"use strict";fe();Bc();Fc=(e,t)=>e.rank.localeCompare(t.rank),Eh=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,_c=(e,t)=>Object.values(e).filter(n=>Eh(n,t)).sort(Fc),Uc=(e,t)=>{let n={};for(let r of Object.values(e)){if(P(r)&&t.length>0&&!t.every(s=>Oc(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(Fc);return n}});var $c,ts,ce,jc,Hc,an,Fn,Et=v(()=>{"use strict";$d();On();N();k();qi();Zn();$c=e=>ts(ce(e),{at:"end"}),ts=(e,t={at:"end"})=>{let n=o=>a(o)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(Fe(void 0,void 0));let r=()=>n(Fe(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(Fe(void 0,o.rank)):i("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(Fe(o.rank,void 0)):i("Unable to resolve last sibling")}case"before":{let o=jc(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(Fe(d?.rank,s.rank))}case"after":{let o=jc(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(Fe(s.rank,d?.rank))}}},ce=e=>{let t=f();if(!Wc()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return _c(t.nodes,e)},jc=(e,t)=>e.findIndex(n=>n.id===t),Hc=(e,t,n={at:"end"})=>ts(ce(t).filter(r=>r.id!==e),n),an=(e,t,n,r,o)=>{let s=Hc(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return l("Resolved rank",s.value.rank);let d=gi(e,r);if(a(d))return d;let c=B([d.value],o);if(a(c))return c;let u=Hc(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)},Fn=(e,t,n)=>{let r=$c(e);if(a(r))return r;if(!r.value.needsRebalance)return l("Resolved rank",r.value.rank);let o=gi(e,t);if(a(o))return o;let s=B([o.value],n);if(a(s))return s;let d=$c(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,Gc,qc,Je=v(()=>{"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:()=>Gc(1),navigateToPreviousItem:()=>Gc(-1),navigateToNextContainer:()=>qc(1),navigateToPreviousContainer:()=>qc(-1),navigate:({contextNode:e,selectedIndex:t})=>{E({contextNodeId:e.id,selectedIndex:t})}},Gc=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})},qc=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(x=>x.id===t.id);if(d<0)return;let c=s.at(d+e)??s.at(0);if(!c)return;let u=ae(c.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),g=u.length?p:-1;U.navigate({contextNode:c,selectedIndex:g})}});var zc,Kc,Rh,ns,Yc,Vc,Sh,Xc,Jc=v(()=>{"use strict";fe();N();Et();k();Je();zc=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Kc=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=f();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},Rh=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=ce(r.id);return U.navigate({contextNode:r,selectedIndex:zc(t,o.length)}),!0},Yc=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=ce(o.id).findIndex(c=>c.id===n.id);return d>=0?(U.navigate({contextNode:o,selectedIndex:d}),!0):Yc(o.id)},Vc=e=>{let{nodes:t}=f(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Yc(n))return!0;n=t[n]?.parentNodeId}return!1},Sh=e=>{if(!e)return!1;let t=f().nodes[e];return!!t&&!t.isDeleted},Xc=e=>{let{nodes:t,rootNodeId:n}=f();if(Rh(e.contextNodeId)&&ns(e.contextNodeId,e.selectedIndex))return l("Restored navigation inside text container",null);if(Sh(e.selectedNodeId)&&e.selectedNodeId&&Vc(e.selectedNodeId))return l("Restored navigation to selected node or ancestor",null);if(ns(e.contextNodeId,e.selectedIndex))return l("Restored navigation to previous container",null);if(e.parentNodeId&&ns(e.parentNodeId,e.selectedIndex))return l("Restored navigation to previous parent",null);if(Vc(e.contextNodeId))return l("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return i("Unable to restore navigation");let o=ce(r.id);return U.navigate({contextNode:r,selectedIndex:zc(e.selectedIndex,o.length)}),l("Restored navigation to root",null)}});import{monotonicFactory as Nh,ulid as Ct}from"ulid";function Ch(){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 l("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?l("Resolved boot nav target",{contextNode:r,selectedIndex:0}):l("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function Ah(){let e=Ch();return a(e)?e:U.navigate(e.value)}function Qc({userId:e,userName:t}){let n=qr(),r=qr(),o=qr(),s=qr(),d=qr(),c=Fe(void 0,void 0);if(a(c))return c;let u=Fe(void 0,void 0);if(a(u))return u;let m=Fe(u.value,void 0);if(a(m))return m;let p=Fe(void 0,void 0);if(a(p))return p;let g=Fe(p.value,void 0);if(a(g))return g;let x=Fe(g.value,void 0);if(a(x))return x;let S=Fe(void 0,void 0);return a(S)?S:l("Created default events",[{id:Ct(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:Ct(),userId:e,userName:t,action:"create.contributor",payload:{id:e,name:t}},{id:Ct(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Ct(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Ct(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:g.value}},{id:Ct(),userId:e,userName:t,action:"add.swimlane",payload:{id:d,name:"Done",parent:r,rank:x.value}},{id:Ct(),userId:e,userName:t,action:"add.board",payload:{id:zo,name:"Closed",parent:n,rank:m.value}},{id:Ct(),userId:e,userName:t,action:"add.swimlane",payload:{id:ye,name:"Closed",parent:zo,rank:S.value}},{id:Ct(),userId:e,userName:t,action:"lock.node",payload:{id:zo}},{id:Ct(),userId:e,userName:t,action:"lock.node",payload:{id:ye}}])}function dn(e,t=[]){if(Th())return l("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Ce.workspace("temporary-uninitialized-workspace","Workspace","a0"),d=Hr(s);return a(d)?d:(E({hasProjectDefinition:!1,mode:h.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=_t(e),{fatal:r,skipped:o}=wn(n);return r.length>0?i(`Materializing failed:
25
- ${r.map(s=>s.message).join(`
26
- `)}`):(Mn(o),Ah(),E({hasProjectDefinition:!0}),wh(t),l("State booted successfully",null))}var qr,Th,wh,Vr=v(()=>{"use strict";Rt();Je();pe();N();Tn();k();Zn();Ut();nr();qr=Nh();Th=()=>{let e=He();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},wh=e=>{if(e.length===0)return;let t=e.filter(r=>r.reason==="corrupt-line"||r.reason==="invalid-payload"),n=e.filter(r=>r.reason==="unsupported-schema-version"||r.reason==="unknown-action");if(n.length>0){let r=[...new Set(n.map(o=>o.detail))].join(", ");X.info(`This build cannot read ${n.length} event(s) in the log (${r}). They are skipped, so anything they changed may be out of date until you upgrade.`)}if(t.length>0){let r=[...new Set(t.map(o=>o.detail))].join(", ");X.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}}});import{WebSocket as Mh}from"ws";var kh,Zc,el=v(()=>{"use strict";kh=new Set,Zc=e=>{let t=JSON.stringify(e);for(let n of kh)n.readyState===Mh.OPEN&&n.send(t)}});var rs,os,ss,Vi,tl,Me,is=v(()=>{"use strict";el();N();k();rs=e=>{ot()&&(E({syncStatus:e}),Zc({type:"sync-status",payload:e}))},os=(e="Syncing...")=>{rs({status:"syncing",msg:e})},ss=(e="Synced")=>{rs({status:"synced",msg:e})},Vi=e=>{rs({status:"failed",msg:e})},tl=e=>{rs({status:"offline",msg:e})},Me=e=>(Vi(e),i(e))});var zr,Q,as=v(()=>{"use strict";N();zr=(e,t)=>(logger.error(`[boot:${e}] ${t}`),i(`[boot:${e}] ${t}`)),Q=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t)});import At from"node:fs";import Kr from"node:path";var rr,nl,rl,ol,Lh,sl,Ph,Dh,il,zi=v(()=>{"use strict";ut();N();ne();rr=e=>e.split(`
27
- `).filter(t=>t.trim().length>0),nl=e=>{let t=Kr.join(e,$e,tn);try{if(!At.existsSync(t))return l("No events directory",[]);let n=At.readdirSync(t).filter(r=>r.endsWith(".jsonl")).filter(r=>rr(At.readFileSync(Kr.join(t,r),"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)}`)}},rl=e=>Kr.join(e,$e,tn),ol=e=>{let t=rl(e),n=new Map;try{if(!At.existsSync(t))return n;for(let r of At.readdirSync(t))r.endsWith(".jsonl")&&n.set(r,rr(At.readFileSync(Kr.join(t,r),"utf8")))}catch{return n}return n},Lh=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},sl=(e,t)=>{if(t.size===0)return[];let n=rl(e),r=[];for(let[o,s]of t){if(s.length===0)continue;let d=Kr.join(n,o);try{let c=At.existsSync(d)?At.readFileSync(d,"utf8"):null,u=new Set(c===null?[]:rr(c)),m=s.filter(g=>!u.has(g)).filter(Lh);if(m.length===0)continue;At.mkdirSync(n,{recursive:!0});let p=c!==null&&c.length>0&&!c.endsWith(`
28
- `);At.appendFileSync(d,`${p?`
36
+ `;Mt.writeFileSync(e,o,"utf8")}function ba(e,t,n=!1){let o=cy();if(!o)return;let r=my(ay.format(...t)),s=new Date,c=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${r}
37
+ `;try{Mt.mkdirSync(Ia.dirname(o),{recursive:!0}),Mt.appendFileSync(o,c,"utf8"),ya++,(ya>=dy||Mt.statSync(o).size>Ea)&&(ya=0,uy(o))}catch{}}var eu,Ea,va,dy,ya,tu,cy,ly,my,xa,J,xt=h(()=>{"use strict";R();ae();eu=500,Ea=4*1024*1024,va=16*1024,dy=50,ya=0,tu=()=>process.env.EPIQ_MCP==="true",cy=()=>{let e=process.cwd(),t=Ls(e);return d(t)?tu()?Ia.join(on(),"epiq-mcp.log"):void 0:Ia.join(t.value,Ge,"log","epiq.log")},ly=(e,t)=>{let n=Mt.statSync(e).size;if(n<=t)return Mt.readFileSync(e,"utf8");let o=Mt.openSync(e,"r");try{let r=Buffer.alloc(t);Mt.readSync(o,r,0,t,n-t);let s=r.toString("utf8"),i=s.indexOf(`
38
+ `);return i===-1?"":s.slice(i+1)}finally{Mt.closeSync(o)}};my=e=>{if(e.length<=va)return e;let t=e.length-va;return`${e.slice(0,va)} \u2026 [${t} more chars]`};xa=()=>tu()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",J={info(...e){let t=xa();(t==="info"||t==="debug")&&ba("[Info]",e,!1)},debug(...e){xa()==="debug"&&ba("[Debug]",e,!0)},error(...e){let t=xa();if(t==="error"||t==="info"||t==="debug"){let o=e.some(r=>r instanceof Error)?void 0:new Error().stack;ba("[Error]",[...e,o].filter(Boolean),!1)}}};globalThis.logger=J});var ue,Io=h(()=>{"use strict";ue={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"}});var j,Cr,Je=h(()=>{"use strict";j=e=>e.slice(-7).toUpperCase(),Cr=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?j(e).includes(n):!0}});var Pe,Gn=h(()=>{"use strict";K();Je();Pe={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:V.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:V.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:r,log:[]}),swimlane:(e,t,n,o)=>({id:e,title:t,rank:o,isDeleted:!1,props:{},context:V.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:i=!1})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:V.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),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:V.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:V.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:V.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:i=!0})=>({id:e,title:t,rank:o,isDeleted:!1,props:r,context:V.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})}});var py,he,Ds,dn=h(()=>{"use strict";py=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[he,Ds]=py});function Nn(e,t=!1){let n=xy[e.action];if(!n)return a(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);if(!It()&&e.action!=="init.workspace")return F(`${e.action} arrived before the workspace was initialized`,e);if(e.action==="init.workspace"&&Qe){if(Qe.genesisApplied)return F("the workspace is already initialized",e);Qe.genesisApplied=!0}let o;try{o=n(e)}catch(s){return F(`threw while materializing (${s instanceof Error?s.message:String(s)})`,e)}if(d(o))return o;let r=by(e,t);return r||o}var Sa,F,wr,zn,Vn,nu,ou,fy,gy,Ra,hy,vy,Qe,yy,by,Ar,xy,cn,ln=h(()=>{"use strict";xt();K();R();Io();ne();Gn();M();Na();dn();Sa=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),F=(e,t)=>({...Sa(e,t),convergence:!0}),wr=e=>d(e)&&e.convergence===!0,zn=e=>{let t=e.filter(d);return{fatal:t.filter(n=>!wr(n)),skipped:t.filter(wr)}},Vn=e=>{e.length!==0&&J.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},nu=e=>{let t=E.getNode(e);if(!t||!P(t)||t.isDeleted)return null;let n=Fs(t);return d(n)?n:null},ou=e=>{if(!_s())return null;for(let t of e){let n=nu(t);if(n)return n;let o=g().nodes[t]?.parentNodeId;if(!o)continue;let r=nu(o);if(r)return r}return null},fy=(e,t)=>{let n=E.getNode(e);n&&E.updateNode({...n,log:[...n.log??[],t]})},gy=e=>{let t=[e],n=g().nodes[e]?.parentNodeId;return n&&t.push(n),t},Ra=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 gy(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[]}},hy=e=>{Ne(t=>({...t,eventLog:[...t.eventLog,e]}))},vy=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?Sa("Invalid user ID format",e):l("Valid user",null)},Qe=null,yy=e=>{for(let[t,n]of e.nodeLog){let o=E.getNode(t);o&&E.updateNode({...o,log:[...o.log??[],...n]})}return e.appLog.length>0&&Ne(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),ou([...e.virtualNodeIds])},by=(e,t)=>{let n=vy(e);if(d(n))return n;let o=[...new Set(Ra(e))];if(Qe){for(let s of o){if(!t){let i=Qe.nodeLog.get(s);i?i.push(e):Qe.nodeLog.set(s,[e])}if(_s()){Qe.virtualNodeIds.add(s);let i=g().nodes[s]?.parentNodeId;i&&Qe.virtualNodeIds.add(i)}}return t||Qe.appLog.push(e),null}t||(o.forEach(s=>fy(s,e)),hy(e));let r=ou(o);return r||null},Ar=(e,t,n)=>E.getNode(e)?F(`a node with id ${e} already exists`,n):t===e?F("a node cannot be its own parent",n):null,xy={"init.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=Pe.workspace(t,n,o),s=Tr(r);if(d(s))return Sa(s.message,e);let i=E.createNode(r);return d(i)?F(i.message??"Failed to initialize workspace",e):ra(i.value)?l("Workspace initialized",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:o}=e.payload,r=Ar(t,void 0,e);if(r)return r;let s=E.createNode(Pe.workspace(t,n,o));return d(s)?F(s.message??"Failed to add workspace",e):ra(s.value)?l("Added workspace",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=Ar(t,o,e);if(s)return s;let i=E.createNode(Pe.board(t,n,o,r));return d(i)?F(i.message??"Unable to create board",e):gr(i.value)?l("Added board",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=Ar(t,o,e);if(s)return s;let i=E.createNode(Pe.swimlane(t,n,o,r));return d(i)?F(i.message??"Unable to create swimlane",e):Sn(i.value)?l("Added swimlane",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:o,rank:r}=e.payload,s=Ar(t,o,e);if(s)return s;let i=E.createNode(Pe.ticket(t,n,o,r));return d(i)?F(i.message??"Unable to create issue",e):P(i.value)?l("Added issue",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:o,val:r,rank:s}=e.payload,i=Ar(t,o,e);if(i)return i;let c=E.createNode(Pe.field({id:t,name:n,parentNodeId:o,rank:s,props:{value:r},childRenderAxis:n.includes(ue.DESCRIPTION)?"vertical":"horizontal"}));return d(c)?F(c.message??`Unable to create field: ${n}`,e):at(c.value)?l("Added field",{action:e.action,result:c.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!E.getNode(t))return F(`Unable to locate node with id ${t}`,e);let r=E.renameNode(t,n);return d(r)?F(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=E.tombstoneNode(t);return d(n)?F(n.message??"Unable to delete node",e):l("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,o=E.createTag({id:t,name:n});return d(o)?F(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=E.tombstoneTag(t);return d(n)?F(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=E.restoreTag(t,n);return d(o)?F(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=E.createContributor({id:t,name:n});return d(o)?F(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=E.renameContributor(t,n);return d(o)?F(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=E.tombstoneContributor(t);return d(n)?F(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=E.restoreContributor(t,n);return d(o)?F(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=E.tag(t,n);return d(o)?F(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=E.untag(t,n);return d(o)?F(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=E.assign(t,n);return d(o)?F(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=E.unassign(t,n);return d(o)?F(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=E.moveNodeToRank({id:t,parentId:n,rank:o});return d(r)?F(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=E.editValue(t,n);return d(o)?F(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=E.getNode(t);if(!r)return F("Unable to locate issue",e);if(!P(r))return F("Can only close issues",e);let s=E.getNode(he);if(!s)return F("Unable to locate target swimlane",e);if(n!==s.id)return F("Close target must be closed swimlane",e);let i=E.moveNodeToRank({id:t,parentId:n,rank:o});return d(i)?F(i.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=E.getNode(t);if(!r)return F("Unable to locate issue",e);if(!P(r))return F("Can only reopen issues",e);let s=E.getNode(he);if(!s)return F("Unable to locate closed swimlane",e);if(n===s.id)return F("Cannot reopen issue into closed swimlane",e);if(!E.getNode(n))return F("Reopen parent no longer exists",e);let c=E.moveNodeToRank({id:t,parentId:n,rank:o});return d(c)?F(c.message??"Unable to reopen issue",e):l("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=E.lockNode(t);return d(n)?F(n.message??"Unable to lock node",e):l("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[o,r]of Object.entries(n)){let s=E.getNode(o);if(!s)return F(`Unable to locate node ${o}`,e);if(s.parentNodeId!==t)return F(`Node ${o} is not child of ${t}`,e);let i=E.updateNode({...s,rank:r});if(d(i))return F(i.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=E.createComment({id:t,issue:n,authorId:o,authorName:E.getContributor(o)?.name??"Unknown",md:r,deleted:!1});return d(s)?F(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=E.getComment(t);if(!r)return F("Unable to locate comment",e);if(r.issue!==n)return F("Comment does not belong to issue",e);let s=E.editComment(t,o);return d(s)?F(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=E.getComment(t);if(!o)return F("Unable to locate comment",e);if(o.issue!==n)return F("Comment does not belong to issue",e);let r=E.deleteComment(t);return d(r)?F(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:i}=e.payload,c=E.createAttachment({id:t,issue:n,hash:o,ext:r,name:s,bytes:i,deleted:!1});return d(c)?F(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=E.getAttachment(t);if(!o)return F("Unable to locate attachment",e);if(o.issue!==n)return F("Attachment does not belong to issue",e);let r=E.deleteAttachment(t);return d(r)?F(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=E.linkUserId({contributorId:t,userId:e.userId});return d(n)?F(n.message??"Unable to link contributor",e):l("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};cn=e=>{let t=ru(()=>{let n=Qe===null;n&&(Qe={appLog:[],nodeLog:new Map,virtualNodeIds:new Set,genesisApplied:!1});try{let o=e.map(r=>Nn(r));if(n&&Qe){let r=yy(Qe);if(r)return e.map(()=>r)}return o}finally{n&&(Qe=null)}});return d(t)?e.map(()=>a(t.message)):t.value}});var Ca,su=h(()=>{"use strict";Ca=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown"});import Ee from"node:fs";import Kn from"node:path";import{ulid as Iy}from"ulid";var Bs,Aa,au,du,wa,cu,lu,Us,uu,Ey,Sy,mu,Ry,pu,Ny,fu,Cy,Os,iu,$s,Yn=h(()=>{"use strict";R();ae();Bs="~pending",Aa=/~pending(-[0-9a-z]+)*$/i,au=/-f(\d+)$/,du=e=>{let t=e.indexOf(".");return t===-1?`${e}${Bs}`:e.slice(0,t)+Bs+e.slice(t)},wa=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},cu=e=>{let[t,n]=wa(e);return Aa.test(t)?t.replace(Aa,"")+n:null},lu=e=>e.replace(Aa,""),Us=e=>e.endsWith(".jsonl")&&cu(e)!==null,uu=e=>{let[t]=wa(e),n=au.exec(t);return n&&Us(e)?Number(n[1]):null},Ey=e=>du(e).replace(Bs,`${Bs}-${Iy().toLowerCase()}`),Sy=(e,t)=>{let[n,o]=wa(e);return`${n.replace(au,"")}-f${t}${o}`},mu=(e,t)=>Kn.join(kt(e),du(t)),Ry=(e,t)=>Math.max(0,Ee.statSync(e).size-(uu(t)??0)),pu=e=>{let t=kt(e);try{return Ee.existsSync(t)?Ee.readdirSync(t).filter(Us).some(n=>Ry(Kn.join(t,n),n)>0):!1}catch{return!0}},Ny=3,fu=(e,t)=>{for(let n=1;;n++){let o=Ee.openSync(e,"a"),r;try{Ee.writeSync(o,t),r=Ee.fstatSync(o).ino}finally{Ee.closeSync(o)}let s;try{s=Ee.statSync(e).ino}catch{s=null}if(s===r||n>=Ny)return}},Cy=e=>{let t;try{t=Ee.openSync(e,"r")}catch{return!0}try{let{size:n}=Ee.fstatSync(t);if(n===0)return!0;let o=Buffer.alloc(1);return Ee.readSync(t,o,0,1,n-1),o[0]===10}finally{Ee.closeSync(t)}},Os=10,iu=(e,t,n=!1)=>{let o=n?t.length:t.lastIndexOf(Os)+1;if(o===0)return{bytes:0,lines:0};let r=t.subarray(0,o);if(r.toString("utf8").trim().length===0)return{bytes:o,lines:0};Ee.appendFileSync(e,Buffer.concat([Buffer.from(Cy(e)?"":`
39
+ `),r,Buffer.from(r[r.length-1]===Os?"":`
40
+ `)]));let s=0;for(let i of r)i===Os&&s++;return r[r.length-1]!==Os&&s++,{bytes:o,lines:s}},$s=(e,t)=>{let n=kt(e);if(!Ee.existsSync(n))return l("No events directory",0);try{let o=Ee.readdirSync(n).filter(i=>cu(i)===t),r=Kn.join(n,t),s=0;for(let i of o){let c=uu(i);if(c!==null){let f=Kn.join(n,i),y=Ee.readFileSync(f).subarray(c);s+=iu(r,y,!0).lines,Ee.rmSync(f,{force:!0});continue}let u=/~pending-/i.test(i)?i:Ey(t),m=Kn.join(n,u);u!==i&&Ee.renameSync(Kn.join(n,i),m);let p=iu(r,Ee.readFileSync(m));s+=p.lines,Ee.renameSync(m,Kn.join(n,Sy(u,p.bytes)))}return l("Folded pending logs",s)}catch(o){return a(`Unable to fold pending event logs in ${n}: ${o instanceof Error?o.message:String(o)}`)}}});import{existsSync as Ay,readdirSync as wy,statSync as Ty}from"node:fs";import ky from"node:path";var Xn,gu,Ta,Cn,hu,vu,yu,kr=h(()=>{"use strict";ae();Xn=e=>{let t=kt(e);return Ay(t)?wy(t).filter(n=>n.endsWith(".jsonl")).sort().map(n=>{let{size:o,mtimeMs:r}=Ty(ky.join(t,n));return`${n}:${o}:${r}`}).join("|"):"none"},gu=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),Ta=(e,t,n)=>{let o=gu(t),r=Xn(e),s=gu(r);for(let[i,c]of s)if(i!==n&&o.get(i)!==c)return null;for(let i of o.keys())if(i!==n&&!s.has(i))return null;return r},Cn=null,hu=e=>Cn&&Cn.root===e?Cn.signature:null,vu=(e,t)=>{Cn={root:e,signature:t}},yu=(e,t)=>{if(!Cn||Cn.root!==e)return;let n=Ta(e,Cn.signature,t);Cn=n===null?null:{root:e,signature:n}}});var My,Py,bu,xu,ka=h(()=>{"use strict";My=["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"],Py=new Set(My),bu=e=>Py.has(e),xu=e=>({action:e.action,payload:e.payload})});import{z}from"zod";var q,Pt,An,js,Ma,Ly,Iu,Eu=h(()=>{"use strict";R();q=z.string().min(1),Pt=z.string(),An=z.string(),js=z.looseObject({id:q}),Ma=z.looseObject({id:q,name:Pt,parent:q,rank:An}),Ly={"init.workspace":z.looseObject({id:q,name:Pt,rank:An}),"add.workspace":z.looseObject({id:q,name:Pt,rank:An}),"add.board":Ma,"add.swimlane":Ma,"add.issue":Ma,"add.field":z.looseObject({id:q,name:Pt,parent:q,rank:An}),"edit.title":z.looseObject({id:q,name:Pt}),"delete.node":js,"lock.node":js,"move.node":z.looseObject({id:q,parent:q,rank:An}),"edit.description":z.looseObject({id:q,md:z.string()}),"close.issue":z.looseObject({id:q,parent:q,rank:An}),"reopen.issue":z.looseObject({id:q,parent:q,rank:An}),"create.tag":z.looseObject({id:q,name:Pt}),"tombstone.tag":js,"restore.tag":z.looseObject({id:q,name:Pt}),"create.contributor":z.looseObject({id:q,name:Pt}),"rename.contributor":z.looseObject({id:q,name:Pt}),"tombstone.contributor":js,"restore.contributor":z.looseObject({id:q,name:Pt}),"link.contributor.user":z.looseObject({contributor:q}),"add.issue.assignee":z.looseObject({id:q,assignee:q}),"remove.issue.assignee":z.looseObject({id:q,assignee:q}),"add.issue.tag":z.looseObject({id:q,tag:q}),"remove.issue.tag":z.looseObject({id:q,tag:q}),"add.issue.comment":z.looseObject({id:q,issue:q,md:z.string()}),"edit.issue.comment":z.looseObject({id:q,issue:q,md:z.string()}),"delete.issue.comment":z.looseObject({id:q,issue:q}),"add.issue.attachment":z.looseObject({id:q,issue:q,hash:z.string().min(1),ext:z.string().min(1),name:Pt,bytes:z.number()}),"delete.issue.attachment":z.looseObject({id:q,issue:q}),"rebalance.children":z.looseObject({parent:q,ranks:z.record(z.string(),An)})},Iu=(e,t)=>{let o=Ly[e].safeParse(t);return o.success?l("Payload is readable",void 0):a(`${e}: ${o.error.issues.map(r=>`${r.path.join(".")||"payload"} ${r.message}`).join(", ")}`)}});import Ws from"node:fs";import qs from"node:path";import{decodeTime as Dy}from"ulid";import{z as Pa}from"zod";function Mr(e,t){let n=kt(e),o=Xn(e);if(!Ws.existsSync(n))return l("No events found",[]);let r=Ws.readdirSync(n).filter(c=>c.endsWith(".jsonl")).map(c=>qs.join(n,c)),s=[];for(let c of r){let u=Wy(c,t);if(d(u))return a(u.message);s.push(...u.value)}let i=qy(s);return un={root:e,signature:o,edge:i.at(-1)?.id?.[0]??null},l("All events loaded",i)}function Et(e){let t=[],n=Mr(e,t);if(d(n))return a(n.message);let o=Da(n.value,t);return d(o)?a(o.message):l("Loaded merged events",{events:o.value,unreadable:t})}function Fa(e){let t=Mr(e);return d(t)?a(t.message):l("Loaded event actors",t.value.map(({userId:n,userName:o})=>({userId:n,userName:o})))}function Jn(e){let t=Et(e);return d(t)?a(t.message):l("Loaded merged events",t.value.events)}function _a(e,t){let n=Mr(e);if(d(n))return a(n.message);let{appliedEvents:o,unappliedEvents:r}=Gy(n.value,t),s=Da(o);if(d(s))return a(s.message);let i=Da(r);return d(i)?a(i.message):l("Loaded merged events before time",{appliedEvents:s.value,unappliedEvents:i.value})}function Su(e=process.cwd()){let t=Xn(e);if(un&&un.root===e&&un.signature===t)return l("Loaded edge reference, unchanged",un.edge);let n=Mr(e);return d(n)?a(n.message):l("Loaded edge reference",n.value.at(-1)?.id?.[0]??null)}function Ru(e,t,n){if(!un||un.root!==e)return;let o=Ta(e,un.signature,t);un=o===null?null:{root:e,signature:o,edge:n}}function Oa(e){let t=Mr(e);if(d(t))return a(t.message);let n=Nu(t.value);return l("Loaded effective event times",new Map(t.value.map((o,r)=>[o.id[0],n[r]??null])))}var Fy,Hs,_y,Oy,By,Uy,$y,jy,Hy,Da,Wy,un,La,qy,Nu,Gy,St=h(()=>{"use strict";xt();R();ae();kr();Ke();ka();Ce();Eu();Yn();Fy=Pa.object({userId:Pa.string().min(1).default("unknown"),userName:Pa.string().min(1).default("unknown")}),Hs=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},_y=/^[0-9a-hjkmnp-tv-z]{26}$/i,Oy=e=>_y.test(e)?e.toUpperCase():e,By=e=>{let t=qs.basename(e,".jsonl"),n=t.indexOf("."),o=lu(n===-1?t:t.slice(0,n)),r=n===-1?void 0:t.slice(n+1),s=Fy.safeParse({userId:Oy(o),userName:r});return s.success?l("Parsed event file actor",s.data):a(`Invalid event file name ${qs.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},Uy=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?a(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?a("Invalid persisted event: action key is missing or invalid"):l("Resolved persisted action",t[0])},$y=(e,t)=>t in e,jy=({id:e,action:t,payload:n,userId:o,userName:r})=>({id:e,action:t,payload:n,userId:o,userName:r}),Hy=e=>{let{userId:t,userName:n,...o}=e,r=Uy(o);if(d(r))return a(r.message);let s=r.value,i=e.id?.[0];return i?$y(o,s)?l("Decoded persisted event",jy({id:i,action:s,payload:o[s],userId:t,userName:n})):a(`Persisted event is missing payload for action: ${s}`):a("Persisted event is missing id")},Da=(e,t)=>{let n=[],o=new Map,r=new Map;for(let s of e){if(!Au(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:Hs(s)});continue}let i=Hy(s);if(d(i)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:i.message,targetNodeId:Hs(s)});continue}let c=i.value.action;if(!bu(c)){o.set(c,(o.get(c)??0)+1),t?.push({eventId:s.id[0],reason:"unknown-action",detail:c,targetNodeId:Hs(s)});continue}let u=Iu(c,i.value.payload);if(d(u)){t?.push({eventId:s.id[0],reason:"invalid-payload",detail:u.message,targetNodeId:Hs(s)});continue}n.push(i.value)}if(o.size>0){let s=[...o.entries()].map(([i,c])=>`${i} (x${c})`).join(", ");J.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(([i,c])=>`v${i} (x${c})`).join(", ");J.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${s}. Upgrade to apply them.`)}return l("Decoded reconstructed events",n)},Wy=(e,t)=>{if(!Ws.existsSync(e))return l("Event file missing",[]);let n=By(e);if(d(n))return a(n.message);let o=Ws.readFileSync(e,"utf8"),r=[],s=qs.basename(e),i=(c,u)=>{t?.push({eventId:null,reason:"corrupt-line",detail:`${s}:${c} (${u})`,targetNodeId:null})};for(let[c,u]of o.split(`
41
+ `).entries()){let m=u.trim();if(!m)continue;let p;try{p=JSON.parse(m)}catch{i(c+1,"invalid JSON");continue}let f=Cu(p);if(d(f)){i(c+1,f.message);continue}r.push({...f.value,userId:n.value.userId,userName:n.value.userName})}return l("Parsed persisted events file",r)};un=null;La=(e,t)=>{let n=e.id[0].localeCompare(t.id[0]);return n!==0?n:JSON.stringify(e).localeCompare(JSON.stringify(t))},qy=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 y=n.get(f)??[];y.push(m),n.set(f,y)}for(let m of n.values())m.sort(La);let o=[],r=new Set,s=m=>{let p=[m];for(;p.length>0;){let f=p.pop(),y=f.id[0];if(r.has(y))continue;o.push(f),r.add(y);let I=n.get(y)??[];for(let S=I.length-1;S>=0;S--)p.push(I[S])}},i=(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 i)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(La);for(let m of c)s(m);let u=e.filter(m=>!r.has(m.id[0])).sort(La);for(let m of u)s(m);return o},Nu=e=>pr(e.map(t=>{try{return Dy(t.id[0])}catch{return null}}));Gy=(e,t)=>{let n=new Set,o=[],r=[],s=Nu(e);for(let i=0;i<e.length;i++){let c=e[i],u=c.id[0],m=c.id[1],p=s[i]??null;!(p!==null&&p<t)||m&&n.has(m)?(n.add(u),r.push(c)):o.push(c)}return{appliedEvents:o,unappliedEvents:r}}});import Ba from"node:path";import{decodeTime as zy,monotonicFactory as Vy}from"ulid";import{z as Qn}from"zod";function Ua(e,t){let n;if(t&&t.current!==void 0)n=t.current;else{let r=Su(e);if(d(r))return a(r.message);n=r.value}let o=n?wu(Xy(n)):wu();return l("Minted event id",[o,n])}function Gs({event:e,rootDir:t,edge:n,id:o}){try{let r=Zl(t);if(d(r))return r;let s=nb(t,{userId:e.userId,userName:e.userName});if(d(s))return s;let i=l("Resolved pending event log path",mu(t,Ba.basename(s.value))),c=o?l("Minted event id",o):Ua(t,n);if(d(c))return a(c.message);let[u,m]=c.value,p=ob(xu(e),[u,m]);if(d(p))return a(p.message);fu(i.value,`${JSON.stringify(p.value)}
42
+ `),n&&(n.current=u);let f=Ba.basename(i.value);return Ru(t,f,u),yu(t,f),l("Event persisted",{path:i.value,entry:p.value})}catch(r){let s=r instanceof Error?r.message:"Unknown persist error";return a(`Failed to persist event: ${s}`)}}var Tu,wu,Ky,Yy,Xy,ku,Jy,Qy,Cu,Zy,eb,Au,tb,oe,Zn,nb,ob,Ce=h(()=>{"use strict";xt();Un();R();We();ae();su();Ke();Yn();St();kr();ka();Tu=1,wu=Vy(),Ky=0xffffffffffff,Yy=ys,Xy=e=>{let t=Date.now(),n;try{n=zy(e)}catch{return t}return n>=Ky?t:n>t+Yy?(J.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)},ku=Qn.tuple([Qn.string().min(1),Qn.string().min(1).nullable()]),Jy=Qn.looseObject({v:Qn.literal(Tu),id:ku}),Qy=Qn.looseObject({v:Qn.number().int().positive(),id:ku}),Cu=e=>{let t=Qy.safeParse(e);return t.success?l("Parsed persisted event envelope",t.data):a(`Invalid persisted event envelope: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Zy=[1],eb=new Set(Zy),Au=e=>eb.has(e),tb=e=>{let t=Jy.safeParse(e);return t.success?l("Parsed persisted event",t.data):a(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},oe=()=>{let{userName:e,userId:t}=Ie();return e?t?vs(t)?ur(e)?l("Successfully resolved actor ID",{userId:t,userName:e}):a("Invalid user name in config"):a("Invalid user ID in config"):a("User ID not configured"):a("User name not configured")},Zn=({userId:e,userName:t})=>`${Ca(e)}.${Ca(t)}.jsonl`,nb=(e,{userId:t,userName:n})=>{let o=Zn({userId:t,userName:n});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(o))return a(`Invalid event log file name: ${o}`);let s=Ba.join(kt(e),o);return l("Successfully resolved event log path",s)},ob=(e,t)=>{let n={[e.action]:e.payload,v:Tu,id:t};return tb(n)}});import{ulid as rb}from"ulid";function Mu(e,t,n){let o=Ua(t,n);if(d(o))return a(o.message);let r={...e,id:o.value[0]},s=Nn(r);if(s.status!==tn.Success)return s;let i=Gs({event:r,rootDir:t,edge:n,id:o.value});return d(i)?i:s}function L(e,t){if(e.length===0||!e[0])return a("No events provided");if(g().readOnly)return a(g().readOnlyReason??"Cannot change the board while time travelling");let n={},o=sb(e[0],t,n);if(d(o))return o;let r=e.map(i=>Mu(i,t,n)),s=r.filter(d);return s.length>0?a("Materialize and persist failed: "+s.map(i=>i.message).join(", ")):l("Materialization succeeded",r.map(i=>i.value))}var sb,Se=h(()=>{"use strict";R();ne();M();ln();Ce();sb=(e,t,n)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return l("Contributor write already in flight",void 0);let o=E.getContributor(e.userId),r={id:rb(),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=Mu(r,t,n);return d(s)?a(s.message):l("Contributor name recorded",void 0)}});var eo,$a,Pu=h(()=>{"use strict";Je();eo=e=>e.trim().toLocaleLowerCase(),$a=(e,t)=>eo(e).includes(eo(t))});var ib,ab,Lu,Du,db,cb,Fu,_u=h(()=>{"use strict";M();Je();Pu();ib=e=>{let{tags:t}=g();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},ab=e=>{let{contributors:t}=g();return(e.props.assignees??[]).map(n=>{let o=t[n];return o?o.name:void 0}).filter(n=>!!n)},Lu=null,Du=new Map,db=()=>{let e=g().eventLog??[];if(e===Lu)return Du;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 Lu=e,Du=t,t},cb=e=>{let{contributors:t}=g(),n=db().get(e.id);return n?[...n].map(o=>t[o]?.name).filter(o=>!!o):[]},Fu=(e,t)=>{let n=eo(t.value);if(!n)return!0;switch(t.target){case"title":return $a(e.title??"",n);case"description":return $a(e.props.description??"",n);case"tag":return ib(e).map(eo).some(r=>r.includes(n));case"assignee":return ab(e).map(eo).some(r=>r.includes(n));case"actor":return cb(e).map(eo).some(r=>r.includes(n));case"ref":return Cr(e.id,t.value);default:return!0}}});var Ou,lb,Bu,Uu,ja=h(()=>{"use strict";K();_u();Ou=(e,t)=>e.rank.localeCompare(t.rank),lb=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,Bu=(e,t)=>Object.values(e).filter(n=>lb(n,t)).sort(Ou),Uu=(e,t)=>{let n={};for(let o of Object.values(e)){if(P(o)&&t.length>0&&!t.every(s=>Fu(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(Ou);return n}});var $u,zs,ge,ju,Hu,jt,wn,yt=h(()=>{"use strict";Al();Se();R();M();ja();yo();$u=e=>zs(ge(e),{at:"end"}),zs=(e,t={at:"end"})=>{let n=r=>d(r)?l("Rank space exhausted",{rank:"",needsRebalance:!0}):l("Resolved rank",{rank:r.value,needsRebalance:!1});if(e.length===0)return n(qe(void 0,void 0));let o=()=>n(qe(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let r=e[0];return r?n(qe(void 0,r.rank)):a("Unable to resolve first sibling")}case"end":{let r=e[e.length-1];return r?n(qe(r.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let r=ju(e,t.sibling),s=r<0?void 0:e[r];if(!s)return o();let i=r>0?e[r-1]:void 0;return n(qe(i?.rank,s.rank))}case"after":{let r=ju(e,t.sibling),s=r<0?void 0:e[r];if(!s)return o();let i=r<e.length-1?e[r+1]:void 0;return n(qe(s.rank,i?.rank))}}},ge=e=>{let t=g();if(!Wu()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return Bu(t.nodes,e)},ju=(e,t)=>e.findIndex(n=>n.id===t),Hu=(e,t,n={at:"end"})=>zs(ge(t).filter(o=>o.id!==e),n),jt=(e,t,n,o,r)=>{let s=Hu(t,e,n);if(d(s))return s;if(!s.value.needsRebalance)return l("Resolved rank",s.value.rank);let i=aa(e,o);if(d(i))return i;let c=L([i.value],r);if(d(c))return c;let u=Hu(t,e,n);return d(u)?u:u.value.needsRebalance?a("Rank rebalance failed to create space"):l("Resolved rank after rebalance",u.value.rank)},wn=(e,t,n)=>{let o=$u(e);if(d(o))return o;if(!o.value.needsRebalance)return l("Resolved rank",o.value.rank);let r=aa(e,t);if(d(r))return r;let s=L([r.value],n);if(d(s))return s;let i=$u(e);return d(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):l("Resolved rank after rebalance",i.value.rank)}});var U,qu,Gu,ut=h(()=>{"use strict";M();U={exit(){process.exit(0)},enterChildNode(){let e=g(),t=e.contextNode,n=Math.max(0,e.selectedIndex),o=se(t.id),r=o[n];r&&(t.context==="FIELD"&&o.length===0||r.context==="COMMENT"||r.context==="TEXT"||U.navigate({contextNode:r,selectedIndex:se(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=se(n.id),r=o.findIndex(({id:i})=>i===e.id),s=o.length===0?-1:r>=0?r:0;U.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>qu(1),navigateToPreviousItem:()=>qu(-1),navigateToNextContainer:()=>Gu(1),navigateToPreviousContainer:()=>Gu(-1),navigate:({contextNode:e,selectedIndex:t})=>{N({contextNodeId:e.id,selectedIndex:t})}},qu=e=>{let{selectedIndex:t,contextNode:n}=g(),o=se(n.id).length;if(o===0)return;let s=(Math.max(0,t)+e+o)%o;U.navigate({selectedIndex:s,contextNode:n})},Gu=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=se(r.id),i=s.findIndex(y=>y.id===t.id);if(i<0)return;let c=s.at(i+e)??s.at(0);if(!c)return;let u=se(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 Vu,Ku,ub,Vs,Yu,zu,mb,Xu,Ju=h(()=>{"use strict";K();R();yt();M();ut();Vu=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Ku=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=g();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},ub=e=>{let t=g().nodes[e];return!!t&&!t.isDeleted&&at(t)&&t.childRenderAxis==="vertical"},Vs=(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:Vu(t,r.length)}),!0},Yu=e=>{let{nodes:t}=g(),n=t[e];if(!n||n.isDeleted)return!1;let o=n.parentNodeId;if(!o)return Vs(n.id,0);let r=t[o];if(!r||r.isDeleted)return!1;let i=ge(r.id).findIndex(c=>c.id===n.id);return i>=0?(U.navigate({contextNode:r,selectedIndex:i}),!0):Yu(r.id)},zu=e=>{let{nodes:t}=g(),n=e,o=new Set;for(;n&&!o.has(n);){if(o.add(n),Yu(n))return!0;n=t[n]?.parentNodeId}return!1},mb=e=>{if(!e)return!1;let t=g().nodes[e];return!!t&&!t.isDeleted},Xu=e=>{let{nodes:t,rootNodeId:n}=g();if(ub(e.contextNodeId)&&Vs(e.contextNodeId,e.selectedIndex))return l("Restored navigation inside text container",null);if(mb(e.selectedNodeId)&&e.selectedNodeId&&zu(e.selectedNodeId))return l("Restored navigation to selected node or ancestor",null);if(Vs(e.contextNodeId,e.selectedIndex))return l("Restored navigation to previous container",null);if(e.parentNodeId&&Vs(e.parentNodeId,e.selectedIndex))return l("Restored navigation to previous parent",null);if(zu(e.contextNodeId))return l("Restored navigation to previous container or ancestor",null);let o=t[n];if(!o||o.isDeleted)return a("Unable to restore navigation");let r=ge(o.id);return U.navigate({contextNode:o,selectedIndex:Vu(e.selectedIndex,r.length)}),l("Restored navigation to root",null)}});import{monotonicFactory as pb,ulid as Ht}from"ulid";function fb(){let e=ze();if(d(e))return a("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return a("No workspace found in event log");let[o]=se(n.id),[r]=o?se(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 gb(){let e=fb();return d(e)?e:U.navigate(e.value)}function Qu({userId:e,userName:t}){let n=Pr(),o=Pr(),r=Pr(),s=Pr(),i=Pr(),c=qe(void 0,void 0);if(d(c))return c;let u=qe(void 0,void 0);if(d(u))return u;let m=qe(u.value,void 0);if(d(m))return m;let p=qe(void 0,void 0);if(d(p))return p;let f=qe(p.value,void 0);if(d(f))return f;let y=qe(f.value,void 0);if(d(y))return y;let I=qe(void 0,void 0);return d(I)?I:l("Created default events",[{id:Ht(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:c.value}},{id:Ht(),userId:e,userName:t,action:"create.contributor",payload:{id:e,name:t}},{id:Ht(),userId:e,userName:t,action:"add.board",payload:{id:o,name:"Default",parent:n,rank:u.value}},{id:Ht(),userId:e,userName:t,action:"add.swimlane",payload:{id:r,name:"Todo",parent:o,rank:p.value}},{id:Ht(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:o,rank:f.value}},{id:Ht(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:o,rank:y.value}},{id:Ht(),userId:e,userName:t,action:"add.board",payload:{id:Ds,name:"Closed",parent:n,rank:m.value}},{id:Ht(),userId:e,userName:t,action:"add.swimlane",payload:{id:he,name:"Closed",parent:Ds,rank:I.value}},{id:Ht(),userId:e,userName:t,action:"lock.node",payload:{id:Ds}},{id:Ht(),userId:e,userName:t,action:"lock.node",payload:{id:he}}])}function Wt(e,t=[]){if(hb())return l("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Pe.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=Tr(s);return d(i)?i:(N({hasProjectDefinition:!1,mode:b.DEFAULT}),l("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return a("Initialized Epiq project has no workspace init event");let n=cn(e),{fatal:o,skipped:r}=zn(n);return o.length>0?a(`Materializing failed:
43
+ ${o.map(s=>s.message).join(`
44
+ `)}`):(Vn(r),gb(),N({hasProjectDefinition:!0}),vb(t),l("State booted successfully",null))}var Pr,hb,vb,to=h(()=>{"use strict";xt();ut();pe();R();Gn();M();yo();ln();dn();Pr=pb();hb=()=>{let e=ze();if(d(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},vb=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(", ");J.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(", ");J.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 yb}from"ws";var bb,Zu,em=h(()=>{"use strict";bb=new Set,Zu=e=>{let t=JSON.stringify(e);for(let n of bb)n.readyState===yb.OPEN&&n.send(t)}});var Ks,Eo,no,Ha,Ys,Re,Lr=h(()=>{"use strict";em();R();M();Ks=e=>{It()&&(N({syncStatus:e}),Zu({type:"sync-status",payload:e}))},Eo=(e="Syncing...")=>{Ks({status:"syncing",msg:e})},no=(e="Synced")=>{Ks({status:"synced",msg:e})},Ha=e=>{Ks({status:"failed",msg:e})},Ys=e=>{Ks({status:"offline",msg:e})},Re=e=>(Ha(e),a(e))});var So,tm,re,Xs=h(()=>{"use strict";R();So=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),tm=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)=>(d(t)&&logger.info(`[${e}]:failed`,t.message),t)});import qt from"node:fs";import Dr from"node:path";var Ro,nm,om,rm,xb,sm,Ib,Eb,im,Wa=h(()=>{"use strict";ct();R();Yn();ae();Ro=e=>e.split(`
45
+ `).filter(t=>t.trim().length>0),nm=e=>{let t=Dr.join(e,Ge,an);try{if(!qt.existsSync(t))return l("No events directory",[]);let n=qt.readdirSync(t).filter(o=>o.endsWith(".jsonl")).filter(o=>Ro(qt.readFileSync(Dr.join(t,o),"utf8")).length>0);return l("Looked for stranded event logs",n)}catch(n){return a(`Unable to check ${t} for event logs before deleting it: ${n instanceof Error?n.message:String(n)}`)}},om=e=>Dr.join(e,Ge,an),rm=e=>{let t=om(e),n=new Map;try{if(!qt.existsSync(t))return n;for(let o of qt.readdirSync(t))o.endsWith(".jsonl")&&(Us(o)||n.set(o,Ro(qt.readFileSync(Dr.join(t,o),"utf8"))))}catch{return n}return n},xb=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},sm=(e,t)=>{if(t.size===0)return[];let n=om(e),o=[];for(let[r,s]of t){if(s.length===0)continue;let i=Dr.join(n,r);try{let c=qt.existsSync(i)?qt.readFileSync(i,"utf8"):null,u=new Set(c===null?[]:Ro(c)),m=s.filter(f=>!u.has(f)).filter(xb);if(m.length===0)continue;qt.mkdirSync(n,{recursive:!0});let p=c!==null&&c.length>0&&!c.endsWith(`
46
+ `);qt.appendFileSync(i,`${p?`
29
47
  `:""}${m.join(`
30
48
  `)}
31
- `,"utf8"),r.push(`${o} (${m.length})`)}catch{continue}}return r},Ph=(e,t)=>{let n=new Set(rr(t));return rr(e).filter(r=>!n.has(r))},Dh=(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
- `),il=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let r=await Ue({args:["show",`HEAD:${t}`],cwd:e});if(r.exitCode!==0)return l("No committed log to compare against",void 0);let o=Ph(r.stdout,n);return o.length>0?i(Dh(t,o,rr(r.stdout).length)):l("Event log only grew",void 0)}});import Wt from"node:fs";import Yr from"node:path";var Oh,dl,al,Bh,Ki,Yi,Fh,_h,_n,Uh,$h,ds,cl,ll,ul,Xr,ml,Jr=v(()=>{"use strict";N();Rt();Uo();Pr();zi();pt();ut();Oh="[epiq:init-repo]",dl=async e=>{let t=await Ue({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 r=await W({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(a(r))return i(r.message);let o=await W({args:["commit-tree",r.value.stdout.trim(),"-m",Oh],cwd:e});if(a(o))return i(o.message);let s=await W({args:["update-ref","HEAD",o.value.stdout.trim()],cwd:e});return a(s)?i(s.message):l("Created initial commit",!0)},al=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Bh=async e=>{let t=await Ho(e);if(a(t))return i(t.message);let n=await Vd(e);return a(n)?i(n.message):l("Built sync commit message",`[sync|branch:${al(t.value)}:sha:${al(n.value)}]`)},Ki=async({repoRoot:e,stateBranchName:t})=>{X.info(`Creating ${t}`);let n=await W({args:["commit-tree",Zd,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return i(`Failed to create state branch commit
34
- ${n.message}`);let r=n.value.stdout.trim(),o=await W({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return a(o)?i(`Failed to create ${t}
35
- ${o.message}`):l("Created state branch",!0)},Yi=async({repoRoot:e,stateBranchName:t})=>{let n=await jo({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 r=await Or({repoRoot:e});if(a(r))return i(`Ensure local state branch failed
37
- `+r.message);let o=r.value,s=o?await vi({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(o&&d){let c=await he.fetch({cwd:e,remote:nt,branch:t});if(a(c))return i(`Failed to fetch ${t} from remote
39
- ${c.message}`)}if(d){let c=await W({args:["branch","--track",t,`${nt}/${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 Ki({repoRoot:e,stateBranchName:t})},Fh=async({repoRoot:e,branch:t})=>{let n=await W({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return i(n.message);let r=n.value.stdout.split(`
41
- `),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return l("Found worktree for branch",o)}return l("No worktree found for branch",null)},_h=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Br(Yr.dirname(t));if(a(r))return i(`Failed to create state branch worktree
42
- `+r.message);if(Wt.existsSync(t)&&!Wt.existsSync(Yr.join(t,".git"))){let s=nl(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"),rc(t)}X.info("Creating state branch worktree");let o=await he.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(o)?i(`Failed to create state branch worktree
44
- ${o.message}`):l("Created state branch worktree",!0)},_n=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await Fh({repoRoot:e,branch:n});if(a(r))return i(r.message);let o=Dr(t),s=r.value?Dr(r.value):null;if(s&&s===o&&Wt.existsSync(s))return l("State branch already checked out in expected worktree",!1);if(s&&s!==o){let u=await Yd(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 ${o}, 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 he.worktreeRemove({cwd:e,worktreeRoot:s});if(a(m))return i(`Failed to remove existing state branch worktree
46
- ${m.message}`)}if(s&&!Wt.existsSync(s)){X.info("Pruning stale state branch worktree");let u=await he.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
47
- ${u.message}`)}let d=await qd({repoRoot:e,worktreeRoot:t});if(a(d))return i(d.message);let c=Wt.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 he.worktreePrune({cwd:e});if(a(u))return i(`Failed to prune stale worktrees
48
- ${u.message}`)}return _h({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Uh=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Ho(e);if(a(n))return i(n.message);if(n.value===t)return l("State branch already checked out",!1);(await Ue({cwd:e,args:["rebase","--abort"]})).exitCode===0&&X.info("Aborted stale state branch rebase");let o=await he.checkout({cwd:e,branch:t});return a(o)?i(`Failed to checkout ${t}
49
- ${o.message}`):l("Checked out state branch",!0)},$h=async({repoRoot:e,stateBranchRoot:t})=>{let n=await yi(t);if(a(n))return i(n.message);if(n.value)return l("State branch upstream already configured",!1);let r=await Or({repoRoot:t});if(a(r))return i(r.message);if(!r.value)return l("No remote available for state branch upstream",!1);let o=Zt(e);if(a(o))return o;let s=o.value,d=await vi({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 he.fetch({cwd:t,remote:nt,branch:s});if(a(c))return i(`Failed to fetch ${s}
50
- ${c.message}`);let u=await he.setUpstream({cwd:t,branch:s,upstream:`${nt}/${s}`});return a(u)?i(`Failed to set state branch upstream
51
- ${u.message}`):l("Configured state branch upstream",!0)},ds=async({stateBranchRoot:e,eventFileName:t})=>{let n=ec(t),r=Yr.join(e,n);if(!Wt.existsSync(r))return l("No event file to stage",null);let o=await il({stateBranchRoot:e,relativePath:n,workingContent:Wt.readFileSync(r,"utf8")});if(a(o))return i(o.message);let s=await he.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)},cl=async({stateBranchRoot:e})=>{let t=tc(),n=Yr.join(e,t);if(!Wt.existsSync(n))return l("No media directory to stage",null);let r=await he.stage({cwd:e,pathspec:[t],ignoreRemoval:!0});return a(r)?i(`Failed to stage state branch media files
53
- ${r.message}`):l("Staged state branch media files",t)},ll=async({stateBranchRoot:e})=>{let t=Ei();if(!Wt.existsSync(Yr.join(e,t)))return l("No event log attributes to stage",null);let n=await he.stage({cwd:e,pathspec:[t]});return a(n)?i(`Failed to stage event log attributes
54
- ${n.message}`):l("Staged event log attributes",t)},ul=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let r=await Bh(e);return a(r)?i(`Create state branch sync commit failed
55
- `+r.message):er({cwd:t,message:r.value,pathspec:n})},Xr=async({repoRoot:e,stateBranchRoot:t})=>{let n=await yi(t);if(a(n))return i(n.message);let r=Zt(e);if(a(r))return r;let o=r.value,s=n.value?await he.push({cwd:t}):await he.push({cwd:t,remote:nt,branch:o,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)},ml=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Zt(e);if(a(o))return o;let s=o.value,d=[Go(),await Yi({repoRoot:e,stateBranchName:s}),await _n({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Uh({stateBranchRoot:t,stateBranchName:s}),await sc(t),n?await $h({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of d){if(a(c))return i(c.message);r=r||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)}});import cs from"node:fs";import Ji from"node:os";import jh from"node:path";var Hh,pl,Wh,Gh,qh,fl,Xi,gl,Vh,hl,vl=v(()=>{"use strict";N();ut();Rt();Hh="epiq-sync.lock",pl=600*1e3,Wh=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}},Gh=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},qh=e=>e&&(e.hostname!==Ji.hostname()||Gh(e.pid))?Date.now()-e.startedAt>pl:!0,fl=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,Xi=e=>{try{return Wh(cs.readFileSync(e,"utf8"))}catch{return null}},gl=(e,t)=>{let n={pid:process.pid,hostname:Ji.hostname(),startedAt:Date.now(),operation:t};try{return cs.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},Vh=async({worktreeRoot:e,operation:t})=>{let n=await hi(e);if(a(n))return i(n.message);let r=jh.join(n.value,Hh),o=()=>{try{let c=Xi(r);c&&c.pid===process.pid&&cs.rmSync(r)}catch{}};if(gl(r,t))return l("Acquired sync lock",{acquired:!0,release:o});let s=Xi(r);if(!qh(s))return l("Sync lock is held",{acquired:!1,heldBy:s});X.info(`Breaking an abandoned sync lock: ${s?fl(s):"unreadable lock file"}`);try{cs.rmSync(r,{force:!0})}catch{}if(gl(r,t))return l("Acquired sync lock after breaking a stale one",{acquired:!0,release:o});let d=Xi(r);return l("Sync lock taken by another process",{acquired:!1,heldBy:d??{pid:-1,hostname:Ji.hostname(),startedAt:Date.now(),operation:"unknown"}})},hl=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await Vh({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 ${fl(r.value.heldBy)}`),l("State worktree is held by another process",null);let{release:o}=r.value;try{return l("Ran under the sync lock",await n())}finally{o()}}});import zh from"node:fs";var Kh,Yh,Qi,yl,Xh,ls,Zi=v(()=>{"use strict";N();is();as();Pr();pt();ut();Jr();zi();vl();Kh=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=Q("getRepoRootDir",await mt(e));if(a(n))return i(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=Q("getStateBranchRoot",Ne({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=Q("bootstrapStateBranchStorage",await ml({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 c=Q("hasInProgressGitOperation(stateBranchRoot)",await $o(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:r,stateBranchRoot:s});let u=Q("ensureStateBranchLayout",oc(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}),l("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:d.value}))},Yh=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=Q("stageStateBranchOwnEventFile",await ds({stateBranchRoot:t,eventFileName:n}));if(a(r))return i(r.message);let o=Q("stageStateBranchMediaFiles",await cl({stateBranchRoot:t}));if(a(o))return i(o.message);let s=Q("stageStateBranchEventAttributes",await ll({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 l("Nothing to stage",{createdCommit:!1});let c=Q("hasStagedChanges(after stage)",await Xd(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=Q("createStateBranchSyncCommit",await ul({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}))},Qi=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return tl(n),l(n,{...e,pulled:!1,pushed:!1,offline:!0})},yl=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=Q("ensureSyncReady",await Kh({cwd:e,ensureUpstream:!0}));if(a(n))return Me(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,d=Q("isDetachedHead(stateBranchRoot)",await Jd(o));if(a(d))return Me(d.message);if(logger.debug("[sync] detached state branch check result",{detached:d.value}),d.value)return Me("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,g=Q("getStateBranch",Zt(r));if(a(g))return Me(g.message);let x=g.value;logger.debug("[sync] resolved state branch",{stateBranch:x,stateBranchRoot:o});let S=Q("commitOwnEventFileToStateBranch",await Yh({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(a(S))return Me(S.message);c=S.value.createdCommit,u=S.value.commitSha;let C=Q("hasRemote",await Or({repoRoot:o}));if(a(C))return Me(C.message);if(!C.value)return Qi({repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,bootstrapped:s},"no remote");let M=Q("pullBranchRebaseIfPresent",await Ii({cwd:o,branch:x}));if(a(M))return bi(M.message)?Qi({repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,bootstrapped:s}):Me(M.message);m=M.value;let w=Q("isAheadOfUpstream",await Kd(o));if(a(w))return Me(w.message);if(c||s||w.value){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:o});let T=Q("pushStateBranch",await Xr({stateBranchRoot:o,repoRoot:r}));if(a(T)&&zd(T.message)){let _=Q("pullBranchRebaseIfPresent(retry)",await Ii({cwd:o,branch:x}));if(a(_))return Me(_.message);m=m||_.value,T=Q("pushStateBranch(retry)",await Xr({stateBranchRoot:o,repoRoot:r}))}if(a(T))return bi(T.message)?Qi({repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,bootstrapped:s}):Me(T.message);p=T.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let T=Q("git rev-parse HEAD",await W({args:["rev-parse","HEAD"],cwd:o}));if(a(T))return Me(T.message);u=T.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return ss(p?"Synced and pushed":m||c?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),l("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:c,commitSha:u,pulled:m,pushed:p,bootstrapped:s,offline:!1})},Xh=async(e,t)=>{let n=ol(e);try{return await t()}finally{let r=sl(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 mt(t);if(a(n))return Me(n.message);let r=Ne({repoRoot:n.value});if(a(r))return Me(r.message);let o=r.value;if(!zh.existsSync(o))return yl(e);let s=await hl({worktreeRoot:o,operation:"sync",fn:()=>Xh(o,()=>yl(e))});return a(s)?Me(s.message):s.value===null?l("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 Tt,us,Jh,bl,ea=v(()=>{"use strict";Jc();Vr();Ht();ht();pe();N();k();is();as();Zi();Tt=null,us=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Tt,currentStatus:f().syncStatus?.status,currentMessage:f().syncStatus?.msg}),Tt)return logger.debug("[sync] syncAndReloadState joining existing promise"),Tt;logger.debug("[sync] syncAndReloadState creating promise"),Tt=Jh();try{let e=await Tt;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}),Tt||i(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:f().syncStatus?.status,statusMessageBeforeClear:f().syncStatus?.msg}),Tt=null}},Jh=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:f().mode,syncStatus:f().syncStatus});let e=bl();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:f().mode,message:e.message,syncStatus:f().syncStatus}),e;if(Tt)return Tt;logger.debug("[sync] syncAndReloadState:start");let t=Q("resolveActorId",ge());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=Dn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=Q("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}),Me(`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=Q("loadMergedEvents",jt(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 c=bl();if(c)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:f().mode,message:c.message,syncStatus:f().syncStatus}),c;let u=Kc(),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=Q("bootStateFromEventLog",dn(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=Q("restoreNavigationAnchor",Xc(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}),l("Synced",!0))},bl=()=>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,Il,xl,ta,na,Qr,ra,Qh,El,Zh,Rl,ms=v(()=>{"use strict";N();Be();k();ea();or=3e3,Il=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<or?null:t},xl=0,na=!1,Qr=!1,ra=()=>{if(na)return!0;let e=He();return a(e)?!1:e.value.syncStatus.status==="syncing"},Qh=()=>{let e=ve().autoSyncIntervalMs??1e4,t=Date.now()-xl;return Math.max(0,e-t)},El=()=>{ta||(ta=setTimeout(async()=>{if(ta=void 0,!!ot()){if(ra()){Qr=!0;return}Qr=!1,await Zh()}},Qh()))},Zh=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(ra())return Qr=!0,i("Sync already in progress");na=!0,xl=Date.now(),E({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await us()}finally{na=!1,Qr&&El()}},Rl=()=>{ot()&&(Qr=!0,!ra()&&El())}});import Zr from"node:fs";import eo from"node:path";import{z as sr}from"zod";var ps,ev,tv,nv,Nl,Cl,Sl,Al,Tl,wl,rv,gs,oa,to=v(()=>{"use strict";N();Ft();_o();ne();ps="recent-projects.json",ev=20,tv=sr.object({projectId:sr.string().min(1),root:sr.string().min(1),lastOpenedAt:sr.number().finite()}),nv=sr.object({projects:sr.array(tv)}),Nl=()=>eo.join(Sn(),ps),Cl=e=>eo.basename(e)||e,Sl=e=>{let t=eo.resolve(e);try{return Zr.realpathSync(t)}catch{return t}},Al=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Tl=e=>{if(!_r(e.root))return!1;let t=Lr(e.root);return!a(t)&&t.value===e.projectId},wl=()=>{let e=Nl();if(!Zr.existsSync(e))return l("No recent projects recorded",[]);let t;try{t=JSON.parse(Zr.readFileSync(e,"utf8"))}catch(r){return i(`Invalid ${ps}: ${r instanceof Error?r.message:String(r)}`)}let n=nv.safeParse(t);return n.success?l("Read recent projects",n.data.projects):i(`Invalid ${ps} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},rv=e=>{let t=Nl();try{Zr.mkdirSync(eo.dirname(t),{recursive:!0}),Zr.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
57
- `,"utf8")}catch(n){return i(`Unable to write ${ps}: ${n instanceof Error?n.message:String(n)}`)}return l("Recorded recent project",e)},gs=({exclude:e}={})=>{let t=wl();if(a(t))return t;let n=e===void 0?null:Sl(e);return l("Listed recent projects",t.value.filter(r=>n===null||Sl(r.root)!==n).filter(Tl).sort(Al))},oa=({root:e,now:t=Date.now()})=>{let n=eo.resolve(e),r=Lr(n);if(a(r))return i(r.message);let o=r.value,s=wl(),d=a(s)?[]:s.value,c=[{projectId:o,root:n,lastOpenedAt:t},...d.filter(u=>u.projectId!==o&&u.root!==n)].filter(Tl).sort(Al).slice(0,ev);return rv(c)}});var fs,Ml,kl,Ll,no=v(()=>{"use strict";N();Ft();Be();ne();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}},Ml=()=>{let e=Xe(process.cwd());if(a(e))return!1;let t=Bt(e.value);return yt(t)},kl=e=>e===!0?"on":e===!1?"off":null,Ll=e=>e==="on"?!0:e==="off"?!1:null});var Le,A,_e=v(()=>{"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"},A={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=v(()=>{"use strict";_e();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 ov,sv,cn,ln,vs,ys,ro=v(()=>{"use strict";fe();N();le();k();ov=e=>e.props.tags??[],sv=e=>e.props.assignees??[],cn=e=>ov(e).map(t=>I.getTag(t)).filter(t=>!!t),ln=e=>sv(e).map(t=>I.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"):l("Retrieved tags from ticket in breadcrumb",cn(n))},ys=()=>{let{breadCrumb:e,selectedNode:t}=f(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!P(n)?i("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",ln(n))}});var b,Un=v(()=>{"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 iv,av,dv,cv,lv,$n,Pl,bs,Is,Dl,uv,sa,oo=v(()=>{"use strict";iv=/^(\d+)(h|d|w|mo|y)$/,av=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,dv=({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},cv=(e,t=new Date)=>{let n=e.match(iv);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}},lv=e=>{let t=e.match(av);if(!t)return null;let[,n,r,o,s,d]=t,c=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,g=d?Number(d):0;return dv({year:c,month:u,day:m,hour:p,minute:g})?new Date(c,u-1,m,p,g):null},$n=e=>{let t=e.trim().toLowerCase();return cv(t)??lv(t)},Pl=/^(\d+)(s|m)?$/,bs=e=>{let t=e.trim().toLowerCase().match(Pl);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Is=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Pl.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Dl=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,uv=[{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}],sa=(e=uv)=>{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 mv,ue,Qe,xe,pv,gv,aa,da,Fl,jn,xs,ia,Ol,fv,hv,so,Bl,vv,yv,ca,bv,Ee,un=v(()=>{"use strict";ms();to();N();no();nr();fe();le();k();hs();ro();Un();oo();mv=["BOARD","TICKET","SWIMLANE","COMMENT"],ue={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"},xe={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},pv=[ue.EDITOR,ue.VIEW,ue.USERNAME,ue.AUTOSYNC,ue.SYNC_DEBOUNCE_MS,ue.ATTACHMENT_MAX_KB,ue.LOG_LEVEL],gv=(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[]}},aa=[String(or),"5000","15000","30000","60000"],da=["250","500","1000"],Fl=["10s","20s","30s","45s"],jn=[b.EXIT,b.SYNC,b.HELP,b.EXPORT,b.CONFIG,b.YANK],xs=[b.NEW,b.EDIT,b.DELETE,b.MOVE],ia=[b.TAG,b.UNTAG,b.ASSIGN,b.UNASSIGN,b.CLOSE_ISSUE,b.RE_OPEN_ISSUE,b.EDIT,b.COMMENT],Ol=[b.FILTER,b.PEEK,b.REPLAY],fv={WORKSPACE:[...jn,...xs],BOARD:[...Ol,...jn,...xs],SWIMLANE:[...Ol,...jn,...xs],TICKET:[...jn,...xs,...ia],FIELD:[...jn,...ia],FIELD_LIST:[...jn,...ia],TEXT:[...jn],COMMENT:[b.EDIT,b.DELETE,b.YANK]},hv=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],so=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&P(n)),Bl=e=>e.parentNodeId===ye,vv=({selectedNode:e,breadCrumb:t})=>{let n=gv(e?.context);return so({breadCrumb:t,selectedNode:e})?n.includes(Qe.DESCRIPTION)?n:[...n,Qe.DESCRIPTION]:n},yv=({selectedNode:e,breadCrumb:t})=>{let n=so({breadCrumb:t,selectedNode:e});return n?[xe.REF,xe.TITLE,...n.props?.description?.trim()?[xe.DESCRIPTION]:[],...cn(n).length>0?[xe.TAGS]:[],...ln(n).length>0?[xe.ASSIGNEES]:[]]:e?[xe.REF,xe.TITLE]:[]},ca=()=>{let e=gs({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},bv=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=fs();if(!r)return[b.HELP,b.CONFIG];if(!Ml())return[b.HELP,b.INIT,b.OPEN];if(t)return[b.HELP,b.PEEK,b.REPLAY,b.EXPORT,b.CONFIG,b.YANK];let o=e?.context,s=o&&mv.includes(o),d=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?fv[u]:[]))],c=so({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&&cn(c).length>0):u===b.UNASSIGN?!!(c&&ln(c).length>0):u===b.RE_OPEN_ISSUE?!!(c&&Bl(c)):u===b.CLOSE_ISSUE?!!(c&&!Bl(c)):!0)},Ee=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=f())=>{let s=t.context??"WORKSPACE";return{[b.NONE]:bv({breadCrumb:o,readOnly:r,selectedNode:n}),[b.EXIT]:["confirm"],[b.EXPORT]:[],[b.SYNC]:[],[b.INIT]:[],[b.OPEN]:e===b.OPEN?ca():[],[b.HELP]:[],[b.PEEK]:[...sa(),"now","prev","next"],[b.REPLAY]:[...sa()],[b.EDIT]:vv({selectedNode:n,breadCrumb:o}),[b.YANK]:yv({selectedNode:n,breadCrumb:o}),[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(ir),...I.getExistingTags()])],[b.UNTAG]:[...vs()?.value?.map(({name:c})=>c)??[]],[b.UNASSIGN]:[...ys()?.value?.map(({name:c})=>c)??[]],[b.ASSIGN]:I.getExistingAssignees(),[b.NEW]:hv(s),[b.CONFIG]:[...pv]}[e]??[]}});var _l,Ul=v(()=>{"use strict";_l=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{accessSync as Iv,copyFileSync as xv,existsSync as Es,mkdirSync as $l,readdirSync as jl,readFileSync as Ev,renameSync as Rv,rmSync as Sv,statSync as Hl,unlinkSync as Nv,writeFileSync as Cv}from"node:fs";import ar from"node:path";var la,We,Rs=v(()=>{"use strict";la=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);Cv(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Ev(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)&&Hl(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await Iv(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)&&Hl(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=jl(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)?jl(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Nv(e)}catch(t){(!la(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{Sv(e,{recursive:!0,force:!0})}catch(t){(!la(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{Rv(e,t)}catch(r){if(la(r)&&r.code==="EXDEV"){xv(e,t),this.rmFile(e);return}throw r}}}});import Av from"node:path";import{z as Gt}from"zod";var Tv,Wl,wv,Gl,ua,ma,Mv,Ss,ql,st,pa,Hn=v(()=>{"use strict";Qn();ne();N();Rs();Tv={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},Wl=Gt.object({logLevel:Gt.enum(["info","error","debug"]),preferredEditor:Gt.string().optional(),userName:Gt.string().optional(),userId:Gt.string().optional(),autoSync:Gt.boolean().nullable().optional(),autoSyncDebounceMs:Gt.number().optional(),attachmentMaxKb:Gt.number().optional(),viewMode:Gt.enum(["dense","wide"]).optional()}).partial(),wv="config.json",Gl=Sn,ua=()=>Av.join(Gl(),wv),ma=()=>{try{return We.mkDir(Gl()),l(`Ensured ~/${lt} exists`,null)}catch{return i(`Unable to create ~/${lt}`)}},Mv=e=>{let t;try{t=JSON.parse(e)}catch{return i(`Invalid ~/${lt}/config.json JSON`)}let n=Wl.safeParse(t??{});return n.success?l("Parsed config",n.data):i(`Invalid ~/${lt}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Ss=()=>{let e=ma();if(a(e))return i(e.message);let t=ua(),n=We.readFile(t);return n==null||n.trim()===""?l("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):Mv(n)},ql=e=>{let t=ma();if(a(t))return i(t.message);let n=Wl.safeParse(e);if(!n.success)return i(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=ua();try{return We.writeToFile(r,JSON.stringify(n.data,null,2)+`
58
- `),l("Config written",null)}catch{return i(`Unable to write ~/${lt}/config.json`)}},st=e=>{let t=Ss();if(a(t))return i("Failed to read existing config");let n={...t.value,...e};return ql(n)},pa=()=>{let e=ua(),t=ma();if(a(t))return i(`Unable to create ~/${lt}`);if(!(We.readFile(e)!==null)){let C=ql(Tv);if(a(C))throw new Error(`Unable to create ~/${lt}/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:c,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:g}=r.value,x=di({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 ~/${lt}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,l("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:S.userName,userId:S.userId,autoSync:c??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:g??"dense"}))}});var Vl,zl,ga,Kl=v(()=>{"use strict";Vl="/media/",zl=e=>`${Vl}${e}`,ga=(e,t)=>`![${e}](${zl(t)})`});import kv from"node:crypto";import fa from"node:fs";import Lv from"node:path";var qt,io,Pv,Dv,Ov,Yl,ao=v(()=>{"use strict";It();N();ne();Kl();qt=500,io=(e,t)=>`${e}.${t}`,Pv=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: ${Cd.join(", ")}`),Dv=e=>kv.createHash("sha256").update(e).digest("hex"),Ov=(e,t=qt)=>{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=Pv(e);return a(n)?n:l("Validated attachment data",{hash:Dv(e),ext:n.value,bytes:e.length})},Yl=(e,t,n=qt)=>{let r=Ov(t,n);if(a(r))return r;let o=qo(e),s=Lv.join(o,io(r.value.hash,r.value.ext));try{fa.existsSync(s)||(fa.mkdirSync(o,{recursive:!0}),fa.writeFileSync(s,t))}catch(d){return i(`Unable to write attachment blob: ${d instanceof Error?d.message:String(d)}`)}return l("Wrote attachment blob",r.value)}});import Bv from"zod";var co,lo,Xl,ha=v(()=>{"use strict";Hn();ao();pe();N();be();Be();k();co=50,lo=5e3,Xl=()=>{let e=me().commandMeta.inputString,t=Bv.coerce.number().int().min(co).max(lo).safeParse(e);if(!t.success)return i(`Attachment size cap must be ${co}-${lo} KB (default ${qt})`);let n=st({attachmentMaxKb:t.data});return a(n)?n:(et({attachmentMaxKb:t.data}),E({mode:h.DEFAULT}),l(`Attachment size cap set to ${t.data} KB`,null))}});import Jl from"chalk";var ya,Ql,va,Zl,Fv,_v,eu,Uv,$v,uo,Pe,tu,nu,Ns,jv,Hv,Cs,wt=v(()=>{"use strict";hs();ya={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Ql=(e,t,n)=>Math.max(t,Math.min(n,e)),va=(e,t,n)=>e+(t-e)*n,Zl=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Fv=e=>e.toLowerCase().trim(),_v=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,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 g=o-s/2;return[Math.round((u+g)*255),Math.round((m+g)*255),Math.round((p+g)*255)]},eu=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Uv=(e,t,n)=>{let r=Ql(n,0,1);return[Math.round(va(e[0],t[0],r)),Math.round(va(e[1],t[1],r)),Math.round(va(e[2],t[2],r))]},$v=(e,t,n)=>Uv(e,t,n),uo=e=>{let t=Zl(e)%360,n=_v(t,ya.stringColor.saturation,ya.stringColor.lightness);return eu(n)},Pe=(e,t=ir)=>{let n=Fv(e??"");return n&&t[n]?t[n]:uo(n)},tu=e=>{let t=ya.gradient.stops,n=Ql(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 $v(t[s],t[s+1],d)},nu=e=>eu(tu(e)),Ns=e=>Zl(e.toLowerCase().trim())/4294967295,jv=e=>{let t=Ns(e);return tu(t)},Hv=e=>{let[t,n,r]=jv(e);return{normal:o=>Jl.bgRgb(t,n,r).black(o),cursor:o=>Jl.bgRgb(t,n,r).white.bold(o)}},Cs=e=>Hv(e).normal(` ${e} `)});var vt,mo=v(()=>{"use strict";vt=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null});import{createHash as Wv}from"node:crypto";var Gv,qv,Ae,dr=v(()=>{"use strict";Gv="0123456789ABCDEFGHJKMNPQRSTVWXYZ",qv=e=>{let t=Wv("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+=Gv[Number(n>>s&31n)]}return r},Ae=(e,t)=>qv(`${e}:virtual:${t}`)});import ru from"chalk";var re,Te,ke,ou=v(()=>{"use strict";wt();_e();re=e=>ru.dim(e),Te=e=>ru.hex(A.primary)(e),ke=({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,x)=>Ns(g)-Ns(x)).slice(0,r).map(g=>Cs(g)).join(" ");return p?`${re(e)}${p}${re(n)}`:""}});var mn,As=v(()=>{"use strict";mn={None:"none",Invalid:"invalid",Valid:"valid"}});import au from"chalk";var Vv,su,de,K,H,lr,iu,Ts,ba,zv,cr,Kv,Yv,Xv,Jv,Qv,du,cu=v(()=>{"use strict";ms();no();Ul();ct();It();N();le();Be();ha();ao();k();wt();mo();ro();dr();ou();Un();As();un();oo();Vv=["BOARD","TICKET","SWIMLANE"],su=()=>{let e=f().selectedNode;if(!e?.context)return H({message:re("Missing target context")});if(Vv.includes(e.context))return K();if(e.parentNodeId){let t=f().nodes[e.parentNodeId];if(t?.id===Ae(t?.parentNodeId??"","comments"))return K()}return H({message:re("Command not available in this context")})},de="<ENTER> to confirm",K=(e="",t=[])=>({message:re(e),validity:mn.Valid,completionWordList:t}),H=({message:e,completionWordList:t=[]})=>({validity:mn.Invalid,message:e,completionWordList:t}),lr=e=>e.length===0,iu=(e,t)=>{let n=Ke(f().breadCrumb,"BOARD");if(a(n))return H({message:Te("Command is not applicable in this context")});let r=Nd(n.value.id);return a(r)?H({message:Te(`Unable to ${t}: board id is not a valid ULID`)}):Dl({date:e,horizonDate:r.value})?null:H({message:Te(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},Ts=e=>` ${au.hex("#000").bgHex(Pe(e))(` ${e} `)} `,ba=({modifier:e})=>{let t="confirm";return e===t?K(de):H({message:lr(e)?re("if you are certain, enter ")+Cs(t):"",completionWordList:[t]})},zv=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?H({message:re(n)}):K():H({message:lr(r)?t:"",completionWordList:[...e]}),cr=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>lr(n)&&lr(r)?H({message:e,completionWordList:[]}):K(t??de),Kv=({modifier:e,inputString:t})=>{let n=ca();return!lr(e)||!lr(t)?K(de):H({message:n.length?re("number from the list, or a path"):re("path to an epiq project"),completionWordList:n})},Yv=({modifier:e,inputString:t})=>{let n=Ee(b.CONFIG);if(!n.includes(e))return H({message:ke({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ue.EDITOR:{let r=[..._l];return t.trim()?r.includes(t.trim())?K(de):H({message:ke({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):H({message:ke({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ue.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?K(de):H({message:ke({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ue.USERNAME:return t.trim()?K(de):H({message:Te("Enter a user name. Saved in ")+au.bgBlack("~/.epiq-global/config.json")});case ue.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?K(de):H({message:ke({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ue.AUTOSYNC:{let r=["on","off"],o=ve().autoSync;if(!r.includes(t.trim())){let s=kl(o);return H({message:ke({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return K(de)}case ue.ATTACHMENT_MAX_KB:{let r=ve().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<co||o>lo){let s=ke({prefix:" examples: ",wordList:da,minLengthForHints:0,inputString:t});return H({message:Te(`provide a size cap in KB (${co}-${lo}). current: ${r??qt} KB.`)+s,completionWordList:da})}return K(de)}case ue.SYNC_DEBOUNCE_MS:{let r=ve().autoSyncIntervalMs,o=Il(t);if(!t.trim()||o===null||o<or){let s=ke({prefix:" examples: ",wordList:aa,minLengthForHints:0,inputString:t});return H({message:Te(`provide duration above ${or}ms. current duration: ${r}ms.`)+s,completionWordList:aa})}return K(de)}default:return H({message:Te("Unknown config option"),completionWordList:n})}},Xv=({modifier:e,inputString:t})=>{let n=Ee(b.EDIT);if(!n.length)return H({message:Te("Command not available in this context")});if(!n.includes(e)){let r=ke({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return H({message:r||Te("Unknown edit option"),completionWordList:n})}switch(e){case Qe.COMMENT:return t.trim()?K(de):H({message:re("write a comment...")});case Qe.TITLE:return K(de);case Qe.DESCRIPTION:{let{preferredEditor:r}=ve();return r?K(re("<ENTER> to edit in ")+r):H({message:"No editor selected"})}default:return H({message:Te("Unknown edit option"),completionWordList:n})}},Jv=({modifier:e})=>{let t=Ee(b.YANK);return t.length?t.includes(e)?K(de+re(" and copy to clipboard")):H({message:ke({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):H({message:Te("Nothing selected to copy from")})},Qv={[b.EXPORT]:()=>K(de+re(", and create export markdown file")),[b.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return K(de);let n={message:re("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=$n(r);if(!r||!o)return H(n);let s=iu(o,"peek");return s||K(de)},[b.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Is(e.modifier,e.inputString),r={message:re("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=$n(t);if(!t||!o)return H(r);let s=iu(o,"replay");return s||(n&&bs(n)===null?H({message:Te("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):K("<ENTER> to replay board history",n?Fl:[]))},[b.EXIT]:()=>K(de+re(" and exit the application")),[b.INIT]:()=>K(de),[b.OPEN]:Kv,[b.PALETTE]:()=>K(de),[b.FILTER]:e=>{if(e.modifier==="clear")return K(de);let t=s=>Ee(b.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return H({message:ke({wordList:Ee(b.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Ee(b.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())?H({message:ke({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):K():H({message:ke({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[b.NONE]:e=>{let t=Ee(b.NONE);return H({message:ke({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[b.NEW]:e=>zv({list:Ee(b.NEW),hint:ke({wordList:Ee(b.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[b.HELP]:()=>K(de),[b.EDIT]:Xv,[b.COMMENT]:e=>{let t=cr({hint:re(`write a comment (max ${4e3} char)...`),onOk:re(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===mn.Invalid?t:e.inputString.length>4e3?K(Te("max input exceeded")):t},[b.CONFIG]:Yv,[b.YANK]:Jv,[b.DELETE]:e=>{let t=su();return t.validity==="invalid"?t:ba(e)},[b.CLOSE_ISSUE]:e=>ba(e),[b.RE_OPEN_ISSUE]:e=>ba(e),[b.MOVE]:e=>{let t=su();return t.validity==="invalid"?t:cr({hint:ke({prefix:"hey hacker! These commands are blocked for you... ",wordList:Ee(b.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[b.TAG]:e=>{let n=I.getExistingTags().slice(0,10).map(Ts).join("");return cr({hint:n.length?re("create tag or reuse:")+n+re(""):re("create tag ...")})(e)},[b.UNTAG]:e=>{let t=vs();if(a(t))return H({message:Te("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Ts).slice(0,10);return n.length?cr({hint:re(" ... ")+n.join("")})(e):H({message:Te("Issue has no tags"),completionWordList:[]})},[b.ASSIGN]:e=>{let t=I.getExistingAssignees().map(Ts).slice(0,10);return cr({hint:re("assignees... ")+t.join("")})(e)},[b.UNASSIGN]:e=>{let t=ys();if(a(t))return H({message:Te("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Ts).slice(0,10);return n.length?cr({hint:re("remove assignee... ")+n.join("")})(e):H({message:Te("Issue has no assignees"),completionWordList:[]})},[b.SYNC]:()=>K(de)},du=Object.fromEntries(Object.entries(Qv).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]))});var ws,lu=v(()=>{"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 Zv,ey,ty,ny,ry,uu,mu,pu,gu=v(()=>{"use strict";N();k();lu();Zv=3,ey=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"]),ty=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},ny=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=Zv&&!ey.has(t)&&!/^\d+$/.test(t)),ry=e=>{let t=new Map;for(let s of ty(e))for(let d of ny(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]},uu=ws,mu=-1,pu=()=>{let e=He();if(a(e))return ws;let t=e.value,n=t.eventLog.length;return n!==mu&&(uu=ry(t),mu=n),uu}});var fu,hu,Ia=v(()=>{"use strict";Fd();un();Un();cu();gu();k();pe();fu=e=>Object.values(b).includes(e),hu=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:d,validity:c,completionWordList:u}=du[n].validate(n,r,s),m=n!==b.PEEK&&n!==b.REPLAY,p=o==="command"||o==="modifier"?Ee(n):m?pu():[],{mode:g}=f(),x=g===h.COMMAND_LINE?d??"":"",S=[...u,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:x,autoCompletion:t?Bd(e,S):{hint:"",hints:[],remainder:"",overlap:0}}}});var vu,oy,sy,iy,yu=v(()=>{"use strict";Ia();un();vu=e=>{let t=e.trimStart(),n=sy(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),d=iy(e),c=fu(r)?r:null,u=c!==null,m=r!=="",p=c?Ee(c)??[]:[],g=c&&p.includes(o)?o:"",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,C=oy(t,c,g);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:d,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:g,target:x,inputToMatch:S,inputString:C}},oy=(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},sy=e=>e.trim()?e.trim().split(/\s+/):[],iy=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as vT}from"react";var ur,xa,mr,ay,bu,Mt,po,Ea,Ra,Iu,xu,Ms,Eu,Y,Ru,Su,Nu,me,ks,be=v(()=>{"use strict";Ia();yu();N();As();ur=e=>e===xa||e===":",xa=" ",mr={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:mn.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},ay=new Set,bu=()=>{for(let e of ay)e()},Mt=e=>{let n=e(mr),r=vu(n.value),o=n.cursorPosition===n.value.length;mr={...n,commandMeta:hu(r,o)},bu()},po=({message:e,status:t})=>{let n=structuredClone(mr);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,mr=n,bu(),l(e,null)},Ea=e=>{Mt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Ra=e=>{Mt(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&ur(n[o-1]);)o--;for(;o>0&&!ur(n[o-1]);)o--}else{for(;o<n.length&&!ur(n[o]);)o++;for(;o<n.length&&ur(n[o]);)o++}return{...t,cursorPosition:o}})},Iu=()=>{Mt(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}})},xu=()=>{Mt(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&ur(t[r-1]);)r--;for(;r>0&&!ur(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Ms=e=>{Mt(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,c=Math.max(0,Math.min(s.length,d.length));return{...t,value:d,cursorPosition:c,commandIsPending:!1}})},Eu=()=>{Mt(e=>({...e,commandIsPending:!0}))},Y=e=>{Mt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Ru=({addToHistory:e=!0})=>{Mt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Su=()=>{Mt(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}})},Nu=()=>{Mt(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},me=()=>mr,ks=()=>{let[e,...t]=mr.value.split(xa);return t.join(xa).trim()}});var D,xn=v(()=>{"use strict";pe();Td();k();be();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 Cu,F,Sa=v(()=>{"use strict";k();Un();Cu=e=>{let{context:t}=f().contextNode;if(!t)return F.None;switch(e){case b.EXIT:return F.Exit;case b.EXPORT:return F.Export;case b.INIT:return F.Init;case b.OPEN:return F.OpenProject;case b.DELETE:return F.Delete;case b.EDIT:return F.Edit;case b.COMMENT:return F.Comment;case b.HELP:return F.ViewHelp;case b.RE_OPEN_ISSUE:return F.ReopenIssue;case b.CLOSE_ISSUE:return F.CloseIssue;case b.TAG:return F.TagTicket;case b.UNTAG:return F.UntagTicket;case b.ASSIGN:return F.AssignUserToTicket;case b.UNASSIGN:return F.UnassignUserFromTicket;case b.NEW:return F.NewItem;case b.FILTER:return F.Filter;case b.MOVE:return F.Move;case b.PEEK:return F.Peek;case b.REPLAY:return F.Replay;case b.CONFIG:return F.Config;case b.YANK:return F.Yank;case b.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"}});import{Text as Au}from"ink";import Tu,{useEffect as wu,useState as dy}from"react";var Mu,qe,pr=v(()=>{"use strict";k();_e();Mu={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},qe=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Ve(),r=Mu[n]??Mu.default,[o,s]=dy(0);if(wu(()=>{s(0)},[r]),wu(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(c)},[e,r]),!e)return Tu.createElement(Au,null,t);let d=r[o]??r[0]??t;return Tu.createElement(Au,{color:A.accent,dimColor:o===1},d)}});import{Box as Na,Text as cy}from"ink";import Ls from"react";var ly,pn,go=v(()=>{"use strict";_e();ly=(e,t,n,r)=>{let o=u=>Math.max(1,e[u]??1),s=n,d=n+1,c=o(n);for(;d<t&&c+o(d)<=r;)c+=o(d),d++;for(;s>0&&c+o(s-1)<=r;)s--,c+=o(s);return{start:s,end:d}},pn=({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)),c=Math.max(1,Math.ceil(r)),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:g,end:x}=o?ly(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},S=Math.max(1,x-g),C=e.slice(g,x),M=e.length>S,w=d,T=M?Math.max(1,Math.floor(S/e.length*w)):w,_=Math.max(0,w-T),O=Math.max(1,e.length-S),$=M?Math.floor(g/O*_):0;return Ls.createElement(Na,{flexDirection:"row",height:d,width:"100%"},Ls.createElement(Na,{flexDirection:"column",flexGrow:1,height:d},C),Ls.createElement(Na,{flexDirection:"column",width:1,height:w},Array.from({length:w}).map((Z,Jt)=>Ls.createElement(cy,{key:Jt,color:M&&Jt>=$&&Jt<$+T?A.accent:A.secondary},M?"\u2502":" "))))}});var ku,Ca,uy,Ps,Aa=v(()=>{"use strict";k();uy=()=>{let{eventLog:e=[]}=f();if(Ca&&ku===e)return Ca;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return ku=e,Ca=t,t},Ps=e=>uy().has(e)});import{Text as my}from"ink";import py from"react";var gy,fy,gr,Ds=v(()=>{"use strict";hs();wt();le();Aa();Qt();gy=e=>e.toLowerCase().trim(),fy=(e,t=ir)=>{let n=gy(e);return t[n]?t[n]:uo(n)},gr=({id:e,isSelected:t,maxWidth:n})=>{let r=I.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:En(o,n);return py.createElement(my,{underline:t,color:fy(o)},"@"+s,Ps(e)?"":"\u2197")}});import{Text as hy}from"ink";import vy from"react";var Os,Ta=v(()=>{"use strict";le();_e();wt();Qt();Os=({id:e,isSelected:t,maxWidth:n})=>{let r=I.getTag(e);if(!r)return;let o=n===void 0?r.name:En(r.name,n);return vy.createElement(hy,{underline:t,backgroundColor:Pe(r.name),color:A.secondary}," "+o+" ")}});import{useEffect as yy,useState as by}from"react";var Iy,Lu,Bs,fo,xy,Ey,fr,Fs=v(()=>{"use strict";wt();Iy=80,Lu=1400,Bs=new Set,fo=null,xy=e=>(Bs.add(e),fo||(fo=setInterval(()=>{for(let t of Bs)t()},Iy)),()=>{Bs.delete(e),Bs.size===0&&fo&&(clearInterval(fo),fo=null)}),Ey=()=>{let e=Date.now()%Lu/Lu;return e<.5?e*2:(1-e)*2},fr=e=>{let[,t]=by(0);return yy(()=>{if(e)return xy(()=>t(n=>n+1))},[e]),nu(Ey())}});import{Box as hr,Text as vr}from"ink";import ze from"react";var Ry,Pu,Sy,Ny,Ou,Bu=v(()=>{"use strict";le();_e();Qt();Aa();nn();ro();Ds();Ta();Fs();Ry=(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),En(e.slice(o).trim(),n)]},Pu=3,Sy=2,Ny=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let d=e.length-o-1,c=d>0?String(d).length+1:0;if(r+s.width+c>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},Ou=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=fr(r),s=e-4,d=s-7-1,[c,u]=Ry(Se(t.title),d,s),m=u?null:En(Se(t.props.description),s)||null,p=cn(t),g=ln(t).map(T=>({...T,name:T.name})),x=Math.max(1,s-Pu),S=I.getCommentsByIssue(t.id),C=S.length?String(S.length).length+2+1:0,{shown:M,hidden:w}=Ny([...p.map(T=>({id:T.id,isTag:!0,width:Math.min(T.name.length,x)+Pu})),...g.map(T=>({id:T.id,isTag:!1,width:Math.min(T.name.length,x)+Sy+(Ps(T.id)?0:1)}))],s-C);return ze.createElement(hr,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?A.accent:A.secondary,justifyContent:"space-between"},ze.createElement(hr,{paddingLeft:1,paddingRight:1,flexDirection:"column"},ze.createElement(hr,{justifyContent:"space-between"},ze.createElement(vr,{color:A.primary},c),ze.createElement(vr,{color:A.secondary2,dimColor:!0},z(t.id))),u&&ze.createElement(vr,{color:A.primary},u),m&&ze.createElement(vr,{color:A.secondary2,dimColor:!0},m)),ze.createElement(hr,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},ze.createElement(hr,{flexDirection:"row"},M.map(T=>ze.createElement(hr,{paddingRight:1,key:T.id},T.isTag?ze.createElement(Os,{id:T.id,maxWidth:x}):ze.createElement(gr,{id:T.id,maxWidth:x}))),w>0&&ze.createElement(vr,{color:A.secondary2,dimColor:!0},"+",w)),S.length>0&&ze.createElement(vr,{color:A.accent},"[",S.length,"]")))}});import{Box as Wn,Text as ho}from"ink";import Ze from"react";var Cy,Fu,_u=v(()=>{"use strict";pe();le();_e();wt();pr();Fs();Cy=(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 c=fr(s),u=(r.props.tags??[]).map(Z=>I.getTag(Z)).filter(Z=>!!Z),m=(r.props.assignees??[]).map(Z=>I.getContributor(Z)).map(Z=>Z&&{...Z,name:Z.name}).filter(Z=>!!Z),p=1,g=u.length*(1+p),x=m.length*(2+p),S=u.map(Z=>Ze.createElement(Wn,{key:Z.id,paddingRight:p},Ze.createElement(ho,{color:Pe(Z.name)},"\u25A0"))),C=m.map(Z=>Ze.createElement(Wn,{key:Z.id,paddingRight:p},Ze.createElement(ho,{color:uo(Z.name)},"@"+Z.name.at(0)))),M=s?c:o?A.accent:d===h.MOVE?A.secondary:A.primary,w=I.getCommentsByIssue(r.id),T=w.length?String(w.length).length+2+p:0,_=w.length?Ze.createElement(Wn,{paddingRight:p},Ze.createElement(ho,{color:A.accent},"[",w.length,"]")):null,O=g+x+T,$=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(ho,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),Ze.createElement(ho,{wrap:"truncate",color:M},Cy(r.title,$))),Ze.createElement(Wn,null,S,C,_))}});import Ay from"chalk";import{Box as wa,Text as Ty}from"ink";import kt from"react";var wy,Uu,$u=v(()=>{"use strict";fe();k();_e();pr();go();Bu();_u();Fs();wy=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:d,mode:c})=>{let{renderedChildrenIndex:u,replay:m}=Ve(),p=u[e.id]??[],g=m?new Set(m.flashNodeIds):null,x=g?.has(e.id)??!1,S=fr(x),C=`${e.title} ${Ay.hex(A.secondary2).dim("("+p.length+")")}`,M=3,w=o?1:5,T=s&&d===-1,_=n-3-(o?1:0)-(T?2:0),O=Math.max(2,String(p.length).length+1),$=r-M-1,Z=kt.createElement(wa,{borderStyle:"round",borderColor:A.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},kt.createElement(qe,{isSelected:t}),kt.createElement(Ty,{bold:!0,color:x?S:t?A.accent:A.primary},C," ",e.readonly?"\u{1F512}":"")),Jt=(Dt,Xn)=>{let Er=s&&d===Xn;if(!P(Dt))return null;let Rr=g?.has(Dt.id)??!1;return o?kt.createElement(Fu,{key:Dt.id,index:Xn,labelWidth:O,width:_,ticket:Dt,isSelected:Er,isFlashing:Rr,mode:c}):kt.createElement(Ou,{key:Dt.id,width:_,ticket:Dt,isSelected:Er,isFlashing:Rr})};return kt.createElement(wa,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?A.accent:A.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},Z,kt.createElement(wa,null,p.length>0&&kt.createElement(pn,{selectedIndex:d,height:$,itemHeight:w},p.map(Jt)),T&&kt.createElement(qe,{isSelected:!0})))},Uu=kt.memo(wy)});var ju,Hu,Ma=v(()=>{"use strict";Tn();ju=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},Hu=(e,t,n)=>Ce.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0})});var yr,_s=v(()=>{"use strict";yr=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 br,Text as Vt}from"ink";import De,{useEffect as My,useMemo as ky,useRef as Ly}from"react";import{decodeTime as Wu}from"ulid";function qu({ticket:e,width:t,height:n}){let r=ky(()=>Dy(e),[e]),o=Ly([]);My(()=>(Gu(o.current),o.current=By(e,r),()=>{Gu(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Ve(),c=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?De.createElement(br,{flexDirection:"column",width:t,height:n,padding:1},De.createElement(Vt,{color:A.primary},"No attachments yet."),De.createElement(br,{paddingTop:1},De.createElement(Vt,{color:A.primary},"Attach images from the browser GUI"),De.createElement(Vt,{color:A.accent}," epiq gui "),De.createElement(Vt,{color:A.primary},"by dropping or pasting them."))):De.createElement(br,{flexDirection:"column",width:t,height:n},De.createElement(br,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:A.secondary,borderStyle:"single",paddingBottom:1},De.createElement(Vt,{color:A.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),De.createElement(pn,{height:c,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let g=p===s,x=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return De.createElement(br,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},De.createElement(Vt,{color:A.accent},g?"\u276F ":" "),De.createElement(br,{paddingLeft:1},De.createElement(Vt,{color:A.secondary2},`#${p+1} `),De.createElement(Vt,{color:g?A.accent:A.primary},x),De.createElement(Vt,{color:A.secondary2}," "+Fy(m.bytes)+" "+yr(dt(m.id)))))})))}var Py,Dy,Gu,Oy,By,Fy,Vu=v(()=>{"use strict";Je();ct();_s();fe();N();le();Tn();k();_e();dr();go();Py=e=>Ae(e,"attachments"),Dy=e=>I.getAttachmentsByIssue(e.id).sort((t,n)=>Wu(t.id)-Wu(n.id)),Gu=e=>{for(let t of e)I.deleteNode(t.id)},Oy=(e,t,n)=>Ce.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),By=(e,t)=>{let n=I.getNode(Py(e.id));if(!n||!Ye(n))return[];let r=t.map((o,s)=>Oy(o,s,n.id)).map(o=>I.createNode(o)).filter(yt).map(({value:o})=>o).filter(Ye);return t.length>0&&f().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),r},Fy=e=>`${Math.max(1,Math.round(e/1024))} KB`});var Ku,ka,zu,La,Yu,Xu,_y,Ju,Uy,Pa,Qu=v(()=>{"use strict";Ku=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,ka=e=>e.replace(Ku,""),zu=e=>e==="additions"||e==="deletions",La=e=>{let t=Ku.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"||!zu(r.side)||!zu(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r},Yu=/```\n([\s\S]*?)\n?```\s*$/,Xu=e=>Yu.exec(e)?.[1]??null,_y=/`[^`\n]+`[^\n]*\n?$/,Ju=e=>ka(e).replace(Yu,"").replace(_y,"").trim(),Uy=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})`},Pa=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${Uy(e)}`});var $y,vo,jy,Hy,Wy,Gy,em,Da,tm,Zu,nm,Oa=v(()=>{"use strict";Qu();$y=(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 c=d;for(;c.length>n;)s&&(o.push(s),s=""),o.push(c.slice(0,n)),c=c.slice(n);s?s.length+1+c.length<=n?s=`${s} ${c}`:(o.push(s),s=c):s=c}return s&&o.push(s),o},vo=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)},jy=/!\[([^\]]*)\]\([^)]*\)/g,Hy=e=>e.replace(jy,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),Wy=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),Gy=4,em=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(Gy)),Da=e=>{let t=!1;return e.map(em).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=La(n);if(r)return{kind:"caption",text:Pa(r)};let o=Hy(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:vo(s[1]??"")}:{kind:"text",spans:vo(o)}})},tm=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Zu=(e,t)=>{let n=[];for(let r of Da(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 tm(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of $y(Wy(r.spans),t))n.push({kind:r.kind,spans:vo(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},nm=(e,t)=>{let n=La(e),r=n?Xu(e):null;if(!n||r===null)return Zu(ka(e).split(`
59
- `),t);let o=Ju(e),s=r.split(`
60
- `).map(em),d=n.side===n.endSide?n.start:void 0,c=d===void 0?0:String(d+s.length-1).length+3;return[...o?[...Zu(o.split(`
61
- `),t),{kind:"blank"}]:[],{kind:"caption",text:Pa(n)},...s.flatMap((u,m)=>tm(u,Math.max(1,t-c)).map((p,g)=>({kind:"code",text:p,number:d===void 0||g>0?void 0:d+m})))]}});import{Box as rm,Text as Gn}from"ink";import it from"react";var om,Ba,sm,Fa=v(()=>{"use strict";_e();om=({spans:e,bold:t,wrap:n})=>it.createElement(Gn,{color:A.primary,bold:t,wrap:n},e.map((r,o)=>r.code?it.createElement(Gn,{key:o,color:A.yellow},r.text):it.createElement(Gn,{key:o},r.text))),Ba=({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:A.secondary2},"```");case"caption":return it.createElement(Gn,{color:A.accent,wrap:r},e.text);case"heading":return it.createElement(om,{spans:e.spans,bold:!0,wrap:r});case"text":return it.createElement(om,{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:A.secondary,color:A.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},sm=({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(rm,{flexDirection:"column"},e.map((o,s)=>it.createElement(rm,{key:s},it.createElement(Ba,{line:o,width:t,gutter:r}))))}});import{Box as gn,Text as fn}from"ink";import Re,{useEffect as qy,useMemo as im,useRef as Vy}from"react";import{decodeTime as am}from"ulid";function cm({ticket:e,width:t,height:n}){let r=im(()=>Yy(e),[e]),o=Vy([]);qy(()=>(dm(o.current),o.current=Xy(e,r),()=>{dm(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Ve(),c=Math.max(1,n-4),u=Math.max(20,t-8),m=im(()=>r.map(g=>{let x=nm(g.md,u);return x.length>0?x:[{kind:"blank"}]}),[r,u]),p=m.map(g=>g.length+zy);return r.length===0?Re.createElement(gn,{flexDirection:"column",width:t,height:n,padding:1},Re.createElement(fn,{color:A.primary},"No comments yet."),Re.createElement(gn,{paddingTop:1},Re.createElement(fn,{color:A.primary},"Use"),Re.createElement(fn,{color:A.accent}," :comment "),Re.createElement(fn,{color:A.primary},"to add the first one."))):Re.createElement(gn,{flexDirection:"column",width:t,height:n},Re.createElement(gn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:A.secondary,borderStyle:"single",paddingBottom:1},Re.createElement(fn,{color:A.secondary2},"Comments (",r.length,") ")),Re.createElement(pn,{height:c,itemHeights:p,selectedIndex:s},r.map((g,x)=>{let S=x===s;return Re.createElement(gn,{key:g.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:A.secondary,borderStyle:"single"},Re.createElement(gn,{flexDirection:"row",paddingBottom:1},Re.createElement(fn,{color:A.accent},S?"\u276F ":" "),Re.createElement(gn,{paddingLeft:1},Re.createElement(fn,{color:A.secondary2},`#${x+1} `),Re.createElement(gr,{id:g.authorId}),Re.createElement(fn,{color:A.secondary2}," "+yr(dt(g.id))))),Re.createElement(gn,{paddingLeft:3,paddingBottom:1},Re.createElement(sm,{lines:m[x]??[],width:u})))})))}var zy,Ky,Yy,dm,Xy,lm=v(()=>{"use strict";Je();ct();_s();fe();N();le();k();_e();dr();Ds();go();Ma();Oa();Fa();zy=4,Ky=e=>Ae(e,"comments"),Yy=e=>I.getCommentsByIssue(e.id).sort((t,n)=>am(t.id)-am(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),dm=e=>{for(let t of e)I.deleteNode(t.id)},Xy=(e,t)=>{let n=I.getNode(Ky(e.id));if(!n||!Ye(n))return[];let r=t.map((o,s)=>Hu(o,s,n.id)).map(I.createNode).filter(yt).map(({value:o})=>o).filter(wr);return t.length>0&&f().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),r}});import{Box as Us,Text as Jy}from"ink";import zt from"react";var um,mm=v(()=>{"use strict";fe();le();tr();k();_e();Ds();pr();Ta();um=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Ve(),{title:o}=t,s=t.parentNodeId?I.getNode(t.parentNodeId):void 0,d=s&&P(s)?o===ie.ASSIGNEES?s.props.assignees??[]:o===ie.TAGS?(s.props.tags??[]).filter(c=>I.getTag(c)):[]:[];return zt.createElement(Us,{alignItems:"center",paddingTop:1},zt.createElement(Us,{minWidth:12},zt.createElement(qe,{isSelected:n}),zt.createElement(Jy,{color:n?A.accent:A.secondary2},o,":")),zt.createElement(Us,{flexDirection:"row",marginLeft:1,paddingRight:1},d.map((c,u)=>{let m=r.id===t.id&&u===e;return zt.createElement(Us,{key:`${o}-${c}`,paddingRight:2,minHeight:1},zt.createElement(qe,{isSelected:m}),o===ie.ASSIGNEES?zt.createElement(gr,{isSelected:m,id:c}):o===ie.TAGS?zt.createElement(Os,{isSelected:m,id:c}):null)})))}});var _a,pm,Ua,$a=v(()=>{"use strict";_a=e=>Math.max(5,String(Math.max(e,1)).length+3),pm=(e,t)=>Math.max(0,e-6-_a(t)),Ua=(e,t=0)=>Math.max(1,e-5-2*t)});import{Box as Ir,Text as ja}from"ink";import at,{useEffect as Qy,useMemo as Ha}from"react";var Zy,gm,Wa,fm,eb,Ga,hm=v(()=>{"use strict";le();N();Tn();k();_e();Qt();$a();pr();go();Fa();Oa();Zn();Zy="\u2029",gm=(e,t)=>`${e}::inline-line::${t}`,Wa=new Map,fm=e=>{let t=Wa.get(e)??[];Wa.delete(e);for(let n of t)I.deleteNode(n)},eb=(e,t)=>{fm(e);let n=[];t.forEach((r,o)=>{let s=tt(BigInt(o+1));if(!yt(s))return;let d=I.createNode(Ce.text({id:gm(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));yt(d)&&n.push(d.value.id)}),Wa.set(e,n)},Ga=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:d,contextNode:c}=Ve(),u=Ha(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Ha(()=>u.join("\0"),[u]);Qy(()=>(eb(e,u),()=>{fm(e)}),[e,m]);let p=_a(u.length),g=pm(s,u.length),S=Ha(()=>Da(u).map(C=>{if(C.kind==="code"||C.kind==="caption")return{...C,text:pi(C.text,g)};if(C.kind==="text"||C.kind==="heading"){let M=C.spans.map(w=>w.code?`\`${w.text}\``:w.text).join("");return{...C,spans:vo(pi(M,g))}}return C}),[u,g]).map((C,M)=>{let w=c.id===e&&d===M;return at.createElement(Ir,{key:gm(e,M)},at.createElement(Ir,{flexShrink:0},at.createElement(ja,{color:w?A.primary:A.secondary2,dimColor:!w},`${M+1} `.padStart(p,"\xA0"))),C.kind==="blank"?at.createElement(ja,{backgroundColor:w?"gray":void 0},Zy):at.createElement(Ir,null,at.createElement(Ba,{line:C,width:C.kind==="code"?g:0,wrap:"truncate-end"})))});return at.createElement(Ir,{flexDirection:"column",paddingTop:1},at.createElement(Ir,null,at.createElement(qe,{isSelected:o}),at.createElement(ja,{color:o?A.accent:A.secondary2},t)),at.createElement(Ir,{flexDirection:"row",borderStyle:"round",borderColor:A.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},at.createElement(pn,{scrollByOne:!0,height:r,selectedIndex:d,itemHeight:1},S)))}});import{Box as qn,Text as qa}from"ink";import we,{useMemo as yo}from"react";var tb,nb,rb,ob,vm,ym=v(()=>{"use strict";fe();le();k();_e();Ma();dr();Vu();lm();pr();mm();hm();$a();tb=e=>Ae(e,"description"),nb=e=>Ae(e,"comments"),rb=e=>Ae(e,"history"),ob=e=>Ae(e,"attachments"),vm=({ticket:e,height:t})=>{let n=yo(()=>ju(e),[e]),{selectedIndex:r,contextNode:o}=Ve(),s=process.stdout.columns||120,d=yo(()=>tb(e.id),[e.id]),c=yo(()=>nb(e.id),[e.id]),u=yo(()=>rb(e.id),[e.id]),m=yo(()=>ob(e.id),[e.id]),p=I.getAttachmentsByIssue(e.id).length,g=o.id===e.id,x=o.id===c||o.parentNodeId===c,S=o.id===u||o.parentNodeId===u,C=o.id===m||o.parentNodeId===m,M=ae(e.id);if(x){let $=t-3;return we.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},we.createElement(cm,{ticket:e,width:s,height:$}))}if(C){let $=t-3;return we.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},we.createElement(qu,{ticket:e,width:s,height:$}))}if(S){let O=I.getNode(u),$=O&&Ye(O)?O.props.value??"":"",Z=Ua(t);return we.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},O?we.createElement(Ga,{id:O.id,label:"Event log",text:$,selected:!1,maxWidth:s,rows:Z}):null)}let w=M.reduce((O,$)=>Tr($)||$.id===c||$.id===m||$.id===u?O+1:O,0),T=Ua(t,w),_=(O,$)=>O.id===d?we.createElement(Ga,{key:O.id,id:d,label:"Description (press e to edit)",text:e.props.description??"",selected:$,maxWidth:s,rows:T}):Tr(O)?we.createElement(um,{key:O.id,parent:O,selected:$,selectedIndex:r}):O.id===c?we.createElement(qn,{key:O.id,paddingTop:1},we.createElement(qe,{isSelected:$}),we.createElement(qa,{backgroundColor:A.secondary,color:$?A.accent:A.primary},` Comments (${n}) \u203A\u203A `)):O.id===m?we.createElement(qn,{key:O.id,paddingTop:1},we.createElement(qe,{isSelected:$}),we.createElement(qa,{backgroundColor:A.secondary,color:$?A.accent:A.primary},` Attachments (${p}) \u203A\u203A `)):O.id===u?we.createElement(qn,{key:O.id,paddingTop:1},we.createElement(qe,{isSelected:$}),we.createElement(qa,{backgroundColor:A.secondary,color:$?A.accent:A.primary}," History \u203A\u203A ")):null;return we.createElement(qn,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},M.map((O,$)=>_(O,g&&r===$)))}});import{Box as sb}from"ink";import $s from"react";var ib,bm,Im=v(()=>{"use strict";fe();$u();ym();ib=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:d,width:c})=>{let u=t.context,m=u===V.TICKET||u===V.FIELD_LIST||u===V.FIELD,p=u===V.BOARD||u===V.SWIMLANE,g=u===V.TICKET?t:r.find(w=>w.context===V.TICKET),x=Math.floor(c/3),S=Math.floor(c/Math.max(e.length,1)),C=Math.min(S,x),M=s==="dense";return $s.createElement(sb,{flexDirection:"row",height:d},p&&e.map((w,T)=>{let _=t.id===w.id,O=_?n:-1,$=t.context===V.BOARD&&n===T;return $s.createElement(Uu,{key:w.id,height:d,width:C,swimlane:w,isSelected:$,isDense:M,isFocused:_,listSelectedIndex:O,mode:o})}),m&&g&&$s.createElement(vm,{height:d,ticket:g}))},bm=$s.memo(ib)});import xm from"node:fs";import ab from"node:path";import db from"react";import{render as cb}from"ink";import{Writable as lb}from"node:stream";var bo,ub,mb,pb,gb,Em,Rm=v(()=>{"use strict";Im();fe();N();k();ne();Be();bo=e=>String(e).padStart(2,"0"),ub=e=>{let t=e.getUTCFullYear(),n=bo(e.getUTCMonth()+1),r=bo(e.getUTCDate()),o=bo(e.getUTCHours()),s=bo(e.getUTCMinutes()),d=bo(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${d}`},mb=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",pb=async(e,{width:t,height:n})=>{let r="",o=new lb({write(d,c,u){let m=gb(d.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=cb(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(d=>setTimeout(d,0)),s.unmount(),r},gb=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),Em=async()=>{let{viewMode:e}=ve(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=f(),d=r.find(T=>T.context==="BOARD");if(!d)return i("No board found to export");let c=120,u=40,m=await pb(db.createElement(bm,{height:u,width:c,swimlanes:(s[d.id]??[]).filter(T=>T!==void 0&&In(T)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:c,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,x=ub(g),S=`board_${mb(d.title)}_${x}.md`,C=ic(p.value);xm.mkdirSync(C,{recursive:!0});let M=ab.join(C,S),w=`# Board - ${d.title}
62
- Date: ${g.toISOString()}
49
+ `,"utf8"),o.push(`${r} (${m.length})`)}catch{continue}}return o},Ib=(e,t)=>{let n=new Set(Ro(t));return Ro(e).filter(o=>!n.has(o))},Eb=(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(`
50
+ `),im=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let o=await Be({args:["show",`HEAD:${t}`],cwd:e});if(o.exitCode!==0)return l("No committed log to compare against",void 0);let r=Ib(o.stdout,n);return r.length>0?a(Eb(t,r,Ro(o.stdout).length)):l("Event log only grew",void 0)}});import mn from"node:fs";import Fr from"node:path";var Sb,dm,am,Rb,qa,Ga,Nb,Cb,oo,Ab,wb,Js,cm,lm,um,_r,mm,Or=h(()=>{"use strict";Yn();R();xt();Cs();bo();Wa();Xe();ct();Sb="[epiq:init-repo]",dm=async e=>{let t=await Be({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 a(["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(`
51
+ `));J.info("Creating initial commit");let o=await W({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(d(o))return a(o.message);let r=await W({args:["commit-tree",o.value.stdout.trim(),"-m",Sb],cwd:e});if(d(r))return a(r.message);let s=await W({args:["update-ref","HEAD",r.value.stdout.trim()],cwd:e});return d(s)?a(s.message):l("Created initial commit",!0)},am=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",Rb=async e=>{let t=await Ts(e);if(d(t))return a(t.message);let n=await _l(e);return d(n)?a(n.message):l("Built sync commit message",`[sync|branch:${am(t.value)}:sha:${am(n.value)}]`)},qa=async({repoRoot:e,stateBranchName:t})=>{J.info(`Creating ${t}`);let n=await W({args:["commit-tree",Gl,"-m","[epiq:init-state-branch]"],cwd:e});if(d(n))return a(`Failed to create state branch commit
52
+ ${n.message}`);let o=n.value.stdout.trim(),r=await W({args:["update-ref",`refs/heads/${t}`,o],cwd:e});return d(r)?a(`Failed to create ${t}
53
+ ${r.message}`):l("Created state branch",!0)},Ga=async({repoRoot:e,stateBranchName:t})=>{let n=await ws({repoRoot:e,branch:t});if(d(n))return a(`Ensure local state branch failed
54
+ `+n.message);if(n.value)return l("Local state branch already exists",!1);let o=await qn({repoRoot:e});if(d(o))return a(`Ensure local state branch failed
55
+ `+o.message);let r=o.value,s=r?await ma({repoRoot:e,branch:t}):l("No remote, no remote state branch",!1);if(d(s))return a(`Ensure local state branch failed
56
+ `+s.message);let i=s.value;if(r&&i){let c=await ye.fetch({cwd:e,remote:bt,branch:t});if(d(c))return a(`Failed to fetch ${t} from remote
57
+ ${c.message}`)}if(i){let c=await W({args:["branch","--track",t,`${bt}/${t}`],cwd:e});return d(c)?a(`Failed to create local ${t} from remote
58
+ ${c.message}`):l("Created local state branch from remote",!0)}return qa({repoRoot:e,stateBranchName:t})},Nb=async({repoRoot:e,branch:t})=>{let n=await W({args:["worktree","list","--porcelain"],cwd:e});if(d(n))return a(n.message);let o=n.value.stdout.split(`
59
+ `),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)},Cb=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=Sr(Fr.dirname(t));if(d(o))return a(`Failed to create state branch worktree
60
+ `+o.message);if(mn.existsSync(t)&&!mn.existsSync(Fr.join(t,".git"))){let s=nm(t);if(d(s))return a(s.message);if(s.value.length>0)return a([`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(i=>` ${i}`),"","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(`
61
+ `));J.info("Removing broken state branch worktree path"),Yl(t)}J.info("Creating state branch worktree");let r=await ye.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return d(r)?a(`Failed to create state branch worktree
62
+ ${r.message}`):l("Created state branch worktree",!0)},oo=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let o=await Nb({repoRoot:e,branch:n});if(d(o))return a(o.message);let r=xr(t),s=o.value?xr(o.value):null;if(s&&s===r&&mn.existsSync(s))return l("State branch already checked out in expected worktree",!1);if(s&&s!==r){let u=await $l(s);if(d(u))return a(u.message);if(u.value||pu(s))return a([`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(`
63
+ `));J.info("Moving state branch worktree to expected location");let m=await ye.worktreeRemove({cwd:e,worktreeRoot:s});if(d(m))return a(`Failed to remove existing state branch worktree
64
+ ${m.message}`)}if(s&&!mn.existsSync(s)){J.info("Pruning stale state branch worktree");let u=await ye.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
65
+ ${u.message}`)}let i=await Fl({repoRoot:e,worktreeRoot:t});if(d(i))return a(i.message);let c=mn.existsSync(t);if(i.value&&c)return l("State branch worktree already exists",!1);if(i.value&&!c){J.info("Pruning missing registered state branch worktree");let u=await ye.worktreePrune({cwd:e});if(d(u))return a(`Failed to prune stale worktrees
66
+ ${u.message}`)}return Cb({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},Ab=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Ts(e);if(d(n))return a(n.message);if(n.value===t)return l("State branch already checked out",!1);(await Be({cwd:e,args:["rebase","--abort"]})).exitCode===0&&J.info("Aborted stale state branch rebase");let r=await ye.checkout({cwd:e,branch:t});return d(r)?a(`Failed to checkout ${t}
67
+ ${r.message}`):l("Checked out state branch",!0)},wb=async({repoRoot:e,stateBranchRoot:t})=>{let n=await pa(t);if(d(n))return a(n.message);if(n.value)return l("State branch upstream already configured",!1);let o=await qn({repoRoot:t});if(d(o))return a(o.message);if(!o.value)return l("No remote available for state branch upstream",!1);let r=Bt(e);if(d(r))return r;let s=r.value,i=await ma({repoRoot:t,branch:s});if(d(i))return a(i.message);if(!i.value)return l("Remote state branch missing; upstream will be configured on first push",!1);J.info(`Configuring ${s} upstream`);let c=await ye.fetch({cwd:t,remote:bt,branch:s});if(d(c))return a(`Failed to fetch ${s}
68
+ ${c.message}`);let u=await ye.setUpstream({cwd:t,branch:s,upstream:`${bt}/${s}`});return d(u)?a(`Failed to set state branch upstream
69
+ ${u.message}`):l("Configured state branch upstream",!0)},Js=async({stateBranchRoot:e,eventFileName:t})=>{let n=zl(t),o=Fr.join(e,n);if(!mn.existsSync(o))return l("No event file to stage",null);let r=await im({stateBranchRoot:e,relativePath:n,workingContent:mn.readFileSync(o,"utf8")});if(d(r))return a(r.message);let s=await ye.stage({cwd:e,pathspec:[n]});return d(s)?a(`Failed to stage state branch event file
70
+ ${s.message}`):l("Staged state branch event file",n)},cm=async({stateBranchRoot:e})=>{let t=Vl(),n=Fr.join(e,t);if(!mn.existsSync(n))return l("No media directory to stage",null);let o=await ye.stage({cwd:e,pathspec:[t],ignoreRemoval:!0});return d(o)?a(`Failed to stage state branch media files
71
+ ${o.message}`):l("Staged state branch media files",t)},lm=async({stateBranchRoot:e})=>{let t=[fa(),ga()].filter(o=>mn.existsSync(Fr.join(e,o)));if(t.length===0)return l("No event log config to stage",[]);let n=await ye.stage({cwd:e,pathspec:t});return d(n)?a(`Failed to stage event log config
72
+ ${n.message}`):l("Staged event log config",t)},um=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let o=await Rb(e);return d(o)?a(`Create state branch sync commit failed
73
+ `+o.message):xo({cwd:t,message:o.value,pathspec:n})},_r=async({repoRoot:e,stateBranchRoot:t})=>{let n=await pa(t);if(d(n))return a(n.message);let o=Bt(e);if(d(o))return o;let r=o.value,s=n.value?await ye.push({cwd:t}):await ye.push({cwd:t,remote:bt,branch:r,setUpstream:!0});if(d(s))return a(`Failed during state branch push
74
+ ${s.message}`);let i=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return l(i?"Pushed state branch":"Remote already up to date",i)},mm=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let o=!1,r=Bt(e);if(d(r))return r;let s=r.value,i=[Ms(),await Ga({repoRoot:e,stateBranchName:s}),await oo({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await Ab({stateBranchRoot:t,stateBranchName:s}),await Jl(t),n?await wb({stateBranchRoot:t,repoRoot:e}):l("Skipped state branch upstream bootstrap",!1)];for(let c of i){if(d(c))return a(c.message);o=o||!!c.value}return l(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",o)}});import Qs from"node:fs";import Va from"node:os";import Tb from"node:path";var kb,pm,Mb,Pb,Lb,gm,za,fm,Db,Zs,Ka=h(()=>{"use strict";R();ct();xt();kb="epiq-sync.lock",pm=600*1e3,Mb=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}},Pb=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Lb=e=>e&&(e.hostname!==Va.hostname()||Pb(e.pid))?Date.now()-e.startedAt>pm:!0,gm=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,za=e=>{try{return Mb(Qs.readFileSync(e,"utf8"))}catch{return null}},fm=(e,t)=>{let n={pid:process.pid,hostname:Va.hostname(),startedAt:Date.now(),operation:t};try{return Qs.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},Db=async({worktreeRoot:e,operation:t})=>{let n=await ua(e);if(d(n))return a(n.message);let o=Tb.join(n.value,kb),r=()=>{try{let c=za(o);c&&c.pid===process.pid&&Qs.rmSync(o)}catch{}};if(fm(o,t))return l("Acquired sync lock",{acquired:!0,release:r});let s=za(o);if(!Lb(s))return l("Sync lock is held",{acquired:!1,heldBy:s});J.info(`Breaking an abandoned sync lock: ${s?gm(s):"unreadable lock file"}`);try{Qs.rmSync(o,{force:!0})}catch{}if(fm(o,t))return l("Acquired sync lock after breaking a stale one",{acquired:!0,release:r});let i=za(o);return l("Sync lock taken by another process",{acquired:!1,heldBy:i??{pid:-1,hostname:Va.hostname(),startedAt:Date.now(),operation:"unknown"}})},Zs=async({worktreeRoot:e,operation:t,fn:n})=>{let o=await Db({worktreeRoot:e,operation:t});if(d(o))return a(o.message);if(!o.value.acquired)return J.info(`Skipping ${t}: the state worktree is held by ${gm(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 Fb from"node:fs";var _b,Ob,Ya,hm,Xa,ei,ti=h(()=>{"use strict";R();Lr();Xs();bo();Xe();ct();Or();Wa();Yn();Ka();_b=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=re("getRepoRootDir",await lt(e));if(d(n))return a(n.message);let o=n.value;logger.debug("[sync] repo root",o);let r=re("getStateBranchRoot",be({repoRoot:o}));if(d(r))return a(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 i=re("bootstrapStateBranchStorage",await mm({repoRoot:o,stateBranchRoot:s,ensureUpstream:t}));if(d(i))return a(i.message);logger.debug("[sync] bootstrap result",{bootstrapped:i.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let c=re("hasInProgressGitOperation(stateBranchRoot)",await As(s));if(d(c))return a(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"),a("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",Xl(o,s));return d(u)?a(u.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:s,bootstrapped:i.value}),l("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:s,bootstrapped:i.value}))},Ob=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 Js({stateBranchRoot:t,eventFileName:n}));if(d(o))return a(o.message);let r=re("stageStateBranchMediaFiles",await cm({stateBranchRoot:t}));if(d(r))return a(r.message);let s=re("stageStateBranchEventConfig",await lm({stateBranchRoot:t}));if(d(s))return a(s.message);let i=[o.value,r.value,...s.value].filter(m=>m!==null);if(i.length===0)return l("Nothing to stage",{createdCommit:!1});let c=re("hasStagedChanges(after stage)",await jl(t,i));if(d(c))return a(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 um({repoRoot:e,stateBranchRoot:t,pathspec:i}));return d(u)?a(u.message):(logger.debug("[sync] created sync commit",u.value),l("Committed own event file",{createdCommit:!0,commitSha:u.value}))},Ya=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return Ys(n),l(n,{...e,pulled:!1,pushed:!1,offline:!0})},hm=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}),a("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}),a("Own event file must end with .jsonl");Eo();let n=re("ensureSyncReady",await _b({cwd:e,ensureUpstream:!0}));if(d(n))return Re(n.message);let{repoRoot:o,stateBranchRoot:r,bootstrapped:s}=n.value,i=re("isDetachedHead(stateBranchRoot)",await Hl(r));if(d(i))return Re(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return Re("Cannot run :sync while the state branch is in detached HEAD state");let c=!1,u,m=!1,p=!1,f=re("getStateBranch",Bt(o));if(d(f))return Re(f.message);let y=f.value;logger.debug("[sync] resolved state branch",{stateBranch:y,stateBranchRoot:r});let I=re("flushPendingLogs",$s(r,t));d(I)&&logger.error(`[sync] ${I.message}`);let S=re("commitOwnEventFileToStateBranch",await Ob({repoRoot:o,stateBranchRoot:r,ownEventFileName:t}));if(d(S))return Re(S.message);c=S.value.createdCommit,u=S.value.commitSha;let A=re("hasRemote",await qn({repoRoot:r}));if(d(A))return Re(A.message);if(!A.value)return Ya({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s},"no remote");let w=re("pullBranchRebaseIfPresent",await Er({cwd:r,branch:y}));if(d(w))return Ir(w.message)?Ya({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s}):Re(w.message);m=w.value;let k=re("isAheadOfUpstream",await Ul(r));if(d(k))return Re(k.message);if(c||s||k.value){logger.info("[sync] pushing state branch",{createdCommit:c,bootstrapped:s,stateBranchRoot:r});let D=re("pushStateBranch",await _r({stateBranchRoot:r,repoRoot:o}));if(d(D)&&Ol(D.message)){let _=re("pullBranchRebaseIfPresent(retry)",await Er({cwd:r,branch:y}));if(d(_))return Re(_.message);m=m||_.value,D=re("pushStateBranch(retry)",await _r({stateBranchRoot:r,repoRoot:o}))}if(d(D))return Ir(D.message)?Ya({repoRoot:o,stateBranchRoot:r,createdCommit:c,commitSha:u,bootstrapped:s}):Re(D.message);p=D.value}if(c){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:r});let D=re("git rev-parse HEAD",await W({args:["rev-parse","HEAD"],cwd:r}));if(d(D))return Re(D.message);u=D.value.stdout.trim(),logger.debug("[sync] final sync commit sha",u)}return no(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})},Xa=async(e,t)=>{let n=rm(e);try{return await t()}finally{let o=sm(e,n);o.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${o.join(", ")}`)}},ei=async e=>{let t=e.cwd??process.cwd(),n=await lt(t);if(d(n))return Re(n.message);let o=be({repoRoot:n.value});if(d(o))return Re(o.message);let r=o.value;if(!Fb.existsSync(r))return hm(e);let s=await Zs({worktreeRoot:r,operation:"sync",fn:()=>Xa(r,()=>hm(e))});return d(s)?Re(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 Gt,ni,Bb,Ja,vm,oi=h(()=>{"use strict";Ju();to();St();Ce();pe();R();M();Lr();Xs();ti();Gt=null,ni=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Gt,currentStatus:g().syncStatus?.status,currentMessage:g().syncStatus?.msg}),Gt)return logger.debug("[sync] syncAndReloadState joining existing promise"),Gt;logger.debug("[sync] syncAndReloadState creating promise"),Gt=Bb();try{let e=await Gt;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!d(e),message:(d(e),e.message),statusAfterResolve:g().syncStatus?.status,statusMessageAfterResolve:g().syncStatus?.msg}),d(e)&&g().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),N({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),Gt||a(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:g().syncStatus?.status,statusMessageBeforeClear:g().syncStatus?.msg}),Gt=null}},Bb=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:g().mode,syncStatus:g().syncStatus});let e=vm();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:g().mode,message:e.message,syncStatus:g().syncStatus}),e;if(Gt)return Gt;logger.debug("[sync] syncAndReloadState:start");let t=re("resolveActorId",oe());if(d(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:d(t)?t.message:"Missing actor id"}),a("Unable to resolve event log path");N({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:g().syncStatus});let n=Zn(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let o=re("syncEpiqWithRemote",await ei({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!d(o),message:(d(o),o.message)}),d(o))return logger.error("[sync] syncAndReloadState:sync failed",o.message),N({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:g().syncStatus}),Re(`Unable to sync state. ${o.message}`);let{stateBranchRoot:r,offline:s}=o.value,i=Ja(r);return d(i)?i:(N({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))},Ja=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=re("loadMergedEvents",Et(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!d(t),message:(d(t),t.message),count:d(t)?void 0:t.value.events.length}),d(t))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:g().syncStatus}),a(`Unable to load events. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=vm();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:g().mode,message:n.message,syncStatus:g().syncStatus}),n;let o=Ku(),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 i=re("bootStateFromEventLog",Wt(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!d(i),message:(d(i),i.message)}),d(i))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:g().syncStatus}),a(`Unable to boot synced state. ${i.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"),N({filters:r}),logger.debug("[sync] restoreNavigationAnchor:start");let s=re("restoreNavigationAnchor",Xu(o));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!d(s),message:d(s)?s.message:"Navigation restored",selectedNodeId:g().selectedNode?.id,contextNodeId:g().contextNode?.id}),d(s)?(N({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)},vm=()=>g().mode===b.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:g().mode,syncStatus:g().syncStatus}),N({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"))});var No,ym,bm,Qa,Za,Br,ed,Ub,xm,$b,Im,ri=h(()=>{"use strict";R();We();M();oi();No=3e3,ym=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<No?null:t},bm=0,Za=!1,Br=!1,ed=()=>{if(Za)return!0;let e=ze();return d(e)?!1:e.value.syncStatus.status==="syncing"},Ub=()=>{let e=Ie().autoSyncIntervalMs??1e4,t=Date.now()-bm;return Math.max(0,e-t)},xm=()=>{Qa||(Qa=setTimeout(async()=>{if(Qa=void 0,!!It()){if(ed()){Br=!0;return}Br=!1,await $b()}},Ub()))},$b=async()=>{if(g().readOnly||g().timeMode==="peek"||g().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!It())return a("Cannot auto-sync before state is initialized");if(ed())return Br=!0,a("Sync already in progress");Za=!0,bm=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await ni()}finally{Za=!1,Br&&xm()}},Im=()=>{It()&&(Br=!0,!ed()&&xm())}});import Ur from"node:fs";import $r from"node:path";import{z as Co}from"zod";var si,jb,Hb,Wb,Sm,Rm,Em,Nm,Cm,Am,qb,ii,jr,Ao=h(()=>{"use strict";R();nn();Ns();ae();si="recent-projects.json",jb=20,Hb=Co.object({projectId:Co.string().min(1),root:Co.string().min(1),lastOpenedAt:Co.number().finite()}),Wb=Co.object({projects:Co.array(Hb)}),Sm=()=>$r.join(on(),si),Rm=e=>$r.basename(e)||e,Em=e=>{let t=$r.resolve(e);try{return Ur.realpathSync(t)}catch{return t}},Nm=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Cm=e=>{if(!Nr(e.root))return!1;let t=br(e.root);return!d(t)&&t.value===e.projectId},Am=()=>{let e=Sm();if(!Ur.existsSync(e))return l("No recent projects recorded",[]);let t;try{t=JSON.parse(Ur.readFileSync(e,"utf8"))}catch(o){return a(`Invalid ${si}: ${o instanceof Error?o.message:String(o)}`)}let n=Wb.safeParse(t);return n.success?l("Read recent projects",n.data.projects):a(`Invalid ${si} shape: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},qb=e=>{let t=Sm();try{Ur.mkdirSync($r.dirname(t),{recursive:!0}),Ur.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
75
+ `,"utf8")}catch(n){return a(`Unable to write ${si}: ${n instanceof Error?n.message:String(n)}`)}return l("Recorded recent project",e)},ii=({exclude:e}={})=>{let t=Am();if(d(t))return t;let n=e===void 0?null:Em(e);return l("Listed recent projects",t.value.filter(o=>n===null||Em(o.root)!==n).filter(Cm).sort(Nm))},jr=({root:e,now:t=Date.now()})=>{let n=$r.resolve(e),o=br(n);if(d(o))return a(o.message);let r=o.value,s=Am(),i=d(s)?[]:s.value,c=[{projectId:r,root:n,lastOpenedAt:t},...i.filter(u=>u.projectId!==r&&u.root!==n)].filter(Cm).sort(Nm).slice(0,jb);return qb(c)}});var ai,wm,Tm,km,Hr=h(()=>{"use strict";R();nn();We();ae();ai=()=>{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}},wm=()=>{let e=Me(process.cwd());if(d(e))return!1;let t=Ot(e.value);return Dt(t)},Tm=e=>e===!0?"on":e===!1?"off":null,km=e=>e==="on"?!0:e==="off"?!1:null});var $e,T,Ve=h(()=>{"use strict";$e={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"},T={accent:$e.cyan,accent2:$e.magenta,primary:$e.white,secondary:$e.grayDark,secondary2:$e.grayLight,gray:$e.gray,green:$e.green,yellow:$e.yellow,red:$e.red}});var C,wo,di=h(()=>{"use strict";Ve();C={red:$e.red,yellow:$e.yellow,green:$e.green,blue:$e.blue,magenta:$e.magenta,cyan:$e.cyan},wo={urgent:C.red,critical:C.red,important:C.red,blocker:C.red,asap:C.red,immediate:C.red,fail:C.red,failure:C.red,broken:C.red,bug:C.red,error:C.red,incident:C.red,outage:C.red,production:C.red,crash:C.red,security:C.red,warning:C.yellow,warn:C.yellow,risky:C.yellow,risk:C.yellow,attention:C.yellow,pending:C.yellow,review:C.yellow,"needs-review":C.yellow,qa:C.yellow,testing:C.yellow,test:C.yellow,validate:C.yellow,verification:C.yellow,staging:C.yellow,check:C.yellow,"follow-up":C.yellow,followup:C.yellow,waiting:C.yellow,blocked:C.yellow,hold:C.yellow,done:C.green,complete:C.green,completed:C.green,success:C.green,ok:C.green,stable:C.green,resolved:C.green,fixed:C.green,closed:C.green,merged:C.green,released:C.green,deployed:C.green,approved:C.green,verified:C.green,working:C.green,healthy:C.green,pass:C.green,passing:C.green,info:C.blue,information:C.blue,note:C.blue,docs:C.blue,documentation:C.blue,doc:C.blue,guide:C.blue,help:C.blue,explanation:C.blue,detail:C.blue,details:C.blue,context:C.blue,design:C.blue,discussion:C.blue,proposal:C.blue,idea:C.blue,feature:C.magenta,enhancement:C.magenta,improvement:C.magenta,refactor:C.magenta,refactoring:C.magenta,cleanup:C.magenta,optimize:C.magenta,optimization:C.magenta,perf:C.magenta,performance:C.magenta,upgrade:C.magenta,migration:C.magenta,modernize:C.magenta,debt:C.magenta,todo:C.cyan,next:C.cyan,planned:C.cyan,plan:C.cyan,future:C.cyan,backlog:C.cyan,investigate:C.cyan,explore:C.cyan,prototype:C.cyan}});var Gb,zb,Tn,kn,ci,li,Wr=h(()=>{"use strict";K();R();ne();M();Gb=e=>e.props.tags??[],zb=e=>e.props.assignees??[],Tn=e=>Gb(e).map(t=>E.getTag(t)).filter(t=>!!t),kn=e=>zb(e).map(t=>E.getContributor(t)).filter(t=>!!t),ci=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!P(n)?a("Invalid untag target"):l("Retrieved tags from ticket in breadcrumb",Tn(n))},li=()=>{let{breadCrumb:e,selectedNode:t}=g(),n=[...e,t].find(o=>o?.context==="TICKET");return!n||!P(n)?a("Invalid unassign target"):l("Retrieved assignees from ticket in breadcrumb",kn(n))}});var x,ro=h(()=>{"use strict";x={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 Vb,Kb,Yb,Xb,Jb,so,Mm,ui,mi,Pm,Qb,td,qr=h(()=>{"use strict";Vb=/^(\d+)(h|d|w|mo|y)$/,Kb=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Yb=({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},Xb=(e,t=new Date)=>{let n=e.match(Vb);if(!n)return null;let[,o,r]=n,s=Number(o);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(r){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},Jb=e=>{let t=e.match(Kb);if(!t)return null;let[,n,o,r,s,i]=t,c=Number(n),u=Number(o),m=Number(r),p=s?Number(s):0,f=i?Number(i):0;return Yb({year:c,month:u,day:m,hour:p,minute:f})?new Date(c,u-1,m,p,f):null},so=e=>{let t=e.trim().toLowerCase();return Xb(t)??Jb(t)},Mm=/^(\d+)(s|m)?$/,ui=e=>{let t=e.trim().toLowerCase().match(Mm);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},mi=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),o=n.length>0&&Mm.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:o}},Pm=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,Qb=[{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}],td=(e=Qb)=>{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 Zb,ve,mt,Ae,ex,tx,od,rd,Fm,io,pi,nd,Lm,nx,ox,Gr,Dm,rx,sx,sd,ix,we,pn=h(()=>{"use strict";ri();Ao();R();Hr();dn();K();ne();M();di();Wr();ro();qr();Zb=["BOARD","TICKET","SWIMLANE","COMMENT"],ve={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},mt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Ae={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},ex=[ve.EDITOR,ve.VIEW,ve.USERNAME,ve.AUTOSYNC,ve.SYNC_DEBOUNCE_MS,ve.ATTACHMENT_MAX_KB,ve.LOG_LEVEL],tx=(e=g().selectedNode?.context)=>{switch(e){case"TICKET":return[mt.TITLE,mt.DESCRIPTION];case"BOARD":case"SWIMLANE":return[mt.TITLE];case"COMMENT":return[mt.COMMENT];default:return[]}},od=[String(No),"5000","15000","30000","60000"],rd=["250","500","1000"],Fm=["10s","20s","30s","45s"],io=[x.EXIT,x.SYNC,x.HELP,x.EXPORT,x.CONFIG,x.YANK],pi=[x.NEW,x.EDIT,x.DELETE,x.MOVE],nd=[x.TAG,x.UNTAG,x.ASSIGN,x.UNASSIGN,x.CLOSE_ISSUE,x.RE_OPEN_ISSUE,x.EDIT,x.COMMENT],Lm=[x.FILTER,x.PEEK,x.REPLAY],nx={WORKSPACE:[...io,...pi],BOARD:[...Lm,...io,...pi],SWIMLANE:[...Lm,...io,...pi],TICKET:[...io,...pi,...nd],FIELD:[...io,...nd],FIELD_LIST:[...io,...nd],TEXT:[...io],COMMENT:[x.EDIT,x.DELETE,x.YANK]},ox=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Gr=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&P(n)),Dm=e=>e.parentNodeId===he,rx=({selectedNode:e,breadCrumb:t})=>{let n=tx(e?.context);return Gr({breadCrumb:t,selectedNode:e})?n.includes(mt.DESCRIPTION)?n:[...n,mt.DESCRIPTION]:n},sx=({selectedNode:e,breadCrumb:t})=>{let n=Gr({breadCrumb:t,selectedNode:e});return n?[Ae.REF,Ae.TITLE,...n.props?.description?.trim()?[Ae.DESCRIPTION]:[],...Tn(n).length>0?[Ae.TAGS]:[],...kn(n).length>0?[Ae.ASSIGNEES]:[]]:e?[Ae.REF,Ae.TITLE]:[]},sd=()=>{let e=ii({exclude:process.cwd()});return d(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},ix=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:o}=ai();if(!o)return[x.HELP,x.CONFIG];if(!wm())return[x.HELP,x.INIT,x.OPEN];if(t)return[x.HELP,x.PEEK,x.REPLAY,x.EXPORT,x.CONFIG,x.YANK];let r=e?.context,s=r&&Zb.includes(r),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?nx[u]:[]))],c=Gr({breadCrumb:n,selectedNode:e});return i.filter(u=>u===x.MOVE?!1:u===x.YANK?!!(c??e):u===x.EDIT?s||!!c:u===x.DELETE?s:u===x.UNTAG?!!(c&&Tn(c).length>0):u===x.UNASSIGN?!!(c&&kn(c).length>0):u===x.RE_OPEN_ISSUE?!!(c&&Dm(c)):u===x.CLOSE_ISSUE?!!(c&&!Dm(c)):!0)},we=(e,{contextNode:t,selectedNode:n,readOnly:o,breadCrumb:r}=g())=>{let s=t.context??"WORKSPACE";return{[x.NONE]:ix({breadCrumb:r,readOnly:o,selectedNode:n}),[x.EXIT]:["confirm"],[x.EXPORT]:[],[x.SYNC]:[],[x.INIT]:[],[x.OPEN]:e===x.OPEN?sd():[],[x.HELP]:[],[x.PEEK]:[...td(),"now","prev","next"],[x.REPLAY]:[...td()],[x.EDIT]:rx({selectedNode:n,breadCrumb:r}),[x.YANK]:sx({selectedNode:n,breadCrumb:r}),[x.COMMENT]:[],[x.DELETE]:["confirm"],[x.RE_OPEN_ISSUE]:["confirm"],[x.CLOSE_ISSUE]:["confirm"],[x.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[x.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[x.TAG]:[...new Set([...Object.keys(wo),...E.getExistingTags()])],[x.UNTAG]:[...ci()?.value?.map(({name:c})=>c)??[]],[x.UNASSIGN]:[...li()?.value?.map(({name:c})=>c)??[]],[x.ASSIGN]:E.getExistingAssignees(),[x.NEW]:ox(s),[x.CONFIG]:[...ex]}[e]??[]}});var _m,Om=h(()=>{"use strict";_m=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"]});import{accessSync as ax,copyFileSync as dx,existsSync as fi,mkdirSync as Bm,readdirSync as Um,readFileSync as cx,renameSync as lx,rmSync as ux,statSync as $m,unlinkSync as mx,writeFileSync as px}from"node:fs";import To from"node:path";var id,Ze,gi=h(()=>{"use strict";id=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Ze={writeToFile:(e,t)=>{try{let n=To.dirname(e);fi(n)||Bm(n,{recursive:!0});let o=typeof t=="string"?t:JSON.stringify(t,null,2);px(e,o,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return cx(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 fi(e)&&$m(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await ax(e),!0}catch{return!1}},mkDir:e=>Bm(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=To.parse(t);for(;;){let o=To.join(t,e);try{if(fi(o)&&$m(o).isDirectory())return o}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=To.dirname(t)}return null},readFirstJSON(e){try{if(!Ze.dirExists(e))return null;let t=Um(e).filter(o=>o.endsWith(".json")).sort()[0];if(!t)return null;let n=To.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)?Um(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{mx(e)}catch(t){(!id(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{ux(e,{recursive:!0,force:!0})}catch(t){(!id(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(To.dirname(t)),!n?.overwrite&&fi(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{lx(e,t)}catch(o){if(id(o)&&o.code==="EXDEV"){dx(e,t),this.rmFile(e);return}throw o}}}});import fx from"node:path";import{z as fn}from"zod";var gx,jm,hx,Hm,ad,dd,vx,ko,Wm,et,zr,zt=h(()=>{"use strict";Un();ae();R();gi();gx={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},jm=fn.object({logLevel:fn.enum(["info","error","debug"]),preferredEditor:fn.string().optional(),userName:fn.string().optional(),userId:fn.string().optional(),autoSync:fn.boolean().nullable().optional(),autoSyncDebounceMs:fn.number().optional(),attachmentMaxKb:fn.number().optional(),viewMode:fn.enum(["dense","wide"]).optional()}).partial(),hx="config.json",Hm=on,ad=()=>fx.join(Hm(),hx),dd=()=>{try{return Ze.mkDir(Hm()),l(`Ensured ~/${Tt} exists`,null)}catch{return a(`Unable to create ~/${Tt}`)}},vx=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${Tt}/config.json JSON`)}let n=jm.safeParse(t??{});return n.success?l("Parsed config",n.data):a(`Invalid ~/${Tt}/config.json shape: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`)},ko=()=>{let e=dd();if(d(e))return a(e.message);let t=ad(),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}):vx(n)},Wm=e=>{let t=dd();if(d(t))return a(t.message);let n=jm.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`);let o=ad();try{return Ze.writeToFile(o,JSON.stringify(n.data,null,2)+`
76
+ `),l("Config written",null)}catch{return a(`Unable to write ~/${Tt}/config.json`)}},et=e=>{let t=ko();if(d(t))return a("Failed to read existing config");let n={...t.value,...e};return Wm(n)},zr=()=>{let e=ad(),t=dd();if(d(t))return a(`Unable to create ~/${Tt}`);if(!(Ze.readFile(e)!==null)){let S=Wm(gx);if(d(S))throw new Error(`Unable to create ~/${Tt}/config.json`)}let o=ko();if(d(o))throw new Error(o.message||"Unable to load settings");let{preferredEditor:r,userName:s,userId:i,autoSync:c,autoSyncDebounceMs:u,attachmentMaxKb:m,logLevel:p,viewMode:f}=o.value,y=ta({userId:i,userName:s});if(d(y))return a(y.message);let I=y.value??{userId:i,userName:s};return!I.userName||!I.userId?a(`User name or ID not configured in ~/${Tt}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,l("successfully loaded settings",{logLevel:p??"debug",preferredEditor:r??"",userName:I.userName,userId:I.userId,autoSync:c??!1,autoSyncIntervalMs:u??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))}});var qm,Gm,cd,zm=h(()=>{"use strict";qm="/media/",Gm=e=>`${qm}${e}`,cd=(e,t)=>`![${e}](${Gm(t)})`});import yx from"node:crypto";import ld from"node:fs";import bx from"node:path";var gn,Mo,xx,Ix,Ex,Vm,Po=h(()=>{"use strict";Ft();R();ae();zm();gn=500,Mo=(e,t)=>`${e}.${t}`,xx=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"):a(`Unsupported image format. Allowed: ${pl.join(", ")}`),Ix=e=>yx.createHash("sha256").update(e).digest("hex"),Ex=(e,t=gn)=>{if(e.length===0)return a("Attachment is empty");if(e.length>t*1024)return a(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=xx(e);return d(n)?n:l("Validated attachment data",{hash:Ix(e),ext:n.value,bytes:e.length})},Vm=(e,t,n=gn)=>{let o=Ex(t,n);if(d(o))return o;let r=Ps(e),s=bx.join(r,Mo(o.value.hash,o.value.ext));try{ld.existsSync(s)||(ld.mkdirSync(r,{recursive:!0}),ld.writeFileSync(s,t))}catch(i){return a(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return l("Wrote attachment blob",o.value)}});import Sx from"zod";var Vr,Kr,Km,ud=h(()=>{"use strict";zt();Po();pe();R();ce();We();M();Vr=50,Kr=5e3,Km=()=>{let e=de().commandMeta.inputString,t=Sx.coerce.number().int().min(Vr).max(Kr).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${Vr}-${Kr} KB (default ${gn})`);let n=et({attachmentMaxKb:t.data});return d(n)?n:(ht({attachmentMaxKb:t.data}),N({mode:b.DEFAULT}),l(`Attachment size cap set to ${t.data} KB`,null))}});import Ym from"chalk";var pd,Xm,md,Jm,Rx,Nx,Qm,Cx,Ax,Yr,Te,Zm,ep,hi,wx,Tx,vi,pt=h(()=>{"use strict";di();pd={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},Xm=(e,t,n)=>Math.max(t,Math.min(n,e)),md=(e,t,n)=>e+(t-e)*n,Jm=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Rx=e=>e.toLowerCase().trim(),Nx=(e,t,n)=>{let o=t/100,r=n/100,s=(1-Math.abs(2*r-1))*o,i=e/60,c=s*(1-Math.abs(i%2-1)),u=0,m=0,p=0;i>=0&&i<1?(u=s,m=c):i>=1&&i<2?(u=c,m=s):i>=2&&i<3?(m=s,p=c):i>=3&&i<4?(m=c,p=s):i>=4&&i<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)]},Qm=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Cx=(e,t,n)=>{let o=Xm(n,0,1);return[Math.round(md(e[0],t[0],o)),Math.round(md(e[1],t[1],o)),Math.round(md(e[2],t[2],o))]},Ax=(e,t,n)=>Cx(e,t,n),Yr=e=>{let t=Jm(e)%360,n=Nx(t,pd.stringColor.saturation,pd.stringColor.lightness);return Qm(n)},Te=(e,t=wo)=>{let n=Rx(e??"");return n&&t[n]?t[n]:Yr(n)},Zm=e=>{let t=pd.gradient.stops,n=Xm(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),i=r-s;return Ax(t[s],t[s+1],i)},ep=e=>Qm(Zm(e)),hi=e=>Jm(e.toLowerCase().trim())/4294967295,wx=e=>{let t=hi(e);return Zm(t)},Tx=e=>{let[t,n,o]=wx(e);return{normal:r=>Ym.bgRgb(t,n,o).black(r),cursor:r=>Ym.bgRgb(t,n,o).white.bold(r)}},vi=e=>Tx(e).normal(` ${e} `)});var tt,hn=h(()=>{"use strict";tt=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null});import{createHash as kx}from"node:crypto";var Mx,Px,Le,Lo=h(()=>{"use strict";Mx="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Px=e=>{let t=kx("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+=Mx[Number(n>>s&31n)]}return o},Le=(e,t)=>Px(`${e}:virtual:${t}`)});import tp from"chalk";var le,De,Ue,np=h(()=>{"use strict";pt();Ve();le=e=>tp.dim(e),De=e=>tp.hex(T.primary)(e),Ue=({prefix:e="",wordList:t,postfix:n="",noOfHints:o=100,inputString:r,minLengthForHints:s=1})=>{let i=r.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(f=>f.startsWith(i))].sort((f,y)=>hi(f)-hi(y)).slice(0,o).map(f=>vi(f)).join(" ");return p?`${le(e)}${p}${le(n)}`:""}});var Mn,yi=h(()=>{"use strict";Mn={None:"none",Invalid:"invalid",Valid:"valid"}});import sp from"chalk";var Lx,op,me,ee,G,Fo,rp,bi,fd,Dx,Do,Fx,_x,Ox,Bx,Ux,ip,ap=h(()=>{"use strict";ri();Hr();Om();Ke();Ft();R();ne();We();ud();Po();M();pt();hn();Wr();Lo();np();ro();yi();pn();qr();Lx=["BOARD","TICKET","SWIMLANE"],op=()=>{let e=g().selectedNode;if(!e?.context)return G({message:le("Missing target context")});if(Lx.includes(e.context))return ee();if(e.parentNodeId){let t=g().nodes[e.parentNodeId];if(t?.id===Le(t?.parentNodeId??"","comments"))return ee()}return G({message:le("Command not available in this context")})},me="<ENTER> to confirm",ee=(e="",t=[])=>({message:le(e),validity:Mn.Valid,completionWordList:t}),G=({message:e,completionWordList:t=[]})=>({validity:Mn.Invalid,message:e,completionWordList:t}),Fo=e=>e.length===0,rp=(e,t)=>{let n=it(g().breadCrumb,"BOARD");if(d(n))return G({message:De("Command is not applicable in this context")});let o=ml(n.value.id);return d(o)?G({message:De(`Unable to ${t}: board id is not a valid ULID`)}):Pm({date:e,horizonDate:o.value})?null:G({message:De(`nothing to ${t} before ${o.value.toISOString().slice(0,16).replace("T"," ")}`)})},bi=e=>` ${sp.hex("#000").bgHex(Te(e))(` ${e} `)} `,fd=({modifier:e})=>{let t="confirm";return e===t?ee(me):G({message:Fo(e)?le("if you are certain, enter ")+vi(t):"",completionWordList:[t]})},Dx=({list:e,hint:t,onValue:n})=>({modifier:o,inputString:r})=>e.includes(o)?r.trim().length<1?G({message:le(n)}):ee():G({message:Fo(o)?t:"",completionWordList:[...e]}),Do=({hint:e,onOk:t})=>({modifier:n,inputString:o})=>Fo(n)&&Fo(o)?G({message:e,completionWordList:[]}):ee(t??me),Fx=({modifier:e,inputString:t})=>{let n=sd();return!Fo(e)||!Fo(t)?ee(me):G({message:n.length?le("number from the list, or a path"):le("path to an epiq project"),completionWordList:n})},_x=({modifier:e,inputString:t})=>{let n=we(x.CONFIG);if(!n.includes(e))return G({message:Ue({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ve.EDITOR:{let o=[..._m];return t.trim()?o.includes(t.trim())?ee(me):G({message:Ue({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o}):G({message:Ue({prefix:"editors: ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case ve.VIEW:{let o=["dense","wide"];return o.includes(t.trim())?ee(me):G({message:Ue({prefix:"view... ",wordList:o,inputString:t,minLengthForHints:0}),completionWordList:o})}case ve.USERNAME:return t.trim()?ee(me):G({message:De("Enter a user name. Saved in ")+sp.bgBlack("~/.epiq-global/config.json")});case ve.LOG_LEVEL:{let o=["debug","error","info"],r=t.trim();return o.includes(r)?ee(me):G({message:Ue({prefix:"one of: ",wordList:[...o],inputString:r,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...o]})}case ve.AUTOSYNC:{let o=["on","off"],r=Ie().autoSync;if(!o.includes(t.trim())){let s=Tm(r);return G({message:Ue({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:o,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:o})}return ee(me)}case ve.ATTACHMENT_MAX_KB:{let o=Ie().attachmentMaxKb,r=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(r)||r<Vr||r>Kr){let s=Ue({prefix:" examples: ",wordList:rd,minLengthForHints:0,inputString:t});return G({message:De(`provide a size cap in KB (${Vr}-${Kr}). current: ${o??gn} KB.`)+s,completionWordList:rd})}return ee(me)}case ve.SYNC_DEBOUNCE_MS:{let o=Ie().autoSyncIntervalMs,r=ym(t);if(!t.trim()||r===null||r<No){let s=Ue({prefix:" examples: ",wordList:od,minLengthForHints:0,inputString:t});return G({message:De(`provide duration above ${No}ms. current duration: ${o}ms.`)+s,completionWordList:od})}return ee(me)}default:return G({message:De("Unknown config option"),completionWordList:n})}},Ox=({modifier:e,inputString:t})=>{let n=we(x.EDIT);if(!n.length)return G({message:De("Command not available in this context")});if(!n.includes(e)){let o=Ue({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return G({message:o||De("Unknown edit option"),completionWordList:n})}switch(e){case mt.COMMENT:return t.trim()?ee(me):G({message:le("write a comment...")});case mt.TITLE:return ee(me);case mt.DESCRIPTION:{let{preferredEditor:o}=Ie();return o?ee(le("<ENTER> to edit in ")+o):G({message:"No editor selected"})}default:return G({message:De("Unknown edit option"),completionWordList:n})}},Bx=({modifier:e})=>{let t=we(x.YANK);return t.length?t.includes(e)?ee(me+le(" and copy to clipboard")):G({message:Ue({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):G({message:De("Nothing selected to copy from")})},Ux={[x.EXPORT]:()=>ee(me+le(", and create export markdown file")),[x.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return ee(me);let n={message:le("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},o=t||e.inputString.trim(),r=so(o);if(!o||!r)return G(n);let s=rp(r,"peek");return s||ee(me)},[x.REPLAY]:e=>{let{dateInput:t,durationInput:n}=mi(e.modifier,e.inputString),o={message:le("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},r=so(t);if(!t||!r)return G(o);let s=rp(r,"replay");return s||(n&&ui(n)===null?G({message:De("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):ee("<ENTER> to replay board history",n?Fm:[]))},[x.EXIT]:()=>ee(me+le(" and exit the application")),[x.INIT]:()=>ee(me),[x.OPEN]:Fx,[x.PALETTE]:()=>ee(me),[x.FILTER]:e=>{if(e.modifier==="clear")return ee(me);let t=s=>we(x.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return G({message:Ue({wordList:we(x.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:we(x.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())?G({message:Ue({prefix:`existing ${e.modifier}s... `,wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r}):ee():G({message:Ue({prefix:"one of... ",wordList:r,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:r})},[x.NONE]:e=>{let t=we(x.NONE);return G({message:Ue({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[x.NEW]:e=>Dx({list:we(x.NEW),hint:Ue({wordList:we(x.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[x.HELP]:()=>ee(me),[x.EDIT]:Ox,[x.COMMENT]:e=>{let t=Do({hint:le(`write a comment (max ${4e3} char)...`),onOk:le(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===Mn.Invalid?t:e.inputString.length>4e3?ee(De("max input exceeded")):t},[x.CONFIG]:_x,[x.YANK]:Bx,[x.DELETE]:e=>{let t=op();return t.validity==="invalid"?t:fd(e)},[x.CLOSE_ISSUE]:e=>fd(e),[x.RE_OPEN_ISSUE]:e=>fd(e),[x.MOVE]:e=>{let t=op();return t.validity==="invalid"?t:Do({hint:Ue({prefix:"hey hacker! These commands are blocked for you... ",wordList:we(x.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[x.TAG]:e=>{let n=E.getExistingTags().slice(0,10).map(bi).join("");return Do({hint:n.length?le("create tag or reuse:")+n+le(""):le("create tag ...")})(e)},[x.UNTAG]:e=>{let t=ci();if(d(t))return G({message:De("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(bi).slice(0,10);return n.length?Do({hint:le(" ... ")+n.join("")})(e):G({message:De("Issue has no tags"),completionWordList:[]})},[x.ASSIGN]:e=>{let t=E.getExistingAssignees().map(bi).slice(0,10);return Do({hint:le("assignees... ")+t.join("")})(e)},[x.UNASSIGN]:e=>{let t=li();if(d(t))return G({message:De("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:o})=>o).map(bi).slice(0,10);return n.length?Do({hint:le("remove assignee... ")+n.join("")})(e):G({message:De("Issue has no assignees"),completionWordList:[]})},[x.SYNC]:()=>ee(me)},ip=Object.fromEntries(Object.entries(Ux).map(([e,t])=>[e,{validate:(n,o,r)=>t({modifier:o,command:n,inputString:r})}]))});var xi,dp=h(()=>{"use strict";xi=["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 $x,jx,Hx,Wx,qx,cp,lp,up,mp=h(()=>{"use strict";R();M();dp();$x=3,jx=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"]),Hx=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},Wx=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=$x&&!jx.has(t)&&!/^\d+$/.test(t)),qx=e=>{let t=new Map;for(let s of Hx(e))for(let i of Wx(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),o=new Set(n),r=xi.filter(s=>!o.has(s));return[...n,...r]},cp=xi,lp=-1,up=()=>{let e=ze();if(d(e))return xi;let t=e.value,n=t.eventLog.length;return n!==lp&&(cp=qx(t),lp=n),cp}});var pp,fp,gd=h(()=>{"use strict";Rl();pn();ro();ap();mp();M();pe();pp=e=>Object.values(x).includes(e),fp=(e,t)=>{let n=e.command??"",{modifier:o,target:r,inputString:s}=e,{message:i,validity:c,completionWordList:u}=ip[n].validate(n,o,s),m=n!==x.PEEK&&n!==x.REPLAY,p=r==="command"||r==="modifier"?we(n):m?up():[],{mode:f}=g(),y=f===b.COMMAND_LINE?i??"":"",I=[...u,...p];return{validity:c,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:y,autoCompletion:t?Sl(e,I):{hint:"",hints:[],remainder:"",overlap:0}}}});var gp,Gx,zx,Vx,hp=h(()=>{"use strict";gd();pn();gp=e=>{let t=e.trimStart(),n=zx(t),o=n[0]??"",r=n[1]??"",s=/\s$/.test(e),i=Vx(e),c=pp(o)?o:null,u=c!==null,m=o!=="",p=c?we(c)??[]:[],f=c&&p.includes(r)?r:"",y="word";n.length===0||n.length===1&&!s?y="command":(n.length===1&&s||n.length===2&&!s)&&(y="modifier");let I=s?"":i,S=Gx(t,c,f);return{raw:e,trimmedStart:t,words:n,firstWord:o,lastWord:i,hasCommand:m,command:c,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:y,inputToMatch:I,inputString:S}},Gx=(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},zx=e=>e.trim()?e.trim().split(/\s+/):[],Vx=e=>e.trimEnd().split(/\s+/).at(-1)??""});import{useSyncExternalStore as aP}from"react";var _o,hd,Oo,Kx,vp,Vt,Xr,vd,yd,yp,bp,Ii,xp,te,Ip,Ep,Sp,de,Ei,ce=h(()=>{"use strict";gd();hp();R();yi();_o=e=>e===hd||e===":",hd=" ",Oo={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:Mn.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Kx=new Set,vp=()=>{for(let e of Kx)e()},Vt=e=>{let n=e(Oo),o=gp(n.value),r=n.cursorPosition===n.value.length;Oo={...n,commandMeta:fp(o,r)},vp()},Xr=({message:e,status:t})=>{let n=structuredClone(Oo);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Oo=n,vp(),l(e,null)},vd=e=>{Vt(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},yd=e=>{Vt(t=>{let{value:n,cursorPosition:o}=t,r=o;if(e==="left"){for(;r>0&&_o(n[r-1]);)r--;for(;r>0&&!_o(n[r-1]);)r--}else{for(;r<n.length&&!_o(n[r]);)r++;for(;r<n.length&&_o(n[r]);)r++}return{...t,cursorPosition:r}})},yp=()=>{Vt(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}})},bp=()=>{Vt(e=>{let{value:t,cursorPosition:n}=e,o=n;for(;o>0&&_o(t[o-1]);)o--;for(;o>0&&!_o(t[o-1]);)o--;let r=t.slice(n);return{...e,value:t.slice(0,o)+r,cursorPosition:o,commandIsPending:!1}})},Ii=e=>{Vt(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),i=s+r,c=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:c,commandIsPending:!1}})},xp=()=>{Vt(e=>({...e,commandIsPending:!0}))},te=e=>{Vt(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Ip=({addToHistory:e=!0})=>{Vt(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},Ep=()=>{Vt(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}})},Sp=()=>{Vt(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=()=>Oo,Ei=()=>{let[e,...t]=Oo.value.split(hd);return t.join(hd).trim()}});var O,jn=h(()=>{"use strict";pe();gl();M();ce();We();O={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 Rp,B,bd=h(()=>{"use strict";M();ro();Rp=e=>{let{context:t}=g().contextNode;if(!t)return B.None;switch(e){case x.EXIT:return B.Exit;case x.EXPORT:return B.Export;case x.INIT:return B.Init;case x.OPEN:return B.OpenProject;case x.DELETE:return B.Delete;case x.EDIT:return B.Edit;case x.COMMENT:return B.Comment;case x.HELP:return B.ViewHelp;case x.RE_OPEN_ISSUE:return B.ReopenIssue;case x.CLOSE_ISSUE:return B.CloseIssue;case x.TAG:return B.TagTicket;case x.UNTAG:return B.UntagTicket;case x.ASSIGN:return B.AssignUserToTicket;case x.UNASSIGN:return B.UnassignUserFromTicket;case x.NEW:return B.NewItem;case x.FILTER:return B.Filter;case x.MOVE:return B.Move;case x.PEEK:return B.Peek;case x.REPLAY:return B.Replay;case x.CONFIG:return B.Config;case x.YANK:return B.Yank;case x.SYNC:return B.Sync;default:return B.None}},B={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 Np}from"ink";import Cp,{useEffect as Ap,useState as Yx}from"react";var wp,ot,Bo=h(()=>{"use strict";M();Ve();wp={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},ot=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=rt(),o=wp[n]??wp.default,[r,s]=Yx(0);if(Ap(()=>{s(0)},[o]),Ap(()=>{if(!e)return;let c=setInterval(()=>{s(u=>(u+1)%o.length)},500);return()=>clearInterval(c)},[e,o]),!e)return Cp.createElement(Np,null,t);let i=o[r]??o[0]??t;return Cp.createElement(Np,{color:T.accent,dimColor:r===1},i)}});import{Box as xd,Text as Xx}from"ink";import Si from"react";var Jx,Pn,Jr=h(()=>{"use strict";Ve();Jx=(e,t,n,o)=>{let r=u=>Math.max(1,e[u]??1),s=n,i=n+1,c=r(n);for(;i<t&&c+r(i)<=o;)c+=r(i),i++;for(;s>0&&c+r(s-1)<=o;)s--,c+=r(s);return{start:s,end:i}},Pn=({children:e=[],height:t,selectedIndex:n,itemHeight:o=1,itemHeights:r,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=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(i/c)),p=Math.max(0,e.length-m),{start:f,end:y}=r?Jx(r,e.length,u,i):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},I=Math.max(1,y-f),S=e.slice(f,y),A=e.length>I,w=i,k=A?Math.max(1,Math.floor(I/e.length*w)):w,D=Math.max(0,w-k),_=Math.max(1,e.length-I),H=A?Math.floor(f/_*D):0;return Si.createElement(xd,{flexDirection:"row",height:i,width:"100%"},Si.createElement(xd,{flexDirection:"column",flexGrow:1,height:i},S),Si.createElement(xd,{flexDirection:"column",width:1,height:w},Array.from({length:w}).map((ie,En)=>Si.createElement(Xx,{key:En,color:A&&En>=H&&En<H+k?T.accent:T.secondary},A?"\u2502":" "))))}});var Tp,Id,Qx,Ri,Ed=h(()=>{"use strict";M();Qx=()=>{let{eventLog:e=[]}=g();if(Id&&Tp===e)return Id;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Tp=e,Id=t,t},Ri=e=>Qx().has(e)});import{Text as Zx}from"ink";import eI from"react";var tI,nI,Uo,Ni=h(()=>{"use strict";di();pt();ne();Ed();dt();tI=e=>e.toLowerCase().trim(),nI=(e,t=wo)=>{let n=tI(e);return t[n]?t[n]:Yr(n)},Uo=({id:e,isSelected:t,maxWidth:n})=>{let o=E.getContributor(e);if(!o)return;let r=o.name,s=n===void 0?r:Hn(r,n);return eI.createElement(Zx,{underline:t,color:nI(r)},"@"+s,Ri(e)?"":"\u2197")}});import{Text as oI}from"ink";import rI from"react";var Ci,Sd=h(()=>{"use strict";ne();Ve();pt();dt();Ci=({id:e,isSelected:t,maxWidth:n})=>{let o=E.getTag(e);if(!o)return;let r=n===void 0?o.name:Hn(o.name,n);return rI.createElement(oI,{underline:t,backgroundColor:Te(o.name),color:T.secondary}," "+r+" ")}});import{useEffect as sI,useState as iI}from"react";var aI,kp,Ai,Qr,dI,cI,$o,wi=h(()=>{"use strict";pt();aI=80,kp=1400,Ai=new Set,Qr=null,dI=e=>(Ai.add(e),Qr||(Qr=setInterval(()=>{for(let t of Ai)t()},aI)),()=>{Ai.delete(e),Ai.size===0&&Qr&&(clearInterval(Qr),Qr=null)}),cI=()=>{let e=Date.now()%kp/kp;return e<.5?e*2:(1-e)*2},$o=e=>{let[,t]=iI(0);return sI(()=>{if(e)return dI(()=>t(n=>n+1))},[e]),ep(cI())}});import{Box as jo,Text as Ho}from"ink";import st from"react";var lI,Mp,uI,mI,Pp,Lp=h(()=>{"use strict";ne();Ve();dt();Ed();Je();Wr();Ni();Sd();wi();lI=(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),Hn(e.slice(r).trim(),n)]},Mp=3,uI=2,mI=(e,t)=>{let n=[],o=0;for(let[r,s]of e.entries()){let i=e.length-r-1,c=i>0?String(i).length+1:0;if(o+s.width+c>t)break;o+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},Pp=({width:e,ticket:t,isSelected:n,isFlashing:o=!1})=>{let r=$o(o),s=e-4,i=s-7-1,[c,u]=lI(fe(t.title),i,s),m=u?null:Hn(fe(t.props.description),s)||null,p=Tn(t),f=kn(t).map(k=>({...k,name:k.name})),y=Math.max(1,s-Mp),I=E.getCommentsByIssue(t.id),S=I.length?String(I.length).length+2+1:0,{shown:A,hidden:w}=mI([...p.map(k=>({id:k.id,isTag:!0,width:Math.min(k.name.length,y)+Mp})),...f.map(k=>({id:k.id,isTag:!1,width:Math.min(k.name.length,y)+uI+(Ri(k.id)?0:1)}))],s-S);return st.createElement(jo,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:o?r:n?T.accent:T.secondary,justifyContent:"space-between"},st.createElement(jo,{paddingLeft:1,paddingRight:1,flexDirection:"column"},st.createElement(jo,{justifyContent:"space-between"},st.createElement(Ho,{color:T.primary},c),st.createElement(Ho,{color:T.secondary2,dimColor:!0},j(t.id))),u&&st.createElement(Ho,{color:T.primary},u),m&&st.createElement(Ho,{color:T.secondary2,dimColor:!0},m)),st.createElement(jo,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},st.createElement(jo,{flexDirection:"row"},A.map(k=>st.createElement(jo,{paddingRight:1,key:k.id},k.isTag?st.createElement(Ci,{id:k.id,maxWidth:y}):st.createElement(Uo,{id:k.id,maxWidth:y}))),w>0&&st.createElement(Ho,{color:T.secondary2,dimColor:!0},"+",w)),I.length>0&&st.createElement(Ho,{color:T.accent},"[",I.length,"]")))}});import{Box as ao,Text as Zr}from"ink";import ft from"react";var pI,Dp,Fp=h(()=>{"use strict";pe();ne();Ve();pt();Bo();wi();pI=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,Dp=({index:e,labelWidth:t,width:n,ticket:o,isSelected:r,isFlashing:s=!1,mode:i})=>{let c=$o(s),u=(o.props.tags??[]).map(ie=>E.getTag(ie)).filter(ie=>!!ie),m=(o.props.assignees??[]).map(ie=>E.getContributor(ie)).map(ie=>ie&&{...ie,name:ie.name}).filter(ie=>!!ie),p=1,f=u.length*(1+p),y=m.length*(2+p),I=u.map(ie=>ft.createElement(ao,{key:ie.id,paddingRight:p},ft.createElement(Zr,{color:Te(ie.name)},"\u25A0"))),S=m.map(ie=>ft.createElement(ao,{key:ie.id,paddingRight:p},ft.createElement(Zr,{color:Yr(ie.name)},"@"+ie.name.at(0)))),A=s?c:r?T.accent:i===b.MOVE?T.secondary:T.primary,w=E.getCommentsByIssue(o.id),k=w.length?String(w.length).length+2+p:0,D=w.length?ft.createElement(ao,{paddingRight:p},ft.createElement(Zr,{color:T.accent},"[",w.length,"]")):null,_=f+y+k,H=Math.max(1,n-t-_-(_>0?1:0));return ft.createElement(ao,{justifyContent:"space-between"},ft.createElement(ao,null,ft.createElement(ao,{width:t},r?ft.createElement(ot,{isSelected:!0}):ft.createElement(Zr,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),ft.createElement(Zr,{wrap:"truncate",color:A},pI(o.title,H))),ft.createElement(ao,null,I,S,D))}});import fI from"chalk";import{Box as Rd,Text as gI}from"ink";import Kt from"react";var hI,_p,Op=h(()=>{"use strict";K();M();Ve();Bo();Jr();Lp();Fp();wi();hI=({swimlane:e,isSelected:t,width:n,height:o,isDense:r,isFocused:s,listSelectedIndex:i,mode:c})=>{let{renderedChildrenIndex:u,replay:m}=rt(),p=u[e.id]??[],f=m?new Set(m.flashNodeIds):null,y=f?.has(e.id)??!1,I=$o(y),S=`${e.title} ${fI.hex(T.secondary2).dim("("+p.length+")")}`,A=3,w=r?1:5,k=s&&i===-1,D=n-3-(r?1:0)-(k?2:0),_=Math.max(2,String(p.length).length+1),H=o-A-1,ie=Kt.createElement(Rd,{borderStyle:"round",borderColor:T.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:r?1:0},Kt.createElement(ot,{isSelected:t}),Kt.createElement(gI,{bold:!0,color:y?I:t?T.accent:T.primary},S," ",e.readonly?"\u{1F512}":"")),En=(en,ar)=>{let dr=s&&i===ar;if(!P(en))return null;let ho=f?.has(en.id)??!1;return r?Kt.createElement(Dp,{key:en.id,index:ar,labelWidth:_,width:D,ticket:en,isSelected:dr,isFlashing:ho,mode:c}):Kt.createElement(Pp,{key:en.id,width:D,ticket:en,isSelected:dr,isFlashing:ho})};return Kt.createElement(Rd,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?T.accent:T.secondary,paddingRight:0,paddingLeft:r?1:0,height:o},ie,Kt.createElement(Rd,null,p.length>0&&Kt.createElement(Pn,{selectedIndex:i,height:H,itemHeight:w},p.map(En)),k&&Kt.createElement(ot,{isSelected:!0})))},_p=Kt.memo(hI)});var Bp,Up,Nd=h(()=>{"use strict";Gn();Bp=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},Up=(e,t,n)=>Pe.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0})});var qo,Ti=h(()=>{"use strict";qo=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 Go,Text as vn}from"ink";import je,{useEffect as vI,useMemo as yI,useRef as bI}from"react";import{decodeTime as $p}from"ulid";function Hp({ticket:e,width:t,height:n}){let o=yI(()=>II(e),[e]),r=bI([]);vI(()=>(jp(r.current),r.current=SI(e,o),()=>{jp(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=rt(),c=Math.max(1,n-4),u=Math.max(12,t-32);return o.length===0?je.createElement(Go,{flexDirection:"column",width:t,height:n,padding:1},je.createElement(vn,{color:T.primary},"No attachments yet."),je.createElement(Go,{paddingTop:1},je.createElement(vn,{color:T.primary},"Attach images from the browser GUI"),je.createElement(vn,{color:T.accent}," epiq gui "),je.createElement(vn,{color:T.primary},"by dropping or pasting them."))):je.createElement(Go,{flexDirection:"column",width:t,height:n},je.createElement(Go,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:T.secondary,borderStyle:"single",paddingBottom:1},je.createElement(vn,{color:T.secondary2},"Attachments (",o.length,") \u2014 enter to open"," ")),je.createElement(Pn,{height:c,itemHeight:2,selectedIndex:s},o.map((m,p)=>{let f=p===s,y=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return je.createElement(Go,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},je.createElement(vn,{color:T.accent},f?"\u276F ":" "),je.createElement(Go,{paddingLeft:1},je.createElement(vn,{color:T.secondary2},`#${p+1} `),je.createElement(vn,{color:f?T.accent:T.primary},y),je.createElement(vn,{color:T.secondary2}," "+RI(m.bytes)+" "+qo(He(m.id)))))})))}var xI,II,jp,EI,SI,RI,Wp=h(()=>{"use strict";ut();Ke();Ti();K();R();ne();Gn();M();Ve();Lo();Jr();xI=e=>Le(e,"attachments"),II=e=>E.getAttachmentsByIssue(e.id).sort((t,n)=>$p(t.id)-$p(n.id)),jp=e=>{for(let t of e)E.deleteNode(t.id)},EI=(e,t,n)=>Pe.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),SI=(e,t)=>{let n=E.getNode(xI(e.id));if(!n||!at(n))return[];let o=t.map((r,s)=>EI(r,s,n.id)).map(r=>E.createNode(r)).filter(Dt).map(({value:r})=>r).filter(at);return t.length>0&&g().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),o},RI=e=>`${Math.max(1,Math.round(e/1024))} KB`});var Gp,Cd,qp,Ad,zp,Vp,NI,Kp,CI,wd,Yp=h(()=>{"use strict";Gp=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,Cd=e=>e.replace(Gp,""),qp=e=>e==="additions"||e==="deletions",Ad=e=>{let t=Gp.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"||!qp(o.side)||!qp(o.endSide)||o.sha!==void 0&&typeof o.sha!="string"||o.issueRef!==void 0&&typeof o.issueRef!="string"?null:o},zp=/```\n([\s\S]*?)\n?```\s*$/,Vp=e=>zp.exec(e)?.[1]??null,NI=/`[^`\n]+`[^\n]*\n?$/,Kp=e=>Cd(e).replace(zp,"").replace(NI,"").trim(),CI=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})`},wd=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${CI(e)}`});var AI,es,wI,TI,kI,MI,Jp,Td,Qp,Xp,Zp,kd=h(()=>{"use strict";Yp();AI=(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 i of o){let c=i;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},es=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)},wI=/!\[([^\]]*)\]\([^)]*\)/g,TI=e=>e.replace(wI,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),kI=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),MI=4,Jp=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(MI)),Td=e=>{let t=!1;return e.map(Jp).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let o=Ad(n);if(o)return{kind:"caption",text:wd(o)};let r=TI(n);if(r.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(r);return s?{kind:"heading",spans:es(s[1]??"")}:{kind:"text",spans:es(r)}})},Qp=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Xp=(e,t)=>{let n=[];for(let o of Td(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 Qp(o.text,t))n.push({kind:"code",text:r});continue}if(o.kind==="caption"){n.push(o);continue}for(let r of AI(kI(o.spans),t))n.push({kind:o.kind,spans:es(r)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},Zp=(e,t)=>{let n=Ad(e),o=n?Vp(e):null;if(!n||o===null)return Xp(Cd(e).split(`
77
+ `),t);let r=Kp(e),s=o.split(`
78
+ `).map(Jp),i=n.side===n.endSide?n.start:void 0,c=i===void 0?0:String(i+s.length-1).length+3;return[...r?[...Xp(r.split(`
79
+ `),t),{kind:"blank"}]:[],{kind:"caption",text:wd(n)},...s.flatMap((u,m)=>Qp(u,Math.max(1,t-c)).map((p,f)=>({kind:"code",text:p,number:i===void 0||f>0?void 0:i+m})))]}});import{Box as ef,Text as co}from"ink";import Rt from"react";var tf,Md,nf,Pd=h(()=>{"use strict";Ve();tf=({spans:e,bold:t,wrap:n})=>Rt.createElement(co,{color:T.primary,bold:t,wrap:n},e.map((o,r)=>o.code?Rt.createElement(co,{key:r,color:T.yellow},o.text):Rt.createElement(co,{key:r},o.text))),Md=({line:e,width:t,gutter:n=0,wrap:o})=>{switch(e.kind){case"blank":return Rt.createElement(co,null," ");case"fence":return Rt.createElement(co,{color:T.secondary2},"```");case"caption":return Rt.createElement(co,{color:T.accent,wrap:o},e.text);case"heading":return Rt.createElement(tf,{spans:e.spans,bold:!0,wrap:o});case"text":return Rt.createElement(tf,{spans:e.spans,wrap:o});case"code":{let r=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return Rt.createElement(co,{backgroundColor:T.secondary,color:T.primary,wrap:o},r,e.text.padEnd(Math.max(0,t-r.length)))}}},nf=({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 Rt.createElement(ef,{flexDirection:"column"},e.map((r,s)=>Rt.createElement(ef,{key:s},Rt.createElement(Md,{line:r,width:t,gutter:o}))))}});import{Box as Ln,Text as Dn}from"ink";import ke,{useEffect as PI,useMemo as of,useRef as LI}from"react";import{decodeTime as rf}from"ulid";function af({ticket:e,width:t,height:n}){let o=of(()=>_I(e),[e]),r=LI([]);PI(()=>(sf(r.current),r.current=OI(e,o),()=>{sf(r.current),r.current=[]}),[e,o]);let{selectedIndex:s}=rt(),c=Math.max(1,n-4),u=Math.max(20,t-8),m=of(()=>o.map(f=>{let y=Zp(f.md,u);return y.length>0?y:[{kind:"blank"}]}),[o,u]),p=m.map(f=>f.length+DI);return o.length===0?ke.createElement(Ln,{flexDirection:"column",width:t,height:n,padding:1},ke.createElement(Dn,{color:T.primary},"No comments yet."),ke.createElement(Ln,{paddingTop:1},ke.createElement(Dn,{color:T.primary},"Use"),ke.createElement(Dn,{color:T.accent}," :comment "),ke.createElement(Dn,{color:T.primary},"to add the first one."))):ke.createElement(Ln,{flexDirection:"column",width:t,height:n},ke.createElement(Ln,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:T.secondary,borderStyle:"single",paddingBottom:1},ke.createElement(Dn,{color:T.secondary2},"Comments (",o.length,") ")),ke.createElement(Pn,{height:c,itemHeights:p,selectedIndex:s},o.map((f,y)=>{let I=y===s;return ke.createElement(Ln,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:T.secondary,borderStyle:"single"},ke.createElement(Ln,{flexDirection:"row",paddingBottom:1},ke.createElement(Dn,{color:T.accent},I?"\u276F ":" "),ke.createElement(Ln,{paddingLeft:1},ke.createElement(Dn,{color:T.secondary2},`#${y+1} `),ke.createElement(Uo,{id:f.authorId}),ke.createElement(Dn,{color:T.secondary2}," "+qo(He(f.id))))),ke.createElement(Ln,{paddingLeft:3,paddingBottom:1},ke.createElement(nf,{lines:m[y]??[],width:u})))})))}var DI,FI,_I,sf,OI,df=h(()=>{"use strict";ut();Ke();Ti();K();R();ne();M();Ve();Lo();Ni();Jr();Nd();kd();Pd();DI=4,FI=e=>Le(e,"comments"),_I=e=>E.getCommentsByIssue(e.id).sort((t,n)=>rf(t.id)-rf(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),sf=e=>{for(let t of e)E.deleteNode(t.id)},OI=(e,t)=>{let n=E.getNode(FI(e.id));if(!n||!at(n))return[];let o=t.map((r,s)=>Up(r,s,n.id)).map(E.createNode).filter(Dt).map(({value:r})=>r).filter(hr);return t.length>0&&g().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),o}});import{Box as ki,Text as BI}from"ink";import yn from"react";var cf,lf=h(()=>{"use strict";K();ne();Io();M();Ve();Ni();Bo();Sd();cf=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:o}=rt(),{title:r}=t,s=t.parentNodeId?E.getNode(t.parentNodeId):void 0,i=s&&P(s)?r===ue.ASSIGNEES?s.props.assignees??[]:r===ue.TAGS?(s.props.tags??[]).filter(c=>E.getTag(c)):[]:[];return yn.createElement(ki,{alignItems:"center",paddingTop:1},yn.createElement(ki,{minWidth:12},yn.createElement(ot,{isSelected:n}),yn.createElement(BI,{color:n?T.accent:T.secondary2},r,":")),yn.createElement(ki,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((c,u)=>{let m=o.id===t.id&&u===e;return yn.createElement(ki,{key:`${r}-${c}`,paddingRight:2,minHeight:1},yn.createElement(ot,{isSelected:m}),r===ue.ASSIGNEES?yn.createElement(Uo,{isSelected:m,id:c}):r===ue.TAGS?yn.createElement(Ci,{isSelected:m,id:c}):null)})))}});var Ld,uf,Dd,Fd=h(()=>{"use strict";Ld=e=>Math.max(5,String(Math.max(e,1)).length+3),uf=(e,t)=>Math.max(0,e-6-Ld(t)),Dd=(e,t=0)=>Math.max(1,e-5-2*t)});import{Box as zo,Text as _d}from"ink";import Nt,{useEffect as UI,useMemo as Od}from"react";var $I,mf,Bd,pf,jI,Ud,ff=h(()=>{"use strict";ne();R();Gn();M();Ve();dt();Fd();Bo();Jr();Pd();kd();yo();$I="\u2029",mf=(e,t)=>`${e}::inline-line::${t}`,Bd=new Map,pf=e=>{let t=Bd.get(e)??[];Bd.delete(e);for(let n of t)E.deleteNode(n)},jI=(e,t)=>{pf(e);let n=[];t.forEach((o,r)=>{let s=vt(BigInt(r+1));if(!Dt(s))return;let i=E.createNode(Pe.text({id:mf(e,r),name:`Line ${r+1}`,parentNodeId:e,rank:s.value,props:{value:o},readonly:!0,isVirtual:!0}));Dt(i)&&n.push(i.value.id)}),Bd.set(e,n)},Ud=({id:e,label:t,text:n,rows:o,selected:r,maxWidth:s})=>{let{selectedIndex:i,contextNode:c}=rt(),u=Od(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Od(()=>u.join("\0"),[u]);UI(()=>(jI(e,u),()=>{pf(e)}),[e,m]);let p=Ld(u.length),f=uf(s,u.length),I=Od(()=>Td(u).map(S=>{if(S.kind==="code"||S.kind==="caption")return{...S,text:ia(S.text,f)};if(S.kind==="text"||S.kind==="heading"){let A=S.spans.map(w=>w.code?`\`${w.text}\``:w.text).join("");return{...S,spans:es(ia(A,f))}}return S}),[u,f]).map((S,A)=>{let w=c.id===e&&i===A;return Nt.createElement(zo,{key:mf(e,A)},Nt.createElement(zo,{flexShrink:0},Nt.createElement(_d,{color:w?T.primary:T.secondary2,dimColor:!w},`${A+1} `.padStart(p,"\xA0"))),S.kind==="blank"?Nt.createElement(_d,{backgroundColor:w?"gray":void 0},$I):Nt.createElement(zo,null,Nt.createElement(Md,{line:S,width:S.kind==="code"?f:0,wrap:"truncate-end"})))});return Nt.createElement(zo,{flexDirection:"column",paddingTop:1},Nt.createElement(zo,null,Nt.createElement(ot,{isSelected:r}),Nt.createElement(_d,{color:r?T.accent:T.secondary2},t)),Nt.createElement(zo,{flexDirection:"row",borderStyle:"round",borderColor:T.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},Nt.createElement(Pn,{scrollByOne:!0,height:o,selectedIndex:i,itemHeight:1},I)))}});import{Box as lo,Text as $d}from"ink";import Fe,{useMemo as ts}from"react";var HI,WI,qI,GI,gf,hf=h(()=>{"use strict";K();ne();M();Ve();Nd();Lo();Wp();df();Bo();lf();ff();Fd();HI=e=>Le(e,"description"),WI=e=>Le(e,"comments"),qI=e=>Le(e,"history"),GI=e=>Le(e,"attachments"),gf=({ticket:e,height:t})=>{let n=ts(()=>Bp(e),[e]),{selectedIndex:o,contextNode:r}=rt(),s=process.stdout.columns||120,i=ts(()=>HI(e.id),[e.id]),c=ts(()=>WI(e.id),[e.id]),u=ts(()=>qI(e.id),[e.id]),m=ts(()=>GI(e.id),[e.id]),p=E.getAttachmentsByIssue(e.id).length,f=r.id===e.id,y=r.id===c||r.parentNodeId===c,I=r.id===u||r.parentNodeId===u,S=r.id===m||r.parentNodeId===m,A=se(e.id);if(y){let H=t-3;return Fe.createElement(lo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Fe.createElement(af,{ticket:e,width:s,height:H}))}if(S){let H=t-3;return Fe.createElement(lo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Fe.createElement(Hp,{ticket:e,width:s,height:H}))}if(I){let _=E.getNode(u),H=_&&at(_)?_.props.value??"":"",ie=Dd(t);return Fe.createElement(lo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},_?Fe.createElement(Ud,{id:_.id,label:"Event log",text:H,selected:!1,maxWidth:s,rows:ie}):null)}let w=A.reduce((_,H)=>fr(H)||H.id===c||H.id===m||H.id===u?_+1:_,0),k=Dd(t,w),D=(_,H)=>_.id===i?Fe.createElement(Ud,{key:_.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:H,maxWidth:s,rows:k}):fr(_)?Fe.createElement(cf,{key:_.id,parent:_,selected:H,selectedIndex:o}):_.id===c?Fe.createElement(lo,{key:_.id,paddingTop:1},Fe.createElement(ot,{isSelected:H}),Fe.createElement($d,{backgroundColor:T.secondary,color:H?T.accent:T.primary},` Comments (${n}) \u203A\u203A `)):_.id===m?Fe.createElement(lo,{key:_.id,paddingTop:1},Fe.createElement(ot,{isSelected:H}),Fe.createElement($d,{backgroundColor:T.secondary,color:H?T.accent:T.primary},` Attachments (${p}) \u203A\u203A `)):_.id===u?Fe.createElement(lo,{key:_.id,paddingTop:1},Fe.createElement(ot,{isSelected:H}),Fe.createElement($d,{backgroundColor:T.secondary,color:H?T.accent:T.primary}," History \u203A\u203A ")):null;return Fe.createElement(lo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},A.map((_,H)=>D(_,f&&o===H)))}});import{Box as zI}from"ink";import Mi from"react";var VI,vf,yf=h(()=>{"use strict";K();Op();hf();VI=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,viewMode:s,height:i,width:c})=>{let u=t.context,m=u===V.TICKET||u===V.FIELD_LIST||u===V.FIELD,p=u===V.BOARD||u===V.SWIMLANE,f=u===V.TICKET?t:o.find(w=>w.context===V.TICKET),y=Math.floor(c/3),I=Math.floor(c/Math.max(e.length,1)),S=Math.min(I,y),A=s==="dense";return Mi.createElement(zI,{flexDirection:"row",height:i},p&&e.map((w,k)=>{let D=t.id===w.id,_=D?n:-1,H=t.context===V.BOARD&&n===k;return Mi.createElement(_p,{key:w.id,height:i,width:S,swimlane:w,isSelected:H,isDense:A,isFocused:D,listSelectedIndex:_,mode:r})}),m&&f&&Mi.createElement(gf,{height:i,ticket:f}))},vf=Mi.memo(VI)});import bf from"node:fs";import KI from"node:path";import YI from"react";import{render as XI}from"ink";import{Writable as JI}from"node:stream";var ns,QI,ZI,eE,tE,xf,If=h(()=>{"use strict";yf();K();R();M();ae();We();ns=e=>String(e).padStart(2,"0"),QI=e=>{let t=e.getUTCFullYear(),n=ns(e.getUTCMonth()+1),o=ns(e.getUTCDate()),r=ns(e.getUTCHours()),s=ns(e.getUTCMinutes()),i=ns(e.getUTCSeconds());return`${t}-${n}-${o}_${r}-${s}-${i}`},ZI=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",eE=async(e,{width:t,height:n})=>{let o="",r=new JI({write(i,c,u){let m=tE(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(o=m),u()}});r.columns=t,r.rows=n,r.isTTY=!0;let s=XI(e,{stdout:r,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),o},tE=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),xf=async()=>{let{viewMode:e}=Ie(),{contextNode:t,selectedIndex:n,breadCrumb:o,mode:r,renderedChildrenIndex:s}=g(),i=o.find(k=>k.context==="BOARD");if(!i)return a("No board found to export");let c=120,u=40,m=await eE(YI.createElement(vf,{height:u,width:c,swimlanes:(s[i.id]??[]).filter(k=>k!==void 0&&Sn(k)),contextNode:t,selectedIndex:n,breadCrumb:o,viewMode:e??"dense",mode:r}),{width:c,height:u});if(!m)return a("Failed to render board export");let p=Ls(process.cwd());if(d(p))return a("Unable to export, epiq root not found");let f=new Date,y=QI(f),I=`board_${ZI(i.title)}_${y}.md`,S=Ql(p.value);bf.mkdirSync(S,{recursive:!0});let A=KI.join(S,I),w=`# Board - ${i.title}
80
+ Date: ${f.toISOString()}
63
81
 
64
82
  \`\`\`text
65
83
  ${m}
66
84
  \`\`\`
67
- `;return xm.writeFileSync(M,w,"utf8"),l("Exported board layout",M)}});var js,Va=v(()=>{"use strict";js=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null}});import{useSyncExternalStore as Qk}from"react";var za,fb,hb,xr,vb,hn,Hs=v(()=>{"use strict";N();fb=new Set,hb=()=>{for(let e of fb)e()},xr=()=>{if(!za)throw new Error("Ui state not initialized. Call initUiState() first.");return za},vb=e=>{let t=xr();return za=e(t),hb(),l("UX state updated",null)},hn=e=>vb(t=>({...t,...e}))});import{spawn as rL,spawnSync as yb}from"node:child_process";import bb from"node:os";import Sm from"node:path";import{ulid as Ib}from"ulid";function Nm(e){let t=[],n="",r=!1,o=null;for(let s of e.trim()){if(o){s===o?o=null:n+=s;continue}if(s==='"'||s==="'"){o=s,r=!0;continue}if(/\s/.test(s)){r&&t.push(n),n="",r=!1;continue}n+=s,r=!0}return r&&t.push(n),t}function xb(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Cm(){let{preferredEditor:e}=ve(),t=[e?xb(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Am(e){let[t=""]=Nm(e);return/(^|\/)code(-insiders)?$/.test(t)}function Eb(e,t){let[n="",...r]=Nm(e);return{command:n,args:[...r,...t]}}function Rb(e,t){return Eb(e,Am(e)?["--wait",t]:[t])}function Tm(e){let t=Sm.join(bb.tmpdir(),"epiq");We.mkDir(t);let n=Sm.join(t,Ib());We.writeToFile(n,e??"");let r=Cm();for(let o of r){let{command:s,args:d}=Rb(o,n);if(!s)continue;let c=yb(s,d,{stdio:"inherit"});if(!c.error&&c.status===0){let u=We.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 Ka=v(()=>{"use strict";N();Be();Rs()});import{ulid as Ya}from"ulid";var wm,Sb,Nb,Mm=v(()=>{"use strict";Ka();On();ht();It();fe();N();tr();le();k();ne();un();wm=async e=>{let{contextNode:t,selectedIndex:n}=f(),r=ae(t.id)[n];if(e.modifier===Qe.DESCRIPTION)return Nb();if(r&&wr(r))return Sb(e);if(e.modifier===Qe.TITLE){let o=ge();if(a(o))return i("Unable to resolve user ID");let s=r;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 Nt();return a(c)?c:B([{id:Ya(),action:"edit.title",payload:{id:s.id,name:d},...o.value}],c.value)}return i("Unknown edit command")},Sb=async e=>{let t=ge();if(a(t))return i("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=f(),o=ae(n.id)[r];if(!o||!wr(o))return i("Select a comment first");if(o.readonly)return i("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return i("Unable to resolve comment issue");let d=f().nodes[s];if(!d||!P(d))return i("Unable to resolve comment issue");if(d.readonly)return i("Cannot edit readonly issue");let c=o.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 Nt();if(a(p))return p;let g=p.value;return B([{id:Ya(),action:"edit.issue.comment",payload:{id:u.id,issue:d.id,md:m},...t.value}],g)},Nb=async()=>{let e=ge();if(a(e))return i("Unable to resolve user ID");let t=await Nt();if(a(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=f(),s=Ke([...r,o],"TICKET");if(a(s))return i("Edit target must be an issue");let d=s.value;if(!P(d))return i("Edit target must be an issue");if(d.readonly)return i("Cannot edit readonly issue");let c=ae(d.id).find(g=>g.title===ie.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=Tm(u);if(a(m))return i("Failed to edit field");let p=m.value;return p===u?l("No changes made",null):B([{id:Ya(),action:"edit.description",payload:{id:d.id,md:p},...e.value}],n)}});import Xa from"node:fs";import Cb from"node:path";var km,Lm=v(()=>{"use strict";N();Rt();km=async e=>{let t=Cb.join(e,".gitignore"),n=Xa.existsSync(t)?Xa.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
68
- `).map(u=>u.trim()),s=r.filter(u=>!o.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(`
85
+ `;return bf.writeFileSync(A,w,"utf8"),l("Exported board layout",A)}});import{useSyncExternalStore as jD}from"react";var jd,nE,oE,Vo,rE,Fn,Pi=h(()=>{"use strict";R();nE=new Set,oE=()=>{for(let e of nE)e()},Vo=()=>{if(!jd)throw new Error("Ui state not initialized. Call initUiState() first.");return jd},rE=e=>{let t=Vo();return jd=e(t),oE(),l("UX state updated",null)},Fn=e=>rE(t=>({...t,...e}))});import{spawn as zD,spawnSync as sE}from"node:child_process";import iE from"node:os";import Ef from"node:path";import{ulid as aE}from"ulid";function Sf(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 dE(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Rf(){let{preferredEditor:e}=Ie(),t=[e?dE(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Nf(e){let[t=""]=Sf(e);return/(^|\/)code(-insiders)?$/.test(t)}function cE(e,t){let[n="",...o]=Sf(e);return{command:n,args:[...o,...t]}}function lE(e,t){return cE(e,Nf(e)?["--wait",t]:[t])}function Cf(e){let t=Ef.join(iE.tmpdir(),"epiq");Ze.mkDir(t);let n=Ef.join(t,aE());Ze.writeToFile(n,e??"");let o=Rf();for(let r of o){let{command:s,args:i}=lE(r,n);if(!s)continue;let c=sE(s,i,{stdio:"inherit"});if(!c.error&&c.status===0){let u=Ze.readFile(n);if(u==null)return a("Unable to read edited file");let m=u.replace(/\r?\n$/,"");return l("Successfully edited",m)}}return a("Unable to open editor")}var Hd=h(()=>{"use strict";R();We();gi()});import{ulid as Wd}from"ulid";var Af,uE,mE,wf=h(()=>{"use strict";Hd();Se();Ce();Ft();K();R();Io();ne();M();ae();pn();Af=async e=>{let{contextNode:t,selectedIndex:n}=g(),o=se(t.id)[n];if(e.modifier===mt.DESCRIPTION)return mE();if(o&&hr(o))return uE(e);if(e.modifier===mt.TITLE){let r=oe();if(d(r))return a("Unable to resolve user ID");let s=o;if(!s)return a("Missing node");if(s.readonly)return a("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return a("Provide a title");let c=await $t();return d(c)?c:L([{id:Wd(),action:"edit.title",payload:{id:s.id,name:i},...r.value}],c.value)}return a("Unknown edit command")},uE=async e=>{let t=oe();if(d(t))return a("Unable to resolve user ID");let{contextNode:n,selectedIndex:o}=g(),r=se(n.id)[o];if(!r||!hr(r))return a("Select a comment first");if(r.readonly)return a("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return a("Unable to resolve comment issue");let i=g().nodes[s];if(!i||!P(i))return a("Unable to resolve comment issue");if(i.readonly)return a("Cannot edit readonly issue");let c=r.id.split(":").at(0)??"",u=E.getComment(c);if(!u||u.deleted)return a("Unable to resolve comment");if(u.issue!==i.id)return a("Comment does not belong to selected issue");if(u.authorId!==t.value.userId)return a("You can only edit your own comments"+u.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return a("Provide a comment");let p=await $t();if(d(p))return p;let f=p.value;return L([{id:Wd(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:m},...t.value}],f)},mE=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let t=await $t();if(d(t))return t;let n=t.value,{breadCrumb:o,selectedNode:r}=g(),s=it([...o,r],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!P(i))return a("Edit target must be an issue");if(i.readonly)return a("Cannot edit readonly issue");let c=se(i.id).find(f=>f.title===ue.DESCRIPTION);if(!c)return a("No target found");if(c.readonly)return a("Cannot edit readonly field");let u=i.props.description??"";if(typeof u!="string")return a("Selected field is not editable text");let m=Cf(u);if(d(m))return a("Failed to edit field");let p=m.value;return p===u?l("No changes made",null):L([{id:Wd(),action:"edit.description",payload:{id:i.id,md:p},...e.value}],n)}});import qd from"node:fs";import pE from"node:path";var Tf,kf=h(()=>{"use strict";R();xt();Tf=async e=>{let t=pE.join(e,".gitignore"),n=qd.existsSync(t)?qd.readFileSync(t,"utf8"):"",o=[".epiq/events/",".epiq/log/"],r=n.split(`
86
+ `).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(`
69
87
  `);return n=n.trimEnd()+`
70
88
 
71
89
  ${c}
72
- `,Xa.writeFileSync(t,n,"utf8"),X.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)}});import Ab from"node:fs";import Pm from"node:path";var Tb,oe,Dm,Om=v(()=>{"use strict";Lm();Uo();pt();ut();Jr();Je();no();Vr();Ut();ht();pe();N();Ft();be();Be();k();ne();Tb=async e=>{let t=await W({cwd:e,args:["status","--porcelain"]});return a(t)?t:l("Checked git diff",t.value.stdout.trim().length>0)},oe=(e,t)=>i(`[${e}] ${t}`),Dm=async()=>{Y("");let e=Bo(),t=await mt(process.cwd());if(a(t))return oe(1,t.message);let n=t.value,r=await $o(n);if(a(r))return oe(2,r.message);if(r.value)return oe(2,`Cannot initialize Epiq while a git operation is in progress: ${r.value}`);let o=await Tb(n);if(a(o))return oe(2.5,o.message);if(o.value)return oe(3,"Cannot initialize Epiq with uncommitted changes. Commit or stash your changes first.");if(_r(n))return oe(4,"Epiq project already initialized");let s=fs();if(!s.isSetupDone||!s.userName)return oe(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let d=ve(),c=d.userName,u=d.userId;if(!u||!c)return oe(5,"Missing Epiq user id");let m=await dl(n);if(a(m))return oe(6,m.message);let p=e.stateBranch,g=await jo({repoRoot:n,branch:p});if(a(g))return oe(6,g.message);if(g.value)return oe(6,`State branch already exists: ${p}`);let x=await Ki({repoRoot:n,stateBranchName:p});if(a(x))return oe(6,x.message);let S=Go();if(a(S))return oe(7,S.message);let C=Pm.join(Wo(),e.projectId),M=await _n({repoRoot:n,stateBranchRoot:C,stateBranchName:p});if(a(M))return oe(8,M.message);let w=Pm.join(C,".epiq");Ab.mkdirSync(w,{recursive:!0});let T=Qc({userId:u,userName:c});if(a(T))return oe(9,T.message);for(let ii of T.value){let bd=es({event:ii,rootDir:C});if(a(bd))return oe(9,bd.message)}let _=await ds({stateBranchRoot:C,eventFileName:Dn({userId:u,userName:c})});if(a(_))return oe(10,_.message);let O=await er({cwd:C,message:"[epiq:init]"});if(a(O))return oe(10,O.message);let $=await km(n);if(a($))return oe(11,$.message);let Z=jd({repoRoot:n,fileContents:e});if(a(Z))return oe(12,Z.message);let Jt=await he.stage({cwd:n,pathspec:[".epiq/project.json",".gitignore"]});if(a(Jt))return oe(13,Jt.message);let Dt=await he.commit({cwd:n,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(a(Dt))return oe(13,Dt.message);let Xn="Project initialized!",Er=await W({cwd:n,args:["push","-u","origin","HEAD"]});a(Er)&&(Xn+=` Warn: [init:14] ${Er.message}`);let Rr=await Xr({repoRoot:n,stateBranchRoot:C});a(Rr)&&(Xn+=` Warn: [init:15] ${Rr.message}`);let vd=_t(T.value).filter(a);if(vd.length>0)return oe(16,vd.map(ii=>ii.message).join(`
73
- `));let si=He();if(a(si))return oe(16,si.message);let{rootNodeId:jg,nodes:Hg}=si.value,yd=Hg[jg];return yd?(U.navigate({contextNode:yd,selectedIndex:0}),E({hasProjectDefinition:!0,mode:h.DEFAULT}),l(Xn,null)):oe(16,"Unable to resolve initialized root node")}});import{ulid as wb}from"ulid";function Qa(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=ce(o.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=_m({id:t.value.id,parentId:c.id,position:{at:"end"}});return a(u)?u:Um(u.value)}function Za(e){let t=Fm();if(a(t))return t;let{contextNode:n,selectedIndex:r}=f(),s=ce(n.id)[r+e];if(!s)return i("Missing sibling node");let d=_m({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(d)?d:Um(d.value)}var Bm,vn,Io,Fm,Ja,_m,Um,ed=v(()=>{"use strict";Ut();ht();N();Et();k();Bm=null,vn=()=>structuredClone(Bm),Io=e=>{Bm=e},Fm=()=>{let{contextNode:e,selectedIndex:t}=f(),r=ce(e.id)[t];return r?l("Resolved selected child",r):i("Target node not found")},Ja=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ce(t).filter(o=>o.id!==e);return ts(r,n)},_m=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ge();if(a(r))return i("Unable to resolve user ID");let o=Ja({parentId:t,id:e,position:n});return a(o)?o:l("Created pending move state",{id:wb(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Um=e=>{Io(e);let t=rn(e,!0);return a(t)?t:l("Node moved successfully",t.value)}});import{ulid as Mb}from"ulid";var $m,Ws,jm,Hm=v(()=>{"use strict";Je();ed();On();ht();pe();N();Et();be();k();ne();$m=()=>{let e=vn();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=ce(n).findIndex(s=>s.id===t);return o===-1?i("Moved node not found among rendered children"):(U.navigate({contextNode:r,selectedIndex:o}),l("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}),l(t,null))},jm=async()=>{let e=ge();if(a(e))return i("Unable to resolve user ID");let{modifier:t}=me().commandMeta,{contextNode:n,selectedIndex:r}=f(),o=ce(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=ce(o.parentNodeId),d=s.findIndex(({id:g})=>g===o.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=Ja({parentId:o.parentNodeId,id:o.id,position:m});return a(p)?p:(Io({id:Mb(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),E({mode:h.MOVE}),l("Move initialized",null))}if(t==="next")return Ws(Za(1));if(t==="previous")return Ws(Za(-1));if(t==="to-next")return Ws(Qa(1));if(t==="to-previous")return Ws(Qa(-1));if(t==="confirm"){let s=vn();if(!s)return i("No pending move to confirm");let d=await Nt();if(a(d))return d;let c=B([s],d.value);if(a(c))return c;let u=$m();return a(u)?u:(Io(null),E({mode:h.DEFAULT}),l("Moved item",null))}return t==="cancel"?(Io(null),E({mode:h.DEFAULT}),l("Cancelling move",null)):i("Invalid move modifier")}});import{monotonicFactory as kb,ulid as Lb}from"ulid";var Pb,Gs,td=v(()=>{"use strict";N();Pb=kb(),Gs=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=Pb();return l("Created issue events",[{id:Lb(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as qs}from"ulid";var Wm,Gm=v(()=>{"use strict";Je();td();On();ht();It();N();le();Et();k();ne();Wm=async(e,t)=>{let n=ge();if(a(n))return i("Unable to resolve user ID");let r=await Nt();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:c}=f(),u=m=>{let p=B([m],o);if(a(p))return p;let g=I.getNode(p.value[0].result.id);if(!g)return i("Created node not found");if(!g.parentNodeId)return p;let x=I.getNode(g.parentNodeId);return x?(U.navigate({contextNode:x,selectedIndex:I.getSiblings(g.parentNodeId).findIndex(({id:S})=>S===g.id)}),p):i("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=f(),p=I.getNode(m);if(!p)return i("Workspace not found");let g=Fn(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=Ke(s,"BOARD");if(a(m))return i("Unable to add swimlane in this context");let p=Fn(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)[c],p=d.context==="SWIMLANE"?d:d.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let _=Ke(s,"SWIMLANE");return a(_)?null:_.value})();if(!p)return i("Unable to add issue in this context");let g=Fn(p.id,n.value,o);if(a(g))return g;let x=Gs({name:t.inputString,parent:p.id,rank:g.value,user:n.value});if(a(x))return x;let S=x.value,C=B([...S],o);if(a(C))return C;if(!C.value[0])return i("Issue creation failed");let T=S.find(_=>_.action==="add.issue")?.payload.id;return T?(U.navigate({contextNode:p,selectedIndex:I.getSiblings(p.id).findIndex(({id:_})=>_===T)}),l("Issue created",null)):i("Unable to determine ticket id")}return l("Success",null)}});var qm,Vm=v(()=>{"use strict";pt();ut();Jr();to();Vr();Ht();N();Ft();k();as();qm=async e=>{let t=Ne({repoRoot:e});if(a(t))return zr(3,t.message);let n=await _n({repoRoot:e,stateBranchRoot:t.value,stateBranchName:Bo().stateBranch});if(a(n))return zr(3,n.message);let r=await W({cwd:t.value,args:["pull","--ff-only"]});a(r)&&logger.info(3,r.message);let o=jt(t.value);if(a(o))return zr(3,o.message);let{events:s,unreadable:d}=o.value,c=dn(s,d);if(a(c))return zr(4,c.message);E({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let u=oa({root:e});return a(u)&&logger.info(u.message),l("Loaded project",void 0)}});import Db from"node:os";import zm from"node:path";var Ob,Bb,Km,Ym=v(()=>{"use strict";Vm();to();N();be();k();ne();Ob=e=>e==="~"||e.startsWith("~/")?zm.join(Db.homedir(),e.slice(1)):e,Bb=(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?l("Resolved recent project",o.root):i(`No recent project #${n}`)}let r=Xe(zm.resolve(Ob(n)));return a(r)?i(`No epiq project at ${n}`):l("Resolved project path",r.value)},Km=async()=>{let e=ks();if(Y(""),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=Bb(e,n);if(a(r))return i(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(c){return i(`Unable to enter ${o}: ${c instanceof Error?c.message:String(c)}`)}let d=await qm(o);return a(d)?(process.chdir(s),i(d.message)):l(`Opened ${Cl(o)}`,null)}});var Vs,nd=v(()=>{"use strict";Je();Ht();Ut();N();k();Vs=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=f(),s=ji(n,t);if(a(s))return i(s.message);let{appliedEvents:d,unappliedEvents:c}=s.value,u=Kt();if(a(u))return u;let m=_t(d),{fatal:p,skipped:g}=wn(m);if(p.length>0)return Kt(),E(o),i(p.map(S=>S.message).join(", "));Mn(g);let x=f().nodes[e];return x?(U.navigate({contextNode:x,selectedIndex:r}),l("",{unappliedEvents:c})):(Kt(),E(o),i("Board did not exist at that date"))}});var Xm,Jm=v(()=>{"use strict";Xm=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 Fb,_b,Ub,zs,Ks,Vn,Qm,Zm,rd=v(()=>{"use strict";ct();xo();Ut();pe();N();Jm();k();Fb=20,_b=16,Ub=150,zs=null,Ks=null,Vn=()=>{zs!==null&&(clearInterval(zs),zs=null),Ks!==null&&(clearTimeout(Ks),Ks=null)},Qm=()=>{Vn(),E({mode:h.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Zm=({events:e,startTime:t,durationMs:n})=>{Vn();let r=e.length,o=Cr(e.map(g=>Ar(g))).map(g=>g??t),s=o[r-1]??Date.now(),d=Xm(o),c=Math.max(1,Math.round(n*Fb/1e3)),u=Math.max(Math.round(n/c),_b),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:[]}}),zs=setInterval(()=>{m++;let g=m/c,x=[],S,C;for(;p<r&&d[p]<=g;){let w=e[p],T=rn(w);if(a(T)){if(jr(T)){p++;continue}Qm();return}x.push(...ki(w)),S=w,C=o[p],p++}if(p>=r||m>=c){for(;p<r;p++){let T=rn(e[p]);if(a(T)&&!jr(T))break}let w=f().replay;E({unappliedEvents:[],replay:w&&{...w,progress:1,appliedCount:r}}),Vn(),Ks=setTimeout(Qm,Ub);return}let M=f().replay;E({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,g),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:S?C??M?.currentTime??t:M?.currentTime??t,currentLabel:S?od(S):M?.currentLabel??"",flashNodeIds:S?[...new Set(x)]:M?.flashNodeIds??[]}})},u)}});var ep,tp=v(()=>{"use strict";pt();ct();Ht();Ut();pe();It();N();be();k();oo();nd();rd();ep=async()=>{let e=Ke(f().breadCrumb,"BOARD");if(a(e))return e;let t=await mt(process.cwd());if(a(t))return i("Unable to locate repo root");let n=Ne({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=me().commandMeta;if(Vn(),r==="now"){let c=Ln(n.value);if(a(c))return i(c.message);let u=Kt();if(a(u))return u;let m=_t(c.value),{fatal:p,skipped:g}=wn(m);return p.length>0?i(p.map(x=>x.message).join(", ")):(Mn(g),E({mode:h.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),l("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let c=Hi(n.value);if(a(c))return c;let u=r==="prev"?f().eventLog.at(-1):f().unappliedEvents.at(0),m=u===void 0?null:Ar(u),p=(u===void 0?null:c.value.get(u.id)??null)??(m===null?null:li(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 c=$n(r||o.trim());if(!c)return i("Invalid peek date");s=c.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}),l("Peeking",!0))}});var np,rp=v(()=>{"use strict";pt();It();N();be();k();oo();nd();rd();np=async()=>{let e=Ke(f().breadCrumb,"BOARD");if(a(e))return e;let t=await mt(process.cwd());if(a(t))return i("Unable to locate repo root");let n=Ne({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=me().commandMeta,{dateInput:s,durationInput:d}=Is(r,o);if(Vn(),f().syncStatus.status==="syncing")return i("Cannot replay while syncing, try again in a moment");let c=$n(s);if(!c)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=c.getTime(),p=f(),g=Vs({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(g))return g;let{unappliedEvents:x}=g.value;return x.length===0?(Kt(),E(p),l("Nothing to replay from that point",!0)):(Zm({events:x,startTime:m,durationMs:u}),l("Replaying board history",!0))}});import jb from"zod";var op,sp=v(()=>{"use strict";Hn();pe();N();be();Be();k();op=()=>{let e=me().commandMeta.inputString,t=jb.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}),l(`Auto sync interval set to ${t.data}ms`,null))}});var ip,ap=v(()=>{"use strict";no();Hn();pe();N();be();Be();k();ip=()=>{let e=me().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return i("Invalid response");let t=Ll(e),n=st({autoSync:t});return a(n)?n:(et({autoSync:t}),E({mode:h.DEFAULT}),l(`Auto sync set to "${e}"`,null))}});var dp,cp=v(()=>{"use strict";Hn();pe();N();be();Be();k();dp=()=>{let e=me().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}),l(`Auto sync set to "${e}"`,null))}});import{spawn as Hb}from"node:child_process";var Wb,lp,up=v(()=>{"use strict";N();Wb=()=>{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"]}}},lp=async e=>new Promise(t=>{let{command:n,args:r}=Wb();try{let o=Hb(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(i(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?l("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,mp,pp=v(()=>{"use strict";N();k();up();nn();ro();un();Eo=async(e,t)=>{if(!e.trim())return i(`Nothing to copy: ${t} is empty`);let n=await lp(e);return a(n)?n:l(`Copied ${t} to clipboard`,null)},mp=async e=>{let{breadCrumb:t,selectedNode:n}=f(),r=so({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return i("Nothing selected to copy from");switch(e.modifier){case xe.REF:return Eo(z(o.id),"ref");case xe.TITLE:return Eo(o.title,"title");case xe.DESCRIPTION:return r?Eo(r.props?.description??"","description"):i("No issue in scope");case xe.TAGS:{if(!r)return i("No issue in scope");let s=cn(r).map(({name:d})=>d);return Eo(s.join(", "),"tags")}case xe.ASSIGNEES:{if(!r)return i("No issue in scope");let s=ln(r).map(({name:d})=>d);return Eo(s.join(", "),"assignees")}default:return i("Yank one of: ref, title, description, tags, assignees")}}});var gp,fp=v(()=>{"use strict";ea();pe();N();be();k();gp=async()=>{Y(""),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 Gb,hp,Yt,vp,yp=v(()=>{"use strict";le();Rm();Je();Qn();Hn();On();ht();Va();nr();pe();It();fe();N();le();Et();be();Be();k();Hs();ne();Un();Sa();un();mo();Mm();Om();Hm();Gm();Ym();tp();rp();sp();ha();ap();cp();pp();fp();Gb=e=>e.action==="add.issue.comment",hp=()=>{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)}))},Yt=async()=>{let e=await Nt();return a(e)?e:l("Resolved persist root",e.value)},vp=[{systemOnly:!0,intent:F.Move,description:"Internal move-state command",mode:h.COMMAND_LINE,action:jm},{intent:F.Delete,description:"Delete the currently selected node",mode:h.COMMAND_LINE,action:async()=>{let e=ge();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 Yt();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 c=f().nodes[d];if(!c||!P(c))return i("Unable to resolve comment issue");let u=c.log?.filter(Gb).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}=me().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(d=>Ee(b.FILTER).map(c=>c.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})),l("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 hn({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),E({mode:h.HELP}),l("Viewing help",null)}},{intent:F.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:h.COMMAND_LINE,action:async()=>{let e=ge();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 Yt();if(a(s))return s;let d=s.value,c=an(o.id,r.id,{at:"end"},e.value,d);if(a(c))return c;let u=B([{id:Oe(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:c.value},...e.value}],d);return a(u)?u:l("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=ge();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"?l("Resolved ticket",r):zn(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 c=js(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=f().nodes[c];if(!u)return i("Previous parent no longer exists");let m=await Yt();if(a(m))return m;let p=m.value,g=an(u.id,s.id,{at:"end"},e.value,p);if(a(g))return g;let x=B([{id:Oe(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:g.value},...e.value}],p);return a(x)?x:l("Issue reopened",null)},onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Init,description:"Initialize Epiq in the current git repository",mode:h.COMMAND_LINE,action:Dm},{intent:F.OpenProject,description:"Open a recently used epiq project, by number or path",mode:h.COMMAND_LINE,action:Km,onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.NewItem,description:"Create a new board, swimlane, or issue",mode:h.COMMAND_LINE,action:Wm,onSuccess:()=>E({mode:h.DEFAULT})},{intent:F.Rename,description:"Rename the currently selected node",mode:h.COMMAND_LINE,action:async()=>{let e=ge();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 Yt();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=ge();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=me().commandMeta,r=(t||n).trim();if(!r)return i("Provide a tag");let o=I.findTagByName(r);if(!o)return i(`Tag "${r}" does not exist`);let{selectedNode:s}=f();if(!s)return i("Invalid untag target");let d=zn(s.id,"TICKET");if(a(d))return i("Unable to untag issue in this context");let c=d.value;if(!P(c))return i("Target node is not issue");if(!(c.props.tags??[]).includes(o.id))return i("Issue is not tagged with that tag");let m=await Yt();return a(m)?m:B([{id:Oe(),action:"remove.issue.tag",payload:{id:c.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=ge();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=me().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=zn(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 c=await Yt();if(a(c))return c;let u=I.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}],c.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=ge();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=me().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:c}=f(),u=ae(c.id)[d];if(!u)return i("Invalid assign target");let m=zn(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 Yt();if(a(g))return g;let x=hp(),S=!o&&s.toLowerCase()==="me",C,M;if(S)C=e.value.userId,M=x.find(_=>_.id===C)?.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 O=_[0];if(!O&&!o)return i(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);C=O?.id??Oe(),M=O?.name??s}if((p.props.assignees??[]).includes(C))return i("Assignee already assigned");let T=!!f().contributors[C];return B([...T?[]:[{id:Oe(),action:"create.contributor",payload:{id:C,name:M},...e.value}],{id:Oe(),action:"add.issue.assignee",payload:{id:p.id,assignee:C},...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=ge();if(a(e))return i("Unable to resolve user ID");let{modifier:t,inputString:n}=me().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=zn(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 c=d.props.assignees??[],u=r.toLowerCase()==="me",m=u?c.filter(x=>x===e.value.userId):hp().filter(x=>x.name===r&&c.includes(x.id)).map(x=>x.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 Yt();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=ge();if(a(r))return i("Unable to resolve user ID");let{breadCrumb:o,selectedNode:s}=f(),d=Ke([...o,s],"TICKET");if(a(d))return i("Edit target must be an issue");let c=d.value;if(!c)return i("Invalid comment target");let u=c.context==="TICKET"?l("Resolved ticket",c):zn(c.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 Yt();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:gp},{intent:F.Peek,description:"View board state at another point in time",mode:h.COMMAND_LINE,action:ep},{intent:F.Replay,description:"Replay board history forward from a point in time",mode:h.COMMAND_LINE,action:np},{intent:F.Export,description:"Export the current board layout to markdown",mode:h.COMMAND_LINE,action:async()=>{let e=await Em();return a(e)?e:(E({mode:h.DEFAULT}),l("Export successful",!0))}},{intent:F.Exit,description:"Exit the application",mode:h.COMMAND_LINE,action:async()=>(U.exit(),l("Exit successful",!0))},{intent:F.Edit,description:"Edit title or description",mode:h.COMMAND_LINE,action:async(e,t)=>wm(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)=>mp(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 ue.USERNAME:{if(process.env[bt])return i(`Cannot change the configured user while ${bt} names this process`);let r=Ss();if(a(r))return r;let{userId:o,preferredEditor:s,userName:d}=r.value,c=n||d,u=o||Oe();if(!c||!u)return i("Unable to resolve user name or id");let m=st({userName:c,userId:u,preferredEditor:s??""});return a(m)?m:(et({userName:c,userId:u}),E({mode:h.DEFAULT}),l(`Username set to "${c}"`,null))}case ue.EDITOR:{if(!n)return i("No editor provided");let r=st({preferredEditor:n});return a(r)?r:(et({preferredEditor:n}),E({mode:h.DEFAULT}),l(`Editor configuration set to "${n}"`,null))}case ue.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}),l(`View set to "${n}"`,null))}case ue.AUTOSYNC:return ip();case ue.LOG_LEVEL:return dp();case ue.SYNC_DEBOUNCE_MS:return op();case ue.ATTACHMENT_MAX_KB:return Xl();default:return i("Unknown config command")}}}]});var qb,Lt,sd=v(()=>{"use strict";ms();As();Sa();yp();N();be();Be();k();qb=new Set(["peek","replay","filter","view-help","yank"]),Lt=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=me();if(!t)return i("No command to confirm");if(!e&&n===mn.Invalid)return i("Invalid command");let s=Cu(t);Eu();let{readOnly:d}=f();if(d&&!qb.has(s))return po({status:Ot.Fail,message:"Command not available in readonly state",value:null});let c=vp.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return po({status:Ot.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:o,modifier:r})}catch(m){return po({status:Ot.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(u)?po(u):(Ru({addToHistory:!e}),c.onSuccess?.(),ve().autoSync&&Rl(),u)}});var Ys,Xs,bp,Ip=v(()=>{"use strict";N();pe();k();xn();sd();ed();be();Ys=[{intent:D.Exit,mode:h.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(E({mode:h.COMMAND_LINE}),Y("move cancel"),Lt({isForceExecutedBySystem:!0}))},{intent:D.InitMove,mode:h.DEFAULT,description:"[m] move",action:()=>(E({mode:h.COMMAND_LINE}),Y("move start"),Lt({isForceExecutedBySystem:!0}))},{intent:D.ConfirmMove,mode:h.MOVE,description:"[m] confirm move",action:()=>(E({mode:h.COMMAND_LINE}),Y("move confirm"),Lt({isForceExecutedBySystem:!0}))}],Xs=[{intent:D.MovePreviousItem,mode:h.MOVE,action:()=>vn()?(E({mode:h.COMMAND_LINE}),Y("move previous"),Lt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:D.MoveNextItem,mode:h.MOVE,action:()=>vn()?(E({mode:h.COMMAND_LINE}),Y("move next"),Lt({isForceExecutedBySystem:!0})):i("No pending move")}],bp=[{intent:D.MoveToNextContainer,mode:h.MOVE,action:()=>vn()?(E({mode:h.COMMAND_LINE}),Y("move to-next"),Lt({isForceExecutedBySystem:!0})):i("No pending move")},{intent:D.MoveToPreviousContainer,mode:h.MOVE,action:()=>vn()?(E({mode:h.COMMAND_LINE}),Y("move to-previous"),Lt({isForceExecutedBySystem:!0})):i("No pending move")}]});var xp,Ep=v(()=>{"use strict";fe();Ip();xp={[V.WORKSPACE]:[...Ys,...Xs],[V.BOARD]:[...Ys,...Xs],[V.SWIMLANE]:[...Ys,...Xs,...bp],[V.TICKET]:[],[V.FIELD]:[],[V.FIELD_LIST]:[],[V.TEXT]:[],[V.COMMENT]:[]}});import{spawn as Vb}from"node:child_process";function Rp(e){let t=process.platform,o=Vb(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}var Sp=v(()=>{"use strict"});import zb from"node:fs";import Kb from"node:path";var Np,Cp=v(()=>{"use strict";pt();ao();N();ne();Sp();Np=e=>{let t=Xe(process.cwd());if(a(t))return i("Unable to resolve project root");let n=Ne({repoRoot:t.value});if(a(n))return i(n.message);let r=io(e.hash,e.ext),o=Kb.join(qo(n.value),r);return zb.existsSync(o)?(Rp(o),l(`Opened ${e.name}`,null)):i("Attachment file not found \u2014 run :sync to fetch it")}});var Ap,Tp,wp=v(()=>{"use strict";pe();N();be();k();Hs();xn();Je();Ap=()=>{Y("");let{pendingNavTarget:e}=xr();E({mode:h.DEFAULT}),e&&U.navigate(e),hn({pendingNavTarget:void 0})},Tp=[{intent:D.ExitCommandLine,mode:h.HELP,action:()=>(Ap(),l("Exiting help",null))},{intent:D.Exit,mode:h.HELP,action:()=>(Ap(),l("Closed help",null))},{intent:D.NavPreviousItem,mode:h.HELP,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:D.NavNextItem,mode:h.HELP,action:()=>(U.navigateToNextItem(),l("Navigating to next help item",null))},{intent:D.NavToPreviousContainer,mode:h.HELP,action:()=>(U.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:D.NavToNextContainer,mode:h.HELP,action:()=>(U.navigateToNextContainer(),l("Navigating to next help container",null))}]});var Yb,Mp,kp,Lp=v(()=>{"use strict";pe();fe();N();be();k();Hs();xn();Je();Yb=e=>{E({mode:h.COMMAND_LINE});let{pendingNavTarget:t}=xr();t&&U.navigate(t),hn({pendingNavTarget:void 0}),Y(`${e} `)},Mp=()=>{Y("");let{pendingNavTarget:e}=xr();e&&U.navigate(e),hn({pendingNavTarget:void 0}),E({mode:h.DEFAULT})},kp=[{intent:D.InitCommandPalette,mode:h.DEFAULT,description:"[?] command palette",action:()=>{Y("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=f();return hn({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),E({mode:h.PALETTE}),l("Opening command palette",null)}},{intent:D.Confirm,mode:h.PALETTE,action:()=>{let{selectedNode:e}=f();if(!e||!Ad(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?(Yb(t),l("Selected command",t)):l("No command selected",null)}},{intent:D.ExitCommandLine,mode:h.PALETTE,action:()=>(Mp(),l("Exiting palette",null))},{intent:D.Exit,mode:h.PALETTE,action:()=>(Mp(),l("Closed command palette",null))},{intent:D.NavPreviousItem,mode:h.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:D.NavNextItem,mode:h.PALETTE,action:()=>(U.navigateToNextItem(),l("Navigating to next item",null))},{intent:D.NavToPreviousContainer,mode:h.PALETTE,action:()=>(U.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:D.NavToNextContainer,mode:h.PALETTE,action:()=>(U.navigateToNextContainer(),l("Navigating to next container",null))}]});var Pp,Dp=v(()=>{"use strict";Un();un();pe();N();tr();le();Et();be();k();Cp();xn();wp();Lp();Je();Pp=[{intent:D.InitCommandLine,mode:h.DEFAULT,description:"[:] write command",action:()=>(E({mode:h.COMMAND_LINE}),Y(""),l("Entering command line mode",null))},...Tp,...kp,{intent:D.AddItem,mode:h.DEFAULT,description:"[n] new...",action:()=>(E({mode:h.COMMAND_LINE}),Y(`${b.NEW} `),l("Adding new item",null))},{intent:D.Delete,mode:h.DEFAULT,description:"[d] delete",action:()=>(E({mode:h.COMMAND_LINE}),Y(`${b.DELETE} `),l("Deleting item",null))},{intent:D.Confirm,mode:h.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=f();if(!ce(e?.id??"")?.length){let r=e?I.getAttachment(e.id):void 0;if(r)return Np(r);if(e?.title===ie.DESCRIPTION)return E({mode:h.COMMAND_LINE}),Y(`${b.EDIT} description `),l("Propose command",!0);if(e?.title===ie.ASSIGNEES)return E({mode:h.COMMAND_LINE}),Y(`${b.ASSIGN} `),l("Propose command",!0);if(e?.title===ie.TAGS)return E({mode:h.COMMAND_LINE}),Y(`${b.TAG} `),l("Propose command",!0);if(t.title===ie.DESCRIPTION&&e?.context==="TEXT")return E({mode:h.COMMAND_LINE}),Y(`${b.EDIT} description `),l("Propose command",!0)}return U.enterChildNode(),l("Entering context",null)}},{intent:D.Yank,mode:h.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=f(),t=e?.title===ie.DESCRIPTION?xe.DESCRIPTION:e?.title===ie.TAGS?xe.TAGS:e?.title===ie.ASSIGNEES?xe.ASSIGNEES:xe.REF,r=Ee(b.YANK).includes(t)?t:xe.REF;return E({mode:h.COMMAND_LINE}),Y(`${b.YANK} ${r}`),l("Propose command",!0)}},{intent:D.EditTitle,mode:h.DEFAULT,description:"[r] rename title",action:()=>(E({mode:h.COMMAND_LINE}),Y(`${b.EDIT} title ${f().selectedNode?.title}`),l("Exiting context",null))},{intent:D.EditDescription,mode:h.DEFAULT,description:"[e] edit desc",action:()=>(E({mode:h.COMMAND_LINE}),Y(`${b.EDIT} description `),l("Exiting context",null))},{intent:D.Exit,mode:h.DEFAULT,description:"[q] exit context",action:()=>(U.enterParentNode(),l("Exiting context",null))},{intent:D.NavPreviousItem,mode:h.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:D.NavNextItem,mode:h.DEFAULT,action:()=>(U.navigateToNextItem(),l("Navigating to next item",null))},{intent:D.NavToPreviousContainer,mode:h.DEFAULT,action:()=>(U.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:D.NavToNextContainer,mode:h.DEFAULT,action:()=>(U.navigateToNextContainer(),l("Navigating to next container",null))}]});var Xb,Jb,Op,Bp=v(()=>{"use strict";be();Xb=500,Jb=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Op=e=>{let t=Jb(e);t&&Ms(n=>(n+t).slice(0,Xb))}});var Qb,Zb,Fp,_p=v(()=>{"use strict";Bp();pe();N();be();k();xn();sd();Qb=[h.COMMAND_LINE,h.PALETTE],Zb=e=>[{intent:D.MoveCursorLeft,mode:e,action:()=>(Ea(-1),l("Moving cursor left",null))},{intent:D.MoveCursorRight,mode:e,action:()=>(Ea(1),l("Moving cursor right",null))},{intent:D.MoveCursorLeftOfWord,mode:e,action:()=>(Ra("left"),l("Moving cursor left of word",null))},{intent:D.MoveCursorRightOfWord,mode:e,action:()=>(Ra("right"),l("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}),l("Auto-completing command",null))},{intent:D.CaptureInput,mode:e,action:(t,{sequence:n})=>(Op(n??""),l("Capturing input",null))},{intent:D.EraseInput,mode:e,action:()=>(Iu(),l("Erasing input",null))},{intent:D.EraseInputWord,mode:e,action:()=>(xu(),l("Erasing input word",null))}],Fp=[{intent:D.Confirm,mode:h.COMMAND_LINE,action:()=>(Lt(),l("Executing command",null))},{intent:D.ViewHelp,mode:h.DEFAULT,action:()=>(E({mode:h.HELP}),l("Viewing help",null))},...Qb.flatMap(Zb),{intent:D.ExitCommandLine,mode:h.COMMAND_LINE,action:()=>(E({mode:h.DEFAULT}),l("Exiting command line",null))},{intent:D.GetLastCommandFromHistory,mode:h.COMMAND_LINE,action:()=>(Su(),l("Getting last command from history",null))},{intent:D.GetNextCommandFromHistory,mode:h.COMMAND_LINE,action:()=>(Nu(),l("Getting next command from history",null))}]});var eI,Up,$p,jp=v(()=>{"use strict";eI=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},Up=({keys:e})=>e.length===1?0:1,$p=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(eI).filter(r=>r!==null).sort((r,o)=>Up(r)-Up(o))}});function Hp(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 c=o[o.length-1];return!c||c.id!==n?i("buildBreadCrumb(): node is not connected to root"):(o.reverse(),l("Breadcrumb built",o))}var Wp=v(()=>{"use strict";N()});var Gp,qp=v(()=>{"use strict";Gp=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 tI}from"react";function cd(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 c=o[t];if(!c)return i("Unable to derive state, contextNode not found");let u=Hp(t,o,r);if(a(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,g=[...Pp,...xp[p]??[],...Fp],x=$p(g,n),S=Gp(g),C=rI(o,s),M=C[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:x,availableActions:g,actionIndex:S,selectedNode:M,renderedChildrenIndex:C})}function Hr(e){id=e;let t=Xe(process.cwd()),n=!1;if(!a(t)){let s=Bt(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=cd(r);return a(o)?o:(Pt=o.value,dd(),l("State initialized",null))}function Ie(e){let t=f(),n=e(t);if(Kn)return Ro=n,Pt={...t,...n},l("State updated",null);let r=cd(n);return a(r)?i(r.message??"Unable to update state"):(Pt=r.value,dd(),l("State updated",null))}function mc(e){if(Kn)return l("Joined batch",e());Kn=!0,Ro=null;let t=()=>{let n=Ro;if(Kn=!1,Ro=null,n===null)return null;let r=cd(n);return a(r)?i(r.message??"Unable to update state"):(Pt=r.value,dd(),l("State updated",null))};try{let n=e(),r=t();return r&&a(r)?i(r.message):l("State updated",n)}finally{Kn&&t()}}function Yn(e,t,n){if(!Kn)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,Pt={...r,...s},l("State updated",null)}var Pt,id,ad,dd,nI,f,He,Kn,Ro,Wc,E,Ve,rI,ae,Kt,ot,k=v(()=>{"use strict";Ep();Dp();_p();jp();Ft();pe();N();ne();qi();Wp();qp();ad=new Set,dd=()=>{for(let e of ad)e()},nI=e=>(ad.add(e),()=>ad.delete(e));f=()=>{if(!Pt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Pt},He=()=>Pt?l("Retrieved state",Pt):i("State not initialized. Call initWorkspaceState() first.");Kn=!1,Ro=null;Wc=()=>Kn,E=e=>Ie(t=>({...t,...e}));Ve=()=>tI(nI,f,f),rI=Uc,ae=e=>f()?.renderedChildrenIndex[e]??[],Kt=()=>id?Hr(id):i("Cannot reset state: no initial workspace found"),ot=()=>Pt!==void 0});var zn,oI,yn,I,le=v(()=>{"use strict";It();fe();N();k();Et();zn=(e,t)=>{let{nodes:n}=f(),r=n[e];if(!r)return i("Node not found");if(r.context===t)return l("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 l("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return i(`No ancestor found for context: ${t}`)},oI=(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},yn=(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 r={...n,userId:t},o=Ie(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?i("Unable to link contributor to user"):l("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"):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 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"):l("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"):l("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"):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},r=Ie(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return a(r)?i("Unable to delete attachment"):l("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=yn(r,"edit");if(o)return o;let s={...r,props:{...r.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 r=yn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),l("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 ce(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=yn(o,"move");if(d)return d;if(oI(t,e))return i("Cannot move node into its own descendant");let c={...o,parentNodeId:t,rank:n};return this.updateNode(c),l("Moved node successfully",c)},tombstoneNode(e){let{nodes:t,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=yn(o,"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 g of ce(p.id))c(g.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",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"):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 r={...n,name:t},o=Ie(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?i("Unable to rename contributor"):l("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"):l("Restored contributor",r)},createContributor(e){let t=Ie(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),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=yn(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),l("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=yn(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 l("Issue is not assigned to that contributor",{assignee:t});let d={...r,props:{...r.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(d),l("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=yn(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),l("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=yn(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 l("Issue is not tagged with that tag",{tag:t});let d={...r,props:{...r.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},r=Ie(o=>({...o,tags:{...o.tags,[e]:n}}));return a(r)?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 r={...n,name:t,tombstoned:!1},o=Ie(s=>({...s,tags:{...s.tags,[e]:r}}));return a(o)?i("Unable to restore tag"):l("Restored tag",r)},createTag(e){let t=Ie(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?i("Could not create tag"):l("Tag created",e)},createNode(e){let t=Yn("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},r=Yn("nodes",e,n);return a(r)?i(r.message):l("Locked node",n)},updateNode(e){let t=Yn("nodes",e.id,e);return a(t)?t:l("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 ce(e)}}});import bn from"chalk";import Vp from"string-width";var sI,iI,ld,aI,dI,zp,Kp,cI,lI,uI,mI,pI,od,Yp,xo=v(()=>{"use strict";ct();le();k();wt();_s();sI=(e,t)=>e+" ".repeat(Math.max(0,t-Vp(e))),iI=(e,t)=>" ".repeat(Math.max(0,t-Vp(e)))+e,ld=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`),aI=(e,t)=>t?e<t?"up":e>t?"down":null:null,dI=(e,t)=>{let n=I.getNode(e.payload.parent),r=n?bn.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=aI(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},zp=e=>`${Math.max(1,Math.round(e/1024))} KB`,Kp=e=>I.getAttachment(e)?.name??"",cI=e=>{switch(e.action){case"add.issue.tag":{let t=f().tags[e.payload.tag];return t?bn.bgHex(Pe(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=f().tags[e.payload.tag];return t?bn.bgHex(Pe(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?bn.hex(Pe(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=f().contributors[e.payload.assignee];return t?bn.hex(Pe(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}" ${bn.dim(`(${zp(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Kp(e.payload.id);return t?`"${t}"`:""}default:return""}},lI=e=>{let t=yr(dt(e));return bn.gray(iI(t,8))},uI=12,mI=e=>sI(`${e}`,uI),pI=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=I.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${zp(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Kp(e.payload.id);return t?`"${t}"`:""}default:return""}},od=e=>[ld(e.action),pI(e)].filter(Boolean).join(" "),Yp=(e,t)=>{let n=lI(e.id),r=mI(e.userName),o=bn.dim("\u203A"),s=e.action==="move.node"?dI(e,t):[ld(e.action),cI(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`}});var Jp={};To(Jp,{areVirtualNodesEnabled:()=>Yo,createOrUpdateVirtualField:()=>So,createOrUpdateVirtualFieldList:()=>ud,materializeTicketVirtualNodes:()=>Ko,materializeVirtualNodes:()=>EI,setVirtualNodesEnabled:()=>xI});var gI,fI,hI,vI,yI,bI,So,ud,Ko,II,Xp,xI,Yo,EI,Li=v(()=>{"use strict";xo();fe();N();tr();le();Tn();k();Zn();dr();gI=e=>Ae(e,"comments"),fI=e=>Ae(e,"description"),hI=e=>Ae(e,"assignees"),vI=e=>Ae(e,"tags"),yI=e=>Ae(e,"history"),bI=e=>Ae(e,"attachments"),So=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:d="horizontal"})=>{let c=I.getNode(e);if(!c){let p=I.createNode({...Ce.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:d});return a(p)?p:l("Virtual field created",void 0)}if(!Ye(c))return i(`Existing virtual node ${e} is not a field`);if(!(c.title!==t||c.parentNodeId!==n||c.rank!==r||c.props.value!==o||c.readonly!==s||c.childRenderAxis!==d))return l("Virtual field unchanged",void 0);let m=I.updateNode({...c,title:t,parentNodeId:n,rank:r,props:{...c.props,value:o},readonly:s,childRenderAxis:d});return a(m)?m:l("Virtual field updated",void 0)},ud=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let d=I.getNode(e);if(!d){let m=I.createNode({...Ce.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return a(m)?m:l("Virtual field list created",void 0)}if(!Tr(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 l("Virtual field list unchanged",void 0);let u=I.updateNode({...d,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(u)?u:l("Virtual field list updated",void 0)},Ko=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 c=So({id:fI(e.id),name:ie.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(c))return c;let u=ud({id:hI(e.id),name:ie.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(u))return u;let m=ud({id:vI(e.id),name:ie.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(a(m))return m;let p=So({id:gI(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:bI(e.id),name:ie.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(g))return g;let x=So({id:yI(e.id),name:ie.HISTORY,parentNodeId:e.id,rank:d.value,value:II(e),readonly:!0,childRenderAxis:"vertical"});return a(x)?x:l("Ticket virtual nodes materialized",void 0)},II=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=>Yp(r,n.get(r.action)??[])).join(`
74
- `)},Xp=!0,xI=e=>{Xp=e},Yo=()=>Xp,EI=()=>{let{nodes:e}=f();for(let t of Object.values(e)){if(!P(t))continue;let n=Ko(t);if(a(n))return n}return l("Virtual nodes materialized",void 0)}});var RI,Qp,md=v(()=>{"use strict";ct();Ht();Wr();xo();N();wt();RI=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 c=s.parent??s.issue;return c&&t.set(d,c),n.has(d)?d:r(d)})},Qp=(e,t)=>{let n=RI(e);return e.filter((r,o)=>n[o]===t)}});var SI,Zp,eg,pd,gd=v(()=>{"use strict";pt();ut();nn();Ka();Ht();Ut();N();Ft();Rs();ne();k();md();SI=null,Zp=Promise.resolve(),eg=e=>{let t=Zp.then(e,e);return Zp=t.then(()=>{},()=>{}),t},pd=()=>{if(!ot())return{mode:"live",asOfTime:null};let{timeMode:e}=f();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:SI}}});import ng from"node:fs";import NI from"node:path";import{ulid as G}from"ulid";async function dg(e){let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=n.value.nodes,o=e.query?.trim().toLowerCase(),s=Object.values(r).filter(P).filter(c=>!c.isDeleted).filter(c=>e.includeClosed||c.parentNodeId!==ye).filter(c=>e.boardId?(c.parentNodeId?r[c.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(c=>!e.swimlaneId||c.parentNodeId===e.swimlaneId).filter(c=>!e.tag||Qs(c).some(u=>tg(u.name,e.tag))).filter(c=>!e.assignee||Zs(c).some(u=>tg(u.name,e.assignee))).filter(c=>!o||c.title.toLowerCase().includes(o)||(c.props.description??"").toLowerCase().includes(o)),d=c=>Se((c.parentNodeId?r[c.parentNodeId]?.title:void 0)??"");return e.brief?l("Listed issues",s.map(c=>({id:c.id,ref:z(c.id),title:Se(c.title),swimlane:d(c),tags:Qs(c).map(u=>u.name),assignees:Zs(c).map(u=>u.name)}))):l("Listed issues",s.map(c=>({id:c.id,ref:z(c.id),title:Se(c.title),description:c.props.description??"",createdAt:dt(c.id),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===ye,readonly:!!c.readonly,tags:Qs(c),assignees:Zs(c)})))}async function lg(e){let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=fd(e);if(a(r))return r;let o=s=>MI(s,n.value,t.value.stateBranchRoot);return e.issueIds?ni("Closed",og(r.value,o)):o(r.value[0])}async function mg(e){let t=ri(e.repoRoot);if(a(t))return t;let n=se();if(a(n))return n;let r=Ne({repoRoot:t.value});if(a(r))return r;let o=jt(r.value);if(a(o))return o;let s=dn(o.value.events,o.value.unreadable);if(a(s))return s;let d=fd(e);if(a(d))return d;let c=u=>kI(u,e,n.value,r.value);return e.issueIds?ni("Moved",og(d.value,c)):c(d.value[0])}async function xg(e){let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=se();if(a(n))return n;let r=fd(e);if(a(r))return r;let o=Se(e.tagName).trim();if(!o)return i("Tag name cannot be empty");let s=vt("Tag name",o,60);if(s)return i(s);let d={done:[],failed:[]};for(let S of r.value){let C=hd(S);a(C)?d.failed.push({id:S,ref:z(S),reason:C.message}):d.done.push({id:S,ref:z(S)})}if(!e.issueIds&&d.failed[0])return i(d.failed[0].reason);if(d.done.length===0)return i(ni("Tagged",d).message);let c=I.findTagByName(o),u=c?.id??G(),m=[...c?[]:[{id:G(),...n.value,action:"create.tag",payload:{id:u,name:o}}],...d.done.map(({id:S})=>({id:G(),...n.value,action:"add.issue.tag",payload:{id:S,tag:u}}))],p=B(m,t.value.stateBranchRoot);if(a(p))return i(p.message);let g={id:u,name:o};if(!e.issueIds)return l("Added issue tag",{...d.done[0],tag:g});let x=ni("Tagged",d);return a(x)?x:l(x.message,{...x.value,tag:g})}var CI,AI,ri,Js,ee,se,te,Qs,TI,rg,wI,Zs,fd,ni,og,hd,sg,ig,ag,tg,cg,MI,ug,kI,pg,gg,fg,hg,vg,yg,iU,bg,Ig,Eg,Rg,Sg,Ng,Cg,Ag,Tg,LI,wg,Mg,kg,Lg,Pg,Dg,Og,Bg=v(()=>{"use strict";pt();ut();Pr();Jr();Zi();Qn();Hn();td();ct();Vr();Wr();ne();Ht();On();ht();md();Va();nr();fe();N();le();Et();k();is();to();ne();It();xo();wt();mo();nn();Qt();ao();Rt();gd();CI=e=>{if(e.filePath)try{return l("Read attachment file",{data:ng.readFileSync(e.filePath),name:e.name??NI.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")},AI=()=>{let e=pa();return a(e)?qt:e.value.attachmentMaxKb??qt},ri=e=>{let t=Xe(e??process.cwd());return a(t)?i(t.message):l("Resolved Epiq repo root",t.value)},Js=null,ee=async(e,t)=>{let n=ri(e);if(a(n))return n;let r=Ne({repoRoot:n.value});if(a(r))return i(r.message);let o=Zt(n.value);if(a(o))return i(o.message);if(!(Js!==null&&Js.repoRoot===n.value&&Js.stateBranchRoot===r.value&&ng.existsSync(Rn(r.value)))){let p=await Yi({repoRoot:n.value,stateBranchName:o.value});if(a(p))return i(p.message);let g=await _n({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(a(g))return i(g.message);Js={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let p=await W({cwd:r.value,args:["pull","--ff-only"]});a(p)&&X.info(3,p.message)}let d={repoRoot:n.value,stateBranchRoot:r.value},c=kn(r.value);if(fc(r.value)===c&&ot()&&pd().mode==="live")return l("Booted Epiq state, unchanged",d);let u=jt(r.value);if(a(u))return i(u.message);let m=dn(u.value.events,u.value.unreadable);return a(m)?i(m.message):(hc(r.value,c),l("Booted Epiq state",d))},se=()=>{let e=pa();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")},te=()=>{let e=He();return a(e)?i(e.message):e},Qs=e=>(e.props.tags??[]).map(t=>I.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Pe(t.name)})),TI=()=>{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},rg=(e,t)=>{let n=new Map(e);for(let r of Object.values(t))n.set(r.id,r.name);return n},wI=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:dt(t.id),body:t.md})),Zs=e=>(e.props.assignees??[]).map(t=>I.getContributor(t)).filter(t=>t!=null).map(({id:t,name:n})=>({id:t,name:n,color:Pe(n)})),fd=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?l("Resolved targets",t):i("Provide issueId or issueIds")},ni=(e,t)=>{let n=t.done.length,r=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?l(r,t):i(`${r}: ${t.failed.map(o=>`${o.ref} ${o.reason}`).join("; ")}`)},og=(e,t)=>{let n={done:[],failed:[]};for(let r of e){let o=t(r);a(o)?n.failed.push({id:r,ref:z(r),reason:o.message}):n.done.push({id:r,ref:z(r)})}return n},hd=e=>{let t=te();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?i("Issue not found"):P(n)?n.readonly?i("Issue is readonly"):l("Found issue",n):i("Target must be an issue")},sg=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();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 l("Listed boards",r)},ig=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();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 l("Listed swimlanes",r)},ag=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();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=>Ur(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)} (${Se(u.title)})`).join(", ")}. Use a full ref or id.`);let c=d[0];return l("Found issue",{id:c.id,ref:z(c.id),title:Se(c.title),description:c.props.description??"",createdAt:dt(c.id),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===ye,readonly:!!c.readonly,tags:Qs(c),assignees:Zs(c),comments:wI(c.id)})},tg=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();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=te();if(a(r))return r;let o=Se(e.title);if(!o)return i("Issue title cannot be empty");let s=e.description??"",d=vt("Issue title",o,300)??vt("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=Fn(e.parentId,n.value,t.value.stateBranchRoot);if(a(c))return c;let u=Gs({name:o,parent:e.parentId,user:n.value,rank:c.value});if(a(u))return u;let m=[...u.value],p=m.find(C=>C.action==="add.issue")?.payload.id;if(!p)return i("Unable to determine created issue id");s&&m.push({id:G(),...n.value,action:"edit.description",payload:{id:p,md:s}});let g=[];for(let C of e.tagNames??[]){let M=Se(C).trim();if(!M||g.some(O=>O.name===M))continue;let w=vt("Tag name",M,60);if(w)return i(w);let T=I.findTagByName(M),_=T?.id??G();T||m.push({id:G(),...n.value,action:"create.tag",payload:{id:_,name:M}}),m.push({id:G(),...n.value,action:"add.issue.tag",payload:{id:p,tag:_}}),g.push({id:_,name:M})}let x=[];for(let C of e.assigneeNames??[]){let M=Se(C).trim();if(!M||x.some(O=>O.name===M))continue;let w=vt("Assignee name",M,80);if(w)return i(w);let T=Object.values(r.value.contributors).find(O=>O.name===M),_=T?.id??G();T||m.push({id:G(),...n.value,action:"create.contributor",payload:{id:_,name:M}}),m.push({id:G(),...n.value,action:"add.issue.assignee",payload:{id:p,assignee:_}}),x.push({id:_,name:M})}let S=B(m,t.value.stateBranchRoot);return a(S)?i(S.message):l("Created issue",{id:p,ref:z(p),title:o,parentId:e.parentId,description:s,tags:g,assignees:x})},MI=(e,t,n)=>{let r=hd(e);if(a(r))return r;let o=an(ye,e,{at:"end"},t,n);if(a(o))return o;let s={id:G(),...t,action:"close.issue",payload:{id:e,parent:ye,rank:o.value}},d=B([s],n);return a(d)?i(d.message):l("Closed issue",{id:e,ref:z(e)})};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=te();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 c=an(d.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(c))return c;let u={id:G(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:d.id,rank:c.value}},m=B([u],t.value.stateBranchRoot);return a(m)?i(m.message):l("Reopened issue",{id:o.id,ref:z(o.id),parentId:d.id})},kI=(e,t,n,r)=>{let o=hd(e);if(a(o))return o;let s=an(t.parentId,e,t.position??{at:"end"},n,r);if(a(s))return s;let d={id:G(),...n,action:"move.node",payload:{id:e,parent:t.parentId,rank:s.value}},c=B([d],r);return a(c)?i(c.message):l("Moved issue",{id:e,ref:z(e),parentId:t.parentId})};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=te();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(pd().mode!=="live")return i("Cannot add a swimlane while time travelling");let s=Se(e.title);if(!s.trim())return i("Swimlane title cannot be empty");let d=vt("Swimlane title",s,300);if(d)return i(d);let c=Fn(e.boardId,n.value,t.value.stateBranchRoot);if(a(c))return c;let u=G(),m={id:G(),...n.value,action:"add.swimlane",payload:{id:u,name:s,parent:e.boardId,rank:c.value}},p=B([m],t.value.stateBranchRoot);return a(p)?i(p.message):l("Created swimlane",{id:u,ref:z(u),title:s,boardId:e.boardId})},gg=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=te();if(a(r))return r;let o=r.value.nodes[e.swimlaneId];if(!o)return i("Swimlane not found");if(!In(o))return i("Edit target must be a swimlane");if(o.readonly)return i("Cannot edit readonly swimlane");let s=Se(e.title);if(!s.trim())return i("Swimlane title cannot be empty");let d=vt("Swimlane title",s,300);if(d)return i(d);if(o.title===s)return l("No changes made",{id:e.swimlaneId,ref:z(e.swimlaneId),title:s});let c={id:G(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:s}},u=B([c],t.value.stateBranchRoot);return a(u)?i(u.message):l("Edited swimlane title",{id:e.swimlaneId,ref:z(e.swimlaneId),title:s})},fg=async e=>{let t=ri(e.repoRoot);if(a(t))return t;let n=se();if(a(n))return n;let r=Ne({repoRoot:t.value});if(a(r))return r;let o=jt(r.value);if(a(o))return o;let s=dn(o.value.events,o.value.unreadable);if(a(s))return s;let d=an(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(a(d))return d;let c={id:G(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:d.value}},u=B([c],r.value);return a(u)?i(u.message):l("Moved swimlane",{id:e.swimlaneId,ref:z(e.swimlaneId),boardId:e.boardId})},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=te();if(a(r))return r;let o=r.value.nodes[e.swimlaneId];if(!o)return i("Swimlane not found");if(!In(o))return i("Delete target must be a swimlane");let s={id:G(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},d=B([s],t.value.stateBranchRoot);return a(d)?i(d.message):l("Deleted swimlane",{id:e.swimlaneId,ref:z(e.swimlaneId)})},vg=async(e={})=>{os();let t=ri(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:Dn(n.value)});return a(r)?(Vi(r.message),r):(ss(),l("Synced",r.value))},yg=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();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})},iU=365*24*60*60*1e3,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=te();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=vt("Issue description",e.description,2e4);if(s)return i(s);let d=o.props.description??"";if(d===e.description)return l("No changes made",{id:e.issueId,ref:z(e.issueId),description:d});let c={id:G(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},u=B([c],t.value.stateBranchRoot);return a(u)?i(u.message):l("Edited issue description",{id:e.issueId,ref:z(e.issueId),description:e.description})},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=te();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=Se(e.title);if(!s.trim())return i("Issue title cannot be empty");let d=vt("Issue title",s,300);if(d)return i(d);if(o.title===s)return l("No changes made",{id:e.issueId,ref:z(e.issueId),title:s});let c={id:G(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},u=B([c],t.value.stateBranchRoot);return a(u)?i(u.message):l("Edited issue title",{id:e.issueId,ref:z(e.issueId),title:s})};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=te();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:G(),...n.value,action:"tombstone.tag",payload:{id:e.tagId}}],d=B(s,t.value.stateBranchRoot);return a(d)?i(d.message):l("Deleted tag",{id:o.id,name:o.name})},Rg=async e=>{let t=ci(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=te();if(a(o))return o;let s=r.value,d=!!o.value.contributors[s.userId];if(!d){let c=B([{id:G(),...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})},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=te();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(I.findTagByName(o.name))return i(`Cannot restore: another tag is already named "${o.name}"`);let s=[{id:G(),...n.value,action:"restore.tag",payload:{id:e.tagId,name:o.name}}],d=B(s,t.value.stateBranchRoot);return a(d)?i(d.message):l("Restored tag",{id:o.id,name:o.name})},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=te();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:G(),...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):l("Removed issue tag",{id:e.issueId,ref:z(e.issueId),tagId:e.tagId})},Cg=async(e,t)=>{let n=$i(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}},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=te();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 w=r.value.contributors[s],T=w?void 0:await Cg(t.value.stateBranchRoot,s);if(!w&&!T)return i("Unknown assignee id");let _=w??T,O=[...w?[]:[{id:G(),...n.value,action:"create.contributor",payload:{id:_.id,name:_.name}}],{id:G(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:_.id}}],$=B(O,t.value.stateBranchRoot);return a($)?i($.message):l("Added issue assignee",{id:e.issueId,ref:z(e.issueId),assignee:{id:_.id,name:_.name}})}let d=Se(e.assigneeName??"").trim();if(!d)return i("Provide assigneeId, self or assigneeName");let c=vt("Assignee name",d,80);if(c)return i(c);let m=[...rg(TI(),r.value.contributors).entries()].filter(([,w])=>w===d);if(m.length>1)return i(`"${d}" matches ${m.length} contributors (${m.map(([w])=>w).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=G(),x=d]=p??[],C=[...!!r.value.contributors[g]?[]:[{id:G(),...n.value,action:"create.contributor",payload:{id:g,name:x}}],{id:G(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:g}}],M=B(C,t.value.stateBranchRoot);return a(M)?i(M.message):l("Added issue assignee",{id:e.issueId,ref:z(e.issueId),assignee:{id:g,name:x}})},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=te();if(a(r))return r;if(!r.value.contributors[e.contributorId])return i("Contributor not found");if(await Cg(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:G(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],c=B(d,t.value.stateBranchRoot);return a(c)?i(c.message):l("Tombstoned contributor",{id:e.contributorId,name:ko})},LI=async(e,t)=>{let n=Ln(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},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=te();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 LI(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:G(),...n.value,action:"restore.contributor",payload:{id:e.contributorId,name:s}}],c=B(d,t.value.stateBranchRoot);return a(c)?i(c.message):l("Restored contributor",{id:e.contributorId,name: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=te();if(a(r))return r;let o=Ln(t.value.stateBranchRoot);if(a(o))return i(o.message);let s=e.boardId?Qp(o.value,e.boardId):o.value,d=new Map,c=new Set,u=new Set,m=$i(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=r.value.contributors,x=[...rg(d,p).entries()].map(([S,C])=>({id:S,name:C,color:Pe(C),isSelf:S===n.value.userId,isExternal:!c.has(S),isRemoved:p[S]?.tombstoned===!0,hasAuthoredAnywhere:u.has(S)}));return l("Listed board contributors",x)},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=te();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:G(),...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):l("Removed issue assignee",{id:e.issueId,ref:z(e.issueId),assigneeId:e.assigneeId})},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=te();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=G(),c={id:G(),...n.value,action:"add.issue.comment",payload:{id:d,issue:e.issueId,md:s,author:n.value.userId}},u=B([c],t.value.stateBranchRoot);return a(u)?i(u.message):l("Added issue comment",{id:d,issueId:e.issueId,body:s})},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=te();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 l("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let c={id:G(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},u=B([c],t.value.stateBranchRoot);return a(u)?i(u.message):l("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},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=te();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 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:G(),...n.value,action:"edit.issue.comment",payload:{id:e.commentId,issue:o.payload.issue,md:c}},m=B([u],t.value.stateBranchRoot);return a(m)?i(m.message):l("Edited issue comment",{id:e.commentId,issueId:o.payload.issue,body:c})},Og=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=te();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=CI(e);if(a(s))return s;let d=Yl(t.value.stateBranchRoot,s.value.data,AI());if(a(d))return d;let c=Se(s.value.name).trim()||"image",u=G(),m={id:G(),...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=B([m],t.value.stateBranchRoot);if(a(p))return i(p.message);let g=io(d.value.hash,d.value.ext);return l("Added issue attachment",{id:u,issueId:e.issueId,fileName:g,bytes:d.value.bytes,markdown:ga(c,g)})}});var Ug={};To(Ug,{createMcpServer:()=>_g,resultJson:()=>Fg,startMcpServer:()=>BI});import{McpServer as DI}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as OI}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as y}from"zod";var Fg,J,_g,BI,$g=v(()=>{"use strict";N();mo();Bg();gd();Fg=e=>({isError:a(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),J=e=>t=>eg(async()=>Fg(await e(t))),_g=()=>{let e=new DI({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:y.object({repoRoot:y.string().optional()})},J(yg)),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:y.object({repoRoot:y.string().optional(),includeClosed:y.boolean().optional(),boardId:y.string().optional(),swimlaneId:y.string().optional(),tag:y.string().optional(),assignee:y.string().optional(),query:y.string().optional(),brief:y.boolean().optional()})},J(dg)),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:y.object({idOrRef:y.string().min(1),repoRoot:y.string().optional()})},J(ag)),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:y.object({repoRoot:y.string().optional()})},J(sg)),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:y.object({repoRoot:y.string().optional(),boardId:y.string().optional()})},J(ig)),e.registerTool("epiq_swimlane_create",{description:"Create an Epiq swimlane on a board",inputSchema:y.object({repoRoot:y.string().optional(),boardId:y.string().min(1),title:y.string().min(1).max(300)})},J(pg)),e.registerTool("epiq_swimlane_title_edit",{description:"Edit an Epiq swimlane title",inputSchema:y.object({repoRoot:y.string().optional(),swimlaneId:y.string().min(1),title:y.string().min(1).max(300)})},J(gg)),e.registerTool("epiq_swimlane_move",{description:"Move/reorder an Epiq swimlane, optionally to another board",inputSchema:y.object({repoRoot:y.string().optional(),swimlaneId:y.string().min(1),boardId:y.string().min(1),position:y.discriminatedUnion("at",[y.object({at:y.literal("start")}),y.object({at:y.literal("end")}),y.object({at:y.literal("before"),sibling:y.string().min(1)}),y.object({at:y.literal("after"),sibling:y.string().min(1)})]).optional()})},J(fg)),e.registerTool("epiq_swimlane_delete",{description:"Delete (archive) an Epiq swimlane. This also archives every issue contained in it.",inputSchema:y.object({repoRoot:y.string().optional(),swimlaneId:y.string().min(1)})},J(hg)),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:y.object({title:y.string().min(1).max(300),parentId:y.string().min(1),repoRoot:y.string().optional(),description:y.string().max(2e4).optional(),tagNames:y.array(y.string().max(60)).max(20).optional(),assigneeNames:y.array(y.string().max(80)).max(20).optional()})},J(cg)),e.registerTool("epiq_issue_description_edit",{description:"Edit the markdown description of an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),description:y.string().max(2e4),repoRoot:y.string().optional()})},J(bg)),e.registerTool("epiq_issue_title_edit",{description:"Edit the title of an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),title:y.string().min(1).max(300),repoRoot:y.string().optional()})},J(Ig)),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:y.object({issueId:y.string().min(1).optional(),issueIds:y.array(y.string().min(1)).min(1).max(200).optional(),tagName:y.string().min(1).max(60),repoRoot:y.string().optional()})},J(xg)),e.registerTool("epiq_issue_tag_remove",{description:"Remove a tag from an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),tagId:y.string().min(1),repoRoot:y.string().optional()})},J(Ng)),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:y.object({boardId:y.string().min(1).optional(),repoRoot:y.string().optional()})},J(Mg)),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:y.object({contributorId:y.string().min(1),repoRoot:y.string().optional()})},J(Tg)),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:y.object({tagId:y.string().min(1),repoRoot:y.string().optional()})},J(Eg)),e.registerTool("epiq_tag_restore",{description:"Put back a tag deleted with epiq_tag_remove, on every ticket that still carried it.",inputSchema:y.object({tagId:y.string().min(1),repoRoot:y.string().optional()})},J(Sg)),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:y.object({contributorId:y.string().min(1),repoRoot:y.string().optional()})},J(wg)),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:y.object({issueId:y.string().min(1),assigneeId:y.string().min(1).optional(),self:y.boolean().optional(),assigneeName:y.string().min(1).max(80).optional(),createUnlinked:y.boolean().optional(),repoRoot:y.string().optional()})},J(Ag)),e.registerTool("epiq_issue_assignee_remove",{description:"Remove an assignee from an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),assigneeId:y.string().min(1),repoRoot:y.string().optional()})},J(kg)),e.registerTool("epiq_issue_comment_add",{description:"Add a comment to an Epiq issue",inputSchema:y.object({issueId:y.string().min(1),body:y.string().min(1).max(4e3),repoRoot:y.string().optional()})},J(Lg)),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:y.object({issueId:y.string().min(1),filePath:y.string().min(1),name:y.string().min(1).max(200).optional(),repoRoot:y.string().optional()})},J(Og)),e.registerTool("epiq_issue_comment_delete",{description:"Delete a comment from an Epiq issue",inputSchema:y.object({commentId:y.string().min(1),repoRoot:y.string().optional()})},J(Pg)),e.registerTool("epiq_issue_comment_edit",{description:"Replace the body of one of your own comments on an Epiq issue",inputSchema:y.object({commentId:y.string().min(1),body:y.string().min(1).max(4e3),repoRoot:y.string().optional()})},J(Dg)),e.registerTool("epiq_issue_reopen",{description:"Reopen a closed Epiq issue, restoring it to its previous swimlane",inputSchema:y.object({issueId:y.string().min(1),repoRoot:y.string().optional()})},J(ug)),e.registerTool("epiq_issue_close",{description:"Close an Epiq issue, or many at once with issueIds \u2014 one call, an outcome per ticket",inputSchema:y.object({issueId:y.string().min(1).optional(),issueIds:y.array(y.string().min(1)).min(1).max(200).optional(),repoRoot:y.string().optional()})},J(lg)),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:y.object({issueId:y.string().min(1).optional(),issueIds:y.array(y.string().min(1)).min(1).max(200).optional(),parentId:y.string().min(1),position:y.discriminatedUnion("at",[y.object({at:y.literal("start")}),y.object({at:y.literal("end")}),y.object({at:y.literal("before"),sibling:y.string().min(1)}),y.object({at:y.literal("after"),sibling:y.string().min(1)})]).optional(),repoRoot:y.string().optional()})},J(mg)),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:y.object({name:y.string().min(1).max(80),repoRoot:y.string().optional()})},J(Rg)),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:y.object({repoRoot:y.string().optional()})},J(vg)),e},BI=async()=>{let e=_g(),t=new OI;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:FI}=await Promise.resolve().then(()=>(Qn(),Rd)),{isFail:_I}=await Promise.resolve().then(()=>(N(),Id)),oi=process.argv.slice(2);oi.length>1&&(console.error(`Expected at most one name argument, got ${oi.length}`),process.exit(1));if(oi[0]!==void 0){let e=FI(oi[0],"The name argument");_I(e)&&(console.error(e.message),process.exit(1))}var{setVirtualNodesEnabled:UI}=await Promise.resolve().then(()=>(Li(),Jp));UI(!1);var{startMcpServer:$I}=await Promise.resolve().then(()=>($g(),Ug));await $I();
90
+ `,qd.writeFileSync(t,n,"utf8"),J.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),l("Local epiq paths ignored",!0)}});import fE from"node:fs";import Mf from"node:path";var gE,xe,Li,Gd=h(()=>{"use strict";kf();Cs();Xe();ct();Or();to();Ce();Yn();R();ae();nn();gE=async e=>{let t=await W({cwd:e,args:["status","--porcelain"]});return d(t)?t:l("Checked git diff",t.value.stdout.split(`
91
+ `).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},xe=(e,t)=>a(`[${e}] ${t}`),Li=async({cwd:e,user:t})=>{let n=Ss(),o=await lt(e);if(d(o))return xe(1,o.message);let r=o.value,s=await As(r);if(d(s))return xe(2,s.message);if(s.value)return xe(2,`Cannot initialize Epiq while a git operation is in progress: ${s.value}`);let i=await gE(r);if(d(i))return xe(2.5,i.message);if(i.value.length>0)return xe(3,`Cannot initialize Epiq with uncommitted changes (${i.value.join(", ")}). Commit or stash your changes first.`);if(Nr(r))return xe(4,"Epiq project already initialized");let{userId:c,userName:u}=t;if(!c||!u)return xe(5,"Missing Epiq user id");let m=await dm(r);if(d(m))return xe(6,m.message);let p=n.stateBranch,f=await ws({repoRoot:r,branch:p});if(d(f))return xe(6,f.message);if(f.value)return xe(6,`State branch already exists: ${p}`);let y=await qa({repoRoot:r,stateBranchName:p});if(d(y))return xe(6,y.message);let I=Ms();if(d(I))return xe(7,I.message);let S=Mf.join(ks(),n.projectId),A=await oo({repoRoot:r,stateBranchRoot:S,stateBranchName:p});if(d(A))return xe(8,A.message);let w=Mf.join(S,".epiq");fE.mkdirSync(w,{recursive:!0});let k=Qu({userId:c,userName:u});if(d(k))return xe(9,k.message);for(let Sv of k.value){let ol=Gs({event:Sv,rootDir:S});if(d(ol))return xe(9,ol.message)}let D=Zn({userId:c,userName:u}),_=$s(S,D);if(d(_))return xe(9,_.message);let H=await Js({stateBranchRoot:S,eventFileName:D});if(d(H))return xe(10,H.message);let ie=await xo({cwd:S,message:"[epiq:init]"});if(d(ie))return xe(10,ie.message);let En=await Tf(r);if(d(En))return xe(11,En.message);let en=wl({repoRoot:r,fileContents:n});if(d(en))return xe(12,en.message);let ar=await ye.stage({cwd:r,pathspec:[".epiq/project.json",".gitignore"]});if(d(ar))return xe(13,ar.message);let dr=await ye.commit({cwd:r,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(d(dr))return xe(13,dr.message);let ho=[],tl=await W({cwd:r,args:["push","-u","origin","HEAD"]});d(tl)&&ho.push(`[init:14] ${tl.message}`);let nl=await _r({repoRoot:r,stateBranchRoot:S});return d(nl)&&ho.push(`[init:15] ${nl.message}`),l("Project initialized",{repoRoot:r,projectId:n.projectId,stateBranch:p,stateBranchRoot:S,defaultEvents:k.value,warnings:ho})}});var os,Pf,Lf=h(()=>{"use strict";ut();Hr();ln();pe();R();Gd();ce();We();M();os=(e,t)=>a(`[${e}] ${t}`),Pf=async()=>{te("");let e=ai();if(!e.isSetupDone||!e.userName)return os(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let t=Ie(),n=t.userName,o=t.userId;if(!o||!n)return os(5,"Missing Epiq user id");let r=await Li({cwd:process.cwd(),user:{userId:o,userName:n}});if(d(r))return r;let s="Project initialized!";for(let y of r.value.warnings)s+=` Warn: ${y}`;let c=cn(r.value.defaultEvents).filter(d);if(c.length>0)return os(16,c.map(y=>y.message).join(`
92
+ `));let u=ze();if(d(u))return os(16,u.message);let{rootNodeId:m,nodes:p}=u.value,f=p[m];return f?(U.navigate({contextNode:f,selectedIndex:0}),N({hasProjectDefinition:!0,mode:b.DEFAULT}),l(s,null)):os(16,"Unable to resolve initialized root node")}});import{ulid as hE}from"ulid";function Vd(e){let t=Ff();if(d(t))return t;let{contextNode:n,nodes:o}=g();if(!n.parentNodeId)return a("Missing parent node id");let r=o[n.parentNodeId];if(!r)return a("Missing parent node");let s=ge(r.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let c=s[i+e];if(!c)return a("Missing sibling node");let u=_f({id:t.value.id,parentId:c.id,position:{at:"end"}});return d(u)?u:Of(u.value)}function Kd(e){let t=Ff();if(d(t))return t;let{contextNode:n,selectedIndex:o}=g(),s=ge(n.id)[o+e];if(!s)return a("Missing sibling node");let i=_f({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return d(i)?i:Of(i.value)}var Df,_n,rs,Ff,zd,_f,Of,Yd=h(()=>{"use strict";ln();Ce();R();yt();M();Df=null,_n=()=>structuredClone(Df),rs=e=>{Df=e},Ff=()=>{let{contextNode:e,selectedIndex:t}=g(),o=ge(e.id)[t];return o?l("Resolved selected child",o):a("Target node not found")},zd=({id:e,parentId:t,position:n={at:"end"}})=>{let o=ge(t).filter(r=>r.id!==e);return zs(o,n)},_f=({id:e,parentId:t,position:n={at:"end"}})=>{let o=oe();if(d(o))return a("Unable to resolve user ID");let r=zd({parentId:t,id:e,position:n});return d(r)?r:l("Created pending move state",{id:hE(),...o.value,action:"move.node",payload:{id:e,parent:t,rank:r.value.rank}})},Of=e=>{rs(e);let t=Nn(e,!0);return d(t)?t:l("Node moved successfully",t.value)}});import{ulid as vE}from"ulid";var Bf,Di,Uf,$f=h(()=>{"use strict";ut();Yd();Se();Ce();pe();R();yt();ce();M();ae();Bf=()=>{let e=_n();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,o=g().nodes[n];if(!o)return a("Move parent not found");let r=ge(n).findIndex(s=>s.id===t);return r===-1?a("Moved node not found among rendered children"):(U.navigate({contextNode:o,selectedIndex:r}),l("Synchronized navigation to moved node",null))},Di=(e,t="Moved preview")=>{if(d(e))return e;let n=Bf();return d(n)?n:(N({mode:b.MOVE}),l(t,null))},Uf=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{modifier:t}=de().commandMeta,{contextNode:n,selectedIndex:o}=g(),r=ge(n.id)[o];if(!r)return N({mode:b.DEFAULT}),a("No move target");if(t==="start"){if(r.readonly)return a("Target node is read-only");if(o===-1)return a("No item selected");if(!r.parentNodeId)return a("Target has no parent");let s=ge(r.parentNodeId),i=s.findIndex(({id:f})=>f===r.id);if(i===-1)return a("Target not found among siblings");let c=s[i-1],u=s[i+1],m=u!=null?{at:"before",sibling:u.id}:c!=null?{at:"after",sibling:c.id}:{at:"start"},p=zd({parentId:r.parentNodeId,id:r.id,position:m});return d(p)?p:(rs({id:vE(),action:"move.node",payload:{id:r.id,parent:r.parentNodeId,rank:p.value.rank},...e.value}),N({mode:b.MOVE}),l("Move initialized",null))}if(t==="next")return Di(Kd(1));if(t==="previous")return Di(Kd(-1));if(t==="to-next")return Di(Vd(1));if(t==="to-previous")return Di(Vd(-1));if(t==="confirm"){let s=_n();if(!s)return a("No pending move to confirm");let i=await $t();if(d(i))return i;let c=L([s],i.value);if(d(c))return c;let u=Bf();return d(u)?u:(rs(null),N({mode:b.DEFAULT}),l("Moved item",null))}return t==="cancel"?(rs(null),N({mode:b.DEFAULT}),l("Cancelling move",null)):a("Invalid move modifier")}});import{monotonicFactory as yE,ulid as bE}from"ulid";var xE,Fi,Xd=h(()=>{"use strict";R();xE=yE(),Fi=({name:e,parent:t,rank:n,user:{userId:o,userName:r}})=>{let s=xE();return l("Created issue events",[{id:bE(),userId:o,userName:r,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])}});import{ulid as _i}from"ulid";var jf,Hf=h(()=>{"use strict";ut();Xd();Se();Ce();Ft();R();ne();yt();M();ae();jf=async(e,t)=>{let n=oe();if(d(n))return a("Unable to resolve user ID");let o=await $t();if(d(o))return o;let r=o.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:c}=g(),u=m=>{let p=L([m],r);if(d(p))return p;let f=E.getNode(p.value[0].result.id);if(!f)return a("Created node not found");if(!f.parentNodeId)return p;let y=E.getNode(f.parentNodeId);return y?(U.navigate({contextNode:y,selectedIndex:E.getSiblings(f.parentNodeId).findIndex(({id:I})=>I===f.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=g(),p=E.getNode(m);if(!p)return a("Workspace not found");let f=wn(p.id,n.value,r);return d(f)?f:u({id:_i(),action:"add.board",payload:{id:_i(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=it(s,"BOARD");if(d(m))return a("Unable to add swimlane in this context");let p=wn(m.value.id,n.value,r);return d(p)?p:u({id:_i(),action:"add.swimlane",payload:{id:_i(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=se(i.id)[c],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let D=it(s,"SWIMLANE");return d(D)?null:D.value})();if(!p)return a("Unable to add issue in this context");let f=wn(p.id,n.value,r);if(d(f))return f;let y=Fi({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(d(y))return y;let I=y.value,S=L([...I],r);if(d(S))return S;if(!S.value[0])return a("Issue creation failed");let k=I.find(D=>D.action==="add.issue")?.payload.id;return k?(U.navigate({contextNode:p,selectedIndex:E.getSiblings(p.id).findIndex(({id:D})=>D===k)}),l("Issue created",null)):a("Unable to determine ticket id")}return l("Success",null)}});var IE,Wf,EE,qf,SE,Gf,zf=h(()=>{"use strict";bo();Xe();ct();Or();oi();Ka();ti();Ao();to();St();R();nn();M();Lr();ae();Xs();IE=e=>e.some(t=>t.action==="init.workspace"),Wf=async(e,t)=>{let n=Bt(e);return d(n)?a(n.message):Er({cwd:t,branch:n.value})},EE=e=>{let t=Me(process.cwd());if(d(t))return!1;let n=be({repoRoot:t.value});return!d(n)&&n.value===e},qf=async e=>{let t=be({repoRoot:e});if(d(t))return So(3,t.message);let n=t.value,o=await oo({repoRoot:e,stateBranchRoot:n,stateBranchName:Ss().stateBranch});if(d(o))return So(3,o.message);let r=Et(n);if(d(r))return So(3,r.message);if(!IE(r.value.events)){let m=await Wf(e,n);if(d(m)&&logger.info(3,m.message),r=Et(n),d(r))return So(3,r.message)}let{events:s,unreadable:i}=r.value,c=Wt(s,i);if(d(c))return So(4,c.message);N({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let u=jr({root:e});return d(u)&&logger.info(u.message),l("Loaded project",void 0)},SE=async e=>{let t=be({repoRoot:e});if(d(t))return a(t.message);let n=t.value,o=await qn({repoRoot:n});if(d(o))return a(o.message);if(!o.value)return l("No remote to pull",void 0);let r=await Zs({worktreeRoot:n,operation:"boot pull",fn:()=>Xa(n,()=>(Eo("Pulling"),Wf(e,n)))});if(d(r))return Re(r.message);if(r.value===null)return l("Another process holds the state worktree",void 0);let s=r.value;if(d(s))return Ir(s.message)?(Ys("Offline"),l("Offline",void 0)):Re(s.message);if(!s.value)return no("Already synced"),l("Already synced",void 0);if(!EE(n))return l("Project changed during the pull",void 0);let i=Ja(n);return d(i)?i:(no("Pulled"),l("Pulled and reloaded",void 0))},Gf=e=>{SE(e).then(t=>{d(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${tm(t)}`)})}});import RE from"node:os";import Vf from"node:path";var NE,CE,Kf,Yf=h(()=>{"use strict";zf();Ao();R();ce();M();ae();NE=e=>e==="~"||e.startsWith("~/")?Vf.join(RE.homedir(),e.slice(1)):e,CE=(e,t)=>{let n=e.trim();if(!n)return a("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):a(`No recent project #${n}`)}let o=Me(Vf.resolve(NE(n)));return d(o)?a(`No epiq project at ${n}`):l("Resolved project path",o.value)},Kf=async()=>{let e=Ei();if(te(""),g().hasProjectDefinition)return a("Already in a project; run epiq from another directory");let t=ii({exclude:process.cwd()}),n=d(t)?[]:t.value,o=CE(e,n);if(d(o))return a(o.message);let r=o.value,s=process.cwd();try{process.chdir(r)}catch(c){return a(`Unable to enter ${r}: ${c instanceof Error?c.message:String(c)}`)}let i=await qf(r);return d(i)?(process.chdir(s),a(i.message)):(Gf(r),l(`Opened ${Rm(r)}`,null))}});var Oi,Jd=h(()=>{"use strict";ut();St();ln();R();M();Oi=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:o})=>{let r=g(),s=_a(n,t);if(d(s))return a(s.message);let{appliedEvents:i,unappliedEvents:c}=s.value,u=bn();if(d(u))return u;let m=cn(i),{fatal:p,skipped:f}=zn(m);if(p.length>0)return bn(),N(r),a(p.map(I=>I.message).join(", "));Vn(f);let y=g().nodes[e];return y?(U.navigate({contextNode:y,selectedIndex:o}),l("",{unappliedEvents:c})):(bn(),N(r),a("Board did not exist at that date"))}});var Xf,Jf=h(()=>{"use strict";Xf=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 AE,wE,TE,Bi,Ui,uo,Qf,Zf,Qd=h(()=>{"use strict";Ke();ss();ln();pe();R();Jf();M();AE=20,wE=16,TE=150,Bi=null,Ui=null,uo=()=>{Bi!==null&&(clearInterval(Bi),Bi=null),Ui!==null&&(clearTimeout(Ui),Ui=null)},Qf=()=>{uo(),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Zf=({events:e,startTime:t,durationMs:n})=>{uo();let o=e.length,r=pr(e.map(f=>$n(f))).map(f=>f??t),s=r[o-1]??Date.now(),i=Xf(r),c=Math.max(1,Math.round(n*AE/1e3)),u=Math.max(Math.round(n/c),wE),m=0,p=0;N({mode:b.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:o,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Bi=setInterval(()=>{m++;let f=m/c,y=[],I,S;for(;p<o&&i[p]<=f;){let w=e[p],k=Nn(w);if(d(k)){if(wr(k)){p++;continue}Qf();return}y.push(...Ra(w)),I=w,S=r[p],p++}if(p>=o||m>=c){for(;p<o;p++){let k=Nn(e[p]);if(d(k)&&!wr(k))break}let w=g().replay;N({unappliedEvents:[],replay:w&&{...w,progress:1,appliedCount:o}}),uo(),Ui=setTimeout(Qf,TE);return}let A=g().replay;N({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:o,startTime:t,endTime:s,currentTime:I?S??A?.currentTime??t:A?.currentTime??t,currentLabel:I?Zd(I):A?.currentLabel??"",flashNodeIds:I?[...new Set(y)]:A?.flashNodeIds??[]}})},u)}});var eg,tg=h(()=>{"use strict";Xe();Ke();St();ln();pe();Ft();R();ce();M();qr();Jd();Qd();eg=async()=>{let e=it(g().breadCrumb,"BOARD");if(d(e))return e;let t=await lt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=be({repoRoot:t.value});if(d(n))return n;let{modifier:o,inputString:r}=de().commandMeta;if(uo(),o==="now"){let c=Jn(n.value);if(d(c))return a(c.message);let u=bn();if(d(u))return u;let m=cn(c.value),{fatal:p,skipped:f}=zn(m);return p.length>0?a(p.map(y=>y.message).join(", ")):(Vn(f),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),l("Peeking now",!0))}let s;if(o==="prev"||o==="next"){let c=Oa(n.value);if(d(c))return c;let u=o==="prev"?g().eventLog.at(-1):g().unappliedEvents.at(0),m=u===void 0?null:$n(u),p=(u===void 0?null:c.value.get(u.id)??null)??(m===null?null:mr(m));if(p===null)return a(o==="prev"?"No previous event to peek":"No next event to peek");s=o==="prev"?p:p+1}else{let c=so(o||r.trim());if(!c)return a("Invalid peek date");s=c.getTime()}let i=Oi({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return d(i)?i:(N({mode:b.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),l("Peeking",!0))}});var ng,og=h(()=>{"use strict";Xe();Ft();R();ce();M();qr();Jd();Qd();ng=async()=>{let e=it(g().breadCrumb,"BOARD");if(d(e))return e;let t=await lt(process.cwd());if(d(t))return a("Unable to locate repo root");let n=be({repoRoot:t.value});if(d(n))return n;let{modifier:o,inputString:r}=de().commandMeta,{dateInput:s,durationInput:i}=mi(o,r);if(uo(),g().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let c=so(s);if(!c)return a("Invalid replay date");let u=i?ui(i):15e3;if(u===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=c.getTime(),p=g(),f=Oi({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(d(f))return f;let{unappliedEvents:y}=f.value;return y.length===0?(bn(),N(p),l("Nothing to replay from that point",!0)):(Zf({events:y,startTime:m,durationMs:u}),l("Replaying board history",!0))}});import{spawn as ME}from"node:child_process";var PE,rg,sg=h(()=>{"use strict";R();PE=()=>{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"]}}},rg=async e=>new Promise(t=>{let{command:n,args:o}=PE();try{let r=ME(n,o,{stdio:["pipe","ignore","ignore"]});r.on("error",()=>t(a(`Clipboard tool not available (${n})`))),r.on("close",s=>t(s===0?l("Copied to clipboard",null):a(`Clipboard tool failed (${n})`))),r.stdin.on("error",()=>{}),r.stdin.write(e),r.stdin.end()}catch{t(a(`Clipboard tool not available (${n})`))}})});var is,ig,ag=h(()=>{"use strict";R();M();sg();Je();Wr();pn();is=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await rg(e);return d(n)?n:l(`Copied ${t} to clipboard`,null)},ig=async e=>{let{breadCrumb:t,selectedNode:n}=g(),o=Gr({breadCrumb:t,selectedNode:n}),r=o??n;if(!r)return a("Nothing selected to copy from");switch(e.modifier){case Ae.REF:return is(j(r.id),"ref");case Ae.TITLE:return is(r.title,"title");case Ae.DESCRIPTION:return o?is(o.props?.description??"","description"):a("No issue in scope");case Ae.TAGS:{if(!o)return a("No issue in scope");let s=Tn(o).map(({name:i})=>i);return is(s.join(", "),"tags")}case Ae.ASSIGNEES:{if(!o)return a("No issue in scope");let s=kn(o).map(({name:i})=>i);return is(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}}});var dg,cg=h(()=>{"use strict";oi();pe();R();ce();M();dg=async()=>{te(""),N({mode:b.DEFAULT});let e=ze();if(d(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");N({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await ni();return d(t)?(N({syncStatus:{msg:t.message,status:"failed"}}),t):(N({mode:b.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)}});var _e,Yt=h(()=>{"use strict";R();ae();_e=async()=>{let e=await $t();return d(e)?e:l("Resolved persist root",e.value)}});import{ulid as lg}from"ulid";var LE,ug,mg=h(()=>{"use strict";Se();Ce();K();R();M();Yt();LE=e=>e.action==="add.issue.comment",ug=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=se(t.id)[n];if(!o)return a("Unable to resolve child to delete");let r=await _e();if(d(r))return r;if(o.context==="COMMENT"){let s=o.id,i=P(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let c=g().nodes[i];if(!c||!P(c))return a("Unable to resolve comment issue");let u=c.log?.filter(LE).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):L([{id:lg(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],r.value):a("Unable to resolve comment")}return L([{id:lg(),action:"delete.node",payload:{id:o.id},...e.value}],r.value)}});import{ulid as DE}from"ulid";var pg,fg=h(()=>{"use strict";Se();Ce();dn();K();R();yt();M();Yt();pg=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=se(t.id)[n];if(!o)return a("Unable to close issue, no target found");if(!P(o))return a("Cannot close in this context");let r=g().nodes[he];if(!r)return a("Unable to locate closed swimlane");if(o.parentNodeId===r.id)return a("Issue is already closed");let s=await _e();if(d(s))return s;let i=s.value,c=jt(r.id,o.id,{at:"end"},e.value,i);if(d(c))return c;let u=L([{id:DE(),action:"close.issue",payload:{id:o.id,parent:r.id,rank:c.value},...e.value}],i);return d(u)?u:l("Issue closed",null)}});var $i,ec=h(()=>{"use strict";$i=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 FE}from"ulid";var gg,hg=h(()=>{"use strict";Se();Ce();ec();dn();K();R();ne();yt();M();Yt();gg=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=se(t.id)[n];if(!o)return a("Unable to reopen issue, no target found");let r=o.context==="TICKET"?l("Resolved ticket",o):Ct(o.id,"TICKET");if(d(r))return a("Cannot reopen in this context");let s=r.value,i=g().nodes[he];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!P(s))return a("Target node is not issue");let c=$i(s);if(!c)return a("Unable to resolve previous parent from issue history");if(c===i.id)return a("Previous parent resolves to closed swimlane");let u=g().nodes[c];if(!u)return a("Previous parent no longer exists");let m=await _e();if(d(m))return m;let p=m.value,f=jt(u.id,s.id,{at:"end"},e.value,p);if(d(f))return f;let y=L([{id:FE(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...e.value}],p);return d(y)?y:l("Issue reopened",null)}});import{ulid as _E}from"ulid";var vg,yg=h(()=>{"use strict";Se();Ce();R();ce();M();Yt();vg=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=g(),o=se(t.id)[n];if(!o)return a("Missing node");if(o.readonly)return a("Cannot rename readonly node");let r=Ei();if(!r)return a("Provide a title");let s=await _e();return d(s)?s:L([{id:_E(),action:"edit.title",payload:{id:o.id,name:r},...e.value}],s.value)}});import{ulid as OE}from"ulid";var bg,xg=h(()=>{"use strict";ne();Se();Ce();K();R();ce();M();Yt();bg=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=de().commandMeta,o=(t||n).trim();if(!o)return a("Provide a tag");let r=E.findTagByName(o);if(!r)return a(`Tag "${o}" does not exist`);let{selectedNode:s}=g();if(!s)return a("Invalid untag target");let i=Ct(s.id,"TICKET");if(d(i))return a("Unable to untag issue in this context");let c=i.value;if(!P(c))return a("Target node is not issue");if(!(c.props.tags??[]).includes(r.id))return a("Issue is not tagged with that tag");let m=await _e();return d(m)?m:L([{id:OE(),action:"remove.issue.tag",payload:{id:c.id,tag:r.id},...e.value}],m.value)}});import{ulid as tc}from"ulid";var Ig,Eg=h(()=>{"use strict";ne();Se();Ce();K();R();ce();M();Yt();Ig=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=de().commandMeta,o=(t||n).trim();if(!o)return a("Provide a tag");let{selectedNode:r}=g();if(!r)return a("Invalid tag target");let s=Ct(r.id,"TICKET");if(d(s))return a("Unable to tag issue in this context");let i=s.value;if(!P(i))return a("Target node is not issue");let c=await _e();if(d(c))return c;let u=E.findTagByName(o),m=u?.id??tc();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):L([...u?[]:[{id:tc(),action:"create.tag",payload:{id:m,name:o},...e.value}],{id:tc(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],c.value)}});var ji,nc=h(()=>{"use strict";M();ji=()=>{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 oc}from"ulid";var Sg,Rg=h(()=>{"use strict";Se();Ce();K();R();ne();ce();M();nc();Yt();Sg=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=de().commandMeta,o=(t||n).trim();if(!o)return a("Provide an assignee");let r=o.startsWith("!"),s=(r?o.slice(1):o).trim();if(!s)return a("Provide an assignee");let{selectedIndex:i,contextNode:c}=g(),u=se(c.id)[i];if(!u)return a("Invalid assign target");let m=Ct(u.id,"TICKET");if(d(m))return a("Unable to assign issue in this context");let p=m.value;if(!P(p))return a("Target node is not issue");let f=await _e();if(d(f))return f;let y=ji(),I=!r&&s.toLowerCase()==="me",S,A;if(I)S=e.value.userId,A=y.find(D=>D.id===S)?.name??e.value.userName;else{let D=y.filter(H=>H.name===s);if(D.length>1)return a(`"${s}" matches ${D.length} contributors (${D.map(H=>H.id).join(", ")}). Assign from the GUI to choose by id.`);let _=D[0];if(!_&&!r)return a(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);S=_?.id??oc(),A=_?.name??s}if((p.props.assignees??[]).includes(S))return a("Assignee already assigned");let k=!!g().contributors[S];return L([...k?[]:[{id:oc(),action:"create.contributor",payload:{id:S,name:A},...e.value}],{id:oc(),action:"add.issue.assignee",payload:{id:p.id,assignee:S},...e.value}],f.value)}});import{ulid as BE}from"ulid";var Ng,Cg=h(()=>{"use strict";Se();Ce();K();R();ne();ce();M();nc();Yt();Ng=async()=>{let e=oe();if(d(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=de().commandMeta,o=(t||n).trim();if(!o)return a("Provide an assignee to remove");let{selectedNode:r}=g();if(!r)return a("Invalid unassign target");let s=Ct(r.id,"TICKET");if(d(s))return a("Unable to unassign in this context");let i=s.value;if(!P(i))return a("Target node is not issue");let c=i.props.assignees??[],u=o.toLowerCase()==="me",m=u?c.filter(y=>y===e.value.userId):ji().filter(y=>y.name===o&&c.includes(y.id)).map(y=>y.id);if(m.length>1)return a(`"${o}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return a(u?"Issue is not assigned to you":`Issue is not assigned to "${o}"`);let f=await _e();return d(f)?f:L([{id:BE(),action:"remove.issue.assignee",payload:{id:i.id,assignee:p},...e.value}],f.value)}});import{ulid as Ag}from"ulid";var wg,Tg=h(()=>{"use strict";Se();Ce();Ft();K();R();ne();M();hn();Yt();wg=async e=>{let t=e.inputString.trim();if(!t)return a("Provide a comment");if(t.length>4e3)return a(`Cannot exceed ${4e3} characters`);let n=oe();if(d(n))return a("Unable to resolve user ID");let{breadCrumb:o,selectedNode:r}=g(),s=it([...o,r],"TICKET");if(d(s))return a("Edit target must be an issue");let i=s.value;if(!i)return a("Invalid comment target");let c=i.context==="TICKET"?l("Resolved ticket",i):Ct(i.id,"TICKET");if(d(c))return a("Unable to comment on issue in this context");let u=c.value;if(!P(u))return a("Target node is not issue");let m=await _e();return d(m)?m:L([{id:Ag(),action:"add.issue.comment",payload:{id:Ag(),issue:u.id,author:n.value.userId,md:t},...n.value}],m.value)}});import UE from"zod";var kg,Mg=h(()=>{"use strict";zt();pe();R();ce();We();M();kg=()=>{let e=de().commandMeta.inputString,t=UE.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return a("Auto sync duration must be a number of at least 3000 ms");let n=et({autoSyncDebounceMs:t.data});return d(n)?n:(ht({autoSyncIntervalMs:t.data}),N({mode:b.DEFAULT}),l(`Auto sync interval set to ${t.data}ms`,null))}});var Pg,Lg=h(()=>{"use strict";Hr();zt();pe();R();ce();We();M();Pg=()=>{let e=de().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=km(e),n=et({autoSync:t});return d(n)?n:(ht({autoSync:t}),N({mode:b.DEFAULT}),l(`Auto sync set to "${e}"`,null))}});var Dg,Fg=h(()=>{"use strict";zt();pe();R();ce();We();M();Dg=()=>{let e=de().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=et({logLevel:e});return d(n)?n:(ht({logLevel:e}),N({mode:b.DEFAULT}),l(`Auto sync set to "${e}"`,null))}});import{ulid as $E}from"ulid";var _g,Og=h(()=>{"use strict";Un();zt();pe();R();We();M();pn();Mg();ud();Lg();Fg();_g=e=>{let t=e.inputString.trim();switch(e.modifier){case ve.USERNAME:{if(process.env[gt])return a(`Cannot change the configured user while ${gt} names this process`);let n=ko();if(d(n))return n;let{userId:o,preferredEditor:r,userName:s}=n.value,i=t||s,c=o||$E();if(!i||!c)return a("Unable to resolve user name or id");let u=et({userName:i,userId:c,preferredEditor:r??""});return d(u)?u:(ht({userName:i,userId:c}),N({mode:b.DEFAULT}),l(`Username set to "${i}"`,null))}case ve.EDITOR:{if(!t)return a("No editor provided");let n=et({preferredEditor:t});return d(n)?n:(ht({preferredEditor:t}),N({mode:b.DEFAULT}),l(`Editor configuration set to "${t}"`,null))}case ve.VIEW:{if(t!=="wide"&&t!=="dense")return a("Invalid view mode");let n=et({viewMode:t});return d(n)?n:(ht({viewMode:t}),N({mode:b.DEFAULT}),l(`View set to "${t}"`,null))}case ve.AUTOSYNC:return Pg();case ve.LOG_LEVEL:return Dg();case ve.SYNC_DEBOUNCE_MS:return kg();case ve.ATTACHMENT_MAX_KB:return Km();default:return a("Unknown config command")}}});var Bg,Ug=h(()=>{"use strict";If();ut();pe();R();ce();M();Pi();ro();bd();pn();wf();Lf();$f();Hf();Yf();tg();og();ag();cg();mg();fg();hg();yg();xg();Eg();Rg();Cg();Tg();Og();Bg=[{systemOnly:!0,intent:B.Move,description:"Internal move-state command",mode:b.COMMAND_LINE,action:Uf},{intent:B.Delete,description:"Delete the currently selected node",mode:b.COMMAND_LINE,action:ug,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:b.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=de().commandMeta,n=/(!=|=)/,[o]=e.split(n);if(!o||!(i=>we(x.FILTER).map(c=>c.split(n)[0]).includes(i))(o))return a("Invalid filter modifier");let s={target:o,operator:"=",value:t.trim()};return Ne(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:b.DEFAULT})),l("Filter updated",null)}},{intent:B.ViewHelp,description:"Open the help screen",mode:b.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return Fn({pendingNavTarget:{contextNode:e,breadCrumb:o,selectedIndex:t,selectedNode:n}}),N({mode:b.HELP}),l("Viewing help",null)}},{intent:B.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:b.COMMAND_LINE,action:pg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:b.COMMAND_LINE,action:gg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Init,description:"Initialize Epiq in the current git repository",mode:b.COMMAND_LINE,action:Pf},{intent:B.OpenProject,description:"Open a recently used epiq project, by number or path",mode:b.COMMAND_LINE,action:Kf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.NewItem,description:"Create a new board, swimlane, or issue",mode:b.COMMAND_LINE,action:jf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Rename,description:"Rename the currently selected node",mode:b.COMMAND_LINE,action:vg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.UntagTicket,description:"Remove a tag from the selected issue",mode:b.COMMAND_LINE,action:bg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.TagTicket,description:"Add or create a tag on the selected issue",mode:b.COMMAND_LINE,action:Ig,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.AssignUserToTicket,description:"Assign a user to the selected issue",mode:b.COMMAND_LINE,action:Sg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:b.COMMAND_LINE,action:Ng,onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Comment,description:"Add a comment to the selected issue",mode:b.COMMAND_LINE,action:async(e,t)=>wg(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Sync,description:"Pull, commit, and push Epiq state",mode:b.COMMAND_LINE,action:dg},{intent:B.Peek,description:"View board state at another point in time",mode:b.COMMAND_LINE,action:eg},{intent:B.Replay,description:"Replay board history forward from a point in time",mode:b.COMMAND_LINE,action:ng},{intent:B.Export,description:"Export the current board layout to markdown",mode:b.COMMAND_LINE,action:async()=>{let e=await xf();return d(e)?e:(N({mode:b.DEFAULT}),l("Export successful",!0))}},{intent:B.Exit,description:"Exit the application",mode:b.COMMAND_LINE,action:async()=>(U.exit(),l("Exit successful",!0))},{intent:B.Edit,description:"Edit title or description",mode:b.COMMAND_LINE,action:async(e,t)=>Af(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:b.COMMAND_LINE,action:async(e,t)=>ig(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:B.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:b.COMMAND_LINE,action:(e,t)=>_g(t)}]});var jE,Xt,rc=h(()=>{"use strict";ri();yi();bd();Ug();R();ce();We();M();jE=new Set(["peek","replay","filter","view-help","yank"]),Xt=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:o,inputString:r}}=de();if(!t)return a("No command to confirm");if(!e&&n===Mn.Invalid)return a("Invalid command");let s=Rp(t);xp();let{readOnly:i}=g();if(i&&!jE.has(s))return Xr({status:tn.Fail,message:"Command not available in readonly state",value:null});let c=Bg.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!c)return Xr({status:tn.Fail,message:"Command not found",value:null});let u;try{u=await c.action(c,{command:t,inputString:r,modifier:o})}catch(m){return Xr({status:tn.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return d(u)?Xr(u):(Ip({addToHistory:!e}),c.onSuccess?.(),Ie().autoSync&&Im(),u)}});var Hi,Wi,$g,jg=h(()=>{"use strict";R();pe();M();jn();rc();Yd();ce();Hi=[{intent:O.Exit,mode:b.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(N({mode:b.COMMAND_LINE}),te("move cancel"),Xt({isForceExecutedBySystem:!0}))},{intent:O.InitMove,mode:b.DEFAULT,description:"[m] move",action:()=>(N({mode:b.COMMAND_LINE}),te("move start"),Xt({isForceExecutedBySystem:!0}))},{intent:O.ConfirmMove,mode:b.MOVE,description:"[m] confirm move",action:()=>(N({mode:b.COMMAND_LINE}),te("move confirm"),Xt({isForceExecutedBySystem:!0}))}],Wi=[{intent:O.MovePreviousItem,mode:b.MOVE,action:()=>_n()?(N({mode:b.COMMAND_LINE}),te("move previous"),Xt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:O.MoveNextItem,mode:b.MOVE,action:()=>_n()?(N({mode:b.COMMAND_LINE}),te("move next"),Xt({isForceExecutedBySystem:!0})):a("No pending move")}],$g=[{intent:O.MoveToNextContainer,mode:b.MOVE,action:()=>_n()?(N({mode:b.COMMAND_LINE}),te("move to-next"),Xt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:O.MoveToPreviousContainer,mode:b.MOVE,action:()=>_n()?(N({mode:b.COMMAND_LINE}),te("move to-previous"),Xt({isForceExecutedBySystem:!0})):a("No pending move")}]});var Hg,Wg=h(()=>{"use strict";K();jg();Hg={[V.WORKSPACE]:[...Hi,...Wi],[V.BOARD]:[...Hi,...Wi],[V.SWIMLANE]:[...Hi,...Wi,...$g],[V.TICKET]:[],[V.FIELD]:[],[V.FIELD_LIST]:[],[V.TEXT]:[],[V.COMMENT]:[]}});import{spawn as HE}from"node:child_process";function qg(e){let t=process.platform,r=HE(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 Gg=h(()=>{"use strict"});import WE from"node:fs";import qE from"node:path";var zg,Vg=h(()=>{"use strict";Xe();Po();R();ae();Gg();zg=e=>{let t=Me(process.cwd());if(d(t))return a("Unable to resolve project root");let n=be({repoRoot:t.value});if(d(n))return a(n.message);let o=Mo(e.hash,e.ext),r=qE.join(Ps(n.value),o);return WE.existsSync(r)?(qg(r),l(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")}});var Kg,Yg,Xg=h(()=>{"use strict";pe();R();ce();M();Pi();jn();ut();Kg=()=>{te("");let{pendingNavTarget:e}=Vo();N({mode:b.DEFAULT}),e&&U.navigate(e),Fn({pendingNavTarget:void 0})},Yg=[{intent:O.ExitCommandLine,mode:b.HELP,action:()=>(Kg(),l("Exiting help",null))},{intent:O.Exit,mode:b.HELP,action:()=>(Kg(),l("Closed help",null))},{intent:O.NavPreviousItem,mode:b.HELP,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),l("Navigating to previous help item",null))},{intent:O.NavNextItem,mode:b.HELP,action:()=>(U.navigateToNextItem(),l("Navigating to next help item",null))},{intent:O.NavToPreviousContainer,mode:b.HELP,action:()=>(U.navigateToPreviousContainer(),l("Navigating to previous help container",null))},{intent:O.NavToNextContainer,mode:b.HELP,action:()=>(U.navigateToNextContainer(),l("Navigating to next help container",null))}]});var GE,Jg,Qg,Zg=h(()=>{"use strict";pe();K();R();ce();M();Pi();jn();ut();GE=e=>{N({mode:b.COMMAND_LINE});let{pendingNavTarget:t}=Vo();t&&U.navigate(t),Fn({pendingNavTarget:void 0}),te(`${e} `)},Jg=()=>{te("");let{pendingNavTarget:e}=Vo();e&&U.navigate(e),Fn({pendingNavTarget:void 0}),N({mode:b.DEFAULT})},Qg=[{intent:O.InitCommandPalette,mode:b.DEFAULT,description:"[?] command palette",action:()=>{te("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}=g();return Fn({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:o}}),N({mode:b.PALETTE}),l("Opening command palette",null)}},{intent:O.Confirm,mode:b.PALETTE,action:()=>{let{selectedNode:e}=g();if(!e||!fl(e))return a("Command only applicable on text nodes");if(e.props.disabled)return a("Command is not available in this context");let t=e.title;return t?(GE(t),l("Selected command",t)):l("No command selected",null)}},{intent:O.ExitCommandLine,mode:b.PALETTE,action:()=>(Jg(),l("Exiting palette",null))},{intent:O.Exit,mode:b.PALETTE,action:()=>(Jg(),l("Closed command palette",null))},{intent:O.NavPreviousItem,mode:b.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:O.NavNextItem,mode:b.PALETTE,action:()=>(U.navigateToNextItem(),l("Navigating to next item",null))},{intent:O.NavToPreviousContainer,mode:b.PALETTE,action:()=>(U.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:O.NavToNextContainer,mode:b.PALETTE,action:()=>(U.navigateToNextContainer(),l("Navigating to next container",null))}]});var eh,th=h(()=>{"use strict";ro();pn();pe();R();Io();ne();yt();ce();M();Vg();jn();Xg();Zg();ut();eh=[{intent:O.InitCommandLine,mode:b.DEFAULT,description:"[:] write command",action:()=>(N({mode:b.COMMAND_LINE}),te(""),l("Entering command line mode",null))},...Yg,...Qg,{intent:O.AddItem,mode:b.DEFAULT,description:"[n] new...",action:()=>(N({mode:b.COMMAND_LINE}),te(`${x.NEW} `),l("Adding new item",null))},{intent:O.Delete,mode:b.DEFAULT,description:"[d] delete",action:()=>(N({mode:b.COMMAND_LINE}),te(`${x.DELETE} `),l("Deleting item",null))},{intent:O.Confirm,mode:b.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=g();if(!ge(e?.id??"")?.length){let o=e?E.getAttachment(e.id):void 0;if(o)return zg(o);if(e?.title===ue.DESCRIPTION)return N({mode:b.COMMAND_LINE}),te(`${x.EDIT} description `),l("Propose command",!0);if(e?.title===ue.ASSIGNEES)return N({mode:b.COMMAND_LINE}),te(`${x.ASSIGN} `),l("Propose command",!0);if(e?.title===ue.TAGS)return N({mode:b.COMMAND_LINE}),te(`${x.TAG} `),l("Propose command",!0);if(t.title===ue.DESCRIPTION&&e?.context==="TEXT")return N({mode:b.COMMAND_LINE}),te(`${x.EDIT} description `),l("Propose command",!0)}return U.enterChildNode(),l("Entering context",null)}},{intent:O.Yank,mode:b.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=g(),t=e?.title===ue.DESCRIPTION?Ae.DESCRIPTION:e?.title===ue.TAGS?Ae.TAGS:e?.title===ue.ASSIGNEES?Ae.ASSIGNEES:Ae.REF,o=we(x.YANK).includes(t)?t:Ae.REF;return N({mode:b.COMMAND_LINE}),te(`${x.YANK} ${o}`),l("Propose command",!0)}},{intent:O.EditTitle,mode:b.DEFAULT,description:"[r] rename title",action:()=>(N({mode:b.COMMAND_LINE}),te(`${x.EDIT} title ${g().selectedNode?.title}`),l("Exiting context",null))},{intent:O.EditDescription,mode:b.DEFAULT,description:"[e] edit desc",action:()=>(N({mode:b.COMMAND_LINE}),te(`${x.EDIT} description `),l("Exiting context",null))},{intent:O.Exit,mode:b.DEFAULT,description:"[q] exit context",action:()=>(U.enterParentNode(),l("Exiting context",null))},{intent:O.NavPreviousItem,mode:b.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),l("Navigating to previous item",null))},{intent:O.NavNextItem,mode:b.DEFAULT,action:()=>(U.navigateToNextItem(),l("Navigating to next item",null))},{intent:O.NavToPreviousContainer,mode:b.DEFAULT,action:()=>(U.navigateToPreviousContainer(),l("Navigating to previous container",null))},{intent:O.NavToNextContainer,mode:b.DEFAULT,action:()=>(U.navigateToNextContainer(),l("Navigating to next container",null))}]});var zE,VE,nh,oh=h(()=>{"use strict";ce();zE=500,VE=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),nh=e=>{let t=VE(e);t&&Ii(n=>(n+t).slice(0,zE))}});var KE,YE,rh,sh=h(()=>{"use strict";oh();pe();R();ce();M();jn();rc();KE=[b.COMMAND_LINE,b.PALETTE],YE=e=>[{intent:O.MoveCursorLeft,mode:e,action:()=>(vd(-1),l("Moving cursor left",null))},{intent:O.MoveCursorRight,mode:e,action:()=>(vd(1),l("Moving cursor right",null))},{intent:O.MoveCursorLeftOfWord,mode:e,action:()=>(yd("left"),l("Moving cursor left of word",null))},{intent:O.MoveCursorRightOfWord,mode:e,action:()=>(yd("right"),l("Moving cursor right of word",null))},{intent:O.AutoCompleteCommand,mode:e,action:()=>(Ii((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:O.CaptureInput,mode:e,action:(t,{sequence:n})=>(nh(n??""),l("Capturing input",null))},{intent:O.EraseInput,mode:e,action:()=>(yp(),l("Erasing input",null))},{intent:O.EraseInputWord,mode:e,action:()=>(bp(),l("Erasing input word",null))}],rh=[{intent:O.Confirm,mode:b.COMMAND_LINE,action:()=>(Xt(),l("Executing command",null))},{intent:O.ViewHelp,mode:b.DEFAULT,action:()=>(N({mode:b.HELP}),l("Viewing help",null))},...KE.flatMap(YE),{intent:O.ExitCommandLine,mode:b.COMMAND_LINE,action:()=>(N({mode:b.DEFAULT}),l("Exiting command line",null))},{intent:O.GetLastCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Ep(),l("Getting last command from history",null))},{intent:O.GetNextCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Sp(),l("Getting next command from history",null))}]});var XE,ih,ah,dh=h(()=>{"use strict";XE=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},ih=({keys:e})=>e.length===1?0:1,ah=(e,t)=>{let n=new Set;for(let o of e)o.mode!==t||!o.description||n.add(o.description);return[...n].map(XE).filter(o=>o!==null).sort((o,r)=>ih(o)-ih(r))}});function ch(e,t,n){let o=t[e];if(!o)return a("buildBreadCrumb(): current node not found");let r=[],s=new Set,i=o;for(;i&&!s.has(i.id)&&(r.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let c=r[r.length-1];return!c||c.id!==n?a("buildBreadCrumb(): node is not connected to root"):(r.reverse(),l("Breadcrumb built",r))}var lh=h(()=>{"use strict";R()});var uh,mh=h(()=>{"use strict";uh=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 JE}from"react";function dc(e){let{contextNodeId:t,mode:n,rootNodeId:o,nodes:r,filters:s}=e;if(!t)return a("derive(): contextNodeId is missing");if(!o)return a("derive(): rootNode is missing");if(!r[o])return a("derive(): unable to find root node");let c=r[t];if(!c)return a("Unable to derive state, contextNode not found");let u=ch(t,r,o);if(d(u))return logger.error(u.message),u;let m=u.value,{context:p}=c,f=[...eh,...Hg[p]??[],...rh],y=ah(f,n),I=uh(f),S=ZE(r,s),A=S[t]?.[e.selectedIndex]??null;return l("Derived successfully",{...e,contextNode:c,breadCrumb:m,availableHints:y,availableActions:f,actionIndex:I,selectedNode:A,renderedChildrenIndex:S})}function Tr(e){sc=e;let t=Me(process.cwd()),n=!1;if(!d(t)){let s=Ot(t.value);if(d(s))return a(s.message);n=!0}let o={readOnly:!1,filters:[],tags:{},contributors:{},mode:b.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=dc(o);return d(r)?r:(Jt=r.value,ac(),l("State initialized",null))}function Ne(e){let t=g(),n=e(t);if(mo)return as=n,Jt={...t,...n},l("State updated",null);let o=dc(n);return d(o)?a(o.message??"Unable to update state"):(Jt=o.value,ac(),l("State updated",null))}function ru(e){if(mo)return l("Joined batch",e());mo=!0,as=null;let t=()=>{let n=as;if(mo=!1,as=null,n===null)return null;let o=dc(n);return d(o)?a(o.message??"Unable to update state"):(Jt=o.value,ac(),l("State updated",null))};try{let n=e(),o=t();return o&&d(o)?a(o.message):l("State updated",n)}finally{mo&&t()}}function po(e,t,n){if(!mo)return Ne(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let o=g(),r=o[e]??{};r[t]=n;let s={...o,[e]:r};return as=s,Jt={...o,...s},l("State updated",null)}var Jt,sc,ic,ac,QE,g,ze,mo,as,Wu,N,rt,ZE,se,bn,It,M=h(()=>{"use strict";Wg();th();sh();dh();nn();pe();R();ae();ja();lh();mh();ic=new Set,ac=()=>{for(let e of ic)e()},QE=e=>(ic.add(e),()=>ic.delete(e));g=()=>{if(!Jt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Jt},ze=()=>Jt?l("Retrieved state",Jt):a("State not initialized. Call initWorkspaceState() first.");mo=!1,as=null;Wu=()=>mo,N=e=>Ne(t=>({...t,...e}));rt=()=>JE(QE,g,g),ZE=Uu,se=e=>g()?.renderedChildrenIndex[e]??[],bn=()=>sc?Tr(sc):a("Cannot reset state: no initial workspace found"),It=()=>Jt!==void 0});var Ct,eS,On,E,ne=h(()=>{"use strict";Ft();K();R();M();yt();Ct=(e,t)=>{let{nodes:n}=g(),o=n[e];if(!o)return a("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 a(`No ancestor found for context: ${t}`)},eS=(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},On=(e,t)=>e?e.readonly?a({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:a("Node not found"),E={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.userId&&n.userId!==t)return a("Contributor is already linked to another user");let o={...n,userId:t},r=Ne(s=>({...s,contributors:{...s.contributors,[e]:o}}));return d(r)?a("Unable to link contributor to user"):l("Linked contributor to user",o)},deleteNode(e){Ne(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create comment, missing issue");if(!P(t))return a("Can only comment on issues");let n=po("comments",e.id,{...e,deleted:!1});return d(n)?a("Unable to create comment"):l("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return a("Unable to edit comment, missing comment");let o=this.getNode(n.issue);if(!o)return a("Unable to edit comment, missing issue");if(!P(o))return a("Can only edit issue comments");let r={...n,md:t,deleted:!1},s=po("comments",e,r);return d(s)?a("Unable to edit comment"):l("Edited comment",r)},deleteComment(e){let t=this.getComment(e);if(!t)return a("Unable to delete comment, missing comment");let n={...t,deleted:!0},o=po("comments",e,n);return d(o)?a("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 a("Unable to create attachment, missing issue");if(!P(t))return a("Can only attach to issues");let n=Ne(o=>({...o,attachments:{...o.attachments??{},[e.id]:{...e,deleted:!1}}}));return d(n)?a("Unable to create attachment"):l("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return a("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},o=Ne(r=>({...r,attachments:{...r.attachments??{},[e]:n}}));return d(o)?a("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 a("Edit target node not found");let r=On(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 a("Rename target node not found");let o=On(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 a("Node not found");if(!s)return a("Target parent not found");if(o===e)return a("Cannot move root node");if(e===t)return a("Cannot move node into itself");let i=On(r,"move");if(i)return i;if(eS(t,e))return a("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 a("Node not found");if(o===e)return a("Cannot delete root node");let s=On(r,"delete");if(s)return s;let i=new Set,c=m=>{let p=t[m];if(!(!p||i.has(m))){i.add(m);for(let f of ge(p.id))c(f.id)}};c(e);let u={...structuredClone(t)};for(let m of i){if(!u[m])return a("Unable to locate node to delete");u[m]={...u[m],isDeleted:!0}}return n?(N({nodes:u}),l("Successfully tomb stoned",r)):a("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return a("Contributor not found");let n={...t,name:bs,tombstoned:!0},o=Ne(r=>({...r,contributors:{...r.contributors,[e]:n}}));return d(o)?a("Unable to remove contributor"):l("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");if(n.tombstoned)return a("Cannot rename a removed contributor");let o={...n,name:t},r=Ne(s=>({...s,contributors:{...s.contributors,[e]:o}}));return d(r)?a("Unable to rename contributor"):l("Renamed contributor",o)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");let o={...n,name:t,tombstoned:!1},r=Ne(s=>({...s,contributors:{...s.contributors,[e]:o}}));return d(r)?a("Unable to restore contributor"):l("Restored contributor",o)},createContributor(e){let t=Ne(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return d(t)?a("Unable to create contributor"):l("Created contributor",e)},assign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return a("Unable to assign contributor, missing contributor");if(!o)return a("Unable to assign contributor, missing target");let r=On(o,"edit");if(r)return r;if(!P(o))return a("Target is not an issue");let s=o.props.assignees??[];if(s.includes(t))return a("Contributor already assigned");let i={...o,props:{...o.props,assignees:[...s,t]}};return this.updateNode(i),l("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),o=this.getNode(e);if(!n)return a("Unable to unassign, missing contributor");if(!o)return a("Unable to unassign, missing target");let r=On(o,"edit");if(r)return r;if(!P(o))return a("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 i={...o,props:{...o.props,assignees:s.filter(c=>c!==t)}};return this.updateNode(i),l("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),o=this.getNode(e);if(!n)return a("Unable to add tag, missing tag");if(!o)return a("Unable to add tag, missing target");let r=On(o,"edit");if(r)return r;if(!P(o))return a("Target is not an issue");let s=o.props.tags??[];if(s.includes(t))return a("Tag already assigned");let i={...o,props:{...o.props,tags:[...s,t]}};return this.updateNode(i),l("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),o=this.getNode(e);if(!n)return a("Unable to remove tag, missing tag");if(!o)return a("Unable to remove tag, missing target");let r=On(o,"edit");if(r)return r;if(!P(o))return a("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 i={...o,props:{...o.props,tags:s.filter(c=>c!==t)}};return this.updateNode(i),l("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return a("Tag not found");let n={...t,tombstoned:!0},o=Ne(r=>({...r,tags:{...r.tags,[e]:n}}));return d(o)?a("Unable to delete tag"):l("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return a("Tag not found");let o={...n,name:t,tombstoned:!1},r=Ne(s=>({...s,tags:{...s.tags,[e]:o}}));return d(r)?a("Unable to restore tag"):l("Restored tag",o)},createTag(e){let t=Ne(n=>({...n,tags:{...n.tags,[e.id]:e}}));return d(t)?a("Could not create tag"):l("Tag created",e)},createNode(e){let t=po("nodes",e.id,e);return d(t)?a("Unable to create node"):l("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},o=po("nodes",e,n);return d(o)?a(o.message):l("Locked node",n)},updateNode(e){let t=po("nodes",e.id,e);return d(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 Bn from"chalk";import ph from"string-width";var tS,nS,cc,oS,rS,fh,gh,sS,iS,aS,dS,cS,Zd,hh,ss=h(()=>{"use strict";Ke();ne();M();pt();Ti();tS=(e,t)=>e+" ".repeat(Math.max(0,t-ph(e))),nS=(e,t)=>" ".repeat(Math.max(0,t-ph(e)))+e,cc=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`),oS=(e,t)=>t?e<t?"up":e>t?"down":null:null,rS=(e,t)=>{let n=E.getNode(e.payload.parent),o=n?Bn.dim.bgBlack(` ${n.title} `):"unknown",r=t.at(-1);if(r&&"parent"in r&&"rank"in r&&r.parent===e.payload.parent){let s=oS(e.payload.rank,r.rank);if(s)return`Moved ${s} in ${o}`}return`Moved issue to ${o}`},fh=e=>`${Math.max(1,Math.round(e/1024))} KB`,gh=e=>E.getAttachment(e)?.name??"",sS=e=>{switch(e.action){case"add.issue.tag":{let t=g().tags[e.payload.tag];return t?Bn.bgHex(Te(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=g().tags[e.payload.tag];return t?Bn.bgHex(Te(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?Bn.hex(Te(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=g().contributors[e.payload.assignee];return t?Bn.hex(Te(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}" ${Bn.dim(`(${fh(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=gh(e.payload.id);return t?`"${t}"`:""}default:return""}},iS=e=>{let t=qo(He(e));return Bn.gray(nS(t,8))},aS=12,dS=e=>tS(`${e}`,aS),cS=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=E.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${fh(e.payload.bytes)})`;case"delete.issue.attachment":{let t=gh(e.payload.id);return t?`"${t}"`:""}default:return""}},Zd=e=>[cc(e.action),cS(e)].filter(Boolean).join(" "),hh=(e,t)=>{let n=iS(e.id),o=dS(e.userName),r=Bn.dim("\u203A"),s=e.action==="move.node"?rS(e,t):[cc(e.action),sS(e)].filter(Boolean).join(" ");return`${o} ${n} ${r} ${s}`}});var yh={};cr(yh,{areVirtualNodesEnabled:()=>_s,createOrUpdateVirtualField:()=>ds,createOrUpdateVirtualFieldList:()=>lc,materializeTicketVirtualNodes:()=>Fs,materializeVirtualNodes:()=>yS,setVirtualNodesEnabled:()=>vS});var lS,uS,mS,pS,fS,gS,ds,lc,Fs,hS,vh,vS,_s,yS,Na=h(()=>{"use strict";ss();K();R();Io();ne();Gn();M();yo();Lo();lS=e=>Le(e,"comments"),uS=e=>Le(e,"description"),mS=e=>Le(e,"assignees"),pS=e=>Le(e,"tags"),fS=e=>Le(e,"history"),gS=e=>Le(e,"attachments"),ds=({id:e,name:t,parentNodeId:n,rank:o,value:r,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let c=E.getNode(e);if(!c){let p=E.createNode({...Pe.field({id:e,name:t,parentNodeId:n,rank:o,props:{value:r},isVirtual:!0}),readonly:s,childRenderAxis:i});return d(p)?p:l("Virtual field created",void 0)}if(!at(c))return a(`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!==i))return l("Virtual field unchanged",void 0);let m=E.updateNode({...c,title:t,parentNodeId:n,rank:o,props:{...c.props,value:r},readonly:s,childRenderAxis:i});return d(m)?m:l("Virtual field updated",void 0)},lc=({id:e,name:t,parentNodeId:n,rank:o,readonly:r=!1,childRenderAxis:s="horizontal"})=>{let i=E.getNode(e);if(!i){let m=E.createNode({...Pe.fieldList({id:e,name:t,parentNodeId:n,rank:o,isVirtual:!0}),readonly:r,childRenderAxis:s});return d(m)?m:l("Virtual field list created",void 0)}if(!fr(i))return a(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==o||i.readonly!==r||i.childRenderAxis!==s))return l("Virtual field list unchanged",void 0);let u=E.updateNode({...i,title:t,parentNodeId:n,rank:o,readonly:r,childRenderAxis:s});return d(u)?u:l("Virtual field list updated",void 0)},Fs=e=>{let t=vt(_t/4n),n=vt(_t/2n),o=vt(_t*3n/4n),r=vt(_t*7n/8n),s=vt(_t*15n/16n),i=vt(_t*13n/16n);if(d(t))return t;if(d(n))return n;if(d(o))return o;if(d(r))return r;if(d(s))return s;if(d(i))return i;let c=ds({id:uS(e.id),name:ue.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(d(c))return c;let u=lc({id:mS(e.id),name:ue.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(d(u))return u;let m=lc({id:pS(e.id),name:ue.TAGS,parentNodeId:e.id,rank:o.value,readonly:!0});if(d(m))return m;let p=ds({id:lS(e.id),name:ue.COMMENTS,parentNodeId:e.id,rank:r.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(d(p))return p;let f=ds({id:gS(e.id),name:ue.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(d(f))return f;let y=ds({id:fS(e.id),name:ue.HISTORY,parentNodeId:e.id,rank:i.value,value:hS(e),readonly:!0,childRenderAxis:"vertical"});return d(y)?y:l("Ticket virtual nodes materialized",void 0)},hS=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=>hh(o,n.get(o.action)??[])).join(`
93
+ `)},vh=!0,vS=e=>{vh=e},_s=()=>vh,yS=()=>{let{nodes:e}=g();for(let t of Object.values(e)){if(!P(t))continue;let n=Fs(t);if(d(n))return n}return l("Virtual nodes materialized",void 0)}});var bS,xS,qi,uc=h(()=>{"use strict";Ke();bS=e=>{switch(e.action){case"add.issue":case"move.node":case"close.issue":case"reopen.issue":return e.payload.parent;default:return null}},xS=(e,t)=>{let n=[];for(let o of e){let r=bS(o);if(r===null||r===n.at(-1)?.laneId)continue;let s=$n(o);n.push({laneId:r,enteredAt:s===null?t:mr(s)})}return n},qi=(e,t)=>xS(e,t).at(-1)?.enteredAt??t});var bh=h(()=>{"use strict";R()});var IS,xh,mc=h(()=>{"use strict";Ke();St();kr();ss();R();pt();IS=e=>{let t=new Map,n=new Set,o=r=>{let s=new Set,i=r;for(;i&&!s.has(i);){if(n.has(i))return i;s.add(i),i=t.get(i)}return null};return e.map(r=>{let s=r.payload,i=s?.id;if(!i)return null;r.action==="add.board"&&n.add(i);let c=s.parent??s.issue;return c&&t.set(i,c),n.has(i)?i:o(i)})},xh=(e,t)=>{let n=IS(e);return e.filter((o,r)=>n[r]===t)}});var ES,Ih,Sh,SS,ls,cs,Eh,RS,Ko,NS,Rh,Yo=h(()=>{"use strict";Xe();ct();Je();Hd();St();ln();R();nn();gi();bh();ae();M();mc();ES=null,Ih=Promise.resolve(),Sh=e=>{let t=Ih.then(e,e);return Ih=t.then(()=>{},()=>{}),t},SS=e=>{let t=Me(e??process.cwd());return d(t)?a(t.message):l("Resolved Epiq repo root",t.value)},ls=()=>{if(!It())return{mode:"live",asOfTime:null};let{timeMode:e}=g();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:ES}},cs="",Eh="",RS=5e3,Ko=null,NS=async(e={})=>{let t=SS(e.repoRoot);if(d(t))return a(t.message);let n=Ot(t.value);if(d(n))return a(n.message);let o=e.start===void 0&&e.end===void 0;if(o&&Ko&&Ko.repoRoot===t.value&&Ko.stateBranch===n.value.stateBranch&&Date.now()-Ko.fetchedAt<RS)return l("Computed commit timeline",Ko.result);let r=await W({cwd:t.value,args:["log","--branches","--not",n.value.stateBranch,...e.start!==void 0?[`--since=@${Math.floor(e.start/1e3)}`]:[],...e.end!==void 0?[`--until=@${Math.floor(e.end/1e3)}`]:[],"--shortstat",`--format=${Eh}%H${cs}%at${cs}%an${cs}%s`]});if(d(r))return a(r.message);let s=r.value.stdout.split(Eh).filter(i=>i.trim().length>0).map(i=>{let[c,...u]=i.split(`
94
+ `),[m,p,f,...y]=(c??"").split(cs);if(!m||!p)return null;let I=u.join(" "),S=Number(/(\d+) insertion/.exec(I)?.[1]??0),A=Number(/(\d+) deletion/.exec(I)?.[1]??0);return{sha:m,time:Number(p)*1e3,author:f??"unknown",subject:y.join(cs),linesChanged:S+A,insertions:S,deletions:A}}).filter(i=>i!==null).filter(i=>(e.start===void 0||i.time>=e.start)&&(e.end===void 0||i.time<=e.end));return o&&(Ko={repoRoot:t.value,stateBranch:n.value.stateBranch,fetchedAt:Date.now(),result:s}),l("Computed commit timeline",s)},Rh=async e=>{let t=e.ref.trim();if(!t)return a("ref must not be empty");if(t.length!==7)return a(`"${t}" is ${t.length} characters; a ref is ${7}. Read it off the issue rather than slicing the id by hand.`);let n=await NS({repoRoot:e.repoRoot});if(d(n))return a(n.message);let o=`${t.toUpperCase()} `,r=c=>c.subject.toUpperCase().startsWith(o),s=n.value,i=[];for(let[c,u]of s.entries()){if(!r(u))continue;let m=s[c+1];i.push({...u,precedingSha:m&&r(m)?m.sha:null})}return l("Matched commits by ref",i)}});import CS from"node:fs";var fo,Gi,Y,Q,X,xn=h(()=>{"use strict";Xe();ct();bo();Or();zt();to();kr();ae();St();R();M();xt();Yo();fo=e=>{let t=Me(e??process.cwd());return d(t)?a(t.message):l("Resolved Epiq repo root",t.value)},Gi=null,Y=async(e,t)=>{let n=fo(e);if(d(n))return n;let o=be({repoRoot:n.value});if(d(o))return a(o.message);let r=Bt(n.value);if(d(r))return a(r.message);if(!(Gi!==null&&Gi.repoRoot===n.value&&Gi.stateBranchRoot===o.value&&CS.existsSync(Wn(o.value)))){let p=await Ga({repoRoot:n.value,stateBranchName:r.value});if(d(p))return a(p.message);let f=await oo({repoRoot:n.value,stateBranchRoot:o.value,stateBranchName:r.value});if(d(f))return a(f.message);Gi={repoRoot:n.value,stateBranchRoot:o.value}}if(t?.pull??!1){let p=await W({cwd:o.value,args:["pull","--ff-only"]});d(p)&&J.info(3,p.message)}let i={repoRoot:n.value,stateBranchRoot:o.value},c=Xn(o.value);if(hu(o.value)===c&&It()&&ls().mode==="live")return l("Booted Epiq state, unchanged",i);let u=Et(o.value);if(d(u))return a(u.message);let m=Wt(u.value.events,u.value.unreadable);return d(m)?a(m.message):(vu(o.value,c),l("Booted Epiq state",i))},Q=()=>{let e=zr();return d(e)?a(e.message):e.value.userId?e.value.userName?l("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):a("Unable to retrieve user name"):a("Unable to retrieve user id")},X=()=>{let e=ze();return d(e)?a(e.message):e}});var Xo,Nh,Jo,pc=h(()=>{"use strict";Ke();ne();pt();Xo=e=>(e.props.tags??[]).map(t=>E.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:Te(t.name)})),Nh=e=>E.getCommentsByIssue(e).sort((t,n)=>t.id<n.id?-1:t.id>n.id?1:0).map(t=>({id:t.id,author:E.getContributor(t.authorId)?.name??t.authorName??"Unknown",createdAt:He(t.id),body:t.md})),Jo=e=>(e.props.assignees??[]).map(t=>E.getContributor(t)).filter(t=>t!=null).map(({id:t,name:n})=>({id:t,name:n,color:Te(n)}))});import AS from"node:fs";import wS from"node:path";import{ulid as Ch}from"ulid";var TS,Ah,fc,gc=h(()=>{"use strict";zt();Se();K();R();dt();Po();xn();TS=e=>{if(e.filePath)try{return l("Read attachment file",{data:AS.readFileSync(e.filePath),name:e.name??wS.basename(e.filePath)})}catch(t){return a(`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"}):a("Provide either filePath or dataBase64")},Ah=()=>{let e=zr();return d(e)?gn:e.value.attachmentMaxKb??gn},fc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!P(r))return a("Attachment target must be an issue");if(r.readonly)return a("Cannot attach to readonly issue");let s=TS(e);if(d(s))return s;let i=Vm(t.value.stateBranchRoot,s.value.data,Ah());if(d(i))return i;let c=fe(s.value.name).trim()||"image",u=Ch(),m={id:Ch(),...n.value,action:"add.issue.attachment",payload:{id:u,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:c,bytes:i.value.bytes}},p=L([m],t.value.stateBranchRoot);if(d(p))return a(p.message);let f=Mo(i.value.hash,i.value.ext);return l("Added issue attachment",{id:u,issueId:e.issueId,fileName:f,bytes:i.value.bytes,markdown:cd(c,f)})}});var hc,xq,vc,wh=h(()=>{"use strict";zt();Ke();dn();K();R();ne();Ao();pt();uc();Je();dt();Po();xt();Yo();xn();pc();gc();ti();Ce();Lr();hc=async(e={})=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=X();return d(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})},xq=365*24*60*60*1e3,vc=async(e={})=>{Eo();let t=fo(e.repoRoot);if(d(t))return a("Sync failed");let n=Q();if(d(n))return n;let o=await ei({cwd:t.value,ownEventFileName:Zn(n.value)});return d(o)?(Ha(o.message),o):(no(),l("Synced",o.value))}});var us,Qo,yc,ms,bc=h(()=>{"use strict";K();R();Je();xn();us=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?l("Resolved targets",t):a("Provide issueId or issueIds")},Qo=(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):a(`${o}: ${t.failed.map(r=>`${r.ref} ${r.reason}`).join("; ")}`)},yc=(e,t)=>{let n={done:[],failed:[]};for(let o of e){let r=t(o);d(r)?n.failed.push({id:o,ref:j(o),reason:r.message}):n.done.push({id:o,ref:j(o)})}return n},ms=e=>{let t=X();if(d(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?a("Issue not found"):P(n)?n.readonly?a("Issue is readonly"):l("Found issue",n):a("Target must be an issue")}});import{ulid as At}from"ulid";async function Ic(e){let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=X();if(d(n))return n;let o=n.value.nodes,r=e.query?.trim().toLowerCase(),s=Object.values(o).filter(P).filter(c=>!c.isDeleted).filter(c=>e.includeClosed||c.parentNodeId!==he).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||Xo(c).some(u=>Th(u.name,e.tag))).filter(c=>!e.assignee||Jo(c).some(u=>Th(u.name,e.assignee))).filter(c=>!r||c.title.toLowerCase().includes(r)||(c.props.description??"").toLowerCase().includes(r)),i=c=>fe((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:fe(c.title),swimlane:i(c),tags:Xo(c).map(u=>u.name),assignees:Jo(c).map(u=>u.name)}))):l("Listed issues",s.map(c=>({id:c.id,ref:j(c.id),title:fe(c.title),description:c.props.description??"",createdAt:He(c.id),enteredLaneAt:qi(c.log??[],He(c.id)),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===he,readonly:!!c.readonly,tags:Xo(c),assignees:Jo(c)})))}async function Sc(e){let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=us(e);if(d(o))return o;let r=s=>kS(s,n.value,t.value.stateBranchRoot);return e.issueIds?Qo("Closed",yc(o.value,r)):r(o.value[0])}async function Nc(e){let t=fo(e.repoRoot);if(d(t))return t;let n=Q();if(d(n))return n;let o=be({repoRoot:t.value});if(d(o))return o;let r=Et(o.value);if(d(r))return r;let s=Wt(r.value.events,r.value.unreadable);if(d(s))return s;let i=us(e);if(d(i))return i;let c=u=>MS(u,e,n.value,o.value);return e.issueIds?Qo("Moved",yc(i.value,c)):c(i.value[0])}var xc,Th,Ec,kS,Rc,MS,Cc,Ac,kh=h(()=>{"use strict";Xe();Xd();Ke();to();St();Se();ec();dn();K();R();ne();yt();ss();pt();hn();uc();Je();dt();xn();pc();bc();xc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=X();if(d(n))return n;let o=e.idOrRef.trim();if(!o)return a("Provide an issue id or ref");let r=Object.values(n.value.nodes).filter(P).filter(u=>!u.isDeleted),s=r.find(u=>u.id===o),i=s?[s]:r.filter(u=>Cr(u.id,o));if(i.length===0)return a(`No issue matches "${o}"`);if(i.length>1)return a(`"${o}" matches ${i.length} issues: ${i.map(u=>`${j(u.id)} (${fe(u.title)})`).join(", ")}. Use a full ref or id.`);let c=i[0];return l("Found issue",{id:c.id,ref:j(c.id),title:fe(c.title),description:c.props.description??"",createdAt:He(c.id),enteredLaneAt:qi(c.log??[],He(c.id)),parentNodeId:c.parentNodeId,isClosed:c.parentNodeId===he,readonly:!!c.readonly,tags:Xo(c),assignees:Jo(c),comments:Nh(c.id)})},Th=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();Ec=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=fe(e.title);if(!r)return a("Issue title cannot be empty");let s=e.description??"",i=tt("Issue title",r,300)??tt("Issue description",s,2e4);if(i)return a(i);if((e.tagNames?.length??0)>20)return a(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return a(`Cannot set more than ${20} assignees at once`);let c=wn(e.parentId,n.value,t.value.stateBranchRoot);if(d(c))return c;let u=Fi({name:r,parent:e.parentId,user:n.value,rank:c.value});if(d(u))return u;let m=[...u.value],p=m.find(S=>S.action==="add.issue")?.payload.id;if(!p)return a("Unable to determine created issue id");s&&m.push({id:At(),...n.value,action:"edit.description",payload:{id:p,md:s}});let f=[];for(let S of e.tagNames??[]){let A=fe(S).trim();if(!A||f.some(_=>_.name===A))continue;let w=tt("Tag name",A,60);if(w)return a(w);let k=E.findTagByName(A),D=k?.id??At();k||m.push({id:At(),...n.value,action:"create.tag",payload:{id:D,name:A}}),m.push({id:At(),...n.value,action:"add.issue.tag",payload:{id:p,tag:D}}),f.push({id:D,name:A})}let y=[];for(let S of e.assigneeNames??[]){let A=fe(S).trim();if(!A||y.some(_=>_.name===A))continue;let w=tt("Assignee name",A,80);if(w)return a(w);let k=Object.values(o.value.contributors).find(_=>_.name===A),D=k?.id??At();k||m.push({id:At(),...n.value,action:"create.contributor",payload:{id:D,name:A}}),m.push({id:At(),...n.value,action:"add.issue.assignee",payload:{id:p,assignee:D}}),y.push({id:D,name:A})}let I=L(m,t.value.stateBranchRoot);return d(I)?a(I.message):l("Created issue",{id:p,ref:j(p),title:r,parentId:e.parentId,description:s,tags:f,assignees:y})},kS=(e,t,n)=>{let o=ms(e);if(d(o))return o;let r=jt(he,e,{at:"end"},t,n);if(d(r))return r;let s={id:At(),...t,action:"close.issue",payload:{id:e,parent:he,rank:r.value}},i=L([s],n);return d(i)?a(i.message):l("Closed issue",{id:e,ref:j(e)})};Rc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!P(r))return a("Target node is not issue");if(r.parentNodeId!==he)return a("Issue is not closed");let s=$i(r);if(!s)return a("Unable to resolve previous parent from issue history");if(s===he)return a("Previous parent resolves to closed swimlane");let i=o.value.nodes[s];if(!i)return a("Previous parent no longer exists");let c=jt(i.id,r.id,{at:"end"},n.value,t.value.stateBranchRoot);if(d(c))return c;let u={id:At(),...n.value,action:"reopen.issue",payload:{id:r.id,parent:i.id,rank:c.value}},m=L([u],t.value.stateBranchRoot);return d(m)?a(m.message):l("Reopened issue",{id:r.id,ref:j(r.id),parentId:i.id})},MS=(e,t,n,o)=>{let r=ms(e);if(d(r))return r;let s=jt(t.parentId,e,t.position??{at:"end"},n,o);if(d(s))return s;let i={id:At(),...n,action:"move.node",payload:{id:e,parent:t.parentId,rank:s.value}},c=L([i],o);return d(c)?a(c.message):l("Moved issue",{id:e,ref:j(e),parentId:t.parentId})};Cc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!P(r))return a("Edit target must be an issue");if(r.readonly)return a("Cannot edit readonly issue");let s=tt("Issue description",e.description,2e4);if(s)return a(s);let i=r.props.description??"";if(i===e.description)return l("No changes made",{id:e.issueId,ref:j(e.issueId),description:i});let c={id:At(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},u=L([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Edited issue description",{id:e.issueId,ref:j(e.issueId),description:e.description})},Ac=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!P(r))return a("Edit target must be an issue");if(r.readonly)return a("Cannot edit readonly issue");let s=fe(e.title);if(!s.trim())return a("Issue title cannot be empty");let i=tt("Issue title",s,300);if(i)return a(i);if(r.title===s)return l("No changes made",{id:e.issueId,ref:j(e.issueId),title:s});let c={id:At(),...n.value,action:"edit.title",payload:{id:e.issueId,name:s}},u=L([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Edited issue title",{id:e.issueId,ref:j(e.issueId),title:s})}});import{ulid as fs}from"ulid";var wc,Tc,kc,Mc,Pc,Lc,Mh=h(()=>{"use strict";Xe();to();St();Se();dn();K();R();yt();hn();Je();dt();Yo();xn();wc=async(e={})=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=X();if(d(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)},Tc=async(e={})=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=X();if(d(n))return n;let o=Object.values(n.value.nodes).filter(r=>r.context==="SWIMLANE"&&!r.isDeleted).filter(r=>!e.boardId||r.parentNodeId===e.boardId).map(r=>({id:r.id,title:r.title,boardId:r.parentNodeId,isClosed:r.id===he,readonly:!!r.readonly}));return l("Listed swimlanes",o)},kc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.boardId];if(!r)return a("Board not found");if(!gr(r))return a("Target parent must be a board");if(r.readonly)return a("Cannot add a swimlane to a readonly board");if(ls().mode!=="live")return a("Cannot add a swimlane while time travelling");let s=fe(e.title);if(!s.trim())return a("Swimlane title cannot be empty");let i=tt("Swimlane title",s,300);if(i)return a(i);let c=wn(e.boardId,n.value,t.value.stateBranchRoot);if(d(c))return c;let u=fs(),m={id:fs(),...n.value,action:"add.swimlane",payload:{id:u,name:s,parent:e.boardId,rank:c.value}},p=L([m],t.value.stateBranchRoot);return d(p)?a(p.message):l("Created swimlane",{id:u,ref:j(u),title:s,boardId:e.boardId})},Mc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.swimlaneId];if(!r)return a("Swimlane not found");if(!Sn(r))return a("Edit target must be a swimlane");if(r.readonly)return a("Cannot edit readonly swimlane");let s=fe(e.title);if(!s.trim())return a("Swimlane title cannot be empty");let i=tt("Swimlane title",s,300);if(i)return a(i);if(r.title===s)return l("No changes made",{id:e.swimlaneId,ref:j(e.swimlaneId),title:s});let c={id:fs(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:s}},u=L([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Edited swimlane title",{id:e.swimlaneId,ref:j(e.swimlaneId),title:s})},Pc=async e=>{let t=fo(e.repoRoot);if(d(t))return t;let n=Q();if(d(n))return n;let o=be({repoRoot:t.value});if(d(o))return o;let r=Et(o.value);if(d(r))return r;let s=Wt(r.value.events,r.value.unreadable);if(d(s))return s;let i=jt(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,o.value);if(d(i))return i;let c={id:fs(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:i.value}},u=L([c],o.value);return d(u)?a(u.message):l("Moved swimlane",{id:e.swimlaneId,ref:j(e.swimlaneId),boardId:e.boardId})},Lc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.swimlaneId];if(!r)return a("Swimlane not found");if(!Sn(r))return a("Delete target must be a swimlane");let s={id:fs(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},i=L([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Deleted swimlane",{id:e.swimlaneId,ref:j(e.swimlaneId)})}});import{ulid as tr}from"ulid";async function Dc(e){let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=us(e);if(d(o))return o;let r=fe(e.tagName).trim();if(!r)return a("Tag name cannot be empty");let s=tt("Tag name",r,60);if(s)return a(s);let i={done:[],failed:[]};for(let I of o.value){let S=ms(I);d(S)?i.failed.push({id:I,ref:j(I),reason:S.message}):i.done.push({id:I,ref:j(I)})}if(!e.issueIds&&i.failed[0])return a(i.failed[0].reason);if(i.done.length===0)return a(Qo("Tagged",i).message);let c=E.findTagByName(r),u=c?.id??tr(),m=[...c?[]:[{id:tr(),...n.value,action:"create.tag",payload:{id:u,name:r}}],...i.done.map(({id:I})=>({id:tr(),...n.value,action:"add.issue.tag",payload:{id:I,tag:u}}))],p=L(m,t.value.stateBranchRoot);if(d(p))return a(p.message);let f={id:u,name:r};if(!e.issueIds)return l("Added issue tag",{...i.done[0],tag:f});let y=Qo("Tagged",i);return d(y)?y:l(y.message,{...y.value,tag:f})}var Fc,_c,Oc,Ph=h(()=>{"use strict";Se();K();R();ne();hn();Je();dt();xn();bc();Fc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.tags[e.tagId];if(!r)return a("Tag not found");if(r.tombstoned)return a("Tag is already deleted");let s=[{id:tr(),...n.value,action:"tombstone.tag",payload:{id:e.tagId}}],i=L(s,t.value.stateBranchRoot);return d(i)?a(i.message):l("Deleted tag",{id:r.id,name:r.name})},_c=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.tags[e.tagId];if(!r)return a("Tag not found");if(!r.tombstoned)return a("Tag is not deleted");if(E.findTagByName(r.name))return a(`Cannot restore: another tag is already named "${r.name}"`);let s=[{id:tr(),...n.value,action:"restore.tag",payload:{id:e.tagId,name:r.name}}],i=L(s,t.value.stateBranchRoot);return d(i)?a(i.message):l("Restored tag",{id:r.id,name:r.name})},Oc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!P(r))return a("Untag target must be an issue");if(r.readonly)return a("Cannot untag readonly issue");if(!o.value.tags[e.tagId])return a("Tag not found");let s={id:tr(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=L([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue tag",{id:e.issueId,ref:j(e.issueId),tagId:e.tagId})}});import{ulid as In}from"ulid";var PS,Lh,Bc,Dh,Uc,$c,LS,jc,Hc,Wc,Fh=h(()=>{"use strict";R();M();Ft();Un();St();Se();mc();K();pt();hn();Je();dt();xn();PS=()=>{let e=ze(),t=d(e)?[]:e.value.eventLog??[],n=new Map;for(let o of t)o.userId&&o.userName&&n.set(o.userId,o.userName);return n},Lh=(e,t)=>{let n=new Map(e);for(let o of Object.values(t))n.set(o.id,o.name);return n},Bc=async e=>{let t=na(e.name,"name");if(d(t))return a(t.message);let n=await Y(e.repoRoot,{pull:!1});if(d(n))return n;let o=Q();if(d(o))return o;let r=X();if(d(r))return r;let s=o.value,i=!!r.value.contributors[s.userId];if(!i){let c=L([{id:In(),...s,action:"create.contributor",payload:{id:s.userId,name:s.userName}}],n.value.stateBranchRoot);if(d(c))return a(c.message)}return l(`Assumed ${s.userName}`,{...s,registered:!i})},Dh=async(e,t)=>{let n=Fa(e);if(d(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}},Uc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!P(r))return a("Assign target must be an issue");if(r.readonly)return a("Cannot assign readonly issue");let s=e.self?n.value.userId:e.assigneeId;if(s){let w=o.value.contributors[s],k=w?void 0:await Dh(t.value.stateBranchRoot,s);if(!w&&!k)return a("Unknown assignee id");let D=w??k,_=[...w?[]:[{id:In(),...n.value,action:"create.contributor",payload:{id:D.id,name:D.name}}],{id:In(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:D.id}}],H=L(_,t.value.stateBranchRoot);return d(H)?a(H.message):l("Added issue assignee",{id:e.issueId,ref:j(e.issueId),assignee:{id:D.id,name:D.name}})}let i=fe(e.assigneeName??"").trim();if(!i)return a("Provide assigneeId, self or assigneeName");let c=tt("Assignee name",i,80);if(c)return a(c);let m=[...Lh(PS(),o.value.contributors).entries()].filter(([,w])=>w===i);if(m.length>1)return a(`"${i}" matches ${m.length} contributors (${m.map(([w])=>w).join(", ")}). Assign by assigneeId to choose.`);let p=m[0];if(!p&&!e.createUnlinked)return a(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[f=In(),y=i]=p??[],S=[...!!o.value.contributors[f]?[]:[{id:In(),...n.value,action:"create.contributor",payload:{id:f,name:y}}],{id:In(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:f}}],A=L(S,t.value.stateBranchRoot);return d(A)?a(A.message):l("Added issue assignee",{id:e.issueId,ref:j(e.issueId),assignee:{id:f,name:y}})},$c=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;if(!o.value.contributors[e.contributorId])return a("Contributor not found");if(await Dh(t.value.stateBranchRoot,e.contributorId))return a("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let i=[{id:In(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],c=L(i,t.value.stateBranchRoot);return d(c)?a(c.message):l("Tombstoned contributor",{id:e.contributorId,name:bs})},LS=async(e,t)=>{let n=Jn(e);if(d(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},jc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.contributors[e.contributorId];if(!r)return a("Contributor not found");if(!r.tombstoned)return a("Contributor is not tombstoned");let s=await LS(t.value.stateBranchRoot,e.contributorId);if(!s)return a("Cannot restore this contributor \u2014 no original name found in the event log");let i=[{id:In(),...n.value,action:"restore.contributor",payload:{id:e.contributorId,name:s}}],c=L(i,t.value.stateBranchRoot);return d(c)?a(c.message):l("Restored contributor",{id:e.contributorId,name:s})},Hc=async(e={})=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=Jn(t.value.stateBranchRoot);if(d(r))return a(r.message);let s=e.boardId?xh(r.value,e.boardId):r.value,i=new Map,c=new Set,u=new Set,m=Fa(t.value.stateBranchRoot);if(d(m))return a(m.message);for(let I of m.value)I.userId&&u.add(I.userId);for(let I of s)I.userId&&(i.set(I.userId,I.userName??""),c.add(I.userId));let p=o.value.contributors,y=[...Lh(i,p).entries()].map(([I,S])=>({id:I,name:S,color:Te(S),isSelf:I===n.value.userId,isExternal:!c.has(I),isRemoved:p[I]?.tombstoned===!0,hasAuthoredAnywhere:u.has(I)}));return l("Listed board contributors",y)},Wc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!P(r))return a("Unassign target must be an issue");if(r.readonly)return a("Cannot unassign readonly issue");if(!o.value.contributors[e.assigneeId])return a("Assignee not found");let s={id:In(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=L([s],t.value.stateBranchRoot);return d(i)?a(i.message):l("Removed issue assignee",{id:e.issueId,ref:j(e.issueId),assigneeId:e.assigneeId})}});import{ulid as Ki}from"ulid";var qc,Gc,zc,_h=h(()=>{"use strict";Se();K();R();hn();xn();qc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.nodes[e.issueId];if(!r)return a("Issue not found");if(!P(r))return a("Comment target must be an issue");if(r.readonly)return a("Cannot comment on readonly issue");let s=e.body.trim();if(!s)return a("Comment cannot be empty");if(s.length>4e3)return a(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i=Ki(),c={id:Ki(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},u=L([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Added issue comment",{id:i,issueId:e.issueId,body:s})},Gc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!r)return a("Unable to resolve comment");if(r.payload.author!==n.value.userId)return a("You can only delete your own comments");let s=o.value.nodes[r.payload.issue];if(!s)return a("Issue not found");if(!P(s))return a("Comment target must be an issue");if(s.readonly)return a("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:Ki(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:r.payload.issue}},u=L([c],t.value.stateBranchRoot);return d(u)?a(u.message):l("Deleted issue comment",{id:e.commentId,issueId:r.payload.issue})},zc=async e=>{let t=await Y(e.repoRoot,{pull:!1});if(d(t))return t;let n=Q();if(d(n))return n;let o=X();if(d(o))return o;let r=o.value.eventLog.find(p=>p.action==="add.issue.comment"&&p.payload.id===e.commentId);if(!r)return a("Unable to resolve comment");if(r.payload.author!==n.value.userId)return a("You can only edit your own comments");let s=o.value.nodes[r.payload.issue];if(!s)return a("Issue not found");if(!P(s))return a("Comment target must be an issue");if(s.readonly)return a("Cannot edit comment on readonly issue");if(o.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return a("Comment was deleted");let c=e.body.trim();if(!c)return a("Comment cannot be empty");if(c.length>4e3)return a(`Comment cannot exceed ${4e3} characters (got ${c.length})`);let u={id:Ki(),...n.value,action:"edit.issue.comment",payload:{id:e.commentId,issue:r.payload.issue,md:c}},m=L([u],t.value.stateBranchRoot);return d(m)?a(m.message):l("Edited issue comment",{id:e.commentId,issueId:r.payload.issue,body:c})}});var Oh=h(()=>{"use strict";wh();kh();Mh();Ph();Fh();_h();gc()});import{ulid as DS}from"ulid";var Bh,Uh,$h,jh=h(()=>{"use strict";Un();Ao();zt();R();Gd();xt();Bh=[{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)"}],Uh=e=>e.trim().toLowerCase(),$h=async(e={})=>{let t=ko();if(d(t))return a(t.message);let n=t.value,o=e.userName?.trim(),r=(process.env[gt]??"").trim();if(o&&r&&Uh(o)===Uh(r))return a(`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},i={userName:n.userName?.trim()||void 0,preferredEditor:n.preferredEditor?.trim()||void 0,autoSync:typeof n.autoSync=="boolean"?n.autoSync:void 0};for(let w of Bh){let k=s[w.name],D=i[w.name];if(!(k===void 0||D===void 0||k===D))return a(`This machine is already set up with ${w.name} ${JSON.stringify(D)}; epiq_project_init does not change it. Call again without ${w.name}, or let the user change it in the TUI with :config.`)}let c={};if(s.userName&&!i.userName&&(c.userName=s.userName),s.preferredEditor&&!i.preferredEditor&&(c.preferredEditor=s.preferredEditor),s.autoSync!==void 0&&i.autoSync===void 0&&(c.autoSync=s.autoSync),(c.userName||i.userName)&&!n.userId&&(c.userId=DS()),Object.keys(c).length>0){let w=et(c);if(d(w))return a(w.message)}let u={...n,...c},m=Bh.filter(w=>{let k=u[w.name];return typeof k=="boolean"?!1:!k?.trim()});if(m.length>0){let w=m.map(k=>`${k.name} (${k.question})`).join("; ");return a(`Setup incomplete. Ask the user for: ${w}. 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 a("Missing Epiq user id");let f=await Li({cwd:e.repoRoot??process.cwd(),user:p});if(d(f))return f;let{defaultEvents:y,...I}=f.value,S=jr({root:I.repoRoot});d(S)&&J.info(S.message);let A=I.warnings.length===0?"Project initialized":`Project initialized, with warnings: ${I.warnings.join(" ")}`;return l(A,{...I,user:p})}});var Zt,Yi=h(()=>{"use strict";Zt=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""})});var FS,Hh,Wh=h(()=>{"use strict";Yi();FS=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},Hh=({commits:e,patch:t})=>{let n=e.map(i=>i.time),r=t.files.map(i=>({...Zt(i),changed:i.addedCount+i.removed})).reduce((i,c)=>i===null||c.changed>i.changed?c:i,null),s=t.insertions+t.deletions;return{commits:e.length,authors:[...new Set(e.map(i=>i.author))].sort(),firstCommitAt:n.length?Math.min(...n):null,lastCommitAt:n.length?Math.max(...n):null,files:t.files.length,filesAdded:t.files.filter(i=>i.status==="added").length,filesModified:t.files.filter(i=>i.status==="modified").length,filesDeleted:t.files.filter(i=>i.status==="deleted").length,binaryFiles:t.files.filter(i=>i.binary).length,directories:new Set(t.files.map(i=>FS(i.path))).size,insertions:t.insertions,deletions:t.deletions,net:t.insertions-t.deletions,largestFile:r,concentration:r&&s>0?r.changed/s:0,selfChurn:t.selfChurn,truncated:t.truncated}}});var Oe,wt,Vc,nr,_S,$,Xi,Ji,qh,OS,Gh,go,gs,BS,US,or,$S,jS,HS,Lt,zh,Vh,Kh,WS,qS,Yh,Xh,rr=h(()=>{"use strict";Oe={line:["//"],block:[["/*","*/"]]},wt={line:["#"],block:[]},Vc={line:["--"],block:[]},nr={line:[],block:[["<!--","-->"]]},_S={line:[],block:[]},$=(e,t)=>({name:e,comment:t}),Xi=$("TypeScript",Oe),Ji=$("JavaScript",Oe),qh={ts:Xi,tsx:Xi,mts:Xi,cts:Xi,js:Ji,jsx:Ji,mjs:Ji,cjs:Ji,py:$("Python",{line:["#"],block:[['"""','"""']]}),rb:$("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:$("Go",Oe),rs:$("Rust",Oe),java:$("Java",Oe),kt:$("Kotlin",Oe),swift:$("Swift",Oe),c:$("C",Oe),h:$("C",Oe),cc:$("C++",Oe),cpp:$("C++",Oe),hpp:$("C++",Oe),cs:$("C#",Oe),php:$("PHP",Oe),scala:$("Scala",Oe),dart:$("Dart",Oe),lua:$("Lua",Vc),hs:$("Haskell",Vc),sql:$("SQL",Vc),ex:$("Elixir",wt),exs:$("Elixir",wt),pl:$("Perl",wt),r:$("R",wt),jl:$("Julia",wt),sh:$("Shell",wt),bash:$("Shell",wt),zsh:$("Shell",wt),vue:$("Vue",nr),svelte:$("Svelte",nr),html:$("HTML",nr),xml:$("XML",nr),md:$("Markdown",nr),mdx:$("Markdown",nr),css:$("CSS",{line:[],block:[["/*","*/"]]}),scss:$("CSS",Oe),less:$("CSS",Oe),yml:$("YAML",wt),yaml:$("YAML",wt),toml:$("TOML",wt),ini:$("INI",wt),json:$("JSON",_S)},OS="Other",Gh=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},go=e=>qh[Gh(e)]?.name??OS,gs=e=>qh[Gh(e)]?.comment??null,BS=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],US=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,or=e=>US.test(e)||BS.some(t=>t.test(e)),$S=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,jS=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,HS=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,Lt=e=>$S.test(e)||jS.test(e)||HS.test(e),zh=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),Vh=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),Kh=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),WS=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,qS=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,Yh=e=>WS.test(e),Xh=e=>qS.test(e)});var Jh,GS,Kc,zS,Qh,Yc=h(()=>{"use strict";rr();Jh=/\b(TODO|FIXME|HACK|XXX)\b/,GS=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,Kc=(e,t)=>{let n=e.trim();return n===""?"blank":t&&(t.line.some(o=>n.startsWith(o))||t.block.some(([o])=>n.startsWith(o))||t.block.some(([o])=>o==="/*")&&(n.startsWith("*")||n.startsWith("*/")))?"comment":"code"},zS=(e,t)=>{let n=e.trim();for(let o of[...t.line,...t.block.flat(),"*"])if(n.startsWith(o)){n=n.slice(o.length).trim();break}return n},Qh=({patch:e,repoShareByLanguage:t})=>{let n=new Map,o=0,r=0,s=0,i=0,c=0,u=0;for(let p of e.files){if(p.binary||Lt(p.path))continue;let f=gs(p.path);if(!f||f.line.length===0&&f.block.length===0)continue;let y=go(p.path),I=n.get(y)??{comment:0,code:0};for(let{text:S}of p.added){let A=Kc(S,f);if(Jh.test(S)&&i++,A==="blank"){s++;continue}if(A==="comment"){o++,I.comment++,f&&GS.test(zS(S,f))&&u++;continue}r++,I.code++}for(let{text:S}of p.removedLines)Jh.test(S)&&c++;n.set(y,I)}let m=o+r;return{byLanguage:[...n.entries()].map(([p,f])=>({name:p,commentLines:f.comment,codeLines:f.code,share:f.comment+f.code===0?0:f.comment/(f.comment+f.code),repoShare:t?.get(p)??null})).sort((p,f)=>f.commentLines+f.codeLines-(p.commentLines+p.codeLines)),commentLines:o,codeLines:r,blankLines:s,share:m===0?0:o/m,todoLinesAdded:i,todoLinesRemoved:c,commentedOutCodeLines:u}}});var VS,Qi,Xc,KS,YS,XS,Zh,ev=h(()=>{"use strict";rr();Yi();VS=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,Qi=6,Xc=10,KS=e=>{let t=0;for(let n of e){if(n.trim()===""||n.startsWith(" "))continue;let o=n.length-n.trimStart().length;o>0&&(t===0||o<t)&&(t=o)}return Math.min(Math.max(t,2),8)},YS=(e,t)=>{let n=e.length-e.trimStart().length;if(n===0)return 0;let o=e.slice(0,n).split(" ").length-1;return o>0?o:Math.floor(n/t)},XS=e=>{if(e.length<Qi*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let o=0;o+Qi<=e.length;o++){let r=e.slice(o,o+Qi);if(r.some(c=>c.text.length<3))continue;let s=r.map(c=>c.text).join(`
95
+ `),i=t.get(s);if(i===void 0){t.set(s,{...r[0],at:o});continue}if(i.file!==r[0]?.file)for(let c=0;c<Qi;c++)n[i.at+c]=!0,n[o+c]=!0}return n.filter(Boolean).length},Zh=({patch:e})=>{let t=[],n=[],o=[],r=!1,s=0,i=0,c=null,u=[];for(let[m,p]of e.files.entries()){if(Lt(p.path)&&t.push(Zt(p)),zh(p.path)&&n.push(Zt(p)),Vh(p.path)&&o.push(Zt(p)),Kh(p.path)&&(r=!0),p.binary||Lt(p.path))continue;let f=p.added.map(S=>S.text),y=KS(f),I=p.status!=="deleted";for(let S of f){VS.test(S)&&s++;let A=YS(S,y);A>i&&(i=A,c=Zt(p)),I&&u.push({text:S.trim(),file:m})}u.push({text:" ",file:m})}return{generatedPaths:t.slice(0,Xc),dependencyManifests:n.slice(0,Xc),buildOrCiPaths:o.slice(0,Xc),docsTouched:r,debugPrintLinesAdded:s,maxIndentLevels:i,deepestFile:c,duplicatedLines:XS(u)}}});var tv,nv=h(()=>{"use strict";rr();tv=({patch:e,languagesBefore:t})=>{let n=new Map,o=0;for(let i of e.files){if(i.binary)continue;let c=i.addedCount+i.removed;if(Lt(i.path)){o+=c;continue}let u=go(i.path),m=n.get(u)??{name:u,added:0,removed:0,addedInTests:0,share:0};m.added+=i.addedCount,m.removed+=i.removed,or(i.path)&&(m.addedInTests+=i.addedCount),n.set(u,m)}let r=[...n.values()].reduce((i,c)=>i+c.added+c.removed,0),s=[...n.values()].map(i=>({...i,share:r===0?0:(i.added+i.removed)/r})).sort((i,c)=>c.added+c.removed-(i.added+i.removed));return{languages:s,introduced:t===null?[]:s.filter(i=>!t.has(i.name)).map(i=>i.name),generatedLines:o}}});var JS,Jc,QS,ov,ZS,Qc,eR,tR,rv,sv,nR,oR,rR,iv,av=h(()=>{"use strict";ct();R();JS=200,Jc=2e5,QS=5e4,ov=25,ZS=64*1024*1024,Qc="",eR=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/,tR=/^diff --git a\/(.+) b\/\1$/,rv=(e,t)=>e==="/dev/null"?null:e.startsWith(t)?e.slice(2):e,sv=(e,t)=>e===null?"added":t===null?"deleted":"modified",nR=()=>({byPath:new Map,insertions:0,deletions:0,selfChurn:0,retainedLines:0}),oR=(e,t)=>{let n=e.byPath,o="",r=null,s=null,i=null,c=!1,u=0,m=(f,y)=>y==="modified"&&f==="added"?"added":y,p=(f,y)=>{let I=n.get(f);if(I)return I.entry.status=m(I.entry.status,y),I.entry.shas.includes(o)||I.entry.shas.push(o),I;let A={entry:{path:f,status:y,binary:!1,added:[],addedCount:0,removed:0,removedLines:[],shas:[o]},pendingByText:new Map};return n.set(f,A),A};for(let f of t.split(`
96
+ `)){if(f.startsWith(Qc)){o=f.slice(Qc.length).trim(),r=null,s=null,i=null,c=!1;continue}if(f.startsWith("diff --git ")){r=null,i=null,c=!0,s=tR.exec(f)?.[1]??null;continue}if(c&&f.startsWith("Binary files ")&&s){let[,I=""]=/^Binary files (.*) differ$/.exec(f)??[],[S="",A=""]=I.split(" and ");r=p(s,sv(S==="/dev/null"?null:S,A==="/dev/null"?null:A)),r.entry.binary=!0;continue}if(c&&f.startsWith("--- ")){i=rv(f.slice(4),"a/");continue}if(c&&f.startsWith("+++ ")){let I=rv(f.slice(4),"b/"),S=I??i??s;S&&(r=p(S,sv(i,I)));continue}let y=eR.exec(f);if(y){u=Number(y[1]),c=!1;continue}if(r){if(f.startsWith("+")){let I=f.slice(1);e.insertions++,r.entry.addedCount++,e.retainedLines<Jc&&(r.entry.added.push({sha:o,line:u,text:I}),e.retainedLines++),r.pendingByText.size<QS&&r.pendingByText.set(I,(r.pendingByText.get(I)??0)+1),u++;continue}if(f.startsWith("-")){let I=f.slice(1);e.deletions++,r.entry.removed++,e.retainedLines<Jc&&(r.entry.removedLines.push({sha:o,line:0,text:I}),e.retainedLines++);let S=r.pendingByText.get(I)??0;S>0&&I.trim().length>2&&(e.selfChurn++,r.pendingByText.set(I,S-1))}}}},rR=e=>({files:[...e.byPath.values()].map(t=>t.entry),insertions:e.insertions,deletions:e.deletions,selfChurn:e.selfChurn,retainedLines:e.retainedLines}),iv=async({repoRoot:e,shas:t})=>{if(t.length===0)return l("No commits to scan",{files:[],insertions:0,deletions:0,selfChurn:0,scannedCommits:0,truncated:!1});let n=t.slice(0,JS).reverse(),o=nR(),r=0,s=0,i=!1;for(let u=0;u<n.length;u+=ov){let m=n.slice(u,u+ov),p=await W({cwd:e,args:["-c","core.quotePath=false","show","--unified=0","--no-renames","--no-color",`--format=${Qc}%H`,...m]});if(d(p))return a(p.message);if(oR(o,p.value.stdout),r+=p.value.stdout.length,s+=m.length,r>ZS){i=!0;break}}let c=rR(o);return l("Scanned ticket patch",{files:c.files,insertions:c.insertions,deletions:c.deletions,selfChurn:c.selfChurn,scannedCommits:s,truncated:i||s<t.length||c.retainedLines>=Jc})}});var sR,iR,dv,cv=h(()=>{"use strict";ct();R();Yc();rr();sR=40,iR=/^\d{6} blob ([0-9a-f]{40})\t(.+)$/,dv=async({repoRoot:e,sha:t})=>{let n=await Be({cwd:e,args:["-c","core.quotePath=false","ls-tree","-r",`${t}~1`]});if(n.exitCode!==0)return null;let o=new Set,r=new Map;for(let p of n.stdout.split(`
97
+ `)){let f=iR.exec(p);if(!f)continue;let[,y="",I=""]=f;if(Lt(I))continue;let S=go(I);if(o.add(S),or(I)||!gs(I))continue;let A=r.get(S)??[];A.length<sR&&(A.push({blob:y,path:I}),r.set(S,A))}let s=[...r.values()].flat(),i=await la(s.map(p=>p.blob),e);if(d(i))return{languages:o,commentShareByLanguage:new Map};let c=i.value,u=new Map;for(let{blob:p,path:f}of s){let y=c.get(p);if(y===void 0)continue;let I=gs(f),S=go(f),A=u.get(S)??{comment:0,code:0};for(let w of y.split(`
98
+ `)){let k=Kc(w,I);k==="comment"&&A.comment++,k==="code"&&A.code++}u.set(S,A)}let m=new Map;for(let[p,f]of u){let y=f.comment+f.code;y>0&&m.set(p,f.comment/y)}return{languages:o,commentShareByLanguage:m}}});var lv,uv=h(()=>{"use strict";rr();Yi();lv=({patch:e})=>{let t=0,n=0,o=[],r=[],s=0,i=0;for(let c of e.files)if(!(c.binary||Lt(c.path))&&or(c.path)){t+=c.addedCount,n+=c.removed,c.status==="added"&&o.push(Zt(c)),c.status==="deleted"&&r.push(Zt(c));for(let{text:u}of c.added)Yh(u)&&s++,Xh(u)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:o,deletedTestFiles:r,skippedTestLinesAdded:s,focusedTestLinesAdded:i}}});var aR,mv,pv=h(()=>{"use strict";R();Wh();Yc();ev();nv();av();cv();uv();aR=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,mv=async({repoRoot:e,ref:t,commits:n})=>{let o=await iv({repoRoot:e,shas:n.map(c=>c.sha)});if(d(o))return a(o.message);let r=o.value,s=aR(n),i=s?await dv({repoRoot:e,sha:s}):null;return l("Derived issue stats",{ref:t,shape:Hh({commits:n,patch:r}),languages:tv({patch:r,languagesBefore:i?.languages??null}),tests:lv({patch:r}),comments:Qh({patch:r,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:Zh({patch:r})})}});var dR,hs,cR,fv,gv=h(()=>{"use strict";R();pv();Je();ae();Yo();dR=32,hs=new Map,cR=(e,t)=>{if(hs.set(e,t),hs.size>dR){let n=hs.keys().next();n.done||hs.delete(n.value)}return t},fv=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return a("idOrRef must not be empty");let n=t.length>7?j(t):t.toUpperCase(),o=Me(e.repoRoot??process.cwd());if(d(o))return a(o.message);let r=o.value,s=await Rh({repoRoot:r,ref:n});if(d(s))return a(s.message);let i=s.value.map(p=>({sha:p.sha,time:p.time,author:p.author,subject:p.subject})),c=[r,n,i.map(p=>p.sha).join(",")].join(" "),u=hs.get(c);if(u)return l("Derived issue stats",u);let m=await mv({repoRoot:r,ref:n,commits:i});return d(m)?a(m.message):l("Derived issue stats",cR(c,m.value))}});var sr,Zc,hv=h(()=>{"use strict";sr=".claude/skills/epiq/SKILL.md",Zc="---\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 Zi from"node:fs";import vv from"node:path";var yv,bv=h(()=>{"use strict";Xe();R();hv();yv=async(e={})=>{let t=await lt(e.repoRoot??process.cwd());if(d(t))return a(t.message);let n=vv.join(t.value,sr);if(Zi.existsSync(n)){if(Zi.readFileSync(n,"utf8")===Zc)return l("Skill already installed and up to date",{path:n,written:!1});if(!e.force)return a(`${sr} already exists and differs from the bundled skill. Pass force:true to overwrite it.`)}try{Zi.mkdirSync(vv.dirname(n),{recursive:!0}),Zi.writeFileSync(n,Zc,"utf8")}catch(o){return a(o instanceof Error?`Failed to write ${sr}: ${o.message}`:`Failed to write ${sr}`)}return l(`Installed skill at ${sr}`,{path:n,written:!0})}});var Iv={};cr(Iv,{createMcpServer:()=>xv,resultJson:()=>el,startMcpServer:()=>pR});import{McpServer as uR}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as mR}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as v}from"zod";var el,Z,xv,pR,Ev=h(()=>{"use strict";R();hn();Oh();jh();gv();bv();Yo();el=e=>({isError:d(e),content:[{type:"text",text:JSON.stringify(e,null,2)}]}),Z=e=>t=>Sh(async()=>el(await e(t))),xv=()=>{let e=new uR({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()})},Z(hc)),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()})},Z(Ic)),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()})},Z(xc)),e.registerTool("epiq_issue_stats",{description:"Code stats for one issue, derived from the commits whose subject carries its ref: how big the change is, how it is spread, and how much of it the ticket spent rewriting its own work. Reads git only \u2014 it never touches the board \u2014 so it is safe to call while other work is in flight. No commits carrying the ref reads as a change of zero size, which is not the same as no work: a commit only links if its subject opens with the ref.",inputSchema:v.object({idOrRef:v.string().min(1),repoRoot:v.string().optional()})},async t=>el(await fv(t))),e.registerTool("epiq_board_list",{description:"List Epiq boards",inputSchema:v.object({repoRoot:v.string().optional()})},Z(wc)),e.registerTool("epiq_swimlane_list",{description:"List Epiq swimlanes",inputSchema:v.object({repoRoot:v.string().optional(),boardId:v.string().optional()})},Z(Tc)),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)})},Z(kc)),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)})},Z(Mc)),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()})},Z(Pc)),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)})},Z(Lc)),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()})},Z(Ec)),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()})},Z(Cc)),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()})},Z(Ac)),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()})},Z(Dc)),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()})},Z(Oc)),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()})},Z(Hc)),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()})},Z($c)),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()})},Z(Fc)),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()})},Z(_c)),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()})},Z(jc)),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()})},Z(Uc)),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()})},Z(Wc)),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()})},Z(qc)),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()})},Z(fc)),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()})},Z(Gc)),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()})},Z(zc)),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()})},Z(Rc)),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()})},Z(Sc)),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()})},Z(Nc)),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()})},Z(Bc)),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()})},Z($h)),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()})},Z(yv)),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()})},Z(vc)),e},pR=async()=>{let e=xv(),t=new mR;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:fR}=await Promise.resolve().then(()=>(Un(),al)),{isFail:gR}=await Promise.resolve().then(()=>(R(),rl)),{parseMcpArgs:hR}=await Promise.resolve().then(()=>(ll(),cl)),ir=hR(process.argv.slice(2));ir.kind==="error"&&(console.error(ir.message),process.exit(1));ir.kind==="print"&&(process.stdout.write(ir.text),process.exit(0));if(ir.kind==="name"){let e=fR(ir.name,"The name argument");gR(e)&&(console.error(e.message),process.exit(1))}var{setVirtualNodesEnabled:vR}=await Promise.resolve().then(()=>(Na(),yh));vR(!1);var{startMcpServer:yR}=await Promise.resolve().then(()=>(Ev(),Iv));await yR();