epiq 1.15.1 → 1.16.0

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.
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env node
2
+ import{a as Yi,c as ud,d as md,f as pd}from"./chunk-WUCQWBQE.js";import{a as sr,b as a,c as d,d as c,e as St}from"./chunk-5RIQL7P4.js";import{createHash as Zb}from"node:crypto";var Kb=new Set(["https:","http:","ssh:","git:","file:"]),qb=/^[A-Za-z0-9][\w.-]*@[A-Za-z0-9][\w.-]*:[^:]+$/,Yb=/^[\x21-\x7e]+$/,Xb=2048,fd="Use https://, ssh://, git:// or user@host:path.",gd=()=>globalThis.process?.env?.EPIQ_ALLOW_LOCAL_REPOS==="1",jr=(e,t=gd())=>{if(e.length>Xb)return"is too long";if(!Yb.test(e))return"holds spaces or characters git would not";if(e.startsWith("-"))return"would be read as an option";if(/[\\#?]/.test(e))return"holds a character a clone URL has no use for";if(e.replace(/\[[^\]]*\]/g,"").includes("::"))return"names a remote helper";if(qb.test(e))return null;let n;try{n=new URL(e)}catch{return"is not a remote URL"}return/%/.test(Jb(e))?"percent-encodes its host":Kb.has(n.protocol)?n.password?"carries a password \u2014 use a credential helper":n.username&&n.protocol!=="ssh:"?"names a user before the host \u2014 leave it to a credential helper":n.protocol==="file:"?t?n.hostname?"names a host in a file:// URL":e.startsWith("file:///")?null:"is not a file:/// URL":"is a path on this machine, which nobody else can fetch":n.hostname?n.hostname.startsWith("-")||n.username.startsWith("-")?"would be read as an option":null:"names no host":"uses a transport epiq does not clone over"},Jb=e=>{let t=e.indexOf("//");if(t===-1)return"";let n=e.slice(t+2),r=n.indexOf("/");return r===-1?n:n.slice(0,r)},tn=(e,t=gd())=>jr(e,t)===null;var Ji=()=>({entries:{},seq:0}),Zi="default",Qi="board",An=20,Qb=/^\d{4}-\d{2}-\d{2}$/,ev=/^[a-z0-9][a-z0-9._-]{0,23}$/,hd=/-[0-9a-f]{12}$/,Tn=e=>e==="board"||e==="all"||tv(e),tv=e=>{if(!Qb.test(e)||e<"1970-01-01")return!1;let t=new Date(`${e}T00:00:00Z`);return!Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e},Mn=e=>ev.test(e)&&!hd.test(e),nv=/^([^@/]+@)([^:/]+)(:.*)$/,rv=/^([a-z][a-z0-9+.-]*:\/\/)([^/]*)(.*)$/i,ov=e=>{let t=nv.exec(e);if(t)return`${t[1]}${t[2].toLowerCase()}${t[3]}`;let n=rv.exec(e);if(!n)return e;let r=n[2],o=r.lastIndexOf("@")+1;return`${n[1].toLowerCase()}${r.slice(0,o)}${r.slice(o).toLowerCase()}${n[3]}`},yd=e=>ov(e.trim().replace(/\/+$/,"").replace(/\.git$/i,"")),Pt=e=>(yd(e).toLowerCase().split(/[/:]/).filter(Boolean).pop()??"").replace(/[^a-z0-9._-]/g,"-").slice(0,24).replace(/^[.-]+/,"")||"repo",nn=e=>`${Pt(e)}-${Zb("sha1").update(yd(e)).digest("hex").slice(0,12)}`,Hr=e=>e.replace(hd,""),bd=e=>{let t={},{branches:n,since:r,label:o}=e;return(n==="default"||n==="all")&&(t.branches=n),typeof r=="string"&&Tn(r)&&(t.since=r),typeof o=="string"&&(o===""||Mn(o))&&(t.label=o),t},Xi=(e,t)=>{let n={...e,...t.branches?{branches:t.branches}:{},...t.since?{since:t.since}:{}};return t.label===""?delete n.label:t.label&&(n.label=t.label),n},ea=(e,t)=>{let n=t.payload&&typeof t.payload=="object"?t.payload:{},r=bd(n);if(t.action==="connect.repo"){let l=typeof n.url=="string"?n.url.trim():"";if(l==="")return a("no URL");let u=nn(l),m=Object.hasOwn(e.entries,u)?e.entries[u]:void 0,p=m?.live===!0?Xi(m,r):Xi({id:u,url:l,branches:Zi,since:Qi,live:!0,seq:e.seq+1},r);return m?.live||e.seq++,e.entries[u]=p,d("Connected repo",p)}let o=typeof n.repo=="string"?n.repo:"",s=Object.hasOwn(e.entries,o)?e.entries[o]:void 0;if(!s?.live)return a("no such connected repo");if(t.action==="disconnect.repo"){let l={...s,live:!1};return e.entries[o]=l,d("Disconnected repo",l)}if(Object.keys(r).length===0)return a("nothing this build reads to change");let i=Xi(s,r);return e.entries[o]=i,d("Edited repo",i)},sv=e=>e==="connect.repo"||e==="edit.repo"||e==="disconnect.repo",vd=e=>{let t=Ji();for(let n of e)sv(n.action)&&ea(t,{action:n.action,payload:n.payload});return t},xd=e=>{let t=Object.values(e.entries),n=t.filter(s=>s.live&&tn(s.url)).sort((s,i)=>s.seq-i.seq),r=new Set,o=n.map(s=>{let i=[s.label,Pt(s.url)].find(l=>l!==void 0&&!r.has(l))??s.id;return r.add(i),{id:s.id,url:s.url,branches:s.branches,since:s.since,label:i}});return{live:o.slice(0,An),overLimit:o.slice(An),disconnected:t.filter(s=>!s.live).map(s=>s.id)}},ta=e=>{let t=e.payload&&typeof e.payload=="object"?e.payload:{},n=typeof t.label=="string"&&t.label!==""?t.label:null;if(e.action==="connect.repo")return typeof t.url=="string"?n??Pt(t.url):"";let r=typeof t.repo=="string"?Hr(t.repo):"";if(e.action!=="edit.repo")return r;let o=bd(t),s=[o.label!==void 0?o.label===""?"label cleared":`label ${o.label}`:null,o.branches?`${o.branches} branches`:null,o.since?`since ${o.since}`:null].filter(Boolean);return s.length>0?`${r} (${s.join(", ")})`:r};import wn from"chalk";import Bb from"string-width";import{decodeTime as Rd}from"ulid";var os=1440*60*1e3,na=(e,t=Date.now())=>e>t+os?t:e,kn=e=>na(Rd(e)),ss=e=>{let t=Date.now()+os,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})},Ed=e=>{try{return d("Decoded date",new Date(kn(e)))}catch(t){return a("Decoding failed + "+t.message)}},is=e=>{if(!e?.id)return null;try{return Rd(e.id)}catch{return null}};import ir from"chalk";var De={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:De.cyan,accent2:De.magenta,primary:De.white,secondary:De.grayDark,secondary2:De.grayLight,gray:De.gray,green:De.green,yellow:De.yellow,red:De.red};var M={red:De.red,yellow:De.yellow,green:De.green,blue:De.blue,magenta:De.magenta,cyan:De.cyan},as={urgent:M.red,critical:M.red,important:M.red,blocker:M.red,asap:M.red,immediate:M.red,fail:M.red,failure:M.red,broken:M.red,bug:M.red,error:M.red,incident:M.red,outage:M.red,production:M.red,crash:M.red,security:M.red,warning:M.yellow,warn:M.yellow,risky:M.yellow,risk:M.yellow,attention:M.yellow,pending:M.yellow,review:M.yellow,"needs-review":M.yellow,qa:M.yellow,testing:M.yellow,test:M.yellow,validate:M.yellow,verification:M.yellow,staging:M.yellow,check:M.yellow,"follow-up":M.yellow,followup:M.yellow,waiting:M.yellow,blocked:M.yellow,hold:M.yellow,done:M.green,complete:M.green,completed:M.green,success:M.green,ok:M.green,stable:M.green,resolved:M.green,fixed:M.green,closed:M.green,merged:M.green,released:M.green,deployed:M.green,approved:M.green,verified:M.green,working:M.green,healthy:M.green,pass:M.green,passing:M.green,info:M.blue,information:M.blue,note:M.blue,docs:M.blue,documentation:M.blue,doc:M.blue,guide:M.blue,help:M.blue,explanation:M.blue,detail:M.blue,details:M.blue,context:M.blue,design:M.blue,discussion:M.blue,proposal:M.blue,idea:M.blue,feature:M.magenta,enhancement:M.magenta,improvement:M.magenta,refactor:M.magenta,refactoring:M.magenta,cleanup:M.magenta,optimize:M.magenta,optimization:M.magenta,perf:M.magenta,performance:M.magenta,upgrade:M.magenta,migration:M.magenta,modernize:M.magenta,debt:M.magenta,todo:M.cyan,next:M.cyan,planned:M.cyan,plan:M.cyan,future:M.cyan,backlog:M.cyan,investigate:M.cyan,explore:M.cyan,prototype:M.cyan};var oa={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},sa=(e,t,n)=>Math.max(t,Math.min(n,e)),ra=(e,t,n)=>e+(t-e)*n,ia=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Cd=e=>e.toLowerCase().trim(),Nd=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,l=s*(1-Math.abs(i%2-1)),u=0,m=0,p=0;i>=0&&i<1?(u=s,m=l):i>=1&&i<2?(u=l,m=s):i>=2&&i<3?(m=s,p=l):i>=3&&i<4?(m=l,p=s):i>=4&&i<5?(u=l,p=s):(u=s,p=l);let f=o-s/2;return[Math.round((u+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},cs=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`,Sd=e=>{let t=e.replace("#","");return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]},Id=(e,t,n)=>{let r=sa(n,0,1);return[Math.round(ra(e[0],t[0],r)),Math.round(ra(e[1],t[1],r)),Math.round(ra(e[2],t[2],r))]};var iv=(e,t,n)=>Id(e,t,n),aa=e=>{let t=ia(e)%360,n=Nd(t,oa.stringColor.saturation,oa.stringColor.lightness);return cs(n)},Ue=(e,t=as)=>{let n=Cd(e??"");return n&&t[n]?t[n]:aa(n)},wd=e=>cs(Nd(ia(Cd(e))%360,28,58));var Ad=e=>{let t=oa.gradient.stops,n=sa(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),i=o-s;return iv(t[s],t[s+1],i)},qw=(e,t)=>{if(e.length===0)return"#000000";if(e.length===1)return e[0];let n=e.length-1,r=sa(t,0,1)*n,o=Math.min(Math.floor(r),n-1);return cs(Id(Sd(e[o]),Sd(e[o+1]),r-o))},Td=e=>cs(Ad(e)),ls=e=>ia(e.toLowerCase().trim())/4294967295,Md=e=>{let t=ls(e);return Ad(t)},av=e=>{let[t,n,r]=Md(e);return{normal:o=>ir.bgRgb(t,n,r).black(o),cursor:o=>ir.bgRgb(t,n,r).white.bold(o)}},Yw=e=>{let[t,n,r]=Md(e);return{fg:o=>ir.rgb(t,n,r)(o),fgCursor:o=>ir.rgb(t,n,r).inverse(o),bg:o=>ir.bgRgb(t,n,r).black(o),bgCursor:o=>ir.bgRgb(t,n,r).white.bold(o)}},ds=e=>av(e).normal(` ${e} `);var cv="Unknown",ca=(e,t)=>t?.length?t:e?.length?e:cv,la=(e,t)=>{let n=ca(e,t);return{id:e?.length?e:n,name:n,color:Ue(n)}};var kd="removed",nt=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?d("Found node",n):a("Unable to find node in breadcrumb")},Ld=["png","jpg","gif","webp"];var rt=e=>e.trim().toLowerCase(),ar=e=>{let t=rt(e);return t.length>0&&t.length<=254&&/^[^\s@]+@[^\s@]+$/.test(t)},da=(e,t)=>`${rt(e)} ${t}`,ua=e=>!e.tombstoned,nA=(e,t)=>{let n=rt(t),r=new Set;for(let o of Object.values(e))ua(o)&&o.email===n&&r.add(o.contributor);return[...r]},cr=(e,t)=>{let n=new Set;for(let r of Object.values(e))ua(r)&&r.contributor===t&&n.add(r.email);return[...n]},rA=e=>{let t=new Map;for(let r of Object.values(e)){if(!ua(r))continue;let o=t.get(r.email)??new Set;o.add(r.contributor),t.set(r.email,o)}let n=new Map;for(let[r,o]of t){let[s]=[...o];o.size===1&&s&&n.set(r,s)}return n};var Pd=(e,t)=>e===t.authorId||e===t.contributor;var re={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function ma(e){return e.context===re.WORKSPACE}function U(e){return e.context===re.TICKET}function Od(e){return e.context===re.TEXT}function Fe(e){return e.context===re.FIELD}function Wr(e){return e.context===re.FIELD_LIST}var ot=e=>e.context===re.SWIMLANE,Gr=e=>e.context===re.BOARD,zr=e=>e.context===re.COMMENT;import{useSyncExternalStore as dw}from"react";var y={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette",IDENTITY:"identity"};var Dd=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Fd=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",_d=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",$d=(e,t)=>{if(Fd(e,e.sequence))return C.MoveCursorLeftOfWord;if(_d(e,e.sequence))return C.MoveCursorRightOfWord;if(Dd(e,e.sequence))return C.EraseInputWord;switch(e.name){case"tab":return C.AutoCompleteCommand;case"up":return C.GetLastCommandFromHistory;case"down":return C.GetNextCommandFromHistory;case"left":return C.MoveCursorLeft;case"right":return C.MoveCursorRight;case"return":return C.Confirm;case"backspace":return t?C.EraseInput:C.ExitCommandLine;case"escape":return C.ExitCommandLine;default:return C.CaptureInput}},Bd=(e,t)=>{if(Fd(e,e.sequence))return C.MoveCursorLeftOfWord;if(_d(e,e.sequence))return C.MoveCursorRightOfWord;if(Dd(e,e.sequence))return C.EraseInputWord;switch(e.name){case"tab":return C.AutoCompleteCommand;case"up":return C.NavPreviousItem;case"down":return C.NavNextItem;case"left":return C.MoveCursorLeft;case"right":return C.MoveCursorRight;case"return":return C.Confirm;case"backspace":return t?C.EraseInput:C.ExitCommandLine;case"escape":return C.ExitCommandLine;default:return C.CaptureInput}};import Ud from"string-width";function us(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Ln=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",lv=/\u001B\[[0-9;]*m/,pa="\x1B[0m",dv=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),Pn=(e,t)=>{if(t<=0)return"";if(Ud(e)<=t)return e;if(t<=3)return"...".slice(0,t);let r=t-3,o="",s=0,i=!1;for(let l of e.split(/(\u001B\[[0-9;]*m)/))if(l!==""){if(lv.test(l)){o+=l,i=l!==pa&&l!=="\x1B[m";continue}for(let u of dv(l)){let m=Ud(u);if(s+m>r)return`${o}...${i?pa:""}`;o+=u,s+=m}}return`${o}...${i?pa:""}`},ut=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),dA=e=>e.charAt(0).toUpperCase()+e.slice(1);var jd=e=>{let t=new Map;for(let n of e){let r=n.toLowerCase();for(let o=1;o<=n.length;o++){let s=r.slice(0,o),i=t.get(s);i?i.push(n):t.set(s,[n])}}return t},Hd=(e,t)=>t?e.get(t)??[]:[];var Wd=new WeakMap,uv=e=>{let t=Wd.get(e);return t||(t=jd(e),Wd.set(e,t)),t};var Gd=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return Hd(uv(e),r).filter(s=>us(r,s.toLowerCase())>=n)};var mv={hint:"",hints:[],overlap:0,remainder:""},Vd=({inputToMatch:e,lastWord:t,isLastWordCompleted:n,inputString:r},o,s=[])=>{if(n||e===""){let[l]=s;return s.length===1&&l&&!r.trim()?zd("",[l]):mv}let i=Gd({wordList:o,inputToMatch:e,overlapThreshold:1});return zd(t,i)},zd=(e,t)=>{let n=t[0]??"",r=us(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,l=!!s,p=(l&&i?o:n)+(l&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}};var lr=e=>{let t=typeof e=="number"?e:Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<3e3||t>864e5?null:t},ms=e=>e==null||!Number.isFinite(e)?1e4:Math.min(864e5,Math.max(1,e));import ro from"node:fs";import oo from"node:path";import{z as pr}from"zod";import no from"node:fs";import{ulid as Vv}from"ulid";import{z as bs}from"zod";import Zr from"node:fs";import Dt from"node:path";import rn from"node:fs";import qe from"node:path";import pv from"node:os";import fv from"node:path";var Ct=".epiq-global",Ve=()=>process.env.EPIQ_GLOBAL_DIR??fv.join(pv.homedir(),Ct);var fa=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let i=r(...s);if(!n.has(i)){let l=e(...s).then(u=>(c(u)&&n.delete(i),u));n.set(i,l)}return n.get(i)});return o.clear=()=>n.clear(),o};import Nt from"fs";import va from"path";import gv from"util";var Kd=500,xa=4*1024*1024,ga=16*1024,hv=50,ha=0,qd=()=>process.env.EPIQ_MCP==="true",yv=()=>{let e=process.cwd(),t=ps(e);return c(t)?qd()?va.join(Ve(),"epiq-mcp.log"):void 0:va.join(t.value,je,"log","epiq.log")},bv=(e,t)=>{let n=Nt.statSync(e).size;if(n<=t)return Nt.readFileSync(e,"utf8");let r=Nt.openSync(e,"r");try{let o=Buffer.alloc(t);Nt.readSync(r,o,0,t,n-t);let s=o.toString("utf8"),i=s.indexOf(`
3
+ `);return i===-1?"":s.slice(i+1)}finally{Nt.closeSync(r)}};function vv(e){if(!Nt.existsSync(e))return;let t=Nt.statSync(e).size,n=bv(e,xa).split(`
4
+ `);if(n[n.length-1]===""&&n.pop(),t<=xa&&n.length<=Kd)return;let r=n.slice(-Kd).join(`
5
+ `)+`
6
+ `;Nt.writeFileSync(e,r,"utf8")}var xv=e=>{if(e.length<=ga)return e;let t=e.length-ga;return`${e.slice(0,ga)} \u2026 [${t} more chars]`};function ya(e,t,n=!1){let r=yv();if(!r)return;let o=xv(gv.format(...t)),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
7
+ `;try{Nt.mkdirSync(va.dirname(r),{recursive:!0}),Nt.appendFileSync(r,l,"utf8"),ha++,(ha>=hv||Nt.statSync(r).size>xa)&&(ha=0,vv(r))}catch{}}var ba=()=>qd()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",V={info(...e){let t=ba();(t==="info"||t==="debug")&&ya("[Info]",e,!1)},debug(...e){ba()==="debug"&&ya("[Debug]",e,!0)},error(...e){let t=ba();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;ya("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=V;import{spawn as Zd}from"node:child_process";import Ke from"node:fs";import Ne from"node:path";var fe={stage:({cwd:e,pathspec:t,ignoreRemoval:n=!1})=>_({args:["add",...n?["--ignore-removal"]:[],...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1,pathspec:r})=>_({args:["commit","--no-verify",...n?["--allow-empty"]:[],"-m",t,...r?.length?["--",...r]:[]],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>_({args:["fetch",t,`+refs/heads/${n}:refs/remotes/${t}/${n}`],cwd:e}),rebaseOnto:({cwd:e,ref:t})=>_({args:["-c","rebase.autoStash=true","rebase",t],cwd:e}),checkout:({cwd:e,branch:t})=>_({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 _({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>_({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>_({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>_({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>_({args:["worktree","prune"],cwd:e})};var It=e=>{let t=Ee(e);if(c(t))return a("Unable to resolve epiq project root");let n=He(t.value);return c(n)?a("Unable to read project.json"):d("Resolved state branch",n.value.stateBranch)},st="origin";var Qd="Output past",gs=e=>e.includes(Qd),eu="Git command timed out",tu=e=>e.includes(eu),Ea=1e4,Rv=12e4,Sa=256*1024*1024,nu=64*1024,Ev=8*1024*1024,Sv=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),Cv=e=>{let t=ou(e);return t&&Sv.has(t)?Rv:Ea},Nv=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(Ne.delimiter))if(t)for(let n of e){let r=Ne.join(t,n);try{if(!Ke.statSync(r).isFile())continue;return Ke.accessSync(r,Ke.constants.X_OK),r}catch{continue}}return"git"},ru=Nv(),Iv=["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_COMMON_DIR","GIT_NAMESPACE"],wv=e=>Object.fromEntries(Object.entries(e).filter(([t])=>!Iv.includes(t))),Ca={...wv(process.env),GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Av=["-c","diff.noprefix=false","-c","diff.mnemonicPrefix=false","-c","diff.srcPrefix=a/","-c","diff.dstPrefix=b/","-c","log.showSignature=false"],Tv=new Set(["log","show","diff"]),ou=e=>e.find((t,n)=>!t.startsWith("-")&&e[n-1]!=="-c"),Mv=e=>Tv.has(ou(e)??"")?Av:[],su=()=>["attr.tree=refs/epiq/no-attributes",`core.hooksPath=${Ne.join(Ve(),"repos",".no-hooks")}`,"protocol.ext.allow=never","protocol.fd.allow=never","protocol.file.allow=always","submodule.recurse=false","fetch.recurseSubmodules=false","credential.interactive=never","core.longpaths=true","gc.auto=0","maintenance.auto=false","fetch.unpackLimit=1","fetch.writeCommitGraph=false","core.logAllRefUpdates=false"].flatMap(e=>["-c",e]),kv=/^[\w-]+[\\/][a-z0-9._-]+-[0-9a-f]{12}\.git(\.\d+(-\d+)?(\.[0-9a-f-]{36})?\.pending)?$/,Yd=e=>{try{return Ke.realpathSync(e)}catch{return Ne.resolve(e)}},Na=e=>{let t=Ne.join(Ve(),"repos");return[[Ne.resolve(t),Ne.resolve(e)],[Yd(t),Yd(e)]].some(([n,r])=>kv.test(Ne.relative(n,r)))},Lv=e=>Na(e)?["--git-dir=.",...su()]:[],iu={...Object.fromEntries(Object.entries(Ca).filter(([e])=>e!=="GIT_ALLOW_PROTOCOL")),LC_ALL:"C",LANGUAGE:"",GIT_PROTOCOL_FROM_USER:"0"},fs=new Set,Xd=!1,au=process.platform!=="win32",cu=(e,t)=>{try{if(au&&e.pid){process.kill(-e.pid,t);return}}catch{}e.kill(t)},Ra=(e="SIGTERM")=>{for(let t of fs)cu(t,e)},Pv=["SIGTERM","SIGINT","SIGHUP"],lu=!1,du=()=>lu,Ov=2e3,uu=()=>{if(Xd)return;Xd=!0,process.once("exit",()=>Ra());let e=new Map;for(let t of Pv)e.set(t,()=>{lu=!0;let n=()=>{for(let[s,i]of e)process.off(s,i);process.kill(process.pid,t)};Ra();let r=Date.now()+Ov,o=()=>{if(fs.size===0)return n();if(Date.now()>=r)return Ra("SIGKILL"),n();setTimeout(o,20)};o()});for(let[t,n]of e)process.once(t,n)},mu=e=>{fs.add(e),e.once("close",()=>fs.delete(e))},pu=({args:e,cwd:t,allowFail:n,timeoutMs:r,maxOutput:o=Sa,forClone:s=!1,keepPartial:i=!1,abort:l,input:u})=>new Promise(m=>{let p=Na(t),f=p||s,g=[...Mv(e),...p?["--git-dir=."]:[],...f?su():[],...e];if(!Ke.existsSync(t)){let F=`Git cwd does not exist: ${t}`;if(n){m({stdout:"",stderr:F,exitCode:1});return}m(a(F));return}f&&uu();let v=Zd(ru,g,{cwd:t,stdio:["pipe","pipe","pipe"],env:f?iu:Ca,detached:f&&au});f&&mu(v),v.stdin.on("error",()=>{}),v.stdin.end(u??"");let I=F=>f?cu(v,F):v.kill(F),x=!1,E="",N="",S=F=>{x||(x=!0,clearTimeout(P),m(F))},T=r??Cv(g),k=!1,H=()=>[`git ${g.join(" ")}`,`cwd=${t}`,`${eu} after ${T}ms`].join(`
8
+ `),L=()=>S(n?{stdout:E,stderr:H(),exitCode:124}:a(H())),P=setTimeout(()=>{k=!0,I("SIGTERM"),setTimeout(()=>I("SIGKILL"),3e3).unref(),setTimeout(L,6e3).unref()},T),$=null,de=()=>{let F=[`git ${g.join(" ")}`,$].join(`
9
+ `);S(n?{stdout:E,stderr:F,exitCode:1}:a(F))},B=()=>{$=String(l?.reason??"stopped"),I("SIGTERM"),setTimeout(()=>I("SIGKILL"),3e3).unref(),setTimeout(de,6e3).unref()};l?.aborted?B():l?.addEventListener("abort",B,{once:!0}),v.stdout.setEncoding("utf8"),v.stderr.setEncoding("utf8"),v.stdout.on("data",F=>{if(E+=F,E.length>o){if(I("SIGTERM"),i&&!n){let en=E.slice(0,o);S(d("Git output cut",{stdout:en.slice(0,en.lastIndexOf(`
10
+ `)+1),stderr:N,exitCode:0,truncated:!0}));return}let Re=`git ${g.join(" ")}
11
+ ${Qd} ${o} characters; stopped`;S(n?{stdout:"",stderr:Re,exitCode:1}:a(Re))}}),v.stderr.on("data",F=>{N.length<nu&&(N+=F)}),v.on("error",F=>{if(n){S({stdout:E,stderr:F.message,exitCode:1});return}S(a([`git ${g.join(" ")}`,`cwd=${t}`,F.message].join(`
12
+ `)))}),v.on("close",F=>{if(l?.removeEventListener("abort",B),k)return L();if($!==null)return de();let Re=F??1;if(n){S({stdout:E,stderr:N,exitCode:Re});return}if(Re!==0){S(a([`git ${g.join(" ")}`,N.trim()||E.trim()||"Git command failed"].filter(Boolean).join(`
13
+ `)));return}S(d("Git command succeeded",{stdout:E,stderr:N,exitCode:Re}))})}),_=({args:e,cwd:t,timeoutMs:n,maxOutput:r,forClone:o,keepPartial:s,abort:i,input:l})=>pu({args:e,cwd:t,allowFail:!1,timeoutMs:n,maxOutput:r,forClone:o,keepPartial:s,abort:i,input:l}),Ie=({args:e,cwd:t})=>pu({args:e,cwd:t,allowFail:!0}),fu=(e,t)=>new Promise(n=>{if(e.length===0){n(d("No blobs to read",new Map));return}let r=Na(t);r&&uu();let o=Zd(ru,[...Lv(t),"cat-file","--batch"],{cwd:t,stdio:["pipe","pipe","pipe"],env:r?iu:Ca});r&&mu(o);let s=[],i="",l=!1,u=f=>{l||(l=!0,clearTimeout(m),n(f))},m=setTimeout(()=>{o.kill("SIGTERM"),u(a(`git cat-file --batch timed out after ${Ea}ms`))},Ea),p=0;o.stdout.on("data",f=>{if(p+=f.length,p>Sa){o.kill("SIGTERM"),u(a(`git cat-file --batch: past ${Sa} bytes; stopped`));return}s.push(f)}),o.stderr.setEncoding("utf8"),o.stderr.on("data",f=>{i.length<nu&&(i+=f)}),o.on("error",f=>u(a(f.message))),o.on("close",f=>{if(f!==0){u(a(`git cat-file --batch exited ${f}${i?`
14
+ ${i}`:""}`));return}let g=Buffer.concat(s),v=new Map,I=0;for(let x of e){let E=g.indexOf(10,I);if(E===-1){u(a(`git cat-file --batch output ended before a header for ${x}`));return}let N=g.toString("utf8",I,E);I=E+1;let S=/^[0-9a-f]{4,64} \S+ (\d+)$/.exec(N);if(!S||!S[1]){u(a(`Unexpected git cat-file --batch header: "${N}"`));return}let T=Number(S[1]);T<=Ev&&v.set(x,g.toString("utf8",I,I+T)),I+=T+1}u(d("Read blobs",v))}),o.stdin.write(e.join(`
15
+ `)+`
16
+ `),o.stdin.end()}),ur=async({cwd:e,message:t,pathspec:n})=>{let r=await fe.commit({cwd:e,message:t,pathspec:n});if(c(r))return a(`Failed to create commit
17
+ ${r.message}`);let o=await _({args:["rev-parse","HEAD"],cwd:e});return c(o)?a(`Commit created, but failed to read HEAD SHA
18
+ ${o.message}`):d("Created commit and resolved SHA",o.value.stdout.trim())},Vr=async e=>{let t=await _({cwd:e,args:["rev-parse","--git-dir"]});if(c(t))return a(t.message);let n=t.value.stdout.trim();return d("Resolved git dir",Ne.isAbsolute(n)?n:Ne.resolve(e,n))},Ia=async e=>{let t=await Vr(e);if(c(t))return a(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(r))if(Ke.existsSync(Ne.join(n,s)))return d("Checked for in-progress Git operation",i);let o={"rebase-merge":"rebase in progress","rebase-apply":"rebase in progress"};for(let[s,i]of Object.entries(o))if(Ke.existsSync(Ne.join(n,s)))return d("Checked for in-progress Git operation",i);return d("Checked for in-progress Git operation",null)},gu=async e=>{let t=await Ia(e);return c(t)?a(t.message):d("Checked for in-progress Git operation",t.value!==null)},Wt=async({repoRoot:e})=>{let n=(await Ie({args:["remote","get-url",st],cwd:e})).exitCode===0;return d(`Checked remote ${n}`,n)},Kr=async({repoRoot:e,branch:t})=>{let n=await Ie({args:["ls-remote","--heads",st,t],cwd:e});return n.exitCode!==0?a(n.stderr.trim()||`Unable to inspect remote branch ${st}/${t}`):d("Checked remote branch",n.stdout.trim().length>0)},hs=async({repoRoot:e,branch:t})=>{let n=await Ie({args:["show-ref","--verify","--quiet",`refs/heads/${t}`],cwd:e});return n.exitCode===0?d("Local branch exists",!0):n.exitCode===1?d("Local branch missing",!1):a(n.stderr.trim()||`Unable to inspect branch ${t}`)},dr=e=>{try{return Ke.realpathSync.native(e)}catch{return Ne.resolve(e)}},hu=async({repoRoot:e,worktreeRoot:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(c(n))return a(n.message);let r=dr(t),o=n.value.stdout.split(`
19
+ `).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(dr).includes(r);return d("Checked worktree registration",o)},wa=async e=>{let t=await Ie({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return d("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},ys=async e=>{let t=await _({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return c(t)?a(t.message):d("Resolved current branch",t.value.stdout.trim())},yu=async e=>{let t=await _({args:["rev-parse","--short","HEAD"],cwd:e});return c(t)?a(t.message):d("Resolved short HEAD sha",t.value.stdout.trim())},bu=e=>e.includes("fetch first")||e.includes("non-fast-forward"),vu=async e=>{let t=await Ie({cwd:e,args:["rev-parse","--absolute-git-dir"]});if(t.exitCode!==0)return!1;let n=t.stdout.trim();return n?Ke.existsSync(Ne.join(n,"rebase-merge"))||Ke.existsSync(Ne.join(n,"rebase-apply")):!1},Dv=3,Fv=120,_v=e=>new Promise(t=>setTimeout(t,e)),$v=async(e,t)=>{let n=await fe.rebaseOnto({cwd:e,ref:t});for(let r=1;r<Dv;r+=1){if(!c(n)||await vu(e))return n;await _v(Fv),n=await fe.rebaseOnto({cwd:e,ref:t})}return n},xu=async(e,{preserve:t=[]}={})=>{let n=await Vr(e);if(c(n))return a(n.message);let r=n.value,o=[];for(let s of Ke.readdirSync(r))if(s.endsWith(".lock")&&!t.includes(s))try{Ke.rmSync(Ne.join(r,s),{force:!0}),o.push(s)}catch{}return d("Cleared stale git lock files",o)},Ru=async(e,t)=>{let n=await Ie({cwd:e,args:["rev-parse","--git-common-dir"]});if(n.exitCode!==0)return a(`Unable to resolve the common git directory at ${e}`);let r=Ne.resolve(e,n.stdout.trim()),o=Ne.join(r,"refs","heads"),s=Ne.resolve(o,`${t}.lock`);if(!s.startsWith(`${o}${Ne.sep}`))return a(`Refusing to clear a ref lock outside ${o}`);if(!Ke.existsSync(s))return d("No ref lock to clear",!1);try{Ke.rmSync(s,{force:!0})}catch{return d("Ref lock could not be cleared",!1)}return d("Cleared a stale ref lock",!0)},Aa=async e=>{if(!await vu(e))return d("No rebase to abort",!1);let t=await Ie({cwd:e,args:["rebase","--abort"]});return t.exitCode!==0?a(`Failed to abort the rebase in progress at ${e}
20
+ ${t.stderr.trim()}`):d("Aborted stale rebase",!0)},Jd=async e=>{let t=await Ie({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},qr=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),Bv=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),Yr=async({cwd:e,branch:t})=>{let n=await Aa(e);if(c(n))return a(n.message);let r=await Jd(e),o=await fe.fetch({cwd:e,remote:st,branch:t});if(c(o))return Bv(o.message)?d("Remote branch missing, skipped pull",!1):a(`Failed to fetch ${t}
21
+ ${o.message}`);let s=await $v(e,`${st}/${t}`);if(c(s))return a(`Failed during rebase
22
+ ${s.message}`);let i=await Jd(e),l=r!==null&&i!==null&&r!==i;return d(l?"Pulled with rebase":"Already up to date",l)},Eu=async e=>{let t=await Ie({args:["rev-list","--count","@{u}..HEAD"],cwd:e});return t.exitCode!==0?d("No upstream to compare against",!1):d("Compared against upstream",Number(t.stdout.trim())>0)},Su=async e=>{let t=await Ie({args:["status","--porcelain","--untracked-files=all"],cwd:e});return t.exitCode!==0?a(t.stderr.trim()||"Unable to inspect the worktree for changes"):d("Inspected worktree for changes",t.stdout.trim().length>0)},Cu=async(e,t)=>{let n=await Ie({args:["diff","--cached","--quiet",...t?.length?["--",...t]:[]],cwd:e});return n.exitCode===0?d("No staged changes",!1):n.exitCode===1?d("Has staged changes",!0):a(n.stderr.trim()||"Unable to inspect staged changes")};var Nu=async e=>{let t=await ys(e);return c(t)?a(t.message):d("Checked detached HEAD state",t.value==="HEAD")};var Au="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Tu=e=>qe.join(je,Gt,e),Mu=()=>qe.join(je,ka),ku=Ve,On=()=>qe.join(ku(),"worktrees"),ve=({repoRoot:e})=>{let t=Ot(e);return c(t)?a(t.message):d("Resolved state branch root",qe.join(On(),t.value))},Uv=e=>qe.join(e,je),Iu=e=>qe.join(Uv(e),Gt);var Xr=e=>{try{return rn.mkdirSync(e,{recursive:!0}),d("Ensured directory",void 0)}catch(t){return a(t instanceof Error?t.message:String(t))}},Jr=()=>{let e=ku(),t=On(),n=!rn.existsSync(e)||!rn.existsSync(t),r=Xr(e);if(c(r))return a(`Ensure epiq home failed.
23
+ `+r.message);let o=Xr(t);return c(o)?a(`Ensure worktrees dir failed.
24
+ `+o.message):d("Ensured epiq storage",n)},Lu=e=>{rn.existsSync(e)&&(V.debug("[sync] remove path",e),rn.rmSync(e,{recursive:!0,force:!0}))};var jv=`*.jsonl merge=union
25
+ `,Hv=`*~pending*.jsonl
26
+ `,Ta=()=>qe.join(je,Gt,".gitattributes"),Ma=()=>qe.join(je,Gt,".gitignore"),wu=(e,t)=>{try{rn.readFileSync(e,"utf8")!==t&&rn.writeFileSync(e,t)}catch{rn.writeFileSync(e,t)}},Pu=(e,t)=>{for(let n of[Iu(e),Iu(t)]){let r=Xr(n);if(c(r))return a(r.message)}return wu(qe.join(t,Ta()),jv),wu(qe.join(t,Ma()),Hv),d("Ensured state branch",void 0)},Ou=async e=>{let t=await _({args:["ls-tree","--name-only","HEAD"],cwd:e});if(c(t))return a(`ensure state branch is storage only failed
27
+ `+t.message);let r=t.value.stdout.trim().split(`
28
+ `).filter(Boolean).filter(i=>i!==je);if(r.length===0)return d("State branch is storage-only",!1);let o=await _({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(c(o))return a(`Failed to clean storage branch
29
+ ${o.message}`);let s=await ur({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:r});return c(s)?a(s.message):d("Cleaned storage branch",!0)},wt=fa(async(e=process.cwd())=>{let t=await _({args:["rev-parse","--show-toplevel"],cwd:e});return c(t)?a("Not inside a Git repository"):d("Resolved repo root",t.value.stdout.trim())},e=>qe.resolve(e)),sT=fa(async e=>{let t=await _({args:["rev-parse","--git-dir"],cwd:e});if(c(t))return a(t.message);let n=t.value.stdout.trim(),r=qe.isAbsolute(n)?n:qe.join(e,n);return d("Resolved git dir",r)},e=>qe.resolve(e));var mT=process.env.IS_LOCAL==="true",je=".epiq",Gt="events",ka="media",Wv="project.json",Qr=e=>Dt.join(e,je),mr=e=>Dt.join(Qr(e),Wv),Ye=e=>Dt.join(Qr(e),Gt),eo=e=>Dt.join(Qr(e),ka),Du=e=>Dt.join(e,je),Gv=e=>{let t=Dt.join(e,je);return Zr.existsSync(t)&&Zr.statSync(t).isDirectory()},to=e=>{let t=mr(e);return Zr.existsSync(t)&&Zr.statSync(t).isFile()},ps=e=>{let t=Dt.resolve(e);for(;;){if(Gv(t))return d("Resolved closest .epiq root",t);let n=Dt.dirname(t);if(n===t)return a("No .epiq directory found in any parent");t=n}},zv="No .epiq/project.json found in any parent",Ee=e=>{let t=Dt.resolve(e);for(;;){if(to(t))return d("Resolved closest epiq project root",t);let n=Dt.dirname(t);if(n===t)return a(zv);t=n}},Fu=e=>{let t=Ye(e);try{return Zr.mkdirSync(t,{recursive:!0}),d("Resolved events dir",t)}catch(n){return a(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},ae=async()=>{let e=await wt(process.cwd());if(c(e))return e;let t=ve({repoRoot:e.value});return c(t)?t:d("Resolved persist root",t.value)};var La="__epiq_state__",Kv=bs.object({projectId:bs.string().min(1),stateBranch:bs.string().min(1),createdAt:bs.iso.datetime()}),vs=()=>({projectId:Vv(),stateBranch:La,createdAt:new Date().toISOString()}),He=e=>{let t=mr(e);if(!no.existsSync(t))return a("Missing .epiq/project.json");try{let n=no.readFileSync(t,"utf8"),r=JSON.parse(n),o=Kv.safeParse(r);return o.success?d("Read project.json",o.data):a(`Invalid .epiq/project.json: ${o.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")}},Ot=e=>{let t=He(e);return c(t)?a(t.message):d("Read projectId",t.value.projectId)},Pa=({repoRoot:e,fileContents:t})=>{let n=Qr(e),r=mr(e);try{if(no.mkdirSync(n,{recursive:!0}),no.existsSync(r)){let o=He(e);return c(o)?a(o.message):d("Project already initialized",null)}return no.writeFileSync(r,JSON.stringify(t,null,2)+`
30
+ `,"utf8"),d("Created project.json",null)}catch(o){return a(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};var xs="recent-projects.json",qv=20,Yv=pr.object({projectId:pr.string().min(1),root:pr.string().min(1),lastOpenedAt:pr.number().finite()}),Xv=pr.object({projects:pr.array(Yv)}),$u=()=>oo.join(Ve(),xs),Bu=e=>oo.basename(e)||e,_u=e=>{let t=oo.resolve(e);try{return ro.realpathSync(t)}catch{return t}},Uu=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,ju=e=>{if(!to(e.root))return!1;let t=Ot(e.root);return!c(t)&&t.value===e.projectId},Hu=()=>{let e=$u();if(!ro.existsSync(e))return d("No recent projects recorded",[]);let t;try{t=JSON.parse(ro.readFileSync(e,"utf8"))}catch(r){return a(`Invalid ${xs}: ${r instanceof Error?r.message:String(r)}`)}let n=Xv.safeParse(t);return n.success?d("Read recent projects",n.data.projects):a(`Invalid ${xs} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Jv=e=>{let t=$u();try{ro.mkdirSync(oo.dirname(t),{recursive:!0}),ro.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
31
+ `,"utf8")}catch(n){return a(`Unable to write ${xs}: ${n instanceof Error?n.message:String(n)}`)}return d("Recorded recent project",e)},Rs=({exclude:e}={})=>{let t=Hu();if(c(t))return t;let n=e===void 0?null:_u(e);return d("Listed recent projects",t.value.filter(r=>n===null||_u(r.root)!==n).filter(ju).sort(Uu))},Wu=({root:e,now:t=Date.now()})=>{let n=oo.resolve(e),r=Ot(n);if(c(r))return a(r.message);let o=r.value,s=Hu(),i=c(s)?[]:s.value,l=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(u=>u.projectId!==o&&u.root!==n)].filter(ju).sort(Uu).slice(0,qv);return Jv(l)};import{useSyncExternalStore as Zv}from"react";var so={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,gitEmail:null,gitName:null,declinedEmailBoards:[],viewMode:null},Oa=new Set,Qv=()=>{for(let e of Oa)e()},ne=()=>so,LT=()=>Zv(e=>(Oa.add(e),()=>{Oa.delete(e)}),()=>so),mt=e=>(so={...so,...e},Qv(),so);var Da=null,Gu=e=>{Da=e},zu=e=>Da?Da(e):[];var Vu=[],Ku=e=>{Vu=e},fr=()=>Vu;var io=()=>{let e=ne(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1,o=qu(),s=o.length>0?null:Fa(),i=s!==null&&(e.declinedEmailBoards??[]).includes(s),l=o.length>0||i||s===null;return{isSetupDone:n&&t&&r&&l,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r,isSetEmails:l,claimedEmails:o,emailSetupDeclined:i}},Fa=()=>{let e=Ee(process.cwd());if(c(e))return null;let t=Ot(e.value);return c(t)?null:t.value||null},qu=()=>{let{userId:e}=ne();return e?zu(e):[]},Yu=()=>qu().length>0;var _a=()=>{let e=Ee(process.cwd());if(c(e))return!1;let t=He(e.value);return St(t)},Xu=e=>e===!0?"on":e===!1?"off":null,Ju=e=>e==="on"?!0:e==="off"?!1:null,Zu=()=>{let e=io();if(!e.isSetUserName)return"config username ";if(!e.isSetPreferredEditor)return"config editor ";if(!e.isSetAutoSync)return"config autoSync ";if(!_a())return"init";if(!e.isSetEmails){let{gitEmail:t}=ne(),n=fr()[0]??t;return n&&ar(n)?`config emails ${n}`:"config emails "}return null};var ex=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[We,Es]=ex;var tx=e=>e.props.tags??[],nx=e=>e.props.assignees??[],on=e=>tx(e).map(t=>R.getTag(t)).filter(t=>!!t),sn=e=>nx(e).map(t=>R.getContributor(t)).filter(t=>!!t),Ss=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!U(n)?a("Invalid untag target"):d("Retrieved tags from ticket in breadcrumb",on(n))},Cs=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!U(n)?a("Invalid unassign target"):d("Retrieved assignees from ticket in breadcrumb",sn(n))};var b={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",GOAL:"goal",UNGOAL:"ungoal",RULE:"rule",UNRULE:"unrule",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 ao=["done"],$a=e=>ao.includes(e);var Ns=e=>ao.filter(t=>!Dn(e).includes(t)),Dn=e=>(e.props?.rules??[]).filter($a),Qu=(e,t,n)=>$a(t)?e.readonly?a("Swimlane is readonly"):(e.props.rules??[]).includes(t)===n?d("No changes made",null):d("Rule changed",{action:n?"add.swimlane.rule":"remove.swimlane.rule",payload:{id:e.id,rule:t}}):a(`No lane rule "${t}"`),rx=e=>e.title.trim().toLowerCase()==="done",Is=e=>{let t=me();if(c(t))return!1;let n=t.value.nodes[e];return!!(n&&ot(n)&&(Dn(n).includes("done")||rx(n)))};var em=new WeakMap,ox=e=>{let t=R.getNode(e);if(!t)return[];let n=em.get(t);if(n)return n;let r=new Set;t.parentNodeId&&r.add(t.parentNodeId);for(let s of t.log??[]){let i=s.payload;i.id===e&&i.parent&&r.add(i.parent)}let o=[...r];return em.set(t,o),o},tm=new WeakMap,sx=e=>{let t=tm.get(e);if(t)return t;let n=new Set;e.parentNodeId&&n.add(e.parentNodeId);for(let o of e.log??[]){let s=o.payload;s.id===e.id&&s.parent&&n.add(s.parent)}let r=[...n];return tm.set(e,r),r},nm=e=>{let t=new Set;for(let n of sx(e))for(let r of ox(n))t.add(r);return[...t]};var ws=()=>{let e=me();return c(e)?null:e.value},om=()=>ws()?.nodes??{},ix=()=>ws()?.goals??{},Ba=e=>ws()?R.getGoal(e):void 0,As=()=>Object.values(ix()).filter(e=>!e.tombstoned).sort((e,t)=>e.id.localeCompare(t.id)),Ts=e=>ut(e).trim(),Ua=e=>{let t=Ts(e);if(!t)return;let n=Ba(t);if(n)return n;let r=t.toLowerCase();return As().find(o=>o.name.toLowerCase()===r)},an=e=>{for(let t of e.props?.goals??[]){let n=Ba(t);if(n)return n}},sm=(e,t)=>{let n=e.props?.goals??[];return[...n.filter(r=>r!==t).map(r=>({action:"remove.issue.goal",payload:{id:e.id,goal:r}})),...t&&!n.includes(t)?[{action:"add.issue.goal",payload:{id:e.id,goal:t}}]:[]]},ax=e=>wd(e.id),cx=e=>(e.parentNodeId?om()[e.parentNodeId]:void 0)?.parentNodeId??void 0,lx=e=>{if(e.parentNodeId===We)return nm(e);let t=cx(e);return t?[t]:[]},rm=new WeakMap,ja=()=>{let e=ws();if(!e)return{members:new Map,onBoard:new Map};let t=rm.get(e);if(t)return t;let n=new Map,r=new Map;for(let s of Object.values(om())){if(!U(s)||s.isDeleted)continue;let i=an(s)?.id;if(!i)continue;let l=n.get(i)??[];l.push(s),n.set(i,l);let u=r.get(i)??new Map;for(let m of lx(s)){let p=u.get(m)??[];p.push(s),u.set(m,p)}r.set(i,u)}let o={members:n,onBoard:r};return rm.set(e,o),o},dx=e=>ja().members.get(e)??[],xM=e=>[...ja().onBoard.get(e)?.keys()??[]],ux=(e,t)=>ja().onBoard.get(e)?.get(t)??[],im=e=>As().filter(t=>ux(t.id,e).length>0),RM=e=>{let t=dx(e);return{done:t.filter(mx).length,total:t.length}},mx=e=>e.parentNodeId===We||Is(e.parentNodeId??""),am=(e,t)=>{let n=Ts(e);if(!n)return"A goal needs a name";if(/^[0-9A-HJKMNP-TV-Z]{26}$/i.test(n)&&!Ba(n))return`No goal has the id ${n}`;let r=Ua(e);return r&&r.id!==t?`There is already a goal called "${r.name}"`:null},Ms=(e,t)=>{let n=an(e);if(!n)return null;let r=`\u25C6 ${ut(n.name)}`;return{text:r.length>t?`${r.slice(0,Math.max(1,t-1))}\u2026`:r,color:ax(n)}};var px=/^(\d+)(h|d|w|mo|y)$/,fx=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,gx=({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},hx=(e,t=new Date)=>{let n=e.match(px);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(o){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}},yx=e=>{let t=e.match(fx);if(!t)return null;let[,n,r,o,s,i]=t,l=Number(n),u=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return gx({year:l,month:u,day:m,hour:p,minute:f})?new Date(l,u-1,m,p,f):null},Fn=e=>{let t=e.trim().toLowerCase();return hx(t)??yx(t)};var cm=/^(\d+)(s|m)?$/,ks=e=>{let t=e.trim().toLowerCase().match(cm);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},Ls=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&cm.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},lm=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,bx=[{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}],Ha=(e=bx)=>{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 vx=["BOARD","TICKET","SWIMLANE","COMMENT"],ee={EDITOR:"editor",VIEW:"view",USERNAME:"username",EMAILS:"emails",EMAILS_UNCLAIM:"emails-unclaim",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",REPO_CLONE_MAX_MB:"repoCloneMaxMb",LOG_LEVEL:"logLevel",REPO_CONNECT:"repoConnect",REPO_DISCONNECT:"repoDisconnect"},pt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Me={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},xx=[ee.EDITOR,ee.VIEW,ee.USERNAME,ee.EMAILS,ee.EMAILS_UNCLAIM,ee.AUTOSYNC,ee.SYNC_DEBOUNCE_MS,ee.ATTACHMENT_MAX_KB,ee.LOG_LEVEL,ee.REPO_CONNECT,ee.REPO_DISCONNECT,ee.REPO_CLONE_MAX_MB],Rx=(e=h().selectedNode?.context)=>{switch(e){case"TICKET":case"BOARD":case"SWIMLANE":return[pt.TITLE,pt.DESCRIPTION];case"COMMENT":return[pt.COMMENT];default:return[]}},Ga=[String(3e3),"5000","15000","30000","60000"],za=["250","500","1000"],Va=["512","2048","8192"],pm=["10s","20s","30s","45s"],_n=[b.EXIT,b.SYNC,b.HELP,b.EXPORT,b.CONFIG,b.YANK],Ps=[b.NEW,b.EDIT,b.DELETE,b.MOVE],Wa=[b.TAG,b.UNTAG,b.GOAL,b.UNGOAL,b.ASSIGN,b.UNASSIGN,b.CLOSE_ISSUE,b.RE_OPEN_ISSUE,b.EDIT,b.COMMENT],dm=[b.RULE,b.UNRULE],um=[b.FILTER,b.PEEK,b.REPLAY],Ex={WORKSPACE:[..._n,...Ps],BOARD:[...um,..._n,...Ps,...dm],SWIMLANE:[...um,..._n,...Ps,...dm],TICKET:[..._n,...Ps,...Wa],FIELD:[..._n,...Wa],FIELD_LIST:[..._n,...Wa],TEXT:[..._n],COMMENT:[b.EDIT,b.DELETE,b.YANK]},Sx=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],co=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&U(n)),zt=()=>{let{breadCrumb:e=[],selectedNode:t}=h();return[t,...[...e].reverse()].find(n=>n!=null&&ot(n))},Os=()=>{let{breadCrumb:e=[],selectedNode:t}=h(),n=[...e,t].find(o=>o?.context==="BOARD"),r=n?im(n.id):[];return[...r,...As().filter(o=>!r.includes(o))].map(o=>o.name)},mm=e=>e.parentNodeId===We,Cx=({selectedNode:e,breadCrumb:t})=>{let n=Rx(e?.context);return co({breadCrumb:t,selectedNode:e})?n.includes(pt.DESCRIPTION)?n:[...n,pt.DESCRIPTION]:n},Nx=({selectedNode:e,breadCrumb:t})=>{let n=co({breadCrumb:t,selectedNode:e});return n?[Me.REF,Me.TITLE,...n.props?.description?.trim()?[Me.DESCRIPTION]:[],...on(n).length>0?[Me.TAGS]:[],...sn(n).length>0?[Me.ASSIGNEES]:[]]:e?[Me.REF,Me.TITLE]:[]},Ka=()=>{let e=Rs({exclude:process.cwd()});return c(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},Ix=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=io();if(!r)return[b.HELP,b.CONFIG];if(!_a())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&&vx.includes(o),i=[...new Set([...n,e].map(u=>u?.context).flatMap(u=>u?Ex[u]:[]))],l=co({breadCrumb:n,selectedNode:e});return i.filter(u=>{if(u===b.MOVE)return!1;if(u===b.YANK)return!!(l??e);if(u===b.EDIT)return s||!!l;if(u===b.DELETE)return s;if(u===b.UNTAG)return!!(l&&on(l).length>0);if(u===b.UNGOAL)return!!(l&&an(l));if(u===b.RULE){let m=zt();return!!(m&&!m.readonly)}if(u===b.UNRULE){let m=zt();return!!(m&&!m.readonly&&Dn(m).length>0)}return u===b.UNASSIGN?!!(l&&sn(l).length>0):u===b.RE_OPEN_ISSUE?!!(l&&mm(l)):u===b.CLOSE_ISSUE?!!(l&&!mm(l)):!0})},ke=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=h())=>{let s=t.context??"WORKSPACE";return{[b.NONE]:Ix({breadCrumb:o,readOnly:r,selectedNode:n}),[b.EXIT]:["confirm"],[b.EXPORT]:[],[b.SYNC]:[],[b.INIT]:[],[b.OPEN]:e===b.OPEN?Ka():[],[b.HELP]:[],[b.PEEK]:[...Ha(),"now","prev","next"],[b.REPLAY]:[...Ha()],[b.EDIT]:Cx({selectedNode:n,breadCrumb:o}),[b.YANK]:Nx({selectedNode:n,breadCrumb:o}),[b.COMMENT]:[],[b.DELETE]:["confirm"],[b.RE_OPEN_ISSUE]:["confirm"],[b.CLOSE_ISSUE]:["confirm"],[b.MOVE]:["start","confirm","next","previous","jump-next","jump-previous","to-next","to-previous","cancel"],[b.FILTER]:["tag","goal","assignee","actor","description","title","ref","clear"],[b.TAG]:[...new Set([...Object.keys(as),...R.getExistingTags()])],[b.UNTAG]:[...Ss()?.value?.map(({name:l})=>l)??[]],[b.GOAL]:Os(),[b.RULE]:(()=>{let l=zt();return l?Ns(l):[]})(),[b.UNRULE]:(()=>{let l=zt();return l?Dn(l):[]})(),[b.UNASSIGN]:[...Cs()?.value?.map(({name:l})=>l)??[]],[b.ASSIGN]:R.getExistingAssignees(),[b.NEW]:Sx(s),[b.CONFIG]:[...xx]}[e]??[]};import lg from"chalk";var fm=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import Wx from"zod";import Ox from"node:path";import{z as ft}from"zod";import{accessSync as wx,copyFileSync as Ax,existsSync as Ds,mkdirSync as gm,readdirSync as hm,readFileSync as Tx,renameSync as Mx,rmSync as kx,statSync as ym,unlinkSync as Lx,writeFileSync as Px}from"node:fs";import gr from"node:path";var qa=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",Oe={writeToFile:(e,t)=>{try{let n=gr.dirname(e);Ds(n)||gm(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);Px(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return Tx(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=Oe.readFile(e);return t===null?null:JSON.parse(t)}catch(t){return logger.error(`Failed to read JSON at ${e}:`,t),null}},dirExists:e=>{try{return Ds(e)&&ym(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await wx(e),!0}catch{return!1}},mkDir:e=>gm(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=gr.parse(t);for(;;){let r=gr.join(t,e);try{if(Ds(r)&&ym(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=gr.dirname(t)}return null},readFirstJSON(e){try{if(!Oe.dirExists(e))return null;let t=hm(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=gr.join(e,t);return Oe.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return Oe.dirExists(e)?hm(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{Lx(e)}catch(t){(!qa(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{kx(e,{recursive:!0,force:!0})}catch(t){(!qa(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(gr.dirname(t)),!n?.overwrite&&Ds(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{Mx(e,t)}catch(r){if(qa(r)&&r.code==="EXDEV"){Ax(e,t),this.rmFile(e);return}throw r}}};var Dx={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},vm=ft.object({logLevel:ft.enum(["info","error","debug"]),preferredEditor:ft.string().optional(),userName:ft.string().optional(),userId:ft.string().optional(),autoSync:ft.boolean().nullable().optional(),autoSyncDebounceMs:ft.number().optional(),attachmentMaxKb:ft.number().optional(),repoCloneMaxMb:ft.number().optional(),viewMode:ft.enum(["dense","wide"]).optional(),declinedEmailBoards:ft.array(ft.string()).optional()}).partial(),Fx="config.json",xm=Ve,Ya=()=>Ox.join(xm(),Fx),Xa=()=>{try{return Oe.mkDir(xm()),d(`Ensured ~/${Ct} exists`,null)}catch{return a(`Unable to create ~/${Ct}`)}},_x=e=>{let t;try{t=JSON.parse(e)}catch{return a(`Invalid ~/${Ct}/config.json JSON`)}let n=vm.safeParse(t??{});return n.success?d("Parsed config",n.data):a(`Invalid ~/${Ct}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Ft=()=>{let e=Xa();if(c(e))return a(e.message);let t=Ya(),n=Oe.readFile(t);return n==null||n.trim()===""?d("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):_x(n)},Rm=e=>{let t=Xa();if(c(t))return a(t.message);let n=vm.safeParse(e);if(!n.success)return a(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=Ya();try{return Oe.writeToFile(r,JSON.stringify(n.data,null,2)+`
32
+ `),d("Config written",null)}catch{return a(`Unable to write ~/${Ct}/config.json`)}},Xe=e=>{let t=Ft();if(c(t))return a("Failed to read existing config");let n={...t.value,...e};return Rm(n)},Em=()=>{let e=Ya(),t=Xa();if(c(t))return a(`Unable to create ~/${Ct}`);if(!(Oe.readFile(e)!==null)){let x=Rm(Dx);if(c(x))throw new Error(`Unable to create ~/${Ct}/config.json`)}let r=Ft();if(c(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,declinedEmailBoards:l,autoSync:u,autoSyncDebounceMs:m,attachmentMaxKb:p,logLevel:f,viewMode:g}=r.value,v=pd({userId:i,userName:s});if(c(v))return a(v.message);let I=v.value??{userId:i,userName:s};return!I.userName||!I.userId?a(`User name or ID not configured in ~/${Ct}/config.json`):(process.env.EPIQ_LOG_LEVEL=f,d("successfully loaded settings",{gitEmail:null,gitName:null,declinedEmailBoards:l??[],logLevel:f??"debug",preferredEditor:o??"",userName:I.userName,userId:I.userId,autoSync:u??!1,autoSyncIntervalMs:m??1e4,attachmentMaxKb:p??null,viewMode:g??"dense"}))};import Bx from"node:crypto";import lo from"node:fs";import Nm from"node:path";var Sm="/media/",Cm=e=>`${Sm}${e}`,$x=(e,t)=>`![${e}](${Cm(t)})`;var Bn=500,Ux=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,Ja=(e,t)=>`${e}.${t}`,jx=e=>Ux.test(e),Im=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?d("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?d("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")))?d("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"))?d("Sniffed image type","webp"):a(`Unsupported image format. Allowed: ${Ld.join(", ")}`),wm=e=>Bx.createHash("sha256").update(e).digest("hex"),Hx=(e,t=Bn)=>{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=Im(e);return c(n)?n:d("Validated attachment data",{hash:wm(e),ext:n.value,bytes:e.length})},mk=(e,t,n=Bn)=>{let r=Hx(t,n);if(c(r))return r;let o=eo(e),s=Nm.join(o,Ja(r.value.hash,r.value.ext));try{lo.existsSync(s)||(lo.mkdirSync(o,{recursive:!0}),lo.writeFileSync(s,t))}catch(i){return a(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return d("Wrote attachment blob",r.value)},pk=(e,t,n=Bn)=>{if(!jx(t))return a("Invalid attachment file name");let r=Nm.join(eo(e),t);if(!lo.existsSync(r))return a("Attachment blob not found");let o;try{o=lo.readFileSync(r)}catch(u){return a(`Unable to read attachment blob: ${u instanceof Error?u.message:String(u)}`)}if(o.length>n*1024)return a(`Attachment exceeds the ${n} KB size cap and will not be served`);let[s,i]=t.split(".");if(wm(o)!==s)return a("Attachment blob does not match its content hash");let l=Im(o);return c(l)?l:l.value!==i?a("Attachment blob content does not match its extension"):d("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var uo=50,mo=5e3,Am=()=>{let e=q().commandMeta.inputString,t=Wx.coerce.number().int().min(uo).max(mo).safeParse(e);if(!t.success)return a(`Attachment size cap must be ${uo}-${mo} KB (default ${Bn})`);let n=Xe({attachmentMaxKb:t.data});return c(n)?n:(mt({attachmentMaxKb:t.data}),d(`Attachment size cap set to ${t.data} KB`,null))};import Tm from"node:fs";import Gx from"node:path";var Za=2048,hr=1,yr=1048576,Qa=e=>Number.isInteger(e)&&e>=hr&&e<=yr,br=()=>{let e=Ft(),t=c(e)?void 0:e.value.repoCloneMaxMb;return t!==void 0&&Qa(t)?t:Za},cn=e=>{let t=0,n=r=>{let o;try{o=Tm.readdirSync(r,{withFileTypes:!0})}catch{return}for(let s of o){let i=Gx.join(r,s.name);if(s.isDirectory()){n(i);continue}try{t+=Tm.lstatSync(i).size}catch{}}};return n(e),t},po=e=>`Its clone would pass this machine's ${e} MB cap for a connected repo: narrow its history, or raise repoCloneMaxMb`;var At=e=>{let t=Ee(e??process.cwd());return c(t)?a(t.message):d("Resolved Epiq repo root",t.value)},Un=e=>/^[0-9a-f]{7,40}$/i.test(e);import{createHash as MR}from"node:crypto";import vp from"node:path";import kR from"node:fs";import{ulid as LR}from"ulid";import ec from"node:fs";import zx from"node:path";var fo=e=>e?.code==="ENOENT",tc=3,nc=e=>ec.readdirSync(e).filter(t=>t.endsWith(".jsonl")).sort(),Tt=e=>{let t=Ye(e);for(let n=1;;n++){if(!ec.existsSync(t))return"none";let r=[],o=!1;for(let s of nc(t))try{let{size:i,mtimeMs:l}=ec.statSync(zx.join(t,s));r.push(`${s}:${i}:${l}`)}catch(i){if(!fo(i))throw i;if(n<tc){o=!0;break}}if(!o)return r.join("|")}},Mm=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),rc=(e,t,n,r)=>{let o=Mm(t),s=Tt(e),i=Mm(s),l=u=>u===void 0?0:Number(u.slice(0,u.indexOf(":")));if(l(i.get(n))!==l(o.get(n))+r)return null;for(let[u,m]of i)if(u!==n&&o.get(u)!==m)return null;for(let u of o.keys())if(u!==n&&!i.has(u))return null;return s},Vt=null,km=e=>Vt&&Vt.root===e?Vt.signature:null,Fs=(e,t)=>{Vt={root:e,signature:t}},Lm=(e,t,n)=>{if(!Vt||Vt.root!==e)return;let r=rc(e,Vt.signature,t,n);Vt=r===null?null:{root:e,signature:r}},Pm=()=>{Vt=null};import{z as jn}from"zod";var Om=1,Dm=jn.tuple([jn.string().min(1),jn.string().min(1).nullable()]),Vx=jn.looseObject({v:jn.literal(Om),id:Dm}),Bk=jn.looseObject({v:jn.number().int().positive(),id:Dm}),Kx=e=>Object.prototype.hasOwnProperty.call(e,"__proto__"),qx=e=>{let t={};for(let n of Object.keys(e))n!=="__proto__"&&(t[n]=e[n]);return t},Fm=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return a("Invalid persisted event envelope: expected an object");let{v:t,id:n}=e;if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return a("Invalid persisted event envelope: v");if(!Array.isArray(n)||n.length!==2)return a("Invalid persisted event envelope: id");let[r,o]=n;return typeof r!="string"||r.length===0?a("Invalid persisted event envelope: id.0"):o!==null&&(typeof o!="string"||o.length===0)?a("Invalid persisted event envelope: id.1"):d("Parsed persisted event envelope",Kx(e)?qx(e):e)};var Yx=[1];var Xx=new Set(Yx),oc=e=>Xx.has(e),_m=e=>{let t=Vx.safeParse(e);return t.success?d("Parsed persisted event",t.data):a(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},sc=(e,t)=>{let n={[e.action]:e.payload,v:Om,id:t};return _m(n)};import yo from"node:fs";import Hs from"node:path";import{decodeTime as oR}from"ulid";import{z as cc}from"zod";import we from"node:fs";import Hn from"node:path";import{ulid as Jx}from"ulid";var $s="~pending",ic=/~pending(-[0-9a-z]+)*$/i,Bm=/-f(\d+)$/,Um=e=>{let t=e.indexOf(".");return t===-1?`${e}${$s}`:e.slice(0,t)+$s+e.slice(t)},Bs=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},Zx=e=>{let[t,n]=Bs(e);return ic.test(t)?t.replace(ic,"")+n:null},ac=e=>e.replace(ic,""),Wn=e=>e.endsWith(".jsonl")&&Zx(e)!==null,go=e=>ac(Bs(e)[0]),jm=e=>{let[t]=Bs(e),n=Bm.exec(t);return n&&Wn(e)?Number(n[1]):null},Qx=e=>Um(e).replace($s,`${$s}-${Jx().toLowerCase()}`),eR=(e,t)=>{let[n,r]=Bs(e);return`${n.replace(Bm,"")}-f${t}${r}`},Hm=(e,t)=>Hn.join(Ye(e),Um(t)),tR=(e,t)=>Math.max(0,we.statSync(e).size-(jm(t)??0)),Wm=e=>{let t=Ye(e);try{return we.existsSync(t)?we.readdirSync(t).filter(Wn).some(n=>tR(Hn.join(t,n),n)>0):!1}catch{return!0}},nR=3,Gm=(e,t)=>{for(let n=1;;n++){let r=we.openSync(e,"a"),o;try{we.writeSync(r,t),o=we.fstatSync(r).ino}finally{we.closeSync(r)}let s;try{s=we.statSync(e).ino}catch{s=null}if(s===o||n>=nR)return}},rR=e=>{let t;try{t=we.openSync(e,"r")}catch{return!0}try{let{size:n}=we.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return we.readSync(t,r,0,1,n-1),r[0]===10}finally{we.closeSync(t)}},_s=10,$m=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(_s)+1;if(r===0)return{bytes:0,lines:0};let o=t.subarray(0,r);if(o.toString("utf8").trim().length===0)return{bytes:r,lines:0};we.appendFileSync(e,Buffer.concat([Buffer.from(rR(e)?"":`
33
+ `),o,Buffer.from(o[o.length-1]===_s?"":`
34
+ `)]));let s=0;for(let i of o)i===_s&&s++;return o[o.length-1]!==_s&&s++,{bytes:r,lines:s}},Us=(e,t)=>{let n=Ye(e);if(!we.existsSync(n))return d("No events directory",0);try{let r=go(t),o=we.readdirSync(n).filter(l=>Wn(l)&&go(l)===r),s=Hn.join(n,t),i=0;for(let l of o){let u=jm(l);if(u!==null){let g=Hn.join(n,l),v=we.readFileSync(g).subarray(u);i+=$m(s,v,!0).lines,we.rmSync(g,{force:!0});continue}let m=/~pending-/i.test(l)?l:Qx(t),p=Hn.join(n,m);m!==l&&we.renameSync(Hn.join(n,l),p);let f=$m(s,we.readFileSync(p));i+=f.lines,we.renameSync(p,Hn.join(n,eR(m,f.bytes)))}return d("Folded pending logs",i)}catch(r){return a(`Unable to fold pending event logs in ${n}: ${r instanceof Error?r.message:String(r)}`)}};var Ws="unknown",sR=cc.object({userId:cc.string().min(1).default(Ws),userName:cc.string().min(1).default(Ws)}),qm=new Set(["id","v","userId","userName"]),js=e=>{let t=Object.entries(e).filter(([o])=>!qm.has(o));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},iR=/^[0-9a-hjkmnp-tv-z]{26}$/i,aR=e=>iR.test(e)?e.toUpperCase():e,Ym=e=>{let t=Hs.basename(e,".jsonl"),n=t.indexOf("."),r=ac(n===-1?t:t.slice(0,n)),o=n===-1?void 0:t.slice(n+1),s=sR.safeParse({userId:aR(r),userName:o});return s.success?d("Parsed event file actor",s.data):a(`Invalid event file name ${Hs.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},cR=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"):d("Resolved persisted action",t[0])},lR=(e,t)=>t in e,ln=new Map,dR=3e5,uR=512,ho=0,lc=e=>e.entries.length+e.quarantined.length,mR=(e,t,n,r)=>{let o=ln.get(e);o&&(ho-=lc(o));let s={stamp:t,entries:n,quarantined:r};ln.delete(e),ln.set(e,s),ho+=lc(s);for(let[i,l]of ln){if(ho<=dR&&ln.size<=uR)break;i!==e&&(ln.delete(i),ho-=lc(l))}},pR=()=>{ln.clear(),ho=0},fR=2n,zm=1000000n,gR=e=>{try{let{size:t,mtimeNs:n}=yo.statSync(e,{bigint:!0});return{value:`${t}:${n}`,settled:BigInt(Date.now())*zm-n>fR*zm}}catch{return null}},Xm=(e,t)=>{let n=Ym(e);if(c(n))return a(n.message);let r=gR(e),o=r?ln.get(e):void 0;if(r&&o&&o.stamp===r.value){if(t)for(let p of o.quarantined)t.push(p);return d("Parsed persisted events file",[...o.entries])}let s;try{s=yo.readFileSync(e,"utf8")}catch(p){if(fo(p))return d("Event file missing",null);throw p}let i=[],l=Hs.basename(e),u=[],m=(p,f)=>{u.push({eventId:null,reason:"corrupt-line",detail:`${l}:${p} (${f})`,targetNodeId:null})};for(let[p,f]of s.split(`
35
+ `).entries()){let g=f.trim();if(!g)continue;let v;try{v=JSON.parse(g)}catch{m(p+1,"invalid JSON");continue}let I=Fm(v);if(c(I)){m(p+1,I.message);continue}i.push({...I.value,userId:n.value.userId,userName:n.value.userName})}if(t)for(let p of u)t.push(p);return r?.settled&&mR(e,r.value,i,u),d("Parsed persisted events file",[...i])},Vm=(e,t)=>e<t?-1:e>t?1:0,dc=(e,t)=>{let n=Vm(e.id[0],t.id[0]);return n!==0?n:Vm(JSON.stringify(e),JSON.stringify(t))},Km=(e,t)=>{let n=new Map,r=new Map;for(let p of e){let f=p.id[0],g=p.id[1]??null;n.set(f,p);let v=r.get(g)??[];v.push(p),r.set(g,v)}for(let p of r.values())p.sort(dc);let o=[],s=new Set,i=p=>{let f=[p];for(;f.length>0;){let g=f.pop(),v=g.id[0];if(s.has(v))continue;o.push(g),s.add(v);let I=r.get(v)??[];for(let x=I.length-1;x>=0;x--)f.push(I[x])}},l=(r.get(null)??[]).filter(p=>{let f=Object.keys(p).filter(g=>!qm.has(g));return f.length===1&&f[0]===t});for(let p of l)i(p);let u=e.filter(p=>{let f=p.id[0],g=p.id[1]??null;return s.has(f)?!1:g===null||!n.has(g)}).sort(dc);for(let p of u)i(p);let m=e.filter(p=>!s.has(p.id[0])).sort(dc);for(let p of m)i(p);return o},uc=e=>ss(e.map(t=>{try{return oR(t.id[0])}catch{return null}})),Jm=(e,t)=>{let n=new Set,r=[],o=[],s=uc(e);for(let i=0;i<e.length;i++){let l=e[i],u=l.id[0],m=l.id[1],p=s[i]??null;!(p!==null&&p<t)||m&&n.has(m)?(n.add(u),o.push(l)):r.push(l)}return{appliedEvents:r,unappliedEvents:o}},Zm=e=>{let t=new Set(e.actions),n=N=>t.has(N),r=N=>{let{userId:S,userName:T,...k}=N,H=cR(k);if(c(H))return a(H.message);let L=H.value,P=N.id?.[0];return P?lR(k,L)?d("Decoded persisted event",{id:P,action:L,payload:k[L],userId:S}):a(`Persisted event is missing payload for action: ${L}`):a("Persisted event is missing id")},o=(N,S)=>{let T=[],k=new Map,H=new Map;for(let L of N){if(!oc(L.v)){H.set(L.v,(H.get(L.v)??0)+1),S?.push({eventId:L.id[0],reason:"unsupported-schema-version",detail:`v${L.v}`,targetNodeId:js(L)});continue}let P=r(L);if(c(P)){S?.push({eventId:L.id[0],reason:"invalid-payload",detail:P.message,targetNodeId:js(L)});continue}let $=P.value.action;if(!n($)){k.set($,(k.get($)??0)+1),S?.push({eventId:L.id[0],reason:"unknown-action",detail:$,targetNodeId:js(L)});continue}let de=e.readPayload($,P.value.payload);if(c(de)){S?.push({eventId:L.id[0],reason:"invalid-payload",detail:de.message,targetNodeId:js(L)});continue}T.push(P.value)}if(k.size>0){let L=[...k.entries()].map(([P,$])=>`${P} (x${$})`).join(", ");V.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${L}. Upgrade to apply them.`)}if(H.size>0){let L=[...H.entries()].map(([P,$])=>`v${P} (x${$})`).join(", ");V.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${L}. Upgrade to apply them.`)}return d("Decoded reconstructed events",T)},s=null;function i(N,S){let T=Ye(N),k=Tt(N);if(!yo.existsSync(T))return d("No events found",[]);let H=[],L=[];for(let $=1;;$++){H=[],L=[];let de=!1;for(let B of nc(T)){let F=Xm(Hs.join(T,B),L);if(c(F))return a(F.message);if(F.value===null){if($<tc){de=!0;break}continue}for(let Re of F.value)H.push(Re)}if(!de)break}if(S)for(let $ of L)S.push($);let P=Km(H,e.genesis);return s={root:N,signature:k,edge:P.at(-1)?.id?.[0]??null},d("All events loaded",P)}function l(N){let S=[],T=i(N,S);if(c(T))return a(T.message);let k=o(T.value,S);return c(k)?a(k.message):d("Loaded merged events",{events:k.value,unreadable:S})}function u(N){let S=i(N);return c(S)?a(S.message):d("Loaded event actors",S.value.map(({userId:T,userName:k})=>({userId:T,userName:k})))}function m(N){let S=new Map,T=Ye(N),k;try{if(!yo.existsSync(T))return S;k=yo.readdirSync(T)}catch{return S}let H=new Set;for(let P of k){if(!P.endsWith(".jsonl"))continue;let $=Ym(P);if(c($))continue;let{userId:de,userName:B}=$.value;if(!de||!B||B===Ws)continue;let F=S.get(de);F!==void 0&&F!==B&&H.add(de),S.set(de,B)}if(H.size===0)return S;let L=u(N);if(c(L))return S;for(let{userId:P,userName:$}of L.value)H.has(P)&&(!$||$===Ws||S.set(P,$));return S}function p(N){let S=l(N);return c(S)?a(S.message):d("Loaded merged events",S.value.events)}function f(N,S){let T=i(N);if(c(T))return a(T.message);let{appliedEvents:k,unappliedEvents:H}=Jm(T.value,S),L=o(k);if(c(L))return a(L.message);let P=o(H);return c(P)?a(P.message):d("Loaded merged events before time",{appliedEvents:L.value,unappliedEvents:P.value})}function g(N=process.cwd()){let S=Tt(N);if(s&&s.root===N&&s.signature===S)return d("Loaded edge reference, unchanged",s.edge);let T=i(N);return c(T)?a(T.message):d("Loaded edge reference",T.value.at(-1)?.id?.[0]??null)}function v(N,S,T,k){if(!s||s.root!==N)return;let H=rc(N,s.signature,S,k);s=H===null?null:{root:N,signature:H,edge:T}}function I(){s=null,pR()}let x=N=>Km(N,e.genesis);function E(N){let S=i(N);if(c(S))return a(S.message);let T=uc(S.value);return d("Loaded effective event times",new Map(S.value.map((k,H)=>[k.id[0],T[H]??null])))}return{fromPersistedEvent:r,decodeReconstructedEvents:o,loadMergedEventsWithUnreadable:l,loadEventActors:u,loadActorNames:m,loadMergedEvents:p,loadMergedEventsBefore:f,getEdgeRef:g,advanceEdgeRef:v,clearEdgeCache:I,getSortedEvents:x,loadEffectiveEventTimes:E}};var Gs=(e,t)=>a(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),O=(e,t)=>({...Gs(e,t),convergence:!0}),vr=e=>c(e)&&e.convergence===!0,Gn=e=>{let t=e.filter(c);return{fatal:t.filter(n=>!vr(n)),skipped:t.filter(vr)}},zn=e=>{e.length!==0&&V.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},hR=e=>e.userId?.length?null:Gs("Invalid user ID format",e),Qm=e=>{let t=null;function n(o,s=!1){let i=e.apply[o.action];if(!i)return a(`Unknown event action "${o.action}", likely created by a newer epiq version. Evt id: ${o.id}`);if(!e.replay.isInitialized()&&o.action!==e.genesis)return O(`${o.action} arrived before the state was initialized`,o);if(o.action===e.genesis&&t){if(t.genesisApplied)return O("the state is already initialized",o);t.genesisApplied=!0}let l;try{l=i(o)}catch(p){return O(`threw while materializing (${p instanceof Error?p.message:String(p)})`,o)}if(c(l))return l;let u=hR(o);if(u)return u;let m=e.replay.afterApply(o,{batched:t!==null,bypassLogging:s});return m||l}return{materialize:n,materializeAll:o=>{let s=e.replay.batch(()=>{let i=t===null;i&&(t={genesisApplied:!1});let l=!1;try{let u=o.map(m=>n(m));if(i){l=!0;let m=e.replay.flush();if(m)return o.map(()=>m)}return u}finally{i&&(t=null,l||e.replay.flush())}});return c(s)?o.map(()=>a(s.message)):s.value}}};import np from"node:fs";import mc from"node:path";import{decodeTime as yR,monotonicFactory as bR}from"ulid";var ep=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown";var Q=({userId:e})=>({userId:e}),tp=e=>({action:e.action,payload:e.payload});var vR=0xffffffffffff,xR=os,RR=e=>{let t=Date.now(),n;try{n=yR(e)}catch{return t}return n>=vR?t:n>t+xR?(V.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)},xr=({userId:e})=>`${ep(e)}.jsonl`,rp=(e,t)=>{let n;try{if(!np.existsSync(e))return[t];n=np.readdirSync(e)}catch{return[t]}let r=go(t);return[...n.filter(s=>!s.endsWith(".jsonl")||s===t||Wn(s)?!1:go(s)===r).sort(),t]},op=(e,{userId:t})=>{let n=xr({userId:t});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(n))return a(`Invalid event log file name: ${n}`);let o=mc.join(Ye(e),n);return d("Successfully resolved event log path",o)},sp=e=>{let t=bR();function n(o,s){let i;if(s&&s.current!==void 0)i=s.current;else{let u=e.getEdgeRef(o);if(c(u))return a(u.message);i=u.value}let l=i?t(RR(i)):t();return d("Minted event id",[l,i])}function r({event:o,rootDir:s,edge:i,id:l}){try{let u=Fu(s);if(c(u))return u;let m=op(s,{userId:o.userId});if(c(m))return m;let p=Hm(s,mc.basename(m.value)),f=l?d("Minted event id",l):n(s,i);if(c(f))return a(f.message);let[g,v]=f.value,I=sc(tp(o),[g,v]);if(c(I))return a(I.message);let x=`${JSON.stringify(I.value)}
36
+ `;Gm(p,x),i&&(i.current=g);let E=mc.basename(p);return e.advanceEdgeRef(s,E,g,Buffer.byteLength(x)),Lm(s,E,Buffer.byteLength(x)),d("Event persisted",{path:p,entry:I.value})}catch(u){let m=u instanceof Error?u.message:"Unknown persist error";return a(`Failed to persist event: ${m}`)}}return{mintEventId:n,persist:r}};var ip=(e,t,n)=>{function r(s,i,l){let u=n.mintEventId(i,l);if(c(u))return a(u.message);let m={...s,id:u.value[0]},p=t.materialize(m);if(p.status!==sr.Success)return p;let f=n.persist({event:m,rootDir:i,edge:l,id:u.value});return c(f)?(Pm(),f):p}function o(s,i){if(s.length===0||!s[0])return a("No events provided");let l=e.write.readOnlyReason();if(l)return a(l);let u=e.replay.batch(()=>{let m={},p=e.write.beforeWrite(s[0],v=>r(v,i,m));if(c(p))return a(p.message);let f=s.map(v=>r(v,i,m)),g=f.filter(c);return g.length>0?a("Materialize and persist failed: "+g.map(v=>v.message).join(", ")):d("Materialization succeeded",f.map(v=>v.value))});return c(u)?a(u.message):u.value??a("Materialize and persist produced nothing")}return{materializeAndPersist:r,materializeAndPersistAll:o}};var ap=e=>{let t=Qm(e),n=Zm(e),r=sp(n),o=ip(e,t,r);return{...t,...n,...r,...o}};import{z as K}from"zod";var W=K.string().min(1),it=K.string(),dn=K.string(),bo=K.looseObject({id:W}),cp=K.string().min(1).max(64),pc=K.looseObject({id:W,name:it,parent:W,rank:dn}),ER={"init.workspace":K.looseObject({id:W,name:it,rank:dn}),"add.workspace":K.looseObject({id:W,name:it,rank:dn}),"add.board":pc,"add.swimlane":pc,"add.issue":pc,"add.field":K.looseObject({id:W,name:it,parent:W,rank:dn}),"edit.title":K.looseObject({id:W,name:it}),"delete.node":bo,"lock.node":bo,"move.node":K.looseObject({id:W,parent:W,rank:dn}),"edit.description":K.looseObject({id:W,md:K.string()}),"add.swimlane.rule":K.looseObject({id:W,rule:cp}),"remove.swimlane.rule":K.looseObject({id:W,rule:cp}),"close.issue":K.looseObject({id:W,parent:W,rank:dn}),"reopen.issue":K.looseObject({id:W,parent:W,rank:dn}),"create.tag":K.looseObject({id:W,name:it}),"tombstone.tag":bo,"restore.tag":K.looseObject({id:W,name:it}),"create.goal":K.looseObject({id:W,name:it}),"rename.goal":K.looseObject({id:W,name:it}),"tombstone.goal":bo,"create.contributor":K.looseObject({id:W,name:it}),"rename.contributor":K.looseObject({id:W,name:it}),"tombstone.contributor":bo,"restore.contributor":K.looseObject({id:W,name:it}),"link.contributor.user":K.looseObject({contributor:W}),"link.contributor.email":K.looseObject({contributor:W,email:W}),"unlink.contributor.email":K.looseObject({contributor:W,email:W}),"connect.repo":K.looseObject({url:K.string()}),"edit.repo":K.looseObject({repo:W}),"disconnect.repo":K.looseObject({repo:W}),"add.issue.assignee":K.looseObject({id:W,assignee:W}),"remove.issue.assignee":K.looseObject({id:W,assignee:W}),"add.issue.tag":K.looseObject({id:W,tag:W}),"remove.issue.tag":K.looseObject({id:W,tag:W}),"add.issue.goal":K.looseObject({id:W,goal:W}),"remove.issue.goal":K.looseObject({id:W,goal:W}),"add.issue.comment":K.looseObject({id:W,issue:W,md:K.string()}),"edit.issue.comment":K.looseObject({id:W,issue:W,md:K.string()}),"delete.issue.comment":K.looseObject({id:W,issue:W}),"add.issue.attachment":K.looseObject({id:W,issue:W,hash:K.string().min(1),ext:K.string().min(1),name:it,bytes:K.number()}),"delete.issue.attachment":K.looseObject({id:W,issue:W}),"rebalance.children":K.looseObject({parent:W,ranks:K.record(K.string(),dn)})},lp=(e,t)=>{let r=ER[e].safeParse(t);return r.success?d("Payload is readable",void 0):a(`${e}: ${r.error.issues.map(o=>`${o.path.join(".")||"payload"} ${o.message}`).join(", ")}`)};import{ulid as SR}from"ulid";var dp=(e,t)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return d("Contributor write already in flight",void 0);let{userId:n,userName:r}=ne();if(!r||n!==e.userId)return d("Not this actor own write",void 0);let o=R.getContributor(e.userId),s={id:SR(),action:o?"rename.contributor":"create.contributor",payload:{id:e.userId,name:r},userId:e.userId};if(o&&(o.tombstoned||o.name===r))return d("Contributor name is current",void 0);let i=t(s);return c(i)?a(i.message):d("Contributor name recorded",void 0)};var fc=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","tombstone.tag","restore.tag","create.goal","rename.goal","tombstone.goal","create.contributor","rename.contributor","tombstone.contributor","restore.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","add.issue.goal","remove.issue.goal","move.node","edit.description","add.swimlane.rule","remove.swimlane.rule","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","link.contributor.email","unlink.contributor.email","connect.repo","edit.repo","disconnect.repo"];var oP=new Set(fc);var ge={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",DIFF:"Diff",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var at=e=>e.slice(-7).toUpperCase(),gc=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?at(e).includes(n):!0};var Ae={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:re.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:at(e)},context:re.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:re.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:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:re.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),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:re.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:at(e)},context:re.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0,disabled:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:i?{disabled:!0}:{},context:re.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:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:re.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};var vo=(e,t,n)=>R.getNode(e)?O(`a node with id ${e} already exists`,n):t===e?O("a node cannot be its own parent",n):null,hc=e=>{let t=h().repos,n=ea(t,e);if(c(n))return{skip:O(n.message,e)};let r=pe(o=>({...o,repos:t}));return c(r)?{skip:O("Unable to update repos",e)}:{message:n.message,entry:n.value}},up={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Ae.workspace(t,n,r),s=xo(o);if(c(s))return Gs(s.message,e);let i=R.createNode(o);return c(i)?O(i.message??"Failed to initialize workspace",e):ma(i.value)?d("Workspace initialized",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=vo(t,void 0,e);if(o)return o;let s=R.createNode(Ae.workspace(t,n,r));return c(s)?O(s.message??"Failed to add workspace",e):ma(s.value)?d("Added workspace",{action:e.action,result:s.value}):a("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=vo(t,r,e);if(s)return s;let i=R.createNode(Ae.board(t,n,r,o));return c(i)?O(i.message??"Unable to create board",e):Gr(i.value)?d("Added board",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=vo(t,r,e);if(s)return s;let i=R.createNode(Ae.swimlane(t,n,r,o));return c(i)?O(i.message??"Unable to create swimlane",e):ot(i.value)?d("Added swimlane",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=vo(t,r,e);if(s)return s;let i=R.createNode(Ae.ticket(t,n,r,o));return c(i)?O(i.message??"Unable to create issue",e):U(i.value)?d("Added issue",{action:e.action,result:i.value}):a("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=vo(t,r,e);if(i)return i;let l=R.createNode(Ae.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(ge.DESCRIPTION)?"vertical":"horizontal"}));return c(l)?O(l.message??`Unable to create field: ${n}`,e):Fe(l.value)?d("Added field",{action:e.action,result:l.value}):a("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!R.getNode(t))return O(`Unable to locate node with id ${t}`,e);let o=R.renameNode(t,n);return c(o)?O(o.message??"Unable to edit title",e):d("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=R.tombstoneNode(t);return c(n)?O(n.message??"Unable to delete node",e):d("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=R.createTag({id:t,name:n});return c(r)?O(r.message??"Unable to create tag",e):d("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=R.tombstoneTag(t);return c(n)?O(n.message??"Unable to delete tag",e):d("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=R.restoreTag(t,n);return c(r)?O(r.message??"Unable to restore tag",e):d("Tag restored",{action:e.action,result:r.value})},"create.goal":e=>{let{id:t,name:n}=e.payload,r=R.createGoal({id:t,name:n});return c(r)?O(r.message??"Unable to create goal",e):d("Goal added",{action:e.action,result:r.value})},"rename.goal":e=>{let{id:t,name:n}=e.payload,r=R.renameGoal(t,n);return c(r)?O(r.message??"Unable to rename goal",e):d("Goal renamed",{action:e.action,result:r.value})},"tombstone.goal":e=>{let t=R.tombstoneGoal(e.payload.id);return c(t)?O(t.message??"Unable to remove goal",e):d("Goal tombstoned",{action:e.action,result:t.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=R.createContributor({id:t,name:n});return c(r)?O(r.message??"Unable to create contributor",e):d("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=R.renameContributor(t,n);return c(r)?O(r.message??"Unable to rename contributor",e):d("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=R.tombstoneContributor(t);return c(n)?O(n.message??"Unable to remove contributor",e):d("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,r=R.restoreContributor(t,n);return c(r)?O(r.message??"Unable to restore contributor",e):d("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=R.tag(t,n);return c(r)?O(r.message??"Unable to tag issue",e):d("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=R.untag(t,n);return c(r)?O(r.message??"Unable to untag issue",e):d("Issue untagged",{action:e.action,result:{tag:n}})},"add.swimlane.rule":e=>{let{id:t,rule:n}=e.payload,r=R.addLaneRule(t,n);return c(r)?O(r.message??"Unable to add rule",e):d("Added lane rule",{action:e.action,result:r.value})},"remove.swimlane.rule":e=>{let{id:t,rule:n}=e.payload,r=R.removeLaneRule(t,n);return c(r)?O(r.message??"Unable to remove rule",e):d("Removed lane rule",{action:e.action,result:r.value})},"add.issue.goal":e=>{let{id:t,goal:n}=e.payload,r=R.addGoal(t,n);return c(r)?O(r.message??"Unable to add goal",e):d("Added to goal",{action:e.action,result:r.value})},"remove.issue.goal":e=>{let{id:t,goal:n}=e.payload,r=R.removeGoal(t,n);return c(r)?O(r.message??"Unable to remove goal",e):d("Removed from goal",{action:e.action,result:r.value})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=R.assign(t,n);return c(r)?O(r.message??"Unable to assign issue",e):d("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=R.unassign(t,n);return c(r)?O(r.message??"Unable to unassign issue",e):d("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=R.moveNodeToRank({id:t,parentId:n,rank:r});return c(o)?O(o.message??"Failed to move node",e):d("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=R.editValue(t,n);return c(r)?O(r.message??"Unable to edit description",e):d("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=R.getNode(t);if(!o)return O("Unable to locate issue",e);if(!U(o))return O("Can only close issues",e);let s=R.getNode(We);if(!s)return O("Unable to locate target swimlane",e);if(n!==s.id)return O("Close target must be closed swimlane",e);let i=R.moveNodeToRank({id:t,parentId:n,rank:r});return c(i)?O(i.message??"Unable to close issue",e):d("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=R.getNode(t);if(!o)return O("Unable to locate issue",e);if(!U(o))return O("Can only reopen issues",e);let s=R.getNode(We);if(!s)return O("Unable to locate closed swimlane",e);if(n===s.id)return O("Cannot reopen issue into closed swimlane",e);if(!R.getNode(n))return O("Reopen parent no longer exists",e);let l=R.moveNodeToRank({id:t,parentId:n,rank:r});return c(l)?O(l.message??"Unable to reopen issue",e):d("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=R.lockNode(t);return c(n)?O(n.message??"Unable to lock node",e):d("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=R.getNode(r);if(!s)return O(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return O(`Node ${r} is not child of ${t}`,e);let i=R.updateNode({...s,rank:o});if(c(i))return O(i.message??"Unable to rebalance child",e)}return d("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=R.createComment({id:t,issue:n,authorId:r,md:o,deleted:!1});return c(s)?O(s.message??"Unable to add comment",e):d("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=R.getComment(t);if(!o)return O("Unable to locate comment",e);if(o.issue!==n)return O("Comment does not belong to issue",e);let s=R.editComment(t,r);return c(s)?O(s.message??"Unable to edit comment",e):d("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=R.getComment(t);if(!r)return O("Unable to locate comment",e);if(r.issue!==n)return O("Comment does not belong to issue",e);let o=R.deleteComment(t);return c(o)?O(o.message??"Unable to delete comment",e):d("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:i}=e.payload,l=R.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return c(l)?O(l.message??"Unable to add attachment",e):d("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=R.getAttachment(t);if(!r)return O("Unable to locate attachment",e);if(r.issue!==n)return O("Attachment does not belong to issue",e);let o=R.deleteAttachment(t);return c(o)?O(o.message??"Unable to delete attachment",e):d("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.email":e=>{let{contributor:t,email:n}=e.payload;if(!ar(n))return O(`not an email address: ${n}`,e);let r=R.linkContributorEmail({email:n,contributor:t,authorId:e.userId});return c(r)?O(r.message??"Unable to link email",e):d("Email linked to contributor",{action:e.action,result:r.value})},"unlink.contributor.email":e=>{let{contributor:t,email:n}=e.payload,r=R.unlinkContributorEmail(n,t,e.userId);return c(r)?O(r.message??"Unable to unlink email",e):d("Email unlinked from contributor",{action:e.action,result:r.value})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=R.linkUserId({contributorId:t,userId:e.userId});return c(n)?O(n.message??"Unable to link contributor",e):d("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})},"connect.repo":e=>{let t=hc(e);return"skip"in t?t.skip:d(t.message,{action:e.action,result:t.entry})},"edit.repo":e=>{let t=hc(e);return"skip"in t?t.skip:d(t.message,{action:e.action,result:t.entry})},"disconnect.repo":e=>{let t=hc(e);return"skip"in t?t.skip:d(t.message,{action:e.action,result:t.entry})}};var mp=e=>{let t=R.getNode(e);if(!t||!U(t)||t.isDeleted)return null;let n=bc(t);return c(n)?n:null},pp=e=>{if(!vc())return null;for(let t of e){let n=mp(t);if(n)return n;let r=h().nodes[t]?.parentNodeId;if(!r)continue;let o=mp(r);if(o)return o}return null},CR=(e,t)=>{let n=R.getNode(e);n&&R.updateNode({...n,log:[...n.log??[],t]})},NR=e=>{let t=[e],n=h().nodes[e]?.parentNodeId;return n&&t.push(n),t},yc=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 NR(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.swimlane.rule":case"remove.swimlane.rule":case"add.issue.goal":case"remove.issue.goal":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.goal":case"rename.goal":case"tombstone.goal":case"create.contributor":case"rename.contributor":case"link.contributor.user":case"link.contributor.email":case"unlink.contributor.email":case"connect.repo":case"edit.repo":case"disconnect.repo":default:return[]}},IR=e=>{pe(t=>({...t,eventLog:[...t.eventLog,e]}))},Kt=null,wR=e=>{for(let[t,n]of e.nodeLog){let r=R.getNode(t);r&&R.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&pe(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),pp([...e.virtualNodeIds])},fp={isInitialized:()=>gt(),batch:e=>zs(e),afterApply(e,{batched:t,bypassLogging:n}){let r=[...new Set(yc(e))];if(t){Kt??={appLog:[],nodeLog:new Map,virtualNodeIds:new Set};for(let o of r){if(!n){let s=Kt.nodeLog.get(o);s?s.push(e):Kt.nodeLog.set(o,[e])}if(vc()){Kt.virtualNodeIds.add(o);let s=h().nodes[o]?.parentNodeId;s&&Kt.virtualNodeIds.add(s)}}return n||Kt.appLog.push(e),null}return n||(r.forEach(o=>CR(o,e)),IR(e)),pp(r)},flush(){if(!Kt)return null;let e=Kt;return Kt=null,wR(e)}};var te=()=>{let{userName:e,userId:t}=ne();return e?t?ud(t)?md(e)?d("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")};var AR={genesis:"init.workspace",actions:fc,readPayload:lp,apply:up,replay:fp,write:{readOnlyReason:()=>{let e=h();return e.readOnly?e.readOnlyReason??"Cannot change the board while time travelling":null},beforeWrite:dp}},TR=ap(AR),{materialize:Ro,materializeAll:un,fromPersistedEvent:ZP,decodeReconstructedEvents:QP,loadMergedEventsWithUnreadable:Eo,loadEventActors:e0,loadActorNames:gp,loadMergedEvents:Vs,loadMergedEventsBefore:hp,getEdgeRef:t0,advanceEdgeRef:n0,clearEdgeCache:r0,getSortedEvents:o0,loadEffectiveEventTimes:yp,mintEventId:s0,persist:bp,materializeAndPersist:i0,materializeAndPersistAll:Y}=TR;var xc="Unchanged",Ks="Renamed ",PR={live:[],overLimit:[],disconnected:[]},So=null,OR=(e,t)=>{if(!gt())return null;let n=h();return n.timeMode==="live"&&n.replay===null&&km(e)===t?n.repos:null},ct=e=>{try{let t=ve({repoRoot:e});if(c(t))return a(t.message);let n=t.value,r=Tt(n);if(r==="none")return d("No log yet",PR);if(So&&So.root===n&&So.signature===r)return d("Read connected repos",So.repos);let o=OR(n,r);if(!o){let i=Vs(n);if(c(i))return a(i.message);o=vd(i.value)}let s=xd(o);return So={root:n,signature:r,repos:s},d("Read connected repos",s)}catch(t){return a(`Could not read the connected repos: ${t instanceof Error?t.message:String(t)}`)}},qs=e=>{let t=ct(e);return c(t)?a(t.message):d("Read other repos",t.value.live)},xp=(e,t)=>{let n=qs(e);return!c(n)&&n.value.some(r=>r.id===t)},Rc=e=>{let t=e.url.trim(),n=jr(t);if(n)return a(`That URL ${n}. ${fd}`);if(e.since!==void 0&&!Tn(e.since))return a(`"${e.since}" is not a history window: use board, all or YYYY-MM-DD.`);let r=e.label?.trim();if(r&&!Mn(r))return a(`"${r}" is not a label: up to 24 of a-z, 0-9, dot, dash or underscore, opening on a letter or digit.`);let o=ct(e.repoRoot);if(c(o))return a(o.message);let s=[...o.value.live,...o.value.overLimit],i=nn(t),l=s.find(g=>g.id===i),u=r===void 0?void 0:r===Pt(l?.url??t)?"":r;if(u&&s.some(g=>g.id!==i&&g.label===u))return a(`Another repo is already called ${u}`);let m={...e.branches?{branches:e.branches}:{},...e.since?{since:e.since}:{},...u!==void 0?{label:u}:{}};if(!l){let g={id:i,url:t,branches:e.branches??Zi,since:e.since??Qi,label:u||Pt(t)};return d("Plan",{kind:"connect",repo:g,event:{url:t,...e.branches?{branches:e.branches}:{},...e.since?{since:e.since}:{},...u?{label:u}:{}}})}let p={...l,branches:e.branches??l.branches,since:e.since??l.since,label:u===void 0?l.label:u||Pt(l.url)};if(p.branches===l.branches&&p.since===l.since&&p.label===l.label)return d("Plan",{kind:"unchanged",repo:l});let f=p.branches===l.branches&&p.since===l.since;return d("Plan",{kind:"edit",repo:p,event:{repo:i,...m},message:`${f?Ks:"Updated "}${p.label}`})},Co=e=>{let t=ve({repoRoot:e.repoRoot});if(c(t))return a(t.message);let n=Y([{id:LR(),userId:e.actorId,...e.event}],t.value);return c(n)?a(n.message):d("Wrote repo event",null)},Ec=e=>{let t=ct(e);return new Map(c(t)?[]:[...t.value.live,...t.value.overLimit].map(n=>[n.id,n.label]))},Sc=e=>e.map(t=>e.filter(n=>n.label===t.label).length===1?t.label:t.id),Ys=(e,t)=>{let n=t.trim(),r=e.filter(s=>s.label===n);if(r.length>1)return a(`Several repos are called ${n} \u2014 name one by its id or URL`);let o=r[0]??e.find(s=>s.id===n||tn(n)&&s.id===nn(n));return o?d("Found",o):a(`No repo "${n}" is connected`)},Cc=(e,t)=>{let n=ct(e);return c(n)?a(n.message):Ys([...n.value.live,...n.value.overLimit],t)},Nc=e=>vp.join(Ve(),"repos",/^[\w-]+$/.test(e)?e:MR("sha1").update(e).digest("hex")),Rp=/^[a-z0-9._-]+-[0-9a-f]{12}\.git$/,_t=(e,t)=>vp.join(Nc(e),`${t}.git`),Rr=e=>`${e}.json`,Xs=/^(?!-)[A-Za-z0-9._/-]{1,100}$/,Ep=e=>{try{let t=JSON.parse(kR.readFileSync(Rr(e),"utf8"));return typeof t.stateBranch=="string"&&Xs.test(t.stateBranch)?t.stateBranch:null}catch{return null}},mn=(e,t)=>e==="all"?null:e==="board"?t.slice(0,10):e,qt=e=>{let t=He(e);return c(t)?a(t.message):d("Read project",{projectId:t.value.projectId,createdAt:t.value.createdAt})};var DR=(e,t)=>{let n=(e.trim().split(/\s+/)[0]??"").toUpperCase();return n&&t.has(n)?n:null},Sp=(e,t)=>{let n=DR(e.subject,t),r=(e.refs??[]).map(o=>o.toUpperCase());return[...new Set([...n?[n]:[],...r])].filter(o=>t.has(o))};import{randomUUID as Po}from"node:crypto";import D from"node:fs";import J from"node:path";import{execFileSync as FR}from"node:child_process";import{randomUUID as Ip}from"node:crypto";import Je from"node:fs";import No from"node:os";import wp from"node:path";var Qs="epiq-sync.lock",_R=600*1e3,Ap=Date.now()-process.uptime()*1e3,Tp=()=>Math.round(Ap),Mp=5e3,$R=5e3,kp=e=>{try{if(process.platform==="linux"){let s=Je.readFileSync(`/proc/${e}/stat`,"utf8"),i=s.slice(s.lastIndexOf(")")+2).split(" "),l=Number(i[19]),u=/^btime (\d+)$/m.exec(Je.readFileSync("/proc/stat","utf8"))?.[1];return u&&Number.isFinite(l)?Number(u)*1e3+l*10:null}if(process.platform==="win32")return null;let t=Cp.get(e);if(t&&Date.now()-t.at<BR)return t.value;let n=FR("ps",["-o","lstart=","-p",String(e)],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"],env:{...process.env,LC_ALL:"C"}}).trim(),r=Date.parse(n),o=Number.isNaN(r)?null:r;return Cp.set(e,{at:Date.now(),value:o}),o}catch{return null}},Lp=(e,t)=>{let n=kp(e);return n!==null&&n>t+Mp},BR=5e3,Cp=new Map,UR=e=>{let t=Date.now()-No.uptime()*1e3;if(e.startedAt<t)return!1;if(Date.now()-e.startedAt<$R||e.processStartedAt===void 0)return!0;let n=kp(e.pid);return n===null||Math.abs(n-e.processStartedAt)<=Mp},Js=new Map,jR=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}},HR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Pp=(e,t=_R,n=!1)=>e?e.hostname!==No.hostname()?Date.now()-e.startedAt>t?"stale":null:!HR(e.pid)||n&&!UR(e)?"dead":Date.now()-e.startedAt>t?"stale":null:"stale",WR=e=>{let t=wp.join(e,Qs);return Je.existsSync(t)?Pp(Er(t))===null:!1},Zs=new Map,GR=e=>{let t=Zs.get(e);if(t)return t;let n=Vr(e).then(r=>c(r)?null:r.value,()=>null);return Zs.set(e,n),n.then(r=>{r===null&&Zs.get(e)===n&&Zs.delete(e)}),n},j0=async e=>{let t=await GR(e);return t!==null&&WR(t)},Op=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,Er=e=>{try{return jR(Je.readFileSync(e,"utf8"))}catch{return null}},zR=(e,t)=>{let n={pid:process.pid,hostname:No.hostname(),startedAt:Date.now(),operation:t,token:Ip(),processStartedAt:Ap},r=`${e}.${process.pid}.pending.lock`;try{return Je.writeFileSync(r,JSON.stringify(n)),Je.linkSync(r,e),n}catch{return null}finally{try{Je.rmSync(r,{force:!0})}catch{}}},VR=async({worktreeRoot:e,operation:t})=>{let n=await Vr(e);return c(n)?a(n.message):d("Tried the sync lock",Io({lockPath:wp.join(n.value,Qs),operation:t}))},Io=({lockPath:e,operation:t,staleAfterMs:n,checkProcess:r=!1})=>{let o=null,s=()=>{try{let u=Er(e);u&&Np(u,o)&&Je.rmSync(e)}catch{}finally{Js.get(e)===o?.token&&Js.delete(e)}},i=u=>(o=zR(e,t),o?(Js.set(e,o.token),{acquired:!0,claim:u,release:s}):null);for(let u=0;u<5;u++){let m=i("clean");if(m)return m;let p=Er(e);if(p===null&&(!Je.existsSync(e)||(p=Er(e),p!==null)||!Je.existsSync(e)))continue;let g=p!==null&&p.pid===process.pid&&p.hostname===No.hostname()&&Js.get(e)!==p.token?"dead":Pp(p,n,r);if(g===null)return{acquired:!1,heldBy:p};V.info(`Breaking an abandoned sync lock: ${p?Op(p):"unreadable lock file"}`);let v=`${e}.${process.pid}.${Ip()}.broken.lock`;try{Je.renameSync(e,v)}catch{continue}if(!Np(Er(v),p)){try{Je.linkSync(v,e)}catch{}Je.rmSync(v,{force:!0});continue}Je.rmSync(v,{force:!0});let I=i(g);if(I)return I}return{acquired:!1,heldBy:Er(e)??{pid:-1,hostname:No.hostname(),startedAt:Date.now(),operation:"unknown"}}},Np=(e,t)=>e===null||t===null?e===t:e.pid===t.pid&&e.hostname===t.hostname&&e.startedAt===t.startedAt&&e.token===t.token,wo=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await VR({worktreeRoot:e,operation:t});if(c(r))return a(r.message);if(!r.value.acquired)return V.info(`Skipping ${t}: the state worktree is held by ${Op(r.value.heldBy)}`),d("State worktree is held by another process",null);let{claim:o,release:s}=r.value;try{return d("Ran under the sync lock",await n(o))}finally{s()}};import{randomBytes as JR}from"node:crypto";import ZR from"node:fs";var KR="EPIQ_CACHE_MS",ei=e=>{let t=process.env[KR];if(t===void 0||t.trim()==="")return e;let n=Number(t);return Number.isFinite(n)&&n>=0?n:e};import Dp from"node:fs";import qR from"node:path";var Fp=new Set,Ic=new Map,wc=(e,t)=>{t?Ic.set(e,t):Ic.delete(e)},_p=e=>Ic.get(e)??null,YR=e=>{try{return new Set(Dp.readFileSync(qR.join(e,"shallow"),"utf8").split(`
37
+ `).map(t=>t.trim()).filter(Boolean))}catch{return Fp}},Vn=async e=>{let t=At(e);if(c(t))return a(t.message);let n=t.value,r=He(n);if(c(r))return a(r.message);let o={cwd:n,revisions:["--branches","--not",r.value.stateBranch],exclude:Fp},s=qs(n);if(c(s))return d("Listed sources",[o]);let i=s.value.flatMap(l=>{let u=_t(r.value.projectId,l.id);if(!Dp.existsSync(u))return[];let m=mn(l.since,r.value.createdAt),p=new Set([r.value.stateBranch,La,Ep(u)].filter(f=>f!==null));return[{repo:l.id,cwd:u,revisions:[...[...p].map(f=>`--exclude=${f}`),"--branches"],exclude:YR(u),...m?{notBefore:Date.parse(`${m}T00:00:00Z`)}:{}}]});return d("Listed sources",[o,...i])},Ac=e=>t=>e.find(n=>(n.repo??"")===(t??""))?.cwd,XR=async(e,t)=>!c(await _({cwd:e,args:["cat-file","-e",`${t}^{commit}`]})),Ao=async e=>{let t=await Vn(e.repoRoot);if(c(t))return a(t.message);let n=t.value;if(e.repo){let r=n.find(o=>o.repo===e.repo);return r?d("Resolved repo",r.cwd):a(`No clone of repo "${e.repo}" here yet \u2014 sync to fetch it`)}if(n.length===1)return d("Resolved repo",n[0].cwd);for(let r of n)if(await XR(r.cwd,e.sha))return d("Resolved repo",r.cwd);return d("Resolved repo",n[0].cwd)};var Tc="",QR="",$p=5e3,eE=12e4,tE=32*1024*1024,ti=new Map,nE=e=>{try{return ZR.statSync(`${e}.json`).mtimeMs}catch{return null}},rE=()=>{let e=JR(8).toString("hex");return{field:`${Tc}${e}`,record:`${QR}${e}`,body:`${Tc}B${e}`,end:`${Tc}E${e}`}},oE=/^[ \t]*Epiq-Ref:[ \t]*(.*)$/gim,sE=new RegExp(`^[0-9A-HJKMNP-TV-Z]{${7}}$`,"i"),kc=e=>[...new Set([...e.matchAll(oE)].flatMap(t=>t[1].split(/[\s,]+/)).filter(t=>sE.test(t)).map(t=>t.toUpperCase()))],iE=/^[0-9a-f]{40}([0-9a-f]{24})?$/;var fn=()=>{ti.clear()},Bp=(e,t,n)=>(t===void 0||e>=Math.floor(t/1e3)*1e3)&&(n===void 0||e<=n),Mc=e=>ut(e).replace(/[\u0080-\u009f\u202a-\u202e\u2066-\u2069]/g,""),aE=async(e,t)=>{let n=t.start===void 0&&t.end===void 0,r=[e.cwd,e.revisions.join(" "),e.notBefore??"",e.exclude.size].join("\0"),o=n?ti.get(r):void 0,s=e.repo?nE(e.cwd):null;if(o&&(e.repo?o.version===s:Date.now()-o.fetchedAt<ei($p)))return o.result;let i=rE(),l=await _({cwd:e.cwd,...e.repo?{timeoutMs:eE,maxOutput:tE}:{},args:["log",...e.revisions,...t.start!==void 0?[`--since=@${Math.floor(t.start/1e3)}`]:[],...t.end!==void 0?[`--until=@${Math.floor(t.end/1e3)}`]:[],"--shortstat",`--format=${i.record}%H${i.field}%at${e.notBefore?`${i.field}%ct`:""}${i.field}%an${i.field}%ae${i.field}%s${i.body}%b${i.end}`]});if(c(l))return e.repo&&n&&!tu(l.message)&&ti.set(r,{fetchedAt:Date.now(),version:s,result:a(l.message)}),a(l.message);let u=l.value.stdout.split(i.record).filter(m=>m.trim().length>0).map(m=>{let p=m.indexOf(i.end),[f="",...g]=m.split(`
38
+ `),v=p===-1?f:m.slice(0,p),I=p===-1?g:m.slice(p+i.end.length).split(`
39
+ `),x=v.indexOf(i.body),E=x===-1?v:v.slice(0,x),N=x===-1?[]:kc(v.slice(x+i.body.length)),S=E.split(i.field),[T,k]=S;if(e.repo&&!iE.test(T??""))return null;let H=e.notBefore?S[2]:void 0,[L,P,...$]=S.slice(e.notBefore?3:2);if(!T||!k||e.exclude.has(T)||e.notBefore&&Number(H)*1e3<e.notBefore)return null;let de=I.join(" "),B=Number(/(\d+) insertion/.exec(de)?.[1]??0),F=Number(/(\d+) deletion/.exec(de)?.[1]??0);return{sha:T,...e.repo?{repo:e.repo}:{},time:Number(k)*1e3,author:Mc(L)||"unknown",authorEmail:Mc(P),subject:Mc($.join(i.field)),...N.length>0?{refs:N}:{},linesChanged:B+F,insertions:B,deletions:F}}).filter(m=>m!==null).filter(m=>Bp(m.time,t.start,t.end));return n&&ti.set(r,{fetchedAt:Date.now(),version:s,result:d("Computed commit timeline",u)}),d("Computed commit timeline",u)},Up=async(e,t)=>{let n=await Vn(e);if(c(n))return a(n.message);let r=n.value,o=[];for(let i of r)o.push(await aE(i,t));let s=[];for(let[i,l]of o.entries()){let u=r[i].repo;if(c(l)){if(!u)return a(l.message);V.info(`[repos] could not read a clone: ${l.message}`),wc(u,gs(l.message)?"its history is too long to read; narrow its window":"its history could not be read");continue}u&&wc(u,null),s.push(l.value)}return d("Read every source",s)},To=e=>{if(e.length<=1)return e;let t=new Set;return e.map(n=>{let r=n.filter(o=>!t.has(o.sha));for(let o of r)t.add(o.sha);return r})},jp=e=>{let t=e.filter(n=>n.length>0);return t.length<=1?t[0]??[]:t.flat().sort((n,r)=>r.time-n.time)},cE=async(e={})=>{let t=await Up(e.repoRoot,{start:e.start,end:e.end});return c(t)?a(t.message):d("Computed commit timeline",jp(To(t.value)))},Hp=async e=>{let t=e.refs.find(s=>s.length!==7);if(t!==void 0)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 Up(e.repoRoot,{});if(c(n))return a(n.message);let r=new Set(e.refs.map(s=>s.toUpperCase())),o=s=>{let i=s.subject.slice(0,7).toUpperCase(),l=s.subject[7]===" "&&r.has(i)?[i]:[],u=(s.refs??[]).filter(m=>r.has(m));return u.length>0?[...new Set([...l,...u])].sort():l};return d("Matched commits by ref",n.value.map(s=>{let i=[];for(let[l,u]of s.entries()){let m=o(u);if(m.length===0||!Bp(u.time,void 0,e.end))continue;let p=s[l+1];i.push({...u,tickets:m,precedingSha:p&&o(p).some(f=>m.includes(f))?p.sha:null})}return i}))},Lc=async e=>{let t=e.ref.trim();if(!t)return a("ref must not be empty");let n=await Hp({...e,refs:[t]});return c(n)?a(n.message):d(n.message,n.value.map(r=>r.map(({tickets:o,...s})=>s)))},Pc=async e=>{let t=await Lc(e);return c(t)?a(t.message):d("Matched commits by ref",jp(To(t.value)))},lE=async e=>{let t=await Hp(e);return c(t)?a(t.message):d("Matched commits by refs",To(t.value).flat().sort((n,r)=>r.time-n.time||(n.repo??"").localeCompare(r.repo??"")||n.sha.localeCompare(r.sha)))};var ni=1800*1e3,Bt=e=>`${e}.removed`,Wp=e=>{try{D.writeFileSync(Bt(e),"",{flag:"wx"})}catch(t){if(t.code!=="EEXIST")throw t;if(ri(Bt(e)))throw new Error("The removal mark is a link, which epiq will not use")}},_c=()=>`${process.pid}-${Tp()}`,Fc=e=>{try{let t=JSON.parse(D.readFileSync(Rr(e),"utf8"));return{fetchedAt:typeof t.fetchedAt=="number"?t.fetchedAt:null,attemptedAt:typeof t.attemptedAt=="number"?t.attemptedAt:null,error:typeof t.error=="string"?t.error:null,branches:t.branches==="all"||t.branches==="default"?t.branches:null,since:typeof t.since=="string"?t.since:null,restartedAt:typeof t.restartedAt=="number"?t.restartedAt:null,restartTriedAt:typeof t.restartTriedAt=="number"?t.restartTriedAt:null,restarts:typeof t.restarts=="number"&&t.restarts>=0?t.restarts:0,bytes:typeof t.bytes=="number"&&t.bytes>=0?t.bytes:null,stateBranch:typeof t.stateBranch=="string"&&Xs.test(t.stateBranch)?t.stateBranch:null}}catch{return null}},Xp=(e,t)=>{try{let n=`${Rr(e)}.${_c()}.${Po()}.tmp`;D.writeFileSync(n,JSON.stringify(t)+`
40
+ `,{flag:"wx"}),D.renameSync(n,Rr(e))}catch(n){V.info(`[repos] could not record fetch status: ${String(n)}`)}},$c=e=>{let t=qt(e);if(c(t))return a(t.message);let n=ct(e);if(c(n))return a(n.message);let r=(o,s)=>{let i=_t(t.value.projectId,o.id),l=Fc(i),u=D.existsSync(i);return{...o,cloned:u,overLimit:s,bytes:u?l?.bytes??null:null,fetchedAt:l?.fetchedAt??null,error:l?.error??_p(o.id)}};return d("Listed repos",[...n.value.live.map(o=>r(o,!1)),...n.value.overLimit.map(o=>r(o,!0))])},Se=e=>_({...e,forClone:!0}),dE=(e,t)=>Se({cwd:e,args:t,timeoutMs:ni}),uE=1e3,ko=async(e,t,n,{undo:r}={})=>{let o=br(),s=o*1024*1024,i=new AbortController,l=setInterval(()=>{cn(n)>s&&i.abort(po(o))},uE),u;try{u=await Se({cwd:e,args:t,timeoutMs:ni,abort:i.signal})}finally{clearInterval(l)}return i.signal.aborted||!c(u)&&cn(n)>s?(Zp(n),r&&(fE(n,r),df(n)),a(po(o))):u},Mo=e=>{try{return D.readFileSync(e)}catch{return null}},Bc=e=>{try{return D.readdirSync(e)}catch{return[]}},mE=e=>{let t=new Map,n=r=>{let o=J.join(e,r);for(let s of D.readdirSync(o,{withFileTypes:!0})){let i=J.join(r,s.name);s.isDirectory()?n(i):t.set(i,D.readFileSync(J.join(e,i)))}};return D.existsSync(J.join(e,"refs"))&&n("refs"),{refs:t,packedRefs:Mo(J.join(e,"packed-refs")),head:Mo(J.join(e,"HEAD")),config:Mo(J.join(e,"config")),shallow:Mo(J.join(e,"shallow")),packs:new Set(Bc(J.join(e,"objects","pack")))}},Jp="epiq-restore-",Gp=(e,t,n)=>{let r=J.join(e,`${Jp}${Po()}.tmp`);D.writeFileSync(r,n,{flag:"wx"}),D.mkdirSync(J.dirname(J.join(e,t)),{recursive:!0}),D.renameSync(r,J.join(e,t))},pE=e=>{let t=[],n=r=>{for(let o of D.readdirSync(J.join(e,r),{withFileTypes:!0})){let s=J.join(r,o.name);o.isDirectory()?n(s):t.push(s)}};return D.existsSync(J.join(e,"refs"))&&n("refs"),t},fE=(e,t)=>{for(let[r,o]of t.refs)Gp(e,r,o);for(let r of pE(e))t.refs.has(r)||D.rmSync(J.join(e,r),{force:!0});for(let[r,o]of[["packed-refs",t.packedRefs],["HEAD",t.head],["config",t.config],["shallow",t.shallow]])o?Gp(e,r,o):D.rmSync(J.join(e,r),{force:!0});let n=J.join(e,"objects","pack");for(let r of Bc(n))t.packs.has(r)||D.rmSync(J.join(n,r));Kn.delete(e)},Zp=e=>{let t=J.join(e,"objects");for(let[n,r]of[[J.join(t,"pack"),"tmp_"],[J.join(t,"pack"),".tmp-"],[t,"incoming-"],[e,Jp]])try{for(let o of D.readdirSync(n))o.startsWith(r)&&D.rmSync(J.join(n,o),{recursive:!0,force:!0})}catch{}},gE=/could not read from remote repository|the remote end hung up unexpectedly|early EOF|fetch-pack: invalid index-pack output/i,Qp=e=>{let t=e.split(`
41
+ `).map(s=>s.replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g,"").trim()).filter(s=>s&&!s.startsWith("git ")),n=t.filter(s=>/^(fatal|error):/i.test(s));return(n.filter(s=>!gE.test(s))[0]??n[n.length-1]??t[t.length-1]??e).replace(/^(fatal|error):\s*/i,"").slice(0,300)},hE=64*1024,ef=async e=>{let t="HEAD:.epiq/project.json",n=await Se({cwd:e,args:["cat-file","-s",t]});if(c(n)||!(Number(n.value.stdout.trim())<=hE))return null;let r=await Se({cwd:e,args:["cat-file","blob",t]});if(c(r))return null;try{let{stateBranch:o}=JSON.parse(r.value.stdout);return typeof o=="string"&&Xs.test(o)?o:null}catch{return null}},Uc=async e=>{let t=await Se({cwd:e,args:["symbolic-ref","--short","HEAD"]});return c(t)?null:t.value.stdout.trim()||null},yE=async(e,t)=>{if(t==="all")return d("All branches","+refs/heads/*:refs/heads/*");let n=await Uc(e);return n?d("Default branch",`+refs/heads/${n}:refs/heads/${n}`):a("Could not tell which branch is the default")},bE=async e=>{let t=await Uc(e);if(!t)return;let n=await Se({cwd:e,args:["for-each-ref","--format=%(refname)","refs/heads/"]});if(!c(n))for(let r of n.value.stdout.split(`
42
+ `).filter(Boolean))r!==`refs/heads/${t}`&&await Se({cwd:e,args:["update-ref","-d",r]})},tf=async e=>{let t=await Se({cwd:e,args:["for-each-ref","--count=1","--format=x","refs/heads/"]});return!c(t)&&t.value.stdout.trim()!==""},nf=e=>Math.floor(Date.parse(`${e}T00:00:00Z`)/1e3),rf=e=>`--shallow-since=@${nf(e)}`,of=async(e,t)=>{let n=await Se({cwd:e,args:["for-each-ref","--format=%(committerdate:unix)","refs/heads/"]});return c(n)?!0:n.value.stdout.split(`
43
+ `).filter(Boolean).some(r=>Number(r)>=nf(t))},sf=async(e,t)=>{if(!await tf(e))return d("Empty",null);let n=await ko(e,["fetch","--no-tags","--deepen=1","origin"],e,{undo:t});return c(n)?a(n.message):d("Deepened",null)},af=async(e,t,n)=>{let r=J.dirname(e);D.mkdirSync(r,{recursive:!0}),D.rmSync(e,{recursive:!0,force:!0});let o=async(i,l)=>{let u=await ko(r,["clone","--bare","--no-tags",t.branches==="default"?"--single-branch":"--no-single-branch",...i,"--",t.url,e],e);if(c(u))return a(u.message);let m=await yE(e,t.branches);return c(m)?a(m.message):(await Se({cwd:e,args:["config","remote.origin.fetch",m.value]}),l?sf(e):d("Cloned",null))},s=await o(n?[rf(n)]:[],!!n);if(c(s)&&n){let i=s;D.rmSync(e,{recursive:!0,force:!0}),s=await o(["--depth=1"],!1),!c(s)&&await of(e,n)&&(s=i)}return c(s)?(D.rmSync(e,{recursive:!0,force:!0}),a(s.message)):d("Built clone",null)},zp=async(e,t,n,{replace:r=!1}={})=>{let o=`${e}.${_c()}.pending`,s=await af(o,t,n);if(c(s))return s;if(r&&D.existsSync(e)){let i=`${e}.${Po()}.deleting`;D.renameSync(e,i),D.renameSync(o,e);try{D.rmSync(i,{recursive:!0,force:!0})}catch(l){V.info(`[repos] could not clear an old clone: ${lt(l)}`)}return d("Cloned anew",null)}return D.existsSync(e)?(D.rmSync(o,{recursive:!0,force:!0}),d("Cloned elsewhere",null)):ri(e)?(D.rmSync(o,{recursive:!0,force:!0}),a("The clone path is a link, which epiq will not use")):(D.renameSync(o,e),d("Cloned",null))},vE=async(e,t)=>!/[*:]/.test(t)&&!c(await Se({cwd:e,args:["check-ref-format",`refs/heads/${t}`]})),cf=async e=>{let t=await dE(e,["ls-remote","--symref","origin","HEAD"]);if(c(t))return null;let n=/^ref: refs\/heads\/(\S+)\tHEAD$/m.exec(t.value.stdout)?.[1],r=/^[0-9a-f]{40,64}\tHEAD$/m.test(t.value.stdout);return n&&r&&await vE(e,n)?n:null},lf=async(e,t)=>{let n=t??await cf(e);if(!n)return a("Could not tell which branch the remote now defaults to");let r=await Se({cwd:e,args:["symbolic-ref","HEAD",`refs/heads/${n}`]});if(c(r))return a(r.message);let o=await Se({cwd:e,args:["config","remote.origin.fetch",`+refs/heads/${n}:refs/heads/${n}`]});return c(o)?a(o.message):d("Followed",null)},df=e=>{let t=(n,r)=>{for(let o of D.readdirSync(n,{withFileTypes:!0})){let s=J.join(n,o.name);o.isFile()&&o.name.endsWith(".lock")?D.rmSync(s,{force:!0}):o.isDirectory()&&r>0&&t(s,r-1)}};try{for(let r of D.readdirSync(e))r.endsWith(".lock")&&D.rmSync(J.join(e,r),{force:!0});let n=J.join(e,"refs");D.existsSync(n)&&t(n,16)}catch(n){V.info(`[repos] could not clear stale locks: ${String(n)}`)}},uf=e=>D.existsSync(J.join(e,"shallow")),xE=20,RE=async e=>{if(Bc(J.join(e,"objects","pack")).filter(r=>r.endsWith(".pack")).length<=xE)return;let n=await Se({cwd:e,args:["repack","--geometric=2","-d","-q"],timeoutMs:ni});c(n)&&V.info(`[repos] repack: ${n.message}`)},EE=async e=>{let t=await Se({cwd:e,args:["config","--get","remote.origin.fetch"]});return c(t)?null:t.value.stdout.trim()||null},SE=e=>`+refs/heads/${e}:refs/heads/${e}`,CE=async(e,t)=>{let n=await EE(e);if(t==="all"){let s="+refs/heads/*:refs/heads/*";if(n===s)return d("Tracking",null);let i=await Se({cwd:e,args:["config","remote.origin.fetch",s]});return c(i)?a(i.message):d("Tracking",null)}let r=await Uc(e),o=await cf(e)??r;return o?r===o&&n===SE(o)?d("Tracking",null):lf(e,o):a("Could not tell which branch is the default")},Vp=async(e,t,n,r)=>{let o=br();if(cn(e)>o*1024*1024)return a(po(o));let s=mE(e),i=await CE(e,t.branches);if(c(i))return a(i.message);let l=n===null?uf(e)?["--unshallow"]:[]:r?.since&&n<r.since?[rf(n)]:[],u=["fetch","--prune","--no-tags",...l,"origin"],m=await ko(e,u,e,{undo:s});if(c(m)&&t.branches==="default"&&/couldn't find remote ref/i.test(m.message)){let g=await lf(e);if(c(g))return a(g.message);m=await ko(e,u,e,{undo:s})}let p=n!==null&&l.length>0,f=c(m)&&p;if(f){let g=m;if(m=await ko(e,["fetch","--prune","--no-tags","origin"],e,{undo:s}),!c(m)&&await of(e,n))return a(g.message)}if(c(m))return a(m.message);if(p&&!f){let g=await sf(e,s);if(c(g))return a(g.message)}return t.branches==="default"&&await bE(e),await RE(e),d("Fetched",null)},Oc=async e=>{if(!D.existsSync(e))return"";let t=await Se({cwd:e,args:["for-each-ref","--format=%(objectname) %(refname)"]}),n=uf(e)?D.readFileSync(J.join(e,"shallow"),"utf8"):"";return`${c(t)?"":t.value.stdout}
44
+ ${n}`},Kn=new Map,Kp=(e,t)=>{let n=Kn.get(e);return Kn.set(e,t),n!==void 0&&n!==t},NE=async(e,t)=>{let n=await Se({cwd:e,args:["config","--get","remote.origin.url"]});return c(n)?"unknown":nn(n.value.stdout.trim())===t.id?"this":"other"},mf=e=>{let t=J.join(e,".gitignore");try{if(D.lstatSync(t,{throwIfNoEntry:!1}))return;D.writeFileSync(t,`*
45
+ `,{flag:"wx"})}catch(n){V.info(`[repos] could not write ${t}: ${lt(n)}`)}},ri=e=>{try{return D.lstatSync(e).isSymbolicLink()}catch{return!1}},lt=e=>e instanceof Error?e.message:String(e),jc=".lock",Hc=ni*4,pf=async(e,t,n)=>{let r=Date.now()+n;for(;;){let o=Io({lockPath:`${e}${jc}`,operation:t,staleAfterMs:Hc,checkProcess:!0});if(o.acquired||Date.now()>=r)return o;await new Promise(s=>setTimeout(s,250))}},Lo=e=>{let t=`${e}.${Po()}.deleting`;try{D.renameSync(e,t)}catch(n){if(n.code!=="ENOENT")throw n}D.rmSync(t,{recursive:!0,force:!0}),D.rmSync(Rr(e),{force:!0}),D.rmSync(Bt(e),{force:!0}),Kn.delete(e)},ff=5e3,IE=async e=>{let t=await Se({cwd:e,args:["config","--get","remote.origin.url"]});if(c(t)||!t.value.stdout.trim())return!1;let n=Mo(J.join(e,"shallow"));return n&&!/^(?:[0-9a-f]{40}(?:[0-9a-f]{24})?\n)*$/.test(n.toString("utf8"))?!1:await tf(e)?!c(await Se({cwd:e,args:["rev-list","--max-count=1","--branches"]})):!0},qp=[0,6e4,10*6e4,60*6e4],gf=e=>{if(!e?.restartTriedAt||Date.now()<e.restartTriedAt)return!0;let t=qp[Math.min(e.restarts,qp.length-1)];return Date.now()-e.restartTriedAt>=t},wE=360*60*1e3,AE=e=>{let t=e?.restartTriedAt??e?.restartedAt;return gf(e)&&(!t||Date.now()<t||Date.now()-t>=wE)},TE=6e4,ME=async(e,t,n)=>{let r=br();return cn(e)>r*1024*1024?"past the cap":n.endsWith(po(r))?null:await hf(e,t)?"remote answers":null},hf=async(e,t)=>!c(await Se({cwd:J.dirname(e),args:["ls-remote","--",t.url,"HEAD"],timeoutMs:TE})),kE=async(e,t,n,r,o)=>{let s=(p,f,g=!1)=>({id:r.id,label:r.label,ok:p,changed:g,message:f}),i=_t(t,r.id),l=mn(r.since,n);try{D.mkdirSync(J.dirname(i),{recursive:!0}),mf(J.dirname(i))}catch(p){return s(!1,lt(p))}let u=Fc(i);if(u?.attemptedAt&&(u.error!==null||u.branches===r.branches&&u.since===l)&&Date.now()>=u.attemptedAt&&Date.now()-u.attemptedAt<o&&!D.existsSync(Bt(i))){let p=D.existsSync(i)&&Kp(i,await Oc(i));return u.error?s(!1,u.error,p):s(!0,"Fetched recently",p)}if(ri(i))return s(!1,"The clone path is a link, which epiq will not use");let m=await pf(i,`fetch ${r.label}`,o===0?ff:0);if(!m.acquired)return{...s(!0,"Being fetched by another process"),skipped:!0};try{let p=D.existsSync(Bt(i));p&&Lo(i);let f=D.existsSync(i);f&&await NE(i,r)==="other"&&(Lo(i),f=!1);let g=f?Fc(i):null;if(f&&!Kn.has(i)&&Kn.set(i,await Oc(i)),f&&(df(i),Zp(i)),!f&&p&&!xp(e,r.id))return s(!0,"Removed before it was cloned");let I=f&&!await IE(i)&&gf(g),x=I&&await hf(i,r),E=f?I?a(x?"Its clone will not open":"Its clone will not open, and its remote does not answer"):await Vp(i,r,l,g):await zp(i,r,l);if(f&&!x&&c(E)&&AE(g)){let k=await ME(i,r,E.message);k==="remote answers"&&(E=await Vp(i,r,l,g)),x=k!==null&&c(E)}x&&(V.info(`[repos] ${r.label}: starting its clone over`),E=await zp(i,r,l,{replace:!0}),Kn.delete(i));let N=x&&!(c(E)&&du()),S=c(E)?Qp(E.message):"Fetched",T=c(E)?g?.stateBranch??null:await ef(i);return Xp(i,{fetchedAt:c(E)?g?.fetchedAt??null:Date.now(),attemptedAt:Date.now(),error:c(E)?S:null,branches:c(E)?g?.branches??r.branches:r.branches,since:c(E)?g?.since??l:l,stateBranch:T,restartedAt:x&&!c(E)?Date.now():g?.restartedAt??null,restartTriedAt:N?Date.now():g?.restartTriedAt??null,restarts:N?(g?.restarts??0)+1:c(E)?g?.restarts??0:0,bytes:c(E)?g?.bytes??null:cn(i)}),c(E)?(V.info(`[repos] ${r.label}: ${E.message}`),s(!1,S)):s(!0,S,Kp(i,await Oc(i))||!f||x)}catch(p){return V.info(`[repos] ${r.label}: ${lt(p)}`),s(!1,lt(p))}finally{try{D.existsSync(Bt(i))&&Lo(i)}catch(p){V.info(`[repos] ${r.label}: could not delete the clone: ${lt(p)}`)}m.release(),yf(i)}},yf=e=>{if(!D.existsSync(Bt(e)))return;let t=Io({lockPath:`${e}${jc}`,operation:"remove",staleAfterMs:Hc,checkProcess:!0});if(t.acquired)try{D.existsSync(Bt(e))&&Lo(e)}catch(n){V.info(`[repos] could not delete a clone: ${lt(n)}`)}finally{t.release()}},LE=e=>{let t=Nc(e);if(D.existsSync(t))for(let n of D.readdirSync(t)){let r=/^.+\.git(?:\.json)?\.(\d+)(?:-(\d+))?(?:\.[0-9a-f-]{36})?\.(?:pending|tmp)$/.exec(n);if(r&&!OE(Number(r[1]),r[2]===void 0?null:Number(r[2]))||/\.git\.[0-9a-f-]{36}\.deleting$/.test(n))try{D.rmSync(J.join(t,n),{recursive:!0,force:!0})}catch(o){V.info(`[repos] could not sweep ${n}: ${lt(o)}`)}}},bf=async(e,t)=>{let n=qt(e);if(c(n))return a(n.message);let r=_t(n.value.projectId,t.id),o=`${r}.${_c()}.${Po()}.pending`;try{D.mkdirSync(J.dirname(r),{recursive:!0}),mf(J.dirname(r));let s=await af(o,t,mn(t.since,n.value.createdAt));return c(s)?a(Qp(s.message)):d("Staged",{stagePath:o,bytes:cn(o)})}catch(s){return $t(o),a(lt(s))}},$t=e=>{try{D.rmSync(e,{recursive:!0,force:!0})}catch(t){V.info(`[repos] could not clear a stage: ${lt(t)}`)}},vf=async(e,t,n)=>{let r=qt(e);if(c(r))return $t(n);let{projectId:o,createdAt:s}=r.value,i=_t(o,t.id),l=await pf(i,`connect ${t.label}`,ff);if(!l.acquired)return $t(n);try{if(D.rmSync(Bt(i),{force:!0}),D.existsSync(i)||ri(i))return $t(n);D.renameSync(n,i),Xp(i,{fetchedAt:Date.now(),attemptedAt:Date.now(),error:null,branches:t.branches,since:mn(t.since,s),stateBranch:await ef(i),restartedAt:null,restartTriedAt:null,restarts:0,bytes:cn(i)}),fn()}catch(u){V.info(`[repos] could not place ${t.label}: ${lt(u)}`),$t(n)}finally{l.release()}},Wc=e=>{let t=Cc(e.repoRoot,e.repo);if(c(t))return t;let n=Co({repoRoot:e.repoRoot,actorId:e.actorId,event:{action:"disconnect.repo",payload:{repo:t.value.id}}});if(c(n))return a(n.message);let r=Gc({repoRoot:e.repoRoot,repoId:t.value.id});fn();let o=qt(e.repoRoot);!c(r)&&!c(o)&&xf(o.value.projectId,t.value.id);let s=`Disconnected ${t.value.label}`;return c(r)?d(`${s}, but its clone stays: ${r.message}`,t.value):d(s,t.value)},Gc=e=>{let t=qt(e.repoRoot);if(c(t))return a(t.message);if(!Rp.test(`${e.repoId}.git`))return a("Not a clone epiq made");let n=_t(t.value.projectId,e.repoId);try{D.mkdirSync(J.dirname(n),{recursive:!0})}catch(o){return a(`Could not remove the clone: ${lt(o)}`)}let r=Io({lockPath:`${n}${jc}`,operation:"remove",staleAfterMs:Hc,checkProcess:!0});try{return r.acquired?(Lo(n),Wp(n),d("Removed clone",null)):(Wp(n),yf(n),d("Removed once its fetch ends",null))}catch(o){return a(`Could not remove the clone: ${String(o)}`)}finally{r.acquired&&r.release()}},xf=(e,t)=>{let n=_t(e,t);D.existsSync(n)||D.rmSync(Bt(n),{force:!0})},PE=(e,t,n)=>{for(let r of n){if(!D.existsSync(_t(t,r)))continue;let o=Gc({repoRoot:e,repoId:r});if(c(o)){V.info(`[repos] could not clear ${r}: ${o.message}`);continue}fn(),xf(t,r)}},OE=(e,t)=>DE(e)&&(t===null||!Lp(e,t)),DE=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Yp=4,oi=e=>{let t=e.minIntervalMs??0,n=Dc.get(e.repoRoot);if(n)return n.minIntervalMs<=t?n.result:n.result.then(()=>oi(e));let r=FE(e.repoRoot,t).catch(o=>a(lt(o))).finally(()=>{Dc.delete(e.repoRoot)});return Dc.set(e.repoRoot,{result:r,minIntervalMs:t}),r},Dc=new Map,FE=async(e,t)=>{let n=qt(e);if(c(n))return a(n.message);let r=ct(e);if(c(r))return a(r.message);let{projectId:o,createdAt:s}=n.value,i=r.value.live;try{LE(o)}catch(u){V.info(`[repos] sweep failed: ${String(u)}`)}if(PE(e,o,r.value.disconnected),i.length===0)return d("No other repos",[]);let l=[];for(let u=0;u<i.length;u+=Yp)l.push(...await Promise.all(i.slice(u,u+Yp).map(m=>kE(e,o,s,m,t))));return l.some(u=>u.changed)&&fn(),d("Fetched other repos",l)},zc=e=>{let t=e.filter(o=>!o.ok),n=e.filter(o=>o.skipped),r=[t.length>0&&`could not fetch ${t.map(o=>`${o.label} (${o.message.slice(0,80)})`).join(", ")}`,n.length>0&&`another process is fetching ${n.map(o=>o.label).join(", ")}`].filter(Boolean);return r.length>0?r.join("; "):null};var Kc=900*1e3,Sr=new Map,Rf=0,qc=new Map,Ef=e=>{let t=(qc.get(e)??0)+1;return qc.set(e,t),t},_E=(e,t)=>JSON.stringify([e,t.id,t.branches,t.since]),Yc=e=>{let t=Sr.get(e);t&&(clearTimeout(t.timer),Sr.delete(e),$t(t.stagePath))},$E=e=>{Ef(e),Yc(e)},Sf=e=>{if(e.startsWith("file:"))return"this machine";let t=/^[^@/]+@([^:/]+):/.exec(e);if(t?.[1])return t[1];try{return new URL(e).host||e}catch{return e}},Vc=async(e,t)=>{let n=await _({cwd:e,args:t,forClone:!0,keepPartial:!0});return c(n)?null:n.value.stdout},BE=async(e,t,n)=>{let r=(await Vc(e,["symbolic-ref","--short","HEAD"]))?.trim().replace(/^refs\/heads\//,""),o=await Vc(e,["log","-1","--format=%s%x00%an%x00%cI","HEAD"]),[s,i,l]=(o??"").trim().split("\0"),m=(await Vc(e,["log","--branches","--max-count=100000",...t?[`--since=@${Math.floor(Date.parse(`${t}T00:00:00Z`)/1e3)}`]:[],"--format=%x1e%s%x1f%b"])??"").split("").filter(Boolean).map(p=>{let[f="",g=""]=p.split("");return{subject:f.trim(),refs:kc(g)}});return{defaultBranch:r||null,latest:s!==void 0&&s!==""&&i&&l?{subject:s,author:i,date:l}:null,commits:m.length,ticketCommits:m.filter(p=>Sp(p,n).length>0).length}},UE=()=>{if(!gt())return{knownRefs:new Set,contributors:0};let e=h();return{knownRefs:new Set(Object.values(e.nodes).filter(t=>U(t)).map(t=>at(t.id))),contributors:Object.values(e.contributors).filter(t=>!t.tombstoned).length}},Cf=e=>{let t=$c(e);return c(t)?0:t.value.reduce((n,r)=>n+(r.bytes??0),0)},Xc=async e=>{let t=Rc(e);if(c(t))return a(t.message);let n=t.value;if(n.kind!=="connect"&&e.mode==="preview")return a(`${n.repo.label} is already connected`);if(n.kind==="unchanged")return d(xc,{kind:"unchanged",repo:n.repo});if(n.kind==="edit"){let x=Co({repoRoot:e.repoRoot,actorId:e.actorId,event:{action:"edit.repo",payload:n.event}});return c(x)?a(x.message):(n.message.startsWith(Ks)||fn(),d(n.message,{kind:"updated",repo:n.repo}))}let r=_E(e.repoRoot,n.repo),o=Sr.get(n.repo.id);if(e.mode==="confirm"&&o?.key!==r)return a("Nothing is staged for this connect here, or it was staged with other options: preview it again");if(e.mode==="confirm"&&o){clearTimeout(o.timer),Sr.delete(n.repo.id);let x=Co({repoRoot:e.repoRoot,actorId:e.actorId,event:{action:"connect.repo",payload:n.event}});if(c(x))return $t(o.stagePath),a(x.message);await vf(e.repoRoot,n.repo,o.stagePath);let E=ct(e.repoRoot),N=!c(E)&&E.value.overLimit.some(S=>S.id===n.repo.id);return d(N?`Connected ${n.repo.label}, but the board already reads ${An} repos: it is not fetched until one ahead of it is disconnected`:`Connected ${n.repo.label}`,{kind:"connected",repo:n.repo})}for(let x of[...Sr.keys()])Yc(x);let s=Ef(n.repo.id),i=++Rf,l=()=>qc.get(n.repo.id)!==s||Rf!==i,u=qt(e.repoRoot);if(c(u))return a(u.message);let m=await bf(e.repoRoot,n.repo);if(c(m))return a(`Could not clone it: ${m.message}`);if(l())return $t(m.value.stagePath),a("Cancelled");let p=UE(),f=await BE(m.value.stagePath,mn(n.repo.since,u.value.createdAt),p.knownRefs),g=ct(e.repoRoot),v={repo:n.repo,host:Sf(n.repo.url),...f,bytes:m.value.bytes,contributors:p.contributors,claimedBytes:Cf(e.repoRoot),overLimit:!c(g)&&g.value.live.length>=An,expiresAt:Date.now()+Kc};if(l())return $t(m.value.stagePath),a("Cancelled");let I=setTimeout(()=>Yc(n.repo.id),Kc);return I.unref(),Sr.set(n.repo.id,{stagePath:m.value.stagePath,key:r,preview:v,timer:I}),d("Preview: nothing is connected until you confirm",{kind:"preview",preview:v})};import jE from"node:path";var HE=async e=>{let t=await Ie({cwd:e,args:["config","--get","remote.origin.url"]}),n=t.exitCode===0&&t.stdout.trim()||null;return{label:n?Pt(n):jE.basename(e),url:n,path:e}};import{randomBytes as WE}from"node:crypto";import GE from"node:fs";import zE from"node:path";var Af=e=>e.replace(/\r\n?/g,`
46
+ `).replace(/[\x00-\x08\x0B-\x1F\x7F\u0080-\u009f\u202a-\u202e\u2066-\u2069]/g,"").trim(),VE=async(e,t)=>{let n=await _({cwd:e,args:["log","-1","--no-show-signature","--format=%b",t,"--"]});return c(n)?"":Af(n.value.stdout)},KE=async(e,t)=>{if(c(t)||t.value.length===0)return t;let n=await Vn(e);if(c(n))return t;let r=WE(8).toString("hex"),o=`${r}`,s=`${r}`,i=new Map,l=async(m,p)=>{let f=await _({cwd:m,args:["cat-file","--batch-check=%(objectname) %(objecttype)"],input:`${p.join(`
47
+ `)}
48
+ `});return c(f)?[]:f.value.stdout.split(`
49
+ `).filter(g=>g.endsWith(" commit")).map(g=>g.slice(0,g.indexOf(" ")))},u=async(m,p)=>{let f=await _({cwd:m,args:["log","--no-walk=unsorted","--no-show-signature","--stdin",`--format=${o}%H${s}%b`,"--"],input:`${p.join(`
50
+ `)}
51
+ `});if(!c(f))for(let g of f.value.stdout.split(o)){let v=g.indexOf(s);if(v===-1)continue;let I=Af(g.slice(v+s.length));I&&i.set(g.slice(0,v).trim(),I)}};for(let m of n.value){let p=t.value.filter(g=>g.repo===m.repo).map(g=>g.sha).filter(Un);if(p.length===0)continue;let f=await l(m.cwd,p);f.length>0&&await u(m.cwd,f)}return d(t.message,t.value.map(m=>{let p=i.get(m.sha);return p?{...m,body:p}:m}))},qE=8*1024*1024,Qc=async e=>{if(!Un(e.sha))return a("Invalid commit sha");let t=await Ao(e);if(c(t))return a(t.message);let n=await _({cwd:t.value,maxOutput:qE,args:["show","--no-ext-diff","--no-color","--patch","--find-renames","--format=",e.sha]});return c(n)?a(gs(n.message)?"This commit is too large to show here; open it in your editor":n.message):d("Read commit patch",n.value.stdout)},YE=200,Nf=e=>/^0+$/.test(e),si=/^:\d{6} \d{6} ([0-9a-f]{40}) ([0-9a-f]{40}) [A-Z]\d*\t(.+)$/,If=/^(\d+|-)\t(\d+|-)\t(.+)$/,Jc=async(e,t,n,r)=>{let o=await _({cwd:e,args:["diff","--raw","--numstat","--no-renames","--abbrev=40",t,n,...r&&r.length>0?["--",...r]:[]]});if(c(o))return V.info(`[commits] diff ${t} ${n}: ${o.message}`),a(Mf);let s=o.value.stdout.split(`
52
+ `).filter(m=>m!==""),i=s.filter(m=>!si.test(m)&&!If.test(m));if(i.length>0)return a(`Could not parse ${i.length} line(s) of "git diff --raw --numstat" output, e.g. "${i[0]}"`);let l=new Map;for(let m of s){let p=If.exec(m);p&&l.set(p[3]??"",{insertions:p[1]==="-"?0:Number(p[1]),deletions:p[2]==="-"?0:Number(p[2]),isBinary:p[1]==="-"&&p[2]==="-"})}let u=s.filter(m=>si.test(m)).map(m=>{let p=si.exec(m),f=p?.[1]??"",g=p?.[2]??"",v=p?.[3]??"";return{path:v,beforeBlob:Nf(f)?null:f,afterBlob:Nf(g)?null:g,...l.get(v)??{insertions:0,deletions:0,isBinary:!1}}});return d("Listed changed files with blob hashes",u)},Tf=async(e,t)=>{if(t.length>YE)return a(`${t.length} files changed \u2014 too many to show as a diff`);let n=t.flatMap(i=>i.isBinary?[]:[i.beforeBlob,i.afterBlob].filter(l=>l!==null)),r=await fu(n,e);if(c(r))return a(r.message);let o=r.value,s=i=>i!==null&&!o.has(i);return d("Read changed file contents",t.map(i=>{let l=i.isBinary||s(i.beforeBlob)||s(i.afterBlob);return{path:i.path,before:l||!i.beforeBlob?"":o.get(i.beforeBlob)??"",after:l||!i.afterBlob?"":o.get(i.afterBlob)??"",insertions:i.insertions,deletions:i.deletions,isBinary:l}}))},XE=async e=>{if(!Un(e.sha))return a("Invalid commit sha");let t=await Ao(e);if(c(t))return a(t.message);let n=t.value,r=VE(n,e.sha),o=await Jc(n,`${e.sha}~1`,e.sha);if(c(o)&&o.message===Mf){let u=await kf(n,e.sha);if(c(u))return a(u.message);u.value===Zc&&(o=await Jc(n,Zc,e.sha))}if(c(o))return a(o.message);if(o.value.length===0)return a("No changed files found for this commit");let s=await Tf(n,o.value);if(c(s))return a(s.message);let i=s.value,l=await r;return d("Loaded commit diff",{sha:e.sha,...e.repo?{repo:e.repo}:{},files:i,...l?{body:l}:{}})},JE=/^[0-9a-f]{40}$/,ZE=async(e,t,n)=>{let r=await _({cwd:e,args:["log","--raw","--no-renames","--abbrev=40","--format=%H",`${t}..${n}`]});if(c(r))return a(r.message);let o=new Map,s=null;for(let i of r.value.stdout.split(`
53
+ `)){if(JE.test(i)){s=new Set,o.set(i,s);continue}let l=si.exec(i);l&&s&&s.add(l[3]??"")}return d("Listed changed paths per commit",o)},wf=e=>{let t=new Set;for(let n of e)for(let r of n)t.add(r);return t},QE=async(e,t,n)=>{if(t===n)return!0;let r=await _({cwd:e,args:["merge-base","--is-ancestor",t,n]});return!c(r)},Zc="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Mf="Could not read this commit's diff",eS="Its parent is outside the fetched history. Widen since to see this diff.",tS=async(e,t)=>{let n=await _({cwd:e,args:["rev-parse","--git-path","shallow"]});if(c(n))return!1;try{return GE.readFileSync(zE.resolve(e,n.value.stdout.trim()),"utf8").split(`
54
+ `).some(r=>r!==""&&r.startsWith(t))}catch{return!1}},kf=async(e,t)=>{let n=await _({cwd:e,args:["rev-parse","--verify","--quiet",`${t}^1`]});return c(n)?await tS(e,t)?a(eS):d("A root commit",Zc):d("Parent",`${t}~1`)},nS=async e=>{let t=At(e.repoRoot);if(c(t))return a(t.message);let n=t.value,r=await Lc({repoRoot:n,ref:e.ref,end:e.end});if(c(r))return a(r.message);let o=new Set(r.value.flat().map(g=>g.sha)),s=await Vn(n);if(c(s))return a(s.message);let i=Ac(s.value),l=new Map;for(let g of To(r.value))g.length>0&&l.set(g[0].repo??"",g);let u=[],m=0;for(let[g,v]of l){let I=i(g);if(!I){m+=1;continue}let x=await rS(I,e.ref,v,o);if(c(x)){if(!g)return a(x.message);V.info(`[repos] could not squash ${g}: ${x.message}`),m+=1;continue}let E=g||void 0;u.push({repo:E,diff:{...x.value,files:x.value.files.map(N=>E?{...N,repo:E}:N),overlappingPaths:x.value.overlappingPaths.map(N=>E?`${E}:${N}`:N)}})}let[p,...f]=u;return p?f.length===0?d("Loaded squashed diff",p.diff):d("Loaded squashed diff",{...p.diff,commits:u.reduce((g,v)=>g+v.diff.commits,0),files:u.flatMap(g=>g.diff.files),contiguous:u.every(g=>g.diff.contiguous),overlappingPaths:u.flatMap(g=>g.diff.overlappingPaths),parts:u.map(({repo:g,diff:v})=>({...g?{repo:g}:{},from:v.from,to:v.to,commits:v.commits,contiguous:v.contiguous}))}):a(m>0?"The clone holding this ticket\u2019s commits could not be read":"No commits reference this ticket")},rS=async(e,t,n,r=new Set)=>{let o=n[0].sha,s=o;for(let L=n.length-1;L>0;L--){let P=n[L].sha;if(await QE(e,P,o)){s=P;break}}let i=await kf(e,s);if(c(i))return a(i.message);let l=i.value,u=await ZE(e,l,o);if(c(u))return a(u.message);let m=u.value,p=new Set(n.map(L=>L.sha)),f=new Set([...p,...r]),g=[...m.keys()].filter(L=>p.has(L)),v=[...m.keys()].filter(L=>f.has(L)),I=v.length===m.size,x=v.length>g.length,E=new Map;for(let L of g)for(let P of m.get(L)??[])E.has(P)||E.set(P,L);let N=(L,P)=>d("Loaded squashed diff",{ref:t.trim().toUpperCase(),from:l,to:o,commits:g.length,files:L.map($=>({...$,sha:E.get($.path)??o})),contiguous:I,overlappingPaths:P}),S,T=[];if(!I||x){let L=wf(g.map($=>m.get($)??new Set)),P=wf([...m.entries()].filter(([$])=>!f.has($)).map(([,$])=>$));if(L.size===0)return N([],[]);S=[...L],T=[...L].filter($=>P.has($)).sort()}let k=await Jc(e,l,o,S);if(c(k))return a(k.message);let H=await Tf(e,k.value);return c(H)?a(H.message):N(H.value,T)};var Pf=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,el=e=>e.replace(Pf,""),oS=e=>`<!-- epiq-diff-comment:${JSON.stringify(e).replaceAll(">","\\u003e")} -->`,Lf=e=>e==="additions"||e==="deletions",Oo=e=>{let t=Pf.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"||!Lf(r.side)||!Lf(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r};var Of=/```\n([\s\S]*?)\n?```\s*$/,Df=e=>Of.exec(e)?.[1]??null,sS=/`[^`\n]+`[^\n]*\n?$/,Ff=e=>el(e).replace(Of,"").replace(sS,"").trim(),_f=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})`},tl=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${_f(e)}`;var iS=e=>{let t=e.split(`
55
+ `),n=t.filter(r=>r.trim()!=="").reduce((r,o)=>{let s=/^[ \t]*/.exec(o)?.[0].length??0;return r===null?s:Math.min(r,s)},null);return n?t.map(r=>r.slice(n)).join(`
56
+ `):e},$f=({snippet:e,...t})=>{let n=t.note.trim();return[...n?[n,""]:[],oS({...t,note:n}),`\`${t.filePath}\` ${_f(t)}`,"```",iS(e),"```"].join(`
57
+ `)};var aS=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/,ii=e=>{if(!e.startsWith('"')||!e.endsWith('"'))return e;let t=e.slice(1,-1),n="";for(let r=0;r<t.length;r++){if(t[r]!=="\\"){n+=t[r];continue}let o=t[++r];if(o==="n")n+=`
58
+ `;else if(o==="t")n+=" ";else if(o==='"'||o==="\\")n+=o;else if(o&&/[0-7]/.test(o)){let s=t.slice(r,r+3);n+=String.fromCharCode(parseInt(s,8)),r+=2}else o!==void 0&&(n+=o)}try{return decodeURIComponent(escape(n))}catch{return n}},Bf=e=>{let t=ii(e.trim());return t==="/dev/null"?null:t.replace(/^[ab]\//,"")},rl=e=>{let t=[],n=null,r=0,o=0,s=()=>{let i={path:"",oldPath:null,binary:!1,added:0,removed:0,lines:[]};return t.push(i),i};for(let i of e.split(`
59
+ `)){if(i.startsWith("diff --git ")){n=s();let p=i.slice(11),f=p.lastIndexOf(" b/");f!==-1&&(n.path=ii(p.slice(f+1)).replace(/^b\//,""));continue}if(!n){if(!i.trim())continue;n=s()}let l=n,u=l.lines.length===0;if(u&&i.startsWith("--- ")){let p=Bf(i.slice(4));p&&(l.oldPath=p);continue}if(u&&i.startsWith("+++ ")){let p=Bf(i.slice(4));p&&(l.path=p);continue}if(u&&i.startsWith("rename from ")){l.oldPath=ii(i.slice(12));continue}if(u&&i.startsWith("rename to ")){l.path=ii(i.slice(10));continue}if(u&&(i.startsWith("Binary files ")||i.startsWith("GIT binary patch"))){l.binary=!0,l.lines.push({kind:"note",text:"Binary file"});continue}let m=aS.exec(i);if(m){r=Number(m[1]),o=Number(m[3]),l.lines.push({kind:"hunk",text:i});continue}if(!u){if(i.startsWith("\\")){l.lines.push({kind:"note",text:i.slice(1).trim()});continue}if(i.startsWith("+")){l.added++,l.lines.push({kind:"added",text:i.slice(1),newLine:o++});continue}if(i.startsWith("-")){l.removed++,l.lines.push({kind:"removed",text:i.slice(1),oldLine:r++});continue}if(i.startsWith(" ")){l.lines.push({kind:"context",text:i.slice(1),oldLine:r++,newLine:o++});continue}i===""&&l.lines.push({kind:"context",text:"",oldLine:r++,newLine:o++})}}for(let i of t)!i.path&&i.oldPath&&(i.path=i.oldPath);return t.filter(i=>i.path!=="")},nl=e=>e.oldPath&&e.oldPath!==e.path?e.oldPath:null;var ol=e=>e.flatMap(t=>[{kind:"file",text:`${nl(t)?`${nl(t)} \u2192 `:""}${t.path}`,file:t},...t.lines]),ai=e=>{let t="",n=-1;return e.map(r=>(r.kind==="file"&&(t=r.file.path),r.kind==="hunk"&&n++,{file:t,hunk:n}))},sl=(e,t,n)=>{let r=t.map(i=>Oo(i.md)).filter(i=>i!==null&&i.sha===n&&i.side==="additions");if(r.length===0)return new Set;let o=ai(e),s=new Set;return e.forEach((i,l)=>{let u=i.newLine;if(u===void 0)return;let m=o[l]?.file;r.some(p=>p.filePath===m&&p.start<=u&&u<=p.end)&&s.add(l)}),s},Uf=(e,t)=>e===t?`line:${e}`:`lines:${e}-${t}`,cS=/^lines?:(\d+)(?:-(\d+))?(?:\s+|$)/,jf=e=>{let t=cS.exec(e);if(!t)return null;let n=Number(t[1]),r=t[2]===void 0?n:Number(t[2]);return{start:Math.min(n,r),end:Math.max(n,r),note:e.slice(t[0].length)}},Hf=(e,t)=>ai(e)[t]?.file??null,Wf=(e,t,n,r)=>{let o=ai(e),s=u=>e.findIndex((m,p)=>o[p]?.file===t&&(m.kind==="added"||m.kind==="context")&&m.newLine===u),i=s(n),l=s(r);return i===-1||l===-1?{ok:!1,reason:`${t} has no line ${i===-1?n:r} on the new side`}:il(e,i,l)},il=(e,t,n)=>{let[r,o]=t<=n?[t,n]:[n,t],s=e[r],i=e[o];if(!s||!i)return{ok:!1,reason:"That line is not in the diff"};let l=g=>(g.kind==="added"||g.kind==="context")&&g.newLine!==void 0;if(!l(s)||!l(i))return{ok:!1,reason:"Comments anchor to the new side: pick an added or unchanged line"};let u=ai(e),m=u[r],p=u[o];if(m.file!==p.file)return{ok:!1,reason:"A comment covers one file at a time"};if(m.hunk!==p.hunk)return{ok:!1,reason:"A comment covers one hunk at a time"};let f=e.slice(r,o+1).filter(l);return{ok:!0,value:{filePath:m.file,start:f[0].newLine,end:f[f.length-1].newLine,snippet:f.map(g=>g.text).join(`
60
+ `)}}};import{existsSync as ul}from"node:fs";import{chmod as ml}from"node:fs/promises";import li from"node:path";import{spawn as lS,spawnSync as dS}from"node:child_process";import uS from"node:os";import Gf from"node:path";import{ulid as mS}from"ulid";function al(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 pS(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function ci(){let{preferredEditor:e}=ne(),t=[e?pS(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function cl(e){let[t=""]=al(e);return/(^|\/)code(-insiders)?$/.test(t)}function zf(e,t){let[n="",...r]=al(e);return{command:n,args:[...r,...t]}}function Vf(e,t){return zf(e,cl(e)?["--wait",t]:[t])}function fS(e,t,n,r="new"){return zf(e,[r==="new"?"--new-window":"--reuse-window","--diff",t,n])}function ll(e){let t=Gf.join(uS.tmpdir(),"epiq");Oe.mkDir(t);let n=Gf.join(t,mS());Oe.writeToFile(n,e??"");let r=ci();for(let o of r){let{command:s,args:i}=Vf(o,n);if(!s)continue;let l=dS(s,i,{stdio:"inherit"});if(!l.error&&l.status===0){let u=Oe.readFile(n);if(u==null)return a("Unable to read edited file");let m=u.replace(/\r?\n$/,"");return d("Successfully edited",m)}}return a("Unable to open editor")}var gS=new Set(["vim","vi","nvim","nano","pico","ed"]);function hS(e){let[t=""]=al(e),n=t.split("/").pop()??t;return gS.has(n)}var yS=600;function Kf({command:e,args:t},n){return new Promise(r=>{if(!e){r(a(`"${n}" is not a usable editor command`));return}let o=lS(e,t,{stdio:"ignore",detached:!0}),s=!1,i=u=>{s||(s=!0,clearTimeout(l),r(u))};o.on("error",u=>i(a(u.message))),o.on("exit",u=>{i(u===0?d("Opened editor",!0):a(`"${n}" exited with code ${u}`))});let l=setTimeout(()=>{o.unref(),i(d("Opened editor",!0))},yS)})}function bS(e,t){return hS(e)?Promise.resolve(a(`"${e}" is a terminal editor and can't open from the GUI (no terminal attached). Set preferredEditor to a GUI editor (e.g. "code"), or open the file yourself: ${t}`)):Kf(Vf(e,t),e)}function dl(e,t,n,r="new"){return Kf(fS(e,t,n,r),e)}async function qf(e){let t=ci();if(t.length===0)return a("No editor configured (preferredEditor, VISUAL, or EDITOR)");let n=a("Unable to open editor");for(let r of t){let o=await bS(r,e);if(!c(o))return o;n=o,logger.error(`Failed to open editor "${r}" for ${e}: ${o.message}`)}return n}import{chmodSync as vS,existsSync as xS,lstatSync as RS,mkdirSync as ES}from"node:fs";import SS from"node:os";import CS from"node:path";var Do=(...e)=>{let t=CS.join(SS.tmpdir(),"epiq",...e);try{return xS(t)&&RS(t).isSymbolicLink()?a(`Refusing to write through a symlink at ${t}`):(ES(t,{recursive:!0,mode:448}),vS(t,448),d("Prepared private temp dir",t))}catch(n){return a(`Unable to prepare ${t}: ${n instanceof Error?n.message:String(n)}`)}};var NS=async(e,t)=>{let n=await _({cwd:e,args:["show","--no-ext-diff",t]});if(c(n))return a(n.message);let r=Do("commit-diffs");if(c(r))return a(r.message);let o=li.join(r.value,`${t}.diff`);return ul(o)||(Oe.writeToFile(o,n.value.stdout),await ml(o,292)),qf(o)},IS=12,wS=800,Yf=async(e,t,n)=>{let r=await _({cwd:e,args:["show",`${t}:${n}`]});return c(r)?"":r.value.stdout},AS=async(e,t)=>{let n=await _({cwd:e,args:["diff","--name-only",`${t}~1`,t]});if(c(n))return a(n.message);let r=n.value.stdout.split(`
61
+ `).map(o=>o.trim()).filter(Boolean);return r.length===0?a("No changed files found for this commit"):d("Listed changed files",r)},TS=async(e,t,n)=>{let r=await AS(e,t);if(c(r))return a(r.message);let o=r.value;if(o.length>IS)return a(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=Do("commit-diffs",t);if(c(s))return a(s.message);let i=s.value,l=await Promise.all(o.map(async(g,v)=>{let[I,x]=await Promise.all([Yf(e,`${t}~1`,g),Yf(e,t,g)]),E=li.basename(g),N=li.join(i,String(v),"before",E),S=li.join(i,String(v),"after",E);return ul(N)||(Oe.writeToFile(N,I),await ml(N,292)),ul(S)||(Oe.writeToFile(S,x),await ml(S,292)),{beforePath:N,afterPath:S}})),[u,...m]=l;if(!u)return a("No changed files found for this commit");let p=await dl(n,u.beforePath,u.afterPath,"new");if(c(p)||m.length===0)return p;await new Promise(g=>setTimeout(g,wS));let f=await Promise.all(m.map(({beforePath:g,afterPath:v})=>dl(n,g,v,"reuse")));for(let g of f)c(g)&&logger.error(`Failed to open an additional diff tab for ${t}: ${g.message}`);return p},pl=async e=>{if(!Un(e.sha))return a("Invalid commit sha");let t=await Ao(e);if(c(t))return a(t.message);let n=t.value,r=ci()[0];if(r&&cl(r)){let o=await TS(n,e.sha,r);if(!c(o))return o;logger.error(`Side-by-side diff failed for ${e.sha}, falling back to unified diff: ${o.message}`)}return NS(n,e.sha)};var Xf=e=>{if(e<1024)return`${e} B`;let t=["KB","MB","GB","TB"],n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${n>=10?Math.round(n):n.toFixed(1)} ${t[r]}`};var fl=["branches=default","branches=all","since=board","since=all","since=YYYY-MM-DD","label=<name>","confirm"],gl=e=>{let[t="",...n]=e.trim().split(/\s+/).filter(Boolean);if(!t)return a("a remote URL to read commits from");if(!tn(t))return a("https://, ssh://, git://, file:/// or user@host:path");let r={url:t},o=new Set;for(let s of n){let i=s.indexOf("="),l=i===-1?s:s.slice(0,i),u=i===-1?"":s.slice(i+1);if(o.has(l))return a(`one ${l}=, not two`);if(o.add(l),s==="confirm")r.confirm=!0;else if(l==="branches"&&(u==="default"||u==="all"))r.branches=u;else if(l==="since"&&Tn(u))r.since=u;else if(l==="label"&&(u===""||Mn(u)))r.label=u;else return a(`${fl.join(", ")}; not "${s}"`)}return d("Parsed",r)},Jf=()=>{let e=At();if(c(e))return[];let t=ct(e.value);return c(t)?[]:[...t.value.live,...t.value.overLimit]},MS=e=>{let t=e.latest?`latest "${ut(e.latest.subject).slice(0,60)}" by ${ut(e.latest.author).slice(0,40)}`:"no commits",n=e.ticketCommits===0?"none linked, wrong repo?":`${e.ticketCommits} linked`;return[`${e.repo.label} from ${e.host}`,e.defaultBranch?ut(e.defaultBranch).slice(0,60):"no default branch",t,`${e.commits} commits, ${n}`,Xf(e.bytes),e.overLimit?"over the limit: not downloaded until another repo is disconnected":e.contributors>1?`all ${e.contributors} contributors download it on next sync`:"everyone downloads it on next sync"].join(" \xB7 ")},Cr=null,kS=e=>`${e.trim()} confirm`,Zf=e=>Cr&&Cr.line===e.trim()?Cr.summary:null,Qf=async()=>{let e=q().commandMeta.inputString,t=gl(e);if(c(t))return a(`Expected ${t.message}`);let{userId:n}=ne();if(!n)return a("Set a username first with :config username");let r=At();if(c(r))return r;let o=await Xc({repoRoot:r.value,actorId:n,url:t.value.url,branches:t.value.branches,since:t.value.since,label:t.value.label,mode:t.value.confirm?"confirm":"auto"});if(c(o))return a(o.message);if(o.value.kind==="preview"){let s=kS(e);return Cr={line:s,summary:MS(o.value.preview)},d(Cr.summary,{followUp:`config repoConnect ${s}`})}return t.value.confirm&&(Cr=null),d(o.value.kind==="connected"?`${o.message} \u2014 it syncs with the board; :sync fetches it`:o.message,null)},eg=()=>{let{userId:e}=ne();if(!e)return a("Set a username first with :config username");let t=At();if(c(t))return t;let n=Wc({repoRoot:t.value,actorId:e,repo:q().commandMeta.inputString});return c(n)?a(n.message):d(`${n.message} \u2014 it syncs with the board`,null)};var tg=e=>e==="board"?4e3:2e3,ng=e=>e.trim()?e:"";var rg=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null;import{createHash as LS}from"node:crypto";var PS="0123456789ABCDEFGHJKMNPQRSTVWXYZ",OS=e=>{let t=LS("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+=PS[Number(n>>s&31n)]}return r},og=new Map,he=(e,t)=>{let n=`${e}:virtual:${t}`,r=og.get(n);if(r!==void 0)return r;let o=OS(n);return og.set(n,o),o};import sg from"chalk";var ie=e=>sg.dim(e),ue=e=>sg.hex(A.primary)(e),xe=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(f=>f.startsWith(i))].sort((f,g)=>ls(f)-ls(g)).slice(0,r).map(f=>ds(f)).join(" ");return p?`${ie(e)}${p}${ie(n)}`:""};var gn={None:"none",Invalid:"invalid",Valid:"valid"};var DS=["BOARD","TICKET","SWIMLANE"],ig=()=>{let e=h().selectedNode;if(!e?.context)return G({message:ie("Missing target context")});if(DS.includes(e.context))return Z();if(e.parentNodeId){let t=h().nodes[e.parentNodeId];if(t?.id===he(t?.parentNodeId??"","comments"))return Z()}return G({message:ie("Command not available in this context")})},se="<ENTER> to confirm",FS=()=>{let{userId:e}=ne(),t=me();return!e||c(t)?[]:cr(t.value.emailLinks,e)},Z=(e="",t=[],n=!0)=>({message:n?ie(e):e,validity:gn.Valid,completionWordList:t}),G=({message:e,completionWordList:t=[]})=>({validity:gn.Invalid,message:e,completionWordList:t}),hn=e=>e.length===0,ag=(e,t)=>{let n=nt(h().breadCrumb,"BOARD");if(c(n))return G({message:ue("Command is not applicable in this context")});let r=Ed(n.value.id);return c(r)?G({message:ue(`Unable to ${t}: board id is not a valid ULID`)}):lm({date:e,horizonDate:r.value})?null:G({message:ue(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},Nr=e=>` ${lg.hex("#000").bgHex(Ue(e))(` ${e} `)} `,hl=({modifier:e})=>{let t="confirm";return e===t?Z(se):G({message:hn(e)?ie("if you are certain, enter ")+ds(t):"",completionWordList:[t]})},_S=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?G({message:ie(n)}):Z():G({message:hn(r)?t:"",completionWordList:[...e]}),cg=e=>({modifier:t,inputString:n})=>{let r=e();return r.includes(t)?hn(n)?Z(se):G({message:ue("Takes one rule"),completionWordList:[]}):G({message:hn(t)?ie("rule:")+r.map(Nr).join("")+ie(""):ue(`Rules: ${ao.join(", ")}`),completionWordList:[...r]})},qn=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>hn(n)&&hn(r)?G({message:e,completionWordList:[]}):Z(t??se),$S=({modifier:e,inputString:t})=>{let n=Ka();return!hn(e)||!hn(t)?Z(se):G({message:n.length?ie("number from the list, or a path"):ie("path to an epiq project"),completionWordList:n})},BS=({modifier:e,inputString:t})=>{let n=ke(b.CONFIG);if(!n.includes(e))return G({message:xe({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ee.EDITOR:{let r=[...fm];return t.trim()?r.includes(t.trim())?Z(se):G({message:xe({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):G({message:xe({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ee.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?Z(se):G({message:xe({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ee.USERNAME:{let r=ne().gitName,o=r?[r]:[],s=t.trim(),i=o.filter(m=>m.startsWith(s)),u=i.length===1&&i[0]===s?"":xe({prefix:"name: ",wordList:o,inputString:s,minLengthForHints:0});return s?u?Z(`${u} ${ie(se)}`,o,!1):Z(se,o):G({message:u||ue("Enter a user name. Saved in ")+lg.bgBlack("~/.epiq-global/config.json"),completionWordList:o})}case ee.EMAILS:{let r=ne().gitEmail,o=fr(),s=o.length>0||!r?o:[r],i=[...s,"none"],l=t.trim(),u=(I,x)=>G({message:xe({prefix:I,wordList:i,noOfHints:3,inputString:x,minLengthForHints:0}),completionWordList:i});if(!l)return Z(`${se} to see your addresses, or name one`,i);let m=l.split(/[,\s]+/).filter(Boolean),p=m[m.length-1]??"",f=I=>I==="none"||s.includes(I.toLowerCase()),g=I=>i.some(x=>x.startsWith(I.toLowerCase())),v=m.filter(I=>!f(I)&&!g(I));return v.length>0?G({message:ue(`no address here matches ${v.join(", ")} \u2014 pick one from the list, or its number`),completionWordList:i}):f(p)?Z(se):u("",p)}case ee.EMAILS_UNCLAIM:{let r=FS(),o=t.trim();return r.length===0?G({message:ue("you have not claimed any addresses"),completionWordList:[]}):o&&r.includes(o.toLowerCase())?Z(se):G({message:xe({prefix:"give an address back ",wordList:r,noOfHints:3,inputString:o,minLengthForHints:0}),completionWordList:r})}case ee.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?Z(se):G({message:xe({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ee.AUTOSYNC:{let r=["on","off"],o=ne().autoSync;if(!r.includes(t.trim())){let s=Xu(o);return G({message:xe({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return Z(se)}case ee.ATTACHMENT_MAX_KB:{let r=ne().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<uo||o>mo){let s=xe({prefix:" examples: ",wordList:za,minLengthForHints:0,inputString:t});return G({message:ue(`provide a size cap in KB (${uo}-${mo}). current: ${r??Bn} KB.`)+s,completionWordList:za})}return Z(se)}case ee.REPO_CLONE_MAX_MB:{let r=t.trim();if(!/^\d+$/.test(r)||!Qa(Number(r))){let o=xe({prefix:" examples: ",wordList:Va,minLengthForHints:0,inputString:t});return G({message:ue(`provide a connected repo's clone cap in MB (${hr}-${yr}). current: ${br()} MB.`)+o,completionWordList:Va})}return Z(se)}case ee.REPO_CONNECT:{let r=gl(t);if(c(r))return G({message:ue(r.message),completionWordList:[]});let o=r.value.confirm?Zf(t):null;return r.value.confirm&&!o?G({message:ue("preview it first: run the line without confirm"),completionWordList:[]}):Z(`${o??ie(fl.join(" "))} ${se}`,[],!1)}case ee.REPO_DISCONNECT:{let r=Jf(),o=Sc(r),s=t.trim();return o.length===0?G({message:ue("no other repos are connected"),completionWordList:[]}):s&&!c(Ys(r,s))?Z(se):G({message:xe({prefix:"stop reading ",wordList:o,noOfHints:3,inputString:s,minLengthForHints:0}),completionWordList:o})}case ee.SYNC_DEBOUNCE_MS:{let r=ne().autoSyncIntervalMs,o=lr(t);if(!t.trim()||o===null){let s=xe({prefix:" examples: ",wordList:Ga,minLengthForHints:0,inputString:t});return G({message:ue(`provide a duration between ${3e3}ms and ${864e5}ms. current duration: ${r}ms.`)+s,completionWordList:Ga})}return Z(se)}default:return G({message:ue("Unknown config option"),completionWordList:n})}},US=({modifier:e,inputString:t})=>{let n=ke(b.EDIT);if(!n.length)return G({message:ue("Command not available in this context")});if(!n.includes(e)){let r=xe({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return G({message:r||ue("Unknown edit option"),completionWordList:n})}switch(e){case pt.COMMENT:return t.trim()?Z(se):G({message:ie("write a comment...")});case pt.TITLE:return Z(se);case pt.DESCRIPTION:{let{preferredEditor:r}=ne();return r?Z(ie("<ENTER> to edit in ")+r):G({message:"No editor selected"})}default:return G({message:ue("Unknown edit option"),completionWordList:n})}},jS=({modifier:e})=>{let t=ke(b.YANK);return t.length?t.includes(e)?Z(se+ie(" and copy to clipboard")):G({message:xe({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):G({message:ue("Nothing selected to copy from")})},HS={[b.EXPORT]:()=>Z(se+ie(", and create export markdown file")),[b.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return Z(se);let n={message:ie("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Fn(r);if(!r||!o)return G(n);let s=ag(o,"peek");return s||Z(se)},[b.REPLAY]:e=>{let{dateInput:t,durationInput:n}=Ls(e.modifier,e.inputString),r={message:ie("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Fn(t);if(!t||!o)return G(r);let s=ag(o,"replay");return s||(n&&ks(n)===null?G({message:ue("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):Z("<ENTER> to replay board history",n?pm:[]))},[b.EXIT]:()=>Z(se+ie(" and exit the application")),[b.INIT]:()=>Z(se),[b.OPEN]:$S,[b.PALETTE]:()=>Z(se),[b.FILTER]:e=>{if(e.modifier==="clear")return Z(se);let t=s=>ke(b.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return G({message:xe({wordList:ke(b.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:ke(b.FILTER)});let n=Object.values(h().tags).map(s=>s.name),r=Object.values(h().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="goal"?Os():e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?G({message:xe({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):Z():G({message:xe({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[b.NONE]:e=>{let t=ke(b.NONE);return G({message:xe({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[b.NEW]:e=>_S({list:ke(b.NEW),hint:xe({wordList:ke(b.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[b.HELP]:()=>Z(se),[b.EDIT]:US,[b.COMMENT]:e=>{let t=qn({hint:ie(`write a comment (max ${4e3} char)...`),onOk:ie(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===gn.Invalid?t:e.inputString.length>4e3?Z(ue("max input exceeded")):t},[b.CONFIG]:BS,[b.YANK]:jS,[b.DELETE]:e=>{let t=ig();return t.validity==="invalid"?t:hl(e)},[b.GOAL]:e=>{let t=Os().slice(0,10).map(Nr);return qn({hint:t.length?ie("goal:")+t.join("")+ie(""):ie("name a new goal ...")})(e)},[b.UNGOAL]:e=>e.modifier||e.inputString.trim()?G({message:ue("Takes no argument"),completionWordList:[]}):Z(se),[b.RULE]:cg(()=>{let e=zt();return e?Ns(e):[]}),[b.UNRULE]:cg(()=>{let e=zt();return e?Dn(e):[]}),[b.CLOSE_ISSUE]:e=>hl(e),[b.RE_OPEN_ISSUE]:e=>hl(e),[b.MOVE]:e=>{let t=ig();return t.validity==="invalid"?t:qn({hint:xe({prefix:"hey hacker! These commands are blocked for you... ",wordList:ke(b.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[b.TAG]:e=>{let n=R.getExistingTags().slice(0,10).map(Nr).join("");return qn({hint:n.length?ie("create tag or reuse:")+n+ie(""):ie("create tag ...")})(e)},[b.UNTAG]:e=>{let t=Ss();if(c(t))return G({message:ue("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Nr).slice(0,10);return n.length?qn({hint:ie(" ... ")+n.join("")})(e):G({message:ue("Issue has no tags"),completionWordList:[]})},[b.ASSIGN]:e=>{let t=R.getExistingAssignees().map(Nr).slice(0,10);return qn({hint:ie("assignees... ")+t.join("")})(e)},[b.UNASSIGN]:e=>{let t=Cs();if(c(t))return G({message:ue("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Nr).slice(0,10);return n.length?qn({hint:ie("remove assignee... ")+n.join("")})(e):G({message:ue("Issue has no assignees"),completionWordList:[]})},[b.SYNC]:()=>Z(se)},dg=Object.fromEntries(Object.entries(HS).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var di=["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 WS=3,GS=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"]),zS=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},VS=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=WS&&!GS.has(t)&&!/^\d+$/.test(t)),KS=e=>{let t=new Map;for(let s of zS(e))for(let i of VS(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),r=new Set(n),o=di.filter(s=>!r.has(s));return[...n,...o]},ug=di,mg=-1,pg=()=>{let e=me();if(c(e))return di;let t=e.value,n=t.eventLog.length;return n!==mg&&(ug=KS(t),mg=n),ug};var fg=e=>Object.values(b).includes(e),gg=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:l,completionWordList:u}=dg[n].validate(n,r,s),m=n!==b.PEEK&&n!==b.REPLAY,p=o==="command"||o==="modifier"?ke(n):m?pg():[],{mode:f}=h(),g=f===y.COMMAND_LINE?i??"":"",v=[...u,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?Vd(e,v,u):{hint:"",hints:[],remainder:"",overlap:0}}};var hg=e=>{let t=e.trimStart(),n=YS(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=XS(e),l=fg(r)?r:null,u=l!==null,m=r!=="",p=l?ke(l)??[]:[],f=l&&p.includes(o)?o:"",g="word";n.length===0||n.length===1&&!s?g="command":(n.length===1&&s||n.length===2&&!s)&&(g="modifier");let v=s?"":i,I=qS(t,l,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:l,isCommandKeyword:u,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:v,inputString:I}},qS=(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},YS=e=>e.trim()?e.trim().split(/\s+/):[],XS=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as JS}from"react";var Ir=e=>e===yl||e===":",yl=" ",_o=40,wr={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:gn.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},bl=new Set,yg=()=>{for(let e of bl)e()},ZS=e=>(bl.add(e),()=>bl.delete(e)),ht=e=>{let n=e(wr),r=hg(n.value),o=n.cursorPosition===n.value.length;wr={...n,commandMeta:gg(r,o)},yg()},$o=({message:e,status:t})=>{let n=structuredClone(wr);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,wr=n,yg(),d(e,null)},vl=e=>{ht(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},xl=e=>{ht(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Ir(n[o-1]);)o--;for(;o>0&&!Ir(n[o-1]);)o--}else{for(;o<n.length&&!Ir(n[o]);)o++;for(;o<n.length&&Ir(n[o]);)o++}return{...t,cursorPosition:o}})},bg=()=>{ht(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}})},vg=()=>{ht(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Ir(t[r-1]);)r--;for(;r>0&&!Ir(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},ui=e=>{ht(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),i=s+o,l=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:l,commandIsPending:!1}})},xg=()=>{ht(e=>({...e,commandIsPending:!0}))},X=e=>{ht(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},Rg=({addToHistory:e=!0,line:t})=>{ht(n=>{let r=t??n.value;return{...n,commandHistory:e&&r.trim()?[r,...n.commandHistory].slice(0,_o):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}})},Eg=e=>{ht(t=>({...t,commandHistory:e.slice(0,_o),commandHistoryIndex:-1}))},Sg=()=>{ht(e=>e.commandHistoryIndex===-1?e:{...e,commandHistoryIndex:-1})},Cg=()=>{ht(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}})},Ng=()=>{ht(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},q=()=>wr,g_=()=>JS(ZS,q,q),mi=()=>{let[e,...t]=wr.value.split(yl);return t.join(yl).trim()};var C={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavPreviousItemJump:"navPreviousItemJump",NavNextItemJump:"navNextItemJump",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MovePreviousItemJump:"movePreviousItemJump",MoveNextItemJump:"moveNextItemJump",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",OpenInEditor:"openInEditor",MarkDiffLine:"markDiffLine",CommentOnDiffLine:"commentOnDiffLine",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"},QS=e=>e.shift===!0,eC={[C.NavPreviousItem]:C.NavPreviousItemJump,[C.NavNextItem]:C.NavNextItemJump,[C.MovePreviousItem]:C.MovePreviousItemJump,[C.MoveNextItem]:C.MoveNextItemJump};function tC(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function nC(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function rC(e,t,n){let r=h().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function S_(e,t){let n=q();if(e.sequence==="?"&&t!==y.PALETTE)return C.InitCommandPalette;if(e.sequence===":"&&t!==y.COMMAND_LINE)return C.InitCommandLine;if(t===y.MOVE)switch(e.name){case"m":case"return":return C.ConfirmMove}if(t===y.COMMAND_LINE)return $d(e,n.value);if(t===y.PALETTE)return Bd(e,n.value);let r=tC(e)||nC(e);if(r)return oC(r,t,QS(e));if(e.ctrl&&e.name==="c")return C.Exit;switch(e.name){case"r":return C.EditTitle;case"e":return C.EditDescription;case"n":return C.AddItem;case"m":return C.InitMove;case"d":return C.Delete;case"y":return C.Yank;case"o":return C.OpenInEditor;case"s":return C.MarkDiffLine;case"c":return C.CommentOnDiffLine;case"return":return C.Confirm;case"space":return C.Confirm;case"v":return ne().viewMode==="wide"?C.SetViewDense:C.SetViewWide;case"q":case"escape":return C.Exit;default:return null}}function oC(e,t,n=!1){let r=t===y.MOVE?{prevItem:C.MovePreviousItem,nextItem:C.MoveNextItem,prevContainer:C.MoveToPreviousContainer,nextContainer:C.MoveToNextContainer}:{prevItem:C.NavPreviousItem,nextItem:C.NavNextItem,prevContainer:C.NavToPreviousContainer,nextContainer:C.NavToNextContainer},o=rC(h().contextNode.childRenderAxis,e,r);return!o||!n?o:eC[o]??o}import{ulid as aC}from"ulid";var Bo=24n,sC=Bo*4n,Mt=(1n<<sC)-1n,iC=/^[0-9a-f]+$/;function Ig(e){return!e||!iC.test(e)?a(`Invalid hex rank: ${e}`):d("Converted rank to bigint",BigInt("0x"+e))}function dt(e,t=Bo){if(e<0n)return a("Negative rank not allowed");let n=e.toString(16);return d("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function Ge(e,t){if(!e&&!t)return dt(Mt/2n,Bo);let n=e?Ig(e):d("Resolved lower bound",0n);if(c(n))return n;let r=t?Ig(t):d("Resolved upper bound",Mt);if(c(r))return r;let o=n.value,s=r.value;if(s<=o)return a("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?a("No rank space available between neighbors"):dt(i,Bo)}function wg(e){if(e<=0)return d("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Mt*BigInt(r+1)/(t+1n),s=dt(o,Bo);if(c(s))return s;n.push(s.value)}return d("Resolved evenly spaced ranks",n)}var Rl=(e,t)=>{let n=be(e),r=wg(n.length);if(c(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],l=r.value[s];if(!i||!l)return a("Unable to assign rebalance rank");o[i.id]=l}return d("Created rebalance event",{id:aC(),action:"rebalance.children",payload:{parent:e,ranks:o},...Q(t)})};var yn=e=>e.trim().toLocaleLowerCase(),El=(e,t)=>yn(e).includes(yn(t));var cC=e=>{let{tags:t}=h();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},lC=e=>{let{contributors:t}=h();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},Ag=null,Tg=new Map,dC=()=>{let e=h().eventLog??[];if(e===Ag)return Tg;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 Ag=e,Tg=t,t},uC=e=>{let{contributors:t}=h(),n=dC().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},Mg=(e,t)=>{let n=yn(t.value);if(!n)return!0;switch(t.target){case"title":return El(e.title??"",n);case"description":return El(e.props.description??"",n);case"tag":return cC(e).map(yn).some(o=>o.includes(n));case"goal":{let r=an(e);return r?yn(r.name).includes(n):!1}case"assignee":return lC(e).map(yn).some(o=>o.includes(n));case"actor":return uC(e).map(yn).some(o=>o.includes(n));case"ref":return gc(e.id,t.value);default:return!0}};var Sl=(e,t)=>e.rank<t.rank?-1:e.rank>t.rank?1:0,mC=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,kg=(e,t)=>Object.values(e).filter(n=>mC(n,t)).sort(Sl),Lg=(e,t)=>{let n={};for(let r of Object.values(e)){if(U(r)&&t.length>0&&!t.every(s=>Mg(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(Sl);return n},Pg=(e,t)=>{let n={};for(let r of Object.values(e)){if(!r.parentNodeId||r.isDeleted||!t.has(r.parentNodeId))continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(Sl);return n};var Og=e=>pi(be(e),{at:"end"}),pi=(e,t={at:"end"})=>{let n=o=>c(o)?d("Rank space exhausted",{rank:"",needsRebalance:!0}):d("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(Ge(void 0,void 0));let r=()=>n(Ge(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(Ge(void 0,o.rank)):a("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(Ge(o.rank,void 0)):a("Unable to resolve last sibling")}case"before":{let o=Dg(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o>0?e[o-1]:void 0;return n(Ge(i?.rank,s.rank))}case"after":{let o=Dg(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o<e.length-1?e[o+1]:void 0;return n(Ge(s.rank,i?.rank))}}},be=e=>{let t=h();if(!_g()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return kg(t.nodes,e)},Dg=(e,t)=>e.findIndex(n=>n.id===t),Fg=(e,t,n={at:"end"})=>pi(be(t).filter(r=>r.id!==e),n),fi=(e,t,n,r,o)=>{let s=Fg(t,e,n);if(c(s))return s;if(!s.value.needsRebalance)return d("Resolved rank",s.value.rank);let i=Rl(e,r);if(c(i))return i;let l=Y([i.value],o);if(c(l))return l;let u=Fg(t,e,n);return c(u)?u:u.value.needsRebalance?a("Rank rebalance failed to create space"):d("Resolved rank after rebalance",u.value.rank)},gi=(e,t,n)=>{let r=Og(e);if(c(r))return r;if(!r.value.needsRebalance)return d("Resolved rank",r.value.rank);let o=Rl(e,t);if(c(o))return o;let s=Y([o.value],n);if(c(s))return s;let i=Og(e);return c(i)?i:i.value.needsRebalance?a("Rank rebalance failed to create space"):d("Resolved rank after rebalance",i.value.rank)};var Uo=5,z={exit(){process.exit(0)},enterChildNode(){let e=h(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=le(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||z.navigate({contextNode:o,selectedIndex:le(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=h();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=le(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;z.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>$g(1),navigateToPreviousItem:()=>$g(-1),jumpToNextItem:()=>Bg(Uo),jumpToPreviousItem:()=>Bg(-Uo),navigateToNextContainer:()=>Ug(1),navigateToPreviousContainer:()=>Ug(-1),navigate:({contextNode:e,selectedIndex:t})=>{w({contextNodeId:e.id,selectedIndex:t})}},$g=e=>{let{selectedIndex:t,contextNode:n}=h(),r=le(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;z.navigate({selectedIndex:s,contextNode:n})},Bg=e=>{let{selectedIndex:t,contextNode:n}=h(),r=le(n.id).length;if(r===0)return;let o=Math.max(0,t),s=Math.min(Math.max(o+e,0),r-1);z.navigate({selectedIndex:s,contextNode:n})},Ug=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=h();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=le(o.id),i=s.findIndex(g=>g.id===t.id);if(i<0)return;let l=s.at(i+e)??s.at(0);if(!l)return;let u=le(l.id),m=Math.max(0,u.length-1),p=Math.min(Math.max(0,r),m),f=u.length?p:-1;z.navigate({contextNode:l,selectedIndex:f})};var Hg=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Wg=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=h();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},pC=e=>{let t=h().nodes[e];return!!t&&!t.isDeleted&&Fe(t)&&t.childRenderAxis==="vertical"},hi=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r||r.isDeleted)return!1;let o=be(r.id);return z.navigate({contextNode:r,selectedIndex:Hg(t,o.length)}),!0},Gg=e=>{let{nodes:t}=h(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return hi(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=be(o.id).findIndex(l=>l.id===n.id);return i>=0?(z.navigate({contextNode:o,selectedIndex:i}),!0):Gg(o.id)},jg=e=>{let{nodes:t}=h(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Gg(n))return!0;n=t[n]?.parentNodeId}return!1},fC=e=>{if(!e)return!1;let t=h().nodes[e];return!!t&&!t.isDeleted},zg=e=>{let{nodes:t,rootNodeId:n}=h();if(pC(e.contextNodeId)&&hi(e.contextNodeId,e.selectedIndex))return d("Restored navigation inside text container",null);if(fC(e.selectedNodeId)&&e.selectedNodeId&&jg(e.selectedNodeId))return d("Restored navigation to selected node or ancestor",null);if(hi(e.contextNodeId,e.selectedIndex))return d("Restored navigation to previous container",null);if(e.parentNodeId&&hi(e.parentNodeId,e.selectedIndex))return d("Restored navigation to previous parent",null);if(jg(e.contextNodeId))return d("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return a("Unable to restore navigation");let o=be(r.id);return z.navigate({contextNode:r,selectedIndex:Hg(e.selectedIndex,o.length)}),d("Restored navigation to root",null)};import{monotonicFactory as gC,ulid as Ut}from"ulid";var jo=gC();function hC(){let e=me();if(c(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[r]=le(n.id),[o]=r?le(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return d("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?d("Resolved boot nav target",{contextNode:r,selectedIndex:0}):d("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function yC(){let e=hC();return c(e)?e:z.navigate(e.value)}function Vg({userId:e,userName:t}){let n=jo(),r=jo(),o=jo(),s=jo(),i=jo(),l=Ge(void 0,void 0);if(c(l))return l;let u=Ge(void 0,void 0);if(c(u))return u;let m=Ge(u.value,void 0);if(c(m))return m;let p=Ge(void 0,void 0);if(c(p))return p;let f=Ge(p.value,void 0);if(c(f))return f;let g=Ge(f.value,void 0);if(c(g))return g;let v=Ge(void 0,void 0);return c(v)?v:d("Created default events",[{id:Ut(),userId:e,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:Ut(),userId:e,action:"create.contributor",payload:{id:e,name:t}},{id:Ut(),userId:e,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:u.value}},{id:Ut(),userId:e,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Ut(),userId:e,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Ut(),userId:e,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:g.value}},{id:Ut(),userId:e,action:"add.board",payload:{id:Es,name:"Closed",parent:n,rank:m.value}},{id:Ut(),userId:e,action:"add.swimlane",payload:{id:We,name:"Closed",parent:Es,rank:v.value}},{id:Ut(),userId:e,action:"lock.node",payload:{id:Es}},{id:Ut(),userId:e,action:"lock.node",payload:{id:We}}])}var bC=()=>{let e=me();if(c(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},vC=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(", ");V.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(", ");V.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}};function Ho(e,t=[]){if(bC())return d("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Ae.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=xo(s);return c(i)?i:(w({hasProjectDefinition:!1,mode:y.DEFAULT}),d("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=un(e),{fatal:r,skipped:o}=Gn(n);return r.length>0?a(`Materializing failed:
62
+ ${r.map(s=>s.message).join(`
63
+ `)}`):(zn(o),yC(),w({hasProjectDefinition:!0}),vC(t),d("State booted successfully",null))}import{WebSocket as xC}from"ws";var yi=new Set,S$=e=>{yi.add(e),e.on("close",()=>{yi.delete(e)}),e.on("error",()=>{yi.delete(e)})},Kg=e=>{let t=JSON.stringify(e);for(let n of yi)n.readyState===xC.OPEN&&n.send(t)};var bi=e=>{gt()&&(w({syncStatus:e}),Kg({type:"sync-status",payload:e}))},vi=(e="Syncing...")=>{bi({status:"syncing",msg:e})},Wo=(e="Synced")=>{bi({status:"synced",msg:e})},RC=e=>{bi({status:"failed",msg:e})},xi=e=>{bi({status:"offline",msg:e})},Te=e=>(RC(e),a(e));var Xn=(e,t)=>(logger.error(`[boot:${e}] ${t}`),a(`[boot:${e}] ${t}`)),qg=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)}},ce=(e,t)=>(c(t)&&logger.info(`[${e}]:failed`,t.message),t);import dh from"node:fs";import Yt from"node:fs";import Xt from"node:path";import Ri from"node:fs";import Yg from"node:path";var _e=".epiq/project.json",Xg=e=>Yg.join(e,_e),EC=e=>{if(!Ri.existsSync(Xg(e)))return d("State branch carries no identity yet",null);let t=He(e);return c(t)?a(`On the state branch: ${t.message}`):d("Read the state branch identity",t.value)},Cl=(e,t)=>{try{let n=Xg(e);return Ri.mkdirSync(Yg.dirname(n),{recursive:!0}),Ri.writeFileSync(n,JSON.stringify(t,null,2)+`
64
+ `,"utf8"),d("Wrote the state branch identity",void 0)}catch(n){return a(n instanceof Error?`Failed to write the state branch identity: ${n.message}`:"Failed to write the state branch identity")}},SC=({checkout:e,branch:t,stateBranch:n})=>[`This checkout's ${_e} names project ${e.projectId}`,`(created ${e.createdAt}), but the state branch ${n}`,`belongs to project ${t.projectId} (created ${t.createdAt}).`,"","The branch holds the board, so its id is the one that counts. Point the","checkout at it and commit the change:","",` git show ${n}:${_e} > ${_e}`,"","A second id is minted when init runs in a checkout that has no","project file while the state branch already exists; nothing on the","board is lost by it, but every checkout has to agree on one."].join(`
65
+ `);var Jg=({repoRoot:e,stateBranchRoot:t,stateBranch:n})=>{if(!Ri.existsSync(mr(e)))return d("No project file to compare","no-checkout-file");let r=He(e);if(c(r))return a(r.message);let o=EC(t);if(c(o))return a(o.message);if(o.value===null){let s=Cl(t,r.value);return c(s)?a(s.message):d("Stamped the state branch with this project","stamped")}return o.value.projectId!==r.value.projectId?a(SC({checkout:r.value,branch:o.value,stateBranch:n})):d("The checkout and the state branch agree","matched")};import jt from"node:fs";import Go from"node:path";var Ar=e=>e.split(`
66
+ `).filter(t=>t.trim().length>0),Zg=e=>{let t=Go.join(e,je,Gt);try{if(!jt.existsSync(t))return d("No events directory",[]);let n=jt.readdirSync(t).filter(r=>r.endsWith(".jsonl")).filter(r=>Ar(jt.readFileSync(Go.join(t,r),"utf8")).length>0);return d("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)}`)}},Qg=e=>Go.join(e,je,Gt),eh=e=>{let t=Qg(e),n=new Map;try{if(!jt.existsSync(t))return n;for(let r of jt.readdirSync(t))if(r.endsWith(".jsonl")&&!Wn(r))try{n.set(r,Ar(jt.readFileSync(Go.join(t,r),"utf8")))}catch(o){if(!fo(o))throw o}}catch{return n}return n},CC=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},th=(e,t)=>{if(t.size===0)return[];let n=Qg(e),r=[];for(let[o,s]of t){if(s.length===0)continue;let i=Go.join(n,o);try{let l=jt.existsSync(i)?jt.readFileSync(i,"utf8"):null,u=new Set(l===null?[]:Ar(l)),m=s.filter(f=>!u.has(f)).filter(CC);if(m.length===0)continue;jt.mkdirSync(n,{recursive:!0});let p=l!==null&&l.length>0&&!l.endsWith(`
67
+ `);jt.appendFileSync(i,`${p?`
68
+ `:""}${m.join(`
69
+ `)}
70
+ `,"utf8"),r.push(`${o} (${m.length})`)}catch{continue}}return r},NC=(e,t)=>{let n=new Set(Ar(t));return Ar(e).filter(r=>!n.has(r))},IC=(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(`
71
+ `),nh=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let r=await Ie({args:["show",`HEAD:${t}`],cwd:e});if(r.exitCode!==0)return d("No committed log to compare against",void 0);let o=NC(r.stdout,n);return o.length>0?a(IC(t,o,Ar(r.stdout).length)):d("Event log only grew",void 0)};var wC="[epiq:init-repo]",oh=async e=>{let t=await Ie({args:["rev-parse","--verify","--quiet","HEAD"],cwd:e});if(t.exitCode===0)return d("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(`
72
+ `));V.info("Creating initial commit");let r=await _({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(c(r))return a(r.message);let o=await _({args:["commit-tree",r.value.stdout.trim(),"-m",wC],cwd:e});if(c(o))return a(o.message);let s=await _({args:["update-ref","HEAD",o.value.stdout.trim()],cwd:e});return c(s)?a(s.message):d("Created initial commit",!0)},rh=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",AC=async e=>{let t=await ys(e);if(c(t))return a(t.message);let n=await yu(e);return c(n)?a(n.message):d("Built sync commit message",`[sync|branch:${rh(t.value)}:sha:${rh(n.value)}]`)},Nl=async({repoRoot:e,stateBranchName:t})=>{V.info(`Creating ${t}`);let n=await _({args:["commit-tree",Au,"-m","[epiq:init-state-branch]"],cwd:e});if(c(n))return a(`Failed to create state branch commit
73
+ ${n.message}`);let r=n.value.stdout.trim(),o=await _({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return c(o)?a(`Failed to create ${t}
74
+ ${o.message}`):d("Created state branch",!0)},Il=async({repoRoot:e,stateBranchName:t})=>{let n=await hs({repoRoot:e,branch:t});if(c(n))return a(`Ensure local state branch failed
75
+ `+n.message);if(n.value)return d("Local state branch already exists",!1);let r=await Wt({repoRoot:e});if(c(r))return a(`Ensure local state branch failed
76
+ `+r.message);let o=r.value,s=o?await Kr({repoRoot:e,branch:t}):d("No remote, no remote state branch",!1);if(c(s))return a(`Ensure local state branch failed
77
+ `+s.message);let i=s.value;if(o&&i){let l=await fe.fetch({cwd:e,remote:st,branch:t});if(c(l))return a(`Failed to fetch ${t} from remote
78
+ ${l.message}`)}if(i){let l=await _({args:["branch","--track",t,`${st}/${t}`],cwd:e});return c(l)?a(`Failed to create local ${t} from remote
79
+ ${l.message}`):d("Created local state branch from remote",!0)}return Nl({repoRoot:e,stateBranchName:t})},TC=async({repoRoot:e,branch:t})=>{let n=await _({args:["worktree","list","--porcelain"],cwd:e});if(c(n))return a(n.message);let r=n.value.stdout.split(`
80
+ `),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return d("Found worktree for branch",o)}return d("No worktree found for branch",null)},MC=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=Xr(Xt.dirname(t));if(c(r))return a(`Failed to create state branch worktree
81
+ `+r.message);if(Yt.existsSync(t)&&!Yt.existsSync(Xt.join(t,".git"))){let s=Zg(t);if(c(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(`
82
+ `));V.info("Removing broken state branch worktree path"),Lu(t)}V.info("Creating state branch worktree");let o=await fe.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return c(o)?a(`Failed to create state branch worktree
83
+ ${o.message}`):d("Created state branch worktree",!0)},Tr=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await LC({repoRoot:e,stateBranchRoot:t,stateBranchName:n});if(c(r))return r;let o=Jg({repoRoot:e,stateBranchRoot:t,stateBranch:n});return c(o)?a(o.message):(o.value==="stamped"&&V.info("Stamped the state branch with this project\u2019s identity"),r)},kC=(e,t)=>{let n=dr(On());return Xt.dirname(e)===n&&Xt.dirname(t)===n},LC=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await TC({repoRoot:e,branch:n});if(c(r))return a(r.message);let o=dr(t),s=r.value?dr(r.value):null;if(s&&s===o&&Yt.existsSync(s))return d("State branch already checked out in expected worktree",!1);if(s&&s!==o&&kC(s,o))return a([`The state branch ${n} is checked out under project ${Xt.basename(s)}, but this checkout names project ${Xt.basename(o)}.`,"","Two ids for one branch means a checkout minted a second identity for","a board that already existed. Nothing on the board is lost by it, but",`every checkout has to agree on one: compare ${_e} here`,`with \`git show ${n}:${_e}\`, and keep the branch's.`].join(`
84
+ `));if(s&&s!==o){let u=await Su(s);if(c(u))return a(u.message);if(u.value||Wm(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 ${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(`
85
+ `));V.info("Moving state branch worktree to expected location");let m=await fe.worktreeRemove({cwd:e,worktreeRoot:s});if(c(m))return a(`Failed to remove existing state branch worktree
86
+ ${m.message}`)}if(s&&!Yt.existsSync(s)){V.info("Pruning stale state branch worktree");let u=await fe.worktreePrune({cwd:e});if(c(u))return a(`Failed to prune stale worktrees
87
+ ${u.message}`)}let i=await hu({repoRoot:e,worktreeRoot:t});if(c(i))return a(i.message);let l=Yt.existsSync(t);if(i.value&&l)return d("State branch worktree already exists",!1);if(i.value&&!l){V.info("Pruning missing registered state branch worktree");let u=await fe.worktreePrune({cwd:e});if(c(u))return a(`Failed to prune stale worktrees
88
+ ${u.message}`)}return MC({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},PC=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await ys(e);if(c(n))return a(n.message);if(n.value===t)return d("State branch already checked out",!1);(await Ie({cwd:e,args:["rebase","--abort"]})).exitCode===0&&V.info("Aborted stale state branch rebase");let o=await fe.checkout({cwd:e,branch:t});return c(o)?a(`Failed to checkout ${t}
89
+ ${o.message}`):d("Checked out state branch",!0)},OC=async({repoRoot:e,stateBranchRoot:t})=>{let n=await wa(t);if(c(n))return a(n.message);if(n.value)return d("State branch upstream already configured",!1);let r=await Wt({repoRoot:t});if(c(r))return a(r.message);if(!r.value)return d("No remote available for state branch upstream",!1);let o=It(e);if(c(o))return o;let s=o.value,i=await Kr({repoRoot:t,branch:s});if(c(i))return a(i.message);if(!i.value)return d("Remote state branch missing; upstream will be configured on first push",!1);V.info(`Configuring ${s} upstream`);let l=await fe.fetch({cwd:t,remote:st,branch:s});if(c(l))return a(`Failed to fetch ${s}
90
+ ${l.message}`);let u=await fe.setUpstream({cwd:t,branch:s,upstream:`${st}/${s}`});return c(u)?a(`Failed to set state branch upstream
91
+ ${u.message}`):d("Configured state branch upstream",!0)},Ei=async({stateBranchRoot:e,eventFileName:t})=>{let n=Tu(t),r=Xt.join(e,n);if(!Yt.existsSync(r))return d("No event file to stage",null);let o=await nh({stateBranchRoot:e,relativePath:n,workingContent:Yt.readFileSync(r,"utf8")});if(c(o))return a(o.message);let s=await fe.stage({cwd:e,pathspec:[n]});return c(s)?a(`Failed to stage state branch event file
92
+ ${s.message}`):d("Staged state branch event file",n)},sh=async({stateBranchRoot:e})=>{let t=Mu(),n=Xt.join(e,t);if(!Yt.existsSync(n))return d("No media directory to stage",null);let r=await fe.stage({cwd:e,pathspec:[t],ignoreRemoval:!0});return c(r)?a(`Failed to stage state branch media files
93
+ ${r.message}`):d("Staged state branch media files",t)},ih=async({stateBranchRoot:e})=>{let t=[Ta(),Ma(),_e].filter(r=>Yt.existsSync(Xt.join(e,r)));if(t.length===0)return d("No event log config to stage",[]);let n=await fe.stage({cwd:e,pathspec:t});return c(n)?a(`Failed to stage event log config
94
+ ${n.message}`):d("Staged event log config",t)},ah=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let r=await AC(e);return c(r)?a(`Create state branch sync commit failed
95
+ `+r.message):ur({cwd:t,message:r.value,pathspec:n})},zo=async({repoRoot:e,stateBranchRoot:t})=>{let n=await wa(t);if(c(n))return a(n.message);let r=It(e);if(c(r))return r;let o=r.value,s=n.value?await fe.push({cwd:t}):await fe.push({cwd:t,remote:st,branch:o,setUpstream:!0});if(c(s))return a(`Failed during state branch push
96
+ ${s.message}`);let i=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return d(i?"Pushed state branch":"Remote already up to date",i)},ch=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=It(e);if(c(o))return o;let s=o.value,i=[Jr(),await Il({repoRoot:e,stateBranchName:s}),await Tr({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await PC({stateBranchRoot:t,stateBranchName:s}),await Ou(t),n?await OC({stateBranchRoot:t,repoRoot:e}):d("Skipped state branch upstream bootstrap",!1)];for(let l of i){if(c(l))return a(l.message);r=r||!!l.value}return d(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};var DC=async({claim:e,cwd:t,ensureUpstream:n})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:t,ensureUpstream:n});let r=ce("getRepoRootDir",await wt(t));if(c(r))return a(r.message);let o=r.value;logger.debug("[sync] repo root",o);let s=ce("getStateBranchRoot",ve({repoRoot:o}));if(c(s))return a(s.message);let i=s.value;if(logger.debug("[sync] state branch root",i),e!=="stale"&&dh.existsSync(i)){let p=await xu(i,{preserve:[Qs]});if(c(p))return a(p.message);p.value.length>0&&logger.info("[sync] cleared git lock files left by a dead process",{removed:p.value,stateBranchRoot:i});let f=It(o);if(c(f))return a(f.message);let g=await Ru(i,f.value);if(c(g))return a(g.message);g.value&&logger.info("[sync] cleared a ref lock left by a dead process",{branch:f.value,stateBranchRoot:i});let v=ce("abortRebaseIfPresent(stateBranchRoot)",await Aa(i));if(c(v))return a(v.message)}logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:i,ensureUpstream:n});let l=ce("bootstrapStateBranchStorage",await ch({repoRoot:o,stateBranchRoot:i,ensureUpstream:n}));if(c(l))return a(l.message);logger.debug("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:i}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:i});let u=ce("getInProgressGitOperation(stateBranchRoot)",await Ia(i));if(c(u))return a(u.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:u.value}),u.value!==null)return logger.info("[sync] state branch git operation in progress",{claim:e}),a(`Cannot sync while there is a ${u.value} in the state branch at ${i}`);logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:i});let m=ce("ensureStateBranchLayout",Pu(o,i));return c(m)?a(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:i,bootstrapped:l.value}),d("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:i,bootstrapped:l.value}))},FC=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=[];for(let m of rp(Ye(t),n)){let p=ce("stageStateBranchOwnEventFile",await Ei({stateBranchRoot:t,eventFileName:m}));if(c(p))return a(p.message);r.push(p.value)}let o=ce("stageStateBranchMediaFiles",await sh({stateBranchRoot:t}));if(c(o))return a(o.message);let s=ce("stageStateBranchEventConfig",await ih({stateBranchRoot:t}));if(c(s))return a(s.message);let i=[...r,o.value,...s.value].filter(m=>m!==null);if(i.length===0)return d("Nothing to stage",{createdCommit:!1});let l=ce("hasStagedChanges(after stage)",await Cu(t,i));if(c(l))return a(l.message);if(logger.debug("[sync] state branch change check after stage result",{changed:l.value}),!l.value)return logger.info("[sync] no own event file changes to commit"),d("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let u=ce("createStateBranchSyncCommit",await ah({repoRoot:e,stateBranchRoot:t,pathspec:i}));return c(u)?a(u.message):(logger.debug("[sync] created sync commit",u.value),d("Committed own event file",{createdCommit:!0,commitSha:u.value}))},wl=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return xi(n),d(n,{...e,pulled:!1,pushed:!1,offline:!0})},lh=async({cwd:e=process.cwd(),ownEventFileName:t},n)=>{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");vi();let r=ce("ensureSyncReady",await DC({claim:n,cwd:e,ensureUpstream:!0}));if(c(r))return Te(r.message);let{repoRoot:o,stateBranchRoot:s,bootstrapped:i}=r.value,l=ce("isDetachedHead(stateBranchRoot)",await Nu(s));if(c(l))return Te(l.message);if(logger.debug("[sync] detached state branch check result",{detached:l.value}),l.value)return Te("Cannot run :sync while the state branch is in detached HEAD state");let u=!1,m,p=!1,f=!1,g=ce("getStateBranch",It(o));if(c(g))return Te(g.message);let v=g.value;logger.debug("[sync] resolved state branch",{stateBranch:v,stateBranchRoot:s});let I=ce("flushPendingLogs",Us(s,t));c(I)&&logger.error(`[sync] ${I.message}`);let x=ce("commitOwnEventFileToStateBranch",await FC({repoRoot:o,stateBranchRoot:s,ownEventFileName:t}));if(c(x))return Te(x.message);u=x.value.createdCommit,m=x.value.commitSha;let E=ce("hasRemote",await Wt({repoRoot:s}));if(c(E))return Te(E.message);if(!E.value)return wl({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:m,bootstrapped:i},"no remote");let N=ce("pullBranchRebaseIfPresent",await Yr({cwd:s,branch:v}));if(c(N))return qr(N.message)?wl({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:m,bootstrapped:i}):Te(N.message);p=N.value;let S=ce("isAheadOfUpstream",await Eu(s));if(c(S))return Te(S.message);if(u||i||S.value){logger.info("[sync] pushing state branch",{createdCommit:u,bootstrapped:i,stateBranchRoot:s});let T=ce("pushStateBranch",await zo({stateBranchRoot:s,repoRoot:o}));if(c(T)&&bu(T.message)){let k=ce("pullBranchRebaseIfPresent(retry)",await Yr({cwd:s,branch:v}));if(c(k))return Te(k.message);p=p||k.value,T=ce("pushStateBranch(retry)",await zo({stateBranchRoot:s,repoRoot:o}))}if(c(T))return qr(T.message)?wl({repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:m,bootstrapped:i}):Te(T.message);f=T.value}if(u){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:s});let T=ce("git rev-parse HEAD",await _({args:["rev-parse","HEAD"],cwd:s}));if(c(T))return Te(T.message);m=T.value.stdout.trim(),logger.debug("[sync] final sync commit sha",m)}return Wo(f?"Synced and pushed":p||u?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),d("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:s,createdCommit:u,commitSha:m,pulled:p,pushed:f,bootstrapped:i,offline:!1})},Si=async(e,t)=>{let n=eh(e);try{return await t()}finally{let r=th(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},uh=async e=>{let t=e.cwd??process.cwd(),n=await wt(t);if(c(n))return Te(n.message);let r=ve({repoRoot:n.value});if(c(r))return Te(r.message);let o=r.value;if(!dh.existsSync(o))return lh(e,"clean");let s=await wo({worktreeRoot:o,operation:"sync",fn:i=>Si(o,()=>lh(e,i))});return c(s)?Te(s.message):s.value===null?d("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 Mr=null,Ci=async({reposMinIntervalMs:e=0}={})=>(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Mr,currentStatus:h().syncStatus?.status,currentMessage:h().syncStatus?.msg}),Mr?(logger.debug("[sync] syncAndReloadState joining existing promise"),Mr):(logger.debug("[sync] syncAndReloadState creating promise"),Mr=_C(e).finally(()=>{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:h().syncStatus?.status,statusMessageBeforeClear:h().syncStatus?.msg}),Mr=null}),Mr)),_C=async e=>{let t;try{t=await $C(e),logger.debug("[sync] syncAndReloadState promise resolved",{success:!c(t),message:t.message,statusAfterResolve:h().syncStatus?.status,statusMessageAfterResolve:h().syncStatus?.msg})}catch(r){let o=r instanceof Error?r.message:String(r);logger.error("[sync] syncAndReloadState promise threw",{message:o,error:r}),t=a(o)}let n=me();return c(t)&&!c(n)&&n.value.syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),w({syncStatus:{msg:t.message,status:"failed"}})),t},$C=async e=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:h().mode,syncStatus:h().syncStatus});let t=mh();if(t)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:h().mode,message:t.message,syncStatus:h().syncStatus}),t;logger.debug("[sync] syncAndReloadState:start");let n=ce("resolveActorId",te());if(c(n)||!n.value)return logger.info("[sync] unable to resolve actor id",{message:c(n)?n.message:"Missing actor id"}),a("Unable to resolve event log path");w({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:h().syncStatus});let r=xr(n.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:r}),logger.debug("[sync] syncEpiqWithRemote:start");let o=ce("syncEpiqWithRemote",await uh({ownEventFileName:r}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!c(o),message:(c(o),o.message)}),c(o))return logger.error("[sync] syncAndReloadState:sync failed",o.message),w({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:h().syncStatus}),Te(`Unable to sync state. ${o.message}`);let{stateBranchRoot:s,offline:i,repoRoot:l}=o.value,u=Al(s);return c(u)?u:(w({hasProjectDefinition:!0,syncStatus:i?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:h().syncStatus}),BC(l,e),d("Synced",!0))},BC=async(e,t)=>{let n=await oi({repoRoot:e,minIntervalMs:t}),r=c(n)?null:zc(n.value),o=h().syncStatus;r&&o?.status==="synced"&&w({syncStatus:{msg:`Synced \xB7 ${r}`,status:"synced"}})},Al=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=Tt(e),n=ce("loadMergedEvents",Eo(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!c(n),message:(c(n),n.message),count:c(n)?void 0:n.value.events.length}),c(n))return w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:h().syncStatus}),a(`Unable to load events. ${n.message}`);logger.debug("[sync] loaded merged events after sync",{count:n.value.events.length});let r=mh();if(r)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:h().mode,message:r.message,syncStatus:h().syncStatus}),r;let o=Wg(),s=h().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:o,selectedNodeId:h().selectedNode?.id,contextNodeId:h().contextNode?.id,selectedNodeIsVirtual:h().selectedNode?.isVirtual,contextNodeIsVirtual:h().contextNode?.isVirtual}),!h().selectedNode?.isVirtual&&!h().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:n.value.events.length});let l=me(),u=!c(l)&&l.value.timeMode==="live",m=ce("bootStateFromEventLog",Ho(n.value.events,n.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!c(m),message:(c(m),m.message)}),c(m))return w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:h().syncStatus}),a(`Unable to boot synced state. ${m.message}`);u&&Fs(e,t)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:h().selectedNode?.isVirtual,contextNodeIsVirtual:h().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),w({filters:s}),logger.debug("[sync] restoreNavigationAnchor:start");let i=ce("restoreNavigationAnchor",zg(o));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!c(i),message:c(i)?i.message:"Navigation restored",selectedNodeId:h().selectedNode?.id,contextNodeId:h().contextNode?.id}),c(i)?(w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:h().syncStatus}),i):d("Reloaded state from event log",null)},mh=()=>h().mode===y.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:h().mode,syncStatus:h().syncStatus}),w({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),a("Will not re-materialize if not in default mode, to not lose edit data"));var ph=0,Tl,Ml=!1,Vo=!1,kl=()=>{if(Ml)return!0;let e=me();return c(e)?!1:e.value.syncStatus.status==="syncing"},UC=()=>{let e=ms(ne().autoSyncIntervalMs),t=Date.now()-ph;return Math.max(0,e-t)},fh=()=>{Tl||(Tl=setTimeout(async()=>{if(Tl=void 0,!!gt()){if(kl()){Vo=!0;return}Vo=!1,await jC()}},UC()))},jC=async()=>{if(h().readOnly||h().timeMode==="peek"||h().timeMode==="replay")return a("Cannot auto-sync while peeking");if(!gt())return a("Cannot auto-sync before state is initialized");if(kl())return Vo=!0,a("Sync already in progress");Ml=!0,ph=Date.now(),w({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Ci({reposMinIntervalMs:6e4})}finally{Ml=!1,Vo&&fh()}},gh=()=>{gt()&&(Vo=!0,!kl()&&fh())};var hh=e=>{let{context:t}=h().contextNode;if(!t)return j.None;switch(e){case b.EXIT:return j.Exit;case b.EXPORT:return j.Export;case b.INIT:return j.Init;case b.OPEN:return j.OpenProject;case b.DELETE:return j.Delete;case b.EDIT:return j.Edit;case b.COMMENT:return j.Comment;case b.HELP:return j.ViewHelp;case b.RE_OPEN_ISSUE:return j.ReopenIssue;case b.CLOSE_ISSUE:return j.CloseIssue;case b.TAG:return j.TagTicket;case b.UNTAG:return j.UntagTicket;case b.GOAL:return j.GoalTicket;case b.UNGOAL:return j.UngoalTicket;case b.RULE:return j.RuleLane;case b.UNRULE:return j.UnruleLane;case b.ASSIGN:return j.AssignUserToTicket;case b.UNASSIGN:return j.UnassignUserFromTicket;case b.NEW:return j.NewItem;case b.FILTER:return j.Filter;case b.MOVE:return j.Move;case b.PEEK:return j.Peek;case b.REPLAY:return j.Replay;case b.CONFIG:return j.Config;case b.YANK:return j.Yank;case b.SYNC:return j.Sync;default:return j.None}},j={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",GoalTicket:"ticket-goal",UngoalTicket:"ticket-ungoal",RuleLane:"lane-rule",UnruleLane:"lane-unrule",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export"};import iy from"node:fs";import JN from"node:path";import ZN from"react";import{Box as YN}from"ink";import Fi from"react";import Ih from"chalk";import{Box as Ol,Text as sN}from"ink";import Ht from"react";import{Text as yh}from"ink";import bh,{useEffect as vh,useState as HC}from"react";var xh={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "],identity:["\u276F "]},yt=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=Pe(),r=xh[n]??xh.default,[o,s]=HC(0);if(vh(()=>{s(0)},[r]),vh(()=>{if(!e)return;let l=setInterval(()=>{s(u=>(u+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return bh.createElement(yh,null,t);let i=r[o]??r[0]??t;return bh.createElement(yh,{color:A.accent,dimColor:o===1},i)};import{Box as Ll,Text as WC}from"ink";import Ni from"react";var GC=(e,t,n,r)=>{let o=u=>Math.max(1,e[u]??1),s=n,i=n+1,l=o(n);for(;i<t&&l+o(i)<=r;)l+=o(i),i++;for(;s>0&&l+o(s-1)<=r;)s--,l+=o(s);return{start:s,end:i}},bt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),l=Math.max(1,Math.ceil(r)),u=Math.max(0,Math.min(n,e.length-1)),m=Math.max(1,Math.floor(i/l)),p=Math.max(0,e.length-m),{start:f,end:g}=o?GC(o,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},v=Math.max(1,g-f),I=e.slice(f,g),x=e.length>v,E=i,N=x?Math.max(1,Math.floor(v/e.length*E)):E,S=Math.max(0,E-N),T=Math.max(1,e.length-v),k=x?Math.floor(f/T*S):0;return Ni.createElement(Ll,{flexDirection:"row",height:i,width:"100%"},Ni.createElement(Ll,{flexDirection:"column",flexGrow:1,height:i},I),Ni.createElement(Ll,{flexDirection:"column",width:1,height:E},Array.from({length:E}).map((H,L)=>Ni.createElement(WC,{key:L,color:x&&L>=k&&L<k+N?A.accent:A.secondary},x?"\u2502":" "))))};import{Box as Jn,Text as Zn}from"ink";import $e from"react";var Rh,Pl,zC=()=>{let{eventLog:e=[]}=h();if(Pl&&Rh===e)return Pl;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Rh=e,Pl=t,t},Ii=e=>zC().has(e);import{Text as VC}from"ink";import KC from"react";var kr=({id:e,isSelected:t,maxWidth:n})=>{let r=R.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:Ln(o,n);return KC.createElement(VC,{underline:t,color:Ue(o)},"@"+s,Ii(e)?"":"\u2197")};import{Text as qC}from"ink";import YC from"react";var wi=({id:e,isSelected:t,maxWidth:n})=>{let r=R.getTag(e);if(!r)return;let o=n===void 0?r.name:Ln(r.name,n);return YC.createElement(qC,{underline:t,backgroundColor:Ue(r.name),color:A.secondary}," "+o+" ")};import{useEffect as XC,useState as JC}from"react";var ZC=80,Eh=1400,Ai=new Set,Ko=null,QC=e=>(Ai.add(e),Ko||(Ko=setInterval(()=>{for(let t of Ai)t()},ZC)),()=>{Ai.delete(e),Ai.size===0&&Ko&&(clearInterval(Ko),Ko=null)}),eN=()=>{let e=Date.now()%Eh/Eh;return e<.5?e*2:(1-e)*2},Lr=e=>{let[,t]=JC(0);return XC(()=>{if(e)return QC(()=>t(n=>n+1))},[e]),Td(eN())};var tN=(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),Ln(e.slice(o).trim(),n)]},Sh=3,nN=2,rN=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let i=e.length-o-1,l=i>0?String(i).length+1:0;if(r+s.width+l>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},Ch=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Lr(r),s=e-4,i=s-7-1,[l,u]=tN(ut(t.title),i,s),m=u?null:Ln(ut(t.props.description),s)||null,p=on(t),f=sn(t).map(T=>({...T,name:T.name})),g=Math.max(1,s-Sh),v=R.getCommentsByIssue(t.id),I=v.length?String(v.length).length+2+1:0,x=Ms(t,Math.max(1,Math.floor(s/2))),E=x?x.text.length+1:0,{shown:N,hidden:S}=rN([...p.map(T=>({id:T.id,isTag:!0,width:Math.min(T.name.length,g)+Sh})),...f.map(T=>({id:T.id,isTag:!1,width:Math.min(T.name.length,g)+nN+(Ii(T.id)?0:1)}))],s-I-E);return $e.createElement(Jn,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?A.accent:A.secondary,justifyContent:"space-between"},$e.createElement(Jn,{paddingLeft:1,paddingRight:1,flexDirection:"column"},$e.createElement(Jn,{justifyContent:"space-between"},$e.createElement(Zn,{color:A.primary},l),$e.createElement(Zn,{color:A.secondary2,dimColor:!0},at(t.id))),u&&$e.createElement(Zn,{color:A.primary},u),m&&$e.createElement(Zn,{color:A.secondary2,dimColor:!0},m)),$e.createElement(Jn,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},$e.createElement(Jn,{flexDirection:"row"},x&&$e.createElement(Jn,{paddingRight:1},$e.createElement(Zn,{color:x.color},x.text)),N.map(T=>$e.createElement(Jn,{paddingRight:1,key:T.id},T.isTag?$e.createElement(wi,{id:T.id,maxWidth:g}):$e.createElement(kr,{id:T.id,maxWidth:g}))),S>0&&$e.createElement(Zn,{color:A.secondary2,dimColor:!0},"+",S)),v.length>0&&$e.createElement(Zn,{color:A.accent},"[",v.length,"]")))};import{Box as bn,Text as Pr}from"ink";import ze from"react";var oN=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,Nh=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let l=Lr(s),u=(r.props.tags??[]).map(P=>R.getTag(P)).filter(P=>!!P),m=(r.props.assignees??[]).map(P=>R.getContributor(P)).map(P=>P&&{...P,name:P.name}).filter(P=>!!P),p=1,f=Ms(r,0),g=f?1+p:0,v=u.length*(1+p)+g,I=m.length*(2+p),x=u.map(P=>ze.createElement(bn,{key:P.id,paddingRight:p},ze.createElement(Pr,{color:Ue(P.name)},"\u25A0"))),E=m.map(P=>ze.createElement(bn,{key:P.id,paddingRight:p},ze.createElement(Pr,{color:aa(P.name)},"@"+P.name.at(0)))),N=s?l:o?A.accent:i===y.MOVE?A.secondary:A.primary,S=R.getCommentsByIssue(r.id),T=S.length?String(S.length).length+2+p:0,k=S.length?ze.createElement(bn,{paddingRight:p},ze.createElement(Pr,{color:A.accent},"[",S.length,"]")):null,H=v+I+T,L=Math.max(1,n-t-H-(H>0?1:0));return ze.createElement(bn,{justifyContent:"space-between"},ze.createElement(bn,null,ze.createElement(bn,{width:t},o?ze.createElement(yt,{isSelected:!0}):ze.createElement(Pr,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),ze.createElement(Pr,{wrap:"truncate",color:N},oN(r.title,L))),ze.createElement(bn,null,f&&ze.createElement(bn,{paddingRight:p},ze.createElement(Pr,{color:f.color},"\u25C6")),x,E,k))};var iN=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:l})=>{let{renderedChildrenIndex:u,replay:m}=Pe(),p=u[e.id]??[],f=m?new Set(m.flashNodeIds):null,g=f?.has(e.id)??!1,v=Lr(g),I=Is(e.id),x=`${e.title} ${Ih.hex(A.secondary2).dim("("+p.length+")")}${I?Ih.hex(A.secondary2)(" \u2713"):""}`,E=3,N=o?1:5,S=s&&i===-1,T=n-3-(o?1:0)-(S?2:0),k=Math.max(2,String(p.length).length+1),H=r-E-1,L=Ht.createElement(Ol,{borderStyle:"round",borderColor:A.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},Ht.createElement(yt,{isSelected:t}),Ht.createElement(sN,{bold:!0,color:g?v:t?A.accent:A.primary},x," ",e.readonly?"\u{1F512}":"")),P=($,de)=>{let B=s&&i===de;if(!U($))return null;let F=f?.has($.id)??!1;return o?Ht.createElement(Nh,{key:$.id,index:de,labelWidth:k,width:T,ticket:$,isSelected:B,isFlashing:F,mode:l}):Ht.createElement(Ch,{key:$.id,width:T,ticket:$,isSelected:B,isFlashing:F})};return Ht.createElement(Ol,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?A.accent:A.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},L,Ht.createElement(Ol,null,p.length>0&&Ht.createElement(bt,{selectedIndex:i,height:H,itemHeight:N},p.map(P)),S&&Ht.createElement(yt,{isSelected:!0})))},wh=Ht.memo(iN);import{Box as _r,Text as WN}from"ink";import Qe,{useMemo as $r}from"react";var Ah=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},Th=(e,t,n)=>Ae.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});var Mh=e=>e.action==="add.issue.comment";import{Box as Or,Text as Jt}from"ink";import Be,{useEffect as aN,useMemo as cN,useRef as lN}from"react";import{decodeTime as kh}from"ulid";var vn=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"},Ti=e=>String(e).padStart(2,"0"),uj=e=>`${e.getFullYear()}-${Ti(e.getMonth()+1)}-${Ti(e.getDate())} ${Ti(e.getHours())}:${Ti(e.getMinutes())}`;var dN=e=>he(e,"attachments"),uN=e=>R.getAttachmentsByIssue(e.id).sort((t,n)=>kh(t.id)-kh(n.id)),Lh=e=>{for(let t of e)R.deleteNode(t.id)},mN=(e,t,n)=>Ae.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),pN=(e,t)=>{let n=R.getNode(dN(e.id));if(!n||!Fe(n))return[];let r=t.map((o,s)=>mN(o,s,n.id)).map(o=>R.createNode(o)).filter(St).map(({value:o})=>o).filter(Fe);return t.length>0&&h().selectedIndex<0&&z.navigate({contextNode:n,selectedIndex:0}),r},fN=e=>`${Math.max(1,Math.round(e/1024))} KB`;function Ph({ticket:e,width:t,height:n}){let r=cN(()=>uN(e),[e]),o=lN([]);aN(()=>(Lh(o.current),o.current=pN(e,r),()=>{Lh(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Pe(),l=Math.max(1,n-4),u=Math.max(12,t-32);return r.length===0?Be.createElement(Or,{flexDirection:"column",width:t,height:n,padding:1},Be.createElement(Jt,{color:A.primary},"No attachments yet."),Be.createElement(Or,{paddingTop:1},Be.createElement(Jt,{color:A.primary},"Attach images from the browser GUI"),Be.createElement(Jt,{color:A.accent}," epiq gui "),Be.createElement(Jt,{color:A.primary},"by dropping or pasting them."))):Be.createElement(Or,{flexDirection:"column",width:t,height:n},Be.createElement(Or,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:A.secondary,borderStyle:"single",paddingBottom:1},Be.createElement(Jt,{color:A.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),Be.createElement(bt,{height:l,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,g=m.name.length>u?m.name.slice(0,u-1)+"\u2026":m.name;return Be.createElement(Or,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},Be.createElement(Jt,{color:A.accent},f?"\u276F ":" "),Be.createElement(Or,{paddingLeft:1},Be.createElement(Jt,{color:A.secondary2},`#${p+1} `),Be.createElement(Jt,{color:f?A.accent:A.primary},g),Be.createElement(Jt,{color:A.secondary2}," "+fN(m.bytes)+" "+vn(kn(m.id)))))})))}import{Box as xn,Text as Rn}from"ink";import Le,{useEffect as xN,useMemo as Uh,useRef as RN}from"react";import{decodeTime as jh}from"ulid";var gN=(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 i of r){let l=i;for(;l.length>n;)s&&(o.push(s),s=""),o.push(l.slice(0,n)),l=l.slice(n);s?s.length+1+l.length<=n?s=`${s} ${l}`:(o.push(s),s=l):s=l}return s&&o.push(s),o},qo=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)},hN=/!\[([^\]]*)\]\([^)]*\)/g,yN=e=>e.replace(hN,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),bN=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),vN=4,Mi=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(vN)),Dl=e=>{let t=!1;return e.map(Mi).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=Oo(n);if(r)return{kind:"caption",text:tl(r)};let o=yN(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:qo(s[1]??"")}:{kind:"text",spans:qo(o)}})},Dh=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],Oh=(e,t)=>{let n=[];for(let r of Dl(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 Dh(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of gN(bN(r.spans),t))n.push({kind:r.kind,spans:qo(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},Fh=(e,t)=>{let n=Oo(e),r=n?Df(e):null;if(!n||r===null)return Oh(el(e).split(`
97
+ `),t);let o=Ff(e),s=r.split(`
98
+ `).map(Mi),i=n.side===n.endSide?n.start:void 0,l=i===void 0?0:String(i+s.length-1).length+3;return[...o?[...Oh(o.split(`
99
+ `),t),{kind:"blank"}]:[],{kind:"caption",text:tl(n)},...s.flatMap((u,m)=>Dh(u,Math.max(1,t-l)).map((p,f)=>({kind:"code",text:p,number:i===void 0||f>0?void 0:i+m})))]};import{Box as _h,Text as Qn}from"ink";import vt from"react";var $h=({spans:e,bold:t,wrap:n})=>vt.createElement(Qn,{color:A.primary,bold:t,wrap:n},e.map((r,o)=>r.code?vt.createElement(Qn,{key:o,color:A.yellow},r.text):vt.createElement(Qn,{key:o},r.text))),Fl=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return vt.createElement(Qn,null," ");case"fence":return vt.createElement(Qn,{color:A.secondary2},"```");case"caption":return vt.createElement(Qn,{color:A.accent,wrap:r},e.text);case"heading":return vt.createElement($h,{spans:e.spans,bold:!0,wrap:r});case"text":return vt.createElement($h,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return vt.createElement(Qn,{backgroundColor:A.secondary,color:A.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},Bh=({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 vt.createElement(_h,{flexDirection:"column"},e.map((o,s)=>vt.createElement(_h,{key:s},vt.createElement(Fl,{line:o,width:t,gutter:r}))))};var EN=4,SN=e=>he(e,"comments"),CN=e=>R.getCommentsByIssue(e.id).sort((t,n)=>jh(t.id)-jh(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,md:t.md})),Hh=e=>{for(let t of e)R.deleteNode(t.id)},NN=(e,t)=>{let n=R.getNode(SN(e.id));if(!n||!Fe(n))return[];let r=t.map((o,s)=>Th(o,s,n.id)).map(R.createNode).filter(St).map(({value:o})=>o).filter(zr);return t.length>0&&h().selectedIndex<0&&z.navigate({contextNode:n,selectedIndex:0}),r};function Wh({ticket:e,width:t,height:n}){let r=Uh(()=>CN(e),[e]),o=RN([]);xN(()=>(Hh(o.current),o.current=NN(e,r),()=>{Hh(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=Pe(),l=Math.max(1,n-4),u=Math.max(20,t-8),m=Uh(()=>r.map(f=>{let g=Fh(f.md,u);return g.length>0?g:[{kind:"blank"}]}),[r,u]),p=m.map(f=>f.length+EN);return r.length===0?Le.createElement(xn,{flexDirection:"column",width:t,height:n,padding:1},Le.createElement(Rn,{color:A.primary},"No comments yet."),Le.createElement(xn,{paddingTop:1},Le.createElement(Rn,{color:A.primary},"Use"),Le.createElement(Rn,{color:A.accent}," :comment "),Le.createElement(Rn,{color:A.primary},"to add the first one."))):Le.createElement(xn,{flexDirection:"column",width:t,height:n},Le.createElement(xn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:A.secondary,borderStyle:"single",paddingBottom:1},Le.createElement(Rn,{color:A.secondary2},"Comments (",r.length,") ")),Le.createElement(bt,{height:l,itemHeights:p,selectedIndex:s},r.map((f,g)=>{let v=g===s;return Le.createElement(xn,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:A.secondary,borderStyle:"single"},Le.createElement(xn,{flexDirection:"row",paddingBottom:1},Le.createElement(Rn,{color:A.accent},v?"\u276F ":" "),Le.createElement(xn,{paddingLeft:1},Le.createElement(Rn,{color:A.secondary2},`#${g+1} `),Le.createElement(kr,{id:f.authorId}),Le.createElement(Rn,{color:A.secondary2}," "+vn(kn(f.id))))),Le.createElement(xn,{paddingLeft:3,paddingBottom:1},Le.createElement(Bh,{lines:m[g]??[],width:u})))})))}import{Box as Sn,Text as Ze}from"ink";import ye,{useEffect as Zh,useRef as PN,useState as ON}from"react";import{Box as kt,Text as Zt}from"ink";import Ce,{useEffect as Ul,useMemo as Kh,useRef as AN,useState as TN}from"react";var ki=(e,t,n)=>{let r=[],o=zs(()=>{for(let s=0;s<t;s++){let i=dt(BigInt(s+1));if(!St(i))continue;let l=R.createNode(Ae.text({id:n(s),name:`Line ${s+1}`,parentNodeId:e,rank:i.value,readonly:!0,isVirtual:!0}));St(l)&&r.push(l.value)}});return c(o)&&logger.error(`Line nodes: ${o.message}`),r},Dr=e=>{R.deleteNodes(e.map(t=>t.id))};import{useSyncExternalStore as IN}from"react";var Pi=null,Li=null,_l=new Set,Gh=()=>{for(let e of _l)e()},$l=e=>{Pi=e,Gh()},Oi=()=>Pi,zh={mark:null},er=e=>{Li=e,zh={mark:e},Gh()};var Bl=e=>Li&&Li.sha===e?Li.row:null,Vh=()=>IN(e=>(_l.add(e),()=>{_l.delete(e)}),()=>zh),En=()=>{let{contextNode:e}=h();return Pi&&Pi.sha===e.id?e.id:null};import MN from"string-width";var jl=(e,t)=>`${e}::patch::${t}`,qh=e=>Mi(e).replace(/[\x00-\x1f\x7f-\x9f]/g,"\uFFFD"),kN=e=>{switch(e){case"added":return A.green;case"removed":return A.red;case"hunk":return A.accent;case"file":return A.primary;default:return A.secondary2}},Yh=(e,t)=>{let n=MN(e);return n>=t?e:e+"\xA0".repeat(t-n)},LN=e=>e==="added"?"+":e==="removed"?"-":" ",Xh=e=>e.kind==="file"||e.kind==="hunk"||e.kind==="note"||e.newLine===void 0?"":String(e.newLine);function Jh({ticket:e,sha:t,repo:n,subject:r,width:o,height:s}){let[i,l]=TN({state:"loading"});Ul(()=>{let k=!0;return l({state:"loading"}),Qc({sha:t,repo:n}).then(H=>{k&&l(c(H)?{state:"failed",message:H.message}:{state:"loaded",rows:ol(rl(H.value))})}),()=>{k=!1}},[t,n]);let u=i.state==="loaded"?i.rows:null,m=u!==null&&u.length>4e3,p=AN([]);Ul(()=>(Dr(p.current),p.current=u&&!m?ki(t,u.length,k=>jl(t,k)):[],()=>{Dr(p.current),p.current=[]}),[t,u,m]),Ul(()=>($l(u?{sha:t,rows:u}:null),er(null),()=>{$l(null),er(null)}),[t,u]);let{selectedIndex:f}=Pe(),{mark:g}=Vh(),v=Kh(()=>u?sl(u,R.getCommentsByIssue(e.id),t):new Set,[u,t,e]),I=g&&g.sha===t?g.row:null,x=k=>I!==null&&k>=Math.min(I,f)&&k<=Math.max(I,f),E=Kh(()=>u?Math.max(5,u.reduce((k,H)=>Math.max(k,Xh(H).length),0)+2):5,[u]),N=Math.max(1,s-4),S=Math.max(8,o-E-6);if(i.state!=="loaded")return Ce.createElement(kt,{flexDirection:"column",width:o,height:s,padding:1},Ce.createElement(Zt,{color:A.primary},i.state==="loading"?"Reading the diff\u2026":`Could not read the diff: ${i.message}`));let T=k=>Ce.createElement(kt,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:A.secondary,borderStyle:"single",paddingBottom:1},Ce.createElement(Zt,{color:A.secondary2,wrap:"truncate-end"},Pn(`${t.slice(0,7)} ${r} \u2014 ${k}`,Math.max(8,o-6))));return i.rows.length===0?Ce.createElement(kt,{flexDirection:"column",width:o,height:s},T("no changes"),Ce.createElement(kt,{paddingX:1},Ce.createElement(Zt,{color:A.primary},"This commit changed no files."))):m?Ce.createElement(kt,{flexDirection:"column",width:o,height:s},T("too large to draw here"),Ce.createElement(kt,{paddingX:1,flexDirection:"column"},Ce.createElement(Zt,{color:A.primary},`${i.rows.length.toLocaleString()} lines of diff.`),Ce.createElement(Zt,{color:A.secondary2},"Press o to open it in your editor."))):Ce.createElement(kt,{flexDirection:"column",width:o,height:s},T(I===null?"enter to comment on a line, s to start a range, o editor, q back":"move to the other end, then enter to comment \u2014 s clears the mark"),Ce.createElement(bt,{scrollByOne:!0,height:N,selectedIndex:f,itemHeight:1},i.rows.map((k,H)=>{let L=H===f,P=kN(k.kind);if(k.kind==="file")return Ce.createElement(kt,{key:jl(t,H),paddingX:1},Ce.createElement(Zt,{backgroundColor:A.secondary,color:L?A.accent:P,bold:!0,wrap:"truncate-end"},Yh(` ${Pn(qh(k.text),S)}`,S+E+1)));let $=x(H),de=`${LN(k.kind)}${Pn(qh(k.text),S)}`;return Ce.createElement(kt,{key:jl(t,H),paddingX:1},Ce.createElement(kt,{flexShrink:0},Ce.createElement(Zt,{color:L||$?A.accent:A.secondary2,dimColor:!L&&!$,wrap:"truncate-end"},`${L?"\u276F":"\xA0"}${$?"\u258C":"\xA0"}${Xh(k).padStart(E-2,"\xA0")}`)),Ce.createElement(kt,{flexShrink:0},Ce.createElement(Zt,{color:A.yellow,wrap:"truncate-end"},v.has(H)?"\u2502":"\xA0")),Ce.createElement(Zt,{color:L?A.accent:P,backgroundColor:L||$?A.secondary:void 0,wrap:"truncate-end"},L||$?Yh(de,S+1):de))})))}var DN=e=>he(e,"diff"),Qh=e=>{for(let t of e)R.deleteNode(t.id)},FN=(e,t,n)=>Ae.field({id:e.sha,name:e.subject,parentNodeId:n,rank:String(t).padStart(6,"0"),childRenderAxis:"vertical",isVirtual:!0}),_N=(e,t)=>{let n=R.getNode(DN(e.id));if(!n||!Fe(n))return[];let r=t.map((o,s)=>FN(o,s,n.id)).map(o=>R.createNode(o)).filter(St).map(({value:o})=>o).filter(Fe);return t.length>0&&h().selectedIndex<0&&h().contextNode.id===n.id&&z.navigate({contextNode:n,selectedIndex:0}),r},$N=e=>`+${e.insertions} -${e.deletions}`;function ey({ticket:e,width:t,height:n}){let[r,o]=ON({state:"loading"}),s=at(e.id);Zh(()=>{let x=!0;return o({state:"loading"}),Pc({ref:s}).then(E=>{if(!x)return;let N=At();o(c(E)?{state:"failed",message:E.message}:{state:"loaded",commits:E.value,labels:c(N)?new Map:Ec(N.value)})}),()=>{x=!1}},[s]);let i=PN([]),l=r.state==="loaded"?r.commits:null,u=r.state==="loaded"?r.labels:null;Zh(()=>(Qh(i.current),i.current=l?_N(e,l):[],()=>{Qh(i.current),i.current=[]}),[e,l]);let{selectedIndex:m,contextNode:p}=Pe(),f=l?.find(x=>x.sha===p.id)??null,v=Math.max(1,n-4),I=Math.max(12,t-34);return r.state!=="loaded"?ye.createElement(Sn,{flexDirection:"column",width:t,height:n,padding:1},ye.createElement(Ze,{color:A.primary},r.state==="loading"?"Reading commits\u2026":`Could not read commits: ${r.message}`)):f?ye.createElement(Jh,{ticket:e,sha:f.sha,repo:f.repo,subject:f.subject,width:t,height:n}):r.commits.length===0?ye.createElement(Sn,{flexDirection:"column",width:t,height:n,padding:1},ye.createElement(Ze,{color:A.primary},"No commits reference this ticket."),ye.createElement(Sn,{paddingTop:1},ye.createElement(Ze,{color:A.primary},"Link one with an"),ye.createElement(Ze,{color:A.accent},` Epiq-Ref: ${s} `),ye.createElement(Ze,{color:A.primary},"line in its body,")),ye.createElement(Sn,null,ye.createElement(Ze,{color:A.primary},"or a"),ye.createElement(Ze,{color:A.accent},` ${s} `),ye.createElement(Ze,{color:A.primary},"prefix on its subject."))):ye.createElement(Sn,{flexDirection:"column",width:t,height:n},ye.createElement(Sn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:A.secondary,borderStyle:"single",paddingBottom:1},ye.createElement(Ze,{color:A.secondary2},`Diff (${r.commits.length}) \u2014 enter to read, o to open in your editor `)),ye.createElement(bt,{height:v,itemHeight:2,selectedIndex:m},r.commits.map((x,E)=>{let N=E===m,S=x.subject.length>I?x.subject.slice(0,I-1)+"\u2026":x.subject;return ye.createElement(Sn,{key:x.sha,flexDirection:"row",paddingX:1,paddingBottom:1},ye.createElement(Ze,{color:A.accent},N?"\u276F ":" "),ye.createElement(Sn,{paddingLeft:1},ye.createElement(Ze,{color:A.secondary2},`${x.sha.slice(0,7)} `),x.repo&&ye.createElement(Ze,{color:A.secondary2},`[${u?.get(x.repo)??Hr(x.repo)}] `),ye.createElement(Ze,{color:N?A.accent:A.primary},S),ye.createElement(Ze,{color:A.secondary2},` ${$N(x)} ${vn(x.time)}`)))})))}import{Box as Di,Text as BN}from"ink";import Qt from"react";var ty=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=Pe(),{title:o}=t,s=t.parentNodeId?R.getNode(t.parentNodeId):void 0,i=s&&U(s)?o===ge.ASSIGNEES?s.props.assignees??[]:o===ge.TAGS?(s.props.tags??[]).filter(l=>R.getTag(l)):[]:[];return Qt.createElement(Di,{alignItems:"center",paddingTop:1},Qt.createElement(Di,{minWidth:12},Qt.createElement(yt,{isSelected:n}),Qt.createElement(BN,{color:n?A.accent:A.secondary2},o,":")),Qt.createElement(Di,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((l,u)=>{let m=r.id===t.id&&u===e;return Qt.createElement(Di,{key:`${o}-${l}`,paddingRight:2,minHeight:1},Qt.createElement(yt,{isSelected:m}),o===ge.ASSIGNEES?Qt.createElement(kr,{isSelected:m,id:l}):o===ge.TAGS?Qt.createElement(wi,{isSelected:m,id:l}):null)})))};import{Box as Fr,Text as Gl}from"ink";import xt,{useEffect as UN,useMemo as zl,useRef as jN}from"react";var Hl=e=>Math.max(5,String(Math.max(e,1)).length+3),ny=(e,t)=>Math.max(0,e-6-Hl(t));var Wl=(e,t=0,n=0)=>Math.max(1,e-5-2*t-(n>0?1+n:0));var HN="\u2029",ry=(e,t)=>`${e}::inline-line::${t}`,Vl=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:l}=Pe(),u=zl(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=zl(()=>u.join("\0"),[u]),p=jN([]);UN(()=>(Dr(p.current),p.current=ki(e,u.length,x=>ry(e,x)),()=>{Dr(p.current),p.current=[]}),[e,m]);let f=Hl(u.length),g=ny(s,u.length),I=zl(()=>Dl(u).map(x=>{if(x.kind==="code"||x.kind==="caption")return{...x,text:Pn(x.text,g)};if(x.kind==="text"||x.kind==="heading"){let E=x.spans.map(N=>N.code?`\`${N.text}\``:N.text).join("");return{...x,spans:qo(Pn(E,g))}}return x}),[u,g]).map((x,E)=>{let N=l.id===e&&i===E;return xt.createElement(Fr,{key:ry(e,E)},xt.createElement(Fr,{flexShrink:0},xt.createElement(Gl,{color:N?A.primary:A.secondary2,dimColor:!N},`${E+1} `.padStart(f,"\xA0"))),x.kind==="blank"?xt.createElement(Gl,{backgroundColor:N?"gray":void 0},HN):xt.createElement(Fr,null,xt.createElement(Fl,{line:x,width:x.kind==="code"?g:0,wrap:"truncate-end"})))});return xt.createElement(Fr,{flexDirection:"column",paddingTop:1},xt.createElement(Fr,null,xt.createElement(yt,{isSelected:o}),xt.createElement(Gl,{color:o?A.accent:A.secondary2},t)),xt.createElement(Fr,{flexDirection:"row",borderStyle:"round",borderColor:A.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},xt.createElement(bt,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},I)))};var GN=e=>he(e,"description"),zN=e=>he(e,"comments"),VN=e=>he(e,"history"),KN=e=>he(e,"diff"),qN=e=>he(e,"attachments"),oy=({ticket:e,height:t})=>{let n=$r(()=>Ah(e),[e]),{selectedIndex:r,contextNode:o}=Pe(),s=process.stdout.columns||120,i=$r(()=>GN(e.id),[e.id]),l=$r(()=>zN(e.id),[e.id]),u=$r(()=>VN(e.id),[e.id]),m=$r(()=>KN(e.id),[e.id]),p=$r(()=>qN(e.id),[e.id]),f=R.getAttachmentsByIssue(e.id).length,g=o.id===e.id,v=o.id===l||o.parentNodeId===l,I=o.id===u||o.parentNodeId===u,x=o.id===p||o.parentNodeId===p,E=o.id===m||o.parentNodeId===m,N=le(e.id);if(v){let F=t-3;return Qe.createElement(_r,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Qe.createElement(Wh,{ticket:e,width:s,height:F}))}if(x){let F=t-3;return Qe.createElement(_r,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Qe.createElement(Ph,{ticket:e,width:s,height:F}))}if(E){let F=t-3;return Qe.createElement(_r,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Qe.createElement(ey,{ticket:e,width:s,height:F}))}if(I){let B=R.getNode(u),F=B&&Fe(B)?B.props.value??"":"",Re=Wl(t);return Qe.createElement(_r,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},B?Qe.createElement(Vl,{id:B.id,label:"Event log",text:F,selected:!1,maxWidth:s,rows:Re}):null)}let S=[u,m,l,p],T=B=>S.includes(B),k=N.reduce((B,F)=>Wr(F)?B+1:B,0),H=N.reduce((B,F)=>T(F.id)?B+1:B,0),L=N.findIndex(B=>T(B.id)),P=Wl(t,k,H),$=(B,F,Re,en)=>Qe.createElement(_r,{key:B.id,paddingTop:F===L?1:0},Qe.createElement(yt,{isSelected:Re}),Qe.createElement(WN,{backgroundColor:A.secondary,color:Re?A.accent:A.primary},en)),de=(B,F,Re)=>B.id===i?Qe.createElement(Vl,{key:B.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:F,maxWidth:s,rows:P}):Wr(B)?Qe.createElement(ty,{key:B.id,parent:B,selected:F,selectedIndex:r}):B.id===l?$(B,Re,F,` Comments (${n}) \u203A\u203A `):B.id===p?$(B,Re,F,` Attachments (${f}) \u203A\u203A `):B.id===u?$(B,Re,F," History \u203A\u203A "):B.id===m?$(B,Re,F," Diff \u203A\u203A "):null;return Qe.createElement(_r,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},N.map((B,F)=>de(B,g&&r===F,F)))};var XN=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:l})=>{let u=t.context,m=u===re.TICKET||u===re.FIELD_LIST||u===re.FIELD,p=u===re.BOARD||u===re.SWIMLANE,f=u===re.TICKET?t:r.find(E=>E.context===re.TICKET),g=Math.floor(l/3),v=Math.floor(l/Math.max(e.length,1)),I=Math.min(v,g),x=s==="dense";return Fi.createElement(YN,{flexDirection:"row",height:i},p&&e.map((E,N)=>{let S=t.id===E.id,T=S?n:-1,k=t.context===re.BOARD&&n===N;return Fi.createElement(wh,{key:E.id,height:i,width:I,swimlane:E,isSelected:k,isDense:x,isFocused:S,listSelectedIndex:T,mode:o})}),m&&f&&Fi.createElement(oy,{height:i,ticket:f}))},sy=Fi.memo(XN);import{render as QN}from"ink";import{Writable as eI}from"node:stream";var Yo=e=>String(e).padStart(2,"0"),tI=e=>{let t=e.getUTCFullYear(),n=Yo(e.getUTCMonth()+1),r=Yo(e.getUTCDate()),o=Yo(e.getUTCHours()),s=Yo(e.getUTCMinutes()),i=Yo(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},nI=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",rI=async(e,{width:t,height:n})=>{let r="",o=new eI({write(i,l,u){let m=oI(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),u()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=QN(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},oI=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),ay=async()=>{let{viewMode:e}=ne(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=h(),i=r.find(N=>N.context==="BOARD");if(!i)return a("No board found to export");let l=120,u=40,m=await rI(ZN.createElement(sy,{height:u,width:l,swimlanes:(s[i.id]??[]).filter(N=>N!==void 0&&ot(N)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:u});if(!m)return a("Failed to render board export");let p=ps(process.cwd());if(c(p))return a("Unable to export, epiq root not found");let f=new Date,g=tI(f),v=`board_${nI(i.title)}_${g}.md`,I=Du(p.value);iy.mkdirSync(I,{recursive:!0});let x=JN.join(I,v),E=`# Board - ${i.title}
100
+ Date: ${f.toISOString()}
101
+
102
+ \`\`\`text
103
+ ${m}
104
+ \`\`\`
105
+ `;return iy.writeFileSync(x,E,"utf8"),d("Exported board layout",x)};import{useSyncExternalStore as oW}from"react";var _i,sI=new Set,cy=()=>{for(let e of sI)e()};var Br=()=>{if(!_i)throw new Error("Ui state not initialized. Call initUiState() first.");return _i};var aW=(e={})=>(_i=e,cy(),d("UX state initialized",null)),iI=e=>{let t=Br();return _i=e(t),cy(),d("UX state updated",null)},Cn=e=>iI(t=>({...t,...e}));import{ulid as $i}from"ulid";var ly=async e=>{let{contextNode:t,selectedIndex:n}=h(),r=le(t.id)[n];if(e.modifier===pt.DESCRIPTION){let{breadCrumb:o,selectedNode:s}=h();return[...o,s].some(l=>l&&U(l))?cI():lI()}if(r&&zr(r))return aI(e);if(e.modifier===pt.TITLE){let o=te();if(c(o))return a("Unable to resolve user ID");let s=r;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 l=await ae();return c(l)?l:Y([{id:$i(),action:"edit.title",payload:{id:s.id,name:i},...Q(o.value)}],l.value)}return a("Unknown edit command")},aI=async e=>{let t=te();if(c(t))return a("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=h(),o=le(n.id)[r];if(!o||!zr(o))return a("Select a comment first");if(o.readonly)return a("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return a("Unable to resolve comment issue");let i=h().nodes[s];if(!i||!U(i))return a("Unable to resolve comment issue");if(i.readonly)return a("Cannot edit readonly issue");let l=o.id.split(":").at(0)??"",u=R.getComment(l);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 ae();if(c(p))return p;let f=p.value;return Y([{id:$i(),action:"edit.issue.comment",payload:{id:u.id,issue:i.id,md:m},...Q(t.value)}],f)},cI=async()=>{let e=te();if(c(e))return a("Unable to resolve user ID");let t=await ae();if(c(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=h(),s=nt([...r,o],"TICKET");if(c(s))return a("Edit target must be an issue");let i=s.value;if(!U(i))return a("Edit target must be an issue");if(i.readonly)return a("Cannot edit readonly issue");let l=le(i.id).find(f=>f.title===ge.DESCRIPTION);if(!l)return a("No target found");if(l.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=ll(u);if(c(m))return a("Failed to edit field");let p=m.value;return p===u?d("No changes made",null):Y([{id:$i(),action:"edit.description",payload:{id:i.id,md:p},...Q(e.value)}],n)},lI=async()=>{let e=te();if(c(e))return a("Unable to resolve user ID");let{selectedNode:t}=h();if(!t||!(Gr(t)||ot(t)))return a("Edit target must be an issue, swimlane or board");if(t.readonly)return a("Cannot edit readonly node");let n=t.props?.description??"",r=ll(n);if(c(r))return a("Failed to edit field");let o=ng(r.value);if(o===n)return d("No changes made",null);let s=Gr(t)?"board":"swimlane",i=rg(s==="board"?"Board description":"Swimlane description",o,tg(s));if(i)return a(i);let l=await ae();return c(l)?l:Y([{id:$i(),action:"edit.description",payload:{id:t.id,md:o},...Q(e.value)}],l.value)};import uI from"node:fs";import ql from"node:path";import Kl from"node:fs";import dI from"node:path";var dy=async e=>{let t=dI.join(e,".gitignore"),n=Kl.existsSync(t)?Kl.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
106
+ `).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 d("Local epiq paths already ignored",!1);let l=["# [epiq]: local hydrated state is never committed",...s].join(`
107
+ `);return n=n.trimEnd()+`
108
+
109
+ ${l}
110
+ `,Kl.writeFileSync(t,n,"utf8"),V.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),d("Local epiq paths ignored",!0)};var mI=async e=>{let t=await _({cwd:e,args:["status","--porcelain"]});return c(t)?t:d("Checked git diff",t.value.stdout.split(`
111
+ `).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},oe=(e,t)=>a(`[${e}] ${t}`),uy=async({cwd:e,user:t})=>{let n=vs(),r=await wt(e);if(c(r))return oe(1,r.message);let o=r.value,s=await gu(o);if(c(s))return oe(2,s.message);if(s.value)return oe(2,`Cannot initialize Epiq while a git operation is in progress: ${s.value}`);let i=await mI(o);if(c(i))return oe(2.5,i.message);if(i.value.length>0)return oe(3,`Cannot initialize Epiq with uncommitted changes (${i.value.join(", ")}). Commit or stash your changes first.`);if(to(o))return oe(4,"Epiq project already initialized");let{userId:l,userName:u}=t;if(!l||!u)return oe(5,"Missing Epiq user id");let m=await oh(o);if(c(m))return oe(6,m.message);let p=n.stateBranch,f=await hs({repoRoot:o,branch:p});if(c(f))return oe(6,f.message);if(f.value)return oe(6,`State branch already exists: ${p}`);let g=await pI({repoRoot:o,stateBranch:p});if(c(g))return oe(6,g.message);if(g.value)return fI({repoRoot:o,stateBranch:p});let v=await Nl({repoRoot:o,stateBranchName:p});if(c(v))return oe(6,v.message);let I=Jr();if(c(I))return oe(7,I.message);let x=ql.join(On(),n.projectId),E=await Tr({repoRoot:o,stateBranchRoot:x,stateBranchName:p});if(c(E))return oe(8,E.message);let N=ql.join(x,".epiq");uI.mkdirSync(N,{recursive:!0});let S=Vg({userId:l,userName:u});if(c(S))return oe(9,S.message);for(let Vb of S.value){let dd=bp({event:Vb,rootDir:x});if(c(dd))return oe(9,dd.message)}let T=xr({userId:l}),k=Us(x,T);if(c(k))return oe(9,k.message);let H=Cl(x,n);if(c(H))return oe(9,H.message);let L=await Ei({stateBranchRoot:x,eventFileName:T});if(c(L))return oe(10,L.message);let P=await fe.stage({cwd:x,pathspec:[_e]});if(c(P))return oe(10,P.message);let $=await ur({cwd:x,message:"[epiq:init]"});if(c($))return oe(10,$.message);let de=await dy(o);if(c(de))return oe(11,de.message);let B=Pa({repoRoot:o,fileContents:n});if(c(B))return oe(12,B.message);let F=await fe.stage({cwd:o,pathspec:[".epiq/project.json",".gitignore"]});if(c(F))return oe(13,F.message);let Re=await fe.commit({cwd:o,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(c(Re))return oe(13,Re.message);let en=[],cd=await _({cwd:o,args:["push","-u","origin","HEAD"]});c(cd)&&en.push(`[init:14] ${cd.message}`);let ld=await zo({repoRoot:o,stateBranchRoot:x});return c(ld)&&en.push(`[init:15] ${ld.message}`),d("Project initialized",{repoRoot:o,projectId:n.projectId,stateBranch:p,stateBranchRoot:x,defaultEvents:S.value,warnings:en})},pI=async({repoRoot:e,stateBranch:t})=>{let n=await Wt({repoRoot:e});if(c(n))return a(n.message);if(!n.value)return d("No remote",!1);let r=await Kr({repoRoot:e,branch:t});return c(r)?a(`Could not ask origin whether ${t} exists: ${r.message}`):r},fI=async({repoRoot:e,stateBranch:t})=>{let n=await _({cwd:e,args:["fetch","origin",t]});if(c(n))return oe(6,n.message);let r=await _({cwd:e,args:["show",`origin/${t}:${_e}`]});if(c(r))return oe(6,[`This repository is already an epiq project: origin has the state branch ${t}.`,"Initialising again would mint a second id for the same board.","","The branch was written before branches carried their identity, so restore",`${_e} from a checkout that has it, for example:`,"",` git show origin/main:${_e} > ${_e}`,"","and commit it; every later boot then stamps the branch, and the next clone adopts it."].join(`
112
+ `));let o;try{o=JSON.parse(r.value.stdout)}catch(I){return oe(6,`The identity on origin/${t} is not readable: ${I instanceof Error?I.message:String(I)}`)}let s=Pa({repoRoot:e,fileContents:o});if(c(s))return oe(12,s.message);let i=await fe.stage({cwd:e,pathspec:[_e]});if(c(i))return oe(13,i.message);let l=await fe.commit({cwd:e,message:"[epiq:adopt-project]",pathspec:[_e]});if(c(l))return oe(13,l.message);let u=Jr();if(c(u))return oe(7,u.message);let m=ql.join(On(),o.projectId),p=await Il({repoRoot:e,stateBranchName:t});if(c(p))return oe(8,p.message);let f=await Tr({repoRoot:e,stateBranchRoot:m,stateBranchName:t});if(c(f))return oe(8,f.message);let g=[],v=await _({cwd:e,args:["push","-u","origin","HEAD"]});return c(v)&&g.push(`[init:14] ${v.message}`),d("Adopted the project origin already holds",{repoRoot:e,projectId:o.projectId,stateBranch:o.stateBranch,stateBranchRoot:m,defaultEvents:[],warnings:g})};var Xo=(e,t)=>a(`[${e}] ${t}`),my=async()=>{X("");let e=io();if(!e.isSetupDone||!e.userName)return Xo(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let t=ne(),n=t.userName,r=t.userId;if(!r||!n)return Xo(5,"Missing Epiq user id");let o=await uy({cwd:process.cwd(),user:{userId:r,userName:n}});if(c(o))return o;let s="Project initialized!";for(let g of o.value.warnings)s+=` Warn: ${g}`;let l=un(o.value.defaultEvents).filter(c);if(l.length>0)return Xo(16,l.map(g=>g.message).join(`
113
+ `));let u=me();if(c(u))return Xo(16,u.message);let{rootNodeId:m,nodes:p}=u.value,f=p[m];return f?(z.navigate({contextNode:f,selectedIndex:0}),w({hasProjectDefinition:!0}),d(s,null)):Xo(16,"Unable to resolve initialized root node")};import{ulid as hI}from"ulid";import{ulid as gI}from"ulid";var py=null,Lt=()=>structuredClone(py),Jo=e=>{py=e},fy=()=>{let{contextNode:e,selectedIndex:t}=h(),r=be(e.id)[t];return r?d("Resolved selected child",r):a("Target node not found")},Yl=({id:e,parentId:t,position:n={at:"end"}})=>{let r=be(t).filter(o=>o.id!==e);return pi(r,n)},gy=({id:e,parentId:t,position:n={at:"end"}})=>{let r=te();if(c(r))return a("Unable to resolve user ID");let o=Yl({parentId:t,id:e,position:n});return c(o)?o:d("Created pending move state",{id:gI(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},hy=e=>{Jo(e);let t=Ro(e,!0);return c(t)?t:d("Node moved successfully",t.value)};function Xl(e){let t=fy();if(c(t))return t;let{contextNode:n,nodes:r}=h();if(!n.parentNodeId)return a("Missing parent node id");let o=r[n.parentNodeId];if(!o)return a("Missing parent node");let s=be(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return a("Current node not found among siblings");let l=s[i+e];if(!l)return a("Missing sibling node");let u=gy({id:t.value.id,parentId:l.id,position:{at:"end"}});return c(u)?u:hy(u.value)}function Zo(e,t=1){let n=fy();if(c(n))return n;let{contextNode:r,selectedIndex:o}=h(),s=be(r.id),i=Math.min(Math.max(o+e*t,0),s.length-1),l=i===o?void 0:s[i];if(!l)return a("Missing sibling node");let u=gy({id:n.value.id,parentId:r.id,position:{at:e===1?"after":"before",sibling:l.id}});return c(u)?u:hy(u.value)}var yy=()=>{let e=Lt();if(!e)return a("No pending move state");let t=e.payload.id,n=e.payload.parent,r=h().nodes[n];if(!r)return a("Move parent not found");let o=be(n).findIndex(s=>s.id===t);return o===-1?a("Moved node not found among rendered children"):(z.navigate({contextNode:r,selectedIndex:o}),d("Synchronized navigation to moved node",null))},Ur=(e,t="Moved preview")=>{if(c(e))return Lt()&&w({mode:y.MOVE}),e;let n=yy();return c(n)?n:(w({mode:y.MOVE}),d(t,null))},by=async()=>{let e=te();if(c(e))return a("Unable to resolve user ID");let{modifier:t}=q().commandMeta,{contextNode:n,selectedIndex:r}=h(),o=be(n.id)[r];if(!o)return w({mode:y.DEFAULT}),a("No move target");if(t==="start"){if(o.readonly)return a("Target node is read-only");if(r===-1)return a("No item selected");if(!o.parentNodeId)return a("Target has no parent");let s=be(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return a("Target not found among siblings");let l=s[i-1],u=s[i+1],m=u!=null?{at:"before",sibling:u.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},p=Yl({parentId:o.parentNodeId,id:o.id,position:m});return c(p)?p:(Jo({id:hI(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...Q(e.value)}),w({mode:y.MOVE}),d("Move initialized",null))}if(t==="next")return Ur(Zo(1));if(t==="previous")return Ur(Zo(-1));if(t==="jump-next")return Ur(Zo(1,Uo));if(t==="jump-previous")return Ur(Zo(-1,Uo));if(t==="to-next")return Ur(Xl(1));if(t==="to-previous")return Ur(Xl(-1));if(t==="confirm"){let s=Lt();if(!s)return a("No pending move to confirm");let i=await ae();if(c(i))return i;let l=Y([s],i.value);if(c(l))return l;let u=yy();return c(u)?u:(Jo(null),w({mode:y.DEFAULT}),d("Moved item",null))}return t==="cancel"?(Jo(null),w({mode:y.DEFAULT}),d("Cancelling move",null)):a("Invalid move modifier")};import{ulid as Bi}from"ulid";import{monotonicFactory as yI,ulid as bI}from"ulid";var vI=yI(),vy=({name:e,parent:t,rank:n,user:{userId:r}})=>{let o=vI();return d("Created issue events",[{id:bI(),userId:r,action:"add.issue",payload:{id:o,parent:t,name:e,rank:n}}])};var xy=async(e,t)=>{let n=te();if(c(n))return a("Unable to resolve user ID");let r=await ae();if(c(r))return r;let o=r.value;if(!t.inputString)return a(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:l}=h(),u=m=>{let p=Y([m],o);if(c(p))return p;let f=R.getNode(p.value[0].result.id);if(!f)return a("Created node not found");if(!f.parentNodeId)return p;let g=R.getNode(f.parentNodeId);return g?(z.navigate({contextNode:g,selectedIndex:R.getSiblings(f.parentNodeId).findIndex(({id:v})=>v===f.id)}),p):a("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=h(),p=R.getNode(m);if(!p)return a("Workspace not found");let f=gi(p.id,n.value,o);return c(f)?f:u({id:Bi(),action:"add.board",payload:{id:Bi(),name:t.inputString,parent:p.id,rank:f.value},...Q(n.value)})}if(t.modifier==="swimlane"){let m=nt(s,"BOARD");if(c(m))return a("Unable to add swimlane in this context");let p=gi(m.value.id,n.value,o);return c(p)?p:u({id:Bi(),action:"add.swimlane",payload:{id:Bi(),name:t.inputString,parent:m.value.id,rank:p.value},...Q(n.value)})}if(t.modifier==="issue"){let m=le(i.id)[l],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let S=nt(s,"SWIMLANE");return c(S)?null:S.value})();if(!p)return a("Unable to add issue in this context");let f=gi(p.id,n.value,o);if(c(f))return f;let g=vy({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(c(g))return g;let v=g.value,I=Y([...v],o);if(c(I))return I;if(!I.value[0])return a("Issue creation failed");let N=v.find(S=>S.action==="add.issue")?.payload.id;return N?(z.navigate({contextNode:p,selectedIndex:R.getSiblings(p.id).findIndex(({id:S})=>S===N)}),d("Issue created",null)):a("Unable to determine ticket id")}return d("Success",null)};import TI from"node:os";import Ay from"node:path";import Qo from"node:fs";import xI from"node:path";import{z as tr}from"zod";var es="command-history.json",RI=20,EI=tr.object({projectId:tr.string().min(1),commands:tr.array(tr.string()),lastUsedAt:tr.number().finite()}),SI=tr.object({projects:tr.array(EI)}),Ry=()=>{let e=Do();return c(e)?e:d("Resolved command history path",xI.join(e.value,es))},CI=()=>{try{let e=Ee(process.cwd());return c(e)?null:e.value}catch{return null}},Ey=e=>{if(!Qo.existsSync(e))return d("No command history recorded",{state:"read",projects:[]});let t;try{t=Qo.readFileSync(e,"utf8")}catch(o){return a(`Unable to read ${es}: ${o instanceof Error?o.message:String(o)}`)}let n;try{n=JSON.parse(t)}catch(o){return d("Unparsable command history",{state:"corrupt",reason:`Invalid ${es}: ${o instanceof Error?o.message:String(o)}`})}let r=SI.safeParse(n);return r.success?d("Read command history",{state:"read",projects:r.data.projects}):d("Command history in an unknown shape",{state:"corrupt",reason:`Invalid ${es} shape: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`})},Sy=({root:e})=>{let t=Ot(e);if(c(t))return a(t.message);let n=Ry();if(c(n))return n;let r=Ey(n.value);if(c(r))return r;let o=r.value;if(o.state==="corrupt")return a(o.reason);let s=o.projects.find(i=>i.projectId===t.value);return d("Read command history",s?.commands.slice(0,_o)??[])},Cy=({commands:e,root:t=CI(),now:n=Date.now()})=>{if(t===null)return d("No project; command history not stored",null);let r=Ot(t);if(c(r))return a(r.message);let o=Ry();if(c(o))return o;let s=o.value,i=Ey(s);if(c(i))return i;let l=i.value,u=l.state==="read"?l.projects:[],m=[{projectId:r.value,commands:e.slice(0,_o),lastUsedAt:n},...u.filter(f=>f.projectId!==r.value)].sort((f,g)=>g.lastUsedAt-f.lastUsedAt).slice(0,RI),p=`${s}.${process.pid}.tmp`;try{Qo.writeFileSync(p,JSON.stringify({projects:m},null,2)+`
114
+ `,"utf8"),Qo.renameSync(p,s)}catch(f){try{Qo.rmSync(p,{force:!0})}catch{}return a(`Unable to write ${es}: ${f instanceof Error?f.message:String(f)}`)}return d("Stored command history",null)};var NI=e=>e.some(t=>t.action==="init.workspace"),Ny=async(e,t)=>{let n=It(e);return c(n)?a(n.message):Yr({cwd:t,branch:n.value})},II=e=>{let t=Ee(process.cwd());if(c(t))return!1;let n=ve({repoRoot:t.value});return!c(n)&&n.value===e},Jl=!1,Ez=()=>Jl,Iy=async e=>{Jl=!0;try{return await wI(e)}finally{Jl=!1}},wI=async e=>{let t=ve({repoRoot:e});if(c(t))return Xn(3,t.message);let n=t.value,r=await Tr({repoRoot:e,stateBranchRoot:n,stateBranchName:vs().stateBranch});if(c(r))return Xn(3,r.message);let o=Tt(n),s=Eo(n);if(c(s))return Xn(3,s.message);if(!NI(s.value.events)){let f=await wo({worktreeRoot:n,operation:"boot pull",fn:()=>Si(n,()=>Ny(e,n))});if(c(f)?logger.info(3,f.message):f.value===null?logger.info(3,"Another process holds the state worktree, skipped pull"):c(f.value)&&logger.info(3,f.value.message),o=Tt(n),s=Eo(n),c(s))return Xn(3,s.message)}let{events:i,unreadable:l}=s.value,u=Ho(i,l);if(c(u))return Xn(4,u.message);Fs(n,o),w({hasProjectDefinition:!0,hasInitializingEvents:!!i.length});let m=Wu({root:e});c(m)&&logger.info(m.message);let p=Sy({root:e});return c(p)&&logger.info(p.message),Eg(c(p)?[]:p.value),d("Loaded project",void 0)},AI=async e=>{let t=ve({repoRoot:e});if(c(t))return a(t.message);let n=t.value,r=await Wt({repoRoot:n});if(c(r))return a(r.message);if(!r.value)return d("No remote to pull",void 0);let o=await wo({worktreeRoot:n,operation:"boot pull",fn:()=>Si(n,()=>(vi("Pulling"),Ny(e,n)))});if(c(o))return Te(o.message);if(o.value===null)return d("Another process holds the state worktree",void 0);let s=o.value;if(c(s))return qr(s.message)?(xi("Offline"),d("Offline",void 0)):Te(s.message);if(!s.value)return Wo("Already synced"),d("Already synced",void 0);if(!II(n))return d("Project changed during the pull",void 0);let i=Al(n);return c(i)?i:(Wo("Pulled"),d("Pulled and reloaded",void 0))},wy=e=>{AI(e).then(t=>{c(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${qg(t)}`)})},Sz=()=>{let e=Ho([]);return c(e)?Xn(4,e.message):(w({hasProjectDefinition:!1,hasInitializingEvents:!1}),d("Booted without a project",void 0))};var MI=e=>e==="~"||e.startsWith("~/")?Ay.join(TI.homedir(),e.slice(1)):e,kI=(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 o=t[Number(n)-1];return o?d("Resolved recent project",o.root):a(`No recent project #${n}`)}let r=Ee(Ay.resolve(MI(n)));return c(r)?a(`No epiq project at ${n}`):d("Resolved project path",r.value)},Ty=async()=>{let e=mi();if(X(""),h().hasProjectDefinition)return a("Already in a project; run epiq from another directory");let t=Rs({exclude:process.cwd()}),n=c(t)?[]:t.value,r=kI(e,n);if(c(r))return a(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(l){return a(`Unable to enter ${o}: ${l instanceof Error?l.message:String(l)}`)}let i=await Iy(o);return c(i)?(process.chdir(s),a(i.message)):(wy(o),d(`Opened ${Bu(o)}`,null))};var Ui=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=h(),s=hp(n,t);if(c(s))return a(s.message);let{appliedEvents:i,unappliedEvents:l}=s.value,u=Nn();if(c(u))return u;let m=un(i),{fatal:p,skipped:f}=Gn(m);if(p.length>0)return Nn(),w(o),a(p.map(v=>v.message).join(", "));zn(f);let g=h().nodes[e];return g?(z.navigate({contextNode:g,selectedIndex:r}),d("",{unappliedEvents:l})):(Nn(),w(o),a("Board did not exist at that date"))};var My=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 LI=20,PI=16,OI=150,ji=null,Hi=null;var nr=()=>{ji!==null&&(clearInterval(ji),ji=null),Hi!==null&&(clearTimeout(Hi),Hi=null)},ky=()=>{nr(),w({mode:y.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Ly=({events:e,startTime:t,durationMs:n})=>{nr();let r=e.length,o=ss(e.map(f=>is(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=My(o),l=Math.max(1,Math.round(n*LI/1e3)),u=Math.max(Math.round(n/l),PI),m=0,p=0;w({mode:y.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),ji=setInterval(()=>{m++;let f=m/l,g=[],v,I;for(;p<r&&i[p]<=f;){let E=e[p],N=Ro(E);if(c(N)){if(vr(N)){p++;continue}ky();return}g.push(...yc(E)),v=E,I=o[p],p++}if(p>=r||m>=l){for(;p<r;p++){let N=Ro(e[p]);if(c(N)&&!vr(N))break}let E=h().replay;w({unappliedEvents:[],replay:E&&{...E,progress:1,appliedCount:r}}),nr(),Hi=setTimeout(ky,OI);return}let x=h().replay;w({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:v?I??x?.currentTime??t:x?.currentTime??t,currentLabel:v?Py(v):x?.currentLabel??"",flashNodeIds:v?[...new Set(g)]:x?.flashNodeIds??[]}})},u)};var Oy=async()=>{let e=nt(h().breadCrumb,"BOARD");if(c(e))return e;let t=await wt(process.cwd());if(c(t))return a("Unable to locate repo root");let n=ve({repoRoot:t.value});if(c(n))return n;let{modifier:r,inputString:o}=q().commandMeta;if(nr(),r==="now"){let l=Vs(n.value);if(c(l))return a(l.message);let u=Nn();if(c(u))return u;let m=un(l.value),{fatal:p,skipped:f}=Gn(m);return p.length>0?a(p.map(g=>g.message).join(", ")):(zn(f),w({mode:y.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),d("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let l=yp(n.value);if(c(l))return l;let u=r==="prev"?h().eventLog.at(-1):h().unappliedEvents.at(0),m=u===void 0?null:is(u),p=(u===void 0?null:l.value.get(u.id)??null)??(m===null?null:na(m));if(p===null)return a(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?p:p+1}else{let l=Fn(r||o.trim());if(!l)return a("Invalid peek date");s=l.getTime()}let i=Ui({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return c(i)?i:(w({mode:y.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),d("Peeking",!0))};var Dy=async()=>{let e=nt(h().breadCrumb,"BOARD");if(c(e))return e;let t=await wt(process.cwd());if(c(t))return a("Unable to locate repo root");let n=ve({repoRoot:t.value});if(c(n))return n;let{modifier:r,inputString:o}=q().commandMeta,{dateInput:s,durationInput:i}=Ls(r,o);if(nr(),h().syncStatus.status==="syncing")return a("Cannot replay while syncing, try again in a moment");let l=Fn(s);if(!l)return a("Invalid replay date");let u=i?ks(i):15e3;if(u===null)return a("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=h(),f=Ui({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(c(f))return f;let{unappliedEvents:g}=f.value;return g.length===0?(Nn(),w(p),d("Nothing to replay from that point",!0)):(Ly({events:g,startTime:m,durationMs:u}),d("Replaying board history",!0))};import{spawn as FI}from"node:child_process";var _I=()=>{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"]}}},Fy=async e=>new Promise(t=>{let{command:n,args:r}=_I();try{let o=FI(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(a(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?d("Copied to clipboard",null):a(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(a(`Clipboard tool not available (${n})`))}});var ts=async(e,t)=>{if(!e.trim())return a(`Nothing to copy: ${t} is empty`);let n=await Fy(e);return c(n)?n:d(`Copied ${t} to clipboard`,null)},_y=async e=>{let{breadCrumb:t,selectedNode:n}=h(),r=co({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return a("Nothing selected to copy from");switch(e.modifier){case Me.REF:return ts(at(o.id),"ref");case Me.TITLE:return ts(o.title,"title");case Me.DESCRIPTION:return r?ts(r.props?.description??"","description"):a("No issue in scope");case Me.TAGS:{if(!r)return a("No issue in scope");let s=on(r).map(({name:i})=>i);return ts(s.join(", "),"tags")}case Me.ASSIGNEES:{if(!r)return a("No issue in scope");let s=sn(r).map(({name:i})=>i);return ts(s.join(", "),"assignees")}default:return a("Yank one of: ref, title, description, tags, assignees")}};var $y=async()=>{X(""),w({mode:y.DEFAULT});let e=me();if(c(e))return a(e.message);if(e.value.syncStatus.status==="syncing")return a("Sync already in progress");w({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Ci();return c(t)?(w({syncStatus:{msg:t.message,status:"failed"}}),t):(w({mode:y.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{ulid as By}from"ulid";var Uy=async()=>{let e=te();if(c(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=le(t.id)[n];if(!r)return a("Unable to resolve child to delete");let o=await ae();if(c(o))return o;if(r.context==="COMMENT"){let s=r.id,i=U(t)?t.id:t.parentNodeId;if(!i)return a("Unable to resolve comment issue");let l=h().nodes[i];if(!l||!U(l))return a("Unable to resolve comment issue");let u=l.log?.filter(Mh).find(m=>m.payload.id===s);return u?u.payload.author!==e.value.userId?a("You can only delete your own comments"):Y([{id:By(),action:"delete.issue.comment",payload:{id:s,issue:i},...Q(e.value)}],o.value):a("Unable to resolve comment")}return Y([{id:By(),action:"delete.node",payload:{id:r.id},...Q(e.value)}],o.value)};import{ulid as $I}from"ulid";var jy=async()=>{let e=te();if(c(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=le(t.id)[n];if(!r)return a("Unable to close issue, no target found");if(!U(r))return a("Cannot close in this context");let o=h().nodes[We];if(!o)return a("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return a("Issue is already closed");let s=await ae();if(c(s))return s;let i=s.value,l=fi(o.id,r.id,{at:"end"},e.value,i);if(c(l))return l;let u=Y([{id:$I(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...Q(e.value)}],i);return c(u)?u:d("Issue closed",null)};import{ulid as BI}from"ulid";var Hy=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};var Wy=async()=>{let e=te();if(c(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=le(t.id)[n];if(!r)return a("Unable to reopen issue, no target found");let o=r.context==="TICKET"?d("Resolved ticket",r):et(r.id,"TICKET");if(c(o))return a("Cannot reopen in this context");let s=o.value,i=h().nodes[We];if(!i)return a("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return a("Issue is not closed");if(!U(s))return a("Target node is not issue");let l=Hy(s);if(!l)return a("Unable to resolve previous parent from issue history");if(l===i.id)return a("Previous parent resolves to closed swimlane");let u=h().nodes[l];if(!u)return a("Previous parent no longer exists");let m=await ae();if(c(m))return m;let p=m.value,f=fi(u.id,s.id,{at:"end"},e.value,p);if(c(f))return f;let g=Y([{id:BI(),action:"reopen.issue",payload:{id:s.id,parent:u.id,rank:f.value},...Q(e.value)}],p);return c(g)?g:d("Issue reopened",null)};import{ulid as UI}from"ulid";var Gy=async()=>{let e=te();if(c(e))return a("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=le(t.id)[n];if(!r)return a("Missing node");if(r.readonly)return a("Cannot rename readonly node");let o=mi();if(!o)return a("Provide a title");let s=await ae();return c(s)?s:Y([{id:UI(),action:"edit.title",payload:{id:r.id,name:o},...Q(e.value)}],s.value)};import{ulid as jI}from"ulid";var zy=async()=>{let e=te();if(c(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let o=R.findTagByName(r);if(!o)return a(`Tag "${r}" does not exist`);let{selectedNode:s}=h();if(!s)return a("Invalid untag target");let i=et(s.id,"TICKET");if(c(i))return a("Unable to untag issue in this context");let l=i.value;if(!U(l))return a("Target node is not issue");if(!(l.props.tags??[]).includes(o.id))return a("Issue is not tagged with that tag");let m=await ae();return c(m)?m:Y([{id:jI(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...Q(e.value)}],m.value)};import{ulid as Zl}from"ulid";var Vy=async()=>{let e=te();if(c(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide a tag");let{selectedNode:o}=h();if(!o)return a("Invalid tag target");let s=et(o.id,"TICKET");if(c(s))return a("Unable to tag issue in this context");let i=s.value;if(!U(i))return a("Target node is not issue");let l=await ae();if(c(l))return l;let u=R.findTagByName(r),m=u?.id??Zl();return(i.props.tags??[]).includes(m)?a("Already tagged with that tag"):Y([...u?[]:[{id:Zl(),action:"create.tag",payload:{id:m,name:r},...Q(e.value)}],{id:Zl(),action:"add.issue.tag",payload:{id:i.id,tag:m},...Q(e.value)}],l.value)};import{ulid as Ky}from"ulid";var qy=()=>{let{selectedNode:e}=h();if(!e)return a("Select an issue first");let t=et(e.id,"TICKET");if(c(t))return a("Not inside an issue");let n=t.value;return U(n)?d("Found issue",n):a("Target node is not issue")},Ql=async e=>{let t=await ae();return c(t)?t:Y(e,t.value)},ed=(e,t,n)=>sm(t,n).map(r=>({id:Ky(),...r,...Q(e)})),Yy=async()=>{let{modifier:e,inputString:t}=q().commandMeta,n=Ts(e||t);if(!n)return a("Name the goal");let r=qy();if(c(r))return r;let o=r.value,s=te();if(c(s))return a("Unable to resolve user ID");let i=s.value,l=Ua(n);if(l){let p=ed(i,o,l.id);return p.length===0?a("Already in that goal"):Ql(p)}let u=am(n);if(u)return a(u);let m=Ky();return Ql([{id:m,action:"create.goal",payload:{id:m,name:n},...Q(i)},...ed(i,o,m)])},Xy=async()=>{let e=qy();if(c(e))return e;let t=e.value;if(!an(t))return a("Not in a goal");let n=te();return c(n)?a("Unable to resolve user ID"):Ql(ed(n.value,t))};import{ulid as HI}from"ulid";var Jy=async e=>{let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim().toLowerCase(),o=zt();if(!o)return a("Select a swimlane first");let s=Qu(o,r,e);if(c(s)||!s.value)return s;let i=te();if(c(i))return a("Unable to resolve user ID");let l=await ae();if(c(l))return l;let u=Y([{id:HI(),...s.value,...Q(i.value)}],l.value);return c(u)?u:d("Saved",null)},Zy=()=>Jy(!0),Qy=()=>Jy(!1);import{ulid as td}from"ulid";var eb=({events:e,registry:t,logFileNames:n})=>{let r=new Map(n),o=new Set;for(let s of e)s.userId&&(r.has(s.userId)||r.set(s.userId,""),o.add(s.userId));for(let s of Object.values(t))r.set(s.id,s.name);return[...r.entries()].map(([s,i])=>({id:s,name:i,isExternal:!o.has(s)}))},SK=({authorName:e,authorEmail:t,owners:n,registry:r})=>{let o=rt(t),s=n.get(o),i=s?r[s]:void 0;return s?{...la(s,i?.name),resolved:!0}:{...la(o||e,e),resolved:!1}};var Wi=e=>{let{eventLog:t=[],contributors:n}=h();return eb({events:t,registry:n,logFileNames:gp(e)})};var tb=async()=>{let e=te();if(c(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return a("Provide an assignee");let{selectedIndex:i,contextNode:l}=h(),u=le(l.id)[i];if(!u)return a("Invalid assign target");let m=et(u.id,"TICKET");if(c(m))return a("Unable to assign issue in this context");let p=m.value;if(!U(p))return a("Target node is not issue");let f=await ae();if(c(f))return f;let g=Wi(f.value),v=!o&&s.toLowerCase()==="me",I,x;if(v)I=e.value.userId,x=g.find(S=>S.id===I)?.name??e.value.userName;else{let S=g.filter(k=>k.name===s);if(S.length>1)return a(`"${s}" matches ${S.length} contributors (${S.map(k=>k.id).join(", ")}). Assign from the GUI to choose by id.`);let T=S[0];if(!T&&!o)return a(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);I=T?.id??td(),x=T?.name??s}if((p.props.assignees??[]).includes(I))return a("Assignee already assigned");let N=!!h().contributors[I];return Y([...N?[]:[{id:td(),action:"create.contributor",payload:{id:I,name:x},...Q(e.value)}],{id:td(),action:"add.issue.assignee",payload:{id:p.id,assignee:I},...Q(e.value)}],f.value)};import{ulid as WI}from"ulid";var nb=async()=>{let e=te();if(c(e))return a("Unable to resolve user ID");let{modifier:t,inputString:n}=q().commandMeta,r=(t||n).trim();if(!r)return a("Provide an assignee to remove");let{selectedNode:o}=h();if(!o)return a("Invalid unassign target");let s=et(o.id,"TICKET");if(c(s))return a("Unable to unassign in this context");let i=s.value;if(!U(i))return a("Target node is not issue");let l=i.props.assignees??[],u=r.toLowerCase()==="me",m=await ae();if(c(m))return m;let p=u?l.filter(g=>g===e.value.userId):Wi(m.value).filter(g=>g.name===r&&l.includes(g.id)).map(g=>g.id);if(p.length>1)return a(`"${r}" matches ${p.length} assignees (${p.join(", ")}). Unassign from the GUI to choose by id.`);let f=p[0];return f?Y([{id:WI(),action:"remove.issue.assignee",payload:{id:i.id,assignee:f},...Q(e.value)}],m.value):a(u?"Issue is not assigned to you":`Issue is not assigned to "${r}"`)};import{ulid as rb}from"ulid";var GI=e=>{let t=e.trim(),n=En(),r=n?jf(t):null;if(!n||!r)return{ok:!0,md:t,anchored:!1};let o=Oi();if(!o||o.sha!==n)return{ok:!1,reason:"No diff is open"};let s=Hf(o.rows,Math.max(0,h().selectedIndex));if(!s)return{ok:!1,reason:"That line is not in a file"};let i=Wf(o.rows,s,r.start,r.end);return i.ok?{ok:!0,anchored:!0,md:$f({filePath:i.value.filePath,start:i.value.start,end:i.value.end,side:"additions",endSide:"additions",note:r.note,sha:n,snippet:i.value.snippet})}:{ok:!1,reason:i.reason}},ob=async e=>{let t=GI(e.inputString);if(!t.ok)return a(t.reason);let{md:n,anchored:r}=t;if(!n)return a("Provide a comment");if(n.length>4e3)return a(r?`The note and the ${n.length} characters of quoted lines exceed ${4e3}; comment on fewer lines`:`Cannot exceed ${4e3} characters`);let o=te();if(c(o))return a("Unable to resolve user ID");let{breadCrumb:s,selectedNode:i}=h(),l=nt([...s,i],"TICKET");if(c(l))return a("Edit target must be an issue");let u=l.value;if(!u)return a("Invalid comment target");let m=u.context==="TICKET"?d("Resolved ticket",u):et(u.id,"TICKET");if(c(m))return a("Unable to comment on issue in this context");let p=m.value;if(!U(p))return a("Target node is not issue");let f=await ae();if(c(f))return f;let g=await Y([{id:rb(),action:"add.issue.comment",payload:{id:rb(),issue:p.id,author:o.value.userId,md:n},...Q(o.value)}],f.value);return r&&!c(g)&&er(null),g};import{ulid as JI}from"ulid";var sb=e=>e.userName?.trim()?e.preferredEditor?.trim()?null:"no editor configured":"no username configured",zI=e=>{let t=Em();return c(t)?sb({userName:e.userName,preferredEditor:e.preferredEditor})??t.message:sb(t.value)},ib=()=>{let e=Ft();return c(e)?a(e.message):d("Read auto sync settings",{enabled:e.value.autoSync===!0,intervalMs:ms(e.value.autoSyncDebounceMs),blockedReason:zI(e.value)})},Gi=e=>{let t=e.intervalMs===void 0?void 0:lr(e.intervalMs);if(e.intervalMs!==void 0&&t===null)return a(`Auto sync interval must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=ib();if(c(n))return n;let r=Xe({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncDebounceMs:t}});if(c(r))return a(r.message);mt({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncIntervalMs:t}});let o=ib();return c(o)?d("Changed auto sync settings",{...n.value,...e.enabled===void 0?{}:{enabled:e.enabled},...t==null?{}:{intervalMs:t}}):o};var ab=()=>{let e=q().commandMeta.inputString,t=lr(e);if(t===null)return a(`Auto sync duration must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=Gi({intervalMs:t});return c(n)?n:d(`Auto sync interval set to ${t}ms`,null)};import VI from"zod";var cb=()=>{let e=VI.coerce.number().int().min(hr).max(yr).safeParse(q().commandMeta.inputString);if(!e.success)return a(`A connected repo's clone cap must be ${hr}-${yr} MB (default ${Za})`);let t=Xe({repoCloneMaxMb:e.data});return c(t)?t:d(`Connected repo clone cap set to ${e.data} MB`,null)};var lb=()=>{let e=q().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return a("Invalid response");let t=Ju(e),n=Gi({enabled:t===!0});return c(n)?n:d(`Auto sync set to "${e}"`,null)};import{ulid as YI}from"ulid";var nd=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=2),db="",ub=new Map,KI=15e3;var qI=async(e,t)=>{let n=`${e} ${t??""}`,r=ub.get(n);if(r&&Date.now()-r.at<ei(KI))return d("Cached author scan",r.authors);let o=await Ie({cwd:e,args:["log","--branches",...t?["--not",t]:[],`--format=%an${db}%ae`]});if(o.exitCode!==0)return a(`Could not read this repository's history: ${(o.stderr??"").trim()||`git exited ${o.exitCode}`}`);let s=new Map;for(let i of(o.stdout??"").split(`
115
+ `)){let l=i.lastIndexOf(db);if(l===-1)continue;let u=i.slice(0,l),m=rt(i.slice(l+1));if(!ar(m))continue;let p=s.get(m)??{names:new Set,commits:0};u&&p.names.add(u),p.commits+=1,s.set(m,p)}return ub.set(n,{at:Date.now(),authors:s}),d("Scanned repository authors",s)},mb=async({repoRoot:e,stateBranch:t,names:n,links:r})=>{let o=await qI(e,t);if(c(o))return a(o.message);let s=o.value,i=new Map;for(let u of Object.values(r)){if(u.tombstoned)continue;let m=i.get(u.email)??new Set;m.add(u.contributor),i.set(u.email,m)}let l=new Set(n.flatMap(u=>nd(u??"")));return d("Found candidates",[...s.entries()].map(([u,m])=>({email:u,names:[...m.names],commits:m.commits,looksLikeYours:[...m.names].some(p=>nd(p).some(f=>l.has(f)))||nd(u.split("@")[0]??"").some(p=>l.has(p)),claimedBy:[...i.get(u)??[]]})).sort((u,m)=>u.looksLikeYours===m.looksLikeYours?m.commits-u.commits:Number(m.looksLikeYours)-Number(u.looksLikeYours)))},pb=e=>e.filter(t=>t.claimedBy.length===0);var fb=()=>{let e=Fa();if(!e)return d("Nothing here to decline",null);let t=Ft(),n=c(t)?[]:t.value.declinedEmailBoards??[],r=[...new Set([...n,e])],o=Xe({declinedEmailBoards:r});return c(o)?a(o.message):(mt({declinedEmailBoards:[...new Set([...ne().declinedEmailBoards??[],e])]}),d("Declined",null))},gb=async()=>{let e=q().commandMeta.inputString.trim();if(e==="none"){let E=fb();return c(E)?E:d("Left unlinked. Your commits will show the name git signed them with. Run :config emails again to change that.",null)}let{userId:t,userName:n,gitName:r}=ne();if(!t)return a("Set a username first with :config username");let o=me();if(c(o))return a("Board is not loaded");let s=Ee(process.cwd());if(c(s))return a(s.message);let i=It(s.value),l=await mb({repoRoot:s.value,stateBranch:c(i)?void 0:i.value,names:[n,r],links:o.value.emailLinks});if(c(l))return l;let m=pb(l.value);if(Ku(m.map(E=>E.email)),m.length===0){if(!Yu()){let E=fb();if(c(E))return E}return d("No unclaimed addresses in this history.",null)}if(!e)return w({mode:y.IDENTITY}),d("Opened identity",null);let p=e.split(/[,\s]+/).filter(Boolean),f=[],g=[];for(let E of p){let N=m.find(S=>S.email===rt(E));if(!N){g.push(E);continue}f.includes(N)||f.push(N)}if(g.length>0)return a(`Not on the list: ${g.join(", ")}. Pick one of ${m.map(E=>E.email).join(", ")}.`);let v=ve({repoRoot:s.value});if(c(v))return v;let I=f.map(E=>({id:YI(),action:"link.contributor.email",payload:{contributor:t,email:E.email},userId:t})),x=Y(I,v.value);return c(x)?a(x.message):d(`Claimed ${f.map(E=>E.email).join(", ")}. Every commit by ${f.length===1?"that address":"those addresses"} is now yours.`,null)};import{ulid as XI}from"ulid";var hb=()=>{let e=q().commandMeta.inputString.trim(),{userId:t}=ne();if(!t)return a("Set a username first with :config username");let n=me();if(c(n))return a("Board is not loaded");let r=cr(n.value.emailLinks,t);if(r.length===0)return a("You have not claimed any addresses.");if(!e)return a(`Which one? ${r.join(", ")}.`);let o=r.find(u=>u===rt(e));if(!o)return a(`You have not claimed ${e}. Yours: ${r.join(", ")}.`);let s=Ee(process.cwd());if(c(s))return s;let i=ve({repoRoot:s.value});if(c(i))return i;let l=Y([{id:XI(),action:"unlink.contributor.email",payload:{contributor:t,email:o},userId:t}],i.value);return c(l)?a(l.message):d(`Unclaimed ${o}`,null)};var yb=()=>{let e=q().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return a("Invalid response");let n=Xe({logLevel:e});return c(n)?n:(mt({logLevel:e}),d(`Auto sync set to "${e}"`,null))};var bb=e=>{let t=e.inputString.trim();switch(e.modifier){case ee.USERNAME:{if(process.env[Yi])return a(`Cannot change the configured user while ${Yi} names this process`);let n=Ft();if(c(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,l=r||JI();if(!i||!l)return a("Unable to resolve user name or id");let u=Xe({userName:i,userId:l,preferredEditor:o??""});return c(u)?u:(mt({userName:i,userId:l}),d(`Username set to "${i}"`,null))}case ee.EDITOR:{if(!t)return a("No editor provided");let n=Xe({preferredEditor:t});return c(n)?n:(mt({preferredEditor:t}),d(`Editor configuration set to "${t}"`,null))}case ee.VIEW:{if(t!=="wide"&&t!=="dense")return a("Invalid view mode");let n=Xe({viewMode:t});return c(n)?n:(mt({viewMode:t}),d(`View set to "${t}"`,null))}case ee.EMAILS:return gb();case ee.EMAILS_UNCLAIM:return hb();case ee.AUTOSYNC:return lb();case ee.LOG_LEVEL:return yb();case ee.SYNC_DEBOUNCE_MS:return ab();case ee.ATTACHMENT_MAX_KB:return Am();case ee.REPO_CLONE_MAX_MB:return cb();case ee.REPO_CONNECT:return Qf();case ee.REPO_DISCONNECT:return eg();default:return a("Unknown config command")}};var rd=()=>{let e=Zu(),t=h().mode;if(!(t!==y.COMMAND_LINE&&t!==y.DEFAULT)){if(!e){w({mode:y.DEFAULT});return}w({mode:y.COMMAND_LINE}),X(e)}};var vb=[{systemOnly:!0,intent:j.Move,description:"Internal move-state command",mode:y.COMMAND_LINE,action:by},{intent:j.Delete,description:"Delete the currently selected node",mode:y.COMMAND_LINE,action:Uy,onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:y.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=q().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>ke(b.FILTER).map(l=>l.split(n)[0]).includes(i))(r))return a("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return pe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:y.DEFAULT})),d("Filter updated",null)}},{intent:j.ViewHelp,description:"Open the help screen",mode:y.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=h();return Cn({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),w({mode:y.HELP}),d("Viewing help",null)}},{intent:j.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:y.COMMAND_LINE,action:jy,onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:y.COMMAND_LINE,action:Wy,onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.Init,description:"Initialize Epiq in the current git repository",mode:y.COMMAND_LINE,action:my,onSuccess:rd},{intent:j.OpenProject,description:"Open a recently used epiq project, by number or path",mode:y.COMMAND_LINE,action:Ty,onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.NewItem,description:"Create a new board, swimlane, or issue",mode:y.COMMAND_LINE,action:xy,onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.Rename,description:"Rename the currently selected node",mode:y.COMMAND_LINE,action:Gy,onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.UntagTicket,description:"Remove a tag from the selected issue",mode:y.COMMAND_LINE,action:zy,onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.TagTicket,description:"Add or create a tag on the selected issue",mode:y.COMMAND_LINE,action:Vy,onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.GoalTicket,description:"Put the selected issue in a goal, or name a new one",mode:y.COMMAND_LINE,action:Yy,onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.UngoalTicket,description:"Take the selected issue out of its goal",mode:y.COMMAND_LINE,action:Xy,onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.RuleLane,description:"Give the selected swimlane a rule: done marks its tickets done",mode:y.COMMAND_LINE,action:Zy,onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.UnruleLane,description:"Take a rule off the selected swimlane",mode:y.COMMAND_LINE,action:Qy,onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.AssignUserToTicket,description:"Assign a user to the selected issue",mode:y.COMMAND_LINE,action:tb,onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:y.COMMAND_LINE,action:nb,onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.Comment,description:"Add a comment to the selected issue",mode:y.COMMAND_LINE,action:async(e,t)=>ob(t),onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.Sync,description:"Pull, commit, and push Epiq state",mode:y.COMMAND_LINE,action:$y},{intent:j.Peek,description:"View board state at another point in time",mode:y.COMMAND_LINE,action:Oy},{intent:j.Replay,description:"Replay board history forward from a point in time",mode:y.COMMAND_LINE,action:Dy},{intent:j.Export,description:"Export the current board layout to markdown",mode:y.COMMAND_LINE,action:async()=>{let e=await ay();return c(e)?e:(w({mode:y.DEFAULT}),d("Export successful",!0))}},{intent:j.Exit,description:"Exit the application",mode:y.COMMAND_LINE,action:async()=>(z.exit(),d("Exit successful",!0))},{intent:j.Edit,description:"Edit title or description",mode:y.COMMAND_LINE,action:async(e,t)=>ly(t),onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:y.COMMAND_LINE,action:async(e,t)=>_y(t),onSuccess:()=>w({mode:y.DEFAULT})},{intent:j.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:y.COMMAND_LINE,action:(e,t)=>bb(t),onSuccess:rd}];var ZI=e=>{let t=e.value;return t&&typeof t=="object"&&typeof t.followUp=="string"?t.followUp:null},QI=new Set(["peek","replay","filter","view-help","yank"]),Rt=async({isForceExecutedBySystem:e=!1}={})=>{let{value:t,commandMeta:{command:n,validity:r,modifier:o,inputString:s}}=q();if(!n)return a("No command to confirm");if(!e&&r===gn.Invalid)return a("Invalid command");let i=hh(n);xg();let{readOnly:l}=h();if(l&&!QI.has(i))return $o({status:sr.Fail,message:"Command not available in readonly state",value:null});let u=vb.filter(g=>e||g.systemOnly!==!0).find(g=>g.intent===i);if(!u)return $o({status:sr.Fail,message:"Command not found",value:null});let m;try{m=await u.action(u,{command:n,inputString:s,modifier:o})}catch(g){return $o({status:sr.Fail,message:g instanceof Error?g.message:"Command failed",value:null})}if(c(m))return $o(m);let p=!e;if(Rg({addToHistory:p,line:t}),p){let g=Cy({commands:q().commandHistory});c(g)&&logger.info(g.message)}let f=ZI(m);return f!==null?(X(f),m):(u.onSuccess?.(),ne().autoSync&&gh(),m)};var zi=[{intent:C.Exit,mode:y.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(w({mode:y.COMMAND_LINE}),X("move cancel"),Rt({isForceExecutedBySystem:!0}))},{intent:C.InitMove,mode:y.DEFAULT,description:"[m] move",action:()=>(w({mode:y.COMMAND_LINE}),X("move start"),Rt({isForceExecutedBySystem:!0}))},{intent:C.ConfirmMove,mode:y.MOVE,description:"[m] confirm move",action:()=>(w({mode:y.COMMAND_LINE}),X("move confirm"),Rt({isForceExecutedBySystem:!0}))}],Vi=[{intent:C.MovePreviousItem,mode:y.MOVE,action:()=>Lt()?(w({mode:y.COMMAND_LINE}),X("move previous"),Rt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:C.MoveNextItem,mode:y.MOVE,description:"[arrows/hjkl] move (shift x5)",action:()=>Lt()?(w({mode:y.COMMAND_LINE}),X("move next"),Rt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:C.MovePreviousItemJump,mode:y.MOVE,action:()=>Lt()?(w({mode:y.COMMAND_LINE}),X("move jump-previous"),Rt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:C.MoveNextItemJump,mode:y.MOVE,action:()=>Lt()?(w({mode:y.COMMAND_LINE}),X("move jump-next"),Rt({isForceExecutedBySystem:!0})):a("No pending move")}],xb=[{intent:C.MoveToNextContainer,mode:y.MOVE,action:()=>Lt()?(w({mode:y.COMMAND_LINE}),X("move to-next"),Rt({isForceExecutedBySystem:!0})):a("No pending move")},{intent:C.MoveToPreviousContainer,mode:y.MOVE,action:()=>Lt()?(w({mode:y.COMMAND_LINE}),X("move to-previous"),Rt({isForceExecutedBySystem:!0})):a("No pending move")}];var Rb={[re.WORKSPACE]:[...zi,...Vi],[re.BOARD]:[...zi,...Vi],[re.SWIMLANE]:[...zi,...Vi,...xb],[re.TICKET]:[],[re.FIELD]:[],[re.FIELD_LIST]:[],[re.TEXT]:[],[re.COMMENT]:[]};import tw from"node:fs";import nw from"node:path";import{spawn as ew}from"node:child_process";function Eb(e){let t=process.platform,o=ew(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 Sb=e=>{let t=Ee(process.cwd());if(c(t))return a("Unable to resolve project root");let n=ve({repoRoot:t.value});if(c(n))return a(n.message);let r=Ja(e.hash,e.ext),o=nw.join(eo(n.value),r);return tw.existsSync(o)?(Eb(o),d(`Opened ${e.name}`,null)):a("Attachment file not found \u2014 run :sync to fetch it")};var Cb=()=>{X("");let{pendingNavTarget:e}=Br();w({mode:y.DEFAULT}),e&&z.navigate(e),Cn({pendingNavTarget:void 0})},Nb=[{intent:C.ExitCommandLine,mode:y.HELP,action:()=>(Cb(),d("Exiting help",null))},{intent:C.Exit,mode:y.HELP,action:()=>(Cb(),d("Closed help",null))},{intent:C.NavPreviousItem,mode:y.HELP,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(z.navigateToPreviousItem(),d("Navigating to previous help item",null))},{intent:C.NavNextItem,mode:y.HELP,action:()=>(z.navigateToNextItem(),d("Navigating to next help item",null))},{intent:C.NavPreviousItemJump,mode:y.HELP,action:()=>(z.jumpToPreviousItem(),d("Jumping to previous help item",null))},{intent:C.NavNextItemJump,mode:y.HELP,action:()=>(z.jumpToNextItem(),d("Jumping to next help item",null))},{intent:C.NavToPreviousContainer,mode:y.HELP,action:()=>(z.navigateToPreviousContainer(),d("Navigating to previous help container",null))},{intent:C.NavToNextContainer,mode:y.HELP,action:()=>(z.navigateToNextContainer(),d("Navigating to next help container",null))}];var Ib=()=>{X(""),w({mode:y.DEFAULT})},wb=[{intent:C.Confirm,mode:y.IDENTITY,description:"[enter] claim the first",action:()=>{let[e]=fr();return e?(w({mode:y.COMMAND_LINE}),X(`config emails ${e}`),d("Proposed claim",null)):d("Nothing left to claim",null)}},{intent:C.ExitCommandLine,mode:y.IDENTITY,action:()=>(Ib(),d("Closed identity",null))},{intent:C.Exit,mode:y.IDENTITY,description:"[esc] close",action:()=>(Ib(),d("Closed identity",null))}];var rw=e=>{w({mode:y.COMMAND_LINE});let{pendingNavTarget:t}=Br();t&&z.navigate(t),Cn({pendingNavTarget:void 0}),X(`${e} `)},Ab=()=>{X("");let{pendingNavTarget:e}=Br();e&&z.navigate(e),Cn({pendingNavTarget:void 0}),w({mode:y.DEFAULT})},Tb=[{intent:C.InitCommandPalette,mode:y.DEFAULT,description:"[?] command palette",action:()=>{X("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=h();return Cn({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),w({mode:y.PALETTE}),d("Opening command palette",null)}},{intent:C.Confirm,mode:y.PALETTE,action:()=>{let{selectedNode:e}=h();if(!e||!Od(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?(rw(t),d("Selected command",t)):d("No command selected",null)}},{intent:C.ExitCommandLine,mode:y.PALETTE,action:()=>(Ab(),d("Exiting palette",null))},{intent:C.Exit,mode:y.PALETTE,action:()=>(Ab(),d("Closed command palette",null))},{intent:C.NavPreviousItem,mode:y.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(z.navigateToPreviousItem(),d("Navigating to previous item",null))},{intent:C.NavNextItem,mode:y.PALETTE,action:()=>(z.navigateToNextItem(),d("Navigating to next item",null))},{intent:C.NavToPreviousContainer,mode:y.PALETTE,action:()=>(z.navigateToPreviousContainer(),d("Navigating to previous container",null))},{intent:C.NavToNextContainer,mode:y.PALETTE,action:()=>(z.navigateToNextContainer(),d("Navigating to next container",null))}];var Mb=()=>{let e=En();if(!e)return d("Nothing to comment on here",null);let t=Oi();if(!t||t.sha!==e)return a("The diff is still loading");let{selectedIndex:n}=h(),r=Math.max(0,n),o=il(t.rows,Bl(e)??r,r);return o.ok?(w({mode:y.COMMAND_LINE}),X(`${b.COMMENT} ${Uf(o.value.start,o.value.end)} `),d("Commenting on a diff line",null)):a(o.reason)},kb=[{intent:C.InitCommandLine,mode:y.DEFAULT,description:"[:] write command",action:()=>(w({mode:y.COMMAND_LINE}),X(""),d("Entering command line mode",null))},...Nb,...wb,...Tb,{intent:C.AddItem,mode:y.DEFAULT,description:"[n] new...",action:()=>(w({mode:y.COMMAND_LINE}),X(`${b.NEW} `),d("Adding new item",null))},{intent:C.Delete,mode:y.DEFAULT,description:"[d] delete",action:()=>(w({mode:y.COMMAND_LINE}),X(`${b.DELETE} `),d("Deleting item",null))},{intent:C.Confirm,mode:y.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=h();if(!be(e?.id??"")?.length){let r=e?R.getAttachment(e.id):void 0;if(r)return Sb(r);if(En())return Mb();if(e?.title===ge.DESCRIPTION)return w({mode:y.COMMAND_LINE}),X(`${b.EDIT} description `),d("Propose command",!0);if(e?.title===ge.ASSIGNEES)return w({mode:y.COMMAND_LINE}),X(`${b.ASSIGN} `),d("Propose command",!0);if(e?.title===ge.TAGS)return w({mode:y.COMMAND_LINE}),X(`${b.TAG} `),d("Propose command",!0);if(t.title===ge.DESCRIPTION&&e?.context==="TEXT")return w({mode:y.COMMAND_LINE}),X(`${b.EDIT} description `),d("Propose command",!0)}return z.enterChildNode(),d("Entering context",null)}},{intent:C.OpenInEditor,mode:y.DEFAULT,action:()=>{let{selectedNode:e,contextNode:t}=h(),n=t.parentNodeId,o=!!n&&t.id===he(n,"diff")?e?.id:En()??void 0;return o?pl({sha:o}):d("Nothing here opens in an editor",null)}},{intent:C.MarkDiffLine,mode:y.DEFAULT,action:()=>{let e=En();if(!e)return d("Nothing to mark here",null);let{selectedIndex:t}=h(),n=Bl(e);return er(n===t?null:{sha:e,row:Math.max(0,t)}),d("Marked diff line",null)}},{intent:C.CommentOnDiffLine,mode:y.DEFAULT,action:()=>En()?Mb():d("Nothing to comment on here",null)},{intent:C.Yank,mode:y.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=h(),t=e?.title===ge.DESCRIPTION?Me.DESCRIPTION:e?.title===ge.TAGS?Me.TAGS:e?.title===ge.ASSIGNEES?Me.ASSIGNEES:Me.REF,r=ke(b.YANK).includes(t)?t:Me.REF;return w({mode:y.COMMAND_LINE}),X(`${b.YANK} ${r}`),d("Propose command",!0)}},{intent:C.EditTitle,mode:y.DEFAULT,description:"[r] rename title",action:()=>(w({mode:y.COMMAND_LINE}),X(`${b.EDIT} title ${h().selectedNode?.title}`),d("Exiting context",null))},{intent:C.EditDescription,mode:y.DEFAULT,description:"[e] edit desc",action:()=>(w({mode:y.COMMAND_LINE}),X(`${b.EDIT} description `),d("Exiting context",null))},{intent:C.Exit,mode:y.DEFAULT,description:"[q] exit context",action:()=>(z.enterParentNode(),d("Exiting context",null))},{intent:C.NavPreviousItem,mode:y.DEFAULT,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(z.navigateToPreviousItem(),d("Navigating to previous item",null))},{intent:C.NavNextItem,mode:y.DEFAULT,action:()=>(z.navigateToNextItem(),d("Navigating to next item",null))},{intent:C.NavPreviousItemJump,mode:y.DEFAULT,action:()=>(z.jumpToPreviousItem(),d("Jumping to previous item",null))},{intent:C.NavNextItemJump,mode:y.DEFAULT,action:()=>(z.jumpToNextItem(),d("Jumping to next item",null))},{intent:C.NavToPreviousContainer,mode:y.DEFAULT,action:()=>(z.navigateToPreviousContainer(),d("Navigating to previous container",null))},{intent:C.NavToNextContainer,mode:y.DEFAULT,action:()=>(z.navigateToNextContainer(),d("Navigating to next container",null))}];var ow=500,sw=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Lb=e=>{let t=sw(e);t&&ui(n=>(n+t).slice(0,ow))};var iw=[y.COMMAND_LINE,y.PALETTE],aw=e=>e==="edit title "?h().selectedNode?.title??"":"",cw=e=>[{intent:C.MoveCursorLeft,mode:e,action:()=>(vl(-1),d("Moving cursor left",null))},{intent:C.MoveCursorRight,mode:e,action:()=>(vl(1),d("Moving cursor right",null))},{intent:C.MoveCursorLeftOfWord,mode:e,action:()=>(xl("left"),d("Moving cursor left of word",null))},{intent:C.MoveCursorRightOfWord,mode:e,action:()=>(xl("right"),d("Moving cursor right of word",null))},{intent:C.AutoCompleteCommand,mode:e,action:()=>(ui((t,{remainder:n})=>{let r=n?t+n:t;return r+aw(r)}),d("Auto-completing command",null))},{intent:C.CaptureInput,mode:e,action:(t,{sequence:n})=>(Lb(n??""),d("Capturing input",null))},{intent:C.EraseInput,mode:e,action:()=>(bg(),d("Erasing input",null))},{intent:C.EraseInputWord,mode:e,action:()=>(vg(),d("Erasing input word",null))}],Pb=[{intent:C.Confirm,mode:y.COMMAND_LINE,action:()=>(Rt(),d("Executing command",null))},{intent:C.ViewHelp,mode:y.DEFAULT,action:()=>(w({mode:y.HELP}),d("Viewing help",null))},...iw.flatMap(cw),{intent:C.ExitCommandLine,mode:y.COMMAND_LINE,action:()=>(Sg(),w({mode:y.DEFAULT}),d("Exiting command line",null))},{intent:C.GetLastCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(Cg(),d("Getting last command from history",null))},{intent:C.GetNextCommandFromHistory,mode:y.COMMAND_LINE,action:()=>(Ng(),d("Getting next command from history",null))}];var lw=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},Ob=({keys:e})=>e.length===1?0:1,Db=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(lw).filter(r=>r!==null).sort((r,o)=>Ob(r)-Ob(o))};function Fb(e,t,n){let r=t[e];if(!r)return a("buildBreadCrumb(): current node not found");let o=[],s=new Set,i=r;for(;i&&!s.has(i.id)&&(o.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let l=o[o.length-1];return!l||l.id!==n?a("buildBreadCrumb(): node is not connected to root"):(o.reverse(),d("Breadcrumb built",o))}var _b=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var tt,od,sd=new Set,id=()=>{for(let e of sd)e()},uw=e=>(sd.add(e),()=>sd.delete(e));function ad(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return a("derive(): contextNodeId is missing");if(!r)return a("derive(): rootNode is missing");if(!o[r])return a("derive(): unable to find root node");let l=o[t];if(!l)return a("Unable to derive state, contextNode not found");let u=Fb(t,o,r);if(c(u))return logger.error(u.message),u;let m=u.value,{context:p}=l,f=[...kb,...Rb[p]??[],...Pb],g=Db(f,n),v=_b(f),I=mw(o,s),x=I[t]?.[e.selectedIndex]??null;return d("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:g,availableActions:f,actionIndex:v,selectedNode:x,renderedChildrenIndex:I})}var h=()=>{if(!tt)throw new Error("State not initialized. Call initWorkspaceState() first.");return tt},me=()=>tt?d("Retrieved state",tt):a("State not initialized. Call initWorkspaceState() first.");Gu(e=>tt?cr(tt.emailLinks,e):[]);function xo(e){od=e;let t=Ee(process.cwd()),n=!1;if(!c(t)){let s=He(t.value);if(c(s))return a(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},goals:{},contributors:{},emailLinks:{},repos:Ji(),mode:y.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{},attachments:{}},o=ad(r);return c(o)?o:(tt=o.value,id(),d("State initialized",null))}var rr=!1,ns=null;function pe(e){let t=h(),n=e(t);if(rr)return n.nodes!==t.nodes&&(In=null),ns=n,tt={...t,...n},d("State updated",null);let r=ad(n);return c(r)?a(r.message??"Unable to update state"):(tt=r.value,id(),d("State updated",null))}function zs(e){if(rr)return d("Joined batch",e());rr=!0,ns=null,In=new Set;let t=()=>{let n=ns;if(rr=!1,ns=null,n===null)return null;let r=ad(n);return c(r)?a(r.message??"Unable to update state"):(tt=r.value,id(),d("State updated",null))};try{let n=e(),r=t();return r&&c(r)?a(r.message):d("State updated",n)}finally{rr&&t()}}var _g=()=>rr,w=e=>pe(t=>({...t,...e}));function or(e,t,n){if(!rr)return pe(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=h(),o=r[e]??{};if(e==="nodes"){let i=o[t],l=n;i?.parentNodeId&&In?.add(i.parentNodeId),l.parentNodeId&&In?.add(l.parentNodeId)}o[t]=n;let s={...r,[e]:o};return ns=s,tt={...r,...s},d("State updated",null)}var Pe=()=>dw(uw,h,h),In=null,$b=null,mw=(e,t)=>{let n=tt?.renderedChildrenIndex,r=n!==void 0&&In!==null&&e===$b&&t.length===0&&tt?.filters.length===0,o;if(r){o={...n};let s=Pg(e,In);for(let i of In){let l=s[i];l?o[i]=l:delete o[i]}}else o=Lg(e,t);return $b=e,In=new Set,o},le=e=>h()?.renderedChildrenIndex[e]??[],Nn=()=>od?xo(od):a("Cannot reset state: no initial workspace found"),gt=()=>tt!==void 0;var et=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r)return a("Node not found");if(r.context===t)return d("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 d("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return a(`No ancestor found for context: ${t}`)},pw=(e,t)=>{let{nodes:n}=h(),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},Et=(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"),R={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 r={...n,userId:t},o=pe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return c(o)?a("Unable to link contributor to user"):d("Linked contributor to user",r)},deleteNode(e){R.deleteNodes([e])},deleteNodes(e){e.length!==0&&pe(t=>{let n={...t.nodes};for(let r of e)delete n[r];return{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return a("Unable to create comment, missing issue");if(!U(t))return a("Can only comment on issues");let n=or("comments",e.id,{...e,deleted:!1});return c(n)?a("Unable to create comment"):d("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return a("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return a("Unable to edit comment, missing issue");if(!U(r))return a("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=or("comments",e,o);return c(s)?a("Unable to edit comment"):d("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return a("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=or("comments",e,n);return c(r)?a("Unable to delete comment"):d("Deleted comment",n)},getComment(e){return h().comments?.[e]},getCommentsByIssue(e){return Object.values(h().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(h().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(!U(t))return a("Can only attach to issues");let n=pe(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return c(n)?a("Unable to create attachment"):d("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},r=pe(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return c(r)?a("Unable to delete attachment"):d("Deleted attachment",n)},getAttachment(e){return h().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(h().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(h().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}=h(),r=n[e];if(!r)return a("Edit target node not found");let o=Et(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),d("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return a("Rename target node not found");let r=Et(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),d("Renamed node",o)},getExistingTags(){let{tags:e}=h();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=h();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return be(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=h(),o=this.getNode(e),s=this.getNode(t);if(!o)return a("Node not found");if(!s)return a("Target parent not found");if(r===e)return a("Cannot move root node");if(e===t)return a("Cannot move node into itself");let i=Et(o,"move");if(i)return i;if(pw(t,e))return a("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),d("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=h(),o=this.getNode(e);if(!o)return a("Node not found");if(r===e)return a("Cannot delete root node");let s=Et(o,"delete");if(s)return s;let i=new Set,l=m=>{let p=t[m];if(!(!p||i.has(m))){i.add(m);for(let f of be(p.id))l(f.id)}};l(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?(w({nodes:u}),d("Successfully tomb stoned",o)):a("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return a("Contributor not found");let n={...t,name:kd,tombstoned:!0},r=pe(o=>({...o,contributors:{...o.contributors,[e]:n}}));return c(r)?a("Unable to remove contributor"):d("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 r={...n,name:t},o=pe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return c(o)?a("Unable to rename contributor"):d("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return a("Contributor not found");let r={...n,name:t,tombstoned:!1},o=pe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return c(o)?a("Unable to restore contributor"):d("Restored contributor",r)},linkContributorEmail({email:e,contributor:t,authorId:n}){if(!this.getContributor(t))return a("Unable to link email, missing contributor");let r={email:rt(e),contributor:t,authorId:n},o=da(r.email,t),s=h().emailLinks[o];if(s&&!s.tombstoned)return d("Email already linked",s);let i=pe(l=>({...l,emailLinks:{...l.emailLinks,[o]:r}}));return c(i)?a("Unable to link email"):d("Linked email to contributor",r)},unlinkContributorEmail(e,t,n){let r=da(e,t),o=h().emailLinks[r];if(!o)return a("Unable to unlink, no such link");if(o.tombstoned)return d("Email already unlinked",o);if(!Pd(n,o))return a("Only the author of a link or the contributor it names may remove it");let s={...o,tombstoned:!0},i=pe(l=>({...l,emailLinks:{...l.emailLinks,[r]:s}}));return c(i)?a("Unable to unlink email"):d("Unlinked email from contributor",s)},getEmailLinks(){return h().emailLinks},createContributor(e){let t=pe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return c(t)?a("Unable to create contributor"):d("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to assign contributor, missing contributor");if(!r)return a("Unable to assign contributor, missing target");let o=Et(r,"edit");if(o)return o;if(!U(r))return a("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return a("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),d("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return a("Unable to unassign, missing contributor");if(!r)return a("Unable to unassign, missing target");let o=Et(r,"edit");if(o)return o;if(!U(r))return a("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return d("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(l=>l!==t)}};return this.updateNode(i),d("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return a("Unable to add tag, missing tag");if(!r)return a("Unable to add tag, missing target");let o=Et(r,"edit");if(o)return o;if(!U(r))return a("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return a("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),d("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),r=this.getNode(e);if(!n)return a("Unable to remove tag, missing tag");if(!r)return a("Unable to remove tag, missing target");let o=Et(r,"edit");if(o)return o;if(!U(r))return a("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return d("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(l=>l!==t)}};return this.updateNode(i),d("Tag removed",{tag:t})},addLaneRule(e,t){let n=this.getNode(e);if(!n)return a("Unable to add rule, missing lane");let r=Et(n,"edit");if(r)return r;if(!ot(n))return a("Target is not a swimlane");let o=n.props.rules??[];return o.includes(t)?a("Lane already has that rule"):(this.updateNode({...n,props:{...n.props,rules:[...o,t]}}),d("Added lane rule",{rule:t}))},removeLaneRule(e,t){let n=this.getNode(e);if(!n)return a("Unable to remove rule, missing lane");let r=Et(n,"edit");if(r)return r;if(!ot(n))return a("Target is not a swimlane");let o=n.props.rules??[];if(!o.includes(t))return d("Lane lacks that rule",{rule:t});let{rules:s,...i}=n.props,l=o.filter(u=>u!==t);return this.updateNode({...n,props:l.length>0?{...i,rules:l}:i}),d("Removed lane rule",{rule:t})},addGoal(e,t){let n=this.getNode(e);if(!n)return a("Unable to add goal, missing target");let r=Et(n,"edit");if(r)return r;if(!U(n))return a("Target is not an issue");if(!this.getGoal(t))return a("Goal not found");let o=n.props.goals??[];return o.includes(t)?a("Already in that goal"):(this.updateNode({...n,props:{...n.props,goals:[...o,t]}}),d("Added to goal",{goal:t}))},removeGoal(e,t){let n=this.getNode(e);if(!n)return a("Unable to remove goal, missing target");let r=Et(n,"edit");if(r)return r;if(!U(n))return a("Target is not an issue");let o=n.props.goals??[];if(!o.includes(t))return d("Not in that goal",{goal:t});let{goals:s,...i}=n.props,l=o.filter(u=>u!==t);return this.updateNode({...n,props:l.length>0?{...i,goals:l}:i}),d("Removed from goal",{goal:t})},createGoal(e){if(h().goals[e.id])return a("Goal already exists");let t=pe(n=>({...n,goals:{...n.goals,[e.id]:e}}));return c(t)?a("Could not create goal"):d("Goal created",e)},renameGoal(e,t){let n=this.getGoal(e);if(!n)return a("Goal not found");let r={...n,name:t},o=pe(s=>({...s,goals:{...s.goals,[e]:r}}));return c(o)?a("Unable to rename goal"):d("Renamed goal",r)},tombstoneGoal(e){let t=h().goals[e];if(!t)return a("Goal not found");let n={...t,tombstoned:!0},r=pe(o=>({...o,goals:{...o.goals,[e]:n}}));return c(r)?a("Unable to remove goal"):d("Tombstoned goal",n)},getGoal(e){let t=h().goals[e];return t?.tombstoned?void 0:t},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return a("Tag not found");let n={...t,tombstoned:!0},r=pe(o=>({...o,tags:{...o.tags,[e]:n}}));return c(r)?a("Unable to delete tag"):d("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return a("Tag not found");let r={...n,name:t,tombstoned:!1},o=pe(s=>({...s,tags:{...s.tags,[e]:r}}));return c(o)?a("Unable to restore tag"):d("Restored tag",r)},createTag(e){let t=pe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return c(t)?a("Could not create tag"):d("Tag created",e)},createNode(e){let t=or("nodes",e.id,e);return c(t)?a("Unable to create node"):d("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return a("Failed to locate node");let n={...t,readonly:!0},r=or("nodes",e,n);return c(r)?a(r.message):d("Locked node",n)},updateNode(e){let t=or("nodes",e.id,e);return c(t)?t:d("Updated node",e)},getContributor(e){return h().contributors[e]},getTag(e){let t=h().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return h().tags[e]},getTags(){return Object.values(h().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return h().nodes[e]},getSiblings(e){return be(e)}};var fw=(e,t)=>e+" ".repeat(Math.max(0,t-Bb(e))),gw=(e,t)=>" ".repeat(Math.max(0,t-Bb(e)))+e,Ub=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","add.issue.goal":"Added to goal","add.swimlane.rule":"Added lane rule","remove.swimlane.rule":"Removed lane rule","remove.issue.goal":"Removed from goal","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.goal":"Created goal","rename.goal":"Renamed goal","tombstone.goal":"Removed goal","create.contributor":"Added contributor","rename.contributor":"Renamed contributor","link.contributor.user":"Linked contributor","link.contributor.email":"Claimed","unlink.contributor.email":"Unclaimed","connect.repo":"Connected repo","edit.repo":"Edited repo","disconnect.repo":"Disconnected repo","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),hw=(e,t)=>t?e<t?"up":e>t?"down":null:null,yw=(e,t)=>{let n=R.getNode(e.payload.parent),r=n?wn.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=hw(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},jb=e=>`${Math.max(1,Math.round(e/1024))} KB`,Hb=e=>R.getAttachment(e)?.name??"",Ki=e=>h().goals[e]?.name??"",bw=e=>{switch(e.action){case"add.issue.tag":{let t=h().tags[e.payload.tag];return t?wn.bgHex(Ue(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=h().tags[e.payload.tag];return t?wn.bgHex(Ue(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=h().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.goal":case"remove.issue.goal":return Ki(e.payload.goal);case"add.swimlane.rule":case"remove.swimlane.rule":return`"${e.payload.rule}"`;case"tombstone.goal":return`"${Ki(e.payload.id)}"`;case"add.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?wn.hex(Ue(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?wn.hex(Ue(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.goal":case"rename.goal":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"connect.repo":case"edit.repo":case"disconnect.repo":return ta(e);case"add.issue.attachment":return`"${e.payload.name}" ${wn.dim(`(${jb(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Hb(e.payload.id);return t?`"${t}"`:""}default:return""}},vw=e=>{let t=vn(kn(e));return wn.gray(gw(t,8))},xw=12,Rw=e=>fw(`${e}`,xw),Ew=e=>{let t=me();return c(t)?e:ca(e,t.value.contributors[e]?.name)},Sw=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=h().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?t.name:""}case"add.issue.goal":case"remove.issue.goal":return Ki(e.payload.goal);case"add.swimlane.rule":case"remove.swimlane.rule":return`"${e.payload.rule}"`;case"tombstone.goal":return`"${Ki(e.payload.id)}"`;case"tombstone.tag":{let t=h().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.goal":case"rename.goal":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"connect.repo":case"edit.repo":case"disconnect.repo":return ta(e);case"move.node":{let t=R.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${jb(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Hb(e.payload.id);return t?`"${t}"`:""}default:return""}},Py=e=>[Ub(e.action),Sw(e)].filter(Boolean).join(" "),Wb=(e,t)=>{let n=vw(e.id),r=Rw(Ew(e.userId)),o=wn.dim("\u203A"),s=e.action==="move.node"?yw(e,t):[Ub(e.action),bw(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};var Cw=e=>he(e,"comments"),Nw=e=>he(e,"description"),Iw=e=>he(e,"assignees"),ww=e=>he(e,"tags"),Aw=e=>he(e,"history"),Tw=e=>he(e,"diff"),Mw=e=>he(e,"attachments"),rs=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let l=R.getNode(e);if(!l){let p=R.createNode({...Ae.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return c(p)?p:d("Virtual field created",void 0)}if(!Fe(l))return a(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==r||l.props.value!==o||l.readonly!==s||l.childRenderAxis!==i))return d("Virtual field unchanged",void 0);let m=R.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:s,childRenderAxis:i});return c(m)?m:d("Virtual field updated",void 0)},Gb=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=R.getNode(e);if(!i){let m=R.createNode({...Ae.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return c(m)?m:d("Virtual field list created",void 0)}if(!Wr(i))return a(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return d("Virtual field list unchanged",void 0);let u=R.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return c(u)?u:d("Virtual field list updated",void 0)},qi=null,kw=()=>{if(qi)return d("Virtual field ranks",qi);let e=dt(Mt/4n),t=dt(Mt/2n),n=dt(Mt*3n/4n),r=dt(Mt*7n/8n),o=dt(Mt*15n/16n),s=dt(Mt*13n/16n),i=dt(Mt*27n/32n);return c(e)?e:c(t)?t:c(n)?n:c(r)?r:c(o)?o:c(s)?s:c(i)?i:(qi={description:e.value,assignees:t.value,tags:n.value,comments:r.value,attachments:o.value,log:s.value,diff:i.value},d("Virtual field ranks",qi))},bc=e=>{let t=kw();if(c(t))return t;let n=t.value,r=rs({id:Nw(e.id),name:ge.DESCRIPTION,parentNodeId:e.id,rank:n.description,value:e.props.description??"",childRenderAxis:"vertical"});if(c(r))return r;let o=Gb({id:Iw(e.id),name:ge.ASSIGNEES,parentNodeId:e.id,rank:n.assignees,readonly:!0});if(c(o))return o;let s=Gb({id:ww(e.id),name:ge.TAGS,parentNodeId:e.id,rank:n.tags,readonly:!0});if(c(s))return s;let i=rs({id:Cw(e.id),name:ge.COMMENTS,parentNodeId:e.id,rank:n.comments,value:"",readonly:!1,childRenderAxis:"vertical"});if(c(i))return i;let l=rs({id:Mw(e.id),name:ge.ATTACHMENTS,parentNodeId:e.id,rank:n.attachments,value:"",readonly:!0,childRenderAxis:"vertical"});if(c(l))return l;let u=rs({id:Aw(e.id),name:ge.HISTORY,parentNodeId:e.id,rank:n.log,value:Lw(e),readonly:!0,childRenderAxis:"vertical"});if(c(u))return u;let m=rs({id:Tw(e.id),name:ge.DIFF,parentNodeId:e.id,rank:n.diff,value:"",readonly:!0,childRenderAxis:"vertical"});return c(m)?m:d("Ticket virtual nodes materialized",void 0)},Lw=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=>Wb(r,n.get(r.action)??[])).join(`
116
+ `)},zb=!0,vJ=e=>{zb=e},vc=()=>zb,xJ=()=>{let{nodes:e}=h();for(let t of Object.values(e)){if(!U(t))continue;let n=bc(t);if(c(n))return n}return d("Virtual nodes materialized",void 0)};export{ms as a,V as b,It as c,_ as d,Ie as e,fu as f,ve as g,wt as h,Qr as i,zv as j,Ee as k,Ft as l,Xe as m,Em as n,ne as o,LT as p,mt as q,A as r,Ue as s,Ad as t,qw as u,Td as v,Yw as w,Xb as x,gd as y,An as z,nn as A,sv as B,ta as C,na as D,kn as E,ss as F,Ed as G,is as H,ca as I,la as J,kd as K,nt as L,rt as M,ar as N,da as O,nA as P,cr as Q,rA as R,Pd as S,U as T,Od as U,ot as V,Gr as W,y as X,Ln as Y,Pn as Z,ut as _,dA as $,Bu as aa,Rs as ba,Wu as ca,Ku as da,io as ea,We as fa,on as ga,sn as ha,b as ia,ao as ja,Dn as ka,Qu as la,rx as ma,Is as na,nm as oa,Ba as pa,As as qa,Ts as ra,Ua as sa,an as ta,sm as ua,ax as va,dx as wa,xM as xa,ux as ya,im as za,RM as Aa,mx as Ba,am as Ca,ke as Da,$x as Ea,Bn as Fa,Ja as Ga,mk as Ha,pk as Ia,At as Ja,Tt as Ka,km as La,Fs as Ma,Gn as Na,zn as Oa,Q as Pa,xr as Qa,at as Ra,gc as Sa,Ae as Ta,un as Ua,Eo as Va,e0 as Wa,gp as Xa,Vs as Ya,hp as Za,yp as _a,Y as $a,xc as ab,Ks as bb,ct as cb,j0 as db,Vn as eb,Ac as fb,cE as gb,Pc as hb,lE as ib,$c as jb,Wc as kb,oi as lb,zc as mb,$E as nb,Cf as ob,Xc as pb,HE as qb,KE as rb,XE as sb,nS as tb,pl as ub,tg as vb,ng as wb,rg as xb,gn as yb,se as zb,wr as Ab,ZS as Bb,g_ as Cb,C as Db,S_ as Eb,be as Fb,fi as Gb,gi as Hb,z as Ib,Ho as Jb,S$ as Kb,Kg as Lb,vi as Mb,Wo as Nb,RC as Ob,Xn as Pb,qg as Qb,Il as Rb,Tr as Sb,uh as Tb,Al as Ub,gh as Vb,hh as Wb,yt as Xb,bt as Yb,kr as Zb,wi as _b,uj as $b,sy as ac,Br as bc,aW as cc,uy as dc,vy as ec,Ez as fc,Iy as gc,wy as hc,Sz as ic,Hy as jc,eb as kc,SK as lc,sb as mc,ib as nc,Gi as oc,mb as pc,pb as qc,vb as rc,lw as sc,h as tc,me as uc,w as vc,Pe as wc,le as xc,Nn as yc,gt as zc,et as Ac,pw as Bc,R as Cc,Ub as Dc,Py as Ec,rs as Fc,Gb as Gc,bc as Hc,vJ as Ic,vc as Jc,xJ as Kc};